x86.c 200 KB

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