x86.c 190 KB

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