workqueue.c 160 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847
  1. /*
  2. * kernel/workqueue.c - generic async execution with shared worker pool
  3. *
  4. * Copyright (C) 2002 Ingo Molnar
  5. *
  6. * Derived from the taskqueue/keventd code by:
  7. * David Woodhouse <dwmw2@infradead.org>
  8. * Andrew Morton
  9. * Kai Petzke <wpp@marie.physik.tu-berlin.de>
  10. * Theodore Ts'o <tytso@mit.edu>
  11. *
  12. * Made to use alloc_percpu by Christoph Lameter.
  13. *
  14. * Copyright (C) 2010 SUSE Linux Products GmbH
  15. * Copyright (C) 2010 Tejun Heo <tj@kernel.org>
  16. *
  17. * This is the generic async execution mechanism. Work items as are
  18. * executed in process context. The worker pool is shared and
  19. * automatically managed. There are two worker pools for each CPU (one for
  20. * normal work items and the other for high priority ones) and some extra
  21. * pools for workqueues which are not bound to any specific CPU - the
  22. * number of these backing pools is dynamic.
  23. *
  24. * Please read Documentation/core-api/workqueue.rst for details.
  25. */
  26. #include <linux/export.h>
  27. #include <linux/kernel.h>
  28. #include <linux/sched.h>
  29. #include <linux/init.h>
  30. #include <linux/signal.h>
  31. #include <linux/completion.h>
  32. #include <linux/workqueue.h>
  33. #include <linux/slab.h>
  34. #include <linux/cpu.h>
  35. #include <linux/notifier.h>
  36. #include <linux/kthread.h>
  37. #include <linux/hardirq.h>
  38. #include <linux/mempolicy.h>
  39. #include <linux/freezer.h>
  40. #include <linux/debug_locks.h>
  41. #include <linux/lockdep.h>
  42. #include <linux/idr.h>
  43. #include <linux/jhash.h>
  44. #include <linux/hashtable.h>
  45. #include <linux/rculist.h>
  46. #include <linux/nodemask.h>
  47. #include <linux/moduleparam.h>
  48. #include <linux/uaccess.h>
  49. #include <linux/sched/isolation.h>
  50. #include <linux/nmi.h>
  51. #include "workqueue_internal.h"
  52. enum {
  53. /*
  54. * worker_pool flags
  55. *
  56. * A bound pool is either associated or disassociated with its CPU.
  57. * While associated (!DISASSOCIATED), all workers are bound to the
  58. * CPU and none has %WORKER_UNBOUND set and concurrency management
  59. * is in effect.
  60. *
  61. * While DISASSOCIATED, the cpu may be offline and all workers have
  62. * %WORKER_UNBOUND set and concurrency management disabled, and may
  63. * be executing on any CPU. The pool behaves as an unbound one.
  64. *
  65. * Note that DISASSOCIATED should be flipped only while holding
  66. * wq_pool_attach_mutex to avoid changing binding state while
  67. * worker_attach_to_pool() is in progress.
  68. */
  69. POOL_MANAGER_ACTIVE = 1 << 0, /* being managed */
  70. POOL_DISASSOCIATED = 1 << 2, /* cpu can't serve workers */
  71. /* worker flags */
  72. WORKER_DIE = 1 << 1, /* die die die */
  73. WORKER_IDLE = 1 << 2, /* is idle */
  74. WORKER_PREP = 1 << 3, /* preparing to run works */
  75. WORKER_CPU_INTENSIVE = 1 << 6, /* cpu intensive */
  76. WORKER_UNBOUND = 1 << 7, /* worker is unbound */
  77. WORKER_REBOUND = 1 << 8, /* worker was rebound */
  78. WORKER_NOT_RUNNING = WORKER_PREP | WORKER_CPU_INTENSIVE |
  79. WORKER_UNBOUND | WORKER_REBOUND,
  80. NR_STD_WORKER_POOLS = 2, /* # standard pools per cpu */
  81. UNBOUND_POOL_HASH_ORDER = 6, /* hashed by pool->attrs */
  82. BUSY_WORKER_HASH_ORDER = 6, /* 64 pointers */
  83. MAX_IDLE_WORKERS_RATIO = 4, /* 1/4 of busy can be idle */
  84. IDLE_WORKER_TIMEOUT = 300 * HZ, /* keep idle ones for 5 mins */
  85. MAYDAY_INITIAL_TIMEOUT = HZ / 100 >= 2 ? HZ / 100 : 2,
  86. /* call for help after 10ms
  87. (min two ticks) */
  88. MAYDAY_INTERVAL = HZ / 10, /* and then every 100ms */
  89. CREATE_COOLDOWN = HZ, /* time to breath after fail */
  90. /*
  91. * Rescue workers are used only on emergencies and shared by
  92. * all cpus. Give MIN_NICE.
  93. */
  94. RESCUER_NICE_LEVEL = MIN_NICE,
  95. HIGHPRI_NICE_LEVEL = MIN_NICE,
  96. WQ_NAME_LEN = 24,
  97. };
  98. /*
  99. * Structure fields follow one of the following exclusion rules.
  100. *
  101. * I: Modifiable by initialization/destruction paths and read-only for
  102. * everyone else.
  103. *
  104. * P: Preemption protected. Disabling preemption is enough and should
  105. * only be modified and accessed from the local cpu.
  106. *
  107. * L: pool->lock protected. Access with pool->lock held.
  108. *
  109. * X: During normal operation, modification requires pool->lock and should
  110. * be done only from local cpu. Either disabling preemption on local
  111. * cpu or grabbing pool->lock is enough for read access. If
  112. * POOL_DISASSOCIATED is set, it's identical to L.
  113. *
  114. * A: wq_pool_attach_mutex protected.
  115. *
  116. * PL: wq_pool_mutex protected.
  117. *
  118. * PR: wq_pool_mutex protected for writes. Sched-RCU protected for reads.
  119. *
  120. * PW: wq_pool_mutex and wq->mutex protected for writes. Either for reads.
  121. *
  122. * PWR: wq_pool_mutex and wq->mutex protected for writes. Either or
  123. * sched-RCU for reads.
  124. *
  125. * WQ: wq->mutex protected.
  126. *
  127. * WR: wq->mutex protected for writes. Sched-RCU protected for reads.
  128. *
  129. * MD: wq_mayday_lock protected.
  130. */
  131. /* struct worker is defined in workqueue_internal.h */
  132. struct worker_pool {
  133. spinlock_t lock; /* the pool lock */
  134. int cpu; /* I: the associated cpu */
  135. int node; /* I: the associated node ID */
  136. int id; /* I: pool ID */
  137. unsigned int flags; /* X: flags */
  138. unsigned long watchdog_ts; /* L: watchdog timestamp */
  139. struct list_head worklist; /* L: list of pending works */
  140. int nr_workers; /* L: total number of workers */
  141. int nr_idle; /* L: currently idle workers */
  142. struct list_head idle_list; /* X: list of idle workers */
  143. struct timer_list idle_timer; /* L: worker idle timeout */
  144. struct timer_list mayday_timer; /* L: SOS timer for workers */
  145. /* a workers is either on busy_hash or idle_list, or the manager */
  146. DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
  147. /* L: hash of busy workers */
  148. struct worker *manager; /* L: purely informational */
  149. struct list_head workers; /* A: attached workers */
  150. struct completion *detach_completion; /* all workers detached */
  151. struct ida worker_ida; /* worker IDs for task name */
  152. struct workqueue_attrs *attrs; /* I: worker attributes */
  153. struct hlist_node hash_node; /* PL: unbound_pool_hash node */
  154. int refcnt; /* PL: refcnt for unbound pools */
  155. /*
  156. * The current concurrency level. As it's likely to be accessed
  157. * from other CPUs during try_to_wake_up(), put it in a separate
  158. * cacheline.
  159. */
  160. atomic_t nr_running ____cacheline_aligned_in_smp;
  161. /*
  162. * Destruction of pool is sched-RCU protected to allow dereferences
  163. * from get_work_pool().
  164. */
  165. struct rcu_head rcu;
  166. } ____cacheline_aligned_in_smp;
  167. /*
  168. * The per-pool workqueue. While queued, the lower WORK_STRUCT_FLAG_BITS
  169. * of work_struct->data are used for flags and the remaining high bits
  170. * point to the pwq; thus, pwqs need to be aligned at two's power of the
  171. * number of flag bits.
  172. */
  173. struct pool_workqueue {
  174. struct worker_pool *pool; /* I: the associated pool */
  175. struct workqueue_struct *wq; /* I: the owning workqueue */
  176. int work_color; /* L: current color */
  177. int flush_color; /* L: flushing color */
  178. int refcnt; /* L: reference count */
  179. int nr_in_flight[WORK_NR_COLORS];
  180. /* L: nr of in_flight works */
  181. int nr_active; /* L: nr of active works */
  182. int max_active; /* L: max active works */
  183. struct list_head delayed_works; /* L: delayed works */
  184. struct list_head pwqs_node; /* WR: node on wq->pwqs */
  185. struct list_head mayday_node; /* MD: node on wq->maydays */
  186. /*
  187. * Release of unbound pwq is punted to system_wq. See put_pwq()
  188. * and pwq_unbound_release_workfn() for details. pool_workqueue
  189. * itself is also sched-RCU protected so that the first pwq can be
  190. * determined without grabbing wq->mutex.
  191. */
  192. struct work_struct unbound_release_work;
  193. struct rcu_head rcu;
  194. } __aligned(1 << WORK_STRUCT_FLAG_BITS);
  195. /*
  196. * Structure used to wait for workqueue flush.
  197. */
  198. struct wq_flusher {
  199. struct list_head list; /* WQ: list of flushers */
  200. int flush_color; /* WQ: flush color waiting for */
  201. struct completion done; /* flush completion */
  202. };
  203. struct wq_device;
  204. /*
  205. * The externally visible workqueue. It relays the issued work items to
  206. * the appropriate worker_pool through its pool_workqueues.
  207. */
  208. struct workqueue_struct {
  209. struct list_head pwqs; /* WR: all pwqs of this wq */
  210. struct list_head list; /* PR: list of all workqueues */
  211. struct mutex mutex; /* protects this wq */
  212. int work_color; /* WQ: current work color */
  213. int flush_color; /* WQ: current flush color */
  214. atomic_t nr_pwqs_to_flush; /* flush in progress */
  215. struct wq_flusher *first_flusher; /* WQ: first flusher */
  216. struct list_head flusher_queue; /* WQ: flush waiters */
  217. struct list_head flusher_overflow; /* WQ: flush overflow list */
  218. struct list_head maydays; /* MD: pwqs requesting rescue */
  219. struct worker *rescuer; /* I: rescue worker */
  220. int nr_drainers; /* WQ: drain in progress */
  221. int saved_max_active; /* WQ: saved pwq max_active */
  222. struct workqueue_attrs *unbound_attrs; /* PW: only for unbound wqs */
  223. struct pool_workqueue *dfl_pwq; /* PW: only for unbound wqs */
  224. #ifdef CONFIG_SYSFS
  225. struct wq_device *wq_dev; /* I: for sysfs interface */
  226. #endif
  227. #ifdef CONFIG_LOCKDEP
  228. struct lockdep_map lockdep_map;
  229. #endif
  230. char name[WQ_NAME_LEN]; /* I: workqueue name */
  231. /*
  232. * Destruction of workqueue_struct is sched-RCU protected to allow
  233. * walking the workqueues list without grabbing wq_pool_mutex.
  234. * This is used to dump all workqueues from sysrq.
  235. */
  236. struct rcu_head rcu;
  237. /* hot fields used during command issue, aligned to cacheline */
  238. unsigned int flags ____cacheline_aligned; /* WQ: WQ_* flags */
  239. struct pool_workqueue __percpu *cpu_pwqs; /* I: per-cpu pwqs */
  240. struct pool_workqueue __rcu *numa_pwq_tbl[]; /* PWR: unbound pwqs indexed by node */
  241. };
  242. static struct kmem_cache *pwq_cache;
  243. static cpumask_var_t *wq_numa_possible_cpumask;
  244. /* possible CPUs of each node */
  245. static bool wq_disable_numa;
  246. module_param_named(disable_numa, wq_disable_numa, bool, 0444);
  247. /* see the comment above the definition of WQ_POWER_EFFICIENT */
  248. static bool wq_power_efficient = IS_ENABLED(CONFIG_WQ_POWER_EFFICIENT_DEFAULT);
  249. module_param_named(power_efficient, wq_power_efficient, bool, 0444);
  250. static bool wq_online; /* can kworkers be created yet? */
  251. static bool wq_numa_enabled; /* unbound NUMA affinity enabled */
  252. /* buf for wq_update_unbound_numa_attrs(), protected by CPU hotplug exclusion */
  253. static struct workqueue_attrs *wq_update_unbound_numa_attrs_buf;
  254. static DEFINE_MUTEX(wq_pool_mutex); /* protects pools and workqueues list */
  255. static DEFINE_MUTEX(wq_pool_attach_mutex); /* protects worker attach/detach */
  256. static DEFINE_SPINLOCK(wq_mayday_lock); /* protects wq->maydays list */
  257. static DECLARE_WAIT_QUEUE_HEAD(wq_manager_wait); /* wait for manager to go away */
  258. static LIST_HEAD(workqueues); /* PR: list of all workqueues */
  259. static bool workqueue_freezing; /* PL: have wqs started freezing? */
  260. /* PL: allowable cpus for unbound wqs and work items */
  261. static cpumask_var_t wq_unbound_cpumask;
  262. /* CPU where unbound work was last round robin scheduled from this CPU */
  263. static DEFINE_PER_CPU(int, wq_rr_cpu_last);
  264. /*
  265. * Local execution of unbound work items is no longer guaranteed. The
  266. * following always forces round-robin CPU selection on unbound work items
  267. * to uncover usages which depend on it.
  268. */
  269. #ifdef CONFIG_DEBUG_WQ_FORCE_RR_CPU
  270. static bool wq_debug_force_rr_cpu = true;
  271. #else
  272. static bool wq_debug_force_rr_cpu = false;
  273. #endif
  274. module_param_named(debug_force_rr_cpu, wq_debug_force_rr_cpu, bool, 0644);
  275. /* the per-cpu worker pools */
  276. static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS], cpu_worker_pools);
  277. static DEFINE_IDR(worker_pool_idr); /* PR: idr of all pools */
  278. /* PL: hash of all unbound pools keyed by pool->attrs */
  279. static DEFINE_HASHTABLE(unbound_pool_hash, UNBOUND_POOL_HASH_ORDER);
  280. /* I: attributes used when instantiating standard unbound pools on demand */
  281. static struct workqueue_attrs *unbound_std_wq_attrs[NR_STD_WORKER_POOLS];
  282. /* I: attributes used when instantiating ordered pools on demand */
  283. static struct workqueue_attrs *ordered_wq_attrs[NR_STD_WORKER_POOLS];
  284. struct workqueue_struct *system_wq __read_mostly;
  285. EXPORT_SYMBOL(system_wq);
  286. struct workqueue_struct *system_highpri_wq __read_mostly;
  287. EXPORT_SYMBOL_GPL(system_highpri_wq);
  288. struct workqueue_struct *system_long_wq __read_mostly;
  289. EXPORT_SYMBOL_GPL(system_long_wq);
  290. struct workqueue_struct *system_unbound_wq __read_mostly;
  291. EXPORT_SYMBOL_GPL(system_unbound_wq);
  292. struct workqueue_struct *system_freezable_wq __read_mostly;
  293. EXPORT_SYMBOL_GPL(system_freezable_wq);
  294. struct workqueue_struct *system_power_efficient_wq __read_mostly;
  295. EXPORT_SYMBOL_GPL(system_power_efficient_wq);
  296. struct workqueue_struct *system_freezable_power_efficient_wq __read_mostly;
  297. EXPORT_SYMBOL_GPL(system_freezable_power_efficient_wq);
  298. static int worker_thread(void *__worker);
  299. static void workqueue_sysfs_unregister(struct workqueue_struct *wq);
  300. #define CREATE_TRACE_POINTS
  301. #include <trace/events/workqueue.h>
  302. #define assert_rcu_or_pool_mutex() \
  303. RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held() && \
  304. !lockdep_is_held(&wq_pool_mutex), \
  305. "sched RCU or wq_pool_mutex should be held")
  306. #define assert_rcu_or_wq_mutex(wq) \
  307. RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held() && \
  308. !lockdep_is_held(&wq->mutex), \
  309. "sched RCU or wq->mutex should be held")
  310. #define assert_rcu_or_wq_mutex_or_pool_mutex(wq) \
  311. RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held() && \
  312. !lockdep_is_held(&wq->mutex) && \
  313. !lockdep_is_held(&wq_pool_mutex), \
  314. "sched RCU, wq->mutex or wq_pool_mutex should be held")
  315. #define for_each_cpu_worker_pool(pool, cpu) \
  316. for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0]; \
  317. (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
  318. (pool)++)
  319. /**
  320. * for_each_pool - iterate through all worker_pools in the system
  321. * @pool: iteration cursor
  322. * @pi: integer used for iteration
  323. *
  324. * This must be called either with wq_pool_mutex held or sched RCU read
  325. * locked. If the pool needs to be used beyond the locking in effect, the
  326. * caller is responsible for guaranteeing that the pool stays online.
  327. *
  328. * The if/else clause exists only for the lockdep assertion and can be
  329. * ignored.
  330. */
  331. #define for_each_pool(pool, pi) \
  332. idr_for_each_entry(&worker_pool_idr, pool, pi) \
  333. if (({ assert_rcu_or_pool_mutex(); false; })) { } \
  334. else
  335. /**
  336. * for_each_pool_worker - iterate through all workers of a worker_pool
  337. * @worker: iteration cursor
  338. * @pool: worker_pool to iterate workers of
  339. *
  340. * This must be called with wq_pool_attach_mutex.
  341. *
  342. * The if/else clause exists only for the lockdep assertion and can be
  343. * ignored.
  344. */
  345. #define for_each_pool_worker(worker, pool) \
  346. list_for_each_entry((worker), &(pool)->workers, node) \
  347. if (({ lockdep_assert_held(&wq_pool_attach_mutex); false; })) { } \
  348. else
  349. /**
  350. * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
  351. * @pwq: iteration cursor
  352. * @wq: the target workqueue
  353. *
  354. * This must be called either with wq->mutex held or sched RCU read locked.
  355. * If the pwq needs to be used beyond the locking in effect, the caller is
  356. * responsible for guaranteeing that the pwq stays online.
  357. *
  358. * The if/else clause exists only for the lockdep assertion and can be
  359. * ignored.
  360. */
  361. #define for_each_pwq(pwq, wq) \
  362. list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node) \
  363. if (({ assert_rcu_or_wq_mutex(wq); false; })) { } \
  364. else
  365. #ifdef CONFIG_DEBUG_OBJECTS_WORK
  366. static struct debug_obj_descr work_debug_descr;
  367. static void *work_debug_hint(void *addr)
  368. {
  369. return ((struct work_struct *) addr)->func;
  370. }
  371. static bool work_is_static_object(void *addr)
  372. {
  373. struct work_struct *work = addr;
  374. return test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work));
  375. }
  376. /*
  377. * fixup_init is called when:
  378. * - an active object is initialized
  379. */
  380. static bool work_fixup_init(void *addr, enum debug_obj_state state)
  381. {
  382. struct work_struct *work = addr;
  383. switch (state) {
  384. case ODEBUG_STATE_ACTIVE:
  385. cancel_work_sync(work);
  386. debug_object_init(work, &work_debug_descr);
  387. return true;
  388. default:
  389. return false;
  390. }
  391. }
  392. /*
  393. * fixup_free is called when:
  394. * - an active object is freed
  395. */
  396. static bool work_fixup_free(void *addr, enum debug_obj_state state)
  397. {
  398. struct work_struct *work = addr;
  399. switch (state) {
  400. case ODEBUG_STATE_ACTIVE:
  401. cancel_work_sync(work);
  402. debug_object_free(work, &work_debug_descr);
  403. return true;
  404. default:
  405. return false;
  406. }
  407. }
  408. static struct debug_obj_descr work_debug_descr = {
  409. .name = "work_struct",
  410. .debug_hint = work_debug_hint,
  411. .is_static_object = work_is_static_object,
  412. .fixup_init = work_fixup_init,
  413. .fixup_free = work_fixup_free,
  414. };
  415. static inline void debug_work_activate(struct work_struct *work)
  416. {
  417. debug_object_activate(work, &work_debug_descr);
  418. }
  419. static inline void debug_work_deactivate(struct work_struct *work)
  420. {
  421. debug_object_deactivate(work, &work_debug_descr);
  422. }
  423. void __init_work(struct work_struct *work, int onstack)
  424. {
  425. if (onstack)
  426. debug_object_init_on_stack(work, &work_debug_descr);
  427. else
  428. debug_object_init(work, &work_debug_descr);
  429. }
  430. EXPORT_SYMBOL_GPL(__init_work);
  431. void destroy_work_on_stack(struct work_struct *work)
  432. {
  433. debug_object_free(work, &work_debug_descr);
  434. }
  435. EXPORT_SYMBOL_GPL(destroy_work_on_stack);
  436. void destroy_delayed_work_on_stack(struct delayed_work *work)
  437. {
  438. destroy_timer_on_stack(&work->timer);
  439. debug_object_free(&work->work, &work_debug_descr);
  440. }
  441. EXPORT_SYMBOL_GPL(destroy_delayed_work_on_stack);
  442. #else
  443. static inline void debug_work_activate(struct work_struct *work) { }
  444. static inline void debug_work_deactivate(struct work_struct *work) { }
  445. #endif
  446. /**
  447. * worker_pool_assign_id - allocate ID and assing it to @pool
  448. * @pool: the pool pointer of interest
  449. *
  450. * Returns 0 if ID in [0, WORK_OFFQ_POOL_NONE) is allocated and assigned
  451. * successfully, -errno on failure.
  452. */
  453. static int worker_pool_assign_id(struct worker_pool *pool)
  454. {
  455. int ret;
  456. lockdep_assert_held(&wq_pool_mutex);
  457. ret = idr_alloc(&worker_pool_idr, pool, 0, WORK_OFFQ_POOL_NONE,
  458. GFP_KERNEL);
  459. if (ret >= 0) {
  460. pool->id = ret;
  461. return 0;
  462. }
  463. return ret;
  464. }
  465. /**
  466. * unbound_pwq_by_node - return the unbound pool_workqueue for the given node
  467. * @wq: the target workqueue
  468. * @node: the node ID
  469. *
  470. * This must be called with any of wq_pool_mutex, wq->mutex or sched RCU
  471. * read locked.
  472. * If the pwq needs to be used beyond the locking in effect, the caller is
  473. * responsible for guaranteeing that the pwq stays online.
  474. *
  475. * Return: The unbound pool_workqueue for @node.
  476. */
  477. static struct pool_workqueue *unbound_pwq_by_node(struct workqueue_struct *wq,
  478. int node)
  479. {
  480. assert_rcu_or_wq_mutex_or_pool_mutex(wq);
  481. /*
  482. * XXX: @node can be NUMA_NO_NODE if CPU goes offline while a
  483. * delayed item is pending. The plan is to keep CPU -> NODE
  484. * mapping valid and stable across CPU on/offlines. Once that
  485. * happens, this workaround can be removed.
  486. */
  487. if (unlikely(node == NUMA_NO_NODE))
  488. return wq->dfl_pwq;
  489. return rcu_dereference_raw(wq->numa_pwq_tbl[node]);
  490. }
  491. static unsigned int work_color_to_flags(int color)
  492. {
  493. return color << WORK_STRUCT_COLOR_SHIFT;
  494. }
  495. static int get_work_color(struct work_struct *work)
  496. {
  497. return (*work_data_bits(work) >> WORK_STRUCT_COLOR_SHIFT) &
  498. ((1 << WORK_STRUCT_COLOR_BITS) - 1);
  499. }
  500. static int work_next_color(int color)
  501. {
  502. return (color + 1) % WORK_NR_COLORS;
  503. }
  504. /*
  505. * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
  506. * contain the pointer to the queued pwq. Once execution starts, the flag
  507. * is cleared and the high bits contain OFFQ flags and pool ID.
  508. *
  509. * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
  510. * and clear_work_data() can be used to set the pwq, pool or clear
  511. * work->data. These functions should only be called while the work is
  512. * owned - ie. while the PENDING bit is set.
  513. *
  514. * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
  515. * corresponding to a work. Pool is available once the work has been
  516. * queued anywhere after initialization until it is sync canceled. pwq is
  517. * available only while the work item is queued.
  518. *
  519. * %WORK_OFFQ_CANCELING is used to mark a work item which is being
  520. * canceled. While being canceled, a work item may have its PENDING set
  521. * but stay off timer and worklist for arbitrarily long and nobody should
  522. * try to steal the PENDING bit.
  523. */
  524. static inline void set_work_data(struct work_struct *work, unsigned long data,
  525. unsigned long flags)
  526. {
  527. WARN_ON_ONCE(!work_pending(work));
  528. atomic_long_set(&work->data, data | flags | work_static(work));
  529. }
  530. static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
  531. unsigned long extra_flags)
  532. {
  533. set_work_data(work, (unsigned long)pwq,
  534. WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | extra_flags);
  535. }
  536. static void set_work_pool_and_keep_pending(struct work_struct *work,
  537. int pool_id)
  538. {
  539. set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT,
  540. WORK_STRUCT_PENDING);
  541. }
  542. static void set_work_pool_and_clear_pending(struct work_struct *work,
  543. int pool_id)
  544. {
  545. /*
  546. * The following wmb is paired with the implied mb in
  547. * test_and_set_bit(PENDING) and ensures all updates to @work made
  548. * here are visible to and precede any updates by the next PENDING
  549. * owner.
  550. */
  551. smp_wmb();
  552. set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0);
  553. /*
  554. * The following mb guarantees that previous clear of a PENDING bit
  555. * will not be reordered with any speculative LOADS or STORES from
  556. * work->current_func, which is executed afterwards. This possible
  557. * reordering can lead to a missed execution on attempt to qeueue
  558. * the same @work. E.g. consider this case:
  559. *
  560. * CPU#0 CPU#1
  561. * ---------------------------- --------------------------------
  562. *
  563. * 1 STORE event_indicated
  564. * 2 queue_work_on() {
  565. * 3 test_and_set_bit(PENDING)
  566. * 4 } set_..._and_clear_pending() {
  567. * 5 set_work_data() # clear bit
  568. * 6 smp_mb()
  569. * 7 work->current_func() {
  570. * 8 LOAD event_indicated
  571. * }
  572. *
  573. * Without an explicit full barrier speculative LOAD on line 8 can
  574. * be executed before CPU#0 does STORE on line 1. If that happens,
  575. * CPU#0 observes the PENDING bit is still set and new execution of
  576. * a @work is not queued in a hope, that CPU#1 will eventually
  577. * finish the queued @work. Meanwhile CPU#1 does not see
  578. * event_indicated is set, because speculative LOAD was executed
  579. * before actual STORE.
  580. */
  581. smp_mb();
  582. }
  583. static void clear_work_data(struct work_struct *work)
  584. {
  585. smp_wmb(); /* see set_work_pool_and_clear_pending() */
  586. set_work_data(work, WORK_STRUCT_NO_POOL, 0);
  587. }
  588. static struct pool_workqueue *get_work_pwq(struct work_struct *work)
  589. {
  590. unsigned long data = atomic_long_read(&work->data);
  591. if (data & WORK_STRUCT_PWQ)
  592. return (void *)(data & WORK_STRUCT_WQ_DATA_MASK);
  593. else
  594. return NULL;
  595. }
  596. /**
  597. * get_work_pool - return the worker_pool a given work was associated with
  598. * @work: the work item of interest
  599. *
  600. * Pools are created and destroyed under wq_pool_mutex, and allows read
  601. * access under sched-RCU read lock. As such, this function should be
  602. * called under wq_pool_mutex or with preemption disabled.
  603. *
  604. * All fields of the returned pool are accessible as long as the above
  605. * mentioned locking is in effect. If the returned pool needs to be used
  606. * beyond the critical section, the caller is responsible for ensuring the
  607. * returned pool is and stays online.
  608. *
  609. * Return: The worker_pool @work was last associated with. %NULL if none.
  610. */
  611. static struct worker_pool *get_work_pool(struct work_struct *work)
  612. {
  613. unsigned long data = atomic_long_read(&work->data);
  614. int pool_id;
  615. assert_rcu_or_pool_mutex();
  616. if (data & WORK_STRUCT_PWQ)
  617. return ((struct pool_workqueue *)
  618. (data & WORK_STRUCT_WQ_DATA_MASK))->pool;
  619. pool_id = data >> WORK_OFFQ_POOL_SHIFT;
  620. if (pool_id == WORK_OFFQ_POOL_NONE)
  621. return NULL;
  622. return idr_find(&worker_pool_idr, pool_id);
  623. }
  624. /**
  625. * get_work_pool_id - return the worker pool ID a given work is associated with
  626. * @work: the work item of interest
  627. *
  628. * Return: The worker_pool ID @work was last associated with.
  629. * %WORK_OFFQ_POOL_NONE if none.
  630. */
  631. static int get_work_pool_id(struct work_struct *work)
  632. {
  633. unsigned long data = atomic_long_read(&work->data);
  634. if (data & WORK_STRUCT_PWQ)
  635. return ((struct pool_workqueue *)
  636. (data & WORK_STRUCT_WQ_DATA_MASK))->pool->id;
  637. return data >> WORK_OFFQ_POOL_SHIFT;
  638. }
  639. static void mark_work_canceling(struct work_struct *work)
  640. {
  641. unsigned long pool_id = get_work_pool_id(work);
  642. pool_id <<= WORK_OFFQ_POOL_SHIFT;
  643. set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
  644. }
  645. static bool work_is_canceling(struct work_struct *work)
  646. {
  647. unsigned long data = atomic_long_read(&work->data);
  648. return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
  649. }
  650. /*
  651. * Policy functions. These define the policies on how the global worker
  652. * pools are managed. Unless noted otherwise, these functions assume that
  653. * they're being called with pool->lock held.
  654. */
  655. static bool __need_more_worker(struct worker_pool *pool)
  656. {
  657. return !atomic_read(&pool->nr_running);
  658. }
  659. /*
  660. * Need to wake up a worker? Called from anything but currently
  661. * running workers.
  662. *
  663. * Note that, because unbound workers never contribute to nr_running, this
  664. * function will always return %true for unbound pools as long as the
  665. * worklist isn't empty.
  666. */
  667. static bool need_more_worker(struct worker_pool *pool)
  668. {
  669. return !list_empty(&pool->worklist) && __need_more_worker(pool);
  670. }
  671. /* Can I start working? Called from busy but !running workers. */
  672. static bool may_start_working(struct worker_pool *pool)
  673. {
  674. return pool->nr_idle;
  675. }
  676. /* Do I need to keep working? Called from currently running workers. */
  677. static bool keep_working(struct worker_pool *pool)
  678. {
  679. return !list_empty(&pool->worklist) &&
  680. atomic_read(&pool->nr_running) <= 1;
  681. }
  682. /* Do we need a new worker? Called from manager. */
  683. static bool need_to_create_worker(struct worker_pool *pool)
  684. {
  685. return need_more_worker(pool) && !may_start_working(pool);
  686. }
  687. /* Do we have too many workers and should some go away? */
  688. static bool too_many_workers(struct worker_pool *pool)
  689. {
  690. bool managing = pool->flags & POOL_MANAGER_ACTIVE;
  691. int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
  692. int nr_busy = pool->nr_workers - nr_idle;
  693. return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
  694. }
  695. /*
  696. * Wake up functions.
  697. */
  698. /* Return the first idle worker. Safe with preemption disabled */
  699. static struct worker *first_idle_worker(struct worker_pool *pool)
  700. {
  701. if (unlikely(list_empty(&pool->idle_list)))
  702. return NULL;
  703. return list_first_entry(&pool->idle_list, struct worker, entry);
  704. }
  705. /**
  706. * wake_up_worker - wake up an idle worker
  707. * @pool: worker pool to wake worker from
  708. *
  709. * Wake up the first idle worker of @pool.
  710. *
  711. * CONTEXT:
  712. * spin_lock_irq(pool->lock).
  713. */
  714. static void wake_up_worker(struct worker_pool *pool)
  715. {
  716. struct worker *worker = first_idle_worker(pool);
  717. if (likely(worker))
  718. wake_up_process(worker->task);
  719. }
  720. /**
  721. * wq_worker_waking_up - a worker is waking up
  722. * @task: task waking up
  723. * @cpu: CPU @task is waking up to
  724. *
  725. * This function is called during try_to_wake_up() when a worker is
  726. * being awoken.
  727. *
  728. * CONTEXT:
  729. * spin_lock_irq(rq->lock)
  730. */
  731. void wq_worker_waking_up(struct task_struct *task, int cpu)
  732. {
  733. struct worker *worker = kthread_data(task);
  734. if (!(worker->flags & WORKER_NOT_RUNNING)) {
  735. WARN_ON_ONCE(worker->pool->cpu != cpu);
  736. atomic_inc(&worker->pool->nr_running);
  737. }
  738. }
  739. /**
  740. * wq_worker_sleeping - a worker is going to sleep
  741. * @task: task going to sleep
  742. *
  743. * This function is called during schedule() when a busy worker is
  744. * going to sleep. Worker on the same cpu can be woken up by
  745. * returning pointer to its task.
  746. *
  747. * CONTEXT:
  748. * spin_lock_irq(rq->lock)
  749. *
  750. * Return:
  751. * Worker task on @cpu to wake up, %NULL if none.
  752. */
  753. struct task_struct *wq_worker_sleeping(struct task_struct *task)
  754. {
  755. struct worker *worker = kthread_data(task), *to_wakeup = NULL;
  756. struct worker_pool *pool;
  757. /*
  758. * Rescuers, which may not have all the fields set up like normal
  759. * workers, also reach here, let's not access anything before
  760. * checking NOT_RUNNING.
  761. */
  762. if (worker->flags & WORKER_NOT_RUNNING)
  763. return NULL;
  764. pool = worker->pool;
  765. /* this can only happen on the local cpu */
  766. if (WARN_ON_ONCE(pool->cpu != raw_smp_processor_id()))
  767. return NULL;
  768. /*
  769. * The counterpart of the following dec_and_test, implied mb,
  770. * worklist not empty test sequence is in insert_work().
  771. * Please read comment there.
  772. *
  773. * NOT_RUNNING is clear. This means that we're bound to and
  774. * running on the local cpu w/ rq lock held and preemption
  775. * disabled, which in turn means that none else could be
  776. * manipulating idle_list, so dereferencing idle_list without pool
  777. * lock is safe.
  778. */
  779. if (atomic_dec_and_test(&pool->nr_running) &&
  780. !list_empty(&pool->worklist))
  781. to_wakeup = first_idle_worker(pool);
  782. return to_wakeup ? to_wakeup->task : NULL;
  783. }
  784. /**
  785. * worker_set_flags - set worker flags and adjust nr_running accordingly
  786. * @worker: self
  787. * @flags: flags to set
  788. *
  789. * Set @flags in @worker->flags and adjust nr_running accordingly.
  790. *
  791. * CONTEXT:
  792. * spin_lock_irq(pool->lock)
  793. */
  794. static inline void worker_set_flags(struct worker *worker, unsigned int flags)
  795. {
  796. struct worker_pool *pool = worker->pool;
  797. WARN_ON_ONCE(worker->task != current);
  798. /* If transitioning into NOT_RUNNING, adjust nr_running. */
  799. if ((flags & WORKER_NOT_RUNNING) &&
  800. !(worker->flags & WORKER_NOT_RUNNING)) {
  801. atomic_dec(&pool->nr_running);
  802. }
  803. worker->flags |= flags;
  804. }
  805. /**
  806. * worker_clr_flags - clear worker flags and adjust nr_running accordingly
  807. * @worker: self
  808. * @flags: flags to clear
  809. *
  810. * Clear @flags in @worker->flags and adjust nr_running accordingly.
  811. *
  812. * CONTEXT:
  813. * spin_lock_irq(pool->lock)
  814. */
  815. static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
  816. {
  817. struct worker_pool *pool = worker->pool;
  818. unsigned int oflags = worker->flags;
  819. WARN_ON_ONCE(worker->task != current);
  820. worker->flags &= ~flags;
  821. /*
  822. * If transitioning out of NOT_RUNNING, increment nr_running. Note
  823. * that the nested NOT_RUNNING is not a noop. NOT_RUNNING is mask
  824. * of multiple flags, not a single flag.
  825. */
  826. if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
  827. if (!(worker->flags & WORKER_NOT_RUNNING))
  828. atomic_inc(&pool->nr_running);
  829. }
  830. /**
  831. * find_worker_executing_work - find worker which is executing a work
  832. * @pool: pool of interest
  833. * @work: work to find worker for
  834. *
  835. * Find a worker which is executing @work on @pool by searching
  836. * @pool->busy_hash which is keyed by the address of @work. For a worker
  837. * to match, its current execution should match the address of @work and
  838. * its work function. This is to avoid unwanted dependency between
  839. * unrelated work executions through a work item being recycled while still
  840. * being executed.
  841. *
  842. * This is a bit tricky. A work item may be freed once its execution
  843. * starts and nothing prevents the freed area from being recycled for
  844. * another work item. If the same work item address ends up being reused
  845. * before the original execution finishes, workqueue will identify the
  846. * recycled work item as currently executing and make it wait until the
  847. * current execution finishes, introducing an unwanted dependency.
  848. *
  849. * This function checks the work item address and work function to avoid
  850. * false positives. Note that this isn't complete as one may construct a
  851. * work function which can introduce dependency onto itself through a
  852. * recycled work item. Well, if somebody wants to shoot oneself in the
  853. * foot that badly, there's only so much we can do, and if such deadlock
  854. * actually occurs, it should be easy to locate the culprit work function.
  855. *
  856. * CONTEXT:
  857. * spin_lock_irq(pool->lock).
  858. *
  859. * Return:
  860. * Pointer to worker which is executing @work if found, %NULL
  861. * otherwise.
  862. */
  863. static struct worker *find_worker_executing_work(struct worker_pool *pool,
  864. struct work_struct *work)
  865. {
  866. struct worker *worker;
  867. hash_for_each_possible(pool->busy_hash, worker, hentry,
  868. (unsigned long)work)
  869. if (worker->current_work == work &&
  870. worker->current_func == work->func)
  871. return worker;
  872. return NULL;
  873. }
  874. /**
  875. * move_linked_works - move linked works to a list
  876. * @work: start of series of works to be scheduled
  877. * @head: target list to append @work to
  878. * @nextp: out parameter for nested worklist walking
  879. *
  880. * Schedule linked works starting from @work to @head. Work series to
  881. * be scheduled starts at @work and includes any consecutive work with
  882. * WORK_STRUCT_LINKED set in its predecessor.
  883. *
  884. * If @nextp is not NULL, it's updated to point to the next work of
  885. * the last scheduled work. This allows move_linked_works() to be
  886. * nested inside outer list_for_each_entry_safe().
  887. *
  888. * CONTEXT:
  889. * spin_lock_irq(pool->lock).
  890. */
  891. static void move_linked_works(struct work_struct *work, struct list_head *head,
  892. struct work_struct **nextp)
  893. {
  894. struct work_struct *n;
  895. /*
  896. * Linked worklist will always end before the end of the list,
  897. * use NULL for list head.
  898. */
  899. list_for_each_entry_safe_from(work, n, NULL, entry) {
  900. list_move_tail(&work->entry, head);
  901. if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
  902. break;
  903. }
  904. /*
  905. * If we're already inside safe list traversal and have moved
  906. * multiple works to the scheduled queue, the next position
  907. * needs to be updated.
  908. */
  909. if (nextp)
  910. *nextp = n;
  911. }
  912. /**
  913. * get_pwq - get an extra reference on the specified pool_workqueue
  914. * @pwq: pool_workqueue to get
  915. *
  916. * Obtain an extra reference on @pwq. The caller should guarantee that
  917. * @pwq has positive refcnt and be holding the matching pool->lock.
  918. */
  919. static void get_pwq(struct pool_workqueue *pwq)
  920. {
  921. lockdep_assert_held(&pwq->pool->lock);
  922. WARN_ON_ONCE(pwq->refcnt <= 0);
  923. pwq->refcnt++;
  924. }
  925. /**
  926. * put_pwq - put a pool_workqueue reference
  927. * @pwq: pool_workqueue to put
  928. *
  929. * Drop a reference of @pwq. If its refcnt reaches zero, schedule its
  930. * destruction. The caller should be holding the matching pool->lock.
  931. */
  932. static void put_pwq(struct pool_workqueue *pwq)
  933. {
  934. lockdep_assert_held(&pwq->pool->lock);
  935. if (likely(--pwq->refcnt))
  936. return;
  937. if (WARN_ON_ONCE(!(pwq->wq->flags & WQ_UNBOUND)))
  938. return;
  939. /*
  940. * @pwq can't be released under pool->lock, bounce to
  941. * pwq_unbound_release_workfn(). This never recurses on the same
  942. * pool->lock as this path is taken only for unbound workqueues and
  943. * the release work item is scheduled on a per-cpu workqueue. To
  944. * avoid lockdep warning, unbound pool->locks are given lockdep
  945. * subclass of 1 in get_unbound_pool().
  946. */
  947. schedule_work(&pwq->unbound_release_work);
  948. }
  949. /**
  950. * put_pwq_unlocked - put_pwq() with surrounding pool lock/unlock
  951. * @pwq: pool_workqueue to put (can be %NULL)
  952. *
  953. * put_pwq() with locking. This function also allows %NULL @pwq.
  954. */
  955. static void put_pwq_unlocked(struct pool_workqueue *pwq)
  956. {
  957. if (pwq) {
  958. /*
  959. * As both pwqs and pools are sched-RCU protected, the
  960. * following lock operations are safe.
  961. */
  962. spin_lock_irq(&pwq->pool->lock);
  963. put_pwq(pwq);
  964. spin_unlock_irq(&pwq->pool->lock);
  965. }
  966. }
  967. static void pwq_activate_delayed_work(struct work_struct *work)
  968. {
  969. struct pool_workqueue *pwq = get_work_pwq(work);
  970. trace_workqueue_activate_work(work);
  971. if (list_empty(&pwq->pool->worklist))
  972. pwq->pool->watchdog_ts = jiffies;
  973. move_linked_works(work, &pwq->pool->worklist, NULL);
  974. __clear_bit(WORK_STRUCT_DELAYED_BIT, work_data_bits(work));
  975. pwq->nr_active++;
  976. }
  977. static void pwq_activate_first_delayed(struct pool_workqueue *pwq)
  978. {
  979. struct work_struct *work = list_first_entry(&pwq->delayed_works,
  980. struct work_struct, entry);
  981. pwq_activate_delayed_work(work);
  982. }
  983. /**
  984. * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
  985. * @pwq: pwq of interest
  986. * @color: color of work which left the queue
  987. *
  988. * A work either has completed or is removed from pending queue,
  989. * decrement nr_in_flight of its pwq and handle workqueue flushing.
  990. *
  991. * CONTEXT:
  992. * spin_lock_irq(pool->lock).
  993. */
  994. static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, int color)
  995. {
  996. /* uncolored work items don't participate in flushing or nr_active */
  997. if (color == WORK_NO_COLOR)
  998. goto out_put;
  999. pwq->nr_in_flight[color]--;
  1000. pwq->nr_active--;
  1001. if (!list_empty(&pwq->delayed_works)) {
  1002. /* one down, submit a delayed one */
  1003. if (pwq->nr_active < pwq->max_active)
  1004. pwq_activate_first_delayed(pwq);
  1005. }
  1006. /* is flush in progress and are we at the flushing tip? */
  1007. if (likely(pwq->flush_color != color))
  1008. goto out_put;
  1009. /* are there still in-flight works? */
  1010. if (pwq->nr_in_flight[color])
  1011. goto out_put;
  1012. /* this pwq is done, clear flush_color */
  1013. pwq->flush_color = -1;
  1014. /*
  1015. * If this was the last pwq, wake up the first flusher. It
  1016. * will handle the rest.
  1017. */
  1018. if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
  1019. complete(&pwq->wq->first_flusher->done);
  1020. out_put:
  1021. put_pwq(pwq);
  1022. }
  1023. /**
  1024. * try_to_grab_pending - steal work item from worklist and disable irq
  1025. * @work: work item to steal
  1026. * @is_dwork: @work is a delayed_work
  1027. * @flags: place to store irq state
  1028. *
  1029. * Try to grab PENDING bit of @work. This function can handle @work in any
  1030. * stable state - idle, on timer or on worklist.
  1031. *
  1032. * Return:
  1033. * 1 if @work was pending and we successfully stole PENDING
  1034. * 0 if @work was idle and we claimed PENDING
  1035. * -EAGAIN if PENDING couldn't be grabbed at the moment, safe to busy-retry
  1036. * -ENOENT if someone else is canceling @work, this state may persist
  1037. * for arbitrarily long
  1038. *
  1039. * Note:
  1040. * On >= 0 return, the caller owns @work's PENDING bit. To avoid getting
  1041. * interrupted while holding PENDING and @work off queue, irq must be
  1042. * disabled on entry. This, combined with delayed_work->timer being
  1043. * irqsafe, ensures that we return -EAGAIN for finite short period of time.
  1044. *
  1045. * On successful return, >= 0, irq is disabled and the caller is
  1046. * responsible for releasing it using local_irq_restore(*@flags).
  1047. *
  1048. * This function is safe to call from any context including IRQ handler.
  1049. */
  1050. static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
  1051. unsigned long *flags)
  1052. {
  1053. struct worker_pool *pool;
  1054. struct pool_workqueue *pwq;
  1055. local_irq_save(*flags);
  1056. /* try to steal the timer if it exists */
  1057. if (is_dwork) {
  1058. struct delayed_work *dwork = to_delayed_work(work);
  1059. /*
  1060. * dwork->timer is irqsafe. If del_timer() fails, it's
  1061. * guaranteed that the timer is not queued anywhere and not
  1062. * running on the local CPU.
  1063. */
  1064. if (likely(del_timer(&dwork->timer)))
  1065. return 1;
  1066. }
  1067. /* try to claim PENDING the normal way */
  1068. if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
  1069. return 0;
  1070. /*
  1071. * The queueing is in progress, or it is already queued. Try to
  1072. * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
  1073. */
  1074. pool = get_work_pool(work);
  1075. if (!pool)
  1076. goto fail;
  1077. spin_lock(&pool->lock);
  1078. /*
  1079. * work->data is guaranteed to point to pwq only while the work
  1080. * item is queued on pwq->wq, and both updating work->data to point
  1081. * to pwq on queueing and to pool on dequeueing are done under
  1082. * pwq->pool->lock. This in turn guarantees that, if work->data
  1083. * points to pwq which is associated with a locked pool, the work
  1084. * item is currently queued on that pool.
  1085. */
  1086. pwq = get_work_pwq(work);
  1087. if (pwq && pwq->pool == pool) {
  1088. debug_work_deactivate(work);
  1089. /*
  1090. * A delayed work item cannot be grabbed directly because
  1091. * it might have linked NO_COLOR work items which, if left
  1092. * on the delayed_list, will confuse pwq->nr_active
  1093. * management later on and cause stall. Make sure the work
  1094. * item is activated before grabbing.
  1095. */
  1096. if (*work_data_bits(work) & WORK_STRUCT_DELAYED)
  1097. pwq_activate_delayed_work(work);
  1098. list_del_init(&work->entry);
  1099. pwq_dec_nr_in_flight(pwq, get_work_color(work));
  1100. /* work->data points to pwq iff queued, point to pool */
  1101. set_work_pool_and_keep_pending(work, pool->id);
  1102. spin_unlock(&pool->lock);
  1103. return 1;
  1104. }
  1105. spin_unlock(&pool->lock);
  1106. fail:
  1107. local_irq_restore(*flags);
  1108. if (work_is_canceling(work))
  1109. return -ENOENT;
  1110. cpu_relax();
  1111. return -EAGAIN;
  1112. }
  1113. /**
  1114. * insert_work - insert a work into a pool
  1115. * @pwq: pwq @work belongs to
  1116. * @work: work to insert
  1117. * @head: insertion point
  1118. * @extra_flags: extra WORK_STRUCT_* flags to set
  1119. *
  1120. * Insert @work which belongs to @pwq after @head. @extra_flags is or'd to
  1121. * work_struct flags.
  1122. *
  1123. * CONTEXT:
  1124. * spin_lock_irq(pool->lock).
  1125. */
  1126. static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
  1127. struct list_head *head, unsigned int extra_flags)
  1128. {
  1129. struct worker_pool *pool = pwq->pool;
  1130. /* we own @work, set data and link */
  1131. set_work_pwq(work, pwq, extra_flags);
  1132. list_add_tail(&work->entry, head);
  1133. get_pwq(pwq);
  1134. /*
  1135. * Ensure either wq_worker_sleeping() sees the above
  1136. * list_add_tail() or we see zero nr_running to avoid workers lying
  1137. * around lazily while there are works to be processed.
  1138. */
  1139. smp_mb();
  1140. if (__need_more_worker(pool))
  1141. wake_up_worker(pool);
  1142. }
  1143. /*
  1144. * Test whether @work is being queued from another work executing on the
  1145. * same workqueue.
  1146. */
  1147. static bool is_chained_work(struct workqueue_struct *wq)
  1148. {
  1149. struct worker *worker;
  1150. worker = current_wq_worker();
  1151. /*
  1152. * Return %true iff I'm a worker execuing a work item on @wq. If
  1153. * I'm @worker, it's safe to dereference it without locking.
  1154. */
  1155. return worker && worker->current_pwq->wq == wq;
  1156. }
  1157. /*
  1158. * When queueing an unbound work item to a wq, prefer local CPU if allowed
  1159. * by wq_unbound_cpumask. Otherwise, round robin among the allowed ones to
  1160. * avoid perturbing sensitive tasks.
  1161. */
  1162. static int wq_select_unbound_cpu(int cpu)
  1163. {
  1164. static bool printed_dbg_warning;
  1165. int new_cpu;
  1166. if (likely(!wq_debug_force_rr_cpu)) {
  1167. if (cpumask_test_cpu(cpu, wq_unbound_cpumask))
  1168. return cpu;
  1169. } else if (!printed_dbg_warning) {
  1170. pr_warn("workqueue: round-robin CPU selection forced, expect performance impact\n");
  1171. printed_dbg_warning = true;
  1172. }
  1173. if (cpumask_empty(wq_unbound_cpumask))
  1174. return cpu;
  1175. new_cpu = __this_cpu_read(wq_rr_cpu_last);
  1176. new_cpu = cpumask_next_and(new_cpu, wq_unbound_cpumask, cpu_online_mask);
  1177. if (unlikely(new_cpu >= nr_cpu_ids)) {
  1178. new_cpu = cpumask_first_and(wq_unbound_cpumask, cpu_online_mask);
  1179. if (unlikely(new_cpu >= nr_cpu_ids))
  1180. return cpu;
  1181. }
  1182. __this_cpu_write(wq_rr_cpu_last, new_cpu);
  1183. return new_cpu;
  1184. }
  1185. static void __queue_work(int cpu, struct workqueue_struct *wq,
  1186. struct work_struct *work)
  1187. {
  1188. struct pool_workqueue *pwq;
  1189. struct worker_pool *last_pool;
  1190. struct list_head *worklist;
  1191. unsigned int work_flags;
  1192. unsigned int req_cpu = cpu;
  1193. /*
  1194. * While a work item is PENDING && off queue, a task trying to
  1195. * steal the PENDING will busy-loop waiting for it to either get
  1196. * queued or lose PENDING. Grabbing PENDING and queueing should
  1197. * happen with IRQ disabled.
  1198. */
  1199. lockdep_assert_irqs_disabled();
  1200. /* if draining, only works from the same workqueue are allowed */
  1201. if (unlikely(wq->flags & __WQ_DRAINING) &&
  1202. WARN_ON_ONCE(!is_chained_work(wq)))
  1203. return;
  1204. retry:
  1205. /* pwq which will be used unless @work is executing elsewhere */
  1206. if (wq->flags & WQ_UNBOUND) {
  1207. if (req_cpu == WORK_CPU_UNBOUND)
  1208. cpu = wq_select_unbound_cpu(raw_smp_processor_id());
  1209. pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
  1210. } else {
  1211. if (req_cpu == WORK_CPU_UNBOUND)
  1212. cpu = raw_smp_processor_id();
  1213. pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
  1214. }
  1215. /*
  1216. * If @work was previously on a different pool, it might still be
  1217. * running there, in which case the work needs to be queued on that
  1218. * pool to guarantee non-reentrancy.
  1219. */
  1220. last_pool = get_work_pool(work);
  1221. if (last_pool && last_pool != pwq->pool) {
  1222. struct worker *worker;
  1223. spin_lock(&last_pool->lock);
  1224. worker = find_worker_executing_work(last_pool, work);
  1225. if (worker && worker->current_pwq->wq == wq) {
  1226. pwq = worker->current_pwq;
  1227. } else {
  1228. /* meh... not running there, queue here */
  1229. spin_unlock(&last_pool->lock);
  1230. spin_lock(&pwq->pool->lock);
  1231. }
  1232. } else {
  1233. spin_lock(&pwq->pool->lock);
  1234. }
  1235. /*
  1236. * pwq is determined and locked. For unbound pools, we could have
  1237. * raced with pwq release and it could already be dead. If its
  1238. * refcnt is zero, repeat pwq selection. Note that pwqs never die
  1239. * without another pwq replacing it in the numa_pwq_tbl or while
  1240. * work items are executing on it, so the retrying is guaranteed to
  1241. * make forward-progress.
  1242. */
  1243. if (unlikely(!pwq->refcnt)) {
  1244. if (wq->flags & WQ_UNBOUND) {
  1245. spin_unlock(&pwq->pool->lock);
  1246. cpu_relax();
  1247. goto retry;
  1248. }
  1249. /* oops */
  1250. WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
  1251. wq->name, cpu);
  1252. }
  1253. /* pwq determined, queue */
  1254. trace_workqueue_queue_work(req_cpu, pwq, work);
  1255. if (WARN_ON(!list_empty(&work->entry))) {
  1256. spin_unlock(&pwq->pool->lock);
  1257. return;
  1258. }
  1259. pwq->nr_in_flight[pwq->work_color]++;
  1260. work_flags = work_color_to_flags(pwq->work_color);
  1261. if (likely(pwq->nr_active < pwq->max_active)) {
  1262. trace_workqueue_activate_work(work);
  1263. pwq->nr_active++;
  1264. worklist = &pwq->pool->worklist;
  1265. if (list_empty(worklist))
  1266. pwq->pool->watchdog_ts = jiffies;
  1267. } else {
  1268. work_flags |= WORK_STRUCT_DELAYED;
  1269. worklist = &pwq->delayed_works;
  1270. }
  1271. debug_work_activate(work);
  1272. insert_work(pwq, work, worklist, work_flags);
  1273. spin_unlock(&pwq->pool->lock);
  1274. }
  1275. /**
  1276. * queue_work_on - queue work on specific cpu
  1277. * @cpu: CPU number to execute work on
  1278. * @wq: workqueue to use
  1279. * @work: work to queue
  1280. *
  1281. * We queue the work to a specific CPU, the caller must ensure it
  1282. * can't go away.
  1283. *
  1284. * Return: %false if @work was already on a queue, %true otherwise.
  1285. */
  1286. bool queue_work_on(int cpu, struct workqueue_struct *wq,
  1287. struct work_struct *work)
  1288. {
  1289. bool ret = false;
  1290. unsigned long flags;
  1291. local_irq_save(flags);
  1292. if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
  1293. __queue_work(cpu, wq, work);
  1294. ret = true;
  1295. }
  1296. local_irq_restore(flags);
  1297. return ret;
  1298. }
  1299. EXPORT_SYMBOL(queue_work_on);
  1300. void delayed_work_timer_fn(struct timer_list *t)
  1301. {
  1302. struct delayed_work *dwork = from_timer(dwork, t, timer);
  1303. /* should have been called from irqsafe timer with irq already off */
  1304. __queue_work(dwork->cpu, dwork->wq, &dwork->work);
  1305. }
  1306. EXPORT_SYMBOL(delayed_work_timer_fn);
  1307. static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
  1308. struct delayed_work *dwork, unsigned long delay)
  1309. {
  1310. struct timer_list *timer = &dwork->timer;
  1311. struct work_struct *work = &dwork->work;
  1312. WARN_ON_ONCE(!wq);
  1313. WARN_ON_ONCE(timer->function != delayed_work_timer_fn);
  1314. WARN_ON_ONCE(timer_pending(timer));
  1315. WARN_ON_ONCE(!list_empty(&work->entry));
  1316. /*
  1317. * If @delay is 0, queue @dwork->work immediately. This is for
  1318. * both optimization and correctness. The earliest @timer can
  1319. * expire is on the closest next tick and delayed_work users depend
  1320. * on that there's no such delay when @delay is 0.
  1321. */
  1322. if (!delay) {
  1323. __queue_work(cpu, wq, &dwork->work);
  1324. return;
  1325. }
  1326. dwork->wq = wq;
  1327. dwork->cpu = cpu;
  1328. timer->expires = jiffies + delay;
  1329. if (unlikely(cpu != WORK_CPU_UNBOUND))
  1330. add_timer_on(timer, cpu);
  1331. else
  1332. add_timer(timer);
  1333. }
  1334. /**
  1335. * queue_delayed_work_on - queue work on specific CPU after delay
  1336. * @cpu: CPU number to execute work on
  1337. * @wq: workqueue to use
  1338. * @dwork: work to queue
  1339. * @delay: number of jiffies to wait before queueing
  1340. *
  1341. * Return: %false if @work was already on a queue, %true otherwise. If
  1342. * @delay is zero and @dwork is idle, it will be scheduled for immediate
  1343. * execution.
  1344. */
  1345. bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
  1346. struct delayed_work *dwork, unsigned long delay)
  1347. {
  1348. struct work_struct *work = &dwork->work;
  1349. bool ret = false;
  1350. unsigned long flags;
  1351. /* read the comment in __queue_work() */
  1352. local_irq_save(flags);
  1353. if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
  1354. __queue_delayed_work(cpu, wq, dwork, delay);
  1355. ret = true;
  1356. }
  1357. local_irq_restore(flags);
  1358. return ret;
  1359. }
  1360. EXPORT_SYMBOL(queue_delayed_work_on);
  1361. /**
  1362. * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
  1363. * @cpu: CPU number to execute work on
  1364. * @wq: workqueue to use
  1365. * @dwork: work to queue
  1366. * @delay: number of jiffies to wait before queueing
  1367. *
  1368. * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
  1369. * modify @dwork's timer so that it expires after @delay. If @delay is
  1370. * zero, @work is guaranteed to be scheduled immediately regardless of its
  1371. * current state.
  1372. *
  1373. * Return: %false if @dwork was idle and queued, %true if @dwork was
  1374. * pending and its timer was modified.
  1375. *
  1376. * This function is safe to call from any context including IRQ handler.
  1377. * See try_to_grab_pending() for details.
  1378. */
  1379. bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
  1380. struct delayed_work *dwork, unsigned long delay)
  1381. {
  1382. unsigned long flags;
  1383. int ret;
  1384. do {
  1385. ret = try_to_grab_pending(&dwork->work, true, &flags);
  1386. } while (unlikely(ret == -EAGAIN));
  1387. if (likely(ret >= 0)) {
  1388. __queue_delayed_work(cpu, wq, dwork, delay);
  1389. local_irq_restore(flags);
  1390. }
  1391. /* -ENOENT from try_to_grab_pending() becomes %true */
  1392. return ret;
  1393. }
  1394. EXPORT_SYMBOL_GPL(mod_delayed_work_on);
  1395. static void rcu_work_rcufn(struct rcu_head *rcu)
  1396. {
  1397. struct rcu_work *rwork = container_of(rcu, struct rcu_work, rcu);
  1398. /* read the comment in __queue_work() */
  1399. local_irq_disable();
  1400. __queue_work(WORK_CPU_UNBOUND, rwork->wq, &rwork->work);
  1401. local_irq_enable();
  1402. }
  1403. /**
  1404. * queue_rcu_work - queue work after a RCU grace period
  1405. * @wq: workqueue to use
  1406. * @rwork: work to queue
  1407. *
  1408. * Return: %false if @rwork was already pending, %true otherwise. Note
  1409. * that a full RCU grace period is guaranteed only after a %true return.
  1410. * While @rwork is guarnateed to be executed after a %false return, the
  1411. * execution may happen before a full RCU grace period has passed.
  1412. */
  1413. bool queue_rcu_work(struct workqueue_struct *wq, struct rcu_work *rwork)
  1414. {
  1415. struct work_struct *work = &rwork->work;
  1416. if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
  1417. rwork->wq = wq;
  1418. call_rcu(&rwork->rcu, rcu_work_rcufn);
  1419. return true;
  1420. }
  1421. return false;
  1422. }
  1423. EXPORT_SYMBOL(queue_rcu_work);
  1424. /**
  1425. * worker_enter_idle - enter idle state
  1426. * @worker: worker which is entering idle state
  1427. *
  1428. * @worker is entering idle state. Update stats and idle timer if
  1429. * necessary.
  1430. *
  1431. * LOCKING:
  1432. * spin_lock_irq(pool->lock).
  1433. */
  1434. static void worker_enter_idle(struct worker *worker)
  1435. {
  1436. struct worker_pool *pool = worker->pool;
  1437. if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
  1438. WARN_ON_ONCE(!list_empty(&worker->entry) &&
  1439. (worker->hentry.next || worker->hentry.pprev)))
  1440. return;
  1441. /* can't use worker_set_flags(), also called from create_worker() */
  1442. worker->flags |= WORKER_IDLE;
  1443. pool->nr_idle++;
  1444. worker->last_active = jiffies;
  1445. /* idle_list is LIFO */
  1446. list_add(&worker->entry, &pool->idle_list);
  1447. if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
  1448. mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
  1449. /*
  1450. * Sanity check nr_running. Because unbind_workers() releases
  1451. * pool->lock between setting %WORKER_UNBOUND and zapping
  1452. * nr_running, the warning may trigger spuriously. Check iff
  1453. * unbind is not in progress.
  1454. */
  1455. WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
  1456. pool->nr_workers == pool->nr_idle &&
  1457. atomic_read(&pool->nr_running));
  1458. }
  1459. /**
  1460. * worker_leave_idle - leave idle state
  1461. * @worker: worker which is leaving idle state
  1462. *
  1463. * @worker is leaving idle state. Update stats.
  1464. *
  1465. * LOCKING:
  1466. * spin_lock_irq(pool->lock).
  1467. */
  1468. static void worker_leave_idle(struct worker *worker)
  1469. {
  1470. struct worker_pool *pool = worker->pool;
  1471. if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
  1472. return;
  1473. worker_clr_flags(worker, WORKER_IDLE);
  1474. pool->nr_idle--;
  1475. list_del_init(&worker->entry);
  1476. }
  1477. static struct worker *alloc_worker(int node)
  1478. {
  1479. struct worker *worker;
  1480. worker = kzalloc_node(sizeof(*worker), GFP_KERNEL, node);
  1481. if (worker) {
  1482. INIT_LIST_HEAD(&worker->entry);
  1483. INIT_LIST_HEAD(&worker->scheduled);
  1484. INIT_LIST_HEAD(&worker->node);
  1485. /* on creation a worker is in !idle && prep state */
  1486. worker->flags = WORKER_PREP;
  1487. }
  1488. return worker;
  1489. }
  1490. /**
  1491. * worker_attach_to_pool() - attach a worker to a pool
  1492. * @worker: worker to be attached
  1493. * @pool: the target pool
  1494. *
  1495. * Attach @worker to @pool. Once attached, the %WORKER_UNBOUND flag and
  1496. * cpu-binding of @worker are kept coordinated with the pool across
  1497. * cpu-[un]hotplugs.
  1498. */
  1499. static void worker_attach_to_pool(struct worker *worker,
  1500. struct worker_pool *pool)
  1501. {
  1502. mutex_lock(&wq_pool_attach_mutex);
  1503. /*
  1504. * The wq_pool_attach_mutex ensures %POOL_DISASSOCIATED remains
  1505. * stable across this function. See the comments above the flag
  1506. * definition for details.
  1507. */
  1508. if (pool->flags & POOL_DISASSOCIATED)
  1509. worker->flags |= WORKER_UNBOUND;
  1510. if (worker->rescue_wq)
  1511. set_cpus_allowed_ptr(worker->task, pool->attrs->cpumask);
  1512. list_add_tail(&worker->node, &pool->workers);
  1513. worker->pool = pool;
  1514. mutex_unlock(&wq_pool_attach_mutex);
  1515. }
  1516. /**
  1517. * worker_detach_from_pool() - detach a worker from its pool
  1518. * @worker: worker which is attached to its pool
  1519. *
  1520. * Undo the attaching which had been done in worker_attach_to_pool(). The
  1521. * caller worker shouldn't access to the pool after detached except it has
  1522. * other reference to the pool.
  1523. */
  1524. static void worker_detach_from_pool(struct worker *worker)
  1525. {
  1526. struct worker_pool *pool = worker->pool;
  1527. struct completion *detach_completion = NULL;
  1528. mutex_lock(&wq_pool_attach_mutex);
  1529. list_del(&worker->node);
  1530. worker->pool = NULL;
  1531. if (list_empty(&pool->workers))
  1532. detach_completion = pool->detach_completion;
  1533. mutex_unlock(&wq_pool_attach_mutex);
  1534. /* clear leftover flags without pool->lock after it is detached */
  1535. worker->flags &= ~(WORKER_UNBOUND | WORKER_REBOUND);
  1536. if (detach_completion)
  1537. complete(detach_completion);
  1538. }
  1539. /**
  1540. * create_worker - create a new workqueue worker
  1541. * @pool: pool the new worker will belong to
  1542. *
  1543. * Create and start a new worker which is attached to @pool.
  1544. *
  1545. * CONTEXT:
  1546. * Might sleep. Does GFP_KERNEL allocations.
  1547. *
  1548. * Return:
  1549. * Pointer to the newly created worker.
  1550. */
  1551. static struct worker *create_worker(struct worker_pool *pool)
  1552. {
  1553. struct worker *worker = NULL;
  1554. int id = -1;
  1555. char id_buf[16];
  1556. /* ID is needed to determine kthread name */
  1557. id = ida_simple_get(&pool->worker_ida, 0, 0, GFP_KERNEL);
  1558. if (id < 0)
  1559. goto fail;
  1560. worker = alloc_worker(pool->node);
  1561. if (!worker)
  1562. goto fail;
  1563. worker->id = id;
  1564. if (pool->cpu >= 0)
  1565. snprintf(id_buf, sizeof(id_buf), "%d:%d%s", pool->cpu, id,
  1566. pool->attrs->nice < 0 ? "H" : "");
  1567. else
  1568. snprintf(id_buf, sizeof(id_buf), "u%d:%d", pool->id, id);
  1569. worker->task = kthread_create_on_node(worker_thread, worker, pool->node,
  1570. "kworker/%s", id_buf);
  1571. if (IS_ERR(worker->task))
  1572. goto fail;
  1573. set_user_nice(worker->task, pool->attrs->nice);
  1574. kthread_bind_mask(worker->task, pool->attrs->cpumask);
  1575. /* successful, attach the worker to the pool */
  1576. worker_attach_to_pool(worker, pool);
  1577. /* start the newly created worker */
  1578. spin_lock_irq(&pool->lock);
  1579. worker->pool->nr_workers++;
  1580. worker_enter_idle(worker);
  1581. wake_up_process(worker->task);
  1582. spin_unlock_irq(&pool->lock);
  1583. return worker;
  1584. fail:
  1585. if (id >= 0)
  1586. ida_simple_remove(&pool->worker_ida, id);
  1587. kfree(worker);
  1588. return NULL;
  1589. }
  1590. /**
  1591. * destroy_worker - destroy a workqueue worker
  1592. * @worker: worker to be destroyed
  1593. *
  1594. * Destroy @worker and adjust @pool stats accordingly. The worker should
  1595. * be idle.
  1596. *
  1597. * CONTEXT:
  1598. * spin_lock_irq(pool->lock).
  1599. */
  1600. static void destroy_worker(struct worker *worker)
  1601. {
  1602. struct worker_pool *pool = worker->pool;
  1603. lockdep_assert_held(&pool->lock);
  1604. /* sanity check frenzy */
  1605. if (WARN_ON(worker->current_work) ||
  1606. WARN_ON(!list_empty(&worker->scheduled)) ||
  1607. WARN_ON(!(worker->flags & WORKER_IDLE)))
  1608. return;
  1609. pool->nr_workers--;
  1610. pool->nr_idle--;
  1611. list_del_init(&worker->entry);
  1612. worker->flags |= WORKER_DIE;
  1613. wake_up_process(worker->task);
  1614. }
  1615. static void idle_worker_timeout(struct timer_list *t)
  1616. {
  1617. struct worker_pool *pool = from_timer(pool, t, idle_timer);
  1618. spin_lock_irq(&pool->lock);
  1619. while (too_many_workers(pool)) {
  1620. struct worker *worker;
  1621. unsigned long expires;
  1622. /* idle_list is kept in LIFO order, check the last one */
  1623. worker = list_entry(pool->idle_list.prev, struct worker, entry);
  1624. expires = worker->last_active + IDLE_WORKER_TIMEOUT;
  1625. if (time_before(jiffies, expires)) {
  1626. mod_timer(&pool->idle_timer, expires);
  1627. break;
  1628. }
  1629. destroy_worker(worker);
  1630. }
  1631. spin_unlock_irq(&pool->lock);
  1632. }
  1633. static void send_mayday(struct work_struct *work)
  1634. {
  1635. struct pool_workqueue *pwq = get_work_pwq(work);
  1636. struct workqueue_struct *wq = pwq->wq;
  1637. lockdep_assert_held(&wq_mayday_lock);
  1638. if (!wq->rescuer)
  1639. return;
  1640. /* mayday mayday mayday */
  1641. if (list_empty(&pwq->mayday_node)) {
  1642. /*
  1643. * If @pwq is for an unbound wq, its base ref may be put at
  1644. * any time due to an attribute change. Pin @pwq until the
  1645. * rescuer is done with it.
  1646. */
  1647. get_pwq(pwq);
  1648. list_add_tail(&pwq->mayday_node, &wq->maydays);
  1649. wake_up_process(wq->rescuer->task);
  1650. }
  1651. }
  1652. static void pool_mayday_timeout(struct timer_list *t)
  1653. {
  1654. struct worker_pool *pool = from_timer(pool, t, mayday_timer);
  1655. struct work_struct *work;
  1656. spin_lock_irq(&pool->lock);
  1657. spin_lock(&wq_mayday_lock); /* for wq->maydays */
  1658. if (need_to_create_worker(pool)) {
  1659. /*
  1660. * We've been trying to create a new worker but
  1661. * haven't been successful. We might be hitting an
  1662. * allocation deadlock. Send distress signals to
  1663. * rescuers.
  1664. */
  1665. list_for_each_entry(work, &pool->worklist, entry)
  1666. send_mayday(work);
  1667. }
  1668. spin_unlock(&wq_mayday_lock);
  1669. spin_unlock_irq(&pool->lock);
  1670. mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
  1671. }
  1672. /**
  1673. * maybe_create_worker - create a new worker if necessary
  1674. * @pool: pool to create a new worker for
  1675. *
  1676. * Create a new worker for @pool if necessary. @pool is guaranteed to
  1677. * have at least one idle worker on return from this function. If
  1678. * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
  1679. * sent to all rescuers with works scheduled on @pool to resolve
  1680. * possible allocation deadlock.
  1681. *
  1682. * On return, need_to_create_worker() is guaranteed to be %false and
  1683. * may_start_working() %true.
  1684. *
  1685. * LOCKING:
  1686. * spin_lock_irq(pool->lock) which may be released and regrabbed
  1687. * multiple times. Does GFP_KERNEL allocations. Called only from
  1688. * manager.
  1689. */
  1690. static void maybe_create_worker(struct worker_pool *pool)
  1691. __releases(&pool->lock)
  1692. __acquires(&pool->lock)
  1693. {
  1694. restart:
  1695. spin_unlock_irq(&pool->lock);
  1696. /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
  1697. mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
  1698. while (true) {
  1699. if (create_worker(pool) || !need_to_create_worker(pool))
  1700. break;
  1701. schedule_timeout_interruptible(CREATE_COOLDOWN);
  1702. if (!need_to_create_worker(pool))
  1703. break;
  1704. }
  1705. del_timer_sync(&pool->mayday_timer);
  1706. spin_lock_irq(&pool->lock);
  1707. /*
  1708. * This is necessary even after a new worker was just successfully
  1709. * created as @pool->lock was dropped and the new worker might have
  1710. * already become busy.
  1711. */
  1712. if (need_to_create_worker(pool))
  1713. goto restart;
  1714. }
  1715. /**
  1716. * manage_workers - manage worker pool
  1717. * @worker: self
  1718. *
  1719. * Assume the manager role and manage the worker pool @worker belongs
  1720. * to. At any given time, there can be only zero or one manager per
  1721. * pool. The exclusion is handled automatically by this function.
  1722. *
  1723. * The caller can safely start processing works on false return. On
  1724. * true return, it's guaranteed that need_to_create_worker() is false
  1725. * and may_start_working() is true.
  1726. *
  1727. * CONTEXT:
  1728. * spin_lock_irq(pool->lock) which may be released and regrabbed
  1729. * multiple times. Does GFP_KERNEL allocations.
  1730. *
  1731. * Return:
  1732. * %false if the pool doesn't need management and the caller can safely
  1733. * start processing works, %true if management function was performed and
  1734. * the conditions that the caller verified before calling the function may
  1735. * no longer be true.
  1736. */
  1737. static bool manage_workers(struct worker *worker)
  1738. {
  1739. struct worker_pool *pool = worker->pool;
  1740. if (pool->flags & POOL_MANAGER_ACTIVE)
  1741. return false;
  1742. pool->flags |= POOL_MANAGER_ACTIVE;
  1743. pool->manager = worker;
  1744. maybe_create_worker(pool);
  1745. pool->manager = NULL;
  1746. pool->flags &= ~POOL_MANAGER_ACTIVE;
  1747. wake_up(&wq_manager_wait);
  1748. return true;
  1749. }
  1750. /**
  1751. * process_one_work - process single work
  1752. * @worker: self
  1753. * @work: work to process
  1754. *
  1755. * Process @work. This function contains all the logics necessary to
  1756. * process a single work including synchronization against and
  1757. * interaction with other workers on the same cpu, queueing and
  1758. * flushing. As long as context requirement is met, any worker can
  1759. * call this function to process a work.
  1760. *
  1761. * CONTEXT:
  1762. * spin_lock_irq(pool->lock) which is released and regrabbed.
  1763. */
  1764. static void process_one_work(struct worker *worker, struct work_struct *work)
  1765. __releases(&pool->lock)
  1766. __acquires(&pool->lock)
  1767. {
  1768. struct pool_workqueue *pwq = get_work_pwq(work);
  1769. struct worker_pool *pool = worker->pool;
  1770. bool cpu_intensive = pwq->wq->flags & WQ_CPU_INTENSIVE;
  1771. int work_color;
  1772. struct worker *collision;
  1773. #ifdef CONFIG_LOCKDEP
  1774. /*
  1775. * It is permissible to free the struct work_struct from
  1776. * inside the function that is called from it, this we need to
  1777. * take into account for lockdep too. To avoid bogus "held
  1778. * lock freed" warnings as well as problems when looking into
  1779. * work->lockdep_map, make a copy and use that here.
  1780. */
  1781. struct lockdep_map lockdep_map;
  1782. lockdep_copy_map(&lockdep_map, &work->lockdep_map);
  1783. #endif
  1784. /* ensure we're on the correct CPU */
  1785. WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
  1786. raw_smp_processor_id() != pool->cpu);
  1787. /*
  1788. * A single work shouldn't be executed concurrently by
  1789. * multiple workers on a single cpu. Check whether anyone is
  1790. * already processing the work. If so, defer the work to the
  1791. * currently executing one.
  1792. */
  1793. collision = find_worker_executing_work(pool, work);
  1794. if (unlikely(collision)) {
  1795. move_linked_works(work, &collision->scheduled, NULL);
  1796. return;
  1797. }
  1798. /* claim and dequeue */
  1799. debug_work_deactivate(work);
  1800. hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
  1801. worker->current_work = work;
  1802. worker->current_func = work->func;
  1803. worker->current_pwq = pwq;
  1804. work_color = get_work_color(work);
  1805. /*
  1806. * Record wq name for cmdline and debug reporting, may get
  1807. * overridden through set_worker_desc().
  1808. */
  1809. strscpy(worker->desc, pwq->wq->name, WORKER_DESC_LEN);
  1810. list_del_init(&work->entry);
  1811. /*
  1812. * CPU intensive works don't participate in concurrency management.
  1813. * They're the scheduler's responsibility. This takes @worker out
  1814. * of concurrency management and the next code block will chain
  1815. * execution of the pending work items.
  1816. */
  1817. if (unlikely(cpu_intensive))
  1818. worker_set_flags(worker, WORKER_CPU_INTENSIVE);
  1819. /*
  1820. * Wake up another worker if necessary. The condition is always
  1821. * false for normal per-cpu workers since nr_running would always
  1822. * be >= 1 at this point. This is used to chain execution of the
  1823. * pending work items for WORKER_NOT_RUNNING workers such as the
  1824. * UNBOUND and CPU_INTENSIVE ones.
  1825. */
  1826. if (need_more_worker(pool))
  1827. wake_up_worker(pool);
  1828. /*
  1829. * Record the last pool and clear PENDING which should be the last
  1830. * update to @work. Also, do this inside @pool->lock so that
  1831. * PENDING and queued state changes happen together while IRQ is
  1832. * disabled.
  1833. */
  1834. set_work_pool_and_clear_pending(work, pool->id);
  1835. spin_unlock_irq(&pool->lock);
  1836. lock_map_acquire(&pwq->wq->lockdep_map);
  1837. lock_map_acquire(&lockdep_map);
  1838. /*
  1839. * Strictly speaking we should mark the invariant state without holding
  1840. * any locks, that is, before these two lock_map_acquire()'s.
  1841. *
  1842. * However, that would result in:
  1843. *
  1844. * A(W1)
  1845. * WFC(C)
  1846. * A(W1)
  1847. * C(C)
  1848. *
  1849. * Which would create W1->C->W1 dependencies, even though there is no
  1850. * actual deadlock possible. There are two solutions, using a
  1851. * read-recursive acquire on the work(queue) 'locks', but this will then
  1852. * hit the lockdep limitation on recursive locks, or simply discard
  1853. * these locks.
  1854. *
  1855. * AFAICT there is no possible deadlock scenario between the
  1856. * flush_work() and complete() primitives (except for single-threaded
  1857. * workqueues), so hiding them isn't a problem.
  1858. */
  1859. lockdep_invariant_state(true);
  1860. trace_workqueue_execute_start(work);
  1861. worker->current_func(work);
  1862. /*
  1863. * While we must be careful to not use "work" after this, the trace
  1864. * point will only record its address.
  1865. */
  1866. trace_workqueue_execute_end(work);
  1867. lock_map_release(&lockdep_map);
  1868. lock_map_release(&pwq->wq->lockdep_map);
  1869. if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
  1870. pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
  1871. " last function: %pf\n",
  1872. current->comm, preempt_count(), task_pid_nr(current),
  1873. worker->current_func);
  1874. debug_show_held_locks(current);
  1875. dump_stack();
  1876. }
  1877. /*
  1878. * The following prevents a kworker from hogging CPU on !PREEMPT
  1879. * kernels, where a requeueing work item waiting for something to
  1880. * happen could deadlock with stop_machine as such work item could
  1881. * indefinitely requeue itself while all other CPUs are trapped in
  1882. * stop_machine. At the same time, report a quiescent RCU state so
  1883. * the same condition doesn't freeze RCU.
  1884. */
  1885. cond_resched();
  1886. spin_lock_irq(&pool->lock);
  1887. /* clear cpu intensive status */
  1888. if (unlikely(cpu_intensive))
  1889. worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
  1890. /* we're done with it, release */
  1891. hash_del(&worker->hentry);
  1892. worker->current_work = NULL;
  1893. worker->current_func = NULL;
  1894. worker->current_pwq = NULL;
  1895. pwq_dec_nr_in_flight(pwq, work_color);
  1896. }
  1897. /**
  1898. * process_scheduled_works - process scheduled works
  1899. * @worker: self
  1900. *
  1901. * Process all scheduled works. Please note that the scheduled list
  1902. * may change while processing a work, so this function repeatedly
  1903. * fetches a work from the top and executes it.
  1904. *
  1905. * CONTEXT:
  1906. * spin_lock_irq(pool->lock) which may be released and regrabbed
  1907. * multiple times.
  1908. */
  1909. static void process_scheduled_works(struct worker *worker)
  1910. {
  1911. while (!list_empty(&worker->scheduled)) {
  1912. struct work_struct *work = list_first_entry(&worker->scheduled,
  1913. struct work_struct, entry);
  1914. process_one_work(worker, work);
  1915. }
  1916. }
  1917. static void set_pf_worker(bool val)
  1918. {
  1919. mutex_lock(&wq_pool_attach_mutex);
  1920. if (val)
  1921. current->flags |= PF_WQ_WORKER;
  1922. else
  1923. current->flags &= ~PF_WQ_WORKER;
  1924. mutex_unlock(&wq_pool_attach_mutex);
  1925. }
  1926. /**
  1927. * worker_thread - the worker thread function
  1928. * @__worker: self
  1929. *
  1930. * The worker thread function. All workers belong to a worker_pool -
  1931. * either a per-cpu one or dynamic unbound one. These workers process all
  1932. * work items regardless of their specific target workqueue. The only
  1933. * exception is work items which belong to workqueues with a rescuer which
  1934. * will be explained in rescuer_thread().
  1935. *
  1936. * Return: 0
  1937. */
  1938. static int worker_thread(void *__worker)
  1939. {
  1940. struct worker *worker = __worker;
  1941. struct worker_pool *pool = worker->pool;
  1942. /* tell the scheduler that this is a workqueue worker */
  1943. set_pf_worker(true);
  1944. woke_up:
  1945. spin_lock_irq(&pool->lock);
  1946. /* am I supposed to die? */
  1947. if (unlikely(worker->flags & WORKER_DIE)) {
  1948. spin_unlock_irq(&pool->lock);
  1949. WARN_ON_ONCE(!list_empty(&worker->entry));
  1950. set_pf_worker(false);
  1951. set_task_comm(worker->task, "kworker/dying");
  1952. ida_simple_remove(&pool->worker_ida, worker->id);
  1953. worker_detach_from_pool(worker);
  1954. kfree(worker);
  1955. return 0;
  1956. }
  1957. worker_leave_idle(worker);
  1958. recheck:
  1959. /* no more worker necessary? */
  1960. if (!need_more_worker(pool))
  1961. goto sleep;
  1962. /* do we need to manage? */
  1963. if (unlikely(!may_start_working(pool)) && manage_workers(worker))
  1964. goto recheck;
  1965. /*
  1966. * ->scheduled list can only be filled while a worker is
  1967. * preparing to process a work or actually processing it.
  1968. * Make sure nobody diddled with it while I was sleeping.
  1969. */
  1970. WARN_ON_ONCE(!list_empty(&worker->scheduled));
  1971. /*
  1972. * Finish PREP stage. We're guaranteed to have at least one idle
  1973. * worker or that someone else has already assumed the manager
  1974. * role. This is where @worker starts participating in concurrency
  1975. * management if applicable and concurrency management is restored
  1976. * after being rebound. See rebind_workers() for details.
  1977. */
  1978. worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
  1979. do {
  1980. struct work_struct *work =
  1981. list_first_entry(&pool->worklist,
  1982. struct work_struct, entry);
  1983. pool->watchdog_ts = jiffies;
  1984. if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
  1985. /* optimization path, not strictly necessary */
  1986. process_one_work(worker, work);
  1987. if (unlikely(!list_empty(&worker->scheduled)))
  1988. process_scheduled_works(worker);
  1989. } else {
  1990. move_linked_works(work, &worker->scheduled, NULL);
  1991. process_scheduled_works(worker);
  1992. }
  1993. } while (keep_working(pool));
  1994. worker_set_flags(worker, WORKER_PREP);
  1995. sleep:
  1996. /*
  1997. * pool->lock is held and there's no work to process and no need to
  1998. * manage, sleep. Workers are woken up only while holding
  1999. * pool->lock or from local cpu, so setting the current state
  2000. * before releasing pool->lock is enough to prevent losing any
  2001. * event.
  2002. */
  2003. worker_enter_idle(worker);
  2004. __set_current_state(TASK_IDLE);
  2005. spin_unlock_irq(&pool->lock);
  2006. schedule();
  2007. goto woke_up;
  2008. }
  2009. /**
  2010. * rescuer_thread - the rescuer thread function
  2011. * @__rescuer: self
  2012. *
  2013. * Workqueue rescuer thread function. There's one rescuer for each
  2014. * workqueue which has WQ_MEM_RECLAIM set.
  2015. *
  2016. * Regular work processing on a pool may block trying to create a new
  2017. * worker which uses GFP_KERNEL allocation which has slight chance of
  2018. * developing into deadlock if some works currently on the same queue
  2019. * need to be processed to satisfy the GFP_KERNEL allocation. This is
  2020. * the problem rescuer solves.
  2021. *
  2022. * When such condition is possible, the pool summons rescuers of all
  2023. * workqueues which have works queued on the pool and let them process
  2024. * those works so that forward progress can be guaranteed.
  2025. *
  2026. * This should happen rarely.
  2027. *
  2028. * Return: 0
  2029. */
  2030. static int rescuer_thread(void *__rescuer)
  2031. {
  2032. struct worker *rescuer = __rescuer;
  2033. struct workqueue_struct *wq = rescuer->rescue_wq;
  2034. struct list_head *scheduled = &rescuer->scheduled;
  2035. bool should_stop;
  2036. set_user_nice(current, RESCUER_NICE_LEVEL);
  2037. /*
  2038. * Mark rescuer as worker too. As WORKER_PREP is never cleared, it
  2039. * doesn't participate in concurrency management.
  2040. */
  2041. set_pf_worker(true);
  2042. repeat:
  2043. set_current_state(TASK_IDLE);
  2044. /*
  2045. * By the time the rescuer is requested to stop, the workqueue
  2046. * shouldn't have any work pending, but @wq->maydays may still have
  2047. * pwq(s) queued. This can happen by non-rescuer workers consuming
  2048. * all the work items before the rescuer got to them. Go through
  2049. * @wq->maydays processing before acting on should_stop so that the
  2050. * list is always empty on exit.
  2051. */
  2052. should_stop = kthread_should_stop();
  2053. /* see whether any pwq is asking for help */
  2054. spin_lock_irq(&wq_mayday_lock);
  2055. while (!list_empty(&wq->maydays)) {
  2056. struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
  2057. struct pool_workqueue, mayday_node);
  2058. struct worker_pool *pool = pwq->pool;
  2059. struct work_struct *work, *n;
  2060. bool first = true;
  2061. __set_current_state(TASK_RUNNING);
  2062. list_del_init(&pwq->mayday_node);
  2063. spin_unlock_irq(&wq_mayday_lock);
  2064. worker_attach_to_pool(rescuer, pool);
  2065. spin_lock_irq(&pool->lock);
  2066. /*
  2067. * Slurp in all works issued via this workqueue and
  2068. * process'em.
  2069. */
  2070. WARN_ON_ONCE(!list_empty(scheduled));
  2071. list_for_each_entry_safe(work, n, &pool->worklist, entry) {
  2072. if (get_work_pwq(work) == pwq) {
  2073. if (first)
  2074. pool->watchdog_ts = jiffies;
  2075. move_linked_works(work, scheduled, &n);
  2076. }
  2077. first = false;
  2078. }
  2079. if (!list_empty(scheduled)) {
  2080. process_scheduled_works(rescuer);
  2081. /*
  2082. * The above execution of rescued work items could
  2083. * have created more to rescue through
  2084. * pwq_activate_first_delayed() or chained
  2085. * queueing. Let's put @pwq back on mayday list so
  2086. * that such back-to-back work items, which may be
  2087. * being used to relieve memory pressure, don't
  2088. * incur MAYDAY_INTERVAL delay inbetween.
  2089. */
  2090. if (need_to_create_worker(pool)) {
  2091. spin_lock(&wq_mayday_lock);
  2092. /*
  2093. * Queue iff we aren't racing destruction
  2094. * and somebody else hasn't queued it already.
  2095. */
  2096. if (wq->rescuer && list_empty(&pwq->mayday_node)) {
  2097. get_pwq(pwq);
  2098. list_add_tail(&pwq->mayday_node, &wq->maydays);
  2099. }
  2100. spin_unlock(&wq_mayday_lock);
  2101. }
  2102. }
  2103. /*
  2104. * Put the reference grabbed by send_mayday(). @pool won't
  2105. * go away while we're still attached to it.
  2106. */
  2107. put_pwq(pwq);
  2108. /*
  2109. * Leave this pool. If need_more_worker() is %true, notify a
  2110. * regular worker; otherwise, we end up with 0 concurrency
  2111. * and stalling the execution.
  2112. */
  2113. if (need_more_worker(pool))
  2114. wake_up_worker(pool);
  2115. spin_unlock_irq(&pool->lock);
  2116. worker_detach_from_pool(rescuer);
  2117. spin_lock_irq(&wq_mayday_lock);
  2118. }
  2119. spin_unlock_irq(&wq_mayday_lock);
  2120. if (should_stop) {
  2121. __set_current_state(TASK_RUNNING);
  2122. set_pf_worker(false);
  2123. return 0;
  2124. }
  2125. /* rescuers should never participate in concurrency management */
  2126. WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
  2127. schedule();
  2128. goto repeat;
  2129. }
  2130. /**
  2131. * check_flush_dependency - check for flush dependency sanity
  2132. * @target_wq: workqueue being flushed
  2133. * @target_work: work item being flushed (NULL for workqueue flushes)
  2134. *
  2135. * %current is trying to flush the whole @target_wq or @target_work on it.
  2136. * If @target_wq doesn't have %WQ_MEM_RECLAIM, verify that %current is not
  2137. * reclaiming memory or running on a workqueue which doesn't have
  2138. * %WQ_MEM_RECLAIM as that can break forward-progress guarantee leading to
  2139. * a deadlock.
  2140. */
  2141. static void check_flush_dependency(struct workqueue_struct *target_wq,
  2142. struct work_struct *target_work)
  2143. {
  2144. work_func_t target_func = target_work ? target_work->func : NULL;
  2145. struct worker *worker;
  2146. if (target_wq->flags & WQ_MEM_RECLAIM)
  2147. return;
  2148. worker = current_wq_worker();
  2149. WARN_ONCE(current->flags & PF_MEMALLOC,
  2150. "workqueue: PF_MEMALLOC task %d(%s) is flushing !WQ_MEM_RECLAIM %s:%pf",
  2151. current->pid, current->comm, target_wq->name, target_func);
  2152. WARN_ONCE(worker && ((worker->current_pwq->wq->flags &
  2153. (WQ_MEM_RECLAIM | __WQ_LEGACY)) == WQ_MEM_RECLAIM),
  2154. "workqueue: WQ_MEM_RECLAIM %s:%pf is flushing !WQ_MEM_RECLAIM %s:%pf",
  2155. worker->current_pwq->wq->name, worker->current_func,
  2156. target_wq->name, target_func);
  2157. }
  2158. struct wq_barrier {
  2159. struct work_struct work;
  2160. struct completion done;
  2161. struct task_struct *task; /* purely informational */
  2162. };
  2163. static void wq_barrier_func(struct work_struct *work)
  2164. {
  2165. struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
  2166. complete(&barr->done);
  2167. }
  2168. /**
  2169. * insert_wq_barrier - insert a barrier work
  2170. * @pwq: pwq to insert barrier into
  2171. * @barr: wq_barrier to insert
  2172. * @target: target work to attach @barr to
  2173. * @worker: worker currently executing @target, NULL if @target is not executing
  2174. *
  2175. * @barr is linked to @target such that @barr is completed only after
  2176. * @target finishes execution. Please note that the ordering
  2177. * guarantee is observed only with respect to @target and on the local
  2178. * cpu.
  2179. *
  2180. * Currently, a queued barrier can't be canceled. This is because
  2181. * try_to_grab_pending() can't determine whether the work to be
  2182. * grabbed is at the head of the queue and thus can't clear LINKED
  2183. * flag of the previous work while there must be a valid next work
  2184. * after a work with LINKED flag set.
  2185. *
  2186. * Note that when @worker is non-NULL, @target may be modified
  2187. * underneath us, so we can't reliably determine pwq from @target.
  2188. *
  2189. * CONTEXT:
  2190. * spin_lock_irq(pool->lock).
  2191. */
  2192. static void insert_wq_barrier(struct pool_workqueue *pwq,
  2193. struct wq_barrier *barr,
  2194. struct work_struct *target, struct worker *worker)
  2195. {
  2196. struct list_head *head;
  2197. unsigned int linked = 0;
  2198. /*
  2199. * debugobject calls are safe here even with pool->lock locked
  2200. * as we know for sure that this will not trigger any of the
  2201. * checks and call back into the fixup functions where we
  2202. * might deadlock.
  2203. */
  2204. INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
  2205. __set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
  2206. init_completion_map(&barr->done, &target->lockdep_map);
  2207. barr->task = current;
  2208. /*
  2209. * If @target is currently being executed, schedule the
  2210. * barrier to the worker; otherwise, put it after @target.
  2211. */
  2212. if (worker)
  2213. head = worker->scheduled.next;
  2214. else {
  2215. unsigned long *bits = work_data_bits(target);
  2216. head = target->entry.next;
  2217. /* there can already be other linked works, inherit and set */
  2218. linked = *bits & WORK_STRUCT_LINKED;
  2219. __set_bit(WORK_STRUCT_LINKED_BIT, bits);
  2220. }
  2221. debug_work_activate(&barr->work);
  2222. insert_work(pwq, &barr->work, head,
  2223. work_color_to_flags(WORK_NO_COLOR) | linked);
  2224. }
  2225. /**
  2226. * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
  2227. * @wq: workqueue being flushed
  2228. * @flush_color: new flush color, < 0 for no-op
  2229. * @work_color: new work color, < 0 for no-op
  2230. *
  2231. * Prepare pwqs for workqueue flushing.
  2232. *
  2233. * If @flush_color is non-negative, flush_color on all pwqs should be
  2234. * -1. If no pwq has in-flight commands at the specified color, all
  2235. * pwq->flush_color's stay at -1 and %false is returned. If any pwq
  2236. * has in flight commands, its pwq->flush_color is set to
  2237. * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
  2238. * wakeup logic is armed and %true is returned.
  2239. *
  2240. * The caller should have initialized @wq->first_flusher prior to
  2241. * calling this function with non-negative @flush_color. If
  2242. * @flush_color is negative, no flush color update is done and %false
  2243. * is returned.
  2244. *
  2245. * If @work_color is non-negative, all pwqs should have the same
  2246. * work_color which is previous to @work_color and all will be
  2247. * advanced to @work_color.
  2248. *
  2249. * CONTEXT:
  2250. * mutex_lock(wq->mutex).
  2251. *
  2252. * Return:
  2253. * %true if @flush_color >= 0 and there's something to flush. %false
  2254. * otherwise.
  2255. */
  2256. static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
  2257. int flush_color, int work_color)
  2258. {
  2259. bool wait = false;
  2260. struct pool_workqueue *pwq;
  2261. if (flush_color >= 0) {
  2262. WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
  2263. atomic_set(&wq->nr_pwqs_to_flush, 1);
  2264. }
  2265. for_each_pwq(pwq, wq) {
  2266. struct worker_pool *pool = pwq->pool;
  2267. spin_lock_irq(&pool->lock);
  2268. if (flush_color >= 0) {
  2269. WARN_ON_ONCE(pwq->flush_color != -1);
  2270. if (pwq->nr_in_flight[flush_color]) {
  2271. pwq->flush_color = flush_color;
  2272. atomic_inc(&wq->nr_pwqs_to_flush);
  2273. wait = true;
  2274. }
  2275. }
  2276. if (work_color >= 0) {
  2277. WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
  2278. pwq->work_color = work_color;
  2279. }
  2280. spin_unlock_irq(&pool->lock);
  2281. }
  2282. if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
  2283. complete(&wq->first_flusher->done);
  2284. return wait;
  2285. }
  2286. /**
  2287. * flush_workqueue - ensure that any scheduled work has run to completion.
  2288. * @wq: workqueue to flush
  2289. *
  2290. * This function sleeps until all work items which were queued on entry
  2291. * have finished execution, but it is not livelocked by new incoming ones.
  2292. */
  2293. void flush_workqueue(struct workqueue_struct *wq)
  2294. {
  2295. struct wq_flusher this_flusher = {
  2296. .list = LIST_HEAD_INIT(this_flusher.list),
  2297. .flush_color = -1,
  2298. .done = COMPLETION_INITIALIZER_ONSTACK_MAP(this_flusher.done, wq->lockdep_map),
  2299. };
  2300. int next_color;
  2301. if (WARN_ON(!wq_online))
  2302. return;
  2303. lock_map_acquire(&wq->lockdep_map);
  2304. lock_map_release(&wq->lockdep_map);
  2305. mutex_lock(&wq->mutex);
  2306. /*
  2307. * Start-to-wait phase
  2308. */
  2309. next_color = work_next_color(wq->work_color);
  2310. if (next_color != wq->flush_color) {
  2311. /*
  2312. * Color space is not full. The current work_color
  2313. * becomes our flush_color and work_color is advanced
  2314. * by one.
  2315. */
  2316. WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
  2317. this_flusher.flush_color = wq->work_color;
  2318. wq->work_color = next_color;
  2319. if (!wq->first_flusher) {
  2320. /* no flush in progress, become the first flusher */
  2321. WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
  2322. wq->first_flusher = &this_flusher;
  2323. if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
  2324. wq->work_color)) {
  2325. /* nothing to flush, done */
  2326. wq->flush_color = next_color;
  2327. wq->first_flusher = NULL;
  2328. goto out_unlock;
  2329. }
  2330. } else {
  2331. /* wait in queue */
  2332. WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
  2333. list_add_tail(&this_flusher.list, &wq->flusher_queue);
  2334. flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
  2335. }
  2336. } else {
  2337. /*
  2338. * Oops, color space is full, wait on overflow queue.
  2339. * The next flush completion will assign us
  2340. * flush_color and transfer to flusher_queue.
  2341. */
  2342. list_add_tail(&this_flusher.list, &wq->flusher_overflow);
  2343. }
  2344. check_flush_dependency(wq, NULL);
  2345. mutex_unlock(&wq->mutex);
  2346. wait_for_completion(&this_flusher.done);
  2347. /*
  2348. * Wake-up-and-cascade phase
  2349. *
  2350. * First flushers are responsible for cascading flushes and
  2351. * handling overflow. Non-first flushers can simply return.
  2352. */
  2353. if (wq->first_flusher != &this_flusher)
  2354. return;
  2355. mutex_lock(&wq->mutex);
  2356. /* we might have raced, check again with mutex held */
  2357. if (wq->first_flusher != &this_flusher)
  2358. goto out_unlock;
  2359. wq->first_flusher = NULL;
  2360. WARN_ON_ONCE(!list_empty(&this_flusher.list));
  2361. WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
  2362. while (true) {
  2363. struct wq_flusher *next, *tmp;
  2364. /* complete all the flushers sharing the current flush color */
  2365. list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
  2366. if (next->flush_color != wq->flush_color)
  2367. break;
  2368. list_del_init(&next->list);
  2369. complete(&next->done);
  2370. }
  2371. WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
  2372. wq->flush_color != work_next_color(wq->work_color));
  2373. /* this flush_color is finished, advance by one */
  2374. wq->flush_color = work_next_color(wq->flush_color);
  2375. /* one color has been freed, handle overflow queue */
  2376. if (!list_empty(&wq->flusher_overflow)) {
  2377. /*
  2378. * Assign the same color to all overflowed
  2379. * flushers, advance work_color and append to
  2380. * flusher_queue. This is the start-to-wait
  2381. * phase for these overflowed flushers.
  2382. */
  2383. list_for_each_entry(tmp, &wq->flusher_overflow, list)
  2384. tmp->flush_color = wq->work_color;
  2385. wq->work_color = work_next_color(wq->work_color);
  2386. list_splice_tail_init(&wq->flusher_overflow,
  2387. &wq->flusher_queue);
  2388. flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
  2389. }
  2390. if (list_empty(&wq->flusher_queue)) {
  2391. WARN_ON_ONCE(wq->flush_color != wq->work_color);
  2392. break;
  2393. }
  2394. /*
  2395. * Need to flush more colors. Make the next flusher
  2396. * the new first flusher and arm pwqs.
  2397. */
  2398. WARN_ON_ONCE(wq->flush_color == wq->work_color);
  2399. WARN_ON_ONCE(wq->flush_color != next->flush_color);
  2400. list_del_init(&next->list);
  2401. wq->first_flusher = next;
  2402. if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
  2403. break;
  2404. /*
  2405. * Meh... this color is already done, clear first
  2406. * flusher and repeat cascading.
  2407. */
  2408. wq->first_flusher = NULL;
  2409. }
  2410. out_unlock:
  2411. mutex_unlock(&wq->mutex);
  2412. }
  2413. EXPORT_SYMBOL(flush_workqueue);
  2414. /**
  2415. * drain_workqueue - drain a workqueue
  2416. * @wq: workqueue to drain
  2417. *
  2418. * Wait until the workqueue becomes empty. While draining is in progress,
  2419. * only chain queueing is allowed. IOW, only currently pending or running
  2420. * work items on @wq can queue further work items on it. @wq is flushed
  2421. * repeatedly until it becomes empty. The number of flushing is determined
  2422. * by the depth of chaining and should be relatively short. Whine if it
  2423. * takes too long.
  2424. */
  2425. void drain_workqueue(struct workqueue_struct *wq)
  2426. {
  2427. unsigned int flush_cnt = 0;
  2428. struct pool_workqueue *pwq;
  2429. /*
  2430. * __queue_work() needs to test whether there are drainers, is much
  2431. * hotter than drain_workqueue() and already looks at @wq->flags.
  2432. * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
  2433. */
  2434. mutex_lock(&wq->mutex);
  2435. if (!wq->nr_drainers++)
  2436. wq->flags |= __WQ_DRAINING;
  2437. mutex_unlock(&wq->mutex);
  2438. reflush:
  2439. flush_workqueue(wq);
  2440. mutex_lock(&wq->mutex);
  2441. for_each_pwq(pwq, wq) {
  2442. bool drained;
  2443. spin_lock_irq(&pwq->pool->lock);
  2444. drained = !pwq->nr_active && list_empty(&pwq->delayed_works);
  2445. spin_unlock_irq(&pwq->pool->lock);
  2446. if (drained)
  2447. continue;
  2448. if (++flush_cnt == 10 ||
  2449. (flush_cnt % 100 == 0 && flush_cnt <= 1000))
  2450. pr_warn("workqueue %s: drain_workqueue() isn't complete after %u tries\n",
  2451. wq->name, flush_cnt);
  2452. mutex_unlock(&wq->mutex);
  2453. goto reflush;
  2454. }
  2455. if (!--wq->nr_drainers)
  2456. wq->flags &= ~__WQ_DRAINING;
  2457. mutex_unlock(&wq->mutex);
  2458. }
  2459. EXPORT_SYMBOL_GPL(drain_workqueue);
  2460. static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr,
  2461. bool from_cancel)
  2462. {
  2463. struct worker *worker = NULL;
  2464. struct worker_pool *pool;
  2465. struct pool_workqueue *pwq;
  2466. might_sleep();
  2467. local_irq_disable();
  2468. pool = get_work_pool(work);
  2469. if (!pool) {
  2470. local_irq_enable();
  2471. return false;
  2472. }
  2473. spin_lock(&pool->lock);
  2474. /* see the comment in try_to_grab_pending() with the same code */
  2475. pwq = get_work_pwq(work);
  2476. if (pwq) {
  2477. if (unlikely(pwq->pool != pool))
  2478. goto already_gone;
  2479. } else {
  2480. worker = find_worker_executing_work(pool, work);
  2481. if (!worker)
  2482. goto already_gone;
  2483. pwq = worker->current_pwq;
  2484. }
  2485. check_flush_dependency(pwq->wq, work);
  2486. insert_wq_barrier(pwq, barr, work, worker);
  2487. spin_unlock_irq(&pool->lock);
  2488. /*
  2489. * Force a lock recursion deadlock when using flush_work() inside a
  2490. * single-threaded or rescuer equipped workqueue.
  2491. *
  2492. * For single threaded workqueues the deadlock happens when the work
  2493. * is after the work issuing the flush_work(). For rescuer equipped
  2494. * workqueues the deadlock happens when the rescuer stalls, blocking
  2495. * forward progress.
  2496. */
  2497. if (!from_cancel &&
  2498. (pwq->wq->saved_max_active == 1 || pwq->wq->rescuer)) {
  2499. lock_map_acquire(&pwq->wq->lockdep_map);
  2500. lock_map_release(&pwq->wq->lockdep_map);
  2501. }
  2502. return true;
  2503. already_gone:
  2504. spin_unlock_irq(&pool->lock);
  2505. return false;
  2506. }
  2507. static bool __flush_work(struct work_struct *work, bool from_cancel)
  2508. {
  2509. struct wq_barrier barr;
  2510. if (WARN_ON(!wq_online))
  2511. return false;
  2512. if (WARN_ON(!work->func))
  2513. return false;
  2514. if (!from_cancel) {
  2515. lock_map_acquire(&work->lockdep_map);
  2516. lock_map_release(&work->lockdep_map);
  2517. }
  2518. if (start_flush_work(work, &barr, from_cancel)) {
  2519. wait_for_completion(&barr.done);
  2520. destroy_work_on_stack(&barr.work);
  2521. return true;
  2522. } else {
  2523. return false;
  2524. }
  2525. }
  2526. /**
  2527. * flush_work - wait for a work to finish executing the last queueing instance
  2528. * @work: the work to flush
  2529. *
  2530. * Wait until @work has finished execution. @work is guaranteed to be idle
  2531. * on return if it hasn't been requeued since flush started.
  2532. *
  2533. * Return:
  2534. * %true if flush_work() waited for the work to finish execution,
  2535. * %false if it was already idle.
  2536. */
  2537. bool flush_work(struct work_struct *work)
  2538. {
  2539. return __flush_work(work, false);
  2540. }
  2541. EXPORT_SYMBOL_GPL(flush_work);
  2542. struct cwt_wait {
  2543. wait_queue_entry_t wait;
  2544. struct work_struct *work;
  2545. };
  2546. static int cwt_wakefn(wait_queue_entry_t *wait, unsigned mode, int sync, void *key)
  2547. {
  2548. struct cwt_wait *cwait = container_of(wait, struct cwt_wait, wait);
  2549. if (cwait->work != key)
  2550. return 0;
  2551. return autoremove_wake_function(wait, mode, sync, key);
  2552. }
  2553. static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
  2554. {
  2555. static DECLARE_WAIT_QUEUE_HEAD(cancel_waitq);
  2556. unsigned long flags;
  2557. int ret;
  2558. do {
  2559. ret = try_to_grab_pending(work, is_dwork, &flags);
  2560. /*
  2561. * If someone else is already canceling, wait for it to
  2562. * finish. flush_work() doesn't work for PREEMPT_NONE
  2563. * because we may get scheduled between @work's completion
  2564. * and the other canceling task resuming and clearing
  2565. * CANCELING - flush_work() will return false immediately
  2566. * as @work is no longer busy, try_to_grab_pending() will
  2567. * return -ENOENT as @work is still being canceled and the
  2568. * other canceling task won't be able to clear CANCELING as
  2569. * we're hogging the CPU.
  2570. *
  2571. * Let's wait for completion using a waitqueue. As this
  2572. * may lead to the thundering herd problem, use a custom
  2573. * wake function which matches @work along with exclusive
  2574. * wait and wakeup.
  2575. */
  2576. if (unlikely(ret == -ENOENT)) {
  2577. struct cwt_wait cwait;
  2578. init_wait(&cwait.wait);
  2579. cwait.wait.func = cwt_wakefn;
  2580. cwait.work = work;
  2581. prepare_to_wait_exclusive(&cancel_waitq, &cwait.wait,
  2582. TASK_UNINTERRUPTIBLE);
  2583. if (work_is_canceling(work))
  2584. schedule();
  2585. finish_wait(&cancel_waitq, &cwait.wait);
  2586. }
  2587. } while (unlikely(ret < 0));
  2588. /* tell other tasks trying to grab @work to back off */
  2589. mark_work_canceling(work);
  2590. local_irq_restore(flags);
  2591. /*
  2592. * This allows canceling during early boot. We know that @work
  2593. * isn't executing.
  2594. */
  2595. if (wq_online)
  2596. __flush_work(work, true);
  2597. clear_work_data(work);
  2598. /*
  2599. * Paired with prepare_to_wait() above so that either
  2600. * waitqueue_active() is visible here or !work_is_canceling() is
  2601. * visible there.
  2602. */
  2603. smp_mb();
  2604. if (waitqueue_active(&cancel_waitq))
  2605. __wake_up(&cancel_waitq, TASK_NORMAL, 1, work);
  2606. return ret;
  2607. }
  2608. /**
  2609. * cancel_work_sync - cancel a work and wait for it to finish
  2610. * @work: the work to cancel
  2611. *
  2612. * Cancel @work and wait for its execution to finish. This function
  2613. * can be used even if the work re-queues itself or migrates to
  2614. * another workqueue. On return from this function, @work is
  2615. * guaranteed to be not pending or executing on any CPU.
  2616. *
  2617. * cancel_work_sync(&delayed_work->work) must not be used for
  2618. * delayed_work's. Use cancel_delayed_work_sync() instead.
  2619. *
  2620. * The caller must ensure that the workqueue on which @work was last
  2621. * queued can't be destroyed before this function returns.
  2622. *
  2623. * Return:
  2624. * %true if @work was pending, %false otherwise.
  2625. */
  2626. bool cancel_work_sync(struct work_struct *work)
  2627. {
  2628. return __cancel_work_timer(work, false);
  2629. }
  2630. EXPORT_SYMBOL_GPL(cancel_work_sync);
  2631. /**
  2632. * flush_delayed_work - wait for a dwork to finish executing the last queueing
  2633. * @dwork: the delayed work to flush
  2634. *
  2635. * Delayed timer is cancelled and the pending work is queued for
  2636. * immediate execution. Like flush_work(), this function only
  2637. * considers the last queueing instance of @dwork.
  2638. *
  2639. * Return:
  2640. * %true if flush_work() waited for the work to finish execution,
  2641. * %false if it was already idle.
  2642. */
  2643. bool flush_delayed_work(struct delayed_work *dwork)
  2644. {
  2645. local_irq_disable();
  2646. if (del_timer_sync(&dwork->timer))
  2647. __queue_work(dwork->cpu, dwork->wq, &dwork->work);
  2648. local_irq_enable();
  2649. return flush_work(&dwork->work);
  2650. }
  2651. EXPORT_SYMBOL(flush_delayed_work);
  2652. /**
  2653. * flush_rcu_work - wait for a rwork to finish executing the last queueing
  2654. * @rwork: the rcu work to flush
  2655. *
  2656. * Return:
  2657. * %true if flush_rcu_work() waited for the work to finish execution,
  2658. * %false if it was already idle.
  2659. */
  2660. bool flush_rcu_work(struct rcu_work *rwork)
  2661. {
  2662. if (test_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&rwork->work))) {
  2663. rcu_barrier();
  2664. flush_work(&rwork->work);
  2665. return true;
  2666. } else {
  2667. return flush_work(&rwork->work);
  2668. }
  2669. }
  2670. EXPORT_SYMBOL(flush_rcu_work);
  2671. static bool __cancel_work(struct work_struct *work, bool is_dwork)
  2672. {
  2673. unsigned long flags;
  2674. int ret;
  2675. do {
  2676. ret = try_to_grab_pending(work, is_dwork, &flags);
  2677. } while (unlikely(ret == -EAGAIN));
  2678. if (unlikely(ret < 0))
  2679. return false;
  2680. set_work_pool_and_clear_pending(work, get_work_pool_id(work));
  2681. local_irq_restore(flags);
  2682. return ret;
  2683. }
  2684. /**
  2685. * cancel_delayed_work - cancel a delayed work
  2686. * @dwork: delayed_work to cancel
  2687. *
  2688. * Kill off a pending delayed_work.
  2689. *
  2690. * Return: %true if @dwork was pending and canceled; %false if it wasn't
  2691. * pending.
  2692. *
  2693. * Note:
  2694. * The work callback function may still be running on return, unless
  2695. * it returns %true and the work doesn't re-arm itself. Explicitly flush or
  2696. * use cancel_delayed_work_sync() to wait on it.
  2697. *
  2698. * This function is safe to call from any context including IRQ handler.
  2699. */
  2700. bool cancel_delayed_work(struct delayed_work *dwork)
  2701. {
  2702. return __cancel_work(&dwork->work, true);
  2703. }
  2704. EXPORT_SYMBOL(cancel_delayed_work);
  2705. /**
  2706. * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
  2707. * @dwork: the delayed work cancel
  2708. *
  2709. * This is cancel_work_sync() for delayed works.
  2710. *
  2711. * Return:
  2712. * %true if @dwork was pending, %false otherwise.
  2713. */
  2714. bool cancel_delayed_work_sync(struct delayed_work *dwork)
  2715. {
  2716. return __cancel_work_timer(&dwork->work, true);
  2717. }
  2718. EXPORT_SYMBOL(cancel_delayed_work_sync);
  2719. /**
  2720. * schedule_on_each_cpu - execute a function synchronously on each online CPU
  2721. * @func: the function to call
  2722. *
  2723. * schedule_on_each_cpu() executes @func on each online CPU using the
  2724. * system workqueue and blocks until all CPUs have completed.
  2725. * schedule_on_each_cpu() is very slow.
  2726. *
  2727. * Return:
  2728. * 0 on success, -errno on failure.
  2729. */
  2730. int schedule_on_each_cpu(work_func_t func)
  2731. {
  2732. int cpu;
  2733. struct work_struct __percpu *works;
  2734. works = alloc_percpu(struct work_struct);
  2735. if (!works)
  2736. return -ENOMEM;
  2737. get_online_cpus();
  2738. for_each_online_cpu(cpu) {
  2739. struct work_struct *work = per_cpu_ptr(works, cpu);
  2740. INIT_WORK(work, func);
  2741. schedule_work_on(cpu, work);
  2742. }
  2743. for_each_online_cpu(cpu)
  2744. flush_work(per_cpu_ptr(works, cpu));
  2745. put_online_cpus();
  2746. free_percpu(works);
  2747. return 0;
  2748. }
  2749. /**
  2750. * execute_in_process_context - reliably execute the routine with user context
  2751. * @fn: the function to execute
  2752. * @ew: guaranteed storage for the execute work structure (must
  2753. * be available when the work executes)
  2754. *
  2755. * Executes the function immediately if process context is available,
  2756. * otherwise schedules the function for delayed execution.
  2757. *
  2758. * Return: 0 - function was executed
  2759. * 1 - function was scheduled for execution
  2760. */
  2761. int execute_in_process_context(work_func_t fn, struct execute_work *ew)
  2762. {
  2763. if (!in_interrupt()) {
  2764. fn(&ew->work);
  2765. return 0;
  2766. }
  2767. INIT_WORK(&ew->work, fn);
  2768. schedule_work(&ew->work);
  2769. return 1;
  2770. }
  2771. EXPORT_SYMBOL_GPL(execute_in_process_context);
  2772. /**
  2773. * free_workqueue_attrs - free a workqueue_attrs
  2774. * @attrs: workqueue_attrs to free
  2775. *
  2776. * Undo alloc_workqueue_attrs().
  2777. */
  2778. void free_workqueue_attrs(struct workqueue_attrs *attrs)
  2779. {
  2780. if (attrs) {
  2781. free_cpumask_var(attrs->cpumask);
  2782. kfree(attrs);
  2783. }
  2784. }
  2785. /**
  2786. * alloc_workqueue_attrs - allocate a workqueue_attrs
  2787. * @gfp_mask: allocation mask to use
  2788. *
  2789. * Allocate a new workqueue_attrs, initialize with default settings and
  2790. * return it.
  2791. *
  2792. * Return: The allocated new workqueue_attr on success. %NULL on failure.
  2793. */
  2794. struct workqueue_attrs *alloc_workqueue_attrs(gfp_t gfp_mask)
  2795. {
  2796. struct workqueue_attrs *attrs;
  2797. attrs = kzalloc(sizeof(*attrs), gfp_mask);
  2798. if (!attrs)
  2799. goto fail;
  2800. if (!alloc_cpumask_var(&attrs->cpumask, gfp_mask))
  2801. goto fail;
  2802. cpumask_copy(attrs->cpumask, cpu_possible_mask);
  2803. return attrs;
  2804. fail:
  2805. free_workqueue_attrs(attrs);
  2806. return NULL;
  2807. }
  2808. static void copy_workqueue_attrs(struct workqueue_attrs *to,
  2809. const struct workqueue_attrs *from)
  2810. {
  2811. to->nice = from->nice;
  2812. cpumask_copy(to->cpumask, from->cpumask);
  2813. /*
  2814. * Unlike hash and equality test, this function doesn't ignore
  2815. * ->no_numa as it is used for both pool and wq attrs. Instead,
  2816. * get_unbound_pool() explicitly clears ->no_numa after copying.
  2817. */
  2818. to->no_numa = from->no_numa;
  2819. }
  2820. /* hash value of the content of @attr */
  2821. static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
  2822. {
  2823. u32 hash = 0;
  2824. hash = jhash_1word(attrs->nice, hash);
  2825. hash = jhash(cpumask_bits(attrs->cpumask),
  2826. BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
  2827. return hash;
  2828. }
  2829. /* content equality test */
  2830. static bool wqattrs_equal(const struct workqueue_attrs *a,
  2831. const struct workqueue_attrs *b)
  2832. {
  2833. if (a->nice != b->nice)
  2834. return false;
  2835. if (!cpumask_equal(a->cpumask, b->cpumask))
  2836. return false;
  2837. return true;
  2838. }
  2839. /**
  2840. * init_worker_pool - initialize a newly zalloc'd worker_pool
  2841. * @pool: worker_pool to initialize
  2842. *
  2843. * Initialize a newly zalloc'd @pool. It also allocates @pool->attrs.
  2844. *
  2845. * Return: 0 on success, -errno on failure. Even on failure, all fields
  2846. * inside @pool proper are initialized and put_unbound_pool() can be called
  2847. * on @pool safely to release it.
  2848. */
  2849. static int init_worker_pool(struct worker_pool *pool)
  2850. {
  2851. spin_lock_init(&pool->lock);
  2852. pool->id = -1;
  2853. pool->cpu = -1;
  2854. pool->node = NUMA_NO_NODE;
  2855. pool->flags |= POOL_DISASSOCIATED;
  2856. pool->watchdog_ts = jiffies;
  2857. INIT_LIST_HEAD(&pool->worklist);
  2858. INIT_LIST_HEAD(&pool->idle_list);
  2859. hash_init(pool->busy_hash);
  2860. timer_setup(&pool->idle_timer, idle_worker_timeout, TIMER_DEFERRABLE);
  2861. timer_setup(&pool->mayday_timer, pool_mayday_timeout, 0);
  2862. INIT_LIST_HEAD(&pool->workers);
  2863. ida_init(&pool->worker_ida);
  2864. INIT_HLIST_NODE(&pool->hash_node);
  2865. pool->refcnt = 1;
  2866. /* shouldn't fail above this point */
  2867. pool->attrs = alloc_workqueue_attrs(GFP_KERNEL);
  2868. if (!pool->attrs)
  2869. return -ENOMEM;
  2870. return 0;
  2871. }
  2872. static void rcu_free_wq(struct rcu_head *rcu)
  2873. {
  2874. struct workqueue_struct *wq =
  2875. container_of(rcu, struct workqueue_struct, rcu);
  2876. if (!(wq->flags & WQ_UNBOUND))
  2877. free_percpu(wq->cpu_pwqs);
  2878. else
  2879. free_workqueue_attrs(wq->unbound_attrs);
  2880. kfree(wq->rescuer);
  2881. kfree(wq);
  2882. }
  2883. static void rcu_free_pool(struct rcu_head *rcu)
  2884. {
  2885. struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
  2886. ida_destroy(&pool->worker_ida);
  2887. free_workqueue_attrs(pool->attrs);
  2888. kfree(pool);
  2889. }
  2890. /**
  2891. * put_unbound_pool - put a worker_pool
  2892. * @pool: worker_pool to put
  2893. *
  2894. * Put @pool. If its refcnt reaches zero, it gets destroyed in sched-RCU
  2895. * safe manner. get_unbound_pool() calls this function on its failure path
  2896. * and this function should be able to release pools which went through,
  2897. * successfully or not, init_worker_pool().
  2898. *
  2899. * Should be called with wq_pool_mutex held.
  2900. */
  2901. static void put_unbound_pool(struct worker_pool *pool)
  2902. {
  2903. DECLARE_COMPLETION_ONSTACK(detach_completion);
  2904. struct worker *worker;
  2905. lockdep_assert_held(&wq_pool_mutex);
  2906. if (--pool->refcnt)
  2907. return;
  2908. /* sanity checks */
  2909. if (WARN_ON(!(pool->cpu < 0)) ||
  2910. WARN_ON(!list_empty(&pool->worklist)))
  2911. return;
  2912. /* release id and unhash */
  2913. if (pool->id >= 0)
  2914. idr_remove(&worker_pool_idr, pool->id);
  2915. hash_del(&pool->hash_node);
  2916. /*
  2917. * Become the manager and destroy all workers. This prevents
  2918. * @pool's workers from blocking on attach_mutex. We're the last
  2919. * manager and @pool gets freed with the flag set.
  2920. */
  2921. spin_lock_irq(&pool->lock);
  2922. wait_event_lock_irq(wq_manager_wait,
  2923. !(pool->flags & POOL_MANAGER_ACTIVE), pool->lock);
  2924. pool->flags |= POOL_MANAGER_ACTIVE;
  2925. while ((worker = first_idle_worker(pool)))
  2926. destroy_worker(worker);
  2927. WARN_ON(pool->nr_workers || pool->nr_idle);
  2928. spin_unlock_irq(&pool->lock);
  2929. mutex_lock(&wq_pool_attach_mutex);
  2930. if (!list_empty(&pool->workers))
  2931. pool->detach_completion = &detach_completion;
  2932. mutex_unlock(&wq_pool_attach_mutex);
  2933. if (pool->detach_completion)
  2934. wait_for_completion(pool->detach_completion);
  2935. /* shut down the timers */
  2936. del_timer_sync(&pool->idle_timer);
  2937. del_timer_sync(&pool->mayday_timer);
  2938. /* sched-RCU protected to allow dereferences from get_work_pool() */
  2939. call_rcu_sched(&pool->rcu, rcu_free_pool);
  2940. }
  2941. /**
  2942. * get_unbound_pool - get a worker_pool with the specified attributes
  2943. * @attrs: the attributes of the worker_pool to get
  2944. *
  2945. * Obtain a worker_pool which has the same attributes as @attrs, bump the
  2946. * reference count and return it. If there already is a matching
  2947. * worker_pool, it will be used; otherwise, this function attempts to
  2948. * create a new one.
  2949. *
  2950. * Should be called with wq_pool_mutex held.
  2951. *
  2952. * Return: On success, a worker_pool with the same attributes as @attrs.
  2953. * On failure, %NULL.
  2954. */
  2955. static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
  2956. {
  2957. u32 hash = wqattrs_hash(attrs);
  2958. struct worker_pool *pool;
  2959. int node;
  2960. int target_node = NUMA_NO_NODE;
  2961. lockdep_assert_held(&wq_pool_mutex);
  2962. /* do we already have a matching pool? */
  2963. hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
  2964. if (wqattrs_equal(pool->attrs, attrs)) {
  2965. pool->refcnt++;
  2966. return pool;
  2967. }
  2968. }
  2969. /* if cpumask is contained inside a NUMA node, we belong to that node */
  2970. if (wq_numa_enabled) {
  2971. for_each_node(node) {
  2972. if (cpumask_subset(attrs->cpumask,
  2973. wq_numa_possible_cpumask[node])) {
  2974. target_node = node;
  2975. break;
  2976. }
  2977. }
  2978. }
  2979. /* nope, create a new one */
  2980. pool = kzalloc_node(sizeof(*pool), GFP_KERNEL, target_node);
  2981. if (!pool || init_worker_pool(pool) < 0)
  2982. goto fail;
  2983. lockdep_set_subclass(&pool->lock, 1); /* see put_pwq() */
  2984. copy_workqueue_attrs(pool->attrs, attrs);
  2985. pool->node = target_node;
  2986. /*
  2987. * no_numa isn't a worker_pool attribute, always clear it. See
  2988. * 'struct workqueue_attrs' comments for detail.
  2989. */
  2990. pool->attrs->no_numa = false;
  2991. if (worker_pool_assign_id(pool) < 0)
  2992. goto fail;
  2993. /* create and start the initial worker */
  2994. if (wq_online && !create_worker(pool))
  2995. goto fail;
  2996. /* install */
  2997. hash_add(unbound_pool_hash, &pool->hash_node, hash);
  2998. return pool;
  2999. fail:
  3000. if (pool)
  3001. put_unbound_pool(pool);
  3002. return NULL;
  3003. }
  3004. static void rcu_free_pwq(struct rcu_head *rcu)
  3005. {
  3006. kmem_cache_free(pwq_cache,
  3007. container_of(rcu, struct pool_workqueue, rcu));
  3008. }
  3009. /*
  3010. * Scheduled on system_wq by put_pwq() when an unbound pwq hits zero refcnt
  3011. * and needs to be destroyed.
  3012. */
  3013. static void pwq_unbound_release_workfn(struct work_struct *work)
  3014. {
  3015. struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
  3016. unbound_release_work);
  3017. struct workqueue_struct *wq = pwq->wq;
  3018. struct worker_pool *pool = pwq->pool;
  3019. bool is_last;
  3020. if (WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND)))
  3021. return;
  3022. mutex_lock(&wq->mutex);
  3023. list_del_rcu(&pwq->pwqs_node);
  3024. is_last = list_empty(&wq->pwqs);
  3025. mutex_unlock(&wq->mutex);
  3026. mutex_lock(&wq_pool_mutex);
  3027. put_unbound_pool(pool);
  3028. mutex_unlock(&wq_pool_mutex);
  3029. call_rcu_sched(&pwq->rcu, rcu_free_pwq);
  3030. /*
  3031. * If we're the last pwq going away, @wq is already dead and no one
  3032. * is gonna access it anymore. Schedule RCU free.
  3033. */
  3034. if (is_last)
  3035. call_rcu_sched(&wq->rcu, rcu_free_wq);
  3036. }
  3037. /**
  3038. * pwq_adjust_max_active - update a pwq's max_active to the current setting
  3039. * @pwq: target pool_workqueue
  3040. *
  3041. * If @pwq isn't freezing, set @pwq->max_active to the associated
  3042. * workqueue's saved_max_active and activate delayed work items
  3043. * accordingly. If @pwq is freezing, clear @pwq->max_active to zero.
  3044. */
  3045. static void pwq_adjust_max_active(struct pool_workqueue *pwq)
  3046. {
  3047. struct workqueue_struct *wq = pwq->wq;
  3048. bool freezable = wq->flags & WQ_FREEZABLE;
  3049. unsigned long flags;
  3050. /* for @wq->saved_max_active */
  3051. lockdep_assert_held(&wq->mutex);
  3052. /* fast exit for non-freezable wqs */
  3053. if (!freezable && pwq->max_active == wq->saved_max_active)
  3054. return;
  3055. /* this function can be called during early boot w/ irq disabled */
  3056. spin_lock_irqsave(&pwq->pool->lock, flags);
  3057. /*
  3058. * During [un]freezing, the caller is responsible for ensuring that
  3059. * this function is called at least once after @workqueue_freezing
  3060. * is updated and visible.
  3061. */
  3062. if (!freezable || !workqueue_freezing) {
  3063. bool kick = false;
  3064. pwq->max_active = wq->saved_max_active;
  3065. while (!list_empty(&pwq->delayed_works) &&
  3066. pwq->nr_active < pwq->max_active) {
  3067. pwq_activate_first_delayed(pwq);
  3068. kick = true;
  3069. }
  3070. /*
  3071. * Need to kick a worker after thawed or an unbound wq's
  3072. * max_active is bumped. In realtime scenarios, always kicking a
  3073. * worker will cause interference on the isolated cpu cores, so
  3074. * let's kick iff work items were activated.
  3075. */
  3076. if (kick)
  3077. wake_up_worker(pwq->pool);
  3078. } else {
  3079. pwq->max_active = 0;
  3080. }
  3081. spin_unlock_irqrestore(&pwq->pool->lock, flags);
  3082. }
  3083. /* initialize newly alloced @pwq which is associated with @wq and @pool */
  3084. static void init_pwq(struct pool_workqueue *pwq, struct workqueue_struct *wq,
  3085. struct worker_pool *pool)
  3086. {
  3087. BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
  3088. memset(pwq, 0, sizeof(*pwq));
  3089. pwq->pool = pool;
  3090. pwq->wq = wq;
  3091. pwq->flush_color = -1;
  3092. pwq->refcnt = 1;
  3093. INIT_LIST_HEAD(&pwq->delayed_works);
  3094. INIT_LIST_HEAD(&pwq->pwqs_node);
  3095. INIT_LIST_HEAD(&pwq->mayday_node);
  3096. INIT_WORK(&pwq->unbound_release_work, pwq_unbound_release_workfn);
  3097. }
  3098. /* sync @pwq with the current state of its associated wq and link it */
  3099. static void link_pwq(struct pool_workqueue *pwq)
  3100. {
  3101. struct workqueue_struct *wq = pwq->wq;
  3102. lockdep_assert_held(&wq->mutex);
  3103. /* may be called multiple times, ignore if already linked */
  3104. if (!list_empty(&pwq->pwqs_node))
  3105. return;
  3106. /* set the matching work_color */
  3107. pwq->work_color = wq->work_color;
  3108. /* sync max_active to the current setting */
  3109. pwq_adjust_max_active(pwq);
  3110. /* link in @pwq */
  3111. list_add_rcu(&pwq->pwqs_node, &wq->pwqs);
  3112. }
  3113. /* obtain a pool matching @attr and create a pwq associating the pool and @wq */
  3114. static struct pool_workqueue *alloc_unbound_pwq(struct workqueue_struct *wq,
  3115. const struct workqueue_attrs *attrs)
  3116. {
  3117. struct worker_pool *pool;
  3118. struct pool_workqueue *pwq;
  3119. lockdep_assert_held(&wq_pool_mutex);
  3120. pool = get_unbound_pool(attrs);
  3121. if (!pool)
  3122. return NULL;
  3123. pwq = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL, pool->node);
  3124. if (!pwq) {
  3125. put_unbound_pool(pool);
  3126. return NULL;
  3127. }
  3128. init_pwq(pwq, wq, pool);
  3129. return pwq;
  3130. }
  3131. /**
  3132. * wq_calc_node_cpumask - calculate a wq_attrs' cpumask for the specified node
  3133. * @attrs: the wq_attrs of the default pwq of the target workqueue
  3134. * @node: the target NUMA node
  3135. * @cpu_going_down: if >= 0, the CPU to consider as offline
  3136. * @cpumask: outarg, the resulting cpumask
  3137. *
  3138. * Calculate the cpumask a workqueue with @attrs should use on @node. If
  3139. * @cpu_going_down is >= 0, that cpu is considered offline during
  3140. * calculation. The result is stored in @cpumask.
  3141. *
  3142. * If NUMA affinity is not enabled, @attrs->cpumask is always used. If
  3143. * enabled and @node has online CPUs requested by @attrs, the returned
  3144. * cpumask is the intersection of the possible CPUs of @node and
  3145. * @attrs->cpumask.
  3146. *
  3147. * The caller is responsible for ensuring that the cpumask of @node stays
  3148. * stable.
  3149. *
  3150. * Return: %true if the resulting @cpumask is different from @attrs->cpumask,
  3151. * %false if equal.
  3152. */
  3153. static bool wq_calc_node_cpumask(const struct workqueue_attrs *attrs, int node,
  3154. int cpu_going_down, cpumask_t *cpumask)
  3155. {
  3156. if (!wq_numa_enabled || attrs->no_numa)
  3157. goto use_dfl;
  3158. /* does @node have any online CPUs @attrs wants? */
  3159. cpumask_and(cpumask, cpumask_of_node(node), attrs->cpumask);
  3160. if (cpu_going_down >= 0)
  3161. cpumask_clear_cpu(cpu_going_down, cpumask);
  3162. if (cpumask_empty(cpumask))
  3163. goto use_dfl;
  3164. /* yeap, return possible CPUs in @node that @attrs wants */
  3165. cpumask_and(cpumask, attrs->cpumask, wq_numa_possible_cpumask[node]);
  3166. if (cpumask_empty(cpumask)) {
  3167. pr_warn_once("WARNING: workqueue cpumask: online intersect > "
  3168. "possible intersect\n");
  3169. return false;
  3170. }
  3171. return !cpumask_equal(cpumask, attrs->cpumask);
  3172. use_dfl:
  3173. cpumask_copy(cpumask, attrs->cpumask);
  3174. return false;
  3175. }
  3176. /* install @pwq into @wq's numa_pwq_tbl[] for @node and return the old pwq */
  3177. static struct pool_workqueue *numa_pwq_tbl_install(struct workqueue_struct *wq,
  3178. int node,
  3179. struct pool_workqueue *pwq)
  3180. {
  3181. struct pool_workqueue *old_pwq;
  3182. lockdep_assert_held(&wq_pool_mutex);
  3183. lockdep_assert_held(&wq->mutex);
  3184. /* link_pwq() can handle duplicate calls */
  3185. link_pwq(pwq);
  3186. old_pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
  3187. rcu_assign_pointer(wq->numa_pwq_tbl[node], pwq);
  3188. return old_pwq;
  3189. }
  3190. /* context to store the prepared attrs & pwqs before applying */
  3191. struct apply_wqattrs_ctx {
  3192. struct workqueue_struct *wq; /* target workqueue */
  3193. struct workqueue_attrs *attrs; /* attrs to apply */
  3194. struct list_head list; /* queued for batching commit */
  3195. struct pool_workqueue *dfl_pwq;
  3196. struct pool_workqueue *pwq_tbl[];
  3197. };
  3198. /* free the resources after success or abort */
  3199. static void apply_wqattrs_cleanup(struct apply_wqattrs_ctx *ctx)
  3200. {
  3201. if (ctx) {
  3202. int node;
  3203. for_each_node(node)
  3204. put_pwq_unlocked(ctx->pwq_tbl[node]);
  3205. put_pwq_unlocked(ctx->dfl_pwq);
  3206. free_workqueue_attrs(ctx->attrs);
  3207. kfree(ctx);
  3208. }
  3209. }
  3210. /* allocate the attrs and pwqs for later installation */
  3211. static struct apply_wqattrs_ctx *
  3212. apply_wqattrs_prepare(struct workqueue_struct *wq,
  3213. const struct workqueue_attrs *attrs)
  3214. {
  3215. struct apply_wqattrs_ctx *ctx;
  3216. struct workqueue_attrs *new_attrs, *tmp_attrs;
  3217. int node;
  3218. lockdep_assert_held(&wq_pool_mutex);
  3219. ctx = kzalloc(struct_size(ctx, pwq_tbl, nr_node_ids), GFP_KERNEL);
  3220. new_attrs = alloc_workqueue_attrs(GFP_KERNEL);
  3221. tmp_attrs = alloc_workqueue_attrs(GFP_KERNEL);
  3222. if (!ctx || !new_attrs || !tmp_attrs)
  3223. goto out_free;
  3224. /*
  3225. * Calculate the attrs of the default pwq.
  3226. * If the user configured cpumask doesn't overlap with the
  3227. * wq_unbound_cpumask, we fallback to the wq_unbound_cpumask.
  3228. */
  3229. copy_workqueue_attrs(new_attrs, attrs);
  3230. cpumask_and(new_attrs->cpumask, new_attrs->cpumask, wq_unbound_cpumask);
  3231. if (unlikely(cpumask_empty(new_attrs->cpumask)))
  3232. cpumask_copy(new_attrs->cpumask, wq_unbound_cpumask);
  3233. /*
  3234. * We may create multiple pwqs with differing cpumasks. Make a
  3235. * copy of @new_attrs which will be modified and used to obtain
  3236. * pools.
  3237. */
  3238. copy_workqueue_attrs(tmp_attrs, new_attrs);
  3239. /*
  3240. * If something goes wrong during CPU up/down, we'll fall back to
  3241. * the default pwq covering whole @attrs->cpumask. Always create
  3242. * it even if we don't use it immediately.
  3243. */
  3244. ctx->dfl_pwq = alloc_unbound_pwq(wq, new_attrs);
  3245. if (!ctx->dfl_pwq)
  3246. goto out_free;
  3247. for_each_node(node) {
  3248. if (wq_calc_node_cpumask(new_attrs, node, -1, tmp_attrs->cpumask)) {
  3249. ctx->pwq_tbl[node] = alloc_unbound_pwq(wq, tmp_attrs);
  3250. if (!ctx->pwq_tbl[node])
  3251. goto out_free;
  3252. } else {
  3253. ctx->dfl_pwq->refcnt++;
  3254. ctx->pwq_tbl[node] = ctx->dfl_pwq;
  3255. }
  3256. }
  3257. /* save the user configured attrs and sanitize it. */
  3258. copy_workqueue_attrs(new_attrs, attrs);
  3259. cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask);
  3260. ctx->attrs = new_attrs;
  3261. ctx->wq = wq;
  3262. free_workqueue_attrs(tmp_attrs);
  3263. return ctx;
  3264. out_free:
  3265. free_workqueue_attrs(tmp_attrs);
  3266. free_workqueue_attrs(new_attrs);
  3267. apply_wqattrs_cleanup(ctx);
  3268. return NULL;
  3269. }
  3270. /* set attrs and install prepared pwqs, @ctx points to old pwqs on return */
  3271. static void apply_wqattrs_commit(struct apply_wqattrs_ctx *ctx)
  3272. {
  3273. int node;
  3274. /* all pwqs have been created successfully, let's install'em */
  3275. mutex_lock(&ctx->wq->mutex);
  3276. copy_workqueue_attrs(ctx->wq->unbound_attrs, ctx->attrs);
  3277. /* save the previous pwq and install the new one */
  3278. for_each_node(node)
  3279. ctx->pwq_tbl[node] = numa_pwq_tbl_install(ctx->wq, node,
  3280. ctx->pwq_tbl[node]);
  3281. /* @dfl_pwq might not have been used, ensure it's linked */
  3282. link_pwq(ctx->dfl_pwq);
  3283. swap(ctx->wq->dfl_pwq, ctx->dfl_pwq);
  3284. mutex_unlock(&ctx->wq->mutex);
  3285. }
  3286. static void apply_wqattrs_lock(void)
  3287. {
  3288. /* CPUs should stay stable across pwq creations and installations */
  3289. get_online_cpus();
  3290. mutex_lock(&wq_pool_mutex);
  3291. }
  3292. static void apply_wqattrs_unlock(void)
  3293. {
  3294. mutex_unlock(&wq_pool_mutex);
  3295. put_online_cpus();
  3296. }
  3297. static int apply_workqueue_attrs_locked(struct workqueue_struct *wq,
  3298. const struct workqueue_attrs *attrs)
  3299. {
  3300. struct apply_wqattrs_ctx *ctx;
  3301. /* only unbound workqueues can change attributes */
  3302. if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
  3303. return -EINVAL;
  3304. /* creating multiple pwqs breaks ordering guarantee */
  3305. if (!list_empty(&wq->pwqs)) {
  3306. if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
  3307. return -EINVAL;
  3308. wq->flags &= ~__WQ_ORDERED;
  3309. }
  3310. ctx = apply_wqattrs_prepare(wq, attrs);
  3311. if (!ctx)
  3312. return -ENOMEM;
  3313. /* the ctx has been prepared successfully, let's commit it */
  3314. apply_wqattrs_commit(ctx);
  3315. apply_wqattrs_cleanup(ctx);
  3316. return 0;
  3317. }
  3318. /**
  3319. * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
  3320. * @wq: the target workqueue
  3321. * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
  3322. *
  3323. * Apply @attrs to an unbound workqueue @wq. Unless disabled, on NUMA
  3324. * machines, this function maps a separate pwq to each NUMA node with
  3325. * possibles CPUs in @attrs->cpumask so that work items are affine to the
  3326. * NUMA node it was issued on. Older pwqs are released as in-flight work
  3327. * items finish. Note that a work item which repeatedly requeues itself
  3328. * back-to-back will stay on its current pwq.
  3329. *
  3330. * Performs GFP_KERNEL allocations.
  3331. *
  3332. * Return: 0 on success and -errno on failure.
  3333. */
  3334. int apply_workqueue_attrs(struct workqueue_struct *wq,
  3335. const struct workqueue_attrs *attrs)
  3336. {
  3337. int ret;
  3338. apply_wqattrs_lock();
  3339. ret = apply_workqueue_attrs_locked(wq, attrs);
  3340. apply_wqattrs_unlock();
  3341. return ret;
  3342. }
  3343. EXPORT_SYMBOL_GPL(apply_workqueue_attrs);
  3344. /**
  3345. * wq_update_unbound_numa - update NUMA affinity of a wq for CPU hot[un]plug
  3346. * @wq: the target workqueue
  3347. * @cpu: the CPU coming up or going down
  3348. * @online: whether @cpu is coming up or going down
  3349. *
  3350. * This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and
  3351. * %CPU_DOWN_FAILED. @cpu is being hot[un]plugged, update NUMA affinity of
  3352. * @wq accordingly.
  3353. *
  3354. * If NUMA affinity can't be adjusted due to memory allocation failure, it
  3355. * falls back to @wq->dfl_pwq which may not be optimal but is always
  3356. * correct.
  3357. *
  3358. * Note that when the last allowed CPU of a NUMA node goes offline for a
  3359. * workqueue with a cpumask spanning multiple nodes, the workers which were
  3360. * already executing the work items for the workqueue will lose their CPU
  3361. * affinity and may execute on any CPU. This is similar to how per-cpu
  3362. * workqueues behave on CPU_DOWN. If a workqueue user wants strict
  3363. * affinity, it's the user's responsibility to flush the work item from
  3364. * CPU_DOWN_PREPARE.
  3365. */
  3366. static void wq_update_unbound_numa(struct workqueue_struct *wq, int cpu,
  3367. bool online)
  3368. {
  3369. int node = cpu_to_node(cpu);
  3370. int cpu_off = online ? -1 : cpu;
  3371. struct pool_workqueue *old_pwq = NULL, *pwq;
  3372. struct workqueue_attrs *target_attrs;
  3373. cpumask_t *cpumask;
  3374. lockdep_assert_held(&wq_pool_mutex);
  3375. if (!wq_numa_enabled || !(wq->flags & WQ_UNBOUND) ||
  3376. wq->unbound_attrs->no_numa)
  3377. return;
  3378. /*
  3379. * We don't wanna alloc/free wq_attrs for each wq for each CPU.
  3380. * Let's use a preallocated one. The following buf is protected by
  3381. * CPU hotplug exclusion.
  3382. */
  3383. target_attrs = wq_update_unbound_numa_attrs_buf;
  3384. cpumask = target_attrs->cpumask;
  3385. copy_workqueue_attrs(target_attrs, wq->unbound_attrs);
  3386. pwq = unbound_pwq_by_node(wq, node);
  3387. /*
  3388. * Let's determine what needs to be done. If the target cpumask is
  3389. * different from the default pwq's, we need to compare it to @pwq's
  3390. * and create a new one if they don't match. If the target cpumask
  3391. * equals the default pwq's, the default pwq should be used.
  3392. */
  3393. if (wq_calc_node_cpumask(wq->dfl_pwq->pool->attrs, node, cpu_off, cpumask)) {
  3394. if (cpumask_equal(cpumask, pwq->pool->attrs->cpumask))
  3395. return;
  3396. } else {
  3397. goto use_dfl_pwq;
  3398. }
  3399. /* create a new pwq */
  3400. pwq = alloc_unbound_pwq(wq, target_attrs);
  3401. if (!pwq) {
  3402. pr_warn("workqueue: allocation failed while updating NUMA affinity of \"%s\"\n",
  3403. wq->name);
  3404. goto use_dfl_pwq;
  3405. }
  3406. /* Install the new pwq. */
  3407. mutex_lock(&wq->mutex);
  3408. old_pwq = numa_pwq_tbl_install(wq, node, pwq);
  3409. goto out_unlock;
  3410. use_dfl_pwq:
  3411. mutex_lock(&wq->mutex);
  3412. spin_lock_irq(&wq->dfl_pwq->pool->lock);
  3413. get_pwq(wq->dfl_pwq);
  3414. spin_unlock_irq(&wq->dfl_pwq->pool->lock);
  3415. old_pwq = numa_pwq_tbl_install(wq, node, wq->dfl_pwq);
  3416. out_unlock:
  3417. mutex_unlock(&wq->mutex);
  3418. put_pwq_unlocked(old_pwq);
  3419. }
  3420. static int alloc_and_link_pwqs(struct workqueue_struct *wq)
  3421. {
  3422. bool highpri = wq->flags & WQ_HIGHPRI;
  3423. int cpu, ret;
  3424. if (!(wq->flags & WQ_UNBOUND)) {
  3425. wq->cpu_pwqs = alloc_percpu(struct pool_workqueue);
  3426. if (!wq->cpu_pwqs)
  3427. return -ENOMEM;
  3428. for_each_possible_cpu(cpu) {
  3429. struct pool_workqueue *pwq =
  3430. per_cpu_ptr(wq->cpu_pwqs, cpu);
  3431. struct worker_pool *cpu_pools =
  3432. per_cpu(cpu_worker_pools, cpu);
  3433. init_pwq(pwq, wq, &cpu_pools[highpri]);
  3434. mutex_lock(&wq->mutex);
  3435. link_pwq(pwq);
  3436. mutex_unlock(&wq->mutex);
  3437. }
  3438. return 0;
  3439. } else if (wq->flags & __WQ_ORDERED) {
  3440. ret = apply_workqueue_attrs(wq, ordered_wq_attrs[highpri]);
  3441. /* there should only be single pwq for ordering guarantee */
  3442. WARN(!ret && (wq->pwqs.next != &wq->dfl_pwq->pwqs_node ||
  3443. wq->pwqs.prev != &wq->dfl_pwq->pwqs_node),
  3444. "ordering guarantee broken for workqueue %s\n", wq->name);
  3445. return ret;
  3446. } else {
  3447. return apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
  3448. }
  3449. }
  3450. static int wq_clamp_max_active(int max_active, unsigned int flags,
  3451. const char *name)
  3452. {
  3453. int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
  3454. if (max_active < 1 || max_active > lim)
  3455. pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
  3456. max_active, name, 1, lim);
  3457. return clamp_val(max_active, 1, lim);
  3458. }
  3459. /*
  3460. * Workqueues which may be used during memory reclaim should have a rescuer
  3461. * to guarantee forward progress.
  3462. */
  3463. static int init_rescuer(struct workqueue_struct *wq)
  3464. {
  3465. struct worker *rescuer;
  3466. int ret;
  3467. if (!(wq->flags & WQ_MEM_RECLAIM))
  3468. return 0;
  3469. rescuer = alloc_worker(NUMA_NO_NODE);
  3470. if (!rescuer)
  3471. return -ENOMEM;
  3472. rescuer->rescue_wq = wq;
  3473. rescuer->task = kthread_create(rescuer_thread, rescuer, "%s", wq->name);
  3474. ret = PTR_ERR_OR_ZERO(rescuer->task);
  3475. if (ret) {
  3476. kfree(rescuer);
  3477. return ret;
  3478. }
  3479. wq->rescuer = rescuer;
  3480. kthread_bind_mask(rescuer->task, cpu_possible_mask);
  3481. wake_up_process(rescuer->task);
  3482. return 0;
  3483. }
  3484. struct workqueue_struct *__alloc_workqueue_key(const char *fmt,
  3485. unsigned int flags,
  3486. int max_active,
  3487. struct lock_class_key *key,
  3488. const char *lock_name, ...)
  3489. {
  3490. size_t tbl_size = 0;
  3491. va_list args;
  3492. struct workqueue_struct *wq;
  3493. struct pool_workqueue *pwq;
  3494. /*
  3495. * Unbound && max_active == 1 used to imply ordered, which is no
  3496. * longer the case on NUMA machines due to per-node pools. While
  3497. * alloc_ordered_workqueue() is the right way to create an ordered
  3498. * workqueue, keep the previous behavior to avoid subtle breakages
  3499. * on NUMA.
  3500. */
  3501. if ((flags & WQ_UNBOUND) && max_active == 1)
  3502. flags |= __WQ_ORDERED;
  3503. /* see the comment above the definition of WQ_POWER_EFFICIENT */
  3504. if ((flags & WQ_POWER_EFFICIENT) && wq_power_efficient)
  3505. flags |= WQ_UNBOUND;
  3506. /* allocate wq and format name */
  3507. if (flags & WQ_UNBOUND)
  3508. tbl_size = nr_node_ids * sizeof(wq->numa_pwq_tbl[0]);
  3509. wq = kzalloc(sizeof(*wq) + tbl_size, GFP_KERNEL);
  3510. if (!wq)
  3511. return NULL;
  3512. if (flags & WQ_UNBOUND) {
  3513. wq->unbound_attrs = alloc_workqueue_attrs(GFP_KERNEL);
  3514. if (!wq->unbound_attrs)
  3515. goto err_free_wq;
  3516. }
  3517. va_start(args, lock_name);
  3518. vsnprintf(wq->name, sizeof(wq->name), fmt, args);
  3519. va_end(args);
  3520. max_active = max_active ?: WQ_DFL_ACTIVE;
  3521. max_active = wq_clamp_max_active(max_active, flags, wq->name);
  3522. /* init wq */
  3523. wq->flags = flags;
  3524. wq->saved_max_active = max_active;
  3525. mutex_init(&wq->mutex);
  3526. atomic_set(&wq->nr_pwqs_to_flush, 0);
  3527. INIT_LIST_HEAD(&wq->pwqs);
  3528. INIT_LIST_HEAD(&wq->flusher_queue);
  3529. INIT_LIST_HEAD(&wq->flusher_overflow);
  3530. INIT_LIST_HEAD(&wq->maydays);
  3531. lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
  3532. INIT_LIST_HEAD(&wq->list);
  3533. if (alloc_and_link_pwqs(wq) < 0)
  3534. goto err_free_wq;
  3535. if (wq_online && init_rescuer(wq) < 0)
  3536. goto err_destroy;
  3537. if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
  3538. goto err_destroy;
  3539. /*
  3540. * wq_pool_mutex protects global freeze state and workqueues list.
  3541. * Grab it, adjust max_active and add the new @wq to workqueues
  3542. * list.
  3543. */
  3544. mutex_lock(&wq_pool_mutex);
  3545. mutex_lock(&wq->mutex);
  3546. for_each_pwq(pwq, wq)
  3547. pwq_adjust_max_active(pwq);
  3548. mutex_unlock(&wq->mutex);
  3549. list_add_tail_rcu(&wq->list, &workqueues);
  3550. mutex_unlock(&wq_pool_mutex);
  3551. return wq;
  3552. err_free_wq:
  3553. free_workqueue_attrs(wq->unbound_attrs);
  3554. kfree(wq);
  3555. return NULL;
  3556. err_destroy:
  3557. destroy_workqueue(wq);
  3558. return NULL;
  3559. }
  3560. EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
  3561. /**
  3562. * destroy_workqueue - safely terminate a workqueue
  3563. * @wq: target workqueue
  3564. *
  3565. * Safely destroy a workqueue. All work currently pending will be done first.
  3566. */
  3567. void destroy_workqueue(struct workqueue_struct *wq)
  3568. {
  3569. struct pool_workqueue *pwq;
  3570. int node;
  3571. /*
  3572. * Remove it from sysfs first so that sanity check failure doesn't
  3573. * lead to sysfs name conflicts.
  3574. */
  3575. workqueue_sysfs_unregister(wq);
  3576. /* drain it before proceeding with destruction */
  3577. drain_workqueue(wq);
  3578. /* kill rescuer, if sanity checks fail, leave it w/o rescuer */
  3579. if (wq->rescuer) {
  3580. struct worker *rescuer = wq->rescuer;
  3581. /* this prevents new queueing */
  3582. spin_lock_irq(&wq_mayday_lock);
  3583. wq->rescuer = NULL;
  3584. spin_unlock_irq(&wq_mayday_lock);
  3585. /* rescuer will empty maydays list before exiting */
  3586. kthread_stop(rescuer->task);
  3587. kfree(rescuer);
  3588. }
  3589. /* sanity checks */
  3590. mutex_lock(&wq->mutex);
  3591. for_each_pwq(pwq, wq) {
  3592. int i;
  3593. for (i = 0; i < WORK_NR_COLORS; i++) {
  3594. if (WARN_ON(pwq->nr_in_flight[i])) {
  3595. mutex_unlock(&wq->mutex);
  3596. show_workqueue_state();
  3597. return;
  3598. }
  3599. }
  3600. if (WARN_ON((pwq != wq->dfl_pwq) && (pwq->refcnt > 1)) ||
  3601. WARN_ON(pwq->nr_active) ||
  3602. WARN_ON(!list_empty(&pwq->delayed_works))) {
  3603. mutex_unlock(&wq->mutex);
  3604. show_workqueue_state();
  3605. return;
  3606. }
  3607. }
  3608. mutex_unlock(&wq->mutex);
  3609. /*
  3610. * wq list is used to freeze wq, remove from list after
  3611. * flushing is complete in case freeze races us.
  3612. */
  3613. mutex_lock(&wq_pool_mutex);
  3614. list_del_rcu(&wq->list);
  3615. mutex_unlock(&wq_pool_mutex);
  3616. if (!(wq->flags & WQ_UNBOUND)) {
  3617. /*
  3618. * The base ref is never dropped on per-cpu pwqs. Directly
  3619. * schedule RCU free.
  3620. */
  3621. call_rcu_sched(&wq->rcu, rcu_free_wq);
  3622. } else {
  3623. /*
  3624. * We're the sole accessor of @wq at this point. Directly
  3625. * access numa_pwq_tbl[] and dfl_pwq to put the base refs.
  3626. * @wq will be freed when the last pwq is released.
  3627. */
  3628. for_each_node(node) {
  3629. pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
  3630. RCU_INIT_POINTER(wq->numa_pwq_tbl[node], NULL);
  3631. put_pwq_unlocked(pwq);
  3632. }
  3633. /*
  3634. * Put dfl_pwq. @wq may be freed any time after dfl_pwq is
  3635. * put. Don't access it afterwards.
  3636. */
  3637. pwq = wq->dfl_pwq;
  3638. wq->dfl_pwq = NULL;
  3639. put_pwq_unlocked(pwq);
  3640. }
  3641. }
  3642. EXPORT_SYMBOL_GPL(destroy_workqueue);
  3643. /**
  3644. * workqueue_set_max_active - adjust max_active of a workqueue
  3645. * @wq: target workqueue
  3646. * @max_active: new max_active value.
  3647. *
  3648. * Set max_active of @wq to @max_active.
  3649. *
  3650. * CONTEXT:
  3651. * Don't call from IRQ context.
  3652. */
  3653. void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
  3654. {
  3655. struct pool_workqueue *pwq;
  3656. /* disallow meddling with max_active for ordered workqueues */
  3657. if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
  3658. return;
  3659. max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
  3660. mutex_lock(&wq->mutex);
  3661. wq->flags &= ~__WQ_ORDERED;
  3662. wq->saved_max_active = max_active;
  3663. for_each_pwq(pwq, wq)
  3664. pwq_adjust_max_active(pwq);
  3665. mutex_unlock(&wq->mutex);
  3666. }
  3667. EXPORT_SYMBOL_GPL(workqueue_set_max_active);
  3668. /**
  3669. * current_work - retrieve %current task's work struct
  3670. *
  3671. * Determine if %current task is a workqueue worker and what it's working on.
  3672. * Useful to find out the context that the %current task is running in.
  3673. *
  3674. * Return: work struct if %current task is a workqueue worker, %NULL otherwise.
  3675. */
  3676. struct work_struct *current_work(void)
  3677. {
  3678. struct worker *worker = current_wq_worker();
  3679. return worker ? worker->current_work : NULL;
  3680. }
  3681. EXPORT_SYMBOL(current_work);
  3682. /**
  3683. * current_is_workqueue_rescuer - is %current workqueue rescuer?
  3684. *
  3685. * Determine whether %current is a workqueue rescuer. Can be used from
  3686. * work functions to determine whether it's being run off the rescuer task.
  3687. *
  3688. * Return: %true if %current is a workqueue rescuer. %false otherwise.
  3689. */
  3690. bool current_is_workqueue_rescuer(void)
  3691. {
  3692. struct worker *worker = current_wq_worker();
  3693. return worker && worker->rescue_wq;
  3694. }
  3695. /**
  3696. * workqueue_congested - test whether a workqueue is congested
  3697. * @cpu: CPU in question
  3698. * @wq: target workqueue
  3699. *
  3700. * Test whether @wq's cpu workqueue for @cpu is congested. There is
  3701. * no synchronization around this function and the test result is
  3702. * unreliable and only useful as advisory hints or for debugging.
  3703. *
  3704. * If @cpu is WORK_CPU_UNBOUND, the test is performed on the local CPU.
  3705. * Note that both per-cpu and unbound workqueues may be associated with
  3706. * multiple pool_workqueues which have separate congested states. A
  3707. * workqueue being congested on one CPU doesn't mean the workqueue is also
  3708. * contested on other CPUs / NUMA nodes.
  3709. *
  3710. * Return:
  3711. * %true if congested, %false otherwise.
  3712. */
  3713. bool workqueue_congested(int cpu, struct workqueue_struct *wq)
  3714. {
  3715. struct pool_workqueue *pwq;
  3716. bool ret;
  3717. rcu_read_lock_sched();
  3718. if (cpu == WORK_CPU_UNBOUND)
  3719. cpu = smp_processor_id();
  3720. if (!(wq->flags & WQ_UNBOUND))
  3721. pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
  3722. else
  3723. pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
  3724. ret = !list_empty(&pwq->delayed_works);
  3725. rcu_read_unlock_sched();
  3726. return ret;
  3727. }
  3728. EXPORT_SYMBOL_GPL(workqueue_congested);
  3729. /**
  3730. * work_busy - test whether a work is currently pending or running
  3731. * @work: the work to be tested
  3732. *
  3733. * Test whether @work is currently pending or running. There is no
  3734. * synchronization around this function and the test result is
  3735. * unreliable and only useful as advisory hints or for debugging.
  3736. *
  3737. * Return:
  3738. * OR'd bitmask of WORK_BUSY_* bits.
  3739. */
  3740. unsigned int work_busy(struct work_struct *work)
  3741. {
  3742. struct worker_pool *pool;
  3743. unsigned long flags;
  3744. unsigned int ret = 0;
  3745. if (work_pending(work))
  3746. ret |= WORK_BUSY_PENDING;
  3747. local_irq_save(flags);
  3748. pool = get_work_pool(work);
  3749. if (pool) {
  3750. spin_lock(&pool->lock);
  3751. if (find_worker_executing_work(pool, work))
  3752. ret |= WORK_BUSY_RUNNING;
  3753. spin_unlock(&pool->lock);
  3754. }
  3755. local_irq_restore(flags);
  3756. return ret;
  3757. }
  3758. EXPORT_SYMBOL_GPL(work_busy);
  3759. /**
  3760. * set_worker_desc - set description for the current work item
  3761. * @fmt: printf-style format string
  3762. * @...: arguments for the format string
  3763. *
  3764. * This function can be called by a running work function to describe what
  3765. * the work item is about. If the worker task gets dumped, this
  3766. * information will be printed out together to help debugging. The
  3767. * description can be at most WORKER_DESC_LEN including the trailing '\0'.
  3768. */
  3769. void set_worker_desc(const char *fmt, ...)
  3770. {
  3771. struct worker *worker = current_wq_worker();
  3772. va_list args;
  3773. if (worker) {
  3774. va_start(args, fmt);
  3775. vsnprintf(worker->desc, sizeof(worker->desc), fmt, args);
  3776. va_end(args);
  3777. }
  3778. }
  3779. EXPORT_SYMBOL_GPL(set_worker_desc);
  3780. /**
  3781. * print_worker_info - print out worker information and description
  3782. * @log_lvl: the log level to use when printing
  3783. * @task: target task
  3784. *
  3785. * If @task is a worker and currently executing a work item, print out the
  3786. * name of the workqueue being serviced and worker description set with
  3787. * set_worker_desc() by the currently executing work item.
  3788. *
  3789. * This function can be safely called on any task as long as the
  3790. * task_struct itself is accessible. While safe, this function isn't
  3791. * synchronized and may print out mixups or garbages of limited length.
  3792. */
  3793. void print_worker_info(const char *log_lvl, struct task_struct *task)
  3794. {
  3795. work_func_t *fn = NULL;
  3796. char name[WQ_NAME_LEN] = { };
  3797. char desc[WORKER_DESC_LEN] = { };
  3798. struct pool_workqueue *pwq = NULL;
  3799. struct workqueue_struct *wq = NULL;
  3800. struct worker *worker;
  3801. if (!(task->flags & PF_WQ_WORKER))
  3802. return;
  3803. /*
  3804. * This function is called without any synchronization and @task
  3805. * could be in any state. Be careful with dereferences.
  3806. */
  3807. worker = kthread_probe_data(task);
  3808. /*
  3809. * Carefully copy the associated workqueue's workfn, name and desc.
  3810. * Keep the original last '\0' in case the original is garbage.
  3811. */
  3812. probe_kernel_read(&fn, &worker->current_func, sizeof(fn));
  3813. probe_kernel_read(&pwq, &worker->current_pwq, sizeof(pwq));
  3814. probe_kernel_read(&wq, &pwq->wq, sizeof(wq));
  3815. probe_kernel_read(name, wq->name, sizeof(name) - 1);
  3816. probe_kernel_read(desc, worker->desc, sizeof(desc) - 1);
  3817. if (fn || name[0] || desc[0]) {
  3818. printk("%sWorkqueue: %s %pf", log_lvl, name, fn);
  3819. if (strcmp(name, desc))
  3820. pr_cont(" (%s)", desc);
  3821. pr_cont("\n");
  3822. }
  3823. }
  3824. static void pr_cont_pool_info(struct worker_pool *pool)
  3825. {
  3826. pr_cont(" cpus=%*pbl", nr_cpumask_bits, pool->attrs->cpumask);
  3827. if (pool->node != NUMA_NO_NODE)
  3828. pr_cont(" node=%d", pool->node);
  3829. pr_cont(" flags=0x%x nice=%d", pool->flags, pool->attrs->nice);
  3830. }
  3831. static void pr_cont_work(bool comma, struct work_struct *work)
  3832. {
  3833. if (work->func == wq_barrier_func) {
  3834. struct wq_barrier *barr;
  3835. barr = container_of(work, struct wq_barrier, work);
  3836. pr_cont("%s BAR(%d)", comma ? "," : "",
  3837. task_pid_nr(barr->task));
  3838. } else {
  3839. pr_cont("%s %pf", comma ? "," : "", work->func);
  3840. }
  3841. }
  3842. static void show_pwq(struct pool_workqueue *pwq)
  3843. {
  3844. struct worker_pool *pool = pwq->pool;
  3845. struct work_struct *work;
  3846. struct worker *worker;
  3847. bool has_in_flight = false, has_pending = false;
  3848. int bkt;
  3849. pr_info(" pwq %d:", pool->id);
  3850. pr_cont_pool_info(pool);
  3851. pr_cont(" active=%d/%d refcnt=%d%s\n",
  3852. pwq->nr_active, pwq->max_active, pwq->refcnt,
  3853. !list_empty(&pwq->mayday_node) ? " MAYDAY" : "");
  3854. hash_for_each(pool->busy_hash, bkt, worker, hentry) {
  3855. if (worker->current_pwq == pwq) {
  3856. has_in_flight = true;
  3857. break;
  3858. }
  3859. }
  3860. if (has_in_flight) {
  3861. bool comma = false;
  3862. pr_info(" in-flight:");
  3863. hash_for_each(pool->busy_hash, bkt, worker, hentry) {
  3864. if (worker->current_pwq != pwq)
  3865. continue;
  3866. pr_cont("%s %d%s:%pf", comma ? "," : "",
  3867. task_pid_nr(worker->task),
  3868. worker == pwq->wq->rescuer ? "(RESCUER)" : "",
  3869. worker->current_func);
  3870. list_for_each_entry(work, &worker->scheduled, entry)
  3871. pr_cont_work(false, work);
  3872. comma = true;
  3873. }
  3874. pr_cont("\n");
  3875. }
  3876. list_for_each_entry(work, &pool->worklist, entry) {
  3877. if (get_work_pwq(work) == pwq) {
  3878. has_pending = true;
  3879. break;
  3880. }
  3881. }
  3882. if (has_pending) {
  3883. bool comma = false;
  3884. pr_info(" pending:");
  3885. list_for_each_entry(work, &pool->worklist, entry) {
  3886. if (get_work_pwq(work) != pwq)
  3887. continue;
  3888. pr_cont_work(comma, work);
  3889. comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
  3890. }
  3891. pr_cont("\n");
  3892. }
  3893. if (!list_empty(&pwq->delayed_works)) {
  3894. bool comma = false;
  3895. pr_info(" delayed:");
  3896. list_for_each_entry(work, &pwq->delayed_works, entry) {
  3897. pr_cont_work(comma, work);
  3898. comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
  3899. }
  3900. pr_cont("\n");
  3901. }
  3902. }
  3903. /**
  3904. * show_workqueue_state - dump workqueue state
  3905. *
  3906. * Called from a sysrq handler or try_to_freeze_tasks() and prints out
  3907. * all busy workqueues and pools.
  3908. */
  3909. void show_workqueue_state(void)
  3910. {
  3911. struct workqueue_struct *wq;
  3912. struct worker_pool *pool;
  3913. unsigned long flags;
  3914. int pi;
  3915. rcu_read_lock_sched();
  3916. pr_info("Showing busy workqueues and worker pools:\n");
  3917. list_for_each_entry_rcu(wq, &workqueues, list) {
  3918. struct pool_workqueue *pwq;
  3919. bool idle = true;
  3920. for_each_pwq(pwq, wq) {
  3921. if (pwq->nr_active || !list_empty(&pwq->delayed_works)) {
  3922. idle = false;
  3923. break;
  3924. }
  3925. }
  3926. if (idle)
  3927. continue;
  3928. pr_info("workqueue %s: flags=0x%x\n", wq->name, wq->flags);
  3929. for_each_pwq(pwq, wq) {
  3930. spin_lock_irqsave(&pwq->pool->lock, flags);
  3931. if (pwq->nr_active || !list_empty(&pwq->delayed_works))
  3932. show_pwq(pwq);
  3933. spin_unlock_irqrestore(&pwq->pool->lock, flags);
  3934. /*
  3935. * We could be printing a lot from atomic context, e.g.
  3936. * sysrq-t -> show_workqueue_state(). Avoid triggering
  3937. * hard lockup.
  3938. */
  3939. touch_nmi_watchdog();
  3940. }
  3941. }
  3942. for_each_pool(pool, pi) {
  3943. struct worker *worker;
  3944. bool first = true;
  3945. spin_lock_irqsave(&pool->lock, flags);
  3946. if (pool->nr_workers == pool->nr_idle)
  3947. goto next_pool;
  3948. pr_info("pool %d:", pool->id);
  3949. pr_cont_pool_info(pool);
  3950. pr_cont(" hung=%us workers=%d",
  3951. jiffies_to_msecs(jiffies - pool->watchdog_ts) / 1000,
  3952. pool->nr_workers);
  3953. if (pool->manager)
  3954. pr_cont(" manager: %d",
  3955. task_pid_nr(pool->manager->task));
  3956. list_for_each_entry(worker, &pool->idle_list, entry) {
  3957. pr_cont(" %s%d", first ? "idle: " : "",
  3958. task_pid_nr(worker->task));
  3959. first = false;
  3960. }
  3961. pr_cont("\n");
  3962. next_pool:
  3963. spin_unlock_irqrestore(&pool->lock, flags);
  3964. /*
  3965. * We could be printing a lot from atomic context, e.g.
  3966. * sysrq-t -> show_workqueue_state(). Avoid triggering
  3967. * hard lockup.
  3968. */
  3969. touch_nmi_watchdog();
  3970. }
  3971. rcu_read_unlock_sched();
  3972. }
  3973. /* used to show worker information through /proc/PID/{comm,stat,status} */
  3974. void wq_worker_comm(char *buf, size_t size, struct task_struct *task)
  3975. {
  3976. int off;
  3977. /* always show the actual comm */
  3978. off = strscpy(buf, task->comm, size);
  3979. if (off < 0)
  3980. return;
  3981. /* stabilize PF_WQ_WORKER and worker pool association */
  3982. mutex_lock(&wq_pool_attach_mutex);
  3983. if (task->flags & PF_WQ_WORKER) {
  3984. struct worker *worker = kthread_data(task);
  3985. struct worker_pool *pool = worker->pool;
  3986. if (pool) {
  3987. spin_lock_irq(&pool->lock);
  3988. /*
  3989. * ->desc tracks information (wq name or
  3990. * set_worker_desc()) for the latest execution. If
  3991. * current, prepend '+', otherwise '-'.
  3992. */
  3993. if (worker->desc[0] != '\0') {
  3994. if (worker->current_work)
  3995. scnprintf(buf + off, size - off, "+%s",
  3996. worker->desc);
  3997. else
  3998. scnprintf(buf + off, size - off, "-%s",
  3999. worker->desc);
  4000. }
  4001. spin_unlock_irq(&pool->lock);
  4002. }
  4003. }
  4004. mutex_unlock(&wq_pool_attach_mutex);
  4005. }
  4006. #ifdef CONFIG_SMP
  4007. /*
  4008. * CPU hotplug.
  4009. *
  4010. * There are two challenges in supporting CPU hotplug. Firstly, there
  4011. * are a lot of assumptions on strong associations among work, pwq and
  4012. * pool which make migrating pending and scheduled works very
  4013. * difficult to implement without impacting hot paths. Secondly,
  4014. * worker pools serve mix of short, long and very long running works making
  4015. * blocked draining impractical.
  4016. *
  4017. * This is solved by allowing the pools to be disassociated from the CPU
  4018. * running as an unbound one and allowing it to be reattached later if the
  4019. * cpu comes back online.
  4020. */
  4021. static void unbind_workers(int cpu)
  4022. {
  4023. struct worker_pool *pool;
  4024. struct worker *worker;
  4025. for_each_cpu_worker_pool(pool, cpu) {
  4026. mutex_lock(&wq_pool_attach_mutex);
  4027. spin_lock_irq(&pool->lock);
  4028. /*
  4029. * We've blocked all attach/detach operations. Make all workers
  4030. * unbound and set DISASSOCIATED. Before this, all workers
  4031. * except for the ones which are still executing works from
  4032. * before the last CPU down must be on the cpu. After
  4033. * this, they may become diasporas.
  4034. */
  4035. for_each_pool_worker(worker, pool)
  4036. worker->flags |= WORKER_UNBOUND;
  4037. pool->flags |= POOL_DISASSOCIATED;
  4038. spin_unlock_irq(&pool->lock);
  4039. mutex_unlock(&wq_pool_attach_mutex);
  4040. /*
  4041. * Call schedule() so that we cross rq->lock and thus can
  4042. * guarantee sched callbacks see the %WORKER_UNBOUND flag.
  4043. * This is necessary as scheduler callbacks may be invoked
  4044. * from other cpus.
  4045. */
  4046. schedule();
  4047. /*
  4048. * Sched callbacks are disabled now. Zap nr_running.
  4049. * After this, nr_running stays zero and need_more_worker()
  4050. * and keep_working() are always true as long as the
  4051. * worklist is not empty. This pool now behaves as an
  4052. * unbound (in terms of concurrency management) pool which
  4053. * are served by workers tied to the pool.
  4054. */
  4055. atomic_set(&pool->nr_running, 0);
  4056. /*
  4057. * With concurrency management just turned off, a busy
  4058. * worker blocking could lead to lengthy stalls. Kick off
  4059. * unbound chain execution of currently pending work items.
  4060. */
  4061. spin_lock_irq(&pool->lock);
  4062. wake_up_worker(pool);
  4063. spin_unlock_irq(&pool->lock);
  4064. }
  4065. }
  4066. /**
  4067. * rebind_workers - rebind all workers of a pool to the associated CPU
  4068. * @pool: pool of interest
  4069. *
  4070. * @pool->cpu is coming online. Rebind all workers to the CPU.
  4071. */
  4072. static void rebind_workers(struct worker_pool *pool)
  4073. {
  4074. struct worker *worker;
  4075. lockdep_assert_held(&wq_pool_attach_mutex);
  4076. /*
  4077. * Restore CPU affinity of all workers. As all idle workers should
  4078. * be on the run-queue of the associated CPU before any local
  4079. * wake-ups for concurrency management happen, restore CPU affinity
  4080. * of all workers first and then clear UNBOUND. As we're called
  4081. * from CPU_ONLINE, the following shouldn't fail.
  4082. */
  4083. for_each_pool_worker(worker, pool)
  4084. WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
  4085. pool->attrs->cpumask) < 0);
  4086. spin_lock_irq(&pool->lock);
  4087. pool->flags &= ~POOL_DISASSOCIATED;
  4088. for_each_pool_worker(worker, pool) {
  4089. unsigned int worker_flags = worker->flags;
  4090. /*
  4091. * A bound idle worker should actually be on the runqueue
  4092. * of the associated CPU for local wake-ups targeting it to
  4093. * work. Kick all idle workers so that they migrate to the
  4094. * associated CPU. Doing this in the same loop as
  4095. * replacing UNBOUND with REBOUND is safe as no worker will
  4096. * be bound before @pool->lock is released.
  4097. */
  4098. if (worker_flags & WORKER_IDLE)
  4099. wake_up_process(worker->task);
  4100. /*
  4101. * We want to clear UNBOUND but can't directly call
  4102. * worker_clr_flags() or adjust nr_running. Atomically
  4103. * replace UNBOUND with another NOT_RUNNING flag REBOUND.
  4104. * @worker will clear REBOUND using worker_clr_flags() when
  4105. * it initiates the next execution cycle thus restoring
  4106. * concurrency management. Note that when or whether
  4107. * @worker clears REBOUND doesn't affect correctness.
  4108. *
  4109. * WRITE_ONCE() is necessary because @worker->flags may be
  4110. * tested without holding any lock in
  4111. * wq_worker_waking_up(). Without it, NOT_RUNNING test may
  4112. * fail incorrectly leading to premature concurrency
  4113. * management operations.
  4114. */
  4115. WARN_ON_ONCE(!(worker_flags & WORKER_UNBOUND));
  4116. worker_flags |= WORKER_REBOUND;
  4117. worker_flags &= ~WORKER_UNBOUND;
  4118. WRITE_ONCE(worker->flags, worker_flags);
  4119. }
  4120. spin_unlock_irq(&pool->lock);
  4121. }
  4122. /**
  4123. * restore_unbound_workers_cpumask - restore cpumask of unbound workers
  4124. * @pool: unbound pool of interest
  4125. * @cpu: the CPU which is coming up
  4126. *
  4127. * An unbound pool may end up with a cpumask which doesn't have any online
  4128. * CPUs. When a worker of such pool get scheduled, the scheduler resets
  4129. * its cpus_allowed. If @cpu is in @pool's cpumask which didn't have any
  4130. * online CPU before, cpus_allowed of all its workers should be restored.
  4131. */
  4132. static void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu)
  4133. {
  4134. static cpumask_t cpumask;
  4135. struct worker *worker;
  4136. lockdep_assert_held(&wq_pool_attach_mutex);
  4137. /* is @cpu allowed for @pool? */
  4138. if (!cpumask_test_cpu(cpu, pool->attrs->cpumask))
  4139. return;
  4140. cpumask_and(&cpumask, pool->attrs->cpumask, cpu_online_mask);
  4141. /* as we're called from CPU_ONLINE, the following shouldn't fail */
  4142. for_each_pool_worker(worker, pool)
  4143. WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, &cpumask) < 0);
  4144. }
  4145. int workqueue_prepare_cpu(unsigned int cpu)
  4146. {
  4147. struct worker_pool *pool;
  4148. for_each_cpu_worker_pool(pool, cpu) {
  4149. if (pool->nr_workers)
  4150. continue;
  4151. if (!create_worker(pool))
  4152. return -ENOMEM;
  4153. }
  4154. return 0;
  4155. }
  4156. int workqueue_online_cpu(unsigned int cpu)
  4157. {
  4158. struct worker_pool *pool;
  4159. struct workqueue_struct *wq;
  4160. int pi;
  4161. mutex_lock(&wq_pool_mutex);
  4162. for_each_pool(pool, pi) {
  4163. mutex_lock(&wq_pool_attach_mutex);
  4164. if (pool->cpu == cpu)
  4165. rebind_workers(pool);
  4166. else if (pool->cpu < 0)
  4167. restore_unbound_workers_cpumask(pool, cpu);
  4168. mutex_unlock(&wq_pool_attach_mutex);
  4169. }
  4170. /* update NUMA affinity of unbound workqueues */
  4171. list_for_each_entry(wq, &workqueues, list)
  4172. wq_update_unbound_numa(wq, cpu, true);
  4173. mutex_unlock(&wq_pool_mutex);
  4174. return 0;
  4175. }
  4176. int workqueue_offline_cpu(unsigned int cpu)
  4177. {
  4178. struct workqueue_struct *wq;
  4179. /* unbinding per-cpu workers should happen on the local CPU */
  4180. if (WARN_ON(cpu != smp_processor_id()))
  4181. return -1;
  4182. unbind_workers(cpu);
  4183. /* update NUMA affinity of unbound workqueues */
  4184. mutex_lock(&wq_pool_mutex);
  4185. list_for_each_entry(wq, &workqueues, list)
  4186. wq_update_unbound_numa(wq, cpu, false);
  4187. mutex_unlock(&wq_pool_mutex);
  4188. return 0;
  4189. }
  4190. struct work_for_cpu {
  4191. struct work_struct work;
  4192. long (*fn)(void *);
  4193. void *arg;
  4194. long ret;
  4195. };
  4196. static void work_for_cpu_fn(struct work_struct *work)
  4197. {
  4198. struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
  4199. wfc->ret = wfc->fn(wfc->arg);
  4200. }
  4201. /**
  4202. * work_on_cpu - run a function in thread context on a particular cpu
  4203. * @cpu: the cpu to run on
  4204. * @fn: the function to run
  4205. * @arg: the function arg
  4206. *
  4207. * It is up to the caller to ensure that the cpu doesn't go offline.
  4208. * The caller must not hold any locks which would prevent @fn from completing.
  4209. *
  4210. * Return: The value @fn returns.
  4211. */
  4212. long work_on_cpu(int cpu, long (*fn)(void *), void *arg)
  4213. {
  4214. struct work_for_cpu wfc = { .fn = fn, .arg = arg };
  4215. INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
  4216. schedule_work_on(cpu, &wfc.work);
  4217. flush_work(&wfc.work);
  4218. destroy_work_on_stack(&wfc.work);
  4219. return wfc.ret;
  4220. }
  4221. EXPORT_SYMBOL_GPL(work_on_cpu);
  4222. /**
  4223. * work_on_cpu_safe - run a function in thread context on a particular cpu
  4224. * @cpu: the cpu to run on
  4225. * @fn: the function to run
  4226. * @arg: the function argument
  4227. *
  4228. * Disables CPU hotplug and calls work_on_cpu(). The caller must not hold
  4229. * any locks which would prevent @fn from completing.
  4230. *
  4231. * Return: The value @fn returns.
  4232. */
  4233. long work_on_cpu_safe(int cpu, long (*fn)(void *), void *arg)
  4234. {
  4235. long ret = -ENODEV;
  4236. get_online_cpus();
  4237. if (cpu_online(cpu))
  4238. ret = work_on_cpu(cpu, fn, arg);
  4239. put_online_cpus();
  4240. return ret;
  4241. }
  4242. EXPORT_SYMBOL_GPL(work_on_cpu_safe);
  4243. #endif /* CONFIG_SMP */
  4244. #ifdef CONFIG_FREEZER
  4245. /**
  4246. * freeze_workqueues_begin - begin freezing workqueues
  4247. *
  4248. * Start freezing workqueues. After this function returns, all freezable
  4249. * workqueues will queue new works to their delayed_works list instead of
  4250. * pool->worklist.
  4251. *
  4252. * CONTEXT:
  4253. * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
  4254. */
  4255. void freeze_workqueues_begin(void)
  4256. {
  4257. struct workqueue_struct *wq;
  4258. struct pool_workqueue *pwq;
  4259. mutex_lock(&wq_pool_mutex);
  4260. WARN_ON_ONCE(workqueue_freezing);
  4261. workqueue_freezing = true;
  4262. list_for_each_entry(wq, &workqueues, list) {
  4263. mutex_lock(&wq->mutex);
  4264. for_each_pwq(pwq, wq)
  4265. pwq_adjust_max_active(pwq);
  4266. mutex_unlock(&wq->mutex);
  4267. }
  4268. mutex_unlock(&wq_pool_mutex);
  4269. }
  4270. /**
  4271. * freeze_workqueues_busy - are freezable workqueues still busy?
  4272. *
  4273. * Check whether freezing is complete. This function must be called
  4274. * between freeze_workqueues_begin() and thaw_workqueues().
  4275. *
  4276. * CONTEXT:
  4277. * Grabs and releases wq_pool_mutex.
  4278. *
  4279. * Return:
  4280. * %true if some freezable workqueues are still busy. %false if freezing
  4281. * is complete.
  4282. */
  4283. bool freeze_workqueues_busy(void)
  4284. {
  4285. bool busy = false;
  4286. struct workqueue_struct *wq;
  4287. struct pool_workqueue *pwq;
  4288. mutex_lock(&wq_pool_mutex);
  4289. WARN_ON_ONCE(!workqueue_freezing);
  4290. list_for_each_entry(wq, &workqueues, list) {
  4291. if (!(wq->flags & WQ_FREEZABLE))
  4292. continue;
  4293. /*
  4294. * nr_active is monotonically decreasing. It's safe
  4295. * to peek without lock.
  4296. */
  4297. rcu_read_lock_sched();
  4298. for_each_pwq(pwq, wq) {
  4299. WARN_ON_ONCE(pwq->nr_active < 0);
  4300. if (pwq->nr_active) {
  4301. busy = true;
  4302. rcu_read_unlock_sched();
  4303. goto out_unlock;
  4304. }
  4305. }
  4306. rcu_read_unlock_sched();
  4307. }
  4308. out_unlock:
  4309. mutex_unlock(&wq_pool_mutex);
  4310. return busy;
  4311. }
  4312. /**
  4313. * thaw_workqueues - thaw workqueues
  4314. *
  4315. * Thaw workqueues. Normal queueing is restored and all collected
  4316. * frozen works are transferred to their respective pool worklists.
  4317. *
  4318. * CONTEXT:
  4319. * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
  4320. */
  4321. void thaw_workqueues(void)
  4322. {
  4323. struct workqueue_struct *wq;
  4324. struct pool_workqueue *pwq;
  4325. mutex_lock(&wq_pool_mutex);
  4326. if (!workqueue_freezing)
  4327. goto out_unlock;
  4328. workqueue_freezing = false;
  4329. /* restore max_active and repopulate worklist */
  4330. list_for_each_entry(wq, &workqueues, list) {
  4331. mutex_lock(&wq->mutex);
  4332. for_each_pwq(pwq, wq)
  4333. pwq_adjust_max_active(pwq);
  4334. mutex_unlock(&wq->mutex);
  4335. }
  4336. out_unlock:
  4337. mutex_unlock(&wq_pool_mutex);
  4338. }
  4339. #endif /* CONFIG_FREEZER */
  4340. static int workqueue_apply_unbound_cpumask(void)
  4341. {
  4342. LIST_HEAD(ctxs);
  4343. int ret = 0;
  4344. struct workqueue_struct *wq;
  4345. struct apply_wqattrs_ctx *ctx, *n;
  4346. lockdep_assert_held(&wq_pool_mutex);
  4347. list_for_each_entry(wq, &workqueues, list) {
  4348. if (!(wq->flags & WQ_UNBOUND))
  4349. continue;
  4350. /* creating multiple pwqs breaks ordering guarantee */
  4351. if (wq->flags & __WQ_ORDERED)
  4352. continue;
  4353. ctx = apply_wqattrs_prepare(wq, wq->unbound_attrs);
  4354. if (!ctx) {
  4355. ret = -ENOMEM;
  4356. break;
  4357. }
  4358. list_add_tail(&ctx->list, &ctxs);
  4359. }
  4360. list_for_each_entry_safe(ctx, n, &ctxs, list) {
  4361. if (!ret)
  4362. apply_wqattrs_commit(ctx);
  4363. apply_wqattrs_cleanup(ctx);
  4364. }
  4365. return ret;
  4366. }
  4367. /**
  4368. * workqueue_set_unbound_cpumask - Set the low-level unbound cpumask
  4369. * @cpumask: the cpumask to set
  4370. *
  4371. * The low-level workqueues cpumask is a global cpumask that limits
  4372. * the affinity of all unbound workqueues. This function check the @cpumask
  4373. * and apply it to all unbound workqueues and updates all pwqs of them.
  4374. *
  4375. * Retun: 0 - Success
  4376. * -EINVAL - Invalid @cpumask
  4377. * -ENOMEM - Failed to allocate memory for attrs or pwqs.
  4378. */
  4379. int workqueue_set_unbound_cpumask(cpumask_var_t cpumask)
  4380. {
  4381. int ret = -EINVAL;
  4382. cpumask_var_t saved_cpumask;
  4383. if (!zalloc_cpumask_var(&saved_cpumask, GFP_KERNEL))
  4384. return -ENOMEM;
  4385. /*
  4386. * Not excluding isolated cpus on purpose.
  4387. * If the user wishes to include them, we allow that.
  4388. */
  4389. cpumask_and(cpumask, cpumask, cpu_possible_mask);
  4390. if (!cpumask_empty(cpumask)) {
  4391. apply_wqattrs_lock();
  4392. /* save the old wq_unbound_cpumask. */
  4393. cpumask_copy(saved_cpumask, wq_unbound_cpumask);
  4394. /* update wq_unbound_cpumask at first and apply it to wqs. */
  4395. cpumask_copy(wq_unbound_cpumask, cpumask);
  4396. ret = workqueue_apply_unbound_cpumask();
  4397. /* restore the wq_unbound_cpumask when failed. */
  4398. if (ret < 0)
  4399. cpumask_copy(wq_unbound_cpumask, saved_cpumask);
  4400. apply_wqattrs_unlock();
  4401. }
  4402. free_cpumask_var(saved_cpumask);
  4403. return ret;
  4404. }
  4405. #ifdef CONFIG_SYSFS
  4406. /*
  4407. * Workqueues with WQ_SYSFS flag set is visible to userland via
  4408. * /sys/bus/workqueue/devices/WQ_NAME. All visible workqueues have the
  4409. * following attributes.
  4410. *
  4411. * per_cpu RO bool : whether the workqueue is per-cpu or unbound
  4412. * max_active RW int : maximum number of in-flight work items
  4413. *
  4414. * Unbound workqueues have the following extra attributes.
  4415. *
  4416. * pool_ids RO int : the associated pool IDs for each node
  4417. * nice RW int : nice value of the workers
  4418. * cpumask RW mask : bitmask of allowed CPUs for the workers
  4419. * numa RW bool : whether enable NUMA affinity
  4420. */
  4421. struct wq_device {
  4422. struct workqueue_struct *wq;
  4423. struct device dev;
  4424. };
  4425. static struct workqueue_struct *dev_to_wq(struct device *dev)
  4426. {
  4427. struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
  4428. return wq_dev->wq;
  4429. }
  4430. static ssize_t per_cpu_show(struct device *dev, struct device_attribute *attr,
  4431. char *buf)
  4432. {
  4433. struct workqueue_struct *wq = dev_to_wq(dev);
  4434. return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND));
  4435. }
  4436. static DEVICE_ATTR_RO(per_cpu);
  4437. static ssize_t max_active_show(struct device *dev,
  4438. struct device_attribute *attr, char *buf)
  4439. {
  4440. struct workqueue_struct *wq = dev_to_wq(dev);
  4441. return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active);
  4442. }
  4443. static ssize_t max_active_store(struct device *dev,
  4444. struct device_attribute *attr, const char *buf,
  4445. size_t count)
  4446. {
  4447. struct workqueue_struct *wq = dev_to_wq(dev);
  4448. int val;
  4449. if (sscanf(buf, "%d", &val) != 1 || val <= 0)
  4450. return -EINVAL;
  4451. workqueue_set_max_active(wq, val);
  4452. return count;
  4453. }
  4454. static DEVICE_ATTR_RW(max_active);
  4455. static struct attribute *wq_sysfs_attrs[] = {
  4456. &dev_attr_per_cpu.attr,
  4457. &dev_attr_max_active.attr,
  4458. NULL,
  4459. };
  4460. ATTRIBUTE_GROUPS(wq_sysfs);
  4461. static ssize_t wq_pool_ids_show(struct device *dev,
  4462. struct device_attribute *attr, char *buf)
  4463. {
  4464. struct workqueue_struct *wq = dev_to_wq(dev);
  4465. const char *delim = "";
  4466. int node, written = 0;
  4467. rcu_read_lock_sched();
  4468. for_each_node(node) {
  4469. written += scnprintf(buf + written, PAGE_SIZE - written,
  4470. "%s%d:%d", delim, node,
  4471. unbound_pwq_by_node(wq, node)->pool->id);
  4472. delim = " ";
  4473. }
  4474. written += scnprintf(buf + written, PAGE_SIZE - written, "\n");
  4475. rcu_read_unlock_sched();
  4476. return written;
  4477. }
  4478. static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr,
  4479. char *buf)
  4480. {
  4481. struct workqueue_struct *wq = dev_to_wq(dev);
  4482. int written;
  4483. mutex_lock(&wq->mutex);
  4484. written = scnprintf(buf, PAGE_SIZE, "%d\n", wq->unbound_attrs->nice);
  4485. mutex_unlock(&wq->mutex);
  4486. return written;
  4487. }
  4488. /* prepare workqueue_attrs for sysfs store operations */
  4489. static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq)
  4490. {
  4491. struct workqueue_attrs *attrs;
  4492. lockdep_assert_held(&wq_pool_mutex);
  4493. attrs = alloc_workqueue_attrs(GFP_KERNEL);
  4494. if (!attrs)
  4495. return NULL;
  4496. copy_workqueue_attrs(attrs, wq->unbound_attrs);
  4497. return attrs;
  4498. }
  4499. static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr,
  4500. const char *buf, size_t count)
  4501. {
  4502. struct workqueue_struct *wq = dev_to_wq(dev);
  4503. struct workqueue_attrs *attrs;
  4504. int ret = -ENOMEM;
  4505. apply_wqattrs_lock();
  4506. attrs = wq_sysfs_prep_attrs(wq);
  4507. if (!attrs)
  4508. goto out_unlock;
  4509. if (sscanf(buf, "%d", &attrs->nice) == 1 &&
  4510. attrs->nice >= MIN_NICE && attrs->nice <= MAX_NICE)
  4511. ret = apply_workqueue_attrs_locked(wq, attrs);
  4512. else
  4513. ret = -EINVAL;
  4514. out_unlock:
  4515. apply_wqattrs_unlock();
  4516. free_workqueue_attrs(attrs);
  4517. return ret ?: count;
  4518. }
  4519. static ssize_t wq_cpumask_show(struct device *dev,
  4520. struct device_attribute *attr, char *buf)
  4521. {
  4522. struct workqueue_struct *wq = dev_to_wq(dev);
  4523. int written;
  4524. mutex_lock(&wq->mutex);
  4525. written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
  4526. cpumask_pr_args(wq->unbound_attrs->cpumask));
  4527. mutex_unlock(&wq->mutex);
  4528. return written;
  4529. }
  4530. static ssize_t wq_cpumask_store(struct device *dev,
  4531. struct device_attribute *attr,
  4532. const char *buf, size_t count)
  4533. {
  4534. struct workqueue_struct *wq = dev_to_wq(dev);
  4535. struct workqueue_attrs *attrs;
  4536. int ret = -ENOMEM;
  4537. apply_wqattrs_lock();
  4538. attrs = wq_sysfs_prep_attrs(wq);
  4539. if (!attrs)
  4540. goto out_unlock;
  4541. ret = cpumask_parse(buf, attrs->cpumask);
  4542. if (!ret)
  4543. ret = apply_workqueue_attrs_locked(wq, attrs);
  4544. out_unlock:
  4545. apply_wqattrs_unlock();
  4546. free_workqueue_attrs(attrs);
  4547. return ret ?: count;
  4548. }
  4549. static ssize_t wq_numa_show(struct device *dev, struct device_attribute *attr,
  4550. char *buf)
  4551. {
  4552. struct workqueue_struct *wq = dev_to_wq(dev);
  4553. int written;
  4554. mutex_lock(&wq->mutex);
  4555. written = scnprintf(buf, PAGE_SIZE, "%d\n",
  4556. !wq->unbound_attrs->no_numa);
  4557. mutex_unlock(&wq->mutex);
  4558. return written;
  4559. }
  4560. static ssize_t wq_numa_store(struct device *dev, struct device_attribute *attr,
  4561. const char *buf, size_t count)
  4562. {
  4563. struct workqueue_struct *wq = dev_to_wq(dev);
  4564. struct workqueue_attrs *attrs;
  4565. int v, ret = -ENOMEM;
  4566. apply_wqattrs_lock();
  4567. attrs = wq_sysfs_prep_attrs(wq);
  4568. if (!attrs)
  4569. goto out_unlock;
  4570. ret = -EINVAL;
  4571. if (sscanf(buf, "%d", &v) == 1) {
  4572. attrs->no_numa = !v;
  4573. ret = apply_workqueue_attrs_locked(wq, attrs);
  4574. }
  4575. out_unlock:
  4576. apply_wqattrs_unlock();
  4577. free_workqueue_attrs(attrs);
  4578. return ret ?: count;
  4579. }
  4580. static struct device_attribute wq_sysfs_unbound_attrs[] = {
  4581. __ATTR(pool_ids, 0444, wq_pool_ids_show, NULL),
  4582. __ATTR(nice, 0644, wq_nice_show, wq_nice_store),
  4583. __ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store),
  4584. __ATTR(numa, 0644, wq_numa_show, wq_numa_store),
  4585. __ATTR_NULL,
  4586. };
  4587. static struct bus_type wq_subsys = {
  4588. .name = "workqueue",
  4589. .dev_groups = wq_sysfs_groups,
  4590. };
  4591. static ssize_t wq_unbound_cpumask_show(struct device *dev,
  4592. struct device_attribute *attr, char *buf)
  4593. {
  4594. int written;
  4595. mutex_lock(&wq_pool_mutex);
  4596. written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
  4597. cpumask_pr_args(wq_unbound_cpumask));
  4598. mutex_unlock(&wq_pool_mutex);
  4599. return written;
  4600. }
  4601. static ssize_t wq_unbound_cpumask_store(struct device *dev,
  4602. struct device_attribute *attr, const char *buf, size_t count)
  4603. {
  4604. cpumask_var_t cpumask;
  4605. int ret;
  4606. if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
  4607. return -ENOMEM;
  4608. ret = cpumask_parse(buf, cpumask);
  4609. if (!ret)
  4610. ret = workqueue_set_unbound_cpumask(cpumask);
  4611. free_cpumask_var(cpumask);
  4612. return ret ? ret : count;
  4613. }
  4614. static struct device_attribute wq_sysfs_cpumask_attr =
  4615. __ATTR(cpumask, 0644, wq_unbound_cpumask_show,
  4616. wq_unbound_cpumask_store);
  4617. static int __init wq_sysfs_init(void)
  4618. {
  4619. int err;
  4620. err = subsys_virtual_register(&wq_subsys, NULL);
  4621. if (err)
  4622. return err;
  4623. return device_create_file(wq_subsys.dev_root, &wq_sysfs_cpumask_attr);
  4624. }
  4625. core_initcall(wq_sysfs_init);
  4626. static void wq_device_release(struct device *dev)
  4627. {
  4628. struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
  4629. kfree(wq_dev);
  4630. }
  4631. /**
  4632. * workqueue_sysfs_register - make a workqueue visible in sysfs
  4633. * @wq: the workqueue to register
  4634. *
  4635. * Expose @wq in sysfs under /sys/bus/workqueue/devices.
  4636. * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
  4637. * which is the preferred method.
  4638. *
  4639. * Workqueue user should use this function directly iff it wants to apply
  4640. * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
  4641. * apply_workqueue_attrs() may race against userland updating the
  4642. * attributes.
  4643. *
  4644. * Return: 0 on success, -errno on failure.
  4645. */
  4646. int workqueue_sysfs_register(struct workqueue_struct *wq)
  4647. {
  4648. struct wq_device *wq_dev;
  4649. int ret;
  4650. /*
  4651. * Adjusting max_active or creating new pwqs by applying
  4652. * attributes breaks ordering guarantee. Disallow exposing ordered
  4653. * workqueues.
  4654. */
  4655. if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
  4656. return -EINVAL;
  4657. wq->wq_dev = wq_dev = kzalloc(sizeof(*wq_dev), GFP_KERNEL);
  4658. if (!wq_dev)
  4659. return -ENOMEM;
  4660. wq_dev->wq = wq;
  4661. wq_dev->dev.bus = &wq_subsys;
  4662. wq_dev->dev.release = wq_device_release;
  4663. dev_set_name(&wq_dev->dev, "%s", wq->name);
  4664. /*
  4665. * unbound_attrs are created separately. Suppress uevent until
  4666. * everything is ready.
  4667. */
  4668. dev_set_uevent_suppress(&wq_dev->dev, true);
  4669. ret = device_register(&wq_dev->dev);
  4670. if (ret) {
  4671. put_device(&wq_dev->dev);
  4672. wq->wq_dev = NULL;
  4673. return ret;
  4674. }
  4675. if (wq->flags & WQ_UNBOUND) {
  4676. struct device_attribute *attr;
  4677. for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) {
  4678. ret = device_create_file(&wq_dev->dev, attr);
  4679. if (ret) {
  4680. device_unregister(&wq_dev->dev);
  4681. wq->wq_dev = NULL;
  4682. return ret;
  4683. }
  4684. }
  4685. }
  4686. dev_set_uevent_suppress(&wq_dev->dev, false);
  4687. kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD);
  4688. return 0;
  4689. }
  4690. /**
  4691. * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
  4692. * @wq: the workqueue to unregister
  4693. *
  4694. * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
  4695. */
  4696. static void workqueue_sysfs_unregister(struct workqueue_struct *wq)
  4697. {
  4698. struct wq_device *wq_dev = wq->wq_dev;
  4699. if (!wq->wq_dev)
  4700. return;
  4701. wq->wq_dev = NULL;
  4702. device_unregister(&wq_dev->dev);
  4703. }
  4704. #else /* CONFIG_SYSFS */
  4705. static void workqueue_sysfs_unregister(struct workqueue_struct *wq) { }
  4706. #endif /* CONFIG_SYSFS */
  4707. /*
  4708. * Workqueue watchdog.
  4709. *
  4710. * Stall may be caused by various bugs - missing WQ_MEM_RECLAIM, illegal
  4711. * flush dependency, a concurrency managed work item which stays RUNNING
  4712. * indefinitely. Workqueue stalls can be very difficult to debug as the
  4713. * usual warning mechanisms don't trigger and internal workqueue state is
  4714. * largely opaque.
  4715. *
  4716. * Workqueue watchdog monitors all worker pools periodically and dumps
  4717. * state if some pools failed to make forward progress for a while where
  4718. * forward progress is defined as the first item on ->worklist changing.
  4719. *
  4720. * This mechanism is controlled through the kernel parameter
  4721. * "workqueue.watchdog_thresh" which can be updated at runtime through the
  4722. * corresponding sysfs parameter file.
  4723. */
  4724. #ifdef CONFIG_WQ_WATCHDOG
  4725. static unsigned long wq_watchdog_thresh = 30;
  4726. static struct timer_list wq_watchdog_timer;
  4727. static unsigned long wq_watchdog_touched = INITIAL_JIFFIES;
  4728. static DEFINE_PER_CPU(unsigned long, wq_watchdog_touched_cpu) = INITIAL_JIFFIES;
  4729. static void wq_watchdog_reset_touched(void)
  4730. {
  4731. int cpu;
  4732. wq_watchdog_touched = jiffies;
  4733. for_each_possible_cpu(cpu)
  4734. per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
  4735. }
  4736. static void wq_watchdog_timer_fn(struct timer_list *unused)
  4737. {
  4738. unsigned long thresh = READ_ONCE(wq_watchdog_thresh) * HZ;
  4739. bool lockup_detected = false;
  4740. struct worker_pool *pool;
  4741. int pi;
  4742. if (!thresh)
  4743. return;
  4744. rcu_read_lock();
  4745. for_each_pool(pool, pi) {
  4746. unsigned long pool_ts, touched, ts;
  4747. if (list_empty(&pool->worklist))
  4748. continue;
  4749. /* get the latest of pool and touched timestamps */
  4750. pool_ts = READ_ONCE(pool->watchdog_ts);
  4751. touched = READ_ONCE(wq_watchdog_touched);
  4752. if (time_after(pool_ts, touched))
  4753. ts = pool_ts;
  4754. else
  4755. ts = touched;
  4756. if (pool->cpu >= 0) {
  4757. unsigned long cpu_touched =
  4758. READ_ONCE(per_cpu(wq_watchdog_touched_cpu,
  4759. pool->cpu));
  4760. if (time_after(cpu_touched, ts))
  4761. ts = cpu_touched;
  4762. }
  4763. /* did we stall? */
  4764. if (time_after(jiffies, ts + thresh)) {
  4765. lockup_detected = true;
  4766. pr_emerg("BUG: workqueue lockup - pool");
  4767. pr_cont_pool_info(pool);
  4768. pr_cont(" stuck for %us!\n",
  4769. jiffies_to_msecs(jiffies - pool_ts) / 1000);
  4770. }
  4771. }
  4772. rcu_read_unlock();
  4773. if (lockup_detected)
  4774. show_workqueue_state();
  4775. wq_watchdog_reset_touched();
  4776. mod_timer(&wq_watchdog_timer, jiffies + thresh);
  4777. }
  4778. notrace void wq_watchdog_touch(int cpu)
  4779. {
  4780. if (cpu >= 0)
  4781. per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
  4782. else
  4783. wq_watchdog_touched = jiffies;
  4784. }
  4785. static void wq_watchdog_set_thresh(unsigned long thresh)
  4786. {
  4787. wq_watchdog_thresh = 0;
  4788. del_timer_sync(&wq_watchdog_timer);
  4789. if (thresh) {
  4790. wq_watchdog_thresh = thresh;
  4791. wq_watchdog_reset_touched();
  4792. mod_timer(&wq_watchdog_timer, jiffies + thresh * HZ);
  4793. }
  4794. }
  4795. static int wq_watchdog_param_set_thresh(const char *val,
  4796. const struct kernel_param *kp)
  4797. {
  4798. unsigned long thresh;
  4799. int ret;
  4800. ret = kstrtoul(val, 0, &thresh);
  4801. if (ret)
  4802. return ret;
  4803. if (system_wq)
  4804. wq_watchdog_set_thresh(thresh);
  4805. else
  4806. wq_watchdog_thresh = thresh;
  4807. return 0;
  4808. }
  4809. static const struct kernel_param_ops wq_watchdog_thresh_ops = {
  4810. .set = wq_watchdog_param_set_thresh,
  4811. .get = param_get_ulong,
  4812. };
  4813. module_param_cb(watchdog_thresh, &wq_watchdog_thresh_ops, &wq_watchdog_thresh,
  4814. 0644);
  4815. static void wq_watchdog_init(void)
  4816. {
  4817. timer_setup(&wq_watchdog_timer, wq_watchdog_timer_fn, TIMER_DEFERRABLE);
  4818. wq_watchdog_set_thresh(wq_watchdog_thresh);
  4819. }
  4820. #else /* CONFIG_WQ_WATCHDOG */
  4821. static inline void wq_watchdog_init(void) { }
  4822. #endif /* CONFIG_WQ_WATCHDOG */
  4823. static void __init wq_numa_init(void)
  4824. {
  4825. cpumask_var_t *tbl;
  4826. int node, cpu;
  4827. if (num_possible_nodes() <= 1)
  4828. return;
  4829. if (wq_disable_numa) {
  4830. pr_info("workqueue: NUMA affinity support disabled\n");
  4831. return;
  4832. }
  4833. wq_update_unbound_numa_attrs_buf = alloc_workqueue_attrs(GFP_KERNEL);
  4834. BUG_ON(!wq_update_unbound_numa_attrs_buf);
  4835. /*
  4836. * We want masks of possible CPUs of each node which isn't readily
  4837. * available. Build one from cpu_to_node() which should have been
  4838. * fully initialized by now.
  4839. */
  4840. tbl = kcalloc(nr_node_ids, sizeof(tbl[0]), GFP_KERNEL);
  4841. BUG_ON(!tbl);
  4842. for_each_node(node)
  4843. BUG_ON(!zalloc_cpumask_var_node(&tbl[node], GFP_KERNEL,
  4844. node_online(node) ? node : NUMA_NO_NODE));
  4845. for_each_possible_cpu(cpu) {
  4846. node = cpu_to_node(cpu);
  4847. if (WARN_ON(node == NUMA_NO_NODE)) {
  4848. pr_warn("workqueue: NUMA node mapping not available for cpu%d, disabling NUMA support\n", cpu);
  4849. /* happens iff arch is bonkers, let's just proceed */
  4850. return;
  4851. }
  4852. cpumask_set_cpu(cpu, tbl[node]);
  4853. }
  4854. wq_numa_possible_cpumask = tbl;
  4855. wq_numa_enabled = true;
  4856. }
  4857. /**
  4858. * workqueue_init_early - early init for workqueue subsystem
  4859. *
  4860. * This is the first half of two-staged workqueue subsystem initialization
  4861. * and invoked as soon as the bare basics - memory allocation, cpumasks and
  4862. * idr are up. It sets up all the data structures and system workqueues
  4863. * and allows early boot code to create workqueues and queue/cancel work
  4864. * items. Actual work item execution starts only after kthreads can be
  4865. * created and scheduled right before early initcalls.
  4866. */
  4867. int __init workqueue_init_early(void)
  4868. {
  4869. int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
  4870. int hk_flags = HK_FLAG_DOMAIN | HK_FLAG_WQ;
  4871. int i, cpu;
  4872. WARN_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
  4873. BUG_ON(!alloc_cpumask_var(&wq_unbound_cpumask, GFP_KERNEL));
  4874. cpumask_copy(wq_unbound_cpumask, housekeeping_cpumask(hk_flags));
  4875. pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
  4876. /* initialize CPU pools */
  4877. for_each_possible_cpu(cpu) {
  4878. struct worker_pool *pool;
  4879. i = 0;
  4880. for_each_cpu_worker_pool(pool, cpu) {
  4881. BUG_ON(init_worker_pool(pool));
  4882. pool->cpu = cpu;
  4883. cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
  4884. pool->attrs->nice = std_nice[i++];
  4885. pool->node = cpu_to_node(cpu);
  4886. /* alloc pool ID */
  4887. mutex_lock(&wq_pool_mutex);
  4888. BUG_ON(worker_pool_assign_id(pool));
  4889. mutex_unlock(&wq_pool_mutex);
  4890. }
  4891. }
  4892. /* create default unbound and ordered wq attrs */
  4893. for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
  4894. struct workqueue_attrs *attrs;
  4895. BUG_ON(!(attrs = alloc_workqueue_attrs(GFP_KERNEL)));
  4896. attrs->nice = std_nice[i];
  4897. unbound_std_wq_attrs[i] = attrs;
  4898. /*
  4899. * An ordered wq should have only one pwq as ordering is
  4900. * guaranteed by max_active which is enforced by pwqs.
  4901. * Turn off NUMA so that dfl_pwq is used for all nodes.
  4902. */
  4903. BUG_ON(!(attrs = alloc_workqueue_attrs(GFP_KERNEL)));
  4904. attrs->nice = std_nice[i];
  4905. attrs->no_numa = true;
  4906. ordered_wq_attrs[i] = attrs;
  4907. }
  4908. system_wq = alloc_workqueue("events", 0, 0);
  4909. system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
  4910. system_long_wq = alloc_workqueue("events_long", 0, 0);
  4911. system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
  4912. WQ_UNBOUND_MAX_ACTIVE);
  4913. system_freezable_wq = alloc_workqueue("events_freezable",
  4914. WQ_FREEZABLE, 0);
  4915. system_power_efficient_wq = alloc_workqueue("events_power_efficient",
  4916. WQ_POWER_EFFICIENT, 0);
  4917. system_freezable_power_efficient_wq = alloc_workqueue("events_freezable_power_efficient",
  4918. WQ_FREEZABLE | WQ_POWER_EFFICIENT,
  4919. 0);
  4920. BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
  4921. !system_unbound_wq || !system_freezable_wq ||
  4922. !system_power_efficient_wq ||
  4923. !system_freezable_power_efficient_wq);
  4924. return 0;
  4925. }
  4926. /**
  4927. * workqueue_init - bring workqueue subsystem fully online
  4928. *
  4929. * This is the latter half of two-staged workqueue subsystem initialization
  4930. * and invoked as soon as kthreads can be created and scheduled.
  4931. * Workqueues have been created and work items queued on them, but there
  4932. * are no kworkers executing the work items yet. Populate the worker pools
  4933. * with the initial workers and enable future kworker creations.
  4934. */
  4935. int __init workqueue_init(void)
  4936. {
  4937. struct workqueue_struct *wq;
  4938. struct worker_pool *pool;
  4939. int cpu, bkt;
  4940. /*
  4941. * It'd be simpler to initialize NUMA in workqueue_init_early() but
  4942. * CPU to node mapping may not be available that early on some
  4943. * archs such as power and arm64. As per-cpu pools created
  4944. * previously could be missing node hint and unbound pools NUMA
  4945. * affinity, fix them up.
  4946. *
  4947. * Also, while iterating workqueues, create rescuers if requested.
  4948. */
  4949. wq_numa_init();
  4950. mutex_lock(&wq_pool_mutex);
  4951. for_each_possible_cpu(cpu) {
  4952. for_each_cpu_worker_pool(pool, cpu) {
  4953. pool->node = cpu_to_node(cpu);
  4954. }
  4955. }
  4956. list_for_each_entry(wq, &workqueues, list) {
  4957. wq_update_unbound_numa(wq, smp_processor_id(), true);
  4958. WARN(init_rescuer(wq),
  4959. "workqueue: failed to create early rescuer for %s",
  4960. wq->name);
  4961. }
  4962. mutex_unlock(&wq_pool_mutex);
  4963. /* create the initial workers */
  4964. for_each_online_cpu(cpu) {
  4965. for_each_cpu_worker_pool(pool, cpu) {
  4966. pool->flags &= ~POOL_DISASSOCIATED;
  4967. BUG_ON(!create_worker(pool));
  4968. }
  4969. }
  4970. hash_for_each(unbound_pool_hash, bkt, pool, hash_node)
  4971. BUG_ON(!create_worker(pool));
  4972. wq_online = true;
  4973. wq_watchdog_init();
  4974. return 0;
  4975. }