x86.c 215 KB

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