x86.c 176 KB

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