core.c 245 KB

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