workqueue.c 138 KB

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