x86.c 233 KB

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