x86.c 194 KB

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