core.c 255 KB

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