kvm_main.c 165 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * Kernel-based Virtual Machine (KVM) Hypervisor
  4. *
  5. * Copyright (C) 2006 Qumranet, Inc.
  6. * Copyright 2010 Red Hat, Inc. and/or its affiliates.
  7. *
  8. * Authors:
  9. * Avi Kivity <avi@qumranet.com>
  10. * Yaniv Kamay <yaniv@qumranet.com>
  11. */
  12. #include <kvm/iodev.h>
  13. #include <linux/kvm_host.h>
  14. #include <linux/kvm.h>
  15. #include <linux/module.h>
  16. #include <linux/errno.h>
  17. #include <linux/percpu.h>
  18. #include <linux/mm.h>
  19. #include <linux/miscdevice.h>
  20. #include <linux/vmalloc.h>
  21. #include <linux/reboot.h>
  22. #include <linux/debugfs.h>
  23. #include <linux/highmem.h>
  24. #include <linux/file.h>
  25. #include <linux/syscore_ops.h>
  26. #include <linux/cpu.h>
  27. #include <linux/sched/signal.h>
  28. #include <linux/sched/mm.h>
  29. #include <linux/sched/stat.h>
  30. #include <linux/cpumask.h>
  31. #include <linux/smp.h>
  32. #include <linux/anon_inodes.h>
  33. #include <linux/profile.h>
  34. #include <linux/kvm_para.h>
  35. #include <linux/pagemap.h>
  36. #include <linux/mman.h>
  37. #include <linux/swap.h>
  38. #include <linux/bitops.h>
  39. #include <linux/spinlock.h>
  40. #include <linux/compat.h>
  41. #include <linux/srcu.h>
  42. #include <linux/hugetlb.h>
  43. #include <linux/slab.h>
  44. #include <linux/sort.h>
  45. #include <linux/bsearch.h>
  46. #include <linux/io.h>
  47. #include <linux/lockdep.h>
  48. #include <linux/kthread.h>
  49. #include <linux/suspend.h>
  50. #include <asm/processor.h>
  51. #include <asm/ioctl.h>
  52. #include <linux/uaccess.h>
  53. #include "coalesced_mmio.h"
  54. #include "async_pf.h"
  55. #include "kvm_mm.h"
  56. #include "vfio.h"
  57. #include <trace/events/ipi.h>
  58. #define CREATE_TRACE_POINTS
  59. #include <trace/events/kvm.h>
  60. #include <linux/kvm_dirty_ring.h>
  61. /* Worst case buffer size needed for holding an integer. */
  62. #define ITOA_MAX_LEN 12
  63. MODULE_AUTHOR("Qumranet");
  64. MODULE_DESCRIPTION("Kernel-based Virtual Machine (KVM) Hypervisor");
  65. MODULE_LICENSE("GPL");
  66. /* Architectures should define their poll value according to the halt latency */
  67. unsigned int halt_poll_ns = KVM_HALT_POLL_NS_DEFAULT;
  68. module_param(halt_poll_ns, uint, 0644);
  69. EXPORT_SYMBOL_GPL(halt_poll_ns);
  70. /* Default doubles per-vcpu halt_poll_ns. */
  71. unsigned int halt_poll_ns_grow = 2;
  72. module_param(halt_poll_ns_grow, uint, 0644);
  73. EXPORT_SYMBOL_GPL(halt_poll_ns_grow);
  74. /* The start value to grow halt_poll_ns from */
  75. unsigned int halt_poll_ns_grow_start = 10000; /* 10us */
  76. module_param(halt_poll_ns_grow_start, uint, 0644);
  77. EXPORT_SYMBOL_GPL(halt_poll_ns_grow_start);
  78. /* Default halves per-vcpu halt_poll_ns. */
  79. unsigned int halt_poll_ns_shrink = 2;
  80. module_param(halt_poll_ns_shrink, uint, 0644);
  81. EXPORT_SYMBOL_GPL(halt_poll_ns_shrink);
  82. /*
  83. * Ordering of locks:
  84. *
  85. * kvm->lock --> kvm->slots_lock --> kvm->irq_lock
  86. */
  87. DEFINE_MUTEX(kvm_lock);
  88. LIST_HEAD(vm_list);
  89. static struct kmem_cache *kvm_vcpu_cache;
  90. static __read_mostly struct preempt_ops kvm_preempt_ops;
  91. static DEFINE_PER_CPU(struct kvm_vcpu *, kvm_running_vcpu);
  92. static struct dentry *kvm_debugfs_dir;
  93. static const struct file_operations stat_fops_per_vm;
  94. static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
  95. unsigned long arg);
  96. #ifdef CONFIG_KVM_COMPAT
  97. static long kvm_vcpu_compat_ioctl(struct file *file, unsigned int ioctl,
  98. unsigned long arg);
  99. #define KVM_COMPAT(c) .compat_ioctl = (c)
  100. #else
  101. /*
  102. * For architectures that don't implement a compat infrastructure,
  103. * adopt a double line of defense:
  104. * - Prevent a compat task from opening /dev/kvm
  105. * - If the open has been done by a 64bit task, and the KVM fd
  106. * passed to a compat task, let the ioctls fail.
  107. */
  108. static long kvm_no_compat_ioctl(struct file *file, unsigned int ioctl,
  109. unsigned long arg) { return -EINVAL; }
  110. static int kvm_no_compat_open(struct inode *inode, struct file *file)
  111. {
  112. return is_compat_task() ? -ENODEV : 0;
  113. }
  114. #define KVM_COMPAT(c) .compat_ioctl = kvm_no_compat_ioctl, \
  115. .open = kvm_no_compat_open
  116. #endif
  117. static int kvm_enable_virtualization(void);
  118. static void kvm_disable_virtualization(void);
  119. static void kvm_io_bus_destroy(struct kvm_io_bus *bus);
  120. #define KVM_EVENT_CREATE_VM 0
  121. #define KVM_EVENT_DESTROY_VM 1
  122. static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm);
  123. static unsigned long long kvm_createvm_count;
  124. static unsigned long long kvm_active_vms;
  125. static DEFINE_PER_CPU(cpumask_var_t, cpu_kick_mask);
  126. __weak void kvm_arch_guest_memory_reclaimed(struct kvm *kvm)
  127. {
  128. }
  129. bool kvm_is_zone_device_page(struct page *page)
  130. {
  131. /*
  132. * The metadata used by is_zone_device_page() to determine whether or
  133. * not a page is ZONE_DEVICE is guaranteed to be valid if and only if
  134. * the device has been pinned, e.g. by get_user_pages(). WARN if the
  135. * page_count() is zero to help detect bad usage of this helper.
  136. */
  137. if (WARN_ON_ONCE(!page_count(page)))
  138. return false;
  139. return is_zone_device_page(page);
  140. }
  141. /*
  142. * Returns a 'struct page' if the pfn is "valid" and backed by a refcounted
  143. * page, NULL otherwise. Note, the list of refcounted PG_reserved page types
  144. * is likely incomplete, it has been compiled purely through people wanting to
  145. * back guest with a certain type of memory and encountering issues.
  146. */
  147. struct page *kvm_pfn_to_refcounted_page(kvm_pfn_t pfn)
  148. {
  149. struct page *page;
  150. if (!pfn_valid(pfn))
  151. return NULL;
  152. page = pfn_to_page(pfn);
  153. if (!PageReserved(page))
  154. return page;
  155. /* The ZERO_PAGE(s) is marked PG_reserved, but is refcounted. */
  156. if (is_zero_pfn(pfn))
  157. return page;
  158. /*
  159. * ZONE_DEVICE pages currently set PG_reserved, but from a refcounting
  160. * perspective they are "normal" pages, albeit with slightly different
  161. * usage rules.
  162. */
  163. if (kvm_is_zone_device_page(page))
  164. return page;
  165. return NULL;
  166. }
  167. /*
  168. * Switches to specified vcpu, until a matching vcpu_put()
  169. */
  170. void vcpu_load(struct kvm_vcpu *vcpu)
  171. {
  172. int cpu = get_cpu();
  173. __this_cpu_write(kvm_running_vcpu, vcpu);
  174. preempt_notifier_register(&vcpu->preempt_notifier);
  175. kvm_arch_vcpu_load(vcpu, cpu);
  176. put_cpu();
  177. }
  178. EXPORT_SYMBOL_GPL(vcpu_load);
  179. void vcpu_put(struct kvm_vcpu *vcpu)
  180. {
  181. preempt_disable();
  182. kvm_arch_vcpu_put(vcpu);
  183. preempt_notifier_unregister(&vcpu->preempt_notifier);
  184. __this_cpu_write(kvm_running_vcpu, NULL);
  185. preempt_enable();
  186. }
  187. EXPORT_SYMBOL_GPL(vcpu_put);
  188. /* TODO: merge with kvm_arch_vcpu_should_kick */
  189. static bool kvm_request_needs_ipi(struct kvm_vcpu *vcpu, unsigned req)
  190. {
  191. int mode = kvm_vcpu_exiting_guest_mode(vcpu);
  192. /*
  193. * We need to wait for the VCPU to reenable interrupts and get out of
  194. * READING_SHADOW_PAGE_TABLES mode.
  195. */
  196. if (req & KVM_REQUEST_WAIT)
  197. return mode != OUTSIDE_GUEST_MODE;
  198. /*
  199. * Need to kick a running VCPU, but otherwise there is nothing to do.
  200. */
  201. return mode == IN_GUEST_MODE;
  202. }
  203. static void ack_kick(void *_completed)
  204. {
  205. }
  206. static inline bool kvm_kick_many_cpus(struct cpumask *cpus, bool wait)
  207. {
  208. if (cpumask_empty(cpus))
  209. return false;
  210. smp_call_function_many(cpus, ack_kick, NULL, wait);
  211. return true;
  212. }
  213. static void kvm_make_vcpu_request(struct kvm_vcpu *vcpu, unsigned int req,
  214. struct cpumask *tmp, int current_cpu)
  215. {
  216. int cpu;
  217. if (likely(!(req & KVM_REQUEST_NO_ACTION)))
  218. __kvm_make_request(req, vcpu);
  219. if (!(req & KVM_REQUEST_NO_WAKEUP) && kvm_vcpu_wake_up(vcpu))
  220. return;
  221. /*
  222. * Note, the vCPU could get migrated to a different pCPU at any point
  223. * after kvm_request_needs_ipi(), which could result in sending an IPI
  224. * to the previous pCPU. But, that's OK because the purpose of the IPI
  225. * is to ensure the vCPU returns to OUTSIDE_GUEST_MODE, which is
  226. * satisfied if the vCPU migrates. Entering READING_SHADOW_PAGE_TABLES
  227. * after this point is also OK, as the requirement is only that KVM wait
  228. * for vCPUs that were reading SPTEs _before_ any changes were
  229. * finalized. See kvm_vcpu_kick() for more details on handling requests.
  230. */
  231. if (kvm_request_needs_ipi(vcpu, req)) {
  232. cpu = READ_ONCE(vcpu->cpu);
  233. if (cpu != -1 && cpu != current_cpu)
  234. __cpumask_set_cpu(cpu, tmp);
  235. }
  236. }
  237. bool kvm_make_vcpus_request_mask(struct kvm *kvm, unsigned int req,
  238. unsigned long *vcpu_bitmap)
  239. {
  240. struct kvm_vcpu *vcpu;
  241. struct cpumask *cpus;
  242. int i, me;
  243. bool called;
  244. me = get_cpu();
  245. cpus = this_cpu_cpumask_var_ptr(cpu_kick_mask);
  246. cpumask_clear(cpus);
  247. for_each_set_bit(i, vcpu_bitmap, KVM_MAX_VCPUS) {
  248. vcpu = kvm_get_vcpu(kvm, i);
  249. if (!vcpu)
  250. continue;
  251. kvm_make_vcpu_request(vcpu, req, cpus, me);
  252. }
  253. called = kvm_kick_many_cpus(cpus, !!(req & KVM_REQUEST_WAIT));
  254. put_cpu();
  255. return called;
  256. }
  257. bool kvm_make_all_cpus_request(struct kvm *kvm, unsigned int req)
  258. {
  259. struct kvm_vcpu *vcpu;
  260. struct cpumask *cpus;
  261. unsigned long i;
  262. bool called;
  263. int me;
  264. me = get_cpu();
  265. cpus = this_cpu_cpumask_var_ptr(cpu_kick_mask);
  266. cpumask_clear(cpus);
  267. kvm_for_each_vcpu(i, vcpu, kvm)
  268. kvm_make_vcpu_request(vcpu, req, cpus, me);
  269. called = kvm_kick_many_cpus(cpus, !!(req & KVM_REQUEST_WAIT));
  270. put_cpu();
  271. return called;
  272. }
  273. EXPORT_SYMBOL_GPL(kvm_make_all_cpus_request);
  274. void kvm_flush_remote_tlbs(struct kvm *kvm)
  275. {
  276. ++kvm->stat.generic.remote_tlb_flush_requests;
  277. /*
  278. * We want to publish modifications to the page tables before reading
  279. * mode. Pairs with a memory barrier in arch-specific code.
  280. * - x86: smp_mb__after_srcu_read_unlock in vcpu_enter_guest
  281. * and smp_mb in walk_shadow_page_lockless_begin/end.
  282. * - powerpc: smp_mb in kvmppc_prepare_to_enter.
  283. *
  284. * There is already an smp_mb__after_atomic() before
  285. * kvm_make_all_cpus_request() reads vcpu->mode. We reuse that
  286. * barrier here.
  287. */
  288. if (!kvm_arch_flush_remote_tlbs(kvm)
  289. || kvm_make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH))
  290. ++kvm->stat.generic.remote_tlb_flush;
  291. }
  292. EXPORT_SYMBOL_GPL(kvm_flush_remote_tlbs);
  293. void kvm_flush_remote_tlbs_range(struct kvm *kvm, gfn_t gfn, u64 nr_pages)
  294. {
  295. if (!kvm_arch_flush_remote_tlbs_range(kvm, gfn, nr_pages))
  296. return;
  297. /*
  298. * Fall back to a flushing entire TLBs if the architecture range-based
  299. * TLB invalidation is unsupported or can't be performed for whatever
  300. * reason.
  301. */
  302. kvm_flush_remote_tlbs(kvm);
  303. }
  304. void kvm_flush_remote_tlbs_memslot(struct kvm *kvm,
  305. const struct kvm_memory_slot *memslot)
  306. {
  307. /*
  308. * All current use cases for flushing the TLBs for a specific memslot
  309. * are related to dirty logging, and many do the TLB flush out of
  310. * mmu_lock. The interaction between the various operations on memslot
  311. * must be serialized by slots_locks to ensure the TLB flush from one
  312. * operation is observed by any other operation on the same memslot.
  313. */
  314. lockdep_assert_held(&kvm->slots_lock);
  315. kvm_flush_remote_tlbs_range(kvm, memslot->base_gfn, memslot->npages);
  316. }
  317. static void kvm_flush_shadow_all(struct kvm *kvm)
  318. {
  319. kvm_arch_flush_shadow_all(kvm);
  320. kvm_arch_guest_memory_reclaimed(kvm);
  321. }
  322. #ifdef KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE
  323. static inline void *mmu_memory_cache_alloc_obj(struct kvm_mmu_memory_cache *mc,
  324. gfp_t gfp_flags)
  325. {
  326. void *page;
  327. gfp_flags |= mc->gfp_zero;
  328. if (mc->kmem_cache)
  329. return kmem_cache_alloc(mc->kmem_cache, gfp_flags);
  330. page = (void *)__get_free_page(gfp_flags);
  331. if (page && mc->init_value)
  332. memset64(page, mc->init_value, PAGE_SIZE / sizeof(u64));
  333. return page;
  334. }
  335. int __kvm_mmu_topup_memory_cache(struct kvm_mmu_memory_cache *mc, int capacity, int min)
  336. {
  337. gfp_t gfp = mc->gfp_custom ? mc->gfp_custom : GFP_KERNEL_ACCOUNT;
  338. void *obj;
  339. if (mc->nobjs >= min)
  340. return 0;
  341. if (unlikely(!mc->objects)) {
  342. if (WARN_ON_ONCE(!capacity))
  343. return -EIO;
  344. /*
  345. * Custom init values can be used only for page allocations,
  346. * and obviously conflict with __GFP_ZERO.
  347. */
  348. if (WARN_ON_ONCE(mc->init_value && (mc->kmem_cache || mc->gfp_zero)))
  349. return -EIO;
  350. mc->objects = kvmalloc_array(capacity, sizeof(void *), gfp);
  351. if (!mc->objects)
  352. return -ENOMEM;
  353. mc->capacity = capacity;
  354. }
  355. /* It is illegal to request a different capacity across topups. */
  356. if (WARN_ON_ONCE(mc->capacity != capacity))
  357. return -EIO;
  358. while (mc->nobjs < mc->capacity) {
  359. obj = mmu_memory_cache_alloc_obj(mc, gfp);
  360. if (!obj)
  361. return mc->nobjs >= min ? 0 : -ENOMEM;
  362. mc->objects[mc->nobjs++] = obj;
  363. }
  364. return 0;
  365. }
  366. int kvm_mmu_topup_memory_cache(struct kvm_mmu_memory_cache *mc, int min)
  367. {
  368. return __kvm_mmu_topup_memory_cache(mc, KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE, min);
  369. }
  370. int kvm_mmu_memory_cache_nr_free_objects(struct kvm_mmu_memory_cache *mc)
  371. {
  372. return mc->nobjs;
  373. }
  374. void kvm_mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc)
  375. {
  376. while (mc->nobjs) {
  377. if (mc->kmem_cache)
  378. kmem_cache_free(mc->kmem_cache, mc->objects[--mc->nobjs]);
  379. else
  380. free_page((unsigned long)mc->objects[--mc->nobjs]);
  381. }
  382. kvfree(mc->objects);
  383. mc->objects = NULL;
  384. mc->capacity = 0;
  385. }
  386. void *kvm_mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)
  387. {
  388. void *p;
  389. if (WARN_ON(!mc->nobjs))
  390. p = mmu_memory_cache_alloc_obj(mc, GFP_ATOMIC | __GFP_ACCOUNT);
  391. else
  392. p = mc->objects[--mc->nobjs];
  393. BUG_ON(!p);
  394. return p;
  395. }
  396. #endif
  397. static void kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
  398. {
  399. mutex_init(&vcpu->mutex);
  400. vcpu->cpu = -1;
  401. vcpu->kvm = kvm;
  402. vcpu->vcpu_id = id;
  403. vcpu->pid = NULL;
  404. #ifndef __KVM_HAVE_ARCH_WQP
  405. rcuwait_init(&vcpu->wait);
  406. #endif
  407. kvm_async_pf_vcpu_init(vcpu);
  408. kvm_vcpu_set_in_spin_loop(vcpu, false);
  409. kvm_vcpu_set_dy_eligible(vcpu, false);
  410. vcpu->preempted = false;
  411. vcpu->ready = false;
  412. preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
  413. vcpu->last_used_slot = NULL;
  414. /* Fill the stats id string for the vcpu */
  415. snprintf(vcpu->stats_id, sizeof(vcpu->stats_id), "kvm-%d/vcpu-%d",
  416. task_pid_nr(current), id);
  417. }
  418. static void kvm_vcpu_destroy(struct kvm_vcpu *vcpu)
  419. {
  420. kvm_arch_vcpu_destroy(vcpu);
  421. kvm_dirty_ring_free(&vcpu->dirty_ring);
  422. /*
  423. * No need for rcu_read_lock as VCPU_RUN is the only place that changes
  424. * the vcpu->pid pointer, and at destruction time all file descriptors
  425. * are already gone.
  426. */
  427. put_pid(rcu_dereference_protected(vcpu->pid, 1));
  428. free_page((unsigned long)vcpu->run);
  429. kmem_cache_free(kvm_vcpu_cache, vcpu);
  430. }
  431. void kvm_destroy_vcpus(struct kvm *kvm)
  432. {
  433. unsigned long i;
  434. struct kvm_vcpu *vcpu;
  435. kvm_for_each_vcpu(i, vcpu, kvm) {
  436. kvm_vcpu_destroy(vcpu);
  437. xa_erase(&kvm->vcpu_array, i);
  438. }
  439. atomic_set(&kvm->online_vcpus, 0);
  440. }
  441. EXPORT_SYMBOL_GPL(kvm_destroy_vcpus);
  442. #ifdef CONFIG_KVM_GENERIC_MMU_NOTIFIER
  443. static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
  444. {
  445. return container_of(mn, struct kvm, mmu_notifier);
  446. }
  447. typedef bool (*gfn_handler_t)(struct kvm *kvm, struct kvm_gfn_range *range);
  448. typedef void (*on_lock_fn_t)(struct kvm *kvm);
  449. struct kvm_mmu_notifier_range {
  450. /*
  451. * 64-bit addresses, as KVM notifiers can operate on host virtual
  452. * addresses (unsigned long) and guest physical addresses (64-bit).
  453. */
  454. u64 start;
  455. u64 end;
  456. union kvm_mmu_notifier_arg arg;
  457. gfn_handler_t handler;
  458. on_lock_fn_t on_lock;
  459. bool flush_on_ret;
  460. bool may_block;
  461. };
  462. /*
  463. * The inner-most helper returns a tuple containing the return value from the
  464. * arch- and action-specific handler, plus a flag indicating whether or not at
  465. * least one memslot was found, i.e. if the handler found guest memory.
  466. *
  467. * Note, most notifiers are averse to booleans, so even though KVM tracks the
  468. * return from arch code as a bool, outer helpers will cast it to an int. :-(
  469. */
  470. typedef struct kvm_mmu_notifier_return {
  471. bool ret;
  472. bool found_memslot;
  473. } kvm_mn_ret_t;
  474. /*
  475. * Use a dedicated stub instead of NULL to indicate that there is no callback
  476. * function/handler. The compiler technically can't guarantee that a real
  477. * function will have a non-zero address, and so it will generate code to
  478. * check for !NULL, whereas comparing against a stub will be elided at compile
  479. * time (unless the compiler is getting long in the tooth, e.g. gcc 4.9).
  480. */
  481. static void kvm_null_fn(void)
  482. {
  483. }
  484. #define IS_KVM_NULL_FN(fn) ((fn) == (void *)kvm_null_fn)
  485. /* Iterate over each memslot intersecting [start, last] (inclusive) range */
  486. #define kvm_for_each_memslot_in_hva_range(node, slots, start, last) \
  487. for (node = interval_tree_iter_first(&slots->hva_tree, start, last); \
  488. node; \
  489. node = interval_tree_iter_next(node, start, last)) \
  490. static __always_inline kvm_mn_ret_t __kvm_handle_hva_range(struct kvm *kvm,
  491. const struct kvm_mmu_notifier_range *range)
  492. {
  493. struct kvm_mmu_notifier_return r = {
  494. .ret = false,
  495. .found_memslot = false,
  496. };
  497. struct kvm_gfn_range gfn_range;
  498. struct kvm_memory_slot *slot;
  499. struct kvm_memslots *slots;
  500. int i, idx;
  501. if (WARN_ON_ONCE(range->end <= range->start))
  502. return r;
  503. /* A null handler is allowed if and only if on_lock() is provided. */
  504. if (WARN_ON_ONCE(IS_KVM_NULL_FN(range->on_lock) &&
  505. IS_KVM_NULL_FN(range->handler)))
  506. return r;
  507. idx = srcu_read_lock(&kvm->srcu);
  508. for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) {
  509. struct interval_tree_node *node;
  510. slots = __kvm_memslots(kvm, i);
  511. kvm_for_each_memslot_in_hva_range(node, slots,
  512. range->start, range->end - 1) {
  513. unsigned long hva_start, hva_end;
  514. slot = container_of(node, struct kvm_memory_slot, hva_node[slots->node_idx]);
  515. hva_start = max_t(unsigned long, range->start, slot->userspace_addr);
  516. hva_end = min_t(unsigned long, range->end,
  517. slot->userspace_addr + (slot->npages << PAGE_SHIFT));
  518. /*
  519. * To optimize for the likely case where the address
  520. * range is covered by zero or one memslots, don't
  521. * bother making these conditional (to avoid writes on
  522. * the second or later invocation of the handler).
  523. */
  524. gfn_range.arg = range->arg;
  525. gfn_range.may_block = range->may_block;
  526. /*
  527. * HVA-based notifications aren't relevant to private
  528. * mappings as they don't have a userspace mapping.
  529. */
  530. gfn_range.attr_filter = KVM_FILTER_SHARED;
  531. /*
  532. * {gfn(page) | page intersects with [hva_start, hva_end)} =
  533. * {gfn_start, gfn_start+1, ..., gfn_end-1}.
  534. */
  535. gfn_range.start = hva_to_gfn_memslot(hva_start, slot);
  536. gfn_range.end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, slot);
  537. gfn_range.slot = slot;
  538. if (!r.found_memslot) {
  539. r.found_memslot = true;
  540. KVM_MMU_LOCK(kvm);
  541. if (!IS_KVM_NULL_FN(range->on_lock))
  542. range->on_lock(kvm);
  543. if (IS_KVM_NULL_FN(range->handler))
  544. goto mmu_unlock;
  545. }
  546. r.ret |= range->handler(kvm, &gfn_range);
  547. }
  548. }
  549. if (range->flush_on_ret && r.ret)
  550. kvm_flush_remote_tlbs(kvm);
  551. mmu_unlock:
  552. if (r.found_memslot)
  553. KVM_MMU_UNLOCK(kvm);
  554. srcu_read_unlock(&kvm->srcu, idx);
  555. return r;
  556. }
  557. static __always_inline int kvm_handle_hva_range(struct mmu_notifier *mn,
  558. unsigned long start,
  559. unsigned long end,
  560. gfn_handler_t handler)
  561. {
  562. struct kvm *kvm = mmu_notifier_to_kvm(mn);
  563. const struct kvm_mmu_notifier_range range = {
  564. .start = start,
  565. .end = end,
  566. .handler = handler,
  567. .on_lock = (void *)kvm_null_fn,
  568. .flush_on_ret = true,
  569. .may_block = false,
  570. };
  571. return __kvm_handle_hva_range(kvm, &range).ret;
  572. }
  573. static __always_inline int kvm_handle_hva_range_no_flush(struct mmu_notifier *mn,
  574. unsigned long start,
  575. unsigned long end,
  576. gfn_handler_t handler)
  577. {
  578. struct kvm *kvm = mmu_notifier_to_kvm(mn);
  579. const struct kvm_mmu_notifier_range range = {
  580. .start = start,
  581. .end = end,
  582. .handler = handler,
  583. .on_lock = (void *)kvm_null_fn,
  584. .flush_on_ret = false,
  585. .may_block = false,
  586. };
  587. return __kvm_handle_hva_range(kvm, &range).ret;
  588. }
  589. void kvm_mmu_invalidate_begin(struct kvm *kvm)
  590. {
  591. lockdep_assert_held_write(&kvm->mmu_lock);
  592. /*
  593. * The count increase must become visible at unlock time as no
  594. * spte can be established without taking the mmu_lock and
  595. * count is also read inside the mmu_lock critical section.
  596. */
  597. kvm->mmu_invalidate_in_progress++;
  598. if (likely(kvm->mmu_invalidate_in_progress == 1)) {
  599. kvm->mmu_invalidate_range_start = INVALID_GPA;
  600. kvm->mmu_invalidate_range_end = INVALID_GPA;
  601. }
  602. }
  603. void kvm_mmu_invalidate_range_add(struct kvm *kvm, gfn_t start, gfn_t end)
  604. {
  605. lockdep_assert_held_write(&kvm->mmu_lock);
  606. WARN_ON_ONCE(!kvm->mmu_invalidate_in_progress);
  607. if (likely(kvm->mmu_invalidate_range_start == INVALID_GPA)) {
  608. kvm->mmu_invalidate_range_start = start;
  609. kvm->mmu_invalidate_range_end = end;
  610. } else {
  611. /*
  612. * Fully tracking multiple concurrent ranges has diminishing
  613. * returns. Keep things simple and just find the minimal range
  614. * which includes the current and new ranges. As there won't be
  615. * enough information to subtract a range after its invalidate
  616. * completes, any ranges invalidated concurrently will
  617. * accumulate and persist until all outstanding invalidates
  618. * complete.
  619. */
  620. kvm->mmu_invalidate_range_start =
  621. min(kvm->mmu_invalidate_range_start, start);
  622. kvm->mmu_invalidate_range_end =
  623. max(kvm->mmu_invalidate_range_end, end);
  624. }
  625. }
  626. bool kvm_mmu_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)
  627. {
  628. kvm_mmu_invalidate_range_add(kvm, range->start, range->end);
  629. return kvm_unmap_gfn_range(kvm, range);
  630. }
  631. static int kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
  632. const struct mmu_notifier_range *range)
  633. {
  634. struct kvm *kvm = mmu_notifier_to_kvm(mn);
  635. const struct kvm_mmu_notifier_range hva_range = {
  636. .start = range->start,
  637. .end = range->end,
  638. .handler = kvm_mmu_unmap_gfn_range,
  639. .on_lock = kvm_mmu_invalidate_begin,
  640. .flush_on_ret = true,
  641. .may_block = mmu_notifier_range_blockable(range),
  642. };
  643. trace_kvm_unmap_hva_range(range->start, range->end);
  644. /*
  645. * Prevent memslot modification between range_start() and range_end()
  646. * so that conditionally locking provides the same result in both
  647. * functions. Without that guarantee, the mmu_invalidate_in_progress
  648. * adjustments will be imbalanced.
  649. *
  650. * Pairs with the decrement in range_end().
  651. */
  652. spin_lock(&kvm->mn_invalidate_lock);
  653. kvm->mn_active_invalidate_count++;
  654. spin_unlock(&kvm->mn_invalidate_lock);
  655. /*
  656. * Invalidate pfn caches _before_ invalidating the secondary MMUs, i.e.
  657. * before acquiring mmu_lock, to avoid holding mmu_lock while acquiring
  658. * each cache's lock. There are relatively few caches in existence at
  659. * any given time, and the caches themselves can check for hva overlap,
  660. * i.e. don't need to rely on memslot overlap checks for performance.
  661. * Because this runs without holding mmu_lock, the pfn caches must use
  662. * mn_active_invalidate_count (see above) instead of
  663. * mmu_invalidate_in_progress.
  664. */
  665. gfn_to_pfn_cache_invalidate_start(kvm, range->start, range->end);
  666. /*
  667. * If one or more memslots were found and thus zapped, notify arch code
  668. * that guest memory has been reclaimed. This needs to be done *after*
  669. * dropping mmu_lock, as x86's reclaim path is slooooow.
  670. */
  671. if (__kvm_handle_hva_range(kvm, &hva_range).found_memslot)
  672. kvm_arch_guest_memory_reclaimed(kvm);
  673. return 0;
  674. }
  675. void kvm_mmu_invalidate_end(struct kvm *kvm)
  676. {
  677. lockdep_assert_held_write(&kvm->mmu_lock);
  678. /*
  679. * This sequence increase will notify the kvm page fault that
  680. * the page that is going to be mapped in the spte could have
  681. * been freed.
  682. */
  683. kvm->mmu_invalidate_seq++;
  684. smp_wmb();
  685. /*
  686. * The above sequence increase must be visible before the
  687. * below count decrease, which is ensured by the smp_wmb above
  688. * in conjunction with the smp_rmb in mmu_invalidate_retry().
  689. */
  690. kvm->mmu_invalidate_in_progress--;
  691. KVM_BUG_ON(kvm->mmu_invalidate_in_progress < 0, kvm);
  692. /*
  693. * Assert that at least one range was added between start() and end().
  694. * Not adding a range isn't fatal, but it is a KVM bug.
  695. */
  696. WARN_ON_ONCE(kvm->mmu_invalidate_range_start == INVALID_GPA);
  697. }
  698. static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
  699. const struct mmu_notifier_range *range)
  700. {
  701. struct kvm *kvm = mmu_notifier_to_kvm(mn);
  702. const struct kvm_mmu_notifier_range hva_range = {
  703. .start = range->start,
  704. .end = range->end,
  705. .handler = (void *)kvm_null_fn,
  706. .on_lock = kvm_mmu_invalidate_end,
  707. .flush_on_ret = false,
  708. .may_block = mmu_notifier_range_blockable(range),
  709. };
  710. bool wake;
  711. __kvm_handle_hva_range(kvm, &hva_range);
  712. /* Pairs with the increment in range_start(). */
  713. spin_lock(&kvm->mn_invalidate_lock);
  714. if (!WARN_ON_ONCE(!kvm->mn_active_invalidate_count))
  715. --kvm->mn_active_invalidate_count;
  716. wake = !kvm->mn_active_invalidate_count;
  717. spin_unlock(&kvm->mn_invalidate_lock);
  718. /*
  719. * There can only be one waiter, since the wait happens under
  720. * slots_lock.
  721. */
  722. if (wake)
  723. rcuwait_wake_up(&kvm->mn_memslots_update_rcuwait);
  724. }
  725. static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
  726. struct mm_struct *mm,
  727. unsigned long start,
  728. unsigned long end)
  729. {
  730. trace_kvm_age_hva(start, end);
  731. return kvm_handle_hva_range(mn, start, end, kvm_age_gfn);
  732. }
  733. static int kvm_mmu_notifier_clear_young(struct mmu_notifier *mn,
  734. struct mm_struct *mm,
  735. unsigned long start,
  736. unsigned long end)
  737. {
  738. trace_kvm_age_hva(start, end);
  739. /*
  740. * Even though we do not flush TLB, this will still adversely
  741. * affect performance on pre-Haswell Intel EPT, where there is
  742. * no EPT Access Bit to clear so that we have to tear down EPT
  743. * tables instead. If we find this unacceptable, we can always
  744. * add a parameter to kvm_age_hva so that it effectively doesn't
  745. * do anything on clear_young.
  746. *
  747. * Also note that currently we never issue secondary TLB flushes
  748. * from clear_young, leaving this job up to the regular system
  749. * cadence. If we find this inaccurate, we might come up with a
  750. * more sophisticated heuristic later.
  751. */
  752. return kvm_handle_hva_range_no_flush(mn, start, end, kvm_age_gfn);
  753. }
  754. static int kvm_mmu_notifier_test_young(struct mmu_notifier *mn,
  755. struct mm_struct *mm,
  756. unsigned long address)
  757. {
  758. trace_kvm_test_age_hva(address);
  759. return kvm_handle_hva_range_no_flush(mn, address, address + 1,
  760. kvm_test_age_gfn);
  761. }
  762. static void kvm_mmu_notifier_release(struct mmu_notifier *mn,
  763. struct mm_struct *mm)
  764. {
  765. struct kvm *kvm = mmu_notifier_to_kvm(mn);
  766. int idx;
  767. idx = srcu_read_lock(&kvm->srcu);
  768. kvm_flush_shadow_all(kvm);
  769. srcu_read_unlock(&kvm->srcu, idx);
  770. }
  771. static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
  772. .invalidate_range_start = kvm_mmu_notifier_invalidate_range_start,
  773. .invalidate_range_end = kvm_mmu_notifier_invalidate_range_end,
  774. .clear_flush_young = kvm_mmu_notifier_clear_flush_young,
  775. .clear_young = kvm_mmu_notifier_clear_young,
  776. .test_young = kvm_mmu_notifier_test_young,
  777. .release = kvm_mmu_notifier_release,
  778. };
  779. static int kvm_init_mmu_notifier(struct kvm *kvm)
  780. {
  781. kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
  782. return mmu_notifier_register(&kvm->mmu_notifier, current->mm);
  783. }
  784. #else /* !CONFIG_KVM_GENERIC_MMU_NOTIFIER */
  785. static int kvm_init_mmu_notifier(struct kvm *kvm)
  786. {
  787. return 0;
  788. }
  789. #endif /* CONFIG_KVM_GENERIC_MMU_NOTIFIER */
  790. #ifdef CONFIG_HAVE_KVM_PM_NOTIFIER
  791. static int kvm_pm_notifier_call(struct notifier_block *bl,
  792. unsigned long state,
  793. void *unused)
  794. {
  795. struct kvm *kvm = container_of(bl, struct kvm, pm_notifier);
  796. return kvm_arch_pm_notifier(kvm, state);
  797. }
  798. static void kvm_init_pm_notifier(struct kvm *kvm)
  799. {
  800. kvm->pm_notifier.notifier_call = kvm_pm_notifier_call;
  801. /* Suspend KVM before we suspend ftrace, RCU, etc. */
  802. kvm->pm_notifier.priority = INT_MAX;
  803. register_pm_notifier(&kvm->pm_notifier);
  804. }
  805. static void kvm_destroy_pm_notifier(struct kvm *kvm)
  806. {
  807. unregister_pm_notifier(&kvm->pm_notifier);
  808. }
  809. #else /* !CONFIG_HAVE_KVM_PM_NOTIFIER */
  810. static void kvm_init_pm_notifier(struct kvm *kvm)
  811. {
  812. }
  813. static void kvm_destroy_pm_notifier(struct kvm *kvm)
  814. {
  815. }
  816. #endif /* CONFIG_HAVE_KVM_PM_NOTIFIER */
  817. static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot)
  818. {
  819. if (!memslot->dirty_bitmap)
  820. return;
  821. vfree(memslot->dirty_bitmap);
  822. memslot->dirty_bitmap = NULL;
  823. }
  824. /* This does not remove the slot from struct kvm_memslots data structures */
  825. static void kvm_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
  826. {
  827. if (slot->flags & KVM_MEM_GUEST_MEMFD)
  828. kvm_gmem_unbind(slot);
  829. kvm_destroy_dirty_bitmap(slot);
  830. kvm_arch_free_memslot(kvm, slot);
  831. kfree(slot);
  832. }
  833. static void kvm_free_memslots(struct kvm *kvm, struct kvm_memslots *slots)
  834. {
  835. struct hlist_node *idnode;
  836. struct kvm_memory_slot *memslot;
  837. int bkt;
  838. /*
  839. * The same memslot objects live in both active and inactive sets,
  840. * arbitrarily free using index '1' so the second invocation of this
  841. * function isn't operating over a structure with dangling pointers
  842. * (even though this function isn't actually touching them).
  843. */
  844. if (!slots->node_idx)
  845. return;
  846. hash_for_each_safe(slots->id_hash, bkt, idnode, memslot, id_node[1])
  847. kvm_free_memslot(kvm, memslot);
  848. }
  849. static umode_t kvm_stats_debugfs_mode(const struct _kvm_stats_desc *pdesc)
  850. {
  851. switch (pdesc->desc.flags & KVM_STATS_TYPE_MASK) {
  852. case KVM_STATS_TYPE_INSTANT:
  853. return 0444;
  854. case KVM_STATS_TYPE_CUMULATIVE:
  855. case KVM_STATS_TYPE_PEAK:
  856. default:
  857. return 0644;
  858. }
  859. }
  860. static void kvm_destroy_vm_debugfs(struct kvm *kvm)
  861. {
  862. int i;
  863. int kvm_debugfs_num_entries = kvm_vm_stats_header.num_desc +
  864. kvm_vcpu_stats_header.num_desc;
  865. if (IS_ERR(kvm->debugfs_dentry))
  866. return;
  867. debugfs_remove_recursive(kvm->debugfs_dentry);
  868. if (kvm->debugfs_stat_data) {
  869. for (i = 0; i < kvm_debugfs_num_entries; i++)
  870. kfree(kvm->debugfs_stat_data[i]);
  871. kfree(kvm->debugfs_stat_data);
  872. }
  873. }
  874. static int kvm_create_vm_debugfs(struct kvm *kvm, const char *fdname)
  875. {
  876. static DEFINE_MUTEX(kvm_debugfs_lock);
  877. struct dentry *dent;
  878. char dir_name[ITOA_MAX_LEN * 2];
  879. struct kvm_stat_data *stat_data;
  880. const struct _kvm_stats_desc *pdesc;
  881. int i, ret = -ENOMEM;
  882. int kvm_debugfs_num_entries = kvm_vm_stats_header.num_desc +
  883. kvm_vcpu_stats_header.num_desc;
  884. if (!debugfs_initialized())
  885. return 0;
  886. snprintf(dir_name, sizeof(dir_name), "%d-%s", task_pid_nr(current), fdname);
  887. mutex_lock(&kvm_debugfs_lock);
  888. dent = debugfs_lookup(dir_name, kvm_debugfs_dir);
  889. if (dent) {
  890. pr_warn_ratelimited("KVM: debugfs: duplicate directory %s\n", dir_name);
  891. dput(dent);
  892. mutex_unlock(&kvm_debugfs_lock);
  893. return 0;
  894. }
  895. dent = debugfs_create_dir(dir_name, kvm_debugfs_dir);
  896. mutex_unlock(&kvm_debugfs_lock);
  897. if (IS_ERR(dent))
  898. return 0;
  899. kvm->debugfs_dentry = dent;
  900. kvm->debugfs_stat_data = kcalloc(kvm_debugfs_num_entries,
  901. sizeof(*kvm->debugfs_stat_data),
  902. GFP_KERNEL_ACCOUNT);
  903. if (!kvm->debugfs_stat_data)
  904. goto out_err;
  905. for (i = 0; i < kvm_vm_stats_header.num_desc; ++i) {
  906. pdesc = &kvm_vm_stats_desc[i];
  907. stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL_ACCOUNT);
  908. if (!stat_data)
  909. goto out_err;
  910. stat_data->kvm = kvm;
  911. stat_data->desc = pdesc;
  912. stat_data->kind = KVM_STAT_VM;
  913. kvm->debugfs_stat_data[i] = stat_data;
  914. debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
  915. kvm->debugfs_dentry, stat_data,
  916. &stat_fops_per_vm);
  917. }
  918. for (i = 0; i < kvm_vcpu_stats_header.num_desc; ++i) {
  919. pdesc = &kvm_vcpu_stats_desc[i];
  920. stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL_ACCOUNT);
  921. if (!stat_data)
  922. goto out_err;
  923. stat_data->kvm = kvm;
  924. stat_data->desc = pdesc;
  925. stat_data->kind = KVM_STAT_VCPU;
  926. kvm->debugfs_stat_data[i + kvm_vm_stats_header.num_desc] = stat_data;
  927. debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
  928. kvm->debugfs_dentry, stat_data,
  929. &stat_fops_per_vm);
  930. }
  931. kvm_arch_create_vm_debugfs(kvm);
  932. return 0;
  933. out_err:
  934. kvm_destroy_vm_debugfs(kvm);
  935. return ret;
  936. }
  937. /*
  938. * Called after the VM is otherwise initialized, but just before adding it to
  939. * the vm_list.
  940. */
  941. int __weak kvm_arch_post_init_vm(struct kvm *kvm)
  942. {
  943. return 0;
  944. }
  945. /*
  946. * Called just after removing the VM from the vm_list, but before doing any
  947. * other destruction.
  948. */
  949. void __weak kvm_arch_pre_destroy_vm(struct kvm *kvm)
  950. {
  951. }
  952. /*
  953. * Called after per-vm debugfs created. When called kvm->debugfs_dentry should
  954. * be setup already, so we can create arch-specific debugfs entries under it.
  955. * Cleanup should be automatic done in kvm_destroy_vm_debugfs() recursively, so
  956. * a per-arch destroy interface is not needed.
  957. */
  958. void __weak kvm_arch_create_vm_debugfs(struct kvm *kvm)
  959. {
  960. }
  961. static struct kvm *kvm_create_vm(unsigned long type, const char *fdname)
  962. {
  963. struct kvm *kvm = kvm_arch_alloc_vm();
  964. struct kvm_memslots *slots;
  965. int r, i, j;
  966. if (!kvm)
  967. return ERR_PTR(-ENOMEM);
  968. KVM_MMU_LOCK_INIT(kvm);
  969. mmgrab(current->mm);
  970. kvm->mm = current->mm;
  971. kvm_eventfd_init(kvm);
  972. mutex_init(&kvm->lock);
  973. mutex_init(&kvm->irq_lock);
  974. mutex_init(&kvm->slots_lock);
  975. mutex_init(&kvm->slots_arch_lock);
  976. spin_lock_init(&kvm->mn_invalidate_lock);
  977. rcuwait_init(&kvm->mn_memslots_update_rcuwait);
  978. xa_init(&kvm->vcpu_array);
  979. #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES
  980. xa_init(&kvm->mem_attr_array);
  981. #endif
  982. INIT_LIST_HEAD(&kvm->gpc_list);
  983. spin_lock_init(&kvm->gpc_lock);
  984. INIT_LIST_HEAD(&kvm->devices);
  985. kvm->max_vcpus = KVM_MAX_VCPUS;
  986. BUILD_BUG_ON(KVM_MEM_SLOTS_NUM > SHRT_MAX);
  987. /*
  988. * Force subsequent debugfs file creations to fail if the VM directory
  989. * is not created (by kvm_create_vm_debugfs()).
  990. */
  991. kvm->debugfs_dentry = ERR_PTR(-ENOENT);
  992. snprintf(kvm->stats_id, sizeof(kvm->stats_id), "kvm-%d",
  993. task_pid_nr(current));
  994. r = -ENOMEM;
  995. if (init_srcu_struct(&kvm->srcu))
  996. goto out_err_no_srcu;
  997. if (init_srcu_struct(&kvm->irq_srcu))
  998. goto out_err_no_irq_srcu;
  999. r = kvm_init_irq_routing(kvm);
  1000. if (r)
  1001. goto out_err_no_irq_routing;
  1002. refcount_set(&kvm->users_count, 1);
  1003. for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) {
  1004. for (j = 0; j < 2; j++) {
  1005. slots = &kvm->__memslots[i][j];
  1006. atomic_long_set(&slots->last_used_slot, (unsigned long)NULL);
  1007. slots->hva_tree = RB_ROOT_CACHED;
  1008. slots->gfn_tree = RB_ROOT;
  1009. hash_init(slots->id_hash);
  1010. slots->node_idx = j;
  1011. /* Generations must be different for each address space. */
  1012. slots->generation = i;
  1013. }
  1014. rcu_assign_pointer(kvm->memslots[i], &kvm->__memslots[i][0]);
  1015. }
  1016. r = -ENOMEM;
  1017. for (i = 0; i < KVM_NR_BUSES; i++) {
  1018. rcu_assign_pointer(kvm->buses[i],
  1019. kzalloc(sizeof(struct kvm_io_bus), GFP_KERNEL_ACCOUNT));
  1020. if (!kvm->buses[i])
  1021. goto out_err_no_arch_destroy_vm;
  1022. }
  1023. r = kvm_arch_init_vm(kvm, type);
  1024. if (r)
  1025. goto out_err_no_arch_destroy_vm;
  1026. r = kvm_enable_virtualization();
  1027. if (r)
  1028. goto out_err_no_disable;
  1029. #ifdef CONFIG_HAVE_KVM_IRQCHIP
  1030. INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list);
  1031. #endif
  1032. r = kvm_init_mmu_notifier(kvm);
  1033. if (r)
  1034. goto out_err_no_mmu_notifier;
  1035. r = kvm_coalesced_mmio_init(kvm);
  1036. if (r < 0)
  1037. goto out_no_coalesced_mmio;
  1038. r = kvm_create_vm_debugfs(kvm, fdname);
  1039. if (r)
  1040. goto out_err_no_debugfs;
  1041. r = kvm_arch_post_init_vm(kvm);
  1042. if (r)
  1043. goto out_err;
  1044. mutex_lock(&kvm_lock);
  1045. list_add(&kvm->vm_list, &vm_list);
  1046. mutex_unlock(&kvm_lock);
  1047. preempt_notifier_inc();
  1048. kvm_init_pm_notifier(kvm);
  1049. return kvm;
  1050. out_err:
  1051. kvm_destroy_vm_debugfs(kvm);
  1052. out_err_no_debugfs:
  1053. kvm_coalesced_mmio_free(kvm);
  1054. out_no_coalesced_mmio:
  1055. #ifdef CONFIG_KVM_GENERIC_MMU_NOTIFIER
  1056. if (kvm->mmu_notifier.ops)
  1057. mmu_notifier_unregister(&kvm->mmu_notifier, current->mm);
  1058. #endif
  1059. out_err_no_mmu_notifier:
  1060. kvm_disable_virtualization();
  1061. out_err_no_disable:
  1062. kvm_arch_destroy_vm(kvm);
  1063. out_err_no_arch_destroy_vm:
  1064. WARN_ON_ONCE(!refcount_dec_and_test(&kvm->users_count));
  1065. for (i = 0; i < KVM_NR_BUSES; i++)
  1066. kfree(kvm_get_bus(kvm, i));
  1067. kvm_free_irq_routing(kvm);
  1068. out_err_no_irq_routing:
  1069. cleanup_srcu_struct(&kvm->irq_srcu);
  1070. out_err_no_irq_srcu:
  1071. cleanup_srcu_struct(&kvm->srcu);
  1072. out_err_no_srcu:
  1073. kvm_arch_free_vm(kvm);
  1074. mmdrop(current->mm);
  1075. return ERR_PTR(r);
  1076. }
  1077. static void kvm_destroy_devices(struct kvm *kvm)
  1078. {
  1079. struct kvm_device *dev, *tmp;
  1080. /*
  1081. * We do not need to take the kvm->lock here, because nobody else
  1082. * has a reference to the struct kvm at this point and therefore
  1083. * cannot access the devices list anyhow.
  1084. *
  1085. * The device list is generally managed as an rculist, but list_del()
  1086. * is used intentionally here. If a bug in KVM introduced a reader that
  1087. * was not backed by a reference on the kvm struct, the hope is that
  1088. * it'd consume the poisoned forward pointer instead of suffering a
  1089. * use-after-free, even though this cannot be guaranteed.
  1090. */
  1091. list_for_each_entry_safe(dev, tmp, &kvm->devices, vm_node) {
  1092. list_del(&dev->vm_node);
  1093. dev->ops->destroy(dev);
  1094. }
  1095. }
  1096. static void kvm_destroy_vm(struct kvm *kvm)
  1097. {
  1098. int i;
  1099. struct mm_struct *mm = kvm->mm;
  1100. kvm_destroy_pm_notifier(kvm);
  1101. kvm_uevent_notify_change(KVM_EVENT_DESTROY_VM, kvm);
  1102. kvm_destroy_vm_debugfs(kvm);
  1103. kvm_arch_sync_events(kvm);
  1104. mutex_lock(&kvm_lock);
  1105. list_del(&kvm->vm_list);
  1106. mutex_unlock(&kvm_lock);
  1107. kvm_arch_pre_destroy_vm(kvm);
  1108. kvm_free_irq_routing(kvm);
  1109. for (i = 0; i < KVM_NR_BUSES; i++) {
  1110. struct kvm_io_bus *bus = kvm_get_bus(kvm, i);
  1111. if (bus)
  1112. kvm_io_bus_destroy(bus);
  1113. kvm->buses[i] = NULL;
  1114. }
  1115. kvm_coalesced_mmio_free(kvm);
  1116. #ifdef CONFIG_KVM_GENERIC_MMU_NOTIFIER
  1117. mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
  1118. /*
  1119. * At this point, pending calls to invalidate_range_start()
  1120. * have completed but no more MMU notifiers will run, so
  1121. * mn_active_invalidate_count may remain unbalanced.
  1122. * No threads can be waiting in kvm_swap_active_memslots() as the
  1123. * last reference on KVM has been dropped, but freeing
  1124. * memslots would deadlock without this manual intervention.
  1125. *
  1126. * If the count isn't unbalanced, i.e. KVM did NOT unregister its MMU
  1127. * notifier between a start() and end(), then there shouldn't be any
  1128. * in-progress invalidations.
  1129. */
  1130. WARN_ON(rcuwait_active(&kvm->mn_memslots_update_rcuwait));
  1131. if (kvm->mn_active_invalidate_count)
  1132. kvm->mn_active_invalidate_count = 0;
  1133. else
  1134. WARN_ON(kvm->mmu_invalidate_in_progress);
  1135. #else
  1136. kvm_flush_shadow_all(kvm);
  1137. #endif
  1138. kvm_arch_destroy_vm(kvm);
  1139. kvm_destroy_devices(kvm);
  1140. for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) {
  1141. kvm_free_memslots(kvm, &kvm->__memslots[i][0]);
  1142. kvm_free_memslots(kvm, &kvm->__memslots[i][1]);
  1143. }
  1144. cleanup_srcu_struct(&kvm->irq_srcu);
  1145. cleanup_srcu_struct(&kvm->srcu);
  1146. #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES
  1147. xa_destroy(&kvm->mem_attr_array);
  1148. #endif
  1149. kvm_arch_free_vm(kvm);
  1150. preempt_notifier_dec();
  1151. kvm_disable_virtualization();
  1152. mmdrop(mm);
  1153. }
  1154. void kvm_get_kvm(struct kvm *kvm)
  1155. {
  1156. refcount_inc(&kvm->users_count);
  1157. }
  1158. EXPORT_SYMBOL_GPL(kvm_get_kvm);
  1159. /*
  1160. * Make sure the vm is not during destruction, which is a safe version of
  1161. * kvm_get_kvm(). Return true if kvm referenced successfully, false otherwise.
  1162. */
  1163. bool kvm_get_kvm_safe(struct kvm *kvm)
  1164. {
  1165. return refcount_inc_not_zero(&kvm->users_count);
  1166. }
  1167. EXPORT_SYMBOL_GPL(kvm_get_kvm_safe);
  1168. void kvm_put_kvm(struct kvm *kvm)
  1169. {
  1170. if (refcount_dec_and_test(&kvm->users_count))
  1171. kvm_destroy_vm(kvm);
  1172. }
  1173. EXPORT_SYMBOL_GPL(kvm_put_kvm);
  1174. /*
  1175. * Used to put a reference that was taken on behalf of an object associated
  1176. * with a user-visible file descriptor, e.g. a vcpu or device, if installation
  1177. * of the new file descriptor fails and the reference cannot be transferred to
  1178. * its final owner. In such cases, the caller is still actively using @kvm and
  1179. * will fail miserably if the refcount unexpectedly hits zero.
  1180. */
  1181. void kvm_put_kvm_no_destroy(struct kvm *kvm)
  1182. {
  1183. WARN_ON(refcount_dec_and_test(&kvm->users_count));
  1184. }
  1185. EXPORT_SYMBOL_GPL(kvm_put_kvm_no_destroy);
  1186. static int kvm_vm_release(struct inode *inode, struct file *filp)
  1187. {
  1188. struct kvm *kvm = filp->private_data;
  1189. kvm_irqfd_release(kvm);
  1190. kvm_put_kvm(kvm);
  1191. return 0;
  1192. }
  1193. /*
  1194. * Allocation size is twice as large as the actual dirty bitmap size.
  1195. * See kvm_vm_ioctl_get_dirty_log() why this is needed.
  1196. */
  1197. static int kvm_alloc_dirty_bitmap(struct kvm_memory_slot *memslot)
  1198. {
  1199. unsigned long dirty_bytes = kvm_dirty_bitmap_bytes(memslot);
  1200. memslot->dirty_bitmap = __vcalloc(2, dirty_bytes, GFP_KERNEL_ACCOUNT);
  1201. if (!memslot->dirty_bitmap)
  1202. return -ENOMEM;
  1203. return 0;
  1204. }
  1205. static struct kvm_memslots *kvm_get_inactive_memslots(struct kvm *kvm, int as_id)
  1206. {
  1207. struct kvm_memslots *active = __kvm_memslots(kvm, as_id);
  1208. int node_idx_inactive = active->node_idx ^ 1;
  1209. return &kvm->__memslots[as_id][node_idx_inactive];
  1210. }
  1211. /*
  1212. * Helper to get the address space ID when one of memslot pointers may be NULL.
  1213. * This also serves as a sanity that at least one of the pointers is non-NULL,
  1214. * and that their address space IDs don't diverge.
  1215. */
  1216. static int kvm_memslots_get_as_id(struct kvm_memory_slot *a,
  1217. struct kvm_memory_slot *b)
  1218. {
  1219. if (WARN_ON_ONCE(!a && !b))
  1220. return 0;
  1221. if (!a)
  1222. return b->as_id;
  1223. if (!b)
  1224. return a->as_id;
  1225. WARN_ON_ONCE(a->as_id != b->as_id);
  1226. return a->as_id;
  1227. }
  1228. static void kvm_insert_gfn_node(struct kvm_memslots *slots,
  1229. struct kvm_memory_slot *slot)
  1230. {
  1231. struct rb_root *gfn_tree = &slots->gfn_tree;
  1232. struct rb_node **node, *parent;
  1233. int idx = slots->node_idx;
  1234. parent = NULL;
  1235. for (node = &gfn_tree->rb_node; *node; ) {
  1236. struct kvm_memory_slot *tmp;
  1237. tmp = container_of(*node, struct kvm_memory_slot, gfn_node[idx]);
  1238. parent = *node;
  1239. if (slot->base_gfn < tmp->base_gfn)
  1240. node = &(*node)->rb_left;
  1241. else if (slot->base_gfn > tmp->base_gfn)
  1242. node = &(*node)->rb_right;
  1243. else
  1244. BUG();
  1245. }
  1246. rb_link_node(&slot->gfn_node[idx], parent, node);
  1247. rb_insert_color(&slot->gfn_node[idx], gfn_tree);
  1248. }
  1249. static void kvm_erase_gfn_node(struct kvm_memslots *slots,
  1250. struct kvm_memory_slot *slot)
  1251. {
  1252. rb_erase(&slot->gfn_node[slots->node_idx], &slots->gfn_tree);
  1253. }
  1254. static void kvm_replace_gfn_node(struct kvm_memslots *slots,
  1255. struct kvm_memory_slot *old,
  1256. struct kvm_memory_slot *new)
  1257. {
  1258. int idx = slots->node_idx;
  1259. WARN_ON_ONCE(old->base_gfn != new->base_gfn);
  1260. rb_replace_node(&old->gfn_node[idx], &new->gfn_node[idx],
  1261. &slots->gfn_tree);
  1262. }
  1263. /*
  1264. * Replace @old with @new in the inactive memslots.
  1265. *
  1266. * With NULL @old this simply adds @new.
  1267. * With NULL @new this simply removes @old.
  1268. *
  1269. * If @new is non-NULL its hva_node[slots_idx] range has to be set
  1270. * appropriately.
  1271. */
  1272. static void kvm_replace_memslot(struct kvm *kvm,
  1273. struct kvm_memory_slot *old,
  1274. struct kvm_memory_slot *new)
  1275. {
  1276. int as_id = kvm_memslots_get_as_id(old, new);
  1277. struct kvm_memslots *slots = kvm_get_inactive_memslots(kvm, as_id);
  1278. int idx = slots->node_idx;
  1279. if (old) {
  1280. hash_del(&old->id_node[idx]);
  1281. interval_tree_remove(&old->hva_node[idx], &slots->hva_tree);
  1282. if ((long)old == atomic_long_read(&slots->last_used_slot))
  1283. atomic_long_set(&slots->last_used_slot, (long)new);
  1284. if (!new) {
  1285. kvm_erase_gfn_node(slots, old);
  1286. return;
  1287. }
  1288. }
  1289. /*
  1290. * Initialize @new's hva range. Do this even when replacing an @old
  1291. * slot, kvm_copy_memslot() deliberately does not touch node data.
  1292. */
  1293. new->hva_node[idx].start = new->userspace_addr;
  1294. new->hva_node[idx].last = new->userspace_addr +
  1295. (new->npages << PAGE_SHIFT) - 1;
  1296. /*
  1297. * (Re)Add the new memslot. There is no O(1) interval_tree_replace(),
  1298. * hva_node needs to be swapped with remove+insert even though hva can't
  1299. * change when replacing an existing slot.
  1300. */
  1301. hash_add(slots->id_hash, &new->id_node[idx], new->id);
  1302. interval_tree_insert(&new->hva_node[idx], &slots->hva_tree);
  1303. /*
  1304. * If the memslot gfn is unchanged, rb_replace_node() can be used to
  1305. * switch the node in the gfn tree instead of removing the old and
  1306. * inserting the new as two separate operations. Replacement is a
  1307. * single O(1) operation versus two O(log(n)) operations for
  1308. * remove+insert.
  1309. */
  1310. if (old && old->base_gfn == new->base_gfn) {
  1311. kvm_replace_gfn_node(slots, old, new);
  1312. } else {
  1313. if (old)
  1314. kvm_erase_gfn_node(slots, old);
  1315. kvm_insert_gfn_node(slots, new);
  1316. }
  1317. }
  1318. /*
  1319. * Flags that do not access any of the extra space of struct
  1320. * kvm_userspace_memory_region2. KVM_SET_USER_MEMORY_REGION_V1_FLAGS
  1321. * only allows these.
  1322. */
  1323. #define KVM_SET_USER_MEMORY_REGION_V1_FLAGS \
  1324. (KVM_MEM_LOG_DIRTY_PAGES | KVM_MEM_READONLY)
  1325. static int check_memory_region_flags(struct kvm *kvm,
  1326. const struct kvm_userspace_memory_region2 *mem)
  1327. {
  1328. u32 valid_flags = KVM_MEM_LOG_DIRTY_PAGES;
  1329. if (kvm_arch_has_private_mem(kvm))
  1330. valid_flags |= KVM_MEM_GUEST_MEMFD;
  1331. /* Dirty logging private memory is not currently supported. */
  1332. if (mem->flags & KVM_MEM_GUEST_MEMFD)
  1333. valid_flags &= ~KVM_MEM_LOG_DIRTY_PAGES;
  1334. /*
  1335. * GUEST_MEMFD is incompatible with read-only memslots, as writes to
  1336. * read-only memslots have emulated MMIO, not page fault, semantics,
  1337. * and KVM doesn't allow emulated MMIO for private memory.
  1338. */
  1339. if (kvm_arch_has_readonly_mem(kvm) &&
  1340. !(mem->flags & KVM_MEM_GUEST_MEMFD))
  1341. valid_flags |= KVM_MEM_READONLY;
  1342. if (mem->flags & ~valid_flags)
  1343. return -EINVAL;
  1344. return 0;
  1345. }
  1346. static void kvm_swap_active_memslots(struct kvm *kvm, int as_id)
  1347. {
  1348. struct kvm_memslots *slots = kvm_get_inactive_memslots(kvm, as_id);
  1349. /* Grab the generation from the activate memslots. */
  1350. u64 gen = __kvm_memslots(kvm, as_id)->generation;
  1351. WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
  1352. slots->generation = gen | KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
  1353. /*
  1354. * Do not store the new memslots while there are invalidations in
  1355. * progress, otherwise the locking in invalidate_range_start and
  1356. * invalidate_range_end will be unbalanced.
  1357. */
  1358. spin_lock(&kvm->mn_invalidate_lock);
  1359. prepare_to_rcuwait(&kvm->mn_memslots_update_rcuwait);
  1360. while (kvm->mn_active_invalidate_count) {
  1361. set_current_state(TASK_UNINTERRUPTIBLE);
  1362. spin_unlock(&kvm->mn_invalidate_lock);
  1363. schedule();
  1364. spin_lock(&kvm->mn_invalidate_lock);
  1365. }
  1366. finish_rcuwait(&kvm->mn_memslots_update_rcuwait);
  1367. rcu_assign_pointer(kvm->memslots[as_id], slots);
  1368. spin_unlock(&kvm->mn_invalidate_lock);
  1369. /*
  1370. * Acquired in kvm_set_memslot. Must be released before synchronize
  1371. * SRCU below in order to avoid deadlock with another thread
  1372. * acquiring the slots_arch_lock in an srcu critical section.
  1373. */
  1374. mutex_unlock(&kvm->slots_arch_lock);
  1375. synchronize_srcu_expedited(&kvm->srcu);
  1376. /*
  1377. * Increment the new memslot generation a second time, dropping the
  1378. * update in-progress flag and incrementing the generation based on
  1379. * the number of address spaces. This provides a unique and easily
  1380. * identifiable generation number while the memslots are in flux.
  1381. */
  1382. gen = slots->generation & ~KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
  1383. /*
  1384. * Generations must be unique even across address spaces. We do not need
  1385. * a global counter for that, instead the generation space is evenly split
  1386. * across address spaces. For example, with two address spaces, address
  1387. * space 0 will use generations 0, 2, 4, ... while address space 1 will
  1388. * use generations 1, 3, 5, ...
  1389. */
  1390. gen += kvm_arch_nr_memslot_as_ids(kvm);
  1391. kvm_arch_memslots_updated(kvm, gen);
  1392. slots->generation = gen;
  1393. }
  1394. static int kvm_prepare_memory_region(struct kvm *kvm,
  1395. const struct kvm_memory_slot *old,
  1396. struct kvm_memory_slot *new,
  1397. enum kvm_mr_change change)
  1398. {
  1399. int r;
  1400. /*
  1401. * If dirty logging is disabled, nullify the bitmap; the old bitmap
  1402. * will be freed on "commit". If logging is enabled in both old and
  1403. * new, reuse the existing bitmap. If logging is enabled only in the
  1404. * new and KVM isn't using a ring buffer, allocate and initialize a
  1405. * new bitmap.
  1406. */
  1407. if (change != KVM_MR_DELETE) {
  1408. if (!(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
  1409. new->dirty_bitmap = NULL;
  1410. else if (old && old->dirty_bitmap)
  1411. new->dirty_bitmap = old->dirty_bitmap;
  1412. else if (kvm_use_dirty_bitmap(kvm)) {
  1413. r = kvm_alloc_dirty_bitmap(new);
  1414. if (r)
  1415. return r;
  1416. if (kvm_dirty_log_manual_protect_and_init_set(kvm))
  1417. bitmap_set(new->dirty_bitmap, 0, new->npages);
  1418. }
  1419. }
  1420. r = kvm_arch_prepare_memory_region(kvm, old, new, change);
  1421. /* Free the bitmap on failure if it was allocated above. */
  1422. if (r && new && new->dirty_bitmap && (!old || !old->dirty_bitmap))
  1423. kvm_destroy_dirty_bitmap(new);
  1424. return r;
  1425. }
  1426. static void kvm_commit_memory_region(struct kvm *kvm,
  1427. struct kvm_memory_slot *old,
  1428. const struct kvm_memory_slot *new,
  1429. enum kvm_mr_change change)
  1430. {
  1431. int old_flags = old ? old->flags : 0;
  1432. int new_flags = new ? new->flags : 0;
  1433. /*
  1434. * Update the total number of memslot pages before calling the arch
  1435. * hook so that architectures can consume the result directly.
  1436. */
  1437. if (change == KVM_MR_DELETE)
  1438. kvm->nr_memslot_pages -= old->npages;
  1439. else if (change == KVM_MR_CREATE)
  1440. kvm->nr_memslot_pages += new->npages;
  1441. if ((old_flags ^ new_flags) & KVM_MEM_LOG_DIRTY_PAGES) {
  1442. int change = (new_flags & KVM_MEM_LOG_DIRTY_PAGES) ? 1 : -1;
  1443. atomic_set(&kvm->nr_memslots_dirty_logging,
  1444. atomic_read(&kvm->nr_memslots_dirty_logging) + change);
  1445. }
  1446. kvm_arch_commit_memory_region(kvm, old, new, change);
  1447. switch (change) {
  1448. case KVM_MR_CREATE:
  1449. /* Nothing more to do. */
  1450. break;
  1451. case KVM_MR_DELETE:
  1452. /* Free the old memslot and all its metadata. */
  1453. kvm_free_memslot(kvm, old);
  1454. break;
  1455. case KVM_MR_MOVE:
  1456. case KVM_MR_FLAGS_ONLY:
  1457. /*
  1458. * Free the dirty bitmap as needed; the below check encompasses
  1459. * both the flags and whether a ring buffer is being used)
  1460. */
  1461. if (old->dirty_bitmap && !new->dirty_bitmap)
  1462. kvm_destroy_dirty_bitmap(old);
  1463. /*
  1464. * The final quirk. Free the detached, old slot, but only its
  1465. * memory, not any metadata. Metadata, including arch specific
  1466. * data, may be reused by @new.
  1467. */
  1468. kfree(old);
  1469. break;
  1470. default:
  1471. BUG();
  1472. }
  1473. }
  1474. /*
  1475. * Activate @new, which must be installed in the inactive slots by the caller,
  1476. * by swapping the active slots and then propagating @new to @old once @old is
  1477. * unreachable and can be safely modified.
  1478. *
  1479. * With NULL @old this simply adds @new to @active (while swapping the sets).
  1480. * With NULL @new this simply removes @old from @active and frees it
  1481. * (while also swapping the sets).
  1482. */
  1483. static void kvm_activate_memslot(struct kvm *kvm,
  1484. struct kvm_memory_slot *old,
  1485. struct kvm_memory_slot *new)
  1486. {
  1487. int as_id = kvm_memslots_get_as_id(old, new);
  1488. kvm_swap_active_memslots(kvm, as_id);
  1489. /* Propagate the new memslot to the now inactive memslots. */
  1490. kvm_replace_memslot(kvm, old, new);
  1491. }
  1492. static void kvm_copy_memslot(struct kvm_memory_slot *dest,
  1493. const struct kvm_memory_slot *src)
  1494. {
  1495. dest->base_gfn = src->base_gfn;
  1496. dest->npages = src->npages;
  1497. dest->dirty_bitmap = src->dirty_bitmap;
  1498. dest->arch = src->arch;
  1499. dest->userspace_addr = src->userspace_addr;
  1500. dest->flags = src->flags;
  1501. dest->id = src->id;
  1502. dest->as_id = src->as_id;
  1503. }
  1504. static void kvm_invalidate_memslot(struct kvm *kvm,
  1505. struct kvm_memory_slot *old,
  1506. struct kvm_memory_slot *invalid_slot)
  1507. {
  1508. /*
  1509. * Mark the current slot INVALID. As with all memslot modifications,
  1510. * this must be done on an unreachable slot to avoid modifying the
  1511. * current slot in the active tree.
  1512. */
  1513. kvm_copy_memslot(invalid_slot, old);
  1514. invalid_slot->flags |= KVM_MEMSLOT_INVALID;
  1515. kvm_replace_memslot(kvm, old, invalid_slot);
  1516. /*
  1517. * Activate the slot that is now marked INVALID, but don't propagate
  1518. * the slot to the now inactive slots. The slot is either going to be
  1519. * deleted or recreated as a new slot.
  1520. */
  1521. kvm_swap_active_memslots(kvm, old->as_id);
  1522. /*
  1523. * From this point no new shadow pages pointing to a deleted, or moved,
  1524. * memslot will be created. Validation of sp->gfn happens in:
  1525. * - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
  1526. * - kvm_is_visible_gfn (mmu_check_root)
  1527. */
  1528. kvm_arch_flush_shadow_memslot(kvm, old);
  1529. kvm_arch_guest_memory_reclaimed(kvm);
  1530. /* Was released by kvm_swap_active_memslots(), reacquire. */
  1531. mutex_lock(&kvm->slots_arch_lock);
  1532. /*
  1533. * Copy the arch-specific field of the newly-installed slot back to the
  1534. * old slot as the arch data could have changed between releasing
  1535. * slots_arch_lock in kvm_swap_active_memslots() and re-acquiring the lock
  1536. * above. Writers are required to retrieve memslots *after* acquiring
  1537. * slots_arch_lock, thus the active slot's data is guaranteed to be fresh.
  1538. */
  1539. old->arch = invalid_slot->arch;
  1540. }
  1541. static void kvm_create_memslot(struct kvm *kvm,
  1542. struct kvm_memory_slot *new)
  1543. {
  1544. /* Add the new memslot to the inactive set and activate. */
  1545. kvm_replace_memslot(kvm, NULL, new);
  1546. kvm_activate_memslot(kvm, NULL, new);
  1547. }
  1548. static void kvm_delete_memslot(struct kvm *kvm,
  1549. struct kvm_memory_slot *old,
  1550. struct kvm_memory_slot *invalid_slot)
  1551. {
  1552. /*
  1553. * Remove the old memslot (in the inactive memslots) by passing NULL as
  1554. * the "new" slot, and for the invalid version in the active slots.
  1555. */
  1556. kvm_replace_memslot(kvm, old, NULL);
  1557. kvm_activate_memslot(kvm, invalid_slot, NULL);
  1558. }
  1559. static void kvm_move_memslot(struct kvm *kvm,
  1560. struct kvm_memory_slot *old,
  1561. struct kvm_memory_slot *new,
  1562. struct kvm_memory_slot *invalid_slot)
  1563. {
  1564. /*
  1565. * Replace the old memslot in the inactive slots, and then swap slots
  1566. * and replace the current INVALID with the new as well.
  1567. */
  1568. kvm_replace_memslot(kvm, old, new);
  1569. kvm_activate_memslot(kvm, invalid_slot, new);
  1570. }
  1571. static void kvm_update_flags_memslot(struct kvm *kvm,
  1572. struct kvm_memory_slot *old,
  1573. struct kvm_memory_slot *new)
  1574. {
  1575. /*
  1576. * Similar to the MOVE case, but the slot doesn't need to be zapped as
  1577. * an intermediate step. Instead, the old memslot is simply replaced
  1578. * with a new, updated copy in both memslot sets.
  1579. */
  1580. kvm_replace_memslot(kvm, old, new);
  1581. kvm_activate_memslot(kvm, old, new);
  1582. }
  1583. static int kvm_set_memslot(struct kvm *kvm,
  1584. struct kvm_memory_slot *old,
  1585. struct kvm_memory_slot *new,
  1586. enum kvm_mr_change change)
  1587. {
  1588. struct kvm_memory_slot *invalid_slot;
  1589. int r;
  1590. /*
  1591. * Released in kvm_swap_active_memslots().
  1592. *
  1593. * Must be held from before the current memslots are copied until after
  1594. * the new memslots are installed with rcu_assign_pointer, then
  1595. * released before the synchronize srcu in kvm_swap_active_memslots().
  1596. *
  1597. * When modifying memslots outside of the slots_lock, must be held
  1598. * before reading the pointer to the current memslots until after all
  1599. * changes to those memslots are complete.
  1600. *
  1601. * These rules ensure that installing new memslots does not lose
  1602. * changes made to the previous memslots.
  1603. */
  1604. mutex_lock(&kvm->slots_arch_lock);
  1605. /*
  1606. * Invalidate the old slot if it's being deleted or moved. This is
  1607. * done prior to actually deleting/moving the memslot to allow vCPUs to
  1608. * continue running by ensuring there are no mappings or shadow pages
  1609. * for the memslot when it is deleted/moved. Without pre-invalidation
  1610. * (and without a lock), a window would exist between effecting the
  1611. * delete/move and committing the changes in arch code where KVM or a
  1612. * guest could access a non-existent memslot.
  1613. *
  1614. * Modifications are done on a temporary, unreachable slot. The old
  1615. * slot needs to be preserved in case a later step fails and the
  1616. * invalidation needs to be reverted.
  1617. */
  1618. if (change == KVM_MR_DELETE || change == KVM_MR_MOVE) {
  1619. invalid_slot = kzalloc(sizeof(*invalid_slot), GFP_KERNEL_ACCOUNT);
  1620. if (!invalid_slot) {
  1621. mutex_unlock(&kvm->slots_arch_lock);
  1622. return -ENOMEM;
  1623. }
  1624. kvm_invalidate_memslot(kvm, old, invalid_slot);
  1625. }
  1626. r = kvm_prepare_memory_region(kvm, old, new, change);
  1627. if (r) {
  1628. /*
  1629. * For DELETE/MOVE, revert the above INVALID change. No
  1630. * modifications required since the original slot was preserved
  1631. * in the inactive slots. Changing the active memslots also
  1632. * release slots_arch_lock.
  1633. */
  1634. if (change == KVM_MR_DELETE || change == KVM_MR_MOVE) {
  1635. kvm_activate_memslot(kvm, invalid_slot, old);
  1636. kfree(invalid_slot);
  1637. } else {
  1638. mutex_unlock(&kvm->slots_arch_lock);
  1639. }
  1640. return r;
  1641. }
  1642. /*
  1643. * For DELETE and MOVE, the working slot is now active as the INVALID
  1644. * version of the old slot. MOVE is particularly special as it reuses
  1645. * the old slot and returns a copy of the old slot (in working_slot).
  1646. * For CREATE, there is no old slot. For DELETE and FLAGS_ONLY, the
  1647. * old slot is detached but otherwise preserved.
  1648. */
  1649. if (change == KVM_MR_CREATE)
  1650. kvm_create_memslot(kvm, new);
  1651. else if (change == KVM_MR_DELETE)
  1652. kvm_delete_memslot(kvm, old, invalid_slot);
  1653. else if (change == KVM_MR_MOVE)
  1654. kvm_move_memslot(kvm, old, new, invalid_slot);
  1655. else if (change == KVM_MR_FLAGS_ONLY)
  1656. kvm_update_flags_memslot(kvm, old, new);
  1657. else
  1658. BUG();
  1659. /* Free the temporary INVALID slot used for DELETE and MOVE. */
  1660. if (change == KVM_MR_DELETE || change == KVM_MR_MOVE)
  1661. kfree(invalid_slot);
  1662. /*
  1663. * No need to refresh new->arch, changes after dropping slots_arch_lock
  1664. * will directly hit the final, active memslot. Architectures are
  1665. * responsible for knowing that new->arch may be stale.
  1666. */
  1667. kvm_commit_memory_region(kvm, old, new, change);
  1668. return 0;
  1669. }
  1670. static bool kvm_check_memslot_overlap(struct kvm_memslots *slots, int id,
  1671. gfn_t start, gfn_t end)
  1672. {
  1673. struct kvm_memslot_iter iter;
  1674. kvm_for_each_memslot_in_gfn_range(&iter, slots, start, end) {
  1675. if (iter.slot->id != id)
  1676. return true;
  1677. }
  1678. return false;
  1679. }
  1680. /*
  1681. * Allocate some memory and give it an address in the guest physical address
  1682. * space.
  1683. *
  1684. * Discontiguous memory is allowed, mostly for framebuffers.
  1685. *
  1686. * Must be called holding kvm->slots_lock for write.
  1687. */
  1688. int __kvm_set_memory_region(struct kvm *kvm,
  1689. const struct kvm_userspace_memory_region2 *mem)
  1690. {
  1691. struct kvm_memory_slot *old, *new;
  1692. struct kvm_memslots *slots;
  1693. enum kvm_mr_change change;
  1694. unsigned long npages;
  1695. gfn_t base_gfn;
  1696. int as_id, id;
  1697. int r;
  1698. r = check_memory_region_flags(kvm, mem);
  1699. if (r)
  1700. return r;
  1701. as_id = mem->slot >> 16;
  1702. id = (u16)mem->slot;
  1703. /* General sanity checks */
  1704. if ((mem->memory_size & (PAGE_SIZE - 1)) ||
  1705. (mem->memory_size != (unsigned long)mem->memory_size))
  1706. return -EINVAL;
  1707. if (mem->guest_phys_addr & (PAGE_SIZE - 1))
  1708. return -EINVAL;
  1709. /* We can read the guest memory with __xxx_user() later on. */
  1710. if ((mem->userspace_addr & (PAGE_SIZE - 1)) ||
  1711. (mem->userspace_addr != untagged_addr(mem->userspace_addr)) ||
  1712. !access_ok((void __user *)(unsigned long)mem->userspace_addr,
  1713. mem->memory_size))
  1714. return -EINVAL;
  1715. if (mem->flags & KVM_MEM_GUEST_MEMFD &&
  1716. (mem->guest_memfd_offset & (PAGE_SIZE - 1) ||
  1717. mem->guest_memfd_offset + mem->memory_size < mem->guest_memfd_offset))
  1718. return -EINVAL;
  1719. if (as_id >= kvm_arch_nr_memslot_as_ids(kvm) || id >= KVM_MEM_SLOTS_NUM)
  1720. return -EINVAL;
  1721. if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
  1722. return -EINVAL;
  1723. if ((mem->memory_size >> PAGE_SHIFT) > KVM_MEM_MAX_NR_PAGES)
  1724. return -EINVAL;
  1725. slots = __kvm_memslots(kvm, as_id);
  1726. /*
  1727. * Note, the old memslot (and the pointer itself!) may be invalidated
  1728. * and/or destroyed by kvm_set_memslot().
  1729. */
  1730. old = id_to_memslot(slots, id);
  1731. if (!mem->memory_size) {
  1732. if (!old || !old->npages)
  1733. return -EINVAL;
  1734. if (WARN_ON_ONCE(kvm->nr_memslot_pages < old->npages))
  1735. return -EIO;
  1736. return kvm_set_memslot(kvm, old, NULL, KVM_MR_DELETE);
  1737. }
  1738. base_gfn = (mem->guest_phys_addr >> PAGE_SHIFT);
  1739. npages = (mem->memory_size >> PAGE_SHIFT);
  1740. if (!old || !old->npages) {
  1741. change = KVM_MR_CREATE;
  1742. /*
  1743. * To simplify KVM internals, the total number of pages across
  1744. * all memslots must fit in an unsigned long.
  1745. */
  1746. if ((kvm->nr_memslot_pages + npages) < kvm->nr_memslot_pages)
  1747. return -EINVAL;
  1748. } else { /* Modify an existing slot. */
  1749. /* Private memslots are immutable, they can only be deleted. */
  1750. if (mem->flags & KVM_MEM_GUEST_MEMFD)
  1751. return -EINVAL;
  1752. if ((mem->userspace_addr != old->userspace_addr) ||
  1753. (npages != old->npages) ||
  1754. ((mem->flags ^ old->flags) & KVM_MEM_READONLY))
  1755. return -EINVAL;
  1756. if (base_gfn != old->base_gfn)
  1757. change = KVM_MR_MOVE;
  1758. else if (mem->flags != old->flags)
  1759. change = KVM_MR_FLAGS_ONLY;
  1760. else /* Nothing to change. */
  1761. return 0;
  1762. }
  1763. if ((change == KVM_MR_CREATE || change == KVM_MR_MOVE) &&
  1764. kvm_check_memslot_overlap(slots, id, base_gfn, base_gfn + npages))
  1765. return -EEXIST;
  1766. /* Allocate a slot that will persist in the memslot. */
  1767. new = kzalloc(sizeof(*new), GFP_KERNEL_ACCOUNT);
  1768. if (!new)
  1769. return -ENOMEM;
  1770. new->as_id = as_id;
  1771. new->id = id;
  1772. new->base_gfn = base_gfn;
  1773. new->npages = npages;
  1774. new->flags = mem->flags;
  1775. new->userspace_addr = mem->userspace_addr;
  1776. if (mem->flags & KVM_MEM_GUEST_MEMFD) {
  1777. r = kvm_gmem_bind(kvm, new, mem->guest_memfd, mem->guest_memfd_offset);
  1778. if (r)
  1779. goto out;
  1780. }
  1781. r = kvm_set_memslot(kvm, old, new, change);
  1782. if (r)
  1783. goto out_unbind;
  1784. return 0;
  1785. out_unbind:
  1786. if (mem->flags & KVM_MEM_GUEST_MEMFD)
  1787. kvm_gmem_unbind(new);
  1788. out:
  1789. kfree(new);
  1790. return r;
  1791. }
  1792. EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
  1793. int kvm_set_memory_region(struct kvm *kvm,
  1794. const struct kvm_userspace_memory_region2 *mem)
  1795. {
  1796. int r;
  1797. mutex_lock(&kvm->slots_lock);
  1798. r = __kvm_set_memory_region(kvm, mem);
  1799. mutex_unlock(&kvm->slots_lock);
  1800. return r;
  1801. }
  1802. EXPORT_SYMBOL_GPL(kvm_set_memory_region);
  1803. static int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
  1804. struct kvm_userspace_memory_region2 *mem)
  1805. {
  1806. if ((u16)mem->slot >= KVM_USER_MEM_SLOTS)
  1807. return -EINVAL;
  1808. return kvm_set_memory_region(kvm, mem);
  1809. }
  1810. #ifndef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
  1811. /**
  1812. * kvm_get_dirty_log - get a snapshot of dirty pages
  1813. * @kvm: pointer to kvm instance
  1814. * @log: slot id and address to which we copy the log
  1815. * @is_dirty: set to '1' if any dirty pages were found
  1816. * @memslot: set to the associated memslot, always valid on success
  1817. */
  1818. int kvm_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log,
  1819. int *is_dirty, struct kvm_memory_slot **memslot)
  1820. {
  1821. struct kvm_memslots *slots;
  1822. int i, as_id, id;
  1823. unsigned long n;
  1824. unsigned long any = 0;
  1825. /* Dirty ring tracking may be exclusive to dirty log tracking */
  1826. if (!kvm_use_dirty_bitmap(kvm))
  1827. return -ENXIO;
  1828. *memslot = NULL;
  1829. *is_dirty = 0;
  1830. as_id = log->slot >> 16;
  1831. id = (u16)log->slot;
  1832. if (as_id >= kvm_arch_nr_memslot_as_ids(kvm) || id >= KVM_USER_MEM_SLOTS)
  1833. return -EINVAL;
  1834. slots = __kvm_memslots(kvm, as_id);
  1835. *memslot = id_to_memslot(slots, id);
  1836. if (!(*memslot) || !(*memslot)->dirty_bitmap)
  1837. return -ENOENT;
  1838. kvm_arch_sync_dirty_log(kvm, *memslot);
  1839. n = kvm_dirty_bitmap_bytes(*memslot);
  1840. for (i = 0; !any && i < n/sizeof(long); ++i)
  1841. any = (*memslot)->dirty_bitmap[i];
  1842. if (copy_to_user(log->dirty_bitmap, (*memslot)->dirty_bitmap, n))
  1843. return -EFAULT;
  1844. if (any)
  1845. *is_dirty = 1;
  1846. return 0;
  1847. }
  1848. EXPORT_SYMBOL_GPL(kvm_get_dirty_log);
  1849. #else /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
  1850. /**
  1851. * kvm_get_dirty_log_protect - get a snapshot of dirty pages
  1852. * and reenable dirty page tracking for the corresponding pages.
  1853. * @kvm: pointer to kvm instance
  1854. * @log: slot id and address to which we copy the log
  1855. *
  1856. * We need to keep it in mind that VCPU threads can write to the bitmap
  1857. * concurrently. So, to avoid losing track of dirty pages we keep the
  1858. * following order:
  1859. *
  1860. * 1. Take a snapshot of the bit and clear it if needed.
  1861. * 2. Write protect the corresponding page.
  1862. * 3. Copy the snapshot to the userspace.
  1863. * 4. Upon return caller flushes TLB's if needed.
  1864. *
  1865. * Between 2 and 4, the guest may write to the page using the remaining TLB
  1866. * entry. This is not a problem because the page is reported dirty using
  1867. * the snapshot taken before and step 4 ensures that writes done after
  1868. * exiting to userspace will be logged for the next call.
  1869. *
  1870. */
  1871. static int kvm_get_dirty_log_protect(struct kvm *kvm, struct kvm_dirty_log *log)
  1872. {
  1873. struct kvm_memslots *slots;
  1874. struct kvm_memory_slot *memslot;
  1875. int i, as_id, id;
  1876. unsigned long n;
  1877. unsigned long *dirty_bitmap;
  1878. unsigned long *dirty_bitmap_buffer;
  1879. bool flush;
  1880. /* Dirty ring tracking may be exclusive to dirty log tracking */
  1881. if (!kvm_use_dirty_bitmap(kvm))
  1882. return -ENXIO;
  1883. as_id = log->slot >> 16;
  1884. id = (u16)log->slot;
  1885. if (as_id >= kvm_arch_nr_memslot_as_ids(kvm) || id >= KVM_USER_MEM_SLOTS)
  1886. return -EINVAL;
  1887. slots = __kvm_memslots(kvm, as_id);
  1888. memslot = id_to_memslot(slots, id);
  1889. if (!memslot || !memslot->dirty_bitmap)
  1890. return -ENOENT;
  1891. dirty_bitmap = memslot->dirty_bitmap;
  1892. kvm_arch_sync_dirty_log(kvm, memslot);
  1893. n = kvm_dirty_bitmap_bytes(memslot);
  1894. flush = false;
  1895. if (kvm->manual_dirty_log_protect) {
  1896. /*
  1897. * Unlike kvm_get_dirty_log, we always return false in *flush,
  1898. * because no flush is needed until KVM_CLEAR_DIRTY_LOG. There
  1899. * is some code duplication between this function and
  1900. * kvm_get_dirty_log, but hopefully all architecture
  1901. * transition to kvm_get_dirty_log_protect and kvm_get_dirty_log
  1902. * can be eliminated.
  1903. */
  1904. dirty_bitmap_buffer = dirty_bitmap;
  1905. } else {
  1906. dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
  1907. memset(dirty_bitmap_buffer, 0, n);
  1908. KVM_MMU_LOCK(kvm);
  1909. for (i = 0; i < n / sizeof(long); i++) {
  1910. unsigned long mask;
  1911. gfn_t offset;
  1912. if (!dirty_bitmap[i])
  1913. continue;
  1914. flush = true;
  1915. mask = xchg(&dirty_bitmap[i], 0);
  1916. dirty_bitmap_buffer[i] = mask;
  1917. offset = i * BITS_PER_LONG;
  1918. kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
  1919. offset, mask);
  1920. }
  1921. KVM_MMU_UNLOCK(kvm);
  1922. }
  1923. if (flush)
  1924. kvm_flush_remote_tlbs_memslot(kvm, memslot);
  1925. if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
  1926. return -EFAULT;
  1927. return 0;
  1928. }
  1929. /**
  1930. * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
  1931. * @kvm: kvm instance
  1932. * @log: slot id and address to which we copy the log
  1933. *
  1934. * Steps 1-4 below provide general overview of dirty page logging. See
  1935. * kvm_get_dirty_log_protect() function description for additional details.
  1936. *
  1937. * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
  1938. * always flush the TLB (step 4) even if previous step failed and the dirty
  1939. * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
  1940. * does not preclude user space subsequent dirty log read. Flushing TLB ensures
  1941. * writes will be marked dirty for next log read.
  1942. *
  1943. * 1. Take a snapshot of the bit and clear it if needed.
  1944. * 2. Write protect the corresponding page.
  1945. * 3. Copy the snapshot to the userspace.
  1946. * 4. Flush TLB's if needed.
  1947. */
  1948. static int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
  1949. struct kvm_dirty_log *log)
  1950. {
  1951. int r;
  1952. mutex_lock(&kvm->slots_lock);
  1953. r = kvm_get_dirty_log_protect(kvm, log);
  1954. mutex_unlock(&kvm->slots_lock);
  1955. return r;
  1956. }
  1957. /**
  1958. * kvm_clear_dirty_log_protect - clear dirty bits in the bitmap
  1959. * and reenable dirty page tracking for the corresponding pages.
  1960. * @kvm: pointer to kvm instance
  1961. * @log: slot id and address from which to fetch the bitmap of dirty pages
  1962. */
  1963. static int kvm_clear_dirty_log_protect(struct kvm *kvm,
  1964. struct kvm_clear_dirty_log *log)
  1965. {
  1966. struct kvm_memslots *slots;
  1967. struct kvm_memory_slot *memslot;
  1968. int as_id, id;
  1969. gfn_t offset;
  1970. unsigned long i, n;
  1971. unsigned long *dirty_bitmap;
  1972. unsigned long *dirty_bitmap_buffer;
  1973. bool flush;
  1974. /* Dirty ring tracking may be exclusive to dirty log tracking */
  1975. if (!kvm_use_dirty_bitmap(kvm))
  1976. return -ENXIO;
  1977. as_id = log->slot >> 16;
  1978. id = (u16)log->slot;
  1979. if (as_id >= kvm_arch_nr_memslot_as_ids(kvm) || id >= KVM_USER_MEM_SLOTS)
  1980. return -EINVAL;
  1981. if (log->first_page & 63)
  1982. return -EINVAL;
  1983. slots = __kvm_memslots(kvm, as_id);
  1984. memslot = id_to_memslot(slots, id);
  1985. if (!memslot || !memslot->dirty_bitmap)
  1986. return -ENOENT;
  1987. dirty_bitmap = memslot->dirty_bitmap;
  1988. n = ALIGN(log->num_pages, BITS_PER_LONG) / 8;
  1989. if (log->first_page > memslot->npages ||
  1990. log->num_pages > memslot->npages - log->first_page ||
  1991. (log->num_pages < memslot->npages - log->first_page && (log->num_pages & 63)))
  1992. return -EINVAL;
  1993. kvm_arch_sync_dirty_log(kvm, memslot);
  1994. flush = false;
  1995. dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
  1996. if (copy_from_user(dirty_bitmap_buffer, log->dirty_bitmap, n))
  1997. return -EFAULT;
  1998. KVM_MMU_LOCK(kvm);
  1999. for (offset = log->first_page, i = offset / BITS_PER_LONG,
  2000. n = DIV_ROUND_UP(log->num_pages, BITS_PER_LONG); n--;
  2001. i++, offset += BITS_PER_LONG) {
  2002. unsigned long mask = *dirty_bitmap_buffer++;
  2003. atomic_long_t *p = (atomic_long_t *) &dirty_bitmap[i];
  2004. if (!mask)
  2005. continue;
  2006. mask &= atomic_long_fetch_andnot(mask, p);
  2007. /*
  2008. * mask contains the bits that really have been cleared. This
  2009. * never includes any bits beyond the length of the memslot (if
  2010. * the length is not aligned to 64 pages), therefore it is not
  2011. * a problem if userspace sets them in log->dirty_bitmap.
  2012. */
  2013. if (mask) {
  2014. flush = true;
  2015. kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
  2016. offset, mask);
  2017. }
  2018. }
  2019. KVM_MMU_UNLOCK(kvm);
  2020. if (flush)
  2021. kvm_flush_remote_tlbs_memslot(kvm, memslot);
  2022. return 0;
  2023. }
  2024. static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm,
  2025. struct kvm_clear_dirty_log *log)
  2026. {
  2027. int r;
  2028. mutex_lock(&kvm->slots_lock);
  2029. r = kvm_clear_dirty_log_protect(kvm, log);
  2030. mutex_unlock(&kvm->slots_lock);
  2031. return r;
  2032. }
  2033. #endif /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
  2034. #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES
  2035. static u64 kvm_supported_mem_attributes(struct kvm *kvm)
  2036. {
  2037. if (!kvm || kvm_arch_has_private_mem(kvm))
  2038. return KVM_MEMORY_ATTRIBUTE_PRIVATE;
  2039. return 0;
  2040. }
  2041. /*
  2042. * Returns true if _all_ gfns in the range [@start, @end) have attributes
  2043. * such that the bits in @mask match @attrs.
  2044. */
  2045. bool kvm_range_has_memory_attributes(struct kvm *kvm, gfn_t start, gfn_t end,
  2046. unsigned long mask, unsigned long attrs)
  2047. {
  2048. XA_STATE(xas, &kvm->mem_attr_array, start);
  2049. unsigned long index;
  2050. void *entry;
  2051. mask &= kvm_supported_mem_attributes(kvm);
  2052. if (attrs & ~mask)
  2053. return false;
  2054. if (end == start + 1)
  2055. return (kvm_get_memory_attributes(kvm, start) & mask) == attrs;
  2056. guard(rcu)();
  2057. if (!attrs)
  2058. return !xas_find(&xas, end - 1);
  2059. for (index = start; index < end; index++) {
  2060. do {
  2061. entry = xas_next(&xas);
  2062. } while (xas_retry(&xas, entry));
  2063. if (xas.xa_index != index ||
  2064. (xa_to_value(entry) & mask) != attrs)
  2065. return false;
  2066. }
  2067. return true;
  2068. }
  2069. static __always_inline void kvm_handle_gfn_range(struct kvm *kvm,
  2070. struct kvm_mmu_notifier_range *range)
  2071. {
  2072. struct kvm_gfn_range gfn_range;
  2073. struct kvm_memory_slot *slot;
  2074. struct kvm_memslots *slots;
  2075. struct kvm_memslot_iter iter;
  2076. bool found_memslot = false;
  2077. bool ret = false;
  2078. int i;
  2079. gfn_range.arg = range->arg;
  2080. gfn_range.may_block = range->may_block;
  2081. /*
  2082. * If/when KVM supports more attributes beyond private .vs shared, this
  2083. * _could_ set KVM_FILTER_{SHARED,PRIVATE} appropriately if the entire target
  2084. * range already has the desired private vs. shared state (it's unclear
  2085. * if that is a net win). For now, KVM reaches this point if and only
  2086. * if the private flag is being toggled, i.e. all mappings are in play.
  2087. */
  2088. for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) {
  2089. slots = __kvm_memslots(kvm, i);
  2090. kvm_for_each_memslot_in_gfn_range(&iter, slots, range->start, range->end) {
  2091. slot = iter.slot;
  2092. gfn_range.slot = slot;
  2093. gfn_range.start = max(range->start, slot->base_gfn);
  2094. gfn_range.end = min(range->end, slot->base_gfn + slot->npages);
  2095. if (gfn_range.start >= gfn_range.end)
  2096. continue;
  2097. if (!found_memslot) {
  2098. found_memslot = true;
  2099. KVM_MMU_LOCK(kvm);
  2100. if (!IS_KVM_NULL_FN(range->on_lock))
  2101. range->on_lock(kvm);
  2102. }
  2103. ret |= range->handler(kvm, &gfn_range);
  2104. }
  2105. }
  2106. if (range->flush_on_ret && ret)
  2107. kvm_flush_remote_tlbs(kvm);
  2108. if (found_memslot)
  2109. KVM_MMU_UNLOCK(kvm);
  2110. }
  2111. static bool kvm_pre_set_memory_attributes(struct kvm *kvm,
  2112. struct kvm_gfn_range *range)
  2113. {
  2114. /*
  2115. * Unconditionally add the range to the invalidation set, regardless of
  2116. * whether or not the arch callback actually needs to zap SPTEs. E.g.
  2117. * if KVM supports RWX attributes in the future and the attributes are
  2118. * going from R=>RW, zapping isn't strictly necessary. Unconditionally
  2119. * adding the range allows KVM to require that MMU invalidations add at
  2120. * least one range between begin() and end(), e.g. allows KVM to detect
  2121. * bugs where the add() is missed. Relaxing the rule *might* be safe,
  2122. * but it's not obvious that allowing new mappings while the attributes
  2123. * are in flux is desirable or worth the complexity.
  2124. */
  2125. kvm_mmu_invalidate_range_add(kvm, range->start, range->end);
  2126. return kvm_arch_pre_set_memory_attributes(kvm, range);
  2127. }
  2128. /* Set @attributes for the gfn range [@start, @end). */
  2129. static int kvm_vm_set_mem_attributes(struct kvm *kvm, gfn_t start, gfn_t end,
  2130. unsigned long attributes)
  2131. {
  2132. struct kvm_mmu_notifier_range pre_set_range = {
  2133. .start = start,
  2134. .end = end,
  2135. .arg.attributes = attributes,
  2136. .handler = kvm_pre_set_memory_attributes,
  2137. .on_lock = kvm_mmu_invalidate_begin,
  2138. .flush_on_ret = true,
  2139. .may_block = true,
  2140. };
  2141. struct kvm_mmu_notifier_range post_set_range = {
  2142. .start = start,
  2143. .end = end,
  2144. .arg.attributes = attributes,
  2145. .handler = kvm_arch_post_set_memory_attributes,
  2146. .on_lock = kvm_mmu_invalidate_end,
  2147. .may_block = true,
  2148. };
  2149. unsigned long i;
  2150. void *entry;
  2151. int r = 0;
  2152. entry = attributes ? xa_mk_value(attributes) : NULL;
  2153. mutex_lock(&kvm->slots_lock);
  2154. /* Nothing to do if the entire range as the desired attributes. */
  2155. if (kvm_range_has_memory_attributes(kvm, start, end, ~0, attributes))
  2156. goto out_unlock;
  2157. /*
  2158. * Reserve memory ahead of time to avoid having to deal with failures
  2159. * partway through setting the new attributes.
  2160. */
  2161. for (i = start; i < end; i++) {
  2162. r = xa_reserve(&kvm->mem_attr_array, i, GFP_KERNEL_ACCOUNT);
  2163. if (r)
  2164. goto out_unlock;
  2165. cond_resched();
  2166. }
  2167. kvm_handle_gfn_range(kvm, &pre_set_range);
  2168. for (i = start; i < end; i++) {
  2169. r = xa_err(xa_store(&kvm->mem_attr_array, i, entry,
  2170. GFP_KERNEL_ACCOUNT));
  2171. KVM_BUG_ON(r, kvm);
  2172. cond_resched();
  2173. }
  2174. kvm_handle_gfn_range(kvm, &post_set_range);
  2175. out_unlock:
  2176. mutex_unlock(&kvm->slots_lock);
  2177. return r;
  2178. }
  2179. static int kvm_vm_ioctl_set_mem_attributes(struct kvm *kvm,
  2180. struct kvm_memory_attributes *attrs)
  2181. {
  2182. gfn_t start, end;
  2183. /* flags is currently not used. */
  2184. if (attrs->flags)
  2185. return -EINVAL;
  2186. if (attrs->attributes & ~kvm_supported_mem_attributes(kvm))
  2187. return -EINVAL;
  2188. if (attrs->size == 0 || attrs->address + attrs->size < attrs->address)
  2189. return -EINVAL;
  2190. if (!PAGE_ALIGNED(attrs->address) || !PAGE_ALIGNED(attrs->size))
  2191. return -EINVAL;
  2192. start = attrs->address >> PAGE_SHIFT;
  2193. end = (attrs->address + attrs->size) >> PAGE_SHIFT;
  2194. /*
  2195. * xarray tracks data using "unsigned long", and as a result so does
  2196. * KVM. For simplicity, supports generic attributes only on 64-bit
  2197. * architectures.
  2198. */
  2199. BUILD_BUG_ON(sizeof(attrs->attributes) != sizeof(unsigned long));
  2200. return kvm_vm_set_mem_attributes(kvm, start, end, attrs->attributes);
  2201. }
  2202. #endif /* CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES */
  2203. struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
  2204. {
  2205. return __gfn_to_memslot(kvm_memslots(kvm), gfn);
  2206. }
  2207. EXPORT_SYMBOL_GPL(gfn_to_memslot);
  2208. struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfn)
  2209. {
  2210. struct kvm_memslots *slots = kvm_vcpu_memslots(vcpu);
  2211. u64 gen = slots->generation;
  2212. struct kvm_memory_slot *slot;
  2213. /*
  2214. * This also protects against using a memslot from a different address space,
  2215. * since different address spaces have different generation numbers.
  2216. */
  2217. if (unlikely(gen != vcpu->last_used_slot_gen)) {
  2218. vcpu->last_used_slot = NULL;
  2219. vcpu->last_used_slot_gen = gen;
  2220. }
  2221. slot = try_get_memslot(vcpu->last_used_slot, gfn);
  2222. if (slot)
  2223. return slot;
  2224. /*
  2225. * Fall back to searching all memslots. We purposely use
  2226. * search_memslots() instead of __gfn_to_memslot() to avoid
  2227. * thrashing the VM-wide last_used_slot in kvm_memslots.
  2228. */
  2229. slot = search_memslots(slots, gfn, false);
  2230. if (slot) {
  2231. vcpu->last_used_slot = slot;
  2232. return slot;
  2233. }
  2234. return NULL;
  2235. }
  2236. bool kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
  2237. {
  2238. struct kvm_memory_slot *memslot = gfn_to_memslot(kvm, gfn);
  2239. return kvm_is_visible_memslot(memslot);
  2240. }
  2241. EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
  2242. bool kvm_vcpu_is_visible_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
  2243. {
  2244. struct kvm_memory_slot *memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
  2245. return kvm_is_visible_memslot(memslot);
  2246. }
  2247. EXPORT_SYMBOL_GPL(kvm_vcpu_is_visible_gfn);
  2248. unsigned long kvm_host_page_size(struct kvm_vcpu *vcpu, gfn_t gfn)
  2249. {
  2250. struct vm_area_struct *vma;
  2251. unsigned long addr, size;
  2252. size = PAGE_SIZE;
  2253. addr = kvm_vcpu_gfn_to_hva_prot(vcpu, gfn, NULL);
  2254. if (kvm_is_error_hva(addr))
  2255. return PAGE_SIZE;
  2256. mmap_read_lock(current->mm);
  2257. vma = find_vma(current->mm, addr);
  2258. if (!vma)
  2259. goto out;
  2260. size = vma_kernel_pagesize(vma);
  2261. out:
  2262. mmap_read_unlock(current->mm);
  2263. return size;
  2264. }
  2265. static bool memslot_is_readonly(const struct kvm_memory_slot *slot)
  2266. {
  2267. return slot->flags & KVM_MEM_READONLY;
  2268. }
  2269. static unsigned long __gfn_to_hva_many(const struct kvm_memory_slot *slot, gfn_t gfn,
  2270. gfn_t *nr_pages, bool write)
  2271. {
  2272. if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
  2273. return KVM_HVA_ERR_BAD;
  2274. if (memslot_is_readonly(slot) && write)
  2275. return KVM_HVA_ERR_RO_BAD;
  2276. if (nr_pages)
  2277. *nr_pages = slot->npages - (gfn - slot->base_gfn);
  2278. return __gfn_to_hva_memslot(slot, gfn);
  2279. }
  2280. static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
  2281. gfn_t *nr_pages)
  2282. {
  2283. return __gfn_to_hva_many(slot, gfn, nr_pages, true);
  2284. }
  2285. unsigned long gfn_to_hva_memslot(struct kvm_memory_slot *slot,
  2286. gfn_t gfn)
  2287. {
  2288. return gfn_to_hva_many(slot, gfn, NULL);
  2289. }
  2290. EXPORT_SYMBOL_GPL(gfn_to_hva_memslot);
  2291. unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
  2292. {
  2293. return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL);
  2294. }
  2295. EXPORT_SYMBOL_GPL(gfn_to_hva);
  2296. unsigned long kvm_vcpu_gfn_to_hva(struct kvm_vcpu *vcpu, gfn_t gfn)
  2297. {
  2298. return gfn_to_hva_many(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn, NULL);
  2299. }
  2300. EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_hva);
  2301. /*
  2302. * Return the hva of a @gfn and the R/W attribute if possible.
  2303. *
  2304. * @slot: the kvm_memory_slot which contains @gfn
  2305. * @gfn: the gfn to be translated
  2306. * @writable: used to return the read/write attribute of the @slot if the hva
  2307. * is valid and @writable is not NULL
  2308. */
  2309. unsigned long gfn_to_hva_memslot_prot(struct kvm_memory_slot *slot,
  2310. gfn_t gfn, bool *writable)
  2311. {
  2312. unsigned long hva = __gfn_to_hva_many(slot, gfn, NULL, false);
  2313. if (!kvm_is_error_hva(hva) && writable)
  2314. *writable = !memslot_is_readonly(slot);
  2315. return hva;
  2316. }
  2317. unsigned long gfn_to_hva_prot(struct kvm *kvm, gfn_t gfn, bool *writable)
  2318. {
  2319. struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
  2320. return gfn_to_hva_memslot_prot(slot, gfn, writable);
  2321. }
  2322. unsigned long kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu *vcpu, gfn_t gfn, bool *writable)
  2323. {
  2324. struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
  2325. return gfn_to_hva_memslot_prot(slot, gfn, writable);
  2326. }
  2327. static inline int check_user_page_hwpoison(unsigned long addr)
  2328. {
  2329. int rc, flags = FOLL_HWPOISON | FOLL_WRITE;
  2330. rc = get_user_pages(addr, 1, flags, NULL);
  2331. return rc == -EHWPOISON;
  2332. }
  2333. /*
  2334. * The fast path to get the writable pfn which will be stored in @pfn,
  2335. * true indicates success, otherwise false is returned. It's also the
  2336. * only part that runs if we can in atomic context.
  2337. */
  2338. static bool hva_to_pfn_fast(unsigned long addr, bool write_fault,
  2339. bool *writable, kvm_pfn_t *pfn)
  2340. {
  2341. struct page *page[1];
  2342. /*
  2343. * Fast pin a writable pfn only if it is a write fault request
  2344. * or the caller allows to map a writable pfn for a read fault
  2345. * request.
  2346. */
  2347. if (!(write_fault || writable))
  2348. return false;
  2349. if (get_user_page_fast_only(addr, FOLL_WRITE, page)) {
  2350. *pfn = page_to_pfn(page[0]);
  2351. if (writable)
  2352. *writable = true;
  2353. return true;
  2354. }
  2355. return false;
  2356. }
  2357. /*
  2358. * The slow path to get the pfn of the specified host virtual address,
  2359. * 1 indicates success, -errno is returned if error is detected.
  2360. */
  2361. static int hva_to_pfn_slow(unsigned long addr, bool *async, bool write_fault,
  2362. bool interruptible, bool *writable, kvm_pfn_t *pfn)
  2363. {
  2364. /*
  2365. * When a VCPU accesses a page that is not mapped into the secondary
  2366. * MMU, we lookup the page using GUP to map it, so the guest VCPU can
  2367. * make progress. We always want to honor NUMA hinting faults in that
  2368. * case, because GUP usage corresponds to memory accesses from the VCPU.
  2369. * Otherwise, we'd not trigger NUMA hinting faults once a page is
  2370. * mapped into the secondary MMU and gets accessed by a VCPU.
  2371. *
  2372. * Note that get_user_page_fast_only() and FOLL_WRITE for now
  2373. * implicitly honor NUMA hinting faults and don't need this flag.
  2374. */
  2375. unsigned int flags = FOLL_HWPOISON | FOLL_HONOR_NUMA_FAULT;
  2376. struct page *page;
  2377. int npages;
  2378. might_sleep();
  2379. if (writable)
  2380. *writable = write_fault;
  2381. if (write_fault)
  2382. flags |= FOLL_WRITE;
  2383. if (async)
  2384. flags |= FOLL_NOWAIT;
  2385. if (interruptible)
  2386. flags |= FOLL_INTERRUPTIBLE;
  2387. npages = get_user_pages_unlocked(addr, 1, &page, flags);
  2388. if (npages != 1)
  2389. return npages;
  2390. /* map read fault as writable if possible */
  2391. if (unlikely(!write_fault) && writable) {
  2392. struct page *wpage;
  2393. if (get_user_page_fast_only(addr, FOLL_WRITE, &wpage)) {
  2394. *writable = true;
  2395. put_page(page);
  2396. page = wpage;
  2397. }
  2398. }
  2399. *pfn = page_to_pfn(page);
  2400. return npages;
  2401. }
  2402. static bool vma_is_valid(struct vm_area_struct *vma, bool write_fault)
  2403. {
  2404. if (unlikely(!(vma->vm_flags & VM_READ)))
  2405. return false;
  2406. if (write_fault && (unlikely(!(vma->vm_flags & VM_WRITE))))
  2407. return false;
  2408. return true;
  2409. }
  2410. static int kvm_try_get_pfn(kvm_pfn_t pfn)
  2411. {
  2412. struct page *page = kvm_pfn_to_refcounted_page(pfn);
  2413. if (!page)
  2414. return 1;
  2415. return get_page_unless_zero(page);
  2416. }
  2417. static int hva_to_pfn_remapped(struct vm_area_struct *vma,
  2418. unsigned long addr, bool write_fault,
  2419. bool *writable, kvm_pfn_t *p_pfn)
  2420. {
  2421. struct follow_pfnmap_args args = { .vma = vma, .address = addr };
  2422. kvm_pfn_t pfn;
  2423. int r;
  2424. r = follow_pfnmap_start(&args);
  2425. if (r) {
  2426. /*
  2427. * get_user_pages fails for VM_IO and VM_PFNMAP vmas and does
  2428. * not call the fault handler, so do it here.
  2429. */
  2430. bool unlocked = false;
  2431. r = fixup_user_fault(current->mm, addr,
  2432. (write_fault ? FAULT_FLAG_WRITE : 0),
  2433. &unlocked);
  2434. if (unlocked)
  2435. return -EAGAIN;
  2436. if (r)
  2437. return r;
  2438. r = follow_pfnmap_start(&args);
  2439. if (r)
  2440. return r;
  2441. }
  2442. if (write_fault && !args.writable) {
  2443. pfn = KVM_PFN_ERR_RO_FAULT;
  2444. goto out;
  2445. }
  2446. if (writable)
  2447. *writable = args.writable;
  2448. pfn = args.pfn;
  2449. /*
  2450. * Get a reference here because callers of *hva_to_pfn* and
  2451. * *gfn_to_pfn* ultimately call kvm_release_pfn_clean on the
  2452. * returned pfn. This is only needed if the VMA has VM_MIXEDMAP
  2453. * set, but the kvm_try_get_pfn/kvm_release_pfn_clean pair will
  2454. * simply do nothing for reserved pfns.
  2455. *
  2456. * Whoever called remap_pfn_range is also going to call e.g.
  2457. * unmap_mapping_range before the underlying pages are freed,
  2458. * causing a call to our MMU notifier.
  2459. *
  2460. * Certain IO or PFNMAP mappings can be backed with valid
  2461. * struct pages, but be allocated without refcounting e.g.,
  2462. * tail pages of non-compound higher order allocations, which
  2463. * would then underflow the refcount when the caller does the
  2464. * required put_page. Don't allow those pages here.
  2465. */
  2466. if (!kvm_try_get_pfn(pfn))
  2467. r = -EFAULT;
  2468. out:
  2469. follow_pfnmap_end(&args);
  2470. *p_pfn = pfn;
  2471. return r;
  2472. }
  2473. /*
  2474. * Pin guest page in memory and return its pfn.
  2475. * @addr: host virtual address which maps memory to the guest
  2476. * @atomic: whether this function is forbidden from sleeping
  2477. * @interruptible: whether the process can be interrupted by non-fatal signals
  2478. * @async: whether this function need to wait IO complete if the
  2479. * host page is not in the memory
  2480. * @write_fault: whether we should get a writable host page
  2481. * @writable: whether it allows to map a writable host page for !@write_fault
  2482. *
  2483. * The function will map a writable host page for these two cases:
  2484. * 1): @write_fault = true
  2485. * 2): @write_fault = false && @writable, @writable will tell the caller
  2486. * whether the mapping is writable.
  2487. */
  2488. kvm_pfn_t hva_to_pfn(unsigned long addr, bool atomic, bool interruptible,
  2489. bool *async, bool write_fault, bool *writable)
  2490. {
  2491. struct vm_area_struct *vma;
  2492. kvm_pfn_t pfn;
  2493. int npages, r;
  2494. /* we can do it either atomically or asynchronously, not both */
  2495. BUG_ON(atomic && async);
  2496. if (hva_to_pfn_fast(addr, write_fault, writable, &pfn))
  2497. return pfn;
  2498. if (atomic)
  2499. return KVM_PFN_ERR_FAULT;
  2500. npages = hva_to_pfn_slow(addr, async, write_fault, interruptible,
  2501. writable, &pfn);
  2502. if (npages == 1)
  2503. return pfn;
  2504. if (npages == -EINTR)
  2505. return KVM_PFN_ERR_SIGPENDING;
  2506. mmap_read_lock(current->mm);
  2507. if (npages == -EHWPOISON ||
  2508. (!async && check_user_page_hwpoison(addr))) {
  2509. pfn = KVM_PFN_ERR_HWPOISON;
  2510. goto exit;
  2511. }
  2512. retry:
  2513. vma = vma_lookup(current->mm, addr);
  2514. if (vma == NULL)
  2515. pfn = KVM_PFN_ERR_FAULT;
  2516. else if (vma->vm_flags & (VM_IO | VM_PFNMAP)) {
  2517. r = hva_to_pfn_remapped(vma, addr, write_fault, writable, &pfn);
  2518. if (r == -EAGAIN)
  2519. goto retry;
  2520. if (r < 0)
  2521. pfn = KVM_PFN_ERR_FAULT;
  2522. } else {
  2523. if (async && vma_is_valid(vma, write_fault))
  2524. *async = true;
  2525. pfn = KVM_PFN_ERR_FAULT;
  2526. }
  2527. exit:
  2528. mmap_read_unlock(current->mm);
  2529. return pfn;
  2530. }
  2531. kvm_pfn_t __gfn_to_pfn_memslot(const struct kvm_memory_slot *slot, gfn_t gfn,
  2532. bool atomic, bool interruptible, bool *async,
  2533. bool write_fault, bool *writable, hva_t *hva)
  2534. {
  2535. unsigned long addr = __gfn_to_hva_many(slot, gfn, NULL, write_fault);
  2536. if (hva)
  2537. *hva = addr;
  2538. if (kvm_is_error_hva(addr)) {
  2539. if (writable)
  2540. *writable = false;
  2541. return addr == KVM_HVA_ERR_RO_BAD ? KVM_PFN_ERR_RO_FAULT :
  2542. KVM_PFN_NOSLOT;
  2543. }
  2544. /* Do not map writable pfn in the readonly memslot. */
  2545. if (writable && memslot_is_readonly(slot)) {
  2546. *writable = false;
  2547. writable = NULL;
  2548. }
  2549. return hva_to_pfn(addr, atomic, interruptible, async, write_fault,
  2550. writable);
  2551. }
  2552. EXPORT_SYMBOL_GPL(__gfn_to_pfn_memslot);
  2553. kvm_pfn_t gfn_to_pfn_prot(struct kvm *kvm, gfn_t gfn, bool write_fault,
  2554. bool *writable)
  2555. {
  2556. return __gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn, false, false,
  2557. NULL, write_fault, writable, NULL);
  2558. }
  2559. EXPORT_SYMBOL_GPL(gfn_to_pfn_prot);
  2560. kvm_pfn_t gfn_to_pfn_memslot(const struct kvm_memory_slot *slot, gfn_t gfn)
  2561. {
  2562. return __gfn_to_pfn_memslot(slot, gfn, false, false, NULL, true,
  2563. NULL, NULL);
  2564. }
  2565. EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot);
  2566. kvm_pfn_t gfn_to_pfn_memslot_atomic(const struct kvm_memory_slot *slot, gfn_t gfn)
  2567. {
  2568. return __gfn_to_pfn_memslot(slot, gfn, true, false, NULL, true,
  2569. NULL, NULL);
  2570. }
  2571. EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot_atomic);
  2572. kvm_pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
  2573. {
  2574. return gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn);
  2575. }
  2576. EXPORT_SYMBOL_GPL(gfn_to_pfn);
  2577. int gfn_to_page_many_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
  2578. struct page **pages, int nr_pages)
  2579. {
  2580. unsigned long addr;
  2581. gfn_t entry = 0;
  2582. addr = gfn_to_hva_many(slot, gfn, &entry);
  2583. if (kvm_is_error_hva(addr))
  2584. return -1;
  2585. if (entry < nr_pages)
  2586. return 0;
  2587. return get_user_pages_fast_only(addr, nr_pages, FOLL_WRITE, pages);
  2588. }
  2589. EXPORT_SYMBOL_GPL(gfn_to_page_many_atomic);
  2590. /*
  2591. * Do not use this helper unless you are absolutely certain the gfn _must_ be
  2592. * backed by 'struct page'. A valid example is if the backing memslot is
  2593. * controlled by KVM. Note, if the returned page is valid, it's refcount has
  2594. * been elevated by gfn_to_pfn().
  2595. */
  2596. struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
  2597. {
  2598. struct page *page;
  2599. kvm_pfn_t pfn;
  2600. pfn = gfn_to_pfn(kvm, gfn);
  2601. if (is_error_noslot_pfn(pfn))
  2602. return KVM_ERR_PTR_BAD_PAGE;
  2603. page = kvm_pfn_to_refcounted_page(pfn);
  2604. if (!page)
  2605. return KVM_ERR_PTR_BAD_PAGE;
  2606. return page;
  2607. }
  2608. EXPORT_SYMBOL_GPL(gfn_to_page);
  2609. void kvm_release_pfn(kvm_pfn_t pfn, bool dirty)
  2610. {
  2611. if (dirty)
  2612. kvm_release_pfn_dirty(pfn);
  2613. else
  2614. kvm_release_pfn_clean(pfn);
  2615. }
  2616. int kvm_vcpu_map(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map)
  2617. {
  2618. kvm_pfn_t pfn;
  2619. void *hva = NULL;
  2620. struct page *page = KVM_UNMAPPED_PAGE;
  2621. if (!map)
  2622. return -EINVAL;
  2623. pfn = gfn_to_pfn(vcpu->kvm, gfn);
  2624. if (is_error_noslot_pfn(pfn))
  2625. return -EINVAL;
  2626. if (pfn_valid(pfn)) {
  2627. page = pfn_to_page(pfn);
  2628. hva = kmap(page);
  2629. #ifdef CONFIG_HAS_IOMEM
  2630. } else {
  2631. hva = memremap(pfn_to_hpa(pfn), PAGE_SIZE, MEMREMAP_WB);
  2632. #endif
  2633. }
  2634. if (!hva)
  2635. return -EFAULT;
  2636. map->page = page;
  2637. map->hva = hva;
  2638. map->pfn = pfn;
  2639. map->gfn = gfn;
  2640. return 0;
  2641. }
  2642. EXPORT_SYMBOL_GPL(kvm_vcpu_map);
  2643. void kvm_vcpu_unmap(struct kvm_vcpu *vcpu, struct kvm_host_map *map, bool dirty)
  2644. {
  2645. if (!map)
  2646. return;
  2647. if (!map->hva)
  2648. return;
  2649. if (map->page != KVM_UNMAPPED_PAGE)
  2650. kunmap(map->page);
  2651. #ifdef CONFIG_HAS_IOMEM
  2652. else
  2653. memunmap(map->hva);
  2654. #endif
  2655. if (dirty)
  2656. kvm_vcpu_mark_page_dirty(vcpu, map->gfn);
  2657. kvm_release_pfn(map->pfn, dirty);
  2658. map->hva = NULL;
  2659. map->page = NULL;
  2660. }
  2661. EXPORT_SYMBOL_GPL(kvm_vcpu_unmap);
  2662. static bool kvm_is_ad_tracked_page(struct page *page)
  2663. {
  2664. /*
  2665. * Per page-flags.h, pages tagged PG_reserved "should in general not be
  2666. * touched (e.g. set dirty) except by its owner".
  2667. */
  2668. return !PageReserved(page);
  2669. }
  2670. static void kvm_set_page_dirty(struct page *page)
  2671. {
  2672. if (kvm_is_ad_tracked_page(page))
  2673. SetPageDirty(page);
  2674. }
  2675. static void kvm_set_page_accessed(struct page *page)
  2676. {
  2677. if (kvm_is_ad_tracked_page(page))
  2678. mark_page_accessed(page);
  2679. }
  2680. void kvm_release_page_clean(struct page *page)
  2681. {
  2682. WARN_ON(is_error_page(page));
  2683. kvm_set_page_accessed(page);
  2684. put_page(page);
  2685. }
  2686. EXPORT_SYMBOL_GPL(kvm_release_page_clean);
  2687. void kvm_release_pfn_clean(kvm_pfn_t pfn)
  2688. {
  2689. struct page *page;
  2690. if (is_error_noslot_pfn(pfn))
  2691. return;
  2692. page = kvm_pfn_to_refcounted_page(pfn);
  2693. if (!page)
  2694. return;
  2695. kvm_release_page_clean(page);
  2696. }
  2697. EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
  2698. void kvm_release_page_dirty(struct page *page)
  2699. {
  2700. WARN_ON(is_error_page(page));
  2701. kvm_set_page_dirty(page);
  2702. kvm_release_page_clean(page);
  2703. }
  2704. EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
  2705. void kvm_release_pfn_dirty(kvm_pfn_t pfn)
  2706. {
  2707. struct page *page;
  2708. if (is_error_noslot_pfn(pfn))
  2709. return;
  2710. page = kvm_pfn_to_refcounted_page(pfn);
  2711. if (!page)
  2712. return;
  2713. kvm_release_page_dirty(page);
  2714. }
  2715. EXPORT_SYMBOL_GPL(kvm_release_pfn_dirty);
  2716. /*
  2717. * Note, checking for an error/noslot pfn is the caller's responsibility when
  2718. * directly marking a page dirty/accessed. Unlike the "release" helpers, the
  2719. * "set" helpers are not to be used when the pfn might point at garbage.
  2720. */
  2721. void kvm_set_pfn_dirty(kvm_pfn_t pfn)
  2722. {
  2723. if (WARN_ON(is_error_noslot_pfn(pfn)))
  2724. return;
  2725. if (pfn_valid(pfn))
  2726. kvm_set_page_dirty(pfn_to_page(pfn));
  2727. }
  2728. EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
  2729. void kvm_set_pfn_accessed(kvm_pfn_t pfn)
  2730. {
  2731. if (WARN_ON(is_error_noslot_pfn(pfn)))
  2732. return;
  2733. if (pfn_valid(pfn))
  2734. kvm_set_page_accessed(pfn_to_page(pfn));
  2735. }
  2736. EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
  2737. static int next_segment(unsigned long len, int offset)
  2738. {
  2739. if (len > PAGE_SIZE - offset)
  2740. return PAGE_SIZE - offset;
  2741. else
  2742. return len;
  2743. }
  2744. /* Copy @len bytes from guest memory at '(@gfn * PAGE_SIZE) + @offset' to @data */
  2745. static int __kvm_read_guest_page(struct kvm_memory_slot *slot, gfn_t gfn,
  2746. void *data, int offset, int len)
  2747. {
  2748. int r;
  2749. unsigned long addr;
  2750. if (WARN_ON_ONCE(offset + len > PAGE_SIZE))
  2751. return -EFAULT;
  2752. addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
  2753. if (kvm_is_error_hva(addr))
  2754. return -EFAULT;
  2755. r = __copy_from_user(data, (void __user *)addr + offset, len);
  2756. if (r)
  2757. return -EFAULT;
  2758. return 0;
  2759. }
  2760. int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
  2761. int len)
  2762. {
  2763. struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
  2764. return __kvm_read_guest_page(slot, gfn, data, offset, len);
  2765. }
  2766. EXPORT_SYMBOL_GPL(kvm_read_guest_page);
  2767. int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data,
  2768. int offset, int len)
  2769. {
  2770. struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
  2771. return __kvm_read_guest_page(slot, gfn, data, offset, len);
  2772. }
  2773. EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_page);
  2774. int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
  2775. {
  2776. gfn_t gfn = gpa >> PAGE_SHIFT;
  2777. int seg;
  2778. int offset = offset_in_page(gpa);
  2779. int ret;
  2780. while ((seg = next_segment(len, offset)) != 0) {
  2781. ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
  2782. if (ret < 0)
  2783. return ret;
  2784. offset = 0;
  2785. len -= seg;
  2786. data += seg;
  2787. ++gfn;
  2788. }
  2789. return 0;
  2790. }
  2791. EXPORT_SYMBOL_GPL(kvm_read_guest);
  2792. int kvm_vcpu_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, unsigned long len)
  2793. {
  2794. gfn_t gfn = gpa >> PAGE_SHIFT;
  2795. int seg;
  2796. int offset = offset_in_page(gpa);
  2797. int ret;
  2798. while ((seg = next_segment(len, offset)) != 0) {
  2799. ret = kvm_vcpu_read_guest_page(vcpu, gfn, data, offset, seg);
  2800. if (ret < 0)
  2801. return ret;
  2802. offset = 0;
  2803. len -= seg;
  2804. data += seg;
  2805. ++gfn;
  2806. }
  2807. return 0;
  2808. }
  2809. EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest);
  2810. static int __kvm_read_guest_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
  2811. void *data, int offset, unsigned long len)
  2812. {
  2813. int r;
  2814. unsigned long addr;
  2815. if (WARN_ON_ONCE(offset + len > PAGE_SIZE))
  2816. return -EFAULT;
  2817. addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
  2818. if (kvm_is_error_hva(addr))
  2819. return -EFAULT;
  2820. pagefault_disable();
  2821. r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
  2822. pagefault_enable();
  2823. if (r)
  2824. return -EFAULT;
  2825. return 0;
  2826. }
  2827. int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa,
  2828. void *data, unsigned long len)
  2829. {
  2830. gfn_t gfn = gpa >> PAGE_SHIFT;
  2831. struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
  2832. int offset = offset_in_page(gpa);
  2833. return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
  2834. }
  2835. EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_atomic);
  2836. /* Copy @len bytes from @data into guest memory at '(@gfn * PAGE_SIZE) + @offset' */
  2837. static int __kvm_write_guest_page(struct kvm *kvm,
  2838. struct kvm_memory_slot *memslot, gfn_t gfn,
  2839. const void *data, int offset, int len)
  2840. {
  2841. int r;
  2842. unsigned long addr;
  2843. if (WARN_ON_ONCE(offset + len > PAGE_SIZE))
  2844. return -EFAULT;
  2845. addr = gfn_to_hva_memslot(memslot, gfn);
  2846. if (kvm_is_error_hva(addr))
  2847. return -EFAULT;
  2848. r = __copy_to_user((void __user *)addr + offset, data, len);
  2849. if (r)
  2850. return -EFAULT;
  2851. mark_page_dirty_in_slot(kvm, memslot, gfn);
  2852. return 0;
  2853. }
  2854. int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn,
  2855. const void *data, int offset, int len)
  2856. {
  2857. struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
  2858. return __kvm_write_guest_page(kvm, slot, gfn, data, offset, len);
  2859. }
  2860. EXPORT_SYMBOL_GPL(kvm_write_guest_page);
  2861. int kvm_vcpu_write_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
  2862. const void *data, int offset, int len)
  2863. {
  2864. struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
  2865. return __kvm_write_guest_page(vcpu->kvm, slot, gfn, data, offset, len);
  2866. }
  2867. EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest_page);
  2868. int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
  2869. unsigned long len)
  2870. {
  2871. gfn_t gfn = gpa >> PAGE_SHIFT;
  2872. int seg;
  2873. int offset = offset_in_page(gpa);
  2874. int ret;
  2875. while ((seg = next_segment(len, offset)) != 0) {
  2876. ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
  2877. if (ret < 0)
  2878. return ret;
  2879. offset = 0;
  2880. len -= seg;
  2881. data += seg;
  2882. ++gfn;
  2883. }
  2884. return 0;
  2885. }
  2886. EXPORT_SYMBOL_GPL(kvm_write_guest);
  2887. int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data,
  2888. unsigned long len)
  2889. {
  2890. gfn_t gfn = gpa >> PAGE_SHIFT;
  2891. int seg;
  2892. int offset = offset_in_page(gpa);
  2893. int ret;
  2894. while ((seg = next_segment(len, offset)) != 0) {
  2895. ret = kvm_vcpu_write_guest_page(vcpu, gfn, data, offset, seg);
  2896. if (ret < 0)
  2897. return ret;
  2898. offset = 0;
  2899. len -= seg;
  2900. data += seg;
  2901. ++gfn;
  2902. }
  2903. return 0;
  2904. }
  2905. EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest);
  2906. static int __kvm_gfn_to_hva_cache_init(struct kvm_memslots *slots,
  2907. struct gfn_to_hva_cache *ghc,
  2908. gpa_t gpa, unsigned long len)
  2909. {
  2910. int offset = offset_in_page(gpa);
  2911. gfn_t start_gfn = gpa >> PAGE_SHIFT;
  2912. gfn_t end_gfn = (gpa + len - 1) >> PAGE_SHIFT;
  2913. gfn_t nr_pages_needed = end_gfn - start_gfn + 1;
  2914. gfn_t nr_pages_avail;
  2915. /* Update ghc->generation before performing any error checks. */
  2916. ghc->generation = slots->generation;
  2917. if (start_gfn > end_gfn) {
  2918. ghc->hva = KVM_HVA_ERR_BAD;
  2919. return -EINVAL;
  2920. }
  2921. /*
  2922. * If the requested region crosses two memslots, we still
  2923. * verify that the entire region is valid here.
  2924. */
  2925. for ( ; start_gfn <= end_gfn; start_gfn += nr_pages_avail) {
  2926. ghc->memslot = __gfn_to_memslot(slots, start_gfn);
  2927. ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn,
  2928. &nr_pages_avail);
  2929. if (kvm_is_error_hva(ghc->hva))
  2930. return -EFAULT;
  2931. }
  2932. /* Use the slow path for cross page reads and writes. */
  2933. if (nr_pages_needed == 1)
  2934. ghc->hva += offset;
  2935. else
  2936. ghc->memslot = NULL;
  2937. ghc->gpa = gpa;
  2938. ghc->len = len;
  2939. return 0;
  2940. }
  2941. int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
  2942. gpa_t gpa, unsigned long len)
  2943. {
  2944. struct kvm_memslots *slots = kvm_memslots(kvm);
  2945. return __kvm_gfn_to_hva_cache_init(slots, ghc, gpa, len);
  2946. }
  2947. EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init);
  2948. int kvm_write_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
  2949. void *data, unsigned int offset,
  2950. unsigned long len)
  2951. {
  2952. struct kvm_memslots *slots = kvm_memslots(kvm);
  2953. int r;
  2954. gpa_t gpa = ghc->gpa + offset;
  2955. if (WARN_ON_ONCE(len + offset > ghc->len))
  2956. return -EINVAL;
  2957. if (slots->generation != ghc->generation) {
  2958. if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
  2959. return -EFAULT;
  2960. }
  2961. if (kvm_is_error_hva(ghc->hva))
  2962. return -EFAULT;
  2963. if (unlikely(!ghc->memslot))
  2964. return kvm_write_guest(kvm, gpa, data, len);
  2965. r = __copy_to_user((void __user *)ghc->hva + offset, data, len);
  2966. if (r)
  2967. return -EFAULT;
  2968. mark_page_dirty_in_slot(kvm, ghc->memslot, gpa >> PAGE_SHIFT);
  2969. return 0;
  2970. }
  2971. EXPORT_SYMBOL_GPL(kvm_write_guest_offset_cached);
  2972. int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
  2973. void *data, unsigned long len)
  2974. {
  2975. return kvm_write_guest_offset_cached(kvm, ghc, data, 0, len);
  2976. }
  2977. EXPORT_SYMBOL_GPL(kvm_write_guest_cached);
  2978. int kvm_read_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
  2979. void *data, unsigned int offset,
  2980. unsigned long len)
  2981. {
  2982. struct kvm_memslots *slots = kvm_memslots(kvm);
  2983. int r;
  2984. gpa_t gpa = ghc->gpa + offset;
  2985. if (WARN_ON_ONCE(len + offset > ghc->len))
  2986. return -EINVAL;
  2987. if (slots->generation != ghc->generation) {
  2988. if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
  2989. return -EFAULT;
  2990. }
  2991. if (kvm_is_error_hva(ghc->hva))
  2992. return -EFAULT;
  2993. if (unlikely(!ghc->memslot))
  2994. return kvm_read_guest(kvm, gpa, data, len);
  2995. r = __copy_from_user(data, (void __user *)ghc->hva + offset, len);
  2996. if (r)
  2997. return -EFAULT;
  2998. return 0;
  2999. }
  3000. EXPORT_SYMBOL_GPL(kvm_read_guest_offset_cached);
  3001. int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
  3002. void *data, unsigned long len)
  3003. {
  3004. return kvm_read_guest_offset_cached(kvm, ghc, data, 0, len);
  3005. }
  3006. EXPORT_SYMBOL_GPL(kvm_read_guest_cached);
  3007. int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
  3008. {
  3009. const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
  3010. gfn_t gfn = gpa >> PAGE_SHIFT;
  3011. int seg;
  3012. int offset = offset_in_page(gpa);
  3013. int ret;
  3014. while ((seg = next_segment(len, offset)) != 0) {
  3015. ret = kvm_write_guest_page(kvm, gfn, zero_page, offset, seg);
  3016. if (ret < 0)
  3017. return ret;
  3018. offset = 0;
  3019. len -= seg;
  3020. ++gfn;
  3021. }
  3022. return 0;
  3023. }
  3024. EXPORT_SYMBOL_GPL(kvm_clear_guest);
  3025. void mark_page_dirty_in_slot(struct kvm *kvm,
  3026. const struct kvm_memory_slot *memslot,
  3027. gfn_t gfn)
  3028. {
  3029. struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
  3030. #ifdef CONFIG_HAVE_KVM_DIRTY_RING
  3031. if (WARN_ON_ONCE(vcpu && vcpu->kvm != kvm))
  3032. return;
  3033. WARN_ON_ONCE(!vcpu && !kvm_arch_allow_write_without_running_vcpu(kvm));
  3034. #endif
  3035. if (memslot && kvm_slot_dirty_track_enabled(memslot)) {
  3036. unsigned long rel_gfn = gfn - memslot->base_gfn;
  3037. u32 slot = (memslot->as_id << 16) | memslot->id;
  3038. if (kvm->dirty_ring_size && vcpu)
  3039. kvm_dirty_ring_push(vcpu, slot, rel_gfn);
  3040. else if (memslot->dirty_bitmap)
  3041. set_bit_le(rel_gfn, memslot->dirty_bitmap);
  3042. }
  3043. }
  3044. EXPORT_SYMBOL_GPL(mark_page_dirty_in_slot);
  3045. void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
  3046. {
  3047. struct kvm_memory_slot *memslot;
  3048. memslot = gfn_to_memslot(kvm, gfn);
  3049. mark_page_dirty_in_slot(kvm, memslot, gfn);
  3050. }
  3051. EXPORT_SYMBOL_GPL(mark_page_dirty);
  3052. void kvm_vcpu_mark_page_dirty(struct kvm_vcpu *vcpu, gfn_t gfn)
  3053. {
  3054. struct kvm_memory_slot *memslot;
  3055. memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
  3056. mark_page_dirty_in_slot(vcpu->kvm, memslot, gfn);
  3057. }
  3058. EXPORT_SYMBOL_GPL(kvm_vcpu_mark_page_dirty);
  3059. void kvm_sigset_activate(struct kvm_vcpu *vcpu)
  3060. {
  3061. if (!vcpu->sigset_active)
  3062. return;
  3063. /*
  3064. * This does a lockless modification of ->real_blocked, which is fine
  3065. * because, only current can change ->real_blocked and all readers of
  3066. * ->real_blocked don't care as long ->real_blocked is always a subset
  3067. * of ->blocked.
  3068. */
  3069. sigprocmask(SIG_SETMASK, &vcpu->sigset, &current->real_blocked);
  3070. }
  3071. void kvm_sigset_deactivate(struct kvm_vcpu *vcpu)
  3072. {
  3073. if (!vcpu->sigset_active)
  3074. return;
  3075. sigprocmask(SIG_SETMASK, &current->real_blocked, NULL);
  3076. sigemptyset(&current->real_blocked);
  3077. }
  3078. static void grow_halt_poll_ns(struct kvm_vcpu *vcpu)
  3079. {
  3080. unsigned int old, val, grow, grow_start;
  3081. old = val = vcpu->halt_poll_ns;
  3082. grow_start = READ_ONCE(halt_poll_ns_grow_start);
  3083. grow = READ_ONCE(halt_poll_ns_grow);
  3084. if (!grow)
  3085. goto out;
  3086. val *= grow;
  3087. if (val < grow_start)
  3088. val = grow_start;
  3089. vcpu->halt_poll_ns = val;
  3090. out:
  3091. trace_kvm_halt_poll_ns_grow(vcpu->vcpu_id, val, old);
  3092. }
  3093. static void shrink_halt_poll_ns(struct kvm_vcpu *vcpu)
  3094. {
  3095. unsigned int old, val, shrink, grow_start;
  3096. old = val = vcpu->halt_poll_ns;
  3097. shrink = READ_ONCE(halt_poll_ns_shrink);
  3098. grow_start = READ_ONCE(halt_poll_ns_grow_start);
  3099. if (shrink == 0)
  3100. val = 0;
  3101. else
  3102. val /= shrink;
  3103. if (val < grow_start)
  3104. val = 0;
  3105. vcpu->halt_poll_ns = val;
  3106. trace_kvm_halt_poll_ns_shrink(vcpu->vcpu_id, val, old);
  3107. }
  3108. static int kvm_vcpu_check_block(struct kvm_vcpu *vcpu)
  3109. {
  3110. int ret = -EINTR;
  3111. int idx = srcu_read_lock(&vcpu->kvm->srcu);
  3112. if (kvm_arch_vcpu_runnable(vcpu))
  3113. goto out;
  3114. if (kvm_cpu_has_pending_timer(vcpu))
  3115. goto out;
  3116. if (signal_pending(current))
  3117. goto out;
  3118. if (kvm_check_request(KVM_REQ_UNBLOCK, vcpu))
  3119. goto out;
  3120. ret = 0;
  3121. out:
  3122. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  3123. return ret;
  3124. }
  3125. /*
  3126. * Block the vCPU until the vCPU is runnable, an event arrives, or a signal is
  3127. * pending. This is mostly used when halting a vCPU, but may also be used
  3128. * directly for other vCPU non-runnable states, e.g. x86's Wait-For-SIPI.
  3129. */
  3130. bool kvm_vcpu_block(struct kvm_vcpu *vcpu)
  3131. {
  3132. struct rcuwait *wait = kvm_arch_vcpu_get_wait(vcpu);
  3133. bool waited = false;
  3134. vcpu->stat.generic.blocking = 1;
  3135. preempt_disable();
  3136. kvm_arch_vcpu_blocking(vcpu);
  3137. prepare_to_rcuwait(wait);
  3138. preempt_enable();
  3139. for (;;) {
  3140. set_current_state(TASK_INTERRUPTIBLE);
  3141. if (kvm_vcpu_check_block(vcpu) < 0)
  3142. break;
  3143. waited = true;
  3144. schedule();
  3145. }
  3146. preempt_disable();
  3147. finish_rcuwait(wait);
  3148. kvm_arch_vcpu_unblocking(vcpu);
  3149. preempt_enable();
  3150. vcpu->stat.generic.blocking = 0;
  3151. return waited;
  3152. }
  3153. static inline void update_halt_poll_stats(struct kvm_vcpu *vcpu, ktime_t start,
  3154. ktime_t end, bool success)
  3155. {
  3156. struct kvm_vcpu_stat_generic *stats = &vcpu->stat.generic;
  3157. u64 poll_ns = ktime_to_ns(ktime_sub(end, start));
  3158. ++vcpu->stat.generic.halt_attempted_poll;
  3159. if (success) {
  3160. ++vcpu->stat.generic.halt_successful_poll;
  3161. if (!vcpu_valid_wakeup(vcpu))
  3162. ++vcpu->stat.generic.halt_poll_invalid;
  3163. stats->halt_poll_success_ns += poll_ns;
  3164. KVM_STATS_LOG_HIST_UPDATE(stats->halt_poll_success_hist, poll_ns);
  3165. } else {
  3166. stats->halt_poll_fail_ns += poll_ns;
  3167. KVM_STATS_LOG_HIST_UPDATE(stats->halt_poll_fail_hist, poll_ns);
  3168. }
  3169. }
  3170. static unsigned int kvm_vcpu_max_halt_poll_ns(struct kvm_vcpu *vcpu)
  3171. {
  3172. struct kvm *kvm = vcpu->kvm;
  3173. if (kvm->override_halt_poll_ns) {
  3174. /*
  3175. * Ensure kvm->max_halt_poll_ns is not read before
  3176. * kvm->override_halt_poll_ns.
  3177. *
  3178. * Pairs with the smp_wmb() when enabling KVM_CAP_HALT_POLL.
  3179. */
  3180. smp_rmb();
  3181. return READ_ONCE(kvm->max_halt_poll_ns);
  3182. }
  3183. return READ_ONCE(halt_poll_ns);
  3184. }
  3185. /*
  3186. * Emulate a vCPU halt condition, e.g. HLT on x86, WFI on arm, etc... If halt
  3187. * polling is enabled, busy wait for a short time before blocking to avoid the
  3188. * expensive block+unblock sequence if a wake event arrives soon after the vCPU
  3189. * is halted.
  3190. */
  3191. void kvm_vcpu_halt(struct kvm_vcpu *vcpu)
  3192. {
  3193. unsigned int max_halt_poll_ns = kvm_vcpu_max_halt_poll_ns(vcpu);
  3194. bool halt_poll_allowed = !kvm_arch_no_poll(vcpu);
  3195. ktime_t start, cur, poll_end;
  3196. bool waited = false;
  3197. bool do_halt_poll;
  3198. u64 halt_ns;
  3199. if (vcpu->halt_poll_ns > max_halt_poll_ns)
  3200. vcpu->halt_poll_ns = max_halt_poll_ns;
  3201. do_halt_poll = halt_poll_allowed && vcpu->halt_poll_ns;
  3202. start = cur = poll_end = ktime_get();
  3203. if (do_halt_poll) {
  3204. ktime_t stop = ktime_add_ns(start, vcpu->halt_poll_ns);
  3205. do {
  3206. if (kvm_vcpu_check_block(vcpu) < 0)
  3207. goto out;
  3208. cpu_relax();
  3209. poll_end = cur = ktime_get();
  3210. } while (kvm_vcpu_can_poll(cur, stop));
  3211. }
  3212. waited = kvm_vcpu_block(vcpu);
  3213. cur = ktime_get();
  3214. if (waited) {
  3215. vcpu->stat.generic.halt_wait_ns +=
  3216. ktime_to_ns(cur) - ktime_to_ns(poll_end);
  3217. KVM_STATS_LOG_HIST_UPDATE(vcpu->stat.generic.halt_wait_hist,
  3218. ktime_to_ns(cur) - ktime_to_ns(poll_end));
  3219. }
  3220. out:
  3221. /* The total time the vCPU was "halted", including polling time. */
  3222. halt_ns = ktime_to_ns(cur) - ktime_to_ns(start);
  3223. /*
  3224. * Note, halt-polling is considered successful so long as the vCPU was
  3225. * never actually scheduled out, i.e. even if the wake event arrived
  3226. * after of the halt-polling loop itself, but before the full wait.
  3227. */
  3228. if (do_halt_poll)
  3229. update_halt_poll_stats(vcpu, start, poll_end, !waited);
  3230. if (halt_poll_allowed) {
  3231. /* Recompute the max halt poll time in case it changed. */
  3232. max_halt_poll_ns = kvm_vcpu_max_halt_poll_ns(vcpu);
  3233. if (!vcpu_valid_wakeup(vcpu)) {
  3234. shrink_halt_poll_ns(vcpu);
  3235. } else if (max_halt_poll_ns) {
  3236. if (halt_ns <= vcpu->halt_poll_ns)
  3237. ;
  3238. /* we had a long block, shrink polling */
  3239. else if (vcpu->halt_poll_ns &&
  3240. halt_ns > max_halt_poll_ns)
  3241. shrink_halt_poll_ns(vcpu);
  3242. /* we had a short halt and our poll time is too small */
  3243. else if (vcpu->halt_poll_ns < max_halt_poll_ns &&
  3244. halt_ns < max_halt_poll_ns)
  3245. grow_halt_poll_ns(vcpu);
  3246. } else {
  3247. vcpu->halt_poll_ns = 0;
  3248. }
  3249. }
  3250. trace_kvm_vcpu_wakeup(halt_ns, waited, vcpu_valid_wakeup(vcpu));
  3251. }
  3252. EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
  3253. bool kvm_vcpu_wake_up(struct kvm_vcpu *vcpu)
  3254. {
  3255. if (__kvm_vcpu_wake_up(vcpu)) {
  3256. WRITE_ONCE(vcpu->ready, true);
  3257. ++vcpu->stat.generic.halt_wakeup;
  3258. return true;
  3259. }
  3260. return false;
  3261. }
  3262. EXPORT_SYMBOL_GPL(kvm_vcpu_wake_up);
  3263. #ifndef CONFIG_S390
  3264. /*
  3265. * Kick a sleeping VCPU, or a guest VCPU in guest mode, into host kernel mode.
  3266. */
  3267. void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
  3268. {
  3269. int me, cpu;
  3270. if (kvm_vcpu_wake_up(vcpu))
  3271. return;
  3272. me = get_cpu();
  3273. /*
  3274. * The only state change done outside the vcpu mutex is IN_GUEST_MODE
  3275. * to EXITING_GUEST_MODE. Therefore the moderately expensive "should
  3276. * kick" check does not need atomic operations if kvm_vcpu_kick is used
  3277. * within the vCPU thread itself.
  3278. */
  3279. if (vcpu == __this_cpu_read(kvm_running_vcpu)) {
  3280. if (vcpu->mode == IN_GUEST_MODE)
  3281. WRITE_ONCE(vcpu->mode, EXITING_GUEST_MODE);
  3282. goto out;
  3283. }
  3284. /*
  3285. * Note, the vCPU could get migrated to a different pCPU at any point
  3286. * after kvm_arch_vcpu_should_kick(), which could result in sending an
  3287. * IPI to the previous pCPU. But, that's ok because the purpose of the
  3288. * IPI is to force the vCPU to leave IN_GUEST_MODE, and migrating the
  3289. * vCPU also requires it to leave IN_GUEST_MODE.
  3290. */
  3291. if (kvm_arch_vcpu_should_kick(vcpu)) {
  3292. cpu = READ_ONCE(vcpu->cpu);
  3293. if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
  3294. smp_send_reschedule(cpu);
  3295. }
  3296. out:
  3297. put_cpu();
  3298. }
  3299. EXPORT_SYMBOL_GPL(kvm_vcpu_kick);
  3300. #endif /* !CONFIG_S390 */
  3301. int kvm_vcpu_yield_to(struct kvm_vcpu *target)
  3302. {
  3303. struct pid *pid;
  3304. struct task_struct *task = NULL;
  3305. int ret = 0;
  3306. rcu_read_lock();
  3307. pid = rcu_dereference(target->pid);
  3308. if (pid)
  3309. task = get_pid_task(pid, PIDTYPE_PID);
  3310. rcu_read_unlock();
  3311. if (!task)
  3312. return ret;
  3313. ret = yield_to(task, 1);
  3314. put_task_struct(task);
  3315. return ret;
  3316. }
  3317. EXPORT_SYMBOL_GPL(kvm_vcpu_yield_to);
  3318. /*
  3319. * Helper that checks whether a VCPU is eligible for directed yield.
  3320. * Most eligible candidate to yield is decided by following heuristics:
  3321. *
  3322. * (a) VCPU which has not done pl-exit or cpu relax intercepted recently
  3323. * (preempted lock holder), indicated by @in_spin_loop.
  3324. * Set at the beginning and cleared at the end of interception/PLE handler.
  3325. *
  3326. * (b) VCPU which has done pl-exit/ cpu relax intercepted but did not get
  3327. * chance last time (mostly it has become eligible now since we have probably
  3328. * yielded to lockholder in last iteration. This is done by toggling
  3329. * @dy_eligible each time a VCPU checked for eligibility.)
  3330. *
  3331. * Yielding to a recently pl-exited/cpu relax intercepted VCPU before yielding
  3332. * to preempted lock-holder could result in wrong VCPU selection and CPU
  3333. * burning. Giving priority for a potential lock-holder increases lock
  3334. * progress.
  3335. *
  3336. * Since algorithm is based on heuristics, accessing another VCPU data without
  3337. * locking does not harm. It may result in trying to yield to same VCPU, fail
  3338. * and continue with next VCPU and so on.
  3339. */
  3340. static bool kvm_vcpu_eligible_for_directed_yield(struct kvm_vcpu *vcpu)
  3341. {
  3342. #ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT
  3343. bool eligible;
  3344. eligible = !vcpu->spin_loop.in_spin_loop ||
  3345. vcpu->spin_loop.dy_eligible;
  3346. if (vcpu->spin_loop.in_spin_loop)
  3347. kvm_vcpu_set_dy_eligible(vcpu, !vcpu->spin_loop.dy_eligible);
  3348. return eligible;
  3349. #else
  3350. return true;
  3351. #endif
  3352. }
  3353. /*
  3354. * Unlike kvm_arch_vcpu_runnable, this function is called outside
  3355. * a vcpu_load/vcpu_put pair. However, for most architectures
  3356. * kvm_arch_vcpu_runnable does not require vcpu_load.
  3357. */
  3358. bool __weak kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
  3359. {
  3360. return kvm_arch_vcpu_runnable(vcpu);
  3361. }
  3362. static bool vcpu_dy_runnable(struct kvm_vcpu *vcpu)
  3363. {
  3364. if (kvm_arch_dy_runnable(vcpu))
  3365. return true;
  3366. #ifdef CONFIG_KVM_ASYNC_PF
  3367. if (!list_empty_careful(&vcpu->async_pf.done))
  3368. return true;
  3369. #endif
  3370. return false;
  3371. }
  3372. /*
  3373. * By default, simply query the target vCPU's current mode when checking if a
  3374. * vCPU was preempted in kernel mode. All architectures except x86 (or more
  3375. * specifical, except VMX) allow querying whether or not a vCPU is in kernel
  3376. * mode even if the vCPU is NOT loaded, i.e. using kvm_arch_vcpu_in_kernel()
  3377. * directly for cross-vCPU checks is functionally correct and accurate.
  3378. */
  3379. bool __weak kvm_arch_vcpu_preempted_in_kernel(struct kvm_vcpu *vcpu)
  3380. {
  3381. return kvm_arch_vcpu_in_kernel(vcpu);
  3382. }
  3383. bool __weak kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu)
  3384. {
  3385. return false;
  3386. }
  3387. void kvm_vcpu_on_spin(struct kvm_vcpu *me, bool yield_to_kernel_mode)
  3388. {
  3389. struct kvm *kvm = me->kvm;
  3390. struct kvm_vcpu *vcpu;
  3391. int last_boosted_vcpu;
  3392. unsigned long i;
  3393. int yielded = 0;
  3394. int try = 3;
  3395. int pass;
  3396. last_boosted_vcpu = READ_ONCE(kvm->last_boosted_vcpu);
  3397. kvm_vcpu_set_in_spin_loop(me, true);
  3398. /*
  3399. * We boost the priority of a VCPU that is runnable but not
  3400. * currently running, because it got preempted by something
  3401. * else and called schedule in __vcpu_run. Hopefully that
  3402. * VCPU is holding the lock that we need and will release it.
  3403. * We approximate round-robin by starting at the last boosted VCPU.
  3404. */
  3405. for (pass = 0; pass < 2 && !yielded && try; pass++) {
  3406. kvm_for_each_vcpu(i, vcpu, kvm) {
  3407. if (!pass && i <= last_boosted_vcpu) {
  3408. i = last_boosted_vcpu;
  3409. continue;
  3410. } else if (pass && i > last_boosted_vcpu)
  3411. break;
  3412. if (!READ_ONCE(vcpu->ready))
  3413. continue;
  3414. if (vcpu == me)
  3415. continue;
  3416. if (kvm_vcpu_is_blocking(vcpu) && !vcpu_dy_runnable(vcpu))
  3417. continue;
  3418. /*
  3419. * Treat the target vCPU as being in-kernel if it has a
  3420. * pending interrupt, as the vCPU trying to yield may
  3421. * be spinning waiting on IPI delivery, i.e. the target
  3422. * vCPU is in-kernel for the purposes of directed yield.
  3423. */
  3424. if (READ_ONCE(vcpu->preempted) && yield_to_kernel_mode &&
  3425. !kvm_arch_dy_has_pending_interrupt(vcpu) &&
  3426. !kvm_arch_vcpu_preempted_in_kernel(vcpu))
  3427. continue;
  3428. if (!kvm_vcpu_eligible_for_directed_yield(vcpu))
  3429. continue;
  3430. yielded = kvm_vcpu_yield_to(vcpu);
  3431. if (yielded > 0) {
  3432. WRITE_ONCE(kvm->last_boosted_vcpu, i);
  3433. break;
  3434. } else if (yielded < 0) {
  3435. try--;
  3436. if (!try)
  3437. break;
  3438. }
  3439. }
  3440. }
  3441. kvm_vcpu_set_in_spin_loop(me, false);
  3442. /* Ensure vcpu is not eligible during next spinloop */
  3443. kvm_vcpu_set_dy_eligible(me, false);
  3444. }
  3445. EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
  3446. static bool kvm_page_in_dirty_ring(struct kvm *kvm, unsigned long pgoff)
  3447. {
  3448. #ifdef CONFIG_HAVE_KVM_DIRTY_RING
  3449. return (pgoff >= KVM_DIRTY_LOG_PAGE_OFFSET) &&
  3450. (pgoff < KVM_DIRTY_LOG_PAGE_OFFSET +
  3451. kvm->dirty_ring_size / PAGE_SIZE);
  3452. #else
  3453. return false;
  3454. #endif
  3455. }
  3456. static vm_fault_t kvm_vcpu_fault(struct vm_fault *vmf)
  3457. {
  3458. struct kvm_vcpu *vcpu = vmf->vma->vm_file->private_data;
  3459. struct page *page;
  3460. if (vmf->pgoff == 0)
  3461. page = virt_to_page(vcpu->run);
  3462. #ifdef CONFIG_X86
  3463. else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
  3464. page = virt_to_page(vcpu->arch.pio_data);
  3465. #endif
  3466. #ifdef CONFIG_KVM_MMIO
  3467. else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
  3468. page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
  3469. #endif
  3470. else if (kvm_page_in_dirty_ring(vcpu->kvm, vmf->pgoff))
  3471. page = kvm_dirty_ring_get_page(
  3472. &vcpu->dirty_ring,
  3473. vmf->pgoff - KVM_DIRTY_LOG_PAGE_OFFSET);
  3474. else
  3475. return kvm_arch_vcpu_fault(vcpu, vmf);
  3476. get_page(page);
  3477. vmf->page = page;
  3478. return 0;
  3479. }
  3480. static const struct vm_operations_struct kvm_vcpu_vm_ops = {
  3481. .fault = kvm_vcpu_fault,
  3482. };
  3483. static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
  3484. {
  3485. struct kvm_vcpu *vcpu = file->private_data;
  3486. unsigned long pages = vma_pages(vma);
  3487. if ((kvm_page_in_dirty_ring(vcpu->kvm, vma->vm_pgoff) ||
  3488. kvm_page_in_dirty_ring(vcpu->kvm, vma->vm_pgoff + pages - 1)) &&
  3489. ((vma->vm_flags & VM_EXEC) || !(vma->vm_flags & VM_SHARED)))
  3490. return -EINVAL;
  3491. vma->vm_ops = &kvm_vcpu_vm_ops;
  3492. return 0;
  3493. }
  3494. static int kvm_vcpu_release(struct inode *inode, struct file *filp)
  3495. {
  3496. struct kvm_vcpu *vcpu = filp->private_data;
  3497. kvm_put_kvm(vcpu->kvm);
  3498. return 0;
  3499. }
  3500. static struct file_operations kvm_vcpu_fops = {
  3501. .release = kvm_vcpu_release,
  3502. .unlocked_ioctl = kvm_vcpu_ioctl,
  3503. .mmap = kvm_vcpu_mmap,
  3504. .llseek = noop_llseek,
  3505. KVM_COMPAT(kvm_vcpu_compat_ioctl),
  3506. };
  3507. /*
  3508. * Allocates an inode for the vcpu.
  3509. */
  3510. static int create_vcpu_fd(struct kvm_vcpu *vcpu)
  3511. {
  3512. char name[8 + 1 + ITOA_MAX_LEN + 1];
  3513. snprintf(name, sizeof(name), "kvm-vcpu:%d", vcpu->vcpu_id);
  3514. return anon_inode_getfd(name, &kvm_vcpu_fops, vcpu, O_RDWR | O_CLOEXEC);
  3515. }
  3516. #ifdef __KVM_HAVE_ARCH_VCPU_DEBUGFS
  3517. static int vcpu_get_pid(void *data, u64 *val)
  3518. {
  3519. struct kvm_vcpu *vcpu = data;
  3520. rcu_read_lock();
  3521. *val = pid_nr(rcu_dereference(vcpu->pid));
  3522. rcu_read_unlock();
  3523. return 0;
  3524. }
  3525. DEFINE_SIMPLE_ATTRIBUTE(vcpu_get_pid_fops, vcpu_get_pid, NULL, "%llu\n");
  3526. static void kvm_create_vcpu_debugfs(struct kvm_vcpu *vcpu)
  3527. {
  3528. struct dentry *debugfs_dentry;
  3529. char dir_name[ITOA_MAX_LEN * 2];
  3530. if (!debugfs_initialized())
  3531. return;
  3532. snprintf(dir_name, sizeof(dir_name), "vcpu%d", vcpu->vcpu_id);
  3533. debugfs_dentry = debugfs_create_dir(dir_name,
  3534. vcpu->kvm->debugfs_dentry);
  3535. debugfs_create_file("pid", 0444, debugfs_dentry, vcpu,
  3536. &vcpu_get_pid_fops);
  3537. kvm_arch_create_vcpu_debugfs(vcpu, debugfs_dentry);
  3538. }
  3539. #endif
  3540. /*
  3541. * Creates some virtual cpus. Good luck creating more than one.
  3542. */
  3543. static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, unsigned long id)
  3544. {
  3545. int r;
  3546. struct kvm_vcpu *vcpu;
  3547. struct page *page;
  3548. /*
  3549. * KVM tracks vCPU IDs as 'int', be kind to userspace and reject
  3550. * too-large values instead of silently truncating.
  3551. *
  3552. * Ensure KVM_MAX_VCPU_IDS isn't pushed above INT_MAX without first
  3553. * changing the storage type (at the very least, IDs should be tracked
  3554. * as unsigned ints).
  3555. */
  3556. BUILD_BUG_ON(KVM_MAX_VCPU_IDS > INT_MAX);
  3557. if (id >= KVM_MAX_VCPU_IDS)
  3558. return -EINVAL;
  3559. mutex_lock(&kvm->lock);
  3560. if (kvm->created_vcpus >= kvm->max_vcpus) {
  3561. mutex_unlock(&kvm->lock);
  3562. return -EINVAL;
  3563. }
  3564. r = kvm_arch_vcpu_precreate(kvm, id);
  3565. if (r) {
  3566. mutex_unlock(&kvm->lock);
  3567. return r;
  3568. }
  3569. kvm->created_vcpus++;
  3570. mutex_unlock(&kvm->lock);
  3571. vcpu = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL_ACCOUNT);
  3572. if (!vcpu) {
  3573. r = -ENOMEM;
  3574. goto vcpu_decrement;
  3575. }
  3576. BUILD_BUG_ON(sizeof(struct kvm_run) > PAGE_SIZE);
  3577. page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
  3578. if (!page) {
  3579. r = -ENOMEM;
  3580. goto vcpu_free;
  3581. }
  3582. vcpu->run = page_address(page);
  3583. kvm_vcpu_init(vcpu, kvm, id);
  3584. r = kvm_arch_vcpu_create(vcpu);
  3585. if (r)
  3586. goto vcpu_free_run_page;
  3587. if (kvm->dirty_ring_size) {
  3588. r = kvm_dirty_ring_alloc(&vcpu->dirty_ring,
  3589. id, kvm->dirty_ring_size);
  3590. if (r)
  3591. goto arch_vcpu_destroy;
  3592. }
  3593. mutex_lock(&kvm->lock);
  3594. #ifdef CONFIG_LOCKDEP
  3595. /* Ensure that lockdep knows vcpu->mutex is taken *inside* kvm->lock */
  3596. mutex_lock(&vcpu->mutex);
  3597. mutex_unlock(&vcpu->mutex);
  3598. #endif
  3599. if (kvm_get_vcpu_by_id(kvm, id)) {
  3600. r = -EEXIST;
  3601. goto unlock_vcpu_destroy;
  3602. }
  3603. vcpu->vcpu_idx = atomic_read(&kvm->online_vcpus);
  3604. r = xa_reserve(&kvm->vcpu_array, vcpu->vcpu_idx, GFP_KERNEL_ACCOUNT);
  3605. if (r)
  3606. goto unlock_vcpu_destroy;
  3607. /* Now it's all set up, let userspace reach it */
  3608. kvm_get_kvm(kvm);
  3609. r = create_vcpu_fd(vcpu);
  3610. if (r < 0)
  3611. goto kvm_put_xa_release;
  3612. if (KVM_BUG_ON(xa_store(&kvm->vcpu_array, vcpu->vcpu_idx, vcpu, 0), kvm)) {
  3613. r = -EINVAL;
  3614. goto kvm_put_xa_release;
  3615. }
  3616. /*
  3617. * Pairs with smp_rmb() in kvm_get_vcpu. Store the vcpu
  3618. * pointer before kvm->online_vcpu's incremented value.
  3619. */
  3620. smp_wmb();
  3621. atomic_inc(&kvm->online_vcpus);
  3622. mutex_unlock(&kvm->lock);
  3623. kvm_arch_vcpu_postcreate(vcpu);
  3624. kvm_create_vcpu_debugfs(vcpu);
  3625. return r;
  3626. kvm_put_xa_release:
  3627. kvm_put_kvm_no_destroy(kvm);
  3628. xa_release(&kvm->vcpu_array, vcpu->vcpu_idx);
  3629. unlock_vcpu_destroy:
  3630. mutex_unlock(&kvm->lock);
  3631. kvm_dirty_ring_free(&vcpu->dirty_ring);
  3632. arch_vcpu_destroy:
  3633. kvm_arch_vcpu_destroy(vcpu);
  3634. vcpu_free_run_page:
  3635. free_page((unsigned long)vcpu->run);
  3636. vcpu_free:
  3637. kmem_cache_free(kvm_vcpu_cache, vcpu);
  3638. vcpu_decrement:
  3639. mutex_lock(&kvm->lock);
  3640. kvm->created_vcpus--;
  3641. mutex_unlock(&kvm->lock);
  3642. return r;
  3643. }
  3644. static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
  3645. {
  3646. if (sigset) {
  3647. sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
  3648. vcpu->sigset_active = 1;
  3649. vcpu->sigset = *sigset;
  3650. } else
  3651. vcpu->sigset_active = 0;
  3652. return 0;
  3653. }
  3654. static ssize_t kvm_vcpu_stats_read(struct file *file, char __user *user_buffer,
  3655. size_t size, loff_t *offset)
  3656. {
  3657. struct kvm_vcpu *vcpu = file->private_data;
  3658. return kvm_stats_read(vcpu->stats_id, &kvm_vcpu_stats_header,
  3659. &kvm_vcpu_stats_desc[0], &vcpu->stat,
  3660. sizeof(vcpu->stat), user_buffer, size, offset);
  3661. }
  3662. static int kvm_vcpu_stats_release(struct inode *inode, struct file *file)
  3663. {
  3664. struct kvm_vcpu *vcpu = file->private_data;
  3665. kvm_put_kvm(vcpu->kvm);
  3666. return 0;
  3667. }
  3668. static const struct file_operations kvm_vcpu_stats_fops = {
  3669. .owner = THIS_MODULE,
  3670. .read = kvm_vcpu_stats_read,
  3671. .release = kvm_vcpu_stats_release,
  3672. .llseek = noop_llseek,
  3673. };
  3674. static int kvm_vcpu_ioctl_get_stats_fd(struct kvm_vcpu *vcpu)
  3675. {
  3676. int fd;
  3677. struct file *file;
  3678. char name[15 + ITOA_MAX_LEN + 1];
  3679. snprintf(name, sizeof(name), "kvm-vcpu-stats:%d", vcpu->vcpu_id);
  3680. fd = get_unused_fd_flags(O_CLOEXEC);
  3681. if (fd < 0)
  3682. return fd;
  3683. file = anon_inode_getfile(name, &kvm_vcpu_stats_fops, vcpu, O_RDONLY);
  3684. if (IS_ERR(file)) {
  3685. put_unused_fd(fd);
  3686. return PTR_ERR(file);
  3687. }
  3688. kvm_get_kvm(vcpu->kvm);
  3689. file->f_mode |= FMODE_PREAD;
  3690. fd_install(fd, file);
  3691. return fd;
  3692. }
  3693. #ifdef CONFIG_KVM_GENERIC_PRE_FAULT_MEMORY
  3694. static int kvm_vcpu_pre_fault_memory(struct kvm_vcpu *vcpu,
  3695. struct kvm_pre_fault_memory *range)
  3696. {
  3697. int idx;
  3698. long r;
  3699. u64 full_size;
  3700. if (range->flags)
  3701. return -EINVAL;
  3702. if (!PAGE_ALIGNED(range->gpa) ||
  3703. !PAGE_ALIGNED(range->size) ||
  3704. range->gpa + range->size <= range->gpa)
  3705. return -EINVAL;
  3706. vcpu_load(vcpu);
  3707. idx = srcu_read_lock(&vcpu->kvm->srcu);
  3708. full_size = range->size;
  3709. do {
  3710. if (signal_pending(current)) {
  3711. r = -EINTR;
  3712. break;
  3713. }
  3714. r = kvm_arch_vcpu_pre_fault_memory(vcpu, range);
  3715. if (WARN_ON_ONCE(r == 0 || r == -EIO))
  3716. break;
  3717. if (r < 0)
  3718. break;
  3719. range->size -= r;
  3720. range->gpa += r;
  3721. cond_resched();
  3722. } while (range->size);
  3723. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  3724. vcpu_put(vcpu);
  3725. /* Return success if at least one page was mapped successfully. */
  3726. return full_size == range->size ? r : 0;
  3727. }
  3728. #endif
  3729. static long kvm_vcpu_ioctl(struct file *filp,
  3730. unsigned int ioctl, unsigned long arg)
  3731. {
  3732. struct kvm_vcpu *vcpu = filp->private_data;
  3733. void __user *argp = (void __user *)arg;
  3734. int r;
  3735. struct kvm_fpu *fpu = NULL;
  3736. struct kvm_sregs *kvm_sregs = NULL;
  3737. if (vcpu->kvm->mm != current->mm || vcpu->kvm->vm_dead)
  3738. return -EIO;
  3739. if (unlikely(_IOC_TYPE(ioctl) != KVMIO))
  3740. return -EINVAL;
  3741. /*
  3742. * Some architectures have vcpu ioctls that are asynchronous to vcpu
  3743. * execution; mutex_lock() would break them.
  3744. */
  3745. r = kvm_arch_vcpu_async_ioctl(filp, ioctl, arg);
  3746. if (r != -ENOIOCTLCMD)
  3747. return r;
  3748. if (mutex_lock_killable(&vcpu->mutex))
  3749. return -EINTR;
  3750. switch (ioctl) {
  3751. case KVM_RUN: {
  3752. struct pid *oldpid;
  3753. r = -EINVAL;
  3754. if (arg)
  3755. goto out;
  3756. oldpid = rcu_access_pointer(vcpu->pid);
  3757. if (unlikely(oldpid != task_pid(current))) {
  3758. /* The thread running this VCPU changed. */
  3759. struct pid *newpid;
  3760. r = kvm_arch_vcpu_run_pid_change(vcpu);
  3761. if (r)
  3762. break;
  3763. newpid = get_task_pid(current, PIDTYPE_PID);
  3764. rcu_assign_pointer(vcpu->pid, newpid);
  3765. if (oldpid)
  3766. synchronize_rcu();
  3767. put_pid(oldpid);
  3768. }
  3769. vcpu->wants_to_run = !READ_ONCE(vcpu->run->immediate_exit__unsafe);
  3770. r = kvm_arch_vcpu_ioctl_run(vcpu);
  3771. vcpu->wants_to_run = false;
  3772. trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
  3773. break;
  3774. }
  3775. case KVM_GET_REGS: {
  3776. struct kvm_regs *kvm_regs;
  3777. r = -ENOMEM;
  3778. kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL);
  3779. if (!kvm_regs)
  3780. goto out;
  3781. r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
  3782. if (r)
  3783. goto out_free1;
  3784. r = -EFAULT;
  3785. if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
  3786. goto out_free1;
  3787. r = 0;
  3788. out_free1:
  3789. kfree(kvm_regs);
  3790. break;
  3791. }
  3792. case KVM_SET_REGS: {
  3793. struct kvm_regs *kvm_regs;
  3794. kvm_regs = memdup_user(argp, sizeof(*kvm_regs));
  3795. if (IS_ERR(kvm_regs)) {
  3796. r = PTR_ERR(kvm_regs);
  3797. goto out;
  3798. }
  3799. r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
  3800. kfree(kvm_regs);
  3801. break;
  3802. }
  3803. case KVM_GET_SREGS: {
  3804. kvm_sregs = kzalloc(sizeof(struct kvm_sregs), GFP_KERNEL);
  3805. r = -ENOMEM;
  3806. if (!kvm_sregs)
  3807. goto out;
  3808. r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
  3809. if (r)
  3810. goto out;
  3811. r = -EFAULT;
  3812. if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
  3813. goto out;
  3814. r = 0;
  3815. break;
  3816. }
  3817. case KVM_SET_SREGS: {
  3818. kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs));
  3819. if (IS_ERR(kvm_sregs)) {
  3820. r = PTR_ERR(kvm_sregs);
  3821. kvm_sregs = NULL;
  3822. goto out;
  3823. }
  3824. r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
  3825. break;
  3826. }
  3827. case KVM_GET_MP_STATE: {
  3828. struct kvm_mp_state mp_state;
  3829. r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
  3830. if (r)
  3831. goto out;
  3832. r = -EFAULT;
  3833. if (copy_to_user(argp, &mp_state, sizeof(mp_state)))
  3834. goto out;
  3835. r = 0;
  3836. break;
  3837. }
  3838. case KVM_SET_MP_STATE: {
  3839. struct kvm_mp_state mp_state;
  3840. r = -EFAULT;
  3841. if (copy_from_user(&mp_state, argp, sizeof(mp_state)))
  3842. goto out;
  3843. r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
  3844. break;
  3845. }
  3846. case KVM_TRANSLATE: {
  3847. struct kvm_translation tr;
  3848. r = -EFAULT;
  3849. if (copy_from_user(&tr, argp, sizeof(tr)))
  3850. goto out;
  3851. r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
  3852. if (r)
  3853. goto out;
  3854. r = -EFAULT;
  3855. if (copy_to_user(argp, &tr, sizeof(tr)))
  3856. goto out;
  3857. r = 0;
  3858. break;
  3859. }
  3860. case KVM_SET_GUEST_DEBUG: {
  3861. struct kvm_guest_debug dbg;
  3862. r = -EFAULT;
  3863. if (copy_from_user(&dbg, argp, sizeof(dbg)))
  3864. goto out;
  3865. r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
  3866. break;
  3867. }
  3868. case KVM_SET_SIGNAL_MASK: {
  3869. struct kvm_signal_mask __user *sigmask_arg = argp;
  3870. struct kvm_signal_mask kvm_sigmask;
  3871. sigset_t sigset, *p;
  3872. p = NULL;
  3873. if (argp) {
  3874. r = -EFAULT;
  3875. if (copy_from_user(&kvm_sigmask, argp,
  3876. sizeof(kvm_sigmask)))
  3877. goto out;
  3878. r = -EINVAL;
  3879. if (kvm_sigmask.len != sizeof(sigset))
  3880. goto out;
  3881. r = -EFAULT;
  3882. if (copy_from_user(&sigset, sigmask_arg->sigset,
  3883. sizeof(sigset)))
  3884. goto out;
  3885. p = &sigset;
  3886. }
  3887. r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
  3888. break;
  3889. }
  3890. case KVM_GET_FPU: {
  3891. fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL);
  3892. r = -ENOMEM;
  3893. if (!fpu)
  3894. goto out;
  3895. r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
  3896. if (r)
  3897. goto out;
  3898. r = -EFAULT;
  3899. if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
  3900. goto out;
  3901. r = 0;
  3902. break;
  3903. }
  3904. case KVM_SET_FPU: {
  3905. fpu = memdup_user(argp, sizeof(*fpu));
  3906. if (IS_ERR(fpu)) {
  3907. r = PTR_ERR(fpu);
  3908. fpu = NULL;
  3909. goto out;
  3910. }
  3911. r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
  3912. break;
  3913. }
  3914. case KVM_GET_STATS_FD: {
  3915. r = kvm_vcpu_ioctl_get_stats_fd(vcpu);
  3916. break;
  3917. }
  3918. #ifdef CONFIG_KVM_GENERIC_PRE_FAULT_MEMORY
  3919. case KVM_PRE_FAULT_MEMORY: {
  3920. struct kvm_pre_fault_memory range;
  3921. r = -EFAULT;
  3922. if (copy_from_user(&range, argp, sizeof(range)))
  3923. break;
  3924. r = kvm_vcpu_pre_fault_memory(vcpu, &range);
  3925. /* Pass back leftover range. */
  3926. if (copy_to_user(argp, &range, sizeof(range)))
  3927. r = -EFAULT;
  3928. break;
  3929. }
  3930. #endif
  3931. default:
  3932. r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
  3933. }
  3934. out:
  3935. mutex_unlock(&vcpu->mutex);
  3936. kfree(fpu);
  3937. kfree(kvm_sregs);
  3938. return r;
  3939. }
  3940. #ifdef CONFIG_KVM_COMPAT
  3941. static long kvm_vcpu_compat_ioctl(struct file *filp,
  3942. unsigned int ioctl, unsigned long arg)
  3943. {
  3944. struct kvm_vcpu *vcpu = filp->private_data;
  3945. void __user *argp = compat_ptr(arg);
  3946. int r;
  3947. if (vcpu->kvm->mm != current->mm || vcpu->kvm->vm_dead)
  3948. return -EIO;
  3949. switch (ioctl) {
  3950. case KVM_SET_SIGNAL_MASK: {
  3951. struct kvm_signal_mask __user *sigmask_arg = argp;
  3952. struct kvm_signal_mask kvm_sigmask;
  3953. sigset_t sigset;
  3954. if (argp) {
  3955. r = -EFAULT;
  3956. if (copy_from_user(&kvm_sigmask, argp,
  3957. sizeof(kvm_sigmask)))
  3958. goto out;
  3959. r = -EINVAL;
  3960. if (kvm_sigmask.len != sizeof(compat_sigset_t))
  3961. goto out;
  3962. r = -EFAULT;
  3963. if (get_compat_sigset(&sigset,
  3964. (compat_sigset_t __user *)sigmask_arg->sigset))
  3965. goto out;
  3966. r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
  3967. } else
  3968. r = kvm_vcpu_ioctl_set_sigmask(vcpu, NULL);
  3969. break;
  3970. }
  3971. default:
  3972. r = kvm_vcpu_ioctl(filp, ioctl, arg);
  3973. }
  3974. out:
  3975. return r;
  3976. }
  3977. #endif
  3978. static int kvm_device_mmap(struct file *filp, struct vm_area_struct *vma)
  3979. {
  3980. struct kvm_device *dev = filp->private_data;
  3981. if (dev->ops->mmap)
  3982. return dev->ops->mmap(dev, vma);
  3983. return -ENODEV;
  3984. }
  3985. static int kvm_device_ioctl_attr(struct kvm_device *dev,
  3986. int (*accessor)(struct kvm_device *dev,
  3987. struct kvm_device_attr *attr),
  3988. unsigned long arg)
  3989. {
  3990. struct kvm_device_attr attr;
  3991. if (!accessor)
  3992. return -EPERM;
  3993. if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
  3994. return -EFAULT;
  3995. return accessor(dev, &attr);
  3996. }
  3997. static long kvm_device_ioctl(struct file *filp, unsigned int ioctl,
  3998. unsigned long arg)
  3999. {
  4000. struct kvm_device *dev = filp->private_data;
  4001. if (dev->kvm->mm != current->mm || dev->kvm->vm_dead)
  4002. return -EIO;
  4003. switch (ioctl) {
  4004. case KVM_SET_DEVICE_ATTR:
  4005. return kvm_device_ioctl_attr(dev, dev->ops->set_attr, arg);
  4006. case KVM_GET_DEVICE_ATTR:
  4007. return kvm_device_ioctl_attr(dev, dev->ops->get_attr, arg);
  4008. case KVM_HAS_DEVICE_ATTR:
  4009. return kvm_device_ioctl_attr(dev, dev->ops->has_attr, arg);
  4010. default:
  4011. if (dev->ops->ioctl)
  4012. return dev->ops->ioctl(dev, ioctl, arg);
  4013. return -ENOTTY;
  4014. }
  4015. }
  4016. static int kvm_device_release(struct inode *inode, struct file *filp)
  4017. {
  4018. struct kvm_device *dev = filp->private_data;
  4019. struct kvm *kvm = dev->kvm;
  4020. if (dev->ops->release) {
  4021. mutex_lock(&kvm->lock);
  4022. list_del_rcu(&dev->vm_node);
  4023. synchronize_rcu();
  4024. dev->ops->release(dev);
  4025. mutex_unlock(&kvm->lock);
  4026. }
  4027. kvm_put_kvm(kvm);
  4028. return 0;
  4029. }
  4030. static struct file_operations kvm_device_fops = {
  4031. .unlocked_ioctl = kvm_device_ioctl,
  4032. .release = kvm_device_release,
  4033. KVM_COMPAT(kvm_device_ioctl),
  4034. .mmap = kvm_device_mmap,
  4035. };
  4036. struct kvm_device *kvm_device_from_filp(struct file *filp)
  4037. {
  4038. if (filp->f_op != &kvm_device_fops)
  4039. return NULL;
  4040. return filp->private_data;
  4041. }
  4042. static const struct kvm_device_ops *kvm_device_ops_table[KVM_DEV_TYPE_MAX] = {
  4043. #ifdef CONFIG_KVM_MPIC
  4044. [KVM_DEV_TYPE_FSL_MPIC_20] = &kvm_mpic_ops,
  4045. [KVM_DEV_TYPE_FSL_MPIC_42] = &kvm_mpic_ops,
  4046. #endif
  4047. };
  4048. int kvm_register_device_ops(const struct kvm_device_ops *ops, u32 type)
  4049. {
  4050. if (type >= ARRAY_SIZE(kvm_device_ops_table))
  4051. return -ENOSPC;
  4052. if (kvm_device_ops_table[type] != NULL)
  4053. return -EEXIST;
  4054. kvm_device_ops_table[type] = ops;
  4055. return 0;
  4056. }
  4057. void kvm_unregister_device_ops(u32 type)
  4058. {
  4059. if (kvm_device_ops_table[type] != NULL)
  4060. kvm_device_ops_table[type] = NULL;
  4061. }
  4062. static int kvm_ioctl_create_device(struct kvm *kvm,
  4063. struct kvm_create_device *cd)
  4064. {
  4065. const struct kvm_device_ops *ops;
  4066. struct kvm_device *dev;
  4067. bool test = cd->flags & KVM_CREATE_DEVICE_TEST;
  4068. int type;
  4069. int ret;
  4070. if (cd->type >= ARRAY_SIZE(kvm_device_ops_table))
  4071. return -ENODEV;
  4072. type = array_index_nospec(cd->type, ARRAY_SIZE(kvm_device_ops_table));
  4073. ops = kvm_device_ops_table[type];
  4074. if (ops == NULL)
  4075. return -ENODEV;
  4076. if (test)
  4077. return 0;
  4078. dev = kzalloc(sizeof(*dev), GFP_KERNEL_ACCOUNT);
  4079. if (!dev)
  4080. return -ENOMEM;
  4081. dev->ops = ops;
  4082. dev->kvm = kvm;
  4083. mutex_lock(&kvm->lock);
  4084. ret = ops->create(dev, type);
  4085. if (ret < 0) {
  4086. mutex_unlock(&kvm->lock);
  4087. kfree(dev);
  4088. return ret;
  4089. }
  4090. list_add_rcu(&dev->vm_node, &kvm->devices);
  4091. mutex_unlock(&kvm->lock);
  4092. if (ops->init)
  4093. ops->init(dev);
  4094. kvm_get_kvm(kvm);
  4095. ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);
  4096. if (ret < 0) {
  4097. kvm_put_kvm_no_destroy(kvm);
  4098. mutex_lock(&kvm->lock);
  4099. list_del_rcu(&dev->vm_node);
  4100. synchronize_rcu();
  4101. if (ops->release)
  4102. ops->release(dev);
  4103. mutex_unlock(&kvm->lock);
  4104. if (ops->destroy)
  4105. ops->destroy(dev);
  4106. return ret;
  4107. }
  4108. cd->fd = ret;
  4109. return 0;
  4110. }
  4111. static int kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)
  4112. {
  4113. switch (arg) {
  4114. case KVM_CAP_USER_MEMORY:
  4115. case KVM_CAP_USER_MEMORY2:
  4116. case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
  4117. case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
  4118. case KVM_CAP_INTERNAL_ERROR_DATA:
  4119. #ifdef CONFIG_HAVE_KVM_MSI
  4120. case KVM_CAP_SIGNAL_MSI:
  4121. #endif
  4122. #ifdef CONFIG_HAVE_KVM_IRQCHIP
  4123. case KVM_CAP_IRQFD:
  4124. #endif
  4125. case KVM_CAP_IOEVENTFD_ANY_LENGTH:
  4126. case KVM_CAP_CHECK_EXTENSION_VM:
  4127. case KVM_CAP_ENABLE_CAP_VM:
  4128. case KVM_CAP_HALT_POLL:
  4129. return 1;
  4130. #ifdef CONFIG_KVM_MMIO
  4131. case KVM_CAP_COALESCED_MMIO:
  4132. return KVM_COALESCED_MMIO_PAGE_OFFSET;
  4133. case KVM_CAP_COALESCED_PIO:
  4134. return 1;
  4135. #endif
  4136. #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
  4137. case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2:
  4138. return KVM_DIRTY_LOG_MANUAL_CAPS;
  4139. #endif
  4140. #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
  4141. case KVM_CAP_IRQ_ROUTING:
  4142. return KVM_MAX_IRQ_ROUTES;
  4143. #endif
  4144. #if KVM_MAX_NR_ADDRESS_SPACES > 1
  4145. case KVM_CAP_MULTI_ADDRESS_SPACE:
  4146. if (kvm)
  4147. return kvm_arch_nr_memslot_as_ids(kvm);
  4148. return KVM_MAX_NR_ADDRESS_SPACES;
  4149. #endif
  4150. case KVM_CAP_NR_MEMSLOTS:
  4151. return KVM_USER_MEM_SLOTS;
  4152. case KVM_CAP_DIRTY_LOG_RING:
  4153. #ifdef CONFIG_HAVE_KVM_DIRTY_RING_TSO
  4154. return KVM_DIRTY_RING_MAX_ENTRIES * sizeof(struct kvm_dirty_gfn);
  4155. #else
  4156. return 0;
  4157. #endif
  4158. case KVM_CAP_DIRTY_LOG_RING_ACQ_REL:
  4159. #ifdef CONFIG_HAVE_KVM_DIRTY_RING_ACQ_REL
  4160. return KVM_DIRTY_RING_MAX_ENTRIES * sizeof(struct kvm_dirty_gfn);
  4161. #else
  4162. return 0;
  4163. #endif
  4164. #ifdef CONFIG_NEED_KVM_DIRTY_RING_WITH_BITMAP
  4165. case KVM_CAP_DIRTY_LOG_RING_WITH_BITMAP:
  4166. #endif
  4167. case KVM_CAP_BINARY_STATS_FD:
  4168. case KVM_CAP_SYSTEM_EVENT_DATA:
  4169. case KVM_CAP_DEVICE_CTRL:
  4170. return 1;
  4171. #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES
  4172. case KVM_CAP_MEMORY_ATTRIBUTES:
  4173. return kvm_supported_mem_attributes(kvm);
  4174. #endif
  4175. #ifdef CONFIG_KVM_PRIVATE_MEM
  4176. case KVM_CAP_GUEST_MEMFD:
  4177. return !kvm || kvm_arch_has_private_mem(kvm);
  4178. #endif
  4179. default:
  4180. break;
  4181. }
  4182. return kvm_vm_ioctl_check_extension(kvm, arg);
  4183. }
  4184. static int kvm_vm_ioctl_enable_dirty_log_ring(struct kvm *kvm, u32 size)
  4185. {
  4186. int r;
  4187. if (!KVM_DIRTY_LOG_PAGE_OFFSET)
  4188. return -EINVAL;
  4189. /* the size should be power of 2 */
  4190. if (!size || (size & (size - 1)))
  4191. return -EINVAL;
  4192. /* Should be bigger to keep the reserved entries, or a page */
  4193. if (size < kvm_dirty_ring_get_rsvd_entries() *
  4194. sizeof(struct kvm_dirty_gfn) || size < PAGE_SIZE)
  4195. return -EINVAL;
  4196. if (size > KVM_DIRTY_RING_MAX_ENTRIES *
  4197. sizeof(struct kvm_dirty_gfn))
  4198. return -E2BIG;
  4199. /* We only allow it to set once */
  4200. if (kvm->dirty_ring_size)
  4201. return -EINVAL;
  4202. mutex_lock(&kvm->lock);
  4203. if (kvm->created_vcpus) {
  4204. /* We don't allow to change this value after vcpu created */
  4205. r = -EINVAL;
  4206. } else {
  4207. kvm->dirty_ring_size = size;
  4208. r = 0;
  4209. }
  4210. mutex_unlock(&kvm->lock);
  4211. return r;
  4212. }
  4213. static int kvm_vm_ioctl_reset_dirty_pages(struct kvm *kvm)
  4214. {
  4215. unsigned long i;
  4216. struct kvm_vcpu *vcpu;
  4217. int cleared = 0;
  4218. if (!kvm->dirty_ring_size)
  4219. return -EINVAL;
  4220. mutex_lock(&kvm->slots_lock);
  4221. kvm_for_each_vcpu(i, vcpu, kvm)
  4222. cleared += kvm_dirty_ring_reset(vcpu->kvm, &vcpu->dirty_ring);
  4223. mutex_unlock(&kvm->slots_lock);
  4224. if (cleared)
  4225. kvm_flush_remote_tlbs(kvm);
  4226. return cleared;
  4227. }
  4228. int __attribute__((weak)) kvm_vm_ioctl_enable_cap(struct kvm *kvm,
  4229. struct kvm_enable_cap *cap)
  4230. {
  4231. return -EINVAL;
  4232. }
  4233. bool kvm_are_all_memslots_empty(struct kvm *kvm)
  4234. {
  4235. int i;
  4236. lockdep_assert_held(&kvm->slots_lock);
  4237. for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) {
  4238. if (!kvm_memslots_empty(__kvm_memslots(kvm, i)))
  4239. return false;
  4240. }
  4241. return true;
  4242. }
  4243. EXPORT_SYMBOL_GPL(kvm_are_all_memslots_empty);
  4244. static int kvm_vm_ioctl_enable_cap_generic(struct kvm *kvm,
  4245. struct kvm_enable_cap *cap)
  4246. {
  4247. switch (cap->cap) {
  4248. #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
  4249. case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2: {
  4250. u64 allowed_options = KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE;
  4251. if (cap->args[0] & KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE)
  4252. allowed_options = KVM_DIRTY_LOG_MANUAL_CAPS;
  4253. if (cap->flags || (cap->args[0] & ~allowed_options))
  4254. return -EINVAL;
  4255. kvm->manual_dirty_log_protect = cap->args[0];
  4256. return 0;
  4257. }
  4258. #endif
  4259. case KVM_CAP_HALT_POLL: {
  4260. if (cap->flags || cap->args[0] != (unsigned int)cap->args[0])
  4261. return -EINVAL;
  4262. kvm->max_halt_poll_ns = cap->args[0];
  4263. /*
  4264. * Ensure kvm->override_halt_poll_ns does not become visible
  4265. * before kvm->max_halt_poll_ns.
  4266. *
  4267. * Pairs with the smp_rmb() in kvm_vcpu_max_halt_poll_ns().
  4268. */
  4269. smp_wmb();
  4270. kvm->override_halt_poll_ns = true;
  4271. return 0;
  4272. }
  4273. case KVM_CAP_DIRTY_LOG_RING:
  4274. case KVM_CAP_DIRTY_LOG_RING_ACQ_REL:
  4275. if (!kvm_vm_ioctl_check_extension_generic(kvm, cap->cap))
  4276. return -EINVAL;
  4277. return kvm_vm_ioctl_enable_dirty_log_ring(kvm, cap->args[0]);
  4278. case KVM_CAP_DIRTY_LOG_RING_WITH_BITMAP: {
  4279. int r = -EINVAL;
  4280. if (!IS_ENABLED(CONFIG_NEED_KVM_DIRTY_RING_WITH_BITMAP) ||
  4281. !kvm->dirty_ring_size || cap->flags)
  4282. return r;
  4283. mutex_lock(&kvm->slots_lock);
  4284. /*
  4285. * For simplicity, allow enabling ring+bitmap if and only if
  4286. * there are no memslots, e.g. to ensure all memslots allocate
  4287. * a bitmap after the capability is enabled.
  4288. */
  4289. if (kvm_are_all_memslots_empty(kvm)) {
  4290. kvm->dirty_ring_with_bitmap = true;
  4291. r = 0;
  4292. }
  4293. mutex_unlock(&kvm->slots_lock);
  4294. return r;
  4295. }
  4296. default:
  4297. return kvm_vm_ioctl_enable_cap(kvm, cap);
  4298. }
  4299. }
  4300. static ssize_t kvm_vm_stats_read(struct file *file, char __user *user_buffer,
  4301. size_t size, loff_t *offset)
  4302. {
  4303. struct kvm *kvm = file->private_data;
  4304. return kvm_stats_read(kvm->stats_id, &kvm_vm_stats_header,
  4305. &kvm_vm_stats_desc[0], &kvm->stat,
  4306. sizeof(kvm->stat), user_buffer, size, offset);
  4307. }
  4308. static int kvm_vm_stats_release(struct inode *inode, struct file *file)
  4309. {
  4310. struct kvm *kvm = file->private_data;
  4311. kvm_put_kvm(kvm);
  4312. return 0;
  4313. }
  4314. static const struct file_operations kvm_vm_stats_fops = {
  4315. .owner = THIS_MODULE,
  4316. .read = kvm_vm_stats_read,
  4317. .release = kvm_vm_stats_release,
  4318. .llseek = noop_llseek,
  4319. };
  4320. static int kvm_vm_ioctl_get_stats_fd(struct kvm *kvm)
  4321. {
  4322. int fd;
  4323. struct file *file;
  4324. fd = get_unused_fd_flags(O_CLOEXEC);
  4325. if (fd < 0)
  4326. return fd;
  4327. file = anon_inode_getfile("kvm-vm-stats",
  4328. &kvm_vm_stats_fops, kvm, O_RDONLY);
  4329. if (IS_ERR(file)) {
  4330. put_unused_fd(fd);
  4331. return PTR_ERR(file);
  4332. }
  4333. kvm_get_kvm(kvm);
  4334. file->f_mode |= FMODE_PREAD;
  4335. fd_install(fd, file);
  4336. return fd;
  4337. }
  4338. #define SANITY_CHECK_MEM_REGION_FIELD(field) \
  4339. do { \
  4340. BUILD_BUG_ON(offsetof(struct kvm_userspace_memory_region, field) != \
  4341. offsetof(struct kvm_userspace_memory_region2, field)); \
  4342. BUILD_BUG_ON(sizeof_field(struct kvm_userspace_memory_region, field) != \
  4343. sizeof_field(struct kvm_userspace_memory_region2, field)); \
  4344. } while (0)
  4345. static long kvm_vm_ioctl(struct file *filp,
  4346. unsigned int ioctl, unsigned long arg)
  4347. {
  4348. struct kvm *kvm = filp->private_data;
  4349. void __user *argp = (void __user *)arg;
  4350. int r;
  4351. if (kvm->mm != current->mm || kvm->vm_dead)
  4352. return -EIO;
  4353. switch (ioctl) {
  4354. case KVM_CREATE_VCPU:
  4355. r = kvm_vm_ioctl_create_vcpu(kvm, arg);
  4356. break;
  4357. case KVM_ENABLE_CAP: {
  4358. struct kvm_enable_cap cap;
  4359. r = -EFAULT;
  4360. if (copy_from_user(&cap, argp, sizeof(cap)))
  4361. goto out;
  4362. r = kvm_vm_ioctl_enable_cap_generic(kvm, &cap);
  4363. break;
  4364. }
  4365. case KVM_SET_USER_MEMORY_REGION2:
  4366. case KVM_SET_USER_MEMORY_REGION: {
  4367. struct kvm_userspace_memory_region2 mem;
  4368. unsigned long size;
  4369. if (ioctl == KVM_SET_USER_MEMORY_REGION) {
  4370. /*
  4371. * Fields beyond struct kvm_userspace_memory_region shouldn't be
  4372. * accessed, but avoid leaking kernel memory in case of a bug.
  4373. */
  4374. memset(&mem, 0, sizeof(mem));
  4375. size = sizeof(struct kvm_userspace_memory_region);
  4376. } else {
  4377. size = sizeof(struct kvm_userspace_memory_region2);
  4378. }
  4379. /* Ensure the common parts of the two structs are identical. */
  4380. SANITY_CHECK_MEM_REGION_FIELD(slot);
  4381. SANITY_CHECK_MEM_REGION_FIELD(flags);
  4382. SANITY_CHECK_MEM_REGION_FIELD(guest_phys_addr);
  4383. SANITY_CHECK_MEM_REGION_FIELD(memory_size);
  4384. SANITY_CHECK_MEM_REGION_FIELD(userspace_addr);
  4385. r = -EFAULT;
  4386. if (copy_from_user(&mem, argp, size))
  4387. goto out;
  4388. r = -EINVAL;
  4389. if (ioctl == KVM_SET_USER_MEMORY_REGION &&
  4390. (mem.flags & ~KVM_SET_USER_MEMORY_REGION_V1_FLAGS))
  4391. goto out;
  4392. r = kvm_vm_ioctl_set_memory_region(kvm, &mem);
  4393. break;
  4394. }
  4395. case KVM_GET_DIRTY_LOG: {
  4396. struct kvm_dirty_log log;
  4397. r = -EFAULT;
  4398. if (copy_from_user(&log, argp, sizeof(log)))
  4399. goto out;
  4400. r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
  4401. break;
  4402. }
  4403. #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
  4404. case KVM_CLEAR_DIRTY_LOG: {
  4405. struct kvm_clear_dirty_log log;
  4406. r = -EFAULT;
  4407. if (copy_from_user(&log, argp, sizeof(log)))
  4408. goto out;
  4409. r = kvm_vm_ioctl_clear_dirty_log(kvm, &log);
  4410. break;
  4411. }
  4412. #endif
  4413. #ifdef CONFIG_KVM_MMIO
  4414. case KVM_REGISTER_COALESCED_MMIO: {
  4415. struct kvm_coalesced_mmio_zone zone;
  4416. r = -EFAULT;
  4417. if (copy_from_user(&zone, argp, sizeof(zone)))
  4418. goto out;
  4419. r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
  4420. break;
  4421. }
  4422. case KVM_UNREGISTER_COALESCED_MMIO: {
  4423. struct kvm_coalesced_mmio_zone zone;
  4424. r = -EFAULT;
  4425. if (copy_from_user(&zone, argp, sizeof(zone)))
  4426. goto out;
  4427. r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
  4428. break;
  4429. }
  4430. #endif
  4431. case KVM_IRQFD: {
  4432. struct kvm_irqfd data;
  4433. r = -EFAULT;
  4434. if (copy_from_user(&data, argp, sizeof(data)))
  4435. goto out;
  4436. r = kvm_irqfd(kvm, &data);
  4437. break;
  4438. }
  4439. case KVM_IOEVENTFD: {
  4440. struct kvm_ioeventfd data;
  4441. r = -EFAULT;
  4442. if (copy_from_user(&data, argp, sizeof(data)))
  4443. goto out;
  4444. r = kvm_ioeventfd(kvm, &data);
  4445. break;
  4446. }
  4447. #ifdef CONFIG_HAVE_KVM_MSI
  4448. case KVM_SIGNAL_MSI: {
  4449. struct kvm_msi msi;
  4450. r = -EFAULT;
  4451. if (copy_from_user(&msi, argp, sizeof(msi)))
  4452. goto out;
  4453. r = kvm_send_userspace_msi(kvm, &msi);
  4454. break;
  4455. }
  4456. #endif
  4457. #ifdef __KVM_HAVE_IRQ_LINE
  4458. case KVM_IRQ_LINE_STATUS:
  4459. case KVM_IRQ_LINE: {
  4460. struct kvm_irq_level irq_event;
  4461. r = -EFAULT;
  4462. if (copy_from_user(&irq_event, argp, sizeof(irq_event)))
  4463. goto out;
  4464. r = kvm_vm_ioctl_irq_line(kvm, &irq_event,
  4465. ioctl == KVM_IRQ_LINE_STATUS);
  4466. if (r)
  4467. goto out;
  4468. r = -EFAULT;
  4469. if (ioctl == KVM_IRQ_LINE_STATUS) {
  4470. if (copy_to_user(argp, &irq_event, sizeof(irq_event)))
  4471. goto out;
  4472. }
  4473. r = 0;
  4474. break;
  4475. }
  4476. #endif
  4477. #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
  4478. case KVM_SET_GSI_ROUTING: {
  4479. struct kvm_irq_routing routing;
  4480. struct kvm_irq_routing __user *urouting;
  4481. struct kvm_irq_routing_entry *entries = NULL;
  4482. r = -EFAULT;
  4483. if (copy_from_user(&routing, argp, sizeof(routing)))
  4484. goto out;
  4485. r = -EINVAL;
  4486. if (!kvm_arch_can_set_irq_routing(kvm))
  4487. goto out;
  4488. if (routing.nr > KVM_MAX_IRQ_ROUTES)
  4489. goto out;
  4490. if (routing.flags)
  4491. goto out;
  4492. if (routing.nr) {
  4493. urouting = argp;
  4494. entries = vmemdup_array_user(urouting->entries,
  4495. routing.nr, sizeof(*entries));
  4496. if (IS_ERR(entries)) {
  4497. r = PTR_ERR(entries);
  4498. goto out;
  4499. }
  4500. }
  4501. r = kvm_set_irq_routing(kvm, entries, routing.nr,
  4502. routing.flags);
  4503. kvfree(entries);
  4504. break;
  4505. }
  4506. #endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */
  4507. #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES
  4508. case KVM_SET_MEMORY_ATTRIBUTES: {
  4509. struct kvm_memory_attributes attrs;
  4510. r = -EFAULT;
  4511. if (copy_from_user(&attrs, argp, sizeof(attrs)))
  4512. goto out;
  4513. r = kvm_vm_ioctl_set_mem_attributes(kvm, &attrs);
  4514. break;
  4515. }
  4516. #endif /* CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES */
  4517. case KVM_CREATE_DEVICE: {
  4518. struct kvm_create_device cd;
  4519. r = -EFAULT;
  4520. if (copy_from_user(&cd, argp, sizeof(cd)))
  4521. goto out;
  4522. r = kvm_ioctl_create_device(kvm, &cd);
  4523. if (r)
  4524. goto out;
  4525. r = -EFAULT;
  4526. if (copy_to_user(argp, &cd, sizeof(cd)))
  4527. goto out;
  4528. r = 0;
  4529. break;
  4530. }
  4531. case KVM_CHECK_EXTENSION:
  4532. r = kvm_vm_ioctl_check_extension_generic(kvm, arg);
  4533. break;
  4534. case KVM_RESET_DIRTY_RINGS:
  4535. r = kvm_vm_ioctl_reset_dirty_pages(kvm);
  4536. break;
  4537. case KVM_GET_STATS_FD:
  4538. r = kvm_vm_ioctl_get_stats_fd(kvm);
  4539. break;
  4540. #ifdef CONFIG_KVM_PRIVATE_MEM
  4541. case KVM_CREATE_GUEST_MEMFD: {
  4542. struct kvm_create_guest_memfd guest_memfd;
  4543. r = -EFAULT;
  4544. if (copy_from_user(&guest_memfd, argp, sizeof(guest_memfd)))
  4545. goto out;
  4546. r = kvm_gmem_create(kvm, &guest_memfd);
  4547. break;
  4548. }
  4549. #endif
  4550. default:
  4551. r = kvm_arch_vm_ioctl(filp, ioctl, arg);
  4552. }
  4553. out:
  4554. return r;
  4555. }
  4556. #ifdef CONFIG_KVM_COMPAT
  4557. struct compat_kvm_dirty_log {
  4558. __u32 slot;
  4559. __u32 padding1;
  4560. union {
  4561. compat_uptr_t dirty_bitmap; /* one bit per page */
  4562. __u64 padding2;
  4563. };
  4564. };
  4565. struct compat_kvm_clear_dirty_log {
  4566. __u32 slot;
  4567. __u32 num_pages;
  4568. __u64 first_page;
  4569. union {
  4570. compat_uptr_t dirty_bitmap; /* one bit per page */
  4571. __u64 padding2;
  4572. };
  4573. };
  4574. long __weak kvm_arch_vm_compat_ioctl(struct file *filp, unsigned int ioctl,
  4575. unsigned long arg)
  4576. {
  4577. return -ENOTTY;
  4578. }
  4579. static long kvm_vm_compat_ioctl(struct file *filp,
  4580. unsigned int ioctl, unsigned long arg)
  4581. {
  4582. struct kvm *kvm = filp->private_data;
  4583. int r;
  4584. if (kvm->mm != current->mm || kvm->vm_dead)
  4585. return -EIO;
  4586. r = kvm_arch_vm_compat_ioctl(filp, ioctl, arg);
  4587. if (r != -ENOTTY)
  4588. return r;
  4589. switch (ioctl) {
  4590. #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
  4591. case KVM_CLEAR_DIRTY_LOG: {
  4592. struct compat_kvm_clear_dirty_log compat_log;
  4593. struct kvm_clear_dirty_log log;
  4594. if (copy_from_user(&compat_log, (void __user *)arg,
  4595. sizeof(compat_log)))
  4596. return -EFAULT;
  4597. log.slot = compat_log.slot;
  4598. log.num_pages = compat_log.num_pages;
  4599. log.first_page = compat_log.first_page;
  4600. log.padding2 = compat_log.padding2;
  4601. log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
  4602. r = kvm_vm_ioctl_clear_dirty_log(kvm, &log);
  4603. break;
  4604. }
  4605. #endif
  4606. case KVM_GET_DIRTY_LOG: {
  4607. struct compat_kvm_dirty_log compat_log;
  4608. struct kvm_dirty_log log;
  4609. if (copy_from_user(&compat_log, (void __user *)arg,
  4610. sizeof(compat_log)))
  4611. return -EFAULT;
  4612. log.slot = compat_log.slot;
  4613. log.padding1 = compat_log.padding1;
  4614. log.padding2 = compat_log.padding2;
  4615. log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
  4616. r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
  4617. break;
  4618. }
  4619. default:
  4620. r = kvm_vm_ioctl(filp, ioctl, arg);
  4621. }
  4622. return r;
  4623. }
  4624. #endif
  4625. static struct file_operations kvm_vm_fops = {
  4626. .release = kvm_vm_release,
  4627. .unlocked_ioctl = kvm_vm_ioctl,
  4628. .llseek = noop_llseek,
  4629. KVM_COMPAT(kvm_vm_compat_ioctl),
  4630. };
  4631. bool file_is_kvm(struct file *file)
  4632. {
  4633. return file && file->f_op == &kvm_vm_fops;
  4634. }
  4635. EXPORT_SYMBOL_GPL(file_is_kvm);
  4636. static int kvm_dev_ioctl_create_vm(unsigned long type)
  4637. {
  4638. char fdname[ITOA_MAX_LEN + 1];
  4639. int r, fd;
  4640. struct kvm *kvm;
  4641. struct file *file;
  4642. fd = get_unused_fd_flags(O_CLOEXEC);
  4643. if (fd < 0)
  4644. return fd;
  4645. snprintf(fdname, sizeof(fdname), "%d", fd);
  4646. kvm = kvm_create_vm(type, fdname);
  4647. if (IS_ERR(kvm)) {
  4648. r = PTR_ERR(kvm);
  4649. goto put_fd;
  4650. }
  4651. file = anon_inode_getfile("kvm-vm", &kvm_vm_fops, kvm, O_RDWR);
  4652. if (IS_ERR(file)) {
  4653. r = PTR_ERR(file);
  4654. goto put_kvm;
  4655. }
  4656. /*
  4657. * Don't call kvm_put_kvm anymore at this point; file->f_op is
  4658. * already set, with ->release() being kvm_vm_release(). In error
  4659. * cases it will be called by the final fput(file) and will take
  4660. * care of doing kvm_put_kvm(kvm).
  4661. */
  4662. kvm_uevent_notify_change(KVM_EVENT_CREATE_VM, kvm);
  4663. fd_install(fd, file);
  4664. return fd;
  4665. put_kvm:
  4666. kvm_put_kvm(kvm);
  4667. put_fd:
  4668. put_unused_fd(fd);
  4669. return r;
  4670. }
  4671. static long kvm_dev_ioctl(struct file *filp,
  4672. unsigned int ioctl, unsigned long arg)
  4673. {
  4674. int r = -EINVAL;
  4675. switch (ioctl) {
  4676. case KVM_GET_API_VERSION:
  4677. if (arg)
  4678. goto out;
  4679. r = KVM_API_VERSION;
  4680. break;
  4681. case KVM_CREATE_VM:
  4682. r = kvm_dev_ioctl_create_vm(arg);
  4683. break;
  4684. case KVM_CHECK_EXTENSION:
  4685. r = kvm_vm_ioctl_check_extension_generic(NULL, arg);
  4686. break;
  4687. case KVM_GET_VCPU_MMAP_SIZE:
  4688. if (arg)
  4689. goto out;
  4690. r = PAGE_SIZE; /* struct kvm_run */
  4691. #ifdef CONFIG_X86
  4692. r += PAGE_SIZE; /* pio data page */
  4693. #endif
  4694. #ifdef CONFIG_KVM_MMIO
  4695. r += PAGE_SIZE; /* coalesced mmio ring page */
  4696. #endif
  4697. break;
  4698. default:
  4699. return kvm_arch_dev_ioctl(filp, ioctl, arg);
  4700. }
  4701. out:
  4702. return r;
  4703. }
  4704. static struct file_operations kvm_chardev_ops = {
  4705. .unlocked_ioctl = kvm_dev_ioctl,
  4706. .llseek = noop_llseek,
  4707. KVM_COMPAT(kvm_dev_ioctl),
  4708. };
  4709. static struct miscdevice kvm_dev = {
  4710. KVM_MINOR,
  4711. "kvm",
  4712. &kvm_chardev_ops,
  4713. };
  4714. #ifdef CONFIG_KVM_GENERIC_HARDWARE_ENABLING
  4715. static bool enable_virt_at_load = true;
  4716. module_param(enable_virt_at_load, bool, 0444);
  4717. __visible bool kvm_rebooting;
  4718. EXPORT_SYMBOL_GPL(kvm_rebooting);
  4719. static DEFINE_PER_CPU(bool, virtualization_enabled);
  4720. static DEFINE_MUTEX(kvm_usage_lock);
  4721. static int kvm_usage_count;
  4722. __weak void kvm_arch_enable_virtualization(void)
  4723. {
  4724. }
  4725. __weak void kvm_arch_disable_virtualization(void)
  4726. {
  4727. }
  4728. static int kvm_enable_virtualization_cpu(void)
  4729. {
  4730. if (__this_cpu_read(virtualization_enabled))
  4731. return 0;
  4732. if (kvm_arch_enable_virtualization_cpu()) {
  4733. pr_info("kvm: enabling virtualization on CPU%d failed\n",
  4734. raw_smp_processor_id());
  4735. return -EIO;
  4736. }
  4737. __this_cpu_write(virtualization_enabled, true);
  4738. return 0;
  4739. }
  4740. static int kvm_online_cpu(unsigned int cpu)
  4741. {
  4742. /*
  4743. * Abort the CPU online process if hardware virtualization cannot
  4744. * be enabled. Otherwise running VMs would encounter unrecoverable
  4745. * errors when scheduled to this CPU.
  4746. */
  4747. return kvm_enable_virtualization_cpu();
  4748. }
  4749. static void kvm_disable_virtualization_cpu(void *ign)
  4750. {
  4751. if (!__this_cpu_read(virtualization_enabled))
  4752. return;
  4753. kvm_arch_disable_virtualization_cpu();
  4754. __this_cpu_write(virtualization_enabled, false);
  4755. }
  4756. static int kvm_offline_cpu(unsigned int cpu)
  4757. {
  4758. kvm_disable_virtualization_cpu(NULL);
  4759. return 0;
  4760. }
  4761. static void kvm_shutdown(void)
  4762. {
  4763. /*
  4764. * Disable hardware virtualization and set kvm_rebooting to indicate
  4765. * that KVM has asynchronously disabled hardware virtualization, i.e.
  4766. * that relevant errors and exceptions aren't entirely unexpected.
  4767. * Some flavors of hardware virtualization need to be disabled before
  4768. * transferring control to firmware (to perform shutdown/reboot), e.g.
  4769. * on x86, virtualization can block INIT interrupts, which are used by
  4770. * firmware to pull APs back under firmware control. Note, this path
  4771. * is used for both shutdown and reboot scenarios, i.e. neither name is
  4772. * 100% comprehensive.
  4773. */
  4774. pr_info("kvm: exiting hardware virtualization\n");
  4775. kvm_rebooting = true;
  4776. on_each_cpu(kvm_disable_virtualization_cpu, NULL, 1);
  4777. }
  4778. static int kvm_suspend(void)
  4779. {
  4780. /*
  4781. * Secondary CPUs and CPU hotplug are disabled across the suspend/resume
  4782. * callbacks, i.e. no need to acquire kvm_usage_lock to ensure the usage
  4783. * count is stable. Assert that kvm_usage_lock is not held to ensure
  4784. * the system isn't suspended while KVM is enabling hardware. Hardware
  4785. * enabling can be preempted, but the task cannot be frozen until it has
  4786. * dropped all locks (userspace tasks are frozen via a fake signal).
  4787. */
  4788. lockdep_assert_not_held(&kvm_usage_lock);
  4789. lockdep_assert_irqs_disabled();
  4790. kvm_disable_virtualization_cpu(NULL);
  4791. return 0;
  4792. }
  4793. static void kvm_resume(void)
  4794. {
  4795. lockdep_assert_not_held(&kvm_usage_lock);
  4796. lockdep_assert_irqs_disabled();
  4797. WARN_ON_ONCE(kvm_enable_virtualization_cpu());
  4798. }
  4799. static struct syscore_ops kvm_syscore_ops = {
  4800. .suspend = kvm_suspend,
  4801. .resume = kvm_resume,
  4802. .shutdown = kvm_shutdown,
  4803. };
  4804. static int kvm_enable_virtualization(void)
  4805. {
  4806. int r;
  4807. guard(mutex)(&kvm_usage_lock);
  4808. if (kvm_usage_count++)
  4809. return 0;
  4810. kvm_arch_enable_virtualization();
  4811. r = cpuhp_setup_state(CPUHP_AP_KVM_ONLINE, "kvm/cpu:online",
  4812. kvm_online_cpu, kvm_offline_cpu);
  4813. if (r)
  4814. goto err_cpuhp;
  4815. register_syscore_ops(&kvm_syscore_ops);
  4816. /*
  4817. * Undo virtualization enabling and bail if the system is going down.
  4818. * If userspace initiated a forced reboot, e.g. reboot -f, then it's
  4819. * possible for an in-flight operation to enable virtualization after
  4820. * syscore_shutdown() is called, i.e. without kvm_shutdown() being
  4821. * invoked. Note, this relies on system_state being set _before_
  4822. * kvm_shutdown(), e.g. to ensure either kvm_shutdown() is invoked
  4823. * or this CPU observes the impending shutdown. Which is why KVM uses
  4824. * a syscore ops hook instead of registering a dedicated reboot
  4825. * notifier (the latter runs before system_state is updated).
  4826. */
  4827. if (system_state == SYSTEM_HALT || system_state == SYSTEM_POWER_OFF ||
  4828. system_state == SYSTEM_RESTART) {
  4829. r = -EBUSY;
  4830. goto err_rebooting;
  4831. }
  4832. return 0;
  4833. err_rebooting:
  4834. unregister_syscore_ops(&kvm_syscore_ops);
  4835. cpuhp_remove_state(CPUHP_AP_KVM_ONLINE);
  4836. err_cpuhp:
  4837. kvm_arch_disable_virtualization();
  4838. --kvm_usage_count;
  4839. return r;
  4840. }
  4841. static void kvm_disable_virtualization(void)
  4842. {
  4843. guard(mutex)(&kvm_usage_lock);
  4844. if (--kvm_usage_count)
  4845. return;
  4846. unregister_syscore_ops(&kvm_syscore_ops);
  4847. cpuhp_remove_state(CPUHP_AP_KVM_ONLINE);
  4848. kvm_arch_disable_virtualization();
  4849. }
  4850. static int kvm_init_virtualization(void)
  4851. {
  4852. if (enable_virt_at_load)
  4853. return kvm_enable_virtualization();
  4854. return 0;
  4855. }
  4856. static void kvm_uninit_virtualization(void)
  4857. {
  4858. if (enable_virt_at_load)
  4859. kvm_disable_virtualization();
  4860. }
  4861. #else /* CONFIG_KVM_GENERIC_HARDWARE_ENABLING */
  4862. static int kvm_enable_virtualization(void)
  4863. {
  4864. return 0;
  4865. }
  4866. static int kvm_init_virtualization(void)
  4867. {
  4868. return 0;
  4869. }
  4870. static void kvm_disable_virtualization(void)
  4871. {
  4872. }
  4873. static void kvm_uninit_virtualization(void)
  4874. {
  4875. }
  4876. #endif /* CONFIG_KVM_GENERIC_HARDWARE_ENABLING */
  4877. static void kvm_iodevice_destructor(struct kvm_io_device *dev)
  4878. {
  4879. if (dev->ops->destructor)
  4880. dev->ops->destructor(dev);
  4881. }
  4882. static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
  4883. {
  4884. int i;
  4885. for (i = 0; i < bus->dev_count; i++) {
  4886. struct kvm_io_device *pos = bus->range[i].dev;
  4887. kvm_iodevice_destructor(pos);
  4888. }
  4889. kfree(bus);
  4890. }
  4891. static inline int kvm_io_bus_cmp(const struct kvm_io_range *r1,
  4892. const struct kvm_io_range *r2)
  4893. {
  4894. gpa_t addr1 = r1->addr;
  4895. gpa_t addr2 = r2->addr;
  4896. if (addr1 < addr2)
  4897. return -1;
  4898. /* If r2->len == 0, match the exact address. If r2->len != 0,
  4899. * accept any overlapping write. Any order is acceptable for
  4900. * overlapping ranges, because kvm_io_bus_get_first_dev ensures
  4901. * we process all of them.
  4902. */
  4903. if (r2->len) {
  4904. addr1 += r1->len;
  4905. addr2 += r2->len;
  4906. }
  4907. if (addr1 > addr2)
  4908. return 1;
  4909. return 0;
  4910. }
  4911. static int kvm_io_bus_sort_cmp(const void *p1, const void *p2)
  4912. {
  4913. return kvm_io_bus_cmp(p1, p2);
  4914. }
  4915. static int kvm_io_bus_get_first_dev(struct kvm_io_bus *bus,
  4916. gpa_t addr, int len)
  4917. {
  4918. struct kvm_io_range *range, key;
  4919. int off;
  4920. key = (struct kvm_io_range) {
  4921. .addr = addr,
  4922. .len = len,
  4923. };
  4924. range = bsearch(&key, bus->range, bus->dev_count,
  4925. sizeof(struct kvm_io_range), kvm_io_bus_sort_cmp);
  4926. if (range == NULL)
  4927. return -ENOENT;
  4928. off = range - bus->range;
  4929. while (off > 0 && kvm_io_bus_cmp(&key, &bus->range[off-1]) == 0)
  4930. off--;
  4931. return off;
  4932. }
  4933. static int __kvm_io_bus_write(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
  4934. struct kvm_io_range *range, const void *val)
  4935. {
  4936. int idx;
  4937. idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
  4938. if (idx < 0)
  4939. return -EOPNOTSUPP;
  4940. while (idx < bus->dev_count &&
  4941. kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
  4942. if (!kvm_iodevice_write(vcpu, bus->range[idx].dev, range->addr,
  4943. range->len, val))
  4944. return idx;
  4945. idx++;
  4946. }
  4947. return -EOPNOTSUPP;
  4948. }
  4949. /* kvm_io_bus_write - called under kvm->slots_lock */
  4950. int kvm_io_bus_write(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
  4951. int len, const void *val)
  4952. {
  4953. struct kvm_io_bus *bus;
  4954. struct kvm_io_range range;
  4955. int r;
  4956. range = (struct kvm_io_range) {
  4957. .addr = addr,
  4958. .len = len,
  4959. };
  4960. bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
  4961. if (!bus)
  4962. return -ENOMEM;
  4963. r = __kvm_io_bus_write(vcpu, bus, &range, val);
  4964. return r < 0 ? r : 0;
  4965. }
  4966. EXPORT_SYMBOL_GPL(kvm_io_bus_write);
  4967. /* kvm_io_bus_write_cookie - called under kvm->slots_lock */
  4968. int kvm_io_bus_write_cookie(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx,
  4969. gpa_t addr, int len, const void *val, long cookie)
  4970. {
  4971. struct kvm_io_bus *bus;
  4972. struct kvm_io_range range;
  4973. range = (struct kvm_io_range) {
  4974. .addr = addr,
  4975. .len = len,
  4976. };
  4977. bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
  4978. if (!bus)
  4979. return -ENOMEM;
  4980. /* First try the device referenced by cookie. */
  4981. if ((cookie >= 0) && (cookie < bus->dev_count) &&
  4982. (kvm_io_bus_cmp(&range, &bus->range[cookie]) == 0))
  4983. if (!kvm_iodevice_write(vcpu, bus->range[cookie].dev, addr, len,
  4984. val))
  4985. return cookie;
  4986. /*
  4987. * cookie contained garbage; fall back to search and return the
  4988. * correct cookie value.
  4989. */
  4990. return __kvm_io_bus_write(vcpu, bus, &range, val);
  4991. }
  4992. static int __kvm_io_bus_read(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
  4993. struct kvm_io_range *range, void *val)
  4994. {
  4995. int idx;
  4996. idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
  4997. if (idx < 0)
  4998. return -EOPNOTSUPP;
  4999. while (idx < bus->dev_count &&
  5000. kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
  5001. if (!kvm_iodevice_read(vcpu, bus->range[idx].dev, range->addr,
  5002. range->len, val))
  5003. return idx;
  5004. idx++;
  5005. }
  5006. return -EOPNOTSUPP;
  5007. }
  5008. /* kvm_io_bus_read - called under kvm->slots_lock */
  5009. int kvm_io_bus_read(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
  5010. int len, void *val)
  5011. {
  5012. struct kvm_io_bus *bus;
  5013. struct kvm_io_range range;
  5014. int r;
  5015. range = (struct kvm_io_range) {
  5016. .addr = addr,
  5017. .len = len,
  5018. };
  5019. bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
  5020. if (!bus)
  5021. return -ENOMEM;
  5022. r = __kvm_io_bus_read(vcpu, bus, &range, val);
  5023. return r < 0 ? r : 0;
  5024. }
  5025. int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
  5026. int len, struct kvm_io_device *dev)
  5027. {
  5028. int i;
  5029. struct kvm_io_bus *new_bus, *bus;
  5030. struct kvm_io_range range;
  5031. lockdep_assert_held(&kvm->slots_lock);
  5032. bus = kvm_get_bus(kvm, bus_idx);
  5033. if (!bus)
  5034. return -ENOMEM;
  5035. /* exclude ioeventfd which is limited by maximum fd */
  5036. if (bus->dev_count - bus->ioeventfd_count > NR_IOBUS_DEVS - 1)
  5037. return -ENOSPC;
  5038. new_bus = kmalloc(struct_size(bus, range, bus->dev_count + 1),
  5039. GFP_KERNEL_ACCOUNT);
  5040. if (!new_bus)
  5041. return -ENOMEM;
  5042. range = (struct kvm_io_range) {
  5043. .addr = addr,
  5044. .len = len,
  5045. .dev = dev,
  5046. };
  5047. for (i = 0; i < bus->dev_count; i++)
  5048. if (kvm_io_bus_cmp(&bus->range[i], &range) > 0)
  5049. break;
  5050. memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
  5051. new_bus->dev_count++;
  5052. new_bus->range[i] = range;
  5053. memcpy(new_bus->range + i + 1, bus->range + i,
  5054. (bus->dev_count - i) * sizeof(struct kvm_io_range));
  5055. rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
  5056. synchronize_srcu_expedited(&kvm->srcu);
  5057. kfree(bus);
  5058. return 0;
  5059. }
  5060. int kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
  5061. struct kvm_io_device *dev)
  5062. {
  5063. int i;
  5064. struct kvm_io_bus *new_bus, *bus;
  5065. lockdep_assert_held(&kvm->slots_lock);
  5066. bus = kvm_get_bus(kvm, bus_idx);
  5067. if (!bus)
  5068. return 0;
  5069. for (i = 0; i < bus->dev_count; i++) {
  5070. if (bus->range[i].dev == dev) {
  5071. break;
  5072. }
  5073. }
  5074. if (i == bus->dev_count)
  5075. return 0;
  5076. new_bus = kmalloc(struct_size(bus, range, bus->dev_count - 1),
  5077. GFP_KERNEL_ACCOUNT);
  5078. if (new_bus) {
  5079. memcpy(new_bus, bus, struct_size(bus, range, i));
  5080. new_bus->dev_count--;
  5081. memcpy(new_bus->range + i, bus->range + i + 1,
  5082. flex_array_size(new_bus, range, new_bus->dev_count - i));
  5083. }
  5084. rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
  5085. synchronize_srcu_expedited(&kvm->srcu);
  5086. /*
  5087. * If NULL bus is installed, destroy the old bus, including all the
  5088. * attached devices. Otherwise, destroy the caller's device only.
  5089. */
  5090. if (!new_bus) {
  5091. pr_err("kvm: failed to shrink bus, removing it completely\n");
  5092. kvm_io_bus_destroy(bus);
  5093. return -ENOMEM;
  5094. }
  5095. kvm_iodevice_destructor(dev);
  5096. kfree(bus);
  5097. return 0;
  5098. }
  5099. struct kvm_io_device *kvm_io_bus_get_dev(struct kvm *kvm, enum kvm_bus bus_idx,
  5100. gpa_t addr)
  5101. {
  5102. struct kvm_io_bus *bus;
  5103. int dev_idx, srcu_idx;
  5104. struct kvm_io_device *iodev = NULL;
  5105. srcu_idx = srcu_read_lock(&kvm->srcu);
  5106. bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
  5107. if (!bus)
  5108. goto out_unlock;
  5109. dev_idx = kvm_io_bus_get_first_dev(bus, addr, 1);
  5110. if (dev_idx < 0)
  5111. goto out_unlock;
  5112. iodev = bus->range[dev_idx].dev;
  5113. out_unlock:
  5114. srcu_read_unlock(&kvm->srcu, srcu_idx);
  5115. return iodev;
  5116. }
  5117. EXPORT_SYMBOL_GPL(kvm_io_bus_get_dev);
  5118. static int kvm_debugfs_open(struct inode *inode, struct file *file,
  5119. int (*get)(void *, u64 *), int (*set)(void *, u64),
  5120. const char *fmt)
  5121. {
  5122. int ret;
  5123. struct kvm_stat_data *stat_data = inode->i_private;
  5124. /*
  5125. * The debugfs files are a reference to the kvm struct which
  5126. * is still valid when kvm_destroy_vm is called. kvm_get_kvm_safe
  5127. * avoids the race between open and the removal of the debugfs directory.
  5128. */
  5129. if (!kvm_get_kvm_safe(stat_data->kvm))
  5130. return -ENOENT;
  5131. ret = simple_attr_open(inode, file, get,
  5132. kvm_stats_debugfs_mode(stat_data->desc) & 0222
  5133. ? set : NULL, fmt);
  5134. if (ret)
  5135. kvm_put_kvm(stat_data->kvm);
  5136. return ret;
  5137. }
  5138. static int kvm_debugfs_release(struct inode *inode, struct file *file)
  5139. {
  5140. struct kvm_stat_data *stat_data = inode->i_private;
  5141. simple_attr_release(inode, file);
  5142. kvm_put_kvm(stat_data->kvm);
  5143. return 0;
  5144. }
  5145. static int kvm_get_stat_per_vm(struct kvm *kvm, size_t offset, u64 *val)
  5146. {
  5147. *val = *(u64 *)((void *)(&kvm->stat) + offset);
  5148. return 0;
  5149. }
  5150. static int kvm_clear_stat_per_vm(struct kvm *kvm, size_t offset)
  5151. {
  5152. *(u64 *)((void *)(&kvm->stat) + offset) = 0;
  5153. return 0;
  5154. }
  5155. static int kvm_get_stat_per_vcpu(struct kvm *kvm, size_t offset, u64 *val)
  5156. {
  5157. unsigned long i;
  5158. struct kvm_vcpu *vcpu;
  5159. *val = 0;
  5160. kvm_for_each_vcpu(i, vcpu, kvm)
  5161. *val += *(u64 *)((void *)(&vcpu->stat) + offset);
  5162. return 0;
  5163. }
  5164. static int kvm_clear_stat_per_vcpu(struct kvm *kvm, size_t offset)
  5165. {
  5166. unsigned long i;
  5167. struct kvm_vcpu *vcpu;
  5168. kvm_for_each_vcpu(i, vcpu, kvm)
  5169. *(u64 *)((void *)(&vcpu->stat) + offset) = 0;
  5170. return 0;
  5171. }
  5172. static int kvm_stat_data_get(void *data, u64 *val)
  5173. {
  5174. int r = -EFAULT;
  5175. struct kvm_stat_data *stat_data = data;
  5176. switch (stat_data->kind) {
  5177. case KVM_STAT_VM:
  5178. r = kvm_get_stat_per_vm(stat_data->kvm,
  5179. stat_data->desc->desc.offset, val);
  5180. break;
  5181. case KVM_STAT_VCPU:
  5182. r = kvm_get_stat_per_vcpu(stat_data->kvm,
  5183. stat_data->desc->desc.offset, val);
  5184. break;
  5185. }
  5186. return r;
  5187. }
  5188. static int kvm_stat_data_clear(void *data, u64 val)
  5189. {
  5190. int r = -EFAULT;
  5191. struct kvm_stat_data *stat_data = data;
  5192. if (val)
  5193. return -EINVAL;
  5194. switch (stat_data->kind) {
  5195. case KVM_STAT_VM:
  5196. r = kvm_clear_stat_per_vm(stat_data->kvm,
  5197. stat_data->desc->desc.offset);
  5198. break;
  5199. case KVM_STAT_VCPU:
  5200. r = kvm_clear_stat_per_vcpu(stat_data->kvm,
  5201. stat_data->desc->desc.offset);
  5202. break;
  5203. }
  5204. return r;
  5205. }
  5206. static int kvm_stat_data_open(struct inode *inode, struct file *file)
  5207. {
  5208. __simple_attr_check_format("%llu\n", 0ull);
  5209. return kvm_debugfs_open(inode, file, kvm_stat_data_get,
  5210. kvm_stat_data_clear, "%llu\n");
  5211. }
  5212. static const struct file_operations stat_fops_per_vm = {
  5213. .owner = THIS_MODULE,
  5214. .open = kvm_stat_data_open,
  5215. .release = kvm_debugfs_release,
  5216. .read = simple_attr_read,
  5217. .write = simple_attr_write,
  5218. };
  5219. static int vm_stat_get(void *_offset, u64 *val)
  5220. {
  5221. unsigned offset = (long)_offset;
  5222. struct kvm *kvm;
  5223. u64 tmp_val;
  5224. *val = 0;
  5225. mutex_lock(&kvm_lock);
  5226. list_for_each_entry(kvm, &vm_list, vm_list) {
  5227. kvm_get_stat_per_vm(kvm, offset, &tmp_val);
  5228. *val += tmp_val;
  5229. }
  5230. mutex_unlock(&kvm_lock);
  5231. return 0;
  5232. }
  5233. static int vm_stat_clear(void *_offset, u64 val)
  5234. {
  5235. unsigned offset = (long)_offset;
  5236. struct kvm *kvm;
  5237. if (val)
  5238. return -EINVAL;
  5239. mutex_lock(&kvm_lock);
  5240. list_for_each_entry(kvm, &vm_list, vm_list) {
  5241. kvm_clear_stat_per_vm(kvm, offset);
  5242. }
  5243. mutex_unlock(&kvm_lock);
  5244. return 0;
  5245. }
  5246. DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, vm_stat_clear, "%llu\n");
  5247. DEFINE_SIMPLE_ATTRIBUTE(vm_stat_readonly_fops, vm_stat_get, NULL, "%llu\n");
  5248. static int vcpu_stat_get(void *_offset, u64 *val)
  5249. {
  5250. unsigned offset = (long)_offset;
  5251. struct kvm *kvm;
  5252. u64 tmp_val;
  5253. *val = 0;
  5254. mutex_lock(&kvm_lock);
  5255. list_for_each_entry(kvm, &vm_list, vm_list) {
  5256. kvm_get_stat_per_vcpu(kvm, offset, &tmp_val);
  5257. *val += tmp_val;
  5258. }
  5259. mutex_unlock(&kvm_lock);
  5260. return 0;
  5261. }
  5262. static int vcpu_stat_clear(void *_offset, u64 val)
  5263. {
  5264. unsigned offset = (long)_offset;
  5265. struct kvm *kvm;
  5266. if (val)
  5267. return -EINVAL;
  5268. mutex_lock(&kvm_lock);
  5269. list_for_each_entry(kvm, &vm_list, vm_list) {
  5270. kvm_clear_stat_per_vcpu(kvm, offset);
  5271. }
  5272. mutex_unlock(&kvm_lock);
  5273. return 0;
  5274. }
  5275. DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, vcpu_stat_clear,
  5276. "%llu\n");
  5277. DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_readonly_fops, vcpu_stat_get, NULL, "%llu\n");
  5278. static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm)
  5279. {
  5280. struct kobj_uevent_env *env;
  5281. unsigned long long created, active;
  5282. if (!kvm_dev.this_device || !kvm)
  5283. return;
  5284. mutex_lock(&kvm_lock);
  5285. if (type == KVM_EVENT_CREATE_VM) {
  5286. kvm_createvm_count++;
  5287. kvm_active_vms++;
  5288. } else if (type == KVM_EVENT_DESTROY_VM) {
  5289. kvm_active_vms--;
  5290. }
  5291. created = kvm_createvm_count;
  5292. active = kvm_active_vms;
  5293. mutex_unlock(&kvm_lock);
  5294. env = kzalloc(sizeof(*env), GFP_KERNEL);
  5295. if (!env)
  5296. return;
  5297. add_uevent_var(env, "CREATED=%llu", created);
  5298. add_uevent_var(env, "COUNT=%llu", active);
  5299. if (type == KVM_EVENT_CREATE_VM) {
  5300. add_uevent_var(env, "EVENT=create");
  5301. kvm->userspace_pid = task_pid_nr(current);
  5302. } else if (type == KVM_EVENT_DESTROY_VM) {
  5303. add_uevent_var(env, "EVENT=destroy");
  5304. }
  5305. add_uevent_var(env, "PID=%d", kvm->userspace_pid);
  5306. if (!IS_ERR(kvm->debugfs_dentry)) {
  5307. char *tmp, *p = kmalloc(PATH_MAX, GFP_KERNEL);
  5308. if (p) {
  5309. tmp = dentry_path_raw(kvm->debugfs_dentry, p, PATH_MAX);
  5310. if (!IS_ERR(tmp))
  5311. add_uevent_var(env, "STATS_PATH=%s", tmp);
  5312. kfree(p);
  5313. }
  5314. }
  5315. /* no need for checks, since we are adding at most only 5 keys */
  5316. env->envp[env->envp_idx++] = NULL;
  5317. kobject_uevent_env(&kvm_dev.this_device->kobj, KOBJ_CHANGE, env->envp);
  5318. kfree(env);
  5319. }
  5320. static void kvm_init_debug(void)
  5321. {
  5322. const struct file_operations *fops;
  5323. const struct _kvm_stats_desc *pdesc;
  5324. int i;
  5325. kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
  5326. for (i = 0; i < kvm_vm_stats_header.num_desc; ++i) {
  5327. pdesc = &kvm_vm_stats_desc[i];
  5328. if (kvm_stats_debugfs_mode(pdesc) & 0222)
  5329. fops = &vm_stat_fops;
  5330. else
  5331. fops = &vm_stat_readonly_fops;
  5332. debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
  5333. kvm_debugfs_dir,
  5334. (void *)(long)pdesc->desc.offset, fops);
  5335. }
  5336. for (i = 0; i < kvm_vcpu_stats_header.num_desc; ++i) {
  5337. pdesc = &kvm_vcpu_stats_desc[i];
  5338. if (kvm_stats_debugfs_mode(pdesc) & 0222)
  5339. fops = &vcpu_stat_fops;
  5340. else
  5341. fops = &vcpu_stat_readonly_fops;
  5342. debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
  5343. kvm_debugfs_dir,
  5344. (void *)(long)pdesc->desc.offset, fops);
  5345. }
  5346. }
  5347. static inline
  5348. struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
  5349. {
  5350. return container_of(pn, struct kvm_vcpu, preempt_notifier);
  5351. }
  5352. static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
  5353. {
  5354. struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
  5355. WRITE_ONCE(vcpu->preempted, false);
  5356. WRITE_ONCE(vcpu->ready, false);
  5357. __this_cpu_write(kvm_running_vcpu, vcpu);
  5358. kvm_arch_vcpu_load(vcpu, cpu);
  5359. WRITE_ONCE(vcpu->scheduled_out, false);
  5360. }
  5361. static void kvm_sched_out(struct preempt_notifier *pn,
  5362. struct task_struct *next)
  5363. {
  5364. struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
  5365. WRITE_ONCE(vcpu->scheduled_out, true);
  5366. if (task_is_runnable(current) && vcpu->wants_to_run) {
  5367. WRITE_ONCE(vcpu->preempted, true);
  5368. WRITE_ONCE(vcpu->ready, true);
  5369. }
  5370. kvm_arch_vcpu_put(vcpu);
  5371. __this_cpu_write(kvm_running_vcpu, NULL);
  5372. }
  5373. /**
  5374. * kvm_get_running_vcpu - get the vcpu running on the current CPU.
  5375. *
  5376. * We can disable preemption locally around accessing the per-CPU variable,
  5377. * and use the resolved vcpu pointer after enabling preemption again,
  5378. * because even if the current thread is migrated to another CPU, reading
  5379. * the per-CPU value later will give us the same value as we update the
  5380. * per-CPU variable in the preempt notifier handlers.
  5381. */
  5382. struct kvm_vcpu *kvm_get_running_vcpu(void)
  5383. {
  5384. struct kvm_vcpu *vcpu;
  5385. preempt_disable();
  5386. vcpu = __this_cpu_read(kvm_running_vcpu);
  5387. preempt_enable();
  5388. return vcpu;
  5389. }
  5390. EXPORT_SYMBOL_GPL(kvm_get_running_vcpu);
  5391. /**
  5392. * kvm_get_running_vcpus - get the per-CPU array of currently running vcpus.
  5393. */
  5394. struct kvm_vcpu * __percpu *kvm_get_running_vcpus(void)
  5395. {
  5396. return &kvm_running_vcpu;
  5397. }
  5398. #ifdef CONFIG_GUEST_PERF_EVENTS
  5399. static unsigned int kvm_guest_state(void)
  5400. {
  5401. struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
  5402. unsigned int state;
  5403. if (!kvm_arch_pmi_in_guest(vcpu))
  5404. return 0;
  5405. state = PERF_GUEST_ACTIVE;
  5406. if (!kvm_arch_vcpu_in_kernel(vcpu))
  5407. state |= PERF_GUEST_USER;
  5408. return state;
  5409. }
  5410. static unsigned long kvm_guest_get_ip(void)
  5411. {
  5412. struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
  5413. /* Retrieving the IP must be guarded by a call to kvm_guest_state(). */
  5414. if (WARN_ON_ONCE(!kvm_arch_pmi_in_guest(vcpu)))
  5415. return 0;
  5416. return kvm_arch_vcpu_get_ip(vcpu);
  5417. }
  5418. static struct perf_guest_info_callbacks kvm_guest_cbs = {
  5419. .state = kvm_guest_state,
  5420. .get_ip = kvm_guest_get_ip,
  5421. .handle_intel_pt_intr = NULL,
  5422. };
  5423. void kvm_register_perf_callbacks(unsigned int (*pt_intr_handler)(void))
  5424. {
  5425. kvm_guest_cbs.handle_intel_pt_intr = pt_intr_handler;
  5426. perf_register_guest_info_callbacks(&kvm_guest_cbs);
  5427. }
  5428. void kvm_unregister_perf_callbacks(void)
  5429. {
  5430. perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
  5431. }
  5432. #endif
  5433. int kvm_init(unsigned vcpu_size, unsigned vcpu_align, struct module *module)
  5434. {
  5435. int r;
  5436. int cpu;
  5437. /* A kmem cache lets us meet the alignment requirements of fx_save. */
  5438. if (!vcpu_align)
  5439. vcpu_align = __alignof__(struct kvm_vcpu);
  5440. kvm_vcpu_cache =
  5441. kmem_cache_create_usercopy("kvm_vcpu", vcpu_size, vcpu_align,
  5442. SLAB_ACCOUNT,
  5443. offsetof(struct kvm_vcpu, arch),
  5444. offsetofend(struct kvm_vcpu, stats_id)
  5445. - offsetof(struct kvm_vcpu, arch),
  5446. NULL);
  5447. if (!kvm_vcpu_cache)
  5448. return -ENOMEM;
  5449. for_each_possible_cpu(cpu) {
  5450. if (!alloc_cpumask_var_node(&per_cpu(cpu_kick_mask, cpu),
  5451. GFP_KERNEL, cpu_to_node(cpu))) {
  5452. r = -ENOMEM;
  5453. goto err_cpu_kick_mask;
  5454. }
  5455. }
  5456. r = kvm_irqfd_init();
  5457. if (r)
  5458. goto err_irqfd;
  5459. r = kvm_async_pf_init();
  5460. if (r)
  5461. goto err_async_pf;
  5462. kvm_chardev_ops.owner = module;
  5463. kvm_vm_fops.owner = module;
  5464. kvm_vcpu_fops.owner = module;
  5465. kvm_device_fops.owner = module;
  5466. kvm_preempt_ops.sched_in = kvm_sched_in;
  5467. kvm_preempt_ops.sched_out = kvm_sched_out;
  5468. kvm_init_debug();
  5469. r = kvm_vfio_ops_init();
  5470. if (WARN_ON_ONCE(r))
  5471. goto err_vfio;
  5472. kvm_gmem_init(module);
  5473. r = kvm_init_virtualization();
  5474. if (r)
  5475. goto err_virt;
  5476. /*
  5477. * Registration _must_ be the very last thing done, as this exposes
  5478. * /dev/kvm to userspace, i.e. all infrastructure must be setup!
  5479. */
  5480. r = misc_register(&kvm_dev);
  5481. if (r) {
  5482. pr_err("kvm: misc device register failed\n");
  5483. goto err_register;
  5484. }
  5485. return 0;
  5486. err_register:
  5487. kvm_uninit_virtualization();
  5488. err_virt:
  5489. kvm_vfio_ops_exit();
  5490. err_vfio:
  5491. kvm_async_pf_deinit();
  5492. err_async_pf:
  5493. kvm_irqfd_exit();
  5494. err_irqfd:
  5495. err_cpu_kick_mask:
  5496. for_each_possible_cpu(cpu)
  5497. free_cpumask_var(per_cpu(cpu_kick_mask, cpu));
  5498. kmem_cache_destroy(kvm_vcpu_cache);
  5499. return r;
  5500. }
  5501. EXPORT_SYMBOL_GPL(kvm_init);
  5502. void kvm_exit(void)
  5503. {
  5504. int cpu;
  5505. /*
  5506. * Note, unregistering /dev/kvm doesn't strictly need to come first,
  5507. * fops_get(), a.k.a. try_module_get(), prevents acquiring references
  5508. * to KVM while the module is being stopped.
  5509. */
  5510. misc_deregister(&kvm_dev);
  5511. kvm_uninit_virtualization();
  5512. debugfs_remove_recursive(kvm_debugfs_dir);
  5513. for_each_possible_cpu(cpu)
  5514. free_cpumask_var(per_cpu(cpu_kick_mask, cpu));
  5515. kmem_cache_destroy(kvm_vcpu_cache);
  5516. kvm_vfio_ops_exit();
  5517. kvm_async_pf_deinit();
  5518. kvm_irqfd_exit();
  5519. }
  5520. EXPORT_SYMBOL_GPL(kvm_exit);