x86.c 367 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * Kernel-based Virtual Machine driver for Linux
  4. *
  5. * derived from drivers/kvm/kvm_main.c
  6. *
  7. * Copyright (C) 2006 Qumranet, Inc.
  8. * Copyright (C) 2008 Qumranet, Inc.
  9. * Copyright IBM Corporation, 2008
  10. * Copyright 2010 Red Hat, Inc. and/or its affiliates.
  11. *
  12. * Authors:
  13. * Avi Kivity <[email protected]>
  14. * Yaniv Kamay <[email protected]>
  15. * Amit Shah <[email protected]>
  16. * Ben-Ami Yassour <[email protected]>
  17. */
  18. #include <linux/kvm_host.h>
  19. #include "irq.h"
  20. #include "ioapic.h"
  21. #include "mmu.h"
  22. #include "i8254.h"
  23. #include "tss.h"
  24. #include "kvm_cache_regs.h"
  25. #include "kvm_emulate.h"
  26. #include "x86.h"
  27. #include "cpuid.h"
  28. #include "pmu.h"
  29. #include "hyperv.h"
  30. #include "lapic.h"
  31. #include "xen.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/cpufreq.h>
  43. #include <linux/user-return-notifier.h>
  44. #include <linux/srcu.h>
  45. #include <linux/slab.h>
  46. #include <linux/perf_event.h>
  47. #include <linux/uaccess.h>
  48. #include <linux/hash.h>
  49. #include <linux/pci.h>
  50. #include <linux/timekeeper_internal.h>
  51. #include <linux/pvclock_gtod.h>
  52. #include <linux/kvm_irqfd.h>
  53. #include <linux/irqbypass.h>
  54. #include <linux/sched/stat.h>
  55. #include <linux/sched/isolation.h>
  56. #include <linux/mem_encrypt.h>
  57. #include <linux/entry-kvm.h>
  58. #include <linux/suspend.h>
  59. #include <trace/events/kvm.h>
  60. #include <asm/debugreg.h>
  61. #include <asm/msr.h>
  62. #include <asm/desc.h>
  63. #include <asm/mce.h>
  64. #include <asm/pkru.h>
  65. #include <linux/kernel_stat.h>
  66. #include <asm/fpu/api.h>
  67. #include <asm/fpu/xcr.h>
  68. #include <asm/fpu/xstate.h>
  69. #include <asm/pvclock.h>
  70. #include <asm/div64.h>
  71. #include <asm/irq_remapping.h>
  72. #include <asm/mshyperv.h>
  73. #include <asm/hypervisor.h>
  74. #include <asm/tlbflush.h>
  75. #include <asm/intel_pt.h>
  76. #include <asm/emulate_prefix.h>
  77. #include <asm/sgx.h>
  78. #include <clocksource/hyperv_timer.h>
  79. #define CREATE_TRACE_POINTS
  80. #include "trace.h"
  81. #define MAX_IO_MSRS 256
  82. #define KVM_MAX_MCE_BANKS 32
  83. struct kvm_caps kvm_caps __read_mostly = {
  84. .supported_mce_cap = MCG_CTL_P | MCG_SER_P,
  85. };
  86. EXPORT_SYMBOL_GPL(kvm_caps);
  87. #define ERR_PTR_USR(e) ((void __user *)ERR_PTR(e))
  88. #define emul_to_vcpu(ctxt) \
  89. ((struct kvm_vcpu *)(ctxt)->vcpu)
  90. /* EFER defaults:
  91. * - enable syscall per default because its emulated by KVM
  92. * - enable LME and LMA per default on 64 bit KVM
  93. */
  94. #ifdef CONFIG_X86_64
  95. static
  96. u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
  97. #else
  98. static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
  99. #endif
  100. static u64 __read_mostly cr4_reserved_bits = CR4_RESERVED_BITS;
  101. #define KVM_EXIT_HYPERCALL_VALID_MASK (1 << KVM_HC_MAP_GPA_RANGE)
  102. #define KVM_CAP_PMU_VALID_MASK KVM_PMU_CAP_DISABLE
  103. #define KVM_X2APIC_API_VALID_FLAGS (KVM_X2APIC_API_USE_32BIT_IDS | \
  104. KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
  105. static void update_cr8_intercept(struct kvm_vcpu *vcpu);
  106. static void process_nmi(struct kvm_vcpu *vcpu);
  107. static void process_smi(struct kvm_vcpu *vcpu);
  108. static void enter_smm(struct kvm_vcpu *vcpu);
  109. static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
  110. static void store_regs(struct kvm_vcpu *vcpu);
  111. static int sync_regs(struct kvm_vcpu *vcpu);
  112. static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu);
  113. static int __set_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2);
  114. static void __get_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2);
  115. struct kvm_x86_ops kvm_x86_ops __read_mostly;
  116. #define KVM_X86_OP(func) \
  117. DEFINE_STATIC_CALL_NULL(kvm_x86_##func, \
  118. *(((struct kvm_x86_ops *)0)->func));
  119. #define KVM_X86_OP_OPTIONAL KVM_X86_OP
  120. #define KVM_X86_OP_OPTIONAL_RET0 KVM_X86_OP
  121. #include <asm/kvm-x86-ops.h>
  122. EXPORT_STATIC_CALL_GPL(kvm_x86_get_cs_db_l_bits);
  123. EXPORT_STATIC_CALL_GPL(kvm_x86_cache_reg);
  124. static bool __read_mostly ignore_msrs = 0;
  125. module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
  126. bool __read_mostly report_ignored_msrs = true;
  127. module_param(report_ignored_msrs, bool, S_IRUGO | S_IWUSR);
  128. EXPORT_SYMBOL_GPL(report_ignored_msrs);
  129. unsigned int min_timer_period_us = 200;
  130. module_param(min_timer_period_us, uint, S_IRUGO | S_IWUSR);
  131. static bool __read_mostly kvmclock_periodic_sync = true;
  132. module_param(kvmclock_periodic_sync, bool, S_IRUGO);
  133. /* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
  134. static u32 __read_mostly tsc_tolerance_ppm = 250;
  135. module_param(tsc_tolerance_ppm, uint, S_IRUGO | S_IWUSR);
  136. /*
  137. * lapic timer advance (tscdeadline mode only) in nanoseconds. '-1' enables
  138. * adaptive tuning starting from default advancement of 1000ns. '0' disables
  139. * advancement entirely. Any other value is used as-is and disables adaptive
  140. * tuning, i.e. allows privileged userspace to set an exact advancement time.
  141. */
  142. static int __read_mostly lapic_timer_advance_ns = -1;
  143. module_param(lapic_timer_advance_ns, int, S_IRUGO | S_IWUSR);
  144. static bool __read_mostly vector_hashing = true;
  145. module_param(vector_hashing, bool, S_IRUGO);
  146. bool __read_mostly enable_vmware_backdoor = false;
  147. module_param(enable_vmware_backdoor, bool, S_IRUGO);
  148. EXPORT_SYMBOL_GPL(enable_vmware_backdoor);
  149. /*
  150. * Flags to manipulate forced emulation behavior (any non-zero value will
  151. * enable forced emulation).
  152. */
  153. #define KVM_FEP_CLEAR_RFLAGS_RF BIT(1)
  154. static int __read_mostly force_emulation_prefix;
  155. module_param(force_emulation_prefix, int, 0644);
  156. int __read_mostly pi_inject_timer = -1;
  157. module_param(pi_inject_timer, bint, S_IRUGO | S_IWUSR);
  158. /* Enable/disable PMU virtualization */
  159. bool __read_mostly enable_pmu = true;
  160. EXPORT_SYMBOL_GPL(enable_pmu);
  161. module_param(enable_pmu, bool, 0444);
  162. bool __read_mostly eager_page_split = true;
  163. module_param(eager_page_split, bool, 0644);
  164. /* Enable/disable SMT_RSB bug mitigation */
  165. bool __read_mostly mitigate_smt_rsb;
  166. module_param(mitigate_smt_rsb, bool, 0444);
  167. /*
  168. * Restoring the host value for MSRs that are only consumed when running in
  169. * usermode, e.g. SYSCALL MSRs and TSC_AUX, can be deferred until the CPU
  170. * returns to userspace, i.e. the kernel can run with the guest's value.
  171. */
  172. #define KVM_MAX_NR_USER_RETURN_MSRS 16
  173. struct kvm_user_return_msrs {
  174. struct user_return_notifier urn;
  175. bool registered;
  176. struct kvm_user_return_msr_values {
  177. u64 host;
  178. u64 curr;
  179. } values[KVM_MAX_NR_USER_RETURN_MSRS];
  180. };
  181. u32 __read_mostly kvm_nr_uret_msrs;
  182. EXPORT_SYMBOL_GPL(kvm_nr_uret_msrs);
  183. static u32 __read_mostly kvm_uret_msrs_list[KVM_MAX_NR_USER_RETURN_MSRS];
  184. static struct kvm_user_return_msrs __percpu *user_return_msrs;
  185. #define KVM_SUPPORTED_XCR0 (XFEATURE_MASK_FP | XFEATURE_MASK_SSE \
  186. | XFEATURE_MASK_YMM | XFEATURE_MASK_BNDREGS \
  187. | XFEATURE_MASK_BNDCSR | XFEATURE_MASK_AVX512 \
  188. | XFEATURE_MASK_PKRU | XFEATURE_MASK_XTILE)
  189. u64 __read_mostly host_efer;
  190. EXPORT_SYMBOL_GPL(host_efer);
  191. bool __read_mostly allow_smaller_maxphyaddr = 0;
  192. EXPORT_SYMBOL_GPL(allow_smaller_maxphyaddr);
  193. bool __read_mostly enable_apicv = true;
  194. EXPORT_SYMBOL_GPL(enable_apicv);
  195. u64 __read_mostly host_xss;
  196. EXPORT_SYMBOL_GPL(host_xss);
  197. const struct _kvm_stats_desc kvm_vm_stats_desc[] = {
  198. KVM_GENERIC_VM_STATS(),
  199. STATS_DESC_COUNTER(VM, mmu_shadow_zapped),
  200. STATS_DESC_COUNTER(VM, mmu_pte_write),
  201. STATS_DESC_COUNTER(VM, mmu_pde_zapped),
  202. STATS_DESC_COUNTER(VM, mmu_flooded),
  203. STATS_DESC_COUNTER(VM, mmu_recycled),
  204. STATS_DESC_COUNTER(VM, mmu_cache_miss),
  205. STATS_DESC_ICOUNTER(VM, mmu_unsync),
  206. STATS_DESC_ICOUNTER(VM, pages_4k),
  207. STATS_DESC_ICOUNTER(VM, pages_2m),
  208. STATS_DESC_ICOUNTER(VM, pages_1g),
  209. STATS_DESC_ICOUNTER(VM, nx_lpage_splits),
  210. STATS_DESC_PCOUNTER(VM, max_mmu_rmap_size),
  211. STATS_DESC_PCOUNTER(VM, max_mmu_page_hash_collisions)
  212. };
  213. const struct kvm_stats_header kvm_vm_stats_header = {
  214. .name_size = KVM_STATS_NAME_SIZE,
  215. .num_desc = ARRAY_SIZE(kvm_vm_stats_desc),
  216. .id_offset = sizeof(struct kvm_stats_header),
  217. .desc_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE,
  218. .data_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE +
  219. sizeof(kvm_vm_stats_desc),
  220. };
  221. const struct _kvm_stats_desc kvm_vcpu_stats_desc[] = {
  222. KVM_GENERIC_VCPU_STATS(),
  223. STATS_DESC_COUNTER(VCPU, pf_taken),
  224. STATS_DESC_COUNTER(VCPU, pf_fixed),
  225. STATS_DESC_COUNTER(VCPU, pf_emulate),
  226. STATS_DESC_COUNTER(VCPU, pf_spurious),
  227. STATS_DESC_COUNTER(VCPU, pf_fast),
  228. STATS_DESC_COUNTER(VCPU, pf_mmio_spte_created),
  229. STATS_DESC_COUNTER(VCPU, pf_guest),
  230. STATS_DESC_COUNTER(VCPU, tlb_flush),
  231. STATS_DESC_COUNTER(VCPU, invlpg),
  232. STATS_DESC_COUNTER(VCPU, exits),
  233. STATS_DESC_COUNTER(VCPU, io_exits),
  234. STATS_DESC_COUNTER(VCPU, mmio_exits),
  235. STATS_DESC_COUNTER(VCPU, signal_exits),
  236. STATS_DESC_COUNTER(VCPU, irq_window_exits),
  237. STATS_DESC_COUNTER(VCPU, nmi_window_exits),
  238. STATS_DESC_COUNTER(VCPU, l1d_flush),
  239. STATS_DESC_COUNTER(VCPU, halt_exits),
  240. STATS_DESC_COUNTER(VCPU, request_irq_exits),
  241. STATS_DESC_COUNTER(VCPU, irq_exits),
  242. STATS_DESC_COUNTER(VCPU, host_state_reload),
  243. STATS_DESC_COUNTER(VCPU, fpu_reload),
  244. STATS_DESC_COUNTER(VCPU, insn_emulation),
  245. STATS_DESC_COUNTER(VCPU, insn_emulation_fail),
  246. STATS_DESC_COUNTER(VCPU, hypercalls),
  247. STATS_DESC_COUNTER(VCPU, irq_injections),
  248. STATS_DESC_COUNTER(VCPU, nmi_injections),
  249. STATS_DESC_COUNTER(VCPU, req_event),
  250. STATS_DESC_COUNTER(VCPU, nested_run),
  251. STATS_DESC_COUNTER(VCPU, directed_yield_attempted),
  252. STATS_DESC_COUNTER(VCPU, directed_yield_successful),
  253. STATS_DESC_COUNTER(VCPU, preemption_reported),
  254. STATS_DESC_COUNTER(VCPU, preemption_other),
  255. STATS_DESC_IBOOLEAN(VCPU, guest_mode),
  256. STATS_DESC_COUNTER(VCPU, notify_window_exits),
  257. };
  258. const struct kvm_stats_header kvm_vcpu_stats_header = {
  259. .name_size = KVM_STATS_NAME_SIZE,
  260. .num_desc = ARRAY_SIZE(kvm_vcpu_stats_desc),
  261. .id_offset = sizeof(struct kvm_stats_header),
  262. .desc_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE,
  263. .data_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE +
  264. sizeof(kvm_vcpu_stats_desc),
  265. };
  266. u64 __read_mostly host_xcr0;
  267. static struct kmem_cache *x86_emulator_cache;
  268. /*
  269. * When called, it means the previous get/set msr reached an invalid msr.
  270. * Return true if we want to ignore/silent this failed msr access.
  271. */
  272. static bool kvm_msr_ignored_check(u32 msr, u64 data, bool write)
  273. {
  274. const char *op = write ? "wrmsr" : "rdmsr";
  275. if (ignore_msrs) {
  276. if (report_ignored_msrs)
  277. kvm_pr_unimpl("ignored %s: 0x%x data 0x%llx\n",
  278. op, msr, data);
  279. /* Mask the error */
  280. return true;
  281. } else {
  282. kvm_debug_ratelimited("unhandled %s: 0x%x data 0x%llx\n",
  283. op, msr, data);
  284. return false;
  285. }
  286. }
  287. static struct kmem_cache *kvm_alloc_emulator_cache(void)
  288. {
  289. unsigned int useroffset = offsetof(struct x86_emulate_ctxt, src);
  290. unsigned int size = sizeof(struct x86_emulate_ctxt);
  291. return kmem_cache_create_usercopy("x86_emulator", size,
  292. __alignof__(struct x86_emulate_ctxt),
  293. SLAB_ACCOUNT, useroffset,
  294. size - useroffset, NULL);
  295. }
  296. static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
  297. static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
  298. {
  299. int i;
  300. for (i = 0; i < ASYNC_PF_PER_VCPU; i++)
  301. vcpu->arch.apf.gfns[i] = ~0;
  302. }
  303. static void kvm_on_user_return(struct user_return_notifier *urn)
  304. {
  305. unsigned slot;
  306. struct kvm_user_return_msrs *msrs
  307. = container_of(urn, struct kvm_user_return_msrs, urn);
  308. struct kvm_user_return_msr_values *values;
  309. unsigned long flags;
  310. /*
  311. * Disabling irqs at this point since the following code could be
  312. * interrupted and executed through kvm_arch_hardware_disable()
  313. */
  314. local_irq_save(flags);
  315. if (msrs->registered) {
  316. msrs->registered = false;
  317. user_return_notifier_unregister(urn);
  318. }
  319. local_irq_restore(flags);
  320. for (slot = 0; slot < kvm_nr_uret_msrs; ++slot) {
  321. values = &msrs->values[slot];
  322. if (values->host != values->curr) {
  323. wrmsrl(kvm_uret_msrs_list[slot], values->host);
  324. values->curr = values->host;
  325. }
  326. }
  327. }
  328. static int kvm_probe_user_return_msr(u32 msr)
  329. {
  330. u64 val;
  331. int ret;
  332. preempt_disable();
  333. ret = rdmsrl_safe(msr, &val);
  334. if (ret)
  335. goto out;
  336. ret = wrmsrl_safe(msr, val);
  337. out:
  338. preempt_enable();
  339. return ret;
  340. }
  341. int kvm_add_user_return_msr(u32 msr)
  342. {
  343. BUG_ON(kvm_nr_uret_msrs >= KVM_MAX_NR_USER_RETURN_MSRS);
  344. if (kvm_probe_user_return_msr(msr))
  345. return -1;
  346. kvm_uret_msrs_list[kvm_nr_uret_msrs] = msr;
  347. return kvm_nr_uret_msrs++;
  348. }
  349. EXPORT_SYMBOL_GPL(kvm_add_user_return_msr);
  350. int kvm_find_user_return_msr(u32 msr)
  351. {
  352. int i;
  353. for (i = 0; i < kvm_nr_uret_msrs; ++i) {
  354. if (kvm_uret_msrs_list[i] == msr)
  355. return i;
  356. }
  357. return -1;
  358. }
  359. EXPORT_SYMBOL_GPL(kvm_find_user_return_msr);
  360. static void kvm_user_return_msr_cpu_online(void)
  361. {
  362. unsigned int cpu = smp_processor_id();
  363. struct kvm_user_return_msrs *msrs = per_cpu_ptr(user_return_msrs, cpu);
  364. u64 value;
  365. int i;
  366. for (i = 0; i < kvm_nr_uret_msrs; ++i) {
  367. rdmsrl_safe(kvm_uret_msrs_list[i], &value);
  368. msrs->values[i].host = value;
  369. msrs->values[i].curr = value;
  370. }
  371. }
  372. int kvm_set_user_return_msr(unsigned slot, u64 value, u64 mask)
  373. {
  374. unsigned int cpu = smp_processor_id();
  375. struct kvm_user_return_msrs *msrs = per_cpu_ptr(user_return_msrs, cpu);
  376. int err;
  377. value = (value & mask) | (msrs->values[slot].host & ~mask);
  378. if (value == msrs->values[slot].curr)
  379. return 0;
  380. err = wrmsrl_safe(kvm_uret_msrs_list[slot], value);
  381. if (err)
  382. return 1;
  383. msrs->values[slot].curr = value;
  384. if (!msrs->registered) {
  385. msrs->urn.on_user_return = kvm_on_user_return;
  386. user_return_notifier_register(&msrs->urn);
  387. msrs->registered = true;
  388. }
  389. return 0;
  390. }
  391. EXPORT_SYMBOL_GPL(kvm_set_user_return_msr);
  392. static void drop_user_return_notifiers(void)
  393. {
  394. unsigned int cpu = smp_processor_id();
  395. struct kvm_user_return_msrs *msrs = per_cpu_ptr(user_return_msrs, cpu);
  396. if (msrs->registered)
  397. kvm_on_user_return(&msrs->urn);
  398. }
  399. u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
  400. {
  401. return vcpu->arch.apic_base;
  402. }
  403. EXPORT_SYMBOL_GPL(kvm_get_apic_base);
  404. enum lapic_mode kvm_get_apic_mode(struct kvm_vcpu *vcpu)
  405. {
  406. return kvm_apic_mode(kvm_get_apic_base(vcpu));
  407. }
  408. EXPORT_SYMBOL_GPL(kvm_get_apic_mode);
  409. int kvm_set_apic_base(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
  410. {
  411. enum lapic_mode old_mode = kvm_get_apic_mode(vcpu);
  412. enum lapic_mode new_mode = kvm_apic_mode(msr_info->data);
  413. u64 reserved_bits = kvm_vcpu_reserved_gpa_bits_raw(vcpu) | 0x2ff |
  414. (guest_cpuid_has(vcpu, X86_FEATURE_X2APIC) ? 0 : X2APIC_ENABLE);
  415. if ((msr_info->data & reserved_bits) != 0 || new_mode == LAPIC_MODE_INVALID)
  416. return 1;
  417. if (!msr_info->host_initiated) {
  418. if (old_mode == LAPIC_MODE_X2APIC && new_mode == LAPIC_MODE_XAPIC)
  419. return 1;
  420. if (old_mode == LAPIC_MODE_DISABLED && new_mode == LAPIC_MODE_X2APIC)
  421. return 1;
  422. }
  423. kvm_lapic_set_base(vcpu, msr_info->data);
  424. kvm_recalculate_apic_map(vcpu->kvm);
  425. return 0;
  426. }
  427. EXPORT_SYMBOL_GPL(kvm_set_apic_base);
  428. /*
  429. * Handle a fault on a hardware virtualization (VMX or SVM) instruction.
  430. *
  431. * Hardware virtualization extension instructions may fault if a reboot turns
  432. * off virtualization while processes are running. Usually after catching the
  433. * fault we just panic; during reboot instead the instruction is ignored.
  434. */
  435. noinstr void kvm_spurious_fault(void)
  436. {
  437. /* Fault while not rebooting. We want the trace. */
  438. BUG_ON(!kvm_rebooting);
  439. }
  440. EXPORT_SYMBOL_GPL(kvm_spurious_fault);
  441. #define EXCPT_BENIGN 0
  442. #define EXCPT_CONTRIBUTORY 1
  443. #define EXCPT_PF 2
  444. static int exception_class(int vector)
  445. {
  446. switch (vector) {
  447. case PF_VECTOR:
  448. return EXCPT_PF;
  449. case DE_VECTOR:
  450. case TS_VECTOR:
  451. case NP_VECTOR:
  452. case SS_VECTOR:
  453. case GP_VECTOR:
  454. return EXCPT_CONTRIBUTORY;
  455. default:
  456. break;
  457. }
  458. return EXCPT_BENIGN;
  459. }
  460. #define EXCPT_FAULT 0
  461. #define EXCPT_TRAP 1
  462. #define EXCPT_ABORT 2
  463. #define EXCPT_INTERRUPT 3
  464. #define EXCPT_DB 4
  465. static int exception_type(int vector)
  466. {
  467. unsigned int mask;
  468. if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
  469. return EXCPT_INTERRUPT;
  470. mask = 1 << vector;
  471. /*
  472. * #DBs can be trap-like or fault-like, the caller must check other CPU
  473. * state, e.g. DR6, to determine whether a #DB is a trap or fault.
  474. */
  475. if (mask & (1 << DB_VECTOR))
  476. return EXCPT_DB;
  477. if (mask & ((1 << BP_VECTOR) | (1 << OF_VECTOR)))
  478. return EXCPT_TRAP;
  479. if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
  480. return EXCPT_ABORT;
  481. /* Reserved exceptions will result in fault */
  482. return EXCPT_FAULT;
  483. }
  484. void kvm_deliver_exception_payload(struct kvm_vcpu *vcpu,
  485. struct kvm_queued_exception *ex)
  486. {
  487. if (!ex->has_payload)
  488. return;
  489. switch (ex->vector) {
  490. case DB_VECTOR:
  491. /*
  492. * "Certain debug exceptions may clear bit 0-3. The
  493. * remaining contents of the DR6 register are never
  494. * cleared by the processor".
  495. */
  496. vcpu->arch.dr6 &= ~DR_TRAP_BITS;
  497. /*
  498. * In order to reflect the #DB exception payload in guest
  499. * dr6, three components need to be considered: active low
  500. * bit, FIXED_1 bits and active high bits (e.g. DR6_BD,
  501. * DR6_BS and DR6_BT)
  502. * DR6_ACTIVE_LOW contains the FIXED_1 and active low bits.
  503. * In the target guest dr6:
  504. * FIXED_1 bits should always be set.
  505. * Active low bits should be cleared if 1-setting in payload.
  506. * Active high bits should be set if 1-setting in payload.
  507. *
  508. * Note, the payload is compatible with the pending debug
  509. * exceptions/exit qualification under VMX, that active_low bits
  510. * are active high in payload.
  511. * So they need to be flipped for DR6.
  512. */
  513. vcpu->arch.dr6 |= DR6_ACTIVE_LOW;
  514. vcpu->arch.dr6 |= ex->payload;
  515. vcpu->arch.dr6 ^= ex->payload & DR6_ACTIVE_LOW;
  516. /*
  517. * The #DB payload is defined as compatible with the 'pending
  518. * debug exceptions' field under VMX, not DR6. While bit 12 is
  519. * defined in the 'pending debug exceptions' field (enabled
  520. * breakpoint), it is reserved and must be zero in DR6.
  521. */
  522. vcpu->arch.dr6 &= ~BIT(12);
  523. break;
  524. case PF_VECTOR:
  525. vcpu->arch.cr2 = ex->payload;
  526. break;
  527. }
  528. ex->has_payload = false;
  529. ex->payload = 0;
  530. }
  531. EXPORT_SYMBOL_GPL(kvm_deliver_exception_payload);
  532. static void kvm_queue_exception_vmexit(struct kvm_vcpu *vcpu, unsigned int vector,
  533. bool has_error_code, u32 error_code,
  534. bool has_payload, unsigned long payload)
  535. {
  536. struct kvm_queued_exception *ex = &vcpu->arch.exception_vmexit;
  537. ex->vector = vector;
  538. ex->injected = false;
  539. ex->pending = true;
  540. ex->has_error_code = has_error_code;
  541. ex->error_code = error_code;
  542. ex->has_payload = has_payload;
  543. ex->payload = payload;
  544. }
  545. /* Forcibly leave the nested mode in cases like a vCPU reset */
  546. static void kvm_leave_nested(struct kvm_vcpu *vcpu)
  547. {
  548. kvm_x86_ops.nested_ops->leave_nested(vcpu);
  549. }
  550. static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
  551. unsigned nr, bool has_error, u32 error_code,
  552. bool has_payload, unsigned long payload, bool reinject)
  553. {
  554. u32 prev_nr;
  555. int class1, class2;
  556. kvm_make_request(KVM_REQ_EVENT, vcpu);
  557. /*
  558. * If the exception is destined for L2 and isn't being reinjected,
  559. * morph it to a VM-Exit if L1 wants to intercept the exception. A
  560. * previously injected exception is not checked because it was checked
  561. * when it was original queued, and re-checking is incorrect if _L1_
  562. * injected the exception, in which case it's exempt from interception.
  563. */
  564. if (!reinject && is_guest_mode(vcpu) &&
  565. kvm_x86_ops.nested_ops->is_exception_vmexit(vcpu, nr, error_code)) {
  566. kvm_queue_exception_vmexit(vcpu, nr, has_error, error_code,
  567. has_payload, payload);
  568. return;
  569. }
  570. if (!vcpu->arch.exception.pending && !vcpu->arch.exception.injected) {
  571. queue:
  572. if (reinject) {
  573. /*
  574. * On VM-Entry, an exception can be pending if and only
  575. * if event injection was blocked by nested_run_pending.
  576. * In that case, however, vcpu_enter_guest() requests an
  577. * immediate exit, and the guest shouldn't proceed far
  578. * enough to need reinjection.
  579. */
  580. WARN_ON_ONCE(kvm_is_exception_pending(vcpu));
  581. vcpu->arch.exception.injected = true;
  582. if (WARN_ON_ONCE(has_payload)) {
  583. /*
  584. * A reinjected event has already
  585. * delivered its payload.
  586. */
  587. has_payload = false;
  588. payload = 0;
  589. }
  590. } else {
  591. vcpu->arch.exception.pending = true;
  592. vcpu->arch.exception.injected = false;
  593. }
  594. vcpu->arch.exception.has_error_code = has_error;
  595. vcpu->arch.exception.vector = nr;
  596. vcpu->arch.exception.error_code = error_code;
  597. vcpu->arch.exception.has_payload = has_payload;
  598. vcpu->arch.exception.payload = payload;
  599. if (!is_guest_mode(vcpu))
  600. kvm_deliver_exception_payload(vcpu,
  601. &vcpu->arch.exception);
  602. return;
  603. }
  604. /* to check exception */
  605. prev_nr = vcpu->arch.exception.vector;
  606. if (prev_nr == DF_VECTOR) {
  607. /* triple fault -> shutdown */
  608. kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
  609. return;
  610. }
  611. class1 = exception_class(prev_nr);
  612. class2 = exception_class(nr);
  613. if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY) ||
  614. (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
  615. /*
  616. * Synthesize #DF. Clear the previously injected or pending
  617. * exception so as not to incorrectly trigger shutdown.
  618. */
  619. vcpu->arch.exception.injected = false;
  620. vcpu->arch.exception.pending = false;
  621. kvm_queue_exception_e(vcpu, DF_VECTOR, 0);
  622. } else {
  623. /* replace previous exception with a new one in a hope
  624. that instruction re-execution will regenerate lost
  625. exception */
  626. goto queue;
  627. }
  628. }
  629. void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
  630. {
  631. kvm_multiple_exception(vcpu, nr, false, 0, false, 0, false);
  632. }
  633. EXPORT_SYMBOL_GPL(kvm_queue_exception);
  634. void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
  635. {
  636. kvm_multiple_exception(vcpu, nr, false, 0, false, 0, true);
  637. }
  638. EXPORT_SYMBOL_GPL(kvm_requeue_exception);
  639. void kvm_queue_exception_p(struct kvm_vcpu *vcpu, unsigned nr,
  640. unsigned long payload)
  641. {
  642. kvm_multiple_exception(vcpu, nr, false, 0, true, payload, false);
  643. }
  644. EXPORT_SYMBOL_GPL(kvm_queue_exception_p);
  645. static void kvm_queue_exception_e_p(struct kvm_vcpu *vcpu, unsigned nr,
  646. u32 error_code, unsigned long payload)
  647. {
  648. kvm_multiple_exception(vcpu, nr, true, error_code,
  649. true, payload, false);
  650. }
  651. int kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
  652. {
  653. if (err)
  654. kvm_inject_gp(vcpu, 0);
  655. else
  656. return kvm_skip_emulated_instruction(vcpu);
  657. return 1;
  658. }
  659. EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
  660. static int complete_emulated_insn_gp(struct kvm_vcpu *vcpu, int err)
  661. {
  662. if (err) {
  663. kvm_inject_gp(vcpu, 0);
  664. return 1;
  665. }
  666. return kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE | EMULTYPE_SKIP |
  667. EMULTYPE_COMPLETE_USER_EXIT);
  668. }
  669. void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
  670. {
  671. ++vcpu->stat.pf_guest;
  672. /*
  673. * Async #PF in L2 is always forwarded to L1 as a VM-Exit regardless of
  674. * whether or not L1 wants to intercept "regular" #PF.
  675. */
  676. if (is_guest_mode(vcpu) && fault->async_page_fault)
  677. kvm_queue_exception_vmexit(vcpu, PF_VECTOR,
  678. true, fault->error_code,
  679. true, fault->address);
  680. else
  681. kvm_queue_exception_e_p(vcpu, PF_VECTOR, fault->error_code,
  682. fault->address);
  683. }
  684. EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
  685. void kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
  686. struct x86_exception *fault)
  687. {
  688. struct kvm_mmu *fault_mmu;
  689. WARN_ON_ONCE(fault->vector != PF_VECTOR);
  690. fault_mmu = fault->nested_page_fault ? vcpu->arch.mmu :
  691. vcpu->arch.walk_mmu;
  692. /*
  693. * Invalidate the TLB entry for the faulting address, if it exists,
  694. * else the access will fault indefinitely (and to emulate hardware).
  695. */
  696. if ((fault->error_code & PFERR_PRESENT_MASK) &&
  697. !(fault->error_code & PFERR_RSVD_MASK))
  698. kvm_mmu_invalidate_gva(vcpu, fault_mmu, fault->address,
  699. fault_mmu->root.hpa);
  700. fault_mmu->inject_page_fault(vcpu, fault);
  701. }
  702. EXPORT_SYMBOL_GPL(kvm_inject_emulated_page_fault);
  703. void kvm_inject_nmi(struct kvm_vcpu *vcpu)
  704. {
  705. atomic_inc(&vcpu->arch.nmi_queued);
  706. kvm_make_request(KVM_REQ_NMI, vcpu);
  707. }
  708. EXPORT_SYMBOL_GPL(kvm_inject_nmi);
  709. void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
  710. {
  711. kvm_multiple_exception(vcpu, nr, true, error_code, false, 0, false);
  712. }
  713. EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
  714. void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
  715. {
  716. kvm_multiple_exception(vcpu, nr, true, error_code, false, 0, true);
  717. }
  718. EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
  719. /*
  720. * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
  721. * a #GP and return false.
  722. */
  723. bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
  724. {
  725. if (static_call(kvm_x86_get_cpl)(vcpu) <= required_cpl)
  726. return true;
  727. kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
  728. return false;
  729. }
  730. EXPORT_SYMBOL_GPL(kvm_require_cpl);
  731. bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
  732. {
  733. if ((dr != 4 && dr != 5) || !kvm_read_cr4_bits(vcpu, X86_CR4_DE))
  734. return true;
  735. kvm_queue_exception(vcpu, UD_VECTOR);
  736. return false;
  737. }
  738. EXPORT_SYMBOL_GPL(kvm_require_dr);
  739. static inline u64 pdptr_rsvd_bits(struct kvm_vcpu *vcpu)
  740. {
  741. return vcpu->arch.reserved_gpa_bits | rsvd_bits(5, 8) | rsvd_bits(1, 2);
  742. }
  743. /*
  744. * Load the pae pdptrs. Return 1 if they are all valid, 0 otherwise.
  745. */
  746. int load_pdptrs(struct kvm_vcpu *vcpu, unsigned long cr3)
  747. {
  748. struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
  749. gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
  750. gpa_t real_gpa;
  751. int i;
  752. int ret;
  753. u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
  754. /*
  755. * If the MMU is nested, CR3 holds an L2 GPA and needs to be translated
  756. * to an L1 GPA.
  757. */
  758. real_gpa = kvm_translate_gpa(vcpu, mmu, gfn_to_gpa(pdpt_gfn),
  759. PFERR_USER_MASK | PFERR_WRITE_MASK, NULL);
  760. if (real_gpa == INVALID_GPA)
  761. return 0;
  762. /* Note the offset, PDPTRs are 32 byte aligned when using PAE paging. */
  763. ret = kvm_vcpu_read_guest_page(vcpu, gpa_to_gfn(real_gpa), pdpte,
  764. cr3 & GENMASK(11, 5), sizeof(pdpte));
  765. if (ret < 0)
  766. return 0;
  767. for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
  768. if ((pdpte[i] & PT_PRESENT_MASK) &&
  769. (pdpte[i] & pdptr_rsvd_bits(vcpu))) {
  770. return 0;
  771. }
  772. }
  773. /*
  774. * Marking VCPU_EXREG_PDPTR dirty doesn't work for !tdp_enabled.
  775. * Shadow page roots need to be reconstructed instead.
  776. */
  777. if (!tdp_enabled && memcmp(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs)))
  778. kvm_mmu_free_roots(vcpu->kvm, mmu, KVM_MMU_ROOT_CURRENT);
  779. memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
  780. kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
  781. kvm_make_request(KVM_REQ_LOAD_MMU_PGD, vcpu);
  782. vcpu->arch.pdptrs_from_userspace = false;
  783. return 1;
  784. }
  785. EXPORT_SYMBOL_GPL(load_pdptrs);
  786. static bool kvm_is_valid_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
  787. {
  788. #ifdef CONFIG_X86_64
  789. if (cr0 & 0xffffffff00000000UL)
  790. return false;
  791. #endif
  792. if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
  793. return false;
  794. if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
  795. return false;
  796. return static_call(kvm_x86_is_valid_cr0)(vcpu, cr0);
  797. }
  798. void kvm_post_set_cr0(struct kvm_vcpu *vcpu, unsigned long old_cr0, unsigned long cr0)
  799. {
  800. /*
  801. * CR0.WP is incorporated into the MMU role, but only for non-nested,
  802. * indirect shadow MMUs. If TDP is enabled, the MMU's metadata needs
  803. * to be updated, e.g. so that emulating guest translations does the
  804. * right thing, but there's no need to unload the root as CR0.WP
  805. * doesn't affect SPTEs.
  806. */
  807. if (tdp_enabled && (cr0 ^ old_cr0) == X86_CR0_WP) {
  808. kvm_init_mmu(vcpu);
  809. return;
  810. }
  811. if ((cr0 ^ old_cr0) & X86_CR0_PG) {
  812. kvm_clear_async_pf_completion_queue(vcpu);
  813. kvm_async_pf_hash_reset(vcpu);
  814. /*
  815. * Clearing CR0.PG is defined to flush the TLB from the guest's
  816. * perspective.
  817. */
  818. if (!(cr0 & X86_CR0_PG))
  819. kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
  820. }
  821. if ((cr0 ^ old_cr0) & KVM_MMU_CR0_ROLE_BITS)
  822. kvm_mmu_reset_context(vcpu);
  823. if (((cr0 ^ old_cr0) & X86_CR0_CD) &&
  824. kvm_arch_has_noncoherent_dma(vcpu->kvm) &&
  825. !kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
  826. kvm_zap_gfn_range(vcpu->kvm, 0, ~0ULL);
  827. }
  828. EXPORT_SYMBOL_GPL(kvm_post_set_cr0);
  829. int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
  830. {
  831. unsigned long old_cr0 = kvm_read_cr0(vcpu);
  832. if (!kvm_is_valid_cr0(vcpu, cr0))
  833. return 1;
  834. cr0 |= X86_CR0_ET;
  835. /* Write to CR0 reserved bits are ignored, even on Intel. */
  836. cr0 &= ~CR0_RESERVED_BITS;
  837. #ifdef CONFIG_X86_64
  838. if ((vcpu->arch.efer & EFER_LME) && !is_paging(vcpu) &&
  839. (cr0 & X86_CR0_PG)) {
  840. int cs_db, cs_l;
  841. if (!is_pae(vcpu))
  842. return 1;
  843. static_call(kvm_x86_get_cs_db_l_bits)(vcpu, &cs_db, &cs_l);
  844. if (cs_l)
  845. return 1;
  846. }
  847. #endif
  848. if (!(vcpu->arch.efer & EFER_LME) && (cr0 & X86_CR0_PG) &&
  849. is_pae(vcpu) && ((cr0 ^ old_cr0) & X86_CR0_PDPTR_BITS) &&
  850. !load_pdptrs(vcpu, kvm_read_cr3(vcpu)))
  851. return 1;
  852. if (!(cr0 & X86_CR0_PG) &&
  853. (is_64_bit_mode(vcpu) || kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE)))
  854. return 1;
  855. static_call(kvm_x86_set_cr0)(vcpu, cr0);
  856. kvm_post_set_cr0(vcpu, old_cr0, cr0);
  857. return 0;
  858. }
  859. EXPORT_SYMBOL_GPL(kvm_set_cr0);
  860. void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
  861. {
  862. (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
  863. }
  864. EXPORT_SYMBOL_GPL(kvm_lmsw);
  865. void kvm_load_guest_xsave_state(struct kvm_vcpu *vcpu)
  866. {
  867. if (vcpu->arch.guest_state_protected)
  868. return;
  869. if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE)) {
  870. if (vcpu->arch.xcr0 != host_xcr0)
  871. xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
  872. if (vcpu->arch.xsaves_enabled &&
  873. vcpu->arch.ia32_xss != host_xss)
  874. wrmsrl(MSR_IA32_XSS, vcpu->arch.ia32_xss);
  875. }
  876. #ifdef CONFIG_X86_INTEL_MEMORY_PROTECTION_KEYS
  877. if (static_cpu_has(X86_FEATURE_PKU) &&
  878. vcpu->arch.pkru != vcpu->arch.host_pkru &&
  879. ((vcpu->arch.xcr0 & XFEATURE_MASK_PKRU) ||
  880. kvm_read_cr4_bits(vcpu, X86_CR4_PKE)))
  881. write_pkru(vcpu->arch.pkru);
  882. #endif /* CONFIG_X86_INTEL_MEMORY_PROTECTION_KEYS */
  883. }
  884. EXPORT_SYMBOL_GPL(kvm_load_guest_xsave_state);
  885. void kvm_load_host_xsave_state(struct kvm_vcpu *vcpu)
  886. {
  887. if (vcpu->arch.guest_state_protected)
  888. return;
  889. #ifdef CONFIG_X86_INTEL_MEMORY_PROTECTION_KEYS
  890. if (static_cpu_has(X86_FEATURE_PKU) &&
  891. ((vcpu->arch.xcr0 & XFEATURE_MASK_PKRU) ||
  892. kvm_read_cr4_bits(vcpu, X86_CR4_PKE))) {
  893. vcpu->arch.pkru = rdpkru();
  894. if (vcpu->arch.pkru != vcpu->arch.host_pkru)
  895. write_pkru(vcpu->arch.host_pkru);
  896. }
  897. #endif /* CONFIG_X86_INTEL_MEMORY_PROTECTION_KEYS */
  898. if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE)) {
  899. if (vcpu->arch.xcr0 != host_xcr0)
  900. xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
  901. if (vcpu->arch.xsaves_enabled &&
  902. vcpu->arch.ia32_xss != host_xss)
  903. wrmsrl(MSR_IA32_XSS, host_xss);
  904. }
  905. }
  906. EXPORT_SYMBOL_GPL(kvm_load_host_xsave_state);
  907. #ifdef CONFIG_X86_64
  908. static inline u64 kvm_guest_supported_xfd(struct kvm_vcpu *vcpu)
  909. {
  910. return vcpu->arch.guest_supported_xcr0 & XFEATURE_MASK_USER_DYNAMIC;
  911. }
  912. #endif
  913. static int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
  914. {
  915. u64 xcr0 = xcr;
  916. u64 old_xcr0 = vcpu->arch.xcr0;
  917. u64 valid_bits;
  918. /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
  919. if (index != XCR_XFEATURE_ENABLED_MASK)
  920. return 1;
  921. if (!(xcr0 & XFEATURE_MASK_FP))
  922. return 1;
  923. if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
  924. return 1;
  925. /*
  926. * Do not allow the guest to set bits that we do not support
  927. * saving. However, xcr0 bit 0 is always set, even if the
  928. * emulated CPU does not support XSAVE (see kvm_vcpu_reset()).
  929. */
  930. valid_bits = vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FP;
  931. if (xcr0 & ~valid_bits)
  932. return 1;
  933. if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
  934. (!(xcr0 & XFEATURE_MASK_BNDCSR)))
  935. return 1;
  936. if (xcr0 & XFEATURE_MASK_AVX512) {
  937. if (!(xcr0 & XFEATURE_MASK_YMM))
  938. return 1;
  939. if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
  940. return 1;
  941. }
  942. if ((xcr0 & XFEATURE_MASK_XTILE) &&
  943. ((xcr0 & XFEATURE_MASK_XTILE) != XFEATURE_MASK_XTILE))
  944. return 1;
  945. vcpu->arch.xcr0 = xcr0;
  946. if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
  947. kvm_update_cpuid_runtime(vcpu);
  948. return 0;
  949. }
  950. int kvm_emulate_xsetbv(struct kvm_vcpu *vcpu)
  951. {
  952. /* Note, #UD due to CR4.OSXSAVE=0 has priority over the intercept. */
  953. if (static_call(kvm_x86_get_cpl)(vcpu) != 0 ||
  954. __kvm_set_xcr(vcpu, kvm_rcx_read(vcpu), kvm_read_edx_eax(vcpu))) {
  955. kvm_inject_gp(vcpu, 0);
  956. return 1;
  957. }
  958. return kvm_skip_emulated_instruction(vcpu);
  959. }
  960. EXPORT_SYMBOL_GPL(kvm_emulate_xsetbv);
  961. bool __kvm_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
  962. {
  963. if (cr4 & cr4_reserved_bits)
  964. return false;
  965. if (cr4 & vcpu->arch.cr4_guest_rsvd_bits)
  966. return false;
  967. return true;
  968. }
  969. EXPORT_SYMBOL_GPL(__kvm_is_valid_cr4);
  970. static bool kvm_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
  971. {
  972. return __kvm_is_valid_cr4(vcpu, cr4) &&
  973. static_call(kvm_x86_is_valid_cr4)(vcpu, cr4);
  974. }
  975. void kvm_post_set_cr4(struct kvm_vcpu *vcpu, unsigned long old_cr4, unsigned long cr4)
  976. {
  977. if ((cr4 ^ old_cr4) & KVM_MMU_CR4_ROLE_BITS)
  978. kvm_mmu_reset_context(vcpu);
  979. /*
  980. * If CR4.PCIDE is changed 0 -> 1, there is no need to flush the TLB
  981. * according to the SDM; however, stale prev_roots could be reused
  982. * incorrectly in the future after a MOV to CR3 with NOFLUSH=1, so we
  983. * free them all. This is *not* a superset of KVM_REQ_TLB_FLUSH_GUEST
  984. * or KVM_REQ_TLB_FLUSH_CURRENT, because the hardware TLB is not flushed,
  985. * so fall through.
  986. */
  987. if (!tdp_enabled &&
  988. (cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE))
  989. kvm_mmu_unload(vcpu);
  990. /*
  991. * The TLB has to be flushed for all PCIDs if any of the following
  992. * (architecturally required) changes happen:
  993. * - CR4.PCIDE is changed from 1 to 0
  994. * - CR4.PGE is toggled
  995. *
  996. * This is a superset of KVM_REQ_TLB_FLUSH_CURRENT.
  997. */
  998. if (((cr4 ^ old_cr4) & X86_CR4_PGE) ||
  999. (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
  1000. kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
  1001. /*
  1002. * The TLB has to be flushed for the current PCID if any of the
  1003. * following (architecturally required) changes happen:
  1004. * - CR4.SMEP is changed from 0 to 1
  1005. * - CR4.PAE is toggled
  1006. */
  1007. else if (((cr4 ^ old_cr4) & X86_CR4_PAE) ||
  1008. ((cr4 & X86_CR4_SMEP) && !(old_cr4 & X86_CR4_SMEP)))
  1009. kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
  1010. }
  1011. EXPORT_SYMBOL_GPL(kvm_post_set_cr4);
  1012. int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
  1013. {
  1014. unsigned long old_cr4 = kvm_read_cr4(vcpu);
  1015. if (!kvm_is_valid_cr4(vcpu, cr4))
  1016. return 1;
  1017. if (is_long_mode(vcpu)) {
  1018. if (!(cr4 & X86_CR4_PAE))
  1019. return 1;
  1020. if ((cr4 ^ old_cr4) & X86_CR4_LA57)
  1021. return 1;
  1022. } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
  1023. && ((cr4 ^ old_cr4) & X86_CR4_PDPTR_BITS)
  1024. && !load_pdptrs(vcpu, kvm_read_cr3(vcpu)))
  1025. return 1;
  1026. if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
  1027. if (!guest_cpuid_has(vcpu, X86_FEATURE_PCID))
  1028. return 1;
  1029. /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
  1030. if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
  1031. return 1;
  1032. }
  1033. static_call(kvm_x86_set_cr4)(vcpu, cr4);
  1034. kvm_post_set_cr4(vcpu, old_cr4, cr4);
  1035. return 0;
  1036. }
  1037. EXPORT_SYMBOL_GPL(kvm_set_cr4);
  1038. static void kvm_invalidate_pcid(struct kvm_vcpu *vcpu, unsigned long pcid)
  1039. {
  1040. struct kvm_mmu *mmu = vcpu->arch.mmu;
  1041. unsigned long roots_to_free = 0;
  1042. int i;
  1043. /*
  1044. * MOV CR3 and INVPCID are usually not intercepted when using TDP, but
  1045. * this is reachable when running EPT=1 and unrestricted_guest=0, and
  1046. * also via the emulator. KVM's TDP page tables are not in the scope of
  1047. * the invalidation, but the guest's TLB entries need to be flushed as
  1048. * the CPU may have cached entries in its TLB for the target PCID.
  1049. */
  1050. if (unlikely(tdp_enabled)) {
  1051. kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
  1052. return;
  1053. }
  1054. /*
  1055. * If neither the current CR3 nor any of the prev_roots use the given
  1056. * PCID, then nothing needs to be done here because a resync will
  1057. * happen anyway before switching to any other CR3.
  1058. */
  1059. if (kvm_get_active_pcid(vcpu) == pcid) {
  1060. kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
  1061. kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
  1062. }
  1063. /*
  1064. * If PCID is disabled, there is no need to free prev_roots even if the
  1065. * PCIDs for them are also 0, because MOV to CR3 always flushes the TLB
  1066. * with PCIDE=0.
  1067. */
  1068. if (!kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
  1069. return;
  1070. for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
  1071. if (kvm_get_pcid(vcpu, mmu->prev_roots[i].pgd) == pcid)
  1072. roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
  1073. kvm_mmu_free_roots(vcpu->kvm, mmu, roots_to_free);
  1074. }
  1075. int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
  1076. {
  1077. bool skip_tlb_flush = false;
  1078. unsigned long pcid = 0;
  1079. #ifdef CONFIG_X86_64
  1080. bool pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
  1081. if (pcid_enabled) {
  1082. skip_tlb_flush = cr3 & X86_CR3_PCID_NOFLUSH;
  1083. cr3 &= ~X86_CR3_PCID_NOFLUSH;
  1084. pcid = cr3 & X86_CR3_PCID_MASK;
  1085. }
  1086. #endif
  1087. /* PDPTRs are always reloaded for PAE paging. */
  1088. if (cr3 == kvm_read_cr3(vcpu) && !is_pae_paging(vcpu))
  1089. goto handle_tlb_flush;
  1090. /*
  1091. * Do not condition the GPA check on long mode, this helper is used to
  1092. * stuff CR3, e.g. for RSM emulation, and there is no guarantee that
  1093. * the current vCPU mode is accurate.
  1094. */
  1095. if (kvm_vcpu_is_illegal_gpa(vcpu, cr3))
  1096. return 1;
  1097. if (is_pae_paging(vcpu) && !load_pdptrs(vcpu, cr3))
  1098. return 1;
  1099. if (cr3 != kvm_read_cr3(vcpu))
  1100. kvm_mmu_new_pgd(vcpu, cr3);
  1101. vcpu->arch.cr3 = cr3;
  1102. kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
  1103. /* Do not call post_set_cr3, we do not get here for confidential guests. */
  1104. handle_tlb_flush:
  1105. /*
  1106. * A load of CR3 that flushes the TLB flushes only the current PCID,
  1107. * even if PCID is disabled, in which case PCID=0 is flushed. It's a
  1108. * moot point in the end because _disabling_ PCID will flush all PCIDs,
  1109. * and it's impossible to use a non-zero PCID when PCID is disabled,
  1110. * i.e. only PCID=0 can be relevant.
  1111. */
  1112. if (!skip_tlb_flush)
  1113. kvm_invalidate_pcid(vcpu, pcid);
  1114. return 0;
  1115. }
  1116. EXPORT_SYMBOL_GPL(kvm_set_cr3);
  1117. int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
  1118. {
  1119. if (cr8 & CR8_RESERVED_BITS)
  1120. return 1;
  1121. if (lapic_in_kernel(vcpu))
  1122. kvm_lapic_set_tpr(vcpu, cr8);
  1123. else
  1124. vcpu->arch.cr8 = cr8;
  1125. return 0;
  1126. }
  1127. EXPORT_SYMBOL_GPL(kvm_set_cr8);
  1128. unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
  1129. {
  1130. if (lapic_in_kernel(vcpu))
  1131. return kvm_lapic_get_cr8(vcpu);
  1132. else
  1133. return vcpu->arch.cr8;
  1134. }
  1135. EXPORT_SYMBOL_GPL(kvm_get_cr8);
  1136. static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
  1137. {
  1138. int i;
  1139. if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
  1140. for (i = 0; i < KVM_NR_DB_REGS; i++)
  1141. vcpu->arch.eff_db[i] = vcpu->arch.db[i];
  1142. }
  1143. }
  1144. void kvm_update_dr7(struct kvm_vcpu *vcpu)
  1145. {
  1146. unsigned long dr7;
  1147. if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
  1148. dr7 = vcpu->arch.guest_debug_dr7;
  1149. else
  1150. dr7 = vcpu->arch.dr7;
  1151. static_call(kvm_x86_set_dr7)(vcpu, dr7);
  1152. vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
  1153. if (dr7 & DR7_BP_EN_MASK)
  1154. vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
  1155. }
  1156. EXPORT_SYMBOL_GPL(kvm_update_dr7);
  1157. static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
  1158. {
  1159. u64 fixed = DR6_FIXED_1;
  1160. if (!guest_cpuid_has(vcpu, X86_FEATURE_RTM))
  1161. fixed |= DR6_RTM;
  1162. if (!guest_cpuid_has(vcpu, X86_FEATURE_BUS_LOCK_DETECT))
  1163. fixed |= DR6_BUS_LOCK;
  1164. return fixed;
  1165. }
  1166. int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
  1167. {
  1168. size_t size = ARRAY_SIZE(vcpu->arch.db);
  1169. switch (dr) {
  1170. case 0 ... 3:
  1171. vcpu->arch.db[array_index_nospec(dr, size)] = val;
  1172. if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
  1173. vcpu->arch.eff_db[dr] = val;
  1174. break;
  1175. case 4:
  1176. case 6:
  1177. if (!kvm_dr6_valid(val))
  1178. return 1; /* #GP */
  1179. vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
  1180. break;
  1181. case 5:
  1182. default: /* 7 */
  1183. if (!kvm_dr7_valid(val))
  1184. return 1; /* #GP */
  1185. vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
  1186. kvm_update_dr7(vcpu);
  1187. break;
  1188. }
  1189. return 0;
  1190. }
  1191. EXPORT_SYMBOL_GPL(kvm_set_dr);
  1192. void kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
  1193. {
  1194. size_t size = ARRAY_SIZE(vcpu->arch.db);
  1195. switch (dr) {
  1196. case 0 ... 3:
  1197. *val = vcpu->arch.db[array_index_nospec(dr, size)];
  1198. break;
  1199. case 4:
  1200. case 6:
  1201. *val = vcpu->arch.dr6;
  1202. break;
  1203. case 5:
  1204. default: /* 7 */
  1205. *val = vcpu->arch.dr7;
  1206. break;
  1207. }
  1208. }
  1209. EXPORT_SYMBOL_GPL(kvm_get_dr);
  1210. int kvm_emulate_rdpmc(struct kvm_vcpu *vcpu)
  1211. {
  1212. u32 ecx = kvm_rcx_read(vcpu);
  1213. u64 data;
  1214. if (kvm_pmu_rdpmc(vcpu, ecx, &data)) {
  1215. kvm_inject_gp(vcpu, 0);
  1216. return 1;
  1217. }
  1218. kvm_rax_write(vcpu, (u32)data);
  1219. kvm_rdx_write(vcpu, data >> 32);
  1220. return kvm_skip_emulated_instruction(vcpu);
  1221. }
  1222. EXPORT_SYMBOL_GPL(kvm_emulate_rdpmc);
  1223. /*
  1224. * List of msr numbers which we expose to userspace through KVM_GET_MSRS
  1225. * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
  1226. *
  1227. * The three MSR lists(msrs_to_save, emulated_msrs, msr_based_features)
  1228. * extract the supported MSRs from the related const lists.
  1229. * msrs_to_save is selected from the msrs_to_save_all to reflect the
  1230. * capabilities of the host cpu. This capabilities test skips MSRs that are
  1231. * kvm-specific. Those are put in emulated_msrs_all; filtering of emulated_msrs
  1232. * may depend on host virtualization features rather than host cpu features.
  1233. */
  1234. static const u32 msrs_to_save_all[] = {
  1235. MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
  1236. MSR_STAR,
  1237. #ifdef CONFIG_X86_64
  1238. MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
  1239. #endif
  1240. MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
  1241. MSR_IA32_FEAT_CTL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
  1242. MSR_IA32_SPEC_CTRL,
  1243. MSR_IA32_RTIT_CTL, MSR_IA32_RTIT_STATUS, MSR_IA32_RTIT_CR3_MATCH,
  1244. MSR_IA32_RTIT_OUTPUT_BASE, MSR_IA32_RTIT_OUTPUT_MASK,
  1245. MSR_IA32_RTIT_ADDR0_A, MSR_IA32_RTIT_ADDR0_B,
  1246. MSR_IA32_RTIT_ADDR1_A, MSR_IA32_RTIT_ADDR1_B,
  1247. MSR_IA32_RTIT_ADDR2_A, MSR_IA32_RTIT_ADDR2_B,
  1248. MSR_IA32_RTIT_ADDR3_A, MSR_IA32_RTIT_ADDR3_B,
  1249. MSR_IA32_UMWAIT_CONTROL,
  1250. MSR_ARCH_PERFMON_FIXED_CTR0, MSR_ARCH_PERFMON_FIXED_CTR1,
  1251. MSR_ARCH_PERFMON_FIXED_CTR0 + 2,
  1252. MSR_CORE_PERF_FIXED_CTR_CTRL, MSR_CORE_PERF_GLOBAL_STATUS,
  1253. MSR_CORE_PERF_GLOBAL_CTRL, MSR_CORE_PERF_GLOBAL_OVF_CTRL,
  1254. MSR_IA32_PEBS_ENABLE, MSR_IA32_DS_AREA, MSR_PEBS_DATA_CFG,
  1255. /* This part of MSRs should match KVM_INTEL_PMC_MAX_GENERIC. */
  1256. MSR_ARCH_PERFMON_PERFCTR0, MSR_ARCH_PERFMON_PERFCTR1,
  1257. MSR_ARCH_PERFMON_PERFCTR0 + 2, MSR_ARCH_PERFMON_PERFCTR0 + 3,
  1258. MSR_ARCH_PERFMON_PERFCTR0 + 4, MSR_ARCH_PERFMON_PERFCTR0 + 5,
  1259. MSR_ARCH_PERFMON_PERFCTR0 + 6, MSR_ARCH_PERFMON_PERFCTR0 + 7,
  1260. MSR_ARCH_PERFMON_EVENTSEL0, MSR_ARCH_PERFMON_EVENTSEL1,
  1261. MSR_ARCH_PERFMON_EVENTSEL0 + 2, MSR_ARCH_PERFMON_EVENTSEL0 + 3,
  1262. MSR_ARCH_PERFMON_EVENTSEL0 + 4, MSR_ARCH_PERFMON_EVENTSEL0 + 5,
  1263. MSR_ARCH_PERFMON_EVENTSEL0 + 6, MSR_ARCH_PERFMON_EVENTSEL0 + 7,
  1264. MSR_K7_EVNTSEL0, MSR_K7_EVNTSEL1, MSR_K7_EVNTSEL2, MSR_K7_EVNTSEL3,
  1265. MSR_K7_PERFCTR0, MSR_K7_PERFCTR1, MSR_K7_PERFCTR2, MSR_K7_PERFCTR3,
  1266. /* This part of MSRs should match KVM_AMD_PMC_MAX_GENERIC. */
  1267. MSR_F15H_PERF_CTL0, MSR_F15H_PERF_CTL1, MSR_F15H_PERF_CTL2,
  1268. MSR_F15H_PERF_CTL3, MSR_F15H_PERF_CTL4, MSR_F15H_PERF_CTL5,
  1269. MSR_F15H_PERF_CTR0, MSR_F15H_PERF_CTR1, MSR_F15H_PERF_CTR2,
  1270. MSR_F15H_PERF_CTR3, MSR_F15H_PERF_CTR4, MSR_F15H_PERF_CTR5,
  1271. MSR_IA32_XFD, MSR_IA32_XFD_ERR,
  1272. };
  1273. static u32 msrs_to_save[ARRAY_SIZE(msrs_to_save_all)];
  1274. static unsigned num_msrs_to_save;
  1275. static const u32 emulated_msrs_all[] = {
  1276. MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
  1277. MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
  1278. HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
  1279. HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
  1280. HV_X64_MSR_TSC_FREQUENCY, HV_X64_MSR_APIC_FREQUENCY,
  1281. HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
  1282. HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
  1283. HV_X64_MSR_RESET,
  1284. HV_X64_MSR_VP_INDEX,
  1285. HV_X64_MSR_VP_RUNTIME,
  1286. HV_X64_MSR_SCONTROL,
  1287. HV_X64_MSR_STIMER0_CONFIG,
  1288. HV_X64_MSR_VP_ASSIST_PAGE,
  1289. HV_X64_MSR_REENLIGHTENMENT_CONTROL, HV_X64_MSR_TSC_EMULATION_CONTROL,
  1290. HV_X64_MSR_TSC_EMULATION_STATUS,
  1291. HV_X64_MSR_SYNDBG_OPTIONS,
  1292. HV_X64_MSR_SYNDBG_CONTROL, HV_X64_MSR_SYNDBG_STATUS,
  1293. HV_X64_MSR_SYNDBG_SEND_BUFFER, HV_X64_MSR_SYNDBG_RECV_BUFFER,
  1294. HV_X64_MSR_SYNDBG_PENDING_BUFFER,
  1295. MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
  1296. MSR_KVM_PV_EOI_EN, MSR_KVM_ASYNC_PF_INT, MSR_KVM_ASYNC_PF_ACK,
  1297. MSR_IA32_TSC_ADJUST,
  1298. MSR_IA32_TSC_DEADLINE,
  1299. MSR_IA32_ARCH_CAPABILITIES,
  1300. MSR_IA32_PERF_CAPABILITIES,
  1301. MSR_IA32_MISC_ENABLE,
  1302. MSR_IA32_MCG_STATUS,
  1303. MSR_IA32_MCG_CTL,
  1304. MSR_IA32_MCG_EXT_CTL,
  1305. MSR_IA32_SMBASE,
  1306. MSR_SMI_COUNT,
  1307. MSR_PLATFORM_INFO,
  1308. MSR_MISC_FEATURES_ENABLES,
  1309. MSR_AMD64_VIRT_SPEC_CTRL,
  1310. MSR_AMD64_TSC_RATIO,
  1311. MSR_IA32_POWER_CTL,
  1312. MSR_IA32_UCODE_REV,
  1313. /*
  1314. * The following list leaves out MSRs whose values are determined
  1315. * by arch/x86/kvm/vmx/nested.c based on CPUID or other MSRs.
  1316. * We always support the "true" VMX control MSRs, even if the host
  1317. * processor does not, so I am putting these registers here rather
  1318. * than in msrs_to_save_all.
  1319. */
  1320. MSR_IA32_VMX_BASIC,
  1321. MSR_IA32_VMX_TRUE_PINBASED_CTLS,
  1322. MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
  1323. MSR_IA32_VMX_TRUE_EXIT_CTLS,
  1324. MSR_IA32_VMX_TRUE_ENTRY_CTLS,
  1325. MSR_IA32_VMX_MISC,
  1326. MSR_IA32_VMX_CR0_FIXED0,
  1327. MSR_IA32_VMX_CR4_FIXED0,
  1328. MSR_IA32_VMX_VMCS_ENUM,
  1329. MSR_IA32_VMX_PROCBASED_CTLS2,
  1330. MSR_IA32_VMX_EPT_VPID_CAP,
  1331. MSR_IA32_VMX_VMFUNC,
  1332. MSR_K7_HWCR,
  1333. MSR_KVM_POLL_CONTROL,
  1334. };
  1335. static u32 emulated_msrs[ARRAY_SIZE(emulated_msrs_all)];
  1336. static unsigned num_emulated_msrs;
  1337. /*
  1338. * List of msr numbers which are used to expose MSR-based features that
  1339. * can be used by a hypervisor to validate requested CPU features.
  1340. */
  1341. static const u32 msr_based_features_all[] = {
  1342. MSR_IA32_VMX_BASIC,
  1343. MSR_IA32_VMX_TRUE_PINBASED_CTLS,
  1344. MSR_IA32_VMX_PINBASED_CTLS,
  1345. MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
  1346. MSR_IA32_VMX_PROCBASED_CTLS,
  1347. MSR_IA32_VMX_TRUE_EXIT_CTLS,
  1348. MSR_IA32_VMX_EXIT_CTLS,
  1349. MSR_IA32_VMX_TRUE_ENTRY_CTLS,
  1350. MSR_IA32_VMX_ENTRY_CTLS,
  1351. MSR_IA32_VMX_MISC,
  1352. MSR_IA32_VMX_CR0_FIXED0,
  1353. MSR_IA32_VMX_CR0_FIXED1,
  1354. MSR_IA32_VMX_CR4_FIXED0,
  1355. MSR_IA32_VMX_CR4_FIXED1,
  1356. MSR_IA32_VMX_VMCS_ENUM,
  1357. MSR_IA32_VMX_PROCBASED_CTLS2,
  1358. MSR_IA32_VMX_EPT_VPID_CAP,
  1359. MSR_IA32_VMX_VMFUNC,
  1360. MSR_AMD64_DE_CFG,
  1361. MSR_IA32_UCODE_REV,
  1362. MSR_IA32_ARCH_CAPABILITIES,
  1363. MSR_IA32_PERF_CAPABILITIES,
  1364. };
  1365. static u32 msr_based_features[ARRAY_SIZE(msr_based_features_all)];
  1366. static unsigned int num_msr_based_features;
  1367. /*
  1368. * Some IA32_ARCH_CAPABILITIES bits have dependencies on MSRs that KVM
  1369. * does not yet virtualize. These include:
  1370. * 10 - MISC_PACKAGE_CTRLS
  1371. * 11 - ENERGY_FILTERING_CTL
  1372. * 12 - DOITM
  1373. * 18 - FB_CLEAR_CTRL
  1374. * 21 - XAPIC_DISABLE_STATUS
  1375. * 23 - OVERCLOCKING_STATUS
  1376. */
  1377. #define KVM_SUPPORTED_ARCH_CAP \
  1378. (ARCH_CAP_RDCL_NO | ARCH_CAP_IBRS_ALL | ARCH_CAP_RSBA | \
  1379. ARCH_CAP_SKIP_VMENTRY_L1DFLUSH | ARCH_CAP_SSB_NO | ARCH_CAP_MDS_NO | \
  1380. ARCH_CAP_PSCHANGE_MC_NO | ARCH_CAP_TSX_CTRL_MSR | ARCH_CAP_TAA_NO | \
  1381. ARCH_CAP_SBDR_SSDP_NO | ARCH_CAP_FBSDP_NO | ARCH_CAP_PSDP_NO | \
  1382. ARCH_CAP_FB_CLEAR | ARCH_CAP_RRSBA | ARCH_CAP_PBRSB_NO | ARCH_CAP_GDS_NO)
  1383. static u64 kvm_get_arch_capabilities(void)
  1384. {
  1385. u64 data = 0;
  1386. if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES)) {
  1387. rdmsrl(MSR_IA32_ARCH_CAPABILITIES, data);
  1388. data &= KVM_SUPPORTED_ARCH_CAP;
  1389. }
  1390. /*
  1391. * If nx_huge_pages is enabled, KVM's shadow paging will ensure that
  1392. * the nested hypervisor runs with NX huge pages. If it is not,
  1393. * L1 is anyway vulnerable to ITLB_MULTIHIT exploits from other
  1394. * L1 guests, so it need not worry about its own (L2) guests.
  1395. */
  1396. data |= ARCH_CAP_PSCHANGE_MC_NO;
  1397. /*
  1398. * If we're doing cache flushes (either "always" or "cond")
  1399. * we will do one whenever the guest does a vmlaunch/vmresume.
  1400. * If an outer hypervisor is doing the cache flush for us
  1401. * (VMENTER_L1D_FLUSH_NESTED_VM), we can safely pass that
  1402. * capability to the guest too, and if EPT is disabled we're not
  1403. * vulnerable. Overall, only VMENTER_L1D_FLUSH_NEVER will
  1404. * require a nested hypervisor to do a flush of its own.
  1405. */
  1406. if (l1tf_vmx_mitigation != VMENTER_L1D_FLUSH_NEVER)
  1407. data |= ARCH_CAP_SKIP_VMENTRY_L1DFLUSH;
  1408. if (!boot_cpu_has_bug(X86_BUG_CPU_MELTDOWN))
  1409. data |= ARCH_CAP_RDCL_NO;
  1410. if (!boot_cpu_has_bug(X86_BUG_SPEC_STORE_BYPASS))
  1411. data |= ARCH_CAP_SSB_NO;
  1412. if (!boot_cpu_has_bug(X86_BUG_MDS))
  1413. data |= ARCH_CAP_MDS_NO;
  1414. if (!boot_cpu_has(X86_FEATURE_RTM)) {
  1415. /*
  1416. * If RTM=0 because the kernel has disabled TSX, the host might
  1417. * have TAA_NO or TSX_CTRL. Clear TAA_NO (the guest sees RTM=0
  1418. * and therefore knows that there cannot be TAA) but keep
  1419. * TSX_CTRL: some buggy userspaces leave it set on tsx=on hosts,
  1420. * and we want to allow migrating those guests to tsx=off hosts.
  1421. */
  1422. data &= ~ARCH_CAP_TAA_NO;
  1423. } else if (!boot_cpu_has_bug(X86_BUG_TAA)) {
  1424. data |= ARCH_CAP_TAA_NO;
  1425. } else {
  1426. /*
  1427. * Nothing to do here; we emulate TSX_CTRL if present on the
  1428. * host so the guest can choose between disabling TSX or
  1429. * using VERW to clear CPU buffers.
  1430. */
  1431. }
  1432. if (!boot_cpu_has_bug(X86_BUG_GDS) || gds_ucode_mitigated())
  1433. data |= ARCH_CAP_GDS_NO;
  1434. return data;
  1435. }
  1436. static int kvm_get_msr_feature(struct kvm_msr_entry *msr)
  1437. {
  1438. switch (msr->index) {
  1439. case MSR_IA32_ARCH_CAPABILITIES:
  1440. msr->data = kvm_get_arch_capabilities();
  1441. break;
  1442. case MSR_IA32_UCODE_REV:
  1443. rdmsrl_safe(msr->index, &msr->data);
  1444. break;
  1445. default:
  1446. return static_call(kvm_x86_get_msr_feature)(msr);
  1447. }
  1448. return 0;
  1449. }
  1450. static int do_get_msr_feature(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
  1451. {
  1452. struct kvm_msr_entry msr;
  1453. int r;
  1454. msr.index = index;
  1455. r = kvm_get_msr_feature(&msr);
  1456. if (r == KVM_MSR_RET_INVALID) {
  1457. /* Unconditionally clear the output for simplicity */
  1458. *data = 0;
  1459. if (kvm_msr_ignored_check(index, 0, false))
  1460. r = 0;
  1461. }
  1462. if (r)
  1463. return r;
  1464. *data = msr.data;
  1465. return 0;
  1466. }
  1467. static bool __kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
  1468. {
  1469. if (efer & EFER_FFXSR && !guest_cpuid_has(vcpu, X86_FEATURE_FXSR_OPT))
  1470. return false;
  1471. if (efer & EFER_SVME && !guest_cpuid_has(vcpu, X86_FEATURE_SVM))
  1472. return false;
  1473. if (efer & (EFER_LME | EFER_LMA) &&
  1474. !guest_cpuid_has(vcpu, X86_FEATURE_LM))
  1475. return false;
  1476. if (efer & EFER_NX && !guest_cpuid_has(vcpu, X86_FEATURE_NX))
  1477. return false;
  1478. return true;
  1479. }
  1480. bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
  1481. {
  1482. if (efer & efer_reserved_bits)
  1483. return false;
  1484. return __kvm_valid_efer(vcpu, efer);
  1485. }
  1486. EXPORT_SYMBOL_GPL(kvm_valid_efer);
  1487. static int set_efer(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
  1488. {
  1489. u64 old_efer = vcpu->arch.efer;
  1490. u64 efer = msr_info->data;
  1491. int r;
  1492. if (efer & efer_reserved_bits)
  1493. return 1;
  1494. if (!msr_info->host_initiated) {
  1495. if (!__kvm_valid_efer(vcpu, efer))
  1496. return 1;
  1497. if (is_paging(vcpu) &&
  1498. (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
  1499. return 1;
  1500. }
  1501. efer &= ~EFER_LMA;
  1502. efer |= vcpu->arch.efer & EFER_LMA;
  1503. r = static_call(kvm_x86_set_efer)(vcpu, efer);
  1504. if (r) {
  1505. WARN_ON(r > 0);
  1506. return r;
  1507. }
  1508. if ((efer ^ old_efer) & KVM_MMU_EFER_ROLE_BITS)
  1509. kvm_mmu_reset_context(vcpu);
  1510. return 0;
  1511. }
  1512. void kvm_enable_efer_bits(u64 mask)
  1513. {
  1514. efer_reserved_bits &= ~mask;
  1515. }
  1516. EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
  1517. bool kvm_msr_allowed(struct kvm_vcpu *vcpu, u32 index, u32 type)
  1518. {
  1519. struct kvm_x86_msr_filter *msr_filter;
  1520. struct msr_bitmap_range *ranges;
  1521. struct kvm *kvm = vcpu->kvm;
  1522. bool allowed;
  1523. int idx;
  1524. u32 i;
  1525. /* x2APIC MSRs do not support filtering. */
  1526. if (index >= 0x800 && index <= 0x8ff)
  1527. return true;
  1528. idx = srcu_read_lock(&kvm->srcu);
  1529. msr_filter = srcu_dereference(kvm->arch.msr_filter, &kvm->srcu);
  1530. if (!msr_filter) {
  1531. allowed = true;
  1532. goto out;
  1533. }
  1534. allowed = msr_filter->default_allow;
  1535. ranges = msr_filter->ranges;
  1536. for (i = 0; i < msr_filter->count; i++) {
  1537. u32 start = ranges[i].base;
  1538. u32 end = start + ranges[i].nmsrs;
  1539. u32 flags = ranges[i].flags;
  1540. unsigned long *bitmap = ranges[i].bitmap;
  1541. if ((index >= start) && (index < end) && (flags & type)) {
  1542. allowed = !!test_bit(index - start, bitmap);
  1543. break;
  1544. }
  1545. }
  1546. out:
  1547. srcu_read_unlock(&kvm->srcu, idx);
  1548. return allowed;
  1549. }
  1550. EXPORT_SYMBOL_GPL(kvm_msr_allowed);
  1551. /*
  1552. * Write @data into the MSR specified by @index. Select MSR specific fault
  1553. * checks are bypassed if @host_initiated is %true.
  1554. * Returns 0 on success, non-0 otherwise.
  1555. * Assumes vcpu_load() was already called.
  1556. */
  1557. static int __kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data,
  1558. bool host_initiated)
  1559. {
  1560. struct msr_data msr;
  1561. switch (index) {
  1562. case MSR_FS_BASE:
  1563. case MSR_GS_BASE:
  1564. case MSR_KERNEL_GS_BASE:
  1565. case MSR_CSTAR:
  1566. case MSR_LSTAR:
  1567. if (is_noncanonical_address(data, vcpu))
  1568. return 1;
  1569. break;
  1570. case MSR_IA32_SYSENTER_EIP:
  1571. case MSR_IA32_SYSENTER_ESP:
  1572. /*
  1573. * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
  1574. * non-canonical address is written on Intel but not on
  1575. * AMD (which ignores the top 32-bits, because it does
  1576. * not implement 64-bit SYSENTER).
  1577. *
  1578. * 64-bit code should hence be able to write a non-canonical
  1579. * value on AMD. Making the address canonical ensures that
  1580. * vmentry does not fail on Intel after writing a non-canonical
  1581. * value, and that something deterministic happens if the guest
  1582. * invokes 64-bit SYSENTER.
  1583. */
  1584. data = __canonical_address(data, vcpu_virt_addr_bits(vcpu));
  1585. break;
  1586. case MSR_TSC_AUX:
  1587. if (!kvm_is_supported_user_return_msr(MSR_TSC_AUX))
  1588. return 1;
  1589. if (!host_initiated &&
  1590. !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP) &&
  1591. !guest_cpuid_has(vcpu, X86_FEATURE_RDPID))
  1592. return 1;
  1593. /*
  1594. * Per Intel's SDM, bits 63:32 are reserved, but AMD's APM has
  1595. * incomplete and conflicting architectural behavior. Current
  1596. * AMD CPUs completely ignore bits 63:32, i.e. they aren't
  1597. * reserved and always read as zeros. Enforce Intel's reserved
  1598. * bits check if and only if the guest CPU is Intel, and clear
  1599. * the bits in all other cases. This ensures cross-vendor
  1600. * migration will provide consistent behavior for the guest.
  1601. */
  1602. if (guest_cpuid_is_intel(vcpu) && (data >> 32) != 0)
  1603. return 1;
  1604. data = (u32)data;
  1605. break;
  1606. }
  1607. msr.data = data;
  1608. msr.index = index;
  1609. msr.host_initiated = host_initiated;
  1610. return static_call(kvm_x86_set_msr)(vcpu, &msr);
  1611. }
  1612. static int kvm_set_msr_ignored_check(struct kvm_vcpu *vcpu,
  1613. u32 index, u64 data, bool host_initiated)
  1614. {
  1615. int ret = __kvm_set_msr(vcpu, index, data, host_initiated);
  1616. if (ret == KVM_MSR_RET_INVALID)
  1617. if (kvm_msr_ignored_check(index, data, true))
  1618. ret = 0;
  1619. return ret;
  1620. }
  1621. /*
  1622. * Read the MSR specified by @index into @data. Select MSR specific fault
  1623. * checks are bypassed if @host_initiated is %true.
  1624. * Returns 0 on success, non-0 otherwise.
  1625. * Assumes vcpu_load() was already called.
  1626. */
  1627. int __kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
  1628. bool host_initiated)
  1629. {
  1630. struct msr_data msr;
  1631. int ret;
  1632. switch (index) {
  1633. case MSR_TSC_AUX:
  1634. if (!kvm_is_supported_user_return_msr(MSR_TSC_AUX))
  1635. return 1;
  1636. if (!host_initiated &&
  1637. !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP) &&
  1638. !guest_cpuid_has(vcpu, X86_FEATURE_RDPID))
  1639. return 1;
  1640. break;
  1641. }
  1642. msr.index = index;
  1643. msr.host_initiated = host_initiated;
  1644. ret = static_call(kvm_x86_get_msr)(vcpu, &msr);
  1645. if (!ret)
  1646. *data = msr.data;
  1647. return ret;
  1648. }
  1649. static int kvm_get_msr_ignored_check(struct kvm_vcpu *vcpu,
  1650. u32 index, u64 *data, bool host_initiated)
  1651. {
  1652. int ret = __kvm_get_msr(vcpu, index, data, host_initiated);
  1653. if (ret == KVM_MSR_RET_INVALID) {
  1654. /* Unconditionally clear *data for simplicity */
  1655. *data = 0;
  1656. if (kvm_msr_ignored_check(index, 0, false))
  1657. ret = 0;
  1658. }
  1659. return ret;
  1660. }
  1661. static int kvm_get_msr_with_filter(struct kvm_vcpu *vcpu, u32 index, u64 *data)
  1662. {
  1663. if (!kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_READ))
  1664. return KVM_MSR_RET_FILTERED;
  1665. return kvm_get_msr_ignored_check(vcpu, index, data, false);
  1666. }
  1667. static int kvm_set_msr_with_filter(struct kvm_vcpu *vcpu, u32 index, u64 data)
  1668. {
  1669. if (!kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_WRITE))
  1670. return KVM_MSR_RET_FILTERED;
  1671. return kvm_set_msr_ignored_check(vcpu, index, data, false);
  1672. }
  1673. int kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data)
  1674. {
  1675. return kvm_get_msr_ignored_check(vcpu, index, data, false);
  1676. }
  1677. EXPORT_SYMBOL_GPL(kvm_get_msr);
  1678. int kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data)
  1679. {
  1680. return kvm_set_msr_ignored_check(vcpu, index, data, false);
  1681. }
  1682. EXPORT_SYMBOL_GPL(kvm_set_msr);
  1683. static void complete_userspace_rdmsr(struct kvm_vcpu *vcpu)
  1684. {
  1685. if (!vcpu->run->msr.error) {
  1686. kvm_rax_write(vcpu, (u32)vcpu->run->msr.data);
  1687. kvm_rdx_write(vcpu, vcpu->run->msr.data >> 32);
  1688. }
  1689. }
  1690. static int complete_emulated_msr_access(struct kvm_vcpu *vcpu)
  1691. {
  1692. return complete_emulated_insn_gp(vcpu, vcpu->run->msr.error);
  1693. }
  1694. static int complete_emulated_rdmsr(struct kvm_vcpu *vcpu)
  1695. {
  1696. complete_userspace_rdmsr(vcpu);
  1697. return complete_emulated_msr_access(vcpu);
  1698. }
  1699. static int complete_fast_msr_access(struct kvm_vcpu *vcpu)
  1700. {
  1701. return static_call(kvm_x86_complete_emulated_msr)(vcpu, vcpu->run->msr.error);
  1702. }
  1703. static int complete_fast_rdmsr(struct kvm_vcpu *vcpu)
  1704. {
  1705. complete_userspace_rdmsr(vcpu);
  1706. return complete_fast_msr_access(vcpu);
  1707. }
  1708. static u64 kvm_msr_reason(int r)
  1709. {
  1710. switch (r) {
  1711. case KVM_MSR_RET_INVALID:
  1712. return KVM_MSR_EXIT_REASON_UNKNOWN;
  1713. case KVM_MSR_RET_FILTERED:
  1714. return KVM_MSR_EXIT_REASON_FILTER;
  1715. default:
  1716. return KVM_MSR_EXIT_REASON_INVAL;
  1717. }
  1718. }
  1719. static int kvm_msr_user_space(struct kvm_vcpu *vcpu, u32 index,
  1720. u32 exit_reason, u64 data,
  1721. int (*completion)(struct kvm_vcpu *vcpu),
  1722. int r)
  1723. {
  1724. u64 msr_reason = kvm_msr_reason(r);
  1725. /* Check if the user wanted to know about this MSR fault */
  1726. if (!(vcpu->kvm->arch.user_space_msr_mask & msr_reason))
  1727. return 0;
  1728. vcpu->run->exit_reason = exit_reason;
  1729. vcpu->run->msr.error = 0;
  1730. memset(vcpu->run->msr.pad, 0, sizeof(vcpu->run->msr.pad));
  1731. vcpu->run->msr.reason = msr_reason;
  1732. vcpu->run->msr.index = index;
  1733. vcpu->run->msr.data = data;
  1734. vcpu->arch.complete_userspace_io = completion;
  1735. return 1;
  1736. }
  1737. int kvm_emulate_rdmsr(struct kvm_vcpu *vcpu)
  1738. {
  1739. u32 ecx = kvm_rcx_read(vcpu);
  1740. u64 data;
  1741. int r;
  1742. r = kvm_get_msr_with_filter(vcpu, ecx, &data);
  1743. if (!r) {
  1744. trace_kvm_msr_read(ecx, data);
  1745. kvm_rax_write(vcpu, data & -1u);
  1746. kvm_rdx_write(vcpu, (data >> 32) & -1u);
  1747. } else {
  1748. /* MSR read failed? See if we should ask user space */
  1749. if (kvm_msr_user_space(vcpu, ecx, KVM_EXIT_X86_RDMSR, 0,
  1750. complete_fast_rdmsr, r))
  1751. return 0;
  1752. trace_kvm_msr_read_ex(ecx);
  1753. }
  1754. return static_call(kvm_x86_complete_emulated_msr)(vcpu, r);
  1755. }
  1756. EXPORT_SYMBOL_GPL(kvm_emulate_rdmsr);
  1757. int kvm_emulate_wrmsr(struct kvm_vcpu *vcpu)
  1758. {
  1759. u32 ecx = kvm_rcx_read(vcpu);
  1760. u64 data = kvm_read_edx_eax(vcpu);
  1761. int r;
  1762. r = kvm_set_msr_with_filter(vcpu, ecx, data);
  1763. if (!r) {
  1764. trace_kvm_msr_write(ecx, data);
  1765. } else {
  1766. /* MSR write failed? See if we should ask user space */
  1767. if (kvm_msr_user_space(vcpu, ecx, KVM_EXIT_X86_WRMSR, data,
  1768. complete_fast_msr_access, r))
  1769. return 0;
  1770. /* Signal all other negative errors to userspace */
  1771. if (r < 0)
  1772. return r;
  1773. trace_kvm_msr_write_ex(ecx, data);
  1774. }
  1775. return static_call(kvm_x86_complete_emulated_msr)(vcpu, r);
  1776. }
  1777. EXPORT_SYMBOL_GPL(kvm_emulate_wrmsr);
  1778. int kvm_emulate_as_nop(struct kvm_vcpu *vcpu)
  1779. {
  1780. return kvm_skip_emulated_instruction(vcpu);
  1781. }
  1782. EXPORT_SYMBOL_GPL(kvm_emulate_as_nop);
  1783. int kvm_emulate_invd(struct kvm_vcpu *vcpu)
  1784. {
  1785. /* Treat an INVD instruction as a NOP and just skip it. */
  1786. return kvm_emulate_as_nop(vcpu);
  1787. }
  1788. EXPORT_SYMBOL_GPL(kvm_emulate_invd);
  1789. int kvm_handle_invalid_op(struct kvm_vcpu *vcpu)
  1790. {
  1791. kvm_queue_exception(vcpu, UD_VECTOR);
  1792. return 1;
  1793. }
  1794. EXPORT_SYMBOL_GPL(kvm_handle_invalid_op);
  1795. static int kvm_emulate_monitor_mwait(struct kvm_vcpu *vcpu, const char *insn)
  1796. {
  1797. if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MWAIT_NEVER_UD_FAULTS) &&
  1798. !guest_cpuid_has(vcpu, X86_FEATURE_MWAIT))
  1799. return kvm_handle_invalid_op(vcpu);
  1800. pr_warn_once("kvm: %s instruction emulated as NOP!\n", insn);
  1801. return kvm_emulate_as_nop(vcpu);
  1802. }
  1803. int kvm_emulate_mwait(struct kvm_vcpu *vcpu)
  1804. {
  1805. return kvm_emulate_monitor_mwait(vcpu, "MWAIT");
  1806. }
  1807. EXPORT_SYMBOL_GPL(kvm_emulate_mwait);
  1808. int kvm_emulate_monitor(struct kvm_vcpu *vcpu)
  1809. {
  1810. return kvm_emulate_monitor_mwait(vcpu, "MONITOR");
  1811. }
  1812. EXPORT_SYMBOL_GPL(kvm_emulate_monitor);
  1813. static inline bool kvm_vcpu_exit_request(struct kvm_vcpu *vcpu)
  1814. {
  1815. xfer_to_guest_mode_prepare();
  1816. return vcpu->mode == EXITING_GUEST_MODE || kvm_request_pending(vcpu) ||
  1817. xfer_to_guest_mode_work_pending();
  1818. }
  1819. /*
  1820. * The fast path for frequent and performance sensitive wrmsr emulation,
  1821. * i.e. the sending of IPI, sending IPI early in the VM-Exit flow reduces
  1822. * the latency of virtual IPI by avoiding the expensive bits of transitioning
  1823. * from guest to host, e.g. reacquiring KVM's SRCU lock. In contrast to the
  1824. * other cases which must be called after interrupts are enabled on the host.
  1825. */
  1826. static int handle_fastpath_set_x2apic_icr_irqoff(struct kvm_vcpu *vcpu, u64 data)
  1827. {
  1828. if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(vcpu->arch.apic))
  1829. return 1;
  1830. if (((data & APIC_SHORT_MASK) == APIC_DEST_NOSHORT) &&
  1831. ((data & APIC_DEST_MASK) == APIC_DEST_PHYSICAL) &&
  1832. ((data & APIC_MODE_MASK) == APIC_DM_FIXED) &&
  1833. ((u32)(data >> 32) != X2APIC_BROADCAST))
  1834. return kvm_x2apic_icr_write(vcpu->arch.apic, data);
  1835. return 1;
  1836. }
  1837. static int handle_fastpath_set_tscdeadline(struct kvm_vcpu *vcpu, u64 data)
  1838. {
  1839. if (!kvm_can_use_hv_timer(vcpu))
  1840. return 1;
  1841. kvm_set_lapic_tscdeadline_msr(vcpu, data);
  1842. return 0;
  1843. }
  1844. fastpath_t handle_fastpath_set_msr_irqoff(struct kvm_vcpu *vcpu)
  1845. {
  1846. u32 msr = kvm_rcx_read(vcpu);
  1847. u64 data;
  1848. fastpath_t ret = EXIT_FASTPATH_NONE;
  1849. switch (msr) {
  1850. case APIC_BASE_MSR + (APIC_ICR >> 4):
  1851. data = kvm_read_edx_eax(vcpu);
  1852. if (!handle_fastpath_set_x2apic_icr_irqoff(vcpu, data)) {
  1853. kvm_skip_emulated_instruction(vcpu);
  1854. ret = EXIT_FASTPATH_EXIT_HANDLED;
  1855. }
  1856. break;
  1857. case MSR_IA32_TSC_DEADLINE:
  1858. data = kvm_read_edx_eax(vcpu);
  1859. if (!handle_fastpath_set_tscdeadline(vcpu, data)) {
  1860. kvm_skip_emulated_instruction(vcpu);
  1861. ret = EXIT_FASTPATH_REENTER_GUEST;
  1862. }
  1863. break;
  1864. default:
  1865. break;
  1866. }
  1867. if (ret != EXIT_FASTPATH_NONE)
  1868. trace_kvm_msr_write(msr, data);
  1869. return ret;
  1870. }
  1871. EXPORT_SYMBOL_GPL(handle_fastpath_set_msr_irqoff);
  1872. /*
  1873. * Adapt set_msr() to msr_io()'s calling convention
  1874. */
  1875. static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
  1876. {
  1877. return kvm_get_msr_ignored_check(vcpu, index, data, true);
  1878. }
  1879. static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
  1880. {
  1881. return kvm_set_msr_ignored_check(vcpu, index, *data, true);
  1882. }
  1883. #ifdef CONFIG_X86_64
  1884. struct pvclock_clock {
  1885. int vclock_mode;
  1886. u64 cycle_last;
  1887. u64 mask;
  1888. u32 mult;
  1889. u32 shift;
  1890. u64 base_cycles;
  1891. u64 offset;
  1892. };
  1893. struct pvclock_gtod_data {
  1894. seqcount_t seq;
  1895. struct pvclock_clock clock; /* extract of a clocksource struct */
  1896. struct pvclock_clock raw_clock; /* extract of a clocksource struct */
  1897. ktime_t offs_boot;
  1898. u64 wall_time_sec;
  1899. };
  1900. static struct pvclock_gtod_data pvclock_gtod_data;
  1901. static void update_pvclock_gtod(struct timekeeper *tk)
  1902. {
  1903. struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
  1904. write_seqcount_begin(&vdata->seq);
  1905. /* copy pvclock gtod data */
  1906. vdata->clock.vclock_mode = tk->tkr_mono.clock->vdso_clock_mode;
  1907. vdata->clock.cycle_last = tk->tkr_mono.cycle_last;
  1908. vdata->clock.mask = tk->tkr_mono.mask;
  1909. vdata->clock.mult = tk->tkr_mono.mult;
  1910. vdata->clock.shift = tk->tkr_mono.shift;
  1911. vdata->clock.base_cycles = tk->tkr_mono.xtime_nsec;
  1912. vdata->clock.offset = tk->tkr_mono.base;
  1913. vdata->raw_clock.vclock_mode = tk->tkr_raw.clock->vdso_clock_mode;
  1914. vdata->raw_clock.cycle_last = tk->tkr_raw.cycle_last;
  1915. vdata->raw_clock.mask = tk->tkr_raw.mask;
  1916. vdata->raw_clock.mult = tk->tkr_raw.mult;
  1917. vdata->raw_clock.shift = tk->tkr_raw.shift;
  1918. vdata->raw_clock.base_cycles = tk->tkr_raw.xtime_nsec;
  1919. vdata->raw_clock.offset = tk->tkr_raw.base;
  1920. vdata->wall_time_sec = tk->xtime_sec;
  1921. vdata->offs_boot = tk->offs_boot;
  1922. write_seqcount_end(&vdata->seq);
  1923. }
  1924. static s64 get_kvmclock_base_ns(void)
  1925. {
  1926. /* Count up from boot time, but with the frequency of the raw clock. */
  1927. return ktime_to_ns(ktime_add(ktime_get_raw(), pvclock_gtod_data.offs_boot));
  1928. }
  1929. #else
  1930. static s64 get_kvmclock_base_ns(void)
  1931. {
  1932. /* Master clock not used, so we can just use CLOCK_BOOTTIME. */
  1933. return ktime_get_boottime_ns();
  1934. }
  1935. #endif
  1936. static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock, int sec_hi_ofs)
  1937. {
  1938. int version;
  1939. int r;
  1940. struct pvclock_wall_clock wc;
  1941. u32 wc_sec_hi;
  1942. u64 wall_nsec;
  1943. if (!wall_clock)
  1944. return;
  1945. r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
  1946. if (r)
  1947. return;
  1948. if (version & 1)
  1949. ++version; /* first time write, random junk */
  1950. ++version;
  1951. if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
  1952. return;
  1953. /*
  1954. * The guest calculates current wall clock time by adding
  1955. * system time (updated by kvm_guest_time_update below) to the
  1956. * wall clock specified here. We do the reverse here.
  1957. */
  1958. wall_nsec = ktime_get_real_ns() - get_kvmclock_ns(kvm);
  1959. wc.nsec = do_div(wall_nsec, 1000000000);
  1960. wc.sec = (u32)wall_nsec; /* overflow in 2106 guest time */
  1961. wc.version = version;
  1962. kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
  1963. if (sec_hi_ofs) {
  1964. wc_sec_hi = wall_nsec >> 32;
  1965. kvm_write_guest(kvm, wall_clock + sec_hi_ofs,
  1966. &wc_sec_hi, sizeof(wc_sec_hi));
  1967. }
  1968. version++;
  1969. kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
  1970. }
  1971. static void kvm_write_system_time(struct kvm_vcpu *vcpu, gpa_t system_time,
  1972. bool old_msr, bool host_initiated)
  1973. {
  1974. struct kvm_arch *ka = &vcpu->kvm->arch;
  1975. if (vcpu->vcpu_id == 0 && !host_initiated) {
  1976. if (ka->boot_vcpu_runs_old_kvmclock != old_msr)
  1977. kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
  1978. ka->boot_vcpu_runs_old_kvmclock = old_msr;
  1979. }
  1980. vcpu->arch.time = system_time;
  1981. kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
  1982. /* we verify if the enable bit is set... */
  1983. if (system_time & 1) {
  1984. kvm_gpc_activate(vcpu->kvm, &vcpu->arch.pv_time, vcpu,
  1985. KVM_HOST_USES_PFN, system_time & ~1ULL,
  1986. sizeof(struct pvclock_vcpu_time_info));
  1987. } else {
  1988. kvm_gpc_deactivate(vcpu->kvm, &vcpu->arch.pv_time);
  1989. }
  1990. return;
  1991. }
  1992. static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
  1993. {
  1994. do_shl32_div32(dividend, divisor);
  1995. return dividend;
  1996. }
  1997. static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
  1998. s8 *pshift, u32 *pmultiplier)
  1999. {
  2000. uint64_t scaled64;
  2001. int32_t shift = 0;
  2002. uint64_t tps64;
  2003. uint32_t tps32;
  2004. tps64 = base_hz;
  2005. scaled64 = scaled_hz;
  2006. while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
  2007. tps64 >>= 1;
  2008. shift--;
  2009. }
  2010. tps32 = (uint32_t)tps64;
  2011. while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
  2012. if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
  2013. scaled64 >>= 1;
  2014. else
  2015. tps32 <<= 1;
  2016. shift++;
  2017. }
  2018. *pshift = shift;
  2019. *pmultiplier = div_frac(scaled64, tps32);
  2020. }
  2021. #ifdef CONFIG_X86_64
  2022. static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
  2023. #endif
  2024. static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
  2025. static unsigned long max_tsc_khz;
  2026. static u32 adjust_tsc_khz(u32 khz, s32 ppm)
  2027. {
  2028. u64 v = (u64)khz * (1000000 + ppm);
  2029. do_div(v, 1000000);
  2030. return v;
  2031. }
  2032. static void kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 l1_multiplier);
  2033. static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
  2034. {
  2035. u64 ratio;
  2036. /* Guest TSC same frequency as host TSC? */
  2037. if (!scale) {
  2038. kvm_vcpu_write_tsc_multiplier(vcpu, kvm_caps.default_tsc_scaling_ratio);
  2039. return 0;
  2040. }
  2041. /* TSC scaling supported? */
  2042. if (!kvm_caps.has_tsc_control) {
  2043. if (user_tsc_khz > tsc_khz) {
  2044. vcpu->arch.tsc_catchup = 1;
  2045. vcpu->arch.tsc_always_catchup = 1;
  2046. return 0;
  2047. } else {
  2048. pr_warn_ratelimited("user requested TSC rate below hardware speed\n");
  2049. return -1;
  2050. }
  2051. }
  2052. /* TSC scaling required - calculate ratio */
  2053. ratio = mul_u64_u32_div(1ULL << kvm_caps.tsc_scaling_ratio_frac_bits,
  2054. user_tsc_khz, tsc_khz);
  2055. if (ratio == 0 || ratio >= kvm_caps.max_tsc_scaling_ratio) {
  2056. pr_warn_ratelimited("Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
  2057. user_tsc_khz);
  2058. return -1;
  2059. }
  2060. kvm_vcpu_write_tsc_multiplier(vcpu, ratio);
  2061. return 0;
  2062. }
  2063. static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
  2064. {
  2065. u32 thresh_lo, thresh_hi;
  2066. int use_scaling = 0;
  2067. /* tsc_khz can be zero if TSC calibration fails */
  2068. if (user_tsc_khz == 0) {
  2069. /* set tsc_scaling_ratio to a safe value */
  2070. kvm_vcpu_write_tsc_multiplier(vcpu, kvm_caps.default_tsc_scaling_ratio);
  2071. return -1;
  2072. }
  2073. /* Compute a scale to convert nanoseconds in TSC cycles */
  2074. kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
  2075. &vcpu->arch.virtual_tsc_shift,
  2076. &vcpu->arch.virtual_tsc_mult);
  2077. vcpu->arch.virtual_tsc_khz = user_tsc_khz;
  2078. /*
  2079. * Compute the variation in TSC rate which is acceptable
  2080. * within the range of tolerance and decide if the
  2081. * rate being applied is within that bounds of the hardware
  2082. * rate. If so, no scaling or compensation need be done.
  2083. */
  2084. thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
  2085. thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
  2086. if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
  2087. pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", user_tsc_khz, thresh_lo, thresh_hi);
  2088. use_scaling = 1;
  2089. }
  2090. return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
  2091. }
  2092. static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
  2093. {
  2094. u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
  2095. vcpu->arch.virtual_tsc_mult,
  2096. vcpu->arch.virtual_tsc_shift);
  2097. tsc += vcpu->arch.this_tsc_write;
  2098. return tsc;
  2099. }
  2100. #ifdef CONFIG_X86_64
  2101. static inline int gtod_is_based_on_tsc(int mode)
  2102. {
  2103. return mode == VDSO_CLOCKMODE_TSC || mode == VDSO_CLOCKMODE_HVCLOCK;
  2104. }
  2105. #endif
  2106. static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
  2107. {
  2108. #ifdef CONFIG_X86_64
  2109. bool vcpus_matched;
  2110. struct kvm_arch *ka = &vcpu->kvm->arch;
  2111. struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
  2112. vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
  2113. atomic_read(&vcpu->kvm->online_vcpus));
  2114. /*
  2115. * Once the masterclock is enabled, always perform request in
  2116. * order to update it.
  2117. *
  2118. * In order to enable masterclock, the host clocksource must be TSC
  2119. * and the vcpus need to have matched TSCs. When that happens,
  2120. * perform request to enable masterclock.
  2121. */
  2122. if (ka->use_master_clock ||
  2123. (gtod_is_based_on_tsc(gtod->clock.vclock_mode) && vcpus_matched))
  2124. kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
  2125. trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
  2126. atomic_read(&vcpu->kvm->online_vcpus),
  2127. ka->use_master_clock, gtod->clock.vclock_mode);
  2128. #endif
  2129. }
  2130. /*
  2131. * Multiply tsc by a fixed point number represented by ratio.
  2132. *
  2133. * The most significant 64-N bits (mult) of ratio represent the
  2134. * integral part of the fixed point number; the remaining N bits
  2135. * (frac) represent the fractional part, ie. ratio represents a fixed
  2136. * point number (mult + frac * 2^(-N)).
  2137. *
  2138. * N equals to kvm_caps.tsc_scaling_ratio_frac_bits.
  2139. */
  2140. static inline u64 __scale_tsc(u64 ratio, u64 tsc)
  2141. {
  2142. return mul_u64_u64_shr(tsc, ratio, kvm_caps.tsc_scaling_ratio_frac_bits);
  2143. }
  2144. u64 kvm_scale_tsc(u64 tsc, u64 ratio)
  2145. {
  2146. u64 _tsc = tsc;
  2147. if (ratio != kvm_caps.default_tsc_scaling_ratio)
  2148. _tsc = __scale_tsc(ratio, tsc);
  2149. return _tsc;
  2150. }
  2151. EXPORT_SYMBOL_GPL(kvm_scale_tsc);
  2152. static u64 kvm_compute_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
  2153. {
  2154. u64 tsc;
  2155. tsc = kvm_scale_tsc(rdtsc(), vcpu->arch.l1_tsc_scaling_ratio);
  2156. return target_tsc - tsc;
  2157. }
  2158. u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
  2159. {
  2160. return vcpu->arch.l1_tsc_offset +
  2161. kvm_scale_tsc(host_tsc, vcpu->arch.l1_tsc_scaling_ratio);
  2162. }
  2163. EXPORT_SYMBOL_GPL(kvm_read_l1_tsc);
  2164. u64 kvm_calc_nested_tsc_offset(u64 l1_offset, u64 l2_offset, u64 l2_multiplier)
  2165. {
  2166. u64 nested_offset;
  2167. if (l2_multiplier == kvm_caps.default_tsc_scaling_ratio)
  2168. nested_offset = l1_offset;
  2169. else
  2170. nested_offset = mul_s64_u64_shr((s64) l1_offset, l2_multiplier,
  2171. kvm_caps.tsc_scaling_ratio_frac_bits);
  2172. nested_offset += l2_offset;
  2173. return nested_offset;
  2174. }
  2175. EXPORT_SYMBOL_GPL(kvm_calc_nested_tsc_offset);
  2176. u64 kvm_calc_nested_tsc_multiplier(u64 l1_multiplier, u64 l2_multiplier)
  2177. {
  2178. if (l2_multiplier != kvm_caps.default_tsc_scaling_ratio)
  2179. return mul_u64_u64_shr(l1_multiplier, l2_multiplier,
  2180. kvm_caps.tsc_scaling_ratio_frac_bits);
  2181. return l1_multiplier;
  2182. }
  2183. EXPORT_SYMBOL_GPL(kvm_calc_nested_tsc_multiplier);
  2184. static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 l1_offset)
  2185. {
  2186. trace_kvm_write_tsc_offset(vcpu->vcpu_id,
  2187. vcpu->arch.l1_tsc_offset,
  2188. l1_offset);
  2189. vcpu->arch.l1_tsc_offset = l1_offset;
  2190. /*
  2191. * If we are here because L1 chose not to trap WRMSR to TSC then
  2192. * according to the spec this should set L1's TSC (as opposed to
  2193. * setting L1's offset for L2).
  2194. */
  2195. if (is_guest_mode(vcpu))
  2196. vcpu->arch.tsc_offset = kvm_calc_nested_tsc_offset(
  2197. l1_offset,
  2198. static_call(kvm_x86_get_l2_tsc_offset)(vcpu),
  2199. static_call(kvm_x86_get_l2_tsc_multiplier)(vcpu));
  2200. else
  2201. vcpu->arch.tsc_offset = l1_offset;
  2202. static_call(kvm_x86_write_tsc_offset)(vcpu, vcpu->arch.tsc_offset);
  2203. }
  2204. static void kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 l1_multiplier)
  2205. {
  2206. vcpu->arch.l1_tsc_scaling_ratio = l1_multiplier;
  2207. /* Userspace is changing the multiplier while L2 is active */
  2208. if (is_guest_mode(vcpu))
  2209. vcpu->arch.tsc_scaling_ratio = kvm_calc_nested_tsc_multiplier(
  2210. l1_multiplier,
  2211. static_call(kvm_x86_get_l2_tsc_multiplier)(vcpu));
  2212. else
  2213. vcpu->arch.tsc_scaling_ratio = l1_multiplier;
  2214. if (kvm_caps.has_tsc_control)
  2215. static_call(kvm_x86_write_tsc_multiplier)(
  2216. vcpu, vcpu->arch.tsc_scaling_ratio);
  2217. }
  2218. static inline bool kvm_check_tsc_unstable(void)
  2219. {
  2220. #ifdef CONFIG_X86_64
  2221. /*
  2222. * TSC is marked unstable when we're running on Hyper-V,
  2223. * 'TSC page' clocksource is good.
  2224. */
  2225. if (pvclock_gtod_data.clock.vclock_mode == VDSO_CLOCKMODE_HVCLOCK)
  2226. return false;
  2227. #endif
  2228. return check_tsc_unstable();
  2229. }
  2230. /*
  2231. * Infers attempts to synchronize the guest's tsc from host writes. Sets the
  2232. * offset for the vcpu and tracks the TSC matching generation that the vcpu
  2233. * participates in.
  2234. */
  2235. static void __kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 offset, u64 tsc,
  2236. u64 ns, bool matched)
  2237. {
  2238. struct kvm *kvm = vcpu->kvm;
  2239. lockdep_assert_held(&kvm->arch.tsc_write_lock);
  2240. /*
  2241. * We also track th most recent recorded KHZ, write and time to
  2242. * allow the matching interval to be extended at each write.
  2243. */
  2244. kvm->arch.last_tsc_nsec = ns;
  2245. kvm->arch.last_tsc_write = tsc;
  2246. kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
  2247. kvm->arch.last_tsc_offset = offset;
  2248. vcpu->arch.last_guest_tsc = tsc;
  2249. kvm_vcpu_write_tsc_offset(vcpu, offset);
  2250. if (!matched) {
  2251. /*
  2252. * We split periods of matched TSC writes into generations.
  2253. * For each generation, we track the original measured
  2254. * nanosecond time, offset, and write, so if TSCs are in
  2255. * sync, we can match exact offset, and if not, we can match
  2256. * exact software computation in compute_guest_tsc()
  2257. *
  2258. * These values are tracked in kvm->arch.cur_xxx variables.
  2259. */
  2260. kvm->arch.cur_tsc_generation++;
  2261. kvm->arch.cur_tsc_nsec = ns;
  2262. kvm->arch.cur_tsc_write = tsc;
  2263. kvm->arch.cur_tsc_offset = offset;
  2264. kvm->arch.nr_vcpus_matched_tsc = 0;
  2265. } else if (vcpu->arch.this_tsc_generation != kvm->arch.cur_tsc_generation) {
  2266. kvm->arch.nr_vcpus_matched_tsc++;
  2267. }
  2268. /* Keep track of which generation this VCPU has synchronized to */
  2269. vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
  2270. vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
  2271. vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
  2272. kvm_track_tsc_matching(vcpu);
  2273. }
  2274. static void kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 data)
  2275. {
  2276. struct kvm *kvm = vcpu->kvm;
  2277. u64 offset, ns, elapsed;
  2278. unsigned long flags;
  2279. bool matched = false;
  2280. bool synchronizing = false;
  2281. raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
  2282. offset = kvm_compute_l1_tsc_offset(vcpu, data);
  2283. ns = get_kvmclock_base_ns();
  2284. elapsed = ns - kvm->arch.last_tsc_nsec;
  2285. if (vcpu->arch.virtual_tsc_khz) {
  2286. if (data == 0) {
  2287. /*
  2288. * detection of vcpu initialization -- need to sync
  2289. * with other vCPUs. This particularly helps to keep
  2290. * kvm_clock stable after CPU hotplug
  2291. */
  2292. synchronizing = true;
  2293. } else {
  2294. u64 tsc_exp = kvm->arch.last_tsc_write +
  2295. nsec_to_cycles(vcpu, elapsed);
  2296. u64 tsc_hz = vcpu->arch.virtual_tsc_khz * 1000LL;
  2297. /*
  2298. * Special case: TSC write with a small delta (1 second)
  2299. * of virtual cycle time against real time is
  2300. * interpreted as an attempt to synchronize the CPU.
  2301. */
  2302. synchronizing = data < tsc_exp + tsc_hz &&
  2303. data + tsc_hz > tsc_exp;
  2304. }
  2305. }
  2306. /*
  2307. * For a reliable TSC, we can match TSC offsets, and for an unstable
  2308. * TSC, we add elapsed time in this computation. We could let the
  2309. * compensation code attempt to catch up if we fall behind, but
  2310. * it's better to try to match offsets from the beginning.
  2311. */
  2312. if (synchronizing &&
  2313. vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
  2314. if (!kvm_check_tsc_unstable()) {
  2315. offset = kvm->arch.cur_tsc_offset;
  2316. } else {
  2317. u64 delta = nsec_to_cycles(vcpu, elapsed);
  2318. data += delta;
  2319. offset = kvm_compute_l1_tsc_offset(vcpu, data);
  2320. }
  2321. matched = true;
  2322. }
  2323. __kvm_synchronize_tsc(vcpu, offset, data, ns, matched);
  2324. raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
  2325. }
  2326. static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
  2327. s64 adjustment)
  2328. {
  2329. u64 tsc_offset = vcpu->arch.l1_tsc_offset;
  2330. kvm_vcpu_write_tsc_offset(vcpu, tsc_offset + adjustment);
  2331. }
  2332. static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
  2333. {
  2334. if (vcpu->arch.l1_tsc_scaling_ratio != kvm_caps.default_tsc_scaling_ratio)
  2335. WARN_ON(adjustment < 0);
  2336. adjustment = kvm_scale_tsc((u64) adjustment,
  2337. vcpu->arch.l1_tsc_scaling_ratio);
  2338. adjust_tsc_offset_guest(vcpu, adjustment);
  2339. }
  2340. #ifdef CONFIG_X86_64
  2341. static u64 read_tsc(void)
  2342. {
  2343. u64 ret = (u64)rdtsc_ordered();
  2344. u64 last = pvclock_gtod_data.clock.cycle_last;
  2345. if (likely(ret >= last))
  2346. return ret;
  2347. /*
  2348. * GCC likes to generate cmov here, but this branch is extremely
  2349. * predictable (it's just a function of time and the likely is
  2350. * very likely) and there's a data dependence, so force GCC
  2351. * to generate a branch instead. I don't barrier() because
  2352. * we don't actually need a barrier, and if this function
  2353. * ever gets inlined it will generate worse code.
  2354. */
  2355. asm volatile ("");
  2356. return last;
  2357. }
  2358. static inline u64 vgettsc(struct pvclock_clock *clock, u64 *tsc_timestamp,
  2359. int *mode)
  2360. {
  2361. long v;
  2362. u64 tsc_pg_val;
  2363. switch (clock->vclock_mode) {
  2364. case VDSO_CLOCKMODE_HVCLOCK:
  2365. tsc_pg_val = hv_read_tsc_page_tsc(hv_get_tsc_page(),
  2366. tsc_timestamp);
  2367. if (tsc_pg_val != U64_MAX) {
  2368. /* TSC page valid */
  2369. *mode = VDSO_CLOCKMODE_HVCLOCK;
  2370. v = (tsc_pg_val - clock->cycle_last) &
  2371. clock->mask;
  2372. } else {
  2373. /* TSC page invalid */
  2374. *mode = VDSO_CLOCKMODE_NONE;
  2375. }
  2376. break;
  2377. case VDSO_CLOCKMODE_TSC:
  2378. *mode = VDSO_CLOCKMODE_TSC;
  2379. *tsc_timestamp = read_tsc();
  2380. v = (*tsc_timestamp - clock->cycle_last) &
  2381. clock->mask;
  2382. break;
  2383. default:
  2384. *mode = VDSO_CLOCKMODE_NONE;
  2385. }
  2386. if (*mode == VDSO_CLOCKMODE_NONE)
  2387. *tsc_timestamp = v = 0;
  2388. return v * clock->mult;
  2389. }
  2390. static int do_monotonic_raw(s64 *t, u64 *tsc_timestamp)
  2391. {
  2392. struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
  2393. unsigned long seq;
  2394. int mode;
  2395. u64 ns;
  2396. do {
  2397. seq = read_seqcount_begin(&gtod->seq);
  2398. ns = gtod->raw_clock.base_cycles;
  2399. ns += vgettsc(&gtod->raw_clock, tsc_timestamp, &mode);
  2400. ns >>= gtod->raw_clock.shift;
  2401. ns += ktime_to_ns(ktime_add(gtod->raw_clock.offset, gtod->offs_boot));
  2402. } while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
  2403. *t = ns;
  2404. return mode;
  2405. }
  2406. static int do_realtime(struct timespec64 *ts, u64 *tsc_timestamp)
  2407. {
  2408. struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
  2409. unsigned long seq;
  2410. int mode;
  2411. u64 ns;
  2412. do {
  2413. seq = read_seqcount_begin(&gtod->seq);
  2414. ts->tv_sec = gtod->wall_time_sec;
  2415. ns = gtod->clock.base_cycles;
  2416. ns += vgettsc(&gtod->clock, tsc_timestamp, &mode);
  2417. ns >>= gtod->clock.shift;
  2418. } while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
  2419. ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns);
  2420. ts->tv_nsec = ns;
  2421. return mode;
  2422. }
  2423. /* returns true if host is using TSC based clocksource */
  2424. static bool kvm_get_time_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
  2425. {
  2426. /* checked again under seqlock below */
  2427. if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
  2428. return false;
  2429. return gtod_is_based_on_tsc(do_monotonic_raw(kernel_ns,
  2430. tsc_timestamp));
  2431. }
  2432. /* returns true if host is using TSC based clocksource */
  2433. static bool kvm_get_walltime_and_clockread(struct timespec64 *ts,
  2434. u64 *tsc_timestamp)
  2435. {
  2436. /* checked again under seqlock below */
  2437. if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
  2438. return false;
  2439. return gtod_is_based_on_tsc(do_realtime(ts, tsc_timestamp));
  2440. }
  2441. #endif
  2442. /*
  2443. *
  2444. * Assuming a stable TSC across physical CPUS, and a stable TSC
  2445. * across virtual CPUs, the following condition is possible.
  2446. * Each numbered line represents an event visible to both
  2447. * CPUs at the next numbered event.
  2448. *
  2449. * "timespecX" represents host monotonic time. "tscX" represents
  2450. * RDTSC value.
  2451. *
  2452. * VCPU0 on CPU0 | VCPU1 on CPU1
  2453. *
  2454. * 1. read timespec0,tsc0
  2455. * 2. | timespec1 = timespec0 + N
  2456. * | tsc1 = tsc0 + M
  2457. * 3. transition to guest | transition to guest
  2458. * 4. ret0 = timespec0 + (rdtsc - tsc0) |
  2459. * 5. | ret1 = timespec1 + (rdtsc - tsc1)
  2460. * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
  2461. *
  2462. * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
  2463. *
  2464. * - ret0 < ret1
  2465. * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
  2466. * ...
  2467. * - 0 < N - M => M < N
  2468. *
  2469. * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
  2470. * always the case (the difference between two distinct xtime instances
  2471. * might be smaller then the difference between corresponding TSC reads,
  2472. * when updating guest vcpus pvclock areas).
  2473. *
  2474. * To avoid that problem, do not allow visibility of distinct
  2475. * system_timestamp/tsc_timestamp values simultaneously: use a master
  2476. * copy of host monotonic time values. Update that master copy
  2477. * in lockstep.
  2478. *
  2479. * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
  2480. *
  2481. */
  2482. static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
  2483. {
  2484. #ifdef CONFIG_X86_64
  2485. struct kvm_arch *ka = &kvm->arch;
  2486. int vclock_mode;
  2487. bool host_tsc_clocksource, vcpus_matched;
  2488. lockdep_assert_held(&kvm->arch.tsc_write_lock);
  2489. vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
  2490. atomic_read(&kvm->online_vcpus));
  2491. /*
  2492. * If the host uses TSC clock, then passthrough TSC as stable
  2493. * to the guest.
  2494. */
  2495. host_tsc_clocksource = kvm_get_time_and_clockread(
  2496. &ka->master_kernel_ns,
  2497. &ka->master_cycle_now);
  2498. ka->use_master_clock = host_tsc_clocksource && vcpus_matched
  2499. && !ka->backwards_tsc_observed
  2500. && !ka->boot_vcpu_runs_old_kvmclock;
  2501. if (ka->use_master_clock)
  2502. atomic_set(&kvm_guest_has_master_clock, 1);
  2503. vclock_mode = pvclock_gtod_data.clock.vclock_mode;
  2504. trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
  2505. vcpus_matched);
  2506. #endif
  2507. }
  2508. static void kvm_make_mclock_inprogress_request(struct kvm *kvm)
  2509. {
  2510. kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
  2511. }
  2512. static void __kvm_start_pvclock_update(struct kvm *kvm)
  2513. {
  2514. raw_spin_lock_irq(&kvm->arch.tsc_write_lock);
  2515. write_seqcount_begin(&kvm->arch.pvclock_sc);
  2516. }
  2517. static void kvm_start_pvclock_update(struct kvm *kvm)
  2518. {
  2519. kvm_make_mclock_inprogress_request(kvm);
  2520. /* no guest entries from this point */
  2521. __kvm_start_pvclock_update(kvm);
  2522. }
  2523. static void kvm_end_pvclock_update(struct kvm *kvm)
  2524. {
  2525. struct kvm_arch *ka = &kvm->arch;
  2526. struct kvm_vcpu *vcpu;
  2527. unsigned long i;
  2528. write_seqcount_end(&ka->pvclock_sc);
  2529. raw_spin_unlock_irq(&ka->tsc_write_lock);
  2530. kvm_for_each_vcpu(i, vcpu, kvm)
  2531. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  2532. /* guest entries allowed */
  2533. kvm_for_each_vcpu(i, vcpu, kvm)
  2534. kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
  2535. }
  2536. static void kvm_update_masterclock(struct kvm *kvm)
  2537. {
  2538. kvm_hv_request_tsc_page_update(kvm);
  2539. kvm_start_pvclock_update(kvm);
  2540. pvclock_update_vm_gtod_copy(kvm);
  2541. kvm_end_pvclock_update(kvm);
  2542. }
  2543. /* Called within read_seqcount_begin/retry for kvm->pvclock_sc. */
  2544. static void __get_kvmclock(struct kvm *kvm, struct kvm_clock_data *data)
  2545. {
  2546. struct kvm_arch *ka = &kvm->arch;
  2547. struct pvclock_vcpu_time_info hv_clock;
  2548. /* both __this_cpu_read() and rdtsc() should be on the same cpu */
  2549. get_cpu();
  2550. data->flags = 0;
  2551. if (ka->use_master_clock && __this_cpu_read(cpu_tsc_khz)) {
  2552. #ifdef CONFIG_X86_64
  2553. struct timespec64 ts;
  2554. if (kvm_get_walltime_and_clockread(&ts, &data->host_tsc)) {
  2555. data->realtime = ts.tv_nsec + NSEC_PER_SEC * ts.tv_sec;
  2556. data->flags |= KVM_CLOCK_REALTIME | KVM_CLOCK_HOST_TSC;
  2557. } else
  2558. #endif
  2559. data->host_tsc = rdtsc();
  2560. data->flags |= KVM_CLOCK_TSC_STABLE;
  2561. hv_clock.tsc_timestamp = ka->master_cycle_now;
  2562. hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
  2563. kvm_get_time_scale(NSEC_PER_SEC, __this_cpu_read(cpu_tsc_khz) * 1000LL,
  2564. &hv_clock.tsc_shift,
  2565. &hv_clock.tsc_to_system_mul);
  2566. data->clock = __pvclock_read_cycles(&hv_clock, data->host_tsc);
  2567. } else {
  2568. data->clock = get_kvmclock_base_ns() + ka->kvmclock_offset;
  2569. }
  2570. put_cpu();
  2571. }
  2572. static void get_kvmclock(struct kvm *kvm, struct kvm_clock_data *data)
  2573. {
  2574. struct kvm_arch *ka = &kvm->arch;
  2575. unsigned seq;
  2576. do {
  2577. seq = read_seqcount_begin(&ka->pvclock_sc);
  2578. __get_kvmclock(kvm, data);
  2579. } while (read_seqcount_retry(&ka->pvclock_sc, seq));
  2580. }
  2581. u64 get_kvmclock_ns(struct kvm *kvm)
  2582. {
  2583. struct kvm_clock_data data;
  2584. get_kvmclock(kvm, &data);
  2585. return data.clock;
  2586. }
  2587. static void kvm_setup_guest_pvclock(struct kvm_vcpu *v,
  2588. struct gfn_to_pfn_cache *gpc,
  2589. unsigned int offset)
  2590. {
  2591. struct kvm_vcpu_arch *vcpu = &v->arch;
  2592. struct pvclock_vcpu_time_info *guest_hv_clock;
  2593. unsigned long flags;
  2594. read_lock_irqsave(&gpc->lock, flags);
  2595. while (!kvm_gfn_to_pfn_cache_check(v->kvm, gpc, gpc->gpa,
  2596. offset + sizeof(*guest_hv_clock))) {
  2597. read_unlock_irqrestore(&gpc->lock, flags);
  2598. if (kvm_gfn_to_pfn_cache_refresh(v->kvm, gpc, gpc->gpa,
  2599. offset + sizeof(*guest_hv_clock)))
  2600. return;
  2601. read_lock_irqsave(&gpc->lock, flags);
  2602. }
  2603. guest_hv_clock = (void *)(gpc->khva + offset);
  2604. /*
  2605. * This VCPU is paused, but it's legal for a guest to read another
  2606. * VCPU's kvmclock, so we really have to follow the specification where
  2607. * it says that version is odd if data is being modified, and even after
  2608. * it is consistent.
  2609. */
  2610. guest_hv_clock->version = vcpu->hv_clock.version = (guest_hv_clock->version + 1) | 1;
  2611. smp_wmb();
  2612. /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
  2613. vcpu->hv_clock.flags |= (guest_hv_clock->flags & PVCLOCK_GUEST_STOPPED);
  2614. if (vcpu->pvclock_set_guest_stopped_request) {
  2615. vcpu->hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
  2616. vcpu->pvclock_set_guest_stopped_request = false;
  2617. }
  2618. memcpy(guest_hv_clock, &vcpu->hv_clock, sizeof(*guest_hv_clock));
  2619. smp_wmb();
  2620. guest_hv_clock->version = ++vcpu->hv_clock.version;
  2621. mark_page_dirty_in_slot(v->kvm, gpc->memslot, gpc->gpa >> PAGE_SHIFT);
  2622. read_unlock_irqrestore(&gpc->lock, flags);
  2623. trace_kvm_pvclock_update(v->vcpu_id, &vcpu->hv_clock);
  2624. }
  2625. static int kvm_guest_time_update(struct kvm_vcpu *v)
  2626. {
  2627. unsigned long flags, tgt_tsc_khz;
  2628. unsigned seq;
  2629. struct kvm_vcpu_arch *vcpu = &v->arch;
  2630. struct kvm_arch *ka = &v->kvm->arch;
  2631. s64 kernel_ns;
  2632. u64 tsc_timestamp, host_tsc;
  2633. u8 pvclock_flags;
  2634. bool use_master_clock;
  2635. kernel_ns = 0;
  2636. host_tsc = 0;
  2637. /*
  2638. * If the host uses TSC clock, then passthrough TSC as stable
  2639. * to the guest.
  2640. */
  2641. do {
  2642. seq = read_seqcount_begin(&ka->pvclock_sc);
  2643. use_master_clock = ka->use_master_clock;
  2644. if (use_master_clock) {
  2645. host_tsc = ka->master_cycle_now;
  2646. kernel_ns = ka->master_kernel_ns;
  2647. }
  2648. } while (read_seqcount_retry(&ka->pvclock_sc, seq));
  2649. /* Keep irq disabled to prevent changes to the clock */
  2650. local_irq_save(flags);
  2651. tgt_tsc_khz = __this_cpu_read(cpu_tsc_khz);
  2652. if (unlikely(tgt_tsc_khz == 0)) {
  2653. local_irq_restore(flags);
  2654. kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
  2655. return 1;
  2656. }
  2657. if (!use_master_clock) {
  2658. host_tsc = rdtsc();
  2659. kernel_ns = get_kvmclock_base_ns();
  2660. }
  2661. tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
  2662. /*
  2663. * We may have to catch up the TSC to match elapsed wall clock
  2664. * time for two reasons, even if kvmclock is used.
  2665. * 1) CPU could have been running below the maximum TSC rate
  2666. * 2) Broken TSC compensation resets the base at each VCPU
  2667. * entry to avoid unknown leaps of TSC even when running
  2668. * again on the same CPU. This may cause apparent elapsed
  2669. * time to disappear, and the guest to stand still or run
  2670. * very slowly.
  2671. */
  2672. if (vcpu->tsc_catchup) {
  2673. u64 tsc = compute_guest_tsc(v, kernel_ns);
  2674. if (tsc > tsc_timestamp) {
  2675. adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
  2676. tsc_timestamp = tsc;
  2677. }
  2678. }
  2679. local_irq_restore(flags);
  2680. /* With all the info we got, fill in the values */
  2681. if (kvm_caps.has_tsc_control)
  2682. tgt_tsc_khz = kvm_scale_tsc(tgt_tsc_khz,
  2683. v->arch.l1_tsc_scaling_ratio);
  2684. if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
  2685. kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
  2686. &vcpu->hv_clock.tsc_shift,
  2687. &vcpu->hv_clock.tsc_to_system_mul);
  2688. vcpu->hw_tsc_khz = tgt_tsc_khz;
  2689. }
  2690. vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
  2691. vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
  2692. vcpu->last_guest_tsc = tsc_timestamp;
  2693. /* If the host uses TSC clocksource, then it is stable */
  2694. pvclock_flags = 0;
  2695. if (use_master_clock)
  2696. pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
  2697. vcpu->hv_clock.flags = pvclock_flags;
  2698. if (vcpu->pv_time.active)
  2699. kvm_setup_guest_pvclock(v, &vcpu->pv_time, 0);
  2700. if (vcpu->xen.vcpu_info_cache.active)
  2701. kvm_setup_guest_pvclock(v, &vcpu->xen.vcpu_info_cache,
  2702. offsetof(struct compat_vcpu_info, time));
  2703. if (vcpu->xen.vcpu_time_info_cache.active)
  2704. kvm_setup_guest_pvclock(v, &vcpu->xen.vcpu_time_info_cache, 0);
  2705. kvm_hv_setup_tsc_page(v->kvm, &vcpu->hv_clock);
  2706. return 0;
  2707. }
  2708. /*
  2709. * kvmclock updates which are isolated to a given vcpu, such as
  2710. * vcpu->cpu migration, should not allow system_timestamp from
  2711. * the rest of the vcpus to remain static. Otherwise ntp frequency
  2712. * correction applies to one vcpu's system_timestamp but not
  2713. * the others.
  2714. *
  2715. * So in those cases, request a kvmclock update for all vcpus.
  2716. * We need to rate-limit these requests though, as they can
  2717. * considerably slow guests that have a large number of vcpus.
  2718. * The time for a remote vcpu to update its kvmclock is bound
  2719. * by the delay we use to rate-limit the updates.
  2720. */
  2721. #define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
  2722. static void kvmclock_update_fn(struct work_struct *work)
  2723. {
  2724. unsigned long i;
  2725. struct delayed_work *dwork = to_delayed_work(work);
  2726. struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
  2727. kvmclock_update_work);
  2728. struct kvm *kvm = container_of(ka, struct kvm, arch);
  2729. struct kvm_vcpu *vcpu;
  2730. kvm_for_each_vcpu(i, vcpu, kvm) {
  2731. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  2732. kvm_vcpu_kick(vcpu);
  2733. }
  2734. }
  2735. static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
  2736. {
  2737. struct kvm *kvm = v->kvm;
  2738. kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
  2739. schedule_delayed_work(&kvm->arch.kvmclock_update_work,
  2740. KVMCLOCK_UPDATE_DELAY);
  2741. }
  2742. #define KVMCLOCK_SYNC_PERIOD (300 * HZ)
  2743. static void kvmclock_sync_fn(struct work_struct *work)
  2744. {
  2745. struct delayed_work *dwork = to_delayed_work(work);
  2746. struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
  2747. kvmclock_sync_work);
  2748. struct kvm *kvm = container_of(ka, struct kvm, arch);
  2749. if (!kvmclock_periodic_sync)
  2750. return;
  2751. schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
  2752. schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
  2753. KVMCLOCK_SYNC_PERIOD);
  2754. }
  2755. /* These helpers are safe iff @msr is known to be an MCx bank MSR. */
  2756. static bool is_mci_control_msr(u32 msr)
  2757. {
  2758. return (msr & 3) == 0;
  2759. }
  2760. static bool is_mci_status_msr(u32 msr)
  2761. {
  2762. return (msr & 3) == 1;
  2763. }
  2764. /*
  2765. * On AMD, HWCR[McStatusWrEn] controls whether setting MCi_STATUS results in #GP.
  2766. */
  2767. static bool can_set_mci_status(struct kvm_vcpu *vcpu)
  2768. {
  2769. /* McStatusWrEn enabled? */
  2770. if (guest_cpuid_is_amd_or_hygon(vcpu))
  2771. return !!(vcpu->arch.msr_hwcr & BIT_ULL(18));
  2772. return false;
  2773. }
  2774. static int set_msr_mce(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
  2775. {
  2776. u64 mcg_cap = vcpu->arch.mcg_cap;
  2777. unsigned bank_num = mcg_cap & 0xff;
  2778. u32 msr = msr_info->index;
  2779. u64 data = msr_info->data;
  2780. u32 offset, last_msr;
  2781. switch (msr) {
  2782. case MSR_IA32_MCG_STATUS:
  2783. vcpu->arch.mcg_status = data;
  2784. break;
  2785. case MSR_IA32_MCG_CTL:
  2786. if (!(mcg_cap & MCG_CTL_P) &&
  2787. (data || !msr_info->host_initiated))
  2788. return 1;
  2789. if (data != 0 && data != ~(u64)0)
  2790. return 1;
  2791. vcpu->arch.mcg_ctl = data;
  2792. break;
  2793. case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
  2794. last_msr = MSR_IA32_MCx_CTL2(bank_num) - 1;
  2795. if (msr > last_msr)
  2796. return 1;
  2797. if (!(mcg_cap & MCG_CMCI_P) && (data || !msr_info->host_initiated))
  2798. return 1;
  2799. /* An attempt to write a 1 to a reserved bit raises #GP */
  2800. if (data & ~(MCI_CTL2_CMCI_EN | MCI_CTL2_CMCI_THRESHOLD_MASK))
  2801. return 1;
  2802. offset = array_index_nospec(msr - MSR_IA32_MC0_CTL2,
  2803. last_msr + 1 - MSR_IA32_MC0_CTL2);
  2804. vcpu->arch.mci_ctl2_banks[offset] = data;
  2805. break;
  2806. case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
  2807. last_msr = MSR_IA32_MCx_CTL(bank_num) - 1;
  2808. if (msr > last_msr)
  2809. return 1;
  2810. /*
  2811. * Only 0 or all 1s can be written to IA32_MCi_CTL, all other
  2812. * values are architecturally undefined. But, some Linux
  2813. * kernels clear bit 10 in bank 4 to workaround a BIOS/GART TLB
  2814. * issue on AMD K8s, allow bit 10 to be clear when setting all
  2815. * other bits in order to avoid an uncaught #GP in the guest.
  2816. *
  2817. * UNIXWARE clears bit 0 of MC1_CTL to ignore correctable,
  2818. * single-bit ECC data errors.
  2819. */
  2820. if (is_mci_control_msr(msr) &&
  2821. data != 0 && (data | (1 << 10) | 1) != ~(u64)0)
  2822. return 1;
  2823. /*
  2824. * All CPUs allow writing 0 to MCi_STATUS MSRs to clear the MSR.
  2825. * AMD-based CPUs allow non-zero values, but if and only if
  2826. * HWCR[McStatusWrEn] is set.
  2827. */
  2828. if (!msr_info->host_initiated && is_mci_status_msr(msr) &&
  2829. data != 0 && !can_set_mci_status(vcpu))
  2830. return 1;
  2831. offset = array_index_nospec(msr - MSR_IA32_MC0_CTL,
  2832. last_msr + 1 - MSR_IA32_MC0_CTL);
  2833. vcpu->arch.mce_banks[offset] = data;
  2834. break;
  2835. default:
  2836. return 1;
  2837. }
  2838. return 0;
  2839. }
  2840. static inline bool kvm_pv_async_pf_enabled(struct kvm_vcpu *vcpu)
  2841. {
  2842. u64 mask = KVM_ASYNC_PF_ENABLED | KVM_ASYNC_PF_DELIVERY_AS_INT;
  2843. return (vcpu->arch.apf.msr_en_val & mask) == mask;
  2844. }
  2845. static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
  2846. {
  2847. gpa_t gpa = data & ~0x3f;
  2848. /* Bits 4:5 are reserved, Should be zero */
  2849. if (data & 0x30)
  2850. return 1;
  2851. if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_VMEXIT) &&
  2852. (data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT))
  2853. return 1;
  2854. if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT) &&
  2855. (data & KVM_ASYNC_PF_DELIVERY_AS_INT))
  2856. return 1;
  2857. if (!lapic_in_kernel(vcpu))
  2858. return data ? 1 : 0;
  2859. vcpu->arch.apf.msr_en_val = data;
  2860. if (!kvm_pv_async_pf_enabled(vcpu)) {
  2861. kvm_clear_async_pf_completion_queue(vcpu);
  2862. kvm_async_pf_hash_reset(vcpu);
  2863. return 0;
  2864. }
  2865. if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
  2866. sizeof(u64)))
  2867. return 1;
  2868. vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
  2869. vcpu->arch.apf.delivery_as_pf_vmexit = data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
  2870. kvm_async_pf_wakeup_all(vcpu);
  2871. return 0;
  2872. }
  2873. static int kvm_pv_enable_async_pf_int(struct kvm_vcpu *vcpu, u64 data)
  2874. {
  2875. /* Bits 8-63 are reserved */
  2876. if (data >> 8)
  2877. return 1;
  2878. if (!lapic_in_kernel(vcpu))
  2879. return 1;
  2880. vcpu->arch.apf.msr_int_val = data;
  2881. vcpu->arch.apf.vec = data & KVM_ASYNC_PF_VEC_MASK;
  2882. return 0;
  2883. }
  2884. static void kvmclock_reset(struct kvm_vcpu *vcpu)
  2885. {
  2886. kvm_gpc_deactivate(vcpu->kvm, &vcpu->arch.pv_time);
  2887. vcpu->arch.time = 0;
  2888. }
  2889. static void kvm_vcpu_flush_tlb_all(struct kvm_vcpu *vcpu)
  2890. {
  2891. ++vcpu->stat.tlb_flush;
  2892. static_call(kvm_x86_flush_tlb_all)(vcpu);
  2893. }
  2894. static void kvm_vcpu_flush_tlb_guest(struct kvm_vcpu *vcpu)
  2895. {
  2896. ++vcpu->stat.tlb_flush;
  2897. if (!tdp_enabled) {
  2898. /*
  2899. * A TLB flush on behalf of the guest is equivalent to
  2900. * INVPCID(all), toggling CR4.PGE, etc., which requires
  2901. * a forced sync of the shadow page tables. Ensure all the
  2902. * roots are synced and the guest TLB in hardware is clean.
  2903. */
  2904. kvm_mmu_sync_roots(vcpu);
  2905. kvm_mmu_sync_prev_roots(vcpu);
  2906. }
  2907. static_call(kvm_x86_flush_tlb_guest)(vcpu);
  2908. }
  2909. static inline void kvm_vcpu_flush_tlb_current(struct kvm_vcpu *vcpu)
  2910. {
  2911. ++vcpu->stat.tlb_flush;
  2912. static_call(kvm_x86_flush_tlb_current)(vcpu);
  2913. }
  2914. /*
  2915. * Service "local" TLB flush requests, which are specific to the current MMU
  2916. * context. In addition to the generic event handling in vcpu_enter_guest(),
  2917. * TLB flushes that are targeted at an MMU context also need to be serviced
  2918. * prior before nested VM-Enter/VM-Exit.
  2919. */
  2920. void kvm_service_local_tlb_flush_requests(struct kvm_vcpu *vcpu)
  2921. {
  2922. if (kvm_check_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu))
  2923. kvm_vcpu_flush_tlb_current(vcpu);
  2924. if (kvm_check_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu))
  2925. kvm_vcpu_flush_tlb_guest(vcpu);
  2926. }
  2927. EXPORT_SYMBOL_GPL(kvm_service_local_tlb_flush_requests);
  2928. static void record_steal_time(struct kvm_vcpu *vcpu)
  2929. {
  2930. struct gfn_to_hva_cache *ghc = &vcpu->arch.st.cache;
  2931. struct kvm_steal_time __user *st;
  2932. struct kvm_memslots *slots;
  2933. gpa_t gpa = vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS;
  2934. u64 steal;
  2935. u32 version;
  2936. if (kvm_xen_msr_enabled(vcpu->kvm)) {
  2937. kvm_xen_runstate_set_running(vcpu);
  2938. return;
  2939. }
  2940. if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
  2941. return;
  2942. if (WARN_ON_ONCE(current->mm != vcpu->kvm->mm))
  2943. return;
  2944. slots = kvm_memslots(vcpu->kvm);
  2945. if (unlikely(slots->generation != ghc->generation ||
  2946. gpa != ghc->gpa ||
  2947. kvm_is_error_hva(ghc->hva) || !ghc->memslot)) {
  2948. /* We rely on the fact that it fits in a single page. */
  2949. BUILD_BUG_ON((sizeof(*st) - 1) & KVM_STEAL_VALID_BITS);
  2950. if (kvm_gfn_to_hva_cache_init(vcpu->kvm, ghc, gpa, sizeof(*st)) ||
  2951. kvm_is_error_hva(ghc->hva) || !ghc->memslot)
  2952. return;
  2953. }
  2954. st = (struct kvm_steal_time __user *)ghc->hva;
  2955. /*
  2956. * Doing a TLB flush here, on the guest's behalf, can avoid
  2957. * expensive IPIs.
  2958. */
  2959. if (guest_pv_has(vcpu, KVM_FEATURE_PV_TLB_FLUSH)) {
  2960. u8 st_preempted = 0;
  2961. int err = -EFAULT;
  2962. if (!user_access_begin(st, sizeof(*st)))
  2963. return;
  2964. asm volatile("1: xchgb %0, %2\n"
  2965. "xor %1, %1\n"
  2966. "2:\n"
  2967. _ASM_EXTABLE_UA(1b, 2b)
  2968. : "+q" (st_preempted),
  2969. "+&r" (err),
  2970. "+m" (st->preempted));
  2971. if (err)
  2972. goto out;
  2973. user_access_end();
  2974. vcpu->arch.st.preempted = 0;
  2975. trace_kvm_pv_tlb_flush(vcpu->vcpu_id,
  2976. st_preempted & KVM_VCPU_FLUSH_TLB);
  2977. if (st_preempted & KVM_VCPU_FLUSH_TLB)
  2978. kvm_vcpu_flush_tlb_guest(vcpu);
  2979. if (!user_access_begin(st, sizeof(*st)))
  2980. goto dirty;
  2981. } else {
  2982. if (!user_access_begin(st, sizeof(*st)))
  2983. return;
  2984. unsafe_put_user(0, &st->preempted, out);
  2985. vcpu->arch.st.preempted = 0;
  2986. }
  2987. unsafe_get_user(version, &st->version, out);
  2988. if (version & 1)
  2989. version += 1; /* first time write, random junk */
  2990. version += 1;
  2991. unsafe_put_user(version, &st->version, out);
  2992. smp_wmb();
  2993. unsafe_get_user(steal, &st->steal, out);
  2994. steal += current->sched_info.run_delay -
  2995. vcpu->arch.st.last_steal;
  2996. vcpu->arch.st.last_steal = current->sched_info.run_delay;
  2997. unsafe_put_user(steal, &st->steal, out);
  2998. version += 1;
  2999. unsafe_put_user(version, &st->version, out);
  3000. out:
  3001. user_access_end();
  3002. dirty:
  3003. mark_page_dirty_in_slot(vcpu->kvm, ghc->memslot, gpa_to_gfn(ghc->gpa));
  3004. }
  3005. int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
  3006. {
  3007. bool pr = false;
  3008. u32 msr = msr_info->index;
  3009. u64 data = msr_info->data;
  3010. if (msr && msr == vcpu->kvm->arch.xen_hvm_config.msr)
  3011. return kvm_xen_write_hypercall_page(vcpu, data);
  3012. switch (msr) {
  3013. case MSR_AMD64_NB_CFG:
  3014. case MSR_IA32_UCODE_WRITE:
  3015. case MSR_VM_HSAVE_PA:
  3016. case MSR_AMD64_PATCH_LOADER:
  3017. case MSR_AMD64_BU_CFG2:
  3018. case MSR_AMD64_DC_CFG:
  3019. case MSR_AMD64_TW_CFG:
  3020. case MSR_F15H_EX_CFG:
  3021. break;
  3022. case MSR_IA32_UCODE_REV:
  3023. if (msr_info->host_initiated)
  3024. vcpu->arch.microcode_version = data;
  3025. break;
  3026. case MSR_IA32_ARCH_CAPABILITIES:
  3027. if (!msr_info->host_initiated)
  3028. return 1;
  3029. vcpu->arch.arch_capabilities = data;
  3030. break;
  3031. case MSR_IA32_PERF_CAPABILITIES: {
  3032. struct kvm_msr_entry msr_ent = {.index = msr, .data = 0};
  3033. if (!msr_info->host_initiated)
  3034. return 1;
  3035. if (kvm_get_msr_feature(&msr_ent))
  3036. return 1;
  3037. if (data & ~msr_ent.data)
  3038. return 1;
  3039. vcpu->arch.perf_capabilities = data;
  3040. kvm_pmu_refresh(vcpu);
  3041. return 0;
  3042. }
  3043. case MSR_EFER:
  3044. return set_efer(vcpu, msr_info);
  3045. case MSR_K7_HWCR:
  3046. data &= ~(u64)0x40; /* ignore flush filter disable */
  3047. data &= ~(u64)0x100; /* ignore ignne emulation enable */
  3048. data &= ~(u64)0x8; /* ignore TLB cache disable */
  3049. /* Handle McStatusWrEn */
  3050. if (data == BIT_ULL(18)) {
  3051. vcpu->arch.msr_hwcr = data;
  3052. } else if (data != 0) {
  3053. vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
  3054. data);
  3055. return 1;
  3056. }
  3057. break;
  3058. case MSR_FAM10H_MMIO_CONF_BASE:
  3059. if (data != 0) {
  3060. vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
  3061. "0x%llx\n", data);
  3062. return 1;
  3063. }
  3064. break;
  3065. case 0x200 ... MSR_IA32_MC0_CTL2 - 1:
  3066. case MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) ... 0x2ff:
  3067. return kvm_mtrr_set_msr(vcpu, msr, data);
  3068. case MSR_IA32_APICBASE:
  3069. return kvm_set_apic_base(vcpu, msr_info);
  3070. case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
  3071. return kvm_x2apic_msr_write(vcpu, msr, data);
  3072. case MSR_IA32_TSC_DEADLINE:
  3073. kvm_set_lapic_tscdeadline_msr(vcpu, data);
  3074. break;
  3075. case MSR_IA32_TSC_ADJUST:
  3076. if (guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST)) {
  3077. if (!msr_info->host_initiated) {
  3078. s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
  3079. adjust_tsc_offset_guest(vcpu, adj);
  3080. /* Before back to guest, tsc_timestamp must be adjusted
  3081. * as well, otherwise guest's percpu pvclock time could jump.
  3082. */
  3083. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  3084. }
  3085. vcpu->arch.ia32_tsc_adjust_msr = data;
  3086. }
  3087. break;
  3088. case MSR_IA32_MISC_ENABLE: {
  3089. u64 old_val = vcpu->arch.ia32_misc_enable_msr;
  3090. if (!msr_info->host_initiated) {
  3091. /* RO bits */
  3092. if ((old_val ^ data) & MSR_IA32_MISC_ENABLE_PMU_RO_MASK)
  3093. return 1;
  3094. /* R bits, i.e. writes are ignored, but don't fault. */
  3095. data = data & ~MSR_IA32_MISC_ENABLE_EMON;
  3096. data |= old_val & MSR_IA32_MISC_ENABLE_EMON;
  3097. }
  3098. if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT) &&
  3099. ((old_val ^ data) & MSR_IA32_MISC_ENABLE_MWAIT)) {
  3100. if (!guest_cpuid_has(vcpu, X86_FEATURE_XMM3))
  3101. return 1;
  3102. vcpu->arch.ia32_misc_enable_msr = data;
  3103. kvm_update_cpuid_runtime(vcpu);
  3104. } else {
  3105. vcpu->arch.ia32_misc_enable_msr = data;
  3106. }
  3107. break;
  3108. }
  3109. case MSR_IA32_SMBASE:
  3110. if (!msr_info->host_initiated)
  3111. return 1;
  3112. vcpu->arch.smbase = data;
  3113. break;
  3114. case MSR_IA32_POWER_CTL:
  3115. vcpu->arch.msr_ia32_power_ctl = data;
  3116. break;
  3117. case MSR_IA32_TSC:
  3118. if (msr_info->host_initiated) {
  3119. kvm_synchronize_tsc(vcpu, data);
  3120. } else {
  3121. u64 adj = kvm_compute_l1_tsc_offset(vcpu, data) - vcpu->arch.l1_tsc_offset;
  3122. adjust_tsc_offset_guest(vcpu, adj);
  3123. vcpu->arch.ia32_tsc_adjust_msr += adj;
  3124. }
  3125. break;
  3126. case MSR_IA32_XSS:
  3127. if (!msr_info->host_initiated &&
  3128. !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
  3129. return 1;
  3130. /*
  3131. * KVM supports exposing PT to the guest, but does not support
  3132. * IA32_XSS[bit 8]. Guests have to use RDMSR/WRMSR rather than
  3133. * XSAVES/XRSTORS to save/restore PT MSRs.
  3134. */
  3135. if (data & ~kvm_caps.supported_xss)
  3136. return 1;
  3137. vcpu->arch.ia32_xss = data;
  3138. kvm_update_cpuid_runtime(vcpu);
  3139. break;
  3140. case MSR_SMI_COUNT:
  3141. if (!msr_info->host_initiated)
  3142. return 1;
  3143. vcpu->arch.smi_count = data;
  3144. break;
  3145. case MSR_KVM_WALL_CLOCK_NEW:
  3146. if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
  3147. return 1;
  3148. vcpu->kvm->arch.wall_clock = data;
  3149. kvm_write_wall_clock(vcpu->kvm, data, 0);
  3150. break;
  3151. case MSR_KVM_WALL_CLOCK:
  3152. if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
  3153. return 1;
  3154. vcpu->kvm->arch.wall_clock = data;
  3155. kvm_write_wall_clock(vcpu->kvm, data, 0);
  3156. break;
  3157. case MSR_KVM_SYSTEM_TIME_NEW:
  3158. if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
  3159. return 1;
  3160. kvm_write_system_time(vcpu, data, false, msr_info->host_initiated);
  3161. break;
  3162. case MSR_KVM_SYSTEM_TIME:
  3163. if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
  3164. return 1;
  3165. kvm_write_system_time(vcpu, data, true, msr_info->host_initiated);
  3166. break;
  3167. case MSR_KVM_ASYNC_PF_EN:
  3168. if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
  3169. return 1;
  3170. if (kvm_pv_enable_async_pf(vcpu, data))
  3171. return 1;
  3172. break;
  3173. case MSR_KVM_ASYNC_PF_INT:
  3174. if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
  3175. return 1;
  3176. if (kvm_pv_enable_async_pf_int(vcpu, data))
  3177. return 1;
  3178. break;
  3179. case MSR_KVM_ASYNC_PF_ACK:
  3180. if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
  3181. return 1;
  3182. if (data & 0x1) {
  3183. vcpu->arch.apf.pageready_pending = false;
  3184. kvm_check_async_pf_completion(vcpu);
  3185. }
  3186. break;
  3187. case MSR_KVM_STEAL_TIME:
  3188. if (!guest_pv_has(vcpu, KVM_FEATURE_STEAL_TIME))
  3189. return 1;
  3190. if (unlikely(!sched_info_on()))
  3191. return 1;
  3192. if (data & KVM_STEAL_RESERVED_MASK)
  3193. return 1;
  3194. vcpu->arch.st.msr_val = data;
  3195. if (!(data & KVM_MSR_ENABLED))
  3196. break;
  3197. kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
  3198. break;
  3199. case MSR_KVM_PV_EOI_EN:
  3200. if (!guest_pv_has(vcpu, KVM_FEATURE_PV_EOI))
  3201. return 1;
  3202. if (kvm_lapic_set_pv_eoi(vcpu, data, sizeof(u8)))
  3203. return 1;
  3204. break;
  3205. case MSR_KVM_POLL_CONTROL:
  3206. if (!guest_pv_has(vcpu, KVM_FEATURE_POLL_CONTROL))
  3207. return 1;
  3208. /* only enable bit supported */
  3209. if (data & (-1ULL << 1))
  3210. return 1;
  3211. vcpu->arch.msr_kvm_poll_control = data;
  3212. break;
  3213. case MSR_IA32_MCG_CTL:
  3214. case MSR_IA32_MCG_STATUS:
  3215. case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
  3216. case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
  3217. return set_msr_mce(vcpu, msr_info);
  3218. case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
  3219. case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
  3220. pr = true;
  3221. fallthrough;
  3222. case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
  3223. case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
  3224. if (kvm_pmu_is_valid_msr(vcpu, msr))
  3225. return kvm_pmu_set_msr(vcpu, msr_info);
  3226. if (pr || data != 0)
  3227. vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
  3228. "0x%x data 0x%llx\n", msr, data);
  3229. break;
  3230. case MSR_K7_CLK_CTL:
  3231. /*
  3232. * Ignore all writes to this no longer documented MSR.
  3233. * Writes are only relevant for old K7 processors,
  3234. * all pre-dating SVM, but a recommended workaround from
  3235. * AMD for these chips. It is possible to specify the
  3236. * affected processor models on the command line, hence
  3237. * the need to ignore the workaround.
  3238. */
  3239. break;
  3240. case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
  3241. case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
  3242. case HV_X64_MSR_SYNDBG_OPTIONS:
  3243. case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
  3244. case HV_X64_MSR_CRASH_CTL:
  3245. case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
  3246. case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
  3247. case HV_X64_MSR_TSC_EMULATION_CONTROL:
  3248. case HV_X64_MSR_TSC_EMULATION_STATUS:
  3249. return kvm_hv_set_msr_common(vcpu, msr, data,
  3250. msr_info->host_initiated);
  3251. case MSR_IA32_BBL_CR_CTL3:
  3252. /* Drop writes to this legacy MSR -- see rdmsr
  3253. * counterpart for further detail.
  3254. */
  3255. if (report_ignored_msrs)
  3256. vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data 0x%llx\n",
  3257. msr, data);
  3258. break;
  3259. case MSR_AMD64_OSVW_ID_LENGTH:
  3260. if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
  3261. return 1;
  3262. vcpu->arch.osvw.length = data;
  3263. break;
  3264. case MSR_AMD64_OSVW_STATUS:
  3265. if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
  3266. return 1;
  3267. vcpu->arch.osvw.status = data;
  3268. break;
  3269. case MSR_PLATFORM_INFO:
  3270. if (!msr_info->host_initiated ||
  3271. (!(data & MSR_PLATFORM_INFO_CPUID_FAULT) &&
  3272. cpuid_fault_enabled(vcpu)))
  3273. return 1;
  3274. vcpu->arch.msr_platform_info = data;
  3275. break;
  3276. case MSR_MISC_FEATURES_ENABLES:
  3277. if (data & ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT ||
  3278. (data & MSR_MISC_FEATURES_ENABLES_CPUID_FAULT &&
  3279. !supports_cpuid_fault(vcpu)))
  3280. return 1;
  3281. vcpu->arch.msr_misc_features_enables = data;
  3282. break;
  3283. #ifdef CONFIG_X86_64
  3284. case MSR_IA32_XFD:
  3285. if (!msr_info->host_initiated &&
  3286. !guest_cpuid_has(vcpu, X86_FEATURE_XFD))
  3287. return 1;
  3288. if (data & ~kvm_guest_supported_xfd(vcpu))
  3289. return 1;
  3290. fpu_update_guest_xfd(&vcpu->arch.guest_fpu, data);
  3291. break;
  3292. case MSR_IA32_XFD_ERR:
  3293. if (!msr_info->host_initiated &&
  3294. !guest_cpuid_has(vcpu, X86_FEATURE_XFD))
  3295. return 1;
  3296. if (data & ~kvm_guest_supported_xfd(vcpu))
  3297. return 1;
  3298. vcpu->arch.guest_fpu.xfd_err = data;
  3299. break;
  3300. #endif
  3301. case MSR_IA32_PEBS_ENABLE:
  3302. case MSR_IA32_DS_AREA:
  3303. case MSR_PEBS_DATA_CFG:
  3304. case MSR_F15H_PERF_CTL0 ... MSR_F15H_PERF_CTR5:
  3305. if (kvm_pmu_is_valid_msr(vcpu, msr))
  3306. return kvm_pmu_set_msr(vcpu, msr_info);
  3307. /*
  3308. * Userspace is allowed to write '0' to MSRs that KVM reports
  3309. * as to-be-saved, even if an MSRs isn't fully supported.
  3310. */
  3311. return !msr_info->host_initiated || data;
  3312. default:
  3313. if (kvm_pmu_is_valid_msr(vcpu, msr))
  3314. return kvm_pmu_set_msr(vcpu, msr_info);
  3315. return KVM_MSR_RET_INVALID;
  3316. }
  3317. return 0;
  3318. }
  3319. EXPORT_SYMBOL_GPL(kvm_set_msr_common);
  3320. static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata, bool host)
  3321. {
  3322. u64 data;
  3323. u64 mcg_cap = vcpu->arch.mcg_cap;
  3324. unsigned bank_num = mcg_cap & 0xff;
  3325. u32 offset, last_msr;
  3326. switch (msr) {
  3327. case MSR_IA32_P5_MC_ADDR:
  3328. case MSR_IA32_P5_MC_TYPE:
  3329. data = 0;
  3330. break;
  3331. case MSR_IA32_MCG_CAP:
  3332. data = vcpu->arch.mcg_cap;
  3333. break;
  3334. case MSR_IA32_MCG_CTL:
  3335. if (!(mcg_cap & MCG_CTL_P) && !host)
  3336. return 1;
  3337. data = vcpu->arch.mcg_ctl;
  3338. break;
  3339. case MSR_IA32_MCG_STATUS:
  3340. data = vcpu->arch.mcg_status;
  3341. break;
  3342. case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
  3343. last_msr = MSR_IA32_MCx_CTL2(bank_num) - 1;
  3344. if (msr > last_msr)
  3345. return 1;
  3346. if (!(mcg_cap & MCG_CMCI_P) && !host)
  3347. return 1;
  3348. offset = array_index_nospec(msr - MSR_IA32_MC0_CTL2,
  3349. last_msr + 1 - MSR_IA32_MC0_CTL2);
  3350. data = vcpu->arch.mci_ctl2_banks[offset];
  3351. break;
  3352. case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
  3353. last_msr = MSR_IA32_MCx_CTL(bank_num) - 1;
  3354. if (msr > last_msr)
  3355. return 1;
  3356. offset = array_index_nospec(msr - MSR_IA32_MC0_CTL,
  3357. last_msr + 1 - MSR_IA32_MC0_CTL);
  3358. data = vcpu->arch.mce_banks[offset];
  3359. break;
  3360. default:
  3361. return 1;
  3362. }
  3363. *pdata = data;
  3364. return 0;
  3365. }
  3366. int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
  3367. {
  3368. switch (msr_info->index) {
  3369. case MSR_IA32_PLATFORM_ID:
  3370. case MSR_IA32_EBL_CR_POWERON:
  3371. case MSR_IA32_LASTBRANCHFROMIP:
  3372. case MSR_IA32_LASTBRANCHTOIP:
  3373. case MSR_IA32_LASTINTFROMIP:
  3374. case MSR_IA32_LASTINTTOIP:
  3375. case MSR_AMD64_SYSCFG:
  3376. case MSR_K8_TSEG_ADDR:
  3377. case MSR_K8_TSEG_MASK:
  3378. case MSR_VM_HSAVE_PA:
  3379. case MSR_K8_INT_PENDING_MSG:
  3380. case MSR_AMD64_NB_CFG:
  3381. case MSR_FAM10H_MMIO_CONF_BASE:
  3382. case MSR_AMD64_BU_CFG2:
  3383. case MSR_IA32_PERF_CTL:
  3384. case MSR_AMD64_DC_CFG:
  3385. case MSR_AMD64_TW_CFG:
  3386. case MSR_F15H_EX_CFG:
  3387. /*
  3388. * Intel Sandy Bridge CPUs must support the RAPL (running average power
  3389. * limit) MSRs. Just return 0, as we do not want to expose the host
  3390. * data here. Do not conditionalize this on CPUID, as KVM does not do
  3391. * so for existing CPU-specific MSRs.
  3392. */
  3393. case MSR_RAPL_POWER_UNIT:
  3394. case MSR_PP0_ENERGY_STATUS: /* Power plane 0 (core) */
  3395. case MSR_PP1_ENERGY_STATUS: /* Power plane 1 (graphics uncore) */
  3396. case MSR_PKG_ENERGY_STATUS: /* Total package */
  3397. case MSR_DRAM_ENERGY_STATUS: /* DRAM controller */
  3398. msr_info->data = 0;
  3399. break;
  3400. case MSR_IA32_PEBS_ENABLE:
  3401. case MSR_IA32_DS_AREA:
  3402. case MSR_PEBS_DATA_CFG:
  3403. case MSR_F15H_PERF_CTL0 ... MSR_F15H_PERF_CTR5:
  3404. if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
  3405. return kvm_pmu_get_msr(vcpu, msr_info);
  3406. /*
  3407. * Userspace is allowed to read MSRs that KVM reports as
  3408. * to-be-saved, even if an MSR isn't fully supported.
  3409. */
  3410. if (!msr_info->host_initiated)
  3411. return 1;
  3412. msr_info->data = 0;
  3413. break;
  3414. case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
  3415. case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
  3416. case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
  3417. case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
  3418. if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
  3419. return kvm_pmu_get_msr(vcpu, msr_info);
  3420. msr_info->data = 0;
  3421. break;
  3422. case MSR_IA32_UCODE_REV:
  3423. msr_info->data = vcpu->arch.microcode_version;
  3424. break;
  3425. case MSR_IA32_ARCH_CAPABILITIES:
  3426. if (!msr_info->host_initiated &&
  3427. !guest_cpuid_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
  3428. return 1;
  3429. msr_info->data = vcpu->arch.arch_capabilities;
  3430. break;
  3431. case MSR_IA32_PERF_CAPABILITIES:
  3432. if (!msr_info->host_initiated &&
  3433. !guest_cpuid_has(vcpu, X86_FEATURE_PDCM))
  3434. return 1;
  3435. msr_info->data = vcpu->arch.perf_capabilities;
  3436. break;
  3437. case MSR_IA32_POWER_CTL:
  3438. msr_info->data = vcpu->arch.msr_ia32_power_ctl;
  3439. break;
  3440. case MSR_IA32_TSC: {
  3441. /*
  3442. * Intel SDM states that MSR_IA32_TSC read adds the TSC offset
  3443. * even when not intercepted. AMD manual doesn't explicitly
  3444. * state this but appears to behave the same.
  3445. *
  3446. * On userspace reads and writes, however, we unconditionally
  3447. * return L1's TSC value to ensure backwards-compatible
  3448. * behavior for migration.
  3449. */
  3450. u64 offset, ratio;
  3451. if (msr_info->host_initiated) {
  3452. offset = vcpu->arch.l1_tsc_offset;
  3453. ratio = vcpu->arch.l1_tsc_scaling_ratio;
  3454. } else {
  3455. offset = vcpu->arch.tsc_offset;
  3456. ratio = vcpu->arch.tsc_scaling_ratio;
  3457. }
  3458. msr_info->data = kvm_scale_tsc(rdtsc(), ratio) + offset;
  3459. break;
  3460. }
  3461. case MSR_MTRRcap:
  3462. case 0x200 ... MSR_IA32_MC0_CTL2 - 1:
  3463. case MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) ... 0x2ff:
  3464. return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
  3465. case 0xcd: /* fsb frequency */
  3466. msr_info->data = 3;
  3467. break;
  3468. /*
  3469. * MSR_EBC_FREQUENCY_ID
  3470. * Conservative value valid for even the basic CPU models.
  3471. * Models 0,1: 000 in bits 23:21 indicating a bus speed of
  3472. * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
  3473. * and 266MHz for model 3, or 4. Set Core Clock
  3474. * Frequency to System Bus Frequency Ratio to 1 (bits
  3475. * 31:24) even though these are only valid for CPU
  3476. * models > 2, however guests may end up dividing or
  3477. * multiplying by zero otherwise.
  3478. */
  3479. case MSR_EBC_FREQUENCY_ID:
  3480. msr_info->data = 1 << 24;
  3481. break;
  3482. case MSR_IA32_APICBASE:
  3483. msr_info->data = kvm_get_apic_base(vcpu);
  3484. break;
  3485. case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
  3486. return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
  3487. case MSR_IA32_TSC_DEADLINE:
  3488. msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
  3489. break;
  3490. case MSR_IA32_TSC_ADJUST:
  3491. msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
  3492. break;
  3493. case MSR_IA32_MISC_ENABLE:
  3494. msr_info->data = vcpu->arch.ia32_misc_enable_msr;
  3495. break;
  3496. case MSR_IA32_SMBASE:
  3497. if (!msr_info->host_initiated)
  3498. return 1;
  3499. msr_info->data = vcpu->arch.smbase;
  3500. break;
  3501. case MSR_SMI_COUNT:
  3502. msr_info->data = vcpu->arch.smi_count;
  3503. break;
  3504. case MSR_IA32_PERF_STATUS:
  3505. /* TSC increment by tick */
  3506. msr_info->data = 1000ULL;
  3507. /* CPU multiplier */
  3508. msr_info->data |= (((uint64_t)4ULL) << 40);
  3509. break;
  3510. case MSR_EFER:
  3511. msr_info->data = vcpu->arch.efer;
  3512. break;
  3513. case MSR_KVM_WALL_CLOCK:
  3514. if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
  3515. return 1;
  3516. msr_info->data = vcpu->kvm->arch.wall_clock;
  3517. break;
  3518. case MSR_KVM_WALL_CLOCK_NEW:
  3519. if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
  3520. return 1;
  3521. msr_info->data = vcpu->kvm->arch.wall_clock;
  3522. break;
  3523. case MSR_KVM_SYSTEM_TIME:
  3524. if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
  3525. return 1;
  3526. msr_info->data = vcpu->arch.time;
  3527. break;
  3528. case MSR_KVM_SYSTEM_TIME_NEW:
  3529. if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
  3530. return 1;
  3531. msr_info->data = vcpu->arch.time;
  3532. break;
  3533. case MSR_KVM_ASYNC_PF_EN:
  3534. if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
  3535. return 1;
  3536. msr_info->data = vcpu->arch.apf.msr_en_val;
  3537. break;
  3538. case MSR_KVM_ASYNC_PF_INT:
  3539. if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
  3540. return 1;
  3541. msr_info->data = vcpu->arch.apf.msr_int_val;
  3542. break;
  3543. case MSR_KVM_ASYNC_PF_ACK:
  3544. if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
  3545. return 1;
  3546. msr_info->data = 0;
  3547. break;
  3548. case MSR_KVM_STEAL_TIME:
  3549. if (!guest_pv_has(vcpu, KVM_FEATURE_STEAL_TIME))
  3550. return 1;
  3551. msr_info->data = vcpu->arch.st.msr_val;
  3552. break;
  3553. case MSR_KVM_PV_EOI_EN:
  3554. if (!guest_pv_has(vcpu, KVM_FEATURE_PV_EOI))
  3555. return 1;
  3556. msr_info->data = vcpu->arch.pv_eoi.msr_val;
  3557. break;
  3558. case MSR_KVM_POLL_CONTROL:
  3559. if (!guest_pv_has(vcpu, KVM_FEATURE_POLL_CONTROL))
  3560. return 1;
  3561. msr_info->data = vcpu->arch.msr_kvm_poll_control;
  3562. break;
  3563. case MSR_IA32_P5_MC_ADDR:
  3564. case MSR_IA32_P5_MC_TYPE:
  3565. case MSR_IA32_MCG_CAP:
  3566. case MSR_IA32_MCG_CTL:
  3567. case MSR_IA32_MCG_STATUS:
  3568. case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
  3569. case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
  3570. return get_msr_mce(vcpu, msr_info->index, &msr_info->data,
  3571. msr_info->host_initiated);
  3572. case MSR_IA32_XSS:
  3573. if (!msr_info->host_initiated &&
  3574. !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
  3575. return 1;
  3576. msr_info->data = vcpu->arch.ia32_xss;
  3577. break;
  3578. case MSR_K7_CLK_CTL:
  3579. /*
  3580. * Provide expected ramp-up count for K7. All other
  3581. * are set to zero, indicating minimum divisors for
  3582. * every field.
  3583. *
  3584. * This prevents guest kernels on AMD host with CPU
  3585. * type 6, model 8 and higher from exploding due to
  3586. * the rdmsr failing.
  3587. */
  3588. msr_info->data = 0x20000000;
  3589. break;
  3590. case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
  3591. case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
  3592. case HV_X64_MSR_SYNDBG_OPTIONS:
  3593. case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
  3594. case HV_X64_MSR_CRASH_CTL:
  3595. case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
  3596. case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
  3597. case HV_X64_MSR_TSC_EMULATION_CONTROL:
  3598. case HV_X64_MSR_TSC_EMULATION_STATUS:
  3599. return kvm_hv_get_msr_common(vcpu,
  3600. msr_info->index, &msr_info->data,
  3601. msr_info->host_initiated);
  3602. case MSR_IA32_BBL_CR_CTL3:
  3603. /* This legacy MSR exists but isn't fully documented in current
  3604. * silicon. It is however accessed by winxp in very narrow
  3605. * scenarios where it sets bit #19, itself documented as
  3606. * a "reserved" bit. Best effort attempt to source coherent
  3607. * read data here should the balance of the register be
  3608. * interpreted by the guest:
  3609. *
  3610. * L2 cache control register 3: 64GB range, 256KB size,
  3611. * enabled, latency 0x1, configured
  3612. */
  3613. msr_info->data = 0xbe702111;
  3614. break;
  3615. case MSR_AMD64_OSVW_ID_LENGTH:
  3616. if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
  3617. return 1;
  3618. msr_info->data = vcpu->arch.osvw.length;
  3619. break;
  3620. case MSR_AMD64_OSVW_STATUS:
  3621. if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
  3622. return 1;
  3623. msr_info->data = vcpu->arch.osvw.status;
  3624. break;
  3625. case MSR_PLATFORM_INFO:
  3626. if (!msr_info->host_initiated &&
  3627. !vcpu->kvm->arch.guest_can_read_msr_platform_info)
  3628. return 1;
  3629. msr_info->data = vcpu->arch.msr_platform_info;
  3630. break;
  3631. case MSR_MISC_FEATURES_ENABLES:
  3632. msr_info->data = vcpu->arch.msr_misc_features_enables;
  3633. break;
  3634. case MSR_K7_HWCR:
  3635. msr_info->data = vcpu->arch.msr_hwcr;
  3636. break;
  3637. #ifdef CONFIG_X86_64
  3638. case MSR_IA32_XFD:
  3639. if (!msr_info->host_initiated &&
  3640. !guest_cpuid_has(vcpu, X86_FEATURE_XFD))
  3641. return 1;
  3642. msr_info->data = vcpu->arch.guest_fpu.fpstate->xfd;
  3643. break;
  3644. case MSR_IA32_XFD_ERR:
  3645. if (!msr_info->host_initiated &&
  3646. !guest_cpuid_has(vcpu, X86_FEATURE_XFD))
  3647. return 1;
  3648. msr_info->data = vcpu->arch.guest_fpu.xfd_err;
  3649. break;
  3650. #endif
  3651. default:
  3652. if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
  3653. return kvm_pmu_get_msr(vcpu, msr_info);
  3654. return KVM_MSR_RET_INVALID;
  3655. }
  3656. return 0;
  3657. }
  3658. EXPORT_SYMBOL_GPL(kvm_get_msr_common);
  3659. /*
  3660. * Read or write a bunch of msrs. All parameters are kernel addresses.
  3661. *
  3662. * @return number of msrs set successfully.
  3663. */
  3664. static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
  3665. struct kvm_msr_entry *entries,
  3666. int (*do_msr)(struct kvm_vcpu *vcpu,
  3667. unsigned index, u64 *data))
  3668. {
  3669. int i;
  3670. for (i = 0; i < msrs->nmsrs; ++i)
  3671. if (do_msr(vcpu, entries[i].index, &entries[i].data))
  3672. break;
  3673. return i;
  3674. }
  3675. /*
  3676. * Read or write a bunch of msrs. Parameters are user addresses.
  3677. *
  3678. * @return number of msrs set successfully.
  3679. */
  3680. static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
  3681. int (*do_msr)(struct kvm_vcpu *vcpu,
  3682. unsigned index, u64 *data),
  3683. int writeback)
  3684. {
  3685. struct kvm_msrs msrs;
  3686. struct kvm_msr_entry *entries;
  3687. int r, n;
  3688. unsigned size;
  3689. r = -EFAULT;
  3690. if (copy_from_user(&msrs, user_msrs, sizeof(msrs)))
  3691. goto out;
  3692. r = -E2BIG;
  3693. if (msrs.nmsrs >= MAX_IO_MSRS)
  3694. goto out;
  3695. size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
  3696. entries = memdup_user(user_msrs->entries, size);
  3697. if (IS_ERR(entries)) {
  3698. r = PTR_ERR(entries);
  3699. goto out;
  3700. }
  3701. r = n = __msr_io(vcpu, &msrs, entries, do_msr);
  3702. if (r < 0)
  3703. goto out_free;
  3704. r = -EFAULT;
  3705. if (writeback && copy_to_user(user_msrs->entries, entries, size))
  3706. goto out_free;
  3707. r = n;
  3708. out_free:
  3709. kfree(entries);
  3710. out:
  3711. return r;
  3712. }
  3713. static inline bool kvm_can_mwait_in_guest(void)
  3714. {
  3715. return boot_cpu_has(X86_FEATURE_MWAIT) &&
  3716. !boot_cpu_has_bug(X86_BUG_MONITOR) &&
  3717. boot_cpu_has(X86_FEATURE_ARAT);
  3718. }
  3719. static int kvm_ioctl_get_supported_hv_cpuid(struct kvm_vcpu *vcpu,
  3720. struct kvm_cpuid2 __user *cpuid_arg)
  3721. {
  3722. struct kvm_cpuid2 cpuid;
  3723. int r;
  3724. r = -EFAULT;
  3725. if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
  3726. return r;
  3727. r = kvm_get_hv_cpuid(vcpu, &cpuid, cpuid_arg->entries);
  3728. if (r)
  3729. return r;
  3730. r = -EFAULT;
  3731. if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
  3732. return r;
  3733. return 0;
  3734. }
  3735. int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
  3736. {
  3737. int r = 0;
  3738. switch (ext) {
  3739. case KVM_CAP_IRQCHIP:
  3740. case KVM_CAP_HLT:
  3741. case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
  3742. case KVM_CAP_SET_TSS_ADDR:
  3743. case KVM_CAP_EXT_CPUID:
  3744. case KVM_CAP_EXT_EMUL_CPUID:
  3745. case KVM_CAP_CLOCKSOURCE:
  3746. case KVM_CAP_PIT:
  3747. case KVM_CAP_NOP_IO_DELAY:
  3748. case KVM_CAP_MP_STATE:
  3749. case KVM_CAP_SYNC_MMU:
  3750. case KVM_CAP_USER_NMI:
  3751. case KVM_CAP_REINJECT_CONTROL:
  3752. case KVM_CAP_IRQ_INJECT_STATUS:
  3753. case KVM_CAP_IOEVENTFD:
  3754. case KVM_CAP_IOEVENTFD_NO_LENGTH:
  3755. case KVM_CAP_PIT2:
  3756. case KVM_CAP_PIT_STATE2:
  3757. case KVM_CAP_SET_IDENTITY_MAP_ADDR:
  3758. case KVM_CAP_VCPU_EVENTS:
  3759. case KVM_CAP_HYPERV:
  3760. case KVM_CAP_HYPERV_VAPIC:
  3761. case KVM_CAP_HYPERV_SPIN:
  3762. case KVM_CAP_HYPERV_SYNIC:
  3763. case KVM_CAP_HYPERV_SYNIC2:
  3764. case KVM_CAP_HYPERV_VP_INDEX:
  3765. case KVM_CAP_HYPERV_EVENTFD:
  3766. case KVM_CAP_HYPERV_TLBFLUSH:
  3767. case KVM_CAP_HYPERV_SEND_IPI:
  3768. case KVM_CAP_HYPERV_CPUID:
  3769. case KVM_CAP_HYPERV_ENFORCE_CPUID:
  3770. case KVM_CAP_SYS_HYPERV_CPUID:
  3771. case KVM_CAP_PCI_SEGMENT:
  3772. case KVM_CAP_DEBUGREGS:
  3773. case KVM_CAP_X86_ROBUST_SINGLESTEP:
  3774. case KVM_CAP_XSAVE:
  3775. case KVM_CAP_ASYNC_PF:
  3776. case KVM_CAP_ASYNC_PF_INT:
  3777. case KVM_CAP_GET_TSC_KHZ:
  3778. case KVM_CAP_KVMCLOCK_CTRL:
  3779. case KVM_CAP_READONLY_MEM:
  3780. case KVM_CAP_HYPERV_TIME:
  3781. case KVM_CAP_IOAPIC_POLARITY_IGNORED:
  3782. case KVM_CAP_TSC_DEADLINE_TIMER:
  3783. case KVM_CAP_DISABLE_QUIRKS:
  3784. case KVM_CAP_SET_BOOT_CPU_ID:
  3785. case KVM_CAP_SPLIT_IRQCHIP:
  3786. case KVM_CAP_IMMEDIATE_EXIT:
  3787. case KVM_CAP_PMU_EVENT_FILTER:
  3788. case KVM_CAP_GET_MSR_FEATURES:
  3789. case KVM_CAP_MSR_PLATFORM_INFO:
  3790. case KVM_CAP_EXCEPTION_PAYLOAD:
  3791. case KVM_CAP_X86_TRIPLE_FAULT_EVENT:
  3792. case KVM_CAP_SET_GUEST_DEBUG:
  3793. case KVM_CAP_LAST_CPU:
  3794. case KVM_CAP_X86_USER_SPACE_MSR:
  3795. case KVM_CAP_X86_MSR_FILTER:
  3796. case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
  3797. #ifdef CONFIG_X86_SGX_KVM
  3798. case KVM_CAP_SGX_ATTRIBUTE:
  3799. #endif
  3800. case KVM_CAP_VM_COPY_ENC_CONTEXT_FROM:
  3801. case KVM_CAP_VM_MOVE_ENC_CONTEXT_FROM:
  3802. case KVM_CAP_SREGS2:
  3803. case KVM_CAP_EXIT_ON_EMULATION_FAILURE:
  3804. case KVM_CAP_VCPU_ATTRIBUTES:
  3805. case KVM_CAP_SYS_ATTRIBUTES:
  3806. case KVM_CAP_VAPIC:
  3807. case KVM_CAP_ENABLE_CAP:
  3808. case KVM_CAP_VM_DISABLE_NX_HUGE_PAGES:
  3809. r = 1;
  3810. break;
  3811. case KVM_CAP_EXIT_HYPERCALL:
  3812. r = KVM_EXIT_HYPERCALL_VALID_MASK;
  3813. break;
  3814. case KVM_CAP_SET_GUEST_DEBUG2:
  3815. return KVM_GUESTDBG_VALID_MASK;
  3816. #ifdef CONFIG_KVM_XEN
  3817. case KVM_CAP_XEN_HVM:
  3818. r = KVM_XEN_HVM_CONFIG_HYPERCALL_MSR |
  3819. KVM_XEN_HVM_CONFIG_INTERCEPT_HCALL |
  3820. KVM_XEN_HVM_CONFIG_SHARED_INFO |
  3821. KVM_XEN_HVM_CONFIG_EVTCHN_2LEVEL |
  3822. KVM_XEN_HVM_CONFIG_EVTCHN_SEND;
  3823. if (sched_info_on())
  3824. r |= KVM_XEN_HVM_CONFIG_RUNSTATE;
  3825. break;
  3826. #endif
  3827. case KVM_CAP_SYNC_REGS:
  3828. r = KVM_SYNC_X86_VALID_FIELDS;
  3829. break;
  3830. case KVM_CAP_ADJUST_CLOCK:
  3831. r = KVM_CLOCK_VALID_FLAGS;
  3832. break;
  3833. case KVM_CAP_X86_DISABLE_EXITS:
  3834. r = KVM_X86_DISABLE_EXITS_PAUSE;
  3835. if (!mitigate_smt_rsb) {
  3836. r |= KVM_X86_DISABLE_EXITS_HLT |
  3837. KVM_X86_DISABLE_EXITS_CSTATE;
  3838. if (kvm_can_mwait_in_guest())
  3839. r |= KVM_X86_DISABLE_EXITS_MWAIT;
  3840. }
  3841. break;
  3842. case KVM_CAP_X86_SMM:
  3843. /* SMBASE is usually relocated above 1M on modern chipsets,
  3844. * and SMM handlers might indeed rely on 4G segment limits,
  3845. * so do not report SMM to be available if real mode is
  3846. * emulated via vm86 mode. Still, do not go to great lengths
  3847. * to avoid userspace's usage of the feature, because it is a
  3848. * fringe case that is not enabled except via specific settings
  3849. * of the module parameters.
  3850. */
  3851. r = static_call(kvm_x86_has_emulated_msr)(kvm, MSR_IA32_SMBASE);
  3852. break;
  3853. case KVM_CAP_NR_VCPUS:
  3854. r = min_t(unsigned int, num_online_cpus(), KVM_MAX_VCPUS);
  3855. break;
  3856. case KVM_CAP_MAX_VCPUS:
  3857. r = KVM_MAX_VCPUS;
  3858. break;
  3859. case KVM_CAP_MAX_VCPU_ID:
  3860. r = KVM_MAX_VCPU_IDS;
  3861. break;
  3862. case KVM_CAP_PV_MMU: /* obsolete */
  3863. r = 0;
  3864. break;
  3865. case KVM_CAP_MCE:
  3866. r = KVM_MAX_MCE_BANKS;
  3867. break;
  3868. case KVM_CAP_XCRS:
  3869. r = boot_cpu_has(X86_FEATURE_XSAVE);
  3870. break;
  3871. case KVM_CAP_TSC_CONTROL:
  3872. case KVM_CAP_VM_TSC_CONTROL:
  3873. r = kvm_caps.has_tsc_control;
  3874. break;
  3875. case KVM_CAP_X2APIC_API:
  3876. r = KVM_X2APIC_API_VALID_FLAGS;
  3877. break;
  3878. case KVM_CAP_NESTED_STATE:
  3879. r = kvm_x86_ops.nested_ops->get_state ?
  3880. kvm_x86_ops.nested_ops->get_state(NULL, NULL, 0) : 0;
  3881. break;
  3882. case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
  3883. r = kvm_x86_ops.enable_direct_tlbflush != NULL;
  3884. break;
  3885. case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
  3886. r = kvm_x86_ops.nested_ops->enable_evmcs != NULL;
  3887. break;
  3888. case KVM_CAP_SMALLER_MAXPHYADDR:
  3889. r = (int) allow_smaller_maxphyaddr;
  3890. break;
  3891. case KVM_CAP_STEAL_TIME:
  3892. r = sched_info_on();
  3893. break;
  3894. case KVM_CAP_X86_BUS_LOCK_EXIT:
  3895. if (kvm_caps.has_bus_lock_exit)
  3896. r = KVM_BUS_LOCK_DETECTION_OFF |
  3897. KVM_BUS_LOCK_DETECTION_EXIT;
  3898. else
  3899. r = 0;
  3900. break;
  3901. case KVM_CAP_XSAVE2: {
  3902. u64 guest_perm = xstate_get_guest_group_perm();
  3903. r = xstate_required_size(kvm_caps.supported_xcr0 & guest_perm, false);
  3904. if (r < sizeof(struct kvm_xsave))
  3905. r = sizeof(struct kvm_xsave);
  3906. break;
  3907. }
  3908. case KVM_CAP_PMU_CAPABILITY:
  3909. r = enable_pmu ? KVM_CAP_PMU_VALID_MASK : 0;
  3910. break;
  3911. case KVM_CAP_DISABLE_QUIRKS2:
  3912. r = KVM_X86_VALID_QUIRKS;
  3913. break;
  3914. case KVM_CAP_X86_NOTIFY_VMEXIT:
  3915. r = kvm_caps.has_notify_vmexit;
  3916. break;
  3917. default:
  3918. break;
  3919. }
  3920. return r;
  3921. }
  3922. static inline void __user *kvm_get_attr_addr(struct kvm_device_attr *attr)
  3923. {
  3924. void __user *uaddr = (void __user*)(unsigned long)attr->addr;
  3925. if ((u64)(unsigned long)uaddr != attr->addr)
  3926. return ERR_PTR_USR(-EFAULT);
  3927. return uaddr;
  3928. }
  3929. static int kvm_x86_dev_get_attr(struct kvm_device_attr *attr)
  3930. {
  3931. u64 __user *uaddr = kvm_get_attr_addr(attr);
  3932. if (attr->group)
  3933. return -ENXIO;
  3934. if (IS_ERR(uaddr))
  3935. return PTR_ERR(uaddr);
  3936. switch (attr->attr) {
  3937. case KVM_X86_XCOMP_GUEST_SUPP:
  3938. if (put_user(kvm_caps.supported_xcr0, uaddr))
  3939. return -EFAULT;
  3940. return 0;
  3941. default:
  3942. return -ENXIO;
  3943. break;
  3944. }
  3945. }
  3946. static int kvm_x86_dev_has_attr(struct kvm_device_attr *attr)
  3947. {
  3948. if (attr->group)
  3949. return -ENXIO;
  3950. switch (attr->attr) {
  3951. case KVM_X86_XCOMP_GUEST_SUPP:
  3952. return 0;
  3953. default:
  3954. return -ENXIO;
  3955. }
  3956. }
  3957. long kvm_arch_dev_ioctl(struct file *filp,
  3958. unsigned int ioctl, unsigned long arg)
  3959. {
  3960. void __user *argp = (void __user *)arg;
  3961. long r;
  3962. switch (ioctl) {
  3963. case KVM_GET_MSR_INDEX_LIST: {
  3964. struct kvm_msr_list __user *user_msr_list = argp;
  3965. struct kvm_msr_list msr_list;
  3966. unsigned n;
  3967. r = -EFAULT;
  3968. if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
  3969. goto out;
  3970. n = msr_list.nmsrs;
  3971. msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
  3972. if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
  3973. goto out;
  3974. r = -E2BIG;
  3975. if (n < msr_list.nmsrs)
  3976. goto out;
  3977. r = -EFAULT;
  3978. if (copy_to_user(user_msr_list->indices, &msrs_to_save,
  3979. num_msrs_to_save * sizeof(u32)))
  3980. goto out;
  3981. if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
  3982. &emulated_msrs,
  3983. num_emulated_msrs * sizeof(u32)))
  3984. goto out;
  3985. r = 0;
  3986. break;
  3987. }
  3988. case KVM_GET_SUPPORTED_CPUID:
  3989. case KVM_GET_EMULATED_CPUID: {
  3990. struct kvm_cpuid2 __user *cpuid_arg = argp;
  3991. struct kvm_cpuid2 cpuid;
  3992. r = -EFAULT;
  3993. if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
  3994. goto out;
  3995. r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
  3996. ioctl);
  3997. if (r)
  3998. goto out;
  3999. r = -EFAULT;
  4000. if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
  4001. goto out;
  4002. r = 0;
  4003. break;
  4004. }
  4005. case KVM_X86_GET_MCE_CAP_SUPPORTED:
  4006. r = -EFAULT;
  4007. if (copy_to_user(argp, &kvm_caps.supported_mce_cap,
  4008. sizeof(kvm_caps.supported_mce_cap)))
  4009. goto out;
  4010. r = 0;
  4011. break;
  4012. case KVM_GET_MSR_FEATURE_INDEX_LIST: {
  4013. struct kvm_msr_list __user *user_msr_list = argp;
  4014. struct kvm_msr_list msr_list;
  4015. unsigned int n;
  4016. r = -EFAULT;
  4017. if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
  4018. goto out;
  4019. n = msr_list.nmsrs;
  4020. msr_list.nmsrs = num_msr_based_features;
  4021. if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
  4022. goto out;
  4023. r = -E2BIG;
  4024. if (n < msr_list.nmsrs)
  4025. goto out;
  4026. r = -EFAULT;
  4027. if (copy_to_user(user_msr_list->indices, &msr_based_features,
  4028. num_msr_based_features * sizeof(u32)))
  4029. goto out;
  4030. r = 0;
  4031. break;
  4032. }
  4033. case KVM_GET_MSRS:
  4034. r = msr_io(NULL, argp, do_get_msr_feature, 1);
  4035. break;
  4036. case KVM_GET_SUPPORTED_HV_CPUID:
  4037. r = kvm_ioctl_get_supported_hv_cpuid(NULL, argp);
  4038. break;
  4039. case KVM_GET_DEVICE_ATTR: {
  4040. struct kvm_device_attr attr;
  4041. r = -EFAULT;
  4042. if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
  4043. break;
  4044. r = kvm_x86_dev_get_attr(&attr);
  4045. break;
  4046. }
  4047. case KVM_HAS_DEVICE_ATTR: {
  4048. struct kvm_device_attr attr;
  4049. r = -EFAULT;
  4050. if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
  4051. break;
  4052. r = kvm_x86_dev_has_attr(&attr);
  4053. break;
  4054. }
  4055. default:
  4056. r = -EINVAL;
  4057. break;
  4058. }
  4059. out:
  4060. return r;
  4061. }
  4062. static void wbinvd_ipi(void *garbage)
  4063. {
  4064. wbinvd();
  4065. }
  4066. static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
  4067. {
  4068. return kvm_arch_has_noncoherent_dma(vcpu->kvm);
  4069. }
  4070. void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
  4071. {
  4072. /* Address WBINVD may be executed by guest */
  4073. if (need_emulate_wbinvd(vcpu)) {
  4074. if (static_call(kvm_x86_has_wbinvd_exit)())
  4075. cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
  4076. else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
  4077. smp_call_function_single(vcpu->cpu,
  4078. wbinvd_ipi, NULL, 1);
  4079. }
  4080. static_call(kvm_x86_vcpu_load)(vcpu, cpu);
  4081. /* Save host pkru register if supported */
  4082. vcpu->arch.host_pkru = read_pkru();
  4083. /* Apply any externally detected TSC adjustments (due to suspend) */
  4084. if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
  4085. adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
  4086. vcpu->arch.tsc_offset_adjustment = 0;
  4087. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  4088. }
  4089. if (unlikely(vcpu->cpu != cpu) || kvm_check_tsc_unstable()) {
  4090. s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
  4091. rdtsc() - vcpu->arch.last_host_tsc;
  4092. if (tsc_delta < 0)
  4093. mark_tsc_unstable("KVM discovered backwards TSC");
  4094. if (kvm_check_tsc_unstable()) {
  4095. u64 offset = kvm_compute_l1_tsc_offset(vcpu,
  4096. vcpu->arch.last_guest_tsc);
  4097. kvm_vcpu_write_tsc_offset(vcpu, offset);
  4098. vcpu->arch.tsc_catchup = 1;
  4099. }
  4100. if (kvm_lapic_hv_timer_in_use(vcpu))
  4101. kvm_lapic_restart_hv_timer(vcpu);
  4102. /*
  4103. * On a host with synchronized TSC, there is no need to update
  4104. * kvmclock on vcpu->cpu migration
  4105. */
  4106. if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
  4107. kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
  4108. if (vcpu->cpu != cpu)
  4109. kvm_make_request(KVM_REQ_MIGRATE_TIMER, vcpu);
  4110. vcpu->cpu = cpu;
  4111. }
  4112. kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
  4113. }
  4114. static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
  4115. {
  4116. struct gfn_to_hva_cache *ghc = &vcpu->arch.st.cache;
  4117. struct kvm_steal_time __user *st;
  4118. struct kvm_memslots *slots;
  4119. static const u8 preempted = KVM_VCPU_PREEMPTED;
  4120. gpa_t gpa = vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS;
  4121. /*
  4122. * The vCPU can be marked preempted if and only if the VM-Exit was on
  4123. * an instruction boundary and will not trigger guest emulation of any
  4124. * kind (see vcpu_run). Vendor specific code controls (conservatively)
  4125. * when this is true, for example allowing the vCPU to be marked
  4126. * preempted if and only if the VM-Exit was due to a host interrupt.
  4127. */
  4128. if (!vcpu->arch.at_instruction_boundary) {
  4129. vcpu->stat.preemption_other++;
  4130. return;
  4131. }
  4132. vcpu->stat.preemption_reported++;
  4133. if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
  4134. return;
  4135. if (vcpu->arch.st.preempted)
  4136. return;
  4137. /* This happens on process exit */
  4138. if (unlikely(current->mm != vcpu->kvm->mm))
  4139. return;
  4140. slots = kvm_memslots(vcpu->kvm);
  4141. if (unlikely(slots->generation != ghc->generation ||
  4142. gpa != ghc->gpa ||
  4143. kvm_is_error_hva(ghc->hva) || !ghc->memslot))
  4144. return;
  4145. st = (struct kvm_steal_time __user *)ghc->hva;
  4146. BUILD_BUG_ON(sizeof(st->preempted) != sizeof(preempted));
  4147. if (!copy_to_user_nofault(&st->preempted, &preempted, sizeof(preempted)))
  4148. vcpu->arch.st.preempted = KVM_VCPU_PREEMPTED;
  4149. mark_page_dirty_in_slot(vcpu->kvm, ghc->memslot, gpa_to_gfn(ghc->gpa));
  4150. }
  4151. void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
  4152. {
  4153. int idx;
  4154. if (vcpu->preempted) {
  4155. if (!vcpu->arch.guest_state_protected)
  4156. vcpu->arch.preempted_in_kernel = !static_call(kvm_x86_get_cpl)(vcpu);
  4157. /*
  4158. * Take the srcu lock as memslots will be accessed to check the gfn
  4159. * cache generation against the memslots generation.
  4160. */
  4161. idx = srcu_read_lock(&vcpu->kvm->srcu);
  4162. if (kvm_xen_msr_enabled(vcpu->kvm))
  4163. kvm_xen_runstate_set_preempted(vcpu);
  4164. else
  4165. kvm_steal_time_set_preempted(vcpu);
  4166. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  4167. }
  4168. static_call(kvm_x86_vcpu_put)(vcpu);
  4169. vcpu->arch.last_host_tsc = rdtsc();
  4170. }
  4171. static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
  4172. struct kvm_lapic_state *s)
  4173. {
  4174. static_call_cond(kvm_x86_sync_pir_to_irr)(vcpu);
  4175. return kvm_apic_get_state(vcpu, s);
  4176. }
  4177. static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
  4178. struct kvm_lapic_state *s)
  4179. {
  4180. int r;
  4181. r = kvm_apic_set_state(vcpu, s);
  4182. if (r)
  4183. return r;
  4184. update_cr8_intercept(vcpu);
  4185. return 0;
  4186. }
  4187. static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
  4188. {
  4189. /*
  4190. * We can accept userspace's request for interrupt injection
  4191. * as long as we have a place to store the interrupt number.
  4192. * The actual injection will happen when the CPU is able to
  4193. * deliver the interrupt.
  4194. */
  4195. if (kvm_cpu_has_extint(vcpu))
  4196. return false;
  4197. /* Acknowledging ExtINT does not happen if LINT0 is masked. */
  4198. return (!lapic_in_kernel(vcpu) ||
  4199. kvm_apic_accept_pic_intr(vcpu));
  4200. }
  4201. static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
  4202. {
  4203. /*
  4204. * Do not cause an interrupt window exit if an exception
  4205. * is pending or an event needs reinjection; userspace
  4206. * might want to inject the interrupt manually using KVM_SET_REGS
  4207. * or KVM_SET_SREGS. For that to work, we must be at an
  4208. * instruction boundary and with no events half-injected.
  4209. */
  4210. return (kvm_arch_interrupt_allowed(vcpu) &&
  4211. kvm_cpu_accept_dm_intr(vcpu) &&
  4212. !kvm_event_needs_reinjection(vcpu) &&
  4213. !kvm_is_exception_pending(vcpu));
  4214. }
  4215. static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
  4216. struct kvm_interrupt *irq)
  4217. {
  4218. if (irq->irq >= KVM_NR_INTERRUPTS)
  4219. return -EINVAL;
  4220. if (!irqchip_in_kernel(vcpu->kvm)) {
  4221. kvm_queue_interrupt(vcpu, irq->irq, false);
  4222. kvm_make_request(KVM_REQ_EVENT, vcpu);
  4223. return 0;
  4224. }
  4225. /*
  4226. * With in-kernel LAPIC, we only use this to inject EXTINT, so
  4227. * fail for in-kernel 8259.
  4228. */
  4229. if (pic_in_kernel(vcpu->kvm))
  4230. return -ENXIO;
  4231. if (vcpu->arch.pending_external_vector != -1)
  4232. return -EEXIST;
  4233. vcpu->arch.pending_external_vector = irq->irq;
  4234. kvm_make_request(KVM_REQ_EVENT, vcpu);
  4235. return 0;
  4236. }
  4237. static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
  4238. {
  4239. kvm_inject_nmi(vcpu);
  4240. return 0;
  4241. }
  4242. static int kvm_vcpu_ioctl_smi(struct kvm_vcpu *vcpu)
  4243. {
  4244. kvm_make_request(KVM_REQ_SMI, vcpu);
  4245. return 0;
  4246. }
  4247. static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
  4248. struct kvm_tpr_access_ctl *tac)
  4249. {
  4250. if (tac->flags)
  4251. return -EINVAL;
  4252. vcpu->arch.tpr_access_reporting = !!tac->enabled;
  4253. return 0;
  4254. }
  4255. static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
  4256. u64 mcg_cap)
  4257. {
  4258. int r;
  4259. unsigned bank_num = mcg_cap & 0xff, bank;
  4260. r = -EINVAL;
  4261. if (!bank_num || bank_num > KVM_MAX_MCE_BANKS)
  4262. goto out;
  4263. if (mcg_cap & ~(kvm_caps.supported_mce_cap | 0xff | 0xff0000))
  4264. goto out;
  4265. r = 0;
  4266. vcpu->arch.mcg_cap = mcg_cap;
  4267. /* Init IA32_MCG_CTL to all 1s */
  4268. if (mcg_cap & MCG_CTL_P)
  4269. vcpu->arch.mcg_ctl = ~(u64)0;
  4270. /* Init IA32_MCi_CTL to all 1s, IA32_MCi_CTL2 to all 0s */
  4271. for (bank = 0; bank < bank_num; bank++) {
  4272. vcpu->arch.mce_banks[bank*4] = ~(u64)0;
  4273. if (mcg_cap & MCG_CMCI_P)
  4274. vcpu->arch.mci_ctl2_banks[bank] = 0;
  4275. }
  4276. kvm_apic_after_set_mcg_cap(vcpu);
  4277. static_call(kvm_x86_setup_mce)(vcpu);
  4278. out:
  4279. return r;
  4280. }
  4281. /*
  4282. * Validate this is an UCNA (uncorrectable no action) error by checking the
  4283. * MCG_STATUS and MCi_STATUS registers:
  4284. * - none of the bits for Machine Check Exceptions are set
  4285. * - both the VAL (valid) and UC (uncorrectable) bits are set
  4286. * MCI_STATUS_PCC - Processor Context Corrupted
  4287. * MCI_STATUS_S - Signaled as a Machine Check Exception
  4288. * MCI_STATUS_AR - Software recoverable Action Required
  4289. */
  4290. static bool is_ucna(struct kvm_x86_mce *mce)
  4291. {
  4292. return !mce->mcg_status &&
  4293. !(mce->status & (MCI_STATUS_PCC | MCI_STATUS_S | MCI_STATUS_AR)) &&
  4294. (mce->status & MCI_STATUS_VAL) &&
  4295. (mce->status & MCI_STATUS_UC);
  4296. }
  4297. static int kvm_vcpu_x86_set_ucna(struct kvm_vcpu *vcpu, struct kvm_x86_mce *mce, u64* banks)
  4298. {
  4299. u64 mcg_cap = vcpu->arch.mcg_cap;
  4300. banks[1] = mce->status;
  4301. banks[2] = mce->addr;
  4302. banks[3] = mce->misc;
  4303. vcpu->arch.mcg_status = mce->mcg_status;
  4304. if (!(mcg_cap & MCG_CMCI_P) ||
  4305. !(vcpu->arch.mci_ctl2_banks[mce->bank] & MCI_CTL2_CMCI_EN))
  4306. return 0;
  4307. if (lapic_in_kernel(vcpu))
  4308. kvm_apic_local_deliver(vcpu->arch.apic, APIC_LVTCMCI);
  4309. return 0;
  4310. }
  4311. static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
  4312. struct kvm_x86_mce *mce)
  4313. {
  4314. u64 mcg_cap = vcpu->arch.mcg_cap;
  4315. unsigned bank_num = mcg_cap & 0xff;
  4316. u64 *banks = vcpu->arch.mce_banks;
  4317. if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
  4318. return -EINVAL;
  4319. banks += array_index_nospec(4 * mce->bank, 4 * bank_num);
  4320. if (is_ucna(mce))
  4321. return kvm_vcpu_x86_set_ucna(vcpu, mce, banks);
  4322. /*
  4323. * if IA32_MCG_CTL is not all 1s, the uncorrected error
  4324. * reporting is disabled
  4325. */
  4326. if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
  4327. vcpu->arch.mcg_ctl != ~(u64)0)
  4328. return 0;
  4329. /*
  4330. * if IA32_MCi_CTL is not all 1s, the uncorrected error
  4331. * reporting is disabled for the bank
  4332. */
  4333. if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
  4334. return 0;
  4335. if (mce->status & MCI_STATUS_UC) {
  4336. if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
  4337. !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
  4338. kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
  4339. return 0;
  4340. }
  4341. if (banks[1] & MCI_STATUS_VAL)
  4342. mce->status |= MCI_STATUS_OVER;
  4343. banks[2] = mce->addr;
  4344. banks[3] = mce->misc;
  4345. vcpu->arch.mcg_status = mce->mcg_status;
  4346. banks[1] = mce->status;
  4347. kvm_queue_exception(vcpu, MC_VECTOR);
  4348. } else if (!(banks[1] & MCI_STATUS_VAL)
  4349. || !(banks[1] & MCI_STATUS_UC)) {
  4350. if (banks[1] & MCI_STATUS_VAL)
  4351. mce->status |= MCI_STATUS_OVER;
  4352. banks[2] = mce->addr;
  4353. banks[3] = mce->misc;
  4354. banks[1] = mce->status;
  4355. } else
  4356. banks[1] |= MCI_STATUS_OVER;
  4357. return 0;
  4358. }
  4359. static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
  4360. struct kvm_vcpu_events *events)
  4361. {
  4362. struct kvm_queued_exception *ex;
  4363. process_nmi(vcpu);
  4364. if (kvm_check_request(KVM_REQ_SMI, vcpu))
  4365. process_smi(vcpu);
  4366. /*
  4367. * KVM's ABI only allows for one exception to be migrated. Luckily,
  4368. * the only time there can be two queued exceptions is if there's a
  4369. * non-exiting _injected_ exception, and a pending exiting exception.
  4370. * In that case, ignore the VM-Exiting exception as it's an extension
  4371. * of the injected exception.
  4372. */
  4373. if (vcpu->arch.exception_vmexit.pending &&
  4374. !vcpu->arch.exception.pending &&
  4375. !vcpu->arch.exception.injected)
  4376. ex = &vcpu->arch.exception_vmexit;
  4377. else
  4378. ex = &vcpu->arch.exception;
  4379. /*
  4380. * In guest mode, payload delivery should be deferred if the exception
  4381. * will be intercepted by L1, e.g. KVM should not modifying CR2 if L1
  4382. * intercepts #PF, ditto for DR6 and #DBs. If the per-VM capability,
  4383. * KVM_CAP_EXCEPTION_PAYLOAD, is not set, userspace may or may not
  4384. * propagate the payload and so it cannot be safely deferred. Deliver
  4385. * the payload if the capability hasn't been requested.
  4386. */
  4387. if (!vcpu->kvm->arch.exception_payload_enabled &&
  4388. ex->pending && ex->has_payload)
  4389. kvm_deliver_exception_payload(vcpu, ex);
  4390. /*
  4391. * The API doesn't provide the instruction length for software
  4392. * exceptions, so don't report them. As long as the guest RIP
  4393. * isn't advanced, we should expect to encounter the exception
  4394. * again.
  4395. */
  4396. if (kvm_exception_is_soft(ex->vector)) {
  4397. events->exception.injected = 0;
  4398. events->exception.pending = 0;
  4399. } else {
  4400. events->exception.injected = ex->injected;
  4401. events->exception.pending = ex->pending;
  4402. /*
  4403. * For ABI compatibility, deliberately conflate
  4404. * pending and injected exceptions when
  4405. * KVM_CAP_EXCEPTION_PAYLOAD isn't enabled.
  4406. */
  4407. if (!vcpu->kvm->arch.exception_payload_enabled)
  4408. events->exception.injected |= ex->pending;
  4409. }
  4410. events->exception.nr = ex->vector;
  4411. events->exception.has_error_code = ex->has_error_code;
  4412. events->exception.error_code = ex->error_code;
  4413. events->exception_has_payload = ex->has_payload;
  4414. events->exception_payload = ex->payload;
  4415. events->interrupt.injected =
  4416. vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
  4417. events->interrupt.nr = vcpu->arch.interrupt.nr;
  4418. events->interrupt.soft = 0;
  4419. events->interrupt.shadow = static_call(kvm_x86_get_interrupt_shadow)(vcpu);
  4420. events->nmi.injected = vcpu->arch.nmi_injected;
  4421. events->nmi.pending = vcpu->arch.nmi_pending != 0;
  4422. events->nmi.masked = static_call(kvm_x86_get_nmi_mask)(vcpu);
  4423. events->nmi.pad = 0;
  4424. events->sipi_vector = 0; /* never valid when reporting to user space */
  4425. events->smi.smm = is_smm(vcpu);
  4426. events->smi.pending = vcpu->arch.smi_pending;
  4427. events->smi.smm_inside_nmi =
  4428. !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
  4429. events->smi.latched_init = kvm_lapic_latched_init(vcpu);
  4430. events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
  4431. | KVM_VCPUEVENT_VALID_SHADOW
  4432. | KVM_VCPUEVENT_VALID_SMM);
  4433. if (vcpu->kvm->arch.exception_payload_enabled)
  4434. events->flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
  4435. if (vcpu->kvm->arch.triple_fault_event) {
  4436. events->triple_fault.pending = kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu);
  4437. events->flags |= KVM_VCPUEVENT_VALID_TRIPLE_FAULT;
  4438. }
  4439. memset(&events->reserved, 0, sizeof(events->reserved));
  4440. }
  4441. static void kvm_smm_changed(struct kvm_vcpu *vcpu, bool entering_smm);
  4442. static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
  4443. struct kvm_vcpu_events *events)
  4444. {
  4445. if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
  4446. | KVM_VCPUEVENT_VALID_SIPI_VECTOR
  4447. | KVM_VCPUEVENT_VALID_SHADOW
  4448. | KVM_VCPUEVENT_VALID_SMM
  4449. | KVM_VCPUEVENT_VALID_PAYLOAD
  4450. | KVM_VCPUEVENT_VALID_TRIPLE_FAULT))
  4451. return -EINVAL;
  4452. if (events->flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
  4453. if (!vcpu->kvm->arch.exception_payload_enabled)
  4454. return -EINVAL;
  4455. if (events->exception.pending)
  4456. events->exception.injected = 0;
  4457. else
  4458. events->exception_has_payload = 0;
  4459. } else {
  4460. events->exception.pending = 0;
  4461. events->exception_has_payload = 0;
  4462. }
  4463. if ((events->exception.injected || events->exception.pending) &&
  4464. (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
  4465. return -EINVAL;
  4466. /* INITs are latched while in SMM */
  4467. if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
  4468. (events->smi.smm || events->smi.pending) &&
  4469. vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
  4470. return -EINVAL;
  4471. process_nmi(vcpu);
  4472. /*
  4473. * Flag that userspace is stuffing an exception, the next KVM_RUN will
  4474. * morph the exception to a VM-Exit if appropriate. Do this only for
  4475. * pending exceptions, already-injected exceptions are not subject to
  4476. * intercpetion. Note, userspace that conflates pending and injected
  4477. * is hosed, and will incorrectly convert an injected exception into a
  4478. * pending exception, which in turn may cause a spurious VM-Exit.
  4479. */
  4480. vcpu->arch.exception_from_userspace = events->exception.pending;
  4481. vcpu->arch.exception_vmexit.pending = false;
  4482. vcpu->arch.exception.injected = events->exception.injected;
  4483. vcpu->arch.exception.pending = events->exception.pending;
  4484. vcpu->arch.exception.vector = events->exception.nr;
  4485. vcpu->arch.exception.has_error_code = events->exception.has_error_code;
  4486. vcpu->arch.exception.error_code = events->exception.error_code;
  4487. vcpu->arch.exception.has_payload = events->exception_has_payload;
  4488. vcpu->arch.exception.payload = events->exception_payload;
  4489. vcpu->arch.interrupt.injected = events->interrupt.injected;
  4490. vcpu->arch.interrupt.nr = events->interrupt.nr;
  4491. vcpu->arch.interrupt.soft = events->interrupt.soft;
  4492. if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
  4493. static_call(kvm_x86_set_interrupt_shadow)(vcpu,
  4494. events->interrupt.shadow);
  4495. vcpu->arch.nmi_injected = events->nmi.injected;
  4496. if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
  4497. vcpu->arch.nmi_pending = events->nmi.pending;
  4498. static_call(kvm_x86_set_nmi_mask)(vcpu, events->nmi.masked);
  4499. if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
  4500. lapic_in_kernel(vcpu))
  4501. vcpu->arch.apic->sipi_vector = events->sipi_vector;
  4502. if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
  4503. if (!!(vcpu->arch.hflags & HF_SMM_MASK) != events->smi.smm) {
  4504. kvm_leave_nested(vcpu);
  4505. kvm_smm_changed(vcpu, events->smi.smm);
  4506. }
  4507. vcpu->arch.smi_pending = events->smi.pending;
  4508. if (events->smi.smm) {
  4509. if (events->smi.smm_inside_nmi)
  4510. vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
  4511. else
  4512. vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
  4513. }
  4514. if (lapic_in_kernel(vcpu)) {
  4515. if (events->smi.latched_init)
  4516. set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
  4517. else
  4518. clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
  4519. }
  4520. }
  4521. if (events->flags & KVM_VCPUEVENT_VALID_TRIPLE_FAULT) {
  4522. if (!vcpu->kvm->arch.triple_fault_event)
  4523. return -EINVAL;
  4524. if (events->triple_fault.pending)
  4525. kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
  4526. else
  4527. kvm_clear_request(KVM_REQ_TRIPLE_FAULT, vcpu);
  4528. }
  4529. kvm_make_request(KVM_REQ_EVENT, vcpu);
  4530. return 0;
  4531. }
  4532. static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
  4533. struct kvm_debugregs *dbgregs)
  4534. {
  4535. unsigned long val;
  4536. memset(dbgregs, 0, sizeof(*dbgregs));
  4537. memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
  4538. kvm_get_dr(vcpu, 6, &val);
  4539. dbgregs->dr6 = val;
  4540. dbgregs->dr7 = vcpu->arch.dr7;
  4541. }
  4542. static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
  4543. struct kvm_debugregs *dbgregs)
  4544. {
  4545. if (dbgregs->flags)
  4546. return -EINVAL;
  4547. if (!kvm_dr6_valid(dbgregs->dr6))
  4548. return -EINVAL;
  4549. if (!kvm_dr7_valid(dbgregs->dr7))
  4550. return -EINVAL;
  4551. memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
  4552. kvm_update_dr0123(vcpu);
  4553. vcpu->arch.dr6 = dbgregs->dr6;
  4554. vcpu->arch.dr7 = dbgregs->dr7;
  4555. kvm_update_dr7(vcpu);
  4556. return 0;
  4557. }
  4558. static void kvm_vcpu_ioctl_x86_get_xsave2(struct kvm_vcpu *vcpu,
  4559. u8 *state, unsigned int size)
  4560. {
  4561. /*
  4562. * Only copy state for features that are enabled for the guest. The
  4563. * state itself isn't problematic, but setting bits in the header for
  4564. * features that are supported in *this* host but not exposed to the
  4565. * guest can result in KVM_SET_XSAVE failing when live migrating to a
  4566. * compatible host without the features that are NOT exposed to the
  4567. * guest.
  4568. *
  4569. * FP+SSE can always be saved/restored via KVM_{G,S}ET_XSAVE, even if
  4570. * XSAVE/XCRO are not exposed to the guest, and even if XSAVE isn't
  4571. * supported by the host.
  4572. */
  4573. u64 supported_xcr0 = vcpu->arch.guest_supported_xcr0 |
  4574. XFEATURE_MASK_FPSSE;
  4575. if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
  4576. return;
  4577. fpu_copy_guest_fpstate_to_uabi(&vcpu->arch.guest_fpu, state, size,
  4578. supported_xcr0, vcpu->arch.pkru);
  4579. }
  4580. static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
  4581. struct kvm_xsave *guest_xsave)
  4582. {
  4583. return kvm_vcpu_ioctl_x86_get_xsave2(vcpu, (void *)guest_xsave->region,
  4584. sizeof(guest_xsave->region));
  4585. }
  4586. static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
  4587. struct kvm_xsave *guest_xsave)
  4588. {
  4589. if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
  4590. return 0;
  4591. return fpu_copy_uabi_to_guest_fpstate(&vcpu->arch.guest_fpu,
  4592. guest_xsave->region,
  4593. kvm_caps.supported_xcr0,
  4594. &vcpu->arch.pkru);
  4595. }
  4596. static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
  4597. struct kvm_xcrs *guest_xcrs)
  4598. {
  4599. if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
  4600. guest_xcrs->nr_xcrs = 0;
  4601. return;
  4602. }
  4603. guest_xcrs->nr_xcrs = 1;
  4604. guest_xcrs->flags = 0;
  4605. guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
  4606. guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
  4607. }
  4608. static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
  4609. struct kvm_xcrs *guest_xcrs)
  4610. {
  4611. int i, r = 0;
  4612. if (!boot_cpu_has(X86_FEATURE_XSAVE))
  4613. return -EINVAL;
  4614. if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
  4615. return -EINVAL;
  4616. for (i = 0; i < guest_xcrs->nr_xcrs; i++)
  4617. /* Only support XCR0 currently */
  4618. if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
  4619. r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
  4620. guest_xcrs->xcrs[i].value);
  4621. break;
  4622. }
  4623. if (r)
  4624. r = -EINVAL;
  4625. return r;
  4626. }
  4627. /*
  4628. * kvm_set_guest_paused() indicates to the guest kernel that it has been
  4629. * stopped by the hypervisor. This function will be called from the host only.
  4630. * EINVAL is returned when the host attempts to set the flag for a guest that
  4631. * does not support pv clocks.
  4632. */
  4633. static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
  4634. {
  4635. if (!vcpu->arch.pv_time.active)
  4636. return -EINVAL;
  4637. vcpu->arch.pvclock_set_guest_stopped_request = true;
  4638. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  4639. return 0;
  4640. }
  4641. static int kvm_arch_tsc_has_attr(struct kvm_vcpu *vcpu,
  4642. struct kvm_device_attr *attr)
  4643. {
  4644. int r;
  4645. switch (attr->attr) {
  4646. case KVM_VCPU_TSC_OFFSET:
  4647. r = 0;
  4648. break;
  4649. default:
  4650. r = -ENXIO;
  4651. }
  4652. return r;
  4653. }
  4654. static int kvm_arch_tsc_get_attr(struct kvm_vcpu *vcpu,
  4655. struct kvm_device_attr *attr)
  4656. {
  4657. u64 __user *uaddr = kvm_get_attr_addr(attr);
  4658. int r;
  4659. if (IS_ERR(uaddr))
  4660. return PTR_ERR(uaddr);
  4661. switch (attr->attr) {
  4662. case KVM_VCPU_TSC_OFFSET:
  4663. r = -EFAULT;
  4664. if (put_user(vcpu->arch.l1_tsc_offset, uaddr))
  4665. break;
  4666. r = 0;
  4667. break;
  4668. default:
  4669. r = -ENXIO;
  4670. }
  4671. return r;
  4672. }
  4673. static int kvm_arch_tsc_set_attr(struct kvm_vcpu *vcpu,
  4674. struct kvm_device_attr *attr)
  4675. {
  4676. u64 __user *uaddr = kvm_get_attr_addr(attr);
  4677. struct kvm *kvm = vcpu->kvm;
  4678. int r;
  4679. if (IS_ERR(uaddr))
  4680. return PTR_ERR(uaddr);
  4681. switch (attr->attr) {
  4682. case KVM_VCPU_TSC_OFFSET: {
  4683. u64 offset, tsc, ns;
  4684. unsigned long flags;
  4685. bool matched;
  4686. r = -EFAULT;
  4687. if (get_user(offset, uaddr))
  4688. break;
  4689. raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
  4690. matched = (vcpu->arch.virtual_tsc_khz &&
  4691. kvm->arch.last_tsc_khz == vcpu->arch.virtual_tsc_khz &&
  4692. kvm->arch.last_tsc_offset == offset);
  4693. tsc = kvm_scale_tsc(rdtsc(), vcpu->arch.l1_tsc_scaling_ratio) + offset;
  4694. ns = get_kvmclock_base_ns();
  4695. __kvm_synchronize_tsc(vcpu, offset, tsc, ns, matched);
  4696. raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
  4697. r = 0;
  4698. break;
  4699. }
  4700. default:
  4701. r = -ENXIO;
  4702. }
  4703. return r;
  4704. }
  4705. static int kvm_vcpu_ioctl_device_attr(struct kvm_vcpu *vcpu,
  4706. unsigned int ioctl,
  4707. void __user *argp)
  4708. {
  4709. struct kvm_device_attr attr;
  4710. int r;
  4711. if (copy_from_user(&attr, argp, sizeof(attr)))
  4712. return -EFAULT;
  4713. if (attr.group != KVM_VCPU_TSC_CTRL)
  4714. return -ENXIO;
  4715. switch (ioctl) {
  4716. case KVM_HAS_DEVICE_ATTR:
  4717. r = kvm_arch_tsc_has_attr(vcpu, &attr);
  4718. break;
  4719. case KVM_GET_DEVICE_ATTR:
  4720. r = kvm_arch_tsc_get_attr(vcpu, &attr);
  4721. break;
  4722. case KVM_SET_DEVICE_ATTR:
  4723. r = kvm_arch_tsc_set_attr(vcpu, &attr);
  4724. break;
  4725. }
  4726. return r;
  4727. }
  4728. static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
  4729. struct kvm_enable_cap *cap)
  4730. {
  4731. int r;
  4732. uint16_t vmcs_version;
  4733. void __user *user_ptr;
  4734. if (cap->flags)
  4735. return -EINVAL;
  4736. switch (cap->cap) {
  4737. case KVM_CAP_HYPERV_SYNIC2:
  4738. if (cap->args[0])
  4739. return -EINVAL;
  4740. fallthrough;
  4741. case KVM_CAP_HYPERV_SYNIC:
  4742. if (!irqchip_in_kernel(vcpu->kvm))
  4743. return -EINVAL;
  4744. return kvm_hv_activate_synic(vcpu, cap->cap ==
  4745. KVM_CAP_HYPERV_SYNIC2);
  4746. case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
  4747. if (!kvm_x86_ops.nested_ops->enable_evmcs)
  4748. return -ENOTTY;
  4749. r = kvm_x86_ops.nested_ops->enable_evmcs(vcpu, &vmcs_version);
  4750. if (!r) {
  4751. user_ptr = (void __user *)(uintptr_t)cap->args[0];
  4752. if (copy_to_user(user_ptr, &vmcs_version,
  4753. sizeof(vmcs_version)))
  4754. r = -EFAULT;
  4755. }
  4756. return r;
  4757. case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
  4758. if (!kvm_x86_ops.enable_direct_tlbflush)
  4759. return -ENOTTY;
  4760. return static_call(kvm_x86_enable_direct_tlbflush)(vcpu);
  4761. case KVM_CAP_HYPERV_ENFORCE_CPUID:
  4762. return kvm_hv_set_enforce_cpuid(vcpu, cap->args[0]);
  4763. case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
  4764. vcpu->arch.pv_cpuid.enforce = cap->args[0];
  4765. if (vcpu->arch.pv_cpuid.enforce)
  4766. kvm_update_pv_runtime(vcpu);
  4767. return 0;
  4768. default:
  4769. return -EINVAL;
  4770. }
  4771. }
  4772. long kvm_arch_vcpu_ioctl(struct file *filp,
  4773. unsigned int ioctl, unsigned long arg)
  4774. {
  4775. struct kvm_vcpu *vcpu = filp->private_data;
  4776. void __user *argp = (void __user *)arg;
  4777. int r;
  4778. union {
  4779. struct kvm_sregs2 *sregs2;
  4780. struct kvm_lapic_state *lapic;
  4781. struct kvm_xsave *xsave;
  4782. struct kvm_xcrs *xcrs;
  4783. void *buffer;
  4784. } u;
  4785. vcpu_load(vcpu);
  4786. u.buffer = NULL;
  4787. switch (ioctl) {
  4788. case KVM_GET_LAPIC: {
  4789. r = -EINVAL;
  4790. if (!lapic_in_kernel(vcpu))
  4791. goto out;
  4792. u.lapic = kzalloc(sizeof(struct kvm_lapic_state),
  4793. GFP_KERNEL_ACCOUNT);
  4794. r = -ENOMEM;
  4795. if (!u.lapic)
  4796. goto out;
  4797. r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
  4798. if (r)
  4799. goto out;
  4800. r = -EFAULT;
  4801. if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
  4802. goto out;
  4803. r = 0;
  4804. break;
  4805. }
  4806. case KVM_SET_LAPIC: {
  4807. r = -EINVAL;
  4808. if (!lapic_in_kernel(vcpu))
  4809. goto out;
  4810. u.lapic = memdup_user(argp, sizeof(*u.lapic));
  4811. if (IS_ERR(u.lapic)) {
  4812. r = PTR_ERR(u.lapic);
  4813. goto out_nofree;
  4814. }
  4815. r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
  4816. break;
  4817. }
  4818. case KVM_INTERRUPT: {
  4819. struct kvm_interrupt irq;
  4820. r = -EFAULT;
  4821. if (copy_from_user(&irq, argp, sizeof(irq)))
  4822. goto out;
  4823. r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
  4824. break;
  4825. }
  4826. case KVM_NMI: {
  4827. r = kvm_vcpu_ioctl_nmi(vcpu);
  4828. break;
  4829. }
  4830. case KVM_SMI: {
  4831. r = kvm_vcpu_ioctl_smi(vcpu);
  4832. break;
  4833. }
  4834. case KVM_SET_CPUID: {
  4835. struct kvm_cpuid __user *cpuid_arg = argp;
  4836. struct kvm_cpuid cpuid;
  4837. r = -EFAULT;
  4838. if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
  4839. goto out;
  4840. r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
  4841. break;
  4842. }
  4843. case KVM_SET_CPUID2: {
  4844. struct kvm_cpuid2 __user *cpuid_arg = argp;
  4845. struct kvm_cpuid2 cpuid;
  4846. r = -EFAULT;
  4847. if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
  4848. goto out;
  4849. r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
  4850. cpuid_arg->entries);
  4851. break;
  4852. }
  4853. case KVM_GET_CPUID2: {
  4854. struct kvm_cpuid2 __user *cpuid_arg = argp;
  4855. struct kvm_cpuid2 cpuid;
  4856. r = -EFAULT;
  4857. if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
  4858. goto out;
  4859. r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
  4860. cpuid_arg->entries);
  4861. if (r)
  4862. goto out;
  4863. r = -EFAULT;
  4864. if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
  4865. goto out;
  4866. r = 0;
  4867. break;
  4868. }
  4869. case KVM_GET_MSRS: {
  4870. int idx = srcu_read_lock(&vcpu->kvm->srcu);
  4871. r = msr_io(vcpu, argp, do_get_msr, 1);
  4872. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  4873. break;
  4874. }
  4875. case KVM_SET_MSRS: {
  4876. int idx = srcu_read_lock(&vcpu->kvm->srcu);
  4877. r = msr_io(vcpu, argp, do_set_msr, 0);
  4878. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  4879. break;
  4880. }
  4881. case KVM_TPR_ACCESS_REPORTING: {
  4882. struct kvm_tpr_access_ctl tac;
  4883. r = -EFAULT;
  4884. if (copy_from_user(&tac, argp, sizeof(tac)))
  4885. goto out;
  4886. r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
  4887. if (r)
  4888. goto out;
  4889. r = -EFAULT;
  4890. if (copy_to_user(argp, &tac, sizeof(tac)))
  4891. goto out;
  4892. r = 0;
  4893. break;
  4894. };
  4895. case KVM_SET_VAPIC_ADDR: {
  4896. struct kvm_vapic_addr va;
  4897. int idx;
  4898. r = -EINVAL;
  4899. if (!lapic_in_kernel(vcpu))
  4900. goto out;
  4901. r = -EFAULT;
  4902. if (copy_from_user(&va, argp, sizeof(va)))
  4903. goto out;
  4904. idx = srcu_read_lock(&vcpu->kvm->srcu);
  4905. r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
  4906. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  4907. break;
  4908. }
  4909. case KVM_X86_SETUP_MCE: {
  4910. u64 mcg_cap;
  4911. r = -EFAULT;
  4912. if (copy_from_user(&mcg_cap, argp, sizeof(mcg_cap)))
  4913. goto out;
  4914. r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
  4915. break;
  4916. }
  4917. case KVM_X86_SET_MCE: {
  4918. struct kvm_x86_mce mce;
  4919. r = -EFAULT;
  4920. if (copy_from_user(&mce, argp, sizeof(mce)))
  4921. goto out;
  4922. r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
  4923. break;
  4924. }
  4925. case KVM_GET_VCPU_EVENTS: {
  4926. struct kvm_vcpu_events events;
  4927. kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
  4928. r = -EFAULT;
  4929. if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
  4930. break;
  4931. r = 0;
  4932. break;
  4933. }
  4934. case KVM_SET_VCPU_EVENTS: {
  4935. struct kvm_vcpu_events events;
  4936. r = -EFAULT;
  4937. if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
  4938. break;
  4939. r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
  4940. break;
  4941. }
  4942. case KVM_GET_DEBUGREGS: {
  4943. struct kvm_debugregs dbgregs;
  4944. kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
  4945. r = -EFAULT;
  4946. if (copy_to_user(argp, &dbgregs,
  4947. sizeof(struct kvm_debugregs)))
  4948. break;
  4949. r = 0;
  4950. break;
  4951. }
  4952. case KVM_SET_DEBUGREGS: {
  4953. struct kvm_debugregs dbgregs;
  4954. r = -EFAULT;
  4955. if (copy_from_user(&dbgregs, argp,
  4956. sizeof(struct kvm_debugregs)))
  4957. break;
  4958. r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
  4959. break;
  4960. }
  4961. case KVM_GET_XSAVE: {
  4962. r = -EINVAL;
  4963. if (vcpu->arch.guest_fpu.uabi_size > sizeof(struct kvm_xsave))
  4964. break;
  4965. u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL_ACCOUNT);
  4966. r = -ENOMEM;
  4967. if (!u.xsave)
  4968. break;
  4969. kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
  4970. r = -EFAULT;
  4971. if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
  4972. break;
  4973. r = 0;
  4974. break;
  4975. }
  4976. case KVM_SET_XSAVE: {
  4977. int size = vcpu->arch.guest_fpu.uabi_size;
  4978. u.xsave = memdup_user(argp, size);
  4979. if (IS_ERR(u.xsave)) {
  4980. r = PTR_ERR(u.xsave);
  4981. goto out_nofree;
  4982. }
  4983. r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
  4984. break;
  4985. }
  4986. case KVM_GET_XSAVE2: {
  4987. int size = vcpu->arch.guest_fpu.uabi_size;
  4988. u.xsave = kzalloc(size, GFP_KERNEL_ACCOUNT);
  4989. r = -ENOMEM;
  4990. if (!u.xsave)
  4991. break;
  4992. kvm_vcpu_ioctl_x86_get_xsave2(vcpu, u.buffer, size);
  4993. r = -EFAULT;
  4994. if (copy_to_user(argp, u.xsave, size))
  4995. break;
  4996. r = 0;
  4997. break;
  4998. }
  4999. case KVM_GET_XCRS: {
  5000. u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL_ACCOUNT);
  5001. r = -ENOMEM;
  5002. if (!u.xcrs)
  5003. break;
  5004. kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
  5005. r = -EFAULT;
  5006. if (copy_to_user(argp, u.xcrs,
  5007. sizeof(struct kvm_xcrs)))
  5008. break;
  5009. r = 0;
  5010. break;
  5011. }
  5012. case KVM_SET_XCRS: {
  5013. u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
  5014. if (IS_ERR(u.xcrs)) {
  5015. r = PTR_ERR(u.xcrs);
  5016. goto out_nofree;
  5017. }
  5018. r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
  5019. break;
  5020. }
  5021. case KVM_SET_TSC_KHZ: {
  5022. u32 user_tsc_khz;
  5023. r = -EINVAL;
  5024. user_tsc_khz = (u32)arg;
  5025. if (kvm_caps.has_tsc_control &&
  5026. user_tsc_khz >= kvm_caps.max_guest_tsc_khz)
  5027. goto out;
  5028. if (user_tsc_khz == 0)
  5029. user_tsc_khz = tsc_khz;
  5030. if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
  5031. r = 0;
  5032. goto out;
  5033. }
  5034. case KVM_GET_TSC_KHZ: {
  5035. r = vcpu->arch.virtual_tsc_khz;
  5036. goto out;
  5037. }
  5038. case KVM_KVMCLOCK_CTRL: {
  5039. r = kvm_set_guest_paused(vcpu);
  5040. goto out;
  5041. }
  5042. case KVM_ENABLE_CAP: {
  5043. struct kvm_enable_cap cap;
  5044. r = -EFAULT;
  5045. if (copy_from_user(&cap, argp, sizeof(cap)))
  5046. goto out;
  5047. r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
  5048. break;
  5049. }
  5050. case KVM_GET_NESTED_STATE: {
  5051. struct kvm_nested_state __user *user_kvm_nested_state = argp;
  5052. u32 user_data_size;
  5053. r = -EINVAL;
  5054. if (!kvm_x86_ops.nested_ops->get_state)
  5055. break;
  5056. BUILD_BUG_ON(sizeof(user_data_size) != sizeof(user_kvm_nested_state->size));
  5057. r = -EFAULT;
  5058. if (get_user(user_data_size, &user_kvm_nested_state->size))
  5059. break;
  5060. r = kvm_x86_ops.nested_ops->get_state(vcpu, user_kvm_nested_state,
  5061. user_data_size);
  5062. if (r < 0)
  5063. break;
  5064. if (r > user_data_size) {
  5065. if (put_user(r, &user_kvm_nested_state->size))
  5066. r = -EFAULT;
  5067. else
  5068. r = -E2BIG;
  5069. break;
  5070. }
  5071. r = 0;
  5072. break;
  5073. }
  5074. case KVM_SET_NESTED_STATE: {
  5075. struct kvm_nested_state __user *user_kvm_nested_state = argp;
  5076. struct kvm_nested_state kvm_state;
  5077. int idx;
  5078. r = -EINVAL;
  5079. if (!kvm_x86_ops.nested_ops->set_state)
  5080. break;
  5081. r = -EFAULT;
  5082. if (copy_from_user(&kvm_state, user_kvm_nested_state, sizeof(kvm_state)))
  5083. break;
  5084. r = -EINVAL;
  5085. if (kvm_state.size < sizeof(kvm_state))
  5086. break;
  5087. if (kvm_state.flags &
  5088. ~(KVM_STATE_NESTED_RUN_PENDING | KVM_STATE_NESTED_GUEST_MODE
  5089. | KVM_STATE_NESTED_EVMCS | KVM_STATE_NESTED_MTF_PENDING
  5090. | KVM_STATE_NESTED_GIF_SET))
  5091. break;
  5092. /* nested_run_pending implies guest_mode. */
  5093. if ((kvm_state.flags & KVM_STATE_NESTED_RUN_PENDING)
  5094. && !(kvm_state.flags & KVM_STATE_NESTED_GUEST_MODE))
  5095. break;
  5096. idx = srcu_read_lock(&vcpu->kvm->srcu);
  5097. r = kvm_x86_ops.nested_ops->set_state(vcpu, user_kvm_nested_state, &kvm_state);
  5098. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  5099. break;
  5100. }
  5101. case KVM_GET_SUPPORTED_HV_CPUID:
  5102. r = kvm_ioctl_get_supported_hv_cpuid(vcpu, argp);
  5103. break;
  5104. #ifdef CONFIG_KVM_XEN
  5105. case KVM_XEN_VCPU_GET_ATTR: {
  5106. struct kvm_xen_vcpu_attr xva;
  5107. r = -EFAULT;
  5108. if (copy_from_user(&xva, argp, sizeof(xva)))
  5109. goto out;
  5110. r = kvm_xen_vcpu_get_attr(vcpu, &xva);
  5111. if (!r && copy_to_user(argp, &xva, sizeof(xva)))
  5112. r = -EFAULT;
  5113. break;
  5114. }
  5115. case KVM_XEN_VCPU_SET_ATTR: {
  5116. struct kvm_xen_vcpu_attr xva;
  5117. r = -EFAULT;
  5118. if (copy_from_user(&xva, argp, sizeof(xva)))
  5119. goto out;
  5120. r = kvm_xen_vcpu_set_attr(vcpu, &xva);
  5121. break;
  5122. }
  5123. #endif
  5124. case KVM_GET_SREGS2: {
  5125. u.sregs2 = kzalloc(sizeof(struct kvm_sregs2), GFP_KERNEL);
  5126. r = -ENOMEM;
  5127. if (!u.sregs2)
  5128. goto out;
  5129. __get_sregs2(vcpu, u.sregs2);
  5130. r = -EFAULT;
  5131. if (copy_to_user(argp, u.sregs2, sizeof(struct kvm_sregs2)))
  5132. goto out;
  5133. r = 0;
  5134. break;
  5135. }
  5136. case KVM_SET_SREGS2: {
  5137. u.sregs2 = memdup_user(argp, sizeof(struct kvm_sregs2));
  5138. if (IS_ERR(u.sregs2)) {
  5139. r = PTR_ERR(u.sregs2);
  5140. u.sregs2 = NULL;
  5141. goto out;
  5142. }
  5143. r = __set_sregs2(vcpu, u.sregs2);
  5144. break;
  5145. }
  5146. case KVM_HAS_DEVICE_ATTR:
  5147. case KVM_GET_DEVICE_ATTR:
  5148. case KVM_SET_DEVICE_ATTR:
  5149. r = kvm_vcpu_ioctl_device_attr(vcpu, ioctl, argp);
  5150. break;
  5151. default:
  5152. r = -EINVAL;
  5153. }
  5154. out:
  5155. kfree(u.buffer);
  5156. out_nofree:
  5157. vcpu_put(vcpu);
  5158. return r;
  5159. }
  5160. vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
  5161. {
  5162. return VM_FAULT_SIGBUS;
  5163. }
  5164. static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
  5165. {
  5166. int ret;
  5167. if (addr > (unsigned int)(-3 * PAGE_SIZE))
  5168. return -EINVAL;
  5169. ret = static_call(kvm_x86_set_tss_addr)(kvm, addr);
  5170. return ret;
  5171. }
  5172. static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
  5173. u64 ident_addr)
  5174. {
  5175. return static_call(kvm_x86_set_identity_map_addr)(kvm, ident_addr);
  5176. }
  5177. static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
  5178. unsigned long kvm_nr_mmu_pages)
  5179. {
  5180. if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
  5181. return -EINVAL;
  5182. mutex_lock(&kvm->slots_lock);
  5183. kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
  5184. kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
  5185. mutex_unlock(&kvm->slots_lock);
  5186. return 0;
  5187. }
  5188. static unsigned long kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
  5189. {
  5190. return kvm->arch.n_max_mmu_pages;
  5191. }
  5192. static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
  5193. {
  5194. struct kvm_pic *pic = kvm->arch.vpic;
  5195. int r;
  5196. r = 0;
  5197. switch (chip->chip_id) {
  5198. case KVM_IRQCHIP_PIC_MASTER:
  5199. memcpy(&chip->chip.pic, &pic->pics[0],
  5200. sizeof(struct kvm_pic_state));
  5201. break;
  5202. case KVM_IRQCHIP_PIC_SLAVE:
  5203. memcpy(&chip->chip.pic, &pic->pics[1],
  5204. sizeof(struct kvm_pic_state));
  5205. break;
  5206. case KVM_IRQCHIP_IOAPIC:
  5207. kvm_get_ioapic(kvm, &chip->chip.ioapic);
  5208. break;
  5209. default:
  5210. r = -EINVAL;
  5211. break;
  5212. }
  5213. return r;
  5214. }
  5215. static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
  5216. {
  5217. struct kvm_pic *pic = kvm->arch.vpic;
  5218. int r;
  5219. r = 0;
  5220. switch (chip->chip_id) {
  5221. case KVM_IRQCHIP_PIC_MASTER:
  5222. spin_lock(&pic->lock);
  5223. memcpy(&pic->pics[0], &chip->chip.pic,
  5224. sizeof(struct kvm_pic_state));
  5225. spin_unlock(&pic->lock);
  5226. break;
  5227. case KVM_IRQCHIP_PIC_SLAVE:
  5228. spin_lock(&pic->lock);
  5229. memcpy(&pic->pics[1], &chip->chip.pic,
  5230. sizeof(struct kvm_pic_state));
  5231. spin_unlock(&pic->lock);
  5232. break;
  5233. case KVM_IRQCHIP_IOAPIC:
  5234. kvm_set_ioapic(kvm, &chip->chip.ioapic);
  5235. break;
  5236. default:
  5237. r = -EINVAL;
  5238. break;
  5239. }
  5240. kvm_pic_update_irq(pic);
  5241. return r;
  5242. }
  5243. static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
  5244. {
  5245. struct kvm_kpit_state *kps = &kvm->arch.vpit->pit_state;
  5246. BUILD_BUG_ON(sizeof(*ps) != sizeof(kps->channels));
  5247. mutex_lock(&kps->lock);
  5248. memcpy(ps, &kps->channels, sizeof(*ps));
  5249. mutex_unlock(&kps->lock);
  5250. return 0;
  5251. }
  5252. static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
  5253. {
  5254. int i;
  5255. struct kvm_pit *pit = kvm->arch.vpit;
  5256. mutex_lock(&pit->pit_state.lock);
  5257. memcpy(&pit->pit_state.channels, ps, sizeof(*ps));
  5258. for (i = 0; i < 3; i++)
  5259. kvm_pit_load_count(pit, i, ps->channels[i].count, 0);
  5260. mutex_unlock(&pit->pit_state.lock);
  5261. return 0;
  5262. }
  5263. static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
  5264. {
  5265. mutex_lock(&kvm->arch.vpit->pit_state.lock);
  5266. memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
  5267. sizeof(ps->channels));
  5268. ps->flags = kvm->arch.vpit->pit_state.flags;
  5269. mutex_unlock(&kvm->arch.vpit->pit_state.lock);
  5270. memset(&ps->reserved, 0, sizeof(ps->reserved));
  5271. return 0;
  5272. }
  5273. static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
  5274. {
  5275. int start = 0;
  5276. int i;
  5277. u32 prev_legacy, cur_legacy;
  5278. struct kvm_pit *pit = kvm->arch.vpit;
  5279. mutex_lock(&pit->pit_state.lock);
  5280. prev_legacy = pit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
  5281. cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
  5282. if (!prev_legacy && cur_legacy)
  5283. start = 1;
  5284. memcpy(&pit->pit_state.channels, &ps->channels,
  5285. sizeof(pit->pit_state.channels));
  5286. pit->pit_state.flags = ps->flags;
  5287. for (i = 0; i < 3; i++)
  5288. kvm_pit_load_count(pit, i, pit->pit_state.channels[i].count,
  5289. start && i == 0);
  5290. mutex_unlock(&pit->pit_state.lock);
  5291. return 0;
  5292. }
  5293. static int kvm_vm_ioctl_reinject(struct kvm *kvm,
  5294. struct kvm_reinject_control *control)
  5295. {
  5296. struct kvm_pit *pit = kvm->arch.vpit;
  5297. /* pit->pit_state.lock was overloaded to prevent userspace from getting
  5298. * an inconsistent state after running multiple KVM_REINJECT_CONTROL
  5299. * ioctls in parallel. Use a separate lock if that ioctl isn't rare.
  5300. */
  5301. mutex_lock(&pit->pit_state.lock);
  5302. kvm_pit_set_reinject(pit, control->pit_reinject);
  5303. mutex_unlock(&pit->pit_state.lock);
  5304. return 0;
  5305. }
  5306. void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot)
  5307. {
  5308. /*
  5309. * Flush all CPUs' dirty log buffers to the dirty_bitmap. Called
  5310. * before reporting dirty_bitmap to userspace. KVM flushes the buffers
  5311. * on all VM-Exits, thus we only need to kick running vCPUs to force a
  5312. * VM-Exit.
  5313. */
  5314. struct kvm_vcpu *vcpu;
  5315. unsigned long i;
  5316. kvm_for_each_vcpu(i, vcpu, kvm)
  5317. kvm_vcpu_kick(vcpu);
  5318. }
  5319. int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
  5320. bool line_status)
  5321. {
  5322. if (!irqchip_in_kernel(kvm))
  5323. return -ENXIO;
  5324. irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
  5325. irq_event->irq, irq_event->level,
  5326. line_status);
  5327. return 0;
  5328. }
  5329. int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
  5330. struct kvm_enable_cap *cap)
  5331. {
  5332. int r;
  5333. if (cap->flags)
  5334. return -EINVAL;
  5335. switch (cap->cap) {
  5336. case KVM_CAP_DISABLE_QUIRKS2:
  5337. r = -EINVAL;
  5338. if (cap->args[0] & ~KVM_X86_VALID_QUIRKS)
  5339. break;
  5340. fallthrough;
  5341. case KVM_CAP_DISABLE_QUIRKS:
  5342. kvm->arch.disabled_quirks = cap->args[0];
  5343. r = 0;
  5344. break;
  5345. case KVM_CAP_SPLIT_IRQCHIP: {
  5346. mutex_lock(&kvm->lock);
  5347. r = -EINVAL;
  5348. if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
  5349. goto split_irqchip_unlock;
  5350. r = -EEXIST;
  5351. if (irqchip_in_kernel(kvm))
  5352. goto split_irqchip_unlock;
  5353. if (kvm->created_vcpus)
  5354. goto split_irqchip_unlock;
  5355. r = kvm_setup_empty_irq_routing(kvm);
  5356. if (r)
  5357. goto split_irqchip_unlock;
  5358. /* Pairs with irqchip_in_kernel. */
  5359. smp_wmb();
  5360. kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
  5361. kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
  5362. kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_ABSENT);
  5363. r = 0;
  5364. split_irqchip_unlock:
  5365. mutex_unlock(&kvm->lock);
  5366. break;
  5367. }
  5368. case KVM_CAP_X2APIC_API:
  5369. r = -EINVAL;
  5370. if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
  5371. break;
  5372. if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
  5373. kvm->arch.x2apic_format = true;
  5374. if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
  5375. kvm->arch.x2apic_broadcast_quirk_disabled = true;
  5376. r = 0;
  5377. break;
  5378. case KVM_CAP_X86_DISABLE_EXITS:
  5379. r = -EINVAL;
  5380. if (cap->args[0] & ~KVM_X86_DISABLE_VALID_EXITS)
  5381. break;
  5382. if (cap->args[0] & KVM_X86_DISABLE_EXITS_PAUSE)
  5383. kvm->arch.pause_in_guest = true;
  5384. #define SMT_RSB_MSG "This processor is affected by the Cross-Thread Return Predictions vulnerability. " \
  5385. "KVM_CAP_X86_DISABLE_EXITS should only be used with SMT disabled or trusted guests."
  5386. if (!mitigate_smt_rsb) {
  5387. if (boot_cpu_has_bug(X86_BUG_SMT_RSB) && cpu_smt_possible() &&
  5388. (cap->args[0] & ~KVM_X86_DISABLE_EXITS_PAUSE))
  5389. pr_warn_once(SMT_RSB_MSG);
  5390. if ((cap->args[0] & KVM_X86_DISABLE_EXITS_MWAIT) &&
  5391. kvm_can_mwait_in_guest())
  5392. kvm->arch.mwait_in_guest = true;
  5393. if (cap->args[0] & KVM_X86_DISABLE_EXITS_HLT)
  5394. kvm->arch.hlt_in_guest = true;
  5395. if (cap->args[0] & KVM_X86_DISABLE_EXITS_CSTATE)
  5396. kvm->arch.cstate_in_guest = true;
  5397. }
  5398. r = 0;
  5399. break;
  5400. case KVM_CAP_MSR_PLATFORM_INFO:
  5401. kvm->arch.guest_can_read_msr_platform_info = cap->args[0];
  5402. r = 0;
  5403. break;
  5404. case KVM_CAP_EXCEPTION_PAYLOAD:
  5405. kvm->arch.exception_payload_enabled = cap->args[0];
  5406. r = 0;
  5407. break;
  5408. case KVM_CAP_X86_TRIPLE_FAULT_EVENT:
  5409. kvm->arch.triple_fault_event = cap->args[0];
  5410. r = 0;
  5411. break;
  5412. case KVM_CAP_X86_USER_SPACE_MSR:
  5413. r = -EINVAL;
  5414. if (cap->args[0] & ~(KVM_MSR_EXIT_REASON_INVAL |
  5415. KVM_MSR_EXIT_REASON_UNKNOWN |
  5416. KVM_MSR_EXIT_REASON_FILTER))
  5417. break;
  5418. kvm->arch.user_space_msr_mask = cap->args[0];
  5419. r = 0;
  5420. break;
  5421. case KVM_CAP_X86_BUS_LOCK_EXIT:
  5422. r = -EINVAL;
  5423. if (cap->args[0] & ~KVM_BUS_LOCK_DETECTION_VALID_MODE)
  5424. break;
  5425. if ((cap->args[0] & KVM_BUS_LOCK_DETECTION_OFF) &&
  5426. (cap->args[0] & KVM_BUS_LOCK_DETECTION_EXIT))
  5427. break;
  5428. if (kvm_caps.has_bus_lock_exit &&
  5429. cap->args[0] & KVM_BUS_LOCK_DETECTION_EXIT)
  5430. kvm->arch.bus_lock_detection_enabled = true;
  5431. r = 0;
  5432. break;
  5433. #ifdef CONFIG_X86_SGX_KVM
  5434. case KVM_CAP_SGX_ATTRIBUTE: {
  5435. unsigned long allowed_attributes = 0;
  5436. r = sgx_set_attribute(&allowed_attributes, cap->args[0]);
  5437. if (r)
  5438. break;
  5439. /* KVM only supports the PROVISIONKEY privileged attribute. */
  5440. if ((allowed_attributes & SGX_ATTR_PROVISIONKEY) &&
  5441. !(allowed_attributes & ~SGX_ATTR_PROVISIONKEY))
  5442. kvm->arch.sgx_provisioning_allowed = true;
  5443. else
  5444. r = -EINVAL;
  5445. break;
  5446. }
  5447. #endif
  5448. case KVM_CAP_VM_COPY_ENC_CONTEXT_FROM:
  5449. r = -EINVAL;
  5450. if (!kvm_x86_ops.vm_copy_enc_context_from)
  5451. break;
  5452. r = static_call(kvm_x86_vm_copy_enc_context_from)(kvm, cap->args[0]);
  5453. break;
  5454. case KVM_CAP_VM_MOVE_ENC_CONTEXT_FROM:
  5455. r = -EINVAL;
  5456. if (!kvm_x86_ops.vm_move_enc_context_from)
  5457. break;
  5458. r = static_call(kvm_x86_vm_move_enc_context_from)(kvm, cap->args[0]);
  5459. break;
  5460. case KVM_CAP_EXIT_HYPERCALL:
  5461. if (cap->args[0] & ~KVM_EXIT_HYPERCALL_VALID_MASK) {
  5462. r = -EINVAL;
  5463. break;
  5464. }
  5465. kvm->arch.hypercall_exit_enabled = cap->args[0];
  5466. r = 0;
  5467. break;
  5468. case KVM_CAP_EXIT_ON_EMULATION_FAILURE:
  5469. r = -EINVAL;
  5470. if (cap->args[0] & ~1)
  5471. break;
  5472. kvm->arch.exit_on_emulation_error = cap->args[0];
  5473. r = 0;
  5474. break;
  5475. case KVM_CAP_PMU_CAPABILITY:
  5476. r = -EINVAL;
  5477. if (!enable_pmu || (cap->args[0] & ~KVM_CAP_PMU_VALID_MASK))
  5478. break;
  5479. mutex_lock(&kvm->lock);
  5480. if (!kvm->created_vcpus) {
  5481. kvm->arch.enable_pmu = !(cap->args[0] & KVM_PMU_CAP_DISABLE);
  5482. r = 0;
  5483. }
  5484. mutex_unlock(&kvm->lock);
  5485. break;
  5486. case KVM_CAP_MAX_VCPU_ID:
  5487. r = -EINVAL;
  5488. if (cap->args[0] > KVM_MAX_VCPU_IDS)
  5489. break;
  5490. mutex_lock(&kvm->lock);
  5491. if (kvm->arch.max_vcpu_ids == cap->args[0]) {
  5492. r = 0;
  5493. } else if (!kvm->arch.max_vcpu_ids) {
  5494. kvm->arch.max_vcpu_ids = cap->args[0];
  5495. r = 0;
  5496. }
  5497. mutex_unlock(&kvm->lock);
  5498. break;
  5499. case KVM_CAP_X86_NOTIFY_VMEXIT:
  5500. r = -EINVAL;
  5501. if ((u32)cap->args[0] & ~KVM_X86_NOTIFY_VMEXIT_VALID_BITS)
  5502. break;
  5503. if (!kvm_caps.has_notify_vmexit)
  5504. break;
  5505. if (!((u32)cap->args[0] & KVM_X86_NOTIFY_VMEXIT_ENABLED))
  5506. break;
  5507. mutex_lock(&kvm->lock);
  5508. if (!kvm->created_vcpus) {
  5509. kvm->arch.notify_window = cap->args[0] >> 32;
  5510. kvm->arch.notify_vmexit_flags = (u32)cap->args[0];
  5511. r = 0;
  5512. }
  5513. mutex_unlock(&kvm->lock);
  5514. break;
  5515. case KVM_CAP_VM_DISABLE_NX_HUGE_PAGES:
  5516. r = -EINVAL;
  5517. /*
  5518. * Since the risk of disabling NX hugepages is a guest crashing
  5519. * the system, ensure the userspace process has permission to
  5520. * reboot the system.
  5521. *
  5522. * Note that unlike the reboot() syscall, the process must have
  5523. * this capability in the root namespace because exposing
  5524. * /dev/kvm into a container does not limit the scope of the
  5525. * iTLB multihit bug to that container. In other words,
  5526. * this must use capable(), not ns_capable().
  5527. */
  5528. if (!capable(CAP_SYS_BOOT)) {
  5529. r = -EPERM;
  5530. break;
  5531. }
  5532. if (cap->args[0])
  5533. break;
  5534. mutex_lock(&kvm->lock);
  5535. if (!kvm->created_vcpus) {
  5536. kvm->arch.disable_nx_huge_pages = true;
  5537. r = 0;
  5538. }
  5539. mutex_unlock(&kvm->lock);
  5540. break;
  5541. default:
  5542. r = -EINVAL;
  5543. break;
  5544. }
  5545. return r;
  5546. }
  5547. static struct kvm_x86_msr_filter *kvm_alloc_msr_filter(bool default_allow)
  5548. {
  5549. struct kvm_x86_msr_filter *msr_filter;
  5550. msr_filter = kzalloc(sizeof(*msr_filter), GFP_KERNEL_ACCOUNT);
  5551. if (!msr_filter)
  5552. return NULL;
  5553. msr_filter->default_allow = default_allow;
  5554. return msr_filter;
  5555. }
  5556. static void kvm_free_msr_filter(struct kvm_x86_msr_filter *msr_filter)
  5557. {
  5558. u32 i;
  5559. if (!msr_filter)
  5560. return;
  5561. for (i = 0; i < msr_filter->count; i++)
  5562. kfree(msr_filter->ranges[i].bitmap);
  5563. kfree(msr_filter);
  5564. }
  5565. static int kvm_add_msr_filter(struct kvm_x86_msr_filter *msr_filter,
  5566. struct kvm_msr_filter_range *user_range)
  5567. {
  5568. unsigned long *bitmap = NULL;
  5569. size_t bitmap_size;
  5570. if (!user_range->nmsrs)
  5571. return 0;
  5572. if (user_range->flags & ~(KVM_MSR_FILTER_READ | KVM_MSR_FILTER_WRITE))
  5573. return -EINVAL;
  5574. if (!user_range->flags)
  5575. return -EINVAL;
  5576. bitmap_size = BITS_TO_LONGS(user_range->nmsrs) * sizeof(long);
  5577. if (!bitmap_size || bitmap_size > KVM_MSR_FILTER_MAX_BITMAP_SIZE)
  5578. return -EINVAL;
  5579. bitmap = memdup_user((__user u8*)user_range->bitmap, bitmap_size);
  5580. if (IS_ERR(bitmap))
  5581. return PTR_ERR(bitmap);
  5582. msr_filter->ranges[msr_filter->count] = (struct msr_bitmap_range) {
  5583. .flags = user_range->flags,
  5584. .base = user_range->base,
  5585. .nmsrs = user_range->nmsrs,
  5586. .bitmap = bitmap,
  5587. };
  5588. msr_filter->count++;
  5589. return 0;
  5590. }
  5591. static int kvm_vm_ioctl_set_msr_filter(struct kvm *kvm,
  5592. struct kvm_msr_filter *filter)
  5593. {
  5594. struct kvm_x86_msr_filter *new_filter, *old_filter;
  5595. bool default_allow;
  5596. bool empty = true;
  5597. int r = 0;
  5598. u32 i;
  5599. if (filter->flags & ~KVM_MSR_FILTER_DEFAULT_DENY)
  5600. return -EINVAL;
  5601. for (i = 0; i < ARRAY_SIZE(filter->ranges); i++)
  5602. empty &= !filter->ranges[i].nmsrs;
  5603. default_allow = !(filter->flags & KVM_MSR_FILTER_DEFAULT_DENY);
  5604. if (empty && !default_allow)
  5605. return -EINVAL;
  5606. new_filter = kvm_alloc_msr_filter(default_allow);
  5607. if (!new_filter)
  5608. return -ENOMEM;
  5609. for (i = 0; i < ARRAY_SIZE(filter->ranges); i++) {
  5610. r = kvm_add_msr_filter(new_filter, &filter->ranges[i]);
  5611. if (r) {
  5612. kvm_free_msr_filter(new_filter);
  5613. return r;
  5614. }
  5615. }
  5616. mutex_lock(&kvm->lock);
  5617. /* The per-VM filter is protected by kvm->lock... */
  5618. old_filter = srcu_dereference_check(kvm->arch.msr_filter, &kvm->srcu, 1);
  5619. rcu_assign_pointer(kvm->arch.msr_filter, new_filter);
  5620. synchronize_srcu(&kvm->srcu);
  5621. kvm_free_msr_filter(old_filter);
  5622. kvm_make_all_cpus_request(kvm, KVM_REQ_MSR_FILTER_CHANGED);
  5623. mutex_unlock(&kvm->lock);
  5624. return 0;
  5625. }
  5626. #ifdef CONFIG_KVM_COMPAT
  5627. /* for KVM_X86_SET_MSR_FILTER */
  5628. struct kvm_msr_filter_range_compat {
  5629. __u32 flags;
  5630. __u32 nmsrs;
  5631. __u32 base;
  5632. __u32 bitmap;
  5633. };
  5634. struct kvm_msr_filter_compat {
  5635. __u32 flags;
  5636. struct kvm_msr_filter_range_compat ranges[KVM_MSR_FILTER_MAX_RANGES];
  5637. };
  5638. #define KVM_X86_SET_MSR_FILTER_COMPAT _IOW(KVMIO, 0xc6, struct kvm_msr_filter_compat)
  5639. long kvm_arch_vm_compat_ioctl(struct file *filp, unsigned int ioctl,
  5640. unsigned long arg)
  5641. {
  5642. void __user *argp = (void __user *)arg;
  5643. struct kvm *kvm = filp->private_data;
  5644. long r = -ENOTTY;
  5645. switch (ioctl) {
  5646. case KVM_X86_SET_MSR_FILTER_COMPAT: {
  5647. struct kvm_msr_filter __user *user_msr_filter = argp;
  5648. struct kvm_msr_filter_compat filter_compat;
  5649. struct kvm_msr_filter filter;
  5650. int i;
  5651. if (copy_from_user(&filter_compat, user_msr_filter,
  5652. sizeof(filter_compat)))
  5653. return -EFAULT;
  5654. filter.flags = filter_compat.flags;
  5655. for (i = 0; i < ARRAY_SIZE(filter.ranges); i++) {
  5656. struct kvm_msr_filter_range_compat *cr;
  5657. cr = &filter_compat.ranges[i];
  5658. filter.ranges[i] = (struct kvm_msr_filter_range) {
  5659. .flags = cr->flags,
  5660. .nmsrs = cr->nmsrs,
  5661. .base = cr->base,
  5662. .bitmap = (__u8 *)(ulong)cr->bitmap,
  5663. };
  5664. }
  5665. r = kvm_vm_ioctl_set_msr_filter(kvm, &filter);
  5666. break;
  5667. }
  5668. }
  5669. return r;
  5670. }
  5671. #endif
  5672. #ifdef CONFIG_HAVE_KVM_PM_NOTIFIER
  5673. static int kvm_arch_suspend_notifier(struct kvm *kvm)
  5674. {
  5675. struct kvm_vcpu *vcpu;
  5676. unsigned long i;
  5677. int ret = 0;
  5678. mutex_lock(&kvm->lock);
  5679. kvm_for_each_vcpu(i, vcpu, kvm) {
  5680. if (!vcpu->arch.pv_time.active)
  5681. continue;
  5682. ret = kvm_set_guest_paused(vcpu);
  5683. if (ret) {
  5684. kvm_err("Failed to pause guest VCPU%d: %d\n",
  5685. vcpu->vcpu_id, ret);
  5686. break;
  5687. }
  5688. }
  5689. mutex_unlock(&kvm->lock);
  5690. return ret ? NOTIFY_BAD : NOTIFY_DONE;
  5691. }
  5692. int kvm_arch_pm_notifier(struct kvm *kvm, unsigned long state)
  5693. {
  5694. switch (state) {
  5695. case PM_HIBERNATION_PREPARE:
  5696. case PM_SUSPEND_PREPARE:
  5697. return kvm_arch_suspend_notifier(kvm);
  5698. }
  5699. return NOTIFY_DONE;
  5700. }
  5701. #endif /* CONFIG_HAVE_KVM_PM_NOTIFIER */
  5702. static int kvm_vm_ioctl_get_clock(struct kvm *kvm, void __user *argp)
  5703. {
  5704. struct kvm_clock_data data = { 0 };
  5705. get_kvmclock(kvm, &data);
  5706. if (copy_to_user(argp, &data, sizeof(data)))
  5707. return -EFAULT;
  5708. return 0;
  5709. }
  5710. static int kvm_vm_ioctl_set_clock(struct kvm *kvm, void __user *argp)
  5711. {
  5712. struct kvm_arch *ka = &kvm->arch;
  5713. struct kvm_clock_data data;
  5714. u64 now_raw_ns;
  5715. if (copy_from_user(&data, argp, sizeof(data)))
  5716. return -EFAULT;
  5717. /*
  5718. * Only KVM_CLOCK_REALTIME is used, but allow passing the
  5719. * result of KVM_GET_CLOCK back to KVM_SET_CLOCK.
  5720. */
  5721. if (data.flags & ~KVM_CLOCK_VALID_FLAGS)
  5722. return -EINVAL;
  5723. kvm_hv_request_tsc_page_update(kvm);
  5724. kvm_start_pvclock_update(kvm);
  5725. pvclock_update_vm_gtod_copy(kvm);
  5726. /*
  5727. * This pairs with kvm_guest_time_update(): when masterclock is
  5728. * in use, we use master_kernel_ns + kvmclock_offset to set
  5729. * unsigned 'system_time' so if we use get_kvmclock_ns() (which
  5730. * is slightly ahead) here we risk going negative on unsigned
  5731. * 'system_time' when 'data.clock' is very small.
  5732. */
  5733. if (data.flags & KVM_CLOCK_REALTIME) {
  5734. u64 now_real_ns = ktime_get_real_ns();
  5735. /*
  5736. * Avoid stepping the kvmclock backwards.
  5737. */
  5738. if (now_real_ns > data.realtime)
  5739. data.clock += now_real_ns - data.realtime;
  5740. }
  5741. if (ka->use_master_clock)
  5742. now_raw_ns = ka->master_kernel_ns;
  5743. else
  5744. now_raw_ns = get_kvmclock_base_ns();
  5745. ka->kvmclock_offset = data.clock - now_raw_ns;
  5746. kvm_end_pvclock_update(kvm);
  5747. return 0;
  5748. }
  5749. long kvm_arch_vm_ioctl(struct file *filp,
  5750. unsigned int ioctl, unsigned long arg)
  5751. {
  5752. struct kvm *kvm = filp->private_data;
  5753. void __user *argp = (void __user *)arg;
  5754. int r = -ENOTTY;
  5755. /*
  5756. * This union makes it completely explicit to gcc-3.x
  5757. * that these two variables' stack usage should be
  5758. * combined, not added together.
  5759. */
  5760. union {
  5761. struct kvm_pit_state ps;
  5762. struct kvm_pit_state2 ps2;
  5763. struct kvm_pit_config pit_config;
  5764. } u;
  5765. switch (ioctl) {
  5766. case KVM_SET_TSS_ADDR:
  5767. r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
  5768. break;
  5769. case KVM_SET_IDENTITY_MAP_ADDR: {
  5770. u64 ident_addr;
  5771. mutex_lock(&kvm->lock);
  5772. r = -EINVAL;
  5773. if (kvm->created_vcpus)
  5774. goto set_identity_unlock;
  5775. r = -EFAULT;
  5776. if (copy_from_user(&ident_addr, argp, sizeof(ident_addr)))
  5777. goto set_identity_unlock;
  5778. r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
  5779. set_identity_unlock:
  5780. mutex_unlock(&kvm->lock);
  5781. break;
  5782. }
  5783. case KVM_SET_NR_MMU_PAGES:
  5784. r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
  5785. break;
  5786. case KVM_GET_NR_MMU_PAGES:
  5787. r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
  5788. break;
  5789. case KVM_CREATE_IRQCHIP: {
  5790. mutex_lock(&kvm->lock);
  5791. r = -EEXIST;
  5792. if (irqchip_in_kernel(kvm))
  5793. goto create_irqchip_unlock;
  5794. r = -EINVAL;
  5795. if (kvm->created_vcpus)
  5796. goto create_irqchip_unlock;
  5797. r = kvm_pic_init(kvm);
  5798. if (r)
  5799. goto create_irqchip_unlock;
  5800. r = kvm_ioapic_init(kvm);
  5801. if (r) {
  5802. kvm_pic_destroy(kvm);
  5803. goto create_irqchip_unlock;
  5804. }
  5805. r = kvm_setup_default_irq_routing(kvm);
  5806. if (r) {
  5807. kvm_ioapic_destroy(kvm);
  5808. kvm_pic_destroy(kvm);
  5809. goto create_irqchip_unlock;
  5810. }
  5811. /* Write kvm->irq_routing before enabling irqchip_in_kernel. */
  5812. smp_wmb();
  5813. kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
  5814. kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_ABSENT);
  5815. create_irqchip_unlock:
  5816. mutex_unlock(&kvm->lock);
  5817. break;
  5818. }
  5819. case KVM_CREATE_PIT:
  5820. u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
  5821. goto create_pit;
  5822. case KVM_CREATE_PIT2:
  5823. r = -EFAULT;
  5824. if (copy_from_user(&u.pit_config, argp,
  5825. sizeof(struct kvm_pit_config)))
  5826. goto out;
  5827. create_pit:
  5828. mutex_lock(&kvm->lock);
  5829. r = -EEXIST;
  5830. if (kvm->arch.vpit)
  5831. goto create_pit_unlock;
  5832. r = -ENOMEM;
  5833. kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
  5834. if (kvm->arch.vpit)
  5835. r = 0;
  5836. create_pit_unlock:
  5837. mutex_unlock(&kvm->lock);
  5838. break;
  5839. case KVM_GET_IRQCHIP: {
  5840. /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
  5841. struct kvm_irqchip *chip;
  5842. chip = memdup_user(argp, sizeof(*chip));
  5843. if (IS_ERR(chip)) {
  5844. r = PTR_ERR(chip);
  5845. goto out;
  5846. }
  5847. r = -ENXIO;
  5848. if (!irqchip_kernel(kvm))
  5849. goto get_irqchip_out;
  5850. r = kvm_vm_ioctl_get_irqchip(kvm, chip);
  5851. if (r)
  5852. goto get_irqchip_out;
  5853. r = -EFAULT;
  5854. if (copy_to_user(argp, chip, sizeof(*chip)))
  5855. goto get_irqchip_out;
  5856. r = 0;
  5857. get_irqchip_out:
  5858. kfree(chip);
  5859. break;
  5860. }
  5861. case KVM_SET_IRQCHIP: {
  5862. /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
  5863. struct kvm_irqchip *chip;
  5864. chip = memdup_user(argp, sizeof(*chip));
  5865. if (IS_ERR(chip)) {
  5866. r = PTR_ERR(chip);
  5867. goto out;
  5868. }
  5869. r = -ENXIO;
  5870. if (!irqchip_kernel(kvm))
  5871. goto set_irqchip_out;
  5872. r = kvm_vm_ioctl_set_irqchip(kvm, chip);
  5873. set_irqchip_out:
  5874. kfree(chip);
  5875. break;
  5876. }
  5877. case KVM_GET_PIT: {
  5878. r = -EFAULT;
  5879. if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
  5880. goto out;
  5881. r = -ENXIO;
  5882. if (!kvm->arch.vpit)
  5883. goto out;
  5884. r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
  5885. if (r)
  5886. goto out;
  5887. r = -EFAULT;
  5888. if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
  5889. goto out;
  5890. r = 0;
  5891. break;
  5892. }
  5893. case KVM_SET_PIT: {
  5894. r = -EFAULT;
  5895. if (copy_from_user(&u.ps, argp, sizeof(u.ps)))
  5896. goto out;
  5897. mutex_lock(&kvm->lock);
  5898. r = -ENXIO;
  5899. if (!kvm->arch.vpit)
  5900. goto set_pit_out;
  5901. r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
  5902. set_pit_out:
  5903. mutex_unlock(&kvm->lock);
  5904. break;
  5905. }
  5906. case KVM_GET_PIT2: {
  5907. r = -ENXIO;
  5908. if (!kvm->arch.vpit)
  5909. goto out;
  5910. r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
  5911. if (r)
  5912. goto out;
  5913. r = -EFAULT;
  5914. if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
  5915. goto out;
  5916. r = 0;
  5917. break;
  5918. }
  5919. case KVM_SET_PIT2: {
  5920. r = -EFAULT;
  5921. if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
  5922. goto out;
  5923. mutex_lock(&kvm->lock);
  5924. r = -ENXIO;
  5925. if (!kvm->arch.vpit)
  5926. goto set_pit2_out;
  5927. r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
  5928. set_pit2_out:
  5929. mutex_unlock(&kvm->lock);
  5930. break;
  5931. }
  5932. case KVM_REINJECT_CONTROL: {
  5933. struct kvm_reinject_control control;
  5934. r = -EFAULT;
  5935. if (copy_from_user(&control, argp, sizeof(control)))
  5936. goto out;
  5937. r = -ENXIO;
  5938. if (!kvm->arch.vpit)
  5939. goto out;
  5940. r = kvm_vm_ioctl_reinject(kvm, &control);
  5941. break;
  5942. }
  5943. case KVM_SET_BOOT_CPU_ID:
  5944. r = 0;
  5945. mutex_lock(&kvm->lock);
  5946. if (kvm->created_vcpus)
  5947. r = -EBUSY;
  5948. else
  5949. kvm->arch.bsp_vcpu_id = arg;
  5950. mutex_unlock(&kvm->lock);
  5951. break;
  5952. #ifdef CONFIG_KVM_XEN
  5953. case KVM_XEN_HVM_CONFIG: {
  5954. struct kvm_xen_hvm_config xhc;
  5955. r = -EFAULT;
  5956. if (copy_from_user(&xhc, argp, sizeof(xhc)))
  5957. goto out;
  5958. r = kvm_xen_hvm_config(kvm, &xhc);
  5959. break;
  5960. }
  5961. case KVM_XEN_HVM_GET_ATTR: {
  5962. struct kvm_xen_hvm_attr xha;
  5963. r = -EFAULT;
  5964. if (copy_from_user(&xha, argp, sizeof(xha)))
  5965. goto out;
  5966. r = kvm_xen_hvm_get_attr(kvm, &xha);
  5967. if (!r && copy_to_user(argp, &xha, sizeof(xha)))
  5968. r = -EFAULT;
  5969. break;
  5970. }
  5971. case KVM_XEN_HVM_SET_ATTR: {
  5972. struct kvm_xen_hvm_attr xha;
  5973. r = -EFAULT;
  5974. if (copy_from_user(&xha, argp, sizeof(xha)))
  5975. goto out;
  5976. r = kvm_xen_hvm_set_attr(kvm, &xha);
  5977. break;
  5978. }
  5979. case KVM_XEN_HVM_EVTCHN_SEND: {
  5980. struct kvm_irq_routing_xen_evtchn uxe;
  5981. r = -EFAULT;
  5982. if (copy_from_user(&uxe, argp, sizeof(uxe)))
  5983. goto out;
  5984. r = kvm_xen_hvm_evtchn_send(kvm, &uxe);
  5985. break;
  5986. }
  5987. #endif
  5988. case KVM_SET_CLOCK:
  5989. r = kvm_vm_ioctl_set_clock(kvm, argp);
  5990. break;
  5991. case KVM_GET_CLOCK:
  5992. r = kvm_vm_ioctl_get_clock(kvm, argp);
  5993. break;
  5994. case KVM_SET_TSC_KHZ: {
  5995. u32 user_tsc_khz;
  5996. r = -EINVAL;
  5997. user_tsc_khz = (u32)arg;
  5998. if (kvm_caps.has_tsc_control &&
  5999. user_tsc_khz >= kvm_caps.max_guest_tsc_khz)
  6000. goto out;
  6001. if (user_tsc_khz == 0)
  6002. user_tsc_khz = tsc_khz;
  6003. WRITE_ONCE(kvm->arch.default_tsc_khz, user_tsc_khz);
  6004. r = 0;
  6005. goto out;
  6006. }
  6007. case KVM_GET_TSC_KHZ: {
  6008. r = READ_ONCE(kvm->arch.default_tsc_khz);
  6009. goto out;
  6010. }
  6011. case KVM_MEMORY_ENCRYPT_OP: {
  6012. r = -ENOTTY;
  6013. if (!kvm_x86_ops.mem_enc_ioctl)
  6014. goto out;
  6015. r = static_call(kvm_x86_mem_enc_ioctl)(kvm, argp);
  6016. break;
  6017. }
  6018. case KVM_MEMORY_ENCRYPT_REG_REGION: {
  6019. struct kvm_enc_region region;
  6020. r = -EFAULT;
  6021. if (copy_from_user(&region, argp, sizeof(region)))
  6022. goto out;
  6023. r = -ENOTTY;
  6024. if (!kvm_x86_ops.mem_enc_register_region)
  6025. goto out;
  6026. r = static_call(kvm_x86_mem_enc_register_region)(kvm, &region);
  6027. break;
  6028. }
  6029. case KVM_MEMORY_ENCRYPT_UNREG_REGION: {
  6030. struct kvm_enc_region region;
  6031. r = -EFAULT;
  6032. if (copy_from_user(&region, argp, sizeof(region)))
  6033. goto out;
  6034. r = -ENOTTY;
  6035. if (!kvm_x86_ops.mem_enc_unregister_region)
  6036. goto out;
  6037. r = static_call(kvm_x86_mem_enc_unregister_region)(kvm, &region);
  6038. break;
  6039. }
  6040. case KVM_HYPERV_EVENTFD: {
  6041. struct kvm_hyperv_eventfd hvevfd;
  6042. r = -EFAULT;
  6043. if (copy_from_user(&hvevfd, argp, sizeof(hvevfd)))
  6044. goto out;
  6045. r = kvm_vm_ioctl_hv_eventfd(kvm, &hvevfd);
  6046. break;
  6047. }
  6048. case KVM_SET_PMU_EVENT_FILTER:
  6049. r = kvm_vm_ioctl_set_pmu_event_filter(kvm, argp);
  6050. break;
  6051. case KVM_X86_SET_MSR_FILTER: {
  6052. struct kvm_msr_filter __user *user_msr_filter = argp;
  6053. struct kvm_msr_filter filter;
  6054. if (copy_from_user(&filter, user_msr_filter, sizeof(filter)))
  6055. return -EFAULT;
  6056. r = kvm_vm_ioctl_set_msr_filter(kvm, &filter);
  6057. break;
  6058. }
  6059. default:
  6060. r = -ENOTTY;
  6061. }
  6062. out:
  6063. return r;
  6064. }
  6065. static void kvm_init_msr_list(void)
  6066. {
  6067. u32 dummy[2];
  6068. unsigned i;
  6069. BUILD_BUG_ON_MSG(KVM_PMC_MAX_FIXED != 3,
  6070. "Please update the fixed PMCs in msrs_to_saved_all[]");
  6071. num_msrs_to_save = 0;
  6072. num_emulated_msrs = 0;
  6073. num_msr_based_features = 0;
  6074. for (i = 0; i < ARRAY_SIZE(msrs_to_save_all); i++) {
  6075. if (rdmsr_safe(msrs_to_save_all[i], &dummy[0], &dummy[1]) < 0)
  6076. continue;
  6077. /*
  6078. * Even MSRs that are valid in the host may not be exposed
  6079. * to the guests in some cases.
  6080. */
  6081. switch (msrs_to_save_all[i]) {
  6082. case MSR_IA32_BNDCFGS:
  6083. if (!kvm_mpx_supported())
  6084. continue;
  6085. break;
  6086. case MSR_TSC_AUX:
  6087. if (!kvm_cpu_cap_has(X86_FEATURE_RDTSCP) &&
  6088. !kvm_cpu_cap_has(X86_FEATURE_RDPID))
  6089. continue;
  6090. break;
  6091. case MSR_IA32_UMWAIT_CONTROL:
  6092. if (!kvm_cpu_cap_has(X86_FEATURE_WAITPKG))
  6093. continue;
  6094. break;
  6095. case MSR_IA32_RTIT_CTL:
  6096. case MSR_IA32_RTIT_STATUS:
  6097. if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT))
  6098. continue;
  6099. break;
  6100. case MSR_IA32_RTIT_CR3_MATCH:
  6101. if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
  6102. !intel_pt_validate_hw_cap(PT_CAP_cr3_filtering))
  6103. continue;
  6104. break;
  6105. case MSR_IA32_RTIT_OUTPUT_BASE:
  6106. case MSR_IA32_RTIT_OUTPUT_MASK:
  6107. if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
  6108. (!intel_pt_validate_hw_cap(PT_CAP_topa_output) &&
  6109. !intel_pt_validate_hw_cap(PT_CAP_single_range_output)))
  6110. continue;
  6111. break;
  6112. case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
  6113. if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
  6114. msrs_to_save_all[i] - MSR_IA32_RTIT_ADDR0_A >=
  6115. intel_pt_validate_hw_cap(PT_CAP_num_address_ranges) * 2)
  6116. continue;
  6117. break;
  6118. case MSR_ARCH_PERFMON_PERFCTR0 ... MSR_ARCH_PERFMON_PERFCTR_MAX:
  6119. if (msrs_to_save_all[i] - MSR_ARCH_PERFMON_PERFCTR0 >=
  6120. min(KVM_INTEL_PMC_MAX_GENERIC, kvm_pmu_cap.num_counters_gp))
  6121. continue;
  6122. break;
  6123. case MSR_ARCH_PERFMON_EVENTSEL0 ... MSR_ARCH_PERFMON_EVENTSEL_MAX:
  6124. if (msrs_to_save_all[i] - MSR_ARCH_PERFMON_EVENTSEL0 >=
  6125. min(KVM_INTEL_PMC_MAX_GENERIC, kvm_pmu_cap.num_counters_gp))
  6126. continue;
  6127. break;
  6128. case MSR_IA32_XFD:
  6129. case MSR_IA32_XFD_ERR:
  6130. if (!kvm_cpu_cap_has(X86_FEATURE_XFD))
  6131. continue;
  6132. break;
  6133. default:
  6134. break;
  6135. }
  6136. msrs_to_save[num_msrs_to_save++] = msrs_to_save_all[i];
  6137. }
  6138. for (i = 0; i < ARRAY_SIZE(emulated_msrs_all); i++) {
  6139. if (!static_call(kvm_x86_has_emulated_msr)(NULL, emulated_msrs_all[i]))
  6140. continue;
  6141. emulated_msrs[num_emulated_msrs++] = emulated_msrs_all[i];
  6142. }
  6143. for (i = 0; i < ARRAY_SIZE(msr_based_features_all); i++) {
  6144. struct kvm_msr_entry msr;
  6145. msr.index = msr_based_features_all[i];
  6146. if (kvm_get_msr_feature(&msr))
  6147. continue;
  6148. msr_based_features[num_msr_based_features++] = msr_based_features_all[i];
  6149. }
  6150. }
  6151. static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
  6152. const void *v)
  6153. {
  6154. int handled = 0;
  6155. int n;
  6156. do {
  6157. n = min(len, 8);
  6158. if (!(lapic_in_kernel(vcpu) &&
  6159. !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
  6160. && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
  6161. break;
  6162. handled += n;
  6163. addr += n;
  6164. len -= n;
  6165. v += n;
  6166. } while (len);
  6167. return handled;
  6168. }
  6169. static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
  6170. {
  6171. int handled = 0;
  6172. int n;
  6173. do {
  6174. n = min(len, 8);
  6175. if (!(lapic_in_kernel(vcpu) &&
  6176. !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
  6177. addr, n, v))
  6178. && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
  6179. break;
  6180. trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
  6181. handled += n;
  6182. addr += n;
  6183. len -= n;
  6184. v += n;
  6185. } while (len);
  6186. return handled;
  6187. }
  6188. static void kvm_set_segment(struct kvm_vcpu *vcpu,
  6189. struct kvm_segment *var, int seg)
  6190. {
  6191. static_call(kvm_x86_set_segment)(vcpu, var, seg);
  6192. }
  6193. void kvm_get_segment(struct kvm_vcpu *vcpu,
  6194. struct kvm_segment *var, int seg)
  6195. {
  6196. static_call(kvm_x86_get_segment)(vcpu, var, seg);
  6197. }
  6198. gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u64 access,
  6199. struct x86_exception *exception)
  6200. {
  6201. struct kvm_mmu *mmu = vcpu->arch.mmu;
  6202. gpa_t t_gpa;
  6203. BUG_ON(!mmu_is_nested(vcpu));
  6204. /* NPT walks are always user-walks */
  6205. access |= PFERR_USER_MASK;
  6206. t_gpa = mmu->gva_to_gpa(vcpu, mmu, gpa, access, exception);
  6207. return t_gpa;
  6208. }
  6209. gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
  6210. struct x86_exception *exception)
  6211. {
  6212. struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
  6213. u64 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
  6214. return mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
  6215. }
  6216. EXPORT_SYMBOL_GPL(kvm_mmu_gva_to_gpa_read);
  6217. gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
  6218. struct x86_exception *exception)
  6219. {
  6220. struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
  6221. u64 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
  6222. access |= PFERR_FETCH_MASK;
  6223. return mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
  6224. }
  6225. gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
  6226. struct x86_exception *exception)
  6227. {
  6228. struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
  6229. u64 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
  6230. access |= PFERR_WRITE_MASK;
  6231. return mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
  6232. }
  6233. EXPORT_SYMBOL_GPL(kvm_mmu_gva_to_gpa_write);
  6234. /* uses this to access any guest's mapped memory without checking CPL */
  6235. gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
  6236. struct x86_exception *exception)
  6237. {
  6238. struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
  6239. return mmu->gva_to_gpa(vcpu, mmu, gva, 0, exception);
  6240. }
  6241. static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
  6242. struct kvm_vcpu *vcpu, u64 access,
  6243. struct x86_exception *exception)
  6244. {
  6245. struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
  6246. void *data = val;
  6247. int r = X86EMUL_CONTINUE;
  6248. while (bytes) {
  6249. gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access, exception);
  6250. unsigned offset = addr & (PAGE_SIZE-1);
  6251. unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
  6252. int ret;
  6253. if (gpa == INVALID_GPA)
  6254. return X86EMUL_PROPAGATE_FAULT;
  6255. ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
  6256. offset, toread);
  6257. if (ret < 0) {
  6258. r = X86EMUL_IO_NEEDED;
  6259. goto out;
  6260. }
  6261. bytes -= toread;
  6262. data += toread;
  6263. addr += toread;
  6264. }
  6265. out:
  6266. return r;
  6267. }
  6268. /* used for instruction fetching */
  6269. static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
  6270. gva_t addr, void *val, unsigned int bytes,
  6271. struct x86_exception *exception)
  6272. {
  6273. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  6274. struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
  6275. u64 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
  6276. unsigned offset;
  6277. int ret;
  6278. /* Inline kvm_read_guest_virt_helper for speed. */
  6279. gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access|PFERR_FETCH_MASK,
  6280. exception);
  6281. if (unlikely(gpa == INVALID_GPA))
  6282. return X86EMUL_PROPAGATE_FAULT;
  6283. offset = addr & (PAGE_SIZE-1);
  6284. if (WARN_ON(offset + bytes > PAGE_SIZE))
  6285. bytes = (unsigned)PAGE_SIZE - offset;
  6286. ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
  6287. offset, bytes);
  6288. if (unlikely(ret < 0))
  6289. return X86EMUL_IO_NEEDED;
  6290. return X86EMUL_CONTINUE;
  6291. }
  6292. int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
  6293. gva_t addr, void *val, unsigned int bytes,
  6294. struct x86_exception *exception)
  6295. {
  6296. u64 access = (static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
  6297. /*
  6298. * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
  6299. * is returned, but our callers are not ready for that and they blindly
  6300. * call kvm_inject_page_fault. Ensure that they at least do not leak
  6301. * uninitialized kernel stack memory into cr2 and error code.
  6302. */
  6303. memset(exception, 0, sizeof(*exception));
  6304. return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
  6305. exception);
  6306. }
  6307. EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
  6308. static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
  6309. gva_t addr, void *val, unsigned int bytes,
  6310. struct x86_exception *exception, bool system)
  6311. {
  6312. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  6313. u64 access = 0;
  6314. if (system)
  6315. access |= PFERR_IMPLICIT_ACCESS;
  6316. else if (static_call(kvm_x86_get_cpl)(vcpu) == 3)
  6317. access |= PFERR_USER_MASK;
  6318. return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
  6319. }
  6320. static int kvm_read_guest_phys_system(struct x86_emulate_ctxt *ctxt,
  6321. unsigned long addr, void *val, unsigned int bytes)
  6322. {
  6323. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  6324. int r = kvm_vcpu_read_guest(vcpu, addr, val, bytes);
  6325. return r < 0 ? X86EMUL_IO_NEEDED : X86EMUL_CONTINUE;
  6326. }
  6327. static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
  6328. struct kvm_vcpu *vcpu, u64 access,
  6329. struct x86_exception *exception)
  6330. {
  6331. struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
  6332. void *data = val;
  6333. int r = X86EMUL_CONTINUE;
  6334. while (bytes) {
  6335. gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access, exception);
  6336. unsigned offset = addr & (PAGE_SIZE-1);
  6337. unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
  6338. int ret;
  6339. if (gpa == INVALID_GPA)
  6340. return X86EMUL_PROPAGATE_FAULT;
  6341. ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
  6342. if (ret < 0) {
  6343. r = X86EMUL_IO_NEEDED;
  6344. goto out;
  6345. }
  6346. bytes -= towrite;
  6347. data += towrite;
  6348. addr += towrite;
  6349. }
  6350. out:
  6351. return r;
  6352. }
  6353. static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
  6354. unsigned int bytes, struct x86_exception *exception,
  6355. bool system)
  6356. {
  6357. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  6358. u64 access = PFERR_WRITE_MASK;
  6359. if (system)
  6360. access |= PFERR_IMPLICIT_ACCESS;
  6361. else if (static_call(kvm_x86_get_cpl)(vcpu) == 3)
  6362. access |= PFERR_USER_MASK;
  6363. return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
  6364. access, exception);
  6365. }
  6366. int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
  6367. unsigned int bytes, struct x86_exception *exception)
  6368. {
  6369. /* kvm_write_guest_virt_system can pull in tons of pages. */
  6370. vcpu->arch.l1tf_flush_l1d = true;
  6371. return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
  6372. PFERR_WRITE_MASK, exception);
  6373. }
  6374. EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
  6375. static int kvm_can_emulate_insn(struct kvm_vcpu *vcpu, int emul_type,
  6376. void *insn, int insn_len)
  6377. {
  6378. return static_call(kvm_x86_can_emulate_instruction)(vcpu, emul_type,
  6379. insn, insn_len);
  6380. }
  6381. int handle_ud(struct kvm_vcpu *vcpu)
  6382. {
  6383. static const char kvm_emulate_prefix[] = { __KVM_EMULATE_PREFIX };
  6384. int fep_flags = READ_ONCE(force_emulation_prefix);
  6385. int emul_type = EMULTYPE_TRAP_UD;
  6386. char sig[5]; /* ud2; .ascii "kvm" */
  6387. struct x86_exception e;
  6388. if (unlikely(!kvm_can_emulate_insn(vcpu, emul_type, NULL, 0)))
  6389. return 1;
  6390. if (fep_flags &&
  6391. kvm_read_guest_virt(vcpu, kvm_get_linear_rip(vcpu),
  6392. sig, sizeof(sig), &e) == 0 &&
  6393. memcmp(sig, kvm_emulate_prefix, sizeof(sig)) == 0) {
  6394. if (fep_flags & KVM_FEP_CLEAR_RFLAGS_RF)
  6395. kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) & ~X86_EFLAGS_RF);
  6396. kvm_rip_write(vcpu, kvm_rip_read(vcpu) + sizeof(sig));
  6397. emul_type = EMULTYPE_TRAP_UD_FORCED;
  6398. }
  6399. return kvm_emulate_instruction(vcpu, emul_type);
  6400. }
  6401. EXPORT_SYMBOL_GPL(handle_ud);
  6402. static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
  6403. gpa_t gpa, bool write)
  6404. {
  6405. /* For APIC access vmexit */
  6406. if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
  6407. return 1;
  6408. if (vcpu_match_mmio_gpa(vcpu, gpa)) {
  6409. trace_vcpu_match_mmio(gva, gpa, write, true);
  6410. return 1;
  6411. }
  6412. return 0;
  6413. }
  6414. static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
  6415. gpa_t *gpa, struct x86_exception *exception,
  6416. bool write)
  6417. {
  6418. struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
  6419. u64 access = ((static_call(kvm_x86_get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0)
  6420. | (write ? PFERR_WRITE_MASK : 0);
  6421. /*
  6422. * currently PKRU is only applied to ept enabled guest so
  6423. * there is no pkey in EPT page table for L1 guest or EPT
  6424. * shadow page table for L2 guest.
  6425. */
  6426. if (vcpu_match_mmio_gva(vcpu, gva) && (!is_paging(vcpu) ||
  6427. !permission_fault(vcpu, vcpu->arch.walk_mmu,
  6428. vcpu->arch.mmio_access, 0, access))) {
  6429. *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
  6430. (gva & (PAGE_SIZE - 1));
  6431. trace_vcpu_match_mmio(gva, *gpa, write, false);
  6432. return 1;
  6433. }
  6434. *gpa = mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
  6435. if (*gpa == INVALID_GPA)
  6436. return -1;
  6437. return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
  6438. }
  6439. int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
  6440. const void *val, int bytes)
  6441. {
  6442. int ret;
  6443. ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
  6444. if (ret < 0)
  6445. return 0;
  6446. kvm_page_track_write(vcpu, gpa, val, bytes);
  6447. return 1;
  6448. }
  6449. struct read_write_emulator_ops {
  6450. int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
  6451. int bytes);
  6452. int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
  6453. void *val, int bytes);
  6454. int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
  6455. int bytes, void *val);
  6456. int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
  6457. void *val, int bytes);
  6458. bool write;
  6459. };
  6460. static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
  6461. {
  6462. if (vcpu->mmio_read_completed) {
  6463. trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
  6464. vcpu->mmio_fragments[0].gpa, val);
  6465. vcpu->mmio_read_completed = 0;
  6466. return 1;
  6467. }
  6468. return 0;
  6469. }
  6470. static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
  6471. void *val, int bytes)
  6472. {
  6473. return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
  6474. }
  6475. static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
  6476. void *val, int bytes)
  6477. {
  6478. return emulator_write_phys(vcpu, gpa, val, bytes);
  6479. }
  6480. static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
  6481. {
  6482. trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
  6483. return vcpu_mmio_write(vcpu, gpa, bytes, val);
  6484. }
  6485. static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
  6486. void *val, int bytes)
  6487. {
  6488. trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
  6489. return X86EMUL_IO_NEEDED;
  6490. }
  6491. static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
  6492. void *val, int bytes)
  6493. {
  6494. struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
  6495. memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
  6496. return X86EMUL_CONTINUE;
  6497. }
  6498. static const struct read_write_emulator_ops read_emultor = {
  6499. .read_write_prepare = read_prepare,
  6500. .read_write_emulate = read_emulate,
  6501. .read_write_mmio = vcpu_mmio_read,
  6502. .read_write_exit_mmio = read_exit_mmio,
  6503. };
  6504. static const struct read_write_emulator_ops write_emultor = {
  6505. .read_write_emulate = write_emulate,
  6506. .read_write_mmio = write_mmio,
  6507. .read_write_exit_mmio = write_exit_mmio,
  6508. .write = true,
  6509. };
  6510. static int emulator_read_write_onepage(unsigned long addr, void *val,
  6511. unsigned int bytes,
  6512. struct x86_exception *exception,
  6513. struct kvm_vcpu *vcpu,
  6514. const struct read_write_emulator_ops *ops)
  6515. {
  6516. gpa_t gpa;
  6517. int handled, ret;
  6518. bool write = ops->write;
  6519. struct kvm_mmio_fragment *frag;
  6520. struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
  6521. /*
  6522. * If the exit was due to a NPF we may already have a GPA.
  6523. * If the GPA is present, use it to avoid the GVA to GPA table walk.
  6524. * Note, this cannot be used on string operations since string
  6525. * operation using rep will only have the initial GPA from the NPF
  6526. * occurred.
  6527. */
  6528. if (ctxt->gpa_available && emulator_can_use_gpa(ctxt) &&
  6529. (addr & ~PAGE_MASK) == (ctxt->gpa_val & ~PAGE_MASK)) {
  6530. gpa = ctxt->gpa_val;
  6531. ret = vcpu_is_mmio_gpa(vcpu, addr, gpa, write);
  6532. } else {
  6533. ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
  6534. if (ret < 0)
  6535. return X86EMUL_PROPAGATE_FAULT;
  6536. }
  6537. if (!ret && ops->read_write_emulate(vcpu, gpa, val, bytes))
  6538. return X86EMUL_CONTINUE;
  6539. /*
  6540. * Is this MMIO handled locally?
  6541. */
  6542. handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
  6543. if (handled == bytes)
  6544. return X86EMUL_CONTINUE;
  6545. gpa += handled;
  6546. bytes -= handled;
  6547. val += handled;
  6548. WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
  6549. frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
  6550. frag->gpa = gpa;
  6551. frag->data = val;
  6552. frag->len = bytes;
  6553. return X86EMUL_CONTINUE;
  6554. }
  6555. static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
  6556. unsigned long addr,
  6557. void *val, unsigned int bytes,
  6558. struct x86_exception *exception,
  6559. const struct read_write_emulator_ops *ops)
  6560. {
  6561. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  6562. gpa_t gpa;
  6563. int rc;
  6564. if (ops->read_write_prepare &&
  6565. ops->read_write_prepare(vcpu, val, bytes))
  6566. return X86EMUL_CONTINUE;
  6567. vcpu->mmio_nr_fragments = 0;
  6568. /* Crossing a page boundary? */
  6569. if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
  6570. int now;
  6571. now = -addr & ~PAGE_MASK;
  6572. rc = emulator_read_write_onepage(addr, val, now, exception,
  6573. vcpu, ops);
  6574. if (rc != X86EMUL_CONTINUE)
  6575. return rc;
  6576. addr += now;
  6577. if (ctxt->mode != X86EMUL_MODE_PROT64)
  6578. addr = (u32)addr;
  6579. val += now;
  6580. bytes -= now;
  6581. }
  6582. rc = emulator_read_write_onepage(addr, val, bytes, exception,
  6583. vcpu, ops);
  6584. if (rc != X86EMUL_CONTINUE)
  6585. return rc;
  6586. if (!vcpu->mmio_nr_fragments)
  6587. return rc;
  6588. gpa = vcpu->mmio_fragments[0].gpa;
  6589. vcpu->mmio_needed = 1;
  6590. vcpu->mmio_cur_fragment = 0;
  6591. vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
  6592. vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
  6593. vcpu->run->exit_reason = KVM_EXIT_MMIO;
  6594. vcpu->run->mmio.phys_addr = gpa;
  6595. return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
  6596. }
  6597. static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
  6598. unsigned long addr,
  6599. void *val,
  6600. unsigned int bytes,
  6601. struct x86_exception *exception)
  6602. {
  6603. return emulator_read_write(ctxt, addr, val, bytes,
  6604. exception, &read_emultor);
  6605. }
  6606. static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
  6607. unsigned long addr,
  6608. const void *val,
  6609. unsigned int bytes,
  6610. struct x86_exception *exception)
  6611. {
  6612. return emulator_read_write(ctxt, addr, (void *)val, bytes,
  6613. exception, &write_emultor);
  6614. }
  6615. #define emulator_try_cmpxchg_user(t, ptr, old, new) \
  6616. (__try_cmpxchg_user((t __user *)(ptr), (t *)(old), *(t *)(new), efault ## t))
  6617. static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
  6618. unsigned long addr,
  6619. const void *old,
  6620. const void *new,
  6621. unsigned int bytes,
  6622. struct x86_exception *exception)
  6623. {
  6624. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  6625. u64 page_line_mask;
  6626. unsigned long hva;
  6627. gpa_t gpa;
  6628. int r;
  6629. /* guests cmpxchg8b have to be emulated atomically */
  6630. if (bytes > 8 || (bytes & (bytes - 1)))
  6631. goto emul_write;
  6632. gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
  6633. if (gpa == INVALID_GPA ||
  6634. (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
  6635. goto emul_write;
  6636. /*
  6637. * Emulate the atomic as a straight write to avoid #AC if SLD is
  6638. * enabled in the host and the access splits a cache line.
  6639. */
  6640. if (boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
  6641. page_line_mask = ~(cache_line_size() - 1);
  6642. else
  6643. page_line_mask = PAGE_MASK;
  6644. if (((gpa + bytes - 1) & page_line_mask) != (gpa & page_line_mask))
  6645. goto emul_write;
  6646. hva = kvm_vcpu_gfn_to_hva(vcpu, gpa_to_gfn(gpa));
  6647. if (kvm_is_error_hva(hva))
  6648. goto emul_write;
  6649. hva += offset_in_page(gpa);
  6650. switch (bytes) {
  6651. case 1:
  6652. r = emulator_try_cmpxchg_user(u8, hva, old, new);
  6653. break;
  6654. case 2:
  6655. r = emulator_try_cmpxchg_user(u16, hva, old, new);
  6656. break;
  6657. case 4:
  6658. r = emulator_try_cmpxchg_user(u32, hva, old, new);
  6659. break;
  6660. case 8:
  6661. r = emulator_try_cmpxchg_user(u64, hva, old, new);
  6662. break;
  6663. default:
  6664. BUG();
  6665. }
  6666. if (r < 0)
  6667. return X86EMUL_UNHANDLEABLE;
  6668. if (r)
  6669. return X86EMUL_CMPXCHG_FAILED;
  6670. kvm_page_track_write(vcpu, gpa, new, bytes);
  6671. return X86EMUL_CONTINUE;
  6672. emul_write:
  6673. printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
  6674. return emulator_write_emulated(ctxt, addr, new, bytes, exception);
  6675. }
  6676. static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
  6677. unsigned short port, void *data,
  6678. unsigned int count, bool in)
  6679. {
  6680. unsigned i;
  6681. int r;
  6682. WARN_ON_ONCE(vcpu->arch.pio.count);
  6683. for (i = 0; i < count; i++) {
  6684. if (in)
  6685. r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, port, size, data);
  6686. else
  6687. r = kvm_io_bus_write(vcpu, KVM_PIO_BUS, port, size, data);
  6688. if (r) {
  6689. if (i == 0)
  6690. goto userspace_io;
  6691. /*
  6692. * Userspace must have unregistered the device while PIO
  6693. * was running. Drop writes / read as 0.
  6694. */
  6695. if (in)
  6696. memset(data, 0, size * (count - i));
  6697. break;
  6698. }
  6699. data += size;
  6700. }
  6701. return 1;
  6702. userspace_io:
  6703. vcpu->arch.pio.port = port;
  6704. vcpu->arch.pio.in = in;
  6705. vcpu->arch.pio.count = count;
  6706. vcpu->arch.pio.size = size;
  6707. if (in)
  6708. memset(vcpu->arch.pio_data, 0, size * count);
  6709. else
  6710. memcpy(vcpu->arch.pio_data, data, size * count);
  6711. vcpu->run->exit_reason = KVM_EXIT_IO;
  6712. vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
  6713. vcpu->run->io.size = size;
  6714. vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
  6715. vcpu->run->io.count = count;
  6716. vcpu->run->io.port = port;
  6717. return 0;
  6718. }
  6719. static int emulator_pio_in(struct kvm_vcpu *vcpu, int size,
  6720. unsigned short port, void *val, unsigned int count)
  6721. {
  6722. int r = emulator_pio_in_out(vcpu, size, port, val, count, true);
  6723. if (r)
  6724. trace_kvm_pio(KVM_PIO_IN, port, size, count, val);
  6725. return r;
  6726. }
  6727. static void complete_emulator_pio_in(struct kvm_vcpu *vcpu, void *val)
  6728. {
  6729. int size = vcpu->arch.pio.size;
  6730. unsigned int count = vcpu->arch.pio.count;
  6731. memcpy(val, vcpu->arch.pio_data, size * count);
  6732. trace_kvm_pio(KVM_PIO_IN, vcpu->arch.pio.port, size, count, vcpu->arch.pio_data);
  6733. vcpu->arch.pio.count = 0;
  6734. }
  6735. static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
  6736. int size, unsigned short port, void *val,
  6737. unsigned int count)
  6738. {
  6739. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  6740. if (vcpu->arch.pio.count) {
  6741. /*
  6742. * Complete a previous iteration that required userspace I/O.
  6743. * Note, @count isn't guaranteed to match pio.count as userspace
  6744. * can modify ECX before rerunning the vCPU. Ignore any such
  6745. * shenanigans as KVM doesn't support modifying the rep count,
  6746. * and the emulator ensures @count doesn't overflow the buffer.
  6747. */
  6748. complete_emulator_pio_in(vcpu, val);
  6749. return 1;
  6750. }
  6751. return emulator_pio_in(vcpu, size, port, val, count);
  6752. }
  6753. static int emulator_pio_out(struct kvm_vcpu *vcpu, int size,
  6754. unsigned short port, const void *val,
  6755. unsigned int count)
  6756. {
  6757. trace_kvm_pio(KVM_PIO_OUT, port, size, count, val);
  6758. return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
  6759. }
  6760. static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
  6761. int size, unsigned short port,
  6762. const void *val, unsigned int count)
  6763. {
  6764. return emulator_pio_out(emul_to_vcpu(ctxt), size, port, val, count);
  6765. }
  6766. static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
  6767. {
  6768. return static_call(kvm_x86_get_segment_base)(vcpu, seg);
  6769. }
  6770. static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
  6771. {
  6772. kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
  6773. }
  6774. static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
  6775. {
  6776. if (!need_emulate_wbinvd(vcpu))
  6777. return X86EMUL_CONTINUE;
  6778. if (static_call(kvm_x86_has_wbinvd_exit)()) {
  6779. int cpu = get_cpu();
  6780. cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
  6781. on_each_cpu_mask(vcpu->arch.wbinvd_dirty_mask,
  6782. wbinvd_ipi, NULL, 1);
  6783. put_cpu();
  6784. cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
  6785. } else
  6786. wbinvd();
  6787. return X86EMUL_CONTINUE;
  6788. }
  6789. int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
  6790. {
  6791. kvm_emulate_wbinvd_noskip(vcpu);
  6792. return kvm_skip_emulated_instruction(vcpu);
  6793. }
  6794. EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
  6795. static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
  6796. {
  6797. kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
  6798. }
  6799. static void emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr,
  6800. unsigned long *dest)
  6801. {
  6802. kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
  6803. }
  6804. static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
  6805. unsigned long value)
  6806. {
  6807. return kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
  6808. }
  6809. static u64 mk_cr_64(u64 curr_cr, u32 new_val)
  6810. {
  6811. return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
  6812. }
  6813. static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
  6814. {
  6815. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  6816. unsigned long value;
  6817. switch (cr) {
  6818. case 0:
  6819. value = kvm_read_cr0(vcpu);
  6820. break;
  6821. case 2:
  6822. value = vcpu->arch.cr2;
  6823. break;
  6824. case 3:
  6825. value = kvm_read_cr3(vcpu);
  6826. break;
  6827. case 4:
  6828. value = kvm_read_cr4(vcpu);
  6829. break;
  6830. case 8:
  6831. value = kvm_get_cr8(vcpu);
  6832. break;
  6833. default:
  6834. kvm_err("%s: unexpected cr %u\n", __func__, cr);
  6835. return 0;
  6836. }
  6837. return value;
  6838. }
  6839. static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
  6840. {
  6841. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  6842. int res = 0;
  6843. switch (cr) {
  6844. case 0:
  6845. res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
  6846. break;
  6847. case 2:
  6848. vcpu->arch.cr2 = val;
  6849. break;
  6850. case 3:
  6851. res = kvm_set_cr3(vcpu, val);
  6852. break;
  6853. case 4:
  6854. res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
  6855. break;
  6856. case 8:
  6857. res = kvm_set_cr8(vcpu, val);
  6858. break;
  6859. default:
  6860. kvm_err("%s: unexpected cr %u\n", __func__, cr);
  6861. res = -1;
  6862. }
  6863. return res;
  6864. }
  6865. static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
  6866. {
  6867. return static_call(kvm_x86_get_cpl)(emul_to_vcpu(ctxt));
  6868. }
  6869. static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
  6870. {
  6871. static_call(kvm_x86_get_gdt)(emul_to_vcpu(ctxt), dt);
  6872. }
  6873. static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
  6874. {
  6875. static_call(kvm_x86_get_idt)(emul_to_vcpu(ctxt), dt);
  6876. }
  6877. static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
  6878. {
  6879. static_call(kvm_x86_set_gdt)(emul_to_vcpu(ctxt), dt);
  6880. }
  6881. static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
  6882. {
  6883. static_call(kvm_x86_set_idt)(emul_to_vcpu(ctxt), dt);
  6884. }
  6885. static unsigned long emulator_get_cached_segment_base(
  6886. struct x86_emulate_ctxt *ctxt, int seg)
  6887. {
  6888. return get_segment_base(emul_to_vcpu(ctxt), seg);
  6889. }
  6890. static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
  6891. struct desc_struct *desc, u32 *base3,
  6892. int seg)
  6893. {
  6894. struct kvm_segment var;
  6895. kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
  6896. *selector = var.selector;
  6897. if (var.unusable) {
  6898. memset(desc, 0, sizeof(*desc));
  6899. if (base3)
  6900. *base3 = 0;
  6901. return false;
  6902. }
  6903. if (var.g)
  6904. var.limit >>= 12;
  6905. set_desc_limit(desc, var.limit);
  6906. set_desc_base(desc, (unsigned long)var.base);
  6907. #ifdef CONFIG_X86_64
  6908. if (base3)
  6909. *base3 = var.base >> 32;
  6910. #endif
  6911. desc->type = var.type;
  6912. desc->s = var.s;
  6913. desc->dpl = var.dpl;
  6914. desc->p = var.present;
  6915. desc->avl = var.avl;
  6916. desc->l = var.l;
  6917. desc->d = var.db;
  6918. desc->g = var.g;
  6919. return true;
  6920. }
  6921. static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
  6922. struct desc_struct *desc, u32 base3,
  6923. int seg)
  6924. {
  6925. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  6926. struct kvm_segment var;
  6927. var.selector = selector;
  6928. var.base = get_desc_base(desc);
  6929. #ifdef CONFIG_X86_64
  6930. var.base |= ((u64)base3) << 32;
  6931. #endif
  6932. var.limit = get_desc_limit(desc);
  6933. if (desc->g)
  6934. var.limit = (var.limit << 12) | 0xfff;
  6935. var.type = desc->type;
  6936. var.dpl = desc->dpl;
  6937. var.db = desc->d;
  6938. var.s = desc->s;
  6939. var.l = desc->l;
  6940. var.g = desc->g;
  6941. var.avl = desc->avl;
  6942. var.present = desc->p;
  6943. var.unusable = !var.present;
  6944. var.padding = 0;
  6945. kvm_set_segment(vcpu, &var, seg);
  6946. return;
  6947. }
  6948. static int emulator_get_msr_with_filter(struct x86_emulate_ctxt *ctxt,
  6949. u32 msr_index, u64 *pdata)
  6950. {
  6951. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  6952. int r;
  6953. r = kvm_get_msr_with_filter(vcpu, msr_index, pdata);
  6954. if (r < 0)
  6955. return X86EMUL_UNHANDLEABLE;
  6956. if (r) {
  6957. if (kvm_msr_user_space(vcpu, msr_index, KVM_EXIT_X86_RDMSR, 0,
  6958. complete_emulated_rdmsr, r))
  6959. return X86EMUL_IO_NEEDED;
  6960. trace_kvm_msr_read_ex(msr_index);
  6961. return X86EMUL_PROPAGATE_FAULT;
  6962. }
  6963. trace_kvm_msr_read(msr_index, *pdata);
  6964. return X86EMUL_CONTINUE;
  6965. }
  6966. static int emulator_set_msr_with_filter(struct x86_emulate_ctxt *ctxt,
  6967. u32 msr_index, u64 data)
  6968. {
  6969. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  6970. int r;
  6971. r = kvm_set_msr_with_filter(vcpu, msr_index, data);
  6972. if (r < 0)
  6973. return X86EMUL_UNHANDLEABLE;
  6974. if (r) {
  6975. if (kvm_msr_user_space(vcpu, msr_index, KVM_EXIT_X86_WRMSR, data,
  6976. complete_emulated_msr_access, r))
  6977. return X86EMUL_IO_NEEDED;
  6978. trace_kvm_msr_write_ex(msr_index, data);
  6979. return X86EMUL_PROPAGATE_FAULT;
  6980. }
  6981. trace_kvm_msr_write(msr_index, data);
  6982. return X86EMUL_CONTINUE;
  6983. }
  6984. static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
  6985. u32 msr_index, u64 *pdata)
  6986. {
  6987. return kvm_get_msr(emul_to_vcpu(ctxt), msr_index, pdata);
  6988. }
  6989. static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
  6990. u32 msr_index, u64 data)
  6991. {
  6992. return kvm_set_msr(emul_to_vcpu(ctxt), msr_index, data);
  6993. }
  6994. static u64 emulator_get_smbase(struct x86_emulate_ctxt *ctxt)
  6995. {
  6996. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  6997. return vcpu->arch.smbase;
  6998. }
  6999. static void emulator_set_smbase(struct x86_emulate_ctxt *ctxt, u64 smbase)
  7000. {
  7001. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  7002. vcpu->arch.smbase = smbase;
  7003. }
  7004. static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
  7005. u32 pmc)
  7006. {
  7007. if (kvm_pmu_is_valid_rdpmc_ecx(emul_to_vcpu(ctxt), pmc))
  7008. return 0;
  7009. return -EINVAL;
  7010. }
  7011. static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
  7012. u32 pmc, u64 *pdata)
  7013. {
  7014. return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
  7015. }
  7016. static void emulator_halt(struct x86_emulate_ctxt *ctxt)
  7017. {
  7018. emul_to_vcpu(ctxt)->arch.halt_request = 1;
  7019. }
  7020. static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
  7021. struct x86_instruction_info *info,
  7022. enum x86_intercept_stage stage)
  7023. {
  7024. return static_call(kvm_x86_check_intercept)(emul_to_vcpu(ctxt), info, stage,
  7025. &ctxt->exception);
  7026. }
  7027. static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
  7028. u32 *eax, u32 *ebx, u32 *ecx, u32 *edx,
  7029. bool exact_only)
  7030. {
  7031. return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, exact_only);
  7032. }
  7033. static bool emulator_guest_has_long_mode(struct x86_emulate_ctxt *ctxt)
  7034. {
  7035. return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_LM);
  7036. }
  7037. static bool emulator_guest_has_movbe(struct x86_emulate_ctxt *ctxt)
  7038. {
  7039. return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_MOVBE);
  7040. }
  7041. static bool emulator_guest_has_fxsr(struct x86_emulate_ctxt *ctxt)
  7042. {
  7043. return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_FXSR);
  7044. }
  7045. static bool emulator_guest_has_rdpid(struct x86_emulate_ctxt *ctxt)
  7046. {
  7047. return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_RDPID);
  7048. }
  7049. static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
  7050. {
  7051. return kvm_register_read_raw(emul_to_vcpu(ctxt), reg);
  7052. }
  7053. static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
  7054. {
  7055. kvm_register_write_raw(emul_to_vcpu(ctxt), reg, val);
  7056. }
  7057. static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
  7058. {
  7059. static_call(kvm_x86_set_nmi_mask)(emul_to_vcpu(ctxt), masked);
  7060. }
  7061. static unsigned emulator_get_hflags(struct x86_emulate_ctxt *ctxt)
  7062. {
  7063. return emul_to_vcpu(ctxt)->arch.hflags;
  7064. }
  7065. static void emulator_exiting_smm(struct x86_emulate_ctxt *ctxt)
  7066. {
  7067. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  7068. kvm_smm_changed(vcpu, false);
  7069. }
  7070. static int emulator_leave_smm(struct x86_emulate_ctxt *ctxt,
  7071. const char *smstate)
  7072. {
  7073. return static_call(kvm_x86_leave_smm)(emul_to_vcpu(ctxt), smstate);
  7074. }
  7075. static void emulator_triple_fault(struct x86_emulate_ctxt *ctxt)
  7076. {
  7077. kvm_make_request(KVM_REQ_TRIPLE_FAULT, emul_to_vcpu(ctxt));
  7078. }
  7079. static int emulator_set_xcr(struct x86_emulate_ctxt *ctxt, u32 index, u64 xcr)
  7080. {
  7081. return __kvm_set_xcr(emul_to_vcpu(ctxt), index, xcr);
  7082. }
  7083. static void emulator_vm_bugged(struct x86_emulate_ctxt *ctxt)
  7084. {
  7085. struct kvm *kvm = emul_to_vcpu(ctxt)->kvm;
  7086. if (!kvm->vm_bugged)
  7087. kvm_vm_bugged(kvm);
  7088. }
  7089. static const struct x86_emulate_ops emulate_ops = {
  7090. .vm_bugged = emulator_vm_bugged,
  7091. .read_gpr = emulator_read_gpr,
  7092. .write_gpr = emulator_write_gpr,
  7093. .read_std = emulator_read_std,
  7094. .write_std = emulator_write_std,
  7095. .read_phys = kvm_read_guest_phys_system,
  7096. .fetch = kvm_fetch_guest_virt,
  7097. .read_emulated = emulator_read_emulated,
  7098. .write_emulated = emulator_write_emulated,
  7099. .cmpxchg_emulated = emulator_cmpxchg_emulated,
  7100. .invlpg = emulator_invlpg,
  7101. .pio_in_emulated = emulator_pio_in_emulated,
  7102. .pio_out_emulated = emulator_pio_out_emulated,
  7103. .get_segment = emulator_get_segment,
  7104. .set_segment = emulator_set_segment,
  7105. .get_cached_segment_base = emulator_get_cached_segment_base,
  7106. .get_gdt = emulator_get_gdt,
  7107. .get_idt = emulator_get_idt,
  7108. .set_gdt = emulator_set_gdt,
  7109. .set_idt = emulator_set_idt,
  7110. .get_cr = emulator_get_cr,
  7111. .set_cr = emulator_set_cr,
  7112. .cpl = emulator_get_cpl,
  7113. .get_dr = emulator_get_dr,
  7114. .set_dr = emulator_set_dr,
  7115. .get_smbase = emulator_get_smbase,
  7116. .set_smbase = emulator_set_smbase,
  7117. .set_msr_with_filter = emulator_set_msr_with_filter,
  7118. .get_msr_with_filter = emulator_get_msr_with_filter,
  7119. .set_msr = emulator_set_msr,
  7120. .get_msr = emulator_get_msr,
  7121. .check_pmc = emulator_check_pmc,
  7122. .read_pmc = emulator_read_pmc,
  7123. .halt = emulator_halt,
  7124. .wbinvd = emulator_wbinvd,
  7125. .fix_hypercall = emulator_fix_hypercall,
  7126. .intercept = emulator_intercept,
  7127. .get_cpuid = emulator_get_cpuid,
  7128. .guest_has_long_mode = emulator_guest_has_long_mode,
  7129. .guest_has_movbe = emulator_guest_has_movbe,
  7130. .guest_has_fxsr = emulator_guest_has_fxsr,
  7131. .guest_has_rdpid = emulator_guest_has_rdpid,
  7132. .set_nmi_mask = emulator_set_nmi_mask,
  7133. .get_hflags = emulator_get_hflags,
  7134. .exiting_smm = emulator_exiting_smm,
  7135. .leave_smm = emulator_leave_smm,
  7136. .triple_fault = emulator_triple_fault,
  7137. .set_xcr = emulator_set_xcr,
  7138. };
  7139. static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
  7140. {
  7141. u32 int_shadow = static_call(kvm_x86_get_interrupt_shadow)(vcpu);
  7142. /*
  7143. * an sti; sti; sequence only disable interrupts for the first
  7144. * instruction. So, if the last instruction, be it emulated or
  7145. * not, left the system with the INT_STI flag enabled, it
  7146. * means that the last instruction is an sti. We should not
  7147. * leave the flag on in this case. The same goes for mov ss
  7148. */
  7149. if (int_shadow & mask)
  7150. mask = 0;
  7151. if (unlikely(int_shadow || mask)) {
  7152. static_call(kvm_x86_set_interrupt_shadow)(vcpu, mask);
  7153. if (!mask)
  7154. kvm_make_request(KVM_REQ_EVENT, vcpu);
  7155. }
  7156. }
  7157. static void inject_emulated_exception(struct kvm_vcpu *vcpu)
  7158. {
  7159. struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
  7160. if (ctxt->exception.vector == PF_VECTOR)
  7161. kvm_inject_emulated_page_fault(vcpu, &ctxt->exception);
  7162. else if (ctxt->exception.error_code_valid)
  7163. kvm_queue_exception_e(vcpu, ctxt->exception.vector,
  7164. ctxt->exception.error_code);
  7165. else
  7166. kvm_queue_exception(vcpu, ctxt->exception.vector);
  7167. }
  7168. static struct x86_emulate_ctxt *alloc_emulate_ctxt(struct kvm_vcpu *vcpu)
  7169. {
  7170. struct x86_emulate_ctxt *ctxt;
  7171. ctxt = kmem_cache_zalloc(x86_emulator_cache, GFP_KERNEL_ACCOUNT);
  7172. if (!ctxt) {
  7173. pr_err("kvm: failed to allocate vcpu's emulator\n");
  7174. return NULL;
  7175. }
  7176. ctxt->vcpu = vcpu;
  7177. ctxt->ops = &emulate_ops;
  7178. vcpu->arch.emulate_ctxt = ctxt;
  7179. return ctxt;
  7180. }
  7181. static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
  7182. {
  7183. struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
  7184. int cs_db, cs_l;
  7185. static_call(kvm_x86_get_cs_db_l_bits)(vcpu, &cs_db, &cs_l);
  7186. ctxt->gpa_available = false;
  7187. ctxt->eflags = kvm_get_rflags(vcpu);
  7188. ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
  7189. ctxt->eip = kvm_rip_read(vcpu);
  7190. ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
  7191. (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
  7192. (cs_l && is_long_mode(vcpu)) ? X86EMUL_MODE_PROT64 :
  7193. cs_db ? X86EMUL_MODE_PROT32 :
  7194. X86EMUL_MODE_PROT16;
  7195. BUILD_BUG_ON(HF_GUEST_MASK != X86EMUL_GUEST_MASK);
  7196. BUILD_BUG_ON(HF_SMM_MASK != X86EMUL_SMM_MASK);
  7197. BUILD_BUG_ON(HF_SMM_INSIDE_NMI_MASK != X86EMUL_SMM_INSIDE_NMI_MASK);
  7198. ctxt->interruptibility = 0;
  7199. ctxt->have_exception = false;
  7200. ctxt->exception.vector = -1;
  7201. ctxt->perm_ok = false;
  7202. init_decode_cache(ctxt);
  7203. vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
  7204. }
  7205. void kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
  7206. {
  7207. struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
  7208. int ret;
  7209. init_emulate_ctxt(vcpu);
  7210. ctxt->op_bytes = 2;
  7211. ctxt->ad_bytes = 2;
  7212. ctxt->_eip = ctxt->eip + inc_eip;
  7213. ret = emulate_int_real(ctxt, irq);
  7214. if (ret != X86EMUL_CONTINUE) {
  7215. kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
  7216. } else {
  7217. ctxt->eip = ctxt->_eip;
  7218. kvm_rip_write(vcpu, ctxt->eip);
  7219. kvm_set_rflags(vcpu, ctxt->eflags);
  7220. }
  7221. }
  7222. EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
  7223. static void prepare_emulation_failure_exit(struct kvm_vcpu *vcpu, u64 *data,
  7224. u8 ndata, u8 *insn_bytes, u8 insn_size)
  7225. {
  7226. struct kvm_run *run = vcpu->run;
  7227. u64 info[5];
  7228. u8 info_start;
  7229. /*
  7230. * Zero the whole array used to retrieve the exit info, as casting to
  7231. * u32 for select entries will leave some chunks uninitialized.
  7232. */
  7233. memset(&info, 0, sizeof(info));
  7234. static_call(kvm_x86_get_exit_info)(vcpu, (u32 *)&info[0], &info[1],
  7235. &info[2], (u32 *)&info[3],
  7236. (u32 *)&info[4]);
  7237. run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
  7238. run->emulation_failure.suberror = KVM_INTERNAL_ERROR_EMULATION;
  7239. /*
  7240. * There's currently space for 13 entries, but 5 are used for the exit
  7241. * reason and info. Restrict to 4 to reduce the maintenance burden
  7242. * when expanding kvm_run.emulation_failure in the future.
  7243. */
  7244. if (WARN_ON_ONCE(ndata > 4))
  7245. ndata = 4;
  7246. /* Always include the flags as a 'data' entry. */
  7247. info_start = 1;
  7248. run->emulation_failure.flags = 0;
  7249. if (insn_size) {
  7250. BUILD_BUG_ON((sizeof(run->emulation_failure.insn_size) +
  7251. sizeof(run->emulation_failure.insn_bytes) != 16));
  7252. info_start += 2;
  7253. run->emulation_failure.flags |=
  7254. KVM_INTERNAL_ERROR_EMULATION_FLAG_INSTRUCTION_BYTES;
  7255. run->emulation_failure.insn_size = insn_size;
  7256. memset(run->emulation_failure.insn_bytes, 0x90,
  7257. sizeof(run->emulation_failure.insn_bytes));
  7258. memcpy(run->emulation_failure.insn_bytes, insn_bytes, insn_size);
  7259. }
  7260. memcpy(&run->internal.data[info_start], info, sizeof(info));
  7261. memcpy(&run->internal.data[info_start + ARRAY_SIZE(info)], data,
  7262. ndata * sizeof(data[0]));
  7263. run->emulation_failure.ndata = info_start + ARRAY_SIZE(info) + ndata;
  7264. }
  7265. static void prepare_emulation_ctxt_failure_exit(struct kvm_vcpu *vcpu)
  7266. {
  7267. struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
  7268. prepare_emulation_failure_exit(vcpu, NULL, 0, ctxt->fetch.data,
  7269. ctxt->fetch.end - ctxt->fetch.data);
  7270. }
  7271. void __kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu, u64 *data,
  7272. u8 ndata)
  7273. {
  7274. prepare_emulation_failure_exit(vcpu, data, ndata, NULL, 0);
  7275. }
  7276. EXPORT_SYMBOL_GPL(__kvm_prepare_emulation_failure_exit);
  7277. void kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu)
  7278. {
  7279. __kvm_prepare_emulation_failure_exit(vcpu, NULL, 0);
  7280. }
  7281. EXPORT_SYMBOL_GPL(kvm_prepare_emulation_failure_exit);
  7282. static int handle_emulation_failure(struct kvm_vcpu *vcpu, int emulation_type)
  7283. {
  7284. struct kvm *kvm = vcpu->kvm;
  7285. ++vcpu->stat.insn_emulation_fail;
  7286. trace_kvm_emulate_insn_failed(vcpu);
  7287. if (emulation_type & EMULTYPE_VMWARE_GP) {
  7288. kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
  7289. return 1;
  7290. }
  7291. if (kvm->arch.exit_on_emulation_error ||
  7292. (emulation_type & EMULTYPE_SKIP)) {
  7293. prepare_emulation_ctxt_failure_exit(vcpu);
  7294. return 0;
  7295. }
  7296. kvm_queue_exception(vcpu, UD_VECTOR);
  7297. if (!is_guest_mode(vcpu) && static_call(kvm_x86_get_cpl)(vcpu) == 0) {
  7298. prepare_emulation_ctxt_failure_exit(vcpu);
  7299. return 0;
  7300. }
  7301. return 1;
  7302. }
  7303. static bool reexecute_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
  7304. bool write_fault_to_shadow_pgtable,
  7305. int emulation_type)
  7306. {
  7307. gpa_t gpa = cr2_or_gpa;
  7308. kvm_pfn_t pfn;
  7309. if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
  7310. return false;
  7311. if (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
  7312. WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF)))
  7313. return false;
  7314. if (!vcpu->arch.mmu->root_role.direct) {
  7315. /*
  7316. * Write permission should be allowed since only
  7317. * write access need to be emulated.
  7318. */
  7319. gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
  7320. /*
  7321. * If the mapping is invalid in guest, let cpu retry
  7322. * it to generate fault.
  7323. */
  7324. if (gpa == INVALID_GPA)
  7325. return true;
  7326. }
  7327. /*
  7328. * Do not retry the unhandleable instruction if it faults on the
  7329. * readonly host memory, otherwise it will goto a infinite loop:
  7330. * retry instruction -> write #PF -> emulation fail -> retry
  7331. * instruction -> ...
  7332. */
  7333. pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
  7334. /*
  7335. * If the instruction failed on the error pfn, it can not be fixed,
  7336. * report the error to userspace.
  7337. */
  7338. if (is_error_noslot_pfn(pfn))
  7339. return false;
  7340. kvm_release_pfn_clean(pfn);
  7341. /* The instructions are well-emulated on direct mmu. */
  7342. if (vcpu->arch.mmu->root_role.direct) {
  7343. unsigned int indirect_shadow_pages;
  7344. write_lock(&vcpu->kvm->mmu_lock);
  7345. indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
  7346. write_unlock(&vcpu->kvm->mmu_lock);
  7347. if (indirect_shadow_pages)
  7348. kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
  7349. return true;
  7350. }
  7351. /*
  7352. * if emulation was due to access to shadowed page table
  7353. * and it failed try to unshadow page and re-enter the
  7354. * guest to let CPU execute the instruction.
  7355. */
  7356. kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
  7357. /*
  7358. * If the access faults on its page table, it can not
  7359. * be fixed by unprotecting shadow page and it should
  7360. * be reported to userspace.
  7361. */
  7362. return !write_fault_to_shadow_pgtable;
  7363. }
  7364. static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
  7365. gpa_t cr2_or_gpa, int emulation_type)
  7366. {
  7367. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  7368. unsigned long last_retry_eip, last_retry_addr, gpa = cr2_or_gpa;
  7369. last_retry_eip = vcpu->arch.last_retry_eip;
  7370. last_retry_addr = vcpu->arch.last_retry_addr;
  7371. /*
  7372. * If the emulation is caused by #PF and it is non-page_table
  7373. * writing instruction, it means the VM-EXIT is caused by shadow
  7374. * page protected, we can zap the shadow page and retry this
  7375. * instruction directly.
  7376. *
  7377. * Note: if the guest uses a non-page-table modifying instruction
  7378. * on the PDE that points to the instruction, then we will unmap
  7379. * the instruction and go to an infinite loop. So, we cache the
  7380. * last retried eip and the last fault address, if we meet the eip
  7381. * and the address again, we can break out of the potential infinite
  7382. * loop.
  7383. */
  7384. vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
  7385. if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
  7386. return false;
  7387. if (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
  7388. WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF)))
  7389. return false;
  7390. if (x86_page_table_writing_insn(ctxt))
  7391. return false;
  7392. if (ctxt->eip == last_retry_eip && last_retry_addr == cr2_or_gpa)
  7393. return false;
  7394. vcpu->arch.last_retry_eip = ctxt->eip;
  7395. vcpu->arch.last_retry_addr = cr2_or_gpa;
  7396. if (!vcpu->arch.mmu->root_role.direct)
  7397. gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
  7398. kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
  7399. return true;
  7400. }
  7401. static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
  7402. static int complete_emulated_pio(struct kvm_vcpu *vcpu);
  7403. static void kvm_smm_changed(struct kvm_vcpu *vcpu, bool entering_smm)
  7404. {
  7405. trace_kvm_smm_transition(vcpu->vcpu_id, vcpu->arch.smbase, entering_smm);
  7406. if (entering_smm) {
  7407. vcpu->arch.hflags |= HF_SMM_MASK;
  7408. } else {
  7409. vcpu->arch.hflags &= ~(HF_SMM_MASK | HF_SMM_INSIDE_NMI_MASK);
  7410. /* Process a latched INIT or SMI, if any. */
  7411. kvm_make_request(KVM_REQ_EVENT, vcpu);
  7412. /*
  7413. * Even if KVM_SET_SREGS2 loaded PDPTRs out of band,
  7414. * on SMM exit we still need to reload them from
  7415. * guest memory
  7416. */
  7417. vcpu->arch.pdptrs_from_userspace = false;
  7418. }
  7419. kvm_mmu_reset_context(vcpu);
  7420. }
  7421. static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
  7422. unsigned long *db)
  7423. {
  7424. u32 dr6 = 0;
  7425. int i;
  7426. u32 enable, rwlen;
  7427. enable = dr7;
  7428. rwlen = dr7 >> 16;
  7429. for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
  7430. if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
  7431. dr6 |= (1 << i);
  7432. return dr6;
  7433. }
  7434. static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu)
  7435. {
  7436. struct kvm_run *kvm_run = vcpu->run;
  7437. if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
  7438. kvm_run->debug.arch.dr6 = DR6_BS | DR6_ACTIVE_LOW;
  7439. kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu);
  7440. kvm_run->debug.arch.exception = DB_VECTOR;
  7441. kvm_run->exit_reason = KVM_EXIT_DEBUG;
  7442. return 0;
  7443. }
  7444. kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BS);
  7445. return 1;
  7446. }
  7447. int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
  7448. {
  7449. unsigned long rflags = static_call(kvm_x86_get_rflags)(vcpu);
  7450. int r;
  7451. r = static_call(kvm_x86_skip_emulated_instruction)(vcpu);
  7452. if (unlikely(!r))
  7453. return 0;
  7454. kvm_pmu_trigger_event(vcpu, PERF_COUNT_HW_INSTRUCTIONS);
  7455. /*
  7456. * rflags is the old, "raw" value of the flags. The new value has
  7457. * not been saved yet.
  7458. *
  7459. * This is correct even for TF set by the guest, because "the
  7460. * processor will not generate this exception after the instruction
  7461. * that sets the TF flag".
  7462. */
  7463. if (unlikely(rflags & X86_EFLAGS_TF))
  7464. r = kvm_vcpu_do_singlestep(vcpu);
  7465. return r;
  7466. }
  7467. EXPORT_SYMBOL_GPL(kvm_skip_emulated_instruction);
  7468. static bool kvm_is_code_breakpoint_inhibited(struct kvm_vcpu *vcpu)
  7469. {
  7470. u32 shadow;
  7471. if (kvm_get_rflags(vcpu) & X86_EFLAGS_RF)
  7472. return true;
  7473. /*
  7474. * Intel CPUs inhibit code #DBs when MOV/POP SS blocking is active,
  7475. * but AMD CPUs do not. MOV/POP SS blocking is rare, check that first
  7476. * to avoid the relatively expensive CPUID lookup.
  7477. */
  7478. shadow = static_call(kvm_x86_get_interrupt_shadow)(vcpu);
  7479. return (shadow & KVM_X86_SHADOW_INT_MOV_SS) &&
  7480. guest_cpuid_is_intel(vcpu);
  7481. }
  7482. static bool kvm_vcpu_check_code_breakpoint(struct kvm_vcpu *vcpu,
  7483. int emulation_type, int *r)
  7484. {
  7485. WARN_ON_ONCE(emulation_type & EMULTYPE_NO_DECODE);
  7486. /*
  7487. * Do not check for code breakpoints if hardware has already done the
  7488. * checks, as inferred from the emulation type. On NO_DECODE and SKIP,
  7489. * the instruction has passed all exception checks, and all intercepted
  7490. * exceptions that trigger emulation have lower priority than code
  7491. * breakpoints, i.e. the fact that the intercepted exception occurred
  7492. * means any code breakpoints have already been serviced.
  7493. *
  7494. * Note, KVM needs to check for code #DBs on EMULTYPE_TRAP_UD_FORCED as
  7495. * hardware has checked the RIP of the magic prefix, but not the RIP of
  7496. * the instruction being emulated. The intent of forced emulation is
  7497. * to behave as if KVM intercepted the instruction without an exception
  7498. * and without a prefix.
  7499. */
  7500. if (emulation_type & (EMULTYPE_NO_DECODE | EMULTYPE_SKIP |
  7501. EMULTYPE_TRAP_UD | EMULTYPE_VMWARE_GP | EMULTYPE_PF))
  7502. return false;
  7503. if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
  7504. (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
  7505. struct kvm_run *kvm_run = vcpu->run;
  7506. unsigned long eip = kvm_get_linear_rip(vcpu);
  7507. u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
  7508. vcpu->arch.guest_debug_dr7,
  7509. vcpu->arch.eff_db);
  7510. if (dr6 != 0) {
  7511. kvm_run->debug.arch.dr6 = dr6 | DR6_ACTIVE_LOW;
  7512. kvm_run->debug.arch.pc = eip;
  7513. kvm_run->debug.arch.exception = DB_VECTOR;
  7514. kvm_run->exit_reason = KVM_EXIT_DEBUG;
  7515. *r = 0;
  7516. return true;
  7517. }
  7518. }
  7519. if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
  7520. !kvm_is_code_breakpoint_inhibited(vcpu)) {
  7521. unsigned long eip = kvm_get_linear_rip(vcpu);
  7522. u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
  7523. vcpu->arch.dr7,
  7524. vcpu->arch.db);
  7525. if (dr6 != 0) {
  7526. kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
  7527. *r = 1;
  7528. return true;
  7529. }
  7530. }
  7531. return false;
  7532. }
  7533. static bool is_vmware_backdoor_opcode(struct x86_emulate_ctxt *ctxt)
  7534. {
  7535. switch (ctxt->opcode_len) {
  7536. case 1:
  7537. switch (ctxt->b) {
  7538. case 0xe4: /* IN */
  7539. case 0xe5:
  7540. case 0xec:
  7541. case 0xed:
  7542. case 0xe6: /* OUT */
  7543. case 0xe7:
  7544. case 0xee:
  7545. case 0xef:
  7546. case 0x6c: /* INS */
  7547. case 0x6d:
  7548. case 0x6e: /* OUTS */
  7549. case 0x6f:
  7550. return true;
  7551. }
  7552. break;
  7553. case 2:
  7554. switch (ctxt->b) {
  7555. case 0x33: /* RDPMC */
  7556. return true;
  7557. }
  7558. break;
  7559. }
  7560. return false;
  7561. }
  7562. /*
  7563. * Decode an instruction for emulation. The caller is responsible for handling
  7564. * code breakpoints. Note, manually detecting code breakpoints is unnecessary
  7565. * (and wrong) when emulating on an intercepted fault-like exception[*], as
  7566. * code breakpoints have higher priority and thus have already been done by
  7567. * hardware.
  7568. *
  7569. * [*] Except #MC, which is higher priority, but KVM should never emulate in
  7570. * response to a machine check.
  7571. */
  7572. int x86_decode_emulated_instruction(struct kvm_vcpu *vcpu, int emulation_type,
  7573. void *insn, int insn_len)
  7574. {
  7575. struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
  7576. int r;
  7577. init_emulate_ctxt(vcpu);
  7578. r = x86_decode_insn(ctxt, insn, insn_len, emulation_type);
  7579. trace_kvm_emulate_insn_start(vcpu);
  7580. ++vcpu->stat.insn_emulation;
  7581. return r;
  7582. }
  7583. EXPORT_SYMBOL_GPL(x86_decode_emulated_instruction);
  7584. int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
  7585. int emulation_type, void *insn, int insn_len)
  7586. {
  7587. int r;
  7588. struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
  7589. bool writeback = true;
  7590. bool write_fault_to_spt;
  7591. if (unlikely(!kvm_can_emulate_insn(vcpu, emulation_type, insn, insn_len)))
  7592. return 1;
  7593. vcpu->arch.l1tf_flush_l1d = true;
  7594. /*
  7595. * Clear write_fault_to_shadow_pgtable here to ensure it is
  7596. * never reused.
  7597. */
  7598. write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
  7599. vcpu->arch.write_fault_to_shadow_pgtable = false;
  7600. if (!(emulation_type & EMULTYPE_NO_DECODE)) {
  7601. kvm_clear_exception_queue(vcpu);
  7602. /*
  7603. * Return immediately if RIP hits a code breakpoint, such #DBs
  7604. * are fault-like and are higher priority than any faults on
  7605. * the code fetch itself.
  7606. */
  7607. if (kvm_vcpu_check_code_breakpoint(vcpu, emulation_type, &r))
  7608. return r;
  7609. r = x86_decode_emulated_instruction(vcpu, emulation_type,
  7610. insn, insn_len);
  7611. if (r != EMULATION_OK) {
  7612. if ((emulation_type & EMULTYPE_TRAP_UD) ||
  7613. (emulation_type & EMULTYPE_TRAP_UD_FORCED)) {
  7614. kvm_queue_exception(vcpu, UD_VECTOR);
  7615. return 1;
  7616. }
  7617. if (reexecute_instruction(vcpu, cr2_or_gpa,
  7618. write_fault_to_spt,
  7619. emulation_type))
  7620. return 1;
  7621. if (ctxt->have_exception &&
  7622. !(emulation_type & EMULTYPE_SKIP)) {
  7623. /*
  7624. * #UD should result in just EMULATION_FAILED, and trap-like
  7625. * exception should not be encountered during decode.
  7626. */
  7627. WARN_ON_ONCE(ctxt->exception.vector == UD_VECTOR ||
  7628. exception_type(ctxt->exception.vector) == EXCPT_TRAP);
  7629. inject_emulated_exception(vcpu);
  7630. return 1;
  7631. }
  7632. return handle_emulation_failure(vcpu, emulation_type);
  7633. }
  7634. }
  7635. if ((emulation_type & EMULTYPE_VMWARE_GP) &&
  7636. !is_vmware_backdoor_opcode(ctxt)) {
  7637. kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
  7638. return 1;
  7639. }
  7640. /*
  7641. * EMULTYPE_SKIP without EMULTYPE_COMPLETE_USER_EXIT is intended for
  7642. * use *only* by vendor callbacks for kvm_skip_emulated_instruction().
  7643. * The caller is responsible for updating interruptibility state and
  7644. * injecting single-step #DBs.
  7645. */
  7646. if (emulation_type & EMULTYPE_SKIP) {
  7647. if (ctxt->mode != X86EMUL_MODE_PROT64)
  7648. ctxt->eip = (u32)ctxt->_eip;
  7649. else
  7650. ctxt->eip = ctxt->_eip;
  7651. if (emulation_type & EMULTYPE_COMPLETE_USER_EXIT) {
  7652. r = 1;
  7653. goto writeback;
  7654. }
  7655. kvm_rip_write(vcpu, ctxt->eip);
  7656. if (ctxt->eflags & X86_EFLAGS_RF)
  7657. kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
  7658. return 1;
  7659. }
  7660. if (retry_instruction(ctxt, cr2_or_gpa, emulation_type))
  7661. return 1;
  7662. /* this is needed for vmware backdoor interface to work since it
  7663. changes registers values during IO operation */
  7664. if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
  7665. vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
  7666. emulator_invalidate_register_cache(ctxt);
  7667. }
  7668. restart:
  7669. if (emulation_type & EMULTYPE_PF) {
  7670. /* Save the faulting GPA (cr2) in the address field */
  7671. ctxt->exception.address = cr2_or_gpa;
  7672. /* With shadow page tables, cr2 contains a GVA or nGPA. */
  7673. if (vcpu->arch.mmu->root_role.direct) {
  7674. ctxt->gpa_available = true;
  7675. ctxt->gpa_val = cr2_or_gpa;
  7676. }
  7677. } else {
  7678. /* Sanitize the address out of an abundance of paranoia. */
  7679. ctxt->exception.address = 0;
  7680. }
  7681. r = x86_emulate_insn(ctxt);
  7682. if (r == EMULATION_INTERCEPTED)
  7683. return 1;
  7684. if (r == EMULATION_FAILED) {
  7685. if (reexecute_instruction(vcpu, cr2_or_gpa, write_fault_to_spt,
  7686. emulation_type))
  7687. return 1;
  7688. return handle_emulation_failure(vcpu, emulation_type);
  7689. }
  7690. if (ctxt->have_exception) {
  7691. r = 1;
  7692. inject_emulated_exception(vcpu);
  7693. } else if (vcpu->arch.pio.count) {
  7694. if (!vcpu->arch.pio.in) {
  7695. /* FIXME: return into emulator if single-stepping. */
  7696. vcpu->arch.pio.count = 0;
  7697. } else {
  7698. writeback = false;
  7699. vcpu->arch.complete_userspace_io = complete_emulated_pio;
  7700. }
  7701. r = 0;
  7702. } else if (vcpu->mmio_needed) {
  7703. ++vcpu->stat.mmio_exits;
  7704. if (!vcpu->mmio_is_write)
  7705. writeback = false;
  7706. r = 0;
  7707. vcpu->arch.complete_userspace_io = complete_emulated_mmio;
  7708. } else if (vcpu->arch.complete_userspace_io) {
  7709. writeback = false;
  7710. r = 0;
  7711. } else if (r == EMULATION_RESTART)
  7712. goto restart;
  7713. else
  7714. r = 1;
  7715. writeback:
  7716. if (writeback) {
  7717. unsigned long rflags = static_call(kvm_x86_get_rflags)(vcpu);
  7718. toggle_interruptibility(vcpu, ctxt->interruptibility);
  7719. vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
  7720. /*
  7721. * Note, EXCPT_DB is assumed to be fault-like as the emulator
  7722. * only supports code breakpoints and general detect #DB, both
  7723. * of which are fault-like.
  7724. */
  7725. if (!ctxt->have_exception ||
  7726. exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
  7727. kvm_pmu_trigger_event(vcpu, PERF_COUNT_HW_INSTRUCTIONS);
  7728. if (ctxt->is_branch)
  7729. kvm_pmu_trigger_event(vcpu, PERF_COUNT_HW_BRANCH_INSTRUCTIONS);
  7730. kvm_rip_write(vcpu, ctxt->eip);
  7731. if (r && (ctxt->tf || (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)))
  7732. r = kvm_vcpu_do_singlestep(vcpu);
  7733. static_call_cond(kvm_x86_update_emulated_instruction)(vcpu);
  7734. __kvm_set_rflags(vcpu, ctxt->eflags);
  7735. }
  7736. /*
  7737. * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
  7738. * do nothing, and it will be requested again as soon as
  7739. * the shadow expires. But we still need to check here,
  7740. * because POPF has no interrupt shadow.
  7741. */
  7742. if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
  7743. kvm_make_request(KVM_REQ_EVENT, vcpu);
  7744. } else
  7745. vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
  7746. return r;
  7747. }
  7748. int kvm_emulate_instruction(struct kvm_vcpu *vcpu, int emulation_type)
  7749. {
  7750. return x86_emulate_instruction(vcpu, 0, emulation_type, NULL, 0);
  7751. }
  7752. EXPORT_SYMBOL_GPL(kvm_emulate_instruction);
  7753. int kvm_emulate_instruction_from_buffer(struct kvm_vcpu *vcpu,
  7754. void *insn, int insn_len)
  7755. {
  7756. return x86_emulate_instruction(vcpu, 0, 0, insn, insn_len);
  7757. }
  7758. EXPORT_SYMBOL_GPL(kvm_emulate_instruction_from_buffer);
  7759. static int complete_fast_pio_out_port_0x7e(struct kvm_vcpu *vcpu)
  7760. {
  7761. vcpu->arch.pio.count = 0;
  7762. return 1;
  7763. }
  7764. static int complete_fast_pio_out(struct kvm_vcpu *vcpu)
  7765. {
  7766. vcpu->arch.pio.count = 0;
  7767. if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip)))
  7768. return 1;
  7769. return kvm_skip_emulated_instruction(vcpu);
  7770. }
  7771. static int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size,
  7772. unsigned short port)
  7773. {
  7774. unsigned long val = kvm_rax_read(vcpu);
  7775. int ret = emulator_pio_out(vcpu, size, port, &val, 1);
  7776. if (ret)
  7777. return ret;
  7778. /*
  7779. * Workaround userspace that relies on old KVM behavior of %rip being
  7780. * incremented prior to exiting to userspace to handle "OUT 0x7e".
  7781. */
  7782. if (port == 0x7e &&
  7783. kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_OUT_7E_INC_RIP)) {
  7784. vcpu->arch.complete_userspace_io =
  7785. complete_fast_pio_out_port_0x7e;
  7786. kvm_skip_emulated_instruction(vcpu);
  7787. } else {
  7788. vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
  7789. vcpu->arch.complete_userspace_io = complete_fast_pio_out;
  7790. }
  7791. return 0;
  7792. }
  7793. static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
  7794. {
  7795. unsigned long val;
  7796. /* We should only ever be called with arch.pio.count equal to 1 */
  7797. BUG_ON(vcpu->arch.pio.count != 1);
  7798. if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.pio.linear_rip))) {
  7799. vcpu->arch.pio.count = 0;
  7800. return 1;
  7801. }
  7802. /* For size less than 4 we merge, else we zero extend */
  7803. val = (vcpu->arch.pio.size < 4) ? kvm_rax_read(vcpu) : 0;
  7804. complete_emulator_pio_in(vcpu, &val);
  7805. kvm_rax_write(vcpu, val);
  7806. return kvm_skip_emulated_instruction(vcpu);
  7807. }
  7808. static int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size,
  7809. unsigned short port)
  7810. {
  7811. unsigned long val;
  7812. int ret;
  7813. /* For size less than 4 we merge, else we zero extend */
  7814. val = (size < 4) ? kvm_rax_read(vcpu) : 0;
  7815. ret = emulator_pio_in(vcpu, size, port, &val, 1);
  7816. if (ret) {
  7817. kvm_rax_write(vcpu, val);
  7818. return ret;
  7819. }
  7820. vcpu->arch.pio.linear_rip = kvm_get_linear_rip(vcpu);
  7821. vcpu->arch.complete_userspace_io = complete_fast_pio_in;
  7822. return 0;
  7823. }
  7824. int kvm_fast_pio(struct kvm_vcpu *vcpu, int size, unsigned short port, int in)
  7825. {
  7826. int ret;
  7827. if (in)
  7828. ret = kvm_fast_pio_in(vcpu, size, port);
  7829. else
  7830. ret = kvm_fast_pio_out(vcpu, size, port);
  7831. return ret && kvm_skip_emulated_instruction(vcpu);
  7832. }
  7833. EXPORT_SYMBOL_GPL(kvm_fast_pio);
  7834. static int kvmclock_cpu_down_prep(unsigned int cpu)
  7835. {
  7836. __this_cpu_write(cpu_tsc_khz, 0);
  7837. return 0;
  7838. }
  7839. static void tsc_khz_changed(void *data)
  7840. {
  7841. struct cpufreq_freqs *freq = data;
  7842. unsigned long khz = 0;
  7843. if (data)
  7844. khz = freq->new;
  7845. else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
  7846. khz = cpufreq_quick_get(raw_smp_processor_id());
  7847. if (!khz)
  7848. khz = tsc_khz;
  7849. __this_cpu_write(cpu_tsc_khz, khz);
  7850. }
  7851. #ifdef CONFIG_X86_64
  7852. static void kvm_hyperv_tsc_notifier(void)
  7853. {
  7854. struct kvm *kvm;
  7855. int cpu;
  7856. mutex_lock(&kvm_lock);
  7857. list_for_each_entry(kvm, &vm_list, vm_list)
  7858. kvm_make_mclock_inprogress_request(kvm);
  7859. /* no guest entries from this point */
  7860. hyperv_stop_tsc_emulation();
  7861. /* TSC frequency always matches when on Hyper-V */
  7862. for_each_present_cpu(cpu)
  7863. per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
  7864. kvm_caps.max_guest_tsc_khz = tsc_khz;
  7865. list_for_each_entry(kvm, &vm_list, vm_list) {
  7866. __kvm_start_pvclock_update(kvm);
  7867. pvclock_update_vm_gtod_copy(kvm);
  7868. kvm_end_pvclock_update(kvm);
  7869. }
  7870. mutex_unlock(&kvm_lock);
  7871. }
  7872. #endif
  7873. static void __kvmclock_cpufreq_notifier(struct cpufreq_freqs *freq, int cpu)
  7874. {
  7875. struct kvm *kvm;
  7876. struct kvm_vcpu *vcpu;
  7877. int send_ipi = 0;
  7878. unsigned long i;
  7879. /*
  7880. * We allow guests to temporarily run on slowing clocks,
  7881. * provided we notify them after, or to run on accelerating
  7882. * clocks, provided we notify them before. Thus time never
  7883. * goes backwards.
  7884. *
  7885. * However, we have a problem. We can't atomically update
  7886. * the frequency of a given CPU from this function; it is
  7887. * merely a notifier, which can be called from any CPU.
  7888. * Changing the TSC frequency at arbitrary points in time
  7889. * requires a recomputation of local variables related to
  7890. * the TSC for each VCPU. We must flag these local variables
  7891. * to be updated and be sure the update takes place with the
  7892. * new frequency before any guests proceed.
  7893. *
  7894. * Unfortunately, the combination of hotplug CPU and frequency
  7895. * change creates an intractable locking scenario; the order
  7896. * of when these callouts happen is undefined with respect to
  7897. * CPU hotplug, and they can race with each other. As such,
  7898. * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
  7899. * undefined; you can actually have a CPU frequency change take
  7900. * place in between the computation of X and the setting of the
  7901. * variable. To protect against this problem, all updates of
  7902. * the per_cpu tsc_khz variable are done in an interrupt
  7903. * protected IPI, and all callers wishing to update the value
  7904. * must wait for a synchronous IPI to complete (which is trivial
  7905. * if the caller is on the CPU already). This establishes the
  7906. * necessary total order on variable updates.
  7907. *
  7908. * Note that because a guest time update may take place
  7909. * anytime after the setting of the VCPU's request bit, the
  7910. * correct TSC value must be set before the request. However,
  7911. * to ensure the update actually makes it to any guest which
  7912. * starts running in hardware virtualization between the set
  7913. * and the acquisition of the spinlock, we must also ping the
  7914. * CPU after setting the request bit.
  7915. *
  7916. */
  7917. smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
  7918. mutex_lock(&kvm_lock);
  7919. list_for_each_entry(kvm, &vm_list, vm_list) {
  7920. kvm_for_each_vcpu(i, vcpu, kvm) {
  7921. if (vcpu->cpu != cpu)
  7922. continue;
  7923. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  7924. if (vcpu->cpu != raw_smp_processor_id())
  7925. send_ipi = 1;
  7926. }
  7927. }
  7928. mutex_unlock(&kvm_lock);
  7929. if (freq->old < freq->new && send_ipi) {
  7930. /*
  7931. * We upscale the frequency. Must make the guest
  7932. * doesn't see old kvmclock values while running with
  7933. * the new frequency, otherwise we risk the guest sees
  7934. * time go backwards.
  7935. *
  7936. * In case we update the frequency for another cpu
  7937. * (which might be in guest context) send an interrupt
  7938. * to kick the cpu out of guest context. Next time
  7939. * guest context is entered kvmclock will be updated,
  7940. * so the guest will not see stale values.
  7941. */
  7942. smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
  7943. }
  7944. }
  7945. static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
  7946. void *data)
  7947. {
  7948. struct cpufreq_freqs *freq = data;
  7949. int cpu;
  7950. if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
  7951. return 0;
  7952. if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
  7953. return 0;
  7954. for_each_cpu(cpu, freq->policy->cpus)
  7955. __kvmclock_cpufreq_notifier(freq, cpu);
  7956. return 0;
  7957. }
  7958. static struct notifier_block kvmclock_cpufreq_notifier_block = {
  7959. .notifier_call = kvmclock_cpufreq_notifier
  7960. };
  7961. static int kvmclock_cpu_online(unsigned int cpu)
  7962. {
  7963. tsc_khz_changed(NULL);
  7964. return 0;
  7965. }
  7966. static void kvm_timer_init(void)
  7967. {
  7968. if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
  7969. max_tsc_khz = tsc_khz;
  7970. if (IS_ENABLED(CONFIG_CPU_FREQ)) {
  7971. struct cpufreq_policy *policy;
  7972. int cpu;
  7973. cpu = get_cpu();
  7974. policy = cpufreq_cpu_get(cpu);
  7975. if (policy) {
  7976. if (policy->cpuinfo.max_freq)
  7977. max_tsc_khz = policy->cpuinfo.max_freq;
  7978. cpufreq_cpu_put(policy);
  7979. }
  7980. put_cpu();
  7981. }
  7982. cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
  7983. CPUFREQ_TRANSITION_NOTIFIER);
  7984. }
  7985. cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
  7986. kvmclock_cpu_online, kvmclock_cpu_down_prep);
  7987. }
  7988. #ifdef CONFIG_X86_64
  7989. static void pvclock_gtod_update_fn(struct work_struct *work)
  7990. {
  7991. struct kvm *kvm;
  7992. struct kvm_vcpu *vcpu;
  7993. unsigned long i;
  7994. mutex_lock(&kvm_lock);
  7995. list_for_each_entry(kvm, &vm_list, vm_list)
  7996. kvm_for_each_vcpu(i, vcpu, kvm)
  7997. kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
  7998. atomic_set(&kvm_guest_has_master_clock, 0);
  7999. mutex_unlock(&kvm_lock);
  8000. }
  8001. static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
  8002. /*
  8003. * Indirection to move queue_work() out of the tk_core.seq write held
  8004. * region to prevent possible deadlocks against time accessors which
  8005. * are invoked with work related locks held.
  8006. */
  8007. static void pvclock_irq_work_fn(struct irq_work *w)
  8008. {
  8009. queue_work(system_long_wq, &pvclock_gtod_work);
  8010. }
  8011. static DEFINE_IRQ_WORK(pvclock_irq_work, pvclock_irq_work_fn);
  8012. /*
  8013. * Notification about pvclock gtod data update.
  8014. */
  8015. static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
  8016. void *priv)
  8017. {
  8018. struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
  8019. struct timekeeper *tk = priv;
  8020. update_pvclock_gtod(tk);
  8021. /*
  8022. * Disable master clock if host does not trust, or does not use,
  8023. * TSC based clocksource. Delegate queue_work() to irq_work as
  8024. * this is invoked with tk_core.seq write held.
  8025. */
  8026. if (!gtod_is_based_on_tsc(gtod->clock.vclock_mode) &&
  8027. atomic_read(&kvm_guest_has_master_clock) != 0)
  8028. irq_work_queue(&pvclock_irq_work);
  8029. return 0;
  8030. }
  8031. static struct notifier_block pvclock_gtod_notifier = {
  8032. .notifier_call = pvclock_gtod_notify,
  8033. };
  8034. #endif
  8035. int kvm_arch_init(void *opaque)
  8036. {
  8037. return 0;
  8038. }
  8039. void kvm_arch_exit(void)
  8040. {
  8041. }
  8042. int kvm_x86_vendor_init(struct kvm_x86_init_ops *ops)
  8043. {
  8044. u64 host_pat;
  8045. int r;
  8046. if (kvm_x86_ops.hardware_enable) {
  8047. pr_err("kvm: already loaded vendor module '%s'\n", kvm_x86_ops.name);
  8048. return -EEXIST;
  8049. }
  8050. if (!ops->cpu_has_kvm_support()) {
  8051. pr_err_ratelimited("kvm: no hardware support for '%s'\n",
  8052. ops->runtime_ops->name);
  8053. return -EOPNOTSUPP;
  8054. }
  8055. if (ops->disabled_by_bios()) {
  8056. pr_err_ratelimited("kvm: support for '%s' disabled by bios\n",
  8057. ops->runtime_ops->name);
  8058. return -EOPNOTSUPP;
  8059. }
  8060. /*
  8061. * KVM explicitly assumes that the guest has an FPU and
  8062. * FXSAVE/FXRSTOR. For example, the KVM_GET_FPU explicitly casts the
  8063. * vCPU's FPU state as a fxregs_state struct.
  8064. */
  8065. if (!boot_cpu_has(X86_FEATURE_FPU) || !boot_cpu_has(X86_FEATURE_FXSR)) {
  8066. printk(KERN_ERR "kvm: inadequate fpu\n");
  8067. return -EOPNOTSUPP;
  8068. }
  8069. if (IS_ENABLED(CONFIG_PREEMPT_RT) && !boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
  8070. pr_err("RT requires X86_FEATURE_CONSTANT_TSC\n");
  8071. return -EOPNOTSUPP;
  8072. }
  8073. /*
  8074. * KVM assumes that PAT entry '0' encodes WB memtype and simply zeroes
  8075. * the PAT bits in SPTEs. Bail if PAT[0] is programmed to something
  8076. * other than WB. Note, EPT doesn't utilize the PAT, but don't bother
  8077. * with an exception. PAT[0] is set to WB on RESET and also by the
  8078. * kernel, i.e. failure indicates a kernel bug or broken firmware.
  8079. */
  8080. if (rdmsrl_safe(MSR_IA32_CR_PAT, &host_pat) ||
  8081. (host_pat & GENMASK(2, 0)) != 6) {
  8082. pr_err("kvm: host PAT[0] is not WB\n");
  8083. return -EIO;
  8084. }
  8085. x86_emulator_cache = kvm_alloc_emulator_cache();
  8086. if (!x86_emulator_cache) {
  8087. pr_err("kvm: failed to allocate cache for x86 emulator\n");
  8088. return -ENOMEM;
  8089. }
  8090. user_return_msrs = alloc_percpu(struct kvm_user_return_msrs);
  8091. if (!user_return_msrs) {
  8092. printk(KERN_ERR "kvm: failed to allocate percpu kvm_user_return_msrs\n");
  8093. r = -ENOMEM;
  8094. goto out_free_x86_emulator_cache;
  8095. }
  8096. kvm_nr_uret_msrs = 0;
  8097. r = kvm_mmu_vendor_module_init();
  8098. if (r)
  8099. goto out_free_percpu;
  8100. kvm_timer_init();
  8101. if (boot_cpu_has(X86_FEATURE_XSAVE)) {
  8102. host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
  8103. kvm_caps.supported_xcr0 = host_xcr0 & KVM_SUPPORTED_XCR0;
  8104. }
  8105. if (pi_inject_timer == -1)
  8106. pi_inject_timer = housekeeping_enabled(HK_TYPE_TIMER);
  8107. #ifdef CONFIG_X86_64
  8108. pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
  8109. if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
  8110. set_hv_tscchange_cb(kvm_hyperv_tsc_notifier);
  8111. #endif
  8112. return 0;
  8113. out_free_percpu:
  8114. free_percpu(user_return_msrs);
  8115. out_free_x86_emulator_cache:
  8116. kmem_cache_destroy(x86_emulator_cache);
  8117. return r;
  8118. }
  8119. EXPORT_SYMBOL_GPL(kvm_x86_vendor_init);
  8120. void kvm_x86_vendor_exit(void)
  8121. {
  8122. #ifdef CONFIG_X86_64
  8123. if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
  8124. clear_hv_tscchange_cb();
  8125. #endif
  8126. kvm_lapic_exit();
  8127. if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
  8128. cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
  8129. CPUFREQ_TRANSITION_NOTIFIER);
  8130. cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
  8131. #ifdef CONFIG_X86_64
  8132. pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
  8133. irq_work_sync(&pvclock_irq_work);
  8134. cancel_work_sync(&pvclock_gtod_work);
  8135. #endif
  8136. kvm_x86_ops.hardware_enable = NULL;
  8137. kvm_mmu_vendor_module_exit();
  8138. free_percpu(user_return_msrs);
  8139. kmem_cache_destroy(x86_emulator_cache);
  8140. #ifdef CONFIG_KVM_XEN
  8141. static_key_deferred_flush(&kvm_xen_enabled);
  8142. WARN_ON(static_branch_unlikely(&kvm_xen_enabled.key));
  8143. #endif
  8144. }
  8145. EXPORT_SYMBOL_GPL(kvm_x86_vendor_exit);
  8146. static int __kvm_emulate_halt(struct kvm_vcpu *vcpu, int state, int reason)
  8147. {
  8148. /*
  8149. * The vCPU has halted, e.g. executed HLT. Update the run state if the
  8150. * local APIC is in-kernel, the run loop will detect the non-runnable
  8151. * state and halt the vCPU. Exit to userspace if the local APIC is
  8152. * managed by userspace, in which case userspace is responsible for
  8153. * handling wake events.
  8154. */
  8155. ++vcpu->stat.halt_exits;
  8156. if (lapic_in_kernel(vcpu)) {
  8157. vcpu->arch.mp_state = state;
  8158. return 1;
  8159. } else {
  8160. vcpu->run->exit_reason = reason;
  8161. return 0;
  8162. }
  8163. }
  8164. int kvm_emulate_halt_noskip(struct kvm_vcpu *vcpu)
  8165. {
  8166. return __kvm_emulate_halt(vcpu, KVM_MP_STATE_HALTED, KVM_EXIT_HLT);
  8167. }
  8168. EXPORT_SYMBOL_GPL(kvm_emulate_halt_noskip);
  8169. int kvm_emulate_halt(struct kvm_vcpu *vcpu)
  8170. {
  8171. int ret = kvm_skip_emulated_instruction(vcpu);
  8172. /*
  8173. * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
  8174. * KVM_EXIT_DEBUG here.
  8175. */
  8176. return kvm_emulate_halt_noskip(vcpu) && ret;
  8177. }
  8178. EXPORT_SYMBOL_GPL(kvm_emulate_halt);
  8179. int kvm_emulate_ap_reset_hold(struct kvm_vcpu *vcpu)
  8180. {
  8181. int ret = kvm_skip_emulated_instruction(vcpu);
  8182. return __kvm_emulate_halt(vcpu, KVM_MP_STATE_AP_RESET_HOLD,
  8183. KVM_EXIT_AP_RESET_HOLD) && ret;
  8184. }
  8185. EXPORT_SYMBOL_GPL(kvm_emulate_ap_reset_hold);
  8186. #ifdef CONFIG_X86_64
  8187. static int kvm_pv_clock_pairing(struct kvm_vcpu *vcpu, gpa_t paddr,
  8188. unsigned long clock_type)
  8189. {
  8190. struct kvm_clock_pairing clock_pairing;
  8191. struct timespec64 ts;
  8192. u64 cycle;
  8193. int ret;
  8194. if (clock_type != KVM_CLOCK_PAIRING_WALLCLOCK)
  8195. return -KVM_EOPNOTSUPP;
  8196. /*
  8197. * When tsc is in permanent catchup mode guests won't be able to use
  8198. * pvclock_read_retry loop to get consistent view of pvclock
  8199. */
  8200. if (vcpu->arch.tsc_always_catchup)
  8201. return -KVM_EOPNOTSUPP;
  8202. if (!kvm_get_walltime_and_clockread(&ts, &cycle))
  8203. return -KVM_EOPNOTSUPP;
  8204. clock_pairing.sec = ts.tv_sec;
  8205. clock_pairing.nsec = ts.tv_nsec;
  8206. clock_pairing.tsc = kvm_read_l1_tsc(vcpu, cycle);
  8207. clock_pairing.flags = 0;
  8208. memset(&clock_pairing.pad, 0, sizeof(clock_pairing.pad));
  8209. ret = 0;
  8210. if (kvm_write_guest(vcpu->kvm, paddr, &clock_pairing,
  8211. sizeof(struct kvm_clock_pairing)))
  8212. ret = -KVM_EFAULT;
  8213. return ret;
  8214. }
  8215. #endif
  8216. /*
  8217. * kvm_pv_kick_cpu_op: Kick a vcpu.
  8218. *
  8219. * @apicid - apicid of vcpu to be kicked.
  8220. */
  8221. static void kvm_pv_kick_cpu_op(struct kvm *kvm, int apicid)
  8222. {
  8223. /*
  8224. * All other fields are unused for APIC_DM_REMRD, but may be consumed by
  8225. * common code, e.g. for tracing. Defer initialization to the compiler.
  8226. */
  8227. struct kvm_lapic_irq lapic_irq = {
  8228. .delivery_mode = APIC_DM_REMRD,
  8229. .dest_mode = APIC_DEST_PHYSICAL,
  8230. .shorthand = APIC_DEST_NOSHORT,
  8231. .dest_id = apicid,
  8232. };
  8233. kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
  8234. }
  8235. bool kvm_apicv_activated(struct kvm *kvm)
  8236. {
  8237. return (READ_ONCE(kvm->arch.apicv_inhibit_reasons) == 0);
  8238. }
  8239. EXPORT_SYMBOL_GPL(kvm_apicv_activated);
  8240. bool kvm_vcpu_apicv_activated(struct kvm_vcpu *vcpu)
  8241. {
  8242. ulong vm_reasons = READ_ONCE(vcpu->kvm->arch.apicv_inhibit_reasons);
  8243. ulong vcpu_reasons = static_call(kvm_x86_vcpu_get_apicv_inhibit_reasons)(vcpu);
  8244. return (vm_reasons | vcpu_reasons) == 0;
  8245. }
  8246. EXPORT_SYMBOL_GPL(kvm_vcpu_apicv_activated);
  8247. static void set_or_clear_apicv_inhibit(unsigned long *inhibits,
  8248. enum kvm_apicv_inhibit reason, bool set)
  8249. {
  8250. if (set)
  8251. __set_bit(reason, inhibits);
  8252. else
  8253. __clear_bit(reason, inhibits);
  8254. trace_kvm_apicv_inhibit_changed(reason, set, *inhibits);
  8255. }
  8256. static void kvm_apicv_init(struct kvm *kvm)
  8257. {
  8258. unsigned long *inhibits = &kvm->arch.apicv_inhibit_reasons;
  8259. init_rwsem(&kvm->arch.apicv_update_lock);
  8260. set_or_clear_apicv_inhibit(inhibits, APICV_INHIBIT_REASON_ABSENT, true);
  8261. if (!enable_apicv)
  8262. set_or_clear_apicv_inhibit(inhibits,
  8263. APICV_INHIBIT_REASON_DISABLE, true);
  8264. }
  8265. static void kvm_sched_yield(struct kvm_vcpu *vcpu, unsigned long dest_id)
  8266. {
  8267. struct kvm_vcpu *target = NULL;
  8268. struct kvm_apic_map *map;
  8269. vcpu->stat.directed_yield_attempted++;
  8270. if (single_task_running())
  8271. goto no_yield;
  8272. rcu_read_lock();
  8273. map = rcu_dereference(vcpu->kvm->arch.apic_map);
  8274. if (likely(map) && dest_id <= map->max_apic_id && map->phys_map[dest_id])
  8275. target = map->phys_map[dest_id]->vcpu;
  8276. rcu_read_unlock();
  8277. if (!target || !READ_ONCE(target->ready))
  8278. goto no_yield;
  8279. /* Ignore requests to yield to self */
  8280. if (vcpu == target)
  8281. goto no_yield;
  8282. if (kvm_vcpu_yield_to(target) <= 0)
  8283. goto no_yield;
  8284. vcpu->stat.directed_yield_successful++;
  8285. no_yield:
  8286. return;
  8287. }
  8288. static int complete_hypercall_exit(struct kvm_vcpu *vcpu)
  8289. {
  8290. u64 ret = vcpu->run->hypercall.ret;
  8291. if (!is_64_bit_mode(vcpu))
  8292. ret = (u32)ret;
  8293. kvm_rax_write(vcpu, ret);
  8294. ++vcpu->stat.hypercalls;
  8295. return kvm_skip_emulated_instruction(vcpu);
  8296. }
  8297. int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
  8298. {
  8299. unsigned long nr, a0, a1, a2, a3, ret;
  8300. int op_64_bit;
  8301. if (kvm_xen_hypercall_enabled(vcpu->kvm))
  8302. return kvm_xen_hypercall(vcpu);
  8303. if (kvm_hv_hypercall_enabled(vcpu))
  8304. return kvm_hv_hypercall(vcpu);
  8305. nr = kvm_rax_read(vcpu);
  8306. a0 = kvm_rbx_read(vcpu);
  8307. a1 = kvm_rcx_read(vcpu);
  8308. a2 = kvm_rdx_read(vcpu);
  8309. a3 = kvm_rsi_read(vcpu);
  8310. trace_kvm_hypercall(nr, a0, a1, a2, a3);
  8311. op_64_bit = is_64_bit_hypercall(vcpu);
  8312. if (!op_64_bit) {
  8313. nr &= 0xFFFFFFFF;
  8314. a0 &= 0xFFFFFFFF;
  8315. a1 &= 0xFFFFFFFF;
  8316. a2 &= 0xFFFFFFFF;
  8317. a3 &= 0xFFFFFFFF;
  8318. }
  8319. if (static_call(kvm_x86_get_cpl)(vcpu) != 0) {
  8320. ret = -KVM_EPERM;
  8321. goto out;
  8322. }
  8323. ret = -KVM_ENOSYS;
  8324. switch (nr) {
  8325. case KVM_HC_VAPIC_POLL_IRQ:
  8326. ret = 0;
  8327. break;
  8328. case KVM_HC_KICK_CPU:
  8329. if (!guest_pv_has(vcpu, KVM_FEATURE_PV_UNHALT))
  8330. break;
  8331. kvm_pv_kick_cpu_op(vcpu->kvm, a1);
  8332. kvm_sched_yield(vcpu, a1);
  8333. ret = 0;
  8334. break;
  8335. #ifdef CONFIG_X86_64
  8336. case KVM_HC_CLOCK_PAIRING:
  8337. ret = kvm_pv_clock_pairing(vcpu, a0, a1);
  8338. break;
  8339. #endif
  8340. case KVM_HC_SEND_IPI:
  8341. if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SEND_IPI))
  8342. break;
  8343. ret = kvm_pv_send_ipi(vcpu->kvm, a0, a1, a2, a3, op_64_bit);
  8344. break;
  8345. case KVM_HC_SCHED_YIELD:
  8346. if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SCHED_YIELD))
  8347. break;
  8348. kvm_sched_yield(vcpu, a0);
  8349. ret = 0;
  8350. break;
  8351. case KVM_HC_MAP_GPA_RANGE: {
  8352. u64 gpa = a0, npages = a1, attrs = a2;
  8353. ret = -KVM_ENOSYS;
  8354. if (!(vcpu->kvm->arch.hypercall_exit_enabled & (1 << KVM_HC_MAP_GPA_RANGE)))
  8355. break;
  8356. if (!PAGE_ALIGNED(gpa) || !npages ||
  8357. gpa_to_gfn(gpa) + npages <= gpa_to_gfn(gpa)) {
  8358. ret = -KVM_EINVAL;
  8359. break;
  8360. }
  8361. vcpu->run->exit_reason = KVM_EXIT_HYPERCALL;
  8362. vcpu->run->hypercall.nr = KVM_HC_MAP_GPA_RANGE;
  8363. vcpu->run->hypercall.args[0] = gpa;
  8364. vcpu->run->hypercall.args[1] = npages;
  8365. vcpu->run->hypercall.args[2] = attrs;
  8366. vcpu->run->hypercall.longmode = op_64_bit;
  8367. vcpu->arch.complete_userspace_io = complete_hypercall_exit;
  8368. return 0;
  8369. }
  8370. default:
  8371. ret = -KVM_ENOSYS;
  8372. break;
  8373. }
  8374. out:
  8375. if (!op_64_bit)
  8376. ret = (u32)ret;
  8377. kvm_rax_write(vcpu, ret);
  8378. ++vcpu->stat.hypercalls;
  8379. return kvm_skip_emulated_instruction(vcpu);
  8380. }
  8381. EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
  8382. static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
  8383. {
  8384. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  8385. char instruction[3];
  8386. unsigned long rip = kvm_rip_read(vcpu);
  8387. /*
  8388. * If the quirk is disabled, synthesize a #UD and let the guest pick up
  8389. * the pieces.
  8390. */
  8391. if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_FIX_HYPERCALL_INSN)) {
  8392. ctxt->exception.error_code_valid = false;
  8393. ctxt->exception.vector = UD_VECTOR;
  8394. ctxt->have_exception = true;
  8395. return X86EMUL_PROPAGATE_FAULT;
  8396. }
  8397. static_call(kvm_x86_patch_hypercall)(vcpu, instruction);
  8398. return emulator_write_emulated(ctxt, rip, instruction, 3,
  8399. &ctxt->exception);
  8400. }
  8401. static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
  8402. {
  8403. return vcpu->run->request_interrupt_window &&
  8404. likely(!pic_in_kernel(vcpu->kvm));
  8405. }
  8406. /* Called within kvm->srcu read side. */
  8407. static void post_kvm_run_save(struct kvm_vcpu *vcpu)
  8408. {
  8409. struct kvm_run *kvm_run = vcpu->run;
  8410. kvm_run->if_flag = static_call(kvm_x86_get_if_flag)(vcpu);
  8411. kvm_run->cr8 = kvm_get_cr8(vcpu);
  8412. kvm_run->apic_base = kvm_get_apic_base(vcpu);
  8413. kvm_run->ready_for_interrupt_injection =
  8414. pic_in_kernel(vcpu->kvm) ||
  8415. kvm_vcpu_ready_for_interrupt_injection(vcpu);
  8416. if (is_smm(vcpu))
  8417. kvm_run->flags |= KVM_RUN_X86_SMM;
  8418. }
  8419. static void update_cr8_intercept(struct kvm_vcpu *vcpu)
  8420. {
  8421. int max_irr, tpr;
  8422. if (!kvm_x86_ops.update_cr8_intercept)
  8423. return;
  8424. if (!lapic_in_kernel(vcpu))
  8425. return;
  8426. if (vcpu->arch.apic->apicv_active)
  8427. return;
  8428. if (!vcpu->arch.apic->vapic_addr)
  8429. max_irr = kvm_lapic_find_highest_irr(vcpu);
  8430. else
  8431. max_irr = -1;
  8432. if (max_irr != -1)
  8433. max_irr >>= 4;
  8434. tpr = kvm_lapic_get_cr8(vcpu);
  8435. static_call(kvm_x86_update_cr8_intercept)(vcpu, tpr, max_irr);
  8436. }
  8437. int kvm_check_nested_events(struct kvm_vcpu *vcpu)
  8438. {
  8439. if (kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
  8440. kvm_x86_ops.nested_ops->triple_fault(vcpu);
  8441. return 1;
  8442. }
  8443. return kvm_x86_ops.nested_ops->check_events(vcpu);
  8444. }
  8445. static void kvm_inject_exception(struct kvm_vcpu *vcpu)
  8446. {
  8447. /*
  8448. * Suppress the error code if the vCPU is in Real Mode, as Real Mode
  8449. * exceptions don't report error codes. The presence of an error code
  8450. * is carried with the exception and only stripped when the exception
  8451. * is injected as intercepted #PF VM-Exits for AMD's Paged Real Mode do
  8452. * report an error code despite the CPU being in Real Mode.
  8453. */
  8454. vcpu->arch.exception.has_error_code &= is_protmode(vcpu);
  8455. trace_kvm_inj_exception(vcpu->arch.exception.vector,
  8456. vcpu->arch.exception.has_error_code,
  8457. vcpu->arch.exception.error_code,
  8458. vcpu->arch.exception.injected);
  8459. static_call(kvm_x86_inject_exception)(vcpu);
  8460. }
  8461. /*
  8462. * Check for any event (interrupt or exception) that is ready to be injected,
  8463. * and if there is at least one event, inject the event with the highest
  8464. * priority. This handles both "pending" events, i.e. events that have never
  8465. * been injected into the guest, and "injected" events, i.e. events that were
  8466. * injected as part of a previous VM-Enter, but weren't successfully delivered
  8467. * and need to be re-injected.
  8468. *
  8469. * Note, this is not guaranteed to be invoked on a guest instruction boundary,
  8470. * i.e. doesn't guarantee that there's an event window in the guest. KVM must
  8471. * be able to inject exceptions in the "middle" of an instruction, and so must
  8472. * also be able to re-inject NMIs and IRQs in the middle of an instruction.
  8473. * I.e. for exceptions and re-injected events, NOT invoking this on instruction
  8474. * boundaries is necessary and correct.
  8475. *
  8476. * For simplicity, KVM uses a single path to inject all events (except events
  8477. * that are injected directly from L1 to L2) and doesn't explicitly track
  8478. * instruction boundaries for asynchronous events. However, because VM-Exits
  8479. * that can occur during instruction execution typically result in KVM skipping
  8480. * the instruction or injecting an exception, e.g. instruction and exception
  8481. * intercepts, and because pending exceptions have higher priority than pending
  8482. * interrupts, KVM still honors instruction boundaries in most scenarios.
  8483. *
  8484. * But, if a VM-Exit occurs during instruction execution, and KVM does NOT skip
  8485. * the instruction or inject an exception, then KVM can incorrecty inject a new
  8486. * asynchrounous event if the event became pending after the CPU fetched the
  8487. * instruction (in the guest). E.g. if a page fault (#PF, #NPF, EPT violation)
  8488. * occurs and is resolved by KVM, a coincident NMI, SMI, IRQ, etc... can be
  8489. * injected on the restarted instruction instead of being deferred until the
  8490. * instruction completes.
  8491. *
  8492. * In practice, this virtualization hole is unlikely to be observed by the
  8493. * guest, and even less likely to cause functional problems. To detect the
  8494. * hole, the guest would have to trigger an event on a side effect of an early
  8495. * phase of instruction execution, e.g. on the instruction fetch from memory.
  8496. * And for it to be a functional problem, the guest would need to depend on the
  8497. * ordering between that side effect, the instruction completing, _and_ the
  8498. * delivery of the asynchronous event.
  8499. */
  8500. static int kvm_check_and_inject_events(struct kvm_vcpu *vcpu,
  8501. bool *req_immediate_exit)
  8502. {
  8503. bool can_inject;
  8504. int r;
  8505. /*
  8506. * Process nested events first, as nested VM-Exit supercedes event
  8507. * re-injection. If there's an event queued for re-injection, it will
  8508. * be saved into the appropriate vmc{b,s}12 fields on nested VM-Exit.
  8509. */
  8510. if (is_guest_mode(vcpu))
  8511. r = kvm_check_nested_events(vcpu);
  8512. else
  8513. r = 0;
  8514. /*
  8515. * Re-inject exceptions and events *especially* if immediate entry+exit
  8516. * to/from L2 is needed, as any event that has already been injected
  8517. * into L2 needs to complete its lifecycle before injecting a new event.
  8518. *
  8519. * Don't re-inject an NMI or interrupt if there is a pending exception.
  8520. * This collision arises if an exception occurred while vectoring the
  8521. * injected event, KVM intercepted said exception, and KVM ultimately
  8522. * determined the fault belongs to the guest and queues the exception
  8523. * for injection back into the guest.
  8524. *
  8525. * "Injected" interrupts can also collide with pending exceptions if
  8526. * userspace ignores the "ready for injection" flag and blindly queues
  8527. * an interrupt. In that case, prioritizing the exception is correct,
  8528. * as the exception "occurred" before the exit to userspace. Trap-like
  8529. * exceptions, e.g. most #DBs, have higher priority than interrupts.
  8530. * And while fault-like exceptions, e.g. #GP and #PF, are the lowest
  8531. * priority, they're only generated (pended) during instruction
  8532. * execution, and interrupts are recognized at instruction boundaries.
  8533. * Thus a pending fault-like exception means the fault occurred on the
  8534. * *previous* instruction and must be serviced prior to recognizing any
  8535. * new events in order to fully complete the previous instruction.
  8536. */
  8537. if (vcpu->arch.exception.injected)
  8538. kvm_inject_exception(vcpu);
  8539. else if (kvm_is_exception_pending(vcpu))
  8540. ; /* see above */
  8541. else if (vcpu->arch.nmi_injected)
  8542. static_call(kvm_x86_inject_nmi)(vcpu);
  8543. else if (vcpu->arch.interrupt.injected)
  8544. static_call(kvm_x86_inject_irq)(vcpu, true);
  8545. /*
  8546. * Exceptions that morph to VM-Exits are handled above, and pending
  8547. * exceptions on top of injected exceptions that do not VM-Exit should
  8548. * either morph to #DF or, sadly, override the injected exception.
  8549. */
  8550. WARN_ON_ONCE(vcpu->arch.exception.injected &&
  8551. vcpu->arch.exception.pending);
  8552. /*
  8553. * Bail if immediate entry+exit to/from the guest is needed to complete
  8554. * nested VM-Enter or event re-injection so that a different pending
  8555. * event can be serviced (or if KVM needs to exit to userspace).
  8556. *
  8557. * Otherwise, continue processing events even if VM-Exit occurred. The
  8558. * VM-Exit will have cleared exceptions that were meant for L2, but
  8559. * there may now be events that can be injected into L1.
  8560. */
  8561. if (r < 0)
  8562. goto out;
  8563. /*
  8564. * A pending exception VM-Exit should either result in nested VM-Exit
  8565. * or force an immediate re-entry and exit to/from L2, and exception
  8566. * VM-Exits cannot be injected (flag should _never_ be set).
  8567. */
  8568. WARN_ON_ONCE(vcpu->arch.exception_vmexit.injected ||
  8569. vcpu->arch.exception_vmexit.pending);
  8570. /*
  8571. * New events, other than exceptions, cannot be injected if KVM needs
  8572. * to re-inject a previous event. See above comments on re-injecting
  8573. * for why pending exceptions get priority.
  8574. */
  8575. can_inject = !kvm_event_needs_reinjection(vcpu);
  8576. if (vcpu->arch.exception.pending) {
  8577. /*
  8578. * Fault-class exceptions, except #DBs, set RF=1 in the RFLAGS
  8579. * value pushed on the stack. Trap-like exception and all #DBs
  8580. * leave RF as-is (KVM follows Intel's behavior in this regard;
  8581. * AMD states that code breakpoint #DBs excplitly clear RF=0).
  8582. *
  8583. * Note, most versions of Intel's SDM and AMD's APM incorrectly
  8584. * describe the behavior of General Detect #DBs, which are
  8585. * fault-like. They do _not_ set RF, a la code breakpoints.
  8586. */
  8587. if (exception_type(vcpu->arch.exception.vector) == EXCPT_FAULT)
  8588. __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
  8589. X86_EFLAGS_RF);
  8590. if (vcpu->arch.exception.vector == DB_VECTOR) {
  8591. kvm_deliver_exception_payload(vcpu, &vcpu->arch.exception);
  8592. if (vcpu->arch.dr7 & DR7_GD) {
  8593. vcpu->arch.dr7 &= ~DR7_GD;
  8594. kvm_update_dr7(vcpu);
  8595. }
  8596. }
  8597. kvm_inject_exception(vcpu);
  8598. vcpu->arch.exception.pending = false;
  8599. vcpu->arch.exception.injected = true;
  8600. can_inject = false;
  8601. }
  8602. /* Don't inject interrupts if the user asked to avoid doing so */
  8603. if (vcpu->guest_debug & KVM_GUESTDBG_BLOCKIRQ)
  8604. return 0;
  8605. /*
  8606. * Finally, inject interrupt events. If an event cannot be injected
  8607. * due to architectural conditions (e.g. IF=0) a window-open exit
  8608. * will re-request KVM_REQ_EVENT. Sometimes however an event is pending
  8609. * and can architecturally be injected, but we cannot do it right now:
  8610. * an interrupt could have arrived just now and we have to inject it
  8611. * as a vmexit, or there could already an event in the queue, which is
  8612. * indicated by can_inject. In that case we request an immediate exit
  8613. * in order to make progress and get back here for another iteration.
  8614. * The kvm_x86_ops hooks communicate this by returning -EBUSY.
  8615. */
  8616. if (vcpu->arch.smi_pending) {
  8617. r = can_inject ? static_call(kvm_x86_smi_allowed)(vcpu, true) : -EBUSY;
  8618. if (r < 0)
  8619. goto out;
  8620. if (r) {
  8621. vcpu->arch.smi_pending = false;
  8622. ++vcpu->arch.smi_count;
  8623. enter_smm(vcpu);
  8624. can_inject = false;
  8625. } else
  8626. static_call(kvm_x86_enable_smi_window)(vcpu);
  8627. }
  8628. if (vcpu->arch.nmi_pending) {
  8629. r = can_inject ? static_call(kvm_x86_nmi_allowed)(vcpu, true) : -EBUSY;
  8630. if (r < 0)
  8631. goto out;
  8632. if (r) {
  8633. --vcpu->arch.nmi_pending;
  8634. vcpu->arch.nmi_injected = true;
  8635. static_call(kvm_x86_inject_nmi)(vcpu);
  8636. can_inject = false;
  8637. WARN_ON(static_call(kvm_x86_nmi_allowed)(vcpu, true) < 0);
  8638. }
  8639. if (vcpu->arch.nmi_pending)
  8640. static_call(kvm_x86_enable_nmi_window)(vcpu);
  8641. }
  8642. if (kvm_cpu_has_injectable_intr(vcpu)) {
  8643. r = can_inject ? static_call(kvm_x86_interrupt_allowed)(vcpu, true) : -EBUSY;
  8644. if (r < 0)
  8645. goto out;
  8646. if (r) {
  8647. kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu), false);
  8648. static_call(kvm_x86_inject_irq)(vcpu, false);
  8649. WARN_ON(static_call(kvm_x86_interrupt_allowed)(vcpu, true) < 0);
  8650. }
  8651. if (kvm_cpu_has_injectable_intr(vcpu))
  8652. static_call(kvm_x86_enable_irq_window)(vcpu);
  8653. }
  8654. if (is_guest_mode(vcpu) &&
  8655. kvm_x86_ops.nested_ops->has_events &&
  8656. kvm_x86_ops.nested_ops->has_events(vcpu))
  8657. *req_immediate_exit = true;
  8658. /*
  8659. * KVM must never queue a new exception while injecting an event; KVM
  8660. * is done emulating and should only propagate the to-be-injected event
  8661. * to the VMCS/VMCB. Queueing a new exception can put the vCPU into an
  8662. * infinite loop as KVM will bail from VM-Enter to inject the pending
  8663. * exception and start the cycle all over.
  8664. *
  8665. * Exempt triple faults as they have special handling and won't put the
  8666. * vCPU into an infinite loop. Triple fault can be queued when running
  8667. * VMX without unrestricted guest, as that requires KVM to emulate Real
  8668. * Mode events (see kvm_inject_realmode_interrupt()).
  8669. */
  8670. WARN_ON_ONCE(vcpu->arch.exception.pending ||
  8671. vcpu->arch.exception_vmexit.pending);
  8672. return 0;
  8673. out:
  8674. if (r == -EBUSY) {
  8675. *req_immediate_exit = true;
  8676. r = 0;
  8677. }
  8678. return r;
  8679. }
  8680. static void process_nmi(struct kvm_vcpu *vcpu)
  8681. {
  8682. unsigned limit = 2;
  8683. /*
  8684. * x86 is limited to one NMI running, and one NMI pending after it.
  8685. * If an NMI is already in progress, limit further NMIs to just one.
  8686. * Otherwise, allow two (and we'll inject the first one immediately).
  8687. */
  8688. if (static_call(kvm_x86_get_nmi_mask)(vcpu) || vcpu->arch.nmi_injected)
  8689. limit = 1;
  8690. vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
  8691. vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
  8692. kvm_make_request(KVM_REQ_EVENT, vcpu);
  8693. }
  8694. static u32 enter_smm_get_segment_flags(struct kvm_segment *seg)
  8695. {
  8696. u32 flags = 0;
  8697. flags |= seg->g << 23;
  8698. flags |= seg->db << 22;
  8699. flags |= seg->l << 21;
  8700. flags |= seg->avl << 20;
  8701. flags |= seg->present << 15;
  8702. flags |= seg->dpl << 13;
  8703. flags |= seg->s << 12;
  8704. flags |= seg->type << 8;
  8705. return flags;
  8706. }
  8707. static void enter_smm_save_seg_32(struct kvm_vcpu *vcpu, char *buf, int n)
  8708. {
  8709. struct kvm_segment seg;
  8710. int offset;
  8711. kvm_get_segment(vcpu, &seg, n);
  8712. put_smstate(u32, buf, 0x7fa8 + n * 4, seg.selector);
  8713. if (n < 3)
  8714. offset = 0x7f84 + n * 12;
  8715. else
  8716. offset = 0x7f2c + (n - 3) * 12;
  8717. put_smstate(u32, buf, offset + 8, seg.base);
  8718. put_smstate(u32, buf, offset + 4, seg.limit);
  8719. put_smstate(u32, buf, offset, enter_smm_get_segment_flags(&seg));
  8720. }
  8721. #ifdef CONFIG_X86_64
  8722. static void enter_smm_save_seg_64(struct kvm_vcpu *vcpu, char *buf, int n)
  8723. {
  8724. struct kvm_segment seg;
  8725. int offset;
  8726. u16 flags;
  8727. kvm_get_segment(vcpu, &seg, n);
  8728. offset = 0x7e00 + n * 16;
  8729. flags = enter_smm_get_segment_flags(&seg) >> 8;
  8730. put_smstate(u16, buf, offset, seg.selector);
  8731. put_smstate(u16, buf, offset + 2, flags);
  8732. put_smstate(u32, buf, offset + 4, seg.limit);
  8733. put_smstate(u64, buf, offset + 8, seg.base);
  8734. }
  8735. #endif
  8736. static void enter_smm_save_state_32(struct kvm_vcpu *vcpu, char *buf)
  8737. {
  8738. struct desc_ptr dt;
  8739. struct kvm_segment seg;
  8740. unsigned long val;
  8741. int i;
  8742. put_smstate(u32, buf, 0x7ffc, kvm_read_cr0(vcpu));
  8743. put_smstate(u32, buf, 0x7ff8, kvm_read_cr3(vcpu));
  8744. put_smstate(u32, buf, 0x7ff4, kvm_get_rflags(vcpu));
  8745. put_smstate(u32, buf, 0x7ff0, kvm_rip_read(vcpu));
  8746. for (i = 0; i < 8; i++)
  8747. put_smstate(u32, buf, 0x7fd0 + i * 4, kvm_register_read_raw(vcpu, i));
  8748. kvm_get_dr(vcpu, 6, &val);
  8749. put_smstate(u32, buf, 0x7fcc, (u32)val);
  8750. kvm_get_dr(vcpu, 7, &val);
  8751. put_smstate(u32, buf, 0x7fc8, (u32)val);
  8752. kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
  8753. put_smstate(u32, buf, 0x7fc4, seg.selector);
  8754. put_smstate(u32, buf, 0x7f64, seg.base);
  8755. put_smstate(u32, buf, 0x7f60, seg.limit);
  8756. put_smstate(u32, buf, 0x7f5c, enter_smm_get_segment_flags(&seg));
  8757. kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
  8758. put_smstate(u32, buf, 0x7fc0, seg.selector);
  8759. put_smstate(u32, buf, 0x7f80, seg.base);
  8760. put_smstate(u32, buf, 0x7f7c, seg.limit);
  8761. put_smstate(u32, buf, 0x7f78, enter_smm_get_segment_flags(&seg));
  8762. static_call(kvm_x86_get_gdt)(vcpu, &dt);
  8763. put_smstate(u32, buf, 0x7f74, dt.address);
  8764. put_smstate(u32, buf, 0x7f70, dt.size);
  8765. static_call(kvm_x86_get_idt)(vcpu, &dt);
  8766. put_smstate(u32, buf, 0x7f58, dt.address);
  8767. put_smstate(u32, buf, 0x7f54, dt.size);
  8768. for (i = 0; i < 6; i++)
  8769. enter_smm_save_seg_32(vcpu, buf, i);
  8770. put_smstate(u32, buf, 0x7f14, kvm_read_cr4(vcpu));
  8771. /* revision id */
  8772. put_smstate(u32, buf, 0x7efc, 0x00020000);
  8773. put_smstate(u32, buf, 0x7ef8, vcpu->arch.smbase);
  8774. }
  8775. #ifdef CONFIG_X86_64
  8776. static void enter_smm_save_state_64(struct kvm_vcpu *vcpu, char *buf)
  8777. {
  8778. struct desc_ptr dt;
  8779. struct kvm_segment seg;
  8780. unsigned long val;
  8781. int i;
  8782. for (i = 0; i < 16; i++)
  8783. put_smstate(u64, buf, 0x7ff8 - i * 8, kvm_register_read_raw(vcpu, i));
  8784. put_smstate(u64, buf, 0x7f78, kvm_rip_read(vcpu));
  8785. put_smstate(u32, buf, 0x7f70, kvm_get_rflags(vcpu));
  8786. kvm_get_dr(vcpu, 6, &val);
  8787. put_smstate(u64, buf, 0x7f68, val);
  8788. kvm_get_dr(vcpu, 7, &val);
  8789. put_smstate(u64, buf, 0x7f60, val);
  8790. put_smstate(u64, buf, 0x7f58, kvm_read_cr0(vcpu));
  8791. put_smstate(u64, buf, 0x7f50, kvm_read_cr3(vcpu));
  8792. put_smstate(u64, buf, 0x7f48, kvm_read_cr4(vcpu));
  8793. put_smstate(u32, buf, 0x7f00, vcpu->arch.smbase);
  8794. /* revision id */
  8795. put_smstate(u32, buf, 0x7efc, 0x00020064);
  8796. put_smstate(u64, buf, 0x7ed0, vcpu->arch.efer);
  8797. kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
  8798. put_smstate(u16, buf, 0x7e90, seg.selector);
  8799. put_smstate(u16, buf, 0x7e92, enter_smm_get_segment_flags(&seg) >> 8);
  8800. put_smstate(u32, buf, 0x7e94, seg.limit);
  8801. put_smstate(u64, buf, 0x7e98, seg.base);
  8802. static_call(kvm_x86_get_idt)(vcpu, &dt);
  8803. put_smstate(u32, buf, 0x7e84, dt.size);
  8804. put_smstate(u64, buf, 0x7e88, dt.address);
  8805. kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
  8806. put_smstate(u16, buf, 0x7e70, seg.selector);
  8807. put_smstate(u16, buf, 0x7e72, enter_smm_get_segment_flags(&seg) >> 8);
  8808. put_smstate(u32, buf, 0x7e74, seg.limit);
  8809. put_smstate(u64, buf, 0x7e78, seg.base);
  8810. static_call(kvm_x86_get_gdt)(vcpu, &dt);
  8811. put_smstate(u32, buf, 0x7e64, dt.size);
  8812. put_smstate(u64, buf, 0x7e68, dt.address);
  8813. for (i = 0; i < 6; i++)
  8814. enter_smm_save_seg_64(vcpu, buf, i);
  8815. }
  8816. #endif
  8817. static void enter_smm(struct kvm_vcpu *vcpu)
  8818. {
  8819. struct kvm_segment cs, ds;
  8820. struct desc_ptr dt;
  8821. unsigned long cr0;
  8822. char buf[512];
  8823. memset(buf, 0, 512);
  8824. #ifdef CONFIG_X86_64
  8825. if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
  8826. enter_smm_save_state_64(vcpu, buf);
  8827. else
  8828. #endif
  8829. enter_smm_save_state_32(vcpu, buf);
  8830. /*
  8831. * Give enter_smm() a chance to make ISA-specific changes to the vCPU
  8832. * state (e.g. leave guest mode) after we've saved the state into the
  8833. * SMM state-save area.
  8834. */
  8835. static_call(kvm_x86_enter_smm)(vcpu, buf);
  8836. kvm_smm_changed(vcpu, true);
  8837. kvm_vcpu_write_guest(vcpu, vcpu->arch.smbase + 0xfe00, buf, sizeof(buf));
  8838. if (static_call(kvm_x86_get_nmi_mask)(vcpu))
  8839. vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
  8840. else
  8841. static_call(kvm_x86_set_nmi_mask)(vcpu, true);
  8842. kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
  8843. kvm_rip_write(vcpu, 0x8000);
  8844. cr0 = vcpu->arch.cr0 & ~(X86_CR0_PE | X86_CR0_EM | X86_CR0_TS | X86_CR0_PG);
  8845. static_call(kvm_x86_set_cr0)(vcpu, cr0);
  8846. vcpu->arch.cr0 = cr0;
  8847. static_call(kvm_x86_set_cr4)(vcpu, 0);
  8848. /* Undocumented: IDT limit is set to zero on entry to SMM. */
  8849. dt.address = dt.size = 0;
  8850. static_call(kvm_x86_set_idt)(vcpu, &dt);
  8851. kvm_set_dr(vcpu, 7, DR7_FIXED_1);
  8852. cs.selector = (vcpu->arch.smbase >> 4) & 0xffff;
  8853. cs.base = vcpu->arch.smbase;
  8854. ds.selector = 0;
  8855. ds.base = 0;
  8856. cs.limit = ds.limit = 0xffffffff;
  8857. cs.type = ds.type = 0x3;
  8858. cs.dpl = ds.dpl = 0;
  8859. cs.db = ds.db = 0;
  8860. cs.s = ds.s = 1;
  8861. cs.l = ds.l = 0;
  8862. cs.g = ds.g = 1;
  8863. cs.avl = ds.avl = 0;
  8864. cs.present = ds.present = 1;
  8865. cs.unusable = ds.unusable = 0;
  8866. cs.padding = ds.padding = 0;
  8867. kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
  8868. kvm_set_segment(vcpu, &ds, VCPU_SREG_DS);
  8869. kvm_set_segment(vcpu, &ds, VCPU_SREG_ES);
  8870. kvm_set_segment(vcpu, &ds, VCPU_SREG_FS);
  8871. kvm_set_segment(vcpu, &ds, VCPU_SREG_GS);
  8872. kvm_set_segment(vcpu, &ds, VCPU_SREG_SS);
  8873. #ifdef CONFIG_X86_64
  8874. if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
  8875. static_call(kvm_x86_set_efer)(vcpu, 0);
  8876. #endif
  8877. kvm_update_cpuid_runtime(vcpu);
  8878. kvm_mmu_reset_context(vcpu);
  8879. }
  8880. static void process_smi(struct kvm_vcpu *vcpu)
  8881. {
  8882. vcpu->arch.smi_pending = true;
  8883. kvm_make_request(KVM_REQ_EVENT, vcpu);
  8884. }
  8885. void kvm_make_scan_ioapic_request_mask(struct kvm *kvm,
  8886. unsigned long *vcpu_bitmap)
  8887. {
  8888. kvm_make_vcpus_request_mask(kvm, KVM_REQ_SCAN_IOAPIC, vcpu_bitmap);
  8889. }
  8890. void kvm_make_scan_ioapic_request(struct kvm *kvm)
  8891. {
  8892. kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
  8893. }
  8894. void kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
  8895. {
  8896. struct kvm_lapic *apic = vcpu->arch.apic;
  8897. bool activate;
  8898. if (!lapic_in_kernel(vcpu))
  8899. return;
  8900. down_read(&vcpu->kvm->arch.apicv_update_lock);
  8901. preempt_disable();
  8902. /* Do not activate APICV when APIC is disabled */
  8903. activate = kvm_vcpu_apicv_activated(vcpu) &&
  8904. (kvm_get_apic_mode(vcpu) != LAPIC_MODE_DISABLED);
  8905. if (apic->apicv_active == activate)
  8906. goto out;
  8907. apic->apicv_active = activate;
  8908. kvm_apic_update_apicv(vcpu);
  8909. static_call(kvm_x86_refresh_apicv_exec_ctrl)(vcpu);
  8910. /*
  8911. * When APICv gets disabled, we may still have injected interrupts
  8912. * pending. At the same time, KVM_REQ_EVENT may not be set as APICv was
  8913. * still active when the interrupt got accepted. Make sure
  8914. * kvm_check_and_inject_events() is called to check for that.
  8915. */
  8916. if (!apic->apicv_active)
  8917. kvm_make_request(KVM_REQ_EVENT, vcpu);
  8918. out:
  8919. preempt_enable();
  8920. up_read(&vcpu->kvm->arch.apicv_update_lock);
  8921. }
  8922. EXPORT_SYMBOL_GPL(kvm_vcpu_update_apicv);
  8923. void __kvm_set_or_clear_apicv_inhibit(struct kvm *kvm,
  8924. enum kvm_apicv_inhibit reason, bool set)
  8925. {
  8926. unsigned long old, new;
  8927. lockdep_assert_held_write(&kvm->arch.apicv_update_lock);
  8928. if (!static_call(kvm_x86_check_apicv_inhibit_reasons)(reason))
  8929. return;
  8930. old = new = kvm->arch.apicv_inhibit_reasons;
  8931. set_or_clear_apicv_inhibit(&new, reason, set);
  8932. if (!!old != !!new) {
  8933. /*
  8934. * Kick all vCPUs before setting apicv_inhibit_reasons to avoid
  8935. * false positives in the sanity check WARN in svm_vcpu_run().
  8936. * This task will wait for all vCPUs to ack the kick IRQ before
  8937. * updating apicv_inhibit_reasons, and all other vCPUs will
  8938. * block on acquiring apicv_update_lock so that vCPUs can't
  8939. * redo svm_vcpu_run() without seeing the new inhibit state.
  8940. *
  8941. * Note, holding apicv_update_lock and taking it in the read
  8942. * side (handling the request) also prevents other vCPUs from
  8943. * servicing the request with a stale apicv_inhibit_reasons.
  8944. */
  8945. kvm_make_all_cpus_request(kvm, KVM_REQ_APICV_UPDATE);
  8946. kvm->arch.apicv_inhibit_reasons = new;
  8947. if (new) {
  8948. unsigned long gfn = gpa_to_gfn(APIC_DEFAULT_PHYS_BASE);
  8949. int idx = srcu_read_lock(&kvm->srcu);
  8950. kvm_zap_gfn_range(kvm, gfn, gfn+1);
  8951. srcu_read_unlock(&kvm->srcu, idx);
  8952. }
  8953. } else {
  8954. kvm->arch.apicv_inhibit_reasons = new;
  8955. }
  8956. }
  8957. void kvm_set_or_clear_apicv_inhibit(struct kvm *kvm,
  8958. enum kvm_apicv_inhibit reason, bool set)
  8959. {
  8960. if (!enable_apicv)
  8961. return;
  8962. down_write(&kvm->arch.apicv_update_lock);
  8963. __kvm_set_or_clear_apicv_inhibit(kvm, reason, set);
  8964. up_write(&kvm->arch.apicv_update_lock);
  8965. }
  8966. EXPORT_SYMBOL_GPL(kvm_set_or_clear_apicv_inhibit);
  8967. static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
  8968. {
  8969. if (!kvm_apic_present(vcpu))
  8970. return;
  8971. bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
  8972. if (irqchip_split(vcpu->kvm))
  8973. kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
  8974. else {
  8975. static_call_cond(kvm_x86_sync_pir_to_irr)(vcpu);
  8976. if (ioapic_in_kernel(vcpu->kvm))
  8977. kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
  8978. }
  8979. if (is_guest_mode(vcpu))
  8980. vcpu->arch.load_eoi_exitmap_pending = true;
  8981. else
  8982. kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu);
  8983. }
  8984. static void vcpu_load_eoi_exitmap(struct kvm_vcpu *vcpu)
  8985. {
  8986. u64 eoi_exit_bitmap[4];
  8987. if (!kvm_apic_hw_enabled(vcpu->arch.apic))
  8988. return;
  8989. if (to_hv_vcpu(vcpu)) {
  8990. bitmap_or((ulong *)eoi_exit_bitmap,
  8991. vcpu->arch.ioapic_handled_vectors,
  8992. to_hv_synic(vcpu)->vec_bitmap, 256);
  8993. static_call_cond(kvm_x86_load_eoi_exitmap)(vcpu, eoi_exit_bitmap);
  8994. return;
  8995. }
  8996. static_call_cond(kvm_x86_load_eoi_exitmap)(
  8997. vcpu, (u64 *)vcpu->arch.ioapic_handled_vectors);
  8998. }
  8999. void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
  9000. unsigned long start, unsigned long end)
  9001. {
  9002. unsigned long apic_address;
  9003. /*
  9004. * The physical address of apic access page is stored in the VMCS.
  9005. * Update it when it becomes invalid.
  9006. */
  9007. apic_address = gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
  9008. if (start <= apic_address && apic_address < end)
  9009. kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
  9010. }
  9011. void kvm_arch_guest_memory_reclaimed(struct kvm *kvm)
  9012. {
  9013. static_call_cond(kvm_x86_guest_memory_reclaimed)(kvm);
  9014. }
  9015. static void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
  9016. {
  9017. if (!lapic_in_kernel(vcpu))
  9018. return;
  9019. static_call_cond(kvm_x86_set_apic_access_page_addr)(vcpu);
  9020. }
  9021. void __kvm_request_immediate_exit(struct kvm_vcpu *vcpu)
  9022. {
  9023. smp_send_reschedule(vcpu->cpu);
  9024. }
  9025. EXPORT_SYMBOL_GPL(__kvm_request_immediate_exit);
  9026. /*
  9027. * Called within kvm->srcu read side.
  9028. * Returns 1 to let vcpu_run() continue the guest execution loop without
  9029. * exiting to the userspace. Otherwise, the value will be returned to the
  9030. * userspace.
  9031. */
  9032. static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
  9033. {
  9034. int r;
  9035. bool req_int_win =
  9036. dm_request_for_irq_injection(vcpu) &&
  9037. kvm_cpu_accept_dm_intr(vcpu);
  9038. fastpath_t exit_fastpath;
  9039. bool req_immediate_exit = false;
  9040. /* Forbid vmenter if vcpu dirty ring is soft-full */
  9041. if (unlikely(vcpu->kvm->dirty_ring_size &&
  9042. kvm_dirty_ring_soft_full(&vcpu->dirty_ring))) {
  9043. vcpu->run->exit_reason = KVM_EXIT_DIRTY_RING_FULL;
  9044. trace_kvm_dirty_ring_exit(vcpu);
  9045. r = 0;
  9046. goto out;
  9047. }
  9048. if (kvm_request_pending(vcpu)) {
  9049. if (kvm_check_request(KVM_REQ_VM_DEAD, vcpu)) {
  9050. r = -EIO;
  9051. goto out;
  9052. }
  9053. if (kvm_check_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu)) {
  9054. if (unlikely(!kvm_x86_ops.nested_ops->get_nested_state_pages(vcpu))) {
  9055. r = 0;
  9056. goto out;
  9057. }
  9058. }
  9059. if (kvm_check_request(KVM_REQ_MMU_FREE_OBSOLETE_ROOTS, vcpu))
  9060. kvm_mmu_free_obsolete_roots(vcpu);
  9061. if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
  9062. __kvm_migrate_timers(vcpu);
  9063. if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
  9064. kvm_update_masterclock(vcpu->kvm);
  9065. if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
  9066. kvm_gen_kvmclock_update(vcpu);
  9067. if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
  9068. r = kvm_guest_time_update(vcpu);
  9069. if (unlikely(r))
  9070. goto out;
  9071. }
  9072. if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
  9073. kvm_mmu_sync_roots(vcpu);
  9074. if (kvm_check_request(KVM_REQ_LOAD_MMU_PGD, vcpu))
  9075. kvm_mmu_load_pgd(vcpu);
  9076. if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu)) {
  9077. kvm_vcpu_flush_tlb_all(vcpu);
  9078. /* Flushing all ASIDs flushes the current ASID... */
  9079. kvm_clear_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
  9080. }
  9081. kvm_service_local_tlb_flush_requests(vcpu);
  9082. if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
  9083. vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
  9084. r = 0;
  9085. goto out;
  9086. }
  9087. if (kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
  9088. if (is_guest_mode(vcpu))
  9089. kvm_x86_ops.nested_ops->triple_fault(vcpu);
  9090. if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
  9091. vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
  9092. vcpu->mmio_needed = 0;
  9093. r = 0;
  9094. goto out;
  9095. }
  9096. }
  9097. if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
  9098. /* Page is swapped out. Do synthetic halt */
  9099. vcpu->arch.apf.halted = true;
  9100. r = 1;
  9101. goto out;
  9102. }
  9103. if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
  9104. record_steal_time(vcpu);
  9105. if (kvm_check_request(KVM_REQ_SMI, vcpu))
  9106. process_smi(vcpu);
  9107. if (kvm_check_request(KVM_REQ_NMI, vcpu))
  9108. process_nmi(vcpu);
  9109. if (kvm_check_request(KVM_REQ_PMU, vcpu))
  9110. kvm_pmu_handle_event(vcpu);
  9111. if (kvm_check_request(KVM_REQ_PMI, vcpu))
  9112. kvm_pmu_deliver_pmi(vcpu);
  9113. if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
  9114. BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
  9115. if (test_bit(vcpu->arch.pending_ioapic_eoi,
  9116. vcpu->arch.ioapic_handled_vectors)) {
  9117. vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
  9118. vcpu->run->eoi.vector =
  9119. vcpu->arch.pending_ioapic_eoi;
  9120. r = 0;
  9121. goto out;
  9122. }
  9123. }
  9124. if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
  9125. vcpu_scan_ioapic(vcpu);
  9126. if (kvm_check_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu))
  9127. vcpu_load_eoi_exitmap(vcpu);
  9128. if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
  9129. kvm_vcpu_reload_apic_access_page(vcpu);
  9130. if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
  9131. vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
  9132. vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
  9133. vcpu->run->system_event.ndata = 0;
  9134. r = 0;
  9135. goto out;
  9136. }
  9137. if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
  9138. vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
  9139. vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
  9140. vcpu->run->system_event.ndata = 0;
  9141. r = 0;
  9142. goto out;
  9143. }
  9144. if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
  9145. struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
  9146. vcpu->run->exit_reason = KVM_EXIT_HYPERV;
  9147. vcpu->run->hyperv = hv_vcpu->exit;
  9148. r = 0;
  9149. goto out;
  9150. }
  9151. /*
  9152. * KVM_REQ_HV_STIMER has to be processed after
  9153. * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
  9154. * depend on the guest clock being up-to-date
  9155. */
  9156. if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
  9157. kvm_hv_process_stimers(vcpu);
  9158. if (kvm_check_request(KVM_REQ_APICV_UPDATE, vcpu))
  9159. kvm_vcpu_update_apicv(vcpu);
  9160. if (kvm_check_request(KVM_REQ_APF_READY, vcpu))
  9161. kvm_check_async_pf_completion(vcpu);
  9162. if (kvm_check_request(KVM_REQ_MSR_FILTER_CHANGED, vcpu))
  9163. static_call(kvm_x86_msr_filter_changed)(vcpu);
  9164. if (kvm_check_request(KVM_REQ_UPDATE_CPU_DIRTY_LOGGING, vcpu))
  9165. static_call(kvm_x86_update_cpu_dirty_logging)(vcpu);
  9166. }
  9167. if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win ||
  9168. kvm_xen_has_interrupt(vcpu)) {
  9169. ++vcpu->stat.req_event;
  9170. r = kvm_apic_accept_events(vcpu);
  9171. if (r < 0) {
  9172. r = 0;
  9173. goto out;
  9174. }
  9175. if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
  9176. r = 1;
  9177. goto out;
  9178. }
  9179. r = kvm_check_and_inject_events(vcpu, &req_immediate_exit);
  9180. if (r < 0) {
  9181. r = 0;
  9182. goto out;
  9183. }
  9184. if (req_int_win)
  9185. static_call(kvm_x86_enable_irq_window)(vcpu);
  9186. if (kvm_lapic_enabled(vcpu)) {
  9187. update_cr8_intercept(vcpu);
  9188. kvm_lapic_sync_to_vapic(vcpu);
  9189. }
  9190. }
  9191. r = kvm_mmu_reload(vcpu);
  9192. if (unlikely(r)) {
  9193. goto cancel_injection;
  9194. }
  9195. preempt_disable();
  9196. static_call(kvm_x86_prepare_switch_to_guest)(vcpu);
  9197. /*
  9198. * Disable IRQs before setting IN_GUEST_MODE. Posted interrupt
  9199. * IPI are then delayed after guest entry, which ensures that they
  9200. * result in virtual interrupt delivery.
  9201. */
  9202. local_irq_disable();
  9203. /* Store vcpu->apicv_active before vcpu->mode. */
  9204. smp_store_release(&vcpu->mode, IN_GUEST_MODE);
  9205. kvm_vcpu_srcu_read_unlock(vcpu);
  9206. /*
  9207. * 1) We should set ->mode before checking ->requests. Please see
  9208. * the comment in kvm_vcpu_exiting_guest_mode().
  9209. *
  9210. * 2) For APICv, we should set ->mode before checking PID.ON. This
  9211. * pairs with the memory barrier implicit in pi_test_and_set_on
  9212. * (see vmx_deliver_posted_interrupt).
  9213. *
  9214. * 3) This also orders the write to mode from any reads to the page
  9215. * tables done while the VCPU is running. Please see the comment
  9216. * in kvm_flush_remote_tlbs.
  9217. */
  9218. smp_mb__after_srcu_read_unlock();
  9219. /*
  9220. * Process pending posted interrupts to handle the case where the
  9221. * notification IRQ arrived in the host, or was never sent (because the
  9222. * target vCPU wasn't running). Do this regardless of the vCPU's APICv
  9223. * status, KVM doesn't update assigned devices when APICv is inhibited,
  9224. * i.e. they can post interrupts even if APICv is temporarily disabled.
  9225. */
  9226. if (kvm_lapic_enabled(vcpu))
  9227. static_call_cond(kvm_x86_sync_pir_to_irr)(vcpu);
  9228. if (kvm_vcpu_exit_request(vcpu)) {
  9229. vcpu->mode = OUTSIDE_GUEST_MODE;
  9230. smp_wmb();
  9231. local_irq_enable();
  9232. preempt_enable();
  9233. kvm_vcpu_srcu_read_lock(vcpu);
  9234. r = 1;
  9235. goto cancel_injection;
  9236. }
  9237. if (req_immediate_exit) {
  9238. kvm_make_request(KVM_REQ_EVENT, vcpu);
  9239. static_call(kvm_x86_request_immediate_exit)(vcpu);
  9240. }
  9241. fpregs_assert_state_consistent();
  9242. if (test_thread_flag(TIF_NEED_FPU_LOAD))
  9243. switch_fpu_return();
  9244. if (vcpu->arch.guest_fpu.xfd_err)
  9245. wrmsrl(MSR_IA32_XFD_ERR, vcpu->arch.guest_fpu.xfd_err);
  9246. if (unlikely(vcpu->arch.switch_db_regs)) {
  9247. set_debugreg(0, 7);
  9248. set_debugreg(vcpu->arch.eff_db[0], 0);
  9249. set_debugreg(vcpu->arch.eff_db[1], 1);
  9250. set_debugreg(vcpu->arch.eff_db[2], 2);
  9251. set_debugreg(vcpu->arch.eff_db[3], 3);
  9252. } else if (unlikely(hw_breakpoint_active())) {
  9253. set_debugreg(0, 7);
  9254. }
  9255. guest_timing_enter_irqoff();
  9256. for (;;) {
  9257. /*
  9258. * Assert that vCPU vs. VM APICv state is consistent. An APICv
  9259. * update must kick and wait for all vCPUs before toggling the
  9260. * per-VM state, and responsing vCPUs must wait for the update
  9261. * to complete before servicing KVM_REQ_APICV_UPDATE.
  9262. */
  9263. WARN_ON_ONCE((kvm_vcpu_apicv_activated(vcpu) != kvm_vcpu_apicv_active(vcpu)) &&
  9264. (kvm_get_apic_mode(vcpu) != LAPIC_MODE_DISABLED));
  9265. exit_fastpath = static_call(kvm_x86_vcpu_run)(vcpu);
  9266. if (likely(exit_fastpath != EXIT_FASTPATH_REENTER_GUEST))
  9267. break;
  9268. if (kvm_lapic_enabled(vcpu))
  9269. static_call_cond(kvm_x86_sync_pir_to_irr)(vcpu);
  9270. if (unlikely(kvm_vcpu_exit_request(vcpu))) {
  9271. exit_fastpath = EXIT_FASTPATH_EXIT_HANDLED;
  9272. break;
  9273. }
  9274. /* Note, VM-Exits that go down the "slow" path are accounted below. */
  9275. ++vcpu->stat.exits;
  9276. }
  9277. /*
  9278. * Do this here before restoring debug registers on the host. And
  9279. * since we do this before handling the vmexit, a DR access vmexit
  9280. * can (a) read the correct value of the debug registers, (b) set
  9281. * KVM_DEBUGREG_WONT_EXIT again.
  9282. */
  9283. if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
  9284. WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
  9285. static_call(kvm_x86_sync_dirty_debug_regs)(vcpu);
  9286. kvm_update_dr0123(vcpu);
  9287. kvm_update_dr7(vcpu);
  9288. }
  9289. /*
  9290. * If the guest has used debug registers, at least dr7
  9291. * will be disabled while returning to the host.
  9292. * If we don't have active breakpoints in the host, we don't
  9293. * care about the messed up debug address registers. But if
  9294. * we have some of them active, restore the old state.
  9295. */
  9296. if (hw_breakpoint_active())
  9297. hw_breakpoint_restore();
  9298. vcpu->arch.last_vmentry_cpu = vcpu->cpu;
  9299. vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
  9300. vcpu->mode = OUTSIDE_GUEST_MODE;
  9301. smp_wmb();
  9302. /*
  9303. * Sync xfd before calling handle_exit_irqoff() which may
  9304. * rely on the fact that guest_fpu::xfd is up-to-date (e.g.
  9305. * in #NM irqoff handler).
  9306. */
  9307. if (vcpu->arch.xfd_no_write_intercept)
  9308. fpu_sync_guest_vmexit_xfd_state();
  9309. static_call(kvm_x86_handle_exit_irqoff)(vcpu);
  9310. if (vcpu->arch.guest_fpu.xfd_err)
  9311. wrmsrl(MSR_IA32_XFD_ERR, 0);
  9312. /*
  9313. * Consume any pending interrupts, including the possible source of
  9314. * VM-Exit on SVM and any ticks that occur between VM-Exit and now.
  9315. * An instruction is required after local_irq_enable() to fully unblock
  9316. * interrupts on processors that implement an interrupt shadow, the
  9317. * stat.exits increment will do nicely.
  9318. */
  9319. kvm_before_interrupt(vcpu, KVM_HANDLING_IRQ);
  9320. local_irq_enable();
  9321. ++vcpu->stat.exits;
  9322. local_irq_disable();
  9323. kvm_after_interrupt(vcpu);
  9324. /*
  9325. * Wait until after servicing IRQs to account guest time so that any
  9326. * ticks that occurred while running the guest are properly accounted
  9327. * to the guest. Waiting until IRQs are enabled degrades the accuracy
  9328. * of accounting via context tracking, but the loss of accuracy is
  9329. * acceptable for all known use cases.
  9330. */
  9331. guest_timing_exit_irqoff();
  9332. local_irq_enable();
  9333. preempt_enable();
  9334. kvm_vcpu_srcu_read_lock(vcpu);
  9335. /*
  9336. * Profile KVM exit RIPs:
  9337. */
  9338. if (unlikely(prof_on == KVM_PROFILING)) {
  9339. unsigned long rip = kvm_rip_read(vcpu);
  9340. profile_hit(KVM_PROFILING, (void *)rip);
  9341. }
  9342. if (unlikely(vcpu->arch.tsc_always_catchup))
  9343. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  9344. if (vcpu->arch.apic_attention)
  9345. kvm_lapic_sync_from_vapic(vcpu);
  9346. r = static_call(kvm_x86_handle_exit)(vcpu, exit_fastpath);
  9347. return r;
  9348. cancel_injection:
  9349. if (req_immediate_exit)
  9350. kvm_make_request(KVM_REQ_EVENT, vcpu);
  9351. static_call(kvm_x86_cancel_injection)(vcpu);
  9352. if (unlikely(vcpu->arch.apic_attention))
  9353. kvm_lapic_sync_from_vapic(vcpu);
  9354. out:
  9355. return r;
  9356. }
  9357. /* Called within kvm->srcu read side. */
  9358. static inline int vcpu_block(struct kvm_vcpu *vcpu)
  9359. {
  9360. bool hv_timer;
  9361. if (!kvm_arch_vcpu_runnable(vcpu)) {
  9362. /*
  9363. * Switch to the software timer before halt-polling/blocking as
  9364. * the guest's timer may be a break event for the vCPU, and the
  9365. * hypervisor timer runs only when the CPU is in guest mode.
  9366. * Switch before halt-polling so that KVM recognizes an expired
  9367. * timer before blocking.
  9368. */
  9369. hv_timer = kvm_lapic_hv_timer_in_use(vcpu);
  9370. if (hv_timer)
  9371. kvm_lapic_switch_to_sw_timer(vcpu);
  9372. kvm_vcpu_srcu_read_unlock(vcpu);
  9373. if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
  9374. kvm_vcpu_halt(vcpu);
  9375. else
  9376. kvm_vcpu_block(vcpu);
  9377. kvm_vcpu_srcu_read_lock(vcpu);
  9378. if (hv_timer)
  9379. kvm_lapic_switch_to_hv_timer(vcpu);
  9380. /*
  9381. * If the vCPU is not runnable, a signal or another host event
  9382. * of some kind is pending; service it without changing the
  9383. * vCPU's activity state.
  9384. */
  9385. if (!kvm_arch_vcpu_runnable(vcpu))
  9386. return 1;
  9387. }
  9388. /*
  9389. * Evaluate nested events before exiting the halted state. This allows
  9390. * the halt state to be recorded properly in the VMCS12's activity
  9391. * state field (AMD does not have a similar field and a VM-Exit always
  9392. * causes a spurious wakeup from HLT).
  9393. */
  9394. if (is_guest_mode(vcpu)) {
  9395. if (kvm_check_nested_events(vcpu) < 0)
  9396. return 0;
  9397. }
  9398. if (kvm_apic_accept_events(vcpu) < 0)
  9399. return 0;
  9400. switch(vcpu->arch.mp_state) {
  9401. case KVM_MP_STATE_HALTED:
  9402. case KVM_MP_STATE_AP_RESET_HOLD:
  9403. vcpu->arch.pv.pv_unhalted = false;
  9404. vcpu->arch.mp_state =
  9405. KVM_MP_STATE_RUNNABLE;
  9406. fallthrough;
  9407. case KVM_MP_STATE_RUNNABLE:
  9408. vcpu->arch.apf.halted = false;
  9409. break;
  9410. case KVM_MP_STATE_INIT_RECEIVED:
  9411. break;
  9412. default:
  9413. WARN_ON_ONCE(1);
  9414. break;
  9415. }
  9416. return 1;
  9417. }
  9418. static inline bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
  9419. {
  9420. return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
  9421. !vcpu->arch.apf.halted);
  9422. }
  9423. /* Called within kvm->srcu read side. */
  9424. static int vcpu_run(struct kvm_vcpu *vcpu)
  9425. {
  9426. int r;
  9427. vcpu->arch.l1tf_flush_l1d = true;
  9428. for (;;) {
  9429. /*
  9430. * If another guest vCPU requests a PV TLB flush in the middle
  9431. * of instruction emulation, the rest of the emulation could
  9432. * use a stale page translation. Assume that any code after
  9433. * this point can start executing an instruction.
  9434. */
  9435. vcpu->arch.at_instruction_boundary = false;
  9436. if (kvm_vcpu_running(vcpu)) {
  9437. r = vcpu_enter_guest(vcpu);
  9438. } else {
  9439. r = vcpu_block(vcpu);
  9440. }
  9441. if (r <= 0)
  9442. break;
  9443. kvm_clear_request(KVM_REQ_UNBLOCK, vcpu);
  9444. if (kvm_xen_has_pending_events(vcpu))
  9445. kvm_xen_inject_pending_events(vcpu);
  9446. if (kvm_cpu_has_pending_timer(vcpu))
  9447. kvm_inject_pending_timer_irqs(vcpu);
  9448. if (dm_request_for_irq_injection(vcpu) &&
  9449. kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
  9450. r = 0;
  9451. vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
  9452. ++vcpu->stat.request_irq_exits;
  9453. break;
  9454. }
  9455. if (__xfer_to_guest_mode_work_pending()) {
  9456. kvm_vcpu_srcu_read_unlock(vcpu);
  9457. r = xfer_to_guest_mode_handle_work(vcpu);
  9458. kvm_vcpu_srcu_read_lock(vcpu);
  9459. if (r)
  9460. return r;
  9461. }
  9462. }
  9463. return r;
  9464. }
  9465. static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
  9466. {
  9467. return kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
  9468. }
  9469. static int complete_emulated_pio(struct kvm_vcpu *vcpu)
  9470. {
  9471. BUG_ON(!vcpu->arch.pio.count);
  9472. return complete_emulated_io(vcpu);
  9473. }
  9474. /*
  9475. * Implements the following, as a state machine:
  9476. *
  9477. * read:
  9478. * for each fragment
  9479. * for each mmio piece in the fragment
  9480. * write gpa, len
  9481. * exit
  9482. * copy data
  9483. * execute insn
  9484. *
  9485. * write:
  9486. * for each fragment
  9487. * for each mmio piece in the fragment
  9488. * write gpa, len
  9489. * copy data
  9490. * exit
  9491. */
  9492. static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
  9493. {
  9494. struct kvm_run *run = vcpu->run;
  9495. struct kvm_mmio_fragment *frag;
  9496. unsigned len;
  9497. BUG_ON(!vcpu->mmio_needed);
  9498. /* Complete previous fragment */
  9499. frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
  9500. len = min(8u, frag->len);
  9501. if (!vcpu->mmio_is_write)
  9502. memcpy(frag->data, run->mmio.data, len);
  9503. if (frag->len <= 8) {
  9504. /* Switch to the next fragment. */
  9505. frag++;
  9506. vcpu->mmio_cur_fragment++;
  9507. } else {
  9508. /* Go forward to the next mmio piece. */
  9509. frag->data += len;
  9510. frag->gpa += len;
  9511. frag->len -= len;
  9512. }
  9513. if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
  9514. vcpu->mmio_needed = 0;
  9515. /* FIXME: return into emulator if single-stepping. */
  9516. if (vcpu->mmio_is_write)
  9517. return 1;
  9518. vcpu->mmio_read_completed = 1;
  9519. return complete_emulated_io(vcpu);
  9520. }
  9521. run->exit_reason = KVM_EXIT_MMIO;
  9522. run->mmio.phys_addr = frag->gpa;
  9523. if (vcpu->mmio_is_write)
  9524. memcpy(run->mmio.data, frag->data, min(8u, frag->len));
  9525. run->mmio.len = min(8u, frag->len);
  9526. run->mmio.is_write = vcpu->mmio_is_write;
  9527. vcpu->arch.complete_userspace_io = complete_emulated_mmio;
  9528. return 0;
  9529. }
  9530. /* Swap (qemu) user FPU context for the guest FPU context. */
  9531. static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
  9532. {
  9533. /* Exclude PKRU, it's restored separately immediately after VM-Exit. */
  9534. fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, true);
  9535. trace_kvm_fpu(1);
  9536. }
  9537. /* When vcpu_run ends, restore user space FPU context. */
  9538. static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
  9539. {
  9540. fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, false);
  9541. ++vcpu->stat.fpu_reload;
  9542. trace_kvm_fpu(0);
  9543. }
  9544. int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
  9545. {
  9546. struct kvm_queued_exception *ex = &vcpu->arch.exception;
  9547. struct kvm_run *kvm_run = vcpu->run;
  9548. int r;
  9549. vcpu_load(vcpu);
  9550. kvm_sigset_activate(vcpu);
  9551. kvm_run->flags = 0;
  9552. kvm_load_guest_fpu(vcpu);
  9553. kvm_vcpu_srcu_read_lock(vcpu);
  9554. if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
  9555. if (kvm_run->immediate_exit) {
  9556. r = -EINTR;
  9557. goto out;
  9558. }
  9559. /*
  9560. * It should be impossible for the hypervisor timer to be in
  9561. * use before KVM has ever run the vCPU.
  9562. */
  9563. WARN_ON_ONCE(kvm_lapic_hv_timer_in_use(vcpu));
  9564. kvm_vcpu_srcu_read_unlock(vcpu);
  9565. kvm_vcpu_block(vcpu);
  9566. kvm_vcpu_srcu_read_lock(vcpu);
  9567. if (kvm_apic_accept_events(vcpu) < 0) {
  9568. r = 0;
  9569. goto out;
  9570. }
  9571. r = -EAGAIN;
  9572. if (signal_pending(current)) {
  9573. r = -EINTR;
  9574. kvm_run->exit_reason = KVM_EXIT_INTR;
  9575. ++vcpu->stat.signal_exits;
  9576. }
  9577. goto out;
  9578. }
  9579. if ((kvm_run->kvm_valid_regs & ~KVM_SYNC_X86_VALID_FIELDS) ||
  9580. (kvm_run->kvm_dirty_regs & ~KVM_SYNC_X86_VALID_FIELDS)) {
  9581. r = -EINVAL;
  9582. goto out;
  9583. }
  9584. if (kvm_run->kvm_dirty_regs) {
  9585. r = sync_regs(vcpu);
  9586. if (r != 0)
  9587. goto out;
  9588. }
  9589. /* re-sync apic's tpr */
  9590. if (!lapic_in_kernel(vcpu)) {
  9591. if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
  9592. r = -EINVAL;
  9593. goto out;
  9594. }
  9595. }
  9596. /*
  9597. * If userspace set a pending exception and L2 is active, convert it to
  9598. * a pending VM-Exit if L1 wants to intercept the exception.
  9599. */
  9600. if (vcpu->arch.exception_from_userspace && is_guest_mode(vcpu) &&
  9601. kvm_x86_ops.nested_ops->is_exception_vmexit(vcpu, ex->vector,
  9602. ex->error_code)) {
  9603. kvm_queue_exception_vmexit(vcpu, ex->vector,
  9604. ex->has_error_code, ex->error_code,
  9605. ex->has_payload, ex->payload);
  9606. ex->injected = false;
  9607. ex->pending = false;
  9608. }
  9609. vcpu->arch.exception_from_userspace = false;
  9610. if (unlikely(vcpu->arch.complete_userspace_io)) {
  9611. int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
  9612. vcpu->arch.complete_userspace_io = NULL;
  9613. r = cui(vcpu);
  9614. if (r <= 0)
  9615. goto out;
  9616. } else {
  9617. WARN_ON_ONCE(vcpu->arch.pio.count);
  9618. WARN_ON_ONCE(vcpu->mmio_needed);
  9619. }
  9620. if (kvm_run->immediate_exit) {
  9621. r = -EINTR;
  9622. goto out;
  9623. }
  9624. r = static_call(kvm_x86_vcpu_pre_run)(vcpu);
  9625. if (r <= 0)
  9626. goto out;
  9627. r = vcpu_run(vcpu);
  9628. out:
  9629. kvm_put_guest_fpu(vcpu);
  9630. if (kvm_run->kvm_valid_regs)
  9631. store_regs(vcpu);
  9632. post_kvm_run_save(vcpu);
  9633. kvm_vcpu_srcu_read_unlock(vcpu);
  9634. kvm_sigset_deactivate(vcpu);
  9635. vcpu_put(vcpu);
  9636. return r;
  9637. }
  9638. static void __get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
  9639. {
  9640. if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
  9641. /*
  9642. * We are here if userspace calls get_regs() in the middle of
  9643. * instruction emulation. Registers state needs to be copied
  9644. * back from emulation context to vcpu. Userspace shouldn't do
  9645. * that usually, but some bad designed PV devices (vmware
  9646. * backdoor interface) need this to work
  9647. */
  9648. emulator_writeback_register_cache(vcpu->arch.emulate_ctxt);
  9649. vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
  9650. }
  9651. regs->rax = kvm_rax_read(vcpu);
  9652. regs->rbx = kvm_rbx_read(vcpu);
  9653. regs->rcx = kvm_rcx_read(vcpu);
  9654. regs->rdx = kvm_rdx_read(vcpu);
  9655. regs->rsi = kvm_rsi_read(vcpu);
  9656. regs->rdi = kvm_rdi_read(vcpu);
  9657. regs->rsp = kvm_rsp_read(vcpu);
  9658. regs->rbp = kvm_rbp_read(vcpu);
  9659. #ifdef CONFIG_X86_64
  9660. regs->r8 = kvm_r8_read(vcpu);
  9661. regs->r9 = kvm_r9_read(vcpu);
  9662. regs->r10 = kvm_r10_read(vcpu);
  9663. regs->r11 = kvm_r11_read(vcpu);
  9664. regs->r12 = kvm_r12_read(vcpu);
  9665. regs->r13 = kvm_r13_read(vcpu);
  9666. regs->r14 = kvm_r14_read(vcpu);
  9667. regs->r15 = kvm_r15_read(vcpu);
  9668. #endif
  9669. regs->rip = kvm_rip_read(vcpu);
  9670. regs->rflags = kvm_get_rflags(vcpu);
  9671. }
  9672. int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
  9673. {
  9674. vcpu_load(vcpu);
  9675. __get_regs(vcpu, regs);
  9676. vcpu_put(vcpu);
  9677. return 0;
  9678. }
  9679. static void __set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
  9680. {
  9681. vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
  9682. vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
  9683. kvm_rax_write(vcpu, regs->rax);
  9684. kvm_rbx_write(vcpu, regs->rbx);
  9685. kvm_rcx_write(vcpu, regs->rcx);
  9686. kvm_rdx_write(vcpu, regs->rdx);
  9687. kvm_rsi_write(vcpu, regs->rsi);
  9688. kvm_rdi_write(vcpu, regs->rdi);
  9689. kvm_rsp_write(vcpu, regs->rsp);
  9690. kvm_rbp_write(vcpu, regs->rbp);
  9691. #ifdef CONFIG_X86_64
  9692. kvm_r8_write(vcpu, regs->r8);
  9693. kvm_r9_write(vcpu, regs->r9);
  9694. kvm_r10_write(vcpu, regs->r10);
  9695. kvm_r11_write(vcpu, regs->r11);
  9696. kvm_r12_write(vcpu, regs->r12);
  9697. kvm_r13_write(vcpu, regs->r13);
  9698. kvm_r14_write(vcpu, regs->r14);
  9699. kvm_r15_write(vcpu, regs->r15);
  9700. #endif
  9701. kvm_rip_write(vcpu, regs->rip);
  9702. kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
  9703. vcpu->arch.exception.pending = false;
  9704. vcpu->arch.exception_vmexit.pending = false;
  9705. kvm_make_request(KVM_REQ_EVENT, vcpu);
  9706. }
  9707. int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
  9708. {
  9709. vcpu_load(vcpu);
  9710. __set_regs(vcpu, regs);
  9711. vcpu_put(vcpu);
  9712. return 0;
  9713. }
  9714. static void __get_sregs_common(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
  9715. {
  9716. struct desc_ptr dt;
  9717. if (vcpu->arch.guest_state_protected)
  9718. goto skip_protected_regs;
  9719. kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
  9720. kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
  9721. kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
  9722. kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
  9723. kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
  9724. kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
  9725. kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
  9726. kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
  9727. static_call(kvm_x86_get_idt)(vcpu, &dt);
  9728. sregs->idt.limit = dt.size;
  9729. sregs->idt.base = dt.address;
  9730. static_call(kvm_x86_get_gdt)(vcpu, &dt);
  9731. sregs->gdt.limit = dt.size;
  9732. sregs->gdt.base = dt.address;
  9733. sregs->cr2 = vcpu->arch.cr2;
  9734. sregs->cr3 = kvm_read_cr3(vcpu);
  9735. skip_protected_regs:
  9736. sregs->cr0 = kvm_read_cr0(vcpu);
  9737. sregs->cr4 = kvm_read_cr4(vcpu);
  9738. sregs->cr8 = kvm_get_cr8(vcpu);
  9739. sregs->efer = vcpu->arch.efer;
  9740. sregs->apic_base = kvm_get_apic_base(vcpu);
  9741. }
  9742. static void __get_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
  9743. {
  9744. __get_sregs_common(vcpu, sregs);
  9745. if (vcpu->arch.guest_state_protected)
  9746. return;
  9747. if (vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft)
  9748. set_bit(vcpu->arch.interrupt.nr,
  9749. (unsigned long *)sregs->interrupt_bitmap);
  9750. }
  9751. static void __get_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2)
  9752. {
  9753. int i;
  9754. __get_sregs_common(vcpu, (struct kvm_sregs *)sregs2);
  9755. if (vcpu->arch.guest_state_protected)
  9756. return;
  9757. if (is_pae_paging(vcpu)) {
  9758. for (i = 0 ; i < 4 ; i++)
  9759. sregs2->pdptrs[i] = kvm_pdptr_read(vcpu, i);
  9760. sregs2->flags |= KVM_SREGS2_FLAGS_PDPTRS_VALID;
  9761. }
  9762. }
  9763. int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
  9764. struct kvm_sregs *sregs)
  9765. {
  9766. vcpu_load(vcpu);
  9767. __get_sregs(vcpu, sregs);
  9768. vcpu_put(vcpu);
  9769. return 0;
  9770. }
  9771. int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
  9772. struct kvm_mp_state *mp_state)
  9773. {
  9774. int r;
  9775. vcpu_load(vcpu);
  9776. if (kvm_mpx_supported())
  9777. kvm_load_guest_fpu(vcpu);
  9778. r = kvm_apic_accept_events(vcpu);
  9779. if (r < 0)
  9780. goto out;
  9781. r = 0;
  9782. if ((vcpu->arch.mp_state == KVM_MP_STATE_HALTED ||
  9783. vcpu->arch.mp_state == KVM_MP_STATE_AP_RESET_HOLD) &&
  9784. vcpu->arch.pv.pv_unhalted)
  9785. mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
  9786. else
  9787. mp_state->mp_state = vcpu->arch.mp_state;
  9788. out:
  9789. if (kvm_mpx_supported())
  9790. kvm_put_guest_fpu(vcpu);
  9791. vcpu_put(vcpu);
  9792. return r;
  9793. }
  9794. int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
  9795. struct kvm_mp_state *mp_state)
  9796. {
  9797. int ret = -EINVAL;
  9798. vcpu_load(vcpu);
  9799. switch (mp_state->mp_state) {
  9800. case KVM_MP_STATE_UNINITIALIZED:
  9801. case KVM_MP_STATE_HALTED:
  9802. case KVM_MP_STATE_AP_RESET_HOLD:
  9803. case KVM_MP_STATE_INIT_RECEIVED:
  9804. case KVM_MP_STATE_SIPI_RECEIVED:
  9805. if (!lapic_in_kernel(vcpu))
  9806. goto out;
  9807. break;
  9808. case KVM_MP_STATE_RUNNABLE:
  9809. break;
  9810. default:
  9811. goto out;
  9812. }
  9813. /*
  9814. * Pending INITs are reported using KVM_SET_VCPU_EVENTS, disallow
  9815. * forcing the guest into INIT/SIPI if those events are supposed to be
  9816. * blocked. KVM prioritizes SMI over INIT, so reject INIT/SIPI state
  9817. * if an SMI is pending as well.
  9818. */
  9819. if ((!kvm_apic_init_sipi_allowed(vcpu) || vcpu->arch.smi_pending) &&
  9820. (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
  9821. mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
  9822. goto out;
  9823. if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
  9824. vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
  9825. set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
  9826. } else
  9827. vcpu->arch.mp_state = mp_state->mp_state;
  9828. kvm_make_request(KVM_REQ_EVENT, vcpu);
  9829. ret = 0;
  9830. out:
  9831. vcpu_put(vcpu);
  9832. return ret;
  9833. }
  9834. int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
  9835. int reason, bool has_error_code, u32 error_code)
  9836. {
  9837. struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
  9838. int ret;
  9839. init_emulate_ctxt(vcpu);
  9840. ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
  9841. has_error_code, error_code);
  9842. if (ret) {
  9843. vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
  9844. vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
  9845. vcpu->run->internal.ndata = 0;
  9846. return 0;
  9847. }
  9848. kvm_rip_write(vcpu, ctxt->eip);
  9849. kvm_set_rflags(vcpu, ctxt->eflags);
  9850. return 1;
  9851. }
  9852. EXPORT_SYMBOL_GPL(kvm_task_switch);
  9853. static bool kvm_is_valid_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
  9854. {
  9855. if ((sregs->efer & EFER_LME) && (sregs->cr0 & X86_CR0_PG)) {
  9856. /*
  9857. * When EFER.LME and CR0.PG are set, the processor is in
  9858. * 64-bit mode (though maybe in a 32-bit code segment).
  9859. * CR4.PAE and EFER.LMA must be set.
  9860. */
  9861. if (!(sregs->cr4 & X86_CR4_PAE) || !(sregs->efer & EFER_LMA))
  9862. return false;
  9863. if (kvm_vcpu_is_illegal_gpa(vcpu, sregs->cr3))
  9864. return false;
  9865. } else {
  9866. /*
  9867. * Not in 64-bit mode: EFER.LMA is clear and the code
  9868. * segment cannot be 64-bit.
  9869. */
  9870. if (sregs->efer & EFER_LMA || sregs->cs.l)
  9871. return false;
  9872. }
  9873. return kvm_is_valid_cr4(vcpu, sregs->cr4) &&
  9874. kvm_is_valid_cr0(vcpu, sregs->cr0);
  9875. }
  9876. static int __set_sregs_common(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs,
  9877. int *mmu_reset_needed, bool update_pdptrs)
  9878. {
  9879. struct msr_data apic_base_msr;
  9880. int idx;
  9881. struct desc_ptr dt;
  9882. if (!kvm_is_valid_sregs(vcpu, sregs))
  9883. return -EINVAL;
  9884. apic_base_msr.data = sregs->apic_base;
  9885. apic_base_msr.host_initiated = true;
  9886. if (kvm_set_apic_base(vcpu, &apic_base_msr))
  9887. return -EINVAL;
  9888. if (vcpu->arch.guest_state_protected)
  9889. return 0;
  9890. dt.size = sregs->idt.limit;
  9891. dt.address = sregs->idt.base;
  9892. static_call(kvm_x86_set_idt)(vcpu, &dt);
  9893. dt.size = sregs->gdt.limit;
  9894. dt.address = sregs->gdt.base;
  9895. static_call(kvm_x86_set_gdt)(vcpu, &dt);
  9896. vcpu->arch.cr2 = sregs->cr2;
  9897. *mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
  9898. vcpu->arch.cr3 = sregs->cr3;
  9899. kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
  9900. static_call_cond(kvm_x86_post_set_cr3)(vcpu, sregs->cr3);
  9901. kvm_set_cr8(vcpu, sregs->cr8);
  9902. *mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
  9903. static_call(kvm_x86_set_efer)(vcpu, sregs->efer);
  9904. *mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
  9905. static_call(kvm_x86_set_cr0)(vcpu, sregs->cr0);
  9906. vcpu->arch.cr0 = sregs->cr0;
  9907. *mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
  9908. static_call(kvm_x86_set_cr4)(vcpu, sregs->cr4);
  9909. if (update_pdptrs) {
  9910. idx = srcu_read_lock(&vcpu->kvm->srcu);
  9911. if (is_pae_paging(vcpu)) {
  9912. load_pdptrs(vcpu, kvm_read_cr3(vcpu));
  9913. *mmu_reset_needed = 1;
  9914. }
  9915. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  9916. }
  9917. kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
  9918. kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
  9919. kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
  9920. kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
  9921. kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
  9922. kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
  9923. kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
  9924. kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
  9925. update_cr8_intercept(vcpu);
  9926. /* Older userspace won't unhalt the vcpu on reset. */
  9927. if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
  9928. sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
  9929. !is_protmode(vcpu))
  9930. vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
  9931. return 0;
  9932. }
  9933. static int __set_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
  9934. {
  9935. int pending_vec, max_bits;
  9936. int mmu_reset_needed = 0;
  9937. int ret = __set_sregs_common(vcpu, sregs, &mmu_reset_needed, true);
  9938. if (ret)
  9939. return ret;
  9940. if (mmu_reset_needed)
  9941. kvm_mmu_reset_context(vcpu);
  9942. max_bits = KVM_NR_INTERRUPTS;
  9943. pending_vec = find_first_bit(
  9944. (const unsigned long *)sregs->interrupt_bitmap, max_bits);
  9945. if (pending_vec < max_bits) {
  9946. kvm_queue_interrupt(vcpu, pending_vec, false);
  9947. pr_debug("Set back pending irq %d\n", pending_vec);
  9948. kvm_make_request(KVM_REQ_EVENT, vcpu);
  9949. }
  9950. return 0;
  9951. }
  9952. static int __set_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2)
  9953. {
  9954. int mmu_reset_needed = 0;
  9955. bool valid_pdptrs = sregs2->flags & KVM_SREGS2_FLAGS_PDPTRS_VALID;
  9956. bool pae = (sregs2->cr0 & X86_CR0_PG) && (sregs2->cr4 & X86_CR4_PAE) &&
  9957. !(sregs2->efer & EFER_LMA);
  9958. int i, ret;
  9959. if (sregs2->flags & ~KVM_SREGS2_FLAGS_PDPTRS_VALID)
  9960. return -EINVAL;
  9961. if (valid_pdptrs && (!pae || vcpu->arch.guest_state_protected))
  9962. return -EINVAL;
  9963. ret = __set_sregs_common(vcpu, (struct kvm_sregs *)sregs2,
  9964. &mmu_reset_needed, !valid_pdptrs);
  9965. if (ret)
  9966. return ret;
  9967. if (valid_pdptrs) {
  9968. for (i = 0; i < 4 ; i++)
  9969. kvm_pdptr_write(vcpu, i, sregs2->pdptrs[i]);
  9970. kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
  9971. mmu_reset_needed = 1;
  9972. vcpu->arch.pdptrs_from_userspace = true;
  9973. }
  9974. if (mmu_reset_needed)
  9975. kvm_mmu_reset_context(vcpu);
  9976. return 0;
  9977. }
  9978. int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
  9979. struct kvm_sregs *sregs)
  9980. {
  9981. int ret;
  9982. vcpu_load(vcpu);
  9983. ret = __set_sregs(vcpu, sregs);
  9984. vcpu_put(vcpu);
  9985. return ret;
  9986. }
  9987. static void kvm_arch_vcpu_guestdbg_update_apicv_inhibit(struct kvm *kvm)
  9988. {
  9989. bool set = false;
  9990. struct kvm_vcpu *vcpu;
  9991. unsigned long i;
  9992. if (!enable_apicv)
  9993. return;
  9994. down_write(&kvm->arch.apicv_update_lock);
  9995. kvm_for_each_vcpu(i, vcpu, kvm) {
  9996. if (vcpu->guest_debug & KVM_GUESTDBG_BLOCKIRQ) {
  9997. set = true;
  9998. break;
  9999. }
  10000. }
  10001. __kvm_set_or_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_BLOCKIRQ, set);
  10002. up_write(&kvm->arch.apicv_update_lock);
  10003. }
  10004. int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
  10005. struct kvm_guest_debug *dbg)
  10006. {
  10007. unsigned long rflags;
  10008. int i, r;
  10009. if (vcpu->arch.guest_state_protected)
  10010. return -EINVAL;
  10011. vcpu_load(vcpu);
  10012. if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
  10013. r = -EBUSY;
  10014. if (kvm_is_exception_pending(vcpu))
  10015. goto out;
  10016. if (dbg->control & KVM_GUESTDBG_INJECT_DB)
  10017. kvm_queue_exception(vcpu, DB_VECTOR);
  10018. else
  10019. kvm_queue_exception(vcpu, BP_VECTOR);
  10020. }
  10021. /*
  10022. * Read rflags as long as potentially injected trace flags are still
  10023. * filtered out.
  10024. */
  10025. rflags = kvm_get_rflags(vcpu);
  10026. vcpu->guest_debug = dbg->control;
  10027. if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
  10028. vcpu->guest_debug = 0;
  10029. if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
  10030. for (i = 0; i < KVM_NR_DB_REGS; ++i)
  10031. vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
  10032. vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
  10033. } else {
  10034. for (i = 0; i < KVM_NR_DB_REGS; i++)
  10035. vcpu->arch.eff_db[i] = vcpu->arch.db[i];
  10036. }
  10037. kvm_update_dr7(vcpu);
  10038. if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
  10039. vcpu->arch.singlestep_rip = kvm_get_linear_rip(vcpu);
  10040. /*
  10041. * Trigger an rflags update that will inject or remove the trace
  10042. * flags.
  10043. */
  10044. kvm_set_rflags(vcpu, rflags);
  10045. static_call(kvm_x86_update_exception_bitmap)(vcpu);
  10046. kvm_arch_vcpu_guestdbg_update_apicv_inhibit(vcpu->kvm);
  10047. r = 0;
  10048. out:
  10049. vcpu_put(vcpu);
  10050. return r;
  10051. }
  10052. /*
  10053. * Translate a guest virtual address to a guest physical address.
  10054. */
  10055. int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
  10056. struct kvm_translation *tr)
  10057. {
  10058. unsigned long vaddr = tr->linear_address;
  10059. gpa_t gpa;
  10060. int idx;
  10061. vcpu_load(vcpu);
  10062. idx = srcu_read_lock(&vcpu->kvm->srcu);
  10063. gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
  10064. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  10065. tr->physical_address = gpa;
  10066. tr->valid = gpa != INVALID_GPA;
  10067. tr->writeable = 1;
  10068. tr->usermode = 0;
  10069. vcpu_put(vcpu);
  10070. return 0;
  10071. }
  10072. int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
  10073. {
  10074. struct fxregs_state *fxsave;
  10075. if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
  10076. return 0;
  10077. vcpu_load(vcpu);
  10078. fxsave = &vcpu->arch.guest_fpu.fpstate->regs.fxsave;
  10079. memcpy(fpu->fpr, fxsave->st_space, 128);
  10080. fpu->fcw = fxsave->cwd;
  10081. fpu->fsw = fxsave->swd;
  10082. fpu->ftwx = fxsave->twd;
  10083. fpu->last_opcode = fxsave->fop;
  10084. fpu->last_ip = fxsave->rip;
  10085. fpu->last_dp = fxsave->rdp;
  10086. memcpy(fpu->xmm, fxsave->xmm_space, sizeof(fxsave->xmm_space));
  10087. vcpu_put(vcpu);
  10088. return 0;
  10089. }
  10090. int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
  10091. {
  10092. struct fxregs_state *fxsave;
  10093. if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
  10094. return 0;
  10095. vcpu_load(vcpu);
  10096. fxsave = &vcpu->arch.guest_fpu.fpstate->regs.fxsave;
  10097. memcpy(fxsave->st_space, fpu->fpr, 128);
  10098. fxsave->cwd = fpu->fcw;
  10099. fxsave->swd = fpu->fsw;
  10100. fxsave->twd = fpu->ftwx;
  10101. fxsave->fop = fpu->last_opcode;
  10102. fxsave->rip = fpu->last_ip;
  10103. fxsave->rdp = fpu->last_dp;
  10104. memcpy(fxsave->xmm_space, fpu->xmm, sizeof(fxsave->xmm_space));
  10105. vcpu_put(vcpu);
  10106. return 0;
  10107. }
  10108. static void store_regs(struct kvm_vcpu *vcpu)
  10109. {
  10110. BUILD_BUG_ON(sizeof(struct kvm_sync_regs) > SYNC_REGS_SIZE_BYTES);
  10111. if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_REGS)
  10112. __get_regs(vcpu, &vcpu->run->s.regs.regs);
  10113. if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_SREGS)
  10114. __get_sregs(vcpu, &vcpu->run->s.regs.sregs);
  10115. if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_EVENTS)
  10116. kvm_vcpu_ioctl_x86_get_vcpu_events(
  10117. vcpu, &vcpu->run->s.regs.events);
  10118. }
  10119. static int sync_regs(struct kvm_vcpu *vcpu)
  10120. {
  10121. if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_REGS) {
  10122. __set_regs(vcpu, &vcpu->run->s.regs.regs);
  10123. vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_REGS;
  10124. }
  10125. if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_SREGS) {
  10126. if (__set_sregs(vcpu, &vcpu->run->s.regs.sregs))
  10127. return -EINVAL;
  10128. vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_SREGS;
  10129. }
  10130. if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_EVENTS) {
  10131. if (kvm_vcpu_ioctl_x86_set_vcpu_events(
  10132. vcpu, &vcpu->run->s.regs.events))
  10133. return -EINVAL;
  10134. vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_EVENTS;
  10135. }
  10136. return 0;
  10137. }
  10138. int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
  10139. {
  10140. if (kvm_check_tsc_unstable() && kvm->created_vcpus)
  10141. pr_warn_once("kvm: SMP vm created on host with unstable TSC; "
  10142. "guest TSC will not be reliable\n");
  10143. if (!kvm->arch.max_vcpu_ids)
  10144. kvm->arch.max_vcpu_ids = KVM_MAX_VCPU_IDS;
  10145. if (id >= kvm->arch.max_vcpu_ids)
  10146. return -EINVAL;
  10147. return static_call(kvm_x86_vcpu_precreate)(kvm);
  10148. }
  10149. int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
  10150. {
  10151. struct page *page;
  10152. int r;
  10153. vcpu->arch.last_vmentry_cpu = -1;
  10154. vcpu->arch.regs_avail = ~0;
  10155. vcpu->arch.regs_dirty = ~0;
  10156. kvm_gpc_init(&vcpu->arch.pv_time);
  10157. if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
  10158. vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
  10159. else
  10160. vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
  10161. r = kvm_mmu_create(vcpu);
  10162. if (r < 0)
  10163. return r;
  10164. if (irqchip_in_kernel(vcpu->kvm)) {
  10165. r = kvm_create_lapic(vcpu, lapic_timer_advance_ns);
  10166. if (r < 0)
  10167. goto fail_mmu_destroy;
  10168. /*
  10169. * Defer evaluating inhibits until the vCPU is first run, as
  10170. * this vCPU will not get notified of any changes until this
  10171. * vCPU is visible to other vCPUs (marked online and added to
  10172. * the set of vCPUs). Opportunistically mark APICv active as
  10173. * VMX in particularly is highly unlikely to have inhibits.
  10174. * Ignore the current per-VM APICv state so that vCPU creation
  10175. * is guaranteed to run with a deterministic value, the request
  10176. * will ensure the vCPU gets the correct state before VM-Entry.
  10177. */
  10178. if (enable_apicv) {
  10179. vcpu->arch.apic->apicv_active = true;
  10180. kvm_make_request(KVM_REQ_APICV_UPDATE, vcpu);
  10181. }
  10182. } else
  10183. static_branch_inc(&kvm_has_noapic_vcpu);
  10184. r = -ENOMEM;
  10185. page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
  10186. if (!page)
  10187. goto fail_free_lapic;
  10188. vcpu->arch.pio_data = page_address(page);
  10189. vcpu->arch.mce_banks = kcalloc(KVM_MAX_MCE_BANKS * 4, sizeof(u64),
  10190. GFP_KERNEL_ACCOUNT);
  10191. vcpu->arch.mci_ctl2_banks = kcalloc(KVM_MAX_MCE_BANKS, sizeof(u64),
  10192. GFP_KERNEL_ACCOUNT);
  10193. if (!vcpu->arch.mce_banks || !vcpu->arch.mci_ctl2_banks)
  10194. goto fail_free_mce_banks;
  10195. vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
  10196. if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask,
  10197. GFP_KERNEL_ACCOUNT))
  10198. goto fail_free_mce_banks;
  10199. if (!alloc_emulate_ctxt(vcpu))
  10200. goto free_wbinvd_dirty_mask;
  10201. if (!fpu_alloc_guest_fpstate(&vcpu->arch.guest_fpu)) {
  10202. pr_err("kvm: failed to allocate vcpu's fpu\n");
  10203. goto free_emulate_ctxt;
  10204. }
  10205. vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
  10206. vcpu->arch.reserved_gpa_bits = kvm_vcpu_reserved_gpa_bits_raw(vcpu);
  10207. vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
  10208. kvm_async_pf_hash_reset(vcpu);
  10209. kvm_pmu_init(vcpu);
  10210. vcpu->arch.pending_external_vector = -1;
  10211. vcpu->arch.preempted_in_kernel = false;
  10212. #if IS_ENABLED(CONFIG_HYPERV)
  10213. vcpu->arch.hv_root_tdp = INVALID_PAGE;
  10214. #endif
  10215. r = static_call(kvm_x86_vcpu_create)(vcpu);
  10216. if (r)
  10217. goto free_guest_fpu;
  10218. vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
  10219. vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
  10220. kvm_xen_init_vcpu(vcpu);
  10221. kvm_vcpu_mtrr_init(vcpu);
  10222. vcpu_load(vcpu);
  10223. kvm_set_tsc_khz(vcpu, vcpu->kvm->arch.default_tsc_khz);
  10224. kvm_vcpu_reset(vcpu, false);
  10225. kvm_init_mmu(vcpu);
  10226. vcpu_put(vcpu);
  10227. return 0;
  10228. free_guest_fpu:
  10229. fpu_free_guest_fpstate(&vcpu->arch.guest_fpu);
  10230. free_emulate_ctxt:
  10231. kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
  10232. free_wbinvd_dirty_mask:
  10233. free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
  10234. fail_free_mce_banks:
  10235. kfree(vcpu->arch.mce_banks);
  10236. kfree(vcpu->arch.mci_ctl2_banks);
  10237. free_page((unsigned long)vcpu->arch.pio_data);
  10238. fail_free_lapic:
  10239. kvm_free_lapic(vcpu);
  10240. fail_mmu_destroy:
  10241. kvm_mmu_destroy(vcpu);
  10242. return r;
  10243. }
  10244. void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
  10245. {
  10246. struct kvm *kvm = vcpu->kvm;
  10247. if (mutex_lock_killable(&vcpu->mutex))
  10248. return;
  10249. vcpu_load(vcpu);
  10250. kvm_synchronize_tsc(vcpu, 0);
  10251. vcpu_put(vcpu);
  10252. /* poll control enabled by default */
  10253. vcpu->arch.msr_kvm_poll_control = 1;
  10254. mutex_unlock(&vcpu->mutex);
  10255. if (kvmclock_periodic_sync && vcpu->vcpu_idx == 0)
  10256. schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
  10257. KVMCLOCK_SYNC_PERIOD);
  10258. }
  10259. void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
  10260. {
  10261. int idx;
  10262. kvmclock_reset(vcpu);
  10263. static_call(kvm_x86_vcpu_free)(vcpu);
  10264. kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
  10265. free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
  10266. fpu_free_guest_fpstate(&vcpu->arch.guest_fpu);
  10267. kvm_xen_destroy_vcpu(vcpu);
  10268. kvm_hv_vcpu_uninit(vcpu);
  10269. kvm_pmu_destroy(vcpu);
  10270. kfree(vcpu->arch.mce_banks);
  10271. kfree(vcpu->arch.mci_ctl2_banks);
  10272. kvm_free_lapic(vcpu);
  10273. idx = srcu_read_lock(&vcpu->kvm->srcu);
  10274. kvm_mmu_destroy(vcpu);
  10275. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  10276. free_page((unsigned long)vcpu->arch.pio_data);
  10277. kvfree(vcpu->arch.cpuid_entries);
  10278. if (!lapic_in_kernel(vcpu))
  10279. static_branch_dec(&kvm_has_noapic_vcpu);
  10280. }
  10281. void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
  10282. {
  10283. struct kvm_cpuid_entry2 *cpuid_0x1;
  10284. unsigned long old_cr0 = kvm_read_cr0(vcpu);
  10285. unsigned long new_cr0;
  10286. /*
  10287. * Several of the "set" flows, e.g. ->set_cr0(), read other registers
  10288. * to handle side effects. RESET emulation hits those flows and relies
  10289. * on emulated/virtualized registers, including those that are loaded
  10290. * into hardware, to be zeroed at vCPU creation. Use CRs as a sentinel
  10291. * to detect improper or missing initialization.
  10292. */
  10293. WARN_ON_ONCE(!init_event &&
  10294. (old_cr0 || kvm_read_cr3(vcpu) || kvm_read_cr4(vcpu)));
  10295. /*
  10296. * SVM doesn't unconditionally VM-Exit on INIT and SHUTDOWN, thus it's
  10297. * possible to INIT the vCPU while L2 is active. Force the vCPU back
  10298. * into L1 as EFER.SVME is cleared on INIT (along with all other EFER
  10299. * bits), i.e. virtualization is disabled.
  10300. */
  10301. if (is_guest_mode(vcpu))
  10302. kvm_leave_nested(vcpu);
  10303. kvm_lapic_reset(vcpu, init_event);
  10304. WARN_ON_ONCE(is_guest_mode(vcpu) || is_smm(vcpu));
  10305. vcpu->arch.hflags = 0;
  10306. vcpu->arch.smi_pending = 0;
  10307. vcpu->arch.smi_count = 0;
  10308. atomic_set(&vcpu->arch.nmi_queued, 0);
  10309. vcpu->arch.nmi_pending = 0;
  10310. vcpu->arch.nmi_injected = false;
  10311. kvm_clear_interrupt_queue(vcpu);
  10312. kvm_clear_exception_queue(vcpu);
  10313. memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
  10314. kvm_update_dr0123(vcpu);
  10315. vcpu->arch.dr6 = DR6_ACTIVE_LOW;
  10316. vcpu->arch.dr7 = DR7_FIXED_1;
  10317. kvm_update_dr7(vcpu);
  10318. vcpu->arch.cr2 = 0;
  10319. kvm_make_request(KVM_REQ_EVENT, vcpu);
  10320. vcpu->arch.apf.msr_en_val = 0;
  10321. vcpu->arch.apf.msr_int_val = 0;
  10322. vcpu->arch.st.msr_val = 0;
  10323. kvmclock_reset(vcpu);
  10324. kvm_clear_async_pf_completion_queue(vcpu);
  10325. kvm_async_pf_hash_reset(vcpu);
  10326. vcpu->arch.apf.halted = false;
  10327. if (vcpu->arch.guest_fpu.fpstate && kvm_mpx_supported()) {
  10328. struct fpstate *fpstate = vcpu->arch.guest_fpu.fpstate;
  10329. /*
  10330. * All paths that lead to INIT are required to load the guest's
  10331. * FPU state (because most paths are buried in KVM_RUN).
  10332. */
  10333. if (init_event)
  10334. kvm_put_guest_fpu(vcpu);
  10335. fpstate_clear_xstate_component(fpstate, XFEATURE_BNDREGS);
  10336. fpstate_clear_xstate_component(fpstate, XFEATURE_BNDCSR);
  10337. if (init_event)
  10338. kvm_load_guest_fpu(vcpu);
  10339. }
  10340. if (!init_event) {
  10341. kvm_pmu_reset(vcpu);
  10342. vcpu->arch.smbase = 0x30000;
  10343. vcpu->arch.msr_misc_features_enables = 0;
  10344. vcpu->arch.ia32_misc_enable_msr = MSR_IA32_MISC_ENABLE_PEBS_UNAVAIL |
  10345. MSR_IA32_MISC_ENABLE_BTS_UNAVAIL;
  10346. __kvm_set_xcr(vcpu, 0, XFEATURE_MASK_FP);
  10347. __kvm_set_msr(vcpu, MSR_IA32_XSS, 0, true);
  10348. }
  10349. /* All GPRs except RDX (handled below) are zeroed on RESET/INIT. */
  10350. memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
  10351. kvm_register_mark_dirty(vcpu, VCPU_REGS_RSP);
  10352. /*
  10353. * Fall back to KVM's default Family/Model/Stepping of 0x600 (P6/Athlon)
  10354. * if no CPUID match is found. Note, it's impossible to get a match at
  10355. * RESET since KVM emulates RESET before exposing the vCPU to userspace,
  10356. * i.e. it's impossible for kvm_find_cpuid_entry() to find a valid entry
  10357. * on RESET. But, go through the motions in case that's ever remedied.
  10358. */
  10359. cpuid_0x1 = kvm_find_cpuid_entry(vcpu, 1);
  10360. kvm_rdx_write(vcpu, cpuid_0x1 ? cpuid_0x1->eax : 0x600);
  10361. static_call(kvm_x86_vcpu_reset)(vcpu, init_event);
  10362. kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
  10363. kvm_rip_write(vcpu, 0xfff0);
  10364. vcpu->arch.cr3 = 0;
  10365. kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
  10366. /*
  10367. * CR0.CD/NW are set on RESET, preserved on INIT. Note, some versions
  10368. * of Intel's SDM list CD/NW as being set on INIT, but they contradict
  10369. * (or qualify) that with a footnote stating that CD/NW are preserved.
  10370. */
  10371. new_cr0 = X86_CR0_ET;
  10372. if (init_event)
  10373. new_cr0 |= (old_cr0 & (X86_CR0_NW | X86_CR0_CD));
  10374. else
  10375. new_cr0 |= X86_CR0_NW | X86_CR0_CD;
  10376. static_call(kvm_x86_set_cr0)(vcpu, new_cr0);
  10377. static_call(kvm_x86_set_cr4)(vcpu, 0);
  10378. static_call(kvm_x86_set_efer)(vcpu, 0);
  10379. static_call(kvm_x86_update_exception_bitmap)(vcpu);
  10380. /*
  10381. * On the standard CR0/CR4/EFER modification paths, there are several
  10382. * complex conditions determining whether the MMU has to be reset and/or
  10383. * which PCIDs have to be flushed. However, CR0.WP and the paging-related
  10384. * bits in CR4 and EFER are irrelevant if CR0.PG was '0'; and a reset+flush
  10385. * is needed anyway if CR0.PG was '1' (which can only happen for INIT, as
  10386. * CR0 will be '0' prior to RESET). So we only need to check CR0.PG here.
  10387. */
  10388. if (old_cr0 & X86_CR0_PG) {
  10389. kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
  10390. kvm_mmu_reset_context(vcpu);
  10391. }
  10392. /*
  10393. * Intel's SDM states that all TLB entries are flushed on INIT. AMD's
  10394. * APM states the TLBs are untouched by INIT, but it also states that
  10395. * the TLBs are flushed on "External initialization of the processor."
  10396. * Flush the guest TLB regardless of vendor, there is no meaningful
  10397. * benefit in relying on the guest to flush the TLB immediately after
  10398. * INIT. A spurious TLB flush is benign and likely negligible from a
  10399. * performance perspective.
  10400. */
  10401. if (init_event)
  10402. kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
  10403. }
  10404. EXPORT_SYMBOL_GPL(kvm_vcpu_reset);
  10405. void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
  10406. {
  10407. struct kvm_segment cs;
  10408. kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
  10409. cs.selector = vector << 8;
  10410. cs.base = vector << 12;
  10411. kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
  10412. kvm_rip_write(vcpu, 0);
  10413. }
  10414. EXPORT_SYMBOL_GPL(kvm_vcpu_deliver_sipi_vector);
  10415. int kvm_arch_hardware_enable(void)
  10416. {
  10417. struct kvm *kvm;
  10418. struct kvm_vcpu *vcpu;
  10419. unsigned long i;
  10420. int ret;
  10421. u64 local_tsc;
  10422. u64 max_tsc = 0;
  10423. bool stable, backwards_tsc = false;
  10424. kvm_user_return_msr_cpu_online();
  10425. ret = static_call(kvm_x86_hardware_enable)();
  10426. if (ret != 0)
  10427. return ret;
  10428. local_tsc = rdtsc();
  10429. stable = !kvm_check_tsc_unstable();
  10430. list_for_each_entry(kvm, &vm_list, vm_list) {
  10431. kvm_for_each_vcpu(i, vcpu, kvm) {
  10432. if (!stable && vcpu->cpu == smp_processor_id())
  10433. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  10434. if (stable && vcpu->arch.last_host_tsc > local_tsc) {
  10435. backwards_tsc = true;
  10436. if (vcpu->arch.last_host_tsc > max_tsc)
  10437. max_tsc = vcpu->arch.last_host_tsc;
  10438. }
  10439. }
  10440. }
  10441. /*
  10442. * Sometimes, even reliable TSCs go backwards. This happens on
  10443. * platforms that reset TSC during suspend or hibernate actions, but
  10444. * maintain synchronization. We must compensate. Fortunately, we can
  10445. * detect that condition here, which happens early in CPU bringup,
  10446. * before any KVM threads can be running. Unfortunately, we can't
  10447. * bring the TSCs fully up to date with real time, as we aren't yet far
  10448. * enough into CPU bringup that we know how much real time has actually
  10449. * elapsed; our helper function, ktime_get_boottime_ns() will be using boot
  10450. * variables that haven't been updated yet.
  10451. *
  10452. * So we simply find the maximum observed TSC above, then record the
  10453. * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
  10454. * the adjustment will be applied. Note that we accumulate
  10455. * adjustments, in case multiple suspend cycles happen before some VCPU
  10456. * gets a chance to run again. In the event that no KVM threads get a
  10457. * chance to run, we will miss the entire elapsed period, as we'll have
  10458. * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
  10459. * loose cycle time. This isn't too big a deal, since the loss will be
  10460. * uniform across all VCPUs (not to mention the scenario is extremely
  10461. * unlikely). It is possible that a second hibernate recovery happens
  10462. * much faster than a first, causing the observed TSC here to be
  10463. * smaller; this would require additional padding adjustment, which is
  10464. * why we set last_host_tsc to the local tsc observed here.
  10465. *
  10466. * N.B. - this code below runs only on platforms with reliable TSC,
  10467. * as that is the only way backwards_tsc is set above. Also note
  10468. * that this runs for ALL vcpus, which is not a bug; all VCPUs should
  10469. * have the same delta_cyc adjustment applied if backwards_tsc
  10470. * is detected. Note further, this adjustment is only done once,
  10471. * as we reset last_host_tsc on all VCPUs to stop this from being
  10472. * called multiple times (one for each physical CPU bringup).
  10473. *
  10474. * Platforms with unreliable TSCs don't have to deal with this, they
  10475. * will be compensated by the logic in vcpu_load, which sets the TSC to
  10476. * catchup mode. This will catchup all VCPUs to real time, but cannot
  10477. * guarantee that they stay in perfect synchronization.
  10478. */
  10479. if (backwards_tsc) {
  10480. u64 delta_cyc = max_tsc - local_tsc;
  10481. list_for_each_entry(kvm, &vm_list, vm_list) {
  10482. kvm->arch.backwards_tsc_observed = true;
  10483. kvm_for_each_vcpu(i, vcpu, kvm) {
  10484. vcpu->arch.tsc_offset_adjustment += delta_cyc;
  10485. vcpu->arch.last_host_tsc = local_tsc;
  10486. kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
  10487. }
  10488. /*
  10489. * We have to disable TSC offset matching.. if you were
  10490. * booting a VM while issuing an S4 host suspend....
  10491. * you may have some problem. Solving this issue is
  10492. * left as an exercise to the reader.
  10493. */
  10494. kvm->arch.last_tsc_nsec = 0;
  10495. kvm->arch.last_tsc_write = 0;
  10496. }
  10497. }
  10498. return 0;
  10499. }
  10500. void kvm_arch_hardware_disable(void)
  10501. {
  10502. static_call(kvm_x86_hardware_disable)();
  10503. drop_user_return_notifiers();
  10504. }
  10505. static inline void kvm_ops_update(struct kvm_x86_init_ops *ops)
  10506. {
  10507. memcpy(&kvm_x86_ops, ops->runtime_ops, sizeof(kvm_x86_ops));
  10508. #define __KVM_X86_OP(func) \
  10509. static_call_update(kvm_x86_##func, kvm_x86_ops.func);
  10510. #define KVM_X86_OP(func) \
  10511. WARN_ON(!kvm_x86_ops.func); __KVM_X86_OP(func)
  10512. #define KVM_X86_OP_OPTIONAL __KVM_X86_OP
  10513. #define KVM_X86_OP_OPTIONAL_RET0(func) \
  10514. static_call_update(kvm_x86_##func, (void *)kvm_x86_ops.func ? : \
  10515. (void *)__static_call_return0);
  10516. #include <asm/kvm-x86-ops.h>
  10517. #undef __KVM_X86_OP
  10518. kvm_pmu_ops_update(ops->pmu_ops);
  10519. }
  10520. int kvm_arch_hardware_setup(void *opaque)
  10521. {
  10522. struct kvm_x86_init_ops *ops = opaque;
  10523. int r;
  10524. rdmsrl_safe(MSR_EFER, &host_efer);
  10525. if (boot_cpu_has(X86_FEATURE_XSAVES))
  10526. rdmsrl(MSR_IA32_XSS, host_xss);
  10527. kvm_init_pmu_capability();
  10528. r = ops->hardware_setup();
  10529. if (r != 0)
  10530. return r;
  10531. kvm_ops_update(ops);
  10532. kvm_register_perf_callbacks(ops->handle_intel_pt_intr);
  10533. if (!kvm_cpu_cap_has(X86_FEATURE_XSAVES))
  10534. kvm_caps.supported_xss = 0;
  10535. #define __kvm_cpu_cap_has(UNUSED_, f) kvm_cpu_cap_has(f)
  10536. cr4_reserved_bits = __cr4_reserved_bits(__kvm_cpu_cap_has, UNUSED_);
  10537. #undef __kvm_cpu_cap_has
  10538. if (kvm_caps.has_tsc_control) {
  10539. /*
  10540. * Make sure the user can only configure tsc_khz values that
  10541. * fit into a signed integer.
  10542. * A min value is not calculated because it will always
  10543. * be 1 on all machines.
  10544. */
  10545. u64 max = min(0x7fffffffULL,
  10546. __scale_tsc(kvm_caps.max_tsc_scaling_ratio, tsc_khz));
  10547. kvm_caps.max_guest_tsc_khz = max;
  10548. }
  10549. kvm_caps.default_tsc_scaling_ratio = 1ULL << kvm_caps.tsc_scaling_ratio_frac_bits;
  10550. kvm_init_msr_list();
  10551. return 0;
  10552. }
  10553. void kvm_arch_hardware_unsetup(void)
  10554. {
  10555. kvm_unregister_perf_callbacks();
  10556. static_call(kvm_x86_hardware_unsetup)();
  10557. }
  10558. int kvm_arch_check_processor_compat(void *opaque)
  10559. {
  10560. struct cpuinfo_x86 *c = &cpu_data(smp_processor_id());
  10561. struct kvm_x86_init_ops *ops = opaque;
  10562. WARN_ON(!irqs_disabled());
  10563. if (__cr4_reserved_bits(cpu_has, c) !=
  10564. __cr4_reserved_bits(cpu_has, &boot_cpu_data))
  10565. return -EIO;
  10566. return ops->check_processor_compatibility();
  10567. }
  10568. bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
  10569. {
  10570. return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
  10571. }
  10572. EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
  10573. bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
  10574. {
  10575. return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
  10576. }
  10577. __read_mostly DEFINE_STATIC_KEY_FALSE(kvm_has_noapic_vcpu);
  10578. EXPORT_SYMBOL_GPL(kvm_has_noapic_vcpu);
  10579. void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
  10580. {
  10581. struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
  10582. vcpu->arch.l1tf_flush_l1d = true;
  10583. if (pmu->version && unlikely(pmu->event_count)) {
  10584. pmu->need_cleanup = true;
  10585. kvm_make_request(KVM_REQ_PMU, vcpu);
  10586. }
  10587. static_call(kvm_x86_sched_in)(vcpu, cpu);
  10588. }
  10589. void kvm_arch_free_vm(struct kvm *kvm)
  10590. {
  10591. kfree(to_kvm_hv(kvm)->hv_pa_pg);
  10592. __kvm_arch_free_vm(kvm);
  10593. }
  10594. int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
  10595. {
  10596. int ret;
  10597. unsigned long flags;
  10598. if (type)
  10599. return -EINVAL;
  10600. ret = kvm_page_track_init(kvm);
  10601. if (ret)
  10602. goto out;
  10603. kvm_mmu_init_vm(kvm);
  10604. ret = static_call(kvm_x86_vm_init)(kvm);
  10605. if (ret)
  10606. goto out_uninit_mmu;
  10607. INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
  10608. INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
  10609. atomic_set(&kvm->arch.noncoherent_dma_count, 0);
  10610. /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
  10611. set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
  10612. /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
  10613. set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
  10614. &kvm->arch.irq_sources_bitmap);
  10615. raw_spin_lock_init(&kvm->arch.tsc_write_lock);
  10616. mutex_init(&kvm->arch.apic_map_lock);
  10617. seqcount_raw_spinlock_init(&kvm->arch.pvclock_sc, &kvm->arch.tsc_write_lock);
  10618. kvm->arch.kvmclock_offset = -get_kvmclock_base_ns();
  10619. raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
  10620. pvclock_update_vm_gtod_copy(kvm);
  10621. raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
  10622. kvm->arch.default_tsc_khz = max_tsc_khz ? : tsc_khz;
  10623. kvm->arch.guest_can_read_msr_platform_info = true;
  10624. kvm->arch.enable_pmu = enable_pmu;
  10625. #if IS_ENABLED(CONFIG_HYPERV)
  10626. spin_lock_init(&kvm->arch.hv_root_tdp_lock);
  10627. kvm->arch.hv_root_tdp = INVALID_PAGE;
  10628. #endif
  10629. INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
  10630. INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
  10631. kvm_apicv_init(kvm);
  10632. kvm_hv_init_vm(kvm);
  10633. kvm_xen_init_vm(kvm);
  10634. return 0;
  10635. out_uninit_mmu:
  10636. kvm_mmu_uninit_vm(kvm);
  10637. kvm_page_track_cleanup(kvm);
  10638. out:
  10639. return ret;
  10640. }
  10641. int kvm_arch_post_init_vm(struct kvm *kvm)
  10642. {
  10643. return kvm_mmu_post_init_vm(kvm);
  10644. }
  10645. static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
  10646. {
  10647. vcpu_load(vcpu);
  10648. kvm_mmu_unload(vcpu);
  10649. vcpu_put(vcpu);
  10650. }
  10651. static void kvm_unload_vcpu_mmus(struct kvm *kvm)
  10652. {
  10653. unsigned long i;
  10654. struct kvm_vcpu *vcpu;
  10655. kvm_for_each_vcpu(i, vcpu, kvm) {
  10656. kvm_clear_async_pf_completion_queue(vcpu);
  10657. kvm_unload_vcpu_mmu(vcpu);
  10658. }
  10659. }
  10660. void kvm_arch_sync_events(struct kvm *kvm)
  10661. {
  10662. cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
  10663. cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
  10664. kvm_free_pit(kvm);
  10665. }
  10666. /**
  10667. * __x86_set_memory_region: Setup KVM internal memory slot
  10668. *
  10669. * @kvm: the kvm pointer to the VM.
  10670. * @id: the slot ID to setup.
  10671. * @gpa: the GPA to install the slot (unused when @size == 0).
  10672. * @size: the size of the slot. Set to zero to uninstall a slot.
  10673. *
  10674. * This function helps to setup a KVM internal memory slot. Specify
  10675. * @size > 0 to install a new slot, while @size == 0 to uninstall a
  10676. * slot. The return code can be one of the following:
  10677. *
  10678. * HVA: on success (uninstall will return a bogus HVA)
  10679. * -errno: on error
  10680. *
  10681. * The caller should always use IS_ERR() to check the return value
  10682. * before use. Note, the KVM internal memory slots are guaranteed to
  10683. * remain valid and unchanged until the VM is destroyed, i.e., the
  10684. * GPA->HVA translation will not change. However, the HVA is a user
  10685. * address, i.e. its accessibility is not guaranteed, and must be
  10686. * accessed via __copy_{to,from}_user().
  10687. */
  10688. void __user * __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa,
  10689. u32 size)
  10690. {
  10691. int i, r;
  10692. unsigned long hva, old_npages;
  10693. struct kvm_memslots *slots = kvm_memslots(kvm);
  10694. struct kvm_memory_slot *slot;
  10695. /* Called with kvm->slots_lock held. */
  10696. if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
  10697. return ERR_PTR_USR(-EINVAL);
  10698. slot = id_to_memslot(slots, id);
  10699. if (size) {
  10700. if (slot && slot->npages)
  10701. return ERR_PTR_USR(-EEXIST);
  10702. /*
  10703. * MAP_SHARED to prevent internal slot pages from being moved
  10704. * by fork()/COW.
  10705. */
  10706. hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
  10707. MAP_SHARED | MAP_ANONYMOUS, 0);
  10708. if (IS_ERR((void *)hva))
  10709. return (void __user *)hva;
  10710. } else {
  10711. if (!slot || !slot->npages)
  10712. return NULL;
  10713. old_npages = slot->npages;
  10714. hva = slot->userspace_addr;
  10715. }
  10716. for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
  10717. struct kvm_userspace_memory_region m;
  10718. m.slot = id | (i << 16);
  10719. m.flags = 0;
  10720. m.guest_phys_addr = gpa;
  10721. m.userspace_addr = hva;
  10722. m.memory_size = size;
  10723. r = __kvm_set_memory_region(kvm, &m);
  10724. if (r < 0)
  10725. return ERR_PTR_USR(r);
  10726. }
  10727. if (!size)
  10728. vm_munmap(hva, old_npages * PAGE_SIZE);
  10729. return (void __user *)hva;
  10730. }
  10731. EXPORT_SYMBOL_GPL(__x86_set_memory_region);
  10732. void kvm_arch_pre_destroy_vm(struct kvm *kvm)
  10733. {
  10734. kvm_mmu_pre_destroy_vm(kvm);
  10735. }
  10736. void kvm_arch_destroy_vm(struct kvm *kvm)
  10737. {
  10738. if (current->mm == kvm->mm) {
  10739. /*
  10740. * Free memory regions allocated on behalf of userspace,
  10741. * unless the memory map has changed due to process exit
  10742. * or fd copying.
  10743. */
  10744. mutex_lock(&kvm->slots_lock);
  10745. __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
  10746. 0, 0);
  10747. __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
  10748. 0, 0);
  10749. __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
  10750. mutex_unlock(&kvm->slots_lock);
  10751. }
  10752. kvm_unload_vcpu_mmus(kvm);
  10753. static_call_cond(kvm_x86_vm_destroy)(kvm);
  10754. kvm_free_msr_filter(srcu_dereference_check(kvm->arch.msr_filter, &kvm->srcu, 1));
  10755. kvm_pic_destroy(kvm);
  10756. kvm_ioapic_destroy(kvm);
  10757. kvm_destroy_vcpus(kvm);
  10758. kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
  10759. kfree(srcu_dereference_check(kvm->arch.pmu_event_filter, &kvm->srcu, 1));
  10760. kvm_mmu_uninit_vm(kvm);
  10761. kvm_page_track_cleanup(kvm);
  10762. kvm_xen_destroy_vm(kvm);
  10763. kvm_hv_destroy_vm(kvm);
  10764. }
  10765. static void memslot_rmap_free(struct kvm_memory_slot *slot)
  10766. {
  10767. int i;
  10768. for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
  10769. kvfree(slot->arch.rmap[i]);
  10770. slot->arch.rmap[i] = NULL;
  10771. }
  10772. }
  10773. void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
  10774. {
  10775. int i;
  10776. memslot_rmap_free(slot);
  10777. for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
  10778. kvfree(slot->arch.lpage_info[i - 1]);
  10779. slot->arch.lpage_info[i - 1] = NULL;
  10780. }
  10781. kvm_page_track_free_memslot(slot);
  10782. }
  10783. int memslot_rmap_alloc(struct kvm_memory_slot *slot, unsigned long npages)
  10784. {
  10785. const int sz = sizeof(*slot->arch.rmap[0]);
  10786. int i;
  10787. for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
  10788. int level = i + 1;
  10789. int lpages = __kvm_mmu_slot_lpages(slot, npages, level);
  10790. if (slot->arch.rmap[i])
  10791. continue;
  10792. slot->arch.rmap[i] = __vcalloc(lpages, sz, GFP_KERNEL_ACCOUNT);
  10793. if (!slot->arch.rmap[i]) {
  10794. memslot_rmap_free(slot);
  10795. return -ENOMEM;
  10796. }
  10797. }
  10798. return 0;
  10799. }
  10800. static int kvm_alloc_memslot_metadata(struct kvm *kvm,
  10801. struct kvm_memory_slot *slot)
  10802. {
  10803. unsigned long npages = slot->npages;
  10804. int i, r;
  10805. /*
  10806. * Clear out the previous array pointers for the KVM_MR_MOVE case. The
  10807. * old arrays will be freed by __kvm_set_memory_region() if installing
  10808. * the new memslot is successful.
  10809. */
  10810. memset(&slot->arch, 0, sizeof(slot->arch));
  10811. if (kvm_memslots_have_rmaps(kvm)) {
  10812. r = memslot_rmap_alloc(slot, npages);
  10813. if (r)
  10814. return r;
  10815. }
  10816. for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
  10817. struct kvm_lpage_info *linfo;
  10818. unsigned long ugfn;
  10819. int lpages;
  10820. int level = i + 1;
  10821. lpages = __kvm_mmu_slot_lpages(slot, npages, level);
  10822. linfo = __vcalloc(lpages, sizeof(*linfo), GFP_KERNEL_ACCOUNT);
  10823. if (!linfo)
  10824. goto out_free;
  10825. slot->arch.lpage_info[i - 1] = linfo;
  10826. if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
  10827. linfo[0].disallow_lpage = 1;
  10828. if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
  10829. linfo[lpages - 1].disallow_lpage = 1;
  10830. ugfn = slot->userspace_addr >> PAGE_SHIFT;
  10831. /*
  10832. * If the gfn and userspace address are not aligned wrt each
  10833. * other, disable large page support for this slot.
  10834. */
  10835. if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1)) {
  10836. unsigned long j;
  10837. for (j = 0; j < lpages; ++j)
  10838. linfo[j].disallow_lpage = 1;
  10839. }
  10840. }
  10841. if (kvm_page_track_create_memslot(kvm, slot, npages))
  10842. goto out_free;
  10843. return 0;
  10844. out_free:
  10845. memslot_rmap_free(slot);
  10846. for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
  10847. kvfree(slot->arch.lpage_info[i - 1]);
  10848. slot->arch.lpage_info[i - 1] = NULL;
  10849. }
  10850. return -ENOMEM;
  10851. }
  10852. void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
  10853. {
  10854. struct kvm_vcpu *vcpu;
  10855. unsigned long i;
  10856. /*
  10857. * memslots->generation has been incremented.
  10858. * mmio generation may have reached its maximum value.
  10859. */
  10860. kvm_mmu_invalidate_mmio_sptes(kvm, gen);
  10861. /* Force re-initialization of steal_time cache */
  10862. kvm_for_each_vcpu(i, vcpu, kvm)
  10863. kvm_vcpu_kick(vcpu);
  10864. }
  10865. int kvm_arch_prepare_memory_region(struct kvm *kvm,
  10866. const struct kvm_memory_slot *old,
  10867. struct kvm_memory_slot *new,
  10868. enum kvm_mr_change change)
  10869. {
  10870. if (change == KVM_MR_CREATE || change == KVM_MR_MOVE) {
  10871. if ((new->base_gfn + new->npages - 1) > kvm_mmu_max_gfn())
  10872. return -EINVAL;
  10873. return kvm_alloc_memslot_metadata(kvm, new);
  10874. }
  10875. if (change == KVM_MR_FLAGS_ONLY)
  10876. memcpy(&new->arch, &old->arch, sizeof(old->arch));
  10877. else if (WARN_ON_ONCE(change != KVM_MR_DELETE))
  10878. return -EIO;
  10879. return 0;
  10880. }
  10881. static void kvm_mmu_update_cpu_dirty_logging(struct kvm *kvm, bool enable)
  10882. {
  10883. struct kvm_arch *ka = &kvm->arch;
  10884. if (!kvm_x86_ops.cpu_dirty_log_size)
  10885. return;
  10886. if ((enable && ++ka->cpu_dirty_logging_count == 1) ||
  10887. (!enable && --ka->cpu_dirty_logging_count == 0))
  10888. kvm_make_all_cpus_request(kvm, KVM_REQ_UPDATE_CPU_DIRTY_LOGGING);
  10889. WARN_ON_ONCE(ka->cpu_dirty_logging_count < 0);
  10890. }
  10891. static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
  10892. struct kvm_memory_slot *old,
  10893. const struct kvm_memory_slot *new,
  10894. enum kvm_mr_change change)
  10895. {
  10896. u32 old_flags = old ? old->flags : 0;
  10897. u32 new_flags = new ? new->flags : 0;
  10898. bool log_dirty_pages = new_flags & KVM_MEM_LOG_DIRTY_PAGES;
  10899. /*
  10900. * Update CPU dirty logging if dirty logging is being toggled. This
  10901. * applies to all operations.
  10902. */
  10903. if ((old_flags ^ new_flags) & KVM_MEM_LOG_DIRTY_PAGES)
  10904. kvm_mmu_update_cpu_dirty_logging(kvm, log_dirty_pages);
  10905. /*
  10906. * Nothing more to do for RO slots (which can't be dirtied and can't be
  10907. * made writable) or CREATE/MOVE/DELETE of a slot.
  10908. *
  10909. * For a memslot with dirty logging disabled:
  10910. * CREATE: No dirty mappings will already exist.
  10911. * MOVE/DELETE: The old mappings will already have been cleaned up by
  10912. * kvm_arch_flush_shadow_memslot()
  10913. *
  10914. * For a memslot with dirty logging enabled:
  10915. * CREATE: No shadow pages exist, thus nothing to write-protect
  10916. * and no dirty bits to clear.
  10917. * MOVE/DELETE: The old mappings will already have been cleaned up by
  10918. * kvm_arch_flush_shadow_memslot().
  10919. */
  10920. if ((change != KVM_MR_FLAGS_ONLY) || (new_flags & KVM_MEM_READONLY))
  10921. return;
  10922. /*
  10923. * READONLY and non-flags changes were filtered out above, and the only
  10924. * other flag is LOG_DIRTY_PAGES, i.e. something is wrong if dirty
  10925. * logging isn't being toggled on or off.
  10926. */
  10927. if (WARN_ON_ONCE(!((old_flags ^ new_flags) & KVM_MEM_LOG_DIRTY_PAGES)))
  10928. return;
  10929. if (!log_dirty_pages) {
  10930. /*
  10931. * Dirty logging tracks sptes in 4k granularity, meaning that
  10932. * large sptes have to be split. If live migration succeeds,
  10933. * the guest in the source machine will be destroyed and large
  10934. * sptes will be created in the destination. However, if the
  10935. * guest continues to run in the source machine (for example if
  10936. * live migration fails), small sptes will remain around and
  10937. * cause bad performance.
  10938. *
  10939. * Scan sptes if dirty logging has been stopped, dropping those
  10940. * which can be collapsed into a single large-page spte. Later
  10941. * page faults will create the large-page sptes.
  10942. */
  10943. kvm_mmu_zap_collapsible_sptes(kvm, new);
  10944. } else {
  10945. /*
  10946. * Initially-all-set does not require write protecting any page,
  10947. * because they're all assumed to be dirty.
  10948. */
  10949. if (kvm_dirty_log_manual_protect_and_init_set(kvm))
  10950. return;
  10951. if (READ_ONCE(eager_page_split))
  10952. kvm_mmu_slot_try_split_huge_pages(kvm, new, PG_LEVEL_4K);
  10953. if (kvm_x86_ops.cpu_dirty_log_size) {
  10954. kvm_mmu_slot_leaf_clear_dirty(kvm, new);
  10955. kvm_mmu_slot_remove_write_access(kvm, new, PG_LEVEL_2M);
  10956. } else {
  10957. kvm_mmu_slot_remove_write_access(kvm, new, PG_LEVEL_4K);
  10958. }
  10959. /*
  10960. * Unconditionally flush the TLBs after enabling dirty logging.
  10961. * A flush is almost always going to be necessary (see below),
  10962. * and unconditionally flushing allows the helpers to omit
  10963. * the subtly complex checks when removing write access.
  10964. *
  10965. * Do the flush outside of mmu_lock to reduce the amount of
  10966. * time mmu_lock is held. Flushing after dropping mmu_lock is
  10967. * safe as KVM only needs to guarantee the slot is fully
  10968. * write-protected before returning to userspace, i.e. before
  10969. * userspace can consume the dirty status.
  10970. *
  10971. * Flushing outside of mmu_lock requires KVM to be careful when
  10972. * making decisions based on writable status of an SPTE, e.g. a
  10973. * !writable SPTE doesn't guarantee a CPU can't perform writes.
  10974. *
  10975. * Specifically, KVM also write-protects guest page tables to
  10976. * monitor changes when using shadow paging, and must guarantee
  10977. * no CPUs can write to those page before mmu_lock is dropped.
  10978. * Because CPUs may have stale TLB entries at this point, a
  10979. * !writable SPTE doesn't guarantee CPUs can't perform writes.
  10980. *
  10981. * KVM also allows making SPTES writable outside of mmu_lock,
  10982. * e.g. to allow dirty logging without taking mmu_lock.
  10983. *
  10984. * To handle these scenarios, KVM uses a separate software-only
  10985. * bit (MMU-writable) to track if a SPTE is !writable due to
  10986. * a guest page table being write-protected (KVM clears the
  10987. * MMU-writable flag when write-protecting for shadow paging).
  10988. *
  10989. * The use of MMU-writable is also the primary motivation for
  10990. * the unconditional flush. Because KVM must guarantee that a
  10991. * CPU doesn't contain stale, writable TLB entries for a
  10992. * !MMU-writable SPTE, KVM must flush if it encounters any
  10993. * MMU-writable SPTE regardless of whether the actual hardware
  10994. * writable bit was set. I.e. KVM is almost guaranteed to need
  10995. * to flush, while unconditionally flushing allows the "remove
  10996. * write access" helpers to ignore MMU-writable entirely.
  10997. *
  10998. * See is_writable_pte() for more details (the case involving
  10999. * access-tracked SPTEs is particularly relevant).
  11000. */
  11001. kvm_arch_flush_remote_tlbs_memslot(kvm, new);
  11002. }
  11003. }
  11004. void kvm_arch_commit_memory_region(struct kvm *kvm,
  11005. struct kvm_memory_slot *old,
  11006. const struct kvm_memory_slot *new,
  11007. enum kvm_mr_change change)
  11008. {
  11009. if (!kvm->arch.n_requested_mmu_pages &&
  11010. (change == KVM_MR_CREATE || change == KVM_MR_DELETE)) {
  11011. unsigned long nr_mmu_pages;
  11012. nr_mmu_pages = kvm->nr_memslot_pages / KVM_MEMSLOT_PAGES_TO_MMU_PAGES_RATIO;
  11013. nr_mmu_pages = max(nr_mmu_pages, KVM_MIN_ALLOC_MMU_PAGES);
  11014. kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
  11015. }
  11016. kvm_mmu_slot_apply_flags(kvm, old, new, change);
  11017. /* Free the arrays associated with the old memslot. */
  11018. if (change == KVM_MR_MOVE)
  11019. kvm_arch_free_memslot(kvm, old);
  11020. }
  11021. void kvm_arch_flush_shadow_all(struct kvm *kvm)
  11022. {
  11023. kvm_mmu_zap_all(kvm);
  11024. }
  11025. void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
  11026. struct kvm_memory_slot *slot)
  11027. {
  11028. kvm_page_track_flush_slot(kvm, slot);
  11029. }
  11030. static inline bool kvm_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
  11031. {
  11032. return (is_guest_mode(vcpu) &&
  11033. static_call(kvm_x86_guest_apic_has_interrupt)(vcpu));
  11034. }
  11035. static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
  11036. {
  11037. if (!list_empty_careful(&vcpu->async_pf.done))
  11038. return true;
  11039. if (kvm_apic_has_pending_init_or_sipi(vcpu) &&
  11040. kvm_apic_init_sipi_allowed(vcpu))
  11041. return true;
  11042. if (vcpu->arch.pv.pv_unhalted)
  11043. return true;
  11044. if (kvm_is_exception_pending(vcpu))
  11045. return true;
  11046. if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
  11047. (vcpu->arch.nmi_pending &&
  11048. static_call(kvm_x86_nmi_allowed)(vcpu, false)))
  11049. return true;
  11050. if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
  11051. (vcpu->arch.smi_pending &&
  11052. static_call(kvm_x86_smi_allowed)(vcpu, false)))
  11053. return true;
  11054. if (kvm_arch_interrupt_allowed(vcpu) &&
  11055. (kvm_cpu_has_interrupt(vcpu) ||
  11056. kvm_guest_apic_has_interrupt(vcpu)))
  11057. return true;
  11058. if (kvm_hv_has_stimer_pending(vcpu))
  11059. return true;
  11060. if (is_guest_mode(vcpu) &&
  11061. kvm_x86_ops.nested_ops->has_events &&
  11062. kvm_x86_ops.nested_ops->has_events(vcpu))
  11063. return true;
  11064. if (kvm_xen_has_pending_events(vcpu))
  11065. return true;
  11066. return false;
  11067. }
  11068. int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
  11069. {
  11070. return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
  11071. }
  11072. bool kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu)
  11073. {
  11074. if (kvm_vcpu_apicv_active(vcpu) &&
  11075. static_call(kvm_x86_dy_apicv_has_pending_interrupt)(vcpu))
  11076. return true;
  11077. return false;
  11078. }
  11079. bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
  11080. {
  11081. if (READ_ONCE(vcpu->arch.pv.pv_unhalted))
  11082. return true;
  11083. if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
  11084. kvm_test_request(KVM_REQ_SMI, vcpu) ||
  11085. kvm_test_request(KVM_REQ_EVENT, vcpu))
  11086. return true;
  11087. return kvm_arch_dy_has_pending_interrupt(vcpu);
  11088. }
  11089. bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
  11090. {
  11091. if (vcpu->arch.guest_state_protected)
  11092. return true;
  11093. return vcpu->arch.preempted_in_kernel;
  11094. }
  11095. unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu)
  11096. {
  11097. return kvm_rip_read(vcpu);
  11098. }
  11099. int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
  11100. {
  11101. return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
  11102. }
  11103. int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
  11104. {
  11105. return static_call(kvm_x86_interrupt_allowed)(vcpu, false);
  11106. }
  11107. unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
  11108. {
  11109. /* Can't read the RIP when guest state is protected, just return 0 */
  11110. if (vcpu->arch.guest_state_protected)
  11111. return 0;
  11112. if (is_64_bit_mode(vcpu))
  11113. return kvm_rip_read(vcpu);
  11114. return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
  11115. kvm_rip_read(vcpu));
  11116. }
  11117. EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
  11118. bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
  11119. {
  11120. return kvm_get_linear_rip(vcpu) == linear_rip;
  11121. }
  11122. EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
  11123. unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
  11124. {
  11125. unsigned long rflags;
  11126. rflags = static_call(kvm_x86_get_rflags)(vcpu);
  11127. if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
  11128. rflags &= ~X86_EFLAGS_TF;
  11129. return rflags;
  11130. }
  11131. EXPORT_SYMBOL_GPL(kvm_get_rflags);
  11132. static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
  11133. {
  11134. if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
  11135. kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
  11136. rflags |= X86_EFLAGS_TF;
  11137. static_call(kvm_x86_set_rflags)(vcpu, rflags);
  11138. }
  11139. void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
  11140. {
  11141. __kvm_set_rflags(vcpu, rflags);
  11142. kvm_make_request(KVM_REQ_EVENT, vcpu);
  11143. }
  11144. EXPORT_SYMBOL_GPL(kvm_set_rflags);
  11145. static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
  11146. {
  11147. BUILD_BUG_ON(!is_power_of_2(ASYNC_PF_PER_VCPU));
  11148. return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
  11149. }
  11150. static inline u32 kvm_async_pf_next_probe(u32 key)
  11151. {
  11152. return (key + 1) & (ASYNC_PF_PER_VCPU - 1);
  11153. }
  11154. static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
  11155. {
  11156. u32 key = kvm_async_pf_hash_fn(gfn);
  11157. while (vcpu->arch.apf.gfns[key] != ~0)
  11158. key = kvm_async_pf_next_probe(key);
  11159. vcpu->arch.apf.gfns[key] = gfn;
  11160. }
  11161. static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
  11162. {
  11163. int i;
  11164. u32 key = kvm_async_pf_hash_fn(gfn);
  11165. for (i = 0; i < ASYNC_PF_PER_VCPU &&
  11166. (vcpu->arch.apf.gfns[key] != gfn &&
  11167. vcpu->arch.apf.gfns[key] != ~0); i++)
  11168. key = kvm_async_pf_next_probe(key);
  11169. return key;
  11170. }
  11171. bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
  11172. {
  11173. return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
  11174. }
  11175. static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
  11176. {
  11177. u32 i, j, k;
  11178. i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
  11179. if (WARN_ON_ONCE(vcpu->arch.apf.gfns[i] != gfn))
  11180. return;
  11181. while (true) {
  11182. vcpu->arch.apf.gfns[i] = ~0;
  11183. do {
  11184. j = kvm_async_pf_next_probe(j);
  11185. if (vcpu->arch.apf.gfns[j] == ~0)
  11186. return;
  11187. k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
  11188. /*
  11189. * k lies cyclically in ]i,j]
  11190. * | i.k.j |
  11191. * |....j i.k.| or |.k..j i...|
  11192. */
  11193. } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
  11194. vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
  11195. i = j;
  11196. }
  11197. }
  11198. static inline int apf_put_user_notpresent(struct kvm_vcpu *vcpu)
  11199. {
  11200. u32 reason = KVM_PV_REASON_PAGE_NOT_PRESENT;
  11201. return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &reason,
  11202. sizeof(reason));
  11203. }
  11204. static inline int apf_put_user_ready(struct kvm_vcpu *vcpu, u32 token)
  11205. {
  11206. unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
  11207. return kvm_write_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
  11208. &token, offset, sizeof(token));
  11209. }
  11210. static inline bool apf_pageready_slot_free(struct kvm_vcpu *vcpu)
  11211. {
  11212. unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
  11213. u32 val;
  11214. if (kvm_read_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
  11215. &val, offset, sizeof(val)))
  11216. return false;
  11217. return !val;
  11218. }
  11219. static bool kvm_can_deliver_async_pf(struct kvm_vcpu *vcpu)
  11220. {
  11221. if (!kvm_pv_async_pf_enabled(vcpu))
  11222. return false;
  11223. if (vcpu->arch.apf.send_user_only &&
  11224. static_call(kvm_x86_get_cpl)(vcpu) == 0)
  11225. return false;
  11226. if (is_guest_mode(vcpu)) {
  11227. /*
  11228. * L1 needs to opt into the special #PF vmexits that are
  11229. * used to deliver async page faults.
  11230. */
  11231. return vcpu->arch.apf.delivery_as_pf_vmexit;
  11232. } else {
  11233. /*
  11234. * Play it safe in case the guest temporarily disables paging.
  11235. * The real mode IDT in particular is unlikely to have a #PF
  11236. * exception setup.
  11237. */
  11238. return is_paging(vcpu);
  11239. }
  11240. }
  11241. bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
  11242. {
  11243. if (unlikely(!lapic_in_kernel(vcpu) ||
  11244. kvm_event_needs_reinjection(vcpu) ||
  11245. kvm_is_exception_pending(vcpu)))
  11246. return false;
  11247. if (kvm_hlt_in_guest(vcpu->kvm) && !kvm_can_deliver_async_pf(vcpu))
  11248. return false;
  11249. /*
  11250. * If interrupts are off we cannot even use an artificial
  11251. * halt state.
  11252. */
  11253. return kvm_arch_interrupt_allowed(vcpu);
  11254. }
  11255. bool kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
  11256. struct kvm_async_pf *work)
  11257. {
  11258. struct x86_exception fault;
  11259. trace_kvm_async_pf_not_present(work->arch.token, work->cr2_or_gpa);
  11260. kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
  11261. if (kvm_can_deliver_async_pf(vcpu) &&
  11262. !apf_put_user_notpresent(vcpu)) {
  11263. fault.vector = PF_VECTOR;
  11264. fault.error_code_valid = true;
  11265. fault.error_code = 0;
  11266. fault.nested_page_fault = false;
  11267. fault.address = work->arch.token;
  11268. fault.async_page_fault = true;
  11269. kvm_inject_page_fault(vcpu, &fault);
  11270. return true;
  11271. } else {
  11272. /*
  11273. * It is not possible to deliver a paravirtualized asynchronous
  11274. * page fault, but putting the guest in an artificial halt state
  11275. * can be beneficial nevertheless: if an interrupt arrives, we
  11276. * can deliver it timely and perhaps the guest will schedule
  11277. * another process. When the instruction that triggered a page
  11278. * fault is retried, hopefully the page will be ready in the host.
  11279. */
  11280. kvm_make_request(KVM_REQ_APF_HALT, vcpu);
  11281. return false;
  11282. }
  11283. }
  11284. void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
  11285. struct kvm_async_pf *work)
  11286. {
  11287. struct kvm_lapic_irq irq = {
  11288. .delivery_mode = APIC_DM_FIXED,
  11289. .vector = vcpu->arch.apf.vec
  11290. };
  11291. if (work->wakeup_all)
  11292. work->arch.token = ~0; /* broadcast wakeup */
  11293. else
  11294. kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
  11295. trace_kvm_async_pf_ready(work->arch.token, work->cr2_or_gpa);
  11296. if ((work->wakeup_all || work->notpresent_injected) &&
  11297. kvm_pv_async_pf_enabled(vcpu) &&
  11298. !apf_put_user_ready(vcpu, work->arch.token)) {
  11299. vcpu->arch.apf.pageready_pending = true;
  11300. kvm_apic_set_irq(vcpu, &irq, NULL);
  11301. }
  11302. vcpu->arch.apf.halted = false;
  11303. vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
  11304. }
  11305. void kvm_arch_async_page_present_queued(struct kvm_vcpu *vcpu)
  11306. {
  11307. kvm_make_request(KVM_REQ_APF_READY, vcpu);
  11308. if (!vcpu->arch.apf.pageready_pending)
  11309. kvm_vcpu_kick(vcpu);
  11310. }
  11311. bool kvm_arch_can_dequeue_async_page_present(struct kvm_vcpu *vcpu)
  11312. {
  11313. if (!kvm_pv_async_pf_enabled(vcpu))
  11314. return true;
  11315. else
  11316. return kvm_lapic_enabled(vcpu) && apf_pageready_slot_free(vcpu);
  11317. }
  11318. void kvm_arch_start_assignment(struct kvm *kvm)
  11319. {
  11320. if (atomic_inc_return(&kvm->arch.assigned_device_count) == 1)
  11321. static_call_cond(kvm_x86_pi_start_assignment)(kvm);
  11322. }
  11323. EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
  11324. void kvm_arch_end_assignment(struct kvm *kvm)
  11325. {
  11326. atomic_dec(&kvm->arch.assigned_device_count);
  11327. }
  11328. EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
  11329. bool noinstr kvm_arch_has_assigned_device(struct kvm *kvm)
  11330. {
  11331. return arch_atomic_read(&kvm->arch.assigned_device_count);
  11332. }
  11333. EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
  11334. void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
  11335. {
  11336. atomic_inc(&kvm->arch.noncoherent_dma_count);
  11337. }
  11338. EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
  11339. void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
  11340. {
  11341. atomic_dec(&kvm->arch.noncoherent_dma_count);
  11342. }
  11343. EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
  11344. bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
  11345. {
  11346. return atomic_read(&kvm->arch.noncoherent_dma_count);
  11347. }
  11348. EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
  11349. bool kvm_arch_has_irq_bypass(void)
  11350. {
  11351. return true;
  11352. }
  11353. int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
  11354. struct irq_bypass_producer *prod)
  11355. {
  11356. struct kvm_kernel_irqfd *irqfd =
  11357. container_of(cons, struct kvm_kernel_irqfd, consumer);
  11358. int ret;
  11359. irqfd->producer = prod;
  11360. kvm_arch_start_assignment(irqfd->kvm);
  11361. ret = static_call(kvm_x86_pi_update_irte)(irqfd->kvm,
  11362. prod->irq, irqfd->gsi, 1);
  11363. if (ret)
  11364. kvm_arch_end_assignment(irqfd->kvm);
  11365. return ret;
  11366. }
  11367. void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
  11368. struct irq_bypass_producer *prod)
  11369. {
  11370. int ret;
  11371. struct kvm_kernel_irqfd *irqfd =
  11372. container_of(cons, struct kvm_kernel_irqfd, consumer);
  11373. WARN_ON(irqfd->producer != prod);
  11374. irqfd->producer = NULL;
  11375. /*
  11376. * When producer of consumer is unregistered, we change back to
  11377. * remapped mode, so we can re-use the current implementation
  11378. * when the irq is masked/disabled or the consumer side (KVM
  11379. * int this case doesn't want to receive the interrupts.
  11380. */
  11381. ret = static_call(kvm_x86_pi_update_irte)(irqfd->kvm, prod->irq, irqfd->gsi, 0);
  11382. if (ret)
  11383. printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
  11384. " fails: %d\n", irqfd->consumer.token, ret);
  11385. kvm_arch_end_assignment(irqfd->kvm);
  11386. }
  11387. int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
  11388. uint32_t guest_irq, bool set)
  11389. {
  11390. return static_call(kvm_x86_pi_update_irte)(kvm, host_irq, guest_irq, set);
  11391. }
  11392. bool kvm_arch_irqfd_route_changed(struct kvm_kernel_irq_routing_entry *old,
  11393. struct kvm_kernel_irq_routing_entry *new)
  11394. {
  11395. if (new->type != KVM_IRQ_ROUTING_MSI)
  11396. return true;
  11397. return !!memcmp(&old->msi, &new->msi, sizeof(new->msi));
  11398. }
  11399. bool kvm_vector_hashing_enabled(void)
  11400. {
  11401. return vector_hashing;
  11402. }
  11403. bool kvm_arch_no_poll(struct kvm_vcpu *vcpu)
  11404. {
  11405. return (vcpu->arch.msr_kvm_poll_control & 1) == 0;
  11406. }
  11407. EXPORT_SYMBOL_GPL(kvm_arch_no_poll);
  11408. int kvm_spec_ctrl_test_value(u64 value)
  11409. {
  11410. /*
  11411. * test that setting IA32_SPEC_CTRL to given value
  11412. * is allowed by the host processor
  11413. */
  11414. u64 saved_value;
  11415. unsigned long flags;
  11416. int ret = 0;
  11417. local_irq_save(flags);
  11418. if (rdmsrl_safe(MSR_IA32_SPEC_CTRL, &saved_value))
  11419. ret = 1;
  11420. else if (wrmsrl_safe(MSR_IA32_SPEC_CTRL, value))
  11421. ret = 1;
  11422. else
  11423. wrmsrl(MSR_IA32_SPEC_CTRL, saved_value);
  11424. local_irq_restore(flags);
  11425. return ret;
  11426. }
  11427. EXPORT_SYMBOL_GPL(kvm_spec_ctrl_test_value);
  11428. void kvm_fixup_and_inject_pf_error(struct kvm_vcpu *vcpu, gva_t gva, u16 error_code)
  11429. {
  11430. struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
  11431. struct x86_exception fault;
  11432. u64 access = error_code &
  11433. (PFERR_WRITE_MASK | PFERR_FETCH_MASK | PFERR_USER_MASK);
  11434. if (!(error_code & PFERR_PRESENT_MASK) ||
  11435. mmu->gva_to_gpa(vcpu, mmu, gva, access, &fault) != INVALID_GPA) {
  11436. /*
  11437. * If vcpu->arch.walk_mmu->gva_to_gpa succeeded, the page
  11438. * tables probably do not match the TLB. Just proceed
  11439. * with the error code that the processor gave.
  11440. */
  11441. fault.vector = PF_VECTOR;
  11442. fault.error_code_valid = true;
  11443. fault.error_code = error_code;
  11444. fault.nested_page_fault = false;
  11445. fault.address = gva;
  11446. fault.async_page_fault = false;
  11447. }
  11448. vcpu->arch.walk_mmu->inject_page_fault(vcpu, &fault);
  11449. }
  11450. EXPORT_SYMBOL_GPL(kvm_fixup_and_inject_pf_error);
  11451. /*
  11452. * Handles kvm_read/write_guest_virt*() result and either injects #PF or returns
  11453. * KVM_EXIT_INTERNAL_ERROR for cases not currently handled by KVM. Return value
  11454. * indicates whether exit to userspace is needed.
  11455. */
  11456. int kvm_handle_memory_failure(struct kvm_vcpu *vcpu, int r,
  11457. struct x86_exception *e)
  11458. {
  11459. if (r == X86EMUL_PROPAGATE_FAULT) {
  11460. kvm_inject_emulated_page_fault(vcpu, e);
  11461. return 1;
  11462. }
  11463. /*
  11464. * In case kvm_read/write_guest_virt*() failed with X86EMUL_IO_NEEDED
  11465. * while handling a VMX instruction KVM could've handled the request
  11466. * correctly by exiting to userspace and performing I/O but there
  11467. * doesn't seem to be a real use-case behind such requests, just return
  11468. * KVM_EXIT_INTERNAL_ERROR for now.
  11469. */
  11470. kvm_prepare_emulation_failure_exit(vcpu);
  11471. return 0;
  11472. }
  11473. EXPORT_SYMBOL_GPL(kvm_handle_memory_failure);
  11474. int kvm_handle_invpcid(struct kvm_vcpu *vcpu, unsigned long type, gva_t gva)
  11475. {
  11476. bool pcid_enabled;
  11477. struct x86_exception e;
  11478. struct {
  11479. u64 pcid;
  11480. u64 gla;
  11481. } operand;
  11482. int r;
  11483. r = kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e);
  11484. if (r != X86EMUL_CONTINUE)
  11485. return kvm_handle_memory_failure(vcpu, r, &e);
  11486. if (operand.pcid >> 12 != 0) {
  11487. kvm_inject_gp(vcpu, 0);
  11488. return 1;
  11489. }
  11490. pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
  11491. switch (type) {
  11492. case INVPCID_TYPE_INDIV_ADDR:
  11493. if ((!pcid_enabled && (operand.pcid != 0)) ||
  11494. is_noncanonical_address(operand.gla, vcpu)) {
  11495. kvm_inject_gp(vcpu, 0);
  11496. return 1;
  11497. }
  11498. kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
  11499. return kvm_skip_emulated_instruction(vcpu);
  11500. case INVPCID_TYPE_SINGLE_CTXT:
  11501. if (!pcid_enabled && (operand.pcid != 0)) {
  11502. kvm_inject_gp(vcpu, 0);
  11503. return 1;
  11504. }
  11505. kvm_invalidate_pcid(vcpu, operand.pcid);
  11506. return kvm_skip_emulated_instruction(vcpu);
  11507. case INVPCID_TYPE_ALL_NON_GLOBAL:
  11508. /*
  11509. * Currently, KVM doesn't mark global entries in the shadow
  11510. * page tables, so a non-global flush just degenerates to a
  11511. * global flush. If needed, we could optimize this later by
  11512. * keeping track of global entries in shadow page tables.
  11513. */
  11514. fallthrough;
  11515. case INVPCID_TYPE_ALL_INCL_GLOBAL:
  11516. kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
  11517. return kvm_skip_emulated_instruction(vcpu);
  11518. default:
  11519. kvm_inject_gp(vcpu, 0);
  11520. return 1;
  11521. }
  11522. }
  11523. EXPORT_SYMBOL_GPL(kvm_handle_invpcid);
  11524. static int complete_sev_es_emulated_mmio(struct kvm_vcpu *vcpu)
  11525. {
  11526. struct kvm_run *run = vcpu->run;
  11527. struct kvm_mmio_fragment *frag;
  11528. unsigned int len;
  11529. BUG_ON(!vcpu->mmio_needed);
  11530. /* Complete previous fragment */
  11531. frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
  11532. len = min(8u, frag->len);
  11533. if (!vcpu->mmio_is_write)
  11534. memcpy(frag->data, run->mmio.data, len);
  11535. if (frag->len <= 8) {
  11536. /* Switch to the next fragment. */
  11537. frag++;
  11538. vcpu->mmio_cur_fragment++;
  11539. } else {
  11540. /* Go forward to the next mmio piece. */
  11541. frag->data += len;
  11542. frag->gpa += len;
  11543. frag->len -= len;
  11544. }
  11545. if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
  11546. vcpu->mmio_needed = 0;
  11547. // VMG change, at this point, we're always done
  11548. // RIP has already been advanced
  11549. return 1;
  11550. }
  11551. // More MMIO is needed
  11552. run->mmio.phys_addr = frag->gpa;
  11553. run->mmio.len = min(8u, frag->len);
  11554. run->mmio.is_write = vcpu->mmio_is_write;
  11555. if (run->mmio.is_write)
  11556. memcpy(run->mmio.data, frag->data, min(8u, frag->len));
  11557. run->exit_reason = KVM_EXIT_MMIO;
  11558. vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
  11559. return 0;
  11560. }
  11561. int kvm_sev_es_mmio_write(struct kvm_vcpu *vcpu, gpa_t gpa, unsigned int bytes,
  11562. void *data)
  11563. {
  11564. int handled;
  11565. struct kvm_mmio_fragment *frag;
  11566. if (!data)
  11567. return -EINVAL;
  11568. handled = write_emultor.read_write_mmio(vcpu, gpa, bytes, data);
  11569. if (handled == bytes)
  11570. return 1;
  11571. bytes -= handled;
  11572. gpa += handled;
  11573. data += handled;
  11574. /*TODO: Check if need to increment number of frags */
  11575. frag = vcpu->mmio_fragments;
  11576. vcpu->mmio_nr_fragments = 1;
  11577. frag->len = bytes;
  11578. frag->gpa = gpa;
  11579. frag->data = data;
  11580. vcpu->mmio_needed = 1;
  11581. vcpu->mmio_cur_fragment = 0;
  11582. vcpu->run->mmio.phys_addr = gpa;
  11583. vcpu->run->mmio.len = min(8u, frag->len);
  11584. vcpu->run->mmio.is_write = 1;
  11585. memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
  11586. vcpu->run->exit_reason = KVM_EXIT_MMIO;
  11587. vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
  11588. return 0;
  11589. }
  11590. EXPORT_SYMBOL_GPL(kvm_sev_es_mmio_write);
  11591. int kvm_sev_es_mmio_read(struct kvm_vcpu *vcpu, gpa_t gpa, unsigned int bytes,
  11592. void *data)
  11593. {
  11594. int handled;
  11595. struct kvm_mmio_fragment *frag;
  11596. if (!data)
  11597. return -EINVAL;
  11598. handled = read_emultor.read_write_mmio(vcpu, gpa, bytes, data);
  11599. if (handled == bytes)
  11600. return 1;
  11601. bytes -= handled;
  11602. gpa += handled;
  11603. data += handled;
  11604. /*TODO: Check if need to increment number of frags */
  11605. frag = vcpu->mmio_fragments;
  11606. vcpu->mmio_nr_fragments = 1;
  11607. frag->len = bytes;
  11608. frag->gpa = gpa;
  11609. frag->data = data;
  11610. vcpu->mmio_needed = 1;
  11611. vcpu->mmio_cur_fragment = 0;
  11612. vcpu->run->mmio.phys_addr = gpa;
  11613. vcpu->run->mmio.len = min(8u, frag->len);
  11614. vcpu->run->mmio.is_write = 0;
  11615. vcpu->run->exit_reason = KVM_EXIT_MMIO;
  11616. vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
  11617. return 0;
  11618. }
  11619. EXPORT_SYMBOL_GPL(kvm_sev_es_mmio_read);
  11620. static void advance_sev_es_emulated_pio(struct kvm_vcpu *vcpu, unsigned count, int size)
  11621. {
  11622. vcpu->arch.sev_pio_count -= count;
  11623. vcpu->arch.sev_pio_data += count * size;
  11624. }
  11625. static int kvm_sev_es_outs(struct kvm_vcpu *vcpu, unsigned int size,
  11626. unsigned int port);
  11627. static int complete_sev_es_emulated_outs(struct kvm_vcpu *vcpu)
  11628. {
  11629. int size = vcpu->arch.pio.size;
  11630. int port = vcpu->arch.pio.port;
  11631. vcpu->arch.pio.count = 0;
  11632. if (vcpu->arch.sev_pio_count)
  11633. return kvm_sev_es_outs(vcpu, size, port);
  11634. return 1;
  11635. }
  11636. static int kvm_sev_es_outs(struct kvm_vcpu *vcpu, unsigned int size,
  11637. unsigned int port)
  11638. {
  11639. for (;;) {
  11640. unsigned int count =
  11641. min_t(unsigned int, PAGE_SIZE / size, vcpu->arch.sev_pio_count);
  11642. int ret = emulator_pio_out(vcpu, size, port, vcpu->arch.sev_pio_data, count);
  11643. /* memcpy done already by emulator_pio_out. */
  11644. advance_sev_es_emulated_pio(vcpu, count, size);
  11645. if (!ret)
  11646. break;
  11647. /* Emulation done by the kernel. */
  11648. if (!vcpu->arch.sev_pio_count)
  11649. return 1;
  11650. }
  11651. vcpu->arch.complete_userspace_io = complete_sev_es_emulated_outs;
  11652. return 0;
  11653. }
  11654. static int kvm_sev_es_ins(struct kvm_vcpu *vcpu, unsigned int size,
  11655. unsigned int port);
  11656. static int complete_sev_es_emulated_ins(struct kvm_vcpu *vcpu)
  11657. {
  11658. unsigned count = vcpu->arch.pio.count;
  11659. int size = vcpu->arch.pio.size;
  11660. int port = vcpu->arch.pio.port;
  11661. complete_emulator_pio_in(vcpu, vcpu->arch.sev_pio_data);
  11662. advance_sev_es_emulated_pio(vcpu, count, size);
  11663. if (vcpu->arch.sev_pio_count)
  11664. return kvm_sev_es_ins(vcpu, size, port);
  11665. return 1;
  11666. }
  11667. static int kvm_sev_es_ins(struct kvm_vcpu *vcpu, unsigned int size,
  11668. unsigned int port)
  11669. {
  11670. for (;;) {
  11671. unsigned int count =
  11672. min_t(unsigned int, PAGE_SIZE / size, vcpu->arch.sev_pio_count);
  11673. if (!emulator_pio_in(vcpu, size, port, vcpu->arch.sev_pio_data, count))
  11674. break;
  11675. /* Emulation done by the kernel. */
  11676. advance_sev_es_emulated_pio(vcpu, count, size);
  11677. if (!vcpu->arch.sev_pio_count)
  11678. return 1;
  11679. }
  11680. vcpu->arch.complete_userspace_io = complete_sev_es_emulated_ins;
  11681. return 0;
  11682. }
  11683. int kvm_sev_es_string_io(struct kvm_vcpu *vcpu, unsigned int size,
  11684. unsigned int port, void *data, unsigned int count,
  11685. int in)
  11686. {
  11687. vcpu->arch.sev_pio_data = data;
  11688. vcpu->arch.sev_pio_count = count;
  11689. return in ? kvm_sev_es_ins(vcpu, size, port)
  11690. : kvm_sev_es_outs(vcpu, size, port);
  11691. }
  11692. EXPORT_SYMBOL_GPL(kvm_sev_es_string_io);
  11693. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_entry);
  11694. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
  11695. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
  11696. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
  11697. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
  11698. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
  11699. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
  11700. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter);
  11701. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
  11702. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
  11703. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
  11704. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter_failed);
  11705. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
  11706. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
  11707. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
  11708. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
  11709. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window_update);
  11710. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
  11711. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);
  11712. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
  11713. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);
  11714. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_ga_log);
  11715. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_kick_vcpu_slowpath);
  11716. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_doorbell);
  11717. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_apicv_accept_irq);
  11718. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_enter);
  11719. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_exit);
  11720. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_enter);
  11721. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_exit);
  11722. static int __init kvm_x86_init(void)
  11723. {
  11724. kvm_mmu_x86_module_init();
  11725. mitigate_smt_rsb &= boot_cpu_has_bug(X86_BUG_SMT_RSB) && cpu_smt_possible();
  11726. return 0;
  11727. }
  11728. module_init(kvm_x86_init);
  11729. static void __exit kvm_x86_exit(void)
  11730. {
  11731. /*
  11732. * If module_init() is implemented, module_exit() must also be
  11733. * implemented to allow module unload.
  11734. */
  11735. }
  11736. module_exit(kvm_x86_exit);