x86.c 208 KB

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