x86.c 181 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262
  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 <linux/clocksource.h>
  30. #include <linux/interrupt.h>
  31. #include <linux/kvm.h>
  32. #include <linux/fs.h>
  33. #include <linux/vmalloc.h>
  34. #include <linux/module.h>
  35. #include <linux/mman.h>
  36. #include <linux/highmem.h>
  37. #include <linux/iommu.h>
  38. #include <linux/intel-iommu.h>
  39. #include <linux/cpufreq.h>
  40. #include <linux/user-return-notifier.h>
  41. #include <linux/srcu.h>
  42. #include <linux/slab.h>
  43. #include <linux/perf_event.h>
  44. #include <linux/uaccess.h>
  45. #include <linux/hash.h>
  46. #include <linux/pci.h>
  47. #include <linux/timekeeper_internal.h>
  48. #include <linux/pvclock_gtod.h>
  49. #include <trace/events/kvm.h>
  50. #define CREATE_TRACE_POINTS
  51. #include "trace.h"
  52. #include <asm/debugreg.h>
  53. #include <asm/msr.h>
  54. #include <asm/desc.h>
  55. #include <asm/mtrr.h>
  56. #include <asm/mce.h>
  57. #include <asm/i387.h>
  58. #include <asm/fpu-internal.h> /* Ugh! */
  59. #include <asm/xcr.h>
  60. #include <asm/pvclock.h>
  61. #include <asm/div64.h>
  62. #define MAX_IO_MSRS 256
  63. #define KVM_MAX_MCE_BANKS 32
  64. #define KVM_MCE_CAP_SUPPORTED (MCG_CTL_P | MCG_SER_P)
  65. #define emul_to_vcpu(ctxt) \
  66. container_of(ctxt, struct kvm_vcpu, arch.emulate_ctxt)
  67. /* EFER defaults:
  68. * - enable syscall per default because its emulated by KVM
  69. * - enable LME and LMA per default on 64 bit KVM
  70. */
  71. #ifdef CONFIG_X86_64
  72. static
  73. u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
  74. #else
  75. static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
  76. #endif
  77. #define VM_STAT(x) offsetof(struct kvm, stat.x), KVM_STAT_VM
  78. #define VCPU_STAT(x) offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU
  79. static void update_cr8_intercept(struct kvm_vcpu *vcpu);
  80. static void process_nmi(struct kvm_vcpu *vcpu);
  81. struct kvm_x86_ops *kvm_x86_ops;
  82. EXPORT_SYMBOL_GPL(kvm_x86_ops);
  83. static bool ignore_msrs = 0;
  84. module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
  85. bool kvm_has_tsc_control;
  86. EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
  87. u32 kvm_max_guest_tsc_khz;
  88. EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
  89. /* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
  90. static u32 tsc_tolerance_ppm = 250;
  91. module_param(tsc_tolerance_ppm, uint, S_IRUGO | S_IWUSR);
  92. #define KVM_NR_SHARED_MSRS 16
  93. struct kvm_shared_msrs_global {
  94. int nr;
  95. u32 msrs[KVM_NR_SHARED_MSRS];
  96. };
  97. struct kvm_shared_msrs {
  98. struct user_return_notifier urn;
  99. bool registered;
  100. struct kvm_shared_msr_values {
  101. u64 host;
  102. u64 curr;
  103. } values[KVM_NR_SHARED_MSRS];
  104. };
  105. static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
  106. static struct kvm_shared_msrs __percpu *shared_msrs;
  107. struct kvm_stats_debugfs_item debugfs_entries[] = {
  108. { "pf_fixed", VCPU_STAT(pf_fixed) },
  109. { "pf_guest", VCPU_STAT(pf_guest) },
  110. { "tlb_flush", VCPU_STAT(tlb_flush) },
  111. { "invlpg", VCPU_STAT(invlpg) },
  112. { "exits", VCPU_STAT(exits) },
  113. { "io_exits", VCPU_STAT(io_exits) },
  114. { "mmio_exits", VCPU_STAT(mmio_exits) },
  115. { "signal_exits", VCPU_STAT(signal_exits) },
  116. { "irq_window", VCPU_STAT(irq_window_exits) },
  117. { "nmi_window", VCPU_STAT(nmi_window_exits) },
  118. { "halt_exits", VCPU_STAT(halt_exits) },
  119. { "halt_wakeup", VCPU_STAT(halt_wakeup) },
  120. { "hypercalls", VCPU_STAT(hypercalls) },
  121. { "request_irq", VCPU_STAT(request_irq_exits) },
  122. { "irq_exits", VCPU_STAT(irq_exits) },
  123. { "host_state_reload", VCPU_STAT(host_state_reload) },
  124. { "efer_reload", VCPU_STAT(efer_reload) },
  125. { "fpu_reload", VCPU_STAT(fpu_reload) },
  126. { "insn_emulation", VCPU_STAT(insn_emulation) },
  127. { "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
  128. { "irq_injections", VCPU_STAT(irq_injections) },
  129. { "nmi_injections", VCPU_STAT(nmi_injections) },
  130. { "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
  131. { "mmu_pte_write", VM_STAT(mmu_pte_write) },
  132. { "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
  133. { "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
  134. { "mmu_flooded", VM_STAT(mmu_flooded) },
  135. { "mmu_recycled", VM_STAT(mmu_recycled) },
  136. { "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
  137. { "mmu_unsync", VM_STAT(mmu_unsync) },
  138. { "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
  139. { "largepages", VM_STAT(lpages) },
  140. { NULL }
  141. };
  142. u64 __read_mostly host_xcr0;
  143. static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
  144. static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
  145. {
  146. int i;
  147. for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU); i++)
  148. vcpu->arch.apf.gfns[i] = ~0;
  149. }
  150. static void kvm_on_user_return(struct user_return_notifier *urn)
  151. {
  152. unsigned slot;
  153. struct kvm_shared_msrs *locals
  154. = container_of(urn, struct kvm_shared_msrs, urn);
  155. struct kvm_shared_msr_values *values;
  156. for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
  157. values = &locals->values[slot];
  158. if (values->host != values->curr) {
  159. wrmsrl(shared_msrs_global.msrs[slot], values->host);
  160. values->curr = values->host;
  161. }
  162. }
  163. locals->registered = false;
  164. user_return_notifier_unregister(urn);
  165. }
  166. static void shared_msr_update(unsigned slot, u32 msr)
  167. {
  168. u64 value;
  169. unsigned int cpu = smp_processor_id();
  170. struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
  171. /* only read, and nobody should modify it at this time,
  172. * so don't need lock */
  173. if (slot >= shared_msrs_global.nr) {
  174. printk(KERN_ERR "kvm: invalid MSR slot!");
  175. return;
  176. }
  177. rdmsrl_safe(msr, &value);
  178. smsr->values[slot].host = value;
  179. smsr->values[slot].curr = value;
  180. }
  181. void kvm_define_shared_msr(unsigned slot, u32 msr)
  182. {
  183. if (slot >= shared_msrs_global.nr)
  184. shared_msrs_global.nr = slot + 1;
  185. shared_msrs_global.msrs[slot] = msr;
  186. /* we need ensured the shared_msr_global have been updated */
  187. smp_wmb();
  188. }
  189. EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
  190. static void kvm_shared_msr_cpu_online(void)
  191. {
  192. unsigned i;
  193. for (i = 0; i < shared_msrs_global.nr; ++i)
  194. shared_msr_update(i, shared_msrs_global.msrs[i]);
  195. }
  196. void kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
  197. {
  198. unsigned int cpu = smp_processor_id();
  199. struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
  200. if (((value ^ smsr->values[slot].curr) & mask) == 0)
  201. return;
  202. smsr->values[slot].curr = value;
  203. wrmsrl(shared_msrs_global.msrs[slot], value);
  204. if (!smsr->registered) {
  205. smsr->urn.on_user_return = kvm_on_user_return;
  206. user_return_notifier_register(&smsr->urn);
  207. smsr->registered = true;
  208. }
  209. }
  210. EXPORT_SYMBOL_GPL(kvm_set_shared_msr);
  211. static void drop_user_return_notifiers(void *ignore)
  212. {
  213. unsigned int cpu = smp_processor_id();
  214. struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
  215. if (smsr->registered)
  216. kvm_on_user_return(&smsr->urn);
  217. }
  218. u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
  219. {
  220. return vcpu->arch.apic_base;
  221. }
  222. EXPORT_SYMBOL_GPL(kvm_get_apic_base);
  223. void kvm_set_apic_base(struct kvm_vcpu *vcpu, u64 data)
  224. {
  225. /* TODO: reserve bits check */
  226. kvm_lapic_set_base(vcpu, data);
  227. }
  228. EXPORT_SYMBOL_GPL(kvm_set_apic_base);
  229. asmlinkage void kvm_spurious_fault(void)
  230. {
  231. /* Fault while not rebooting. We want the trace. */
  232. BUG();
  233. }
  234. EXPORT_SYMBOL_GPL(kvm_spurious_fault);
  235. #define EXCPT_BENIGN 0
  236. #define EXCPT_CONTRIBUTORY 1
  237. #define EXCPT_PF 2
  238. static int exception_class(int vector)
  239. {
  240. switch (vector) {
  241. case PF_VECTOR:
  242. return EXCPT_PF;
  243. case DE_VECTOR:
  244. case TS_VECTOR:
  245. case NP_VECTOR:
  246. case SS_VECTOR:
  247. case GP_VECTOR:
  248. return EXCPT_CONTRIBUTORY;
  249. default:
  250. break;
  251. }
  252. return EXCPT_BENIGN;
  253. }
  254. static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
  255. unsigned nr, bool has_error, u32 error_code,
  256. bool reinject)
  257. {
  258. u32 prev_nr;
  259. int class1, class2;
  260. kvm_make_request(KVM_REQ_EVENT, vcpu);
  261. if (!vcpu->arch.exception.pending) {
  262. queue:
  263. vcpu->arch.exception.pending = true;
  264. vcpu->arch.exception.has_error_code = has_error;
  265. vcpu->arch.exception.nr = nr;
  266. vcpu->arch.exception.error_code = error_code;
  267. vcpu->arch.exception.reinject = reinject;
  268. return;
  269. }
  270. /* to check exception */
  271. prev_nr = vcpu->arch.exception.nr;
  272. if (prev_nr == DF_VECTOR) {
  273. /* triple fault -> shutdown */
  274. kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
  275. return;
  276. }
  277. class1 = exception_class(prev_nr);
  278. class2 = exception_class(nr);
  279. if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
  280. || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
  281. /* generate double fault per SDM Table 5-5 */
  282. vcpu->arch.exception.pending = true;
  283. vcpu->arch.exception.has_error_code = true;
  284. vcpu->arch.exception.nr = DF_VECTOR;
  285. vcpu->arch.exception.error_code = 0;
  286. } else
  287. /* replace previous exception with a new one in a hope
  288. that instruction re-execution will regenerate lost
  289. exception */
  290. goto queue;
  291. }
  292. void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
  293. {
  294. kvm_multiple_exception(vcpu, nr, false, 0, false);
  295. }
  296. EXPORT_SYMBOL_GPL(kvm_queue_exception);
  297. void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
  298. {
  299. kvm_multiple_exception(vcpu, nr, false, 0, true);
  300. }
  301. EXPORT_SYMBOL_GPL(kvm_requeue_exception);
  302. void kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
  303. {
  304. if (err)
  305. kvm_inject_gp(vcpu, 0);
  306. else
  307. kvm_x86_ops->skip_emulated_instruction(vcpu);
  308. }
  309. EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
  310. void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
  311. {
  312. ++vcpu->stat.pf_guest;
  313. vcpu->arch.cr2 = fault->address;
  314. kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
  315. }
  316. EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
  317. void kvm_propagate_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
  318. {
  319. if (mmu_is_nested(vcpu) && !fault->nested_page_fault)
  320. vcpu->arch.nested_mmu.inject_page_fault(vcpu, fault);
  321. else
  322. vcpu->arch.mmu.inject_page_fault(vcpu, fault);
  323. }
  324. void kvm_inject_nmi(struct kvm_vcpu *vcpu)
  325. {
  326. atomic_inc(&vcpu->arch.nmi_queued);
  327. kvm_make_request(KVM_REQ_NMI, vcpu);
  328. }
  329. EXPORT_SYMBOL_GPL(kvm_inject_nmi);
  330. void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
  331. {
  332. kvm_multiple_exception(vcpu, nr, true, error_code, false);
  333. }
  334. EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
  335. void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
  336. {
  337. kvm_multiple_exception(vcpu, nr, true, error_code, true);
  338. }
  339. EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
  340. /*
  341. * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
  342. * a #GP and return false.
  343. */
  344. bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
  345. {
  346. if (kvm_x86_ops->get_cpl(vcpu) <= required_cpl)
  347. return true;
  348. kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
  349. return false;
  350. }
  351. EXPORT_SYMBOL_GPL(kvm_require_cpl);
  352. /*
  353. * This function will be used to read from the physical memory of the currently
  354. * running guest. The difference to kvm_read_guest_page is that this function
  355. * can read from guest physical or from the guest's guest physical memory.
  356. */
  357. int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
  358. gfn_t ngfn, void *data, int offset, int len,
  359. u32 access)
  360. {
  361. gfn_t real_gfn;
  362. gpa_t ngpa;
  363. ngpa = gfn_to_gpa(ngfn);
  364. real_gfn = mmu->translate_gpa(vcpu, ngpa, access);
  365. if (real_gfn == UNMAPPED_GVA)
  366. return -EFAULT;
  367. real_gfn = gpa_to_gfn(real_gfn);
  368. return kvm_read_guest_page(vcpu->kvm, real_gfn, data, offset, len);
  369. }
  370. EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
  371. int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
  372. void *data, int offset, int len, u32 access)
  373. {
  374. return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
  375. data, offset, len, access);
  376. }
  377. /*
  378. * Load the pae pdptrs. Return true is they are all valid.
  379. */
  380. int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
  381. {
  382. gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
  383. unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
  384. int i;
  385. int ret;
  386. u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
  387. ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
  388. offset * sizeof(u64), sizeof(pdpte),
  389. PFERR_USER_MASK|PFERR_WRITE_MASK);
  390. if (ret < 0) {
  391. ret = 0;
  392. goto out;
  393. }
  394. for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
  395. if (is_present_gpte(pdpte[i]) &&
  396. (pdpte[i] & vcpu->arch.mmu.rsvd_bits_mask[0][2])) {
  397. ret = 0;
  398. goto out;
  399. }
  400. }
  401. ret = 1;
  402. memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
  403. __set_bit(VCPU_EXREG_PDPTR,
  404. (unsigned long *)&vcpu->arch.regs_avail);
  405. __set_bit(VCPU_EXREG_PDPTR,
  406. (unsigned long *)&vcpu->arch.regs_dirty);
  407. out:
  408. return ret;
  409. }
  410. EXPORT_SYMBOL_GPL(load_pdptrs);
  411. static bool pdptrs_changed(struct kvm_vcpu *vcpu)
  412. {
  413. u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
  414. bool changed = true;
  415. int offset;
  416. gfn_t gfn;
  417. int r;
  418. if (is_long_mode(vcpu) || !is_pae(vcpu))
  419. return false;
  420. if (!test_bit(VCPU_EXREG_PDPTR,
  421. (unsigned long *)&vcpu->arch.regs_avail))
  422. return true;
  423. gfn = (kvm_read_cr3(vcpu) & ~31u) >> PAGE_SHIFT;
  424. offset = (kvm_read_cr3(vcpu) & ~31u) & (PAGE_SIZE - 1);
  425. r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
  426. PFERR_USER_MASK | PFERR_WRITE_MASK);
  427. if (r < 0)
  428. goto out;
  429. changed = memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
  430. out:
  431. return changed;
  432. }
  433. int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
  434. {
  435. unsigned long old_cr0 = kvm_read_cr0(vcpu);
  436. unsigned long update_bits = X86_CR0_PG | X86_CR0_WP |
  437. X86_CR0_CD | X86_CR0_NW;
  438. cr0 |= X86_CR0_ET;
  439. #ifdef CONFIG_X86_64
  440. if (cr0 & 0xffffffff00000000UL)
  441. return 1;
  442. #endif
  443. cr0 &= ~CR0_RESERVED_BITS;
  444. if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
  445. return 1;
  446. if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
  447. return 1;
  448. if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
  449. #ifdef CONFIG_X86_64
  450. if ((vcpu->arch.efer & EFER_LME)) {
  451. int cs_db, cs_l;
  452. if (!is_pae(vcpu))
  453. return 1;
  454. kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
  455. if (cs_l)
  456. return 1;
  457. } else
  458. #endif
  459. if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
  460. kvm_read_cr3(vcpu)))
  461. return 1;
  462. }
  463. if (!(cr0 & X86_CR0_PG) && kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
  464. return 1;
  465. kvm_x86_ops->set_cr0(vcpu, cr0);
  466. if ((cr0 ^ old_cr0) & X86_CR0_PG) {
  467. kvm_clear_async_pf_completion_queue(vcpu);
  468. kvm_async_pf_hash_reset(vcpu);
  469. }
  470. if ((cr0 ^ old_cr0) & update_bits)
  471. kvm_mmu_reset_context(vcpu);
  472. return 0;
  473. }
  474. EXPORT_SYMBOL_GPL(kvm_set_cr0);
  475. void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
  476. {
  477. (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
  478. }
  479. EXPORT_SYMBOL_GPL(kvm_lmsw);
  480. int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
  481. {
  482. u64 xcr0;
  483. /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
  484. if (index != XCR_XFEATURE_ENABLED_MASK)
  485. return 1;
  486. xcr0 = xcr;
  487. if (kvm_x86_ops->get_cpl(vcpu) != 0)
  488. return 1;
  489. if (!(xcr0 & XSTATE_FP))
  490. return 1;
  491. if ((xcr0 & XSTATE_YMM) && !(xcr0 & XSTATE_SSE))
  492. return 1;
  493. if (xcr0 & ~host_xcr0)
  494. return 1;
  495. vcpu->arch.xcr0 = xcr0;
  496. vcpu->guest_xcr0_loaded = 0;
  497. return 0;
  498. }
  499. int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
  500. {
  501. if (__kvm_set_xcr(vcpu, index, xcr)) {
  502. kvm_inject_gp(vcpu, 0);
  503. return 1;
  504. }
  505. return 0;
  506. }
  507. EXPORT_SYMBOL_GPL(kvm_set_xcr);
  508. int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
  509. {
  510. unsigned long old_cr4 = kvm_read_cr4(vcpu);
  511. unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE |
  512. X86_CR4_PAE | X86_CR4_SMEP;
  513. if (cr4 & CR4_RESERVED_BITS)
  514. return 1;
  515. if (!guest_cpuid_has_xsave(vcpu) && (cr4 & X86_CR4_OSXSAVE))
  516. return 1;
  517. if (!guest_cpuid_has_smep(vcpu) && (cr4 & X86_CR4_SMEP))
  518. return 1;
  519. if (!guest_cpuid_has_fsgsbase(vcpu) && (cr4 & X86_CR4_RDWRGSFS))
  520. return 1;
  521. if (is_long_mode(vcpu)) {
  522. if (!(cr4 & X86_CR4_PAE))
  523. return 1;
  524. } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
  525. && ((cr4 ^ old_cr4) & pdptr_bits)
  526. && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
  527. kvm_read_cr3(vcpu)))
  528. return 1;
  529. if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
  530. if (!guest_cpuid_has_pcid(vcpu))
  531. return 1;
  532. /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
  533. if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
  534. return 1;
  535. }
  536. if (kvm_x86_ops->set_cr4(vcpu, cr4))
  537. return 1;
  538. if (((cr4 ^ old_cr4) & pdptr_bits) ||
  539. (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
  540. kvm_mmu_reset_context(vcpu);
  541. if ((cr4 ^ old_cr4) & X86_CR4_OSXSAVE)
  542. kvm_update_cpuid(vcpu);
  543. return 0;
  544. }
  545. EXPORT_SYMBOL_GPL(kvm_set_cr4);
  546. int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
  547. {
  548. if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
  549. kvm_mmu_sync_roots(vcpu);
  550. kvm_mmu_flush_tlb(vcpu);
  551. return 0;
  552. }
  553. if (is_long_mode(vcpu)) {
  554. if (kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE)) {
  555. if (cr3 & CR3_PCID_ENABLED_RESERVED_BITS)
  556. return 1;
  557. } else
  558. if (cr3 & CR3_L_MODE_RESERVED_BITS)
  559. return 1;
  560. } else {
  561. if (is_pae(vcpu)) {
  562. if (cr3 & CR3_PAE_RESERVED_BITS)
  563. return 1;
  564. if (is_paging(vcpu) &&
  565. !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
  566. return 1;
  567. }
  568. /*
  569. * We don't check reserved bits in nonpae mode, because
  570. * this isn't enforced, and VMware depends on this.
  571. */
  572. }
  573. /*
  574. * Does the new cr3 value map to physical memory? (Note, we
  575. * catch an invalid cr3 even in real-mode, because it would
  576. * cause trouble later on when we turn on paging anyway.)
  577. *
  578. * A real CPU would silently accept an invalid cr3 and would
  579. * attempt to use it - with largely undefined (and often hard
  580. * to debug) behavior on the guest side.
  581. */
  582. if (unlikely(!gfn_to_memslot(vcpu->kvm, cr3 >> PAGE_SHIFT)))
  583. return 1;
  584. vcpu->arch.cr3 = cr3;
  585. __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
  586. vcpu->arch.mmu.new_cr3(vcpu);
  587. return 0;
  588. }
  589. EXPORT_SYMBOL_GPL(kvm_set_cr3);
  590. int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
  591. {
  592. if (cr8 & CR8_RESERVED_BITS)
  593. return 1;
  594. if (irqchip_in_kernel(vcpu->kvm))
  595. kvm_lapic_set_tpr(vcpu, cr8);
  596. else
  597. vcpu->arch.cr8 = cr8;
  598. return 0;
  599. }
  600. EXPORT_SYMBOL_GPL(kvm_set_cr8);
  601. unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
  602. {
  603. if (irqchip_in_kernel(vcpu->kvm))
  604. return kvm_lapic_get_cr8(vcpu);
  605. else
  606. return vcpu->arch.cr8;
  607. }
  608. EXPORT_SYMBOL_GPL(kvm_get_cr8);
  609. static void kvm_update_dr7(struct kvm_vcpu *vcpu)
  610. {
  611. unsigned long dr7;
  612. if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
  613. dr7 = vcpu->arch.guest_debug_dr7;
  614. else
  615. dr7 = vcpu->arch.dr7;
  616. kvm_x86_ops->set_dr7(vcpu, dr7);
  617. vcpu->arch.switch_db_regs = (dr7 & DR7_BP_EN_MASK);
  618. }
  619. static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
  620. {
  621. switch (dr) {
  622. case 0 ... 3:
  623. vcpu->arch.db[dr] = val;
  624. if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
  625. vcpu->arch.eff_db[dr] = val;
  626. break;
  627. case 4:
  628. if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
  629. return 1; /* #UD */
  630. /* fall through */
  631. case 6:
  632. if (val & 0xffffffff00000000ULL)
  633. return -1; /* #GP */
  634. vcpu->arch.dr6 = (val & DR6_VOLATILE) | DR6_FIXED_1;
  635. break;
  636. case 5:
  637. if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
  638. return 1; /* #UD */
  639. /* fall through */
  640. default: /* 7 */
  641. if (val & 0xffffffff00000000ULL)
  642. return -1; /* #GP */
  643. vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
  644. kvm_update_dr7(vcpu);
  645. break;
  646. }
  647. return 0;
  648. }
  649. int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
  650. {
  651. int res;
  652. res = __kvm_set_dr(vcpu, dr, val);
  653. if (res > 0)
  654. kvm_queue_exception(vcpu, UD_VECTOR);
  655. else if (res < 0)
  656. kvm_inject_gp(vcpu, 0);
  657. return res;
  658. }
  659. EXPORT_SYMBOL_GPL(kvm_set_dr);
  660. static int _kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
  661. {
  662. switch (dr) {
  663. case 0 ... 3:
  664. *val = vcpu->arch.db[dr];
  665. break;
  666. case 4:
  667. if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
  668. return 1;
  669. /* fall through */
  670. case 6:
  671. *val = vcpu->arch.dr6;
  672. break;
  673. case 5:
  674. if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
  675. return 1;
  676. /* fall through */
  677. default: /* 7 */
  678. *val = vcpu->arch.dr7;
  679. break;
  680. }
  681. return 0;
  682. }
  683. int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
  684. {
  685. if (_kvm_get_dr(vcpu, dr, val)) {
  686. kvm_queue_exception(vcpu, UD_VECTOR);
  687. return 1;
  688. }
  689. return 0;
  690. }
  691. EXPORT_SYMBOL_GPL(kvm_get_dr);
  692. bool kvm_rdpmc(struct kvm_vcpu *vcpu)
  693. {
  694. u32 ecx = kvm_register_read(vcpu, VCPU_REGS_RCX);
  695. u64 data;
  696. int err;
  697. err = kvm_pmu_read_pmc(vcpu, ecx, &data);
  698. if (err)
  699. return err;
  700. kvm_register_write(vcpu, VCPU_REGS_RAX, (u32)data);
  701. kvm_register_write(vcpu, VCPU_REGS_RDX, data >> 32);
  702. return err;
  703. }
  704. EXPORT_SYMBOL_GPL(kvm_rdpmc);
  705. /*
  706. * List of msr numbers which we expose to userspace through KVM_GET_MSRS
  707. * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
  708. *
  709. * This list is modified at module load time to reflect the
  710. * capabilities of the host cpu. This capabilities test skips MSRs that are
  711. * kvm-specific. Those are put in the beginning of the list.
  712. */
  713. #define KVM_SAVE_MSRS_BEGIN 10
  714. static u32 msrs_to_save[] = {
  715. MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
  716. MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
  717. HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
  718. HV_X64_MSR_APIC_ASSIST_PAGE, MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
  719. MSR_KVM_PV_EOI_EN,
  720. MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
  721. MSR_STAR,
  722. #ifdef CONFIG_X86_64
  723. MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
  724. #endif
  725. MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA
  726. };
  727. static unsigned num_msrs_to_save;
  728. static const u32 emulated_msrs[] = {
  729. MSR_IA32_TSC_ADJUST,
  730. MSR_IA32_TSCDEADLINE,
  731. MSR_IA32_MISC_ENABLE,
  732. MSR_IA32_MCG_STATUS,
  733. MSR_IA32_MCG_CTL,
  734. };
  735. bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
  736. {
  737. if (efer & efer_reserved_bits)
  738. return false;
  739. if (efer & EFER_FFXSR) {
  740. struct kvm_cpuid_entry2 *feat;
  741. feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
  742. if (!feat || !(feat->edx & bit(X86_FEATURE_FXSR_OPT)))
  743. return false;
  744. }
  745. if (efer & EFER_SVME) {
  746. struct kvm_cpuid_entry2 *feat;
  747. feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
  748. if (!feat || !(feat->ecx & bit(X86_FEATURE_SVM)))
  749. return false;
  750. }
  751. return true;
  752. }
  753. EXPORT_SYMBOL_GPL(kvm_valid_efer);
  754. static int set_efer(struct kvm_vcpu *vcpu, u64 efer)
  755. {
  756. u64 old_efer = vcpu->arch.efer;
  757. if (!kvm_valid_efer(vcpu, efer))
  758. return 1;
  759. if (is_paging(vcpu)
  760. && (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
  761. return 1;
  762. efer &= ~EFER_LMA;
  763. efer |= vcpu->arch.efer & EFER_LMA;
  764. kvm_x86_ops->set_efer(vcpu, efer);
  765. /* Update reserved bits */
  766. if ((efer ^ old_efer) & EFER_NX)
  767. kvm_mmu_reset_context(vcpu);
  768. return 0;
  769. }
  770. void kvm_enable_efer_bits(u64 mask)
  771. {
  772. efer_reserved_bits &= ~mask;
  773. }
  774. EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
  775. /*
  776. * Writes msr value into into the appropriate "register".
  777. * Returns 0 on success, non-0 otherwise.
  778. * Assumes vcpu_load() was already called.
  779. */
  780. int kvm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
  781. {
  782. return kvm_x86_ops->set_msr(vcpu, msr);
  783. }
  784. /*
  785. * Adapt set_msr() to msr_io()'s calling convention
  786. */
  787. static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
  788. {
  789. struct msr_data msr;
  790. msr.data = *data;
  791. msr.index = index;
  792. msr.host_initiated = true;
  793. return kvm_set_msr(vcpu, &msr);
  794. }
  795. #ifdef CONFIG_X86_64
  796. struct pvclock_gtod_data {
  797. seqcount_t seq;
  798. struct { /* extract of a clocksource struct */
  799. int vclock_mode;
  800. cycle_t cycle_last;
  801. cycle_t mask;
  802. u32 mult;
  803. u32 shift;
  804. } clock;
  805. /* open coded 'struct timespec' */
  806. u64 monotonic_time_snsec;
  807. time_t monotonic_time_sec;
  808. };
  809. static struct pvclock_gtod_data pvclock_gtod_data;
  810. static void update_pvclock_gtod(struct timekeeper *tk)
  811. {
  812. struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
  813. write_seqcount_begin(&vdata->seq);
  814. /* copy pvclock gtod data */
  815. vdata->clock.vclock_mode = tk->clock->archdata.vclock_mode;
  816. vdata->clock.cycle_last = tk->clock->cycle_last;
  817. vdata->clock.mask = tk->clock->mask;
  818. vdata->clock.mult = tk->mult;
  819. vdata->clock.shift = tk->shift;
  820. vdata->monotonic_time_sec = tk->xtime_sec
  821. + tk->wall_to_monotonic.tv_sec;
  822. vdata->monotonic_time_snsec = tk->xtime_nsec
  823. + (tk->wall_to_monotonic.tv_nsec
  824. << tk->shift);
  825. while (vdata->monotonic_time_snsec >=
  826. (((u64)NSEC_PER_SEC) << tk->shift)) {
  827. vdata->monotonic_time_snsec -=
  828. ((u64)NSEC_PER_SEC) << tk->shift;
  829. vdata->monotonic_time_sec++;
  830. }
  831. write_seqcount_end(&vdata->seq);
  832. }
  833. #endif
  834. static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
  835. {
  836. int version;
  837. int r;
  838. struct pvclock_wall_clock wc;
  839. struct timespec boot;
  840. if (!wall_clock)
  841. return;
  842. r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
  843. if (r)
  844. return;
  845. if (version & 1)
  846. ++version; /* first time write, random junk */
  847. ++version;
  848. kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
  849. /*
  850. * The guest calculates current wall clock time by adding
  851. * system time (updated by kvm_guest_time_update below) to the
  852. * wall clock specified here. guest system time equals host
  853. * system time for us, thus we must fill in host boot time here.
  854. */
  855. getboottime(&boot);
  856. if (kvm->arch.kvmclock_offset) {
  857. struct timespec ts = ns_to_timespec(kvm->arch.kvmclock_offset);
  858. boot = timespec_sub(boot, ts);
  859. }
  860. wc.sec = boot.tv_sec;
  861. wc.nsec = boot.tv_nsec;
  862. wc.version = version;
  863. kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
  864. version++;
  865. kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
  866. }
  867. static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
  868. {
  869. uint32_t quotient, remainder;
  870. /* Don't try to replace with do_div(), this one calculates
  871. * "(dividend << 32) / divisor" */
  872. __asm__ ( "divl %4"
  873. : "=a" (quotient), "=d" (remainder)
  874. : "0" (0), "1" (dividend), "r" (divisor) );
  875. return quotient;
  876. }
  877. static void kvm_get_time_scale(uint32_t scaled_khz, uint32_t base_khz,
  878. s8 *pshift, u32 *pmultiplier)
  879. {
  880. uint64_t scaled64;
  881. int32_t shift = 0;
  882. uint64_t tps64;
  883. uint32_t tps32;
  884. tps64 = base_khz * 1000LL;
  885. scaled64 = scaled_khz * 1000LL;
  886. while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
  887. tps64 >>= 1;
  888. shift--;
  889. }
  890. tps32 = (uint32_t)tps64;
  891. while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
  892. if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
  893. scaled64 >>= 1;
  894. else
  895. tps32 <<= 1;
  896. shift++;
  897. }
  898. *pshift = shift;
  899. *pmultiplier = div_frac(scaled64, tps32);
  900. pr_debug("%s: base_khz %u => %u, shift %d, mul %u\n",
  901. __func__, base_khz, scaled_khz, shift, *pmultiplier);
  902. }
  903. static inline u64 get_kernel_ns(void)
  904. {
  905. struct timespec ts;
  906. WARN_ON(preemptible());
  907. ktime_get_ts(&ts);
  908. monotonic_to_bootbased(&ts);
  909. return timespec_to_ns(&ts);
  910. }
  911. #ifdef CONFIG_X86_64
  912. static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
  913. #endif
  914. static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
  915. unsigned long max_tsc_khz;
  916. static inline u64 nsec_to_cycles(struct kvm_vcpu *vcpu, u64 nsec)
  917. {
  918. return pvclock_scale_delta(nsec, vcpu->arch.virtual_tsc_mult,
  919. vcpu->arch.virtual_tsc_shift);
  920. }
  921. static u32 adjust_tsc_khz(u32 khz, s32 ppm)
  922. {
  923. u64 v = (u64)khz * (1000000 + ppm);
  924. do_div(v, 1000000);
  925. return v;
  926. }
  927. static void kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 this_tsc_khz)
  928. {
  929. u32 thresh_lo, thresh_hi;
  930. int use_scaling = 0;
  931. /* tsc_khz can be zero if TSC calibration fails */
  932. if (this_tsc_khz == 0)
  933. return;
  934. /* Compute a scale to convert nanoseconds in TSC cycles */
  935. kvm_get_time_scale(this_tsc_khz, NSEC_PER_SEC / 1000,
  936. &vcpu->arch.virtual_tsc_shift,
  937. &vcpu->arch.virtual_tsc_mult);
  938. vcpu->arch.virtual_tsc_khz = this_tsc_khz;
  939. /*
  940. * Compute the variation in TSC rate which is acceptable
  941. * within the range of tolerance and decide if the
  942. * rate being applied is within that bounds of the hardware
  943. * rate. If so, no scaling or compensation need be done.
  944. */
  945. thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
  946. thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
  947. if (this_tsc_khz < thresh_lo || this_tsc_khz > thresh_hi) {
  948. pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", this_tsc_khz, thresh_lo, thresh_hi);
  949. use_scaling = 1;
  950. }
  951. kvm_x86_ops->set_tsc_khz(vcpu, this_tsc_khz, use_scaling);
  952. }
  953. static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
  954. {
  955. u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
  956. vcpu->arch.virtual_tsc_mult,
  957. vcpu->arch.virtual_tsc_shift);
  958. tsc += vcpu->arch.this_tsc_write;
  959. return tsc;
  960. }
  961. void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
  962. {
  963. #ifdef CONFIG_X86_64
  964. bool vcpus_matched;
  965. bool do_request = false;
  966. struct kvm_arch *ka = &vcpu->kvm->arch;
  967. struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
  968. vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
  969. atomic_read(&vcpu->kvm->online_vcpus));
  970. if (vcpus_matched && gtod->clock.vclock_mode == VCLOCK_TSC)
  971. if (!ka->use_master_clock)
  972. do_request = 1;
  973. if (!vcpus_matched && ka->use_master_clock)
  974. do_request = 1;
  975. if (do_request)
  976. kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
  977. trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
  978. atomic_read(&vcpu->kvm->online_vcpus),
  979. ka->use_master_clock, gtod->clock.vclock_mode);
  980. #endif
  981. }
  982. static void update_ia32_tsc_adjust_msr(struct kvm_vcpu *vcpu, s64 offset)
  983. {
  984. u64 curr_offset = kvm_x86_ops->read_tsc_offset(vcpu);
  985. vcpu->arch.ia32_tsc_adjust_msr += offset - curr_offset;
  986. }
  987. void kvm_write_tsc(struct kvm_vcpu *vcpu, struct msr_data *msr)
  988. {
  989. struct kvm *kvm = vcpu->kvm;
  990. u64 offset, ns, elapsed;
  991. unsigned long flags;
  992. s64 usdiff;
  993. bool matched;
  994. u64 data = msr->data;
  995. raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
  996. offset = kvm_x86_ops->compute_tsc_offset(vcpu, data);
  997. ns = get_kernel_ns();
  998. elapsed = ns - kvm->arch.last_tsc_nsec;
  999. if (vcpu->arch.virtual_tsc_khz) {
  1000. /* n.b - signed multiplication and division required */
  1001. usdiff = data - kvm->arch.last_tsc_write;
  1002. #ifdef CONFIG_X86_64
  1003. usdiff = (usdiff * 1000) / vcpu->arch.virtual_tsc_khz;
  1004. #else
  1005. /* do_div() only does unsigned */
  1006. asm("idivl %2; xor %%edx, %%edx"
  1007. : "=A"(usdiff)
  1008. : "A"(usdiff * 1000), "rm"(vcpu->arch.virtual_tsc_khz));
  1009. #endif
  1010. do_div(elapsed, 1000);
  1011. usdiff -= elapsed;
  1012. if (usdiff < 0)
  1013. usdiff = -usdiff;
  1014. } else
  1015. usdiff = USEC_PER_SEC; /* disable TSC match window below */
  1016. /*
  1017. * Special case: TSC write with a small delta (1 second) of virtual
  1018. * cycle time against real time is interpreted as an attempt to
  1019. * synchronize the CPU.
  1020. *
  1021. * For a reliable TSC, we can match TSC offsets, and for an unstable
  1022. * TSC, we add elapsed time in this computation. We could let the
  1023. * compensation code attempt to catch up if we fall behind, but
  1024. * it's better to try to match offsets from the beginning.
  1025. */
  1026. if (usdiff < USEC_PER_SEC &&
  1027. vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
  1028. if (!check_tsc_unstable()) {
  1029. offset = kvm->arch.cur_tsc_offset;
  1030. pr_debug("kvm: matched tsc offset for %llu\n", data);
  1031. } else {
  1032. u64 delta = nsec_to_cycles(vcpu, elapsed);
  1033. data += delta;
  1034. offset = kvm_x86_ops->compute_tsc_offset(vcpu, data);
  1035. pr_debug("kvm: adjusted tsc offset by %llu\n", delta);
  1036. }
  1037. matched = true;
  1038. } else {
  1039. /*
  1040. * We split periods of matched TSC writes into generations.
  1041. * For each generation, we track the original measured
  1042. * nanosecond time, offset, and write, so if TSCs are in
  1043. * sync, we can match exact offset, and if not, we can match
  1044. * exact software computation in compute_guest_tsc()
  1045. *
  1046. * These values are tracked in kvm->arch.cur_xxx variables.
  1047. */
  1048. kvm->arch.cur_tsc_generation++;
  1049. kvm->arch.cur_tsc_nsec = ns;
  1050. kvm->arch.cur_tsc_write = data;
  1051. kvm->arch.cur_tsc_offset = offset;
  1052. matched = false;
  1053. pr_debug("kvm: new tsc generation %u, clock %llu\n",
  1054. kvm->arch.cur_tsc_generation, data);
  1055. }
  1056. /*
  1057. * We also track th most recent recorded KHZ, write and time to
  1058. * allow the matching interval to be extended at each write.
  1059. */
  1060. kvm->arch.last_tsc_nsec = ns;
  1061. kvm->arch.last_tsc_write = data;
  1062. kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
  1063. /* Reset of TSC must disable overshoot protection below */
  1064. vcpu->arch.hv_clock.tsc_timestamp = 0;
  1065. vcpu->arch.last_guest_tsc = data;
  1066. /* Keep track of which generation this VCPU has synchronized to */
  1067. vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
  1068. vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
  1069. vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
  1070. if (guest_cpuid_has_tsc_adjust(vcpu) && !msr->host_initiated)
  1071. update_ia32_tsc_adjust_msr(vcpu, offset);
  1072. kvm_x86_ops->write_tsc_offset(vcpu, offset);
  1073. raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
  1074. spin_lock(&kvm->arch.pvclock_gtod_sync_lock);
  1075. if (matched)
  1076. kvm->arch.nr_vcpus_matched_tsc++;
  1077. else
  1078. kvm->arch.nr_vcpus_matched_tsc = 0;
  1079. kvm_track_tsc_matching(vcpu);
  1080. spin_unlock(&kvm->arch.pvclock_gtod_sync_lock);
  1081. }
  1082. EXPORT_SYMBOL_GPL(kvm_write_tsc);
  1083. #ifdef CONFIG_X86_64
  1084. static cycle_t read_tsc(void)
  1085. {
  1086. cycle_t ret;
  1087. u64 last;
  1088. /*
  1089. * Empirically, a fence (of type that depends on the CPU)
  1090. * before rdtsc is enough to ensure that rdtsc is ordered
  1091. * with respect to loads. The various CPU manuals are unclear
  1092. * as to whether rdtsc can be reordered with later loads,
  1093. * but no one has ever seen it happen.
  1094. */
  1095. rdtsc_barrier();
  1096. ret = (cycle_t)vget_cycles();
  1097. last = pvclock_gtod_data.clock.cycle_last;
  1098. if (likely(ret >= last))
  1099. return ret;
  1100. /*
  1101. * GCC likes to generate cmov here, but this branch is extremely
  1102. * predictable (it's just a funciton of time and the likely is
  1103. * very likely) and there's a data dependence, so force GCC
  1104. * to generate a branch instead. I don't barrier() because
  1105. * we don't actually need a barrier, and if this function
  1106. * ever gets inlined it will generate worse code.
  1107. */
  1108. asm volatile ("");
  1109. return last;
  1110. }
  1111. static inline u64 vgettsc(cycle_t *cycle_now)
  1112. {
  1113. long v;
  1114. struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
  1115. *cycle_now = read_tsc();
  1116. v = (*cycle_now - gtod->clock.cycle_last) & gtod->clock.mask;
  1117. return v * gtod->clock.mult;
  1118. }
  1119. static int do_monotonic(struct timespec *ts, cycle_t *cycle_now)
  1120. {
  1121. unsigned long seq;
  1122. u64 ns;
  1123. int mode;
  1124. struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
  1125. ts->tv_nsec = 0;
  1126. do {
  1127. seq = read_seqcount_begin(&gtod->seq);
  1128. mode = gtod->clock.vclock_mode;
  1129. ts->tv_sec = gtod->monotonic_time_sec;
  1130. ns = gtod->monotonic_time_snsec;
  1131. ns += vgettsc(cycle_now);
  1132. ns >>= gtod->clock.shift;
  1133. } while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
  1134. timespec_add_ns(ts, ns);
  1135. return mode;
  1136. }
  1137. /* returns true if host is using tsc clocksource */
  1138. static bool kvm_get_time_and_clockread(s64 *kernel_ns, cycle_t *cycle_now)
  1139. {
  1140. struct timespec ts;
  1141. /* checked again under seqlock below */
  1142. if (pvclock_gtod_data.clock.vclock_mode != VCLOCK_TSC)
  1143. return false;
  1144. if (do_monotonic(&ts, cycle_now) != VCLOCK_TSC)
  1145. return false;
  1146. monotonic_to_bootbased(&ts);
  1147. *kernel_ns = timespec_to_ns(&ts);
  1148. return true;
  1149. }
  1150. #endif
  1151. /*
  1152. *
  1153. * Assuming a stable TSC across physical CPUS, and a stable TSC
  1154. * across virtual CPUs, the following condition is possible.
  1155. * Each numbered line represents an event visible to both
  1156. * CPUs at the next numbered event.
  1157. *
  1158. * "timespecX" represents host monotonic time. "tscX" represents
  1159. * RDTSC value.
  1160. *
  1161. * VCPU0 on CPU0 | VCPU1 on CPU1
  1162. *
  1163. * 1. read timespec0,tsc0
  1164. * 2. | timespec1 = timespec0 + N
  1165. * | tsc1 = tsc0 + M
  1166. * 3. transition to guest | transition to guest
  1167. * 4. ret0 = timespec0 + (rdtsc - tsc0) |
  1168. * 5. | ret1 = timespec1 + (rdtsc - tsc1)
  1169. * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
  1170. *
  1171. * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
  1172. *
  1173. * - ret0 < ret1
  1174. * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
  1175. * ...
  1176. * - 0 < N - M => M < N
  1177. *
  1178. * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
  1179. * always the case (the difference between two distinct xtime instances
  1180. * might be smaller then the difference between corresponding TSC reads,
  1181. * when updating guest vcpus pvclock areas).
  1182. *
  1183. * To avoid that problem, do not allow visibility of distinct
  1184. * system_timestamp/tsc_timestamp values simultaneously: use a master
  1185. * copy of host monotonic time values. Update that master copy
  1186. * in lockstep.
  1187. *
  1188. * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
  1189. *
  1190. */
  1191. static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
  1192. {
  1193. #ifdef CONFIG_X86_64
  1194. struct kvm_arch *ka = &kvm->arch;
  1195. int vclock_mode;
  1196. bool host_tsc_clocksource, vcpus_matched;
  1197. vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
  1198. atomic_read(&kvm->online_vcpus));
  1199. /*
  1200. * If the host uses TSC clock, then passthrough TSC as stable
  1201. * to the guest.
  1202. */
  1203. host_tsc_clocksource = kvm_get_time_and_clockread(
  1204. &ka->master_kernel_ns,
  1205. &ka->master_cycle_now);
  1206. ka->use_master_clock = host_tsc_clocksource & vcpus_matched;
  1207. if (ka->use_master_clock)
  1208. atomic_set(&kvm_guest_has_master_clock, 1);
  1209. vclock_mode = pvclock_gtod_data.clock.vclock_mode;
  1210. trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
  1211. vcpus_matched);
  1212. #endif
  1213. }
  1214. static int kvm_guest_time_update(struct kvm_vcpu *v)
  1215. {
  1216. unsigned long flags, this_tsc_khz;
  1217. struct kvm_vcpu_arch *vcpu = &v->arch;
  1218. struct kvm_arch *ka = &v->kvm->arch;
  1219. s64 kernel_ns, max_kernel_ns;
  1220. u64 tsc_timestamp, host_tsc;
  1221. struct pvclock_vcpu_time_info guest_hv_clock;
  1222. u8 pvclock_flags;
  1223. bool use_master_clock;
  1224. kernel_ns = 0;
  1225. host_tsc = 0;
  1226. /*
  1227. * If the host uses TSC clock, then passthrough TSC as stable
  1228. * to the guest.
  1229. */
  1230. spin_lock(&ka->pvclock_gtod_sync_lock);
  1231. use_master_clock = ka->use_master_clock;
  1232. if (use_master_clock) {
  1233. host_tsc = ka->master_cycle_now;
  1234. kernel_ns = ka->master_kernel_ns;
  1235. }
  1236. spin_unlock(&ka->pvclock_gtod_sync_lock);
  1237. /* Keep irq disabled to prevent changes to the clock */
  1238. local_irq_save(flags);
  1239. this_tsc_khz = __get_cpu_var(cpu_tsc_khz);
  1240. if (unlikely(this_tsc_khz == 0)) {
  1241. local_irq_restore(flags);
  1242. kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
  1243. return 1;
  1244. }
  1245. if (!use_master_clock) {
  1246. host_tsc = native_read_tsc();
  1247. kernel_ns = get_kernel_ns();
  1248. }
  1249. tsc_timestamp = kvm_x86_ops->read_l1_tsc(v, host_tsc);
  1250. /*
  1251. * We may have to catch up the TSC to match elapsed wall clock
  1252. * time for two reasons, even if kvmclock is used.
  1253. * 1) CPU could have been running below the maximum TSC rate
  1254. * 2) Broken TSC compensation resets the base at each VCPU
  1255. * entry to avoid unknown leaps of TSC even when running
  1256. * again on the same CPU. This may cause apparent elapsed
  1257. * time to disappear, and the guest to stand still or run
  1258. * very slowly.
  1259. */
  1260. if (vcpu->tsc_catchup) {
  1261. u64 tsc = compute_guest_tsc(v, kernel_ns);
  1262. if (tsc > tsc_timestamp) {
  1263. adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
  1264. tsc_timestamp = tsc;
  1265. }
  1266. }
  1267. local_irq_restore(flags);
  1268. if (!vcpu->pv_time_enabled)
  1269. return 0;
  1270. /*
  1271. * Time as measured by the TSC may go backwards when resetting the base
  1272. * tsc_timestamp. The reason for this is that the TSC resolution is
  1273. * higher than the resolution of the other clock scales. Thus, many
  1274. * possible measurments of the TSC correspond to one measurement of any
  1275. * other clock, and so a spread of values is possible. This is not a
  1276. * problem for the computation of the nanosecond clock; with TSC rates
  1277. * around 1GHZ, there can only be a few cycles which correspond to one
  1278. * nanosecond value, and any path through this code will inevitably
  1279. * take longer than that. However, with the kernel_ns value itself,
  1280. * the precision may be much lower, down to HZ granularity. If the
  1281. * first sampling of TSC against kernel_ns ends in the low part of the
  1282. * range, and the second in the high end of the range, we can get:
  1283. *
  1284. * (TSC - offset_low) * S + kns_old > (TSC - offset_high) * S + kns_new
  1285. *
  1286. * As the sampling errors potentially range in the thousands of cycles,
  1287. * it is possible such a time value has already been observed by the
  1288. * guest. To protect against this, we must compute the system time as
  1289. * observed by the guest and ensure the new system time is greater.
  1290. */
  1291. max_kernel_ns = 0;
  1292. if (vcpu->hv_clock.tsc_timestamp) {
  1293. max_kernel_ns = vcpu->last_guest_tsc -
  1294. vcpu->hv_clock.tsc_timestamp;
  1295. max_kernel_ns = pvclock_scale_delta(max_kernel_ns,
  1296. vcpu->hv_clock.tsc_to_system_mul,
  1297. vcpu->hv_clock.tsc_shift);
  1298. max_kernel_ns += vcpu->last_kernel_ns;
  1299. }
  1300. if (unlikely(vcpu->hw_tsc_khz != this_tsc_khz)) {
  1301. kvm_get_time_scale(NSEC_PER_SEC / 1000, this_tsc_khz,
  1302. &vcpu->hv_clock.tsc_shift,
  1303. &vcpu->hv_clock.tsc_to_system_mul);
  1304. vcpu->hw_tsc_khz = this_tsc_khz;
  1305. }
  1306. /* with a master <monotonic time, tsc value> tuple,
  1307. * pvclock clock reads always increase at the (scaled) rate
  1308. * of guest TSC - no need to deal with sampling errors.
  1309. */
  1310. if (!use_master_clock) {
  1311. if (max_kernel_ns > kernel_ns)
  1312. kernel_ns = max_kernel_ns;
  1313. }
  1314. /* With all the info we got, fill in the values */
  1315. vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
  1316. vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
  1317. vcpu->last_kernel_ns = kernel_ns;
  1318. vcpu->last_guest_tsc = tsc_timestamp;
  1319. /*
  1320. * The interface expects us to write an even number signaling that the
  1321. * update is finished. Since the guest won't see the intermediate
  1322. * state, we just increase by 2 at the end.
  1323. */
  1324. vcpu->hv_clock.version += 2;
  1325. if (unlikely(kvm_read_guest_cached(v->kvm, &vcpu->pv_time,
  1326. &guest_hv_clock, sizeof(guest_hv_clock))))
  1327. return 0;
  1328. /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
  1329. pvclock_flags = (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED);
  1330. if (vcpu->pvclock_set_guest_stopped_request) {
  1331. pvclock_flags |= PVCLOCK_GUEST_STOPPED;
  1332. vcpu->pvclock_set_guest_stopped_request = false;
  1333. }
  1334. /* If the host uses TSC clocksource, then it is stable */
  1335. if (use_master_clock)
  1336. pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
  1337. vcpu->hv_clock.flags = pvclock_flags;
  1338. kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
  1339. &vcpu->hv_clock,
  1340. sizeof(vcpu->hv_clock));
  1341. return 0;
  1342. }
  1343. static bool msr_mtrr_valid(unsigned msr)
  1344. {
  1345. switch (msr) {
  1346. case 0x200 ... 0x200 + 2 * KVM_NR_VAR_MTRR - 1:
  1347. case MSR_MTRRfix64K_00000:
  1348. case MSR_MTRRfix16K_80000:
  1349. case MSR_MTRRfix16K_A0000:
  1350. case MSR_MTRRfix4K_C0000:
  1351. case MSR_MTRRfix4K_C8000:
  1352. case MSR_MTRRfix4K_D0000:
  1353. case MSR_MTRRfix4K_D8000:
  1354. case MSR_MTRRfix4K_E0000:
  1355. case MSR_MTRRfix4K_E8000:
  1356. case MSR_MTRRfix4K_F0000:
  1357. case MSR_MTRRfix4K_F8000:
  1358. case MSR_MTRRdefType:
  1359. case MSR_IA32_CR_PAT:
  1360. return true;
  1361. case 0x2f8:
  1362. return true;
  1363. }
  1364. return false;
  1365. }
  1366. static bool valid_pat_type(unsigned t)
  1367. {
  1368. return t < 8 && (1 << t) & 0xf3; /* 0, 1, 4, 5, 6, 7 */
  1369. }
  1370. static bool valid_mtrr_type(unsigned t)
  1371. {
  1372. return t < 8 && (1 << t) & 0x73; /* 0, 1, 4, 5, 6 */
  1373. }
  1374. static bool mtrr_valid(struct kvm_vcpu *vcpu, u32 msr, u64 data)
  1375. {
  1376. int i;
  1377. if (!msr_mtrr_valid(msr))
  1378. return false;
  1379. if (msr == MSR_IA32_CR_PAT) {
  1380. for (i = 0; i < 8; i++)
  1381. if (!valid_pat_type((data >> (i * 8)) & 0xff))
  1382. return false;
  1383. return true;
  1384. } else if (msr == MSR_MTRRdefType) {
  1385. if (data & ~0xcff)
  1386. return false;
  1387. return valid_mtrr_type(data & 0xff);
  1388. } else if (msr >= MSR_MTRRfix64K_00000 && msr <= MSR_MTRRfix4K_F8000) {
  1389. for (i = 0; i < 8 ; i++)
  1390. if (!valid_mtrr_type((data >> (i * 8)) & 0xff))
  1391. return false;
  1392. return true;
  1393. }
  1394. /* variable MTRRs */
  1395. return valid_mtrr_type(data & 0xff);
  1396. }
  1397. static int set_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 data)
  1398. {
  1399. u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
  1400. if (!mtrr_valid(vcpu, msr, data))
  1401. return 1;
  1402. if (msr == MSR_MTRRdefType) {
  1403. vcpu->arch.mtrr_state.def_type = data;
  1404. vcpu->arch.mtrr_state.enabled = (data & 0xc00) >> 10;
  1405. } else if (msr == MSR_MTRRfix64K_00000)
  1406. p[0] = data;
  1407. else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
  1408. p[1 + msr - MSR_MTRRfix16K_80000] = data;
  1409. else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
  1410. p[3 + msr - MSR_MTRRfix4K_C0000] = data;
  1411. else if (msr == MSR_IA32_CR_PAT)
  1412. vcpu->arch.pat = data;
  1413. else { /* Variable MTRRs */
  1414. int idx, is_mtrr_mask;
  1415. u64 *pt;
  1416. idx = (msr - 0x200) / 2;
  1417. is_mtrr_mask = msr - 0x200 - 2 * idx;
  1418. if (!is_mtrr_mask)
  1419. pt =
  1420. (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
  1421. else
  1422. pt =
  1423. (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
  1424. *pt = data;
  1425. }
  1426. kvm_mmu_reset_context(vcpu);
  1427. return 0;
  1428. }
  1429. static int set_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 data)
  1430. {
  1431. u64 mcg_cap = vcpu->arch.mcg_cap;
  1432. unsigned bank_num = mcg_cap & 0xff;
  1433. switch (msr) {
  1434. case MSR_IA32_MCG_STATUS:
  1435. vcpu->arch.mcg_status = data;
  1436. break;
  1437. case MSR_IA32_MCG_CTL:
  1438. if (!(mcg_cap & MCG_CTL_P))
  1439. return 1;
  1440. if (data != 0 && data != ~(u64)0)
  1441. return -1;
  1442. vcpu->arch.mcg_ctl = data;
  1443. break;
  1444. default:
  1445. if (msr >= MSR_IA32_MC0_CTL &&
  1446. msr < MSR_IA32_MC0_CTL + 4 * bank_num) {
  1447. u32 offset = msr - MSR_IA32_MC0_CTL;
  1448. /* only 0 or all 1s can be written to IA32_MCi_CTL
  1449. * some Linux kernels though clear bit 10 in bank 4 to
  1450. * workaround a BIOS/GART TBL issue on AMD K8s, ignore
  1451. * this to avoid an uncatched #GP in the guest
  1452. */
  1453. if ((offset & 0x3) == 0 &&
  1454. data != 0 && (data | (1 << 10)) != ~(u64)0)
  1455. return -1;
  1456. vcpu->arch.mce_banks[offset] = data;
  1457. break;
  1458. }
  1459. return 1;
  1460. }
  1461. return 0;
  1462. }
  1463. static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
  1464. {
  1465. struct kvm *kvm = vcpu->kvm;
  1466. int lm = is_long_mode(vcpu);
  1467. u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
  1468. : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
  1469. u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
  1470. : kvm->arch.xen_hvm_config.blob_size_32;
  1471. u32 page_num = data & ~PAGE_MASK;
  1472. u64 page_addr = data & PAGE_MASK;
  1473. u8 *page;
  1474. int r;
  1475. r = -E2BIG;
  1476. if (page_num >= blob_size)
  1477. goto out;
  1478. r = -ENOMEM;
  1479. page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
  1480. if (IS_ERR(page)) {
  1481. r = PTR_ERR(page);
  1482. goto out;
  1483. }
  1484. if (kvm_write_guest(kvm, page_addr, page, PAGE_SIZE))
  1485. goto out_free;
  1486. r = 0;
  1487. out_free:
  1488. kfree(page);
  1489. out:
  1490. return r;
  1491. }
  1492. static bool kvm_hv_hypercall_enabled(struct kvm *kvm)
  1493. {
  1494. return kvm->arch.hv_hypercall & HV_X64_MSR_HYPERCALL_ENABLE;
  1495. }
  1496. static bool kvm_hv_msr_partition_wide(u32 msr)
  1497. {
  1498. bool r = false;
  1499. switch (msr) {
  1500. case HV_X64_MSR_GUEST_OS_ID:
  1501. case HV_X64_MSR_HYPERCALL:
  1502. r = true;
  1503. break;
  1504. }
  1505. return r;
  1506. }
  1507. static int set_msr_hyperv_pw(struct kvm_vcpu *vcpu, u32 msr, u64 data)
  1508. {
  1509. struct kvm *kvm = vcpu->kvm;
  1510. switch (msr) {
  1511. case HV_X64_MSR_GUEST_OS_ID:
  1512. kvm->arch.hv_guest_os_id = data;
  1513. /* setting guest os id to zero disables hypercall page */
  1514. if (!kvm->arch.hv_guest_os_id)
  1515. kvm->arch.hv_hypercall &= ~HV_X64_MSR_HYPERCALL_ENABLE;
  1516. break;
  1517. case HV_X64_MSR_HYPERCALL: {
  1518. u64 gfn;
  1519. unsigned long addr;
  1520. u8 instructions[4];
  1521. /* if guest os id is not set hypercall should remain disabled */
  1522. if (!kvm->arch.hv_guest_os_id)
  1523. break;
  1524. if (!(data & HV_X64_MSR_HYPERCALL_ENABLE)) {
  1525. kvm->arch.hv_hypercall = data;
  1526. break;
  1527. }
  1528. gfn = data >> HV_X64_MSR_HYPERCALL_PAGE_ADDRESS_SHIFT;
  1529. addr = gfn_to_hva(kvm, gfn);
  1530. if (kvm_is_error_hva(addr))
  1531. return 1;
  1532. kvm_x86_ops->patch_hypercall(vcpu, instructions);
  1533. ((unsigned char *)instructions)[3] = 0xc3; /* ret */
  1534. if (__copy_to_user((void __user *)addr, instructions, 4))
  1535. return 1;
  1536. kvm->arch.hv_hypercall = data;
  1537. break;
  1538. }
  1539. default:
  1540. vcpu_unimpl(vcpu, "HYPER-V unimplemented wrmsr: 0x%x "
  1541. "data 0x%llx\n", msr, data);
  1542. return 1;
  1543. }
  1544. return 0;
  1545. }
  1546. static int set_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 data)
  1547. {
  1548. switch (msr) {
  1549. case HV_X64_MSR_APIC_ASSIST_PAGE: {
  1550. unsigned long addr;
  1551. if (!(data & HV_X64_MSR_APIC_ASSIST_PAGE_ENABLE)) {
  1552. vcpu->arch.hv_vapic = data;
  1553. break;
  1554. }
  1555. addr = gfn_to_hva(vcpu->kvm, data >>
  1556. HV_X64_MSR_APIC_ASSIST_PAGE_ADDRESS_SHIFT);
  1557. if (kvm_is_error_hva(addr))
  1558. return 1;
  1559. if (__clear_user((void __user *)addr, PAGE_SIZE))
  1560. return 1;
  1561. vcpu->arch.hv_vapic = data;
  1562. break;
  1563. }
  1564. case HV_X64_MSR_EOI:
  1565. return kvm_hv_vapic_msr_write(vcpu, APIC_EOI, data);
  1566. case HV_X64_MSR_ICR:
  1567. return kvm_hv_vapic_msr_write(vcpu, APIC_ICR, data);
  1568. case HV_X64_MSR_TPR:
  1569. return kvm_hv_vapic_msr_write(vcpu, APIC_TASKPRI, data);
  1570. default:
  1571. vcpu_unimpl(vcpu, "HYPER-V unimplemented wrmsr: 0x%x "
  1572. "data 0x%llx\n", msr, data);
  1573. return 1;
  1574. }
  1575. return 0;
  1576. }
  1577. static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
  1578. {
  1579. gpa_t gpa = data & ~0x3f;
  1580. /* Bits 2:5 are reserved, Should be zero */
  1581. if (data & 0x3c)
  1582. return 1;
  1583. vcpu->arch.apf.msr_val = data;
  1584. if (!(data & KVM_ASYNC_PF_ENABLED)) {
  1585. kvm_clear_async_pf_completion_queue(vcpu);
  1586. kvm_async_pf_hash_reset(vcpu);
  1587. return 0;
  1588. }
  1589. if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa))
  1590. return 1;
  1591. vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
  1592. kvm_async_pf_wakeup_all(vcpu);
  1593. return 0;
  1594. }
  1595. static void kvmclock_reset(struct kvm_vcpu *vcpu)
  1596. {
  1597. vcpu->arch.pv_time_enabled = false;
  1598. }
  1599. static void accumulate_steal_time(struct kvm_vcpu *vcpu)
  1600. {
  1601. u64 delta;
  1602. if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
  1603. return;
  1604. delta = current->sched_info.run_delay - vcpu->arch.st.last_steal;
  1605. vcpu->arch.st.last_steal = current->sched_info.run_delay;
  1606. vcpu->arch.st.accum_steal = delta;
  1607. }
  1608. static void record_steal_time(struct kvm_vcpu *vcpu)
  1609. {
  1610. if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
  1611. return;
  1612. if (unlikely(kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
  1613. &vcpu->arch.st.steal, sizeof(struct kvm_steal_time))))
  1614. return;
  1615. vcpu->arch.st.steal.steal += vcpu->arch.st.accum_steal;
  1616. vcpu->arch.st.steal.version += 2;
  1617. vcpu->arch.st.accum_steal = 0;
  1618. kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
  1619. &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
  1620. }
  1621. int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
  1622. {
  1623. bool pr = false;
  1624. u32 msr = msr_info->index;
  1625. u64 data = msr_info->data;
  1626. switch (msr) {
  1627. case MSR_AMD64_NB_CFG:
  1628. case MSR_IA32_UCODE_REV:
  1629. case MSR_IA32_UCODE_WRITE:
  1630. case MSR_VM_HSAVE_PA:
  1631. case MSR_AMD64_PATCH_LOADER:
  1632. case MSR_AMD64_BU_CFG2:
  1633. break;
  1634. case MSR_EFER:
  1635. return set_efer(vcpu, data);
  1636. case MSR_K7_HWCR:
  1637. data &= ~(u64)0x40; /* ignore flush filter disable */
  1638. data &= ~(u64)0x100; /* ignore ignne emulation enable */
  1639. data &= ~(u64)0x8; /* ignore TLB cache disable */
  1640. if (data != 0) {
  1641. vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
  1642. data);
  1643. return 1;
  1644. }
  1645. break;
  1646. case MSR_FAM10H_MMIO_CONF_BASE:
  1647. if (data != 0) {
  1648. vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
  1649. "0x%llx\n", data);
  1650. return 1;
  1651. }
  1652. break;
  1653. case MSR_IA32_DEBUGCTLMSR:
  1654. if (!data) {
  1655. /* We support the non-activated case already */
  1656. break;
  1657. } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
  1658. /* Values other than LBR and BTF are vendor-specific,
  1659. thus reserved and should throw a #GP */
  1660. return 1;
  1661. }
  1662. vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
  1663. __func__, data);
  1664. break;
  1665. case 0x200 ... 0x2ff:
  1666. return set_msr_mtrr(vcpu, msr, data);
  1667. case MSR_IA32_APICBASE:
  1668. kvm_set_apic_base(vcpu, data);
  1669. break;
  1670. case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
  1671. return kvm_x2apic_msr_write(vcpu, msr, data);
  1672. case MSR_IA32_TSCDEADLINE:
  1673. kvm_set_lapic_tscdeadline_msr(vcpu, data);
  1674. break;
  1675. case MSR_IA32_TSC_ADJUST:
  1676. if (guest_cpuid_has_tsc_adjust(vcpu)) {
  1677. if (!msr_info->host_initiated) {
  1678. u64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
  1679. kvm_x86_ops->adjust_tsc_offset(vcpu, adj, true);
  1680. }
  1681. vcpu->arch.ia32_tsc_adjust_msr = data;
  1682. }
  1683. break;
  1684. case MSR_IA32_MISC_ENABLE:
  1685. vcpu->arch.ia32_misc_enable_msr = data;
  1686. break;
  1687. case MSR_KVM_WALL_CLOCK_NEW:
  1688. case MSR_KVM_WALL_CLOCK:
  1689. vcpu->kvm->arch.wall_clock = data;
  1690. kvm_write_wall_clock(vcpu->kvm, data);
  1691. break;
  1692. case MSR_KVM_SYSTEM_TIME_NEW:
  1693. case MSR_KVM_SYSTEM_TIME: {
  1694. u64 gpa_offset;
  1695. kvmclock_reset(vcpu);
  1696. vcpu->arch.time = data;
  1697. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  1698. /* we verify if the enable bit is set... */
  1699. if (!(data & 1))
  1700. break;
  1701. gpa_offset = data & ~(PAGE_MASK | 1);
  1702. /* Check that the address is 32-byte aligned. */
  1703. if (gpa_offset & (sizeof(struct pvclock_vcpu_time_info) - 1))
  1704. break;
  1705. if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
  1706. &vcpu->arch.pv_time, data & ~1ULL))
  1707. vcpu->arch.pv_time_enabled = false;
  1708. else
  1709. vcpu->arch.pv_time_enabled = true;
  1710. break;
  1711. }
  1712. case MSR_KVM_ASYNC_PF_EN:
  1713. if (kvm_pv_enable_async_pf(vcpu, data))
  1714. return 1;
  1715. break;
  1716. case MSR_KVM_STEAL_TIME:
  1717. if (unlikely(!sched_info_on()))
  1718. return 1;
  1719. if (data & KVM_STEAL_RESERVED_MASK)
  1720. return 1;
  1721. if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
  1722. data & KVM_STEAL_VALID_BITS))
  1723. return 1;
  1724. vcpu->arch.st.msr_val = data;
  1725. if (!(data & KVM_MSR_ENABLED))
  1726. break;
  1727. vcpu->arch.st.last_steal = current->sched_info.run_delay;
  1728. preempt_disable();
  1729. accumulate_steal_time(vcpu);
  1730. preempt_enable();
  1731. kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
  1732. break;
  1733. case MSR_KVM_PV_EOI_EN:
  1734. if (kvm_lapic_enable_pv_eoi(vcpu, data))
  1735. return 1;
  1736. break;
  1737. case MSR_IA32_MCG_CTL:
  1738. case MSR_IA32_MCG_STATUS:
  1739. case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
  1740. return set_msr_mce(vcpu, msr, data);
  1741. /* Performance counters are not protected by a CPUID bit,
  1742. * so we should check all of them in the generic path for the sake of
  1743. * cross vendor migration.
  1744. * Writing a zero into the event select MSRs disables them,
  1745. * which we perfectly emulate ;-). Any other value should be at least
  1746. * reported, some guests depend on them.
  1747. */
  1748. case MSR_K7_EVNTSEL0:
  1749. case MSR_K7_EVNTSEL1:
  1750. case MSR_K7_EVNTSEL2:
  1751. case MSR_K7_EVNTSEL3:
  1752. if (data != 0)
  1753. vcpu_unimpl(vcpu, "unimplemented perfctr wrmsr: "
  1754. "0x%x data 0x%llx\n", msr, data);
  1755. break;
  1756. /* at least RHEL 4 unconditionally writes to the perfctr registers,
  1757. * so we ignore writes to make it happy.
  1758. */
  1759. case MSR_K7_PERFCTR0:
  1760. case MSR_K7_PERFCTR1:
  1761. case MSR_K7_PERFCTR2:
  1762. case MSR_K7_PERFCTR3:
  1763. vcpu_unimpl(vcpu, "unimplemented perfctr wrmsr: "
  1764. "0x%x data 0x%llx\n", msr, data);
  1765. break;
  1766. case MSR_P6_PERFCTR0:
  1767. case MSR_P6_PERFCTR1:
  1768. pr = true;
  1769. case MSR_P6_EVNTSEL0:
  1770. case MSR_P6_EVNTSEL1:
  1771. if (kvm_pmu_msr(vcpu, msr))
  1772. return kvm_pmu_set_msr(vcpu, msr_info);
  1773. if (pr || data != 0)
  1774. vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
  1775. "0x%x data 0x%llx\n", msr, data);
  1776. break;
  1777. case MSR_K7_CLK_CTL:
  1778. /*
  1779. * Ignore all writes to this no longer documented MSR.
  1780. * Writes are only relevant for old K7 processors,
  1781. * all pre-dating SVM, but a recommended workaround from
  1782. * AMD for these chips. It is possible to specify the
  1783. * affected processor models on the command line, hence
  1784. * the need to ignore the workaround.
  1785. */
  1786. break;
  1787. case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
  1788. if (kvm_hv_msr_partition_wide(msr)) {
  1789. int r;
  1790. mutex_lock(&vcpu->kvm->lock);
  1791. r = set_msr_hyperv_pw(vcpu, msr, data);
  1792. mutex_unlock(&vcpu->kvm->lock);
  1793. return r;
  1794. } else
  1795. return set_msr_hyperv(vcpu, msr, data);
  1796. break;
  1797. case MSR_IA32_BBL_CR_CTL3:
  1798. /* Drop writes to this legacy MSR -- see rdmsr
  1799. * counterpart for further detail.
  1800. */
  1801. vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n", msr, data);
  1802. break;
  1803. case MSR_AMD64_OSVW_ID_LENGTH:
  1804. if (!guest_cpuid_has_osvw(vcpu))
  1805. return 1;
  1806. vcpu->arch.osvw.length = data;
  1807. break;
  1808. case MSR_AMD64_OSVW_STATUS:
  1809. if (!guest_cpuid_has_osvw(vcpu))
  1810. return 1;
  1811. vcpu->arch.osvw.status = data;
  1812. break;
  1813. default:
  1814. if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
  1815. return xen_hvm_config(vcpu, data);
  1816. if (kvm_pmu_msr(vcpu, msr))
  1817. return kvm_pmu_set_msr(vcpu, msr_info);
  1818. if (!ignore_msrs) {
  1819. vcpu_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n",
  1820. msr, data);
  1821. return 1;
  1822. } else {
  1823. vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n",
  1824. msr, data);
  1825. break;
  1826. }
  1827. }
  1828. return 0;
  1829. }
  1830. EXPORT_SYMBOL_GPL(kvm_set_msr_common);
  1831. /*
  1832. * Reads an msr value (of 'msr_index') into 'pdata'.
  1833. * Returns 0 on success, non-0 otherwise.
  1834. * Assumes vcpu_load() was already called.
  1835. */
  1836. int kvm_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
  1837. {
  1838. return kvm_x86_ops->get_msr(vcpu, msr_index, pdata);
  1839. }
  1840. static int get_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
  1841. {
  1842. u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
  1843. if (!msr_mtrr_valid(msr))
  1844. return 1;
  1845. if (msr == MSR_MTRRdefType)
  1846. *pdata = vcpu->arch.mtrr_state.def_type +
  1847. (vcpu->arch.mtrr_state.enabled << 10);
  1848. else if (msr == MSR_MTRRfix64K_00000)
  1849. *pdata = p[0];
  1850. else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
  1851. *pdata = p[1 + msr - MSR_MTRRfix16K_80000];
  1852. else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
  1853. *pdata = p[3 + msr - MSR_MTRRfix4K_C0000];
  1854. else if (msr == MSR_IA32_CR_PAT)
  1855. *pdata = vcpu->arch.pat;
  1856. else { /* Variable MTRRs */
  1857. int idx, is_mtrr_mask;
  1858. u64 *pt;
  1859. idx = (msr - 0x200) / 2;
  1860. is_mtrr_mask = msr - 0x200 - 2 * idx;
  1861. if (!is_mtrr_mask)
  1862. pt =
  1863. (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
  1864. else
  1865. pt =
  1866. (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
  1867. *pdata = *pt;
  1868. }
  1869. return 0;
  1870. }
  1871. static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
  1872. {
  1873. u64 data;
  1874. u64 mcg_cap = vcpu->arch.mcg_cap;
  1875. unsigned bank_num = mcg_cap & 0xff;
  1876. switch (msr) {
  1877. case MSR_IA32_P5_MC_ADDR:
  1878. case MSR_IA32_P5_MC_TYPE:
  1879. data = 0;
  1880. break;
  1881. case MSR_IA32_MCG_CAP:
  1882. data = vcpu->arch.mcg_cap;
  1883. break;
  1884. case MSR_IA32_MCG_CTL:
  1885. if (!(mcg_cap & MCG_CTL_P))
  1886. return 1;
  1887. data = vcpu->arch.mcg_ctl;
  1888. break;
  1889. case MSR_IA32_MCG_STATUS:
  1890. data = vcpu->arch.mcg_status;
  1891. break;
  1892. default:
  1893. if (msr >= MSR_IA32_MC0_CTL &&
  1894. msr < MSR_IA32_MC0_CTL + 4 * bank_num) {
  1895. u32 offset = msr - MSR_IA32_MC0_CTL;
  1896. data = vcpu->arch.mce_banks[offset];
  1897. break;
  1898. }
  1899. return 1;
  1900. }
  1901. *pdata = data;
  1902. return 0;
  1903. }
  1904. static int get_msr_hyperv_pw(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
  1905. {
  1906. u64 data = 0;
  1907. struct kvm *kvm = vcpu->kvm;
  1908. switch (msr) {
  1909. case HV_X64_MSR_GUEST_OS_ID:
  1910. data = kvm->arch.hv_guest_os_id;
  1911. break;
  1912. case HV_X64_MSR_HYPERCALL:
  1913. data = kvm->arch.hv_hypercall;
  1914. break;
  1915. default:
  1916. vcpu_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
  1917. return 1;
  1918. }
  1919. *pdata = data;
  1920. return 0;
  1921. }
  1922. static int get_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
  1923. {
  1924. u64 data = 0;
  1925. switch (msr) {
  1926. case HV_X64_MSR_VP_INDEX: {
  1927. int r;
  1928. struct kvm_vcpu *v;
  1929. kvm_for_each_vcpu(r, v, vcpu->kvm)
  1930. if (v == vcpu)
  1931. data = r;
  1932. break;
  1933. }
  1934. case HV_X64_MSR_EOI:
  1935. return kvm_hv_vapic_msr_read(vcpu, APIC_EOI, pdata);
  1936. case HV_X64_MSR_ICR:
  1937. return kvm_hv_vapic_msr_read(vcpu, APIC_ICR, pdata);
  1938. case HV_X64_MSR_TPR:
  1939. return kvm_hv_vapic_msr_read(vcpu, APIC_TASKPRI, pdata);
  1940. case HV_X64_MSR_APIC_ASSIST_PAGE:
  1941. data = vcpu->arch.hv_vapic;
  1942. break;
  1943. default:
  1944. vcpu_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
  1945. return 1;
  1946. }
  1947. *pdata = data;
  1948. return 0;
  1949. }
  1950. int kvm_get_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
  1951. {
  1952. u64 data;
  1953. switch (msr) {
  1954. case MSR_IA32_PLATFORM_ID:
  1955. case MSR_IA32_EBL_CR_POWERON:
  1956. case MSR_IA32_DEBUGCTLMSR:
  1957. case MSR_IA32_LASTBRANCHFROMIP:
  1958. case MSR_IA32_LASTBRANCHTOIP:
  1959. case MSR_IA32_LASTINTFROMIP:
  1960. case MSR_IA32_LASTINTTOIP:
  1961. case MSR_K8_SYSCFG:
  1962. case MSR_K7_HWCR:
  1963. case MSR_VM_HSAVE_PA:
  1964. case MSR_K7_EVNTSEL0:
  1965. case MSR_K7_PERFCTR0:
  1966. case MSR_K8_INT_PENDING_MSG:
  1967. case MSR_AMD64_NB_CFG:
  1968. case MSR_FAM10H_MMIO_CONF_BASE:
  1969. case MSR_AMD64_BU_CFG2:
  1970. data = 0;
  1971. break;
  1972. case MSR_P6_PERFCTR0:
  1973. case MSR_P6_PERFCTR1:
  1974. case MSR_P6_EVNTSEL0:
  1975. case MSR_P6_EVNTSEL1:
  1976. if (kvm_pmu_msr(vcpu, msr))
  1977. return kvm_pmu_get_msr(vcpu, msr, pdata);
  1978. data = 0;
  1979. break;
  1980. case MSR_IA32_UCODE_REV:
  1981. data = 0x100000000ULL;
  1982. break;
  1983. case MSR_MTRRcap:
  1984. data = 0x500 | KVM_NR_VAR_MTRR;
  1985. break;
  1986. case 0x200 ... 0x2ff:
  1987. return get_msr_mtrr(vcpu, msr, pdata);
  1988. case 0xcd: /* fsb frequency */
  1989. data = 3;
  1990. break;
  1991. /*
  1992. * MSR_EBC_FREQUENCY_ID
  1993. * Conservative value valid for even the basic CPU models.
  1994. * Models 0,1: 000 in bits 23:21 indicating a bus speed of
  1995. * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
  1996. * and 266MHz for model 3, or 4. Set Core Clock
  1997. * Frequency to System Bus Frequency Ratio to 1 (bits
  1998. * 31:24) even though these are only valid for CPU
  1999. * models > 2, however guests may end up dividing or
  2000. * multiplying by zero otherwise.
  2001. */
  2002. case MSR_EBC_FREQUENCY_ID:
  2003. data = 1 << 24;
  2004. break;
  2005. case MSR_IA32_APICBASE:
  2006. data = kvm_get_apic_base(vcpu);
  2007. break;
  2008. case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
  2009. return kvm_x2apic_msr_read(vcpu, msr, pdata);
  2010. break;
  2011. case MSR_IA32_TSCDEADLINE:
  2012. data = kvm_get_lapic_tscdeadline_msr(vcpu);
  2013. break;
  2014. case MSR_IA32_TSC_ADJUST:
  2015. data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
  2016. break;
  2017. case MSR_IA32_MISC_ENABLE:
  2018. data = vcpu->arch.ia32_misc_enable_msr;
  2019. break;
  2020. case MSR_IA32_PERF_STATUS:
  2021. /* TSC increment by tick */
  2022. data = 1000ULL;
  2023. /* CPU multiplier */
  2024. data |= (((uint64_t)4ULL) << 40);
  2025. break;
  2026. case MSR_EFER:
  2027. data = vcpu->arch.efer;
  2028. break;
  2029. case MSR_KVM_WALL_CLOCK:
  2030. case MSR_KVM_WALL_CLOCK_NEW:
  2031. data = vcpu->kvm->arch.wall_clock;
  2032. break;
  2033. case MSR_KVM_SYSTEM_TIME:
  2034. case MSR_KVM_SYSTEM_TIME_NEW:
  2035. data = vcpu->arch.time;
  2036. break;
  2037. case MSR_KVM_ASYNC_PF_EN:
  2038. data = vcpu->arch.apf.msr_val;
  2039. break;
  2040. case MSR_KVM_STEAL_TIME:
  2041. data = vcpu->arch.st.msr_val;
  2042. break;
  2043. case MSR_KVM_PV_EOI_EN:
  2044. data = vcpu->arch.pv_eoi.msr_val;
  2045. break;
  2046. case MSR_IA32_P5_MC_ADDR:
  2047. case MSR_IA32_P5_MC_TYPE:
  2048. case MSR_IA32_MCG_CAP:
  2049. case MSR_IA32_MCG_CTL:
  2050. case MSR_IA32_MCG_STATUS:
  2051. case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
  2052. return get_msr_mce(vcpu, msr, pdata);
  2053. case MSR_K7_CLK_CTL:
  2054. /*
  2055. * Provide expected ramp-up count for K7. All other
  2056. * are set to zero, indicating minimum divisors for
  2057. * every field.
  2058. *
  2059. * This prevents guest kernels on AMD host with CPU
  2060. * type 6, model 8 and higher from exploding due to
  2061. * the rdmsr failing.
  2062. */
  2063. data = 0x20000000;
  2064. break;
  2065. case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
  2066. if (kvm_hv_msr_partition_wide(msr)) {
  2067. int r;
  2068. mutex_lock(&vcpu->kvm->lock);
  2069. r = get_msr_hyperv_pw(vcpu, msr, pdata);
  2070. mutex_unlock(&vcpu->kvm->lock);
  2071. return r;
  2072. } else
  2073. return get_msr_hyperv(vcpu, msr, pdata);
  2074. break;
  2075. case MSR_IA32_BBL_CR_CTL3:
  2076. /* This legacy MSR exists but isn't fully documented in current
  2077. * silicon. It is however accessed by winxp in very narrow
  2078. * scenarios where it sets bit #19, itself documented as
  2079. * a "reserved" bit. Best effort attempt to source coherent
  2080. * read data here should the balance of the register be
  2081. * interpreted by the guest:
  2082. *
  2083. * L2 cache control register 3: 64GB range, 256KB size,
  2084. * enabled, latency 0x1, configured
  2085. */
  2086. data = 0xbe702111;
  2087. break;
  2088. case MSR_AMD64_OSVW_ID_LENGTH:
  2089. if (!guest_cpuid_has_osvw(vcpu))
  2090. return 1;
  2091. data = vcpu->arch.osvw.length;
  2092. break;
  2093. case MSR_AMD64_OSVW_STATUS:
  2094. if (!guest_cpuid_has_osvw(vcpu))
  2095. return 1;
  2096. data = vcpu->arch.osvw.status;
  2097. break;
  2098. default:
  2099. if (kvm_pmu_msr(vcpu, msr))
  2100. return kvm_pmu_get_msr(vcpu, msr, pdata);
  2101. if (!ignore_msrs) {
  2102. vcpu_unimpl(vcpu, "unhandled rdmsr: 0x%x\n", msr);
  2103. return 1;
  2104. } else {
  2105. vcpu_unimpl(vcpu, "ignored rdmsr: 0x%x\n", msr);
  2106. data = 0;
  2107. }
  2108. break;
  2109. }
  2110. *pdata = data;
  2111. return 0;
  2112. }
  2113. EXPORT_SYMBOL_GPL(kvm_get_msr_common);
  2114. /*
  2115. * Read or write a bunch of msrs. All parameters are kernel addresses.
  2116. *
  2117. * @return number of msrs set successfully.
  2118. */
  2119. static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
  2120. struct kvm_msr_entry *entries,
  2121. int (*do_msr)(struct kvm_vcpu *vcpu,
  2122. unsigned index, u64 *data))
  2123. {
  2124. int i, idx;
  2125. idx = srcu_read_lock(&vcpu->kvm->srcu);
  2126. for (i = 0; i < msrs->nmsrs; ++i)
  2127. if (do_msr(vcpu, entries[i].index, &entries[i].data))
  2128. break;
  2129. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  2130. return i;
  2131. }
  2132. /*
  2133. * Read or write a bunch of msrs. Parameters are user addresses.
  2134. *
  2135. * @return number of msrs set successfully.
  2136. */
  2137. static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
  2138. int (*do_msr)(struct kvm_vcpu *vcpu,
  2139. unsigned index, u64 *data),
  2140. int writeback)
  2141. {
  2142. struct kvm_msrs msrs;
  2143. struct kvm_msr_entry *entries;
  2144. int r, n;
  2145. unsigned size;
  2146. r = -EFAULT;
  2147. if (copy_from_user(&msrs, user_msrs, sizeof msrs))
  2148. goto out;
  2149. r = -E2BIG;
  2150. if (msrs.nmsrs >= MAX_IO_MSRS)
  2151. goto out;
  2152. size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
  2153. entries = memdup_user(user_msrs->entries, size);
  2154. if (IS_ERR(entries)) {
  2155. r = PTR_ERR(entries);
  2156. goto out;
  2157. }
  2158. r = n = __msr_io(vcpu, &msrs, entries, do_msr);
  2159. if (r < 0)
  2160. goto out_free;
  2161. r = -EFAULT;
  2162. if (writeback && copy_to_user(user_msrs->entries, entries, size))
  2163. goto out_free;
  2164. r = n;
  2165. out_free:
  2166. kfree(entries);
  2167. out:
  2168. return r;
  2169. }
  2170. int kvm_dev_ioctl_check_extension(long ext)
  2171. {
  2172. int r;
  2173. switch (ext) {
  2174. case KVM_CAP_IRQCHIP:
  2175. case KVM_CAP_HLT:
  2176. case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
  2177. case KVM_CAP_SET_TSS_ADDR:
  2178. case KVM_CAP_EXT_CPUID:
  2179. case KVM_CAP_CLOCKSOURCE:
  2180. case KVM_CAP_PIT:
  2181. case KVM_CAP_NOP_IO_DELAY:
  2182. case KVM_CAP_MP_STATE:
  2183. case KVM_CAP_SYNC_MMU:
  2184. case KVM_CAP_USER_NMI:
  2185. case KVM_CAP_REINJECT_CONTROL:
  2186. case KVM_CAP_IRQ_INJECT_STATUS:
  2187. case KVM_CAP_ASSIGN_DEV_IRQ:
  2188. case KVM_CAP_IRQFD:
  2189. case KVM_CAP_IOEVENTFD:
  2190. case KVM_CAP_PIT2:
  2191. case KVM_CAP_PIT_STATE2:
  2192. case KVM_CAP_SET_IDENTITY_MAP_ADDR:
  2193. case KVM_CAP_XEN_HVM:
  2194. case KVM_CAP_ADJUST_CLOCK:
  2195. case KVM_CAP_VCPU_EVENTS:
  2196. case KVM_CAP_HYPERV:
  2197. case KVM_CAP_HYPERV_VAPIC:
  2198. case KVM_CAP_HYPERV_SPIN:
  2199. case KVM_CAP_PCI_SEGMENT:
  2200. case KVM_CAP_DEBUGREGS:
  2201. case KVM_CAP_X86_ROBUST_SINGLESTEP:
  2202. case KVM_CAP_XSAVE:
  2203. case KVM_CAP_ASYNC_PF:
  2204. case KVM_CAP_GET_TSC_KHZ:
  2205. case KVM_CAP_PCI_2_3:
  2206. case KVM_CAP_KVMCLOCK_CTRL:
  2207. case KVM_CAP_READONLY_MEM:
  2208. r = 1;
  2209. break;
  2210. case KVM_CAP_COALESCED_MMIO:
  2211. r = KVM_COALESCED_MMIO_PAGE_OFFSET;
  2212. break;
  2213. case KVM_CAP_VAPIC:
  2214. r = !kvm_x86_ops->cpu_has_accelerated_tpr();
  2215. break;
  2216. case KVM_CAP_NR_VCPUS:
  2217. r = KVM_SOFT_MAX_VCPUS;
  2218. break;
  2219. case KVM_CAP_MAX_VCPUS:
  2220. r = KVM_MAX_VCPUS;
  2221. break;
  2222. case KVM_CAP_NR_MEMSLOTS:
  2223. r = KVM_USER_MEM_SLOTS;
  2224. break;
  2225. case KVM_CAP_PV_MMU: /* obsolete */
  2226. r = 0;
  2227. break;
  2228. case KVM_CAP_IOMMU:
  2229. r = iommu_present(&pci_bus_type);
  2230. break;
  2231. case KVM_CAP_MCE:
  2232. r = KVM_MAX_MCE_BANKS;
  2233. break;
  2234. case KVM_CAP_XCRS:
  2235. r = cpu_has_xsave;
  2236. break;
  2237. case KVM_CAP_TSC_CONTROL:
  2238. r = kvm_has_tsc_control;
  2239. break;
  2240. case KVM_CAP_TSC_DEADLINE_TIMER:
  2241. r = boot_cpu_has(X86_FEATURE_TSC_DEADLINE_TIMER);
  2242. break;
  2243. default:
  2244. r = 0;
  2245. break;
  2246. }
  2247. return r;
  2248. }
  2249. long kvm_arch_dev_ioctl(struct file *filp,
  2250. unsigned int ioctl, unsigned long arg)
  2251. {
  2252. void __user *argp = (void __user *)arg;
  2253. long r;
  2254. switch (ioctl) {
  2255. case KVM_GET_MSR_INDEX_LIST: {
  2256. struct kvm_msr_list __user *user_msr_list = argp;
  2257. struct kvm_msr_list msr_list;
  2258. unsigned n;
  2259. r = -EFAULT;
  2260. if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
  2261. goto out;
  2262. n = msr_list.nmsrs;
  2263. msr_list.nmsrs = num_msrs_to_save + ARRAY_SIZE(emulated_msrs);
  2264. if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
  2265. goto out;
  2266. r = -E2BIG;
  2267. if (n < msr_list.nmsrs)
  2268. goto out;
  2269. r = -EFAULT;
  2270. if (copy_to_user(user_msr_list->indices, &msrs_to_save,
  2271. num_msrs_to_save * sizeof(u32)))
  2272. goto out;
  2273. if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
  2274. &emulated_msrs,
  2275. ARRAY_SIZE(emulated_msrs) * sizeof(u32)))
  2276. goto out;
  2277. r = 0;
  2278. break;
  2279. }
  2280. case KVM_GET_SUPPORTED_CPUID: {
  2281. struct kvm_cpuid2 __user *cpuid_arg = argp;
  2282. struct kvm_cpuid2 cpuid;
  2283. r = -EFAULT;
  2284. if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
  2285. goto out;
  2286. r = kvm_dev_ioctl_get_supported_cpuid(&cpuid,
  2287. cpuid_arg->entries);
  2288. if (r)
  2289. goto out;
  2290. r = -EFAULT;
  2291. if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
  2292. goto out;
  2293. r = 0;
  2294. break;
  2295. }
  2296. case KVM_X86_GET_MCE_CAP_SUPPORTED: {
  2297. u64 mce_cap;
  2298. mce_cap = KVM_MCE_CAP_SUPPORTED;
  2299. r = -EFAULT;
  2300. if (copy_to_user(argp, &mce_cap, sizeof mce_cap))
  2301. goto out;
  2302. r = 0;
  2303. break;
  2304. }
  2305. default:
  2306. r = -EINVAL;
  2307. }
  2308. out:
  2309. return r;
  2310. }
  2311. static void wbinvd_ipi(void *garbage)
  2312. {
  2313. wbinvd();
  2314. }
  2315. static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
  2316. {
  2317. return vcpu->kvm->arch.iommu_domain &&
  2318. !(vcpu->kvm->arch.iommu_flags & KVM_IOMMU_CACHE_COHERENCY);
  2319. }
  2320. void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
  2321. {
  2322. /* Address WBINVD may be executed by guest */
  2323. if (need_emulate_wbinvd(vcpu)) {
  2324. if (kvm_x86_ops->has_wbinvd_exit())
  2325. cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
  2326. else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
  2327. smp_call_function_single(vcpu->cpu,
  2328. wbinvd_ipi, NULL, 1);
  2329. }
  2330. kvm_x86_ops->vcpu_load(vcpu, cpu);
  2331. /* Apply any externally detected TSC adjustments (due to suspend) */
  2332. if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
  2333. adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
  2334. vcpu->arch.tsc_offset_adjustment = 0;
  2335. set_bit(KVM_REQ_CLOCK_UPDATE, &vcpu->requests);
  2336. }
  2337. if (unlikely(vcpu->cpu != cpu) || check_tsc_unstable()) {
  2338. s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
  2339. native_read_tsc() - vcpu->arch.last_host_tsc;
  2340. if (tsc_delta < 0)
  2341. mark_tsc_unstable("KVM discovered backwards TSC");
  2342. if (check_tsc_unstable()) {
  2343. u64 offset = kvm_x86_ops->compute_tsc_offset(vcpu,
  2344. vcpu->arch.last_guest_tsc);
  2345. kvm_x86_ops->write_tsc_offset(vcpu, offset);
  2346. vcpu->arch.tsc_catchup = 1;
  2347. }
  2348. /*
  2349. * On a host with synchronized TSC, there is no need to update
  2350. * kvmclock on vcpu->cpu migration
  2351. */
  2352. if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
  2353. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  2354. if (vcpu->cpu != cpu)
  2355. kvm_migrate_timers(vcpu);
  2356. vcpu->cpu = cpu;
  2357. }
  2358. accumulate_steal_time(vcpu);
  2359. kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
  2360. }
  2361. void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
  2362. {
  2363. kvm_x86_ops->vcpu_put(vcpu);
  2364. kvm_put_guest_fpu(vcpu);
  2365. vcpu->arch.last_host_tsc = native_read_tsc();
  2366. }
  2367. static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
  2368. struct kvm_lapic_state *s)
  2369. {
  2370. kvm_x86_ops->sync_pir_to_irr(vcpu);
  2371. memcpy(s->regs, vcpu->arch.apic->regs, sizeof *s);
  2372. return 0;
  2373. }
  2374. static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
  2375. struct kvm_lapic_state *s)
  2376. {
  2377. kvm_apic_post_state_restore(vcpu, s);
  2378. update_cr8_intercept(vcpu);
  2379. return 0;
  2380. }
  2381. static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
  2382. struct kvm_interrupt *irq)
  2383. {
  2384. if (irq->irq >= KVM_NR_INTERRUPTS)
  2385. return -EINVAL;
  2386. if (irqchip_in_kernel(vcpu->kvm))
  2387. return -ENXIO;
  2388. kvm_queue_interrupt(vcpu, irq->irq, false);
  2389. kvm_make_request(KVM_REQ_EVENT, vcpu);
  2390. return 0;
  2391. }
  2392. static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
  2393. {
  2394. kvm_inject_nmi(vcpu);
  2395. return 0;
  2396. }
  2397. static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
  2398. struct kvm_tpr_access_ctl *tac)
  2399. {
  2400. if (tac->flags)
  2401. return -EINVAL;
  2402. vcpu->arch.tpr_access_reporting = !!tac->enabled;
  2403. return 0;
  2404. }
  2405. static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
  2406. u64 mcg_cap)
  2407. {
  2408. int r;
  2409. unsigned bank_num = mcg_cap & 0xff, bank;
  2410. r = -EINVAL;
  2411. if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
  2412. goto out;
  2413. if (mcg_cap & ~(KVM_MCE_CAP_SUPPORTED | 0xff | 0xff0000))
  2414. goto out;
  2415. r = 0;
  2416. vcpu->arch.mcg_cap = mcg_cap;
  2417. /* Init IA32_MCG_CTL to all 1s */
  2418. if (mcg_cap & MCG_CTL_P)
  2419. vcpu->arch.mcg_ctl = ~(u64)0;
  2420. /* Init IA32_MCi_CTL to all 1s */
  2421. for (bank = 0; bank < bank_num; bank++)
  2422. vcpu->arch.mce_banks[bank*4] = ~(u64)0;
  2423. out:
  2424. return r;
  2425. }
  2426. static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
  2427. struct kvm_x86_mce *mce)
  2428. {
  2429. u64 mcg_cap = vcpu->arch.mcg_cap;
  2430. unsigned bank_num = mcg_cap & 0xff;
  2431. u64 *banks = vcpu->arch.mce_banks;
  2432. if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
  2433. return -EINVAL;
  2434. /*
  2435. * if IA32_MCG_CTL is not all 1s, the uncorrected error
  2436. * reporting is disabled
  2437. */
  2438. if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
  2439. vcpu->arch.mcg_ctl != ~(u64)0)
  2440. return 0;
  2441. banks += 4 * mce->bank;
  2442. /*
  2443. * if IA32_MCi_CTL is not all 1s, the uncorrected error
  2444. * reporting is disabled for the bank
  2445. */
  2446. if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
  2447. return 0;
  2448. if (mce->status & MCI_STATUS_UC) {
  2449. if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
  2450. !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
  2451. kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
  2452. return 0;
  2453. }
  2454. if (banks[1] & MCI_STATUS_VAL)
  2455. mce->status |= MCI_STATUS_OVER;
  2456. banks[2] = mce->addr;
  2457. banks[3] = mce->misc;
  2458. vcpu->arch.mcg_status = mce->mcg_status;
  2459. banks[1] = mce->status;
  2460. kvm_queue_exception(vcpu, MC_VECTOR);
  2461. } else if (!(banks[1] & MCI_STATUS_VAL)
  2462. || !(banks[1] & MCI_STATUS_UC)) {
  2463. if (banks[1] & MCI_STATUS_VAL)
  2464. mce->status |= MCI_STATUS_OVER;
  2465. banks[2] = mce->addr;
  2466. banks[3] = mce->misc;
  2467. banks[1] = mce->status;
  2468. } else
  2469. banks[1] |= MCI_STATUS_OVER;
  2470. return 0;
  2471. }
  2472. static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
  2473. struct kvm_vcpu_events *events)
  2474. {
  2475. process_nmi(vcpu);
  2476. events->exception.injected =
  2477. vcpu->arch.exception.pending &&
  2478. !kvm_exception_is_soft(vcpu->arch.exception.nr);
  2479. events->exception.nr = vcpu->arch.exception.nr;
  2480. events->exception.has_error_code = vcpu->arch.exception.has_error_code;
  2481. events->exception.pad = 0;
  2482. events->exception.error_code = vcpu->arch.exception.error_code;
  2483. events->interrupt.injected =
  2484. vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft;
  2485. events->interrupt.nr = vcpu->arch.interrupt.nr;
  2486. events->interrupt.soft = 0;
  2487. events->interrupt.shadow =
  2488. kvm_x86_ops->get_interrupt_shadow(vcpu,
  2489. KVM_X86_SHADOW_INT_MOV_SS | KVM_X86_SHADOW_INT_STI);
  2490. events->nmi.injected = vcpu->arch.nmi_injected;
  2491. events->nmi.pending = vcpu->arch.nmi_pending != 0;
  2492. events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
  2493. events->nmi.pad = 0;
  2494. events->sipi_vector = 0; /* never valid when reporting to user space */
  2495. events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
  2496. | KVM_VCPUEVENT_VALID_SHADOW);
  2497. memset(&events->reserved, 0, sizeof(events->reserved));
  2498. }
  2499. static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
  2500. struct kvm_vcpu_events *events)
  2501. {
  2502. if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
  2503. | KVM_VCPUEVENT_VALID_SIPI_VECTOR
  2504. | KVM_VCPUEVENT_VALID_SHADOW))
  2505. return -EINVAL;
  2506. process_nmi(vcpu);
  2507. vcpu->arch.exception.pending = events->exception.injected;
  2508. vcpu->arch.exception.nr = events->exception.nr;
  2509. vcpu->arch.exception.has_error_code = events->exception.has_error_code;
  2510. vcpu->arch.exception.error_code = events->exception.error_code;
  2511. vcpu->arch.interrupt.pending = events->interrupt.injected;
  2512. vcpu->arch.interrupt.nr = events->interrupt.nr;
  2513. vcpu->arch.interrupt.soft = events->interrupt.soft;
  2514. if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
  2515. kvm_x86_ops->set_interrupt_shadow(vcpu,
  2516. events->interrupt.shadow);
  2517. vcpu->arch.nmi_injected = events->nmi.injected;
  2518. if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
  2519. vcpu->arch.nmi_pending = events->nmi.pending;
  2520. kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
  2521. if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
  2522. kvm_vcpu_has_lapic(vcpu))
  2523. vcpu->arch.apic->sipi_vector = events->sipi_vector;
  2524. kvm_make_request(KVM_REQ_EVENT, vcpu);
  2525. return 0;
  2526. }
  2527. static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
  2528. struct kvm_debugregs *dbgregs)
  2529. {
  2530. memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
  2531. dbgregs->dr6 = vcpu->arch.dr6;
  2532. dbgregs->dr7 = vcpu->arch.dr7;
  2533. dbgregs->flags = 0;
  2534. memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
  2535. }
  2536. static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
  2537. struct kvm_debugregs *dbgregs)
  2538. {
  2539. if (dbgregs->flags)
  2540. return -EINVAL;
  2541. memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
  2542. vcpu->arch.dr6 = dbgregs->dr6;
  2543. vcpu->arch.dr7 = dbgregs->dr7;
  2544. return 0;
  2545. }
  2546. static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
  2547. struct kvm_xsave *guest_xsave)
  2548. {
  2549. if (cpu_has_xsave)
  2550. memcpy(guest_xsave->region,
  2551. &vcpu->arch.guest_fpu.state->xsave,
  2552. xstate_size);
  2553. else {
  2554. memcpy(guest_xsave->region,
  2555. &vcpu->arch.guest_fpu.state->fxsave,
  2556. sizeof(struct i387_fxsave_struct));
  2557. *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
  2558. XSTATE_FPSSE;
  2559. }
  2560. }
  2561. static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
  2562. struct kvm_xsave *guest_xsave)
  2563. {
  2564. u64 xstate_bv =
  2565. *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
  2566. if (cpu_has_xsave)
  2567. memcpy(&vcpu->arch.guest_fpu.state->xsave,
  2568. guest_xsave->region, xstate_size);
  2569. else {
  2570. if (xstate_bv & ~XSTATE_FPSSE)
  2571. return -EINVAL;
  2572. memcpy(&vcpu->arch.guest_fpu.state->fxsave,
  2573. guest_xsave->region, sizeof(struct i387_fxsave_struct));
  2574. }
  2575. return 0;
  2576. }
  2577. static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
  2578. struct kvm_xcrs *guest_xcrs)
  2579. {
  2580. if (!cpu_has_xsave) {
  2581. guest_xcrs->nr_xcrs = 0;
  2582. return;
  2583. }
  2584. guest_xcrs->nr_xcrs = 1;
  2585. guest_xcrs->flags = 0;
  2586. guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
  2587. guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
  2588. }
  2589. static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
  2590. struct kvm_xcrs *guest_xcrs)
  2591. {
  2592. int i, r = 0;
  2593. if (!cpu_has_xsave)
  2594. return -EINVAL;
  2595. if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
  2596. return -EINVAL;
  2597. for (i = 0; i < guest_xcrs->nr_xcrs; i++)
  2598. /* Only support XCR0 currently */
  2599. if (guest_xcrs->xcrs[0].xcr == XCR_XFEATURE_ENABLED_MASK) {
  2600. r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
  2601. guest_xcrs->xcrs[0].value);
  2602. break;
  2603. }
  2604. if (r)
  2605. r = -EINVAL;
  2606. return r;
  2607. }
  2608. /*
  2609. * kvm_set_guest_paused() indicates to the guest kernel that it has been
  2610. * stopped by the hypervisor. This function will be called from the host only.
  2611. * EINVAL is returned when the host attempts to set the flag for a guest that
  2612. * does not support pv clocks.
  2613. */
  2614. static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
  2615. {
  2616. if (!vcpu->arch.pv_time_enabled)
  2617. return -EINVAL;
  2618. vcpu->arch.pvclock_set_guest_stopped_request = true;
  2619. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  2620. return 0;
  2621. }
  2622. long kvm_arch_vcpu_ioctl(struct file *filp,
  2623. unsigned int ioctl, unsigned long arg)
  2624. {
  2625. struct kvm_vcpu *vcpu = filp->private_data;
  2626. void __user *argp = (void __user *)arg;
  2627. int r;
  2628. union {
  2629. struct kvm_lapic_state *lapic;
  2630. struct kvm_xsave *xsave;
  2631. struct kvm_xcrs *xcrs;
  2632. void *buffer;
  2633. } u;
  2634. u.buffer = NULL;
  2635. switch (ioctl) {
  2636. case KVM_GET_LAPIC: {
  2637. r = -EINVAL;
  2638. if (!vcpu->arch.apic)
  2639. goto out;
  2640. u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
  2641. r = -ENOMEM;
  2642. if (!u.lapic)
  2643. goto out;
  2644. r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
  2645. if (r)
  2646. goto out;
  2647. r = -EFAULT;
  2648. if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
  2649. goto out;
  2650. r = 0;
  2651. break;
  2652. }
  2653. case KVM_SET_LAPIC: {
  2654. r = -EINVAL;
  2655. if (!vcpu->arch.apic)
  2656. goto out;
  2657. u.lapic = memdup_user(argp, sizeof(*u.lapic));
  2658. if (IS_ERR(u.lapic))
  2659. return PTR_ERR(u.lapic);
  2660. r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
  2661. break;
  2662. }
  2663. case KVM_INTERRUPT: {
  2664. struct kvm_interrupt irq;
  2665. r = -EFAULT;
  2666. if (copy_from_user(&irq, argp, sizeof irq))
  2667. goto out;
  2668. r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
  2669. break;
  2670. }
  2671. case KVM_NMI: {
  2672. r = kvm_vcpu_ioctl_nmi(vcpu);
  2673. break;
  2674. }
  2675. case KVM_SET_CPUID: {
  2676. struct kvm_cpuid __user *cpuid_arg = argp;
  2677. struct kvm_cpuid cpuid;
  2678. r = -EFAULT;
  2679. if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
  2680. goto out;
  2681. r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
  2682. break;
  2683. }
  2684. case KVM_SET_CPUID2: {
  2685. struct kvm_cpuid2 __user *cpuid_arg = argp;
  2686. struct kvm_cpuid2 cpuid;
  2687. r = -EFAULT;
  2688. if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
  2689. goto out;
  2690. r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
  2691. cpuid_arg->entries);
  2692. break;
  2693. }
  2694. case KVM_GET_CPUID2: {
  2695. struct kvm_cpuid2 __user *cpuid_arg = argp;
  2696. struct kvm_cpuid2 cpuid;
  2697. r = -EFAULT;
  2698. if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
  2699. goto out;
  2700. r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
  2701. cpuid_arg->entries);
  2702. if (r)
  2703. goto out;
  2704. r = -EFAULT;
  2705. if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
  2706. goto out;
  2707. r = 0;
  2708. break;
  2709. }
  2710. case KVM_GET_MSRS:
  2711. r = msr_io(vcpu, argp, kvm_get_msr, 1);
  2712. break;
  2713. case KVM_SET_MSRS:
  2714. r = msr_io(vcpu, argp, do_set_msr, 0);
  2715. break;
  2716. case KVM_TPR_ACCESS_REPORTING: {
  2717. struct kvm_tpr_access_ctl tac;
  2718. r = -EFAULT;
  2719. if (copy_from_user(&tac, argp, sizeof tac))
  2720. goto out;
  2721. r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
  2722. if (r)
  2723. goto out;
  2724. r = -EFAULT;
  2725. if (copy_to_user(argp, &tac, sizeof tac))
  2726. goto out;
  2727. r = 0;
  2728. break;
  2729. };
  2730. case KVM_SET_VAPIC_ADDR: {
  2731. struct kvm_vapic_addr va;
  2732. r = -EINVAL;
  2733. if (!irqchip_in_kernel(vcpu->kvm))
  2734. goto out;
  2735. r = -EFAULT;
  2736. if (copy_from_user(&va, argp, sizeof va))
  2737. goto out;
  2738. r = 0;
  2739. kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
  2740. break;
  2741. }
  2742. case KVM_X86_SETUP_MCE: {
  2743. u64 mcg_cap;
  2744. r = -EFAULT;
  2745. if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
  2746. goto out;
  2747. r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
  2748. break;
  2749. }
  2750. case KVM_X86_SET_MCE: {
  2751. struct kvm_x86_mce mce;
  2752. r = -EFAULT;
  2753. if (copy_from_user(&mce, argp, sizeof mce))
  2754. goto out;
  2755. r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
  2756. break;
  2757. }
  2758. case KVM_GET_VCPU_EVENTS: {
  2759. struct kvm_vcpu_events events;
  2760. kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
  2761. r = -EFAULT;
  2762. if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
  2763. break;
  2764. r = 0;
  2765. break;
  2766. }
  2767. case KVM_SET_VCPU_EVENTS: {
  2768. struct kvm_vcpu_events events;
  2769. r = -EFAULT;
  2770. if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
  2771. break;
  2772. r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
  2773. break;
  2774. }
  2775. case KVM_GET_DEBUGREGS: {
  2776. struct kvm_debugregs dbgregs;
  2777. kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
  2778. r = -EFAULT;
  2779. if (copy_to_user(argp, &dbgregs,
  2780. sizeof(struct kvm_debugregs)))
  2781. break;
  2782. r = 0;
  2783. break;
  2784. }
  2785. case KVM_SET_DEBUGREGS: {
  2786. struct kvm_debugregs dbgregs;
  2787. r = -EFAULT;
  2788. if (copy_from_user(&dbgregs, argp,
  2789. sizeof(struct kvm_debugregs)))
  2790. break;
  2791. r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
  2792. break;
  2793. }
  2794. case KVM_GET_XSAVE: {
  2795. u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
  2796. r = -ENOMEM;
  2797. if (!u.xsave)
  2798. break;
  2799. kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
  2800. r = -EFAULT;
  2801. if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
  2802. break;
  2803. r = 0;
  2804. break;
  2805. }
  2806. case KVM_SET_XSAVE: {
  2807. u.xsave = memdup_user(argp, sizeof(*u.xsave));
  2808. if (IS_ERR(u.xsave))
  2809. return PTR_ERR(u.xsave);
  2810. r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
  2811. break;
  2812. }
  2813. case KVM_GET_XCRS: {
  2814. u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
  2815. r = -ENOMEM;
  2816. if (!u.xcrs)
  2817. break;
  2818. kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
  2819. r = -EFAULT;
  2820. if (copy_to_user(argp, u.xcrs,
  2821. sizeof(struct kvm_xcrs)))
  2822. break;
  2823. r = 0;
  2824. break;
  2825. }
  2826. case KVM_SET_XCRS: {
  2827. u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
  2828. if (IS_ERR(u.xcrs))
  2829. return PTR_ERR(u.xcrs);
  2830. r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
  2831. break;
  2832. }
  2833. case KVM_SET_TSC_KHZ: {
  2834. u32 user_tsc_khz;
  2835. r = -EINVAL;
  2836. user_tsc_khz = (u32)arg;
  2837. if (user_tsc_khz >= kvm_max_guest_tsc_khz)
  2838. goto out;
  2839. if (user_tsc_khz == 0)
  2840. user_tsc_khz = tsc_khz;
  2841. kvm_set_tsc_khz(vcpu, user_tsc_khz);
  2842. r = 0;
  2843. goto out;
  2844. }
  2845. case KVM_GET_TSC_KHZ: {
  2846. r = vcpu->arch.virtual_tsc_khz;
  2847. goto out;
  2848. }
  2849. case KVM_KVMCLOCK_CTRL: {
  2850. r = kvm_set_guest_paused(vcpu);
  2851. goto out;
  2852. }
  2853. default:
  2854. r = -EINVAL;
  2855. }
  2856. out:
  2857. kfree(u.buffer);
  2858. return r;
  2859. }
  2860. int kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
  2861. {
  2862. return VM_FAULT_SIGBUS;
  2863. }
  2864. static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
  2865. {
  2866. int ret;
  2867. if (addr > (unsigned int)(-3 * PAGE_SIZE))
  2868. return -EINVAL;
  2869. ret = kvm_x86_ops->set_tss_addr(kvm, addr);
  2870. return ret;
  2871. }
  2872. static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
  2873. u64 ident_addr)
  2874. {
  2875. kvm->arch.ept_identity_map_addr = ident_addr;
  2876. return 0;
  2877. }
  2878. static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
  2879. u32 kvm_nr_mmu_pages)
  2880. {
  2881. if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
  2882. return -EINVAL;
  2883. mutex_lock(&kvm->slots_lock);
  2884. kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
  2885. kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
  2886. mutex_unlock(&kvm->slots_lock);
  2887. return 0;
  2888. }
  2889. static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
  2890. {
  2891. return kvm->arch.n_max_mmu_pages;
  2892. }
  2893. static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
  2894. {
  2895. int r;
  2896. r = 0;
  2897. switch (chip->chip_id) {
  2898. case KVM_IRQCHIP_PIC_MASTER:
  2899. memcpy(&chip->chip.pic,
  2900. &pic_irqchip(kvm)->pics[0],
  2901. sizeof(struct kvm_pic_state));
  2902. break;
  2903. case KVM_IRQCHIP_PIC_SLAVE:
  2904. memcpy(&chip->chip.pic,
  2905. &pic_irqchip(kvm)->pics[1],
  2906. sizeof(struct kvm_pic_state));
  2907. break;
  2908. case KVM_IRQCHIP_IOAPIC:
  2909. r = kvm_get_ioapic(kvm, &chip->chip.ioapic);
  2910. break;
  2911. default:
  2912. r = -EINVAL;
  2913. break;
  2914. }
  2915. return r;
  2916. }
  2917. static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
  2918. {
  2919. int r;
  2920. r = 0;
  2921. switch (chip->chip_id) {
  2922. case KVM_IRQCHIP_PIC_MASTER:
  2923. spin_lock(&pic_irqchip(kvm)->lock);
  2924. memcpy(&pic_irqchip(kvm)->pics[0],
  2925. &chip->chip.pic,
  2926. sizeof(struct kvm_pic_state));
  2927. spin_unlock(&pic_irqchip(kvm)->lock);
  2928. break;
  2929. case KVM_IRQCHIP_PIC_SLAVE:
  2930. spin_lock(&pic_irqchip(kvm)->lock);
  2931. memcpy(&pic_irqchip(kvm)->pics[1],
  2932. &chip->chip.pic,
  2933. sizeof(struct kvm_pic_state));
  2934. spin_unlock(&pic_irqchip(kvm)->lock);
  2935. break;
  2936. case KVM_IRQCHIP_IOAPIC:
  2937. r = kvm_set_ioapic(kvm, &chip->chip.ioapic);
  2938. break;
  2939. default:
  2940. r = -EINVAL;
  2941. break;
  2942. }
  2943. kvm_pic_update_irq(pic_irqchip(kvm));
  2944. return r;
  2945. }
  2946. static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
  2947. {
  2948. int r = 0;
  2949. mutex_lock(&kvm->arch.vpit->pit_state.lock);
  2950. memcpy(ps, &kvm->arch.vpit->pit_state, sizeof(struct kvm_pit_state));
  2951. mutex_unlock(&kvm->arch.vpit->pit_state.lock);
  2952. return r;
  2953. }
  2954. static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
  2955. {
  2956. int r = 0;
  2957. mutex_lock(&kvm->arch.vpit->pit_state.lock);
  2958. memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));
  2959. kvm_pit_load_count(kvm, 0, ps->channels[0].count, 0);
  2960. mutex_unlock(&kvm->arch.vpit->pit_state.lock);
  2961. return r;
  2962. }
  2963. static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
  2964. {
  2965. int r = 0;
  2966. mutex_lock(&kvm->arch.vpit->pit_state.lock);
  2967. memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
  2968. sizeof(ps->channels));
  2969. ps->flags = kvm->arch.vpit->pit_state.flags;
  2970. mutex_unlock(&kvm->arch.vpit->pit_state.lock);
  2971. memset(&ps->reserved, 0, sizeof(ps->reserved));
  2972. return r;
  2973. }
  2974. static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
  2975. {
  2976. int r = 0, start = 0;
  2977. u32 prev_legacy, cur_legacy;
  2978. mutex_lock(&kvm->arch.vpit->pit_state.lock);
  2979. prev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
  2980. cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
  2981. if (!prev_legacy && cur_legacy)
  2982. start = 1;
  2983. memcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels,
  2984. sizeof(kvm->arch.vpit->pit_state.channels));
  2985. kvm->arch.vpit->pit_state.flags = ps->flags;
  2986. kvm_pit_load_count(kvm, 0, kvm->arch.vpit->pit_state.channels[0].count, start);
  2987. mutex_unlock(&kvm->arch.vpit->pit_state.lock);
  2988. return r;
  2989. }
  2990. static int kvm_vm_ioctl_reinject(struct kvm *kvm,
  2991. struct kvm_reinject_control *control)
  2992. {
  2993. if (!kvm->arch.vpit)
  2994. return -ENXIO;
  2995. mutex_lock(&kvm->arch.vpit->pit_state.lock);
  2996. kvm->arch.vpit->pit_state.reinject = control->pit_reinject;
  2997. mutex_unlock(&kvm->arch.vpit->pit_state.lock);
  2998. return 0;
  2999. }
  3000. /**
  3001. * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
  3002. * @kvm: kvm instance
  3003. * @log: slot id and address to which we copy the log
  3004. *
  3005. * We need to keep it in mind that VCPU threads can write to the bitmap
  3006. * concurrently. So, to avoid losing data, we keep the following order for
  3007. * each bit:
  3008. *
  3009. * 1. Take a snapshot of the bit and clear it if needed.
  3010. * 2. Write protect the corresponding page.
  3011. * 3. Flush TLB's if needed.
  3012. * 4. Copy the snapshot to the userspace.
  3013. *
  3014. * Between 2 and 3, the guest may write to the page using the remaining TLB
  3015. * entry. This is not a problem because the page will be reported dirty at
  3016. * step 4 using the snapshot taken before and step 3 ensures that successive
  3017. * writes will be logged for the next call.
  3018. */
  3019. int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log)
  3020. {
  3021. int r;
  3022. struct kvm_memory_slot *memslot;
  3023. unsigned long n, i;
  3024. unsigned long *dirty_bitmap;
  3025. unsigned long *dirty_bitmap_buffer;
  3026. bool is_dirty = false;
  3027. mutex_lock(&kvm->slots_lock);
  3028. r = -EINVAL;
  3029. if (log->slot >= KVM_USER_MEM_SLOTS)
  3030. goto out;
  3031. memslot = id_to_memslot(kvm->memslots, log->slot);
  3032. dirty_bitmap = memslot->dirty_bitmap;
  3033. r = -ENOENT;
  3034. if (!dirty_bitmap)
  3035. goto out;
  3036. n = kvm_dirty_bitmap_bytes(memslot);
  3037. dirty_bitmap_buffer = dirty_bitmap + n / sizeof(long);
  3038. memset(dirty_bitmap_buffer, 0, n);
  3039. spin_lock(&kvm->mmu_lock);
  3040. for (i = 0; i < n / sizeof(long); i++) {
  3041. unsigned long mask;
  3042. gfn_t offset;
  3043. if (!dirty_bitmap[i])
  3044. continue;
  3045. is_dirty = true;
  3046. mask = xchg(&dirty_bitmap[i], 0);
  3047. dirty_bitmap_buffer[i] = mask;
  3048. offset = i * BITS_PER_LONG;
  3049. kvm_mmu_write_protect_pt_masked(kvm, memslot, offset, mask);
  3050. }
  3051. if (is_dirty)
  3052. kvm_flush_remote_tlbs(kvm);
  3053. spin_unlock(&kvm->mmu_lock);
  3054. r = -EFAULT;
  3055. if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
  3056. goto out;
  3057. r = 0;
  3058. out:
  3059. mutex_unlock(&kvm->slots_lock);
  3060. return r;
  3061. }
  3062. int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
  3063. bool line_status)
  3064. {
  3065. if (!irqchip_in_kernel(kvm))
  3066. return -ENXIO;
  3067. irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
  3068. irq_event->irq, irq_event->level,
  3069. line_status);
  3070. return 0;
  3071. }
  3072. long kvm_arch_vm_ioctl(struct file *filp,
  3073. unsigned int ioctl, unsigned long arg)
  3074. {
  3075. struct kvm *kvm = filp->private_data;
  3076. void __user *argp = (void __user *)arg;
  3077. int r = -ENOTTY;
  3078. /*
  3079. * This union makes it completely explicit to gcc-3.x
  3080. * that these two variables' stack usage should be
  3081. * combined, not added together.
  3082. */
  3083. union {
  3084. struct kvm_pit_state ps;
  3085. struct kvm_pit_state2 ps2;
  3086. struct kvm_pit_config pit_config;
  3087. } u;
  3088. switch (ioctl) {
  3089. case KVM_SET_TSS_ADDR:
  3090. r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
  3091. break;
  3092. case KVM_SET_IDENTITY_MAP_ADDR: {
  3093. u64 ident_addr;
  3094. r = -EFAULT;
  3095. if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
  3096. goto out;
  3097. r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
  3098. break;
  3099. }
  3100. case KVM_SET_NR_MMU_PAGES:
  3101. r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
  3102. break;
  3103. case KVM_GET_NR_MMU_PAGES:
  3104. r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
  3105. break;
  3106. case KVM_CREATE_IRQCHIP: {
  3107. struct kvm_pic *vpic;
  3108. mutex_lock(&kvm->lock);
  3109. r = -EEXIST;
  3110. if (kvm->arch.vpic)
  3111. goto create_irqchip_unlock;
  3112. r = -EINVAL;
  3113. if (atomic_read(&kvm->online_vcpus))
  3114. goto create_irqchip_unlock;
  3115. r = -ENOMEM;
  3116. vpic = kvm_create_pic(kvm);
  3117. if (vpic) {
  3118. r = kvm_ioapic_init(kvm);
  3119. if (r) {
  3120. mutex_lock(&kvm->slots_lock);
  3121. kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
  3122. &vpic->dev_master);
  3123. kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
  3124. &vpic->dev_slave);
  3125. kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
  3126. &vpic->dev_eclr);
  3127. mutex_unlock(&kvm->slots_lock);
  3128. kfree(vpic);
  3129. goto create_irqchip_unlock;
  3130. }
  3131. } else
  3132. goto create_irqchip_unlock;
  3133. smp_wmb();
  3134. kvm->arch.vpic = vpic;
  3135. smp_wmb();
  3136. r = kvm_setup_default_irq_routing(kvm);
  3137. if (r) {
  3138. mutex_lock(&kvm->slots_lock);
  3139. mutex_lock(&kvm->irq_lock);
  3140. kvm_ioapic_destroy(kvm);
  3141. kvm_destroy_pic(kvm);
  3142. mutex_unlock(&kvm->irq_lock);
  3143. mutex_unlock(&kvm->slots_lock);
  3144. }
  3145. create_irqchip_unlock:
  3146. mutex_unlock(&kvm->lock);
  3147. break;
  3148. }
  3149. case KVM_CREATE_PIT:
  3150. u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
  3151. goto create_pit;
  3152. case KVM_CREATE_PIT2:
  3153. r = -EFAULT;
  3154. if (copy_from_user(&u.pit_config, argp,
  3155. sizeof(struct kvm_pit_config)))
  3156. goto out;
  3157. create_pit:
  3158. mutex_lock(&kvm->slots_lock);
  3159. r = -EEXIST;
  3160. if (kvm->arch.vpit)
  3161. goto create_pit_unlock;
  3162. r = -ENOMEM;
  3163. kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
  3164. if (kvm->arch.vpit)
  3165. r = 0;
  3166. create_pit_unlock:
  3167. mutex_unlock(&kvm->slots_lock);
  3168. break;
  3169. case KVM_GET_IRQCHIP: {
  3170. /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
  3171. struct kvm_irqchip *chip;
  3172. chip = memdup_user(argp, sizeof(*chip));
  3173. if (IS_ERR(chip)) {
  3174. r = PTR_ERR(chip);
  3175. goto out;
  3176. }
  3177. r = -ENXIO;
  3178. if (!irqchip_in_kernel(kvm))
  3179. goto get_irqchip_out;
  3180. r = kvm_vm_ioctl_get_irqchip(kvm, chip);
  3181. if (r)
  3182. goto get_irqchip_out;
  3183. r = -EFAULT;
  3184. if (copy_to_user(argp, chip, sizeof *chip))
  3185. goto get_irqchip_out;
  3186. r = 0;
  3187. get_irqchip_out:
  3188. kfree(chip);
  3189. break;
  3190. }
  3191. case KVM_SET_IRQCHIP: {
  3192. /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
  3193. struct kvm_irqchip *chip;
  3194. chip = memdup_user(argp, sizeof(*chip));
  3195. if (IS_ERR(chip)) {
  3196. r = PTR_ERR(chip);
  3197. goto out;
  3198. }
  3199. r = -ENXIO;
  3200. if (!irqchip_in_kernel(kvm))
  3201. goto set_irqchip_out;
  3202. r = kvm_vm_ioctl_set_irqchip(kvm, chip);
  3203. if (r)
  3204. goto set_irqchip_out;
  3205. r = 0;
  3206. set_irqchip_out:
  3207. kfree(chip);
  3208. break;
  3209. }
  3210. case KVM_GET_PIT: {
  3211. r = -EFAULT;
  3212. if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
  3213. goto out;
  3214. r = -ENXIO;
  3215. if (!kvm->arch.vpit)
  3216. goto out;
  3217. r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
  3218. if (r)
  3219. goto out;
  3220. r = -EFAULT;
  3221. if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
  3222. goto out;
  3223. r = 0;
  3224. break;
  3225. }
  3226. case KVM_SET_PIT: {
  3227. r = -EFAULT;
  3228. if (copy_from_user(&u.ps, argp, sizeof u.ps))
  3229. goto out;
  3230. r = -ENXIO;
  3231. if (!kvm->arch.vpit)
  3232. goto out;
  3233. r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
  3234. break;
  3235. }
  3236. case KVM_GET_PIT2: {
  3237. r = -ENXIO;
  3238. if (!kvm->arch.vpit)
  3239. goto out;
  3240. r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
  3241. if (r)
  3242. goto out;
  3243. r = -EFAULT;
  3244. if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
  3245. goto out;
  3246. r = 0;
  3247. break;
  3248. }
  3249. case KVM_SET_PIT2: {
  3250. r = -EFAULT;
  3251. if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
  3252. goto out;
  3253. r = -ENXIO;
  3254. if (!kvm->arch.vpit)
  3255. goto out;
  3256. r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
  3257. break;
  3258. }
  3259. case KVM_REINJECT_CONTROL: {
  3260. struct kvm_reinject_control control;
  3261. r = -EFAULT;
  3262. if (copy_from_user(&control, argp, sizeof(control)))
  3263. goto out;
  3264. r = kvm_vm_ioctl_reinject(kvm, &control);
  3265. break;
  3266. }
  3267. case KVM_XEN_HVM_CONFIG: {
  3268. r = -EFAULT;
  3269. if (copy_from_user(&kvm->arch.xen_hvm_config, argp,
  3270. sizeof(struct kvm_xen_hvm_config)))
  3271. goto out;
  3272. r = -EINVAL;
  3273. if (kvm->arch.xen_hvm_config.flags)
  3274. goto out;
  3275. r = 0;
  3276. break;
  3277. }
  3278. case KVM_SET_CLOCK: {
  3279. struct kvm_clock_data user_ns;
  3280. u64 now_ns;
  3281. s64 delta;
  3282. r = -EFAULT;
  3283. if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
  3284. goto out;
  3285. r = -EINVAL;
  3286. if (user_ns.flags)
  3287. goto out;
  3288. r = 0;
  3289. local_irq_disable();
  3290. now_ns = get_kernel_ns();
  3291. delta = user_ns.clock - now_ns;
  3292. local_irq_enable();
  3293. kvm->arch.kvmclock_offset = delta;
  3294. break;
  3295. }
  3296. case KVM_GET_CLOCK: {
  3297. struct kvm_clock_data user_ns;
  3298. u64 now_ns;
  3299. local_irq_disable();
  3300. now_ns = get_kernel_ns();
  3301. user_ns.clock = kvm->arch.kvmclock_offset + now_ns;
  3302. local_irq_enable();
  3303. user_ns.flags = 0;
  3304. memset(&user_ns.pad, 0, sizeof(user_ns.pad));
  3305. r = -EFAULT;
  3306. if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
  3307. goto out;
  3308. r = 0;
  3309. break;
  3310. }
  3311. default:
  3312. ;
  3313. }
  3314. out:
  3315. return r;
  3316. }
  3317. static void kvm_init_msr_list(void)
  3318. {
  3319. u32 dummy[2];
  3320. unsigned i, j;
  3321. /* skip the first msrs in the list. KVM-specific */
  3322. for (i = j = KVM_SAVE_MSRS_BEGIN; i < ARRAY_SIZE(msrs_to_save); i++) {
  3323. if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
  3324. continue;
  3325. if (j < i)
  3326. msrs_to_save[j] = msrs_to_save[i];
  3327. j++;
  3328. }
  3329. num_msrs_to_save = j;
  3330. }
  3331. static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
  3332. const void *v)
  3333. {
  3334. int handled = 0;
  3335. int n;
  3336. do {
  3337. n = min(len, 8);
  3338. if (!(vcpu->arch.apic &&
  3339. !kvm_iodevice_write(&vcpu->arch.apic->dev, addr, n, v))
  3340. && kvm_io_bus_write(vcpu->kvm, KVM_MMIO_BUS, addr, n, v))
  3341. break;
  3342. handled += n;
  3343. addr += n;
  3344. len -= n;
  3345. v += n;
  3346. } while (len);
  3347. return handled;
  3348. }
  3349. static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
  3350. {
  3351. int handled = 0;
  3352. int n;
  3353. do {
  3354. n = min(len, 8);
  3355. if (!(vcpu->arch.apic &&
  3356. !kvm_iodevice_read(&vcpu->arch.apic->dev, addr, n, v))
  3357. && kvm_io_bus_read(vcpu->kvm, KVM_MMIO_BUS, addr, n, v))
  3358. break;
  3359. trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, *(u64 *)v);
  3360. handled += n;
  3361. addr += n;
  3362. len -= n;
  3363. v += n;
  3364. } while (len);
  3365. return handled;
  3366. }
  3367. static void kvm_set_segment(struct kvm_vcpu *vcpu,
  3368. struct kvm_segment *var, int seg)
  3369. {
  3370. kvm_x86_ops->set_segment(vcpu, var, seg);
  3371. }
  3372. void kvm_get_segment(struct kvm_vcpu *vcpu,
  3373. struct kvm_segment *var, int seg)
  3374. {
  3375. kvm_x86_ops->get_segment(vcpu, var, seg);
  3376. }
  3377. gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access)
  3378. {
  3379. gpa_t t_gpa;
  3380. struct x86_exception exception;
  3381. BUG_ON(!mmu_is_nested(vcpu));
  3382. /* NPT walks are always user-walks */
  3383. access |= PFERR_USER_MASK;
  3384. t_gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gpa, access, &exception);
  3385. return t_gpa;
  3386. }
  3387. gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
  3388. struct x86_exception *exception)
  3389. {
  3390. u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
  3391. return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
  3392. }
  3393. gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
  3394. struct x86_exception *exception)
  3395. {
  3396. u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
  3397. access |= PFERR_FETCH_MASK;
  3398. return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
  3399. }
  3400. gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
  3401. struct x86_exception *exception)
  3402. {
  3403. u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
  3404. access |= PFERR_WRITE_MASK;
  3405. return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
  3406. }
  3407. /* uses this to access any guest's mapped memory without checking CPL */
  3408. gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
  3409. struct x86_exception *exception)
  3410. {
  3411. return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
  3412. }
  3413. static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
  3414. struct kvm_vcpu *vcpu, u32 access,
  3415. struct x86_exception *exception)
  3416. {
  3417. void *data = val;
  3418. int r = X86EMUL_CONTINUE;
  3419. while (bytes) {
  3420. gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
  3421. exception);
  3422. unsigned offset = addr & (PAGE_SIZE-1);
  3423. unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
  3424. int ret;
  3425. if (gpa == UNMAPPED_GVA)
  3426. return X86EMUL_PROPAGATE_FAULT;
  3427. ret = kvm_read_guest(vcpu->kvm, gpa, data, toread);
  3428. if (ret < 0) {
  3429. r = X86EMUL_IO_NEEDED;
  3430. goto out;
  3431. }
  3432. bytes -= toread;
  3433. data += toread;
  3434. addr += toread;
  3435. }
  3436. out:
  3437. return r;
  3438. }
  3439. /* used for instruction fetching */
  3440. static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
  3441. gva_t addr, void *val, unsigned int bytes,
  3442. struct x86_exception *exception)
  3443. {
  3444. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  3445. u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
  3446. return kvm_read_guest_virt_helper(addr, val, bytes, vcpu,
  3447. access | PFERR_FETCH_MASK,
  3448. exception);
  3449. }
  3450. int kvm_read_guest_virt(struct x86_emulate_ctxt *ctxt,
  3451. gva_t addr, void *val, unsigned int bytes,
  3452. struct x86_exception *exception)
  3453. {
  3454. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  3455. u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
  3456. return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
  3457. exception);
  3458. }
  3459. EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
  3460. static int kvm_read_guest_virt_system(struct x86_emulate_ctxt *ctxt,
  3461. gva_t addr, void *val, unsigned int bytes,
  3462. struct x86_exception *exception)
  3463. {
  3464. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  3465. return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, 0, exception);
  3466. }
  3467. int kvm_write_guest_virt_system(struct x86_emulate_ctxt *ctxt,
  3468. gva_t addr, void *val,
  3469. unsigned int bytes,
  3470. struct x86_exception *exception)
  3471. {
  3472. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  3473. void *data = val;
  3474. int r = X86EMUL_CONTINUE;
  3475. while (bytes) {
  3476. gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
  3477. PFERR_WRITE_MASK,
  3478. exception);
  3479. unsigned offset = addr & (PAGE_SIZE-1);
  3480. unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
  3481. int ret;
  3482. if (gpa == UNMAPPED_GVA)
  3483. return X86EMUL_PROPAGATE_FAULT;
  3484. ret = kvm_write_guest(vcpu->kvm, gpa, data, towrite);
  3485. if (ret < 0) {
  3486. r = X86EMUL_IO_NEEDED;
  3487. goto out;
  3488. }
  3489. bytes -= towrite;
  3490. data += towrite;
  3491. addr += towrite;
  3492. }
  3493. out:
  3494. return r;
  3495. }
  3496. EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
  3497. static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
  3498. gpa_t *gpa, struct x86_exception *exception,
  3499. bool write)
  3500. {
  3501. u32 access = ((kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0)
  3502. | (write ? PFERR_WRITE_MASK : 0);
  3503. if (vcpu_match_mmio_gva(vcpu, gva)
  3504. && !permission_fault(vcpu->arch.walk_mmu, vcpu->arch.access, access)) {
  3505. *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
  3506. (gva & (PAGE_SIZE - 1));
  3507. trace_vcpu_match_mmio(gva, *gpa, write, false);
  3508. return 1;
  3509. }
  3510. *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
  3511. if (*gpa == UNMAPPED_GVA)
  3512. return -1;
  3513. /* For APIC access vmexit */
  3514. if ((*gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
  3515. return 1;
  3516. if (vcpu_match_mmio_gpa(vcpu, *gpa)) {
  3517. trace_vcpu_match_mmio(gva, *gpa, write, true);
  3518. return 1;
  3519. }
  3520. return 0;
  3521. }
  3522. int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
  3523. const void *val, int bytes)
  3524. {
  3525. int ret;
  3526. ret = kvm_write_guest(vcpu->kvm, gpa, val, bytes);
  3527. if (ret < 0)
  3528. return 0;
  3529. kvm_mmu_pte_write(vcpu, gpa, val, bytes);
  3530. return 1;
  3531. }
  3532. struct read_write_emulator_ops {
  3533. int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
  3534. int bytes);
  3535. int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
  3536. void *val, int bytes);
  3537. int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
  3538. int bytes, void *val);
  3539. int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
  3540. void *val, int bytes);
  3541. bool write;
  3542. };
  3543. static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
  3544. {
  3545. if (vcpu->mmio_read_completed) {
  3546. trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
  3547. vcpu->mmio_fragments[0].gpa, *(u64 *)val);
  3548. vcpu->mmio_read_completed = 0;
  3549. return 1;
  3550. }
  3551. return 0;
  3552. }
  3553. static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
  3554. void *val, int bytes)
  3555. {
  3556. return !kvm_read_guest(vcpu->kvm, gpa, val, bytes);
  3557. }
  3558. static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
  3559. void *val, int bytes)
  3560. {
  3561. return emulator_write_phys(vcpu, gpa, val, bytes);
  3562. }
  3563. static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
  3564. {
  3565. trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, *(u64 *)val);
  3566. return vcpu_mmio_write(vcpu, gpa, bytes, val);
  3567. }
  3568. static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
  3569. void *val, int bytes)
  3570. {
  3571. trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, 0);
  3572. return X86EMUL_IO_NEEDED;
  3573. }
  3574. static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
  3575. void *val, int bytes)
  3576. {
  3577. struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
  3578. memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
  3579. return X86EMUL_CONTINUE;
  3580. }
  3581. static const struct read_write_emulator_ops read_emultor = {
  3582. .read_write_prepare = read_prepare,
  3583. .read_write_emulate = read_emulate,
  3584. .read_write_mmio = vcpu_mmio_read,
  3585. .read_write_exit_mmio = read_exit_mmio,
  3586. };
  3587. static const struct read_write_emulator_ops write_emultor = {
  3588. .read_write_emulate = write_emulate,
  3589. .read_write_mmio = write_mmio,
  3590. .read_write_exit_mmio = write_exit_mmio,
  3591. .write = true,
  3592. };
  3593. static int emulator_read_write_onepage(unsigned long addr, void *val,
  3594. unsigned int bytes,
  3595. struct x86_exception *exception,
  3596. struct kvm_vcpu *vcpu,
  3597. const struct read_write_emulator_ops *ops)
  3598. {
  3599. gpa_t gpa;
  3600. int handled, ret;
  3601. bool write = ops->write;
  3602. struct kvm_mmio_fragment *frag;
  3603. ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
  3604. if (ret < 0)
  3605. return X86EMUL_PROPAGATE_FAULT;
  3606. /* For APIC access vmexit */
  3607. if (ret)
  3608. goto mmio;
  3609. if (ops->read_write_emulate(vcpu, gpa, val, bytes))
  3610. return X86EMUL_CONTINUE;
  3611. mmio:
  3612. /*
  3613. * Is this MMIO handled locally?
  3614. */
  3615. handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
  3616. if (handled == bytes)
  3617. return X86EMUL_CONTINUE;
  3618. gpa += handled;
  3619. bytes -= handled;
  3620. val += handled;
  3621. WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
  3622. frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
  3623. frag->gpa = gpa;
  3624. frag->data = val;
  3625. frag->len = bytes;
  3626. return X86EMUL_CONTINUE;
  3627. }
  3628. int emulator_read_write(struct x86_emulate_ctxt *ctxt, unsigned long addr,
  3629. void *val, unsigned int bytes,
  3630. struct x86_exception *exception,
  3631. const struct read_write_emulator_ops *ops)
  3632. {
  3633. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  3634. gpa_t gpa;
  3635. int rc;
  3636. if (ops->read_write_prepare &&
  3637. ops->read_write_prepare(vcpu, val, bytes))
  3638. return X86EMUL_CONTINUE;
  3639. vcpu->mmio_nr_fragments = 0;
  3640. /* Crossing a page boundary? */
  3641. if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
  3642. int now;
  3643. now = -addr & ~PAGE_MASK;
  3644. rc = emulator_read_write_onepage(addr, val, now, exception,
  3645. vcpu, ops);
  3646. if (rc != X86EMUL_CONTINUE)
  3647. return rc;
  3648. addr += now;
  3649. val += now;
  3650. bytes -= now;
  3651. }
  3652. rc = emulator_read_write_onepage(addr, val, bytes, exception,
  3653. vcpu, ops);
  3654. if (rc != X86EMUL_CONTINUE)
  3655. return rc;
  3656. if (!vcpu->mmio_nr_fragments)
  3657. return rc;
  3658. gpa = vcpu->mmio_fragments[0].gpa;
  3659. vcpu->mmio_needed = 1;
  3660. vcpu->mmio_cur_fragment = 0;
  3661. vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
  3662. vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
  3663. vcpu->run->exit_reason = KVM_EXIT_MMIO;
  3664. vcpu->run->mmio.phys_addr = gpa;
  3665. return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
  3666. }
  3667. static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
  3668. unsigned long addr,
  3669. void *val,
  3670. unsigned int bytes,
  3671. struct x86_exception *exception)
  3672. {
  3673. return emulator_read_write(ctxt, addr, val, bytes,
  3674. exception, &read_emultor);
  3675. }
  3676. int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
  3677. unsigned long addr,
  3678. const void *val,
  3679. unsigned int bytes,
  3680. struct x86_exception *exception)
  3681. {
  3682. return emulator_read_write(ctxt, addr, (void *)val, bytes,
  3683. exception, &write_emultor);
  3684. }
  3685. #define CMPXCHG_TYPE(t, ptr, old, new) \
  3686. (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
  3687. #ifdef CONFIG_X86_64
  3688. # define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
  3689. #else
  3690. # define CMPXCHG64(ptr, old, new) \
  3691. (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
  3692. #endif
  3693. static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
  3694. unsigned long addr,
  3695. const void *old,
  3696. const void *new,
  3697. unsigned int bytes,
  3698. struct x86_exception *exception)
  3699. {
  3700. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  3701. gpa_t gpa;
  3702. struct page *page;
  3703. char *kaddr;
  3704. bool exchanged;
  3705. /* guests cmpxchg8b have to be emulated atomically */
  3706. if (bytes > 8 || (bytes & (bytes - 1)))
  3707. goto emul_write;
  3708. gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
  3709. if (gpa == UNMAPPED_GVA ||
  3710. (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
  3711. goto emul_write;
  3712. if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
  3713. goto emul_write;
  3714. page = gfn_to_page(vcpu->kvm, gpa >> PAGE_SHIFT);
  3715. if (is_error_page(page))
  3716. goto emul_write;
  3717. kaddr = kmap_atomic(page);
  3718. kaddr += offset_in_page(gpa);
  3719. switch (bytes) {
  3720. case 1:
  3721. exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
  3722. break;
  3723. case 2:
  3724. exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
  3725. break;
  3726. case 4:
  3727. exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
  3728. break;
  3729. case 8:
  3730. exchanged = CMPXCHG64(kaddr, old, new);
  3731. break;
  3732. default:
  3733. BUG();
  3734. }
  3735. kunmap_atomic(kaddr);
  3736. kvm_release_page_dirty(page);
  3737. if (!exchanged)
  3738. return X86EMUL_CMPXCHG_FAILED;
  3739. kvm_mmu_pte_write(vcpu, gpa, new, bytes);
  3740. return X86EMUL_CONTINUE;
  3741. emul_write:
  3742. printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
  3743. return emulator_write_emulated(ctxt, addr, new, bytes, exception);
  3744. }
  3745. static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
  3746. {
  3747. /* TODO: String I/O for in kernel device */
  3748. int r;
  3749. if (vcpu->arch.pio.in)
  3750. r = kvm_io_bus_read(vcpu->kvm, KVM_PIO_BUS, vcpu->arch.pio.port,
  3751. vcpu->arch.pio.size, pd);
  3752. else
  3753. r = kvm_io_bus_write(vcpu->kvm, KVM_PIO_BUS,
  3754. vcpu->arch.pio.port, vcpu->arch.pio.size,
  3755. pd);
  3756. return r;
  3757. }
  3758. static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
  3759. unsigned short port, void *val,
  3760. unsigned int count, bool in)
  3761. {
  3762. trace_kvm_pio(!in, port, size, count);
  3763. vcpu->arch.pio.port = port;
  3764. vcpu->arch.pio.in = in;
  3765. vcpu->arch.pio.count = count;
  3766. vcpu->arch.pio.size = size;
  3767. if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
  3768. vcpu->arch.pio.count = 0;
  3769. return 1;
  3770. }
  3771. vcpu->run->exit_reason = KVM_EXIT_IO;
  3772. vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
  3773. vcpu->run->io.size = size;
  3774. vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
  3775. vcpu->run->io.count = count;
  3776. vcpu->run->io.port = port;
  3777. return 0;
  3778. }
  3779. static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
  3780. int size, unsigned short port, void *val,
  3781. unsigned int count)
  3782. {
  3783. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  3784. int ret;
  3785. if (vcpu->arch.pio.count)
  3786. goto data_avail;
  3787. ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
  3788. if (ret) {
  3789. data_avail:
  3790. memcpy(val, vcpu->arch.pio_data, size * count);
  3791. vcpu->arch.pio.count = 0;
  3792. return 1;
  3793. }
  3794. return 0;
  3795. }
  3796. static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
  3797. int size, unsigned short port,
  3798. const void *val, unsigned int count)
  3799. {
  3800. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  3801. memcpy(vcpu->arch.pio_data, val, size * count);
  3802. return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
  3803. }
  3804. static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
  3805. {
  3806. return kvm_x86_ops->get_segment_base(vcpu, seg);
  3807. }
  3808. static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
  3809. {
  3810. kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
  3811. }
  3812. int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
  3813. {
  3814. if (!need_emulate_wbinvd(vcpu))
  3815. return X86EMUL_CONTINUE;
  3816. if (kvm_x86_ops->has_wbinvd_exit()) {
  3817. int cpu = get_cpu();
  3818. cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
  3819. smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
  3820. wbinvd_ipi, NULL, 1);
  3821. put_cpu();
  3822. cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
  3823. } else
  3824. wbinvd();
  3825. return X86EMUL_CONTINUE;
  3826. }
  3827. EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
  3828. static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
  3829. {
  3830. kvm_emulate_wbinvd(emul_to_vcpu(ctxt));
  3831. }
  3832. int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long *dest)
  3833. {
  3834. return _kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
  3835. }
  3836. int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long value)
  3837. {
  3838. return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
  3839. }
  3840. static u64 mk_cr_64(u64 curr_cr, u32 new_val)
  3841. {
  3842. return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
  3843. }
  3844. static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
  3845. {
  3846. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  3847. unsigned long value;
  3848. switch (cr) {
  3849. case 0:
  3850. value = kvm_read_cr0(vcpu);
  3851. break;
  3852. case 2:
  3853. value = vcpu->arch.cr2;
  3854. break;
  3855. case 3:
  3856. value = kvm_read_cr3(vcpu);
  3857. break;
  3858. case 4:
  3859. value = kvm_read_cr4(vcpu);
  3860. break;
  3861. case 8:
  3862. value = kvm_get_cr8(vcpu);
  3863. break;
  3864. default:
  3865. kvm_err("%s: unexpected cr %u\n", __func__, cr);
  3866. return 0;
  3867. }
  3868. return value;
  3869. }
  3870. static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
  3871. {
  3872. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  3873. int res = 0;
  3874. switch (cr) {
  3875. case 0:
  3876. res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
  3877. break;
  3878. case 2:
  3879. vcpu->arch.cr2 = val;
  3880. break;
  3881. case 3:
  3882. res = kvm_set_cr3(vcpu, val);
  3883. break;
  3884. case 4:
  3885. res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
  3886. break;
  3887. case 8:
  3888. res = kvm_set_cr8(vcpu, val);
  3889. break;
  3890. default:
  3891. kvm_err("%s: unexpected cr %u\n", __func__, cr);
  3892. res = -1;
  3893. }
  3894. return res;
  3895. }
  3896. static void emulator_set_rflags(struct x86_emulate_ctxt *ctxt, ulong val)
  3897. {
  3898. kvm_set_rflags(emul_to_vcpu(ctxt), val);
  3899. }
  3900. static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
  3901. {
  3902. return kvm_x86_ops->get_cpl(emul_to_vcpu(ctxt));
  3903. }
  3904. static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
  3905. {
  3906. kvm_x86_ops->get_gdt(emul_to_vcpu(ctxt), dt);
  3907. }
  3908. static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
  3909. {
  3910. kvm_x86_ops->get_idt(emul_to_vcpu(ctxt), dt);
  3911. }
  3912. static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
  3913. {
  3914. kvm_x86_ops->set_gdt(emul_to_vcpu(ctxt), dt);
  3915. }
  3916. static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
  3917. {
  3918. kvm_x86_ops->set_idt(emul_to_vcpu(ctxt), dt);
  3919. }
  3920. static unsigned long emulator_get_cached_segment_base(
  3921. struct x86_emulate_ctxt *ctxt, int seg)
  3922. {
  3923. return get_segment_base(emul_to_vcpu(ctxt), seg);
  3924. }
  3925. static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
  3926. struct desc_struct *desc, u32 *base3,
  3927. int seg)
  3928. {
  3929. struct kvm_segment var;
  3930. kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
  3931. *selector = var.selector;
  3932. if (var.unusable) {
  3933. memset(desc, 0, sizeof(*desc));
  3934. return false;
  3935. }
  3936. if (var.g)
  3937. var.limit >>= 12;
  3938. set_desc_limit(desc, var.limit);
  3939. set_desc_base(desc, (unsigned long)var.base);
  3940. #ifdef CONFIG_X86_64
  3941. if (base3)
  3942. *base3 = var.base >> 32;
  3943. #endif
  3944. desc->type = var.type;
  3945. desc->s = var.s;
  3946. desc->dpl = var.dpl;
  3947. desc->p = var.present;
  3948. desc->avl = var.avl;
  3949. desc->l = var.l;
  3950. desc->d = var.db;
  3951. desc->g = var.g;
  3952. return true;
  3953. }
  3954. static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
  3955. struct desc_struct *desc, u32 base3,
  3956. int seg)
  3957. {
  3958. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  3959. struct kvm_segment var;
  3960. var.selector = selector;
  3961. var.base = get_desc_base(desc);
  3962. #ifdef CONFIG_X86_64
  3963. var.base |= ((u64)base3) << 32;
  3964. #endif
  3965. var.limit = get_desc_limit(desc);
  3966. if (desc->g)
  3967. var.limit = (var.limit << 12) | 0xfff;
  3968. var.type = desc->type;
  3969. var.present = desc->p;
  3970. var.dpl = desc->dpl;
  3971. var.db = desc->d;
  3972. var.s = desc->s;
  3973. var.l = desc->l;
  3974. var.g = desc->g;
  3975. var.avl = desc->avl;
  3976. var.present = desc->p;
  3977. var.unusable = !var.present;
  3978. var.padding = 0;
  3979. kvm_set_segment(vcpu, &var, seg);
  3980. return;
  3981. }
  3982. static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
  3983. u32 msr_index, u64 *pdata)
  3984. {
  3985. return kvm_get_msr(emul_to_vcpu(ctxt), msr_index, pdata);
  3986. }
  3987. static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
  3988. u32 msr_index, u64 data)
  3989. {
  3990. struct msr_data msr;
  3991. msr.data = data;
  3992. msr.index = msr_index;
  3993. msr.host_initiated = false;
  3994. return kvm_set_msr(emul_to_vcpu(ctxt), &msr);
  3995. }
  3996. static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
  3997. u32 pmc, u64 *pdata)
  3998. {
  3999. return kvm_pmu_read_pmc(emul_to_vcpu(ctxt), pmc, pdata);
  4000. }
  4001. static void emulator_halt(struct x86_emulate_ctxt *ctxt)
  4002. {
  4003. emul_to_vcpu(ctxt)->arch.halt_request = 1;
  4004. }
  4005. static void emulator_get_fpu(struct x86_emulate_ctxt *ctxt)
  4006. {
  4007. preempt_disable();
  4008. kvm_load_guest_fpu(emul_to_vcpu(ctxt));
  4009. /*
  4010. * CR0.TS may reference the host fpu state, not the guest fpu state,
  4011. * so it may be clear at this point.
  4012. */
  4013. clts();
  4014. }
  4015. static void emulator_put_fpu(struct x86_emulate_ctxt *ctxt)
  4016. {
  4017. preempt_enable();
  4018. }
  4019. static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
  4020. struct x86_instruction_info *info,
  4021. enum x86_intercept_stage stage)
  4022. {
  4023. return kvm_x86_ops->check_intercept(emul_to_vcpu(ctxt), info, stage);
  4024. }
  4025. static void emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
  4026. u32 *eax, u32 *ebx, u32 *ecx, u32 *edx)
  4027. {
  4028. kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx);
  4029. }
  4030. static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
  4031. {
  4032. return kvm_register_read(emul_to_vcpu(ctxt), reg);
  4033. }
  4034. static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
  4035. {
  4036. kvm_register_write(emul_to_vcpu(ctxt), reg, val);
  4037. }
  4038. static const struct x86_emulate_ops emulate_ops = {
  4039. .read_gpr = emulator_read_gpr,
  4040. .write_gpr = emulator_write_gpr,
  4041. .read_std = kvm_read_guest_virt_system,
  4042. .write_std = kvm_write_guest_virt_system,
  4043. .fetch = kvm_fetch_guest_virt,
  4044. .read_emulated = emulator_read_emulated,
  4045. .write_emulated = emulator_write_emulated,
  4046. .cmpxchg_emulated = emulator_cmpxchg_emulated,
  4047. .invlpg = emulator_invlpg,
  4048. .pio_in_emulated = emulator_pio_in_emulated,
  4049. .pio_out_emulated = emulator_pio_out_emulated,
  4050. .get_segment = emulator_get_segment,
  4051. .set_segment = emulator_set_segment,
  4052. .get_cached_segment_base = emulator_get_cached_segment_base,
  4053. .get_gdt = emulator_get_gdt,
  4054. .get_idt = emulator_get_idt,
  4055. .set_gdt = emulator_set_gdt,
  4056. .set_idt = emulator_set_idt,
  4057. .get_cr = emulator_get_cr,
  4058. .set_cr = emulator_set_cr,
  4059. .set_rflags = emulator_set_rflags,
  4060. .cpl = emulator_get_cpl,
  4061. .get_dr = emulator_get_dr,
  4062. .set_dr = emulator_set_dr,
  4063. .set_msr = emulator_set_msr,
  4064. .get_msr = emulator_get_msr,
  4065. .read_pmc = emulator_read_pmc,
  4066. .halt = emulator_halt,
  4067. .wbinvd = emulator_wbinvd,
  4068. .fix_hypercall = emulator_fix_hypercall,
  4069. .get_fpu = emulator_get_fpu,
  4070. .put_fpu = emulator_put_fpu,
  4071. .intercept = emulator_intercept,
  4072. .get_cpuid = emulator_get_cpuid,
  4073. };
  4074. static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
  4075. {
  4076. u32 int_shadow = kvm_x86_ops->get_interrupt_shadow(vcpu, mask);
  4077. /*
  4078. * an sti; sti; sequence only disable interrupts for the first
  4079. * instruction. So, if the last instruction, be it emulated or
  4080. * not, left the system with the INT_STI flag enabled, it
  4081. * means that the last instruction is an sti. We should not
  4082. * leave the flag on in this case. The same goes for mov ss
  4083. */
  4084. if (!(int_shadow & mask))
  4085. kvm_x86_ops->set_interrupt_shadow(vcpu, mask);
  4086. }
  4087. static void inject_emulated_exception(struct kvm_vcpu *vcpu)
  4088. {
  4089. struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
  4090. if (ctxt->exception.vector == PF_VECTOR)
  4091. kvm_propagate_fault(vcpu, &ctxt->exception);
  4092. else if (ctxt->exception.error_code_valid)
  4093. kvm_queue_exception_e(vcpu, ctxt->exception.vector,
  4094. ctxt->exception.error_code);
  4095. else
  4096. kvm_queue_exception(vcpu, ctxt->exception.vector);
  4097. }
  4098. static void init_decode_cache(struct x86_emulate_ctxt *ctxt)
  4099. {
  4100. memset(&ctxt->twobyte, 0,
  4101. (void *)&ctxt->_regs - (void *)&ctxt->twobyte);
  4102. ctxt->fetch.start = 0;
  4103. ctxt->fetch.end = 0;
  4104. ctxt->io_read.pos = 0;
  4105. ctxt->io_read.end = 0;
  4106. ctxt->mem_read.pos = 0;
  4107. ctxt->mem_read.end = 0;
  4108. }
  4109. static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
  4110. {
  4111. struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
  4112. int cs_db, cs_l;
  4113. kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
  4114. ctxt->eflags = kvm_get_rflags(vcpu);
  4115. ctxt->eip = kvm_rip_read(vcpu);
  4116. ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
  4117. (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
  4118. cs_l ? X86EMUL_MODE_PROT64 :
  4119. cs_db ? X86EMUL_MODE_PROT32 :
  4120. X86EMUL_MODE_PROT16;
  4121. ctxt->guest_mode = is_guest_mode(vcpu);
  4122. init_decode_cache(ctxt);
  4123. vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
  4124. }
  4125. int kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
  4126. {
  4127. struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
  4128. int ret;
  4129. init_emulate_ctxt(vcpu);
  4130. ctxt->op_bytes = 2;
  4131. ctxt->ad_bytes = 2;
  4132. ctxt->_eip = ctxt->eip + inc_eip;
  4133. ret = emulate_int_real(ctxt, irq);
  4134. if (ret != X86EMUL_CONTINUE)
  4135. return EMULATE_FAIL;
  4136. ctxt->eip = ctxt->_eip;
  4137. kvm_rip_write(vcpu, ctxt->eip);
  4138. kvm_set_rflags(vcpu, ctxt->eflags);
  4139. if (irq == NMI_VECTOR)
  4140. vcpu->arch.nmi_pending = 0;
  4141. else
  4142. vcpu->arch.interrupt.pending = false;
  4143. return EMULATE_DONE;
  4144. }
  4145. EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
  4146. static int handle_emulation_failure(struct kvm_vcpu *vcpu)
  4147. {
  4148. int r = EMULATE_DONE;
  4149. ++vcpu->stat.insn_emulation_fail;
  4150. trace_kvm_emulate_insn_failed(vcpu);
  4151. if (!is_guest_mode(vcpu)) {
  4152. vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
  4153. vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
  4154. vcpu->run->internal.ndata = 0;
  4155. r = EMULATE_FAIL;
  4156. }
  4157. kvm_queue_exception(vcpu, UD_VECTOR);
  4158. return r;
  4159. }
  4160. static bool reexecute_instruction(struct kvm_vcpu *vcpu, gva_t cr2,
  4161. bool write_fault_to_shadow_pgtable,
  4162. int emulation_type)
  4163. {
  4164. gpa_t gpa = cr2;
  4165. pfn_t pfn;
  4166. if (emulation_type & EMULTYPE_NO_REEXECUTE)
  4167. return false;
  4168. if (!vcpu->arch.mmu.direct_map) {
  4169. /*
  4170. * Write permission should be allowed since only
  4171. * write access need to be emulated.
  4172. */
  4173. gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
  4174. /*
  4175. * If the mapping is invalid in guest, let cpu retry
  4176. * it to generate fault.
  4177. */
  4178. if (gpa == UNMAPPED_GVA)
  4179. return true;
  4180. }
  4181. /*
  4182. * Do not retry the unhandleable instruction if it faults on the
  4183. * readonly host memory, otherwise it will goto a infinite loop:
  4184. * retry instruction -> write #PF -> emulation fail -> retry
  4185. * instruction -> ...
  4186. */
  4187. pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
  4188. /*
  4189. * If the instruction failed on the error pfn, it can not be fixed,
  4190. * report the error to userspace.
  4191. */
  4192. if (is_error_noslot_pfn(pfn))
  4193. return false;
  4194. kvm_release_pfn_clean(pfn);
  4195. /* The instructions are well-emulated on direct mmu. */
  4196. if (vcpu->arch.mmu.direct_map) {
  4197. unsigned int indirect_shadow_pages;
  4198. spin_lock(&vcpu->kvm->mmu_lock);
  4199. indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
  4200. spin_unlock(&vcpu->kvm->mmu_lock);
  4201. if (indirect_shadow_pages)
  4202. kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
  4203. return true;
  4204. }
  4205. /*
  4206. * if emulation was due to access to shadowed page table
  4207. * and it failed try to unshadow page and re-enter the
  4208. * guest to let CPU execute the instruction.
  4209. */
  4210. kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
  4211. /*
  4212. * If the access faults on its page table, it can not
  4213. * be fixed by unprotecting shadow page and it should
  4214. * be reported to userspace.
  4215. */
  4216. return !write_fault_to_shadow_pgtable;
  4217. }
  4218. static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
  4219. unsigned long cr2, int emulation_type)
  4220. {
  4221. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  4222. unsigned long last_retry_eip, last_retry_addr, gpa = cr2;
  4223. last_retry_eip = vcpu->arch.last_retry_eip;
  4224. last_retry_addr = vcpu->arch.last_retry_addr;
  4225. /*
  4226. * If the emulation is caused by #PF and it is non-page_table
  4227. * writing instruction, it means the VM-EXIT is caused by shadow
  4228. * page protected, we can zap the shadow page and retry this
  4229. * instruction directly.
  4230. *
  4231. * Note: if the guest uses a non-page-table modifying instruction
  4232. * on the PDE that points to the instruction, then we will unmap
  4233. * the instruction and go to an infinite loop. So, we cache the
  4234. * last retried eip and the last fault address, if we meet the eip
  4235. * and the address again, we can break out of the potential infinite
  4236. * loop.
  4237. */
  4238. vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
  4239. if (!(emulation_type & EMULTYPE_RETRY))
  4240. return false;
  4241. if (x86_page_table_writing_insn(ctxt))
  4242. return false;
  4243. if (ctxt->eip == last_retry_eip && last_retry_addr == cr2)
  4244. return false;
  4245. vcpu->arch.last_retry_eip = ctxt->eip;
  4246. vcpu->arch.last_retry_addr = cr2;
  4247. if (!vcpu->arch.mmu.direct_map)
  4248. gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
  4249. kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
  4250. return true;
  4251. }
  4252. static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
  4253. static int complete_emulated_pio(struct kvm_vcpu *vcpu);
  4254. int x86_emulate_instruction(struct kvm_vcpu *vcpu,
  4255. unsigned long cr2,
  4256. int emulation_type,
  4257. void *insn,
  4258. int insn_len)
  4259. {
  4260. int r;
  4261. struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
  4262. bool writeback = true;
  4263. bool write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
  4264. /*
  4265. * Clear write_fault_to_shadow_pgtable here to ensure it is
  4266. * never reused.
  4267. */
  4268. vcpu->arch.write_fault_to_shadow_pgtable = false;
  4269. kvm_clear_exception_queue(vcpu);
  4270. if (!(emulation_type & EMULTYPE_NO_DECODE)) {
  4271. init_emulate_ctxt(vcpu);
  4272. ctxt->interruptibility = 0;
  4273. ctxt->have_exception = false;
  4274. ctxt->perm_ok = false;
  4275. ctxt->only_vendor_specific_insn
  4276. = emulation_type & EMULTYPE_TRAP_UD;
  4277. r = x86_decode_insn(ctxt, insn, insn_len);
  4278. trace_kvm_emulate_insn_start(vcpu);
  4279. ++vcpu->stat.insn_emulation;
  4280. if (r != EMULATION_OK) {
  4281. if (emulation_type & EMULTYPE_TRAP_UD)
  4282. return EMULATE_FAIL;
  4283. if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
  4284. emulation_type))
  4285. return EMULATE_DONE;
  4286. if (emulation_type & EMULTYPE_SKIP)
  4287. return EMULATE_FAIL;
  4288. return handle_emulation_failure(vcpu);
  4289. }
  4290. }
  4291. if (emulation_type & EMULTYPE_SKIP) {
  4292. kvm_rip_write(vcpu, ctxt->_eip);
  4293. return EMULATE_DONE;
  4294. }
  4295. if (retry_instruction(ctxt, cr2, emulation_type))
  4296. return EMULATE_DONE;
  4297. /* this is needed for vmware backdoor interface to work since it
  4298. changes registers values during IO operation */
  4299. if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
  4300. vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
  4301. emulator_invalidate_register_cache(ctxt);
  4302. }
  4303. restart:
  4304. r = x86_emulate_insn(ctxt);
  4305. if (r == EMULATION_INTERCEPTED)
  4306. return EMULATE_DONE;
  4307. if (r == EMULATION_FAILED) {
  4308. if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
  4309. emulation_type))
  4310. return EMULATE_DONE;
  4311. return handle_emulation_failure(vcpu);
  4312. }
  4313. if (ctxt->have_exception) {
  4314. inject_emulated_exception(vcpu);
  4315. r = EMULATE_DONE;
  4316. } else if (vcpu->arch.pio.count) {
  4317. if (!vcpu->arch.pio.in)
  4318. vcpu->arch.pio.count = 0;
  4319. else {
  4320. writeback = false;
  4321. vcpu->arch.complete_userspace_io = complete_emulated_pio;
  4322. }
  4323. r = EMULATE_DO_MMIO;
  4324. } else if (vcpu->mmio_needed) {
  4325. if (!vcpu->mmio_is_write)
  4326. writeback = false;
  4327. r = EMULATE_DO_MMIO;
  4328. vcpu->arch.complete_userspace_io = complete_emulated_mmio;
  4329. } else if (r == EMULATION_RESTART)
  4330. goto restart;
  4331. else
  4332. r = EMULATE_DONE;
  4333. if (writeback) {
  4334. toggle_interruptibility(vcpu, ctxt->interruptibility);
  4335. kvm_set_rflags(vcpu, ctxt->eflags);
  4336. kvm_make_request(KVM_REQ_EVENT, vcpu);
  4337. vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
  4338. kvm_rip_write(vcpu, ctxt->eip);
  4339. } else
  4340. vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
  4341. return r;
  4342. }
  4343. EXPORT_SYMBOL_GPL(x86_emulate_instruction);
  4344. int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size, unsigned short port)
  4345. {
  4346. unsigned long val = kvm_register_read(vcpu, VCPU_REGS_RAX);
  4347. int ret = emulator_pio_out_emulated(&vcpu->arch.emulate_ctxt,
  4348. size, port, &val, 1);
  4349. /* do not return to emulator after return from userspace */
  4350. vcpu->arch.pio.count = 0;
  4351. return ret;
  4352. }
  4353. EXPORT_SYMBOL_GPL(kvm_fast_pio_out);
  4354. static void tsc_bad(void *info)
  4355. {
  4356. __this_cpu_write(cpu_tsc_khz, 0);
  4357. }
  4358. static void tsc_khz_changed(void *data)
  4359. {
  4360. struct cpufreq_freqs *freq = data;
  4361. unsigned long khz = 0;
  4362. if (data)
  4363. khz = freq->new;
  4364. else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
  4365. khz = cpufreq_quick_get(raw_smp_processor_id());
  4366. if (!khz)
  4367. khz = tsc_khz;
  4368. __this_cpu_write(cpu_tsc_khz, khz);
  4369. }
  4370. static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
  4371. void *data)
  4372. {
  4373. struct cpufreq_freqs *freq = data;
  4374. struct kvm *kvm;
  4375. struct kvm_vcpu *vcpu;
  4376. int i, send_ipi = 0;
  4377. /*
  4378. * We allow guests to temporarily run on slowing clocks,
  4379. * provided we notify them after, or to run on accelerating
  4380. * clocks, provided we notify them before. Thus time never
  4381. * goes backwards.
  4382. *
  4383. * However, we have a problem. We can't atomically update
  4384. * the frequency of a given CPU from this function; it is
  4385. * merely a notifier, which can be called from any CPU.
  4386. * Changing the TSC frequency at arbitrary points in time
  4387. * requires a recomputation of local variables related to
  4388. * the TSC for each VCPU. We must flag these local variables
  4389. * to be updated and be sure the update takes place with the
  4390. * new frequency before any guests proceed.
  4391. *
  4392. * Unfortunately, the combination of hotplug CPU and frequency
  4393. * change creates an intractable locking scenario; the order
  4394. * of when these callouts happen is undefined with respect to
  4395. * CPU hotplug, and they can race with each other. As such,
  4396. * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
  4397. * undefined; you can actually have a CPU frequency change take
  4398. * place in between the computation of X and the setting of the
  4399. * variable. To protect against this problem, all updates of
  4400. * the per_cpu tsc_khz variable are done in an interrupt
  4401. * protected IPI, and all callers wishing to update the value
  4402. * must wait for a synchronous IPI to complete (which is trivial
  4403. * if the caller is on the CPU already). This establishes the
  4404. * necessary total order on variable updates.
  4405. *
  4406. * Note that because a guest time update may take place
  4407. * anytime after the setting of the VCPU's request bit, the
  4408. * correct TSC value must be set before the request. However,
  4409. * to ensure the update actually makes it to any guest which
  4410. * starts running in hardware virtualization between the set
  4411. * and the acquisition of the spinlock, we must also ping the
  4412. * CPU after setting the request bit.
  4413. *
  4414. */
  4415. if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
  4416. return 0;
  4417. if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
  4418. return 0;
  4419. smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
  4420. raw_spin_lock(&kvm_lock);
  4421. list_for_each_entry(kvm, &vm_list, vm_list) {
  4422. kvm_for_each_vcpu(i, vcpu, kvm) {
  4423. if (vcpu->cpu != freq->cpu)
  4424. continue;
  4425. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  4426. if (vcpu->cpu != smp_processor_id())
  4427. send_ipi = 1;
  4428. }
  4429. }
  4430. raw_spin_unlock(&kvm_lock);
  4431. if (freq->old < freq->new && send_ipi) {
  4432. /*
  4433. * We upscale the frequency. Must make the guest
  4434. * doesn't see old kvmclock values while running with
  4435. * the new frequency, otherwise we risk the guest sees
  4436. * time go backwards.
  4437. *
  4438. * In case we update the frequency for another cpu
  4439. * (which might be in guest context) send an interrupt
  4440. * to kick the cpu out of guest context. Next time
  4441. * guest context is entered kvmclock will be updated,
  4442. * so the guest will not see stale values.
  4443. */
  4444. smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
  4445. }
  4446. return 0;
  4447. }
  4448. static struct notifier_block kvmclock_cpufreq_notifier_block = {
  4449. .notifier_call = kvmclock_cpufreq_notifier
  4450. };
  4451. static int kvmclock_cpu_notifier(struct notifier_block *nfb,
  4452. unsigned long action, void *hcpu)
  4453. {
  4454. unsigned int cpu = (unsigned long)hcpu;
  4455. switch (action) {
  4456. case CPU_ONLINE:
  4457. case CPU_DOWN_FAILED:
  4458. smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
  4459. break;
  4460. case CPU_DOWN_PREPARE:
  4461. smp_call_function_single(cpu, tsc_bad, NULL, 1);
  4462. break;
  4463. }
  4464. return NOTIFY_OK;
  4465. }
  4466. static struct notifier_block kvmclock_cpu_notifier_block = {
  4467. .notifier_call = kvmclock_cpu_notifier,
  4468. .priority = -INT_MAX
  4469. };
  4470. static void kvm_timer_init(void)
  4471. {
  4472. int cpu;
  4473. max_tsc_khz = tsc_khz;
  4474. register_hotcpu_notifier(&kvmclock_cpu_notifier_block);
  4475. if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
  4476. #ifdef CONFIG_CPU_FREQ
  4477. struct cpufreq_policy policy;
  4478. memset(&policy, 0, sizeof(policy));
  4479. cpu = get_cpu();
  4480. cpufreq_get_policy(&policy, cpu);
  4481. if (policy.cpuinfo.max_freq)
  4482. max_tsc_khz = policy.cpuinfo.max_freq;
  4483. put_cpu();
  4484. #endif
  4485. cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
  4486. CPUFREQ_TRANSITION_NOTIFIER);
  4487. }
  4488. pr_debug("kvm: max_tsc_khz = %ld\n", max_tsc_khz);
  4489. for_each_online_cpu(cpu)
  4490. smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
  4491. }
  4492. static DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
  4493. int kvm_is_in_guest(void)
  4494. {
  4495. return __this_cpu_read(current_vcpu) != NULL;
  4496. }
  4497. static int kvm_is_user_mode(void)
  4498. {
  4499. int user_mode = 3;
  4500. if (__this_cpu_read(current_vcpu))
  4501. user_mode = kvm_x86_ops->get_cpl(__this_cpu_read(current_vcpu));
  4502. return user_mode != 0;
  4503. }
  4504. static unsigned long kvm_get_guest_ip(void)
  4505. {
  4506. unsigned long ip = 0;
  4507. if (__this_cpu_read(current_vcpu))
  4508. ip = kvm_rip_read(__this_cpu_read(current_vcpu));
  4509. return ip;
  4510. }
  4511. static struct perf_guest_info_callbacks kvm_guest_cbs = {
  4512. .is_in_guest = kvm_is_in_guest,
  4513. .is_user_mode = kvm_is_user_mode,
  4514. .get_guest_ip = kvm_get_guest_ip,
  4515. };
  4516. void kvm_before_handle_nmi(struct kvm_vcpu *vcpu)
  4517. {
  4518. __this_cpu_write(current_vcpu, vcpu);
  4519. }
  4520. EXPORT_SYMBOL_GPL(kvm_before_handle_nmi);
  4521. void kvm_after_handle_nmi(struct kvm_vcpu *vcpu)
  4522. {
  4523. __this_cpu_write(current_vcpu, NULL);
  4524. }
  4525. EXPORT_SYMBOL_GPL(kvm_after_handle_nmi);
  4526. static void kvm_set_mmio_spte_mask(void)
  4527. {
  4528. u64 mask;
  4529. int maxphyaddr = boot_cpu_data.x86_phys_bits;
  4530. /*
  4531. * Set the reserved bits and the present bit of an paging-structure
  4532. * entry to generate page fault with PFER.RSV = 1.
  4533. */
  4534. mask = ((1ull << (62 - maxphyaddr + 1)) - 1) << maxphyaddr;
  4535. mask |= 1ull;
  4536. #ifdef CONFIG_X86_64
  4537. /*
  4538. * If reserved bit is not supported, clear the present bit to disable
  4539. * mmio page fault.
  4540. */
  4541. if (maxphyaddr == 52)
  4542. mask &= ~1ull;
  4543. #endif
  4544. kvm_mmu_set_mmio_spte_mask(mask);
  4545. }
  4546. #ifdef CONFIG_X86_64
  4547. static void pvclock_gtod_update_fn(struct work_struct *work)
  4548. {
  4549. struct kvm *kvm;
  4550. struct kvm_vcpu *vcpu;
  4551. int i;
  4552. raw_spin_lock(&kvm_lock);
  4553. list_for_each_entry(kvm, &vm_list, vm_list)
  4554. kvm_for_each_vcpu(i, vcpu, kvm)
  4555. set_bit(KVM_REQ_MASTERCLOCK_UPDATE, &vcpu->requests);
  4556. atomic_set(&kvm_guest_has_master_clock, 0);
  4557. raw_spin_unlock(&kvm_lock);
  4558. }
  4559. static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
  4560. /*
  4561. * Notification about pvclock gtod data update.
  4562. */
  4563. static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
  4564. void *priv)
  4565. {
  4566. struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
  4567. struct timekeeper *tk = priv;
  4568. update_pvclock_gtod(tk);
  4569. /* disable master clock if host does not trust, or does not
  4570. * use, TSC clocksource
  4571. */
  4572. if (gtod->clock.vclock_mode != VCLOCK_TSC &&
  4573. atomic_read(&kvm_guest_has_master_clock) != 0)
  4574. queue_work(system_long_wq, &pvclock_gtod_work);
  4575. return 0;
  4576. }
  4577. static struct notifier_block pvclock_gtod_notifier = {
  4578. .notifier_call = pvclock_gtod_notify,
  4579. };
  4580. #endif
  4581. int kvm_arch_init(void *opaque)
  4582. {
  4583. int r;
  4584. struct kvm_x86_ops *ops = (struct kvm_x86_ops *)opaque;
  4585. if (kvm_x86_ops) {
  4586. printk(KERN_ERR "kvm: already loaded the other module\n");
  4587. r = -EEXIST;
  4588. goto out;
  4589. }
  4590. if (!ops->cpu_has_kvm_support()) {
  4591. printk(KERN_ERR "kvm: no hardware support\n");
  4592. r = -EOPNOTSUPP;
  4593. goto out;
  4594. }
  4595. if (ops->disabled_by_bios()) {
  4596. printk(KERN_ERR "kvm: disabled by bios\n");
  4597. r = -EOPNOTSUPP;
  4598. goto out;
  4599. }
  4600. r = -ENOMEM;
  4601. shared_msrs = alloc_percpu(struct kvm_shared_msrs);
  4602. if (!shared_msrs) {
  4603. printk(KERN_ERR "kvm: failed to allocate percpu kvm_shared_msrs\n");
  4604. goto out;
  4605. }
  4606. r = kvm_mmu_module_init();
  4607. if (r)
  4608. goto out_free_percpu;
  4609. kvm_set_mmio_spte_mask();
  4610. kvm_init_msr_list();
  4611. kvm_x86_ops = ops;
  4612. kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
  4613. PT_DIRTY_MASK, PT64_NX_MASK, 0);
  4614. kvm_timer_init();
  4615. perf_register_guest_info_callbacks(&kvm_guest_cbs);
  4616. if (cpu_has_xsave)
  4617. host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
  4618. kvm_lapic_init();
  4619. #ifdef CONFIG_X86_64
  4620. pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
  4621. #endif
  4622. return 0;
  4623. out_free_percpu:
  4624. free_percpu(shared_msrs);
  4625. out:
  4626. return r;
  4627. }
  4628. void kvm_arch_exit(void)
  4629. {
  4630. perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
  4631. if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
  4632. cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
  4633. CPUFREQ_TRANSITION_NOTIFIER);
  4634. unregister_hotcpu_notifier(&kvmclock_cpu_notifier_block);
  4635. #ifdef CONFIG_X86_64
  4636. pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
  4637. #endif
  4638. kvm_x86_ops = NULL;
  4639. kvm_mmu_module_exit();
  4640. free_percpu(shared_msrs);
  4641. }
  4642. int kvm_emulate_halt(struct kvm_vcpu *vcpu)
  4643. {
  4644. ++vcpu->stat.halt_exits;
  4645. if (irqchip_in_kernel(vcpu->kvm)) {
  4646. vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
  4647. return 1;
  4648. } else {
  4649. vcpu->run->exit_reason = KVM_EXIT_HLT;
  4650. return 0;
  4651. }
  4652. }
  4653. EXPORT_SYMBOL_GPL(kvm_emulate_halt);
  4654. int kvm_hv_hypercall(struct kvm_vcpu *vcpu)
  4655. {
  4656. u64 param, ingpa, outgpa, ret;
  4657. uint16_t code, rep_idx, rep_cnt, res = HV_STATUS_SUCCESS, rep_done = 0;
  4658. bool fast, longmode;
  4659. int cs_db, cs_l;
  4660. /*
  4661. * hypercall generates UD from non zero cpl and real mode
  4662. * per HYPER-V spec
  4663. */
  4664. if (kvm_x86_ops->get_cpl(vcpu) != 0 || !is_protmode(vcpu)) {
  4665. kvm_queue_exception(vcpu, UD_VECTOR);
  4666. return 0;
  4667. }
  4668. kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
  4669. longmode = is_long_mode(vcpu) && cs_l == 1;
  4670. if (!longmode) {
  4671. param = ((u64)kvm_register_read(vcpu, VCPU_REGS_RDX) << 32) |
  4672. (kvm_register_read(vcpu, VCPU_REGS_RAX) & 0xffffffff);
  4673. ingpa = ((u64)kvm_register_read(vcpu, VCPU_REGS_RBX) << 32) |
  4674. (kvm_register_read(vcpu, VCPU_REGS_RCX) & 0xffffffff);
  4675. outgpa = ((u64)kvm_register_read(vcpu, VCPU_REGS_RDI) << 32) |
  4676. (kvm_register_read(vcpu, VCPU_REGS_RSI) & 0xffffffff);
  4677. }
  4678. #ifdef CONFIG_X86_64
  4679. else {
  4680. param = kvm_register_read(vcpu, VCPU_REGS_RCX);
  4681. ingpa = kvm_register_read(vcpu, VCPU_REGS_RDX);
  4682. outgpa = kvm_register_read(vcpu, VCPU_REGS_R8);
  4683. }
  4684. #endif
  4685. code = param & 0xffff;
  4686. fast = (param >> 16) & 0x1;
  4687. rep_cnt = (param >> 32) & 0xfff;
  4688. rep_idx = (param >> 48) & 0xfff;
  4689. trace_kvm_hv_hypercall(code, fast, rep_cnt, rep_idx, ingpa, outgpa);
  4690. switch (code) {
  4691. case HV_X64_HV_NOTIFY_LONG_SPIN_WAIT:
  4692. kvm_vcpu_on_spin(vcpu);
  4693. break;
  4694. default:
  4695. res = HV_STATUS_INVALID_HYPERCALL_CODE;
  4696. break;
  4697. }
  4698. ret = res | (((u64)rep_done & 0xfff) << 32);
  4699. if (longmode) {
  4700. kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
  4701. } else {
  4702. kvm_register_write(vcpu, VCPU_REGS_RDX, ret >> 32);
  4703. kvm_register_write(vcpu, VCPU_REGS_RAX, ret & 0xffffffff);
  4704. }
  4705. return 1;
  4706. }
  4707. int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
  4708. {
  4709. unsigned long nr, a0, a1, a2, a3, ret;
  4710. int r = 1;
  4711. if (kvm_hv_hypercall_enabled(vcpu->kvm))
  4712. return kvm_hv_hypercall(vcpu);
  4713. nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
  4714. a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
  4715. a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
  4716. a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
  4717. a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
  4718. trace_kvm_hypercall(nr, a0, a1, a2, a3);
  4719. if (!is_long_mode(vcpu)) {
  4720. nr &= 0xFFFFFFFF;
  4721. a0 &= 0xFFFFFFFF;
  4722. a1 &= 0xFFFFFFFF;
  4723. a2 &= 0xFFFFFFFF;
  4724. a3 &= 0xFFFFFFFF;
  4725. }
  4726. if (kvm_x86_ops->get_cpl(vcpu) != 0) {
  4727. ret = -KVM_EPERM;
  4728. goto out;
  4729. }
  4730. switch (nr) {
  4731. case KVM_HC_VAPIC_POLL_IRQ:
  4732. ret = 0;
  4733. break;
  4734. default:
  4735. ret = -KVM_ENOSYS;
  4736. break;
  4737. }
  4738. out:
  4739. kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
  4740. ++vcpu->stat.hypercalls;
  4741. return r;
  4742. }
  4743. EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
  4744. static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
  4745. {
  4746. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  4747. char instruction[3];
  4748. unsigned long rip = kvm_rip_read(vcpu);
  4749. /*
  4750. * Blow out the MMU to ensure that no other VCPU has an active mapping
  4751. * to ensure that the updated hypercall appears atomically across all
  4752. * VCPUs.
  4753. */
  4754. kvm_mmu_zap_all(vcpu->kvm);
  4755. kvm_x86_ops->patch_hypercall(vcpu, instruction);
  4756. return emulator_write_emulated(ctxt, rip, instruction, 3, NULL);
  4757. }
  4758. /*
  4759. * Check if userspace requested an interrupt window, and that the
  4760. * interrupt window is open.
  4761. *
  4762. * No need to exit to userspace if we already have an interrupt queued.
  4763. */
  4764. static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
  4765. {
  4766. return (!irqchip_in_kernel(vcpu->kvm) && !kvm_cpu_has_interrupt(vcpu) &&
  4767. vcpu->run->request_interrupt_window &&
  4768. kvm_arch_interrupt_allowed(vcpu));
  4769. }
  4770. static void post_kvm_run_save(struct kvm_vcpu *vcpu)
  4771. {
  4772. struct kvm_run *kvm_run = vcpu->run;
  4773. kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
  4774. kvm_run->cr8 = kvm_get_cr8(vcpu);
  4775. kvm_run->apic_base = kvm_get_apic_base(vcpu);
  4776. if (irqchip_in_kernel(vcpu->kvm))
  4777. kvm_run->ready_for_interrupt_injection = 1;
  4778. else
  4779. kvm_run->ready_for_interrupt_injection =
  4780. kvm_arch_interrupt_allowed(vcpu) &&
  4781. !kvm_cpu_has_interrupt(vcpu) &&
  4782. !kvm_event_needs_reinjection(vcpu);
  4783. }
  4784. static int vapic_enter(struct kvm_vcpu *vcpu)
  4785. {
  4786. struct kvm_lapic *apic = vcpu->arch.apic;
  4787. struct page *page;
  4788. if (!apic || !apic->vapic_addr)
  4789. return 0;
  4790. page = gfn_to_page(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
  4791. if (is_error_page(page))
  4792. return -EFAULT;
  4793. vcpu->arch.apic->vapic_page = page;
  4794. return 0;
  4795. }
  4796. static void vapic_exit(struct kvm_vcpu *vcpu)
  4797. {
  4798. struct kvm_lapic *apic = vcpu->arch.apic;
  4799. int idx;
  4800. if (!apic || !apic->vapic_addr)
  4801. return;
  4802. idx = srcu_read_lock(&vcpu->kvm->srcu);
  4803. kvm_release_page_dirty(apic->vapic_page);
  4804. mark_page_dirty(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
  4805. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  4806. }
  4807. static void update_cr8_intercept(struct kvm_vcpu *vcpu)
  4808. {
  4809. int max_irr, tpr;
  4810. if (!kvm_x86_ops->update_cr8_intercept)
  4811. return;
  4812. if (!vcpu->arch.apic)
  4813. return;
  4814. if (!vcpu->arch.apic->vapic_addr)
  4815. max_irr = kvm_lapic_find_highest_irr(vcpu);
  4816. else
  4817. max_irr = -1;
  4818. if (max_irr != -1)
  4819. max_irr >>= 4;
  4820. tpr = kvm_lapic_get_cr8(vcpu);
  4821. kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
  4822. }
  4823. static void inject_pending_event(struct kvm_vcpu *vcpu)
  4824. {
  4825. /* try to reinject previous events if any */
  4826. if (vcpu->arch.exception.pending) {
  4827. trace_kvm_inj_exception(vcpu->arch.exception.nr,
  4828. vcpu->arch.exception.has_error_code,
  4829. vcpu->arch.exception.error_code);
  4830. kvm_x86_ops->queue_exception(vcpu, vcpu->arch.exception.nr,
  4831. vcpu->arch.exception.has_error_code,
  4832. vcpu->arch.exception.error_code,
  4833. vcpu->arch.exception.reinject);
  4834. return;
  4835. }
  4836. if (vcpu->arch.nmi_injected) {
  4837. kvm_x86_ops->set_nmi(vcpu);
  4838. return;
  4839. }
  4840. if (vcpu->arch.interrupt.pending) {
  4841. kvm_x86_ops->set_irq(vcpu);
  4842. return;
  4843. }
  4844. /* try to inject new event if pending */
  4845. if (vcpu->arch.nmi_pending) {
  4846. if (kvm_x86_ops->nmi_allowed(vcpu)) {
  4847. --vcpu->arch.nmi_pending;
  4848. vcpu->arch.nmi_injected = true;
  4849. kvm_x86_ops->set_nmi(vcpu);
  4850. }
  4851. } else if (kvm_cpu_has_injectable_intr(vcpu)) {
  4852. if (kvm_x86_ops->interrupt_allowed(vcpu)) {
  4853. kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
  4854. false);
  4855. kvm_x86_ops->set_irq(vcpu);
  4856. }
  4857. }
  4858. }
  4859. static void kvm_load_guest_xcr0(struct kvm_vcpu *vcpu)
  4860. {
  4861. if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE) &&
  4862. !vcpu->guest_xcr0_loaded) {
  4863. /* kvm_set_xcr() also depends on this */
  4864. xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
  4865. vcpu->guest_xcr0_loaded = 1;
  4866. }
  4867. }
  4868. static void kvm_put_guest_xcr0(struct kvm_vcpu *vcpu)
  4869. {
  4870. if (vcpu->guest_xcr0_loaded) {
  4871. if (vcpu->arch.xcr0 != host_xcr0)
  4872. xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
  4873. vcpu->guest_xcr0_loaded = 0;
  4874. }
  4875. }
  4876. static void process_nmi(struct kvm_vcpu *vcpu)
  4877. {
  4878. unsigned limit = 2;
  4879. /*
  4880. * x86 is limited to one NMI running, and one NMI pending after it.
  4881. * If an NMI is already in progress, limit further NMIs to just one.
  4882. * Otherwise, allow two (and we'll inject the first one immediately).
  4883. */
  4884. if (kvm_x86_ops->get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
  4885. limit = 1;
  4886. vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
  4887. vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
  4888. kvm_make_request(KVM_REQ_EVENT, vcpu);
  4889. }
  4890. static void kvm_gen_update_masterclock(struct kvm *kvm)
  4891. {
  4892. #ifdef CONFIG_X86_64
  4893. int i;
  4894. struct kvm_vcpu *vcpu;
  4895. struct kvm_arch *ka = &kvm->arch;
  4896. spin_lock(&ka->pvclock_gtod_sync_lock);
  4897. kvm_make_mclock_inprogress_request(kvm);
  4898. /* no guest entries from this point */
  4899. pvclock_update_vm_gtod_copy(kvm);
  4900. kvm_for_each_vcpu(i, vcpu, kvm)
  4901. set_bit(KVM_REQ_CLOCK_UPDATE, &vcpu->requests);
  4902. /* guest entries allowed */
  4903. kvm_for_each_vcpu(i, vcpu, kvm)
  4904. clear_bit(KVM_REQ_MCLOCK_INPROGRESS, &vcpu->requests);
  4905. spin_unlock(&ka->pvclock_gtod_sync_lock);
  4906. #endif
  4907. }
  4908. static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
  4909. {
  4910. u64 eoi_exit_bitmap[4];
  4911. u32 tmr[8];
  4912. if (!kvm_apic_hw_enabled(vcpu->arch.apic))
  4913. return;
  4914. memset(eoi_exit_bitmap, 0, 32);
  4915. memset(tmr, 0, 32);
  4916. kvm_ioapic_scan_entry(vcpu, eoi_exit_bitmap, tmr);
  4917. kvm_x86_ops->load_eoi_exitmap(vcpu, eoi_exit_bitmap);
  4918. kvm_apic_update_tmr(vcpu, tmr);
  4919. }
  4920. static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
  4921. {
  4922. int r;
  4923. bool req_int_win = !irqchip_in_kernel(vcpu->kvm) &&
  4924. vcpu->run->request_interrupt_window;
  4925. bool req_immediate_exit = false;
  4926. if (vcpu->requests) {
  4927. if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
  4928. kvm_mmu_unload(vcpu);
  4929. if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
  4930. __kvm_migrate_timers(vcpu);
  4931. if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
  4932. kvm_gen_update_masterclock(vcpu->kvm);
  4933. if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
  4934. r = kvm_guest_time_update(vcpu);
  4935. if (unlikely(r))
  4936. goto out;
  4937. }
  4938. if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
  4939. kvm_mmu_sync_roots(vcpu);
  4940. if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
  4941. kvm_x86_ops->tlb_flush(vcpu);
  4942. if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
  4943. vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
  4944. r = 0;
  4945. goto out;
  4946. }
  4947. if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
  4948. vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
  4949. r = 0;
  4950. goto out;
  4951. }
  4952. if (kvm_check_request(KVM_REQ_DEACTIVATE_FPU, vcpu)) {
  4953. vcpu->fpu_active = 0;
  4954. kvm_x86_ops->fpu_deactivate(vcpu);
  4955. }
  4956. if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
  4957. /* Page is swapped out. Do synthetic halt */
  4958. vcpu->arch.apf.halted = true;
  4959. r = 1;
  4960. goto out;
  4961. }
  4962. if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
  4963. record_steal_time(vcpu);
  4964. if (kvm_check_request(KVM_REQ_NMI, vcpu))
  4965. process_nmi(vcpu);
  4966. if (kvm_check_request(KVM_REQ_PMU, vcpu))
  4967. kvm_handle_pmu_event(vcpu);
  4968. if (kvm_check_request(KVM_REQ_PMI, vcpu))
  4969. kvm_deliver_pmi(vcpu);
  4970. if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
  4971. vcpu_scan_ioapic(vcpu);
  4972. }
  4973. if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
  4974. kvm_apic_accept_events(vcpu);
  4975. if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
  4976. r = 1;
  4977. goto out;
  4978. }
  4979. inject_pending_event(vcpu);
  4980. /* enable NMI/IRQ window open exits if needed */
  4981. if (vcpu->arch.nmi_pending)
  4982. kvm_x86_ops->enable_nmi_window(vcpu);
  4983. else if (kvm_cpu_has_injectable_intr(vcpu) || req_int_win)
  4984. req_immediate_exit =
  4985. kvm_x86_ops->enable_irq_window(vcpu) != 0;
  4986. if (kvm_lapic_enabled(vcpu)) {
  4987. /*
  4988. * Update architecture specific hints for APIC
  4989. * virtual interrupt delivery.
  4990. */
  4991. if (kvm_x86_ops->hwapic_irr_update)
  4992. kvm_x86_ops->hwapic_irr_update(vcpu,
  4993. kvm_lapic_find_highest_irr(vcpu));
  4994. update_cr8_intercept(vcpu);
  4995. kvm_lapic_sync_to_vapic(vcpu);
  4996. }
  4997. }
  4998. r = kvm_mmu_reload(vcpu);
  4999. if (unlikely(r)) {
  5000. goto cancel_injection;
  5001. }
  5002. preempt_disable();
  5003. kvm_x86_ops->prepare_guest_switch(vcpu);
  5004. if (vcpu->fpu_active)
  5005. kvm_load_guest_fpu(vcpu);
  5006. kvm_load_guest_xcr0(vcpu);
  5007. vcpu->mode = IN_GUEST_MODE;
  5008. /* We should set ->mode before check ->requests,
  5009. * see the comment in make_all_cpus_request.
  5010. */
  5011. smp_mb();
  5012. local_irq_disable();
  5013. if (vcpu->mode == EXITING_GUEST_MODE || vcpu->requests
  5014. || need_resched() || signal_pending(current)) {
  5015. vcpu->mode = OUTSIDE_GUEST_MODE;
  5016. smp_wmb();
  5017. local_irq_enable();
  5018. preempt_enable();
  5019. r = 1;
  5020. goto cancel_injection;
  5021. }
  5022. srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
  5023. if (req_immediate_exit)
  5024. smp_send_reschedule(vcpu->cpu);
  5025. kvm_guest_enter();
  5026. if (unlikely(vcpu->arch.switch_db_regs)) {
  5027. set_debugreg(0, 7);
  5028. set_debugreg(vcpu->arch.eff_db[0], 0);
  5029. set_debugreg(vcpu->arch.eff_db[1], 1);
  5030. set_debugreg(vcpu->arch.eff_db[2], 2);
  5031. set_debugreg(vcpu->arch.eff_db[3], 3);
  5032. }
  5033. trace_kvm_entry(vcpu->vcpu_id);
  5034. kvm_x86_ops->run(vcpu);
  5035. /*
  5036. * If the guest has used debug registers, at least dr7
  5037. * will be disabled while returning to the host.
  5038. * If we don't have active breakpoints in the host, we don't
  5039. * care about the messed up debug address registers. But if
  5040. * we have some of them active, restore the old state.
  5041. */
  5042. if (hw_breakpoint_active())
  5043. hw_breakpoint_restore();
  5044. vcpu->arch.last_guest_tsc = kvm_x86_ops->read_l1_tsc(vcpu,
  5045. native_read_tsc());
  5046. vcpu->mode = OUTSIDE_GUEST_MODE;
  5047. smp_wmb();
  5048. /* Interrupt is enabled by handle_external_intr() */
  5049. kvm_x86_ops->handle_external_intr(vcpu);
  5050. ++vcpu->stat.exits;
  5051. /*
  5052. * We must have an instruction between local_irq_enable() and
  5053. * kvm_guest_exit(), so the timer interrupt isn't delayed by
  5054. * the interrupt shadow. The stat.exits increment will do nicely.
  5055. * But we need to prevent reordering, hence this barrier():
  5056. */
  5057. barrier();
  5058. kvm_guest_exit();
  5059. preempt_enable();
  5060. vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
  5061. /*
  5062. * Profile KVM exit RIPs:
  5063. */
  5064. if (unlikely(prof_on == KVM_PROFILING)) {
  5065. unsigned long rip = kvm_rip_read(vcpu);
  5066. profile_hit(KVM_PROFILING, (void *)rip);
  5067. }
  5068. if (unlikely(vcpu->arch.tsc_always_catchup))
  5069. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  5070. if (vcpu->arch.apic_attention)
  5071. kvm_lapic_sync_from_vapic(vcpu);
  5072. r = kvm_x86_ops->handle_exit(vcpu);
  5073. return r;
  5074. cancel_injection:
  5075. kvm_x86_ops->cancel_injection(vcpu);
  5076. if (unlikely(vcpu->arch.apic_attention))
  5077. kvm_lapic_sync_from_vapic(vcpu);
  5078. out:
  5079. return r;
  5080. }
  5081. static int __vcpu_run(struct kvm_vcpu *vcpu)
  5082. {
  5083. int r;
  5084. struct kvm *kvm = vcpu->kvm;
  5085. vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
  5086. r = vapic_enter(vcpu);
  5087. if (r) {
  5088. srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
  5089. return r;
  5090. }
  5091. r = 1;
  5092. while (r > 0) {
  5093. if (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
  5094. !vcpu->arch.apf.halted)
  5095. r = vcpu_enter_guest(vcpu);
  5096. else {
  5097. srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
  5098. kvm_vcpu_block(vcpu);
  5099. vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
  5100. if (kvm_check_request(KVM_REQ_UNHALT, vcpu)) {
  5101. kvm_apic_accept_events(vcpu);
  5102. switch(vcpu->arch.mp_state) {
  5103. case KVM_MP_STATE_HALTED:
  5104. vcpu->arch.mp_state =
  5105. KVM_MP_STATE_RUNNABLE;
  5106. case KVM_MP_STATE_RUNNABLE:
  5107. vcpu->arch.apf.halted = false;
  5108. break;
  5109. case KVM_MP_STATE_INIT_RECEIVED:
  5110. break;
  5111. default:
  5112. r = -EINTR;
  5113. break;
  5114. }
  5115. }
  5116. }
  5117. if (r <= 0)
  5118. break;
  5119. clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);
  5120. if (kvm_cpu_has_pending_timer(vcpu))
  5121. kvm_inject_pending_timer_irqs(vcpu);
  5122. if (dm_request_for_irq_injection(vcpu)) {
  5123. r = -EINTR;
  5124. vcpu->run->exit_reason = KVM_EXIT_INTR;
  5125. ++vcpu->stat.request_irq_exits;
  5126. }
  5127. kvm_check_async_pf_completion(vcpu);
  5128. if (signal_pending(current)) {
  5129. r = -EINTR;
  5130. vcpu->run->exit_reason = KVM_EXIT_INTR;
  5131. ++vcpu->stat.signal_exits;
  5132. }
  5133. if (need_resched()) {
  5134. srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
  5135. kvm_resched(vcpu);
  5136. vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
  5137. }
  5138. }
  5139. srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
  5140. vapic_exit(vcpu);
  5141. return r;
  5142. }
  5143. static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
  5144. {
  5145. int r;
  5146. vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
  5147. r = emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
  5148. srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
  5149. if (r != EMULATE_DONE)
  5150. return 0;
  5151. return 1;
  5152. }
  5153. static int complete_emulated_pio(struct kvm_vcpu *vcpu)
  5154. {
  5155. BUG_ON(!vcpu->arch.pio.count);
  5156. return complete_emulated_io(vcpu);
  5157. }
  5158. /*
  5159. * Implements the following, as a state machine:
  5160. *
  5161. * read:
  5162. * for each fragment
  5163. * for each mmio piece in the fragment
  5164. * write gpa, len
  5165. * exit
  5166. * copy data
  5167. * execute insn
  5168. *
  5169. * write:
  5170. * for each fragment
  5171. * for each mmio piece in the fragment
  5172. * write gpa, len
  5173. * copy data
  5174. * exit
  5175. */
  5176. static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
  5177. {
  5178. struct kvm_run *run = vcpu->run;
  5179. struct kvm_mmio_fragment *frag;
  5180. unsigned len;
  5181. BUG_ON(!vcpu->mmio_needed);
  5182. /* Complete previous fragment */
  5183. frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
  5184. len = min(8u, frag->len);
  5185. if (!vcpu->mmio_is_write)
  5186. memcpy(frag->data, run->mmio.data, len);
  5187. if (frag->len <= 8) {
  5188. /* Switch to the next fragment. */
  5189. frag++;
  5190. vcpu->mmio_cur_fragment++;
  5191. } else {
  5192. /* Go forward to the next mmio piece. */
  5193. frag->data += len;
  5194. frag->gpa += len;
  5195. frag->len -= len;
  5196. }
  5197. if (vcpu->mmio_cur_fragment == vcpu->mmio_nr_fragments) {
  5198. vcpu->mmio_needed = 0;
  5199. if (vcpu->mmio_is_write)
  5200. return 1;
  5201. vcpu->mmio_read_completed = 1;
  5202. return complete_emulated_io(vcpu);
  5203. }
  5204. run->exit_reason = KVM_EXIT_MMIO;
  5205. run->mmio.phys_addr = frag->gpa;
  5206. if (vcpu->mmio_is_write)
  5207. memcpy(run->mmio.data, frag->data, min(8u, frag->len));
  5208. run->mmio.len = min(8u, frag->len);
  5209. run->mmio.is_write = vcpu->mmio_is_write;
  5210. vcpu->arch.complete_userspace_io = complete_emulated_mmio;
  5211. return 0;
  5212. }
  5213. int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
  5214. {
  5215. int r;
  5216. sigset_t sigsaved;
  5217. if (!tsk_used_math(current) && init_fpu(current))
  5218. return -ENOMEM;
  5219. if (vcpu->sigset_active)
  5220. sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
  5221. if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
  5222. kvm_vcpu_block(vcpu);
  5223. kvm_apic_accept_events(vcpu);
  5224. clear_bit(KVM_REQ_UNHALT, &vcpu->requests);
  5225. r = -EAGAIN;
  5226. goto out;
  5227. }
  5228. /* re-sync apic's tpr */
  5229. if (!irqchip_in_kernel(vcpu->kvm)) {
  5230. if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
  5231. r = -EINVAL;
  5232. goto out;
  5233. }
  5234. }
  5235. if (unlikely(vcpu->arch.complete_userspace_io)) {
  5236. int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
  5237. vcpu->arch.complete_userspace_io = NULL;
  5238. r = cui(vcpu);
  5239. if (r <= 0)
  5240. goto out;
  5241. } else
  5242. WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
  5243. r = __vcpu_run(vcpu);
  5244. out:
  5245. post_kvm_run_save(vcpu);
  5246. if (vcpu->sigset_active)
  5247. sigprocmask(SIG_SETMASK, &sigsaved, NULL);
  5248. return r;
  5249. }
  5250. int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
  5251. {
  5252. if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
  5253. /*
  5254. * We are here if userspace calls get_regs() in the middle of
  5255. * instruction emulation. Registers state needs to be copied
  5256. * back from emulation context to vcpu. Userspace shouldn't do
  5257. * that usually, but some bad designed PV devices (vmware
  5258. * backdoor interface) need this to work
  5259. */
  5260. emulator_writeback_register_cache(&vcpu->arch.emulate_ctxt);
  5261. vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
  5262. }
  5263. regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
  5264. regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
  5265. regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
  5266. regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
  5267. regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
  5268. regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
  5269. regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
  5270. regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
  5271. #ifdef CONFIG_X86_64
  5272. regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
  5273. regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
  5274. regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
  5275. regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
  5276. regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
  5277. regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
  5278. regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
  5279. regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
  5280. #endif
  5281. regs->rip = kvm_rip_read(vcpu);
  5282. regs->rflags = kvm_get_rflags(vcpu);
  5283. return 0;
  5284. }
  5285. int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
  5286. {
  5287. vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
  5288. vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
  5289. kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
  5290. kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
  5291. kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
  5292. kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
  5293. kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
  5294. kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
  5295. kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
  5296. kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
  5297. #ifdef CONFIG_X86_64
  5298. kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
  5299. kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
  5300. kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
  5301. kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
  5302. kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
  5303. kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
  5304. kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
  5305. kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
  5306. #endif
  5307. kvm_rip_write(vcpu, regs->rip);
  5308. kvm_set_rflags(vcpu, regs->rflags);
  5309. vcpu->arch.exception.pending = false;
  5310. kvm_make_request(KVM_REQ_EVENT, vcpu);
  5311. return 0;
  5312. }
  5313. void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
  5314. {
  5315. struct kvm_segment cs;
  5316. kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
  5317. *db = cs.db;
  5318. *l = cs.l;
  5319. }
  5320. EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
  5321. int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
  5322. struct kvm_sregs *sregs)
  5323. {
  5324. struct desc_ptr dt;
  5325. kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
  5326. kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
  5327. kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
  5328. kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
  5329. kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
  5330. kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
  5331. kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
  5332. kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
  5333. kvm_x86_ops->get_idt(vcpu, &dt);
  5334. sregs->idt.limit = dt.size;
  5335. sregs->idt.base = dt.address;
  5336. kvm_x86_ops->get_gdt(vcpu, &dt);
  5337. sregs->gdt.limit = dt.size;
  5338. sregs->gdt.base = dt.address;
  5339. sregs->cr0 = kvm_read_cr0(vcpu);
  5340. sregs->cr2 = vcpu->arch.cr2;
  5341. sregs->cr3 = kvm_read_cr3(vcpu);
  5342. sregs->cr4 = kvm_read_cr4(vcpu);
  5343. sregs->cr8 = kvm_get_cr8(vcpu);
  5344. sregs->efer = vcpu->arch.efer;
  5345. sregs->apic_base = kvm_get_apic_base(vcpu);
  5346. memset(sregs->interrupt_bitmap, 0, sizeof sregs->interrupt_bitmap);
  5347. if (vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft)
  5348. set_bit(vcpu->arch.interrupt.nr,
  5349. (unsigned long *)sregs->interrupt_bitmap);
  5350. return 0;
  5351. }
  5352. int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
  5353. struct kvm_mp_state *mp_state)
  5354. {
  5355. kvm_apic_accept_events(vcpu);
  5356. mp_state->mp_state = vcpu->arch.mp_state;
  5357. return 0;
  5358. }
  5359. int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
  5360. struct kvm_mp_state *mp_state)
  5361. {
  5362. if (!kvm_vcpu_has_lapic(vcpu) &&
  5363. mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
  5364. return -EINVAL;
  5365. if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
  5366. vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
  5367. set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
  5368. } else
  5369. vcpu->arch.mp_state = mp_state->mp_state;
  5370. kvm_make_request(KVM_REQ_EVENT, vcpu);
  5371. return 0;
  5372. }
  5373. int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
  5374. int reason, bool has_error_code, u32 error_code)
  5375. {
  5376. struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
  5377. int ret;
  5378. init_emulate_ctxt(vcpu);
  5379. ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
  5380. has_error_code, error_code);
  5381. if (ret)
  5382. return EMULATE_FAIL;
  5383. kvm_rip_write(vcpu, ctxt->eip);
  5384. kvm_set_rflags(vcpu, ctxt->eflags);
  5385. kvm_make_request(KVM_REQ_EVENT, vcpu);
  5386. return EMULATE_DONE;
  5387. }
  5388. EXPORT_SYMBOL_GPL(kvm_task_switch);
  5389. int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
  5390. struct kvm_sregs *sregs)
  5391. {
  5392. int mmu_reset_needed = 0;
  5393. int pending_vec, max_bits, idx;
  5394. struct desc_ptr dt;
  5395. if (!guest_cpuid_has_xsave(vcpu) && (sregs->cr4 & X86_CR4_OSXSAVE))
  5396. return -EINVAL;
  5397. dt.size = sregs->idt.limit;
  5398. dt.address = sregs->idt.base;
  5399. kvm_x86_ops->set_idt(vcpu, &dt);
  5400. dt.size = sregs->gdt.limit;
  5401. dt.address = sregs->gdt.base;
  5402. kvm_x86_ops->set_gdt(vcpu, &dt);
  5403. vcpu->arch.cr2 = sregs->cr2;
  5404. mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
  5405. vcpu->arch.cr3 = sregs->cr3;
  5406. __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
  5407. kvm_set_cr8(vcpu, sregs->cr8);
  5408. mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
  5409. kvm_x86_ops->set_efer(vcpu, sregs->efer);
  5410. kvm_set_apic_base(vcpu, sregs->apic_base);
  5411. mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
  5412. kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
  5413. vcpu->arch.cr0 = sregs->cr0;
  5414. mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
  5415. kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
  5416. if (sregs->cr4 & X86_CR4_OSXSAVE)
  5417. kvm_update_cpuid(vcpu);
  5418. idx = srcu_read_lock(&vcpu->kvm->srcu);
  5419. if (!is_long_mode(vcpu) && is_pae(vcpu)) {
  5420. load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
  5421. mmu_reset_needed = 1;
  5422. }
  5423. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  5424. if (mmu_reset_needed)
  5425. kvm_mmu_reset_context(vcpu);
  5426. max_bits = KVM_NR_INTERRUPTS;
  5427. pending_vec = find_first_bit(
  5428. (const unsigned long *)sregs->interrupt_bitmap, max_bits);
  5429. if (pending_vec < max_bits) {
  5430. kvm_queue_interrupt(vcpu, pending_vec, false);
  5431. pr_debug("Set back pending irq %d\n", pending_vec);
  5432. }
  5433. kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
  5434. kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
  5435. kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
  5436. kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
  5437. kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
  5438. kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
  5439. kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
  5440. kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
  5441. update_cr8_intercept(vcpu);
  5442. /* Older userspace won't unhalt the vcpu on reset. */
  5443. if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
  5444. sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
  5445. !is_protmode(vcpu))
  5446. vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
  5447. kvm_make_request(KVM_REQ_EVENT, vcpu);
  5448. return 0;
  5449. }
  5450. int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
  5451. struct kvm_guest_debug *dbg)
  5452. {
  5453. unsigned long rflags;
  5454. int i, r;
  5455. if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
  5456. r = -EBUSY;
  5457. if (vcpu->arch.exception.pending)
  5458. goto out;
  5459. if (dbg->control & KVM_GUESTDBG_INJECT_DB)
  5460. kvm_queue_exception(vcpu, DB_VECTOR);
  5461. else
  5462. kvm_queue_exception(vcpu, BP_VECTOR);
  5463. }
  5464. /*
  5465. * Read rflags as long as potentially injected trace flags are still
  5466. * filtered out.
  5467. */
  5468. rflags = kvm_get_rflags(vcpu);
  5469. vcpu->guest_debug = dbg->control;
  5470. if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
  5471. vcpu->guest_debug = 0;
  5472. if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
  5473. for (i = 0; i < KVM_NR_DB_REGS; ++i)
  5474. vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
  5475. vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
  5476. } else {
  5477. for (i = 0; i < KVM_NR_DB_REGS; i++)
  5478. vcpu->arch.eff_db[i] = vcpu->arch.db[i];
  5479. }
  5480. kvm_update_dr7(vcpu);
  5481. if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
  5482. vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
  5483. get_segment_base(vcpu, VCPU_SREG_CS);
  5484. /*
  5485. * Trigger an rflags update that will inject or remove the trace
  5486. * flags.
  5487. */
  5488. kvm_set_rflags(vcpu, rflags);
  5489. kvm_x86_ops->update_db_bp_intercept(vcpu);
  5490. r = 0;
  5491. out:
  5492. return r;
  5493. }
  5494. /*
  5495. * Translate a guest virtual address to a guest physical address.
  5496. */
  5497. int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
  5498. struct kvm_translation *tr)
  5499. {
  5500. unsigned long vaddr = tr->linear_address;
  5501. gpa_t gpa;
  5502. int idx;
  5503. idx = srcu_read_lock(&vcpu->kvm->srcu);
  5504. gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
  5505. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  5506. tr->physical_address = gpa;
  5507. tr->valid = gpa != UNMAPPED_GVA;
  5508. tr->writeable = 1;
  5509. tr->usermode = 0;
  5510. return 0;
  5511. }
  5512. int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
  5513. {
  5514. struct i387_fxsave_struct *fxsave =
  5515. &vcpu->arch.guest_fpu.state->fxsave;
  5516. memcpy(fpu->fpr, fxsave->st_space, 128);
  5517. fpu->fcw = fxsave->cwd;
  5518. fpu->fsw = fxsave->swd;
  5519. fpu->ftwx = fxsave->twd;
  5520. fpu->last_opcode = fxsave->fop;
  5521. fpu->last_ip = fxsave->rip;
  5522. fpu->last_dp = fxsave->rdp;
  5523. memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
  5524. return 0;
  5525. }
  5526. int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
  5527. {
  5528. struct i387_fxsave_struct *fxsave =
  5529. &vcpu->arch.guest_fpu.state->fxsave;
  5530. memcpy(fxsave->st_space, fpu->fpr, 128);
  5531. fxsave->cwd = fpu->fcw;
  5532. fxsave->swd = fpu->fsw;
  5533. fxsave->twd = fpu->ftwx;
  5534. fxsave->fop = fpu->last_opcode;
  5535. fxsave->rip = fpu->last_ip;
  5536. fxsave->rdp = fpu->last_dp;
  5537. memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
  5538. return 0;
  5539. }
  5540. int fx_init(struct kvm_vcpu *vcpu)
  5541. {
  5542. int err;
  5543. err = fpu_alloc(&vcpu->arch.guest_fpu);
  5544. if (err)
  5545. return err;
  5546. fpu_finit(&vcpu->arch.guest_fpu);
  5547. /*
  5548. * Ensure guest xcr0 is valid for loading
  5549. */
  5550. vcpu->arch.xcr0 = XSTATE_FP;
  5551. vcpu->arch.cr0 |= X86_CR0_ET;
  5552. return 0;
  5553. }
  5554. EXPORT_SYMBOL_GPL(fx_init);
  5555. static void fx_free(struct kvm_vcpu *vcpu)
  5556. {
  5557. fpu_free(&vcpu->arch.guest_fpu);
  5558. }
  5559. void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
  5560. {
  5561. if (vcpu->guest_fpu_loaded)
  5562. return;
  5563. /*
  5564. * Restore all possible states in the guest,
  5565. * and assume host would use all available bits.
  5566. * Guest xcr0 would be loaded later.
  5567. */
  5568. kvm_put_guest_xcr0(vcpu);
  5569. vcpu->guest_fpu_loaded = 1;
  5570. __kernel_fpu_begin();
  5571. fpu_restore_checking(&vcpu->arch.guest_fpu);
  5572. trace_kvm_fpu(1);
  5573. }
  5574. void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
  5575. {
  5576. kvm_put_guest_xcr0(vcpu);
  5577. if (!vcpu->guest_fpu_loaded)
  5578. return;
  5579. vcpu->guest_fpu_loaded = 0;
  5580. fpu_save_init(&vcpu->arch.guest_fpu);
  5581. __kernel_fpu_end();
  5582. ++vcpu->stat.fpu_reload;
  5583. kvm_make_request(KVM_REQ_DEACTIVATE_FPU, vcpu);
  5584. trace_kvm_fpu(0);
  5585. }
  5586. void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
  5587. {
  5588. kvmclock_reset(vcpu);
  5589. free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
  5590. fx_free(vcpu);
  5591. kvm_x86_ops->vcpu_free(vcpu);
  5592. }
  5593. struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
  5594. unsigned int id)
  5595. {
  5596. if (check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
  5597. printk_once(KERN_WARNING
  5598. "kvm: SMP vm created on host with unstable TSC; "
  5599. "guest TSC will not be reliable\n");
  5600. return kvm_x86_ops->vcpu_create(kvm, id);
  5601. }
  5602. int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
  5603. {
  5604. int r;
  5605. vcpu->arch.mtrr_state.have_fixed = 1;
  5606. r = vcpu_load(vcpu);
  5607. if (r)
  5608. return r;
  5609. kvm_vcpu_reset(vcpu);
  5610. r = kvm_mmu_setup(vcpu);
  5611. vcpu_put(vcpu);
  5612. return r;
  5613. }
  5614. int kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
  5615. {
  5616. int r;
  5617. struct msr_data msr;
  5618. r = vcpu_load(vcpu);
  5619. if (r)
  5620. return r;
  5621. msr.data = 0x0;
  5622. msr.index = MSR_IA32_TSC;
  5623. msr.host_initiated = true;
  5624. kvm_write_tsc(vcpu, &msr);
  5625. vcpu_put(vcpu);
  5626. return r;
  5627. }
  5628. void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
  5629. {
  5630. int r;
  5631. vcpu->arch.apf.msr_val = 0;
  5632. r = vcpu_load(vcpu);
  5633. BUG_ON(r);
  5634. kvm_mmu_unload(vcpu);
  5635. vcpu_put(vcpu);
  5636. fx_free(vcpu);
  5637. kvm_x86_ops->vcpu_free(vcpu);
  5638. }
  5639. void kvm_vcpu_reset(struct kvm_vcpu *vcpu)
  5640. {
  5641. atomic_set(&vcpu->arch.nmi_queued, 0);
  5642. vcpu->arch.nmi_pending = 0;
  5643. vcpu->arch.nmi_injected = false;
  5644. memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
  5645. vcpu->arch.dr6 = DR6_FIXED_1;
  5646. vcpu->arch.dr7 = DR7_FIXED_1;
  5647. kvm_update_dr7(vcpu);
  5648. kvm_make_request(KVM_REQ_EVENT, vcpu);
  5649. vcpu->arch.apf.msr_val = 0;
  5650. vcpu->arch.st.msr_val = 0;
  5651. kvmclock_reset(vcpu);
  5652. kvm_clear_async_pf_completion_queue(vcpu);
  5653. kvm_async_pf_hash_reset(vcpu);
  5654. vcpu->arch.apf.halted = false;
  5655. kvm_pmu_reset(vcpu);
  5656. memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
  5657. vcpu->arch.regs_avail = ~0;
  5658. vcpu->arch.regs_dirty = ~0;
  5659. kvm_x86_ops->vcpu_reset(vcpu);
  5660. }
  5661. void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, unsigned int vector)
  5662. {
  5663. struct kvm_segment cs;
  5664. kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
  5665. cs.selector = vector << 8;
  5666. cs.base = vector << 12;
  5667. kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
  5668. kvm_rip_write(vcpu, 0);
  5669. }
  5670. int kvm_arch_hardware_enable(void *garbage)
  5671. {
  5672. struct kvm *kvm;
  5673. struct kvm_vcpu *vcpu;
  5674. int i;
  5675. int ret;
  5676. u64 local_tsc;
  5677. u64 max_tsc = 0;
  5678. bool stable, backwards_tsc = false;
  5679. kvm_shared_msr_cpu_online();
  5680. ret = kvm_x86_ops->hardware_enable(garbage);
  5681. if (ret != 0)
  5682. return ret;
  5683. local_tsc = native_read_tsc();
  5684. stable = !check_tsc_unstable();
  5685. list_for_each_entry(kvm, &vm_list, vm_list) {
  5686. kvm_for_each_vcpu(i, vcpu, kvm) {
  5687. if (!stable && vcpu->cpu == smp_processor_id())
  5688. set_bit(KVM_REQ_CLOCK_UPDATE, &vcpu->requests);
  5689. if (stable && vcpu->arch.last_host_tsc > local_tsc) {
  5690. backwards_tsc = true;
  5691. if (vcpu->arch.last_host_tsc > max_tsc)
  5692. max_tsc = vcpu->arch.last_host_tsc;
  5693. }
  5694. }
  5695. }
  5696. /*
  5697. * Sometimes, even reliable TSCs go backwards. This happens on
  5698. * platforms that reset TSC during suspend or hibernate actions, but
  5699. * maintain synchronization. We must compensate. Fortunately, we can
  5700. * detect that condition here, which happens early in CPU bringup,
  5701. * before any KVM threads can be running. Unfortunately, we can't
  5702. * bring the TSCs fully up to date with real time, as we aren't yet far
  5703. * enough into CPU bringup that we know how much real time has actually
  5704. * elapsed; our helper function, get_kernel_ns() will be using boot
  5705. * variables that haven't been updated yet.
  5706. *
  5707. * So we simply find the maximum observed TSC above, then record the
  5708. * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
  5709. * the adjustment will be applied. Note that we accumulate
  5710. * adjustments, in case multiple suspend cycles happen before some VCPU
  5711. * gets a chance to run again. In the event that no KVM threads get a
  5712. * chance to run, we will miss the entire elapsed period, as we'll have
  5713. * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
  5714. * loose cycle time. This isn't too big a deal, since the loss will be
  5715. * uniform across all VCPUs (not to mention the scenario is extremely
  5716. * unlikely). It is possible that a second hibernate recovery happens
  5717. * much faster than a first, causing the observed TSC here to be
  5718. * smaller; this would require additional padding adjustment, which is
  5719. * why we set last_host_tsc to the local tsc observed here.
  5720. *
  5721. * N.B. - this code below runs only on platforms with reliable TSC,
  5722. * as that is the only way backwards_tsc is set above. Also note
  5723. * that this runs for ALL vcpus, which is not a bug; all VCPUs should
  5724. * have the same delta_cyc adjustment applied if backwards_tsc
  5725. * is detected. Note further, this adjustment is only done once,
  5726. * as we reset last_host_tsc on all VCPUs to stop this from being
  5727. * called multiple times (one for each physical CPU bringup).
  5728. *
  5729. * Platforms with unreliable TSCs don't have to deal with this, they
  5730. * will be compensated by the logic in vcpu_load, which sets the TSC to
  5731. * catchup mode. This will catchup all VCPUs to real time, but cannot
  5732. * guarantee that they stay in perfect synchronization.
  5733. */
  5734. if (backwards_tsc) {
  5735. u64 delta_cyc = max_tsc - local_tsc;
  5736. list_for_each_entry(kvm, &vm_list, vm_list) {
  5737. kvm_for_each_vcpu(i, vcpu, kvm) {
  5738. vcpu->arch.tsc_offset_adjustment += delta_cyc;
  5739. vcpu->arch.last_host_tsc = local_tsc;
  5740. set_bit(KVM_REQ_MASTERCLOCK_UPDATE,
  5741. &vcpu->requests);
  5742. }
  5743. /*
  5744. * We have to disable TSC offset matching.. if you were
  5745. * booting a VM while issuing an S4 host suspend....
  5746. * you may have some problem. Solving this issue is
  5747. * left as an exercise to the reader.
  5748. */
  5749. kvm->arch.last_tsc_nsec = 0;
  5750. kvm->arch.last_tsc_write = 0;
  5751. }
  5752. }
  5753. return 0;
  5754. }
  5755. void kvm_arch_hardware_disable(void *garbage)
  5756. {
  5757. kvm_x86_ops->hardware_disable(garbage);
  5758. drop_user_return_notifiers(garbage);
  5759. }
  5760. int kvm_arch_hardware_setup(void)
  5761. {
  5762. return kvm_x86_ops->hardware_setup();
  5763. }
  5764. void kvm_arch_hardware_unsetup(void)
  5765. {
  5766. kvm_x86_ops->hardware_unsetup();
  5767. }
  5768. void kvm_arch_check_processor_compat(void *rtn)
  5769. {
  5770. kvm_x86_ops->check_processor_compatibility(rtn);
  5771. }
  5772. bool kvm_vcpu_compatible(struct kvm_vcpu *vcpu)
  5773. {
  5774. return irqchip_in_kernel(vcpu->kvm) == (vcpu->arch.apic != NULL);
  5775. }
  5776. struct static_key kvm_no_apic_vcpu __read_mostly;
  5777. int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
  5778. {
  5779. struct page *page;
  5780. struct kvm *kvm;
  5781. int r;
  5782. BUG_ON(vcpu->kvm == NULL);
  5783. kvm = vcpu->kvm;
  5784. vcpu->arch.emulate_ctxt.ops = &emulate_ops;
  5785. if (!irqchip_in_kernel(kvm) || kvm_vcpu_is_bsp(vcpu))
  5786. vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
  5787. else
  5788. vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
  5789. page = alloc_page(GFP_KERNEL | __GFP_ZERO);
  5790. if (!page) {
  5791. r = -ENOMEM;
  5792. goto fail;
  5793. }
  5794. vcpu->arch.pio_data = page_address(page);
  5795. kvm_set_tsc_khz(vcpu, max_tsc_khz);
  5796. r = kvm_mmu_create(vcpu);
  5797. if (r < 0)
  5798. goto fail_free_pio_data;
  5799. if (irqchip_in_kernel(kvm)) {
  5800. r = kvm_create_lapic(vcpu);
  5801. if (r < 0)
  5802. goto fail_mmu_destroy;
  5803. } else
  5804. static_key_slow_inc(&kvm_no_apic_vcpu);
  5805. vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
  5806. GFP_KERNEL);
  5807. if (!vcpu->arch.mce_banks) {
  5808. r = -ENOMEM;
  5809. goto fail_free_lapic;
  5810. }
  5811. vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
  5812. if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL)) {
  5813. r = -ENOMEM;
  5814. goto fail_free_mce_banks;
  5815. }
  5816. r = fx_init(vcpu);
  5817. if (r)
  5818. goto fail_free_wbinvd_dirty_mask;
  5819. vcpu->arch.ia32_tsc_adjust_msr = 0x0;
  5820. vcpu->arch.pv_time_enabled = false;
  5821. kvm_async_pf_hash_reset(vcpu);
  5822. kvm_pmu_init(vcpu);
  5823. return 0;
  5824. fail_free_wbinvd_dirty_mask:
  5825. free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
  5826. fail_free_mce_banks:
  5827. kfree(vcpu->arch.mce_banks);
  5828. fail_free_lapic:
  5829. kvm_free_lapic(vcpu);
  5830. fail_mmu_destroy:
  5831. kvm_mmu_destroy(vcpu);
  5832. fail_free_pio_data:
  5833. free_page((unsigned long)vcpu->arch.pio_data);
  5834. fail:
  5835. return r;
  5836. }
  5837. void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
  5838. {
  5839. int idx;
  5840. kvm_pmu_destroy(vcpu);
  5841. kfree(vcpu->arch.mce_banks);
  5842. kvm_free_lapic(vcpu);
  5843. idx = srcu_read_lock(&vcpu->kvm->srcu);
  5844. kvm_mmu_destroy(vcpu);
  5845. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  5846. free_page((unsigned long)vcpu->arch.pio_data);
  5847. if (!irqchip_in_kernel(vcpu->kvm))
  5848. static_key_slow_dec(&kvm_no_apic_vcpu);
  5849. }
  5850. int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
  5851. {
  5852. if (type)
  5853. return -EINVAL;
  5854. INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
  5855. INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
  5856. /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
  5857. set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
  5858. /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
  5859. set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
  5860. &kvm->arch.irq_sources_bitmap);
  5861. raw_spin_lock_init(&kvm->arch.tsc_write_lock);
  5862. mutex_init(&kvm->arch.apic_map_lock);
  5863. spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
  5864. pvclock_update_vm_gtod_copy(kvm);
  5865. return 0;
  5866. }
  5867. static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
  5868. {
  5869. int r;
  5870. r = vcpu_load(vcpu);
  5871. BUG_ON(r);
  5872. kvm_mmu_unload(vcpu);
  5873. vcpu_put(vcpu);
  5874. }
  5875. static void kvm_free_vcpus(struct kvm *kvm)
  5876. {
  5877. unsigned int i;
  5878. struct kvm_vcpu *vcpu;
  5879. /*
  5880. * Unpin any mmu pages first.
  5881. */
  5882. kvm_for_each_vcpu(i, vcpu, kvm) {
  5883. kvm_clear_async_pf_completion_queue(vcpu);
  5884. kvm_unload_vcpu_mmu(vcpu);
  5885. }
  5886. kvm_for_each_vcpu(i, vcpu, kvm)
  5887. kvm_arch_vcpu_free(vcpu);
  5888. mutex_lock(&kvm->lock);
  5889. for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
  5890. kvm->vcpus[i] = NULL;
  5891. atomic_set(&kvm->online_vcpus, 0);
  5892. mutex_unlock(&kvm->lock);
  5893. }
  5894. void kvm_arch_sync_events(struct kvm *kvm)
  5895. {
  5896. kvm_free_all_assigned_devices(kvm);
  5897. kvm_free_pit(kvm);
  5898. }
  5899. void kvm_arch_destroy_vm(struct kvm *kvm)
  5900. {
  5901. if (current->mm == kvm->mm) {
  5902. /*
  5903. * Free memory regions allocated on behalf of userspace,
  5904. * unless the the memory map has changed due to process exit
  5905. * or fd copying.
  5906. */
  5907. struct kvm_userspace_memory_region mem;
  5908. memset(&mem, 0, sizeof(mem));
  5909. mem.slot = APIC_ACCESS_PAGE_PRIVATE_MEMSLOT;
  5910. kvm_set_memory_region(kvm, &mem);
  5911. mem.slot = IDENTITY_PAGETABLE_PRIVATE_MEMSLOT;
  5912. kvm_set_memory_region(kvm, &mem);
  5913. mem.slot = TSS_PRIVATE_MEMSLOT;
  5914. kvm_set_memory_region(kvm, &mem);
  5915. }
  5916. kvm_iommu_unmap_guest(kvm);
  5917. kfree(kvm->arch.vpic);
  5918. kfree(kvm->arch.vioapic);
  5919. kvm_free_vcpus(kvm);
  5920. if (kvm->arch.apic_access_page)
  5921. put_page(kvm->arch.apic_access_page);
  5922. if (kvm->arch.ept_identity_pagetable)
  5923. put_page(kvm->arch.ept_identity_pagetable);
  5924. kfree(rcu_dereference_check(kvm->arch.apic_map, 1));
  5925. }
  5926. void kvm_arch_free_memslot(struct kvm_memory_slot *free,
  5927. struct kvm_memory_slot *dont)
  5928. {
  5929. int i;
  5930. for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
  5931. if (!dont || free->arch.rmap[i] != dont->arch.rmap[i]) {
  5932. kvm_kvfree(free->arch.rmap[i]);
  5933. free->arch.rmap[i] = NULL;
  5934. }
  5935. if (i == 0)
  5936. continue;
  5937. if (!dont || free->arch.lpage_info[i - 1] !=
  5938. dont->arch.lpage_info[i - 1]) {
  5939. kvm_kvfree(free->arch.lpage_info[i - 1]);
  5940. free->arch.lpage_info[i - 1] = NULL;
  5941. }
  5942. }
  5943. }
  5944. int kvm_arch_create_memslot(struct kvm_memory_slot *slot, unsigned long npages)
  5945. {
  5946. int i;
  5947. for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
  5948. unsigned long ugfn;
  5949. int lpages;
  5950. int level = i + 1;
  5951. lpages = gfn_to_index(slot->base_gfn + npages - 1,
  5952. slot->base_gfn, level) + 1;
  5953. slot->arch.rmap[i] =
  5954. kvm_kvzalloc(lpages * sizeof(*slot->arch.rmap[i]));
  5955. if (!slot->arch.rmap[i])
  5956. goto out_free;
  5957. if (i == 0)
  5958. continue;
  5959. slot->arch.lpage_info[i - 1] = kvm_kvzalloc(lpages *
  5960. sizeof(*slot->arch.lpage_info[i - 1]));
  5961. if (!slot->arch.lpage_info[i - 1])
  5962. goto out_free;
  5963. if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
  5964. slot->arch.lpage_info[i - 1][0].write_count = 1;
  5965. if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
  5966. slot->arch.lpage_info[i - 1][lpages - 1].write_count = 1;
  5967. ugfn = slot->userspace_addr >> PAGE_SHIFT;
  5968. /*
  5969. * If the gfn and userspace address are not aligned wrt each
  5970. * other, or if explicitly asked to, disable large page
  5971. * support for this slot
  5972. */
  5973. if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||
  5974. !kvm_largepages_enabled()) {
  5975. unsigned long j;
  5976. for (j = 0; j < lpages; ++j)
  5977. slot->arch.lpage_info[i - 1][j].write_count = 1;
  5978. }
  5979. }
  5980. return 0;
  5981. out_free:
  5982. for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
  5983. kvm_kvfree(slot->arch.rmap[i]);
  5984. slot->arch.rmap[i] = NULL;
  5985. if (i == 0)
  5986. continue;
  5987. kvm_kvfree(slot->arch.lpage_info[i - 1]);
  5988. slot->arch.lpage_info[i - 1] = NULL;
  5989. }
  5990. return -ENOMEM;
  5991. }
  5992. int kvm_arch_prepare_memory_region(struct kvm *kvm,
  5993. struct kvm_memory_slot *memslot,
  5994. struct kvm_userspace_memory_region *mem,
  5995. enum kvm_mr_change change)
  5996. {
  5997. /*
  5998. * Only private memory slots need to be mapped here since
  5999. * KVM_SET_MEMORY_REGION ioctl is no longer supported.
  6000. */
  6001. if ((memslot->id >= KVM_USER_MEM_SLOTS) && (change == KVM_MR_CREATE)) {
  6002. unsigned long userspace_addr;
  6003. /*
  6004. * MAP_SHARED to prevent internal slot pages from being moved
  6005. * by fork()/COW.
  6006. */
  6007. userspace_addr = vm_mmap(NULL, 0, memslot->npages * PAGE_SIZE,
  6008. PROT_READ | PROT_WRITE,
  6009. MAP_SHARED | MAP_ANONYMOUS, 0);
  6010. if (IS_ERR((void *)userspace_addr))
  6011. return PTR_ERR((void *)userspace_addr);
  6012. memslot->userspace_addr = userspace_addr;
  6013. }
  6014. return 0;
  6015. }
  6016. void kvm_arch_commit_memory_region(struct kvm *kvm,
  6017. struct kvm_userspace_memory_region *mem,
  6018. const struct kvm_memory_slot *old,
  6019. enum kvm_mr_change change)
  6020. {
  6021. int nr_mmu_pages = 0;
  6022. if ((mem->slot >= KVM_USER_MEM_SLOTS) && (change == KVM_MR_DELETE)) {
  6023. int ret;
  6024. ret = vm_munmap(old->userspace_addr,
  6025. old->npages * PAGE_SIZE);
  6026. if (ret < 0)
  6027. printk(KERN_WARNING
  6028. "kvm_vm_ioctl_set_memory_region: "
  6029. "failed to munmap memory\n");
  6030. }
  6031. if (!kvm->arch.n_requested_mmu_pages)
  6032. nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
  6033. if (nr_mmu_pages)
  6034. kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
  6035. /*
  6036. * Write protect all pages for dirty logging.
  6037. * Existing largepage mappings are destroyed here and new ones will
  6038. * not be created until the end of the logging.
  6039. */
  6040. if ((change != KVM_MR_DELETE) && (mem->flags & KVM_MEM_LOG_DIRTY_PAGES))
  6041. kvm_mmu_slot_remove_write_access(kvm, mem->slot);
  6042. /*
  6043. * If memory slot is created, or moved, we need to clear all
  6044. * mmio sptes.
  6045. */
  6046. if ((change == KVM_MR_CREATE) || (change == KVM_MR_MOVE)) {
  6047. kvm_mmu_zap_mmio_sptes(kvm);
  6048. kvm_reload_remote_mmus(kvm);
  6049. }
  6050. }
  6051. void kvm_arch_flush_shadow_all(struct kvm *kvm)
  6052. {
  6053. kvm_mmu_zap_all(kvm);
  6054. kvm_reload_remote_mmus(kvm);
  6055. }
  6056. void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
  6057. struct kvm_memory_slot *slot)
  6058. {
  6059. kvm_arch_flush_shadow_all(kvm);
  6060. }
  6061. int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
  6062. {
  6063. return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
  6064. !vcpu->arch.apf.halted)
  6065. || !list_empty_careful(&vcpu->async_pf.done)
  6066. || kvm_apic_has_events(vcpu)
  6067. || atomic_read(&vcpu->arch.nmi_queued) ||
  6068. (kvm_arch_interrupt_allowed(vcpu) &&
  6069. kvm_cpu_has_interrupt(vcpu));
  6070. }
  6071. int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
  6072. {
  6073. return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
  6074. }
  6075. int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
  6076. {
  6077. return kvm_x86_ops->interrupt_allowed(vcpu);
  6078. }
  6079. bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
  6080. {
  6081. unsigned long current_rip = kvm_rip_read(vcpu) +
  6082. get_segment_base(vcpu, VCPU_SREG_CS);
  6083. return current_rip == linear_rip;
  6084. }
  6085. EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
  6086. unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
  6087. {
  6088. unsigned long rflags;
  6089. rflags = kvm_x86_ops->get_rflags(vcpu);
  6090. if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
  6091. rflags &= ~X86_EFLAGS_TF;
  6092. return rflags;
  6093. }
  6094. EXPORT_SYMBOL_GPL(kvm_get_rflags);
  6095. void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
  6096. {
  6097. if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
  6098. kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
  6099. rflags |= X86_EFLAGS_TF;
  6100. kvm_x86_ops->set_rflags(vcpu, rflags);
  6101. kvm_make_request(KVM_REQ_EVENT, vcpu);
  6102. }
  6103. EXPORT_SYMBOL_GPL(kvm_set_rflags);
  6104. void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
  6105. {
  6106. int r;
  6107. if ((vcpu->arch.mmu.direct_map != work->arch.direct_map) ||
  6108. is_error_page(work->page))
  6109. return;
  6110. r = kvm_mmu_reload(vcpu);
  6111. if (unlikely(r))
  6112. return;
  6113. if (!vcpu->arch.mmu.direct_map &&
  6114. work->arch.cr3 != vcpu->arch.mmu.get_cr3(vcpu))
  6115. return;
  6116. vcpu->arch.mmu.page_fault(vcpu, work->gva, 0, true);
  6117. }
  6118. static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
  6119. {
  6120. return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
  6121. }
  6122. static inline u32 kvm_async_pf_next_probe(u32 key)
  6123. {
  6124. return (key + 1) & (roundup_pow_of_two(ASYNC_PF_PER_VCPU) - 1);
  6125. }
  6126. static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
  6127. {
  6128. u32 key = kvm_async_pf_hash_fn(gfn);
  6129. while (vcpu->arch.apf.gfns[key] != ~0)
  6130. key = kvm_async_pf_next_probe(key);
  6131. vcpu->arch.apf.gfns[key] = gfn;
  6132. }
  6133. static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
  6134. {
  6135. int i;
  6136. u32 key = kvm_async_pf_hash_fn(gfn);
  6137. for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU) &&
  6138. (vcpu->arch.apf.gfns[key] != gfn &&
  6139. vcpu->arch.apf.gfns[key] != ~0); i++)
  6140. key = kvm_async_pf_next_probe(key);
  6141. return key;
  6142. }
  6143. bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
  6144. {
  6145. return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
  6146. }
  6147. static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
  6148. {
  6149. u32 i, j, k;
  6150. i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
  6151. while (true) {
  6152. vcpu->arch.apf.gfns[i] = ~0;
  6153. do {
  6154. j = kvm_async_pf_next_probe(j);
  6155. if (vcpu->arch.apf.gfns[j] == ~0)
  6156. return;
  6157. k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
  6158. /*
  6159. * k lies cyclically in ]i,j]
  6160. * | i.k.j |
  6161. * |....j i.k.| or |.k..j i...|
  6162. */
  6163. } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
  6164. vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
  6165. i = j;
  6166. }
  6167. }
  6168. static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
  6169. {
  6170. return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
  6171. sizeof(val));
  6172. }
  6173. void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
  6174. struct kvm_async_pf *work)
  6175. {
  6176. struct x86_exception fault;
  6177. trace_kvm_async_pf_not_present(work->arch.token, work->gva);
  6178. kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
  6179. if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
  6180. (vcpu->arch.apf.send_user_only &&
  6181. kvm_x86_ops->get_cpl(vcpu) == 0))
  6182. kvm_make_request(KVM_REQ_APF_HALT, vcpu);
  6183. else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
  6184. fault.vector = PF_VECTOR;
  6185. fault.error_code_valid = true;
  6186. fault.error_code = 0;
  6187. fault.nested_page_fault = false;
  6188. fault.address = work->arch.token;
  6189. kvm_inject_page_fault(vcpu, &fault);
  6190. }
  6191. }
  6192. void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
  6193. struct kvm_async_pf *work)
  6194. {
  6195. struct x86_exception fault;
  6196. trace_kvm_async_pf_ready(work->arch.token, work->gva);
  6197. if (is_error_page(work->page))
  6198. work->arch.token = ~0; /* broadcast wakeup */
  6199. else
  6200. kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
  6201. if ((vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) &&
  6202. !apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
  6203. fault.vector = PF_VECTOR;
  6204. fault.error_code_valid = true;
  6205. fault.error_code = 0;
  6206. fault.nested_page_fault = false;
  6207. fault.address = work->arch.token;
  6208. kvm_inject_page_fault(vcpu, &fault);
  6209. }
  6210. vcpu->arch.apf.halted = false;
  6211. vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
  6212. }
  6213. bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu)
  6214. {
  6215. if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED))
  6216. return true;
  6217. else
  6218. return !kvm_event_needs_reinjection(vcpu) &&
  6219. kvm_x86_ops->interrupt_allowed(vcpu);
  6220. }
  6221. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
  6222. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
  6223. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
  6224. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
  6225. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
  6226. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
  6227. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
  6228. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
  6229. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
  6230. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
  6231. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
  6232. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);