x86.c 186 KB

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