x86.c 224 KB

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