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_x86_ops->set_hv_timer(vcpu,
  2460. kvm_get_lapic_target_expiration_tsc(vcpu)))
  2461. kvm_lapic_switch_to_sw_timer(vcpu);
  2462. /*
  2463. * On a host with synchronized TSC, there is no need to update
  2464. * kvmclock on vcpu->cpu migration
  2465. */
  2466. if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
  2467. kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
  2468. if (vcpu->cpu != cpu)
  2469. kvm_make_request(KVM_REQ_MIGRATE_TIMER, vcpu);
  2470. vcpu->cpu = cpu;
  2471. }
  2472. kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
  2473. }
  2474. static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
  2475. {
  2476. if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
  2477. return;
  2478. vcpu->arch.st.steal.preempted = 1;
  2479. kvm_write_guest_offset_cached(vcpu->kvm, &vcpu->arch.st.stime,
  2480. &vcpu->arch.st.steal.preempted,
  2481. offsetof(struct kvm_steal_time, preempted),
  2482. sizeof(vcpu->arch.st.steal.preempted));
  2483. }
  2484. void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
  2485. {
  2486. int idx;
  2487. /*
  2488. * Disable page faults because we're in atomic context here.
  2489. * kvm_write_guest_offset_cached() would call might_fault()
  2490. * that relies on pagefault_disable() to tell if there's a
  2491. * bug. NOTE: the write to guest memory may not go through if
  2492. * during postcopy live migration or if there's heavy guest
  2493. * paging.
  2494. */
  2495. pagefault_disable();
  2496. /*
  2497. * kvm_memslots() will be called by
  2498. * kvm_write_guest_offset_cached() so take the srcu lock.
  2499. */
  2500. idx = srcu_read_lock(&vcpu->kvm->srcu);
  2501. kvm_steal_time_set_preempted(vcpu);
  2502. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  2503. pagefault_enable();
  2504. kvm_x86_ops->vcpu_put(vcpu);
  2505. kvm_put_guest_fpu(vcpu);
  2506. vcpu->arch.last_host_tsc = rdtsc();
  2507. }
  2508. static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
  2509. struct kvm_lapic_state *s)
  2510. {
  2511. if (kvm_x86_ops->sync_pir_to_irr && vcpu->arch.apicv_active)
  2512. kvm_x86_ops->sync_pir_to_irr(vcpu);
  2513. return kvm_apic_get_state(vcpu, s);
  2514. }
  2515. static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
  2516. struct kvm_lapic_state *s)
  2517. {
  2518. int r;
  2519. r = kvm_apic_set_state(vcpu, s);
  2520. if (r)
  2521. return r;
  2522. update_cr8_intercept(vcpu);
  2523. return 0;
  2524. }
  2525. static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
  2526. {
  2527. return (!lapic_in_kernel(vcpu) ||
  2528. kvm_apic_accept_pic_intr(vcpu));
  2529. }
  2530. /*
  2531. * if userspace requested an interrupt window, check that the
  2532. * interrupt window is open.
  2533. *
  2534. * No need to exit to userspace if we already have an interrupt queued.
  2535. */
  2536. static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
  2537. {
  2538. return kvm_arch_interrupt_allowed(vcpu) &&
  2539. !kvm_cpu_has_interrupt(vcpu) &&
  2540. !kvm_event_needs_reinjection(vcpu) &&
  2541. kvm_cpu_accept_dm_intr(vcpu);
  2542. }
  2543. static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
  2544. struct kvm_interrupt *irq)
  2545. {
  2546. if (irq->irq >= KVM_NR_INTERRUPTS)
  2547. return -EINVAL;
  2548. if (!irqchip_in_kernel(vcpu->kvm)) {
  2549. kvm_queue_interrupt(vcpu, irq->irq, false);
  2550. kvm_make_request(KVM_REQ_EVENT, vcpu);
  2551. return 0;
  2552. }
  2553. /*
  2554. * With in-kernel LAPIC, we only use this to inject EXTINT, so
  2555. * fail for in-kernel 8259.
  2556. */
  2557. if (pic_in_kernel(vcpu->kvm))
  2558. return -ENXIO;
  2559. if (vcpu->arch.pending_external_vector != -1)
  2560. return -EEXIST;
  2561. vcpu->arch.pending_external_vector = irq->irq;
  2562. kvm_make_request(KVM_REQ_EVENT, vcpu);
  2563. return 0;
  2564. }
  2565. static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
  2566. {
  2567. kvm_inject_nmi(vcpu);
  2568. return 0;
  2569. }
  2570. static int kvm_vcpu_ioctl_smi(struct kvm_vcpu *vcpu)
  2571. {
  2572. kvm_make_request(KVM_REQ_SMI, vcpu);
  2573. return 0;
  2574. }
  2575. static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
  2576. struct kvm_tpr_access_ctl *tac)
  2577. {
  2578. if (tac->flags)
  2579. return -EINVAL;
  2580. vcpu->arch.tpr_access_reporting = !!tac->enabled;
  2581. return 0;
  2582. }
  2583. static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
  2584. u64 mcg_cap)
  2585. {
  2586. int r;
  2587. unsigned bank_num = mcg_cap & 0xff, bank;
  2588. r = -EINVAL;
  2589. if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
  2590. goto out;
  2591. if (mcg_cap & ~(kvm_mce_cap_supported | 0xff | 0xff0000))
  2592. goto out;
  2593. r = 0;
  2594. vcpu->arch.mcg_cap = mcg_cap;
  2595. /* Init IA32_MCG_CTL to all 1s */
  2596. if (mcg_cap & MCG_CTL_P)
  2597. vcpu->arch.mcg_ctl = ~(u64)0;
  2598. /* Init IA32_MCi_CTL to all 1s */
  2599. for (bank = 0; bank < bank_num; bank++)
  2600. vcpu->arch.mce_banks[bank*4] = ~(u64)0;
  2601. if (kvm_x86_ops->setup_mce)
  2602. kvm_x86_ops->setup_mce(vcpu);
  2603. out:
  2604. return r;
  2605. }
  2606. static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
  2607. struct kvm_x86_mce *mce)
  2608. {
  2609. u64 mcg_cap = vcpu->arch.mcg_cap;
  2610. unsigned bank_num = mcg_cap & 0xff;
  2611. u64 *banks = vcpu->arch.mce_banks;
  2612. if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
  2613. return -EINVAL;
  2614. /*
  2615. * if IA32_MCG_CTL is not all 1s, the uncorrected error
  2616. * reporting is disabled
  2617. */
  2618. if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
  2619. vcpu->arch.mcg_ctl != ~(u64)0)
  2620. return 0;
  2621. banks += 4 * mce->bank;
  2622. /*
  2623. * if IA32_MCi_CTL is not all 1s, the uncorrected error
  2624. * reporting is disabled for the bank
  2625. */
  2626. if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
  2627. return 0;
  2628. if (mce->status & MCI_STATUS_UC) {
  2629. if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
  2630. !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
  2631. kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
  2632. return 0;
  2633. }
  2634. if (banks[1] & MCI_STATUS_VAL)
  2635. mce->status |= MCI_STATUS_OVER;
  2636. banks[2] = mce->addr;
  2637. banks[3] = mce->misc;
  2638. vcpu->arch.mcg_status = mce->mcg_status;
  2639. banks[1] = mce->status;
  2640. kvm_queue_exception(vcpu, MC_VECTOR);
  2641. } else if (!(banks[1] & MCI_STATUS_VAL)
  2642. || !(banks[1] & MCI_STATUS_UC)) {
  2643. if (banks[1] & MCI_STATUS_VAL)
  2644. mce->status |= MCI_STATUS_OVER;
  2645. banks[2] = mce->addr;
  2646. banks[3] = mce->misc;
  2647. banks[1] = mce->status;
  2648. } else
  2649. banks[1] |= MCI_STATUS_OVER;
  2650. return 0;
  2651. }
  2652. static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
  2653. struct kvm_vcpu_events *events)
  2654. {
  2655. process_nmi(vcpu);
  2656. events->exception.injected =
  2657. vcpu->arch.exception.pending &&
  2658. !kvm_exception_is_soft(vcpu->arch.exception.nr);
  2659. events->exception.nr = vcpu->arch.exception.nr;
  2660. events->exception.has_error_code = vcpu->arch.exception.has_error_code;
  2661. events->exception.pad = 0;
  2662. events->exception.error_code = vcpu->arch.exception.error_code;
  2663. events->interrupt.injected =
  2664. vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft;
  2665. events->interrupt.nr = vcpu->arch.interrupt.nr;
  2666. events->interrupt.soft = 0;
  2667. events->interrupt.shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
  2668. events->nmi.injected = vcpu->arch.nmi_injected;
  2669. events->nmi.pending = vcpu->arch.nmi_pending != 0;
  2670. events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
  2671. events->nmi.pad = 0;
  2672. events->sipi_vector = 0; /* never valid when reporting to user space */
  2673. events->smi.smm = is_smm(vcpu);
  2674. events->smi.pending = vcpu->arch.smi_pending;
  2675. events->smi.smm_inside_nmi =
  2676. !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
  2677. events->smi.latched_init = kvm_lapic_latched_init(vcpu);
  2678. events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
  2679. | KVM_VCPUEVENT_VALID_SHADOW
  2680. | KVM_VCPUEVENT_VALID_SMM);
  2681. memset(&events->reserved, 0, sizeof(events->reserved));
  2682. }
  2683. static void kvm_set_hflags(struct kvm_vcpu *vcpu, unsigned emul_flags);
  2684. static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
  2685. struct kvm_vcpu_events *events)
  2686. {
  2687. if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
  2688. | KVM_VCPUEVENT_VALID_SIPI_VECTOR
  2689. | KVM_VCPUEVENT_VALID_SHADOW
  2690. | KVM_VCPUEVENT_VALID_SMM))
  2691. return -EINVAL;
  2692. if (events->exception.injected &&
  2693. (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR ||
  2694. is_guest_mode(vcpu)))
  2695. return -EINVAL;
  2696. /* INITs are latched while in SMM */
  2697. if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
  2698. (events->smi.smm || events->smi.pending) &&
  2699. vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
  2700. return -EINVAL;
  2701. process_nmi(vcpu);
  2702. vcpu->arch.exception.pending = events->exception.injected;
  2703. vcpu->arch.exception.nr = events->exception.nr;
  2704. vcpu->arch.exception.has_error_code = events->exception.has_error_code;
  2705. vcpu->arch.exception.error_code = events->exception.error_code;
  2706. vcpu->arch.interrupt.pending = events->interrupt.injected;
  2707. vcpu->arch.interrupt.nr = events->interrupt.nr;
  2708. vcpu->arch.interrupt.soft = events->interrupt.soft;
  2709. if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
  2710. kvm_x86_ops->set_interrupt_shadow(vcpu,
  2711. events->interrupt.shadow);
  2712. vcpu->arch.nmi_injected = events->nmi.injected;
  2713. if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
  2714. vcpu->arch.nmi_pending = events->nmi.pending;
  2715. kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
  2716. if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
  2717. lapic_in_kernel(vcpu))
  2718. vcpu->arch.apic->sipi_vector = events->sipi_vector;
  2719. if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
  2720. u32 hflags = vcpu->arch.hflags;
  2721. if (events->smi.smm)
  2722. hflags |= HF_SMM_MASK;
  2723. else
  2724. hflags &= ~HF_SMM_MASK;
  2725. kvm_set_hflags(vcpu, hflags);
  2726. vcpu->arch.smi_pending = events->smi.pending;
  2727. if (events->smi.smm_inside_nmi)
  2728. vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
  2729. else
  2730. vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
  2731. if (lapic_in_kernel(vcpu)) {
  2732. if (events->smi.latched_init)
  2733. set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
  2734. else
  2735. clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
  2736. }
  2737. }
  2738. kvm_make_request(KVM_REQ_EVENT, vcpu);
  2739. return 0;
  2740. }
  2741. static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
  2742. struct kvm_debugregs *dbgregs)
  2743. {
  2744. unsigned long val;
  2745. memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
  2746. kvm_get_dr(vcpu, 6, &val);
  2747. dbgregs->dr6 = val;
  2748. dbgregs->dr7 = vcpu->arch.dr7;
  2749. dbgregs->flags = 0;
  2750. memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
  2751. }
  2752. static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
  2753. struct kvm_debugregs *dbgregs)
  2754. {
  2755. if (dbgregs->flags)
  2756. return -EINVAL;
  2757. if (dbgregs->dr6 & ~0xffffffffull)
  2758. return -EINVAL;
  2759. if (dbgregs->dr7 & ~0xffffffffull)
  2760. return -EINVAL;
  2761. memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
  2762. kvm_update_dr0123(vcpu);
  2763. vcpu->arch.dr6 = dbgregs->dr6;
  2764. kvm_update_dr6(vcpu);
  2765. vcpu->arch.dr7 = dbgregs->dr7;
  2766. kvm_update_dr7(vcpu);
  2767. return 0;
  2768. }
  2769. #define XSTATE_COMPACTION_ENABLED (1ULL << 63)
  2770. static void fill_xsave(u8 *dest, struct kvm_vcpu *vcpu)
  2771. {
  2772. struct xregs_state *xsave = &vcpu->arch.guest_fpu.state.xsave;
  2773. u64 xstate_bv = xsave->header.xfeatures;
  2774. u64 valid;
  2775. /*
  2776. * Copy legacy XSAVE area, to avoid complications with CPUID
  2777. * leaves 0 and 1 in the loop below.
  2778. */
  2779. memcpy(dest, xsave, XSAVE_HDR_OFFSET);
  2780. /* Set XSTATE_BV */
  2781. xstate_bv &= vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FPSSE;
  2782. *(u64 *)(dest + XSAVE_HDR_OFFSET) = xstate_bv;
  2783. /*
  2784. * Copy each region from the possibly compacted offset to the
  2785. * non-compacted offset.
  2786. */
  2787. valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
  2788. while (valid) {
  2789. u64 feature = valid & -valid;
  2790. int index = fls64(feature) - 1;
  2791. void *src = get_xsave_addr(xsave, feature);
  2792. if (src) {
  2793. u32 size, offset, ecx, edx;
  2794. cpuid_count(XSTATE_CPUID, index,
  2795. &size, &offset, &ecx, &edx);
  2796. memcpy(dest + offset, src, size);
  2797. }
  2798. valid -= feature;
  2799. }
  2800. }
  2801. static void load_xsave(struct kvm_vcpu *vcpu, u8 *src)
  2802. {
  2803. struct xregs_state *xsave = &vcpu->arch.guest_fpu.state.xsave;
  2804. u64 xstate_bv = *(u64 *)(src + XSAVE_HDR_OFFSET);
  2805. u64 valid;
  2806. /*
  2807. * Copy legacy XSAVE area, to avoid complications with CPUID
  2808. * leaves 0 and 1 in the loop below.
  2809. */
  2810. memcpy(xsave, src, XSAVE_HDR_OFFSET);
  2811. /* Set XSTATE_BV and possibly XCOMP_BV. */
  2812. xsave->header.xfeatures = xstate_bv;
  2813. if (boot_cpu_has(X86_FEATURE_XSAVES))
  2814. xsave->header.xcomp_bv = host_xcr0 | XSTATE_COMPACTION_ENABLED;
  2815. /*
  2816. * Copy each region from the non-compacted offset to the
  2817. * possibly compacted offset.
  2818. */
  2819. valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
  2820. while (valid) {
  2821. u64 feature = valid & -valid;
  2822. int index = fls64(feature) - 1;
  2823. void *dest = get_xsave_addr(xsave, feature);
  2824. if (dest) {
  2825. u32 size, offset, ecx, edx;
  2826. cpuid_count(XSTATE_CPUID, index,
  2827. &size, &offset, &ecx, &edx);
  2828. memcpy(dest, src + offset, size);
  2829. }
  2830. valid -= feature;
  2831. }
  2832. }
  2833. static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
  2834. struct kvm_xsave *guest_xsave)
  2835. {
  2836. if (boot_cpu_has(X86_FEATURE_XSAVE)) {
  2837. memset(guest_xsave, 0, sizeof(struct kvm_xsave));
  2838. fill_xsave((u8 *) guest_xsave->region, vcpu);
  2839. } else {
  2840. memcpy(guest_xsave->region,
  2841. &vcpu->arch.guest_fpu.state.fxsave,
  2842. sizeof(struct fxregs_state));
  2843. *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
  2844. XFEATURE_MASK_FPSSE;
  2845. }
  2846. }
  2847. #define XSAVE_MXCSR_OFFSET 24
  2848. static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
  2849. struct kvm_xsave *guest_xsave)
  2850. {
  2851. u64 xstate_bv =
  2852. *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
  2853. u32 mxcsr = *(u32 *)&guest_xsave->region[XSAVE_MXCSR_OFFSET / sizeof(u32)];
  2854. if (boot_cpu_has(X86_FEATURE_XSAVE)) {
  2855. /*
  2856. * Here we allow setting states that are not present in
  2857. * CPUID leaf 0xD, index 0, EDX:EAX. This is for compatibility
  2858. * with old userspace.
  2859. */
  2860. if (xstate_bv & ~kvm_supported_xcr0() ||
  2861. mxcsr & ~mxcsr_feature_mask)
  2862. return -EINVAL;
  2863. load_xsave(vcpu, (u8 *)guest_xsave->region);
  2864. } else {
  2865. if (xstate_bv & ~XFEATURE_MASK_FPSSE ||
  2866. mxcsr & ~mxcsr_feature_mask)
  2867. return -EINVAL;
  2868. memcpy(&vcpu->arch.guest_fpu.state.fxsave,
  2869. guest_xsave->region, sizeof(struct fxregs_state));
  2870. }
  2871. return 0;
  2872. }
  2873. static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
  2874. struct kvm_xcrs *guest_xcrs)
  2875. {
  2876. if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
  2877. guest_xcrs->nr_xcrs = 0;
  2878. return;
  2879. }
  2880. guest_xcrs->nr_xcrs = 1;
  2881. guest_xcrs->flags = 0;
  2882. guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
  2883. guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
  2884. }
  2885. static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
  2886. struct kvm_xcrs *guest_xcrs)
  2887. {
  2888. int i, r = 0;
  2889. if (!boot_cpu_has(X86_FEATURE_XSAVE))
  2890. return -EINVAL;
  2891. if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
  2892. return -EINVAL;
  2893. for (i = 0; i < guest_xcrs->nr_xcrs; i++)
  2894. /* Only support XCR0 currently */
  2895. if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
  2896. r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
  2897. guest_xcrs->xcrs[i].value);
  2898. break;
  2899. }
  2900. if (r)
  2901. r = -EINVAL;
  2902. return r;
  2903. }
  2904. /*
  2905. * kvm_set_guest_paused() indicates to the guest kernel that it has been
  2906. * stopped by the hypervisor. This function will be called from the host only.
  2907. * EINVAL is returned when the host attempts to set the flag for a guest that
  2908. * does not support pv clocks.
  2909. */
  2910. static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
  2911. {
  2912. if (!vcpu->arch.pv_time_enabled)
  2913. return -EINVAL;
  2914. vcpu->arch.pvclock_set_guest_stopped_request = true;
  2915. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  2916. return 0;
  2917. }
  2918. static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
  2919. struct kvm_enable_cap *cap)
  2920. {
  2921. if (cap->flags)
  2922. return -EINVAL;
  2923. switch (cap->cap) {
  2924. case KVM_CAP_HYPERV_SYNIC:
  2925. if (!irqchip_in_kernel(vcpu->kvm))
  2926. return -EINVAL;
  2927. return kvm_hv_activate_synic(vcpu);
  2928. default:
  2929. return -EINVAL;
  2930. }
  2931. }
  2932. long kvm_arch_vcpu_ioctl(struct file *filp,
  2933. unsigned int ioctl, unsigned long arg)
  2934. {
  2935. struct kvm_vcpu *vcpu = filp->private_data;
  2936. void __user *argp = (void __user *)arg;
  2937. int r;
  2938. union {
  2939. struct kvm_lapic_state *lapic;
  2940. struct kvm_xsave *xsave;
  2941. struct kvm_xcrs *xcrs;
  2942. void *buffer;
  2943. } u;
  2944. u.buffer = NULL;
  2945. switch (ioctl) {
  2946. case KVM_GET_LAPIC: {
  2947. r = -EINVAL;
  2948. if (!lapic_in_kernel(vcpu))
  2949. goto out;
  2950. u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
  2951. r = -ENOMEM;
  2952. if (!u.lapic)
  2953. goto out;
  2954. r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
  2955. if (r)
  2956. goto out;
  2957. r = -EFAULT;
  2958. if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
  2959. goto out;
  2960. r = 0;
  2961. break;
  2962. }
  2963. case KVM_SET_LAPIC: {
  2964. r = -EINVAL;
  2965. if (!lapic_in_kernel(vcpu))
  2966. goto out;
  2967. u.lapic = memdup_user(argp, sizeof(*u.lapic));
  2968. if (IS_ERR(u.lapic))
  2969. return PTR_ERR(u.lapic);
  2970. r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
  2971. break;
  2972. }
  2973. case KVM_INTERRUPT: {
  2974. struct kvm_interrupt irq;
  2975. r = -EFAULT;
  2976. if (copy_from_user(&irq, argp, sizeof irq))
  2977. goto out;
  2978. r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
  2979. break;
  2980. }
  2981. case KVM_NMI: {
  2982. r = kvm_vcpu_ioctl_nmi(vcpu);
  2983. break;
  2984. }
  2985. case KVM_SMI: {
  2986. r = kvm_vcpu_ioctl_smi(vcpu);
  2987. break;
  2988. }
  2989. case KVM_SET_CPUID: {
  2990. struct kvm_cpuid __user *cpuid_arg = argp;
  2991. struct kvm_cpuid cpuid;
  2992. r = -EFAULT;
  2993. if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
  2994. goto out;
  2995. r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
  2996. break;
  2997. }
  2998. case KVM_SET_CPUID2: {
  2999. struct kvm_cpuid2 __user *cpuid_arg = argp;
  3000. struct kvm_cpuid2 cpuid;
  3001. r = -EFAULT;
  3002. if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
  3003. goto out;
  3004. r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
  3005. cpuid_arg->entries);
  3006. break;
  3007. }
  3008. case KVM_GET_CPUID2: {
  3009. struct kvm_cpuid2 __user *cpuid_arg = argp;
  3010. struct kvm_cpuid2 cpuid;
  3011. r = -EFAULT;
  3012. if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
  3013. goto out;
  3014. r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
  3015. cpuid_arg->entries);
  3016. if (r)
  3017. goto out;
  3018. r = -EFAULT;
  3019. if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
  3020. goto out;
  3021. r = 0;
  3022. break;
  3023. }
  3024. case KVM_GET_MSRS:
  3025. r = msr_io(vcpu, argp, do_get_msr, 1);
  3026. break;
  3027. case KVM_SET_MSRS:
  3028. r = msr_io(vcpu, argp, do_set_msr, 0);
  3029. break;
  3030. case KVM_TPR_ACCESS_REPORTING: {
  3031. struct kvm_tpr_access_ctl tac;
  3032. r = -EFAULT;
  3033. if (copy_from_user(&tac, argp, sizeof tac))
  3034. goto out;
  3035. r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
  3036. if (r)
  3037. goto out;
  3038. r = -EFAULT;
  3039. if (copy_to_user(argp, &tac, sizeof tac))
  3040. goto out;
  3041. r = 0;
  3042. break;
  3043. };
  3044. case KVM_SET_VAPIC_ADDR: {
  3045. struct kvm_vapic_addr va;
  3046. int idx;
  3047. r = -EINVAL;
  3048. if (!lapic_in_kernel(vcpu))
  3049. goto out;
  3050. r = -EFAULT;
  3051. if (copy_from_user(&va, argp, sizeof va))
  3052. goto out;
  3053. idx = srcu_read_lock(&vcpu->kvm->srcu);
  3054. r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
  3055. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  3056. break;
  3057. }
  3058. case KVM_X86_SETUP_MCE: {
  3059. u64 mcg_cap;
  3060. r = -EFAULT;
  3061. if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
  3062. goto out;
  3063. r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
  3064. break;
  3065. }
  3066. case KVM_X86_SET_MCE: {
  3067. struct kvm_x86_mce mce;
  3068. r = -EFAULT;
  3069. if (copy_from_user(&mce, argp, sizeof mce))
  3070. goto out;
  3071. r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
  3072. break;
  3073. }
  3074. case KVM_GET_VCPU_EVENTS: {
  3075. struct kvm_vcpu_events events;
  3076. kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
  3077. r = -EFAULT;
  3078. if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
  3079. break;
  3080. r = 0;
  3081. break;
  3082. }
  3083. case KVM_SET_VCPU_EVENTS: {
  3084. struct kvm_vcpu_events events;
  3085. r = -EFAULT;
  3086. if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
  3087. break;
  3088. r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
  3089. break;
  3090. }
  3091. case KVM_GET_DEBUGREGS: {
  3092. struct kvm_debugregs dbgregs;
  3093. kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
  3094. r = -EFAULT;
  3095. if (copy_to_user(argp, &dbgregs,
  3096. sizeof(struct kvm_debugregs)))
  3097. break;
  3098. r = 0;
  3099. break;
  3100. }
  3101. case KVM_SET_DEBUGREGS: {
  3102. struct kvm_debugregs dbgregs;
  3103. r = -EFAULT;
  3104. if (copy_from_user(&dbgregs, argp,
  3105. sizeof(struct kvm_debugregs)))
  3106. break;
  3107. r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
  3108. break;
  3109. }
  3110. case KVM_GET_XSAVE: {
  3111. u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
  3112. r = -ENOMEM;
  3113. if (!u.xsave)
  3114. break;
  3115. kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
  3116. r = -EFAULT;
  3117. if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
  3118. break;
  3119. r = 0;
  3120. break;
  3121. }
  3122. case KVM_SET_XSAVE: {
  3123. u.xsave = memdup_user(argp, sizeof(*u.xsave));
  3124. if (IS_ERR(u.xsave))
  3125. return PTR_ERR(u.xsave);
  3126. r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
  3127. break;
  3128. }
  3129. case KVM_GET_XCRS: {
  3130. u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
  3131. r = -ENOMEM;
  3132. if (!u.xcrs)
  3133. break;
  3134. kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
  3135. r = -EFAULT;
  3136. if (copy_to_user(argp, u.xcrs,
  3137. sizeof(struct kvm_xcrs)))
  3138. break;
  3139. r = 0;
  3140. break;
  3141. }
  3142. case KVM_SET_XCRS: {
  3143. u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
  3144. if (IS_ERR(u.xcrs))
  3145. return PTR_ERR(u.xcrs);
  3146. r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
  3147. break;
  3148. }
  3149. case KVM_SET_TSC_KHZ: {
  3150. u32 user_tsc_khz;
  3151. r = -EINVAL;
  3152. user_tsc_khz = (u32)arg;
  3153. if (user_tsc_khz >= kvm_max_guest_tsc_khz)
  3154. goto out;
  3155. if (user_tsc_khz == 0)
  3156. user_tsc_khz = tsc_khz;
  3157. if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
  3158. r = 0;
  3159. goto out;
  3160. }
  3161. case KVM_GET_TSC_KHZ: {
  3162. r = vcpu->arch.virtual_tsc_khz;
  3163. goto out;
  3164. }
  3165. case KVM_KVMCLOCK_CTRL: {
  3166. r = kvm_set_guest_paused(vcpu);
  3167. goto out;
  3168. }
  3169. case KVM_ENABLE_CAP: {
  3170. struct kvm_enable_cap cap;
  3171. r = -EFAULT;
  3172. if (copy_from_user(&cap, argp, sizeof(cap)))
  3173. goto out;
  3174. r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
  3175. break;
  3176. }
  3177. default:
  3178. r = -EINVAL;
  3179. }
  3180. out:
  3181. kfree(u.buffer);
  3182. return r;
  3183. }
  3184. int kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
  3185. {
  3186. return VM_FAULT_SIGBUS;
  3187. }
  3188. static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
  3189. {
  3190. int ret;
  3191. if (addr > (unsigned int)(-3 * PAGE_SIZE))
  3192. return -EINVAL;
  3193. ret = kvm_x86_ops->set_tss_addr(kvm, addr);
  3194. return ret;
  3195. }
  3196. static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
  3197. u64 ident_addr)
  3198. {
  3199. kvm->arch.ept_identity_map_addr = ident_addr;
  3200. return 0;
  3201. }
  3202. static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
  3203. u32 kvm_nr_mmu_pages)
  3204. {
  3205. if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
  3206. return -EINVAL;
  3207. mutex_lock(&kvm->slots_lock);
  3208. kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
  3209. kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
  3210. mutex_unlock(&kvm->slots_lock);
  3211. return 0;
  3212. }
  3213. static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
  3214. {
  3215. return kvm->arch.n_max_mmu_pages;
  3216. }
  3217. static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
  3218. {
  3219. struct kvm_pic *pic = kvm->arch.vpic;
  3220. int r;
  3221. r = 0;
  3222. switch (chip->chip_id) {
  3223. case KVM_IRQCHIP_PIC_MASTER:
  3224. memcpy(&chip->chip.pic, &pic->pics[0],
  3225. sizeof(struct kvm_pic_state));
  3226. break;
  3227. case KVM_IRQCHIP_PIC_SLAVE:
  3228. memcpy(&chip->chip.pic, &pic->pics[1],
  3229. sizeof(struct kvm_pic_state));
  3230. break;
  3231. case KVM_IRQCHIP_IOAPIC:
  3232. kvm_get_ioapic(kvm, &chip->chip.ioapic);
  3233. break;
  3234. default:
  3235. r = -EINVAL;
  3236. break;
  3237. }
  3238. return r;
  3239. }
  3240. static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
  3241. {
  3242. struct kvm_pic *pic = kvm->arch.vpic;
  3243. int r;
  3244. r = 0;
  3245. switch (chip->chip_id) {
  3246. case KVM_IRQCHIP_PIC_MASTER:
  3247. spin_lock(&pic->lock);
  3248. memcpy(&pic->pics[0], &chip->chip.pic,
  3249. sizeof(struct kvm_pic_state));
  3250. spin_unlock(&pic->lock);
  3251. break;
  3252. case KVM_IRQCHIP_PIC_SLAVE:
  3253. spin_lock(&pic->lock);
  3254. memcpy(&pic->pics[1], &chip->chip.pic,
  3255. sizeof(struct kvm_pic_state));
  3256. spin_unlock(&pic->lock);
  3257. break;
  3258. case KVM_IRQCHIP_IOAPIC:
  3259. kvm_set_ioapic(kvm, &chip->chip.ioapic);
  3260. break;
  3261. default:
  3262. r = -EINVAL;
  3263. break;
  3264. }
  3265. kvm_pic_update_irq(pic);
  3266. return r;
  3267. }
  3268. static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
  3269. {
  3270. struct kvm_kpit_state *kps = &kvm->arch.vpit->pit_state;
  3271. BUILD_BUG_ON(sizeof(*ps) != sizeof(kps->channels));
  3272. mutex_lock(&kps->lock);
  3273. memcpy(ps, &kps->channels, sizeof(*ps));
  3274. mutex_unlock(&kps->lock);
  3275. return 0;
  3276. }
  3277. static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
  3278. {
  3279. int i;
  3280. struct kvm_pit *pit = kvm->arch.vpit;
  3281. mutex_lock(&pit->pit_state.lock);
  3282. memcpy(&pit->pit_state.channels, ps, sizeof(*ps));
  3283. for (i = 0; i < 3; i++)
  3284. kvm_pit_load_count(pit, i, ps->channels[i].count, 0);
  3285. mutex_unlock(&pit->pit_state.lock);
  3286. return 0;
  3287. }
  3288. static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
  3289. {
  3290. mutex_lock(&kvm->arch.vpit->pit_state.lock);
  3291. memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
  3292. sizeof(ps->channels));
  3293. ps->flags = kvm->arch.vpit->pit_state.flags;
  3294. mutex_unlock(&kvm->arch.vpit->pit_state.lock);
  3295. memset(&ps->reserved, 0, sizeof(ps->reserved));
  3296. return 0;
  3297. }
  3298. static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
  3299. {
  3300. int start = 0;
  3301. int i;
  3302. u32 prev_legacy, cur_legacy;
  3303. struct kvm_pit *pit = kvm->arch.vpit;
  3304. mutex_lock(&pit->pit_state.lock);
  3305. prev_legacy = pit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
  3306. cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
  3307. if (!prev_legacy && cur_legacy)
  3308. start = 1;
  3309. memcpy(&pit->pit_state.channels, &ps->channels,
  3310. sizeof(pit->pit_state.channels));
  3311. pit->pit_state.flags = ps->flags;
  3312. for (i = 0; i < 3; i++)
  3313. kvm_pit_load_count(pit, i, pit->pit_state.channels[i].count,
  3314. start && i == 0);
  3315. mutex_unlock(&pit->pit_state.lock);
  3316. return 0;
  3317. }
  3318. static int kvm_vm_ioctl_reinject(struct kvm *kvm,
  3319. struct kvm_reinject_control *control)
  3320. {
  3321. struct kvm_pit *pit = kvm->arch.vpit;
  3322. if (!pit)
  3323. return -ENXIO;
  3324. /* pit->pit_state.lock was overloaded to prevent userspace from getting
  3325. * an inconsistent state after running multiple KVM_REINJECT_CONTROL
  3326. * ioctls in parallel. Use a separate lock if that ioctl isn't rare.
  3327. */
  3328. mutex_lock(&pit->pit_state.lock);
  3329. kvm_pit_set_reinject(pit, control->pit_reinject);
  3330. mutex_unlock(&pit->pit_state.lock);
  3331. return 0;
  3332. }
  3333. /**
  3334. * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
  3335. * @kvm: kvm instance
  3336. * @log: slot id and address to which we copy the log
  3337. *
  3338. * Steps 1-4 below provide general overview of dirty page logging. See
  3339. * kvm_get_dirty_log_protect() function description for additional details.
  3340. *
  3341. * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
  3342. * always flush the TLB (step 4) even if previous step failed and the dirty
  3343. * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
  3344. * does not preclude user space subsequent dirty log read. Flushing TLB ensures
  3345. * writes will be marked dirty for next log read.
  3346. *
  3347. * 1. Take a snapshot of the bit and clear it if needed.
  3348. * 2. Write protect the corresponding page.
  3349. * 3. Copy the snapshot to the userspace.
  3350. * 4. Flush TLB's if needed.
  3351. */
  3352. int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log)
  3353. {
  3354. bool is_dirty = false;
  3355. int r;
  3356. mutex_lock(&kvm->slots_lock);
  3357. /*
  3358. * Flush potentially hardware-cached dirty pages to dirty_bitmap.
  3359. */
  3360. if (kvm_x86_ops->flush_log_dirty)
  3361. kvm_x86_ops->flush_log_dirty(kvm);
  3362. r = kvm_get_dirty_log_protect(kvm, log, &is_dirty);
  3363. /*
  3364. * All the TLBs can be flushed out of mmu lock, see the comments in
  3365. * kvm_mmu_slot_remove_write_access().
  3366. */
  3367. lockdep_assert_held(&kvm->slots_lock);
  3368. if (is_dirty)
  3369. kvm_flush_remote_tlbs(kvm);
  3370. mutex_unlock(&kvm->slots_lock);
  3371. return r;
  3372. }
  3373. int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
  3374. bool line_status)
  3375. {
  3376. if (!irqchip_in_kernel(kvm))
  3377. return -ENXIO;
  3378. irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
  3379. irq_event->irq, irq_event->level,
  3380. line_status);
  3381. return 0;
  3382. }
  3383. static int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
  3384. struct kvm_enable_cap *cap)
  3385. {
  3386. int r;
  3387. if (cap->flags)
  3388. return -EINVAL;
  3389. switch (cap->cap) {
  3390. case KVM_CAP_DISABLE_QUIRKS:
  3391. kvm->arch.disabled_quirks = cap->args[0];
  3392. r = 0;
  3393. break;
  3394. case KVM_CAP_SPLIT_IRQCHIP: {
  3395. mutex_lock(&kvm->lock);
  3396. r = -EINVAL;
  3397. if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
  3398. goto split_irqchip_unlock;
  3399. r = -EEXIST;
  3400. if (irqchip_in_kernel(kvm))
  3401. goto split_irqchip_unlock;
  3402. if (kvm->created_vcpus)
  3403. goto split_irqchip_unlock;
  3404. r = kvm_setup_empty_irq_routing(kvm);
  3405. if (r)
  3406. goto split_irqchip_unlock;
  3407. /* Pairs with irqchip_in_kernel. */
  3408. smp_wmb();
  3409. kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
  3410. kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
  3411. r = 0;
  3412. split_irqchip_unlock:
  3413. mutex_unlock(&kvm->lock);
  3414. break;
  3415. }
  3416. case KVM_CAP_X2APIC_API:
  3417. r = -EINVAL;
  3418. if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
  3419. break;
  3420. if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
  3421. kvm->arch.x2apic_format = true;
  3422. if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
  3423. kvm->arch.x2apic_broadcast_quirk_disabled = true;
  3424. r = 0;
  3425. break;
  3426. default:
  3427. r = -EINVAL;
  3428. break;
  3429. }
  3430. return r;
  3431. }
  3432. long kvm_arch_vm_ioctl(struct file *filp,
  3433. unsigned int ioctl, unsigned long arg)
  3434. {
  3435. struct kvm *kvm = filp->private_data;
  3436. void __user *argp = (void __user *)arg;
  3437. int r = -ENOTTY;
  3438. /*
  3439. * This union makes it completely explicit to gcc-3.x
  3440. * that these two variables' stack usage should be
  3441. * combined, not added together.
  3442. */
  3443. union {
  3444. struct kvm_pit_state ps;
  3445. struct kvm_pit_state2 ps2;
  3446. struct kvm_pit_config pit_config;
  3447. } u;
  3448. switch (ioctl) {
  3449. case KVM_SET_TSS_ADDR:
  3450. r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
  3451. break;
  3452. case KVM_SET_IDENTITY_MAP_ADDR: {
  3453. u64 ident_addr;
  3454. r = -EFAULT;
  3455. if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
  3456. goto out;
  3457. r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
  3458. break;
  3459. }
  3460. case KVM_SET_NR_MMU_PAGES:
  3461. r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
  3462. break;
  3463. case KVM_GET_NR_MMU_PAGES:
  3464. r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
  3465. break;
  3466. case KVM_CREATE_IRQCHIP: {
  3467. mutex_lock(&kvm->lock);
  3468. r = -EEXIST;
  3469. if (irqchip_in_kernel(kvm))
  3470. goto create_irqchip_unlock;
  3471. r = -EINVAL;
  3472. if (kvm->created_vcpus)
  3473. goto create_irqchip_unlock;
  3474. r = kvm_pic_init(kvm);
  3475. if (r)
  3476. goto create_irqchip_unlock;
  3477. r = kvm_ioapic_init(kvm);
  3478. if (r) {
  3479. kvm_pic_destroy(kvm);
  3480. goto create_irqchip_unlock;
  3481. }
  3482. r = kvm_setup_default_irq_routing(kvm);
  3483. if (r) {
  3484. kvm_ioapic_destroy(kvm);
  3485. kvm_pic_destroy(kvm);
  3486. goto create_irqchip_unlock;
  3487. }
  3488. /* Write kvm->irq_routing before enabling irqchip_in_kernel. */
  3489. smp_wmb();
  3490. kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
  3491. create_irqchip_unlock:
  3492. mutex_unlock(&kvm->lock);
  3493. break;
  3494. }
  3495. case KVM_CREATE_PIT:
  3496. u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
  3497. goto create_pit;
  3498. case KVM_CREATE_PIT2:
  3499. r = -EFAULT;
  3500. if (copy_from_user(&u.pit_config, argp,
  3501. sizeof(struct kvm_pit_config)))
  3502. goto out;
  3503. create_pit:
  3504. mutex_lock(&kvm->lock);
  3505. r = -EEXIST;
  3506. if (kvm->arch.vpit)
  3507. goto create_pit_unlock;
  3508. r = -ENOMEM;
  3509. kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
  3510. if (kvm->arch.vpit)
  3511. r = 0;
  3512. create_pit_unlock:
  3513. mutex_unlock(&kvm->lock);
  3514. break;
  3515. case KVM_GET_IRQCHIP: {
  3516. /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
  3517. struct kvm_irqchip *chip;
  3518. chip = memdup_user(argp, sizeof(*chip));
  3519. if (IS_ERR(chip)) {
  3520. r = PTR_ERR(chip);
  3521. goto out;
  3522. }
  3523. r = -ENXIO;
  3524. if (!irqchip_kernel(kvm))
  3525. goto get_irqchip_out;
  3526. r = kvm_vm_ioctl_get_irqchip(kvm, chip);
  3527. if (r)
  3528. goto get_irqchip_out;
  3529. r = -EFAULT;
  3530. if (copy_to_user(argp, chip, sizeof *chip))
  3531. goto get_irqchip_out;
  3532. r = 0;
  3533. get_irqchip_out:
  3534. kfree(chip);
  3535. break;
  3536. }
  3537. case KVM_SET_IRQCHIP: {
  3538. /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
  3539. struct kvm_irqchip *chip;
  3540. chip = memdup_user(argp, sizeof(*chip));
  3541. if (IS_ERR(chip)) {
  3542. r = PTR_ERR(chip);
  3543. goto out;
  3544. }
  3545. r = -ENXIO;
  3546. if (!irqchip_kernel(kvm))
  3547. goto set_irqchip_out;
  3548. r = kvm_vm_ioctl_set_irqchip(kvm, chip);
  3549. if (r)
  3550. goto set_irqchip_out;
  3551. r = 0;
  3552. set_irqchip_out:
  3553. kfree(chip);
  3554. break;
  3555. }
  3556. case KVM_GET_PIT: {
  3557. r = -EFAULT;
  3558. if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
  3559. goto out;
  3560. r = -ENXIO;
  3561. if (!kvm->arch.vpit)
  3562. goto out;
  3563. r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
  3564. if (r)
  3565. goto out;
  3566. r = -EFAULT;
  3567. if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
  3568. goto out;
  3569. r = 0;
  3570. break;
  3571. }
  3572. case KVM_SET_PIT: {
  3573. r = -EFAULT;
  3574. if (copy_from_user(&u.ps, argp, sizeof u.ps))
  3575. goto out;
  3576. r = -ENXIO;
  3577. if (!kvm->arch.vpit)
  3578. goto out;
  3579. r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
  3580. break;
  3581. }
  3582. case KVM_GET_PIT2: {
  3583. r = -ENXIO;
  3584. if (!kvm->arch.vpit)
  3585. goto out;
  3586. r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
  3587. if (r)
  3588. goto out;
  3589. r = -EFAULT;
  3590. if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
  3591. goto out;
  3592. r = 0;
  3593. break;
  3594. }
  3595. case KVM_SET_PIT2: {
  3596. r = -EFAULT;
  3597. if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
  3598. goto out;
  3599. r = -ENXIO;
  3600. if (!kvm->arch.vpit)
  3601. goto out;
  3602. r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
  3603. break;
  3604. }
  3605. case KVM_REINJECT_CONTROL: {
  3606. struct kvm_reinject_control control;
  3607. r = -EFAULT;
  3608. if (copy_from_user(&control, argp, sizeof(control)))
  3609. goto out;
  3610. r = kvm_vm_ioctl_reinject(kvm, &control);
  3611. break;
  3612. }
  3613. case KVM_SET_BOOT_CPU_ID:
  3614. r = 0;
  3615. mutex_lock(&kvm->lock);
  3616. if (kvm->created_vcpus)
  3617. r = -EBUSY;
  3618. else
  3619. kvm->arch.bsp_vcpu_id = arg;
  3620. mutex_unlock(&kvm->lock);
  3621. break;
  3622. case KVM_XEN_HVM_CONFIG: {
  3623. r = -EFAULT;
  3624. if (copy_from_user(&kvm->arch.xen_hvm_config, argp,
  3625. sizeof(struct kvm_xen_hvm_config)))
  3626. goto out;
  3627. r = -EINVAL;
  3628. if (kvm->arch.xen_hvm_config.flags)
  3629. goto out;
  3630. r = 0;
  3631. break;
  3632. }
  3633. case KVM_SET_CLOCK: {
  3634. struct kvm_clock_data user_ns;
  3635. u64 now_ns;
  3636. r = -EFAULT;
  3637. if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
  3638. goto out;
  3639. r = -EINVAL;
  3640. if (user_ns.flags)
  3641. goto out;
  3642. r = 0;
  3643. now_ns = get_kvmclock_ns(kvm);
  3644. kvm->arch.kvmclock_offset += user_ns.clock - now_ns;
  3645. kvm_gen_update_masterclock(kvm);
  3646. break;
  3647. }
  3648. case KVM_GET_CLOCK: {
  3649. struct kvm_clock_data user_ns;
  3650. u64 now_ns;
  3651. now_ns = get_kvmclock_ns(kvm);
  3652. user_ns.clock = now_ns;
  3653. user_ns.flags = kvm->arch.use_master_clock ? KVM_CLOCK_TSC_STABLE : 0;
  3654. memset(&user_ns.pad, 0, sizeof(user_ns.pad));
  3655. r = -EFAULT;
  3656. if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
  3657. goto out;
  3658. r = 0;
  3659. break;
  3660. }
  3661. case KVM_ENABLE_CAP: {
  3662. struct kvm_enable_cap cap;
  3663. r = -EFAULT;
  3664. if (copy_from_user(&cap, argp, sizeof(cap)))
  3665. goto out;
  3666. r = kvm_vm_ioctl_enable_cap(kvm, &cap);
  3667. break;
  3668. }
  3669. default:
  3670. r = -ENOTTY;
  3671. }
  3672. out:
  3673. return r;
  3674. }
  3675. static void kvm_init_msr_list(void)
  3676. {
  3677. u32 dummy[2];
  3678. unsigned i, j;
  3679. for (i = j = 0; i < ARRAY_SIZE(msrs_to_save); i++) {
  3680. if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
  3681. continue;
  3682. /*
  3683. * Even MSRs that are valid in the host may not be exposed
  3684. * to the guests in some cases.
  3685. */
  3686. switch (msrs_to_save[i]) {
  3687. case MSR_IA32_BNDCFGS:
  3688. if (!kvm_x86_ops->mpx_supported())
  3689. continue;
  3690. break;
  3691. case MSR_TSC_AUX:
  3692. if (!kvm_x86_ops->rdtscp_supported())
  3693. continue;
  3694. break;
  3695. default:
  3696. break;
  3697. }
  3698. if (j < i)
  3699. msrs_to_save[j] = msrs_to_save[i];
  3700. j++;
  3701. }
  3702. num_msrs_to_save = j;
  3703. for (i = j = 0; i < ARRAY_SIZE(emulated_msrs); i++) {
  3704. switch (emulated_msrs[i]) {
  3705. case MSR_IA32_SMBASE:
  3706. if (!kvm_x86_ops->cpu_has_high_real_mode_segbase())
  3707. continue;
  3708. break;
  3709. default:
  3710. break;
  3711. }
  3712. if (j < i)
  3713. emulated_msrs[j] = emulated_msrs[i];
  3714. j++;
  3715. }
  3716. num_emulated_msrs = j;
  3717. }
  3718. static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
  3719. const void *v)
  3720. {
  3721. int handled = 0;
  3722. int n;
  3723. do {
  3724. n = min(len, 8);
  3725. if (!(lapic_in_kernel(vcpu) &&
  3726. !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
  3727. && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
  3728. break;
  3729. handled += n;
  3730. addr += n;
  3731. len -= n;
  3732. v += n;
  3733. } while (len);
  3734. return handled;
  3735. }
  3736. static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
  3737. {
  3738. int handled = 0;
  3739. int n;
  3740. do {
  3741. n = min(len, 8);
  3742. if (!(lapic_in_kernel(vcpu) &&
  3743. !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
  3744. addr, n, v))
  3745. && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
  3746. break;
  3747. trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, *(u64 *)v);
  3748. handled += n;
  3749. addr += n;
  3750. len -= n;
  3751. v += n;
  3752. } while (len);
  3753. return handled;
  3754. }
  3755. static void kvm_set_segment(struct kvm_vcpu *vcpu,
  3756. struct kvm_segment *var, int seg)
  3757. {
  3758. kvm_x86_ops->set_segment(vcpu, var, seg);
  3759. }
  3760. void kvm_get_segment(struct kvm_vcpu *vcpu,
  3761. struct kvm_segment *var, int seg)
  3762. {
  3763. kvm_x86_ops->get_segment(vcpu, var, seg);
  3764. }
  3765. gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
  3766. struct x86_exception *exception)
  3767. {
  3768. gpa_t t_gpa;
  3769. BUG_ON(!mmu_is_nested(vcpu));
  3770. /* NPT walks are always user-walks */
  3771. access |= PFERR_USER_MASK;
  3772. t_gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gpa, access, exception);
  3773. return t_gpa;
  3774. }
  3775. gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
  3776. struct x86_exception *exception)
  3777. {
  3778. u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
  3779. return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
  3780. }
  3781. gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
  3782. struct x86_exception *exception)
  3783. {
  3784. u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
  3785. access |= PFERR_FETCH_MASK;
  3786. return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
  3787. }
  3788. gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
  3789. struct x86_exception *exception)
  3790. {
  3791. u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
  3792. access |= PFERR_WRITE_MASK;
  3793. return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
  3794. }
  3795. /* uses this to access any guest's mapped memory without checking CPL */
  3796. gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
  3797. struct x86_exception *exception)
  3798. {
  3799. return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
  3800. }
  3801. static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
  3802. struct kvm_vcpu *vcpu, u32 access,
  3803. struct x86_exception *exception)
  3804. {
  3805. void *data = val;
  3806. int r = X86EMUL_CONTINUE;
  3807. while (bytes) {
  3808. gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
  3809. exception);
  3810. unsigned offset = addr & (PAGE_SIZE-1);
  3811. unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
  3812. int ret;
  3813. if (gpa == UNMAPPED_GVA)
  3814. return X86EMUL_PROPAGATE_FAULT;
  3815. ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
  3816. offset, toread);
  3817. if (ret < 0) {
  3818. r = X86EMUL_IO_NEEDED;
  3819. goto out;
  3820. }
  3821. bytes -= toread;
  3822. data += toread;
  3823. addr += toread;
  3824. }
  3825. out:
  3826. return r;
  3827. }
  3828. /* used for instruction fetching */
  3829. static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
  3830. gva_t addr, void *val, unsigned int bytes,
  3831. struct x86_exception *exception)
  3832. {
  3833. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  3834. u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
  3835. unsigned offset;
  3836. int ret;
  3837. /* Inline kvm_read_guest_virt_helper for speed. */
  3838. gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access|PFERR_FETCH_MASK,
  3839. exception);
  3840. if (unlikely(gpa == UNMAPPED_GVA))
  3841. return X86EMUL_PROPAGATE_FAULT;
  3842. offset = addr & (PAGE_SIZE-1);
  3843. if (WARN_ON(offset + bytes > PAGE_SIZE))
  3844. bytes = (unsigned)PAGE_SIZE - offset;
  3845. ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
  3846. offset, bytes);
  3847. if (unlikely(ret < 0))
  3848. return X86EMUL_IO_NEEDED;
  3849. return X86EMUL_CONTINUE;
  3850. }
  3851. int kvm_read_guest_virt(struct x86_emulate_ctxt *ctxt,
  3852. gva_t addr, void *val, unsigned int bytes,
  3853. struct x86_exception *exception)
  3854. {
  3855. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  3856. u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
  3857. return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
  3858. exception);
  3859. }
  3860. EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
  3861. static int kvm_read_guest_virt_system(struct x86_emulate_ctxt *ctxt,
  3862. gva_t addr, void *val, unsigned int bytes,
  3863. struct x86_exception *exception)
  3864. {
  3865. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  3866. return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, 0, exception);
  3867. }
  3868. static int kvm_read_guest_phys_system(struct x86_emulate_ctxt *ctxt,
  3869. unsigned long addr, void *val, unsigned int bytes)
  3870. {
  3871. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  3872. int r = kvm_vcpu_read_guest(vcpu, addr, val, bytes);
  3873. return r < 0 ? X86EMUL_IO_NEEDED : X86EMUL_CONTINUE;
  3874. }
  3875. int kvm_write_guest_virt_system(struct x86_emulate_ctxt *ctxt,
  3876. gva_t addr, void *val,
  3877. unsigned int bytes,
  3878. struct x86_exception *exception)
  3879. {
  3880. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  3881. void *data = val;
  3882. int r = X86EMUL_CONTINUE;
  3883. while (bytes) {
  3884. gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
  3885. PFERR_WRITE_MASK,
  3886. exception);
  3887. unsigned offset = addr & (PAGE_SIZE-1);
  3888. unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
  3889. int ret;
  3890. if (gpa == UNMAPPED_GVA)
  3891. return X86EMUL_PROPAGATE_FAULT;
  3892. ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
  3893. if (ret < 0) {
  3894. r = X86EMUL_IO_NEEDED;
  3895. goto out;
  3896. }
  3897. bytes -= towrite;
  3898. data += towrite;
  3899. addr += towrite;
  3900. }
  3901. out:
  3902. return r;
  3903. }
  3904. EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
  3905. static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
  3906. gpa_t gpa, bool write)
  3907. {
  3908. /* For APIC access vmexit */
  3909. if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
  3910. return 1;
  3911. if (vcpu_match_mmio_gpa(vcpu, gpa)) {
  3912. trace_vcpu_match_mmio(gva, gpa, write, true);
  3913. return 1;
  3914. }
  3915. return 0;
  3916. }
  3917. static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
  3918. gpa_t *gpa, struct x86_exception *exception,
  3919. bool write)
  3920. {
  3921. u32 access = ((kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0)
  3922. | (write ? PFERR_WRITE_MASK : 0);
  3923. /*
  3924. * currently PKRU is only applied to ept enabled guest so
  3925. * there is no pkey in EPT page table for L1 guest or EPT
  3926. * shadow page table for L2 guest.
  3927. */
  3928. if (vcpu_match_mmio_gva(vcpu, gva)
  3929. && !permission_fault(vcpu, vcpu->arch.walk_mmu,
  3930. vcpu->arch.access, 0, access)) {
  3931. *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
  3932. (gva & (PAGE_SIZE - 1));
  3933. trace_vcpu_match_mmio(gva, *gpa, write, false);
  3934. return 1;
  3935. }
  3936. *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
  3937. if (*gpa == UNMAPPED_GVA)
  3938. return -1;
  3939. return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
  3940. }
  3941. int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
  3942. const void *val, int bytes)
  3943. {
  3944. int ret;
  3945. ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
  3946. if (ret < 0)
  3947. return 0;
  3948. kvm_page_track_write(vcpu, gpa, val, bytes);
  3949. return 1;
  3950. }
  3951. struct read_write_emulator_ops {
  3952. int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
  3953. int bytes);
  3954. int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
  3955. void *val, int bytes);
  3956. int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
  3957. int bytes, void *val);
  3958. int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
  3959. void *val, int bytes);
  3960. bool write;
  3961. };
  3962. static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
  3963. {
  3964. if (vcpu->mmio_read_completed) {
  3965. trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
  3966. vcpu->mmio_fragments[0].gpa, *(u64 *)val);
  3967. vcpu->mmio_read_completed = 0;
  3968. return 1;
  3969. }
  3970. return 0;
  3971. }
  3972. static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
  3973. void *val, int bytes)
  3974. {
  3975. return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
  3976. }
  3977. static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
  3978. void *val, int bytes)
  3979. {
  3980. return emulator_write_phys(vcpu, gpa, val, bytes);
  3981. }
  3982. static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
  3983. {
  3984. trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, *(u64 *)val);
  3985. return vcpu_mmio_write(vcpu, gpa, bytes, val);
  3986. }
  3987. static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
  3988. void *val, int bytes)
  3989. {
  3990. trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, 0);
  3991. return X86EMUL_IO_NEEDED;
  3992. }
  3993. static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
  3994. void *val, int bytes)
  3995. {
  3996. struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
  3997. memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
  3998. return X86EMUL_CONTINUE;
  3999. }
  4000. static const struct read_write_emulator_ops read_emultor = {
  4001. .read_write_prepare = read_prepare,
  4002. .read_write_emulate = read_emulate,
  4003. .read_write_mmio = vcpu_mmio_read,
  4004. .read_write_exit_mmio = read_exit_mmio,
  4005. };
  4006. static const struct read_write_emulator_ops write_emultor = {
  4007. .read_write_emulate = write_emulate,
  4008. .read_write_mmio = write_mmio,
  4009. .read_write_exit_mmio = write_exit_mmio,
  4010. .write = true,
  4011. };
  4012. static int emulator_read_write_onepage(unsigned long addr, void *val,
  4013. unsigned int bytes,
  4014. struct x86_exception *exception,
  4015. struct kvm_vcpu *vcpu,
  4016. const struct read_write_emulator_ops *ops)
  4017. {
  4018. gpa_t gpa;
  4019. int handled, ret;
  4020. bool write = ops->write;
  4021. struct kvm_mmio_fragment *frag;
  4022. struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
  4023. /*
  4024. * If the exit was due to a NPF we may already have a GPA.
  4025. * If the GPA is present, use it to avoid the GVA to GPA table walk.
  4026. * Note, this cannot be used on string operations since string
  4027. * operation using rep will only have the initial GPA from the NPF
  4028. * occurred.
  4029. */
  4030. if (vcpu->arch.gpa_available &&
  4031. emulator_can_use_gpa(ctxt) &&
  4032. vcpu_is_mmio_gpa(vcpu, addr, exception->address, write) &&
  4033. (addr & ~PAGE_MASK) == (exception->address & ~PAGE_MASK)) {
  4034. gpa = exception->address;
  4035. goto mmio;
  4036. }
  4037. ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
  4038. if (ret < 0)
  4039. return X86EMUL_PROPAGATE_FAULT;
  4040. /* For APIC access vmexit */
  4041. if (ret)
  4042. goto mmio;
  4043. if (ops->read_write_emulate(vcpu, gpa, val, bytes))
  4044. return X86EMUL_CONTINUE;
  4045. mmio:
  4046. /*
  4047. * Is this MMIO handled locally?
  4048. */
  4049. handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
  4050. if (handled == bytes)
  4051. return X86EMUL_CONTINUE;
  4052. gpa += handled;
  4053. bytes -= handled;
  4054. val += handled;
  4055. WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
  4056. frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
  4057. frag->gpa = gpa;
  4058. frag->data = val;
  4059. frag->len = bytes;
  4060. return X86EMUL_CONTINUE;
  4061. }
  4062. static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
  4063. unsigned long addr,
  4064. void *val, unsigned int bytes,
  4065. struct x86_exception *exception,
  4066. const struct read_write_emulator_ops *ops)
  4067. {
  4068. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  4069. gpa_t gpa;
  4070. int rc;
  4071. if (ops->read_write_prepare &&
  4072. ops->read_write_prepare(vcpu, val, bytes))
  4073. return X86EMUL_CONTINUE;
  4074. vcpu->mmio_nr_fragments = 0;
  4075. /* Crossing a page boundary? */
  4076. if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
  4077. int now;
  4078. now = -addr & ~PAGE_MASK;
  4079. rc = emulator_read_write_onepage(addr, val, now, exception,
  4080. vcpu, ops);
  4081. if (rc != X86EMUL_CONTINUE)
  4082. return rc;
  4083. addr += now;
  4084. if (ctxt->mode != X86EMUL_MODE_PROT64)
  4085. addr = (u32)addr;
  4086. val += now;
  4087. bytes -= now;
  4088. }
  4089. rc = emulator_read_write_onepage(addr, val, bytes, exception,
  4090. vcpu, ops);
  4091. if (rc != X86EMUL_CONTINUE)
  4092. return rc;
  4093. if (!vcpu->mmio_nr_fragments)
  4094. return rc;
  4095. gpa = vcpu->mmio_fragments[0].gpa;
  4096. vcpu->mmio_needed = 1;
  4097. vcpu->mmio_cur_fragment = 0;
  4098. vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
  4099. vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
  4100. vcpu->run->exit_reason = KVM_EXIT_MMIO;
  4101. vcpu->run->mmio.phys_addr = gpa;
  4102. return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
  4103. }
  4104. static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
  4105. unsigned long addr,
  4106. void *val,
  4107. unsigned int bytes,
  4108. struct x86_exception *exception)
  4109. {
  4110. return emulator_read_write(ctxt, addr, val, bytes,
  4111. exception, &read_emultor);
  4112. }
  4113. static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
  4114. unsigned long addr,
  4115. const void *val,
  4116. unsigned int bytes,
  4117. struct x86_exception *exception)
  4118. {
  4119. return emulator_read_write(ctxt, addr, (void *)val, bytes,
  4120. exception, &write_emultor);
  4121. }
  4122. #define CMPXCHG_TYPE(t, ptr, old, new) \
  4123. (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
  4124. #ifdef CONFIG_X86_64
  4125. # define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
  4126. #else
  4127. # define CMPXCHG64(ptr, old, new) \
  4128. (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
  4129. #endif
  4130. static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
  4131. unsigned long addr,
  4132. const void *old,
  4133. const void *new,
  4134. unsigned int bytes,
  4135. struct x86_exception *exception)
  4136. {
  4137. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  4138. gpa_t gpa;
  4139. struct page *page;
  4140. char *kaddr;
  4141. bool exchanged;
  4142. /* guests cmpxchg8b have to be emulated atomically */
  4143. if (bytes > 8 || (bytes & (bytes - 1)))
  4144. goto emul_write;
  4145. gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
  4146. if (gpa == UNMAPPED_GVA ||
  4147. (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
  4148. goto emul_write;
  4149. if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
  4150. goto emul_write;
  4151. page = kvm_vcpu_gfn_to_page(vcpu, gpa >> PAGE_SHIFT);
  4152. if (is_error_page(page))
  4153. goto emul_write;
  4154. kaddr = kmap_atomic(page);
  4155. kaddr += offset_in_page(gpa);
  4156. switch (bytes) {
  4157. case 1:
  4158. exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
  4159. break;
  4160. case 2:
  4161. exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
  4162. break;
  4163. case 4:
  4164. exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
  4165. break;
  4166. case 8:
  4167. exchanged = CMPXCHG64(kaddr, old, new);
  4168. break;
  4169. default:
  4170. BUG();
  4171. }
  4172. kunmap_atomic(kaddr);
  4173. kvm_release_page_dirty(page);
  4174. if (!exchanged)
  4175. return X86EMUL_CMPXCHG_FAILED;
  4176. kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
  4177. kvm_page_track_write(vcpu, gpa, new, bytes);
  4178. return X86EMUL_CONTINUE;
  4179. emul_write:
  4180. printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
  4181. return emulator_write_emulated(ctxt, addr, new, bytes, exception);
  4182. }
  4183. static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
  4184. {
  4185. int r = 0, i;
  4186. for (i = 0; i < vcpu->arch.pio.count; i++) {
  4187. if (vcpu->arch.pio.in)
  4188. r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, vcpu->arch.pio.port,
  4189. vcpu->arch.pio.size, pd);
  4190. else
  4191. r = kvm_io_bus_write(vcpu, KVM_PIO_BUS,
  4192. vcpu->arch.pio.port, vcpu->arch.pio.size,
  4193. pd);
  4194. if (r)
  4195. break;
  4196. pd += vcpu->arch.pio.size;
  4197. }
  4198. return r;
  4199. }
  4200. static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
  4201. unsigned short port, void *val,
  4202. unsigned int count, bool in)
  4203. {
  4204. vcpu->arch.pio.port = port;
  4205. vcpu->arch.pio.in = in;
  4206. vcpu->arch.pio.count = count;
  4207. vcpu->arch.pio.size = size;
  4208. if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
  4209. vcpu->arch.pio.count = 0;
  4210. return 1;
  4211. }
  4212. vcpu->run->exit_reason = KVM_EXIT_IO;
  4213. vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
  4214. vcpu->run->io.size = size;
  4215. vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
  4216. vcpu->run->io.count = count;
  4217. vcpu->run->io.port = port;
  4218. return 0;
  4219. }
  4220. static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
  4221. int size, unsigned short port, void *val,
  4222. unsigned int count)
  4223. {
  4224. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  4225. int ret;
  4226. if (vcpu->arch.pio.count)
  4227. goto data_avail;
  4228. memset(vcpu->arch.pio_data, 0, size * count);
  4229. ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
  4230. if (ret) {
  4231. data_avail:
  4232. memcpy(val, vcpu->arch.pio_data, size * count);
  4233. trace_kvm_pio(KVM_PIO_IN, port, size, count, vcpu->arch.pio_data);
  4234. vcpu->arch.pio.count = 0;
  4235. return 1;
  4236. }
  4237. return 0;
  4238. }
  4239. static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
  4240. int size, unsigned short port,
  4241. const void *val, unsigned int count)
  4242. {
  4243. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  4244. memcpy(vcpu->arch.pio_data, val, size * count);
  4245. trace_kvm_pio(KVM_PIO_OUT, port, size, count, vcpu->arch.pio_data);
  4246. return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
  4247. }
  4248. static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
  4249. {
  4250. return kvm_x86_ops->get_segment_base(vcpu, seg);
  4251. }
  4252. static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
  4253. {
  4254. kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
  4255. }
  4256. static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
  4257. {
  4258. if (!need_emulate_wbinvd(vcpu))
  4259. return X86EMUL_CONTINUE;
  4260. if (kvm_x86_ops->has_wbinvd_exit()) {
  4261. int cpu = get_cpu();
  4262. cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
  4263. smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
  4264. wbinvd_ipi, NULL, 1);
  4265. put_cpu();
  4266. cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
  4267. } else
  4268. wbinvd();
  4269. return X86EMUL_CONTINUE;
  4270. }
  4271. int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
  4272. {
  4273. kvm_emulate_wbinvd_noskip(vcpu);
  4274. return kvm_skip_emulated_instruction(vcpu);
  4275. }
  4276. EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
  4277. static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
  4278. {
  4279. kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
  4280. }
  4281. static int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr,
  4282. unsigned long *dest)
  4283. {
  4284. return kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
  4285. }
  4286. static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
  4287. unsigned long value)
  4288. {
  4289. return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
  4290. }
  4291. static u64 mk_cr_64(u64 curr_cr, u32 new_val)
  4292. {
  4293. return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
  4294. }
  4295. static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
  4296. {
  4297. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  4298. unsigned long value;
  4299. switch (cr) {
  4300. case 0:
  4301. value = kvm_read_cr0(vcpu);
  4302. break;
  4303. case 2:
  4304. value = vcpu->arch.cr2;
  4305. break;
  4306. case 3:
  4307. value = kvm_read_cr3(vcpu);
  4308. break;
  4309. case 4:
  4310. value = kvm_read_cr4(vcpu);
  4311. break;
  4312. case 8:
  4313. value = kvm_get_cr8(vcpu);
  4314. break;
  4315. default:
  4316. kvm_err("%s: unexpected cr %u\n", __func__, cr);
  4317. return 0;
  4318. }
  4319. return value;
  4320. }
  4321. static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
  4322. {
  4323. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  4324. int res = 0;
  4325. switch (cr) {
  4326. case 0:
  4327. res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
  4328. break;
  4329. case 2:
  4330. vcpu->arch.cr2 = val;
  4331. break;
  4332. case 3:
  4333. res = kvm_set_cr3(vcpu, val);
  4334. break;
  4335. case 4:
  4336. res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
  4337. break;
  4338. case 8:
  4339. res = kvm_set_cr8(vcpu, val);
  4340. break;
  4341. default:
  4342. kvm_err("%s: unexpected cr %u\n", __func__, cr);
  4343. res = -1;
  4344. }
  4345. return res;
  4346. }
  4347. static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
  4348. {
  4349. return kvm_x86_ops->get_cpl(emul_to_vcpu(ctxt));
  4350. }
  4351. static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
  4352. {
  4353. kvm_x86_ops->get_gdt(emul_to_vcpu(ctxt), dt);
  4354. }
  4355. static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
  4356. {
  4357. kvm_x86_ops->get_idt(emul_to_vcpu(ctxt), dt);
  4358. }
  4359. static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
  4360. {
  4361. kvm_x86_ops->set_gdt(emul_to_vcpu(ctxt), dt);
  4362. }
  4363. static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
  4364. {
  4365. kvm_x86_ops->set_idt(emul_to_vcpu(ctxt), dt);
  4366. }
  4367. static unsigned long emulator_get_cached_segment_base(
  4368. struct x86_emulate_ctxt *ctxt, int seg)
  4369. {
  4370. return get_segment_base(emul_to_vcpu(ctxt), seg);
  4371. }
  4372. static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
  4373. struct desc_struct *desc, u32 *base3,
  4374. int seg)
  4375. {
  4376. struct kvm_segment var;
  4377. kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
  4378. *selector = var.selector;
  4379. if (var.unusable) {
  4380. memset(desc, 0, sizeof(*desc));
  4381. if (base3)
  4382. *base3 = 0;
  4383. return false;
  4384. }
  4385. if (var.g)
  4386. var.limit >>= 12;
  4387. set_desc_limit(desc, var.limit);
  4388. set_desc_base(desc, (unsigned long)var.base);
  4389. #ifdef CONFIG_X86_64
  4390. if (base3)
  4391. *base3 = var.base >> 32;
  4392. #endif
  4393. desc->type = var.type;
  4394. desc->s = var.s;
  4395. desc->dpl = var.dpl;
  4396. desc->p = var.present;
  4397. desc->avl = var.avl;
  4398. desc->l = var.l;
  4399. desc->d = var.db;
  4400. desc->g = var.g;
  4401. return true;
  4402. }
  4403. static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
  4404. struct desc_struct *desc, u32 base3,
  4405. int seg)
  4406. {
  4407. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  4408. struct kvm_segment var;
  4409. var.selector = selector;
  4410. var.base = get_desc_base(desc);
  4411. #ifdef CONFIG_X86_64
  4412. var.base |= ((u64)base3) << 32;
  4413. #endif
  4414. var.limit = get_desc_limit(desc);
  4415. if (desc->g)
  4416. var.limit = (var.limit << 12) | 0xfff;
  4417. var.type = desc->type;
  4418. var.dpl = desc->dpl;
  4419. var.db = desc->d;
  4420. var.s = desc->s;
  4421. var.l = desc->l;
  4422. var.g = desc->g;
  4423. var.avl = desc->avl;
  4424. var.present = desc->p;
  4425. var.unusable = !var.present;
  4426. var.padding = 0;
  4427. kvm_set_segment(vcpu, &var, seg);
  4428. return;
  4429. }
  4430. static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
  4431. u32 msr_index, u64 *pdata)
  4432. {
  4433. struct msr_data msr;
  4434. int r;
  4435. msr.index = msr_index;
  4436. msr.host_initiated = false;
  4437. r = kvm_get_msr(emul_to_vcpu(ctxt), &msr);
  4438. if (r)
  4439. return r;
  4440. *pdata = msr.data;
  4441. return 0;
  4442. }
  4443. static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
  4444. u32 msr_index, u64 data)
  4445. {
  4446. struct msr_data msr;
  4447. msr.data = data;
  4448. msr.index = msr_index;
  4449. msr.host_initiated = false;
  4450. return kvm_set_msr(emul_to_vcpu(ctxt), &msr);
  4451. }
  4452. static u64 emulator_get_smbase(struct x86_emulate_ctxt *ctxt)
  4453. {
  4454. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  4455. return vcpu->arch.smbase;
  4456. }
  4457. static void emulator_set_smbase(struct x86_emulate_ctxt *ctxt, u64 smbase)
  4458. {
  4459. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  4460. vcpu->arch.smbase = smbase;
  4461. }
  4462. static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
  4463. u32 pmc)
  4464. {
  4465. return kvm_pmu_is_valid_msr_idx(emul_to_vcpu(ctxt), pmc);
  4466. }
  4467. static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
  4468. u32 pmc, u64 *pdata)
  4469. {
  4470. return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
  4471. }
  4472. static void emulator_halt(struct x86_emulate_ctxt *ctxt)
  4473. {
  4474. emul_to_vcpu(ctxt)->arch.halt_request = 1;
  4475. }
  4476. static void emulator_get_fpu(struct x86_emulate_ctxt *ctxt)
  4477. {
  4478. preempt_disable();
  4479. kvm_load_guest_fpu(emul_to_vcpu(ctxt));
  4480. }
  4481. static void emulator_put_fpu(struct x86_emulate_ctxt *ctxt)
  4482. {
  4483. preempt_enable();
  4484. }
  4485. static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
  4486. struct x86_instruction_info *info,
  4487. enum x86_intercept_stage stage)
  4488. {
  4489. return kvm_x86_ops->check_intercept(emul_to_vcpu(ctxt), info, stage);
  4490. }
  4491. static void emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
  4492. u32 *eax, u32 *ebx, u32 *ecx, u32 *edx)
  4493. {
  4494. kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx);
  4495. }
  4496. static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
  4497. {
  4498. return kvm_register_read(emul_to_vcpu(ctxt), reg);
  4499. }
  4500. static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
  4501. {
  4502. kvm_register_write(emul_to_vcpu(ctxt), reg, val);
  4503. }
  4504. static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
  4505. {
  4506. kvm_x86_ops->set_nmi_mask(emul_to_vcpu(ctxt), masked);
  4507. }
  4508. static unsigned emulator_get_hflags(struct x86_emulate_ctxt *ctxt)
  4509. {
  4510. return emul_to_vcpu(ctxt)->arch.hflags;
  4511. }
  4512. static void emulator_set_hflags(struct x86_emulate_ctxt *ctxt, unsigned emul_flags)
  4513. {
  4514. kvm_set_hflags(emul_to_vcpu(ctxt), emul_flags);
  4515. }
  4516. static const struct x86_emulate_ops emulate_ops = {
  4517. .read_gpr = emulator_read_gpr,
  4518. .write_gpr = emulator_write_gpr,
  4519. .read_std = kvm_read_guest_virt_system,
  4520. .write_std = kvm_write_guest_virt_system,
  4521. .read_phys = kvm_read_guest_phys_system,
  4522. .fetch = kvm_fetch_guest_virt,
  4523. .read_emulated = emulator_read_emulated,
  4524. .write_emulated = emulator_write_emulated,
  4525. .cmpxchg_emulated = emulator_cmpxchg_emulated,
  4526. .invlpg = emulator_invlpg,
  4527. .pio_in_emulated = emulator_pio_in_emulated,
  4528. .pio_out_emulated = emulator_pio_out_emulated,
  4529. .get_segment = emulator_get_segment,
  4530. .set_segment = emulator_set_segment,
  4531. .get_cached_segment_base = emulator_get_cached_segment_base,
  4532. .get_gdt = emulator_get_gdt,
  4533. .get_idt = emulator_get_idt,
  4534. .set_gdt = emulator_set_gdt,
  4535. .set_idt = emulator_set_idt,
  4536. .get_cr = emulator_get_cr,
  4537. .set_cr = emulator_set_cr,
  4538. .cpl = emulator_get_cpl,
  4539. .get_dr = emulator_get_dr,
  4540. .set_dr = emulator_set_dr,
  4541. .get_smbase = emulator_get_smbase,
  4542. .set_smbase = emulator_set_smbase,
  4543. .set_msr = emulator_set_msr,
  4544. .get_msr = emulator_get_msr,
  4545. .check_pmc = emulator_check_pmc,
  4546. .read_pmc = emulator_read_pmc,
  4547. .halt = emulator_halt,
  4548. .wbinvd = emulator_wbinvd,
  4549. .fix_hypercall = emulator_fix_hypercall,
  4550. .get_fpu = emulator_get_fpu,
  4551. .put_fpu = emulator_put_fpu,
  4552. .intercept = emulator_intercept,
  4553. .get_cpuid = emulator_get_cpuid,
  4554. .set_nmi_mask = emulator_set_nmi_mask,
  4555. .get_hflags = emulator_get_hflags,
  4556. .set_hflags = emulator_set_hflags,
  4557. };
  4558. static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
  4559. {
  4560. u32 int_shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
  4561. /*
  4562. * an sti; sti; sequence only disable interrupts for the first
  4563. * instruction. So, if the last instruction, be it emulated or
  4564. * not, left the system with the INT_STI flag enabled, it
  4565. * means that the last instruction is an sti. We should not
  4566. * leave the flag on in this case. The same goes for mov ss
  4567. */
  4568. if (int_shadow & mask)
  4569. mask = 0;
  4570. if (unlikely(int_shadow || mask)) {
  4571. kvm_x86_ops->set_interrupt_shadow(vcpu, mask);
  4572. if (!mask)
  4573. kvm_make_request(KVM_REQ_EVENT, vcpu);
  4574. }
  4575. }
  4576. static bool inject_emulated_exception(struct kvm_vcpu *vcpu)
  4577. {
  4578. struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
  4579. if (ctxt->exception.vector == PF_VECTOR)
  4580. return kvm_propagate_fault(vcpu, &ctxt->exception);
  4581. if (ctxt->exception.error_code_valid)
  4582. kvm_queue_exception_e(vcpu, ctxt->exception.vector,
  4583. ctxt->exception.error_code);
  4584. else
  4585. kvm_queue_exception(vcpu, ctxt->exception.vector);
  4586. return false;
  4587. }
  4588. static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
  4589. {
  4590. struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
  4591. int cs_db, cs_l;
  4592. kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
  4593. ctxt->eflags = kvm_get_rflags(vcpu);
  4594. ctxt->eip = kvm_rip_read(vcpu);
  4595. ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
  4596. (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
  4597. (cs_l && is_long_mode(vcpu)) ? X86EMUL_MODE_PROT64 :
  4598. cs_db ? X86EMUL_MODE_PROT32 :
  4599. X86EMUL_MODE_PROT16;
  4600. BUILD_BUG_ON(HF_GUEST_MASK != X86EMUL_GUEST_MASK);
  4601. BUILD_BUG_ON(HF_SMM_MASK != X86EMUL_SMM_MASK);
  4602. BUILD_BUG_ON(HF_SMM_INSIDE_NMI_MASK != X86EMUL_SMM_INSIDE_NMI_MASK);
  4603. init_decode_cache(ctxt);
  4604. vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
  4605. }
  4606. int kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
  4607. {
  4608. struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
  4609. int ret;
  4610. init_emulate_ctxt(vcpu);
  4611. ctxt->op_bytes = 2;
  4612. ctxt->ad_bytes = 2;
  4613. ctxt->_eip = ctxt->eip + inc_eip;
  4614. ret = emulate_int_real(ctxt, irq);
  4615. if (ret != X86EMUL_CONTINUE)
  4616. return EMULATE_FAIL;
  4617. ctxt->eip = ctxt->_eip;
  4618. kvm_rip_write(vcpu, ctxt->eip);
  4619. kvm_set_rflags(vcpu, ctxt->eflags);
  4620. if (irq == NMI_VECTOR)
  4621. vcpu->arch.nmi_pending = 0;
  4622. else
  4623. vcpu->arch.interrupt.pending = false;
  4624. return EMULATE_DONE;
  4625. }
  4626. EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
  4627. static int handle_emulation_failure(struct kvm_vcpu *vcpu)
  4628. {
  4629. int r = EMULATE_DONE;
  4630. ++vcpu->stat.insn_emulation_fail;
  4631. trace_kvm_emulate_insn_failed(vcpu);
  4632. if (!is_guest_mode(vcpu) && kvm_x86_ops->get_cpl(vcpu) == 0) {
  4633. vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
  4634. vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
  4635. vcpu->run->internal.ndata = 0;
  4636. r = EMULATE_FAIL;
  4637. }
  4638. kvm_queue_exception(vcpu, UD_VECTOR);
  4639. return r;
  4640. }
  4641. static bool reexecute_instruction(struct kvm_vcpu *vcpu, gva_t cr2,
  4642. bool write_fault_to_shadow_pgtable,
  4643. int emulation_type)
  4644. {
  4645. gpa_t gpa = cr2;
  4646. kvm_pfn_t pfn;
  4647. if (emulation_type & EMULTYPE_NO_REEXECUTE)
  4648. return false;
  4649. if (!vcpu->arch.mmu.direct_map) {
  4650. /*
  4651. * Write permission should be allowed since only
  4652. * write access need to be emulated.
  4653. */
  4654. gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
  4655. /*
  4656. * If the mapping is invalid in guest, let cpu retry
  4657. * it to generate fault.
  4658. */
  4659. if (gpa == UNMAPPED_GVA)
  4660. return true;
  4661. }
  4662. /*
  4663. * Do not retry the unhandleable instruction if it faults on the
  4664. * readonly host memory, otherwise it will goto a infinite loop:
  4665. * retry instruction -> write #PF -> emulation fail -> retry
  4666. * instruction -> ...
  4667. */
  4668. pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
  4669. /*
  4670. * If the instruction failed on the error pfn, it can not be fixed,
  4671. * report the error to userspace.
  4672. */
  4673. if (is_error_noslot_pfn(pfn))
  4674. return false;
  4675. kvm_release_pfn_clean(pfn);
  4676. /* The instructions are well-emulated on direct mmu. */
  4677. if (vcpu->arch.mmu.direct_map) {
  4678. unsigned int indirect_shadow_pages;
  4679. spin_lock(&vcpu->kvm->mmu_lock);
  4680. indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
  4681. spin_unlock(&vcpu->kvm->mmu_lock);
  4682. if (indirect_shadow_pages)
  4683. kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
  4684. return true;
  4685. }
  4686. /*
  4687. * if emulation was due to access to shadowed page table
  4688. * and it failed try to unshadow page and re-enter the
  4689. * guest to let CPU execute the instruction.
  4690. */
  4691. kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
  4692. /*
  4693. * If the access faults on its page table, it can not
  4694. * be fixed by unprotecting shadow page and it should
  4695. * be reported to userspace.
  4696. */
  4697. return !write_fault_to_shadow_pgtable;
  4698. }
  4699. static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
  4700. unsigned long cr2, int emulation_type)
  4701. {
  4702. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  4703. unsigned long last_retry_eip, last_retry_addr, gpa = cr2;
  4704. last_retry_eip = vcpu->arch.last_retry_eip;
  4705. last_retry_addr = vcpu->arch.last_retry_addr;
  4706. /*
  4707. * If the emulation is caused by #PF and it is non-page_table
  4708. * writing instruction, it means the VM-EXIT is caused by shadow
  4709. * page protected, we can zap the shadow page and retry this
  4710. * instruction directly.
  4711. *
  4712. * Note: if the guest uses a non-page-table modifying instruction
  4713. * on the PDE that points to the instruction, then we will unmap
  4714. * the instruction and go to an infinite loop. So, we cache the
  4715. * last retried eip and the last fault address, if we meet the eip
  4716. * and the address again, we can break out of the potential infinite
  4717. * loop.
  4718. */
  4719. vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
  4720. if (!(emulation_type & EMULTYPE_RETRY))
  4721. return false;
  4722. if (x86_page_table_writing_insn(ctxt))
  4723. return false;
  4724. if (ctxt->eip == last_retry_eip && last_retry_addr == cr2)
  4725. return false;
  4726. vcpu->arch.last_retry_eip = ctxt->eip;
  4727. vcpu->arch.last_retry_addr = cr2;
  4728. if (!vcpu->arch.mmu.direct_map)
  4729. gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
  4730. kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
  4731. return true;
  4732. }
  4733. static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
  4734. static int complete_emulated_pio(struct kvm_vcpu *vcpu);
  4735. static void kvm_smm_changed(struct kvm_vcpu *vcpu)
  4736. {
  4737. if (!(vcpu->arch.hflags & HF_SMM_MASK)) {
  4738. /* This is a good place to trace that we are exiting SMM. */
  4739. trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, false);
  4740. /* Process a latched INIT or SMI, if any. */
  4741. kvm_make_request(KVM_REQ_EVENT, vcpu);
  4742. }
  4743. kvm_mmu_reset_context(vcpu);
  4744. }
  4745. static void kvm_set_hflags(struct kvm_vcpu *vcpu, unsigned emul_flags)
  4746. {
  4747. unsigned changed = vcpu->arch.hflags ^ emul_flags;
  4748. vcpu->arch.hflags = emul_flags;
  4749. if (changed & HF_SMM_MASK)
  4750. kvm_smm_changed(vcpu);
  4751. }
  4752. static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
  4753. unsigned long *db)
  4754. {
  4755. u32 dr6 = 0;
  4756. int i;
  4757. u32 enable, rwlen;
  4758. enable = dr7;
  4759. rwlen = dr7 >> 16;
  4760. for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
  4761. if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
  4762. dr6 |= (1 << i);
  4763. return dr6;
  4764. }
  4765. static void kvm_vcpu_check_singlestep(struct kvm_vcpu *vcpu, unsigned long rflags, int *r)
  4766. {
  4767. struct kvm_run *kvm_run = vcpu->run;
  4768. /*
  4769. * rflags is the old, "raw" value of the flags. The new value has
  4770. * not been saved yet.
  4771. *
  4772. * This is correct even for TF set by the guest, because "the
  4773. * processor will not generate this exception after the instruction
  4774. * that sets the TF flag".
  4775. */
  4776. if (unlikely(rflags & X86_EFLAGS_TF)) {
  4777. if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
  4778. kvm_run->debug.arch.dr6 = DR6_BS | DR6_FIXED_1 |
  4779. DR6_RTM;
  4780. kvm_run->debug.arch.pc = vcpu->arch.singlestep_rip;
  4781. kvm_run->debug.arch.exception = DB_VECTOR;
  4782. kvm_run->exit_reason = KVM_EXIT_DEBUG;
  4783. *r = EMULATE_USER_EXIT;
  4784. } else {
  4785. /*
  4786. * "Certain debug exceptions may clear bit 0-3. The
  4787. * remaining contents of the DR6 register are never
  4788. * cleared by the processor".
  4789. */
  4790. vcpu->arch.dr6 &= ~15;
  4791. vcpu->arch.dr6 |= DR6_BS | DR6_RTM;
  4792. kvm_queue_exception(vcpu, DB_VECTOR);
  4793. }
  4794. }
  4795. }
  4796. int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
  4797. {
  4798. unsigned long rflags = kvm_x86_ops->get_rflags(vcpu);
  4799. int r = EMULATE_DONE;
  4800. kvm_x86_ops->skip_emulated_instruction(vcpu);
  4801. kvm_vcpu_check_singlestep(vcpu, rflags, &r);
  4802. return r == EMULATE_DONE;
  4803. }
  4804. EXPORT_SYMBOL_GPL(kvm_skip_emulated_instruction);
  4805. static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu *vcpu, int *r)
  4806. {
  4807. if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
  4808. (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
  4809. struct kvm_run *kvm_run = vcpu->run;
  4810. unsigned long eip = kvm_get_linear_rip(vcpu);
  4811. u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
  4812. vcpu->arch.guest_debug_dr7,
  4813. vcpu->arch.eff_db);
  4814. if (dr6 != 0) {
  4815. kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1 | DR6_RTM;
  4816. kvm_run->debug.arch.pc = eip;
  4817. kvm_run->debug.arch.exception = DB_VECTOR;
  4818. kvm_run->exit_reason = KVM_EXIT_DEBUG;
  4819. *r = EMULATE_USER_EXIT;
  4820. return true;
  4821. }
  4822. }
  4823. if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
  4824. !(kvm_get_rflags(vcpu) & X86_EFLAGS_RF)) {
  4825. unsigned long eip = kvm_get_linear_rip(vcpu);
  4826. u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
  4827. vcpu->arch.dr7,
  4828. vcpu->arch.db);
  4829. if (dr6 != 0) {
  4830. vcpu->arch.dr6 &= ~15;
  4831. vcpu->arch.dr6 |= dr6 | DR6_RTM;
  4832. kvm_queue_exception(vcpu, DB_VECTOR);
  4833. *r = EMULATE_DONE;
  4834. return true;
  4835. }
  4836. }
  4837. return false;
  4838. }
  4839. int x86_emulate_instruction(struct kvm_vcpu *vcpu,
  4840. unsigned long cr2,
  4841. int emulation_type,
  4842. void *insn,
  4843. int insn_len)
  4844. {
  4845. int r;
  4846. struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
  4847. bool writeback = true;
  4848. bool write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
  4849. /*
  4850. * Clear write_fault_to_shadow_pgtable here to ensure it is
  4851. * never reused.
  4852. */
  4853. vcpu->arch.write_fault_to_shadow_pgtable = false;
  4854. kvm_clear_exception_queue(vcpu);
  4855. if (!(emulation_type & EMULTYPE_NO_DECODE)) {
  4856. init_emulate_ctxt(vcpu);
  4857. /*
  4858. * We will reenter on the same instruction since
  4859. * we do not set complete_userspace_io. This does not
  4860. * handle watchpoints yet, those would be handled in
  4861. * the emulate_ops.
  4862. */
  4863. if (kvm_vcpu_check_breakpoint(vcpu, &r))
  4864. return r;
  4865. ctxt->interruptibility = 0;
  4866. ctxt->have_exception = false;
  4867. ctxt->exception.vector = -1;
  4868. ctxt->perm_ok = false;
  4869. ctxt->ud = emulation_type & EMULTYPE_TRAP_UD;
  4870. r = x86_decode_insn(ctxt, insn, insn_len);
  4871. trace_kvm_emulate_insn_start(vcpu);
  4872. ++vcpu->stat.insn_emulation;
  4873. if (r != EMULATION_OK) {
  4874. if (emulation_type & EMULTYPE_TRAP_UD)
  4875. return EMULATE_FAIL;
  4876. if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
  4877. emulation_type))
  4878. return EMULATE_DONE;
  4879. if (emulation_type & EMULTYPE_SKIP)
  4880. return EMULATE_FAIL;
  4881. return handle_emulation_failure(vcpu);
  4882. }
  4883. }
  4884. if (emulation_type & EMULTYPE_SKIP) {
  4885. kvm_rip_write(vcpu, ctxt->_eip);
  4886. if (ctxt->eflags & X86_EFLAGS_RF)
  4887. kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
  4888. return EMULATE_DONE;
  4889. }
  4890. if (retry_instruction(ctxt, cr2, emulation_type))
  4891. return EMULATE_DONE;
  4892. /* this is needed for vmware backdoor interface to work since it
  4893. changes registers values during IO operation */
  4894. if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
  4895. vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
  4896. emulator_invalidate_register_cache(ctxt);
  4897. }
  4898. restart:
  4899. /* Save the faulting GPA (cr2) in the address field */
  4900. ctxt->exception.address = cr2;
  4901. r = x86_emulate_insn(ctxt);
  4902. if (r == EMULATION_INTERCEPTED)
  4903. return EMULATE_DONE;
  4904. if (r == EMULATION_FAILED) {
  4905. if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
  4906. emulation_type))
  4907. return EMULATE_DONE;
  4908. return handle_emulation_failure(vcpu);
  4909. }
  4910. if (ctxt->have_exception) {
  4911. r = EMULATE_DONE;
  4912. if (inject_emulated_exception(vcpu))
  4913. return r;
  4914. } else if (vcpu->arch.pio.count) {
  4915. if (!vcpu->arch.pio.in) {
  4916. /* FIXME: return into emulator if single-stepping. */
  4917. vcpu->arch.pio.count = 0;
  4918. } else {
  4919. writeback = false;
  4920. vcpu->arch.complete_userspace_io = complete_emulated_pio;
  4921. }
  4922. r = EMULATE_USER_EXIT;
  4923. } else if (vcpu->mmio_needed) {
  4924. if (!vcpu->mmio_is_write)
  4925. writeback = false;
  4926. r = EMULATE_USER_EXIT;
  4927. vcpu->arch.complete_userspace_io = complete_emulated_mmio;
  4928. } else if (r == EMULATION_RESTART)
  4929. goto restart;
  4930. else
  4931. r = EMULATE_DONE;
  4932. if (writeback) {
  4933. unsigned long rflags = kvm_x86_ops->get_rflags(vcpu);
  4934. toggle_interruptibility(vcpu, ctxt->interruptibility);
  4935. vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
  4936. kvm_rip_write(vcpu, ctxt->eip);
  4937. if (r == EMULATE_DONE)
  4938. kvm_vcpu_check_singlestep(vcpu, rflags, &r);
  4939. if (!ctxt->have_exception ||
  4940. exception_type(ctxt->exception.vector) == EXCPT_TRAP)
  4941. __kvm_set_rflags(vcpu, ctxt->eflags);
  4942. /*
  4943. * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
  4944. * do nothing, and it will be requested again as soon as
  4945. * the shadow expires. But we still need to check here,
  4946. * because POPF has no interrupt shadow.
  4947. */
  4948. if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
  4949. kvm_make_request(KVM_REQ_EVENT, vcpu);
  4950. } else
  4951. vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
  4952. return r;
  4953. }
  4954. EXPORT_SYMBOL_GPL(x86_emulate_instruction);
  4955. int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size, unsigned short port)
  4956. {
  4957. unsigned long val = kvm_register_read(vcpu, VCPU_REGS_RAX);
  4958. int ret = emulator_pio_out_emulated(&vcpu->arch.emulate_ctxt,
  4959. size, port, &val, 1);
  4960. /* do not return to emulator after return from userspace */
  4961. vcpu->arch.pio.count = 0;
  4962. return ret;
  4963. }
  4964. EXPORT_SYMBOL_GPL(kvm_fast_pio_out);
  4965. static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
  4966. {
  4967. unsigned long val;
  4968. /* We should only ever be called with arch.pio.count equal to 1 */
  4969. BUG_ON(vcpu->arch.pio.count != 1);
  4970. /* For size less than 4 we merge, else we zero extend */
  4971. val = (vcpu->arch.pio.size < 4) ? kvm_register_read(vcpu, VCPU_REGS_RAX)
  4972. : 0;
  4973. /*
  4974. * Since vcpu->arch.pio.count == 1 let emulator_pio_in_emulated perform
  4975. * the copy and tracing
  4976. */
  4977. emulator_pio_in_emulated(&vcpu->arch.emulate_ctxt, vcpu->arch.pio.size,
  4978. vcpu->arch.pio.port, &val, 1);
  4979. kvm_register_write(vcpu, VCPU_REGS_RAX, val);
  4980. return 1;
  4981. }
  4982. int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size, unsigned short port)
  4983. {
  4984. unsigned long val;
  4985. int ret;
  4986. /* For size less than 4 we merge, else we zero extend */
  4987. val = (size < 4) ? kvm_register_read(vcpu, VCPU_REGS_RAX) : 0;
  4988. ret = emulator_pio_in_emulated(&vcpu->arch.emulate_ctxt, size, port,
  4989. &val, 1);
  4990. if (ret) {
  4991. kvm_register_write(vcpu, VCPU_REGS_RAX, val);
  4992. return ret;
  4993. }
  4994. vcpu->arch.complete_userspace_io = complete_fast_pio_in;
  4995. return 0;
  4996. }
  4997. EXPORT_SYMBOL_GPL(kvm_fast_pio_in);
  4998. static int kvmclock_cpu_down_prep(unsigned int cpu)
  4999. {
  5000. __this_cpu_write(cpu_tsc_khz, 0);
  5001. return 0;
  5002. }
  5003. static void tsc_khz_changed(void *data)
  5004. {
  5005. struct cpufreq_freqs *freq = data;
  5006. unsigned long khz = 0;
  5007. if (data)
  5008. khz = freq->new;
  5009. else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
  5010. khz = cpufreq_quick_get(raw_smp_processor_id());
  5011. if (!khz)
  5012. khz = tsc_khz;
  5013. __this_cpu_write(cpu_tsc_khz, khz);
  5014. }
  5015. static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
  5016. void *data)
  5017. {
  5018. struct cpufreq_freqs *freq = data;
  5019. struct kvm *kvm;
  5020. struct kvm_vcpu *vcpu;
  5021. int i, send_ipi = 0;
  5022. /*
  5023. * We allow guests to temporarily run on slowing clocks,
  5024. * provided we notify them after, or to run on accelerating
  5025. * clocks, provided we notify them before. Thus time never
  5026. * goes backwards.
  5027. *
  5028. * However, we have a problem. We can't atomically update
  5029. * the frequency of a given CPU from this function; it is
  5030. * merely a notifier, which can be called from any CPU.
  5031. * Changing the TSC frequency at arbitrary points in time
  5032. * requires a recomputation of local variables related to
  5033. * the TSC for each VCPU. We must flag these local variables
  5034. * to be updated and be sure the update takes place with the
  5035. * new frequency before any guests proceed.
  5036. *
  5037. * Unfortunately, the combination of hotplug CPU and frequency
  5038. * change creates an intractable locking scenario; the order
  5039. * of when these callouts happen is undefined with respect to
  5040. * CPU hotplug, and they can race with each other. As such,
  5041. * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
  5042. * undefined; you can actually have a CPU frequency change take
  5043. * place in between the computation of X and the setting of the
  5044. * variable. To protect against this problem, all updates of
  5045. * the per_cpu tsc_khz variable are done in an interrupt
  5046. * protected IPI, and all callers wishing to update the value
  5047. * must wait for a synchronous IPI to complete (which is trivial
  5048. * if the caller is on the CPU already). This establishes the
  5049. * necessary total order on variable updates.
  5050. *
  5051. * Note that because a guest time update may take place
  5052. * anytime after the setting of the VCPU's request bit, the
  5053. * correct TSC value must be set before the request. However,
  5054. * to ensure the update actually makes it to any guest which
  5055. * starts running in hardware virtualization between the set
  5056. * and the acquisition of the spinlock, we must also ping the
  5057. * CPU after setting the request bit.
  5058. *
  5059. */
  5060. if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
  5061. return 0;
  5062. if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
  5063. return 0;
  5064. smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
  5065. spin_lock(&kvm_lock);
  5066. list_for_each_entry(kvm, &vm_list, vm_list) {
  5067. kvm_for_each_vcpu(i, vcpu, kvm) {
  5068. if (vcpu->cpu != freq->cpu)
  5069. continue;
  5070. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  5071. if (vcpu->cpu != smp_processor_id())
  5072. send_ipi = 1;
  5073. }
  5074. }
  5075. spin_unlock(&kvm_lock);
  5076. if (freq->old < freq->new && send_ipi) {
  5077. /*
  5078. * We upscale the frequency. Must make the guest
  5079. * doesn't see old kvmclock values while running with
  5080. * the new frequency, otherwise we risk the guest sees
  5081. * time go backwards.
  5082. *
  5083. * In case we update the frequency for another cpu
  5084. * (which might be in guest context) send an interrupt
  5085. * to kick the cpu out of guest context. Next time
  5086. * guest context is entered kvmclock will be updated,
  5087. * so the guest will not see stale values.
  5088. */
  5089. smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
  5090. }
  5091. return 0;
  5092. }
  5093. static struct notifier_block kvmclock_cpufreq_notifier_block = {
  5094. .notifier_call = kvmclock_cpufreq_notifier
  5095. };
  5096. static int kvmclock_cpu_online(unsigned int cpu)
  5097. {
  5098. tsc_khz_changed(NULL);
  5099. return 0;
  5100. }
  5101. static void kvm_timer_init(void)
  5102. {
  5103. max_tsc_khz = tsc_khz;
  5104. if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
  5105. #ifdef CONFIG_CPU_FREQ
  5106. struct cpufreq_policy policy;
  5107. int cpu;
  5108. memset(&policy, 0, sizeof(policy));
  5109. cpu = get_cpu();
  5110. cpufreq_get_policy(&policy, cpu);
  5111. if (policy.cpuinfo.max_freq)
  5112. max_tsc_khz = policy.cpuinfo.max_freq;
  5113. put_cpu();
  5114. #endif
  5115. cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
  5116. CPUFREQ_TRANSITION_NOTIFIER);
  5117. }
  5118. pr_debug("kvm: max_tsc_khz = %ld\n", max_tsc_khz);
  5119. cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
  5120. kvmclock_cpu_online, kvmclock_cpu_down_prep);
  5121. }
  5122. static DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
  5123. int kvm_is_in_guest(void)
  5124. {
  5125. return __this_cpu_read(current_vcpu) != NULL;
  5126. }
  5127. static int kvm_is_user_mode(void)
  5128. {
  5129. int user_mode = 3;
  5130. if (__this_cpu_read(current_vcpu))
  5131. user_mode = kvm_x86_ops->get_cpl(__this_cpu_read(current_vcpu));
  5132. return user_mode != 0;
  5133. }
  5134. static unsigned long kvm_get_guest_ip(void)
  5135. {
  5136. unsigned long ip = 0;
  5137. if (__this_cpu_read(current_vcpu))
  5138. ip = kvm_rip_read(__this_cpu_read(current_vcpu));
  5139. return ip;
  5140. }
  5141. static struct perf_guest_info_callbacks kvm_guest_cbs = {
  5142. .is_in_guest = kvm_is_in_guest,
  5143. .is_user_mode = kvm_is_user_mode,
  5144. .get_guest_ip = kvm_get_guest_ip,
  5145. };
  5146. void kvm_before_handle_nmi(struct kvm_vcpu *vcpu)
  5147. {
  5148. __this_cpu_write(current_vcpu, vcpu);
  5149. }
  5150. EXPORT_SYMBOL_GPL(kvm_before_handle_nmi);
  5151. void kvm_after_handle_nmi(struct kvm_vcpu *vcpu)
  5152. {
  5153. __this_cpu_write(current_vcpu, NULL);
  5154. }
  5155. EXPORT_SYMBOL_GPL(kvm_after_handle_nmi);
  5156. static void kvm_set_mmio_spte_mask(void)
  5157. {
  5158. u64 mask;
  5159. int maxphyaddr = boot_cpu_data.x86_phys_bits;
  5160. /*
  5161. * Set the reserved bits and the present bit of an paging-structure
  5162. * entry to generate page fault with PFER.RSV = 1.
  5163. */
  5164. /* Mask the reserved physical address bits. */
  5165. mask = rsvd_bits(maxphyaddr, 51);
  5166. /* Set the present bit. */
  5167. mask |= 1ull;
  5168. #ifdef CONFIG_X86_64
  5169. /*
  5170. * If reserved bit is not supported, clear the present bit to disable
  5171. * mmio page fault.
  5172. */
  5173. if (maxphyaddr == 52)
  5174. mask &= ~1ull;
  5175. #endif
  5176. kvm_mmu_set_mmio_spte_mask(mask);
  5177. }
  5178. #ifdef CONFIG_X86_64
  5179. static void pvclock_gtod_update_fn(struct work_struct *work)
  5180. {
  5181. struct kvm *kvm;
  5182. struct kvm_vcpu *vcpu;
  5183. int i;
  5184. spin_lock(&kvm_lock);
  5185. list_for_each_entry(kvm, &vm_list, vm_list)
  5186. kvm_for_each_vcpu(i, vcpu, kvm)
  5187. kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
  5188. atomic_set(&kvm_guest_has_master_clock, 0);
  5189. spin_unlock(&kvm_lock);
  5190. }
  5191. static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
  5192. /*
  5193. * Notification about pvclock gtod data update.
  5194. */
  5195. static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
  5196. void *priv)
  5197. {
  5198. struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
  5199. struct timekeeper *tk = priv;
  5200. update_pvclock_gtod(tk);
  5201. /* disable master clock if host does not trust, or does not
  5202. * use, TSC clocksource
  5203. */
  5204. if (gtod->clock.vclock_mode != VCLOCK_TSC &&
  5205. atomic_read(&kvm_guest_has_master_clock) != 0)
  5206. queue_work(system_long_wq, &pvclock_gtod_work);
  5207. return 0;
  5208. }
  5209. static struct notifier_block pvclock_gtod_notifier = {
  5210. .notifier_call = pvclock_gtod_notify,
  5211. };
  5212. #endif
  5213. int kvm_arch_init(void *opaque)
  5214. {
  5215. int r;
  5216. struct kvm_x86_ops *ops = opaque;
  5217. if (kvm_x86_ops) {
  5218. printk(KERN_ERR "kvm: already loaded the other module\n");
  5219. r = -EEXIST;
  5220. goto out;
  5221. }
  5222. if (!ops->cpu_has_kvm_support()) {
  5223. printk(KERN_ERR "kvm: no hardware support\n");
  5224. r = -EOPNOTSUPP;
  5225. goto out;
  5226. }
  5227. if (ops->disabled_by_bios()) {
  5228. printk(KERN_ERR "kvm: disabled by bios\n");
  5229. r = -EOPNOTSUPP;
  5230. goto out;
  5231. }
  5232. r = -ENOMEM;
  5233. shared_msrs = alloc_percpu(struct kvm_shared_msrs);
  5234. if (!shared_msrs) {
  5235. printk(KERN_ERR "kvm: failed to allocate percpu kvm_shared_msrs\n");
  5236. goto out;
  5237. }
  5238. r = kvm_mmu_module_init();
  5239. if (r)
  5240. goto out_free_percpu;
  5241. kvm_set_mmio_spte_mask();
  5242. kvm_x86_ops = ops;
  5243. kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
  5244. PT_DIRTY_MASK, PT64_NX_MASK, 0,
  5245. PT_PRESENT_MASK, 0);
  5246. kvm_timer_init();
  5247. perf_register_guest_info_callbacks(&kvm_guest_cbs);
  5248. if (boot_cpu_has(X86_FEATURE_XSAVE))
  5249. host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
  5250. kvm_lapic_init();
  5251. #ifdef CONFIG_X86_64
  5252. pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
  5253. #endif
  5254. return 0;
  5255. out_free_percpu:
  5256. free_percpu(shared_msrs);
  5257. out:
  5258. return r;
  5259. }
  5260. void kvm_arch_exit(void)
  5261. {
  5262. kvm_lapic_exit();
  5263. perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
  5264. if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
  5265. cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
  5266. CPUFREQ_TRANSITION_NOTIFIER);
  5267. cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
  5268. #ifdef CONFIG_X86_64
  5269. pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
  5270. #endif
  5271. kvm_x86_ops = NULL;
  5272. kvm_mmu_module_exit();
  5273. free_percpu(shared_msrs);
  5274. }
  5275. int kvm_vcpu_halt(struct kvm_vcpu *vcpu)
  5276. {
  5277. ++vcpu->stat.halt_exits;
  5278. if (lapic_in_kernel(vcpu)) {
  5279. vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
  5280. return 1;
  5281. } else {
  5282. vcpu->run->exit_reason = KVM_EXIT_HLT;
  5283. return 0;
  5284. }
  5285. }
  5286. EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
  5287. int kvm_emulate_halt(struct kvm_vcpu *vcpu)
  5288. {
  5289. int ret = kvm_skip_emulated_instruction(vcpu);
  5290. /*
  5291. * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
  5292. * KVM_EXIT_DEBUG here.
  5293. */
  5294. return kvm_vcpu_halt(vcpu) && ret;
  5295. }
  5296. EXPORT_SYMBOL_GPL(kvm_emulate_halt);
  5297. #ifdef CONFIG_X86_64
  5298. static int kvm_pv_clock_pairing(struct kvm_vcpu *vcpu, gpa_t paddr,
  5299. unsigned long clock_type)
  5300. {
  5301. struct kvm_clock_pairing clock_pairing;
  5302. struct timespec ts;
  5303. u64 cycle;
  5304. int ret;
  5305. if (clock_type != KVM_CLOCK_PAIRING_WALLCLOCK)
  5306. return -KVM_EOPNOTSUPP;
  5307. if (kvm_get_walltime_and_clockread(&ts, &cycle) == false)
  5308. return -KVM_EOPNOTSUPP;
  5309. clock_pairing.sec = ts.tv_sec;
  5310. clock_pairing.nsec = ts.tv_nsec;
  5311. clock_pairing.tsc = kvm_read_l1_tsc(vcpu, cycle);
  5312. clock_pairing.flags = 0;
  5313. ret = 0;
  5314. if (kvm_write_guest(vcpu->kvm, paddr, &clock_pairing,
  5315. sizeof(struct kvm_clock_pairing)))
  5316. ret = -KVM_EFAULT;
  5317. return ret;
  5318. }
  5319. #endif
  5320. /*
  5321. * kvm_pv_kick_cpu_op: Kick a vcpu.
  5322. *
  5323. * @apicid - apicid of vcpu to be kicked.
  5324. */
  5325. static void kvm_pv_kick_cpu_op(struct kvm *kvm, unsigned long flags, int apicid)
  5326. {
  5327. struct kvm_lapic_irq lapic_irq;
  5328. lapic_irq.shorthand = 0;
  5329. lapic_irq.dest_mode = 0;
  5330. lapic_irq.dest_id = apicid;
  5331. lapic_irq.msi_redir_hint = false;
  5332. lapic_irq.delivery_mode = APIC_DM_REMRD;
  5333. kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
  5334. }
  5335. void kvm_vcpu_deactivate_apicv(struct kvm_vcpu *vcpu)
  5336. {
  5337. vcpu->arch.apicv_active = false;
  5338. kvm_x86_ops->refresh_apicv_exec_ctrl(vcpu);
  5339. }
  5340. int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
  5341. {
  5342. unsigned long nr, a0, a1, a2, a3, ret;
  5343. int op_64_bit, r;
  5344. r = kvm_skip_emulated_instruction(vcpu);
  5345. if (kvm_hv_hypercall_enabled(vcpu->kvm))
  5346. return kvm_hv_hypercall(vcpu);
  5347. nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
  5348. a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
  5349. a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
  5350. a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
  5351. a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
  5352. trace_kvm_hypercall(nr, a0, a1, a2, a3);
  5353. op_64_bit = is_64_bit_mode(vcpu);
  5354. if (!op_64_bit) {
  5355. nr &= 0xFFFFFFFF;
  5356. a0 &= 0xFFFFFFFF;
  5357. a1 &= 0xFFFFFFFF;
  5358. a2 &= 0xFFFFFFFF;
  5359. a3 &= 0xFFFFFFFF;
  5360. }
  5361. if (kvm_x86_ops->get_cpl(vcpu) != 0) {
  5362. ret = -KVM_EPERM;
  5363. goto out;
  5364. }
  5365. switch (nr) {
  5366. case KVM_HC_VAPIC_POLL_IRQ:
  5367. ret = 0;
  5368. break;
  5369. case KVM_HC_KICK_CPU:
  5370. kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
  5371. ret = 0;
  5372. break;
  5373. #ifdef CONFIG_X86_64
  5374. case KVM_HC_CLOCK_PAIRING:
  5375. ret = kvm_pv_clock_pairing(vcpu, a0, a1);
  5376. break;
  5377. #endif
  5378. default:
  5379. ret = -KVM_ENOSYS;
  5380. break;
  5381. }
  5382. out:
  5383. if (!op_64_bit)
  5384. ret = (u32)ret;
  5385. kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
  5386. ++vcpu->stat.hypercalls;
  5387. return r;
  5388. }
  5389. EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
  5390. static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
  5391. {
  5392. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  5393. char instruction[3];
  5394. unsigned long rip = kvm_rip_read(vcpu);
  5395. kvm_x86_ops->patch_hypercall(vcpu, instruction);
  5396. return emulator_write_emulated(ctxt, rip, instruction, 3,
  5397. &ctxt->exception);
  5398. }
  5399. static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
  5400. {
  5401. return vcpu->run->request_interrupt_window &&
  5402. likely(!pic_in_kernel(vcpu->kvm));
  5403. }
  5404. static void post_kvm_run_save(struct kvm_vcpu *vcpu)
  5405. {
  5406. struct kvm_run *kvm_run = vcpu->run;
  5407. kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
  5408. kvm_run->flags = is_smm(vcpu) ? KVM_RUN_X86_SMM : 0;
  5409. kvm_run->cr8 = kvm_get_cr8(vcpu);
  5410. kvm_run->apic_base = kvm_get_apic_base(vcpu);
  5411. kvm_run->ready_for_interrupt_injection =
  5412. pic_in_kernel(vcpu->kvm) ||
  5413. kvm_vcpu_ready_for_interrupt_injection(vcpu);
  5414. }
  5415. static void update_cr8_intercept(struct kvm_vcpu *vcpu)
  5416. {
  5417. int max_irr, tpr;
  5418. if (!kvm_x86_ops->update_cr8_intercept)
  5419. return;
  5420. if (!lapic_in_kernel(vcpu))
  5421. return;
  5422. if (vcpu->arch.apicv_active)
  5423. return;
  5424. if (!vcpu->arch.apic->vapic_addr)
  5425. max_irr = kvm_lapic_find_highest_irr(vcpu);
  5426. else
  5427. max_irr = -1;
  5428. if (max_irr != -1)
  5429. max_irr >>= 4;
  5430. tpr = kvm_lapic_get_cr8(vcpu);
  5431. kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
  5432. }
  5433. static int inject_pending_event(struct kvm_vcpu *vcpu, bool req_int_win)
  5434. {
  5435. int r;
  5436. /* try to reinject previous events if any */
  5437. if (vcpu->arch.exception.pending) {
  5438. trace_kvm_inj_exception(vcpu->arch.exception.nr,
  5439. vcpu->arch.exception.has_error_code,
  5440. vcpu->arch.exception.error_code);
  5441. if (exception_type(vcpu->arch.exception.nr) == EXCPT_FAULT)
  5442. __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
  5443. X86_EFLAGS_RF);
  5444. if (vcpu->arch.exception.nr == DB_VECTOR &&
  5445. (vcpu->arch.dr7 & DR7_GD)) {
  5446. vcpu->arch.dr7 &= ~DR7_GD;
  5447. kvm_update_dr7(vcpu);
  5448. }
  5449. kvm_x86_ops->queue_exception(vcpu, vcpu->arch.exception.nr,
  5450. vcpu->arch.exception.has_error_code,
  5451. vcpu->arch.exception.error_code,
  5452. vcpu->arch.exception.reinject);
  5453. return 0;
  5454. }
  5455. if (vcpu->arch.nmi_injected) {
  5456. kvm_x86_ops->set_nmi(vcpu);
  5457. return 0;
  5458. }
  5459. if (vcpu->arch.interrupt.pending) {
  5460. kvm_x86_ops->set_irq(vcpu);
  5461. return 0;
  5462. }
  5463. if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
  5464. r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
  5465. if (r != 0)
  5466. return r;
  5467. }
  5468. /* try to inject new event if pending */
  5469. if (vcpu->arch.smi_pending && !is_smm(vcpu)) {
  5470. vcpu->arch.smi_pending = false;
  5471. enter_smm(vcpu);
  5472. } else if (vcpu->arch.nmi_pending && kvm_x86_ops->nmi_allowed(vcpu)) {
  5473. --vcpu->arch.nmi_pending;
  5474. vcpu->arch.nmi_injected = true;
  5475. kvm_x86_ops->set_nmi(vcpu);
  5476. } else if (kvm_cpu_has_injectable_intr(vcpu)) {
  5477. /*
  5478. * Because interrupts can be injected asynchronously, we are
  5479. * calling check_nested_events again here to avoid a race condition.
  5480. * See https://lkml.org/lkml/2014/7/2/60 for discussion about this
  5481. * proposal and current concerns. Perhaps we should be setting
  5482. * KVM_REQ_EVENT only on certain events and not unconditionally?
  5483. */
  5484. if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
  5485. r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
  5486. if (r != 0)
  5487. return r;
  5488. }
  5489. if (kvm_x86_ops->interrupt_allowed(vcpu)) {
  5490. kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
  5491. false);
  5492. kvm_x86_ops->set_irq(vcpu);
  5493. }
  5494. }
  5495. return 0;
  5496. }
  5497. static void process_nmi(struct kvm_vcpu *vcpu)
  5498. {
  5499. unsigned limit = 2;
  5500. /*
  5501. * x86 is limited to one NMI running, and one NMI pending after it.
  5502. * If an NMI is already in progress, limit further NMIs to just one.
  5503. * Otherwise, allow two (and we'll inject the first one immediately).
  5504. */
  5505. if (kvm_x86_ops->get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
  5506. limit = 1;
  5507. vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
  5508. vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
  5509. kvm_make_request(KVM_REQ_EVENT, vcpu);
  5510. }
  5511. #define put_smstate(type, buf, offset, val) \
  5512. *(type *)((buf) + (offset) - 0x7e00) = val
  5513. static u32 enter_smm_get_segment_flags(struct kvm_segment *seg)
  5514. {
  5515. u32 flags = 0;
  5516. flags |= seg->g << 23;
  5517. flags |= seg->db << 22;
  5518. flags |= seg->l << 21;
  5519. flags |= seg->avl << 20;
  5520. flags |= seg->present << 15;
  5521. flags |= seg->dpl << 13;
  5522. flags |= seg->s << 12;
  5523. flags |= seg->type << 8;
  5524. return flags;
  5525. }
  5526. static void enter_smm_save_seg_32(struct kvm_vcpu *vcpu, char *buf, int n)
  5527. {
  5528. struct kvm_segment seg;
  5529. int offset;
  5530. kvm_get_segment(vcpu, &seg, n);
  5531. put_smstate(u32, buf, 0x7fa8 + n * 4, seg.selector);
  5532. if (n < 3)
  5533. offset = 0x7f84 + n * 12;
  5534. else
  5535. offset = 0x7f2c + (n - 3) * 12;
  5536. put_smstate(u32, buf, offset + 8, seg.base);
  5537. put_smstate(u32, buf, offset + 4, seg.limit);
  5538. put_smstate(u32, buf, offset, enter_smm_get_segment_flags(&seg));
  5539. }
  5540. #ifdef CONFIG_X86_64
  5541. static void enter_smm_save_seg_64(struct kvm_vcpu *vcpu, char *buf, int n)
  5542. {
  5543. struct kvm_segment seg;
  5544. int offset;
  5545. u16 flags;
  5546. kvm_get_segment(vcpu, &seg, n);
  5547. offset = 0x7e00 + n * 16;
  5548. flags = enter_smm_get_segment_flags(&seg) >> 8;
  5549. put_smstate(u16, buf, offset, seg.selector);
  5550. put_smstate(u16, buf, offset + 2, flags);
  5551. put_smstate(u32, buf, offset + 4, seg.limit);
  5552. put_smstate(u64, buf, offset + 8, seg.base);
  5553. }
  5554. #endif
  5555. static void enter_smm_save_state_32(struct kvm_vcpu *vcpu, char *buf)
  5556. {
  5557. struct desc_ptr dt;
  5558. struct kvm_segment seg;
  5559. unsigned long val;
  5560. int i;
  5561. put_smstate(u32, buf, 0x7ffc, kvm_read_cr0(vcpu));
  5562. put_smstate(u32, buf, 0x7ff8, kvm_read_cr3(vcpu));
  5563. put_smstate(u32, buf, 0x7ff4, kvm_get_rflags(vcpu));
  5564. put_smstate(u32, buf, 0x7ff0, kvm_rip_read(vcpu));
  5565. for (i = 0; i < 8; i++)
  5566. put_smstate(u32, buf, 0x7fd0 + i * 4, kvm_register_read(vcpu, i));
  5567. kvm_get_dr(vcpu, 6, &val);
  5568. put_smstate(u32, buf, 0x7fcc, (u32)val);
  5569. kvm_get_dr(vcpu, 7, &val);
  5570. put_smstate(u32, buf, 0x7fc8, (u32)val);
  5571. kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
  5572. put_smstate(u32, buf, 0x7fc4, seg.selector);
  5573. put_smstate(u32, buf, 0x7f64, seg.base);
  5574. put_smstate(u32, buf, 0x7f60, seg.limit);
  5575. put_smstate(u32, buf, 0x7f5c, enter_smm_get_segment_flags(&seg));
  5576. kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
  5577. put_smstate(u32, buf, 0x7fc0, seg.selector);
  5578. put_smstate(u32, buf, 0x7f80, seg.base);
  5579. put_smstate(u32, buf, 0x7f7c, seg.limit);
  5580. put_smstate(u32, buf, 0x7f78, enter_smm_get_segment_flags(&seg));
  5581. kvm_x86_ops->get_gdt(vcpu, &dt);
  5582. put_smstate(u32, buf, 0x7f74, dt.address);
  5583. put_smstate(u32, buf, 0x7f70, dt.size);
  5584. kvm_x86_ops->get_idt(vcpu, &dt);
  5585. put_smstate(u32, buf, 0x7f58, dt.address);
  5586. put_smstate(u32, buf, 0x7f54, dt.size);
  5587. for (i = 0; i < 6; i++)
  5588. enter_smm_save_seg_32(vcpu, buf, i);
  5589. put_smstate(u32, buf, 0x7f14, kvm_read_cr4(vcpu));
  5590. /* revision id */
  5591. put_smstate(u32, buf, 0x7efc, 0x00020000);
  5592. put_smstate(u32, buf, 0x7ef8, vcpu->arch.smbase);
  5593. }
  5594. static void enter_smm_save_state_64(struct kvm_vcpu *vcpu, char *buf)
  5595. {
  5596. #ifdef CONFIG_X86_64
  5597. struct desc_ptr dt;
  5598. struct kvm_segment seg;
  5599. unsigned long val;
  5600. int i;
  5601. for (i = 0; i < 16; i++)
  5602. put_smstate(u64, buf, 0x7ff8 - i * 8, kvm_register_read(vcpu, i));
  5603. put_smstate(u64, buf, 0x7f78, kvm_rip_read(vcpu));
  5604. put_smstate(u32, buf, 0x7f70, kvm_get_rflags(vcpu));
  5605. kvm_get_dr(vcpu, 6, &val);
  5606. put_smstate(u64, buf, 0x7f68, val);
  5607. kvm_get_dr(vcpu, 7, &val);
  5608. put_smstate(u64, buf, 0x7f60, val);
  5609. put_smstate(u64, buf, 0x7f58, kvm_read_cr0(vcpu));
  5610. put_smstate(u64, buf, 0x7f50, kvm_read_cr3(vcpu));
  5611. put_smstate(u64, buf, 0x7f48, kvm_read_cr4(vcpu));
  5612. put_smstate(u32, buf, 0x7f00, vcpu->arch.smbase);
  5613. /* revision id */
  5614. put_smstate(u32, buf, 0x7efc, 0x00020064);
  5615. put_smstate(u64, buf, 0x7ed0, vcpu->arch.efer);
  5616. kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
  5617. put_smstate(u16, buf, 0x7e90, seg.selector);
  5618. put_smstate(u16, buf, 0x7e92, enter_smm_get_segment_flags(&seg) >> 8);
  5619. put_smstate(u32, buf, 0x7e94, seg.limit);
  5620. put_smstate(u64, buf, 0x7e98, seg.base);
  5621. kvm_x86_ops->get_idt(vcpu, &dt);
  5622. put_smstate(u32, buf, 0x7e84, dt.size);
  5623. put_smstate(u64, buf, 0x7e88, dt.address);
  5624. kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
  5625. put_smstate(u16, buf, 0x7e70, seg.selector);
  5626. put_smstate(u16, buf, 0x7e72, enter_smm_get_segment_flags(&seg) >> 8);
  5627. put_smstate(u32, buf, 0x7e74, seg.limit);
  5628. put_smstate(u64, buf, 0x7e78, seg.base);
  5629. kvm_x86_ops->get_gdt(vcpu, &dt);
  5630. put_smstate(u32, buf, 0x7e64, dt.size);
  5631. put_smstate(u64, buf, 0x7e68, dt.address);
  5632. for (i = 0; i < 6; i++)
  5633. enter_smm_save_seg_64(vcpu, buf, i);
  5634. #else
  5635. WARN_ON_ONCE(1);
  5636. #endif
  5637. }
  5638. static void enter_smm(struct kvm_vcpu *vcpu)
  5639. {
  5640. struct kvm_segment cs, ds;
  5641. struct desc_ptr dt;
  5642. char buf[512];
  5643. u32 cr0;
  5644. trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, true);
  5645. vcpu->arch.hflags |= HF_SMM_MASK;
  5646. memset(buf, 0, 512);
  5647. if (guest_cpuid_has_longmode(vcpu))
  5648. enter_smm_save_state_64(vcpu, buf);
  5649. else
  5650. enter_smm_save_state_32(vcpu, buf);
  5651. kvm_vcpu_write_guest(vcpu, vcpu->arch.smbase + 0xfe00, buf, sizeof(buf));
  5652. if (kvm_x86_ops->get_nmi_mask(vcpu))
  5653. vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
  5654. else
  5655. kvm_x86_ops->set_nmi_mask(vcpu, true);
  5656. kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
  5657. kvm_rip_write(vcpu, 0x8000);
  5658. cr0 = vcpu->arch.cr0 & ~(X86_CR0_PE | X86_CR0_EM | X86_CR0_TS | X86_CR0_PG);
  5659. kvm_x86_ops->set_cr0(vcpu, cr0);
  5660. vcpu->arch.cr0 = cr0;
  5661. kvm_x86_ops->set_cr4(vcpu, 0);
  5662. /* Undocumented: IDT limit is set to zero on entry to SMM. */
  5663. dt.address = dt.size = 0;
  5664. kvm_x86_ops->set_idt(vcpu, &dt);
  5665. __kvm_set_dr(vcpu, 7, DR7_FIXED_1);
  5666. cs.selector = (vcpu->arch.smbase >> 4) & 0xffff;
  5667. cs.base = vcpu->arch.smbase;
  5668. ds.selector = 0;
  5669. ds.base = 0;
  5670. cs.limit = ds.limit = 0xffffffff;
  5671. cs.type = ds.type = 0x3;
  5672. cs.dpl = ds.dpl = 0;
  5673. cs.db = ds.db = 0;
  5674. cs.s = ds.s = 1;
  5675. cs.l = ds.l = 0;
  5676. cs.g = ds.g = 1;
  5677. cs.avl = ds.avl = 0;
  5678. cs.present = ds.present = 1;
  5679. cs.unusable = ds.unusable = 0;
  5680. cs.padding = ds.padding = 0;
  5681. kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
  5682. kvm_set_segment(vcpu, &ds, VCPU_SREG_DS);
  5683. kvm_set_segment(vcpu, &ds, VCPU_SREG_ES);
  5684. kvm_set_segment(vcpu, &ds, VCPU_SREG_FS);
  5685. kvm_set_segment(vcpu, &ds, VCPU_SREG_GS);
  5686. kvm_set_segment(vcpu, &ds, VCPU_SREG_SS);
  5687. if (guest_cpuid_has_longmode(vcpu))
  5688. kvm_x86_ops->set_efer(vcpu, 0);
  5689. kvm_update_cpuid(vcpu);
  5690. kvm_mmu_reset_context(vcpu);
  5691. }
  5692. static void process_smi(struct kvm_vcpu *vcpu)
  5693. {
  5694. vcpu->arch.smi_pending = true;
  5695. kvm_make_request(KVM_REQ_EVENT, vcpu);
  5696. }
  5697. void kvm_make_scan_ioapic_request(struct kvm *kvm)
  5698. {
  5699. kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
  5700. }
  5701. static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
  5702. {
  5703. u64 eoi_exit_bitmap[4];
  5704. if (!kvm_apic_hw_enabled(vcpu->arch.apic))
  5705. return;
  5706. bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
  5707. if (irqchip_split(vcpu->kvm))
  5708. kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
  5709. else {
  5710. if (kvm_x86_ops->sync_pir_to_irr && vcpu->arch.apicv_active)
  5711. kvm_x86_ops->sync_pir_to_irr(vcpu);
  5712. kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
  5713. }
  5714. bitmap_or((ulong *)eoi_exit_bitmap, vcpu->arch.ioapic_handled_vectors,
  5715. vcpu_to_synic(vcpu)->vec_bitmap, 256);
  5716. kvm_x86_ops->load_eoi_exitmap(vcpu, eoi_exit_bitmap);
  5717. }
  5718. static void kvm_vcpu_flush_tlb(struct kvm_vcpu *vcpu)
  5719. {
  5720. ++vcpu->stat.tlb_flush;
  5721. kvm_x86_ops->tlb_flush(vcpu);
  5722. }
  5723. void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
  5724. {
  5725. struct page *page = NULL;
  5726. if (!lapic_in_kernel(vcpu))
  5727. return;
  5728. if (!kvm_x86_ops->set_apic_access_page_addr)
  5729. return;
  5730. page = gfn_to_page(vcpu->kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
  5731. if (is_error_page(page))
  5732. return;
  5733. kvm_x86_ops->set_apic_access_page_addr(vcpu, page_to_phys(page));
  5734. /*
  5735. * Do not pin apic access page in memory, the MMU notifier
  5736. * will call us again if it is migrated or swapped out.
  5737. */
  5738. put_page(page);
  5739. }
  5740. EXPORT_SYMBOL_GPL(kvm_vcpu_reload_apic_access_page);
  5741. void kvm_arch_mmu_notifier_invalidate_page(struct kvm *kvm,
  5742. unsigned long address)
  5743. {
  5744. /*
  5745. * The physical address of apic access page is stored in the VMCS.
  5746. * Update it when it becomes invalid.
  5747. */
  5748. if (address == gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT))
  5749. kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
  5750. }
  5751. /*
  5752. * Returns 1 to let vcpu_run() continue the guest execution loop without
  5753. * exiting to the userspace. Otherwise, the value will be returned to the
  5754. * userspace.
  5755. */
  5756. static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
  5757. {
  5758. int r;
  5759. bool req_int_win =
  5760. dm_request_for_irq_injection(vcpu) &&
  5761. kvm_cpu_accept_dm_intr(vcpu);
  5762. bool req_immediate_exit = false;
  5763. if (vcpu->requests) {
  5764. if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
  5765. kvm_mmu_unload(vcpu);
  5766. if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
  5767. __kvm_migrate_timers(vcpu);
  5768. if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
  5769. kvm_gen_update_masterclock(vcpu->kvm);
  5770. if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
  5771. kvm_gen_kvmclock_update(vcpu);
  5772. if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
  5773. r = kvm_guest_time_update(vcpu);
  5774. if (unlikely(r))
  5775. goto out;
  5776. }
  5777. if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
  5778. kvm_mmu_sync_roots(vcpu);
  5779. if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
  5780. kvm_vcpu_flush_tlb(vcpu);
  5781. if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
  5782. vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
  5783. r = 0;
  5784. goto out;
  5785. }
  5786. if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
  5787. vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
  5788. r = 0;
  5789. goto out;
  5790. }
  5791. if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
  5792. /* Page is swapped out. Do synthetic halt */
  5793. vcpu->arch.apf.halted = true;
  5794. r = 1;
  5795. goto out;
  5796. }
  5797. if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
  5798. record_steal_time(vcpu);
  5799. if (kvm_check_request(KVM_REQ_SMI, vcpu))
  5800. process_smi(vcpu);
  5801. if (kvm_check_request(KVM_REQ_NMI, vcpu))
  5802. process_nmi(vcpu);
  5803. if (kvm_check_request(KVM_REQ_PMU, vcpu))
  5804. kvm_pmu_handle_event(vcpu);
  5805. if (kvm_check_request(KVM_REQ_PMI, vcpu))
  5806. kvm_pmu_deliver_pmi(vcpu);
  5807. if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
  5808. BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
  5809. if (test_bit(vcpu->arch.pending_ioapic_eoi,
  5810. vcpu->arch.ioapic_handled_vectors)) {
  5811. vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
  5812. vcpu->run->eoi.vector =
  5813. vcpu->arch.pending_ioapic_eoi;
  5814. r = 0;
  5815. goto out;
  5816. }
  5817. }
  5818. if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
  5819. vcpu_scan_ioapic(vcpu);
  5820. if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
  5821. kvm_vcpu_reload_apic_access_page(vcpu);
  5822. if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
  5823. vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
  5824. vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
  5825. r = 0;
  5826. goto out;
  5827. }
  5828. if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
  5829. vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
  5830. vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
  5831. r = 0;
  5832. goto out;
  5833. }
  5834. if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
  5835. vcpu->run->exit_reason = KVM_EXIT_HYPERV;
  5836. vcpu->run->hyperv = vcpu->arch.hyperv.exit;
  5837. r = 0;
  5838. goto out;
  5839. }
  5840. /*
  5841. * KVM_REQ_HV_STIMER has to be processed after
  5842. * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
  5843. * depend on the guest clock being up-to-date
  5844. */
  5845. if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
  5846. kvm_hv_process_stimers(vcpu);
  5847. }
  5848. if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
  5849. ++vcpu->stat.req_event;
  5850. kvm_apic_accept_events(vcpu);
  5851. if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
  5852. r = 1;
  5853. goto out;
  5854. }
  5855. if (inject_pending_event(vcpu, req_int_win) != 0)
  5856. req_immediate_exit = true;
  5857. else {
  5858. /* Enable NMI/IRQ window open exits if needed.
  5859. *
  5860. * SMIs have two cases: 1) they can be nested, and
  5861. * then there is nothing to do here because RSM will
  5862. * cause a vmexit anyway; 2) or the SMI can be pending
  5863. * because inject_pending_event has completed the
  5864. * injection of an IRQ or NMI from the previous vmexit,
  5865. * and then we request an immediate exit to inject the SMI.
  5866. */
  5867. if (vcpu->arch.smi_pending && !is_smm(vcpu))
  5868. req_immediate_exit = true;
  5869. if (vcpu->arch.nmi_pending)
  5870. kvm_x86_ops->enable_nmi_window(vcpu);
  5871. if (kvm_cpu_has_injectable_intr(vcpu) || req_int_win)
  5872. kvm_x86_ops->enable_irq_window(vcpu);
  5873. }
  5874. if (kvm_lapic_enabled(vcpu)) {
  5875. update_cr8_intercept(vcpu);
  5876. kvm_lapic_sync_to_vapic(vcpu);
  5877. }
  5878. }
  5879. r = kvm_mmu_reload(vcpu);
  5880. if (unlikely(r)) {
  5881. goto cancel_injection;
  5882. }
  5883. preempt_disable();
  5884. kvm_x86_ops->prepare_guest_switch(vcpu);
  5885. kvm_load_guest_fpu(vcpu);
  5886. /*
  5887. * Disable IRQs before setting IN_GUEST_MODE. Posted interrupt
  5888. * IPI are then delayed after guest entry, which ensures that they
  5889. * result in virtual interrupt delivery.
  5890. */
  5891. local_irq_disable();
  5892. vcpu->mode = IN_GUEST_MODE;
  5893. srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
  5894. /*
  5895. * 1) We should set ->mode before checking ->requests. Please see
  5896. * the comment in kvm_vcpu_exiting_guest_mode().
  5897. *
  5898. * 2) For APICv, we should set ->mode before checking PIR.ON. This
  5899. * pairs with the memory barrier implicit in pi_test_and_set_on
  5900. * (see vmx_deliver_posted_interrupt).
  5901. *
  5902. * 3) This also orders the write to mode from any reads to the page
  5903. * tables done while the VCPU is running. Please see the comment
  5904. * in kvm_flush_remote_tlbs.
  5905. */
  5906. smp_mb__after_srcu_read_unlock();
  5907. /*
  5908. * This handles the case where a posted interrupt was
  5909. * notified with kvm_vcpu_kick.
  5910. */
  5911. if (kvm_lapic_enabled(vcpu)) {
  5912. if (kvm_x86_ops->sync_pir_to_irr && vcpu->arch.apicv_active)
  5913. kvm_x86_ops->sync_pir_to_irr(vcpu);
  5914. }
  5915. if (vcpu->mode == EXITING_GUEST_MODE || vcpu->requests
  5916. || need_resched() || signal_pending(current)) {
  5917. vcpu->mode = OUTSIDE_GUEST_MODE;
  5918. smp_wmb();
  5919. local_irq_enable();
  5920. preempt_enable();
  5921. vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
  5922. r = 1;
  5923. goto cancel_injection;
  5924. }
  5925. kvm_load_guest_xcr0(vcpu);
  5926. if (req_immediate_exit) {
  5927. kvm_make_request(KVM_REQ_EVENT, vcpu);
  5928. smp_send_reschedule(vcpu->cpu);
  5929. }
  5930. trace_kvm_entry(vcpu->vcpu_id);
  5931. wait_lapic_expire(vcpu);
  5932. guest_enter_irqoff();
  5933. if (unlikely(vcpu->arch.switch_db_regs)) {
  5934. set_debugreg(0, 7);
  5935. set_debugreg(vcpu->arch.eff_db[0], 0);
  5936. set_debugreg(vcpu->arch.eff_db[1], 1);
  5937. set_debugreg(vcpu->arch.eff_db[2], 2);
  5938. set_debugreg(vcpu->arch.eff_db[3], 3);
  5939. set_debugreg(vcpu->arch.dr6, 6);
  5940. vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
  5941. }
  5942. kvm_x86_ops->run(vcpu);
  5943. /*
  5944. * Do this here before restoring debug registers on the host. And
  5945. * since we do this before handling the vmexit, a DR access vmexit
  5946. * can (a) read the correct value of the debug registers, (b) set
  5947. * KVM_DEBUGREG_WONT_EXIT again.
  5948. */
  5949. if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
  5950. WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
  5951. kvm_x86_ops->sync_dirty_debug_regs(vcpu);
  5952. kvm_update_dr0123(vcpu);
  5953. kvm_update_dr6(vcpu);
  5954. kvm_update_dr7(vcpu);
  5955. vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
  5956. }
  5957. /*
  5958. * If the guest has used debug registers, at least dr7
  5959. * will be disabled while returning to the host.
  5960. * If we don't have active breakpoints in the host, we don't
  5961. * care about the messed up debug address registers. But if
  5962. * we have some of them active, restore the old state.
  5963. */
  5964. if (hw_breakpoint_active())
  5965. hw_breakpoint_restore();
  5966. vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
  5967. vcpu->mode = OUTSIDE_GUEST_MODE;
  5968. smp_wmb();
  5969. kvm_put_guest_xcr0(vcpu);
  5970. kvm_x86_ops->handle_external_intr(vcpu);
  5971. ++vcpu->stat.exits;
  5972. guest_exit_irqoff();
  5973. local_irq_enable();
  5974. preempt_enable();
  5975. vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
  5976. /*
  5977. * Profile KVM exit RIPs:
  5978. */
  5979. if (unlikely(prof_on == KVM_PROFILING)) {
  5980. unsigned long rip = kvm_rip_read(vcpu);
  5981. profile_hit(KVM_PROFILING, (void *)rip);
  5982. }
  5983. if (unlikely(vcpu->arch.tsc_always_catchup))
  5984. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  5985. if (vcpu->arch.apic_attention)
  5986. kvm_lapic_sync_from_vapic(vcpu);
  5987. r = kvm_x86_ops->handle_exit(vcpu);
  5988. return r;
  5989. cancel_injection:
  5990. kvm_x86_ops->cancel_injection(vcpu);
  5991. if (unlikely(vcpu->arch.apic_attention))
  5992. kvm_lapic_sync_from_vapic(vcpu);
  5993. out:
  5994. return r;
  5995. }
  5996. static inline int vcpu_block(struct kvm *kvm, struct kvm_vcpu *vcpu)
  5997. {
  5998. if (!kvm_arch_vcpu_runnable(vcpu) &&
  5999. (!kvm_x86_ops->pre_block || kvm_x86_ops->pre_block(vcpu) == 0)) {
  6000. srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
  6001. kvm_vcpu_block(vcpu);
  6002. vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
  6003. if (kvm_x86_ops->post_block)
  6004. kvm_x86_ops->post_block(vcpu);
  6005. if (!kvm_check_request(KVM_REQ_UNHALT, vcpu))
  6006. return 1;
  6007. }
  6008. kvm_apic_accept_events(vcpu);
  6009. switch(vcpu->arch.mp_state) {
  6010. case KVM_MP_STATE_HALTED:
  6011. vcpu->arch.pv.pv_unhalted = false;
  6012. vcpu->arch.mp_state =
  6013. KVM_MP_STATE_RUNNABLE;
  6014. case KVM_MP_STATE_RUNNABLE:
  6015. vcpu->arch.apf.halted = false;
  6016. break;
  6017. case KVM_MP_STATE_INIT_RECEIVED:
  6018. break;
  6019. default:
  6020. return -EINTR;
  6021. break;
  6022. }
  6023. return 1;
  6024. }
  6025. static inline bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
  6026. {
  6027. if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events)
  6028. kvm_x86_ops->check_nested_events(vcpu, false);
  6029. return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
  6030. !vcpu->arch.apf.halted);
  6031. }
  6032. static int vcpu_run(struct kvm_vcpu *vcpu)
  6033. {
  6034. int r;
  6035. struct kvm *kvm = vcpu->kvm;
  6036. vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
  6037. for (;;) {
  6038. if (kvm_vcpu_running(vcpu)) {
  6039. r = vcpu_enter_guest(vcpu);
  6040. } else {
  6041. r = vcpu_block(kvm, vcpu);
  6042. }
  6043. if (r <= 0)
  6044. break;
  6045. kvm_clear_request(KVM_REQ_PENDING_TIMER, vcpu);
  6046. if (kvm_cpu_has_pending_timer(vcpu))
  6047. kvm_inject_pending_timer_irqs(vcpu);
  6048. if (dm_request_for_irq_injection(vcpu) &&
  6049. kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
  6050. r = 0;
  6051. vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
  6052. ++vcpu->stat.request_irq_exits;
  6053. break;
  6054. }
  6055. kvm_check_async_pf_completion(vcpu);
  6056. if (signal_pending(current)) {
  6057. r = -EINTR;
  6058. vcpu->run->exit_reason = KVM_EXIT_INTR;
  6059. ++vcpu->stat.signal_exits;
  6060. break;
  6061. }
  6062. if (need_resched()) {
  6063. srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
  6064. cond_resched();
  6065. vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
  6066. }
  6067. }
  6068. srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
  6069. return r;
  6070. }
  6071. static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
  6072. {
  6073. int r;
  6074. vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
  6075. r = emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
  6076. srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
  6077. if (r != EMULATE_DONE)
  6078. return 0;
  6079. return 1;
  6080. }
  6081. static int complete_emulated_pio(struct kvm_vcpu *vcpu)
  6082. {
  6083. BUG_ON(!vcpu->arch.pio.count);
  6084. return complete_emulated_io(vcpu);
  6085. }
  6086. /*
  6087. * Implements the following, as a state machine:
  6088. *
  6089. * read:
  6090. * for each fragment
  6091. * for each mmio piece in the fragment
  6092. * write gpa, len
  6093. * exit
  6094. * copy data
  6095. * execute insn
  6096. *
  6097. * write:
  6098. * for each fragment
  6099. * for each mmio piece in the fragment
  6100. * write gpa, len
  6101. * copy data
  6102. * exit
  6103. */
  6104. static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
  6105. {
  6106. struct kvm_run *run = vcpu->run;
  6107. struct kvm_mmio_fragment *frag;
  6108. unsigned len;
  6109. BUG_ON(!vcpu->mmio_needed);
  6110. /* Complete previous fragment */
  6111. frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
  6112. len = min(8u, frag->len);
  6113. if (!vcpu->mmio_is_write)
  6114. memcpy(frag->data, run->mmio.data, len);
  6115. if (frag->len <= 8) {
  6116. /* Switch to the next fragment. */
  6117. frag++;
  6118. vcpu->mmio_cur_fragment++;
  6119. } else {
  6120. /* Go forward to the next mmio piece. */
  6121. frag->data += len;
  6122. frag->gpa += len;
  6123. frag->len -= len;
  6124. }
  6125. if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
  6126. vcpu->mmio_needed = 0;
  6127. /* FIXME: return into emulator if single-stepping. */
  6128. if (vcpu->mmio_is_write)
  6129. return 1;
  6130. vcpu->mmio_read_completed = 1;
  6131. return complete_emulated_io(vcpu);
  6132. }
  6133. run->exit_reason = KVM_EXIT_MMIO;
  6134. run->mmio.phys_addr = frag->gpa;
  6135. if (vcpu->mmio_is_write)
  6136. memcpy(run->mmio.data, frag->data, min(8u, frag->len));
  6137. run->mmio.len = min(8u, frag->len);
  6138. run->mmio.is_write = vcpu->mmio_is_write;
  6139. vcpu->arch.complete_userspace_io = complete_emulated_mmio;
  6140. return 0;
  6141. }
  6142. int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
  6143. {
  6144. struct fpu *fpu = &current->thread.fpu;
  6145. int r;
  6146. sigset_t sigsaved;
  6147. fpu__activate_curr(fpu);
  6148. if (vcpu->sigset_active)
  6149. sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
  6150. if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
  6151. kvm_vcpu_block(vcpu);
  6152. kvm_apic_accept_events(vcpu);
  6153. kvm_clear_request(KVM_REQ_UNHALT, vcpu);
  6154. r = -EAGAIN;
  6155. goto out;
  6156. }
  6157. /* re-sync apic's tpr */
  6158. if (!lapic_in_kernel(vcpu)) {
  6159. if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
  6160. r = -EINVAL;
  6161. goto out;
  6162. }
  6163. }
  6164. if (unlikely(vcpu->arch.complete_userspace_io)) {
  6165. int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
  6166. vcpu->arch.complete_userspace_io = NULL;
  6167. r = cui(vcpu);
  6168. if (r <= 0)
  6169. goto out;
  6170. } else
  6171. WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
  6172. if (kvm_run->immediate_exit)
  6173. r = -EINTR;
  6174. else
  6175. r = vcpu_run(vcpu);
  6176. out:
  6177. post_kvm_run_save(vcpu);
  6178. if (vcpu->sigset_active)
  6179. sigprocmask(SIG_SETMASK, &sigsaved, NULL);
  6180. return r;
  6181. }
  6182. int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
  6183. {
  6184. if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
  6185. /*
  6186. * We are here if userspace calls get_regs() in the middle of
  6187. * instruction emulation. Registers state needs to be copied
  6188. * back from emulation context to vcpu. Userspace shouldn't do
  6189. * that usually, but some bad designed PV devices (vmware
  6190. * backdoor interface) need this to work
  6191. */
  6192. emulator_writeback_register_cache(&vcpu->arch.emulate_ctxt);
  6193. vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
  6194. }
  6195. regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
  6196. regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
  6197. regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
  6198. regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
  6199. regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
  6200. regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
  6201. regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
  6202. regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
  6203. #ifdef CONFIG_X86_64
  6204. regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
  6205. regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
  6206. regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
  6207. regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
  6208. regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
  6209. regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
  6210. regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
  6211. regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
  6212. #endif
  6213. regs->rip = kvm_rip_read(vcpu);
  6214. regs->rflags = kvm_get_rflags(vcpu);
  6215. return 0;
  6216. }
  6217. int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
  6218. {
  6219. vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
  6220. vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
  6221. kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
  6222. kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
  6223. kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
  6224. kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
  6225. kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
  6226. kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
  6227. kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
  6228. kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
  6229. #ifdef CONFIG_X86_64
  6230. kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
  6231. kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
  6232. kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
  6233. kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
  6234. kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
  6235. kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
  6236. kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
  6237. kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
  6238. #endif
  6239. kvm_rip_write(vcpu, regs->rip);
  6240. kvm_set_rflags(vcpu, regs->rflags);
  6241. vcpu->arch.exception.pending = false;
  6242. kvm_make_request(KVM_REQ_EVENT, vcpu);
  6243. return 0;
  6244. }
  6245. void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
  6246. {
  6247. struct kvm_segment cs;
  6248. kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
  6249. *db = cs.db;
  6250. *l = cs.l;
  6251. }
  6252. EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
  6253. int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
  6254. struct kvm_sregs *sregs)
  6255. {
  6256. struct desc_ptr dt;
  6257. kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
  6258. kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
  6259. kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
  6260. kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
  6261. kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
  6262. kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
  6263. kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
  6264. kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
  6265. kvm_x86_ops->get_idt(vcpu, &dt);
  6266. sregs->idt.limit = dt.size;
  6267. sregs->idt.base = dt.address;
  6268. kvm_x86_ops->get_gdt(vcpu, &dt);
  6269. sregs->gdt.limit = dt.size;
  6270. sregs->gdt.base = dt.address;
  6271. sregs->cr0 = kvm_read_cr0(vcpu);
  6272. sregs->cr2 = vcpu->arch.cr2;
  6273. sregs->cr3 = kvm_read_cr3(vcpu);
  6274. sregs->cr4 = kvm_read_cr4(vcpu);
  6275. sregs->cr8 = kvm_get_cr8(vcpu);
  6276. sregs->efer = vcpu->arch.efer;
  6277. sregs->apic_base = kvm_get_apic_base(vcpu);
  6278. memset(sregs->interrupt_bitmap, 0, sizeof sregs->interrupt_bitmap);
  6279. if (vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft)
  6280. set_bit(vcpu->arch.interrupt.nr,
  6281. (unsigned long *)sregs->interrupt_bitmap);
  6282. return 0;
  6283. }
  6284. int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
  6285. struct kvm_mp_state *mp_state)
  6286. {
  6287. kvm_apic_accept_events(vcpu);
  6288. if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED &&
  6289. vcpu->arch.pv.pv_unhalted)
  6290. mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
  6291. else
  6292. mp_state->mp_state = vcpu->arch.mp_state;
  6293. return 0;
  6294. }
  6295. int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
  6296. struct kvm_mp_state *mp_state)
  6297. {
  6298. if (!lapic_in_kernel(vcpu) &&
  6299. mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
  6300. return -EINVAL;
  6301. /* INITs are latched while in SMM */
  6302. if ((is_smm(vcpu) || vcpu->arch.smi_pending) &&
  6303. (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
  6304. mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
  6305. return -EINVAL;
  6306. if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
  6307. vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
  6308. set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
  6309. } else
  6310. vcpu->arch.mp_state = mp_state->mp_state;
  6311. kvm_make_request(KVM_REQ_EVENT, vcpu);
  6312. return 0;
  6313. }
  6314. int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
  6315. int reason, bool has_error_code, u32 error_code)
  6316. {
  6317. struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
  6318. int ret;
  6319. init_emulate_ctxt(vcpu);
  6320. ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
  6321. has_error_code, error_code);
  6322. if (ret)
  6323. return EMULATE_FAIL;
  6324. kvm_rip_write(vcpu, ctxt->eip);
  6325. kvm_set_rflags(vcpu, ctxt->eflags);
  6326. kvm_make_request(KVM_REQ_EVENT, vcpu);
  6327. return EMULATE_DONE;
  6328. }
  6329. EXPORT_SYMBOL_GPL(kvm_task_switch);
  6330. int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
  6331. struct kvm_sregs *sregs)
  6332. {
  6333. struct msr_data apic_base_msr;
  6334. int mmu_reset_needed = 0;
  6335. int pending_vec, max_bits, idx;
  6336. struct desc_ptr dt;
  6337. if (!guest_cpuid_has_xsave(vcpu) && (sregs->cr4 & X86_CR4_OSXSAVE))
  6338. return -EINVAL;
  6339. dt.size = sregs->idt.limit;
  6340. dt.address = sregs->idt.base;
  6341. kvm_x86_ops->set_idt(vcpu, &dt);
  6342. dt.size = sregs->gdt.limit;
  6343. dt.address = sregs->gdt.base;
  6344. kvm_x86_ops->set_gdt(vcpu, &dt);
  6345. vcpu->arch.cr2 = sregs->cr2;
  6346. mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
  6347. vcpu->arch.cr3 = sregs->cr3;
  6348. __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
  6349. kvm_set_cr8(vcpu, sregs->cr8);
  6350. mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
  6351. kvm_x86_ops->set_efer(vcpu, sregs->efer);
  6352. apic_base_msr.data = sregs->apic_base;
  6353. apic_base_msr.host_initiated = true;
  6354. kvm_set_apic_base(vcpu, &apic_base_msr);
  6355. mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
  6356. kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
  6357. vcpu->arch.cr0 = sregs->cr0;
  6358. mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
  6359. kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
  6360. if (sregs->cr4 & (X86_CR4_OSXSAVE | X86_CR4_PKE))
  6361. kvm_update_cpuid(vcpu);
  6362. idx = srcu_read_lock(&vcpu->kvm->srcu);
  6363. if (!is_long_mode(vcpu) && is_pae(vcpu)) {
  6364. load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
  6365. mmu_reset_needed = 1;
  6366. }
  6367. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  6368. if (mmu_reset_needed)
  6369. kvm_mmu_reset_context(vcpu);
  6370. max_bits = KVM_NR_INTERRUPTS;
  6371. pending_vec = find_first_bit(
  6372. (const unsigned long *)sregs->interrupt_bitmap, max_bits);
  6373. if (pending_vec < max_bits) {
  6374. kvm_queue_interrupt(vcpu, pending_vec, false);
  6375. pr_debug("Set back pending irq %d\n", pending_vec);
  6376. }
  6377. kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
  6378. kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
  6379. kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
  6380. kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
  6381. kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
  6382. kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
  6383. kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
  6384. kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
  6385. update_cr8_intercept(vcpu);
  6386. /* Older userspace won't unhalt the vcpu on reset. */
  6387. if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
  6388. sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
  6389. !is_protmode(vcpu))
  6390. vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
  6391. kvm_make_request(KVM_REQ_EVENT, vcpu);
  6392. return 0;
  6393. }
  6394. int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
  6395. struct kvm_guest_debug *dbg)
  6396. {
  6397. unsigned long rflags;
  6398. int i, r;
  6399. if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
  6400. r = -EBUSY;
  6401. if (vcpu->arch.exception.pending)
  6402. goto out;
  6403. if (dbg->control & KVM_GUESTDBG_INJECT_DB)
  6404. kvm_queue_exception(vcpu, DB_VECTOR);
  6405. else
  6406. kvm_queue_exception(vcpu, BP_VECTOR);
  6407. }
  6408. /*
  6409. * Read rflags as long as potentially injected trace flags are still
  6410. * filtered out.
  6411. */
  6412. rflags = kvm_get_rflags(vcpu);
  6413. vcpu->guest_debug = dbg->control;
  6414. if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
  6415. vcpu->guest_debug = 0;
  6416. if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
  6417. for (i = 0; i < KVM_NR_DB_REGS; ++i)
  6418. vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
  6419. vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
  6420. } else {
  6421. for (i = 0; i < KVM_NR_DB_REGS; i++)
  6422. vcpu->arch.eff_db[i] = vcpu->arch.db[i];
  6423. }
  6424. kvm_update_dr7(vcpu);
  6425. if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
  6426. vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
  6427. get_segment_base(vcpu, VCPU_SREG_CS);
  6428. /*
  6429. * Trigger an rflags update that will inject or remove the trace
  6430. * flags.
  6431. */
  6432. kvm_set_rflags(vcpu, rflags);
  6433. kvm_x86_ops->update_bp_intercept(vcpu);
  6434. r = 0;
  6435. out:
  6436. return r;
  6437. }
  6438. /*
  6439. * Translate a guest virtual address to a guest physical address.
  6440. */
  6441. int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
  6442. struct kvm_translation *tr)
  6443. {
  6444. unsigned long vaddr = tr->linear_address;
  6445. gpa_t gpa;
  6446. int idx;
  6447. idx = srcu_read_lock(&vcpu->kvm->srcu);
  6448. gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
  6449. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  6450. tr->physical_address = gpa;
  6451. tr->valid = gpa != UNMAPPED_GVA;
  6452. tr->writeable = 1;
  6453. tr->usermode = 0;
  6454. return 0;
  6455. }
  6456. int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
  6457. {
  6458. struct fxregs_state *fxsave =
  6459. &vcpu->arch.guest_fpu.state.fxsave;
  6460. memcpy(fpu->fpr, fxsave->st_space, 128);
  6461. fpu->fcw = fxsave->cwd;
  6462. fpu->fsw = fxsave->swd;
  6463. fpu->ftwx = fxsave->twd;
  6464. fpu->last_opcode = fxsave->fop;
  6465. fpu->last_ip = fxsave->rip;
  6466. fpu->last_dp = fxsave->rdp;
  6467. memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
  6468. return 0;
  6469. }
  6470. int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
  6471. {
  6472. struct fxregs_state *fxsave =
  6473. &vcpu->arch.guest_fpu.state.fxsave;
  6474. memcpy(fxsave->st_space, fpu->fpr, 128);
  6475. fxsave->cwd = fpu->fcw;
  6476. fxsave->swd = fpu->fsw;
  6477. fxsave->twd = fpu->ftwx;
  6478. fxsave->fop = fpu->last_opcode;
  6479. fxsave->rip = fpu->last_ip;
  6480. fxsave->rdp = fpu->last_dp;
  6481. memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
  6482. return 0;
  6483. }
  6484. static void fx_init(struct kvm_vcpu *vcpu)
  6485. {
  6486. fpstate_init(&vcpu->arch.guest_fpu.state);
  6487. if (boot_cpu_has(X86_FEATURE_XSAVES))
  6488. vcpu->arch.guest_fpu.state.xsave.header.xcomp_bv =
  6489. host_xcr0 | XSTATE_COMPACTION_ENABLED;
  6490. /*
  6491. * Ensure guest xcr0 is valid for loading
  6492. */
  6493. vcpu->arch.xcr0 = XFEATURE_MASK_FP;
  6494. vcpu->arch.cr0 |= X86_CR0_ET;
  6495. }
  6496. void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
  6497. {
  6498. if (vcpu->guest_fpu_loaded)
  6499. return;
  6500. /*
  6501. * Restore all possible states in the guest,
  6502. * and assume host would use all available bits.
  6503. * Guest xcr0 would be loaded later.
  6504. */
  6505. vcpu->guest_fpu_loaded = 1;
  6506. __kernel_fpu_begin();
  6507. __copy_kernel_to_fpregs(&vcpu->arch.guest_fpu.state);
  6508. trace_kvm_fpu(1);
  6509. }
  6510. void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
  6511. {
  6512. if (!vcpu->guest_fpu_loaded)
  6513. return;
  6514. vcpu->guest_fpu_loaded = 0;
  6515. copy_fpregs_to_fpstate(&vcpu->arch.guest_fpu);
  6516. __kernel_fpu_end();
  6517. ++vcpu->stat.fpu_reload;
  6518. trace_kvm_fpu(0);
  6519. }
  6520. void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
  6521. {
  6522. void *wbinvd_dirty_mask = vcpu->arch.wbinvd_dirty_mask;
  6523. kvmclock_reset(vcpu);
  6524. kvm_x86_ops->vcpu_free(vcpu);
  6525. free_cpumask_var(wbinvd_dirty_mask);
  6526. }
  6527. struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
  6528. unsigned int id)
  6529. {
  6530. struct kvm_vcpu *vcpu;
  6531. if (check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
  6532. printk_once(KERN_WARNING
  6533. "kvm: SMP vm created on host with unstable TSC; "
  6534. "guest TSC will not be reliable\n");
  6535. vcpu = kvm_x86_ops->vcpu_create(kvm, id);
  6536. return vcpu;
  6537. }
  6538. int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
  6539. {
  6540. int r;
  6541. kvm_vcpu_mtrr_init(vcpu);
  6542. r = vcpu_load(vcpu);
  6543. if (r)
  6544. return r;
  6545. kvm_vcpu_reset(vcpu, false);
  6546. kvm_mmu_setup(vcpu);
  6547. vcpu_put(vcpu);
  6548. return r;
  6549. }
  6550. void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
  6551. {
  6552. struct msr_data msr;
  6553. struct kvm *kvm = vcpu->kvm;
  6554. if (vcpu_load(vcpu))
  6555. return;
  6556. msr.data = 0x0;
  6557. msr.index = MSR_IA32_TSC;
  6558. msr.host_initiated = true;
  6559. kvm_write_tsc(vcpu, &msr);
  6560. vcpu_put(vcpu);
  6561. if (!kvmclock_periodic_sync)
  6562. return;
  6563. schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
  6564. KVMCLOCK_SYNC_PERIOD);
  6565. }
  6566. void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
  6567. {
  6568. int r;
  6569. vcpu->arch.apf.msr_val = 0;
  6570. r = vcpu_load(vcpu);
  6571. BUG_ON(r);
  6572. kvm_mmu_unload(vcpu);
  6573. vcpu_put(vcpu);
  6574. kvm_x86_ops->vcpu_free(vcpu);
  6575. }
  6576. void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
  6577. {
  6578. vcpu->arch.hflags = 0;
  6579. vcpu->arch.smi_pending = 0;
  6580. atomic_set(&vcpu->arch.nmi_queued, 0);
  6581. vcpu->arch.nmi_pending = 0;
  6582. vcpu->arch.nmi_injected = false;
  6583. kvm_clear_interrupt_queue(vcpu);
  6584. kvm_clear_exception_queue(vcpu);
  6585. memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
  6586. kvm_update_dr0123(vcpu);
  6587. vcpu->arch.dr6 = DR6_INIT;
  6588. kvm_update_dr6(vcpu);
  6589. vcpu->arch.dr7 = DR7_FIXED_1;
  6590. kvm_update_dr7(vcpu);
  6591. vcpu->arch.cr2 = 0;
  6592. kvm_make_request(KVM_REQ_EVENT, vcpu);
  6593. vcpu->arch.apf.msr_val = 0;
  6594. vcpu->arch.st.msr_val = 0;
  6595. kvmclock_reset(vcpu);
  6596. kvm_clear_async_pf_completion_queue(vcpu);
  6597. kvm_async_pf_hash_reset(vcpu);
  6598. vcpu->arch.apf.halted = false;
  6599. if (!init_event) {
  6600. kvm_pmu_reset(vcpu);
  6601. vcpu->arch.smbase = 0x30000;
  6602. vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
  6603. vcpu->arch.msr_misc_features_enables = 0;
  6604. }
  6605. memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
  6606. vcpu->arch.regs_avail = ~0;
  6607. vcpu->arch.regs_dirty = ~0;
  6608. kvm_x86_ops->vcpu_reset(vcpu, init_event);
  6609. }
  6610. void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
  6611. {
  6612. struct kvm_segment cs;
  6613. kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
  6614. cs.selector = vector << 8;
  6615. cs.base = vector << 12;
  6616. kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
  6617. kvm_rip_write(vcpu, 0);
  6618. }
  6619. int kvm_arch_hardware_enable(void)
  6620. {
  6621. struct kvm *kvm;
  6622. struct kvm_vcpu *vcpu;
  6623. int i;
  6624. int ret;
  6625. u64 local_tsc;
  6626. u64 max_tsc = 0;
  6627. bool stable, backwards_tsc = false;
  6628. kvm_shared_msr_cpu_online();
  6629. ret = kvm_x86_ops->hardware_enable();
  6630. if (ret != 0)
  6631. return ret;
  6632. local_tsc = rdtsc();
  6633. stable = !check_tsc_unstable();
  6634. list_for_each_entry(kvm, &vm_list, vm_list) {
  6635. kvm_for_each_vcpu(i, vcpu, kvm) {
  6636. if (!stable && vcpu->cpu == smp_processor_id())
  6637. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  6638. if (stable && vcpu->arch.last_host_tsc > local_tsc) {
  6639. backwards_tsc = true;
  6640. if (vcpu->arch.last_host_tsc > max_tsc)
  6641. max_tsc = vcpu->arch.last_host_tsc;
  6642. }
  6643. }
  6644. }
  6645. /*
  6646. * Sometimes, even reliable TSCs go backwards. This happens on
  6647. * platforms that reset TSC during suspend or hibernate actions, but
  6648. * maintain synchronization. We must compensate. Fortunately, we can
  6649. * detect that condition here, which happens early in CPU bringup,
  6650. * before any KVM threads can be running. Unfortunately, we can't
  6651. * bring the TSCs fully up to date with real time, as we aren't yet far
  6652. * enough into CPU bringup that we know how much real time has actually
  6653. * elapsed; our helper function, ktime_get_boot_ns() will be using boot
  6654. * variables that haven't been updated yet.
  6655. *
  6656. * So we simply find the maximum observed TSC above, then record the
  6657. * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
  6658. * the adjustment will be applied. Note that we accumulate
  6659. * adjustments, in case multiple suspend cycles happen before some VCPU
  6660. * gets a chance to run again. In the event that no KVM threads get a
  6661. * chance to run, we will miss the entire elapsed period, as we'll have
  6662. * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
  6663. * loose cycle time. This isn't too big a deal, since the loss will be
  6664. * uniform across all VCPUs (not to mention the scenario is extremely
  6665. * unlikely). It is possible that a second hibernate recovery happens
  6666. * much faster than a first, causing the observed TSC here to be
  6667. * smaller; this would require additional padding adjustment, which is
  6668. * why we set last_host_tsc to the local tsc observed here.
  6669. *
  6670. * N.B. - this code below runs only on platforms with reliable TSC,
  6671. * as that is the only way backwards_tsc is set above. Also note
  6672. * that this runs for ALL vcpus, which is not a bug; all VCPUs should
  6673. * have the same delta_cyc adjustment applied if backwards_tsc
  6674. * is detected. Note further, this adjustment is only done once,
  6675. * as we reset last_host_tsc on all VCPUs to stop this from being
  6676. * called multiple times (one for each physical CPU bringup).
  6677. *
  6678. * Platforms with unreliable TSCs don't have to deal with this, they
  6679. * will be compensated by the logic in vcpu_load, which sets the TSC to
  6680. * catchup mode. This will catchup all VCPUs to real time, but cannot
  6681. * guarantee that they stay in perfect synchronization.
  6682. */
  6683. if (backwards_tsc) {
  6684. u64 delta_cyc = max_tsc - local_tsc;
  6685. backwards_tsc_observed = true;
  6686. list_for_each_entry(kvm, &vm_list, vm_list) {
  6687. kvm_for_each_vcpu(i, vcpu, kvm) {
  6688. vcpu->arch.tsc_offset_adjustment += delta_cyc;
  6689. vcpu->arch.last_host_tsc = local_tsc;
  6690. kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
  6691. }
  6692. /*
  6693. * We have to disable TSC offset matching.. if you were
  6694. * booting a VM while issuing an S4 host suspend....
  6695. * you may have some problem. Solving this issue is
  6696. * left as an exercise to the reader.
  6697. */
  6698. kvm->arch.last_tsc_nsec = 0;
  6699. kvm->arch.last_tsc_write = 0;
  6700. }
  6701. }
  6702. return 0;
  6703. }
  6704. void kvm_arch_hardware_disable(void)
  6705. {
  6706. kvm_x86_ops->hardware_disable();
  6707. drop_user_return_notifiers();
  6708. }
  6709. int kvm_arch_hardware_setup(void)
  6710. {
  6711. int r;
  6712. r = kvm_x86_ops->hardware_setup();
  6713. if (r != 0)
  6714. return r;
  6715. if (kvm_has_tsc_control) {
  6716. /*
  6717. * Make sure the user can only configure tsc_khz values that
  6718. * fit into a signed integer.
  6719. * A min value is not calculated needed because it will always
  6720. * be 1 on all machines.
  6721. */
  6722. u64 max = min(0x7fffffffULL,
  6723. __scale_tsc(kvm_max_tsc_scaling_ratio, tsc_khz));
  6724. kvm_max_guest_tsc_khz = max;
  6725. kvm_default_tsc_scaling_ratio = 1ULL << kvm_tsc_scaling_ratio_frac_bits;
  6726. }
  6727. kvm_init_msr_list();
  6728. return 0;
  6729. }
  6730. void kvm_arch_hardware_unsetup(void)
  6731. {
  6732. kvm_x86_ops->hardware_unsetup();
  6733. }
  6734. void kvm_arch_check_processor_compat(void *rtn)
  6735. {
  6736. kvm_x86_ops->check_processor_compatibility(rtn);
  6737. }
  6738. bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
  6739. {
  6740. return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
  6741. }
  6742. EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
  6743. bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
  6744. {
  6745. return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
  6746. }
  6747. struct static_key kvm_no_apic_vcpu __read_mostly;
  6748. EXPORT_SYMBOL_GPL(kvm_no_apic_vcpu);
  6749. int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
  6750. {
  6751. struct page *page;
  6752. struct kvm *kvm;
  6753. int r;
  6754. BUG_ON(vcpu->kvm == NULL);
  6755. kvm = vcpu->kvm;
  6756. vcpu->arch.apicv_active = kvm_x86_ops->get_enable_apicv();
  6757. vcpu->arch.pv.pv_unhalted = false;
  6758. vcpu->arch.emulate_ctxt.ops = &emulate_ops;
  6759. if (!irqchip_in_kernel(kvm) || kvm_vcpu_is_reset_bsp(vcpu))
  6760. vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
  6761. else
  6762. vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
  6763. page = alloc_page(GFP_KERNEL | __GFP_ZERO);
  6764. if (!page) {
  6765. r = -ENOMEM;
  6766. goto fail;
  6767. }
  6768. vcpu->arch.pio_data = page_address(page);
  6769. kvm_set_tsc_khz(vcpu, max_tsc_khz);
  6770. r = kvm_mmu_create(vcpu);
  6771. if (r < 0)
  6772. goto fail_free_pio_data;
  6773. if (irqchip_in_kernel(kvm)) {
  6774. r = kvm_create_lapic(vcpu);
  6775. if (r < 0)
  6776. goto fail_mmu_destroy;
  6777. } else
  6778. static_key_slow_inc(&kvm_no_apic_vcpu);
  6779. vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
  6780. GFP_KERNEL);
  6781. if (!vcpu->arch.mce_banks) {
  6782. r = -ENOMEM;
  6783. goto fail_free_lapic;
  6784. }
  6785. vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
  6786. if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL)) {
  6787. r = -ENOMEM;
  6788. goto fail_free_mce_banks;
  6789. }
  6790. fx_init(vcpu);
  6791. vcpu->arch.ia32_tsc_adjust_msr = 0x0;
  6792. vcpu->arch.pv_time_enabled = false;
  6793. vcpu->arch.guest_supported_xcr0 = 0;
  6794. vcpu->arch.guest_xstate_size = XSAVE_HDR_SIZE + XSAVE_HDR_OFFSET;
  6795. vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
  6796. vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
  6797. kvm_async_pf_hash_reset(vcpu);
  6798. kvm_pmu_init(vcpu);
  6799. vcpu->arch.pending_external_vector = -1;
  6800. kvm_hv_vcpu_init(vcpu);
  6801. return 0;
  6802. fail_free_mce_banks:
  6803. kfree(vcpu->arch.mce_banks);
  6804. fail_free_lapic:
  6805. kvm_free_lapic(vcpu);
  6806. fail_mmu_destroy:
  6807. kvm_mmu_destroy(vcpu);
  6808. fail_free_pio_data:
  6809. free_page((unsigned long)vcpu->arch.pio_data);
  6810. fail:
  6811. return r;
  6812. }
  6813. void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
  6814. {
  6815. int idx;
  6816. kvm_hv_vcpu_uninit(vcpu);
  6817. kvm_pmu_destroy(vcpu);
  6818. kfree(vcpu->arch.mce_banks);
  6819. kvm_free_lapic(vcpu);
  6820. idx = srcu_read_lock(&vcpu->kvm->srcu);
  6821. kvm_mmu_destroy(vcpu);
  6822. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  6823. free_page((unsigned long)vcpu->arch.pio_data);
  6824. if (!lapic_in_kernel(vcpu))
  6825. static_key_slow_dec(&kvm_no_apic_vcpu);
  6826. }
  6827. void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
  6828. {
  6829. kvm_x86_ops->sched_in(vcpu, cpu);
  6830. }
  6831. int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
  6832. {
  6833. if (type)
  6834. return -EINVAL;
  6835. INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
  6836. INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
  6837. INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
  6838. INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
  6839. atomic_set(&kvm->arch.noncoherent_dma_count, 0);
  6840. /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
  6841. set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
  6842. /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
  6843. set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
  6844. &kvm->arch.irq_sources_bitmap);
  6845. raw_spin_lock_init(&kvm->arch.tsc_write_lock);
  6846. mutex_init(&kvm->arch.apic_map_lock);
  6847. mutex_init(&kvm->arch.hyperv.hv_lock);
  6848. spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
  6849. kvm->arch.kvmclock_offset = -ktime_get_boot_ns();
  6850. pvclock_update_vm_gtod_copy(kvm);
  6851. INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
  6852. INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
  6853. kvm_page_track_init(kvm);
  6854. kvm_mmu_init_vm(kvm);
  6855. if (kvm_x86_ops->vm_init)
  6856. return kvm_x86_ops->vm_init(kvm);
  6857. return 0;
  6858. }
  6859. static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
  6860. {
  6861. int r;
  6862. r = vcpu_load(vcpu);
  6863. BUG_ON(r);
  6864. kvm_mmu_unload(vcpu);
  6865. vcpu_put(vcpu);
  6866. }
  6867. static void kvm_free_vcpus(struct kvm *kvm)
  6868. {
  6869. unsigned int i;
  6870. struct kvm_vcpu *vcpu;
  6871. /*
  6872. * Unpin any mmu pages first.
  6873. */
  6874. kvm_for_each_vcpu(i, vcpu, kvm) {
  6875. kvm_clear_async_pf_completion_queue(vcpu);
  6876. kvm_unload_vcpu_mmu(vcpu);
  6877. }
  6878. kvm_for_each_vcpu(i, vcpu, kvm)
  6879. kvm_arch_vcpu_free(vcpu);
  6880. mutex_lock(&kvm->lock);
  6881. for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
  6882. kvm->vcpus[i] = NULL;
  6883. atomic_set(&kvm->online_vcpus, 0);
  6884. mutex_unlock(&kvm->lock);
  6885. }
  6886. void kvm_arch_sync_events(struct kvm *kvm)
  6887. {
  6888. cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
  6889. cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
  6890. kvm_free_pit(kvm);
  6891. }
  6892. int __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
  6893. {
  6894. int i, r;
  6895. unsigned long hva;
  6896. struct kvm_memslots *slots = kvm_memslots(kvm);
  6897. struct kvm_memory_slot *slot, old;
  6898. /* Called with kvm->slots_lock held. */
  6899. if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
  6900. return -EINVAL;
  6901. slot = id_to_memslot(slots, id);
  6902. if (size) {
  6903. if (slot->npages)
  6904. return -EEXIST;
  6905. /*
  6906. * MAP_SHARED to prevent internal slot pages from being moved
  6907. * by fork()/COW.
  6908. */
  6909. hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
  6910. MAP_SHARED | MAP_ANONYMOUS, 0);
  6911. if (IS_ERR((void *)hva))
  6912. return PTR_ERR((void *)hva);
  6913. } else {
  6914. if (!slot->npages)
  6915. return 0;
  6916. hva = 0;
  6917. }
  6918. old = *slot;
  6919. for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
  6920. struct kvm_userspace_memory_region m;
  6921. m.slot = id | (i << 16);
  6922. m.flags = 0;
  6923. m.guest_phys_addr = gpa;
  6924. m.userspace_addr = hva;
  6925. m.memory_size = size;
  6926. r = __kvm_set_memory_region(kvm, &m);
  6927. if (r < 0)
  6928. return r;
  6929. }
  6930. if (!size) {
  6931. r = vm_munmap(old.userspace_addr, old.npages * PAGE_SIZE);
  6932. WARN_ON(r < 0);
  6933. }
  6934. return 0;
  6935. }
  6936. EXPORT_SYMBOL_GPL(__x86_set_memory_region);
  6937. int x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
  6938. {
  6939. int r;
  6940. mutex_lock(&kvm->slots_lock);
  6941. r = __x86_set_memory_region(kvm, id, gpa, size);
  6942. mutex_unlock(&kvm->slots_lock);
  6943. return r;
  6944. }
  6945. EXPORT_SYMBOL_GPL(x86_set_memory_region);
  6946. void kvm_arch_destroy_vm(struct kvm *kvm)
  6947. {
  6948. if (current->mm == kvm->mm) {
  6949. /*
  6950. * Free memory regions allocated on behalf of userspace,
  6951. * unless the the memory map has changed due to process exit
  6952. * or fd copying.
  6953. */
  6954. x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT, 0, 0);
  6955. x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT, 0, 0);
  6956. x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
  6957. }
  6958. if (kvm_x86_ops->vm_destroy)
  6959. kvm_x86_ops->vm_destroy(kvm);
  6960. kvm_pic_destroy(kvm);
  6961. kvm_ioapic_destroy(kvm);
  6962. kvm_free_vcpus(kvm);
  6963. kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
  6964. kvm_mmu_uninit_vm(kvm);
  6965. kvm_page_track_cleanup(kvm);
  6966. }
  6967. void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *free,
  6968. struct kvm_memory_slot *dont)
  6969. {
  6970. int i;
  6971. for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
  6972. if (!dont || free->arch.rmap[i] != dont->arch.rmap[i]) {
  6973. kvfree(free->arch.rmap[i]);
  6974. free->arch.rmap[i] = NULL;
  6975. }
  6976. if (i == 0)
  6977. continue;
  6978. if (!dont || free->arch.lpage_info[i - 1] !=
  6979. dont->arch.lpage_info[i - 1]) {
  6980. kvfree(free->arch.lpage_info[i - 1]);
  6981. free->arch.lpage_info[i - 1] = NULL;
  6982. }
  6983. }
  6984. kvm_page_track_free_memslot(free, dont);
  6985. }
  6986. int kvm_arch_create_memslot(struct kvm *kvm, struct kvm_memory_slot *slot,
  6987. unsigned long npages)
  6988. {
  6989. int i;
  6990. for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
  6991. struct kvm_lpage_info *linfo;
  6992. unsigned long ugfn;
  6993. int lpages;
  6994. int level = i + 1;
  6995. lpages = gfn_to_index(slot->base_gfn + npages - 1,
  6996. slot->base_gfn, level) + 1;
  6997. slot->arch.rmap[i] =
  6998. kvzalloc(lpages * sizeof(*slot->arch.rmap[i]), GFP_KERNEL);
  6999. if (!slot->arch.rmap[i])
  7000. goto out_free;
  7001. if (i == 0)
  7002. continue;
  7003. linfo = kvzalloc(lpages * sizeof(*linfo), GFP_KERNEL);
  7004. if (!linfo)
  7005. goto out_free;
  7006. slot->arch.lpage_info[i - 1] = linfo;
  7007. if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
  7008. linfo[0].disallow_lpage = 1;
  7009. if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
  7010. linfo[lpages - 1].disallow_lpage = 1;
  7011. ugfn = slot->userspace_addr >> PAGE_SHIFT;
  7012. /*
  7013. * If the gfn and userspace address are not aligned wrt each
  7014. * other, or if explicitly asked to, disable large page
  7015. * support for this slot
  7016. */
  7017. if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||
  7018. !kvm_largepages_enabled()) {
  7019. unsigned long j;
  7020. for (j = 0; j < lpages; ++j)
  7021. linfo[j].disallow_lpage = 1;
  7022. }
  7023. }
  7024. if (kvm_page_track_create_memslot(slot, npages))
  7025. goto out_free;
  7026. return 0;
  7027. out_free:
  7028. for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
  7029. kvfree(slot->arch.rmap[i]);
  7030. slot->arch.rmap[i] = NULL;
  7031. if (i == 0)
  7032. continue;
  7033. kvfree(slot->arch.lpage_info[i - 1]);
  7034. slot->arch.lpage_info[i - 1] = NULL;
  7035. }
  7036. return -ENOMEM;
  7037. }
  7038. void kvm_arch_memslots_updated(struct kvm *kvm, struct kvm_memslots *slots)
  7039. {
  7040. /*
  7041. * memslots->generation has been incremented.
  7042. * mmio generation may have reached its maximum value.
  7043. */
  7044. kvm_mmu_invalidate_mmio_sptes(kvm, slots);
  7045. }
  7046. int kvm_arch_prepare_memory_region(struct kvm *kvm,
  7047. struct kvm_memory_slot *memslot,
  7048. const struct kvm_userspace_memory_region *mem,
  7049. enum kvm_mr_change change)
  7050. {
  7051. return 0;
  7052. }
  7053. static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
  7054. struct kvm_memory_slot *new)
  7055. {
  7056. /* Still write protect RO slot */
  7057. if (new->flags & KVM_MEM_READONLY) {
  7058. kvm_mmu_slot_remove_write_access(kvm, new);
  7059. return;
  7060. }
  7061. /*
  7062. * Call kvm_x86_ops dirty logging hooks when they are valid.
  7063. *
  7064. * kvm_x86_ops->slot_disable_log_dirty is called when:
  7065. *
  7066. * - KVM_MR_CREATE with dirty logging is disabled
  7067. * - KVM_MR_FLAGS_ONLY with dirty logging is disabled in new flag
  7068. *
  7069. * The reason is, in case of PML, we need to set D-bit for any slots
  7070. * with dirty logging disabled in order to eliminate unnecessary GPA
  7071. * logging in PML buffer (and potential PML buffer full VMEXT). This
  7072. * guarantees leaving PML enabled during guest's lifetime won't have
  7073. * any additonal overhead from PML when guest is running with dirty
  7074. * logging disabled for memory slots.
  7075. *
  7076. * kvm_x86_ops->slot_enable_log_dirty is called when switching new slot
  7077. * to dirty logging mode.
  7078. *
  7079. * If kvm_x86_ops dirty logging hooks are invalid, use write protect.
  7080. *
  7081. * In case of write protect:
  7082. *
  7083. * Write protect all pages for dirty logging.
  7084. *
  7085. * All the sptes including the large sptes which point to this
  7086. * slot are set to readonly. We can not create any new large
  7087. * spte on this slot until the end of the logging.
  7088. *
  7089. * See the comments in fast_page_fault().
  7090. */
  7091. if (new->flags & KVM_MEM_LOG_DIRTY_PAGES) {
  7092. if (kvm_x86_ops->slot_enable_log_dirty)
  7093. kvm_x86_ops->slot_enable_log_dirty(kvm, new);
  7094. else
  7095. kvm_mmu_slot_remove_write_access(kvm, new);
  7096. } else {
  7097. if (kvm_x86_ops->slot_disable_log_dirty)
  7098. kvm_x86_ops->slot_disable_log_dirty(kvm, new);
  7099. }
  7100. }
  7101. void kvm_arch_commit_memory_region(struct kvm *kvm,
  7102. const struct kvm_userspace_memory_region *mem,
  7103. const struct kvm_memory_slot *old,
  7104. const struct kvm_memory_slot *new,
  7105. enum kvm_mr_change change)
  7106. {
  7107. int nr_mmu_pages = 0;
  7108. if (!kvm->arch.n_requested_mmu_pages)
  7109. nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
  7110. if (nr_mmu_pages)
  7111. kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
  7112. /*
  7113. * Dirty logging tracks sptes in 4k granularity, meaning that large
  7114. * sptes have to be split. If live migration is successful, the guest
  7115. * in the source machine will be destroyed and large sptes will be
  7116. * created in the destination. However, if the guest continues to run
  7117. * in the source machine (for example if live migration fails), small
  7118. * sptes will remain around and cause bad performance.
  7119. *
  7120. * Scan sptes if dirty logging has been stopped, dropping those
  7121. * which can be collapsed into a single large-page spte. Later
  7122. * page faults will create the large-page sptes.
  7123. */
  7124. if ((change != KVM_MR_DELETE) &&
  7125. (old->flags & KVM_MEM_LOG_DIRTY_PAGES) &&
  7126. !(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
  7127. kvm_mmu_zap_collapsible_sptes(kvm, new);
  7128. /*
  7129. * Set up write protection and/or dirty logging for the new slot.
  7130. *
  7131. * For KVM_MR_DELETE and KVM_MR_MOVE, the shadow pages of old slot have
  7132. * been zapped so no dirty logging staff is needed for old slot. For
  7133. * KVM_MR_FLAGS_ONLY, the old slot is essentially the same one as the
  7134. * new and it's also covered when dealing with the new slot.
  7135. *
  7136. * FIXME: const-ify all uses of struct kvm_memory_slot.
  7137. */
  7138. if (change != KVM_MR_DELETE)
  7139. kvm_mmu_slot_apply_flags(kvm, (struct kvm_memory_slot *) new);
  7140. }
  7141. void kvm_arch_flush_shadow_all(struct kvm *kvm)
  7142. {
  7143. kvm_mmu_invalidate_zap_all_pages(kvm);
  7144. }
  7145. void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
  7146. struct kvm_memory_slot *slot)
  7147. {
  7148. kvm_page_track_flush_slot(kvm, slot);
  7149. }
  7150. static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
  7151. {
  7152. if (!list_empty_careful(&vcpu->async_pf.done))
  7153. return true;
  7154. if (kvm_apic_has_events(vcpu))
  7155. return true;
  7156. if (vcpu->arch.pv.pv_unhalted)
  7157. return true;
  7158. if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
  7159. (vcpu->arch.nmi_pending &&
  7160. kvm_x86_ops->nmi_allowed(vcpu)))
  7161. return true;
  7162. if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
  7163. (vcpu->arch.smi_pending && !is_smm(vcpu)))
  7164. return true;
  7165. if (kvm_arch_interrupt_allowed(vcpu) &&
  7166. kvm_cpu_has_interrupt(vcpu))
  7167. return true;
  7168. if (kvm_hv_has_stimer_pending(vcpu))
  7169. return true;
  7170. return false;
  7171. }
  7172. int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
  7173. {
  7174. return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
  7175. }
  7176. int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
  7177. {
  7178. return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
  7179. }
  7180. int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
  7181. {
  7182. return kvm_x86_ops->interrupt_allowed(vcpu);
  7183. }
  7184. unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
  7185. {
  7186. if (is_64_bit_mode(vcpu))
  7187. return kvm_rip_read(vcpu);
  7188. return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
  7189. kvm_rip_read(vcpu));
  7190. }
  7191. EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
  7192. bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
  7193. {
  7194. return kvm_get_linear_rip(vcpu) == linear_rip;
  7195. }
  7196. EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
  7197. unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
  7198. {
  7199. unsigned long rflags;
  7200. rflags = kvm_x86_ops->get_rflags(vcpu);
  7201. if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
  7202. rflags &= ~X86_EFLAGS_TF;
  7203. return rflags;
  7204. }
  7205. EXPORT_SYMBOL_GPL(kvm_get_rflags);
  7206. static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
  7207. {
  7208. if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
  7209. kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
  7210. rflags |= X86_EFLAGS_TF;
  7211. kvm_x86_ops->set_rflags(vcpu, rflags);
  7212. }
  7213. void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
  7214. {
  7215. __kvm_set_rflags(vcpu, rflags);
  7216. kvm_make_request(KVM_REQ_EVENT, vcpu);
  7217. }
  7218. EXPORT_SYMBOL_GPL(kvm_set_rflags);
  7219. void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
  7220. {
  7221. int r;
  7222. if ((vcpu->arch.mmu.direct_map != work->arch.direct_map) ||
  7223. work->wakeup_all)
  7224. return;
  7225. r = kvm_mmu_reload(vcpu);
  7226. if (unlikely(r))
  7227. return;
  7228. if (!vcpu->arch.mmu.direct_map &&
  7229. work->arch.cr3 != vcpu->arch.mmu.get_cr3(vcpu))
  7230. return;
  7231. vcpu->arch.mmu.page_fault(vcpu, work->gva, 0, true);
  7232. }
  7233. static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
  7234. {
  7235. return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
  7236. }
  7237. static inline u32 kvm_async_pf_next_probe(u32 key)
  7238. {
  7239. return (key + 1) & (roundup_pow_of_two(ASYNC_PF_PER_VCPU) - 1);
  7240. }
  7241. static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
  7242. {
  7243. u32 key = kvm_async_pf_hash_fn(gfn);
  7244. while (vcpu->arch.apf.gfns[key] != ~0)
  7245. key = kvm_async_pf_next_probe(key);
  7246. vcpu->arch.apf.gfns[key] = gfn;
  7247. }
  7248. static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
  7249. {
  7250. int i;
  7251. u32 key = kvm_async_pf_hash_fn(gfn);
  7252. for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU) &&
  7253. (vcpu->arch.apf.gfns[key] != gfn &&
  7254. vcpu->arch.apf.gfns[key] != ~0); i++)
  7255. key = kvm_async_pf_next_probe(key);
  7256. return key;
  7257. }
  7258. bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
  7259. {
  7260. return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
  7261. }
  7262. static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
  7263. {
  7264. u32 i, j, k;
  7265. i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
  7266. while (true) {
  7267. vcpu->arch.apf.gfns[i] = ~0;
  7268. do {
  7269. j = kvm_async_pf_next_probe(j);
  7270. if (vcpu->arch.apf.gfns[j] == ~0)
  7271. return;
  7272. k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
  7273. /*
  7274. * k lies cyclically in ]i,j]
  7275. * | i.k.j |
  7276. * |....j i.k.| or |.k..j i...|
  7277. */
  7278. } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
  7279. vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
  7280. i = j;
  7281. }
  7282. }
  7283. static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
  7284. {
  7285. return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
  7286. sizeof(val));
  7287. }
  7288. void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
  7289. struct kvm_async_pf *work)
  7290. {
  7291. struct x86_exception fault;
  7292. trace_kvm_async_pf_not_present(work->arch.token, work->gva);
  7293. kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
  7294. if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
  7295. (vcpu->arch.apf.send_user_only &&
  7296. kvm_x86_ops->get_cpl(vcpu) == 0))
  7297. kvm_make_request(KVM_REQ_APF_HALT, vcpu);
  7298. else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
  7299. fault.vector = PF_VECTOR;
  7300. fault.error_code_valid = true;
  7301. fault.error_code = 0;
  7302. fault.nested_page_fault = false;
  7303. fault.address = work->arch.token;
  7304. kvm_inject_page_fault(vcpu, &fault);
  7305. }
  7306. }
  7307. void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
  7308. struct kvm_async_pf *work)
  7309. {
  7310. struct x86_exception fault;
  7311. if (work->wakeup_all)
  7312. work->arch.token = ~0; /* broadcast wakeup */
  7313. else
  7314. kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
  7315. trace_kvm_async_pf_ready(work->arch.token, work->gva);
  7316. if ((vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) &&
  7317. !apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
  7318. fault.vector = PF_VECTOR;
  7319. fault.error_code_valid = true;
  7320. fault.error_code = 0;
  7321. fault.nested_page_fault = false;
  7322. fault.address = work->arch.token;
  7323. kvm_inject_page_fault(vcpu, &fault);
  7324. }
  7325. vcpu->arch.apf.halted = false;
  7326. vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
  7327. }
  7328. bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu)
  7329. {
  7330. if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED))
  7331. return true;
  7332. else
  7333. return !kvm_event_needs_reinjection(vcpu) &&
  7334. kvm_x86_ops->interrupt_allowed(vcpu);
  7335. }
  7336. void kvm_arch_start_assignment(struct kvm *kvm)
  7337. {
  7338. atomic_inc(&kvm->arch.assigned_device_count);
  7339. }
  7340. EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
  7341. void kvm_arch_end_assignment(struct kvm *kvm)
  7342. {
  7343. atomic_dec(&kvm->arch.assigned_device_count);
  7344. }
  7345. EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
  7346. bool kvm_arch_has_assigned_device(struct kvm *kvm)
  7347. {
  7348. return atomic_read(&kvm->arch.assigned_device_count);
  7349. }
  7350. EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
  7351. void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
  7352. {
  7353. atomic_inc(&kvm->arch.noncoherent_dma_count);
  7354. }
  7355. EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
  7356. void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
  7357. {
  7358. atomic_dec(&kvm->arch.noncoherent_dma_count);
  7359. }
  7360. EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
  7361. bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
  7362. {
  7363. return atomic_read(&kvm->arch.noncoherent_dma_count);
  7364. }
  7365. EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
  7366. bool kvm_arch_has_irq_bypass(void)
  7367. {
  7368. return kvm_x86_ops->update_pi_irte != NULL;
  7369. }
  7370. int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
  7371. struct irq_bypass_producer *prod)
  7372. {
  7373. struct kvm_kernel_irqfd *irqfd =
  7374. container_of(cons, struct kvm_kernel_irqfd, consumer);
  7375. irqfd->producer = prod;
  7376. return kvm_x86_ops->update_pi_irte(irqfd->kvm,
  7377. prod->irq, irqfd->gsi, 1);
  7378. }
  7379. void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
  7380. struct irq_bypass_producer *prod)
  7381. {
  7382. int ret;
  7383. struct kvm_kernel_irqfd *irqfd =
  7384. container_of(cons, struct kvm_kernel_irqfd, consumer);
  7385. WARN_ON(irqfd->producer != prod);
  7386. irqfd->producer = NULL;
  7387. /*
  7388. * When producer of consumer is unregistered, we change back to
  7389. * remapped mode, so we can re-use the current implementation
  7390. * when the irq is masked/disabled or the consumer side (KVM
  7391. * int this case doesn't want to receive the interrupts.
  7392. */
  7393. ret = kvm_x86_ops->update_pi_irte(irqfd->kvm, prod->irq, irqfd->gsi, 0);
  7394. if (ret)
  7395. printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
  7396. " fails: %d\n", irqfd->consumer.token, ret);
  7397. }
  7398. int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
  7399. uint32_t guest_irq, bool set)
  7400. {
  7401. if (!kvm_x86_ops->update_pi_irte)
  7402. return -EINVAL;
  7403. return kvm_x86_ops->update_pi_irte(kvm, host_irq, guest_irq, set);
  7404. }
  7405. bool kvm_vector_hashing_enabled(void)
  7406. {
  7407. return vector_hashing;
  7408. }
  7409. EXPORT_SYMBOL_GPL(kvm_vector_hashing_enabled);
  7410. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
  7411. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
  7412. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
  7413. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
  7414. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
  7415. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
  7416. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
  7417. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
  7418. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
  7419. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
  7420. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
  7421. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
  7422. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
  7423. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
  7424. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window);
  7425. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
  7426. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);
  7427. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
  7428. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);