core.c 280 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838
  1. /*
  2. * Performance events core code:
  3. *
  4. * Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de>
  5. * Copyright (C) 2008-2011 Red Hat, Inc., Ingo Molnar
  6. * Copyright (C) 2008-2011 Red Hat, Inc., Peter Zijlstra
  7. * Copyright © 2009 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
  8. *
  9. * For licensing details see kernel-base/COPYING
  10. */
  11. #include <linux/fs.h>
  12. #include <linux/mm.h>
  13. #include <linux/cpu.h>
  14. #include <linux/smp.h>
  15. #include <linux/idr.h>
  16. #include <linux/file.h>
  17. #include <linux/poll.h>
  18. #include <linux/slab.h>
  19. #include <linux/hash.h>
  20. #include <linux/tick.h>
  21. #include <linux/sysfs.h>
  22. #include <linux/dcache.h>
  23. #include <linux/percpu.h>
  24. #include <linux/ptrace.h>
  25. #include <linux/reboot.h>
  26. #include <linux/vmstat.h>
  27. #include <linux/device.h>
  28. #include <linux/export.h>
  29. #include <linux/vmalloc.h>
  30. #include <linux/hardirq.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 "internal.h"
  53. #include <asm/irq_regs.h>
  54. typedef int (*remote_function_f)(void *);
  55. struct remote_function_call {
  56. struct task_struct *p;
  57. remote_function_f func;
  58. void *info;
  59. int ret;
  60. };
  61. static void remote_function(void *data)
  62. {
  63. struct remote_function_call *tfc = data;
  64. struct task_struct *p = tfc->p;
  65. if (p) {
  66. /* -EAGAIN */
  67. if (task_cpu(p) != smp_processor_id())
  68. return;
  69. /*
  70. * Now that we're on right CPU with IRQs disabled, we can test
  71. * if we hit the right task without races.
  72. */
  73. tfc->ret = -ESRCH; /* No such (running) process */
  74. if (p != current)
  75. return;
  76. }
  77. tfc->ret = tfc->func(tfc->info);
  78. }
  79. /**
  80. * task_function_call - call a function on the cpu on which a task runs
  81. * @p: the task to evaluate
  82. * @func: the function to be called
  83. * @info: the function call argument
  84. *
  85. * Calls the function @func when the task is currently running. This might
  86. * be on the current CPU, which just calls the function directly
  87. *
  88. * returns: @func return value, or
  89. * -ESRCH - when the process isn't running
  90. * -EAGAIN - when the process moved away
  91. */
  92. static int
  93. task_function_call(struct task_struct *p, remote_function_f func, void *info)
  94. {
  95. struct remote_function_call data = {
  96. .p = p,
  97. .func = func,
  98. .info = info,
  99. .ret = -EAGAIN,
  100. };
  101. int ret;
  102. do {
  103. ret = smp_call_function_single(task_cpu(p), remote_function, &data, 1);
  104. if (!ret)
  105. ret = data.ret;
  106. } while (ret == -EAGAIN);
  107. return ret;
  108. }
  109. /**
  110. * cpu_function_call - call a function on the cpu
  111. * @func: the function to be called
  112. * @info: the function call argument
  113. *
  114. * Calls the function @func on the remote cpu.
  115. *
  116. * returns: @func return value or -ENXIO when the cpu is offline
  117. */
  118. static int cpu_function_call(int cpu, remote_function_f func, void *info)
  119. {
  120. struct remote_function_call data = {
  121. .p = NULL,
  122. .func = func,
  123. .info = info,
  124. .ret = -ENXIO, /* No such CPU */
  125. };
  126. smp_call_function_single(cpu, remote_function, &data, 1);
  127. return data.ret;
  128. }
  129. static inline struct perf_cpu_context *
  130. __get_cpu_context(struct perf_event_context *ctx)
  131. {
  132. return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
  133. }
  134. static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
  135. struct perf_event_context *ctx)
  136. {
  137. raw_spin_lock(&cpuctx->ctx.lock);
  138. if (ctx)
  139. raw_spin_lock(&ctx->lock);
  140. }
  141. static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
  142. struct perf_event_context *ctx)
  143. {
  144. if (ctx)
  145. raw_spin_unlock(&ctx->lock);
  146. raw_spin_unlock(&cpuctx->ctx.lock);
  147. }
  148. #define TASK_TOMBSTONE ((void *)-1L)
  149. static bool is_kernel_event(struct perf_event *event)
  150. {
  151. return READ_ONCE(event->owner) == TASK_TOMBSTONE;
  152. }
  153. /*
  154. * On task ctx scheduling...
  155. *
  156. * When !ctx->nr_events a task context will not be scheduled. This means
  157. * we can disable the scheduler hooks (for performance) without leaving
  158. * pending task ctx state.
  159. *
  160. * This however results in two special cases:
  161. *
  162. * - removing the last event from a task ctx; this is relatively straight
  163. * forward and is done in __perf_remove_from_context.
  164. *
  165. * - adding the first event to a task ctx; this is tricky because we cannot
  166. * rely on ctx->is_active and therefore cannot use event_function_call().
  167. * See perf_install_in_context().
  168. *
  169. * If ctx->nr_events, then ctx->is_active and cpuctx->task_ctx are set.
  170. */
  171. typedef void (*event_f)(struct perf_event *, struct perf_cpu_context *,
  172. struct perf_event_context *, void *);
  173. struct event_function_struct {
  174. struct perf_event *event;
  175. event_f func;
  176. void *data;
  177. };
  178. static int event_function(void *info)
  179. {
  180. struct event_function_struct *efs = info;
  181. struct perf_event *event = efs->event;
  182. struct perf_event_context *ctx = event->ctx;
  183. struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
  184. struct perf_event_context *task_ctx = cpuctx->task_ctx;
  185. int ret = 0;
  186. lockdep_assert_irqs_disabled();
  187. perf_ctx_lock(cpuctx, task_ctx);
  188. /*
  189. * Since we do the IPI call without holding ctx->lock things can have
  190. * changed, double check we hit the task we set out to hit.
  191. */
  192. if (ctx->task) {
  193. if (ctx->task != current) {
  194. ret = -ESRCH;
  195. goto unlock;
  196. }
  197. /*
  198. * We only use event_function_call() on established contexts,
  199. * and event_function() is only ever called when active (or
  200. * rather, we'll have bailed in task_function_call() or the
  201. * above ctx->task != current test), therefore we must have
  202. * ctx->is_active here.
  203. */
  204. WARN_ON_ONCE(!ctx->is_active);
  205. /*
  206. * And since we have ctx->is_active, cpuctx->task_ctx must
  207. * match.
  208. */
  209. WARN_ON_ONCE(task_ctx != ctx);
  210. } else {
  211. WARN_ON_ONCE(&cpuctx->ctx != ctx);
  212. }
  213. efs->func(event, cpuctx, ctx, efs->data);
  214. unlock:
  215. perf_ctx_unlock(cpuctx, task_ctx);
  216. return ret;
  217. }
  218. static void event_function_call(struct perf_event *event, event_f func, void *data)
  219. {
  220. struct perf_event_context *ctx = event->ctx;
  221. struct task_struct *task = READ_ONCE(ctx->task); /* verified in event_function */
  222. struct event_function_struct efs = {
  223. .event = event,
  224. .func = func,
  225. .data = data,
  226. };
  227. if (!event->parent) {
  228. /*
  229. * If this is a !child event, we must hold ctx::mutex to
  230. * stabilize the the event->ctx relation. See
  231. * perf_event_ctx_lock().
  232. */
  233. lockdep_assert_held(&ctx->mutex);
  234. }
  235. if (!task) {
  236. cpu_function_call(event->cpu, event_function, &efs);
  237. return;
  238. }
  239. if (task == TASK_TOMBSTONE)
  240. return;
  241. again:
  242. if (!task_function_call(task, event_function, &efs))
  243. return;
  244. raw_spin_lock_irq(&ctx->lock);
  245. /*
  246. * Reload the task pointer, it might have been changed by
  247. * a concurrent perf_event_context_sched_out().
  248. */
  249. task = ctx->task;
  250. if (task == TASK_TOMBSTONE) {
  251. raw_spin_unlock_irq(&ctx->lock);
  252. return;
  253. }
  254. if (ctx->is_active) {
  255. raw_spin_unlock_irq(&ctx->lock);
  256. goto again;
  257. }
  258. func(event, NULL, ctx, data);
  259. raw_spin_unlock_irq(&ctx->lock);
  260. }
  261. /*
  262. * Similar to event_function_call() + event_function(), but hard assumes IRQs
  263. * are already disabled and we're on the right CPU.
  264. */
  265. static void event_function_local(struct perf_event *event, event_f func, void *data)
  266. {
  267. struct perf_event_context *ctx = event->ctx;
  268. struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
  269. struct task_struct *task = READ_ONCE(ctx->task);
  270. struct perf_event_context *task_ctx = NULL;
  271. lockdep_assert_irqs_disabled();
  272. if (task) {
  273. if (task == TASK_TOMBSTONE)
  274. return;
  275. task_ctx = ctx;
  276. }
  277. perf_ctx_lock(cpuctx, task_ctx);
  278. task = ctx->task;
  279. if (task == TASK_TOMBSTONE)
  280. goto unlock;
  281. if (task) {
  282. /*
  283. * We must be either inactive or active and the right task,
  284. * otherwise we're screwed, since we cannot IPI to somewhere
  285. * else.
  286. */
  287. if (ctx->is_active) {
  288. if (WARN_ON_ONCE(task != current))
  289. goto unlock;
  290. if (WARN_ON_ONCE(cpuctx->task_ctx != ctx))
  291. goto unlock;
  292. }
  293. } else {
  294. WARN_ON_ONCE(&cpuctx->ctx != ctx);
  295. }
  296. func(event, cpuctx, ctx, data);
  297. unlock:
  298. perf_ctx_unlock(cpuctx, task_ctx);
  299. }
  300. #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
  301. PERF_FLAG_FD_OUTPUT |\
  302. PERF_FLAG_PID_CGROUP |\
  303. PERF_FLAG_FD_CLOEXEC)
  304. /*
  305. * branch priv levels that need permission checks
  306. */
  307. #define PERF_SAMPLE_BRANCH_PERM_PLM \
  308. (PERF_SAMPLE_BRANCH_KERNEL |\
  309. PERF_SAMPLE_BRANCH_HV)
  310. enum event_type_t {
  311. EVENT_FLEXIBLE = 0x1,
  312. EVENT_PINNED = 0x2,
  313. EVENT_TIME = 0x4,
  314. /* see ctx_resched() for details */
  315. EVENT_CPU = 0x8,
  316. EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
  317. };
  318. /*
  319. * perf_sched_events : >0 events exist
  320. * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
  321. */
  322. static void perf_sched_delayed(struct work_struct *work);
  323. DEFINE_STATIC_KEY_FALSE(perf_sched_events);
  324. static DECLARE_DELAYED_WORK(perf_sched_work, perf_sched_delayed);
  325. static DEFINE_MUTEX(perf_sched_mutex);
  326. static atomic_t perf_sched_count;
  327. static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
  328. static DEFINE_PER_CPU(int, perf_sched_cb_usages);
  329. static DEFINE_PER_CPU(struct pmu_event_list, pmu_sb_events);
  330. static atomic_t nr_mmap_events __read_mostly;
  331. static atomic_t nr_comm_events __read_mostly;
  332. static atomic_t nr_namespaces_events __read_mostly;
  333. static atomic_t nr_task_events __read_mostly;
  334. static atomic_t nr_freq_events __read_mostly;
  335. static atomic_t nr_switch_events __read_mostly;
  336. static LIST_HEAD(pmus);
  337. static DEFINE_MUTEX(pmus_lock);
  338. static struct srcu_struct pmus_srcu;
  339. static cpumask_var_t perf_online_mask;
  340. /*
  341. * perf event paranoia level:
  342. * -1 - not paranoid at all
  343. * 0 - disallow raw tracepoint access for unpriv
  344. * 1 - disallow cpu events for unpriv
  345. * 2 - disallow kernel profiling for unpriv
  346. */
  347. int sysctl_perf_event_paranoid __read_mostly = 2;
  348. /* Minimum for 512 kiB + 1 user control page */
  349. int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
  350. /*
  351. * max perf event sample rate
  352. */
  353. #define DEFAULT_MAX_SAMPLE_RATE 100000
  354. #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
  355. #define DEFAULT_CPU_TIME_MAX_PERCENT 25
  356. int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
  357. static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
  358. static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
  359. static int perf_sample_allowed_ns __read_mostly =
  360. DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
  361. static void update_perf_cpu_limits(void)
  362. {
  363. u64 tmp = perf_sample_period_ns;
  364. tmp *= sysctl_perf_cpu_time_max_percent;
  365. tmp = div_u64(tmp, 100);
  366. if (!tmp)
  367. tmp = 1;
  368. WRITE_ONCE(perf_sample_allowed_ns, tmp);
  369. }
  370. static bool perf_rotate_context(struct perf_cpu_context *cpuctx);
  371. int perf_proc_update_handler(struct ctl_table *table, int write,
  372. void __user *buffer, size_t *lenp,
  373. loff_t *ppos)
  374. {
  375. int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
  376. if (ret || !write)
  377. return ret;
  378. /*
  379. * If throttling is disabled don't allow the write:
  380. */
  381. if (sysctl_perf_cpu_time_max_percent == 100 ||
  382. sysctl_perf_cpu_time_max_percent == 0)
  383. return -EINVAL;
  384. max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
  385. perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
  386. update_perf_cpu_limits();
  387. return 0;
  388. }
  389. int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
  390. int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
  391. void __user *buffer, size_t *lenp,
  392. loff_t *ppos)
  393. {
  394. int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
  395. if (ret || !write)
  396. return ret;
  397. if (sysctl_perf_cpu_time_max_percent == 100 ||
  398. sysctl_perf_cpu_time_max_percent == 0) {
  399. printk(KERN_WARNING
  400. "perf: Dynamic interrupt throttling disabled, can hang your system!\n");
  401. WRITE_ONCE(perf_sample_allowed_ns, 0);
  402. } else {
  403. update_perf_cpu_limits();
  404. }
  405. return 0;
  406. }
  407. /*
  408. * perf samples are done in some very critical code paths (NMIs).
  409. * If they take too much CPU time, the system can lock up and not
  410. * get any real work done. This will drop the sample rate when
  411. * we detect that events are taking too long.
  412. */
  413. #define NR_ACCUMULATED_SAMPLES 128
  414. static DEFINE_PER_CPU(u64, running_sample_length);
  415. static u64 __report_avg;
  416. static u64 __report_allowed;
  417. static void perf_duration_warn(struct irq_work *w)
  418. {
  419. printk_ratelimited(KERN_INFO
  420. "perf: interrupt took too long (%lld > %lld), lowering "
  421. "kernel.perf_event_max_sample_rate to %d\n",
  422. __report_avg, __report_allowed,
  423. sysctl_perf_event_sample_rate);
  424. }
  425. static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
  426. void perf_sample_event_took(u64 sample_len_ns)
  427. {
  428. u64 max_len = READ_ONCE(perf_sample_allowed_ns);
  429. u64 running_len;
  430. u64 avg_len;
  431. u32 max;
  432. if (max_len == 0)
  433. return;
  434. /* Decay the counter by 1 average sample. */
  435. running_len = __this_cpu_read(running_sample_length);
  436. running_len -= running_len/NR_ACCUMULATED_SAMPLES;
  437. running_len += sample_len_ns;
  438. __this_cpu_write(running_sample_length, running_len);
  439. /*
  440. * Note: this will be biased artifically low until we have
  441. * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
  442. * from having to maintain a count.
  443. */
  444. avg_len = running_len/NR_ACCUMULATED_SAMPLES;
  445. if (avg_len <= max_len)
  446. return;
  447. __report_avg = avg_len;
  448. __report_allowed = max_len;
  449. /*
  450. * Compute a throttle threshold 25% below the current duration.
  451. */
  452. avg_len += avg_len / 4;
  453. max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent;
  454. if (avg_len < max)
  455. max /= (u32)avg_len;
  456. else
  457. max = 1;
  458. WRITE_ONCE(perf_sample_allowed_ns, avg_len);
  459. WRITE_ONCE(max_samples_per_tick, max);
  460. sysctl_perf_event_sample_rate = max * HZ;
  461. perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
  462. if (!irq_work_queue(&perf_duration_work)) {
  463. early_printk("perf: interrupt took too long (%lld > %lld), lowering "
  464. "kernel.perf_event_max_sample_rate to %d\n",
  465. __report_avg, __report_allowed,
  466. sysctl_perf_event_sample_rate);
  467. }
  468. }
  469. static atomic64_t perf_event_id;
  470. static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
  471. enum event_type_t event_type);
  472. static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
  473. enum event_type_t event_type,
  474. struct task_struct *task);
  475. static void update_context_time(struct perf_event_context *ctx);
  476. static u64 perf_event_time(struct perf_event *event);
  477. void __weak perf_event_print_debug(void) { }
  478. extern __weak const char *perf_pmu_name(void)
  479. {
  480. return "pmu";
  481. }
  482. static inline u64 perf_clock(void)
  483. {
  484. return local_clock();
  485. }
  486. static inline u64 perf_event_clock(struct perf_event *event)
  487. {
  488. return event->clock();
  489. }
  490. /*
  491. * State based event timekeeping...
  492. *
  493. * The basic idea is to use event->state to determine which (if any) time
  494. * fields to increment with the current delta. This means we only need to
  495. * update timestamps when we change state or when they are explicitly requested
  496. * (read).
  497. *
  498. * Event groups make things a little more complicated, but not terribly so. The
  499. * rules for a group are that if the group leader is OFF the entire group is
  500. * OFF, irrespecive of what the group member states are. This results in
  501. * __perf_effective_state().
  502. *
  503. * A futher ramification is that when a group leader flips between OFF and
  504. * !OFF, we need to update all group member times.
  505. *
  506. *
  507. * NOTE: perf_event_time() is based on the (cgroup) context time, and thus we
  508. * need to make sure the relevant context time is updated before we try and
  509. * update our timestamps.
  510. */
  511. static __always_inline enum perf_event_state
  512. __perf_effective_state(struct perf_event *event)
  513. {
  514. struct perf_event *leader = event->group_leader;
  515. if (leader->state <= PERF_EVENT_STATE_OFF)
  516. return leader->state;
  517. return event->state;
  518. }
  519. static __always_inline void
  520. __perf_update_times(struct perf_event *event, u64 now, u64 *enabled, u64 *running)
  521. {
  522. enum perf_event_state state = __perf_effective_state(event);
  523. u64 delta = now - event->tstamp;
  524. *enabled = event->total_time_enabled;
  525. if (state >= PERF_EVENT_STATE_INACTIVE)
  526. *enabled += delta;
  527. *running = event->total_time_running;
  528. if (state >= PERF_EVENT_STATE_ACTIVE)
  529. *running += delta;
  530. }
  531. static void perf_event_update_time(struct perf_event *event)
  532. {
  533. u64 now = perf_event_time(event);
  534. __perf_update_times(event, now, &event->total_time_enabled,
  535. &event->total_time_running);
  536. event->tstamp = now;
  537. }
  538. static void perf_event_update_sibling_time(struct perf_event *leader)
  539. {
  540. struct perf_event *sibling;
  541. for_each_sibling_event(sibling, leader)
  542. perf_event_update_time(sibling);
  543. }
  544. static void
  545. perf_event_set_state(struct perf_event *event, enum perf_event_state state)
  546. {
  547. if (event->state == state)
  548. return;
  549. perf_event_update_time(event);
  550. /*
  551. * If a group leader gets enabled/disabled all its siblings
  552. * are affected too.
  553. */
  554. if ((event->state < 0) ^ (state < 0))
  555. perf_event_update_sibling_time(event);
  556. WRITE_ONCE(event->state, state);
  557. }
  558. #ifdef CONFIG_CGROUP_PERF
  559. static inline bool
  560. perf_cgroup_match(struct perf_event *event)
  561. {
  562. struct perf_event_context *ctx = event->ctx;
  563. struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
  564. /* @event doesn't care about cgroup */
  565. if (!event->cgrp)
  566. return true;
  567. /* wants specific cgroup scope but @cpuctx isn't associated with any */
  568. if (!cpuctx->cgrp)
  569. return false;
  570. /*
  571. * Cgroup scoping is recursive. An event enabled for a cgroup is
  572. * also enabled for all its descendant cgroups. If @cpuctx's
  573. * cgroup is a descendant of @event's (the test covers identity
  574. * case), it's a match.
  575. */
  576. return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
  577. event->cgrp->css.cgroup);
  578. }
  579. static inline void perf_detach_cgroup(struct perf_event *event)
  580. {
  581. css_put(&event->cgrp->css);
  582. event->cgrp = NULL;
  583. }
  584. static inline int is_cgroup_event(struct perf_event *event)
  585. {
  586. return event->cgrp != NULL;
  587. }
  588. static inline u64 perf_cgroup_event_time(struct perf_event *event)
  589. {
  590. struct perf_cgroup_info *t;
  591. t = per_cpu_ptr(event->cgrp->info, event->cpu);
  592. return t->time;
  593. }
  594. static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
  595. {
  596. struct perf_cgroup_info *info;
  597. u64 now;
  598. now = perf_clock();
  599. info = this_cpu_ptr(cgrp->info);
  600. info->time += now - info->timestamp;
  601. info->timestamp = now;
  602. }
  603. static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
  604. {
  605. struct perf_cgroup *cgrp = cpuctx->cgrp;
  606. struct cgroup_subsys_state *css;
  607. if (cgrp) {
  608. for (css = &cgrp->css; css; css = css->parent) {
  609. cgrp = container_of(css, struct perf_cgroup, css);
  610. __update_cgrp_time(cgrp);
  611. }
  612. }
  613. }
  614. static inline void update_cgrp_time_from_event(struct perf_event *event)
  615. {
  616. struct perf_cgroup *cgrp;
  617. /*
  618. * ensure we access cgroup data only when needed and
  619. * when we know the cgroup is pinned (css_get)
  620. */
  621. if (!is_cgroup_event(event))
  622. return;
  623. cgrp = perf_cgroup_from_task(current, event->ctx);
  624. /*
  625. * Do not update time when cgroup is not active
  626. */
  627. if (cgroup_is_descendant(cgrp->css.cgroup, event->cgrp->css.cgroup))
  628. __update_cgrp_time(event->cgrp);
  629. }
  630. static inline void
  631. perf_cgroup_set_timestamp(struct task_struct *task,
  632. struct perf_event_context *ctx)
  633. {
  634. struct perf_cgroup *cgrp;
  635. struct perf_cgroup_info *info;
  636. struct cgroup_subsys_state *css;
  637. /*
  638. * ctx->lock held by caller
  639. * ensure we do not access cgroup data
  640. * unless we have the cgroup pinned (css_get)
  641. */
  642. if (!task || !ctx->nr_cgroups)
  643. return;
  644. cgrp = perf_cgroup_from_task(task, ctx);
  645. for (css = &cgrp->css; css; css = css->parent) {
  646. cgrp = container_of(css, struct perf_cgroup, css);
  647. info = this_cpu_ptr(cgrp->info);
  648. info->timestamp = ctx->timestamp;
  649. }
  650. }
  651. static DEFINE_PER_CPU(struct list_head, cgrp_cpuctx_list);
  652. #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
  653. #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
  654. /*
  655. * reschedule events based on the cgroup constraint of task.
  656. *
  657. * mode SWOUT : schedule out everything
  658. * mode SWIN : schedule in based on cgroup for next
  659. */
  660. static void perf_cgroup_switch(struct task_struct *task, int mode)
  661. {
  662. struct perf_cpu_context *cpuctx;
  663. struct list_head *list;
  664. unsigned long flags;
  665. /*
  666. * Disable interrupts and preemption to avoid this CPU's
  667. * cgrp_cpuctx_entry to change under us.
  668. */
  669. local_irq_save(flags);
  670. list = this_cpu_ptr(&cgrp_cpuctx_list);
  671. list_for_each_entry(cpuctx, list, cgrp_cpuctx_entry) {
  672. WARN_ON_ONCE(cpuctx->ctx.nr_cgroups == 0);
  673. perf_ctx_lock(cpuctx, cpuctx->task_ctx);
  674. perf_pmu_disable(cpuctx->ctx.pmu);
  675. if (mode & PERF_CGROUP_SWOUT) {
  676. cpu_ctx_sched_out(cpuctx, EVENT_ALL);
  677. /*
  678. * must not be done before ctxswout due
  679. * to event_filter_match() in event_sched_out()
  680. */
  681. cpuctx->cgrp = NULL;
  682. }
  683. if (mode & PERF_CGROUP_SWIN) {
  684. WARN_ON_ONCE(cpuctx->cgrp);
  685. /*
  686. * set cgrp before ctxsw in to allow
  687. * event_filter_match() to not have to pass
  688. * task around
  689. * we pass the cpuctx->ctx to perf_cgroup_from_task()
  690. * because cgorup events are only per-cpu
  691. */
  692. cpuctx->cgrp = perf_cgroup_from_task(task,
  693. &cpuctx->ctx);
  694. cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
  695. }
  696. perf_pmu_enable(cpuctx->ctx.pmu);
  697. perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
  698. }
  699. local_irq_restore(flags);
  700. }
  701. static inline void perf_cgroup_sched_out(struct task_struct *task,
  702. struct task_struct *next)
  703. {
  704. struct perf_cgroup *cgrp1;
  705. struct perf_cgroup *cgrp2 = NULL;
  706. rcu_read_lock();
  707. /*
  708. * we come here when we know perf_cgroup_events > 0
  709. * we do not need to pass the ctx here because we know
  710. * we are holding the rcu lock
  711. */
  712. cgrp1 = perf_cgroup_from_task(task, NULL);
  713. cgrp2 = perf_cgroup_from_task(next, NULL);
  714. /*
  715. * only schedule out current cgroup events if we know
  716. * that we are switching to a different cgroup. Otherwise,
  717. * do no touch the cgroup events.
  718. */
  719. if (cgrp1 != cgrp2)
  720. perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
  721. rcu_read_unlock();
  722. }
  723. static inline void perf_cgroup_sched_in(struct task_struct *prev,
  724. struct task_struct *task)
  725. {
  726. struct perf_cgroup *cgrp1;
  727. struct perf_cgroup *cgrp2 = NULL;
  728. rcu_read_lock();
  729. /*
  730. * we come here when we know perf_cgroup_events > 0
  731. * we do not need to pass the ctx here because we know
  732. * we are holding the rcu lock
  733. */
  734. cgrp1 = perf_cgroup_from_task(task, NULL);
  735. cgrp2 = perf_cgroup_from_task(prev, NULL);
  736. /*
  737. * only need to schedule in cgroup events if we are changing
  738. * cgroup during ctxsw. Cgroup events were not scheduled
  739. * out of ctxsw out if that was not the case.
  740. */
  741. if (cgrp1 != cgrp2)
  742. perf_cgroup_switch(task, PERF_CGROUP_SWIN);
  743. rcu_read_unlock();
  744. }
  745. static inline int perf_cgroup_connect(int fd, struct perf_event *event,
  746. struct perf_event_attr *attr,
  747. struct perf_event *group_leader)
  748. {
  749. struct perf_cgroup *cgrp;
  750. struct cgroup_subsys_state *css;
  751. struct fd f = fdget(fd);
  752. int ret = 0;
  753. if (!f.file)
  754. return -EBADF;
  755. css = css_tryget_online_from_dir(f.file->f_path.dentry,
  756. &perf_event_cgrp_subsys);
  757. if (IS_ERR(css)) {
  758. ret = PTR_ERR(css);
  759. goto out;
  760. }
  761. cgrp = container_of(css, struct perf_cgroup, css);
  762. event->cgrp = cgrp;
  763. /*
  764. * all events in a group must monitor
  765. * the same cgroup because a task belongs
  766. * to only one perf cgroup at a time
  767. */
  768. if (group_leader && group_leader->cgrp != cgrp) {
  769. perf_detach_cgroup(event);
  770. ret = -EINVAL;
  771. }
  772. out:
  773. fdput(f);
  774. return ret;
  775. }
  776. static inline void
  777. perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
  778. {
  779. struct perf_cgroup_info *t;
  780. t = per_cpu_ptr(event->cgrp->info, event->cpu);
  781. event->shadow_ctx_time = now - t->timestamp;
  782. }
  783. /*
  784. * Update cpuctx->cgrp so that it is set when first cgroup event is added and
  785. * cleared when last cgroup event is removed.
  786. */
  787. static inline void
  788. list_update_cgroup_event(struct perf_event *event,
  789. struct perf_event_context *ctx, bool add)
  790. {
  791. struct perf_cpu_context *cpuctx;
  792. struct list_head *cpuctx_entry;
  793. if (!is_cgroup_event(event))
  794. return;
  795. /*
  796. * Because cgroup events are always per-cpu events,
  797. * this will always be called from the right CPU.
  798. */
  799. cpuctx = __get_cpu_context(ctx);
  800. /*
  801. * Since setting cpuctx->cgrp is conditional on the current @cgrp
  802. * matching the event's cgroup, we must do this for every new event,
  803. * because if the first would mismatch, the second would not try again
  804. * and we would leave cpuctx->cgrp unset.
  805. */
  806. if (add && !cpuctx->cgrp) {
  807. struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
  808. if (cgroup_is_descendant(cgrp->css.cgroup, event->cgrp->css.cgroup))
  809. cpuctx->cgrp = cgrp;
  810. }
  811. if (add && ctx->nr_cgroups++)
  812. return;
  813. else if (!add && --ctx->nr_cgroups)
  814. return;
  815. /* no cgroup running */
  816. if (!add)
  817. cpuctx->cgrp = NULL;
  818. cpuctx_entry = &cpuctx->cgrp_cpuctx_entry;
  819. if (add)
  820. list_add(cpuctx_entry, this_cpu_ptr(&cgrp_cpuctx_list));
  821. else
  822. list_del(cpuctx_entry);
  823. }
  824. #else /* !CONFIG_CGROUP_PERF */
  825. static inline bool
  826. perf_cgroup_match(struct perf_event *event)
  827. {
  828. return true;
  829. }
  830. static inline void perf_detach_cgroup(struct perf_event *event)
  831. {}
  832. static inline int is_cgroup_event(struct perf_event *event)
  833. {
  834. return 0;
  835. }
  836. static inline void update_cgrp_time_from_event(struct perf_event *event)
  837. {
  838. }
  839. static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
  840. {
  841. }
  842. static inline void perf_cgroup_sched_out(struct task_struct *task,
  843. struct task_struct *next)
  844. {
  845. }
  846. static inline void perf_cgroup_sched_in(struct task_struct *prev,
  847. struct task_struct *task)
  848. {
  849. }
  850. static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
  851. struct perf_event_attr *attr,
  852. struct perf_event *group_leader)
  853. {
  854. return -EINVAL;
  855. }
  856. static inline void
  857. perf_cgroup_set_timestamp(struct task_struct *task,
  858. struct perf_event_context *ctx)
  859. {
  860. }
  861. void
  862. perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
  863. {
  864. }
  865. static inline void
  866. perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
  867. {
  868. }
  869. static inline u64 perf_cgroup_event_time(struct perf_event *event)
  870. {
  871. return 0;
  872. }
  873. static inline void
  874. list_update_cgroup_event(struct perf_event *event,
  875. struct perf_event_context *ctx, bool add)
  876. {
  877. }
  878. #endif
  879. /*
  880. * set default to be dependent on timer tick just
  881. * like original code
  882. */
  883. #define PERF_CPU_HRTIMER (1000 / HZ)
  884. /*
  885. * function must be called with interrupts disabled
  886. */
  887. static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
  888. {
  889. struct perf_cpu_context *cpuctx;
  890. bool rotations;
  891. lockdep_assert_irqs_disabled();
  892. cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
  893. rotations = perf_rotate_context(cpuctx);
  894. raw_spin_lock(&cpuctx->hrtimer_lock);
  895. if (rotations)
  896. hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
  897. else
  898. cpuctx->hrtimer_active = 0;
  899. raw_spin_unlock(&cpuctx->hrtimer_lock);
  900. return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
  901. }
  902. static void __perf_mux_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
  903. {
  904. struct hrtimer *timer = &cpuctx->hrtimer;
  905. struct pmu *pmu = cpuctx->ctx.pmu;
  906. u64 interval;
  907. /* no multiplexing needed for SW PMU */
  908. if (pmu->task_ctx_nr == perf_sw_context)
  909. return;
  910. /*
  911. * check default is sane, if not set then force to
  912. * default interval (1/tick)
  913. */
  914. interval = pmu->hrtimer_interval_ms;
  915. if (interval < 1)
  916. interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
  917. cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
  918. raw_spin_lock_init(&cpuctx->hrtimer_lock);
  919. hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
  920. timer->function = perf_mux_hrtimer_handler;
  921. }
  922. static int perf_mux_hrtimer_restart(struct perf_cpu_context *cpuctx)
  923. {
  924. struct hrtimer *timer = &cpuctx->hrtimer;
  925. struct pmu *pmu = cpuctx->ctx.pmu;
  926. unsigned long flags;
  927. /* not for SW PMU */
  928. if (pmu->task_ctx_nr == perf_sw_context)
  929. return 0;
  930. raw_spin_lock_irqsave(&cpuctx->hrtimer_lock, flags);
  931. if (!cpuctx->hrtimer_active) {
  932. cpuctx->hrtimer_active = 1;
  933. hrtimer_forward_now(timer, cpuctx->hrtimer_interval);
  934. hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
  935. }
  936. raw_spin_unlock_irqrestore(&cpuctx->hrtimer_lock, flags);
  937. return 0;
  938. }
  939. void perf_pmu_disable(struct pmu *pmu)
  940. {
  941. int *count = this_cpu_ptr(pmu->pmu_disable_count);
  942. if (!(*count)++)
  943. pmu->pmu_disable(pmu);
  944. }
  945. void perf_pmu_enable(struct pmu *pmu)
  946. {
  947. int *count = this_cpu_ptr(pmu->pmu_disable_count);
  948. if (!--(*count))
  949. pmu->pmu_enable(pmu);
  950. }
  951. static DEFINE_PER_CPU(struct list_head, active_ctx_list);
  952. /*
  953. * perf_event_ctx_activate(), perf_event_ctx_deactivate(), and
  954. * perf_event_task_tick() are fully serialized because they're strictly cpu
  955. * affine and perf_event_ctx{activate,deactivate} are called with IRQs
  956. * disabled, while perf_event_task_tick is called from IRQ context.
  957. */
  958. static void perf_event_ctx_activate(struct perf_event_context *ctx)
  959. {
  960. struct list_head *head = this_cpu_ptr(&active_ctx_list);
  961. lockdep_assert_irqs_disabled();
  962. WARN_ON(!list_empty(&ctx->active_ctx_list));
  963. list_add(&ctx->active_ctx_list, head);
  964. }
  965. static void perf_event_ctx_deactivate(struct perf_event_context *ctx)
  966. {
  967. lockdep_assert_irqs_disabled();
  968. WARN_ON(list_empty(&ctx->active_ctx_list));
  969. list_del_init(&ctx->active_ctx_list);
  970. }
  971. static void get_ctx(struct perf_event_context *ctx)
  972. {
  973. WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
  974. }
  975. static void free_ctx(struct rcu_head *head)
  976. {
  977. struct perf_event_context *ctx;
  978. ctx = container_of(head, struct perf_event_context, rcu_head);
  979. kfree(ctx->task_ctx_data);
  980. kfree(ctx);
  981. }
  982. static void put_ctx(struct perf_event_context *ctx)
  983. {
  984. if (atomic_dec_and_test(&ctx->refcount)) {
  985. if (ctx->parent_ctx)
  986. put_ctx(ctx->parent_ctx);
  987. if (ctx->task && ctx->task != TASK_TOMBSTONE)
  988. put_task_struct(ctx->task);
  989. call_rcu(&ctx->rcu_head, free_ctx);
  990. }
  991. }
  992. /*
  993. * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
  994. * perf_pmu_migrate_context() we need some magic.
  995. *
  996. * Those places that change perf_event::ctx will hold both
  997. * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
  998. *
  999. * Lock ordering is by mutex address. There are two other sites where
  1000. * perf_event_context::mutex nests and those are:
  1001. *
  1002. * - perf_event_exit_task_context() [ child , 0 ]
  1003. * perf_event_exit_event()
  1004. * put_event() [ parent, 1 ]
  1005. *
  1006. * - perf_event_init_context() [ parent, 0 ]
  1007. * inherit_task_group()
  1008. * inherit_group()
  1009. * inherit_event()
  1010. * perf_event_alloc()
  1011. * perf_init_event()
  1012. * perf_try_init_event() [ child , 1 ]
  1013. *
  1014. * While it appears there is an obvious deadlock here -- the parent and child
  1015. * nesting levels are inverted between the two. This is in fact safe because
  1016. * life-time rules separate them. That is an exiting task cannot fork, and a
  1017. * spawning task cannot (yet) exit.
  1018. *
  1019. * But remember that that these are parent<->child context relations, and
  1020. * migration does not affect children, therefore these two orderings should not
  1021. * interact.
  1022. *
  1023. * The change in perf_event::ctx does not affect children (as claimed above)
  1024. * because the sys_perf_event_open() case will install a new event and break
  1025. * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
  1026. * concerned with cpuctx and that doesn't have children.
  1027. *
  1028. * The places that change perf_event::ctx will issue:
  1029. *
  1030. * perf_remove_from_context();
  1031. * synchronize_rcu();
  1032. * perf_install_in_context();
  1033. *
  1034. * to affect the change. The remove_from_context() + synchronize_rcu() should
  1035. * quiesce the event, after which we can install it in the new location. This
  1036. * means that only external vectors (perf_fops, prctl) can perturb the event
  1037. * while in transit. Therefore all such accessors should also acquire
  1038. * perf_event_context::mutex to serialize against this.
  1039. *
  1040. * However; because event->ctx can change while we're waiting to acquire
  1041. * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
  1042. * function.
  1043. *
  1044. * Lock order:
  1045. * cred_guard_mutex
  1046. * task_struct::perf_event_mutex
  1047. * perf_event_context::mutex
  1048. * perf_event::child_mutex;
  1049. * perf_event_context::lock
  1050. * perf_event::mmap_mutex
  1051. * mmap_sem
  1052. *
  1053. * cpu_hotplug_lock
  1054. * pmus_lock
  1055. * cpuctx->mutex / perf_event_context::mutex
  1056. */
  1057. static struct perf_event_context *
  1058. perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
  1059. {
  1060. struct perf_event_context *ctx;
  1061. again:
  1062. rcu_read_lock();
  1063. ctx = READ_ONCE(event->ctx);
  1064. if (!atomic_inc_not_zero(&ctx->refcount)) {
  1065. rcu_read_unlock();
  1066. goto again;
  1067. }
  1068. rcu_read_unlock();
  1069. mutex_lock_nested(&ctx->mutex, nesting);
  1070. if (event->ctx != ctx) {
  1071. mutex_unlock(&ctx->mutex);
  1072. put_ctx(ctx);
  1073. goto again;
  1074. }
  1075. return ctx;
  1076. }
  1077. static inline struct perf_event_context *
  1078. perf_event_ctx_lock(struct perf_event *event)
  1079. {
  1080. return perf_event_ctx_lock_nested(event, 0);
  1081. }
  1082. static void perf_event_ctx_unlock(struct perf_event *event,
  1083. struct perf_event_context *ctx)
  1084. {
  1085. mutex_unlock(&ctx->mutex);
  1086. put_ctx(ctx);
  1087. }
  1088. /*
  1089. * This must be done under the ctx->lock, such as to serialize against
  1090. * context_equiv(), therefore we cannot call put_ctx() since that might end up
  1091. * calling scheduler related locks and ctx->lock nests inside those.
  1092. */
  1093. static __must_check struct perf_event_context *
  1094. unclone_ctx(struct perf_event_context *ctx)
  1095. {
  1096. struct perf_event_context *parent_ctx = ctx->parent_ctx;
  1097. lockdep_assert_held(&ctx->lock);
  1098. if (parent_ctx)
  1099. ctx->parent_ctx = NULL;
  1100. ctx->generation++;
  1101. return parent_ctx;
  1102. }
  1103. static u32 perf_event_pid_type(struct perf_event *event, struct task_struct *p,
  1104. enum pid_type type)
  1105. {
  1106. u32 nr;
  1107. /*
  1108. * only top level events have the pid namespace they were created in
  1109. */
  1110. if (event->parent)
  1111. event = event->parent;
  1112. nr = __task_pid_nr_ns(p, type, event->ns);
  1113. /* avoid -1 if it is idle thread or runs in another ns */
  1114. if (!nr && !pid_alive(p))
  1115. nr = -1;
  1116. return nr;
  1117. }
  1118. static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
  1119. {
  1120. return perf_event_pid_type(event, p, PIDTYPE_TGID);
  1121. }
  1122. static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
  1123. {
  1124. return perf_event_pid_type(event, p, PIDTYPE_PID);
  1125. }
  1126. /*
  1127. * If we inherit events we want to return the parent event id
  1128. * to userspace.
  1129. */
  1130. static u64 primary_event_id(struct perf_event *event)
  1131. {
  1132. u64 id = event->id;
  1133. if (event->parent)
  1134. id = event->parent->id;
  1135. return id;
  1136. }
  1137. /*
  1138. * Get the perf_event_context for a task and lock it.
  1139. *
  1140. * This has to cope with with the fact that until it is locked,
  1141. * the context could get moved to another task.
  1142. */
  1143. static struct perf_event_context *
  1144. perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
  1145. {
  1146. struct perf_event_context *ctx;
  1147. retry:
  1148. /*
  1149. * One of the few rules of preemptible RCU is that one cannot do
  1150. * rcu_read_unlock() while holding a scheduler (or nested) lock when
  1151. * part of the read side critical section was irqs-enabled -- see
  1152. * rcu_read_unlock_special().
  1153. *
  1154. * Since ctx->lock nests under rq->lock we must ensure the entire read
  1155. * side critical section has interrupts disabled.
  1156. */
  1157. local_irq_save(*flags);
  1158. rcu_read_lock();
  1159. ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
  1160. if (ctx) {
  1161. /*
  1162. * If this context is a clone of another, it might
  1163. * get swapped for another underneath us by
  1164. * perf_event_task_sched_out, though the
  1165. * rcu_read_lock() protects us from any context
  1166. * getting freed. Lock the context and check if it
  1167. * got swapped before we could get the lock, and retry
  1168. * if so. If we locked the right context, then it
  1169. * can't get swapped on us any more.
  1170. */
  1171. raw_spin_lock(&ctx->lock);
  1172. if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
  1173. raw_spin_unlock(&ctx->lock);
  1174. rcu_read_unlock();
  1175. local_irq_restore(*flags);
  1176. goto retry;
  1177. }
  1178. if (ctx->task == TASK_TOMBSTONE ||
  1179. !atomic_inc_not_zero(&ctx->refcount)) {
  1180. raw_spin_unlock(&ctx->lock);
  1181. ctx = NULL;
  1182. } else {
  1183. WARN_ON_ONCE(ctx->task != task);
  1184. }
  1185. }
  1186. rcu_read_unlock();
  1187. if (!ctx)
  1188. local_irq_restore(*flags);
  1189. return ctx;
  1190. }
  1191. /*
  1192. * Get the context for a task and increment its pin_count so it
  1193. * can't get swapped to another task. This also increments its
  1194. * reference count so that the context can't get freed.
  1195. */
  1196. static struct perf_event_context *
  1197. perf_pin_task_context(struct task_struct *task, int ctxn)
  1198. {
  1199. struct perf_event_context *ctx;
  1200. unsigned long flags;
  1201. ctx = perf_lock_task_context(task, ctxn, &flags);
  1202. if (ctx) {
  1203. ++ctx->pin_count;
  1204. raw_spin_unlock_irqrestore(&ctx->lock, flags);
  1205. }
  1206. return ctx;
  1207. }
  1208. static void perf_unpin_context(struct perf_event_context *ctx)
  1209. {
  1210. unsigned long flags;
  1211. raw_spin_lock_irqsave(&ctx->lock, flags);
  1212. --ctx->pin_count;
  1213. raw_spin_unlock_irqrestore(&ctx->lock, flags);
  1214. }
  1215. /*
  1216. * Update the record of the current time in a context.
  1217. */
  1218. static void update_context_time(struct perf_event_context *ctx)
  1219. {
  1220. u64 now = perf_clock();
  1221. ctx->time += now - ctx->timestamp;
  1222. ctx->timestamp = now;
  1223. }
  1224. static u64 perf_event_time(struct perf_event *event)
  1225. {
  1226. struct perf_event_context *ctx = event->ctx;
  1227. if (is_cgroup_event(event))
  1228. return perf_cgroup_event_time(event);
  1229. return ctx ? ctx->time : 0;
  1230. }
  1231. static enum event_type_t get_event_type(struct perf_event *event)
  1232. {
  1233. struct perf_event_context *ctx = event->ctx;
  1234. enum event_type_t event_type;
  1235. lockdep_assert_held(&ctx->lock);
  1236. /*
  1237. * It's 'group type', really, because if our group leader is
  1238. * pinned, so are we.
  1239. */
  1240. if (event->group_leader != event)
  1241. event = event->group_leader;
  1242. event_type = event->attr.pinned ? EVENT_PINNED : EVENT_FLEXIBLE;
  1243. if (!ctx->task)
  1244. event_type |= EVENT_CPU;
  1245. return event_type;
  1246. }
  1247. /*
  1248. * Helper function to initialize event group nodes.
  1249. */
  1250. static void init_event_group(struct perf_event *event)
  1251. {
  1252. RB_CLEAR_NODE(&event->group_node);
  1253. event->group_index = 0;
  1254. }
  1255. /*
  1256. * Extract pinned or flexible groups from the context
  1257. * based on event attrs bits.
  1258. */
  1259. static struct perf_event_groups *
  1260. get_event_groups(struct perf_event *event, struct perf_event_context *ctx)
  1261. {
  1262. if (event->attr.pinned)
  1263. return &ctx->pinned_groups;
  1264. else
  1265. return &ctx->flexible_groups;
  1266. }
  1267. /*
  1268. * Helper function to initializes perf_event_group trees.
  1269. */
  1270. static void perf_event_groups_init(struct perf_event_groups *groups)
  1271. {
  1272. groups->tree = RB_ROOT;
  1273. groups->index = 0;
  1274. }
  1275. /*
  1276. * Compare function for event groups;
  1277. *
  1278. * Implements complex key that first sorts by CPU and then by virtual index
  1279. * which provides ordering when rotating groups for the same CPU.
  1280. */
  1281. static bool
  1282. perf_event_groups_less(struct perf_event *left, struct perf_event *right)
  1283. {
  1284. if (left->cpu < right->cpu)
  1285. return true;
  1286. if (left->cpu > right->cpu)
  1287. return false;
  1288. if (left->group_index < right->group_index)
  1289. return true;
  1290. if (left->group_index > right->group_index)
  1291. return false;
  1292. return false;
  1293. }
  1294. /*
  1295. * Insert @event into @groups' tree; using {@event->cpu, ++@groups->index} for
  1296. * key (see perf_event_groups_less). This places it last inside the CPU
  1297. * subtree.
  1298. */
  1299. static void
  1300. perf_event_groups_insert(struct perf_event_groups *groups,
  1301. struct perf_event *event)
  1302. {
  1303. struct perf_event *node_event;
  1304. struct rb_node *parent;
  1305. struct rb_node **node;
  1306. event->group_index = ++groups->index;
  1307. node = &groups->tree.rb_node;
  1308. parent = *node;
  1309. while (*node) {
  1310. parent = *node;
  1311. node_event = container_of(*node, struct perf_event, group_node);
  1312. if (perf_event_groups_less(event, node_event))
  1313. node = &parent->rb_left;
  1314. else
  1315. node = &parent->rb_right;
  1316. }
  1317. rb_link_node(&event->group_node, parent, node);
  1318. rb_insert_color(&event->group_node, &groups->tree);
  1319. }
  1320. /*
  1321. * Helper function to insert event into the pinned or flexible groups.
  1322. */
  1323. static void
  1324. add_event_to_groups(struct perf_event *event, struct perf_event_context *ctx)
  1325. {
  1326. struct perf_event_groups *groups;
  1327. groups = get_event_groups(event, ctx);
  1328. perf_event_groups_insert(groups, event);
  1329. }
  1330. /*
  1331. * Delete a group from a tree.
  1332. */
  1333. static void
  1334. perf_event_groups_delete(struct perf_event_groups *groups,
  1335. struct perf_event *event)
  1336. {
  1337. WARN_ON_ONCE(RB_EMPTY_NODE(&event->group_node) ||
  1338. RB_EMPTY_ROOT(&groups->tree));
  1339. rb_erase(&event->group_node, &groups->tree);
  1340. init_event_group(event);
  1341. }
  1342. /*
  1343. * Helper function to delete event from its groups.
  1344. */
  1345. static void
  1346. del_event_from_groups(struct perf_event *event, struct perf_event_context *ctx)
  1347. {
  1348. struct perf_event_groups *groups;
  1349. groups = get_event_groups(event, ctx);
  1350. perf_event_groups_delete(groups, event);
  1351. }
  1352. /*
  1353. * Get the leftmost event in the @cpu subtree.
  1354. */
  1355. static struct perf_event *
  1356. perf_event_groups_first(struct perf_event_groups *groups, int cpu)
  1357. {
  1358. struct perf_event *node_event = NULL, *match = NULL;
  1359. struct rb_node *node = groups->tree.rb_node;
  1360. while (node) {
  1361. node_event = container_of(node, struct perf_event, group_node);
  1362. if (cpu < node_event->cpu) {
  1363. node = node->rb_left;
  1364. } else if (cpu > node_event->cpu) {
  1365. node = node->rb_right;
  1366. } else {
  1367. match = node_event;
  1368. node = node->rb_left;
  1369. }
  1370. }
  1371. return match;
  1372. }
  1373. /*
  1374. * Like rb_entry_next_safe() for the @cpu subtree.
  1375. */
  1376. static struct perf_event *
  1377. perf_event_groups_next(struct perf_event *event)
  1378. {
  1379. struct perf_event *next;
  1380. next = rb_entry_safe(rb_next(&event->group_node), typeof(*event), group_node);
  1381. if (next && next->cpu == event->cpu)
  1382. return next;
  1383. return NULL;
  1384. }
  1385. /*
  1386. * Iterate through the whole groups tree.
  1387. */
  1388. #define perf_event_groups_for_each(event, groups) \
  1389. for (event = rb_entry_safe(rb_first(&((groups)->tree)), \
  1390. typeof(*event), group_node); event; \
  1391. event = rb_entry_safe(rb_next(&event->group_node), \
  1392. typeof(*event), group_node))
  1393. /*
  1394. * Add an event from the lists for its context.
  1395. * Must be called with ctx->mutex and ctx->lock held.
  1396. */
  1397. static void
  1398. list_add_event(struct perf_event *event, struct perf_event_context *ctx)
  1399. {
  1400. lockdep_assert_held(&ctx->lock);
  1401. WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
  1402. event->attach_state |= PERF_ATTACH_CONTEXT;
  1403. event->tstamp = perf_event_time(event);
  1404. /*
  1405. * If we're a stand alone event or group leader, we go to the context
  1406. * list, group events are kept attached to the group so that
  1407. * perf_group_detach can, at all times, locate all siblings.
  1408. */
  1409. if (event->group_leader == event) {
  1410. event->group_caps = event->event_caps;
  1411. add_event_to_groups(event, ctx);
  1412. }
  1413. list_update_cgroup_event(event, ctx, true);
  1414. list_add_rcu(&event->event_entry, &ctx->event_list);
  1415. ctx->nr_events++;
  1416. if (event->attr.inherit_stat)
  1417. ctx->nr_stat++;
  1418. ctx->generation++;
  1419. }
  1420. /*
  1421. * Initialize event state based on the perf_event_attr::disabled.
  1422. */
  1423. static inline void perf_event__state_init(struct perf_event *event)
  1424. {
  1425. event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
  1426. PERF_EVENT_STATE_INACTIVE;
  1427. }
  1428. static void __perf_event_read_size(struct perf_event *event, int nr_siblings)
  1429. {
  1430. int entry = sizeof(u64); /* value */
  1431. int size = 0;
  1432. int nr = 1;
  1433. if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
  1434. size += sizeof(u64);
  1435. if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
  1436. size += sizeof(u64);
  1437. if (event->attr.read_format & PERF_FORMAT_ID)
  1438. entry += sizeof(u64);
  1439. if (event->attr.read_format & PERF_FORMAT_GROUP) {
  1440. nr += nr_siblings;
  1441. size += sizeof(u64);
  1442. }
  1443. size += entry * nr;
  1444. event->read_size = size;
  1445. }
  1446. static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
  1447. {
  1448. struct perf_sample_data *data;
  1449. u16 size = 0;
  1450. if (sample_type & PERF_SAMPLE_IP)
  1451. size += sizeof(data->ip);
  1452. if (sample_type & PERF_SAMPLE_ADDR)
  1453. size += sizeof(data->addr);
  1454. if (sample_type & PERF_SAMPLE_PERIOD)
  1455. size += sizeof(data->period);
  1456. if (sample_type & PERF_SAMPLE_WEIGHT)
  1457. size += sizeof(data->weight);
  1458. if (sample_type & PERF_SAMPLE_READ)
  1459. size += event->read_size;
  1460. if (sample_type & PERF_SAMPLE_DATA_SRC)
  1461. size += sizeof(data->data_src.val);
  1462. if (sample_type & PERF_SAMPLE_TRANSACTION)
  1463. size += sizeof(data->txn);
  1464. if (sample_type & PERF_SAMPLE_PHYS_ADDR)
  1465. size += sizeof(data->phys_addr);
  1466. event->header_size = size;
  1467. }
  1468. /*
  1469. * Called at perf_event creation and when events are attached/detached from a
  1470. * group.
  1471. */
  1472. static void perf_event__header_size(struct perf_event *event)
  1473. {
  1474. __perf_event_read_size(event,
  1475. event->group_leader->nr_siblings);
  1476. __perf_event_header_size(event, event->attr.sample_type);
  1477. }
  1478. static void perf_event__id_header_size(struct perf_event *event)
  1479. {
  1480. struct perf_sample_data *data;
  1481. u64 sample_type = event->attr.sample_type;
  1482. u16 size = 0;
  1483. if (sample_type & PERF_SAMPLE_TID)
  1484. size += sizeof(data->tid_entry);
  1485. if (sample_type & PERF_SAMPLE_TIME)
  1486. size += sizeof(data->time);
  1487. if (sample_type & PERF_SAMPLE_IDENTIFIER)
  1488. size += sizeof(data->id);
  1489. if (sample_type & PERF_SAMPLE_ID)
  1490. size += sizeof(data->id);
  1491. if (sample_type & PERF_SAMPLE_STREAM_ID)
  1492. size += sizeof(data->stream_id);
  1493. if (sample_type & PERF_SAMPLE_CPU)
  1494. size += sizeof(data->cpu_entry);
  1495. event->id_header_size = size;
  1496. }
  1497. static bool perf_event_validate_size(struct perf_event *event)
  1498. {
  1499. /*
  1500. * The values computed here will be over-written when we actually
  1501. * attach the event.
  1502. */
  1503. __perf_event_read_size(event, event->group_leader->nr_siblings + 1);
  1504. __perf_event_header_size(event, event->attr.sample_type & ~PERF_SAMPLE_READ);
  1505. perf_event__id_header_size(event);
  1506. /*
  1507. * Sum the lot; should not exceed the 64k limit we have on records.
  1508. * Conservative limit to allow for callchains and other variable fields.
  1509. */
  1510. if (event->read_size + event->header_size +
  1511. event->id_header_size + sizeof(struct perf_event_header) >= 16*1024)
  1512. return false;
  1513. return true;
  1514. }
  1515. static void perf_group_attach(struct perf_event *event)
  1516. {
  1517. struct perf_event *group_leader = event->group_leader, *pos;
  1518. lockdep_assert_held(&event->ctx->lock);
  1519. /*
  1520. * We can have double attach due to group movement in perf_event_open.
  1521. */
  1522. if (event->attach_state & PERF_ATTACH_GROUP)
  1523. return;
  1524. event->attach_state |= PERF_ATTACH_GROUP;
  1525. if (group_leader == event)
  1526. return;
  1527. WARN_ON_ONCE(group_leader->ctx != event->ctx);
  1528. group_leader->group_caps &= event->event_caps;
  1529. list_add_tail(&event->sibling_list, &group_leader->sibling_list);
  1530. group_leader->nr_siblings++;
  1531. perf_event__header_size(group_leader);
  1532. for_each_sibling_event(pos, group_leader)
  1533. perf_event__header_size(pos);
  1534. }
  1535. /*
  1536. * Remove an event from the lists for its context.
  1537. * Must be called with ctx->mutex and ctx->lock held.
  1538. */
  1539. static void
  1540. list_del_event(struct perf_event *event, struct perf_event_context *ctx)
  1541. {
  1542. WARN_ON_ONCE(event->ctx != ctx);
  1543. lockdep_assert_held(&ctx->lock);
  1544. /*
  1545. * We can have double detach due to exit/hot-unplug + close.
  1546. */
  1547. if (!(event->attach_state & PERF_ATTACH_CONTEXT))
  1548. return;
  1549. event->attach_state &= ~PERF_ATTACH_CONTEXT;
  1550. list_update_cgroup_event(event, ctx, false);
  1551. ctx->nr_events--;
  1552. if (event->attr.inherit_stat)
  1553. ctx->nr_stat--;
  1554. list_del_rcu(&event->event_entry);
  1555. if (event->group_leader == event)
  1556. del_event_from_groups(event, ctx);
  1557. /*
  1558. * If event was in error state, then keep it
  1559. * that way, otherwise bogus counts will be
  1560. * returned on read(). The only way to get out
  1561. * of error state is by explicit re-enabling
  1562. * of the event
  1563. */
  1564. if (event->state > PERF_EVENT_STATE_OFF)
  1565. perf_event_set_state(event, PERF_EVENT_STATE_OFF);
  1566. ctx->generation++;
  1567. }
  1568. static void perf_group_detach(struct perf_event *event)
  1569. {
  1570. struct perf_event *sibling, *tmp;
  1571. struct perf_event_context *ctx = event->ctx;
  1572. lockdep_assert_held(&ctx->lock);
  1573. /*
  1574. * We can have double detach due to exit/hot-unplug + close.
  1575. */
  1576. if (!(event->attach_state & PERF_ATTACH_GROUP))
  1577. return;
  1578. event->attach_state &= ~PERF_ATTACH_GROUP;
  1579. /*
  1580. * If this is a sibling, remove it from its group.
  1581. */
  1582. if (event->group_leader != event) {
  1583. list_del_init(&event->sibling_list);
  1584. event->group_leader->nr_siblings--;
  1585. goto out;
  1586. }
  1587. /*
  1588. * If this was a group event with sibling events then
  1589. * upgrade the siblings to singleton events by adding them
  1590. * to whatever list we are on.
  1591. */
  1592. list_for_each_entry_safe(sibling, tmp, &event->sibling_list, sibling_list) {
  1593. sibling->group_leader = sibling;
  1594. list_del_init(&sibling->sibling_list);
  1595. /* Inherit group flags from the previous leader */
  1596. sibling->group_caps = event->group_caps;
  1597. if (!RB_EMPTY_NODE(&event->group_node)) {
  1598. add_event_to_groups(sibling, event->ctx);
  1599. if (sibling->state == PERF_EVENT_STATE_ACTIVE) {
  1600. struct list_head *list = sibling->attr.pinned ?
  1601. &ctx->pinned_active : &ctx->flexible_active;
  1602. list_add_tail(&sibling->active_list, list);
  1603. }
  1604. }
  1605. WARN_ON_ONCE(sibling->ctx != event->ctx);
  1606. }
  1607. out:
  1608. perf_event__header_size(event->group_leader);
  1609. for_each_sibling_event(tmp, event->group_leader)
  1610. perf_event__header_size(tmp);
  1611. }
  1612. static bool is_orphaned_event(struct perf_event *event)
  1613. {
  1614. return event->state == PERF_EVENT_STATE_DEAD;
  1615. }
  1616. static inline int __pmu_filter_match(struct perf_event *event)
  1617. {
  1618. struct pmu *pmu = event->pmu;
  1619. return pmu->filter_match ? pmu->filter_match(event) : 1;
  1620. }
  1621. /*
  1622. * Check whether we should attempt to schedule an event group based on
  1623. * PMU-specific filtering. An event group can consist of HW and SW events,
  1624. * potentially with a SW leader, so we must check all the filters, to
  1625. * determine whether a group is schedulable:
  1626. */
  1627. static inline int pmu_filter_match(struct perf_event *event)
  1628. {
  1629. struct perf_event *sibling;
  1630. if (!__pmu_filter_match(event))
  1631. return 0;
  1632. for_each_sibling_event(sibling, event) {
  1633. if (!__pmu_filter_match(sibling))
  1634. return 0;
  1635. }
  1636. return 1;
  1637. }
  1638. static inline int
  1639. event_filter_match(struct perf_event *event)
  1640. {
  1641. return (event->cpu == -1 || event->cpu == smp_processor_id()) &&
  1642. perf_cgroup_match(event) && pmu_filter_match(event);
  1643. }
  1644. static void
  1645. event_sched_out(struct perf_event *event,
  1646. struct perf_cpu_context *cpuctx,
  1647. struct perf_event_context *ctx)
  1648. {
  1649. enum perf_event_state state = PERF_EVENT_STATE_INACTIVE;
  1650. WARN_ON_ONCE(event->ctx != ctx);
  1651. lockdep_assert_held(&ctx->lock);
  1652. if (event->state != PERF_EVENT_STATE_ACTIVE)
  1653. return;
  1654. /*
  1655. * Asymmetry; we only schedule events _IN_ through ctx_sched_in(), but
  1656. * we can schedule events _OUT_ individually through things like
  1657. * __perf_remove_from_context().
  1658. */
  1659. list_del_init(&event->active_list);
  1660. perf_pmu_disable(event->pmu);
  1661. event->pmu->del(event, 0);
  1662. event->oncpu = -1;
  1663. if (event->pending_disable) {
  1664. event->pending_disable = 0;
  1665. state = PERF_EVENT_STATE_OFF;
  1666. }
  1667. perf_event_set_state(event, state);
  1668. if (!is_software_event(event))
  1669. cpuctx->active_oncpu--;
  1670. if (!--ctx->nr_active)
  1671. perf_event_ctx_deactivate(ctx);
  1672. if (event->attr.freq && event->attr.sample_freq)
  1673. ctx->nr_freq--;
  1674. if (event->attr.exclusive || !cpuctx->active_oncpu)
  1675. cpuctx->exclusive = 0;
  1676. perf_pmu_enable(event->pmu);
  1677. }
  1678. static void
  1679. group_sched_out(struct perf_event *group_event,
  1680. struct perf_cpu_context *cpuctx,
  1681. struct perf_event_context *ctx)
  1682. {
  1683. struct perf_event *event;
  1684. if (group_event->state != PERF_EVENT_STATE_ACTIVE)
  1685. return;
  1686. perf_pmu_disable(ctx->pmu);
  1687. event_sched_out(group_event, cpuctx, ctx);
  1688. /*
  1689. * Schedule out siblings (if any):
  1690. */
  1691. for_each_sibling_event(event, group_event)
  1692. event_sched_out(event, cpuctx, ctx);
  1693. perf_pmu_enable(ctx->pmu);
  1694. if (group_event->attr.exclusive)
  1695. cpuctx->exclusive = 0;
  1696. }
  1697. #define DETACH_GROUP 0x01UL
  1698. /*
  1699. * Cross CPU call to remove a performance event
  1700. *
  1701. * We disable the event on the hardware level first. After that we
  1702. * remove it from the context list.
  1703. */
  1704. static void
  1705. __perf_remove_from_context(struct perf_event *event,
  1706. struct perf_cpu_context *cpuctx,
  1707. struct perf_event_context *ctx,
  1708. void *info)
  1709. {
  1710. unsigned long flags = (unsigned long)info;
  1711. if (ctx->is_active & EVENT_TIME) {
  1712. update_context_time(ctx);
  1713. update_cgrp_time_from_cpuctx(cpuctx);
  1714. }
  1715. event_sched_out(event, cpuctx, ctx);
  1716. if (flags & DETACH_GROUP)
  1717. perf_group_detach(event);
  1718. list_del_event(event, ctx);
  1719. if (!ctx->nr_events && ctx->is_active) {
  1720. ctx->is_active = 0;
  1721. if (ctx->task) {
  1722. WARN_ON_ONCE(cpuctx->task_ctx != ctx);
  1723. cpuctx->task_ctx = NULL;
  1724. }
  1725. }
  1726. }
  1727. /*
  1728. * Remove the event from a task's (or a CPU's) list of events.
  1729. *
  1730. * If event->ctx is a cloned context, callers must make sure that
  1731. * every task struct that event->ctx->task could possibly point to
  1732. * remains valid. This is OK when called from perf_release since
  1733. * that only calls us on the top-level context, which can't be a clone.
  1734. * When called from perf_event_exit_task, it's OK because the
  1735. * context has been detached from its task.
  1736. */
  1737. static void perf_remove_from_context(struct perf_event *event, unsigned long flags)
  1738. {
  1739. struct perf_event_context *ctx = event->ctx;
  1740. lockdep_assert_held(&ctx->mutex);
  1741. event_function_call(event, __perf_remove_from_context, (void *)flags);
  1742. /*
  1743. * The above event_function_call() can NO-OP when it hits
  1744. * TASK_TOMBSTONE. In that case we must already have been detached
  1745. * from the context (by perf_event_exit_event()) but the grouping
  1746. * might still be in-tact.
  1747. */
  1748. WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
  1749. if ((flags & DETACH_GROUP) &&
  1750. (event->attach_state & PERF_ATTACH_GROUP)) {
  1751. /*
  1752. * Since in that case we cannot possibly be scheduled, simply
  1753. * detach now.
  1754. */
  1755. raw_spin_lock_irq(&ctx->lock);
  1756. perf_group_detach(event);
  1757. raw_spin_unlock_irq(&ctx->lock);
  1758. }
  1759. }
  1760. /*
  1761. * Cross CPU call to disable a performance event
  1762. */
  1763. static void __perf_event_disable(struct perf_event *event,
  1764. struct perf_cpu_context *cpuctx,
  1765. struct perf_event_context *ctx,
  1766. void *info)
  1767. {
  1768. if (event->state < PERF_EVENT_STATE_INACTIVE)
  1769. return;
  1770. if (ctx->is_active & EVENT_TIME) {
  1771. update_context_time(ctx);
  1772. update_cgrp_time_from_event(event);
  1773. }
  1774. if (event == event->group_leader)
  1775. group_sched_out(event, cpuctx, ctx);
  1776. else
  1777. event_sched_out(event, cpuctx, ctx);
  1778. perf_event_set_state(event, PERF_EVENT_STATE_OFF);
  1779. }
  1780. /*
  1781. * Disable an event.
  1782. *
  1783. * If event->ctx is a cloned context, callers must make sure that
  1784. * every task struct that event->ctx->task could possibly point to
  1785. * remains valid. This condition is satisifed when called through
  1786. * perf_event_for_each_child or perf_event_for_each because they
  1787. * hold the top-level event's child_mutex, so any descendant that
  1788. * goes to exit will block in perf_event_exit_event().
  1789. *
  1790. * When called from perf_pending_event it's OK because event->ctx
  1791. * is the current context on this CPU and preemption is disabled,
  1792. * hence we can't get into perf_event_task_sched_out for this context.
  1793. */
  1794. static void _perf_event_disable(struct perf_event *event)
  1795. {
  1796. struct perf_event_context *ctx = event->ctx;
  1797. raw_spin_lock_irq(&ctx->lock);
  1798. if (event->state <= PERF_EVENT_STATE_OFF) {
  1799. raw_spin_unlock_irq(&ctx->lock);
  1800. return;
  1801. }
  1802. raw_spin_unlock_irq(&ctx->lock);
  1803. event_function_call(event, __perf_event_disable, NULL);
  1804. }
  1805. void perf_event_disable_local(struct perf_event *event)
  1806. {
  1807. event_function_local(event, __perf_event_disable, NULL);
  1808. }
  1809. /*
  1810. * Strictly speaking kernel users cannot create groups and therefore this
  1811. * interface does not need the perf_event_ctx_lock() magic.
  1812. */
  1813. void perf_event_disable(struct perf_event *event)
  1814. {
  1815. struct perf_event_context *ctx;
  1816. ctx = perf_event_ctx_lock(event);
  1817. _perf_event_disable(event);
  1818. perf_event_ctx_unlock(event, ctx);
  1819. }
  1820. EXPORT_SYMBOL_GPL(perf_event_disable);
  1821. void perf_event_disable_inatomic(struct perf_event *event)
  1822. {
  1823. event->pending_disable = 1;
  1824. irq_work_queue(&event->pending);
  1825. }
  1826. static void perf_set_shadow_time(struct perf_event *event,
  1827. struct perf_event_context *ctx)
  1828. {
  1829. /*
  1830. * use the correct time source for the time snapshot
  1831. *
  1832. * We could get by without this by leveraging the
  1833. * fact that to get to this function, the caller
  1834. * has most likely already called update_context_time()
  1835. * and update_cgrp_time_xx() and thus both timestamp
  1836. * are identical (or very close). Given that tstamp is,
  1837. * already adjusted for cgroup, we could say that:
  1838. * tstamp - ctx->timestamp
  1839. * is equivalent to
  1840. * tstamp - cgrp->timestamp.
  1841. *
  1842. * Then, in perf_output_read(), the calculation would
  1843. * work with no changes because:
  1844. * - event is guaranteed scheduled in
  1845. * - no scheduled out in between
  1846. * - thus the timestamp would be the same
  1847. *
  1848. * But this is a bit hairy.
  1849. *
  1850. * So instead, we have an explicit cgroup call to remain
  1851. * within the time time source all along. We believe it
  1852. * is cleaner and simpler to understand.
  1853. */
  1854. if (is_cgroup_event(event))
  1855. perf_cgroup_set_shadow_time(event, event->tstamp);
  1856. else
  1857. event->shadow_ctx_time = event->tstamp - ctx->timestamp;
  1858. }
  1859. #define MAX_INTERRUPTS (~0ULL)
  1860. static void perf_log_throttle(struct perf_event *event, int enable);
  1861. static void perf_log_itrace_start(struct perf_event *event);
  1862. static int
  1863. event_sched_in(struct perf_event *event,
  1864. struct perf_cpu_context *cpuctx,
  1865. struct perf_event_context *ctx)
  1866. {
  1867. int ret = 0;
  1868. lockdep_assert_held(&ctx->lock);
  1869. if (event->state <= PERF_EVENT_STATE_OFF)
  1870. return 0;
  1871. WRITE_ONCE(event->oncpu, smp_processor_id());
  1872. /*
  1873. * Order event::oncpu write to happen before the ACTIVE state is
  1874. * visible. This allows perf_event_{stop,read}() to observe the correct
  1875. * ->oncpu if it sees ACTIVE.
  1876. */
  1877. smp_wmb();
  1878. perf_event_set_state(event, PERF_EVENT_STATE_ACTIVE);
  1879. /*
  1880. * Unthrottle events, since we scheduled we might have missed several
  1881. * ticks already, also for a heavily scheduling task there is little
  1882. * guarantee it'll get a tick in a timely manner.
  1883. */
  1884. if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
  1885. perf_log_throttle(event, 1);
  1886. event->hw.interrupts = 0;
  1887. }
  1888. perf_pmu_disable(event->pmu);
  1889. perf_set_shadow_time(event, ctx);
  1890. perf_log_itrace_start(event);
  1891. if (event->pmu->add(event, PERF_EF_START)) {
  1892. perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
  1893. event->oncpu = -1;
  1894. ret = -EAGAIN;
  1895. goto out;
  1896. }
  1897. if (!is_software_event(event))
  1898. cpuctx->active_oncpu++;
  1899. if (!ctx->nr_active++)
  1900. perf_event_ctx_activate(ctx);
  1901. if (event->attr.freq && event->attr.sample_freq)
  1902. ctx->nr_freq++;
  1903. if (event->attr.exclusive)
  1904. cpuctx->exclusive = 1;
  1905. out:
  1906. perf_pmu_enable(event->pmu);
  1907. return ret;
  1908. }
  1909. static int
  1910. group_sched_in(struct perf_event *group_event,
  1911. struct perf_cpu_context *cpuctx,
  1912. struct perf_event_context *ctx)
  1913. {
  1914. struct perf_event *event, *partial_group = NULL;
  1915. struct pmu *pmu = ctx->pmu;
  1916. if (group_event->state == PERF_EVENT_STATE_OFF)
  1917. return 0;
  1918. pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
  1919. if (event_sched_in(group_event, cpuctx, ctx)) {
  1920. pmu->cancel_txn(pmu);
  1921. perf_mux_hrtimer_restart(cpuctx);
  1922. return -EAGAIN;
  1923. }
  1924. /*
  1925. * Schedule in siblings as one group (if any):
  1926. */
  1927. for_each_sibling_event(event, group_event) {
  1928. if (event_sched_in(event, cpuctx, ctx)) {
  1929. partial_group = event;
  1930. goto group_error;
  1931. }
  1932. }
  1933. if (!pmu->commit_txn(pmu))
  1934. return 0;
  1935. group_error:
  1936. /*
  1937. * Groups can be scheduled in as one unit only, so undo any
  1938. * partial group before returning:
  1939. * The events up to the failed event are scheduled out normally.
  1940. */
  1941. for_each_sibling_event(event, group_event) {
  1942. if (event == partial_group)
  1943. break;
  1944. event_sched_out(event, cpuctx, ctx);
  1945. }
  1946. event_sched_out(group_event, cpuctx, ctx);
  1947. pmu->cancel_txn(pmu);
  1948. perf_mux_hrtimer_restart(cpuctx);
  1949. return -EAGAIN;
  1950. }
  1951. /*
  1952. * Work out whether we can put this event group on the CPU now.
  1953. */
  1954. static int group_can_go_on(struct perf_event *event,
  1955. struct perf_cpu_context *cpuctx,
  1956. int can_add_hw)
  1957. {
  1958. /*
  1959. * Groups consisting entirely of software events can always go on.
  1960. */
  1961. if (event->group_caps & PERF_EV_CAP_SOFTWARE)
  1962. return 1;
  1963. /*
  1964. * If an exclusive group is already on, no other hardware
  1965. * events can go on.
  1966. */
  1967. if (cpuctx->exclusive)
  1968. return 0;
  1969. /*
  1970. * If this group is exclusive and there are already
  1971. * events on the CPU, it can't go on.
  1972. */
  1973. if (event->attr.exclusive && cpuctx->active_oncpu)
  1974. return 0;
  1975. /*
  1976. * Otherwise, try to add it if all previous groups were able
  1977. * to go on.
  1978. */
  1979. return can_add_hw;
  1980. }
  1981. static void add_event_to_ctx(struct perf_event *event,
  1982. struct perf_event_context *ctx)
  1983. {
  1984. list_add_event(event, ctx);
  1985. perf_group_attach(event);
  1986. }
  1987. static void ctx_sched_out(struct perf_event_context *ctx,
  1988. struct perf_cpu_context *cpuctx,
  1989. enum event_type_t event_type);
  1990. static void
  1991. ctx_sched_in(struct perf_event_context *ctx,
  1992. struct perf_cpu_context *cpuctx,
  1993. enum event_type_t event_type,
  1994. struct task_struct *task);
  1995. static void task_ctx_sched_out(struct perf_cpu_context *cpuctx,
  1996. struct perf_event_context *ctx,
  1997. enum event_type_t event_type)
  1998. {
  1999. if (!cpuctx->task_ctx)
  2000. return;
  2001. if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
  2002. return;
  2003. ctx_sched_out(ctx, cpuctx, event_type);
  2004. }
  2005. static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
  2006. struct perf_event_context *ctx,
  2007. struct task_struct *task)
  2008. {
  2009. cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
  2010. if (ctx)
  2011. ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
  2012. cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
  2013. if (ctx)
  2014. ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
  2015. }
  2016. /*
  2017. * We want to maintain the following priority of scheduling:
  2018. * - CPU pinned (EVENT_CPU | EVENT_PINNED)
  2019. * - task pinned (EVENT_PINNED)
  2020. * - CPU flexible (EVENT_CPU | EVENT_FLEXIBLE)
  2021. * - task flexible (EVENT_FLEXIBLE).
  2022. *
  2023. * In order to avoid unscheduling and scheduling back in everything every
  2024. * time an event is added, only do it for the groups of equal priority and
  2025. * below.
  2026. *
  2027. * This can be called after a batch operation on task events, in which case
  2028. * event_type is a bit mask of the types of events involved. For CPU events,
  2029. * event_type is only either EVENT_PINNED or EVENT_FLEXIBLE.
  2030. */
  2031. static void ctx_resched(struct perf_cpu_context *cpuctx,
  2032. struct perf_event_context *task_ctx,
  2033. enum event_type_t event_type)
  2034. {
  2035. enum event_type_t ctx_event_type;
  2036. bool cpu_event = !!(event_type & EVENT_CPU);
  2037. /*
  2038. * If pinned groups are involved, flexible groups also need to be
  2039. * scheduled out.
  2040. */
  2041. if (event_type & EVENT_PINNED)
  2042. event_type |= EVENT_FLEXIBLE;
  2043. ctx_event_type = event_type & EVENT_ALL;
  2044. perf_pmu_disable(cpuctx->ctx.pmu);
  2045. if (task_ctx)
  2046. task_ctx_sched_out(cpuctx, task_ctx, event_type);
  2047. /*
  2048. * Decide which cpu ctx groups to schedule out based on the types
  2049. * of events that caused rescheduling:
  2050. * - EVENT_CPU: schedule out corresponding groups;
  2051. * - EVENT_PINNED task events: schedule out EVENT_FLEXIBLE groups;
  2052. * - otherwise, do nothing more.
  2053. */
  2054. if (cpu_event)
  2055. cpu_ctx_sched_out(cpuctx, ctx_event_type);
  2056. else if (ctx_event_type & EVENT_PINNED)
  2057. cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
  2058. perf_event_sched_in(cpuctx, task_ctx, current);
  2059. perf_pmu_enable(cpuctx->ctx.pmu);
  2060. }
  2061. /*
  2062. * Cross CPU call to install and enable a performance event
  2063. *
  2064. * Very similar to remote_function() + event_function() but cannot assume that
  2065. * things like ctx->is_active and cpuctx->task_ctx are set.
  2066. */
  2067. static int __perf_install_in_context(void *info)
  2068. {
  2069. struct perf_event *event = info;
  2070. struct perf_event_context *ctx = event->ctx;
  2071. struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
  2072. struct perf_event_context *task_ctx = cpuctx->task_ctx;
  2073. bool reprogram = true;
  2074. int ret = 0;
  2075. raw_spin_lock(&cpuctx->ctx.lock);
  2076. if (ctx->task) {
  2077. raw_spin_lock(&ctx->lock);
  2078. task_ctx = ctx;
  2079. reprogram = (ctx->task == current);
  2080. /*
  2081. * If the task is running, it must be running on this CPU,
  2082. * otherwise we cannot reprogram things.
  2083. *
  2084. * If its not running, we don't care, ctx->lock will
  2085. * serialize against it becoming runnable.
  2086. */
  2087. if (task_curr(ctx->task) && !reprogram) {
  2088. ret = -ESRCH;
  2089. goto unlock;
  2090. }
  2091. WARN_ON_ONCE(reprogram && cpuctx->task_ctx && cpuctx->task_ctx != ctx);
  2092. } else if (task_ctx) {
  2093. raw_spin_lock(&task_ctx->lock);
  2094. }
  2095. #ifdef CONFIG_CGROUP_PERF
  2096. if (is_cgroup_event(event)) {
  2097. /*
  2098. * If the current cgroup doesn't match the event's
  2099. * cgroup, we should not try to schedule it.
  2100. */
  2101. struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
  2102. reprogram = cgroup_is_descendant(cgrp->css.cgroup,
  2103. event->cgrp->css.cgroup);
  2104. }
  2105. #endif
  2106. if (reprogram) {
  2107. ctx_sched_out(ctx, cpuctx, EVENT_TIME);
  2108. add_event_to_ctx(event, ctx);
  2109. ctx_resched(cpuctx, task_ctx, get_event_type(event));
  2110. } else {
  2111. add_event_to_ctx(event, ctx);
  2112. }
  2113. unlock:
  2114. perf_ctx_unlock(cpuctx, task_ctx);
  2115. return ret;
  2116. }
  2117. /*
  2118. * Attach a performance event to a context.
  2119. *
  2120. * Very similar to event_function_call, see comment there.
  2121. */
  2122. static void
  2123. perf_install_in_context(struct perf_event_context *ctx,
  2124. struct perf_event *event,
  2125. int cpu)
  2126. {
  2127. struct task_struct *task = READ_ONCE(ctx->task);
  2128. lockdep_assert_held(&ctx->mutex);
  2129. if (event->cpu != -1)
  2130. event->cpu = cpu;
  2131. /*
  2132. * Ensures that if we can observe event->ctx, both the event and ctx
  2133. * will be 'complete'. See perf_iterate_sb_cpu().
  2134. */
  2135. smp_store_release(&event->ctx, ctx);
  2136. if (!task) {
  2137. cpu_function_call(cpu, __perf_install_in_context, event);
  2138. return;
  2139. }
  2140. /*
  2141. * Should not happen, we validate the ctx is still alive before calling.
  2142. */
  2143. if (WARN_ON_ONCE(task == TASK_TOMBSTONE))
  2144. return;
  2145. /*
  2146. * Installing events is tricky because we cannot rely on ctx->is_active
  2147. * to be set in case this is the nr_events 0 -> 1 transition.
  2148. *
  2149. * Instead we use task_curr(), which tells us if the task is running.
  2150. * However, since we use task_curr() outside of rq::lock, we can race
  2151. * against the actual state. This means the result can be wrong.
  2152. *
  2153. * If we get a false positive, we retry, this is harmless.
  2154. *
  2155. * If we get a false negative, things are complicated. If we are after
  2156. * perf_event_context_sched_in() ctx::lock will serialize us, and the
  2157. * value must be correct. If we're before, it doesn't matter since
  2158. * perf_event_context_sched_in() will program the counter.
  2159. *
  2160. * However, this hinges on the remote context switch having observed
  2161. * our task->perf_event_ctxp[] store, such that it will in fact take
  2162. * ctx::lock in perf_event_context_sched_in().
  2163. *
  2164. * We do this by task_function_call(), if the IPI fails to hit the task
  2165. * we know any future context switch of task must see the
  2166. * perf_event_ctpx[] store.
  2167. */
  2168. /*
  2169. * This smp_mb() orders the task->perf_event_ctxp[] store with the
  2170. * task_cpu() load, such that if the IPI then does not find the task
  2171. * running, a future context switch of that task must observe the
  2172. * store.
  2173. */
  2174. smp_mb();
  2175. again:
  2176. if (!task_function_call(task, __perf_install_in_context, event))
  2177. return;
  2178. raw_spin_lock_irq(&ctx->lock);
  2179. task = ctx->task;
  2180. if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) {
  2181. /*
  2182. * Cannot happen because we already checked above (which also
  2183. * cannot happen), and we hold ctx->mutex, which serializes us
  2184. * against perf_event_exit_task_context().
  2185. */
  2186. raw_spin_unlock_irq(&ctx->lock);
  2187. return;
  2188. }
  2189. /*
  2190. * If the task is not running, ctx->lock will avoid it becoming so,
  2191. * thus we can safely install the event.
  2192. */
  2193. if (task_curr(task)) {
  2194. raw_spin_unlock_irq(&ctx->lock);
  2195. goto again;
  2196. }
  2197. add_event_to_ctx(event, ctx);
  2198. raw_spin_unlock_irq(&ctx->lock);
  2199. }
  2200. /*
  2201. * Cross CPU call to enable a performance event
  2202. */
  2203. static void __perf_event_enable(struct perf_event *event,
  2204. struct perf_cpu_context *cpuctx,
  2205. struct perf_event_context *ctx,
  2206. void *info)
  2207. {
  2208. struct perf_event *leader = event->group_leader;
  2209. struct perf_event_context *task_ctx;
  2210. if (event->state >= PERF_EVENT_STATE_INACTIVE ||
  2211. event->state <= PERF_EVENT_STATE_ERROR)
  2212. return;
  2213. if (ctx->is_active)
  2214. ctx_sched_out(ctx, cpuctx, EVENT_TIME);
  2215. perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
  2216. if (!ctx->is_active)
  2217. return;
  2218. if (!event_filter_match(event)) {
  2219. ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
  2220. return;
  2221. }
  2222. /*
  2223. * If the event is in a group and isn't the group leader,
  2224. * then don't put it on unless the group is on.
  2225. */
  2226. if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE) {
  2227. ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
  2228. return;
  2229. }
  2230. task_ctx = cpuctx->task_ctx;
  2231. if (ctx->task)
  2232. WARN_ON_ONCE(task_ctx != ctx);
  2233. ctx_resched(cpuctx, task_ctx, get_event_type(event));
  2234. }
  2235. /*
  2236. * Enable an event.
  2237. *
  2238. * If event->ctx is a cloned context, callers must make sure that
  2239. * every task struct that event->ctx->task could possibly point to
  2240. * remains valid. This condition is satisfied when called through
  2241. * perf_event_for_each_child or perf_event_for_each as described
  2242. * for perf_event_disable.
  2243. */
  2244. static void _perf_event_enable(struct perf_event *event)
  2245. {
  2246. struct perf_event_context *ctx = event->ctx;
  2247. raw_spin_lock_irq(&ctx->lock);
  2248. if (event->state >= PERF_EVENT_STATE_INACTIVE ||
  2249. event->state < PERF_EVENT_STATE_ERROR) {
  2250. raw_spin_unlock_irq(&ctx->lock);
  2251. return;
  2252. }
  2253. /*
  2254. * If the event is in error state, clear that first.
  2255. *
  2256. * That way, if we see the event in error state below, we know that it
  2257. * has gone back into error state, as distinct from the task having
  2258. * been scheduled away before the cross-call arrived.
  2259. */
  2260. if (event->state == PERF_EVENT_STATE_ERROR)
  2261. event->state = PERF_EVENT_STATE_OFF;
  2262. raw_spin_unlock_irq(&ctx->lock);
  2263. event_function_call(event, __perf_event_enable, NULL);
  2264. }
  2265. /*
  2266. * See perf_event_disable();
  2267. */
  2268. void perf_event_enable(struct perf_event *event)
  2269. {
  2270. struct perf_event_context *ctx;
  2271. ctx = perf_event_ctx_lock(event);
  2272. _perf_event_enable(event);
  2273. perf_event_ctx_unlock(event, ctx);
  2274. }
  2275. EXPORT_SYMBOL_GPL(perf_event_enable);
  2276. struct stop_event_data {
  2277. struct perf_event *event;
  2278. unsigned int restart;
  2279. };
  2280. static int __perf_event_stop(void *info)
  2281. {
  2282. struct stop_event_data *sd = info;
  2283. struct perf_event *event = sd->event;
  2284. /* if it's already INACTIVE, do nothing */
  2285. if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
  2286. return 0;
  2287. /* matches smp_wmb() in event_sched_in() */
  2288. smp_rmb();
  2289. /*
  2290. * There is a window with interrupts enabled before we get here,
  2291. * so we need to check again lest we try to stop another CPU's event.
  2292. */
  2293. if (READ_ONCE(event->oncpu) != smp_processor_id())
  2294. return -EAGAIN;
  2295. event->pmu->stop(event, PERF_EF_UPDATE);
  2296. /*
  2297. * May race with the actual stop (through perf_pmu_output_stop()),
  2298. * but it is only used for events with AUX ring buffer, and such
  2299. * events will refuse to restart because of rb::aux_mmap_count==0,
  2300. * see comments in perf_aux_output_begin().
  2301. *
  2302. * Since this is happening on an event-local CPU, no trace is lost
  2303. * while restarting.
  2304. */
  2305. if (sd->restart)
  2306. event->pmu->start(event, 0);
  2307. return 0;
  2308. }
  2309. static int perf_event_stop(struct perf_event *event, int restart)
  2310. {
  2311. struct stop_event_data sd = {
  2312. .event = event,
  2313. .restart = restart,
  2314. };
  2315. int ret = 0;
  2316. do {
  2317. if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
  2318. return 0;
  2319. /* matches smp_wmb() in event_sched_in() */
  2320. smp_rmb();
  2321. /*
  2322. * We only want to restart ACTIVE events, so if the event goes
  2323. * inactive here (event->oncpu==-1), there's nothing more to do;
  2324. * fall through with ret==-ENXIO.
  2325. */
  2326. ret = cpu_function_call(READ_ONCE(event->oncpu),
  2327. __perf_event_stop, &sd);
  2328. } while (ret == -EAGAIN);
  2329. return ret;
  2330. }
  2331. /*
  2332. * In order to contain the amount of racy and tricky in the address filter
  2333. * configuration management, it is a two part process:
  2334. *
  2335. * (p1) when userspace mappings change as a result of (1) or (2) or (3) below,
  2336. * we update the addresses of corresponding vmas in
  2337. * event::addr_filters_offs array and bump the event::addr_filters_gen;
  2338. * (p2) when an event is scheduled in (pmu::add), it calls
  2339. * perf_event_addr_filters_sync() which calls pmu::addr_filters_sync()
  2340. * if the generation has changed since the previous call.
  2341. *
  2342. * If (p1) happens while the event is active, we restart it to force (p2).
  2343. *
  2344. * (1) perf_addr_filters_apply(): adjusting filters' offsets based on
  2345. * pre-existing mappings, called once when new filters arrive via SET_FILTER
  2346. * ioctl;
  2347. * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly
  2348. * registered mapping, called for every new mmap(), with mm::mmap_sem down
  2349. * for reading;
  2350. * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process
  2351. * of exec.
  2352. */
  2353. void perf_event_addr_filters_sync(struct perf_event *event)
  2354. {
  2355. struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
  2356. if (!has_addr_filter(event))
  2357. return;
  2358. raw_spin_lock(&ifh->lock);
  2359. if (event->addr_filters_gen != event->hw.addr_filters_gen) {
  2360. event->pmu->addr_filters_sync(event);
  2361. event->hw.addr_filters_gen = event->addr_filters_gen;
  2362. }
  2363. raw_spin_unlock(&ifh->lock);
  2364. }
  2365. EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync);
  2366. static int _perf_event_refresh(struct perf_event *event, int refresh)
  2367. {
  2368. /*
  2369. * not supported on inherited events
  2370. */
  2371. if (event->attr.inherit || !is_sampling_event(event))
  2372. return -EINVAL;
  2373. atomic_add(refresh, &event->event_limit);
  2374. _perf_event_enable(event);
  2375. return 0;
  2376. }
  2377. /*
  2378. * See perf_event_disable()
  2379. */
  2380. int perf_event_refresh(struct perf_event *event, int refresh)
  2381. {
  2382. struct perf_event_context *ctx;
  2383. int ret;
  2384. ctx = perf_event_ctx_lock(event);
  2385. ret = _perf_event_refresh(event, refresh);
  2386. perf_event_ctx_unlock(event, ctx);
  2387. return ret;
  2388. }
  2389. EXPORT_SYMBOL_GPL(perf_event_refresh);
  2390. static int perf_event_modify_breakpoint(struct perf_event *bp,
  2391. struct perf_event_attr *attr)
  2392. {
  2393. int err;
  2394. _perf_event_disable(bp);
  2395. err = modify_user_hw_breakpoint_check(bp, attr, true);
  2396. if (!bp->attr.disabled)
  2397. _perf_event_enable(bp);
  2398. return err;
  2399. }
  2400. static int perf_event_modify_attr(struct perf_event *event,
  2401. struct perf_event_attr *attr)
  2402. {
  2403. if (event->attr.type != attr->type)
  2404. return -EINVAL;
  2405. switch (event->attr.type) {
  2406. case PERF_TYPE_BREAKPOINT:
  2407. return perf_event_modify_breakpoint(event, attr);
  2408. default:
  2409. /* Place holder for future additions. */
  2410. return -EOPNOTSUPP;
  2411. }
  2412. }
  2413. static void ctx_sched_out(struct perf_event_context *ctx,
  2414. struct perf_cpu_context *cpuctx,
  2415. enum event_type_t event_type)
  2416. {
  2417. struct perf_event *event, *tmp;
  2418. int is_active = ctx->is_active;
  2419. lockdep_assert_held(&ctx->lock);
  2420. if (likely(!ctx->nr_events)) {
  2421. /*
  2422. * See __perf_remove_from_context().
  2423. */
  2424. WARN_ON_ONCE(ctx->is_active);
  2425. if (ctx->task)
  2426. WARN_ON_ONCE(cpuctx->task_ctx);
  2427. return;
  2428. }
  2429. ctx->is_active &= ~event_type;
  2430. if (!(ctx->is_active & EVENT_ALL))
  2431. ctx->is_active = 0;
  2432. if (ctx->task) {
  2433. WARN_ON_ONCE(cpuctx->task_ctx != ctx);
  2434. if (!ctx->is_active)
  2435. cpuctx->task_ctx = NULL;
  2436. }
  2437. /*
  2438. * Always update time if it was set; not only when it changes.
  2439. * Otherwise we can 'forget' to update time for any but the last
  2440. * context we sched out. For example:
  2441. *
  2442. * ctx_sched_out(.event_type = EVENT_FLEXIBLE)
  2443. * ctx_sched_out(.event_type = EVENT_PINNED)
  2444. *
  2445. * would only update time for the pinned events.
  2446. */
  2447. if (is_active & EVENT_TIME) {
  2448. /* update (and stop) ctx time */
  2449. update_context_time(ctx);
  2450. update_cgrp_time_from_cpuctx(cpuctx);
  2451. }
  2452. is_active ^= ctx->is_active; /* changed bits */
  2453. if (!ctx->nr_active || !(is_active & EVENT_ALL))
  2454. return;
  2455. perf_pmu_disable(ctx->pmu);
  2456. if (is_active & EVENT_PINNED) {
  2457. list_for_each_entry_safe(event, tmp, &ctx->pinned_active, active_list)
  2458. group_sched_out(event, cpuctx, ctx);
  2459. }
  2460. if (is_active & EVENT_FLEXIBLE) {
  2461. list_for_each_entry_safe(event, tmp, &ctx->flexible_active, active_list)
  2462. group_sched_out(event, cpuctx, ctx);
  2463. }
  2464. perf_pmu_enable(ctx->pmu);
  2465. }
  2466. /*
  2467. * Test whether two contexts are equivalent, i.e. whether they have both been
  2468. * cloned from the same version of the same context.
  2469. *
  2470. * Equivalence is measured using a generation number in the context that is
  2471. * incremented on each modification to it; see unclone_ctx(), list_add_event()
  2472. * and list_del_event().
  2473. */
  2474. static int context_equiv(struct perf_event_context *ctx1,
  2475. struct perf_event_context *ctx2)
  2476. {
  2477. lockdep_assert_held(&ctx1->lock);
  2478. lockdep_assert_held(&ctx2->lock);
  2479. /* Pinning disables the swap optimization */
  2480. if (ctx1->pin_count || ctx2->pin_count)
  2481. return 0;
  2482. /* If ctx1 is the parent of ctx2 */
  2483. if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
  2484. return 1;
  2485. /* If ctx2 is the parent of ctx1 */
  2486. if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
  2487. return 1;
  2488. /*
  2489. * If ctx1 and ctx2 have the same parent; we flatten the parent
  2490. * hierarchy, see perf_event_init_context().
  2491. */
  2492. if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
  2493. ctx1->parent_gen == ctx2->parent_gen)
  2494. return 1;
  2495. /* Unmatched */
  2496. return 0;
  2497. }
  2498. static void __perf_event_sync_stat(struct perf_event *event,
  2499. struct perf_event *next_event)
  2500. {
  2501. u64 value;
  2502. if (!event->attr.inherit_stat)
  2503. return;
  2504. /*
  2505. * Update the event value, we cannot use perf_event_read()
  2506. * because we're in the middle of a context switch and have IRQs
  2507. * disabled, which upsets smp_call_function_single(), however
  2508. * we know the event must be on the current CPU, therefore we
  2509. * don't need to use it.
  2510. */
  2511. if (event->state == PERF_EVENT_STATE_ACTIVE)
  2512. event->pmu->read(event);
  2513. perf_event_update_time(event);
  2514. /*
  2515. * In order to keep per-task stats reliable we need to flip the event
  2516. * values when we flip the contexts.
  2517. */
  2518. value = local64_read(&next_event->count);
  2519. value = local64_xchg(&event->count, value);
  2520. local64_set(&next_event->count, value);
  2521. swap(event->total_time_enabled, next_event->total_time_enabled);
  2522. swap(event->total_time_running, next_event->total_time_running);
  2523. /*
  2524. * Since we swizzled the values, update the user visible data too.
  2525. */
  2526. perf_event_update_userpage(event);
  2527. perf_event_update_userpage(next_event);
  2528. }
  2529. static void perf_event_sync_stat(struct perf_event_context *ctx,
  2530. struct perf_event_context *next_ctx)
  2531. {
  2532. struct perf_event *event, *next_event;
  2533. if (!ctx->nr_stat)
  2534. return;
  2535. update_context_time(ctx);
  2536. event = list_first_entry(&ctx->event_list,
  2537. struct perf_event, event_entry);
  2538. next_event = list_first_entry(&next_ctx->event_list,
  2539. struct perf_event, event_entry);
  2540. while (&event->event_entry != &ctx->event_list &&
  2541. &next_event->event_entry != &next_ctx->event_list) {
  2542. __perf_event_sync_stat(event, next_event);
  2543. event = list_next_entry(event, event_entry);
  2544. next_event = list_next_entry(next_event, event_entry);
  2545. }
  2546. }
  2547. static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
  2548. struct task_struct *next)
  2549. {
  2550. struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
  2551. struct perf_event_context *next_ctx;
  2552. struct perf_event_context *parent, *next_parent;
  2553. struct perf_cpu_context *cpuctx;
  2554. int do_switch = 1;
  2555. if (likely(!ctx))
  2556. return;
  2557. cpuctx = __get_cpu_context(ctx);
  2558. if (!cpuctx->task_ctx)
  2559. return;
  2560. rcu_read_lock();
  2561. next_ctx = next->perf_event_ctxp[ctxn];
  2562. if (!next_ctx)
  2563. goto unlock;
  2564. parent = rcu_dereference(ctx->parent_ctx);
  2565. next_parent = rcu_dereference(next_ctx->parent_ctx);
  2566. /* If neither context have a parent context; they cannot be clones. */
  2567. if (!parent && !next_parent)
  2568. goto unlock;
  2569. if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
  2570. /*
  2571. * Looks like the two contexts are clones, so we might be
  2572. * able to optimize the context switch. We lock both
  2573. * contexts and check that they are clones under the
  2574. * lock (including re-checking that neither has been
  2575. * uncloned in the meantime). It doesn't matter which
  2576. * order we take the locks because no other cpu could
  2577. * be trying to lock both of these tasks.
  2578. */
  2579. raw_spin_lock(&ctx->lock);
  2580. raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
  2581. if (context_equiv(ctx, next_ctx)) {
  2582. WRITE_ONCE(ctx->task, next);
  2583. WRITE_ONCE(next_ctx->task, task);
  2584. swap(ctx->task_ctx_data, next_ctx->task_ctx_data);
  2585. /*
  2586. * RCU_INIT_POINTER here is safe because we've not
  2587. * modified the ctx and the above modification of
  2588. * ctx->task and ctx->task_ctx_data are immaterial
  2589. * since those values are always verified under
  2590. * ctx->lock which we're now holding.
  2591. */
  2592. RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], next_ctx);
  2593. RCU_INIT_POINTER(next->perf_event_ctxp[ctxn], ctx);
  2594. do_switch = 0;
  2595. perf_event_sync_stat(ctx, next_ctx);
  2596. }
  2597. raw_spin_unlock(&next_ctx->lock);
  2598. raw_spin_unlock(&ctx->lock);
  2599. }
  2600. unlock:
  2601. rcu_read_unlock();
  2602. if (do_switch) {
  2603. raw_spin_lock(&ctx->lock);
  2604. task_ctx_sched_out(cpuctx, ctx, EVENT_ALL);
  2605. raw_spin_unlock(&ctx->lock);
  2606. }
  2607. }
  2608. static DEFINE_PER_CPU(struct list_head, sched_cb_list);
  2609. void perf_sched_cb_dec(struct pmu *pmu)
  2610. {
  2611. struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
  2612. this_cpu_dec(perf_sched_cb_usages);
  2613. if (!--cpuctx->sched_cb_usage)
  2614. list_del(&cpuctx->sched_cb_entry);
  2615. }
  2616. void perf_sched_cb_inc(struct pmu *pmu)
  2617. {
  2618. struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
  2619. if (!cpuctx->sched_cb_usage++)
  2620. list_add(&cpuctx->sched_cb_entry, this_cpu_ptr(&sched_cb_list));
  2621. this_cpu_inc(perf_sched_cb_usages);
  2622. }
  2623. /*
  2624. * This function provides the context switch callback to the lower code
  2625. * layer. It is invoked ONLY when the context switch callback is enabled.
  2626. *
  2627. * This callback is relevant even to per-cpu events; for example multi event
  2628. * PEBS requires this to provide PID/TID information. This requires we flush
  2629. * all queued PEBS records before we context switch to a new task.
  2630. */
  2631. static void perf_pmu_sched_task(struct task_struct *prev,
  2632. struct task_struct *next,
  2633. bool sched_in)
  2634. {
  2635. struct perf_cpu_context *cpuctx;
  2636. struct pmu *pmu;
  2637. if (prev == next)
  2638. return;
  2639. list_for_each_entry(cpuctx, this_cpu_ptr(&sched_cb_list), sched_cb_entry) {
  2640. pmu = cpuctx->ctx.pmu; /* software PMUs will not have sched_task */
  2641. if (WARN_ON_ONCE(!pmu->sched_task))
  2642. continue;
  2643. perf_ctx_lock(cpuctx, cpuctx->task_ctx);
  2644. perf_pmu_disable(pmu);
  2645. pmu->sched_task(cpuctx->task_ctx, sched_in);
  2646. perf_pmu_enable(pmu);
  2647. perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
  2648. }
  2649. }
  2650. static void perf_event_switch(struct task_struct *task,
  2651. struct task_struct *next_prev, bool sched_in);
  2652. #define for_each_task_context_nr(ctxn) \
  2653. for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
  2654. /*
  2655. * Called from scheduler to remove the events of the current task,
  2656. * with interrupts disabled.
  2657. *
  2658. * We stop each event and update the event value in event->count.
  2659. *
  2660. * This does not protect us against NMI, but disable()
  2661. * sets the disabled bit in the control field of event _before_
  2662. * accessing the event control register. If a NMI hits, then it will
  2663. * not restart the event.
  2664. */
  2665. void __perf_event_task_sched_out(struct task_struct *task,
  2666. struct task_struct *next)
  2667. {
  2668. int ctxn;
  2669. if (__this_cpu_read(perf_sched_cb_usages))
  2670. perf_pmu_sched_task(task, next, false);
  2671. if (atomic_read(&nr_switch_events))
  2672. perf_event_switch(task, next, false);
  2673. for_each_task_context_nr(ctxn)
  2674. perf_event_context_sched_out(task, ctxn, next);
  2675. /*
  2676. * if cgroup events exist on this CPU, then we need
  2677. * to check if we have to switch out PMU state.
  2678. * cgroup event are system-wide mode only
  2679. */
  2680. if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
  2681. perf_cgroup_sched_out(task, next);
  2682. }
  2683. /*
  2684. * Called with IRQs disabled
  2685. */
  2686. static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
  2687. enum event_type_t event_type)
  2688. {
  2689. ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
  2690. }
  2691. static int visit_groups_merge(struct perf_event_groups *groups, int cpu,
  2692. int (*func)(struct perf_event *, void *), void *data)
  2693. {
  2694. struct perf_event **evt, *evt1, *evt2;
  2695. int ret;
  2696. evt1 = perf_event_groups_first(groups, -1);
  2697. evt2 = perf_event_groups_first(groups, cpu);
  2698. while (evt1 || evt2) {
  2699. if (evt1 && evt2) {
  2700. if (evt1->group_index < evt2->group_index)
  2701. evt = &evt1;
  2702. else
  2703. evt = &evt2;
  2704. } else if (evt1) {
  2705. evt = &evt1;
  2706. } else {
  2707. evt = &evt2;
  2708. }
  2709. ret = func(*evt, data);
  2710. if (ret)
  2711. return ret;
  2712. *evt = perf_event_groups_next(*evt);
  2713. }
  2714. return 0;
  2715. }
  2716. struct sched_in_data {
  2717. struct perf_event_context *ctx;
  2718. struct perf_cpu_context *cpuctx;
  2719. int can_add_hw;
  2720. };
  2721. static int pinned_sched_in(struct perf_event *event, void *data)
  2722. {
  2723. struct sched_in_data *sid = data;
  2724. if (event->state <= PERF_EVENT_STATE_OFF)
  2725. return 0;
  2726. if (!event_filter_match(event))
  2727. return 0;
  2728. if (group_can_go_on(event, sid->cpuctx, sid->can_add_hw)) {
  2729. if (!group_sched_in(event, sid->cpuctx, sid->ctx))
  2730. list_add_tail(&event->active_list, &sid->ctx->pinned_active);
  2731. }
  2732. /*
  2733. * If this pinned group hasn't been scheduled,
  2734. * put it in error state.
  2735. */
  2736. if (event->state == PERF_EVENT_STATE_INACTIVE)
  2737. perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
  2738. return 0;
  2739. }
  2740. static int flexible_sched_in(struct perf_event *event, void *data)
  2741. {
  2742. struct sched_in_data *sid = data;
  2743. if (event->state <= PERF_EVENT_STATE_OFF)
  2744. return 0;
  2745. if (!event_filter_match(event))
  2746. return 0;
  2747. if (group_can_go_on(event, sid->cpuctx, sid->can_add_hw)) {
  2748. if (!group_sched_in(event, sid->cpuctx, sid->ctx))
  2749. list_add_tail(&event->active_list, &sid->ctx->flexible_active);
  2750. else
  2751. sid->can_add_hw = 0;
  2752. }
  2753. return 0;
  2754. }
  2755. static void
  2756. ctx_pinned_sched_in(struct perf_event_context *ctx,
  2757. struct perf_cpu_context *cpuctx)
  2758. {
  2759. struct sched_in_data sid = {
  2760. .ctx = ctx,
  2761. .cpuctx = cpuctx,
  2762. .can_add_hw = 1,
  2763. };
  2764. visit_groups_merge(&ctx->pinned_groups,
  2765. smp_processor_id(),
  2766. pinned_sched_in, &sid);
  2767. }
  2768. static void
  2769. ctx_flexible_sched_in(struct perf_event_context *ctx,
  2770. struct perf_cpu_context *cpuctx)
  2771. {
  2772. struct sched_in_data sid = {
  2773. .ctx = ctx,
  2774. .cpuctx = cpuctx,
  2775. .can_add_hw = 1,
  2776. };
  2777. visit_groups_merge(&ctx->flexible_groups,
  2778. smp_processor_id(),
  2779. flexible_sched_in, &sid);
  2780. }
  2781. static void
  2782. ctx_sched_in(struct perf_event_context *ctx,
  2783. struct perf_cpu_context *cpuctx,
  2784. enum event_type_t event_type,
  2785. struct task_struct *task)
  2786. {
  2787. int is_active = ctx->is_active;
  2788. u64 now;
  2789. lockdep_assert_held(&ctx->lock);
  2790. if (likely(!ctx->nr_events))
  2791. return;
  2792. ctx->is_active |= (event_type | EVENT_TIME);
  2793. if (ctx->task) {
  2794. if (!is_active)
  2795. cpuctx->task_ctx = ctx;
  2796. else
  2797. WARN_ON_ONCE(cpuctx->task_ctx != ctx);
  2798. }
  2799. is_active ^= ctx->is_active; /* changed bits */
  2800. if (is_active & EVENT_TIME) {
  2801. /* start ctx time */
  2802. now = perf_clock();
  2803. ctx->timestamp = now;
  2804. perf_cgroup_set_timestamp(task, ctx);
  2805. }
  2806. /*
  2807. * First go through the list and put on any pinned groups
  2808. * in order to give them the best chance of going on.
  2809. */
  2810. if (is_active & EVENT_PINNED)
  2811. ctx_pinned_sched_in(ctx, cpuctx);
  2812. /* Then walk through the lower prio flexible groups */
  2813. if (is_active & EVENT_FLEXIBLE)
  2814. ctx_flexible_sched_in(ctx, cpuctx);
  2815. }
  2816. static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
  2817. enum event_type_t event_type,
  2818. struct task_struct *task)
  2819. {
  2820. struct perf_event_context *ctx = &cpuctx->ctx;
  2821. ctx_sched_in(ctx, cpuctx, event_type, task);
  2822. }
  2823. static void perf_event_context_sched_in(struct perf_event_context *ctx,
  2824. struct task_struct *task)
  2825. {
  2826. struct perf_cpu_context *cpuctx;
  2827. cpuctx = __get_cpu_context(ctx);
  2828. if (cpuctx->task_ctx == ctx)
  2829. return;
  2830. perf_ctx_lock(cpuctx, ctx);
  2831. /*
  2832. * We must check ctx->nr_events while holding ctx->lock, such
  2833. * that we serialize against perf_install_in_context().
  2834. */
  2835. if (!ctx->nr_events)
  2836. goto unlock;
  2837. perf_pmu_disable(ctx->pmu);
  2838. /*
  2839. * We want to keep the following priority order:
  2840. * cpu pinned (that don't need to move), task pinned,
  2841. * cpu flexible, task flexible.
  2842. *
  2843. * However, if task's ctx is not carrying any pinned
  2844. * events, no need to flip the cpuctx's events around.
  2845. */
  2846. if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree))
  2847. cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
  2848. perf_event_sched_in(cpuctx, ctx, task);
  2849. perf_pmu_enable(ctx->pmu);
  2850. unlock:
  2851. perf_ctx_unlock(cpuctx, ctx);
  2852. }
  2853. /*
  2854. * Called from scheduler to add the events of the current task
  2855. * with interrupts disabled.
  2856. *
  2857. * We restore the event value and then enable it.
  2858. *
  2859. * This does not protect us against NMI, but enable()
  2860. * sets the enabled bit in the control field of event _before_
  2861. * accessing the event control register. If a NMI hits, then it will
  2862. * keep the event running.
  2863. */
  2864. void __perf_event_task_sched_in(struct task_struct *prev,
  2865. struct task_struct *task)
  2866. {
  2867. struct perf_event_context *ctx;
  2868. int ctxn;
  2869. /*
  2870. * If cgroup events exist on this CPU, then we need to check if we have
  2871. * to switch in PMU state; cgroup event are system-wide mode only.
  2872. *
  2873. * Since cgroup events are CPU events, we must schedule these in before
  2874. * we schedule in the task events.
  2875. */
  2876. if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
  2877. perf_cgroup_sched_in(prev, task);
  2878. for_each_task_context_nr(ctxn) {
  2879. ctx = task->perf_event_ctxp[ctxn];
  2880. if (likely(!ctx))
  2881. continue;
  2882. perf_event_context_sched_in(ctx, task);
  2883. }
  2884. if (atomic_read(&nr_switch_events))
  2885. perf_event_switch(task, prev, true);
  2886. if (__this_cpu_read(perf_sched_cb_usages))
  2887. perf_pmu_sched_task(prev, task, true);
  2888. }
  2889. static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
  2890. {
  2891. u64 frequency = event->attr.sample_freq;
  2892. u64 sec = NSEC_PER_SEC;
  2893. u64 divisor, dividend;
  2894. int count_fls, nsec_fls, frequency_fls, sec_fls;
  2895. count_fls = fls64(count);
  2896. nsec_fls = fls64(nsec);
  2897. frequency_fls = fls64(frequency);
  2898. sec_fls = 30;
  2899. /*
  2900. * We got @count in @nsec, with a target of sample_freq HZ
  2901. * the target period becomes:
  2902. *
  2903. * @count * 10^9
  2904. * period = -------------------
  2905. * @nsec * sample_freq
  2906. *
  2907. */
  2908. /*
  2909. * Reduce accuracy by one bit such that @a and @b converge
  2910. * to a similar magnitude.
  2911. */
  2912. #define REDUCE_FLS(a, b) \
  2913. do { \
  2914. if (a##_fls > b##_fls) { \
  2915. a >>= 1; \
  2916. a##_fls--; \
  2917. } else { \
  2918. b >>= 1; \
  2919. b##_fls--; \
  2920. } \
  2921. } while (0)
  2922. /*
  2923. * Reduce accuracy until either term fits in a u64, then proceed with
  2924. * the other, so that finally we can do a u64/u64 division.
  2925. */
  2926. while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
  2927. REDUCE_FLS(nsec, frequency);
  2928. REDUCE_FLS(sec, count);
  2929. }
  2930. if (count_fls + sec_fls > 64) {
  2931. divisor = nsec * frequency;
  2932. while (count_fls + sec_fls > 64) {
  2933. REDUCE_FLS(count, sec);
  2934. divisor >>= 1;
  2935. }
  2936. dividend = count * sec;
  2937. } else {
  2938. dividend = count * sec;
  2939. while (nsec_fls + frequency_fls > 64) {
  2940. REDUCE_FLS(nsec, frequency);
  2941. dividend >>= 1;
  2942. }
  2943. divisor = nsec * frequency;
  2944. }
  2945. if (!divisor)
  2946. return dividend;
  2947. return div64_u64(dividend, divisor);
  2948. }
  2949. static DEFINE_PER_CPU(int, perf_throttled_count);
  2950. static DEFINE_PER_CPU(u64, perf_throttled_seq);
  2951. static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
  2952. {
  2953. struct hw_perf_event *hwc = &event->hw;
  2954. s64 period, sample_period;
  2955. s64 delta;
  2956. period = perf_calculate_period(event, nsec, count);
  2957. delta = (s64)(period - hwc->sample_period);
  2958. delta = (delta + 7) / 8; /* low pass filter */
  2959. sample_period = hwc->sample_period + delta;
  2960. if (!sample_period)
  2961. sample_period = 1;
  2962. hwc->sample_period = sample_period;
  2963. if (local64_read(&hwc->period_left) > 8*sample_period) {
  2964. if (disable)
  2965. event->pmu->stop(event, PERF_EF_UPDATE);
  2966. local64_set(&hwc->period_left, 0);
  2967. if (disable)
  2968. event->pmu->start(event, PERF_EF_RELOAD);
  2969. }
  2970. }
  2971. /*
  2972. * combine freq adjustment with unthrottling to avoid two passes over the
  2973. * events. At the same time, make sure, having freq events does not change
  2974. * the rate of unthrottling as that would introduce bias.
  2975. */
  2976. static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
  2977. int needs_unthr)
  2978. {
  2979. struct perf_event *event;
  2980. struct hw_perf_event *hwc;
  2981. u64 now, period = TICK_NSEC;
  2982. s64 delta;
  2983. /*
  2984. * only need to iterate over all events iff:
  2985. * - context have events in frequency mode (needs freq adjust)
  2986. * - there are events to unthrottle on this cpu
  2987. */
  2988. if (!(ctx->nr_freq || needs_unthr))
  2989. return;
  2990. raw_spin_lock(&ctx->lock);
  2991. perf_pmu_disable(ctx->pmu);
  2992. list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
  2993. if (event->state != PERF_EVENT_STATE_ACTIVE)
  2994. continue;
  2995. if (!event_filter_match(event))
  2996. continue;
  2997. perf_pmu_disable(event->pmu);
  2998. hwc = &event->hw;
  2999. if (hwc->interrupts == MAX_INTERRUPTS) {
  3000. hwc->interrupts = 0;
  3001. perf_log_throttle(event, 1);
  3002. event->pmu->start(event, 0);
  3003. }
  3004. if (!event->attr.freq || !event->attr.sample_freq)
  3005. goto next;
  3006. /*
  3007. * stop the event and update event->count
  3008. */
  3009. event->pmu->stop(event, PERF_EF_UPDATE);
  3010. now = local64_read(&event->count);
  3011. delta = now - hwc->freq_count_stamp;
  3012. hwc->freq_count_stamp = now;
  3013. /*
  3014. * restart the event
  3015. * reload only if value has changed
  3016. * we have stopped the event so tell that
  3017. * to perf_adjust_period() to avoid stopping it
  3018. * twice.
  3019. */
  3020. if (delta > 0)
  3021. perf_adjust_period(event, period, delta, false);
  3022. event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
  3023. next:
  3024. perf_pmu_enable(event->pmu);
  3025. }
  3026. perf_pmu_enable(ctx->pmu);
  3027. raw_spin_unlock(&ctx->lock);
  3028. }
  3029. /*
  3030. * Move @event to the tail of the @ctx's elegible events.
  3031. */
  3032. static void rotate_ctx(struct perf_event_context *ctx, struct perf_event *event)
  3033. {
  3034. /*
  3035. * Rotate the first entry last of non-pinned groups. Rotation might be
  3036. * disabled by the inheritance code.
  3037. */
  3038. if (ctx->rotate_disable)
  3039. return;
  3040. perf_event_groups_delete(&ctx->flexible_groups, event);
  3041. perf_event_groups_insert(&ctx->flexible_groups, event);
  3042. }
  3043. static inline struct perf_event *
  3044. ctx_first_active(struct perf_event_context *ctx)
  3045. {
  3046. return list_first_entry_or_null(&ctx->flexible_active,
  3047. struct perf_event, active_list);
  3048. }
  3049. static bool perf_rotate_context(struct perf_cpu_context *cpuctx)
  3050. {
  3051. struct perf_event *cpu_event = NULL, *task_event = NULL;
  3052. bool cpu_rotate = false, task_rotate = false;
  3053. struct perf_event_context *ctx = NULL;
  3054. /*
  3055. * Since we run this from IRQ context, nobody can install new
  3056. * events, thus the event count values are stable.
  3057. */
  3058. if (cpuctx->ctx.nr_events) {
  3059. if (cpuctx->ctx.nr_events != cpuctx->ctx.nr_active)
  3060. cpu_rotate = true;
  3061. }
  3062. ctx = cpuctx->task_ctx;
  3063. if (ctx && ctx->nr_events) {
  3064. if (ctx->nr_events != ctx->nr_active)
  3065. task_rotate = true;
  3066. }
  3067. if (!(cpu_rotate || task_rotate))
  3068. return false;
  3069. perf_ctx_lock(cpuctx, cpuctx->task_ctx);
  3070. perf_pmu_disable(cpuctx->ctx.pmu);
  3071. if (task_rotate)
  3072. task_event = ctx_first_active(ctx);
  3073. if (cpu_rotate)
  3074. cpu_event = ctx_first_active(&cpuctx->ctx);
  3075. /*
  3076. * As per the order given at ctx_resched() first 'pop' task flexible
  3077. * and then, if needed CPU flexible.
  3078. */
  3079. if (task_event || (ctx && cpu_event))
  3080. ctx_sched_out(ctx, cpuctx, EVENT_FLEXIBLE);
  3081. if (cpu_event)
  3082. cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
  3083. if (task_event)
  3084. rotate_ctx(ctx, task_event);
  3085. if (cpu_event)
  3086. rotate_ctx(&cpuctx->ctx, cpu_event);
  3087. perf_event_sched_in(cpuctx, ctx, current);
  3088. perf_pmu_enable(cpuctx->ctx.pmu);
  3089. perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
  3090. return true;
  3091. }
  3092. void perf_event_task_tick(void)
  3093. {
  3094. struct list_head *head = this_cpu_ptr(&active_ctx_list);
  3095. struct perf_event_context *ctx, *tmp;
  3096. int throttled;
  3097. lockdep_assert_irqs_disabled();
  3098. __this_cpu_inc(perf_throttled_seq);
  3099. throttled = __this_cpu_xchg(perf_throttled_count, 0);
  3100. tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
  3101. list_for_each_entry_safe(ctx, tmp, head, active_ctx_list)
  3102. perf_adjust_freq_unthr_context(ctx, throttled);
  3103. }
  3104. static int event_enable_on_exec(struct perf_event *event,
  3105. struct perf_event_context *ctx)
  3106. {
  3107. if (!event->attr.enable_on_exec)
  3108. return 0;
  3109. event->attr.enable_on_exec = 0;
  3110. if (event->state >= PERF_EVENT_STATE_INACTIVE)
  3111. return 0;
  3112. perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
  3113. return 1;
  3114. }
  3115. /*
  3116. * Enable all of a task's events that have been marked enable-on-exec.
  3117. * This expects task == current.
  3118. */
  3119. static void perf_event_enable_on_exec(int ctxn)
  3120. {
  3121. struct perf_event_context *ctx, *clone_ctx = NULL;
  3122. enum event_type_t event_type = 0;
  3123. struct perf_cpu_context *cpuctx;
  3124. struct perf_event *event;
  3125. unsigned long flags;
  3126. int enabled = 0;
  3127. local_irq_save(flags);
  3128. ctx = current->perf_event_ctxp[ctxn];
  3129. if (!ctx || !ctx->nr_events)
  3130. goto out;
  3131. cpuctx = __get_cpu_context(ctx);
  3132. perf_ctx_lock(cpuctx, ctx);
  3133. ctx_sched_out(ctx, cpuctx, EVENT_TIME);
  3134. list_for_each_entry(event, &ctx->event_list, event_entry) {
  3135. enabled |= event_enable_on_exec(event, ctx);
  3136. event_type |= get_event_type(event);
  3137. }
  3138. /*
  3139. * Unclone and reschedule this context if we enabled any event.
  3140. */
  3141. if (enabled) {
  3142. clone_ctx = unclone_ctx(ctx);
  3143. ctx_resched(cpuctx, ctx, event_type);
  3144. } else {
  3145. ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
  3146. }
  3147. perf_ctx_unlock(cpuctx, ctx);
  3148. out:
  3149. local_irq_restore(flags);
  3150. if (clone_ctx)
  3151. put_ctx(clone_ctx);
  3152. }
  3153. struct perf_read_data {
  3154. struct perf_event *event;
  3155. bool group;
  3156. int ret;
  3157. };
  3158. static int __perf_event_read_cpu(struct perf_event *event, int event_cpu)
  3159. {
  3160. u16 local_pkg, event_pkg;
  3161. if (event->group_caps & PERF_EV_CAP_READ_ACTIVE_PKG) {
  3162. int local_cpu = smp_processor_id();
  3163. event_pkg = topology_physical_package_id(event_cpu);
  3164. local_pkg = topology_physical_package_id(local_cpu);
  3165. if (event_pkg == local_pkg)
  3166. return local_cpu;
  3167. }
  3168. return event_cpu;
  3169. }
  3170. /*
  3171. * Cross CPU call to read the hardware event
  3172. */
  3173. static void __perf_event_read(void *info)
  3174. {
  3175. struct perf_read_data *data = info;
  3176. struct perf_event *sub, *event = data->event;
  3177. struct perf_event_context *ctx = event->ctx;
  3178. struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
  3179. struct pmu *pmu = event->pmu;
  3180. /*
  3181. * If this is a task context, we need to check whether it is
  3182. * the current task context of this cpu. If not it has been
  3183. * scheduled out before the smp call arrived. In that case
  3184. * event->count would have been updated to a recent sample
  3185. * when the event was scheduled out.
  3186. */
  3187. if (ctx->task && cpuctx->task_ctx != ctx)
  3188. return;
  3189. raw_spin_lock(&ctx->lock);
  3190. if (ctx->is_active & EVENT_TIME) {
  3191. update_context_time(ctx);
  3192. update_cgrp_time_from_event(event);
  3193. }
  3194. perf_event_update_time(event);
  3195. if (data->group)
  3196. perf_event_update_sibling_time(event);
  3197. if (event->state != PERF_EVENT_STATE_ACTIVE)
  3198. goto unlock;
  3199. if (!data->group) {
  3200. pmu->read(event);
  3201. data->ret = 0;
  3202. goto unlock;
  3203. }
  3204. pmu->start_txn(pmu, PERF_PMU_TXN_READ);
  3205. pmu->read(event);
  3206. for_each_sibling_event(sub, event) {
  3207. if (sub->state == PERF_EVENT_STATE_ACTIVE) {
  3208. /*
  3209. * Use sibling's PMU rather than @event's since
  3210. * sibling could be on different (eg: software) PMU.
  3211. */
  3212. sub->pmu->read(sub);
  3213. }
  3214. }
  3215. data->ret = pmu->commit_txn(pmu);
  3216. unlock:
  3217. raw_spin_unlock(&ctx->lock);
  3218. }
  3219. static inline u64 perf_event_count(struct perf_event *event)
  3220. {
  3221. return local64_read(&event->count) + atomic64_read(&event->child_count);
  3222. }
  3223. /*
  3224. * NMI-safe method to read a local event, that is an event that
  3225. * is:
  3226. * - either for the current task, or for this CPU
  3227. * - does not have inherit set, for inherited task events
  3228. * will not be local and we cannot read them atomically
  3229. * - must not have a pmu::count method
  3230. */
  3231. int perf_event_read_local(struct perf_event *event, u64 *value,
  3232. u64 *enabled, u64 *running)
  3233. {
  3234. unsigned long flags;
  3235. int ret = 0;
  3236. /*
  3237. * Disabling interrupts avoids all counter scheduling (context
  3238. * switches, timer based rotation and IPIs).
  3239. */
  3240. local_irq_save(flags);
  3241. /*
  3242. * It must not be an event with inherit set, we cannot read
  3243. * all child counters from atomic context.
  3244. */
  3245. if (event->attr.inherit) {
  3246. ret = -EOPNOTSUPP;
  3247. goto out;
  3248. }
  3249. /* If this is a per-task event, it must be for current */
  3250. if ((event->attach_state & PERF_ATTACH_TASK) &&
  3251. event->hw.target != current) {
  3252. ret = -EINVAL;
  3253. goto out;
  3254. }
  3255. /* If this is a per-CPU event, it must be for this CPU */
  3256. if (!(event->attach_state & PERF_ATTACH_TASK) &&
  3257. event->cpu != smp_processor_id()) {
  3258. ret = -EINVAL;
  3259. goto out;
  3260. }
  3261. /* If this is a pinned event it must be running on this CPU */
  3262. if (event->attr.pinned && event->oncpu != smp_processor_id()) {
  3263. ret = -EBUSY;
  3264. goto out;
  3265. }
  3266. /*
  3267. * If the event is currently on this CPU, its either a per-task event,
  3268. * or local to this CPU. Furthermore it means its ACTIVE (otherwise
  3269. * oncpu == -1).
  3270. */
  3271. if (event->oncpu == smp_processor_id())
  3272. event->pmu->read(event);
  3273. *value = local64_read(&event->count);
  3274. if (enabled || running) {
  3275. u64 now = event->shadow_ctx_time + perf_clock();
  3276. u64 __enabled, __running;
  3277. __perf_update_times(event, now, &__enabled, &__running);
  3278. if (enabled)
  3279. *enabled = __enabled;
  3280. if (running)
  3281. *running = __running;
  3282. }
  3283. out:
  3284. local_irq_restore(flags);
  3285. return ret;
  3286. }
  3287. static int perf_event_read(struct perf_event *event, bool group)
  3288. {
  3289. enum perf_event_state state = READ_ONCE(event->state);
  3290. int event_cpu, ret = 0;
  3291. /*
  3292. * If event is enabled and currently active on a CPU, update the
  3293. * value in the event structure:
  3294. */
  3295. again:
  3296. if (state == PERF_EVENT_STATE_ACTIVE) {
  3297. struct perf_read_data data;
  3298. /*
  3299. * Orders the ->state and ->oncpu loads such that if we see
  3300. * ACTIVE we must also see the right ->oncpu.
  3301. *
  3302. * Matches the smp_wmb() from event_sched_in().
  3303. */
  3304. smp_rmb();
  3305. event_cpu = READ_ONCE(event->oncpu);
  3306. if ((unsigned)event_cpu >= nr_cpu_ids)
  3307. return 0;
  3308. data = (struct perf_read_data){
  3309. .event = event,
  3310. .group = group,
  3311. .ret = 0,
  3312. };
  3313. preempt_disable();
  3314. event_cpu = __perf_event_read_cpu(event, event_cpu);
  3315. /*
  3316. * Purposely ignore the smp_call_function_single() return
  3317. * value.
  3318. *
  3319. * If event_cpu isn't a valid CPU it means the event got
  3320. * scheduled out and that will have updated the event count.
  3321. *
  3322. * Therefore, either way, we'll have an up-to-date event count
  3323. * after this.
  3324. */
  3325. (void)smp_call_function_single(event_cpu, __perf_event_read, &data, 1);
  3326. preempt_enable();
  3327. ret = data.ret;
  3328. } else if (state == PERF_EVENT_STATE_INACTIVE) {
  3329. struct perf_event_context *ctx = event->ctx;
  3330. unsigned long flags;
  3331. raw_spin_lock_irqsave(&ctx->lock, flags);
  3332. state = event->state;
  3333. if (state != PERF_EVENT_STATE_INACTIVE) {
  3334. raw_spin_unlock_irqrestore(&ctx->lock, flags);
  3335. goto again;
  3336. }
  3337. /*
  3338. * May read while context is not active (e.g., thread is
  3339. * blocked), in that case we cannot update context time
  3340. */
  3341. if (ctx->is_active & EVENT_TIME) {
  3342. update_context_time(ctx);
  3343. update_cgrp_time_from_event(event);
  3344. }
  3345. perf_event_update_time(event);
  3346. if (group)
  3347. perf_event_update_sibling_time(event);
  3348. raw_spin_unlock_irqrestore(&ctx->lock, flags);
  3349. }
  3350. return ret;
  3351. }
  3352. /*
  3353. * Initialize the perf_event context in a task_struct:
  3354. */
  3355. static void __perf_event_init_context(struct perf_event_context *ctx)
  3356. {
  3357. raw_spin_lock_init(&ctx->lock);
  3358. mutex_init(&ctx->mutex);
  3359. INIT_LIST_HEAD(&ctx->active_ctx_list);
  3360. perf_event_groups_init(&ctx->pinned_groups);
  3361. perf_event_groups_init(&ctx->flexible_groups);
  3362. INIT_LIST_HEAD(&ctx->event_list);
  3363. INIT_LIST_HEAD(&ctx->pinned_active);
  3364. INIT_LIST_HEAD(&ctx->flexible_active);
  3365. atomic_set(&ctx->refcount, 1);
  3366. }
  3367. static struct perf_event_context *
  3368. alloc_perf_context(struct pmu *pmu, struct task_struct *task)
  3369. {
  3370. struct perf_event_context *ctx;
  3371. ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
  3372. if (!ctx)
  3373. return NULL;
  3374. __perf_event_init_context(ctx);
  3375. if (task) {
  3376. ctx->task = task;
  3377. get_task_struct(task);
  3378. }
  3379. ctx->pmu = pmu;
  3380. return ctx;
  3381. }
  3382. static struct task_struct *
  3383. find_lively_task_by_vpid(pid_t vpid)
  3384. {
  3385. struct task_struct *task;
  3386. rcu_read_lock();
  3387. if (!vpid)
  3388. task = current;
  3389. else
  3390. task = find_task_by_vpid(vpid);
  3391. if (task)
  3392. get_task_struct(task);
  3393. rcu_read_unlock();
  3394. if (!task)
  3395. return ERR_PTR(-ESRCH);
  3396. return task;
  3397. }
  3398. /*
  3399. * Returns a matching context with refcount and pincount.
  3400. */
  3401. static struct perf_event_context *
  3402. find_get_context(struct pmu *pmu, struct task_struct *task,
  3403. struct perf_event *event)
  3404. {
  3405. struct perf_event_context *ctx, *clone_ctx = NULL;
  3406. struct perf_cpu_context *cpuctx;
  3407. void *task_ctx_data = NULL;
  3408. unsigned long flags;
  3409. int ctxn, err;
  3410. int cpu = event->cpu;
  3411. if (!task) {
  3412. /* Must be root to operate on a CPU event: */
  3413. if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
  3414. return ERR_PTR(-EACCES);
  3415. cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
  3416. ctx = &cpuctx->ctx;
  3417. get_ctx(ctx);
  3418. ++ctx->pin_count;
  3419. return ctx;
  3420. }
  3421. err = -EINVAL;
  3422. ctxn = pmu->task_ctx_nr;
  3423. if (ctxn < 0)
  3424. goto errout;
  3425. if (event->attach_state & PERF_ATTACH_TASK_DATA) {
  3426. task_ctx_data = kzalloc(pmu->task_ctx_size, GFP_KERNEL);
  3427. if (!task_ctx_data) {
  3428. err = -ENOMEM;
  3429. goto errout;
  3430. }
  3431. }
  3432. retry:
  3433. ctx = perf_lock_task_context(task, ctxn, &flags);
  3434. if (ctx) {
  3435. clone_ctx = unclone_ctx(ctx);
  3436. ++ctx->pin_count;
  3437. if (task_ctx_data && !ctx->task_ctx_data) {
  3438. ctx->task_ctx_data = task_ctx_data;
  3439. task_ctx_data = NULL;
  3440. }
  3441. raw_spin_unlock_irqrestore(&ctx->lock, flags);
  3442. if (clone_ctx)
  3443. put_ctx(clone_ctx);
  3444. } else {
  3445. ctx = alloc_perf_context(pmu, task);
  3446. err = -ENOMEM;
  3447. if (!ctx)
  3448. goto errout;
  3449. if (task_ctx_data) {
  3450. ctx->task_ctx_data = task_ctx_data;
  3451. task_ctx_data = NULL;
  3452. }
  3453. err = 0;
  3454. mutex_lock(&task->perf_event_mutex);
  3455. /*
  3456. * If it has already passed perf_event_exit_task().
  3457. * we must see PF_EXITING, it takes this mutex too.
  3458. */
  3459. if (task->flags & PF_EXITING)
  3460. err = -ESRCH;
  3461. else if (task->perf_event_ctxp[ctxn])
  3462. err = -EAGAIN;
  3463. else {
  3464. get_ctx(ctx);
  3465. ++ctx->pin_count;
  3466. rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
  3467. }
  3468. mutex_unlock(&task->perf_event_mutex);
  3469. if (unlikely(err)) {
  3470. put_ctx(ctx);
  3471. if (err == -EAGAIN)
  3472. goto retry;
  3473. goto errout;
  3474. }
  3475. }
  3476. kfree(task_ctx_data);
  3477. return ctx;
  3478. errout:
  3479. kfree(task_ctx_data);
  3480. return ERR_PTR(err);
  3481. }
  3482. static void perf_event_free_filter(struct perf_event *event);
  3483. static void perf_event_free_bpf_prog(struct perf_event *event);
  3484. static void free_event_rcu(struct rcu_head *head)
  3485. {
  3486. struct perf_event *event;
  3487. event = container_of(head, struct perf_event, rcu_head);
  3488. if (event->ns)
  3489. put_pid_ns(event->ns);
  3490. perf_event_free_filter(event);
  3491. kfree(event);
  3492. }
  3493. static void ring_buffer_attach(struct perf_event *event,
  3494. struct ring_buffer *rb);
  3495. static void detach_sb_event(struct perf_event *event)
  3496. {
  3497. struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
  3498. raw_spin_lock(&pel->lock);
  3499. list_del_rcu(&event->sb_list);
  3500. raw_spin_unlock(&pel->lock);
  3501. }
  3502. static bool is_sb_event(struct perf_event *event)
  3503. {
  3504. struct perf_event_attr *attr = &event->attr;
  3505. if (event->parent)
  3506. return false;
  3507. if (event->attach_state & PERF_ATTACH_TASK)
  3508. return false;
  3509. if (attr->mmap || attr->mmap_data || attr->mmap2 ||
  3510. attr->comm || attr->comm_exec ||
  3511. attr->task ||
  3512. attr->context_switch)
  3513. return true;
  3514. return false;
  3515. }
  3516. static void unaccount_pmu_sb_event(struct perf_event *event)
  3517. {
  3518. if (is_sb_event(event))
  3519. detach_sb_event(event);
  3520. }
  3521. static void unaccount_event_cpu(struct perf_event *event, int cpu)
  3522. {
  3523. if (event->parent)
  3524. return;
  3525. if (is_cgroup_event(event))
  3526. atomic_dec(&per_cpu(perf_cgroup_events, cpu));
  3527. }
  3528. #ifdef CONFIG_NO_HZ_FULL
  3529. static DEFINE_SPINLOCK(nr_freq_lock);
  3530. #endif
  3531. static void unaccount_freq_event_nohz(void)
  3532. {
  3533. #ifdef CONFIG_NO_HZ_FULL
  3534. spin_lock(&nr_freq_lock);
  3535. if (atomic_dec_and_test(&nr_freq_events))
  3536. tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS);
  3537. spin_unlock(&nr_freq_lock);
  3538. #endif
  3539. }
  3540. static void unaccount_freq_event(void)
  3541. {
  3542. if (tick_nohz_full_enabled())
  3543. unaccount_freq_event_nohz();
  3544. else
  3545. atomic_dec(&nr_freq_events);
  3546. }
  3547. static void unaccount_event(struct perf_event *event)
  3548. {
  3549. bool dec = false;
  3550. if (event->parent)
  3551. return;
  3552. if (event->attach_state & PERF_ATTACH_TASK)
  3553. dec = true;
  3554. if (event->attr.mmap || event->attr.mmap_data)
  3555. atomic_dec(&nr_mmap_events);
  3556. if (event->attr.comm)
  3557. atomic_dec(&nr_comm_events);
  3558. if (event->attr.namespaces)
  3559. atomic_dec(&nr_namespaces_events);
  3560. if (event->attr.task)
  3561. atomic_dec(&nr_task_events);
  3562. if (event->attr.freq)
  3563. unaccount_freq_event();
  3564. if (event->attr.context_switch) {
  3565. dec = true;
  3566. atomic_dec(&nr_switch_events);
  3567. }
  3568. if (is_cgroup_event(event))
  3569. dec = true;
  3570. if (has_branch_stack(event))
  3571. dec = true;
  3572. if (dec) {
  3573. if (!atomic_add_unless(&perf_sched_count, -1, 1))
  3574. schedule_delayed_work(&perf_sched_work, HZ);
  3575. }
  3576. unaccount_event_cpu(event, event->cpu);
  3577. unaccount_pmu_sb_event(event);
  3578. }
  3579. static void perf_sched_delayed(struct work_struct *work)
  3580. {
  3581. mutex_lock(&perf_sched_mutex);
  3582. if (atomic_dec_and_test(&perf_sched_count))
  3583. static_branch_disable(&perf_sched_events);
  3584. mutex_unlock(&perf_sched_mutex);
  3585. }
  3586. /*
  3587. * The following implement mutual exclusion of events on "exclusive" pmus
  3588. * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
  3589. * at a time, so we disallow creating events that might conflict, namely:
  3590. *
  3591. * 1) cpu-wide events in the presence of per-task events,
  3592. * 2) per-task events in the presence of cpu-wide events,
  3593. * 3) two matching events on the same context.
  3594. *
  3595. * The former two cases are handled in the allocation path (perf_event_alloc(),
  3596. * _free_event()), the latter -- before the first perf_install_in_context().
  3597. */
  3598. static int exclusive_event_init(struct perf_event *event)
  3599. {
  3600. struct pmu *pmu = event->pmu;
  3601. if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
  3602. return 0;
  3603. /*
  3604. * Prevent co-existence of per-task and cpu-wide events on the
  3605. * same exclusive pmu.
  3606. *
  3607. * Negative pmu::exclusive_cnt means there are cpu-wide
  3608. * events on this "exclusive" pmu, positive means there are
  3609. * per-task events.
  3610. *
  3611. * Since this is called in perf_event_alloc() path, event::ctx
  3612. * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
  3613. * to mean "per-task event", because unlike other attach states it
  3614. * never gets cleared.
  3615. */
  3616. if (event->attach_state & PERF_ATTACH_TASK) {
  3617. if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
  3618. return -EBUSY;
  3619. } else {
  3620. if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
  3621. return -EBUSY;
  3622. }
  3623. return 0;
  3624. }
  3625. static void exclusive_event_destroy(struct perf_event *event)
  3626. {
  3627. struct pmu *pmu = event->pmu;
  3628. if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
  3629. return;
  3630. /* see comment in exclusive_event_init() */
  3631. if (event->attach_state & PERF_ATTACH_TASK)
  3632. atomic_dec(&pmu->exclusive_cnt);
  3633. else
  3634. atomic_inc(&pmu->exclusive_cnt);
  3635. }
  3636. static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
  3637. {
  3638. if ((e1->pmu == e2->pmu) &&
  3639. (e1->cpu == e2->cpu ||
  3640. e1->cpu == -1 ||
  3641. e2->cpu == -1))
  3642. return true;
  3643. return false;
  3644. }
  3645. /* Called under the same ctx::mutex as perf_install_in_context() */
  3646. static bool exclusive_event_installable(struct perf_event *event,
  3647. struct perf_event_context *ctx)
  3648. {
  3649. struct perf_event *iter_event;
  3650. struct pmu *pmu = event->pmu;
  3651. if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
  3652. return true;
  3653. list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
  3654. if (exclusive_event_match(iter_event, event))
  3655. return false;
  3656. }
  3657. return true;
  3658. }
  3659. static void perf_addr_filters_splice(struct perf_event *event,
  3660. struct list_head *head);
  3661. static void _free_event(struct perf_event *event)
  3662. {
  3663. irq_work_sync(&event->pending);
  3664. unaccount_event(event);
  3665. if (event->rb) {
  3666. /*
  3667. * Can happen when we close an event with re-directed output.
  3668. *
  3669. * Since we have a 0 refcount, perf_mmap_close() will skip
  3670. * over us; possibly making our ring_buffer_put() the last.
  3671. */
  3672. mutex_lock(&event->mmap_mutex);
  3673. ring_buffer_attach(event, NULL);
  3674. mutex_unlock(&event->mmap_mutex);
  3675. }
  3676. if (is_cgroup_event(event))
  3677. perf_detach_cgroup(event);
  3678. if (!event->parent) {
  3679. if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
  3680. put_callchain_buffers();
  3681. }
  3682. perf_event_free_bpf_prog(event);
  3683. perf_addr_filters_splice(event, NULL);
  3684. kfree(event->addr_filters_offs);
  3685. if (event->destroy)
  3686. event->destroy(event);
  3687. if (event->ctx)
  3688. put_ctx(event->ctx);
  3689. if (event->hw.target)
  3690. put_task_struct(event->hw.target);
  3691. exclusive_event_destroy(event);
  3692. module_put(event->pmu->module);
  3693. call_rcu(&event->rcu_head, free_event_rcu);
  3694. }
  3695. /*
  3696. * Used to free events which have a known refcount of 1, such as in error paths
  3697. * where the event isn't exposed yet and inherited events.
  3698. */
  3699. static void free_event(struct perf_event *event)
  3700. {
  3701. if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
  3702. "unexpected event refcount: %ld; ptr=%p\n",
  3703. atomic_long_read(&event->refcount), event)) {
  3704. /* leak to avoid use-after-free */
  3705. return;
  3706. }
  3707. _free_event(event);
  3708. }
  3709. /*
  3710. * Remove user event from the owner task.
  3711. */
  3712. static void perf_remove_from_owner(struct perf_event *event)
  3713. {
  3714. struct task_struct *owner;
  3715. rcu_read_lock();
  3716. /*
  3717. * Matches the smp_store_release() in perf_event_exit_task(). If we
  3718. * observe !owner it means the list deletion is complete and we can
  3719. * indeed free this event, otherwise we need to serialize on
  3720. * owner->perf_event_mutex.
  3721. */
  3722. owner = READ_ONCE(event->owner);
  3723. if (owner) {
  3724. /*
  3725. * Since delayed_put_task_struct() also drops the last
  3726. * task reference we can safely take a new reference
  3727. * while holding the rcu_read_lock().
  3728. */
  3729. get_task_struct(owner);
  3730. }
  3731. rcu_read_unlock();
  3732. if (owner) {
  3733. /*
  3734. * If we're here through perf_event_exit_task() we're already
  3735. * holding ctx->mutex which would be an inversion wrt. the
  3736. * normal lock order.
  3737. *
  3738. * However we can safely take this lock because its the child
  3739. * ctx->mutex.
  3740. */
  3741. mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
  3742. /*
  3743. * We have to re-check the event->owner field, if it is cleared
  3744. * we raced with perf_event_exit_task(), acquiring the mutex
  3745. * ensured they're done, and we can proceed with freeing the
  3746. * event.
  3747. */
  3748. if (event->owner) {
  3749. list_del_init(&event->owner_entry);
  3750. smp_store_release(&event->owner, NULL);
  3751. }
  3752. mutex_unlock(&owner->perf_event_mutex);
  3753. put_task_struct(owner);
  3754. }
  3755. }
  3756. static void put_event(struct perf_event *event)
  3757. {
  3758. if (!atomic_long_dec_and_test(&event->refcount))
  3759. return;
  3760. _free_event(event);
  3761. }
  3762. /*
  3763. * Kill an event dead; while event:refcount will preserve the event
  3764. * object, it will not preserve its functionality. Once the last 'user'
  3765. * gives up the object, we'll destroy the thing.
  3766. */
  3767. int perf_event_release_kernel(struct perf_event *event)
  3768. {
  3769. struct perf_event_context *ctx = event->ctx;
  3770. struct perf_event *child, *tmp;
  3771. LIST_HEAD(free_list);
  3772. /*
  3773. * If we got here through err_file: fput(event_file); we will not have
  3774. * attached to a context yet.
  3775. */
  3776. if (!ctx) {
  3777. WARN_ON_ONCE(event->attach_state &
  3778. (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP));
  3779. goto no_ctx;
  3780. }
  3781. if (!is_kernel_event(event))
  3782. perf_remove_from_owner(event);
  3783. ctx = perf_event_ctx_lock(event);
  3784. WARN_ON_ONCE(ctx->parent_ctx);
  3785. perf_remove_from_context(event, DETACH_GROUP);
  3786. raw_spin_lock_irq(&ctx->lock);
  3787. /*
  3788. * Mark this event as STATE_DEAD, there is no external reference to it
  3789. * anymore.
  3790. *
  3791. * Anybody acquiring event->child_mutex after the below loop _must_
  3792. * also see this, most importantly inherit_event() which will avoid
  3793. * placing more children on the list.
  3794. *
  3795. * Thus this guarantees that we will in fact observe and kill _ALL_
  3796. * child events.
  3797. */
  3798. event->state = PERF_EVENT_STATE_DEAD;
  3799. raw_spin_unlock_irq(&ctx->lock);
  3800. perf_event_ctx_unlock(event, ctx);
  3801. again:
  3802. mutex_lock(&event->child_mutex);
  3803. list_for_each_entry(child, &event->child_list, child_list) {
  3804. /*
  3805. * Cannot change, child events are not migrated, see the
  3806. * comment with perf_event_ctx_lock_nested().
  3807. */
  3808. ctx = READ_ONCE(child->ctx);
  3809. /*
  3810. * Since child_mutex nests inside ctx::mutex, we must jump
  3811. * through hoops. We start by grabbing a reference on the ctx.
  3812. *
  3813. * Since the event cannot get freed while we hold the
  3814. * child_mutex, the context must also exist and have a !0
  3815. * reference count.
  3816. */
  3817. get_ctx(ctx);
  3818. /*
  3819. * Now that we have a ctx ref, we can drop child_mutex, and
  3820. * acquire ctx::mutex without fear of it going away. Then we
  3821. * can re-acquire child_mutex.
  3822. */
  3823. mutex_unlock(&event->child_mutex);
  3824. mutex_lock(&ctx->mutex);
  3825. mutex_lock(&event->child_mutex);
  3826. /*
  3827. * Now that we hold ctx::mutex and child_mutex, revalidate our
  3828. * state, if child is still the first entry, it didn't get freed
  3829. * and we can continue doing so.
  3830. */
  3831. tmp = list_first_entry_or_null(&event->child_list,
  3832. struct perf_event, child_list);
  3833. if (tmp == child) {
  3834. perf_remove_from_context(child, DETACH_GROUP);
  3835. list_move(&child->child_list, &free_list);
  3836. /*
  3837. * This matches the refcount bump in inherit_event();
  3838. * this can't be the last reference.
  3839. */
  3840. put_event(event);
  3841. }
  3842. mutex_unlock(&event->child_mutex);
  3843. mutex_unlock(&ctx->mutex);
  3844. put_ctx(ctx);
  3845. goto again;
  3846. }
  3847. mutex_unlock(&event->child_mutex);
  3848. list_for_each_entry_safe(child, tmp, &free_list, child_list) {
  3849. list_del(&child->child_list);
  3850. free_event(child);
  3851. }
  3852. no_ctx:
  3853. put_event(event); /* Must be the 'last' reference */
  3854. return 0;
  3855. }
  3856. EXPORT_SYMBOL_GPL(perf_event_release_kernel);
  3857. /*
  3858. * Called when the last reference to the file is gone.
  3859. */
  3860. static int perf_release(struct inode *inode, struct file *file)
  3861. {
  3862. perf_event_release_kernel(file->private_data);
  3863. return 0;
  3864. }
  3865. static u64 __perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
  3866. {
  3867. struct perf_event *child;
  3868. u64 total = 0;
  3869. *enabled = 0;
  3870. *running = 0;
  3871. mutex_lock(&event->child_mutex);
  3872. (void)perf_event_read(event, false);
  3873. total += perf_event_count(event);
  3874. *enabled += event->total_time_enabled +
  3875. atomic64_read(&event->child_total_time_enabled);
  3876. *running += event->total_time_running +
  3877. atomic64_read(&event->child_total_time_running);
  3878. list_for_each_entry(child, &event->child_list, child_list) {
  3879. (void)perf_event_read(child, false);
  3880. total += perf_event_count(child);
  3881. *enabled += child->total_time_enabled;
  3882. *running += child->total_time_running;
  3883. }
  3884. mutex_unlock(&event->child_mutex);
  3885. return total;
  3886. }
  3887. u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
  3888. {
  3889. struct perf_event_context *ctx;
  3890. u64 count;
  3891. ctx = perf_event_ctx_lock(event);
  3892. count = __perf_event_read_value(event, enabled, running);
  3893. perf_event_ctx_unlock(event, ctx);
  3894. return count;
  3895. }
  3896. EXPORT_SYMBOL_GPL(perf_event_read_value);
  3897. static int __perf_read_group_add(struct perf_event *leader,
  3898. u64 read_format, u64 *values)
  3899. {
  3900. struct perf_event_context *ctx = leader->ctx;
  3901. struct perf_event *sub;
  3902. unsigned long flags;
  3903. int n = 1; /* skip @nr */
  3904. int ret;
  3905. ret = perf_event_read(leader, true);
  3906. if (ret)
  3907. return ret;
  3908. raw_spin_lock_irqsave(&ctx->lock, flags);
  3909. /*
  3910. * Since we co-schedule groups, {enabled,running} times of siblings
  3911. * will be identical to those of the leader, so we only publish one
  3912. * set.
  3913. */
  3914. if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
  3915. values[n++] += leader->total_time_enabled +
  3916. atomic64_read(&leader->child_total_time_enabled);
  3917. }
  3918. if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
  3919. values[n++] += leader->total_time_running +
  3920. atomic64_read(&leader->child_total_time_running);
  3921. }
  3922. /*
  3923. * Write {count,id} tuples for every sibling.
  3924. */
  3925. values[n++] += perf_event_count(leader);
  3926. if (read_format & PERF_FORMAT_ID)
  3927. values[n++] = primary_event_id(leader);
  3928. for_each_sibling_event(sub, leader) {
  3929. values[n++] += perf_event_count(sub);
  3930. if (read_format & PERF_FORMAT_ID)
  3931. values[n++] = primary_event_id(sub);
  3932. }
  3933. raw_spin_unlock_irqrestore(&ctx->lock, flags);
  3934. return 0;
  3935. }
  3936. static int perf_read_group(struct perf_event *event,
  3937. u64 read_format, char __user *buf)
  3938. {
  3939. struct perf_event *leader = event->group_leader, *child;
  3940. struct perf_event_context *ctx = leader->ctx;
  3941. int ret;
  3942. u64 *values;
  3943. lockdep_assert_held(&ctx->mutex);
  3944. values = kzalloc(event->read_size, GFP_KERNEL);
  3945. if (!values)
  3946. return -ENOMEM;
  3947. values[0] = 1 + leader->nr_siblings;
  3948. /*
  3949. * By locking the child_mutex of the leader we effectively
  3950. * lock the child list of all siblings.. XXX explain how.
  3951. */
  3952. mutex_lock(&leader->child_mutex);
  3953. ret = __perf_read_group_add(leader, read_format, values);
  3954. if (ret)
  3955. goto unlock;
  3956. list_for_each_entry(child, &leader->child_list, child_list) {
  3957. ret = __perf_read_group_add(child, read_format, values);
  3958. if (ret)
  3959. goto unlock;
  3960. }
  3961. mutex_unlock(&leader->child_mutex);
  3962. ret = event->read_size;
  3963. if (copy_to_user(buf, values, event->read_size))
  3964. ret = -EFAULT;
  3965. goto out;
  3966. unlock:
  3967. mutex_unlock(&leader->child_mutex);
  3968. out:
  3969. kfree(values);
  3970. return ret;
  3971. }
  3972. static int perf_read_one(struct perf_event *event,
  3973. u64 read_format, char __user *buf)
  3974. {
  3975. u64 enabled, running;
  3976. u64 values[4];
  3977. int n = 0;
  3978. values[n++] = __perf_event_read_value(event, &enabled, &running);
  3979. if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
  3980. values[n++] = enabled;
  3981. if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
  3982. values[n++] = running;
  3983. if (read_format & PERF_FORMAT_ID)
  3984. values[n++] = primary_event_id(event);
  3985. if (copy_to_user(buf, values, n * sizeof(u64)))
  3986. return -EFAULT;
  3987. return n * sizeof(u64);
  3988. }
  3989. static bool is_event_hup(struct perf_event *event)
  3990. {
  3991. bool no_children;
  3992. if (event->state > PERF_EVENT_STATE_EXIT)
  3993. return false;
  3994. mutex_lock(&event->child_mutex);
  3995. no_children = list_empty(&event->child_list);
  3996. mutex_unlock(&event->child_mutex);
  3997. return no_children;
  3998. }
  3999. /*
  4000. * Read the performance event - simple non blocking version for now
  4001. */
  4002. static ssize_t
  4003. __perf_read(struct perf_event *event, char __user *buf, size_t count)
  4004. {
  4005. u64 read_format = event->attr.read_format;
  4006. int ret;
  4007. /*
  4008. * Return end-of-file for a read on an event that is in
  4009. * error state (i.e. because it was pinned but it couldn't be
  4010. * scheduled on to the CPU at some point).
  4011. */
  4012. if (event->state == PERF_EVENT_STATE_ERROR)
  4013. return 0;
  4014. if (count < event->read_size)
  4015. return -ENOSPC;
  4016. WARN_ON_ONCE(event->ctx->parent_ctx);
  4017. if (read_format & PERF_FORMAT_GROUP)
  4018. ret = perf_read_group(event, read_format, buf);
  4019. else
  4020. ret = perf_read_one(event, read_format, buf);
  4021. return ret;
  4022. }
  4023. static ssize_t
  4024. perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
  4025. {
  4026. struct perf_event *event = file->private_data;
  4027. struct perf_event_context *ctx;
  4028. int ret;
  4029. ctx = perf_event_ctx_lock(event);
  4030. ret = __perf_read(event, buf, count);
  4031. perf_event_ctx_unlock(event, ctx);
  4032. return ret;
  4033. }
  4034. static __poll_t perf_poll(struct file *file, poll_table *wait)
  4035. {
  4036. struct perf_event *event = file->private_data;
  4037. struct ring_buffer *rb;
  4038. __poll_t events = EPOLLHUP;
  4039. poll_wait(file, &event->waitq, wait);
  4040. if (is_event_hup(event))
  4041. return events;
  4042. /*
  4043. * Pin the event->rb by taking event->mmap_mutex; otherwise
  4044. * perf_event_set_output() can swizzle our rb and make us miss wakeups.
  4045. */
  4046. mutex_lock(&event->mmap_mutex);
  4047. rb = event->rb;
  4048. if (rb)
  4049. events = atomic_xchg(&rb->poll, 0);
  4050. mutex_unlock(&event->mmap_mutex);
  4051. return events;
  4052. }
  4053. static void _perf_event_reset(struct perf_event *event)
  4054. {
  4055. (void)perf_event_read(event, false);
  4056. local64_set(&event->count, 0);
  4057. perf_event_update_userpage(event);
  4058. }
  4059. /*
  4060. * Holding the top-level event's child_mutex means that any
  4061. * descendant process that has inherited this event will block
  4062. * in perf_event_exit_event() if it goes to exit, thus satisfying the
  4063. * task existence requirements of perf_event_enable/disable.
  4064. */
  4065. static void perf_event_for_each_child(struct perf_event *event,
  4066. void (*func)(struct perf_event *))
  4067. {
  4068. struct perf_event *child;
  4069. WARN_ON_ONCE(event->ctx->parent_ctx);
  4070. mutex_lock(&event->child_mutex);
  4071. func(event);
  4072. list_for_each_entry(child, &event->child_list, child_list)
  4073. func(child);
  4074. mutex_unlock(&event->child_mutex);
  4075. }
  4076. static void perf_event_for_each(struct perf_event *event,
  4077. void (*func)(struct perf_event *))
  4078. {
  4079. struct perf_event_context *ctx = event->ctx;
  4080. struct perf_event *sibling;
  4081. lockdep_assert_held(&ctx->mutex);
  4082. event = event->group_leader;
  4083. perf_event_for_each_child(event, func);
  4084. for_each_sibling_event(sibling, event)
  4085. perf_event_for_each_child(sibling, func);
  4086. }
  4087. static void __perf_event_period(struct perf_event *event,
  4088. struct perf_cpu_context *cpuctx,
  4089. struct perf_event_context *ctx,
  4090. void *info)
  4091. {
  4092. u64 value = *((u64 *)info);
  4093. bool active;
  4094. if (event->attr.freq) {
  4095. event->attr.sample_freq = value;
  4096. } else {
  4097. event->attr.sample_period = value;
  4098. event->hw.sample_period = value;
  4099. }
  4100. active = (event->state == PERF_EVENT_STATE_ACTIVE);
  4101. if (active) {
  4102. perf_pmu_disable(ctx->pmu);
  4103. /*
  4104. * We could be throttled; unthrottle now to avoid the tick
  4105. * trying to unthrottle while we already re-started the event.
  4106. */
  4107. if (event->hw.interrupts == MAX_INTERRUPTS) {
  4108. event->hw.interrupts = 0;
  4109. perf_log_throttle(event, 1);
  4110. }
  4111. event->pmu->stop(event, PERF_EF_UPDATE);
  4112. }
  4113. local64_set(&event->hw.period_left, 0);
  4114. if (active) {
  4115. event->pmu->start(event, PERF_EF_RELOAD);
  4116. perf_pmu_enable(ctx->pmu);
  4117. }
  4118. }
  4119. static int perf_event_period(struct perf_event *event, u64 __user *arg)
  4120. {
  4121. u64 value;
  4122. if (!is_sampling_event(event))
  4123. return -EINVAL;
  4124. if (copy_from_user(&value, arg, sizeof(value)))
  4125. return -EFAULT;
  4126. if (!value)
  4127. return -EINVAL;
  4128. if (event->attr.freq && value > sysctl_perf_event_sample_rate)
  4129. return -EINVAL;
  4130. event_function_call(event, __perf_event_period, &value);
  4131. return 0;
  4132. }
  4133. static const struct file_operations perf_fops;
  4134. static inline int perf_fget_light(int fd, struct fd *p)
  4135. {
  4136. struct fd f = fdget(fd);
  4137. if (!f.file)
  4138. return -EBADF;
  4139. if (f.file->f_op != &perf_fops) {
  4140. fdput(f);
  4141. return -EBADF;
  4142. }
  4143. *p = f;
  4144. return 0;
  4145. }
  4146. static int perf_event_set_output(struct perf_event *event,
  4147. struct perf_event *output_event);
  4148. static int perf_event_set_filter(struct perf_event *event, void __user *arg);
  4149. static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd);
  4150. static int perf_copy_attr(struct perf_event_attr __user *uattr,
  4151. struct perf_event_attr *attr);
  4152. static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
  4153. {
  4154. void (*func)(struct perf_event *);
  4155. u32 flags = arg;
  4156. switch (cmd) {
  4157. case PERF_EVENT_IOC_ENABLE:
  4158. func = _perf_event_enable;
  4159. break;
  4160. case PERF_EVENT_IOC_DISABLE:
  4161. func = _perf_event_disable;
  4162. break;
  4163. case PERF_EVENT_IOC_RESET:
  4164. func = _perf_event_reset;
  4165. break;
  4166. case PERF_EVENT_IOC_REFRESH:
  4167. return _perf_event_refresh(event, arg);
  4168. case PERF_EVENT_IOC_PERIOD:
  4169. return perf_event_period(event, (u64 __user *)arg);
  4170. case PERF_EVENT_IOC_ID:
  4171. {
  4172. u64 id = primary_event_id(event);
  4173. if (copy_to_user((void __user *)arg, &id, sizeof(id)))
  4174. return -EFAULT;
  4175. return 0;
  4176. }
  4177. case PERF_EVENT_IOC_SET_OUTPUT:
  4178. {
  4179. int ret;
  4180. if (arg != -1) {
  4181. struct perf_event *output_event;
  4182. struct fd output;
  4183. ret = perf_fget_light(arg, &output);
  4184. if (ret)
  4185. return ret;
  4186. output_event = output.file->private_data;
  4187. ret = perf_event_set_output(event, output_event);
  4188. fdput(output);
  4189. } else {
  4190. ret = perf_event_set_output(event, NULL);
  4191. }
  4192. return ret;
  4193. }
  4194. case PERF_EVENT_IOC_SET_FILTER:
  4195. return perf_event_set_filter(event, (void __user *)arg);
  4196. case PERF_EVENT_IOC_SET_BPF:
  4197. return perf_event_set_bpf_prog(event, arg);
  4198. case PERF_EVENT_IOC_PAUSE_OUTPUT: {
  4199. struct ring_buffer *rb;
  4200. rcu_read_lock();
  4201. rb = rcu_dereference(event->rb);
  4202. if (!rb || !rb->nr_pages) {
  4203. rcu_read_unlock();
  4204. return -EINVAL;
  4205. }
  4206. rb_toggle_paused(rb, !!arg);
  4207. rcu_read_unlock();
  4208. return 0;
  4209. }
  4210. case PERF_EVENT_IOC_QUERY_BPF:
  4211. return perf_event_query_prog_array(event, (void __user *)arg);
  4212. case PERF_EVENT_IOC_MODIFY_ATTRIBUTES: {
  4213. struct perf_event_attr new_attr;
  4214. int err = perf_copy_attr((struct perf_event_attr __user *)arg,
  4215. &new_attr);
  4216. if (err)
  4217. return err;
  4218. return perf_event_modify_attr(event, &new_attr);
  4219. }
  4220. default:
  4221. return -ENOTTY;
  4222. }
  4223. if (flags & PERF_IOC_FLAG_GROUP)
  4224. perf_event_for_each(event, func);
  4225. else
  4226. perf_event_for_each_child(event, func);
  4227. return 0;
  4228. }
  4229. static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
  4230. {
  4231. struct perf_event *event = file->private_data;
  4232. struct perf_event_context *ctx;
  4233. long ret;
  4234. ctx = perf_event_ctx_lock(event);
  4235. ret = _perf_ioctl(event, cmd, arg);
  4236. perf_event_ctx_unlock(event, ctx);
  4237. return ret;
  4238. }
  4239. #ifdef CONFIG_COMPAT
  4240. static long perf_compat_ioctl(struct file *file, unsigned int cmd,
  4241. unsigned long arg)
  4242. {
  4243. switch (_IOC_NR(cmd)) {
  4244. case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
  4245. case _IOC_NR(PERF_EVENT_IOC_ID):
  4246. case _IOC_NR(PERF_EVENT_IOC_QUERY_BPF):
  4247. case _IOC_NR(PERF_EVENT_IOC_MODIFY_ATTRIBUTES):
  4248. /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
  4249. if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
  4250. cmd &= ~IOCSIZE_MASK;
  4251. cmd |= sizeof(void *) << IOCSIZE_SHIFT;
  4252. }
  4253. break;
  4254. }
  4255. return perf_ioctl(file, cmd, arg);
  4256. }
  4257. #else
  4258. # define perf_compat_ioctl NULL
  4259. #endif
  4260. int perf_event_task_enable(void)
  4261. {
  4262. struct perf_event_context *ctx;
  4263. struct perf_event *event;
  4264. mutex_lock(&current->perf_event_mutex);
  4265. list_for_each_entry(event, &current->perf_event_list, owner_entry) {
  4266. ctx = perf_event_ctx_lock(event);
  4267. perf_event_for_each_child(event, _perf_event_enable);
  4268. perf_event_ctx_unlock(event, ctx);
  4269. }
  4270. mutex_unlock(&current->perf_event_mutex);
  4271. return 0;
  4272. }
  4273. int perf_event_task_disable(void)
  4274. {
  4275. struct perf_event_context *ctx;
  4276. struct perf_event *event;
  4277. mutex_lock(&current->perf_event_mutex);
  4278. list_for_each_entry(event, &current->perf_event_list, owner_entry) {
  4279. ctx = perf_event_ctx_lock(event);
  4280. perf_event_for_each_child(event, _perf_event_disable);
  4281. perf_event_ctx_unlock(event, ctx);
  4282. }
  4283. mutex_unlock(&current->perf_event_mutex);
  4284. return 0;
  4285. }
  4286. static int perf_event_index(struct perf_event *event)
  4287. {
  4288. if (event->hw.state & PERF_HES_STOPPED)
  4289. return 0;
  4290. if (event->state != PERF_EVENT_STATE_ACTIVE)
  4291. return 0;
  4292. return event->pmu->event_idx(event);
  4293. }
  4294. static void calc_timer_values(struct perf_event *event,
  4295. u64 *now,
  4296. u64 *enabled,
  4297. u64 *running)
  4298. {
  4299. u64 ctx_time;
  4300. *now = perf_clock();
  4301. ctx_time = event->shadow_ctx_time + *now;
  4302. __perf_update_times(event, ctx_time, enabled, running);
  4303. }
  4304. static void perf_event_init_userpage(struct perf_event *event)
  4305. {
  4306. struct perf_event_mmap_page *userpg;
  4307. struct ring_buffer *rb;
  4308. rcu_read_lock();
  4309. rb = rcu_dereference(event->rb);
  4310. if (!rb)
  4311. goto unlock;
  4312. userpg = rb->user_page;
  4313. /* Allow new userspace to detect that bit 0 is deprecated */
  4314. userpg->cap_bit0_is_deprecated = 1;
  4315. userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
  4316. userpg->data_offset = PAGE_SIZE;
  4317. userpg->data_size = perf_data_size(rb);
  4318. unlock:
  4319. rcu_read_unlock();
  4320. }
  4321. void __weak arch_perf_update_userpage(
  4322. struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
  4323. {
  4324. }
  4325. /*
  4326. * Callers need to ensure there can be no nesting of this function, otherwise
  4327. * the seqlock logic goes bad. We can not serialize this because the arch
  4328. * code calls this from NMI context.
  4329. */
  4330. void perf_event_update_userpage(struct perf_event *event)
  4331. {
  4332. struct perf_event_mmap_page *userpg;
  4333. struct ring_buffer *rb;
  4334. u64 enabled, running, now;
  4335. rcu_read_lock();
  4336. rb = rcu_dereference(event->rb);
  4337. if (!rb)
  4338. goto unlock;
  4339. /*
  4340. * compute total_time_enabled, total_time_running
  4341. * based on snapshot values taken when the event
  4342. * was last scheduled in.
  4343. *
  4344. * we cannot simply called update_context_time()
  4345. * because of locking issue as we can be called in
  4346. * NMI context
  4347. */
  4348. calc_timer_values(event, &now, &enabled, &running);
  4349. userpg = rb->user_page;
  4350. /*
  4351. * Disable preemption to guarantee consistent time stamps are stored to
  4352. * the user page.
  4353. */
  4354. preempt_disable();
  4355. ++userpg->lock;
  4356. barrier();
  4357. userpg->index = perf_event_index(event);
  4358. userpg->offset = perf_event_count(event);
  4359. if (userpg->index)
  4360. userpg->offset -= local64_read(&event->hw.prev_count);
  4361. userpg->time_enabled = enabled +
  4362. atomic64_read(&event->child_total_time_enabled);
  4363. userpg->time_running = running +
  4364. atomic64_read(&event->child_total_time_running);
  4365. arch_perf_update_userpage(event, userpg, now);
  4366. barrier();
  4367. ++userpg->lock;
  4368. preempt_enable();
  4369. unlock:
  4370. rcu_read_unlock();
  4371. }
  4372. EXPORT_SYMBOL_GPL(perf_event_update_userpage);
  4373. static vm_fault_t perf_mmap_fault(struct vm_fault *vmf)
  4374. {
  4375. struct perf_event *event = vmf->vma->vm_file->private_data;
  4376. struct ring_buffer *rb;
  4377. vm_fault_t ret = VM_FAULT_SIGBUS;
  4378. if (vmf->flags & FAULT_FLAG_MKWRITE) {
  4379. if (vmf->pgoff == 0)
  4380. ret = 0;
  4381. return ret;
  4382. }
  4383. rcu_read_lock();
  4384. rb = rcu_dereference(event->rb);
  4385. if (!rb)
  4386. goto unlock;
  4387. if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
  4388. goto unlock;
  4389. vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
  4390. if (!vmf->page)
  4391. goto unlock;
  4392. get_page(vmf->page);
  4393. vmf->page->mapping = vmf->vma->vm_file->f_mapping;
  4394. vmf->page->index = vmf->pgoff;
  4395. ret = 0;
  4396. unlock:
  4397. rcu_read_unlock();
  4398. return ret;
  4399. }
  4400. static void ring_buffer_attach(struct perf_event *event,
  4401. struct ring_buffer *rb)
  4402. {
  4403. struct ring_buffer *old_rb = NULL;
  4404. unsigned long flags;
  4405. if (event->rb) {
  4406. /*
  4407. * Should be impossible, we set this when removing
  4408. * event->rb_entry and wait/clear when adding event->rb_entry.
  4409. */
  4410. WARN_ON_ONCE(event->rcu_pending);
  4411. old_rb = event->rb;
  4412. spin_lock_irqsave(&old_rb->event_lock, flags);
  4413. list_del_rcu(&event->rb_entry);
  4414. spin_unlock_irqrestore(&old_rb->event_lock, flags);
  4415. event->rcu_batches = get_state_synchronize_rcu();
  4416. event->rcu_pending = 1;
  4417. }
  4418. if (rb) {
  4419. if (event->rcu_pending) {
  4420. cond_synchronize_rcu(event->rcu_batches);
  4421. event->rcu_pending = 0;
  4422. }
  4423. spin_lock_irqsave(&rb->event_lock, flags);
  4424. list_add_rcu(&event->rb_entry, &rb->event_list);
  4425. spin_unlock_irqrestore(&rb->event_lock, flags);
  4426. }
  4427. /*
  4428. * Avoid racing with perf_mmap_close(AUX): stop the event
  4429. * before swizzling the event::rb pointer; if it's getting
  4430. * unmapped, its aux_mmap_count will be 0 and it won't
  4431. * restart. See the comment in __perf_pmu_output_stop().
  4432. *
  4433. * Data will inevitably be lost when set_output is done in
  4434. * mid-air, but then again, whoever does it like this is
  4435. * not in for the data anyway.
  4436. */
  4437. if (has_aux(event))
  4438. perf_event_stop(event, 0);
  4439. rcu_assign_pointer(event->rb, rb);
  4440. if (old_rb) {
  4441. ring_buffer_put(old_rb);
  4442. /*
  4443. * Since we detached before setting the new rb, so that we
  4444. * could attach the new rb, we could have missed a wakeup.
  4445. * Provide it now.
  4446. */
  4447. wake_up_all(&event->waitq);
  4448. }
  4449. }
  4450. static void ring_buffer_wakeup(struct perf_event *event)
  4451. {
  4452. struct ring_buffer *rb;
  4453. rcu_read_lock();
  4454. rb = rcu_dereference(event->rb);
  4455. if (rb) {
  4456. list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
  4457. wake_up_all(&event->waitq);
  4458. }
  4459. rcu_read_unlock();
  4460. }
  4461. struct ring_buffer *ring_buffer_get(struct perf_event *event)
  4462. {
  4463. struct ring_buffer *rb;
  4464. rcu_read_lock();
  4465. rb = rcu_dereference(event->rb);
  4466. if (rb) {
  4467. if (!atomic_inc_not_zero(&rb->refcount))
  4468. rb = NULL;
  4469. }
  4470. rcu_read_unlock();
  4471. return rb;
  4472. }
  4473. void ring_buffer_put(struct ring_buffer *rb)
  4474. {
  4475. if (!atomic_dec_and_test(&rb->refcount))
  4476. return;
  4477. WARN_ON_ONCE(!list_empty(&rb->event_list));
  4478. call_rcu(&rb->rcu_head, rb_free_rcu);
  4479. }
  4480. static void perf_mmap_open(struct vm_area_struct *vma)
  4481. {
  4482. struct perf_event *event = vma->vm_file->private_data;
  4483. atomic_inc(&event->mmap_count);
  4484. atomic_inc(&event->rb->mmap_count);
  4485. if (vma->vm_pgoff)
  4486. atomic_inc(&event->rb->aux_mmap_count);
  4487. if (event->pmu->event_mapped)
  4488. event->pmu->event_mapped(event, vma->vm_mm);
  4489. }
  4490. static void perf_pmu_output_stop(struct perf_event *event);
  4491. /*
  4492. * A buffer can be mmap()ed multiple times; either directly through the same
  4493. * event, or through other events by use of perf_event_set_output().
  4494. *
  4495. * In order to undo the VM accounting done by perf_mmap() we need to destroy
  4496. * the buffer here, where we still have a VM context. This means we need
  4497. * to detach all events redirecting to us.
  4498. */
  4499. static void perf_mmap_close(struct vm_area_struct *vma)
  4500. {
  4501. struct perf_event *event = vma->vm_file->private_data;
  4502. struct ring_buffer *rb = ring_buffer_get(event);
  4503. struct user_struct *mmap_user = rb->mmap_user;
  4504. int mmap_locked = rb->mmap_locked;
  4505. unsigned long size = perf_data_size(rb);
  4506. if (event->pmu->event_unmapped)
  4507. event->pmu->event_unmapped(event, vma->vm_mm);
  4508. /*
  4509. * rb->aux_mmap_count will always drop before rb->mmap_count and
  4510. * event->mmap_count, so it is ok to use event->mmap_mutex to
  4511. * serialize with perf_mmap here.
  4512. */
  4513. if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
  4514. atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
  4515. /*
  4516. * Stop all AUX events that are writing to this buffer,
  4517. * so that we can free its AUX pages and corresponding PMU
  4518. * data. Note that after rb::aux_mmap_count dropped to zero,
  4519. * they won't start any more (see perf_aux_output_begin()).
  4520. */
  4521. perf_pmu_output_stop(event);
  4522. /* now it's safe to free the pages */
  4523. atomic_long_sub(rb->aux_nr_pages, &mmap_user->locked_vm);
  4524. vma->vm_mm->pinned_vm -= rb->aux_mmap_locked;
  4525. /* this has to be the last one */
  4526. rb_free_aux(rb);
  4527. WARN_ON_ONCE(atomic_read(&rb->aux_refcount));
  4528. mutex_unlock(&event->mmap_mutex);
  4529. }
  4530. atomic_dec(&rb->mmap_count);
  4531. if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
  4532. goto out_put;
  4533. ring_buffer_attach(event, NULL);
  4534. mutex_unlock(&event->mmap_mutex);
  4535. /* If there's still other mmap()s of this buffer, we're done. */
  4536. if (atomic_read(&rb->mmap_count))
  4537. goto out_put;
  4538. /*
  4539. * No other mmap()s, detach from all other events that might redirect
  4540. * into the now unreachable buffer. Somewhat complicated by the
  4541. * fact that rb::event_lock otherwise nests inside mmap_mutex.
  4542. */
  4543. again:
  4544. rcu_read_lock();
  4545. list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
  4546. if (!atomic_long_inc_not_zero(&event->refcount)) {
  4547. /*
  4548. * This event is en-route to free_event() which will
  4549. * detach it and remove it from the list.
  4550. */
  4551. continue;
  4552. }
  4553. rcu_read_unlock();
  4554. mutex_lock(&event->mmap_mutex);
  4555. /*
  4556. * Check we didn't race with perf_event_set_output() which can
  4557. * swizzle the rb from under us while we were waiting to
  4558. * acquire mmap_mutex.
  4559. *
  4560. * If we find a different rb; ignore this event, a next
  4561. * iteration will no longer find it on the list. We have to
  4562. * still restart the iteration to make sure we're not now
  4563. * iterating the wrong list.
  4564. */
  4565. if (event->rb == rb)
  4566. ring_buffer_attach(event, NULL);
  4567. mutex_unlock(&event->mmap_mutex);
  4568. put_event(event);
  4569. /*
  4570. * Restart the iteration; either we're on the wrong list or
  4571. * destroyed its integrity by doing a deletion.
  4572. */
  4573. goto again;
  4574. }
  4575. rcu_read_unlock();
  4576. /*
  4577. * It could be there's still a few 0-ref events on the list; they'll
  4578. * get cleaned up by free_event() -- they'll also still have their
  4579. * ref on the rb and will free it whenever they are done with it.
  4580. *
  4581. * Aside from that, this buffer is 'fully' detached and unmapped,
  4582. * undo the VM accounting.
  4583. */
  4584. atomic_long_sub((size >> PAGE_SHIFT) + 1, &mmap_user->locked_vm);
  4585. vma->vm_mm->pinned_vm -= mmap_locked;
  4586. free_uid(mmap_user);
  4587. out_put:
  4588. ring_buffer_put(rb); /* could be last */
  4589. }
  4590. static const struct vm_operations_struct perf_mmap_vmops = {
  4591. .open = perf_mmap_open,
  4592. .close = perf_mmap_close, /* non mergable */
  4593. .fault = perf_mmap_fault,
  4594. .page_mkwrite = perf_mmap_fault,
  4595. };
  4596. static int perf_mmap(struct file *file, struct vm_area_struct *vma)
  4597. {
  4598. struct perf_event *event = file->private_data;
  4599. unsigned long user_locked, user_lock_limit;
  4600. struct user_struct *user = current_user();
  4601. unsigned long locked, lock_limit;
  4602. struct ring_buffer *rb = NULL;
  4603. unsigned long vma_size;
  4604. unsigned long nr_pages;
  4605. long user_extra = 0, extra = 0;
  4606. int ret = 0, flags = 0;
  4607. /*
  4608. * Don't allow mmap() of inherited per-task counters. This would
  4609. * create a performance issue due to all children writing to the
  4610. * same rb.
  4611. */
  4612. if (event->cpu == -1 && event->attr.inherit)
  4613. return -EINVAL;
  4614. if (!(vma->vm_flags & VM_SHARED))
  4615. return -EINVAL;
  4616. vma_size = vma->vm_end - vma->vm_start;
  4617. if (vma->vm_pgoff == 0) {
  4618. nr_pages = (vma_size / PAGE_SIZE) - 1;
  4619. } else {
  4620. /*
  4621. * AUX area mapping: if rb->aux_nr_pages != 0, it's already
  4622. * mapped, all subsequent mappings should have the same size
  4623. * and offset. Must be above the normal perf buffer.
  4624. */
  4625. u64 aux_offset, aux_size;
  4626. if (!event->rb)
  4627. return -EINVAL;
  4628. nr_pages = vma_size / PAGE_SIZE;
  4629. mutex_lock(&event->mmap_mutex);
  4630. ret = -EINVAL;
  4631. rb = event->rb;
  4632. if (!rb)
  4633. goto aux_unlock;
  4634. aux_offset = READ_ONCE(rb->user_page->aux_offset);
  4635. aux_size = READ_ONCE(rb->user_page->aux_size);
  4636. if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
  4637. goto aux_unlock;
  4638. if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
  4639. goto aux_unlock;
  4640. /* already mapped with a different offset */
  4641. if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
  4642. goto aux_unlock;
  4643. if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
  4644. goto aux_unlock;
  4645. /* already mapped with a different size */
  4646. if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
  4647. goto aux_unlock;
  4648. if (!is_power_of_2(nr_pages))
  4649. goto aux_unlock;
  4650. if (!atomic_inc_not_zero(&rb->mmap_count))
  4651. goto aux_unlock;
  4652. if (rb_has_aux(rb)) {
  4653. atomic_inc(&rb->aux_mmap_count);
  4654. ret = 0;
  4655. goto unlock;
  4656. }
  4657. atomic_set(&rb->aux_mmap_count, 1);
  4658. user_extra = nr_pages;
  4659. goto accounting;
  4660. }
  4661. /*
  4662. * If we have rb pages ensure they're a power-of-two number, so we
  4663. * can do bitmasks instead of modulo.
  4664. */
  4665. if (nr_pages != 0 && !is_power_of_2(nr_pages))
  4666. return -EINVAL;
  4667. if (vma_size != PAGE_SIZE * (1 + nr_pages))
  4668. return -EINVAL;
  4669. WARN_ON_ONCE(event->ctx->parent_ctx);
  4670. again:
  4671. mutex_lock(&event->mmap_mutex);
  4672. if (event->rb) {
  4673. if (event->rb->nr_pages != nr_pages) {
  4674. ret = -EINVAL;
  4675. goto unlock;
  4676. }
  4677. if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
  4678. /*
  4679. * Raced against perf_mmap_close() through
  4680. * perf_event_set_output(). Try again, hope for better
  4681. * luck.
  4682. */
  4683. mutex_unlock(&event->mmap_mutex);
  4684. goto again;
  4685. }
  4686. goto unlock;
  4687. }
  4688. user_extra = nr_pages + 1;
  4689. accounting:
  4690. user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
  4691. /*
  4692. * Increase the limit linearly with more CPUs:
  4693. */
  4694. user_lock_limit *= num_online_cpus();
  4695. user_locked = atomic_long_read(&user->locked_vm) + user_extra;
  4696. if (user_locked > user_lock_limit)
  4697. extra = user_locked - user_lock_limit;
  4698. lock_limit = rlimit(RLIMIT_MEMLOCK);
  4699. lock_limit >>= PAGE_SHIFT;
  4700. locked = vma->vm_mm->pinned_vm + extra;
  4701. if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
  4702. !capable(CAP_IPC_LOCK)) {
  4703. ret = -EPERM;
  4704. goto unlock;
  4705. }
  4706. WARN_ON(!rb && event->rb);
  4707. if (vma->vm_flags & VM_WRITE)
  4708. flags |= RING_BUFFER_WRITABLE;
  4709. if (!rb) {
  4710. rb = rb_alloc(nr_pages,
  4711. event->attr.watermark ? event->attr.wakeup_watermark : 0,
  4712. event->cpu, flags);
  4713. if (!rb) {
  4714. ret = -ENOMEM;
  4715. goto unlock;
  4716. }
  4717. atomic_set(&rb->mmap_count, 1);
  4718. rb->mmap_user = get_current_user();
  4719. rb->mmap_locked = extra;
  4720. ring_buffer_attach(event, rb);
  4721. perf_event_init_userpage(event);
  4722. perf_event_update_userpage(event);
  4723. } else {
  4724. ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
  4725. event->attr.aux_watermark, flags);
  4726. if (!ret)
  4727. rb->aux_mmap_locked = extra;
  4728. }
  4729. unlock:
  4730. if (!ret) {
  4731. atomic_long_add(user_extra, &user->locked_vm);
  4732. vma->vm_mm->pinned_vm += extra;
  4733. atomic_inc(&event->mmap_count);
  4734. } else if (rb) {
  4735. atomic_dec(&rb->mmap_count);
  4736. }
  4737. aux_unlock:
  4738. mutex_unlock(&event->mmap_mutex);
  4739. /*
  4740. * Since pinned accounting is per vm we cannot allow fork() to copy our
  4741. * vma.
  4742. */
  4743. vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
  4744. vma->vm_ops = &perf_mmap_vmops;
  4745. if (event->pmu->event_mapped)
  4746. event->pmu->event_mapped(event, vma->vm_mm);
  4747. return ret;
  4748. }
  4749. static int perf_fasync(int fd, struct file *filp, int on)
  4750. {
  4751. struct inode *inode = file_inode(filp);
  4752. struct perf_event *event = filp->private_data;
  4753. int retval;
  4754. inode_lock(inode);
  4755. retval = fasync_helper(fd, filp, on, &event->fasync);
  4756. inode_unlock(inode);
  4757. if (retval < 0)
  4758. return retval;
  4759. return 0;
  4760. }
  4761. static const struct file_operations perf_fops = {
  4762. .llseek = no_llseek,
  4763. .release = perf_release,
  4764. .read = perf_read,
  4765. .poll = perf_poll,
  4766. .unlocked_ioctl = perf_ioctl,
  4767. .compat_ioctl = perf_compat_ioctl,
  4768. .mmap = perf_mmap,
  4769. .fasync = perf_fasync,
  4770. };
  4771. /*
  4772. * Perf event wakeup
  4773. *
  4774. * If there's data, ensure we set the poll() state and publish everything
  4775. * to user-space before waking everybody up.
  4776. */
  4777. static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
  4778. {
  4779. /* only the parent has fasync state */
  4780. if (event->parent)
  4781. event = event->parent;
  4782. return &event->fasync;
  4783. }
  4784. void perf_event_wakeup(struct perf_event *event)
  4785. {
  4786. ring_buffer_wakeup(event);
  4787. if (event->pending_kill) {
  4788. kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
  4789. event->pending_kill = 0;
  4790. }
  4791. }
  4792. static void perf_pending_event(struct irq_work *entry)
  4793. {
  4794. struct perf_event *event = container_of(entry,
  4795. struct perf_event, pending);
  4796. int rctx;
  4797. rctx = perf_swevent_get_recursion_context();
  4798. /*
  4799. * If we 'fail' here, that's OK, it means recursion is already disabled
  4800. * and we won't recurse 'further'.
  4801. */
  4802. if (event->pending_disable) {
  4803. event->pending_disable = 0;
  4804. perf_event_disable_local(event);
  4805. }
  4806. if (event->pending_wakeup) {
  4807. event->pending_wakeup = 0;
  4808. perf_event_wakeup(event);
  4809. }
  4810. if (rctx >= 0)
  4811. perf_swevent_put_recursion_context(rctx);
  4812. }
  4813. /*
  4814. * We assume there is only KVM supporting the callbacks.
  4815. * Later on, we might change it to a list if there is
  4816. * another virtualization implementation supporting the callbacks.
  4817. */
  4818. struct perf_guest_info_callbacks *perf_guest_cbs;
  4819. int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
  4820. {
  4821. perf_guest_cbs = cbs;
  4822. return 0;
  4823. }
  4824. EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
  4825. int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
  4826. {
  4827. perf_guest_cbs = NULL;
  4828. return 0;
  4829. }
  4830. EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
  4831. static void
  4832. perf_output_sample_regs(struct perf_output_handle *handle,
  4833. struct pt_regs *regs, u64 mask)
  4834. {
  4835. int bit;
  4836. DECLARE_BITMAP(_mask, 64);
  4837. bitmap_from_u64(_mask, mask);
  4838. for_each_set_bit(bit, _mask, sizeof(mask) * BITS_PER_BYTE) {
  4839. u64 val;
  4840. val = perf_reg_value(regs, bit);
  4841. perf_output_put(handle, val);
  4842. }
  4843. }
  4844. static void perf_sample_regs_user(struct perf_regs *regs_user,
  4845. struct pt_regs *regs,
  4846. struct pt_regs *regs_user_copy)
  4847. {
  4848. if (user_mode(regs)) {
  4849. regs_user->abi = perf_reg_abi(current);
  4850. regs_user->regs = regs;
  4851. } else if (current->mm) {
  4852. perf_get_regs_user(regs_user, regs, regs_user_copy);
  4853. } else {
  4854. regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
  4855. regs_user->regs = NULL;
  4856. }
  4857. }
  4858. static void perf_sample_regs_intr(struct perf_regs *regs_intr,
  4859. struct pt_regs *regs)
  4860. {
  4861. regs_intr->regs = regs;
  4862. regs_intr->abi = perf_reg_abi(current);
  4863. }
  4864. /*
  4865. * Get remaining task size from user stack pointer.
  4866. *
  4867. * It'd be better to take stack vma map and limit this more
  4868. * precisly, but there's no way to get it safely under interrupt,
  4869. * so using TASK_SIZE as limit.
  4870. */
  4871. static u64 perf_ustack_task_size(struct pt_regs *regs)
  4872. {
  4873. unsigned long addr = perf_user_stack_pointer(regs);
  4874. if (!addr || addr >= TASK_SIZE)
  4875. return 0;
  4876. return TASK_SIZE - addr;
  4877. }
  4878. static u16
  4879. perf_sample_ustack_size(u16 stack_size, u16 header_size,
  4880. struct pt_regs *regs)
  4881. {
  4882. u64 task_size;
  4883. /* No regs, no stack pointer, no dump. */
  4884. if (!regs)
  4885. return 0;
  4886. /*
  4887. * Check if we fit in with the requested stack size into the:
  4888. * - TASK_SIZE
  4889. * If we don't, we limit the size to the TASK_SIZE.
  4890. *
  4891. * - remaining sample size
  4892. * If we don't, we customize the stack size to
  4893. * fit in to the remaining sample size.
  4894. */
  4895. task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
  4896. stack_size = min(stack_size, (u16) task_size);
  4897. /* Current header size plus static size and dynamic size. */
  4898. header_size += 2 * sizeof(u64);
  4899. /* Do we fit in with the current stack dump size? */
  4900. if ((u16) (header_size + stack_size) < header_size) {
  4901. /*
  4902. * If we overflow the maximum size for the sample,
  4903. * we customize the stack dump size to fit in.
  4904. */
  4905. stack_size = USHRT_MAX - header_size - sizeof(u64);
  4906. stack_size = round_up(stack_size, sizeof(u64));
  4907. }
  4908. return stack_size;
  4909. }
  4910. static void
  4911. perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
  4912. struct pt_regs *regs)
  4913. {
  4914. /* Case of a kernel thread, nothing to dump */
  4915. if (!regs) {
  4916. u64 size = 0;
  4917. perf_output_put(handle, size);
  4918. } else {
  4919. unsigned long sp;
  4920. unsigned int rem;
  4921. u64 dyn_size;
  4922. mm_segment_t fs;
  4923. /*
  4924. * We dump:
  4925. * static size
  4926. * - the size requested by user or the best one we can fit
  4927. * in to the sample max size
  4928. * data
  4929. * - user stack dump data
  4930. * dynamic size
  4931. * - the actual dumped size
  4932. */
  4933. /* Static size. */
  4934. perf_output_put(handle, dump_size);
  4935. /* Data. */
  4936. sp = perf_user_stack_pointer(regs);
  4937. fs = get_fs();
  4938. set_fs(USER_DS);
  4939. rem = __output_copy_user(handle, (void *) sp, dump_size);
  4940. set_fs(fs);
  4941. dyn_size = dump_size - rem;
  4942. perf_output_skip(handle, rem);
  4943. /* Dynamic size. */
  4944. perf_output_put(handle, dyn_size);
  4945. }
  4946. }
  4947. static void __perf_event_header__init_id(struct perf_event_header *header,
  4948. struct perf_sample_data *data,
  4949. struct perf_event *event)
  4950. {
  4951. u64 sample_type = event->attr.sample_type;
  4952. data->type = sample_type;
  4953. header->size += event->id_header_size;
  4954. if (sample_type & PERF_SAMPLE_TID) {
  4955. /* namespace issues */
  4956. data->tid_entry.pid = perf_event_pid(event, current);
  4957. data->tid_entry.tid = perf_event_tid(event, current);
  4958. }
  4959. if (sample_type & PERF_SAMPLE_TIME)
  4960. data->time = perf_event_clock(event);
  4961. if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
  4962. data->id = primary_event_id(event);
  4963. if (sample_type & PERF_SAMPLE_STREAM_ID)
  4964. data->stream_id = event->id;
  4965. if (sample_type & PERF_SAMPLE_CPU) {
  4966. data->cpu_entry.cpu = raw_smp_processor_id();
  4967. data->cpu_entry.reserved = 0;
  4968. }
  4969. }
  4970. void perf_event_header__init_id(struct perf_event_header *header,
  4971. struct perf_sample_data *data,
  4972. struct perf_event *event)
  4973. {
  4974. if (event->attr.sample_id_all)
  4975. __perf_event_header__init_id(header, data, event);
  4976. }
  4977. static void __perf_event__output_id_sample(struct perf_output_handle *handle,
  4978. struct perf_sample_data *data)
  4979. {
  4980. u64 sample_type = data->type;
  4981. if (sample_type & PERF_SAMPLE_TID)
  4982. perf_output_put(handle, data->tid_entry);
  4983. if (sample_type & PERF_SAMPLE_TIME)
  4984. perf_output_put(handle, data->time);
  4985. if (sample_type & PERF_SAMPLE_ID)
  4986. perf_output_put(handle, data->id);
  4987. if (sample_type & PERF_SAMPLE_STREAM_ID)
  4988. perf_output_put(handle, data->stream_id);
  4989. if (sample_type & PERF_SAMPLE_CPU)
  4990. perf_output_put(handle, data->cpu_entry);
  4991. if (sample_type & PERF_SAMPLE_IDENTIFIER)
  4992. perf_output_put(handle, data->id);
  4993. }
  4994. void perf_event__output_id_sample(struct perf_event *event,
  4995. struct perf_output_handle *handle,
  4996. struct perf_sample_data *sample)
  4997. {
  4998. if (event->attr.sample_id_all)
  4999. __perf_event__output_id_sample(handle, sample);
  5000. }
  5001. static void perf_output_read_one(struct perf_output_handle *handle,
  5002. struct perf_event *event,
  5003. u64 enabled, u64 running)
  5004. {
  5005. u64 read_format = event->attr.read_format;
  5006. u64 values[4];
  5007. int n = 0;
  5008. values[n++] = perf_event_count(event);
  5009. if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
  5010. values[n++] = enabled +
  5011. atomic64_read(&event->child_total_time_enabled);
  5012. }
  5013. if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
  5014. values[n++] = running +
  5015. atomic64_read(&event->child_total_time_running);
  5016. }
  5017. if (read_format & PERF_FORMAT_ID)
  5018. values[n++] = primary_event_id(event);
  5019. __output_copy(handle, values, n * sizeof(u64));
  5020. }
  5021. static void perf_output_read_group(struct perf_output_handle *handle,
  5022. struct perf_event *event,
  5023. u64 enabled, u64 running)
  5024. {
  5025. struct perf_event *leader = event->group_leader, *sub;
  5026. u64 read_format = event->attr.read_format;
  5027. u64 values[5];
  5028. int n = 0;
  5029. values[n++] = 1 + leader->nr_siblings;
  5030. if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
  5031. values[n++] = enabled;
  5032. if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
  5033. values[n++] = running;
  5034. if ((leader != event) &&
  5035. (leader->state == PERF_EVENT_STATE_ACTIVE))
  5036. leader->pmu->read(leader);
  5037. values[n++] = perf_event_count(leader);
  5038. if (read_format & PERF_FORMAT_ID)
  5039. values[n++] = primary_event_id(leader);
  5040. __output_copy(handle, values, n * sizeof(u64));
  5041. for_each_sibling_event(sub, leader) {
  5042. n = 0;
  5043. if ((sub != event) &&
  5044. (sub->state == PERF_EVENT_STATE_ACTIVE))
  5045. sub->pmu->read(sub);
  5046. values[n++] = perf_event_count(sub);
  5047. if (read_format & PERF_FORMAT_ID)
  5048. values[n++] = primary_event_id(sub);
  5049. __output_copy(handle, values, n * sizeof(u64));
  5050. }
  5051. }
  5052. #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
  5053. PERF_FORMAT_TOTAL_TIME_RUNNING)
  5054. /*
  5055. * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
  5056. *
  5057. * The problem is that its both hard and excessively expensive to iterate the
  5058. * child list, not to mention that its impossible to IPI the children running
  5059. * on another CPU, from interrupt/NMI context.
  5060. */
  5061. static void perf_output_read(struct perf_output_handle *handle,
  5062. struct perf_event *event)
  5063. {
  5064. u64 enabled = 0, running = 0, now;
  5065. u64 read_format = event->attr.read_format;
  5066. /*
  5067. * compute total_time_enabled, total_time_running
  5068. * based on snapshot values taken when the event
  5069. * was last scheduled in.
  5070. *
  5071. * we cannot simply called update_context_time()
  5072. * because of locking issue as we are called in
  5073. * NMI context
  5074. */
  5075. if (read_format & PERF_FORMAT_TOTAL_TIMES)
  5076. calc_timer_values(event, &now, &enabled, &running);
  5077. if (event->attr.read_format & PERF_FORMAT_GROUP)
  5078. perf_output_read_group(handle, event, enabled, running);
  5079. else
  5080. perf_output_read_one(handle, event, enabled, running);
  5081. }
  5082. void perf_output_sample(struct perf_output_handle *handle,
  5083. struct perf_event_header *header,
  5084. struct perf_sample_data *data,
  5085. struct perf_event *event)
  5086. {
  5087. u64 sample_type = data->type;
  5088. perf_output_put(handle, *header);
  5089. if (sample_type & PERF_SAMPLE_IDENTIFIER)
  5090. perf_output_put(handle, data->id);
  5091. if (sample_type & PERF_SAMPLE_IP)
  5092. perf_output_put(handle, data->ip);
  5093. if (sample_type & PERF_SAMPLE_TID)
  5094. perf_output_put(handle, data->tid_entry);
  5095. if (sample_type & PERF_SAMPLE_TIME)
  5096. perf_output_put(handle, data->time);
  5097. if (sample_type & PERF_SAMPLE_ADDR)
  5098. perf_output_put(handle, data->addr);
  5099. if (sample_type & PERF_SAMPLE_ID)
  5100. perf_output_put(handle, data->id);
  5101. if (sample_type & PERF_SAMPLE_STREAM_ID)
  5102. perf_output_put(handle, data->stream_id);
  5103. if (sample_type & PERF_SAMPLE_CPU)
  5104. perf_output_put(handle, data->cpu_entry);
  5105. if (sample_type & PERF_SAMPLE_PERIOD)
  5106. perf_output_put(handle, data->period);
  5107. if (sample_type & PERF_SAMPLE_READ)
  5108. perf_output_read(handle, event);
  5109. if (sample_type & PERF_SAMPLE_CALLCHAIN) {
  5110. int size = 1;
  5111. size += data->callchain->nr;
  5112. size *= sizeof(u64);
  5113. __output_copy(handle, data->callchain, size);
  5114. }
  5115. if (sample_type & PERF_SAMPLE_RAW) {
  5116. struct perf_raw_record *raw = data->raw;
  5117. if (raw) {
  5118. struct perf_raw_frag *frag = &raw->frag;
  5119. perf_output_put(handle, raw->size);
  5120. do {
  5121. if (frag->copy) {
  5122. __output_custom(handle, frag->copy,
  5123. frag->data, frag->size);
  5124. } else {
  5125. __output_copy(handle, frag->data,
  5126. frag->size);
  5127. }
  5128. if (perf_raw_frag_last(frag))
  5129. break;
  5130. frag = frag->next;
  5131. } while (1);
  5132. if (frag->pad)
  5133. __output_skip(handle, NULL, frag->pad);
  5134. } else {
  5135. struct {
  5136. u32 size;
  5137. u32 data;
  5138. } raw = {
  5139. .size = sizeof(u32),
  5140. .data = 0,
  5141. };
  5142. perf_output_put(handle, raw);
  5143. }
  5144. }
  5145. if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
  5146. if (data->br_stack) {
  5147. size_t size;
  5148. size = data->br_stack->nr
  5149. * sizeof(struct perf_branch_entry);
  5150. perf_output_put(handle, data->br_stack->nr);
  5151. perf_output_copy(handle, data->br_stack->entries, size);
  5152. } else {
  5153. /*
  5154. * we always store at least the value of nr
  5155. */
  5156. u64 nr = 0;
  5157. perf_output_put(handle, nr);
  5158. }
  5159. }
  5160. if (sample_type & PERF_SAMPLE_REGS_USER) {
  5161. u64 abi = data->regs_user.abi;
  5162. /*
  5163. * If there are no regs to dump, notice it through
  5164. * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
  5165. */
  5166. perf_output_put(handle, abi);
  5167. if (abi) {
  5168. u64 mask = event->attr.sample_regs_user;
  5169. perf_output_sample_regs(handle,
  5170. data->regs_user.regs,
  5171. mask);
  5172. }
  5173. }
  5174. if (sample_type & PERF_SAMPLE_STACK_USER) {
  5175. perf_output_sample_ustack(handle,
  5176. data->stack_user_size,
  5177. data->regs_user.regs);
  5178. }
  5179. if (sample_type & PERF_SAMPLE_WEIGHT)
  5180. perf_output_put(handle, data->weight);
  5181. if (sample_type & PERF_SAMPLE_DATA_SRC)
  5182. perf_output_put(handle, data->data_src.val);
  5183. if (sample_type & PERF_SAMPLE_TRANSACTION)
  5184. perf_output_put(handle, data->txn);
  5185. if (sample_type & PERF_SAMPLE_REGS_INTR) {
  5186. u64 abi = data->regs_intr.abi;
  5187. /*
  5188. * If there are no regs to dump, notice it through
  5189. * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
  5190. */
  5191. perf_output_put(handle, abi);
  5192. if (abi) {
  5193. u64 mask = event->attr.sample_regs_intr;
  5194. perf_output_sample_regs(handle,
  5195. data->regs_intr.regs,
  5196. mask);
  5197. }
  5198. }
  5199. if (sample_type & PERF_SAMPLE_PHYS_ADDR)
  5200. perf_output_put(handle, data->phys_addr);
  5201. if (!event->attr.watermark) {
  5202. int wakeup_events = event->attr.wakeup_events;
  5203. if (wakeup_events) {
  5204. struct ring_buffer *rb = handle->rb;
  5205. int events = local_inc_return(&rb->events);
  5206. if (events >= wakeup_events) {
  5207. local_sub(wakeup_events, &rb->events);
  5208. local_inc(&rb->wakeup);
  5209. }
  5210. }
  5211. }
  5212. }
  5213. static u64 perf_virt_to_phys(u64 virt)
  5214. {
  5215. u64 phys_addr = 0;
  5216. struct page *p = NULL;
  5217. if (!virt)
  5218. return 0;
  5219. if (virt >= TASK_SIZE) {
  5220. /* If it's vmalloc()d memory, leave phys_addr as 0 */
  5221. if (virt_addr_valid((void *)(uintptr_t)virt) &&
  5222. !(virt >= VMALLOC_START && virt < VMALLOC_END))
  5223. phys_addr = (u64)virt_to_phys((void *)(uintptr_t)virt);
  5224. } else {
  5225. /*
  5226. * Walking the pages tables for user address.
  5227. * Interrupts are disabled, so it prevents any tear down
  5228. * of the page tables.
  5229. * Try IRQ-safe __get_user_pages_fast first.
  5230. * If failed, leave phys_addr as 0.
  5231. */
  5232. if ((current->mm != NULL) &&
  5233. (__get_user_pages_fast(virt, 1, 0, &p) == 1))
  5234. phys_addr = page_to_phys(p) + virt % PAGE_SIZE;
  5235. if (p)
  5236. put_page(p);
  5237. }
  5238. return phys_addr;
  5239. }
  5240. static struct perf_callchain_entry __empty_callchain = { .nr = 0, };
  5241. struct perf_callchain_entry *
  5242. perf_callchain(struct perf_event *event, struct pt_regs *regs)
  5243. {
  5244. bool kernel = !event->attr.exclude_callchain_kernel;
  5245. bool user = !event->attr.exclude_callchain_user;
  5246. /* Disallow cross-task user callchains. */
  5247. bool crosstask = event->ctx->task && event->ctx->task != current;
  5248. const u32 max_stack = event->attr.sample_max_stack;
  5249. struct perf_callchain_entry *callchain;
  5250. if (!kernel && !user)
  5251. return &__empty_callchain;
  5252. callchain = get_perf_callchain(regs, 0, kernel, user,
  5253. max_stack, crosstask, true);
  5254. return callchain ?: &__empty_callchain;
  5255. }
  5256. void perf_prepare_sample(struct perf_event_header *header,
  5257. struct perf_sample_data *data,
  5258. struct perf_event *event,
  5259. struct pt_regs *regs)
  5260. {
  5261. u64 sample_type = event->attr.sample_type;
  5262. header->type = PERF_RECORD_SAMPLE;
  5263. header->size = sizeof(*header) + event->header_size;
  5264. header->misc = 0;
  5265. header->misc |= perf_misc_flags(regs);
  5266. __perf_event_header__init_id(header, data, event);
  5267. if (sample_type & PERF_SAMPLE_IP)
  5268. data->ip = perf_instruction_pointer(regs);
  5269. if (sample_type & PERF_SAMPLE_CALLCHAIN) {
  5270. int size = 1;
  5271. if (!(sample_type & __PERF_SAMPLE_CALLCHAIN_EARLY))
  5272. data->callchain = perf_callchain(event, regs);
  5273. size += data->callchain->nr;
  5274. header->size += size * sizeof(u64);
  5275. }
  5276. if (sample_type & PERF_SAMPLE_RAW) {
  5277. struct perf_raw_record *raw = data->raw;
  5278. int size;
  5279. if (raw) {
  5280. struct perf_raw_frag *frag = &raw->frag;
  5281. u32 sum = 0;
  5282. do {
  5283. sum += frag->size;
  5284. if (perf_raw_frag_last(frag))
  5285. break;
  5286. frag = frag->next;
  5287. } while (1);
  5288. size = round_up(sum + sizeof(u32), sizeof(u64));
  5289. raw->size = size - sizeof(u32);
  5290. frag->pad = raw->size - sum;
  5291. } else {
  5292. size = sizeof(u64);
  5293. }
  5294. header->size += size;
  5295. }
  5296. if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
  5297. int size = sizeof(u64); /* nr */
  5298. if (data->br_stack) {
  5299. size += data->br_stack->nr
  5300. * sizeof(struct perf_branch_entry);
  5301. }
  5302. header->size += size;
  5303. }
  5304. if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
  5305. perf_sample_regs_user(&data->regs_user, regs,
  5306. &data->regs_user_copy);
  5307. if (sample_type & PERF_SAMPLE_REGS_USER) {
  5308. /* regs dump ABI info */
  5309. int size = sizeof(u64);
  5310. if (data->regs_user.regs) {
  5311. u64 mask = event->attr.sample_regs_user;
  5312. size += hweight64(mask) * sizeof(u64);
  5313. }
  5314. header->size += size;
  5315. }
  5316. if (sample_type & PERF_SAMPLE_STACK_USER) {
  5317. /*
  5318. * Either we need PERF_SAMPLE_STACK_USER bit to be allways
  5319. * processed as the last one or have additional check added
  5320. * in case new sample type is added, because we could eat
  5321. * up the rest of the sample size.
  5322. */
  5323. u16 stack_size = event->attr.sample_stack_user;
  5324. u16 size = sizeof(u64);
  5325. stack_size = perf_sample_ustack_size(stack_size, header->size,
  5326. data->regs_user.regs);
  5327. /*
  5328. * If there is something to dump, add space for the dump
  5329. * itself and for the field that tells the dynamic size,
  5330. * which is how many have been actually dumped.
  5331. */
  5332. if (stack_size)
  5333. size += sizeof(u64) + stack_size;
  5334. data->stack_user_size = stack_size;
  5335. header->size += size;
  5336. }
  5337. if (sample_type & PERF_SAMPLE_REGS_INTR) {
  5338. /* regs dump ABI info */
  5339. int size = sizeof(u64);
  5340. perf_sample_regs_intr(&data->regs_intr, regs);
  5341. if (data->regs_intr.regs) {
  5342. u64 mask = event->attr.sample_regs_intr;
  5343. size += hweight64(mask) * sizeof(u64);
  5344. }
  5345. header->size += size;
  5346. }
  5347. if (sample_type & PERF_SAMPLE_PHYS_ADDR)
  5348. data->phys_addr = perf_virt_to_phys(data->addr);
  5349. }
  5350. static __always_inline void
  5351. __perf_event_output(struct perf_event *event,
  5352. struct perf_sample_data *data,
  5353. struct pt_regs *regs,
  5354. int (*output_begin)(struct perf_output_handle *,
  5355. struct perf_event *,
  5356. unsigned int))
  5357. {
  5358. struct perf_output_handle handle;
  5359. struct perf_event_header header;
  5360. /* protect the callchain buffers */
  5361. rcu_read_lock();
  5362. perf_prepare_sample(&header, data, event, regs);
  5363. if (output_begin(&handle, event, header.size))
  5364. goto exit;
  5365. perf_output_sample(&handle, &header, data, event);
  5366. perf_output_end(&handle);
  5367. exit:
  5368. rcu_read_unlock();
  5369. }
  5370. void
  5371. perf_event_output_forward(struct perf_event *event,
  5372. struct perf_sample_data *data,
  5373. struct pt_regs *regs)
  5374. {
  5375. __perf_event_output(event, data, regs, perf_output_begin_forward);
  5376. }
  5377. void
  5378. perf_event_output_backward(struct perf_event *event,
  5379. struct perf_sample_data *data,
  5380. struct pt_regs *regs)
  5381. {
  5382. __perf_event_output(event, data, regs, perf_output_begin_backward);
  5383. }
  5384. void
  5385. perf_event_output(struct perf_event *event,
  5386. struct perf_sample_data *data,
  5387. struct pt_regs *regs)
  5388. {
  5389. __perf_event_output(event, data, regs, perf_output_begin);
  5390. }
  5391. /*
  5392. * read event_id
  5393. */
  5394. struct perf_read_event {
  5395. struct perf_event_header header;
  5396. u32 pid;
  5397. u32 tid;
  5398. };
  5399. static void
  5400. perf_event_read_event(struct perf_event *event,
  5401. struct task_struct *task)
  5402. {
  5403. struct perf_output_handle handle;
  5404. struct perf_sample_data sample;
  5405. struct perf_read_event read_event = {
  5406. .header = {
  5407. .type = PERF_RECORD_READ,
  5408. .misc = 0,
  5409. .size = sizeof(read_event) + event->read_size,
  5410. },
  5411. .pid = perf_event_pid(event, task),
  5412. .tid = perf_event_tid(event, task),
  5413. };
  5414. int ret;
  5415. perf_event_header__init_id(&read_event.header, &sample, event);
  5416. ret = perf_output_begin(&handle, event, read_event.header.size);
  5417. if (ret)
  5418. return;
  5419. perf_output_put(&handle, read_event);
  5420. perf_output_read(&handle, event);
  5421. perf_event__output_id_sample(event, &handle, &sample);
  5422. perf_output_end(&handle);
  5423. }
  5424. typedef void (perf_iterate_f)(struct perf_event *event, void *data);
  5425. static void
  5426. perf_iterate_ctx(struct perf_event_context *ctx,
  5427. perf_iterate_f output,
  5428. void *data, bool all)
  5429. {
  5430. struct perf_event *event;
  5431. list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
  5432. if (!all) {
  5433. if (event->state < PERF_EVENT_STATE_INACTIVE)
  5434. continue;
  5435. if (!event_filter_match(event))
  5436. continue;
  5437. }
  5438. output(event, data);
  5439. }
  5440. }
  5441. static void perf_iterate_sb_cpu(perf_iterate_f output, void *data)
  5442. {
  5443. struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events);
  5444. struct perf_event *event;
  5445. list_for_each_entry_rcu(event, &pel->list, sb_list) {
  5446. /*
  5447. * Skip events that are not fully formed yet; ensure that
  5448. * if we observe event->ctx, both event and ctx will be
  5449. * complete enough. See perf_install_in_context().
  5450. */
  5451. if (!smp_load_acquire(&event->ctx))
  5452. continue;
  5453. if (event->state < PERF_EVENT_STATE_INACTIVE)
  5454. continue;
  5455. if (!event_filter_match(event))
  5456. continue;
  5457. output(event, data);
  5458. }
  5459. }
  5460. /*
  5461. * Iterate all events that need to receive side-band events.
  5462. *
  5463. * For new callers; ensure that account_pmu_sb_event() includes
  5464. * your event, otherwise it might not get delivered.
  5465. */
  5466. static void
  5467. perf_iterate_sb(perf_iterate_f output, void *data,
  5468. struct perf_event_context *task_ctx)
  5469. {
  5470. struct perf_event_context *ctx;
  5471. int ctxn;
  5472. rcu_read_lock();
  5473. preempt_disable();
  5474. /*
  5475. * If we have task_ctx != NULL we only notify the task context itself.
  5476. * The task_ctx is set only for EXIT events before releasing task
  5477. * context.
  5478. */
  5479. if (task_ctx) {
  5480. perf_iterate_ctx(task_ctx, output, data, false);
  5481. goto done;
  5482. }
  5483. perf_iterate_sb_cpu(output, data);
  5484. for_each_task_context_nr(ctxn) {
  5485. ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
  5486. if (ctx)
  5487. perf_iterate_ctx(ctx, output, data, false);
  5488. }
  5489. done:
  5490. preempt_enable();
  5491. rcu_read_unlock();
  5492. }
  5493. /*
  5494. * Clear all file-based filters at exec, they'll have to be
  5495. * re-instated when/if these objects are mmapped again.
  5496. */
  5497. static void perf_event_addr_filters_exec(struct perf_event *event, void *data)
  5498. {
  5499. struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
  5500. struct perf_addr_filter *filter;
  5501. unsigned int restart = 0, count = 0;
  5502. unsigned long flags;
  5503. if (!has_addr_filter(event))
  5504. return;
  5505. raw_spin_lock_irqsave(&ifh->lock, flags);
  5506. list_for_each_entry(filter, &ifh->list, entry) {
  5507. if (filter->path.dentry) {
  5508. event->addr_filters_offs[count] = 0;
  5509. restart++;
  5510. }
  5511. count++;
  5512. }
  5513. if (restart)
  5514. event->addr_filters_gen++;
  5515. raw_spin_unlock_irqrestore(&ifh->lock, flags);
  5516. if (restart)
  5517. perf_event_stop(event, 1);
  5518. }
  5519. void perf_event_exec(void)
  5520. {
  5521. struct perf_event_context *ctx;
  5522. int ctxn;
  5523. rcu_read_lock();
  5524. for_each_task_context_nr(ctxn) {
  5525. ctx = current->perf_event_ctxp[ctxn];
  5526. if (!ctx)
  5527. continue;
  5528. perf_event_enable_on_exec(ctxn);
  5529. perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL,
  5530. true);
  5531. }
  5532. rcu_read_unlock();
  5533. }
  5534. struct remote_output {
  5535. struct ring_buffer *rb;
  5536. int err;
  5537. };
  5538. static void __perf_event_output_stop(struct perf_event *event, void *data)
  5539. {
  5540. struct perf_event *parent = event->parent;
  5541. struct remote_output *ro = data;
  5542. struct ring_buffer *rb = ro->rb;
  5543. struct stop_event_data sd = {
  5544. .event = event,
  5545. };
  5546. if (!has_aux(event))
  5547. return;
  5548. if (!parent)
  5549. parent = event;
  5550. /*
  5551. * In case of inheritance, it will be the parent that links to the
  5552. * ring-buffer, but it will be the child that's actually using it.
  5553. *
  5554. * We are using event::rb to determine if the event should be stopped,
  5555. * however this may race with ring_buffer_attach() (through set_output),
  5556. * which will make us skip the event that actually needs to be stopped.
  5557. * So ring_buffer_attach() has to stop an aux event before re-assigning
  5558. * its rb pointer.
  5559. */
  5560. if (rcu_dereference(parent->rb) == rb)
  5561. ro->err = __perf_event_stop(&sd);
  5562. }
  5563. static int __perf_pmu_output_stop(void *info)
  5564. {
  5565. struct perf_event *event = info;
  5566. struct pmu *pmu = event->pmu;
  5567. struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
  5568. struct remote_output ro = {
  5569. .rb = event->rb,
  5570. };
  5571. rcu_read_lock();
  5572. perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false);
  5573. if (cpuctx->task_ctx)
  5574. perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop,
  5575. &ro, false);
  5576. rcu_read_unlock();
  5577. return ro.err;
  5578. }
  5579. static void perf_pmu_output_stop(struct perf_event *event)
  5580. {
  5581. struct perf_event *iter;
  5582. int err, cpu;
  5583. restart:
  5584. rcu_read_lock();
  5585. list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) {
  5586. /*
  5587. * For per-CPU events, we need to make sure that neither they
  5588. * nor their children are running; for cpu==-1 events it's
  5589. * sufficient to stop the event itself if it's active, since
  5590. * it can't have children.
  5591. */
  5592. cpu = iter->cpu;
  5593. if (cpu == -1)
  5594. cpu = READ_ONCE(iter->oncpu);
  5595. if (cpu == -1)
  5596. continue;
  5597. err = cpu_function_call(cpu, __perf_pmu_output_stop, event);
  5598. if (err == -EAGAIN) {
  5599. rcu_read_unlock();
  5600. goto restart;
  5601. }
  5602. }
  5603. rcu_read_unlock();
  5604. }
  5605. /*
  5606. * task tracking -- fork/exit
  5607. *
  5608. * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
  5609. */
  5610. struct perf_task_event {
  5611. struct task_struct *task;
  5612. struct perf_event_context *task_ctx;
  5613. struct {
  5614. struct perf_event_header header;
  5615. u32 pid;
  5616. u32 ppid;
  5617. u32 tid;
  5618. u32 ptid;
  5619. u64 time;
  5620. } event_id;
  5621. };
  5622. static int perf_event_task_match(struct perf_event *event)
  5623. {
  5624. return event->attr.comm || event->attr.mmap ||
  5625. event->attr.mmap2 || event->attr.mmap_data ||
  5626. event->attr.task;
  5627. }
  5628. static void perf_event_task_output(struct perf_event *event,
  5629. void *data)
  5630. {
  5631. struct perf_task_event *task_event = data;
  5632. struct perf_output_handle handle;
  5633. struct perf_sample_data sample;
  5634. struct task_struct *task = task_event->task;
  5635. int ret, size = task_event->event_id.header.size;
  5636. if (!perf_event_task_match(event))
  5637. return;
  5638. perf_event_header__init_id(&task_event->event_id.header, &sample, event);
  5639. ret = perf_output_begin(&handle, event,
  5640. task_event->event_id.header.size);
  5641. if (ret)
  5642. goto out;
  5643. task_event->event_id.pid = perf_event_pid(event, task);
  5644. task_event->event_id.ppid = perf_event_pid(event, current);
  5645. task_event->event_id.tid = perf_event_tid(event, task);
  5646. task_event->event_id.ptid = perf_event_tid(event, current);
  5647. task_event->event_id.time = perf_event_clock(event);
  5648. perf_output_put(&handle, task_event->event_id);
  5649. perf_event__output_id_sample(event, &handle, &sample);
  5650. perf_output_end(&handle);
  5651. out:
  5652. task_event->event_id.header.size = size;
  5653. }
  5654. static void perf_event_task(struct task_struct *task,
  5655. struct perf_event_context *task_ctx,
  5656. int new)
  5657. {
  5658. struct perf_task_event task_event;
  5659. if (!atomic_read(&nr_comm_events) &&
  5660. !atomic_read(&nr_mmap_events) &&
  5661. !atomic_read(&nr_task_events))
  5662. return;
  5663. task_event = (struct perf_task_event){
  5664. .task = task,
  5665. .task_ctx = task_ctx,
  5666. .event_id = {
  5667. .header = {
  5668. .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
  5669. .misc = 0,
  5670. .size = sizeof(task_event.event_id),
  5671. },
  5672. /* .pid */
  5673. /* .ppid */
  5674. /* .tid */
  5675. /* .ptid */
  5676. /* .time */
  5677. },
  5678. };
  5679. perf_iterate_sb(perf_event_task_output,
  5680. &task_event,
  5681. task_ctx);
  5682. }
  5683. void perf_event_fork(struct task_struct *task)
  5684. {
  5685. perf_event_task(task, NULL, 1);
  5686. perf_event_namespaces(task);
  5687. }
  5688. /*
  5689. * comm tracking
  5690. */
  5691. struct perf_comm_event {
  5692. struct task_struct *task;
  5693. char *comm;
  5694. int comm_size;
  5695. struct {
  5696. struct perf_event_header header;
  5697. u32 pid;
  5698. u32 tid;
  5699. } event_id;
  5700. };
  5701. static int perf_event_comm_match(struct perf_event *event)
  5702. {
  5703. return event->attr.comm;
  5704. }
  5705. static void perf_event_comm_output(struct perf_event *event,
  5706. void *data)
  5707. {
  5708. struct perf_comm_event *comm_event = data;
  5709. struct perf_output_handle handle;
  5710. struct perf_sample_data sample;
  5711. int size = comm_event->event_id.header.size;
  5712. int ret;
  5713. if (!perf_event_comm_match(event))
  5714. return;
  5715. perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
  5716. ret = perf_output_begin(&handle, event,
  5717. comm_event->event_id.header.size);
  5718. if (ret)
  5719. goto out;
  5720. comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
  5721. comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
  5722. perf_output_put(&handle, comm_event->event_id);
  5723. __output_copy(&handle, comm_event->comm,
  5724. comm_event->comm_size);
  5725. perf_event__output_id_sample(event, &handle, &sample);
  5726. perf_output_end(&handle);
  5727. out:
  5728. comm_event->event_id.header.size = size;
  5729. }
  5730. static void perf_event_comm_event(struct perf_comm_event *comm_event)
  5731. {
  5732. char comm[TASK_COMM_LEN];
  5733. unsigned int size;
  5734. memset(comm, 0, sizeof(comm));
  5735. strlcpy(comm, comm_event->task->comm, sizeof(comm));
  5736. size = ALIGN(strlen(comm)+1, sizeof(u64));
  5737. comm_event->comm = comm;
  5738. comm_event->comm_size = size;
  5739. comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
  5740. perf_iterate_sb(perf_event_comm_output,
  5741. comm_event,
  5742. NULL);
  5743. }
  5744. void perf_event_comm(struct task_struct *task, bool exec)
  5745. {
  5746. struct perf_comm_event comm_event;
  5747. if (!atomic_read(&nr_comm_events))
  5748. return;
  5749. comm_event = (struct perf_comm_event){
  5750. .task = task,
  5751. /* .comm */
  5752. /* .comm_size */
  5753. .event_id = {
  5754. .header = {
  5755. .type = PERF_RECORD_COMM,
  5756. .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
  5757. /* .size */
  5758. },
  5759. /* .pid */
  5760. /* .tid */
  5761. },
  5762. };
  5763. perf_event_comm_event(&comm_event);
  5764. }
  5765. /*
  5766. * namespaces tracking
  5767. */
  5768. struct perf_namespaces_event {
  5769. struct task_struct *task;
  5770. struct {
  5771. struct perf_event_header header;
  5772. u32 pid;
  5773. u32 tid;
  5774. u64 nr_namespaces;
  5775. struct perf_ns_link_info link_info[NR_NAMESPACES];
  5776. } event_id;
  5777. };
  5778. static int perf_event_namespaces_match(struct perf_event *event)
  5779. {
  5780. return event->attr.namespaces;
  5781. }
  5782. static void perf_event_namespaces_output(struct perf_event *event,
  5783. void *data)
  5784. {
  5785. struct perf_namespaces_event *namespaces_event = data;
  5786. struct perf_output_handle handle;
  5787. struct perf_sample_data sample;
  5788. u16 header_size = namespaces_event->event_id.header.size;
  5789. int ret;
  5790. if (!perf_event_namespaces_match(event))
  5791. return;
  5792. perf_event_header__init_id(&namespaces_event->event_id.header,
  5793. &sample, event);
  5794. ret = perf_output_begin(&handle, event,
  5795. namespaces_event->event_id.header.size);
  5796. if (ret)
  5797. goto out;
  5798. namespaces_event->event_id.pid = perf_event_pid(event,
  5799. namespaces_event->task);
  5800. namespaces_event->event_id.tid = perf_event_tid(event,
  5801. namespaces_event->task);
  5802. perf_output_put(&handle, namespaces_event->event_id);
  5803. perf_event__output_id_sample(event, &handle, &sample);
  5804. perf_output_end(&handle);
  5805. out:
  5806. namespaces_event->event_id.header.size = header_size;
  5807. }
  5808. static void perf_fill_ns_link_info(struct perf_ns_link_info *ns_link_info,
  5809. struct task_struct *task,
  5810. const struct proc_ns_operations *ns_ops)
  5811. {
  5812. struct path ns_path;
  5813. struct inode *ns_inode;
  5814. void *error;
  5815. error = ns_get_path(&ns_path, task, ns_ops);
  5816. if (!error) {
  5817. ns_inode = ns_path.dentry->d_inode;
  5818. ns_link_info->dev = new_encode_dev(ns_inode->i_sb->s_dev);
  5819. ns_link_info->ino = ns_inode->i_ino;
  5820. path_put(&ns_path);
  5821. }
  5822. }
  5823. void perf_event_namespaces(struct task_struct *task)
  5824. {
  5825. struct perf_namespaces_event namespaces_event;
  5826. struct perf_ns_link_info *ns_link_info;
  5827. if (!atomic_read(&nr_namespaces_events))
  5828. return;
  5829. namespaces_event = (struct perf_namespaces_event){
  5830. .task = task,
  5831. .event_id = {
  5832. .header = {
  5833. .type = PERF_RECORD_NAMESPACES,
  5834. .misc = 0,
  5835. .size = sizeof(namespaces_event.event_id),
  5836. },
  5837. /* .pid */
  5838. /* .tid */
  5839. .nr_namespaces = NR_NAMESPACES,
  5840. /* .link_info[NR_NAMESPACES] */
  5841. },
  5842. };
  5843. ns_link_info = namespaces_event.event_id.link_info;
  5844. perf_fill_ns_link_info(&ns_link_info[MNT_NS_INDEX],
  5845. task, &mntns_operations);
  5846. #ifdef CONFIG_USER_NS
  5847. perf_fill_ns_link_info(&ns_link_info[USER_NS_INDEX],
  5848. task, &userns_operations);
  5849. #endif
  5850. #ifdef CONFIG_NET_NS
  5851. perf_fill_ns_link_info(&ns_link_info[NET_NS_INDEX],
  5852. task, &netns_operations);
  5853. #endif
  5854. #ifdef CONFIG_UTS_NS
  5855. perf_fill_ns_link_info(&ns_link_info[UTS_NS_INDEX],
  5856. task, &utsns_operations);
  5857. #endif
  5858. #ifdef CONFIG_IPC_NS
  5859. perf_fill_ns_link_info(&ns_link_info[IPC_NS_INDEX],
  5860. task, &ipcns_operations);
  5861. #endif
  5862. #ifdef CONFIG_PID_NS
  5863. perf_fill_ns_link_info(&ns_link_info[PID_NS_INDEX],
  5864. task, &pidns_operations);
  5865. #endif
  5866. #ifdef CONFIG_CGROUPS
  5867. perf_fill_ns_link_info(&ns_link_info[CGROUP_NS_INDEX],
  5868. task, &cgroupns_operations);
  5869. #endif
  5870. perf_iterate_sb(perf_event_namespaces_output,
  5871. &namespaces_event,
  5872. NULL);
  5873. }
  5874. /*
  5875. * mmap tracking
  5876. */
  5877. struct perf_mmap_event {
  5878. struct vm_area_struct *vma;
  5879. const char *file_name;
  5880. int file_size;
  5881. int maj, min;
  5882. u64 ino;
  5883. u64 ino_generation;
  5884. u32 prot, flags;
  5885. struct {
  5886. struct perf_event_header header;
  5887. u32 pid;
  5888. u32 tid;
  5889. u64 start;
  5890. u64 len;
  5891. u64 pgoff;
  5892. } event_id;
  5893. };
  5894. static int perf_event_mmap_match(struct perf_event *event,
  5895. void *data)
  5896. {
  5897. struct perf_mmap_event *mmap_event = data;
  5898. struct vm_area_struct *vma = mmap_event->vma;
  5899. int executable = vma->vm_flags & VM_EXEC;
  5900. return (!executable && event->attr.mmap_data) ||
  5901. (executable && (event->attr.mmap || event->attr.mmap2));
  5902. }
  5903. static void perf_event_mmap_output(struct perf_event *event,
  5904. void *data)
  5905. {
  5906. struct perf_mmap_event *mmap_event = data;
  5907. struct perf_output_handle handle;
  5908. struct perf_sample_data sample;
  5909. int size = mmap_event->event_id.header.size;
  5910. int ret;
  5911. if (!perf_event_mmap_match(event, data))
  5912. return;
  5913. if (event->attr.mmap2) {
  5914. mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
  5915. mmap_event->event_id.header.size += sizeof(mmap_event->maj);
  5916. mmap_event->event_id.header.size += sizeof(mmap_event->min);
  5917. mmap_event->event_id.header.size += sizeof(mmap_event->ino);
  5918. mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
  5919. mmap_event->event_id.header.size += sizeof(mmap_event->prot);
  5920. mmap_event->event_id.header.size += sizeof(mmap_event->flags);
  5921. }
  5922. perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
  5923. ret = perf_output_begin(&handle, event,
  5924. mmap_event->event_id.header.size);
  5925. if (ret)
  5926. goto out;
  5927. mmap_event->event_id.pid = perf_event_pid(event, current);
  5928. mmap_event->event_id.tid = perf_event_tid(event, current);
  5929. perf_output_put(&handle, mmap_event->event_id);
  5930. if (event->attr.mmap2) {
  5931. perf_output_put(&handle, mmap_event->maj);
  5932. perf_output_put(&handle, mmap_event->min);
  5933. perf_output_put(&handle, mmap_event->ino);
  5934. perf_output_put(&handle, mmap_event->ino_generation);
  5935. perf_output_put(&handle, mmap_event->prot);
  5936. perf_output_put(&handle, mmap_event->flags);
  5937. }
  5938. __output_copy(&handle, mmap_event->file_name,
  5939. mmap_event->file_size);
  5940. perf_event__output_id_sample(event, &handle, &sample);
  5941. perf_output_end(&handle);
  5942. out:
  5943. mmap_event->event_id.header.size = size;
  5944. }
  5945. static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
  5946. {
  5947. struct vm_area_struct *vma = mmap_event->vma;
  5948. struct file *file = vma->vm_file;
  5949. int maj = 0, min = 0;
  5950. u64 ino = 0, gen = 0;
  5951. u32 prot = 0, flags = 0;
  5952. unsigned int size;
  5953. char tmp[16];
  5954. char *buf = NULL;
  5955. char *name;
  5956. if (vma->vm_flags & VM_READ)
  5957. prot |= PROT_READ;
  5958. if (vma->vm_flags & VM_WRITE)
  5959. prot |= PROT_WRITE;
  5960. if (vma->vm_flags & VM_EXEC)
  5961. prot |= PROT_EXEC;
  5962. if (vma->vm_flags & VM_MAYSHARE)
  5963. flags = MAP_SHARED;
  5964. else
  5965. flags = MAP_PRIVATE;
  5966. if (vma->vm_flags & VM_DENYWRITE)
  5967. flags |= MAP_DENYWRITE;
  5968. if (vma->vm_flags & VM_MAYEXEC)
  5969. flags |= MAP_EXECUTABLE;
  5970. if (vma->vm_flags & VM_LOCKED)
  5971. flags |= MAP_LOCKED;
  5972. if (vma->vm_flags & VM_HUGETLB)
  5973. flags |= MAP_HUGETLB;
  5974. if (file) {
  5975. struct inode *inode;
  5976. dev_t dev;
  5977. buf = kmalloc(PATH_MAX, GFP_KERNEL);
  5978. if (!buf) {
  5979. name = "//enomem";
  5980. goto cpy_name;
  5981. }
  5982. /*
  5983. * d_path() works from the end of the rb backwards, so we
  5984. * need to add enough zero bytes after the string to handle
  5985. * the 64bit alignment we do later.
  5986. */
  5987. name = file_path(file, buf, PATH_MAX - sizeof(u64));
  5988. if (IS_ERR(name)) {
  5989. name = "//toolong";
  5990. goto cpy_name;
  5991. }
  5992. inode = file_inode(vma->vm_file);
  5993. dev = inode->i_sb->s_dev;
  5994. ino = inode->i_ino;
  5995. gen = inode->i_generation;
  5996. maj = MAJOR(dev);
  5997. min = MINOR(dev);
  5998. goto got_name;
  5999. } else {
  6000. if (vma->vm_ops && vma->vm_ops->name) {
  6001. name = (char *) vma->vm_ops->name(vma);
  6002. if (name)
  6003. goto cpy_name;
  6004. }
  6005. name = (char *)arch_vma_name(vma);
  6006. if (name)
  6007. goto cpy_name;
  6008. if (vma->vm_start <= vma->vm_mm->start_brk &&
  6009. vma->vm_end >= vma->vm_mm->brk) {
  6010. name = "[heap]";
  6011. goto cpy_name;
  6012. }
  6013. if (vma->vm_start <= vma->vm_mm->start_stack &&
  6014. vma->vm_end >= vma->vm_mm->start_stack) {
  6015. name = "[stack]";
  6016. goto cpy_name;
  6017. }
  6018. name = "//anon";
  6019. goto cpy_name;
  6020. }
  6021. cpy_name:
  6022. strlcpy(tmp, name, sizeof(tmp));
  6023. name = tmp;
  6024. got_name:
  6025. /*
  6026. * Since our buffer works in 8 byte units we need to align our string
  6027. * size to a multiple of 8. However, we must guarantee the tail end is
  6028. * zero'd out to avoid leaking random bits to userspace.
  6029. */
  6030. size = strlen(name)+1;
  6031. while (!IS_ALIGNED(size, sizeof(u64)))
  6032. name[size++] = '\0';
  6033. mmap_event->file_name = name;
  6034. mmap_event->file_size = size;
  6035. mmap_event->maj = maj;
  6036. mmap_event->min = min;
  6037. mmap_event->ino = ino;
  6038. mmap_event->ino_generation = gen;
  6039. mmap_event->prot = prot;
  6040. mmap_event->flags = flags;
  6041. if (!(vma->vm_flags & VM_EXEC))
  6042. mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
  6043. mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
  6044. perf_iterate_sb(perf_event_mmap_output,
  6045. mmap_event,
  6046. NULL);
  6047. kfree(buf);
  6048. }
  6049. /*
  6050. * Check whether inode and address range match filter criteria.
  6051. */
  6052. static bool perf_addr_filter_match(struct perf_addr_filter *filter,
  6053. struct file *file, unsigned long offset,
  6054. unsigned long size)
  6055. {
  6056. /* d_inode(NULL) won't be equal to any mapped user-space file */
  6057. if (!filter->path.dentry)
  6058. return false;
  6059. if (d_inode(filter->path.dentry) != file_inode(file))
  6060. return false;
  6061. if (filter->offset > offset + size)
  6062. return false;
  6063. if (filter->offset + filter->size < offset)
  6064. return false;
  6065. return true;
  6066. }
  6067. static void __perf_addr_filters_adjust(struct perf_event *event, void *data)
  6068. {
  6069. struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
  6070. struct vm_area_struct *vma = data;
  6071. unsigned long off = vma->vm_pgoff << PAGE_SHIFT, flags;
  6072. struct file *file = vma->vm_file;
  6073. struct perf_addr_filter *filter;
  6074. unsigned int restart = 0, count = 0;
  6075. if (!has_addr_filter(event))
  6076. return;
  6077. if (!file)
  6078. return;
  6079. raw_spin_lock_irqsave(&ifh->lock, flags);
  6080. list_for_each_entry(filter, &ifh->list, entry) {
  6081. if (perf_addr_filter_match(filter, file, off,
  6082. vma->vm_end - vma->vm_start)) {
  6083. event->addr_filters_offs[count] = vma->vm_start;
  6084. restart++;
  6085. }
  6086. count++;
  6087. }
  6088. if (restart)
  6089. event->addr_filters_gen++;
  6090. raw_spin_unlock_irqrestore(&ifh->lock, flags);
  6091. if (restart)
  6092. perf_event_stop(event, 1);
  6093. }
  6094. /*
  6095. * Adjust all task's events' filters to the new vma
  6096. */
  6097. static void perf_addr_filters_adjust(struct vm_area_struct *vma)
  6098. {
  6099. struct perf_event_context *ctx;
  6100. int ctxn;
  6101. /*
  6102. * Data tracing isn't supported yet and as such there is no need
  6103. * to keep track of anything that isn't related to executable code:
  6104. */
  6105. if (!(vma->vm_flags & VM_EXEC))
  6106. return;
  6107. rcu_read_lock();
  6108. for_each_task_context_nr(ctxn) {
  6109. ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
  6110. if (!ctx)
  6111. continue;
  6112. perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true);
  6113. }
  6114. rcu_read_unlock();
  6115. }
  6116. void perf_event_mmap(struct vm_area_struct *vma)
  6117. {
  6118. struct perf_mmap_event mmap_event;
  6119. if (!atomic_read(&nr_mmap_events))
  6120. return;
  6121. mmap_event = (struct perf_mmap_event){
  6122. .vma = vma,
  6123. /* .file_name */
  6124. /* .file_size */
  6125. .event_id = {
  6126. .header = {
  6127. .type = PERF_RECORD_MMAP,
  6128. .misc = PERF_RECORD_MISC_USER,
  6129. /* .size */
  6130. },
  6131. /* .pid */
  6132. /* .tid */
  6133. .start = vma->vm_start,
  6134. .len = vma->vm_end - vma->vm_start,
  6135. .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
  6136. },
  6137. /* .maj (attr_mmap2 only) */
  6138. /* .min (attr_mmap2 only) */
  6139. /* .ino (attr_mmap2 only) */
  6140. /* .ino_generation (attr_mmap2 only) */
  6141. /* .prot (attr_mmap2 only) */
  6142. /* .flags (attr_mmap2 only) */
  6143. };
  6144. perf_addr_filters_adjust(vma);
  6145. perf_event_mmap_event(&mmap_event);
  6146. }
  6147. void perf_event_aux_event(struct perf_event *event, unsigned long head,
  6148. unsigned long size, u64 flags)
  6149. {
  6150. struct perf_output_handle handle;
  6151. struct perf_sample_data sample;
  6152. struct perf_aux_event {
  6153. struct perf_event_header header;
  6154. u64 offset;
  6155. u64 size;
  6156. u64 flags;
  6157. } rec = {
  6158. .header = {
  6159. .type = PERF_RECORD_AUX,
  6160. .misc = 0,
  6161. .size = sizeof(rec),
  6162. },
  6163. .offset = head,
  6164. .size = size,
  6165. .flags = flags,
  6166. };
  6167. int ret;
  6168. perf_event_header__init_id(&rec.header, &sample, event);
  6169. ret = perf_output_begin(&handle, event, rec.header.size);
  6170. if (ret)
  6171. return;
  6172. perf_output_put(&handle, rec);
  6173. perf_event__output_id_sample(event, &handle, &sample);
  6174. perf_output_end(&handle);
  6175. }
  6176. /*
  6177. * Lost/dropped samples logging
  6178. */
  6179. void perf_log_lost_samples(struct perf_event *event, u64 lost)
  6180. {
  6181. struct perf_output_handle handle;
  6182. struct perf_sample_data sample;
  6183. int ret;
  6184. struct {
  6185. struct perf_event_header header;
  6186. u64 lost;
  6187. } lost_samples_event = {
  6188. .header = {
  6189. .type = PERF_RECORD_LOST_SAMPLES,
  6190. .misc = 0,
  6191. .size = sizeof(lost_samples_event),
  6192. },
  6193. .lost = lost,
  6194. };
  6195. perf_event_header__init_id(&lost_samples_event.header, &sample, event);
  6196. ret = perf_output_begin(&handle, event,
  6197. lost_samples_event.header.size);
  6198. if (ret)
  6199. return;
  6200. perf_output_put(&handle, lost_samples_event);
  6201. perf_event__output_id_sample(event, &handle, &sample);
  6202. perf_output_end(&handle);
  6203. }
  6204. /*
  6205. * context_switch tracking
  6206. */
  6207. struct perf_switch_event {
  6208. struct task_struct *task;
  6209. struct task_struct *next_prev;
  6210. struct {
  6211. struct perf_event_header header;
  6212. u32 next_prev_pid;
  6213. u32 next_prev_tid;
  6214. } event_id;
  6215. };
  6216. static int perf_event_switch_match(struct perf_event *event)
  6217. {
  6218. return event->attr.context_switch;
  6219. }
  6220. static void perf_event_switch_output(struct perf_event *event, void *data)
  6221. {
  6222. struct perf_switch_event *se = data;
  6223. struct perf_output_handle handle;
  6224. struct perf_sample_data sample;
  6225. int ret;
  6226. if (!perf_event_switch_match(event))
  6227. return;
  6228. /* Only CPU-wide events are allowed to see next/prev pid/tid */
  6229. if (event->ctx->task) {
  6230. se->event_id.header.type = PERF_RECORD_SWITCH;
  6231. se->event_id.header.size = sizeof(se->event_id.header);
  6232. } else {
  6233. se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
  6234. se->event_id.header.size = sizeof(se->event_id);
  6235. se->event_id.next_prev_pid =
  6236. perf_event_pid(event, se->next_prev);
  6237. se->event_id.next_prev_tid =
  6238. perf_event_tid(event, se->next_prev);
  6239. }
  6240. perf_event_header__init_id(&se->event_id.header, &sample, event);
  6241. ret = perf_output_begin(&handle, event, se->event_id.header.size);
  6242. if (ret)
  6243. return;
  6244. if (event->ctx->task)
  6245. perf_output_put(&handle, se->event_id.header);
  6246. else
  6247. perf_output_put(&handle, se->event_id);
  6248. perf_event__output_id_sample(event, &handle, &sample);
  6249. perf_output_end(&handle);
  6250. }
  6251. static void perf_event_switch(struct task_struct *task,
  6252. struct task_struct *next_prev, bool sched_in)
  6253. {
  6254. struct perf_switch_event switch_event;
  6255. /* N.B. caller checks nr_switch_events != 0 */
  6256. switch_event = (struct perf_switch_event){
  6257. .task = task,
  6258. .next_prev = next_prev,
  6259. .event_id = {
  6260. .header = {
  6261. /* .type */
  6262. .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
  6263. /* .size */
  6264. },
  6265. /* .next_prev_pid */
  6266. /* .next_prev_tid */
  6267. },
  6268. };
  6269. if (!sched_in && task->state == TASK_RUNNING)
  6270. switch_event.event_id.header.misc |=
  6271. PERF_RECORD_MISC_SWITCH_OUT_PREEMPT;
  6272. perf_iterate_sb(perf_event_switch_output,
  6273. &switch_event,
  6274. NULL);
  6275. }
  6276. /*
  6277. * IRQ throttle logging
  6278. */
  6279. static void perf_log_throttle(struct perf_event *event, int enable)
  6280. {
  6281. struct perf_output_handle handle;
  6282. struct perf_sample_data sample;
  6283. int ret;
  6284. struct {
  6285. struct perf_event_header header;
  6286. u64 time;
  6287. u64 id;
  6288. u64 stream_id;
  6289. } throttle_event = {
  6290. .header = {
  6291. .type = PERF_RECORD_THROTTLE,
  6292. .misc = 0,
  6293. .size = sizeof(throttle_event),
  6294. },
  6295. .time = perf_event_clock(event),
  6296. .id = primary_event_id(event),
  6297. .stream_id = event->id,
  6298. };
  6299. if (enable)
  6300. throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
  6301. perf_event_header__init_id(&throttle_event.header, &sample, event);
  6302. ret = perf_output_begin(&handle, event,
  6303. throttle_event.header.size);
  6304. if (ret)
  6305. return;
  6306. perf_output_put(&handle, throttle_event);
  6307. perf_event__output_id_sample(event, &handle, &sample);
  6308. perf_output_end(&handle);
  6309. }
  6310. void perf_event_itrace_started(struct perf_event *event)
  6311. {
  6312. event->attach_state |= PERF_ATTACH_ITRACE;
  6313. }
  6314. static void perf_log_itrace_start(struct perf_event *event)
  6315. {
  6316. struct perf_output_handle handle;
  6317. struct perf_sample_data sample;
  6318. struct perf_aux_event {
  6319. struct perf_event_header header;
  6320. u32 pid;
  6321. u32 tid;
  6322. } rec;
  6323. int ret;
  6324. if (event->parent)
  6325. event = event->parent;
  6326. if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
  6327. event->attach_state & PERF_ATTACH_ITRACE)
  6328. return;
  6329. rec.header.type = PERF_RECORD_ITRACE_START;
  6330. rec.header.misc = 0;
  6331. rec.header.size = sizeof(rec);
  6332. rec.pid = perf_event_pid(event, current);
  6333. rec.tid = perf_event_tid(event, current);
  6334. perf_event_header__init_id(&rec.header, &sample, event);
  6335. ret = perf_output_begin(&handle, event, rec.header.size);
  6336. if (ret)
  6337. return;
  6338. perf_output_put(&handle, rec);
  6339. perf_event__output_id_sample(event, &handle, &sample);
  6340. perf_output_end(&handle);
  6341. }
  6342. static int
  6343. __perf_event_account_interrupt(struct perf_event *event, int throttle)
  6344. {
  6345. struct hw_perf_event *hwc = &event->hw;
  6346. int ret = 0;
  6347. u64 seq;
  6348. seq = __this_cpu_read(perf_throttled_seq);
  6349. if (seq != hwc->interrupts_seq) {
  6350. hwc->interrupts_seq = seq;
  6351. hwc->interrupts = 1;
  6352. } else {
  6353. hwc->interrupts++;
  6354. if (unlikely(throttle
  6355. && hwc->interrupts >= max_samples_per_tick)) {
  6356. __this_cpu_inc(perf_throttled_count);
  6357. tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
  6358. hwc->interrupts = MAX_INTERRUPTS;
  6359. perf_log_throttle(event, 0);
  6360. ret = 1;
  6361. }
  6362. }
  6363. if (event->attr.freq) {
  6364. u64 now = perf_clock();
  6365. s64 delta = now - hwc->freq_time_stamp;
  6366. hwc->freq_time_stamp = now;
  6367. if (delta > 0 && delta < 2*TICK_NSEC)
  6368. perf_adjust_period(event, delta, hwc->last_period, true);
  6369. }
  6370. return ret;
  6371. }
  6372. int perf_event_account_interrupt(struct perf_event *event)
  6373. {
  6374. return __perf_event_account_interrupt(event, 1);
  6375. }
  6376. /*
  6377. * Generic event overflow handling, sampling.
  6378. */
  6379. static int __perf_event_overflow(struct perf_event *event,
  6380. int throttle, struct perf_sample_data *data,
  6381. struct pt_regs *regs)
  6382. {
  6383. int events = atomic_read(&event->event_limit);
  6384. int ret = 0;
  6385. /*
  6386. * Non-sampling counters might still use the PMI to fold short
  6387. * hardware counters, ignore those.
  6388. */
  6389. if (unlikely(!is_sampling_event(event)))
  6390. return 0;
  6391. ret = __perf_event_account_interrupt(event, throttle);
  6392. /*
  6393. * XXX event_limit might not quite work as expected on inherited
  6394. * events
  6395. */
  6396. event->pending_kill = POLL_IN;
  6397. if (events && atomic_dec_and_test(&event->event_limit)) {
  6398. ret = 1;
  6399. event->pending_kill = POLL_HUP;
  6400. perf_event_disable_inatomic(event);
  6401. }
  6402. READ_ONCE(event->overflow_handler)(event, data, regs);
  6403. if (*perf_event_fasync(event) && event->pending_kill) {
  6404. event->pending_wakeup = 1;
  6405. irq_work_queue(&event->pending);
  6406. }
  6407. return ret;
  6408. }
  6409. int perf_event_overflow(struct perf_event *event,
  6410. struct perf_sample_data *data,
  6411. struct pt_regs *regs)
  6412. {
  6413. return __perf_event_overflow(event, 1, data, regs);
  6414. }
  6415. /*
  6416. * Generic software event infrastructure
  6417. */
  6418. struct swevent_htable {
  6419. struct swevent_hlist *swevent_hlist;
  6420. struct mutex hlist_mutex;
  6421. int hlist_refcount;
  6422. /* Recursion avoidance in each contexts */
  6423. int recursion[PERF_NR_CONTEXTS];
  6424. };
  6425. static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
  6426. /*
  6427. * We directly increment event->count and keep a second value in
  6428. * event->hw.period_left to count intervals. This period event
  6429. * is kept in the range [-sample_period, 0] so that we can use the
  6430. * sign as trigger.
  6431. */
  6432. u64 perf_swevent_set_period(struct perf_event *event)
  6433. {
  6434. struct hw_perf_event *hwc = &event->hw;
  6435. u64 period = hwc->last_period;
  6436. u64 nr, offset;
  6437. s64 old, val;
  6438. hwc->last_period = hwc->sample_period;
  6439. again:
  6440. old = val = local64_read(&hwc->period_left);
  6441. if (val < 0)
  6442. return 0;
  6443. nr = div64_u64(period + val, period);
  6444. offset = nr * period;
  6445. val -= offset;
  6446. if (local64_cmpxchg(&hwc->period_left, old, val) != old)
  6447. goto again;
  6448. return nr;
  6449. }
  6450. static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
  6451. struct perf_sample_data *data,
  6452. struct pt_regs *regs)
  6453. {
  6454. struct hw_perf_event *hwc = &event->hw;
  6455. int throttle = 0;
  6456. if (!overflow)
  6457. overflow = perf_swevent_set_period(event);
  6458. if (hwc->interrupts == MAX_INTERRUPTS)
  6459. return;
  6460. for (; overflow; overflow--) {
  6461. if (__perf_event_overflow(event, throttle,
  6462. data, regs)) {
  6463. /*
  6464. * We inhibit the overflow from happening when
  6465. * hwc->interrupts == MAX_INTERRUPTS.
  6466. */
  6467. break;
  6468. }
  6469. throttle = 1;
  6470. }
  6471. }
  6472. static void perf_swevent_event(struct perf_event *event, u64 nr,
  6473. struct perf_sample_data *data,
  6474. struct pt_regs *regs)
  6475. {
  6476. struct hw_perf_event *hwc = &event->hw;
  6477. local64_add(nr, &event->count);
  6478. if (!regs)
  6479. return;
  6480. if (!is_sampling_event(event))
  6481. return;
  6482. if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
  6483. data->period = nr;
  6484. return perf_swevent_overflow(event, 1, data, regs);
  6485. } else
  6486. data->period = event->hw.last_period;
  6487. if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
  6488. return perf_swevent_overflow(event, 1, data, regs);
  6489. if (local64_add_negative(nr, &hwc->period_left))
  6490. return;
  6491. perf_swevent_overflow(event, 0, data, regs);
  6492. }
  6493. static int perf_exclude_event(struct perf_event *event,
  6494. struct pt_regs *regs)
  6495. {
  6496. if (event->hw.state & PERF_HES_STOPPED)
  6497. return 1;
  6498. if (regs) {
  6499. if (event->attr.exclude_user && user_mode(regs))
  6500. return 1;
  6501. if (event->attr.exclude_kernel && !user_mode(regs))
  6502. return 1;
  6503. }
  6504. return 0;
  6505. }
  6506. static int perf_swevent_match(struct perf_event *event,
  6507. enum perf_type_id type,
  6508. u32 event_id,
  6509. struct perf_sample_data *data,
  6510. struct pt_regs *regs)
  6511. {
  6512. if (event->attr.type != type)
  6513. return 0;
  6514. if (event->attr.config != event_id)
  6515. return 0;
  6516. if (perf_exclude_event(event, regs))
  6517. return 0;
  6518. return 1;
  6519. }
  6520. static inline u64 swevent_hash(u64 type, u32 event_id)
  6521. {
  6522. u64 val = event_id | (type << 32);
  6523. return hash_64(val, SWEVENT_HLIST_BITS);
  6524. }
  6525. static inline struct hlist_head *
  6526. __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
  6527. {
  6528. u64 hash = swevent_hash(type, event_id);
  6529. return &hlist->heads[hash];
  6530. }
  6531. /* For the read side: events when they trigger */
  6532. static inline struct hlist_head *
  6533. find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
  6534. {
  6535. struct swevent_hlist *hlist;
  6536. hlist = rcu_dereference(swhash->swevent_hlist);
  6537. if (!hlist)
  6538. return NULL;
  6539. return __find_swevent_head(hlist, type, event_id);
  6540. }
  6541. /* For the event head insertion and removal in the hlist */
  6542. static inline struct hlist_head *
  6543. find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
  6544. {
  6545. struct swevent_hlist *hlist;
  6546. u32 event_id = event->attr.config;
  6547. u64 type = event->attr.type;
  6548. /*
  6549. * Event scheduling is always serialized against hlist allocation
  6550. * and release. Which makes the protected version suitable here.
  6551. * The context lock guarantees that.
  6552. */
  6553. hlist = rcu_dereference_protected(swhash->swevent_hlist,
  6554. lockdep_is_held(&event->ctx->lock));
  6555. if (!hlist)
  6556. return NULL;
  6557. return __find_swevent_head(hlist, type, event_id);
  6558. }
  6559. static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
  6560. u64 nr,
  6561. struct perf_sample_data *data,
  6562. struct pt_regs *regs)
  6563. {
  6564. struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
  6565. struct perf_event *event;
  6566. struct hlist_head *head;
  6567. rcu_read_lock();
  6568. head = find_swevent_head_rcu(swhash, type, event_id);
  6569. if (!head)
  6570. goto end;
  6571. hlist_for_each_entry_rcu(event, head, hlist_entry) {
  6572. if (perf_swevent_match(event, type, event_id, data, regs))
  6573. perf_swevent_event(event, nr, data, regs);
  6574. }
  6575. end:
  6576. rcu_read_unlock();
  6577. }
  6578. DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
  6579. int perf_swevent_get_recursion_context(void)
  6580. {
  6581. struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
  6582. return get_recursion_context(swhash->recursion);
  6583. }
  6584. EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
  6585. void perf_swevent_put_recursion_context(int rctx)
  6586. {
  6587. struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
  6588. put_recursion_context(swhash->recursion, rctx);
  6589. }
  6590. void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
  6591. {
  6592. struct perf_sample_data data;
  6593. if (WARN_ON_ONCE(!regs))
  6594. return;
  6595. perf_sample_data_init(&data, addr, 0);
  6596. do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
  6597. }
  6598. void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
  6599. {
  6600. int rctx;
  6601. preempt_disable_notrace();
  6602. rctx = perf_swevent_get_recursion_context();
  6603. if (unlikely(rctx < 0))
  6604. goto fail;
  6605. ___perf_sw_event(event_id, nr, regs, addr);
  6606. perf_swevent_put_recursion_context(rctx);
  6607. fail:
  6608. preempt_enable_notrace();
  6609. }
  6610. static void perf_swevent_read(struct perf_event *event)
  6611. {
  6612. }
  6613. static int perf_swevent_add(struct perf_event *event, int flags)
  6614. {
  6615. struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
  6616. struct hw_perf_event *hwc = &event->hw;
  6617. struct hlist_head *head;
  6618. if (is_sampling_event(event)) {
  6619. hwc->last_period = hwc->sample_period;
  6620. perf_swevent_set_period(event);
  6621. }
  6622. hwc->state = !(flags & PERF_EF_START);
  6623. head = find_swevent_head(swhash, event);
  6624. if (WARN_ON_ONCE(!head))
  6625. return -EINVAL;
  6626. hlist_add_head_rcu(&event->hlist_entry, head);
  6627. perf_event_update_userpage(event);
  6628. return 0;
  6629. }
  6630. static void perf_swevent_del(struct perf_event *event, int flags)
  6631. {
  6632. hlist_del_rcu(&event->hlist_entry);
  6633. }
  6634. static void perf_swevent_start(struct perf_event *event, int flags)
  6635. {
  6636. event->hw.state = 0;
  6637. }
  6638. static void perf_swevent_stop(struct perf_event *event, int flags)
  6639. {
  6640. event->hw.state = PERF_HES_STOPPED;
  6641. }
  6642. /* Deref the hlist from the update side */
  6643. static inline struct swevent_hlist *
  6644. swevent_hlist_deref(struct swevent_htable *swhash)
  6645. {
  6646. return rcu_dereference_protected(swhash->swevent_hlist,
  6647. lockdep_is_held(&swhash->hlist_mutex));
  6648. }
  6649. static void swevent_hlist_release(struct swevent_htable *swhash)
  6650. {
  6651. struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
  6652. if (!hlist)
  6653. return;
  6654. RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
  6655. kfree_rcu(hlist, rcu_head);
  6656. }
  6657. static void swevent_hlist_put_cpu(int cpu)
  6658. {
  6659. struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
  6660. mutex_lock(&swhash->hlist_mutex);
  6661. if (!--swhash->hlist_refcount)
  6662. swevent_hlist_release(swhash);
  6663. mutex_unlock(&swhash->hlist_mutex);
  6664. }
  6665. static void swevent_hlist_put(void)
  6666. {
  6667. int cpu;
  6668. for_each_possible_cpu(cpu)
  6669. swevent_hlist_put_cpu(cpu);
  6670. }
  6671. static int swevent_hlist_get_cpu(int cpu)
  6672. {
  6673. struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
  6674. int err = 0;
  6675. mutex_lock(&swhash->hlist_mutex);
  6676. if (!swevent_hlist_deref(swhash) &&
  6677. cpumask_test_cpu(cpu, perf_online_mask)) {
  6678. struct swevent_hlist *hlist;
  6679. hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
  6680. if (!hlist) {
  6681. err = -ENOMEM;
  6682. goto exit;
  6683. }
  6684. rcu_assign_pointer(swhash->swevent_hlist, hlist);
  6685. }
  6686. swhash->hlist_refcount++;
  6687. exit:
  6688. mutex_unlock(&swhash->hlist_mutex);
  6689. return err;
  6690. }
  6691. static int swevent_hlist_get(void)
  6692. {
  6693. int err, cpu, failed_cpu;
  6694. mutex_lock(&pmus_lock);
  6695. for_each_possible_cpu(cpu) {
  6696. err = swevent_hlist_get_cpu(cpu);
  6697. if (err) {
  6698. failed_cpu = cpu;
  6699. goto fail;
  6700. }
  6701. }
  6702. mutex_unlock(&pmus_lock);
  6703. return 0;
  6704. fail:
  6705. for_each_possible_cpu(cpu) {
  6706. if (cpu == failed_cpu)
  6707. break;
  6708. swevent_hlist_put_cpu(cpu);
  6709. }
  6710. mutex_unlock(&pmus_lock);
  6711. return err;
  6712. }
  6713. struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
  6714. static void sw_perf_event_destroy(struct perf_event *event)
  6715. {
  6716. u64 event_id = event->attr.config;
  6717. WARN_ON(event->parent);
  6718. static_key_slow_dec(&perf_swevent_enabled[event_id]);
  6719. swevent_hlist_put();
  6720. }
  6721. static int perf_swevent_init(struct perf_event *event)
  6722. {
  6723. u64 event_id = event->attr.config;
  6724. if (event->attr.type != PERF_TYPE_SOFTWARE)
  6725. return -ENOENT;
  6726. /*
  6727. * no branch sampling for software events
  6728. */
  6729. if (has_branch_stack(event))
  6730. return -EOPNOTSUPP;
  6731. switch (event_id) {
  6732. case PERF_COUNT_SW_CPU_CLOCK:
  6733. case PERF_COUNT_SW_TASK_CLOCK:
  6734. return -ENOENT;
  6735. default:
  6736. break;
  6737. }
  6738. if (event_id >= PERF_COUNT_SW_MAX)
  6739. return -ENOENT;
  6740. if (!event->parent) {
  6741. int err;
  6742. err = swevent_hlist_get();
  6743. if (err)
  6744. return err;
  6745. static_key_slow_inc(&perf_swevent_enabled[event_id]);
  6746. event->destroy = sw_perf_event_destroy;
  6747. }
  6748. return 0;
  6749. }
  6750. static struct pmu perf_swevent = {
  6751. .task_ctx_nr = perf_sw_context,
  6752. .capabilities = PERF_PMU_CAP_NO_NMI,
  6753. .event_init = perf_swevent_init,
  6754. .add = perf_swevent_add,
  6755. .del = perf_swevent_del,
  6756. .start = perf_swevent_start,
  6757. .stop = perf_swevent_stop,
  6758. .read = perf_swevent_read,
  6759. };
  6760. #ifdef CONFIG_EVENT_TRACING
  6761. static int perf_tp_filter_match(struct perf_event *event,
  6762. struct perf_sample_data *data)
  6763. {
  6764. void *record = data->raw->frag.data;
  6765. /* only top level events have filters set */
  6766. if (event->parent)
  6767. event = event->parent;
  6768. if (likely(!event->filter) || filter_match_preds(event->filter, record))
  6769. return 1;
  6770. return 0;
  6771. }
  6772. static int perf_tp_event_match(struct perf_event *event,
  6773. struct perf_sample_data *data,
  6774. struct pt_regs *regs)
  6775. {
  6776. if (event->hw.state & PERF_HES_STOPPED)
  6777. return 0;
  6778. /*
  6779. * All tracepoints are from kernel-space.
  6780. */
  6781. if (event->attr.exclude_kernel)
  6782. return 0;
  6783. if (!perf_tp_filter_match(event, data))
  6784. return 0;
  6785. return 1;
  6786. }
  6787. void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx,
  6788. struct trace_event_call *call, u64 count,
  6789. struct pt_regs *regs, struct hlist_head *head,
  6790. struct task_struct *task)
  6791. {
  6792. if (bpf_prog_array_valid(call)) {
  6793. *(struct pt_regs **)raw_data = regs;
  6794. if (!trace_call_bpf(call, raw_data) || hlist_empty(head)) {
  6795. perf_swevent_put_recursion_context(rctx);
  6796. return;
  6797. }
  6798. }
  6799. perf_tp_event(call->event.type, count, raw_data, size, regs, head,
  6800. rctx, task);
  6801. }
  6802. EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit);
  6803. void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size,
  6804. struct pt_regs *regs, struct hlist_head *head, int rctx,
  6805. struct task_struct *task)
  6806. {
  6807. struct perf_sample_data data;
  6808. struct perf_event *event;
  6809. struct perf_raw_record raw = {
  6810. .frag = {
  6811. .size = entry_size,
  6812. .data = record,
  6813. },
  6814. };
  6815. perf_sample_data_init(&data, 0, 0);
  6816. data.raw = &raw;
  6817. perf_trace_buf_update(record, event_type);
  6818. hlist_for_each_entry_rcu(event, head, hlist_entry) {
  6819. if (perf_tp_event_match(event, &data, regs))
  6820. perf_swevent_event(event, count, &data, regs);
  6821. }
  6822. /*
  6823. * If we got specified a target task, also iterate its context and
  6824. * deliver this event there too.
  6825. */
  6826. if (task && task != current) {
  6827. struct perf_event_context *ctx;
  6828. struct trace_entry *entry = record;
  6829. rcu_read_lock();
  6830. ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
  6831. if (!ctx)
  6832. goto unlock;
  6833. list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
  6834. if (event->cpu != smp_processor_id())
  6835. continue;
  6836. if (event->attr.type != PERF_TYPE_TRACEPOINT)
  6837. continue;
  6838. if (event->attr.config != entry->type)
  6839. continue;
  6840. if (perf_tp_event_match(event, &data, regs))
  6841. perf_swevent_event(event, count, &data, regs);
  6842. }
  6843. unlock:
  6844. rcu_read_unlock();
  6845. }
  6846. perf_swevent_put_recursion_context(rctx);
  6847. }
  6848. EXPORT_SYMBOL_GPL(perf_tp_event);
  6849. static void tp_perf_event_destroy(struct perf_event *event)
  6850. {
  6851. perf_trace_destroy(event);
  6852. }
  6853. static int perf_tp_event_init(struct perf_event *event)
  6854. {
  6855. int err;
  6856. if (event->attr.type != PERF_TYPE_TRACEPOINT)
  6857. return -ENOENT;
  6858. /*
  6859. * no branch sampling for tracepoint events
  6860. */
  6861. if (has_branch_stack(event))
  6862. return -EOPNOTSUPP;
  6863. err = perf_trace_init(event);
  6864. if (err)
  6865. return err;
  6866. event->destroy = tp_perf_event_destroy;
  6867. return 0;
  6868. }
  6869. static struct pmu perf_tracepoint = {
  6870. .task_ctx_nr = perf_sw_context,
  6871. .event_init = perf_tp_event_init,
  6872. .add = perf_trace_add,
  6873. .del = perf_trace_del,
  6874. .start = perf_swevent_start,
  6875. .stop = perf_swevent_stop,
  6876. .read = perf_swevent_read,
  6877. };
  6878. #if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS)
  6879. /*
  6880. * Flags in config, used by dynamic PMU kprobe and uprobe
  6881. * The flags should match following PMU_FORMAT_ATTR().
  6882. *
  6883. * PERF_PROBE_CONFIG_IS_RETPROBE if set, create kretprobe/uretprobe
  6884. * if not set, create kprobe/uprobe
  6885. *
  6886. * The following values specify a reference counter (or semaphore in the
  6887. * terminology of tools like dtrace, systemtap, etc.) Userspace Statically
  6888. * Defined Tracepoints (USDT). Currently, we use 40 bit for the offset.
  6889. *
  6890. * PERF_UPROBE_REF_CTR_OFFSET_BITS # of bits in config as th offset
  6891. * PERF_UPROBE_REF_CTR_OFFSET_SHIFT # of bits to shift left
  6892. */
  6893. enum perf_probe_config {
  6894. PERF_PROBE_CONFIG_IS_RETPROBE = 1U << 0, /* [k,u]retprobe */
  6895. PERF_UPROBE_REF_CTR_OFFSET_BITS = 32,
  6896. PERF_UPROBE_REF_CTR_OFFSET_SHIFT = 64 - PERF_UPROBE_REF_CTR_OFFSET_BITS,
  6897. };
  6898. PMU_FORMAT_ATTR(retprobe, "config:0");
  6899. #endif
  6900. #ifdef CONFIG_KPROBE_EVENTS
  6901. static struct attribute *kprobe_attrs[] = {
  6902. &format_attr_retprobe.attr,
  6903. NULL,
  6904. };
  6905. static struct attribute_group kprobe_format_group = {
  6906. .name = "format",
  6907. .attrs = kprobe_attrs,
  6908. };
  6909. static const struct attribute_group *kprobe_attr_groups[] = {
  6910. &kprobe_format_group,
  6911. NULL,
  6912. };
  6913. static int perf_kprobe_event_init(struct perf_event *event);
  6914. static struct pmu perf_kprobe = {
  6915. .task_ctx_nr = perf_sw_context,
  6916. .event_init = perf_kprobe_event_init,
  6917. .add = perf_trace_add,
  6918. .del = perf_trace_del,
  6919. .start = perf_swevent_start,
  6920. .stop = perf_swevent_stop,
  6921. .read = perf_swevent_read,
  6922. .attr_groups = kprobe_attr_groups,
  6923. };
  6924. static int perf_kprobe_event_init(struct perf_event *event)
  6925. {
  6926. int err;
  6927. bool is_retprobe;
  6928. if (event->attr.type != perf_kprobe.type)
  6929. return -ENOENT;
  6930. if (!capable(CAP_SYS_ADMIN))
  6931. return -EACCES;
  6932. /*
  6933. * no branch sampling for probe events
  6934. */
  6935. if (has_branch_stack(event))
  6936. return -EOPNOTSUPP;
  6937. is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
  6938. err = perf_kprobe_init(event, is_retprobe);
  6939. if (err)
  6940. return err;
  6941. event->destroy = perf_kprobe_destroy;
  6942. return 0;
  6943. }
  6944. #endif /* CONFIG_KPROBE_EVENTS */
  6945. #ifdef CONFIG_UPROBE_EVENTS
  6946. PMU_FORMAT_ATTR(ref_ctr_offset, "config:32-63");
  6947. static struct attribute *uprobe_attrs[] = {
  6948. &format_attr_retprobe.attr,
  6949. &format_attr_ref_ctr_offset.attr,
  6950. NULL,
  6951. };
  6952. static struct attribute_group uprobe_format_group = {
  6953. .name = "format",
  6954. .attrs = uprobe_attrs,
  6955. };
  6956. static const struct attribute_group *uprobe_attr_groups[] = {
  6957. &uprobe_format_group,
  6958. NULL,
  6959. };
  6960. static int perf_uprobe_event_init(struct perf_event *event);
  6961. static struct pmu perf_uprobe = {
  6962. .task_ctx_nr = perf_sw_context,
  6963. .event_init = perf_uprobe_event_init,
  6964. .add = perf_trace_add,
  6965. .del = perf_trace_del,
  6966. .start = perf_swevent_start,
  6967. .stop = perf_swevent_stop,
  6968. .read = perf_swevent_read,
  6969. .attr_groups = uprobe_attr_groups,
  6970. };
  6971. static int perf_uprobe_event_init(struct perf_event *event)
  6972. {
  6973. int err;
  6974. unsigned long ref_ctr_offset;
  6975. bool is_retprobe;
  6976. if (event->attr.type != perf_uprobe.type)
  6977. return -ENOENT;
  6978. if (!capable(CAP_SYS_ADMIN))
  6979. return -EACCES;
  6980. /*
  6981. * no branch sampling for probe events
  6982. */
  6983. if (has_branch_stack(event))
  6984. return -EOPNOTSUPP;
  6985. is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
  6986. ref_ctr_offset = event->attr.config >> PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
  6987. err = perf_uprobe_init(event, ref_ctr_offset, is_retprobe);
  6988. if (err)
  6989. return err;
  6990. event->destroy = perf_uprobe_destroy;
  6991. return 0;
  6992. }
  6993. #endif /* CONFIG_UPROBE_EVENTS */
  6994. static inline void perf_tp_register(void)
  6995. {
  6996. perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
  6997. #ifdef CONFIG_KPROBE_EVENTS
  6998. perf_pmu_register(&perf_kprobe, "kprobe", -1);
  6999. #endif
  7000. #ifdef CONFIG_UPROBE_EVENTS
  7001. perf_pmu_register(&perf_uprobe, "uprobe", -1);
  7002. #endif
  7003. }
  7004. static void perf_event_free_filter(struct perf_event *event)
  7005. {
  7006. ftrace_profile_free_filter(event);
  7007. }
  7008. #ifdef CONFIG_BPF_SYSCALL
  7009. static void bpf_overflow_handler(struct perf_event *event,
  7010. struct perf_sample_data *data,
  7011. struct pt_regs *regs)
  7012. {
  7013. struct bpf_perf_event_data_kern ctx = {
  7014. .data = data,
  7015. .event = event,
  7016. };
  7017. int ret = 0;
  7018. ctx.regs = perf_arch_bpf_user_pt_regs(regs);
  7019. preempt_disable();
  7020. if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1))
  7021. goto out;
  7022. rcu_read_lock();
  7023. ret = BPF_PROG_RUN(event->prog, &ctx);
  7024. rcu_read_unlock();
  7025. out:
  7026. __this_cpu_dec(bpf_prog_active);
  7027. preempt_enable();
  7028. if (!ret)
  7029. return;
  7030. event->orig_overflow_handler(event, data, regs);
  7031. }
  7032. static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
  7033. {
  7034. struct bpf_prog *prog;
  7035. if (event->overflow_handler_context)
  7036. /* hw breakpoint or kernel counter */
  7037. return -EINVAL;
  7038. if (event->prog)
  7039. return -EEXIST;
  7040. prog = bpf_prog_get_type(prog_fd, BPF_PROG_TYPE_PERF_EVENT);
  7041. if (IS_ERR(prog))
  7042. return PTR_ERR(prog);
  7043. event->prog = prog;
  7044. event->orig_overflow_handler = READ_ONCE(event->overflow_handler);
  7045. WRITE_ONCE(event->overflow_handler, bpf_overflow_handler);
  7046. return 0;
  7047. }
  7048. static void perf_event_free_bpf_handler(struct perf_event *event)
  7049. {
  7050. struct bpf_prog *prog = event->prog;
  7051. if (!prog)
  7052. return;
  7053. WRITE_ONCE(event->overflow_handler, event->orig_overflow_handler);
  7054. event->prog = NULL;
  7055. bpf_prog_put(prog);
  7056. }
  7057. #else
  7058. static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
  7059. {
  7060. return -EOPNOTSUPP;
  7061. }
  7062. static void perf_event_free_bpf_handler(struct perf_event *event)
  7063. {
  7064. }
  7065. #endif
  7066. /*
  7067. * returns true if the event is a tracepoint, or a kprobe/upprobe created
  7068. * with perf_event_open()
  7069. */
  7070. static inline bool perf_event_is_tracing(struct perf_event *event)
  7071. {
  7072. if (event->pmu == &perf_tracepoint)
  7073. return true;
  7074. #ifdef CONFIG_KPROBE_EVENTS
  7075. if (event->pmu == &perf_kprobe)
  7076. return true;
  7077. #endif
  7078. #ifdef CONFIG_UPROBE_EVENTS
  7079. if (event->pmu == &perf_uprobe)
  7080. return true;
  7081. #endif
  7082. return false;
  7083. }
  7084. static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
  7085. {
  7086. bool is_kprobe, is_tracepoint, is_syscall_tp;
  7087. struct bpf_prog *prog;
  7088. int ret;
  7089. if (!perf_event_is_tracing(event))
  7090. return perf_event_set_bpf_handler(event, prog_fd);
  7091. is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_UKPROBE;
  7092. is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT;
  7093. is_syscall_tp = is_syscall_trace_event(event->tp_event);
  7094. if (!is_kprobe && !is_tracepoint && !is_syscall_tp)
  7095. /* bpf programs can only be attached to u/kprobe or tracepoint */
  7096. return -EINVAL;
  7097. prog = bpf_prog_get(prog_fd);
  7098. if (IS_ERR(prog))
  7099. return PTR_ERR(prog);
  7100. if ((is_kprobe && prog->type != BPF_PROG_TYPE_KPROBE) ||
  7101. (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT) ||
  7102. (is_syscall_tp && prog->type != BPF_PROG_TYPE_TRACEPOINT)) {
  7103. /* valid fd, but invalid bpf program type */
  7104. bpf_prog_put(prog);
  7105. return -EINVAL;
  7106. }
  7107. /* Kprobe override only works for kprobes, not uprobes. */
  7108. if (prog->kprobe_override &&
  7109. !(event->tp_event->flags & TRACE_EVENT_FL_KPROBE)) {
  7110. bpf_prog_put(prog);
  7111. return -EINVAL;
  7112. }
  7113. if (is_tracepoint || is_syscall_tp) {
  7114. int off = trace_event_get_offsets(event->tp_event);
  7115. if (prog->aux->max_ctx_offset > off) {
  7116. bpf_prog_put(prog);
  7117. return -EACCES;
  7118. }
  7119. }
  7120. ret = perf_event_attach_bpf_prog(event, prog);
  7121. if (ret)
  7122. bpf_prog_put(prog);
  7123. return ret;
  7124. }
  7125. static void perf_event_free_bpf_prog(struct perf_event *event)
  7126. {
  7127. if (!perf_event_is_tracing(event)) {
  7128. perf_event_free_bpf_handler(event);
  7129. return;
  7130. }
  7131. perf_event_detach_bpf_prog(event);
  7132. }
  7133. #else
  7134. static inline void perf_tp_register(void)
  7135. {
  7136. }
  7137. static void perf_event_free_filter(struct perf_event *event)
  7138. {
  7139. }
  7140. static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
  7141. {
  7142. return -ENOENT;
  7143. }
  7144. static void perf_event_free_bpf_prog(struct perf_event *event)
  7145. {
  7146. }
  7147. #endif /* CONFIG_EVENT_TRACING */
  7148. #ifdef CONFIG_HAVE_HW_BREAKPOINT
  7149. void perf_bp_event(struct perf_event *bp, void *data)
  7150. {
  7151. struct perf_sample_data sample;
  7152. struct pt_regs *regs = data;
  7153. perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
  7154. if (!bp->hw.state && !perf_exclude_event(bp, regs))
  7155. perf_swevent_event(bp, 1, &sample, regs);
  7156. }
  7157. #endif
  7158. /*
  7159. * Allocate a new address filter
  7160. */
  7161. static struct perf_addr_filter *
  7162. perf_addr_filter_new(struct perf_event *event, struct list_head *filters)
  7163. {
  7164. int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu);
  7165. struct perf_addr_filter *filter;
  7166. filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node);
  7167. if (!filter)
  7168. return NULL;
  7169. INIT_LIST_HEAD(&filter->entry);
  7170. list_add_tail(&filter->entry, filters);
  7171. return filter;
  7172. }
  7173. static void free_filters_list(struct list_head *filters)
  7174. {
  7175. struct perf_addr_filter *filter, *iter;
  7176. list_for_each_entry_safe(filter, iter, filters, entry) {
  7177. path_put(&filter->path);
  7178. list_del(&filter->entry);
  7179. kfree(filter);
  7180. }
  7181. }
  7182. /*
  7183. * Free existing address filters and optionally install new ones
  7184. */
  7185. static void perf_addr_filters_splice(struct perf_event *event,
  7186. struct list_head *head)
  7187. {
  7188. unsigned long flags;
  7189. LIST_HEAD(list);
  7190. if (!has_addr_filter(event))
  7191. return;
  7192. /* don't bother with children, they don't have their own filters */
  7193. if (event->parent)
  7194. return;
  7195. raw_spin_lock_irqsave(&event->addr_filters.lock, flags);
  7196. list_splice_init(&event->addr_filters.list, &list);
  7197. if (head)
  7198. list_splice(head, &event->addr_filters.list);
  7199. raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags);
  7200. free_filters_list(&list);
  7201. }
  7202. /*
  7203. * Scan through mm's vmas and see if one of them matches the
  7204. * @filter; if so, adjust filter's address range.
  7205. * Called with mm::mmap_sem down for reading.
  7206. */
  7207. static unsigned long perf_addr_filter_apply(struct perf_addr_filter *filter,
  7208. struct mm_struct *mm)
  7209. {
  7210. struct vm_area_struct *vma;
  7211. for (vma = mm->mmap; vma; vma = vma->vm_next) {
  7212. struct file *file = vma->vm_file;
  7213. unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
  7214. unsigned long vma_size = vma->vm_end - vma->vm_start;
  7215. if (!file)
  7216. continue;
  7217. if (!perf_addr_filter_match(filter, file, off, vma_size))
  7218. continue;
  7219. return vma->vm_start;
  7220. }
  7221. return 0;
  7222. }
  7223. /*
  7224. * Update event's address range filters based on the
  7225. * task's existing mappings, if any.
  7226. */
  7227. static void perf_event_addr_filters_apply(struct perf_event *event)
  7228. {
  7229. struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
  7230. struct task_struct *task = READ_ONCE(event->ctx->task);
  7231. struct perf_addr_filter *filter;
  7232. struct mm_struct *mm = NULL;
  7233. unsigned int count = 0;
  7234. unsigned long flags;
  7235. /*
  7236. * We may observe TASK_TOMBSTONE, which means that the event tear-down
  7237. * will stop on the parent's child_mutex that our caller is also holding
  7238. */
  7239. if (task == TASK_TOMBSTONE)
  7240. return;
  7241. if (!ifh->nr_file_filters)
  7242. return;
  7243. mm = get_task_mm(event->ctx->task);
  7244. if (!mm)
  7245. goto restart;
  7246. down_read(&mm->mmap_sem);
  7247. raw_spin_lock_irqsave(&ifh->lock, flags);
  7248. list_for_each_entry(filter, &ifh->list, entry) {
  7249. event->addr_filters_offs[count] = 0;
  7250. /*
  7251. * Adjust base offset if the filter is associated to a binary
  7252. * that needs to be mapped:
  7253. */
  7254. if (filter->path.dentry)
  7255. event->addr_filters_offs[count] =
  7256. perf_addr_filter_apply(filter, mm);
  7257. count++;
  7258. }
  7259. event->addr_filters_gen++;
  7260. raw_spin_unlock_irqrestore(&ifh->lock, flags);
  7261. up_read(&mm->mmap_sem);
  7262. mmput(mm);
  7263. restart:
  7264. perf_event_stop(event, 1);
  7265. }
  7266. /*
  7267. * Address range filtering: limiting the data to certain
  7268. * instruction address ranges. Filters are ioctl()ed to us from
  7269. * userspace as ascii strings.
  7270. *
  7271. * Filter string format:
  7272. *
  7273. * ACTION RANGE_SPEC
  7274. * where ACTION is one of the
  7275. * * "filter": limit the trace to this region
  7276. * * "start": start tracing from this address
  7277. * * "stop": stop tracing at this address/region;
  7278. * RANGE_SPEC is
  7279. * * for kernel addresses: <start address>[/<size>]
  7280. * * for object files: <start address>[/<size>]@</path/to/object/file>
  7281. *
  7282. * if <size> is not specified or is zero, the range is treated as a single
  7283. * address; not valid for ACTION=="filter".
  7284. */
  7285. enum {
  7286. IF_ACT_NONE = -1,
  7287. IF_ACT_FILTER,
  7288. IF_ACT_START,
  7289. IF_ACT_STOP,
  7290. IF_SRC_FILE,
  7291. IF_SRC_KERNEL,
  7292. IF_SRC_FILEADDR,
  7293. IF_SRC_KERNELADDR,
  7294. };
  7295. enum {
  7296. IF_STATE_ACTION = 0,
  7297. IF_STATE_SOURCE,
  7298. IF_STATE_END,
  7299. };
  7300. static const match_table_t if_tokens = {
  7301. { IF_ACT_FILTER, "filter" },
  7302. { IF_ACT_START, "start" },
  7303. { IF_ACT_STOP, "stop" },
  7304. { IF_SRC_FILE, "%u/%u@%s" },
  7305. { IF_SRC_KERNEL, "%u/%u" },
  7306. { IF_SRC_FILEADDR, "%u@%s" },
  7307. { IF_SRC_KERNELADDR, "%u" },
  7308. { IF_ACT_NONE, NULL },
  7309. };
  7310. /*
  7311. * Address filter string parser
  7312. */
  7313. static int
  7314. perf_event_parse_addr_filter(struct perf_event *event, char *fstr,
  7315. struct list_head *filters)
  7316. {
  7317. struct perf_addr_filter *filter = NULL;
  7318. char *start, *orig, *filename = NULL;
  7319. substring_t args[MAX_OPT_ARGS];
  7320. int state = IF_STATE_ACTION, token;
  7321. unsigned int kernel = 0;
  7322. int ret = -EINVAL;
  7323. orig = fstr = kstrdup(fstr, GFP_KERNEL);
  7324. if (!fstr)
  7325. return -ENOMEM;
  7326. while ((start = strsep(&fstr, " ,\n")) != NULL) {
  7327. static const enum perf_addr_filter_action_t actions[] = {
  7328. [IF_ACT_FILTER] = PERF_ADDR_FILTER_ACTION_FILTER,
  7329. [IF_ACT_START] = PERF_ADDR_FILTER_ACTION_START,
  7330. [IF_ACT_STOP] = PERF_ADDR_FILTER_ACTION_STOP,
  7331. };
  7332. ret = -EINVAL;
  7333. if (!*start)
  7334. continue;
  7335. /* filter definition begins */
  7336. if (state == IF_STATE_ACTION) {
  7337. filter = perf_addr_filter_new(event, filters);
  7338. if (!filter)
  7339. goto fail;
  7340. }
  7341. token = match_token(start, if_tokens, args);
  7342. switch (token) {
  7343. case IF_ACT_FILTER:
  7344. case IF_ACT_START:
  7345. case IF_ACT_STOP:
  7346. if (state != IF_STATE_ACTION)
  7347. goto fail;
  7348. filter->action = actions[token];
  7349. state = IF_STATE_SOURCE;
  7350. break;
  7351. case IF_SRC_KERNELADDR:
  7352. case IF_SRC_KERNEL:
  7353. kernel = 1;
  7354. case IF_SRC_FILEADDR:
  7355. case IF_SRC_FILE:
  7356. if (state != IF_STATE_SOURCE)
  7357. goto fail;
  7358. *args[0].to = 0;
  7359. ret = kstrtoul(args[0].from, 0, &filter->offset);
  7360. if (ret)
  7361. goto fail;
  7362. if (token == IF_SRC_KERNEL || token == IF_SRC_FILE) {
  7363. *args[1].to = 0;
  7364. ret = kstrtoul(args[1].from, 0, &filter->size);
  7365. if (ret)
  7366. goto fail;
  7367. }
  7368. if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) {
  7369. int fpos = token == IF_SRC_FILE ? 2 : 1;
  7370. filename = match_strdup(&args[fpos]);
  7371. if (!filename) {
  7372. ret = -ENOMEM;
  7373. goto fail;
  7374. }
  7375. }
  7376. state = IF_STATE_END;
  7377. break;
  7378. default:
  7379. goto fail;
  7380. }
  7381. /*
  7382. * Filter definition is fully parsed, validate and install it.
  7383. * Make sure that it doesn't contradict itself or the event's
  7384. * attribute.
  7385. */
  7386. if (state == IF_STATE_END) {
  7387. ret = -EINVAL;
  7388. if (kernel && event->attr.exclude_kernel)
  7389. goto fail;
  7390. /*
  7391. * ACTION "filter" must have a non-zero length region
  7392. * specified.
  7393. */
  7394. if (filter->action == PERF_ADDR_FILTER_ACTION_FILTER &&
  7395. !filter->size)
  7396. goto fail;
  7397. if (!kernel) {
  7398. if (!filename)
  7399. goto fail;
  7400. /*
  7401. * For now, we only support file-based filters
  7402. * in per-task events; doing so for CPU-wide
  7403. * events requires additional context switching
  7404. * trickery, since same object code will be
  7405. * mapped at different virtual addresses in
  7406. * different processes.
  7407. */
  7408. ret = -EOPNOTSUPP;
  7409. if (!event->ctx->task)
  7410. goto fail_free_name;
  7411. /* look up the path and grab its inode */
  7412. ret = kern_path(filename, LOOKUP_FOLLOW,
  7413. &filter->path);
  7414. if (ret)
  7415. goto fail_free_name;
  7416. kfree(filename);
  7417. filename = NULL;
  7418. ret = -EINVAL;
  7419. if (!filter->path.dentry ||
  7420. !S_ISREG(d_inode(filter->path.dentry)
  7421. ->i_mode))
  7422. goto fail;
  7423. event->addr_filters.nr_file_filters++;
  7424. }
  7425. /* ready to consume more filters */
  7426. state = IF_STATE_ACTION;
  7427. filter = NULL;
  7428. }
  7429. }
  7430. if (state != IF_STATE_ACTION)
  7431. goto fail;
  7432. kfree(orig);
  7433. return 0;
  7434. fail_free_name:
  7435. kfree(filename);
  7436. fail:
  7437. free_filters_list(filters);
  7438. kfree(orig);
  7439. return ret;
  7440. }
  7441. static int
  7442. perf_event_set_addr_filter(struct perf_event *event, char *filter_str)
  7443. {
  7444. LIST_HEAD(filters);
  7445. int ret;
  7446. /*
  7447. * Since this is called in perf_ioctl() path, we're already holding
  7448. * ctx::mutex.
  7449. */
  7450. lockdep_assert_held(&event->ctx->mutex);
  7451. if (WARN_ON_ONCE(event->parent))
  7452. return -EINVAL;
  7453. ret = perf_event_parse_addr_filter(event, filter_str, &filters);
  7454. if (ret)
  7455. goto fail_clear_files;
  7456. ret = event->pmu->addr_filters_validate(&filters);
  7457. if (ret)
  7458. goto fail_free_filters;
  7459. /* remove existing filters, if any */
  7460. perf_addr_filters_splice(event, &filters);
  7461. /* install new filters */
  7462. perf_event_for_each_child(event, perf_event_addr_filters_apply);
  7463. return ret;
  7464. fail_free_filters:
  7465. free_filters_list(&filters);
  7466. fail_clear_files:
  7467. event->addr_filters.nr_file_filters = 0;
  7468. return ret;
  7469. }
  7470. static int perf_event_set_filter(struct perf_event *event, void __user *arg)
  7471. {
  7472. int ret = -EINVAL;
  7473. char *filter_str;
  7474. filter_str = strndup_user(arg, PAGE_SIZE);
  7475. if (IS_ERR(filter_str))
  7476. return PTR_ERR(filter_str);
  7477. #ifdef CONFIG_EVENT_TRACING
  7478. if (perf_event_is_tracing(event)) {
  7479. struct perf_event_context *ctx = event->ctx;
  7480. /*
  7481. * Beware, here be dragons!!
  7482. *
  7483. * the tracepoint muck will deadlock against ctx->mutex, but
  7484. * the tracepoint stuff does not actually need it. So
  7485. * temporarily drop ctx->mutex. As per perf_event_ctx_lock() we
  7486. * already have a reference on ctx.
  7487. *
  7488. * This can result in event getting moved to a different ctx,
  7489. * but that does not affect the tracepoint state.
  7490. */
  7491. mutex_unlock(&ctx->mutex);
  7492. ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
  7493. mutex_lock(&ctx->mutex);
  7494. } else
  7495. #endif
  7496. if (has_addr_filter(event))
  7497. ret = perf_event_set_addr_filter(event, filter_str);
  7498. kfree(filter_str);
  7499. return ret;
  7500. }
  7501. /*
  7502. * hrtimer based swevent callback
  7503. */
  7504. static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
  7505. {
  7506. enum hrtimer_restart ret = HRTIMER_RESTART;
  7507. struct perf_sample_data data;
  7508. struct pt_regs *regs;
  7509. struct perf_event *event;
  7510. u64 period;
  7511. event = container_of(hrtimer, struct perf_event, hw.hrtimer);
  7512. if (event->state != PERF_EVENT_STATE_ACTIVE)
  7513. return HRTIMER_NORESTART;
  7514. event->pmu->read(event);
  7515. perf_sample_data_init(&data, 0, event->hw.last_period);
  7516. regs = get_irq_regs();
  7517. if (regs && !perf_exclude_event(event, regs)) {
  7518. if (!(event->attr.exclude_idle && is_idle_task(current)))
  7519. if (__perf_event_overflow(event, 1, &data, regs))
  7520. ret = HRTIMER_NORESTART;
  7521. }
  7522. period = max_t(u64, 10000, event->hw.sample_period);
  7523. hrtimer_forward_now(hrtimer, ns_to_ktime(period));
  7524. return ret;
  7525. }
  7526. static void perf_swevent_start_hrtimer(struct perf_event *event)
  7527. {
  7528. struct hw_perf_event *hwc = &event->hw;
  7529. s64 period;
  7530. if (!is_sampling_event(event))
  7531. return;
  7532. period = local64_read(&hwc->period_left);
  7533. if (period) {
  7534. if (period < 0)
  7535. period = 10000;
  7536. local64_set(&hwc->period_left, 0);
  7537. } else {
  7538. period = max_t(u64, 10000, hwc->sample_period);
  7539. }
  7540. hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
  7541. HRTIMER_MODE_REL_PINNED);
  7542. }
  7543. static void perf_swevent_cancel_hrtimer(struct perf_event *event)
  7544. {
  7545. struct hw_perf_event *hwc = &event->hw;
  7546. if (is_sampling_event(event)) {
  7547. ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
  7548. local64_set(&hwc->period_left, ktime_to_ns(remaining));
  7549. hrtimer_cancel(&hwc->hrtimer);
  7550. }
  7551. }
  7552. static void perf_swevent_init_hrtimer(struct perf_event *event)
  7553. {
  7554. struct hw_perf_event *hwc = &event->hw;
  7555. if (!is_sampling_event(event))
  7556. return;
  7557. hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
  7558. hwc->hrtimer.function = perf_swevent_hrtimer;
  7559. /*
  7560. * Since hrtimers have a fixed rate, we can do a static freq->period
  7561. * mapping and avoid the whole period adjust feedback stuff.
  7562. */
  7563. if (event->attr.freq) {
  7564. long freq = event->attr.sample_freq;
  7565. event->attr.sample_period = NSEC_PER_SEC / freq;
  7566. hwc->sample_period = event->attr.sample_period;
  7567. local64_set(&hwc->period_left, hwc->sample_period);
  7568. hwc->last_period = hwc->sample_period;
  7569. event->attr.freq = 0;
  7570. }
  7571. }
  7572. /*
  7573. * Software event: cpu wall time clock
  7574. */
  7575. static void cpu_clock_event_update(struct perf_event *event)
  7576. {
  7577. s64 prev;
  7578. u64 now;
  7579. now = local_clock();
  7580. prev = local64_xchg(&event->hw.prev_count, now);
  7581. local64_add(now - prev, &event->count);
  7582. }
  7583. static void cpu_clock_event_start(struct perf_event *event, int flags)
  7584. {
  7585. local64_set(&event->hw.prev_count, local_clock());
  7586. perf_swevent_start_hrtimer(event);
  7587. }
  7588. static void cpu_clock_event_stop(struct perf_event *event, int flags)
  7589. {
  7590. perf_swevent_cancel_hrtimer(event);
  7591. cpu_clock_event_update(event);
  7592. }
  7593. static int cpu_clock_event_add(struct perf_event *event, int flags)
  7594. {
  7595. if (flags & PERF_EF_START)
  7596. cpu_clock_event_start(event, flags);
  7597. perf_event_update_userpage(event);
  7598. return 0;
  7599. }
  7600. static void cpu_clock_event_del(struct perf_event *event, int flags)
  7601. {
  7602. cpu_clock_event_stop(event, flags);
  7603. }
  7604. static void cpu_clock_event_read(struct perf_event *event)
  7605. {
  7606. cpu_clock_event_update(event);
  7607. }
  7608. static int cpu_clock_event_init(struct perf_event *event)
  7609. {
  7610. if (event->attr.type != PERF_TYPE_SOFTWARE)
  7611. return -ENOENT;
  7612. if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
  7613. return -ENOENT;
  7614. /*
  7615. * no branch sampling for software events
  7616. */
  7617. if (has_branch_stack(event))
  7618. return -EOPNOTSUPP;
  7619. perf_swevent_init_hrtimer(event);
  7620. return 0;
  7621. }
  7622. static struct pmu perf_cpu_clock = {
  7623. .task_ctx_nr = perf_sw_context,
  7624. .capabilities = PERF_PMU_CAP_NO_NMI,
  7625. .event_init = cpu_clock_event_init,
  7626. .add = cpu_clock_event_add,
  7627. .del = cpu_clock_event_del,
  7628. .start = cpu_clock_event_start,
  7629. .stop = cpu_clock_event_stop,
  7630. .read = cpu_clock_event_read,
  7631. };
  7632. /*
  7633. * Software event: task time clock
  7634. */
  7635. static void task_clock_event_update(struct perf_event *event, u64 now)
  7636. {
  7637. u64 prev;
  7638. s64 delta;
  7639. prev = local64_xchg(&event->hw.prev_count, now);
  7640. delta = now - prev;
  7641. local64_add(delta, &event->count);
  7642. }
  7643. static void task_clock_event_start(struct perf_event *event, int flags)
  7644. {
  7645. local64_set(&event->hw.prev_count, event->ctx->time);
  7646. perf_swevent_start_hrtimer(event);
  7647. }
  7648. static void task_clock_event_stop(struct perf_event *event, int flags)
  7649. {
  7650. perf_swevent_cancel_hrtimer(event);
  7651. task_clock_event_update(event, event->ctx->time);
  7652. }
  7653. static int task_clock_event_add(struct perf_event *event, int flags)
  7654. {
  7655. if (flags & PERF_EF_START)
  7656. task_clock_event_start(event, flags);
  7657. perf_event_update_userpage(event);
  7658. return 0;
  7659. }
  7660. static void task_clock_event_del(struct perf_event *event, int flags)
  7661. {
  7662. task_clock_event_stop(event, PERF_EF_UPDATE);
  7663. }
  7664. static void task_clock_event_read(struct perf_event *event)
  7665. {
  7666. u64 now = perf_clock();
  7667. u64 delta = now - event->ctx->timestamp;
  7668. u64 time = event->ctx->time + delta;
  7669. task_clock_event_update(event, time);
  7670. }
  7671. static int task_clock_event_init(struct perf_event *event)
  7672. {
  7673. if (event->attr.type != PERF_TYPE_SOFTWARE)
  7674. return -ENOENT;
  7675. if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
  7676. return -ENOENT;
  7677. /*
  7678. * no branch sampling for software events
  7679. */
  7680. if (has_branch_stack(event))
  7681. return -EOPNOTSUPP;
  7682. perf_swevent_init_hrtimer(event);
  7683. return 0;
  7684. }
  7685. static struct pmu perf_task_clock = {
  7686. .task_ctx_nr = perf_sw_context,
  7687. .capabilities = PERF_PMU_CAP_NO_NMI,
  7688. .event_init = task_clock_event_init,
  7689. .add = task_clock_event_add,
  7690. .del = task_clock_event_del,
  7691. .start = task_clock_event_start,
  7692. .stop = task_clock_event_stop,
  7693. .read = task_clock_event_read,
  7694. };
  7695. static void perf_pmu_nop_void(struct pmu *pmu)
  7696. {
  7697. }
  7698. static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
  7699. {
  7700. }
  7701. static int perf_pmu_nop_int(struct pmu *pmu)
  7702. {
  7703. return 0;
  7704. }
  7705. static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
  7706. static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
  7707. {
  7708. __this_cpu_write(nop_txn_flags, flags);
  7709. if (flags & ~PERF_PMU_TXN_ADD)
  7710. return;
  7711. perf_pmu_disable(pmu);
  7712. }
  7713. static int perf_pmu_commit_txn(struct pmu *pmu)
  7714. {
  7715. unsigned int flags = __this_cpu_read(nop_txn_flags);
  7716. __this_cpu_write(nop_txn_flags, 0);
  7717. if (flags & ~PERF_PMU_TXN_ADD)
  7718. return 0;
  7719. perf_pmu_enable(pmu);
  7720. return 0;
  7721. }
  7722. static void perf_pmu_cancel_txn(struct pmu *pmu)
  7723. {
  7724. unsigned int flags = __this_cpu_read(nop_txn_flags);
  7725. __this_cpu_write(nop_txn_flags, 0);
  7726. if (flags & ~PERF_PMU_TXN_ADD)
  7727. return;
  7728. perf_pmu_enable(pmu);
  7729. }
  7730. static int perf_event_idx_default(struct perf_event *event)
  7731. {
  7732. return 0;
  7733. }
  7734. /*
  7735. * Ensures all contexts with the same task_ctx_nr have the same
  7736. * pmu_cpu_context too.
  7737. */
  7738. static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
  7739. {
  7740. struct pmu *pmu;
  7741. if (ctxn < 0)
  7742. return NULL;
  7743. list_for_each_entry(pmu, &pmus, entry) {
  7744. if (pmu->task_ctx_nr == ctxn)
  7745. return pmu->pmu_cpu_context;
  7746. }
  7747. return NULL;
  7748. }
  7749. static void free_pmu_context(struct pmu *pmu)
  7750. {
  7751. /*
  7752. * Static contexts such as perf_sw_context have a global lifetime
  7753. * and may be shared between different PMUs. Avoid freeing them
  7754. * when a single PMU is going away.
  7755. */
  7756. if (pmu->task_ctx_nr > perf_invalid_context)
  7757. return;
  7758. free_percpu(pmu->pmu_cpu_context);
  7759. }
  7760. /*
  7761. * Let userspace know that this PMU supports address range filtering:
  7762. */
  7763. static ssize_t nr_addr_filters_show(struct device *dev,
  7764. struct device_attribute *attr,
  7765. char *page)
  7766. {
  7767. struct pmu *pmu = dev_get_drvdata(dev);
  7768. return snprintf(page, PAGE_SIZE - 1, "%d\n", pmu->nr_addr_filters);
  7769. }
  7770. DEVICE_ATTR_RO(nr_addr_filters);
  7771. static struct idr pmu_idr;
  7772. static ssize_t
  7773. type_show(struct device *dev, struct device_attribute *attr, char *page)
  7774. {
  7775. struct pmu *pmu = dev_get_drvdata(dev);
  7776. return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
  7777. }
  7778. static DEVICE_ATTR_RO(type);
  7779. static ssize_t
  7780. perf_event_mux_interval_ms_show(struct device *dev,
  7781. struct device_attribute *attr,
  7782. char *page)
  7783. {
  7784. struct pmu *pmu = dev_get_drvdata(dev);
  7785. return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
  7786. }
  7787. static DEFINE_MUTEX(mux_interval_mutex);
  7788. static ssize_t
  7789. perf_event_mux_interval_ms_store(struct device *dev,
  7790. struct device_attribute *attr,
  7791. const char *buf, size_t count)
  7792. {
  7793. struct pmu *pmu = dev_get_drvdata(dev);
  7794. int timer, cpu, ret;
  7795. ret = kstrtoint(buf, 0, &timer);
  7796. if (ret)
  7797. return ret;
  7798. if (timer < 1)
  7799. return -EINVAL;
  7800. /* same value, noting to do */
  7801. if (timer == pmu->hrtimer_interval_ms)
  7802. return count;
  7803. mutex_lock(&mux_interval_mutex);
  7804. pmu->hrtimer_interval_ms = timer;
  7805. /* update all cpuctx for this PMU */
  7806. cpus_read_lock();
  7807. for_each_online_cpu(cpu) {
  7808. struct perf_cpu_context *cpuctx;
  7809. cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
  7810. cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
  7811. cpu_function_call(cpu,
  7812. (remote_function_f)perf_mux_hrtimer_restart, cpuctx);
  7813. }
  7814. cpus_read_unlock();
  7815. mutex_unlock(&mux_interval_mutex);
  7816. return count;
  7817. }
  7818. static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
  7819. static struct attribute *pmu_dev_attrs[] = {
  7820. &dev_attr_type.attr,
  7821. &dev_attr_perf_event_mux_interval_ms.attr,
  7822. NULL,
  7823. };
  7824. ATTRIBUTE_GROUPS(pmu_dev);
  7825. static int pmu_bus_running;
  7826. static struct bus_type pmu_bus = {
  7827. .name = "event_source",
  7828. .dev_groups = pmu_dev_groups,
  7829. };
  7830. static void pmu_dev_release(struct device *dev)
  7831. {
  7832. kfree(dev);
  7833. }
  7834. static int pmu_dev_alloc(struct pmu *pmu)
  7835. {
  7836. int ret = -ENOMEM;
  7837. pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
  7838. if (!pmu->dev)
  7839. goto out;
  7840. pmu->dev->groups = pmu->attr_groups;
  7841. device_initialize(pmu->dev);
  7842. ret = dev_set_name(pmu->dev, "%s", pmu->name);
  7843. if (ret)
  7844. goto free_dev;
  7845. dev_set_drvdata(pmu->dev, pmu);
  7846. pmu->dev->bus = &pmu_bus;
  7847. pmu->dev->release = pmu_dev_release;
  7848. ret = device_add(pmu->dev);
  7849. if (ret)
  7850. goto free_dev;
  7851. /* For PMUs with address filters, throw in an extra attribute: */
  7852. if (pmu->nr_addr_filters)
  7853. ret = device_create_file(pmu->dev, &dev_attr_nr_addr_filters);
  7854. if (ret)
  7855. goto del_dev;
  7856. out:
  7857. return ret;
  7858. del_dev:
  7859. device_del(pmu->dev);
  7860. free_dev:
  7861. put_device(pmu->dev);
  7862. goto out;
  7863. }
  7864. static struct lock_class_key cpuctx_mutex;
  7865. static struct lock_class_key cpuctx_lock;
  7866. int perf_pmu_register(struct pmu *pmu, const char *name, int type)
  7867. {
  7868. int cpu, ret;
  7869. mutex_lock(&pmus_lock);
  7870. ret = -ENOMEM;
  7871. pmu->pmu_disable_count = alloc_percpu(int);
  7872. if (!pmu->pmu_disable_count)
  7873. goto unlock;
  7874. pmu->type = -1;
  7875. if (!name)
  7876. goto skip_type;
  7877. pmu->name = name;
  7878. if (type < 0) {
  7879. type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL);
  7880. if (type < 0) {
  7881. ret = type;
  7882. goto free_pdc;
  7883. }
  7884. }
  7885. pmu->type = type;
  7886. if (pmu_bus_running) {
  7887. ret = pmu_dev_alloc(pmu);
  7888. if (ret)
  7889. goto free_idr;
  7890. }
  7891. skip_type:
  7892. if (pmu->task_ctx_nr == perf_hw_context) {
  7893. static int hw_context_taken = 0;
  7894. /*
  7895. * Other than systems with heterogeneous CPUs, it never makes
  7896. * sense for two PMUs to share perf_hw_context. PMUs which are
  7897. * uncore must use perf_invalid_context.
  7898. */
  7899. if (WARN_ON_ONCE(hw_context_taken &&
  7900. !(pmu->capabilities & PERF_PMU_CAP_HETEROGENEOUS_CPUS)))
  7901. pmu->task_ctx_nr = perf_invalid_context;
  7902. hw_context_taken = 1;
  7903. }
  7904. pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
  7905. if (pmu->pmu_cpu_context)
  7906. goto got_cpu_context;
  7907. ret = -ENOMEM;
  7908. pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
  7909. if (!pmu->pmu_cpu_context)
  7910. goto free_dev;
  7911. for_each_possible_cpu(cpu) {
  7912. struct perf_cpu_context *cpuctx;
  7913. cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
  7914. __perf_event_init_context(&cpuctx->ctx);
  7915. lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
  7916. lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
  7917. cpuctx->ctx.pmu = pmu;
  7918. cpuctx->online = cpumask_test_cpu(cpu, perf_online_mask);
  7919. __perf_mux_hrtimer_init(cpuctx, cpu);
  7920. }
  7921. got_cpu_context:
  7922. if (!pmu->start_txn) {
  7923. if (pmu->pmu_enable) {
  7924. /*
  7925. * If we have pmu_enable/pmu_disable calls, install
  7926. * transaction stubs that use that to try and batch
  7927. * hardware accesses.
  7928. */
  7929. pmu->start_txn = perf_pmu_start_txn;
  7930. pmu->commit_txn = perf_pmu_commit_txn;
  7931. pmu->cancel_txn = perf_pmu_cancel_txn;
  7932. } else {
  7933. pmu->start_txn = perf_pmu_nop_txn;
  7934. pmu->commit_txn = perf_pmu_nop_int;
  7935. pmu->cancel_txn = perf_pmu_nop_void;
  7936. }
  7937. }
  7938. if (!pmu->pmu_enable) {
  7939. pmu->pmu_enable = perf_pmu_nop_void;
  7940. pmu->pmu_disable = perf_pmu_nop_void;
  7941. }
  7942. if (!pmu->event_idx)
  7943. pmu->event_idx = perf_event_idx_default;
  7944. list_add_rcu(&pmu->entry, &pmus);
  7945. atomic_set(&pmu->exclusive_cnt, 0);
  7946. ret = 0;
  7947. unlock:
  7948. mutex_unlock(&pmus_lock);
  7949. return ret;
  7950. free_dev:
  7951. device_del(pmu->dev);
  7952. put_device(pmu->dev);
  7953. free_idr:
  7954. if (pmu->type >= PERF_TYPE_MAX)
  7955. idr_remove(&pmu_idr, pmu->type);
  7956. free_pdc:
  7957. free_percpu(pmu->pmu_disable_count);
  7958. goto unlock;
  7959. }
  7960. EXPORT_SYMBOL_GPL(perf_pmu_register);
  7961. void perf_pmu_unregister(struct pmu *pmu)
  7962. {
  7963. mutex_lock(&pmus_lock);
  7964. list_del_rcu(&pmu->entry);
  7965. /*
  7966. * We dereference the pmu list under both SRCU and regular RCU, so
  7967. * synchronize against both of those.
  7968. */
  7969. synchronize_srcu(&pmus_srcu);
  7970. synchronize_rcu();
  7971. free_percpu(pmu->pmu_disable_count);
  7972. if (pmu->type >= PERF_TYPE_MAX)
  7973. idr_remove(&pmu_idr, pmu->type);
  7974. if (pmu_bus_running) {
  7975. if (pmu->nr_addr_filters)
  7976. device_remove_file(pmu->dev, &dev_attr_nr_addr_filters);
  7977. device_del(pmu->dev);
  7978. put_device(pmu->dev);
  7979. }
  7980. free_pmu_context(pmu);
  7981. mutex_unlock(&pmus_lock);
  7982. }
  7983. EXPORT_SYMBOL_GPL(perf_pmu_unregister);
  7984. static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
  7985. {
  7986. struct perf_event_context *ctx = NULL;
  7987. int ret;
  7988. if (!try_module_get(pmu->module))
  7989. return -ENODEV;
  7990. /*
  7991. * A number of pmu->event_init() methods iterate the sibling_list to,
  7992. * for example, validate if the group fits on the PMU. Therefore,
  7993. * if this is a sibling event, acquire the ctx->mutex to protect
  7994. * the sibling_list.
  7995. */
  7996. if (event->group_leader != event && pmu->task_ctx_nr != perf_sw_context) {
  7997. /*
  7998. * This ctx->mutex can nest when we're called through
  7999. * inheritance. See the perf_event_ctx_lock_nested() comment.
  8000. */
  8001. ctx = perf_event_ctx_lock_nested(event->group_leader,
  8002. SINGLE_DEPTH_NESTING);
  8003. BUG_ON(!ctx);
  8004. }
  8005. event->pmu = pmu;
  8006. ret = pmu->event_init(event);
  8007. if (ctx)
  8008. perf_event_ctx_unlock(event->group_leader, ctx);
  8009. if (ret)
  8010. module_put(pmu->module);
  8011. return ret;
  8012. }
  8013. static struct pmu *perf_init_event(struct perf_event *event)
  8014. {
  8015. struct pmu *pmu;
  8016. int idx;
  8017. int ret;
  8018. idx = srcu_read_lock(&pmus_srcu);
  8019. /* Try parent's PMU first: */
  8020. if (event->parent && event->parent->pmu) {
  8021. pmu = event->parent->pmu;
  8022. ret = perf_try_init_event(pmu, event);
  8023. if (!ret)
  8024. goto unlock;
  8025. }
  8026. rcu_read_lock();
  8027. pmu = idr_find(&pmu_idr, event->attr.type);
  8028. rcu_read_unlock();
  8029. if (pmu) {
  8030. ret = perf_try_init_event(pmu, event);
  8031. if (ret)
  8032. pmu = ERR_PTR(ret);
  8033. goto unlock;
  8034. }
  8035. list_for_each_entry_rcu(pmu, &pmus, entry) {
  8036. ret = perf_try_init_event(pmu, event);
  8037. if (!ret)
  8038. goto unlock;
  8039. if (ret != -ENOENT) {
  8040. pmu = ERR_PTR(ret);
  8041. goto unlock;
  8042. }
  8043. }
  8044. pmu = ERR_PTR(-ENOENT);
  8045. unlock:
  8046. srcu_read_unlock(&pmus_srcu, idx);
  8047. return pmu;
  8048. }
  8049. static void attach_sb_event(struct perf_event *event)
  8050. {
  8051. struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
  8052. raw_spin_lock(&pel->lock);
  8053. list_add_rcu(&event->sb_list, &pel->list);
  8054. raw_spin_unlock(&pel->lock);
  8055. }
  8056. /*
  8057. * We keep a list of all !task (and therefore per-cpu) events
  8058. * that need to receive side-band records.
  8059. *
  8060. * This avoids having to scan all the various PMU per-cpu contexts
  8061. * looking for them.
  8062. */
  8063. static void account_pmu_sb_event(struct perf_event *event)
  8064. {
  8065. if (is_sb_event(event))
  8066. attach_sb_event(event);
  8067. }
  8068. static void account_event_cpu(struct perf_event *event, int cpu)
  8069. {
  8070. if (event->parent)
  8071. return;
  8072. if (is_cgroup_event(event))
  8073. atomic_inc(&per_cpu(perf_cgroup_events, cpu));
  8074. }
  8075. /* Freq events need the tick to stay alive (see perf_event_task_tick). */
  8076. static void account_freq_event_nohz(void)
  8077. {
  8078. #ifdef CONFIG_NO_HZ_FULL
  8079. /* Lock so we don't race with concurrent unaccount */
  8080. spin_lock(&nr_freq_lock);
  8081. if (atomic_inc_return(&nr_freq_events) == 1)
  8082. tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS);
  8083. spin_unlock(&nr_freq_lock);
  8084. #endif
  8085. }
  8086. static void account_freq_event(void)
  8087. {
  8088. if (tick_nohz_full_enabled())
  8089. account_freq_event_nohz();
  8090. else
  8091. atomic_inc(&nr_freq_events);
  8092. }
  8093. static void account_event(struct perf_event *event)
  8094. {
  8095. bool inc = false;
  8096. if (event->parent)
  8097. return;
  8098. if (event->attach_state & PERF_ATTACH_TASK)
  8099. inc = true;
  8100. if (event->attr.mmap || event->attr.mmap_data)
  8101. atomic_inc(&nr_mmap_events);
  8102. if (event->attr.comm)
  8103. atomic_inc(&nr_comm_events);
  8104. if (event->attr.namespaces)
  8105. atomic_inc(&nr_namespaces_events);
  8106. if (event->attr.task)
  8107. atomic_inc(&nr_task_events);
  8108. if (event->attr.freq)
  8109. account_freq_event();
  8110. if (event->attr.context_switch) {
  8111. atomic_inc(&nr_switch_events);
  8112. inc = true;
  8113. }
  8114. if (has_branch_stack(event))
  8115. inc = true;
  8116. if (is_cgroup_event(event))
  8117. inc = true;
  8118. if (inc) {
  8119. /*
  8120. * We need the mutex here because static_branch_enable()
  8121. * must complete *before* the perf_sched_count increment
  8122. * becomes visible.
  8123. */
  8124. if (atomic_inc_not_zero(&perf_sched_count))
  8125. goto enabled;
  8126. mutex_lock(&perf_sched_mutex);
  8127. if (!atomic_read(&perf_sched_count)) {
  8128. static_branch_enable(&perf_sched_events);
  8129. /*
  8130. * Guarantee that all CPUs observe they key change and
  8131. * call the perf scheduling hooks before proceeding to
  8132. * install events that need them.
  8133. */
  8134. synchronize_sched();
  8135. }
  8136. /*
  8137. * Now that we have waited for the sync_sched(), allow further
  8138. * increments to by-pass the mutex.
  8139. */
  8140. atomic_inc(&perf_sched_count);
  8141. mutex_unlock(&perf_sched_mutex);
  8142. }
  8143. enabled:
  8144. account_event_cpu(event, event->cpu);
  8145. account_pmu_sb_event(event);
  8146. }
  8147. /*
  8148. * Allocate and initialize an event structure
  8149. */
  8150. static struct perf_event *
  8151. perf_event_alloc(struct perf_event_attr *attr, int cpu,
  8152. struct task_struct *task,
  8153. struct perf_event *group_leader,
  8154. struct perf_event *parent_event,
  8155. perf_overflow_handler_t overflow_handler,
  8156. void *context, int cgroup_fd)
  8157. {
  8158. struct pmu *pmu;
  8159. struct perf_event *event;
  8160. struct hw_perf_event *hwc;
  8161. long err = -EINVAL;
  8162. if ((unsigned)cpu >= nr_cpu_ids) {
  8163. if (!task || cpu != -1)
  8164. return ERR_PTR(-EINVAL);
  8165. }
  8166. event = kzalloc(sizeof(*event), GFP_KERNEL);
  8167. if (!event)
  8168. return ERR_PTR(-ENOMEM);
  8169. /*
  8170. * Single events are their own group leaders, with an
  8171. * empty sibling list:
  8172. */
  8173. if (!group_leader)
  8174. group_leader = event;
  8175. mutex_init(&event->child_mutex);
  8176. INIT_LIST_HEAD(&event->child_list);
  8177. INIT_LIST_HEAD(&event->event_entry);
  8178. INIT_LIST_HEAD(&event->sibling_list);
  8179. INIT_LIST_HEAD(&event->active_list);
  8180. init_event_group(event);
  8181. INIT_LIST_HEAD(&event->rb_entry);
  8182. INIT_LIST_HEAD(&event->active_entry);
  8183. INIT_LIST_HEAD(&event->addr_filters.list);
  8184. INIT_HLIST_NODE(&event->hlist_entry);
  8185. init_waitqueue_head(&event->waitq);
  8186. init_irq_work(&event->pending, perf_pending_event);
  8187. mutex_init(&event->mmap_mutex);
  8188. raw_spin_lock_init(&event->addr_filters.lock);
  8189. atomic_long_set(&event->refcount, 1);
  8190. event->cpu = cpu;
  8191. event->attr = *attr;
  8192. event->group_leader = group_leader;
  8193. event->pmu = NULL;
  8194. event->oncpu = -1;
  8195. event->parent = parent_event;
  8196. event->ns = get_pid_ns(task_active_pid_ns(current));
  8197. event->id = atomic64_inc_return(&perf_event_id);
  8198. event->state = PERF_EVENT_STATE_INACTIVE;
  8199. if (task) {
  8200. event->attach_state = PERF_ATTACH_TASK;
  8201. /*
  8202. * XXX pmu::event_init needs to know what task to account to
  8203. * and we cannot use the ctx information because we need the
  8204. * pmu before we get a ctx.
  8205. */
  8206. get_task_struct(task);
  8207. event->hw.target = task;
  8208. }
  8209. event->clock = &local_clock;
  8210. if (parent_event)
  8211. event->clock = parent_event->clock;
  8212. if (!overflow_handler && parent_event) {
  8213. overflow_handler = parent_event->overflow_handler;
  8214. context = parent_event->overflow_handler_context;
  8215. #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING)
  8216. if (overflow_handler == bpf_overflow_handler) {
  8217. struct bpf_prog *prog = bpf_prog_inc(parent_event->prog);
  8218. if (IS_ERR(prog)) {
  8219. err = PTR_ERR(prog);
  8220. goto err_ns;
  8221. }
  8222. event->prog = prog;
  8223. event->orig_overflow_handler =
  8224. parent_event->orig_overflow_handler;
  8225. }
  8226. #endif
  8227. }
  8228. if (overflow_handler) {
  8229. event->overflow_handler = overflow_handler;
  8230. event->overflow_handler_context = context;
  8231. } else if (is_write_backward(event)){
  8232. event->overflow_handler = perf_event_output_backward;
  8233. event->overflow_handler_context = NULL;
  8234. } else {
  8235. event->overflow_handler = perf_event_output_forward;
  8236. event->overflow_handler_context = NULL;
  8237. }
  8238. perf_event__state_init(event);
  8239. pmu = NULL;
  8240. hwc = &event->hw;
  8241. hwc->sample_period = attr->sample_period;
  8242. if (attr->freq && attr->sample_freq)
  8243. hwc->sample_period = 1;
  8244. hwc->last_period = hwc->sample_period;
  8245. local64_set(&hwc->period_left, hwc->sample_period);
  8246. /*
  8247. * We currently do not support PERF_SAMPLE_READ on inherited events.
  8248. * See perf_output_read().
  8249. */
  8250. if (attr->inherit && (attr->sample_type & PERF_SAMPLE_READ))
  8251. goto err_ns;
  8252. if (!has_branch_stack(event))
  8253. event->attr.branch_sample_type = 0;
  8254. if (cgroup_fd != -1) {
  8255. err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
  8256. if (err)
  8257. goto err_ns;
  8258. }
  8259. pmu = perf_init_event(event);
  8260. if (IS_ERR(pmu)) {
  8261. err = PTR_ERR(pmu);
  8262. goto err_ns;
  8263. }
  8264. err = exclusive_event_init(event);
  8265. if (err)
  8266. goto err_pmu;
  8267. if (has_addr_filter(event)) {
  8268. event->addr_filters_offs = kcalloc(pmu->nr_addr_filters,
  8269. sizeof(unsigned long),
  8270. GFP_KERNEL);
  8271. if (!event->addr_filters_offs) {
  8272. err = -ENOMEM;
  8273. goto err_per_task;
  8274. }
  8275. /* force hw sync on the address filters */
  8276. event->addr_filters_gen = 1;
  8277. }
  8278. if (!event->parent) {
  8279. if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
  8280. err = get_callchain_buffers(attr->sample_max_stack);
  8281. if (err)
  8282. goto err_addr_filters;
  8283. }
  8284. }
  8285. /* symmetric to unaccount_event() in _free_event() */
  8286. account_event(event);
  8287. return event;
  8288. err_addr_filters:
  8289. kfree(event->addr_filters_offs);
  8290. err_per_task:
  8291. exclusive_event_destroy(event);
  8292. err_pmu:
  8293. if (event->destroy)
  8294. event->destroy(event);
  8295. module_put(pmu->module);
  8296. err_ns:
  8297. if (is_cgroup_event(event))
  8298. perf_detach_cgroup(event);
  8299. if (event->ns)
  8300. put_pid_ns(event->ns);
  8301. if (event->hw.target)
  8302. put_task_struct(event->hw.target);
  8303. kfree(event);
  8304. return ERR_PTR(err);
  8305. }
  8306. static int perf_copy_attr(struct perf_event_attr __user *uattr,
  8307. struct perf_event_attr *attr)
  8308. {
  8309. u32 size;
  8310. int ret;
  8311. if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
  8312. return -EFAULT;
  8313. /*
  8314. * zero the full structure, so that a short copy will be nice.
  8315. */
  8316. memset(attr, 0, sizeof(*attr));
  8317. ret = get_user(size, &uattr->size);
  8318. if (ret)
  8319. return ret;
  8320. if (size > PAGE_SIZE) /* silly large */
  8321. goto err_size;
  8322. if (!size) /* abi compat */
  8323. size = PERF_ATTR_SIZE_VER0;
  8324. if (size < PERF_ATTR_SIZE_VER0)
  8325. goto err_size;
  8326. /*
  8327. * If we're handed a bigger struct than we know of,
  8328. * ensure all the unknown bits are 0 - i.e. new
  8329. * user-space does not rely on any kernel feature
  8330. * extensions we dont know about yet.
  8331. */
  8332. if (size > sizeof(*attr)) {
  8333. unsigned char __user *addr;
  8334. unsigned char __user *end;
  8335. unsigned char val;
  8336. addr = (void __user *)uattr + sizeof(*attr);
  8337. end = (void __user *)uattr + size;
  8338. for (; addr < end; addr++) {
  8339. ret = get_user(val, addr);
  8340. if (ret)
  8341. return ret;
  8342. if (val)
  8343. goto err_size;
  8344. }
  8345. size = sizeof(*attr);
  8346. }
  8347. ret = copy_from_user(attr, uattr, size);
  8348. if (ret)
  8349. return -EFAULT;
  8350. attr->size = size;
  8351. if (attr->__reserved_1)
  8352. return -EINVAL;
  8353. if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
  8354. return -EINVAL;
  8355. if (attr->read_format & ~(PERF_FORMAT_MAX-1))
  8356. return -EINVAL;
  8357. if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
  8358. u64 mask = attr->branch_sample_type;
  8359. /* only using defined bits */
  8360. if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
  8361. return -EINVAL;
  8362. /* at least one branch bit must be set */
  8363. if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
  8364. return -EINVAL;
  8365. /* propagate priv level, when not set for branch */
  8366. if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
  8367. /* exclude_kernel checked on syscall entry */
  8368. if (!attr->exclude_kernel)
  8369. mask |= PERF_SAMPLE_BRANCH_KERNEL;
  8370. if (!attr->exclude_user)
  8371. mask |= PERF_SAMPLE_BRANCH_USER;
  8372. if (!attr->exclude_hv)
  8373. mask |= PERF_SAMPLE_BRANCH_HV;
  8374. /*
  8375. * adjust user setting (for HW filter setup)
  8376. */
  8377. attr->branch_sample_type = mask;
  8378. }
  8379. /* privileged levels capture (kernel, hv): check permissions */
  8380. if ((mask & PERF_SAMPLE_BRANCH_PERM_PLM)
  8381. && perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
  8382. return -EACCES;
  8383. }
  8384. if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
  8385. ret = perf_reg_validate(attr->sample_regs_user);
  8386. if (ret)
  8387. return ret;
  8388. }
  8389. if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
  8390. if (!arch_perf_have_user_stack_dump())
  8391. return -ENOSYS;
  8392. /*
  8393. * We have __u32 type for the size, but so far
  8394. * we can only use __u16 as maximum due to the
  8395. * __u16 sample size limit.
  8396. */
  8397. if (attr->sample_stack_user >= USHRT_MAX)
  8398. return -EINVAL;
  8399. else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
  8400. return -EINVAL;
  8401. }
  8402. if (!attr->sample_max_stack)
  8403. attr->sample_max_stack = sysctl_perf_event_max_stack;
  8404. if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
  8405. ret = perf_reg_validate(attr->sample_regs_intr);
  8406. out:
  8407. return ret;
  8408. err_size:
  8409. put_user(sizeof(*attr), &uattr->size);
  8410. ret = -E2BIG;
  8411. goto out;
  8412. }
  8413. static int
  8414. perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
  8415. {
  8416. struct ring_buffer *rb = NULL;
  8417. int ret = -EINVAL;
  8418. if (!output_event)
  8419. goto set;
  8420. /* don't allow circular references */
  8421. if (event == output_event)
  8422. goto out;
  8423. /*
  8424. * Don't allow cross-cpu buffers
  8425. */
  8426. if (output_event->cpu != event->cpu)
  8427. goto out;
  8428. /*
  8429. * If its not a per-cpu rb, it must be the same task.
  8430. */
  8431. if (output_event->cpu == -1 && output_event->ctx != event->ctx)
  8432. goto out;
  8433. /*
  8434. * Mixing clocks in the same buffer is trouble you don't need.
  8435. */
  8436. if (output_event->clock != event->clock)
  8437. goto out;
  8438. /*
  8439. * Either writing ring buffer from beginning or from end.
  8440. * Mixing is not allowed.
  8441. */
  8442. if (is_write_backward(output_event) != is_write_backward(event))
  8443. goto out;
  8444. /*
  8445. * If both events generate aux data, they must be on the same PMU
  8446. */
  8447. if (has_aux(event) && has_aux(output_event) &&
  8448. event->pmu != output_event->pmu)
  8449. goto out;
  8450. set:
  8451. mutex_lock(&event->mmap_mutex);
  8452. /* Can't redirect output if we've got an active mmap() */
  8453. if (atomic_read(&event->mmap_count))
  8454. goto unlock;
  8455. if (output_event) {
  8456. /* get the rb we want to redirect to */
  8457. rb = ring_buffer_get(output_event);
  8458. if (!rb)
  8459. goto unlock;
  8460. }
  8461. ring_buffer_attach(event, rb);
  8462. ret = 0;
  8463. unlock:
  8464. mutex_unlock(&event->mmap_mutex);
  8465. out:
  8466. return ret;
  8467. }
  8468. static void mutex_lock_double(struct mutex *a, struct mutex *b)
  8469. {
  8470. if (b < a)
  8471. swap(a, b);
  8472. mutex_lock(a);
  8473. mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
  8474. }
  8475. static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
  8476. {
  8477. bool nmi_safe = false;
  8478. switch (clk_id) {
  8479. case CLOCK_MONOTONIC:
  8480. event->clock = &ktime_get_mono_fast_ns;
  8481. nmi_safe = true;
  8482. break;
  8483. case CLOCK_MONOTONIC_RAW:
  8484. event->clock = &ktime_get_raw_fast_ns;
  8485. nmi_safe = true;
  8486. break;
  8487. case CLOCK_REALTIME:
  8488. event->clock = &ktime_get_real_ns;
  8489. break;
  8490. case CLOCK_BOOTTIME:
  8491. event->clock = &ktime_get_boot_ns;
  8492. break;
  8493. case CLOCK_TAI:
  8494. event->clock = &ktime_get_tai_ns;
  8495. break;
  8496. default:
  8497. return -EINVAL;
  8498. }
  8499. if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
  8500. return -EINVAL;
  8501. return 0;
  8502. }
  8503. /*
  8504. * Variation on perf_event_ctx_lock_nested(), except we take two context
  8505. * mutexes.
  8506. */
  8507. static struct perf_event_context *
  8508. __perf_event_ctx_lock_double(struct perf_event *group_leader,
  8509. struct perf_event_context *ctx)
  8510. {
  8511. struct perf_event_context *gctx;
  8512. again:
  8513. rcu_read_lock();
  8514. gctx = READ_ONCE(group_leader->ctx);
  8515. if (!atomic_inc_not_zero(&gctx->refcount)) {
  8516. rcu_read_unlock();
  8517. goto again;
  8518. }
  8519. rcu_read_unlock();
  8520. mutex_lock_double(&gctx->mutex, &ctx->mutex);
  8521. if (group_leader->ctx != gctx) {
  8522. mutex_unlock(&ctx->mutex);
  8523. mutex_unlock(&gctx->mutex);
  8524. put_ctx(gctx);
  8525. goto again;
  8526. }
  8527. return gctx;
  8528. }
  8529. /**
  8530. * sys_perf_event_open - open a performance event, associate it to a task/cpu
  8531. *
  8532. * @attr_uptr: event_id type attributes for monitoring/sampling
  8533. * @pid: target pid
  8534. * @cpu: target cpu
  8535. * @group_fd: group leader event fd
  8536. */
  8537. SYSCALL_DEFINE5(perf_event_open,
  8538. struct perf_event_attr __user *, attr_uptr,
  8539. pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
  8540. {
  8541. struct perf_event *group_leader = NULL, *output_event = NULL;
  8542. struct perf_event *event, *sibling;
  8543. struct perf_event_attr attr;
  8544. struct perf_event_context *ctx, *uninitialized_var(gctx);
  8545. struct file *event_file = NULL;
  8546. struct fd group = {NULL, 0};
  8547. struct task_struct *task = NULL;
  8548. struct pmu *pmu;
  8549. int event_fd;
  8550. int move_group = 0;
  8551. int err;
  8552. int f_flags = O_RDWR;
  8553. int cgroup_fd = -1;
  8554. /* for future expandability... */
  8555. if (flags & ~PERF_FLAG_ALL)
  8556. return -EINVAL;
  8557. err = perf_copy_attr(attr_uptr, &attr);
  8558. if (err)
  8559. return err;
  8560. if (!attr.exclude_kernel) {
  8561. if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
  8562. return -EACCES;
  8563. }
  8564. if (attr.namespaces) {
  8565. if (!capable(CAP_SYS_ADMIN))
  8566. return -EACCES;
  8567. }
  8568. if (attr.freq) {
  8569. if (attr.sample_freq > sysctl_perf_event_sample_rate)
  8570. return -EINVAL;
  8571. } else {
  8572. if (attr.sample_period & (1ULL << 63))
  8573. return -EINVAL;
  8574. }
  8575. /* Only privileged users can get physical addresses */
  8576. if ((attr.sample_type & PERF_SAMPLE_PHYS_ADDR) &&
  8577. perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
  8578. return -EACCES;
  8579. /*
  8580. * In cgroup mode, the pid argument is used to pass the fd
  8581. * opened to the cgroup directory in cgroupfs. The cpu argument
  8582. * designates the cpu on which to monitor threads from that
  8583. * cgroup.
  8584. */
  8585. if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
  8586. return -EINVAL;
  8587. if (flags & PERF_FLAG_FD_CLOEXEC)
  8588. f_flags |= O_CLOEXEC;
  8589. event_fd = get_unused_fd_flags(f_flags);
  8590. if (event_fd < 0)
  8591. return event_fd;
  8592. if (group_fd != -1) {
  8593. err = perf_fget_light(group_fd, &group);
  8594. if (err)
  8595. goto err_fd;
  8596. group_leader = group.file->private_data;
  8597. if (flags & PERF_FLAG_FD_OUTPUT)
  8598. output_event = group_leader;
  8599. if (flags & PERF_FLAG_FD_NO_GROUP)
  8600. group_leader = NULL;
  8601. }
  8602. if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
  8603. task = find_lively_task_by_vpid(pid);
  8604. if (IS_ERR(task)) {
  8605. err = PTR_ERR(task);
  8606. goto err_group_fd;
  8607. }
  8608. }
  8609. if (task && group_leader &&
  8610. group_leader->attr.inherit != attr.inherit) {
  8611. err = -EINVAL;
  8612. goto err_task;
  8613. }
  8614. if (task) {
  8615. err = mutex_lock_interruptible(&task->signal->cred_guard_mutex);
  8616. if (err)
  8617. goto err_task;
  8618. /*
  8619. * Reuse ptrace permission checks for now.
  8620. *
  8621. * We must hold cred_guard_mutex across this and any potential
  8622. * perf_install_in_context() call for this new event to
  8623. * serialize against exec() altering our credentials (and the
  8624. * perf_event_exit_task() that could imply).
  8625. */
  8626. err = -EACCES;
  8627. if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS))
  8628. goto err_cred;
  8629. }
  8630. if (flags & PERF_FLAG_PID_CGROUP)
  8631. cgroup_fd = pid;
  8632. event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
  8633. NULL, NULL, cgroup_fd);
  8634. if (IS_ERR(event)) {
  8635. err = PTR_ERR(event);
  8636. goto err_cred;
  8637. }
  8638. if (is_sampling_event(event)) {
  8639. if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
  8640. err = -EOPNOTSUPP;
  8641. goto err_alloc;
  8642. }
  8643. }
  8644. /*
  8645. * Special case software events and allow them to be part of
  8646. * any hardware group.
  8647. */
  8648. pmu = event->pmu;
  8649. if (attr.use_clockid) {
  8650. err = perf_event_set_clock(event, attr.clockid);
  8651. if (err)
  8652. goto err_alloc;
  8653. }
  8654. if (pmu->task_ctx_nr == perf_sw_context)
  8655. event->event_caps |= PERF_EV_CAP_SOFTWARE;
  8656. if (group_leader) {
  8657. if (is_software_event(event) &&
  8658. !in_software_context(group_leader)) {
  8659. /*
  8660. * If the event is a sw event, but the group_leader
  8661. * is on hw context.
  8662. *
  8663. * Allow the addition of software events to hw
  8664. * groups, this is safe because software events
  8665. * never fail to schedule.
  8666. */
  8667. pmu = group_leader->ctx->pmu;
  8668. } else if (!is_software_event(event) &&
  8669. is_software_event(group_leader) &&
  8670. (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
  8671. /*
  8672. * In case the group is a pure software group, and we
  8673. * try to add a hardware event, move the whole group to
  8674. * the hardware context.
  8675. */
  8676. move_group = 1;
  8677. }
  8678. }
  8679. /*
  8680. * Get the target context (task or percpu):
  8681. */
  8682. ctx = find_get_context(pmu, task, event);
  8683. if (IS_ERR(ctx)) {
  8684. err = PTR_ERR(ctx);
  8685. goto err_alloc;
  8686. }
  8687. if ((pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE) && group_leader) {
  8688. err = -EBUSY;
  8689. goto err_context;
  8690. }
  8691. /*
  8692. * Look up the group leader (we will attach this event to it):
  8693. */
  8694. if (group_leader) {
  8695. err = -EINVAL;
  8696. /*
  8697. * Do not allow a recursive hierarchy (this new sibling
  8698. * becoming part of another group-sibling):
  8699. */
  8700. if (group_leader->group_leader != group_leader)
  8701. goto err_context;
  8702. /* All events in a group should have the same clock */
  8703. if (group_leader->clock != event->clock)
  8704. goto err_context;
  8705. /*
  8706. * Make sure we're both events for the same CPU;
  8707. * grouping events for different CPUs is broken; since
  8708. * you can never concurrently schedule them anyhow.
  8709. */
  8710. if (group_leader->cpu != event->cpu)
  8711. goto err_context;
  8712. /*
  8713. * Make sure we're both on the same task, or both
  8714. * per-CPU events.
  8715. */
  8716. if (group_leader->ctx->task != ctx->task)
  8717. goto err_context;
  8718. /*
  8719. * Do not allow to attach to a group in a different task
  8720. * or CPU context. If we're moving SW events, we'll fix
  8721. * this up later, so allow that.
  8722. */
  8723. if (!move_group && group_leader->ctx != ctx)
  8724. goto err_context;
  8725. /*
  8726. * Only a group leader can be exclusive or pinned
  8727. */
  8728. if (attr.exclusive || attr.pinned)
  8729. goto err_context;
  8730. }
  8731. if (output_event) {
  8732. err = perf_event_set_output(event, output_event);
  8733. if (err)
  8734. goto err_context;
  8735. }
  8736. event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
  8737. f_flags);
  8738. if (IS_ERR(event_file)) {
  8739. err = PTR_ERR(event_file);
  8740. event_file = NULL;
  8741. goto err_context;
  8742. }
  8743. if (move_group) {
  8744. gctx = __perf_event_ctx_lock_double(group_leader, ctx);
  8745. if (gctx->task == TASK_TOMBSTONE) {
  8746. err = -ESRCH;
  8747. goto err_locked;
  8748. }
  8749. /*
  8750. * Check if we raced against another sys_perf_event_open() call
  8751. * moving the software group underneath us.
  8752. */
  8753. if (!(group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
  8754. /*
  8755. * If someone moved the group out from under us, check
  8756. * if this new event wound up on the same ctx, if so
  8757. * its the regular !move_group case, otherwise fail.
  8758. */
  8759. if (gctx != ctx) {
  8760. err = -EINVAL;
  8761. goto err_locked;
  8762. } else {
  8763. perf_event_ctx_unlock(group_leader, gctx);
  8764. move_group = 0;
  8765. }
  8766. }
  8767. } else {
  8768. mutex_lock(&ctx->mutex);
  8769. }
  8770. if (ctx->task == TASK_TOMBSTONE) {
  8771. err = -ESRCH;
  8772. goto err_locked;
  8773. }
  8774. if (!perf_event_validate_size(event)) {
  8775. err = -E2BIG;
  8776. goto err_locked;
  8777. }
  8778. if (!task) {
  8779. /*
  8780. * Check if the @cpu we're creating an event for is online.
  8781. *
  8782. * We use the perf_cpu_context::ctx::mutex to serialize against
  8783. * the hotplug notifiers. See perf_event_{init,exit}_cpu().
  8784. */
  8785. struct perf_cpu_context *cpuctx =
  8786. container_of(ctx, struct perf_cpu_context, ctx);
  8787. if (!cpuctx->online) {
  8788. err = -ENODEV;
  8789. goto err_locked;
  8790. }
  8791. }
  8792. /*
  8793. * Must be under the same ctx::mutex as perf_install_in_context(),
  8794. * because we need to serialize with concurrent event creation.
  8795. */
  8796. if (!exclusive_event_installable(event, ctx)) {
  8797. /* exclusive and group stuff are assumed mutually exclusive */
  8798. WARN_ON_ONCE(move_group);
  8799. err = -EBUSY;
  8800. goto err_locked;
  8801. }
  8802. WARN_ON_ONCE(ctx->parent_ctx);
  8803. /*
  8804. * This is the point on no return; we cannot fail hereafter. This is
  8805. * where we start modifying current state.
  8806. */
  8807. if (move_group) {
  8808. /*
  8809. * See perf_event_ctx_lock() for comments on the details
  8810. * of swizzling perf_event::ctx.
  8811. */
  8812. perf_remove_from_context(group_leader, 0);
  8813. put_ctx(gctx);
  8814. for_each_sibling_event(sibling, group_leader) {
  8815. perf_remove_from_context(sibling, 0);
  8816. put_ctx(gctx);
  8817. }
  8818. /*
  8819. * Wait for everybody to stop referencing the events through
  8820. * the old lists, before installing it on new lists.
  8821. */
  8822. synchronize_rcu();
  8823. /*
  8824. * Install the group siblings before the group leader.
  8825. *
  8826. * Because a group leader will try and install the entire group
  8827. * (through the sibling list, which is still in-tact), we can
  8828. * end up with siblings installed in the wrong context.
  8829. *
  8830. * By installing siblings first we NO-OP because they're not
  8831. * reachable through the group lists.
  8832. */
  8833. for_each_sibling_event(sibling, group_leader) {
  8834. perf_event__state_init(sibling);
  8835. perf_install_in_context(ctx, sibling, sibling->cpu);
  8836. get_ctx(ctx);
  8837. }
  8838. /*
  8839. * Removing from the context ends up with disabled
  8840. * event. What we want here is event in the initial
  8841. * startup state, ready to be add into new context.
  8842. */
  8843. perf_event__state_init(group_leader);
  8844. perf_install_in_context(ctx, group_leader, group_leader->cpu);
  8845. get_ctx(ctx);
  8846. }
  8847. /*
  8848. * Precalculate sample_data sizes; do while holding ctx::mutex such
  8849. * that we're serialized against further additions and before
  8850. * perf_install_in_context() which is the point the event is active and
  8851. * can use these values.
  8852. */
  8853. perf_event__header_size(event);
  8854. perf_event__id_header_size(event);
  8855. event->owner = current;
  8856. perf_install_in_context(ctx, event, event->cpu);
  8857. perf_unpin_context(ctx);
  8858. if (move_group)
  8859. perf_event_ctx_unlock(group_leader, gctx);
  8860. mutex_unlock(&ctx->mutex);
  8861. if (task) {
  8862. mutex_unlock(&task->signal->cred_guard_mutex);
  8863. put_task_struct(task);
  8864. }
  8865. mutex_lock(&current->perf_event_mutex);
  8866. list_add_tail(&event->owner_entry, &current->perf_event_list);
  8867. mutex_unlock(&current->perf_event_mutex);
  8868. /*
  8869. * Drop the reference on the group_event after placing the
  8870. * new event on the sibling_list. This ensures destruction
  8871. * of the group leader will find the pointer to itself in
  8872. * perf_group_detach().
  8873. */
  8874. fdput(group);
  8875. fd_install(event_fd, event_file);
  8876. return event_fd;
  8877. err_locked:
  8878. if (move_group)
  8879. perf_event_ctx_unlock(group_leader, gctx);
  8880. mutex_unlock(&ctx->mutex);
  8881. /* err_file: */
  8882. fput(event_file);
  8883. err_context:
  8884. perf_unpin_context(ctx);
  8885. put_ctx(ctx);
  8886. err_alloc:
  8887. /*
  8888. * If event_file is set, the fput() above will have called ->release()
  8889. * and that will take care of freeing the event.
  8890. */
  8891. if (!event_file)
  8892. free_event(event);
  8893. err_cred:
  8894. if (task)
  8895. mutex_unlock(&task->signal->cred_guard_mutex);
  8896. err_task:
  8897. if (task)
  8898. put_task_struct(task);
  8899. err_group_fd:
  8900. fdput(group);
  8901. err_fd:
  8902. put_unused_fd(event_fd);
  8903. return err;
  8904. }
  8905. /**
  8906. * perf_event_create_kernel_counter
  8907. *
  8908. * @attr: attributes of the counter to create
  8909. * @cpu: cpu in which the counter is bound
  8910. * @task: task to profile (NULL for percpu)
  8911. */
  8912. struct perf_event *
  8913. perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
  8914. struct task_struct *task,
  8915. perf_overflow_handler_t overflow_handler,
  8916. void *context)
  8917. {
  8918. struct perf_event_context *ctx;
  8919. struct perf_event *event;
  8920. int err;
  8921. /*
  8922. * Get the target context (task or percpu):
  8923. */
  8924. event = perf_event_alloc(attr, cpu, task, NULL, NULL,
  8925. overflow_handler, context, -1);
  8926. if (IS_ERR(event)) {
  8927. err = PTR_ERR(event);
  8928. goto err;
  8929. }
  8930. /* Mark owner so we could distinguish it from user events. */
  8931. event->owner = TASK_TOMBSTONE;
  8932. ctx = find_get_context(event->pmu, task, event);
  8933. if (IS_ERR(ctx)) {
  8934. err = PTR_ERR(ctx);
  8935. goto err_free;
  8936. }
  8937. WARN_ON_ONCE(ctx->parent_ctx);
  8938. mutex_lock(&ctx->mutex);
  8939. if (ctx->task == TASK_TOMBSTONE) {
  8940. err = -ESRCH;
  8941. goto err_unlock;
  8942. }
  8943. if (!task) {
  8944. /*
  8945. * Check if the @cpu we're creating an event for is online.
  8946. *
  8947. * We use the perf_cpu_context::ctx::mutex to serialize against
  8948. * the hotplug notifiers. See perf_event_{init,exit}_cpu().
  8949. */
  8950. struct perf_cpu_context *cpuctx =
  8951. container_of(ctx, struct perf_cpu_context, ctx);
  8952. if (!cpuctx->online) {
  8953. err = -ENODEV;
  8954. goto err_unlock;
  8955. }
  8956. }
  8957. if (!exclusive_event_installable(event, ctx)) {
  8958. err = -EBUSY;
  8959. goto err_unlock;
  8960. }
  8961. perf_install_in_context(ctx, event, cpu);
  8962. perf_unpin_context(ctx);
  8963. mutex_unlock(&ctx->mutex);
  8964. return event;
  8965. err_unlock:
  8966. mutex_unlock(&ctx->mutex);
  8967. perf_unpin_context(ctx);
  8968. put_ctx(ctx);
  8969. err_free:
  8970. free_event(event);
  8971. err:
  8972. return ERR_PTR(err);
  8973. }
  8974. EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
  8975. void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
  8976. {
  8977. struct perf_event_context *src_ctx;
  8978. struct perf_event_context *dst_ctx;
  8979. struct perf_event *event, *tmp;
  8980. LIST_HEAD(events);
  8981. src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
  8982. dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
  8983. /*
  8984. * See perf_event_ctx_lock() for comments on the details
  8985. * of swizzling perf_event::ctx.
  8986. */
  8987. mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
  8988. list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
  8989. event_entry) {
  8990. perf_remove_from_context(event, 0);
  8991. unaccount_event_cpu(event, src_cpu);
  8992. put_ctx(src_ctx);
  8993. list_add(&event->migrate_entry, &events);
  8994. }
  8995. /*
  8996. * Wait for the events to quiesce before re-instating them.
  8997. */
  8998. synchronize_rcu();
  8999. /*
  9000. * Re-instate events in 2 passes.
  9001. *
  9002. * Skip over group leaders and only install siblings on this first
  9003. * pass, siblings will not get enabled without a leader, however a
  9004. * leader will enable its siblings, even if those are still on the old
  9005. * context.
  9006. */
  9007. list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
  9008. if (event->group_leader == event)
  9009. continue;
  9010. list_del(&event->migrate_entry);
  9011. if (event->state >= PERF_EVENT_STATE_OFF)
  9012. event->state = PERF_EVENT_STATE_INACTIVE;
  9013. account_event_cpu(event, dst_cpu);
  9014. perf_install_in_context(dst_ctx, event, dst_cpu);
  9015. get_ctx(dst_ctx);
  9016. }
  9017. /*
  9018. * Once all the siblings are setup properly, install the group leaders
  9019. * to make it go.
  9020. */
  9021. list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
  9022. list_del(&event->migrate_entry);
  9023. if (event->state >= PERF_EVENT_STATE_OFF)
  9024. event->state = PERF_EVENT_STATE_INACTIVE;
  9025. account_event_cpu(event, dst_cpu);
  9026. perf_install_in_context(dst_ctx, event, dst_cpu);
  9027. get_ctx(dst_ctx);
  9028. }
  9029. mutex_unlock(&dst_ctx->mutex);
  9030. mutex_unlock(&src_ctx->mutex);
  9031. }
  9032. EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
  9033. static void sync_child_event(struct perf_event *child_event,
  9034. struct task_struct *child)
  9035. {
  9036. struct perf_event *parent_event = child_event->parent;
  9037. u64 child_val;
  9038. if (child_event->attr.inherit_stat)
  9039. perf_event_read_event(child_event, child);
  9040. child_val = perf_event_count(child_event);
  9041. /*
  9042. * Add back the child's count to the parent's count:
  9043. */
  9044. atomic64_add(child_val, &parent_event->child_count);
  9045. atomic64_add(child_event->total_time_enabled,
  9046. &parent_event->child_total_time_enabled);
  9047. atomic64_add(child_event->total_time_running,
  9048. &parent_event->child_total_time_running);
  9049. }
  9050. static void
  9051. perf_event_exit_event(struct perf_event *child_event,
  9052. struct perf_event_context *child_ctx,
  9053. struct task_struct *child)
  9054. {
  9055. struct perf_event *parent_event = child_event->parent;
  9056. /*
  9057. * Do not destroy the 'original' grouping; because of the context
  9058. * switch optimization the original events could've ended up in a
  9059. * random child task.
  9060. *
  9061. * If we were to destroy the original group, all group related
  9062. * operations would cease to function properly after this random
  9063. * child dies.
  9064. *
  9065. * Do destroy all inherited groups, we don't care about those
  9066. * and being thorough is better.
  9067. */
  9068. raw_spin_lock_irq(&child_ctx->lock);
  9069. WARN_ON_ONCE(child_ctx->is_active);
  9070. if (parent_event)
  9071. perf_group_detach(child_event);
  9072. list_del_event(child_event, child_ctx);
  9073. perf_event_set_state(child_event, PERF_EVENT_STATE_EXIT); /* is_event_hup() */
  9074. raw_spin_unlock_irq(&child_ctx->lock);
  9075. /*
  9076. * Parent events are governed by their filedesc, retain them.
  9077. */
  9078. if (!parent_event) {
  9079. perf_event_wakeup(child_event);
  9080. return;
  9081. }
  9082. /*
  9083. * Child events can be cleaned up.
  9084. */
  9085. sync_child_event(child_event, child);
  9086. /*
  9087. * Remove this event from the parent's list
  9088. */
  9089. WARN_ON_ONCE(parent_event->ctx->parent_ctx);
  9090. mutex_lock(&parent_event->child_mutex);
  9091. list_del_init(&child_event->child_list);
  9092. mutex_unlock(&parent_event->child_mutex);
  9093. /*
  9094. * Kick perf_poll() for is_event_hup().
  9095. */
  9096. perf_event_wakeup(parent_event);
  9097. free_event(child_event);
  9098. put_event(parent_event);
  9099. }
  9100. static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
  9101. {
  9102. struct perf_event_context *child_ctx, *clone_ctx = NULL;
  9103. struct perf_event *child_event, *next;
  9104. WARN_ON_ONCE(child != current);
  9105. child_ctx = perf_pin_task_context(child, ctxn);
  9106. if (!child_ctx)
  9107. return;
  9108. /*
  9109. * In order to reduce the amount of tricky in ctx tear-down, we hold
  9110. * ctx::mutex over the entire thing. This serializes against almost
  9111. * everything that wants to access the ctx.
  9112. *
  9113. * The exception is sys_perf_event_open() /
  9114. * perf_event_create_kernel_count() which does find_get_context()
  9115. * without ctx::mutex (it cannot because of the move_group double mutex
  9116. * lock thing). See the comments in perf_install_in_context().
  9117. */
  9118. mutex_lock(&child_ctx->mutex);
  9119. /*
  9120. * In a single ctx::lock section, de-schedule the events and detach the
  9121. * context from the task such that we cannot ever get it scheduled back
  9122. * in.
  9123. */
  9124. raw_spin_lock_irq(&child_ctx->lock);
  9125. task_ctx_sched_out(__get_cpu_context(child_ctx), child_ctx, EVENT_ALL);
  9126. /*
  9127. * Now that the context is inactive, destroy the task <-> ctx relation
  9128. * and mark the context dead.
  9129. */
  9130. RCU_INIT_POINTER(child->perf_event_ctxp[ctxn], NULL);
  9131. put_ctx(child_ctx); /* cannot be last */
  9132. WRITE_ONCE(child_ctx->task, TASK_TOMBSTONE);
  9133. put_task_struct(current); /* cannot be last */
  9134. clone_ctx = unclone_ctx(child_ctx);
  9135. raw_spin_unlock_irq(&child_ctx->lock);
  9136. if (clone_ctx)
  9137. put_ctx(clone_ctx);
  9138. /*
  9139. * Report the task dead after unscheduling the events so that we
  9140. * won't get any samples after PERF_RECORD_EXIT. We can however still
  9141. * get a few PERF_RECORD_READ events.
  9142. */
  9143. perf_event_task(child, child_ctx, 0);
  9144. list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
  9145. perf_event_exit_event(child_event, child_ctx, child);
  9146. mutex_unlock(&child_ctx->mutex);
  9147. put_ctx(child_ctx);
  9148. }
  9149. /*
  9150. * When a child task exits, feed back event values to parent events.
  9151. *
  9152. * Can be called with cred_guard_mutex held when called from
  9153. * install_exec_creds().
  9154. */
  9155. void perf_event_exit_task(struct task_struct *child)
  9156. {
  9157. struct perf_event *event, *tmp;
  9158. int ctxn;
  9159. mutex_lock(&child->perf_event_mutex);
  9160. list_for_each_entry_safe(event, tmp, &child->perf_event_list,
  9161. owner_entry) {
  9162. list_del_init(&event->owner_entry);
  9163. /*
  9164. * Ensure the list deletion is visible before we clear
  9165. * the owner, closes a race against perf_release() where
  9166. * we need to serialize on the owner->perf_event_mutex.
  9167. */
  9168. smp_store_release(&event->owner, NULL);
  9169. }
  9170. mutex_unlock(&child->perf_event_mutex);
  9171. for_each_task_context_nr(ctxn)
  9172. perf_event_exit_task_context(child, ctxn);
  9173. /*
  9174. * The perf_event_exit_task_context calls perf_event_task
  9175. * with child's task_ctx, which generates EXIT events for
  9176. * child contexts and sets child->perf_event_ctxp[] to NULL.
  9177. * At this point we need to send EXIT events to cpu contexts.
  9178. */
  9179. perf_event_task(child, NULL, 0);
  9180. }
  9181. static void perf_free_event(struct perf_event *event,
  9182. struct perf_event_context *ctx)
  9183. {
  9184. struct perf_event *parent = event->parent;
  9185. if (WARN_ON_ONCE(!parent))
  9186. return;
  9187. mutex_lock(&parent->child_mutex);
  9188. list_del_init(&event->child_list);
  9189. mutex_unlock(&parent->child_mutex);
  9190. put_event(parent);
  9191. raw_spin_lock_irq(&ctx->lock);
  9192. perf_group_detach(event);
  9193. list_del_event(event, ctx);
  9194. raw_spin_unlock_irq(&ctx->lock);
  9195. free_event(event);
  9196. }
  9197. /*
  9198. * Free an unexposed, unused context as created by inheritance by
  9199. * perf_event_init_task below, used by fork() in case of fail.
  9200. *
  9201. * Not all locks are strictly required, but take them anyway to be nice and
  9202. * help out with the lockdep assertions.
  9203. */
  9204. void perf_event_free_task(struct task_struct *task)
  9205. {
  9206. struct perf_event_context *ctx;
  9207. struct perf_event *event, *tmp;
  9208. int ctxn;
  9209. for_each_task_context_nr(ctxn) {
  9210. ctx = task->perf_event_ctxp[ctxn];
  9211. if (!ctx)
  9212. continue;
  9213. mutex_lock(&ctx->mutex);
  9214. raw_spin_lock_irq(&ctx->lock);
  9215. /*
  9216. * Destroy the task <-> ctx relation and mark the context dead.
  9217. *
  9218. * This is important because even though the task hasn't been
  9219. * exposed yet the context has been (through child_list).
  9220. */
  9221. RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], NULL);
  9222. WRITE_ONCE(ctx->task, TASK_TOMBSTONE);
  9223. put_task_struct(task); /* cannot be last */
  9224. raw_spin_unlock_irq(&ctx->lock);
  9225. list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry)
  9226. perf_free_event(event, ctx);
  9227. mutex_unlock(&ctx->mutex);
  9228. put_ctx(ctx);
  9229. }
  9230. }
  9231. void perf_event_delayed_put(struct task_struct *task)
  9232. {
  9233. int ctxn;
  9234. for_each_task_context_nr(ctxn)
  9235. WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
  9236. }
  9237. struct file *perf_event_get(unsigned int fd)
  9238. {
  9239. struct file *file;
  9240. file = fget_raw(fd);
  9241. if (!file)
  9242. return ERR_PTR(-EBADF);
  9243. if (file->f_op != &perf_fops) {
  9244. fput(file);
  9245. return ERR_PTR(-EBADF);
  9246. }
  9247. return file;
  9248. }
  9249. const struct perf_event *perf_get_event(struct file *file)
  9250. {
  9251. if (file->f_op != &perf_fops)
  9252. return ERR_PTR(-EINVAL);
  9253. return file->private_data;
  9254. }
  9255. const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
  9256. {
  9257. if (!event)
  9258. return ERR_PTR(-EINVAL);
  9259. return &event->attr;
  9260. }
  9261. /*
  9262. * Inherit an event from parent task to child task.
  9263. *
  9264. * Returns:
  9265. * - valid pointer on success
  9266. * - NULL for orphaned events
  9267. * - IS_ERR() on error
  9268. */
  9269. static struct perf_event *
  9270. inherit_event(struct perf_event *parent_event,
  9271. struct task_struct *parent,
  9272. struct perf_event_context *parent_ctx,
  9273. struct task_struct *child,
  9274. struct perf_event *group_leader,
  9275. struct perf_event_context *child_ctx)
  9276. {
  9277. enum perf_event_state parent_state = parent_event->state;
  9278. struct perf_event *child_event;
  9279. unsigned long flags;
  9280. /*
  9281. * Instead of creating recursive hierarchies of events,
  9282. * we link inherited events back to the original parent,
  9283. * which has a filp for sure, which we use as the reference
  9284. * count:
  9285. */
  9286. if (parent_event->parent)
  9287. parent_event = parent_event->parent;
  9288. child_event = perf_event_alloc(&parent_event->attr,
  9289. parent_event->cpu,
  9290. child,
  9291. group_leader, parent_event,
  9292. NULL, NULL, -1);
  9293. if (IS_ERR(child_event))
  9294. return child_event;
  9295. if ((child_event->attach_state & PERF_ATTACH_TASK_DATA) &&
  9296. !child_ctx->task_ctx_data) {
  9297. struct pmu *pmu = child_event->pmu;
  9298. child_ctx->task_ctx_data = kzalloc(pmu->task_ctx_size,
  9299. GFP_KERNEL);
  9300. if (!child_ctx->task_ctx_data) {
  9301. free_event(child_event);
  9302. return NULL;
  9303. }
  9304. }
  9305. /*
  9306. * is_orphaned_event() and list_add_tail(&parent_event->child_list)
  9307. * must be under the same lock in order to serialize against
  9308. * perf_event_release_kernel(), such that either we must observe
  9309. * is_orphaned_event() or they will observe us on the child_list.
  9310. */
  9311. mutex_lock(&parent_event->child_mutex);
  9312. if (is_orphaned_event(parent_event) ||
  9313. !atomic_long_inc_not_zero(&parent_event->refcount)) {
  9314. mutex_unlock(&parent_event->child_mutex);
  9315. /* task_ctx_data is freed with child_ctx */
  9316. free_event(child_event);
  9317. return NULL;
  9318. }
  9319. get_ctx(child_ctx);
  9320. /*
  9321. * Make the child state follow the state of the parent event,
  9322. * not its attr.disabled bit. We hold the parent's mutex,
  9323. * so we won't race with perf_event_{en, dis}able_family.
  9324. */
  9325. if (parent_state >= PERF_EVENT_STATE_INACTIVE)
  9326. child_event->state = PERF_EVENT_STATE_INACTIVE;
  9327. else
  9328. child_event->state = PERF_EVENT_STATE_OFF;
  9329. if (parent_event->attr.freq) {
  9330. u64 sample_period = parent_event->hw.sample_period;
  9331. struct hw_perf_event *hwc = &child_event->hw;
  9332. hwc->sample_period = sample_period;
  9333. hwc->last_period = sample_period;
  9334. local64_set(&hwc->period_left, sample_period);
  9335. }
  9336. child_event->ctx = child_ctx;
  9337. child_event->overflow_handler = parent_event->overflow_handler;
  9338. child_event->overflow_handler_context
  9339. = parent_event->overflow_handler_context;
  9340. /*
  9341. * Precalculate sample_data sizes
  9342. */
  9343. perf_event__header_size(child_event);
  9344. perf_event__id_header_size(child_event);
  9345. /*
  9346. * Link it up in the child's context:
  9347. */
  9348. raw_spin_lock_irqsave(&child_ctx->lock, flags);
  9349. add_event_to_ctx(child_event, child_ctx);
  9350. raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
  9351. /*
  9352. * Link this into the parent event's child list
  9353. */
  9354. list_add_tail(&child_event->child_list, &parent_event->child_list);
  9355. mutex_unlock(&parent_event->child_mutex);
  9356. return child_event;
  9357. }
  9358. /*
  9359. * Inherits an event group.
  9360. *
  9361. * This will quietly suppress orphaned events; !inherit_event() is not an error.
  9362. * This matches with perf_event_release_kernel() removing all child events.
  9363. *
  9364. * Returns:
  9365. * - 0 on success
  9366. * - <0 on error
  9367. */
  9368. static int inherit_group(struct perf_event *parent_event,
  9369. struct task_struct *parent,
  9370. struct perf_event_context *parent_ctx,
  9371. struct task_struct *child,
  9372. struct perf_event_context *child_ctx)
  9373. {
  9374. struct perf_event *leader;
  9375. struct perf_event *sub;
  9376. struct perf_event *child_ctr;
  9377. leader = inherit_event(parent_event, parent, parent_ctx,
  9378. child, NULL, child_ctx);
  9379. if (IS_ERR(leader))
  9380. return PTR_ERR(leader);
  9381. /*
  9382. * @leader can be NULL here because of is_orphaned_event(). In this
  9383. * case inherit_event() will create individual events, similar to what
  9384. * perf_group_detach() would do anyway.
  9385. */
  9386. for_each_sibling_event(sub, parent_event) {
  9387. child_ctr = inherit_event(sub, parent, parent_ctx,
  9388. child, leader, child_ctx);
  9389. if (IS_ERR(child_ctr))
  9390. return PTR_ERR(child_ctr);
  9391. }
  9392. return 0;
  9393. }
  9394. /*
  9395. * Creates the child task context and tries to inherit the event-group.
  9396. *
  9397. * Clears @inherited_all on !attr.inherited or error. Note that we'll leave
  9398. * inherited_all set when we 'fail' to inherit an orphaned event; this is
  9399. * consistent with perf_event_release_kernel() removing all child events.
  9400. *
  9401. * Returns:
  9402. * - 0 on success
  9403. * - <0 on error
  9404. */
  9405. static int
  9406. inherit_task_group(struct perf_event *event, struct task_struct *parent,
  9407. struct perf_event_context *parent_ctx,
  9408. struct task_struct *child, int ctxn,
  9409. int *inherited_all)
  9410. {
  9411. int ret;
  9412. struct perf_event_context *child_ctx;
  9413. if (!event->attr.inherit) {
  9414. *inherited_all = 0;
  9415. return 0;
  9416. }
  9417. child_ctx = child->perf_event_ctxp[ctxn];
  9418. if (!child_ctx) {
  9419. /*
  9420. * This is executed from the parent task context, so
  9421. * inherit events that have been marked for cloning.
  9422. * First allocate and initialize a context for the
  9423. * child.
  9424. */
  9425. child_ctx = alloc_perf_context(parent_ctx->pmu, child);
  9426. if (!child_ctx)
  9427. return -ENOMEM;
  9428. child->perf_event_ctxp[ctxn] = child_ctx;
  9429. }
  9430. ret = inherit_group(event, parent, parent_ctx,
  9431. child, child_ctx);
  9432. if (ret)
  9433. *inherited_all = 0;
  9434. return ret;
  9435. }
  9436. /*
  9437. * Initialize the perf_event context in task_struct
  9438. */
  9439. static int perf_event_init_context(struct task_struct *child, int ctxn)
  9440. {
  9441. struct perf_event_context *child_ctx, *parent_ctx;
  9442. struct perf_event_context *cloned_ctx;
  9443. struct perf_event *event;
  9444. struct task_struct *parent = current;
  9445. int inherited_all = 1;
  9446. unsigned long flags;
  9447. int ret = 0;
  9448. if (likely(!parent->perf_event_ctxp[ctxn]))
  9449. return 0;
  9450. /*
  9451. * If the parent's context is a clone, pin it so it won't get
  9452. * swapped under us.
  9453. */
  9454. parent_ctx = perf_pin_task_context(parent, ctxn);
  9455. if (!parent_ctx)
  9456. return 0;
  9457. /*
  9458. * No need to check if parent_ctx != NULL here; since we saw
  9459. * it non-NULL earlier, the only reason for it to become NULL
  9460. * is if we exit, and since we're currently in the middle of
  9461. * a fork we can't be exiting at the same time.
  9462. */
  9463. /*
  9464. * Lock the parent list. No need to lock the child - not PID
  9465. * hashed yet and not running, so nobody can access it.
  9466. */
  9467. mutex_lock(&parent_ctx->mutex);
  9468. /*
  9469. * We dont have to disable NMIs - we are only looking at
  9470. * the list, not manipulating it:
  9471. */
  9472. perf_event_groups_for_each(event, &parent_ctx->pinned_groups) {
  9473. ret = inherit_task_group(event, parent, parent_ctx,
  9474. child, ctxn, &inherited_all);
  9475. if (ret)
  9476. goto out_unlock;
  9477. }
  9478. /*
  9479. * We can't hold ctx->lock when iterating the ->flexible_group list due
  9480. * to allocations, but we need to prevent rotation because
  9481. * rotate_ctx() will change the list from interrupt context.
  9482. */
  9483. raw_spin_lock_irqsave(&parent_ctx->lock, flags);
  9484. parent_ctx->rotate_disable = 1;
  9485. raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
  9486. perf_event_groups_for_each(event, &parent_ctx->flexible_groups) {
  9487. ret = inherit_task_group(event, parent, parent_ctx,
  9488. child, ctxn, &inherited_all);
  9489. if (ret)
  9490. goto out_unlock;
  9491. }
  9492. raw_spin_lock_irqsave(&parent_ctx->lock, flags);
  9493. parent_ctx->rotate_disable = 0;
  9494. child_ctx = child->perf_event_ctxp[ctxn];
  9495. if (child_ctx && inherited_all) {
  9496. /*
  9497. * Mark the child context as a clone of the parent
  9498. * context, or of whatever the parent is a clone of.
  9499. *
  9500. * Note that if the parent is a clone, the holding of
  9501. * parent_ctx->lock avoids it from being uncloned.
  9502. */
  9503. cloned_ctx = parent_ctx->parent_ctx;
  9504. if (cloned_ctx) {
  9505. child_ctx->parent_ctx = cloned_ctx;
  9506. child_ctx->parent_gen = parent_ctx->parent_gen;
  9507. } else {
  9508. child_ctx->parent_ctx = parent_ctx;
  9509. child_ctx->parent_gen = parent_ctx->generation;
  9510. }
  9511. get_ctx(child_ctx->parent_ctx);
  9512. }
  9513. raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
  9514. out_unlock:
  9515. mutex_unlock(&parent_ctx->mutex);
  9516. perf_unpin_context(parent_ctx);
  9517. put_ctx(parent_ctx);
  9518. return ret;
  9519. }
  9520. /*
  9521. * Initialize the perf_event context in task_struct
  9522. */
  9523. int perf_event_init_task(struct task_struct *child)
  9524. {
  9525. int ctxn, ret;
  9526. memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
  9527. mutex_init(&child->perf_event_mutex);
  9528. INIT_LIST_HEAD(&child->perf_event_list);
  9529. for_each_task_context_nr(ctxn) {
  9530. ret = perf_event_init_context(child, ctxn);
  9531. if (ret) {
  9532. perf_event_free_task(child);
  9533. return ret;
  9534. }
  9535. }
  9536. return 0;
  9537. }
  9538. static void __init perf_event_init_all_cpus(void)
  9539. {
  9540. struct swevent_htable *swhash;
  9541. int cpu;
  9542. zalloc_cpumask_var(&perf_online_mask, GFP_KERNEL);
  9543. for_each_possible_cpu(cpu) {
  9544. swhash = &per_cpu(swevent_htable, cpu);
  9545. mutex_init(&swhash->hlist_mutex);
  9546. INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu));
  9547. INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu));
  9548. raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu));
  9549. #ifdef CONFIG_CGROUP_PERF
  9550. INIT_LIST_HEAD(&per_cpu(cgrp_cpuctx_list, cpu));
  9551. #endif
  9552. INIT_LIST_HEAD(&per_cpu(sched_cb_list, cpu));
  9553. }
  9554. }
  9555. void perf_swevent_init_cpu(unsigned int cpu)
  9556. {
  9557. struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
  9558. mutex_lock(&swhash->hlist_mutex);
  9559. if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) {
  9560. struct swevent_hlist *hlist;
  9561. hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
  9562. WARN_ON(!hlist);
  9563. rcu_assign_pointer(swhash->swevent_hlist, hlist);
  9564. }
  9565. mutex_unlock(&swhash->hlist_mutex);
  9566. }
  9567. #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
  9568. static void __perf_event_exit_context(void *__info)
  9569. {
  9570. struct perf_event_context *ctx = __info;
  9571. struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
  9572. struct perf_event *event;
  9573. raw_spin_lock(&ctx->lock);
  9574. ctx_sched_out(ctx, cpuctx, EVENT_TIME);
  9575. list_for_each_entry(event, &ctx->event_list, event_entry)
  9576. __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP);
  9577. raw_spin_unlock(&ctx->lock);
  9578. }
  9579. static void perf_event_exit_cpu_context(int cpu)
  9580. {
  9581. struct perf_cpu_context *cpuctx;
  9582. struct perf_event_context *ctx;
  9583. struct pmu *pmu;
  9584. mutex_lock(&pmus_lock);
  9585. list_for_each_entry(pmu, &pmus, entry) {
  9586. cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
  9587. ctx = &cpuctx->ctx;
  9588. mutex_lock(&ctx->mutex);
  9589. smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
  9590. cpuctx->online = 0;
  9591. mutex_unlock(&ctx->mutex);
  9592. }
  9593. cpumask_clear_cpu(cpu, perf_online_mask);
  9594. mutex_unlock(&pmus_lock);
  9595. }
  9596. #else
  9597. static void perf_event_exit_cpu_context(int cpu) { }
  9598. #endif
  9599. int perf_event_init_cpu(unsigned int cpu)
  9600. {
  9601. struct perf_cpu_context *cpuctx;
  9602. struct perf_event_context *ctx;
  9603. struct pmu *pmu;
  9604. perf_swevent_init_cpu(cpu);
  9605. mutex_lock(&pmus_lock);
  9606. cpumask_set_cpu(cpu, perf_online_mask);
  9607. list_for_each_entry(pmu, &pmus, entry) {
  9608. cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
  9609. ctx = &cpuctx->ctx;
  9610. mutex_lock(&ctx->mutex);
  9611. cpuctx->online = 1;
  9612. mutex_unlock(&ctx->mutex);
  9613. }
  9614. mutex_unlock(&pmus_lock);
  9615. return 0;
  9616. }
  9617. int perf_event_exit_cpu(unsigned int cpu)
  9618. {
  9619. perf_event_exit_cpu_context(cpu);
  9620. return 0;
  9621. }
  9622. static int
  9623. perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
  9624. {
  9625. int cpu;
  9626. for_each_online_cpu(cpu)
  9627. perf_event_exit_cpu(cpu);
  9628. return NOTIFY_OK;
  9629. }
  9630. /*
  9631. * Run the perf reboot notifier at the very last possible moment so that
  9632. * the generic watchdog code runs as long as possible.
  9633. */
  9634. static struct notifier_block perf_reboot_notifier = {
  9635. .notifier_call = perf_reboot,
  9636. .priority = INT_MIN,
  9637. };
  9638. void __init perf_event_init(void)
  9639. {
  9640. int ret;
  9641. idr_init(&pmu_idr);
  9642. perf_event_init_all_cpus();
  9643. init_srcu_struct(&pmus_srcu);
  9644. perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
  9645. perf_pmu_register(&perf_cpu_clock, NULL, -1);
  9646. perf_pmu_register(&perf_task_clock, NULL, -1);
  9647. perf_tp_register();
  9648. perf_event_init_cpu(smp_processor_id());
  9649. register_reboot_notifier(&perf_reboot_notifier);
  9650. ret = init_hw_breakpoint();
  9651. WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
  9652. /*
  9653. * Build time assertion that we keep the data_head at the intended
  9654. * location. IOW, validation we got the __reserved[] size right.
  9655. */
  9656. BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
  9657. != 1024);
  9658. }
  9659. ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
  9660. char *page)
  9661. {
  9662. struct perf_pmu_events_attr *pmu_attr =
  9663. container_of(attr, struct perf_pmu_events_attr, attr);
  9664. if (pmu_attr->event_str)
  9665. return sprintf(page, "%s\n", pmu_attr->event_str);
  9666. return 0;
  9667. }
  9668. EXPORT_SYMBOL_GPL(perf_event_sysfs_show);
  9669. static int __init perf_event_sysfs_init(void)
  9670. {
  9671. struct pmu *pmu;
  9672. int ret;
  9673. mutex_lock(&pmus_lock);
  9674. ret = bus_register(&pmu_bus);
  9675. if (ret)
  9676. goto unlock;
  9677. list_for_each_entry(pmu, &pmus, entry) {
  9678. if (!pmu->name || pmu->type < 0)
  9679. continue;
  9680. ret = pmu_dev_alloc(pmu);
  9681. WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
  9682. }
  9683. pmu_bus_running = 1;
  9684. ret = 0;
  9685. unlock:
  9686. mutex_unlock(&pmus_lock);
  9687. return ret;
  9688. }
  9689. device_initcall(perf_event_sysfs_init);
  9690. #ifdef CONFIG_CGROUP_PERF
  9691. static struct cgroup_subsys_state *
  9692. perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
  9693. {
  9694. struct perf_cgroup *jc;
  9695. jc = kzalloc(sizeof(*jc), GFP_KERNEL);
  9696. if (!jc)
  9697. return ERR_PTR(-ENOMEM);
  9698. jc->info = alloc_percpu(struct perf_cgroup_info);
  9699. if (!jc->info) {
  9700. kfree(jc);
  9701. return ERR_PTR(-ENOMEM);
  9702. }
  9703. return &jc->css;
  9704. }
  9705. static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
  9706. {
  9707. struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
  9708. free_percpu(jc->info);
  9709. kfree(jc);
  9710. }
  9711. static int __perf_cgroup_move(void *info)
  9712. {
  9713. struct task_struct *task = info;
  9714. rcu_read_lock();
  9715. perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
  9716. rcu_read_unlock();
  9717. return 0;
  9718. }
  9719. static void perf_cgroup_attach(struct cgroup_taskset *tset)
  9720. {
  9721. struct task_struct *task;
  9722. struct cgroup_subsys_state *css;
  9723. cgroup_taskset_for_each(task, css, tset)
  9724. task_function_call(task, __perf_cgroup_move, task);
  9725. }
  9726. struct cgroup_subsys perf_event_cgrp_subsys = {
  9727. .css_alloc = perf_cgroup_css_alloc,
  9728. .css_free = perf_cgroup_css_free,
  9729. .attach = perf_cgroup_attach,
  9730. /*
  9731. * Implicitly enable on dfl hierarchy so that perf events can
  9732. * always be filtered by cgroup2 path as long as perf_event
  9733. * controller is not mounted on a legacy hierarchy.
  9734. */
  9735. .implicit_on_dfl = true,
  9736. .threaded = true,
  9737. };
  9738. #endif /* CONFIG_CGROUP_PERF */