x86.c 180 KB

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