x86.c 186 KB

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