core.c 347 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Performance events core code:
  4. *
  5. * Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de>
  6. * Copyright (C) 2008-2011 Red Hat, Inc., Ingo Molnar
  7. * Copyright (C) 2008-2011 Red Hat, Inc., Peter Zijlstra
  8. * Copyright © 2009 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
  9. */
  10. #include <linux/fs.h>
  11. #include <linux/mm.h>
  12. #include <linux/cpu.h>
  13. #include <linux/smp.h>
  14. #include <linux/idr.h>
  15. #include <linux/file.h>
  16. #include <linux/poll.h>
  17. #include <linux/slab.h>
  18. #include <linux/hash.h>
  19. #include <linux/tick.h>
  20. #include <linux/sysfs.h>
  21. #include <linux/dcache.h>
  22. #include <linux/percpu.h>
  23. #include <linux/ptrace.h>
  24. #include <linux/reboot.h>
  25. #include <linux/vmstat.h>
  26. #include <linux/device.h>
  27. #include <linux/export.h>
  28. #include <linux/vmalloc.h>
  29. #include <linux/hardirq.h>
  30. #include <linux/hugetlb.h>
  31. #include <linux/rculist.h>
  32. #include <linux/uaccess.h>
  33. #include <linux/syscalls.h>
  34. #include <linux/anon_inodes.h>
  35. #include <linux/kernel_stat.h>
  36. #include <linux/cgroup.h>
  37. #include <linux/perf_event.h>
  38. #include <linux/trace_events.h>
  39. #include <linux/hw_breakpoint.h>
  40. #include <linux/mm_types.h>
  41. #include <linux/module.h>
  42. #include <linux/mman.h>
  43. #include <linux/compat.h>
  44. #include <linux/bpf.h>
  45. #include <linux/filter.h>
  46. #include <linux/namei.h>
  47. #include <linux/parser.h>
  48. #include <linux/sched/clock.h>
  49. #include <linux/sched/mm.h>
  50. #include <linux/proc_ns.h>
  51. #include <linux/mount.h>
  52. #include <linux/min_heap.h>
  53. #include <linux/highmem.h>
  54. #include <linux/pgtable.h>
  55. #include <linux/buildid.h>
  56. #include <linux/task_work.h>
  57. #include "internal.h"
  58. #include <asm/irq_regs.h>
  59. typedef int (*remote_function_f)(void *);
  60. struct remote_function_call {
  61. struct task_struct *p;
  62. remote_function_f func;
  63. void *info;
  64. int ret;
  65. };
  66. static void remote_function(void *data)
  67. {
  68. struct remote_function_call *tfc = data;
  69. struct task_struct *p = tfc->p;
  70. if (p) {
  71. /* -EAGAIN */
  72. if (task_cpu(p) != smp_processor_id())
  73. return;
  74. /*
  75. * Now that we're on right CPU with IRQs disabled, we can test
  76. * if we hit the right task without races.
  77. */
  78. tfc->ret = -ESRCH; /* No such (running) process */
  79. if (p != current)
  80. return;
  81. }
  82. tfc->ret = tfc->func(tfc->info);
  83. }
  84. /**
  85. * task_function_call - call a function on the cpu on which a task runs
  86. * @p: the task to evaluate
  87. * @func: the function to be called
  88. * @info: the function call argument
  89. *
  90. * Calls the function @func when the task is currently running. This might
  91. * be on the current CPU, which just calls the function directly. This will
  92. * retry due to any failures in smp_call_function_single(), such as if the
  93. * task_cpu() goes offline concurrently.
  94. *
  95. * returns @func return value or -ESRCH or -ENXIO when the process isn't running
  96. */
  97. static int
  98. task_function_call(struct task_struct *p, remote_function_f func, void *info)
  99. {
  100. struct remote_function_call data = {
  101. .p = p,
  102. .func = func,
  103. .info = info,
  104. .ret = -EAGAIN,
  105. };
  106. int ret;
  107. for (;;) {
  108. ret = smp_call_function_single(task_cpu(p), remote_function,
  109. &data, 1);
  110. if (!ret)
  111. ret = data.ret;
  112. if (ret != -EAGAIN)
  113. break;
  114. cond_resched();
  115. }
  116. return ret;
  117. }
  118. /**
  119. * cpu_function_call - call a function on the cpu
  120. * @cpu: target cpu to queue this function
  121. * @func: the function to be called
  122. * @info: the function call argument
  123. *
  124. * Calls the function @func on the remote cpu.
  125. *
  126. * returns: @func return value or -ENXIO when the cpu is offline
  127. */
  128. static int cpu_function_call(int cpu, remote_function_f func, void *info)
  129. {
  130. struct remote_function_call data = {
  131. .p = NULL,
  132. .func = func,
  133. .info = info,
  134. .ret = -ENXIO, /* No such CPU */
  135. };
  136. smp_call_function_single(cpu, remote_function, &data, 1);
  137. return data.ret;
  138. }
  139. enum event_type_t {
  140. EVENT_FLEXIBLE = 0x01,
  141. EVENT_PINNED = 0x02,
  142. EVENT_TIME = 0x04,
  143. EVENT_FROZEN = 0x08,
  144. /* see ctx_resched() for details */
  145. EVENT_CPU = 0x10,
  146. EVENT_CGROUP = 0x20,
  147. /* compound helpers */
  148. EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
  149. EVENT_TIME_FROZEN = EVENT_TIME | EVENT_FROZEN,
  150. };
  151. static inline void __perf_ctx_lock(struct perf_event_context *ctx)
  152. {
  153. raw_spin_lock(&ctx->lock);
  154. WARN_ON_ONCE(ctx->is_active & EVENT_FROZEN);
  155. }
  156. static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
  157. struct perf_event_context *ctx)
  158. {
  159. __perf_ctx_lock(&cpuctx->ctx);
  160. if (ctx)
  161. __perf_ctx_lock(ctx);
  162. }
  163. static inline void __perf_ctx_unlock(struct perf_event_context *ctx)
  164. {
  165. /*
  166. * If ctx_sched_in() didn't again set any ALL flags, clean up
  167. * after ctx_sched_out() by clearing is_active.
  168. */
  169. if (ctx->is_active & EVENT_FROZEN) {
  170. if (!(ctx->is_active & EVENT_ALL))
  171. ctx->is_active = 0;
  172. else
  173. ctx->is_active &= ~EVENT_FROZEN;
  174. }
  175. raw_spin_unlock(&ctx->lock);
  176. }
  177. static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
  178. struct perf_event_context *ctx)
  179. {
  180. if (ctx)
  181. __perf_ctx_unlock(ctx);
  182. __perf_ctx_unlock(&cpuctx->ctx);
  183. }
  184. typedef struct {
  185. struct perf_cpu_context *cpuctx;
  186. struct perf_event_context *ctx;
  187. } class_perf_ctx_lock_t;
  188. static inline void class_perf_ctx_lock_destructor(class_perf_ctx_lock_t *_T)
  189. { perf_ctx_unlock(_T->cpuctx, _T->ctx); }
  190. static inline class_perf_ctx_lock_t
  191. class_perf_ctx_lock_constructor(struct perf_cpu_context *cpuctx,
  192. struct perf_event_context *ctx)
  193. { perf_ctx_lock(cpuctx, ctx); return (class_perf_ctx_lock_t){ cpuctx, ctx }; }
  194. #define TASK_TOMBSTONE ((void *)-1L)
  195. static bool is_kernel_event(struct perf_event *event)
  196. {
  197. return READ_ONCE(event->owner) == TASK_TOMBSTONE;
  198. }
  199. static DEFINE_PER_CPU(struct perf_cpu_context, perf_cpu_context);
  200. struct perf_event_context *perf_cpu_task_ctx(void)
  201. {
  202. lockdep_assert_irqs_disabled();
  203. return this_cpu_ptr(&perf_cpu_context)->task_ctx;
  204. }
  205. /*
  206. * On task ctx scheduling...
  207. *
  208. * When !ctx->nr_events a task context will not be scheduled. This means
  209. * we can disable the scheduler hooks (for performance) without leaving
  210. * pending task ctx state.
  211. *
  212. * This however results in two special cases:
  213. *
  214. * - removing the last event from a task ctx; this is relatively straight
  215. * forward and is done in __perf_remove_from_context.
  216. *
  217. * - adding the first event to a task ctx; this is tricky because we cannot
  218. * rely on ctx->is_active and therefore cannot use event_function_call().
  219. * See perf_install_in_context().
  220. *
  221. * If ctx->nr_events, then ctx->is_active and cpuctx->task_ctx are set.
  222. */
  223. typedef void (*event_f)(struct perf_event *, struct perf_cpu_context *,
  224. struct perf_event_context *, void *);
  225. struct event_function_struct {
  226. struct perf_event *event;
  227. event_f func;
  228. void *data;
  229. };
  230. static int event_function(void *info)
  231. {
  232. struct event_function_struct *efs = info;
  233. struct perf_event *event = efs->event;
  234. struct perf_event_context *ctx = event->ctx;
  235. struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
  236. struct perf_event_context *task_ctx = cpuctx->task_ctx;
  237. int ret = 0;
  238. lockdep_assert_irqs_disabled();
  239. perf_ctx_lock(cpuctx, task_ctx);
  240. /*
  241. * Since we do the IPI call without holding ctx->lock things can have
  242. * changed, double check we hit the task we set out to hit.
  243. */
  244. if (ctx->task) {
  245. if (ctx->task != current) {
  246. ret = -ESRCH;
  247. goto unlock;
  248. }
  249. /*
  250. * We only use event_function_call() on established contexts,
  251. * and event_function() is only ever called when active (or
  252. * rather, we'll have bailed in task_function_call() or the
  253. * above ctx->task != current test), therefore we must have
  254. * ctx->is_active here.
  255. */
  256. WARN_ON_ONCE(!ctx->is_active);
  257. /*
  258. * And since we have ctx->is_active, cpuctx->task_ctx must
  259. * match.
  260. */
  261. WARN_ON_ONCE(task_ctx != ctx);
  262. } else {
  263. WARN_ON_ONCE(&cpuctx->ctx != ctx);
  264. }
  265. efs->func(event, cpuctx, ctx, efs->data);
  266. unlock:
  267. perf_ctx_unlock(cpuctx, task_ctx);
  268. return ret;
  269. }
  270. static void event_function_call(struct perf_event *event, event_f func, void *data)
  271. {
  272. struct perf_event_context *ctx = event->ctx;
  273. struct task_struct *task = READ_ONCE(ctx->task); /* verified in event_function */
  274. struct perf_cpu_context *cpuctx;
  275. struct event_function_struct efs = {
  276. .event = event,
  277. .func = func,
  278. .data = data,
  279. };
  280. if (!event->parent) {
  281. /*
  282. * If this is a !child event, we must hold ctx::mutex to
  283. * stabilize the event->ctx relation. See
  284. * perf_event_ctx_lock().
  285. */
  286. lockdep_assert_held(&ctx->mutex);
  287. }
  288. if (!task) {
  289. cpu_function_call(event->cpu, event_function, &efs);
  290. return;
  291. }
  292. if (task == TASK_TOMBSTONE)
  293. return;
  294. again:
  295. if (!task_function_call(task, event_function, &efs))
  296. return;
  297. local_irq_disable();
  298. cpuctx = this_cpu_ptr(&perf_cpu_context);
  299. perf_ctx_lock(cpuctx, ctx);
  300. /*
  301. * Reload the task pointer, it might have been changed by
  302. * a concurrent perf_event_context_sched_out().
  303. */
  304. task = ctx->task;
  305. if (task == TASK_TOMBSTONE)
  306. goto unlock;
  307. if (ctx->is_active) {
  308. perf_ctx_unlock(cpuctx, ctx);
  309. local_irq_enable();
  310. goto again;
  311. }
  312. func(event, NULL, ctx, data);
  313. unlock:
  314. perf_ctx_unlock(cpuctx, ctx);
  315. local_irq_enable();
  316. }
  317. /*
  318. * Similar to event_function_call() + event_function(), but hard assumes IRQs
  319. * are already disabled and we're on the right CPU.
  320. */
  321. static void event_function_local(struct perf_event *event, event_f func, void *data)
  322. {
  323. struct perf_event_context *ctx = event->ctx;
  324. struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
  325. struct task_struct *task = READ_ONCE(ctx->task);
  326. struct perf_event_context *task_ctx = NULL;
  327. lockdep_assert_irqs_disabled();
  328. if (task) {
  329. if (task == TASK_TOMBSTONE)
  330. return;
  331. task_ctx = ctx;
  332. }
  333. perf_ctx_lock(cpuctx, task_ctx);
  334. task = ctx->task;
  335. if (task == TASK_TOMBSTONE)
  336. goto unlock;
  337. if (task) {
  338. /*
  339. * We must be either inactive or active and the right task,
  340. * otherwise we're screwed, since we cannot IPI to somewhere
  341. * else.
  342. */
  343. if (ctx->is_active) {
  344. if (WARN_ON_ONCE(task != current))
  345. goto unlock;
  346. if (WARN_ON_ONCE(cpuctx->task_ctx != ctx))
  347. goto unlock;
  348. }
  349. } else {
  350. WARN_ON_ONCE(&cpuctx->ctx != ctx);
  351. }
  352. func(event, cpuctx, ctx, data);
  353. unlock:
  354. perf_ctx_unlock(cpuctx, task_ctx);
  355. }
  356. #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
  357. PERF_FLAG_FD_OUTPUT |\
  358. PERF_FLAG_PID_CGROUP |\
  359. PERF_FLAG_FD_CLOEXEC)
  360. /*
  361. * branch priv levels that need permission checks
  362. */
  363. #define PERF_SAMPLE_BRANCH_PERM_PLM \
  364. (PERF_SAMPLE_BRANCH_KERNEL |\
  365. PERF_SAMPLE_BRANCH_HV)
  366. /*
  367. * perf_sched_events : >0 events exist
  368. */
  369. static void perf_sched_delayed(struct work_struct *work);
  370. DEFINE_STATIC_KEY_FALSE(perf_sched_events);
  371. static DECLARE_DELAYED_WORK(perf_sched_work, perf_sched_delayed);
  372. static DEFINE_MUTEX(perf_sched_mutex);
  373. static atomic_t perf_sched_count;
  374. static DEFINE_PER_CPU(struct pmu_event_list, pmu_sb_events);
  375. static atomic_t nr_mmap_events __read_mostly;
  376. static atomic_t nr_comm_events __read_mostly;
  377. static atomic_t nr_namespaces_events __read_mostly;
  378. static atomic_t nr_task_events __read_mostly;
  379. static atomic_t nr_freq_events __read_mostly;
  380. static atomic_t nr_switch_events __read_mostly;
  381. static atomic_t nr_ksymbol_events __read_mostly;
  382. static atomic_t nr_bpf_events __read_mostly;
  383. static atomic_t nr_cgroup_events __read_mostly;
  384. static atomic_t nr_text_poke_events __read_mostly;
  385. static atomic_t nr_build_id_events __read_mostly;
  386. static LIST_HEAD(pmus);
  387. static DEFINE_MUTEX(pmus_lock);
  388. static struct srcu_struct pmus_srcu;
  389. static cpumask_var_t perf_online_mask;
  390. static cpumask_var_t perf_online_core_mask;
  391. static cpumask_var_t perf_online_die_mask;
  392. static cpumask_var_t perf_online_cluster_mask;
  393. static cpumask_var_t perf_online_pkg_mask;
  394. static cpumask_var_t perf_online_sys_mask;
  395. static struct kmem_cache *perf_event_cache;
  396. /*
  397. * perf event paranoia level:
  398. * -1 - not paranoid at all
  399. * 0 - disallow raw tracepoint access for unpriv
  400. * 1 - disallow cpu events for unpriv
  401. * 2 - disallow kernel profiling for unpriv
  402. */
  403. int sysctl_perf_event_paranoid __read_mostly = 2;
  404. /* Minimum for 512 kiB + 1 user control page */
  405. int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
  406. /*
  407. * max perf event sample rate
  408. */
  409. #define DEFAULT_MAX_SAMPLE_RATE 100000
  410. #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
  411. #define DEFAULT_CPU_TIME_MAX_PERCENT 25
  412. int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
  413. static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
  414. static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
  415. static int perf_sample_allowed_ns __read_mostly =
  416. DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
  417. static void update_perf_cpu_limits(void)
  418. {
  419. u64 tmp = perf_sample_period_ns;
  420. tmp *= sysctl_perf_cpu_time_max_percent;
  421. tmp = div_u64(tmp, 100);
  422. if (!tmp)
  423. tmp = 1;
  424. WRITE_ONCE(perf_sample_allowed_ns, tmp);
  425. }
  426. static bool perf_rotate_context(struct perf_cpu_pmu_context *cpc);
  427. int perf_event_max_sample_rate_handler(const struct ctl_table *table, int write,
  428. void *buffer, size_t *lenp, loff_t *ppos)
  429. {
  430. int ret;
  431. int perf_cpu = sysctl_perf_cpu_time_max_percent;
  432. /*
  433. * If throttling is disabled don't allow the write:
  434. */
  435. if (write && (perf_cpu == 100 || perf_cpu == 0))
  436. return -EINVAL;
  437. ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
  438. if (ret || !write)
  439. return ret;
  440. max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
  441. perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
  442. update_perf_cpu_limits();
  443. return 0;
  444. }
  445. int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
  446. int perf_cpu_time_max_percent_handler(const struct ctl_table *table, int write,
  447. void *buffer, size_t *lenp, loff_t *ppos)
  448. {
  449. int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
  450. if (ret || !write)
  451. return ret;
  452. if (sysctl_perf_cpu_time_max_percent == 100 ||
  453. sysctl_perf_cpu_time_max_percent == 0) {
  454. printk(KERN_WARNING
  455. "perf: Dynamic interrupt throttling disabled, can hang your system!\n");
  456. WRITE_ONCE(perf_sample_allowed_ns, 0);
  457. } else {
  458. update_perf_cpu_limits();
  459. }
  460. return 0;
  461. }
  462. /*
  463. * perf samples are done in some very critical code paths (NMIs).
  464. * If they take too much CPU time, the system can lock up and not
  465. * get any real work done. This will drop the sample rate when
  466. * we detect that events are taking too long.
  467. */
  468. #define NR_ACCUMULATED_SAMPLES 128
  469. static DEFINE_PER_CPU(u64, running_sample_length);
  470. static u64 __report_avg;
  471. static u64 __report_allowed;
  472. static void perf_duration_warn(struct irq_work *w)
  473. {
  474. printk_ratelimited(KERN_INFO
  475. "perf: interrupt took too long (%lld > %lld), lowering "
  476. "kernel.perf_event_max_sample_rate to %d\n",
  477. __report_avg, __report_allowed,
  478. sysctl_perf_event_sample_rate);
  479. }
  480. static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
  481. void perf_sample_event_took(u64 sample_len_ns)
  482. {
  483. u64 max_len = READ_ONCE(perf_sample_allowed_ns);
  484. u64 running_len;
  485. u64 avg_len;
  486. u32 max;
  487. if (max_len == 0)
  488. return;
  489. /* Decay the counter by 1 average sample. */
  490. running_len = __this_cpu_read(running_sample_length);
  491. running_len -= running_len/NR_ACCUMULATED_SAMPLES;
  492. running_len += sample_len_ns;
  493. __this_cpu_write(running_sample_length, running_len);
  494. /*
  495. * Note: this will be biased artificially low until we have
  496. * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
  497. * from having to maintain a count.
  498. */
  499. avg_len = running_len/NR_ACCUMULATED_SAMPLES;
  500. if (avg_len <= max_len)
  501. return;
  502. __report_avg = avg_len;
  503. __report_allowed = max_len;
  504. /*
  505. * Compute a throttle threshold 25% below the current duration.
  506. */
  507. avg_len += avg_len / 4;
  508. max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent;
  509. if (avg_len < max)
  510. max /= (u32)avg_len;
  511. else
  512. max = 1;
  513. WRITE_ONCE(perf_sample_allowed_ns, avg_len);
  514. WRITE_ONCE(max_samples_per_tick, max);
  515. sysctl_perf_event_sample_rate = max * HZ;
  516. perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
  517. if (!irq_work_queue(&perf_duration_work)) {
  518. early_printk("perf: interrupt took too long (%lld > %lld), lowering "
  519. "kernel.perf_event_max_sample_rate to %d\n",
  520. __report_avg, __report_allowed,
  521. sysctl_perf_event_sample_rate);
  522. }
  523. }
  524. static atomic64_t perf_event_id;
  525. static void update_context_time(struct perf_event_context *ctx);
  526. static u64 perf_event_time(struct perf_event *event);
  527. void __weak perf_event_print_debug(void) { }
  528. static inline u64 perf_clock(void)
  529. {
  530. return local_clock();
  531. }
  532. static inline u64 perf_event_clock(struct perf_event *event)
  533. {
  534. return event->clock();
  535. }
  536. /*
  537. * State based event timekeeping...
  538. *
  539. * The basic idea is to use event->state to determine which (if any) time
  540. * fields to increment with the current delta. This means we only need to
  541. * update timestamps when we change state or when they are explicitly requested
  542. * (read).
  543. *
  544. * Event groups make things a little more complicated, but not terribly so. The
  545. * rules for a group are that if the group leader is OFF the entire group is
  546. * OFF, irrespective of what the group member states are. This results in
  547. * __perf_effective_state().
  548. *
  549. * A further ramification is that when a group leader flips between OFF and
  550. * !OFF, we need to update all group member times.
  551. *
  552. *
  553. * NOTE: perf_event_time() is based on the (cgroup) context time, and thus we
  554. * need to make sure the relevant context time is updated before we try and
  555. * update our timestamps.
  556. */
  557. static __always_inline enum perf_event_state
  558. __perf_effective_state(struct perf_event *event)
  559. {
  560. struct perf_event *leader = event->group_leader;
  561. if (leader->state <= PERF_EVENT_STATE_OFF)
  562. return leader->state;
  563. return event->state;
  564. }
  565. static __always_inline void
  566. __perf_update_times(struct perf_event *event, u64 now, u64 *enabled, u64 *running)
  567. {
  568. enum perf_event_state state = __perf_effective_state(event);
  569. u64 delta = now - event->tstamp;
  570. *enabled = event->total_time_enabled;
  571. if (state >= PERF_EVENT_STATE_INACTIVE)
  572. *enabled += delta;
  573. *running = event->total_time_running;
  574. if (state >= PERF_EVENT_STATE_ACTIVE)
  575. *running += delta;
  576. }
  577. static void perf_event_update_time(struct perf_event *event)
  578. {
  579. u64 now = perf_event_time(event);
  580. __perf_update_times(event, now, &event->total_time_enabled,
  581. &event->total_time_running);
  582. event->tstamp = now;
  583. }
  584. static void perf_event_update_sibling_time(struct perf_event *leader)
  585. {
  586. struct perf_event *sibling;
  587. for_each_sibling_event(sibling, leader)
  588. perf_event_update_time(sibling);
  589. }
  590. static void
  591. perf_event_set_state(struct perf_event *event, enum perf_event_state state)
  592. {
  593. if (event->state == state)
  594. return;
  595. perf_event_update_time(event);
  596. /*
  597. * If a group leader gets enabled/disabled all its siblings
  598. * are affected too.
  599. */
  600. if ((event->state < 0) ^ (state < 0))
  601. perf_event_update_sibling_time(event);
  602. WRITE_ONCE(event->state, state);
  603. }
  604. /*
  605. * UP store-release, load-acquire
  606. */
  607. #define __store_release(ptr, val) \
  608. do { \
  609. barrier(); \
  610. WRITE_ONCE(*(ptr), (val)); \
  611. } while (0)
  612. #define __load_acquire(ptr) \
  613. ({ \
  614. __unqual_scalar_typeof(*(ptr)) ___p = READ_ONCE(*(ptr)); \
  615. barrier(); \
  616. ___p; \
  617. })
  618. #define for_each_epc(_epc, _ctx, _pmu, _cgroup) \
  619. list_for_each_entry(_epc, &((_ctx)->pmu_ctx_list), pmu_ctx_entry) \
  620. if (_cgroup && !_epc->nr_cgroups) \
  621. continue; \
  622. else if (_pmu && _epc->pmu != _pmu) \
  623. continue; \
  624. else
  625. static void perf_ctx_disable(struct perf_event_context *ctx, bool cgroup)
  626. {
  627. struct perf_event_pmu_context *pmu_ctx;
  628. for_each_epc(pmu_ctx, ctx, NULL, cgroup)
  629. perf_pmu_disable(pmu_ctx->pmu);
  630. }
  631. static void perf_ctx_enable(struct perf_event_context *ctx, bool cgroup)
  632. {
  633. struct perf_event_pmu_context *pmu_ctx;
  634. for_each_epc(pmu_ctx, ctx, NULL, cgroup)
  635. perf_pmu_enable(pmu_ctx->pmu);
  636. }
  637. static void ctx_sched_out(struct perf_event_context *ctx, struct pmu *pmu, enum event_type_t event_type);
  638. static void ctx_sched_in(struct perf_event_context *ctx, struct pmu *pmu, enum event_type_t event_type);
  639. #ifdef CONFIG_CGROUP_PERF
  640. static inline bool
  641. perf_cgroup_match(struct perf_event *event)
  642. {
  643. struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
  644. /* @event doesn't care about cgroup */
  645. if (!event->cgrp)
  646. return true;
  647. /* wants specific cgroup scope but @cpuctx isn't associated with any */
  648. if (!cpuctx->cgrp)
  649. return false;
  650. /*
  651. * Cgroup scoping is recursive. An event enabled for a cgroup is
  652. * also enabled for all its descendant cgroups. If @cpuctx's
  653. * cgroup is a descendant of @event's (the test covers identity
  654. * case), it's a match.
  655. */
  656. return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
  657. event->cgrp->css.cgroup);
  658. }
  659. static inline void perf_detach_cgroup(struct perf_event *event)
  660. {
  661. css_put(&event->cgrp->css);
  662. event->cgrp = NULL;
  663. }
  664. static inline int is_cgroup_event(struct perf_event *event)
  665. {
  666. return event->cgrp != NULL;
  667. }
  668. static inline u64 perf_cgroup_event_time(struct perf_event *event)
  669. {
  670. struct perf_cgroup_info *t;
  671. t = per_cpu_ptr(event->cgrp->info, event->cpu);
  672. return t->time;
  673. }
  674. static inline u64 perf_cgroup_event_time_now(struct perf_event *event, u64 now)
  675. {
  676. struct perf_cgroup_info *t;
  677. t = per_cpu_ptr(event->cgrp->info, event->cpu);
  678. if (!__load_acquire(&t->active))
  679. return t->time;
  680. now += READ_ONCE(t->timeoffset);
  681. return now;
  682. }
  683. static inline void __update_cgrp_time(struct perf_cgroup_info *info, u64 now, bool adv)
  684. {
  685. if (adv)
  686. info->time += now - info->timestamp;
  687. info->timestamp = now;
  688. /*
  689. * see update_context_time()
  690. */
  691. WRITE_ONCE(info->timeoffset, info->time - info->timestamp);
  692. }
  693. static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx, bool final)
  694. {
  695. struct perf_cgroup *cgrp = cpuctx->cgrp;
  696. struct cgroup_subsys_state *css;
  697. struct perf_cgroup_info *info;
  698. if (cgrp) {
  699. u64 now = perf_clock();
  700. for (css = &cgrp->css; css; css = css->parent) {
  701. cgrp = container_of(css, struct perf_cgroup, css);
  702. info = this_cpu_ptr(cgrp->info);
  703. __update_cgrp_time(info, now, true);
  704. if (final)
  705. __store_release(&info->active, 0);
  706. }
  707. }
  708. }
  709. static inline void update_cgrp_time_from_event(struct perf_event *event)
  710. {
  711. struct perf_cgroup_info *info;
  712. /*
  713. * ensure we access cgroup data only when needed and
  714. * when we know the cgroup is pinned (css_get)
  715. */
  716. if (!is_cgroup_event(event))
  717. return;
  718. info = this_cpu_ptr(event->cgrp->info);
  719. /*
  720. * Do not update time when cgroup is not active
  721. */
  722. if (info->active)
  723. __update_cgrp_time(info, perf_clock(), true);
  724. }
  725. static inline void
  726. perf_cgroup_set_timestamp(struct perf_cpu_context *cpuctx)
  727. {
  728. struct perf_event_context *ctx = &cpuctx->ctx;
  729. struct perf_cgroup *cgrp = cpuctx->cgrp;
  730. struct perf_cgroup_info *info;
  731. struct cgroup_subsys_state *css;
  732. /*
  733. * ctx->lock held by caller
  734. * ensure we do not access cgroup data
  735. * unless we have the cgroup pinned (css_get)
  736. */
  737. if (!cgrp)
  738. return;
  739. WARN_ON_ONCE(!ctx->nr_cgroups);
  740. for (css = &cgrp->css; css; css = css->parent) {
  741. cgrp = container_of(css, struct perf_cgroup, css);
  742. info = this_cpu_ptr(cgrp->info);
  743. __update_cgrp_time(info, ctx->timestamp, false);
  744. __store_release(&info->active, 1);
  745. }
  746. }
  747. /*
  748. * reschedule events based on the cgroup constraint of task.
  749. */
  750. static void perf_cgroup_switch(struct task_struct *task)
  751. {
  752. struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
  753. struct perf_cgroup *cgrp;
  754. /*
  755. * cpuctx->cgrp is set when the first cgroup event enabled,
  756. * and is cleared when the last cgroup event disabled.
  757. */
  758. if (READ_ONCE(cpuctx->cgrp) == NULL)
  759. return;
  760. cgrp = perf_cgroup_from_task(task, NULL);
  761. if (READ_ONCE(cpuctx->cgrp) == cgrp)
  762. return;
  763. guard(perf_ctx_lock)(cpuctx, cpuctx->task_ctx);
  764. /*
  765. * Re-check, could've raced vs perf_remove_from_context().
  766. */
  767. if (READ_ONCE(cpuctx->cgrp) == NULL)
  768. return;
  769. WARN_ON_ONCE(cpuctx->ctx.nr_cgroups == 0);
  770. perf_ctx_disable(&cpuctx->ctx, true);
  771. ctx_sched_out(&cpuctx->ctx, NULL, EVENT_ALL|EVENT_CGROUP);
  772. /*
  773. * must not be done before ctxswout due
  774. * to update_cgrp_time_from_cpuctx() in
  775. * ctx_sched_out()
  776. */
  777. cpuctx->cgrp = cgrp;
  778. /*
  779. * set cgrp before ctxsw in to allow
  780. * perf_cgroup_set_timestamp() in ctx_sched_in()
  781. * to not have to pass task around
  782. */
  783. ctx_sched_in(&cpuctx->ctx, NULL, EVENT_ALL|EVENT_CGROUP);
  784. perf_ctx_enable(&cpuctx->ctx, true);
  785. }
  786. static int perf_cgroup_ensure_storage(struct perf_event *event,
  787. struct cgroup_subsys_state *css)
  788. {
  789. struct perf_cpu_context *cpuctx;
  790. struct perf_event **storage;
  791. int cpu, heap_size, ret = 0;
  792. /*
  793. * Allow storage to have sufficient space for an iterator for each
  794. * possibly nested cgroup plus an iterator for events with no cgroup.
  795. */
  796. for (heap_size = 1; css; css = css->parent)
  797. heap_size++;
  798. for_each_possible_cpu(cpu) {
  799. cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
  800. if (heap_size <= cpuctx->heap_size)
  801. continue;
  802. storage = kmalloc_node(heap_size * sizeof(struct perf_event *),
  803. GFP_KERNEL, cpu_to_node(cpu));
  804. if (!storage) {
  805. ret = -ENOMEM;
  806. break;
  807. }
  808. raw_spin_lock_irq(&cpuctx->ctx.lock);
  809. if (cpuctx->heap_size < heap_size) {
  810. swap(cpuctx->heap, storage);
  811. if (storage == cpuctx->heap_default)
  812. storage = NULL;
  813. cpuctx->heap_size = heap_size;
  814. }
  815. raw_spin_unlock_irq(&cpuctx->ctx.lock);
  816. kfree(storage);
  817. }
  818. return ret;
  819. }
  820. static inline int perf_cgroup_connect(int fd, struct perf_event *event,
  821. struct perf_event_attr *attr,
  822. struct perf_event *group_leader)
  823. {
  824. struct perf_cgroup *cgrp;
  825. struct cgroup_subsys_state *css;
  826. struct fd f = fdget(fd);
  827. int ret = 0;
  828. if (!fd_file(f))
  829. return -EBADF;
  830. css = css_tryget_online_from_dir(fd_file(f)->f_path.dentry,
  831. &perf_event_cgrp_subsys);
  832. if (IS_ERR(css)) {
  833. ret = PTR_ERR(css);
  834. goto out;
  835. }
  836. ret = perf_cgroup_ensure_storage(event, css);
  837. if (ret)
  838. goto out;
  839. cgrp = container_of(css, struct perf_cgroup, css);
  840. event->cgrp = cgrp;
  841. /*
  842. * all events in a group must monitor
  843. * the same cgroup because a task belongs
  844. * to only one perf cgroup at a time
  845. */
  846. if (group_leader && group_leader->cgrp != cgrp) {
  847. perf_detach_cgroup(event);
  848. ret = -EINVAL;
  849. }
  850. out:
  851. fdput(f);
  852. return ret;
  853. }
  854. static inline void
  855. perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
  856. {
  857. struct perf_cpu_context *cpuctx;
  858. if (!is_cgroup_event(event))
  859. return;
  860. event->pmu_ctx->nr_cgroups++;
  861. /*
  862. * Because cgroup events are always per-cpu events,
  863. * @ctx == &cpuctx->ctx.
  864. */
  865. cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
  866. if (ctx->nr_cgroups++)
  867. return;
  868. cpuctx->cgrp = perf_cgroup_from_task(current, ctx);
  869. }
  870. static inline void
  871. perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
  872. {
  873. struct perf_cpu_context *cpuctx;
  874. if (!is_cgroup_event(event))
  875. return;
  876. event->pmu_ctx->nr_cgroups--;
  877. /*
  878. * Because cgroup events are always per-cpu events,
  879. * @ctx == &cpuctx->ctx.
  880. */
  881. cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
  882. if (--ctx->nr_cgroups)
  883. return;
  884. cpuctx->cgrp = NULL;
  885. }
  886. #else /* !CONFIG_CGROUP_PERF */
  887. static inline bool
  888. perf_cgroup_match(struct perf_event *event)
  889. {
  890. return true;
  891. }
  892. static inline void perf_detach_cgroup(struct perf_event *event)
  893. {}
  894. static inline int is_cgroup_event(struct perf_event *event)
  895. {
  896. return 0;
  897. }
  898. static inline void update_cgrp_time_from_event(struct perf_event *event)
  899. {
  900. }
  901. static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx,
  902. bool final)
  903. {
  904. }
  905. static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
  906. struct perf_event_attr *attr,
  907. struct perf_event *group_leader)
  908. {
  909. return -EINVAL;
  910. }
  911. static inline void
  912. perf_cgroup_set_timestamp(struct perf_cpu_context *cpuctx)
  913. {
  914. }
  915. static inline u64 perf_cgroup_event_time(struct perf_event *event)
  916. {
  917. return 0;
  918. }
  919. static inline u64 perf_cgroup_event_time_now(struct perf_event *event, u64 now)
  920. {
  921. return 0;
  922. }
  923. static inline void
  924. perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
  925. {
  926. }
  927. static inline void
  928. perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
  929. {
  930. }
  931. static void perf_cgroup_switch(struct task_struct *task)
  932. {
  933. }
  934. #endif
  935. /*
  936. * set default to be dependent on timer tick just
  937. * like original code
  938. */
  939. #define PERF_CPU_HRTIMER (1000 / HZ)
  940. /*
  941. * function must be called with interrupts disabled
  942. */
  943. static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
  944. {
  945. struct perf_cpu_pmu_context *cpc;
  946. bool rotations;
  947. lockdep_assert_irqs_disabled();
  948. cpc = container_of(hr, struct perf_cpu_pmu_context, hrtimer);
  949. rotations = perf_rotate_context(cpc);
  950. raw_spin_lock(&cpc->hrtimer_lock);
  951. if (rotations)
  952. hrtimer_forward_now(hr, cpc->hrtimer_interval);
  953. else
  954. cpc->hrtimer_active = 0;
  955. raw_spin_unlock(&cpc->hrtimer_lock);
  956. return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
  957. }
  958. static void __perf_mux_hrtimer_init(struct perf_cpu_pmu_context *cpc, int cpu)
  959. {
  960. struct hrtimer *timer = &cpc->hrtimer;
  961. struct pmu *pmu = cpc->epc.pmu;
  962. u64 interval;
  963. /*
  964. * check default is sane, if not set then force to
  965. * default interval (1/tick)
  966. */
  967. interval = pmu->hrtimer_interval_ms;
  968. if (interval < 1)
  969. interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
  970. cpc->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
  971. raw_spin_lock_init(&cpc->hrtimer_lock);
  972. hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED_HARD);
  973. timer->function = perf_mux_hrtimer_handler;
  974. }
  975. static int perf_mux_hrtimer_restart(struct perf_cpu_pmu_context *cpc)
  976. {
  977. struct hrtimer *timer = &cpc->hrtimer;
  978. unsigned long flags;
  979. raw_spin_lock_irqsave(&cpc->hrtimer_lock, flags);
  980. if (!cpc->hrtimer_active) {
  981. cpc->hrtimer_active = 1;
  982. hrtimer_forward_now(timer, cpc->hrtimer_interval);
  983. hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED_HARD);
  984. }
  985. raw_spin_unlock_irqrestore(&cpc->hrtimer_lock, flags);
  986. return 0;
  987. }
  988. static int perf_mux_hrtimer_restart_ipi(void *arg)
  989. {
  990. return perf_mux_hrtimer_restart(arg);
  991. }
  992. void perf_pmu_disable(struct pmu *pmu)
  993. {
  994. int *count = this_cpu_ptr(pmu->pmu_disable_count);
  995. if (!(*count)++)
  996. pmu->pmu_disable(pmu);
  997. }
  998. void perf_pmu_enable(struct pmu *pmu)
  999. {
  1000. int *count = this_cpu_ptr(pmu->pmu_disable_count);
  1001. if (!--(*count))
  1002. pmu->pmu_enable(pmu);
  1003. }
  1004. static void perf_assert_pmu_disabled(struct pmu *pmu)
  1005. {
  1006. WARN_ON_ONCE(*this_cpu_ptr(pmu->pmu_disable_count) == 0);
  1007. }
  1008. static inline void perf_pmu_read(struct perf_event *event)
  1009. {
  1010. if (event->state == PERF_EVENT_STATE_ACTIVE)
  1011. event->pmu->read(event);
  1012. }
  1013. static void get_ctx(struct perf_event_context *ctx)
  1014. {
  1015. refcount_inc(&ctx->refcount);
  1016. }
  1017. static void *alloc_task_ctx_data(struct pmu *pmu)
  1018. {
  1019. if (pmu->task_ctx_cache)
  1020. return kmem_cache_zalloc(pmu->task_ctx_cache, GFP_KERNEL);
  1021. return NULL;
  1022. }
  1023. static void free_task_ctx_data(struct pmu *pmu, void *task_ctx_data)
  1024. {
  1025. if (pmu->task_ctx_cache && task_ctx_data)
  1026. kmem_cache_free(pmu->task_ctx_cache, task_ctx_data);
  1027. }
  1028. static void free_ctx(struct rcu_head *head)
  1029. {
  1030. struct perf_event_context *ctx;
  1031. ctx = container_of(head, struct perf_event_context, rcu_head);
  1032. kfree(ctx);
  1033. }
  1034. static void put_ctx(struct perf_event_context *ctx)
  1035. {
  1036. if (refcount_dec_and_test(&ctx->refcount)) {
  1037. if (ctx->parent_ctx)
  1038. put_ctx(ctx->parent_ctx);
  1039. if (ctx->task && ctx->task != TASK_TOMBSTONE)
  1040. put_task_struct(ctx->task);
  1041. call_rcu(&ctx->rcu_head, free_ctx);
  1042. }
  1043. }
  1044. /*
  1045. * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
  1046. * perf_pmu_migrate_context() we need some magic.
  1047. *
  1048. * Those places that change perf_event::ctx will hold both
  1049. * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
  1050. *
  1051. * Lock ordering is by mutex address. There are two other sites where
  1052. * perf_event_context::mutex nests and those are:
  1053. *
  1054. * - perf_event_exit_task_context() [ child , 0 ]
  1055. * perf_event_exit_event()
  1056. * put_event() [ parent, 1 ]
  1057. *
  1058. * - perf_event_init_context() [ parent, 0 ]
  1059. * inherit_task_group()
  1060. * inherit_group()
  1061. * inherit_event()
  1062. * perf_event_alloc()
  1063. * perf_init_event()
  1064. * perf_try_init_event() [ child , 1 ]
  1065. *
  1066. * While it appears there is an obvious deadlock here -- the parent and child
  1067. * nesting levels are inverted between the two. This is in fact safe because
  1068. * life-time rules separate them. That is an exiting task cannot fork, and a
  1069. * spawning task cannot (yet) exit.
  1070. *
  1071. * But remember that these are parent<->child context relations, and
  1072. * migration does not affect children, therefore these two orderings should not
  1073. * interact.
  1074. *
  1075. * The change in perf_event::ctx does not affect children (as claimed above)
  1076. * because the sys_perf_event_open() case will install a new event and break
  1077. * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
  1078. * concerned with cpuctx and that doesn't have children.
  1079. *
  1080. * The places that change perf_event::ctx will issue:
  1081. *
  1082. * perf_remove_from_context();
  1083. * synchronize_rcu();
  1084. * perf_install_in_context();
  1085. *
  1086. * to affect the change. The remove_from_context() + synchronize_rcu() should
  1087. * quiesce the event, after which we can install it in the new location. This
  1088. * means that only external vectors (perf_fops, prctl) can perturb the event
  1089. * while in transit. Therefore all such accessors should also acquire
  1090. * perf_event_context::mutex to serialize against this.
  1091. *
  1092. * However; because event->ctx can change while we're waiting to acquire
  1093. * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
  1094. * function.
  1095. *
  1096. * Lock order:
  1097. * exec_update_lock
  1098. * task_struct::perf_event_mutex
  1099. * perf_event_context::mutex
  1100. * perf_event::child_mutex;
  1101. * perf_event_context::lock
  1102. * mmap_lock
  1103. * perf_event::mmap_mutex
  1104. * perf_buffer::aux_mutex
  1105. * perf_addr_filters_head::lock
  1106. *
  1107. * cpu_hotplug_lock
  1108. * pmus_lock
  1109. * cpuctx->mutex / perf_event_context::mutex
  1110. */
  1111. static struct perf_event_context *
  1112. perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
  1113. {
  1114. struct perf_event_context *ctx;
  1115. again:
  1116. rcu_read_lock();
  1117. ctx = READ_ONCE(event->ctx);
  1118. if (!refcount_inc_not_zero(&ctx->refcount)) {
  1119. rcu_read_unlock();
  1120. goto again;
  1121. }
  1122. rcu_read_unlock();
  1123. mutex_lock_nested(&ctx->mutex, nesting);
  1124. if (event->ctx != ctx) {
  1125. mutex_unlock(&ctx->mutex);
  1126. put_ctx(ctx);
  1127. goto again;
  1128. }
  1129. return ctx;
  1130. }
  1131. static inline struct perf_event_context *
  1132. perf_event_ctx_lock(struct perf_event *event)
  1133. {
  1134. return perf_event_ctx_lock_nested(event, 0);
  1135. }
  1136. static void perf_event_ctx_unlock(struct perf_event *event,
  1137. struct perf_event_context *ctx)
  1138. {
  1139. mutex_unlock(&ctx->mutex);
  1140. put_ctx(ctx);
  1141. }
  1142. /*
  1143. * This must be done under the ctx->lock, such as to serialize against
  1144. * context_equiv(), therefore we cannot call put_ctx() since that might end up
  1145. * calling scheduler related locks and ctx->lock nests inside those.
  1146. */
  1147. static __must_check struct perf_event_context *
  1148. unclone_ctx(struct perf_event_context *ctx)
  1149. {
  1150. struct perf_event_context *parent_ctx = ctx->parent_ctx;
  1151. lockdep_assert_held(&ctx->lock);
  1152. if (parent_ctx)
  1153. ctx->parent_ctx = NULL;
  1154. ctx->generation++;
  1155. return parent_ctx;
  1156. }
  1157. static u32 perf_event_pid_type(struct perf_event *event, struct task_struct *p,
  1158. enum pid_type type)
  1159. {
  1160. u32 nr;
  1161. /*
  1162. * only top level events have the pid namespace they were created in
  1163. */
  1164. if (event->parent)
  1165. event = event->parent;
  1166. nr = __task_pid_nr_ns(p, type, event->ns);
  1167. /* avoid -1 if it is idle thread or runs in another ns */
  1168. if (!nr && !pid_alive(p))
  1169. nr = -1;
  1170. return nr;
  1171. }
  1172. static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
  1173. {
  1174. return perf_event_pid_type(event, p, PIDTYPE_TGID);
  1175. }
  1176. static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
  1177. {
  1178. return perf_event_pid_type(event, p, PIDTYPE_PID);
  1179. }
  1180. /*
  1181. * If we inherit events we want to return the parent event id
  1182. * to userspace.
  1183. */
  1184. static u64 primary_event_id(struct perf_event *event)
  1185. {
  1186. u64 id = event->id;
  1187. if (event->parent)
  1188. id = event->parent->id;
  1189. return id;
  1190. }
  1191. /*
  1192. * Get the perf_event_context for a task and lock it.
  1193. *
  1194. * This has to cope with the fact that until it is locked,
  1195. * the context could get moved to another task.
  1196. */
  1197. static struct perf_event_context *
  1198. perf_lock_task_context(struct task_struct *task, unsigned long *flags)
  1199. {
  1200. struct perf_event_context *ctx;
  1201. retry:
  1202. /*
  1203. * One of the few rules of preemptible RCU is that one cannot do
  1204. * rcu_read_unlock() while holding a scheduler (or nested) lock when
  1205. * part of the read side critical section was irqs-enabled -- see
  1206. * rcu_read_unlock_special().
  1207. *
  1208. * Since ctx->lock nests under rq->lock we must ensure the entire read
  1209. * side critical section has interrupts disabled.
  1210. */
  1211. local_irq_save(*flags);
  1212. rcu_read_lock();
  1213. ctx = rcu_dereference(task->perf_event_ctxp);
  1214. if (ctx) {
  1215. /*
  1216. * If this context is a clone of another, it might
  1217. * get swapped for another underneath us by
  1218. * perf_event_task_sched_out, though the
  1219. * rcu_read_lock() protects us from any context
  1220. * getting freed. Lock the context and check if it
  1221. * got swapped before we could get the lock, and retry
  1222. * if so. If we locked the right context, then it
  1223. * can't get swapped on us any more.
  1224. */
  1225. raw_spin_lock(&ctx->lock);
  1226. if (ctx != rcu_dereference(task->perf_event_ctxp)) {
  1227. raw_spin_unlock(&ctx->lock);
  1228. rcu_read_unlock();
  1229. local_irq_restore(*flags);
  1230. goto retry;
  1231. }
  1232. if (ctx->task == TASK_TOMBSTONE ||
  1233. !refcount_inc_not_zero(&ctx->refcount)) {
  1234. raw_spin_unlock(&ctx->lock);
  1235. ctx = NULL;
  1236. } else {
  1237. WARN_ON_ONCE(ctx->task != task);
  1238. }
  1239. }
  1240. rcu_read_unlock();
  1241. if (!ctx)
  1242. local_irq_restore(*flags);
  1243. return ctx;
  1244. }
  1245. /*
  1246. * Get the context for a task and increment its pin_count so it
  1247. * can't get swapped to another task. This also increments its
  1248. * reference count so that the context can't get freed.
  1249. */
  1250. static struct perf_event_context *
  1251. perf_pin_task_context(struct task_struct *task)
  1252. {
  1253. struct perf_event_context *ctx;
  1254. unsigned long flags;
  1255. ctx = perf_lock_task_context(task, &flags);
  1256. if (ctx) {
  1257. ++ctx->pin_count;
  1258. raw_spin_unlock_irqrestore(&ctx->lock, flags);
  1259. }
  1260. return ctx;
  1261. }
  1262. static void perf_unpin_context(struct perf_event_context *ctx)
  1263. {
  1264. unsigned long flags;
  1265. raw_spin_lock_irqsave(&ctx->lock, flags);
  1266. --ctx->pin_count;
  1267. raw_spin_unlock_irqrestore(&ctx->lock, flags);
  1268. }
  1269. /*
  1270. * Update the record of the current time in a context.
  1271. */
  1272. static void __update_context_time(struct perf_event_context *ctx, bool adv)
  1273. {
  1274. u64 now = perf_clock();
  1275. lockdep_assert_held(&ctx->lock);
  1276. if (adv)
  1277. ctx->time += now - ctx->timestamp;
  1278. ctx->timestamp = now;
  1279. /*
  1280. * The above: time' = time + (now - timestamp), can be re-arranged
  1281. * into: time` = now + (time - timestamp), which gives a single value
  1282. * offset to compute future time without locks on.
  1283. *
  1284. * See perf_event_time_now(), which can be used from NMI context where
  1285. * it's (obviously) not possible to acquire ctx->lock in order to read
  1286. * both the above values in a consistent manner.
  1287. */
  1288. WRITE_ONCE(ctx->timeoffset, ctx->time - ctx->timestamp);
  1289. }
  1290. static void update_context_time(struct perf_event_context *ctx)
  1291. {
  1292. __update_context_time(ctx, true);
  1293. }
  1294. static u64 perf_event_time(struct perf_event *event)
  1295. {
  1296. struct perf_event_context *ctx = event->ctx;
  1297. if (unlikely(!ctx))
  1298. return 0;
  1299. if (is_cgroup_event(event))
  1300. return perf_cgroup_event_time(event);
  1301. return ctx->time;
  1302. }
  1303. static u64 perf_event_time_now(struct perf_event *event, u64 now)
  1304. {
  1305. struct perf_event_context *ctx = event->ctx;
  1306. if (unlikely(!ctx))
  1307. return 0;
  1308. if (is_cgroup_event(event))
  1309. return perf_cgroup_event_time_now(event, now);
  1310. if (!(__load_acquire(&ctx->is_active) & EVENT_TIME))
  1311. return ctx->time;
  1312. now += READ_ONCE(ctx->timeoffset);
  1313. return now;
  1314. }
  1315. static enum event_type_t get_event_type(struct perf_event *event)
  1316. {
  1317. struct perf_event_context *ctx = event->ctx;
  1318. enum event_type_t event_type;
  1319. lockdep_assert_held(&ctx->lock);
  1320. /*
  1321. * It's 'group type', really, because if our group leader is
  1322. * pinned, so are we.
  1323. */
  1324. if (event->group_leader != event)
  1325. event = event->group_leader;
  1326. event_type = event->attr.pinned ? EVENT_PINNED : EVENT_FLEXIBLE;
  1327. if (!ctx->task)
  1328. event_type |= EVENT_CPU;
  1329. return event_type;
  1330. }
  1331. /*
  1332. * Helper function to initialize event group nodes.
  1333. */
  1334. static void init_event_group(struct perf_event *event)
  1335. {
  1336. RB_CLEAR_NODE(&event->group_node);
  1337. event->group_index = 0;
  1338. }
  1339. /*
  1340. * Extract pinned or flexible groups from the context
  1341. * based on event attrs bits.
  1342. */
  1343. static struct perf_event_groups *
  1344. get_event_groups(struct perf_event *event, struct perf_event_context *ctx)
  1345. {
  1346. if (event->attr.pinned)
  1347. return &ctx->pinned_groups;
  1348. else
  1349. return &ctx->flexible_groups;
  1350. }
  1351. /*
  1352. * Helper function to initializes perf_event_group trees.
  1353. */
  1354. static void perf_event_groups_init(struct perf_event_groups *groups)
  1355. {
  1356. groups->tree = RB_ROOT;
  1357. groups->index = 0;
  1358. }
  1359. static inline struct cgroup *event_cgroup(const struct perf_event *event)
  1360. {
  1361. struct cgroup *cgroup = NULL;
  1362. #ifdef CONFIG_CGROUP_PERF
  1363. if (event->cgrp)
  1364. cgroup = event->cgrp->css.cgroup;
  1365. #endif
  1366. return cgroup;
  1367. }
  1368. /*
  1369. * Compare function for event groups;
  1370. *
  1371. * Implements complex key that first sorts by CPU and then by virtual index
  1372. * which provides ordering when rotating groups for the same CPU.
  1373. */
  1374. static __always_inline int
  1375. perf_event_groups_cmp(const int left_cpu, const struct pmu *left_pmu,
  1376. const struct cgroup *left_cgroup, const u64 left_group_index,
  1377. const struct perf_event *right)
  1378. {
  1379. if (left_cpu < right->cpu)
  1380. return -1;
  1381. if (left_cpu > right->cpu)
  1382. return 1;
  1383. if (left_pmu) {
  1384. if (left_pmu < right->pmu_ctx->pmu)
  1385. return -1;
  1386. if (left_pmu > right->pmu_ctx->pmu)
  1387. return 1;
  1388. }
  1389. #ifdef CONFIG_CGROUP_PERF
  1390. {
  1391. const struct cgroup *right_cgroup = event_cgroup(right);
  1392. if (left_cgroup != right_cgroup) {
  1393. if (!left_cgroup) {
  1394. /*
  1395. * Left has no cgroup but right does, no
  1396. * cgroups come first.
  1397. */
  1398. return -1;
  1399. }
  1400. if (!right_cgroup) {
  1401. /*
  1402. * Right has no cgroup but left does, no
  1403. * cgroups come first.
  1404. */
  1405. return 1;
  1406. }
  1407. /* Two dissimilar cgroups, order by id. */
  1408. if (cgroup_id(left_cgroup) < cgroup_id(right_cgroup))
  1409. return -1;
  1410. return 1;
  1411. }
  1412. }
  1413. #endif
  1414. if (left_group_index < right->group_index)
  1415. return -1;
  1416. if (left_group_index > right->group_index)
  1417. return 1;
  1418. return 0;
  1419. }
  1420. #define __node_2_pe(node) \
  1421. rb_entry((node), struct perf_event, group_node)
  1422. static inline bool __group_less(struct rb_node *a, const struct rb_node *b)
  1423. {
  1424. struct perf_event *e = __node_2_pe(a);
  1425. return perf_event_groups_cmp(e->cpu, e->pmu_ctx->pmu, event_cgroup(e),
  1426. e->group_index, __node_2_pe(b)) < 0;
  1427. }
  1428. struct __group_key {
  1429. int cpu;
  1430. struct pmu *pmu;
  1431. struct cgroup *cgroup;
  1432. };
  1433. static inline int __group_cmp(const void *key, const struct rb_node *node)
  1434. {
  1435. const struct __group_key *a = key;
  1436. const struct perf_event *b = __node_2_pe(node);
  1437. /* partial/subtree match: @cpu, @pmu, @cgroup; ignore: @group_index */
  1438. return perf_event_groups_cmp(a->cpu, a->pmu, a->cgroup, b->group_index, b);
  1439. }
  1440. static inline int
  1441. __group_cmp_ignore_cgroup(const void *key, const struct rb_node *node)
  1442. {
  1443. const struct __group_key *a = key;
  1444. const struct perf_event *b = __node_2_pe(node);
  1445. /* partial/subtree match: @cpu, @pmu, ignore: @cgroup, @group_index */
  1446. return perf_event_groups_cmp(a->cpu, a->pmu, event_cgroup(b),
  1447. b->group_index, b);
  1448. }
  1449. /*
  1450. * Insert @event into @groups' tree; using
  1451. * {@event->cpu, @event->pmu_ctx->pmu, event_cgroup(@event), ++@groups->index}
  1452. * as key. This places it last inside the {cpu,pmu,cgroup} subtree.
  1453. */
  1454. static void
  1455. perf_event_groups_insert(struct perf_event_groups *groups,
  1456. struct perf_event *event)
  1457. {
  1458. event->group_index = ++groups->index;
  1459. rb_add(&event->group_node, &groups->tree, __group_less);
  1460. }
  1461. /*
  1462. * Helper function to insert event into the pinned or flexible groups.
  1463. */
  1464. static void
  1465. add_event_to_groups(struct perf_event *event, struct perf_event_context *ctx)
  1466. {
  1467. struct perf_event_groups *groups;
  1468. groups = get_event_groups(event, ctx);
  1469. perf_event_groups_insert(groups, event);
  1470. }
  1471. /*
  1472. * Delete a group from a tree.
  1473. */
  1474. static void
  1475. perf_event_groups_delete(struct perf_event_groups *groups,
  1476. struct perf_event *event)
  1477. {
  1478. WARN_ON_ONCE(RB_EMPTY_NODE(&event->group_node) ||
  1479. RB_EMPTY_ROOT(&groups->tree));
  1480. rb_erase(&event->group_node, &groups->tree);
  1481. init_event_group(event);
  1482. }
  1483. /*
  1484. * Helper function to delete event from its groups.
  1485. */
  1486. static void
  1487. del_event_from_groups(struct perf_event *event, struct perf_event_context *ctx)
  1488. {
  1489. struct perf_event_groups *groups;
  1490. groups = get_event_groups(event, ctx);
  1491. perf_event_groups_delete(groups, event);
  1492. }
  1493. /*
  1494. * Get the leftmost event in the {cpu,pmu,cgroup} subtree.
  1495. */
  1496. static struct perf_event *
  1497. perf_event_groups_first(struct perf_event_groups *groups, int cpu,
  1498. struct pmu *pmu, struct cgroup *cgrp)
  1499. {
  1500. struct __group_key key = {
  1501. .cpu = cpu,
  1502. .pmu = pmu,
  1503. .cgroup = cgrp,
  1504. };
  1505. struct rb_node *node;
  1506. node = rb_find_first(&key, &groups->tree, __group_cmp);
  1507. if (node)
  1508. return __node_2_pe(node);
  1509. return NULL;
  1510. }
  1511. static struct perf_event *
  1512. perf_event_groups_next(struct perf_event *event, struct pmu *pmu)
  1513. {
  1514. struct __group_key key = {
  1515. .cpu = event->cpu,
  1516. .pmu = pmu,
  1517. .cgroup = event_cgroup(event),
  1518. };
  1519. struct rb_node *next;
  1520. next = rb_next_match(&key, &event->group_node, __group_cmp);
  1521. if (next)
  1522. return __node_2_pe(next);
  1523. return NULL;
  1524. }
  1525. #define perf_event_groups_for_cpu_pmu(event, groups, cpu, pmu) \
  1526. for (event = perf_event_groups_first(groups, cpu, pmu, NULL); \
  1527. event; event = perf_event_groups_next(event, pmu))
  1528. /*
  1529. * Iterate through the whole groups tree.
  1530. */
  1531. #define perf_event_groups_for_each(event, groups) \
  1532. for (event = rb_entry_safe(rb_first(&((groups)->tree)), \
  1533. typeof(*event), group_node); event; \
  1534. event = rb_entry_safe(rb_next(&event->group_node), \
  1535. typeof(*event), group_node))
  1536. /*
  1537. * Does the event attribute request inherit with PERF_SAMPLE_READ
  1538. */
  1539. static inline bool has_inherit_and_sample_read(struct perf_event_attr *attr)
  1540. {
  1541. return attr->inherit && (attr->sample_type & PERF_SAMPLE_READ);
  1542. }
  1543. /*
  1544. * Add an event from the lists for its context.
  1545. * Must be called with ctx->mutex and ctx->lock held.
  1546. */
  1547. static void
  1548. list_add_event(struct perf_event *event, struct perf_event_context *ctx)
  1549. {
  1550. lockdep_assert_held(&ctx->lock);
  1551. WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
  1552. event->attach_state |= PERF_ATTACH_CONTEXT;
  1553. event->tstamp = perf_event_time(event);
  1554. /*
  1555. * If we're a stand alone event or group leader, we go to the context
  1556. * list, group events are kept attached to the group so that
  1557. * perf_group_detach can, at all times, locate all siblings.
  1558. */
  1559. if (event->group_leader == event) {
  1560. event->group_caps = event->event_caps;
  1561. add_event_to_groups(event, ctx);
  1562. }
  1563. list_add_rcu(&event->event_entry, &ctx->event_list);
  1564. ctx->nr_events++;
  1565. if (event->hw.flags & PERF_EVENT_FLAG_USER_READ_CNT)
  1566. ctx->nr_user++;
  1567. if (event->attr.inherit_stat)
  1568. ctx->nr_stat++;
  1569. if (has_inherit_and_sample_read(&event->attr))
  1570. local_inc(&ctx->nr_no_switch_fast);
  1571. if (event->state > PERF_EVENT_STATE_OFF)
  1572. perf_cgroup_event_enable(event, ctx);
  1573. ctx->generation++;
  1574. event->pmu_ctx->nr_events++;
  1575. }
  1576. /*
  1577. * Initialize event state based on the perf_event_attr::disabled.
  1578. */
  1579. static inline void perf_event__state_init(struct perf_event *event)
  1580. {
  1581. event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
  1582. PERF_EVENT_STATE_INACTIVE;
  1583. }
  1584. static int __perf_event_read_size(u64 read_format, int nr_siblings)
  1585. {
  1586. int entry = sizeof(u64); /* value */
  1587. int size = 0;
  1588. int nr = 1;
  1589. if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
  1590. size += sizeof(u64);
  1591. if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
  1592. size += sizeof(u64);
  1593. if (read_format & PERF_FORMAT_ID)
  1594. entry += sizeof(u64);
  1595. if (read_format & PERF_FORMAT_LOST)
  1596. entry += sizeof(u64);
  1597. if (read_format & PERF_FORMAT_GROUP) {
  1598. nr += nr_siblings;
  1599. size += sizeof(u64);
  1600. }
  1601. /*
  1602. * Since perf_event_validate_size() limits this to 16k and inhibits
  1603. * adding more siblings, this will never overflow.
  1604. */
  1605. return size + nr * entry;
  1606. }
  1607. static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
  1608. {
  1609. struct perf_sample_data *data;
  1610. u16 size = 0;
  1611. if (sample_type & PERF_SAMPLE_IP)
  1612. size += sizeof(data->ip);
  1613. if (sample_type & PERF_SAMPLE_ADDR)
  1614. size += sizeof(data->addr);
  1615. if (sample_type & PERF_SAMPLE_PERIOD)
  1616. size += sizeof(data->period);
  1617. if (sample_type & PERF_SAMPLE_WEIGHT_TYPE)
  1618. size += sizeof(data->weight.full);
  1619. if (sample_type & PERF_SAMPLE_READ)
  1620. size += event->read_size;
  1621. if (sample_type & PERF_SAMPLE_DATA_SRC)
  1622. size += sizeof(data->data_src.val);
  1623. if (sample_type & PERF_SAMPLE_TRANSACTION)
  1624. size += sizeof(data->txn);
  1625. if (sample_type & PERF_SAMPLE_PHYS_ADDR)
  1626. size += sizeof(data->phys_addr);
  1627. if (sample_type & PERF_SAMPLE_CGROUP)
  1628. size += sizeof(data->cgroup);
  1629. if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
  1630. size += sizeof(data->data_page_size);
  1631. if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
  1632. size += sizeof(data->code_page_size);
  1633. event->header_size = size;
  1634. }
  1635. /*
  1636. * Called at perf_event creation and when events are attached/detached from a
  1637. * group.
  1638. */
  1639. static void perf_event__header_size(struct perf_event *event)
  1640. {
  1641. event->read_size =
  1642. __perf_event_read_size(event->attr.read_format,
  1643. event->group_leader->nr_siblings);
  1644. __perf_event_header_size(event, event->attr.sample_type);
  1645. }
  1646. static void perf_event__id_header_size(struct perf_event *event)
  1647. {
  1648. struct perf_sample_data *data;
  1649. u64 sample_type = event->attr.sample_type;
  1650. u16 size = 0;
  1651. if (sample_type & PERF_SAMPLE_TID)
  1652. size += sizeof(data->tid_entry);
  1653. if (sample_type & PERF_SAMPLE_TIME)
  1654. size += sizeof(data->time);
  1655. if (sample_type & PERF_SAMPLE_IDENTIFIER)
  1656. size += sizeof(data->id);
  1657. if (sample_type & PERF_SAMPLE_ID)
  1658. size += sizeof(data->id);
  1659. if (sample_type & PERF_SAMPLE_STREAM_ID)
  1660. size += sizeof(data->stream_id);
  1661. if (sample_type & PERF_SAMPLE_CPU)
  1662. size += sizeof(data->cpu_entry);
  1663. event->id_header_size = size;
  1664. }
  1665. /*
  1666. * Check that adding an event to the group does not result in anybody
  1667. * overflowing the 64k event limit imposed by the output buffer.
  1668. *
  1669. * Specifically, check that the read_size for the event does not exceed 16k,
  1670. * read_size being the one term that grows with groups size. Since read_size
  1671. * depends on per-event read_format, also (re)check the existing events.
  1672. *
  1673. * This leaves 48k for the constant size fields and things like callchains,
  1674. * branch stacks and register sets.
  1675. */
  1676. static bool perf_event_validate_size(struct perf_event *event)
  1677. {
  1678. struct perf_event *sibling, *group_leader = event->group_leader;
  1679. if (__perf_event_read_size(event->attr.read_format,
  1680. group_leader->nr_siblings + 1) > 16*1024)
  1681. return false;
  1682. if (__perf_event_read_size(group_leader->attr.read_format,
  1683. group_leader->nr_siblings + 1) > 16*1024)
  1684. return false;
  1685. /*
  1686. * When creating a new group leader, group_leader->ctx is initialized
  1687. * after the size has been validated, but we cannot safely use
  1688. * for_each_sibling_event() until group_leader->ctx is set. A new group
  1689. * leader cannot have any siblings yet, so we can safely skip checking
  1690. * the non-existent siblings.
  1691. */
  1692. if (event == group_leader)
  1693. return true;
  1694. for_each_sibling_event(sibling, group_leader) {
  1695. if (__perf_event_read_size(sibling->attr.read_format,
  1696. group_leader->nr_siblings + 1) > 16*1024)
  1697. return false;
  1698. }
  1699. return true;
  1700. }
  1701. static void perf_group_attach(struct perf_event *event)
  1702. {
  1703. struct perf_event *group_leader = event->group_leader, *pos;
  1704. lockdep_assert_held(&event->ctx->lock);
  1705. /*
  1706. * We can have double attach due to group movement (move_group) in
  1707. * perf_event_open().
  1708. */
  1709. if (event->attach_state & PERF_ATTACH_GROUP)
  1710. return;
  1711. event->attach_state |= PERF_ATTACH_GROUP;
  1712. if (group_leader == event)
  1713. return;
  1714. WARN_ON_ONCE(group_leader->ctx != event->ctx);
  1715. group_leader->group_caps &= event->event_caps;
  1716. list_add_tail(&event->sibling_list, &group_leader->sibling_list);
  1717. group_leader->nr_siblings++;
  1718. group_leader->group_generation++;
  1719. perf_event__header_size(group_leader);
  1720. for_each_sibling_event(pos, group_leader)
  1721. perf_event__header_size(pos);
  1722. }
  1723. /*
  1724. * Remove an event from the lists for its context.
  1725. * Must be called with ctx->mutex and ctx->lock held.
  1726. */
  1727. static void
  1728. list_del_event(struct perf_event *event, struct perf_event_context *ctx)
  1729. {
  1730. WARN_ON_ONCE(event->ctx != ctx);
  1731. lockdep_assert_held(&ctx->lock);
  1732. /*
  1733. * We can have double detach due to exit/hot-unplug + close.
  1734. */
  1735. if (!(event->attach_state & PERF_ATTACH_CONTEXT))
  1736. return;
  1737. event->attach_state &= ~PERF_ATTACH_CONTEXT;
  1738. ctx->nr_events--;
  1739. if (event->hw.flags & PERF_EVENT_FLAG_USER_READ_CNT)
  1740. ctx->nr_user--;
  1741. if (event->attr.inherit_stat)
  1742. ctx->nr_stat--;
  1743. if (has_inherit_and_sample_read(&event->attr))
  1744. local_dec(&ctx->nr_no_switch_fast);
  1745. list_del_rcu(&event->event_entry);
  1746. if (event->group_leader == event)
  1747. del_event_from_groups(event, ctx);
  1748. /*
  1749. * If event was in error state, then keep it
  1750. * that way, otherwise bogus counts will be
  1751. * returned on read(). The only way to get out
  1752. * of error state is by explicit re-enabling
  1753. * of the event
  1754. */
  1755. if (event->state > PERF_EVENT_STATE_OFF) {
  1756. perf_cgroup_event_disable(event, ctx);
  1757. perf_event_set_state(event, PERF_EVENT_STATE_OFF);
  1758. }
  1759. ctx->generation++;
  1760. event->pmu_ctx->nr_events--;
  1761. }
  1762. static int
  1763. perf_aux_output_match(struct perf_event *event, struct perf_event *aux_event)
  1764. {
  1765. if (!has_aux(aux_event))
  1766. return 0;
  1767. if (!event->pmu->aux_output_match)
  1768. return 0;
  1769. return event->pmu->aux_output_match(aux_event);
  1770. }
  1771. static void put_event(struct perf_event *event);
  1772. static void __event_disable(struct perf_event *event,
  1773. struct perf_event_context *ctx,
  1774. enum perf_event_state state);
  1775. static void perf_put_aux_event(struct perf_event *event)
  1776. {
  1777. struct perf_event_context *ctx = event->ctx;
  1778. struct perf_event *iter;
  1779. /*
  1780. * If event uses aux_event tear down the link
  1781. */
  1782. if (event->aux_event) {
  1783. iter = event->aux_event;
  1784. event->aux_event = NULL;
  1785. put_event(iter);
  1786. return;
  1787. }
  1788. /*
  1789. * If the event is an aux_event, tear down all links to
  1790. * it from other events.
  1791. */
  1792. for_each_sibling_event(iter, event->group_leader) {
  1793. if (iter->aux_event != event)
  1794. continue;
  1795. iter->aux_event = NULL;
  1796. put_event(event);
  1797. /*
  1798. * If it's ACTIVE, schedule it out and put it into ERROR
  1799. * state so that we don't try to schedule it again. Note
  1800. * that perf_event_enable() will clear the ERROR status.
  1801. */
  1802. __event_disable(iter, ctx, PERF_EVENT_STATE_ERROR);
  1803. }
  1804. }
  1805. static bool perf_need_aux_event(struct perf_event *event)
  1806. {
  1807. return event->attr.aux_output || has_aux_action(event);
  1808. }
  1809. static int perf_get_aux_event(struct perf_event *event,
  1810. struct perf_event *group_leader)
  1811. {
  1812. /*
  1813. * Our group leader must be an aux event if we want to be
  1814. * an aux_output. This way, the aux event will precede its
  1815. * aux_output events in the group, and therefore will always
  1816. * schedule first.
  1817. */
  1818. if (!group_leader)
  1819. return 0;
  1820. /*
  1821. * aux_output and aux_sample_size are mutually exclusive.
  1822. */
  1823. if (event->attr.aux_output && event->attr.aux_sample_size)
  1824. return 0;
  1825. if (event->attr.aux_output &&
  1826. !perf_aux_output_match(event, group_leader))
  1827. return 0;
  1828. if ((event->attr.aux_pause || event->attr.aux_resume) &&
  1829. !(group_leader->pmu->capabilities & PERF_PMU_CAP_AUX_PAUSE))
  1830. return 0;
  1831. if (event->attr.aux_sample_size && !group_leader->pmu->snapshot_aux)
  1832. return 0;
  1833. if (!atomic_long_inc_not_zero(&group_leader->refcount))
  1834. return 0;
  1835. /*
  1836. * Link aux_outputs to their aux event; this is undone in
  1837. * perf_group_detach() by perf_put_aux_event(). When the
  1838. * group in torn down, the aux_output events loose their
  1839. * link to the aux_event and can't schedule any more.
  1840. */
  1841. event->aux_event = group_leader;
  1842. return 1;
  1843. }
  1844. static inline struct list_head *get_event_list(struct perf_event *event)
  1845. {
  1846. return event->attr.pinned ? &event->pmu_ctx->pinned_active :
  1847. &event->pmu_ctx->flexible_active;
  1848. }
  1849. static void perf_group_detach(struct perf_event *event)
  1850. {
  1851. struct perf_event *leader = event->group_leader;
  1852. struct perf_event *sibling, *tmp;
  1853. struct perf_event_context *ctx = event->ctx;
  1854. lockdep_assert_held(&ctx->lock);
  1855. /*
  1856. * We can have double detach due to exit/hot-unplug + close.
  1857. */
  1858. if (!(event->attach_state & PERF_ATTACH_GROUP))
  1859. return;
  1860. event->attach_state &= ~PERF_ATTACH_GROUP;
  1861. perf_put_aux_event(event);
  1862. /*
  1863. * If this is a sibling, remove it from its group.
  1864. */
  1865. if (leader != event) {
  1866. list_del_init(&event->sibling_list);
  1867. event->group_leader->nr_siblings--;
  1868. event->group_leader->group_generation++;
  1869. goto out;
  1870. }
  1871. /*
  1872. * If this was a group event with sibling events then
  1873. * upgrade the siblings to singleton events by adding them
  1874. * to whatever list we are on.
  1875. */
  1876. list_for_each_entry_safe(sibling, tmp, &event->sibling_list, sibling_list) {
  1877. /*
  1878. * Events that have PERF_EV_CAP_SIBLING require being part of
  1879. * a group and cannot exist on their own, schedule them out
  1880. * and move them into the ERROR state. Also see
  1881. * _perf_event_enable(), it will not be able to recover this
  1882. * ERROR state.
  1883. */
  1884. if (sibling->event_caps & PERF_EV_CAP_SIBLING)
  1885. __event_disable(sibling, ctx, PERF_EVENT_STATE_ERROR);
  1886. sibling->group_leader = sibling;
  1887. list_del_init(&sibling->sibling_list);
  1888. /* Inherit group flags from the previous leader */
  1889. sibling->group_caps = event->group_caps;
  1890. if (sibling->attach_state & PERF_ATTACH_CONTEXT) {
  1891. add_event_to_groups(sibling, event->ctx);
  1892. if (sibling->state == PERF_EVENT_STATE_ACTIVE)
  1893. list_add_tail(&sibling->active_list, get_event_list(sibling));
  1894. }
  1895. WARN_ON_ONCE(sibling->ctx != event->ctx);
  1896. }
  1897. out:
  1898. for_each_sibling_event(tmp, leader)
  1899. perf_event__header_size(tmp);
  1900. perf_event__header_size(leader);
  1901. }
  1902. static void sync_child_event(struct perf_event *child_event);
  1903. static void perf_child_detach(struct perf_event *event)
  1904. {
  1905. struct perf_event *parent_event = event->parent;
  1906. if (!(event->attach_state & PERF_ATTACH_CHILD))
  1907. return;
  1908. event->attach_state &= ~PERF_ATTACH_CHILD;
  1909. if (WARN_ON_ONCE(!parent_event))
  1910. return;
  1911. lockdep_assert_held(&parent_event->child_mutex);
  1912. sync_child_event(event);
  1913. list_del_init(&event->child_list);
  1914. }
  1915. static bool is_orphaned_event(struct perf_event *event)
  1916. {
  1917. return event->state == PERF_EVENT_STATE_DEAD;
  1918. }
  1919. static inline int
  1920. event_filter_match(struct perf_event *event)
  1921. {
  1922. return (event->cpu == -1 || event->cpu == smp_processor_id()) &&
  1923. perf_cgroup_match(event);
  1924. }
  1925. static void
  1926. event_sched_out(struct perf_event *event, struct perf_event_context *ctx)
  1927. {
  1928. struct perf_event_pmu_context *epc = event->pmu_ctx;
  1929. struct perf_cpu_pmu_context *cpc = this_cpu_ptr(epc->pmu->cpu_pmu_context);
  1930. enum perf_event_state state = PERF_EVENT_STATE_INACTIVE;
  1931. // XXX cpc serialization, probably per-cpu IRQ disabled
  1932. WARN_ON_ONCE(event->ctx != ctx);
  1933. lockdep_assert_held(&ctx->lock);
  1934. if (event->state != PERF_EVENT_STATE_ACTIVE)
  1935. return;
  1936. /*
  1937. * Asymmetry; we only schedule events _IN_ through ctx_sched_in(), but
  1938. * we can schedule events _OUT_ individually through things like
  1939. * __perf_remove_from_context().
  1940. */
  1941. list_del_init(&event->active_list);
  1942. perf_pmu_disable(event->pmu);
  1943. event->pmu->del(event, 0);
  1944. event->oncpu = -1;
  1945. if (event->pending_disable) {
  1946. event->pending_disable = 0;
  1947. perf_cgroup_event_disable(event, ctx);
  1948. state = PERF_EVENT_STATE_OFF;
  1949. }
  1950. perf_event_set_state(event, state);
  1951. if (!is_software_event(event))
  1952. cpc->active_oncpu--;
  1953. if (event->attr.freq && event->attr.sample_freq) {
  1954. ctx->nr_freq--;
  1955. epc->nr_freq--;
  1956. }
  1957. if (event->attr.exclusive || !cpc->active_oncpu)
  1958. cpc->exclusive = 0;
  1959. perf_pmu_enable(event->pmu);
  1960. }
  1961. static void
  1962. group_sched_out(struct perf_event *group_event, struct perf_event_context *ctx)
  1963. {
  1964. struct perf_event *event;
  1965. if (group_event->state != PERF_EVENT_STATE_ACTIVE)
  1966. return;
  1967. perf_assert_pmu_disabled(group_event->pmu_ctx->pmu);
  1968. event_sched_out(group_event, ctx);
  1969. /*
  1970. * Schedule out siblings (if any):
  1971. */
  1972. for_each_sibling_event(event, group_event)
  1973. event_sched_out(event, ctx);
  1974. }
  1975. static inline void
  1976. __ctx_time_update(struct perf_cpu_context *cpuctx, struct perf_event_context *ctx, bool final)
  1977. {
  1978. if (ctx->is_active & EVENT_TIME) {
  1979. if (ctx->is_active & EVENT_FROZEN)
  1980. return;
  1981. update_context_time(ctx);
  1982. update_cgrp_time_from_cpuctx(cpuctx, final);
  1983. }
  1984. }
  1985. static inline void
  1986. ctx_time_update(struct perf_cpu_context *cpuctx, struct perf_event_context *ctx)
  1987. {
  1988. __ctx_time_update(cpuctx, ctx, false);
  1989. }
  1990. /*
  1991. * To be used inside perf_ctx_lock() / perf_ctx_unlock(). Lasts until perf_ctx_unlock().
  1992. */
  1993. static inline void
  1994. ctx_time_freeze(struct perf_cpu_context *cpuctx, struct perf_event_context *ctx)
  1995. {
  1996. ctx_time_update(cpuctx, ctx);
  1997. if (ctx->is_active & EVENT_TIME)
  1998. ctx->is_active |= EVENT_FROZEN;
  1999. }
  2000. static inline void
  2001. ctx_time_update_event(struct perf_event_context *ctx, struct perf_event *event)
  2002. {
  2003. if (ctx->is_active & EVENT_TIME) {
  2004. if (ctx->is_active & EVENT_FROZEN)
  2005. return;
  2006. update_context_time(ctx);
  2007. update_cgrp_time_from_event(event);
  2008. }
  2009. }
  2010. #define DETACH_GROUP 0x01UL
  2011. #define DETACH_CHILD 0x02UL
  2012. #define DETACH_DEAD 0x04UL
  2013. #define DETACH_EXIT 0x08UL
  2014. /*
  2015. * Cross CPU call to remove a performance event
  2016. *
  2017. * We disable the event on the hardware level first. After that we
  2018. * remove it from the context list.
  2019. */
  2020. static void
  2021. __perf_remove_from_context(struct perf_event *event,
  2022. struct perf_cpu_context *cpuctx,
  2023. struct perf_event_context *ctx,
  2024. void *info)
  2025. {
  2026. struct perf_event_pmu_context *pmu_ctx = event->pmu_ctx;
  2027. enum perf_event_state state = PERF_EVENT_STATE_OFF;
  2028. unsigned long flags = (unsigned long)info;
  2029. ctx_time_update(cpuctx, ctx);
  2030. /*
  2031. * Ensure event_sched_out() switches to OFF, at the very least
  2032. * this avoids raising perf_pending_task() at this time.
  2033. */
  2034. if (flags & DETACH_EXIT)
  2035. state = PERF_EVENT_STATE_EXIT;
  2036. if (flags & DETACH_DEAD) {
  2037. event->pending_disable = 1;
  2038. state = PERF_EVENT_STATE_DEAD;
  2039. }
  2040. event_sched_out(event, ctx);
  2041. perf_event_set_state(event, min(event->state, state));
  2042. if (flags & DETACH_GROUP)
  2043. perf_group_detach(event);
  2044. if (flags & DETACH_CHILD)
  2045. perf_child_detach(event);
  2046. list_del_event(event, ctx);
  2047. if (!pmu_ctx->nr_events) {
  2048. pmu_ctx->rotate_necessary = 0;
  2049. if (ctx->task && ctx->is_active) {
  2050. struct perf_cpu_pmu_context *cpc;
  2051. cpc = this_cpu_ptr(pmu_ctx->pmu->cpu_pmu_context);
  2052. WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx);
  2053. cpc->task_epc = NULL;
  2054. }
  2055. }
  2056. if (!ctx->nr_events && ctx->is_active) {
  2057. if (ctx == &cpuctx->ctx)
  2058. update_cgrp_time_from_cpuctx(cpuctx, true);
  2059. ctx->is_active = 0;
  2060. if (ctx->task) {
  2061. WARN_ON_ONCE(cpuctx->task_ctx != ctx);
  2062. cpuctx->task_ctx = NULL;
  2063. }
  2064. }
  2065. }
  2066. /*
  2067. * Remove the event from a task's (or a CPU's) list of events.
  2068. *
  2069. * If event->ctx is a cloned context, callers must make sure that
  2070. * every task struct that event->ctx->task could possibly point to
  2071. * remains valid. This is OK when called from perf_release since
  2072. * that only calls us on the top-level context, which can't be a clone.
  2073. * When called from perf_event_exit_task, it's OK because the
  2074. * context has been detached from its task.
  2075. */
  2076. static void perf_remove_from_context(struct perf_event *event, unsigned long flags)
  2077. {
  2078. struct perf_event_context *ctx = event->ctx;
  2079. lockdep_assert_held(&ctx->mutex);
  2080. /*
  2081. * Because of perf_event_exit_task(), perf_remove_from_context() ought
  2082. * to work in the face of TASK_TOMBSTONE, unlike every other
  2083. * event_function_call() user.
  2084. */
  2085. raw_spin_lock_irq(&ctx->lock);
  2086. if (!ctx->is_active) {
  2087. __perf_remove_from_context(event, this_cpu_ptr(&perf_cpu_context),
  2088. ctx, (void *)flags);
  2089. raw_spin_unlock_irq(&ctx->lock);
  2090. return;
  2091. }
  2092. raw_spin_unlock_irq(&ctx->lock);
  2093. event_function_call(event, __perf_remove_from_context, (void *)flags);
  2094. }
  2095. static void __event_disable(struct perf_event *event,
  2096. struct perf_event_context *ctx,
  2097. enum perf_event_state state)
  2098. {
  2099. event_sched_out(event, ctx);
  2100. perf_cgroup_event_disable(event, ctx);
  2101. perf_event_set_state(event, state);
  2102. }
  2103. /*
  2104. * Cross CPU call to disable a performance event
  2105. */
  2106. static void __perf_event_disable(struct perf_event *event,
  2107. struct perf_cpu_context *cpuctx,
  2108. struct perf_event_context *ctx,
  2109. void *info)
  2110. {
  2111. if (event->state < PERF_EVENT_STATE_INACTIVE)
  2112. return;
  2113. perf_pmu_disable(event->pmu_ctx->pmu);
  2114. ctx_time_update_event(ctx, event);
  2115. /*
  2116. * When disabling a group leader, the whole group becomes ineligible
  2117. * to run, so schedule out the full group.
  2118. */
  2119. if (event == event->group_leader)
  2120. group_sched_out(event, ctx);
  2121. /*
  2122. * But only mark the leader OFF; the siblings will remain
  2123. * INACTIVE.
  2124. */
  2125. __event_disable(event, ctx, PERF_EVENT_STATE_OFF);
  2126. perf_pmu_enable(event->pmu_ctx->pmu);
  2127. }
  2128. /*
  2129. * Disable an event.
  2130. *
  2131. * If event->ctx is a cloned context, callers must make sure that
  2132. * every task struct that event->ctx->task could possibly point to
  2133. * remains valid. This condition is satisfied when called through
  2134. * perf_event_for_each_child or perf_event_for_each because they
  2135. * hold the top-level event's child_mutex, so any descendant that
  2136. * goes to exit will block in perf_event_exit_event().
  2137. *
  2138. * When called from perf_pending_disable it's OK because event->ctx
  2139. * is the current context on this CPU and preemption is disabled,
  2140. * hence we can't get into perf_event_task_sched_out for this context.
  2141. */
  2142. static void _perf_event_disable(struct perf_event *event)
  2143. {
  2144. struct perf_event_context *ctx = event->ctx;
  2145. raw_spin_lock_irq(&ctx->lock);
  2146. if (event->state <= PERF_EVENT_STATE_OFF) {
  2147. raw_spin_unlock_irq(&ctx->lock);
  2148. return;
  2149. }
  2150. raw_spin_unlock_irq(&ctx->lock);
  2151. event_function_call(event, __perf_event_disable, NULL);
  2152. }
  2153. void perf_event_disable_local(struct perf_event *event)
  2154. {
  2155. event_function_local(event, __perf_event_disable, NULL);
  2156. }
  2157. /*
  2158. * Strictly speaking kernel users cannot create groups and therefore this
  2159. * interface does not need the perf_event_ctx_lock() magic.
  2160. */
  2161. void perf_event_disable(struct perf_event *event)
  2162. {
  2163. struct perf_event_context *ctx;
  2164. ctx = perf_event_ctx_lock(event);
  2165. _perf_event_disable(event);
  2166. perf_event_ctx_unlock(event, ctx);
  2167. }
  2168. EXPORT_SYMBOL_GPL(perf_event_disable);
  2169. void perf_event_disable_inatomic(struct perf_event *event)
  2170. {
  2171. event->pending_disable = 1;
  2172. irq_work_queue(&event->pending_disable_irq);
  2173. }
  2174. #define MAX_INTERRUPTS (~0ULL)
  2175. static void perf_log_throttle(struct perf_event *event, int enable);
  2176. static void perf_log_itrace_start(struct perf_event *event);
  2177. static int
  2178. event_sched_in(struct perf_event *event, struct perf_event_context *ctx)
  2179. {
  2180. struct perf_event_pmu_context *epc = event->pmu_ctx;
  2181. struct perf_cpu_pmu_context *cpc = this_cpu_ptr(epc->pmu->cpu_pmu_context);
  2182. int ret = 0;
  2183. WARN_ON_ONCE(event->ctx != ctx);
  2184. lockdep_assert_held(&ctx->lock);
  2185. if (event->state <= PERF_EVENT_STATE_OFF)
  2186. return 0;
  2187. WRITE_ONCE(event->oncpu, smp_processor_id());
  2188. /*
  2189. * Order event::oncpu write to happen before the ACTIVE state is
  2190. * visible. This allows perf_event_{stop,read}() to observe the correct
  2191. * ->oncpu if it sees ACTIVE.
  2192. */
  2193. smp_wmb();
  2194. perf_event_set_state(event, PERF_EVENT_STATE_ACTIVE);
  2195. /*
  2196. * Unthrottle events, since we scheduled we might have missed several
  2197. * ticks already, also for a heavily scheduling task there is little
  2198. * guarantee it'll get a tick in a timely manner.
  2199. */
  2200. if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
  2201. perf_log_throttle(event, 1);
  2202. event->hw.interrupts = 0;
  2203. }
  2204. perf_pmu_disable(event->pmu);
  2205. perf_log_itrace_start(event);
  2206. if (event->pmu->add(event, PERF_EF_START)) {
  2207. perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
  2208. event->oncpu = -1;
  2209. ret = -EAGAIN;
  2210. goto out;
  2211. }
  2212. if (!is_software_event(event))
  2213. cpc->active_oncpu++;
  2214. if (event->attr.freq && event->attr.sample_freq) {
  2215. ctx->nr_freq++;
  2216. epc->nr_freq++;
  2217. }
  2218. if (event->attr.exclusive)
  2219. cpc->exclusive = 1;
  2220. out:
  2221. perf_pmu_enable(event->pmu);
  2222. return ret;
  2223. }
  2224. static int
  2225. group_sched_in(struct perf_event *group_event, struct perf_event_context *ctx)
  2226. {
  2227. struct perf_event *event, *partial_group = NULL;
  2228. struct pmu *pmu = group_event->pmu_ctx->pmu;
  2229. if (group_event->state == PERF_EVENT_STATE_OFF)
  2230. return 0;
  2231. pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
  2232. if (event_sched_in(group_event, ctx))
  2233. goto error;
  2234. /*
  2235. * Schedule in siblings as one group (if any):
  2236. */
  2237. for_each_sibling_event(event, group_event) {
  2238. if (event_sched_in(event, ctx)) {
  2239. partial_group = event;
  2240. goto group_error;
  2241. }
  2242. }
  2243. if (!pmu->commit_txn(pmu))
  2244. return 0;
  2245. group_error:
  2246. /*
  2247. * Groups can be scheduled in as one unit only, so undo any
  2248. * partial group before returning:
  2249. * The events up to the failed event are scheduled out normally.
  2250. */
  2251. for_each_sibling_event(event, group_event) {
  2252. if (event == partial_group)
  2253. break;
  2254. event_sched_out(event, ctx);
  2255. }
  2256. event_sched_out(group_event, ctx);
  2257. error:
  2258. pmu->cancel_txn(pmu);
  2259. return -EAGAIN;
  2260. }
  2261. /*
  2262. * Work out whether we can put this event group on the CPU now.
  2263. */
  2264. static int group_can_go_on(struct perf_event *event, int can_add_hw)
  2265. {
  2266. struct perf_event_pmu_context *epc = event->pmu_ctx;
  2267. struct perf_cpu_pmu_context *cpc = this_cpu_ptr(epc->pmu->cpu_pmu_context);
  2268. /*
  2269. * Groups consisting entirely of software events can always go on.
  2270. */
  2271. if (event->group_caps & PERF_EV_CAP_SOFTWARE)
  2272. return 1;
  2273. /*
  2274. * If an exclusive group is already on, no other hardware
  2275. * events can go on.
  2276. */
  2277. if (cpc->exclusive)
  2278. return 0;
  2279. /*
  2280. * If this group is exclusive and there are already
  2281. * events on the CPU, it can't go on.
  2282. */
  2283. if (event->attr.exclusive && !list_empty(get_event_list(event)))
  2284. return 0;
  2285. /*
  2286. * Otherwise, try to add it if all previous groups were able
  2287. * to go on.
  2288. */
  2289. return can_add_hw;
  2290. }
  2291. static void add_event_to_ctx(struct perf_event *event,
  2292. struct perf_event_context *ctx)
  2293. {
  2294. list_add_event(event, ctx);
  2295. perf_group_attach(event);
  2296. }
  2297. static void task_ctx_sched_out(struct perf_event_context *ctx,
  2298. struct pmu *pmu,
  2299. enum event_type_t event_type)
  2300. {
  2301. struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
  2302. if (!cpuctx->task_ctx)
  2303. return;
  2304. if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
  2305. return;
  2306. ctx_sched_out(ctx, pmu, event_type);
  2307. }
  2308. static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
  2309. struct perf_event_context *ctx,
  2310. struct pmu *pmu)
  2311. {
  2312. ctx_sched_in(&cpuctx->ctx, pmu, EVENT_PINNED);
  2313. if (ctx)
  2314. ctx_sched_in(ctx, pmu, EVENT_PINNED);
  2315. ctx_sched_in(&cpuctx->ctx, pmu, EVENT_FLEXIBLE);
  2316. if (ctx)
  2317. ctx_sched_in(ctx, pmu, EVENT_FLEXIBLE);
  2318. }
  2319. /*
  2320. * We want to maintain the following priority of scheduling:
  2321. * - CPU pinned (EVENT_CPU | EVENT_PINNED)
  2322. * - task pinned (EVENT_PINNED)
  2323. * - CPU flexible (EVENT_CPU | EVENT_FLEXIBLE)
  2324. * - task flexible (EVENT_FLEXIBLE).
  2325. *
  2326. * In order to avoid unscheduling and scheduling back in everything every
  2327. * time an event is added, only do it for the groups of equal priority and
  2328. * below.
  2329. *
  2330. * This can be called after a batch operation on task events, in which case
  2331. * event_type is a bit mask of the types of events involved. For CPU events,
  2332. * event_type is only either EVENT_PINNED or EVENT_FLEXIBLE.
  2333. */
  2334. static void ctx_resched(struct perf_cpu_context *cpuctx,
  2335. struct perf_event_context *task_ctx,
  2336. struct pmu *pmu, enum event_type_t event_type)
  2337. {
  2338. bool cpu_event = !!(event_type & EVENT_CPU);
  2339. struct perf_event_pmu_context *epc;
  2340. /*
  2341. * If pinned groups are involved, flexible groups also need to be
  2342. * scheduled out.
  2343. */
  2344. if (event_type & EVENT_PINNED)
  2345. event_type |= EVENT_FLEXIBLE;
  2346. event_type &= EVENT_ALL;
  2347. for_each_epc(epc, &cpuctx->ctx, pmu, false)
  2348. perf_pmu_disable(epc->pmu);
  2349. if (task_ctx) {
  2350. for_each_epc(epc, task_ctx, pmu, false)
  2351. perf_pmu_disable(epc->pmu);
  2352. task_ctx_sched_out(task_ctx, pmu, event_type);
  2353. }
  2354. /*
  2355. * Decide which cpu ctx groups to schedule out based on the types
  2356. * of events that caused rescheduling:
  2357. * - EVENT_CPU: schedule out corresponding groups;
  2358. * - EVENT_PINNED task events: schedule out EVENT_FLEXIBLE groups;
  2359. * - otherwise, do nothing more.
  2360. */
  2361. if (cpu_event)
  2362. ctx_sched_out(&cpuctx->ctx, pmu, event_type);
  2363. else if (event_type & EVENT_PINNED)
  2364. ctx_sched_out(&cpuctx->ctx, pmu, EVENT_FLEXIBLE);
  2365. perf_event_sched_in(cpuctx, task_ctx, pmu);
  2366. for_each_epc(epc, &cpuctx->ctx, pmu, false)
  2367. perf_pmu_enable(epc->pmu);
  2368. if (task_ctx) {
  2369. for_each_epc(epc, task_ctx, pmu, false)
  2370. perf_pmu_enable(epc->pmu);
  2371. }
  2372. }
  2373. void perf_pmu_resched(struct pmu *pmu)
  2374. {
  2375. struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
  2376. struct perf_event_context *task_ctx = cpuctx->task_ctx;
  2377. perf_ctx_lock(cpuctx, task_ctx);
  2378. ctx_resched(cpuctx, task_ctx, pmu, EVENT_ALL|EVENT_CPU);
  2379. perf_ctx_unlock(cpuctx, task_ctx);
  2380. }
  2381. /*
  2382. * Cross CPU call to install and enable a performance event
  2383. *
  2384. * Very similar to remote_function() + event_function() but cannot assume that
  2385. * things like ctx->is_active and cpuctx->task_ctx are set.
  2386. */
  2387. static int __perf_install_in_context(void *info)
  2388. {
  2389. struct perf_event *event = info;
  2390. struct perf_event_context *ctx = event->ctx;
  2391. struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
  2392. struct perf_event_context *task_ctx = cpuctx->task_ctx;
  2393. bool reprogram = true;
  2394. int ret = 0;
  2395. raw_spin_lock(&cpuctx->ctx.lock);
  2396. if (ctx->task) {
  2397. raw_spin_lock(&ctx->lock);
  2398. task_ctx = ctx;
  2399. reprogram = (ctx->task == current);
  2400. /*
  2401. * If the task is running, it must be running on this CPU,
  2402. * otherwise we cannot reprogram things.
  2403. *
  2404. * If its not running, we don't care, ctx->lock will
  2405. * serialize against it becoming runnable.
  2406. */
  2407. if (task_curr(ctx->task) && !reprogram) {
  2408. ret = -ESRCH;
  2409. goto unlock;
  2410. }
  2411. WARN_ON_ONCE(reprogram && cpuctx->task_ctx && cpuctx->task_ctx != ctx);
  2412. } else if (task_ctx) {
  2413. raw_spin_lock(&task_ctx->lock);
  2414. }
  2415. #ifdef CONFIG_CGROUP_PERF
  2416. if (event->state > PERF_EVENT_STATE_OFF && is_cgroup_event(event)) {
  2417. /*
  2418. * If the current cgroup doesn't match the event's
  2419. * cgroup, we should not try to schedule it.
  2420. */
  2421. struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
  2422. reprogram = cgroup_is_descendant(cgrp->css.cgroup,
  2423. event->cgrp->css.cgroup);
  2424. }
  2425. #endif
  2426. if (reprogram) {
  2427. ctx_time_freeze(cpuctx, ctx);
  2428. add_event_to_ctx(event, ctx);
  2429. ctx_resched(cpuctx, task_ctx, event->pmu_ctx->pmu,
  2430. get_event_type(event));
  2431. } else {
  2432. add_event_to_ctx(event, ctx);
  2433. }
  2434. unlock:
  2435. perf_ctx_unlock(cpuctx, task_ctx);
  2436. return ret;
  2437. }
  2438. static bool exclusive_event_installable(struct perf_event *event,
  2439. struct perf_event_context *ctx);
  2440. /*
  2441. * Attach a performance event to a context.
  2442. *
  2443. * Very similar to event_function_call, see comment there.
  2444. */
  2445. static void
  2446. perf_install_in_context(struct perf_event_context *ctx,
  2447. struct perf_event *event,
  2448. int cpu)
  2449. {
  2450. struct task_struct *task = READ_ONCE(ctx->task);
  2451. lockdep_assert_held(&ctx->mutex);
  2452. WARN_ON_ONCE(!exclusive_event_installable(event, ctx));
  2453. if (event->cpu != -1)
  2454. WARN_ON_ONCE(event->cpu != cpu);
  2455. /*
  2456. * Ensures that if we can observe event->ctx, both the event and ctx
  2457. * will be 'complete'. See perf_iterate_sb_cpu().
  2458. */
  2459. smp_store_release(&event->ctx, ctx);
  2460. /*
  2461. * perf_event_attr::disabled events will not run and can be initialized
  2462. * without IPI. Except when this is the first event for the context, in
  2463. * that case we need the magic of the IPI to set ctx->is_active.
  2464. *
  2465. * The IOC_ENABLE that is sure to follow the creation of a disabled
  2466. * event will issue the IPI and reprogram the hardware.
  2467. */
  2468. if (__perf_effective_state(event) == PERF_EVENT_STATE_OFF &&
  2469. ctx->nr_events && !is_cgroup_event(event)) {
  2470. raw_spin_lock_irq(&ctx->lock);
  2471. if (ctx->task == TASK_TOMBSTONE) {
  2472. raw_spin_unlock_irq(&ctx->lock);
  2473. return;
  2474. }
  2475. add_event_to_ctx(event, ctx);
  2476. raw_spin_unlock_irq(&ctx->lock);
  2477. return;
  2478. }
  2479. if (!task) {
  2480. cpu_function_call(cpu, __perf_install_in_context, event);
  2481. return;
  2482. }
  2483. /*
  2484. * Should not happen, we validate the ctx is still alive before calling.
  2485. */
  2486. if (WARN_ON_ONCE(task == TASK_TOMBSTONE))
  2487. return;
  2488. /*
  2489. * Installing events is tricky because we cannot rely on ctx->is_active
  2490. * to be set in case this is the nr_events 0 -> 1 transition.
  2491. *
  2492. * Instead we use task_curr(), which tells us if the task is running.
  2493. * However, since we use task_curr() outside of rq::lock, we can race
  2494. * against the actual state. This means the result can be wrong.
  2495. *
  2496. * If we get a false positive, we retry, this is harmless.
  2497. *
  2498. * If we get a false negative, things are complicated. If we are after
  2499. * perf_event_context_sched_in() ctx::lock will serialize us, and the
  2500. * value must be correct. If we're before, it doesn't matter since
  2501. * perf_event_context_sched_in() will program the counter.
  2502. *
  2503. * However, this hinges on the remote context switch having observed
  2504. * our task->perf_event_ctxp[] store, such that it will in fact take
  2505. * ctx::lock in perf_event_context_sched_in().
  2506. *
  2507. * We do this by task_function_call(), if the IPI fails to hit the task
  2508. * we know any future context switch of task must see the
  2509. * perf_event_ctpx[] store.
  2510. */
  2511. /*
  2512. * This smp_mb() orders the task->perf_event_ctxp[] store with the
  2513. * task_cpu() load, such that if the IPI then does not find the task
  2514. * running, a future context switch of that task must observe the
  2515. * store.
  2516. */
  2517. smp_mb();
  2518. again:
  2519. if (!task_function_call(task, __perf_install_in_context, event))
  2520. return;
  2521. raw_spin_lock_irq(&ctx->lock);
  2522. task = ctx->task;
  2523. if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) {
  2524. /*
  2525. * Cannot happen because we already checked above (which also
  2526. * cannot happen), and we hold ctx->mutex, which serializes us
  2527. * against perf_event_exit_task_context().
  2528. */
  2529. raw_spin_unlock_irq(&ctx->lock);
  2530. return;
  2531. }
  2532. /*
  2533. * If the task is not running, ctx->lock will avoid it becoming so,
  2534. * thus we can safely install the event.
  2535. */
  2536. if (task_curr(task)) {
  2537. raw_spin_unlock_irq(&ctx->lock);
  2538. goto again;
  2539. }
  2540. add_event_to_ctx(event, ctx);
  2541. raw_spin_unlock_irq(&ctx->lock);
  2542. }
  2543. /*
  2544. * Cross CPU call to enable a performance event
  2545. */
  2546. static void __perf_event_enable(struct perf_event *event,
  2547. struct perf_cpu_context *cpuctx,
  2548. struct perf_event_context *ctx,
  2549. void *info)
  2550. {
  2551. struct perf_event *leader = event->group_leader;
  2552. struct perf_event_context *task_ctx;
  2553. if (event->state >= PERF_EVENT_STATE_INACTIVE ||
  2554. event->state <= PERF_EVENT_STATE_ERROR)
  2555. return;
  2556. ctx_time_freeze(cpuctx, ctx);
  2557. perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
  2558. perf_cgroup_event_enable(event, ctx);
  2559. if (!ctx->is_active)
  2560. return;
  2561. if (!event_filter_match(event))
  2562. return;
  2563. /*
  2564. * If the event is in a group and isn't the group leader,
  2565. * then don't put it on unless the group is on.
  2566. */
  2567. if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE)
  2568. return;
  2569. task_ctx = cpuctx->task_ctx;
  2570. if (ctx->task)
  2571. WARN_ON_ONCE(task_ctx != ctx);
  2572. ctx_resched(cpuctx, task_ctx, event->pmu_ctx->pmu, get_event_type(event));
  2573. }
  2574. /*
  2575. * Enable an event.
  2576. *
  2577. * If event->ctx is a cloned context, callers must make sure that
  2578. * every task struct that event->ctx->task could possibly point to
  2579. * remains valid. This condition is satisfied when called through
  2580. * perf_event_for_each_child or perf_event_for_each as described
  2581. * for perf_event_disable.
  2582. */
  2583. static void _perf_event_enable(struct perf_event *event)
  2584. {
  2585. struct perf_event_context *ctx = event->ctx;
  2586. raw_spin_lock_irq(&ctx->lock);
  2587. if (event->state >= PERF_EVENT_STATE_INACTIVE ||
  2588. event->state < PERF_EVENT_STATE_ERROR) {
  2589. out:
  2590. raw_spin_unlock_irq(&ctx->lock);
  2591. return;
  2592. }
  2593. /*
  2594. * If the event is in error state, clear that first.
  2595. *
  2596. * That way, if we see the event in error state below, we know that it
  2597. * has gone back into error state, as distinct from the task having
  2598. * been scheduled away before the cross-call arrived.
  2599. */
  2600. if (event->state == PERF_EVENT_STATE_ERROR) {
  2601. /*
  2602. * Detached SIBLING events cannot leave ERROR state.
  2603. */
  2604. if (event->event_caps & PERF_EV_CAP_SIBLING &&
  2605. event->group_leader == event)
  2606. goto out;
  2607. event->state = PERF_EVENT_STATE_OFF;
  2608. }
  2609. raw_spin_unlock_irq(&ctx->lock);
  2610. event_function_call(event, __perf_event_enable, NULL);
  2611. }
  2612. /*
  2613. * See perf_event_disable();
  2614. */
  2615. void perf_event_enable(struct perf_event *event)
  2616. {
  2617. struct perf_event_context *ctx;
  2618. ctx = perf_event_ctx_lock(event);
  2619. _perf_event_enable(event);
  2620. perf_event_ctx_unlock(event, ctx);
  2621. }
  2622. EXPORT_SYMBOL_GPL(perf_event_enable);
  2623. struct stop_event_data {
  2624. struct perf_event *event;
  2625. unsigned int restart;
  2626. };
  2627. static int __perf_event_stop(void *info)
  2628. {
  2629. struct stop_event_data *sd = info;
  2630. struct perf_event *event = sd->event;
  2631. /* if it's already INACTIVE, do nothing */
  2632. if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
  2633. return 0;
  2634. /* matches smp_wmb() in event_sched_in() */
  2635. smp_rmb();
  2636. /*
  2637. * There is a window with interrupts enabled before we get here,
  2638. * so we need to check again lest we try to stop another CPU's event.
  2639. */
  2640. if (READ_ONCE(event->oncpu) != smp_processor_id())
  2641. return -EAGAIN;
  2642. event->pmu->stop(event, PERF_EF_UPDATE);
  2643. /*
  2644. * May race with the actual stop (through perf_pmu_output_stop()),
  2645. * but it is only used for events with AUX ring buffer, and such
  2646. * events will refuse to restart because of rb::aux_mmap_count==0,
  2647. * see comments in perf_aux_output_begin().
  2648. *
  2649. * Since this is happening on an event-local CPU, no trace is lost
  2650. * while restarting.
  2651. */
  2652. if (sd->restart)
  2653. event->pmu->start(event, 0);
  2654. return 0;
  2655. }
  2656. static int perf_event_stop(struct perf_event *event, int restart)
  2657. {
  2658. struct stop_event_data sd = {
  2659. .event = event,
  2660. .restart = restart,
  2661. };
  2662. int ret = 0;
  2663. do {
  2664. if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
  2665. return 0;
  2666. /* matches smp_wmb() in event_sched_in() */
  2667. smp_rmb();
  2668. /*
  2669. * We only want to restart ACTIVE events, so if the event goes
  2670. * inactive here (event->oncpu==-1), there's nothing more to do;
  2671. * fall through with ret==-ENXIO.
  2672. */
  2673. ret = cpu_function_call(READ_ONCE(event->oncpu),
  2674. __perf_event_stop, &sd);
  2675. } while (ret == -EAGAIN);
  2676. return ret;
  2677. }
  2678. /*
  2679. * In order to contain the amount of racy and tricky in the address filter
  2680. * configuration management, it is a two part process:
  2681. *
  2682. * (p1) when userspace mappings change as a result of (1) or (2) or (3) below,
  2683. * we update the addresses of corresponding vmas in
  2684. * event::addr_filter_ranges array and bump the event::addr_filters_gen;
  2685. * (p2) when an event is scheduled in (pmu::add), it calls
  2686. * perf_event_addr_filters_sync() which calls pmu::addr_filters_sync()
  2687. * if the generation has changed since the previous call.
  2688. *
  2689. * If (p1) happens while the event is active, we restart it to force (p2).
  2690. *
  2691. * (1) perf_addr_filters_apply(): adjusting filters' offsets based on
  2692. * pre-existing mappings, called once when new filters arrive via SET_FILTER
  2693. * ioctl;
  2694. * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly
  2695. * registered mapping, called for every new mmap(), with mm::mmap_lock down
  2696. * for reading;
  2697. * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process
  2698. * of exec.
  2699. */
  2700. void perf_event_addr_filters_sync(struct perf_event *event)
  2701. {
  2702. struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
  2703. if (!has_addr_filter(event))
  2704. return;
  2705. raw_spin_lock(&ifh->lock);
  2706. if (event->addr_filters_gen != event->hw.addr_filters_gen) {
  2707. event->pmu->addr_filters_sync(event);
  2708. event->hw.addr_filters_gen = event->addr_filters_gen;
  2709. }
  2710. raw_spin_unlock(&ifh->lock);
  2711. }
  2712. EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync);
  2713. static int _perf_event_refresh(struct perf_event *event, int refresh)
  2714. {
  2715. /*
  2716. * not supported on inherited events
  2717. */
  2718. if (event->attr.inherit || !is_sampling_event(event))
  2719. return -EINVAL;
  2720. atomic_add(refresh, &event->event_limit);
  2721. _perf_event_enable(event);
  2722. return 0;
  2723. }
  2724. /*
  2725. * See perf_event_disable()
  2726. */
  2727. int perf_event_refresh(struct perf_event *event, int refresh)
  2728. {
  2729. struct perf_event_context *ctx;
  2730. int ret;
  2731. ctx = perf_event_ctx_lock(event);
  2732. ret = _perf_event_refresh(event, refresh);
  2733. perf_event_ctx_unlock(event, ctx);
  2734. return ret;
  2735. }
  2736. EXPORT_SYMBOL_GPL(perf_event_refresh);
  2737. static int perf_event_modify_breakpoint(struct perf_event *bp,
  2738. struct perf_event_attr *attr)
  2739. {
  2740. int err;
  2741. _perf_event_disable(bp);
  2742. err = modify_user_hw_breakpoint_check(bp, attr, true);
  2743. if (!bp->attr.disabled)
  2744. _perf_event_enable(bp);
  2745. return err;
  2746. }
  2747. /*
  2748. * Copy event-type-independent attributes that may be modified.
  2749. */
  2750. static void perf_event_modify_copy_attr(struct perf_event_attr *to,
  2751. const struct perf_event_attr *from)
  2752. {
  2753. to->sig_data = from->sig_data;
  2754. }
  2755. static int perf_event_modify_attr(struct perf_event *event,
  2756. struct perf_event_attr *attr)
  2757. {
  2758. int (*func)(struct perf_event *, struct perf_event_attr *);
  2759. struct perf_event *child;
  2760. int err;
  2761. if (event->attr.type != attr->type)
  2762. return -EINVAL;
  2763. switch (event->attr.type) {
  2764. case PERF_TYPE_BREAKPOINT:
  2765. func = perf_event_modify_breakpoint;
  2766. break;
  2767. default:
  2768. /* Place holder for future additions. */
  2769. return -EOPNOTSUPP;
  2770. }
  2771. WARN_ON_ONCE(event->ctx->parent_ctx);
  2772. mutex_lock(&event->child_mutex);
  2773. /*
  2774. * Event-type-independent attributes must be copied before event-type
  2775. * modification, which will validate that final attributes match the
  2776. * source attributes after all relevant attributes have been copied.
  2777. */
  2778. perf_event_modify_copy_attr(&event->attr, attr);
  2779. err = func(event, attr);
  2780. if (err)
  2781. goto out;
  2782. list_for_each_entry(child, &event->child_list, child_list) {
  2783. perf_event_modify_copy_attr(&child->attr, attr);
  2784. err = func(child, attr);
  2785. if (err)
  2786. goto out;
  2787. }
  2788. out:
  2789. mutex_unlock(&event->child_mutex);
  2790. return err;
  2791. }
  2792. static void __pmu_ctx_sched_out(struct perf_event_pmu_context *pmu_ctx,
  2793. enum event_type_t event_type)
  2794. {
  2795. struct perf_event_context *ctx = pmu_ctx->ctx;
  2796. struct perf_event *event, *tmp;
  2797. struct pmu *pmu = pmu_ctx->pmu;
  2798. if (ctx->task && !(ctx->is_active & EVENT_ALL)) {
  2799. struct perf_cpu_pmu_context *cpc;
  2800. cpc = this_cpu_ptr(pmu->cpu_pmu_context);
  2801. WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx);
  2802. cpc->task_epc = NULL;
  2803. }
  2804. if (!(event_type & EVENT_ALL))
  2805. return;
  2806. perf_pmu_disable(pmu);
  2807. if (event_type & EVENT_PINNED) {
  2808. list_for_each_entry_safe(event, tmp,
  2809. &pmu_ctx->pinned_active,
  2810. active_list)
  2811. group_sched_out(event, ctx);
  2812. }
  2813. if (event_type & EVENT_FLEXIBLE) {
  2814. list_for_each_entry_safe(event, tmp,
  2815. &pmu_ctx->flexible_active,
  2816. active_list)
  2817. group_sched_out(event, ctx);
  2818. /*
  2819. * Since we cleared EVENT_FLEXIBLE, also clear
  2820. * rotate_necessary, is will be reset by
  2821. * ctx_flexible_sched_in() when needed.
  2822. */
  2823. pmu_ctx->rotate_necessary = 0;
  2824. }
  2825. perf_pmu_enable(pmu);
  2826. }
  2827. /*
  2828. * Be very careful with the @pmu argument since this will change ctx state.
  2829. * The @pmu argument works for ctx_resched(), because that is symmetric in
  2830. * ctx_sched_out() / ctx_sched_in() usage and the ctx state ends up invariant.
  2831. *
  2832. * However, if you were to be asymmetrical, you could end up with messed up
  2833. * state, eg. ctx->is_active cleared even though most EPCs would still actually
  2834. * be active.
  2835. */
  2836. static void
  2837. ctx_sched_out(struct perf_event_context *ctx, struct pmu *pmu, enum event_type_t event_type)
  2838. {
  2839. struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
  2840. struct perf_event_pmu_context *pmu_ctx;
  2841. int is_active = ctx->is_active;
  2842. bool cgroup = event_type & EVENT_CGROUP;
  2843. event_type &= ~EVENT_CGROUP;
  2844. lockdep_assert_held(&ctx->lock);
  2845. if (likely(!ctx->nr_events)) {
  2846. /*
  2847. * See __perf_remove_from_context().
  2848. */
  2849. WARN_ON_ONCE(ctx->is_active);
  2850. if (ctx->task)
  2851. WARN_ON_ONCE(cpuctx->task_ctx);
  2852. return;
  2853. }
  2854. /*
  2855. * Always update time if it was set; not only when it changes.
  2856. * Otherwise we can 'forget' to update time for any but the last
  2857. * context we sched out. For example:
  2858. *
  2859. * ctx_sched_out(.event_type = EVENT_FLEXIBLE)
  2860. * ctx_sched_out(.event_type = EVENT_PINNED)
  2861. *
  2862. * would only update time for the pinned events.
  2863. */
  2864. __ctx_time_update(cpuctx, ctx, ctx == &cpuctx->ctx);
  2865. /*
  2866. * CPU-release for the below ->is_active store,
  2867. * see __load_acquire() in perf_event_time_now()
  2868. */
  2869. barrier();
  2870. ctx->is_active &= ~event_type;
  2871. if (!(ctx->is_active & EVENT_ALL)) {
  2872. /*
  2873. * For FROZEN, preserve TIME|FROZEN such that perf_event_time_now()
  2874. * does not observe a hole. perf_ctx_unlock() will clean up.
  2875. */
  2876. if (ctx->is_active & EVENT_FROZEN)
  2877. ctx->is_active &= EVENT_TIME_FROZEN;
  2878. else
  2879. ctx->is_active = 0;
  2880. }
  2881. if (ctx->task) {
  2882. WARN_ON_ONCE(cpuctx->task_ctx != ctx);
  2883. if (!(ctx->is_active & EVENT_ALL))
  2884. cpuctx->task_ctx = NULL;
  2885. }
  2886. is_active ^= ctx->is_active; /* changed bits */
  2887. for_each_epc(pmu_ctx, ctx, pmu, cgroup)
  2888. __pmu_ctx_sched_out(pmu_ctx, is_active);
  2889. }
  2890. /*
  2891. * Test whether two contexts are equivalent, i.e. whether they have both been
  2892. * cloned from the same version of the same context.
  2893. *
  2894. * Equivalence is measured using a generation number in the context that is
  2895. * incremented on each modification to it; see unclone_ctx(), list_add_event()
  2896. * and list_del_event().
  2897. */
  2898. static int context_equiv(struct perf_event_context *ctx1,
  2899. struct perf_event_context *ctx2)
  2900. {
  2901. lockdep_assert_held(&ctx1->lock);
  2902. lockdep_assert_held(&ctx2->lock);
  2903. /* Pinning disables the swap optimization */
  2904. if (ctx1->pin_count || ctx2->pin_count)
  2905. return 0;
  2906. /* If ctx1 is the parent of ctx2 */
  2907. if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
  2908. return 1;
  2909. /* If ctx2 is the parent of ctx1 */
  2910. if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
  2911. return 1;
  2912. /*
  2913. * If ctx1 and ctx2 have the same parent; we flatten the parent
  2914. * hierarchy, see perf_event_init_context().
  2915. */
  2916. if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
  2917. ctx1->parent_gen == ctx2->parent_gen)
  2918. return 1;
  2919. /* Unmatched */
  2920. return 0;
  2921. }
  2922. static void __perf_event_sync_stat(struct perf_event *event,
  2923. struct perf_event *next_event)
  2924. {
  2925. u64 value;
  2926. if (!event->attr.inherit_stat)
  2927. return;
  2928. /*
  2929. * Update the event value, we cannot use perf_event_read()
  2930. * because we're in the middle of a context switch and have IRQs
  2931. * disabled, which upsets smp_call_function_single(), however
  2932. * we know the event must be on the current CPU, therefore we
  2933. * don't need to use it.
  2934. */
  2935. perf_pmu_read(event);
  2936. perf_event_update_time(event);
  2937. /*
  2938. * In order to keep per-task stats reliable we need to flip the event
  2939. * values when we flip the contexts.
  2940. */
  2941. value = local64_read(&next_event->count);
  2942. value = local64_xchg(&event->count, value);
  2943. local64_set(&next_event->count, value);
  2944. swap(event->total_time_enabled, next_event->total_time_enabled);
  2945. swap(event->total_time_running, next_event->total_time_running);
  2946. /*
  2947. * Since we swizzled the values, update the user visible data too.
  2948. */
  2949. perf_event_update_userpage(event);
  2950. perf_event_update_userpage(next_event);
  2951. }
  2952. static void perf_event_sync_stat(struct perf_event_context *ctx,
  2953. struct perf_event_context *next_ctx)
  2954. {
  2955. struct perf_event *event, *next_event;
  2956. if (!ctx->nr_stat)
  2957. return;
  2958. update_context_time(ctx);
  2959. event = list_first_entry(&ctx->event_list,
  2960. struct perf_event, event_entry);
  2961. next_event = list_first_entry(&next_ctx->event_list,
  2962. struct perf_event, event_entry);
  2963. while (&event->event_entry != &ctx->event_list &&
  2964. &next_event->event_entry != &next_ctx->event_list) {
  2965. __perf_event_sync_stat(event, next_event);
  2966. event = list_next_entry(event, event_entry);
  2967. next_event = list_next_entry(next_event, event_entry);
  2968. }
  2969. }
  2970. #define double_list_for_each_entry(pos1, pos2, head1, head2, member) \
  2971. for (pos1 = list_first_entry(head1, typeof(*pos1), member), \
  2972. pos2 = list_first_entry(head2, typeof(*pos2), member); \
  2973. !list_entry_is_head(pos1, head1, member) && \
  2974. !list_entry_is_head(pos2, head2, member); \
  2975. pos1 = list_next_entry(pos1, member), \
  2976. pos2 = list_next_entry(pos2, member))
  2977. static void perf_event_swap_task_ctx_data(struct perf_event_context *prev_ctx,
  2978. struct perf_event_context *next_ctx)
  2979. {
  2980. struct perf_event_pmu_context *prev_epc, *next_epc;
  2981. if (!prev_ctx->nr_task_data)
  2982. return;
  2983. double_list_for_each_entry(prev_epc, next_epc,
  2984. &prev_ctx->pmu_ctx_list, &next_ctx->pmu_ctx_list,
  2985. pmu_ctx_entry) {
  2986. if (WARN_ON_ONCE(prev_epc->pmu != next_epc->pmu))
  2987. continue;
  2988. /*
  2989. * PMU specific parts of task perf context can require
  2990. * additional synchronization. As an example of such
  2991. * synchronization see implementation details of Intel
  2992. * LBR call stack data profiling;
  2993. */
  2994. if (prev_epc->pmu->swap_task_ctx)
  2995. prev_epc->pmu->swap_task_ctx(prev_epc, next_epc);
  2996. else
  2997. swap(prev_epc->task_ctx_data, next_epc->task_ctx_data);
  2998. }
  2999. }
  3000. static void perf_ctx_sched_task_cb(struct perf_event_context *ctx, bool sched_in)
  3001. {
  3002. struct perf_event_pmu_context *pmu_ctx;
  3003. struct perf_cpu_pmu_context *cpc;
  3004. list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry) {
  3005. cpc = this_cpu_ptr(pmu_ctx->pmu->cpu_pmu_context);
  3006. if (cpc->sched_cb_usage && pmu_ctx->pmu->sched_task)
  3007. pmu_ctx->pmu->sched_task(pmu_ctx, sched_in);
  3008. }
  3009. }
  3010. static void
  3011. perf_event_context_sched_out(struct task_struct *task, struct task_struct *next)
  3012. {
  3013. struct perf_event_context *ctx = task->perf_event_ctxp;
  3014. struct perf_event_context *next_ctx;
  3015. struct perf_event_context *parent, *next_parent;
  3016. int do_switch = 1;
  3017. if (likely(!ctx))
  3018. return;
  3019. rcu_read_lock();
  3020. next_ctx = rcu_dereference(next->perf_event_ctxp);
  3021. if (!next_ctx)
  3022. goto unlock;
  3023. parent = rcu_dereference(ctx->parent_ctx);
  3024. next_parent = rcu_dereference(next_ctx->parent_ctx);
  3025. /* If neither context have a parent context; they cannot be clones. */
  3026. if (!parent && !next_parent)
  3027. goto unlock;
  3028. if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
  3029. /*
  3030. * Looks like the two contexts are clones, so we might be
  3031. * able to optimize the context switch. We lock both
  3032. * contexts and check that they are clones under the
  3033. * lock (including re-checking that neither has been
  3034. * uncloned in the meantime). It doesn't matter which
  3035. * order we take the locks because no other cpu could
  3036. * be trying to lock both of these tasks.
  3037. */
  3038. raw_spin_lock(&ctx->lock);
  3039. raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
  3040. if (context_equiv(ctx, next_ctx)) {
  3041. perf_ctx_disable(ctx, false);
  3042. /* PMIs are disabled; ctx->nr_no_switch_fast is stable. */
  3043. if (local_read(&ctx->nr_no_switch_fast) ||
  3044. local_read(&next_ctx->nr_no_switch_fast)) {
  3045. /*
  3046. * Must not swap out ctx when there's pending
  3047. * events that rely on the ctx->task relation.
  3048. *
  3049. * Likewise, when a context contains inherit +
  3050. * SAMPLE_READ events they should be switched
  3051. * out using the slow path so that they are
  3052. * treated as if they were distinct contexts.
  3053. */
  3054. raw_spin_unlock(&next_ctx->lock);
  3055. rcu_read_unlock();
  3056. goto inside_switch;
  3057. }
  3058. WRITE_ONCE(ctx->task, next);
  3059. WRITE_ONCE(next_ctx->task, task);
  3060. perf_ctx_sched_task_cb(ctx, false);
  3061. perf_event_swap_task_ctx_data(ctx, next_ctx);
  3062. perf_ctx_enable(ctx, false);
  3063. /*
  3064. * RCU_INIT_POINTER here is safe because we've not
  3065. * modified the ctx and the above modification of
  3066. * ctx->task and ctx->task_ctx_data are immaterial
  3067. * since those values are always verified under
  3068. * ctx->lock which we're now holding.
  3069. */
  3070. RCU_INIT_POINTER(task->perf_event_ctxp, next_ctx);
  3071. RCU_INIT_POINTER(next->perf_event_ctxp, ctx);
  3072. do_switch = 0;
  3073. perf_event_sync_stat(ctx, next_ctx);
  3074. }
  3075. raw_spin_unlock(&next_ctx->lock);
  3076. raw_spin_unlock(&ctx->lock);
  3077. }
  3078. unlock:
  3079. rcu_read_unlock();
  3080. if (do_switch) {
  3081. raw_spin_lock(&ctx->lock);
  3082. perf_ctx_disable(ctx, false);
  3083. inside_switch:
  3084. perf_ctx_sched_task_cb(ctx, false);
  3085. task_ctx_sched_out(ctx, NULL, EVENT_ALL);
  3086. perf_ctx_enable(ctx, false);
  3087. raw_spin_unlock(&ctx->lock);
  3088. }
  3089. }
  3090. static DEFINE_PER_CPU(struct list_head, sched_cb_list);
  3091. static DEFINE_PER_CPU(int, perf_sched_cb_usages);
  3092. void perf_sched_cb_dec(struct pmu *pmu)
  3093. {
  3094. struct perf_cpu_pmu_context *cpc = this_cpu_ptr(pmu->cpu_pmu_context);
  3095. this_cpu_dec(perf_sched_cb_usages);
  3096. barrier();
  3097. if (!--cpc->sched_cb_usage)
  3098. list_del(&cpc->sched_cb_entry);
  3099. }
  3100. void perf_sched_cb_inc(struct pmu *pmu)
  3101. {
  3102. struct perf_cpu_pmu_context *cpc = this_cpu_ptr(pmu->cpu_pmu_context);
  3103. if (!cpc->sched_cb_usage++)
  3104. list_add(&cpc->sched_cb_entry, this_cpu_ptr(&sched_cb_list));
  3105. barrier();
  3106. this_cpu_inc(perf_sched_cb_usages);
  3107. }
  3108. /*
  3109. * This function provides the context switch callback to the lower code
  3110. * layer. It is invoked ONLY when the context switch callback is enabled.
  3111. *
  3112. * This callback is relevant even to per-cpu events; for example multi event
  3113. * PEBS requires this to provide PID/TID information. This requires we flush
  3114. * all queued PEBS records before we context switch to a new task.
  3115. */
  3116. static void __perf_pmu_sched_task(struct perf_cpu_pmu_context *cpc, bool sched_in)
  3117. {
  3118. struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
  3119. struct pmu *pmu;
  3120. pmu = cpc->epc.pmu;
  3121. /* software PMUs will not have sched_task */
  3122. if (WARN_ON_ONCE(!pmu->sched_task))
  3123. return;
  3124. perf_ctx_lock(cpuctx, cpuctx->task_ctx);
  3125. perf_pmu_disable(pmu);
  3126. pmu->sched_task(cpc->task_epc, sched_in);
  3127. perf_pmu_enable(pmu);
  3128. perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
  3129. }
  3130. static void perf_pmu_sched_task(struct task_struct *prev,
  3131. struct task_struct *next,
  3132. bool sched_in)
  3133. {
  3134. struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
  3135. struct perf_cpu_pmu_context *cpc;
  3136. /* cpuctx->task_ctx will be handled in perf_event_context_sched_in/out */
  3137. if (prev == next || cpuctx->task_ctx)
  3138. return;
  3139. list_for_each_entry(cpc, this_cpu_ptr(&sched_cb_list), sched_cb_entry)
  3140. __perf_pmu_sched_task(cpc, sched_in);
  3141. }
  3142. static void perf_event_switch(struct task_struct *task,
  3143. struct task_struct *next_prev, bool sched_in);
  3144. /*
  3145. * Called from scheduler to remove the events of the current task,
  3146. * with interrupts disabled.
  3147. *
  3148. * We stop each event and update the event value in event->count.
  3149. *
  3150. * This does not protect us against NMI, but disable()
  3151. * sets the disabled bit in the control field of event _before_
  3152. * accessing the event control register. If a NMI hits, then it will
  3153. * not restart the event.
  3154. */
  3155. void __perf_event_task_sched_out(struct task_struct *task,
  3156. struct task_struct *next)
  3157. {
  3158. if (__this_cpu_read(perf_sched_cb_usages))
  3159. perf_pmu_sched_task(task, next, false);
  3160. if (atomic_read(&nr_switch_events))
  3161. perf_event_switch(task, next, false);
  3162. perf_event_context_sched_out(task, next);
  3163. /*
  3164. * if cgroup events exist on this CPU, then we need
  3165. * to check if we have to switch out PMU state.
  3166. * cgroup event are system-wide mode only
  3167. */
  3168. perf_cgroup_switch(next);
  3169. }
  3170. static bool perf_less_group_idx(const void *l, const void *r, void __always_unused *args)
  3171. {
  3172. const struct perf_event *le = *(const struct perf_event **)l;
  3173. const struct perf_event *re = *(const struct perf_event **)r;
  3174. return le->group_index < re->group_index;
  3175. }
  3176. static void swap_ptr(void *l, void *r, void __always_unused *args)
  3177. {
  3178. void **lp = l, **rp = r;
  3179. swap(*lp, *rp);
  3180. }
  3181. DEFINE_MIN_HEAP(struct perf_event *, perf_event_min_heap);
  3182. static const struct min_heap_callbacks perf_min_heap = {
  3183. .less = perf_less_group_idx,
  3184. .swp = swap_ptr,
  3185. };
  3186. static void __heap_add(struct perf_event_min_heap *heap, struct perf_event *event)
  3187. {
  3188. struct perf_event **itrs = heap->data;
  3189. if (event) {
  3190. itrs[heap->nr] = event;
  3191. heap->nr++;
  3192. }
  3193. }
  3194. static void __link_epc(struct perf_event_pmu_context *pmu_ctx)
  3195. {
  3196. struct perf_cpu_pmu_context *cpc;
  3197. if (!pmu_ctx->ctx->task)
  3198. return;
  3199. cpc = this_cpu_ptr(pmu_ctx->pmu->cpu_pmu_context);
  3200. WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx);
  3201. cpc->task_epc = pmu_ctx;
  3202. }
  3203. static noinline int visit_groups_merge(struct perf_event_context *ctx,
  3204. struct perf_event_groups *groups, int cpu,
  3205. struct pmu *pmu,
  3206. int (*func)(struct perf_event *, void *),
  3207. void *data)
  3208. {
  3209. #ifdef CONFIG_CGROUP_PERF
  3210. struct cgroup_subsys_state *css = NULL;
  3211. #endif
  3212. struct perf_cpu_context *cpuctx = NULL;
  3213. /* Space for per CPU and/or any CPU event iterators. */
  3214. struct perf_event *itrs[2];
  3215. struct perf_event_min_heap event_heap;
  3216. struct perf_event **evt;
  3217. int ret;
  3218. if (pmu->filter && pmu->filter(pmu, cpu))
  3219. return 0;
  3220. if (!ctx->task) {
  3221. cpuctx = this_cpu_ptr(&perf_cpu_context);
  3222. event_heap = (struct perf_event_min_heap){
  3223. .data = cpuctx->heap,
  3224. .nr = 0,
  3225. .size = cpuctx->heap_size,
  3226. };
  3227. lockdep_assert_held(&cpuctx->ctx.lock);
  3228. #ifdef CONFIG_CGROUP_PERF
  3229. if (cpuctx->cgrp)
  3230. css = &cpuctx->cgrp->css;
  3231. #endif
  3232. } else {
  3233. event_heap = (struct perf_event_min_heap){
  3234. .data = itrs,
  3235. .nr = 0,
  3236. .size = ARRAY_SIZE(itrs),
  3237. };
  3238. /* Events not within a CPU context may be on any CPU. */
  3239. __heap_add(&event_heap, perf_event_groups_first(groups, -1, pmu, NULL));
  3240. }
  3241. evt = event_heap.data;
  3242. __heap_add(&event_heap, perf_event_groups_first(groups, cpu, pmu, NULL));
  3243. #ifdef CONFIG_CGROUP_PERF
  3244. for (; css; css = css->parent)
  3245. __heap_add(&event_heap, perf_event_groups_first(groups, cpu, pmu, css->cgroup));
  3246. #endif
  3247. if (event_heap.nr) {
  3248. __link_epc((*evt)->pmu_ctx);
  3249. perf_assert_pmu_disabled((*evt)->pmu_ctx->pmu);
  3250. }
  3251. min_heapify_all(&event_heap, &perf_min_heap, NULL);
  3252. while (event_heap.nr) {
  3253. ret = func(*evt, data);
  3254. if (ret)
  3255. return ret;
  3256. *evt = perf_event_groups_next(*evt, pmu);
  3257. if (*evt)
  3258. min_heap_sift_down(&event_heap, 0, &perf_min_heap, NULL);
  3259. else
  3260. min_heap_pop(&event_heap, &perf_min_heap, NULL);
  3261. }
  3262. return 0;
  3263. }
  3264. /*
  3265. * Because the userpage is strictly per-event (there is no concept of context,
  3266. * so there cannot be a context indirection), every userpage must be updated
  3267. * when context time starts :-(
  3268. *
  3269. * IOW, we must not miss EVENT_TIME edges.
  3270. */
  3271. static inline bool event_update_userpage(struct perf_event *event)
  3272. {
  3273. if (likely(!atomic_read(&event->mmap_count)))
  3274. return false;
  3275. perf_event_update_time(event);
  3276. perf_event_update_userpage(event);
  3277. return true;
  3278. }
  3279. static inline void group_update_userpage(struct perf_event *group_event)
  3280. {
  3281. struct perf_event *event;
  3282. if (!event_update_userpage(group_event))
  3283. return;
  3284. for_each_sibling_event(event, group_event)
  3285. event_update_userpage(event);
  3286. }
  3287. static int merge_sched_in(struct perf_event *event, void *data)
  3288. {
  3289. struct perf_event_context *ctx = event->ctx;
  3290. int *can_add_hw = data;
  3291. if (event->state <= PERF_EVENT_STATE_OFF)
  3292. return 0;
  3293. if (!event_filter_match(event))
  3294. return 0;
  3295. if (group_can_go_on(event, *can_add_hw)) {
  3296. if (!group_sched_in(event, ctx))
  3297. list_add_tail(&event->active_list, get_event_list(event));
  3298. }
  3299. if (event->state == PERF_EVENT_STATE_INACTIVE) {
  3300. *can_add_hw = 0;
  3301. if (event->attr.pinned) {
  3302. perf_cgroup_event_disable(event, ctx);
  3303. perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
  3304. } else {
  3305. struct perf_cpu_pmu_context *cpc;
  3306. event->pmu_ctx->rotate_necessary = 1;
  3307. cpc = this_cpu_ptr(event->pmu_ctx->pmu->cpu_pmu_context);
  3308. perf_mux_hrtimer_restart(cpc);
  3309. group_update_userpage(event);
  3310. }
  3311. }
  3312. return 0;
  3313. }
  3314. static void pmu_groups_sched_in(struct perf_event_context *ctx,
  3315. struct perf_event_groups *groups,
  3316. struct pmu *pmu)
  3317. {
  3318. int can_add_hw = 1;
  3319. visit_groups_merge(ctx, groups, smp_processor_id(), pmu,
  3320. merge_sched_in, &can_add_hw);
  3321. }
  3322. static void __pmu_ctx_sched_in(struct perf_event_pmu_context *pmu_ctx,
  3323. enum event_type_t event_type)
  3324. {
  3325. struct perf_event_context *ctx = pmu_ctx->ctx;
  3326. if (event_type & EVENT_PINNED)
  3327. pmu_groups_sched_in(ctx, &ctx->pinned_groups, pmu_ctx->pmu);
  3328. if (event_type & EVENT_FLEXIBLE)
  3329. pmu_groups_sched_in(ctx, &ctx->flexible_groups, pmu_ctx->pmu);
  3330. }
  3331. static void
  3332. ctx_sched_in(struct perf_event_context *ctx, struct pmu *pmu, enum event_type_t event_type)
  3333. {
  3334. struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
  3335. struct perf_event_pmu_context *pmu_ctx;
  3336. int is_active = ctx->is_active;
  3337. bool cgroup = event_type & EVENT_CGROUP;
  3338. event_type &= ~EVENT_CGROUP;
  3339. lockdep_assert_held(&ctx->lock);
  3340. if (likely(!ctx->nr_events))
  3341. return;
  3342. if (!(is_active & EVENT_TIME)) {
  3343. /* start ctx time */
  3344. __update_context_time(ctx, false);
  3345. perf_cgroup_set_timestamp(cpuctx);
  3346. /*
  3347. * CPU-release for the below ->is_active store,
  3348. * see __load_acquire() in perf_event_time_now()
  3349. */
  3350. barrier();
  3351. }
  3352. ctx->is_active |= (event_type | EVENT_TIME);
  3353. if (ctx->task) {
  3354. if (!(is_active & EVENT_ALL))
  3355. cpuctx->task_ctx = ctx;
  3356. else
  3357. WARN_ON_ONCE(cpuctx->task_ctx != ctx);
  3358. }
  3359. is_active ^= ctx->is_active; /* changed bits */
  3360. /*
  3361. * First go through the list and put on any pinned groups
  3362. * in order to give them the best chance of going on.
  3363. */
  3364. if (is_active & EVENT_PINNED) {
  3365. for_each_epc(pmu_ctx, ctx, pmu, cgroup)
  3366. __pmu_ctx_sched_in(pmu_ctx, EVENT_PINNED);
  3367. }
  3368. /* Then walk through the lower prio flexible groups */
  3369. if (is_active & EVENT_FLEXIBLE) {
  3370. for_each_epc(pmu_ctx, ctx, pmu, cgroup)
  3371. __pmu_ctx_sched_in(pmu_ctx, EVENT_FLEXIBLE);
  3372. }
  3373. }
  3374. static void perf_event_context_sched_in(struct task_struct *task)
  3375. {
  3376. struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
  3377. struct perf_event_context *ctx;
  3378. rcu_read_lock();
  3379. ctx = rcu_dereference(task->perf_event_ctxp);
  3380. if (!ctx)
  3381. goto rcu_unlock;
  3382. if (cpuctx->task_ctx == ctx) {
  3383. perf_ctx_lock(cpuctx, ctx);
  3384. perf_ctx_disable(ctx, false);
  3385. perf_ctx_sched_task_cb(ctx, true);
  3386. perf_ctx_enable(ctx, false);
  3387. perf_ctx_unlock(cpuctx, ctx);
  3388. goto rcu_unlock;
  3389. }
  3390. perf_ctx_lock(cpuctx, ctx);
  3391. /*
  3392. * We must check ctx->nr_events while holding ctx->lock, such
  3393. * that we serialize against perf_install_in_context().
  3394. */
  3395. if (!ctx->nr_events)
  3396. goto unlock;
  3397. perf_ctx_disable(ctx, false);
  3398. /*
  3399. * We want to keep the following priority order:
  3400. * cpu pinned (that don't need to move), task pinned,
  3401. * cpu flexible, task flexible.
  3402. *
  3403. * However, if task's ctx is not carrying any pinned
  3404. * events, no need to flip the cpuctx's events around.
  3405. */
  3406. if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree)) {
  3407. perf_ctx_disable(&cpuctx->ctx, false);
  3408. ctx_sched_out(&cpuctx->ctx, NULL, EVENT_FLEXIBLE);
  3409. }
  3410. perf_event_sched_in(cpuctx, ctx, NULL);
  3411. perf_ctx_sched_task_cb(cpuctx->task_ctx, true);
  3412. if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree))
  3413. perf_ctx_enable(&cpuctx->ctx, false);
  3414. perf_ctx_enable(ctx, false);
  3415. unlock:
  3416. perf_ctx_unlock(cpuctx, ctx);
  3417. rcu_unlock:
  3418. rcu_read_unlock();
  3419. }
  3420. /*
  3421. * Called from scheduler to add the events of the current task
  3422. * with interrupts disabled.
  3423. *
  3424. * We restore the event value and then enable it.
  3425. *
  3426. * This does not protect us against NMI, but enable()
  3427. * sets the enabled bit in the control field of event _before_
  3428. * accessing the event control register. If a NMI hits, then it will
  3429. * keep the event running.
  3430. */
  3431. void __perf_event_task_sched_in(struct task_struct *prev,
  3432. struct task_struct *task)
  3433. {
  3434. perf_event_context_sched_in(task);
  3435. if (atomic_read(&nr_switch_events))
  3436. perf_event_switch(task, prev, true);
  3437. if (__this_cpu_read(perf_sched_cb_usages))
  3438. perf_pmu_sched_task(prev, task, true);
  3439. }
  3440. static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
  3441. {
  3442. u64 frequency = event->attr.sample_freq;
  3443. u64 sec = NSEC_PER_SEC;
  3444. u64 divisor, dividend;
  3445. int count_fls, nsec_fls, frequency_fls, sec_fls;
  3446. count_fls = fls64(count);
  3447. nsec_fls = fls64(nsec);
  3448. frequency_fls = fls64(frequency);
  3449. sec_fls = 30;
  3450. /*
  3451. * We got @count in @nsec, with a target of sample_freq HZ
  3452. * the target period becomes:
  3453. *
  3454. * @count * 10^9
  3455. * period = -------------------
  3456. * @nsec * sample_freq
  3457. *
  3458. */
  3459. /*
  3460. * Reduce accuracy by one bit such that @a and @b converge
  3461. * to a similar magnitude.
  3462. */
  3463. #define REDUCE_FLS(a, b) \
  3464. do { \
  3465. if (a##_fls > b##_fls) { \
  3466. a >>= 1; \
  3467. a##_fls--; \
  3468. } else { \
  3469. b >>= 1; \
  3470. b##_fls--; \
  3471. } \
  3472. } while (0)
  3473. /*
  3474. * Reduce accuracy until either term fits in a u64, then proceed with
  3475. * the other, so that finally we can do a u64/u64 division.
  3476. */
  3477. while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
  3478. REDUCE_FLS(nsec, frequency);
  3479. REDUCE_FLS(sec, count);
  3480. }
  3481. if (count_fls + sec_fls > 64) {
  3482. divisor = nsec * frequency;
  3483. while (count_fls + sec_fls > 64) {
  3484. REDUCE_FLS(count, sec);
  3485. divisor >>= 1;
  3486. }
  3487. dividend = count * sec;
  3488. } else {
  3489. dividend = count * sec;
  3490. while (nsec_fls + frequency_fls > 64) {
  3491. REDUCE_FLS(nsec, frequency);
  3492. dividend >>= 1;
  3493. }
  3494. divisor = nsec * frequency;
  3495. }
  3496. if (!divisor)
  3497. return dividend;
  3498. return div64_u64(dividend, divisor);
  3499. }
  3500. static DEFINE_PER_CPU(int, perf_throttled_count);
  3501. static DEFINE_PER_CPU(u64, perf_throttled_seq);
  3502. static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
  3503. {
  3504. struct hw_perf_event *hwc = &event->hw;
  3505. s64 period, sample_period;
  3506. s64 delta;
  3507. period = perf_calculate_period(event, nsec, count);
  3508. delta = (s64)(period - hwc->sample_period);
  3509. if (delta >= 0)
  3510. delta += 7;
  3511. else
  3512. delta -= 7;
  3513. delta /= 8; /* low pass filter */
  3514. sample_period = hwc->sample_period + delta;
  3515. if (!sample_period)
  3516. sample_period = 1;
  3517. hwc->sample_period = sample_period;
  3518. if (local64_read(&hwc->period_left) > 8*sample_period) {
  3519. if (disable)
  3520. event->pmu->stop(event, PERF_EF_UPDATE);
  3521. local64_set(&hwc->period_left, 0);
  3522. if (disable)
  3523. event->pmu->start(event, PERF_EF_RELOAD);
  3524. }
  3525. }
  3526. static void perf_adjust_freq_unthr_events(struct list_head *event_list)
  3527. {
  3528. struct perf_event *event;
  3529. struct hw_perf_event *hwc;
  3530. u64 now, period = TICK_NSEC;
  3531. s64 delta;
  3532. list_for_each_entry(event, event_list, active_list) {
  3533. if (event->state != PERF_EVENT_STATE_ACTIVE)
  3534. continue;
  3535. // XXX use visit thingy to avoid the -1,cpu match
  3536. if (!event_filter_match(event))
  3537. continue;
  3538. hwc = &event->hw;
  3539. if (hwc->interrupts == MAX_INTERRUPTS) {
  3540. hwc->interrupts = 0;
  3541. perf_log_throttle(event, 1);
  3542. if (!event->attr.freq || !event->attr.sample_freq)
  3543. event->pmu->start(event, 0);
  3544. }
  3545. if (!event->attr.freq || !event->attr.sample_freq)
  3546. continue;
  3547. /*
  3548. * stop the event and update event->count
  3549. */
  3550. event->pmu->stop(event, PERF_EF_UPDATE);
  3551. now = local64_read(&event->count);
  3552. delta = now - hwc->freq_count_stamp;
  3553. hwc->freq_count_stamp = now;
  3554. /*
  3555. * restart the event
  3556. * reload only if value has changed
  3557. * we have stopped the event so tell that
  3558. * to perf_adjust_period() to avoid stopping it
  3559. * twice.
  3560. */
  3561. if (delta > 0)
  3562. perf_adjust_period(event, period, delta, false);
  3563. event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
  3564. }
  3565. }
  3566. /*
  3567. * combine freq adjustment with unthrottling to avoid two passes over the
  3568. * events. At the same time, make sure, having freq events does not change
  3569. * the rate of unthrottling as that would introduce bias.
  3570. */
  3571. static void
  3572. perf_adjust_freq_unthr_context(struct perf_event_context *ctx, bool unthrottle)
  3573. {
  3574. struct perf_event_pmu_context *pmu_ctx;
  3575. /*
  3576. * only need to iterate over all events iff:
  3577. * - context have events in frequency mode (needs freq adjust)
  3578. * - there are events to unthrottle on this cpu
  3579. */
  3580. if (!(ctx->nr_freq || unthrottle))
  3581. return;
  3582. raw_spin_lock(&ctx->lock);
  3583. list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry) {
  3584. if (!(pmu_ctx->nr_freq || unthrottle))
  3585. continue;
  3586. if (!perf_pmu_ctx_is_active(pmu_ctx))
  3587. continue;
  3588. if (pmu_ctx->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT)
  3589. continue;
  3590. perf_pmu_disable(pmu_ctx->pmu);
  3591. perf_adjust_freq_unthr_events(&pmu_ctx->pinned_active);
  3592. perf_adjust_freq_unthr_events(&pmu_ctx->flexible_active);
  3593. perf_pmu_enable(pmu_ctx->pmu);
  3594. }
  3595. raw_spin_unlock(&ctx->lock);
  3596. }
  3597. /*
  3598. * Move @event to the tail of the @ctx's elegible events.
  3599. */
  3600. static void rotate_ctx(struct perf_event_context *ctx, struct perf_event *event)
  3601. {
  3602. /*
  3603. * Rotate the first entry last of non-pinned groups. Rotation might be
  3604. * disabled by the inheritance code.
  3605. */
  3606. if (ctx->rotate_disable)
  3607. return;
  3608. perf_event_groups_delete(&ctx->flexible_groups, event);
  3609. perf_event_groups_insert(&ctx->flexible_groups, event);
  3610. }
  3611. /* pick an event from the flexible_groups to rotate */
  3612. static inline struct perf_event *
  3613. ctx_event_to_rotate(struct perf_event_pmu_context *pmu_ctx)
  3614. {
  3615. struct perf_event *event;
  3616. struct rb_node *node;
  3617. struct rb_root *tree;
  3618. struct __group_key key = {
  3619. .pmu = pmu_ctx->pmu,
  3620. };
  3621. /* pick the first active flexible event */
  3622. event = list_first_entry_or_null(&pmu_ctx->flexible_active,
  3623. struct perf_event, active_list);
  3624. if (event)
  3625. goto out;
  3626. /* if no active flexible event, pick the first event */
  3627. tree = &pmu_ctx->ctx->flexible_groups.tree;
  3628. if (!pmu_ctx->ctx->task) {
  3629. key.cpu = smp_processor_id();
  3630. node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup);
  3631. if (node)
  3632. event = __node_2_pe(node);
  3633. goto out;
  3634. }
  3635. key.cpu = -1;
  3636. node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup);
  3637. if (node) {
  3638. event = __node_2_pe(node);
  3639. goto out;
  3640. }
  3641. key.cpu = smp_processor_id();
  3642. node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup);
  3643. if (node)
  3644. event = __node_2_pe(node);
  3645. out:
  3646. /*
  3647. * Unconditionally clear rotate_necessary; if ctx_flexible_sched_in()
  3648. * finds there are unschedulable events, it will set it again.
  3649. */
  3650. pmu_ctx->rotate_necessary = 0;
  3651. return event;
  3652. }
  3653. static bool perf_rotate_context(struct perf_cpu_pmu_context *cpc)
  3654. {
  3655. struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
  3656. struct perf_event_pmu_context *cpu_epc, *task_epc = NULL;
  3657. struct perf_event *cpu_event = NULL, *task_event = NULL;
  3658. int cpu_rotate, task_rotate;
  3659. struct pmu *pmu;
  3660. /*
  3661. * Since we run this from IRQ context, nobody can install new
  3662. * events, thus the event count values are stable.
  3663. */
  3664. cpu_epc = &cpc->epc;
  3665. pmu = cpu_epc->pmu;
  3666. task_epc = cpc->task_epc;
  3667. cpu_rotate = cpu_epc->rotate_necessary;
  3668. task_rotate = task_epc ? task_epc->rotate_necessary : 0;
  3669. if (!(cpu_rotate || task_rotate))
  3670. return false;
  3671. perf_ctx_lock(cpuctx, cpuctx->task_ctx);
  3672. perf_pmu_disable(pmu);
  3673. if (task_rotate)
  3674. task_event = ctx_event_to_rotate(task_epc);
  3675. if (cpu_rotate)
  3676. cpu_event = ctx_event_to_rotate(cpu_epc);
  3677. /*
  3678. * As per the order given at ctx_resched() first 'pop' task flexible
  3679. * and then, if needed CPU flexible.
  3680. */
  3681. if (task_event || (task_epc && cpu_event)) {
  3682. update_context_time(task_epc->ctx);
  3683. __pmu_ctx_sched_out(task_epc, EVENT_FLEXIBLE);
  3684. }
  3685. if (cpu_event) {
  3686. update_context_time(&cpuctx->ctx);
  3687. __pmu_ctx_sched_out(cpu_epc, EVENT_FLEXIBLE);
  3688. rotate_ctx(&cpuctx->ctx, cpu_event);
  3689. __pmu_ctx_sched_in(cpu_epc, EVENT_FLEXIBLE);
  3690. }
  3691. if (task_event)
  3692. rotate_ctx(task_epc->ctx, task_event);
  3693. if (task_event || (task_epc && cpu_event))
  3694. __pmu_ctx_sched_in(task_epc, EVENT_FLEXIBLE);
  3695. perf_pmu_enable(pmu);
  3696. perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
  3697. return true;
  3698. }
  3699. void perf_event_task_tick(void)
  3700. {
  3701. struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
  3702. struct perf_event_context *ctx;
  3703. int throttled;
  3704. lockdep_assert_irqs_disabled();
  3705. __this_cpu_inc(perf_throttled_seq);
  3706. throttled = __this_cpu_xchg(perf_throttled_count, 0);
  3707. tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
  3708. perf_adjust_freq_unthr_context(&cpuctx->ctx, !!throttled);
  3709. rcu_read_lock();
  3710. ctx = rcu_dereference(current->perf_event_ctxp);
  3711. if (ctx)
  3712. perf_adjust_freq_unthr_context(ctx, !!throttled);
  3713. rcu_read_unlock();
  3714. }
  3715. static int event_enable_on_exec(struct perf_event *event,
  3716. struct perf_event_context *ctx)
  3717. {
  3718. if (!event->attr.enable_on_exec)
  3719. return 0;
  3720. event->attr.enable_on_exec = 0;
  3721. if (event->state >= PERF_EVENT_STATE_INACTIVE)
  3722. return 0;
  3723. perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
  3724. return 1;
  3725. }
  3726. /*
  3727. * Enable all of a task's events that have been marked enable-on-exec.
  3728. * This expects task == current.
  3729. */
  3730. static void perf_event_enable_on_exec(struct perf_event_context *ctx)
  3731. {
  3732. struct perf_event_context *clone_ctx = NULL;
  3733. enum event_type_t event_type = 0;
  3734. struct perf_cpu_context *cpuctx;
  3735. struct perf_event *event;
  3736. unsigned long flags;
  3737. int enabled = 0;
  3738. local_irq_save(flags);
  3739. if (WARN_ON_ONCE(current->perf_event_ctxp != ctx))
  3740. goto out;
  3741. if (!ctx->nr_events)
  3742. goto out;
  3743. cpuctx = this_cpu_ptr(&perf_cpu_context);
  3744. perf_ctx_lock(cpuctx, ctx);
  3745. ctx_time_freeze(cpuctx, ctx);
  3746. list_for_each_entry(event, &ctx->event_list, event_entry) {
  3747. enabled |= event_enable_on_exec(event, ctx);
  3748. event_type |= get_event_type(event);
  3749. }
  3750. /*
  3751. * Unclone and reschedule this context if we enabled any event.
  3752. */
  3753. if (enabled) {
  3754. clone_ctx = unclone_ctx(ctx);
  3755. ctx_resched(cpuctx, ctx, NULL, event_type);
  3756. }
  3757. perf_ctx_unlock(cpuctx, ctx);
  3758. out:
  3759. local_irq_restore(flags);
  3760. if (clone_ctx)
  3761. put_ctx(clone_ctx);
  3762. }
  3763. static void perf_remove_from_owner(struct perf_event *event);
  3764. static void perf_event_exit_event(struct perf_event *event,
  3765. struct perf_event_context *ctx);
  3766. /*
  3767. * Removes all events from the current task that have been marked
  3768. * remove-on-exec, and feeds their values back to parent events.
  3769. */
  3770. static void perf_event_remove_on_exec(struct perf_event_context *ctx)
  3771. {
  3772. struct perf_event_context *clone_ctx = NULL;
  3773. struct perf_event *event, *next;
  3774. unsigned long flags;
  3775. bool modified = false;
  3776. mutex_lock(&ctx->mutex);
  3777. if (WARN_ON_ONCE(ctx->task != current))
  3778. goto unlock;
  3779. list_for_each_entry_safe(event, next, &ctx->event_list, event_entry) {
  3780. if (!event->attr.remove_on_exec)
  3781. continue;
  3782. if (!is_kernel_event(event))
  3783. perf_remove_from_owner(event);
  3784. modified = true;
  3785. perf_event_exit_event(event, ctx);
  3786. }
  3787. raw_spin_lock_irqsave(&ctx->lock, flags);
  3788. if (modified)
  3789. clone_ctx = unclone_ctx(ctx);
  3790. raw_spin_unlock_irqrestore(&ctx->lock, flags);
  3791. unlock:
  3792. mutex_unlock(&ctx->mutex);
  3793. if (clone_ctx)
  3794. put_ctx(clone_ctx);
  3795. }
  3796. struct perf_read_data {
  3797. struct perf_event *event;
  3798. bool group;
  3799. int ret;
  3800. };
  3801. static inline const struct cpumask *perf_scope_cpu_topology_cpumask(unsigned int scope, int cpu);
  3802. static int __perf_event_read_cpu(struct perf_event *event, int event_cpu)
  3803. {
  3804. int local_cpu = smp_processor_id();
  3805. u16 local_pkg, event_pkg;
  3806. if ((unsigned)event_cpu >= nr_cpu_ids)
  3807. return event_cpu;
  3808. if (event->group_caps & PERF_EV_CAP_READ_SCOPE) {
  3809. const struct cpumask *cpumask = perf_scope_cpu_topology_cpumask(event->pmu->scope, event_cpu);
  3810. if (cpumask && cpumask_test_cpu(local_cpu, cpumask))
  3811. return local_cpu;
  3812. }
  3813. if (event->group_caps & PERF_EV_CAP_READ_ACTIVE_PKG) {
  3814. event_pkg = topology_physical_package_id(event_cpu);
  3815. local_pkg = topology_physical_package_id(local_cpu);
  3816. if (event_pkg == local_pkg)
  3817. return local_cpu;
  3818. }
  3819. return event_cpu;
  3820. }
  3821. /*
  3822. * Cross CPU call to read the hardware event
  3823. */
  3824. static void __perf_event_read(void *info)
  3825. {
  3826. struct perf_read_data *data = info;
  3827. struct perf_event *sub, *event = data->event;
  3828. struct perf_event_context *ctx = event->ctx;
  3829. struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
  3830. struct pmu *pmu = event->pmu;
  3831. /*
  3832. * If this is a task context, we need to check whether it is
  3833. * the current task context of this cpu. If not it has been
  3834. * scheduled out before the smp call arrived. In that case
  3835. * event->count would have been updated to a recent sample
  3836. * when the event was scheduled out.
  3837. */
  3838. if (ctx->task && cpuctx->task_ctx != ctx)
  3839. return;
  3840. raw_spin_lock(&ctx->lock);
  3841. ctx_time_update_event(ctx, event);
  3842. perf_event_update_time(event);
  3843. if (data->group)
  3844. perf_event_update_sibling_time(event);
  3845. if (event->state != PERF_EVENT_STATE_ACTIVE)
  3846. goto unlock;
  3847. if (!data->group) {
  3848. pmu->read(event);
  3849. data->ret = 0;
  3850. goto unlock;
  3851. }
  3852. pmu->start_txn(pmu, PERF_PMU_TXN_READ);
  3853. pmu->read(event);
  3854. for_each_sibling_event(sub, event)
  3855. perf_pmu_read(sub);
  3856. data->ret = pmu->commit_txn(pmu);
  3857. unlock:
  3858. raw_spin_unlock(&ctx->lock);
  3859. }
  3860. static inline u64 perf_event_count(struct perf_event *event, bool self)
  3861. {
  3862. if (self)
  3863. return local64_read(&event->count);
  3864. return local64_read(&event->count) + atomic64_read(&event->child_count);
  3865. }
  3866. static void calc_timer_values(struct perf_event *event,
  3867. u64 *now,
  3868. u64 *enabled,
  3869. u64 *running)
  3870. {
  3871. u64 ctx_time;
  3872. *now = perf_clock();
  3873. ctx_time = perf_event_time_now(event, *now);
  3874. __perf_update_times(event, ctx_time, enabled, running);
  3875. }
  3876. /*
  3877. * NMI-safe method to read a local event, that is an event that
  3878. * is:
  3879. * - either for the current task, or for this CPU
  3880. * - does not have inherit set, for inherited task events
  3881. * will not be local and we cannot read them atomically
  3882. * - must not have a pmu::count method
  3883. */
  3884. int perf_event_read_local(struct perf_event *event, u64 *value,
  3885. u64 *enabled, u64 *running)
  3886. {
  3887. unsigned long flags;
  3888. int event_oncpu;
  3889. int event_cpu;
  3890. int ret = 0;
  3891. /*
  3892. * Disabling interrupts avoids all counter scheduling (context
  3893. * switches, timer based rotation and IPIs).
  3894. */
  3895. local_irq_save(flags);
  3896. /*
  3897. * It must not be an event with inherit set, we cannot read
  3898. * all child counters from atomic context.
  3899. */
  3900. if (event->attr.inherit) {
  3901. ret = -EOPNOTSUPP;
  3902. goto out;
  3903. }
  3904. /* If this is a per-task event, it must be for current */
  3905. if ((event->attach_state & PERF_ATTACH_TASK) &&
  3906. event->hw.target != current) {
  3907. ret = -EINVAL;
  3908. goto out;
  3909. }
  3910. /*
  3911. * Get the event CPU numbers, and adjust them to local if the event is
  3912. * a per-package event that can be read locally
  3913. */
  3914. event_oncpu = __perf_event_read_cpu(event, event->oncpu);
  3915. event_cpu = __perf_event_read_cpu(event, event->cpu);
  3916. /* If this is a per-CPU event, it must be for this CPU */
  3917. if (!(event->attach_state & PERF_ATTACH_TASK) &&
  3918. event_cpu != smp_processor_id()) {
  3919. ret = -EINVAL;
  3920. goto out;
  3921. }
  3922. /* If this is a pinned event it must be running on this CPU */
  3923. if (event->attr.pinned && event_oncpu != smp_processor_id()) {
  3924. ret = -EBUSY;
  3925. goto out;
  3926. }
  3927. /*
  3928. * If the event is currently on this CPU, its either a per-task event,
  3929. * or local to this CPU. Furthermore it means its ACTIVE (otherwise
  3930. * oncpu == -1).
  3931. */
  3932. if (event_oncpu == smp_processor_id())
  3933. event->pmu->read(event);
  3934. *value = local64_read(&event->count);
  3935. if (enabled || running) {
  3936. u64 __enabled, __running, __now;
  3937. calc_timer_values(event, &__now, &__enabled, &__running);
  3938. if (enabled)
  3939. *enabled = __enabled;
  3940. if (running)
  3941. *running = __running;
  3942. }
  3943. out:
  3944. local_irq_restore(flags);
  3945. return ret;
  3946. }
  3947. static int perf_event_read(struct perf_event *event, bool group)
  3948. {
  3949. enum perf_event_state state = READ_ONCE(event->state);
  3950. int event_cpu, ret = 0;
  3951. /*
  3952. * If event is enabled and currently active on a CPU, update the
  3953. * value in the event structure:
  3954. */
  3955. again:
  3956. if (state == PERF_EVENT_STATE_ACTIVE) {
  3957. struct perf_read_data data;
  3958. /*
  3959. * Orders the ->state and ->oncpu loads such that if we see
  3960. * ACTIVE we must also see the right ->oncpu.
  3961. *
  3962. * Matches the smp_wmb() from event_sched_in().
  3963. */
  3964. smp_rmb();
  3965. event_cpu = READ_ONCE(event->oncpu);
  3966. if ((unsigned)event_cpu >= nr_cpu_ids)
  3967. return 0;
  3968. data = (struct perf_read_data){
  3969. .event = event,
  3970. .group = group,
  3971. .ret = 0,
  3972. };
  3973. preempt_disable();
  3974. event_cpu = __perf_event_read_cpu(event, event_cpu);
  3975. /*
  3976. * Purposely ignore the smp_call_function_single() return
  3977. * value.
  3978. *
  3979. * If event_cpu isn't a valid CPU it means the event got
  3980. * scheduled out and that will have updated the event count.
  3981. *
  3982. * Therefore, either way, we'll have an up-to-date event count
  3983. * after this.
  3984. */
  3985. (void)smp_call_function_single(event_cpu, __perf_event_read, &data, 1);
  3986. preempt_enable();
  3987. ret = data.ret;
  3988. } else if (state == PERF_EVENT_STATE_INACTIVE) {
  3989. struct perf_event_context *ctx = event->ctx;
  3990. unsigned long flags;
  3991. raw_spin_lock_irqsave(&ctx->lock, flags);
  3992. state = event->state;
  3993. if (state != PERF_EVENT_STATE_INACTIVE) {
  3994. raw_spin_unlock_irqrestore(&ctx->lock, flags);
  3995. goto again;
  3996. }
  3997. /*
  3998. * May read while context is not active (e.g., thread is
  3999. * blocked), in that case we cannot update context time
  4000. */
  4001. ctx_time_update_event(ctx, event);
  4002. perf_event_update_time(event);
  4003. if (group)
  4004. perf_event_update_sibling_time(event);
  4005. raw_spin_unlock_irqrestore(&ctx->lock, flags);
  4006. }
  4007. return ret;
  4008. }
  4009. /*
  4010. * Initialize the perf_event context in a task_struct:
  4011. */
  4012. static void __perf_event_init_context(struct perf_event_context *ctx)
  4013. {
  4014. raw_spin_lock_init(&ctx->lock);
  4015. mutex_init(&ctx->mutex);
  4016. INIT_LIST_HEAD(&ctx->pmu_ctx_list);
  4017. perf_event_groups_init(&ctx->pinned_groups);
  4018. perf_event_groups_init(&ctx->flexible_groups);
  4019. INIT_LIST_HEAD(&ctx->event_list);
  4020. refcount_set(&ctx->refcount, 1);
  4021. }
  4022. static void
  4023. __perf_init_event_pmu_context(struct perf_event_pmu_context *epc, struct pmu *pmu)
  4024. {
  4025. epc->pmu = pmu;
  4026. INIT_LIST_HEAD(&epc->pmu_ctx_entry);
  4027. INIT_LIST_HEAD(&epc->pinned_active);
  4028. INIT_LIST_HEAD(&epc->flexible_active);
  4029. atomic_set(&epc->refcount, 1);
  4030. }
  4031. static struct perf_event_context *
  4032. alloc_perf_context(struct task_struct *task)
  4033. {
  4034. struct perf_event_context *ctx;
  4035. ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
  4036. if (!ctx)
  4037. return NULL;
  4038. __perf_event_init_context(ctx);
  4039. if (task)
  4040. ctx->task = get_task_struct(task);
  4041. return ctx;
  4042. }
  4043. static struct task_struct *
  4044. find_lively_task_by_vpid(pid_t vpid)
  4045. {
  4046. struct task_struct *task;
  4047. rcu_read_lock();
  4048. if (!vpid)
  4049. task = current;
  4050. else
  4051. task = find_task_by_vpid(vpid);
  4052. if (task)
  4053. get_task_struct(task);
  4054. rcu_read_unlock();
  4055. if (!task)
  4056. return ERR_PTR(-ESRCH);
  4057. return task;
  4058. }
  4059. /*
  4060. * Returns a matching context with refcount and pincount.
  4061. */
  4062. static struct perf_event_context *
  4063. find_get_context(struct task_struct *task, struct perf_event *event)
  4064. {
  4065. struct perf_event_context *ctx, *clone_ctx = NULL;
  4066. struct perf_cpu_context *cpuctx;
  4067. unsigned long flags;
  4068. int err;
  4069. if (!task) {
  4070. /* Must be root to operate on a CPU event: */
  4071. err = perf_allow_cpu(&event->attr);
  4072. if (err)
  4073. return ERR_PTR(err);
  4074. cpuctx = per_cpu_ptr(&perf_cpu_context, event->cpu);
  4075. ctx = &cpuctx->ctx;
  4076. get_ctx(ctx);
  4077. raw_spin_lock_irqsave(&ctx->lock, flags);
  4078. ++ctx->pin_count;
  4079. raw_spin_unlock_irqrestore(&ctx->lock, flags);
  4080. return ctx;
  4081. }
  4082. err = -EINVAL;
  4083. retry:
  4084. ctx = perf_lock_task_context(task, &flags);
  4085. if (ctx) {
  4086. clone_ctx = unclone_ctx(ctx);
  4087. ++ctx->pin_count;
  4088. raw_spin_unlock_irqrestore(&ctx->lock, flags);
  4089. if (clone_ctx)
  4090. put_ctx(clone_ctx);
  4091. } else {
  4092. ctx = alloc_perf_context(task);
  4093. err = -ENOMEM;
  4094. if (!ctx)
  4095. goto errout;
  4096. err = 0;
  4097. mutex_lock(&task->perf_event_mutex);
  4098. /*
  4099. * If it has already passed perf_event_exit_task().
  4100. * we must see PF_EXITING, it takes this mutex too.
  4101. */
  4102. if (task->flags & PF_EXITING)
  4103. err = -ESRCH;
  4104. else if (task->perf_event_ctxp)
  4105. err = -EAGAIN;
  4106. else {
  4107. get_ctx(ctx);
  4108. ++ctx->pin_count;
  4109. rcu_assign_pointer(task->perf_event_ctxp, ctx);
  4110. }
  4111. mutex_unlock(&task->perf_event_mutex);
  4112. if (unlikely(err)) {
  4113. put_ctx(ctx);
  4114. if (err == -EAGAIN)
  4115. goto retry;
  4116. goto errout;
  4117. }
  4118. }
  4119. return ctx;
  4120. errout:
  4121. return ERR_PTR(err);
  4122. }
  4123. static struct perf_event_pmu_context *
  4124. find_get_pmu_context(struct pmu *pmu, struct perf_event_context *ctx,
  4125. struct perf_event *event)
  4126. {
  4127. struct perf_event_pmu_context *new = NULL, *pos = NULL, *epc;
  4128. void *task_ctx_data = NULL;
  4129. if (!ctx->task) {
  4130. /*
  4131. * perf_pmu_migrate_context() / __perf_pmu_install_event()
  4132. * relies on the fact that find_get_pmu_context() cannot fail
  4133. * for CPU contexts.
  4134. */
  4135. struct perf_cpu_pmu_context *cpc;
  4136. cpc = per_cpu_ptr(pmu->cpu_pmu_context, event->cpu);
  4137. epc = &cpc->epc;
  4138. raw_spin_lock_irq(&ctx->lock);
  4139. if (!epc->ctx) {
  4140. atomic_set(&epc->refcount, 1);
  4141. epc->embedded = 1;
  4142. list_add(&epc->pmu_ctx_entry, &ctx->pmu_ctx_list);
  4143. epc->ctx = ctx;
  4144. } else {
  4145. WARN_ON_ONCE(epc->ctx != ctx);
  4146. atomic_inc(&epc->refcount);
  4147. }
  4148. raw_spin_unlock_irq(&ctx->lock);
  4149. return epc;
  4150. }
  4151. new = kzalloc(sizeof(*epc), GFP_KERNEL);
  4152. if (!new)
  4153. return ERR_PTR(-ENOMEM);
  4154. if (event->attach_state & PERF_ATTACH_TASK_DATA) {
  4155. task_ctx_data = alloc_task_ctx_data(pmu);
  4156. if (!task_ctx_data) {
  4157. kfree(new);
  4158. return ERR_PTR(-ENOMEM);
  4159. }
  4160. }
  4161. __perf_init_event_pmu_context(new, pmu);
  4162. /*
  4163. * XXX
  4164. *
  4165. * lockdep_assert_held(&ctx->mutex);
  4166. *
  4167. * can't because perf_event_init_task() doesn't actually hold the
  4168. * child_ctx->mutex.
  4169. */
  4170. raw_spin_lock_irq(&ctx->lock);
  4171. list_for_each_entry(epc, &ctx->pmu_ctx_list, pmu_ctx_entry) {
  4172. if (epc->pmu == pmu) {
  4173. WARN_ON_ONCE(epc->ctx != ctx);
  4174. atomic_inc(&epc->refcount);
  4175. goto found_epc;
  4176. }
  4177. /* Make sure the pmu_ctx_list is sorted by PMU type: */
  4178. if (!pos && epc->pmu->type > pmu->type)
  4179. pos = epc;
  4180. }
  4181. epc = new;
  4182. new = NULL;
  4183. if (!pos)
  4184. list_add_tail(&epc->pmu_ctx_entry, &ctx->pmu_ctx_list);
  4185. else
  4186. list_add(&epc->pmu_ctx_entry, pos->pmu_ctx_entry.prev);
  4187. epc->ctx = ctx;
  4188. found_epc:
  4189. if (task_ctx_data && !epc->task_ctx_data) {
  4190. epc->task_ctx_data = task_ctx_data;
  4191. task_ctx_data = NULL;
  4192. ctx->nr_task_data++;
  4193. }
  4194. raw_spin_unlock_irq(&ctx->lock);
  4195. free_task_ctx_data(pmu, task_ctx_data);
  4196. kfree(new);
  4197. return epc;
  4198. }
  4199. static void get_pmu_ctx(struct perf_event_pmu_context *epc)
  4200. {
  4201. WARN_ON_ONCE(!atomic_inc_not_zero(&epc->refcount));
  4202. }
  4203. static void free_epc_rcu(struct rcu_head *head)
  4204. {
  4205. struct perf_event_pmu_context *epc = container_of(head, typeof(*epc), rcu_head);
  4206. kfree(epc->task_ctx_data);
  4207. kfree(epc);
  4208. }
  4209. static void put_pmu_ctx(struct perf_event_pmu_context *epc)
  4210. {
  4211. struct perf_event_context *ctx = epc->ctx;
  4212. unsigned long flags;
  4213. /*
  4214. * XXX
  4215. *
  4216. * lockdep_assert_held(&ctx->mutex);
  4217. *
  4218. * can't because of the call-site in _free_event()/put_event()
  4219. * which isn't always called under ctx->mutex.
  4220. */
  4221. if (!atomic_dec_and_raw_lock_irqsave(&epc->refcount, &ctx->lock, flags))
  4222. return;
  4223. WARN_ON_ONCE(list_empty(&epc->pmu_ctx_entry));
  4224. list_del_init(&epc->pmu_ctx_entry);
  4225. epc->ctx = NULL;
  4226. WARN_ON_ONCE(!list_empty(&epc->pinned_active));
  4227. WARN_ON_ONCE(!list_empty(&epc->flexible_active));
  4228. raw_spin_unlock_irqrestore(&ctx->lock, flags);
  4229. if (epc->embedded)
  4230. return;
  4231. call_rcu(&epc->rcu_head, free_epc_rcu);
  4232. }
  4233. static void perf_event_free_filter(struct perf_event *event);
  4234. static void free_event_rcu(struct rcu_head *head)
  4235. {
  4236. struct perf_event *event = container_of(head, typeof(*event), rcu_head);
  4237. if (event->ns)
  4238. put_pid_ns(event->ns);
  4239. perf_event_free_filter(event);
  4240. kmem_cache_free(perf_event_cache, event);
  4241. }
  4242. static void ring_buffer_attach(struct perf_event *event,
  4243. struct perf_buffer *rb);
  4244. static void detach_sb_event(struct perf_event *event)
  4245. {
  4246. struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
  4247. raw_spin_lock(&pel->lock);
  4248. list_del_rcu(&event->sb_list);
  4249. raw_spin_unlock(&pel->lock);
  4250. }
  4251. static bool is_sb_event(struct perf_event *event)
  4252. {
  4253. struct perf_event_attr *attr = &event->attr;
  4254. if (event->parent)
  4255. return false;
  4256. if (event->attach_state & PERF_ATTACH_TASK)
  4257. return false;
  4258. if (attr->mmap || attr->mmap_data || attr->mmap2 ||
  4259. attr->comm || attr->comm_exec ||
  4260. attr->task || attr->ksymbol ||
  4261. attr->context_switch || attr->text_poke ||
  4262. attr->bpf_event)
  4263. return true;
  4264. return false;
  4265. }
  4266. static void unaccount_pmu_sb_event(struct perf_event *event)
  4267. {
  4268. if (is_sb_event(event))
  4269. detach_sb_event(event);
  4270. }
  4271. #ifdef CONFIG_NO_HZ_FULL
  4272. static DEFINE_SPINLOCK(nr_freq_lock);
  4273. #endif
  4274. static void unaccount_freq_event_nohz(void)
  4275. {
  4276. #ifdef CONFIG_NO_HZ_FULL
  4277. spin_lock(&nr_freq_lock);
  4278. if (atomic_dec_and_test(&nr_freq_events))
  4279. tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS);
  4280. spin_unlock(&nr_freq_lock);
  4281. #endif
  4282. }
  4283. static void unaccount_freq_event(void)
  4284. {
  4285. if (tick_nohz_full_enabled())
  4286. unaccount_freq_event_nohz();
  4287. else
  4288. atomic_dec(&nr_freq_events);
  4289. }
  4290. static void unaccount_event(struct perf_event *event)
  4291. {
  4292. bool dec = false;
  4293. if (event->parent)
  4294. return;
  4295. if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB))
  4296. dec = true;
  4297. if (event->attr.mmap || event->attr.mmap_data)
  4298. atomic_dec(&nr_mmap_events);
  4299. if (event->attr.build_id)
  4300. atomic_dec(&nr_build_id_events);
  4301. if (event->attr.comm)
  4302. atomic_dec(&nr_comm_events);
  4303. if (event->attr.namespaces)
  4304. atomic_dec(&nr_namespaces_events);
  4305. if (event->attr.cgroup)
  4306. atomic_dec(&nr_cgroup_events);
  4307. if (event->attr.task)
  4308. atomic_dec(&nr_task_events);
  4309. if (event->attr.freq)
  4310. unaccount_freq_event();
  4311. if (event->attr.context_switch) {
  4312. dec = true;
  4313. atomic_dec(&nr_switch_events);
  4314. }
  4315. if (is_cgroup_event(event))
  4316. dec = true;
  4317. if (has_branch_stack(event))
  4318. dec = true;
  4319. if (event->attr.ksymbol)
  4320. atomic_dec(&nr_ksymbol_events);
  4321. if (event->attr.bpf_event)
  4322. atomic_dec(&nr_bpf_events);
  4323. if (event->attr.text_poke)
  4324. atomic_dec(&nr_text_poke_events);
  4325. if (dec) {
  4326. if (!atomic_add_unless(&perf_sched_count, -1, 1))
  4327. schedule_delayed_work(&perf_sched_work, HZ);
  4328. }
  4329. unaccount_pmu_sb_event(event);
  4330. }
  4331. static void perf_sched_delayed(struct work_struct *work)
  4332. {
  4333. mutex_lock(&perf_sched_mutex);
  4334. if (atomic_dec_and_test(&perf_sched_count))
  4335. static_branch_disable(&perf_sched_events);
  4336. mutex_unlock(&perf_sched_mutex);
  4337. }
  4338. /*
  4339. * The following implement mutual exclusion of events on "exclusive" pmus
  4340. * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
  4341. * at a time, so we disallow creating events that might conflict, namely:
  4342. *
  4343. * 1) cpu-wide events in the presence of per-task events,
  4344. * 2) per-task events in the presence of cpu-wide events,
  4345. * 3) two matching events on the same perf_event_context.
  4346. *
  4347. * The former two cases are handled in the allocation path (perf_event_alloc(),
  4348. * _free_event()), the latter -- before the first perf_install_in_context().
  4349. */
  4350. static int exclusive_event_init(struct perf_event *event)
  4351. {
  4352. struct pmu *pmu = event->pmu;
  4353. if (!is_exclusive_pmu(pmu))
  4354. return 0;
  4355. /*
  4356. * Prevent co-existence of per-task and cpu-wide events on the
  4357. * same exclusive pmu.
  4358. *
  4359. * Negative pmu::exclusive_cnt means there are cpu-wide
  4360. * events on this "exclusive" pmu, positive means there are
  4361. * per-task events.
  4362. *
  4363. * Since this is called in perf_event_alloc() path, event::ctx
  4364. * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
  4365. * to mean "per-task event", because unlike other attach states it
  4366. * never gets cleared.
  4367. */
  4368. if (event->attach_state & PERF_ATTACH_TASK) {
  4369. if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
  4370. return -EBUSY;
  4371. } else {
  4372. if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
  4373. return -EBUSY;
  4374. }
  4375. event->attach_state |= PERF_ATTACH_EXCLUSIVE;
  4376. return 0;
  4377. }
  4378. static void exclusive_event_destroy(struct perf_event *event)
  4379. {
  4380. struct pmu *pmu = event->pmu;
  4381. /* see comment in exclusive_event_init() */
  4382. if (event->attach_state & PERF_ATTACH_TASK)
  4383. atomic_dec(&pmu->exclusive_cnt);
  4384. else
  4385. atomic_inc(&pmu->exclusive_cnt);
  4386. event->attach_state &= ~PERF_ATTACH_EXCLUSIVE;
  4387. }
  4388. static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
  4389. {
  4390. if ((e1->pmu == e2->pmu) &&
  4391. (e1->cpu == e2->cpu ||
  4392. e1->cpu == -1 ||
  4393. e2->cpu == -1))
  4394. return true;
  4395. return false;
  4396. }
  4397. static bool exclusive_event_installable(struct perf_event *event,
  4398. struct perf_event_context *ctx)
  4399. {
  4400. struct perf_event *iter_event;
  4401. struct pmu *pmu = event->pmu;
  4402. lockdep_assert_held(&ctx->mutex);
  4403. if (!is_exclusive_pmu(pmu))
  4404. return true;
  4405. list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
  4406. if (exclusive_event_match(iter_event, event))
  4407. return false;
  4408. }
  4409. return true;
  4410. }
  4411. static void perf_addr_filters_splice(struct perf_event *event,
  4412. struct list_head *head);
  4413. /* vs perf_event_alloc() error */
  4414. static void __free_event(struct perf_event *event)
  4415. {
  4416. if (event->attach_state & PERF_ATTACH_CALLCHAIN)
  4417. put_callchain_buffers();
  4418. kfree(event->addr_filter_ranges);
  4419. if (event->attach_state & PERF_ATTACH_EXCLUSIVE)
  4420. exclusive_event_destroy(event);
  4421. if (is_cgroup_event(event))
  4422. perf_detach_cgroup(event);
  4423. if (event->destroy)
  4424. event->destroy(event);
  4425. /*
  4426. * Must be after ->destroy(), due to uprobe_perf_close() using
  4427. * hw.target.
  4428. */
  4429. if (event->hw.target)
  4430. put_task_struct(event->hw.target);
  4431. if (event->pmu_ctx) {
  4432. /*
  4433. * put_pmu_ctx() needs an event->ctx reference, because of
  4434. * epc->ctx.
  4435. */
  4436. WARN_ON_ONCE(!event->ctx);
  4437. WARN_ON_ONCE(event->pmu_ctx->ctx != event->ctx);
  4438. put_pmu_ctx(event->pmu_ctx);
  4439. }
  4440. /*
  4441. * perf_event_free_task() relies on put_ctx() being 'last', in
  4442. * particular all task references must be cleaned up.
  4443. */
  4444. if (event->ctx)
  4445. put_ctx(event->ctx);
  4446. if (event->pmu)
  4447. module_put(event->pmu->module);
  4448. call_rcu(&event->rcu_head, free_event_rcu);
  4449. }
  4450. /* vs perf_event_alloc() success */
  4451. static void _free_event(struct perf_event *event)
  4452. {
  4453. irq_work_sync(&event->pending_irq);
  4454. irq_work_sync(&event->pending_disable_irq);
  4455. unaccount_event(event);
  4456. security_perf_event_free(event);
  4457. if (event->rb) {
  4458. /*
  4459. * Can happen when we close an event with re-directed output.
  4460. *
  4461. * Since we have a 0 refcount, perf_mmap_close() will skip
  4462. * over us; possibly making our ring_buffer_put() the last.
  4463. */
  4464. mutex_lock(&event->mmap_mutex);
  4465. ring_buffer_attach(event, NULL);
  4466. mutex_unlock(&event->mmap_mutex);
  4467. }
  4468. perf_event_free_bpf_prog(event);
  4469. perf_addr_filters_splice(event, NULL);
  4470. __free_event(event);
  4471. }
  4472. /*
  4473. * Used to free events which have a known refcount of 1, such as in error paths
  4474. * where the event isn't exposed yet and inherited events.
  4475. */
  4476. static void free_event(struct perf_event *event)
  4477. {
  4478. if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
  4479. "unexpected event refcount: %ld; ptr=%p\n",
  4480. atomic_long_read(&event->refcount), event)) {
  4481. /* leak to avoid use-after-free */
  4482. return;
  4483. }
  4484. _free_event(event);
  4485. }
  4486. /*
  4487. * Remove user event from the owner task.
  4488. */
  4489. static void perf_remove_from_owner(struct perf_event *event)
  4490. {
  4491. struct task_struct *owner;
  4492. rcu_read_lock();
  4493. /*
  4494. * Matches the smp_store_release() in perf_event_exit_task(). If we
  4495. * observe !owner it means the list deletion is complete and we can
  4496. * indeed free this event, otherwise we need to serialize on
  4497. * owner->perf_event_mutex.
  4498. */
  4499. owner = READ_ONCE(event->owner);
  4500. if (owner) {
  4501. /*
  4502. * Since delayed_put_task_struct() also drops the last
  4503. * task reference we can safely take a new reference
  4504. * while holding the rcu_read_lock().
  4505. */
  4506. get_task_struct(owner);
  4507. }
  4508. rcu_read_unlock();
  4509. if (owner) {
  4510. /*
  4511. * If we're here through perf_event_exit_task() we're already
  4512. * holding ctx->mutex which would be an inversion wrt. the
  4513. * normal lock order.
  4514. *
  4515. * However we can safely take this lock because its the child
  4516. * ctx->mutex.
  4517. */
  4518. mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
  4519. /*
  4520. * We have to re-check the event->owner field, if it is cleared
  4521. * we raced with perf_event_exit_task(), acquiring the mutex
  4522. * ensured they're done, and we can proceed with freeing the
  4523. * event.
  4524. */
  4525. if (event->owner) {
  4526. list_del_init(&event->owner_entry);
  4527. smp_store_release(&event->owner, NULL);
  4528. }
  4529. mutex_unlock(&owner->perf_event_mutex);
  4530. put_task_struct(owner);
  4531. }
  4532. }
  4533. static void put_event(struct perf_event *event)
  4534. {
  4535. struct perf_event *parent;
  4536. if (!atomic_long_dec_and_test(&event->refcount))
  4537. return;
  4538. parent = event->parent;
  4539. _free_event(event);
  4540. /* Matches the refcount bump in inherit_event() */
  4541. if (parent)
  4542. put_event(parent);
  4543. }
  4544. /*
  4545. * Kill an event dead; while event:refcount will preserve the event
  4546. * object, it will not preserve its functionality. Once the last 'user'
  4547. * gives up the object, we'll destroy the thing.
  4548. */
  4549. int perf_event_release_kernel(struct perf_event *event)
  4550. {
  4551. struct perf_event_context *ctx = event->ctx;
  4552. struct perf_event *child, *tmp;
  4553. LIST_HEAD(free_list);
  4554. /*
  4555. * If we got here through err_alloc: free_event(event); we will not
  4556. * have attached to a context yet.
  4557. */
  4558. if (!ctx) {
  4559. WARN_ON_ONCE(event->attach_state &
  4560. (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP));
  4561. goto no_ctx;
  4562. }
  4563. if (!is_kernel_event(event))
  4564. perf_remove_from_owner(event);
  4565. ctx = perf_event_ctx_lock(event);
  4566. WARN_ON_ONCE(ctx->parent_ctx);
  4567. /*
  4568. * Mark this event as STATE_DEAD, there is no external reference to it
  4569. * anymore.
  4570. *
  4571. * Anybody acquiring event->child_mutex after the below loop _must_
  4572. * also see this, most importantly inherit_event() which will avoid
  4573. * placing more children on the list.
  4574. *
  4575. * Thus this guarantees that we will in fact observe and kill _ALL_
  4576. * child events.
  4577. */
  4578. perf_remove_from_context(event, DETACH_GROUP|DETACH_DEAD);
  4579. perf_event_ctx_unlock(event, ctx);
  4580. again:
  4581. mutex_lock(&event->child_mutex);
  4582. list_for_each_entry(child, &event->child_list, child_list) {
  4583. void *var = NULL;
  4584. /*
  4585. * Cannot change, child events are not migrated, see the
  4586. * comment with perf_event_ctx_lock_nested().
  4587. */
  4588. ctx = READ_ONCE(child->ctx);
  4589. /*
  4590. * Since child_mutex nests inside ctx::mutex, we must jump
  4591. * through hoops. We start by grabbing a reference on the ctx.
  4592. *
  4593. * Since the event cannot get freed while we hold the
  4594. * child_mutex, the context must also exist and have a !0
  4595. * reference count.
  4596. */
  4597. get_ctx(ctx);
  4598. /*
  4599. * Now that we have a ctx ref, we can drop child_mutex, and
  4600. * acquire ctx::mutex without fear of it going away. Then we
  4601. * can re-acquire child_mutex.
  4602. */
  4603. mutex_unlock(&event->child_mutex);
  4604. mutex_lock(&ctx->mutex);
  4605. mutex_lock(&event->child_mutex);
  4606. /*
  4607. * Now that we hold ctx::mutex and child_mutex, revalidate our
  4608. * state, if child is still the first entry, it didn't get freed
  4609. * and we can continue doing so.
  4610. */
  4611. tmp = list_first_entry_or_null(&event->child_list,
  4612. struct perf_event, child_list);
  4613. if (tmp == child) {
  4614. perf_remove_from_context(child, DETACH_GROUP);
  4615. list_move(&child->child_list, &free_list);
  4616. } else {
  4617. var = &ctx->refcount;
  4618. }
  4619. mutex_unlock(&event->child_mutex);
  4620. mutex_unlock(&ctx->mutex);
  4621. put_ctx(ctx);
  4622. if (var) {
  4623. /*
  4624. * If perf_event_free_task() has deleted all events from the
  4625. * ctx while the child_mutex got released above, make sure to
  4626. * notify about the preceding put_ctx().
  4627. */
  4628. smp_mb(); /* pairs with wait_var_event() */
  4629. wake_up_var(var);
  4630. }
  4631. goto again;
  4632. }
  4633. mutex_unlock(&event->child_mutex);
  4634. list_for_each_entry_safe(child, tmp, &free_list, child_list) {
  4635. void *var = &child->ctx->refcount;
  4636. list_del(&child->child_list);
  4637. /* Last reference unless ->pending_task work is pending */
  4638. put_event(child);
  4639. /*
  4640. * Wake any perf_event_free_task() waiting for this event to be
  4641. * freed.
  4642. */
  4643. smp_mb(); /* pairs with wait_var_event() */
  4644. wake_up_var(var);
  4645. }
  4646. no_ctx:
  4647. /*
  4648. * Last reference unless ->pending_task work is pending on this event
  4649. * or any of its children.
  4650. */
  4651. put_event(event);
  4652. return 0;
  4653. }
  4654. EXPORT_SYMBOL_GPL(perf_event_release_kernel);
  4655. /*
  4656. * Called when the last reference to the file is gone.
  4657. */
  4658. static int perf_release(struct inode *inode, struct file *file)
  4659. {
  4660. perf_event_release_kernel(file->private_data);
  4661. return 0;
  4662. }
  4663. static u64 __perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
  4664. {
  4665. struct perf_event *child;
  4666. u64 total = 0;
  4667. *enabled = 0;
  4668. *running = 0;
  4669. mutex_lock(&event->child_mutex);
  4670. (void)perf_event_read(event, false);
  4671. total += perf_event_count(event, false);
  4672. *enabled += event->total_time_enabled +
  4673. atomic64_read(&event->child_total_time_enabled);
  4674. *running += event->total_time_running +
  4675. atomic64_read(&event->child_total_time_running);
  4676. list_for_each_entry(child, &event->child_list, child_list) {
  4677. (void)perf_event_read(child, false);
  4678. total += perf_event_count(child, false);
  4679. *enabled += child->total_time_enabled;
  4680. *running += child->total_time_running;
  4681. }
  4682. mutex_unlock(&event->child_mutex);
  4683. return total;
  4684. }
  4685. u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
  4686. {
  4687. struct perf_event_context *ctx;
  4688. u64 count;
  4689. ctx = perf_event_ctx_lock(event);
  4690. count = __perf_event_read_value(event, enabled, running);
  4691. perf_event_ctx_unlock(event, ctx);
  4692. return count;
  4693. }
  4694. EXPORT_SYMBOL_GPL(perf_event_read_value);
  4695. static int __perf_read_group_add(struct perf_event *leader,
  4696. u64 read_format, u64 *values)
  4697. {
  4698. struct perf_event_context *ctx = leader->ctx;
  4699. struct perf_event *sub, *parent;
  4700. unsigned long flags;
  4701. int n = 1; /* skip @nr */
  4702. int ret;
  4703. ret = perf_event_read(leader, true);
  4704. if (ret)
  4705. return ret;
  4706. raw_spin_lock_irqsave(&ctx->lock, flags);
  4707. /*
  4708. * Verify the grouping between the parent and child (inherited)
  4709. * events is still in tact.
  4710. *
  4711. * Specifically:
  4712. * - leader->ctx->lock pins leader->sibling_list
  4713. * - parent->child_mutex pins parent->child_list
  4714. * - parent->ctx->mutex pins parent->sibling_list
  4715. *
  4716. * Because parent->ctx != leader->ctx (and child_list nests inside
  4717. * ctx->mutex), group destruction is not atomic between children, also
  4718. * see perf_event_release_kernel(). Additionally, parent can grow the
  4719. * group.
  4720. *
  4721. * Therefore it is possible to have parent and child groups in a
  4722. * different configuration and summing over such a beast makes no sense
  4723. * what so ever.
  4724. *
  4725. * Reject this.
  4726. */
  4727. parent = leader->parent;
  4728. if (parent &&
  4729. (parent->group_generation != leader->group_generation ||
  4730. parent->nr_siblings != leader->nr_siblings)) {
  4731. ret = -ECHILD;
  4732. goto unlock;
  4733. }
  4734. /*
  4735. * Since we co-schedule groups, {enabled,running} times of siblings
  4736. * will be identical to those of the leader, so we only publish one
  4737. * set.
  4738. */
  4739. if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
  4740. values[n++] += leader->total_time_enabled +
  4741. atomic64_read(&leader->child_total_time_enabled);
  4742. }
  4743. if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
  4744. values[n++] += leader->total_time_running +
  4745. atomic64_read(&leader->child_total_time_running);
  4746. }
  4747. /*
  4748. * Write {count,id} tuples for every sibling.
  4749. */
  4750. values[n++] += perf_event_count(leader, false);
  4751. if (read_format & PERF_FORMAT_ID)
  4752. values[n++] = primary_event_id(leader);
  4753. if (read_format & PERF_FORMAT_LOST)
  4754. values[n++] = atomic64_read(&leader->lost_samples);
  4755. for_each_sibling_event(sub, leader) {
  4756. values[n++] += perf_event_count(sub, false);
  4757. if (read_format & PERF_FORMAT_ID)
  4758. values[n++] = primary_event_id(sub);
  4759. if (read_format & PERF_FORMAT_LOST)
  4760. values[n++] = atomic64_read(&sub->lost_samples);
  4761. }
  4762. unlock:
  4763. raw_spin_unlock_irqrestore(&ctx->lock, flags);
  4764. return ret;
  4765. }
  4766. static int perf_read_group(struct perf_event *event,
  4767. u64 read_format, char __user *buf)
  4768. {
  4769. struct perf_event *leader = event->group_leader, *child;
  4770. struct perf_event_context *ctx = leader->ctx;
  4771. int ret;
  4772. u64 *values;
  4773. lockdep_assert_held(&ctx->mutex);
  4774. values = kzalloc(event->read_size, GFP_KERNEL);
  4775. if (!values)
  4776. return -ENOMEM;
  4777. values[0] = 1 + leader->nr_siblings;
  4778. mutex_lock(&leader->child_mutex);
  4779. ret = __perf_read_group_add(leader, read_format, values);
  4780. if (ret)
  4781. goto unlock;
  4782. list_for_each_entry(child, &leader->child_list, child_list) {
  4783. ret = __perf_read_group_add(child, read_format, values);
  4784. if (ret)
  4785. goto unlock;
  4786. }
  4787. mutex_unlock(&leader->child_mutex);
  4788. ret = event->read_size;
  4789. if (copy_to_user(buf, values, event->read_size))
  4790. ret = -EFAULT;
  4791. goto out;
  4792. unlock:
  4793. mutex_unlock(&leader->child_mutex);
  4794. out:
  4795. kfree(values);
  4796. return ret;
  4797. }
  4798. static int perf_read_one(struct perf_event *event,
  4799. u64 read_format, char __user *buf)
  4800. {
  4801. u64 enabled, running;
  4802. u64 values[5];
  4803. int n = 0;
  4804. values[n++] = __perf_event_read_value(event, &enabled, &running);
  4805. if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
  4806. values[n++] = enabled;
  4807. if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
  4808. values[n++] = running;
  4809. if (read_format & PERF_FORMAT_ID)
  4810. values[n++] = primary_event_id(event);
  4811. if (read_format & PERF_FORMAT_LOST)
  4812. values[n++] = atomic64_read(&event->lost_samples);
  4813. if (copy_to_user(buf, values, n * sizeof(u64)))
  4814. return -EFAULT;
  4815. return n * sizeof(u64);
  4816. }
  4817. static bool is_event_hup(struct perf_event *event)
  4818. {
  4819. bool no_children;
  4820. if (event->state > PERF_EVENT_STATE_EXIT)
  4821. return false;
  4822. mutex_lock(&event->child_mutex);
  4823. no_children = list_empty(&event->child_list);
  4824. mutex_unlock(&event->child_mutex);
  4825. return no_children;
  4826. }
  4827. /*
  4828. * Read the performance event - simple non blocking version for now
  4829. */
  4830. static ssize_t
  4831. __perf_read(struct perf_event *event, char __user *buf, size_t count)
  4832. {
  4833. u64 read_format = event->attr.read_format;
  4834. int ret;
  4835. /*
  4836. * Return end-of-file for a read on an event that is in
  4837. * error state (i.e. because it was pinned but it couldn't be
  4838. * scheduled on to the CPU at some point).
  4839. */
  4840. if (event->state == PERF_EVENT_STATE_ERROR)
  4841. return 0;
  4842. if (count < event->read_size)
  4843. return -ENOSPC;
  4844. WARN_ON_ONCE(event->ctx->parent_ctx);
  4845. if (read_format & PERF_FORMAT_GROUP)
  4846. ret = perf_read_group(event, read_format, buf);
  4847. else
  4848. ret = perf_read_one(event, read_format, buf);
  4849. return ret;
  4850. }
  4851. static ssize_t
  4852. perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
  4853. {
  4854. struct perf_event *event = file->private_data;
  4855. struct perf_event_context *ctx;
  4856. int ret;
  4857. ret = security_perf_event_read(event);
  4858. if (ret)
  4859. return ret;
  4860. ctx = perf_event_ctx_lock(event);
  4861. ret = __perf_read(event, buf, count);
  4862. perf_event_ctx_unlock(event, ctx);
  4863. return ret;
  4864. }
  4865. static __poll_t perf_poll(struct file *file, poll_table *wait)
  4866. {
  4867. struct perf_event *event = file->private_data;
  4868. struct perf_buffer *rb;
  4869. __poll_t events = EPOLLHUP;
  4870. poll_wait(file, &event->waitq, wait);
  4871. if (is_event_hup(event))
  4872. return events;
  4873. /*
  4874. * Pin the event->rb by taking event->mmap_mutex; otherwise
  4875. * perf_event_set_output() can swizzle our rb and make us miss wakeups.
  4876. */
  4877. mutex_lock(&event->mmap_mutex);
  4878. rb = event->rb;
  4879. if (rb)
  4880. events = atomic_xchg(&rb->poll, 0);
  4881. mutex_unlock(&event->mmap_mutex);
  4882. return events;
  4883. }
  4884. static void _perf_event_reset(struct perf_event *event)
  4885. {
  4886. (void)perf_event_read(event, false);
  4887. local64_set(&event->count, 0);
  4888. perf_event_update_userpage(event);
  4889. }
  4890. /* Assume it's not an event with inherit set. */
  4891. u64 perf_event_pause(struct perf_event *event, bool reset)
  4892. {
  4893. struct perf_event_context *ctx;
  4894. u64 count;
  4895. ctx = perf_event_ctx_lock(event);
  4896. WARN_ON_ONCE(event->attr.inherit);
  4897. _perf_event_disable(event);
  4898. count = local64_read(&event->count);
  4899. if (reset)
  4900. local64_set(&event->count, 0);
  4901. perf_event_ctx_unlock(event, ctx);
  4902. return count;
  4903. }
  4904. EXPORT_SYMBOL_GPL(perf_event_pause);
  4905. /*
  4906. * Holding the top-level event's child_mutex means that any
  4907. * descendant process that has inherited this event will block
  4908. * in perf_event_exit_event() if it goes to exit, thus satisfying the
  4909. * task existence requirements of perf_event_enable/disable.
  4910. */
  4911. static void perf_event_for_each_child(struct perf_event *event,
  4912. void (*func)(struct perf_event *))
  4913. {
  4914. struct perf_event *child;
  4915. WARN_ON_ONCE(event->ctx->parent_ctx);
  4916. mutex_lock(&event->child_mutex);
  4917. func(event);
  4918. list_for_each_entry(child, &event->child_list, child_list)
  4919. func(child);
  4920. mutex_unlock(&event->child_mutex);
  4921. }
  4922. static void perf_event_for_each(struct perf_event *event,
  4923. void (*func)(struct perf_event *))
  4924. {
  4925. struct perf_event_context *ctx = event->ctx;
  4926. struct perf_event *sibling;
  4927. lockdep_assert_held(&ctx->mutex);
  4928. event = event->group_leader;
  4929. perf_event_for_each_child(event, func);
  4930. for_each_sibling_event(sibling, event)
  4931. perf_event_for_each_child(sibling, func);
  4932. }
  4933. static void __perf_event_period(struct perf_event *event,
  4934. struct perf_cpu_context *cpuctx,
  4935. struct perf_event_context *ctx,
  4936. void *info)
  4937. {
  4938. u64 value = *((u64 *)info);
  4939. bool active;
  4940. if (event->attr.freq) {
  4941. event->attr.sample_freq = value;
  4942. } else {
  4943. event->attr.sample_period = value;
  4944. event->hw.sample_period = value;
  4945. }
  4946. active = (event->state == PERF_EVENT_STATE_ACTIVE);
  4947. if (active) {
  4948. perf_pmu_disable(event->pmu);
  4949. /*
  4950. * We could be throttled; unthrottle now to avoid the tick
  4951. * trying to unthrottle while we already re-started the event.
  4952. */
  4953. if (event->hw.interrupts == MAX_INTERRUPTS) {
  4954. event->hw.interrupts = 0;
  4955. perf_log_throttle(event, 1);
  4956. }
  4957. event->pmu->stop(event, PERF_EF_UPDATE);
  4958. }
  4959. local64_set(&event->hw.period_left, 0);
  4960. if (active) {
  4961. event->pmu->start(event, PERF_EF_RELOAD);
  4962. perf_pmu_enable(event->pmu);
  4963. }
  4964. }
  4965. static int perf_event_check_period(struct perf_event *event, u64 value)
  4966. {
  4967. return event->pmu->check_period(event, value);
  4968. }
  4969. static int _perf_event_period(struct perf_event *event, u64 value)
  4970. {
  4971. if (!is_sampling_event(event))
  4972. return -EINVAL;
  4973. if (!value)
  4974. return -EINVAL;
  4975. if (event->attr.freq) {
  4976. if (value > sysctl_perf_event_sample_rate)
  4977. return -EINVAL;
  4978. } else {
  4979. if (perf_event_check_period(event, value))
  4980. return -EINVAL;
  4981. if (value & (1ULL << 63))
  4982. return -EINVAL;
  4983. }
  4984. event_function_call(event, __perf_event_period, &value);
  4985. return 0;
  4986. }
  4987. int perf_event_period(struct perf_event *event, u64 value)
  4988. {
  4989. struct perf_event_context *ctx;
  4990. int ret;
  4991. ctx = perf_event_ctx_lock(event);
  4992. ret = _perf_event_period(event, value);
  4993. perf_event_ctx_unlock(event, ctx);
  4994. return ret;
  4995. }
  4996. EXPORT_SYMBOL_GPL(perf_event_period);
  4997. static const struct file_operations perf_fops;
  4998. static inline int perf_fget_light(int fd, struct fd *p)
  4999. {
  5000. struct fd f = fdget(fd);
  5001. if (!fd_file(f))
  5002. return -EBADF;
  5003. if (fd_file(f)->f_op != &perf_fops) {
  5004. fdput(f);
  5005. return -EBADF;
  5006. }
  5007. *p = f;
  5008. return 0;
  5009. }
  5010. static int perf_event_set_output(struct perf_event *event,
  5011. struct perf_event *output_event);
  5012. static int perf_event_set_filter(struct perf_event *event, void __user *arg);
  5013. static int perf_copy_attr(struct perf_event_attr __user *uattr,
  5014. struct perf_event_attr *attr);
  5015. static int __perf_event_set_bpf_prog(struct perf_event *event,
  5016. struct bpf_prog *prog,
  5017. u64 bpf_cookie);
  5018. static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
  5019. {
  5020. void (*func)(struct perf_event *);
  5021. u32 flags = arg;
  5022. switch (cmd) {
  5023. case PERF_EVENT_IOC_ENABLE:
  5024. func = _perf_event_enable;
  5025. break;
  5026. case PERF_EVENT_IOC_DISABLE:
  5027. func = _perf_event_disable;
  5028. break;
  5029. case PERF_EVENT_IOC_RESET:
  5030. func = _perf_event_reset;
  5031. break;
  5032. case PERF_EVENT_IOC_REFRESH:
  5033. return _perf_event_refresh(event, arg);
  5034. case PERF_EVENT_IOC_PERIOD:
  5035. {
  5036. u64 value;
  5037. if (copy_from_user(&value, (u64 __user *)arg, sizeof(value)))
  5038. return -EFAULT;
  5039. return _perf_event_period(event, value);
  5040. }
  5041. case PERF_EVENT_IOC_ID:
  5042. {
  5043. u64 id = primary_event_id(event);
  5044. if (copy_to_user((void __user *)arg, &id, sizeof(id)))
  5045. return -EFAULT;
  5046. return 0;
  5047. }
  5048. case PERF_EVENT_IOC_SET_OUTPUT:
  5049. {
  5050. int ret;
  5051. if (arg != -1) {
  5052. struct perf_event *output_event;
  5053. struct fd output;
  5054. ret = perf_fget_light(arg, &output);
  5055. if (ret)
  5056. return ret;
  5057. output_event = fd_file(output)->private_data;
  5058. ret = perf_event_set_output(event, output_event);
  5059. fdput(output);
  5060. } else {
  5061. ret = perf_event_set_output(event, NULL);
  5062. }
  5063. return ret;
  5064. }
  5065. case PERF_EVENT_IOC_SET_FILTER:
  5066. return perf_event_set_filter(event, (void __user *)arg);
  5067. case PERF_EVENT_IOC_SET_BPF:
  5068. {
  5069. struct bpf_prog *prog;
  5070. int err;
  5071. prog = bpf_prog_get(arg);
  5072. if (IS_ERR(prog))
  5073. return PTR_ERR(prog);
  5074. err = __perf_event_set_bpf_prog(event, prog, 0);
  5075. if (err) {
  5076. bpf_prog_put(prog);
  5077. return err;
  5078. }
  5079. return 0;
  5080. }
  5081. case PERF_EVENT_IOC_PAUSE_OUTPUT: {
  5082. struct perf_buffer *rb;
  5083. rcu_read_lock();
  5084. rb = rcu_dereference(event->rb);
  5085. if (!rb || !rb->nr_pages) {
  5086. rcu_read_unlock();
  5087. return -EINVAL;
  5088. }
  5089. rb_toggle_paused(rb, !!arg);
  5090. rcu_read_unlock();
  5091. return 0;
  5092. }
  5093. case PERF_EVENT_IOC_QUERY_BPF:
  5094. return perf_event_query_prog_array(event, (void __user *)arg);
  5095. case PERF_EVENT_IOC_MODIFY_ATTRIBUTES: {
  5096. struct perf_event_attr new_attr;
  5097. int err = perf_copy_attr((struct perf_event_attr __user *)arg,
  5098. &new_attr);
  5099. if (err)
  5100. return err;
  5101. return perf_event_modify_attr(event, &new_attr);
  5102. }
  5103. default:
  5104. return -ENOTTY;
  5105. }
  5106. if (flags & PERF_IOC_FLAG_GROUP)
  5107. perf_event_for_each(event, func);
  5108. else
  5109. perf_event_for_each_child(event, func);
  5110. return 0;
  5111. }
  5112. static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
  5113. {
  5114. struct perf_event *event = file->private_data;
  5115. struct perf_event_context *ctx;
  5116. long ret;
  5117. /* Treat ioctl like writes as it is likely a mutating operation. */
  5118. ret = security_perf_event_write(event);
  5119. if (ret)
  5120. return ret;
  5121. ctx = perf_event_ctx_lock(event);
  5122. ret = _perf_ioctl(event, cmd, arg);
  5123. perf_event_ctx_unlock(event, ctx);
  5124. return ret;
  5125. }
  5126. #ifdef CONFIG_COMPAT
  5127. static long perf_compat_ioctl(struct file *file, unsigned int cmd,
  5128. unsigned long arg)
  5129. {
  5130. switch (_IOC_NR(cmd)) {
  5131. case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
  5132. case _IOC_NR(PERF_EVENT_IOC_ID):
  5133. case _IOC_NR(PERF_EVENT_IOC_QUERY_BPF):
  5134. case _IOC_NR(PERF_EVENT_IOC_MODIFY_ATTRIBUTES):
  5135. /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
  5136. if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
  5137. cmd &= ~IOCSIZE_MASK;
  5138. cmd |= sizeof(void *) << IOCSIZE_SHIFT;
  5139. }
  5140. break;
  5141. }
  5142. return perf_ioctl(file, cmd, arg);
  5143. }
  5144. #else
  5145. # define perf_compat_ioctl NULL
  5146. #endif
  5147. int perf_event_task_enable(void)
  5148. {
  5149. struct perf_event_context *ctx;
  5150. struct perf_event *event;
  5151. mutex_lock(&current->perf_event_mutex);
  5152. list_for_each_entry(event, &current->perf_event_list, owner_entry) {
  5153. ctx = perf_event_ctx_lock(event);
  5154. perf_event_for_each_child(event, _perf_event_enable);
  5155. perf_event_ctx_unlock(event, ctx);
  5156. }
  5157. mutex_unlock(&current->perf_event_mutex);
  5158. return 0;
  5159. }
  5160. int perf_event_task_disable(void)
  5161. {
  5162. struct perf_event_context *ctx;
  5163. struct perf_event *event;
  5164. mutex_lock(&current->perf_event_mutex);
  5165. list_for_each_entry(event, &current->perf_event_list, owner_entry) {
  5166. ctx = perf_event_ctx_lock(event);
  5167. perf_event_for_each_child(event, _perf_event_disable);
  5168. perf_event_ctx_unlock(event, ctx);
  5169. }
  5170. mutex_unlock(&current->perf_event_mutex);
  5171. return 0;
  5172. }
  5173. static int perf_event_index(struct perf_event *event)
  5174. {
  5175. if (event->hw.state & PERF_HES_STOPPED)
  5176. return 0;
  5177. if (event->state != PERF_EVENT_STATE_ACTIVE)
  5178. return 0;
  5179. return event->pmu->event_idx(event);
  5180. }
  5181. static void perf_event_init_userpage(struct perf_event *event)
  5182. {
  5183. struct perf_event_mmap_page *userpg;
  5184. struct perf_buffer *rb;
  5185. rcu_read_lock();
  5186. rb = rcu_dereference(event->rb);
  5187. if (!rb)
  5188. goto unlock;
  5189. userpg = rb->user_page;
  5190. /* Allow new userspace to detect that bit 0 is deprecated */
  5191. userpg->cap_bit0_is_deprecated = 1;
  5192. userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
  5193. userpg->data_offset = PAGE_SIZE;
  5194. userpg->data_size = perf_data_size(rb);
  5195. unlock:
  5196. rcu_read_unlock();
  5197. }
  5198. void __weak arch_perf_update_userpage(
  5199. struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
  5200. {
  5201. }
  5202. /*
  5203. * Callers need to ensure there can be no nesting of this function, otherwise
  5204. * the seqlock logic goes bad. We can not serialize this because the arch
  5205. * code calls this from NMI context.
  5206. */
  5207. void perf_event_update_userpage(struct perf_event *event)
  5208. {
  5209. struct perf_event_mmap_page *userpg;
  5210. struct perf_buffer *rb;
  5211. u64 enabled, running, now;
  5212. rcu_read_lock();
  5213. rb = rcu_dereference(event->rb);
  5214. if (!rb)
  5215. goto unlock;
  5216. /*
  5217. * compute total_time_enabled, total_time_running
  5218. * based on snapshot values taken when the event
  5219. * was last scheduled in.
  5220. *
  5221. * we cannot simply called update_context_time()
  5222. * because of locking issue as we can be called in
  5223. * NMI context
  5224. */
  5225. calc_timer_values(event, &now, &enabled, &running);
  5226. userpg = rb->user_page;
  5227. /*
  5228. * Disable preemption to guarantee consistent time stamps are stored to
  5229. * the user page.
  5230. */
  5231. preempt_disable();
  5232. ++userpg->lock;
  5233. barrier();
  5234. userpg->index = perf_event_index(event);
  5235. userpg->offset = perf_event_count(event, false);
  5236. if (userpg->index)
  5237. userpg->offset -= local64_read(&event->hw.prev_count);
  5238. userpg->time_enabled = enabled +
  5239. atomic64_read(&event->child_total_time_enabled);
  5240. userpg->time_running = running +
  5241. atomic64_read(&event->child_total_time_running);
  5242. arch_perf_update_userpage(event, userpg, now);
  5243. barrier();
  5244. ++userpg->lock;
  5245. preempt_enable();
  5246. unlock:
  5247. rcu_read_unlock();
  5248. }
  5249. EXPORT_SYMBOL_GPL(perf_event_update_userpage);
  5250. static vm_fault_t perf_mmap_fault(struct vm_fault *vmf)
  5251. {
  5252. struct perf_event *event = vmf->vma->vm_file->private_data;
  5253. struct perf_buffer *rb;
  5254. vm_fault_t ret = VM_FAULT_SIGBUS;
  5255. if (vmf->flags & FAULT_FLAG_MKWRITE) {
  5256. if (vmf->pgoff == 0)
  5257. ret = 0;
  5258. return ret;
  5259. }
  5260. rcu_read_lock();
  5261. rb = rcu_dereference(event->rb);
  5262. if (!rb)
  5263. goto unlock;
  5264. if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
  5265. goto unlock;
  5266. vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
  5267. if (!vmf->page)
  5268. goto unlock;
  5269. get_page(vmf->page);
  5270. vmf->page->mapping = vmf->vma->vm_file->f_mapping;
  5271. vmf->page->index = vmf->pgoff;
  5272. ret = 0;
  5273. unlock:
  5274. rcu_read_unlock();
  5275. return ret;
  5276. }
  5277. static void ring_buffer_attach(struct perf_event *event,
  5278. struct perf_buffer *rb)
  5279. {
  5280. struct perf_buffer *old_rb = NULL;
  5281. unsigned long flags;
  5282. WARN_ON_ONCE(event->parent);
  5283. if (event->rb) {
  5284. /*
  5285. * Should be impossible, we set this when removing
  5286. * event->rb_entry and wait/clear when adding event->rb_entry.
  5287. */
  5288. WARN_ON_ONCE(event->rcu_pending);
  5289. old_rb = event->rb;
  5290. spin_lock_irqsave(&old_rb->event_lock, flags);
  5291. list_del_rcu(&event->rb_entry);
  5292. spin_unlock_irqrestore(&old_rb->event_lock, flags);
  5293. event->rcu_batches = get_state_synchronize_rcu();
  5294. event->rcu_pending = 1;
  5295. }
  5296. if (rb) {
  5297. if (event->rcu_pending) {
  5298. cond_synchronize_rcu(event->rcu_batches);
  5299. event->rcu_pending = 0;
  5300. }
  5301. spin_lock_irqsave(&rb->event_lock, flags);
  5302. list_add_rcu(&event->rb_entry, &rb->event_list);
  5303. spin_unlock_irqrestore(&rb->event_lock, flags);
  5304. }
  5305. /*
  5306. * Avoid racing with perf_mmap_close(AUX): stop the event
  5307. * before swizzling the event::rb pointer; if it's getting
  5308. * unmapped, its aux_mmap_count will be 0 and it won't
  5309. * restart. See the comment in __perf_pmu_output_stop().
  5310. *
  5311. * Data will inevitably be lost when set_output is done in
  5312. * mid-air, but then again, whoever does it like this is
  5313. * not in for the data anyway.
  5314. */
  5315. if (has_aux(event))
  5316. perf_event_stop(event, 0);
  5317. rcu_assign_pointer(event->rb, rb);
  5318. if (old_rb) {
  5319. ring_buffer_put(old_rb);
  5320. /*
  5321. * Since we detached before setting the new rb, so that we
  5322. * could attach the new rb, we could have missed a wakeup.
  5323. * Provide it now.
  5324. */
  5325. wake_up_all(&event->waitq);
  5326. }
  5327. }
  5328. static void ring_buffer_wakeup(struct perf_event *event)
  5329. {
  5330. struct perf_buffer *rb;
  5331. if (event->parent)
  5332. event = event->parent;
  5333. rcu_read_lock();
  5334. rb = rcu_dereference(event->rb);
  5335. if (rb) {
  5336. list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
  5337. wake_up_all(&event->waitq);
  5338. }
  5339. rcu_read_unlock();
  5340. }
  5341. struct perf_buffer *ring_buffer_get(struct perf_event *event)
  5342. {
  5343. struct perf_buffer *rb;
  5344. if (event->parent)
  5345. event = event->parent;
  5346. rcu_read_lock();
  5347. rb = rcu_dereference(event->rb);
  5348. if (rb) {
  5349. if (!refcount_inc_not_zero(&rb->refcount))
  5350. rb = NULL;
  5351. }
  5352. rcu_read_unlock();
  5353. return rb;
  5354. }
  5355. void ring_buffer_put(struct perf_buffer *rb)
  5356. {
  5357. if (!refcount_dec_and_test(&rb->refcount))
  5358. return;
  5359. WARN_ON_ONCE(!list_empty(&rb->event_list));
  5360. call_rcu(&rb->rcu_head, rb_free_rcu);
  5361. }
  5362. static void perf_mmap_open(struct vm_area_struct *vma)
  5363. {
  5364. struct perf_event *event = vma->vm_file->private_data;
  5365. atomic_inc(&event->mmap_count);
  5366. atomic_inc(&event->rb->mmap_count);
  5367. if (vma->vm_pgoff)
  5368. atomic_inc(&event->rb->aux_mmap_count);
  5369. if (event->pmu->event_mapped)
  5370. event->pmu->event_mapped(event, vma->vm_mm);
  5371. }
  5372. static void perf_pmu_output_stop(struct perf_event *event);
  5373. /*
  5374. * A buffer can be mmap()ed multiple times; either directly through the same
  5375. * event, or through other events by use of perf_event_set_output().
  5376. *
  5377. * In order to undo the VM accounting done by perf_mmap() we need to destroy
  5378. * the buffer here, where we still have a VM context. This means we need
  5379. * to detach all events redirecting to us.
  5380. */
  5381. static void perf_mmap_close(struct vm_area_struct *vma)
  5382. {
  5383. struct perf_event *event = vma->vm_file->private_data;
  5384. struct perf_buffer *rb = ring_buffer_get(event);
  5385. struct user_struct *mmap_user = rb->mmap_user;
  5386. int mmap_locked = rb->mmap_locked;
  5387. unsigned long size = perf_data_size(rb);
  5388. bool detach_rest = false;
  5389. if (event->pmu->event_unmapped)
  5390. event->pmu->event_unmapped(event, vma->vm_mm);
  5391. /*
  5392. * The AUX buffer is strictly a sub-buffer, serialize using aux_mutex
  5393. * to avoid complications.
  5394. */
  5395. if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
  5396. atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &rb->aux_mutex)) {
  5397. /*
  5398. * Stop all AUX events that are writing to this buffer,
  5399. * so that we can free its AUX pages and corresponding PMU
  5400. * data. Note that after rb::aux_mmap_count dropped to zero,
  5401. * they won't start any more (see perf_aux_output_begin()).
  5402. */
  5403. perf_pmu_output_stop(event);
  5404. /* now it's safe to free the pages */
  5405. atomic_long_sub(rb->aux_nr_pages - rb->aux_mmap_locked, &mmap_user->locked_vm);
  5406. atomic64_sub(rb->aux_mmap_locked, &vma->vm_mm->pinned_vm);
  5407. /* this has to be the last one */
  5408. rb_free_aux(rb);
  5409. WARN_ON_ONCE(refcount_read(&rb->aux_refcount));
  5410. mutex_unlock(&rb->aux_mutex);
  5411. }
  5412. if (atomic_dec_and_test(&rb->mmap_count))
  5413. detach_rest = true;
  5414. if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
  5415. goto out_put;
  5416. ring_buffer_attach(event, NULL);
  5417. mutex_unlock(&event->mmap_mutex);
  5418. /* If there's still other mmap()s of this buffer, we're done. */
  5419. if (!detach_rest)
  5420. goto out_put;
  5421. /*
  5422. * No other mmap()s, detach from all other events that might redirect
  5423. * into the now unreachable buffer. Somewhat complicated by the
  5424. * fact that rb::event_lock otherwise nests inside mmap_mutex.
  5425. */
  5426. again:
  5427. rcu_read_lock();
  5428. list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
  5429. if (!atomic_long_inc_not_zero(&event->refcount)) {
  5430. /*
  5431. * This event is en-route to free_event() which will
  5432. * detach it and remove it from the list.
  5433. */
  5434. continue;
  5435. }
  5436. rcu_read_unlock();
  5437. mutex_lock(&event->mmap_mutex);
  5438. /*
  5439. * Check we didn't race with perf_event_set_output() which can
  5440. * swizzle the rb from under us while we were waiting to
  5441. * acquire mmap_mutex.
  5442. *
  5443. * If we find a different rb; ignore this event, a next
  5444. * iteration will no longer find it on the list. We have to
  5445. * still restart the iteration to make sure we're not now
  5446. * iterating the wrong list.
  5447. */
  5448. if (event->rb == rb)
  5449. ring_buffer_attach(event, NULL);
  5450. mutex_unlock(&event->mmap_mutex);
  5451. put_event(event);
  5452. /*
  5453. * Restart the iteration; either we're on the wrong list or
  5454. * destroyed its integrity by doing a deletion.
  5455. */
  5456. goto again;
  5457. }
  5458. rcu_read_unlock();
  5459. /*
  5460. * It could be there's still a few 0-ref events on the list; they'll
  5461. * get cleaned up by free_event() -- they'll also still have their
  5462. * ref on the rb and will free it whenever they are done with it.
  5463. *
  5464. * Aside from that, this buffer is 'fully' detached and unmapped,
  5465. * undo the VM accounting.
  5466. */
  5467. atomic_long_sub((size >> PAGE_SHIFT) + 1 - mmap_locked,
  5468. &mmap_user->locked_vm);
  5469. atomic64_sub(mmap_locked, &vma->vm_mm->pinned_vm);
  5470. free_uid(mmap_user);
  5471. out_put:
  5472. ring_buffer_put(rb); /* could be last */
  5473. }
  5474. static int perf_mmap_may_split(struct vm_area_struct *vma, unsigned long addr)
  5475. {
  5476. /*
  5477. * Forbid splitting perf mappings to prevent refcount leaks due to
  5478. * the resulting non-matching offsets and sizes. See open()/close().
  5479. */
  5480. return -EINVAL;
  5481. }
  5482. static const struct vm_operations_struct perf_mmap_vmops = {
  5483. .open = perf_mmap_open,
  5484. .close = perf_mmap_close, /* non mergeable */
  5485. .fault = perf_mmap_fault,
  5486. .page_mkwrite = perf_mmap_fault,
  5487. .may_split = perf_mmap_may_split,
  5488. };
  5489. static int perf_mmap(struct file *file, struct vm_area_struct *vma)
  5490. {
  5491. struct perf_event *event = file->private_data;
  5492. unsigned long user_locked, user_lock_limit;
  5493. struct user_struct *user = current_user();
  5494. struct mutex *aux_mutex = NULL;
  5495. struct perf_buffer *rb = NULL;
  5496. unsigned long locked, lock_limit;
  5497. unsigned long vma_size;
  5498. unsigned long nr_pages;
  5499. long user_extra = 0, extra = 0;
  5500. int ret = 0, flags = 0;
  5501. /*
  5502. * Don't allow mmap() of inherited per-task counters. This would
  5503. * create a performance issue due to all children writing to the
  5504. * same rb.
  5505. */
  5506. if (event->cpu == -1 && event->attr.inherit)
  5507. return -EINVAL;
  5508. if (!(vma->vm_flags & VM_SHARED))
  5509. return -EINVAL;
  5510. ret = security_perf_event_read(event);
  5511. if (ret)
  5512. return ret;
  5513. vma_size = vma->vm_end - vma->vm_start;
  5514. if (vma->vm_pgoff == 0) {
  5515. nr_pages = (vma_size / PAGE_SIZE) - 1;
  5516. } else {
  5517. /*
  5518. * AUX area mapping: if rb->aux_nr_pages != 0, it's already
  5519. * mapped, all subsequent mappings should have the same size
  5520. * and offset. Must be above the normal perf buffer.
  5521. */
  5522. u64 aux_offset, aux_size;
  5523. if (!event->rb)
  5524. return -EINVAL;
  5525. nr_pages = vma_size / PAGE_SIZE;
  5526. if (nr_pages > INT_MAX)
  5527. return -ENOMEM;
  5528. mutex_lock(&event->mmap_mutex);
  5529. ret = -EINVAL;
  5530. rb = event->rb;
  5531. if (!rb)
  5532. goto aux_unlock;
  5533. aux_mutex = &rb->aux_mutex;
  5534. mutex_lock(aux_mutex);
  5535. aux_offset = READ_ONCE(rb->user_page->aux_offset);
  5536. aux_size = READ_ONCE(rb->user_page->aux_size);
  5537. if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
  5538. goto aux_unlock;
  5539. if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
  5540. goto aux_unlock;
  5541. /* already mapped with a different offset */
  5542. if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
  5543. goto aux_unlock;
  5544. if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
  5545. goto aux_unlock;
  5546. /* already mapped with a different size */
  5547. if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
  5548. goto aux_unlock;
  5549. if (!is_power_of_2(nr_pages))
  5550. goto aux_unlock;
  5551. if (!atomic_inc_not_zero(&rb->mmap_count))
  5552. goto aux_unlock;
  5553. if (rb_has_aux(rb)) {
  5554. atomic_inc(&rb->aux_mmap_count);
  5555. ret = 0;
  5556. goto unlock;
  5557. }
  5558. user_extra = nr_pages;
  5559. goto accounting;
  5560. }
  5561. /*
  5562. * If we have rb pages ensure they're a power-of-two number, so we
  5563. * can do bitmasks instead of modulo.
  5564. */
  5565. if (nr_pages != 0 && !is_power_of_2(nr_pages))
  5566. return -EINVAL;
  5567. if (vma_size != PAGE_SIZE * (1 + nr_pages))
  5568. return -EINVAL;
  5569. WARN_ON_ONCE(event->ctx->parent_ctx);
  5570. again:
  5571. mutex_lock(&event->mmap_mutex);
  5572. if (event->rb) {
  5573. if (data_page_nr(event->rb) != nr_pages) {
  5574. ret = -EINVAL;
  5575. goto unlock;
  5576. }
  5577. if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
  5578. /*
  5579. * Raced against perf_mmap_close(); remove the
  5580. * event and try again.
  5581. */
  5582. ring_buffer_attach(event, NULL);
  5583. mutex_unlock(&event->mmap_mutex);
  5584. goto again;
  5585. }
  5586. goto unlock;
  5587. }
  5588. user_extra = nr_pages + 1;
  5589. accounting:
  5590. user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
  5591. /*
  5592. * Increase the limit linearly with more CPUs:
  5593. */
  5594. user_lock_limit *= num_online_cpus();
  5595. user_locked = atomic_long_read(&user->locked_vm);
  5596. /*
  5597. * sysctl_perf_event_mlock may have changed, so that
  5598. * user->locked_vm > user_lock_limit
  5599. */
  5600. if (user_locked > user_lock_limit)
  5601. user_locked = user_lock_limit;
  5602. user_locked += user_extra;
  5603. if (user_locked > user_lock_limit) {
  5604. /*
  5605. * charge locked_vm until it hits user_lock_limit;
  5606. * charge the rest from pinned_vm
  5607. */
  5608. extra = user_locked - user_lock_limit;
  5609. user_extra -= extra;
  5610. }
  5611. lock_limit = rlimit(RLIMIT_MEMLOCK);
  5612. lock_limit >>= PAGE_SHIFT;
  5613. locked = atomic64_read(&vma->vm_mm->pinned_vm) + extra;
  5614. if ((locked > lock_limit) && perf_is_paranoid() &&
  5615. !capable(CAP_IPC_LOCK)) {
  5616. ret = -EPERM;
  5617. goto unlock;
  5618. }
  5619. WARN_ON(!rb && event->rb);
  5620. if (vma->vm_flags & VM_WRITE)
  5621. flags |= RING_BUFFER_WRITABLE;
  5622. if (!rb) {
  5623. rb = rb_alloc(nr_pages,
  5624. event->attr.watermark ? event->attr.wakeup_watermark : 0,
  5625. event->cpu, flags);
  5626. if (!rb) {
  5627. ret = -ENOMEM;
  5628. goto unlock;
  5629. }
  5630. atomic_set(&rb->mmap_count, 1);
  5631. rb->mmap_user = get_current_user();
  5632. rb->mmap_locked = extra;
  5633. ring_buffer_attach(event, rb);
  5634. perf_event_update_time(event);
  5635. perf_event_init_userpage(event);
  5636. perf_event_update_userpage(event);
  5637. } else {
  5638. ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
  5639. event->attr.aux_watermark, flags);
  5640. if (!ret) {
  5641. atomic_set(&rb->aux_mmap_count, 1);
  5642. rb->aux_mmap_locked = extra;
  5643. }
  5644. }
  5645. unlock:
  5646. if (!ret) {
  5647. atomic_long_add(user_extra, &user->locked_vm);
  5648. atomic64_add(extra, &vma->vm_mm->pinned_vm);
  5649. atomic_inc(&event->mmap_count);
  5650. } else if (rb) {
  5651. /* AUX allocation failed */
  5652. atomic_dec(&rb->mmap_count);
  5653. }
  5654. aux_unlock:
  5655. if (aux_mutex)
  5656. mutex_unlock(aux_mutex);
  5657. mutex_unlock(&event->mmap_mutex);
  5658. if (ret)
  5659. return ret;
  5660. /*
  5661. * Since pinned accounting is per vm we cannot allow fork() to copy our
  5662. * vma.
  5663. */
  5664. vm_flags_set(vma, VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP);
  5665. vma->vm_ops = &perf_mmap_vmops;
  5666. if (event->pmu->event_mapped)
  5667. event->pmu->event_mapped(event, vma->vm_mm);
  5668. return ret;
  5669. }
  5670. static int perf_fasync(int fd, struct file *filp, int on)
  5671. {
  5672. struct inode *inode = file_inode(filp);
  5673. struct perf_event *event = filp->private_data;
  5674. int retval;
  5675. inode_lock(inode);
  5676. retval = fasync_helper(fd, filp, on, &event->fasync);
  5677. inode_unlock(inode);
  5678. if (retval < 0)
  5679. return retval;
  5680. return 0;
  5681. }
  5682. static const struct file_operations perf_fops = {
  5683. .release = perf_release,
  5684. .read = perf_read,
  5685. .poll = perf_poll,
  5686. .unlocked_ioctl = perf_ioctl,
  5687. .compat_ioctl = perf_compat_ioctl,
  5688. .mmap = perf_mmap,
  5689. .fasync = perf_fasync,
  5690. };
  5691. /*
  5692. * Perf event wakeup
  5693. *
  5694. * If there's data, ensure we set the poll() state and publish everything
  5695. * to user-space before waking everybody up.
  5696. */
  5697. void perf_event_wakeup(struct perf_event *event)
  5698. {
  5699. ring_buffer_wakeup(event);
  5700. if (event->pending_kill) {
  5701. kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
  5702. event->pending_kill = 0;
  5703. }
  5704. }
  5705. static void perf_sigtrap(struct perf_event *event)
  5706. {
  5707. /*
  5708. * We'd expect this to only occur if the irq_work is delayed and either
  5709. * ctx->task or current has changed in the meantime. This can be the
  5710. * case on architectures that do not implement arch_irq_work_raise().
  5711. */
  5712. if (WARN_ON_ONCE(event->ctx->task != current))
  5713. return;
  5714. /*
  5715. * Both perf_pending_task() and perf_pending_irq() can race with the
  5716. * task exiting.
  5717. */
  5718. if (current->flags & PF_EXITING)
  5719. return;
  5720. send_sig_perf((void __user *)event->pending_addr,
  5721. event->orig_type, event->attr.sig_data);
  5722. }
  5723. /*
  5724. * Deliver the pending work in-event-context or follow the context.
  5725. */
  5726. static void __perf_pending_disable(struct perf_event *event)
  5727. {
  5728. int cpu = READ_ONCE(event->oncpu);
  5729. /*
  5730. * If the event isn't running; we done. event_sched_out() will have
  5731. * taken care of things.
  5732. */
  5733. if (cpu < 0)
  5734. return;
  5735. /*
  5736. * Yay, we hit home and are in the context of the event.
  5737. */
  5738. if (cpu == smp_processor_id()) {
  5739. if (event->pending_disable) {
  5740. event->pending_disable = 0;
  5741. perf_event_disable_local(event);
  5742. }
  5743. return;
  5744. }
  5745. /*
  5746. * CPU-A CPU-B
  5747. *
  5748. * perf_event_disable_inatomic()
  5749. * @pending_disable = CPU-A;
  5750. * irq_work_queue();
  5751. *
  5752. * sched-out
  5753. * @pending_disable = -1;
  5754. *
  5755. * sched-in
  5756. * perf_event_disable_inatomic()
  5757. * @pending_disable = CPU-B;
  5758. * irq_work_queue(); // FAILS
  5759. *
  5760. * irq_work_run()
  5761. * perf_pending_disable()
  5762. *
  5763. * But the event runs on CPU-B and wants disabling there.
  5764. */
  5765. irq_work_queue_on(&event->pending_disable_irq, cpu);
  5766. }
  5767. static void perf_pending_disable(struct irq_work *entry)
  5768. {
  5769. struct perf_event *event = container_of(entry, struct perf_event, pending_disable_irq);
  5770. int rctx;
  5771. /*
  5772. * If we 'fail' here, that's OK, it means recursion is already disabled
  5773. * and we won't recurse 'further'.
  5774. */
  5775. rctx = perf_swevent_get_recursion_context();
  5776. __perf_pending_disable(event);
  5777. if (rctx >= 0)
  5778. perf_swevent_put_recursion_context(rctx);
  5779. }
  5780. static void perf_pending_irq(struct irq_work *entry)
  5781. {
  5782. struct perf_event *event = container_of(entry, struct perf_event, pending_irq);
  5783. int rctx;
  5784. /*
  5785. * If we 'fail' here, that's OK, it means recursion is already disabled
  5786. * and we won't recurse 'further'.
  5787. */
  5788. rctx = perf_swevent_get_recursion_context();
  5789. /*
  5790. * The wakeup isn't bound to the context of the event -- it can happen
  5791. * irrespective of where the event is.
  5792. */
  5793. if (event->pending_wakeup) {
  5794. event->pending_wakeup = 0;
  5795. perf_event_wakeup(event);
  5796. }
  5797. if (rctx >= 0)
  5798. perf_swevent_put_recursion_context(rctx);
  5799. }
  5800. static void perf_pending_task(struct callback_head *head)
  5801. {
  5802. struct perf_event *event = container_of(head, struct perf_event, pending_task);
  5803. int rctx;
  5804. /*
  5805. * If we 'fail' here, that's OK, it means recursion is already disabled
  5806. * and we won't recurse 'further'.
  5807. */
  5808. rctx = perf_swevent_get_recursion_context();
  5809. if (event->pending_work) {
  5810. event->pending_work = 0;
  5811. perf_sigtrap(event);
  5812. local_dec(&event->ctx->nr_no_switch_fast);
  5813. }
  5814. put_event(event);
  5815. if (rctx >= 0)
  5816. perf_swevent_put_recursion_context(rctx);
  5817. }
  5818. #ifdef CONFIG_GUEST_PERF_EVENTS
  5819. struct perf_guest_info_callbacks __rcu *perf_guest_cbs;
  5820. DEFINE_STATIC_CALL_RET0(__perf_guest_state, *perf_guest_cbs->state);
  5821. DEFINE_STATIC_CALL_RET0(__perf_guest_get_ip, *perf_guest_cbs->get_ip);
  5822. DEFINE_STATIC_CALL_RET0(__perf_guest_handle_intel_pt_intr, *perf_guest_cbs->handle_intel_pt_intr);
  5823. void perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
  5824. {
  5825. if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs)))
  5826. return;
  5827. rcu_assign_pointer(perf_guest_cbs, cbs);
  5828. static_call_update(__perf_guest_state, cbs->state);
  5829. static_call_update(__perf_guest_get_ip, cbs->get_ip);
  5830. /* Implementing ->handle_intel_pt_intr is optional. */
  5831. if (cbs->handle_intel_pt_intr)
  5832. static_call_update(__perf_guest_handle_intel_pt_intr,
  5833. cbs->handle_intel_pt_intr);
  5834. }
  5835. EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
  5836. void perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
  5837. {
  5838. if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs) != cbs))
  5839. return;
  5840. rcu_assign_pointer(perf_guest_cbs, NULL);
  5841. static_call_update(__perf_guest_state, (void *)&__static_call_return0);
  5842. static_call_update(__perf_guest_get_ip, (void *)&__static_call_return0);
  5843. static_call_update(__perf_guest_handle_intel_pt_intr,
  5844. (void *)&__static_call_return0);
  5845. synchronize_rcu();
  5846. }
  5847. EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
  5848. #endif
  5849. static void
  5850. perf_output_sample_regs(struct perf_output_handle *handle,
  5851. struct pt_regs *regs, u64 mask)
  5852. {
  5853. int bit;
  5854. DECLARE_BITMAP(_mask, 64);
  5855. bitmap_from_u64(_mask, mask);
  5856. for_each_set_bit(bit, _mask, sizeof(mask) * BITS_PER_BYTE) {
  5857. u64 val;
  5858. val = perf_reg_value(regs, bit);
  5859. perf_output_put(handle, val);
  5860. }
  5861. }
  5862. static void perf_sample_regs_user(struct perf_regs *regs_user,
  5863. struct pt_regs *regs)
  5864. {
  5865. if (user_mode(regs)) {
  5866. regs_user->abi = perf_reg_abi(current);
  5867. regs_user->regs = regs;
  5868. } else if (!(current->flags & PF_KTHREAD)) {
  5869. perf_get_regs_user(regs_user, regs);
  5870. } else {
  5871. regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
  5872. regs_user->regs = NULL;
  5873. }
  5874. }
  5875. static void perf_sample_regs_intr(struct perf_regs *regs_intr,
  5876. struct pt_regs *regs)
  5877. {
  5878. regs_intr->regs = regs;
  5879. regs_intr->abi = perf_reg_abi(current);
  5880. }
  5881. /*
  5882. * Get remaining task size from user stack pointer.
  5883. *
  5884. * It'd be better to take stack vma map and limit this more
  5885. * precisely, but there's no way to get it safely under interrupt,
  5886. * so using TASK_SIZE as limit.
  5887. */
  5888. static u64 perf_ustack_task_size(struct pt_regs *regs)
  5889. {
  5890. unsigned long addr = perf_user_stack_pointer(regs);
  5891. if (!addr || addr >= TASK_SIZE)
  5892. return 0;
  5893. return TASK_SIZE - addr;
  5894. }
  5895. static u16
  5896. perf_sample_ustack_size(u16 stack_size, u16 header_size,
  5897. struct pt_regs *regs)
  5898. {
  5899. u64 task_size;
  5900. /* No regs, no stack pointer, no dump. */
  5901. if (!regs)
  5902. return 0;
  5903. /* No mm, no stack, no dump. */
  5904. if (!current->mm)
  5905. return 0;
  5906. /*
  5907. * Check if we fit in with the requested stack size into the:
  5908. * - TASK_SIZE
  5909. * If we don't, we limit the size to the TASK_SIZE.
  5910. *
  5911. * - remaining sample size
  5912. * If we don't, we customize the stack size to
  5913. * fit in to the remaining sample size.
  5914. */
  5915. task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
  5916. stack_size = min(stack_size, (u16) task_size);
  5917. /* Current header size plus static size and dynamic size. */
  5918. header_size += 2 * sizeof(u64);
  5919. /* Do we fit in with the current stack dump size? */
  5920. if ((u16) (header_size + stack_size) < header_size) {
  5921. /*
  5922. * If we overflow the maximum size for the sample,
  5923. * we customize the stack dump size to fit in.
  5924. */
  5925. stack_size = USHRT_MAX - header_size - sizeof(u64);
  5926. stack_size = round_up(stack_size, sizeof(u64));
  5927. }
  5928. return stack_size;
  5929. }
  5930. static void
  5931. perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
  5932. struct pt_regs *regs)
  5933. {
  5934. /* Case of a kernel thread, nothing to dump */
  5935. if (!regs) {
  5936. u64 size = 0;
  5937. perf_output_put(handle, size);
  5938. } else {
  5939. unsigned long sp;
  5940. unsigned int rem;
  5941. u64 dyn_size;
  5942. /*
  5943. * We dump:
  5944. * static size
  5945. * - the size requested by user or the best one we can fit
  5946. * in to the sample max size
  5947. * data
  5948. * - user stack dump data
  5949. * dynamic size
  5950. * - the actual dumped size
  5951. */
  5952. /* Static size. */
  5953. perf_output_put(handle, dump_size);
  5954. /* Data. */
  5955. sp = perf_user_stack_pointer(regs);
  5956. rem = __output_copy_user(handle, (void *) sp, dump_size);
  5957. dyn_size = dump_size - rem;
  5958. perf_output_skip(handle, rem);
  5959. /* Dynamic size. */
  5960. perf_output_put(handle, dyn_size);
  5961. }
  5962. }
  5963. static unsigned long perf_prepare_sample_aux(struct perf_event *event,
  5964. struct perf_sample_data *data,
  5965. size_t size)
  5966. {
  5967. struct perf_event *sampler = event->aux_event;
  5968. struct perf_buffer *rb;
  5969. data->aux_size = 0;
  5970. if (!sampler)
  5971. goto out;
  5972. if (WARN_ON_ONCE(READ_ONCE(sampler->state) != PERF_EVENT_STATE_ACTIVE))
  5973. goto out;
  5974. if (WARN_ON_ONCE(READ_ONCE(sampler->oncpu) != smp_processor_id()))
  5975. goto out;
  5976. rb = ring_buffer_get(sampler);
  5977. if (!rb)
  5978. goto out;
  5979. /*
  5980. * If this is an NMI hit inside sampling code, don't take
  5981. * the sample. See also perf_aux_sample_output().
  5982. */
  5983. if (READ_ONCE(rb->aux_in_sampling)) {
  5984. data->aux_size = 0;
  5985. } else {
  5986. size = min_t(size_t, size, perf_aux_size(rb));
  5987. data->aux_size = ALIGN(size, sizeof(u64));
  5988. }
  5989. ring_buffer_put(rb);
  5990. out:
  5991. return data->aux_size;
  5992. }
  5993. static long perf_pmu_snapshot_aux(struct perf_buffer *rb,
  5994. struct perf_event *event,
  5995. struct perf_output_handle *handle,
  5996. unsigned long size)
  5997. {
  5998. unsigned long flags;
  5999. long ret;
  6000. /*
  6001. * Normal ->start()/->stop() callbacks run in IRQ mode in scheduler
  6002. * paths. If we start calling them in NMI context, they may race with
  6003. * the IRQ ones, that is, for example, re-starting an event that's just
  6004. * been stopped, which is why we're using a separate callback that
  6005. * doesn't change the event state.
  6006. *
  6007. * IRQs need to be disabled to prevent IPIs from racing with us.
  6008. */
  6009. local_irq_save(flags);
  6010. /*
  6011. * Guard against NMI hits inside the critical section;
  6012. * see also perf_prepare_sample_aux().
  6013. */
  6014. WRITE_ONCE(rb->aux_in_sampling, 1);
  6015. barrier();
  6016. ret = event->pmu->snapshot_aux(event, handle, size);
  6017. barrier();
  6018. WRITE_ONCE(rb->aux_in_sampling, 0);
  6019. local_irq_restore(flags);
  6020. return ret;
  6021. }
  6022. static void perf_aux_sample_output(struct perf_event *event,
  6023. struct perf_output_handle *handle,
  6024. struct perf_sample_data *data)
  6025. {
  6026. struct perf_event *sampler = event->aux_event;
  6027. struct perf_buffer *rb;
  6028. unsigned long pad;
  6029. long size;
  6030. if (WARN_ON_ONCE(!sampler || !data->aux_size))
  6031. return;
  6032. rb = ring_buffer_get(sampler);
  6033. if (!rb)
  6034. return;
  6035. size = perf_pmu_snapshot_aux(rb, sampler, handle, data->aux_size);
  6036. /*
  6037. * An error here means that perf_output_copy() failed (returned a
  6038. * non-zero surplus that it didn't copy), which in its current
  6039. * enlightened implementation is not possible. If that changes, we'd
  6040. * like to know.
  6041. */
  6042. if (WARN_ON_ONCE(size < 0))
  6043. goto out_put;
  6044. /*
  6045. * The pad comes from ALIGN()ing data->aux_size up to u64 in
  6046. * perf_prepare_sample_aux(), so should not be more than that.
  6047. */
  6048. pad = data->aux_size - size;
  6049. if (WARN_ON_ONCE(pad >= sizeof(u64)))
  6050. pad = 8;
  6051. if (pad) {
  6052. u64 zero = 0;
  6053. perf_output_copy(handle, &zero, pad);
  6054. }
  6055. out_put:
  6056. ring_buffer_put(rb);
  6057. }
  6058. /*
  6059. * A set of common sample data types saved even for non-sample records
  6060. * when event->attr.sample_id_all is set.
  6061. */
  6062. #define PERF_SAMPLE_ID_ALL (PERF_SAMPLE_TID | PERF_SAMPLE_TIME | \
  6063. PERF_SAMPLE_ID | PERF_SAMPLE_STREAM_ID | \
  6064. PERF_SAMPLE_CPU | PERF_SAMPLE_IDENTIFIER)
  6065. static void __perf_event_header__init_id(struct perf_sample_data *data,
  6066. struct perf_event *event,
  6067. u64 sample_type)
  6068. {
  6069. data->type = event->attr.sample_type;
  6070. data->sample_flags |= data->type & PERF_SAMPLE_ID_ALL;
  6071. if (sample_type & PERF_SAMPLE_TID) {
  6072. /* namespace issues */
  6073. data->tid_entry.pid = perf_event_pid(event, current);
  6074. data->tid_entry.tid = perf_event_tid(event, current);
  6075. }
  6076. if (sample_type & PERF_SAMPLE_TIME)
  6077. data->time = perf_event_clock(event);
  6078. if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
  6079. data->id = primary_event_id(event);
  6080. if (sample_type & PERF_SAMPLE_STREAM_ID)
  6081. data->stream_id = event->id;
  6082. if (sample_type & PERF_SAMPLE_CPU) {
  6083. data->cpu_entry.cpu = raw_smp_processor_id();
  6084. data->cpu_entry.reserved = 0;
  6085. }
  6086. }
  6087. void perf_event_header__init_id(struct perf_event_header *header,
  6088. struct perf_sample_data *data,
  6089. struct perf_event *event)
  6090. {
  6091. if (event->attr.sample_id_all) {
  6092. header->size += event->id_header_size;
  6093. __perf_event_header__init_id(data, event, event->attr.sample_type);
  6094. }
  6095. }
  6096. static void __perf_event__output_id_sample(struct perf_output_handle *handle,
  6097. struct perf_sample_data *data)
  6098. {
  6099. u64 sample_type = data->type;
  6100. if (sample_type & PERF_SAMPLE_TID)
  6101. perf_output_put(handle, data->tid_entry);
  6102. if (sample_type & PERF_SAMPLE_TIME)
  6103. perf_output_put(handle, data->time);
  6104. if (sample_type & PERF_SAMPLE_ID)
  6105. perf_output_put(handle, data->id);
  6106. if (sample_type & PERF_SAMPLE_STREAM_ID)
  6107. perf_output_put(handle, data->stream_id);
  6108. if (sample_type & PERF_SAMPLE_CPU)
  6109. perf_output_put(handle, data->cpu_entry);
  6110. if (sample_type & PERF_SAMPLE_IDENTIFIER)
  6111. perf_output_put(handle, data->id);
  6112. }
  6113. void perf_event__output_id_sample(struct perf_event *event,
  6114. struct perf_output_handle *handle,
  6115. struct perf_sample_data *sample)
  6116. {
  6117. if (event->attr.sample_id_all)
  6118. __perf_event__output_id_sample(handle, sample);
  6119. }
  6120. static void perf_output_read_one(struct perf_output_handle *handle,
  6121. struct perf_event *event,
  6122. u64 enabled, u64 running)
  6123. {
  6124. u64 read_format = event->attr.read_format;
  6125. u64 values[5];
  6126. int n = 0;
  6127. values[n++] = perf_event_count(event, has_inherit_and_sample_read(&event->attr));
  6128. if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
  6129. values[n++] = enabled +
  6130. atomic64_read(&event->child_total_time_enabled);
  6131. }
  6132. if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
  6133. values[n++] = running +
  6134. atomic64_read(&event->child_total_time_running);
  6135. }
  6136. if (read_format & PERF_FORMAT_ID)
  6137. values[n++] = primary_event_id(event);
  6138. if (read_format & PERF_FORMAT_LOST)
  6139. values[n++] = atomic64_read(&event->lost_samples);
  6140. __output_copy(handle, values, n * sizeof(u64));
  6141. }
  6142. static void perf_output_read_group(struct perf_output_handle *handle,
  6143. struct perf_event *event,
  6144. u64 enabled, u64 running)
  6145. {
  6146. struct perf_event *leader = event->group_leader, *sub;
  6147. u64 read_format = event->attr.read_format;
  6148. unsigned long flags;
  6149. u64 values[6];
  6150. int n = 0;
  6151. bool self = has_inherit_and_sample_read(&event->attr);
  6152. /*
  6153. * Disabling interrupts avoids all counter scheduling
  6154. * (context switches, timer based rotation and IPIs).
  6155. */
  6156. local_irq_save(flags);
  6157. values[n++] = 1 + leader->nr_siblings;
  6158. if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
  6159. values[n++] = enabled;
  6160. if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
  6161. values[n++] = running;
  6162. if ((leader != event) && !handle->skip_read)
  6163. perf_pmu_read(leader);
  6164. values[n++] = perf_event_count(leader, self);
  6165. if (read_format & PERF_FORMAT_ID)
  6166. values[n++] = primary_event_id(leader);
  6167. if (read_format & PERF_FORMAT_LOST)
  6168. values[n++] = atomic64_read(&leader->lost_samples);
  6169. __output_copy(handle, values, n * sizeof(u64));
  6170. for_each_sibling_event(sub, leader) {
  6171. n = 0;
  6172. if ((sub != event) && !handle->skip_read)
  6173. perf_pmu_read(sub);
  6174. values[n++] = perf_event_count(sub, self);
  6175. if (read_format & PERF_FORMAT_ID)
  6176. values[n++] = primary_event_id(sub);
  6177. if (read_format & PERF_FORMAT_LOST)
  6178. values[n++] = atomic64_read(&sub->lost_samples);
  6179. __output_copy(handle, values, n * sizeof(u64));
  6180. }
  6181. local_irq_restore(flags);
  6182. }
  6183. #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
  6184. PERF_FORMAT_TOTAL_TIME_RUNNING)
  6185. /*
  6186. * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
  6187. *
  6188. * The problem is that its both hard and excessively expensive to iterate the
  6189. * child list, not to mention that its impossible to IPI the children running
  6190. * on another CPU, from interrupt/NMI context.
  6191. *
  6192. * Instead the combination of PERF_SAMPLE_READ and inherit will track per-thread
  6193. * counts rather than attempting to accumulate some value across all children on
  6194. * all cores.
  6195. */
  6196. static void perf_output_read(struct perf_output_handle *handle,
  6197. struct perf_event *event)
  6198. {
  6199. u64 enabled = 0, running = 0, now;
  6200. u64 read_format = event->attr.read_format;
  6201. /*
  6202. * compute total_time_enabled, total_time_running
  6203. * based on snapshot values taken when the event
  6204. * was last scheduled in.
  6205. *
  6206. * we cannot simply called update_context_time()
  6207. * because of locking issue as we are called in
  6208. * NMI context
  6209. */
  6210. if (read_format & PERF_FORMAT_TOTAL_TIMES)
  6211. calc_timer_values(event, &now, &enabled, &running);
  6212. if (event->attr.read_format & PERF_FORMAT_GROUP)
  6213. perf_output_read_group(handle, event, enabled, running);
  6214. else
  6215. perf_output_read_one(handle, event, enabled, running);
  6216. }
  6217. void perf_output_sample(struct perf_output_handle *handle,
  6218. struct perf_event_header *header,
  6219. struct perf_sample_data *data,
  6220. struct perf_event *event)
  6221. {
  6222. u64 sample_type = data->type;
  6223. if (data->sample_flags & PERF_SAMPLE_READ)
  6224. handle->skip_read = 1;
  6225. perf_output_put(handle, *header);
  6226. if (sample_type & PERF_SAMPLE_IDENTIFIER)
  6227. perf_output_put(handle, data->id);
  6228. if (sample_type & PERF_SAMPLE_IP)
  6229. perf_output_put(handle, data->ip);
  6230. if (sample_type & PERF_SAMPLE_TID)
  6231. perf_output_put(handle, data->tid_entry);
  6232. if (sample_type & PERF_SAMPLE_TIME)
  6233. perf_output_put(handle, data->time);
  6234. if (sample_type & PERF_SAMPLE_ADDR)
  6235. perf_output_put(handle, data->addr);
  6236. if (sample_type & PERF_SAMPLE_ID)
  6237. perf_output_put(handle, data->id);
  6238. if (sample_type & PERF_SAMPLE_STREAM_ID)
  6239. perf_output_put(handle, data->stream_id);
  6240. if (sample_type & PERF_SAMPLE_CPU)
  6241. perf_output_put(handle, data->cpu_entry);
  6242. if (sample_type & PERF_SAMPLE_PERIOD)
  6243. perf_output_put(handle, data->period);
  6244. if (sample_type & PERF_SAMPLE_READ)
  6245. perf_output_read(handle, event);
  6246. if (sample_type & PERF_SAMPLE_CALLCHAIN) {
  6247. int size = 1;
  6248. size += data->callchain->nr;
  6249. size *= sizeof(u64);
  6250. __output_copy(handle, data->callchain, size);
  6251. }
  6252. if (sample_type & PERF_SAMPLE_RAW) {
  6253. struct perf_raw_record *raw = data->raw;
  6254. if (raw) {
  6255. struct perf_raw_frag *frag = &raw->frag;
  6256. perf_output_put(handle, raw->size);
  6257. do {
  6258. if (frag->copy) {
  6259. __output_custom(handle, frag->copy,
  6260. frag->data, frag->size);
  6261. } else {
  6262. __output_copy(handle, frag->data,
  6263. frag->size);
  6264. }
  6265. if (perf_raw_frag_last(frag))
  6266. break;
  6267. frag = frag->next;
  6268. } while (1);
  6269. if (frag->pad)
  6270. __output_skip(handle, NULL, frag->pad);
  6271. } else {
  6272. struct {
  6273. u32 size;
  6274. u32 data;
  6275. } raw = {
  6276. .size = sizeof(u32),
  6277. .data = 0,
  6278. };
  6279. perf_output_put(handle, raw);
  6280. }
  6281. }
  6282. if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
  6283. if (data->br_stack) {
  6284. size_t size;
  6285. size = data->br_stack->nr
  6286. * sizeof(struct perf_branch_entry);
  6287. perf_output_put(handle, data->br_stack->nr);
  6288. if (branch_sample_hw_index(event))
  6289. perf_output_put(handle, data->br_stack->hw_idx);
  6290. perf_output_copy(handle, data->br_stack->entries, size);
  6291. /*
  6292. * Add the extension space which is appended
  6293. * right after the struct perf_branch_stack.
  6294. */
  6295. if (data->br_stack_cntr) {
  6296. size = data->br_stack->nr * sizeof(u64);
  6297. perf_output_copy(handle, data->br_stack_cntr, size);
  6298. }
  6299. } else {
  6300. /*
  6301. * we always store at least the value of nr
  6302. */
  6303. u64 nr = 0;
  6304. perf_output_put(handle, nr);
  6305. }
  6306. }
  6307. if (sample_type & PERF_SAMPLE_REGS_USER) {
  6308. u64 abi = data->regs_user.abi;
  6309. /*
  6310. * If there are no regs to dump, notice it through
  6311. * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
  6312. */
  6313. perf_output_put(handle, abi);
  6314. if (abi) {
  6315. u64 mask = event->attr.sample_regs_user;
  6316. perf_output_sample_regs(handle,
  6317. data->regs_user.regs,
  6318. mask);
  6319. }
  6320. }
  6321. if (sample_type & PERF_SAMPLE_STACK_USER) {
  6322. perf_output_sample_ustack(handle,
  6323. data->stack_user_size,
  6324. data->regs_user.regs);
  6325. }
  6326. if (sample_type & PERF_SAMPLE_WEIGHT_TYPE)
  6327. perf_output_put(handle, data->weight.full);
  6328. if (sample_type & PERF_SAMPLE_DATA_SRC)
  6329. perf_output_put(handle, data->data_src.val);
  6330. if (sample_type & PERF_SAMPLE_TRANSACTION)
  6331. perf_output_put(handle, data->txn);
  6332. if (sample_type & PERF_SAMPLE_REGS_INTR) {
  6333. u64 abi = data->regs_intr.abi;
  6334. /*
  6335. * If there are no regs to dump, notice it through
  6336. * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
  6337. */
  6338. perf_output_put(handle, abi);
  6339. if (abi) {
  6340. u64 mask = event->attr.sample_regs_intr;
  6341. perf_output_sample_regs(handle,
  6342. data->regs_intr.regs,
  6343. mask);
  6344. }
  6345. }
  6346. if (sample_type & PERF_SAMPLE_PHYS_ADDR)
  6347. perf_output_put(handle, data->phys_addr);
  6348. if (sample_type & PERF_SAMPLE_CGROUP)
  6349. perf_output_put(handle, data->cgroup);
  6350. if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
  6351. perf_output_put(handle, data->data_page_size);
  6352. if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
  6353. perf_output_put(handle, data->code_page_size);
  6354. if (sample_type & PERF_SAMPLE_AUX) {
  6355. perf_output_put(handle, data->aux_size);
  6356. if (data->aux_size)
  6357. perf_aux_sample_output(event, handle, data);
  6358. }
  6359. if (!event->attr.watermark) {
  6360. int wakeup_events = event->attr.wakeup_events;
  6361. if (wakeup_events) {
  6362. struct perf_buffer *rb = handle->rb;
  6363. int events = local_inc_return(&rb->events);
  6364. if (events >= wakeup_events) {
  6365. local_sub(wakeup_events, &rb->events);
  6366. local_inc(&rb->wakeup);
  6367. }
  6368. }
  6369. }
  6370. }
  6371. static u64 perf_virt_to_phys(u64 virt)
  6372. {
  6373. u64 phys_addr = 0;
  6374. if (!virt)
  6375. return 0;
  6376. if (virt >= TASK_SIZE) {
  6377. /* If it's vmalloc()d memory, leave phys_addr as 0 */
  6378. if (virt_addr_valid((void *)(uintptr_t)virt) &&
  6379. !(virt >= VMALLOC_START && virt < VMALLOC_END))
  6380. phys_addr = (u64)virt_to_phys((void *)(uintptr_t)virt);
  6381. } else {
  6382. /*
  6383. * Walking the pages tables for user address.
  6384. * Interrupts are disabled, so it prevents any tear down
  6385. * of the page tables.
  6386. * Try IRQ-safe get_user_page_fast_only first.
  6387. * If failed, leave phys_addr as 0.
  6388. */
  6389. if (current->mm != NULL) {
  6390. struct page *p;
  6391. pagefault_disable();
  6392. if (get_user_page_fast_only(virt, 0, &p)) {
  6393. phys_addr = page_to_phys(p) + virt % PAGE_SIZE;
  6394. put_page(p);
  6395. }
  6396. pagefault_enable();
  6397. }
  6398. }
  6399. return phys_addr;
  6400. }
  6401. /*
  6402. * Return the pagetable size of a given virtual address.
  6403. */
  6404. static u64 perf_get_pgtable_size(struct mm_struct *mm, unsigned long addr)
  6405. {
  6406. u64 size = 0;
  6407. #ifdef CONFIG_HAVE_GUP_FAST
  6408. pgd_t *pgdp, pgd;
  6409. p4d_t *p4dp, p4d;
  6410. pud_t *pudp, pud;
  6411. pmd_t *pmdp, pmd;
  6412. pte_t *ptep, pte;
  6413. pgdp = pgd_offset(mm, addr);
  6414. pgd = READ_ONCE(*pgdp);
  6415. if (pgd_none(pgd))
  6416. return 0;
  6417. if (pgd_leaf(pgd))
  6418. return pgd_leaf_size(pgd);
  6419. p4dp = p4d_offset_lockless(pgdp, pgd, addr);
  6420. p4d = READ_ONCE(*p4dp);
  6421. if (!p4d_present(p4d))
  6422. return 0;
  6423. if (p4d_leaf(p4d))
  6424. return p4d_leaf_size(p4d);
  6425. pudp = pud_offset_lockless(p4dp, p4d, addr);
  6426. pud = READ_ONCE(*pudp);
  6427. if (!pud_present(pud))
  6428. return 0;
  6429. if (pud_leaf(pud))
  6430. return pud_leaf_size(pud);
  6431. pmdp = pmd_offset_lockless(pudp, pud, addr);
  6432. again:
  6433. pmd = pmdp_get_lockless(pmdp);
  6434. if (!pmd_present(pmd))
  6435. return 0;
  6436. if (pmd_leaf(pmd))
  6437. return pmd_leaf_size(pmd);
  6438. ptep = pte_offset_map(&pmd, addr);
  6439. if (!ptep)
  6440. goto again;
  6441. pte = ptep_get_lockless(ptep);
  6442. if (pte_present(pte))
  6443. size = __pte_leaf_size(pmd, pte);
  6444. pte_unmap(ptep);
  6445. #endif /* CONFIG_HAVE_GUP_FAST */
  6446. return size;
  6447. }
  6448. static u64 perf_get_page_size(unsigned long addr)
  6449. {
  6450. struct mm_struct *mm;
  6451. unsigned long flags;
  6452. u64 size;
  6453. if (!addr)
  6454. return 0;
  6455. /*
  6456. * Software page-table walkers must disable IRQs,
  6457. * which prevents any tear down of the page tables.
  6458. */
  6459. local_irq_save(flags);
  6460. mm = current->mm;
  6461. if (!mm) {
  6462. /*
  6463. * For kernel threads and the like, use init_mm so that
  6464. * we can find kernel memory.
  6465. */
  6466. mm = &init_mm;
  6467. }
  6468. size = perf_get_pgtable_size(mm, addr);
  6469. local_irq_restore(flags);
  6470. return size;
  6471. }
  6472. static struct perf_callchain_entry __empty_callchain = { .nr = 0, };
  6473. struct perf_callchain_entry *
  6474. perf_callchain(struct perf_event *event, struct pt_regs *regs)
  6475. {
  6476. bool kernel = !event->attr.exclude_callchain_kernel;
  6477. bool user = !event->attr.exclude_callchain_user;
  6478. /* Disallow cross-task user callchains. */
  6479. bool crosstask = event->ctx->task && event->ctx->task != current;
  6480. const u32 max_stack = event->attr.sample_max_stack;
  6481. struct perf_callchain_entry *callchain;
  6482. if (!current->mm)
  6483. user = false;
  6484. if (!kernel && !user)
  6485. return &__empty_callchain;
  6486. callchain = get_perf_callchain(regs, 0, kernel, user,
  6487. max_stack, crosstask, true);
  6488. return callchain ?: &__empty_callchain;
  6489. }
  6490. static __always_inline u64 __cond_set(u64 flags, u64 s, u64 d)
  6491. {
  6492. return d * !!(flags & s);
  6493. }
  6494. void perf_prepare_sample(struct perf_sample_data *data,
  6495. struct perf_event *event,
  6496. struct pt_regs *regs)
  6497. {
  6498. u64 sample_type = event->attr.sample_type;
  6499. u64 filtered_sample_type;
  6500. /*
  6501. * Add the sample flags that are dependent to others. And clear the
  6502. * sample flags that have already been done by the PMU driver.
  6503. */
  6504. filtered_sample_type = sample_type;
  6505. filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_CODE_PAGE_SIZE,
  6506. PERF_SAMPLE_IP);
  6507. filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_DATA_PAGE_SIZE |
  6508. PERF_SAMPLE_PHYS_ADDR, PERF_SAMPLE_ADDR);
  6509. filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_STACK_USER,
  6510. PERF_SAMPLE_REGS_USER);
  6511. filtered_sample_type &= ~data->sample_flags;
  6512. if (filtered_sample_type == 0) {
  6513. /* Make sure it has the correct data->type for output */
  6514. data->type = event->attr.sample_type;
  6515. return;
  6516. }
  6517. __perf_event_header__init_id(data, event, filtered_sample_type);
  6518. if (filtered_sample_type & PERF_SAMPLE_IP) {
  6519. data->ip = perf_instruction_pointer(regs);
  6520. data->sample_flags |= PERF_SAMPLE_IP;
  6521. }
  6522. if (filtered_sample_type & PERF_SAMPLE_CALLCHAIN)
  6523. perf_sample_save_callchain(data, event, regs);
  6524. if (filtered_sample_type & PERF_SAMPLE_RAW) {
  6525. data->raw = NULL;
  6526. data->dyn_size += sizeof(u64);
  6527. data->sample_flags |= PERF_SAMPLE_RAW;
  6528. }
  6529. if (filtered_sample_type & PERF_SAMPLE_BRANCH_STACK) {
  6530. data->br_stack = NULL;
  6531. data->dyn_size += sizeof(u64);
  6532. data->sample_flags |= PERF_SAMPLE_BRANCH_STACK;
  6533. }
  6534. if (filtered_sample_type & PERF_SAMPLE_REGS_USER)
  6535. perf_sample_regs_user(&data->regs_user, regs);
  6536. /*
  6537. * It cannot use the filtered_sample_type here as REGS_USER can be set
  6538. * by STACK_USER (using __cond_set() above) and we don't want to update
  6539. * the dyn_size if it's not requested by users.
  6540. */
  6541. if ((sample_type & ~data->sample_flags) & PERF_SAMPLE_REGS_USER) {
  6542. /* regs dump ABI info */
  6543. int size = sizeof(u64);
  6544. if (data->regs_user.regs) {
  6545. u64 mask = event->attr.sample_regs_user;
  6546. size += hweight64(mask) * sizeof(u64);
  6547. }
  6548. data->dyn_size += size;
  6549. data->sample_flags |= PERF_SAMPLE_REGS_USER;
  6550. }
  6551. if (filtered_sample_type & PERF_SAMPLE_STACK_USER) {
  6552. /*
  6553. * Either we need PERF_SAMPLE_STACK_USER bit to be always
  6554. * processed as the last one or have additional check added
  6555. * in case new sample type is added, because we could eat
  6556. * up the rest of the sample size.
  6557. */
  6558. u16 stack_size = event->attr.sample_stack_user;
  6559. u16 header_size = perf_sample_data_size(data, event);
  6560. u16 size = sizeof(u64);
  6561. stack_size = perf_sample_ustack_size(stack_size, header_size,
  6562. data->regs_user.regs);
  6563. /*
  6564. * If there is something to dump, add space for the dump
  6565. * itself and for the field that tells the dynamic size,
  6566. * which is how many have been actually dumped.
  6567. */
  6568. if (stack_size)
  6569. size += sizeof(u64) + stack_size;
  6570. data->stack_user_size = stack_size;
  6571. data->dyn_size += size;
  6572. data->sample_flags |= PERF_SAMPLE_STACK_USER;
  6573. }
  6574. if (filtered_sample_type & PERF_SAMPLE_WEIGHT_TYPE) {
  6575. data->weight.full = 0;
  6576. data->sample_flags |= PERF_SAMPLE_WEIGHT_TYPE;
  6577. }
  6578. if (filtered_sample_type & PERF_SAMPLE_DATA_SRC) {
  6579. data->data_src.val = PERF_MEM_NA;
  6580. data->sample_flags |= PERF_SAMPLE_DATA_SRC;
  6581. }
  6582. if (filtered_sample_type & PERF_SAMPLE_TRANSACTION) {
  6583. data->txn = 0;
  6584. data->sample_flags |= PERF_SAMPLE_TRANSACTION;
  6585. }
  6586. if (filtered_sample_type & PERF_SAMPLE_ADDR) {
  6587. data->addr = 0;
  6588. data->sample_flags |= PERF_SAMPLE_ADDR;
  6589. }
  6590. if (filtered_sample_type & PERF_SAMPLE_REGS_INTR) {
  6591. /* regs dump ABI info */
  6592. int size = sizeof(u64);
  6593. perf_sample_regs_intr(&data->regs_intr, regs);
  6594. if (data->regs_intr.regs) {
  6595. u64 mask = event->attr.sample_regs_intr;
  6596. size += hweight64(mask) * sizeof(u64);
  6597. }
  6598. data->dyn_size += size;
  6599. data->sample_flags |= PERF_SAMPLE_REGS_INTR;
  6600. }
  6601. if (filtered_sample_type & PERF_SAMPLE_PHYS_ADDR) {
  6602. data->phys_addr = perf_virt_to_phys(data->addr);
  6603. data->sample_flags |= PERF_SAMPLE_PHYS_ADDR;
  6604. }
  6605. #ifdef CONFIG_CGROUP_PERF
  6606. if (filtered_sample_type & PERF_SAMPLE_CGROUP) {
  6607. struct cgroup *cgrp;
  6608. /* protected by RCU */
  6609. cgrp = task_css_check(current, perf_event_cgrp_id, 1)->cgroup;
  6610. data->cgroup = cgroup_id(cgrp);
  6611. data->sample_flags |= PERF_SAMPLE_CGROUP;
  6612. }
  6613. #endif
  6614. /*
  6615. * PERF_DATA_PAGE_SIZE requires PERF_SAMPLE_ADDR. If the user doesn't
  6616. * require PERF_SAMPLE_ADDR, kernel implicitly retrieve the data->addr,
  6617. * but the value will not dump to the userspace.
  6618. */
  6619. if (filtered_sample_type & PERF_SAMPLE_DATA_PAGE_SIZE) {
  6620. data->data_page_size = perf_get_page_size(data->addr);
  6621. data->sample_flags |= PERF_SAMPLE_DATA_PAGE_SIZE;
  6622. }
  6623. if (filtered_sample_type & PERF_SAMPLE_CODE_PAGE_SIZE) {
  6624. data->code_page_size = perf_get_page_size(data->ip);
  6625. data->sample_flags |= PERF_SAMPLE_CODE_PAGE_SIZE;
  6626. }
  6627. if (filtered_sample_type & PERF_SAMPLE_AUX) {
  6628. u64 size;
  6629. u16 header_size = perf_sample_data_size(data, event);
  6630. header_size += sizeof(u64); /* size */
  6631. /*
  6632. * Given the 16bit nature of header::size, an AUX sample can
  6633. * easily overflow it, what with all the preceding sample bits.
  6634. * Make sure this doesn't happen by using up to U16_MAX bytes
  6635. * per sample in total (rounded down to 8 byte boundary).
  6636. */
  6637. size = min_t(size_t, U16_MAX - header_size,
  6638. event->attr.aux_sample_size);
  6639. size = rounddown(size, 8);
  6640. size = perf_prepare_sample_aux(event, data, size);
  6641. WARN_ON_ONCE(size + header_size > U16_MAX);
  6642. data->dyn_size += size + sizeof(u64); /* size above */
  6643. data->sample_flags |= PERF_SAMPLE_AUX;
  6644. }
  6645. }
  6646. void perf_prepare_header(struct perf_event_header *header,
  6647. struct perf_sample_data *data,
  6648. struct perf_event *event,
  6649. struct pt_regs *regs)
  6650. {
  6651. header->type = PERF_RECORD_SAMPLE;
  6652. header->size = perf_sample_data_size(data, event);
  6653. header->misc = perf_misc_flags(regs);
  6654. /*
  6655. * If you're adding more sample types here, you likely need to do
  6656. * something about the overflowing header::size, like repurpose the
  6657. * lowest 3 bits of size, which should be always zero at the moment.
  6658. * This raises a more important question, do we really need 512k sized
  6659. * samples and why, so good argumentation is in order for whatever you
  6660. * do here next.
  6661. */
  6662. WARN_ON_ONCE(header->size & 7);
  6663. }
  6664. static void __perf_event_aux_pause(struct perf_event *event, bool pause)
  6665. {
  6666. if (pause) {
  6667. if (!event->hw.aux_paused) {
  6668. event->hw.aux_paused = 1;
  6669. event->pmu->stop(event, PERF_EF_PAUSE);
  6670. }
  6671. } else {
  6672. if (event->hw.aux_paused) {
  6673. event->hw.aux_paused = 0;
  6674. event->pmu->start(event, PERF_EF_RESUME);
  6675. }
  6676. }
  6677. }
  6678. static void perf_event_aux_pause(struct perf_event *event, bool pause)
  6679. {
  6680. struct perf_buffer *rb;
  6681. if (WARN_ON_ONCE(!event))
  6682. return;
  6683. rb = ring_buffer_get(event);
  6684. if (!rb)
  6685. return;
  6686. scoped_guard (irqsave) {
  6687. /*
  6688. * Guard against self-recursion here. Another event could trip
  6689. * this same from NMI context.
  6690. */
  6691. if (READ_ONCE(rb->aux_in_pause_resume))
  6692. break;
  6693. WRITE_ONCE(rb->aux_in_pause_resume, 1);
  6694. barrier();
  6695. __perf_event_aux_pause(event, pause);
  6696. barrier();
  6697. WRITE_ONCE(rb->aux_in_pause_resume, 0);
  6698. }
  6699. ring_buffer_put(rb);
  6700. }
  6701. static __always_inline int
  6702. __perf_event_output(struct perf_event *event,
  6703. struct perf_sample_data *data,
  6704. struct pt_regs *regs,
  6705. int (*output_begin)(struct perf_output_handle *,
  6706. struct perf_sample_data *,
  6707. struct perf_event *,
  6708. unsigned int))
  6709. {
  6710. struct perf_output_handle handle;
  6711. struct perf_event_header header;
  6712. int err;
  6713. /* protect the callchain buffers */
  6714. rcu_read_lock();
  6715. perf_prepare_sample(data, event, regs);
  6716. perf_prepare_header(&header, data, event, regs);
  6717. err = output_begin(&handle, data, event, header.size);
  6718. if (err)
  6719. goto exit;
  6720. perf_output_sample(&handle, &header, data, event);
  6721. perf_output_end(&handle);
  6722. exit:
  6723. rcu_read_unlock();
  6724. return err;
  6725. }
  6726. void
  6727. perf_event_output_forward(struct perf_event *event,
  6728. struct perf_sample_data *data,
  6729. struct pt_regs *regs)
  6730. {
  6731. __perf_event_output(event, data, regs, perf_output_begin_forward);
  6732. }
  6733. void
  6734. perf_event_output_backward(struct perf_event *event,
  6735. struct perf_sample_data *data,
  6736. struct pt_regs *regs)
  6737. {
  6738. __perf_event_output(event, data, regs, perf_output_begin_backward);
  6739. }
  6740. int
  6741. perf_event_output(struct perf_event *event,
  6742. struct perf_sample_data *data,
  6743. struct pt_regs *regs)
  6744. {
  6745. return __perf_event_output(event, data, regs, perf_output_begin);
  6746. }
  6747. /*
  6748. * read event_id
  6749. */
  6750. struct perf_read_event {
  6751. struct perf_event_header header;
  6752. u32 pid;
  6753. u32 tid;
  6754. };
  6755. static void
  6756. perf_event_read_event(struct perf_event *event,
  6757. struct task_struct *task)
  6758. {
  6759. struct perf_output_handle handle;
  6760. struct perf_sample_data sample;
  6761. struct perf_read_event read_event = {
  6762. .header = {
  6763. .type = PERF_RECORD_READ,
  6764. .misc = 0,
  6765. .size = sizeof(read_event) + event->read_size,
  6766. },
  6767. .pid = perf_event_pid(event, task),
  6768. .tid = perf_event_tid(event, task),
  6769. };
  6770. int ret;
  6771. perf_event_header__init_id(&read_event.header, &sample, event);
  6772. ret = perf_output_begin(&handle, &sample, event, read_event.header.size);
  6773. if (ret)
  6774. return;
  6775. perf_output_put(&handle, read_event);
  6776. perf_output_read(&handle, event);
  6777. perf_event__output_id_sample(event, &handle, &sample);
  6778. perf_output_end(&handle);
  6779. }
  6780. typedef void (perf_iterate_f)(struct perf_event *event, void *data);
  6781. static void
  6782. perf_iterate_ctx(struct perf_event_context *ctx,
  6783. perf_iterate_f output,
  6784. void *data, bool all)
  6785. {
  6786. struct perf_event *event;
  6787. list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
  6788. if (!all) {
  6789. if (event->state < PERF_EVENT_STATE_INACTIVE)
  6790. continue;
  6791. if (!event_filter_match(event))
  6792. continue;
  6793. }
  6794. output(event, data);
  6795. }
  6796. }
  6797. static void perf_iterate_sb_cpu(perf_iterate_f output, void *data)
  6798. {
  6799. struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events);
  6800. struct perf_event *event;
  6801. list_for_each_entry_rcu(event, &pel->list, sb_list) {
  6802. /*
  6803. * Skip events that are not fully formed yet; ensure that
  6804. * if we observe event->ctx, both event and ctx will be
  6805. * complete enough. See perf_install_in_context().
  6806. */
  6807. if (!smp_load_acquire(&event->ctx))
  6808. continue;
  6809. if (event->state < PERF_EVENT_STATE_INACTIVE)
  6810. continue;
  6811. if (!event_filter_match(event))
  6812. continue;
  6813. output(event, data);
  6814. }
  6815. }
  6816. /*
  6817. * Iterate all events that need to receive side-band events.
  6818. *
  6819. * For new callers; ensure that account_pmu_sb_event() includes
  6820. * your event, otherwise it might not get delivered.
  6821. */
  6822. static void
  6823. perf_iterate_sb(perf_iterate_f output, void *data,
  6824. struct perf_event_context *task_ctx)
  6825. {
  6826. struct perf_event_context *ctx;
  6827. rcu_read_lock();
  6828. preempt_disable();
  6829. /*
  6830. * If we have task_ctx != NULL we only notify the task context itself.
  6831. * The task_ctx is set only for EXIT events before releasing task
  6832. * context.
  6833. */
  6834. if (task_ctx) {
  6835. perf_iterate_ctx(task_ctx, output, data, false);
  6836. goto done;
  6837. }
  6838. perf_iterate_sb_cpu(output, data);
  6839. ctx = rcu_dereference(current->perf_event_ctxp);
  6840. if (ctx)
  6841. perf_iterate_ctx(ctx, output, data, false);
  6842. done:
  6843. preempt_enable();
  6844. rcu_read_unlock();
  6845. }
  6846. /*
  6847. * Clear all file-based filters at exec, they'll have to be
  6848. * re-instated when/if these objects are mmapped again.
  6849. */
  6850. static void perf_event_addr_filters_exec(struct perf_event *event, void *data)
  6851. {
  6852. struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
  6853. struct perf_addr_filter *filter;
  6854. unsigned int restart = 0, count = 0;
  6855. unsigned long flags;
  6856. if (!has_addr_filter(event))
  6857. return;
  6858. raw_spin_lock_irqsave(&ifh->lock, flags);
  6859. list_for_each_entry(filter, &ifh->list, entry) {
  6860. if (filter->path.dentry) {
  6861. event->addr_filter_ranges[count].start = 0;
  6862. event->addr_filter_ranges[count].size = 0;
  6863. restart++;
  6864. }
  6865. count++;
  6866. }
  6867. if (restart)
  6868. event->addr_filters_gen++;
  6869. raw_spin_unlock_irqrestore(&ifh->lock, flags);
  6870. if (restart)
  6871. perf_event_stop(event, 1);
  6872. }
  6873. void perf_event_exec(void)
  6874. {
  6875. struct perf_event_context *ctx;
  6876. ctx = perf_pin_task_context(current);
  6877. if (!ctx)
  6878. return;
  6879. perf_event_enable_on_exec(ctx);
  6880. perf_event_remove_on_exec(ctx);
  6881. scoped_guard(rcu)
  6882. perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL, true);
  6883. perf_unpin_context(ctx);
  6884. put_ctx(ctx);
  6885. }
  6886. struct remote_output {
  6887. struct perf_buffer *rb;
  6888. int err;
  6889. };
  6890. static void __perf_event_output_stop(struct perf_event *event, void *data)
  6891. {
  6892. struct perf_event *parent = event->parent;
  6893. struct remote_output *ro = data;
  6894. struct perf_buffer *rb = ro->rb;
  6895. struct stop_event_data sd = {
  6896. .event = event,
  6897. };
  6898. if (!has_aux(event))
  6899. return;
  6900. if (!parent)
  6901. parent = event;
  6902. /*
  6903. * In case of inheritance, it will be the parent that links to the
  6904. * ring-buffer, but it will be the child that's actually using it.
  6905. *
  6906. * We are using event::rb to determine if the event should be stopped,
  6907. * however this may race with ring_buffer_attach() (through set_output),
  6908. * which will make us skip the event that actually needs to be stopped.
  6909. * So ring_buffer_attach() has to stop an aux event before re-assigning
  6910. * its rb pointer.
  6911. */
  6912. if (rcu_dereference(parent->rb) == rb)
  6913. ro->err = __perf_event_stop(&sd);
  6914. }
  6915. static int __perf_pmu_output_stop(void *info)
  6916. {
  6917. struct perf_event *event = info;
  6918. struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
  6919. struct remote_output ro = {
  6920. .rb = event->rb,
  6921. };
  6922. rcu_read_lock();
  6923. perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false);
  6924. if (cpuctx->task_ctx)
  6925. perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop,
  6926. &ro, false);
  6927. rcu_read_unlock();
  6928. return ro.err;
  6929. }
  6930. static void perf_pmu_output_stop(struct perf_event *event)
  6931. {
  6932. struct perf_event *iter;
  6933. int err, cpu;
  6934. restart:
  6935. rcu_read_lock();
  6936. list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) {
  6937. /*
  6938. * For per-CPU events, we need to make sure that neither they
  6939. * nor their children are running; for cpu==-1 events it's
  6940. * sufficient to stop the event itself if it's active, since
  6941. * it can't have children.
  6942. */
  6943. cpu = iter->cpu;
  6944. if (cpu == -1)
  6945. cpu = READ_ONCE(iter->oncpu);
  6946. if (cpu == -1)
  6947. continue;
  6948. err = cpu_function_call(cpu, __perf_pmu_output_stop, event);
  6949. if (err == -EAGAIN) {
  6950. rcu_read_unlock();
  6951. goto restart;
  6952. }
  6953. }
  6954. rcu_read_unlock();
  6955. }
  6956. /*
  6957. * task tracking -- fork/exit
  6958. *
  6959. * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
  6960. */
  6961. struct perf_task_event {
  6962. struct task_struct *task;
  6963. struct perf_event_context *task_ctx;
  6964. struct {
  6965. struct perf_event_header header;
  6966. u32 pid;
  6967. u32 ppid;
  6968. u32 tid;
  6969. u32 ptid;
  6970. u64 time;
  6971. } event_id;
  6972. };
  6973. static int perf_event_task_match(struct perf_event *event)
  6974. {
  6975. return event->attr.comm || event->attr.mmap ||
  6976. event->attr.mmap2 || event->attr.mmap_data ||
  6977. event->attr.task;
  6978. }
  6979. static void perf_event_task_output(struct perf_event *event,
  6980. void *data)
  6981. {
  6982. struct perf_task_event *task_event = data;
  6983. struct perf_output_handle handle;
  6984. struct perf_sample_data sample;
  6985. struct task_struct *task = task_event->task;
  6986. int ret, size = task_event->event_id.header.size;
  6987. if (!perf_event_task_match(event))
  6988. return;
  6989. perf_event_header__init_id(&task_event->event_id.header, &sample, event);
  6990. ret = perf_output_begin(&handle, &sample, event,
  6991. task_event->event_id.header.size);
  6992. if (ret)
  6993. goto out;
  6994. task_event->event_id.pid = perf_event_pid(event, task);
  6995. task_event->event_id.tid = perf_event_tid(event, task);
  6996. if (task_event->event_id.header.type == PERF_RECORD_EXIT) {
  6997. task_event->event_id.ppid = perf_event_pid(event,
  6998. task->real_parent);
  6999. task_event->event_id.ptid = perf_event_pid(event,
  7000. task->real_parent);
  7001. } else { /* PERF_RECORD_FORK */
  7002. task_event->event_id.ppid = perf_event_pid(event, current);
  7003. task_event->event_id.ptid = perf_event_tid(event, current);
  7004. }
  7005. task_event->event_id.time = perf_event_clock(event);
  7006. perf_output_put(&handle, task_event->event_id);
  7007. perf_event__output_id_sample(event, &handle, &sample);
  7008. perf_output_end(&handle);
  7009. out:
  7010. task_event->event_id.header.size = size;
  7011. }
  7012. static void perf_event_task(struct task_struct *task,
  7013. struct perf_event_context *task_ctx,
  7014. int new)
  7015. {
  7016. struct perf_task_event task_event;
  7017. if (!atomic_read(&nr_comm_events) &&
  7018. !atomic_read(&nr_mmap_events) &&
  7019. !atomic_read(&nr_task_events))
  7020. return;
  7021. task_event = (struct perf_task_event){
  7022. .task = task,
  7023. .task_ctx = task_ctx,
  7024. .event_id = {
  7025. .header = {
  7026. .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
  7027. .misc = 0,
  7028. .size = sizeof(task_event.event_id),
  7029. },
  7030. /* .pid */
  7031. /* .ppid */
  7032. /* .tid */
  7033. /* .ptid */
  7034. /* .time */
  7035. },
  7036. };
  7037. perf_iterate_sb(perf_event_task_output,
  7038. &task_event,
  7039. task_ctx);
  7040. }
  7041. void perf_event_fork(struct task_struct *task)
  7042. {
  7043. perf_event_task(task, NULL, 1);
  7044. perf_event_namespaces(task);
  7045. }
  7046. /*
  7047. * comm tracking
  7048. */
  7049. struct perf_comm_event {
  7050. struct task_struct *task;
  7051. char *comm;
  7052. int comm_size;
  7053. struct {
  7054. struct perf_event_header header;
  7055. u32 pid;
  7056. u32 tid;
  7057. } event_id;
  7058. };
  7059. static int perf_event_comm_match(struct perf_event *event)
  7060. {
  7061. return event->attr.comm;
  7062. }
  7063. static void perf_event_comm_output(struct perf_event *event,
  7064. void *data)
  7065. {
  7066. struct perf_comm_event *comm_event = data;
  7067. struct perf_output_handle handle;
  7068. struct perf_sample_data sample;
  7069. int size = comm_event->event_id.header.size;
  7070. int ret;
  7071. if (!perf_event_comm_match(event))
  7072. return;
  7073. perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
  7074. ret = perf_output_begin(&handle, &sample, event,
  7075. comm_event->event_id.header.size);
  7076. if (ret)
  7077. goto out;
  7078. comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
  7079. comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
  7080. perf_output_put(&handle, comm_event->event_id);
  7081. __output_copy(&handle, comm_event->comm,
  7082. comm_event->comm_size);
  7083. perf_event__output_id_sample(event, &handle, &sample);
  7084. perf_output_end(&handle);
  7085. out:
  7086. comm_event->event_id.header.size = size;
  7087. }
  7088. static void perf_event_comm_event(struct perf_comm_event *comm_event)
  7089. {
  7090. char comm[TASK_COMM_LEN];
  7091. unsigned int size;
  7092. memset(comm, 0, sizeof(comm));
  7093. strscpy(comm, comm_event->task->comm, sizeof(comm));
  7094. size = ALIGN(strlen(comm)+1, sizeof(u64));
  7095. comm_event->comm = comm;
  7096. comm_event->comm_size = size;
  7097. comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
  7098. perf_iterate_sb(perf_event_comm_output,
  7099. comm_event,
  7100. NULL);
  7101. }
  7102. void perf_event_comm(struct task_struct *task, bool exec)
  7103. {
  7104. struct perf_comm_event comm_event;
  7105. if (!atomic_read(&nr_comm_events))
  7106. return;
  7107. comm_event = (struct perf_comm_event){
  7108. .task = task,
  7109. /* .comm */
  7110. /* .comm_size */
  7111. .event_id = {
  7112. .header = {
  7113. .type = PERF_RECORD_COMM,
  7114. .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
  7115. /* .size */
  7116. },
  7117. /* .pid */
  7118. /* .tid */
  7119. },
  7120. };
  7121. perf_event_comm_event(&comm_event);
  7122. }
  7123. /*
  7124. * namespaces tracking
  7125. */
  7126. struct perf_namespaces_event {
  7127. struct task_struct *task;
  7128. struct {
  7129. struct perf_event_header header;
  7130. u32 pid;
  7131. u32 tid;
  7132. u64 nr_namespaces;
  7133. struct perf_ns_link_info link_info[NR_NAMESPACES];
  7134. } event_id;
  7135. };
  7136. static int perf_event_namespaces_match(struct perf_event *event)
  7137. {
  7138. return event->attr.namespaces;
  7139. }
  7140. static void perf_event_namespaces_output(struct perf_event *event,
  7141. void *data)
  7142. {
  7143. struct perf_namespaces_event *namespaces_event = data;
  7144. struct perf_output_handle handle;
  7145. struct perf_sample_data sample;
  7146. u16 header_size = namespaces_event->event_id.header.size;
  7147. int ret;
  7148. if (!perf_event_namespaces_match(event))
  7149. return;
  7150. perf_event_header__init_id(&namespaces_event->event_id.header,
  7151. &sample, event);
  7152. ret = perf_output_begin(&handle, &sample, event,
  7153. namespaces_event->event_id.header.size);
  7154. if (ret)
  7155. goto out;
  7156. namespaces_event->event_id.pid = perf_event_pid(event,
  7157. namespaces_event->task);
  7158. namespaces_event->event_id.tid = perf_event_tid(event,
  7159. namespaces_event->task);
  7160. perf_output_put(&handle, namespaces_event->event_id);
  7161. perf_event__output_id_sample(event, &handle, &sample);
  7162. perf_output_end(&handle);
  7163. out:
  7164. namespaces_event->event_id.header.size = header_size;
  7165. }
  7166. static void perf_fill_ns_link_info(struct perf_ns_link_info *ns_link_info,
  7167. struct task_struct *task,
  7168. const struct proc_ns_operations *ns_ops)
  7169. {
  7170. struct path ns_path;
  7171. struct inode *ns_inode;
  7172. int error;
  7173. error = ns_get_path(&ns_path, task, ns_ops);
  7174. if (!error) {
  7175. ns_inode = ns_path.dentry->d_inode;
  7176. ns_link_info->dev = new_encode_dev(ns_inode->i_sb->s_dev);
  7177. ns_link_info->ino = ns_inode->i_ino;
  7178. path_put(&ns_path);
  7179. }
  7180. }
  7181. void perf_event_namespaces(struct task_struct *task)
  7182. {
  7183. struct perf_namespaces_event namespaces_event;
  7184. struct perf_ns_link_info *ns_link_info;
  7185. if (!atomic_read(&nr_namespaces_events))
  7186. return;
  7187. namespaces_event = (struct perf_namespaces_event){
  7188. .task = task,
  7189. .event_id = {
  7190. .header = {
  7191. .type = PERF_RECORD_NAMESPACES,
  7192. .misc = 0,
  7193. .size = sizeof(namespaces_event.event_id),
  7194. },
  7195. /* .pid */
  7196. /* .tid */
  7197. .nr_namespaces = NR_NAMESPACES,
  7198. /* .link_info[NR_NAMESPACES] */
  7199. },
  7200. };
  7201. ns_link_info = namespaces_event.event_id.link_info;
  7202. perf_fill_ns_link_info(&ns_link_info[MNT_NS_INDEX],
  7203. task, &mntns_operations);
  7204. #ifdef CONFIG_USER_NS
  7205. perf_fill_ns_link_info(&ns_link_info[USER_NS_INDEX],
  7206. task, &userns_operations);
  7207. #endif
  7208. #ifdef CONFIG_NET_NS
  7209. perf_fill_ns_link_info(&ns_link_info[NET_NS_INDEX],
  7210. task, &netns_operations);
  7211. #endif
  7212. #ifdef CONFIG_UTS_NS
  7213. perf_fill_ns_link_info(&ns_link_info[UTS_NS_INDEX],
  7214. task, &utsns_operations);
  7215. #endif
  7216. #ifdef CONFIG_IPC_NS
  7217. perf_fill_ns_link_info(&ns_link_info[IPC_NS_INDEX],
  7218. task, &ipcns_operations);
  7219. #endif
  7220. #ifdef CONFIG_PID_NS
  7221. perf_fill_ns_link_info(&ns_link_info[PID_NS_INDEX],
  7222. task, &pidns_operations);
  7223. #endif
  7224. #ifdef CONFIG_CGROUPS
  7225. perf_fill_ns_link_info(&ns_link_info[CGROUP_NS_INDEX],
  7226. task, &cgroupns_operations);
  7227. #endif
  7228. perf_iterate_sb(perf_event_namespaces_output,
  7229. &namespaces_event,
  7230. NULL);
  7231. }
  7232. /*
  7233. * cgroup tracking
  7234. */
  7235. #ifdef CONFIG_CGROUP_PERF
  7236. struct perf_cgroup_event {
  7237. char *path;
  7238. int path_size;
  7239. struct {
  7240. struct perf_event_header header;
  7241. u64 id;
  7242. char path[];
  7243. } event_id;
  7244. };
  7245. static int perf_event_cgroup_match(struct perf_event *event)
  7246. {
  7247. return event->attr.cgroup;
  7248. }
  7249. static void perf_event_cgroup_output(struct perf_event *event, void *data)
  7250. {
  7251. struct perf_cgroup_event *cgroup_event = data;
  7252. struct perf_output_handle handle;
  7253. struct perf_sample_data sample;
  7254. u16 header_size = cgroup_event->event_id.header.size;
  7255. int ret;
  7256. if (!perf_event_cgroup_match(event))
  7257. return;
  7258. perf_event_header__init_id(&cgroup_event->event_id.header,
  7259. &sample, event);
  7260. ret = perf_output_begin(&handle, &sample, event,
  7261. cgroup_event->event_id.header.size);
  7262. if (ret)
  7263. goto out;
  7264. perf_output_put(&handle, cgroup_event->event_id);
  7265. __output_copy(&handle, cgroup_event->path, cgroup_event->path_size);
  7266. perf_event__output_id_sample(event, &handle, &sample);
  7267. perf_output_end(&handle);
  7268. out:
  7269. cgroup_event->event_id.header.size = header_size;
  7270. }
  7271. static void perf_event_cgroup(struct cgroup *cgrp)
  7272. {
  7273. struct perf_cgroup_event cgroup_event;
  7274. char path_enomem[16] = "//enomem";
  7275. char *pathname;
  7276. size_t size;
  7277. if (!atomic_read(&nr_cgroup_events))
  7278. return;
  7279. cgroup_event = (struct perf_cgroup_event){
  7280. .event_id = {
  7281. .header = {
  7282. .type = PERF_RECORD_CGROUP,
  7283. .misc = 0,
  7284. .size = sizeof(cgroup_event.event_id),
  7285. },
  7286. .id = cgroup_id(cgrp),
  7287. },
  7288. };
  7289. pathname = kmalloc(PATH_MAX, GFP_KERNEL);
  7290. if (pathname == NULL) {
  7291. cgroup_event.path = path_enomem;
  7292. } else {
  7293. /* just to be sure to have enough space for alignment */
  7294. cgroup_path(cgrp, pathname, PATH_MAX - sizeof(u64));
  7295. cgroup_event.path = pathname;
  7296. }
  7297. /*
  7298. * Since our buffer works in 8 byte units we need to align our string
  7299. * size to a multiple of 8. However, we must guarantee the tail end is
  7300. * zero'd out to avoid leaking random bits to userspace.
  7301. */
  7302. size = strlen(cgroup_event.path) + 1;
  7303. while (!IS_ALIGNED(size, sizeof(u64)))
  7304. cgroup_event.path[size++] = '\0';
  7305. cgroup_event.event_id.header.size += size;
  7306. cgroup_event.path_size = size;
  7307. perf_iterate_sb(perf_event_cgroup_output,
  7308. &cgroup_event,
  7309. NULL);
  7310. kfree(pathname);
  7311. }
  7312. #endif
  7313. /*
  7314. * mmap tracking
  7315. */
  7316. struct perf_mmap_event {
  7317. struct vm_area_struct *vma;
  7318. const char *file_name;
  7319. int file_size;
  7320. int maj, min;
  7321. u64 ino;
  7322. u64 ino_generation;
  7323. u32 prot, flags;
  7324. u8 build_id[BUILD_ID_SIZE_MAX];
  7325. u32 build_id_size;
  7326. struct {
  7327. struct perf_event_header header;
  7328. u32 pid;
  7329. u32 tid;
  7330. u64 start;
  7331. u64 len;
  7332. u64 pgoff;
  7333. } event_id;
  7334. };
  7335. static int perf_event_mmap_match(struct perf_event *event,
  7336. void *data)
  7337. {
  7338. struct perf_mmap_event *mmap_event = data;
  7339. struct vm_area_struct *vma = mmap_event->vma;
  7340. int executable = vma->vm_flags & VM_EXEC;
  7341. return (!executable && event->attr.mmap_data) ||
  7342. (executable && (event->attr.mmap || event->attr.mmap2));
  7343. }
  7344. static void perf_event_mmap_output(struct perf_event *event,
  7345. void *data)
  7346. {
  7347. struct perf_mmap_event *mmap_event = data;
  7348. struct perf_output_handle handle;
  7349. struct perf_sample_data sample;
  7350. int size = mmap_event->event_id.header.size;
  7351. u32 type = mmap_event->event_id.header.type;
  7352. bool use_build_id;
  7353. int ret;
  7354. if (!perf_event_mmap_match(event, data))
  7355. return;
  7356. if (event->attr.mmap2) {
  7357. mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
  7358. mmap_event->event_id.header.size += sizeof(mmap_event->maj);
  7359. mmap_event->event_id.header.size += sizeof(mmap_event->min);
  7360. mmap_event->event_id.header.size += sizeof(mmap_event->ino);
  7361. mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
  7362. mmap_event->event_id.header.size += sizeof(mmap_event->prot);
  7363. mmap_event->event_id.header.size += sizeof(mmap_event->flags);
  7364. }
  7365. perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
  7366. ret = perf_output_begin(&handle, &sample, event,
  7367. mmap_event->event_id.header.size);
  7368. if (ret)
  7369. goto out;
  7370. mmap_event->event_id.pid = perf_event_pid(event, current);
  7371. mmap_event->event_id.tid = perf_event_tid(event, current);
  7372. use_build_id = event->attr.build_id && mmap_event->build_id_size;
  7373. if (event->attr.mmap2 && use_build_id)
  7374. mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_BUILD_ID;
  7375. perf_output_put(&handle, mmap_event->event_id);
  7376. if (event->attr.mmap2) {
  7377. if (use_build_id) {
  7378. u8 size[4] = { (u8) mmap_event->build_id_size, 0, 0, 0 };
  7379. __output_copy(&handle, size, 4);
  7380. __output_copy(&handle, mmap_event->build_id, BUILD_ID_SIZE_MAX);
  7381. } else {
  7382. perf_output_put(&handle, mmap_event->maj);
  7383. perf_output_put(&handle, mmap_event->min);
  7384. perf_output_put(&handle, mmap_event->ino);
  7385. perf_output_put(&handle, mmap_event->ino_generation);
  7386. }
  7387. perf_output_put(&handle, mmap_event->prot);
  7388. perf_output_put(&handle, mmap_event->flags);
  7389. }
  7390. __output_copy(&handle, mmap_event->file_name,
  7391. mmap_event->file_size);
  7392. perf_event__output_id_sample(event, &handle, &sample);
  7393. perf_output_end(&handle);
  7394. out:
  7395. mmap_event->event_id.header.size = size;
  7396. mmap_event->event_id.header.type = type;
  7397. }
  7398. static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
  7399. {
  7400. struct vm_area_struct *vma = mmap_event->vma;
  7401. struct file *file = vma->vm_file;
  7402. int maj = 0, min = 0;
  7403. u64 ino = 0, gen = 0;
  7404. u32 prot = 0, flags = 0;
  7405. unsigned int size;
  7406. char tmp[16];
  7407. char *buf = NULL;
  7408. char *name = NULL;
  7409. if (vma->vm_flags & VM_READ)
  7410. prot |= PROT_READ;
  7411. if (vma->vm_flags & VM_WRITE)
  7412. prot |= PROT_WRITE;
  7413. if (vma->vm_flags & VM_EXEC)
  7414. prot |= PROT_EXEC;
  7415. if (vma->vm_flags & VM_MAYSHARE)
  7416. flags = MAP_SHARED;
  7417. else
  7418. flags = MAP_PRIVATE;
  7419. if (vma->vm_flags & VM_LOCKED)
  7420. flags |= MAP_LOCKED;
  7421. if (is_vm_hugetlb_page(vma))
  7422. flags |= MAP_HUGETLB;
  7423. if (file) {
  7424. const struct inode *inode;
  7425. dev_t dev;
  7426. buf = kmalloc(PATH_MAX, GFP_KERNEL);
  7427. if (!buf) {
  7428. name = "//enomem";
  7429. goto cpy_name;
  7430. }
  7431. /*
  7432. * d_path() works from the end of the rb backwards, so we
  7433. * need to add enough zero bytes after the string to handle
  7434. * the 64bit alignment we do later.
  7435. */
  7436. name = d_path(file_user_path(file), buf, PATH_MAX - sizeof(u64));
  7437. if (IS_ERR(name)) {
  7438. name = "//toolong";
  7439. goto cpy_name;
  7440. }
  7441. inode = file_user_inode(vma->vm_file);
  7442. dev = inode->i_sb->s_dev;
  7443. ino = inode->i_ino;
  7444. gen = inode->i_generation;
  7445. maj = MAJOR(dev);
  7446. min = MINOR(dev);
  7447. goto got_name;
  7448. } else {
  7449. if (vma->vm_ops && vma->vm_ops->name)
  7450. name = (char *) vma->vm_ops->name(vma);
  7451. if (!name)
  7452. name = (char *)arch_vma_name(vma);
  7453. if (!name) {
  7454. if (vma_is_initial_heap(vma))
  7455. name = "[heap]";
  7456. else if (vma_is_initial_stack(vma))
  7457. name = "[stack]";
  7458. else
  7459. name = "//anon";
  7460. }
  7461. }
  7462. cpy_name:
  7463. strscpy(tmp, name, sizeof(tmp));
  7464. name = tmp;
  7465. got_name:
  7466. /*
  7467. * Since our buffer works in 8 byte units we need to align our string
  7468. * size to a multiple of 8. However, we must guarantee the tail end is
  7469. * zero'd out to avoid leaking random bits to userspace.
  7470. */
  7471. size = strlen(name)+1;
  7472. while (!IS_ALIGNED(size, sizeof(u64)))
  7473. name[size++] = '\0';
  7474. mmap_event->file_name = name;
  7475. mmap_event->file_size = size;
  7476. mmap_event->maj = maj;
  7477. mmap_event->min = min;
  7478. mmap_event->ino = ino;
  7479. mmap_event->ino_generation = gen;
  7480. mmap_event->prot = prot;
  7481. mmap_event->flags = flags;
  7482. if (!(vma->vm_flags & VM_EXEC))
  7483. mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
  7484. mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
  7485. if (atomic_read(&nr_build_id_events))
  7486. build_id_parse_nofault(vma, mmap_event->build_id, &mmap_event->build_id_size);
  7487. perf_iterate_sb(perf_event_mmap_output,
  7488. mmap_event,
  7489. NULL);
  7490. kfree(buf);
  7491. }
  7492. /*
  7493. * Check whether inode and address range match filter criteria.
  7494. */
  7495. static bool perf_addr_filter_match(struct perf_addr_filter *filter,
  7496. struct file *file, unsigned long offset,
  7497. unsigned long size)
  7498. {
  7499. /* d_inode(NULL) won't be equal to any mapped user-space file */
  7500. if (!filter->path.dentry)
  7501. return false;
  7502. if (d_inode(filter->path.dentry) != file_user_inode(file))
  7503. return false;
  7504. if (filter->offset > offset + size)
  7505. return false;
  7506. if (filter->offset + filter->size < offset)
  7507. return false;
  7508. return true;
  7509. }
  7510. static bool perf_addr_filter_vma_adjust(struct perf_addr_filter *filter,
  7511. struct vm_area_struct *vma,
  7512. struct perf_addr_filter_range *fr)
  7513. {
  7514. unsigned long vma_size = vma->vm_end - vma->vm_start;
  7515. unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
  7516. struct file *file = vma->vm_file;
  7517. if (!perf_addr_filter_match(filter, file, off, vma_size))
  7518. return false;
  7519. if (filter->offset < off) {
  7520. fr->start = vma->vm_start;
  7521. fr->size = min(vma_size, filter->size - (off - filter->offset));
  7522. } else {
  7523. fr->start = vma->vm_start + filter->offset - off;
  7524. fr->size = min(vma->vm_end - fr->start, filter->size);
  7525. }
  7526. return true;
  7527. }
  7528. static void __perf_addr_filters_adjust(struct perf_event *event, void *data)
  7529. {
  7530. struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
  7531. struct vm_area_struct *vma = data;
  7532. struct perf_addr_filter *filter;
  7533. unsigned int restart = 0, count = 0;
  7534. unsigned long flags;
  7535. if (!has_addr_filter(event))
  7536. return;
  7537. if (!vma->vm_file)
  7538. return;
  7539. raw_spin_lock_irqsave(&ifh->lock, flags);
  7540. list_for_each_entry(filter, &ifh->list, entry) {
  7541. if (perf_addr_filter_vma_adjust(filter, vma,
  7542. &event->addr_filter_ranges[count]))
  7543. restart++;
  7544. count++;
  7545. }
  7546. if (restart)
  7547. event->addr_filters_gen++;
  7548. raw_spin_unlock_irqrestore(&ifh->lock, flags);
  7549. if (restart)
  7550. perf_event_stop(event, 1);
  7551. }
  7552. /*
  7553. * Adjust all task's events' filters to the new vma
  7554. */
  7555. static void perf_addr_filters_adjust(struct vm_area_struct *vma)
  7556. {
  7557. struct perf_event_context *ctx;
  7558. /*
  7559. * Data tracing isn't supported yet and as such there is no need
  7560. * to keep track of anything that isn't related to executable code:
  7561. */
  7562. if (!(vma->vm_flags & VM_EXEC))
  7563. return;
  7564. rcu_read_lock();
  7565. ctx = rcu_dereference(current->perf_event_ctxp);
  7566. if (ctx)
  7567. perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true);
  7568. rcu_read_unlock();
  7569. }
  7570. void perf_event_mmap(struct vm_area_struct *vma)
  7571. {
  7572. struct perf_mmap_event mmap_event;
  7573. if (!atomic_read(&nr_mmap_events))
  7574. return;
  7575. mmap_event = (struct perf_mmap_event){
  7576. .vma = vma,
  7577. /* .file_name */
  7578. /* .file_size */
  7579. .event_id = {
  7580. .header = {
  7581. .type = PERF_RECORD_MMAP,
  7582. .misc = PERF_RECORD_MISC_USER,
  7583. /* .size */
  7584. },
  7585. /* .pid */
  7586. /* .tid */
  7587. .start = vma->vm_start,
  7588. .len = vma->vm_end - vma->vm_start,
  7589. .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
  7590. },
  7591. /* .maj (attr_mmap2 only) */
  7592. /* .min (attr_mmap2 only) */
  7593. /* .ino (attr_mmap2 only) */
  7594. /* .ino_generation (attr_mmap2 only) */
  7595. /* .prot (attr_mmap2 only) */
  7596. /* .flags (attr_mmap2 only) */
  7597. };
  7598. perf_addr_filters_adjust(vma);
  7599. perf_event_mmap_event(&mmap_event);
  7600. }
  7601. void perf_event_aux_event(struct perf_event *event, unsigned long head,
  7602. unsigned long size, u64 flags)
  7603. {
  7604. struct perf_output_handle handle;
  7605. struct perf_sample_data sample;
  7606. struct perf_aux_event {
  7607. struct perf_event_header header;
  7608. u64 offset;
  7609. u64 size;
  7610. u64 flags;
  7611. } rec = {
  7612. .header = {
  7613. .type = PERF_RECORD_AUX,
  7614. .misc = 0,
  7615. .size = sizeof(rec),
  7616. },
  7617. .offset = head,
  7618. .size = size,
  7619. .flags = flags,
  7620. };
  7621. int ret;
  7622. perf_event_header__init_id(&rec.header, &sample, event);
  7623. ret = perf_output_begin(&handle, &sample, event, rec.header.size);
  7624. if (ret)
  7625. return;
  7626. perf_output_put(&handle, rec);
  7627. perf_event__output_id_sample(event, &handle, &sample);
  7628. perf_output_end(&handle);
  7629. }
  7630. /*
  7631. * Lost/dropped samples logging
  7632. */
  7633. void perf_log_lost_samples(struct perf_event *event, u64 lost)
  7634. {
  7635. struct perf_output_handle handle;
  7636. struct perf_sample_data sample;
  7637. int ret;
  7638. struct {
  7639. struct perf_event_header header;
  7640. u64 lost;
  7641. } lost_samples_event = {
  7642. .header = {
  7643. .type = PERF_RECORD_LOST_SAMPLES,
  7644. .misc = 0,
  7645. .size = sizeof(lost_samples_event),
  7646. },
  7647. .lost = lost,
  7648. };
  7649. perf_event_header__init_id(&lost_samples_event.header, &sample, event);
  7650. ret = perf_output_begin(&handle, &sample, event,
  7651. lost_samples_event.header.size);
  7652. if (ret)
  7653. return;
  7654. perf_output_put(&handle, lost_samples_event);
  7655. perf_event__output_id_sample(event, &handle, &sample);
  7656. perf_output_end(&handle);
  7657. }
  7658. /*
  7659. * context_switch tracking
  7660. */
  7661. struct perf_switch_event {
  7662. struct task_struct *task;
  7663. struct task_struct *next_prev;
  7664. struct {
  7665. struct perf_event_header header;
  7666. u32 next_prev_pid;
  7667. u32 next_prev_tid;
  7668. } event_id;
  7669. };
  7670. static int perf_event_switch_match(struct perf_event *event)
  7671. {
  7672. return event->attr.context_switch;
  7673. }
  7674. static void perf_event_switch_output(struct perf_event *event, void *data)
  7675. {
  7676. struct perf_switch_event *se = data;
  7677. struct perf_output_handle handle;
  7678. struct perf_sample_data sample;
  7679. int ret;
  7680. if (!perf_event_switch_match(event))
  7681. return;
  7682. /* Only CPU-wide events are allowed to see next/prev pid/tid */
  7683. if (event->ctx->task) {
  7684. se->event_id.header.type = PERF_RECORD_SWITCH;
  7685. se->event_id.header.size = sizeof(se->event_id.header);
  7686. } else {
  7687. se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
  7688. se->event_id.header.size = sizeof(se->event_id);
  7689. se->event_id.next_prev_pid =
  7690. perf_event_pid(event, se->next_prev);
  7691. se->event_id.next_prev_tid =
  7692. perf_event_tid(event, se->next_prev);
  7693. }
  7694. perf_event_header__init_id(&se->event_id.header, &sample, event);
  7695. ret = perf_output_begin(&handle, &sample, event, se->event_id.header.size);
  7696. if (ret)
  7697. return;
  7698. if (event->ctx->task)
  7699. perf_output_put(&handle, se->event_id.header);
  7700. else
  7701. perf_output_put(&handle, se->event_id);
  7702. perf_event__output_id_sample(event, &handle, &sample);
  7703. perf_output_end(&handle);
  7704. }
  7705. static void perf_event_switch(struct task_struct *task,
  7706. struct task_struct *next_prev, bool sched_in)
  7707. {
  7708. struct perf_switch_event switch_event;
  7709. /* N.B. caller checks nr_switch_events != 0 */
  7710. switch_event = (struct perf_switch_event){
  7711. .task = task,
  7712. .next_prev = next_prev,
  7713. .event_id = {
  7714. .header = {
  7715. /* .type */
  7716. .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
  7717. /* .size */
  7718. },
  7719. /* .next_prev_pid */
  7720. /* .next_prev_tid */
  7721. },
  7722. };
  7723. if (!sched_in && task_is_runnable(task)) {
  7724. switch_event.event_id.header.misc |=
  7725. PERF_RECORD_MISC_SWITCH_OUT_PREEMPT;
  7726. }
  7727. perf_iterate_sb(perf_event_switch_output, &switch_event, NULL);
  7728. }
  7729. /*
  7730. * IRQ throttle logging
  7731. */
  7732. static void perf_log_throttle(struct perf_event *event, int enable)
  7733. {
  7734. struct perf_output_handle handle;
  7735. struct perf_sample_data sample;
  7736. int ret;
  7737. struct {
  7738. struct perf_event_header header;
  7739. u64 time;
  7740. u64 id;
  7741. u64 stream_id;
  7742. } throttle_event = {
  7743. .header = {
  7744. .type = PERF_RECORD_THROTTLE,
  7745. .misc = 0,
  7746. .size = sizeof(throttle_event),
  7747. },
  7748. .time = perf_event_clock(event),
  7749. .id = primary_event_id(event),
  7750. .stream_id = event->id,
  7751. };
  7752. if (enable)
  7753. throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
  7754. perf_event_header__init_id(&throttle_event.header, &sample, event);
  7755. ret = perf_output_begin(&handle, &sample, event,
  7756. throttle_event.header.size);
  7757. if (ret)
  7758. return;
  7759. perf_output_put(&handle, throttle_event);
  7760. perf_event__output_id_sample(event, &handle, &sample);
  7761. perf_output_end(&handle);
  7762. }
  7763. /*
  7764. * ksymbol register/unregister tracking
  7765. */
  7766. struct perf_ksymbol_event {
  7767. const char *name;
  7768. int name_len;
  7769. struct {
  7770. struct perf_event_header header;
  7771. u64 addr;
  7772. u32 len;
  7773. u16 ksym_type;
  7774. u16 flags;
  7775. } event_id;
  7776. };
  7777. static int perf_event_ksymbol_match(struct perf_event *event)
  7778. {
  7779. return event->attr.ksymbol;
  7780. }
  7781. static void perf_event_ksymbol_output(struct perf_event *event, void *data)
  7782. {
  7783. struct perf_ksymbol_event *ksymbol_event = data;
  7784. struct perf_output_handle handle;
  7785. struct perf_sample_data sample;
  7786. int ret;
  7787. if (!perf_event_ksymbol_match(event))
  7788. return;
  7789. perf_event_header__init_id(&ksymbol_event->event_id.header,
  7790. &sample, event);
  7791. ret = perf_output_begin(&handle, &sample, event,
  7792. ksymbol_event->event_id.header.size);
  7793. if (ret)
  7794. return;
  7795. perf_output_put(&handle, ksymbol_event->event_id);
  7796. __output_copy(&handle, ksymbol_event->name, ksymbol_event->name_len);
  7797. perf_event__output_id_sample(event, &handle, &sample);
  7798. perf_output_end(&handle);
  7799. }
  7800. void perf_event_ksymbol(u16 ksym_type, u64 addr, u32 len, bool unregister,
  7801. const char *sym)
  7802. {
  7803. struct perf_ksymbol_event ksymbol_event;
  7804. char name[KSYM_NAME_LEN];
  7805. u16 flags = 0;
  7806. int name_len;
  7807. if (!atomic_read(&nr_ksymbol_events))
  7808. return;
  7809. if (ksym_type >= PERF_RECORD_KSYMBOL_TYPE_MAX ||
  7810. ksym_type == PERF_RECORD_KSYMBOL_TYPE_UNKNOWN)
  7811. goto err;
  7812. strscpy(name, sym, KSYM_NAME_LEN);
  7813. name_len = strlen(name) + 1;
  7814. while (!IS_ALIGNED(name_len, sizeof(u64)))
  7815. name[name_len++] = '\0';
  7816. BUILD_BUG_ON(KSYM_NAME_LEN % sizeof(u64));
  7817. if (unregister)
  7818. flags |= PERF_RECORD_KSYMBOL_FLAGS_UNREGISTER;
  7819. ksymbol_event = (struct perf_ksymbol_event){
  7820. .name = name,
  7821. .name_len = name_len,
  7822. .event_id = {
  7823. .header = {
  7824. .type = PERF_RECORD_KSYMBOL,
  7825. .size = sizeof(ksymbol_event.event_id) +
  7826. name_len,
  7827. },
  7828. .addr = addr,
  7829. .len = len,
  7830. .ksym_type = ksym_type,
  7831. .flags = flags,
  7832. },
  7833. };
  7834. perf_iterate_sb(perf_event_ksymbol_output, &ksymbol_event, NULL);
  7835. return;
  7836. err:
  7837. WARN_ONCE(1, "%s: Invalid KSYMBOL type 0x%x\n", __func__, ksym_type);
  7838. }
  7839. /*
  7840. * bpf program load/unload tracking
  7841. */
  7842. struct perf_bpf_event {
  7843. struct bpf_prog *prog;
  7844. struct {
  7845. struct perf_event_header header;
  7846. u16 type;
  7847. u16 flags;
  7848. u32 id;
  7849. u8 tag[BPF_TAG_SIZE];
  7850. } event_id;
  7851. };
  7852. static int perf_event_bpf_match(struct perf_event *event)
  7853. {
  7854. return event->attr.bpf_event;
  7855. }
  7856. static void perf_event_bpf_output(struct perf_event *event, void *data)
  7857. {
  7858. struct perf_bpf_event *bpf_event = data;
  7859. struct perf_output_handle handle;
  7860. struct perf_sample_data sample;
  7861. int ret;
  7862. if (!perf_event_bpf_match(event))
  7863. return;
  7864. perf_event_header__init_id(&bpf_event->event_id.header,
  7865. &sample, event);
  7866. ret = perf_output_begin(&handle, &sample, event,
  7867. bpf_event->event_id.header.size);
  7868. if (ret)
  7869. return;
  7870. perf_output_put(&handle, bpf_event->event_id);
  7871. perf_event__output_id_sample(event, &handle, &sample);
  7872. perf_output_end(&handle);
  7873. }
  7874. static void perf_event_bpf_emit_ksymbols(struct bpf_prog *prog,
  7875. enum perf_bpf_event_type type)
  7876. {
  7877. bool unregister = type == PERF_BPF_EVENT_PROG_UNLOAD;
  7878. int i;
  7879. perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF,
  7880. (u64)(unsigned long)prog->bpf_func,
  7881. prog->jited_len, unregister,
  7882. prog->aux->ksym.name);
  7883. for (i = 1; i < prog->aux->func_cnt; i++) {
  7884. struct bpf_prog *subprog = prog->aux->func[i];
  7885. perf_event_ksymbol(
  7886. PERF_RECORD_KSYMBOL_TYPE_BPF,
  7887. (u64)(unsigned long)subprog->bpf_func,
  7888. subprog->jited_len, unregister,
  7889. subprog->aux->ksym.name);
  7890. }
  7891. }
  7892. void perf_event_bpf_event(struct bpf_prog *prog,
  7893. enum perf_bpf_event_type type,
  7894. u16 flags)
  7895. {
  7896. struct perf_bpf_event bpf_event;
  7897. switch (type) {
  7898. case PERF_BPF_EVENT_PROG_LOAD:
  7899. case PERF_BPF_EVENT_PROG_UNLOAD:
  7900. if (atomic_read(&nr_ksymbol_events))
  7901. perf_event_bpf_emit_ksymbols(prog, type);
  7902. break;
  7903. default:
  7904. return;
  7905. }
  7906. if (!atomic_read(&nr_bpf_events))
  7907. return;
  7908. bpf_event = (struct perf_bpf_event){
  7909. .prog = prog,
  7910. .event_id = {
  7911. .header = {
  7912. .type = PERF_RECORD_BPF_EVENT,
  7913. .size = sizeof(bpf_event.event_id),
  7914. },
  7915. .type = type,
  7916. .flags = flags,
  7917. .id = prog->aux->id,
  7918. },
  7919. };
  7920. BUILD_BUG_ON(BPF_TAG_SIZE % sizeof(u64));
  7921. memcpy(bpf_event.event_id.tag, prog->tag, BPF_TAG_SIZE);
  7922. perf_iterate_sb(perf_event_bpf_output, &bpf_event, NULL);
  7923. }
  7924. struct perf_text_poke_event {
  7925. const void *old_bytes;
  7926. const void *new_bytes;
  7927. size_t pad;
  7928. u16 old_len;
  7929. u16 new_len;
  7930. struct {
  7931. struct perf_event_header header;
  7932. u64 addr;
  7933. } event_id;
  7934. };
  7935. static int perf_event_text_poke_match(struct perf_event *event)
  7936. {
  7937. return event->attr.text_poke;
  7938. }
  7939. static void perf_event_text_poke_output(struct perf_event *event, void *data)
  7940. {
  7941. struct perf_text_poke_event *text_poke_event = data;
  7942. struct perf_output_handle handle;
  7943. struct perf_sample_data sample;
  7944. u64 padding = 0;
  7945. int ret;
  7946. if (!perf_event_text_poke_match(event))
  7947. return;
  7948. perf_event_header__init_id(&text_poke_event->event_id.header, &sample, event);
  7949. ret = perf_output_begin(&handle, &sample, event,
  7950. text_poke_event->event_id.header.size);
  7951. if (ret)
  7952. return;
  7953. perf_output_put(&handle, text_poke_event->event_id);
  7954. perf_output_put(&handle, text_poke_event->old_len);
  7955. perf_output_put(&handle, text_poke_event->new_len);
  7956. __output_copy(&handle, text_poke_event->old_bytes, text_poke_event->old_len);
  7957. __output_copy(&handle, text_poke_event->new_bytes, text_poke_event->new_len);
  7958. if (text_poke_event->pad)
  7959. __output_copy(&handle, &padding, text_poke_event->pad);
  7960. perf_event__output_id_sample(event, &handle, &sample);
  7961. perf_output_end(&handle);
  7962. }
  7963. void perf_event_text_poke(const void *addr, const void *old_bytes,
  7964. size_t old_len, const void *new_bytes, size_t new_len)
  7965. {
  7966. struct perf_text_poke_event text_poke_event;
  7967. size_t tot, pad;
  7968. if (!atomic_read(&nr_text_poke_events))
  7969. return;
  7970. tot = sizeof(text_poke_event.old_len) + old_len;
  7971. tot += sizeof(text_poke_event.new_len) + new_len;
  7972. pad = ALIGN(tot, sizeof(u64)) - tot;
  7973. text_poke_event = (struct perf_text_poke_event){
  7974. .old_bytes = old_bytes,
  7975. .new_bytes = new_bytes,
  7976. .pad = pad,
  7977. .old_len = old_len,
  7978. .new_len = new_len,
  7979. .event_id = {
  7980. .header = {
  7981. .type = PERF_RECORD_TEXT_POKE,
  7982. .misc = PERF_RECORD_MISC_KERNEL,
  7983. .size = sizeof(text_poke_event.event_id) + tot + pad,
  7984. },
  7985. .addr = (unsigned long)addr,
  7986. },
  7987. };
  7988. perf_iterate_sb(perf_event_text_poke_output, &text_poke_event, NULL);
  7989. }
  7990. void perf_event_itrace_started(struct perf_event *event)
  7991. {
  7992. event->attach_state |= PERF_ATTACH_ITRACE;
  7993. }
  7994. static void perf_log_itrace_start(struct perf_event *event)
  7995. {
  7996. struct perf_output_handle handle;
  7997. struct perf_sample_data sample;
  7998. struct perf_aux_event {
  7999. struct perf_event_header header;
  8000. u32 pid;
  8001. u32 tid;
  8002. } rec;
  8003. int ret;
  8004. if (event->parent)
  8005. event = event->parent;
  8006. if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
  8007. event->attach_state & PERF_ATTACH_ITRACE)
  8008. return;
  8009. rec.header.type = PERF_RECORD_ITRACE_START;
  8010. rec.header.misc = 0;
  8011. rec.header.size = sizeof(rec);
  8012. rec.pid = perf_event_pid(event, current);
  8013. rec.tid = perf_event_tid(event, current);
  8014. perf_event_header__init_id(&rec.header, &sample, event);
  8015. ret = perf_output_begin(&handle, &sample, event, rec.header.size);
  8016. if (ret)
  8017. return;
  8018. perf_output_put(&handle, rec);
  8019. perf_event__output_id_sample(event, &handle, &sample);
  8020. perf_output_end(&handle);
  8021. }
  8022. void perf_report_aux_output_id(struct perf_event *event, u64 hw_id)
  8023. {
  8024. struct perf_output_handle handle;
  8025. struct perf_sample_data sample;
  8026. struct perf_aux_event {
  8027. struct perf_event_header header;
  8028. u64 hw_id;
  8029. } rec;
  8030. int ret;
  8031. if (event->parent)
  8032. event = event->parent;
  8033. rec.header.type = PERF_RECORD_AUX_OUTPUT_HW_ID;
  8034. rec.header.misc = 0;
  8035. rec.header.size = sizeof(rec);
  8036. rec.hw_id = hw_id;
  8037. perf_event_header__init_id(&rec.header, &sample, event);
  8038. ret = perf_output_begin(&handle, &sample, event, rec.header.size);
  8039. if (ret)
  8040. return;
  8041. perf_output_put(&handle, rec);
  8042. perf_event__output_id_sample(event, &handle, &sample);
  8043. perf_output_end(&handle);
  8044. }
  8045. EXPORT_SYMBOL_GPL(perf_report_aux_output_id);
  8046. static int
  8047. __perf_event_account_interrupt(struct perf_event *event, int throttle)
  8048. {
  8049. struct hw_perf_event *hwc = &event->hw;
  8050. int ret = 0;
  8051. u64 seq;
  8052. seq = __this_cpu_read(perf_throttled_seq);
  8053. if (seq != hwc->interrupts_seq) {
  8054. hwc->interrupts_seq = seq;
  8055. hwc->interrupts = 1;
  8056. } else {
  8057. hwc->interrupts++;
  8058. }
  8059. if (unlikely(throttle && hwc->interrupts >= max_samples_per_tick)) {
  8060. __this_cpu_inc(perf_throttled_count);
  8061. tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
  8062. hwc->interrupts = MAX_INTERRUPTS;
  8063. perf_log_throttle(event, 0);
  8064. ret = 1;
  8065. }
  8066. if (event->attr.freq) {
  8067. u64 now = perf_clock();
  8068. s64 delta = now - hwc->freq_time_stamp;
  8069. hwc->freq_time_stamp = now;
  8070. if (delta > 0 && delta < 2*TICK_NSEC)
  8071. perf_adjust_period(event, delta, hwc->last_period, true);
  8072. }
  8073. return ret;
  8074. }
  8075. int perf_event_account_interrupt(struct perf_event *event)
  8076. {
  8077. return __perf_event_account_interrupt(event, 1);
  8078. }
  8079. static inline bool sample_is_allowed(struct perf_event *event, struct pt_regs *regs)
  8080. {
  8081. /*
  8082. * Due to interrupt latency (AKA "skid"), we may enter the
  8083. * kernel before taking an overflow, even if the PMU is only
  8084. * counting user events.
  8085. */
  8086. if (event->attr.exclude_kernel && !user_mode(regs))
  8087. return false;
  8088. return true;
  8089. }
  8090. #ifdef CONFIG_BPF_SYSCALL
  8091. static int bpf_overflow_handler(struct perf_event *event,
  8092. struct perf_sample_data *data,
  8093. struct pt_regs *regs)
  8094. {
  8095. struct bpf_perf_event_data_kern ctx = {
  8096. .data = data,
  8097. .event = event,
  8098. };
  8099. struct bpf_prog *prog;
  8100. int ret = 0;
  8101. ctx.regs = perf_arch_bpf_user_pt_regs(regs);
  8102. if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1))
  8103. goto out;
  8104. rcu_read_lock();
  8105. prog = READ_ONCE(event->prog);
  8106. if (prog) {
  8107. perf_prepare_sample(data, event, regs);
  8108. ret = bpf_prog_run(prog, &ctx);
  8109. }
  8110. rcu_read_unlock();
  8111. out:
  8112. __this_cpu_dec(bpf_prog_active);
  8113. return ret;
  8114. }
  8115. static inline int perf_event_set_bpf_handler(struct perf_event *event,
  8116. struct bpf_prog *prog,
  8117. u64 bpf_cookie)
  8118. {
  8119. if (event->overflow_handler_context)
  8120. /* hw breakpoint or kernel counter */
  8121. return -EINVAL;
  8122. if (event->prog)
  8123. return -EEXIST;
  8124. if (prog->type != BPF_PROG_TYPE_PERF_EVENT)
  8125. return -EINVAL;
  8126. if (event->attr.precise_ip &&
  8127. prog->call_get_stack &&
  8128. (!(event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) ||
  8129. event->attr.exclude_callchain_kernel ||
  8130. event->attr.exclude_callchain_user)) {
  8131. /*
  8132. * On perf_event with precise_ip, calling bpf_get_stack()
  8133. * may trigger unwinder warnings and occasional crashes.
  8134. * bpf_get_[stack|stackid] works around this issue by using
  8135. * callchain attached to perf_sample_data. If the
  8136. * perf_event does not full (kernel and user) callchain
  8137. * attached to perf_sample_data, do not allow attaching BPF
  8138. * program that calls bpf_get_[stack|stackid].
  8139. */
  8140. return -EPROTO;
  8141. }
  8142. event->prog = prog;
  8143. event->bpf_cookie = bpf_cookie;
  8144. return 0;
  8145. }
  8146. static inline void perf_event_free_bpf_handler(struct perf_event *event)
  8147. {
  8148. struct bpf_prog *prog = event->prog;
  8149. if (!prog)
  8150. return;
  8151. event->prog = NULL;
  8152. bpf_prog_put(prog);
  8153. }
  8154. #else
  8155. static inline int bpf_overflow_handler(struct perf_event *event,
  8156. struct perf_sample_data *data,
  8157. struct pt_regs *regs)
  8158. {
  8159. return 1;
  8160. }
  8161. static inline int perf_event_set_bpf_handler(struct perf_event *event,
  8162. struct bpf_prog *prog,
  8163. u64 bpf_cookie)
  8164. {
  8165. return -EOPNOTSUPP;
  8166. }
  8167. static inline void perf_event_free_bpf_handler(struct perf_event *event)
  8168. {
  8169. }
  8170. #endif
  8171. /*
  8172. * Generic event overflow handling, sampling.
  8173. */
  8174. static int __perf_event_overflow(struct perf_event *event,
  8175. int throttle, struct perf_sample_data *data,
  8176. struct pt_regs *regs)
  8177. {
  8178. int events = atomic_read(&event->event_limit);
  8179. int ret = 0;
  8180. /*
  8181. * Non-sampling counters might still use the PMI to fold short
  8182. * hardware counters, ignore those.
  8183. */
  8184. if (unlikely(!is_sampling_event(event)))
  8185. return 0;
  8186. ret = __perf_event_account_interrupt(event, throttle);
  8187. if (event->attr.aux_pause)
  8188. perf_event_aux_pause(event->aux_event, true);
  8189. if (event->prog && event->prog->type == BPF_PROG_TYPE_PERF_EVENT &&
  8190. !bpf_overflow_handler(event, data, regs))
  8191. goto out;
  8192. /*
  8193. * XXX event_limit might not quite work as expected on inherited
  8194. * events
  8195. */
  8196. event->pending_kill = POLL_IN;
  8197. if (events && atomic_dec_and_test(&event->event_limit)) {
  8198. ret = 1;
  8199. event->pending_kill = POLL_HUP;
  8200. perf_event_disable_inatomic(event);
  8201. }
  8202. if (event->attr.sigtrap) {
  8203. /*
  8204. * The desired behaviour of sigtrap vs invalid samples is a bit
  8205. * tricky; on the one hand, one should not loose the SIGTRAP if
  8206. * it is the first event, on the other hand, we should also not
  8207. * trigger the WARN or override the data address.
  8208. */
  8209. bool valid_sample = sample_is_allowed(event, regs);
  8210. unsigned int pending_id = 1;
  8211. enum task_work_notify_mode notify_mode;
  8212. if (regs)
  8213. pending_id = hash32_ptr((void *)instruction_pointer(regs)) ?: 1;
  8214. notify_mode = in_nmi() ? TWA_NMI_CURRENT : TWA_RESUME;
  8215. if (!event->pending_work &&
  8216. !task_work_add(current, &event->pending_task, notify_mode)) {
  8217. event->pending_work = pending_id;
  8218. local_inc(&event->ctx->nr_no_switch_fast);
  8219. WARN_ON_ONCE(!atomic_long_inc_not_zero(&event->refcount));
  8220. event->pending_addr = 0;
  8221. if (valid_sample && (data->sample_flags & PERF_SAMPLE_ADDR))
  8222. event->pending_addr = data->addr;
  8223. } else if (event->attr.exclude_kernel && valid_sample) {
  8224. /*
  8225. * Should not be able to return to user space without
  8226. * consuming pending_work; with exceptions:
  8227. *
  8228. * 1. Where !exclude_kernel, events can overflow again
  8229. * in the kernel without returning to user space.
  8230. *
  8231. * 2. Events that can overflow again before the IRQ-
  8232. * work without user space progress (e.g. hrtimer).
  8233. * To approximate progress (with false negatives),
  8234. * check 32-bit hash of the current IP.
  8235. */
  8236. WARN_ON_ONCE(event->pending_work != pending_id);
  8237. }
  8238. }
  8239. READ_ONCE(event->overflow_handler)(event, data, regs);
  8240. if (*perf_event_fasync(event) && event->pending_kill) {
  8241. event->pending_wakeup = 1;
  8242. irq_work_queue(&event->pending_irq);
  8243. }
  8244. out:
  8245. if (event->attr.aux_resume)
  8246. perf_event_aux_pause(event->aux_event, false);
  8247. return ret;
  8248. }
  8249. int perf_event_overflow(struct perf_event *event,
  8250. struct perf_sample_data *data,
  8251. struct pt_regs *regs)
  8252. {
  8253. return __perf_event_overflow(event, 1, data, regs);
  8254. }
  8255. /*
  8256. * Generic software event infrastructure
  8257. */
  8258. struct swevent_htable {
  8259. struct swevent_hlist *swevent_hlist;
  8260. struct mutex hlist_mutex;
  8261. int hlist_refcount;
  8262. };
  8263. static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
  8264. /*
  8265. * We directly increment event->count and keep a second value in
  8266. * event->hw.period_left to count intervals. This period event
  8267. * is kept in the range [-sample_period, 0] so that we can use the
  8268. * sign as trigger.
  8269. */
  8270. u64 perf_swevent_set_period(struct perf_event *event)
  8271. {
  8272. struct hw_perf_event *hwc = &event->hw;
  8273. u64 period = hwc->last_period;
  8274. u64 nr, offset;
  8275. s64 old, val;
  8276. hwc->last_period = hwc->sample_period;
  8277. old = local64_read(&hwc->period_left);
  8278. do {
  8279. val = old;
  8280. if (val < 0)
  8281. return 0;
  8282. nr = div64_u64(period + val, period);
  8283. offset = nr * period;
  8284. val -= offset;
  8285. } while (!local64_try_cmpxchg(&hwc->period_left, &old, val));
  8286. return nr;
  8287. }
  8288. static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
  8289. struct perf_sample_data *data,
  8290. struct pt_regs *regs)
  8291. {
  8292. struct hw_perf_event *hwc = &event->hw;
  8293. int throttle = 0;
  8294. if (!overflow)
  8295. overflow = perf_swevent_set_period(event);
  8296. if (hwc->interrupts == MAX_INTERRUPTS)
  8297. return;
  8298. for (; overflow; overflow--) {
  8299. if (__perf_event_overflow(event, throttle,
  8300. data, regs)) {
  8301. /*
  8302. * We inhibit the overflow from happening when
  8303. * hwc->interrupts == MAX_INTERRUPTS.
  8304. */
  8305. break;
  8306. }
  8307. throttle = 1;
  8308. }
  8309. }
  8310. static void perf_swevent_event(struct perf_event *event, u64 nr,
  8311. struct perf_sample_data *data,
  8312. struct pt_regs *regs)
  8313. {
  8314. struct hw_perf_event *hwc = &event->hw;
  8315. local64_add(nr, &event->count);
  8316. if (!regs)
  8317. return;
  8318. if (!is_sampling_event(event))
  8319. return;
  8320. if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
  8321. data->period = nr;
  8322. return perf_swevent_overflow(event, 1, data, regs);
  8323. } else
  8324. data->period = event->hw.last_period;
  8325. if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
  8326. return perf_swevent_overflow(event, 1, data, regs);
  8327. if (local64_add_negative(nr, &hwc->period_left))
  8328. return;
  8329. perf_swevent_overflow(event, 0, data, regs);
  8330. }
  8331. static int perf_exclude_event(struct perf_event *event,
  8332. struct pt_regs *regs)
  8333. {
  8334. if (event->hw.state & PERF_HES_STOPPED)
  8335. return 1;
  8336. if (regs) {
  8337. if (event->attr.exclude_user && user_mode(regs))
  8338. return 1;
  8339. if (event->attr.exclude_kernel && !user_mode(regs))
  8340. return 1;
  8341. }
  8342. return 0;
  8343. }
  8344. static int perf_swevent_match(struct perf_event *event,
  8345. enum perf_type_id type,
  8346. u32 event_id,
  8347. struct perf_sample_data *data,
  8348. struct pt_regs *regs)
  8349. {
  8350. if (event->attr.type != type)
  8351. return 0;
  8352. if (event->attr.config != event_id)
  8353. return 0;
  8354. if (perf_exclude_event(event, regs))
  8355. return 0;
  8356. return 1;
  8357. }
  8358. static inline u64 swevent_hash(u64 type, u32 event_id)
  8359. {
  8360. u64 val = event_id | (type << 32);
  8361. return hash_64(val, SWEVENT_HLIST_BITS);
  8362. }
  8363. static inline struct hlist_head *
  8364. __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
  8365. {
  8366. u64 hash = swevent_hash(type, event_id);
  8367. return &hlist->heads[hash];
  8368. }
  8369. /* For the read side: events when they trigger */
  8370. static inline struct hlist_head *
  8371. find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
  8372. {
  8373. struct swevent_hlist *hlist;
  8374. hlist = rcu_dereference(swhash->swevent_hlist);
  8375. if (!hlist)
  8376. return NULL;
  8377. return __find_swevent_head(hlist, type, event_id);
  8378. }
  8379. /* For the event head insertion and removal in the hlist */
  8380. static inline struct hlist_head *
  8381. find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
  8382. {
  8383. struct swevent_hlist *hlist;
  8384. u32 event_id = event->attr.config;
  8385. u64 type = event->attr.type;
  8386. /*
  8387. * Event scheduling is always serialized against hlist allocation
  8388. * and release. Which makes the protected version suitable here.
  8389. * The context lock guarantees that.
  8390. */
  8391. hlist = rcu_dereference_protected(swhash->swevent_hlist,
  8392. lockdep_is_held(&event->ctx->lock));
  8393. if (!hlist)
  8394. return NULL;
  8395. return __find_swevent_head(hlist, type, event_id);
  8396. }
  8397. static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
  8398. u64 nr,
  8399. struct perf_sample_data *data,
  8400. struct pt_regs *regs)
  8401. {
  8402. struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
  8403. struct perf_event *event;
  8404. struct hlist_head *head;
  8405. rcu_read_lock();
  8406. head = find_swevent_head_rcu(swhash, type, event_id);
  8407. if (!head)
  8408. goto end;
  8409. hlist_for_each_entry_rcu(event, head, hlist_entry) {
  8410. if (perf_swevent_match(event, type, event_id, data, regs))
  8411. perf_swevent_event(event, nr, data, regs);
  8412. }
  8413. end:
  8414. rcu_read_unlock();
  8415. }
  8416. DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
  8417. int perf_swevent_get_recursion_context(void)
  8418. {
  8419. return get_recursion_context(current->perf_recursion);
  8420. }
  8421. EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
  8422. void perf_swevent_put_recursion_context(int rctx)
  8423. {
  8424. put_recursion_context(current->perf_recursion, rctx);
  8425. }
  8426. void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
  8427. {
  8428. struct perf_sample_data data;
  8429. if (WARN_ON_ONCE(!regs))
  8430. return;
  8431. perf_sample_data_init(&data, addr, 0);
  8432. do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
  8433. }
  8434. void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
  8435. {
  8436. int rctx;
  8437. preempt_disable_notrace();
  8438. rctx = perf_swevent_get_recursion_context();
  8439. if (unlikely(rctx < 0))
  8440. goto fail;
  8441. ___perf_sw_event(event_id, nr, regs, addr);
  8442. perf_swevent_put_recursion_context(rctx);
  8443. fail:
  8444. preempt_enable_notrace();
  8445. }
  8446. static void perf_swevent_read(struct perf_event *event)
  8447. {
  8448. }
  8449. static int perf_swevent_add(struct perf_event *event, int flags)
  8450. {
  8451. struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
  8452. struct hw_perf_event *hwc = &event->hw;
  8453. struct hlist_head *head;
  8454. if (is_sampling_event(event)) {
  8455. hwc->last_period = hwc->sample_period;
  8456. perf_swevent_set_period(event);
  8457. }
  8458. hwc->state = !(flags & PERF_EF_START);
  8459. head = find_swevent_head(swhash, event);
  8460. if (WARN_ON_ONCE(!head))
  8461. return -EINVAL;
  8462. hlist_add_head_rcu(&event->hlist_entry, head);
  8463. perf_event_update_userpage(event);
  8464. return 0;
  8465. }
  8466. static void perf_swevent_del(struct perf_event *event, int flags)
  8467. {
  8468. hlist_del_rcu(&event->hlist_entry);
  8469. }
  8470. static void perf_swevent_start(struct perf_event *event, int flags)
  8471. {
  8472. event->hw.state = 0;
  8473. }
  8474. static void perf_swevent_stop(struct perf_event *event, int flags)
  8475. {
  8476. event->hw.state = PERF_HES_STOPPED;
  8477. }
  8478. /* Deref the hlist from the update side */
  8479. static inline struct swevent_hlist *
  8480. swevent_hlist_deref(struct swevent_htable *swhash)
  8481. {
  8482. return rcu_dereference_protected(swhash->swevent_hlist,
  8483. lockdep_is_held(&swhash->hlist_mutex));
  8484. }
  8485. static void swevent_hlist_release(struct swevent_htable *swhash)
  8486. {
  8487. struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
  8488. if (!hlist)
  8489. return;
  8490. RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
  8491. kfree_rcu(hlist, rcu_head);
  8492. }
  8493. static void swevent_hlist_put_cpu(int cpu)
  8494. {
  8495. struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
  8496. mutex_lock(&swhash->hlist_mutex);
  8497. if (!--swhash->hlist_refcount)
  8498. swevent_hlist_release(swhash);
  8499. mutex_unlock(&swhash->hlist_mutex);
  8500. }
  8501. static void swevent_hlist_put(void)
  8502. {
  8503. int cpu;
  8504. for_each_possible_cpu(cpu)
  8505. swevent_hlist_put_cpu(cpu);
  8506. }
  8507. static int swevent_hlist_get_cpu(int cpu)
  8508. {
  8509. struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
  8510. int err = 0;
  8511. mutex_lock(&swhash->hlist_mutex);
  8512. if (!swevent_hlist_deref(swhash) &&
  8513. cpumask_test_cpu(cpu, perf_online_mask)) {
  8514. struct swevent_hlist *hlist;
  8515. hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
  8516. if (!hlist) {
  8517. err = -ENOMEM;
  8518. goto exit;
  8519. }
  8520. rcu_assign_pointer(swhash->swevent_hlist, hlist);
  8521. }
  8522. swhash->hlist_refcount++;
  8523. exit:
  8524. mutex_unlock(&swhash->hlist_mutex);
  8525. return err;
  8526. }
  8527. static int swevent_hlist_get(void)
  8528. {
  8529. int err, cpu, failed_cpu;
  8530. mutex_lock(&pmus_lock);
  8531. for_each_possible_cpu(cpu) {
  8532. err = swevent_hlist_get_cpu(cpu);
  8533. if (err) {
  8534. failed_cpu = cpu;
  8535. goto fail;
  8536. }
  8537. }
  8538. mutex_unlock(&pmus_lock);
  8539. return 0;
  8540. fail:
  8541. for_each_possible_cpu(cpu) {
  8542. if (cpu == failed_cpu)
  8543. break;
  8544. swevent_hlist_put_cpu(cpu);
  8545. }
  8546. mutex_unlock(&pmus_lock);
  8547. return err;
  8548. }
  8549. struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
  8550. static void sw_perf_event_destroy(struct perf_event *event)
  8551. {
  8552. u64 event_id = event->attr.config;
  8553. WARN_ON(event->parent);
  8554. static_key_slow_dec(&perf_swevent_enabled[event_id]);
  8555. swevent_hlist_put();
  8556. }
  8557. static struct pmu perf_cpu_clock; /* fwd declaration */
  8558. static struct pmu perf_task_clock;
  8559. static int perf_swevent_init(struct perf_event *event)
  8560. {
  8561. u64 event_id = event->attr.config;
  8562. if (event->attr.type != PERF_TYPE_SOFTWARE)
  8563. return -ENOENT;
  8564. /*
  8565. * no branch sampling for software events
  8566. */
  8567. if (has_branch_stack(event))
  8568. return -EOPNOTSUPP;
  8569. switch (event_id) {
  8570. case PERF_COUNT_SW_CPU_CLOCK:
  8571. event->attr.type = perf_cpu_clock.type;
  8572. return -ENOENT;
  8573. case PERF_COUNT_SW_TASK_CLOCK:
  8574. event->attr.type = perf_task_clock.type;
  8575. return -ENOENT;
  8576. default:
  8577. break;
  8578. }
  8579. if (event_id >= PERF_COUNT_SW_MAX)
  8580. return -ENOENT;
  8581. if (!event->parent) {
  8582. int err;
  8583. err = swevent_hlist_get();
  8584. if (err)
  8585. return err;
  8586. static_key_slow_inc(&perf_swevent_enabled[event_id]);
  8587. event->destroy = sw_perf_event_destroy;
  8588. }
  8589. return 0;
  8590. }
  8591. static struct pmu perf_swevent = {
  8592. .task_ctx_nr = perf_sw_context,
  8593. .capabilities = PERF_PMU_CAP_NO_NMI,
  8594. .event_init = perf_swevent_init,
  8595. .add = perf_swevent_add,
  8596. .del = perf_swevent_del,
  8597. .start = perf_swevent_start,
  8598. .stop = perf_swevent_stop,
  8599. .read = perf_swevent_read,
  8600. };
  8601. #ifdef CONFIG_EVENT_TRACING
  8602. static void tp_perf_event_destroy(struct perf_event *event)
  8603. {
  8604. perf_trace_destroy(event);
  8605. }
  8606. static int perf_tp_event_init(struct perf_event *event)
  8607. {
  8608. int err;
  8609. if (event->attr.type != PERF_TYPE_TRACEPOINT)
  8610. return -ENOENT;
  8611. /*
  8612. * no branch sampling for tracepoint events
  8613. */
  8614. if (has_branch_stack(event))
  8615. return -EOPNOTSUPP;
  8616. err = perf_trace_init(event);
  8617. if (err)
  8618. return err;
  8619. event->destroy = tp_perf_event_destroy;
  8620. return 0;
  8621. }
  8622. static struct pmu perf_tracepoint = {
  8623. .task_ctx_nr = perf_sw_context,
  8624. .event_init = perf_tp_event_init,
  8625. .add = perf_trace_add,
  8626. .del = perf_trace_del,
  8627. .start = perf_swevent_start,
  8628. .stop = perf_swevent_stop,
  8629. .read = perf_swevent_read,
  8630. };
  8631. static int perf_tp_filter_match(struct perf_event *event,
  8632. struct perf_raw_record *raw)
  8633. {
  8634. void *record = raw->frag.data;
  8635. /* only top level events have filters set */
  8636. if (event->parent)
  8637. event = event->parent;
  8638. if (likely(!event->filter) || filter_match_preds(event->filter, record))
  8639. return 1;
  8640. return 0;
  8641. }
  8642. static int perf_tp_event_match(struct perf_event *event,
  8643. struct perf_raw_record *raw,
  8644. struct pt_regs *regs)
  8645. {
  8646. if (event->hw.state & PERF_HES_STOPPED)
  8647. return 0;
  8648. /*
  8649. * If exclude_kernel, only trace user-space tracepoints (uprobes)
  8650. */
  8651. if (event->attr.exclude_kernel && !user_mode(regs))
  8652. return 0;
  8653. if (!perf_tp_filter_match(event, raw))
  8654. return 0;
  8655. return 1;
  8656. }
  8657. void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx,
  8658. struct trace_event_call *call, u64 count,
  8659. struct pt_regs *regs, struct hlist_head *head,
  8660. struct task_struct *task)
  8661. {
  8662. if (bpf_prog_array_valid(call)) {
  8663. *(struct pt_regs **)raw_data = regs;
  8664. if (!trace_call_bpf(call, raw_data) || hlist_empty(head)) {
  8665. perf_swevent_put_recursion_context(rctx);
  8666. return;
  8667. }
  8668. }
  8669. perf_tp_event(call->event.type, count, raw_data, size, regs, head,
  8670. rctx, task);
  8671. }
  8672. EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit);
  8673. static void __perf_tp_event_target_task(u64 count, void *record,
  8674. struct pt_regs *regs,
  8675. struct perf_sample_data *data,
  8676. struct perf_raw_record *raw,
  8677. struct perf_event *event)
  8678. {
  8679. struct trace_entry *entry = record;
  8680. if (event->attr.config != entry->type)
  8681. return;
  8682. /* Cannot deliver synchronous signal to other task. */
  8683. if (event->attr.sigtrap)
  8684. return;
  8685. if (perf_tp_event_match(event, raw, regs)) {
  8686. perf_sample_data_init(data, 0, 0);
  8687. perf_sample_save_raw_data(data, event, raw);
  8688. perf_swevent_event(event, count, data, regs);
  8689. }
  8690. }
  8691. static void perf_tp_event_target_task(u64 count, void *record,
  8692. struct pt_regs *regs,
  8693. struct perf_sample_data *data,
  8694. struct perf_raw_record *raw,
  8695. struct perf_event_context *ctx)
  8696. {
  8697. unsigned int cpu = smp_processor_id();
  8698. struct pmu *pmu = &perf_tracepoint;
  8699. struct perf_event *event, *sibling;
  8700. perf_event_groups_for_cpu_pmu(event, &ctx->pinned_groups, cpu, pmu) {
  8701. __perf_tp_event_target_task(count, record, regs, data, raw, event);
  8702. for_each_sibling_event(sibling, event)
  8703. __perf_tp_event_target_task(count, record, regs, data, raw, sibling);
  8704. }
  8705. perf_event_groups_for_cpu_pmu(event, &ctx->flexible_groups, cpu, pmu) {
  8706. __perf_tp_event_target_task(count, record, regs, data, raw, event);
  8707. for_each_sibling_event(sibling, event)
  8708. __perf_tp_event_target_task(count, record, regs, data, raw, sibling);
  8709. }
  8710. }
  8711. void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size,
  8712. struct pt_regs *regs, struct hlist_head *head, int rctx,
  8713. struct task_struct *task)
  8714. {
  8715. struct perf_sample_data data;
  8716. struct perf_event *event;
  8717. struct perf_raw_record raw = {
  8718. .frag = {
  8719. .size = entry_size,
  8720. .data = record,
  8721. },
  8722. };
  8723. perf_trace_buf_update(record, event_type);
  8724. hlist_for_each_entry_rcu(event, head, hlist_entry) {
  8725. if (perf_tp_event_match(event, &raw, regs)) {
  8726. /*
  8727. * Here use the same on-stack perf_sample_data,
  8728. * some members in data are event-specific and
  8729. * need to be re-computed for different sweveents.
  8730. * Re-initialize data->sample_flags safely to avoid
  8731. * the problem that next event skips preparing data
  8732. * because data->sample_flags is set.
  8733. */
  8734. perf_sample_data_init(&data, 0, 0);
  8735. perf_sample_save_raw_data(&data, event, &raw);
  8736. perf_swevent_event(event, count, &data, regs);
  8737. }
  8738. }
  8739. /*
  8740. * If we got specified a target task, also iterate its context and
  8741. * deliver this event there too.
  8742. */
  8743. if (task && task != current) {
  8744. struct perf_event_context *ctx;
  8745. rcu_read_lock();
  8746. ctx = rcu_dereference(task->perf_event_ctxp);
  8747. if (!ctx)
  8748. goto unlock;
  8749. raw_spin_lock(&ctx->lock);
  8750. perf_tp_event_target_task(count, record, regs, &data, &raw, ctx);
  8751. raw_spin_unlock(&ctx->lock);
  8752. unlock:
  8753. rcu_read_unlock();
  8754. }
  8755. perf_swevent_put_recursion_context(rctx);
  8756. }
  8757. EXPORT_SYMBOL_GPL(perf_tp_event);
  8758. #if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS)
  8759. /*
  8760. * Flags in config, used by dynamic PMU kprobe and uprobe
  8761. * The flags should match following PMU_FORMAT_ATTR().
  8762. *
  8763. * PERF_PROBE_CONFIG_IS_RETPROBE if set, create kretprobe/uretprobe
  8764. * if not set, create kprobe/uprobe
  8765. *
  8766. * The following values specify a reference counter (or semaphore in the
  8767. * terminology of tools like dtrace, systemtap, etc.) Userspace Statically
  8768. * Defined Tracepoints (USDT). Currently, we use 40 bit for the offset.
  8769. *
  8770. * PERF_UPROBE_REF_CTR_OFFSET_BITS # of bits in config as th offset
  8771. * PERF_UPROBE_REF_CTR_OFFSET_SHIFT # of bits to shift left
  8772. */
  8773. enum perf_probe_config {
  8774. PERF_PROBE_CONFIG_IS_RETPROBE = 1U << 0, /* [k,u]retprobe */
  8775. PERF_UPROBE_REF_CTR_OFFSET_BITS = 32,
  8776. PERF_UPROBE_REF_CTR_OFFSET_SHIFT = 64 - PERF_UPROBE_REF_CTR_OFFSET_BITS,
  8777. };
  8778. PMU_FORMAT_ATTR(retprobe, "config:0");
  8779. #endif
  8780. #ifdef CONFIG_KPROBE_EVENTS
  8781. static struct attribute *kprobe_attrs[] = {
  8782. &format_attr_retprobe.attr,
  8783. NULL,
  8784. };
  8785. static struct attribute_group kprobe_format_group = {
  8786. .name = "format",
  8787. .attrs = kprobe_attrs,
  8788. };
  8789. static const struct attribute_group *kprobe_attr_groups[] = {
  8790. &kprobe_format_group,
  8791. NULL,
  8792. };
  8793. static int perf_kprobe_event_init(struct perf_event *event);
  8794. static struct pmu perf_kprobe = {
  8795. .task_ctx_nr = perf_sw_context,
  8796. .event_init = perf_kprobe_event_init,
  8797. .add = perf_trace_add,
  8798. .del = perf_trace_del,
  8799. .start = perf_swevent_start,
  8800. .stop = perf_swevent_stop,
  8801. .read = perf_swevent_read,
  8802. .attr_groups = kprobe_attr_groups,
  8803. };
  8804. static int perf_kprobe_event_init(struct perf_event *event)
  8805. {
  8806. int err;
  8807. bool is_retprobe;
  8808. if (event->attr.type != perf_kprobe.type)
  8809. return -ENOENT;
  8810. if (!perfmon_capable())
  8811. return -EACCES;
  8812. /*
  8813. * no branch sampling for probe events
  8814. */
  8815. if (has_branch_stack(event))
  8816. return -EOPNOTSUPP;
  8817. is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
  8818. err = perf_kprobe_init(event, is_retprobe);
  8819. if (err)
  8820. return err;
  8821. event->destroy = perf_kprobe_destroy;
  8822. return 0;
  8823. }
  8824. #endif /* CONFIG_KPROBE_EVENTS */
  8825. #ifdef CONFIG_UPROBE_EVENTS
  8826. PMU_FORMAT_ATTR(ref_ctr_offset, "config:32-63");
  8827. static struct attribute *uprobe_attrs[] = {
  8828. &format_attr_retprobe.attr,
  8829. &format_attr_ref_ctr_offset.attr,
  8830. NULL,
  8831. };
  8832. static struct attribute_group uprobe_format_group = {
  8833. .name = "format",
  8834. .attrs = uprobe_attrs,
  8835. };
  8836. static const struct attribute_group *uprobe_attr_groups[] = {
  8837. &uprobe_format_group,
  8838. NULL,
  8839. };
  8840. static int perf_uprobe_event_init(struct perf_event *event);
  8841. static struct pmu perf_uprobe = {
  8842. .task_ctx_nr = perf_sw_context,
  8843. .event_init = perf_uprobe_event_init,
  8844. .add = perf_trace_add,
  8845. .del = perf_trace_del,
  8846. .start = perf_swevent_start,
  8847. .stop = perf_swevent_stop,
  8848. .read = perf_swevent_read,
  8849. .attr_groups = uprobe_attr_groups,
  8850. };
  8851. static int perf_uprobe_event_init(struct perf_event *event)
  8852. {
  8853. int err;
  8854. unsigned long ref_ctr_offset;
  8855. bool is_retprobe;
  8856. if (event->attr.type != perf_uprobe.type)
  8857. return -ENOENT;
  8858. if (!capable(CAP_SYS_ADMIN))
  8859. return -EACCES;
  8860. /*
  8861. * no branch sampling for probe events
  8862. */
  8863. if (has_branch_stack(event))
  8864. return -EOPNOTSUPP;
  8865. is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
  8866. ref_ctr_offset = event->attr.config >> PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
  8867. err = perf_uprobe_init(event, ref_ctr_offset, is_retprobe);
  8868. if (err)
  8869. return err;
  8870. event->destroy = perf_uprobe_destroy;
  8871. return 0;
  8872. }
  8873. #endif /* CONFIG_UPROBE_EVENTS */
  8874. static inline void perf_tp_register(void)
  8875. {
  8876. perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
  8877. #ifdef CONFIG_KPROBE_EVENTS
  8878. perf_pmu_register(&perf_kprobe, "kprobe", -1);
  8879. #endif
  8880. #ifdef CONFIG_UPROBE_EVENTS
  8881. perf_pmu_register(&perf_uprobe, "uprobe", -1);
  8882. #endif
  8883. }
  8884. static void perf_event_free_filter(struct perf_event *event)
  8885. {
  8886. ftrace_profile_free_filter(event);
  8887. }
  8888. /*
  8889. * returns true if the event is a tracepoint, or a kprobe/upprobe created
  8890. * with perf_event_open()
  8891. */
  8892. static inline bool perf_event_is_tracing(struct perf_event *event)
  8893. {
  8894. if (event->pmu == &perf_tracepoint)
  8895. return true;
  8896. #ifdef CONFIG_KPROBE_EVENTS
  8897. if (event->pmu == &perf_kprobe)
  8898. return true;
  8899. #endif
  8900. #ifdef CONFIG_UPROBE_EVENTS
  8901. if (event->pmu == &perf_uprobe)
  8902. return true;
  8903. #endif
  8904. return false;
  8905. }
  8906. static int __perf_event_set_bpf_prog(struct perf_event *event,
  8907. struct bpf_prog *prog,
  8908. u64 bpf_cookie)
  8909. {
  8910. bool is_kprobe, is_uprobe, is_tracepoint, is_syscall_tp;
  8911. if (!perf_event_is_tracing(event))
  8912. return perf_event_set_bpf_handler(event, prog, bpf_cookie);
  8913. is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_KPROBE;
  8914. is_uprobe = event->tp_event->flags & TRACE_EVENT_FL_UPROBE;
  8915. is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT;
  8916. is_syscall_tp = is_syscall_trace_event(event->tp_event);
  8917. if (!is_kprobe && !is_uprobe && !is_tracepoint && !is_syscall_tp)
  8918. /* bpf programs can only be attached to u/kprobe or tracepoint */
  8919. return -EINVAL;
  8920. if (((is_kprobe || is_uprobe) && prog->type != BPF_PROG_TYPE_KPROBE) ||
  8921. (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT) ||
  8922. (is_syscall_tp && prog->type != BPF_PROG_TYPE_TRACEPOINT))
  8923. return -EINVAL;
  8924. if (prog->type == BPF_PROG_TYPE_KPROBE && prog->sleepable && !is_uprobe)
  8925. /* only uprobe programs are allowed to be sleepable */
  8926. return -EINVAL;
  8927. /* Kprobe override only works for kprobes, not uprobes. */
  8928. if (prog->kprobe_override && !is_kprobe)
  8929. return -EINVAL;
  8930. if (is_tracepoint || is_syscall_tp) {
  8931. int off = trace_event_get_offsets(event->tp_event);
  8932. if (prog->aux->max_ctx_offset > off)
  8933. return -EACCES;
  8934. }
  8935. return perf_event_attach_bpf_prog(event, prog, bpf_cookie);
  8936. }
  8937. int perf_event_set_bpf_prog(struct perf_event *event,
  8938. struct bpf_prog *prog,
  8939. u64 bpf_cookie)
  8940. {
  8941. struct perf_event_context *ctx;
  8942. int ret;
  8943. ctx = perf_event_ctx_lock(event);
  8944. ret = __perf_event_set_bpf_prog(event, prog, bpf_cookie);
  8945. perf_event_ctx_unlock(event, ctx);
  8946. return ret;
  8947. }
  8948. void perf_event_free_bpf_prog(struct perf_event *event)
  8949. {
  8950. if (!perf_event_is_tracing(event)) {
  8951. perf_event_free_bpf_handler(event);
  8952. return;
  8953. }
  8954. perf_event_detach_bpf_prog(event);
  8955. }
  8956. #else
  8957. static inline void perf_tp_register(void)
  8958. {
  8959. }
  8960. static void perf_event_free_filter(struct perf_event *event)
  8961. {
  8962. }
  8963. static int __perf_event_set_bpf_prog(struct perf_event *event,
  8964. struct bpf_prog *prog,
  8965. u64 bpf_cookie)
  8966. {
  8967. return -ENOENT;
  8968. }
  8969. int perf_event_set_bpf_prog(struct perf_event *event,
  8970. struct bpf_prog *prog,
  8971. u64 bpf_cookie)
  8972. {
  8973. return -ENOENT;
  8974. }
  8975. void perf_event_free_bpf_prog(struct perf_event *event)
  8976. {
  8977. }
  8978. #endif /* CONFIG_EVENT_TRACING */
  8979. #ifdef CONFIG_HAVE_HW_BREAKPOINT
  8980. void perf_bp_event(struct perf_event *bp, void *data)
  8981. {
  8982. struct perf_sample_data sample;
  8983. struct pt_regs *regs = data;
  8984. perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
  8985. if (!bp->hw.state && !perf_exclude_event(bp, regs))
  8986. perf_swevent_event(bp, 1, &sample, regs);
  8987. }
  8988. #endif
  8989. /*
  8990. * Allocate a new address filter
  8991. */
  8992. static struct perf_addr_filter *
  8993. perf_addr_filter_new(struct perf_event *event, struct list_head *filters)
  8994. {
  8995. int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu);
  8996. struct perf_addr_filter *filter;
  8997. filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node);
  8998. if (!filter)
  8999. return NULL;
  9000. INIT_LIST_HEAD(&filter->entry);
  9001. list_add_tail(&filter->entry, filters);
  9002. return filter;
  9003. }
  9004. static void free_filters_list(struct list_head *filters)
  9005. {
  9006. struct perf_addr_filter *filter, *iter;
  9007. list_for_each_entry_safe(filter, iter, filters, entry) {
  9008. path_put(&filter->path);
  9009. list_del(&filter->entry);
  9010. kfree(filter);
  9011. }
  9012. }
  9013. /*
  9014. * Free existing address filters and optionally install new ones
  9015. */
  9016. static void perf_addr_filters_splice(struct perf_event *event,
  9017. struct list_head *head)
  9018. {
  9019. unsigned long flags;
  9020. LIST_HEAD(list);
  9021. if (!has_addr_filter(event))
  9022. return;
  9023. /* don't bother with children, they don't have their own filters */
  9024. if (event->parent)
  9025. return;
  9026. raw_spin_lock_irqsave(&event->addr_filters.lock, flags);
  9027. list_splice_init(&event->addr_filters.list, &list);
  9028. if (head)
  9029. list_splice(head, &event->addr_filters.list);
  9030. raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags);
  9031. free_filters_list(&list);
  9032. }
  9033. /*
  9034. * Scan through mm's vmas and see if one of them matches the
  9035. * @filter; if so, adjust filter's address range.
  9036. * Called with mm::mmap_lock down for reading.
  9037. */
  9038. static void perf_addr_filter_apply(struct perf_addr_filter *filter,
  9039. struct mm_struct *mm,
  9040. struct perf_addr_filter_range *fr)
  9041. {
  9042. struct vm_area_struct *vma;
  9043. VMA_ITERATOR(vmi, mm, 0);
  9044. for_each_vma(vmi, vma) {
  9045. if (!vma->vm_file)
  9046. continue;
  9047. if (perf_addr_filter_vma_adjust(filter, vma, fr))
  9048. return;
  9049. }
  9050. }
  9051. /*
  9052. * Update event's address range filters based on the
  9053. * task's existing mappings, if any.
  9054. */
  9055. static void perf_event_addr_filters_apply(struct perf_event *event)
  9056. {
  9057. struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
  9058. struct task_struct *task = READ_ONCE(event->ctx->task);
  9059. struct perf_addr_filter *filter;
  9060. struct mm_struct *mm = NULL;
  9061. unsigned int count = 0;
  9062. unsigned long flags;
  9063. /*
  9064. * We may observe TASK_TOMBSTONE, which means that the event tear-down
  9065. * will stop on the parent's child_mutex that our caller is also holding
  9066. */
  9067. if (task == TASK_TOMBSTONE)
  9068. return;
  9069. if (ifh->nr_file_filters) {
  9070. mm = get_task_mm(task);
  9071. if (!mm)
  9072. goto restart;
  9073. mmap_read_lock(mm);
  9074. }
  9075. raw_spin_lock_irqsave(&ifh->lock, flags);
  9076. list_for_each_entry(filter, &ifh->list, entry) {
  9077. if (filter->path.dentry) {
  9078. /*
  9079. * Adjust base offset if the filter is associated to a
  9080. * binary that needs to be mapped:
  9081. */
  9082. event->addr_filter_ranges[count].start = 0;
  9083. event->addr_filter_ranges[count].size = 0;
  9084. perf_addr_filter_apply(filter, mm, &event->addr_filter_ranges[count]);
  9085. } else {
  9086. event->addr_filter_ranges[count].start = filter->offset;
  9087. event->addr_filter_ranges[count].size = filter->size;
  9088. }
  9089. count++;
  9090. }
  9091. event->addr_filters_gen++;
  9092. raw_spin_unlock_irqrestore(&ifh->lock, flags);
  9093. if (ifh->nr_file_filters) {
  9094. mmap_read_unlock(mm);
  9095. mmput(mm);
  9096. }
  9097. restart:
  9098. perf_event_stop(event, 1);
  9099. }
  9100. /*
  9101. * Address range filtering: limiting the data to certain
  9102. * instruction address ranges. Filters are ioctl()ed to us from
  9103. * userspace as ascii strings.
  9104. *
  9105. * Filter string format:
  9106. *
  9107. * ACTION RANGE_SPEC
  9108. * where ACTION is one of the
  9109. * * "filter": limit the trace to this region
  9110. * * "start": start tracing from this address
  9111. * * "stop": stop tracing at this address/region;
  9112. * RANGE_SPEC is
  9113. * * for kernel addresses: <start address>[/<size>]
  9114. * * for object files: <start address>[/<size>]@</path/to/object/file>
  9115. *
  9116. * if <size> is not specified or is zero, the range is treated as a single
  9117. * address; not valid for ACTION=="filter".
  9118. */
  9119. enum {
  9120. IF_ACT_NONE = -1,
  9121. IF_ACT_FILTER,
  9122. IF_ACT_START,
  9123. IF_ACT_STOP,
  9124. IF_SRC_FILE,
  9125. IF_SRC_KERNEL,
  9126. IF_SRC_FILEADDR,
  9127. IF_SRC_KERNELADDR,
  9128. };
  9129. enum {
  9130. IF_STATE_ACTION = 0,
  9131. IF_STATE_SOURCE,
  9132. IF_STATE_END,
  9133. };
  9134. static const match_table_t if_tokens = {
  9135. { IF_ACT_FILTER, "filter" },
  9136. { IF_ACT_START, "start" },
  9137. { IF_ACT_STOP, "stop" },
  9138. { IF_SRC_FILE, "%u/%u@%s" },
  9139. { IF_SRC_KERNEL, "%u/%u" },
  9140. { IF_SRC_FILEADDR, "%u@%s" },
  9141. { IF_SRC_KERNELADDR, "%u" },
  9142. { IF_ACT_NONE, NULL },
  9143. };
  9144. /*
  9145. * Address filter string parser
  9146. */
  9147. static int
  9148. perf_event_parse_addr_filter(struct perf_event *event, char *fstr,
  9149. struct list_head *filters)
  9150. {
  9151. struct perf_addr_filter *filter = NULL;
  9152. char *start, *orig, *filename = NULL;
  9153. substring_t args[MAX_OPT_ARGS];
  9154. int state = IF_STATE_ACTION, token;
  9155. unsigned int kernel = 0;
  9156. int ret = -EINVAL;
  9157. orig = fstr = kstrdup(fstr, GFP_KERNEL);
  9158. if (!fstr)
  9159. return -ENOMEM;
  9160. while ((start = strsep(&fstr, " ,\n")) != NULL) {
  9161. static const enum perf_addr_filter_action_t actions[] = {
  9162. [IF_ACT_FILTER] = PERF_ADDR_FILTER_ACTION_FILTER,
  9163. [IF_ACT_START] = PERF_ADDR_FILTER_ACTION_START,
  9164. [IF_ACT_STOP] = PERF_ADDR_FILTER_ACTION_STOP,
  9165. };
  9166. ret = -EINVAL;
  9167. if (!*start)
  9168. continue;
  9169. /* filter definition begins */
  9170. if (state == IF_STATE_ACTION) {
  9171. filter = perf_addr_filter_new(event, filters);
  9172. if (!filter)
  9173. goto fail;
  9174. }
  9175. token = match_token(start, if_tokens, args);
  9176. switch (token) {
  9177. case IF_ACT_FILTER:
  9178. case IF_ACT_START:
  9179. case IF_ACT_STOP:
  9180. if (state != IF_STATE_ACTION)
  9181. goto fail;
  9182. filter->action = actions[token];
  9183. state = IF_STATE_SOURCE;
  9184. break;
  9185. case IF_SRC_KERNELADDR:
  9186. case IF_SRC_KERNEL:
  9187. kernel = 1;
  9188. fallthrough;
  9189. case IF_SRC_FILEADDR:
  9190. case IF_SRC_FILE:
  9191. if (state != IF_STATE_SOURCE)
  9192. goto fail;
  9193. *args[0].to = 0;
  9194. ret = kstrtoul(args[0].from, 0, &filter->offset);
  9195. if (ret)
  9196. goto fail;
  9197. if (token == IF_SRC_KERNEL || token == IF_SRC_FILE) {
  9198. *args[1].to = 0;
  9199. ret = kstrtoul(args[1].from, 0, &filter->size);
  9200. if (ret)
  9201. goto fail;
  9202. }
  9203. if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) {
  9204. int fpos = token == IF_SRC_FILE ? 2 : 1;
  9205. kfree(filename);
  9206. filename = match_strdup(&args[fpos]);
  9207. if (!filename) {
  9208. ret = -ENOMEM;
  9209. goto fail;
  9210. }
  9211. }
  9212. state = IF_STATE_END;
  9213. break;
  9214. default:
  9215. goto fail;
  9216. }
  9217. /*
  9218. * Filter definition is fully parsed, validate and install it.
  9219. * Make sure that it doesn't contradict itself or the event's
  9220. * attribute.
  9221. */
  9222. if (state == IF_STATE_END) {
  9223. ret = -EINVAL;
  9224. /*
  9225. * ACTION "filter" must have a non-zero length region
  9226. * specified.
  9227. */
  9228. if (filter->action == PERF_ADDR_FILTER_ACTION_FILTER &&
  9229. !filter->size)
  9230. goto fail;
  9231. if (!kernel) {
  9232. if (!filename)
  9233. goto fail;
  9234. /*
  9235. * For now, we only support file-based filters
  9236. * in per-task events; doing so for CPU-wide
  9237. * events requires additional context switching
  9238. * trickery, since same object code will be
  9239. * mapped at different virtual addresses in
  9240. * different processes.
  9241. */
  9242. ret = -EOPNOTSUPP;
  9243. if (!event->ctx->task)
  9244. goto fail;
  9245. /* look up the path and grab its inode */
  9246. ret = kern_path(filename, LOOKUP_FOLLOW,
  9247. &filter->path);
  9248. if (ret)
  9249. goto fail;
  9250. ret = -EINVAL;
  9251. if (!filter->path.dentry ||
  9252. !S_ISREG(d_inode(filter->path.dentry)
  9253. ->i_mode))
  9254. goto fail;
  9255. event->addr_filters.nr_file_filters++;
  9256. }
  9257. /* ready to consume more filters */
  9258. kfree(filename);
  9259. filename = NULL;
  9260. state = IF_STATE_ACTION;
  9261. filter = NULL;
  9262. kernel = 0;
  9263. }
  9264. }
  9265. if (state != IF_STATE_ACTION)
  9266. goto fail;
  9267. kfree(filename);
  9268. kfree(orig);
  9269. return 0;
  9270. fail:
  9271. kfree(filename);
  9272. free_filters_list(filters);
  9273. kfree(orig);
  9274. return ret;
  9275. }
  9276. static int
  9277. perf_event_set_addr_filter(struct perf_event *event, char *filter_str)
  9278. {
  9279. LIST_HEAD(filters);
  9280. int ret;
  9281. /*
  9282. * Since this is called in perf_ioctl() path, we're already holding
  9283. * ctx::mutex.
  9284. */
  9285. lockdep_assert_held(&event->ctx->mutex);
  9286. if (WARN_ON_ONCE(event->parent))
  9287. return -EINVAL;
  9288. ret = perf_event_parse_addr_filter(event, filter_str, &filters);
  9289. if (ret)
  9290. goto fail_clear_files;
  9291. ret = event->pmu->addr_filters_validate(&filters);
  9292. if (ret)
  9293. goto fail_free_filters;
  9294. /* remove existing filters, if any */
  9295. perf_addr_filters_splice(event, &filters);
  9296. /* install new filters */
  9297. perf_event_for_each_child(event, perf_event_addr_filters_apply);
  9298. return ret;
  9299. fail_free_filters:
  9300. free_filters_list(&filters);
  9301. fail_clear_files:
  9302. event->addr_filters.nr_file_filters = 0;
  9303. return ret;
  9304. }
  9305. static int perf_event_set_filter(struct perf_event *event, void __user *arg)
  9306. {
  9307. int ret = -EINVAL;
  9308. char *filter_str;
  9309. filter_str = strndup_user(arg, PAGE_SIZE);
  9310. if (IS_ERR(filter_str))
  9311. return PTR_ERR(filter_str);
  9312. #ifdef CONFIG_EVENT_TRACING
  9313. if (perf_event_is_tracing(event)) {
  9314. struct perf_event_context *ctx = event->ctx;
  9315. /*
  9316. * Beware, here be dragons!!
  9317. *
  9318. * the tracepoint muck will deadlock against ctx->mutex, but
  9319. * the tracepoint stuff does not actually need it. So
  9320. * temporarily drop ctx->mutex. As per perf_event_ctx_lock() we
  9321. * already have a reference on ctx.
  9322. *
  9323. * This can result in event getting moved to a different ctx,
  9324. * but that does not affect the tracepoint state.
  9325. */
  9326. mutex_unlock(&ctx->mutex);
  9327. ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
  9328. mutex_lock(&ctx->mutex);
  9329. } else
  9330. #endif
  9331. if (has_addr_filter(event))
  9332. ret = perf_event_set_addr_filter(event, filter_str);
  9333. kfree(filter_str);
  9334. return ret;
  9335. }
  9336. /*
  9337. * hrtimer based swevent callback
  9338. */
  9339. static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
  9340. {
  9341. enum hrtimer_restart ret = HRTIMER_RESTART;
  9342. struct perf_sample_data data;
  9343. struct pt_regs *regs;
  9344. struct perf_event *event;
  9345. u64 period;
  9346. event = container_of(hrtimer, struct perf_event, hw.hrtimer);
  9347. if (event->state != PERF_EVENT_STATE_ACTIVE)
  9348. return HRTIMER_NORESTART;
  9349. event->pmu->read(event);
  9350. perf_sample_data_init(&data, 0, event->hw.last_period);
  9351. regs = get_irq_regs();
  9352. if (regs && !perf_exclude_event(event, regs)) {
  9353. if (!(event->attr.exclude_idle && is_idle_task(current)))
  9354. if (__perf_event_overflow(event, 1, &data, regs))
  9355. ret = HRTIMER_NORESTART;
  9356. }
  9357. period = max_t(u64, 10000, event->hw.sample_period);
  9358. hrtimer_forward_now(hrtimer, ns_to_ktime(period));
  9359. return ret;
  9360. }
  9361. static void perf_swevent_start_hrtimer(struct perf_event *event)
  9362. {
  9363. struct hw_perf_event *hwc = &event->hw;
  9364. s64 period;
  9365. if (!is_sampling_event(event))
  9366. return;
  9367. period = local64_read(&hwc->period_left);
  9368. if (period) {
  9369. if (period < 0)
  9370. period = 10000;
  9371. local64_set(&hwc->period_left, 0);
  9372. } else {
  9373. period = max_t(u64, 10000, hwc->sample_period);
  9374. }
  9375. hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
  9376. HRTIMER_MODE_REL_PINNED_HARD);
  9377. }
  9378. static void perf_swevent_cancel_hrtimer(struct perf_event *event)
  9379. {
  9380. struct hw_perf_event *hwc = &event->hw;
  9381. if (is_sampling_event(event)) {
  9382. ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
  9383. local64_set(&hwc->period_left, ktime_to_ns(remaining));
  9384. hrtimer_cancel(&hwc->hrtimer);
  9385. }
  9386. }
  9387. static void perf_swevent_init_hrtimer(struct perf_event *event)
  9388. {
  9389. struct hw_perf_event *hwc = &event->hw;
  9390. if (!is_sampling_event(event))
  9391. return;
  9392. hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
  9393. hwc->hrtimer.function = perf_swevent_hrtimer;
  9394. /*
  9395. * Since hrtimers have a fixed rate, we can do a static freq->period
  9396. * mapping and avoid the whole period adjust feedback stuff.
  9397. */
  9398. if (event->attr.freq) {
  9399. long freq = event->attr.sample_freq;
  9400. event->attr.sample_period = NSEC_PER_SEC / freq;
  9401. hwc->sample_period = event->attr.sample_period;
  9402. local64_set(&hwc->period_left, hwc->sample_period);
  9403. hwc->last_period = hwc->sample_period;
  9404. event->attr.freq = 0;
  9405. }
  9406. }
  9407. /*
  9408. * Software event: cpu wall time clock
  9409. */
  9410. static void cpu_clock_event_update(struct perf_event *event)
  9411. {
  9412. s64 prev;
  9413. u64 now;
  9414. now = local_clock();
  9415. prev = local64_xchg(&event->hw.prev_count, now);
  9416. local64_add(now - prev, &event->count);
  9417. }
  9418. static void cpu_clock_event_start(struct perf_event *event, int flags)
  9419. {
  9420. local64_set(&event->hw.prev_count, local_clock());
  9421. perf_swevent_start_hrtimer(event);
  9422. }
  9423. static void cpu_clock_event_stop(struct perf_event *event, int flags)
  9424. {
  9425. perf_swevent_cancel_hrtimer(event);
  9426. cpu_clock_event_update(event);
  9427. }
  9428. static int cpu_clock_event_add(struct perf_event *event, int flags)
  9429. {
  9430. if (flags & PERF_EF_START)
  9431. cpu_clock_event_start(event, flags);
  9432. perf_event_update_userpage(event);
  9433. return 0;
  9434. }
  9435. static void cpu_clock_event_del(struct perf_event *event, int flags)
  9436. {
  9437. cpu_clock_event_stop(event, flags);
  9438. }
  9439. static void cpu_clock_event_read(struct perf_event *event)
  9440. {
  9441. cpu_clock_event_update(event);
  9442. }
  9443. static int cpu_clock_event_init(struct perf_event *event)
  9444. {
  9445. if (event->attr.type != perf_cpu_clock.type)
  9446. return -ENOENT;
  9447. if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
  9448. return -ENOENT;
  9449. /*
  9450. * no branch sampling for software events
  9451. */
  9452. if (has_branch_stack(event))
  9453. return -EOPNOTSUPP;
  9454. perf_swevent_init_hrtimer(event);
  9455. return 0;
  9456. }
  9457. static struct pmu perf_cpu_clock = {
  9458. .task_ctx_nr = perf_sw_context,
  9459. .capabilities = PERF_PMU_CAP_NO_NMI,
  9460. .dev = PMU_NULL_DEV,
  9461. .event_init = cpu_clock_event_init,
  9462. .add = cpu_clock_event_add,
  9463. .del = cpu_clock_event_del,
  9464. .start = cpu_clock_event_start,
  9465. .stop = cpu_clock_event_stop,
  9466. .read = cpu_clock_event_read,
  9467. };
  9468. /*
  9469. * Software event: task time clock
  9470. */
  9471. static void task_clock_event_update(struct perf_event *event, u64 now)
  9472. {
  9473. u64 prev;
  9474. s64 delta;
  9475. prev = local64_xchg(&event->hw.prev_count, now);
  9476. delta = now - prev;
  9477. local64_add(delta, &event->count);
  9478. }
  9479. static void task_clock_event_start(struct perf_event *event, int flags)
  9480. {
  9481. local64_set(&event->hw.prev_count, event->ctx->time);
  9482. perf_swevent_start_hrtimer(event);
  9483. }
  9484. static void task_clock_event_stop(struct perf_event *event, int flags)
  9485. {
  9486. perf_swevent_cancel_hrtimer(event);
  9487. task_clock_event_update(event, event->ctx->time);
  9488. }
  9489. static int task_clock_event_add(struct perf_event *event, int flags)
  9490. {
  9491. if (flags & PERF_EF_START)
  9492. task_clock_event_start(event, flags);
  9493. perf_event_update_userpage(event);
  9494. return 0;
  9495. }
  9496. static void task_clock_event_del(struct perf_event *event, int flags)
  9497. {
  9498. task_clock_event_stop(event, PERF_EF_UPDATE);
  9499. }
  9500. static void task_clock_event_read(struct perf_event *event)
  9501. {
  9502. u64 now = perf_clock();
  9503. u64 delta = now - event->ctx->timestamp;
  9504. u64 time = event->ctx->time + delta;
  9505. task_clock_event_update(event, time);
  9506. }
  9507. static int task_clock_event_init(struct perf_event *event)
  9508. {
  9509. if (event->attr.type != perf_task_clock.type)
  9510. return -ENOENT;
  9511. if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
  9512. return -ENOENT;
  9513. /*
  9514. * no branch sampling for software events
  9515. */
  9516. if (has_branch_stack(event))
  9517. return -EOPNOTSUPP;
  9518. perf_swevent_init_hrtimer(event);
  9519. return 0;
  9520. }
  9521. static struct pmu perf_task_clock = {
  9522. .task_ctx_nr = perf_sw_context,
  9523. .capabilities = PERF_PMU_CAP_NO_NMI,
  9524. .dev = PMU_NULL_DEV,
  9525. .event_init = task_clock_event_init,
  9526. .add = task_clock_event_add,
  9527. .del = task_clock_event_del,
  9528. .start = task_clock_event_start,
  9529. .stop = task_clock_event_stop,
  9530. .read = task_clock_event_read,
  9531. };
  9532. static void perf_pmu_nop_void(struct pmu *pmu)
  9533. {
  9534. }
  9535. static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
  9536. {
  9537. }
  9538. static int perf_pmu_nop_int(struct pmu *pmu)
  9539. {
  9540. return 0;
  9541. }
  9542. static int perf_event_nop_int(struct perf_event *event, u64 value)
  9543. {
  9544. return 0;
  9545. }
  9546. static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
  9547. static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
  9548. {
  9549. __this_cpu_write(nop_txn_flags, flags);
  9550. if (flags & ~PERF_PMU_TXN_ADD)
  9551. return;
  9552. perf_pmu_disable(pmu);
  9553. }
  9554. static int perf_pmu_commit_txn(struct pmu *pmu)
  9555. {
  9556. unsigned int flags = __this_cpu_read(nop_txn_flags);
  9557. __this_cpu_write(nop_txn_flags, 0);
  9558. if (flags & ~PERF_PMU_TXN_ADD)
  9559. return 0;
  9560. perf_pmu_enable(pmu);
  9561. return 0;
  9562. }
  9563. static void perf_pmu_cancel_txn(struct pmu *pmu)
  9564. {
  9565. unsigned int flags = __this_cpu_read(nop_txn_flags);
  9566. __this_cpu_write(nop_txn_flags, 0);
  9567. if (flags & ~PERF_PMU_TXN_ADD)
  9568. return;
  9569. perf_pmu_enable(pmu);
  9570. }
  9571. static int perf_event_idx_default(struct perf_event *event)
  9572. {
  9573. return 0;
  9574. }
  9575. static void free_pmu_context(struct pmu *pmu)
  9576. {
  9577. free_percpu(pmu->cpu_pmu_context);
  9578. }
  9579. /*
  9580. * Let userspace know that this PMU supports address range filtering:
  9581. */
  9582. static ssize_t nr_addr_filters_show(struct device *dev,
  9583. struct device_attribute *attr,
  9584. char *page)
  9585. {
  9586. struct pmu *pmu = dev_get_drvdata(dev);
  9587. return scnprintf(page, PAGE_SIZE - 1, "%d\n", pmu->nr_addr_filters);
  9588. }
  9589. DEVICE_ATTR_RO(nr_addr_filters);
  9590. static struct idr pmu_idr;
  9591. static ssize_t
  9592. type_show(struct device *dev, struct device_attribute *attr, char *page)
  9593. {
  9594. struct pmu *pmu = dev_get_drvdata(dev);
  9595. return scnprintf(page, PAGE_SIZE - 1, "%d\n", pmu->type);
  9596. }
  9597. static DEVICE_ATTR_RO(type);
  9598. static ssize_t
  9599. perf_event_mux_interval_ms_show(struct device *dev,
  9600. struct device_attribute *attr,
  9601. char *page)
  9602. {
  9603. struct pmu *pmu = dev_get_drvdata(dev);
  9604. return scnprintf(page, PAGE_SIZE - 1, "%d\n", pmu->hrtimer_interval_ms);
  9605. }
  9606. static DEFINE_MUTEX(mux_interval_mutex);
  9607. static ssize_t
  9608. perf_event_mux_interval_ms_store(struct device *dev,
  9609. struct device_attribute *attr,
  9610. const char *buf, size_t count)
  9611. {
  9612. struct pmu *pmu = dev_get_drvdata(dev);
  9613. int timer, cpu, ret;
  9614. ret = kstrtoint(buf, 0, &timer);
  9615. if (ret)
  9616. return ret;
  9617. if (timer < 1)
  9618. return -EINVAL;
  9619. /* same value, noting to do */
  9620. if (timer == pmu->hrtimer_interval_ms)
  9621. return count;
  9622. mutex_lock(&mux_interval_mutex);
  9623. pmu->hrtimer_interval_ms = timer;
  9624. /* update all cpuctx for this PMU */
  9625. cpus_read_lock();
  9626. for_each_online_cpu(cpu) {
  9627. struct perf_cpu_pmu_context *cpc;
  9628. cpc = per_cpu_ptr(pmu->cpu_pmu_context, cpu);
  9629. cpc->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
  9630. cpu_function_call(cpu, perf_mux_hrtimer_restart_ipi, cpc);
  9631. }
  9632. cpus_read_unlock();
  9633. mutex_unlock(&mux_interval_mutex);
  9634. return count;
  9635. }
  9636. static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
  9637. static inline const struct cpumask *perf_scope_cpu_topology_cpumask(unsigned int scope, int cpu)
  9638. {
  9639. switch (scope) {
  9640. case PERF_PMU_SCOPE_CORE:
  9641. return topology_sibling_cpumask(cpu);
  9642. case PERF_PMU_SCOPE_DIE:
  9643. return topology_die_cpumask(cpu);
  9644. case PERF_PMU_SCOPE_CLUSTER:
  9645. return topology_cluster_cpumask(cpu);
  9646. case PERF_PMU_SCOPE_PKG:
  9647. return topology_core_cpumask(cpu);
  9648. case PERF_PMU_SCOPE_SYS_WIDE:
  9649. return cpu_online_mask;
  9650. }
  9651. return NULL;
  9652. }
  9653. static inline struct cpumask *perf_scope_cpumask(unsigned int scope)
  9654. {
  9655. switch (scope) {
  9656. case PERF_PMU_SCOPE_CORE:
  9657. return perf_online_core_mask;
  9658. case PERF_PMU_SCOPE_DIE:
  9659. return perf_online_die_mask;
  9660. case PERF_PMU_SCOPE_CLUSTER:
  9661. return perf_online_cluster_mask;
  9662. case PERF_PMU_SCOPE_PKG:
  9663. return perf_online_pkg_mask;
  9664. case PERF_PMU_SCOPE_SYS_WIDE:
  9665. return perf_online_sys_mask;
  9666. }
  9667. return NULL;
  9668. }
  9669. static ssize_t cpumask_show(struct device *dev, struct device_attribute *attr,
  9670. char *buf)
  9671. {
  9672. struct pmu *pmu = dev_get_drvdata(dev);
  9673. struct cpumask *mask = perf_scope_cpumask(pmu->scope);
  9674. if (mask)
  9675. return cpumap_print_to_pagebuf(true, buf, mask);
  9676. return 0;
  9677. }
  9678. static DEVICE_ATTR_RO(cpumask);
  9679. static struct attribute *pmu_dev_attrs[] = {
  9680. &dev_attr_type.attr,
  9681. &dev_attr_perf_event_mux_interval_ms.attr,
  9682. &dev_attr_nr_addr_filters.attr,
  9683. &dev_attr_cpumask.attr,
  9684. NULL,
  9685. };
  9686. static umode_t pmu_dev_is_visible(struct kobject *kobj, struct attribute *a, int n)
  9687. {
  9688. struct device *dev = kobj_to_dev(kobj);
  9689. struct pmu *pmu = dev_get_drvdata(dev);
  9690. if (n == 2 && !pmu->nr_addr_filters)
  9691. return 0;
  9692. /* cpumask */
  9693. if (n == 3 && pmu->scope == PERF_PMU_SCOPE_NONE)
  9694. return 0;
  9695. return a->mode;
  9696. }
  9697. static struct attribute_group pmu_dev_attr_group = {
  9698. .is_visible = pmu_dev_is_visible,
  9699. .attrs = pmu_dev_attrs,
  9700. };
  9701. static const struct attribute_group *pmu_dev_groups[] = {
  9702. &pmu_dev_attr_group,
  9703. NULL,
  9704. };
  9705. static int pmu_bus_running;
  9706. static struct bus_type pmu_bus = {
  9707. .name = "event_source",
  9708. .dev_groups = pmu_dev_groups,
  9709. };
  9710. static void pmu_dev_release(struct device *dev)
  9711. {
  9712. kfree(dev);
  9713. }
  9714. static int pmu_dev_alloc(struct pmu *pmu)
  9715. {
  9716. int ret = -ENOMEM;
  9717. pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
  9718. if (!pmu->dev)
  9719. goto out;
  9720. pmu->dev->groups = pmu->attr_groups;
  9721. device_initialize(pmu->dev);
  9722. dev_set_drvdata(pmu->dev, pmu);
  9723. pmu->dev->bus = &pmu_bus;
  9724. pmu->dev->parent = pmu->parent;
  9725. pmu->dev->release = pmu_dev_release;
  9726. ret = dev_set_name(pmu->dev, "%s", pmu->name);
  9727. if (ret)
  9728. goto free_dev;
  9729. ret = device_add(pmu->dev);
  9730. if (ret)
  9731. goto free_dev;
  9732. if (pmu->attr_update) {
  9733. ret = sysfs_update_groups(&pmu->dev->kobj, pmu->attr_update);
  9734. if (ret)
  9735. goto del_dev;
  9736. }
  9737. out:
  9738. return ret;
  9739. del_dev:
  9740. device_del(pmu->dev);
  9741. free_dev:
  9742. put_device(pmu->dev);
  9743. goto out;
  9744. }
  9745. static struct lock_class_key cpuctx_mutex;
  9746. static struct lock_class_key cpuctx_lock;
  9747. static bool idr_cmpxchg(struct idr *idr, unsigned long id, void *old, void *new)
  9748. {
  9749. void *tmp, *val = idr_find(idr, id);
  9750. if (val != old)
  9751. return false;
  9752. tmp = idr_replace(idr, new, id);
  9753. if (IS_ERR(tmp))
  9754. return false;
  9755. WARN_ON_ONCE(tmp != val);
  9756. return true;
  9757. }
  9758. int perf_pmu_register(struct pmu *pmu, const char *name, int type)
  9759. {
  9760. int cpu, ret, max = PERF_TYPE_MAX;
  9761. mutex_lock(&pmus_lock);
  9762. ret = -ENOMEM;
  9763. pmu->pmu_disable_count = alloc_percpu(int);
  9764. if (!pmu->pmu_disable_count)
  9765. goto unlock;
  9766. pmu->type = -1;
  9767. if (WARN_ONCE(!name, "Can not register anonymous pmu.\n")) {
  9768. ret = -EINVAL;
  9769. goto free_pdc;
  9770. }
  9771. if (WARN_ONCE(pmu->scope >= PERF_PMU_MAX_SCOPE, "Can not register a pmu with an invalid scope.\n")) {
  9772. ret = -EINVAL;
  9773. goto free_pdc;
  9774. }
  9775. pmu->name = name;
  9776. if (type >= 0)
  9777. max = type;
  9778. ret = idr_alloc(&pmu_idr, NULL, max, 0, GFP_KERNEL);
  9779. if (ret < 0)
  9780. goto free_pdc;
  9781. WARN_ON(type >= 0 && ret != type);
  9782. type = ret;
  9783. pmu->type = type;
  9784. atomic_set(&pmu->exclusive_cnt, 0);
  9785. if (pmu_bus_running && !pmu->dev) {
  9786. ret = pmu_dev_alloc(pmu);
  9787. if (ret)
  9788. goto free_idr;
  9789. }
  9790. ret = -ENOMEM;
  9791. pmu->cpu_pmu_context = alloc_percpu(struct perf_cpu_pmu_context);
  9792. if (!pmu->cpu_pmu_context)
  9793. goto free_dev;
  9794. for_each_possible_cpu(cpu) {
  9795. struct perf_cpu_pmu_context *cpc;
  9796. cpc = per_cpu_ptr(pmu->cpu_pmu_context, cpu);
  9797. __perf_init_event_pmu_context(&cpc->epc, pmu);
  9798. __perf_mux_hrtimer_init(cpc, cpu);
  9799. }
  9800. if (!pmu->start_txn) {
  9801. if (pmu->pmu_enable) {
  9802. /*
  9803. * If we have pmu_enable/pmu_disable calls, install
  9804. * transaction stubs that use that to try and batch
  9805. * hardware accesses.
  9806. */
  9807. pmu->start_txn = perf_pmu_start_txn;
  9808. pmu->commit_txn = perf_pmu_commit_txn;
  9809. pmu->cancel_txn = perf_pmu_cancel_txn;
  9810. } else {
  9811. pmu->start_txn = perf_pmu_nop_txn;
  9812. pmu->commit_txn = perf_pmu_nop_int;
  9813. pmu->cancel_txn = perf_pmu_nop_void;
  9814. }
  9815. }
  9816. if (!pmu->pmu_enable) {
  9817. pmu->pmu_enable = perf_pmu_nop_void;
  9818. pmu->pmu_disable = perf_pmu_nop_void;
  9819. }
  9820. if (!pmu->check_period)
  9821. pmu->check_period = perf_event_nop_int;
  9822. if (!pmu->event_idx)
  9823. pmu->event_idx = perf_event_idx_default;
  9824. /*
  9825. * Now that the PMU is complete, make it visible to perf_try_init_event().
  9826. */
  9827. if (!idr_cmpxchg(&pmu_idr, pmu->type, NULL, pmu))
  9828. goto free_context;
  9829. list_add_rcu(&pmu->entry, &pmus);
  9830. ret = 0;
  9831. unlock:
  9832. mutex_unlock(&pmus_lock);
  9833. return ret;
  9834. free_context:
  9835. free_percpu(pmu->cpu_pmu_context);
  9836. free_dev:
  9837. if (pmu->dev && pmu->dev != PMU_NULL_DEV) {
  9838. device_del(pmu->dev);
  9839. put_device(pmu->dev);
  9840. }
  9841. free_idr:
  9842. idr_remove(&pmu_idr, pmu->type);
  9843. free_pdc:
  9844. free_percpu(pmu->pmu_disable_count);
  9845. goto unlock;
  9846. }
  9847. EXPORT_SYMBOL_GPL(perf_pmu_register);
  9848. void perf_pmu_unregister(struct pmu *pmu)
  9849. {
  9850. mutex_lock(&pmus_lock);
  9851. list_del_rcu(&pmu->entry);
  9852. idr_remove(&pmu_idr, pmu->type);
  9853. mutex_unlock(&pmus_lock);
  9854. /*
  9855. * We dereference the pmu list under both SRCU and regular RCU, so
  9856. * synchronize against both of those.
  9857. */
  9858. synchronize_srcu(&pmus_srcu);
  9859. synchronize_rcu();
  9860. free_percpu(pmu->pmu_disable_count);
  9861. if (pmu_bus_running && pmu->dev && pmu->dev != PMU_NULL_DEV) {
  9862. if (pmu->nr_addr_filters)
  9863. device_remove_file(pmu->dev, &dev_attr_nr_addr_filters);
  9864. device_del(pmu->dev);
  9865. put_device(pmu->dev);
  9866. }
  9867. free_pmu_context(pmu);
  9868. }
  9869. EXPORT_SYMBOL_GPL(perf_pmu_unregister);
  9870. static inline bool has_extended_regs(struct perf_event *event)
  9871. {
  9872. return (event->attr.sample_regs_user & PERF_REG_EXTENDED_MASK) ||
  9873. (event->attr.sample_regs_intr & PERF_REG_EXTENDED_MASK);
  9874. }
  9875. static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
  9876. {
  9877. struct perf_event_context *ctx = NULL;
  9878. int ret;
  9879. if (!try_module_get(pmu->module))
  9880. return -ENODEV;
  9881. /*
  9882. * A number of pmu->event_init() methods iterate the sibling_list to,
  9883. * for example, validate if the group fits on the PMU. Therefore,
  9884. * if this is a sibling event, acquire the ctx->mutex to protect
  9885. * the sibling_list.
  9886. */
  9887. if (event->group_leader != event && pmu->task_ctx_nr != perf_sw_context) {
  9888. /*
  9889. * This ctx->mutex can nest when we're called through
  9890. * inheritance. See the perf_event_ctx_lock_nested() comment.
  9891. */
  9892. ctx = perf_event_ctx_lock_nested(event->group_leader,
  9893. SINGLE_DEPTH_NESTING);
  9894. BUG_ON(!ctx);
  9895. }
  9896. event->pmu = pmu;
  9897. ret = pmu->event_init(event);
  9898. if (ctx)
  9899. perf_event_ctx_unlock(event->group_leader, ctx);
  9900. if (ret)
  9901. goto err_pmu;
  9902. if (!(pmu->capabilities & PERF_PMU_CAP_EXTENDED_REGS) &&
  9903. has_extended_regs(event)) {
  9904. ret = -EOPNOTSUPP;
  9905. goto err_destroy;
  9906. }
  9907. if (pmu->capabilities & PERF_PMU_CAP_NO_EXCLUDE &&
  9908. event_has_any_exclude_flag(event)) {
  9909. ret = -EINVAL;
  9910. goto err_destroy;
  9911. }
  9912. if (pmu->scope != PERF_PMU_SCOPE_NONE && event->cpu >= 0) {
  9913. const struct cpumask *cpumask;
  9914. struct cpumask *pmu_cpumask;
  9915. int cpu;
  9916. cpumask = perf_scope_cpu_topology_cpumask(pmu->scope, event->cpu);
  9917. pmu_cpumask = perf_scope_cpumask(pmu->scope);
  9918. ret = -ENODEV;
  9919. if (!pmu_cpumask || !cpumask)
  9920. goto err_destroy;
  9921. cpu = cpumask_any_and(pmu_cpumask, cpumask);
  9922. if (cpu >= nr_cpu_ids)
  9923. goto err_destroy;
  9924. event->event_caps |= PERF_EV_CAP_READ_SCOPE;
  9925. }
  9926. return 0;
  9927. err_destroy:
  9928. if (event->destroy) {
  9929. event->destroy(event);
  9930. event->destroy = NULL;
  9931. }
  9932. err_pmu:
  9933. event->pmu = NULL;
  9934. module_put(pmu->module);
  9935. return ret;
  9936. }
  9937. static struct pmu *perf_init_event(struct perf_event *event)
  9938. {
  9939. bool extended_type = false;
  9940. int idx, type, ret;
  9941. struct pmu *pmu;
  9942. idx = srcu_read_lock(&pmus_srcu);
  9943. /*
  9944. * Save original type before calling pmu->event_init() since certain
  9945. * pmus overwrites event->attr.type to forward event to another pmu.
  9946. */
  9947. event->orig_type = event->attr.type;
  9948. /* Try parent's PMU first: */
  9949. if (event->parent && event->parent->pmu) {
  9950. pmu = event->parent->pmu;
  9951. ret = perf_try_init_event(pmu, event);
  9952. if (!ret)
  9953. goto unlock;
  9954. }
  9955. /*
  9956. * PERF_TYPE_HARDWARE and PERF_TYPE_HW_CACHE
  9957. * are often aliases for PERF_TYPE_RAW.
  9958. */
  9959. type = event->attr.type;
  9960. if (type == PERF_TYPE_HARDWARE || type == PERF_TYPE_HW_CACHE) {
  9961. type = event->attr.config >> PERF_PMU_TYPE_SHIFT;
  9962. if (!type) {
  9963. type = PERF_TYPE_RAW;
  9964. } else {
  9965. extended_type = true;
  9966. event->attr.config &= PERF_HW_EVENT_MASK;
  9967. }
  9968. }
  9969. again:
  9970. rcu_read_lock();
  9971. pmu = idr_find(&pmu_idr, type);
  9972. rcu_read_unlock();
  9973. if (pmu) {
  9974. if (event->attr.type != type && type != PERF_TYPE_RAW &&
  9975. !(pmu->capabilities & PERF_PMU_CAP_EXTENDED_HW_TYPE))
  9976. goto fail;
  9977. ret = perf_try_init_event(pmu, event);
  9978. if (ret == -ENOENT && event->attr.type != type && !extended_type) {
  9979. type = event->attr.type;
  9980. goto again;
  9981. }
  9982. if (ret)
  9983. pmu = ERR_PTR(ret);
  9984. goto unlock;
  9985. }
  9986. list_for_each_entry_rcu(pmu, &pmus, entry, lockdep_is_held(&pmus_srcu)) {
  9987. ret = perf_try_init_event(pmu, event);
  9988. if (!ret)
  9989. goto unlock;
  9990. if (ret != -ENOENT) {
  9991. pmu = ERR_PTR(ret);
  9992. goto unlock;
  9993. }
  9994. }
  9995. fail:
  9996. pmu = ERR_PTR(-ENOENT);
  9997. unlock:
  9998. srcu_read_unlock(&pmus_srcu, idx);
  9999. return pmu;
  10000. }
  10001. static void attach_sb_event(struct perf_event *event)
  10002. {
  10003. struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
  10004. raw_spin_lock(&pel->lock);
  10005. list_add_rcu(&event->sb_list, &pel->list);
  10006. raw_spin_unlock(&pel->lock);
  10007. }
  10008. /*
  10009. * We keep a list of all !task (and therefore per-cpu) events
  10010. * that need to receive side-band records.
  10011. *
  10012. * This avoids having to scan all the various PMU per-cpu contexts
  10013. * looking for them.
  10014. */
  10015. static void account_pmu_sb_event(struct perf_event *event)
  10016. {
  10017. if (is_sb_event(event))
  10018. attach_sb_event(event);
  10019. }
  10020. /* Freq events need the tick to stay alive (see perf_event_task_tick). */
  10021. static void account_freq_event_nohz(void)
  10022. {
  10023. #ifdef CONFIG_NO_HZ_FULL
  10024. /* Lock so we don't race with concurrent unaccount */
  10025. spin_lock(&nr_freq_lock);
  10026. if (atomic_inc_return(&nr_freq_events) == 1)
  10027. tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS);
  10028. spin_unlock(&nr_freq_lock);
  10029. #endif
  10030. }
  10031. static void account_freq_event(void)
  10032. {
  10033. if (tick_nohz_full_enabled())
  10034. account_freq_event_nohz();
  10035. else
  10036. atomic_inc(&nr_freq_events);
  10037. }
  10038. static void account_event(struct perf_event *event)
  10039. {
  10040. bool inc = false;
  10041. if (event->parent)
  10042. return;
  10043. if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB))
  10044. inc = true;
  10045. if (event->attr.mmap || event->attr.mmap_data)
  10046. atomic_inc(&nr_mmap_events);
  10047. if (event->attr.build_id)
  10048. atomic_inc(&nr_build_id_events);
  10049. if (event->attr.comm)
  10050. atomic_inc(&nr_comm_events);
  10051. if (event->attr.namespaces)
  10052. atomic_inc(&nr_namespaces_events);
  10053. if (event->attr.cgroup)
  10054. atomic_inc(&nr_cgroup_events);
  10055. if (event->attr.task)
  10056. atomic_inc(&nr_task_events);
  10057. if (event->attr.freq)
  10058. account_freq_event();
  10059. if (event->attr.context_switch) {
  10060. atomic_inc(&nr_switch_events);
  10061. inc = true;
  10062. }
  10063. if (has_branch_stack(event))
  10064. inc = true;
  10065. if (is_cgroup_event(event))
  10066. inc = true;
  10067. if (event->attr.ksymbol)
  10068. atomic_inc(&nr_ksymbol_events);
  10069. if (event->attr.bpf_event)
  10070. atomic_inc(&nr_bpf_events);
  10071. if (event->attr.text_poke)
  10072. atomic_inc(&nr_text_poke_events);
  10073. if (inc) {
  10074. /*
  10075. * We need the mutex here because static_branch_enable()
  10076. * must complete *before* the perf_sched_count increment
  10077. * becomes visible.
  10078. */
  10079. if (atomic_inc_not_zero(&perf_sched_count))
  10080. goto enabled;
  10081. mutex_lock(&perf_sched_mutex);
  10082. if (!atomic_read(&perf_sched_count)) {
  10083. static_branch_enable(&perf_sched_events);
  10084. /*
  10085. * Guarantee that all CPUs observe they key change and
  10086. * call the perf scheduling hooks before proceeding to
  10087. * install events that need them.
  10088. */
  10089. synchronize_rcu();
  10090. }
  10091. /*
  10092. * Now that we have waited for the sync_sched(), allow further
  10093. * increments to by-pass the mutex.
  10094. */
  10095. atomic_inc(&perf_sched_count);
  10096. mutex_unlock(&perf_sched_mutex);
  10097. }
  10098. enabled:
  10099. account_pmu_sb_event(event);
  10100. }
  10101. /*
  10102. * Allocate and initialize an event structure
  10103. */
  10104. static struct perf_event *
  10105. perf_event_alloc(struct perf_event_attr *attr, int cpu,
  10106. struct task_struct *task,
  10107. struct perf_event *group_leader,
  10108. struct perf_event *parent_event,
  10109. perf_overflow_handler_t overflow_handler,
  10110. void *context, int cgroup_fd)
  10111. {
  10112. struct pmu *pmu;
  10113. struct perf_event *event;
  10114. struct hw_perf_event *hwc;
  10115. long err = -EINVAL;
  10116. int node;
  10117. if ((unsigned)cpu >= nr_cpu_ids) {
  10118. if (!task || cpu != -1)
  10119. return ERR_PTR(-EINVAL);
  10120. }
  10121. if (attr->sigtrap && !task) {
  10122. /* Requires a task: avoid signalling random tasks. */
  10123. return ERR_PTR(-EINVAL);
  10124. }
  10125. node = (cpu >= 0) ? cpu_to_node(cpu) : -1;
  10126. event = kmem_cache_alloc_node(perf_event_cache, GFP_KERNEL | __GFP_ZERO,
  10127. node);
  10128. if (!event)
  10129. return ERR_PTR(-ENOMEM);
  10130. /*
  10131. * Single events are their own group leaders, with an
  10132. * empty sibling list:
  10133. */
  10134. if (!group_leader)
  10135. group_leader = event;
  10136. mutex_init(&event->child_mutex);
  10137. INIT_LIST_HEAD(&event->child_list);
  10138. INIT_LIST_HEAD(&event->event_entry);
  10139. INIT_LIST_HEAD(&event->sibling_list);
  10140. INIT_LIST_HEAD(&event->active_list);
  10141. init_event_group(event);
  10142. INIT_LIST_HEAD(&event->rb_entry);
  10143. INIT_LIST_HEAD(&event->active_entry);
  10144. INIT_LIST_HEAD(&event->addr_filters.list);
  10145. INIT_HLIST_NODE(&event->hlist_entry);
  10146. init_waitqueue_head(&event->waitq);
  10147. init_irq_work(&event->pending_irq, perf_pending_irq);
  10148. event->pending_disable_irq = IRQ_WORK_INIT_HARD(perf_pending_disable);
  10149. init_task_work(&event->pending_task, perf_pending_task);
  10150. mutex_init(&event->mmap_mutex);
  10151. raw_spin_lock_init(&event->addr_filters.lock);
  10152. atomic_long_set(&event->refcount, 1);
  10153. event->cpu = cpu;
  10154. event->attr = *attr;
  10155. event->group_leader = group_leader;
  10156. event->pmu = NULL;
  10157. event->oncpu = -1;
  10158. event->parent = parent_event;
  10159. event->ns = get_pid_ns(task_active_pid_ns(current));
  10160. event->id = atomic64_inc_return(&perf_event_id);
  10161. event->state = PERF_EVENT_STATE_INACTIVE;
  10162. if (parent_event)
  10163. event->event_caps = parent_event->event_caps;
  10164. if (task) {
  10165. event->attach_state = PERF_ATTACH_TASK;
  10166. /*
  10167. * XXX pmu::event_init needs to know what task to account to
  10168. * and we cannot use the ctx information because we need the
  10169. * pmu before we get a ctx.
  10170. */
  10171. event->hw.target = get_task_struct(task);
  10172. }
  10173. event->clock = &local_clock;
  10174. if (parent_event)
  10175. event->clock = parent_event->clock;
  10176. if (!overflow_handler && parent_event) {
  10177. overflow_handler = parent_event->overflow_handler;
  10178. context = parent_event->overflow_handler_context;
  10179. #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING)
  10180. if (parent_event->prog) {
  10181. struct bpf_prog *prog = parent_event->prog;
  10182. bpf_prog_inc(prog);
  10183. event->prog = prog;
  10184. }
  10185. #endif
  10186. }
  10187. if (overflow_handler) {
  10188. event->overflow_handler = overflow_handler;
  10189. event->overflow_handler_context = context;
  10190. } else if (is_write_backward(event)){
  10191. event->overflow_handler = perf_event_output_backward;
  10192. event->overflow_handler_context = NULL;
  10193. } else {
  10194. event->overflow_handler = perf_event_output_forward;
  10195. event->overflow_handler_context = NULL;
  10196. }
  10197. perf_event__state_init(event);
  10198. pmu = NULL;
  10199. hwc = &event->hw;
  10200. hwc->sample_period = attr->sample_period;
  10201. if (attr->freq && attr->sample_freq)
  10202. hwc->sample_period = 1;
  10203. hwc->last_period = hwc->sample_period;
  10204. local64_set(&hwc->period_left, hwc->sample_period);
  10205. /*
  10206. * We do not support PERF_SAMPLE_READ on inherited events unless
  10207. * PERF_SAMPLE_TID is also selected, which allows inherited events to
  10208. * collect per-thread samples.
  10209. * See perf_output_read().
  10210. */
  10211. if (has_inherit_and_sample_read(attr) && !(attr->sample_type & PERF_SAMPLE_TID))
  10212. goto err;
  10213. if (!has_branch_stack(event))
  10214. event->attr.branch_sample_type = 0;
  10215. pmu = perf_init_event(event);
  10216. if (IS_ERR(pmu)) {
  10217. err = PTR_ERR(pmu);
  10218. goto err;
  10219. }
  10220. /*
  10221. * Disallow uncore-task events. Similarly, disallow uncore-cgroup
  10222. * events (they don't make sense as the cgroup will be different
  10223. * on other CPUs in the uncore mask).
  10224. */
  10225. if (pmu->task_ctx_nr == perf_invalid_context && (task || cgroup_fd != -1)) {
  10226. err = -EINVAL;
  10227. goto err;
  10228. }
  10229. if (event->attr.aux_output &&
  10230. (!(pmu->capabilities & PERF_PMU_CAP_AUX_OUTPUT) ||
  10231. event->attr.aux_pause || event->attr.aux_resume)) {
  10232. err = -EOPNOTSUPP;
  10233. goto err;
  10234. }
  10235. if (event->attr.aux_pause && event->attr.aux_resume) {
  10236. err = -EINVAL;
  10237. goto err;
  10238. }
  10239. if (event->attr.aux_start_paused) {
  10240. if (!(pmu->capabilities & PERF_PMU_CAP_AUX_PAUSE)) {
  10241. err = -EOPNOTSUPP;
  10242. goto err;
  10243. }
  10244. event->hw.aux_paused = 1;
  10245. }
  10246. if (cgroup_fd != -1) {
  10247. err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
  10248. if (err)
  10249. goto err;
  10250. }
  10251. err = exclusive_event_init(event);
  10252. if (err)
  10253. goto err;
  10254. if (has_addr_filter(event)) {
  10255. event->addr_filter_ranges = kcalloc(pmu->nr_addr_filters,
  10256. sizeof(struct perf_addr_filter_range),
  10257. GFP_KERNEL);
  10258. if (!event->addr_filter_ranges) {
  10259. err = -ENOMEM;
  10260. goto err;
  10261. }
  10262. /*
  10263. * Clone the parent's vma offsets: they are valid until exec()
  10264. * even if the mm is not shared with the parent.
  10265. */
  10266. if (event->parent) {
  10267. struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
  10268. raw_spin_lock_irq(&ifh->lock);
  10269. memcpy(event->addr_filter_ranges,
  10270. event->parent->addr_filter_ranges,
  10271. pmu->nr_addr_filters * sizeof(struct perf_addr_filter_range));
  10272. raw_spin_unlock_irq(&ifh->lock);
  10273. }
  10274. /* force hw sync on the address filters */
  10275. event->addr_filters_gen = 1;
  10276. }
  10277. if (!event->parent) {
  10278. if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
  10279. err = get_callchain_buffers(attr->sample_max_stack);
  10280. if (err)
  10281. goto err;
  10282. event->attach_state |= PERF_ATTACH_CALLCHAIN;
  10283. }
  10284. }
  10285. err = security_perf_event_alloc(event);
  10286. if (err)
  10287. goto err;
  10288. /* symmetric to unaccount_event() in _free_event() */
  10289. account_event(event);
  10290. return event;
  10291. err:
  10292. __free_event(event);
  10293. return ERR_PTR(err);
  10294. }
  10295. static int perf_copy_attr(struct perf_event_attr __user *uattr,
  10296. struct perf_event_attr *attr)
  10297. {
  10298. u32 size;
  10299. int ret;
  10300. /* Zero the full structure, so that a short copy will be nice. */
  10301. memset(attr, 0, sizeof(*attr));
  10302. ret = get_user(size, &uattr->size);
  10303. if (ret)
  10304. return ret;
  10305. /* ABI compatibility quirk: */
  10306. if (!size)
  10307. size = PERF_ATTR_SIZE_VER0;
  10308. if (size < PERF_ATTR_SIZE_VER0 || size > PAGE_SIZE)
  10309. goto err_size;
  10310. ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size);
  10311. if (ret) {
  10312. if (ret == -E2BIG)
  10313. goto err_size;
  10314. return ret;
  10315. }
  10316. attr->size = size;
  10317. if (attr->__reserved_1 || attr->__reserved_2 || attr->__reserved_3)
  10318. return -EINVAL;
  10319. if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
  10320. return -EINVAL;
  10321. if (attr->read_format & ~(PERF_FORMAT_MAX-1))
  10322. return -EINVAL;
  10323. if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
  10324. u64 mask = attr->branch_sample_type;
  10325. /* only using defined bits */
  10326. if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
  10327. return -EINVAL;
  10328. /* at least one branch bit must be set */
  10329. if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
  10330. return -EINVAL;
  10331. /* propagate priv level, when not set for branch */
  10332. if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
  10333. /* exclude_kernel checked on syscall entry */
  10334. if (!attr->exclude_kernel)
  10335. mask |= PERF_SAMPLE_BRANCH_KERNEL;
  10336. if (!attr->exclude_user)
  10337. mask |= PERF_SAMPLE_BRANCH_USER;
  10338. if (!attr->exclude_hv)
  10339. mask |= PERF_SAMPLE_BRANCH_HV;
  10340. /*
  10341. * adjust user setting (for HW filter setup)
  10342. */
  10343. attr->branch_sample_type = mask;
  10344. }
  10345. /* privileged levels capture (kernel, hv): check permissions */
  10346. if (mask & PERF_SAMPLE_BRANCH_PERM_PLM) {
  10347. ret = perf_allow_kernel(attr);
  10348. if (ret)
  10349. return ret;
  10350. }
  10351. }
  10352. if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
  10353. ret = perf_reg_validate(attr->sample_regs_user);
  10354. if (ret)
  10355. return ret;
  10356. }
  10357. if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
  10358. if (!arch_perf_have_user_stack_dump())
  10359. return -ENOSYS;
  10360. /*
  10361. * We have __u32 type for the size, but so far
  10362. * we can only use __u16 as maximum due to the
  10363. * __u16 sample size limit.
  10364. */
  10365. if (attr->sample_stack_user >= USHRT_MAX)
  10366. return -EINVAL;
  10367. else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
  10368. return -EINVAL;
  10369. }
  10370. if (!attr->sample_max_stack)
  10371. attr->sample_max_stack = sysctl_perf_event_max_stack;
  10372. if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
  10373. ret = perf_reg_validate(attr->sample_regs_intr);
  10374. #ifndef CONFIG_CGROUP_PERF
  10375. if (attr->sample_type & PERF_SAMPLE_CGROUP)
  10376. return -EINVAL;
  10377. #endif
  10378. if ((attr->sample_type & PERF_SAMPLE_WEIGHT) &&
  10379. (attr->sample_type & PERF_SAMPLE_WEIGHT_STRUCT))
  10380. return -EINVAL;
  10381. if (!attr->inherit && attr->inherit_thread)
  10382. return -EINVAL;
  10383. if (attr->remove_on_exec && attr->enable_on_exec)
  10384. return -EINVAL;
  10385. if (attr->sigtrap && !attr->remove_on_exec)
  10386. return -EINVAL;
  10387. out:
  10388. return ret;
  10389. err_size:
  10390. put_user(sizeof(*attr), &uattr->size);
  10391. ret = -E2BIG;
  10392. goto out;
  10393. }
  10394. static void mutex_lock_double(struct mutex *a, struct mutex *b)
  10395. {
  10396. if (b < a)
  10397. swap(a, b);
  10398. mutex_lock(a);
  10399. mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
  10400. }
  10401. static int
  10402. perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
  10403. {
  10404. struct perf_buffer *rb = NULL;
  10405. int ret = -EINVAL;
  10406. if (!output_event) {
  10407. mutex_lock(&event->mmap_mutex);
  10408. goto set;
  10409. }
  10410. /* don't allow circular references */
  10411. if (event == output_event)
  10412. goto out;
  10413. /*
  10414. * Don't allow cross-cpu buffers
  10415. */
  10416. if (output_event->cpu != event->cpu)
  10417. goto out;
  10418. /*
  10419. * If its not a per-cpu rb, it must be the same task.
  10420. */
  10421. if (output_event->cpu == -1 && output_event->hw.target != event->hw.target)
  10422. goto out;
  10423. /*
  10424. * Mixing clocks in the same buffer is trouble you don't need.
  10425. */
  10426. if (output_event->clock != event->clock)
  10427. goto out;
  10428. /*
  10429. * Either writing ring buffer from beginning or from end.
  10430. * Mixing is not allowed.
  10431. */
  10432. if (is_write_backward(output_event) != is_write_backward(event))
  10433. goto out;
  10434. /*
  10435. * If both events generate aux data, they must be on the same PMU
  10436. */
  10437. if (has_aux(event) && has_aux(output_event) &&
  10438. event->pmu != output_event->pmu)
  10439. goto out;
  10440. /*
  10441. * Hold both mmap_mutex to serialize against perf_mmap_close(). Since
  10442. * output_event is already on rb->event_list, and the list iteration
  10443. * restarts after every removal, it is guaranteed this new event is
  10444. * observed *OR* if output_event is already removed, it's guaranteed we
  10445. * observe !rb->mmap_count.
  10446. */
  10447. mutex_lock_double(&event->mmap_mutex, &output_event->mmap_mutex);
  10448. set:
  10449. /* Can't redirect output if we've got an active mmap() */
  10450. if (atomic_read(&event->mmap_count))
  10451. goto unlock;
  10452. if (output_event) {
  10453. /* get the rb we want to redirect to */
  10454. rb = ring_buffer_get(output_event);
  10455. if (!rb)
  10456. goto unlock;
  10457. /* did we race against perf_mmap_close() */
  10458. if (!atomic_read(&rb->mmap_count)) {
  10459. ring_buffer_put(rb);
  10460. goto unlock;
  10461. }
  10462. }
  10463. ring_buffer_attach(event, rb);
  10464. ret = 0;
  10465. unlock:
  10466. mutex_unlock(&event->mmap_mutex);
  10467. if (output_event)
  10468. mutex_unlock(&output_event->mmap_mutex);
  10469. out:
  10470. return ret;
  10471. }
  10472. static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
  10473. {
  10474. bool nmi_safe = false;
  10475. switch (clk_id) {
  10476. case CLOCK_MONOTONIC:
  10477. event->clock = &ktime_get_mono_fast_ns;
  10478. nmi_safe = true;
  10479. break;
  10480. case CLOCK_MONOTONIC_RAW:
  10481. event->clock = &ktime_get_raw_fast_ns;
  10482. nmi_safe = true;
  10483. break;
  10484. case CLOCK_REALTIME:
  10485. event->clock = &ktime_get_real_ns;
  10486. break;
  10487. case CLOCK_BOOTTIME:
  10488. event->clock = &ktime_get_boottime_ns;
  10489. break;
  10490. case CLOCK_TAI:
  10491. event->clock = &ktime_get_clocktai_ns;
  10492. break;
  10493. default:
  10494. return -EINVAL;
  10495. }
  10496. if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
  10497. return -EINVAL;
  10498. return 0;
  10499. }
  10500. static bool
  10501. perf_check_permission(struct perf_event_attr *attr, struct task_struct *task)
  10502. {
  10503. unsigned int ptrace_mode = PTRACE_MODE_READ_REALCREDS;
  10504. bool is_capable = perfmon_capable();
  10505. if (attr->sigtrap) {
  10506. /*
  10507. * perf_event_attr::sigtrap sends signals to the other task.
  10508. * Require the current task to also have CAP_KILL.
  10509. */
  10510. rcu_read_lock();
  10511. is_capable &= ns_capable(__task_cred(task)->user_ns, CAP_KILL);
  10512. rcu_read_unlock();
  10513. /*
  10514. * If the required capabilities aren't available, checks for
  10515. * ptrace permissions: upgrade to ATTACH, since sending signals
  10516. * can effectively change the target task.
  10517. */
  10518. ptrace_mode = PTRACE_MODE_ATTACH_REALCREDS;
  10519. }
  10520. /*
  10521. * Preserve ptrace permission check for backwards compatibility. The
  10522. * ptrace check also includes checks that the current task and other
  10523. * task have matching uids, and is therefore not done here explicitly.
  10524. */
  10525. return is_capable || ptrace_may_access(task, ptrace_mode);
  10526. }
  10527. /**
  10528. * sys_perf_event_open - open a performance event, associate it to a task/cpu
  10529. *
  10530. * @attr_uptr: event_id type attributes for monitoring/sampling
  10531. * @pid: target pid
  10532. * @cpu: target cpu
  10533. * @group_fd: group leader event fd
  10534. * @flags: perf event open flags
  10535. */
  10536. SYSCALL_DEFINE5(perf_event_open,
  10537. struct perf_event_attr __user *, attr_uptr,
  10538. pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
  10539. {
  10540. struct perf_event *group_leader = NULL, *output_event = NULL;
  10541. struct perf_event_pmu_context *pmu_ctx;
  10542. struct perf_event *event, *sibling;
  10543. struct perf_event_attr attr;
  10544. struct perf_event_context *ctx;
  10545. struct file *event_file = NULL;
  10546. struct fd group = EMPTY_FD;
  10547. struct task_struct *task = NULL;
  10548. struct pmu *pmu;
  10549. int event_fd;
  10550. int move_group = 0;
  10551. int err;
  10552. int f_flags = O_RDWR;
  10553. int cgroup_fd = -1;
  10554. /* for future expandability... */
  10555. if (flags & ~PERF_FLAG_ALL)
  10556. return -EINVAL;
  10557. err = perf_copy_attr(attr_uptr, &attr);
  10558. if (err)
  10559. return err;
  10560. /* Do we allow access to perf_event_open(2) ? */
  10561. err = security_perf_event_open(&attr, PERF_SECURITY_OPEN);
  10562. if (err)
  10563. return err;
  10564. if (!attr.exclude_kernel) {
  10565. err = perf_allow_kernel(&attr);
  10566. if (err)
  10567. return err;
  10568. }
  10569. if (attr.namespaces) {
  10570. if (!perfmon_capable())
  10571. return -EACCES;
  10572. }
  10573. if (attr.freq) {
  10574. if (attr.sample_freq > sysctl_perf_event_sample_rate)
  10575. return -EINVAL;
  10576. } else {
  10577. if (attr.sample_period & (1ULL << 63))
  10578. return -EINVAL;
  10579. }
  10580. /* Only privileged users can get physical addresses */
  10581. if ((attr.sample_type & PERF_SAMPLE_PHYS_ADDR)) {
  10582. err = perf_allow_kernel(&attr);
  10583. if (err)
  10584. return err;
  10585. }
  10586. /* REGS_INTR can leak data, lockdown must prevent this */
  10587. if (attr.sample_type & PERF_SAMPLE_REGS_INTR) {
  10588. err = security_locked_down(LOCKDOWN_PERF);
  10589. if (err)
  10590. return err;
  10591. }
  10592. /*
  10593. * In cgroup mode, the pid argument is used to pass the fd
  10594. * opened to the cgroup directory in cgroupfs. The cpu argument
  10595. * designates the cpu on which to monitor threads from that
  10596. * cgroup.
  10597. */
  10598. if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
  10599. return -EINVAL;
  10600. if (flags & PERF_FLAG_FD_CLOEXEC)
  10601. f_flags |= O_CLOEXEC;
  10602. event_fd = get_unused_fd_flags(f_flags);
  10603. if (event_fd < 0)
  10604. return event_fd;
  10605. if (group_fd != -1) {
  10606. err = perf_fget_light(group_fd, &group);
  10607. if (err)
  10608. goto err_fd;
  10609. group_leader = fd_file(group)->private_data;
  10610. if (flags & PERF_FLAG_FD_OUTPUT)
  10611. output_event = group_leader;
  10612. if (flags & PERF_FLAG_FD_NO_GROUP)
  10613. group_leader = NULL;
  10614. }
  10615. if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
  10616. task = find_lively_task_by_vpid(pid);
  10617. if (IS_ERR(task)) {
  10618. err = PTR_ERR(task);
  10619. goto err_group_fd;
  10620. }
  10621. }
  10622. if (task && group_leader &&
  10623. group_leader->attr.inherit != attr.inherit) {
  10624. err = -EINVAL;
  10625. goto err_task;
  10626. }
  10627. if (flags & PERF_FLAG_PID_CGROUP)
  10628. cgroup_fd = pid;
  10629. event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
  10630. NULL, NULL, cgroup_fd);
  10631. if (IS_ERR(event)) {
  10632. err = PTR_ERR(event);
  10633. goto err_task;
  10634. }
  10635. if (is_sampling_event(event)) {
  10636. if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
  10637. err = -EOPNOTSUPP;
  10638. goto err_alloc;
  10639. }
  10640. }
  10641. /*
  10642. * Special case software events and allow them to be part of
  10643. * any hardware group.
  10644. */
  10645. pmu = event->pmu;
  10646. if (attr.use_clockid) {
  10647. err = perf_event_set_clock(event, attr.clockid);
  10648. if (err)
  10649. goto err_alloc;
  10650. }
  10651. if (pmu->task_ctx_nr == perf_sw_context)
  10652. event->event_caps |= PERF_EV_CAP_SOFTWARE;
  10653. if (task) {
  10654. err = down_read_interruptible(&task->signal->exec_update_lock);
  10655. if (err)
  10656. goto err_alloc;
  10657. /*
  10658. * We must hold exec_update_lock across this and any potential
  10659. * perf_install_in_context() call for this new event to
  10660. * serialize against exec() altering our credentials (and the
  10661. * perf_event_exit_task() that could imply).
  10662. */
  10663. err = -EACCES;
  10664. if (!perf_check_permission(&attr, task))
  10665. goto err_cred;
  10666. }
  10667. /*
  10668. * Get the target context (task or percpu):
  10669. */
  10670. ctx = find_get_context(task, event);
  10671. if (IS_ERR(ctx)) {
  10672. err = PTR_ERR(ctx);
  10673. goto err_cred;
  10674. }
  10675. mutex_lock(&ctx->mutex);
  10676. if (ctx->task == TASK_TOMBSTONE) {
  10677. err = -ESRCH;
  10678. goto err_locked;
  10679. }
  10680. if (!task) {
  10681. /*
  10682. * Check if the @cpu we're creating an event for is online.
  10683. *
  10684. * We use the perf_cpu_context::ctx::mutex to serialize against
  10685. * the hotplug notifiers. See perf_event_{init,exit}_cpu().
  10686. */
  10687. struct perf_cpu_context *cpuctx = per_cpu_ptr(&perf_cpu_context, event->cpu);
  10688. if (!cpuctx->online) {
  10689. err = -ENODEV;
  10690. goto err_locked;
  10691. }
  10692. }
  10693. if (group_leader) {
  10694. err = -EINVAL;
  10695. /*
  10696. * Do not allow a recursive hierarchy (this new sibling
  10697. * becoming part of another group-sibling):
  10698. */
  10699. if (group_leader->group_leader != group_leader)
  10700. goto err_locked;
  10701. /* All events in a group should have the same clock */
  10702. if (group_leader->clock != event->clock)
  10703. goto err_locked;
  10704. /*
  10705. * Make sure we're both events for the same CPU;
  10706. * grouping events for different CPUs is broken; since
  10707. * you can never concurrently schedule them anyhow.
  10708. */
  10709. if (group_leader->cpu != event->cpu)
  10710. goto err_locked;
  10711. /*
  10712. * Make sure we're both on the same context; either task or cpu.
  10713. */
  10714. if (group_leader->ctx != ctx)
  10715. goto err_locked;
  10716. /*
  10717. * Only a group leader can be exclusive or pinned
  10718. */
  10719. if (attr.exclusive || attr.pinned)
  10720. goto err_locked;
  10721. if (is_software_event(event) &&
  10722. !in_software_context(group_leader)) {
  10723. /*
  10724. * If the event is a sw event, but the group_leader
  10725. * is on hw context.
  10726. *
  10727. * Allow the addition of software events to hw
  10728. * groups, this is safe because software events
  10729. * never fail to schedule.
  10730. *
  10731. * Note the comment that goes with struct
  10732. * perf_event_pmu_context.
  10733. */
  10734. pmu = group_leader->pmu_ctx->pmu;
  10735. } else if (!is_software_event(event)) {
  10736. if (is_software_event(group_leader) &&
  10737. (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
  10738. /*
  10739. * In case the group is a pure software group, and we
  10740. * try to add a hardware event, move the whole group to
  10741. * the hardware context.
  10742. */
  10743. move_group = 1;
  10744. }
  10745. /* Don't allow group of multiple hw events from different pmus */
  10746. if (!in_software_context(group_leader) &&
  10747. group_leader->pmu_ctx->pmu != pmu)
  10748. goto err_locked;
  10749. }
  10750. }
  10751. /*
  10752. * Now that we're certain of the pmu; find the pmu_ctx.
  10753. */
  10754. pmu_ctx = find_get_pmu_context(pmu, ctx, event);
  10755. if (IS_ERR(pmu_ctx)) {
  10756. err = PTR_ERR(pmu_ctx);
  10757. goto err_locked;
  10758. }
  10759. event->pmu_ctx = pmu_ctx;
  10760. if (output_event) {
  10761. err = perf_event_set_output(event, output_event);
  10762. if (err)
  10763. goto err_context;
  10764. }
  10765. if (!perf_event_validate_size(event)) {
  10766. err = -E2BIG;
  10767. goto err_context;
  10768. }
  10769. if (perf_need_aux_event(event) && !perf_get_aux_event(event, group_leader)) {
  10770. err = -EINVAL;
  10771. goto err_context;
  10772. }
  10773. /*
  10774. * Must be under the same ctx::mutex as perf_install_in_context(),
  10775. * because we need to serialize with concurrent event creation.
  10776. */
  10777. if (!exclusive_event_installable(event, ctx)) {
  10778. err = -EBUSY;
  10779. goto err_context;
  10780. }
  10781. WARN_ON_ONCE(ctx->parent_ctx);
  10782. event_file = anon_inode_getfile("[perf_event]", &perf_fops, event, f_flags);
  10783. if (IS_ERR(event_file)) {
  10784. err = PTR_ERR(event_file);
  10785. event_file = NULL;
  10786. goto err_context;
  10787. }
  10788. /*
  10789. * This is the point on no return; we cannot fail hereafter. This is
  10790. * where we start modifying current state.
  10791. */
  10792. if (move_group) {
  10793. perf_remove_from_context(group_leader, 0);
  10794. put_pmu_ctx(group_leader->pmu_ctx);
  10795. for_each_sibling_event(sibling, group_leader) {
  10796. perf_remove_from_context(sibling, 0);
  10797. put_pmu_ctx(sibling->pmu_ctx);
  10798. }
  10799. /*
  10800. * Install the group siblings before the group leader.
  10801. *
  10802. * Because a group leader will try and install the entire group
  10803. * (through the sibling list, which is still in-tact), we can
  10804. * end up with siblings installed in the wrong context.
  10805. *
  10806. * By installing siblings first we NO-OP because they're not
  10807. * reachable through the group lists.
  10808. */
  10809. for_each_sibling_event(sibling, group_leader) {
  10810. sibling->pmu_ctx = pmu_ctx;
  10811. get_pmu_ctx(pmu_ctx);
  10812. perf_event__state_init(sibling);
  10813. perf_install_in_context(ctx, sibling, sibling->cpu);
  10814. }
  10815. /*
  10816. * Removing from the context ends up with disabled
  10817. * event. What we want here is event in the initial
  10818. * startup state, ready to be add into new context.
  10819. */
  10820. group_leader->pmu_ctx = pmu_ctx;
  10821. get_pmu_ctx(pmu_ctx);
  10822. perf_event__state_init(group_leader);
  10823. perf_install_in_context(ctx, group_leader, group_leader->cpu);
  10824. }
  10825. /*
  10826. * Precalculate sample_data sizes; do while holding ctx::mutex such
  10827. * that we're serialized against further additions and before
  10828. * perf_install_in_context() which is the point the event is active and
  10829. * can use these values.
  10830. */
  10831. perf_event__header_size(event);
  10832. perf_event__id_header_size(event);
  10833. event->owner = current;
  10834. perf_install_in_context(ctx, event, event->cpu);
  10835. perf_unpin_context(ctx);
  10836. mutex_unlock(&ctx->mutex);
  10837. if (task) {
  10838. up_read(&task->signal->exec_update_lock);
  10839. put_task_struct(task);
  10840. }
  10841. mutex_lock(&current->perf_event_mutex);
  10842. list_add_tail(&event->owner_entry, &current->perf_event_list);
  10843. mutex_unlock(&current->perf_event_mutex);
  10844. /*
  10845. * Drop the reference on the group_event after placing the
  10846. * new event on the sibling_list. This ensures destruction
  10847. * of the group leader will find the pointer to itself in
  10848. * perf_group_detach().
  10849. */
  10850. fdput(group);
  10851. fd_install(event_fd, event_file);
  10852. return event_fd;
  10853. err_context:
  10854. put_pmu_ctx(event->pmu_ctx);
  10855. event->pmu_ctx = NULL; /* _free_event() */
  10856. err_locked:
  10857. mutex_unlock(&ctx->mutex);
  10858. perf_unpin_context(ctx);
  10859. put_ctx(ctx);
  10860. err_cred:
  10861. if (task)
  10862. up_read(&task->signal->exec_update_lock);
  10863. err_alloc:
  10864. free_event(event);
  10865. err_task:
  10866. if (task)
  10867. put_task_struct(task);
  10868. err_group_fd:
  10869. fdput(group);
  10870. err_fd:
  10871. put_unused_fd(event_fd);
  10872. return err;
  10873. }
  10874. /**
  10875. * perf_event_create_kernel_counter
  10876. *
  10877. * @attr: attributes of the counter to create
  10878. * @cpu: cpu in which the counter is bound
  10879. * @task: task to profile (NULL for percpu)
  10880. * @overflow_handler: callback to trigger when we hit the event
  10881. * @context: context data could be used in overflow_handler callback
  10882. */
  10883. struct perf_event *
  10884. perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
  10885. struct task_struct *task,
  10886. perf_overflow_handler_t overflow_handler,
  10887. void *context)
  10888. {
  10889. struct perf_event_pmu_context *pmu_ctx;
  10890. struct perf_event_context *ctx;
  10891. struct perf_event *event;
  10892. struct pmu *pmu;
  10893. int err;
  10894. /*
  10895. * Grouping is not supported for kernel events, neither is 'AUX',
  10896. * make sure the caller's intentions are adjusted.
  10897. */
  10898. if (attr->aux_output || attr->aux_action)
  10899. return ERR_PTR(-EINVAL);
  10900. event = perf_event_alloc(attr, cpu, task, NULL, NULL,
  10901. overflow_handler, context, -1);
  10902. if (IS_ERR(event)) {
  10903. err = PTR_ERR(event);
  10904. goto err;
  10905. }
  10906. /* Mark owner so we could distinguish it from user events. */
  10907. event->owner = TASK_TOMBSTONE;
  10908. pmu = event->pmu;
  10909. if (pmu->task_ctx_nr == perf_sw_context)
  10910. event->event_caps |= PERF_EV_CAP_SOFTWARE;
  10911. /*
  10912. * Get the target context (task or percpu):
  10913. */
  10914. ctx = find_get_context(task, event);
  10915. if (IS_ERR(ctx)) {
  10916. err = PTR_ERR(ctx);
  10917. goto err_alloc;
  10918. }
  10919. WARN_ON_ONCE(ctx->parent_ctx);
  10920. mutex_lock(&ctx->mutex);
  10921. if (ctx->task == TASK_TOMBSTONE) {
  10922. err = -ESRCH;
  10923. goto err_unlock;
  10924. }
  10925. pmu_ctx = find_get_pmu_context(pmu, ctx, event);
  10926. if (IS_ERR(pmu_ctx)) {
  10927. err = PTR_ERR(pmu_ctx);
  10928. goto err_unlock;
  10929. }
  10930. event->pmu_ctx = pmu_ctx;
  10931. if (!task) {
  10932. /*
  10933. * Check if the @cpu we're creating an event for is online.
  10934. *
  10935. * We use the perf_cpu_context::ctx::mutex to serialize against
  10936. * the hotplug notifiers. See perf_event_{init,exit}_cpu().
  10937. */
  10938. struct perf_cpu_context *cpuctx =
  10939. container_of(ctx, struct perf_cpu_context, ctx);
  10940. if (!cpuctx->online) {
  10941. err = -ENODEV;
  10942. goto err_pmu_ctx;
  10943. }
  10944. }
  10945. if (!exclusive_event_installable(event, ctx)) {
  10946. err = -EBUSY;
  10947. goto err_pmu_ctx;
  10948. }
  10949. perf_install_in_context(ctx, event, event->cpu);
  10950. perf_unpin_context(ctx);
  10951. mutex_unlock(&ctx->mutex);
  10952. return event;
  10953. err_pmu_ctx:
  10954. put_pmu_ctx(pmu_ctx);
  10955. event->pmu_ctx = NULL; /* _free_event() */
  10956. err_unlock:
  10957. mutex_unlock(&ctx->mutex);
  10958. perf_unpin_context(ctx);
  10959. put_ctx(ctx);
  10960. err_alloc:
  10961. free_event(event);
  10962. err:
  10963. return ERR_PTR(err);
  10964. }
  10965. EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
  10966. static void __perf_pmu_remove(struct perf_event_context *ctx,
  10967. int cpu, struct pmu *pmu,
  10968. struct perf_event_groups *groups,
  10969. struct list_head *events)
  10970. {
  10971. struct perf_event *event, *sibling;
  10972. perf_event_groups_for_cpu_pmu(event, groups, cpu, pmu) {
  10973. perf_remove_from_context(event, 0);
  10974. put_pmu_ctx(event->pmu_ctx);
  10975. list_add(&event->migrate_entry, events);
  10976. for_each_sibling_event(sibling, event) {
  10977. perf_remove_from_context(sibling, 0);
  10978. put_pmu_ctx(sibling->pmu_ctx);
  10979. list_add(&sibling->migrate_entry, events);
  10980. }
  10981. }
  10982. }
  10983. static void __perf_pmu_install_event(struct pmu *pmu,
  10984. struct perf_event_context *ctx,
  10985. int cpu, struct perf_event *event)
  10986. {
  10987. struct perf_event_pmu_context *epc;
  10988. struct perf_event_context *old_ctx = event->ctx;
  10989. get_ctx(ctx); /* normally find_get_context() */
  10990. event->cpu = cpu;
  10991. epc = find_get_pmu_context(pmu, ctx, event);
  10992. event->pmu_ctx = epc;
  10993. if (event->state >= PERF_EVENT_STATE_OFF)
  10994. event->state = PERF_EVENT_STATE_INACTIVE;
  10995. perf_install_in_context(ctx, event, cpu);
  10996. /*
  10997. * Now that event->ctx is updated and visible, put the old ctx.
  10998. */
  10999. put_ctx(old_ctx);
  11000. }
  11001. static void __perf_pmu_install(struct perf_event_context *ctx,
  11002. int cpu, struct pmu *pmu, struct list_head *events)
  11003. {
  11004. struct perf_event *event, *tmp;
  11005. /*
  11006. * Re-instate events in 2 passes.
  11007. *
  11008. * Skip over group leaders and only install siblings on this first
  11009. * pass, siblings will not get enabled without a leader, however a
  11010. * leader will enable its siblings, even if those are still on the old
  11011. * context.
  11012. */
  11013. list_for_each_entry_safe(event, tmp, events, migrate_entry) {
  11014. if (event->group_leader == event)
  11015. continue;
  11016. list_del(&event->migrate_entry);
  11017. __perf_pmu_install_event(pmu, ctx, cpu, event);
  11018. }
  11019. /*
  11020. * Once all the siblings are setup properly, install the group leaders
  11021. * to make it go.
  11022. */
  11023. list_for_each_entry_safe(event, tmp, events, migrate_entry) {
  11024. list_del(&event->migrate_entry);
  11025. __perf_pmu_install_event(pmu, ctx, cpu, event);
  11026. }
  11027. }
  11028. void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
  11029. {
  11030. struct perf_event_context *src_ctx, *dst_ctx;
  11031. LIST_HEAD(events);
  11032. /*
  11033. * Since per-cpu context is persistent, no need to grab an extra
  11034. * reference.
  11035. */
  11036. src_ctx = &per_cpu_ptr(&perf_cpu_context, src_cpu)->ctx;
  11037. dst_ctx = &per_cpu_ptr(&perf_cpu_context, dst_cpu)->ctx;
  11038. /*
  11039. * See perf_event_ctx_lock() for comments on the details
  11040. * of swizzling perf_event::ctx.
  11041. */
  11042. mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
  11043. __perf_pmu_remove(src_ctx, src_cpu, pmu, &src_ctx->pinned_groups, &events);
  11044. __perf_pmu_remove(src_ctx, src_cpu, pmu, &src_ctx->flexible_groups, &events);
  11045. if (!list_empty(&events)) {
  11046. /*
  11047. * Wait for the events to quiesce before re-instating them.
  11048. */
  11049. synchronize_rcu();
  11050. __perf_pmu_install(dst_ctx, dst_cpu, pmu, &events);
  11051. }
  11052. mutex_unlock(&dst_ctx->mutex);
  11053. mutex_unlock(&src_ctx->mutex);
  11054. }
  11055. EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
  11056. static void sync_child_event(struct perf_event *child_event)
  11057. {
  11058. struct perf_event *parent_event = child_event->parent;
  11059. u64 child_val;
  11060. if (child_event->attr.inherit_stat) {
  11061. struct task_struct *task = child_event->ctx->task;
  11062. if (task && task != TASK_TOMBSTONE)
  11063. perf_event_read_event(child_event, task);
  11064. }
  11065. child_val = perf_event_count(child_event, false);
  11066. /*
  11067. * Add back the child's count to the parent's count:
  11068. */
  11069. atomic64_add(child_val, &parent_event->child_count);
  11070. atomic64_add(child_event->total_time_enabled,
  11071. &parent_event->child_total_time_enabled);
  11072. atomic64_add(child_event->total_time_running,
  11073. &parent_event->child_total_time_running);
  11074. }
  11075. static void
  11076. perf_event_exit_event(struct perf_event *event, struct perf_event_context *ctx)
  11077. {
  11078. struct perf_event *parent_event = event->parent;
  11079. unsigned long detach_flags = 0;
  11080. if (parent_event) {
  11081. /*
  11082. * Do not destroy the 'original' grouping; because of the
  11083. * context switch optimization the original events could've
  11084. * ended up in a random child task.
  11085. *
  11086. * If we were to destroy the original group, all group related
  11087. * operations would cease to function properly after this
  11088. * random child dies.
  11089. *
  11090. * Do destroy all inherited groups, we don't care about those
  11091. * and being thorough is better.
  11092. */
  11093. detach_flags = DETACH_GROUP | DETACH_CHILD;
  11094. mutex_lock(&parent_event->child_mutex);
  11095. }
  11096. perf_remove_from_context(event, detach_flags | DETACH_EXIT);
  11097. /*
  11098. * Child events can be freed.
  11099. */
  11100. if (parent_event) {
  11101. mutex_unlock(&parent_event->child_mutex);
  11102. /*
  11103. * Kick perf_poll() for is_event_hup();
  11104. */
  11105. perf_event_wakeup(parent_event);
  11106. put_event(event);
  11107. return;
  11108. }
  11109. /*
  11110. * Parent events are governed by their filedesc, retain them.
  11111. */
  11112. perf_event_wakeup(event);
  11113. }
  11114. static void perf_event_exit_task_context(struct task_struct *child)
  11115. {
  11116. struct perf_event_context *child_ctx, *clone_ctx = NULL;
  11117. struct perf_event *child_event, *next;
  11118. WARN_ON_ONCE(child != current);
  11119. child_ctx = perf_pin_task_context(child);
  11120. if (!child_ctx)
  11121. return;
  11122. /*
  11123. * In order to reduce the amount of tricky in ctx tear-down, we hold
  11124. * ctx::mutex over the entire thing. This serializes against almost
  11125. * everything that wants to access the ctx.
  11126. *
  11127. * The exception is sys_perf_event_open() /
  11128. * perf_event_create_kernel_count() which does find_get_context()
  11129. * without ctx::mutex (it cannot because of the move_group double mutex
  11130. * lock thing). See the comments in perf_install_in_context().
  11131. */
  11132. mutex_lock(&child_ctx->mutex);
  11133. /*
  11134. * In a single ctx::lock section, de-schedule the events and detach the
  11135. * context from the task such that we cannot ever get it scheduled back
  11136. * in.
  11137. */
  11138. raw_spin_lock_irq(&child_ctx->lock);
  11139. task_ctx_sched_out(child_ctx, NULL, EVENT_ALL);
  11140. /*
  11141. * Now that the context is inactive, destroy the task <-> ctx relation
  11142. * and mark the context dead.
  11143. */
  11144. RCU_INIT_POINTER(child->perf_event_ctxp, NULL);
  11145. put_ctx(child_ctx); /* cannot be last */
  11146. WRITE_ONCE(child_ctx->task, TASK_TOMBSTONE);
  11147. put_task_struct(current); /* cannot be last */
  11148. clone_ctx = unclone_ctx(child_ctx);
  11149. raw_spin_unlock_irq(&child_ctx->lock);
  11150. if (clone_ctx)
  11151. put_ctx(clone_ctx);
  11152. /*
  11153. * Report the task dead after unscheduling the events so that we
  11154. * won't get any samples after PERF_RECORD_EXIT. We can however still
  11155. * get a few PERF_RECORD_READ events.
  11156. */
  11157. perf_event_task(child, child_ctx, 0);
  11158. list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
  11159. perf_event_exit_event(child_event, child_ctx);
  11160. mutex_unlock(&child_ctx->mutex);
  11161. put_ctx(child_ctx);
  11162. }
  11163. /*
  11164. * When a child task exits, feed back event values to parent events.
  11165. *
  11166. * Can be called with exec_update_lock held when called from
  11167. * setup_new_exec().
  11168. */
  11169. void perf_event_exit_task(struct task_struct *child)
  11170. {
  11171. struct perf_event *event, *tmp;
  11172. mutex_lock(&child->perf_event_mutex);
  11173. list_for_each_entry_safe(event, tmp, &child->perf_event_list,
  11174. owner_entry) {
  11175. list_del_init(&event->owner_entry);
  11176. /*
  11177. * Ensure the list deletion is visible before we clear
  11178. * the owner, closes a race against perf_release() where
  11179. * we need to serialize on the owner->perf_event_mutex.
  11180. */
  11181. smp_store_release(&event->owner, NULL);
  11182. }
  11183. mutex_unlock(&child->perf_event_mutex);
  11184. perf_event_exit_task_context(child);
  11185. /*
  11186. * The perf_event_exit_task_context calls perf_event_task
  11187. * with child's task_ctx, which generates EXIT events for
  11188. * child contexts and sets child->perf_event_ctxp[] to NULL.
  11189. * At this point we need to send EXIT events to cpu contexts.
  11190. */
  11191. perf_event_task(child, NULL, 0);
  11192. }
  11193. static void perf_free_event(struct perf_event *event,
  11194. struct perf_event_context *ctx)
  11195. {
  11196. struct perf_event *parent = event->parent;
  11197. if (WARN_ON_ONCE(!parent))
  11198. return;
  11199. mutex_lock(&parent->child_mutex);
  11200. list_del_init(&event->child_list);
  11201. mutex_unlock(&parent->child_mutex);
  11202. raw_spin_lock_irq(&ctx->lock);
  11203. perf_group_detach(event);
  11204. list_del_event(event, ctx);
  11205. raw_spin_unlock_irq(&ctx->lock);
  11206. put_event(event);
  11207. }
  11208. /*
  11209. * Free a context as created by inheritance by perf_event_init_task() below,
  11210. * used by fork() in case of fail.
  11211. *
  11212. * Even though the task has never lived, the context and events have been
  11213. * exposed through the child_list, so we must take care tearing it all down.
  11214. */
  11215. void perf_event_free_task(struct task_struct *task)
  11216. {
  11217. struct perf_event_context *ctx;
  11218. struct perf_event *event, *tmp;
  11219. ctx = rcu_access_pointer(task->perf_event_ctxp);
  11220. if (!ctx)
  11221. return;
  11222. mutex_lock(&ctx->mutex);
  11223. raw_spin_lock_irq(&ctx->lock);
  11224. /*
  11225. * Destroy the task <-> ctx relation and mark the context dead.
  11226. *
  11227. * This is important because even though the task hasn't been
  11228. * exposed yet the context has been (through child_list).
  11229. */
  11230. RCU_INIT_POINTER(task->perf_event_ctxp, NULL);
  11231. WRITE_ONCE(ctx->task, TASK_TOMBSTONE);
  11232. put_task_struct(task); /* cannot be last */
  11233. raw_spin_unlock_irq(&ctx->lock);
  11234. list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry)
  11235. perf_free_event(event, ctx);
  11236. mutex_unlock(&ctx->mutex);
  11237. /*
  11238. * perf_event_release_kernel() could've stolen some of our
  11239. * child events and still have them on its free_list. In that
  11240. * case we must wait for these events to have been freed (in
  11241. * particular all their references to this task must've been
  11242. * dropped).
  11243. *
  11244. * Without this copy_process() will unconditionally free this
  11245. * task (irrespective of its reference count) and
  11246. * _free_event()'s put_task_struct(event->hw.target) will be a
  11247. * use-after-free.
  11248. *
  11249. * Wait for all events to drop their context reference.
  11250. */
  11251. wait_var_event(&ctx->refcount, refcount_read(&ctx->refcount) == 1);
  11252. put_ctx(ctx); /* must be last */
  11253. }
  11254. void perf_event_delayed_put(struct task_struct *task)
  11255. {
  11256. WARN_ON_ONCE(task->perf_event_ctxp);
  11257. }
  11258. struct file *perf_event_get(unsigned int fd)
  11259. {
  11260. struct file *file = fget(fd);
  11261. if (!file)
  11262. return ERR_PTR(-EBADF);
  11263. if (file->f_op != &perf_fops) {
  11264. fput(file);
  11265. return ERR_PTR(-EBADF);
  11266. }
  11267. return file;
  11268. }
  11269. const struct perf_event *perf_get_event(struct file *file)
  11270. {
  11271. if (file->f_op != &perf_fops)
  11272. return ERR_PTR(-EINVAL);
  11273. return file->private_data;
  11274. }
  11275. const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
  11276. {
  11277. if (!event)
  11278. return ERR_PTR(-EINVAL);
  11279. return &event->attr;
  11280. }
  11281. int perf_allow_kernel(struct perf_event_attr *attr)
  11282. {
  11283. if (sysctl_perf_event_paranoid > 1 && !perfmon_capable())
  11284. return -EACCES;
  11285. return security_perf_event_open(attr, PERF_SECURITY_KERNEL);
  11286. }
  11287. EXPORT_SYMBOL_GPL(perf_allow_kernel);
  11288. /*
  11289. * Inherit an event from parent task to child task.
  11290. *
  11291. * Returns:
  11292. * - valid pointer on success
  11293. * - NULL for orphaned events
  11294. * - IS_ERR() on error
  11295. */
  11296. static struct perf_event *
  11297. inherit_event(struct perf_event *parent_event,
  11298. struct task_struct *parent,
  11299. struct perf_event_context *parent_ctx,
  11300. struct task_struct *child,
  11301. struct perf_event *group_leader,
  11302. struct perf_event_context *child_ctx)
  11303. {
  11304. enum perf_event_state parent_state = parent_event->state;
  11305. struct perf_event_pmu_context *pmu_ctx;
  11306. struct perf_event *child_event;
  11307. unsigned long flags;
  11308. /*
  11309. * Instead of creating recursive hierarchies of events,
  11310. * we link inherited events back to the original parent,
  11311. * which has a filp for sure, which we use as the reference
  11312. * count:
  11313. */
  11314. if (parent_event->parent)
  11315. parent_event = parent_event->parent;
  11316. child_event = perf_event_alloc(&parent_event->attr,
  11317. parent_event->cpu,
  11318. child,
  11319. group_leader, parent_event,
  11320. NULL, NULL, -1);
  11321. if (IS_ERR(child_event))
  11322. return child_event;
  11323. get_ctx(child_ctx);
  11324. child_event->ctx = child_ctx;
  11325. pmu_ctx = find_get_pmu_context(child_event->pmu, child_ctx, child_event);
  11326. if (IS_ERR(pmu_ctx)) {
  11327. free_event(child_event);
  11328. return ERR_CAST(pmu_ctx);
  11329. }
  11330. child_event->pmu_ctx = pmu_ctx;
  11331. /*
  11332. * is_orphaned_event() and list_add_tail(&parent_event->child_list)
  11333. * must be under the same lock in order to serialize against
  11334. * perf_event_release_kernel(), such that either we must observe
  11335. * is_orphaned_event() or they will observe us on the child_list.
  11336. */
  11337. mutex_lock(&parent_event->child_mutex);
  11338. if (is_orphaned_event(parent_event) ||
  11339. !atomic_long_inc_not_zero(&parent_event->refcount)) {
  11340. mutex_unlock(&parent_event->child_mutex);
  11341. /* task_ctx_data is freed with child_ctx */
  11342. free_event(child_event);
  11343. return NULL;
  11344. }
  11345. /*
  11346. * Make the child state follow the state of the parent event,
  11347. * not its attr.disabled bit. We hold the parent's mutex,
  11348. * so we won't race with perf_event_{en, dis}able_family.
  11349. */
  11350. if (parent_state >= PERF_EVENT_STATE_INACTIVE)
  11351. child_event->state = PERF_EVENT_STATE_INACTIVE;
  11352. else
  11353. child_event->state = PERF_EVENT_STATE_OFF;
  11354. if (parent_event->attr.freq) {
  11355. u64 sample_period = parent_event->hw.sample_period;
  11356. struct hw_perf_event *hwc = &child_event->hw;
  11357. hwc->sample_period = sample_period;
  11358. hwc->last_period = sample_period;
  11359. local64_set(&hwc->period_left, sample_period);
  11360. }
  11361. child_event->overflow_handler = parent_event->overflow_handler;
  11362. child_event->overflow_handler_context
  11363. = parent_event->overflow_handler_context;
  11364. /*
  11365. * Precalculate sample_data sizes
  11366. */
  11367. perf_event__header_size(child_event);
  11368. perf_event__id_header_size(child_event);
  11369. /*
  11370. * Link it up in the child's context:
  11371. */
  11372. raw_spin_lock_irqsave(&child_ctx->lock, flags);
  11373. add_event_to_ctx(child_event, child_ctx);
  11374. child_event->attach_state |= PERF_ATTACH_CHILD;
  11375. raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
  11376. /*
  11377. * Link this into the parent event's child list
  11378. */
  11379. list_add_tail(&child_event->child_list, &parent_event->child_list);
  11380. mutex_unlock(&parent_event->child_mutex);
  11381. return child_event;
  11382. }
  11383. /*
  11384. * Inherits an event group.
  11385. *
  11386. * This will quietly suppress orphaned events; !inherit_event() is not an error.
  11387. * This matches with perf_event_release_kernel() removing all child events.
  11388. *
  11389. * Returns:
  11390. * - 0 on success
  11391. * - <0 on error
  11392. */
  11393. static int inherit_group(struct perf_event *parent_event,
  11394. struct task_struct *parent,
  11395. struct perf_event_context *parent_ctx,
  11396. struct task_struct *child,
  11397. struct perf_event_context *child_ctx)
  11398. {
  11399. struct perf_event *leader;
  11400. struct perf_event *sub;
  11401. struct perf_event *child_ctr;
  11402. leader = inherit_event(parent_event, parent, parent_ctx,
  11403. child, NULL, child_ctx);
  11404. if (IS_ERR(leader))
  11405. return PTR_ERR(leader);
  11406. /*
  11407. * @leader can be NULL here because of is_orphaned_event(). In this
  11408. * case inherit_event() will create individual events, similar to what
  11409. * perf_group_detach() would do anyway.
  11410. */
  11411. for_each_sibling_event(sub, parent_event) {
  11412. child_ctr = inherit_event(sub, parent, parent_ctx,
  11413. child, leader, child_ctx);
  11414. if (IS_ERR(child_ctr))
  11415. return PTR_ERR(child_ctr);
  11416. if (sub->aux_event == parent_event && child_ctr &&
  11417. !perf_get_aux_event(child_ctr, leader))
  11418. return -EINVAL;
  11419. }
  11420. if (leader)
  11421. leader->group_generation = parent_event->group_generation;
  11422. return 0;
  11423. }
  11424. /*
  11425. * Creates the child task context and tries to inherit the event-group.
  11426. *
  11427. * Clears @inherited_all on !attr.inherited or error. Note that we'll leave
  11428. * inherited_all set when we 'fail' to inherit an orphaned event; this is
  11429. * consistent with perf_event_release_kernel() removing all child events.
  11430. *
  11431. * Returns:
  11432. * - 0 on success
  11433. * - <0 on error
  11434. */
  11435. static int
  11436. inherit_task_group(struct perf_event *event, struct task_struct *parent,
  11437. struct perf_event_context *parent_ctx,
  11438. struct task_struct *child,
  11439. u64 clone_flags, int *inherited_all)
  11440. {
  11441. struct perf_event_context *child_ctx;
  11442. int ret;
  11443. if (!event->attr.inherit ||
  11444. (event->attr.inherit_thread && !(clone_flags & CLONE_THREAD)) ||
  11445. /* Do not inherit if sigtrap and signal handlers were cleared. */
  11446. (event->attr.sigtrap && (clone_flags & CLONE_CLEAR_SIGHAND))) {
  11447. *inherited_all = 0;
  11448. return 0;
  11449. }
  11450. child_ctx = child->perf_event_ctxp;
  11451. if (!child_ctx) {
  11452. /*
  11453. * This is executed from the parent task context, so
  11454. * inherit events that have been marked for cloning.
  11455. * First allocate and initialize a context for the
  11456. * child.
  11457. */
  11458. child_ctx = alloc_perf_context(child);
  11459. if (!child_ctx)
  11460. return -ENOMEM;
  11461. child->perf_event_ctxp = child_ctx;
  11462. }
  11463. ret = inherit_group(event, parent, parent_ctx, child, child_ctx);
  11464. if (ret)
  11465. *inherited_all = 0;
  11466. return ret;
  11467. }
  11468. /*
  11469. * Initialize the perf_event context in task_struct
  11470. */
  11471. static int perf_event_init_context(struct task_struct *child, u64 clone_flags)
  11472. {
  11473. struct perf_event_context *child_ctx, *parent_ctx;
  11474. struct perf_event_context *cloned_ctx;
  11475. struct perf_event *event;
  11476. struct task_struct *parent = current;
  11477. int inherited_all = 1;
  11478. unsigned long flags;
  11479. int ret = 0;
  11480. if (likely(!parent->perf_event_ctxp))
  11481. return 0;
  11482. /*
  11483. * If the parent's context is a clone, pin it so it won't get
  11484. * swapped under us.
  11485. */
  11486. parent_ctx = perf_pin_task_context(parent);
  11487. if (!parent_ctx)
  11488. return 0;
  11489. /*
  11490. * No need to check if parent_ctx != NULL here; since we saw
  11491. * it non-NULL earlier, the only reason for it to become NULL
  11492. * is if we exit, and since we're currently in the middle of
  11493. * a fork we can't be exiting at the same time.
  11494. */
  11495. /*
  11496. * Lock the parent list. No need to lock the child - not PID
  11497. * hashed yet and not running, so nobody can access it.
  11498. */
  11499. mutex_lock(&parent_ctx->mutex);
  11500. /*
  11501. * We dont have to disable NMIs - we are only looking at
  11502. * the list, not manipulating it:
  11503. */
  11504. perf_event_groups_for_each(event, &parent_ctx->pinned_groups) {
  11505. ret = inherit_task_group(event, parent, parent_ctx,
  11506. child, clone_flags, &inherited_all);
  11507. if (ret)
  11508. goto out_unlock;
  11509. }
  11510. /*
  11511. * We can't hold ctx->lock when iterating the ->flexible_group list due
  11512. * to allocations, but we need to prevent rotation because
  11513. * rotate_ctx() will change the list from interrupt context.
  11514. */
  11515. raw_spin_lock_irqsave(&parent_ctx->lock, flags);
  11516. parent_ctx->rotate_disable = 1;
  11517. raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
  11518. perf_event_groups_for_each(event, &parent_ctx->flexible_groups) {
  11519. ret = inherit_task_group(event, parent, parent_ctx,
  11520. child, clone_flags, &inherited_all);
  11521. if (ret)
  11522. goto out_unlock;
  11523. }
  11524. raw_spin_lock_irqsave(&parent_ctx->lock, flags);
  11525. parent_ctx->rotate_disable = 0;
  11526. child_ctx = child->perf_event_ctxp;
  11527. if (child_ctx && inherited_all) {
  11528. /*
  11529. * Mark the child context as a clone of the parent
  11530. * context, or of whatever the parent is a clone of.
  11531. *
  11532. * Note that if the parent is a clone, the holding of
  11533. * parent_ctx->lock avoids it from being uncloned.
  11534. */
  11535. cloned_ctx = parent_ctx->parent_ctx;
  11536. if (cloned_ctx) {
  11537. child_ctx->parent_ctx = cloned_ctx;
  11538. child_ctx->parent_gen = parent_ctx->parent_gen;
  11539. } else {
  11540. child_ctx->parent_ctx = parent_ctx;
  11541. child_ctx->parent_gen = parent_ctx->generation;
  11542. }
  11543. get_ctx(child_ctx->parent_ctx);
  11544. }
  11545. raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
  11546. out_unlock:
  11547. mutex_unlock(&parent_ctx->mutex);
  11548. perf_unpin_context(parent_ctx);
  11549. put_ctx(parent_ctx);
  11550. return ret;
  11551. }
  11552. /*
  11553. * Initialize the perf_event context in task_struct
  11554. */
  11555. int perf_event_init_task(struct task_struct *child, u64 clone_flags)
  11556. {
  11557. int ret;
  11558. memset(child->perf_recursion, 0, sizeof(child->perf_recursion));
  11559. child->perf_event_ctxp = NULL;
  11560. mutex_init(&child->perf_event_mutex);
  11561. INIT_LIST_HEAD(&child->perf_event_list);
  11562. ret = perf_event_init_context(child, clone_flags);
  11563. if (ret) {
  11564. perf_event_free_task(child);
  11565. return ret;
  11566. }
  11567. return 0;
  11568. }
  11569. static void __init perf_event_init_all_cpus(void)
  11570. {
  11571. struct swevent_htable *swhash;
  11572. struct perf_cpu_context *cpuctx;
  11573. int cpu;
  11574. zalloc_cpumask_var(&perf_online_mask, GFP_KERNEL);
  11575. zalloc_cpumask_var(&perf_online_core_mask, GFP_KERNEL);
  11576. zalloc_cpumask_var(&perf_online_die_mask, GFP_KERNEL);
  11577. zalloc_cpumask_var(&perf_online_cluster_mask, GFP_KERNEL);
  11578. zalloc_cpumask_var(&perf_online_pkg_mask, GFP_KERNEL);
  11579. zalloc_cpumask_var(&perf_online_sys_mask, GFP_KERNEL);
  11580. for_each_possible_cpu(cpu) {
  11581. swhash = &per_cpu(swevent_htable, cpu);
  11582. mutex_init(&swhash->hlist_mutex);
  11583. INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu));
  11584. raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu));
  11585. INIT_LIST_HEAD(&per_cpu(sched_cb_list, cpu));
  11586. cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
  11587. __perf_event_init_context(&cpuctx->ctx);
  11588. lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
  11589. lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
  11590. cpuctx->online = cpumask_test_cpu(cpu, perf_online_mask);
  11591. cpuctx->heap_size = ARRAY_SIZE(cpuctx->heap_default);
  11592. cpuctx->heap = cpuctx->heap_default;
  11593. }
  11594. }
  11595. static void perf_swevent_init_cpu(unsigned int cpu)
  11596. {
  11597. struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
  11598. mutex_lock(&swhash->hlist_mutex);
  11599. if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) {
  11600. struct swevent_hlist *hlist;
  11601. hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
  11602. WARN_ON(!hlist);
  11603. rcu_assign_pointer(swhash->swevent_hlist, hlist);
  11604. }
  11605. mutex_unlock(&swhash->hlist_mutex);
  11606. }
  11607. #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
  11608. static void __perf_event_exit_context(void *__info)
  11609. {
  11610. struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
  11611. struct perf_event_context *ctx = __info;
  11612. struct perf_event *event;
  11613. raw_spin_lock(&ctx->lock);
  11614. ctx_sched_out(ctx, NULL, EVENT_TIME);
  11615. list_for_each_entry(event, &ctx->event_list, event_entry)
  11616. __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP);
  11617. raw_spin_unlock(&ctx->lock);
  11618. }
  11619. static void perf_event_clear_cpumask(unsigned int cpu)
  11620. {
  11621. int target[PERF_PMU_MAX_SCOPE];
  11622. unsigned int scope;
  11623. struct pmu *pmu;
  11624. cpumask_clear_cpu(cpu, perf_online_mask);
  11625. for (scope = PERF_PMU_SCOPE_NONE + 1; scope < PERF_PMU_MAX_SCOPE; scope++) {
  11626. const struct cpumask *cpumask = perf_scope_cpu_topology_cpumask(scope, cpu);
  11627. struct cpumask *pmu_cpumask = perf_scope_cpumask(scope);
  11628. target[scope] = -1;
  11629. if (WARN_ON_ONCE(!pmu_cpumask || !cpumask))
  11630. continue;
  11631. if (!cpumask_test_and_clear_cpu(cpu, pmu_cpumask))
  11632. continue;
  11633. target[scope] = cpumask_any_but(cpumask, cpu);
  11634. if (target[scope] < nr_cpu_ids)
  11635. cpumask_set_cpu(target[scope], pmu_cpumask);
  11636. }
  11637. /* migrate */
  11638. list_for_each_entry(pmu, &pmus, entry) {
  11639. if (pmu->scope == PERF_PMU_SCOPE_NONE ||
  11640. WARN_ON_ONCE(pmu->scope >= PERF_PMU_MAX_SCOPE))
  11641. continue;
  11642. if (target[pmu->scope] >= 0 && target[pmu->scope] < nr_cpu_ids)
  11643. perf_pmu_migrate_context(pmu, cpu, target[pmu->scope]);
  11644. }
  11645. }
  11646. static void perf_event_exit_cpu_context(int cpu)
  11647. {
  11648. struct perf_cpu_context *cpuctx;
  11649. struct perf_event_context *ctx;
  11650. // XXX simplify cpuctx->online
  11651. mutex_lock(&pmus_lock);
  11652. /*
  11653. * Clear the cpumasks, and migrate to other CPUs if possible.
  11654. * Must be invoked before the __perf_event_exit_context.
  11655. */
  11656. perf_event_clear_cpumask(cpu);
  11657. cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
  11658. ctx = &cpuctx->ctx;
  11659. mutex_lock(&ctx->mutex);
  11660. smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
  11661. cpuctx->online = 0;
  11662. mutex_unlock(&ctx->mutex);
  11663. mutex_unlock(&pmus_lock);
  11664. }
  11665. #else
  11666. static void perf_event_exit_cpu_context(int cpu) { }
  11667. #endif
  11668. static void perf_event_setup_cpumask(unsigned int cpu)
  11669. {
  11670. struct cpumask *pmu_cpumask;
  11671. unsigned int scope;
  11672. /*
  11673. * Early boot stage, the cpumask hasn't been set yet.
  11674. * The perf_online_<domain>_masks includes the first CPU of each domain.
  11675. * Always unconditionally set the boot CPU for the perf_online_<domain>_masks.
  11676. */
  11677. if (cpumask_empty(perf_online_mask)) {
  11678. for (scope = PERF_PMU_SCOPE_NONE + 1; scope < PERF_PMU_MAX_SCOPE; scope++) {
  11679. pmu_cpumask = perf_scope_cpumask(scope);
  11680. if (WARN_ON_ONCE(!pmu_cpumask))
  11681. continue;
  11682. cpumask_set_cpu(cpu, pmu_cpumask);
  11683. }
  11684. goto end;
  11685. }
  11686. for (scope = PERF_PMU_SCOPE_NONE + 1; scope < PERF_PMU_MAX_SCOPE; scope++) {
  11687. const struct cpumask *cpumask = perf_scope_cpu_topology_cpumask(scope, cpu);
  11688. pmu_cpumask = perf_scope_cpumask(scope);
  11689. if (WARN_ON_ONCE(!pmu_cpumask || !cpumask))
  11690. continue;
  11691. if (!cpumask_empty(cpumask) &&
  11692. cpumask_any_and(pmu_cpumask, cpumask) >= nr_cpu_ids)
  11693. cpumask_set_cpu(cpu, pmu_cpumask);
  11694. }
  11695. end:
  11696. cpumask_set_cpu(cpu, perf_online_mask);
  11697. }
  11698. int perf_event_init_cpu(unsigned int cpu)
  11699. {
  11700. struct perf_cpu_context *cpuctx;
  11701. struct perf_event_context *ctx;
  11702. perf_swevent_init_cpu(cpu);
  11703. mutex_lock(&pmus_lock);
  11704. perf_event_setup_cpumask(cpu);
  11705. cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
  11706. ctx = &cpuctx->ctx;
  11707. mutex_lock(&ctx->mutex);
  11708. cpuctx->online = 1;
  11709. mutex_unlock(&ctx->mutex);
  11710. mutex_unlock(&pmus_lock);
  11711. return 0;
  11712. }
  11713. int perf_event_exit_cpu(unsigned int cpu)
  11714. {
  11715. perf_event_exit_cpu_context(cpu);
  11716. return 0;
  11717. }
  11718. static int
  11719. perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
  11720. {
  11721. int cpu;
  11722. for_each_online_cpu(cpu)
  11723. perf_event_exit_cpu(cpu);
  11724. return NOTIFY_OK;
  11725. }
  11726. /*
  11727. * Run the perf reboot notifier at the very last possible moment so that
  11728. * the generic watchdog code runs as long as possible.
  11729. */
  11730. static struct notifier_block perf_reboot_notifier = {
  11731. .notifier_call = perf_reboot,
  11732. .priority = INT_MIN,
  11733. };
  11734. void __init perf_event_init(void)
  11735. {
  11736. int ret;
  11737. idr_init(&pmu_idr);
  11738. perf_event_init_all_cpus();
  11739. init_srcu_struct(&pmus_srcu);
  11740. perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
  11741. perf_pmu_register(&perf_cpu_clock, "cpu_clock", -1);
  11742. perf_pmu_register(&perf_task_clock, "task_clock", -1);
  11743. perf_tp_register();
  11744. perf_event_init_cpu(smp_processor_id());
  11745. register_reboot_notifier(&perf_reboot_notifier);
  11746. ret = init_hw_breakpoint();
  11747. WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
  11748. perf_event_cache = KMEM_CACHE(perf_event, SLAB_PANIC);
  11749. /*
  11750. * Build time assertion that we keep the data_head at the intended
  11751. * location. IOW, validation we got the __reserved[] size right.
  11752. */
  11753. BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
  11754. != 1024);
  11755. }
  11756. ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
  11757. char *page)
  11758. {
  11759. struct perf_pmu_events_attr *pmu_attr =
  11760. container_of(attr, struct perf_pmu_events_attr, attr);
  11761. if (pmu_attr->event_str)
  11762. return sprintf(page, "%s\n", pmu_attr->event_str);
  11763. return 0;
  11764. }
  11765. EXPORT_SYMBOL_GPL(perf_event_sysfs_show);
  11766. static int __init perf_event_sysfs_init(void)
  11767. {
  11768. struct pmu *pmu;
  11769. int ret;
  11770. mutex_lock(&pmus_lock);
  11771. ret = bus_register(&pmu_bus);
  11772. if (ret)
  11773. goto unlock;
  11774. list_for_each_entry(pmu, &pmus, entry) {
  11775. if (pmu->dev)
  11776. continue;
  11777. ret = pmu_dev_alloc(pmu);
  11778. WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
  11779. }
  11780. pmu_bus_running = 1;
  11781. ret = 0;
  11782. unlock:
  11783. mutex_unlock(&pmus_lock);
  11784. return ret;
  11785. }
  11786. device_initcall(perf_event_sysfs_init);
  11787. #ifdef CONFIG_CGROUP_PERF
  11788. static struct cgroup_subsys_state *
  11789. perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
  11790. {
  11791. struct perf_cgroup *jc;
  11792. jc = kzalloc(sizeof(*jc), GFP_KERNEL);
  11793. if (!jc)
  11794. return ERR_PTR(-ENOMEM);
  11795. jc->info = alloc_percpu(struct perf_cgroup_info);
  11796. if (!jc->info) {
  11797. kfree(jc);
  11798. return ERR_PTR(-ENOMEM);
  11799. }
  11800. return &jc->css;
  11801. }
  11802. static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
  11803. {
  11804. struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
  11805. free_percpu(jc->info);
  11806. kfree(jc);
  11807. }
  11808. static int perf_cgroup_css_online(struct cgroup_subsys_state *css)
  11809. {
  11810. perf_event_cgroup(css->cgroup);
  11811. return 0;
  11812. }
  11813. static int __perf_cgroup_move(void *info)
  11814. {
  11815. struct task_struct *task = info;
  11816. preempt_disable();
  11817. perf_cgroup_switch(task);
  11818. preempt_enable();
  11819. return 0;
  11820. }
  11821. static void perf_cgroup_attach(struct cgroup_taskset *tset)
  11822. {
  11823. struct task_struct *task;
  11824. struct cgroup_subsys_state *css;
  11825. cgroup_taskset_for_each(task, css, tset)
  11826. task_function_call(task, __perf_cgroup_move, task);
  11827. }
  11828. struct cgroup_subsys perf_event_cgrp_subsys = {
  11829. .css_alloc = perf_cgroup_css_alloc,
  11830. .css_free = perf_cgroup_css_free,
  11831. .css_online = perf_cgroup_css_online,
  11832. .attach = perf_cgroup_attach,
  11833. /*
  11834. * Implicitly enable on dfl hierarchy so that perf events can
  11835. * always be filtered by cgroup2 path as long as perf_event
  11836. * controller is not mounted on a legacy hierarchy.
  11837. */
  11838. .implicit_on_dfl = true,
  11839. .threaded = true,
  11840. };
  11841. #endif /* CONFIG_CGROUP_PERF */
  11842. DEFINE_STATIC_CALL_RET0(perf_snapshot_branch_stack, perf_snapshot_branch_stack_t);