x86.c 223 KB

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