x86.c 216 KB

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