x86.c 204 KB

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