workqueue.c 123 KB

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