x86.c 228 KB

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