x86.c 225 KB

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