core.c 279 KB

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