x86.c 182 KB

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