x86.c 187 KB

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