workqueue.c 135 KB

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