x86.c 212 KB

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