core.c 259 KB

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