x86.c 223 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732
  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)) |
  273. 0x2ff | (guest_cpuid_has_x2apic(vcpu) ? 0 : X2APIC_ENABLE);
  274. if (!msr_info->host_initiated &&
  275. ((msr_info->data & reserved_bits) != 0 ||
  276. new_state == X2APIC_ENABLE ||
  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.cr2 = fault->address;
  392. kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
  393. }
  394. EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
  395. static bool kvm_propagate_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
  396. {
  397. if (mmu_is_nested(vcpu) && !fault->nested_page_fault)
  398. vcpu->arch.nested_mmu.inject_page_fault(vcpu, fault);
  399. else
  400. vcpu->arch.mmu.inject_page_fault(vcpu, fault);
  401. return fault->nested_page_fault;
  402. }
  403. void kvm_inject_nmi(struct kvm_vcpu *vcpu)
  404. {
  405. atomic_inc(&vcpu->arch.nmi_queued);
  406. kvm_make_request(KVM_REQ_NMI, vcpu);
  407. }
  408. EXPORT_SYMBOL_GPL(kvm_inject_nmi);
  409. void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
  410. {
  411. kvm_multiple_exception(vcpu, nr, true, error_code, false);
  412. }
  413. EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
  414. void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
  415. {
  416. kvm_multiple_exception(vcpu, nr, true, error_code, true);
  417. }
  418. EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
  419. /*
  420. * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
  421. * a #GP and return false.
  422. */
  423. bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
  424. {
  425. if (kvm_x86_ops->get_cpl(vcpu) <= required_cpl)
  426. return true;
  427. kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
  428. return false;
  429. }
  430. EXPORT_SYMBOL_GPL(kvm_require_cpl);
  431. bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
  432. {
  433. if ((dr != 4 && dr != 5) || !kvm_read_cr4_bits(vcpu, X86_CR4_DE))
  434. return true;
  435. kvm_queue_exception(vcpu, UD_VECTOR);
  436. return false;
  437. }
  438. EXPORT_SYMBOL_GPL(kvm_require_dr);
  439. /*
  440. * This function will be used to read from the physical memory of the currently
  441. * running guest. The difference to kvm_vcpu_read_guest_page is that this function
  442. * can read from guest physical or from the guest's guest physical memory.
  443. */
  444. int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
  445. gfn_t ngfn, void *data, int offset, int len,
  446. u32 access)
  447. {
  448. struct x86_exception exception;
  449. gfn_t real_gfn;
  450. gpa_t ngpa;
  451. ngpa = gfn_to_gpa(ngfn);
  452. real_gfn = mmu->translate_gpa(vcpu, ngpa, access, &exception);
  453. if (real_gfn == UNMAPPED_GVA)
  454. return -EFAULT;
  455. real_gfn = gpa_to_gfn(real_gfn);
  456. return kvm_vcpu_read_guest_page(vcpu, real_gfn, data, offset, len);
  457. }
  458. EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
  459. static int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
  460. void *data, int offset, int len, u32 access)
  461. {
  462. return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
  463. data, offset, len, access);
  464. }
  465. /*
  466. * Load the pae pdptrs. Return true is they are all valid.
  467. */
  468. int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
  469. {
  470. gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
  471. unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
  472. int i;
  473. int ret;
  474. u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
  475. ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
  476. offset * sizeof(u64), sizeof(pdpte),
  477. PFERR_USER_MASK|PFERR_WRITE_MASK);
  478. if (ret < 0) {
  479. ret = 0;
  480. goto out;
  481. }
  482. for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
  483. if ((pdpte[i] & PT_PRESENT_MASK) &&
  484. (pdpte[i] &
  485. vcpu->arch.mmu.guest_rsvd_check.rsvd_bits_mask[0][2])) {
  486. ret = 0;
  487. goto out;
  488. }
  489. }
  490. ret = 1;
  491. memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
  492. __set_bit(VCPU_EXREG_PDPTR,
  493. (unsigned long *)&vcpu->arch.regs_avail);
  494. __set_bit(VCPU_EXREG_PDPTR,
  495. (unsigned long *)&vcpu->arch.regs_dirty);
  496. out:
  497. return ret;
  498. }
  499. EXPORT_SYMBOL_GPL(load_pdptrs);
  500. bool pdptrs_changed(struct kvm_vcpu *vcpu)
  501. {
  502. u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
  503. bool changed = true;
  504. int offset;
  505. gfn_t gfn;
  506. int r;
  507. if (is_long_mode(vcpu) || !is_pae(vcpu))
  508. return false;
  509. if (!test_bit(VCPU_EXREG_PDPTR,
  510. (unsigned long *)&vcpu->arch.regs_avail))
  511. return true;
  512. gfn = (kvm_read_cr3(vcpu) & ~31u) >> PAGE_SHIFT;
  513. offset = (kvm_read_cr3(vcpu) & ~31u) & (PAGE_SIZE - 1);
  514. r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
  515. PFERR_USER_MASK | PFERR_WRITE_MASK);
  516. if (r < 0)
  517. goto out;
  518. changed = memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
  519. out:
  520. return changed;
  521. }
  522. EXPORT_SYMBOL_GPL(pdptrs_changed);
  523. int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
  524. {
  525. unsigned long old_cr0 = kvm_read_cr0(vcpu);
  526. unsigned long update_bits = X86_CR0_PG | X86_CR0_WP;
  527. cr0 |= X86_CR0_ET;
  528. #ifdef CONFIG_X86_64
  529. if (cr0 & 0xffffffff00000000UL)
  530. return 1;
  531. #endif
  532. cr0 &= ~CR0_RESERVED_BITS;
  533. if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
  534. return 1;
  535. if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
  536. return 1;
  537. if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
  538. #ifdef CONFIG_X86_64
  539. if ((vcpu->arch.efer & EFER_LME)) {
  540. int cs_db, cs_l;
  541. if (!is_pae(vcpu))
  542. return 1;
  543. kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
  544. if (cs_l)
  545. return 1;
  546. } else
  547. #endif
  548. if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
  549. kvm_read_cr3(vcpu)))
  550. return 1;
  551. }
  552. if (!(cr0 & X86_CR0_PG) && kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
  553. return 1;
  554. kvm_x86_ops->set_cr0(vcpu, cr0);
  555. if ((cr0 ^ old_cr0) & X86_CR0_PG) {
  556. kvm_clear_async_pf_completion_queue(vcpu);
  557. kvm_async_pf_hash_reset(vcpu);
  558. }
  559. if ((cr0 ^ old_cr0) & update_bits)
  560. kvm_mmu_reset_context(vcpu);
  561. if (((cr0 ^ old_cr0) & X86_CR0_CD) &&
  562. kvm_arch_has_noncoherent_dma(vcpu->kvm) &&
  563. !kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
  564. kvm_zap_gfn_range(vcpu->kvm, 0, ~0ULL);
  565. return 0;
  566. }
  567. EXPORT_SYMBOL_GPL(kvm_set_cr0);
  568. void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
  569. {
  570. (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
  571. }
  572. EXPORT_SYMBOL_GPL(kvm_lmsw);
  573. static void kvm_load_guest_xcr0(struct kvm_vcpu *vcpu)
  574. {
  575. if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE) &&
  576. !vcpu->guest_xcr0_loaded) {
  577. /* kvm_set_xcr() also depends on this */
  578. xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
  579. vcpu->guest_xcr0_loaded = 1;
  580. }
  581. }
  582. static void kvm_put_guest_xcr0(struct kvm_vcpu *vcpu)
  583. {
  584. if (vcpu->guest_xcr0_loaded) {
  585. if (vcpu->arch.xcr0 != host_xcr0)
  586. xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
  587. vcpu->guest_xcr0_loaded = 0;
  588. }
  589. }
  590. static int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
  591. {
  592. u64 xcr0 = xcr;
  593. u64 old_xcr0 = vcpu->arch.xcr0;
  594. u64 valid_bits;
  595. /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
  596. if (index != XCR_XFEATURE_ENABLED_MASK)
  597. return 1;
  598. if (!(xcr0 & XFEATURE_MASK_FP))
  599. return 1;
  600. if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
  601. return 1;
  602. /*
  603. * Do not allow the guest to set bits that we do not support
  604. * saving. However, xcr0 bit 0 is always set, even if the
  605. * emulated CPU does not support XSAVE (see fx_init).
  606. */
  607. valid_bits = vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FP;
  608. if (xcr0 & ~valid_bits)
  609. return 1;
  610. if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
  611. (!(xcr0 & XFEATURE_MASK_BNDCSR)))
  612. return 1;
  613. if (xcr0 & XFEATURE_MASK_AVX512) {
  614. if (!(xcr0 & XFEATURE_MASK_YMM))
  615. return 1;
  616. if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
  617. return 1;
  618. }
  619. vcpu->arch.xcr0 = xcr0;
  620. if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
  621. kvm_update_cpuid(vcpu);
  622. return 0;
  623. }
  624. int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
  625. {
  626. if (kvm_x86_ops->get_cpl(vcpu) != 0 ||
  627. __kvm_set_xcr(vcpu, index, xcr)) {
  628. kvm_inject_gp(vcpu, 0);
  629. return 1;
  630. }
  631. return 0;
  632. }
  633. EXPORT_SYMBOL_GPL(kvm_set_xcr);
  634. int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
  635. {
  636. unsigned long old_cr4 = kvm_read_cr4(vcpu);
  637. unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE | X86_CR4_PAE |
  638. X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE;
  639. if (cr4 & CR4_RESERVED_BITS)
  640. return 1;
  641. if (!guest_cpuid_has_xsave(vcpu) && (cr4 & X86_CR4_OSXSAVE))
  642. return 1;
  643. if (!guest_cpuid_has_smep(vcpu) && (cr4 & X86_CR4_SMEP))
  644. return 1;
  645. if (!guest_cpuid_has_smap(vcpu) && (cr4 & X86_CR4_SMAP))
  646. return 1;
  647. if (!guest_cpuid_has_fsgsbase(vcpu) && (cr4 & X86_CR4_FSGSBASE))
  648. return 1;
  649. if (!guest_cpuid_has_pku(vcpu) && (cr4 & X86_CR4_PKE))
  650. return 1;
  651. if (is_long_mode(vcpu)) {
  652. if (!(cr4 & X86_CR4_PAE))
  653. return 1;
  654. } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
  655. && ((cr4 ^ old_cr4) & pdptr_bits)
  656. && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
  657. kvm_read_cr3(vcpu)))
  658. return 1;
  659. if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
  660. if (!guest_cpuid_has_pcid(vcpu))
  661. return 1;
  662. /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
  663. if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
  664. return 1;
  665. }
  666. if (kvm_x86_ops->set_cr4(vcpu, cr4))
  667. return 1;
  668. if (((cr4 ^ old_cr4) & pdptr_bits) ||
  669. (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
  670. kvm_mmu_reset_context(vcpu);
  671. if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
  672. kvm_update_cpuid(vcpu);
  673. return 0;
  674. }
  675. EXPORT_SYMBOL_GPL(kvm_set_cr4);
  676. int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
  677. {
  678. #ifdef CONFIG_X86_64
  679. cr3 &= ~CR3_PCID_INVD;
  680. #endif
  681. if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
  682. kvm_mmu_sync_roots(vcpu);
  683. kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
  684. return 0;
  685. }
  686. if (is_long_mode(vcpu)) {
  687. if (cr3 & CR3_L_MODE_RESERVED_BITS)
  688. return 1;
  689. } else if (is_pae(vcpu) && is_paging(vcpu) &&
  690. !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
  691. return 1;
  692. vcpu->arch.cr3 = cr3;
  693. __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
  694. kvm_mmu_new_cr3(vcpu);
  695. return 0;
  696. }
  697. EXPORT_SYMBOL_GPL(kvm_set_cr3);
  698. int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
  699. {
  700. if (cr8 & CR8_RESERVED_BITS)
  701. return 1;
  702. if (lapic_in_kernel(vcpu))
  703. kvm_lapic_set_tpr(vcpu, cr8);
  704. else
  705. vcpu->arch.cr8 = cr8;
  706. return 0;
  707. }
  708. EXPORT_SYMBOL_GPL(kvm_set_cr8);
  709. unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
  710. {
  711. if (lapic_in_kernel(vcpu))
  712. return kvm_lapic_get_cr8(vcpu);
  713. else
  714. return vcpu->arch.cr8;
  715. }
  716. EXPORT_SYMBOL_GPL(kvm_get_cr8);
  717. static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
  718. {
  719. int i;
  720. if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
  721. for (i = 0; i < KVM_NR_DB_REGS; i++)
  722. vcpu->arch.eff_db[i] = vcpu->arch.db[i];
  723. vcpu->arch.switch_db_regs |= KVM_DEBUGREG_RELOAD;
  724. }
  725. }
  726. static void kvm_update_dr6(struct kvm_vcpu *vcpu)
  727. {
  728. if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
  729. kvm_x86_ops->set_dr6(vcpu, vcpu->arch.dr6);
  730. }
  731. static void kvm_update_dr7(struct kvm_vcpu *vcpu)
  732. {
  733. unsigned long dr7;
  734. if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
  735. dr7 = vcpu->arch.guest_debug_dr7;
  736. else
  737. dr7 = vcpu->arch.dr7;
  738. kvm_x86_ops->set_dr7(vcpu, dr7);
  739. vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
  740. if (dr7 & DR7_BP_EN_MASK)
  741. vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
  742. }
  743. static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
  744. {
  745. u64 fixed = DR6_FIXED_1;
  746. if (!guest_cpuid_has_rtm(vcpu))
  747. fixed |= DR6_RTM;
  748. return fixed;
  749. }
  750. static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
  751. {
  752. switch (dr) {
  753. case 0 ... 3:
  754. vcpu->arch.db[dr] = val;
  755. if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
  756. vcpu->arch.eff_db[dr] = val;
  757. break;
  758. case 4:
  759. /* fall through */
  760. case 6:
  761. if (val & 0xffffffff00000000ULL)
  762. return -1; /* #GP */
  763. vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
  764. kvm_update_dr6(vcpu);
  765. break;
  766. case 5:
  767. /* fall through */
  768. default: /* 7 */
  769. if (val & 0xffffffff00000000ULL)
  770. return -1; /* #GP */
  771. vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
  772. kvm_update_dr7(vcpu);
  773. break;
  774. }
  775. return 0;
  776. }
  777. int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
  778. {
  779. if (__kvm_set_dr(vcpu, dr, val)) {
  780. kvm_inject_gp(vcpu, 0);
  781. return 1;
  782. }
  783. return 0;
  784. }
  785. EXPORT_SYMBOL_GPL(kvm_set_dr);
  786. int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
  787. {
  788. switch (dr) {
  789. case 0 ... 3:
  790. *val = vcpu->arch.db[dr];
  791. break;
  792. case 4:
  793. /* fall through */
  794. case 6:
  795. if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
  796. *val = vcpu->arch.dr6;
  797. else
  798. *val = kvm_x86_ops->get_dr6(vcpu);
  799. break;
  800. case 5:
  801. /* fall through */
  802. default: /* 7 */
  803. *val = vcpu->arch.dr7;
  804. break;
  805. }
  806. return 0;
  807. }
  808. EXPORT_SYMBOL_GPL(kvm_get_dr);
  809. bool kvm_rdpmc(struct kvm_vcpu *vcpu)
  810. {
  811. u32 ecx = kvm_register_read(vcpu, VCPU_REGS_RCX);
  812. u64 data;
  813. int err;
  814. err = kvm_pmu_rdpmc(vcpu, ecx, &data);
  815. if (err)
  816. return err;
  817. kvm_register_write(vcpu, VCPU_REGS_RAX, (u32)data);
  818. kvm_register_write(vcpu, VCPU_REGS_RDX, data >> 32);
  819. return err;
  820. }
  821. EXPORT_SYMBOL_GPL(kvm_rdpmc);
  822. /*
  823. * List of msr numbers which we expose to userspace through KVM_GET_MSRS
  824. * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
  825. *
  826. * This list is modified at module load time to reflect the
  827. * capabilities of the host cpu. This capabilities test skips MSRs that are
  828. * kvm-specific. Those are put in emulated_msrs; filtering of emulated_msrs
  829. * may depend on host virtualization features rather than host cpu features.
  830. */
  831. static u32 msrs_to_save[] = {
  832. MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
  833. MSR_STAR,
  834. #ifdef CONFIG_X86_64
  835. MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
  836. #endif
  837. MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
  838. MSR_IA32_FEATURE_CONTROL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
  839. };
  840. static unsigned num_msrs_to_save;
  841. static u32 emulated_msrs[] = {
  842. MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
  843. MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
  844. HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
  845. HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
  846. HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
  847. HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
  848. HV_X64_MSR_RESET,
  849. HV_X64_MSR_VP_INDEX,
  850. HV_X64_MSR_VP_RUNTIME,
  851. HV_X64_MSR_SCONTROL,
  852. HV_X64_MSR_STIMER0_CONFIG,
  853. HV_X64_MSR_APIC_ASSIST_PAGE, MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
  854. MSR_KVM_PV_EOI_EN,
  855. MSR_IA32_TSC_ADJUST,
  856. MSR_IA32_TSCDEADLINE,
  857. MSR_IA32_MISC_ENABLE,
  858. MSR_IA32_MCG_STATUS,
  859. MSR_IA32_MCG_CTL,
  860. MSR_IA32_MCG_EXT_CTL,
  861. MSR_IA32_SMBASE,
  862. MSR_PLATFORM_INFO,
  863. MSR_MISC_FEATURES_ENABLES,
  864. };
  865. static unsigned num_emulated_msrs;
  866. bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
  867. {
  868. if (efer & efer_reserved_bits)
  869. return false;
  870. if (efer & EFER_FFXSR) {
  871. struct kvm_cpuid_entry2 *feat;
  872. feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
  873. if (!feat || !(feat->edx & bit(X86_FEATURE_FXSR_OPT)))
  874. return false;
  875. }
  876. if (efer & EFER_SVME) {
  877. struct kvm_cpuid_entry2 *feat;
  878. feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
  879. if (!feat || !(feat->ecx & bit(X86_FEATURE_SVM)))
  880. return false;
  881. }
  882. return true;
  883. }
  884. EXPORT_SYMBOL_GPL(kvm_valid_efer);
  885. static int set_efer(struct kvm_vcpu *vcpu, u64 efer)
  886. {
  887. u64 old_efer = vcpu->arch.efer;
  888. if (!kvm_valid_efer(vcpu, efer))
  889. return 1;
  890. if (is_paging(vcpu)
  891. && (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
  892. return 1;
  893. efer &= ~EFER_LMA;
  894. efer |= vcpu->arch.efer & EFER_LMA;
  895. kvm_x86_ops->set_efer(vcpu, efer);
  896. /* Update reserved bits */
  897. if ((efer ^ old_efer) & EFER_NX)
  898. kvm_mmu_reset_context(vcpu);
  899. return 0;
  900. }
  901. void kvm_enable_efer_bits(u64 mask)
  902. {
  903. efer_reserved_bits &= ~mask;
  904. }
  905. EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
  906. /*
  907. * Writes msr value into into the appropriate "register".
  908. * Returns 0 on success, non-0 otherwise.
  909. * Assumes vcpu_load() was already called.
  910. */
  911. int kvm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
  912. {
  913. switch (msr->index) {
  914. case MSR_FS_BASE:
  915. case MSR_GS_BASE:
  916. case MSR_KERNEL_GS_BASE:
  917. case MSR_CSTAR:
  918. case MSR_LSTAR:
  919. if (is_noncanonical_address(msr->data))
  920. return 1;
  921. break;
  922. case MSR_IA32_SYSENTER_EIP:
  923. case MSR_IA32_SYSENTER_ESP:
  924. /*
  925. * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
  926. * non-canonical address is written on Intel but not on
  927. * AMD (which ignores the top 32-bits, because it does
  928. * not implement 64-bit SYSENTER).
  929. *
  930. * 64-bit code should hence be able to write a non-canonical
  931. * value on AMD. Making the address canonical ensures that
  932. * vmentry does not fail on Intel after writing a non-canonical
  933. * value, and that something deterministic happens if the guest
  934. * invokes 64-bit SYSENTER.
  935. */
  936. msr->data = get_canonical(msr->data);
  937. }
  938. return kvm_x86_ops->set_msr(vcpu, msr);
  939. }
  940. EXPORT_SYMBOL_GPL(kvm_set_msr);
  941. /*
  942. * Adapt set_msr() to msr_io()'s calling convention
  943. */
  944. static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
  945. {
  946. struct msr_data msr;
  947. int r;
  948. msr.index = index;
  949. msr.host_initiated = true;
  950. r = kvm_get_msr(vcpu, &msr);
  951. if (r)
  952. return r;
  953. *data = msr.data;
  954. return 0;
  955. }
  956. static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
  957. {
  958. struct msr_data msr;
  959. msr.data = *data;
  960. msr.index = index;
  961. msr.host_initiated = true;
  962. return kvm_set_msr(vcpu, &msr);
  963. }
  964. #ifdef CONFIG_X86_64
  965. struct pvclock_gtod_data {
  966. seqcount_t seq;
  967. struct { /* extract of a clocksource struct */
  968. int vclock_mode;
  969. u64 cycle_last;
  970. u64 mask;
  971. u32 mult;
  972. u32 shift;
  973. } clock;
  974. u64 boot_ns;
  975. u64 nsec_base;
  976. u64 wall_time_sec;
  977. };
  978. static struct pvclock_gtod_data pvclock_gtod_data;
  979. static void update_pvclock_gtod(struct timekeeper *tk)
  980. {
  981. struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
  982. u64 boot_ns;
  983. boot_ns = ktime_to_ns(ktime_add(tk->tkr_mono.base, tk->offs_boot));
  984. write_seqcount_begin(&vdata->seq);
  985. /* copy pvclock gtod data */
  986. vdata->clock.vclock_mode = tk->tkr_mono.clock->archdata.vclock_mode;
  987. vdata->clock.cycle_last = tk->tkr_mono.cycle_last;
  988. vdata->clock.mask = tk->tkr_mono.mask;
  989. vdata->clock.mult = tk->tkr_mono.mult;
  990. vdata->clock.shift = tk->tkr_mono.shift;
  991. vdata->boot_ns = boot_ns;
  992. vdata->nsec_base = tk->tkr_mono.xtime_nsec;
  993. vdata->wall_time_sec = tk->xtime_sec;
  994. write_seqcount_end(&vdata->seq);
  995. }
  996. #endif
  997. void kvm_set_pending_timer(struct kvm_vcpu *vcpu)
  998. {
  999. /*
  1000. * Note: KVM_REQ_PENDING_TIMER is implicitly checked in
  1001. * vcpu_enter_guest. This function is only called from
  1002. * the physical CPU that is running vcpu.
  1003. */
  1004. kvm_make_request(KVM_REQ_PENDING_TIMER, vcpu);
  1005. }
  1006. static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
  1007. {
  1008. int version;
  1009. int r;
  1010. struct pvclock_wall_clock wc;
  1011. struct timespec64 boot;
  1012. if (!wall_clock)
  1013. return;
  1014. r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
  1015. if (r)
  1016. return;
  1017. if (version & 1)
  1018. ++version; /* first time write, random junk */
  1019. ++version;
  1020. if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
  1021. return;
  1022. /*
  1023. * The guest calculates current wall clock time by adding
  1024. * system time (updated by kvm_guest_time_update below) to the
  1025. * wall clock specified here. guest system time equals host
  1026. * system time for us, thus we must fill in host boot time here.
  1027. */
  1028. getboottime64(&boot);
  1029. if (kvm->arch.kvmclock_offset) {
  1030. struct timespec64 ts = ns_to_timespec64(kvm->arch.kvmclock_offset);
  1031. boot = timespec64_sub(boot, ts);
  1032. }
  1033. wc.sec = (u32)boot.tv_sec; /* overflow in 2106 guest time */
  1034. wc.nsec = boot.tv_nsec;
  1035. wc.version = version;
  1036. kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
  1037. version++;
  1038. kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
  1039. }
  1040. static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
  1041. {
  1042. do_shl32_div32(dividend, divisor);
  1043. return dividend;
  1044. }
  1045. static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
  1046. s8 *pshift, u32 *pmultiplier)
  1047. {
  1048. uint64_t scaled64;
  1049. int32_t shift = 0;
  1050. uint64_t tps64;
  1051. uint32_t tps32;
  1052. tps64 = base_hz;
  1053. scaled64 = scaled_hz;
  1054. while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
  1055. tps64 >>= 1;
  1056. shift--;
  1057. }
  1058. tps32 = (uint32_t)tps64;
  1059. while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
  1060. if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
  1061. scaled64 >>= 1;
  1062. else
  1063. tps32 <<= 1;
  1064. shift++;
  1065. }
  1066. *pshift = shift;
  1067. *pmultiplier = div_frac(scaled64, tps32);
  1068. pr_debug("%s: base_hz %llu => %llu, shift %d, mul %u\n",
  1069. __func__, base_hz, scaled_hz, shift, *pmultiplier);
  1070. }
  1071. #ifdef CONFIG_X86_64
  1072. static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
  1073. #endif
  1074. static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
  1075. static unsigned long max_tsc_khz;
  1076. static u32 adjust_tsc_khz(u32 khz, s32 ppm)
  1077. {
  1078. u64 v = (u64)khz * (1000000 + ppm);
  1079. do_div(v, 1000000);
  1080. return v;
  1081. }
  1082. static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
  1083. {
  1084. u64 ratio;
  1085. /* Guest TSC same frequency as host TSC? */
  1086. if (!scale) {
  1087. vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
  1088. return 0;
  1089. }
  1090. /* TSC scaling supported? */
  1091. if (!kvm_has_tsc_control) {
  1092. if (user_tsc_khz > tsc_khz) {
  1093. vcpu->arch.tsc_catchup = 1;
  1094. vcpu->arch.tsc_always_catchup = 1;
  1095. return 0;
  1096. } else {
  1097. WARN(1, "user requested TSC rate below hardware speed\n");
  1098. return -1;
  1099. }
  1100. }
  1101. /* TSC scaling required - calculate ratio */
  1102. ratio = mul_u64_u32_div(1ULL << kvm_tsc_scaling_ratio_frac_bits,
  1103. user_tsc_khz, tsc_khz);
  1104. if (ratio == 0 || ratio >= kvm_max_tsc_scaling_ratio) {
  1105. WARN_ONCE(1, "Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
  1106. user_tsc_khz);
  1107. return -1;
  1108. }
  1109. vcpu->arch.tsc_scaling_ratio = ratio;
  1110. return 0;
  1111. }
  1112. static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
  1113. {
  1114. u32 thresh_lo, thresh_hi;
  1115. int use_scaling = 0;
  1116. /* tsc_khz can be zero if TSC calibration fails */
  1117. if (user_tsc_khz == 0) {
  1118. /* set tsc_scaling_ratio to a safe value */
  1119. vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
  1120. return -1;
  1121. }
  1122. /* Compute a scale to convert nanoseconds in TSC cycles */
  1123. kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
  1124. &vcpu->arch.virtual_tsc_shift,
  1125. &vcpu->arch.virtual_tsc_mult);
  1126. vcpu->arch.virtual_tsc_khz = user_tsc_khz;
  1127. /*
  1128. * Compute the variation in TSC rate which is acceptable
  1129. * within the range of tolerance and decide if the
  1130. * rate being applied is within that bounds of the hardware
  1131. * rate. If so, no scaling or compensation need be done.
  1132. */
  1133. thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
  1134. thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
  1135. if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
  1136. pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", user_tsc_khz, thresh_lo, thresh_hi);
  1137. use_scaling = 1;
  1138. }
  1139. return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
  1140. }
  1141. static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
  1142. {
  1143. u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
  1144. vcpu->arch.virtual_tsc_mult,
  1145. vcpu->arch.virtual_tsc_shift);
  1146. tsc += vcpu->arch.this_tsc_write;
  1147. return tsc;
  1148. }
  1149. static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
  1150. {
  1151. #ifdef CONFIG_X86_64
  1152. bool vcpus_matched;
  1153. struct kvm_arch *ka = &vcpu->kvm->arch;
  1154. struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
  1155. vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
  1156. atomic_read(&vcpu->kvm->online_vcpus));
  1157. /*
  1158. * Once the masterclock is enabled, always perform request in
  1159. * order to update it.
  1160. *
  1161. * In order to enable masterclock, the host clocksource must be TSC
  1162. * and the vcpus need to have matched TSCs. When that happens,
  1163. * perform request to enable masterclock.
  1164. */
  1165. if (ka->use_master_clock ||
  1166. (gtod->clock.vclock_mode == VCLOCK_TSC && vcpus_matched))
  1167. kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
  1168. trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
  1169. atomic_read(&vcpu->kvm->online_vcpus),
  1170. ka->use_master_clock, gtod->clock.vclock_mode);
  1171. #endif
  1172. }
  1173. static void update_ia32_tsc_adjust_msr(struct kvm_vcpu *vcpu, s64 offset)
  1174. {
  1175. u64 curr_offset = vcpu->arch.tsc_offset;
  1176. vcpu->arch.ia32_tsc_adjust_msr += offset - curr_offset;
  1177. }
  1178. /*
  1179. * Multiply tsc by a fixed point number represented by ratio.
  1180. *
  1181. * The most significant 64-N bits (mult) of ratio represent the
  1182. * integral part of the fixed point number; the remaining N bits
  1183. * (frac) represent the fractional part, ie. ratio represents a fixed
  1184. * point number (mult + frac * 2^(-N)).
  1185. *
  1186. * N equals to kvm_tsc_scaling_ratio_frac_bits.
  1187. */
  1188. static inline u64 __scale_tsc(u64 ratio, u64 tsc)
  1189. {
  1190. return mul_u64_u64_shr(tsc, ratio, kvm_tsc_scaling_ratio_frac_bits);
  1191. }
  1192. u64 kvm_scale_tsc(struct kvm_vcpu *vcpu, u64 tsc)
  1193. {
  1194. u64 _tsc = tsc;
  1195. u64 ratio = vcpu->arch.tsc_scaling_ratio;
  1196. if (ratio != kvm_default_tsc_scaling_ratio)
  1197. _tsc = __scale_tsc(ratio, tsc);
  1198. return _tsc;
  1199. }
  1200. EXPORT_SYMBOL_GPL(kvm_scale_tsc);
  1201. static u64 kvm_compute_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
  1202. {
  1203. u64 tsc;
  1204. tsc = kvm_scale_tsc(vcpu, rdtsc());
  1205. return target_tsc - tsc;
  1206. }
  1207. u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
  1208. {
  1209. return vcpu->arch.tsc_offset + kvm_scale_tsc(vcpu, host_tsc);
  1210. }
  1211. EXPORT_SYMBOL_GPL(kvm_read_l1_tsc);
  1212. static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
  1213. {
  1214. kvm_x86_ops->write_tsc_offset(vcpu, offset);
  1215. vcpu->arch.tsc_offset = offset;
  1216. }
  1217. void kvm_write_tsc(struct kvm_vcpu *vcpu, struct msr_data *msr)
  1218. {
  1219. struct kvm *kvm = vcpu->kvm;
  1220. u64 offset, ns, elapsed;
  1221. unsigned long flags;
  1222. bool matched;
  1223. bool already_matched;
  1224. u64 data = msr->data;
  1225. bool synchronizing = false;
  1226. raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
  1227. offset = kvm_compute_tsc_offset(vcpu, data);
  1228. ns = ktime_get_boot_ns();
  1229. elapsed = ns - kvm->arch.last_tsc_nsec;
  1230. if (vcpu->arch.virtual_tsc_khz) {
  1231. if (data == 0 && msr->host_initiated) {
  1232. /*
  1233. * detection of vcpu initialization -- need to sync
  1234. * with other vCPUs. This particularly helps to keep
  1235. * kvm_clock stable after CPU hotplug
  1236. */
  1237. synchronizing = true;
  1238. } else {
  1239. u64 tsc_exp = kvm->arch.last_tsc_write +
  1240. nsec_to_cycles(vcpu, elapsed);
  1241. u64 tsc_hz = vcpu->arch.virtual_tsc_khz * 1000LL;
  1242. /*
  1243. * Special case: TSC write with a small delta (1 second)
  1244. * of virtual cycle time against real time is
  1245. * interpreted as an attempt to synchronize the CPU.
  1246. */
  1247. synchronizing = data < tsc_exp + tsc_hz &&
  1248. data + tsc_hz > tsc_exp;
  1249. }
  1250. }
  1251. /*
  1252. * For a reliable TSC, we can match TSC offsets, and for an unstable
  1253. * TSC, we add elapsed time in this computation. We could let the
  1254. * compensation code attempt to catch up if we fall behind, but
  1255. * it's better to try to match offsets from the beginning.
  1256. */
  1257. if (synchronizing &&
  1258. vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
  1259. if (!check_tsc_unstable()) {
  1260. offset = kvm->arch.cur_tsc_offset;
  1261. pr_debug("kvm: matched tsc offset for %llu\n", data);
  1262. } else {
  1263. u64 delta = nsec_to_cycles(vcpu, elapsed);
  1264. data += delta;
  1265. offset = kvm_compute_tsc_offset(vcpu, data);
  1266. pr_debug("kvm: adjusted tsc offset by %llu\n", delta);
  1267. }
  1268. matched = true;
  1269. already_matched = (vcpu->arch.this_tsc_generation == kvm->arch.cur_tsc_generation);
  1270. } else {
  1271. /*
  1272. * We split periods of matched TSC writes into generations.
  1273. * For each generation, we track the original measured
  1274. * nanosecond time, offset, and write, so if TSCs are in
  1275. * sync, we can match exact offset, and if not, we can match
  1276. * exact software computation in compute_guest_tsc()
  1277. *
  1278. * These values are tracked in kvm->arch.cur_xxx variables.
  1279. */
  1280. kvm->arch.cur_tsc_generation++;
  1281. kvm->arch.cur_tsc_nsec = ns;
  1282. kvm->arch.cur_tsc_write = data;
  1283. kvm->arch.cur_tsc_offset = offset;
  1284. matched = false;
  1285. pr_debug("kvm: new tsc generation %llu, clock %llu\n",
  1286. kvm->arch.cur_tsc_generation, data);
  1287. }
  1288. /*
  1289. * We also track th most recent recorded KHZ, write and time to
  1290. * allow the matching interval to be extended at each write.
  1291. */
  1292. kvm->arch.last_tsc_nsec = ns;
  1293. kvm->arch.last_tsc_write = data;
  1294. kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
  1295. vcpu->arch.last_guest_tsc = data;
  1296. /* Keep track of which generation this VCPU has synchronized to */
  1297. vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
  1298. vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
  1299. vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
  1300. if (guest_cpuid_has_tsc_adjust(vcpu) && !msr->host_initiated)
  1301. update_ia32_tsc_adjust_msr(vcpu, offset);
  1302. kvm_vcpu_write_tsc_offset(vcpu, offset);
  1303. raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
  1304. spin_lock(&kvm->arch.pvclock_gtod_sync_lock);
  1305. if (!matched) {
  1306. kvm->arch.nr_vcpus_matched_tsc = 0;
  1307. } else if (!already_matched) {
  1308. kvm->arch.nr_vcpus_matched_tsc++;
  1309. }
  1310. kvm_track_tsc_matching(vcpu);
  1311. spin_unlock(&kvm->arch.pvclock_gtod_sync_lock);
  1312. }
  1313. EXPORT_SYMBOL_GPL(kvm_write_tsc);
  1314. static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
  1315. s64 adjustment)
  1316. {
  1317. kvm_vcpu_write_tsc_offset(vcpu, vcpu->arch.tsc_offset + adjustment);
  1318. }
  1319. static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
  1320. {
  1321. if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio)
  1322. WARN_ON(adjustment < 0);
  1323. adjustment = kvm_scale_tsc(vcpu, (u64) adjustment);
  1324. adjust_tsc_offset_guest(vcpu, adjustment);
  1325. }
  1326. #ifdef CONFIG_X86_64
  1327. static u64 read_tsc(void)
  1328. {
  1329. u64 ret = (u64)rdtsc_ordered();
  1330. u64 last = pvclock_gtod_data.clock.cycle_last;
  1331. if (likely(ret >= last))
  1332. return ret;
  1333. /*
  1334. * GCC likes to generate cmov here, but this branch is extremely
  1335. * predictable (it's just a function of time and the likely is
  1336. * very likely) and there's a data dependence, so force GCC
  1337. * to generate a branch instead. I don't barrier() because
  1338. * we don't actually need a barrier, and if this function
  1339. * ever gets inlined it will generate worse code.
  1340. */
  1341. asm volatile ("");
  1342. return last;
  1343. }
  1344. static inline u64 vgettsc(u64 *cycle_now)
  1345. {
  1346. long v;
  1347. struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
  1348. *cycle_now = read_tsc();
  1349. v = (*cycle_now - gtod->clock.cycle_last) & gtod->clock.mask;
  1350. return v * gtod->clock.mult;
  1351. }
  1352. static int do_monotonic_boot(s64 *t, u64 *cycle_now)
  1353. {
  1354. struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
  1355. unsigned long seq;
  1356. int mode;
  1357. u64 ns;
  1358. do {
  1359. seq = read_seqcount_begin(&gtod->seq);
  1360. mode = gtod->clock.vclock_mode;
  1361. ns = gtod->nsec_base;
  1362. ns += vgettsc(cycle_now);
  1363. ns >>= gtod->clock.shift;
  1364. ns += gtod->boot_ns;
  1365. } while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
  1366. *t = ns;
  1367. return mode;
  1368. }
  1369. static int do_realtime(struct timespec *ts, u64 *cycle_now)
  1370. {
  1371. struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
  1372. unsigned long seq;
  1373. int mode;
  1374. u64 ns;
  1375. do {
  1376. seq = read_seqcount_begin(&gtod->seq);
  1377. mode = gtod->clock.vclock_mode;
  1378. ts->tv_sec = gtod->wall_time_sec;
  1379. ns = gtod->nsec_base;
  1380. ns += vgettsc(cycle_now);
  1381. ns >>= gtod->clock.shift;
  1382. } while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
  1383. ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns);
  1384. ts->tv_nsec = ns;
  1385. return mode;
  1386. }
  1387. /* returns true if host is using tsc clocksource */
  1388. static bool kvm_get_time_and_clockread(s64 *kernel_ns, u64 *cycle_now)
  1389. {
  1390. /* checked again under seqlock below */
  1391. if (pvclock_gtod_data.clock.vclock_mode != VCLOCK_TSC)
  1392. return false;
  1393. return do_monotonic_boot(kernel_ns, cycle_now) == VCLOCK_TSC;
  1394. }
  1395. /* returns true if host is using tsc clocksource */
  1396. static bool kvm_get_walltime_and_clockread(struct timespec *ts,
  1397. u64 *cycle_now)
  1398. {
  1399. /* checked again under seqlock below */
  1400. if (pvclock_gtod_data.clock.vclock_mode != VCLOCK_TSC)
  1401. return false;
  1402. return do_realtime(ts, cycle_now) == VCLOCK_TSC;
  1403. }
  1404. #endif
  1405. /*
  1406. *
  1407. * Assuming a stable TSC across physical CPUS, and a stable TSC
  1408. * across virtual CPUs, the following condition is possible.
  1409. * Each numbered line represents an event visible to both
  1410. * CPUs at the next numbered event.
  1411. *
  1412. * "timespecX" represents host monotonic time. "tscX" represents
  1413. * RDTSC value.
  1414. *
  1415. * VCPU0 on CPU0 | VCPU1 on CPU1
  1416. *
  1417. * 1. read timespec0,tsc0
  1418. * 2. | timespec1 = timespec0 + N
  1419. * | tsc1 = tsc0 + M
  1420. * 3. transition to guest | transition to guest
  1421. * 4. ret0 = timespec0 + (rdtsc - tsc0) |
  1422. * 5. | ret1 = timespec1 + (rdtsc - tsc1)
  1423. * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
  1424. *
  1425. * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
  1426. *
  1427. * - ret0 < ret1
  1428. * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
  1429. * ...
  1430. * - 0 < N - M => M < N
  1431. *
  1432. * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
  1433. * always the case (the difference between two distinct xtime instances
  1434. * might be smaller then the difference between corresponding TSC reads,
  1435. * when updating guest vcpus pvclock areas).
  1436. *
  1437. * To avoid that problem, do not allow visibility of distinct
  1438. * system_timestamp/tsc_timestamp values simultaneously: use a master
  1439. * copy of host monotonic time values. Update that master copy
  1440. * in lockstep.
  1441. *
  1442. * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
  1443. *
  1444. */
  1445. static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
  1446. {
  1447. #ifdef CONFIG_X86_64
  1448. struct kvm_arch *ka = &kvm->arch;
  1449. int vclock_mode;
  1450. bool host_tsc_clocksource, vcpus_matched;
  1451. vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
  1452. atomic_read(&kvm->online_vcpus));
  1453. /*
  1454. * If the host uses TSC clock, then passthrough TSC as stable
  1455. * to the guest.
  1456. */
  1457. host_tsc_clocksource = kvm_get_time_and_clockread(
  1458. &ka->master_kernel_ns,
  1459. &ka->master_cycle_now);
  1460. ka->use_master_clock = host_tsc_clocksource && vcpus_matched
  1461. && !ka->backwards_tsc_observed
  1462. && !ka->boot_vcpu_runs_old_kvmclock;
  1463. if (ka->use_master_clock)
  1464. atomic_set(&kvm_guest_has_master_clock, 1);
  1465. vclock_mode = pvclock_gtod_data.clock.vclock_mode;
  1466. trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
  1467. vcpus_matched);
  1468. #endif
  1469. }
  1470. void kvm_make_mclock_inprogress_request(struct kvm *kvm)
  1471. {
  1472. kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
  1473. }
  1474. static void kvm_gen_update_masterclock(struct kvm *kvm)
  1475. {
  1476. #ifdef CONFIG_X86_64
  1477. int i;
  1478. struct kvm_vcpu *vcpu;
  1479. struct kvm_arch *ka = &kvm->arch;
  1480. spin_lock(&ka->pvclock_gtod_sync_lock);
  1481. kvm_make_mclock_inprogress_request(kvm);
  1482. /* no guest entries from this point */
  1483. pvclock_update_vm_gtod_copy(kvm);
  1484. kvm_for_each_vcpu(i, vcpu, kvm)
  1485. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  1486. /* guest entries allowed */
  1487. kvm_for_each_vcpu(i, vcpu, kvm)
  1488. kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
  1489. spin_unlock(&ka->pvclock_gtod_sync_lock);
  1490. #endif
  1491. }
  1492. u64 get_kvmclock_ns(struct kvm *kvm)
  1493. {
  1494. struct kvm_arch *ka = &kvm->arch;
  1495. struct pvclock_vcpu_time_info hv_clock;
  1496. u64 ret;
  1497. spin_lock(&ka->pvclock_gtod_sync_lock);
  1498. if (!ka->use_master_clock) {
  1499. spin_unlock(&ka->pvclock_gtod_sync_lock);
  1500. return ktime_get_boot_ns() + ka->kvmclock_offset;
  1501. }
  1502. hv_clock.tsc_timestamp = ka->master_cycle_now;
  1503. hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
  1504. spin_unlock(&ka->pvclock_gtod_sync_lock);
  1505. /* both __this_cpu_read() and rdtsc() should be on the same cpu */
  1506. get_cpu();
  1507. kvm_get_time_scale(NSEC_PER_SEC, __this_cpu_read(cpu_tsc_khz) * 1000LL,
  1508. &hv_clock.tsc_shift,
  1509. &hv_clock.tsc_to_system_mul);
  1510. ret = __pvclock_read_cycles(&hv_clock, rdtsc());
  1511. put_cpu();
  1512. return ret;
  1513. }
  1514. static void kvm_setup_pvclock_page(struct kvm_vcpu *v)
  1515. {
  1516. struct kvm_vcpu_arch *vcpu = &v->arch;
  1517. struct pvclock_vcpu_time_info guest_hv_clock;
  1518. if (unlikely(kvm_read_guest_cached(v->kvm, &vcpu->pv_time,
  1519. &guest_hv_clock, sizeof(guest_hv_clock))))
  1520. return;
  1521. /* This VCPU is paused, but it's legal for a guest to read another
  1522. * VCPU's kvmclock, so we really have to follow the specification where
  1523. * it says that version is odd if data is being modified, and even after
  1524. * it is consistent.
  1525. *
  1526. * Version field updates must be kept separate. This is because
  1527. * kvm_write_guest_cached might use a "rep movs" instruction, and
  1528. * writes within a string instruction are weakly ordered. So there
  1529. * are three writes overall.
  1530. *
  1531. * As a small optimization, only write the version field in the first
  1532. * and third write. The vcpu->pv_time cache is still valid, because the
  1533. * version field is the first in the struct.
  1534. */
  1535. BUILD_BUG_ON(offsetof(struct pvclock_vcpu_time_info, version) != 0);
  1536. vcpu->hv_clock.version = guest_hv_clock.version + 1;
  1537. kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
  1538. &vcpu->hv_clock,
  1539. sizeof(vcpu->hv_clock.version));
  1540. smp_wmb();
  1541. /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
  1542. vcpu->hv_clock.flags |= (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED);
  1543. if (vcpu->pvclock_set_guest_stopped_request) {
  1544. vcpu->hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
  1545. vcpu->pvclock_set_guest_stopped_request = false;
  1546. }
  1547. trace_kvm_pvclock_update(v->vcpu_id, &vcpu->hv_clock);
  1548. kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
  1549. &vcpu->hv_clock,
  1550. sizeof(vcpu->hv_clock));
  1551. smp_wmb();
  1552. vcpu->hv_clock.version++;
  1553. kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
  1554. &vcpu->hv_clock,
  1555. sizeof(vcpu->hv_clock.version));
  1556. }
  1557. static int kvm_guest_time_update(struct kvm_vcpu *v)
  1558. {
  1559. unsigned long flags, tgt_tsc_khz;
  1560. struct kvm_vcpu_arch *vcpu = &v->arch;
  1561. struct kvm_arch *ka = &v->kvm->arch;
  1562. s64 kernel_ns;
  1563. u64 tsc_timestamp, host_tsc;
  1564. u8 pvclock_flags;
  1565. bool use_master_clock;
  1566. kernel_ns = 0;
  1567. host_tsc = 0;
  1568. /*
  1569. * If the host uses TSC clock, then passthrough TSC as stable
  1570. * to the guest.
  1571. */
  1572. spin_lock(&ka->pvclock_gtod_sync_lock);
  1573. use_master_clock = ka->use_master_clock;
  1574. if (use_master_clock) {
  1575. host_tsc = ka->master_cycle_now;
  1576. kernel_ns = ka->master_kernel_ns;
  1577. }
  1578. spin_unlock(&ka->pvclock_gtod_sync_lock);
  1579. /* Keep irq disabled to prevent changes to the clock */
  1580. local_irq_save(flags);
  1581. tgt_tsc_khz = __this_cpu_read(cpu_tsc_khz);
  1582. if (unlikely(tgt_tsc_khz == 0)) {
  1583. local_irq_restore(flags);
  1584. kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
  1585. return 1;
  1586. }
  1587. if (!use_master_clock) {
  1588. host_tsc = rdtsc();
  1589. kernel_ns = ktime_get_boot_ns();
  1590. }
  1591. tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
  1592. /*
  1593. * We may have to catch up the TSC to match elapsed wall clock
  1594. * time for two reasons, even if kvmclock is used.
  1595. * 1) CPU could have been running below the maximum TSC rate
  1596. * 2) Broken TSC compensation resets the base at each VCPU
  1597. * entry to avoid unknown leaps of TSC even when running
  1598. * again on the same CPU. This may cause apparent elapsed
  1599. * time to disappear, and the guest to stand still or run
  1600. * very slowly.
  1601. */
  1602. if (vcpu->tsc_catchup) {
  1603. u64 tsc = compute_guest_tsc(v, kernel_ns);
  1604. if (tsc > tsc_timestamp) {
  1605. adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
  1606. tsc_timestamp = tsc;
  1607. }
  1608. }
  1609. local_irq_restore(flags);
  1610. /* With all the info we got, fill in the values */
  1611. if (kvm_has_tsc_control)
  1612. tgt_tsc_khz = kvm_scale_tsc(v, tgt_tsc_khz);
  1613. if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
  1614. kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
  1615. &vcpu->hv_clock.tsc_shift,
  1616. &vcpu->hv_clock.tsc_to_system_mul);
  1617. vcpu->hw_tsc_khz = tgt_tsc_khz;
  1618. }
  1619. vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
  1620. vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
  1621. vcpu->last_guest_tsc = tsc_timestamp;
  1622. /* If the host uses TSC clocksource, then it is stable */
  1623. pvclock_flags = 0;
  1624. if (use_master_clock)
  1625. pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
  1626. vcpu->hv_clock.flags = pvclock_flags;
  1627. if (vcpu->pv_time_enabled)
  1628. kvm_setup_pvclock_page(v);
  1629. if (v == kvm_get_vcpu(v->kvm, 0))
  1630. kvm_hv_setup_tsc_page(v->kvm, &vcpu->hv_clock);
  1631. return 0;
  1632. }
  1633. /*
  1634. * kvmclock updates which are isolated to a given vcpu, such as
  1635. * vcpu->cpu migration, should not allow system_timestamp from
  1636. * the rest of the vcpus to remain static. Otherwise ntp frequency
  1637. * correction applies to one vcpu's system_timestamp but not
  1638. * the others.
  1639. *
  1640. * So in those cases, request a kvmclock update for all vcpus.
  1641. * We need to rate-limit these requests though, as they can
  1642. * considerably slow guests that have a large number of vcpus.
  1643. * The time for a remote vcpu to update its kvmclock is bound
  1644. * by the delay we use to rate-limit the updates.
  1645. */
  1646. #define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
  1647. static void kvmclock_update_fn(struct work_struct *work)
  1648. {
  1649. int i;
  1650. struct delayed_work *dwork = to_delayed_work(work);
  1651. struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
  1652. kvmclock_update_work);
  1653. struct kvm *kvm = container_of(ka, struct kvm, arch);
  1654. struct kvm_vcpu *vcpu;
  1655. kvm_for_each_vcpu(i, vcpu, kvm) {
  1656. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  1657. kvm_vcpu_kick(vcpu);
  1658. }
  1659. }
  1660. static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
  1661. {
  1662. struct kvm *kvm = v->kvm;
  1663. kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
  1664. schedule_delayed_work(&kvm->arch.kvmclock_update_work,
  1665. KVMCLOCK_UPDATE_DELAY);
  1666. }
  1667. #define KVMCLOCK_SYNC_PERIOD (300 * HZ)
  1668. static void kvmclock_sync_fn(struct work_struct *work)
  1669. {
  1670. struct delayed_work *dwork = to_delayed_work(work);
  1671. struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
  1672. kvmclock_sync_work);
  1673. struct kvm *kvm = container_of(ka, struct kvm, arch);
  1674. if (!kvmclock_periodic_sync)
  1675. return;
  1676. schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
  1677. schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
  1678. KVMCLOCK_SYNC_PERIOD);
  1679. }
  1680. static int set_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 data)
  1681. {
  1682. u64 mcg_cap = vcpu->arch.mcg_cap;
  1683. unsigned bank_num = mcg_cap & 0xff;
  1684. switch (msr) {
  1685. case MSR_IA32_MCG_STATUS:
  1686. vcpu->arch.mcg_status = data;
  1687. break;
  1688. case MSR_IA32_MCG_CTL:
  1689. if (!(mcg_cap & MCG_CTL_P))
  1690. return 1;
  1691. if (data != 0 && data != ~(u64)0)
  1692. return -1;
  1693. vcpu->arch.mcg_ctl = data;
  1694. break;
  1695. default:
  1696. if (msr >= MSR_IA32_MC0_CTL &&
  1697. msr < MSR_IA32_MCx_CTL(bank_num)) {
  1698. u32 offset = msr - MSR_IA32_MC0_CTL;
  1699. /* only 0 or all 1s can be written to IA32_MCi_CTL
  1700. * some Linux kernels though clear bit 10 in bank 4 to
  1701. * workaround a BIOS/GART TBL issue on AMD K8s, ignore
  1702. * this to avoid an uncatched #GP in the guest
  1703. */
  1704. if ((offset & 0x3) == 0 &&
  1705. data != 0 && (data | (1 << 10)) != ~(u64)0)
  1706. return -1;
  1707. vcpu->arch.mce_banks[offset] = data;
  1708. break;
  1709. }
  1710. return 1;
  1711. }
  1712. return 0;
  1713. }
  1714. static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
  1715. {
  1716. struct kvm *kvm = vcpu->kvm;
  1717. int lm = is_long_mode(vcpu);
  1718. u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
  1719. : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
  1720. u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
  1721. : kvm->arch.xen_hvm_config.blob_size_32;
  1722. u32 page_num = data & ~PAGE_MASK;
  1723. u64 page_addr = data & PAGE_MASK;
  1724. u8 *page;
  1725. int r;
  1726. r = -E2BIG;
  1727. if (page_num >= blob_size)
  1728. goto out;
  1729. r = -ENOMEM;
  1730. page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
  1731. if (IS_ERR(page)) {
  1732. r = PTR_ERR(page);
  1733. goto out;
  1734. }
  1735. if (kvm_vcpu_write_guest(vcpu, page_addr, page, PAGE_SIZE))
  1736. goto out_free;
  1737. r = 0;
  1738. out_free:
  1739. kfree(page);
  1740. out:
  1741. return r;
  1742. }
  1743. static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
  1744. {
  1745. gpa_t gpa = data & ~0x3f;
  1746. /* Bits 2:5 are reserved, Should be zero */
  1747. if (data & 0x3c)
  1748. return 1;
  1749. vcpu->arch.apf.msr_val = data;
  1750. if (!(data & KVM_ASYNC_PF_ENABLED)) {
  1751. kvm_clear_async_pf_completion_queue(vcpu);
  1752. kvm_async_pf_hash_reset(vcpu);
  1753. return 0;
  1754. }
  1755. if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
  1756. sizeof(u32)))
  1757. return 1;
  1758. vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
  1759. kvm_async_pf_wakeup_all(vcpu);
  1760. return 0;
  1761. }
  1762. static void kvmclock_reset(struct kvm_vcpu *vcpu)
  1763. {
  1764. vcpu->arch.pv_time_enabled = false;
  1765. }
  1766. static void record_steal_time(struct kvm_vcpu *vcpu)
  1767. {
  1768. if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
  1769. return;
  1770. if (unlikely(kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
  1771. &vcpu->arch.st.steal, sizeof(struct kvm_steal_time))))
  1772. return;
  1773. vcpu->arch.st.steal.preempted = 0;
  1774. if (vcpu->arch.st.steal.version & 1)
  1775. vcpu->arch.st.steal.version += 1; /* first time write, random junk */
  1776. vcpu->arch.st.steal.version += 1;
  1777. kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
  1778. &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
  1779. smp_wmb();
  1780. vcpu->arch.st.steal.steal += current->sched_info.run_delay -
  1781. vcpu->arch.st.last_steal;
  1782. vcpu->arch.st.last_steal = current->sched_info.run_delay;
  1783. kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
  1784. &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
  1785. smp_wmb();
  1786. vcpu->arch.st.steal.version += 1;
  1787. kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
  1788. &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
  1789. }
  1790. int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
  1791. {
  1792. bool pr = false;
  1793. u32 msr = msr_info->index;
  1794. u64 data = msr_info->data;
  1795. switch (msr) {
  1796. case MSR_AMD64_NB_CFG:
  1797. case MSR_IA32_UCODE_REV:
  1798. case MSR_IA32_UCODE_WRITE:
  1799. case MSR_VM_HSAVE_PA:
  1800. case MSR_AMD64_PATCH_LOADER:
  1801. case MSR_AMD64_BU_CFG2:
  1802. case MSR_AMD64_DC_CFG:
  1803. break;
  1804. case MSR_EFER:
  1805. return set_efer(vcpu, data);
  1806. case MSR_K7_HWCR:
  1807. data &= ~(u64)0x40; /* ignore flush filter disable */
  1808. data &= ~(u64)0x100; /* ignore ignne emulation enable */
  1809. data &= ~(u64)0x8; /* ignore TLB cache disable */
  1810. data &= ~(u64)0x40000; /* ignore Mc status write enable */
  1811. if (data != 0) {
  1812. vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
  1813. data);
  1814. return 1;
  1815. }
  1816. break;
  1817. case MSR_FAM10H_MMIO_CONF_BASE:
  1818. if (data != 0) {
  1819. vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
  1820. "0x%llx\n", data);
  1821. return 1;
  1822. }
  1823. break;
  1824. case MSR_IA32_DEBUGCTLMSR:
  1825. if (!data) {
  1826. /* We support the non-activated case already */
  1827. break;
  1828. } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
  1829. /* Values other than LBR and BTF are vendor-specific,
  1830. thus reserved and should throw a #GP */
  1831. return 1;
  1832. }
  1833. vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
  1834. __func__, data);
  1835. break;
  1836. case 0x200 ... 0x2ff:
  1837. return kvm_mtrr_set_msr(vcpu, msr, data);
  1838. case MSR_IA32_APICBASE:
  1839. return kvm_set_apic_base(vcpu, msr_info);
  1840. case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
  1841. return kvm_x2apic_msr_write(vcpu, msr, data);
  1842. case MSR_IA32_TSCDEADLINE:
  1843. kvm_set_lapic_tscdeadline_msr(vcpu, data);
  1844. break;
  1845. case MSR_IA32_TSC_ADJUST:
  1846. if (guest_cpuid_has_tsc_adjust(vcpu)) {
  1847. if (!msr_info->host_initiated) {
  1848. s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
  1849. adjust_tsc_offset_guest(vcpu, adj);
  1850. }
  1851. vcpu->arch.ia32_tsc_adjust_msr = data;
  1852. }
  1853. break;
  1854. case MSR_IA32_MISC_ENABLE:
  1855. vcpu->arch.ia32_misc_enable_msr = data;
  1856. break;
  1857. case MSR_IA32_SMBASE:
  1858. if (!msr_info->host_initiated)
  1859. return 1;
  1860. vcpu->arch.smbase = data;
  1861. break;
  1862. case MSR_KVM_WALL_CLOCK_NEW:
  1863. case MSR_KVM_WALL_CLOCK:
  1864. vcpu->kvm->arch.wall_clock = data;
  1865. kvm_write_wall_clock(vcpu->kvm, data);
  1866. break;
  1867. case MSR_KVM_SYSTEM_TIME_NEW:
  1868. case MSR_KVM_SYSTEM_TIME: {
  1869. struct kvm_arch *ka = &vcpu->kvm->arch;
  1870. kvmclock_reset(vcpu);
  1871. if (vcpu->vcpu_id == 0 && !msr_info->host_initiated) {
  1872. bool tmp = (msr == MSR_KVM_SYSTEM_TIME);
  1873. if (ka->boot_vcpu_runs_old_kvmclock != tmp)
  1874. kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
  1875. ka->boot_vcpu_runs_old_kvmclock = tmp;
  1876. }
  1877. vcpu->arch.time = data;
  1878. kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
  1879. /* we verify if the enable bit is set... */
  1880. if (!(data & 1))
  1881. break;
  1882. if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
  1883. &vcpu->arch.pv_time, data & ~1ULL,
  1884. sizeof(struct pvclock_vcpu_time_info)))
  1885. vcpu->arch.pv_time_enabled = false;
  1886. else
  1887. vcpu->arch.pv_time_enabled = true;
  1888. break;
  1889. }
  1890. case MSR_KVM_ASYNC_PF_EN:
  1891. if (kvm_pv_enable_async_pf(vcpu, data))
  1892. return 1;
  1893. break;
  1894. case MSR_KVM_STEAL_TIME:
  1895. if (unlikely(!sched_info_on()))
  1896. return 1;
  1897. if (data & KVM_STEAL_RESERVED_MASK)
  1898. return 1;
  1899. if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
  1900. data & KVM_STEAL_VALID_BITS,
  1901. sizeof(struct kvm_steal_time)))
  1902. return 1;
  1903. vcpu->arch.st.msr_val = data;
  1904. if (!(data & KVM_MSR_ENABLED))
  1905. break;
  1906. kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
  1907. break;
  1908. case MSR_KVM_PV_EOI_EN:
  1909. if (kvm_lapic_enable_pv_eoi(vcpu, data))
  1910. return 1;
  1911. break;
  1912. case MSR_IA32_MCG_CTL:
  1913. case MSR_IA32_MCG_STATUS:
  1914. case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
  1915. return set_msr_mce(vcpu, msr, data);
  1916. case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
  1917. case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
  1918. pr = true; /* fall through */
  1919. case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
  1920. case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
  1921. if (kvm_pmu_is_valid_msr(vcpu, msr))
  1922. return kvm_pmu_set_msr(vcpu, msr_info);
  1923. if (pr || data != 0)
  1924. vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
  1925. "0x%x data 0x%llx\n", msr, data);
  1926. break;
  1927. case MSR_K7_CLK_CTL:
  1928. /*
  1929. * Ignore all writes to this no longer documented MSR.
  1930. * Writes are only relevant for old K7 processors,
  1931. * all pre-dating SVM, but a recommended workaround from
  1932. * AMD for these chips. It is possible to specify the
  1933. * affected processor models on the command line, hence
  1934. * the need to ignore the workaround.
  1935. */
  1936. break;
  1937. case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
  1938. case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
  1939. case HV_X64_MSR_CRASH_CTL:
  1940. case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
  1941. return kvm_hv_set_msr_common(vcpu, msr, data,
  1942. msr_info->host_initiated);
  1943. case MSR_IA32_BBL_CR_CTL3:
  1944. /* Drop writes to this legacy MSR -- see rdmsr
  1945. * counterpart for further detail.
  1946. */
  1947. vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data 0x%llx\n", msr, data);
  1948. break;
  1949. case MSR_AMD64_OSVW_ID_LENGTH:
  1950. if (!guest_cpuid_has_osvw(vcpu))
  1951. return 1;
  1952. vcpu->arch.osvw.length = data;
  1953. break;
  1954. case MSR_AMD64_OSVW_STATUS:
  1955. if (!guest_cpuid_has_osvw(vcpu))
  1956. return 1;
  1957. vcpu->arch.osvw.status = data;
  1958. break;
  1959. case MSR_PLATFORM_INFO:
  1960. if (!msr_info->host_initiated ||
  1961. data & ~MSR_PLATFORM_INFO_CPUID_FAULT ||
  1962. (!(data & MSR_PLATFORM_INFO_CPUID_FAULT) &&
  1963. cpuid_fault_enabled(vcpu)))
  1964. return 1;
  1965. vcpu->arch.msr_platform_info = data;
  1966. break;
  1967. case MSR_MISC_FEATURES_ENABLES:
  1968. if (data & ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT ||
  1969. (data & MSR_MISC_FEATURES_ENABLES_CPUID_FAULT &&
  1970. !supports_cpuid_fault(vcpu)))
  1971. return 1;
  1972. vcpu->arch.msr_misc_features_enables = data;
  1973. break;
  1974. default:
  1975. if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
  1976. return xen_hvm_config(vcpu, data);
  1977. if (kvm_pmu_is_valid_msr(vcpu, msr))
  1978. return kvm_pmu_set_msr(vcpu, msr_info);
  1979. if (!ignore_msrs) {
  1980. vcpu_debug_ratelimited(vcpu, "unhandled wrmsr: 0x%x data 0x%llx\n",
  1981. msr, data);
  1982. return 1;
  1983. } else {
  1984. vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data 0x%llx\n",
  1985. msr, data);
  1986. break;
  1987. }
  1988. }
  1989. return 0;
  1990. }
  1991. EXPORT_SYMBOL_GPL(kvm_set_msr_common);
  1992. /*
  1993. * Reads an msr value (of 'msr_index') into 'pdata'.
  1994. * Returns 0 on success, non-0 otherwise.
  1995. * Assumes vcpu_load() was already called.
  1996. */
  1997. int kvm_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
  1998. {
  1999. return kvm_x86_ops->get_msr(vcpu, msr);
  2000. }
  2001. EXPORT_SYMBOL_GPL(kvm_get_msr);
  2002. static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
  2003. {
  2004. u64 data;
  2005. u64 mcg_cap = vcpu->arch.mcg_cap;
  2006. unsigned bank_num = mcg_cap & 0xff;
  2007. switch (msr) {
  2008. case MSR_IA32_P5_MC_ADDR:
  2009. case MSR_IA32_P5_MC_TYPE:
  2010. data = 0;
  2011. break;
  2012. case MSR_IA32_MCG_CAP:
  2013. data = vcpu->arch.mcg_cap;
  2014. break;
  2015. case MSR_IA32_MCG_CTL:
  2016. if (!(mcg_cap & MCG_CTL_P))
  2017. return 1;
  2018. data = vcpu->arch.mcg_ctl;
  2019. break;
  2020. case MSR_IA32_MCG_STATUS:
  2021. data = vcpu->arch.mcg_status;
  2022. break;
  2023. default:
  2024. if (msr >= MSR_IA32_MC0_CTL &&
  2025. msr < MSR_IA32_MCx_CTL(bank_num)) {
  2026. u32 offset = msr - MSR_IA32_MC0_CTL;
  2027. data = vcpu->arch.mce_banks[offset];
  2028. break;
  2029. }
  2030. return 1;
  2031. }
  2032. *pdata = data;
  2033. return 0;
  2034. }
  2035. int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
  2036. {
  2037. switch (msr_info->index) {
  2038. case MSR_IA32_PLATFORM_ID:
  2039. case MSR_IA32_EBL_CR_POWERON:
  2040. case MSR_IA32_DEBUGCTLMSR:
  2041. case MSR_IA32_LASTBRANCHFROMIP:
  2042. case MSR_IA32_LASTBRANCHTOIP:
  2043. case MSR_IA32_LASTINTFROMIP:
  2044. case MSR_IA32_LASTINTTOIP:
  2045. case MSR_K8_SYSCFG:
  2046. case MSR_K8_TSEG_ADDR:
  2047. case MSR_K8_TSEG_MASK:
  2048. case MSR_K7_HWCR:
  2049. case MSR_VM_HSAVE_PA:
  2050. case MSR_K8_INT_PENDING_MSG:
  2051. case MSR_AMD64_NB_CFG:
  2052. case MSR_FAM10H_MMIO_CONF_BASE:
  2053. case MSR_AMD64_BU_CFG2:
  2054. case MSR_IA32_PERF_CTL:
  2055. case MSR_AMD64_DC_CFG:
  2056. msr_info->data = 0;
  2057. break;
  2058. case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
  2059. case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
  2060. case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
  2061. case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
  2062. if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
  2063. return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
  2064. msr_info->data = 0;
  2065. break;
  2066. case MSR_IA32_UCODE_REV:
  2067. msr_info->data = 0x100000000ULL;
  2068. break;
  2069. case MSR_MTRRcap:
  2070. case 0x200 ... 0x2ff:
  2071. return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
  2072. case 0xcd: /* fsb frequency */
  2073. msr_info->data = 3;
  2074. break;
  2075. /*
  2076. * MSR_EBC_FREQUENCY_ID
  2077. * Conservative value valid for even the basic CPU models.
  2078. * Models 0,1: 000 in bits 23:21 indicating a bus speed of
  2079. * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
  2080. * and 266MHz for model 3, or 4. Set Core Clock
  2081. * Frequency to System Bus Frequency Ratio to 1 (bits
  2082. * 31:24) even though these are only valid for CPU
  2083. * models > 2, however guests may end up dividing or
  2084. * multiplying by zero otherwise.
  2085. */
  2086. case MSR_EBC_FREQUENCY_ID:
  2087. msr_info->data = 1 << 24;
  2088. break;
  2089. case MSR_IA32_APICBASE:
  2090. msr_info->data = kvm_get_apic_base(vcpu);
  2091. break;
  2092. case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
  2093. return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
  2094. break;
  2095. case MSR_IA32_TSCDEADLINE:
  2096. msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
  2097. break;
  2098. case MSR_IA32_TSC_ADJUST:
  2099. msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
  2100. break;
  2101. case MSR_IA32_MISC_ENABLE:
  2102. msr_info->data = vcpu->arch.ia32_misc_enable_msr;
  2103. break;
  2104. case MSR_IA32_SMBASE:
  2105. if (!msr_info->host_initiated)
  2106. return 1;
  2107. msr_info->data = vcpu->arch.smbase;
  2108. break;
  2109. case MSR_IA32_PERF_STATUS:
  2110. /* TSC increment by tick */
  2111. msr_info->data = 1000ULL;
  2112. /* CPU multiplier */
  2113. msr_info->data |= (((uint64_t)4ULL) << 40);
  2114. break;
  2115. case MSR_EFER:
  2116. msr_info->data = vcpu->arch.efer;
  2117. break;
  2118. case MSR_KVM_WALL_CLOCK:
  2119. case MSR_KVM_WALL_CLOCK_NEW:
  2120. msr_info->data = vcpu->kvm->arch.wall_clock;
  2121. break;
  2122. case MSR_KVM_SYSTEM_TIME:
  2123. case MSR_KVM_SYSTEM_TIME_NEW:
  2124. msr_info->data = vcpu->arch.time;
  2125. break;
  2126. case MSR_KVM_ASYNC_PF_EN:
  2127. msr_info->data = vcpu->arch.apf.msr_val;
  2128. break;
  2129. case MSR_KVM_STEAL_TIME:
  2130. msr_info->data = vcpu->arch.st.msr_val;
  2131. break;
  2132. case MSR_KVM_PV_EOI_EN:
  2133. msr_info->data = vcpu->arch.pv_eoi.msr_val;
  2134. break;
  2135. case MSR_IA32_P5_MC_ADDR:
  2136. case MSR_IA32_P5_MC_TYPE:
  2137. case MSR_IA32_MCG_CAP:
  2138. case MSR_IA32_MCG_CTL:
  2139. case MSR_IA32_MCG_STATUS:
  2140. case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
  2141. return get_msr_mce(vcpu, msr_info->index, &msr_info->data);
  2142. case MSR_K7_CLK_CTL:
  2143. /*
  2144. * Provide expected ramp-up count for K7. All other
  2145. * are set to zero, indicating minimum divisors for
  2146. * every field.
  2147. *
  2148. * This prevents guest kernels on AMD host with CPU
  2149. * type 6, model 8 and higher from exploding due to
  2150. * the rdmsr failing.
  2151. */
  2152. msr_info->data = 0x20000000;
  2153. break;
  2154. case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
  2155. case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
  2156. case HV_X64_MSR_CRASH_CTL:
  2157. case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
  2158. return kvm_hv_get_msr_common(vcpu,
  2159. msr_info->index, &msr_info->data);
  2160. break;
  2161. case MSR_IA32_BBL_CR_CTL3:
  2162. /* This legacy MSR exists but isn't fully documented in current
  2163. * silicon. It is however accessed by winxp in very narrow
  2164. * scenarios where it sets bit #19, itself documented as
  2165. * a "reserved" bit. Best effort attempt to source coherent
  2166. * read data here should the balance of the register be
  2167. * interpreted by the guest:
  2168. *
  2169. * L2 cache control register 3: 64GB range, 256KB size,
  2170. * enabled, latency 0x1, configured
  2171. */
  2172. msr_info->data = 0xbe702111;
  2173. break;
  2174. case MSR_AMD64_OSVW_ID_LENGTH:
  2175. if (!guest_cpuid_has_osvw(vcpu))
  2176. return 1;
  2177. msr_info->data = vcpu->arch.osvw.length;
  2178. break;
  2179. case MSR_AMD64_OSVW_STATUS:
  2180. if (!guest_cpuid_has_osvw(vcpu))
  2181. return 1;
  2182. msr_info->data = vcpu->arch.osvw.status;
  2183. break;
  2184. case MSR_PLATFORM_INFO:
  2185. msr_info->data = vcpu->arch.msr_platform_info;
  2186. break;
  2187. case MSR_MISC_FEATURES_ENABLES:
  2188. msr_info->data = vcpu->arch.msr_misc_features_enables;
  2189. break;
  2190. default:
  2191. if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
  2192. return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
  2193. if (!ignore_msrs) {
  2194. vcpu_debug_ratelimited(vcpu, "unhandled rdmsr: 0x%x\n",
  2195. msr_info->index);
  2196. return 1;
  2197. } else {
  2198. vcpu_unimpl(vcpu, "ignored rdmsr: 0x%x\n", msr_info->index);
  2199. msr_info->data = 0;
  2200. }
  2201. break;
  2202. }
  2203. return 0;
  2204. }
  2205. EXPORT_SYMBOL_GPL(kvm_get_msr_common);
  2206. /*
  2207. * Read or write a bunch of msrs. All parameters are kernel addresses.
  2208. *
  2209. * @return number of msrs set successfully.
  2210. */
  2211. static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
  2212. struct kvm_msr_entry *entries,
  2213. int (*do_msr)(struct kvm_vcpu *vcpu,
  2214. unsigned index, u64 *data))
  2215. {
  2216. int i, idx;
  2217. idx = srcu_read_lock(&vcpu->kvm->srcu);
  2218. for (i = 0; i < msrs->nmsrs; ++i)
  2219. if (do_msr(vcpu, entries[i].index, &entries[i].data))
  2220. break;
  2221. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  2222. return i;
  2223. }
  2224. /*
  2225. * Read or write a bunch of msrs. Parameters are user addresses.
  2226. *
  2227. * @return number of msrs set successfully.
  2228. */
  2229. static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
  2230. int (*do_msr)(struct kvm_vcpu *vcpu,
  2231. unsigned index, u64 *data),
  2232. int writeback)
  2233. {
  2234. struct kvm_msrs msrs;
  2235. struct kvm_msr_entry *entries;
  2236. int r, n;
  2237. unsigned size;
  2238. r = -EFAULT;
  2239. if (copy_from_user(&msrs, user_msrs, sizeof msrs))
  2240. goto out;
  2241. r = -E2BIG;
  2242. if (msrs.nmsrs >= MAX_IO_MSRS)
  2243. goto out;
  2244. size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
  2245. entries = memdup_user(user_msrs->entries, size);
  2246. if (IS_ERR(entries)) {
  2247. r = PTR_ERR(entries);
  2248. goto out;
  2249. }
  2250. r = n = __msr_io(vcpu, &msrs, entries, do_msr);
  2251. if (r < 0)
  2252. goto out_free;
  2253. r = -EFAULT;
  2254. if (writeback && copy_to_user(user_msrs->entries, entries, size))
  2255. goto out_free;
  2256. r = n;
  2257. out_free:
  2258. kfree(entries);
  2259. out:
  2260. return r;
  2261. }
  2262. int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
  2263. {
  2264. int r;
  2265. switch (ext) {
  2266. case KVM_CAP_IRQCHIP:
  2267. case KVM_CAP_HLT:
  2268. case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
  2269. case KVM_CAP_SET_TSS_ADDR:
  2270. case KVM_CAP_EXT_CPUID:
  2271. case KVM_CAP_EXT_EMUL_CPUID:
  2272. case KVM_CAP_CLOCKSOURCE:
  2273. case KVM_CAP_PIT:
  2274. case KVM_CAP_NOP_IO_DELAY:
  2275. case KVM_CAP_MP_STATE:
  2276. case KVM_CAP_SYNC_MMU:
  2277. case KVM_CAP_USER_NMI:
  2278. case KVM_CAP_REINJECT_CONTROL:
  2279. case KVM_CAP_IRQ_INJECT_STATUS:
  2280. case KVM_CAP_IOEVENTFD:
  2281. case KVM_CAP_IOEVENTFD_NO_LENGTH:
  2282. case KVM_CAP_PIT2:
  2283. case KVM_CAP_PIT_STATE2:
  2284. case KVM_CAP_SET_IDENTITY_MAP_ADDR:
  2285. case KVM_CAP_XEN_HVM:
  2286. case KVM_CAP_VCPU_EVENTS:
  2287. case KVM_CAP_HYPERV:
  2288. case KVM_CAP_HYPERV_VAPIC:
  2289. case KVM_CAP_HYPERV_SPIN:
  2290. case KVM_CAP_HYPERV_SYNIC:
  2291. case KVM_CAP_HYPERV_SYNIC2:
  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. /*
  2486. * Disable page faults because we're in atomic context here.
  2487. * kvm_write_guest_offset_cached() would call might_fault()
  2488. * that relies on pagefault_disable() to tell if there's a
  2489. * bug. NOTE: the write to guest memory may not go through if
  2490. * during postcopy live migration or if there's heavy guest
  2491. * paging.
  2492. */
  2493. pagefault_disable();
  2494. /*
  2495. * kvm_memslots() will be called by
  2496. * kvm_write_guest_offset_cached() so take the srcu lock.
  2497. */
  2498. idx = srcu_read_lock(&vcpu->kvm->srcu);
  2499. kvm_steal_time_set_preempted(vcpu);
  2500. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  2501. pagefault_enable();
  2502. kvm_x86_ops->vcpu_put(vcpu);
  2503. kvm_put_guest_fpu(vcpu);
  2504. vcpu->arch.last_host_tsc = rdtsc();
  2505. }
  2506. static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
  2507. struct kvm_lapic_state *s)
  2508. {
  2509. if (kvm_x86_ops->sync_pir_to_irr && vcpu->arch.apicv_active)
  2510. kvm_x86_ops->sync_pir_to_irr(vcpu);
  2511. return kvm_apic_get_state(vcpu, s);
  2512. }
  2513. static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
  2514. struct kvm_lapic_state *s)
  2515. {
  2516. int r;
  2517. r = kvm_apic_set_state(vcpu, s);
  2518. if (r)
  2519. return r;
  2520. update_cr8_intercept(vcpu);
  2521. return 0;
  2522. }
  2523. static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
  2524. {
  2525. return (!lapic_in_kernel(vcpu) ||
  2526. kvm_apic_accept_pic_intr(vcpu));
  2527. }
  2528. /*
  2529. * if userspace requested an interrupt window, check that the
  2530. * interrupt window is open.
  2531. *
  2532. * No need to exit to userspace if we already have an interrupt queued.
  2533. */
  2534. static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
  2535. {
  2536. return kvm_arch_interrupt_allowed(vcpu) &&
  2537. !kvm_cpu_has_interrupt(vcpu) &&
  2538. !kvm_event_needs_reinjection(vcpu) &&
  2539. kvm_cpu_accept_dm_intr(vcpu);
  2540. }
  2541. static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
  2542. struct kvm_interrupt *irq)
  2543. {
  2544. if (irq->irq >= KVM_NR_INTERRUPTS)
  2545. return -EINVAL;
  2546. if (!irqchip_in_kernel(vcpu->kvm)) {
  2547. kvm_queue_interrupt(vcpu, irq->irq, false);
  2548. kvm_make_request(KVM_REQ_EVENT, vcpu);
  2549. return 0;
  2550. }
  2551. /*
  2552. * With in-kernel LAPIC, we only use this to inject EXTINT, so
  2553. * fail for in-kernel 8259.
  2554. */
  2555. if (pic_in_kernel(vcpu->kvm))
  2556. return -ENXIO;
  2557. if (vcpu->arch.pending_external_vector != -1)
  2558. return -EEXIST;
  2559. vcpu->arch.pending_external_vector = irq->irq;
  2560. kvm_make_request(KVM_REQ_EVENT, vcpu);
  2561. return 0;
  2562. }
  2563. static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
  2564. {
  2565. kvm_inject_nmi(vcpu);
  2566. return 0;
  2567. }
  2568. static int kvm_vcpu_ioctl_smi(struct kvm_vcpu *vcpu)
  2569. {
  2570. kvm_make_request(KVM_REQ_SMI, vcpu);
  2571. return 0;
  2572. }
  2573. static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
  2574. struct kvm_tpr_access_ctl *tac)
  2575. {
  2576. if (tac->flags)
  2577. return -EINVAL;
  2578. vcpu->arch.tpr_access_reporting = !!tac->enabled;
  2579. return 0;
  2580. }
  2581. static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
  2582. u64 mcg_cap)
  2583. {
  2584. int r;
  2585. unsigned bank_num = mcg_cap & 0xff, bank;
  2586. r = -EINVAL;
  2587. if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
  2588. goto out;
  2589. if (mcg_cap & ~(kvm_mce_cap_supported | 0xff | 0xff0000))
  2590. goto out;
  2591. r = 0;
  2592. vcpu->arch.mcg_cap = mcg_cap;
  2593. /* Init IA32_MCG_CTL to all 1s */
  2594. if (mcg_cap & MCG_CTL_P)
  2595. vcpu->arch.mcg_ctl = ~(u64)0;
  2596. /* Init IA32_MCi_CTL to all 1s */
  2597. for (bank = 0; bank < bank_num; bank++)
  2598. vcpu->arch.mce_banks[bank*4] = ~(u64)0;
  2599. if (kvm_x86_ops->setup_mce)
  2600. kvm_x86_ops->setup_mce(vcpu);
  2601. out:
  2602. return r;
  2603. }
  2604. static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
  2605. struct kvm_x86_mce *mce)
  2606. {
  2607. u64 mcg_cap = vcpu->arch.mcg_cap;
  2608. unsigned bank_num = mcg_cap & 0xff;
  2609. u64 *banks = vcpu->arch.mce_banks;
  2610. if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
  2611. return -EINVAL;
  2612. /*
  2613. * if IA32_MCG_CTL is not all 1s, the uncorrected error
  2614. * reporting is disabled
  2615. */
  2616. if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
  2617. vcpu->arch.mcg_ctl != ~(u64)0)
  2618. return 0;
  2619. banks += 4 * mce->bank;
  2620. /*
  2621. * if IA32_MCi_CTL is not all 1s, the uncorrected error
  2622. * reporting is disabled for the bank
  2623. */
  2624. if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
  2625. return 0;
  2626. if (mce->status & MCI_STATUS_UC) {
  2627. if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
  2628. !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
  2629. kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
  2630. return 0;
  2631. }
  2632. if (banks[1] & MCI_STATUS_VAL)
  2633. mce->status |= MCI_STATUS_OVER;
  2634. banks[2] = mce->addr;
  2635. banks[3] = mce->misc;
  2636. vcpu->arch.mcg_status = mce->mcg_status;
  2637. banks[1] = mce->status;
  2638. kvm_queue_exception(vcpu, MC_VECTOR);
  2639. } else if (!(banks[1] & MCI_STATUS_VAL)
  2640. || !(banks[1] & MCI_STATUS_UC)) {
  2641. if (banks[1] & MCI_STATUS_VAL)
  2642. mce->status |= MCI_STATUS_OVER;
  2643. banks[2] = mce->addr;
  2644. banks[3] = mce->misc;
  2645. banks[1] = mce->status;
  2646. } else
  2647. banks[1] |= MCI_STATUS_OVER;
  2648. return 0;
  2649. }
  2650. static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
  2651. struct kvm_vcpu_events *events)
  2652. {
  2653. process_nmi(vcpu);
  2654. events->exception.injected =
  2655. vcpu->arch.exception.pending &&
  2656. !kvm_exception_is_soft(vcpu->arch.exception.nr);
  2657. events->exception.nr = vcpu->arch.exception.nr;
  2658. events->exception.has_error_code = vcpu->arch.exception.has_error_code;
  2659. events->exception.pad = 0;
  2660. events->exception.error_code = vcpu->arch.exception.error_code;
  2661. events->interrupt.injected =
  2662. vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft;
  2663. events->interrupt.nr = vcpu->arch.interrupt.nr;
  2664. events->interrupt.soft = 0;
  2665. events->interrupt.shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
  2666. events->nmi.injected = vcpu->arch.nmi_injected;
  2667. events->nmi.pending = vcpu->arch.nmi_pending != 0;
  2668. events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
  2669. events->nmi.pad = 0;
  2670. events->sipi_vector = 0; /* never valid when reporting to user space */
  2671. events->smi.smm = is_smm(vcpu);
  2672. events->smi.pending = vcpu->arch.smi_pending;
  2673. events->smi.smm_inside_nmi =
  2674. !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
  2675. events->smi.latched_init = kvm_lapic_latched_init(vcpu);
  2676. events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
  2677. | KVM_VCPUEVENT_VALID_SHADOW
  2678. | KVM_VCPUEVENT_VALID_SMM);
  2679. memset(&events->reserved, 0, sizeof(events->reserved));
  2680. }
  2681. static void kvm_set_hflags(struct kvm_vcpu *vcpu, unsigned emul_flags);
  2682. static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
  2683. struct kvm_vcpu_events *events)
  2684. {
  2685. if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
  2686. | KVM_VCPUEVENT_VALID_SIPI_VECTOR
  2687. | KVM_VCPUEVENT_VALID_SHADOW
  2688. | KVM_VCPUEVENT_VALID_SMM))
  2689. return -EINVAL;
  2690. if (events->exception.injected &&
  2691. (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR ||
  2692. is_guest_mode(vcpu)))
  2693. return -EINVAL;
  2694. /* INITs are latched while in SMM */
  2695. if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
  2696. (events->smi.smm || events->smi.pending) &&
  2697. vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
  2698. return -EINVAL;
  2699. process_nmi(vcpu);
  2700. vcpu->arch.exception.pending = events->exception.injected;
  2701. vcpu->arch.exception.nr = events->exception.nr;
  2702. vcpu->arch.exception.has_error_code = events->exception.has_error_code;
  2703. vcpu->arch.exception.error_code = events->exception.error_code;
  2704. vcpu->arch.interrupt.pending = events->interrupt.injected;
  2705. vcpu->arch.interrupt.nr = events->interrupt.nr;
  2706. vcpu->arch.interrupt.soft = events->interrupt.soft;
  2707. if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
  2708. kvm_x86_ops->set_interrupt_shadow(vcpu,
  2709. events->interrupt.shadow);
  2710. vcpu->arch.nmi_injected = events->nmi.injected;
  2711. if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
  2712. vcpu->arch.nmi_pending = events->nmi.pending;
  2713. kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
  2714. if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
  2715. lapic_in_kernel(vcpu))
  2716. vcpu->arch.apic->sipi_vector = events->sipi_vector;
  2717. if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
  2718. u32 hflags = vcpu->arch.hflags;
  2719. if (events->smi.smm)
  2720. hflags |= HF_SMM_MASK;
  2721. else
  2722. hflags &= ~HF_SMM_MASK;
  2723. kvm_set_hflags(vcpu, hflags);
  2724. vcpu->arch.smi_pending = events->smi.pending;
  2725. if (events->smi.smm_inside_nmi)
  2726. vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
  2727. else
  2728. vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
  2729. if (lapic_in_kernel(vcpu)) {
  2730. if (events->smi.latched_init)
  2731. set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
  2732. else
  2733. clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
  2734. }
  2735. }
  2736. kvm_make_request(KVM_REQ_EVENT, vcpu);
  2737. return 0;
  2738. }
  2739. static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
  2740. struct kvm_debugregs *dbgregs)
  2741. {
  2742. unsigned long val;
  2743. memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
  2744. kvm_get_dr(vcpu, 6, &val);
  2745. dbgregs->dr6 = val;
  2746. dbgregs->dr7 = vcpu->arch.dr7;
  2747. dbgregs->flags = 0;
  2748. memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
  2749. }
  2750. static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
  2751. struct kvm_debugregs *dbgregs)
  2752. {
  2753. if (dbgregs->flags)
  2754. return -EINVAL;
  2755. if (dbgregs->dr6 & ~0xffffffffull)
  2756. return -EINVAL;
  2757. if (dbgregs->dr7 & ~0xffffffffull)
  2758. return -EINVAL;
  2759. memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
  2760. kvm_update_dr0123(vcpu);
  2761. vcpu->arch.dr6 = dbgregs->dr6;
  2762. kvm_update_dr6(vcpu);
  2763. vcpu->arch.dr7 = dbgregs->dr7;
  2764. kvm_update_dr7(vcpu);
  2765. return 0;
  2766. }
  2767. #define XSTATE_COMPACTION_ENABLED (1ULL << 63)
  2768. static void fill_xsave(u8 *dest, struct kvm_vcpu *vcpu)
  2769. {
  2770. struct xregs_state *xsave = &vcpu->arch.guest_fpu.state.xsave;
  2771. u64 xstate_bv = xsave->header.xfeatures;
  2772. u64 valid;
  2773. /*
  2774. * Copy legacy XSAVE area, to avoid complications with CPUID
  2775. * leaves 0 and 1 in the loop below.
  2776. */
  2777. memcpy(dest, xsave, XSAVE_HDR_OFFSET);
  2778. /* Set XSTATE_BV */
  2779. xstate_bv &= vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FPSSE;
  2780. *(u64 *)(dest + XSAVE_HDR_OFFSET) = xstate_bv;
  2781. /*
  2782. * Copy each region from the possibly compacted offset to the
  2783. * non-compacted offset.
  2784. */
  2785. valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
  2786. while (valid) {
  2787. u64 feature = valid & -valid;
  2788. int index = fls64(feature) - 1;
  2789. void *src = get_xsave_addr(xsave, feature);
  2790. if (src) {
  2791. u32 size, offset, ecx, edx;
  2792. cpuid_count(XSTATE_CPUID, index,
  2793. &size, &offset, &ecx, &edx);
  2794. memcpy(dest + offset, src, size);
  2795. }
  2796. valid -= feature;
  2797. }
  2798. }
  2799. static void load_xsave(struct kvm_vcpu *vcpu, u8 *src)
  2800. {
  2801. struct xregs_state *xsave = &vcpu->arch.guest_fpu.state.xsave;
  2802. u64 xstate_bv = *(u64 *)(src + XSAVE_HDR_OFFSET);
  2803. u64 valid;
  2804. /*
  2805. * Copy legacy XSAVE area, to avoid complications with CPUID
  2806. * leaves 0 and 1 in the loop below.
  2807. */
  2808. memcpy(xsave, src, XSAVE_HDR_OFFSET);
  2809. /* Set XSTATE_BV and possibly XCOMP_BV. */
  2810. xsave->header.xfeatures = xstate_bv;
  2811. if (boot_cpu_has(X86_FEATURE_XSAVES))
  2812. xsave->header.xcomp_bv = host_xcr0 | XSTATE_COMPACTION_ENABLED;
  2813. /*
  2814. * Copy each region from the non-compacted offset to the
  2815. * possibly compacted offset.
  2816. */
  2817. valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
  2818. while (valid) {
  2819. u64 feature = valid & -valid;
  2820. int index = fls64(feature) - 1;
  2821. void *dest = get_xsave_addr(xsave, feature);
  2822. if (dest) {
  2823. u32 size, offset, ecx, edx;
  2824. cpuid_count(XSTATE_CPUID, index,
  2825. &size, &offset, &ecx, &edx);
  2826. memcpy(dest, src + offset, size);
  2827. }
  2828. valid -= feature;
  2829. }
  2830. }
  2831. static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
  2832. struct kvm_xsave *guest_xsave)
  2833. {
  2834. if (boot_cpu_has(X86_FEATURE_XSAVE)) {
  2835. memset(guest_xsave, 0, sizeof(struct kvm_xsave));
  2836. fill_xsave((u8 *) guest_xsave->region, vcpu);
  2837. } else {
  2838. memcpy(guest_xsave->region,
  2839. &vcpu->arch.guest_fpu.state.fxsave,
  2840. sizeof(struct fxregs_state));
  2841. *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
  2842. XFEATURE_MASK_FPSSE;
  2843. }
  2844. }
  2845. #define XSAVE_MXCSR_OFFSET 24
  2846. static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
  2847. struct kvm_xsave *guest_xsave)
  2848. {
  2849. u64 xstate_bv =
  2850. *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
  2851. u32 mxcsr = *(u32 *)&guest_xsave->region[XSAVE_MXCSR_OFFSET / sizeof(u32)];
  2852. if (boot_cpu_has(X86_FEATURE_XSAVE)) {
  2853. /*
  2854. * Here we allow setting states that are not present in
  2855. * CPUID leaf 0xD, index 0, EDX:EAX. This is for compatibility
  2856. * with old userspace.
  2857. */
  2858. if (xstate_bv & ~kvm_supported_xcr0() ||
  2859. mxcsr & ~mxcsr_feature_mask)
  2860. return -EINVAL;
  2861. load_xsave(vcpu, (u8 *)guest_xsave->region);
  2862. } else {
  2863. if (xstate_bv & ~XFEATURE_MASK_FPSSE ||
  2864. mxcsr & ~mxcsr_feature_mask)
  2865. return -EINVAL;
  2866. memcpy(&vcpu->arch.guest_fpu.state.fxsave,
  2867. guest_xsave->region, sizeof(struct fxregs_state));
  2868. }
  2869. return 0;
  2870. }
  2871. static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
  2872. struct kvm_xcrs *guest_xcrs)
  2873. {
  2874. if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
  2875. guest_xcrs->nr_xcrs = 0;
  2876. return;
  2877. }
  2878. guest_xcrs->nr_xcrs = 1;
  2879. guest_xcrs->flags = 0;
  2880. guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
  2881. guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
  2882. }
  2883. static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
  2884. struct kvm_xcrs *guest_xcrs)
  2885. {
  2886. int i, r = 0;
  2887. if (!boot_cpu_has(X86_FEATURE_XSAVE))
  2888. return -EINVAL;
  2889. if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
  2890. return -EINVAL;
  2891. for (i = 0; i < guest_xcrs->nr_xcrs; i++)
  2892. /* Only support XCR0 currently */
  2893. if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
  2894. r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
  2895. guest_xcrs->xcrs[i].value);
  2896. break;
  2897. }
  2898. if (r)
  2899. r = -EINVAL;
  2900. return r;
  2901. }
  2902. /*
  2903. * kvm_set_guest_paused() indicates to the guest kernel that it has been
  2904. * stopped by the hypervisor. This function will be called from the host only.
  2905. * EINVAL is returned when the host attempts to set the flag for a guest that
  2906. * does not support pv clocks.
  2907. */
  2908. static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
  2909. {
  2910. if (!vcpu->arch.pv_time_enabled)
  2911. return -EINVAL;
  2912. vcpu->arch.pvclock_set_guest_stopped_request = true;
  2913. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  2914. return 0;
  2915. }
  2916. static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
  2917. struct kvm_enable_cap *cap)
  2918. {
  2919. if (cap->flags)
  2920. return -EINVAL;
  2921. switch (cap->cap) {
  2922. case KVM_CAP_HYPERV_SYNIC2:
  2923. if (cap->args[0])
  2924. return -EINVAL;
  2925. case KVM_CAP_HYPERV_SYNIC:
  2926. if (!irqchip_in_kernel(vcpu->kvm))
  2927. return -EINVAL;
  2928. return kvm_hv_activate_synic(vcpu, cap->cap ==
  2929. KVM_CAP_HYPERV_SYNIC2);
  2930. default:
  2931. return -EINVAL;
  2932. }
  2933. }
  2934. long kvm_arch_vcpu_ioctl(struct file *filp,
  2935. unsigned int ioctl, unsigned long arg)
  2936. {
  2937. struct kvm_vcpu *vcpu = filp->private_data;
  2938. void __user *argp = (void __user *)arg;
  2939. int r;
  2940. union {
  2941. struct kvm_lapic_state *lapic;
  2942. struct kvm_xsave *xsave;
  2943. struct kvm_xcrs *xcrs;
  2944. void *buffer;
  2945. } u;
  2946. u.buffer = NULL;
  2947. switch (ioctl) {
  2948. case KVM_GET_LAPIC: {
  2949. r = -EINVAL;
  2950. if (!lapic_in_kernel(vcpu))
  2951. goto out;
  2952. u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
  2953. r = -ENOMEM;
  2954. if (!u.lapic)
  2955. goto out;
  2956. r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
  2957. if (r)
  2958. goto out;
  2959. r = -EFAULT;
  2960. if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
  2961. goto out;
  2962. r = 0;
  2963. break;
  2964. }
  2965. case KVM_SET_LAPIC: {
  2966. r = -EINVAL;
  2967. if (!lapic_in_kernel(vcpu))
  2968. goto out;
  2969. u.lapic = memdup_user(argp, sizeof(*u.lapic));
  2970. if (IS_ERR(u.lapic))
  2971. return PTR_ERR(u.lapic);
  2972. r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
  2973. break;
  2974. }
  2975. case KVM_INTERRUPT: {
  2976. struct kvm_interrupt irq;
  2977. r = -EFAULT;
  2978. if (copy_from_user(&irq, argp, sizeof irq))
  2979. goto out;
  2980. r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
  2981. break;
  2982. }
  2983. case KVM_NMI: {
  2984. r = kvm_vcpu_ioctl_nmi(vcpu);
  2985. break;
  2986. }
  2987. case KVM_SMI: {
  2988. r = kvm_vcpu_ioctl_smi(vcpu);
  2989. break;
  2990. }
  2991. case KVM_SET_CPUID: {
  2992. struct kvm_cpuid __user *cpuid_arg = argp;
  2993. struct kvm_cpuid cpuid;
  2994. r = -EFAULT;
  2995. if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
  2996. goto out;
  2997. r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
  2998. break;
  2999. }
  3000. case KVM_SET_CPUID2: {
  3001. struct kvm_cpuid2 __user *cpuid_arg = argp;
  3002. struct kvm_cpuid2 cpuid;
  3003. r = -EFAULT;
  3004. if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
  3005. goto out;
  3006. r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
  3007. cpuid_arg->entries);
  3008. break;
  3009. }
  3010. case KVM_GET_CPUID2: {
  3011. struct kvm_cpuid2 __user *cpuid_arg = argp;
  3012. struct kvm_cpuid2 cpuid;
  3013. r = -EFAULT;
  3014. if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
  3015. goto out;
  3016. r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
  3017. cpuid_arg->entries);
  3018. if (r)
  3019. goto out;
  3020. r = -EFAULT;
  3021. if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
  3022. goto out;
  3023. r = 0;
  3024. break;
  3025. }
  3026. case KVM_GET_MSRS:
  3027. r = msr_io(vcpu, argp, do_get_msr, 1);
  3028. break;
  3029. case KVM_SET_MSRS:
  3030. r = msr_io(vcpu, argp, do_set_msr, 0);
  3031. break;
  3032. case KVM_TPR_ACCESS_REPORTING: {
  3033. struct kvm_tpr_access_ctl tac;
  3034. r = -EFAULT;
  3035. if (copy_from_user(&tac, argp, sizeof tac))
  3036. goto out;
  3037. r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
  3038. if (r)
  3039. goto out;
  3040. r = -EFAULT;
  3041. if (copy_to_user(argp, &tac, sizeof tac))
  3042. goto out;
  3043. r = 0;
  3044. break;
  3045. };
  3046. case KVM_SET_VAPIC_ADDR: {
  3047. struct kvm_vapic_addr va;
  3048. int idx;
  3049. r = -EINVAL;
  3050. if (!lapic_in_kernel(vcpu))
  3051. goto out;
  3052. r = -EFAULT;
  3053. if (copy_from_user(&va, argp, sizeof va))
  3054. goto out;
  3055. idx = srcu_read_lock(&vcpu->kvm->srcu);
  3056. r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
  3057. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  3058. break;
  3059. }
  3060. case KVM_X86_SETUP_MCE: {
  3061. u64 mcg_cap;
  3062. r = -EFAULT;
  3063. if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
  3064. goto out;
  3065. r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
  3066. break;
  3067. }
  3068. case KVM_X86_SET_MCE: {
  3069. struct kvm_x86_mce mce;
  3070. r = -EFAULT;
  3071. if (copy_from_user(&mce, argp, sizeof mce))
  3072. goto out;
  3073. r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
  3074. break;
  3075. }
  3076. case KVM_GET_VCPU_EVENTS: {
  3077. struct kvm_vcpu_events events;
  3078. kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
  3079. r = -EFAULT;
  3080. if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
  3081. break;
  3082. r = 0;
  3083. break;
  3084. }
  3085. case KVM_SET_VCPU_EVENTS: {
  3086. struct kvm_vcpu_events events;
  3087. r = -EFAULT;
  3088. if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
  3089. break;
  3090. r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
  3091. break;
  3092. }
  3093. case KVM_GET_DEBUGREGS: {
  3094. struct kvm_debugregs dbgregs;
  3095. kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
  3096. r = -EFAULT;
  3097. if (copy_to_user(argp, &dbgregs,
  3098. sizeof(struct kvm_debugregs)))
  3099. break;
  3100. r = 0;
  3101. break;
  3102. }
  3103. case KVM_SET_DEBUGREGS: {
  3104. struct kvm_debugregs dbgregs;
  3105. r = -EFAULT;
  3106. if (copy_from_user(&dbgregs, argp,
  3107. sizeof(struct kvm_debugregs)))
  3108. break;
  3109. r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
  3110. break;
  3111. }
  3112. case KVM_GET_XSAVE: {
  3113. u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
  3114. r = -ENOMEM;
  3115. if (!u.xsave)
  3116. break;
  3117. kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
  3118. r = -EFAULT;
  3119. if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
  3120. break;
  3121. r = 0;
  3122. break;
  3123. }
  3124. case KVM_SET_XSAVE: {
  3125. u.xsave = memdup_user(argp, sizeof(*u.xsave));
  3126. if (IS_ERR(u.xsave))
  3127. return PTR_ERR(u.xsave);
  3128. r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
  3129. break;
  3130. }
  3131. case KVM_GET_XCRS: {
  3132. u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
  3133. r = -ENOMEM;
  3134. if (!u.xcrs)
  3135. break;
  3136. kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
  3137. r = -EFAULT;
  3138. if (copy_to_user(argp, u.xcrs,
  3139. sizeof(struct kvm_xcrs)))
  3140. break;
  3141. r = 0;
  3142. break;
  3143. }
  3144. case KVM_SET_XCRS: {
  3145. u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
  3146. if (IS_ERR(u.xcrs))
  3147. return PTR_ERR(u.xcrs);
  3148. r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
  3149. break;
  3150. }
  3151. case KVM_SET_TSC_KHZ: {
  3152. u32 user_tsc_khz;
  3153. r = -EINVAL;
  3154. user_tsc_khz = (u32)arg;
  3155. if (user_tsc_khz >= kvm_max_guest_tsc_khz)
  3156. goto out;
  3157. if (user_tsc_khz == 0)
  3158. user_tsc_khz = tsc_khz;
  3159. if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
  3160. r = 0;
  3161. goto out;
  3162. }
  3163. case KVM_GET_TSC_KHZ: {
  3164. r = vcpu->arch.virtual_tsc_khz;
  3165. goto out;
  3166. }
  3167. case KVM_KVMCLOCK_CTRL: {
  3168. r = kvm_set_guest_paused(vcpu);
  3169. goto out;
  3170. }
  3171. case KVM_ENABLE_CAP: {
  3172. struct kvm_enable_cap cap;
  3173. r = -EFAULT;
  3174. if (copy_from_user(&cap, argp, sizeof(cap)))
  3175. goto out;
  3176. r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
  3177. break;
  3178. }
  3179. default:
  3180. r = -EINVAL;
  3181. }
  3182. out:
  3183. kfree(u.buffer);
  3184. return r;
  3185. }
  3186. int kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
  3187. {
  3188. return VM_FAULT_SIGBUS;
  3189. }
  3190. static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
  3191. {
  3192. int ret;
  3193. if (addr > (unsigned int)(-3 * PAGE_SIZE))
  3194. return -EINVAL;
  3195. ret = kvm_x86_ops->set_tss_addr(kvm, addr);
  3196. return ret;
  3197. }
  3198. static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
  3199. u64 ident_addr)
  3200. {
  3201. kvm->arch.ept_identity_map_addr = ident_addr;
  3202. return 0;
  3203. }
  3204. static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
  3205. u32 kvm_nr_mmu_pages)
  3206. {
  3207. if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
  3208. return -EINVAL;
  3209. mutex_lock(&kvm->slots_lock);
  3210. kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
  3211. kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
  3212. mutex_unlock(&kvm->slots_lock);
  3213. return 0;
  3214. }
  3215. static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
  3216. {
  3217. return kvm->arch.n_max_mmu_pages;
  3218. }
  3219. static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
  3220. {
  3221. struct kvm_pic *pic = kvm->arch.vpic;
  3222. int r;
  3223. r = 0;
  3224. switch (chip->chip_id) {
  3225. case KVM_IRQCHIP_PIC_MASTER:
  3226. memcpy(&chip->chip.pic, &pic->pics[0],
  3227. sizeof(struct kvm_pic_state));
  3228. break;
  3229. case KVM_IRQCHIP_PIC_SLAVE:
  3230. memcpy(&chip->chip.pic, &pic->pics[1],
  3231. sizeof(struct kvm_pic_state));
  3232. break;
  3233. case KVM_IRQCHIP_IOAPIC:
  3234. kvm_get_ioapic(kvm, &chip->chip.ioapic);
  3235. break;
  3236. default:
  3237. r = -EINVAL;
  3238. break;
  3239. }
  3240. return r;
  3241. }
  3242. static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
  3243. {
  3244. struct kvm_pic *pic = kvm->arch.vpic;
  3245. int r;
  3246. r = 0;
  3247. switch (chip->chip_id) {
  3248. case KVM_IRQCHIP_PIC_MASTER:
  3249. spin_lock(&pic->lock);
  3250. memcpy(&pic->pics[0], &chip->chip.pic,
  3251. sizeof(struct kvm_pic_state));
  3252. spin_unlock(&pic->lock);
  3253. break;
  3254. case KVM_IRQCHIP_PIC_SLAVE:
  3255. spin_lock(&pic->lock);
  3256. memcpy(&pic->pics[1], &chip->chip.pic,
  3257. sizeof(struct kvm_pic_state));
  3258. spin_unlock(&pic->lock);
  3259. break;
  3260. case KVM_IRQCHIP_IOAPIC:
  3261. kvm_set_ioapic(kvm, &chip->chip.ioapic);
  3262. break;
  3263. default:
  3264. r = -EINVAL;
  3265. break;
  3266. }
  3267. kvm_pic_update_irq(pic);
  3268. return r;
  3269. }
  3270. static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
  3271. {
  3272. struct kvm_kpit_state *kps = &kvm->arch.vpit->pit_state;
  3273. BUILD_BUG_ON(sizeof(*ps) != sizeof(kps->channels));
  3274. mutex_lock(&kps->lock);
  3275. memcpy(ps, &kps->channels, sizeof(*ps));
  3276. mutex_unlock(&kps->lock);
  3277. return 0;
  3278. }
  3279. static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
  3280. {
  3281. int i;
  3282. struct kvm_pit *pit = kvm->arch.vpit;
  3283. mutex_lock(&pit->pit_state.lock);
  3284. memcpy(&pit->pit_state.channels, ps, sizeof(*ps));
  3285. for (i = 0; i < 3; i++)
  3286. kvm_pit_load_count(pit, i, ps->channels[i].count, 0);
  3287. mutex_unlock(&pit->pit_state.lock);
  3288. return 0;
  3289. }
  3290. static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
  3291. {
  3292. mutex_lock(&kvm->arch.vpit->pit_state.lock);
  3293. memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
  3294. sizeof(ps->channels));
  3295. ps->flags = kvm->arch.vpit->pit_state.flags;
  3296. mutex_unlock(&kvm->arch.vpit->pit_state.lock);
  3297. memset(&ps->reserved, 0, sizeof(ps->reserved));
  3298. return 0;
  3299. }
  3300. static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
  3301. {
  3302. int start = 0;
  3303. int i;
  3304. u32 prev_legacy, cur_legacy;
  3305. struct kvm_pit *pit = kvm->arch.vpit;
  3306. mutex_lock(&pit->pit_state.lock);
  3307. prev_legacy = pit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
  3308. cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
  3309. if (!prev_legacy && cur_legacy)
  3310. start = 1;
  3311. memcpy(&pit->pit_state.channels, &ps->channels,
  3312. sizeof(pit->pit_state.channels));
  3313. pit->pit_state.flags = ps->flags;
  3314. for (i = 0; i < 3; i++)
  3315. kvm_pit_load_count(pit, i, pit->pit_state.channels[i].count,
  3316. start && i == 0);
  3317. mutex_unlock(&pit->pit_state.lock);
  3318. return 0;
  3319. }
  3320. static int kvm_vm_ioctl_reinject(struct kvm *kvm,
  3321. struct kvm_reinject_control *control)
  3322. {
  3323. struct kvm_pit *pit = kvm->arch.vpit;
  3324. if (!pit)
  3325. return -ENXIO;
  3326. /* pit->pit_state.lock was overloaded to prevent userspace from getting
  3327. * an inconsistent state after running multiple KVM_REINJECT_CONTROL
  3328. * ioctls in parallel. Use a separate lock if that ioctl isn't rare.
  3329. */
  3330. mutex_lock(&pit->pit_state.lock);
  3331. kvm_pit_set_reinject(pit, control->pit_reinject);
  3332. mutex_unlock(&pit->pit_state.lock);
  3333. return 0;
  3334. }
  3335. /**
  3336. * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
  3337. * @kvm: kvm instance
  3338. * @log: slot id and address to which we copy the log
  3339. *
  3340. * Steps 1-4 below provide general overview of dirty page logging. See
  3341. * kvm_get_dirty_log_protect() function description for additional details.
  3342. *
  3343. * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
  3344. * always flush the TLB (step 4) even if previous step failed and the dirty
  3345. * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
  3346. * does not preclude user space subsequent dirty log read. Flushing TLB ensures
  3347. * writes will be marked dirty for next log read.
  3348. *
  3349. * 1. Take a snapshot of the bit and clear it if needed.
  3350. * 2. Write protect the corresponding page.
  3351. * 3. Copy the snapshot to the userspace.
  3352. * 4. Flush TLB's if needed.
  3353. */
  3354. int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log)
  3355. {
  3356. bool is_dirty = false;
  3357. int r;
  3358. mutex_lock(&kvm->slots_lock);
  3359. /*
  3360. * Flush potentially hardware-cached dirty pages to dirty_bitmap.
  3361. */
  3362. if (kvm_x86_ops->flush_log_dirty)
  3363. kvm_x86_ops->flush_log_dirty(kvm);
  3364. r = kvm_get_dirty_log_protect(kvm, log, &is_dirty);
  3365. /*
  3366. * All the TLBs can be flushed out of mmu lock, see the comments in
  3367. * kvm_mmu_slot_remove_write_access().
  3368. */
  3369. lockdep_assert_held(&kvm->slots_lock);
  3370. if (is_dirty)
  3371. kvm_flush_remote_tlbs(kvm);
  3372. mutex_unlock(&kvm->slots_lock);
  3373. return r;
  3374. }
  3375. int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
  3376. bool line_status)
  3377. {
  3378. if (!irqchip_in_kernel(kvm))
  3379. return -ENXIO;
  3380. irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
  3381. irq_event->irq, irq_event->level,
  3382. line_status);
  3383. return 0;
  3384. }
  3385. static int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
  3386. struct kvm_enable_cap *cap)
  3387. {
  3388. int r;
  3389. if (cap->flags)
  3390. return -EINVAL;
  3391. switch (cap->cap) {
  3392. case KVM_CAP_DISABLE_QUIRKS:
  3393. kvm->arch.disabled_quirks = cap->args[0];
  3394. r = 0;
  3395. break;
  3396. case KVM_CAP_SPLIT_IRQCHIP: {
  3397. mutex_lock(&kvm->lock);
  3398. r = -EINVAL;
  3399. if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
  3400. goto split_irqchip_unlock;
  3401. r = -EEXIST;
  3402. if (irqchip_in_kernel(kvm))
  3403. goto split_irqchip_unlock;
  3404. if (kvm->created_vcpus)
  3405. goto split_irqchip_unlock;
  3406. r = kvm_setup_empty_irq_routing(kvm);
  3407. if (r)
  3408. goto split_irqchip_unlock;
  3409. /* Pairs with irqchip_in_kernel. */
  3410. smp_wmb();
  3411. kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
  3412. kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
  3413. r = 0;
  3414. split_irqchip_unlock:
  3415. mutex_unlock(&kvm->lock);
  3416. break;
  3417. }
  3418. case KVM_CAP_X2APIC_API:
  3419. r = -EINVAL;
  3420. if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
  3421. break;
  3422. if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
  3423. kvm->arch.x2apic_format = true;
  3424. if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
  3425. kvm->arch.x2apic_broadcast_quirk_disabled = true;
  3426. r = 0;
  3427. break;
  3428. default:
  3429. r = -EINVAL;
  3430. break;
  3431. }
  3432. return r;
  3433. }
  3434. long kvm_arch_vm_ioctl(struct file *filp,
  3435. unsigned int ioctl, unsigned long arg)
  3436. {
  3437. struct kvm *kvm = filp->private_data;
  3438. void __user *argp = (void __user *)arg;
  3439. int r = -ENOTTY;
  3440. /*
  3441. * This union makes it completely explicit to gcc-3.x
  3442. * that these two variables' stack usage should be
  3443. * combined, not added together.
  3444. */
  3445. union {
  3446. struct kvm_pit_state ps;
  3447. struct kvm_pit_state2 ps2;
  3448. struct kvm_pit_config pit_config;
  3449. } u;
  3450. switch (ioctl) {
  3451. case KVM_SET_TSS_ADDR:
  3452. r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
  3453. break;
  3454. case KVM_SET_IDENTITY_MAP_ADDR: {
  3455. u64 ident_addr;
  3456. r = -EFAULT;
  3457. if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
  3458. goto out;
  3459. r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
  3460. break;
  3461. }
  3462. case KVM_SET_NR_MMU_PAGES:
  3463. r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
  3464. break;
  3465. case KVM_GET_NR_MMU_PAGES:
  3466. r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
  3467. break;
  3468. case KVM_CREATE_IRQCHIP: {
  3469. mutex_lock(&kvm->lock);
  3470. r = -EEXIST;
  3471. if (irqchip_in_kernel(kvm))
  3472. goto create_irqchip_unlock;
  3473. r = -EINVAL;
  3474. if (kvm->created_vcpus)
  3475. goto create_irqchip_unlock;
  3476. r = kvm_pic_init(kvm);
  3477. if (r)
  3478. goto create_irqchip_unlock;
  3479. r = kvm_ioapic_init(kvm);
  3480. if (r) {
  3481. kvm_pic_destroy(kvm);
  3482. goto create_irqchip_unlock;
  3483. }
  3484. r = kvm_setup_default_irq_routing(kvm);
  3485. if (r) {
  3486. kvm_ioapic_destroy(kvm);
  3487. kvm_pic_destroy(kvm);
  3488. goto create_irqchip_unlock;
  3489. }
  3490. /* Write kvm->irq_routing before enabling irqchip_in_kernel. */
  3491. smp_wmb();
  3492. kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
  3493. create_irqchip_unlock:
  3494. mutex_unlock(&kvm->lock);
  3495. break;
  3496. }
  3497. case KVM_CREATE_PIT:
  3498. u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
  3499. goto create_pit;
  3500. case KVM_CREATE_PIT2:
  3501. r = -EFAULT;
  3502. if (copy_from_user(&u.pit_config, argp,
  3503. sizeof(struct kvm_pit_config)))
  3504. goto out;
  3505. create_pit:
  3506. mutex_lock(&kvm->lock);
  3507. r = -EEXIST;
  3508. if (kvm->arch.vpit)
  3509. goto create_pit_unlock;
  3510. r = -ENOMEM;
  3511. kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
  3512. if (kvm->arch.vpit)
  3513. r = 0;
  3514. create_pit_unlock:
  3515. mutex_unlock(&kvm->lock);
  3516. break;
  3517. case KVM_GET_IRQCHIP: {
  3518. /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
  3519. struct kvm_irqchip *chip;
  3520. chip = memdup_user(argp, sizeof(*chip));
  3521. if (IS_ERR(chip)) {
  3522. r = PTR_ERR(chip);
  3523. goto out;
  3524. }
  3525. r = -ENXIO;
  3526. if (!irqchip_kernel(kvm))
  3527. goto get_irqchip_out;
  3528. r = kvm_vm_ioctl_get_irqchip(kvm, chip);
  3529. if (r)
  3530. goto get_irqchip_out;
  3531. r = -EFAULT;
  3532. if (copy_to_user(argp, chip, sizeof *chip))
  3533. goto get_irqchip_out;
  3534. r = 0;
  3535. get_irqchip_out:
  3536. kfree(chip);
  3537. break;
  3538. }
  3539. case KVM_SET_IRQCHIP: {
  3540. /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
  3541. struct kvm_irqchip *chip;
  3542. chip = memdup_user(argp, sizeof(*chip));
  3543. if (IS_ERR(chip)) {
  3544. r = PTR_ERR(chip);
  3545. goto out;
  3546. }
  3547. r = -ENXIO;
  3548. if (!irqchip_kernel(kvm))
  3549. goto set_irqchip_out;
  3550. r = kvm_vm_ioctl_set_irqchip(kvm, chip);
  3551. if (r)
  3552. goto set_irqchip_out;
  3553. r = 0;
  3554. set_irqchip_out:
  3555. kfree(chip);
  3556. break;
  3557. }
  3558. case KVM_GET_PIT: {
  3559. r = -EFAULT;
  3560. if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
  3561. goto out;
  3562. r = -ENXIO;
  3563. if (!kvm->arch.vpit)
  3564. goto out;
  3565. r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
  3566. if (r)
  3567. goto out;
  3568. r = -EFAULT;
  3569. if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
  3570. goto out;
  3571. r = 0;
  3572. break;
  3573. }
  3574. case KVM_SET_PIT: {
  3575. r = -EFAULT;
  3576. if (copy_from_user(&u.ps, argp, sizeof u.ps))
  3577. goto out;
  3578. r = -ENXIO;
  3579. if (!kvm->arch.vpit)
  3580. goto out;
  3581. r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
  3582. break;
  3583. }
  3584. case KVM_GET_PIT2: {
  3585. r = -ENXIO;
  3586. if (!kvm->arch.vpit)
  3587. goto out;
  3588. r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
  3589. if (r)
  3590. goto out;
  3591. r = -EFAULT;
  3592. if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
  3593. goto out;
  3594. r = 0;
  3595. break;
  3596. }
  3597. case KVM_SET_PIT2: {
  3598. r = -EFAULT;
  3599. if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
  3600. goto out;
  3601. r = -ENXIO;
  3602. if (!kvm->arch.vpit)
  3603. goto out;
  3604. r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
  3605. break;
  3606. }
  3607. case KVM_REINJECT_CONTROL: {
  3608. struct kvm_reinject_control control;
  3609. r = -EFAULT;
  3610. if (copy_from_user(&control, argp, sizeof(control)))
  3611. goto out;
  3612. r = kvm_vm_ioctl_reinject(kvm, &control);
  3613. break;
  3614. }
  3615. case KVM_SET_BOOT_CPU_ID:
  3616. r = 0;
  3617. mutex_lock(&kvm->lock);
  3618. if (kvm->created_vcpus)
  3619. r = -EBUSY;
  3620. else
  3621. kvm->arch.bsp_vcpu_id = arg;
  3622. mutex_unlock(&kvm->lock);
  3623. break;
  3624. case KVM_XEN_HVM_CONFIG: {
  3625. r = -EFAULT;
  3626. if (copy_from_user(&kvm->arch.xen_hvm_config, argp,
  3627. sizeof(struct kvm_xen_hvm_config)))
  3628. goto out;
  3629. r = -EINVAL;
  3630. if (kvm->arch.xen_hvm_config.flags)
  3631. goto out;
  3632. r = 0;
  3633. break;
  3634. }
  3635. case KVM_SET_CLOCK: {
  3636. struct kvm_clock_data user_ns;
  3637. u64 now_ns;
  3638. r = -EFAULT;
  3639. if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
  3640. goto out;
  3641. r = -EINVAL;
  3642. if (user_ns.flags)
  3643. goto out;
  3644. r = 0;
  3645. /*
  3646. * TODO: userspace has to take care of races with VCPU_RUN, so
  3647. * kvm_gen_update_masterclock() can be cut down to locked
  3648. * pvclock_update_vm_gtod_copy().
  3649. */
  3650. kvm_gen_update_masterclock(kvm);
  3651. now_ns = get_kvmclock_ns(kvm);
  3652. kvm->arch.kvmclock_offset += user_ns.clock - now_ns;
  3653. kvm_make_all_cpus_request(kvm, KVM_REQ_CLOCK_UPDATE);
  3654. break;
  3655. }
  3656. case KVM_GET_CLOCK: {
  3657. struct kvm_clock_data user_ns;
  3658. u64 now_ns;
  3659. now_ns = get_kvmclock_ns(kvm);
  3660. user_ns.clock = now_ns;
  3661. user_ns.flags = kvm->arch.use_master_clock ? KVM_CLOCK_TSC_STABLE : 0;
  3662. memset(&user_ns.pad, 0, sizeof(user_ns.pad));
  3663. r = -EFAULT;
  3664. if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
  3665. goto out;
  3666. r = 0;
  3667. break;
  3668. }
  3669. case KVM_ENABLE_CAP: {
  3670. struct kvm_enable_cap cap;
  3671. r = -EFAULT;
  3672. if (copy_from_user(&cap, argp, sizeof(cap)))
  3673. goto out;
  3674. r = kvm_vm_ioctl_enable_cap(kvm, &cap);
  3675. break;
  3676. }
  3677. default:
  3678. r = -ENOTTY;
  3679. }
  3680. out:
  3681. return r;
  3682. }
  3683. static void kvm_init_msr_list(void)
  3684. {
  3685. u32 dummy[2];
  3686. unsigned i, j;
  3687. for (i = j = 0; i < ARRAY_SIZE(msrs_to_save); i++) {
  3688. if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
  3689. continue;
  3690. /*
  3691. * Even MSRs that are valid in the host may not be exposed
  3692. * to the guests in some cases.
  3693. */
  3694. switch (msrs_to_save[i]) {
  3695. case MSR_IA32_BNDCFGS:
  3696. if (!kvm_x86_ops->mpx_supported())
  3697. continue;
  3698. break;
  3699. case MSR_TSC_AUX:
  3700. if (!kvm_x86_ops->rdtscp_supported())
  3701. continue;
  3702. break;
  3703. default:
  3704. break;
  3705. }
  3706. if (j < i)
  3707. msrs_to_save[j] = msrs_to_save[i];
  3708. j++;
  3709. }
  3710. num_msrs_to_save = j;
  3711. for (i = j = 0; i < ARRAY_SIZE(emulated_msrs); i++) {
  3712. switch (emulated_msrs[i]) {
  3713. case MSR_IA32_SMBASE:
  3714. if (!kvm_x86_ops->cpu_has_high_real_mode_segbase())
  3715. continue;
  3716. break;
  3717. default:
  3718. break;
  3719. }
  3720. if (j < i)
  3721. emulated_msrs[j] = emulated_msrs[i];
  3722. j++;
  3723. }
  3724. num_emulated_msrs = j;
  3725. }
  3726. static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
  3727. const void *v)
  3728. {
  3729. int handled = 0;
  3730. int n;
  3731. do {
  3732. n = min(len, 8);
  3733. if (!(lapic_in_kernel(vcpu) &&
  3734. !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
  3735. && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
  3736. break;
  3737. handled += n;
  3738. addr += n;
  3739. len -= n;
  3740. v += n;
  3741. } while (len);
  3742. return handled;
  3743. }
  3744. static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
  3745. {
  3746. int handled = 0;
  3747. int n;
  3748. do {
  3749. n = min(len, 8);
  3750. if (!(lapic_in_kernel(vcpu) &&
  3751. !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
  3752. addr, n, v))
  3753. && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
  3754. break;
  3755. trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, *(u64 *)v);
  3756. handled += n;
  3757. addr += n;
  3758. len -= n;
  3759. v += n;
  3760. } while (len);
  3761. return handled;
  3762. }
  3763. static void kvm_set_segment(struct kvm_vcpu *vcpu,
  3764. struct kvm_segment *var, int seg)
  3765. {
  3766. kvm_x86_ops->set_segment(vcpu, var, seg);
  3767. }
  3768. void kvm_get_segment(struct kvm_vcpu *vcpu,
  3769. struct kvm_segment *var, int seg)
  3770. {
  3771. kvm_x86_ops->get_segment(vcpu, var, seg);
  3772. }
  3773. gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
  3774. struct x86_exception *exception)
  3775. {
  3776. gpa_t t_gpa;
  3777. BUG_ON(!mmu_is_nested(vcpu));
  3778. /* NPT walks are always user-walks */
  3779. access |= PFERR_USER_MASK;
  3780. t_gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gpa, access, exception);
  3781. return t_gpa;
  3782. }
  3783. gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
  3784. struct x86_exception *exception)
  3785. {
  3786. u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
  3787. return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
  3788. }
  3789. gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
  3790. struct x86_exception *exception)
  3791. {
  3792. u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
  3793. access |= PFERR_FETCH_MASK;
  3794. return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
  3795. }
  3796. gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
  3797. struct x86_exception *exception)
  3798. {
  3799. u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
  3800. access |= PFERR_WRITE_MASK;
  3801. return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
  3802. }
  3803. /* uses this to access any guest's mapped memory without checking CPL */
  3804. gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
  3805. struct x86_exception *exception)
  3806. {
  3807. return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
  3808. }
  3809. static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
  3810. struct kvm_vcpu *vcpu, u32 access,
  3811. struct x86_exception *exception)
  3812. {
  3813. void *data = val;
  3814. int r = X86EMUL_CONTINUE;
  3815. while (bytes) {
  3816. gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
  3817. exception);
  3818. unsigned offset = addr & (PAGE_SIZE-1);
  3819. unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
  3820. int ret;
  3821. if (gpa == UNMAPPED_GVA)
  3822. return X86EMUL_PROPAGATE_FAULT;
  3823. ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
  3824. offset, toread);
  3825. if (ret < 0) {
  3826. r = X86EMUL_IO_NEEDED;
  3827. goto out;
  3828. }
  3829. bytes -= toread;
  3830. data += toread;
  3831. addr += toread;
  3832. }
  3833. out:
  3834. return r;
  3835. }
  3836. /* used for instruction fetching */
  3837. static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
  3838. gva_t addr, void *val, unsigned int bytes,
  3839. struct x86_exception *exception)
  3840. {
  3841. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  3842. u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
  3843. unsigned offset;
  3844. int ret;
  3845. /* Inline kvm_read_guest_virt_helper for speed. */
  3846. gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access|PFERR_FETCH_MASK,
  3847. exception);
  3848. if (unlikely(gpa == UNMAPPED_GVA))
  3849. return X86EMUL_PROPAGATE_FAULT;
  3850. offset = addr & (PAGE_SIZE-1);
  3851. if (WARN_ON(offset + bytes > PAGE_SIZE))
  3852. bytes = (unsigned)PAGE_SIZE - offset;
  3853. ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
  3854. offset, bytes);
  3855. if (unlikely(ret < 0))
  3856. return X86EMUL_IO_NEEDED;
  3857. return X86EMUL_CONTINUE;
  3858. }
  3859. int kvm_read_guest_virt(struct x86_emulate_ctxt *ctxt,
  3860. gva_t addr, void *val, unsigned int bytes,
  3861. struct x86_exception *exception)
  3862. {
  3863. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  3864. u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
  3865. return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
  3866. exception);
  3867. }
  3868. EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
  3869. static int kvm_read_guest_virt_system(struct x86_emulate_ctxt *ctxt,
  3870. gva_t addr, void *val, unsigned int bytes,
  3871. struct x86_exception *exception)
  3872. {
  3873. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  3874. return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, 0, exception);
  3875. }
  3876. static int kvm_read_guest_phys_system(struct x86_emulate_ctxt *ctxt,
  3877. unsigned long addr, void *val, unsigned int bytes)
  3878. {
  3879. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  3880. int r = kvm_vcpu_read_guest(vcpu, addr, val, bytes);
  3881. return r < 0 ? X86EMUL_IO_NEEDED : X86EMUL_CONTINUE;
  3882. }
  3883. int kvm_write_guest_virt_system(struct x86_emulate_ctxt *ctxt,
  3884. gva_t addr, void *val,
  3885. unsigned int bytes,
  3886. struct x86_exception *exception)
  3887. {
  3888. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  3889. void *data = val;
  3890. int r = X86EMUL_CONTINUE;
  3891. while (bytes) {
  3892. gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
  3893. PFERR_WRITE_MASK,
  3894. exception);
  3895. unsigned offset = addr & (PAGE_SIZE-1);
  3896. unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
  3897. int ret;
  3898. if (gpa == UNMAPPED_GVA)
  3899. return X86EMUL_PROPAGATE_FAULT;
  3900. ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
  3901. if (ret < 0) {
  3902. r = X86EMUL_IO_NEEDED;
  3903. goto out;
  3904. }
  3905. bytes -= towrite;
  3906. data += towrite;
  3907. addr += towrite;
  3908. }
  3909. out:
  3910. return r;
  3911. }
  3912. EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
  3913. static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
  3914. gpa_t gpa, bool write)
  3915. {
  3916. /* For APIC access vmexit */
  3917. if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
  3918. return 1;
  3919. if (vcpu_match_mmio_gpa(vcpu, gpa)) {
  3920. trace_vcpu_match_mmio(gva, gpa, write, true);
  3921. return 1;
  3922. }
  3923. return 0;
  3924. }
  3925. static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
  3926. gpa_t *gpa, struct x86_exception *exception,
  3927. bool write)
  3928. {
  3929. u32 access = ((kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0)
  3930. | (write ? PFERR_WRITE_MASK : 0);
  3931. /*
  3932. * currently PKRU is only applied to ept enabled guest so
  3933. * there is no pkey in EPT page table for L1 guest or EPT
  3934. * shadow page table for L2 guest.
  3935. */
  3936. if (vcpu_match_mmio_gva(vcpu, gva)
  3937. && !permission_fault(vcpu, vcpu->arch.walk_mmu,
  3938. vcpu->arch.access, 0, access)) {
  3939. *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
  3940. (gva & (PAGE_SIZE - 1));
  3941. trace_vcpu_match_mmio(gva, *gpa, write, false);
  3942. return 1;
  3943. }
  3944. *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
  3945. if (*gpa == UNMAPPED_GVA)
  3946. return -1;
  3947. return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
  3948. }
  3949. int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
  3950. const void *val, int bytes)
  3951. {
  3952. int ret;
  3953. ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
  3954. if (ret < 0)
  3955. return 0;
  3956. kvm_page_track_write(vcpu, gpa, val, bytes);
  3957. return 1;
  3958. }
  3959. struct read_write_emulator_ops {
  3960. int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
  3961. int bytes);
  3962. int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
  3963. void *val, int bytes);
  3964. int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
  3965. int bytes, void *val);
  3966. int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
  3967. void *val, int bytes);
  3968. bool write;
  3969. };
  3970. static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
  3971. {
  3972. if (vcpu->mmio_read_completed) {
  3973. trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
  3974. vcpu->mmio_fragments[0].gpa, *(u64 *)val);
  3975. vcpu->mmio_read_completed = 0;
  3976. return 1;
  3977. }
  3978. return 0;
  3979. }
  3980. static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
  3981. void *val, int bytes)
  3982. {
  3983. return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
  3984. }
  3985. static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
  3986. void *val, int bytes)
  3987. {
  3988. return emulator_write_phys(vcpu, gpa, val, bytes);
  3989. }
  3990. static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
  3991. {
  3992. trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, *(u64 *)val);
  3993. return vcpu_mmio_write(vcpu, gpa, bytes, val);
  3994. }
  3995. static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
  3996. void *val, int bytes)
  3997. {
  3998. trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, 0);
  3999. return X86EMUL_IO_NEEDED;
  4000. }
  4001. static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
  4002. void *val, int bytes)
  4003. {
  4004. struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
  4005. memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
  4006. return X86EMUL_CONTINUE;
  4007. }
  4008. static const struct read_write_emulator_ops read_emultor = {
  4009. .read_write_prepare = read_prepare,
  4010. .read_write_emulate = read_emulate,
  4011. .read_write_mmio = vcpu_mmio_read,
  4012. .read_write_exit_mmio = read_exit_mmio,
  4013. };
  4014. static const struct read_write_emulator_ops write_emultor = {
  4015. .read_write_emulate = write_emulate,
  4016. .read_write_mmio = write_mmio,
  4017. .read_write_exit_mmio = write_exit_mmio,
  4018. .write = true,
  4019. };
  4020. static int emulator_read_write_onepage(unsigned long addr, void *val,
  4021. unsigned int bytes,
  4022. struct x86_exception *exception,
  4023. struct kvm_vcpu *vcpu,
  4024. const struct read_write_emulator_ops *ops)
  4025. {
  4026. gpa_t gpa;
  4027. int handled, ret;
  4028. bool write = ops->write;
  4029. struct kvm_mmio_fragment *frag;
  4030. struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
  4031. /*
  4032. * If the exit was due to a NPF we may already have a GPA.
  4033. * If the GPA is present, use it to avoid the GVA to GPA table walk.
  4034. * Note, this cannot be used on string operations since string
  4035. * operation using rep will only have the initial GPA from the NPF
  4036. * occurred.
  4037. */
  4038. if (vcpu->arch.gpa_available &&
  4039. emulator_can_use_gpa(ctxt) &&
  4040. vcpu_is_mmio_gpa(vcpu, addr, exception->address, write) &&
  4041. (addr & ~PAGE_MASK) == (exception->address & ~PAGE_MASK)) {
  4042. gpa = exception->address;
  4043. goto mmio;
  4044. }
  4045. ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
  4046. if (ret < 0)
  4047. return X86EMUL_PROPAGATE_FAULT;
  4048. /* For APIC access vmexit */
  4049. if (ret)
  4050. goto mmio;
  4051. if (ops->read_write_emulate(vcpu, gpa, val, bytes))
  4052. return X86EMUL_CONTINUE;
  4053. mmio:
  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.dest_id = apicid;
  5339. lapic_irq.msi_redir_hint = false;
  5340. lapic_irq.delivery_mode = APIC_DM_REMRD;
  5341. kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
  5342. }
  5343. void kvm_vcpu_deactivate_apicv(struct kvm_vcpu *vcpu)
  5344. {
  5345. vcpu->arch.apicv_active = false;
  5346. kvm_x86_ops->refresh_apicv_exec_ctrl(vcpu);
  5347. }
  5348. int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
  5349. {
  5350. unsigned long nr, a0, a1, a2, a3, ret;
  5351. int op_64_bit, r;
  5352. r = kvm_skip_emulated_instruction(vcpu);
  5353. if (kvm_hv_hypercall_enabled(vcpu->kvm))
  5354. return kvm_hv_hypercall(vcpu);
  5355. nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
  5356. a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
  5357. a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
  5358. a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
  5359. a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
  5360. trace_kvm_hypercall(nr, a0, a1, a2, a3);
  5361. op_64_bit = is_64_bit_mode(vcpu);
  5362. if (!op_64_bit) {
  5363. nr &= 0xFFFFFFFF;
  5364. a0 &= 0xFFFFFFFF;
  5365. a1 &= 0xFFFFFFFF;
  5366. a2 &= 0xFFFFFFFF;
  5367. a3 &= 0xFFFFFFFF;
  5368. }
  5369. if (kvm_x86_ops->get_cpl(vcpu) != 0) {
  5370. ret = -KVM_EPERM;
  5371. goto out;
  5372. }
  5373. switch (nr) {
  5374. case KVM_HC_VAPIC_POLL_IRQ:
  5375. ret = 0;
  5376. break;
  5377. case KVM_HC_KICK_CPU:
  5378. kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
  5379. ret = 0;
  5380. break;
  5381. #ifdef CONFIG_X86_64
  5382. case KVM_HC_CLOCK_PAIRING:
  5383. ret = kvm_pv_clock_pairing(vcpu, a0, a1);
  5384. break;
  5385. #endif
  5386. default:
  5387. ret = -KVM_ENOSYS;
  5388. break;
  5389. }
  5390. out:
  5391. if (!op_64_bit)
  5392. ret = (u32)ret;
  5393. kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
  5394. ++vcpu->stat.hypercalls;
  5395. return r;
  5396. }
  5397. EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
  5398. static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
  5399. {
  5400. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  5401. char instruction[3];
  5402. unsigned long rip = kvm_rip_read(vcpu);
  5403. kvm_x86_ops->patch_hypercall(vcpu, instruction);
  5404. return emulator_write_emulated(ctxt, rip, instruction, 3,
  5405. &ctxt->exception);
  5406. }
  5407. static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
  5408. {
  5409. return vcpu->run->request_interrupt_window &&
  5410. likely(!pic_in_kernel(vcpu->kvm));
  5411. }
  5412. static void post_kvm_run_save(struct kvm_vcpu *vcpu)
  5413. {
  5414. struct kvm_run *kvm_run = vcpu->run;
  5415. kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
  5416. kvm_run->flags = is_smm(vcpu) ? KVM_RUN_X86_SMM : 0;
  5417. kvm_run->cr8 = kvm_get_cr8(vcpu);
  5418. kvm_run->apic_base = kvm_get_apic_base(vcpu);
  5419. kvm_run->ready_for_interrupt_injection =
  5420. pic_in_kernel(vcpu->kvm) ||
  5421. kvm_vcpu_ready_for_interrupt_injection(vcpu);
  5422. }
  5423. static void update_cr8_intercept(struct kvm_vcpu *vcpu)
  5424. {
  5425. int max_irr, tpr;
  5426. if (!kvm_x86_ops->update_cr8_intercept)
  5427. return;
  5428. if (!lapic_in_kernel(vcpu))
  5429. return;
  5430. if (vcpu->arch.apicv_active)
  5431. return;
  5432. if (!vcpu->arch.apic->vapic_addr)
  5433. max_irr = kvm_lapic_find_highest_irr(vcpu);
  5434. else
  5435. max_irr = -1;
  5436. if (max_irr != -1)
  5437. max_irr >>= 4;
  5438. tpr = kvm_lapic_get_cr8(vcpu);
  5439. kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
  5440. }
  5441. static int inject_pending_event(struct kvm_vcpu *vcpu, bool req_int_win)
  5442. {
  5443. int r;
  5444. /* try to reinject previous events if any */
  5445. if (vcpu->arch.exception.pending) {
  5446. trace_kvm_inj_exception(vcpu->arch.exception.nr,
  5447. vcpu->arch.exception.has_error_code,
  5448. vcpu->arch.exception.error_code);
  5449. if (exception_type(vcpu->arch.exception.nr) == EXCPT_FAULT)
  5450. __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
  5451. X86_EFLAGS_RF);
  5452. if (vcpu->arch.exception.nr == DB_VECTOR &&
  5453. (vcpu->arch.dr7 & DR7_GD)) {
  5454. vcpu->arch.dr7 &= ~DR7_GD;
  5455. kvm_update_dr7(vcpu);
  5456. }
  5457. kvm_x86_ops->queue_exception(vcpu, vcpu->arch.exception.nr,
  5458. vcpu->arch.exception.has_error_code,
  5459. vcpu->arch.exception.error_code,
  5460. vcpu->arch.exception.reinject);
  5461. return 0;
  5462. }
  5463. if (vcpu->arch.nmi_injected) {
  5464. kvm_x86_ops->set_nmi(vcpu);
  5465. return 0;
  5466. }
  5467. if (vcpu->arch.interrupt.pending) {
  5468. kvm_x86_ops->set_irq(vcpu);
  5469. return 0;
  5470. }
  5471. if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
  5472. r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
  5473. if (r != 0)
  5474. return r;
  5475. }
  5476. /* try to inject new event if pending */
  5477. if (vcpu->arch.smi_pending && !is_smm(vcpu)) {
  5478. vcpu->arch.smi_pending = false;
  5479. enter_smm(vcpu);
  5480. } else if (vcpu->arch.nmi_pending && kvm_x86_ops->nmi_allowed(vcpu)) {
  5481. --vcpu->arch.nmi_pending;
  5482. vcpu->arch.nmi_injected = true;
  5483. kvm_x86_ops->set_nmi(vcpu);
  5484. } else if (kvm_cpu_has_injectable_intr(vcpu)) {
  5485. /*
  5486. * Because interrupts can be injected asynchronously, we are
  5487. * calling check_nested_events again here to avoid a race condition.
  5488. * See https://lkml.org/lkml/2014/7/2/60 for discussion about this
  5489. * proposal and current concerns. Perhaps we should be setting
  5490. * KVM_REQ_EVENT only on certain events and not unconditionally?
  5491. */
  5492. if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
  5493. r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
  5494. if (r != 0)
  5495. return r;
  5496. }
  5497. if (kvm_x86_ops->interrupt_allowed(vcpu)) {
  5498. kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
  5499. false);
  5500. kvm_x86_ops->set_irq(vcpu);
  5501. }
  5502. }
  5503. return 0;
  5504. }
  5505. static void process_nmi(struct kvm_vcpu *vcpu)
  5506. {
  5507. unsigned limit = 2;
  5508. /*
  5509. * x86 is limited to one NMI running, and one NMI pending after it.
  5510. * If an NMI is already in progress, limit further NMIs to just one.
  5511. * Otherwise, allow two (and we'll inject the first one immediately).
  5512. */
  5513. if (kvm_x86_ops->get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
  5514. limit = 1;
  5515. vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
  5516. vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
  5517. kvm_make_request(KVM_REQ_EVENT, vcpu);
  5518. }
  5519. #define put_smstate(type, buf, offset, val) \
  5520. *(type *)((buf) + (offset) - 0x7e00) = val
  5521. static u32 enter_smm_get_segment_flags(struct kvm_segment *seg)
  5522. {
  5523. u32 flags = 0;
  5524. flags |= seg->g << 23;
  5525. flags |= seg->db << 22;
  5526. flags |= seg->l << 21;
  5527. flags |= seg->avl << 20;
  5528. flags |= seg->present << 15;
  5529. flags |= seg->dpl << 13;
  5530. flags |= seg->s << 12;
  5531. flags |= seg->type << 8;
  5532. return flags;
  5533. }
  5534. static void enter_smm_save_seg_32(struct kvm_vcpu *vcpu, char *buf, int n)
  5535. {
  5536. struct kvm_segment seg;
  5537. int offset;
  5538. kvm_get_segment(vcpu, &seg, n);
  5539. put_smstate(u32, buf, 0x7fa8 + n * 4, seg.selector);
  5540. if (n < 3)
  5541. offset = 0x7f84 + n * 12;
  5542. else
  5543. offset = 0x7f2c + (n - 3) * 12;
  5544. put_smstate(u32, buf, offset + 8, seg.base);
  5545. put_smstate(u32, buf, offset + 4, seg.limit);
  5546. put_smstate(u32, buf, offset, enter_smm_get_segment_flags(&seg));
  5547. }
  5548. #ifdef CONFIG_X86_64
  5549. static void enter_smm_save_seg_64(struct kvm_vcpu *vcpu, char *buf, int n)
  5550. {
  5551. struct kvm_segment seg;
  5552. int offset;
  5553. u16 flags;
  5554. kvm_get_segment(vcpu, &seg, n);
  5555. offset = 0x7e00 + n * 16;
  5556. flags = enter_smm_get_segment_flags(&seg) >> 8;
  5557. put_smstate(u16, buf, offset, seg.selector);
  5558. put_smstate(u16, buf, offset + 2, flags);
  5559. put_smstate(u32, buf, offset + 4, seg.limit);
  5560. put_smstate(u64, buf, offset + 8, seg.base);
  5561. }
  5562. #endif
  5563. static void enter_smm_save_state_32(struct kvm_vcpu *vcpu, char *buf)
  5564. {
  5565. struct desc_ptr dt;
  5566. struct kvm_segment seg;
  5567. unsigned long val;
  5568. int i;
  5569. put_smstate(u32, buf, 0x7ffc, kvm_read_cr0(vcpu));
  5570. put_smstate(u32, buf, 0x7ff8, kvm_read_cr3(vcpu));
  5571. put_smstate(u32, buf, 0x7ff4, kvm_get_rflags(vcpu));
  5572. put_smstate(u32, buf, 0x7ff0, kvm_rip_read(vcpu));
  5573. for (i = 0; i < 8; i++)
  5574. put_smstate(u32, buf, 0x7fd0 + i * 4, kvm_register_read(vcpu, i));
  5575. kvm_get_dr(vcpu, 6, &val);
  5576. put_smstate(u32, buf, 0x7fcc, (u32)val);
  5577. kvm_get_dr(vcpu, 7, &val);
  5578. put_smstate(u32, buf, 0x7fc8, (u32)val);
  5579. kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
  5580. put_smstate(u32, buf, 0x7fc4, seg.selector);
  5581. put_smstate(u32, buf, 0x7f64, seg.base);
  5582. put_smstate(u32, buf, 0x7f60, seg.limit);
  5583. put_smstate(u32, buf, 0x7f5c, enter_smm_get_segment_flags(&seg));
  5584. kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
  5585. put_smstate(u32, buf, 0x7fc0, seg.selector);
  5586. put_smstate(u32, buf, 0x7f80, seg.base);
  5587. put_smstate(u32, buf, 0x7f7c, seg.limit);
  5588. put_smstate(u32, buf, 0x7f78, enter_smm_get_segment_flags(&seg));
  5589. kvm_x86_ops->get_gdt(vcpu, &dt);
  5590. put_smstate(u32, buf, 0x7f74, dt.address);
  5591. put_smstate(u32, buf, 0x7f70, dt.size);
  5592. kvm_x86_ops->get_idt(vcpu, &dt);
  5593. put_smstate(u32, buf, 0x7f58, dt.address);
  5594. put_smstate(u32, buf, 0x7f54, dt.size);
  5595. for (i = 0; i < 6; i++)
  5596. enter_smm_save_seg_32(vcpu, buf, i);
  5597. put_smstate(u32, buf, 0x7f14, kvm_read_cr4(vcpu));
  5598. /* revision id */
  5599. put_smstate(u32, buf, 0x7efc, 0x00020000);
  5600. put_smstate(u32, buf, 0x7ef8, vcpu->arch.smbase);
  5601. }
  5602. static void enter_smm_save_state_64(struct kvm_vcpu *vcpu, char *buf)
  5603. {
  5604. #ifdef CONFIG_X86_64
  5605. struct desc_ptr dt;
  5606. struct kvm_segment seg;
  5607. unsigned long val;
  5608. int i;
  5609. for (i = 0; i < 16; i++)
  5610. put_smstate(u64, buf, 0x7ff8 - i * 8, kvm_register_read(vcpu, i));
  5611. put_smstate(u64, buf, 0x7f78, kvm_rip_read(vcpu));
  5612. put_smstate(u32, buf, 0x7f70, kvm_get_rflags(vcpu));
  5613. kvm_get_dr(vcpu, 6, &val);
  5614. put_smstate(u64, buf, 0x7f68, val);
  5615. kvm_get_dr(vcpu, 7, &val);
  5616. put_smstate(u64, buf, 0x7f60, val);
  5617. put_smstate(u64, buf, 0x7f58, kvm_read_cr0(vcpu));
  5618. put_smstate(u64, buf, 0x7f50, kvm_read_cr3(vcpu));
  5619. put_smstate(u64, buf, 0x7f48, kvm_read_cr4(vcpu));
  5620. put_smstate(u32, buf, 0x7f00, vcpu->arch.smbase);
  5621. /* revision id */
  5622. put_smstate(u32, buf, 0x7efc, 0x00020064);
  5623. put_smstate(u64, buf, 0x7ed0, vcpu->arch.efer);
  5624. kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
  5625. put_smstate(u16, buf, 0x7e90, seg.selector);
  5626. put_smstate(u16, buf, 0x7e92, enter_smm_get_segment_flags(&seg) >> 8);
  5627. put_smstate(u32, buf, 0x7e94, seg.limit);
  5628. put_smstate(u64, buf, 0x7e98, seg.base);
  5629. kvm_x86_ops->get_idt(vcpu, &dt);
  5630. put_smstate(u32, buf, 0x7e84, dt.size);
  5631. put_smstate(u64, buf, 0x7e88, dt.address);
  5632. kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
  5633. put_smstate(u16, buf, 0x7e70, seg.selector);
  5634. put_smstate(u16, buf, 0x7e72, enter_smm_get_segment_flags(&seg) >> 8);
  5635. put_smstate(u32, buf, 0x7e74, seg.limit);
  5636. put_smstate(u64, buf, 0x7e78, seg.base);
  5637. kvm_x86_ops->get_gdt(vcpu, &dt);
  5638. put_smstate(u32, buf, 0x7e64, dt.size);
  5639. put_smstate(u64, buf, 0x7e68, dt.address);
  5640. for (i = 0; i < 6; i++)
  5641. enter_smm_save_seg_64(vcpu, buf, i);
  5642. #else
  5643. WARN_ON_ONCE(1);
  5644. #endif
  5645. }
  5646. static void enter_smm(struct kvm_vcpu *vcpu)
  5647. {
  5648. struct kvm_segment cs, ds;
  5649. struct desc_ptr dt;
  5650. char buf[512];
  5651. u32 cr0;
  5652. trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, true);
  5653. vcpu->arch.hflags |= HF_SMM_MASK;
  5654. memset(buf, 0, 512);
  5655. if (guest_cpuid_has_longmode(vcpu))
  5656. enter_smm_save_state_64(vcpu, buf);
  5657. else
  5658. enter_smm_save_state_32(vcpu, buf);
  5659. kvm_vcpu_write_guest(vcpu, vcpu->arch.smbase + 0xfe00, buf, sizeof(buf));
  5660. if (kvm_x86_ops->get_nmi_mask(vcpu))
  5661. vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
  5662. else
  5663. kvm_x86_ops->set_nmi_mask(vcpu, true);
  5664. kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
  5665. kvm_rip_write(vcpu, 0x8000);
  5666. cr0 = vcpu->arch.cr0 & ~(X86_CR0_PE | X86_CR0_EM | X86_CR0_TS | X86_CR0_PG);
  5667. kvm_x86_ops->set_cr0(vcpu, cr0);
  5668. vcpu->arch.cr0 = cr0;
  5669. kvm_x86_ops->set_cr4(vcpu, 0);
  5670. /* Undocumented: IDT limit is set to zero on entry to SMM. */
  5671. dt.address = dt.size = 0;
  5672. kvm_x86_ops->set_idt(vcpu, &dt);
  5673. __kvm_set_dr(vcpu, 7, DR7_FIXED_1);
  5674. cs.selector = (vcpu->arch.smbase >> 4) & 0xffff;
  5675. cs.base = vcpu->arch.smbase;
  5676. ds.selector = 0;
  5677. ds.base = 0;
  5678. cs.limit = ds.limit = 0xffffffff;
  5679. cs.type = ds.type = 0x3;
  5680. cs.dpl = ds.dpl = 0;
  5681. cs.db = ds.db = 0;
  5682. cs.s = ds.s = 1;
  5683. cs.l = ds.l = 0;
  5684. cs.g = ds.g = 1;
  5685. cs.avl = ds.avl = 0;
  5686. cs.present = ds.present = 1;
  5687. cs.unusable = ds.unusable = 0;
  5688. cs.padding = ds.padding = 0;
  5689. kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
  5690. kvm_set_segment(vcpu, &ds, VCPU_SREG_DS);
  5691. kvm_set_segment(vcpu, &ds, VCPU_SREG_ES);
  5692. kvm_set_segment(vcpu, &ds, VCPU_SREG_FS);
  5693. kvm_set_segment(vcpu, &ds, VCPU_SREG_GS);
  5694. kvm_set_segment(vcpu, &ds, VCPU_SREG_SS);
  5695. if (guest_cpuid_has_longmode(vcpu))
  5696. kvm_x86_ops->set_efer(vcpu, 0);
  5697. kvm_update_cpuid(vcpu);
  5698. kvm_mmu_reset_context(vcpu);
  5699. }
  5700. static void process_smi(struct kvm_vcpu *vcpu)
  5701. {
  5702. vcpu->arch.smi_pending = true;
  5703. kvm_make_request(KVM_REQ_EVENT, vcpu);
  5704. }
  5705. void kvm_make_scan_ioapic_request(struct kvm *kvm)
  5706. {
  5707. kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
  5708. }
  5709. static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
  5710. {
  5711. u64 eoi_exit_bitmap[4];
  5712. if (!kvm_apic_hw_enabled(vcpu->arch.apic))
  5713. return;
  5714. bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
  5715. if (irqchip_split(vcpu->kvm))
  5716. kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
  5717. else {
  5718. if (kvm_x86_ops->sync_pir_to_irr && vcpu->arch.apicv_active)
  5719. kvm_x86_ops->sync_pir_to_irr(vcpu);
  5720. kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
  5721. }
  5722. bitmap_or((ulong *)eoi_exit_bitmap, vcpu->arch.ioapic_handled_vectors,
  5723. vcpu_to_synic(vcpu)->vec_bitmap, 256);
  5724. kvm_x86_ops->load_eoi_exitmap(vcpu, eoi_exit_bitmap);
  5725. }
  5726. static void kvm_vcpu_flush_tlb(struct kvm_vcpu *vcpu)
  5727. {
  5728. ++vcpu->stat.tlb_flush;
  5729. kvm_x86_ops->tlb_flush(vcpu);
  5730. }
  5731. void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
  5732. {
  5733. struct page *page = NULL;
  5734. if (!lapic_in_kernel(vcpu))
  5735. return;
  5736. if (!kvm_x86_ops->set_apic_access_page_addr)
  5737. return;
  5738. page = gfn_to_page(vcpu->kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
  5739. if (is_error_page(page))
  5740. return;
  5741. kvm_x86_ops->set_apic_access_page_addr(vcpu, page_to_phys(page));
  5742. /*
  5743. * Do not pin apic access page in memory, the MMU notifier
  5744. * will call us again if it is migrated or swapped out.
  5745. */
  5746. put_page(page);
  5747. }
  5748. EXPORT_SYMBOL_GPL(kvm_vcpu_reload_apic_access_page);
  5749. void kvm_arch_mmu_notifier_invalidate_page(struct kvm *kvm,
  5750. unsigned long address)
  5751. {
  5752. /*
  5753. * The physical address of apic access page is stored in the VMCS.
  5754. * Update it when it becomes invalid.
  5755. */
  5756. if (address == gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT))
  5757. kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
  5758. }
  5759. /*
  5760. * Returns 1 to let vcpu_run() continue the guest execution loop without
  5761. * exiting to the userspace. Otherwise, the value will be returned to the
  5762. * userspace.
  5763. */
  5764. static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
  5765. {
  5766. int r;
  5767. bool req_int_win =
  5768. dm_request_for_irq_injection(vcpu) &&
  5769. kvm_cpu_accept_dm_intr(vcpu);
  5770. bool req_immediate_exit = false;
  5771. if (kvm_request_pending(vcpu)) {
  5772. if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
  5773. kvm_mmu_unload(vcpu);
  5774. if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
  5775. __kvm_migrate_timers(vcpu);
  5776. if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
  5777. kvm_gen_update_masterclock(vcpu->kvm);
  5778. if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
  5779. kvm_gen_kvmclock_update(vcpu);
  5780. if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
  5781. r = kvm_guest_time_update(vcpu);
  5782. if (unlikely(r))
  5783. goto out;
  5784. }
  5785. if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
  5786. kvm_mmu_sync_roots(vcpu);
  5787. if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
  5788. kvm_vcpu_flush_tlb(vcpu);
  5789. if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
  5790. vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
  5791. r = 0;
  5792. goto out;
  5793. }
  5794. if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
  5795. vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
  5796. r = 0;
  5797. goto out;
  5798. }
  5799. if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
  5800. /* Page is swapped out. Do synthetic halt */
  5801. vcpu->arch.apf.halted = true;
  5802. r = 1;
  5803. goto out;
  5804. }
  5805. if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
  5806. record_steal_time(vcpu);
  5807. if (kvm_check_request(KVM_REQ_SMI, vcpu))
  5808. process_smi(vcpu);
  5809. if (kvm_check_request(KVM_REQ_NMI, vcpu))
  5810. process_nmi(vcpu);
  5811. if (kvm_check_request(KVM_REQ_PMU, vcpu))
  5812. kvm_pmu_handle_event(vcpu);
  5813. if (kvm_check_request(KVM_REQ_PMI, vcpu))
  5814. kvm_pmu_deliver_pmi(vcpu);
  5815. if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
  5816. BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
  5817. if (test_bit(vcpu->arch.pending_ioapic_eoi,
  5818. vcpu->arch.ioapic_handled_vectors)) {
  5819. vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
  5820. vcpu->run->eoi.vector =
  5821. vcpu->arch.pending_ioapic_eoi;
  5822. r = 0;
  5823. goto out;
  5824. }
  5825. }
  5826. if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
  5827. vcpu_scan_ioapic(vcpu);
  5828. if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
  5829. kvm_vcpu_reload_apic_access_page(vcpu);
  5830. if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
  5831. vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
  5832. vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
  5833. r = 0;
  5834. goto out;
  5835. }
  5836. if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
  5837. vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
  5838. vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
  5839. r = 0;
  5840. goto out;
  5841. }
  5842. if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
  5843. vcpu->run->exit_reason = KVM_EXIT_HYPERV;
  5844. vcpu->run->hyperv = vcpu->arch.hyperv.exit;
  5845. r = 0;
  5846. goto out;
  5847. }
  5848. /*
  5849. * KVM_REQ_HV_STIMER has to be processed after
  5850. * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
  5851. * depend on the guest clock being up-to-date
  5852. */
  5853. if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
  5854. kvm_hv_process_stimers(vcpu);
  5855. }
  5856. if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
  5857. ++vcpu->stat.req_event;
  5858. kvm_apic_accept_events(vcpu);
  5859. if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
  5860. r = 1;
  5861. goto out;
  5862. }
  5863. if (inject_pending_event(vcpu, req_int_win) != 0)
  5864. req_immediate_exit = true;
  5865. else {
  5866. /* Enable NMI/IRQ window open exits if needed.
  5867. *
  5868. * SMIs have two cases: 1) they can be nested, and
  5869. * then there is nothing to do here because RSM will
  5870. * cause a vmexit anyway; 2) or the SMI can be pending
  5871. * because inject_pending_event has completed the
  5872. * injection of an IRQ or NMI from the previous vmexit,
  5873. * and then we request an immediate exit to inject the SMI.
  5874. */
  5875. if (vcpu->arch.smi_pending && !is_smm(vcpu))
  5876. req_immediate_exit = true;
  5877. if (vcpu->arch.nmi_pending)
  5878. kvm_x86_ops->enable_nmi_window(vcpu);
  5879. if (kvm_cpu_has_injectable_intr(vcpu) || req_int_win)
  5880. kvm_x86_ops->enable_irq_window(vcpu);
  5881. }
  5882. if (kvm_lapic_enabled(vcpu)) {
  5883. update_cr8_intercept(vcpu);
  5884. kvm_lapic_sync_to_vapic(vcpu);
  5885. }
  5886. }
  5887. r = kvm_mmu_reload(vcpu);
  5888. if (unlikely(r)) {
  5889. goto cancel_injection;
  5890. }
  5891. preempt_disable();
  5892. kvm_x86_ops->prepare_guest_switch(vcpu);
  5893. kvm_load_guest_fpu(vcpu);
  5894. /*
  5895. * Disable IRQs before setting IN_GUEST_MODE. Posted interrupt
  5896. * IPI are then delayed after guest entry, which ensures that they
  5897. * result in virtual interrupt delivery.
  5898. */
  5899. local_irq_disable();
  5900. vcpu->mode = IN_GUEST_MODE;
  5901. srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
  5902. /*
  5903. * 1) We should set ->mode before checking ->requests. Please see
  5904. * the comment in kvm_vcpu_exiting_guest_mode().
  5905. *
  5906. * 2) For APICv, we should set ->mode before checking PIR.ON. This
  5907. * pairs with the memory barrier implicit in pi_test_and_set_on
  5908. * (see vmx_deliver_posted_interrupt).
  5909. *
  5910. * 3) This also orders the write to mode from any reads to the page
  5911. * tables done while the VCPU is running. Please see the comment
  5912. * in kvm_flush_remote_tlbs.
  5913. */
  5914. smp_mb__after_srcu_read_unlock();
  5915. /*
  5916. * This handles the case where a posted interrupt was
  5917. * notified with kvm_vcpu_kick.
  5918. */
  5919. if (kvm_lapic_enabled(vcpu)) {
  5920. if (kvm_x86_ops->sync_pir_to_irr && vcpu->arch.apicv_active)
  5921. kvm_x86_ops->sync_pir_to_irr(vcpu);
  5922. }
  5923. if (vcpu->mode == EXITING_GUEST_MODE || kvm_request_pending(vcpu)
  5924. || need_resched() || signal_pending(current)) {
  5925. vcpu->mode = OUTSIDE_GUEST_MODE;
  5926. smp_wmb();
  5927. local_irq_enable();
  5928. preempt_enable();
  5929. vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
  5930. r = 1;
  5931. goto cancel_injection;
  5932. }
  5933. kvm_load_guest_xcr0(vcpu);
  5934. if (req_immediate_exit) {
  5935. kvm_make_request(KVM_REQ_EVENT, vcpu);
  5936. smp_send_reschedule(vcpu->cpu);
  5937. }
  5938. trace_kvm_entry(vcpu->vcpu_id);
  5939. wait_lapic_expire(vcpu);
  5940. guest_enter_irqoff();
  5941. if (unlikely(vcpu->arch.switch_db_regs)) {
  5942. set_debugreg(0, 7);
  5943. set_debugreg(vcpu->arch.eff_db[0], 0);
  5944. set_debugreg(vcpu->arch.eff_db[1], 1);
  5945. set_debugreg(vcpu->arch.eff_db[2], 2);
  5946. set_debugreg(vcpu->arch.eff_db[3], 3);
  5947. set_debugreg(vcpu->arch.dr6, 6);
  5948. vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
  5949. }
  5950. kvm_x86_ops->run(vcpu);
  5951. /*
  5952. * Do this here before restoring debug registers on the host. And
  5953. * since we do this before handling the vmexit, a DR access vmexit
  5954. * can (a) read the correct value of the debug registers, (b) set
  5955. * KVM_DEBUGREG_WONT_EXIT again.
  5956. */
  5957. if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
  5958. WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
  5959. kvm_x86_ops->sync_dirty_debug_regs(vcpu);
  5960. kvm_update_dr0123(vcpu);
  5961. kvm_update_dr6(vcpu);
  5962. kvm_update_dr7(vcpu);
  5963. vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
  5964. }
  5965. /*
  5966. * If the guest has used debug registers, at least dr7
  5967. * will be disabled while returning to the host.
  5968. * If we don't have active breakpoints in the host, we don't
  5969. * care about the messed up debug address registers. But if
  5970. * we have some of them active, restore the old state.
  5971. */
  5972. if (hw_breakpoint_active())
  5973. hw_breakpoint_restore();
  5974. vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
  5975. vcpu->mode = OUTSIDE_GUEST_MODE;
  5976. smp_wmb();
  5977. kvm_put_guest_xcr0(vcpu);
  5978. kvm_x86_ops->handle_external_intr(vcpu);
  5979. ++vcpu->stat.exits;
  5980. guest_exit_irqoff();
  5981. local_irq_enable();
  5982. preempt_enable();
  5983. vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
  5984. /*
  5985. * Profile KVM exit RIPs:
  5986. */
  5987. if (unlikely(prof_on == KVM_PROFILING)) {
  5988. unsigned long rip = kvm_rip_read(vcpu);
  5989. profile_hit(KVM_PROFILING, (void *)rip);
  5990. }
  5991. if (unlikely(vcpu->arch.tsc_always_catchup))
  5992. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  5993. if (vcpu->arch.apic_attention)
  5994. kvm_lapic_sync_from_vapic(vcpu);
  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_xsave(vcpu) && (sregs->cr4 & X86_CR4_OSXSAVE))
  6346. return -EINVAL;
  6347. dt.size = sregs->idt.limit;
  6348. dt.address = sregs->idt.base;
  6349. kvm_x86_ops->set_idt(vcpu, &dt);
  6350. dt.size = sregs->gdt.limit;
  6351. dt.address = sregs->gdt.base;
  6352. kvm_x86_ops->set_gdt(vcpu, &dt);
  6353. vcpu->arch.cr2 = sregs->cr2;
  6354. mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
  6355. vcpu->arch.cr3 = sregs->cr3;
  6356. __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
  6357. kvm_set_cr8(vcpu, sregs->cr8);
  6358. mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
  6359. kvm_x86_ops->set_efer(vcpu, sregs->efer);
  6360. apic_base_msr.data = sregs->apic_base;
  6361. apic_base_msr.host_initiated = true;
  6362. kvm_set_apic_base(vcpu, &apic_base_msr);
  6363. mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
  6364. kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
  6365. vcpu->arch.cr0 = sregs->cr0;
  6366. mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
  6367. kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
  6368. if (sregs->cr4 & (X86_CR4_OSXSAVE | X86_CR4_PKE))
  6369. kvm_update_cpuid(vcpu);
  6370. idx = srcu_read_lock(&vcpu->kvm->srcu);
  6371. if (!is_long_mode(vcpu) && is_pae(vcpu)) {
  6372. load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
  6373. mmu_reset_needed = 1;
  6374. }
  6375. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  6376. if (mmu_reset_needed)
  6377. kvm_mmu_reset_context(vcpu);
  6378. max_bits = KVM_NR_INTERRUPTS;
  6379. pending_vec = find_first_bit(
  6380. (const unsigned long *)sregs->interrupt_bitmap, max_bits);
  6381. if (pending_vec < max_bits) {
  6382. kvm_queue_interrupt(vcpu, pending_vec, false);
  6383. pr_debug("Set back pending irq %d\n", pending_vec);
  6384. }
  6385. kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
  6386. kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
  6387. kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
  6388. kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
  6389. kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
  6390. kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
  6391. kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
  6392. kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
  6393. update_cr8_intercept(vcpu);
  6394. /* Older userspace won't unhalt the vcpu on reset. */
  6395. if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
  6396. sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
  6397. !is_protmode(vcpu))
  6398. vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
  6399. kvm_make_request(KVM_REQ_EVENT, vcpu);
  6400. return 0;
  6401. }
  6402. int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
  6403. struct kvm_guest_debug *dbg)
  6404. {
  6405. unsigned long rflags;
  6406. int i, r;
  6407. if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
  6408. r = -EBUSY;
  6409. if (vcpu->arch.exception.pending)
  6410. goto out;
  6411. if (dbg->control & KVM_GUESTDBG_INJECT_DB)
  6412. kvm_queue_exception(vcpu, DB_VECTOR);
  6413. else
  6414. kvm_queue_exception(vcpu, BP_VECTOR);
  6415. }
  6416. /*
  6417. * Read rflags as long as potentially injected trace flags are still
  6418. * filtered out.
  6419. */
  6420. rflags = kvm_get_rflags(vcpu);
  6421. vcpu->guest_debug = dbg->control;
  6422. if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
  6423. vcpu->guest_debug = 0;
  6424. if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
  6425. for (i = 0; i < KVM_NR_DB_REGS; ++i)
  6426. vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
  6427. vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
  6428. } else {
  6429. for (i = 0; i < KVM_NR_DB_REGS; i++)
  6430. vcpu->arch.eff_db[i] = vcpu->arch.db[i];
  6431. }
  6432. kvm_update_dr7(vcpu);
  6433. if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
  6434. vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
  6435. get_segment_base(vcpu, VCPU_SREG_CS);
  6436. /*
  6437. * Trigger an rflags update that will inject or remove the trace
  6438. * flags.
  6439. */
  6440. kvm_set_rflags(vcpu, rflags);
  6441. kvm_x86_ops->update_bp_intercept(vcpu);
  6442. r = 0;
  6443. out:
  6444. return r;
  6445. }
  6446. /*
  6447. * Translate a guest virtual address to a guest physical address.
  6448. */
  6449. int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
  6450. struct kvm_translation *tr)
  6451. {
  6452. unsigned long vaddr = tr->linear_address;
  6453. gpa_t gpa;
  6454. int idx;
  6455. idx = srcu_read_lock(&vcpu->kvm->srcu);
  6456. gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
  6457. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  6458. tr->physical_address = gpa;
  6459. tr->valid = gpa != UNMAPPED_GVA;
  6460. tr->writeable = 1;
  6461. tr->usermode = 0;
  6462. return 0;
  6463. }
  6464. int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
  6465. {
  6466. struct fxregs_state *fxsave =
  6467. &vcpu->arch.guest_fpu.state.fxsave;
  6468. memcpy(fpu->fpr, fxsave->st_space, 128);
  6469. fpu->fcw = fxsave->cwd;
  6470. fpu->fsw = fxsave->swd;
  6471. fpu->ftwx = fxsave->twd;
  6472. fpu->last_opcode = fxsave->fop;
  6473. fpu->last_ip = fxsave->rip;
  6474. fpu->last_dp = fxsave->rdp;
  6475. memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
  6476. return 0;
  6477. }
  6478. int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
  6479. {
  6480. struct fxregs_state *fxsave =
  6481. &vcpu->arch.guest_fpu.state.fxsave;
  6482. memcpy(fxsave->st_space, fpu->fpr, 128);
  6483. fxsave->cwd = fpu->fcw;
  6484. fxsave->swd = fpu->fsw;
  6485. fxsave->twd = fpu->ftwx;
  6486. fxsave->fop = fpu->last_opcode;
  6487. fxsave->rip = fpu->last_ip;
  6488. fxsave->rdp = fpu->last_dp;
  6489. memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
  6490. return 0;
  6491. }
  6492. static void fx_init(struct kvm_vcpu *vcpu)
  6493. {
  6494. fpstate_init(&vcpu->arch.guest_fpu.state);
  6495. if (boot_cpu_has(X86_FEATURE_XSAVES))
  6496. vcpu->arch.guest_fpu.state.xsave.header.xcomp_bv =
  6497. host_xcr0 | XSTATE_COMPACTION_ENABLED;
  6498. /*
  6499. * Ensure guest xcr0 is valid for loading
  6500. */
  6501. vcpu->arch.xcr0 = XFEATURE_MASK_FP;
  6502. vcpu->arch.cr0 |= X86_CR0_ET;
  6503. }
  6504. void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
  6505. {
  6506. if (vcpu->guest_fpu_loaded)
  6507. return;
  6508. /*
  6509. * Restore all possible states in the guest,
  6510. * and assume host would use all available bits.
  6511. * Guest xcr0 would be loaded later.
  6512. */
  6513. vcpu->guest_fpu_loaded = 1;
  6514. __kernel_fpu_begin();
  6515. __copy_kernel_to_fpregs(&vcpu->arch.guest_fpu.state);
  6516. trace_kvm_fpu(1);
  6517. }
  6518. void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
  6519. {
  6520. if (!vcpu->guest_fpu_loaded)
  6521. return;
  6522. vcpu->guest_fpu_loaded = 0;
  6523. copy_fpregs_to_fpstate(&vcpu->arch.guest_fpu);
  6524. __kernel_fpu_end();
  6525. ++vcpu->stat.fpu_reload;
  6526. trace_kvm_fpu(0);
  6527. }
  6528. void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
  6529. {
  6530. void *wbinvd_dirty_mask = vcpu->arch.wbinvd_dirty_mask;
  6531. kvmclock_reset(vcpu);
  6532. kvm_x86_ops->vcpu_free(vcpu);
  6533. free_cpumask_var(wbinvd_dirty_mask);
  6534. }
  6535. struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
  6536. unsigned int id)
  6537. {
  6538. struct kvm_vcpu *vcpu;
  6539. if (check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
  6540. printk_once(KERN_WARNING
  6541. "kvm: SMP vm created on host with unstable TSC; "
  6542. "guest TSC will not be reliable\n");
  6543. vcpu = kvm_x86_ops->vcpu_create(kvm, id);
  6544. return vcpu;
  6545. }
  6546. int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
  6547. {
  6548. int r;
  6549. kvm_vcpu_mtrr_init(vcpu);
  6550. r = vcpu_load(vcpu);
  6551. if (r)
  6552. return r;
  6553. kvm_vcpu_reset(vcpu, false);
  6554. kvm_mmu_setup(vcpu);
  6555. vcpu_put(vcpu);
  6556. return r;
  6557. }
  6558. void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
  6559. {
  6560. struct msr_data msr;
  6561. struct kvm *kvm = vcpu->kvm;
  6562. if (vcpu_load(vcpu))
  6563. return;
  6564. msr.data = 0x0;
  6565. msr.index = MSR_IA32_TSC;
  6566. msr.host_initiated = true;
  6567. kvm_write_tsc(vcpu, &msr);
  6568. vcpu_put(vcpu);
  6569. if (!kvmclock_periodic_sync)
  6570. return;
  6571. schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
  6572. KVMCLOCK_SYNC_PERIOD);
  6573. }
  6574. void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
  6575. {
  6576. int r;
  6577. vcpu->arch.apf.msr_val = 0;
  6578. r = vcpu_load(vcpu);
  6579. BUG_ON(r);
  6580. kvm_mmu_unload(vcpu);
  6581. vcpu_put(vcpu);
  6582. kvm_x86_ops->vcpu_free(vcpu);
  6583. }
  6584. void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
  6585. {
  6586. vcpu->arch.hflags = 0;
  6587. vcpu->arch.smi_pending = 0;
  6588. atomic_set(&vcpu->arch.nmi_queued, 0);
  6589. vcpu->arch.nmi_pending = 0;
  6590. vcpu->arch.nmi_injected = false;
  6591. kvm_clear_interrupt_queue(vcpu);
  6592. kvm_clear_exception_queue(vcpu);
  6593. memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
  6594. kvm_update_dr0123(vcpu);
  6595. vcpu->arch.dr6 = DR6_INIT;
  6596. kvm_update_dr6(vcpu);
  6597. vcpu->arch.dr7 = DR7_FIXED_1;
  6598. kvm_update_dr7(vcpu);
  6599. vcpu->arch.cr2 = 0;
  6600. kvm_make_request(KVM_REQ_EVENT, vcpu);
  6601. vcpu->arch.apf.msr_val = 0;
  6602. vcpu->arch.st.msr_val = 0;
  6603. kvmclock_reset(vcpu);
  6604. kvm_clear_async_pf_completion_queue(vcpu);
  6605. kvm_async_pf_hash_reset(vcpu);
  6606. vcpu->arch.apf.halted = false;
  6607. if (!init_event) {
  6608. kvm_pmu_reset(vcpu);
  6609. vcpu->arch.smbase = 0x30000;
  6610. vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
  6611. vcpu->arch.msr_misc_features_enables = 0;
  6612. }
  6613. memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
  6614. vcpu->arch.regs_avail = ~0;
  6615. vcpu->arch.regs_dirty = ~0;
  6616. kvm_x86_ops->vcpu_reset(vcpu, init_event);
  6617. }
  6618. void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
  6619. {
  6620. struct kvm_segment cs;
  6621. kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
  6622. cs.selector = vector << 8;
  6623. cs.base = vector << 12;
  6624. kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
  6625. kvm_rip_write(vcpu, 0);
  6626. }
  6627. int kvm_arch_hardware_enable(void)
  6628. {
  6629. struct kvm *kvm;
  6630. struct kvm_vcpu *vcpu;
  6631. int i;
  6632. int ret;
  6633. u64 local_tsc;
  6634. u64 max_tsc = 0;
  6635. bool stable, backwards_tsc = false;
  6636. kvm_shared_msr_cpu_online();
  6637. ret = kvm_x86_ops->hardware_enable();
  6638. if (ret != 0)
  6639. return ret;
  6640. local_tsc = rdtsc();
  6641. stable = !check_tsc_unstable();
  6642. list_for_each_entry(kvm, &vm_list, vm_list) {
  6643. kvm_for_each_vcpu(i, vcpu, kvm) {
  6644. if (!stable && vcpu->cpu == smp_processor_id())
  6645. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  6646. if (stable && vcpu->arch.last_host_tsc > local_tsc) {
  6647. backwards_tsc = true;
  6648. if (vcpu->arch.last_host_tsc > max_tsc)
  6649. max_tsc = vcpu->arch.last_host_tsc;
  6650. }
  6651. }
  6652. }
  6653. /*
  6654. * Sometimes, even reliable TSCs go backwards. This happens on
  6655. * platforms that reset TSC during suspend or hibernate actions, but
  6656. * maintain synchronization. We must compensate. Fortunately, we can
  6657. * detect that condition here, which happens early in CPU bringup,
  6658. * before any KVM threads can be running. Unfortunately, we can't
  6659. * bring the TSCs fully up to date with real time, as we aren't yet far
  6660. * enough into CPU bringup that we know how much real time has actually
  6661. * elapsed; our helper function, ktime_get_boot_ns() will be using boot
  6662. * variables that haven't been updated yet.
  6663. *
  6664. * So we simply find the maximum observed TSC above, then record the
  6665. * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
  6666. * the adjustment will be applied. Note that we accumulate
  6667. * adjustments, in case multiple suspend cycles happen before some VCPU
  6668. * gets a chance to run again. In the event that no KVM threads get a
  6669. * chance to run, we will miss the entire elapsed period, as we'll have
  6670. * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
  6671. * loose cycle time. This isn't too big a deal, since the loss will be
  6672. * uniform across all VCPUs (not to mention the scenario is extremely
  6673. * unlikely). It is possible that a second hibernate recovery happens
  6674. * much faster than a first, causing the observed TSC here to be
  6675. * smaller; this would require additional padding adjustment, which is
  6676. * why we set last_host_tsc to the local tsc observed here.
  6677. *
  6678. * N.B. - this code below runs only on platforms with reliable TSC,
  6679. * as that is the only way backwards_tsc is set above. Also note
  6680. * that this runs for ALL vcpus, which is not a bug; all VCPUs should
  6681. * have the same delta_cyc adjustment applied if backwards_tsc
  6682. * is detected. Note further, this adjustment is only done once,
  6683. * as we reset last_host_tsc on all VCPUs to stop this from being
  6684. * called multiple times (one for each physical CPU bringup).
  6685. *
  6686. * Platforms with unreliable TSCs don't have to deal with this, they
  6687. * will be compensated by the logic in vcpu_load, which sets the TSC to
  6688. * catchup mode. This will catchup all VCPUs to real time, but cannot
  6689. * guarantee that they stay in perfect synchronization.
  6690. */
  6691. if (backwards_tsc) {
  6692. u64 delta_cyc = max_tsc - local_tsc;
  6693. list_for_each_entry(kvm, &vm_list, vm_list) {
  6694. kvm->arch.backwards_tsc_observed = true;
  6695. kvm_for_each_vcpu(i, vcpu, kvm) {
  6696. vcpu->arch.tsc_offset_adjustment += delta_cyc;
  6697. vcpu->arch.last_host_tsc = local_tsc;
  6698. kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
  6699. }
  6700. /*
  6701. * We have to disable TSC offset matching.. if you were
  6702. * booting a VM while issuing an S4 host suspend....
  6703. * you may have some problem. Solving this issue is
  6704. * left as an exercise to the reader.
  6705. */
  6706. kvm->arch.last_tsc_nsec = 0;
  6707. kvm->arch.last_tsc_write = 0;
  6708. }
  6709. }
  6710. return 0;
  6711. }
  6712. void kvm_arch_hardware_disable(void)
  6713. {
  6714. kvm_x86_ops->hardware_disable();
  6715. drop_user_return_notifiers();
  6716. }
  6717. int kvm_arch_hardware_setup(void)
  6718. {
  6719. int r;
  6720. r = kvm_x86_ops->hardware_setup();
  6721. if (r != 0)
  6722. return r;
  6723. if (kvm_has_tsc_control) {
  6724. /*
  6725. * Make sure the user can only configure tsc_khz values that
  6726. * fit into a signed integer.
  6727. * A min value is not calculated needed because it will always
  6728. * be 1 on all machines.
  6729. */
  6730. u64 max = min(0x7fffffffULL,
  6731. __scale_tsc(kvm_max_tsc_scaling_ratio, tsc_khz));
  6732. kvm_max_guest_tsc_khz = max;
  6733. kvm_default_tsc_scaling_ratio = 1ULL << kvm_tsc_scaling_ratio_frac_bits;
  6734. }
  6735. kvm_init_msr_list();
  6736. return 0;
  6737. }
  6738. void kvm_arch_hardware_unsetup(void)
  6739. {
  6740. kvm_x86_ops->hardware_unsetup();
  6741. }
  6742. void kvm_arch_check_processor_compat(void *rtn)
  6743. {
  6744. kvm_x86_ops->check_processor_compatibility(rtn);
  6745. }
  6746. bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
  6747. {
  6748. return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
  6749. }
  6750. EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
  6751. bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
  6752. {
  6753. return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
  6754. }
  6755. struct static_key kvm_no_apic_vcpu __read_mostly;
  6756. EXPORT_SYMBOL_GPL(kvm_no_apic_vcpu);
  6757. int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
  6758. {
  6759. struct page *page;
  6760. struct kvm *kvm;
  6761. int r;
  6762. BUG_ON(vcpu->kvm == NULL);
  6763. kvm = vcpu->kvm;
  6764. vcpu->arch.apicv_active = kvm_x86_ops->get_enable_apicv();
  6765. vcpu->arch.pv.pv_unhalted = false;
  6766. vcpu->arch.emulate_ctxt.ops = &emulate_ops;
  6767. if (!irqchip_in_kernel(kvm) || kvm_vcpu_is_reset_bsp(vcpu))
  6768. vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
  6769. else
  6770. vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
  6771. page = alloc_page(GFP_KERNEL | __GFP_ZERO);
  6772. if (!page) {
  6773. r = -ENOMEM;
  6774. goto fail;
  6775. }
  6776. vcpu->arch.pio_data = page_address(page);
  6777. kvm_set_tsc_khz(vcpu, max_tsc_khz);
  6778. r = kvm_mmu_create(vcpu);
  6779. if (r < 0)
  6780. goto fail_free_pio_data;
  6781. if (irqchip_in_kernel(kvm)) {
  6782. r = kvm_create_lapic(vcpu);
  6783. if (r < 0)
  6784. goto fail_mmu_destroy;
  6785. } else
  6786. static_key_slow_inc(&kvm_no_apic_vcpu);
  6787. vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
  6788. GFP_KERNEL);
  6789. if (!vcpu->arch.mce_banks) {
  6790. r = -ENOMEM;
  6791. goto fail_free_lapic;
  6792. }
  6793. vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
  6794. if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL)) {
  6795. r = -ENOMEM;
  6796. goto fail_free_mce_banks;
  6797. }
  6798. fx_init(vcpu);
  6799. vcpu->arch.ia32_tsc_adjust_msr = 0x0;
  6800. vcpu->arch.pv_time_enabled = false;
  6801. vcpu->arch.guest_supported_xcr0 = 0;
  6802. vcpu->arch.guest_xstate_size = XSAVE_HDR_SIZE + XSAVE_HDR_OFFSET;
  6803. vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
  6804. vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
  6805. kvm_async_pf_hash_reset(vcpu);
  6806. kvm_pmu_init(vcpu);
  6807. vcpu->arch.pending_external_vector = -1;
  6808. kvm_hv_vcpu_init(vcpu);
  6809. return 0;
  6810. fail_free_mce_banks:
  6811. kfree(vcpu->arch.mce_banks);
  6812. fail_free_lapic:
  6813. kvm_free_lapic(vcpu);
  6814. fail_mmu_destroy:
  6815. kvm_mmu_destroy(vcpu);
  6816. fail_free_pio_data:
  6817. free_page((unsigned long)vcpu->arch.pio_data);
  6818. fail:
  6819. return r;
  6820. }
  6821. void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
  6822. {
  6823. int idx;
  6824. kvm_hv_vcpu_uninit(vcpu);
  6825. kvm_pmu_destroy(vcpu);
  6826. kfree(vcpu->arch.mce_banks);
  6827. kvm_free_lapic(vcpu);
  6828. idx = srcu_read_lock(&vcpu->kvm->srcu);
  6829. kvm_mmu_destroy(vcpu);
  6830. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  6831. free_page((unsigned long)vcpu->arch.pio_data);
  6832. if (!lapic_in_kernel(vcpu))
  6833. static_key_slow_dec(&kvm_no_apic_vcpu);
  6834. }
  6835. void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
  6836. {
  6837. kvm_x86_ops->sched_in(vcpu, cpu);
  6838. }
  6839. int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
  6840. {
  6841. if (type)
  6842. return -EINVAL;
  6843. INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
  6844. INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
  6845. INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
  6846. INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
  6847. atomic_set(&kvm->arch.noncoherent_dma_count, 0);
  6848. /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
  6849. set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
  6850. /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
  6851. set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
  6852. &kvm->arch.irq_sources_bitmap);
  6853. raw_spin_lock_init(&kvm->arch.tsc_write_lock);
  6854. mutex_init(&kvm->arch.apic_map_lock);
  6855. mutex_init(&kvm->arch.hyperv.hv_lock);
  6856. spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
  6857. kvm->arch.kvmclock_offset = -ktime_get_boot_ns();
  6858. pvclock_update_vm_gtod_copy(kvm);
  6859. INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
  6860. INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
  6861. kvm_page_track_init(kvm);
  6862. kvm_mmu_init_vm(kvm);
  6863. if (kvm_x86_ops->vm_init)
  6864. return kvm_x86_ops->vm_init(kvm);
  6865. return 0;
  6866. }
  6867. static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
  6868. {
  6869. int r;
  6870. r = vcpu_load(vcpu);
  6871. BUG_ON(r);
  6872. kvm_mmu_unload(vcpu);
  6873. vcpu_put(vcpu);
  6874. }
  6875. static void kvm_free_vcpus(struct kvm *kvm)
  6876. {
  6877. unsigned int i;
  6878. struct kvm_vcpu *vcpu;
  6879. /*
  6880. * Unpin any mmu pages first.
  6881. */
  6882. kvm_for_each_vcpu(i, vcpu, kvm) {
  6883. kvm_clear_async_pf_completion_queue(vcpu);
  6884. kvm_unload_vcpu_mmu(vcpu);
  6885. }
  6886. kvm_for_each_vcpu(i, vcpu, kvm)
  6887. kvm_arch_vcpu_free(vcpu);
  6888. mutex_lock(&kvm->lock);
  6889. for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
  6890. kvm->vcpus[i] = NULL;
  6891. atomic_set(&kvm->online_vcpus, 0);
  6892. mutex_unlock(&kvm->lock);
  6893. }
  6894. void kvm_arch_sync_events(struct kvm *kvm)
  6895. {
  6896. cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
  6897. cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
  6898. kvm_free_pit(kvm);
  6899. }
  6900. int __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
  6901. {
  6902. int i, r;
  6903. unsigned long hva;
  6904. struct kvm_memslots *slots = kvm_memslots(kvm);
  6905. struct kvm_memory_slot *slot, old;
  6906. /* Called with kvm->slots_lock held. */
  6907. if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
  6908. return -EINVAL;
  6909. slot = id_to_memslot(slots, id);
  6910. if (size) {
  6911. if (slot->npages)
  6912. return -EEXIST;
  6913. /*
  6914. * MAP_SHARED to prevent internal slot pages from being moved
  6915. * by fork()/COW.
  6916. */
  6917. hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
  6918. MAP_SHARED | MAP_ANONYMOUS, 0);
  6919. if (IS_ERR((void *)hva))
  6920. return PTR_ERR((void *)hva);
  6921. } else {
  6922. if (!slot->npages)
  6923. return 0;
  6924. hva = 0;
  6925. }
  6926. old = *slot;
  6927. for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
  6928. struct kvm_userspace_memory_region m;
  6929. m.slot = id | (i << 16);
  6930. m.flags = 0;
  6931. m.guest_phys_addr = gpa;
  6932. m.userspace_addr = hva;
  6933. m.memory_size = size;
  6934. r = __kvm_set_memory_region(kvm, &m);
  6935. if (r < 0)
  6936. return r;
  6937. }
  6938. if (!size) {
  6939. r = vm_munmap(old.userspace_addr, old.npages * PAGE_SIZE);
  6940. WARN_ON(r < 0);
  6941. }
  6942. return 0;
  6943. }
  6944. EXPORT_SYMBOL_GPL(__x86_set_memory_region);
  6945. int x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
  6946. {
  6947. int r;
  6948. mutex_lock(&kvm->slots_lock);
  6949. r = __x86_set_memory_region(kvm, id, gpa, size);
  6950. mutex_unlock(&kvm->slots_lock);
  6951. return r;
  6952. }
  6953. EXPORT_SYMBOL_GPL(x86_set_memory_region);
  6954. void kvm_arch_destroy_vm(struct kvm *kvm)
  6955. {
  6956. if (current->mm == kvm->mm) {
  6957. /*
  6958. * Free memory regions allocated on behalf of userspace,
  6959. * unless the the memory map has changed due to process exit
  6960. * or fd copying.
  6961. */
  6962. x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT, 0, 0);
  6963. x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT, 0, 0);
  6964. x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
  6965. }
  6966. if (kvm_x86_ops->vm_destroy)
  6967. kvm_x86_ops->vm_destroy(kvm);
  6968. kvm_pic_destroy(kvm);
  6969. kvm_ioapic_destroy(kvm);
  6970. kvm_free_vcpus(kvm);
  6971. kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
  6972. kvm_mmu_uninit_vm(kvm);
  6973. kvm_page_track_cleanup(kvm);
  6974. }
  6975. void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *free,
  6976. struct kvm_memory_slot *dont)
  6977. {
  6978. int i;
  6979. for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
  6980. if (!dont || free->arch.rmap[i] != dont->arch.rmap[i]) {
  6981. kvfree(free->arch.rmap[i]);
  6982. free->arch.rmap[i] = NULL;
  6983. }
  6984. if (i == 0)
  6985. continue;
  6986. if (!dont || free->arch.lpage_info[i - 1] !=
  6987. dont->arch.lpage_info[i - 1]) {
  6988. kvfree(free->arch.lpage_info[i - 1]);
  6989. free->arch.lpage_info[i - 1] = NULL;
  6990. }
  6991. }
  6992. kvm_page_track_free_memslot(free, dont);
  6993. }
  6994. int kvm_arch_create_memslot(struct kvm *kvm, struct kvm_memory_slot *slot,
  6995. unsigned long npages)
  6996. {
  6997. int i;
  6998. for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
  6999. struct kvm_lpage_info *linfo;
  7000. unsigned long ugfn;
  7001. int lpages;
  7002. int level = i + 1;
  7003. lpages = gfn_to_index(slot->base_gfn + npages - 1,
  7004. slot->base_gfn, level) + 1;
  7005. slot->arch.rmap[i] =
  7006. kvzalloc(lpages * sizeof(*slot->arch.rmap[i]), GFP_KERNEL);
  7007. if (!slot->arch.rmap[i])
  7008. goto out_free;
  7009. if (i == 0)
  7010. continue;
  7011. linfo = kvzalloc(lpages * sizeof(*linfo), GFP_KERNEL);
  7012. if (!linfo)
  7013. goto out_free;
  7014. slot->arch.lpage_info[i - 1] = linfo;
  7015. if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
  7016. linfo[0].disallow_lpage = 1;
  7017. if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
  7018. linfo[lpages - 1].disallow_lpage = 1;
  7019. ugfn = slot->userspace_addr >> PAGE_SHIFT;
  7020. /*
  7021. * If the gfn and userspace address are not aligned wrt each
  7022. * other, or if explicitly asked to, disable large page
  7023. * support for this slot
  7024. */
  7025. if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||
  7026. !kvm_largepages_enabled()) {
  7027. unsigned long j;
  7028. for (j = 0; j < lpages; ++j)
  7029. linfo[j].disallow_lpage = 1;
  7030. }
  7031. }
  7032. if (kvm_page_track_create_memslot(slot, npages))
  7033. goto out_free;
  7034. return 0;
  7035. out_free:
  7036. for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
  7037. kvfree(slot->arch.rmap[i]);
  7038. slot->arch.rmap[i] = NULL;
  7039. if (i == 0)
  7040. continue;
  7041. kvfree(slot->arch.lpage_info[i - 1]);
  7042. slot->arch.lpage_info[i - 1] = NULL;
  7043. }
  7044. return -ENOMEM;
  7045. }
  7046. void kvm_arch_memslots_updated(struct kvm *kvm, struct kvm_memslots *slots)
  7047. {
  7048. /*
  7049. * memslots->generation has been incremented.
  7050. * mmio generation may have reached its maximum value.
  7051. */
  7052. kvm_mmu_invalidate_mmio_sptes(kvm, slots);
  7053. }
  7054. int kvm_arch_prepare_memory_region(struct kvm *kvm,
  7055. struct kvm_memory_slot *memslot,
  7056. const struct kvm_userspace_memory_region *mem,
  7057. enum kvm_mr_change change)
  7058. {
  7059. return 0;
  7060. }
  7061. static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
  7062. struct kvm_memory_slot *new)
  7063. {
  7064. /* Still write protect RO slot */
  7065. if (new->flags & KVM_MEM_READONLY) {
  7066. kvm_mmu_slot_remove_write_access(kvm, new);
  7067. return;
  7068. }
  7069. /*
  7070. * Call kvm_x86_ops dirty logging hooks when they are valid.
  7071. *
  7072. * kvm_x86_ops->slot_disable_log_dirty is called when:
  7073. *
  7074. * - KVM_MR_CREATE with dirty logging is disabled
  7075. * - KVM_MR_FLAGS_ONLY with dirty logging is disabled in new flag
  7076. *
  7077. * The reason is, in case of PML, we need to set D-bit for any slots
  7078. * with dirty logging disabled in order to eliminate unnecessary GPA
  7079. * logging in PML buffer (and potential PML buffer full VMEXT). This
  7080. * guarantees leaving PML enabled during guest's lifetime won't have
  7081. * any additonal overhead from PML when guest is running with dirty
  7082. * logging disabled for memory slots.
  7083. *
  7084. * kvm_x86_ops->slot_enable_log_dirty is called when switching new slot
  7085. * to dirty logging mode.
  7086. *
  7087. * If kvm_x86_ops dirty logging hooks are invalid, use write protect.
  7088. *
  7089. * In case of write protect:
  7090. *
  7091. * Write protect all pages for dirty logging.
  7092. *
  7093. * All the sptes including the large sptes which point to this
  7094. * slot are set to readonly. We can not create any new large
  7095. * spte on this slot until the end of the logging.
  7096. *
  7097. * See the comments in fast_page_fault().
  7098. */
  7099. if (new->flags & KVM_MEM_LOG_DIRTY_PAGES) {
  7100. if (kvm_x86_ops->slot_enable_log_dirty)
  7101. kvm_x86_ops->slot_enable_log_dirty(kvm, new);
  7102. else
  7103. kvm_mmu_slot_remove_write_access(kvm, new);
  7104. } else {
  7105. if (kvm_x86_ops->slot_disable_log_dirty)
  7106. kvm_x86_ops->slot_disable_log_dirty(kvm, new);
  7107. }
  7108. }
  7109. void kvm_arch_commit_memory_region(struct kvm *kvm,
  7110. const struct kvm_userspace_memory_region *mem,
  7111. const struct kvm_memory_slot *old,
  7112. const struct kvm_memory_slot *new,
  7113. enum kvm_mr_change change)
  7114. {
  7115. int nr_mmu_pages = 0;
  7116. if (!kvm->arch.n_requested_mmu_pages)
  7117. nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
  7118. if (nr_mmu_pages)
  7119. kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
  7120. /*
  7121. * Dirty logging tracks sptes in 4k granularity, meaning that large
  7122. * sptes have to be split. If live migration is successful, the guest
  7123. * in the source machine will be destroyed and large sptes will be
  7124. * created in the destination. However, if the guest continues to run
  7125. * in the source machine (for example if live migration fails), small
  7126. * sptes will remain around and cause bad performance.
  7127. *
  7128. * Scan sptes if dirty logging has been stopped, dropping those
  7129. * which can be collapsed into a single large-page spte. Later
  7130. * page faults will create the large-page sptes.
  7131. */
  7132. if ((change != KVM_MR_DELETE) &&
  7133. (old->flags & KVM_MEM_LOG_DIRTY_PAGES) &&
  7134. !(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
  7135. kvm_mmu_zap_collapsible_sptes(kvm, new);
  7136. /*
  7137. * Set up write protection and/or dirty logging for the new slot.
  7138. *
  7139. * For KVM_MR_DELETE and KVM_MR_MOVE, the shadow pages of old slot have
  7140. * been zapped so no dirty logging staff is needed for old slot. For
  7141. * KVM_MR_FLAGS_ONLY, the old slot is essentially the same one as the
  7142. * new and it's also covered when dealing with the new slot.
  7143. *
  7144. * FIXME: const-ify all uses of struct kvm_memory_slot.
  7145. */
  7146. if (change != KVM_MR_DELETE)
  7147. kvm_mmu_slot_apply_flags(kvm, (struct kvm_memory_slot *) new);
  7148. }
  7149. void kvm_arch_flush_shadow_all(struct kvm *kvm)
  7150. {
  7151. kvm_mmu_invalidate_zap_all_pages(kvm);
  7152. }
  7153. void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
  7154. struct kvm_memory_slot *slot)
  7155. {
  7156. kvm_page_track_flush_slot(kvm, slot);
  7157. }
  7158. static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
  7159. {
  7160. if (!list_empty_careful(&vcpu->async_pf.done))
  7161. return true;
  7162. if (kvm_apic_has_events(vcpu))
  7163. return true;
  7164. if (vcpu->arch.pv.pv_unhalted)
  7165. return true;
  7166. if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
  7167. (vcpu->arch.nmi_pending &&
  7168. kvm_x86_ops->nmi_allowed(vcpu)))
  7169. return true;
  7170. if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
  7171. (vcpu->arch.smi_pending && !is_smm(vcpu)))
  7172. return true;
  7173. if (kvm_arch_interrupt_allowed(vcpu) &&
  7174. kvm_cpu_has_interrupt(vcpu))
  7175. return true;
  7176. if (kvm_hv_has_stimer_pending(vcpu))
  7177. return true;
  7178. return false;
  7179. }
  7180. int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
  7181. {
  7182. return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
  7183. }
  7184. int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
  7185. {
  7186. return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
  7187. }
  7188. int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
  7189. {
  7190. return kvm_x86_ops->interrupt_allowed(vcpu);
  7191. }
  7192. unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
  7193. {
  7194. if (is_64_bit_mode(vcpu))
  7195. return kvm_rip_read(vcpu);
  7196. return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
  7197. kvm_rip_read(vcpu));
  7198. }
  7199. EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
  7200. bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
  7201. {
  7202. return kvm_get_linear_rip(vcpu) == linear_rip;
  7203. }
  7204. EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
  7205. unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
  7206. {
  7207. unsigned long rflags;
  7208. rflags = kvm_x86_ops->get_rflags(vcpu);
  7209. if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
  7210. rflags &= ~X86_EFLAGS_TF;
  7211. return rflags;
  7212. }
  7213. EXPORT_SYMBOL_GPL(kvm_get_rflags);
  7214. static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
  7215. {
  7216. if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
  7217. kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
  7218. rflags |= X86_EFLAGS_TF;
  7219. kvm_x86_ops->set_rflags(vcpu, rflags);
  7220. }
  7221. void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
  7222. {
  7223. __kvm_set_rflags(vcpu, rflags);
  7224. kvm_make_request(KVM_REQ_EVENT, vcpu);
  7225. }
  7226. EXPORT_SYMBOL_GPL(kvm_set_rflags);
  7227. void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
  7228. {
  7229. int r;
  7230. if ((vcpu->arch.mmu.direct_map != work->arch.direct_map) ||
  7231. work->wakeup_all)
  7232. return;
  7233. r = kvm_mmu_reload(vcpu);
  7234. if (unlikely(r))
  7235. return;
  7236. if (!vcpu->arch.mmu.direct_map &&
  7237. work->arch.cr3 != vcpu->arch.mmu.get_cr3(vcpu))
  7238. return;
  7239. vcpu->arch.mmu.page_fault(vcpu, work->gva, 0, true);
  7240. }
  7241. static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
  7242. {
  7243. return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
  7244. }
  7245. static inline u32 kvm_async_pf_next_probe(u32 key)
  7246. {
  7247. return (key + 1) & (roundup_pow_of_two(ASYNC_PF_PER_VCPU) - 1);
  7248. }
  7249. static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
  7250. {
  7251. u32 key = kvm_async_pf_hash_fn(gfn);
  7252. while (vcpu->arch.apf.gfns[key] != ~0)
  7253. key = kvm_async_pf_next_probe(key);
  7254. vcpu->arch.apf.gfns[key] = gfn;
  7255. }
  7256. static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
  7257. {
  7258. int i;
  7259. u32 key = kvm_async_pf_hash_fn(gfn);
  7260. for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU) &&
  7261. (vcpu->arch.apf.gfns[key] != gfn &&
  7262. vcpu->arch.apf.gfns[key] != ~0); i++)
  7263. key = kvm_async_pf_next_probe(key);
  7264. return key;
  7265. }
  7266. bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
  7267. {
  7268. return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
  7269. }
  7270. static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
  7271. {
  7272. u32 i, j, k;
  7273. i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
  7274. while (true) {
  7275. vcpu->arch.apf.gfns[i] = ~0;
  7276. do {
  7277. j = kvm_async_pf_next_probe(j);
  7278. if (vcpu->arch.apf.gfns[j] == ~0)
  7279. return;
  7280. k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
  7281. /*
  7282. * k lies cyclically in ]i,j]
  7283. * | i.k.j |
  7284. * |....j i.k.| or |.k..j i...|
  7285. */
  7286. } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
  7287. vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
  7288. i = j;
  7289. }
  7290. }
  7291. static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
  7292. {
  7293. return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
  7294. sizeof(val));
  7295. }
  7296. void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
  7297. struct kvm_async_pf *work)
  7298. {
  7299. struct x86_exception fault;
  7300. trace_kvm_async_pf_not_present(work->arch.token, work->gva);
  7301. kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
  7302. if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
  7303. (vcpu->arch.apf.send_user_only &&
  7304. kvm_x86_ops->get_cpl(vcpu) == 0))
  7305. kvm_make_request(KVM_REQ_APF_HALT, vcpu);
  7306. else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
  7307. fault.vector = PF_VECTOR;
  7308. fault.error_code_valid = true;
  7309. fault.error_code = 0;
  7310. fault.nested_page_fault = false;
  7311. fault.address = work->arch.token;
  7312. kvm_inject_page_fault(vcpu, &fault);
  7313. }
  7314. }
  7315. void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
  7316. struct kvm_async_pf *work)
  7317. {
  7318. struct x86_exception fault;
  7319. if (work->wakeup_all)
  7320. work->arch.token = ~0; /* broadcast wakeup */
  7321. else
  7322. kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
  7323. trace_kvm_async_pf_ready(work->arch.token, work->gva);
  7324. if ((vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) &&
  7325. !apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
  7326. fault.vector = PF_VECTOR;
  7327. fault.error_code_valid = true;
  7328. fault.error_code = 0;
  7329. fault.nested_page_fault = false;
  7330. fault.address = work->arch.token;
  7331. kvm_inject_page_fault(vcpu, &fault);
  7332. }
  7333. vcpu->arch.apf.halted = false;
  7334. vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
  7335. }
  7336. bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu)
  7337. {
  7338. if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED))
  7339. return true;
  7340. else
  7341. return kvm_can_do_async_pf(vcpu);
  7342. }
  7343. void kvm_arch_start_assignment(struct kvm *kvm)
  7344. {
  7345. atomic_inc(&kvm->arch.assigned_device_count);
  7346. }
  7347. EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
  7348. void kvm_arch_end_assignment(struct kvm *kvm)
  7349. {
  7350. atomic_dec(&kvm->arch.assigned_device_count);
  7351. }
  7352. EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
  7353. bool kvm_arch_has_assigned_device(struct kvm *kvm)
  7354. {
  7355. return atomic_read(&kvm->arch.assigned_device_count);
  7356. }
  7357. EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
  7358. void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
  7359. {
  7360. atomic_inc(&kvm->arch.noncoherent_dma_count);
  7361. }
  7362. EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
  7363. void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
  7364. {
  7365. atomic_dec(&kvm->arch.noncoherent_dma_count);
  7366. }
  7367. EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
  7368. bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
  7369. {
  7370. return atomic_read(&kvm->arch.noncoherent_dma_count);
  7371. }
  7372. EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
  7373. bool kvm_arch_has_irq_bypass(void)
  7374. {
  7375. return kvm_x86_ops->update_pi_irte != NULL;
  7376. }
  7377. int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
  7378. struct irq_bypass_producer *prod)
  7379. {
  7380. struct kvm_kernel_irqfd *irqfd =
  7381. container_of(cons, struct kvm_kernel_irqfd, consumer);
  7382. irqfd->producer = prod;
  7383. return kvm_x86_ops->update_pi_irte(irqfd->kvm,
  7384. prod->irq, irqfd->gsi, 1);
  7385. }
  7386. void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
  7387. struct irq_bypass_producer *prod)
  7388. {
  7389. int ret;
  7390. struct kvm_kernel_irqfd *irqfd =
  7391. container_of(cons, struct kvm_kernel_irqfd, consumer);
  7392. WARN_ON(irqfd->producer != prod);
  7393. irqfd->producer = NULL;
  7394. /*
  7395. * When producer of consumer is unregistered, we change back to
  7396. * remapped mode, so we can re-use the current implementation
  7397. * when the irq is masked/disabled or the consumer side (KVM
  7398. * int this case doesn't want to receive the interrupts.
  7399. */
  7400. ret = kvm_x86_ops->update_pi_irte(irqfd->kvm, prod->irq, irqfd->gsi, 0);
  7401. if (ret)
  7402. printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
  7403. " fails: %d\n", irqfd->consumer.token, ret);
  7404. }
  7405. int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
  7406. uint32_t guest_irq, bool set)
  7407. {
  7408. if (!kvm_x86_ops->update_pi_irte)
  7409. return -EINVAL;
  7410. return kvm_x86_ops->update_pi_irte(kvm, host_irq, guest_irq, set);
  7411. }
  7412. bool kvm_vector_hashing_enabled(void)
  7413. {
  7414. return vector_hashing;
  7415. }
  7416. EXPORT_SYMBOL_GPL(kvm_vector_hashing_enabled);
  7417. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
  7418. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
  7419. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
  7420. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
  7421. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
  7422. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
  7423. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
  7424. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
  7425. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
  7426. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
  7427. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
  7428. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
  7429. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
  7430. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
  7431. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window);
  7432. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
  7433. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);
  7434. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
  7435. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);