core.c 265 KB

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