x86.c 186 KB

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