core.c 272 KB

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