x86.c 190 KB

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