x86.c 205 KB

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