x86.c 242 KB

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