lockdep.c 174 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * kernel/lockdep.c
  4. *
  5. * Runtime locking correctness validator
  6. *
  7. * Started by Ingo Molnar:
  8. *
  9. * Copyright (C) 2006,2007 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
  10. * Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra
  11. *
  12. * this code maps all the lock dependencies as they occur in a live kernel
  13. * and will warn about the following classes of locking bugs:
  14. *
  15. * - lock inversion scenarios
  16. * - circular lock dependencies
  17. * - hardirq/softirq safe/unsafe locking bugs
  18. *
  19. * Bugs are reported even if the current locking scenario does not cause
  20. * any deadlock at this point.
  21. *
  22. * I.e. if anytime in the past two locks were taken in a different order,
  23. * even if it happened for another task, even if those were different
  24. * locks (but of the same class as this lock), this code will detect it.
  25. *
  26. * Thanks to Arjan van de Ven for coming up with the initial idea of
  27. * mapping lock dependencies runtime.
  28. */
  29. #define DISABLE_BRANCH_PROFILING
  30. #include <linux/mutex.h>
  31. #include <linux/sched.h>
  32. #include <linux/sched/clock.h>
  33. #include <linux/sched/task.h>
  34. #include <linux/sched/mm.h>
  35. #include <linux/delay.h>
  36. #include <linux/module.h>
  37. #include <linux/proc_fs.h>
  38. #include <linux/seq_file.h>
  39. #include <linux/spinlock.h>
  40. #include <linux/kallsyms.h>
  41. #include <linux/interrupt.h>
  42. #include <linux/stacktrace.h>
  43. #include <linux/debug_locks.h>
  44. #include <linux/irqflags.h>
  45. #include <linux/utsname.h>
  46. #include <linux/hash.h>
  47. #include <linux/ftrace.h>
  48. #include <linux/stringify.h>
  49. #include <linux/bitmap.h>
  50. #include <linux/bitops.h>
  51. #include <linux/gfp.h>
  52. #include <linux/random.h>
  53. #include <linux/jhash.h>
  54. #include <linux/nmi.h>
  55. #include <linux/rcupdate.h>
  56. #include <linux/kprobes.h>
  57. #include <linux/lockdep.h>
  58. #include <linux/context_tracking.h>
  59. #include <linux/console.h>
  60. #include <asm/sections.h>
  61. #include "lockdep_internals.h"
  62. #include <trace/events/lock.h>
  63. #ifdef CONFIG_PROVE_LOCKING
  64. static int prove_locking = 1;
  65. module_param(prove_locking, int, 0644);
  66. #else
  67. #define prove_locking 0
  68. #endif
  69. #ifdef CONFIG_LOCK_STAT
  70. static int lock_stat = 1;
  71. module_param(lock_stat, int, 0644);
  72. #else
  73. #define lock_stat 0
  74. #endif
  75. #ifdef CONFIG_SYSCTL
  76. static struct ctl_table kern_lockdep_table[] = {
  77. #ifdef CONFIG_PROVE_LOCKING
  78. {
  79. .procname = "prove_locking",
  80. .data = &prove_locking,
  81. .maxlen = sizeof(int),
  82. .mode = 0644,
  83. .proc_handler = proc_dointvec,
  84. },
  85. #endif /* CONFIG_PROVE_LOCKING */
  86. #ifdef CONFIG_LOCK_STAT
  87. {
  88. .procname = "lock_stat",
  89. .data = &lock_stat,
  90. .maxlen = sizeof(int),
  91. .mode = 0644,
  92. .proc_handler = proc_dointvec,
  93. },
  94. #endif /* CONFIG_LOCK_STAT */
  95. };
  96. static __init int kernel_lockdep_sysctls_init(void)
  97. {
  98. register_sysctl_init("kernel", kern_lockdep_table);
  99. return 0;
  100. }
  101. late_initcall(kernel_lockdep_sysctls_init);
  102. #endif /* CONFIG_SYSCTL */
  103. DEFINE_PER_CPU(unsigned int, lockdep_recursion);
  104. EXPORT_PER_CPU_SYMBOL_GPL(lockdep_recursion);
  105. static __always_inline bool lockdep_enabled(void)
  106. {
  107. if (!debug_locks)
  108. return false;
  109. if (this_cpu_read(lockdep_recursion))
  110. return false;
  111. if (current->lockdep_recursion)
  112. return false;
  113. return true;
  114. }
  115. /*
  116. * lockdep_lock: protects the lockdep graph, the hashes and the
  117. * class/list/hash allocators.
  118. *
  119. * This is one of the rare exceptions where it's justified
  120. * to use a raw spinlock - we really dont want the spinlock
  121. * code to recurse back into the lockdep code...
  122. */
  123. static arch_spinlock_t __lock = (arch_spinlock_t)__ARCH_SPIN_LOCK_UNLOCKED;
  124. static struct task_struct *__owner;
  125. static inline void lockdep_lock(void)
  126. {
  127. DEBUG_LOCKS_WARN_ON(!irqs_disabled());
  128. __this_cpu_inc(lockdep_recursion);
  129. arch_spin_lock(&__lock);
  130. __owner = current;
  131. }
  132. static inline void lockdep_unlock(void)
  133. {
  134. DEBUG_LOCKS_WARN_ON(!irqs_disabled());
  135. if (debug_locks && DEBUG_LOCKS_WARN_ON(__owner != current))
  136. return;
  137. __owner = NULL;
  138. arch_spin_unlock(&__lock);
  139. __this_cpu_dec(lockdep_recursion);
  140. }
  141. static inline bool lockdep_assert_locked(void)
  142. {
  143. return DEBUG_LOCKS_WARN_ON(__owner != current);
  144. }
  145. static struct task_struct *lockdep_selftest_task_struct;
  146. static int graph_lock(void)
  147. {
  148. lockdep_lock();
  149. /*
  150. * Make sure that if another CPU detected a bug while
  151. * walking the graph we dont change it (while the other
  152. * CPU is busy printing out stuff with the graph lock
  153. * dropped already)
  154. */
  155. if (!debug_locks) {
  156. lockdep_unlock();
  157. return 0;
  158. }
  159. return 1;
  160. }
  161. static inline void graph_unlock(void)
  162. {
  163. lockdep_unlock();
  164. }
  165. /*
  166. * Turn lock debugging off and return with 0 if it was off already,
  167. * and also release the graph lock:
  168. */
  169. static inline int debug_locks_off_graph_unlock(void)
  170. {
  171. int ret = debug_locks_off();
  172. lockdep_unlock();
  173. return ret;
  174. }
  175. unsigned long nr_list_entries;
  176. static struct lock_list list_entries[MAX_LOCKDEP_ENTRIES];
  177. static DECLARE_BITMAP(list_entries_in_use, MAX_LOCKDEP_ENTRIES);
  178. /*
  179. * All data structures here are protected by the global debug_lock.
  180. *
  181. * nr_lock_classes is the number of elements of lock_classes[] that is
  182. * in use.
  183. */
  184. #define KEYHASH_BITS (MAX_LOCKDEP_KEYS_BITS - 1)
  185. #define KEYHASH_SIZE (1UL << KEYHASH_BITS)
  186. static struct hlist_head lock_keys_hash[KEYHASH_SIZE];
  187. unsigned long nr_lock_classes;
  188. unsigned long nr_zapped_classes;
  189. unsigned long max_lock_class_idx;
  190. struct lock_class lock_classes[MAX_LOCKDEP_KEYS];
  191. DECLARE_BITMAP(lock_classes_in_use, MAX_LOCKDEP_KEYS);
  192. static inline struct lock_class *hlock_class(struct held_lock *hlock)
  193. {
  194. unsigned int class_idx = hlock->class_idx;
  195. /* Don't re-read hlock->class_idx, can't use READ_ONCE() on bitfield */
  196. barrier();
  197. if (!test_bit(class_idx, lock_classes_in_use)) {
  198. /*
  199. * Someone passed in garbage, we give up.
  200. */
  201. DEBUG_LOCKS_WARN_ON(1);
  202. return NULL;
  203. }
  204. /*
  205. * At this point, if the passed hlock->class_idx is still garbage,
  206. * we just have to live with it
  207. */
  208. return lock_classes + class_idx;
  209. }
  210. #ifdef CONFIG_LOCK_STAT
  211. static DEFINE_PER_CPU(struct lock_class_stats[MAX_LOCKDEP_KEYS], cpu_lock_stats);
  212. static inline u64 lockstat_clock(void)
  213. {
  214. return local_clock();
  215. }
  216. static int lock_point(unsigned long points[], unsigned long ip)
  217. {
  218. int i;
  219. for (i = 0; i < LOCKSTAT_POINTS; i++) {
  220. if (points[i] == 0) {
  221. points[i] = ip;
  222. break;
  223. }
  224. if (points[i] == ip)
  225. break;
  226. }
  227. return i;
  228. }
  229. static void lock_time_inc(struct lock_time *lt, u64 time)
  230. {
  231. if (time > lt->max)
  232. lt->max = time;
  233. if (time < lt->min || !lt->nr)
  234. lt->min = time;
  235. lt->total += time;
  236. lt->nr++;
  237. }
  238. static inline void lock_time_add(struct lock_time *src, struct lock_time *dst)
  239. {
  240. if (!src->nr)
  241. return;
  242. if (src->max > dst->max)
  243. dst->max = src->max;
  244. if (src->min < dst->min || !dst->nr)
  245. dst->min = src->min;
  246. dst->total += src->total;
  247. dst->nr += src->nr;
  248. }
  249. struct lock_class_stats lock_stats(struct lock_class *class)
  250. {
  251. struct lock_class_stats stats;
  252. int cpu, i;
  253. memset(&stats, 0, sizeof(struct lock_class_stats));
  254. for_each_possible_cpu(cpu) {
  255. struct lock_class_stats *pcs =
  256. &per_cpu(cpu_lock_stats, cpu)[class - lock_classes];
  257. for (i = 0; i < ARRAY_SIZE(stats.contention_point); i++)
  258. stats.contention_point[i] += pcs->contention_point[i];
  259. for (i = 0; i < ARRAY_SIZE(stats.contending_point); i++)
  260. stats.contending_point[i] += pcs->contending_point[i];
  261. lock_time_add(&pcs->read_waittime, &stats.read_waittime);
  262. lock_time_add(&pcs->write_waittime, &stats.write_waittime);
  263. lock_time_add(&pcs->read_holdtime, &stats.read_holdtime);
  264. lock_time_add(&pcs->write_holdtime, &stats.write_holdtime);
  265. for (i = 0; i < ARRAY_SIZE(stats.bounces); i++)
  266. stats.bounces[i] += pcs->bounces[i];
  267. }
  268. return stats;
  269. }
  270. void clear_lock_stats(struct lock_class *class)
  271. {
  272. int cpu;
  273. for_each_possible_cpu(cpu) {
  274. struct lock_class_stats *cpu_stats =
  275. &per_cpu(cpu_lock_stats, cpu)[class - lock_classes];
  276. memset(cpu_stats, 0, sizeof(struct lock_class_stats));
  277. }
  278. memset(class->contention_point, 0, sizeof(class->contention_point));
  279. memset(class->contending_point, 0, sizeof(class->contending_point));
  280. }
  281. static struct lock_class_stats *get_lock_stats(struct lock_class *class)
  282. {
  283. return &this_cpu_ptr(cpu_lock_stats)[class - lock_classes];
  284. }
  285. static void lock_release_holdtime(struct held_lock *hlock)
  286. {
  287. struct lock_class_stats *stats;
  288. u64 holdtime;
  289. if (!lock_stat)
  290. return;
  291. holdtime = lockstat_clock() - hlock->holdtime_stamp;
  292. stats = get_lock_stats(hlock_class(hlock));
  293. if (hlock->read)
  294. lock_time_inc(&stats->read_holdtime, holdtime);
  295. else
  296. lock_time_inc(&stats->write_holdtime, holdtime);
  297. }
  298. #else
  299. static inline void lock_release_holdtime(struct held_lock *hlock)
  300. {
  301. }
  302. #endif
  303. /*
  304. * We keep a global list of all lock classes. The list is only accessed with
  305. * the lockdep spinlock lock held. free_lock_classes is a list with free
  306. * elements. These elements are linked together by the lock_entry member in
  307. * struct lock_class.
  308. */
  309. static LIST_HEAD(all_lock_classes);
  310. static LIST_HEAD(free_lock_classes);
  311. /**
  312. * struct pending_free - information about data structures about to be freed
  313. * @zapped: Head of a list with struct lock_class elements.
  314. * @lock_chains_being_freed: Bitmap that indicates which lock_chains[] elements
  315. * are about to be freed.
  316. */
  317. struct pending_free {
  318. struct list_head zapped;
  319. DECLARE_BITMAP(lock_chains_being_freed, MAX_LOCKDEP_CHAINS);
  320. };
  321. /**
  322. * struct delayed_free - data structures used for delayed freeing
  323. *
  324. * A data structure for delayed freeing of data structures that may be
  325. * accessed by RCU readers at the time these were freed.
  326. *
  327. * @rcu_head: Used to schedule an RCU callback for freeing data structures.
  328. * @index: Index of @pf to which freed data structures are added.
  329. * @scheduled: Whether or not an RCU callback has been scheduled.
  330. * @pf: Array with information about data structures about to be freed.
  331. */
  332. static struct delayed_free {
  333. struct rcu_head rcu_head;
  334. int index;
  335. int scheduled;
  336. struct pending_free pf[2];
  337. } delayed_free;
  338. /*
  339. * The lockdep classes are in a hash-table as well, for fast lookup:
  340. */
  341. #define CLASSHASH_BITS (MAX_LOCKDEP_KEYS_BITS - 1)
  342. #define CLASSHASH_SIZE (1UL << CLASSHASH_BITS)
  343. #define __classhashfn(key) hash_long((unsigned long)key, CLASSHASH_BITS)
  344. #define classhashentry(key) (classhash_table + __classhashfn((key)))
  345. static struct hlist_head classhash_table[CLASSHASH_SIZE];
  346. /*
  347. * We put the lock dependency chains into a hash-table as well, to cache
  348. * their existence:
  349. */
  350. #define CHAINHASH_BITS (MAX_LOCKDEP_CHAINS_BITS-1)
  351. #define CHAINHASH_SIZE (1UL << CHAINHASH_BITS)
  352. #define __chainhashfn(chain) hash_long(chain, CHAINHASH_BITS)
  353. #define chainhashentry(chain) (chainhash_table + __chainhashfn((chain)))
  354. static struct hlist_head chainhash_table[CHAINHASH_SIZE];
  355. /*
  356. * the id of held_lock
  357. */
  358. static inline u16 hlock_id(struct held_lock *hlock)
  359. {
  360. BUILD_BUG_ON(MAX_LOCKDEP_KEYS_BITS + 2 > 16);
  361. return (hlock->class_idx | (hlock->read << MAX_LOCKDEP_KEYS_BITS));
  362. }
  363. static inline unsigned int chain_hlock_class_idx(u16 hlock_id)
  364. {
  365. return hlock_id & (MAX_LOCKDEP_KEYS - 1);
  366. }
  367. /*
  368. * The hash key of the lock dependency chains is a hash itself too:
  369. * it's a hash of all locks taken up to that lock, including that lock.
  370. * It's a 64-bit hash, because it's important for the keys to be
  371. * unique.
  372. */
  373. static inline u64 iterate_chain_key(u64 key, u32 idx)
  374. {
  375. u32 k0 = key, k1 = key >> 32;
  376. __jhash_mix(idx, k0, k1); /* Macro that modifies arguments! */
  377. return k0 | (u64)k1 << 32;
  378. }
  379. void lockdep_init_task(struct task_struct *task)
  380. {
  381. task->lockdep_depth = 0; /* no locks held yet */
  382. task->curr_chain_key = INITIAL_CHAIN_KEY;
  383. task->lockdep_recursion = 0;
  384. }
  385. static __always_inline void lockdep_recursion_inc(void)
  386. {
  387. __this_cpu_inc(lockdep_recursion);
  388. }
  389. static __always_inline void lockdep_recursion_finish(void)
  390. {
  391. if (WARN_ON_ONCE(__this_cpu_dec_return(lockdep_recursion)))
  392. __this_cpu_write(lockdep_recursion, 0);
  393. }
  394. void lockdep_set_selftest_task(struct task_struct *task)
  395. {
  396. lockdep_selftest_task_struct = task;
  397. }
  398. /*
  399. * Debugging switches:
  400. */
  401. #define VERBOSE 0
  402. #define VERY_VERBOSE 0
  403. #if VERBOSE
  404. # define HARDIRQ_VERBOSE 1
  405. # define SOFTIRQ_VERBOSE 1
  406. #else
  407. # define HARDIRQ_VERBOSE 0
  408. # define SOFTIRQ_VERBOSE 0
  409. #endif
  410. #if VERBOSE || HARDIRQ_VERBOSE || SOFTIRQ_VERBOSE
  411. /*
  412. * Quick filtering for interesting events:
  413. */
  414. static int class_filter(struct lock_class *class)
  415. {
  416. #if 0
  417. /* Example */
  418. if (class->name_version == 1 &&
  419. !strcmp(class->name, "lockname"))
  420. return 1;
  421. if (class->name_version == 1 &&
  422. !strcmp(class->name, "&struct->lockfield"))
  423. return 1;
  424. #endif
  425. /* Filter everything else. 1 would be to allow everything else */
  426. return 0;
  427. }
  428. #endif
  429. static int verbose(struct lock_class *class)
  430. {
  431. #if VERBOSE
  432. return class_filter(class);
  433. #endif
  434. return 0;
  435. }
  436. static void print_lockdep_off(const char *bug_msg)
  437. {
  438. printk(KERN_DEBUG "%s\n", bug_msg);
  439. printk(KERN_DEBUG "turning off the locking correctness validator.\n");
  440. #ifdef CONFIG_LOCK_STAT
  441. printk(KERN_DEBUG "Please attach the output of /proc/lock_stat to the bug report\n");
  442. #endif
  443. }
  444. unsigned long nr_stack_trace_entries;
  445. #ifdef CONFIG_PROVE_LOCKING
  446. /**
  447. * struct lock_trace - single stack backtrace
  448. * @hash_entry: Entry in a stack_trace_hash[] list.
  449. * @hash: jhash() of @entries.
  450. * @nr_entries: Number of entries in @entries.
  451. * @entries: Actual stack backtrace.
  452. */
  453. struct lock_trace {
  454. struct hlist_node hash_entry;
  455. u32 hash;
  456. u32 nr_entries;
  457. unsigned long entries[] __aligned(sizeof(unsigned long));
  458. };
  459. #define LOCK_TRACE_SIZE_IN_LONGS \
  460. (sizeof(struct lock_trace) / sizeof(unsigned long))
  461. /*
  462. * Stack-trace: sequence of lock_trace structures. Protected by the graph_lock.
  463. */
  464. static unsigned long stack_trace[MAX_STACK_TRACE_ENTRIES];
  465. static struct hlist_head stack_trace_hash[STACK_TRACE_HASH_SIZE];
  466. static bool traces_identical(struct lock_trace *t1, struct lock_trace *t2)
  467. {
  468. return t1->hash == t2->hash && t1->nr_entries == t2->nr_entries &&
  469. memcmp(t1->entries, t2->entries,
  470. t1->nr_entries * sizeof(t1->entries[0])) == 0;
  471. }
  472. static struct lock_trace *save_trace(void)
  473. {
  474. struct lock_trace *trace, *t2;
  475. struct hlist_head *hash_head;
  476. u32 hash;
  477. int max_entries;
  478. BUILD_BUG_ON_NOT_POWER_OF_2(STACK_TRACE_HASH_SIZE);
  479. BUILD_BUG_ON(LOCK_TRACE_SIZE_IN_LONGS >= MAX_STACK_TRACE_ENTRIES);
  480. trace = (struct lock_trace *)(stack_trace + nr_stack_trace_entries);
  481. max_entries = MAX_STACK_TRACE_ENTRIES - nr_stack_trace_entries -
  482. LOCK_TRACE_SIZE_IN_LONGS;
  483. if (max_entries <= 0) {
  484. if (!debug_locks_off_graph_unlock())
  485. return NULL;
  486. nbcon_cpu_emergency_enter();
  487. print_lockdep_off("BUG: MAX_STACK_TRACE_ENTRIES too low!");
  488. dump_stack();
  489. nbcon_cpu_emergency_exit();
  490. return NULL;
  491. }
  492. trace->nr_entries = stack_trace_save(trace->entries, max_entries, 3);
  493. hash = jhash(trace->entries, trace->nr_entries *
  494. sizeof(trace->entries[0]), 0);
  495. trace->hash = hash;
  496. hash_head = stack_trace_hash + (hash & (STACK_TRACE_HASH_SIZE - 1));
  497. hlist_for_each_entry(t2, hash_head, hash_entry) {
  498. if (traces_identical(trace, t2))
  499. return t2;
  500. }
  501. nr_stack_trace_entries += LOCK_TRACE_SIZE_IN_LONGS + trace->nr_entries;
  502. hlist_add_head(&trace->hash_entry, hash_head);
  503. return trace;
  504. }
  505. /* Return the number of stack traces in the stack_trace[] array. */
  506. u64 lockdep_stack_trace_count(void)
  507. {
  508. struct lock_trace *trace;
  509. u64 c = 0;
  510. int i;
  511. for (i = 0; i < ARRAY_SIZE(stack_trace_hash); i++) {
  512. hlist_for_each_entry(trace, &stack_trace_hash[i], hash_entry) {
  513. c++;
  514. }
  515. }
  516. return c;
  517. }
  518. /* Return the number of stack hash chains that have at least one stack trace. */
  519. u64 lockdep_stack_hash_count(void)
  520. {
  521. u64 c = 0;
  522. int i;
  523. for (i = 0; i < ARRAY_SIZE(stack_trace_hash); i++)
  524. if (!hlist_empty(&stack_trace_hash[i]))
  525. c++;
  526. return c;
  527. }
  528. #endif
  529. unsigned int nr_hardirq_chains;
  530. unsigned int nr_softirq_chains;
  531. unsigned int nr_process_chains;
  532. unsigned int max_lockdep_depth;
  533. #ifdef CONFIG_DEBUG_LOCKDEP
  534. /*
  535. * Various lockdep statistics:
  536. */
  537. DEFINE_PER_CPU(struct lockdep_stats, lockdep_stats);
  538. #endif
  539. #ifdef CONFIG_PROVE_LOCKING
  540. /*
  541. * Locking printouts:
  542. */
  543. #define __USAGE(__STATE) \
  544. [LOCK_USED_IN_##__STATE] = "IN-"__stringify(__STATE)"-W", \
  545. [LOCK_ENABLED_##__STATE] = __stringify(__STATE)"-ON-W", \
  546. [LOCK_USED_IN_##__STATE##_READ] = "IN-"__stringify(__STATE)"-R",\
  547. [LOCK_ENABLED_##__STATE##_READ] = __stringify(__STATE)"-ON-R",
  548. static const char *usage_str[] =
  549. {
  550. #define LOCKDEP_STATE(__STATE) __USAGE(__STATE)
  551. #include "lockdep_states.h"
  552. #undef LOCKDEP_STATE
  553. [LOCK_USED] = "INITIAL USE",
  554. [LOCK_USED_READ] = "INITIAL READ USE",
  555. /* abused as string storage for verify_lock_unused() */
  556. [LOCK_USAGE_STATES] = "IN-NMI",
  557. };
  558. #endif
  559. const char *__get_key_name(const struct lockdep_subclass_key *key, char *str)
  560. {
  561. return kallsyms_lookup((unsigned long)key, NULL, NULL, NULL, str);
  562. }
  563. static inline unsigned long lock_flag(enum lock_usage_bit bit)
  564. {
  565. return 1UL << bit;
  566. }
  567. static char get_usage_char(struct lock_class *class, enum lock_usage_bit bit)
  568. {
  569. /*
  570. * The usage character defaults to '.' (i.e., irqs disabled and not in
  571. * irq context), which is the safest usage category.
  572. */
  573. char c = '.';
  574. /*
  575. * The order of the following usage checks matters, which will
  576. * result in the outcome character as follows:
  577. *
  578. * - '+': irq is enabled and not in irq context
  579. * - '-': in irq context and irq is disabled
  580. * - '?': in irq context and irq is enabled
  581. */
  582. if (class->usage_mask & lock_flag(bit + LOCK_USAGE_DIR_MASK)) {
  583. c = '+';
  584. if (class->usage_mask & lock_flag(bit))
  585. c = '?';
  586. } else if (class->usage_mask & lock_flag(bit))
  587. c = '-';
  588. return c;
  589. }
  590. void get_usage_chars(struct lock_class *class, char usage[LOCK_USAGE_CHARS])
  591. {
  592. int i = 0;
  593. #define LOCKDEP_STATE(__STATE) \
  594. usage[i++] = get_usage_char(class, LOCK_USED_IN_##__STATE); \
  595. usage[i++] = get_usage_char(class, LOCK_USED_IN_##__STATE##_READ);
  596. #include "lockdep_states.h"
  597. #undef LOCKDEP_STATE
  598. usage[i] = '\0';
  599. }
  600. static void __print_lock_name(struct held_lock *hlock, struct lock_class *class)
  601. {
  602. char str[KSYM_NAME_LEN];
  603. const char *name;
  604. name = class->name;
  605. if (!name) {
  606. name = __get_key_name(class->key, str);
  607. printk(KERN_CONT "%s", name);
  608. } else {
  609. printk(KERN_CONT "%s", name);
  610. if (class->name_version > 1)
  611. printk(KERN_CONT "#%d", class->name_version);
  612. if (class->subclass)
  613. printk(KERN_CONT "/%d", class->subclass);
  614. if (hlock && class->print_fn)
  615. class->print_fn(hlock->instance);
  616. }
  617. }
  618. static void print_lock_name(struct held_lock *hlock, struct lock_class *class)
  619. {
  620. char usage[LOCK_USAGE_CHARS];
  621. get_usage_chars(class, usage);
  622. printk(KERN_CONT " (");
  623. __print_lock_name(hlock, class);
  624. printk(KERN_CONT "){%s}-{%d:%d}", usage,
  625. class->wait_type_outer ?: class->wait_type_inner,
  626. class->wait_type_inner);
  627. }
  628. static void print_lockdep_cache(struct lockdep_map *lock)
  629. {
  630. const char *name;
  631. char str[KSYM_NAME_LEN];
  632. name = lock->name;
  633. if (!name)
  634. name = __get_key_name(lock->key->subkeys, str);
  635. printk(KERN_CONT "%s", name);
  636. }
  637. static void print_lock(struct held_lock *hlock)
  638. {
  639. /*
  640. * We can be called locklessly through debug_show_all_locks() so be
  641. * extra careful, the hlock might have been released and cleared.
  642. *
  643. * If this indeed happens, lets pretend it does not hurt to continue
  644. * to print the lock unless the hlock class_idx does not point to a
  645. * registered class. The rationale here is: since we don't attempt
  646. * to distinguish whether we are in this situation, if it just
  647. * happened we can't count on class_idx to tell either.
  648. */
  649. struct lock_class *lock = hlock_class(hlock);
  650. if (!lock) {
  651. printk(KERN_CONT "<RELEASED>\n");
  652. return;
  653. }
  654. printk(KERN_CONT "%px", hlock->instance);
  655. print_lock_name(hlock, lock);
  656. printk(KERN_CONT ", at: %pS\n", (void *)hlock->acquire_ip);
  657. }
  658. static void lockdep_print_held_locks(struct task_struct *p)
  659. {
  660. int i, depth = READ_ONCE(p->lockdep_depth);
  661. if (!depth)
  662. printk("no locks held by %s/%d.\n", p->comm, task_pid_nr(p));
  663. else
  664. printk("%d lock%s held by %s/%d:\n", depth,
  665. str_plural(depth), p->comm, task_pid_nr(p));
  666. /*
  667. * It's not reliable to print a task's held locks if it's not sleeping
  668. * and it's not the current task.
  669. */
  670. if (p != current && task_is_running(p))
  671. return;
  672. for (i = 0; i < depth; i++) {
  673. printk(" #%d: ", i);
  674. print_lock(p->held_locks + i);
  675. }
  676. }
  677. static void print_kernel_ident(void)
  678. {
  679. printk("%s %.*s %s\n", init_utsname()->release,
  680. (int)strcspn(init_utsname()->version, " "),
  681. init_utsname()->version,
  682. print_tainted());
  683. }
  684. static int very_verbose(struct lock_class *class)
  685. {
  686. #if VERY_VERBOSE
  687. return class_filter(class);
  688. #endif
  689. return 0;
  690. }
  691. /*
  692. * Is this the address of a static object:
  693. */
  694. #ifdef __KERNEL__
  695. static int static_obj(const void *obj)
  696. {
  697. unsigned long addr = (unsigned long) obj;
  698. if (is_kernel_core_data(addr))
  699. return 1;
  700. /*
  701. * keys are allowed in the __ro_after_init section.
  702. */
  703. if (is_kernel_rodata(addr))
  704. return 1;
  705. /*
  706. * in initdata section and used during bootup only?
  707. * NOTE: On some platforms the initdata section is
  708. * outside of the _stext ... _end range.
  709. */
  710. if (system_state < SYSTEM_FREEING_INITMEM &&
  711. init_section_contains((void *)addr, 1))
  712. return 1;
  713. /*
  714. * in-kernel percpu var?
  715. */
  716. if (is_kernel_percpu_address(addr))
  717. return 1;
  718. /*
  719. * module static or percpu var?
  720. */
  721. return is_module_address(addr) || is_module_percpu_address(addr);
  722. }
  723. #endif
  724. /*
  725. * To make lock name printouts unique, we calculate a unique
  726. * class->name_version generation counter. The caller must hold the graph
  727. * lock.
  728. */
  729. static int count_matching_names(struct lock_class *new_class)
  730. {
  731. struct lock_class *class;
  732. int count = 0;
  733. if (!new_class->name)
  734. return 0;
  735. list_for_each_entry(class, &all_lock_classes, lock_entry) {
  736. if (new_class->key - new_class->subclass == class->key)
  737. return class->name_version;
  738. if (class->name && !strcmp(class->name, new_class->name))
  739. count = max(count, class->name_version);
  740. }
  741. return count + 1;
  742. }
  743. /* used from NMI context -- must be lockless */
  744. static noinstr struct lock_class *
  745. look_up_lock_class(const struct lockdep_map *lock, unsigned int subclass)
  746. {
  747. struct lockdep_subclass_key *key;
  748. struct hlist_head *hash_head;
  749. struct lock_class *class;
  750. if (unlikely(subclass >= MAX_LOCKDEP_SUBCLASSES)) {
  751. instrumentation_begin();
  752. debug_locks_off();
  753. nbcon_cpu_emergency_enter();
  754. printk(KERN_ERR
  755. "BUG: looking up invalid subclass: %u\n", subclass);
  756. printk(KERN_ERR
  757. "turning off the locking correctness validator.\n");
  758. dump_stack();
  759. nbcon_cpu_emergency_exit();
  760. instrumentation_end();
  761. return NULL;
  762. }
  763. /*
  764. * If it is not initialised then it has never been locked,
  765. * so it won't be present in the hash table.
  766. */
  767. if (unlikely(!lock->key))
  768. return NULL;
  769. /*
  770. * NOTE: the class-key must be unique. For dynamic locks, a static
  771. * lock_class_key variable is passed in through the mutex_init()
  772. * (or spin_lock_init()) call - which acts as the key. For static
  773. * locks we use the lock object itself as the key.
  774. */
  775. BUILD_BUG_ON(sizeof(struct lock_class_key) >
  776. sizeof(struct lockdep_map));
  777. key = lock->key->subkeys + subclass;
  778. hash_head = classhashentry(key);
  779. /*
  780. * We do an RCU walk of the hash, see lockdep_free_key_range().
  781. */
  782. if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
  783. return NULL;
  784. hlist_for_each_entry_rcu_notrace(class, hash_head, hash_entry) {
  785. if (class->key == key) {
  786. /*
  787. * Huh! same key, different name? Did someone trample
  788. * on some memory? We're most confused.
  789. */
  790. WARN_ONCE(class->name != lock->name &&
  791. lock->key != &__lockdep_no_validate__,
  792. "Looking for class \"%s\" with key %ps, but found a different class \"%s\" with the same key\n",
  793. lock->name, lock->key, class->name);
  794. return class;
  795. }
  796. }
  797. return NULL;
  798. }
  799. /*
  800. * Static locks do not have their class-keys yet - for them the key is
  801. * the lock object itself. If the lock is in the per cpu area, the
  802. * canonical address of the lock (per cpu offset removed) is used.
  803. */
  804. static bool assign_lock_key(struct lockdep_map *lock)
  805. {
  806. unsigned long can_addr, addr = (unsigned long)lock;
  807. #ifdef __KERNEL__
  808. /*
  809. * lockdep_free_key_range() assumes that struct lock_class_key
  810. * objects do not overlap. Since we use the address of lock
  811. * objects as class key for static objects, check whether the
  812. * size of lock_class_key objects does not exceed the size of
  813. * the smallest lock object.
  814. */
  815. BUILD_BUG_ON(sizeof(struct lock_class_key) > sizeof(raw_spinlock_t));
  816. #endif
  817. if (__is_kernel_percpu_address(addr, &can_addr))
  818. lock->key = (void *)can_addr;
  819. else if (__is_module_percpu_address(addr, &can_addr))
  820. lock->key = (void *)can_addr;
  821. else if (static_obj(lock))
  822. lock->key = (void *)lock;
  823. else {
  824. /* Debug-check: all keys must be persistent! */
  825. debug_locks_off();
  826. nbcon_cpu_emergency_enter();
  827. pr_err("INFO: trying to register non-static key.\n");
  828. pr_err("The code is fine but needs lockdep annotation, or maybe\n");
  829. pr_err("you didn't initialize this object before use?\n");
  830. pr_err("turning off the locking correctness validator.\n");
  831. dump_stack();
  832. nbcon_cpu_emergency_exit();
  833. return false;
  834. }
  835. return true;
  836. }
  837. #ifdef CONFIG_DEBUG_LOCKDEP
  838. /* Check whether element @e occurs in list @h */
  839. static bool in_list(struct list_head *e, struct list_head *h)
  840. {
  841. struct list_head *f;
  842. list_for_each(f, h) {
  843. if (e == f)
  844. return true;
  845. }
  846. return false;
  847. }
  848. /*
  849. * Check whether entry @e occurs in any of the locks_after or locks_before
  850. * lists.
  851. */
  852. static bool in_any_class_list(struct list_head *e)
  853. {
  854. struct lock_class *class;
  855. int i;
  856. for (i = 0; i < ARRAY_SIZE(lock_classes); i++) {
  857. class = &lock_classes[i];
  858. if (in_list(e, &class->locks_after) ||
  859. in_list(e, &class->locks_before))
  860. return true;
  861. }
  862. return false;
  863. }
  864. static bool class_lock_list_valid(struct lock_class *c, struct list_head *h)
  865. {
  866. struct lock_list *e;
  867. list_for_each_entry(e, h, entry) {
  868. if (e->links_to != c) {
  869. printk(KERN_INFO "class %s: mismatch for lock entry %ld; class %s <> %s",
  870. c->name ? : "(?)",
  871. (unsigned long)(e - list_entries),
  872. e->links_to && e->links_to->name ?
  873. e->links_to->name : "(?)",
  874. e->class && e->class->name ? e->class->name :
  875. "(?)");
  876. return false;
  877. }
  878. }
  879. return true;
  880. }
  881. #ifdef CONFIG_PROVE_LOCKING
  882. static u16 chain_hlocks[MAX_LOCKDEP_CHAIN_HLOCKS];
  883. #endif
  884. static bool check_lock_chain_key(struct lock_chain *chain)
  885. {
  886. #ifdef CONFIG_PROVE_LOCKING
  887. u64 chain_key = INITIAL_CHAIN_KEY;
  888. int i;
  889. for (i = chain->base; i < chain->base + chain->depth; i++)
  890. chain_key = iterate_chain_key(chain_key, chain_hlocks[i]);
  891. /*
  892. * The 'unsigned long long' casts avoid that a compiler warning
  893. * is reported when building tools/lib/lockdep.
  894. */
  895. if (chain->chain_key != chain_key) {
  896. printk(KERN_INFO "chain %lld: key %#llx <> %#llx\n",
  897. (unsigned long long)(chain - lock_chains),
  898. (unsigned long long)chain->chain_key,
  899. (unsigned long long)chain_key);
  900. return false;
  901. }
  902. #endif
  903. return true;
  904. }
  905. static bool in_any_zapped_class_list(struct lock_class *class)
  906. {
  907. struct pending_free *pf;
  908. int i;
  909. for (i = 0, pf = delayed_free.pf; i < ARRAY_SIZE(delayed_free.pf); i++, pf++) {
  910. if (in_list(&class->lock_entry, &pf->zapped))
  911. return true;
  912. }
  913. return false;
  914. }
  915. static bool __check_data_structures(void)
  916. {
  917. struct lock_class *class;
  918. struct lock_chain *chain;
  919. struct hlist_head *head;
  920. struct lock_list *e;
  921. int i;
  922. /* Check whether all classes occur in a lock list. */
  923. for (i = 0; i < ARRAY_SIZE(lock_classes); i++) {
  924. class = &lock_classes[i];
  925. if (!in_list(&class->lock_entry, &all_lock_classes) &&
  926. !in_list(&class->lock_entry, &free_lock_classes) &&
  927. !in_any_zapped_class_list(class)) {
  928. printk(KERN_INFO "class %px/%s is not in any class list\n",
  929. class, class->name ? : "(?)");
  930. return false;
  931. }
  932. }
  933. /* Check whether all classes have valid lock lists. */
  934. for (i = 0; i < ARRAY_SIZE(lock_classes); i++) {
  935. class = &lock_classes[i];
  936. if (!class_lock_list_valid(class, &class->locks_before))
  937. return false;
  938. if (!class_lock_list_valid(class, &class->locks_after))
  939. return false;
  940. }
  941. /* Check the chain_key of all lock chains. */
  942. for (i = 0; i < ARRAY_SIZE(chainhash_table); i++) {
  943. head = chainhash_table + i;
  944. hlist_for_each_entry_rcu(chain, head, entry) {
  945. if (!check_lock_chain_key(chain))
  946. return false;
  947. }
  948. }
  949. /*
  950. * Check whether all list entries that are in use occur in a class
  951. * lock list.
  952. */
  953. for_each_set_bit(i, list_entries_in_use, ARRAY_SIZE(list_entries)) {
  954. e = list_entries + i;
  955. if (!in_any_class_list(&e->entry)) {
  956. printk(KERN_INFO "list entry %d is not in any class list; class %s <> %s\n",
  957. (unsigned int)(e - list_entries),
  958. e->class->name ? : "(?)",
  959. e->links_to->name ? : "(?)");
  960. return false;
  961. }
  962. }
  963. /*
  964. * Check whether all list entries that are not in use do not occur in
  965. * a class lock list.
  966. */
  967. for_each_clear_bit(i, list_entries_in_use, ARRAY_SIZE(list_entries)) {
  968. e = list_entries + i;
  969. if (in_any_class_list(&e->entry)) {
  970. printk(KERN_INFO "list entry %d occurs in a class list; class %s <> %s\n",
  971. (unsigned int)(e - list_entries),
  972. e->class && e->class->name ? e->class->name :
  973. "(?)",
  974. e->links_to && e->links_to->name ?
  975. e->links_to->name : "(?)");
  976. return false;
  977. }
  978. }
  979. return true;
  980. }
  981. int check_consistency = 0;
  982. module_param(check_consistency, int, 0644);
  983. static void check_data_structures(void)
  984. {
  985. static bool once = false;
  986. if (check_consistency && !once) {
  987. if (!__check_data_structures()) {
  988. once = true;
  989. WARN_ON(once);
  990. }
  991. }
  992. }
  993. #else /* CONFIG_DEBUG_LOCKDEP */
  994. static inline void check_data_structures(void) { }
  995. #endif /* CONFIG_DEBUG_LOCKDEP */
  996. static void init_chain_block_buckets(void);
  997. /*
  998. * Initialize the lock_classes[] array elements, the free_lock_classes list
  999. * and also the delayed_free structure.
  1000. */
  1001. static void init_data_structures_once(void)
  1002. {
  1003. static bool __read_mostly ds_initialized, rcu_head_initialized;
  1004. int i;
  1005. if (likely(rcu_head_initialized))
  1006. return;
  1007. if (system_state >= SYSTEM_SCHEDULING) {
  1008. init_rcu_head(&delayed_free.rcu_head);
  1009. rcu_head_initialized = true;
  1010. }
  1011. if (ds_initialized)
  1012. return;
  1013. ds_initialized = true;
  1014. INIT_LIST_HEAD(&delayed_free.pf[0].zapped);
  1015. INIT_LIST_HEAD(&delayed_free.pf[1].zapped);
  1016. for (i = 0; i < ARRAY_SIZE(lock_classes); i++) {
  1017. list_add_tail(&lock_classes[i].lock_entry, &free_lock_classes);
  1018. INIT_LIST_HEAD(&lock_classes[i].locks_after);
  1019. INIT_LIST_HEAD(&lock_classes[i].locks_before);
  1020. }
  1021. init_chain_block_buckets();
  1022. }
  1023. static inline struct hlist_head *keyhashentry(const struct lock_class_key *key)
  1024. {
  1025. unsigned long hash = hash_long((uintptr_t)key, KEYHASH_BITS);
  1026. return lock_keys_hash + hash;
  1027. }
  1028. /* Register a dynamically allocated key. */
  1029. void lockdep_register_key(struct lock_class_key *key)
  1030. {
  1031. struct hlist_head *hash_head;
  1032. struct lock_class_key *k;
  1033. unsigned long flags;
  1034. if (WARN_ON_ONCE(static_obj(key)))
  1035. return;
  1036. hash_head = keyhashentry(key);
  1037. raw_local_irq_save(flags);
  1038. if (!graph_lock())
  1039. goto restore_irqs;
  1040. hlist_for_each_entry_rcu(k, hash_head, hash_entry) {
  1041. if (WARN_ON_ONCE(k == key))
  1042. goto out_unlock;
  1043. }
  1044. hlist_add_head_rcu(&key->hash_entry, hash_head);
  1045. out_unlock:
  1046. graph_unlock();
  1047. restore_irqs:
  1048. raw_local_irq_restore(flags);
  1049. }
  1050. EXPORT_SYMBOL_GPL(lockdep_register_key);
  1051. /* Check whether a key has been registered as a dynamic key. */
  1052. static bool is_dynamic_key(const struct lock_class_key *key)
  1053. {
  1054. struct hlist_head *hash_head;
  1055. struct lock_class_key *k;
  1056. bool found = false;
  1057. if (WARN_ON_ONCE(static_obj(key)))
  1058. return false;
  1059. /*
  1060. * If lock debugging is disabled lock_keys_hash[] may contain
  1061. * pointers to memory that has already been freed. Avoid triggering
  1062. * a use-after-free in that case by returning early.
  1063. */
  1064. if (!debug_locks)
  1065. return true;
  1066. hash_head = keyhashentry(key);
  1067. rcu_read_lock();
  1068. hlist_for_each_entry_rcu(k, hash_head, hash_entry) {
  1069. if (k == key) {
  1070. found = true;
  1071. break;
  1072. }
  1073. }
  1074. rcu_read_unlock();
  1075. return found;
  1076. }
  1077. /*
  1078. * Register a lock's class in the hash-table, if the class is not present
  1079. * yet. Otherwise we look it up. We cache the result in the lock object
  1080. * itself, so actual lookup of the hash should be once per lock object.
  1081. */
  1082. static struct lock_class *
  1083. register_lock_class(struct lockdep_map *lock, unsigned int subclass, int force)
  1084. {
  1085. struct lockdep_subclass_key *key;
  1086. struct hlist_head *hash_head;
  1087. struct lock_class *class;
  1088. int idx;
  1089. DEBUG_LOCKS_WARN_ON(!irqs_disabled());
  1090. class = look_up_lock_class(lock, subclass);
  1091. if (likely(class))
  1092. goto out_set_class_cache;
  1093. if (!lock->key) {
  1094. if (!assign_lock_key(lock))
  1095. return NULL;
  1096. } else if (!static_obj(lock->key) && !is_dynamic_key(lock->key)) {
  1097. return NULL;
  1098. }
  1099. key = lock->key->subkeys + subclass;
  1100. hash_head = classhashentry(key);
  1101. if (!graph_lock()) {
  1102. return NULL;
  1103. }
  1104. /*
  1105. * We have to do the hash-walk again, to avoid races
  1106. * with another CPU:
  1107. */
  1108. hlist_for_each_entry_rcu(class, hash_head, hash_entry) {
  1109. if (class->key == key)
  1110. goto out_unlock_set;
  1111. }
  1112. init_data_structures_once();
  1113. /* Allocate a new lock class and add it to the hash. */
  1114. class = list_first_entry_or_null(&free_lock_classes, typeof(*class),
  1115. lock_entry);
  1116. if (!class) {
  1117. if (!debug_locks_off_graph_unlock()) {
  1118. return NULL;
  1119. }
  1120. nbcon_cpu_emergency_enter();
  1121. print_lockdep_off("BUG: MAX_LOCKDEP_KEYS too low!");
  1122. dump_stack();
  1123. nbcon_cpu_emergency_exit();
  1124. return NULL;
  1125. }
  1126. nr_lock_classes++;
  1127. __set_bit(class - lock_classes, lock_classes_in_use);
  1128. debug_atomic_inc(nr_unused_locks);
  1129. class->key = key;
  1130. class->name = lock->name;
  1131. class->subclass = subclass;
  1132. WARN_ON_ONCE(!list_empty(&class->locks_before));
  1133. WARN_ON_ONCE(!list_empty(&class->locks_after));
  1134. class->name_version = count_matching_names(class);
  1135. class->wait_type_inner = lock->wait_type_inner;
  1136. class->wait_type_outer = lock->wait_type_outer;
  1137. class->lock_type = lock->lock_type;
  1138. /*
  1139. * We use RCU's safe list-add method to make
  1140. * parallel walking of the hash-list safe:
  1141. */
  1142. hlist_add_head_rcu(&class->hash_entry, hash_head);
  1143. /*
  1144. * Remove the class from the free list and add it to the global list
  1145. * of classes.
  1146. */
  1147. list_move_tail(&class->lock_entry, &all_lock_classes);
  1148. idx = class - lock_classes;
  1149. if (idx > max_lock_class_idx)
  1150. max_lock_class_idx = idx;
  1151. if (verbose(class)) {
  1152. graph_unlock();
  1153. nbcon_cpu_emergency_enter();
  1154. printk("\nnew class %px: %s", class->key, class->name);
  1155. if (class->name_version > 1)
  1156. printk(KERN_CONT "#%d", class->name_version);
  1157. printk(KERN_CONT "\n");
  1158. dump_stack();
  1159. nbcon_cpu_emergency_exit();
  1160. if (!graph_lock()) {
  1161. return NULL;
  1162. }
  1163. }
  1164. out_unlock_set:
  1165. graph_unlock();
  1166. out_set_class_cache:
  1167. if (!subclass || force)
  1168. lock->class_cache[0] = class;
  1169. else if (subclass < NR_LOCKDEP_CACHING_CLASSES)
  1170. lock->class_cache[subclass] = class;
  1171. /*
  1172. * Hash collision, did we smoke some? We found a class with a matching
  1173. * hash but the subclass -- which is hashed in -- didn't match.
  1174. */
  1175. if (DEBUG_LOCKS_WARN_ON(class->subclass != subclass))
  1176. return NULL;
  1177. return class;
  1178. }
  1179. #ifdef CONFIG_PROVE_LOCKING
  1180. /*
  1181. * Allocate a lockdep entry. (assumes the graph_lock held, returns
  1182. * with NULL on failure)
  1183. */
  1184. static struct lock_list *alloc_list_entry(void)
  1185. {
  1186. int idx = find_first_zero_bit(list_entries_in_use,
  1187. ARRAY_SIZE(list_entries));
  1188. if (idx >= ARRAY_SIZE(list_entries)) {
  1189. if (!debug_locks_off_graph_unlock())
  1190. return NULL;
  1191. nbcon_cpu_emergency_enter();
  1192. print_lockdep_off("BUG: MAX_LOCKDEP_ENTRIES too low!");
  1193. dump_stack();
  1194. nbcon_cpu_emergency_exit();
  1195. return NULL;
  1196. }
  1197. nr_list_entries++;
  1198. __set_bit(idx, list_entries_in_use);
  1199. return list_entries + idx;
  1200. }
  1201. /*
  1202. * Add a new dependency to the head of the list:
  1203. */
  1204. static int add_lock_to_list(struct lock_class *this,
  1205. struct lock_class *links_to, struct list_head *head,
  1206. u16 distance, u8 dep,
  1207. const struct lock_trace *trace)
  1208. {
  1209. struct lock_list *entry;
  1210. /*
  1211. * Lock not present yet - get a new dependency struct and
  1212. * add it to the list:
  1213. */
  1214. entry = alloc_list_entry();
  1215. if (!entry)
  1216. return 0;
  1217. entry->class = this;
  1218. entry->links_to = links_to;
  1219. entry->dep = dep;
  1220. entry->distance = distance;
  1221. entry->trace = trace;
  1222. /*
  1223. * Both allocation and removal are done under the graph lock; but
  1224. * iteration is under RCU-sched; see look_up_lock_class() and
  1225. * lockdep_free_key_range().
  1226. */
  1227. list_add_tail_rcu(&entry->entry, head);
  1228. return 1;
  1229. }
  1230. /*
  1231. * For good efficiency of modular, we use power of 2
  1232. */
  1233. #define MAX_CIRCULAR_QUEUE_SIZE (1UL << CONFIG_LOCKDEP_CIRCULAR_QUEUE_BITS)
  1234. #define CQ_MASK (MAX_CIRCULAR_QUEUE_SIZE-1)
  1235. /*
  1236. * The circular_queue and helpers are used to implement graph
  1237. * breadth-first search (BFS) algorithm, by which we can determine
  1238. * whether there is a path from a lock to another. In deadlock checks,
  1239. * a path from the next lock to be acquired to a previous held lock
  1240. * indicates that adding the <prev> -> <next> lock dependency will
  1241. * produce a circle in the graph. Breadth-first search instead of
  1242. * depth-first search is used in order to find the shortest (circular)
  1243. * path.
  1244. */
  1245. struct circular_queue {
  1246. struct lock_list *element[MAX_CIRCULAR_QUEUE_SIZE];
  1247. unsigned int front, rear;
  1248. };
  1249. static struct circular_queue lock_cq;
  1250. unsigned int max_bfs_queue_depth;
  1251. static unsigned int lockdep_dependency_gen_id;
  1252. static inline void __cq_init(struct circular_queue *cq)
  1253. {
  1254. cq->front = cq->rear = 0;
  1255. lockdep_dependency_gen_id++;
  1256. }
  1257. static inline int __cq_empty(struct circular_queue *cq)
  1258. {
  1259. return (cq->front == cq->rear);
  1260. }
  1261. static inline int __cq_full(struct circular_queue *cq)
  1262. {
  1263. return ((cq->rear + 1) & CQ_MASK) == cq->front;
  1264. }
  1265. static inline int __cq_enqueue(struct circular_queue *cq, struct lock_list *elem)
  1266. {
  1267. if (__cq_full(cq))
  1268. return -1;
  1269. cq->element[cq->rear] = elem;
  1270. cq->rear = (cq->rear + 1) & CQ_MASK;
  1271. return 0;
  1272. }
  1273. /*
  1274. * Dequeue an element from the circular_queue, return a lock_list if
  1275. * the queue is not empty, or NULL if otherwise.
  1276. */
  1277. static inline struct lock_list * __cq_dequeue(struct circular_queue *cq)
  1278. {
  1279. struct lock_list * lock;
  1280. if (__cq_empty(cq))
  1281. return NULL;
  1282. lock = cq->element[cq->front];
  1283. cq->front = (cq->front + 1) & CQ_MASK;
  1284. return lock;
  1285. }
  1286. static inline unsigned int __cq_get_elem_count(struct circular_queue *cq)
  1287. {
  1288. return (cq->rear - cq->front) & CQ_MASK;
  1289. }
  1290. static inline void mark_lock_accessed(struct lock_list *lock)
  1291. {
  1292. lock->class->dep_gen_id = lockdep_dependency_gen_id;
  1293. }
  1294. static inline void visit_lock_entry(struct lock_list *lock,
  1295. struct lock_list *parent)
  1296. {
  1297. lock->parent = parent;
  1298. }
  1299. static inline unsigned long lock_accessed(struct lock_list *lock)
  1300. {
  1301. return lock->class->dep_gen_id == lockdep_dependency_gen_id;
  1302. }
  1303. static inline struct lock_list *get_lock_parent(struct lock_list *child)
  1304. {
  1305. return child->parent;
  1306. }
  1307. static inline int get_lock_depth(struct lock_list *child)
  1308. {
  1309. int depth = 0;
  1310. struct lock_list *parent;
  1311. while ((parent = get_lock_parent(child))) {
  1312. child = parent;
  1313. depth++;
  1314. }
  1315. return depth;
  1316. }
  1317. /*
  1318. * Return the forward or backward dependency list.
  1319. *
  1320. * @lock: the lock_list to get its class's dependency list
  1321. * @offset: the offset to struct lock_class to determine whether it is
  1322. * locks_after or locks_before
  1323. */
  1324. static inline struct list_head *get_dep_list(struct lock_list *lock, int offset)
  1325. {
  1326. void *lock_class = lock->class;
  1327. return lock_class + offset;
  1328. }
  1329. /*
  1330. * Return values of a bfs search:
  1331. *
  1332. * BFS_E* indicates an error
  1333. * BFS_R* indicates a result (match or not)
  1334. *
  1335. * BFS_EINVALIDNODE: Find a invalid node in the graph.
  1336. *
  1337. * BFS_EQUEUEFULL: The queue is full while doing the bfs.
  1338. *
  1339. * BFS_RMATCH: Find the matched node in the graph, and put that node into
  1340. * *@target_entry.
  1341. *
  1342. * BFS_RNOMATCH: Haven't found the matched node and keep *@target_entry
  1343. * _unchanged_.
  1344. */
  1345. enum bfs_result {
  1346. BFS_EINVALIDNODE = -2,
  1347. BFS_EQUEUEFULL = -1,
  1348. BFS_RMATCH = 0,
  1349. BFS_RNOMATCH = 1,
  1350. };
  1351. /*
  1352. * bfs_result < 0 means error
  1353. */
  1354. static inline bool bfs_error(enum bfs_result res)
  1355. {
  1356. return res < 0;
  1357. }
  1358. /*
  1359. * DEP_*_BIT in lock_list::dep
  1360. *
  1361. * For dependency @prev -> @next:
  1362. *
  1363. * SR: @prev is shared reader (->read != 0) and @next is recursive reader
  1364. * (->read == 2)
  1365. * ER: @prev is exclusive locker (->read == 0) and @next is recursive reader
  1366. * SN: @prev is shared reader and @next is non-recursive locker (->read != 2)
  1367. * EN: @prev is exclusive locker and @next is non-recursive locker
  1368. *
  1369. * Note that we define the value of DEP_*_BITs so that:
  1370. * bit0 is prev->read == 0
  1371. * bit1 is next->read != 2
  1372. */
  1373. #define DEP_SR_BIT (0 + (0 << 1)) /* 0 */
  1374. #define DEP_ER_BIT (1 + (0 << 1)) /* 1 */
  1375. #define DEP_SN_BIT (0 + (1 << 1)) /* 2 */
  1376. #define DEP_EN_BIT (1 + (1 << 1)) /* 3 */
  1377. #define DEP_SR_MASK (1U << (DEP_SR_BIT))
  1378. #define DEP_ER_MASK (1U << (DEP_ER_BIT))
  1379. #define DEP_SN_MASK (1U << (DEP_SN_BIT))
  1380. #define DEP_EN_MASK (1U << (DEP_EN_BIT))
  1381. static inline unsigned int
  1382. __calc_dep_bit(struct held_lock *prev, struct held_lock *next)
  1383. {
  1384. return (prev->read == 0) + ((next->read != 2) << 1);
  1385. }
  1386. static inline u8 calc_dep(struct held_lock *prev, struct held_lock *next)
  1387. {
  1388. return 1U << __calc_dep_bit(prev, next);
  1389. }
  1390. /*
  1391. * calculate the dep_bit for backwards edges. We care about whether @prev is
  1392. * shared and whether @next is recursive.
  1393. */
  1394. static inline unsigned int
  1395. __calc_dep_bitb(struct held_lock *prev, struct held_lock *next)
  1396. {
  1397. return (next->read != 2) + ((prev->read == 0) << 1);
  1398. }
  1399. static inline u8 calc_depb(struct held_lock *prev, struct held_lock *next)
  1400. {
  1401. return 1U << __calc_dep_bitb(prev, next);
  1402. }
  1403. /*
  1404. * Initialize a lock_list entry @lock belonging to @class as the root for a BFS
  1405. * search.
  1406. */
  1407. static inline void __bfs_init_root(struct lock_list *lock,
  1408. struct lock_class *class)
  1409. {
  1410. lock->class = class;
  1411. lock->parent = NULL;
  1412. lock->only_xr = 0;
  1413. }
  1414. /*
  1415. * Initialize a lock_list entry @lock based on a lock acquisition @hlock as the
  1416. * root for a BFS search.
  1417. *
  1418. * ->only_xr of the initial lock node is set to @hlock->read == 2, to make sure
  1419. * that <prev> -> @hlock and @hlock -> <whatever __bfs() found> is not -(*R)->
  1420. * and -(S*)->.
  1421. */
  1422. static inline void bfs_init_root(struct lock_list *lock,
  1423. struct held_lock *hlock)
  1424. {
  1425. __bfs_init_root(lock, hlock_class(hlock));
  1426. lock->only_xr = (hlock->read == 2);
  1427. }
  1428. /*
  1429. * Similar to bfs_init_root() but initialize the root for backwards BFS.
  1430. *
  1431. * ->only_xr of the initial lock node is set to @hlock->read != 0, to make sure
  1432. * that <next> -> @hlock and @hlock -> <whatever backwards BFS found> is not
  1433. * -(*S)-> and -(R*)-> (reverse order of -(*R)-> and -(S*)->).
  1434. */
  1435. static inline void bfs_init_rootb(struct lock_list *lock,
  1436. struct held_lock *hlock)
  1437. {
  1438. __bfs_init_root(lock, hlock_class(hlock));
  1439. lock->only_xr = (hlock->read != 0);
  1440. }
  1441. static inline struct lock_list *__bfs_next(struct lock_list *lock, int offset)
  1442. {
  1443. if (!lock || !lock->parent)
  1444. return NULL;
  1445. return list_next_or_null_rcu(get_dep_list(lock->parent, offset),
  1446. &lock->entry, struct lock_list, entry);
  1447. }
  1448. /*
  1449. * Breadth-First Search to find a strong path in the dependency graph.
  1450. *
  1451. * @source_entry: the source of the path we are searching for.
  1452. * @data: data used for the second parameter of @match function
  1453. * @match: match function for the search
  1454. * @target_entry: pointer to the target of a matched path
  1455. * @offset: the offset to struct lock_class to determine whether it is
  1456. * locks_after or locks_before
  1457. *
  1458. * We may have multiple edges (considering different kinds of dependencies,
  1459. * e.g. ER and SN) between two nodes in the dependency graph. But
  1460. * only the strong dependency path in the graph is relevant to deadlocks. A
  1461. * strong dependency path is a dependency path that doesn't have two adjacent
  1462. * dependencies as -(*R)-> -(S*)->, please see:
  1463. *
  1464. * Documentation/locking/lockdep-design.rst
  1465. *
  1466. * for more explanation of the definition of strong dependency paths
  1467. *
  1468. * In __bfs(), we only traverse in the strong dependency path:
  1469. *
  1470. * In lock_list::only_xr, we record whether the previous dependency only
  1471. * has -(*R)-> in the search, and if it does (prev only has -(*R)->), we
  1472. * filter out any -(S*)-> in the current dependency and after that, the
  1473. * ->only_xr is set according to whether we only have -(*R)-> left.
  1474. */
  1475. static enum bfs_result __bfs(struct lock_list *source_entry,
  1476. void *data,
  1477. bool (*match)(struct lock_list *entry, void *data),
  1478. bool (*skip)(struct lock_list *entry, void *data),
  1479. struct lock_list **target_entry,
  1480. int offset)
  1481. {
  1482. struct circular_queue *cq = &lock_cq;
  1483. struct lock_list *lock = NULL;
  1484. struct lock_list *entry;
  1485. struct list_head *head;
  1486. unsigned int cq_depth;
  1487. bool first;
  1488. lockdep_assert_locked();
  1489. __cq_init(cq);
  1490. __cq_enqueue(cq, source_entry);
  1491. while ((lock = __bfs_next(lock, offset)) || (lock = __cq_dequeue(cq))) {
  1492. if (!lock->class)
  1493. return BFS_EINVALIDNODE;
  1494. /*
  1495. * Step 1: check whether we already finish on this one.
  1496. *
  1497. * If we have visited all the dependencies from this @lock to
  1498. * others (iow, if we have visited all lock_list entries in
  1499. * @lock->class->locks_{after,before}) we skip, otherwise go
  1500. * and visit all the dependencies in the list and mark this
  1501. * list accessed.
  1502. */
  1503. if (lock_accessed(lock))
  1504. continue;
  1505. else
  1506. mark_lock_accessed(lock);
  1507. /*
  1508. * Step 2: check whether prev dependency and this form a strong
  1509. * dependency path.
  1510. */
  1511. if (lock->parent) { /* Parent exists, check prev dependency */
  1512. u8 dep = lock->dep;
  1513. bool prev_only_xr = lock->parent->only_xr;
  1514. /*
  1515. * Mask out all -(S*)-> if we only have *R in previous
  1516. * step, because -(*R)-> -(S*)-> don't make up a strong
  1517. * dependency.
  1518. */
  1519. if (prev_only_xr)
  1520. dep &= ~(DEP_SR_MASK | DEP_SN_MASK);
  1521. /* If nothing left, we skip */
  1522. if (!dep)
  1523. continue;
  1524. /* If there are only -(*R)-> left, set that for the next step */
  1525. lock->only_xr = !(dep & (DEP_SN_MASK | DEP_EN_MASK));
  1526. }
  1527. /*
  1528. * Step 3: we haven't visited this and there is a strong
  1529. * dependency path to this, so check with @match.
  1530. * If @skip is provide and returns true, we skip this
  1531. * lock (and any path this lock is in).
  1532. */
  1533. if (skip && skip(lock, data))
  1534. continue;
  1535. if (match(lock, data)) {
  1536. *target_entry = lock;
  1537. return BFS_RMATCH;
  1538. }
  1539. /*
  1540. * Step 4: if not match, expand the path by adding the
  1541. * forward or backwards dependencies in the search
  1542. *
  1543. */
  1544. first = true;
  1545. head = get_dep_list(lock, offset);
  1546. list_for_each_entry_rcu(entry, head, entry) {
  1547. visit_lock_entry(entry, lock);
  1548. /*
  1549. * Note we only enqueue the first of the list into the
  1550. * queue, because we can always find a sibling
  1551. * dependency from one (see __bfs_next()), as a result
  1552. * the space of queue is saved.
  1553. */
  1554. if (!first)
  1555. continue;
  1556. first = false;
  1557. if (__cq_enqueue(cq, entry))
  1558. return BFS_EQUEUEFULL;
  1559. cq_depth = __cq_get_elem_count(cq);
  1560. if (max_bfs_queue_depth < cq_depth)
  1561. max_bfs_queue_depth = cq_depth;
  1562. }
  1563. }
  1564. return BFS_RNOMATCH;
  1565. }
  1566. static inline enum bfs_result
  1567. __bfs_forwards(struct lock_list *src_entry,
  1568. void *data,
  1569. bool (*match)(struct lock_list *entry, void *data),
  1570. bool (*skip)(struct lock_list *entry, void *data),
  1571. struct lock_list **target_entry)
  1572. {
  1573. return __bfs(src_entry, data, match, skip, target_entry,
  1574. offsetof(struct lock_class, locks_after));
  1575. }
  1576. static inline enum bfs_result
  1577. __bfs_backwards(struct lock_list *src_entry,
  1578. void *data,
  1579. bool (*match)(struct lock_list *entry, void *data),
  1580. bool (*skip)(struct lock_list *entry, void *data),
  1581. struct lock_list **target_entry)
  1582. {
  1583. return __bfs(src_entry, data, match, skip, target_entry,
  1584. offsetof(struct lock_class, locks_before));
  1585. }
  1586. static void print_lock_trace(const struct lock_trace *trace,
  1587. unsigned int spaces)
  1588. {
  1589. stack_trace_print(trace->entries, trace->nr_entries, spaces);
  1590. }
  1591. /*
  1592. * Print a dependency chain entry (this is only done when a deadlock
  1593. * has been detected):
  1594. */
  1595. static noinline void
  1596. print_circular_bug_entry(struct lock_list *target, int depth)
  1597. {
  1598. if (debug_locks_silent)
  1599. return;
  1600. printk("\n-> #%u", depth);
  1601. print_lock_name(NULL, target->class);
  1602. printk(KERN_CONT ":\n");
  1603. print_lock_trace(target->trace, 6);
  1604. }
  1605. static void
  1606. print_circular_lock_scenario(struct held_lock *src,
  1607. struct held_lock *tgt,
  1608. struct lock_list *prt)
  1609. {
  1610. struct lock_class *source = hlock_class(src);
  1611. struct lock_class *target = hlock_class(tgt);
  1612. struct lock_class *parent = prt->class;
  1613. int src_read = src->read;
  1614. int tgt_read = tgt->read;
  1615. /*
  1616. * A direct locking problem where unsafe_class lock is taken
  1617. * directly by safe_class lock, then all we need to show
  1618. * is the deadlock scenario, as it is obvious that the
  1619. * unsafe lock is taken under the safe lock.
  1620. *
  1621. * But if there is a chain instead, where the safe lock takes
  1622. * an intermediate lock (middle_class) where this lock is
  1623. * not the same as the safe lock, then the lock chain is
  1624. * used to describe the problem. Otherwise we would need
  1625. * to show a different CPU case for each link in the chain
  1626. * from the safe_class lock to the unsafe_class lock.
  1627. */
  1628. if (parent != source) {
  1629. printk("Chain exists of:\n ");
  1630. __print_lock_name(src, source);
  1631. printk(KERN_CONT " --> ");
  1632. __print_lock_name(NULL, parent);
  1633. printk(KERN_CONT " --> ");
  1634. __print_lock_name(tgt, target);
  1635. printk(KERN_CONT "\n\n");
  1636. }
  1637. printk(" Possible unsafe locking scenario:\n\n");
  1638. printk(" CPU0 CPU1\n");
  1639. printk(" ---- ----\n");
  1640. if (tgt_read != 0)
  1641. printk(" rlock(");
  1642. else
  1643. printk(" lock(");
  1644. __print_lock_name(tgt, target);
  1645. printk(KERN_CONT ");\n");
  1646. printk(" lock(");
  1647. __print_lock_name(NULL, parent);
  1648. printk(KERN_CONT ");\n");
  1649. printk(" lock(");
  1650. __print_lock_name(tgt, target);
  1651. printk(KERN_CONT ");\n");
  1652. if (src_read != 0)
  1653. printk(" rlock(");
  1654. else if (src->sync)
  1655. printk(" sync(");
  1656. else
  1657. printk(" lock(");
  1658. __print_lock_name(src, source);
  1659. printk(KERN_CONT ");\n");
  1660. printk("\n *** DEADLOCK ***\n\n");
  1661. }
  1662. /*
  1663. * When a circular dependency is detected, print the
  1664. * header first:
  1665. */
  1666. static noinline void
  1667. print_circular_bug_header(struct lock_list *entry, unsigned int depth,
  1668. struct held_lock *check_src,
  1669. struct held_lock *check_tgt)
  1670. {
  1671. struct task_struct *curr = current;
  1672. if (debug_locks_silent)
  1673. return;
  1674. pr_warn("\n");
  1675. pr_warn("======================================================\n");
  1676. pr_warn("WARNING: possible circular locking dependency detected\n");
  1677. print_kernel_ident();
  1678. pr_warn("------------------------------------------------------\n");
  1679. pr_warn("%s/%d is trying to acquire lock:\n",
  1680. curr->comm, task_pid_nr(curr));
  1681. print_lock(check_src);
  1682. pr_warn("\nbut task is already holding lock:\n");
  1683. print_lock(check_tgt);
  1684. pr_warn("\nwhich lock already depends on the new lock.\n\n");
  1685. pr_warn("\nthe existing dependency chain (in reverse order) is:\n");
  1686. print_circular_bug_entry(entry, depth);
  1687. }
  1688. /*
  1689. * We are about to add A -> B into the dependency graph, and in __bfs() a
  1690. * strong dependency path A -> .. -> B is found: hlock_class equals
  1691. * entry->class.
  1692. *
  1693. * If A -> .. -> B can replace A -> B in any __bfs() search (means the former
  1694. * is _stronger_ than or equal to the latter), we consider A -> B as redundant.
  1695. * For example if A -> .. -> B is -(EN)-> (i.e. A -(E*)-> .. -(*N)-> B), and A
  1696. * -> B is -(ER)-> or -(EN)->, then we don't need to add A -> B into the
  1697. * dependency graph, as any strong path ..-> A -> B ->.. we can get with
  1698. * having dependency A -> B, we could already get a equivalent path ..-> A ->
  1699. * .. -> B -> .. with A -> .. -> B. Therefore A -> B is redundant.
  1700. *
  1701. * We need to make sure both the start and the end of A -> .. -> B is not
  1702. * weaker than A -> B. For the start part, please see the comment in
  1703. * check_redundant(). For the end part, we need:
  1704. *
  1705. * Either
  1706. *
  1707. * a) A -> B is -(*R)-> (everything is not weaker than that)
  1708. *
  1709. * or
  1710. *
  1711. * b) A -> .. -> B is -(*N)-> (nothing is stronger than this)
  1712. *
  1713. */
  1714. static inline bool hlock_equal(struct lock_list *entry, void *data)
  1715. {
  1716. struct held_lock *hlock = (struct held_lock *)data;
  1717. return hlock_class(hlock) == entry->class && /* Found A -> .. -> B */
  1718. (hlock->read == 2 || /* A -> B is -(*R)-> */
  1719. !entry->only_xr); /* A -> .. -> B is -(*N)-> */
  1720. }
  1721. /*
  1722. * We are about to add B -> A into the dependency graph, and in __bfs() a
  1723. * strong dependency path A -> .. -> B is found: hlock_class equals
  1724. * entry->class.
  1725. *
  1726. * We will have a deadlock case (conflict) if A -> .. -> B -> A is a strong
  1727. * dependency cycle, that means:
  1728. *
  1729. * Either
  1730. *
  1731. * a) B -> A is -(E*)->
  1732. *
  1733. * or
  1734. *
  1735. * b) A -> .. -> B is -(*N)-> (i.e. A -> .. -(*N)-> B)
  1736. *
  1737. * as then we don't have -(*R)-> -(S*)-> in the cycle.
  1738. */
  1739. static inline bool hlock_conflict(struct lock_list *entry, void *data)
  1740. {
  1741. struct held_lock *hlock = (struct held_lock *)data;
  1742. return hlock_class(hlock) == entry->class && /* Found A -> .. -> B */
  1743. (hlock->read == 0 || /* B -> A is -(E*)-> */
  1744. !entry->only_xr); /* A -> .. -> B is -(*N)-> */
  1745. }
  1746. static noinline void print_circular_bug(struct lock_list *this,
  1747. struct lock_list *target,
  1748. struct held_lock *check_src,
  1749. struct held_lock *check_tgt)
  1750. {
  1751. struct task_struct *curr = current;
  1752. struct lock_list *parent;
  1753. struct lock_list *first_parent;
  1754. int depth;
  1755. if (!debug_locks_off_graph_unlock() || debug_locks_silent)
  1756. return;
  1757. this->trace = save_trace();
  1758. if (!this->trace)
  1759. return;
  1760. depth = get_lock_depth(target);
  1761. nbcon_cpu_emergency_enter();
  1762. print_circular_bug_header(target, depth, check_src, check_tgt);
  1763. parent = get_lock_parent(target);
  1764. first_parent = parent;
  1765. while (parent) {
  1766. print_circular_bug_entry(parent, --depth);
  1767. parent = get_lock_parent(parent);
  1768. }
  1769. printk("\nother info that might help us debug this:\n\n");
  1770. print_circular_lock_scenario(check_src, check_tgt,
  1771. first_parent);
  1772. lockdep_print_held_locks(curr);
  1773. printk("\nstack backtrace:\n");
  1774. dump_stack();
  1775. nbcon_cpu_emergency_exit();
  1776. }
  1777. static noinline void print_bfs_bug(int ret)
  1778. {
  1779. if (!debug_locks_off_graph_unlock())
  1780. return;
  1781. /*
  1782. * Breadth-first-search failed, graph got corrupted?
  1783. */
  1784. if (ret == BFS_EQUEUEFULL)
  1785. pr_warn("Increase LOCKDEP_CIRCULAR_QUEUE_BITS to avoid this warning:\n");
  1786. WARN(1, "lockdep bfs error:%d\n", ret);
  1787. }
  1788. static bool noop_count(struct lock_list *entry, void *data)
  1789. {
  1790. (*(unsigned long *)data)++;
  1791. return false;
  1792. }
  1793. static unsigned long __lockdep_count_forward_deps(struct lock_list *this)
  1794. {
  1795. unsigned long count = 0;
  1796. struct lock_list *target_entry;
  1797. __bfs_forwards(this, (void *)&count, noop_count, NULL, &target_entry);
  1798. return count;
  1799. }
  1800. unsigned long lockdep_count_forward_deps(struct lock_class *class)
  1801. {
  1802. unsigned long ret, flags;
  1803. struct lock_list this;
  1804. __bfs_init_root(&this, class);
  1805. raw_local_irq_save(flags);
  1806. lockdep_lock();
  1807. ret = __lockdep_count_forward_deps(&this);
  1808. lockdep_unlock();
  1809. raw_local_irq_restore(flags);
  1810. return ret;
  1811. }
  1812. static unsigned long __lockdep_count_backward_deps(struct lock_list *this)
  1813. {
  1814. unsigned long count = 0;
  1815. struct lock_list *target_entry;
  1816. __bfs_backwards(this, (void *)&count, noop_count, NULL, &target_entry);
  1817. return count;
  1818. }
  1819. unsigned long lockdep_count_backward_deps(struct lock_class *class)
  1820. {
  1821. unsigned long ret, flags;
  1822. struct lock_list this;
  1823. __bfs_init_root(&this, class);
  1824. raw_local_irq_save(flags);
  1825. lockdep_lock();
  1826. ret = __lockdep_count_backward_deps(&this);
  1827. lockdep_unlock();
  1828. raw_local_irq_restore(flags);
  1829. return ret;
  1830. }
  1831. /*
  1832. * Check that the dependency graph starting at <src> can lead to
  1833. * <target> or not.
  1834. */
  1835. static noinline enum bfs_result
  1836. check_path(struct held_lock *target, struct lock_list *src_entry,
  1837. bool (*match)(struct lock_list *entry, void *data),
  1838. bool (*skip)(struct lock_list *entry, void *data),
  1839. struct lock_list **target_entry)
  1840. {
  1841. enum bfs_result ret;
  1842. ret = __bfs_forwards(src_entry, target, match, skip, target_entry);
  1843. if (unlikely(bfs_error(ret)))
  1844. print_bfs_bug(ret);
  1845. return ret;
  1846. }
  1847. static void print_deadlock_bug(struct task_struct *, struct held_lock *, struct held_lock *);
  1848. /*
  1849. * Prove that the dependency graph starting at <src> can not
  1850. * lead to <target>. If it can, there is a circle when adding
  1851. * <target> -> <src> dependency.
  1852. *
  1853. * Print an error and return BFS_RMATCH if it does.
  1854. */
  1855. static noinline enum bfs_result
  1856. check_noncircular(struct held_lock *src, struct held_lock *target,
  1857. struct lock_trace **const trace)
  1858. {
  1859. enum bfs_result ret;
  1860. struct lock_list *target_entry;
  1861. struct lock_list src_entry;
  1862. bfs_init_root(&src_entry, src);
  1863. debug_atomic_inc(nr_cyclic_checks);
  1864. ret = check_path(target, &src_entry, hlock_conflict, NULL, &target_entry);
  1865. if (unlikely(ret == BFS_RMATCH)) {
  1866. if (!*trace) {
  1867. /*
  1868. * If save_trace fails here, the printing might
  1869. * trigger a WARN but because of the !nr_entries it
  1870. * should not do bad things.
  1871. */
  1872. *trace = save_trace();
  1873. }
  1874. if (src->class_idx == target->class_idx)
  1875. print_deadlock_bug(current, src, target);
  1876. else
  1877. print_circular_bug(&src_entry, target_entry, src, target);
  1878. }
  1879. return ret;
  1880. }
  1881. #ifdef CONFIG_TRACE_IRQFLAGS
  1882. /*
  1883. * Forwards and backwards subgraph searching, for the purposes of
  1884. * proving that two subgraphs can be connected by a new dependency
  1885. * without creating any illegal irq-safe -> irq-unsafe lock dependency.
  1886. *
  1887. * A irq safe->unsafe deadlock happens with the following conditions:
  1888. *
  1889. * 1) We have a strong dependency path A -> ... -> B
  1890. *
  1891. * 2) and we have ENABLED_IRQ usage of B and USED_IN_IRQ usage of A, therefore
  1892. * irq can create a new dependency B -> A (consider the case that a holder
  1893. * of B gets interrupted by an irq whose handler will try to acquire A).
  1894. *
  1895. * 3) the dependency circle A -> ... -> B -> A we get from 1) and 2) is a
  1896. * strong circle:
  1897. *
  1898. * For the usage bits of B:
  1899. * a) if A -> B is -(*N)->, then B -> A could be any type, so any
  1900. * ENABLED_IRQ usage suffices.
  1901. * b) if A -> B is -(*R)->, then B -> A must be -(E*)->, so only
  1902. * ENABLED_IRQ_*_READ usage suffices.
  1903. *
  1904. * For the usage bits of A:
  1905. * c) if A -> B is -(E*)->, then B -> A could be any type, so any
  1906. * USED_IN_IRQ usage suffices.
  1907. * d) if A -> B is -(S*)->, then B -> A must be -(*N)->, so only
  1908. * USED_IN_IRQ_*_READ usage suffices.
  1909. */
  1910. /*
  1911. * There is a strong dependency path in the dependency graph: A -> B, and now
  1912. * we need to decide which usage bit of A should be accumulated to detect
  1913. * safe->unsafe bugs.
  1914. *
  1915. * Note that usage_accumulate() is used in backwards search, so ->only_xr
  1916. * stands for whether A -> B only has -(S*)-> (in this case ->only_xr is true).
  1917. *
  1918. * As above, if only_xr is false, which means A -> B has -(E*)-> dependency
  1919. * path, any usage of A should be considered. Otherwise, we should only
  1920. * consider _READ usage.
  1921. */
  1922. static inline bool usage_accumulate(struct lock_list *entry, void *mask)
  1923. {
  1924. if (!entry->only_xr)
  1925. *(unsigned long *)mask |= entry->class->usage_mask;
  1926. else /* Mask out _READ usage bits */
  1927. *(unsigned long *)mask |= (entry->class->usage_mask & LOCKF_IRQ);
  1928. return false;
  1929. }
  1930. /*
  1931. * There is a strong dependency path in the dependency graph: A -> B, and now
  1932. * we need to decide which usage bit of B conflicts with the usage bits of A,
  1933. * i.e. which usage bit of B may introduce safe->unsafe deadlocks.
  1934. *
  1935. * As above, if only_xr is false, which means A -> B has -(*N)-> dependency
  1936. * path, any usage of B should be considered. Otherwise, we should only
  1937. * consider _READ usage.
  1938. */
  1939. static inline bool usage_match(struct lock_list *entry, void *mask)
  1940. {
  1941. if (!entry->only_xr)
  1942. return !!(entry->class->usage_mask & *(unsigned long *)mask);
  1943. else /* Mask out _READ usage bits */
  1944. return !!((entry->class->usage_mask & LOCKF_IRQ) & *(unsigned long *)mask);
  1945. }
  1946. static inline bool usage_skip(struct lock_list *entry, void *mask)
  1947. {
  1948. if (entry->class->lock_type == LD_LOCK_NORMAL)
  1949. return false;
  1950. /*
  1951. * Skip local_lock() for irq inversion detection.
  1952. *
  1953. * For !RT, local_lock() is not a real lock, so it won't carry any
  1954. * dependency.
  1955. *
  1956. * For RT, an irq inversion happens when we have lock A and B, and on
  1957. * some CPU we can have:
  1958. *
  1959. * lock(A);
  1960. * <interrupted>
  1961. * lock(B);
  1962. *
  1963. * where lock(B) cannot sleep, and we have a dependency B -> ... -> A.
  1964. *
  1965. * Now we prove local_lock() cannot exist in that dependency. First we
  1966. * have the observation for any lock chain L1 -> ... -> Ln, for any
  1967. * 1 <= i <= n, Li.inner_wait_type <= L1.inner_wait_type, otherwise
  1968. * wait context check will complain. And since B is not a sleep lock,
  1969. * therefore B.inner_wait_type >= 2, and since the inner_wait_type of
  1970. * local_lock() is 3, which is greater than 2, therefore there is no
  1971. * way the local_lock() exists in the dependency B -> ... -> A.
  1972. *
  1973. * As a result, we will skip local_lock(), when we search for irq
  1974. * inversion bugs.
  1975. */
  1976. if (entry->class->lock_type == LD_LOCK_PERCPU &&
  1977. DEBUG_LOCKS_WARN_ON(entry->class->wait_type_inner < LD_WAIT_CONFIG))
  1978. return false;
  1979. /*
  1980. * Skip WAIT_OVERRIDE for irq inversion detection -- it's not actually
  1981. * a lock and only used to override the wait_type.
  1982. */
  1983. return true;
  1984. }
  1985. /*
  1986. * Find a node in the forwards-direction dependency sub-graph starting
  1987. * at @root->class that matches @bit.
  1988. *
  1989. * Return BFS_MATCH if such a node exists in the subgraph, and put that node
  1990. * into *@target_entry.
  1991. */
  1992. static enum bfs_result
  1993. find_usage_forwards(struct lock_list *root, unsigned long usage_mask,
  1994. struct lock_list **target_entry)
  1995. {
  1996. enum bfs_result result;
  1997. debug_atomic_inc(nr_find_usage_forwards_checks);
  1998. result = __bfs_forwards(root, &usage_mask, usage_match, usage_skip, target_entry);
  1999. return result;
  2000. }
  2001. /*
  2002. * Find a node in the backwards-direction dependency sub-graph starting
  2003. * at @root->class that matches @bit.
  2004. */
  2005. static enum bfs_result
  2006. find_usage_backwards(struct lock_list *root, unsigned long usage_mask,
  2007. struct lock_list **target_entry)
  2008. {
  2009. enum bfs_result result;
  2010. debug_atomic_inc(nr_find_usage_backwards_checks);
  2011. result = __bfs_backwards(root, &usage_mask, usage_match, usage_skip, target_entry);
  2012. return result;
  2013. }
  2014. static void print_lock_class_header(struct lock_class *class, int depth)
  2015. {
  2016. int bit;
  2017. printk("%*s->", depth, "");
  2018. print_lock_name(NULL, class);
  2019. #ifdef CONFIG_DEBUG_LOCKDEP
  2020. printk(KERN_CONT " ops: %lu", debug_class_ops_read(class));
  2021. #endif
  2022. printk(KERN_CONT " {\n");
  2023. for (bit = 0; bit < LOCK_TRACE_STATES; bit++) {
  2024. if (class->usage_mask & (1 << bit)) {
  2025. int len = depth;
  2026. len += printk("%*s %s", depth, "", usage_str[bit]);
  2027. len += printk(KERN_CONT " at:\n");
  2028. print_lock_trace(class->usage_traces[bit], len);
  2029. }
  2030. }
  2031. printk("%*s }\n", depth, "");
  2032. printk("%*s ... key at: [<%px>] %pS\n",
  2033. depth, "", class->key, class->key);
  2034. }
  2035. /*
  2036. * Dependency path printing:
  2037. *
  2038. * After BFS we get a lock dependency path (linked via ->parent of lock_list),
  2039. * printing out each lock in the dependency path will help on understanding how
  2040. * the deadlock could happen. Here are some details about dependency path
  2041. * printing:
  2042. *
  2043. * 1) A lock_list can be either forwards or backwards for a lock dependency,
  2044. * for a lock dependency A -> B, there are two lock_lists:
  2045. *
  2046. * a) lock_list in the ->locks_after list of A, whose ->class is B and
  2047. * ->links_to is A. In this case, we can say the lock_list is
  2048. * "A -> B" (forwards case).
  2049. *
  2050. * b) lock_list in the ->locks_before list of B, whose ->class is A
  2051. * and ->links_to is B. In this case, we can say the lock_list is
  2052. * "B <- A" (bacwards case).
  2053. *
  2054. * The ->trace of both a) and b) point to the call trace where B was
  2055. * acquired with A held.
  2056. *
  2057. * 2) A "helper" lock_list is introduced during BFS, this lock_list doesn't
  2058. * represent a certain lock dependency, it only provides an initial entry
  2059. * for BFS. For example, BFS may introduce a "helper" lock_list whose
  2060. * ->class is A, as a result BFS will search all dependencies starting with
  2061. * A, e.g. A -> B or A -> C.
  2062. *
  2063. * The notation of a forwards helper lock_list is like "-> A", which means
  2064. * we should search the forwards dependencies starting with "A", e.g A -> B
  2065. * or A -> C.
  2066. *
  2067. * The notation of a bacwards helper lock_list is like "<- B", which means
  2068. * we should search the backwards dependencies ending with "B", e.g.
  2069. * B <- A or B <- C.
  2070. */
  2071. /*
  2072. * printk the shortest lock dependencies from @root to @leaf in reverse order.
  2073. *
  2074. * We have a lock dependency path as follow:
  2075. *
  2076. * @root @leaf
  2077. * | |
  2078. * V V
  2079. * ->parent ->parent
  2080. * | lock_list | <--------- | lock_list | ... | lock_list | <--------- | lock_list |
  2081. * | -> L1 | | L1 -> L2 | ... |Ln-2 -> Ln-1| | Ln-1 -> Ln|
  2082. *
  2083. * , so it's natural that we start from @leaf and print every ->class and
  2084. * ->trace until we reach the @root.
  2085. */
  2086. static void __used
  2087. print_shortest_lock_dependencies(struct lock_list *leaf,
  2088. struct lock_list *root)
  2089. {
  2090. struct lock_list *entry = leaf;
  2091. int depth;
  2092. /*compute depth from generated tree by BFS*/
  2093. depth = get_lock_depth(leaf);
  2094. do {
  2095. print_lock_class_header(entry->class, depth);
  2096. printk("%*s ... acquired at:\n", depth, "");
  2097. print_lock_trace(entry->trace, 2);
  2098. printk("\n");
  2099. if (depth == 0 && (entry != root)) {
  2100. printk("lockdep:%s bad path found in chain graph\n", __func__);
  2101. break;
  2102. }
  2103. entry = get_lock_parent(entry);
  2104. depth--;
  2105. } while (entry && (depth >= 0));
  2106. }
  2107. /*
  2108. * printk the shortest lock dependencies from @leaf to @root.
  2109. *
  2110. * We have a lock dependency path (from a backwards search) as follow:
  2111. *
  2112. * @leaf @root
  2113. * | |
  2114. * V V
  2115. * ->parent ->parent
  2116. * | lock_list | ---------> | lock_list | ... | lock_list | ---------> | lock_list |
  2117. * | L2 <- L1 | | L3 <- L2 | ... | Ln <- Ln-1 | | <- Ln |
  2118. *
  2119. * , so when we iterate from @leaf to @root, we actually print the lock
  2120. * dependency path L1 -> L2 -> .. -> Ln in the non-reverse order.
  2121. *
  2122. * Another thing to notice here is that ->class of L2 <- L1 is L1, while the
  2123. * ->trace of L2 <- L1 is the call trace of L2, in fact we don't have the call
  2124. * trace of L1 in the dependency path, which is alright, because most of the
  2125. * time we can figure out where L1 is held from the call trace of L2.
  2126. */
  2127. static void __used
  2128. print_shortest_lock_dependencies_backwards(struct lock_list *leaf,
  2129. struct lock_list *root)
  2130. {
  2131. struct lock_list *entry = leaf;
  2132. const struct lock_trace *trace = NULL;
  2133. int depth;
  2134. /*compute depth from generated tree by BFS*/
  2135. depth = get_lock_depth(leaf);
  2136. do {
  2137. print_lock_class_header(entry->class, depth);
  2138. if (trace) {
  2139. printk("%*s ... acquired at:\n", depth, "");
  2140. print_lock_trace(trace, 2);
  2141. printk("\n");
  2142. }
  2143. /*
  2144. * Record the pointer to the trace for the next lock_list
  2145. * entry, see the comments for the function.
  2146. */
  2147. trace = entry->trace;
  2148. if (depth == 0 && (entry != root)) {
  2149. printk("lockdep:%s bad path found in chain graph\n", __func__);
  2150. break;
  2151. }
  2152. entry = get_lock_parent(entry);
  2153. depth--;
  2154. } while (entry && (depth >= 0));
  2155. }
  2156. static void
  2157. print_irq_lock_scenario(struct lock_list *safe_entry,
  2158. struct lock_list *unsafe_entry,
  2159. struct lock_class *prev_class,
  2160. struct lock_class *next_class)
  2161. {
  2162. struct lock_class *safe_class = safe_entry->class;
  2163. struct lock_class *unsafe_class = unsafe_entry->class;
  2164. struct lock_class *middle_class = prev_class;
  2165. if (middle_class == safe_class)
  2166. middle_class = next_class;
  2167. /*
  2168. * A direct locking problem where unsafe_class lock is taken
  2169. * directly by safe_class lock, then all we need to show
  2170. * is the deadlock scenario, as it is obvious that the
  2171. * unsafe lock is taken under the safe lock.
  2172. *
  2173. * But if there is a chain instead, where the safe lock takes
  2174. * an intermediate lock (middle_class) where this lock is
  2175. * not the same as the safe lock, then the lock chain is
  2176. * used to describe the problem. Otherwise we would need
  2177. * to show a different CPU case for each link in the chain
  2178. * from the safe_class lock to the unsafe_class lock.
  2179. */
  2180. if (middle_class != unsafe_class) {
  2181. printk("Chain exists of:\n ");
  2182. __print_lock_name(NULL, safe_class);
  2183. printk(KERN_CONT " --> ");
  2184. __print_lock_name(NULL, middle_class);
  2185. printk(KERN_CONT " --> ");
  2186. __print_lock_name(NULL, unsafe_class);
  2187. printk(KERN_CONT "\n\n");
  2188. }
  2189. printk(" Possible interrupt unsafe locking scenario:\n\n");
  2190. printk(" CPU0 CPU1\n");
  2191. printk(" ---- ----\n");
  2192. printk(" lock(");
  2193. __print_lock_name(NULL, unsafe_class);
  2194. printk(KERN_CONT ");\n");
  2195. printk(" local_irq_disable();\n");
  2196. printk(" lock(");
  2197. __print_lock_name(NULL, safe_class);
  2198. printk(KERN_CONT ");\n");
  2199. printk(" lock(");
  2200. __print_lock_name(NULL, middle_class);
  2201. printk(KERN_CONT ");\n");
  2202. printk(" <Interrupt>\n");
  2203. printk(" lock(");
  2204. __print_lock_name(NULL, safe_class);
  2205. printk(KERN_CONT ");\n");
  2206. printk("\n *** DEADLOCK ***\n\n");
  2207. }
  2208. static void
  2209. print_bad_irq_dependency(struct task_struct *curr,
  2210. struct lock_list *prev_root,
  2211. struct lock_list *next_root,
  2212. struct lock_list *backwards_entry,
  2213. struct lock_list *forwards_entry,
  2214. struct held_lock *prev,
  2215. struct held_lock *next,
  2216. enum lock_usage_bit bit1,
  2217. enum lock_usage_bit bit2,
  2218. const char *irqclass)
  2219. {
  2220. if (!debug_locks_off_graph_unlock() || debug_locks_silent)
  2221. return;
  2222. nbcon_cpu_emergency_enter();
  2223. pr_warn("\n");
  2224. pr_warn("=====================================================\n");
  2225. pr_warn("WARNING: %s-safe -> %s-unsafe lock order detected\n",
  2226. irqclass, irqclass);
  2227. print_kernel_ident();
  2228. pr_warn("-----------------------------------------------------\n");
  2229. pr_warn("%s/%d [HC%u[%lu]:SC%u[%lu]:HE%u:SE%u] is trying to acquire:\n",
  2230. curr->comm, task_pid_nr(curr),
  2231. lockdep_hardirq_context(), hardirq_count() >> HARDIRQ_SHIFT,
  2232. curr->softirq_context, softirq_count() >> SOFTIRQ_SHIFT,
  2233. lockdep_hardirqs_enabled(),
  2234. curr->softirqs_enabled);
  2235. print_lock(next);
  2236. pr_warn("\nand this task is already holding:\n");
  2237. print_lock(prev);
  2238. pr_warn("which would create a new lock dependency:\n");
  2239. print_lock_name(prev, hlock_class(prev));
  2240. pr_cont(" ->");
  2241. print_lock_name(next, hlock_class(next));
  2242. pr_cont("\n");
  2243. pr_warn("\nbut this new dependency connects a %s-irq-safe lock:\n",
  2244. irqclass);
  2245. print_lock_name(NULL, backwards_entry->class);
  2246. pr_warn("\n... which became %s-irq-safe at:\n", irqclass);
  2247. print_lock_trace(backwards_entry->class->usage_traces[bit1], 1);
  2248. pr_warn("\nto a %s-irq-unsafe lock:\n", irqclass);
  2249. print_lock_name(NULL, forwards_entry->class);
  2250. pr_warn("\n... which became %s-irq-unsafe at:\n", irqclass);
  2251. pr_warn("...");
  2252. print_lock_trace(forwards_entry->class->usage_traces[bit2], 1);
  2253. pr_warn("\nother info that might help us debug this:\n\n");
  2254. print_irq_lock_scenario(backwards_entry, forwards_entry,
  2255. hlock_class(prev), hlock_class(next));
  2256. lockdep_print_held_locks(curr);
  2257. pr_warn("\nthe dependencies between %s-irq-safe lock and the holding lock:\n", irqclass);
  2258. print_shortest_lock_dependencies_backwards(backwards_entry, prev_root);
  2259. pr_warn("\nthe dependencies between the lock to be acquired");
  2260. pr_warn(" and %s-irq-unsafe lock:\n", irqclass);
  2261. next_root->trace = save_trace();
  2262. if (!next_root->trace)
  2263. goto out;
  2264. print_shortest_lock_dependencies(forwards_entry, next_root);
  2265. pr_warn("\nstack backtrace:\n");
  2266. dump_stack();
  2267. out:
  2268. nbcon_cpu_emergency_exit();
  2269. }
  2270. static const char *state_names[] = {
  2271. #define LOCKDEP_STATE(__STATE) \
  2272. __stringify(__STATE),
  2273. #include "lockdep_states.h"
  2274. #undef LOCKDEP_STATE
  2275. };
  2276. static const char *state_rnames[] = {
  2277. #define LOCKDEP_STATE(__STATE) \
  2278. __stringify(__STATE)"-READ",
  2279. #include "lockdep_states.h"
  2280. #undef LOCKDEP_STATE
  2281. };
  2282. static inline const char *state_name(enum lock_usage_bit bit)
  2283. {
  2284. if (bit & LOCK_USAGE_READ_MASK)
  2285. return state_rnames[bit >> LOCK_USAGE_DIR_MASK];
  2286. else
  2287. return state_names[bit >> LOCK_USAGE_DIR_MASK];
  2288. }
  2289. /*
  2290. * The bit number is encoded like:
  2291. *
  2292. * bit0: 0 exclusive, 1 read lock
  2293. * bit1: 0 used in irq, 1 irq enabled
  2294. * bit2-n: state
  2295. */
  2296. static int exclusive_bit(int new_bit)
  2297. {
  2298. int state = new_bit & LOCK_USAGE_STATE_MASK;
  2299. int dir = new_bit & LOCK_USAGE_DIR_MASK;
  2300. /*
  2301. * keep state, bit flip the direction and strip read.
  2302. */
  2303. return state | (dir ^ LOCK_USAGE_DIR_MASK);
  2304. }
  2305. /*
  2306. * Observe that when given a bitmask where each bitnr is encoded as above, a
  2307. * right shift of the mask transforms the individual bitnrs as -1 and
  2308. * conversely, a left shift transforms into +1 for the individual bitnrs.
  2309. *
  2310. * So for all bits whose number have LOCK_ENABLED_* set (bitnr1 == 1), we can
  2311. * create the mask with those bit numbers using LOCK_USED_IN_* (bitnr1 == 0)
  2312. * instead by subtracting the bit number by 2, or shifting the mask right by 2.
  2313. *
  2314. * Similarly, bitnr1 == 0 becomes bitnr1 == 1 by adding 2, or shifting left 2.
  2315. *
  2316. * So split the mask (note that LOCKF_ENABLED_IRQ_ALL|LOCKF_USED_IN_IRQ_ALL is
  2317. * all bits set) and recompose with bitnr1 flipped.
  2318. */
  2319. static unsigned long invert_dir_mask(unsigned long mask)
  2320. {
  2321. unsigned long excl = 0;
  2322. /* Invert dir */
  2323. excl |= (mask & LOCKF_ENABLED_IRQ_ALL) >> LOCK_USAGE_DIR_MASK;
  2324. excl |= (mask & LOCKF_USED_IN_IRQ_ALL) << LOCK_USAGE_DIR_MASK;
  2325. return excl;
  2326. }
  2327. /*
  2328. * Note that a LOCK_ENABLED_IRQ_*_READ usage and a LOCK_USED_IN_IRQ_*_READ
  2329. * usage may cause deadlock too, for example:
  2330. *
  2331. * P1 P2
  2332. * <irq disabled>
  2333. * write_lock(l1); <irq enabled>
  2334. * read_lock(l2);
  2335. * write_lock(l2);
  2336. * <in irq>
  2337. * read_lock(l1);
  2338. *
  2339. * , in above case, l1 will be marked as LOCK_USED_IN_IRQ_HARDIRQ_READ and l2
  2340. * will marked as LOCK_ENABLE_IRQ_HARDIRQ_READ, and this is a possible
  2341. * deadlock.
  2342. *
  2343. * In fact, all of the following cases may cause deadlocks:
  2344. *
  2345. * LOCK_USED_IN_IRQ_* -> LOCK_ENABLED_IRQ_*
  2346. * LOCK_USED_IN_IRQ_*_READ -> LOCK_ENABLED_IRQ_*
  2347. * LOCK_USED_IN_IRQ_* -> LOCK_ENABLED_IRQ_*_READ
  2348. * LOCK_USED_IN_IRQ_*_READ -> LOCK_ENABLED_IRQ_*_READ
  2349. *
  2350. * As a result, to calculate the "exclusive mask", first we invert the
  2351. * direction (USED_IN/ENABLED) of the original mask, and 1) for all bits with
  2352. * bitnr0 set (LOCK_*_READ), add those with bitnr0 cleared (LOCK_*). 2) for all
  2353. * bits with bitnr0 cleared (LOCK_*_READ), add those with bitnr0 set (LOCK_*).
  2354. */
  2355. static unsigned long exclusive_mask(unsigned long mask)
  2356. {
  2357. unsigned long excl = invert_dir_mask(mask);
  2358. excl |= (excl & LOCKF_IRQ_READ) >> LOCK_USAGE_READ_MASK;
  2359. excl |= (excl & LOCKF_IRQ) << LOCK_USAGE_READ_MASK;
  2360. return excl;
  2361. }
  2362. /*
  2363. * Retrieve the _possible_ original mask to which @mask is
  2364. * exclusive. Ie: this is the opposite of exclusive_mask().
  2365. * Note that 2 possible original bits can match an exclusive
  2366. * bit: one has LOCK_USAGE_READ_MASK set, the other has it
  2367. * cleared. So both are returned for each exclusive bit.
  2368. */
  2369. static unsigned long original_mask(unsigned long mask)
  2370. {
  2371. unsigned long excl = invert_dir_mask(mask);
  2372. /* Include read in existing usages */
  2373. excl |= (excl & LOCKF_IRQ_READ) >> LOCK_USAGE_READ_MASK;
  2374. excl |= (excl & LOCKF_IRQ) << LOCK_USAGE_READ_MASK;
  2375. return excl;
  2376. }
  2377. /*
  2378. * Find the first pair of bit match between an original
  2379. * usage mask and an exclusive usage mask.
  2380. */
  2381. static int find_exclusive_match(unsigned long mask,
  2382. unsigned long excl_mask,
  2383. enum lock_usage_bit *bitp,
  2384. enum lock_usage_bit *excl_bitp)
  2385. {
  2386. int bit, excl, excl_read;
  2387. for_each_set_bit(bit, &mask, LOCK_USED) {
  2388. /*
  2389. * exclusive_bit() strips the read bit, however,
  2390. * LOCK_ENABLED_IRQ_*_READ may cause deadlocks too, so we need
  2391. * to search excl | LOCK_USAGE_READ_MASK as well.
  2392. */
  2393. excl = exclusive_bit(bit);
  2394. excl_read = excl | LOCK_USAGE_READ_MASK;
  2395. if (excl_mask & lock_flag(excl)) {
  2396. *bitp = bit;
  2397. *excl_bitp = excl;
  2398. return 0;
  2399. } else if (excl_mask & lock_flag(excl_read)) {
  2400. *bitp = bit;
  2401. *excl_bitp = excl_read;
  2402. return 0;
  2403. }
  2404. }
  2405. return -1;
  2406. }
  2407. /*
  2408. * Prove that the new dependency does not connect a hardirq-safe(-read)
  2409. * lock with a hardirq-unsafe lock - to achieve this we search
  2410. * the backwards-subgraph starting at <prev>, and the
  2411. * forwards-subgraph starting at <next>:
  2412. */
  2413. static int check_irq_usage(struct task_struct *curr, struct held_lock *prev,
  2414. struct held_lock *next)
  2415. {
  2416. unsigned long usage_mask = 0, forward_mask, backward_mask;
  2417. enum lock_usage_bit forward_bit = 0, backward_bit = 0;
  2418. struct lock_list *target_entry1;
  2419. struct lock_list *target_entry;
  2420. struct lock_list this, that;
  2421. enum bfs_result ret;
  2422. /*
  2423. * Step 1: gather all hard/soft IRQs usages backward in an
  2424. * accumulated usage mask.
  2425. */
  2426. bfs_init_rootb(&this, prev);
  2427. ret = __bfs_backwards(&this, &usage_mask, usage_accumulate, usage_skip, NULL);
  2428. if (bfs_error(ret)) {
  2429. print_bfs_bug(ret);
  2430. return 0;
  2431. }
  2432. usage_mask &= LOCKF_USED_IN_IRQ_ALL;
  2433. if (!usage_mask)
  2434. return 1;
  2435. /*
  2436. * Step 2: find exclusive uses forward that match the previous
  2437. * backward accumulated mask.
  2438. */
  2439. forward_mask = exclusive_mask(usage_mask);
  2440. bfs_init_root(&that, next);
  2441. ret = find_usage_forwards(&that, forward_mask, &target_entry1);
  2442. if (bfs_error(ret)) {
  2443. print_bfs_bug(ret);
  2444. return 0;
  2445. }
  2446. if (ret == BFS_RNOMATCH)
  2447. return 1;
  2448. /*
  2449. * Step 3: we found a bad match! Now retrieve a lock from the backward
  2450. * list whose usage mask matches the exclusive usage mask from the
  2451. * lock found on the forward list.
  2452. *
  2453. * Note, we should only keep the LOCKF_ENABLED_IRQ_ALL bits, considering
  2454. * the follow case:
  2455. *
  2456. * When trying to add A -> B to the graph, we find that there is a
  2457. * hardirq-safe L, that L -> ... -> A, and another hardirq-unsafe M,
  2458. * that B -> ... -> M. However M is **softirq-safe**, if we use exact
  2459. * invert bits of M's usage_mask, we will find another lock N that is
  2460. * **softirq-unsafe** and N -> ... -> A, however N -> .. -> M will not
  2461. * cause a inversion deadlock.
  2462. */
  2463. backward_mask = original_mask(target_entry1->class->usage_mask & LOCKF_ENABLED_IRQ_ALL);
  2464. ret = find_usage_backwards(&this, backward_mask, &target_entry);
  2465. if (bfs_error(ret)) {
  2466. print_bfs_bug(ret);
  2467. return 0;
  2468. }
  2469. if (DEBUG_LOCKS_WARN_ON(ret == BFS_RNOMATCH))
  2470. return 1;
  2471. /*
  2472. * Step 4: narrow down to a pair of incompatible usage bits
  2473. * and report it.
  2474. */
  2475. ret = find_exclusive_match(target_entry->class->usage_mask,
  2476. target_entry1->class->usage_mask,
  2477. &backward_bit, &forward_bit);
  2478. if (DEBUG_LOCKS_WARN_ON(ret == -1))
  2479. return 1;
  2480. print_bad_irq_dependency(curr, &this, &that,
  2481. target_entry, target_entry1,
  2482. prev, next,
  2483. backward_bit, forward_bit,
  2484. state_name(backward_bit));
  2485. return 0;
  2486. }
  2487. #else
  2488. static inline int check_irq_usage(struct task_struct *curr,
  2489. struct held_lock *prev, struct held_lock *next)
  2490. {
  2491. return 1;
  2492. }
  2493. static inline bool usage_skip(struct lock_list *entry, void *mask)
  2494. {
  2495. return false;
  2496. }
  2497. #endif /* CONFIG_TRACE_IRQFLAGS */
  2498. #ifdef CONFIG_LOCKDEP_SMALL
  2499. /*
  2500. * Check that the dependency graph starting at <src> can lead to
  2501. * <target> or not. If it can, <src> -> <target> dependency is already
  2502. * in the graph.
  2503. *
  2504. * Return BFS_RMATCH if it does, or BFS_RNOMATCH if it does not, return BFS_E* if
  2505. * any error appears in the bfs search.
  2506. */
  2507. static noinline enum bfs_result
  2508. check_redundant(struct held_lock *src, struct held_lock *target)
  2509. {
  2510. enum bfs_result ret;
  2511. struct lock_list *target_entry;
  2512. struct lock_list src_entry;
  2513. bfs_init_root(&src_entry, src);
  2514. /*
  2515. * Special setup for check_redundant().
  2516. *
  2517. * To report redundant, we need to find a strong dependency path that
  2518. * is equal to or stronger than <src> -> <target>. So if <src> is E,
  2519. * we need to let __bfs() only search for a path starting at a -(E*)->,
  2520. * we achieve this by setting the initial node's ->only_xr to true in
  2521. * that case. And if <prev> is S, we set initial ->only_xr to false
  2522. * because both -(S*)-> (equal) and -(E*)-> (stronger) are redundant.
  2523. */
  2524. src_entry.only_xr = src->read == 0;
  2525. debug_atomic_inc(nr_redundant_checks);
  2526. /*
  2527. * Note: we skip local_lock() for redundant check, because as the
  2528. * comment in usage_skip(), A -> local_lock() -> B and A -> B are not
  2529. * the same.
  2530. */
  2531. ret = check_path(target, &src_entry, hlock_equal, usage_skip, &target_entry);
  2532. if (ret == BFS_RMATCH)
  2533. debug_atomic_inc(nr_redundant);
  2534. return ret;
  2535. }
  2536. #else
  2537. static inline enum bfs_result
  2538. check_redundant(struct held_lock *src, struct held_lock *target)
  2539. {
  2540. return BFS_RNOMATCH;
  2541. }
  2542. #endif
  2543. static void inc_chains(int irq_context)
  2544. {
  2545. if (irq_context & LOCK_CHAIN_HARDIRQ_CONTEXT)
  2546. nr_hardirq_chains++;
  2547. else if (irq_context & LOCK_CHAIN_SOFTIRQ_CONTEXT)
  2548. nr_softirq_chains++;
  2549. else
  2550. nr_process_chains++;
  2551. }
  2552. static void dec_chains(int irq_context)
  2553. {
  2554. if (irq_context & LOCK_CHAIN_HARDIRQ_CONTEXT)
  2555. nr_hardirq_chains--;
  2556. else if (irq_context & LOCK_CHAIN_SOFTIRQ_CONTEXT)
  2557. nr_softirq_chains--;
  2558. else
  2559. nr_process_chains--;
  2560. }
  2561. static void
  2562. print_deadlock_scenario(struct held_lock *nxt, struct held_lock *prv)
  2563. {
  2564. struct lock_class *next = hlock_class(nxt);
  2565. struct lock_class *prev = hlock_class(prv);
  2566. printk(" Possible unsafe locking scenario:\n\n");
  2567. printk(" CPU0\n");
  2568. printk(" ----\n");
  2569. printk(" lock(");
  2570. __print_lock_name(prv, prev);
  2571. printk(KERN_CONT ");\n");
  2572. printk(" lock(");
  2573. __print_lock_name(nxt, next);
  2574. printk(KERN_CONT ");\n");
  2575. printk("\n *** DEADLOCK ***\n\n");
  2576. printk(" May be due to missing lock nesting notation\n\n");
  2577. }
  2578. static void
  2579. print_deadlock_bug(struct task_struct *curr, struct held_lock *prev,
  2580. struct held_lock *next)
  2581. {
  2582. struct lock_class *class = hlock_class(prev);
  2583. if (!debug_locks_off_graph_unlock() || debug_locks_silent)
  2584. return;
  2585. nbcon_cpu_emergency_enter();
  2586. pr_warn("\n");
  2587. pr_warn("============================================\n");
  2588. pr_warn("WARNING: possible recursive locking detected\n");
  2589. print_kernel_ident();
  2590. pr_warn("--------------------------------------------\n");
  2591. pr_warn("%s/%d is trying to acquire lock:\n",
  2592. curr->comm, task_pid_nr(curr));
  2593. print_lock(next);
  2594. pr_warn("\nbut task is already holding lock:\n");
  2595. print_lock(prev);
  2596. if (class->cmp_fn) {
  2597. pr_warn("and the lock comparison function returns %i:\n",
  2598. class->cmp_fn(prev->instance, next->instance));
  2599. }
  2600. pr_warn("\nother info that might help us debug this:\n");
  2601. print_deadlock_scenario(next, prev);
  2602. lockdep_print_held_locks(curr);
  2603. pr_warn("\nstack backtrace:\n");
  2604. dump_stack();
  2605. nbcon_cpu_emergency_exit();
  2606. }
  2607. /*
  2608. * Check whether we are holding such a class already.
  2609. *
  2610. * (Note that this has to be done separately, because the graph cannot
  2611. * detect such classes of deadlocks.)
  2612. *
  2613. * Returns: 0 on deadlock detected, 1 on OK, 2 if another lock with the same
  2614. * lock class is held but nest_lock is also held, i.e. we rely on the
  2615. * nest_lock to avoid the deadlock.
  2616. */
  2617. static int
  2618. check_deadlock(struct task_struct *curr, struct held_lock *next)
  2619. {
  2620. struct lock_class *class;
  2621. struct held_lock *prev;
  2622. struct held_lock *nest = NULL;
  2623. int i;
  2624. for (i = 0; i < curr->lockdep_depth; i++) {
  2625. prev = curr->held_locks + i;
  2626. if (prev->instance == next->nest_lock)
  2627. nest = prev;
  2628. if (hlock_class(prev) != hlock_class(next))
  2629. continue;
  2630. /*
  2631. * Allow read-after-read recursion of the same
  2632. * lock class (i.e. read_lock(lock)+read_lock(lock)):
  2633. */
  2634. if ((next->read == 2) && prev->read)
  2635. continue;
  2636. class = hlock_class(prev);
  2637. if (class->cmp_fn &&
  2638. class->cmp_fn(prev->instance, next->instance) < 0)
  2639. continue;
  2640. /*
  2641. * We're holding the nest_lock, which serializes this lock's
  2642. * nesting behaviour.
  2643. */
  2644. if (nest)
  2645. return 2;
  2646. print_deadlock_bug(curr, prev, next);
  2647. return 0;
  2648. }
  2649. return 1;
  2650. }
  2651. /*
  2652. * There was a chain-cache miss, and we are about to add a new dependency
  2653. * to a previous lock. We validate the following rules:
  2654. *
  2655. * - would the adding of the <prev> -> <next> dependency create a
  2656. * circular dependency in the graph? [== circular deadlock]
  2657. *
  2658. * - does the new prev->next dependency connect any hardirq-safe lock
  2659. * (in the full backwards-subgraph starting at <prev>) with any
  2660. * hardirq-unsafe lock (in the full forwards-subgraph starting at
  2661. * <next>)? [== illegal lock inversion with hardirq contexts]
  2662. *
  2663. * - does the new prev->next dependency connect any softirq-safe lock
  2664. * (in the full backwards-subgraph starting at <prev>) with any
  2665. * softirq-unsafe lock (in the full forwards-subgraph starting at
  2666. * <next>)? [== illegal lock inversion with softirq contexts]
  2667. *
  2668. * any of these scenarios could lead to a deadlock.
  2669. *
  2670. * Then if all the validations pass, we add the forwards and backwards
  2671. * dependency.
  2672. */
  2673. static int
  2674. check_prev_add(struct task_struct *curr, struct held_lock *prev,
  2675. struct held_lock *next, u16 distance,
  2676. struct lock_trace **const trace)
  2677. {
  2678. struct lock_list *entry;
  2679. enum bfs_result ret;
  2680. if (!hlock_class(prev)->key || !hlock_class(next)->key) {
  2681. /*
  2682. * The warning statements below may trigger a use-after-free
  2683. * of the class name. It is better to trigger a use-after free
  2684. * and to have the class name most of the time instead of not
  2685. * having the class name available.
  2686. */
  2687. WARN_ONCE(!debug_locks_silent && !hlock_class(prev)->key,
  2688. "Detected use-after-free of lock class %px/%s\n",
  2689. hlock_class(prev),
  2690. hlock_class(prev)->name);
  2691. WARN_ONCE(!debug_locks_silent && !hlock_class(next)->key,
  2692. "Detected use-after-free of lock class %px/%s\n",
  2693. hlock_class(next),
  2694. hlock_class(next)->name);
  2695. return 2;
  2696. }
  2697. if (prev->class_idx == next->class_idx) {
  2698. struct lock_class *class = hlock_class(prev);
  2699. if (class->cmp_fn &&
  2700. class->cmp_fn(prev->instance, next->instance) < 0)
  2701. return 2;
  2702. }
  2703. /*
  2704. * Prove that the new <prev> -> <next> dependency would not
  2705. * create a circular dependency in the graph. (We do this by
  2706. * a breadth-first search into the graph starting at <next>,
  2707. * and check whether we can reach <prev>.)
  2708. *
  2709. * The search is limited by the size of the circular queue (i.e.,
  2710. * MAX_CIRCULAR_QUEUE_SIZE) which keeps track of a breadth of nodes
  2711. * in the graph whose neighbours are to be checked.
  2712. */
  2713. ret = check_noncircular(next, prev, trace);
  2714. if (unlikely(bfs_error(ret) || ret == BFS_RMATCH))
  2715. return 0;
  2716. if (!check_irq_usage(curr, prev, next))
  2717. return 0;
  2718. /*
  2719. * Is the <prev> -> <next> dependency already present?
  2720. *
  2721. * (this may occur even though this is a new chain: consider
  2722. * e.g. the L1 -> L2 -> L3 -> L4 and the L5 -> L1 -> L2 -> L3
  2723. * chains - the second one will be new, but L1 already has
  2724. * L2 added to its dependency list, due to the first chain.)
  2725. */
  2726. list_for_each_entry(entry, &hlock_class(prev)->locks_after, entry) {
  2727. if (entry->class == hlock_class(next)) {
  2728. if (distance == 1)
  2729. entry->distance = 1;
  2730. entry->dep |= calc_dep(prev, next);
  2731. /*
  2732. * Also, update the reverse dependency in @next's
  2733. * ->locks_before list.
  2734. *
  2735. * Here we reuse @entry as the cursor, which is fine
  2736. * because we won't go to the next iteration of the
  2737. * outer loop:
  2738. *
  2739. * For normal cases, we return in the inner loop.
  2740. *
  2741. * If we fail to return, we have inconsistency, i.e.
  2742. * <prev>::locks_after contains <next> while
  2743. * <next>::locks_before doesn't contain <prev>. In
  2744. * that case, we return after the inner and indicate
  2745. * something is wrong.
  2746. */
  2747. list_for_each_entry(entry, &hlock_class(next)->locks_before, entry) {
  2748. if (entry->class == hlock_class(prev)) {
  2749. if (distance == 1)
  2750. entry->distance = 1;
  2751. entry->dep |= calc_depb(prev, next);
  2752. return 1;
  2753. }
  2754. }
  2755. /* <prev> is not found in <next>::locks_before */
  2756. return 0;
  2757. }
  2758. }
  2759. /*
  2760. * Is the <prev> -> <next> link redundant?
  2761. */
  2762. ret = check_redundant(prev, next);
  2763. if (bfs_error(ret))
  2764. return 0;
  2765. else if (ret == BFS_RMATCH)
  2766. return 2;
  2767. if (!*trace) {
  2768. *trace = save_trace();
  2769. if (!*trace)
  2770. return 0;
  2771. }
  2772. /*
  2773. * Ok, all validations passed, add the new lock
  2774. * to the previous lock's dependency list:
  2775. */
  2776. ret = add_lock_to_list(hlock_class(next), hlock_class(prev),
  2777. &hlock_class(prev)->locks_after, distance,
  2778. calc_dep(prev, next), *trace);
  2779. if (!ret)
  2780. return 0;
  2781. ret = add_lock_to_list(hlock_class(prev), hlock_class(next),
  2782. &hlock_class(next)->locks_before, distance,
  2783. calc_depb(prev, next), *trace);
  2784. if (!ret)
  2785. return 0;
  2786. return 2;
  2787. }
  2788. /*
  2789. * Add the dependency to all directly-previous locks that are 'relevant'.
  2790. * The ones that are relevant are (in increasing distance from curr):
  2791. * all consecutive trylock entries and the final non-trylock entry - or
  2792. * the end of this context's lock-chain - whichever comes first.
  2793. */
  2794. static int
  2795. check_prevs_add(struct task_struct *curr, struct held_lock *next)
  2796. {
  2797. struct lock_trace *trace = NULL;
  2798. int depth = curr->lockdep_depth;
  2799. struct held_lock *hlock;
  2800. /*
  2801. * Debugging checks.
  2802. *
  2803. * Depth must not be zero for a non-head lock:
  2804. */
  2805. if (!depth)
  2806. goto out_bug;
  2807. /*
  2808. * At least two relevant locks must exist for this
  2809. * to be a head:
  2810. */
  2811. if (curr->held_locks[depth].irq_context !=
  2812. curr->held_locks[depth-1].irq_context)
  2813. goto out_bug;
  2814. for (;;) {
  2815. u16 distance = curr->lockdep_depth - depth + 1;
  2816. hlock = curr->held_locks + depth - 1;
  2817. if (hlock->check) {
  2818. int ret = check_prev_add(curr, hlock, next, distance, &trace);
  2819. if (!ret)
  2820. return 0;
  2821. /*
  2822. * Stop after the first non-trylock entry,
  2823. * as non-trylock entries have added their
  2824. * own direct dependencies already, so this
  2825. * lock is connected to them indirectly:
  2826. */
  2827. if (!hlock->trylock)
  2828. break;
  2829. }
  2830. depth--;
  2831. /*
  2832. * End of lock-stack?
  2833. */
  2834. if (!depth)
  2835. break;
  2836. /*
  2837. * Stop the search if we cross into another context:
  2838. */
  2839. if (curr->held_locks[depth].irq_context !=
  2840. curr->held_locks[depth-1].irq_context)
  2841. break;
  2842. }
  2843. return 1;
  2844. out_bug:
  2845. if (!debug_locks_off_graph_unlock())
  2846. return 0;
  2847. /*
  2848. * Clearly we all shouldn't be here, but since we made it we
  2849. * can reliable say we messed up our state. See the above two
  2850. * gotos for reasons why we could possibly end up here.
  2851. */
  2852. WARN_ON(1);
  2853. return 0;
  2854. }
  2855. struct lock_chain lock_chains[MAX_LOCKDEP_CHAINS];
  2856. static DECLARE_BITMAP(lock_chains_in_use, MAX_LOCKDEP_CHAINS);
  2857. static u16 chain_hlocks[MAX_LOCKDEP_CHAIN_HLOCKS];
  2858. unsigned long nr_zapped_lock_chains;
  2859. unsigned int nr_free_chain_hlocks; /* Free chain_hlocks in buckets */
  2860. unsigned int nr_lost_chain_hlocks; /* Lost chain_hlocks */
  2861. unsigned int nr_large_chain_blocks; /* size > MAX_CHAIN_BUCKETS */
  2862. /*
  2863. * The first 2 chain_hlocks entries in the chain block in the bucket
  2864. * list contains the following meta data:
  2865. *
  2866. * entry[0]:
  2867. * Bit 15 - always set to 1 (it is not a class index)
  2868. * Bits 0-14 - upper 15 bits of the next block index
  2869. * entry[1] - lower 16 bits of next block index
  2870. *
  2871. * A next block index of all 1 bits means it is the end of the list.
  2872. *
  2873. * On the unsized bucket (bucket-0), the 3rd and 4th entries contain
  2874. * the chain block size:
  2875. *
  2876. * entry[2] - upper 16 bits of the chain block size
  2877. * entry[3] - lower 16 bits of the chain block size
  2878. */
  2879. #define MAX_CHAIN_BUCKETS 16
  2880. #define CHAIN_BLK_FLAG (1U << 15)
  2881. #define CHAIN_BLK_LIST_END 0xFFFFU
  2882. static int chain_block_buckets[MAX_CHAIN_BUCKETS];
  2883. static inline int size_to_bucket(int size)
  2884. {
  2885. if (size > MAX_CHAIN_BUCKETS)
  2886. return 0;
  2887. return size - 1;
  2888. }
  2889. /*
  2890. * Iterate all the chain blocks in a bucket.
  2891. */
  2892. #define for_each_chain_block(bucket, prev, curr) \
  2893. for ((prev) = -1, (curr) = chain_block_buckets[bucket]; \
  2894. (curr) >= 0; \
  2895. (prev) = (curr), (curr) = chain_block_next(curr))
  2896. /*
  2897. * next block or -1
  2898. */
  2899. static inline int chain_block_next(int offset)
  2900. {
  2901. int next = chain_hlocks[offset];
  2902. WARN_ON_ONCE(!(next & CHAIN_BLK_FLAG));
  2903. if (next == CHAIN_BLK_LIST_END)
  2904. return -1;
  2905. next &= ~CHAIN_BLK_FLAG;
  2906. next <<= 16;
  2907. next |= chain_hlocks[offset + 1];
  2908. return next;
  2909. }
  2910. /*
  2911. * bucket-0 only
  2912. */
  2913. static inline int chain_block_size(int offset)
  2914. {
  2915. return (chain_hlocks[offset + 2] << 16) | chain_hlocks[offset + 3];
  2916. }
  2917. static inline void init_chain_block(int offset, int next, int bucket, int size)
  2918. {
  2919. chain_hlocks[offset] = (next >> 16) | CHAIN_BLK_FLAG;
  2920. chain_hlocks[offset + 1] = (u16)next;
  2921. if (size && !bucket) {
  2922. chain_hlocks[offset + 2] = size >> 16;
  2923. chain_hlocks[offset + 3] = (u16)size;
  2924. }
  2925. }
  2926. static inline void add_chain_block(int offset, int size)
  2927. {
  2928. int bucket = size_to_bucket(size);
  2929. int next = chain_block_buckets[bucket];
  2930. int prev, curr;
  2931. if (unlikely(size < 2)) {
  2932. /*
  2933. * We can't store single entries on the freelist. Leak them.
  2934. *
  2935. * One possible way out would be to uniquely mark them, other
  2936. * than with CHAIN_BLK_FLAG, such that we can recover them when
  2937. * the block before it is re-added.
  2938. */
  2939. if (size)
  2940. nr_lost_chain_hlocks++;
  2941. return;
  2942. }
  2943. nr_free_chain_hlocks += size;
  2944. if (!bucket) {
  2945. nr_large_chain_blocks++;
  2946. /*
  2947. * Variable sized, sort large to small.
  2948. */
  2949. for_each_chain_block(0, prev, curr) {
  2950. if (size >= chain_block_size(curr))
  2951. break;
  2952. }
  2953. init_chain_block(offset, curr, 0, size);
  2954. if (prev < 0)
  2955. chain_block_buckets[0] = offset;
  2956. else
  2957. init_chain_block(prev, offset, 0, 0);
  2958. return;
  2959. }
  2960. /*
  2961. * Fixed size, add to head.
  2962. */
  2963. init_chain_block(offset, next, bucket, size);
  2964. chain_block_buckets[bucket] = offset;
  2965. }
  2966. /*
  2967. * Only the first block in the list can be deleted.
  2968. *
  2969. * For the variable size bucket[0], the first block (the largest one) is
  2970. * returned, broken up and put back into the pool. So if a chain block of
  2971. * length > MAX_CHAIN_BUCKETS is ever used and zapped, it will just be
  2972. * queued up after the primordial chain block and never be used until the
  2973. * hlock entries in the primordial chain block is almost used up. That
  2974. * causes fragmentation and reduce allocation efficiency. That can be
  2975. * monitored by looking at the "large chain blocks" number in lockdep_stats.
  2976. */
  2977. static inline void del_chain_block(int bucket, int size, int next)
  2978. {
  2979. nr_free_chain_hlocks -= size;
  2980. chain_block_buckets[bucket] = next;
  2981. if (!bucket)
  2982. nr_large_chain_blocks--;
  2983. }
  2984. static void init_chain_block_buckets(void)
  2985. {
  2986. int i;
  2987. for (i = 0; i < MAX_CHAIN_BUCKETS; i++)
  2988. chain_block_buckets[i] = -1;
  2989. add_chain_block(0, ARRAY_SIZE(chain_hlocks));
  2990. }
  2991. /*
  2992. * Return offset of a chain block of the right size or -1 if not found.
  2993. *
  2994. * Fairly simple worst-fit allocator with the addition of a number of size
  2995. * specific free lists.
  2996. */
  2997. static int alloc_chain_hlocks(int req)
  2998. {
  2999. int bucket, curr, size;
  3000. /*
  3001. * We rely on the MSB to act as an escape bit to denote freelist
  3002. * pointers. Make sure this bit isn't set in 'normal' class_idx usage.
  3003. */
  3004. BUILD_BUG_ON((MAX_LOCKDEP_KEYS-1) & CHAIN_BLK_FLAG);
  3005. init_data_structures_once();
  3006. if (nr_free_chain_hlocks < req)
  3007. return -1;
  3008. /*
  3009. * We require a minimum of 2 (u16) entries to encode a freelist
  3010. * 'pointer'.
  3011. */
  3012. req = max(req, 2);
  3013. bucket = size_to_bucket(req);
  3014. curr = chain_block_buckets[bucket];
  3015. if (bucket) {
  3016. if (curr >= 0) {
  3017. del_chain_block(bucket, req, chain_block_next(curr));
  3018. return curr;
  3019. }
  3020. /* Try bucket 0 */
  3021. curr = chain_block_buckets[0];
  3022. }
  3023. /*
  3024. * The variable sized freelist is sorted by size; the first entry is
  3025. * the largest. Use it if it fits.
  3026. */
  3027. if (curr >= 0) {
  3028. size = chain_block_size(curr);
  3029. if (likely(size >= req)) {
  3030. del_chain_block(0, size, chain_block_next(curr));
  3031. if (size > req)
  3032. add_chain_block(curr + req, size - req);
  3033. return curr;
  3034. }
  3035. }
  3036. /*
  3037. * Last resort, split a block in a larger sized bucket.
  3038. */
  3039. for (size = MAX_CHAIN_BUCKETS; size > req; size--) {
  3040. bucket = size_to_bucket(size);
  3041. curr = chain_block_buckets[bucket];
  3042. if (curr < 0)
  3043. continue;
  3044. del_chain_block(bucket, size, chain_block_next(curr));
  3045. add_chain_block(curr + req, size - req);
  3046. return curr;
  3047. }
  3048. return -1;
  3049. }
  3050. static inline void free_chain_hlocks(int base, int size)
  3051. {
  3052. add_chain_block(base, max(size, 2));
  3053. }
  3054. struct lock_class *lock_chain_get_class(struct lock_chain *chain, int i)
  3055. {
  3056. u16 chain_hlock = chain_hlocks[chain->base + i];
  3057. unsigned int class_idx = chain_hlock_class_idx(chain_hlock);
  3058. return lock_classes + class_idx;
  3059. }
  3060. /*
  3061. * Returns the index of the first held_lock of the current chain
  3062. */
  3063. static inline int get_first_held_lock(struct task_struct *curr,
  3064. struct held_lock *hlock)
  3065. {
  3066. int i;
  3067. struct held_lock *hlock_curr;
  3068. for (i = curr->lockdep_depth - 1; i >= 0; i--) {
  3069. hlock_curr = curr->held_locks + i;
  3070. if (hlock_curr->irq_context != hlock->irq_context)
  3071. break;
  3072. }
  3073. return ++i;
  3074. }
  3075. #ifdef CONFIG_DEBUG_LOCKDEP
  3076. /*
  3077. * Returns the next chain_key iteration
  3078. */
  3079. static u64 print_chain_key_iteration(u16 hlock_id, u64 chain_key)
  3080. {
  3081. u64 new_chain_key = iterate_chain_key(chain_key, hlock_id);
  3082. printk(" hlock_id:%d -> chain_key:%016Lx",
  3083. (unsigned int)hlock_id,
  3084. (unsigned long long)new_chain_key);
  3085. return new_chain_key;
  3086. }
  3087. static void
  3088. print_chain_keys_held_locks(struct task_struct *curr, struct held_lock *hlock_next)
  3089. {
  3090. struct held_lock *hlock;
  3091. u64 chain_key = INITIAL_CHAIN_KEY;
  3092. int depth = curr->lockdep_depth;
  3093. int i = get_first_held_lock(curr, hlock_next);
  3094. printk("depth: %u (irq_context %u)\n", depth - i + 1,
  3095. hlock_next->irq_context);
  3096. for (; i < depth; i++) {
  3097. hlock = curr->held_locks + i;
  3098. chain_key = print_chain_key_iteration(hlock_id(hlock), chain_key);
  3099. print_lock(hlock);
  3100. }
  3101. print_chain_key_iteration(hlock_id(hlock_next), chain_key);
  3102. print_lock(hlock_next);
  3103. }
  3104. static void print_chain_keys_chain(struct lock_chain *chain)
  3105. {
  3106. int i;
  3107. u64 chain_key = INITIAL_CHAIN_KEY;
  3108. u16 hlock_id;
  3109. printk("depth: %u\n", chain->depth);
  3110. for (i = 0; i < chain->depth; i++) {
  3111. hlock_id = chain_hlocks[chain->base + i];
  3112. chain_key = print_chain_key_iteration(hlock_id, chain_key);
  3113. print_lock_name(NULL, lock_classes + chain_hlock_class_idx(hlock_id));
  3114. printk("\n");
  3115. }
  3116. }
  3117. static void print_collision(struct task_struct *curr,
  3118. struct held_lock *hlock_next,
  3119. struct lock_chain *chain)
  3120. {
  3121. nbcon_cpu_emergency_enter();
  3122. pr_warn("\n");
  3123. pr_warn("============================\n");
  3124. pr_warn("WARNING: chain_key collision\n");
  3125. print_kernel_ident();
  3126. pr_warn("----------------------------\n");
  3127. pr_warn("%s/%d: ", current->comm, task_pid_nr(current));
  3128. pr_warn("Hash chain already cached but the contents don't match!\n");
  3129. pr_warn("Held locks:");
  3130. print_chain_keys_held_locks(curr, hlock_next);
  3131. pr_warn("Locks in cached chain:");
  3132. print_chain_keys_chain(chain);
  3133. pr_warn("\nstack backtrace:\n");
  3134. dump_stack();
  3135. nbcon_cpu_emergency_exit();
  3136. }
  3137. #endif
  3138. /*
  3139. * Checks whether the chain and the current held locks are consistent
  3140. * in depth and also in content. If they are not it most likely means
  3141. * that there was a collision during the calculation of the chain_key.
  3142. * Returns: 0 not passed, 1 passed
  3143. */
  3144. static int check_no_collision(struct task_struct *curr,
  3145. struct held_lock *hlock,
  3146. struct lock_chain *chain)
  3147. {
  3148. #ifdef CONFIG_DEBUG_LOCKDEP
  3149. int i, j, id;
  3150. i = get_first_held_lock(curr, hlock);
  3151. if (DEBUG_LOCKS_WARN_ON(chain->depth != curr->lockdep_depth - (i - 1))) {
  3152. print_collision(curr, hlock, chain);
  3153. return 0;
  3154. }
  3155. for (j = 0; j < chain->depth - 1; j++, i++) {
  3156. id = hlock_id(&curr->held_locks[i]);
  3157. if (DEBUG_LOCKS_WARN_ON(chain_hlocks[chain->base + j] != id)) {
  3158. print_collision(curr, hlock, chain);
  3159. return 0;
  3160. }
  3161. }
  3162. #endif
  3163. return 1;
  3164. }
  3165. /*
  3166. * Given an index that is >= -1, return the index of the next lock chain.
  3167. * Return -2 if there is no next lock chain.
  3168. */
  3169. long lockdep_next_lockchain(long i)
  3170. {
  3171. i = find_next_bit(lock_chains_in_use, ARRAY_SIZE(lock_chains), i + 1);
  3172. return i < ARRAY_SIZE(lock_chains) ? i : -2;
  3173. }
  3174. unsigned long lock_chain_count(void)
  3175. {
  3176. return bitmap_weight(lock_chains_in_use, ARRAY_SIZE(lock_chains));
  3177. }
  3178. /* Must be called with the graph lock held. */
  3179. static struct lock_chain *alloc_lock_chain(void)
  3180. {
  3181. int idx = find_first_zero_bit(lock_chains_in_use,
  3182. ARRAY_SIZE(lock_chains));
  3183. if (unlikely(idx >= ARRAY_SIZE(lock_chains)))
  3184. return NULL;
  3185. __set_bit(idx, lock_chains_in_use);
  3186. return lock_chains + idx;
  3187. }
  3188. /*
  3189. * Adds a dependency chain into chain hashtable. And must be called with
  3190. * graph_lock held.
  3191. *
  3192. * Return 0 if fail, and graph_lock is released.
  3193. * Return 1 if succeed, with graph_lock held.
  3194. */
  3195. static inline int add_chain_cache(struct task_struct *curr,
  3196. struct held_lock *hlock,
  3197. u64 chain_key)
  3198. {
  3199. struct hlist_head *hash_head = chainhashentry(chain_key);
  3200. struct lock_chain *chain;
  3201. int i, j;
  3202. /*
  3203. * The caller must hold the graph lock, ensure we've got IRQs
  3204. * disabled to make this an IRQ-safe lock.. for recursion reasons
  3205. * lockdep won't complain about its own locking errors.
  3206. */
  3207. if (lockdep_assert_locked())
  3208. return 0;
  3209. chain = alloc_lock_chain();
  3210. if (!chain) {
  3211. if (!debug_locks_off_graph_unlock())
  3212. return 0;
  3213. nbcon_cpu_emergency_enter();
  3214. print_lockdep_off("BUG: MAX_LOCKDEP_CHAINS too low!");
  3215. dump_stack();
  3216. nbcon_cpu_emergency_exit();
  3217. return 0;
  3218. }
  3219. chain->chain_key = chain_key;
  3220. chain->irq_context = hlock->irq_context;
  3221. i = get_first_held_lock(curr, hlock);
  3222. chain->depth = curr->lockdep_depth + 1 - i;
  3223. BUILD_BUG_ON((1UL << 24) <= ARRAY_SIZE(chain_hlocks));
  3224. BUILD_BUG_ON((1UL << 6) <= ARRAY_SIZE(curr->held_locks));
  3225. BUILD_BUG_ON((1UL << 8*sizeof(chain_hlocks[0])) <= ARRAY_SIZE(lock_classes));
  3226. j = alloc_chain_hlocks(chain->depth);
  3227. if (j < 0) {
  3228. if (!debug_locks_off_graph_unlock())
  3229. return 0;
  3230. nbcon_cpu_emergency_enter();
  3231. print_lockdep_off("BUG: MAX_LOCKDEP_CHAIN_HLOCKS too low!");
  3232. dump_stack();
  3233. nbcon_cpu_emergency_exit();
  3234. return 0;
  3235. }
  3236. chain->base = j;
  3237. for (j = 0; j < chain->depth - 1; j++, i++) {
  3238. int lock_id = hlock_id(curr->held_locks + i);
  3239. chain_hlocks[chain->base + j] = lock_id;
  3240. }
  3241. chain_hlocks[chain->base + j] = hlock_id(hlock);
  3242. hlist_add_head_rcu(&chain->entry, hash_head);
  3243. debug_atomic_inc(chain_lookup_misses);
  3244. inc_chains(chain->irq_context);
  3245. return 1;
  3246. }
  3247. /*
  3248. * Look up a dependency chain. Must be called with either the graph lock or
  3249. * the RCU read lock held.
  3250. */
  3251. static inline struct lock_chain *lookup_chain_cache(u64 chain_key)
  3252. {
  3253. struct hlist_head *hash_head = chainhashentry(chain_key);
  3254. struct lock_chain *chain;
  3255. hlist_for_each_entry_rcu(chain, hash_head, entry) {
  3256. if (READ_ONCE(chain->chain_key) == chain_key) {
  3257. debug_atomic_inc(chain_lookup_hits);
  3258. return chain;
  3259. }
  3260. }
  3261. return NULL;
  3262. }
  3263. /*
  3264. * If the key is not present yet in dependency chain cache then
  3265. * add it and return 1 - in this case the new dependency chain is
  3266. * validated. If the key is already hashed, return 0.
  3267. * (On return with 1 graph_lock is held.)
  3268. */
  3269. static inline int lookup_chain_cache_add(struct task_struct *curr,
  3270. struct held_lock *hlock,
  3271. u64 chain_key)
  3272. {
  3273. struct lock_class *class = hlock_class(hlock);
  3274. struct lock_chain *chain = lookup_chain_cache(chain_key);
  3275. if (chain) {
  3276. cache_hit:
  3277. if (!check_no_collision(curr, hlock, chain))
  3278. return 0;
  3279. if (very_verbose(class)) {
  3280. printk("\nhash chain already cached, key: "
  3281. "%016Lx tail class: [%px] %s\n",
  3282. (unsigned long long)chain_key,
  3283. class->key, class->name);
  3284. }
  3285. return 0;
  3286. }
  3287. if (very_verbose(class)) {
  3288. printk("\nnew hash chain, key: %016Lx tail class: [%px] %s\n",
  3289. (unsigned long long)chain_key, class->key, class->name);
  3290. }
  3291. if (!graph_lock())
  3292. return 0;
  3293. /*
  3294. * We have to walk the chain again locked - to avoid duplicates:
  3295. */
  3296. chain = lookup_chain_cache(chain_key);
  3297. if (chain) {
  3298. graph_unlock();
  3299. goto cache_hit;
  3300. }
  3301. if (!add_chain_cache(curr, hlock, chain_key))
  3302. return 0;
  3303. return 1;
  3304. }
  3305. static int validate_chain(struct task_struct *curr,
  3306. struct held_lock *hlock,
  3307. int chain_head, u64 chain_key)
  3308. {
  3309. /*
  3310. * Trylock needs to maintain the stack of held locks, but it
  3311. * does not add new dependencies, because trylock can be done
  3312. * in any order.
  3313. *
  3314. * We look up the chain_key and do the O(N^2) check and update of
  3315. * the dependencies only if this is a new dependency chain.
  3316. * (If lookup_chain_cache_add() return with 1 it acquires
  3317. * graph_lock for us)
  3318. */
  3319. if (!hlock->trylock && hlock->check &&
  3320. lookup_chain_cache_add(curr, hlock, chain_key)) {
  3321. /*
  3322. * Check whether last held lock:
  3323. *
  3324. * - is irq-safe, if this lock is irq-unsafe
  3325. * - is softirq-safe, if this lock is hardirq-unsafe
  3326. *
  3327. * And check whether the new lock's dependency graph
  3328. * could lead back to the previous lock:
  3329. *
  3330. * - within the current held-lock stack
  3331. * - across our accumulated lock dependency records
  3332. *
  3333. * any of these scenarios could lead to a deadlock.
  3334. */
  3335. /*
  3336. * The simple case: does the current hold the same lock
  3337. * already?
  3338. */
  3339. int ret = check_deadlock(curr, hlock);
  3340. if (!ret)
  3341. return 0;
  3342. /*
  3343. * Add dependency only if this lock is not the head
  3344. * of the chain, and if the new lock introduces no more
  3345. * lock dependency (because we already hold a lock with the
  3346. * same lock class) nor deadlock (because the nest_lock
  3347. * serializes nesting locks), see the comments for
  3348. * check_deadlock().
  3349. */
  3350. if (!chain_head && ret != 2) {
  3351. if (!check_prevs_add(curr, hlock))
  3352. return 0;
  3353. }
  3354. graph_unlock();
  3355. } else {
  3356. /* after lookup_chain_cache_add(): */
  3357. if (unlikely(!debug_locks))
  3358. return 0;
  3359. }
  3360. return 1;
  3361. }
  3362. #else
  3363. static inline int validate_chain(struct task_struct *curr,
  3364. struct held_lock *hlock,
  3365. int chain_head, u64 chain_key)
  3366. {
  3367. return 1;
  3368. }
  3369. static void init_chain_block_buckets(void) { }
  3370. #endif /* CONFIG_PROVE_LOCKING */
  3371. /*
  3372. * We are building curr_chain_key incrementally, so double-check
  3373. * it from scratch, to make sure that it's done correctly:
  3374. */
  3375. static void check_chain_key(struct task_struct *curr)
  3376. {
  3377. #ifdef CONFIG_DEBUG_LOCKDEP
  3378. struct held_lock *hlock, *prev_hlock = NULL;
  3379. unsigned int i;
  3380. u64 chain_key = INITIAL_CHAIN_KEY;
  3381. for (i = 0; i < curr->lockdep_depth; i++) {
  3382. hlock = curr->held_locks + i;
  3383. if (chain_key != hlock->prev_chain_key) {
  3384. debug_locks_off();
  3385. /*
  3386. * We got mighty confused, our chain keys don't match
  3387. * with what we expect, someone trample on our task state?
  3388. */
  3389. WARN(1, "hm#1, depth: %u [%u], %016Lx != %016Lx\n",
  3390. curr->lockdep_depth, i,
  3391. (unsigned long long)chain_key,
  3392. (unsigned long long)hlock->prev_chain_key);
  3393. return;
  3394. }
  3395. /*
  3396. * hlock->class_idx can't go beyond MAX_LOCKDEP_KEYS, but is
  3397. * it registered lock class index?
  3398. */
  3399. if (DEBUG_LOCKS_WARN_ON(!test_bit(hlock->class_idx, lock_classes_in_use)))
  3400. return;
  3401. if (prev_hlock && (prev_hlock->irq_context !=
  3402. hlock->irq_context))
  3403. chain_key = INITIAL_CHAIN_KEY;
  3404. chain_key = iterate_chain_key(chain_key, hlock_id(hlock));
  3405. prev_hlock = hlock;
  3406. }
  3407. if (chain_key != curr->curr_chain_key) {
  3408. debug_locks_off();
  3409. /*
  3410. * More smoking hash instead of calculating it, damn see these
  3411. * numbers float.. I bet that a pink elephant stepped on my memory.
  3412. */
  3413. WARN(1, "hm#2, depth: %u [%u], %016Lx != %016Lx\n",
  3414. curr->lockdep_depth, i,
  3415. (unsigned long long)chain_key,
  3416. (unsigned long long)curr->curr_chain_key);
  3417. }
  3418. #endif
  3419. }
  3420. #ifdef CONFIG_PROVE_LOCKING
  3421. static int mark_lock(struct task_struct *curr, struct held_lock *this,
  3422. enum lock_usage_bit new_bit);
  3423. static void print_usage_bug_scenario(struct held_lock *lock)
  3424. {
  3425. struct lock_class *class = hlock_class(lock);
  3426. printk(" Possible unsafe locking scenario:\n\n");
  3427. printk(" CPU0\n");
  3428. printk(" ----\n");
  3429. printk(" lock(");
  3430. __print_lock_name(lock, class);
  3431. printk(KERN_CONT ");\n");
  3432. printk(" <Interrupt>\n");
  3433. printk(" lock(");
  3434. __print_lock_name(lock, class);
  3435. printk(KERN_CONT ");\n");
  3436. printk("\n *** DEADLOCK ***\n\n");
  3437. }
  3438. static void
  3439. print_usage_bug(struct task_struct *curr, struct held_lock *this,
  3440. enum lock_usage_bit prev_bit, enum lock_usage_bit new_bit)
  3441. {
  3442. if (!debug_locks_off() || debug_locks_silent)
  3443. return;
  3444. nbcon_cpu_emergency_enter();
  3445. pr_warn("\n");
  3446. pr_warn("================================\n");
  3447. pr_warn("WARNING: inconsistent lock state\n");
  3448. print_kernel_ident();
  3449. pr_warn("--------------------------------\n");
  3450. pr_warn("inconsistent {%s} -> {%s} usage.\n",
  3451. usage_str[prev_bit], usage_str[new_bit]);
  3452. pr_warn("%s/%d [HC%u[%lu]:SC%u[%lu]:HE%u:SE%u] takes:\n",
  3453. curr->comm, task_pid_nr(curr),
  3454. lockdep_hardirq_context(), hardirq_count() >> HARDIRQ_SHIFT,
  3455. lockdep_softirq_context(curr), softirq_count() >> SOFTIRQ_SHIFT,
  3456. lockdep_hardirqs_enabled(),
  3457. lockdep_softirqs_enabled(curr));
  3458. print_lock(this);
  3459. pr_warn("{%s} state was registered at:\n", usage_str[prev_bit]);
  3460. print_lock_trace(hlock_class(this)->usage_traces[prev_bit], 1);
  3461. print_irqtrace_events(curr);
  3462. pr_warn("\nother info that might help us debug this:\n");
  3463. print_usage_bug_scenario(this);
  3464. lockdep_print_held_locks(curr);
  3465. pr_warn("\nstack backtrace:\n");
  3466. dump_stack();
  3467. nbcon_cpu_emergency_exit();
  3468. }
  3469. /*
  3470. * Print out an error if an invalid bit is set:
  3471. */
  3472. static inline int
  3473. valid_state(struct task_struct *curr, struct held_lock *this,
  3474. enum lock_usage_bit new_bit, enum lock_usage_bit bad_bit)
  3475. {
  3476. if (unlikely(hlock_class(this)->usage_mask & (1 << bad_bit))) {
  3477. graph_unlock();
  3478. print_usage_bug(curr, this, bad_bit, new_bit);
  3479. return 0;
  3480. }
  3481. return 1;
  3482. }
  3483. /*
  3484. * print irq inversion bug:
  3485. */
  3486. static void
  3487. print_irq_inversion_bug(struct task_struct *curr,
  3488. struct lock_list *root, struct lock_list *other,
  3489. struct held_lock *this, int forwards,
  3490. const char *irqclass)
  3491. {
  3492. struct lock_list *entry = other;
  3493. struct lock_list *middle = NULL;
  3494. int depth;
  3495. if (!debug_locks_off_graph_unlock() || debug_locks_silent)
  3496. return;
  3497. nbcon_cpu_emergency_enter();
  3498. pr_warn("\n");
  3499. pr_warn("========================================================\n");
  3500. pr_warn("WARNING: possible irq lock inversion dependency detected\n");
  3501. print_kernel_ident();
  3502. pr_warn("--------------------------------------------------------\n");
  3503. pr_warn("%s/%d just changed the state of lock:\n",
  3504. curr->comm, task_pid_nr(curr));
  3505. print_lock(this);
  3506. if (forwards)
  3507. pr_warn("but this lock took another, %s-unsafe lock in the past:\n", irqclass);
  3508. else
  3509. pr_warn("but this lock was taken by another, %s-safe lock in the past:\n", irqclass);
  3510. print_lock_name(NULL, other->class);
  3511. pr_warn("\n\nand interrupts could create inverse lock ordering between them.\n\n");
  3512. pr_warn("\nother info that might help us debug this:\n");
  3513. /* Find a middle lock (if one exists) */
  3514. depth = get_lock_depth(other);
  3515. do {
  3516. if (depth == 0 && (entry != root)) {
  3517. pr_warn("lockdep:%s bad path found in chain graph\n", __func__);
  3518. break;
  3519. }
  3520. middle = entry;
  3521. entry = get_lock_parent(entry);
  3522. depth--;
  3523. } while (entry && entry != root && (depth >= 0));
  3524. if (forwards)
  3525. print_irq_lock_scenario(root, other,
  3526. middle ? middle->class : root->class, other->class);
  3527. else
  3528. print_irq_lock_scenario(other, root,
  3529. middle ? middle->class : other->class, root->class);
  3530. lockdep_print_held_locks(curr);
  3531. pr_warn("\nthe shortest dependencies between 2nd lock and 1st lock:\n");
  3532. root->trace = save_trace();
  3533. if (!root->trace)
  3534. goto out;
  3535. print_shortest_lock_dependencies(other, root);
  3536. pr_warn("\nstack backtrace:\n");
  3537. dump_stack();
  3538. out:
  3539. nbcon_cpu_emergency_exit();
  3540. }
  3541. /*
  3542. * Prove that in the forwards-direction subgraph starting at <this>
  3543. * there is no lock matching <mask>:
  3544. */
  3545. static int
  3546. check_usage_forwards(struct task_struct *curr, struct held_lock *this,
  3547. enum lock_usage_bit bit)
  3548. {
  3549. enum bfs_result ret;
  3550. struct lock_list root;
  3551. struct lock_list *target_entry;
  3552. enum lock_usage_bit read_bit = bit + LOCK_USAGE_READ_MASK;
  3553. unsigned usage_mask = lock_flag(bit) | lock_flag(read_bit);
  3554. bfs_init_root(&root, this);
  3555. ret = find_usage_forwards(&root, usage_mask, &target_entry);
  3556. if (bfs_error(ret)) {
  3557. print_bfs_bug(ret);
  3558. return 0;
  3559. }
  3560. if (ret == BFS_RNOMATCH)
  3561. return 1;
  3562. /* Check whether write or read usage is the match */
  3563. if (target_entry->class->usage_mask & lock_flag(bit)) {
  3564. print_irq_inversion_bug(curr, &root, target_entry,
  3565. this, 1, state_name(bit));
  3566. } else {
  3567. print_irq_inversion_bug(curr, &root, target_entry,
  3568. this, 1, state_name(read_bit));
  3569. }
  3570. return 0;
  3571. }
  3572. /*
  3573. * Prove that in the backwards-direction subgraph starting at <this>
  3574. * there is no lock matching <mask>:
  3575. */
  3576. static int
  3577. check_usage_backwards(struct task_struct *curr, struct held_lock *this,
  3578. enum lock_usage_bit bit)
  3579. {
  3580. enum bfs_result ret;
  3581. struct lock_list root;
  3582. struct lock_list *target_entry;
  3583. enum lock_usage_bit read_bit = bit + LOCK_USAGE_READ_MASK;
  3584. unsigned usage_mask = lock_flag(bit) | lock_flag(read_bit);
  3585. bfs_init_rootb(&root, this);
  3586. ret = find_usage_backwards(&root, usage_mask, &target_entry);
  3587. if (bfs_error(ret)) {
  3588. print_bfs_bug(ret);
  3589. return 0;
  3590. }
  3591. if (ret == BFS_RNOMATCH)
  3592. return 1;
  3593. /* Check whether write or read usage is the match */
  3594. if (target_entry->class->usage_mask & lock_flag(bit)) {
  3595. print_irq_inversion_bug(curr, &root, target_entry,
  3596. this, 0, state_name(bit));
  3597. } else {
  3598. print_irq_inversion_bug(curr, &root, target_entry,
  3599. this, 0, state_name(read_bit));
  3600. }
  3601. return 0;
  3602. }
  3603. void print_irqtrace_events(struct task_struct *curr)
  3604. {
  3605. const struct irqtrace_events *trace = &curr->irqtrace;
  3606. nbcon_cpu_emergency_enter();
  3607. printk("irq event stamp: %u\n", trace->irq_events);
  3608. printk("hardirqs last enabled at (%u): [<%px>] %pS\n",
  3609. trace->hardirq_enable_event, (void *)trace->hardirq_enable_ip,
  3610. (void *)trace->hardirq_enable_ip);
  3611. printk("hardirqs last disabled at (%u): [<%px>] %pS\n",
  3612. trace->hardirq_disable_event, (void *)trace->hardirq_disable_ip,
  3613. (void *)trace->hardirq_disable_ip);
  3614. printk("softirqs last enabled at (%u): [<%px>] %pS\n",
  3615. trace->softirq_enable_event, (void *)trace->softirq_enable_ip,
  3616. (void *)trace->softirq_enable_ip);
  3617. printk("softirqs last disabled at (%u): [<%px>] %pS\n",
  3618. trace->softirq_disable_event, (void *)trace->softirq_disable_ip,
  3619. (void *)trace->softirq_disable_ip);
  3620. nbcon_cpu_emergency_exit();
  3621. }
  3622. static int HARDIRQ_verbose(struct lock_class *class)
  3623. {
  3624. #if HARDIRQ_VERBOSE
  3625. return class_filter(class);
  3626. #endif
  3627. return 0;
  3628. }
  3629. static int SOFTIRQ_verbose(struct lock_class *class)
  3630. {
  3631. #if SOFTIRQ_VERBOSE
  3632. return class_filter(class);
  3633. #endif
  3634. return 0;
  3635. }
  3636. static int (*state_verbose_f[])(struct lock_class *class) = {
  3637. #define LOCKDEP_STATE(__STATE) \
  3638. __STATE##_verbose,
  3639. #include "lockdep_states.h"
  3640. #undef LOCKDEP_STATE
  3641. };
  3642. static inline int state_verbose(enum lock_usage_bit bit,
  3643. struct lock_class *class)
  3644. {
  3645. return state_verbose_f[bit >> LOCK_USAGE_DIR_MASK](class);
  3646. }
  3647. typedef int (*check_usage_f)(struct task_struct *, struct held_lock *,
  3648. enum lock_usage_bit bit, const char *name);
  3649. static int
  3650. mark_lock_irq(struct task_struct *curr, struct held_lock *this,
  3651. enum lock_usage_bit new_bit)
  3652. {
  3653. int excl_bit = exclusive_bit(new_bit);
  3654. int read = new_bit & LOCK_USAGE_READ_MASK;
  3655. int dir = new_bit & LOCK_USAGE_DIR_MASK;
  3656. /*
  3657. * Validate that this particular lock does not have conflicting
  3658. * usage states.
  3659. */
  3660. if (!valid_state(curr, this, new_bit, excl_bit))
  3661. return 0;
  3662. /*
  3663. * Check for read in write conflicts
  3664. */
  3665. if (!read && !valid_state(curr, this, new_bit,
  3666. excl_bit + LOCK_USAGE_READ_MASK))
  3667. return 0;
  3668. /*
  3669. * Validate that the lock dependencies don't have conflicting usage
  3670. * states.
  3671. */
  3672. if (dir) {
  3673. /*
  3674. * mark ENABLED has to look backwards -- to ensure no dependee
  3675. * has USED_IN state, which, again, would allow recursion deadlocks.
  3676. */
  3677. if (!check_usage_backwards(curr, this, excl_bit))
  3678. return 0;
  3679. } else {
  3680. /*
  3681. * mark USED_IN has to look forwards -- to ensure no dependency
  3682. * has ENABLED state, which would allow recursion deadlocks.
  3683. */
  3684. if (!check_usage_forwards(curr, this, excl_bit))
  3685. return 0;
  3686. }
  3687. if (state_verbose(new_bit, hlock_class(this)))
  3688. return 2;
  3689. return 1;
  3690. }
  3691. /*
  3692. * Mark all held locks with a usage bit:
  3693. */
  3694. static int
  3695. mark_held_locks(struct task_struct *curr, enum lock_usage_bit base_bit)
  3696. {
  3697. struct held_lock *hlock;
  3698. int i;
  3699. for (i = 0; i < curr->lockdep_depth; i++) {
  3700. enum lock_usage_bit hlock_bit = base_bit;
  3701. hlock = curr->held_locks + i;
  3702. if (hlock->read)
  3703. hlock_bit += LOCK_USAGE_READ_MASK;
  3704. BUG_ON(hlock_bit >= LOCK_USAGE_STATES);
  3705. if (!hlock->check)
  3706. continue;
  3707. if (!mark_lock(curr, hlock, hlock_bit))
  3708. return 0;
  3709. }
  3710. return 1;
  3711. }
  3712. /*
  3713. * Hardirqs will be enabled:
  3714. */
  3715. static void __trace_hardirqs_on_caller(void)
  3716. {
  3717. struct task_struct *curr = current;
  3718. /*
  3719. * We are going to turn hardirqs on, so set the
  3720. * usage bit for all held locks:
  3721. */
  3722. if (!mark_held_locks(curr, LOCK_ENABLED_HARDIRQ))
  3723. return;
  3724. /*
  3725. * If we have softirqs enabled, then set the usage
  3726. * bit for all held locks. (disabled hardirqs prevented
  3727. * this bit from being set before)
  3728. */
  3729. if (curr->softirqs_enabled)
  3730. mark_held_locks(curr, LOCK_ENABLED_SOFTIRQ);
  3731. }
  3732. /**
  3733. * lockdep_hardirqs_on_prepare - Prepare for enabling interrupts
  3734. *
  3735. * Invoked before a possible transition to RCU idle from exit to user or
  3736. * guest mode. This ensures that all RCU operations are done before RCU
  3737. * stops watching. After the RCU transition lockdep_hardirqs_on() has to be
  3738. * invoked to set the final state.
  3739. */
  3740. void lockdep_hardirqs_on_prepare(void)
  3741. {
  3742. if (unlikely(!debug_locks))
  3743. return;
  3744. /*
  3745. * NMIs do not (and cannot) track lock dependencies, nothing to do.
  3746. */
  3747. if (unlikely(in_nmi()))
  3748. return;
  3749. if (unlikely(this_cpu_read(lockdep_recursion)))
  3750. return;
  3751. if (unlikely(lockdep_hardirqs_enabled())) {
  3752. /*
  3753. * Neither irq nor preemption are disabled here
  3754. * so this is racy by nature but losing one hit
  3755. * in a stat is not a big deal.
  3756. */
  3757. __debug_atomic_inc(redundant_hardirqs_on);
  3758. return;
  3759. }
  3760. /*
  3761. * We're enabling irqs and according to our state above irqs weren't
  3762. * already enabled, yet we find the hardware thinks they are in fact
  3763. * enabled.. someone messed up their IRQ state tracing.
  3764. */
  3765. if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
  3766. return;
  3767. /*
  3768. * See the fine text that goes along with this variable definition.
  3769. */
  3770. if (DEBUG_LOCKS_WARN_ON(early_boot_irqs_disabled))
  3771. return;
  3772. /*
  3773. * Can't allow enabling interrupts while in an interrupt handler,
  3774. * that's general bad form and such. Recursion, limited stack etc..
  3775. */
  3776. if (DEBUG_LOCKS_WARN_ON(lockdep_hardirq_context()))
  3777. return;
  3778. current->hardirq_chain_key = current->curr_chain_key;
  3779. lockdep_recursion_inc();
  3780. __trace_hardirqs_on_caller();
  3781. lockdep_recursion_finish();
  3782. }
  3783. EXPORT_SYMBOL_GPL(lockdep_hardirqs_on_prepare);
  3784. void noinstr lockdep_hardirqs_on(unsigned long ip)
  3785. {
  3786. struct irqtrace_events *trace = &current->irqtrace;
  3787. if (unlikely(!debug_locks))
  3788. return;
  3789. /*
  3790. * NMIs can happen in the middle of local_irq_{en,dis}able() where the
  3791. * tracking state and hardware state are out of sync.
  3792. *
  3793. * NMIs must save lockdep_hardirqs_enabled() to restore IRQ state from,
  3794. * and not rely on hardware state like normal interrupts.
  3795. */
  3796. if (unlikely(in_nmi())) {
  3797. if (!IS_ENABLED(CONFIG_TRACE_IRQFLAGS_NMI))
  3798. return;
  3799. /*
  3800. * Skip:
  3801. * - recursion check, because NMI can hit lockdep;
  3802. * - hardware state check, because above;
  3803. * - chain_key check, see lockdep_hardirqs_on_prepare().
  3804. */
  3805. goto skip_checks;
  3806. }
  3807. if (unlikely(this_cpu_read(lockdep_recursion)))
  3808. return;
  3809. if (lockdep_hardirqs_enabled()) {
  3810. /*
  3811. * Neither irq nor preemption are disabled here
  3812. * so this is racy by nature but losing one hit
  3813. * in a stat is not a big deal.
  3814. */
  3815. __debug_atomic_inc(redundant_hardirqs_on);
  3816. return;
  3817. }
  3818. /*
  3819. * We're enabling irqs and according to our state above irqs weren't
  3820. * already enabled, yet we find the hardware thinks they are in fact
  3821. * enabled.. someone messed up their IRQ state tracing.
  3822. */
  3823. if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
  3824. return;
  3825. /*
  3826. * Ensure the lock stack remained unchanged between
  3827. * lockdep_hardirqs_on_prepare() and lockdep_hardirqs_on().
  3828. */
  3829. DEBUG_LOCKS_WARN_ON(current->hardirq_chain_key !=
  3830. current->curr_chain_key);
  3831. skip_checks:
  3832. /* we'll do an OFF -> ON transition: */
  3833. __this_cpu_write(hardirqs_enabled, 1);
  3834. trace->hardirq_enable_ip = ip;
  3835. trace->hardirq_enable_event = ++trace->irq_events;
  3836. debug_atomic_inc(hardirqs_on_events);
  3837. }
  3838. EXPORT_SYMBOL_GPL(lockdep_hardirqs_on);
  3839. /*
  3840. * Hardirqs were disabled:
  3841. */
  3842. void noinstr lockdep_hardirqs_off(unsigned long ip)
  3843. {
  3844. if (unlikely(!debug_locks))
  3845. return;
  3846. /*
  3847. * Matching lockdep_hardirqs_on(), allow NMIs in the middle of lockdep;
  3848. * they will restore the software state. This ensures the software
  3849. * state is consistent inside NMIs as well.
  3850. */
  3851. if (in_nmi()) {
  3852. if (!IS_ENABLED(CONFIG_TRACE_IRQFLAGS_NMI))
  3853. return;
  3854. } else if (__this_cpu_read(lockdep_recursion))
  3855. return;
  3856. /*
  3857. * So we're supposed to get called after you mask local IRQs, but for
  3858. * some reason the hardware doesn't quite think you did a proper job.
  3859. */
  3860. if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
  3861. return;
  3862. if (lockdep_hardirqs_enabled()) {
  3863. struct irqtrace_events *trace = &current->irqtrace;
  3864. /*
  3865. * We have done an ON -> OFF transition:
  3866. */
  3867. __this_cpu_write(hardirqs_enabled, 0);
  3868. trace->hardirq_disable_ip = ip;
  3869. trace->hardirq_disable_event = ++trace->irq_events;
  3870. debug_atomic_inc(hardirqs_off_events);
  3871. } else {
  3872. debug_atomic_inc(redundant_hardirqs_off);
  3873. }
  3874. }
  3875. EXPORT_SYMBOL_GPL(lockdep_hardirqs_off);
  3876. /*
  3877. * Softirqs will be enabled:
  3878. */
  3879. void lockdep_softirqs_on(unsigned long ip)
  3880. {
  3881. struct irqtrace_events *trace = &current->irqtrace;
  3882. if (unlikely(!lockdep_enabled()))
  3883. return;
  3884. /*
  3885. * We fancy IRQs being disabled here, see softirq.c, avoids
  3886. * funny state and nesting things.
  3887. */
  3888. if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
  3889. return;
  3890. if (current->softirqs_enabled) {
  3891. debug_atomic_inc(redundant_softirqs_on);
  3892. return;
  3893. }
  3894. lockdep_recursion_inc();
  3895. /*
  3896. * We'll do an OFF -> ON transition:
  3897. */
  3898. current->softirqs_enabled = 1;
  3899. trace->softirq_enable_ip = ip;
  3900. trace->softirq_enable_event = ++trace->irq_events;
  3901. debug_atomic_inc(softirqs_on_events);
  3902. /*
  3903. * We are going to turn softirqs on, so set the
  3904. * usage bit for all held locks, if hardirqs are
  3905. * enabled too:
  3906. */
  3907. if (lockdep_hardirqs_enabled())
  3908. mark_held_locks(current, LOCK_ENABLED_SOFTIRQ);
  3909. lockdep_recursion_finish();
  3910. }
  3911. /*
  3912. * Softirqs were disabled:
  3913. */
  3914. void lockdep_softirqs_off(unsigned long ip)
  3915. {
  3916. if (unlikely(!lockdep_enabled()))
  3917. return;
  3918. /*
  3919. * We fancy IRQs being disabled here, see softirq.c
  3920. */
  3921. if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
  3922. return;
  3923. if (current->softirqs_enabled) {
  3924. struct irqtrace_events *trace = &current->irqtrace;
  3925. /*
  3926. * We have done an ON -> OFF transition:
  3927. */
  3928. current->softirqs_enabled = 0;
  3929. trace->softirq_disable_ip = ip;
  3930. trace->softirq_disable_event = ++trace->irq_events;
  3931. debug_atomic_inc(softirqs_off_events);
  3932. /*
  3933. * Whoops, we wanted softirqs off, so why aren't they?
  3934. */
  3935. DEBUG_LOCKS_WARN_ON(!softirq_count());
  3936. } else
  3937. debug_atomic_inc(redundant_softirqs_off);
  3938. }
  3939. static int
  3940. mark_usage(struct task_struct *curr, struct held_lock *hlock, int check)
  3941. {
  3942. if (!check)
  3943. goto lock_used;
  3944. /*
  3945. * If non-trylock use in a hardirq or softirq context, then
  3946. * mark the lock as used in these contexts:
  3947. */
  3948. if (!hlock->trylock) {
  3949. if (hlock->read) {
  3950. if (lockdep_hardirq_context())
  3951. if (!mark_lock(curr, hlock,
  3952. LOCK_USED_IN_HARDIRQ_READ))
  3953. return 0;
  3954. if (curr->softirq_context)
  3955. if (!mark_lock(curr, hlock,
  3956. LOCK_USED_IN_SOFTIRQ_READ))
  3957. return 0;
  3958. } else {
  3959. if (lockdep_hardirq_context())
  3960. if (!mark_lock(curr, hlock, LOCK_USED_IN_HARDIRQ))
  3961. return 0;
  3962. if (curr->softirq_context)
  3963. if (!mark_lock(curr, hlock, LOCK_USED_IN_SOFTIRQ))
  3964. return 0;
  3965. }
  3966. }
  3967. /*
  3968. * For lock_sync(), don't mark the ENABLED usage, since lock_sync()
  3969. * creates no critical section and no extra dependency can be introduced
  3970. * by interrupts
  3971. */
  3972. if (!hlock->hardirqs_off && !hlock->sync) {
  3973. if (hlock->read) {
  3974. if (!mark_lock(curr, hlock,
  3975. LOCK_ENABLED_HARDIRQ_READ))
  3976. return 0;
  3977. if (curr->softirqs_enabled)
  3978. if (!mark_lock(curr, hlock,
  3979. LOCK_ENABLED_SOFTIRQ_READ))
  3980. return 0;
  3981. } else {
  3982. if (!mark_lock(curr, hlock,
  3983. LOCK_ENABLED_HARDIRQ))
  3984. return 0;
  3985. if (curr->softirqs_enabled)
  3986. if (!mark_lock(curr, hlock,
  3987. LOCK_ENABLED_SOFTIRQ))
  3988. return 0;
  3989. }
  3990. }
  3991. lock_used:
  3992. /* mark it as used: */
  3993. if (!mark_lock(curr, hlock, LOCK_USED))
  3994. return 0;
  3995. return 1;
  3996. }
  3997. static inline unsigned int task_irq_context(struct task_struct *task)
  3998. {
  3999. return LOCK_CHAIN_HARDIRQ_CONTEXT * !!lockdep_hardirq_context() +
  4000. LOCK_CHAIN_SOFTIRQ_CONTEXT * !!task->softirq_context;
  4001. }
  4002. static int separate_irq_context(struct task_struct *curr,
  4003. struct held_lock *hlock)
  4004. {
  4005. unsigned int depth = curr->lockdep_depth;
  4006. /*
  4007. * Keep track of points where we cross into an interrupt context:
  4008. */
  4009. if (depth) {
  4010. struct held_lock *prev_hlock;
  4011. prev_hlock = curr->held_locks + depth-1;
  4012. /*
  4013. * If we cross into another context, reset the
  4014. * hash key (this also prevents the checking and the
  4015. * adding of the dependency to 'prev'):
  4016. */
  4017. if (prev_hlock->irq_context != hlock->irq_context)
  4018. return 1;
  4019. }
  4020. return 0;
  4021. }
  4022. /*
  4023. * Mark a lock with a usage bit, and validate the state transition:
  4024. */
  4025. static int mark_lock(struct task_struct *curr, struct held_lock *this,
  4026. enum lock_usage_bit new_bit)
  4027. {
  4028. unsigned int new_mask, ret = 1;
  4029. if (new_bit >= LOCK_USAGE_STATES) {
  4030. DEBUG_LOCKS_WARN_ON(1);
  4031. return 0;
  4032. }
  4033. if (new_bit == LOCK_USED && this->read)
  4034. new_bit = LOCK_USED_READ;
  4035. new_mask = 1 << new_bit;
  4036. /*
  4037. * If already set then do not dirty the cacheline,
  4038. * nor do any checks:
  4039. */
  4040. if (likely(hlock_class(this)->usage_mask & new_mask))
  4041. return 1;
  4042. if (!graph_lock())
  4043. return 0;
  4044. /*
  4045. * Make sure we didn't race:
  4046. */
  4047. if (unlikely(hlock_class(this)->usage_mask & new_mask))
  4048. goto unlock;
  4049. if (!hlock_class(this)->usage_mask)
  4050. debug_atomic_dec(nr_unused_locks);
  4051. hlock_class(this)->usage_mask |= new_mask;
  4052. if (new_bit < LOCK_TRACE_STATES) {
  4053. if (!(hlock_class(this)->usage_traces[new_bit] = save_trace()))
  4054. return 0;
  4055. }
  4056. if (new_bit < LOCK_USED) {
  4057. ret = mark_lock_irq(curr, this, new_bit);
  4058. if (!ret)
  4059. return 0;
  4060. }
  4061. unlock:
  4062. graph_unlock();
  4063. /*
  4064. * We must printk outside of the graph_lock:
  4065. */
  4066. if (ret == 2) {
  4067. nbcon_cpu_emergency_enter();
  4068. printk("\nmarked lock as {%s}:\n", usage_str[new_bit]);
  4069. print_lock(this);
  4070. print_irqtrace_events(curr);
  4071. dump_stack();
  4072. nbcon_cpu_emergency_exit();
  4073. }
  4074. return ret;
  4075. }
  4076. static inline short task_wait_context(struct task_struct *curr)
  4077. {
  4078. /*
  4079. * Set appropriate wait type for the context; for IRQs we have to take
  4080. * into account force_irqthread as that is implied by PREEMPT_RT.
  4081. */
  4082. if (lockdep_hardirq_context()) {
  4083. /*
  4084. * Check if force_irqthreads will run us threaded.
  4085. */
  4086. if (curr->hardirq_threaded || curr->irq_config)
  4087. return LD_WAIT_CONFIG;
  4088. return LD_WAIT_SPIN;
  4089. } else if (curr->softirq_context) {
  4090. /*
  4091. * Softirqs are always threaded.
  4092. */
  4093. return LD_WAIT_CONFIG;
  4094. }
  4095. return LD_WAIT_MAX;
  4096. }
  4097. static int
  4098. print_lock_invalid_wait_context(struct task_struct *curr,
  4099. struct held_lock *hlock)
  4100. {
  4101. short curr_inner;
  4102. if (!debug_locks_off())
  4103. return 0;
  4104. if (debug_locks_silent)
  4105. return 0;
  4106. nbcon_cpu_emergency_enter();
  4107. pr_warn("\n");
  4108. pr_warn("=============================\n");
  4109. pr_warn("[ BUG: Invalid wait context ]\n");
  4110. print_kernel_ident();
  4111. pr_warn("-----------------------------\n");
  4112. pr_warn("%s/%d is trying to lock:\n", curr->comm, task_pid_nr(curr));
  4113. print_lock(hlock);
  4114. pr_warn("other info that might help us debug this:\n");
  4115. curr_inner = task_wait_context(curr);
  4116. pr_warn("context-{%d:%d}\n", curr_inner, curr_inner);
  4117. lockdep_print_held_locks(curr);
  4118. pr_warn("stack backtrace:\n");
  4119. dump_stack();
  4120. nbcon_cpu_emergency_exit();
  4121. return 0;
  4122. }
  4123. /*
  4124. * Verify the wait_type context.
  4125. *
  4126. * This check validates we take locks in the right wait-type order; that is it
  4127. * ensures that we do not take mutexes inside spinlocks and do not attempt to
  4128. * acquire spinlocks inside raw_spinlocks and the sort.
  4129. *
  4130. * The entire thing is slightly more complex because of RCU, RCU is a lock that
  4131. * can be taken from (pretty much) any context but also has constraints.
  4132. * However when taken in a stricter environment the RCU lock does not loosen
  4133. * the constraints.
  4134. *
  4135. * Therefore we must look for the strictest environment in the lock stack and
  4136. * compare that to the lock we're trying to acquire.
  4137. */
  4138. static int check_wait_context(struct task_struct *curr, struct held_lock *next)
  4139. {
  4140. u8 next_inner = hlock_class(next)->wait_type_inner;
  4141. u8 next_outer = hlock_class(next)->wait_type_outer;
  4142. u8 curr_inner;
  4143. int depth;
  4144. if (!next_inner || next->trylock)
  4145. return 0;
  4146. if (!next_outer)
  4147. next_outer = next_inner;
  4148. /*
  4149. * Find start of current irq_context..
  4150. */
  4151. for (depth = curr->lockdep_depth - 1; depth >= 0; depth--) {
  4152. struct held_lock *prev = curr->held_locks + depth;
  4153. if (prev->irq_context != next->irq_context)
  4154. break;
  4155. }
  4156. depth++;
  4157. curr_inner = task_wait_context(curr);
  4158. for (; depth < curr->lockdep_depth; depth++) {
  4159. struct held_lock *prev = curr->held_locks + depth;
  4160. struct lock_class *class = hlock_class(prev);
  4161. u8 prev_inner = class->wait_type_inner;
  4162. if (prev_inner) {
  4163. /*
  4164. * We can have a bigger inner than a previous one
  4165. * when outer is smaller than inner, as with RCU.
  4166. *
  4167. * Also due to trylocks.
  4168. */
  4169. curr_inner = min(curr_inner, prev_inner);
  4170. /*
  4171. * Allow override for annotations -- this is typically
  4172. * only valid/needed for code that only exists when
  4173. * CONFIG_PREEMPT_RT=n.
  4174. */
  4175. if (unlikely(class->lock_type == LD_LOCK_WAIT_OVERRIDE))
  4176. curr_inner = prev_inner;
  4177. }
  4178. }
  4179. if (next_outer > curr_inner)
  4180. return print_lock_invalid_wait_context(curr, next);
  4181. return 0;
  4182. }
  4183. #else /* CONFIG_PROVE_LOCKING */
  4184. static inline int
  4185. mark_usage(struct task_struct *curr, struct held_lock *hlock, int check)
  4186. {
  4187. return 1;
  4188. }
  4189. static inline unsigned int task_irq_context(struct task_struct *task)
  4190. {
  4191. return 0;
  4192. }
  4193. static inline int separate_irq_context(struct task_struct *curr,
  4194. struct held_lock *hlock)
  4195. {
  4196. return 0;
  4197. }
  4198. static inline int check_wait_context(struct task_struct *curr,
  4199. struct held_lock *next)
  4200. {
  4201. return 0;
  4202. }
  4203. #endif /* CONFIG_PROVE_LOCKING */
  4204. /*
  4205. * Initialize a lock instance's lock-class mapping info:
  4206. */
  4207. void lockdep_init_map_type(struct lockdep_map *lock, const char *name,
  4208. struct lock_class_key *key, int subclass,
  4209. u8 inner, u8 outer, u8 lock_type)
  4210. {
  4211. int i;
  4212. for (i = 0; i < NR_LOCKDEP_CACHING_CLASSES; i++)
  4213. lock->class_cache[i] = NULL;
  4214. #ifdef CONFIG_LOCK_STAT
  4215. lock->cpu = raw_smp_processor_id();
  4216. #endif
  4217. /*
  4218. * Can't be having no nameless bastards around this place!
  4219. */
  4220. if (DEBUG_LOCKS_WARN_ON(!name)) {
  4221. lock->name = "NULL";
  4222. return;
  4223. }
  4224. lock->name = name;
  4225. lock->wait_type_outer = outer;
  4226. lock->wait_type_inner = inner;
  4227. lock->lock_type = lock_type;
  4228. /*
  4229. * No key, no joy, we need to hash something.
  4230. */
  4231. if (DEBUG_LOCKS_WARN_ON(!key))
  4232. return;
  4233. /*
  4234. * Sanity check, the lock-class key must either have been allocated
  4235. * statically or must have been registered as a dynamic key.
  4236. */
  4237. if (!static_obj(key) && !is_dynamic_key(key)) {
  4238. if (debug_locks)
  4239. printk(KERN_ERR "BUG: key %px has not been registered!\n", key);
  4240. DEBUG_LOCKS_WARN_ON(1);
  4241. return;
  4242. }
  4243. lock->key = key;
  4244. if (unlikely(!debug_locks))
  4245. return;
  4246. if (subclass) {
  4247. unsigned long flags;
  4248. if (DEBUG_LOCKS_WARN_ON(!lockdep_enabled()))
  4249. return;
  4250. raw_local_irq_save(flags);
  4251. lockdep_recursion_inc();
  4252. register_lock_class(lock, subclass, 1);
  4253. lockdep_recursion_finish();
  4254. raw_local_irq_restore(flags);
  4255. }
  4256. }
  4257. EXPORT_SYMBOL_GPL(lockdep_init_map_type);
  4258. struct lock_class_key __lockdep_no_validate__;
  4259. EXPORT_SYMBOL_GPL(__lockdep_no_validate__);
  4260. struct lock_class_key __lockdep_no_track__;
  4261. EXPORT_SYMBOL_GPL(__lockdep_no_track__);
  4262. #ifdef CONFIG_PROVE_LOCKING
  4263. void lockdep_set_lock_cmp_fn(struct lockdep_map *lock, lock_cmp_fn cmp_fn,
  4264. lock_print_fn print_fn)
  4265. {
  4266. struct lock_class *class = lock->class_cache[0];
  4267. unsigned long flags;
  4268. raw_local_irq_save(flags);
  4269. lockdep_recursion_inc();
  4270. if (!class)
  4271. class = register_lock_class(lock, 0, 0);
  4272. if (class) {
  4273. WARN_ON(class->cmp_fn && class->cmp_fn != cmp_fn);
  4274. WARN_ON(class->print_fn && class->print_fn != print_fn);
  4275. class->cmp_fn = cmp_fn;
  4276. class->print_fn = print_fn;
  4277. }
  4278. lockdep_recursion_finish();
  4279. raw_local_irq_restore(flags);
  4280. }
  4281. EXPORT_SYMBOL_GPL(lockdep_set_lock_cmp_fn);
  4282. #endif
  4283. static void
  4284. print_lock_nested_lock_not_held(struct task_struct *curr,
  4285. struct held_lock *hlock)
  4286. {
  4287. if (!debug_locks_off())
  4288. return;
  4289. if (debug_locks_silent)
  4290. return;
  4291. nbcon_cpu_emergency_enter();
  4292. pr_warn("\n");
  4293. pr_warn("==================================\n");
  4294. pr_warn("WARNING: Nested lock was not taken\n");
  4295. print_kernel_ident();
  4296. pr_warn("----------------------------------\n");
  4297. pr_warn("%s/%d is trying to lock:\n", curr->comm, task_pid_nr(curr));
  4298. print_lock(hlock);
  4299. pr_warn("\nbut this task is not holding:\n");
  4300. pr_warn("%s\n", hlock->nest_lock->name);
  4301. pr_warn("\nstack backtrace:\n");
  4302. dump_stack();
  4303. pr_warn("\nother info that might help us debug this:\n");
  4304. lockdep_print_held_locks(curr);
  4305. pr_warn("\nstack backtrace:\n");
  4306. dump_stack();
  4307. nbcon_cpu_emergency_exit();
  4308. }
  4309. static int __lock_is_held(const struct lockdep_map *lock, int read);
  4310. /*
  4311. * This gets called for every mutex_lock*()/spin_lock*() operation.
  4312. * We maintain the dependency maps and validate the locking attempt:
  4313. *
  4314. * The callers must make sure that IRQs are disabled before calling it,
  4315. * otherwise we could get an interrupt which would want to take locks,
  4316. * which would end up in lockdep again.
  4317. */
  4318. static int __lock_acquire(struct lockdep_map *lock, unsigned int subclass,
  4319. int trylock, int read, int check, int hardirqs_off,
  4320. struct lockdep_map *nest_lock, unsigned long ip,
  4321. int references, int pin_count, int sync)
  4322. {
  4323. struct task_struct *curr = current;
  4324. struct lock_class *class = NULL;
  4325. struct held_lock *hlock;
  4326. unsigned int depth;
  4327. int chain_head = 0;
  4328. int class_idx;
  4329. u64 chain_key;
  4330. if (unlikely(!debug_locks))
  4331. return 0;
  4332. if (unlikely(lock->key == &__lockdep_no_track__))
  4333. return 0;
  4334. if (!prove_locking || lock->key == &__lockdep_no_validate__)
  4335. check = 0;
  4336. if (subclass < NR_LOCKDEP_CACHING_CLASSES)
  4337. class = lock->class_cache[subclass];
  4338. /*
  4339. * Not cached?
  4340. */
  4341. if (unlikely(!class)) {
  4342. class = register_lock_class(lock, subclass, 0);
  4343. if (!class)
  4344. return 0;
  4345. }
  4346. debug_class_ops_inc(class);
  4347. if (very_verbose(class)) {
  4348. nbcon_cpu_emergency_enter();
  4349. printk("\nacquire class [%px] %s", class->key, class->name);
  4350. if (class->name_version > 1)
  4351. printk(KERN_CONT "#%d", class->name_version);
  4352. printk(KERN_CONT "\n");
  4353. dump_stack();
  4354. nbcon_cpu_emergency_exit();
  4355. }
  4356. /*
  4357. * Add the lock to the list of currently held locks.
  4358. * (we dont increase the depth just yet, up until the
  4359. * dependency checks are done)
  4360. */
  4361. depth = curr->lockdep_depth;
  4362. /*
  4363. * Ran out of static storage for our per-task lock stack again have we?
  4364. */
  4365. if (DEBUG_LOCKS_WARN_ON(depth >= MAX_LOCK_DEPTH))
  4366. return 0;
  4367. class_idx = class - lock_classes;
  4368. if (depth && !sync) {
  4369. /* we're holding locks and the new held lock is not a sync */
  4370. hlock = curr->held_locks + depth - 1;
  4371. if (hlock->class_idx == class_idx && nest_lock) {
  4372. if (!references)
  4373. references++;
  4374. if (!hlock->references)
  4375. hlock->references++;
  4376. hlock->references += references;
  4377. /* Overflow */
  4378. if (DEBUG_LOCKS_WARN_ON(hlock->references < references))
  4379. return 0;
  4380. return 2;
  4381. }
  4382. }
  4383. hlock = curr->held_locks + depth;
  4384. /*
  4385. * Plain impossible, we just registered it and checked it weren't no
  4386. * NULL like.. I bet this mushroom I ate was good!
  4387. */
  4388. if (DEBUG_LOCKS_WARN_ON(!class))
  4389. return 0;
  4390. hlock->class_idx = class_idx;
  4391. hlock->acquire_ip = ip;
  4392. hlock->instance = lock;
  4393. hlock->nest_lock = nest_lock;
  4394. hlock->irq_context = task_irq_context(curr);
  4395. hlock->trylock = trylock;
  4396. hlock->read = read;
  4397. hlock->check = check;
  4398. hlock->sync = !!sync;
  4399. hlock->hardirqs_off = !!hardirqs_off;
  4400. hlock->references = references;
  4401. #ifdef CONFIG_LOCK_STAT
  4402. hlock->waittime_stamp = 0;
  4403. hlock->holdtime_stamp = lockstat_clock();
  4404. #endif
  4405. hlock->pin_count = pin_count;
  4406. if (check_wait_context(curr, hlock))
  4407. return 0;
  4408. /* Initialize the lock usage bit */
  4409. if (!mark_usage(curr, hlock, check))
  4410. return 0;
  4411. /*
  4412. * Calculate the chain hash: it's the combined hash of all the
  4413. * lock keys along the dependency chain. We save the hash value
  4414. * at every step so that we can get the current hash easily
  4415. * after unlock. The chain hash is then used to cache dependency
  4416. * results.
  4417. *
  4418. * The 'key ID' is what is the most compact key value to drive
  4419. * the hash, not class->key.
  4420. */
  4421. /*
  4422. * Whoops, we did it again.. class_idx is invalid.
  4423. */
  4424. if (DEBUG_LOCKS_WARN_ON(!test_bit(class_idx, lock_classes_in_use)))
  4425. return 0;
  4426. chain_key = curr->curr_chain_key;
  4427. if (!depth) {
  4428. /*
  4429. * How can we have a chain hash when we ain't got no keys?!
  4430. */
  4431. if (DEBUG_LOCKS_WARN_ON(chain_key != INITIAL_CHAIN_KEY))
  4432. return 0;
  4433. chain_head = 1;
  4434. }
  4435. hlock->prev_chain_key = chain_key;
  4436. if (separate_irq_context(curr, hlock)) {
  4437. chain_key = INITIAL_CHAIN_KEY;
  4438. chain_head = 1;
  4439. }
  4440. chain_key = iterate_chain_key(chain_key, hlock_id(hlock));
  4441. if (nest_lock && !__lock_is_held(nest_lock, -1)) {
  4442. print_lock_nested_lock_not_held(curr, hlock);
  4443. return 0;
  4444. }
  4445. if (!debug_locks_silent) {
  4446. WARN_ON_ONCE(depth && !hlock_class(hlock - 1)->key);
  4447. WARN_ON_ONCE(!hlock_class(hlock)->key);
  4448. }
  4449. if (!validate_chain(curr, hlock, chain_head, chain_key))
  4450. return 0;
  4451. /* For lock_sync(), we are done here since no actual critical section */
  4452. if (hlock->sync)
  4453. return 1;
  4454. curr->curr_chain_key = chain_key;
  4455. curr->lockdep_depth++;
  4456. check_chain_key(curr);
  4457. #ifdef CONFIG_DEBUG_LOCKDEP
  4458. if (unlikely(!debug_locks))
  4459. return 0;
  4460. #endif
  4461. if (unlikely(curr->lockdep_depth >= MAX_LOCK_DEPTH)) {
  4462. debug_locks_off();
  4463. nbcon_cpu_emergency_enter();
  4464. print_lockdep_off("BUG: MAX_LOCK_DEPTH too low!");
  4465. printk(KERN_DEBUG "depth: %i max: %lu!\n",
  4466. curr->lockdep_depth, MAX_LOCK_DEPTH);
  4467. lockdep_print_held_locks(current);
  4468. debug_show_all_locks();
  4469. dump_stack();
  4470. nbcon_cpu_emergency_exit();
  4471. return 0;
  4472. }
  4473. if (unlikely(curr->lockdep_depth > max_lockdep_depth))
  4474. max_lockdep_depth = curr->lockdep_depth;
  4475. return 1;
  4476. }
  4477. static void print_unlock_imbalance_bug(struct task_struct *curr,
  4478. struct lockdep_map *lock,
  4479. unsigned long ip)
  4480. {
  4481. if (!debug_locks_off())
  4482. return;
  4483. if (debug_locks_silent)
  4484. return;
  4485. nbcon_cpu_emergency_enter();
  4486. pr_warn("\n");
  4487. pr_warn("=====================================\n");
  4488. pr_warn("WARNING: bad unlock balance detected!\n");
  4489. print_kernel_ident();
  4490. pr_warn("-------------------------------------\n");
  4491. pr_warn("%s/%d is trying to release lock (",
  4492. curr->comm, task_pid_nr(curr));
  4493. print_lockdep_cache(lock);
  4494. pr_cont(") at:\n");
  4495. print_ip_sym(KERN_WARNING, ip);
  4496. pr_warn("but there are no more locks to release!\n");
  4497. pr_warn("\nother info that might help us debug this:\n");
  4498. lockdep_print_held_locks(curr);
  4499. pr_warn("\nstack backtrace:\n");
  4500. dump_stack();
  4501. nbcon_cpu_emergency_exit();
  4502. }
  4503. static noinstr int match_held_lock(const struct held_lock *hlock,
  4504. const struct lockdep_map *lock)
  4505. {
  4506. if (hlock->instance == lock)
  4507. return 1;
  4508. if (hlock->references) {
  4509. const struct lock_class *class = lock->class_cache[0];
  4510. if (!class)
  4511. class = look_up_lock_class(lock, 0);
  4512. /*
  4513. * If look_up_lock_class() failed to find a class, we're trying
  4514. * to test if we hold a lock that has never yet been acquired.
  4515. * Clearly if the lock hasn't been acquired _ever_, we're not
  4516. * holding it either, so report failure.
  4517. */
  4518. if (!class)
  4519. return 0;
  4520. /*
  4521. * References, but not a lock we're actually ref-counting?
  4522. * State got messed up, follow the sites that change ->references
  4523. * and try to make sense of it.
  4524. */
  4525. if (DEBUG_LOCKS_WARN_ON(!hlock->nest_lock))
  4526. return 0;
  4527. if (hlock->class_idx == class - lock_classes)
  4528. return 1;
  4529. }
  4530. return 0;
  4531. }
  4532. /* @depth must not be zero */
  4533. static struct held_lock *find_held_lock(struct task_struct *curr,
  4534. struct lockdep_map *lock,
  4535. unsigned int depth, int *idx)
  4536. {
  4537. struct held_lock *ret, *hlock, *prev_hlock;
  4538. int i;
  4539. i = depth - 1;
  4540. hlock = curr->held_locks + i;
  4541. ret = hlock;
  4542. if (match_held_lock(hlock, lock))
  4543. goto out;
  4544. ret = NULL;
  4545. for (i--, prev_hlock = hlock--;
  4546. i >= 0;
  4547. i--, prev_hlock = hlock--) {
  4548. /*
  4549. * We must not cross into another context:
  4550. */
  4551. if (prev_hlock->irq_context != hlock->irq_context) {
  4552. ret = NULL;
  4553. break;
  4554. }
  4555. if (match_held_lock(hlock, lock)) {
  4556. ret = hlock;
  4557. break;
  4558. }
  4559. }
  4560. out:
  4561. *idx = i;
  4562. return ret;
  4563. }
  4564. static int reacquire_held_locks(struct task_struct *curr, unsigned int depth,
  4565. int idx, unsigned int *merged)
  4566. {
  4567. struct held_lock *hlock;
  4568. int first_idx = idx;
  4569. if (DEBUG_LOCKS_WARN_ON(!irqs_disabled()))
  4570. return 0;
  4571. for (hlock = curr->held_locks + idx; idx < depth; idx++, hlock++) {
  4572. switch (__lock_acquire(hlock->instance,
  4573. hlock_class(hlock)->subclass,
  4574. hlock->trylock,
  4575. hlock->read, hlock->check,
  4576. hlock->hardirqs_off,
  4577. hlock->nest_lock, hlock->acquire_ip,
  4578. hlock->references, hlock->pin_count, 0)) {
  4579. case 0:
  4580. return 1;
  4581. case 1:
  4582. break;
  4583. case 2:
  4584. *merged += (idx == first_idx);
  4585. break;
  4586. default:
  4587. WARN_ON(1);
  4588. return 0;
  4589. }
  4590. }
  4591. return 0;
  4592. }
  4593. static int
  4594. __lock_set_class(struct lockdep_map *lock, const char *name,
  4595. struct lock_class_key *key, unsigned int subclass,
  4596. unsigned long ip)
  4597. {
  4598. struct task_struct *curr = current;
  4599. unsigned int depth, merged = 0;
  4600. struct held_lock *hlock;
  4601. struct lock_class *class;
  4602. int i;
  4603. if (unlikely(!debug_locks))
  4604. return 0;
  4605. depth = curr->lockdep_depth;
  4606. /*
  4607. * This function is about (re)setting the class of a held lock,
  4608. * yet we're not actually holding any locks. Naughty user!
  4609. */
  4610. if (DEBUG_LOCKS_WARN_ON(!depth))
  4611. return 0;
  4612. hlock = find_held_lock(curr, lock, depth, &i);
  4613. if (!hlock) {
  4614. print_unlock_imbalance_bug(curr, lock, ip);
  4615. return 0;
  4616. }
  4617. lockdep_init_map_type(lock, name, key, 0,
  4618. lock->wait_type_inner,
  4619. lock->wait_type_outer,
  4620. lock->lock_type);
  4621. class = register_lock_class(lock, subclass, 0);
  4622. hlock->class_idx = class - lock_classes;
  4623. curr->lockdep_depth = i;
  4624. curr->curr_chain_key = hlock->prev_chain_key;
  4625. if (reacquire_held_locks(curr, depth, i, &merged))
  4626. return 0;
  4627. /*
  4628. * I took it apart and put it back together again, except now I have
  4629. * these 'spare' parts.. where shall I put them.
  4630. */
  4631. if (DEBUG_LOCKS_WARN_ON(curr->lockdep_depth != depth - merged))
  4632. return 0;
  4633. return 1;
  4634. }
  4635. static int __lock_downgrade(struct lockdep_map *lock, unsigned long ip)
  4636. {
  4637. struct task_struct *curr = current;
  4638. unsigned int depth, merged = 0;
  4639. struct held_lock *hlock;
  4640. int i;
  4641. if (unlikely(!debug_locks))
  4642. return 0;
  4643. depth = curr->lockdep_depth;
  4644. /*
  4645. * This function is about (re)setting the class of a held lock,
  4646. * yet we're not actually holding any locks. Naughty user!
  4647. */
  4648. if (DEBUG_LOCKS_WARN_ON(!depth))
  4649. return 0;
  4650. hlock = find_held_lock(curr, lock, depth, &i);
  4651. if (!hlock) {
  4652. print_unlock_imbalance_bug(curr, lock, ip);
  4653. return 0;
  4654. }
  4655. curr->lockdep_depth = i;
  4656. curr->curr_chain_key = hlock->prev_chain_key;
  4657. WARN(hlock->read, "downgrading a read lock");
  4658. hlock->read = 1;
  4659. hlock->acquire_ip = ip;
  4660. if (reacquire_held_locks(curr, depth, i, &merged))
  4661. return 0;
  4662. /* Merging can't happen with unchanged classes.. */
  4663. if (DEBUG_LOCKS_WARN_ON(merged))
  4664. return 0;
  4665. /*
  4666. * I took it apart and put it back together again, except now I have
  4667. * these 'spare' parts.. where shall I put them.
  4668. */
  4669. if (DEBUG_LOCKS_WARN_ON(curr->lockdep_depth != depth))
  4670. return 0;
  4671. return 1;
  4672. }
  4673. /*
  4674. * Remove the lock from the list of currently held locks - this gets
  4675. * called on mutex_unlock()/spin_unlock*() (or on a failed
  4676. * mutex_lock_interruptible()).
  4677. */
  4678. static int
  4679. __lock_release(struct lockdep_map *lock, unsigned long ip)
  4680. {
  4681. struct task_struct *curr = current;
  4682. unsigned int depth, merged = 1;
  4683. struct held_lock *hlock;
  4684. int i;
  4685. if (unlikely(!debug_locks))
  4686. return 0;
  4687. depth = curr->lockdep_depth;
  4688. /*
  4689. * So we're all set to release this lock.. wait what lock? We don't
  4690. * own any locks, you've been drinking again?
  4691. */
  4692. if (depth <= 0) {
  4693. print_unlock_imbalance_bug(curr, lock, ip);
  4694. return 0;
  4695. }
  4696. /*
  4697. * Check whether the lock exists in the current stack
  4698. * of held locks:
  4699. */
  4700. hlock = find_held_lock(curr, lock, depth, &i);
  4701. if (!hlock) {
  4702. print_unlock_imbalance_bug(curr, lock, ip);
  4703. return 0;
  4704. }
  4705. if (hlock->instance == lock)
  4706. lock_release_holdtime(hlock);
  4707. WARN(hlock->pin_count, "releasing a pinned lock\n");
  4708. if (hlock->references) {
  4709. hlock->references--;
  4710. if (hlock->references) {
  4711. /*
  4712. * We had, and after removing one, still have
  4713. * references, the current lock stack is still
  4714. * valid. We're done!
  4715. */
  4716. return 1;
  4717. }
  4718. }
  4719. /*
  4720. * We have the right lock to unlock, 'hlock' points to it.
  4721. * Now we remove it from the stack, and add back the other
  4722. * entries (if any), recalculating the hash along the way:
  4723. */
  4724. curr->lockdep_depth = i;
  4725. curr->curr_chain_key = hlock->prev_chain_key;
  4726. /*
  4727. * The most likely case is when the unlock is on the innermost
  4728. * lock. In this case, we are done!
  4729. */
  4730. if (i == depth-1)
  4731. return 1;
  4732. if (reacquire_held_locks(curr, depth, i + 1, &merged))
  4733. return 0;
  4734. /*
  4735. * We had N bottles of beer on the wall, we drank one, but now
  4736. * there's not N-1 bottles of beer left on the wall...
  4737. * Pouring two of the bottles together is acceptable.
  4738. */
  4739. DEBUG_LOCKS_WARN_ON(curr->lockdep_depth != depth - merged);
  4740. /*
  4741. * Since reacquire_held_locks() would have called check_chain_key()
  4742. * indirectly via __lock_acquire(), we don't need to do it again
  4743. * on return.
  4744. */
  4745. return 0;
  4746. }
  4747. static __always_inline
  4748. int __lock_is_held(const struct lockdep_map *lock, int read)
  4749. {
  4750. struct task_struct *curr = current;
  4751. int i;
  4752. for (i = 0; i < curr->lockdep_depth; i++) {
  4753. struct held_lock *hlock = curr->held_locks + i;
  4754. if (match_held_lock(hlock, lock)) {
  4755. if (read == -1 || !!hlock->read == read)
  4756. return LOCK_STATE_HELD;
  4757. return LOCK_STATE_NOT_HELD;
  4758. }
  4759. }
  4760. return LOCK_STATE_NOT_HELD;
  4761. }
  4762. static struct pin_cookie __lock_pin_lock(struct lockdep_map *lock)
  4763. {
  4764. struct pin_cookie cookie = NIL_COOKIE;
  4765. struct task_struct *curr = current;
  4766. int i;
  4767. if (unlikely(!debug_locks))
  4768. return cookie;
  4769. for (i = 0; i < curr->lockdep_depth; i++) {
  4770. struct held_lock *hlock = curr->held_locks + i;
  4771. if (match_held_lock(hlock, lock)) {
  4772. /*
  4773. * Grab 16bits of randomness; this is sufficient to not
  4774. * be guessable and still allows some pin nesting in
  4775. * our u32 pin_count.
  4776. */
  4777. cookie.val = 1 + (sched_clock() & 0xffff);
  4778. hlock->pin_count += cookie.val;
  4779. return cookie;
  4780. }
  4781. }
  4782. WARN(1, "pinning an unheld lock\n");
  4783. return cookie;
  4784. }
  4785. static void __lock_repin_lock(struct lockdep_map *lock, struct pin_cookie cookie)
  4786. {
  4787. struct task_struct *curr = current;
  4788. int i;
  4789. if (unlikely(!debug_locks))
  4790. return;
  4791. for (i = 0; i < curr->lockdep_depth; i++) {
  4792. struct held_lock *hlock = curr->held_locks + i;
  4793. if (match_held_lock(hlock, lock)) {
  4794. hlock->pin_count += cookie.val;
  4795. return;
  4796. }
  4797. }
  4798. WARN(1, "pinning an unheld lock\n");
  4799. }
  4800. static void __lock_unpin_lock(struct lockdep_map *lock, struct pin_cookie cookie)
  4801. {
  4802. struct task_struct *curr = current;
  4803. int i;
  4804. if (unlikely(!debug_locks))
  4805. return;
  4806. for (i = 0; i < curr->lockdep_depth; i++) {
  4807. struct held_lock *hlock = curr->held_locks + i;
  4808. if (match_held_lock(hlock, lock)) {
  4809. if (WARN(!hlock->pin_count, "unpinning an unpinned lock\n"))
  4810. return;
  4811. hlock->pin_count -= cookie.val;
  4812. if (WARN((int)hlock->pin_count < 0, "pin count corrupted\n"))
  4813. hlock->pin_count = 0;
  4814. return;
  4815. }
  4816. }
  4817. WARN(1, "unpinning an unheld lock\n");
  4818. }
  4819. /*
  4820. * Check whether we follow the irq-flags state precisely:
  4821. */
  4822. static noinstr void check_flags(unsigned long flags)
  4823. {
  4824. #if defined(CONFIG_PROVE_LOCKING) && defined(CONFIG_DEBUG_LOCKDEP)
  4825. if (!debug_locks)
  4826. return;
  4827. /* Get the warning out.. */
  4828. instrumentation_begin();
  4829. if (irqs_disabled_flags(flags)) {
  4830. if (DEBUG_LOCKS_WARN_ON(lockdep_hardirqs_enabled())) {
  4831. printk("possible reason: unannotated irqs-off.\n");
  4832. }
  4833. } else {
  4834. if (DEBUG_LOCKS_WARN_ON(!lockdep_hardirqs_enabled())) {
  4835. printk("possible reason: unannotated irqs-on.\n");
  4836. }
  4837. }
  4838. #ifndef CONFIG_PREEMPT_RT
  4839. /*
  4840. * We dont accurately track softirq state in e.g.
  4841. * hardirq contexts (such as on 4KSTACKS), so only
  4842. * check if not in hardirq contexts:
  4843. */
  4844. if (!hardirq_count()) {
  4845. if (softirq_count()) {
  4846. /* like the above, but with softirqs */
  4847. DEBUG_LOCKS_WARN_ON(current->softirqs_enabled);
  4848. } else {
  4849. /* lick the above, does it taste good? */
  4850. DEBUG_LOCKS_WARN_ON(!current->softirqs_enabled);
  4851. }
  4852. }
  4853. #endif
  4854. if (!debug_locks)
  4855. print_irqtrace_events(current);
  4856. instrumentation_end();
  4857. #endif
  4858. }
  4859. void lock_set_class(struct lockdep_map *lock, const char *name,
  4860. struct lock_class_key *key, unsigned int subclass,
  4861. unsigned long ip)
  4862. {
  4863. unsigned long flags;
  4864. if (unlikely(!lockdep_enabled()))
  4865. return;
  4866. raw_local_irq_save(flags);
  4867. lockdep_recursion_inc();
  4868. check_flags(flags);
  4869. if (__lock_set_class(lock, name, key, subclass, ip))
  4870. check_chain_key(current);
  4871. lockdep_recursion_finish();
  4872. raw_local_irq_restore(flags);
  4873. }
  4874. EXPORT_SYMBOL_GPL(lock_set_class);
  4875. void lock_downgrade(struct lockdep_map *lock, unsigned long ip)
  4876. {
  4877. unsigned long flags;
  4878. if (unlikely(!lockdep_enabled()))
  4879. return;
  4880. raw_local_irq_save(flags);
  4881. lockdep_recursion_inc();
  4882. check_flags(flags);
  4883. if (__lock_downgrade(lock, ip))
  4884. check_chain_key(current);
  4885. lockdep_recursion_finish();
  4886. raw_local_irq_restore(flags);
  4887. }
  4888. EXPORT_SYMBOL_GPL(lock_downgrade);
  4889. /* NMI context !!! */
  4890. static void verify_lock_unused(struct lockdep_map *lock, struct held_lock *hlock, int subclass)
  4891. {
  4892. #ifdef CONFIG_PROVE_LOCKING
  4893. struct lock_class *class = look_up_lock_class(lock, subclass);
  4894. unsigned long mask = LOCKF_USED;
  4895. /* if it doesn't have a class (yet), it certainly hasn't been used yet */
  4896. if (!class)
  4897. return;
  4898. /*
  4899. * READ locks only conflict with USED, such that if we only ever use
  4900. * READ locks, there is no deadlock possible -- RCU.
  4901. */
  4902. if (!hlock->read)
  4903. mask |= LOCKF_USED_READ;
  4904. if (!(class->usage_mask & mask))
  4905. return;
  4906. hlock->class_idx = class - lock_classes;
  4907. print_usage_bug(current, hlock, LOCK_USED, LOCK_USAGE_STATES);
  4908. #endif
  4909. }
  4910. static bool lockdep_nmi(void)
  4911. {
  4912. if (raw_cpu_read(lockdep_recursion))
  4913. return false;
  4914. if (!in_nmi())
  4915. return false;
  4916. return true;
  4917. }
  4918. /*
  4919. * read_lock() is recursive if:
  4920. * 1. We force lockdep think this way in selftests or
  4921. * 2. The implementation is not queued read/write lock or
  4922. * 3. The locker is at an in_interrupt() context.
  4923. */
  4924. bool read_lock_is_recursive(void)
  4925. {
  4926. return force_read_lock_recursive ||
  4927. !IS_ENABLED(CONFIG_QUEUED_RWLOCKS) ||
  4928. in_interrupt();
  4929. }
  4930. EXPORT_SYMBOL_GPL(read_lock_is_recursive);
  4931. /*
  4932. * We are not always called with irqs disabled - do that here,
  4933. * and also avoid lockdep recursion:
  4934. */
  4935. void lock_acquire(struct lockdep_map *lock, unsigned int subclass,
  4936. int trylock, int read, int check,
  4937. struct lockdep_map *nest_lock, unsigned long ip)
  4938. {
  4939. unsigned long flags;
  4940. trace_lock_acquire(lock, subclass, trylock, read, check, nest_lock, ip);
  4941. if (!debug_locks)
  4942. return;
  4943. if (unlikely(!lockdep_enabled())) {
  4944. /* XXX allow trylock from NMI ?!? */
  4945. if (lockdep_nmi() && !trylock) {
  4946. struct held_lock hlock;
  4947. hlock.acquire_ip = ip;
  4948. hlock.instance = lock;
  4949. hlock.nest_lock = nest_lock;
  4950. hlock.irq_context = 2; // XXX
  4951. hlock.trylock = trylock;
  4952. hlock.read = read;
  4953. hlock.check = check;
  4954. hlock.hardirqs_off = true;
  4955. hlock.references = 0;
  4956. verify_lock_unused(lock, &hlock, subclass);
  4957. }
  4958. return;
  4959. }
  4960. raw_local_irq_save(flags);
  4961. check_flags(flags);
  4962. lockdep_recursion_inc();
  4963. __lock_acquire(lock, subclass, trylock, read, check,
  4964. irqs_disabled_flags(flags), nest_lock, ip, 0, 0, 0);
  4965. lockdep_recursion_finish();
  4966. raw_local_irq_restore(flags);
  4967. }
  4968. EXPORT_SYMBOL_GPL(lock_acquire);
  4969. void lock_release(struct lockdep_map *lock, unsigned long ip)
  4970. {
  4971. unsigned long flags;
  4972. trace_lock_release(lock, ip);
  4973. if (unlikely(!lockdep_enabled() ||
  4974. lock->key == &__lockdep_no_track__))
  4975. return;
  4976. raw_local_irq_save(flags);
  4977. check_flags(flags);
  4978. lockdep_recursion_inc();
  4979. if (__lock_release(lock, ip))
  4980. check_chain_key(current);
  4981. lockdep_recursion_finish();
  4982. raw_local_irq_restore(flags);
  4983. }
  4984. EXPORT_SYMBOL_GPL(lock_release);
  4985. /*
  4986. * lock_sync() - A special annotation for synchronize_{s,}rcu()-like API.
  4987. *
  4988. * No actual critical section is created by the APIs annotated with this: these
  4989. * APIs are used to wait for one or multiple critical sections (on other CPUs
  4990. * or threads), and it means that calling these APIs inside these critical
  4991. * sections is potential deadlock.
  4992. */
  4993. void lock_sync(struct lockdep_map *lock, unsigned subclass, int read,
  4994. int check, struct lockdep_map *nest_lock, unsigned long ip)
  4995. {
  4996. unsigned long flags;
  4997. if (unlikely(!lockdep_enabled()))
  4998. return;
  4999. raw_local_irq_save(flags);
  5000. check_flags(flags);
  5001. lockdep_recursion_inc();
  5002. __lock_acquire(lock, subclass, 0, read, check,
  5003. irqs_disabled_flags(flags), nest_lock, ip, 0, 0, 1);
  5004. check_chain_key(current);
  5005. lockdep_recursion_finish();
  5006. raw_local_irq_restore(flags);
  5007. }
  5008. EXPORT_SYMBOL_GPL(lock_sync);
  5009. noinstr int lock_is_held_type(const struct lockdep_map *lock, int read)
  5010. {
  5011. unsigned long flags;
  5012. int ret = LOCK_STATE_NOT_HELD;
  5013. /*
  5014. * Avoid false negative lockdep_assert_held() and
  5015. * lockdep_assert_not_held().
  5016. */
  5017. if (unlikely(!lockdep_enabled()))
  5018. return LOCK_STATE_UNKNOWN;
  5019. raw_local_irq_save(flags);
  5020. check_flags(flags);
  5021. lockdep_recursion_inc();
  5022. ret = __lock_is_held(lock, read);
  5023. lockdep_recursion_finish();
  5024. raw_local_irq_restore(flags);
  5025. return ret;
  5026. }
  5027. EXPORT_SYMBOL_GPL(lock_is_held_type);
  5028. NOKPROBE_SYMBOL(lock_is_held_type);
  5029. struct pin_cookie lock_pin_lock(struct lockdep_map *lock)
  5030. {
  5031. struct pin_cookie cookie = NIL_COOKIE;
  5032. unsigned long flags;
  5033. if (unlikely(!lockdep_enabled()))
  5034. return cookie;
  5035. raw_local_irq_save(flags);
  5036. check_flags(flags);
  5037. lockdep_recursion_inc();
  5038. cookie = __lock_pin_lock(lock);
  5039. lockdep_recursion_finish();
  5040. raw_local_irq_restore(flags);
  5041. return cookie;
  5042. }
  5043. EXPORT_SYMBOL_GPL(lock_pin_lock);
  5044. void lock_repin_lock(struct lockdep_map *lock, struct pin_cookie cookie)
  5045. {
  5046. unsigned long flags;
  5047. if (unlikely(!lockdep_enabled()))
  5048. return;
  5049. raw_local_irq_save(flags);
  5050. check_flags(flags);
  5051. lockdep_recursion_inc();
  5052. __lock_repin_lock(lock, cookie);
  5053. lockdep_recursion_finish();
  5054. raw_local_irq_restore(flags);
  5055. }
  5056. EXPORT_SYMBOL_GPL(lock_repin_lock);
  5057. void lock_unpin_lock(struct lockdep_map *lock, struct pin_cookie cookie)
  5058. {
  5059. unsigned long flags;
  5060. if (unlikely(!lockdep_enabled()))
  5061. return;
  5062. raw_local_irq_save(flags);
  5063. check_flags(flags);
  5064. lockdep_recursion_inc();
  5065. __lock_unpin_lock(lock, cookie);
  5066. lockdep_recursion_finish();
  5067. raw_local_irq_restore(flags);
  5068. }
  5069. EXPORT_SYMBOL_GPL(lock_unpin_lock);
  5070. #ifdef CONFIG_LOCK_STAT
  5071. static void print_lock_contention_bug(struct task_struct *curr,
  5072. struct lockdep_map *lock,
  5073. unsigned long ip)
  5074. {
  5075. if (!debug_locks_off())
  5076. return;
  5077. if (debug_locks_silent)
  5078. return;
  5079. nbcon_cpu_emergency_enter();
  5080. pr_warn("\n");
  5081. pr_warn("=================================\n");
  5082. pr_warn("WARNING: bad contention detected!\n");
  5083. print_kernel_ident();
  5084. pr_warn("---------------------------------\n");
  5085. pr_warn("%s/%d is trying to contend lock (",
  5086. curr->comm, task_pid_nr(curr));
  5087. print_lockdep_cache(lock);
  5088. pr_cont(") at:\n");
  5089. print_ip_sym(KERN_WARNING, ip);
  5090. pr_warn("but there are no locks held!\n");
  5091. pr_warn("\nother info that might help us debug this:\n");
  5092. lockdep_print_held_locks(curr);
  5093. pr_warn("\nstack backtrace:\n");
  5094. dump_stack();
  5095. nbcon_cpu_emergency_exit();
  5096. }
  5097. static void
  5098. __lock_contended(struct lockdep_map *lock, unsigned long ip)
  5099. {
  5100. struct task_struct *curr = current;
  5101. struct held_lock *hlock;
  5102. struct lock_class_stats *stats;
  5103. unsigned int depth;
  5104. int i, contention_point, contending_point;
  5105. depth = curr->lockdep_depth;
  5106. /*
  5107. * Whee, we contended on this lock, except it seems we're not
  5108. * actually trying to acquire anything much at all..
  5109. */
  5110. if (DEBUG_LOCKS_WARN_ON(!depth))
  5111. return;
  5112. if (unlikely(lock->key == &__lockdep_no_track__))
  5113. return;
  5114. hlock = find_held_lock(curr, lock, depth, &i);
  5115. if (!hlock) {
  5116. print_lock_contention_bug(curr, lock, ip);
  5117. return;
  5118. }
  5119. if (hlock->instance != lock)
  5120. return;
  5121. hlock->waittime_stamp = lockstat_clock();
  5122. contention_point = lock_point(hlock_class(hlock)->contention_point, ip);
  5123. contending_point = lock_point(hlock_class(hlock)->contending_point,
  5124. lock->ip);
  5125. stats = get_lock_stats(hlock_class(hlock));
  5126. if (contention_point < LOCKSTAT_POINTS)
  5127. stats->contention_point[contention_point]++;
  5128. if (contending_point < LOCKSTAT_POINTS)
  5129. stats->contending_point[contending_point]++;
  5130. if (lock->cpu != smp_processor_id())
  5131. stats->bounces[bounce_contended + !!hlock->read]++;
  5132. }
  5133. static void
  5134. __lock_acquired(struct lockdep_map *lock, unsigned long ip)
  5135. {
  5136. struct task_struct *curr = current;
  5137. struct held_lock *hlock;
  5138. struct lock_class_stats *stats;
  5139. unsigned int depth;
  5140. u64 now, waittime = 0;
  5141. int i, cpu;
  5142. depth = curr->lockdep_depth;
  5143. /*
  5144. * Yay, we acquired ownership of this lock we didn't try to
  5145. * acquire, how the heck did that happen?
  5146. */
  5147. if (DEBUG_LOCKS_WARN_ON(!depth))
  5148. return;
  5149. if (unlikely(lock->key == &__lockdep_no_track__))
  5150. return;
  5151. hlock = find_held_lock(curr, lock, depth, &i);
  5152. if (!hlock) {
  5153. print_lock_contention_bug(curr, lock, _RET_IP_);
  5154. return;
  5155. }
  5156. if (hlock->instance != lock)
  5157. return;
  5158. cpu = smp_processor_id();
  5159. if (hlock->waittime_stamp) {
  5160. now = lockstat_clock();
  5161. waittime = now - hlock->waittime_stamp;
  5162. hlock->holdtime_stamp = now;
  5163. }
  5164. stats = get_lock_stats(hlock_class(hlock));
  5165. if (waittime) {
  5166. if (hlock->read)
  5167. lock_time_inc(&stats->read_waittime, waittime);
  5168. else
  5169. lock_time_inc(&stats->write_waittime, waittime);
  5170. }
  5171. if (lock->cpu != cpu)
  5172. stats->bounces[bounce_acquired + !!hlock->read]++;
  5173. lock->cpu = cpu;
  5174. lock->ip = ip;
  5175. }
  5176. void lock_contended(struct lockdep_map *lock, unsigned long ip)
  5177. {
  5178. unsigned long flags;
  5179. trace_lock_contended(lock, ip);
  5180. if (unlikely(!lock_stat || !lockdep_enabled()))
  5181. return;
  5182. raw_local_irq_save(flags);
  5183. check_flags(flags);
  5184. lockdep_recursion_inc();
  5185. __lock_contended(lock, ip);
  5186. lockdep_recursion_finish();
  5187. raw_local_irq_restore(flags);
  5188. }
  5189. EXPORT_SYMBOL_GPL(lock_contended);
  5190. void lock_acquired(struct lockdep_map *lock, unsigned long ip)
  5191. {
  5192. unsigned long flags;
  5193. trace_lock_acquired(lock, ip);
  5194. if (unlikely(!lock_stat || !lockdep_enabled()))
  5195. return;
  5196. raw_local_irq_save(flags);
  5197. check_flags(flags);
  5198. lockdep_recursion_inc();
  5199. __lock_acquired(lock, ip);
  5200. lockdep_recursion_finish();
  5201. raw_local_irq_restore(flags);
  5202. }
  5203. EXPORT_SYMBOL_GPL(lock_acquired);
  5204. #endif
  5205. /*
  5206. * Used by the testsuite, sanitize the validator state
  5207. * after a simulated failure:
  5208. */
  5209. void lockdep_reset(void)
  5210. {
  5211. unsigned long flags;
  5212. int i;
  5213. raw_local_irq_save(flags);
  5214. lockdep_init_task(current);
  5215. memset(current->held_locks, 0, MAX_LOCK_DEPTH*sizeof(struct held_lock));
  5216. nr_hardirq_chains = 0;
  5217. nr_softirq_chains = 0;
  5218. nr_process_chains = 0;
  5219. debug_locks = 1;
  5220. for (i = 0; i < CHAINHASH_SIZE; i++)
  5221. INIT_HLIST_HEAD(chainhash_table + i);
  5222. raw_local_irq_restore(flags);
  5223. }
  5224. /* Remove a class from a lock chain. Must be called with the graph lock held. */
  5225. static void remove_class_from_lock_chain(struct pending_free *pf,
  5226. struct lock_chain *chain,
  5227. struct lock_class *class)
  5228. {
  5229. #ifdef CONFIG_PROVE_LOCKING
  5230. int i;
  5231. for (i = chain->base; i < chain->base + chain->depth; i++) {
  5232. if (chain_hlock_class_idx(chain_hlocks[i]) != class - lock_classes)
  5233. continue;
  5234. /*
  5235. * Each lock class occurs at most once in a lock chain so once
  5236. * we found a match we can break out of this loop.
  5237. */
  5238. goto free_lock_chain;
  5239. }
  5240. /* Since the chain has not been modified, return. */
  5241. return;
  5242. free_lock_chain:
  5243. free_chain_hlocks(chain->base, chain->depth);
  5244. /* Overwrite the chain key for concurrent RCU readers. */
  5245. WRITE_ONCE(chain->chain_key, INITIAL_CHAIN_KEY);
  5246. dec_chains(chain->irq_context);
  5247. /*
  5248. * Note: calling hlist_del_rcu() from inside a
  5249. * hlist_for_each_entry_rcu() loop is safe.
  5250. */
  5251. hlist_del_rcu(&chain->entry);
  5252. __set_bit(chain - lock_chains, pf->lock_chains_being_freed);
  5253. nr_zapped_lock_chains++;
  5254. #endif
  5255. }
  5256. /* Must be called with the graph lock held. */
  5257. static void remove_class_from_lock_chains(struct pending_free *pf,
  5258. struct lock_class *class)
  5259. {
  5260. struct lock_chain *chain;
  5261. struct hlist_head *head;
  5262. int i;
  5263. for (i = 0; i < ARRAY_SIZE(chainhash_table); i++) {
  5264. head = chainhash_table + i;
  5265. hlist_for_each_entry_rcu(chain, head, entry) {
  5266. remove_class_from_lock_chain(pf, chain, class);
  5267. }
  5268. }
  5269. }
  5270. /*
  5271. * Remove all references to a lock class. The caller must hold the graph lock.
  5272. */
  5273. static void zap_class(struct pending_free *pf, struct lock_class *class)
  5274. {
  5275. struct lock_list *entry;
  5276. int i;
  5277. WARN_ON_ONCE(!class->key);
  5278. /*
  5279. * Remove all dependencies this lock is
  5280. * involved in:
  5281. */
  5282. for_each_set_bit(i, list_entries_in_use, ARRAY_SIZE(list_entries)) {
  5283. entry = list_entries + i;
  5284. if (entry->class != class && entry->links_to != class)
  5285. continue;
  5286. __clear_bit(i, list_entries_in_use);
  5287. nr_list_entries--;
  5288. list_del_rcu(&entry->entry);
  5289. }
  5290. if (list_empty(&class->locks_after) &&
  5291. list_empty(&class->locks_before)) {
  5292. list_move_tail(&class->lock_entry, &pf->zapped);
  5293. hlist_del_rcu(&class->hash_entry);
  5294. WRITE_ONCE(class->key, NULL);
  5295. WRITE_ONCE(class->name, NULL);
  5296. /* Class allocated but not used, -1 in nr_unused_locks */
  5297. if (class->usage_mask == 0)
  5298. debug_atomic_dec(nr_unused_locks);
  5299. nr_lock_classes--;
  5300. __clear_bit(class - lock_classes, lock_classes_in_use);
  5301. if (class - lock_classes == max_lock_class_idx)
  5302. max_lock_class_idx--;
  5303. } else {
  5304. WARN_ONCE(true, "%s() failed for class %s\n", __func__,
  5305. class->name);
  5306. }
  5307. remove_class_from_lock_chains(pf, class);
  5308. nr_zapped_classes++;
  5309. }
  5310. static void reinit_class(struct lock_class *class)
  5311. {
  5312. WARN_ON_ONCE(!class->lock_entry.next);
  5313. WARN_ON_ONCE(!list_empty(&class->locks_after));
  5314. WARN_ON_ONCE(!list_empty(&class->locks_before));
  5315. memset_startat(class, 0, key);
  5316. WARN_ON_ONCE(!class->lock_entry.next);
  5317. WARN_ON_ONCE(!list_empty(&class->locks_after));
  5318. WARN_ON_ONCE(!list_empty(&class->locks_before));
  5319. }
  5320. static inline int within(const void *addr, void *start, unsigned long size)
  5321. {
  5322. return addr >= start && addr < start + size;
  5323. }
  5324. static bool inside_selftest(void)
  5325. {
  5326. return current == lockdep_selftest_task_struct;
  5327. }
  5328. /* The caller must hold the graph lock. */
  5329. static struct pending_free *get_pending_free(void)
  5330. {
  5331. return delayed_free.pf + delayed_free.index;
  5332. }
  5333. static void free_zapped_rcu(struct rcu_head *cb);
  5334. /*
  5335. * See if we need to queue an RCU callback, must called with
  5336. * the lockdep lock held, returns false if either we don't have
  5337. * any pending free or the callback is already scheduled.
  5338. * Otherwise, a call_rcu() must follow this function call.
  5339. */
  5340. static bool prepare_call_rcu_zapped(struct pending_free *pf)
  5341. {
  5342. WARN_ON_ONCE(inside_selftest());
  5343. if (list_empty(&pf->zapped))
  5344. return false;
  5345. if (delayed_free.scheduled)
  5346. return false;
  5347. delayed_free.scheduled = true;
  5348. WARN_ON_ONCE(delayed_free.pf + delayed_free.index != pf);
  5349. delayed_free.index ^= 1;
  5350. return true;
  5351. }
  5352. /* The caller must hold the graph lock. May be called from RCU context. */
  5353. static void __free_zapped_classes(struct pending_free *pf)
  5354. {
  5355. struct lock_class *class;
  5356. check_data_structures();
  5357. list_for_each_entry(class, &pf->zapped, lock_entry)
  5358. reinit_class(class);
  5359. list_splice_init(&pf->zapped, &free_lock_classes);
  5360. #ifdef CONFIG_PROVE_LOCKING
  5361. bitmap_andnot(lock_chains_in_use, lock_chains_in_use,
  5362. pf->lock_chains_being_freed, ARRAY_SIZE(lock_chains));
  5363. bitmap_clear(pf->lock_chains_being_freed, 0, ARRAY_SIZE(lock_chains));
  5364. #endif
  5365. }
  5366. static void free_zapped_rcu(struct rcu_head *ch)
  5367. {
  5368. struct pending_free *pf;
  5369. unsigned long flags;
  5370. bool need_callback;
  5371. if (WARN_ON_ONCE(ch != &delayed_free.rcu_head))
  5372. return;
  5373. raw_local_irq_save(flags);
  5374. lockdep_lock();
  5375. /* closed head */
  5376. pf = delayed_free.pf + (delayed_free.index ^ 1);
  5377. __free_zapped_classes(pf);
  5378. delayed_free.scheduled = false;
  5379. need_callback =
  5380. prepare_call_rcu_zapped(delayed_free.pf + delayed_free.index);
  5381. lockdep_unlock();
  5382. raw_local_irq_restore(flags);
  5383. /*
  5384. * If there's pending free and its callback has not been scheduled,
  5385. * queue an RCU callback.
  5386. */
  5387. if (need_callback)
  5388. call_rcu(&delayed_free.rcu_head, free_zapped_rcu);
  5389. }
  5390. /*
  5391. * Remove all lock classes from the class hash table and from the
  5392. * all_lock_classes list whose key or name is in the address range [start,
  5393. * start + size). Move these lock classes to the zapped_classes list. Must
  5394. * be called with the graph lock held.
  5395. */
  5396. static void __lockdep_free_key_range(struct pending_free *pf, void *start,
  5397. unsigned long size)
  5398. {
  5399. struct lock_class *class;
  5400. struct hlist_head *head;
  5401. int i;
  5402. /* Unhash all classes that were created by a module. */
  5403. for (i = 0; i < CLASSHASH_SIZE; i++) {
  5404. head = classhash_table + i;
  5405. hlist_for_each_entry_rcu(class, head, hash_entry) {
  5406. if (!within(class->key, start, size) &&
  5407. !within(class->name, start, size))
  5408. continue;
  5409. zap_class(pf, class);
  5410. }
  5411. }
  5412. }
  5413. /*
  5414. * Used in module.c to remove lock classes from memory that is going to be
  5415. * freed; and possibly re-used by other modules.
  5416. *
  5417. * We will have had one synchronize_rcu() before getting here, so we're
  5418. * guaranteed nobody will look up these exact classes -- they're properly dead
  5419. * but still allocated.
  5420. */
  5421. static void lockdep_free_key_range_reg(void *start, unsigned long size)
  5422. {
  5423. struct pending_free *pf;
  5424. unsigned long flags;
  5425. bool need_callback;
  5426. init_data_structures_once();
  5427. raw_local_irq_save(flags);
  5428. lockdep_lock();
  5429. pf = get_pending_free();
  5430. __lockdep_free_key_range(pf, start, size);
  5431. need_callback = prepare_call_rcu_zapped(pf);
  5432. lockdep_unlock();
  5433. raw_local_irq_restore(flags);
  5434. if (need_callback)
  5435. call_rcu(&delayed_free.rcu_head, free_zapped_rcu);
  5436. /*
  5437. * Wait for any possible iterators from look_up_lock_class() to pass
  5438. * before continuing to free the memory they refer to.
  5439. */
  5440. synchronize_rcu();
  5441. }
  5442. /*
  5443. * Free all lockdep keys in the range [start, start+size). Does not sleep.
  5444. * Ignores debug_locks. Must only be used by the lockdep selftests.
  5445. */
  5446. static void lockdep_free_key_range_imm(void *start, unsigned long size)
  5447. {
  5448. struct pending_free *pf = delayed_free.pf;
  5449. unsigned long flags;
  5450. init_data_structures_once();
  5451. raw_local_irq_save(flags);
  5452. lockdep_lock();
  5453. __lockdep_free_key_range(pf, start, size);
  5454. __free_zapped_classes(pf);
  5455. lockdep_unlock();
  5456. raw_local_irq_restore(flags);
  5457. }
  5458. void lockdep_free_key_range(void *start, unsigned long size)
  5459. {
  5460. init_data_structures_once();
  5461. if (inside_selftest())
  5462. lockdep_free_key_range_imm(start, size);
  5463. else
  5464. lockdep_free_key_range_reg(start, size);
  5465. }
  5466. /*
  5467. * Check whether any element of the @lock->class_cache[] array refers to a
  5468. * registered lock class. The caller must hold either the graph lock or the
  5469. * RCU read lock.
  5470. */
  5471. static bool lock_class_cache_is_registered(struct lockdep_map *lock)
  5472. {
  5473. struct lock_class *class;
  5474. struct hlist_head *head;
  5475. int i, j;
  5476. for (i = 0; i < CLASSHASH_SIZE; i++) {
  5477. head = classhash_table + i;
  5478. hlist_for_each_entry_rcu(class, head, hash_entry) {
  5479. for (j = 0; j < NR_LOCKDEP_CACHING_CLASSES; j++)
  5480. if (lock->class_cache[j] == class)
  5481. return true;
  5482. }
  5483. }
  5484. return false;
  5485. }
  5486. /* The caller must hold the graph lock. Does not sleep. */
  5487. static void __lockdep_reset_lock(struct pending_free *pf,
  5488. struct lockdep_map *lock)
  5489. {
  5490. struct lock_class *class;
  5491. int j;
  5492. /*
  5493. * Remove all classes this lock might have:
  5494. */
  5495. for (j = 0; j < MAX_LOCKDEP_SUBCLASSES; j++) {
  5496. /*
  5497. * If the class exists we look it up and zap it:
  5498. */
  5499. class = look_up_lock_class(lock, j);
  5500. if (class)
  5501. zap_class(pf, class);
  5502. }
  5503. /*
  5504. * Debug check: in the end all mapped classes should
  5505. * be gone.
  5506. */
  5507. if (WARN_ON_ONCE(lock_class_cache_is_registered(lock)))
  5508. debug_locks_off();
  5509. }
  5510. /*
  5511. * Remove all information lockdep has about a lock if debug_locks == 1. Free
  5512. * released data structures from RCU context.
  5513. */
  5514. static void lockdep_reset_lock_reg(struct lockdep_map *lock)
  5515. {
  5516. struct pending_free *pf;
  5517. unsigned long flags;
  5518. int locked;
  5519. bool need_callback = false;
  5520. raw_local_irq_save(flags);
  5521. locked = graph_lock();
  5522. if (!locked)
  5523. goto out_irq;
  5524. pf = get_pending_free();
  5525. __lockdep_reset_lock(pf, lock);
  5526. need_callback = prepare_call_rcu_zapped(pf);
  5527. graph_unlock();
  5528. out_irq:
  5529. raw_local_irq_restore(flags);
  5530. if (need_callback)
  5531. call_rcu(&delayed_free.rcu_head, free_zapped_rcu);
  5532. }
  5533. /*
  5534. * Reset a lock. Does not sleep. Ignores debug_locks. Must only be used by the
  5535. * lockdep selftests.
  5536. */
  5537. static void lockdep_reset_lock_imm(struct lockdep_map *lock)
  5538. {
  5539. struct pending_free *pf = delayed_free.pf;
  5540. unsigned long flags;
  5541. raw_local_irq_save(flags);
  5542. lockdep_lock();
  5543. __lockdep_reset_lock(pf, lock);
  5544. __free_zapped_classes(pf);
  5545. lockdep_unlock();
  5546. raw_local_irq_restore(flags);
  5547. }
  5548. void lockdep_reset_lock(struct lockdep_map *lock)
  5549. {
  5550. init_data_structures_once();
  5551. if (inside_selftest())
  5552. lockdep_reset_lock_imm(lock);
  5553. else
  5554. lockdep_reset_lock_reg(lock);
  5555. }
  5556. /*
  5557. * Unregister a dynamically allocated key.
  5558. *
  5559. * Unlike lockdep_register_key(), a search is always done to find a matching
  5560. * key irrespective of debug_locks to avoid potential invalid access to freed
  5561. * memory in lock_class entry.
  5562. */
  5563. void lockdep_unregister_key(struct lock_class_key *key)
  5564. {
  5565. struct hlist_head *hash_head = keyhashentry(key);
  5566. struct lock_class_key *k;
  5567. struct pending_free *pf;
  5568. unsigned long flags;
  5569. bool found = false;
  5570. bool need_callback = false;
  5571. might_sleep();
  5572. if (WARN_ON_ONCE(static_obj(key)))
  5573. return;
  5574. raw_local_irq_save(flags);
  5575. lockdep_lock();
  5576. hlist_for_each_entry_rcu(k, hash_head, hash_entry) {
  5577. if (k == key) {
  5578. hlist_del_rcu(&k->hash_entry);
  5579. found = true;
  5580. break;
  5581. }
  5582. }
  5583. WARN_ON_ONCE(!found && debug_locks);
  5584. if (found) {
  5585. pf = get_pending_free();
  5586. __lockdep_free_key_range(pf, key, 1);
  5587. need_callback = prepare_call_rcu_zapped(pf);
  5588. }
  5589. lockdep_unlock();
  5590. raw_local_irq_restore(flags);
  5591. if (need_callback)
  5592. call_rcu(&delayed_free.rcu_head, free_zapped_rcu);
  5593. /* Wait until is_dynamic_key() has finished accessing k->hash_entry. */
  5594. synchronize_rcu();
  5595. }
  5596. EXPORT_SYMBOL_GPL(lockdep_unregister_key);
  5597. void __init lockdep_init(void)
  5598. {
  5599. printk("Lock dependency validator: Copyright (c) 2006 Red Hat, Inc., Ingo Molnar\n");
  5600. printk("... MAX_LOCKDEP_SUBCLASSES: %lu\n", MAX_LOCKDEP_SUBCLASSES);
  5601. printk("... MAX_LOCK_DEPTH: %lu\n", MAX_LOCK_DEPTH);
  5602. printk("... MAX_LOCKDEP_KEYS: %lu\n", MAX_LOCKDEP_KEYS);
  5603. printk("... CLASSHASH_SIZE: %lu\n", CLASSHASH_SIZE);
  5604. printk("... MAX_LOCKDEP_ENTRIES: %lu\n", MAX_LOCKDEP_ENTRIES);
  5605. printk("... MAX_LOCKDEP_CHAINS: %lu\n", MAX_LOCKDEP_CHAINS);
  5606. printk("... CHAINHASH_SIZE: %lu\n", CHAINHASH_SIZE);
  5607. printk(" memory used by lock dependency info: %zu kB\n",
  5608. (sizeof(lock_classes) +
  5609. sizeof(lock_classes_in_use) +
  5610. sizeof(classhash_table) +
  5611. sizeof(list_entries) +
  5612. sizeof(list_entries_in_use) +
  5613. sizeof(chainhash_table) +
  5614. sizeof(delayed_free)
  5615. #ifdef CONFIG_PROVE_LOCKING
  5616. + sizeof(lock_cq)
  5617. + sizeof(lock_chains)
  5618. + sizeof(lock_chains_in_use)
  5619. + sizeof(chain_hlocks)
  5620. #endif
  5621. ) / 1024
  5622. );
  5623. #if defined(CONFIG_TRACE_IRQFLAGS) && defined(CONFIG_PROVE_LOCKING)
  5624. printk(" memory used for stack traces: %zu kB\n",
  5625. (sizeof(stack_trace) + sizeof(stack_trace_hash)) / 1024
  5626. );
  5627. #endif
  5628. printk(" per task-struct memory footprint: %zu bytes\n",
  5629. sizeof(((struct task_struct *)NULL)->held_locks));
  5630. }
  5631. static void
  5632. print_freed_lock_bug(struct task_struct *curr, const void *mem_from,
  5633. const void *mem_to, struct held_lock *hlock)
  5634. {
  5635. if (!debug_locks_off())
  5636. return;
  5637. if (debug_locks_silent)
  5638. return;
  5639. nbcon_cpu_emergency_enter();
  5640. pr_warn("\n");
  5641. pr_warn("=========================\n");
  5642. pr_warn("WARNING: held lock freed!\n");
  5643. print_kernel_ident();
  5644. pr_warn("-------------------------\n");
  5645. pr_warn("%s/%d is freeing memory %px-%px, with a lock still held there!\n",
  5646. curr->comm, task_pid_nr(curr), mem_from, mem_to-1);
  5647. print_lock(hlock);
  5648. lockdep_print_held_locks(curr);
  5649. pr_warn("\nstack backtrace:\n");
  5650. dump_stack();
  5651. nbcon_cpu_emergency_exit();
  5652. }
  5653. static inline int not_in_range(const void* mem_from, unsigned long mem_len,
  5654. const void* lock_from, unsigned long lock_len)
  5655. {
  5656. return lock_from + lock_len <= mem_from ||
  5657. mem_from + mem_len <= lock_from;
  5658. }
  5659. /*
  5660. * Called when kernel memory is freed (or unmapped), or if a lock
  5661. * is destroyed or reinitialized - this code checks whether there is
  5662. * any held lock in the memory range of <from> to <to>:
  5663. */
  5664. void debug_check_no_locks_freed(const void *mem_from, unsigned long mem_len)
  5665. {
  5666. struct task_struct *curr = current;
  5667. struct held_lock *hlock;
  5668. unsigned long flags;
  5669. int i;
  5670. if (unlikely(!debug_locks))
  5671. return;
  5672. raw_local_irq_save(flags);
  5673. for (i = 0; i < curr->lockdep_depth; i++) {
  5674. hlock = curr->held_locks + i;
  5675. if (not_in_range(mem_from, mem_len, hlock->instance,
  5676. sizeof(*hlock->instance)))
  5677. continue;
  5678. print_freed_lock_bug(curr, mem_from, mem_from + mem_len, hlock);
  5679. break;
  5680. }
  5681. raw_local_irq_restore(flags);
  5682. }
  5683. EXPORT_SYMBOL_GPL(debug_check_no_locks_freed);
  5684. static void print_held_locks_bug(void)
  5685. {
  5686. if (!debug_locks_off())
  5687. return;
  5688. if (debug_locks_silent)
  5689. return;
  5690. nbcon_cpu_emergency_enter();
  5691. pr_warn("\n");
  5692. pr_warn("====================================\n");
  5693. pr_warn("WARNING: %s/%d still has locks held!\n",
  5694. current->comm, task_pid_nr(current));
  5695. print_kernel_ident();
  5696. pr_warn("------------------------------------\n");
  5697. lockdep_print_held_locks(current);
  5698. pr_warn("\nstack backtrace:\n");
  5699. dump_stack();
  5700. nbcon_cpu_emergency_exit();
  5701. }
  5702. void debug_check_no_locks_held(void)
  5703. {
  5704. if (unlikely(current->lockdep_depth > 0))
  5705. print_held_locks_bug();
  5706. }
  5707. EXPORT_SYMBOL_GPL(debug_check_no_locks_held);
  5708. #ifdef __KERNEL__
  5709. void debug_show_all_locks(void)
  5710. {
  5711. struct task_struct *g, *p;
  5712. if (unlikely(!debug_locks)) {
  5713. pr_warn("INFO: lockdep is turned off.\n");
  5714. return;
  5715. }
  5716. pr_warn("\nShowing all locks held in the system:\n");
  5717. rcu_read_lock();
  5718. for_each_process_thread(g, p) {
  5719. if (!p->lockdep_depth)
  5720. continue;
  5721. lockdep_print_held_locks(p);
  5722. touch_nmi_watchdog();
  5723. touch_all_softlockup_watchdogs();
  5724. }
  5725. rcu_read_unlock();
  5726. pr_warn("\n");
  5727. pr_warn("=============================================\n\n");
  5728. }
  5729. EXPORT_SYMBOL_GPL(debug_show_all_locks);
  5730. #endif
  5731. /*
  5732. * Careful: only use this function if you are sure that
  5733. * the task cannot run in parallel!
  5734. */
  5735. void debug_show_held_locks(struct task_struct *task)
  5736. {
  5737. if (unlikely(!debug_locks)) {
  5738. printk("INFO: lockdep is turned off.\n");
  5739. return;
  5740. }
  5741. lockdep_print_held_locks(task);
  5742. }
  5743. EXPORT_SYMBOL_GPL(debug_show_held_locks);
  5744. asmlinkage __visible void lockdep_sys_exit(void)
  5745. {
  5746. struct task_struct *curr = current;
  5747. if (unlikely(curr->lockdep_depth)) {
  5748. if (!debug_locks_off())
  5749. return;
  5750. nbcon_cpu_emergency_enter();
  5751. pr_warn("\n");
  5752. pr_warn("================================================\n");
  5753. pr_warn("WARNING: lock held when returning to user space!\n");
  5754. print_kernel_ident();
  5755. pr_warn("------------------------------------------------\n");
  5756. pr_warn("%s/%d is leaving the kernel with locks still held!\n",
  5757. curr->comm, curr->pid);
  5758. lockdep_print_held_locks(curr);
  5759. nbcon_cpu_emergency_exit();
  5760. }
  5761. /*
  5762. * The lock history for each syscall should be independent. So wipe the
  5763. * slate clean on return to userspace.
  5764. */
  5765. lockdep_invariant_state(false);
  5766. }
  5767. void lockdep_rcu_suspicious(const char *file, const int line, const char *s)
  5768. {
  5769. struct task_struct *curr = current;
  5770. int dl = READ_ONCE(debug_locks);
  5771. bool rcu = warn_rcu_enter();
  5772. /* Note: the following can be executed concurrently, so be careful. */
  5773. nbcon_cpu_emergency_enter();
  5774. pr_warn("\n");
  5775. pr_warn("=============================\n");
  5776. pr_warn("WARNING: suspicious RCU usage\n");
  5777. print_kernel_ident();
  5778. pr_warn("-----------------------------\n");
  5779. pr_warn("%s:%d %s!\n", file, line, s);
  5780. pr_warn("\nother info that might help us debug this:\n\n");
  5781. pr_warn("\n%srcu_scheduler_active = %d, debug_locks = %d\n%s",
  5782. !rcu_lockdep_current_cpu_online()
  5783. ? "RCU used illegally from offline CPU!\n"
  5784. : "",
  5785. rcu_scheduler_active, dl,
  5786. dl ? "" : "Possible false positive due to lockdep disabling via debug_locks = 0\n");
  5787. /*
  5788. * If a CPU is in the RCU-free window in idle (ie: in the section
  5789. * between ct_idle_enter() and ct_idle_exit(), then RCU
  5790. * considers that CPU to be in an "extended quiescent state",
  5791. * which means that RCU will be completely ignoring that CPU.
  5792. * Therefore, rcu_read_lock() and friends have absolutely no
  5793. * effect on a CPU running in that state. In other words, even if
  5794. * such an RCU-idle CPU has called rcu_read_lock(), RCU might well
  5795. * delete data structures out from under it. RCU really has no
  5796. * choice here: we need to keep an RCU-free window in idle where
  5797. * the CPU may possibly enter into low power mode. This way we can
  5798. * notice an extended quiescent state to other CPUs that started a grace
  5799. * period. Otherwise we would delay any grace period as long as we run
  5800. * in the idle task.
  5801. *
  5802. * So complain bitterly if someone does call rcu_read_lock(),
  5803. * rcu_read_lock_bh() and so on from extended quiescent states.
  5804. */
  5805. if (!rcu_is_watching())
  5806. pr_warn("RCU used illegally from extended quiescent state!\n");
  5807. lockdep_print_held_locks(curr);
  5808. pr_warn("\nstack backtrace:\n");
  5809. dump_stack();
  5810. nbcon_cpu_emergency_exit();
  5811. warn_rcu_exit(rcu);
  5812. }
  5813. EXPORT_SYMBOL_GPL(lockdep_rcu_suspicious);