x86.c 217 KB

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