x86.c 252 KB

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