kvm_main.c 152 KB

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