workqueue.c 114 KB

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