workqueue.c 136 KB

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