x86.c 210 KB

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