x86.c 175 KB

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