x86.c 199 KB

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