x86.c 218 KB

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