x86.c 251 KB

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