workqueue.c 157 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691
  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/kallsyms.h>
  41. #include <linux/debug_locks.h>
  42. #include <linux/lockdep.h>
  43. #include <linux/idr.h>
  44. #include <linux/jhash.h>
  45. #include <linux/hashtable.h>
  46. #include <linux/rculist.h>
  47. #include <linux/nodemask.h>
  48. #include <linux/moduleparam.h>
  49. #include <linux/uaccess.h>
  50. #include "workqueue_internal.h"
  51. enum {
  52. /*
  53. * worker_pool flags
  54. *
  55. * A bound pool is either associated or disassociated with its CPU.
  56. * While associated (!DISASSOCIATED), all workers are bound to the
  57. * CPU and none has %WORKER_UNBOUND set and concurrency management
  58. * is in effect.
  59. *
  60. * While DISASSOCIATED, the cpu may be offline and all workers have
  61. * %WORKER_UNBOUND set and concurrency management disabled, and may
  62. * be executing on any CPU. The pool behaves as an unbound one.
  63. *
  64. * Note that DISASSOCIATED should be flipped only while holding
  65. * attach_mutex to avoid changing binding state while
  66. * worker_attach_to_pool() is in progress.
  67. */
  68. POOL_DISASSOCIATED = 1 << 2, /* cpu can't serve workers */
  69. /* worker flags */
  70. WORKER_DIE = 1 << 1, /* die die die */
  71. WORKER_IDLE = 1 << 2, /* is idle */
  72. WORKER_PREP = 1 << 3, /* preparing to run works */
  73. WORKER_CPU_INTENSIVE = 1 << 6, /* cpu intensive */
  74. WORKER_UNBOUND = 1 << 7, /* worker is unbound */
  75. WORKER_REBOUND = 1 << 8, /* worker was rebound */
  76. WORKER_NOT_RUNNING = WORKER_PREP | WORKER_CPU_INTENSIVE |
  77. WORKER_UNBOUND | WORKER_REBOUND,
  78. NR_STD_WORKER_POOLS = 2, /* # standard pools per cpu */
  79. UNBOUND_POOL_HASH_ORDER = 6, /* hashed by pool->attrs */
  80. BUSY_WORKER_HASH_ORDER = 6, /* 64 pointers */
  81. MAX_IDLE_WORKERS_RATIO = 4, /* 1/4 of busy can be idle */
  82. IDLE_WORKER_TIMEOUT = 300 * HZ, /* keep idle ones for 5 mins */
  83. MAYDAY_INITIAL_TIMEOUT = HZ / 100 >= 2 ? HZ / 100 : 2,
  84. /* call for help after 10ms
  85. (min two ticks) */
  86. MAYDAY_INTERVAL = HZ / 10, /* and then every 100ms */
  87. CREATE_COOLDOWN = HZ, /* time to breath after fail */
  88. /*
  89. * Rescue workers are used only on emergencies and shared by
  90. * all cpus. Give MIN_NICE.
  91. */
  92. RESCUER_NICE_LEVEL = MIN_NICE,
  93. HIGHPRI_NICE_LEVEL = MIN_NICE,
  94. WQ_NAME_LEN = 24,
  95. };
  96. /*
  97. * Structure fields follow one of the following exclusion rules.
  98. *
  99. * I: Modifiable by initialization/destruction paths and read-only for
  100. * everyone else.
  101. *
  102. * P: Preemption protected. Disabling preemption is enough and should
  103. * only be modified and accessed from the local cpu.
  104. *
  105. * L: pool->lock protected. Access with pool->lock held.
  106. *
  107. * X: During normal operation, modification requires pool->lock and should
  108. * be done only from local cpu. Either disabling preemption on local
  109. * cpu or grabbing pool->lock is enough for read access. If
  110. * POOL_DISASSOCIATED is set, it's identical to L.
  111. *
  112. * A: pool->attach_mutex protected.
  113. *
  114. * PL: wq_pool_mutex protected.
  115. *
  116. * PR: wq_pool_mutex protected for writes. Sched-RCU protected for reads.
  117. *
  118. * PW: wq_pool_mutex and wq->mutex protected for writes. Either for reads.
  119. *
  120. * PWR: wq_pool_mutex and wq->mutex protected for writes. Either or
  121. * sched-RCU for reads.
  122. *
  123. * WQ: wq->mutex protected.
  124. *
  125. * WR: wq->mutex protected for writes. Sched-RCU protected for reads.
  126. *
  127. * MD: wq_mayday_lock protected.
  128. */
  129. /* struct worker is defined in workqueue_internal.h */
  130. struct worker_pool {
  131. spinlock_t lock; /* the pool lock */
  132. int cpu; /* I: the associated cpu */
  133. int node; /* I: the associated node ID */
  134. int id; /* I: pool ID */
  135. unsigned int flags; /* X: flags */
  136. unsigned long watchdog_ts; /* L: watchdog timestamp */
  137. struct list_head worklist; /* L: list of pending works */
  138. int nr_workers; /* L: total number of workers */
  139. /* nr_idle includes the ones off idle_list for rebinding */
  140. int nr_idle; /* L: currently idle ones */
  141. struct list_head idle_list; /* X: list of idle workers */
  142. struct timer_list idle_timer; /* L: worker idle timeout */
  143. struct timer_list mayday_timer; /* L: SOS timer for workers */
  144. /* a workers is either on busy_hash or idle_list, or the manager */
  145. DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
  146. /* L: hash of busy workers */
  147. /* see manage_workers() for details on the two manager mutexes */
  148. struct mutex manager_arb; /* manager arbitration */
  149. struct worker *manager; /* L: purely informational */
  150. struct mutex attach_mutex; /* attach/detach exclusion */
  151. struct list_head workers; /* A: attached workers */
  152. struct completion *detach_completion; /* all workers detached */
  153. struct ida worker_ida; /* worker IDs for task name */
  154. struct workqueue_attrs *attrs; /* I: worker attributes */
  155. struct hlist_node hash_node; /* PL: unbound_pool_hash node */
  156. int refcnt; /* PL: refcnt for unbound pools */
  157. /*
  158. * The current concurrency level. As it's likely to be accessed
  159. * from other CPUs during try_to_wake_up(), put it in a separate
  160. * cacheline.
  161. */
  162. atomic_t nr_running ____cacheline_aligned_in_smp;
  163. /*
  164. * Destruction of pool is sched-RCU protected to allow dereferences
  165. * from get_work_pool().
  166. */
  167. struct rcu_head rcu;
  168. } ____cacheline_aligned_in_smp;
  169. /*
  170. * The per-pool workqueue. While queued, the lower WORK_STRUCT_FLAG_BITS
  171. * of work_struct->data are used for flags and the remaining high bits
  172. * point to the pwq; thus, pwqs need to be aligned at two's power of the
  173. * number of flag bits.
  174. */
  175. struct pool_workqueue {
  176. struct worker_pool *pool; /* I: the associated pool */
  177. struct workqueue_struct *wq; /* I: the owning workqueue */
  178. int work_color; /* L: current color */
  179. int flush_color; /* L: flushing color */
  180. int refcnt; /* L: reference count */
  181. int nr_in_flight[WORK_NR_COLORS];
  182. /* L: nr of in_flight works */
  183. int nr_active; /* L: nr of active works */
  184. int max_active; /* L: max active works */
  185. struct list_head delayed_works; /* L: delayed works */
  186. struct list_head pwqs_node; /* WR: node on wq->pwqs */
  187. struct list_head mayday_node; /* MD: node on wq->maydays */
  188. /*
  189. * Release of unbound pwq is punted to system_wq. See put_pwq()
  190. * and pwq_unbound_release_workfn() for details. pool_workqueue
  191. * itself is also sched-RCU protected so that the first pwq can be
  192. * determined without grabbing wq->mutex.
  193. */
  194. struct work_struct unbound_release_work;
  195. struct rcu_head rcu;
  196. } __aligned(1 << WORK_STRUCT_FLAG_BITS);
  197. /*
  198. * Structure used to wait for workqueue flush.
  199. */
  200. struct wq_flusher {
  201. struct list_head list; /* WQ: list of flushers */
  202. int flush_color; /* WQ: flush color waiting for */
  203. struct completion done; /* flush completion */
  204. };
  205. struct wq_device;
  206. /*
  207. * The externally visible workqueue. It relays the issued work items to
  208. * the appropriate worker_pool through its pool_workqueues.
  209. */
  210. struct workqueue_struct {
  211. struct list_head pwqs; /* WR: all pwqs of this wq */
  212. struct list_head list; /* PR: list of all workqueues */
  213. struct mutex mutex; /* protects this wq */
  214. int work_color; /* WQ: current work color */
  215. int flush_color; /* WQ: current flush color */
  216. atomic_t nr_pwqs_to_flush; /* flush in progress */
  217. struct wq_flusher *first_flusher; /* WQ: first flusher */
  218. struct list_head flusher_queue; /* WQ: flush waiters */
  219. struct list_head flusher_overflow; /* WQ: flush overflow list */
  220. struct list_head maydays; /* MD: pwqs requesting rescue */
  221. struct worker *rescuer; /* I: rescue worker */
  222. int nr_drainers; /* WQ: drain in progress */
  223. int saved_max_active; /* WQ: saved pwq max_active */
  224. struct workqueue_attrs *unbound_attrs; /* PW: only for unbound wqs */
  225. struct pool_workqueue *dfl_pwq; /* PW: only for unbound wqs */
  226. #ifdef CONFIG_SYSFS
  227. struct wq_device *wq_dev; /* I: for sysfs interface */
  228. #endif
  229. #ifdef CONFIG_LOCKDEP
  230. struct lockdep_map lockdep_map;
  231. #endif
  232. char name[WQ_NAME_LEN]; /* I: workqueue name */
  233. /*
  234. * Destruction of workqueue_struct is sched-RCU protected to allow
  235. * walking the workqueues list without grabbing wq_pool_mutex.
  236. * This is used to dump all workqueues from sysrq.
  237. */
  238. struct rcu_head rcu;
  239. /* hot fields used during command issue, aligned to cacheline */
  240. unsigned int flags ____cacheline_aligned; /* WQ: WQ_* flags */
  241. struct pool_workqueue __percpu *cpu_pwqs; /* I: per-cpu pwqs */
  242. struct pool_workqueue __rcu *numa_pwq_tbl[]; /* PWR: unbound pwqs indexed by node */
  243. };
  244. static struct kmem_cache *pwq_cache;
  245. static cpumask_var_t *wq_numa_possible_cpumask;
  246. /* possible CPUs of each node */
  247. static bool wq_disable_numa;
  248. module_param_named(disable_numa, wq_disable_numa, bool, 0444);
  249. /* see the comment above the definition of WQ_POWER_EFFICIENT */
  250. static bool wq_power_efficient = IS_ENABLED(CONFIG_WQ_POWER_EFFICIENT_DEFAULT);
  251. module_param_named(power_efficient, wq_power_efficient, bool, 0444);
  252. static bool wq_online; /* can kworkers be created yet? */
  253. static bool wq_numa_enabled; /* unbound NUMA affinity enabled */
  254. /* buf for wq_update_unbound_numa_attrs(), protected by CPU hotplug exclusion */
  255. static struct workqueue_attrs *wq_update_unbound_numa_attrs_buf;
  256. static DEFINE_MUTEX(wq_pool_mutex); /* protects pools and workqueues list */
  257. static DEFINE_SPINLOCK(wq_mayday_lock); /* protects wq->maydays list */
  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 @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(&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 = mutex_is_locked(&pool->manager_arb);
  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. WARN_ON_ONCE(!irqs_disabled());
  1200. debug_work_activate(work);
  1201. /* if draining, only works from the same workqueue are allowed */
  1202. if (unlikely(wq->flags & __WQ_DRAINING) &&
  1203. WARN_ON_ONCE(!is_chained_work(wq)))
  1204. return;
  1205. retry:
  1206. if (req_cpu == WORK_CPU_UNBOUND)
  1207. cpu = wq_select_unbound_cpu(raw_smp_processor_id());
  1208. /* pwq which will be used unless @work is executing elsewhere */
  1209. if (!(wq->flags & WQ_UNBOUND))
  1210. pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
  1211. else
  1212. pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
  1213. /*
  1214. * If @work was previously on a different pool, it might still be
  1215. * running there, in which case the work needs to be queued on that
  1216. * pool to guarantee non-reentrancy.
  1217. */
  1218. last_pool = get_work_pool(work);
  1219. if (last_pool && last_pool != pwq->pool) {
  1220. struct worker *worker;
  1221. spin_lock(&last_pool->lock);
  1222. worker = find_worker_executing_work(last_pool, work);
  1223. if (worker && worker->current_pwq->wq == wq) {
  1224. pwq = worker->current_pwq;
  1225. } else {
  1226. /* meh... not running there, queue here */
  1227. spin_unlock(&last_pool->lock);
  1228. spin_lock(&pwq->pool->lock);
  1229. }
  1230. } else {
  1231. spin_lock(&pwq->pool->lock);
  1232. }
  1233. /*
  1234. * pwq is determined and locked. For unbound pools, we could have
  1235. * raced with pwq release and it could already be dead. If its
  1236. * refcnt is zero, repeat pwq selection. Note that pwqs never die
  1237. * without another pwq replacing it in the numa_pwq_tbl or while
  1238. * work items are executing on it, so the retrying is guaranteed to
  1239. * make forward-progress.
  1240. */
  1241. if (unlikely(!pwq->refcnt)) {
  1242. if (wq->flags & WQ_UNBOUND) {
  1243. spin_unlock(&pwq->pool->lock);
  1244. cpu_relax();
  1245. goto retry;
  1246. }
  1247. /* oops */
  1248. WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
  1249. wq->name, cpu);
  1250. }
  1251. /* pwq determined, queue */
  1252. trace_workqueue_queue_work(req_cpu, pwq, work);
  1253. if (WARN_ON(!list_empty(&work->entry))) {
  1254. spin_unlock(&pwq->pool->lock);
  1255. return;
  1256. }
  1257. pwq->nr_in_flight[pwq->work_color]++;
  1258. work_flags = work_color_to_flags(pwq->work_color);
  1259. if (likely(pwq->nr_active < pwq->max_active)) {
  1260. trace_workqueue_activate_work(work);
  1261. pwq->nr_active++;
  1262. worklist = &pwq->pool->worklist;
  1263. if (list_empty(worklist))
  1264. pwq->pool->watchdog_ts = jiffies;
  1265. } else {
  1266. work_flags |= WORK_STRUCT_DELAYED;
  1267. worklist = &pwq->delayed_works;
  1268. }
  1269. insert_work(pwq, work, worklist, work_flags);
  1270. spin_unlock(&pwq->pool->lock);
  1271. }
  1272. /**
  1273. * queue_work_on - queue work on specific cpu
  1274. * @cpu: CPU number to execute work on
  1275. * @wq: workqueue to use
  1276. * @work: work to queue
  1277. *
  1278. * We queue the work to a specific CPU, the caller must ensure it
  1279. * can't go away.
  1280. *
  1281. * Return: %false if @work was already on a queue, %true otherwise.
  1282. */
  1283. bool queue_work_on(int cpu, struct workqueue_struct *wq,
  1284. struct work_struct *work)
  1285. {
  1286. bool ret = false;
  1287. unsigned long flags;
  1288. local_irq_save(flags);
  1289. if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
  1290. __queue_work(cpu, wq, work);
  1291. ret = true;
  1292. }
  1293. local_irq_restore(flags);
  1294. return ret;
  1295. }
  1296. EXPORT_SYMBOL(queue_work_on);
  1297. void delayed_work_timer_fn(struct timer_list *t)
  1298. {
  1299. struct delayed_work *dwork = from_timer(dwork, t, timer);
  1300. /* should have been called from irqsafe timer with irq already off */
  1301. __queue_work(dwork->cpu, dwork->wq, &dwork->work);
  1302. }
  1303. EXPORT_SYMBOL(delayed_work_timer_fn);
  1304. static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
  1305. struct delayed_work *dwork, unsigned long delay)
  1306. {
  1307. struct timer_list *timer = &dwork->timer;
  1308. struct work_struct *work = &dwork->work;
  1309. WARN_ON_ONCE(!wq);
  1310. WARN_ON_ONCE(timer->function != (TIMER_FUNC_TYPE)delayed_work_timer_fn);
  1311. WARN_ON_ONCE(timer_pending(timer));
  1312. WARN_ON_ONCE(!list_empty(&work->entry));
  1313. /*
  1314. * If @delay is 0, queue @dwork->work immediately. This is for
  1315. * both optimization and correctness. The earliest @timer can
  1316. * expire is on the closest next tick and delayed_work users depend
  1317. * on that there's no such delay when @delay is 0.
  1318. */
  1319. if (!delay) {
  1320. __queue_work(cpu, wq, &dwork->work);
  1321. return;
  1322. }
  1323. dwork->wq = wq;
  1324. dwork->cpu = cpu;
  1325. timer->expires = jiffies + delay;
  1326. if (unlikely(cpu != WORK_CPU_UNBOUND))
  1327. add_timer_on(timer, cpu);
  1328. else
  1329. add_timer(timer);
  1330. }
  1331. /**
  1332. * queue_delayed_work_on - queue work on specific CPU after delay
  1333. * @cpu: CPU number to execute work on
  1334. * @wq: workqueue to use
  1335. * @dwork: work to queue
  1336. * @delay: number of jiffies to wait before queueing
  1337. *
  1338. * Return: %false if @work was already on a queue, %true otherwise. If
  1339. * @delay is zero and @dwork is idle, it will be scheduled for immediate
  1340. * execution.
  1341. */
  1342. bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
  1343. struct delayed_work *dwork, unsigned long delay)
  1344. {
  1345. struct work_struct *work = &dwork->work;
  1346. bool ret = false;
  1347. unsigned long flags;
  1348. /* read the comment in __queue_work() */
  1349. local_irq_save(flags);
  1350. if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
  1351. __queue_delayed_work(cpu, wq, dwork, delay);
  1352. ret = true;
  1353. }
  1354. local_irq_restore(flags);
  1355. return ret;
  1356. }
  1357. EXPORT_SYMBOL(queue_delayed_work_on);
  1358. /**
  1359. * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
  1360. * @cpu: CPU number to execute work on
  1361. * @wq: workqueue to use
  1362. * @dwork: work to queue
  1363. * @delay: number of jiffies to wait before queueing
  1364. *
  1365. * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
  1366. * modify @dwork's timer so that it expires after @delay. If @delay is
  1367. * zero, @work is guaranteed to be scheduled immediately regardless of its
  1368. * current state.
  1369. *
  1370. * Return: %false if @dwork was idle and queued, %true if @dwork was
  1371. * pending and its timer was modified.
  1372. *
  1373. * This function is safe to call from any context including IRQ handler.
  1374. * See try_to_grab_pending() for details.
  1375. */
  1376. bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
  1377. struct delayed_work *dwork, unsigned long delay)
  1378. {
  1379. unsigned long flags;
  1380. int ret;
  1381. do {
  1382. ret = try_to_grab_pending(&dwork->work, true, &flags);
  1383. } while (unlikely(ret == -EAGAIN));
  1384. if (likely(ret >= 0)) {
  1385. __queue_delayed_work(cpu, wq, dwork, delay);
  1386. local_irq_restore(flags);
  1387. }
  1388. /* -ENOENT from try_to_grab_pending() becomes %true */
  1389. return ret;
  1390. }
  1391. EXPORT_SYMBOL_GPL(mod_delayed_work_on);
  1392. /**
  1393. * worker_enter_idle - enter idle state
  1394. * @worker: worker which is entering idle state
  1395. *
  1396. * @worker is entering idle state. Update stats and idle timer if
  1397. * necessary.
  1398. *
  1399. * LOCKING:
  1400. * spin_lock_irq(pool->lock).
  1401. */
  1402. static void worker_enter_idle(struct worker *worker)
  1403. {
  1404. struct worker_pool *pool = worker->pool;
  1405. if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
  1406. WARN_ON_ONCE(!list_empty(&worker->entry) &&
  1407. (worker->hentry.next || worker->hentry.pprev)))
  1408. return;
  1409. /* can't use worker_set_flags(), also called from create_worker() */
  1410. worker->flags |= WORKER_IDLE;
  1411. pool->nr_idle++;
  1412. worker->last_active = jiffies;
  1413. /* idle_list is LIFO */
  1414. list_add(&worker->entry, &pool->idle_list);
  1415. if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
  1416. mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
  1417. /*
  1418. * Sanity check nr_running. Because wq_unbind_fn() releases
  1419. * pool->lock between setting %WORKER_UNBOUND and zapping
  1420. * nr_running, the warning may trigger spuriously. Check iff
  1421. * unbind is not in progress.
  1422. */
  1423. WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
  1424. pool->nr_workers == pool->nr_idle &&
  1425. atomic_read(&pool->nr_running));
  1426. }
  1427. /**
  1428. * worker_leave_idle - leave idle state
  1429. * @worker: worker which is leaving idle state
  1430. *
  1431. * @worker is leaving idle state. Update stats.
  1432. *
  1433. * LOCKING:
  1434. * spin_lock_irq(pool->lock).
  1435. */
  1436. static void worker_leave_idle(struct worker *worker)
  1437. {
  1438. struct worker_pool *pool = worker->pool;
  1439. if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
  1440. return;
  1441. worker_clr_flags(worker, WORKER_IDLE);
  1442. pool->nr_idle--;
  1443. list_del_init(&worker->entry);
  1444. }
  1445. static struct worker *alloc_worker(int node)
  1446. {
  1447. struct worker *worker;
  1448. worker = kzalloc_node(sizeof(*worker), GFP_KERNEL, node);
  1449. if (worker) {
  1450. INIT_LIST_HEAD(&worker->entry);
  1451. INIT_LIST_HEAD(&worker->scheduled);
  1452. INIT_LIST_HEAD(&worker->node);
  1453. /* on creation a worker is in !idle && prep state */
  1454. worker->flags = WORKER_PREP;
  1455. }
  1456. return worker;
  1457. }
  1458. /**
  1459. * worker_attach_to_pool() - attach a worker to a pool
  1460. * @worker: worker to be attached
  1461. * @pool: the target pool
  1462. *
  1463. * Attach @worker to @pool. Once attached, the %WORKER_UNBOUND flag and
  1464. * cpu-binding of @worker are kept coordinated with the pool across
  1465. * cpu-[un]hotplugs.
  1466. */
  1467. static void worker_attach_to_pool(struct worker *worker,
  1468. struct worker_pool *pool)
  1469. {
  1470. mutex_lock(&pool->attach_mutex);
  1471. /*
  1472. * set_cpus_allowed_ptr() will fail if the cpumask doesn't have any
  1473. * online CPUs. It'll be re-applied when any of the CPUs come up.
  1474. */
  1475. set_cpus_allowed_ptr(worker->task, pool->attrs->cpumask);
  1476. /*
  1477. * The pool->attach_mutex ensures %POOL_DISASSOCIATED remains
  1478. * stable across this function. See the comments above the
  1479. * flag definition for details.
  1480. */
  1481. if (pool->flags & POOL_DISASSOCIATED)
  1482. worker->flags |= WORKER_UNBOUND;
  1483. list_add_tail(&worker->node, &pool->workers);
  1484. mutex_unlock(&pool->attach_mutex);
  1485. }
  1486. /**
  1487. * worker_detach_from_pool() - detach a worker from its pool
  1488. * @worker: worker which is attached to its pool
  1489. * @pool: the pool @worker is attached to
  1490. *
  1491. * Undo the attaching which had been done in worker_attach_to_pool(). The
  1492. * caller worker shouldn't access to the pool after detached except it has
  1493. * other reference to the pool.
  1494. */
  1495. static void worker_detach_from_pool(struct worker *worker,
  1496. struct worker_pool *pool)
  1497. {
  1498. struct completion *detach_completion = NULL;
  1499. mutex_lock(&pool->attach_mutex);
  1500. list_del(&worker->node);
  1501. if (list_empty(&pool->workers))
  1502. detach_completion = pool->detach_completion;
  1503. mutex_unlock(&pool->attach_mutex);
  1504. /* clear leftover flags without pool->lock after it is detached */
  1505. worker->flags &= ~(WORKER_UNBOUND | WORKER_REBOUND);
  1506. if (detach_completion)
  1507. complete(detach_completion);
  1508. }
  1509. /**
  1510. * create_worker - create a new workqueue worker
  1511. * @pool: pool the new worker will belong to
  1512. *
  1513. * Create and start a new worker which is attached to @pool.
  1514. *
  1515. * CONTEXT:
  1516. * Might sleep. Does GFP_KERNEL allocations.
  1517. *
  1518. * Return:
  1519. * Pointer to the newly created worker.
  1520. */
  1521. static struct worker *create_worker(struct worker_pool *pool)
  1522. {
  1523. struct worker *worker = NULL;
  1524. int id = -1;
  1525. char id_buf[16];
  1526. /* ID is needed to determine kthread name */
  1527. id = ida_simple_get(&pool->worker_ida, 0, 0, GFP_KERNEL);
  1528. if (id < 0)
  1529. goto fail;
  1530. worker = alloc_worker(pool->node);
  1531. if (!worker)
  1532. goto fail;
  1533. worker->pool = pool;
  1534. worker->id = id;
  1535. if (pool->cpu >= 0)
  1536. snprintf(id_buf, sizeof(id_buf), "%d:%d%s", pool->cpu, id,
  1537. pool->attrs->nice < 0 ? "H" : "");
  1538. else
  1539. snprintf(id_buf, sizeof(id_buf), "u%d:%d", pool->id, id);
  1540. worker->task = kthread_create_on_node(worker_thread, worker, pool->node,
  1541. "kworker/%s", id_buf);
  1542. if (IS_ERR(worker->task))
  1543. goto fail;
  1544. set_user_nice(worker->task, pool->attrs->nice);
  1545. kthread_bind_mask(worker->task, pool->attrs->cpumask);
  1546. /* successful, attach the worker to the pool */
  1547. worker_attach_to_pool(worker, pool);
  1548. /* start the newly created worker */
  1549. spin_lock_irq(&pool->lock);
  1550. worker->pool->nr_workers++;
  1551. worker_enter_idle(worker);
  1552. wake_up_process(worker->task);
  1553. spin_unlock_irq(&pool->lock);
  1554. return worker;
  1555. fail:
  1556. if (id >= 0)
  1557. ida_simple_remove(&pool->worker_ida, id);
  1558. kfree(worker);
  1559. return NULL;
  1560. }
  1561. /**
  1562. * destroy_worker - destroy a workqueue worker
  1563. * @worker: worker to be destroyed
  1564. *
  1565. * Destroy @worker and adjust @pool stats accordingly. The worker should
  1566. * be idle.
  1567. *
  1568. * CONTEXT:
  1569. * spin_lock_irq(pool->lock).
  1570. */
  1571. static void destroy_worker(struct worker *worker)
  1572. {
  1573. struct worker_pool *pool = worker->pool;
  1574. lockdep_assert_held(&pool->lock);
  1575. /* sanity check frenzy */
  1576. if (WARN_ON(worker->current_work) ||
  1577. WARN_ON(!list_empty(&worker->scheduled)) ||
  1578. WARN_ON(!(worker->flags & WORKER_IDLE)))
  1579. return;
  1580. pool->nr_workers--;
  1581. pool->nr_idle--;
  1582. list_del_init(&worker->entry);
  1583. worker->flags |= WORKER_DIE;
  1584. wake_up_process(worker->task);
  1585. }
  1586. static void idle_worker_timeout(struct timer_list *t)
  1587. {
  1588. struct worker_pool *pool = from_timer(pool, t, idle_timer);
  1589. spin_lock_irq(&pool->lock);
  1590. while (too_many_workers(pool)) {
  1591. struct worker *worker;
  1592. unsigned long expires;
  1593. /* idle_list is kept in LIFO order, check the last one */
  1594. worker = list_entry(pool->idle_list.prev, struct worker, entry);
  1595. expires = worker->last_active + IDLE_WORKER_TIMEOUT;
  1596. if (time_before(jiffies, expires)) {
  1597. mod_timer(&pool->idle_timer, expires);
  1598. break;
  1599. }
  1600. destroy_worker(worker);
  1601. }
  1602. spin_unlock_irq(&pool->lock);
  1603. }
  1604. static void send_mayday(struct work_struct *work)
  1605. {
  1606. struct pool_workqueue *pwq = get_work_pwq(work);
  1607. struct workqueue_struct *wq = pwq->wq;
  1608. lockdep_assert_held(&wq_mayday_lock);
  1609. if (!wq->rescuer)
  1610. return;
  1611. /* mayday mayday mayday */
  1612. if (list_empty(&pwq->mayday_node)) {
  1613. /*
  1614. * If @pwq is for an unbound wq, its base ref may be put at
  1615. * any time due to an attribute change. Pin @pwq until the
  1616. * rescuer is done with it.
  1617. */
  1618. get_pwq(pwq);
  1619. list_add_tail(&pwq->mayday_node, &wq->maydays);
  1620. wake_up_process(wq->rescuer->task);
  1621. }
  1622. }
  1623. static void pool_mayday_timeout(struct timer_list *t)
  1624. {
  1625. struct worker_pool *pool = from_timer(pool, t, mayday_timer);
  1626. struct work_struct *work;
  1627. spin_lock_irq(&pool->lock);
  1628. spin_lock(&wq_mayday_lock); /* for wq->maydays */
  1629. if (need_to_create_worker(pool)) {
  1630. /*
  1631. * We've been trying to create a new worker but
  1632. * haven't been successful. We might be hitting an
  1633. * allocation deadlock. Send distress signals to
  1634. * rescuers.
  1635. */
  1636. list_for_each_entry(work, &pool->worklist, entry)
  1637. send_mayday(work);
  1638. }
  1639. spin_unlock(&wq_mayday_lock);
  1640. spin_unlock_irq(&pool->lock);
  1641. mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
  1642. }
  1643. /**
  1644. * maybe_create_worker - create a new worker if necessary
  1645. * @pool: pool to create a new worker for
  1646. *
  1647. * Create a new worker for @pool if necessary. @pool is guaranteed to
  1648. * have at least one idle worker on return from this function. If
  1649. * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
  1650. * sent to all rescuers with works scheduled on @pool to resolve
  1651. * possible allocation deadlock.
  1652. *
  1653. * On return, need_to_create_worker() is guaranteed to be %false and
  1654. * may_start_working() %true.
  1655. *
  1656. * LOCKING:
  1657. * spin_lock_irq(pool->lock) which may be released and regrabbed
  1658. * multiple times. Does GFP_KERNEL allocations. Called only from
  1659. * manager.
  1660. */
  1661. static void maybe_create_worker(struct worker_pool *pool)
  1662. __releases(&pool->lock)
  1663. __acquires(&pool->lock)
  1664. {
  1665. restart:
  1666. spin_unlock_irq(&pool->lock);
  1667. /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
  1668. mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
  1669. while (true) {
  1670. if (create_worker(pool) || !need_to_create_worker(pool))
  1671. break;
  1672. schedule_timeout_interruptible(CREATE_COOLDOWN);
  1673. if (!need_to_create_worker(pool))
  1674. break;
  1675. }
  1676. del_timer_sync(&pool->mayday_timer);
  1677. spin_lock_irq(&pool->lock);
  1678. /*
  1679. * This is necessary even after a new worker was just successfully
  1680. * created as @pool->lock was dropped and the new worker might have
  1681. * already become busy.
  1682. */
  1683. if (need_to_create_worker(pool))
  1684. goto restart;
  1685. }
  1686. /**
  1687. * manage_workers - manage worker pool
  1688. * @worker: self
  1689. *
  1690. * Assume the manager role and manage the worker pool @worker belongs
  1691. * to. At any given time, there can be only zero or one manager per
  1692. * pool. The exclusion is handled automatically by this function.
  1693. *
  1694. * The caller can safely start processing works on false return. On
  1695. * true return, it's guaranteed that need_to_create_worker() is false
  1696. * and may_start_working() is true.
  1697. *
  1698. * CONTEXT:
  1699. * spin_lock_irq(pool->lock) which may be released and regrabbed
  1700. * multiple times. Does GFP_KERNEL allocations.
  1701. *
  1702. * Return:
  1703. * %false if the pool doesn't need management and the caller can safely
  1704. * start processing works, %true if management function was performed and
  1705. * the conditions that the caller verified before calling the function may
  1706. * no longer be true.
  1707. */
  1708. static bool manage_workers(struct worker *worker)
  1709. {
  1710. struct worker_pool *pool = worker->pool;
  1711. /*
  1712. * Anyone who successfully grabs manager_arb wins the arbitration
  1713. * and becomes the manager. mutex_trylock() on pool->manager_arb
  1714. * failure while holding pool->lock reliably indicates that someone
  1715. * else is managing the pool and the worker which failed trylock
  1716. * can proceed to executing work items. This means that anyone
  1717. * grabbing manager_arb is responsible for actually performing
  1718. * manager duties. If manager_arb is grabbed and released without
  1719. * actual management, the pool may stall indefinitely.
  1720. */
  1721. if (!mutex_trylock(&pool->manager_arb))
  1722. return false;
  1723. pool->manager = worker;
  1724. maybe_create_worker(pool);
  1725. pool->manager = NULL;
  1726. mutex_unlock(&pool->manager_arb);
  1727. return true;
  1728. }
  1729. /**
  1730. * process_one_work - process single work
  1731. * @worker: self
  1732. * @work: work to process
  1733. *
  1734. * Process @work. This function contains all the logics necessary to
  1735. * process a single work including synchronization against and
  1736. * interaction with other workers on the same cpu, queueing and
  1737. * flushing. As long as context requirement is met, any worker can
  1738. * call this function to process a work.
  1739. *
  1740. * CONTEXT:
  1741. * spin_lock_irq(pool->lock) which is released and regrabbed.
  1742. */
  1743. static void process_one_work(struct worker *worker, struct work_struct *work)
  1744. __releases(&pool->lock)
  1745. __acquires(&pool->lock)
  1746. {
  1747. struct pool_workqueue *pwq = get_work_pwq(work);
  1748. struct worker_pool *pool = worker->pool;
  1749. bool cpu_intensive = pwq->wq->flags & WQ_CPU_INTENSIVE;
  1750. int work_color;
  1751. struct worker *collision;
  1752. #ifdef CONFIG_LOCKDEP
  1753. /*
  1754. * It is permissible to free the struct work_struct from
  1755. * inside the function that is called from it, this we need to
  1756. * take into account for lockdep too. To avoid bogus "held
  1757. * lock freed" warnings as well as problems when looking into
  1758. * work->lockdep_map, make a copy and use that here.
  1759. */
  1760. struct lockdep_map lockdep_map;
  1761. lockdep_copy_map(&lockdep_map, &work->lockdep_map);
  1762. #endif
  1763. /* ensure we're on the correct CPU */
  1764. WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
  1765. raw_smp_processor_id() != pool->cpu);
  1766. /*
  1767. * A single work shouldn't be executed concurrently by
  1768. * multiple workers on a single cpu. Check whether anyone is
  1769. * already processing the work. If so, defer the work to the
  1770. * currently executing one.
  1771. */
  1772. collision = find_worker_executing_work(pool, work);
  1773. if (unlikely(collision)) {
  1774. move_linked_works(work, &collision->scheduled, NULL);
  1775. return;
  1776. }
  1777. /* claim and dequeue */
  1778. debug_work_deactivate(work);
  1779. hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
  1780. worker->current_work = work;
  1781. worker->current_func = work->func;
  1782. worker->current_pwq = pwq;
  1783. work_color = get_work_color(work);
  1784. list_del_init(&work->entry);
  1785. /*
  1786. * CPU intensive works don't participate in concurrency management.
  1787. * They're the scheduler's responsibility. This takes @worker out
  1788. * of concurrency management and the next code block will chain
  1789. * execution of the pending work items.
  1790. */
  1791. if (unlikely(cpu_intensive))
  1792. worker_set_flags(worker, WORKER_CPU_INTENSIVE);
  1793. /*
  1794. * Wake up another worker if necessary. The condition is always
  1795. * false for normal per-cpu workers since nr_running would always
  1796. * be >= 1 at this point. This is used to chain execution of the
  1797. * pending work items for WORKER_NOT_RUNNING workers such as the
  1798. * UNBOUND and CPU_INTENSIVE ones.
  1799. */
  1800. if (need_more_worker(pool))
  1801. wake_up_worker(pool);
  1802. /*
  1803. * Record the last pool and clear PENDING which should be the last
  1804. * update to @work. Also, do this inside @pool->lock so that
  1805. * PENDING and queued state changes happen together while IRQ is
  1806. * disabled.
  1807. */
  1808. set_work_pool_and_clear_pending(work, pool->id);
  1809. spin_unlock_irq(&pool->lock);
  1810. lock_map_acquire(&pwq->wq->lockdep_map);
  1811. lock_map_acquire(&lockdep_map);
  1812. /*
  1813. * Strictly speaking we should mark the invariant state without holding
  1814. * any locks, that is, before these two lock_map_acquire()'s.
  1815. *
  1816. * However, that would result in:
  1817. *
  1818. * A(W1)
  1819. * WFC(C)
  1820. * A(W1)
  1821. * C(C)
  1822. *
  1823. * Which would create W1->C->W1 dependencies, even though there is no
  1824. * actual deadlock possible. There are two solutions, using a
  1825. * read-recursive acquire on the work(queue) 'locks', but this will then
  1826. * hit the lockdep limitation on recursive locks, or simply discard
  1827. * these locks.
  1828. *
  1829. * AFAICT there is no possible deadlock scenario between the
  1830. * flush_work() and complete() primitives (except for single-threaded
  1831. * workqueues), so hiding them isn't a problem.
  1832. */
  1833. lockdep_invariant_state(true);
  1834. trace_workqueue_execute_start(work);
  1835. worker->current_func(work);
  1836. /*
  1837. * While we must be careful to not use "work" after this, the trace
  1838. * point will only record its address.
  1839. */
  1840. trace_workqueue_execute_end(work);
  1841. lock_map_release(&lockdep_map);
  1842. lock_map_release(&pwq->wq->lockdep_map);
  1843. if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
  1844. pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
  1845. " last function: %pf\n",
  1846. current->comm, preempt_count(), task_pid_nr(current),
  1847. worker->current_func);
  1848. debug_show_held_locks(current);
  1849. dump_stack();
  1850. }
  1851. /*
  1852. * The following prevents a kworker from hogging CPU on !PREEMPT
  1853. * kernels, where a requeueing work item waiting for something to
  1854. * happen could deadlock with stop_machine as such work item could
  1855. * indefinitely requeue itself while all other CPUs are trapped in
  1856. * stop_machine. At the same time, report a quiescent RCU state so
  1857. * the same condition doesn't freeze RCU.
  1858. */
  1859. cond_resched_rcu_qs();
  1860. spin_lock_irq(&pool->lock);
  1861. /* clear cpu intensive status */
  1862. if (unlikely(cpu_intensive))
  1863. worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
  1864. /* we're done with it, release */
  1865. hash_del(&worker->hentry);
  1866. worker->current_work = NULL;
  1867. worker->current_func = NULL;
  1868. worker->current_pwq = NULL;
  1869. worker->desc_valid = false;
  1870. pwq_dec_nr_in_flight(pwq, work_color);
  1871. }
  1872. /**
  1873. * process_scheduled_works - process scheduled works
  1874. * @worker: self
  1875. *
  1876. * Process all scheduled works. Please note that the scheduled list
  1877. * may change while processing a work, so this function repeatedly
  1878. * fetches a work from the top and executes it.
  1879. *
  1880. * CONTEXT:
  1881. * spin_lock_irq(pool->lock) which may be released and regrabbed
  1882. * multiple times.
  1883. */
  1884. static void process_scheduled_works(struct worker *worker)
  1885. {
  1886. while (!list_empty(&worker->scheduled)) {
  1887. struct work_struct *work = list_first_entry(&worker->scheduled,
  1888. struct work_struct, entry);
  1889. process_one_work(worker, work);
  1890. }
  1891. }
  1892. /**
  1893. * worker_thread - the worker thread function
  1894. * @__worker: self
  1895. *
  1896. * The worker thread function. All workers belong to a worker_pool -
  1897. * either a per-cpu one or dynamic unbound one. These workers process all
  1898. * work items regardless of their specific target workqueue. The only
  1899. * exception is work items which belong to workqueues with a rescuer which
  1900. * will be explained in rescuer_thread().
  1901. *
  1902. * Return: 0
  1903. */
  1904. static int worker_thread(void *__worker)
  1905. {
  1906. struct worker *worker = __worker;
  1907. struct worker_pool *pool = worker->pool;
  1908. /* tell the scheduler that this is a workqueue worker */
  1909. worker->task->flags |= PF_WQ_WORKER;
  1910. woke_up:
  1911. spin_lock_irq(&pool->lock);
  1912. /* am I supposed to die? */
  1913. if (unlikely(worker->flags & WORKER_DIE)) {
  1914. spin_unlock_irq(&pool->lock);
  1915. WARN_ON_ONCE(!list_empty(&worker->entry));
  1916. worker->task->flags &= ~PF_WQ_WORKER;
  1917. set_task_comm(worker->task, "kworker/dying");
  1918. ida_simple_remove(&pool->worker_ida, worker->id);
  1919. worker_detach_from_pool(worker, pool);
  1920. kfree(worker);
  1921. return 0;
  1922. }
  1923. worker_leave_idle(worker);
  1924. recheck:
  1925. /* no more worker necessary? */
  1926. if (!need_more_worker(pool))
  1927. goto sleep;
  1928. /* do we need to manage? */
  1929. if (unlikely(!may_start_working(pool)) && manage_workers(worker))
  1930. goto recheck;
  1931. /*
  1932. * ->scheduled list can only be filled while a worker is
  1933. * preparing to process a work or actually processing it.
  1934. * Make sure nobody diddled with it while I was sleeping.
  1935. */
  1936. WARN_ON_ONCE(!list_empty(&worker->scheduled));
  1937. /*
  1938. * Finish PREP stage. We're guaranteed to have at least one idle
  1939. * worker or that someone else has already assumed the manager
  1940. * role. This is where @worker starts participating in concurrency
  1941. * management if applicable and concurrency management is restored
  1942. * after being rebound. See rebind_workers() for details.
  1943. */
  1944. worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
  1945. do {
  1946. struct work_struct *work =
  1947. list_first_entry(&pool->worklist,
  1948. struct work_struct, entry);
  1949. pool->watchdog_ts = jiffies;
  1950. if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
  1951. /* optimization path, not strictly necessary */
  1952. process_one_work(worker, work);
  1953. if (unlikely(!list_empty(&worker->scheduled)))
  1954. process_scheduled_works(worker);
  1955. } else {
  1956. move_linked_works(work, &worker->scheduled, NULL);
  1957. process_scheduled_works(worker);
  1958. }
  1959. } while (keep_working(pool));
  1960. worker_set_flags(worker, WORKER_PREP);
  1961. sleep:
  1962. /*
  1963. * pool->lock is held and there's no work to process and no need to
  1964. * manage, sleep. Workers are woken up only while holding
  1965. * pool->lock or from local cpu, so setting the current state
  1966. * before releasing pool->lock is enough to prevent losing any
  1967. * event.
  1968. */
  1969. worker_enter_idle(worker);
  1970. __set_current_state(TASK_IDLE);
  1971. spin_unlock_irq(&pool->lock);
  1972. schedule();
  1973. goto woke_up;
  1974. }
  1975. /**
  1976. * rescuer_thread - the rescuer thread function
  1977. * @__rescuer: self
  1978. *
  1979. * Workqueue rescuer thread function. There's one rescuer for each
  1980. * workqueue which has WQ_MEM_RECLAIM set.
  1981. *
  1982. * Regular work processing on a pool may block trying to create a new
  1983. * worker which uses GFP_KERNEL allocation which has slight chance of
  1984. * developing into deadlock if some works currently on the same queue
  1985. * need to be processed to satisfy the GFP_KERNEL allocation. This is
  1986. * the problem rescuer solves.
  1987. *
  1988. * When such condition is possible, the pool summons rescuers of all
  1989. * workqueues which have works queued on the pool and let them process
  1990. * those works so that forward progress can be guaranteed.
  1991. *
  1992. * This should happen rarely.
  1993. *
  1994. * Return: 0
  1995. */
  1996. static int rescuer_thread(void *__rescuer)
  1997. {
  1998. struct worker *rescuer = __rescuer;
  1999. struct workqueue_struct *wq = rescuer->rescue_wq;
  2000. struct list_head *scheduled = &rescuer->scheduled;
  2001. bool should_stop;
  2002. set_user_nice(current, RESCUER_NICE_LEVEL);
  2003. /*
  2004. * Mark rescuer as worker too. As WORKER_PREP is never cleared, it
  2005. * doesn't participate in concurrency management.
  2006. */
  2007. rescuer->task->flags |= PF_WQ_WORKER;
  2008. repeat:
  2009. set_current_state(TASK_IDLE);
  2010. /*
  2011. * By the time the rescuer is requested to stop, the workqueue
  2012. * shouldn't have any work pending, but @wq->maydays may still have
  2013. * pwq(s) queued. This can happen by non-rescuer workers consuming
  2014. * all the work items before the rescuer got to them. Go through
  2015. * @wq->maydays processing before acting on should_stop so that the
  2016. * list is always empty on exit.
  2017. */
  2018. should_stop = kthread_should_stop();
  2019. /* see whether any pwq is asking for help */
  2020. spin_lock_irq(&wq_mayday_lock);
  2021. while (!list_empty(&wq->maydays)) {
  2022. struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
  2023. struct pool_workqueue, mayday_node);
  2024. struct worker_pool *pool = pwq->pool;
  2025. struct work_struct *work, *n;
  2026. bool first = true;
  2027. __set_current_state(TASK_RUNNING);
  2028. list_del_init(&pwq->mayday_node);
  2029. spin_unlock_irq(&wq_mayday_lock);
  2030. worker_attach_to_pool(rescuer, pool);
  2031. spin_lock_irq(&pool->lock);
  2032. rescuer->pool = pool;
  2033. /*
  2034. * Slurp in all works issued via this workqueue and
  2035. * process'em.
  2036. */
  2037. WARN_ON_ONCE(!list_empty(scheduled));
  2038. list_for_each_entry_safe(work, n, &pool->worklist, entry) {
  2039. if (get_work_pwq(work) == pwq) {
  2040. if (first)
  2041. pool->watchdog_ts = jiffies;
  2042. move_linked_works(work, scheduled, &n);
  2043. }
  2044. first = false;
  2045. }
  2046. if (!list_empty(scheduled)) {
  2047. process_scheduled_works(rescuer);
  2048. /*
  2049. * The above execution of rescued work items could
  2050. * have created more to rescue through
  2051. * pwq_activate_first_delayed() or chained
  2052. * queueing. Let's put @pwq back on mayday list so
  2053. * that such back-to-back work items, which may be
  2054. * being used to relieve memory pressure, don't
  2055. * incur MAYDAY_INTERVAL delay inbetween.
  2056. */
  2057. if (need_to_create_worker(pool)) {
  2058. spin_lock(&wq_mayday_lock);
  2059. get_pwq(pwq);
  2060. list_move_tail(&pwq->mayday_node, &wq->maydays);
  2061. spin_unlock(&wq_mayday_lock);
  2062. }
  2063. }
  2064. /*
  2065. * Put the reference grabbed by send_mayday(). @pool won't
  2066. * go away while we're still attached to it.
  2067. */
  2068. put_pwq(pwq);
  2069. /*
  2070. * Leave this pool. If need_more_worker() is %true, notify a
  2071. * regular worker; otherwise, we end up with 0 concurrency
  2072. * and stalling the execution.
  2073. */
  2074. if (need_more_worker(pool))
  2075. wake_up_worker(pool);
  2076. rescuer->pool = NULL;
  2077. spin_unlock_irq(&pool->lock);
  2078. worker_detach_from_pool(rescuer, pool);
  2079. spin_lock_irq(&wq_mayday_lock);
  2080. }
  2081. spin_unlock_irq(&wq_mayday_lock);
  2082. if (should_stop) {
  2083. __set_current_state(TASK_RUNNING);
  2084. rescuer->task->flags &= ~PF_WQ_WORKER;
  2085. return 0;
  2086. }
  2087. /* rescuers should never participate in concurrency management */
  2088. WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
  2089. schedule();
  2090. goto repeat;
  2091. }
  2092. /**
  2093. * check_flush_dependency - check for flush dependency sanity
  2094. * @target_wq: workqueue being flushed
  2095. * @target_work: work item being flushed (NULL for workqueue flushes)
  2096. *
  2097. * %current is trying to flush the whole @target_wq or @target_work on it.
  2098. * If @target_wq doesn't have %WQ_MEM_RECLAIM, verify that %current is not
  2099. * reclaiming memory or running on a workqueue which doesn't have
  2100. * %WQ_MEM_RECLAIM as that can break forward-progress guarantee leading to
  2101. * a deadlock.
  2102. */
  2103. static void check_flush_dependency(struct workqueue_struct *target_wq,
  2104. struct work_struct *target_work)
  2105. {
  2106. work_func_t target_func = target_work ? target_work->func : NULL;
  2107. struct worker *worker;
  2108. if (target_wq->flags & WQ_MEM_RECLAIM)
  2109. return;
  2110. worker = current_wq_worker();
  2111. WARN_ONCE(current->flags & PF_MEMALLOC,
  2112. "workqueue: PF_MEMALLOC task %d(%s) is flushing !WQ_MEM_RECLAIM %s:%pf",
  2113. current->pid, current->comm, target_wq->name, target_func);
  2114. WARN_ONCE(worker && ((worker->current_pwq->wq->flags &
  2115. (WQ_MEM_RECLAIM | __WQ_LEGACY)) == WQ_MEM_RECLAIM),
  2116. "workqueue: WQ_MEM_RECLAIM %s:%pf is flushing !WQ_MEM_RECLAIM %s:%pf",
  2117. worker->current_pwq->wq->name, worker->current_func,
  2118. target_wq->name, target_func);
  2119. }
  2120. struct wq_barrier {
  2121. struct work_struct work;
  2122. struct completion done;
  2123. struct task_struct *task; /* purely informational */
  2124. };
  2125. static void wq_barrier_func(struct work_struct *work)
  2126. {
  2127. struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
  2128. complete(&barr->done);
  2129. }
  2130. /**
  2131. * insert_wq_barrier - insert a barrier work
  2132. * @pwq: pwq to insert barrier into
  2133. * @barr: wq_barrier to insert
  2134. * @target: target work to attach @barr to
  2135. * @worker: worker currently executing @target, NULL if @target is not executing
  2136. *
  2137. * @barr is linked to @target such that @barr is completed only after
  2138. * @target finishes execution. Please note that the ordering
  2139. * guarantee is observed only with respect to @target and on the local
  2140. * cpu.
  2141. *
  2142. * Currently, a queued barrier can't be canceled. This is because
  2143. * try_to_grab_pending() can't determine whether the work to be
  2144. * grabbed is at the head of the queue and thus can't clear LINKED
  2145. * flag of the previous work while there must be a valid next work
  2146. * after a work with LINKED flag set.
  2147. *
  2148. * Note that when @worker is non-NULL, @target may be modified
  2149. * underneath us, so we can't reliably determine pwq from @target.
  2150. *
  2151. * CONTEXT:
  2152. * spin_lock_irq(pool->lock).
  2153. */
  2154. static void insert_wq_barrier(struct pool_workqueue *pwq,
  2155. struct wq_barrier *barr,
  2156. struct work_struct *target, struct worker *worker)
  2157. {
  2158. struct list_head *head;
  2159. unsigned int linked = 0;
  2160. /*
  2161. * debugobject calls are safe here even with pool->lock locked
  2162. * as we know for sure that this will not trigger any of the
  2163. * checks and call back into the fixup functions where we
  2164. * might deadlock.
  2165. */
  2166. INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
  2167. __set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
  2168. /*
  2169. * Explicitly init the crosslock for wq_barrier::done, make its lock
  2170. * key a subkey of the corresponding work. As a result we won't
  2171. * build a dependency between wq_barrier::done and unrelated work.
  2172. */
  2173. lockdep_init_map_crosslock((struct lockdep_map *)&barr->done.map,
  2174. "(complete)wq_barr::done",
  2175. target->lockdep_map.key, 1);
  2176. __init_completion(&barr->done);
  2177. barr->task = current;
  2178. /*
  2179. * If @target is currently being executed, schedule the
  2180. * barrier to the worker; otherwise, put it after @target.
  2181. */
  2182. if (worker)
  2183. head = worker->scheduled.next;
  2184. else {
  2185. unsigned long *bits = work_data_bits(target);
  2186. head = target->entry.next;
  2187. /* there can already be other linked works, inherit and set */
  2188. linked = *bits & WORK_STRUCT_LINKED;
  2189. __set_bit(WORK_STRUCT_LINKED_BIT, bits);
  2190. }
  2191. debug_work_activate(&barr->work);
  2192. insert_work(pwq, &barr->work, head,
  2193. work_color_to_flags(WORK_NO_COLOR) | linked);
  2194. }
  2195. /**
  2196. * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
  2197. * @wq: workqueue being flushed
  2198. * @flush_color: new flush color, < 0 for no-op
  2199. * @work_color: new work color, < 0 for no-op
  2200. *
  2201. * Prepare pwqs for workqueue flushing.
  2202. *
  2203. * If @flush_color is non-negative, flush_color on all pwqs should be
  2204. * -1. If no pwq has in-flight commands at the specified color, all
  2205. * pwq->flush_color's stay at -1 and %false is returned. If any pwq
  2206. * has in flight commands, its pwq->flush_color is set to
  2207. * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
  2208. * wakeup logic is armed and %true is returned.
  2209. *
  2210. * The caller should have initialized @wq->first_flusher prior to
  2211. * calling this function with non-negative @flush_color. If
  2212. * @flush_color is negative, no flush color update is done and %false
  2213. * is returned.
  2214. *
  2215. * If @work_color is non-negative, all pwqs should have the same
  2216. * work_color which is previous to @work_color and all will be
  2217. * advanced to @work_color.
  2218. *
  2219. * CONTEXT:
  2220. * mutex_lock(wq->mutex).
  2221. *
  2222. * Return:
  2223. * %true if @flush_color >= 0 and there's something to flush. %false
  2224. * otherwise.
  2225. */
  2226. static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
  2227. int flush_color, int work_color)
  2228. {
  2229. bool wait = false;
  2230. struct pool_workqueue *pwq;
  2231. if (flush_color >= 0) {
  2232. WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
  2233. atomic_set(&wq->nr_pwqs_to_flush, 1);
  2234. }
  2235. for_each_pwq(pwq, wq) {
  2236. struct worker_pool *pool = pwq->pool;
  2237. spin_lock_irq(&pool->lock);
  2238. if (flush_color >= 0) {
  2239. WARN_ON_ONCE(pwq->flush_color != -1);
  2240. if (pwq->nr_in_flight[flush_color]) {
  2241. pwq->flush_color = flush_color;
  2242. atomic_inc(&wq->nr_pwqs_to_flush);
  2243. wait = true;
  2244. }
  2245. }
  2246. if (work_color >= 0) {
  2247. WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
  2248. pwq->work_color = work_color;
  2249. }
  2250. spin_unlock_irq(&pool->lock);
  2251. }
  2252. if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
  2253. complete(&wq->first_flusher->done);
  2254. return wait;
  2255. }
  2256. /**
  2257. * flush_workqueue - ensure that any scheduled work has run to completion.
  2258. * @wq: workqueue to flush
  2259. *
  2260. * This function sleeps until all work items which were queued on entry
  2261. * have finished execution, but it is not livelocked by new incoming ones.
  2262. */
  2263. void flush_workqueue(struct workqueue_struct *wq)
  2264. {
  2265. struct wq_flusher this_flusher = {
  2266. .list = LIST_HEAD_INIT(this_flusher.list),
  2267. .flush_color = -1,
  2268. .done = COMPLETION_INITIALIZER_ONSTACK(this_flusher.done),
  2269. };
  2270. int next_color;
  2271. if (WARN_ON(!wq_online))
  2272. return;
  2273. lock_map_acquire(&wq->lockdep_map);
  2274. lock_map_release(&wq->lockdep_map);
  2275. mutex_lock(&wq->mutex);
  2276. /*
  2277. * Start-to-wait phase
  2278. */
  2279. next_color = work_next_color(wq->work_color);
  2280. if (next_color != wq->flush_color) {
  2281. /*
  2282. * Color space is not full. The current work_color
  2283. * becomes our flush_color and work_color is advanced
  2284. * by one.
  2285. */
  2286. WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
  2287. this_flusher.flush_color = wq->work_color;
  2288. wq->work_color = next_color;
  2289. if (!wq->first_flusher) {
  2290. /* no flush in progress, become the first flusher */
  2291. WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
  2292. wq->first_flusher = &this_flusher;
  2293. if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
  2294. wq->work_color)) {
  2295. /* nothing to flush, done */
  2296. wq->flush_color = next_color;
  2297. wq->first_flusher = NULL;
  2298. goto out_unlock;
  2299. }
  2300. } else {
  2301. /* wait in queue */
  2302. WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
  2303. list_add_tail(&this_flusher.list, &wq->flusher_queue);
  2304. flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
  2305. }
  2306. } else {
  2307. /*
  2308. * Oops, color space is full, wait on overflow queue.
  2309. * The next flush completion will assign us
  2310. * flush_color and transfer to flusher_queue.
  2311. */
  2312. list_add_tail(&this_flusher.list, &wq->flusher_overflow);
  2313. }
  2314. check_flush_dependency(wq, NULL);
  2315. mutex_unlock(&wq->mutex);
  2316. wait_for_completion(&this_flusher.done);
  2317. /*
  2318. * Wake-up-and-cascade phase
  2319. *
  2320. * First flushers are responsible for cascading flushes and
  2321. * handling overflow. Non-first flushers can simply return.
  2322. */
  2323. if (wq->first_flusher != &this_flusher)
  2324. return;
  2325. mutex_lock(&wq->mutex);
  2326. /* we might have raced, check again with mutex held */
  2327. if (wq->first_flusher != &this_flusher)
  2328. goto out_unlock;
  2329. wq->first_flusher = NULL;
  2330. WARN_ON_ONCE(!list_empty(&this_flusher.list));
  2331. WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
  2332. while (true) {
  2333. struct wq_flusher *next, *tmp;
  2334. /* complete all the flushers sharing the current flush color */
  2335. list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
  2336. if (next->flush_color != wq->flush_color)
  2337. break;
  2338. list_del_init(&next->list);
  2339. complete(&next->done);
  2340. }
  2341. WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
  2342. wq->flush_color != work_next_color(wq->work_color));
  2343. /* this flush_color is finished, advance by one */
  2344. wq->flush_color = work_next_color(wq->flush_color);
  2345. /* one color has been freed, handle overflow queue */
  2346. if (!list_empty(&wq->flusher_overflow)) {
  2347. /*
  2348. * Assign the same color to all overflowed
  2349. * flushers, advance work_color and append to
  2350. * flusher_queue. This is the start-to-wait
  2351. * phase for these overflowed flushers.
  2352. */
  2353. list_for_each_entry(tmp, &wq->flusher_overflow, list)
  2354. tmp->flush_color = wq->work_color;
  2355. wq->work_color = work_next_color(wq->work_color);
  2356. list_splice_tail_init(&wq->flusher_overflow,
  2357. &wq->flusher_queue);
  2358. flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
  2359. }
  2360. if (list_empty(&wq->flusher_queue)) {
  2361. WARN_ON_ONCE(wq->flush_color != wq->work_color);
  2362. break;
  2363. }
  2364. /*
  2365. * Need to flush more colors. Make the next flusher
  2366. * the new first flusher and arm pwqs.
  2367. */
  2368. WARN_ON_ONCE(wq->flush_color == wq->work_color);
  2369. WARN_ON_ONCE(wq->flush_color != next->flush_color);
  2370. list_del_init(&next->list);
  2371. wq->first_flusher = next;
  2372. if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
  2373. break;
  2374. /*
  2375. * Meh... this color is already done, clear first
  2376. * flusher and repeat cascading.
  2377. */
  2378. wq->first_flusher = NULL;
  2379. }
  2380. out_unlock:
  2381. mutex_unlock(&wq->mutex);
  2382. }
  2383. EXPORT_SYMBOL(flush_workqueue);
  2384. /**
  2385. * drain_workqueue - drain a workqueue
  2386. * @wq: workqueue to drain
  2387. *
  2388. * Wait until the workqueue becomes empty. While draining is in progress,
  2389. * only chain queueing is allowed. IOW, only currently pending or running
  2390. * work items on @wq can queue further work items on it. @wq is flushed
  2391. * repeatedly until it becomes empty. The number of flushing is determined
  2392. * by the depth of chaining and should be relatively short. Whine if it
  2393. * takes too long.
  2394. */
  2395. void drain_workqueue(struct workqueue_struct *wq)
  2396. {
  2397. unsigned int flush_cnt = 0;
  2398. struct pool_workqueue *pwq;
  2399. /*
  2400. * __queue_work() needs to test whether there are drainers, is much
  2401. * hotter than drain_workqueue() and already looks at @wq->flags.
  2402. * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
  2403. */
  2404. mutex_lock(&wq->mutex);
  2405. if (!wq->nr_drainers++)
  2406. wq->flags |= __WQ_DRAINING;
  2407. mutex_unlock(&wq->mutex);
  2408. reflush:
  2409. flush_workqueue(wq);
  2410. mutex_lock(&wq->mutex);
  2411. for_each_pwq(pwq, wq) {
  2412. bool drained;
  2413. spin_lock_irq(&pwq->pool->lock);
  2414. drained = !pwq->nr_active && list_empty(&pwq->delayed_works);
  2415. spin_unlock_irq(&pwq->pool->lock);
  2416. if (drained)
  2417. continue;
  2418. if (++flush_cnt == 10 ||
  2419. (flush_cnt % 100 == 0 && flush_cnt <= 1000))
  2420. pr_warn("workqueue %s: drain_workqueue() isn't complete after %u tries\n",
  2421. wq->name, flush_cnt);
  2422. mutex_unlock(&wq->mutex);
  2423. goto reflush;
  2424. }
  2425. if (!--wq->nr_drainers)
  2426. wq->flags &= ~__WQ_DRAINING;
  2427. mutex_unlock(&wq->mutex);
  2428. }
  2429. EXPORT_SYMBOL_GPL(drain_workqueue);
  2430. static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr)
  2431. {
  2432. struct worker *worker = NULL;
  2433. struct worker_pool *pool;
  2434. struct pool_workqueue *pwq;
  2435. might_sleep();
  2436. local_irq_disable();
  2437. pool = get_work_pool(work);
  2438. if (!pool) {
  2439. local_irq_enable();
  2440. return false;
  2441. }
  2442. spin_lock(&pool->lock);
  2443. /* see the comment in try_to_grab_pending() with the same code */
  2444. pwq = get_work_pwq(work);
  2445. if (pwq) {
  2446. if (unlikely(pwq->pool != pool))
  2447. goto already_gone;
  2448. } else {
  2449. worker = find_worker_executing_work(pool, work);
  2450. if (!worker)
  2451. goto already_gone;
  2452. pwq = worker->current_pwq;
  2453. }
  2454. check_flush_dependency(pwq->wq, work);
  2455. insert_wq_barrier(pwq, barr, work, worker);
  2456. spin_unlock_irq(&pool->lock);
  2457. /*
  2458. * Force a lock recursion deadlock when using flush_work() inside a
  2459. * single-threaded or rescuer equipped workqueue.
  2460. *
  2461. * For single threaded workqueues the deadlock happens when the work
  2462. * is after the work issuing the flush_work(). For rescuer equipped
  2463. * workqueues the deadlock happens when the rescuer stalls, blocking
  2464. * forward progress.
  2465. */
  2466. if (pwq->wq->saved_max_active == 1 || pwq->wq->rescuer) {
  2467. lock_map_acquire(&pwq->wq->lockdep_map);
  2468. lock_map_release(&pwq->wq->lockdep_map);
  2469. }
  2470. return true;
  2471. already_gone:
  2472. spin_unlock_irq(&pool->lock);
  2473. return false;
  2474. }
  2475. /**
  2476. * flush_work - wait for a work to finish executing the last queueing instance
  2477. * @work: the work to flush
  2478. *
  2479. * Wait until @work has finished execution. @work is guaranteed to be idle
  2480. * on return if it hasn't been requeued since flush started.
  2481. *
  2482. * Return:
  2483. * %true if flush_work() waited for the work to finish execution,
  2484. * %false if it was already idle.
  2485. */
  2486. bool flush_work(struct work_struct *work)
  2487. {
  2488. struct wq_barrier barr;
  2489. if (WARN_ON(!wq_online))
  2490. return false;
  2491. lock_map_acquire(&work->lockdep_map);
  2492. lock_map_release(&work->lockdep_map);
  2493. if (start_flush_work(work, &barr)) {
  2494. wait_for_completion(&barr.done);
  2495. destroy_work_on_stack(&barr.work);
  2496. return true;
  2497. } else {
  2498. return false;
  2499. }
  2500. }
  2501. EXPORT_SYMBOL_GPL(flush_work);
  2502. struct cwt_wait {
  2503. wait_queue_entry_t wait;
  2504. struct work_struct *work;
  2505. };
  2506. static int cwt_wakefn(wait_queue_entry_t *wait, unsigned mode, int sync, void *key)
  2507. {
  2508. struct cwt_wait *cwait = container_of(wait, struct cwt_wait, wait);
  2509. if (cwait->work != key)
  2510. return 0;
  2511. return autoremove_wake_function(wait, mode, sync, key);
  2512. }
  2513. static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
  2514. {
  2515. static DECLARE_WAIT_QUEUE_HEAD(cancel_waitq);
  2516. unsigned long flags;
  2517. int ret;
  2518. do {
  2519. ret = try_to_grab_pending(work, is_dwork, &flags);
  2520. /*
  2521. * If someone else is already canceling, wait for it to
  2522. * finish. flush_work() doesn't work for PREEMPT_NONE
  2523. * because we may get scheduled between @work's completion
  2524. * and the other canceling task resuming and clearing
  2525. * CANCELING - flush_work() will return false immediately
  2526. * as @work is no longer busy, try_to_grab_pending() will
  2527. * return -ENOENT as @work is still being canceled and the
  2528. * other canceling task won't be able to clear CANCELING as
  2529. * we're hogging the CPU.
  2530. *
  2531. * Let's wait for completion using a waitqueue. As this
  2532. * may lead to the thundering herd problem, use a custom
  2533. * wake function which matches @work along with exclusive
  2534. * wait and wakeup.
  2535. */
  2536. if (unlikely(ret == -ENOENT)) {
  2537. struct cwt_wait cwait;
  2538. init_wait(&cwait.wait);
  2539. cwait.wait.func = cwt_wakefn;
  2540. cwait.work = work;
  2541. prepare_to_wait_exclusive(&cancel_waitq, &cwait.wait,
  2542. TASK_UNINTERRUPTIBLE);
  2543. if (work_is_canceling(work))
  2544. schedule();
  2545. finish_wait(&cancel_waitq, &cwait.wait);
  2546. }
  2547. } while (unlikely(ret < 0));
  2548. /* tell other tasks trying to grab @work to back off */
  2549. mark_work_canceling(work);
  2550. local_irq_restore(flags);
  2551. /*
  2552. * This allows canceling during early boot. We know that @work
  2553. * isn't executing.
  2554. */
  2555. if (wq_online)
  2556. flush_work(work);
  2557. clear_work_data(work);
  2558. /*
  2559. * Paired with prepare_to_wait() above so that either
  2560. * waitqueue_active() is visible here or !work_is_canceling() is
  2561. * visible there.
  2562. */
  2563. smp_mb();
  2564. if (waitqueue_active(&cancel_waitq))
  2565. __wake_up(&cancel_waitq, TASK_NORMAL, 1, work);
  2566. return ret;
  2567. }
  2568. /**
  2569. * cancel_work_sync - cancel a work and wait for it to finish
  2570. * @work: the work to cancel
  2571. *
  2572. * Cancel @work and wait for its execution to finish. This function
  2573. * can be used even if the work re-queues itself or migrates to
  2574. * another workqueue. On return from this function, @work is
  2575. * guaranteed to be not pending or executing on any CPU.
  2576. *
  2577. * cancel_work_sync(&delayed_work->work) must not be used for
  2578. * delayed_work's. Use cancel_delayed_work_sync() instead.
  2579. *
  2580. * The caller must ensure that the workqueue on which @work was last
  2581. * queued can't be destroyed before this function returns.
  2582. *
  2583. * Return:
  2584. * %true if @work was pending, %false otherwise.
  2585. */
  2586. bool cancel_work_sync(struct work_struct *work)
  2587. {
  2588. return __cancel_work_timer(work, false);
  2589. }
  2590. EXPORT_SYMBOL_GPL(cancel_work_sync);
  2591. /**
  2592. * flush_delayed_work - wait for a dwork to finish executing the last queueing
  2593. * @dwork: the delayed work to flush
  2594. *
  2595. * Delayed timer is cancelled and the pending work is queued for
  2596. * immediate execution. Like flush_work(), this function only
  2597. * considers the last queueing instance of @dwork.
  2598. *
  2599. * Return:
  2600. * %true if flush_work() waited for the work to finish execution,
  2601. * %false if it was already idle.
  2602. */
  2603. bool flush_delayed_work(struct delayed_work *dwork)
  2604. {
  2605. local_irq_disable();
  2606. if (del_timer_sync(&dwork->timer))
  2607. __queue_work(dwork->cpu, dwork->wq, &dwork->work);
  2608. local_irq_enable();
  2609. return flush_work(&dwork->work);
  2610. }
  2611. EXPORT_SYMBOL(flush_delayed_work);
  2612. static bool __cancel_work(struct work_struct *work, bool is_dwork)
  2613. {
  2614. unsigned long flags;
  2615. int ret;
  2616. do {
  2617. ret = try_to_grab_pending(work, is_dwork, &flags);
  2618. } while (unlikely(ret == -EAGAIN));
  2619. if (unlikely(ret < 0))
  2620. return false;
  2621. set_work_pool_and_clear_pending(work, get_work_pool_id(work));
  2622. local_irq_restore(flags);
  2623. return ret;
  2624. }
  2625. /*
  2626. * See cancel_delayed_work()
  2627. */
  2628. bool cancel_work(struct work_struct *work)
  2629. {
  2630. return __cancel_work(work, false);
  2631. }
  2632. /**
  2633. * cancel_delayed_work - cancel a delayed work
  2634. * @dwork: delayed_work to cancel
  2635. *
  2636. * Kill off a pending delayed_work.
  2637. *
  2638. * Return: %true if @dwork was pending and canceled; %false if it wasn't
  2639. * pending.
  2640. *
  2641. * Note:
  2642. * The work callback function may still be running on return, unless
  2643. * it returns %true and the work doesn't re-arm itself. Explicitly flush or
  2644. * use cancel_delayed_work_sync() to wait on it.
  2645. *
  2646. * This function is safe to call from any context including IRQ handler.
  2647. */
  2648. bool cancel_delayed_work(struct delayed_work *dwork)
  2649. {
  2650. return __cancel_work(&dwork->work, true);
  2651. }
  2652. EXPORT_SYMBOL(cancel_delayed_work);
  2653. /**
  2654. * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
  2655. * @dwork: the delayed work cancel
  2656. *
  2657. * This is cancel_work_sync() for delayed works.
  2658. *
  2659. * Return:
  2660. * %true if @dwork was pending, %false otherwise.
  2661. */
  2662. bool cancel_delayed_work_sync(struct delayed_work *dwork)
  2663. {
  2664. return __cancel_work_timer(&dwork->work, true);
  2665. }
  2666. EXPORT_SYMBOL(cancel_delayed_work_sync);
  2667. /**
  2668. * schedule_on_each_cpu - execute a function synchronously on each online CPU
  2669. * @func: the function to call
  2670. *
  2671. * schedule_on_each_cpu() executes @func on each online CPU using the
  2672. * system workqueue and blocks until all CPUs have completed.
  2673. * schedule_on_each_cpu() is very slow.
  2674. *
  2675. * Return:
  2676. * 0 on success, -errno on failure.
  2677. */
  2678. int schedule_on_each_cpu(work_func_t func)
  2679. {
  2680. int cpu;
  2681. struct work_struct __percpu *works;
  2682. works = alloc_percpu(struct work_struct);
  2683. if (!works)
  2684. return -ENOMEM;
  2685. get_online_cpus();
  2686. for_each_online_cpu(cpu) {
  2687. struct work_struct *work = per_cpu_ptr(works, cpu);
  2688. INIT_WORK(work, func);
  2689. schedule_work_on(cpu, work);
  2690. }
  2691. for_each_online_cpu(cpu)
  2692. flush_work(per_cpu_ptr(works, cpu));
  2693. put_online_cpus();
  2694. free_percpu(works);
  2695. return 0;
  2696. }
  2697. /**
  2698. * execute_in_process_context - reliably execute the routine with user context
  2699. * @fn: the function to execute
  2700. * @ew: guaranteed storage for the execute work structure (must
  2701. * be available when the work executes)
  2702. *
  2703. * Executes the function immediately if process context is available,
  2704. * otherwise schedules the function for delayed execution.
  2705. *
  2706. * Return: 0 - function was executed
  2707. * 1 - function was scheduled for execution
  2708. */
  2709. int execute_in_process_context(work_func_t fn, struct execute_work *ew)
  2710. {
  2711. if (!in_interrupt()) {
  2712. fn(&ew->work);
  2713. return 0;
  2714. }
  2715. INIT_WORK(&ew->work, fn);
  2716. schedule_work(&ew->work);
  2717. return 1;
  2718. }
  2719. EXPORT_SYMBOL_GPL(execute_in_process_context);
  2720. /**
  2721. * free_workqueue_attrs - free a workqueue_attrs
  2722. * @attrs: workqueue_attrs to free
  2723. *
  2724. * Undo alloc_workqueue_attrs().
  2725. */
  2726. void free_workqueue_attrs(struct workqueue_attrs *attrs)
  2727. {
  2728. if (attrs) {
  2729. free_cpumask_var(attrs->cpumask);
  2730. kfree(attrs);
  2731. }
  2732. }
  2733. /**
  2734. * alloc_workqueue_attrs - allocate a workqueue_attrs
  2735. * @gfp_mask: allocation mask to use
  2736. *
  2737. * Allocate a new workqueue_attrs, initialize with default settings and
  2738. * return it.
  2739. *
  2740. * Return: The allocated new workqueue_attr on success. %NULL on failure.
  2741. */
  2742. struct workqueue_attrs *alloc_workqueue_attrs(gfp_t gfp_mask)
  2743. {
  2744. struct workqueue_attrs *attrs;
  2745. attrs = kzalloc(sizeof(*attrs), gfp_mask);
  2746. if (!attrs)
  2747. goto fail;
  2748. if (!alloc_cpumask_var(&attrs->cpumask, gfp_mask))
  2749. goto fail;
  2750. cpumask_copy(attrs->cpumask, cpu_possible_mask);
  2751. return attrs;
  2752. fail:
  2753. free_workqueue_attrs(attrs);
  2754. return NULL;
  2755. }
  2756. static void copy_workqueue_attrs(struct workqueue_attrs *to,
  2757. const struct workqueue_attrs *from)
  2758. {
  2759. to->nice = from->nice;
  2760. cpumask_copy(to->cpumask, from->cpumask);
  2761. /*
  2762. * Unlike hash and equality test, this function doesn't ignore
  2763. * ->no_numa as it is used for both pool and wq attrs. Instead,
  2764. * get_unbound_pool() explicitly clears ->no_numa after copying.
  2765. */
  2766. to->no_numa = from->no_numa;
  2767. }
  2768. /* hash value of the content of @attr */
  2769. static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
  2770. {
  2771. u32 hash = 0;
  2772. hash = jhash_1word(attrs->nice, hash);
  2773. hash = jhash(cpumask_bits(attrs->cpumask),
  2774. BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
  2775. return hash;
  2776. }
  2777. /* content equality test */
  2778. static bool wqattrs_equal(const struct workqueue_attrs *a,
  2779. const struct workqueue_attrs *b)
  2780. {
  2781. if (a->nice != b->nice)
  2782. return false;
  2783. if (!cpumask_equal(a->cpumask, b->cpumask))
  2784. return false;
  2785. return true;
  2786. }
  2787. /**
  2788. * init_worker_pool - initialize a newly zalloc'd worker_pool
  2789. * @pool: worker_pool to initialize
  2790. *
  2791. * Initialize a newly zalloc'd @pool. It also allocates @pool->attrs.
  2792. *
  2793. * Return: 0 on success, -errno on failure. Even on failure, all fields
  2794. * inside @pool proper are initialized and put_unbound_pool() can be called
  2795. * on @pool safely to release it.
  2796. */
  2797. static int init_worker_pool(struct worker_pool *pool)
  2798. {
  2799. spin_lock_init(&pool->lock);
  2800. pool->id = -1;
  2801. pool->cpu = -1;
  2802. pool->node = NUMA_NO_NODE;
  2803. pool->flags |= POOL_DISASSOCIATED;
  2804. pool->watchdog_ts = jiffies;
  2805. INIT_LIST_HEAD(&pool->worklist);
  2806. INIT_LIST_HEAD(&pool->idle_list);
  2807. hash_init(pool->busy_hash);
  2808. timer_setup(&pool->idle_timer, idle_worker_timeout, TIMER_DEFERRABLE);
  2809. timer_setup(&pool->mayday_timer, pool_mayday_timeout, 0);
  2810. mutex_init(&pool->manager_arb);
  2811. mutex_init(&pool->attach_mutex);
  2812. INIT_LIST_HEAD(&pool->workers);
  2813. ida_init(&pool->worker_ida);
  2814. INIT_HLIST_NODE(&pool->hash_node);
  2815. pool->refcnt = 1;
  2816. /* shouldn't fail above this point */
  2817. pool->attrs = alloc_workqueue_attrs(GFP_KERNEL);
  2818. if (!pool->attrs)
  2819. return -ENOMEM;
  2820. return 0;
  2821. }
  2822. static void rcu_free_wq(struct rcu_head *rcu)
  2823. {
  2824. struct workqueue_struct *wq =
  2825. container_of(rcu, struct workqueue_struct, rcu);
  2826. if (!(wq->flags & WQ_UNBOUND))
  2827. free_percpu(wq->cpu_pwqs);
  2828. else
  2829. free_workqueue_attrs(wq->unbound_attrs);
  2830. kfree(wq->rescuer);
  2831. kfree(wq);
  2832. }
  2833. static void rcu_free_pool(struct rcu_head *rcu)
  2834. {
  2835. struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
  2836. ida_destroy(&pool->worker_ida);
  2837. free_workqueue_attrs(pool->attrs);
  2838. kfree(pool);
  2839. }
  2840. /**
  2841. * put_unbound_pool - put a worker_pool
  2842. * @pool: worker_pool to put
  2843. *
  2844. * Put @pool. If its refcnt reaches zero, it gets destroyed in sched-RCU
  2845. * safe manner. get_unbound_pool() calls this function on its failure path
  2846. * and this function should be able to release pools which went through,
  2847. * successfully or not, init_worker_pool().
  2848. *
  2849. * Should be called with wq_pool_mutex held.
  2850. */
  2851. static void put_unbound_pool(struct worker_pool *pool)
  2852. {
  2853. DECLARE_COMPLETION_ONSTACK(detach_completion);
  2854. struct worker *worker;
  2855. lockdep_assert_held(&wq_pool_mutex);
  2856. if (--pool->refcnt)
  2857. return;
  2858. /* sanity checks */
  2859. if (WARN_ON(!(pool->cpu < 0)) ||
  2860. WARN_ON(!list_empty(&pool->worklist)))
  2861. return;
  2862. /* release id and unhash */
  2863. if (pool->id >= 0)
  2864. idr_remove(&worker_pool_idr, pool->id);
  2865. hash_del(&pool->hash_node);
  2866. /*
  2867. * Become the manager and destroy all workers. Grabbing
  2868. * manager_arb prevents @pool's workers from blocking on
  2869. * attach_mutex.
  2870. */
  2871. mutex_lock(&pool->manager_arb);
  2872. spin_lock_irq(&pool->lock);
  2873. while ((worker = first_idle_worker(pool)))
  2874. destroy_worker(worker);
  2875. WARN_ON(pool->nr_workers || pool->nr_idle);
  2876. spin_unlock_irq(&pool->lock);
  2877. mutex_lock(&pool->attach_mutex);
  2878. if (!list_empty(&pool->workers))
  2879. pool->detach_completion = &detach_completion;
  2880. mutex_unlock(&pool->attach_mutex);
  2881. if (pool->detach_completion)
  2882. wait_for_completion(pool->detach_completion);
  2883. mutex_unlock(&pool->manager_arb);
  2884. /* shut down the timers */
  2885. del_timer_sync(&pool->idle_timer);
  2886. del_timer_sync(&pool->mayday_timer);
  2887. /* sched-RCU protected to allow dereferences from get_work_pool() */
  2888. call_rcu_sched(&pool->rcu, rcu_free_pool);
  2889. }
  2890. /**
  2891. * get_unbound_pool - get a worker_pool with the specified attributes
  2892. * @attrs: the attributes of the worker_pool to get
  2893. *
  2894. * Obtain a worker_pool which has the same attributes as @attrs, bump the
  2895. * reference count and return it. If there already is a matching
  2896. * worker_pool, it will be used; otherwise, this function attempts to
  2897. * create a new one.
  2898. *
  2899. * Should be called with wq_pool_mutex held.
  2900. *
  2901. * Return: On success, a worker_pool with the same attributes as @attrs.
  2902. * On failure, %NULL.
  2903. */
  2904. static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
  2905. {
  2906. u32 hash = wqattrs_hash(attrs);
  2907. struct worker_pool *pool;
  2908. int node;
  2909. int target_node = NUMA_NO_NODE;
  2910. lockdep_assert_held(&wq_pool_mutex);
  2911. /* do we already have a matching pool? */
  2912. hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
  2913. if (wqattrs_equal(pool->attrs, attrs)) {
  2914. pool->refcnt++;
  2915. return pool;
  2916. }
  2917. }
  2918. /* if cpumask is contained inside a NUMA node, we belong to that node */
  2919. if (wq_numa_enabled) {
  2920. for_each_node(node) {
  2921. if (cpumask_subset(attrs->cpumask,
  2922. wq_numa_possible_cpumask[node])) {
  2923. target_node = node;
  2924. break;
  2925. }
  2926. }
  2927. }
  2928. /* nope, create a new one */
  2929. pool = kzalloc_node(sizeof(*pool), GFP_KERNEL, target_node);
  2930. if (!pool || init_worker_pool(pool) < 0)
  2931. goto fail;
  2932. lockdep_set_subclass(&pool->lock, 1); /* see put_pwq() */
  2933. copy_workqueue_attrs(pool->attrs, attrs);
  2934. pool->node = target_node;
  2935. /*
  2936. * no_numa isn't a worker_pool attribute, always clear it. See
  2937. * 'struct workqueue_attrs' comments for detail.
  2938. */
  2939. pool->attrs->no_numa = false;
  2940. if (worker_pool_assign_id(pool) < 0)
  2941. goto fail;
  2942. /* create and start the initial worker */
  2943. if (wq_online && !create_worker(pool))
  2944. goto fail;
  2945. /* install */
  2946. hash_add(unbound_pool_hash, &pool->hash_node, hash);
  2947. return pool;
  2948. fail:
  2949. if (pool)
  2950. put_unbound_pool(pool);
  2951. return NULL;
  2952. }
  2953. static void rcu_free_pwq(struct rcu_head *rcu)
  2954. {
  2955. kmem_cache_free(pwq_cache,
  2956. container_of(rcu, struct pool_workqueue, rcu));
  2957. }
  2958. /*
  2959. * Scheduled on system_wq by put_pwq() when an unbound pwq hits zero refcnt
  2960. * and needs to be destroyed.
  2961. */
  2962. static void pwq_unbound_release_workfn(struct work_struct *work)
  2963. {
  2964. struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
  2965. unbound_release_work);
  2966. struct workqueue_struct *wq = pwq->wq;
  2967. struct worker_pool *pool = pwq->pool;
  2968. bool is_last;
  2969. if (WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND)))
  2970. return;
  2971. mutex_lock(&wq->mutex);
  2972. list_del_rcu(&pwq->pwqs_node);
  2973. is_last = list_empty(&wq->pwqs);
  2974. mutex_unlock(&wq->mutex);
  2975. mutex_lock(&wq_pool_mutex);
  2976. put_unbound_pool(pool);
  2977. mutex_unlock(&wq_pool_mutex);
  2978. call_rcu_sched(&pwq->rcu, rcu_free_pwq);
  2979. /*
  2980. * If we're the last pwq going away, @wq is already dead and no one
  2981. * is gonna access it anymore. Schedule RCU free.
  2982. */
  2983. if (is_last)
  2984. call_rcu_sched(&wq->rcu, rcu_free_wq);
  2985. }
  2986. /**
  2987. * pwq_adjust_max_active - update a pwq's max_active to the current setting
  2988. * @pwq: target pool_workqueue
  2989. *
  2990. * If @pwq isn't freezing, set @pwq->max_active to the associated
  2991. * workqueue's saved_max_active and activate delayed work items
  2992. * accordingly. If @pwq is freezing, clear @pwq->max_active to zero.
  2993. */
  2994. static void pwq_adjust_max_active(struct pool_workqueue *pwq)
  2995. {
  2996. struct workqueue_struct *wq = pwq->wq;
  2997. bool freezable = wq->flags & WQ_FREEZABLE;
  2998. unsigned long flags;
  2999. /* for @wq->saved_max_active */
  3000. lockdep_assert_held(&wq->mutex);
  3001. /* fast exit for non-freezable wqs */
  3002. if (!freezable && pwq->max_active == wq->saved_max_active)
  3003. return;
  3004. /* this function can be called during early boot w/ irq disabled */
  3005. spin_lock_irqsave(&pwq->pool->lock, flags);
  3006. /*
  3007. * During [un]freezing, the caller is responsible for ensuring that
  3008. * this function is called at least once after @workqueue_freezing
  3009. * is updated and visible.
  3010. */
  3011. if (!freezable || !workqueue_freezing) {
  3012. pwq->max_active = wq->saved_max_active;
  3013. while (!list_empty(&pwq->delayed_works) &&
  3014. pwq->nr_active < pwq->max_active)
  3015. pwq_activate_first_delayed(pwq);
  3016. /*
  3017. * Need to kick a worker after thawed or an unbound wq's
  3018. * max_active is bumped. It's a slow path. Do it always.
  3019. */
  3020. wake_up_worker(pwq->pool);
  3021. } else {
  3022. pwq->max_active = 0;
  3023. }
  3024. spin_unlock_irqrestore(&pwq->pool->lock, flags);
  3025. }
  3026. /* initialize newly alloced @pwq which is associated with @wq and @pool */
  3027. static void init_pwq(struct pool_workqueue *pwq, struct workqueue_struct *wq,
  3028. struct worker_pool *pool)
  3029. {
  3030. BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
  3031. memset(pwq, 0, sizeof(*pwq));
  3032. pwq->pool = pool;
  3033. pwq->wq = wq;
  3034. pwq->flush_color = -1;
  3035. pwq->refcnt = 1;
  3036. INIT_LIST_HEAD(&pwq->delayed_works);
  3037. INIT_LIST_HEAD(&pwq->pwqs_node);
  3038. INIT_LIST_HEAD(&pwq->mayday_node);
  3039. INIT_WORK(&pwq->unbound_release_work, pwq_unbound_release_workfn);
  3040. }
  3041. /* sync @pwq with the current state of its associated wq and link it */
  3042. static void link_pwq(struct pool_workqueue *pwq)
  3043. {
  3044. struct workqueue_struct *wq = pwq->wq;
  3045. lockdep_assert_held(&wq->mutex);
  3046. /* may be called multiple times, ignore if already linked */
  3047. if (!list_empty(&pwq->pwqs_node))
  3048. return;
  3049. /* set the matching work_color */
  3050. pwq->work_color = wq->work_color;
  3051. /* sync max_active to the current setting */
  3052. pwq_adjust_max_active(pwq);
  3053. /* link in @pwq */
  3054. list_add_rcu(&pwq->pwqs_node, &wq->pwqs);
  3055. }
  3056. /* obtain a pool matching @attr and create a pwq associating the pool and @wq */
  3057. static struct pool_workqueue *alloc_unbound_pwq(struct workqueue_struct *wq,
  3058. const struct workqueue_attrs *attrs)
  3059. {
  3060. struct worker_pool *pool;
  3061. struct pool_workqueue *pwq;
  3062. lockdep_assert_held(&wq_pool_mutex);
  3063. pool = get_unbound_pool(attrs);
  3064. if (!pool)
  3065. return NULL;
  3066. pwq = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL, pool->node);
  3067. if (!pwq) {
  3068. put_unbound_pool(pool);
  3069. return NULL;
  3070. }
  3071. init_pwq(pwq, wq, pool);
  3072. return pwq;
  3073. }
  3074. /**
  3075. * wq_calc_node_cpumask - calculate a wq_attrs' cpumask for the specified node
  3076. * @attrs: the wq_attrs of the default pwq of the target workqueue
  3077. * @node: the target NUMA node
  3078. * @cpu_going_down: if >= 0, the CPU to consider as offline
  3079. * @cpumask: outarg, the resulting cpumask
  3080. *
  3081. * Calculate the cpumask a workqueue with @attrs should use on @node. If
  3082. * @cpu_going_down is >= 0, that cpu is considered offline during
  3083. * calculation. The result is stored in @cpumask.
  3084. *
  3085. * If NUMA affinity is not enabled, @attrs->cpumask is always used. If
  3086. * enabled and @node has online CPUs requested by @attrs, the returned
  3087. * cpumask is the intersection of the possible CPUs of @node and
  3088. * @attrs->cpumask.
  3089. *
  3090. * The caller is responsible for ensuring that the cpumask of @node stays
  3091. * stable.
  3092. *
  3093. * Return: %true if the resulting @cpumask is different from @attrs->cpumask,
  3094. * %false if equal.
  3095. */
  3096. static bool wq_calc_node_cpumask(const struct workqueue_attrs *attrs, int node,
  3097. int cpu_going_down, cpumask_t *cpumask)
  3098. {
  3099. if (!wq_numa_enabled || attrs->no_numa)
  3100. goto use_dfl;
  3101. /* does @node have any online CPUs @attrs wants? */
  3102. cpumask_and(cpumask, cpumask_of_node(node), attrs->cpumask);
  3103. if (cpu_going_down >= 0)
  3104. cpumask_clear_cpu(cpu_going_down, cpumask);
  3105. if (cpumask_empty(cpumask))
  3106. goto use_dfl;
  3107. /* yeap, return possible CPUs in @node that @attrs wants */
  3108. cpumask_and(cpumask, attrs->cpumask, wq_numa_possible_cpumask[node]);
  3109. if (cpumask_empty(cpumask)) {
  3110. pr_warn_once("WARNING: workqueue cpumask: online intersect > "
  3111. "possible intersect\n");
  3112. return false;
  3113. }
  3114. return !cpumask_equal(cpumask, attrs->cpumask);
  3115. use_dfl:
  3116. cpumask_copy(cpumask, attrs->cpumask);
  3117. return false;
  3118. }
  3119. /* install @pwq into @wq's numa_pwq_tbl[] for @node and return the old pwq */
  3120. static struct pool_workqueue *numa_pwq_tbl_install(struct workqueue_struct *wq,
  3121. int node,
  3122. struct pool_workqueue *pwq)
  3123. {
  3124. struct pool_workqueue *old_pwq;
  3125. lockdep_assert_held(&wq_pool_mutex);
  3126. lockdep_assert_held(&wq->mutex);
  3127. /* link_pwq() can handle duplicate calls */
  3128. link_pwq(pwq);
  3129. old_pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
  3130. rcu_assign_pointer(wq->numa_pwq_tbl[node], pwq);
  3131. return old_pwq;
  3132. }
  3133. /* context to store the prepared attrs & pwqs before applying */
  3134. struct apply_wqattrs_ctx {
  3135. struct workqueue_struct *wq; /* target workqueue */
  3136. struct workqueue_attrs *attrs; /* attrs to apply */
  3137. struct list_head list; /* queued for batching commit */
  3138. struct pool_workqueue *dfl_pwq;
  3139. struct pool_workqueue *pwq_tbl[];
  3140. };
  3141. /* free the resources after success or abort */
  3142. static void apply_wqattrs_cleanup(struct apply_wqattrs_ctx *ctx)
  3143. {
  3144. if (ctx) {
  3145. int node;
  3146. for_each_node(node)
  3147. put_pwq_unlocked(ctx->pwq_tbl[node]);
  3148. put_pwq_unlocked(ctx->dfl_pwq);
  3149. free_workqueue_attrs(ctx->attrs);
  3150. kfree(ctx);
  3151. }
  3152. }
  3153. /* allocate the attrs and pwqs for later installation */
  3154. static struct apply_wqattrs_ctx *
  3155. apply_wqattrs_prepare(struct workqueue_struct *wq,
  3156. const struct workqueue_attrs *attrs)
  3157. {
  3158. struct apply_wqattrs_ctx *ctx;
  3159. struct workqueue_attrs *new_attrs, *tmp_attrs;
  3160. int node;
  3161. lockdep_assert_held(&wq_pool_mutex);
  3162. ctx = kzalloc(sizeof(*ctx) + nr_node_ids * sizeof(ctx->pwq_tbl[0]),
  3163. GFP_KERNEL);
  3164. new_attrs = alloc_workqueue_attrs(GFP_KERNEL);
  3165. tmp_attrs = alloc_workqueue_attrs(GFP_KERNEL);
  3166. if (!ctx || !new_attrs || !tmp_attrs)
  3167. goto out_free;
  3168. /*
  3169. * Calculate the attrs of the default pwq.
  3170. * If the user configured cpumask doesn't overlap with the
  3171. * wq_unbound_cpumask, we fallback to the wq_unbound_cpumask.
  3172. */
  3173. copy_workqueue_attrs(new_attrs, attrs);
  3174. cpumask_and(new_attrs->cpumask, new_attrs->cpumask, wq_unbound_cpumask);
  3175. if (unlikely(cpumask_empty(new_attrs->cpumask)))
  3176. cpumask_copy(new_attrs->cpumask, wq_unbound_cpumask);
  3177. /*
  3178. * We may create multiple pwqs with differing cpumasks. Make a
  3179. * copy of @new_attrs which will be modified and used to obtain
  3180. * pools.
  3181. */
  3182. copy_workqueue_attrs(tmp_attrs, new_attrs);
  3183. /*
  3184. * If something goes wrong during CPU up/down, we'll fall back to
  3185. * the default pwq covering whole @attrs->cpumask. Always create
  3186. * it even if we don't use it immediately.
  3187. */
  3188. ctx->dfl_pwq = alloc_unbound_pwq(wq, new_attrs);
  3189. if (!ctx->dfl_pwq)
  3190. goto out_free;
  3191. for_each_node(node) {
  3192. if (wq_calc_node_cpumask(new_attrs, node, -1, tmp_attrs->cpumask)) {
  3193. ctx->pwq_tbl[node] = alloc_unbound_pwq(wq, tmp_attrs);
  3194. if (!ctx->pwq_tbl[node])
  3195. goto out_free;
  3196. } else {
  3197. ctx->dfl_pwq->refcnt++;
  3198. ctx->pwq_tbl[node] = ctx->dfl_pwq;
  3199. }
  3200. }
  3201. /* save the user configured attrs and sanitize it. */
  3202. copy_workqueue_attrs(new_attrs, attrs);
  3203. cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask);
  3204. ctx->attrs = new_attrs;
  3205. ctx->wq = wq;
  3206. free_workqueue_attrs(tmp_attrs);
  3207. return ctx;
  3208. out_free:
  3209. free_workqueue_attrs(tmp_attrs);
  3210. free_workqueue_attrs(new_attrs);
  3211. apply_wqattrs_cleanup(ctx);
  3212. return NULL;
  3213. }
  3214. /* set attrs and install prepared pwqs, @ctx points to old pwqs on return */
  3215. static void apply_wqattrs_commit(struct apply_wqattrs_ctx *ctx)
  3216. {
  3217. int node;
  3218. /* all pwqs have been created successfully, let's install'em */
  3219. mutex_lock(&ctx->wq->mutex);
  3220. copy_workqueue_attrs(ctx->wq->unbound_attrs, ctx->attrs);
  3221. /* save the previous pwq and install the new one */
  3222. for_each_node(node)
  3223. ctx->pwq_tbl[node] = numa_pwq_tbl_install(ctx->wq, node,
  3224. ctx->pwq_tbl[node]);
  3225. /* @dfl_pwq might not have been used, ensure it's linked */
  3226. link_pwq(ctx->dfl_pwq);
  3227. swap(ctx->wq->dfl_pwq, ctx->dfl_pwq);
  3228. mutex_unlock(&ctx->wq->mutex);
  3229. }
  3230. static void apply_wqattrs_lock(void)
  3231. {
  3232. /* CPUs should stay stable across pwq creations and installations */
  3233. get_online_cpus();
  3234. mutex_lock(&wq_pool_mutex);
  3235. }
  3236. static void apply_wqattrs_unlock(void)
  3237. {
  3238. mutex_unlock(&wq_pool_mutex);
  3239. put_online_cpus();
  3240. }
  3241. static int apply_workqueue_attrs_locked(struct workqueue_struct *wq,
  3242. const struct workqueue_attrs *attrs)
  3243. {
  3244. struct apply_wqattrs_ctx *ctx;
  3245. /* only unbound workqueues can change attributes */
  3246. if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
  3247. return -EINVAL;
  3248. /* creating multiple pwqs breaks ordering guarantee */
  3249. if (!list_empty(&wq->pwqs)) {
  3250. if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
  3251. return -EINVAL;
  3252. wq->flags &= ~__WQ_ORDERED;
  3253. }
  3254. ctx = apply_wqattrs_prepare(wq, attrs);
  3255. if (!ctx)
  3256. return -ENOMEM;
  3257. /* the ctx has been prepared successfully, let's commit it */
  3258. apply_wqattrs_commit(ctx);
  3259. apply_wqattrs_cleanup(ctx);
  3260. return 0;
  3261. }
  3262. /**
  3263. * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
  3264. * @wq: the target workqueue
  3265. * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
  3266. *
  3267. * Apply @attrs to an unbound workqueue @wq. Unless disabled, on NUMA
  3268. * machines, this function maps a separate pwq to each NUMA node with
  3269. * possibles CPUs in @attrs->cpumask so that work items are affine to the
  3270. * NUMA node it was issued on. Older pwqs are released as in-flight work
  3271. * items finish. Note that a work item which repeatedly requeues itself
  3272. * back-to-back will stay on its current pwq.
  3273. *
  3274. * Performs GFP_KERNEL allocations.
  3275. *
  3276. * Return: 0 on success and -errno on failure.
  3277. */
  3278. int apply_workqueue_attrs(struct workqueue_struct *wq,
  3279. const struct workqueue_attrs *attrs)
  3280. {
  3281. int ret;
  3282. apply_wqattrs_lock();
  3283. ret = apply_workqueue_attrs_locked(wq, attrs);
  3284. apply_wqattrs_unlock();
  3285. return ret;
  3286. }
  3287. /**
  3288. * wq_update_unbound_numa - update NUMA affinity of a wq for CPU hot[un]plug
  3289. * @wq: the target workqueue
  3290. * @cpu: the CPU coming up or going down
  3291. * @online: whether @cpu is coming up or going down
  3292. *
  3293. * This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and
  3294. * %CPU_DOWN_FAILED. @cpu is being hot[un]plugged, update NUMA affinity of
  3295. * @wq accordingly.
  3296. *
  3297. * If NUMA affinity can't be adjusted due to memory allocation failure, it
  3298. * falls back to @wq->dfl_pwq which may not be optimal but is always
  3299. * correct.
  3300. *
  3301. * Note that when the last allowed CPU of a NUMA node goes offline for a
  3302. * workqueue with a cpumask spanning multiple nodes, the workers which were
  3303. * already executing the work items for the workqueue will lose their CPU
  3304. * affinity and may execute on any CPU. This is similar to how per-cpu
  3305. * workqueues behave on CPU_DOWN. If a workqueue user wants strict
  3306. * affinity, it's the user's responsibility to flush the work item from
  3307. * CPU_DOWN_PREPARE.
  3308. */
  3309. static void wq_update_unbound_numa(struct workqueue_struct *wq, int cpu,
  3310. bool online)
  3311. {
  3312. int node = cpu_to_node(cpu);
  3313. int cpu_off = online ? -1 : cpu;
  3314. struct pool_workqueue *old_pwq = NULL, *pwq;
  3315. struct workqueue_attrs *target_attrs;
  3316. cpumask_t *cpumask;
  3317. lockdep_assert_held(&wq_pool_mutex);
  3318. if (!wq_numa_enabled || !(wq->flags & WQ_UNBOUND) ||
  3319. wq->unbound_attrs->no_numa)
  3320. return;
  3321. /*
  3322. * We don't wanna alloc/free wq_attrs for each wq for each CPU.
  3323. * Let's use a preallocated one. The following buf is protected by
  3324. * CPU hotplug exclusion.
  3325. */
  3326. target_attrs = wq_update_unbound_numa_attrs_buf;
  3327. cpumask = target_attrs->cpumask;
  3328. copy_workqueue_attrs(target_attrs, wq->unbound_attrs);
  3329. pwq = unbound_pwq_by_node(wq, node);
  3330. /*
  3331. * Let's determine what needs to be done. If the target cpumask is
  3332. * different from the default pwq's, we need to compare it to @pwq's
  3333. * and create a new one if they don't match. If the target cpumask
  3334. * equals the default pwq's, the default pwq should be used.
  3335. */
  3336. if (wq_calc_node_cpumask(wq->dfl_pwq->pool->attrs, node, cpu_off, cpumask)) {
  3337. if (cpumask_equal(cpumask, pwq->pool->attrs->cpumask))
  3338. return;
  3339. } else {
  3340. goto use_dfl_pwq;
  3341. }
  3342. /* create a new pwq */
  3343. pwq = alloc_unbound_pwq(wq, target_attrs);
  3344. if (!pwq) {
  3345. pr_warn("workqueue: allocation failed while updating NUMA affinity of \"%s\"\n",
  3346. wq->name);
  3347. goto use_dfl_pwq;
  3348. }
  3349. /* Install the new pwq. */
  3350. mutex_lock(&wq->mutex);
  3351. old_pwq = numa_pwq_tbl_install(wq, node, pwq);
  3352. goto out_unlock;
  3353. use_dfl_pwq:
  3354. mutex_lock(&wq->mutex);
  3355. spin_lock_irq(&wq->dfl_pwq->pool->lock);
  3356. get_pwq(wq->dfl_pwq);
  3357. spin_unlock_irq(&wq->dfl_pwq->pool->lock);
  3358. old_pwq = numa_pwq_tbl_install(wq, node, wq->dfl_pwq);
  3359. out_unlock:
  3360. mutex_unlock(&wq->mutex);
  3361. put_pwq_unlocked(old_pwq);
  3362. }
  3363. static int alloc_and_link_pwqs(struct workqueue_struct *wq)
  3364. {
  3365. bool highpri = wq->flags & WQ_HIGHPRI;
  3366. int cpu, ret;
  3367. if (!(wq->flags & WQ_UNBOUND)) {
  3368. wq->cpu_pwqs = alloc_percpu(struct pool_workqueue);
  3369. if (!wq->cpu_pwqs)
  3370. return -ENOMEM;
  3371. for_each_possible_cpu(cpu) {
  3372. struct pool_workqueue *pwq =
  3373. per_cpu_ptr(wq->cpu_pwqs, cpu);
  3374. struct worker_pool *cpu_pools =
  3375. per_cpu(cpu_worker_pools, cpu);
  3376. init_pwq(pwq, wq, &cpu_pools[highpri]);
  3377. mutex_lock(&wq->mutex);
  3378. link_pwq(pwq);
  3379. mutex_unlock(&wq->mutex);
  3380. }
  3381. return 0;
  3382. } else if (wq->flags & __WQ_ORDERED) {
  3383. ret = apply_workqueue_attrs(wq, ordered_wq_attrs[highpri]);
  3384. /* there should only be single pwq for ordering guarantee */
  3385. WARN(!ret && (wq->pwqs.next != &wq->dfl_pwq->pwqs_node ||
  3386. wq->pwqs.prev != &wq->dfl_pwq->pwqs_node),
  3387. "ordering guarantee broken for workqueue %s\n", wq->name);
  3388. return ret;
  3389. } else {
  3390. return apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
  3391. }
  3392. }
  3393. static int wq_clamp_max_active(int max_active, unsigned int flags,
  3394. const char *name)
  3395. {
  3396. int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
  3397. if (max_active < 1 || max_active > lim)
  3398. pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
  3399. max_active, name, 1, lim);
  3400. return clamp_val(max_active, 1, lim);
  3401. }
  3402. struct workqueue_struct *__alloc_workqueue_key(const char *fmt,
  3403. unsigned int flags,
  3404. int max_active,
  3405. struct lock_class_key *key,
  3406. const char *lock_name, ...)
  3407. {
  3408. size_t tbl_size = 0;
  3409. va_list args;
  3410. struct workqueue_struct *wq;
  3411. struct pool_workqueue *pwq;
  3412. /*
  3413. * Unbound && max_active == 1 used to imply ordered, which is no
  3414. * longer the case on NUMA machines due to per-node pools. While
  3415. * alloc_ordered_workqueue() is the right way to create an ordered
  3416. * workqueue, keep the previous behavior to avoid subtle breakages
  3417. * on NUMA.
  3418. */
  3419. if ((flags & WQ_UNBOUND) && max_active == 1)
  3420. flags |= __WQ_ORDERED;
  3421. /* see the comment above the definition of WQ_POWER_EFFICIENT */
  3422. if ((flags & WQ_POWER_EFFICIENT) && wq_power_efficient)
  3423. flags |= WQ_UNBOUND;
  3424. /* allocate wq and format name */
  3425. if (flags & WQ_UNBOUND)
  3426. tbl_size = nr_node_ids * sizeof(wq->numa_pwq_tbl[0]);
  3427. wq = kzalloc(sizeof(*wq) + tbl_size, GFP_KERNEL);
  3428. if (!wq)
  3429. return NULL;
  3430. if (flags & WQ_UNBOUND) {
  3431. wq->unbound_attrs = alloc_workqueue_attrs(GFP_KERNEL);
  3432. if (!wq->unbound_attrs)
  3433. goto err_free_wq;
  3434. }
  3435. va_start(args, lock_name);
  3436. vsnprintf(wq->name, sizeof(wq->name), fmt, args);
  3437. va_end(args);
  3438. max_active = max_active ?: WQ_DFL_ACTIVE;
  3439. max_active = wq_clamp_max_active(max_active, flags, wq->name);
  3440. /* init wq */
  3441. wq->flags = flags;
  3442. wq->saved_max_active = max_active;
  3443. mutex_init(&wq->mutex);
  3444. atomic_set(&wq->nr_pwqs_to_flush, 0);
  3445. INIT_LIST_HEAD(&wq->pwqs);
  3446. INIT_LIST_HEAD(&wq->flusher_queue);
  3447. INIT_LIST_HEAD(&wq->flusher_overflow);
  3448. INIT_LIST_HEAD(&wq->maydays);
  3449. lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
  3450. INIT_LIST_HEAD(&wq->list);
  3451. if (alloc_and_link_pwqs(wq) < 0)
  3452. goto err_free_wq;
  3453. /*
  3454. * Workqueues which may be used during memory reclaim should
  3455. * have a rescuer to guarantee forward progress.
  3456. */
  3457. if (flags & WQ_MEM_RECLAIM) {
  3458. struct worker *rescuer;
  3459. rescuer = alloc_worker(NUMA_NO_NODE);
  3460. if (!rescuer)
  3461. goto err_destroy;
  3462. rescuer->rescue_wq = wq;
  3463. rescuer->task = kthread_create(rescuer_thread, rescuer, "%s",
  3464. wq->name);
  3465. if (IS_ERR(rescuer->task)) {
  3466. kfree(rescuer);
  3467. goto err_destroy;
  3468. }
  3469. wq->rescuer = rescuer;
  3470. kthread_bind_mask(rescuer->task, cpu_possible_mask);
  3471. wake_up_process(rescuer->task);
  3472. }
  3473. if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
  3474. goto err_destroy;
  3475. /*
  3476. * wq_pool_mutex protects global freeze state and workqueues list.
  3477. * Grab it, adjust max_active and add the new @wq to workqueues
  3478. * list.
  3479. */
  3480. mutex_lock(&wq_pool_mutex);
  3481. mutex_lock(&wq->mutex);
  3482. for_each_pwq(pwq, wq)
  3483. pwq_adjust_max_active(pwq);
  3484. mutex_unlock(&wq->mutex);
  3485. list_add_tail_rcu(&wq->list, &workqueues);
  3486. mutex_unlock(&wq_pool_mutex);
  3487. return wq;
  3488. err_free_wq:
  3489. free_workqueue_attrs(wq->unbound_attrs);
  3490. kfree(wq);
  3491. return NULL;
  3492. err_destroy:
  3493. destroy_workqueue(wq);
  3494. return NULL;
  3495. }
  3496. EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
  3497. /**
  3498. * destroy_workqueue - safely terminate a workqueue
  3499. * @wq: target workqueue
  3500. *
  3501. * Safely destroy a workqueue. All work currently pending will be done first.
  3502. */
  3503. void destroy_workqueue(struct workqueue_struct *wq)
  3504. {
  3505. struct pool_workqueue *pwq;
  3506. int node;
  3507. /* drain it before proceeding with destruction */
  3508. drain_workqueue(wq);
  3509. /* sanity checks */
  3510. mutex_lock(&wq->mutex);
  3511. for_each_pwq(pwq, wq) {
  3512. int i;
  3513. for (i = 0; i < WORK_NR_COLORS; i++) {
  3514. if (WARN_ON(pwq->nr_in_flight[i])) {
  3515. mutex_unlock(&wq->mutex);
  3516. show_workqueue_state();
  3517. return;
  3518. }
  3519. }
  3520. if (WARN_ON((pwq != wq->dfl_pwq) && (pwq->refcnt > 1)) ||
  3521. WARN_ON(pwq->nr_active) ||
  3522. WARN_ON(!list_empty(&pwq->delayed_works))) {
  3523. mutex_unlock(&wq->mutex);
  3524. show_workqueue_state();
  3525. return;
  3526. }
  3527. }
  3528. mutex_unlock(&wq->mutex);
  3529. /*
  3530. * wq list is used to freeze wq, remove from list after
  3531. * flushing is complete in case freeze races us.
  3532. */
  3533. mutex_lock(&wq_pool_mutex);
  3534. list_del_rcu(&wq->list);
  3535. mutex_unlock(&wq_pool_mutex);
  3536. workqueue_sysfs_unregister(wq);
  3537. if (wq->rescuer)
  3538. kthread_stop(wq->rescuer->task);
  3539. if (!(wq->flags & WQ_UNBOUND)) {
  3540. /*
  3541. * The base ref is never dropped on per-cpu pwqs. Directly
  3542. * schedule RCU free.
  3543. */
  3544. call_rcu_sched(&wq->rcu, rcu_free_wq);
  3545. } else {
  3546. /*
  3547. * We're the sole accessor of @wq at this point. Directly
  3548. * access numa_pwq_tbl[] and dfl_pwq to put the base refs.
  3549. * @wq will be freed when the last pwq is released.
  3550. */
  3551. for_each_node(node) {
  3552. pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
  3553. RCU_INIT_POINTER(wq->numa_pwq_tbl[node], NULL);
  3554. put_pwq_unlocked(pwq);
  3555. }
  3556. /*
  3557. * Put dfl_pwq. @wq may be freed any time after dfl_pwq is
  3558. * put. Don't access it afterwards.
  3559. */
  3560. pwq = wq->dfl_pwq;
  3561. wq->dfl_pwq = NULL;
  3562. put_pwq_unlocked(pwq);
  3563. }
  3564. }
  3565. EXPORT_SYMBOL_GPL(destroy_workqueue);
  3566. /**
  3567. * workqueue_set_max_active - adjust max_active of a workqueue
  3568. * @wq: target workqueue
  3569. * @max_active: new max_active value.
  3570. *
  3571. * Set max_active of @wq to @max_active.
  3572. *
  3573. * CONTEXT:
  3574. * Don't call from IRQ context.
  3575. */
  3576. void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
  3577. {
  3578. struct pool_workqueue *pwq;
  3579. /* disallow meddling with max_active for ordered workqueues */
  3580. if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
  3581. return;
  3582. max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
  3583. mutex_lock(&wq->mutex);
  3584. wq->flags &= ~__WQ_ORDERED;
  3585. wq->saved_max_active = max_active;
  3586. for_each_pwq(pwq, wq)
  3587. pwq_adjust_max_active(pwq);
  3588. mutex_unlock(&wq->mutex);
  3589. }
  3590. EXPORT_SYMBOL_GPL(workqueue_set_max_active);
  3591. /**
  3592. * current_is_workqueue_rescuer - is %current workqueue rescuer?
  3593. *
  3594. * Determine whether %current is a workqueue rescuer. Can be used from
  3595. * work functions to determine whether it's being run off the rescuer task.
  3596. *
  3597. * Return: %true if %current is a workqueue rescuer. %false otherwise.
  3598. */
  3599. bool current_is_workqueue_rescuer(void)
  3600. {
  3601. struct worker *worker = current_wq_worker();
  3602. return worker && worker->rescue_wq;
  3603. }
  3604. /**
  3605. * workqueue_congested - test whether a workqueue is congested
  3606. * @cpu: CPU in question
  3607. * @wq: target workqueue
  3608. *
  3609. * Test whether @wq's cpu workqueue for @cpu is congested. There is
  3610. * no synchronization around this function and the test result is
  3611. * unreliable and only useful as advisory hints or for debugging.
  3612. *
  3613. * If @cpu is WORK_CPU_UNBOUND, the test is performed on the local CPU.
  3614. * Note that both per-cpu and unbound workqueues may be associated with
  3615. * multiple pool_workqueues which have separate congested states. A
  3616. * workqueue being congested on one CPU doesn't mean the workqueue is also
  3617. * contested on other CPUs / NUMA nodes.
  3618. *
  3619. * Return:
  3620. * %true if congested, %false otherwise.
  3621. */
  3622. bool workqueue_congested(int cpu, struct workqueue_struct *wq)
  3623. {
  3624. struct pool_workqueue *pwq;
  3625. bool ret;
  3626. rcu_read_lock_sched();
  3627. if (cpu == WORK_CPU_UNBOUND)
  3628. cpu = smp_processor_id();
  3629. if (!(wq->flags & WQ_UNBOUND))
  3630. pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
  3631. else
  3632. pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
  3633. ret = !list_empty(&pwq->delayed_works);
  3634. rcu_read_unlock_sched();
  3635. return ret;
  3636. }
  3637. EXPORT_SYMBOL_GPL(workqueue_congested);
  3638. /**
  3639. * work_busy - test whether a work is currently pending or running
  3640. * @work: the work to be tested
  3641. *
  3642. * Test whether @work is currently pending or running. There is no
  3643. * synchronization around this function and the test result is
  3644. * unreliable and only useful as advisory hints or for debugging.
  3645. *
  3646. * Return:
  3647. * OR'd bitmask of WORK_BUSY_* bits.
  3648. */
  3649. unsigned int work_busy(struct work_struct *work)
  3650. {
  3651. struct worker_pool *pool;
  3652. unsigned long flags;
  3653. unsigned int ret = 0;
  3654. if (work_pending(work))
  3655. ret |= WORK_BUSY_PENDING;
  3656. local_irq_save(flags);
  3657. pool = get_work_pool(work);
  3658. if (pool) {
  3659. spin_lock(&pool->lock);
  3660. if (find_worker_executing_work(pool, work))
  3661. ret |= WORK_BUSY_RUNNING;
  3662. spin_unlock(&pool->lock);
  3663. }
  3664. local_irq_restore(flags);
  3665. return ret;
  3666. }
  3667. EXPORT_SYMBOL_GPL(work_busy);
  3668. /**
  3669. * set_worker_desc - set description for the current work item
  3670. * @fmt: printf-style format string
  3671. * @...: arguments for the format string
  3672. *
  3673. * This function can be called by a running work function to describe what
  3674. * the work item is about. If the worker task gets dumped, this
  3675. * information will be printed out together to help debugging. The
  3676. * description can be at most WORKER_DESC_LEN including the trailing '\0'.
  3677. */
  3678. void set_worker_desc(const char *fmt, ...)
  3679. {
  3680. struct worker *worker = current_wq_worker();
  3681. va_list args;
  3682. if (worker) {
  3683. va_start(args, fmt);
  3684. vsnprintf(worker->desc, sizeof(worker->desc), fmt, args);
  3685. va_end(args);
  3686. worker->desc_valid = true;
  3687. }
  3688. }
  3689. /**
  3690. * print_worker_info - print out worker information and description
  3691. * @log_lvl: the log level to use when printing
  3692. * @task: target task
  3693. *
  3694. * If @task is a worker and currently executing a work item, print out the
  3695. * name of the workqueue being serviced and worker description set with
  3696. * set_worker_desc() by the currently executing work item.
  3697. *
  3698. * This function can be safely called on any task as long as the
  3699. * task_struct itself is accessible. While safe, this function isn't
  3700. * synchronized and may print out mixups or garbages of limited length.
  3701. */
  3702. void print_worker_info(const char *log_lvl, struct task_struct *task)
  3703. {
  3704. work_func_t *fn = NULL;
  3705. char name[WQ_NAME_LEN] = { };
  3706. char desc[WORKER_DESC_LEN] = { };
  3707. struct pool_workqueue *pwq = NULL;
  3708. struct workqueue_struct *wq = NULL;
  3709. bool desc_valid = false;
  3710. struct worker *worker;
  3711. if (!(task->flags & PF_WQ_WORKER))
  3712. return;
  3713. /*
  3714. * This function is called without any synchronization and @task
  3715. * could be in any state. Be careful with dereferences.
  3716. */
  3717. worker = kthread_probe_data(task);
  3718. /*
  3719. * Carefully copy the associated workqueue's workfn and name. Keep
  3720. * the original last '\0' in case the original contains garbage.
  3721. */
  3722. probe_kernel_read(&fn, &worker->current_func, sizeof(fn));
  3723. probe_kernel_read(&pwq, &worker->current_pwq, sizeof(pwq));
  3724. probe_kernel_read(&wq, &pwq->wq, sizeof(wq));
  3725. probe_kernel_read(name, wq->name, sizeof(name) - 1);
  3726. /* copy worker description */
  3727. probe_kernel_read(&desc_valid, &worker->desc_valid, sizeof(desc_valid));
  3728. if (desc_valid)
  3729. probe_kernel_read(desc, worker->desc, sizeof(desc) - 1);
  3730. if (fn || name[0] || desc[0]) {
  3731. printk("%sWorkqueue: %s %pf", log_lvl, name, fn);
  3732. if (desc[0])
  3733. pr_cont(" (%s)", desc);
  3734. pr_cont("\n");
  3735. }
  3736. }
  3737. static void pr_cont_pool_info(struct worker_pool *pool)
  3738. {
  3739. pr_cont(" cpus=%*pbl", nr_cpumask_bits, pool->attrs->cpumask);
  3740. if (pool->node != NUMA_NO_NODE)
  3741. pr_cont(" node=%d", pool->node);
  3742. pr_cont(" flags=0x%x nice=%d", pool->flags, pool->attrs->nice);
  3743. }
  3744. static void pr_cont_work(bool comma, struct work_struct *work)
  3745. {
  3746. if (work->func == wq_barrier_func) {
  3747. struct wq_barrier *barr;
  3748. barr = container_of(work, struct wq_barrier, work);
  3749. pr_cont("%s BAR(%d)", comma ? "," : "",
  3750. task_pid_nr(barr->task));
  3751. } else {
  3752. pr_cont("%s %pf", comma ? "," : "", work->func);
  3753. }
  3754. }
  3755. static void show_pwq(struct pool_workqueue *pwq)
  3756. {
  3757. struct worker_pool *pool = pwq->pool;
  3758. struct work_struct *work;
  3759. struct worker *worker;
  3760. bool has_in_flight = false, has_pending = false;
  3761. int bkt;
  3762. pr_info(" pwq %d:", pool->id);
  3763. pr_cont_pool_info(pool);
  3764. pr_cont(" active=%d/%d%s\n", pwq->nr_active, pwq->max_active,
  3765. !list_empty(&pwq->mayday_node) ? " MAYDAY" : "");
  3766. hash_for_each(pool->busy_hash, bkt, worker, hentry) {
  3767. if (worker->current_pwq == pwq) {
  3768. has_in_flight = true;
  3769. break;
  3770. }
  3771. }
  3772. if (has_in_flight) {
  3773. bool comma = false;
  3774. pr_info(" in-flight:");
  3775. hash_for_each(pool->busy_hash, bkt, worker, hentry) {
  3776. if (worker->current_pwq != pwq)
  3777. continue;
  3778. pr_cont("%s %d%s:%pf", comma ? "," : "",
  3779. task_pid_nr(worker->task),
  3780. worker == pwq->wq->rescuer ? "(RESCUER)" : "",
  3781. worker->current_func);
  3782. list_for_each_entry(work, &worker->scheduled, entry)
  3783. pr_cont_work(false, work);
  3784. comma = true;
  3785. }
  3786. pr_cont("\n");
  3787. }
  3788. list_for_each_entry(work, &pool->worklist, entry) {
  3789. if (get_work_pwq(work) == pwq) {
  3790. has_pending = true;
  3791. break;
  3792. }
  3793. }
  3794. if (has_pending) {
  3795. bool comma = false;
  3796. pr_info(" pending:");
  3797. list_for_each_entry(work, &pool->worklist, entry) {
  3798. if (get_work_pwq(work) != pwq)
  3799. continue;
  3800. pr_cont_work(comma, work);
  3801. comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
  3802. }
  3803. pr_cont("\n");
  3804. }
  3805. if (!list_empty(&pwq->delayed_works)) {
  3806. bool comma = false;
  3807. pr_info(" delayed:");
  3808. list_for_each_entry(work, &pwq->delayed_works, entry) {
  3809. pr_cont_work(comma, work);
  3810. comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
  3811. }
  3812. pr_cont("\n");
  3813. }
  3814. }
  3815. /**
  3816. * show_workqueue_state - dump workqueue state
  3817. *
  3818. * Called from a sysrq handler or try_to_freeze_tasks() and prints out
  3819. * all busy workqueues and pools.
  3820. */
  3821. void show_workqueue_state(void)
  3822. {
  3823. struct workqueue_struct *wq;
  3824. struct worker_pool *pool;
  3825. unsigned long flags;
  3826. int pi;
  3827. rcu_read_lock_sched();
  3828. pr_info("Showing busy workqueues and worker pools:\n");
  3829. list_for_each_entry_rcu(wq, &workqueues, list) {
  3830. struct pool_workqueue *pwq;
  3831. bool idle = true;
  3832. for_each_pwq(pwq, wq) {
  3833. if (pwq->nr_active || !list_empty(&pwq->delayed_works)) {
  3834. idle = false;
  3835. break;
  3836. }
  3837. }
  3838. if (idle)
  3839. continue;
  3840. pr_info("workqueue %s: flags=0x%x\n", wq->name, wq->flags);
  3841. for_each_pwq(pwq, wq) {
  3842. spin_lock_irqsave(&pwq->pool->lock, flags);
  3843. if (pwq->nr_active || !list_empty(&pwq->delayed_works))
  3844. show_pwq(pwq);
  3845. spin_unlock_irqrestore(&pwq->pool->lock, flags);
  3846. }
  3847. }
  3848. for_each_pool(pool, pi) {
  3849. struct worker *worker;
  3850. bool first = true;
  3851. spin_lock_irqsave(&pool->lock, flags);
  3852. if (pool->nr_workers == pool->nr_idle)
  3853. goto next_pool;
  3854. pr_info("pool %d:", pool->id);
  3855. pr_cont_pool_info(pool);
  3856. pr_cont(" hung=%us workers=%d",
  3857. jiffies_to_msecs(jiffies - pool->watchdog_ts) / 1000,
  3858. pool->nr_workers);
  3859. if (pool->manager)
  3860. pr_cont(" manager: %d",
  3861. task_pid_nr(pool->manager->task));
  3862. list_for_each_entry(worker, &pool->idle_list, entry) {
  3863. pr_cont(" %s%d", first ? "idle: " : "",
  3864. task_pid_nr(worker->task));
  3865. first = false;
  3866. }
  3867. pr_cont("\n");
  3868. next_pool:
  3869. spin_unlock_irqrestore(&pool->lock, flags);
  3870. }
  3871. rcu_read_unlock_sched();
  3872. }
  3873. /*
  3874. * CPU hotplug.
  3875. *
  3876. * There are two challenges in supporting CPU hotplug. Firstly, there
  3877. * are a lot of assumptions on strong associations among work, pwq and
  3878. * pool which make migrating pending and scheduled works very
  3879. * difficult to implement without impacting hot paths. Secondly,
  3880. * worker pools serve mix of short, long and very long running works making
  3881. * blocked draining impractical.
  3882. *
  3883. * This is solved by allowing the pools to be disassociated from the CPU
  3884. * running as an unbound one and allowing it to be reattached later if the
  3885. * cpu comes back online.
  3886. */
  3887. static void wq_unbind_fn(struct work_struct *work)
  3888. {
  3889. int cpu = smp_processor_id();
  3890. struct worker_pool *pool;
  3891. struct worker *worker;
  3892. for_each_cpu_worker_pool(pool, cpu) {
  3893. mutex_lock(&pool->attach_mutex);
  3894. spin_lock_irq(&pool->lock);
  3895. /*
  3896. * We've blocked all attach/detach operations. Make all workers
  3897. * unbound and set DISASSOCIATED. Before this, all workers
  3898. * except for the ones which are still executing works from
  3899. * before the last CPU down must be on the cpu. After
  3900. * this, they may become diasporas.
  3901. */
  3902. for_each_pool_worker(worker, pool)
  3903. worker->flags |= WORKER_UNBOUND;
  3904. pool->flags |= POOL_DISASSOCIATED;
  3905. spin_unlock_irq(&pool->lock);
  3906. mutex_unlock(&pool->attach_mutex);
  3907. /*
  3908. * Call schedule() so that we cross rq->lock and thus can
  3909. * guarantee sched callbacks see the %WORKER_UNBOUND flag.
  3910. * This is necessary as scheduler callbacks may be invoked
  3911. * from other cpus.
  3912. */
  3913. schedule();
  3914. /*
  3915. * Sched callbacks are disabled now. Zap nr_running.
  3916. * After this, nr_running stays zero and need_more_worker()
  3917. * and keep_working() are always true as long as the
  3918. * worklist is not empty. This pool now behaves as an
  3919. * unbound (in terms of concurrency management) pool which
  3920. * are served by workers tied to the pool.
  3921. */
  3922. atomic_set(&pool->nr_running, 0);
  3923. /*
  3924. * With concurrency management just turned off, a busy
  3925. * worker blocking could lead to lengthy stalls. Kick off
  3926. * unbound chain execution of currently pending work items.
  3927. */
  3928. spin_lock_irq(&pool->lock);
  3929. wake_up_worker(pool);
  3930. spin_unlock_irq(&pool->lock);
  3931. }
  3932. }
  3933. /**
  3934. * rebind_workers - rebind all workers of a pool to the associated CPU
  3935. * @pool: pool of interest
  3936. *
  3937. * @pool->cpu is coming online. Rebind all workers to the CPU.
  3938. */
  3939. static void rebind_workers(struct worker_pool *pool)
  3940. {
  3941. struct worker *worker;
  3942. lockdep_assert_held(&pool->attach_mutex);
  3943. /*
  3944. * Restore CPU affinity of all workers. As all idle workers should
  3945. * be on the run-queue of the associated CPU before any local
  3946. * wake-ups for concurrency management happen, restore CPU affinity
  3947. * of all workers first and then clear UNBOUND. As we're called
  3948. * from CPU_ONLINE, the following shouldn't fail.
  3949. */
  3950. for_each_pool_worker(worker, pool)
  3951. WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
  3952. pool->attrs->cpumask) < 0);
  3953. spin_lock_irq(&pool->lock);
  3954. /*
  3955. * XXX: CPU hotplug notifiers are weird and can call DOWN_FAILED
  3956. * w/o preceding DOWN_PREPARE. Work around it. CPU hotplug is
  3957. * being reworked and this can go away in time.
  3958. */
  3959. if (!(pool->flags & POOL_DISASSOCIATED)) {
  3960. spin_unlock_irq(&pool->lock);
  3961. return;
  3962. }
  3963. pool->flags &= ~POOL_DISASSOCIATED;
  3964. for_each_pool_worker(worker, pool) {
  3965. unsigned int worker_flags = worker->flags;
  3966. /*
  3967. * A bound idle worker should actually be on the runqueue
  3968. * of the associated CPU for local wake-ups targeting it to
  3969. * work. Kick all idle workers so that they migrate to the
  3970. * associated CPU. Doing this in the same loop as
  3971. * replacing UNBOUND with REBOUND is safe as no worker will
  3972. * be bound before @pool->lock is released.
  3973. */
  3974. if (worker_flags & WORKER_IDLE)
  3975. wake_up_process(worker->task);
  3976. /*
  3977. * We want to clear UNBOUND but can't directly call
  3978. * worker_clr_flags() or adjust nr_running. Atomically
  3979. * replace UNBOUND with another NOT_RUNNING flag REBOUND.
  3980. * @worker will clear REBOUND using worker_clr_flags() when
  3981. * it initiates the next execution cycle thus restoring
  3982. * concurrency management. Note that when or whether
  3983. * @worker clears REBOUND doesn't affect correctness.
  3984. *
  3985. * ACCESS_ONCE() is necessary because @worker->flags may be
  3986. * tested without holding any lock in
  3987. * wq_worker_waking_up(). Without it, NOT_RUNNING test may
  3988. * fail incorrectly leading to premature concurrency
  3989. * management operations.
  3990. */
  3991. WARN_ON_ONCE(!(worker_flags & WORKER_UNBOUND));
  3992. worker_flags |= WORKER_REBOUND;
  3993. worker_flags &= ~WORKER_UNBOUND;
  3994. ACCESS_ONCE(worker->flags) = worker_flags;
  3995. }
  3996. spin_unlock_irq(&pool->lock);
  3997. }
  3998. /**
  3999. * restore_unbound_workers_cpumask - restore cpumask of unbound workers
  4000. * @pool: unbound pool of interest
  4001. * @cpu: the CPU which is coming up
  4002. *
  4003. * An unbound pool may end up with a cpumask which doesn't have any online
  4004. * CPUs. When a worker of such pool get scheduled, the scheduler resets
  4005. * its cpus_allowed. If @cpu is in @pool's cpumask which didn't have any
  4006. * online CPU before, cpus_allowed of all its workers should be restored.
  4007. */
  4008. static void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu)
  4009. {
  4010. static cpumask_t cpumask;
  4011. struct worker *worker;
  4012. lockdep_assert_held(&pool->attach_mutex);
  4013. /* is @cpu allowed for @pool? */
  4014. if (!cpumask_test_cpu(cpu, pool->attrs->cpumask))
  4015. return;
  4016. cpumask_and(&cpumask, pool->attrs->cpumask, cpu_online_mask);
  4017. /* as we're called from CPU_ONLINE, the following shouldn't fail */
  4018. for_each_pool_worker(worker, pool)
  4019. WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, &cpumask) < 0);
  4020. }
  4021. int workqueue_prepare_cpu(unsigned int cpu)
  4022. {
  4023. struct worker_pool *pool;
  4024. for_each_cpu_worker_pool(pool, cpu) {
  4025. if (pool->nr_workers)
  4026. continue;
  4027. if (!create_worker(pool))
  4028. return -ENOMEM;
  4029. }
  4030. return 0;
  4031. }
  4032. int workqueue_online_cpu(unsigned int cpu)
  4033. {
  4034. struct worker_pool *pool;
  4035. struct workqueue_struct *wq;
  4036. int pi;
  4037. mutex_lock(&wq_pool_mutex);
  4038. for_each_pool(pool, pi) {
  4039. mutex_lock(&pool->attach_mutex);
  4040. if (pool->cpu == cpu)
  4041. rebind_workers(pool);
  4042. else if (pool->cpu < 0)
  4043. restore_unbound_workers_cpumask(pool, cpu);
  4044. mutex_unlock(&pool->attach_mutex);
  4045. }
  4046. /* update NUMA affinity of unbound workqueues */
  4047. list_for_each_entry(wq, &workqueues, list)
  4048. wq_update_unbound_numa(wq, cpu, true);
  4049. mutex_unlock(&wq_pool_mutex);
  4050. return 0;
  4051. }
  4052. int workqueue_offline_cpu(unsigned int cpu)
  4053. {
  4054. struct work_struct unbind_work;
  4055. struct workqueue_struct *wq;
  4056. /* unbinding per-cpu workers should happen on the local CPU */
  4057. INIT_WORK_ONSTACK(&unbind_work, wq_unbind_fn);
  4058. queue_work_on(cpu, system_highpri_wq, &unbind_work);
  4059. /* update NUMA affinity of unbound workqueues */
  4060. mutex_lock(&wq_pool_mutex);
  4061. list_for_each_entry(wq, &workqueues, list)
  4062. wq_update_unbound_numa(wq, cpu, false);
  4063. mutex_unlock(&wq_pool_mutex);
  4064. /* wait for per-cpu unbinding to finish */
  4065. flush_work(&unbind_work);
  4066. destroy_work_on_stack(&unbind_work);
  4067. return 0;
  4068. }
  4069. #ifdef CONFIG_SMP
  4070. struct work_for_cpu {
  4071. struct work_struct work;
  4072. long (*fn)(void *);
  4073. void *arg;
  4074. long ret;
  4075. };
  4076. static void work_for_cpu_fn(struct work_struct *work)
  4077. {
  4078. struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
  4079. wfc->ret = wfc->fn(wfc->arg);
  4080. }
  4081. /**
  4082. * work_on_cpu - run a function in thread context on a particular cpu
  4083. * @cpu: the cpu to run on
  4084. * @fn: the function to run
  4085. * @arg: the function arg
  4086. *
  4087. * It is up to the caller to ensure that the cpu doesn't go offline.
  4088. * The caller must not hold any locks which would prevent @fn from completing.
  4089. *
  4090. * Return: The value @fn returns.
  4091. */
  4092. long work_on_cpu(int cpu, long (*fn)(void *), void *arg)
  4093. {
  4094. struct work_for_cpu wfc = { .fn = fn, .arg = arg };
  4095. INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
  4096. schedule_work_on(cpu, &wfc.work);
  4097. flush_work(&wfc.work);
  4098. destroy_work_on_stack(&wfc.work);
  4099. return wfc.ret;
  4100. }
  4101. EXPORT_SYMBOL_GPL(work_on_cpu);
  4102. /**
  4103. * work_on_cpu_safe - run a function in thread context on a particular cpu
  4104. * @cpu: the cpu to run on
  4105. * @fn: the function to run
  4106. * @arg: the function argument
  4107. *
  4108. * Disables CPU hotplug and calls work_on_cpu(). The caller must not hold
  4109. * any locks which would prevent @fn from completing.
  4110. *
  4111. * Return: The value @fn returns.
  4112. */
  4113. long work_on_cpu_safe(int cpu, long (*fn)(void *), void *arg)
  4114. {
  4115. long ret = -ENODEV;
  4116. get_online_cpus();
  4117. if (cpu_online(cpu))
  4118. ret = work_on_cpu(cpu, fn, arg);
  4119. put_online_cpus();
  4120. return ret;
  4121. }
  4122. EXPORT_SYMBOL_GPL(work_on_cpu_safe);
  4123. #endif /* CONFIG_SMP */
  4124. #ifdef CONFIG_FREEZER
  4125. /**
  4126. * freeze_workqueues_begin - begin freezing workqueues
  4127. *
  4128. * Start freezing workqueues. After this function returns, all freezable
  4129. * workqueues will queue new works to their delayed_works list instead of
  4130. * pool->worklist.
  4131. *
  4132. * CONTEXT:
  4133. * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
  4134. */
  4135. void freeze_workqueues_begin(void)
  4136. {
  4137. struct workqueue_struct *wq;
  4138. struct pool_workqueue *pwq;
  4139. mutex_lock(&wq_pool_mutex);
  4140. WARN_ON_ONCE(workqueue_freezing);
  4141. workqueue_freezing = true;
  4142. list_for_each_entry(wq, &workqueues, list) {
  4143. mutex_lock(&wq->mutex);
  4144. for_each_pwq(pwq, wq)
  4145. pwq_adjust_max_active(pwq);
  4146. mutex_unlock(&wq->mutex);
  4147. }
  4148. mutex_unlock(&wq_pool_mutex);
  4149. }
  4150. /**
  4151. * freeze_workqueues_busy - are freezable workqueues still busy?
  4152. *
  4153. * Check whether freezing is complete. This function must be called
  4154. * between freeze_workqueues_begin() and thaw_workqueues().
  4155. *
  4156. * CONTEXT:
  4157. * Grabs and releases wq_pool_mutex.
  4158. *
  4159. * Return:
  4160. * %true if some freezable workqueues are still busy. %false if freezing
  4161. * is complete.
  4162. */
  4163. bool freeze_workqueues_busy(void)
  4164. {
  4165. bool busy = false;
  4166. struct workqueue_struct *wq;
  4167. struct pool_workqueue *pwq;
  4168. mutex_lock(&wq_pool_mutex);
  4169. WARN_ON_ONCE(!workqueue_freezing);
  4170. list_for_each_entry(wq, &workqueues, list) {
  4171. if (!(wq->flags & WQ_FREEZABLE))
  4172. continue;
  4173. /*
  4174. * nr_active is monotonically decreasing. It's safe
  4175. * to peek without lock.
  4176. */
  4177. rcu_read_lock_sched();
  4178. for_each_pwq(pwq, wq) {
  4179. WARN_ON_ONCE(pwq->nr_active < 0);
  4180. if (pwq->nr_active) {
  4181. busy = true;
  4182. rcu_read_unlock_sched();
  4183. goto out_unlock;
  4184. }
  4185. }
  4186. rcu_read_unlock_sched();
  4187. }
  4188. out_unlock:
  4189. mutex_unlock(&wq_pool_mutex);
  4190. return busy;
  4191. }
  4192. /**
  4193. * thaw_workqueues - thaw workqueues
  4194. *
  4195. * Thaw workqueues. Normal queueing is restored and all collected
  4196. * frozen works are transferred to their respective pool worklists.
  4197. *
  4198. * CONTEXT:
  4199. * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
  4200. */
  4201. void thaw_workqueues(void)
  4202. {
  4203. struct workqueue_struct *wq;
  4204. struct pool_workqueue *pwq;
  4205. mutex_lock(&wq_pool_mutex);
  4206. if (!workqueue_freezing)
  4207. goto out_unlock;
  4208. workqueue_freezing = false;
  4209. /* restore max_active and repopulate worklist */
  4210. list_for_each_entry(wq, &workqueues, list) {
  4211. mutex_lock(&wq->mutex);
  4212. for_each_pwq(pwq, wq)
  4213. pwq_adjust_max_active(pwq);
  4214. mutex_unlock(&wq->mutex);
  4215. }
  4216. out_unlock:
  4217. mutex_unlock(&wq_pool_mutex);
  4218. }
  4219. #endif /* CONFIG_FREEZER */
  4220. static int workqueue_apply_unbound_cpumask(void)
  4221. {
  4222. LIST_HEAD(ctxs);
  4223. int ret = 0;
  4224. struct workqueue_struct *wq;
  4225. struct apply_wqattrs_ctx *ctx, *n;
  4226. lockdep_assert_held(&wq_pool_mutex);
  4227. list_for_each_entry(wq, &workqueues, list) {
  4228. if (!(wq->flags & WQ_UNBOUND))
  4229. continue;
  4230. /* creating multiple pwqs breaks ordering guarantee */
  4231. if (wq->flags & __WQ_ORDERED)
  4232. continue;
  4233. ctx = apply_wqattrs_prepare(wq, wq->unbound_attrs);
  4234. if (!ctx) {
  4235. ret = -ENOMEM;
  4236. break;
  4237. }
  4238. list_add_tail(&ctx->list, &ctxs);
  4239. }
  4240. list_for_each_entry_safe(ctx, n, &ctxs, list) {
  4241. if (!ret)
  4242. apply_wqattrs_commit(ctx);
  4243. apply_wqattrs_cleanup(ctx);
  4244. }
  4245. return ret;
  4246. }
  4247. /**
  4248. * workqueue_set_unbound_cpumask - Set the low-level unbound cpumask
  4249. * @cpumask: the cpumask to set
  4250. *
  4251. * The low-level workqueues cpumask is a global cpumask that limits
  4252. * the affinity of all unbound workqueues. This function check the @cpumask
  4253. * and apply it to all unbound workqueues and updates all pwqs of them.
  4254. *
  4255. * Retun: 0 - Success
  4256. * -EINVAL - Invalid @cpumask
  4257. * -ENOMEM - Failed to allocate memory for attrs or pwqs.
  4258. */
  4259. int workqueue_set_unbound_cpumask(cpumask_var_t cpumask)
  4260. {
  4261. int ret = -EINVAL;
  4262. cpumask_var_t saved_cpumask;
  4263. if (!zalloc_cpumask_var(&saved_cpumask, GFP_KERNEL))
  4264. return -ENOMEM;
  4265. cpumask_and(cpumask, cpumask, cpu_possible_mask);
  4266. if (!cpumask_empty(cpumask)) {
  4267. apply_wqattrs_lock();
  4268. /* save the old wq_unbound_cpumask. */
  4269. cpumask_copy(saved_cpumask, wq_unbound_cpumask);
  4270. /* update wq_unbound_cpumask at first and apply it to wqs. */
  4271. cpumask_copy(wq_unbound_cpumask, cpumask);
  4272. ret = workqueue_apply_unbound_cpumask();
  4273. /* restore the wq_unbound_cpumask when failed. */
  4274. if (ret < 0)
  4275. cpumask_copy(wq_unbound_cpumask, saved_cpumask);
  4276. apply_wqattrs_unlock();
  4277. }
  4278. free_cpumask_var(saved_cpumask);
  4279. return ret;
  4280. }
  4281. #ifdef CONFIG_SYSFS
  4282. /*
  4283. * Workqueues with WQ_SYSFS flag set is visible to userland via
  4284. * /sys/bus/workqueue/devices/WQ_NAME. All visible workqueues have the
  4285. * following attributes.
  4286. *
  4287. * per_cpu RO bool : whether the workqueue is per-cpu or unbound
  4288. * max_active RW int : maximum number of in-flight work items
  4289. *
  4290. * Unbound workqueues have the following extra attributes.
  4291. *
  4292. * id RO int : the associated pool ID
  4293. * nice RW int : nice value of the workers
  4294. * cpumask RW mask : bitmask of allowed CPUs for the workers
  4295. */
  4296. struct wq_device {
  4297. struct workqueue_struct *wq;
  4298. struct device dev;
  4299. };
  4300. static struct workqueue_struct *dev_to_wq(struct device *dev)
  4301. {
  4302. struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
  4303. return wq_dev->wq;
  4304. }
  4305. static ssize_t per_cpu_show(struct device *dev, struct device_attribute *attr,
  4306. char *buf)
  4307. {
  4308. struct workqueue_struct *wq = dev_to_wq(dev);
  4309. return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND));
  4310. }
  4311. static DEVICE_ATTR_RO(per_cpu);
  4312. static ssize_t max_active_show(struct device *dev,
  4313. struct device_attribute *attr, char *buf)
  4314. {
  4315. struct workqueue_struct *wq = dev_to_wq(dev);
  4316. return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active);
  4317. }
  4318. static ssize_t max_active_store(struct device *dev,
  4319. struct device_attribute *attr, const char *buf,
  4320. size_t count)
  4321. {
  4322. struct workqueue_struct *wq = dev_to_wq(dev);
  4323. int val;
  4324. if (sscanf(buf, "%d", &val) != 1 || val <= 0)
  4325. return -EINVAL;
  4326. workqueue_set_max_active(wq, val);
  4327. return count;
  4328. }
  4329. static DEVICE_ATTR_RW(max_active);
  4330. static struct attribute *wq_sysfs_attrs[] = {
  4331. &dev_attr_per_cpu.attr,
  4332. &dev_attr_max_active.attr,
  4333. NULL,
  4334. };
  4335. ATTRIBUTE_GROUPS(wq_sysfs);
  4336. static ssize_t wq_pool_ids_show(struct device *dev,
  4337. struct device_attribute *attr, char *buf)
  4338. {
  4339. struct workqueue_struct *wq = dev_to_wq(dev);
  4340. const char *delim = "";
  4341. int node, written = 0;
  4342. rcu_read_lock_sched();
  4343. for_each_node(node) {
  4344. written += scnprintf(buf + written, PAGE_SIZE - written,
  4345. "%s%d:%d", delim, node,
  4346. unbound_pwq_by_node(wq, node)->pool->id);
  4347. delim = " ";
  4348. }
  4349. written += scnprintf(buf + written, PAGE_SIZE - written, "\n");
  4350. rcu_read_unlock_sched();
  4351. return written;
  4352. }
  4353. static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr,
  4354. char *buf)
  4355. {
  4356. struct workqueue_struct *wq = dev_to_wq(dev);
  4357. int written;
  4358. mutex_lock(&wq->mutex);
  4359. written = scnprintf(buf, PAGE_SIZE, "%d\n", wq->unbound_attrs->nice);
  4360. mutex_unlock(&wq->mutex);
  4361. return written;
  4362. }
  4363. /* prepare workqueue_attrs for sysfs store operations */
  4364. static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq)
  4365. {
  4366. struct workqueue_attrs *attrs;
  4367. lockdep_assert_held(&wq_pool_mutex);
  4368. attrs = alloc_workqueue_attrs(GFP_KERNEL);
  4369. if (!attrs)
  4370. return NULL;
  4371. copy_workqueue_attrs(attrs, wq->unbound_attrs);
  4372. return attrs;
  4373. }
  4374. static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr,
  4375. const char *buf, size_t count)
  4376. {
  4377. struct workqueue_struct *wq = dev_to_wq(dev);
  4378. struct workqueue_attrs *attrs;
  4379. int ret = -ENOMEM;
  4380. apply_wqattrs_lock();
  4381. attrs = wq_sysfs_prep_attrs(wq);
  4382. if (!attrs)
  4383. goto out_unlock;
  4384. if (sscanf(buf, "%d", &attrs->nice) == 1 &&
  4385. attrs->nice >= MIN_NICE && attrs->nice <= MAX_NICE)
  4386. ret = apply_workqueue_attrs_locked(wq, attrs);
  4387. else
  4388. ret = -EINVAL;
  4389. out_unlock:
  4390. apply_wqattrs_unlock();
  4391. free_workqueue_attrs(attrs);
  4392. return ret ?: count;
  4393. }
  4394. static ssize_t wq_cpumask_show(struct device *dev,
  4395. struct device_attribute *attr, char *buf)
  4396. {
  4397. struct workqueue_struct *wq = dev_to_wq(dev);
  4398. int written;
  4399. mutex_lock(&wq->mutex);
  4400. written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
  4401. cpumask_pr_args(wq->unbound_attrs->cpumask));
  4402. mutex_unlock(&wq->mutex);
  4403. return written;
  4404. }
  4405. static ssize_t wq_cpumask_store(struct device *dev,
  4406. struct device_attribute *attr,
  4407. const char *buf, size_t count)
  4408. {
  4409. struct workqueue_struct *wq = dev_to_wq(dev);
  4410. struct workqueue_attrs *attrs;
  4411. int ret = -ENOMEM;
  4412. apply_wqattrs_lock();
  4413. attrs = wq_sysfs_prep_attrs(wq);
  4414. if (!attrs)
  4415. goto out_unlock;
  4416. ret = cpumask_parse(buf, attrs->cpumask);
  4417. if (!ret)
  4418. ret = apply_workqueue_attrs_locked(wq, attrs);
  4419. out_unlock:
  4420. apply_wqattrs_unlock();
  4421. free_workqueue_attrs(attrs);
  4422. return ret ?: count;
  4423. }
  4424. static ssize_t wq_numa_show(struct device *dev, struct device_attribute *attr,
  4425. char *buf)
  4426. {
  4427. struct workqueue_struct *wq = dev_to_wq(dev);
  4428. int written;
  4429. mutex_lock(&wq->mutex);
  4430. written = scnprintf(buf, PAGE_SIZE, "%d\n",
  4431. !wq->unbound_attrs->no_numa);
  4432. mutex_unlock(&wq->mutex);
  4433. return written;
  4434. }
  4435. static ssize_t wq_numa_store(struct device *dev, struct device_attribute *attr,
  4436. const char *buf, size_t count)
  4437. {
  4438. struct workqueue_struct *wq = dev_to_wq(dev);
  4439. struct workqueue_attrs *attrs;
  4440. int v, ret = -ENOMEM;
  4441. apply_wqattrs_lock();
  4442. attrs = wq_sysfs_prep_attrs(wq);
  4443. if (!attrs)
  4444. goto out_unlock;
  4445. ret = -EINVAL;
  4446. if (sscanf(buf, "%d", &v) == 1) {
  4447. attrs->no_numa = !v;
  4448. ret = apply_workqueue_attrs_locked(wq, attrs);
  4449. }
  4450. out_unlock:
  4451. apply_wqattrs_unlock();
  4452. free_workqueue_attrs(attrs);
  4453. return ret ?: count;
  4454. }
  4455. static struct device_attribute wq_sysfs_unbound_attrs[] = {
  4456. __ATTR(pool_ids, 0444, wq_pool_ids_show, NULL),
  4457. __ATTR(nice, 0644, wq_nice_show, wq_nice_store),
  4458. __ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store),
  4459. __ATTR(numa, 0644, wq_numa_show, wq_numa_store),
  4460. __ATTR_NULL,
  4461. };
  4462. static struct bus_type wq_subsys = {
  4463. .name = "workqueue",
  4464. .dev_groups = wq_sysfs_groups,
  4465. };
  4466. static ssize_t wq_unbound_cpumask_show(struct device *dev,
  4467. struct device_attribute *attr, char *buf)
  4468. {
  4469. int written;
  4470. mutex_lock(&wq_pool_mutex);
  4471. written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
  4472. cpumask_pr_args(wq_unbound_cpumask));
  4473. mutex_unlock(&wq_pool_mutex);
  4474. return written;
  4475. }
  4476. static ssize_t wq_unbound_cpumask_store(struct device *dev,
  4477. struct device_attribute *attr, const char *buf, size_t count)
  4478. {
  4479. cpumask_var_t cpumask;
  4480. int ret;
  4481. if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
  4482. return -ENOMEM;
  4483. ret = cpumask_parse(buf, cpumask);
  4484. if (!ret)
  4485. ret = workqueue_set_unbound_cpumask(cpumask);
  4486. free_cpumask_var(cpumask);
  4487. return ret ? ret : count;
  4488. }
  4489. static struct device_attribute wq_sysfs_cpumask_attr =
  4490. __ATTR(cpumask, 0644, wq_unbound_cpumask_show,
  4491. wq_unbound_cpumask_store);
  4492. static int __init wq_sysfs_init(void)
  4493. {
  4494. int err;
  4495. err = subsys_virtual_register(&wq_subsys, NULL);
  4496. if (err)
  4497. return err;
  4498. return device_create_file(wq_subsys.dev_root, &wq_sysfs_cpumask_attr);
  4499. }
  4500. core_initcall(wq_sysfs_init);
  4501. static void wq_device_release(struct device *dev)
  4502. {
  4503. struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
  4504. kfree(wq_dev);
  4505. }
  4506. /**
  4507. * workqueue_sysfs_register - make a workqueue visible in sysfs
  4508. * @wq: the workqueue to register
  4509. *
  4510. * Expose @wq in sysfs under /sys/bus/workqueue/devices.
  4511. * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
  4512. * which is the preferred method.
  4513. *
  4514. * Workqueue user should use this function directly iff it wants to apply
  4515. * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
  4516. * apply_workqueue_attrs() may race against userland updating the
  4517. * attributes.
  4518. *
  4519. * Return: 0 on success, -errno on failure.
  4520. */
  4521. int workqueue_sysfs_register(struct workqueue_struct *wq)
  4522. {
  4523. struct wq_device *wq_dev;
  4524. int ret;
  4525. /*
  4526. * Adjusting max_active or creating new pwqs by applying
  4527. * attributes breaks ordering guarantee. Disallow exposing ordered
  4528. * workqueues.
  4529. */
  4530. if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
  4531. return -EINVAL;
  4532. wq->wq_dev = wq_dev = kzalloc(sizeof(*wq_dev), GFP_KERNEL);
  4533. if (!wq_dev)
  4534. return -ENOMEM;
  4535. wq_dev->wq = wq;
  4536. wq_dev->dev.bus = &wq_subsys;
  4537. wq_dev->dev.release = wq_device_release;
  4538. dev_set_name(&wq_dev->dev, "%s", wq->name);
  4539. /*
  4540. * unbound_attrs are created separately. Suppress uevent until
  4541. * everything is ready.
  4542. */
  4543. dev_set_uevent_suppress(&wq_dev->dev, true);
  4544. ret = device_register(&wq_dev->dev);
  4545. if (ret) {
  4546. kfree(wq_dev);
  4547. wq->wq_dev = NULL;
  4548. return ret;
  4549. }
  4550. if (wq->flags & WQ_UNBOUND) {
  4551. struct device_attribute *attr;
  4552. for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) {
  4553. ret = device_create_file(&wq_dev->dev, attr);
  4554. if (ret) {
  4555. device_unregister(&wq_dev->dev);
  4556. wq->wq_dev = NULL;
  4557. return ret;
  4558. }
  4559. }
  4560. }
  4561. dev_set_uevent_suppress(&wq_dev->dev, false);
  4562. kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD);
  4563. return 0;
  4564. }
  4565. /**
  4566. * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
  4567. * @wq: the workqueue to unregister
  4568. *
  4569. * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
  4570. */
  4571. static void workqueue_sysfs_unregister(struct workqueue_struct *wq)
  4572. {
  4573. struct wq_device *wq_dev = wq->wq_dev;
  4574. if (!wq->wq_dev)
  4575. return;
  4576. wq->wq_dev = NULL;
  4577. device_unregister(&wq_dev->dev);
  4578. }
  4579. #else /* CONFIG_SYSFS */
  4580. static void workqueue_sysfs_unregister(struct workqueue_struct *wq) { }
  4581. #endif /* CONFIG_SYSFS */
  4582. /*
  4583. * Workqueue watchdog.
  4584. *
  4585. * Stall may be caused by various bugs - missing WQ_MEM_RECLAIM, illegal
  4586. * flush dependency, a concurrency managed work item which stays RUNNING
  4587. * indefinitely. Workqueue stalls can be very difficult to debug as the
  4588. * usual warning mechanisms don't trigger and internal workqueue state is
  4589. * largely opaque.
  4590. *
  4591. * Workqueue watchdog monitors all worker pools periodically and dumps
  4592. * state if some pools failed to make forward progress for a while where
  4593. * forward progress is defined as the first item on ->worklist changing.
  4594. *
  4595. * This mechanism is controlled through the kernel parameter
  4596. * "workqueue.watchdog_thresh" which can be updated at runtime through the
  4597. * corresponding sysfs parameter file.
  4598. */
  4599. #ifdef CONFIG_WQ_WATCHDOG
  4600. static unsigned long wq_watchdog_thresh = 30;
  4601. static struct timer_list wq_watchdog_timer;
  4602. static unsigned long wq_watchdog_touched = INITIAL_JIFFIES;
  4603. static DEFINE_PER_CPU(unsigned long, wq_watchdog_touched_cpu) = INITIAL_JIFFIES;
  4604. static void wq_watchdog_reset_touched(void)
  4605. {
  4606. int cpu;
  4607. wq_watchdog_touched = jiffies;
  4608. for_each_possible_cpu(cpu)
  4609. per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
  4610. }
  4611. static void wq_watchdog_timer_fn(struct timer_list *unused)
  4612. {
  4613. unsigned long thresh = READ_ONCE(wq_watchdog_thresh) * HZ;
  4614. bool lockup_detected = false;
  4615. struct worker_pool *pool;
  4616. int pi;
  4617. if (!thresh)
  4618. return;
  4619. rcu_read_lock();
  4620. for_each_pool(pool, pi) {
  4621. unsigned long pool_ts, touched, ts;
  4622. if (list_empty(&pool->worklist))
  4623. continue;
  4624. /* get the latest of pool and touched timestamps */
  4625. pool_ts = READ_ONCE(pool->watchdog_ts);
  4626. touched = READ_ONCE(wq_watchdog_touched);
  4627. if (time_after(pool_ts, touched))
  4628. ts = pool_ts;
  4629. else
  4630. ts = touched;
  4631. if (pool->cpu >= 0) {
  4632. unsigned long cpu_touched =
  4633. READ_ONCE(per_cpu(wq_watchdog_touched_cpu,
  4634. pool->cpu));
  4635. if (time_after(cpu_touched, ts))
  4636. ts = cpu_touched;
  4637. }
  4638. /* did we stall? */
  4639. if (time_after(jiffies, ts + thresh)) {
  4640. lockup_detected = true;
  4641. pr_emerg("BUG: workqueue lockup - pool");
  4642. pr_cont_pool_info(pool);
  4643. pr_cont(" stuck for %us!\n",
  4644. jiffies_to_msecs(jiffies - pool_ts) / 1000);
  4645. }
  4646. }
  4647. rcu_read_unlock();
  4648. if (lockup_detected)
  4649. show_workqueue_state();
  4650. wq_watchdog_reset_touched();
  4651. mod_timer(&wq_watchdog_timer, jiffies + thresh);
  4652. }
  4653. void wq_watchdog_touch(int cpu)
  4654. {
  4655. if (cpu >= 0)
  4656. per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
  4657. else
  4658. wq_watchdog_touched = jiffies;
  4659. }
  4660. static void wq_watchdog_set_thresh(unsigned long thresh)
  4661. {
  4662. wq_watchdog_thresh = 0;
  4663. del_timer_sync(&wq_watchdog_timer);
  4664. if (thresh) {
  4665. wq_watchdog_thresh = thresh;
  4666. wq_watchdog_reset_touched();
  4667. mod_timer(&wq_watchdog_timer, jiffies + thresh * HZ);
  4668. }
  4669. }
  4670. static int wq_watchdog_param_set_thresh(const char *val,
  4671. const struct kernel_param *kp)
  4672. {
  4673. unsigned long thresh;
  4674. int ret;
  4675. ret = kstrtoul(val, 0, &thresh);
  4676. if (ret)
  4677. return ret;
  4678. if (system_wq)
  4679. wq_watchdog_set_thresh(thresh);
  4680. else
  4681. wq_watchdog_thresh = thresh;
  4682. return 0;
  4683. }
  4684. static const struct kernel_param_ops wq_watchdog_thresh_ops = {
  4685. .set = wq_watchdog_param_set_thresh,
  4686. .get = param_get_ulong,
  4687. };
  4688. module_param_cb(watchdog_thresh, &wq_watchdog_thresh_ops, &wq_watchdog_thresh,
  4689. 0644);
  4690. static void wq_watchdog_init(void)
  4691. {
  4692. timer_setup(&wq_watchdog_timer, wq_watchdog_timer_fn, TIMER_DEFERRABLE);
  4693. wq_watchdog_set_thresh(wq_watchdog_thresh);
  4694. }
  4695. #else /* CONFIG_WQ_WATCHDOG */
  4696. static inline void wq_watchdog_init(void) { }
  4697. #endif /* CONFIG_WQ_WATCHDOG */
  4698. static void __init wq_numa_init(void)
  4699. {
  4700. cpumask_var_t *tbl;
  4701. int node, cpu;
  4702. if (num_possible_nodes() <= 1)
  4703. return;
  4704. if (wq_disable_numa) {
  4705. pr_info("workqueue: NUMA affinity support disabled\n");
  4706. return;
  4707. }
  4708. wq_update_unbound_numa_attrs_buf = alloc_workqueue_attrs(GFP_KERNEL);
  4709. BUG_ON(!wq_update_unbound_numa_attrs_buf);
  4710. /*
  4711. * We want masks of possible CPUs of each node which isn't readily
  4712. * available. Build one from cpu_to_node() which should have been
  4713. * fully initialized by now.
  4714. */
  4715. tbl = kzalloc(nr_node_ids * sizeof(tbl[0]), GFP_KERNEL);
  4716. BUG_ON(!tbl);
  4717. for_each_node(node)
  4718. BUG_ON(!zalloc_cpumask_var_node(&tbl[node], GFP_KERNEL,
  4719. node_online(node) ? node : NUMA_NO_NODE));
  4720. for_each_possible_cpu(cpu) {
  4721. node = cpu_to_node(cpu);
  4722. if (WARN_ON(node == NUMA_NO_NODE)) {
  4723. pr_warn("workqueue: NUMA node mapping not available for cpu%d, disabling NUMA support\n", cpu);
  4724. /* happens iff arch is bonkers, let's just proceed */
  4725. return;
  4726. }
  4727. cpumask_set_cpu(cpu, tbl[node]);
  4728. }
  4729. wq_numa_possible_cpumask = tbl;
  4730. wq_numa_enabled = true;
  4731. }
  4732. /**
  4733. * workqueue_init_early - early init for workqueue subsystem
  4734. *
  4735. * This is the first half of two-staged workqueue subsystem initialization
  4736. * and invoked as soon as the bare basics - memory allocation, cpumasks and
  4737. * idr are up. It sets up all the data structures and system workqueues
  4738. * and allows early boot code to create workqueues and queue/cancel work
  4739. * items. Actual work item execution starts only after kthreads can be
  4740. * created and scheduled right before early initcalls.
  4741. */
  4742. int __init workqueue_init_early(void)
  4743. {
  4744. int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
  4745. int i, cpu;
  4746. WARN_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
  4747. BUG_ON(!alloc_cpumask_var(&wq_unbound_cpumask, GFP_KERNEL));
  4748. cpumask_copy(wq_unbound_cpumask, cpu_possible_mask);
  4749. pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
  4750. /* initialize CPU pools */
  4751. for_each_possible_cpu(cpu) {
  4752. struct worker_pool *pool;
  4753. i = 0;
  4754. for_each_cpu_worker_pool(pool, cpu) {
  4755. BUG_ON(init_worker_pool(pool));
  4756. pool->cpu = cpu;
  4757. cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
  4758. pool->attrs->nice = std_nice[i++];
  4759. pool->node = cpu_to_node(cpu);
  4760. /* alloc pool ID */
  4761. mutex_lock(&wq_pool_mutex);
  4762. BUG_ON(worker_pool_assign_id(pool));
  4763. mutex_unlock(&wq_pool_mutex);
  4764. }
  4765. }
  4766. /* create default unbound and ordered wq attrs */
  4767. for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
  4768. struct workqueue_attrs *attrs;
  4769. BUG_ON(!(attrs = alloc_workqueue_attrs(GFP_KERNEL)));
  4770. attrs->nice = std_nice[i];
  4771. unbound_std_wq_attrs[i] = attrs;
  4772. /*
  4773. * An ordered wq should have only one pwq as ordering is
  4774. * guaranteed by max_active which is enforced by pwqs.
  4775. * Turn off NUMA so that dfl_pwq is used for all nodes.
  4776. */
  4777. BUG_ON(!(attrs = alloc_workqueue_attrs(GFP_KERNEL)));
  4778. attrs->nice = std_nice[i];
  4779. attrs->no_numa = true;
  4780. ordered_wq_attrs[i] = attrs;
  4781. }
  4782. system_wq = alloc_workqueue("events", 0, 0);
  4783. system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
  4784. system_long_wq = alloc_workqueue("events_long", 0, 0);
  4785. system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
  4786. WQ_UNBOUND_MAX_ACTIVE);
  4787. system_freezable_wq = alloc_workqueue("events_freezable",
  4788. WQ_FREEZABLE, 0);
  4789. system_power_efficient_wq = alloc_workqueue("events_power_efficient",
  4790. WQ_POWER_EFFICIENT, 0);
  4791. system_freezable_power_efficient_wq = alloc_workqueue("events_freezable_power_efficient",
  4792. WQ_FREEZABLE | WQ_POWER_EFFICIENT,
  4793. 0);
  4794. BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
  4795. !system_unbound_wq || !system_freezable_wq ||
  4796. !system_power_efficient_wq ||
  4797. !system_freezable_power_efficient_wq);
  4798. return 0;
  4799. }
  4800. /**
  4801. * workqueue_init - bring workqueue subsystem fully online
  4802. *
  4803. * This is the latter half of two-staged workqueue subsystem initialization
  4804. * and invoked as soon as kthreads can be created and scheduled.
  4805. * Workqueues have been created and work items queued on them, but there
  4806. * are no kworkers executing the work items yet. Populate the worker pools
  4807. * with the initial workers and enable future kworker creations.
  4808. */
  4809. int __init workqueue_init(void)
  4810. {
  4811. struct workqueue_struct *wq;
  4812. struct worker_pool *pool;
  4813. int cpu, bkt;
  4814. /*
  4815. * It'd be simpler to initialize NUMA in workqueue_init_early() but
  4816. * CPU to node mapping may not be available that early on some
  4817. * archs such as power and arm64. As per-cpu pools created
  4818. * previously could be missing node hint and unbound pools NUMA
  4819. * affinity, fix them up.
  4820. */
  4821. wq_numa_init();
  4822. mutex_lock(&wq_pool_mutex);
  4823. for_each_possible_cpu(cpu) {
  4824. for_each_cpu_worker_pool(pool, cpu) {
  4825. pool->node = cpu_to_node(cpu);
  4826. }
  4827. }
  4828. list_for_each_entry(wq, &workqueues, list)
  4829. wq_update_unbound_numa(wq, smp_processor_id(), true);
  4830. mutex_unlock(&wq_pool_mutex);
  4831. /* create the initial workers */
  4832. for_each_online_cpu(cpu) {
  4833. for_each_cpu_worker_pool(pool, cpu) {
  4834. pool->flags &= ~POOL_DISASSOCIATED;
  4835. BUG_ON(!create_worker(pool));
  4836. }
  4837. }
  4838. hash_for_each(unbound_pool_hash, bkt, pool, hash_node)
  4839. BUG_ON(!create_worker(pool));
  4840. wq_online = true;
  4841. wq_watchdog_init();
  4842. return 0;
  4843. }