workqueue.c 116 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242
  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. retry:
  1075. /* pwq which will be used unless @work is executing elsewhere */
  1076. if (!(wq->flags & WQ_UNBOUND)) {
  1077. if (cpu == WORK_CPU_UNBOUND)
  1078. cpu = raw_smp_processor_id();
  1079. pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
  1080. } else {
  1081. pwq = first_pwq(wq);
  1082. }
  1083. /*
  1084. * If @work was previously on a different pool, it might still be
  1085. * running there, in which case the work needs to be queued on that
  1086. * pool to guarantee non-reentrancy.
  1087. */
  1088. last_pool = get_work_pool(work);
  1089. if (last_pool && last_pool != pwq->pool) {
  1090. struct worker *worker;
  1091. spin_lock(&last_pool->lock);
  1092. worker = find_worker_executing_work(last_pool, work);
  1093. if (worker && worker->current_pwq->wq == wq) {
  1094. pwq = worker->current_pwq;
  1095. } else {
  1096. /* meh... not running there, queue here */
  1097. spin_unlock(&last_pool->lock);
  1098. spin_lock(&pwq->pool->lock);
  1099. }
  1100. } else {
  1101. spin_lock(&pwq->pool->lock);
  1102. }
  1103. /*
  1104. * pwq is determined and locked. For unbound pools, we could have
  1105. * raced with pwq release and it could already be dead. If its
  1106. * refcnt is zero, repeat pwq selection. Note that pwqs never die
  1107. * without another pwq replacing it as the first pwq or while a
  1108. * work item is executing on it, so the retying is guaranteed to
  1109. * make forward-progress.
  1110. */
  1111. if (unlikely(!pwq->refcnt)) {
  1112. if (wq->flags & WQ_UNBOUND) {
  1113. spin_unlock(&pwq->pool->lock);
  1114. cpu_relax();
  1115. goto retry;
  1116. }
  1117. /* oops */
  1118. WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
  1119. wq->name, cpu);
  1120. }
  1121. /* pwq determined, queue */
  1122. trace_workqueue_queue_work(req_cpu, pwq, work);
  1123. if (WARN_ON(!list_empty(&work->entry))) {
  1124. spin_unlock(&pwq->pool->lock);
  1125. return;
  1126. }
  1127. pwq->nr_in_flight[pwq->work_color]++;
  1128. work_flags = work_color_to_flags(pwq->work_color);
  1129. if (likely(pwq->nr_active < pwq->max_active)) {
  1130. trace_workqueue_activate_work(work);
  1131. pwq->nr_active++;
  1132. worklist = &pwq->pool->worklist;
  1133. } else {
  1134. work_flags |= WORK_STRUCT_DELAYED;
  1135. worklist = &pwq->delayed_works;
  1136. }
  1137. insert_work(pwq, work, worklist, work_flags);
  1138. spin_unlock(&pwq->pool->lock);
  1139. }
  1140. /**
  1141. * queue_work_on - queue work on specific cpu
  1142. * @cpu: CPU number to execute work on
  1143. * @wq: workqueue to use
  1144. * @work: work to queue
  1145. *
  1146. * Returns %false if @work was already on a queue, %true otherwise.
  1147. *
  1148. * We queue the work to a specific CPU, the caller must ensure it
  1149. * can't go away.
  1150. */
  1151. bool queue_work_on(int cpu, struct workqueue_struct *wq,
  1152. struct work_struct *work)
  1153. {
  1154. bool ret = false;
  1155. unsigned long flags;
  1156. local_irq_save(flags);
  1157. if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
  1158. __queue_work(cpu, wq, work);
  1159. ret = true;
  1160. }
  1161. local_irq_restore(flags);
  1162. return ret;
  1163. }
  1164. EXPORT_SYMBOL_GPL(queue_work_on);
  1165. /**
  1166. * queue_work - queue work on a workqueue
  1167. * @wq: workqueue to use
  1168. * @work: work to queue
  1169. *
  1170. * Returns %false if @work was already on a queue, %true otherwise.
  1171. *
  1172. * We queue the work to the CPU on which it was submitted, but if the CPU dies
  1173. * it can be processed by another CPU.
  1174. */
  1175. bool queue_work(struct workqueue_struct *wq, struct work_struct *work)
  1176. {
  1177. return queue_work_on(WORK_CPU_UNBOUND, wq, work);
  1178. }
  1179. EXPORT_SYMBOL_GPL(queue_work);
  1180. void delayed_work_timer_fn(unsigned long __data)
  1181. {
  1182. struct delayed_work *dwork = (struct delayed_work *)__data;
  1183. /* should have been called from irqsafe timer with irq already off */
  1184. __queue_work(dwork->cpu, dwork->wq, &dwork->work);
  1185. }
  1186. EXPORT_SYMBOL(delayed_work_timer_fn);
  1187. static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
  1188. struct delayed_work *dwork, unsigned long delay)
  1189. {
  1190. struct timer_list *timer = &dwork->timer;
  1191. struct work_struct *work = &dwork->work;
  1192. WARN_ON_ONCE(timer->function != delayed_work_timer_fn ||
  1193. timer->data != (unsigned long)dwork);
  1194. WARN_ON_ONCE(timer_pending(timer));
  1195. WARN_ON_ONCE(!list_empty(&work->entry));
  1196. /*
  1197. * If @delay is 0, queue @dwork->work immediately. This is for
  1198. * both optimization and correctness. The earliest @timer can
  1199. * expire is on the closest next tick and delayed_work users depend
  1200. * on that there's no such delay when @delay is 0.
  1201. */
  1202. if (!delay) {
  1203. __queue_work(cpu, wq, &dwork->work);
  1204. return;
  1205. }
  1206. timer_stats_timer_set_start_info(&dwork->timer);
  1207. dwork->wq = wq;
  1208. dwork->cpu = cpu;
  1209. timer->expires = jiffies + delay;
  1210. if (unlikely(cpu != WORK_CPU_UNBOUND))
  1211. add_timer_on(timer, cpu);
  1212. else
  1213. add_timer(timer);
  1214. }
  1215. /**
  1216. * queue_delayed_work_on - queue work on specific CPU after delay
  1217. * @cpu: CPU number to execute work on
  1218. * @wq: workqueue to use
  1219. * @dwork: work to queue
  1220. * @delay: number of jiffies to wait before queueing
  1221. *
  1222. * Returns %false if @work was already on a queue, %true otherwise. If
  1223. * @delay is zero and @dwork is idle, it will be scheduled for immediate
  1224. * execution.
  1225. */
  1226. bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
  1227. struct delayed_work *dwork, unsigned long delay)
  1228. {
  1229. struct work_struct *work = &dwork->work;
  1230. bool ret = false;
  1231. unsigned long flags;
  1232. /* read the comment in __queue_work() */
  1233. local_irq_save(flags);
  1234. if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
  1235. __queue_delayed_work(cpu, wq, dwork, delay);
  1236. ret = true;
  1237. }
  1238. local_irq_restore(flags);
  1239. return ret;
  1240. }
  1241. EXPORT_SYMBOL_GPL(queue_delayed_work_on);
  1242. /**
  1243. * queue_delayed_work - queue work on a workqueue after delay
  1244. * @wq: workqueue to use
  1245. * @dwork: delayable work to queue
  1246. * @delay: number of jiffies to wait before queueing
  1247. *
  1248. * Equivalent to queue_delayed_work_on() but tries to use the local CPU.
  1249. */
  1250. bool queue_delayed_work(struct workqueue_struct *wq,
  1251. struct delayed_work *dwork, unsigned long delay)
  1252. {
  1253. return queue_delayed_work_on(WORK_CPU_UNBOUND, wq, dwork, delay);
  1254. }
  1255. EXPORT_SYMBOL_GPL(queue_delayed_work);
  1256. /**
  1257. * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
  1258. * @cpu: CPU number to execute work on
  1259. * @wq: workqueue to use
  1260. * @dwork: work to queue
  1261. * @delay: number of jiffies to wait before queueing
  1262. *
  1263. * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
  1264. * modify @dwork's timer so that it expires after @delay. If @delay is
  1265. * zero, @work is guaranteed to be scheduled immediately regardless of its
  1266. * current state.
  1267. *
  1268. * Returns %false if @dwork was idle and queued, %true if @dwork was
  1269. * pending and its timer was modified.
  1270. *
  1271. * This function is safe to call from any context including IRQ handler.
  1272. * See try_to_grab_pending() for details.
  1273. */
  1274. bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
  1275. struct delayed_work *dwork, unsigned long delay)
  1276. {
  1277. unsigned long flags;
  1278. int ret;
  1279. do {
  1280. ret = try_to_grab_pending(&dwork->work, true, &flags);
  1281. } while (unlikely(ret == -EAGAIN));
  1282. if (likely(ret >= 0)) {
  1283. __queue_delayed_work(cpu, wq, dwork, delay);
  1284. local_irq_restore(flags);
  1285. }
  1286. /* -ENOENT from try_to_grab_pending() becomes %true */
  1287. return ret;
  1288. }
  1289. EXPORT_SYMBOL_GPL(mod_delayed_work_on);
  1290. /**
  1291. * mod_delayed_work - modify delay of or queue a delayed work
  1292. * @wq: workqueue to use
  1293. * @dwork: work to queue
  1294. * @delay: number of jiffies to wait before queueing
  1295. *
  1296. * mod_delayed_work_on() on local CPU.
  1297. */
  1298. bool mod_delayed_work(struct workqueue_struct *wq, struct delayed_work *dwork,
  1299. unsigned long delay)
  1300. {
  1301. return mod_delayed_work_on(WORK_CPU_UNBOUND, wq, dwork, delay);
  1302. }
  1303. EXPORT_SYMBOL_GPL(mod_delayed_work);
  1304. /**
  1305. * worker_enter_idle - enter idle state
  1306. * @worker: worker which is entering idle state
  1307. *
  1308. * @worker is entering idle state. Update stats and idle timer if
  1309. * necessary.
  1310. *
  1311. * LOCKING:
  1312. * spin_lock_irq(pool->lock).
  1313. */
  1314. static void worker_enter_idle(struct worker *worker)
  1315. {
  1316. struct worker_pool *pool = worker->pool;
  1317. if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
  1318. WARN_ON_ONCE(!list_empty(&worker->entry) &&
  1319. (worker->hentry.next || worker->hentry.pprev)))
  1320. return;
  1321. /* can't use worker_set_flags(), also called from start_worker() */
  1322. worker->flags |= WORKER_IDLE;
  1323. pool->nr_idle++;
  1324. worker->last_active = jiffies;
  1325. /* idle_list is LIFO */
  1326. list_add(&worker->entry, &pool->idle_list);
  1327. if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
  1328. mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
  1329. /*
  1330. * Sanity check nr_running. Because wq_unbind_fn() releases
  1331. * pool->lock between setting %WORKER_UNBOUND and zapping
  1332. * nr_running, the warning may trigger spuriously. Check iff
  1333. * unbind is not in progress.
  1334. */
  1335. WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
  1336. pool->nr_workers == pool->nr_idle &&
  1337. atomic_read(&pool->nr_running));
  1338. }
  1339. /**
  1340. * worker_leave_idle - leave idle state
  1341. * @worker: worker which is leaving idle state
  1342. *
  1343. * @worker is leaving idle state. Update stats.
  1344. *
  1345. * LOCKING:
  1346. * spin_lock_irq(pool->lock).
  1347. */
  1348. static void worker_leave_idle(struct worker *worker)
  1349. {
  1350. struct worker_pool *pool = worker->pool;
  1351. if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
  1352. return;
  1353. worker_clr_flags(worker, WORKER_IDLE);
  1354. pool->nr_idle--;
  1355. list_del_init(&worker->entry);
  1356. }
  1357. /**
  1358. * worker_maybe_bind_and_lock - try to bind %current to worker_pool and lock it
  1359. * @pool: target worker_pool
  1360. *
  1361. * Bind %current to the cpu of @pool if it is associated and lock @pool.
  1362. *
  1363. * Works which are scheduled while the cpu is online must at least be
  1364. * scheduled to a worker which is bound to the cpu so that if they are
  1365. * flushed from cpu callbacks while cpu is going down, they are
  1366. * guaranteed to execute on the cpu.
  1367. *
  1368. * This function is to be used by unbound workers and rescuers to bind
  1369. * themselves to the target cpu and may race with cpu going down or
  1370. * coming online. kthread_bind() can't be used because it may put the
  1371. * worker to already dead cpu and set_cpus_allowed_ptr() can't be used
  1372. * verbatim as it's best effort and blocking and pool may be
  1373. * [dis]associated in the meantime.
  1374. *
  1375. * This function tries set_cpus_allowed() and locks pool and verifies the
  1376. * binding against %POOL_DISASSOCIATED which is set during
  1377. * %CPU_DOWN_PREPARE and cleared during %CPU_ONLINE, so if the worker
  1378. * enters idle state or fetches works without dropping lock, it can
  1379. * guarantee the scheduling requirement described in the first paragraph.
  1380. *
  1381. * CONTEXT:
  1382. * Might sleep. Called without any lock but returns with pool->lock
  1383. * held.
  1384. *
  1385. * RETURNS:
  1386. * %true if the associated pool is online (@worker is successfully
  1387. * bound), %false if offline.
  1388. */
  1389. static bool worker_maybe_bind_and_lock(struct worker_pool *pool)
  1390. __acquires(&pool->lock)
  1391. {
  1392. while (true) {
  1393. /*
  1394. * The following call may fail, succeed or succeed
  1395. * without actually migrating the task to the cpu if
  1396. * it races with cpu hotunplug operation. Verify
  1397. * against POOL_DISASSOCIATED.
  1398. */
  1399. if (!(pool->flags & POOL_DISASSOCIATED))
  1400. set_cpus_allowed_ptr(current, pool->attrs->cpumask);
  1401. spin_lock_irq(&pool->lock);
  1402. if (pool->flags & POOL_DISASSOCIATED)
  1403. return false;
  1404. if (task_cpu(current) == pool->cpu &&
  1405. cpumask_equal(&current->cpus_allowed, pool->attrs->cpumask))
  1406. return true;
  1407. spin_unlock_irq(&pool->lock);
  1408. /*
  1409. * We've raced with CPU hot[un]plug. Give it a breather
  1410. * and retry migration. cond_resched() is required here;
  1411. * otherwise, we might deadlock against cpu_stop trying to
  1412. * bring down the CPU on non-preemptive kernel.
  1413. */
  1414. cpu_relax();
  1415. cond_resched();
  1416. }
  1417. }
  1418. /*
  1419. * Rebind an idle @worker to its CPU. worker_thread() will test
  1420. * list_empty(@worker->entry) before leaving idle and call this function.
  1421. */
  1422. static void idle_worker_rebind(struct worker *worker)
  1423. {
  1424. /* CPU may go down again inbetween, clear UNBOUND only on success */
  1425. if (worker_maybe_bind_and_lock(worker->pool))
  1426. worker_clr_flags(worker, WORKER_UNBOUND);
  1427. /* rebind complete, become available again */
  1428. list_add(&worker->entry, &worker->pool->idle_list);
  1429. spin_unlock_irq(&worker->pool->lock);
  1430. }
  1431. /*
  1432. * Function for @worker->rebind.work used to rebind unbound busy workers to
  1433. * the associated cpu which is coming back online. This is scheduled by
  1434. * cpu up but can race with other cpu hotplug operations and may be
  1435. * executed twice without intervening cpu down.
  1436. */
  1437. static void busy_worker_rebind_fn(struct work_struct *work)
  1438. {
  1439. struct worker *worker = container_of(work, struct worker, rebind_work);
  1440. if (worker_maybe_bind_and_lock(worker->pool))
  1441. worker_clr_flags(worker, WORKER_UNBOUND);
  1442. spin_unlock_irq(&worker->pool->lock);
  1443. }
  1444. /**
  1445. * rebind_workers - rebind all workers of a pool to the associated CPU
  1446. * @pool: pool of interest
  1447. *
  1448. * @pool->cpu is coming online. Rebind all workers to the CPU. Rebinding
  1449. * is different for idle and busy ones.
  1450. *
  1451. * Idle ones will be removed from the idle_list and woken up. They will
  1452. * add themselves back after completing rebind. This ensures that the
  1453. * idle_list doesn't contain any unbound workers when re-bound busy workers
  1454. * try to perform local wake-ups for concurrency management.
  1455. *
  1456. * Busy workers can rebind after they finish their current work items.
  1457. * Queueing the rebind work item at the head of the scheduled list is
  1458. * enough. Note that nr_running will be properly bumped as busy workers
  1459. * rebind.
  1460. *
  1461. * On return, all non-manager workers are scheduled for rebind - see
  1462. * manage_workers() for the manager special case. Any idle worker
  1463. * including the manager will not appear on @idle_list until rebind is
  1464. * complete, making local wake-ups safe.
  1465. */
  1466. static void rebind_workers(struct worker_pool *pool)
  1467. {
  1468. struct worker *worker, *n;
  1469. int i;
  1470. lockdep_assert_held(&pool->assoc_mutex);
  1471. lockdep_assert_held(&pool->lock);
  1472. /* dequeue and kick idle ones */
  1473. list_for_each_entry_safe(worker, n, &pool->idle_list, entry) {
  1474. /*
  1475. * idle workers should be off @pool->idle_list until rebind
  1476. * is complete to avoid receiving premature local wake-ups.
  1477. */
  1478. list_del_init(&worker->entry);
  1479. /*
  1480. * worker_thread() will see the above dequeuing and call
  1481. * idle_worker_rebind().
  1482. */
  1483. wake_up_process(worker->task);
  1484. }
  1485. /* rebind busy workers */
  1486. for_each_busy_worker(worker, i, pool) {
  1487. struct work_struct *rebind_work = &worker->rebind_work;
  1488. struct workqueue_struct *wq;
  1489. if (test_and_set_bit(WORK_STRUCT_PENDING_BIT,
  1490. work_data_bits(rebind_work)))
  1491. continue;
  1492. debug_work_activate(rebind_work);
  1493. /*
  1494. * wq doesn't really matter but let's keep @worker->pool
  1495. * and @pwq->pool consistent for sanity.
  1496. */
  1497. if (worker->pool->attrs->nice < 0)
  1498. wq = system_highpri_wq;
  1499. else
  1500. wq = system_wq;
  1501. insert_work(per_cpu_ptr(wq->cpu_pwqs, pool->cpu), rebind_work,
  1502. worker->scheduled.next,
  1503. work_color_to_flags(WORK_NO_COLOR));
  1504. }
  1505. }
  1506. static struct worker *alloc_worker(void)
  1507. {
  1508. struct worker *worker;
  1509. worker = kzalloc(sizeof(*worker), GFP_KERNEL);
  1510. if (worker) {
  1511. INIT_LIST_HEAD(&worker->entry);
  1512. INIT_LIST_HEAD(&worker->scheduled);
  1513. INIT_WORK(&worker->rebind_work, busy_worker_rebind_fn);
  1514. /* on creation a worker is in !idle && prep state */
  1515. worker->flags = WORKER_PREP;
  1516. }
  1517. return worker;
  1518. }
  1519. /**
  1520. * create_worker - create a new workqueue worker
  1521. * @pool: pool the new worker will belong to
  1522. *
  1523. * Create a new worker which is bound to @pool. The returned worker
  1524. * can be started by calling start_worker() or destroyed using
  1525. * destroy_worker().
  1526. *
  1527. * CONTEXT:
  1528. * Might sleep. Does GFP_KERNEL allocations.
  1529. *
  1530. * RETURNS:
  1531. * Pointer to the newly created worker.
  1532. */
  1533. static struct worker *create_worker(struct worker_pool *pool)
  1534. {
  1535. const char *pri = pool->attrs->nice < 0 ? "H" : "";
  1536. struct worker *worker = NULL;
  1537. int id = -1;
  1538. spin_lock_irq(&pool->lock);
  1539. while (ida_get_new(&pool->worker_ida, &id)) {
  1540. spin_unlock_irq(&pool->lock);
  1541. if (!ida_pre_get(&pool->worker_ida, GFP_KERNEL))
  1542. goto fail;
  1543. spin_lock_irq(&pool->lock);
  1544. }
  1545. spin_unlock_irq(&pool->lock);
  1546. worker = alloc_worker();
  1547. if (!worker)
  1548. goto fail;
  1549. worker->pool = pool;
  1550. worker->id = id;
  1551. if (pool->cpu >= 0)
  1552. worker->task = kthread_create_on_node(worker_thread,
  1553. worker, cpu_to_node(pool->cpu),
  1554. "kworker/%d:%d%s", pool->cpu, id, pri);
  1555. else
  1556. worker->task = kthread_create(worker_thread, worker,
  1557. "kworker/u%d:%d%s",
  1558. pool->id, id, pri);
  1559. if (IS_ERR(worker->task))
  1560. goto fail;
  1561. set_user_nice(worker->task, pool->attrs->nice);
  1562. set_cpus_allowed_ptr(worker->task, pool->attrs->cpumask);
  1563. /*
  1564. * %PF_THREAD_BOUND is used to prevent userland from meddling with
  1565. * cpumask of workqueue workers. This is an abuse. We need
  1566. * %PF_NO_SETAFFINITY.
  1567. */
  1568. worker->task->flags |= PF_THREAD_BOUND;
  1569. /*
  1570. * The caller is responsible for ensuring %POOL_DISASSOCIATED
  1571. * remains stable across this function. See the comments above the
  1572. * flag definition for details.
  1573. */
  1574. if (pool->flags & POOL_DISASSOCIATED)
  1575. worker->flags |= WORKER_UNBOUND;
  1576. return worker;
  1577. fail:
  1578. if (id >= 0) {
  1579. spin_lock_irq(&pool->lock);
  1580. ida_remove(&pool->worker_ida, id);
  1581. spin_unlock_irq(&pool->lock);
  1582. }
  1583. kfree(worker);
  1584. return NULL;
  1585. }
  1586. /**
  1587. * start_worker - start a newly created worker
  1588. * @worker: worker to start
  1589. *
  1590. * Make the pool aware of @worker and start it.
  1591. *
  1592. * CONTEXT:
  1593. * spin_lock_irq(pool->lock).
  1594. */
  1595. static void start_worker(struct worker *worker)
  1596. {
  1597. worker->flags |= WORKER_STARTED;
  1598. worker->pool->nr_workers++;
  1599. worker_enter_idle(worker);
  1600. wake_up_process(worker->task);
  1601. }
  1602. /**
  1603. * destroy_worker - destroy a workqueue worker
  1604. * @worker: worker to be destroyed
  1605. *
  1606. * Destroy @worker and adjust @pool stats accordingly.
  1607. *
  1608. * CONTEXT:
  1609. * spin_lock_irq(pool->lock) which is released and regrabbed.
  1610. */
  1611. static void destroy_worker(struct worker *worker)
  1612. {
  1613. struct worker_pool *pool = worker->pool;
  1614. int id = worker->id;
  1615. /* sanity check frenzy */
  1616. if (WARN_ON(worker->current_work) ||
  1617. WARN_ON(!list_empty(&worker->scheduled)))
  1618. return;
  1619. if (worker->flags & WORKER_STARTED)
  1620. pool->nr_workers--;
  1621. if (worker->flags & WORKER_IDLE)
  1622. pool->nr_idle--;
  1623. list_del_init(&worker->entry);
  1624. worker->flags |= WORKER_DIE;
  1625. spin_unlock_irq(&pool->lock);
  1626. kthread_stop(worker->task);
  1627. kfree(worker);
  1628. spin_lock_irq(&pool->lock);
  1629. ida_remove(&pool->worker_ida, id);
  1630. }
  1631. static void idle_worker_timeout(unsigned long __pool)
  1632. {
  1633. struct worker_pool *pool = (void *)__pool;
  1634. spin_lock_irq(&pool->lock);
  1635. if (too_many_workers(pool)) {
  1636. struct worker *worker;
  1637. unsigned long expires;
  1638. /* idle_list is kept in LIFO order, check the last one */
  1639. worker = list_entry(pool->idle_list.prev, struct worker, entry);
  1640. expires = worker->last_active + IDLE_WORKER_TIMEOUT;
  1641. if (time_before(jiffies, expires))
  1642. mod_timer(&pool->idle_timer, expires);
  1643. else {
  1644. /* it's been idle for too long, wake up manager */
  1645. pool->flags |= POOL_MANAGE_WORKERS;
  1646. wake_up_worker(pool);
  1647. }
  1648. }
  1649. spin_unlock_irq(&pool->lock);
  1650. }
  1651. static void send_mayday(struct work_struct *work)
  1652. {
  1653. struct pool_workqueue *pwq = get_work_pwq(work);
  1654. struct workqueue_struct *wq = pwq->wq;
  1655. lockdep_assert_held(&workqueue_lock);
  1656. if (!wq->rescuer)
  1657. return;
  1658. /* mayday mayday mayday */
  1659. if (list_empty(&pwq->mayday_node)) {
  1660. list_add_tail(&pwq->mayday_node, &wq->maydays);
  1661. wake_up_process(wq->rescuer->task);
  1662. }
  1663. }
  1664. static void pool_mayday_timeout(unsigned long __pool)
  1665. {
  1666. struct worker_pool *pool = (void *)__pool;
  1667. struct work_struct *work;
  1668. spin_lock_irq(&workqueue_lock); /* for wq->maydays */
  1669. spin_lock(&pool->lock);
  1670. if (need_to_create_worker(pool)) {
  1671. /*
  1672. * We've been trying to create a new worker but
  1673. * haven't been successful. We might be hitting an
  1674. * allocation deadlock. Send distress signals to
  1675. * rescuers.
  1676. */
  1677. list_for_each_entry(work, &pool->worklist, entry)
  1678. send_mayday(work);
  1679. }
  1680. spin_unlock(&pool->lock);
  1681. spin_unlock_irq(&workqueue_lock);
  1682. mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
  1683. }
  1684. /**
  1685. * maybe_create_worker - create a new worker if necessary
  1686. * @pool: pool to create a new worker for
  1687. *
  1688. * Create a new worker for @pool if necessary. @pool is guaranteed to
  1689. * have at least one idle worker on return from this function. If
  1690. * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
  1691. * sent to all rescuers with works scheduled on @pool to resolve
  1692. * possible allocation deadlock.
  1693. *
  1694. * On return, need_to_create_worker() is guaranteed to be false and
  1695. * may_start_working() true.
  1696. *
  1697. * LOCKING:
  1698. * spin_lock_irq(pool->lock) which may be released and regrabbed
  1699. * multiple times. Does GFP_KERNEL allocations. Called only from
  1700. * manager.
  1701. *
  1702. * RETURNS:
  1703. * false if no action was taken and pool->lock stayed locked, true
  1704. * otherwise.
  1705. */
  1706. static bool maybe_create_worker(struct worker_pool *pool)
  1707. __releases(&pool->lock)
  1708. __acquires(&pool->lock)
  1709. {
  1710. if (!need_to_create_worker(pool))
  1711. return false;
  1712. restart:
  1713. spin_unlock_irq(&pool->lock);
  1714. /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
  1715. mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
  1716. while (true) {
  1717. struct worker *worker;
  1718. worker = create_worker(pool);
  1719. if (worker) {
  1720. del_timer_sync(&pool->mayday_timer);
  1721. spin_lock_irq(&pool->lock);
  1722. start_worker(worker);
  1723. if (WARN_ON_ONCE(need_to_create_worker(pool)))
  1724. goto restart;
  1725. return true;
  1726. }
  1727. if (!need_to_create_worker(pool))
  1728. break;
  1729. __set_current_state(TASK_INTERRUPTIBLE);
  1730. schedule_timeout(CREATE_COOLDOWN);
  1731. if (!need_to_create_worker(pool))
  1732. break;
  1733. }
  1734. del_timer_sync(&pool->mayday_timer);
  1735. spin_lock_irq(&pool->lock);
  1736. if (need_to_create_worker(pool))
  1737. goto restart;
  1738. return true;
  1739. }
  1740. /**
  1741. * maybe_destroy_worker - destroy workers which have been idle for a while
  1742. * @pool: pool to destroy workers for
  1743. *
  1744. * Destroy @pool workers which have been idle for longer than
  1745. * IDLE_WORKER_TIMEOUT.
  1746. *
  1747. * LOCKING:
  1748. * spin_lock_irq(pool->lock) which may be released and regrabbed
  1749. * multiple times. Called only from manager.
  1750. *
  1751. * RETURNS:
  1752. * false if no action was taken and pool->lock stayed locked, true
  1753. * otherwise.
  1754. */
  1755. static bool maybe_destroy_workers(struct worker_pool *pool)
  1756. {
  1757. bool ret = false;
  1758. while (too_many_workers(pool)) {
  1759. struct worker *worker;
  1760. unsigned long expires;
  1761. worker = list_entry(pool->idle_list.prev, struct worker, entry);
  1762. expires = worker->last_active + IDLE_WORKER_TIMEOUT;
  1763. if (time_before(jiffies, expires)) {
  1764. mod_timer(&pool->idle_timer, expires);
  1765. break;
  1766. }
  1767. destroy_worker(worker);
  1768. ret = true;
  1769. }
  1770. return ret;
  1771. }
  1772. /**
  1773. * manage_workers - manage worker pool
  1774. * @worker: self
  1775. *
  1776. * Assume the manager role and manage the worker pool @worker belongs
  1777. * to. At any given time, there can be only zero or one manager per
  1778. * pool. The exclusion is handled automatically by this function.
  1779. *
  1780. * The caller can safely start processing works on false return. On
  1781. * true return, it's guaranteed that need_to_create_worker() is false
  1782. * and may_start_working() is true.
  1783. *
  1784. * CONTEXT:
  1785. * spin_lock_irq(pool->lock) which may be released and regrabbed
  1786. * multiple times. Does GFP_KERNEL allocations.
  1787. *
  1788. * RETURNS:
  1789. * spin_lock_irq(pool->lock) which may be released and regrabbed
  1790. * multiple times. Does GFP_KERNEL allocations.
  1791. */
  1792. static bool manage_workers(struct worker *worker)
  1793. {
  1794. struct worker_pool *pool = worker->pool;
  1795. bool ret = false;
  1796. if (!mutex_trylock(&pool->manager_arb))
  1797. return ret;
  1798. /*
  1799. * To simplify both worker management and CPU hotplug, hold off
  1800. * management while hotplug is in progress. CPU hotplug path can't
  1801. * grab @pool->manager_arb to achieve this because that can lead to
  1802. * idle worker depletion (all become busy thinking someone else is
  1803. * managing) which in turn can result in deadlock under extreme
  1804. * circumstances. Use @pool->assoc_mutex to synchronize manager
  1805. * against CPU hotplug.
  1806. *
  1807. * assoc_mutex would always be free unless CPU hotplug is in
  1808. * progress. trylock first without dropping @pool->lock.
  1809. */
  1810. if (unlikely(!mutex_trylock(&pool->assoc_mutex))) {
  1811. spin_unlock_irq(&pool->lock);
  1812. mutex_lock(&pool->assoc_mutex);
  1813. /*
  1814. * CPU hotplug could have happened while we were waiting
  1815. * for assoc_mutex. Hotplug itself can't handle us
  1816. * because manager isn't either on idle or busy list, and
  1817. * @pool's state and ours could have deviated.
  1818. *
  1819. * As hotplug is now excluded via assoc_mutex, we can
  1820. * simply try to bind. It will succeed or fail depending
  1821. * on @pool's current state. Try it and adjust
  1822. * %WORKER_UNBOUND accordingly.
  1823. */
  1824. if (worker_maybe_bind_and_lock(pool))
  1825. worker->flags &= ~WORKER_UNBOUND;
  1826. else
  1827. worker->flags |= WORKER_UNBOUND;
  1828. ret = true;
  1829. }
  1830. pool->flags &= ~POOL_MANAGE_WORKERS;
  1831. /*
  1832. * Destroy and then create so that may_start_working() is true
  1833. * on return.
  1834. */
  1835. ret |= maybe_destroy_workers(pool);
  1836. ret |= maybe_create_worker(pool);
  1837. mutex_unlock(&pool->assoc_mutex);
  1838. mutex_unlock(&pool->manager_arb);
  1839. return ret;
  1840. }
  1841. /**
  1842. * process_one_work - process single work
  1843. * @worker: self
  1844. * @work: work to process
  1845. *
  1846. * Process @work. This function contains all the logics necessary to
  1847. * process a single work including synchronization against and
  1848. * interaction with other workers on the same cpu, queueing and
  1849. * flushing. As long as context requirement is met, any worker can
  1850. * call this function to process a work.
  1851. *
  1852. * CONTEXT:
  1853. * spin_lock_irq(pool->lock) which is released and regrabbed.
  1854. */
  1855. static void process_one_work(struct worker *worker, struct work_struct *work)
  1856. __releases(&pool->lock)
  1857. __acquires(&pool->lock)
  1858. {
  1859. struct pool_workqueue *pwq = get_work_pwq(work);
  1860. struct worker_pool *pool = worker->pool;
  1861. bool cpu_intensive = pwq->wq->flags & WQ_CPU_INTENSIVE;
  1862. int work_color;
  1863. struct worker *collision;
  1864. #ifdef CONFIG_LOCKDEP
  1865. /*
  1866. * It is permissible to free the struct work_struct from
  1867. * inside the function that is called from it, this we need to
  1868. * take into account for lockdep too. To avoid bogus "held
  1869. * lock freed" warnings as well as problems when looking into
  1870. * work->lockdep_map, make a copy and use that here.
  1871. */
  1872. struct lockdep_map lockdep_map;
  1873. lockdep_copy_map(&lockdep_map, &work->lockdep_map);
  1874. #endif
  1875. /*
  1876. * Ensure we're on the correct CPU. DISASSOCIATED test is
  1877. * necessary to avoid spurious warnings from rescuers servicing the
  1878. * unbound or a disassociated pool.
  1879. */
  1880. WARN_ON_ONCE(!(worker->flags & WORKER_UNBOUND) &&
  1881. !(pool->flags & POOL_DISASSOCIATED) &&
  1882. raw_smp_processor_id() != pool->cpu);
  1883. /*
  1884. * A single work shouldn't be executed concurrently by
  1885. * multiple workers on a single cpu. Check whether anyone is
  1886. * already processing the work. If so, defer the work to the
  1887. * currently executing one.
  1888. */
  1889. collision = find_worker_executing_work(pool, work);
  1890. if (unlikely(collision)) {
  1891. move_linked_works(work, &collision->scheduled, NULL);
  1892. return;
  1893. }
  1894. /* claim and dequeue */
  1895. debug_work_deactivate(work);
  1896. hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
  1897. worker->current_work = work;
  1898. worker->current_func = work->func;
  1899. worker->current_pwq = pwq;
  1900. work_color = get_work_color(work);
  1901. list_del_init(&work->entry);
  1902. /*
  1903. * CPU intensive works don't participate in concurrency
  1904. * management. They're the scheduler's responsibility.
  1905. */
  1906. if (unlikely(cpu_intensive))
  1907. worker_set_flags(worker, WORKER_CPU_INTENSIVE, true);
  1908. /*
  1909. * Unbound pool isn't concurrency managed and work items should be
  1910. * executed ASAP. Wake up another worker if necessary.
  1911. */
  1912. if ((worker->flags & WORKER_UNBOUND) && need_more_worker(pool))
  1913. wake_up_worker(pool);
  1914. /*
  1915. * Record the last pool and clear PENDING which should be the last
  1916. * update to @work. Also, do this inside @pool->lock so that
  1917. * PENDING and queued state changes happen together while IRQ is
  1918. * disabled.
  1919. */
  1920. set_work_pool_and_clear_pending(work, pool->id);
  1921. spin_unlock_irq(&pool->lock);
  1922. lock_map_acquire_read(&pwq->wq->lockdep_map);
  1923. lock_map_acquire(&lockdep_map);
  1924. trace_workqueue_execute_start(work);
  1925. worker->current_func(work);
  1926. /*
  1927. * While we must be careful to not use "work" after this, the trace
  1928. * point will only record its address.
  1929. */
  1930. trace_workqueue_execute_end(work);
  1931. lock_map_release(&lockdep_map);
  1932. lock_map_release(&pwq->wq->lockdep_map);
  1933. if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
  1934. pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
  1935. " last function: %pf\n",
  1936. current->comm, preempt_count(), task_pid_nr(current),
  1937. worker->current_func);
  1938. debug_show_held_locks(current);
  1939. dump_stack();
  1940. }
  1941. spin_lock_irq(&pool->lock);
  1942. /* clear cpu intensive status */
  1943. if (unlikely(cpu_intensive))
  1944. worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
  1945. /* we're done with it, release */
  1946. hash_del(&worker->hentry);
  1947. worker->current_work = NULL;
  1948. worker->current_func = NULL;
  1949. worker->current_pwq = NULL;
  1950. pwq_dec_nr_in_flight(pwq, work_color);
  1951. }
  1952. /**
  1953. * process_scheduled_works - process scheduled works
  1954. * @worker: self
  1955. *
  1956. * Process all scheduled works. Please note that the scheduled list
  1957. * may change while processing a work, so this function repeatedly
  1958. * fetches a work from the top and executes it.
  1959. *
  1960. * CONTEXT:
  1961. * spin_lock_irq(pool->lock) which may be released and regrabbed
  1962. * multiple times.
  1963. */
  1964. static void process_scheduled_works(struct worker *worker)
  1965. {
  1966. while (!list_empty(&worker->scheduled)) {
  1967. struct work_struct *work = list_first_entry(&worker->scheduled,
  1968. struct work_struct, entry);
  1969. process_one_work(worker, work);
  1970. }
  1971. }
  1972. /**
  1973. * worker_thread - the worker thread function
  1974. * @__worker: self
  1975. *
  1976. * The worker thread function. There are NR_CPU_WORKER_POOLS dynamic pools
  1977. * of these per each cpu. These workers process all works regardless of
  1978. * their specific target workqueue. The only exception is works which
  1979. * belong to workqueues with a rescuer which will be explained in
  1980. * rescuer_thread().
  1981. */
  1982. static int worker_thread(void *__worker)
  1983. {
  1984. struct worker *worker = __worker;
  1985. struct worker_pool *pool = worker->pool;
  1986. /* tell the scheduler that this is a workqueue worker */
  1987. worker->task->flags |= PF_WQ_WORKER;
  1988. woke_up:
  1989. spin_lock_irq(&pool->lock);
  1990. /* we are off idle list if destruction or rebind is requested */
  1991. if (unlikely(list_empty(&worker->entry))) {
  1992. spin_unlock_irq(&pool->lock);
  1993. /* if DIE is set, destruction is requested */
  1994. if (worker->flags & WORKER_DIE) {
  1995. worker->task->flags &= ~PF_WQ_WORKER;
  1996. return 0;
  1997. }
  1998. /* otherwise, rebind */
  1999. idle_worker_rebind(worker);
  2000. goto woke_up;
  2001. }
  2002. worker_leave_idle(worker);
  2003. recheck:
  2004. /* no more worker necessary? */
  2005. if (!need_more_worker(pool))
  2006. goto sleep;
  2007. /* do we need to manage? */
  2008. if (unlikely(!may_start_working(pool)) && manage_workers(worker))
  2009. goto recheck;
  2010. /*
  2011. * ->scheduled list can only be filled while a worker is
  2012. * preparing to process a work or actually processing it.
  2013. * Make sure nobody diddled with it while I was sleeping.
  2014. */
  2015. WARN_ON_ONCE(!list_empty(&worker->scheduled));
  2016. /*
  2017. * When control reaches this point, we're guaranteed to have
  2018. * at least one idle worker or that someone else has already
  2019. * assumed the manager role.
  2020. */
  2021. worker_clr_flags(worker, WORKER_PREP);
  2022. do {
  2023. struct work_struct *work =
  2024. list_first_entry(&pool->worklist,
  2025. struct work_struct, entry);
  2026. if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
  2027. /* optimization path, not strictly necessary */
  2028. process_one_work(worker, work);
  2029. if (unlikely(!list_empty(&worker->scheduled)))
  2030. process_scheduled_works(worker);
  2031. } else {
  2032. move_linked_works(work, &worker->scheduled, NULL);
  2033. process_scheduled_works(worker);
  2034. }
  2035. } while (keep_working(pool));
  2036. worker_set_flags(worker, WORKER_PREP, false);
  2037. sleep:
  2038. if (unlikely(need_to_manage_workers(pool)) && manage_workers(worker))
  2039. goto recheck;
  2040. /*
  2041. * pool->lock is held and there's no work to process and no need to
  2042. * manage, sleep. Workers are woken up only while holding
  2043. * pool->lock or from local cpu, so setting the current state
  2044. * before releasing pool->lock is enough to prevent losing any
  2045. * event.
  2046. */
  2047. worker_enter_idle(worker);
  2048. __set_current_state(TASK_INTERRUPTIBLE);
  2049. spin_unlock_irq(&pool->lock);
  2050. schedule();
  2051. goto woke_up;
  2052. }
  2053. /**
  2054. * rescuer_thread - the rescuer thread function
  2055. * @__rescuer: self
  2056. *
  2057. * Workqueue rescuer thread function. There's one rescuer for each
  2058. * workqueue which has WQ_MEM_RECLAIM set.
  2059. *
  2060. * Regular work processing on a pool may block trying to create a new
  2061. * worker which uses GFP_KERNEL allocation which has slight chance of
  2062. * developing into deadlock if some works currently on the same queue
  2063. * need to be processed to satisfy the GFP_KERNEL allocation. This is
  2064. * the problem rescuer solves.
  2065. *
  2066. * When such condition is possible, the pool summons rescuers of all
  2067. * workqueues which have works queued on the pool and let them process
  2068. * those works so that forward progress can be guaranteed.
  2069. *
  2070. * This should happen rarely.
  2071. */
  2072. static int rescuer_thread(void *__rescuer)
  2073. {
  2074. struct worker *rescuer = __rescuer;
  2075. struct workqueue_struct *wq = rescuer->rescue_wq;
  2076. struct list_head *scheduled = &rescuer->scheduled;
  2077. set_user_nice(current, RESCUER_NICE_LEVEL);
  2078. /*
  2079. * Mark rescuer as worker too. As WORKER_PREP is never cleared, it
  2080. * doesn't participate in concurrency management.
  2081. */
  2082. rescuer->task->flags |= PF_WQ_WORKER;
  2083. repeat:
  2084. set_current_state(TASK_INTERRUPTIBLE);
  2085. if (kthread_should_stop()) {
  2086. __set_current_state(TASK_RUNNING);
  2087. rescuer->task->flags &= ~PF_WQ_WORKER;
  2088. return 0;
  2089. }
  2090. /* see whether any pwq is asking for help */
  2091. spin_lock_irq(&workqueue_lock);
  2092. while (!list_empty(&wq->maydays)) {
  2093. struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
  2094. struct pool_workqueue, mayday_node);
  2095. struct worker_pool *pool = pwq->pool;
  2096. struct work_struct *work, *n;
  2097. __set_current_state(TASK_RUNNING);
  2098. list_del_init(&pwq->mayday_node);
  2099. spin_unlock_irq(&workqueue_lock);
  2100. /* migrate to the target cpu if possible */
  2101. worker_maybe_bind_and_lock(pool);
  2102. rescuer->pool = pool;
  2103. /*
  2104. * Slurp in all works issued via this workqueue and
  2105. * process'em.
  2106. */
  2107. WARN_ON_ONCE(!list_empty(&rescuer->scheduled));
  2108. list_for_each_entry_safe(work, n, &pool->worklist, entry)
  2109. if (get_work_pwq(work) == pwq)
  2110. move_linked_works(work, scheduled, &n);
  2111. process_scheduled_works(rescuer);
  2112. /*
  2113. * Leave this pool. If keep_working() is %true, notify a
  2114. * regular worker; otherwise, we end up with 0 concurrency
  2115. * and stalling the execution.
  2116. */
  2117. if (keep_working(pool))
  2118. wake_up_worker(pool);
  2119. rescuer->pool = NULL;
  2120. spin_unlock(&pool->lock);
  2121. spin_lock(&workqueue_lock);
  2122. }
  2123. spin_unlock_irq(&workqueue_lock);
  2124. /* rescuers should never participate in concurrency management */
  2125. WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
  2126. schedule();
  2127. goto repeat;
  2128. }
  2129. struct wq_barrier {
  2130. struct work_struct work;
  2131. struct completion done;
  2132. };
  2133. static void wq_barrier_func(struct work_struct *work)
  2134. {
  2135. struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
  2136. complete(&barr->done);
  2137. }
  2138. /**
  2139. * insert_wq_barrier - insert a barrier work
  2140. * @pwq: pwq to insert barrier into
  2141. * @barr: wq_barrier to insert
  2142. * @target: target work to attach @barr to
  2143. * @worker: worker currently executing @target, NULL if @target is not executing
  2144. *
  2145. * @barr is linked to @target such that @barr is completed only after
  2146. * @target finishes execution. Please note that the ordering
  2147. * guarantee is observed only with respect to @target and on the local
  2148. * cpu.
  2149. *
  2150. * Currently, a queued barrier can't be canceled. This is because
  2151. * try_to_grab_pending() can't determine whether the work to be
  2152. * grabbed is at the head of the queue and thus can't clear LINKED
  2153. * flag of the previous work while there must be a valid next work
  2154. * after a work with LINKED flag set.
  2155. *
  2156. * Note that when @worker is non-NULL, @target may be modified
  2157. * underneath us, so we can't reliably determine pwq from @target.
  2158. *
  2159. * CONTEXT:
  2160. * spin_lock_irq(pool->lock).
  2161. */
  2162. static void insert_wq_barrier(struct pool_workqueue *pwq,
  2163. struct wq_barrier *barr,
  2164. struct work_struct *target, struct worker *worker)
  2165. {
  2166. struct list_head *head;
  2167. unsigned int linked = 0;
  2168. /*
  2169. * debugobject calls are safe here even with pool->lock locked
  2170. * as we know for sure that this will not trigger any of the
  2171. * checks and call back into the fixup functions where we
  2172. * might deadlock.
  2173. */
  2174. INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
  2175. __set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
  2176. init_completion(&barr->done);
  2177. /*
  2178. * If @target is currently being executed, schedule the
  2179. * barrier to the worker; otherwise, put it after @target.
  2180. */
  2181. if (worker)
  2182. head = worker->scheduled.next;
  2183. else {
  2184. unsigned long *bits = work_data_bits(target);
  2185. head = target->entry.next;
  2186. /* there can already be other linked works, inherit and set */
  2187. linked = *bits & WORK_STRUCT_LINKED;
  2188. __set_bit(WORK_STRUCT_LINKED_BIT, bits);
  2189. }
  2190. debug_work_activate(&barr->work);
  2191. insert_work(pwq, &barr->work, head,
  2192. work_color_to_flags(WORK_NO_COLOR) | linked);
  2193. }
  2194. /**
  2195. * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
  2196. * @wq: workqueue being flushed
  2197. * @flush_color: new flush color, < 0 for no-op
  2198. * @work_color: new work color, < 0 for no-op
  2199. *
  2200. * Prepare pwqs for workqueue flushing.
  2201. *
  2202. * If @flush_color is non-negative, flush_color on all pwqs should be
  2203. * -1. If no pwq has in-flight commands at the specified color, all
  2204. * pwq->flush_color's stay at -1 and %false is returned. If any pwq
  2205. * has in flight commands, its pwq->flush_color is set to
  2206. * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
  2207. * wakeup logic is armed and %true is returned.
  2208. *
  2209. * The caller should have initialized @wq->first_flusher prior to
  2210. * calling this function with non-negative @flush_color. If
  2211. * @flush_color is negative, no flush color update is done and %false
  2212. * is returned.
  2213. *
  2214. * If @work_color is non-negative, all pwqs should have the same
  2215. * work_color which is previous to @work_color and all will be
  2216. * advanced to @work_color.
  2217. *
  2218. * CONTEXT:
  2219. * mutex_lock(wq->flush_mutex).
  2220. *
  2221. * RETURNS:
  2222. * %true if @flush_color >= 0 and there's something to flush. %false
  2223. * otherwise.
  2224. */
  2225. static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
  2226. int flush_color, int work_color)
  2227. {
  2228. bool wait = false;
  2229. struct pool_workqueue *pwq;
  2230. if (flush_color >= 0) {
  2231. WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
  2232. atomic_set(&wq->nr_pwqs_to_flush, 1);
  2233. }
  2234. local_irq_disable();
  2235. for_each_pwq(pwq, wq) {
  2236. struct worker_pool *pool = pwq->pool;
  2237. spin_lock(&pool->lock);
  2238. if (flush_color >= 0) {
  2239. WARN_ON_ONCE(pwq->flush_color != -1);
  2240. if (pwq->nr_in_flight[flush_color]) {
  2241. pwq->flush_color = flush_color;
  2242. atomic_inc(&wq->nr_pwqs_to_flush);
  2243. wait = true;
  2244. }
  2245. }
  2246. if (work_color >= 0) {
  2247. WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
  2248. pwq->work_color = work_color;
  2249. }
  2250. spin_unlock(&pool->lock);
  2251. }
  2252. local_irq_enable();
  2253. if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
  2254. complete(&wq->first_flusher->done);
  2255. return wait;
  2256. }
  2257. /**
  2258. * flush_workqueue - ensure that any scheduled work has run to completion.
  2259. * @wq: workqueue to flush
  2260. *
  2261. * Forces execution of the workqueue and blocks until its completion.
  2262. * This is typically used in driver shutdown handlers.
  2263. *
  2264. * We sleep until all works which were queued on entry have been handled,
  2265. * but we are not livelocked by new incoming ones.
  2266. */
  2267. void flush_workqueue(struct workqueue_struct *wq)
  2268. {
  2269. struct wq_flusher this_flusher = {
  2270. .list = LIST_HEAD_INIT(this_flusher.list),
  2271. .flush_color = -1,
  2272. .done = COMPLETION_INITIALIZER_ONSTACK(this_flusher.done),
  2273. };
  2274. int next_color;
  2275. lock_map_acquire(&wq->lockdep_map);
  2276. lock_map_release(&wq->lockdep_map);
  2277. mutex_lock(&wq->flush_mutex);
  2278. /*
  2279. * Start-to-wait phase
  2280. */
  2281. next_color = work_next_color(wq->work_color);
  2282. if (next_color != wq->flush_color) {
  2283. /*
  2284. * Color space is not full. The current work_color
  2285. * becomes our flush_color and work_color is advanced
  2286. * by one.
  2287. */
  2288. WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
  2289. this_flusher.flush_color = wq->work_color;
  2290. wq->work_color = next_color;
  2291. if (!wq->first_flusher) {
  2292. /* no flush in progress, become the first flusher */
  2293. WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
  2294. wq->first_flusher = &this_flusher;
  2295. if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
  2296. wq->work_color)) {
  2297. /* nothing to flush, done */
  2298. wq->flush_color = next_color;
  2299. wq->first_flusher = NULL;
  2300. goto out_unlock;
  2301. }
  2302. } else {
  2303. /* wait in queue */
  2304. WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
  2305. list_add_tail(&this_flusher.list, &wq->flusher_queue);
  2306. flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
  2307. }
  2308. } else {
  2309. /*
  2310. * Oops, color space is full, wait on overflow queue.
  2311. * The next flush completion will assign us
  2312. * flush_color and transfer to flusher_queue.
  2313. */
  2314. list_add_tail(&this_flusher.list, &wq->flusher_overflow);
  2315. }
  2316. mutex_unlock(&wq->flush_mutex);
  2317. wait_for_completion(&this_flusher.done);
  2318. /*
  2319. * Wake-up-and-cascade phase
  2320. *
  2321. * First flushers are responsible for cascading flushes and
  2322. * handling overflow. Non-first flushers can simply return.
  2323. */
  2324. if (wq->first_flusher != &this_flusher)
  2325. return;
  2326. mutex_lock(&wq->flush_mutex);
  2327. /* we might have raced, check again with mutex held */
  2328. if (wq->first_flusher != &this_flusher)
  2329. goto out_unlock;
  2330. wq->first_flusher = NULL;
  2331. WARN_ON_ONCE(!list_empty(&this_flusher.list));
  2332. WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
  2333. while (true) {
  2334. struct wq_flusher *next, *tmp;
  2335. /* complete all the flushers sharing the current flush color */
  2336. list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
  2337. if (next->flush_color != wq->flush_color)
  2338. break;
  2339. list_del_init(&next->list);
  2340. complete(&next->done);
  2341. }
  2342. WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
  2343. wq->flush_color != work_next_color(wq->work_color));
  2344. /* this flush_color is finished, advance by one */
  2345. wq->flush_color = work_next_color(wq->flush_color);
  2346. /* one color has been freed, handle overflow queue */
  2347. if (!list_empty(&wq->flusher_overflow)) {
  2348. /*
  2349. * Assign the same color to all overflowed
  2350. * flushers, advance work_color and append to
  2351. * flusher_queue. This is the start-to-wait
  2352. * phase for these overflowed flushers.
  2353. */
  2354. list_for_each_entry(tmp, &wq->flusher_overflow, list)
  2355. tmp->flush_color = wq->work_color;
  2356. wq->work_color = work_next_color(wq->work_color);
  2357. list_splice_tail_init(&wq->flusher_overflow,
  2358. &wq->flusher_queue);
  2359. flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
  2360. }
  2361. if (list_empty(&wq->flusher_queue)) {
  2362. WARN_ON_ONCE(wq->flush_color != wq->work_color);
  2363. break;
  2364. }
  2365. /*
  2366. * Need to flush more colors. Make the next flusher
  2367. * the new first flusher and arm pwqs.
  2368. */
  2369. WARN_ON_ONCE(wq->flush_color == wq->work_color);
  2370. WARN_ON_ONCE(wq->flush_color != next->flush_color);
  2371. list_del_init(&next->list);
  2372. wq->first_flusher = next;
  2373. if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
  2374. break;
  2375. /*
  2376. * Meh... this color is already done, clear first
  2377. * flusher and repeat cascading.
  2378. */
  2379. wq->first_flusher = NULL;
  2380. }
  2381. out_unlock:
  2382. mutex_unlock(&wq->flush_mutex);
  2383. }
  2384. EXPORT_SYMBOL_GPL(flush_workqueue);
  2385. /**
  2386. * drain_workqueue - drain a workqueue
  2387. * @wq: workqueue to drain
  2388. *
  2389. * Wait until the workqueue becomes empty. While draining is in progress,
  2390. * only chain queueing is allowed. IOW, only currently pending or running
  2391. * work items on @wq can queue further work items on it. @wq is flushed
  2392. * repeatedly until it becomes empty. The number of flushing is detemined
  2393. * by the depth of chaining and should be relatively short. Whine if it
  2394. * takes too long.
  2395. */
  2396. void drain_workqueue(struct workqueue_struct *wq)
  2397. {
  2398. unsigned int flush_cnt = 0;
  2399. struct pool_workqueue *pwq;
  2400. /*
  2401. * __queue_work() needs to test whether there are drainers, is much
  2402. * hotter than drain_workqueue() and already looks at @wq->flags.
  2403. * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
  2404. */
  2405. spin_lock_irq(&workqueue_lock);
  2406. if (!wq->nr_drainers++)
  2407. wq->flags |= __WQ_DRAINING;
  2408. spin_unlock_irq(&workqueue_lock);
  2409. reflush:
  2410. flush_workqueue(wq);
  2411. local_irq_disable();
  2412. for_each_pwq(pwq, wq) {
  2413. bool drained;
  2414. spin_lock(&pwq->pool->lock);
  2415. drained = !pwq->nr_active && list_empty(&pwq->delayed_works);
  2416. spin_unlock(&pwq->pool->lock);
  2417. if (drained)
  2418. continue;
  2419. if (++flush_cnt == 10 ||
  2420. (flush_cnt % 100 == 0 && flush_cnt <= 1000))
  2421. pr_warn("workqueue %s: flush on destruction isn't complete after %u tries\n",
  2422. wq->name, flush_cnt);
  2423. local_irq_enable();
  2424. goto reflush;
  2425. }
  2426. spin_lock(&workqueue_lock);
  2427. if (!--wq->nr_drainers)
  2428. wq->flags &= ~__WQ_DRAINING;
  2429. spin_unlock(&workqueue_lock);
  2430. local_irq_enable();
  2431. }
  2432. EXPORT_SYMBOL_GPL(drain_workqueue);
  2433. static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr)
  2434. {
  2435. struct worker *worker = NULL;
  2436. struct worker_pool *pool;
  2437. struct pool_workqueue *pwq;
  2438. might_sleep();
  2439. local_irq_disable();
  2440. pool = get_work_pool(work);
  2441. if (!pool) {
  2442. local_irq_enable();
  2443. return false;
  2444. }
  2445. spin_lock(&pool->lock);
  2446. /* see the comment in try_to_grab_pending() with the same code */
  2447. pwq = get_work_pwq(work);
  2448. if (pwq) {
  2449. if (unlikely(pwq->pool != pool))
  2450. goto already_gone;
  2451. } else {
  2452. worker = find_worker_executing_work(pool, work);
  2453. if (!worker)
  2454. goto already_gone;
  2455. pwq = worker->current_pwq;
  2456. }
  2457. insert_wq_barrier(pwq, barr, work, worker);
  2458. spin_unlock_irq(&pool->lock);
  2459. /*
  2460. * If @max_active is 1 or rescuer is in use, flushing another work
  2461. * item on the same workqueue may lead to deadlock. Make sure the
  2462. * flusher is not running on the same workqueue by verifying write
  2463. * access.
  2464. */
  2465. if (pwq->wq->saved_max_active == 1 || pwq->wq->rescuer)
  2466. lock_map_acquire(&pwq->wq->lockdep_map);
  2467. else
  2468. lock_map_acquire_read(&pwq->wq->lockdep_map);
  2469. lock_map_release(&pwq->wq->lockdep_map);
  2470. return true;
  2471. already_gone:
  2472. spin_unlock_irq(&pool->lock);
  2473. return false;
  2474. }
  2475. /**
  2476. * flush_work - wait for a work to finish executing the last queueing instance
  2477. * @work: the work to flush
  2478. *
  2479. * Wait until @work has finished execution. @work is guaranteed to be idle
  2480. * on return if it hasn't been requeued since flush started.
  2481. *
  2482. * RETURNS:
  2483. * %true if flush_work() waited for the work to finish execution,
  2484. * %false if it was already idle.
  2485. */
  2486. bool flush_work(struct work_struct *work)
  2487. {
  2488. struct wq_barrier barr;
  2489. lock_map_acquire(&work->lockdep_map);
  2490. lock_map_release(&work->lockdep_map);
  2491. if (start_flush_work(work, &barr)) {
  2492. wait_for_completion(&barr.done);
  2493. destroy_work_on_stack(&barr.work);
  2494. return true;
  2495. } else {
  2496. return false;
  2497. }
  2498. }
  2499. EXPORT_SYMBOL_GPL(flush_work);
  2500. static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
  2501. {
  2502. unsigned long flags;
  2503. int ret;
  2504. do {
  2505. ret = try_to_grab_pending(work, is_dwork, &flags);
  2506. /*
  2507. * If someone else is canceling, wait for the same event it
  2508. * would be waiting for before retrying.
  2509. */
  2510. if (unlikely(ret == -ENOENT))
  2511. flush_work(work);
  2512. } while (unlikely(ret < 0));
  2513. /* tell other tasks trying to grab @work to back off */
  2514. mark_work_canceling(work);
  2515. local_irq_restore(flags);
  2516. flush_work(work);
  2517. clear_work_data(work);
  2518. return ret;
  2519. }
  2520. /**
  2521. * cancel_work_sync - cancel a work and wait for it to finish
  2522. * @work: the work to cancel
  2523. *
  2524. * Cancel @work and wait for its execution to finish. This function
  2525. * can be used even if the work re-queues itself or migrates to
  2526. * another workqueue. On return from this function, @work is
  2527. * guaranteed to be not pending or executing on any CPU.
  2528. *
  2529. * cancel_work_sync(&delayed_work->work) must not be used for
  2530. * delayed_work's. Use cancel_delayed_work_sync() instead.
  2531. *
  2532. * The caller must ensure that the workqueue on which @work was last
  2533. * queued can't be destroyed before this function returns.
  2534. *
  2535. * RETURNS:
  2536. * %true if @work was pending, %false otherwise.
  2537. */
  2538. bool cancel_work_sync(struct work_struct *work)
  2539. {
  2540. return __cancel_work_timer(work, false);
  2541. }
  2542. EXPORT_SYMBOL_GPL(cancel_work_sync);
  2543. /**
  2544. * flush_delayed_work - wait for a dwork to finish executing the last queueing
  2545. * @dwork: the delayed work to flush
  2546. *
  2547. * Delayed timer is cancelled and the pending work is queued for
  2548. * immediate execution. Like flush_work(), this function only
  2549. * considers the last queueing instance of @dwork.
  2550. *
  2551. * RETURNS:
  2552. * %true if flush_work() waited for the work to finish execution,
  2553. * %false if it was already idle.
  2554. */
  2555. bool flush_delayed_work(struct delayed_work *dwork)
  2556. {
  2557. local_irq_disable();
  2558. if (del_timer_sync(&dwork->timer))
  2559. __queue_work(dwork->cpu, dwork->wq, &dwork->work);
  2560. local_irq_enable();
  2561. return flush_work(&dwork->work);
  2562. }
  2563. EXPORT_SYMBOL(flush_delayed_work);
  2564. /**
  2565. * cancel_delayed_work - cancel a delayed work
  2566. * @dwork: delayed_work to cancel
  2567. *
  2568. * Kill off a pending delayed_work. Returns %true if @dwork was pending
  2569. * and canceled; %false if wasn't pending. Note that the work callback
  2570. * function may still be running on return, unless it returns %true and the
  2571. * work doesn't re-arm itself. Explicitly flush or use
  2572. * cancel_delayed_work_sync() to wait on it.
  2573. *
  2574. * This function is safe to call from any context including IRQ handler.
  2575. */
  2576. bool cancel_delayed_work(struct delayed_work *dwork)
  2577. {
  2578. unsigned long flags;
  2579. int ret;
  2580. do {
  2581. ret = try_to_grab_pending(&dwork->work, true, &flags);
  2582. } while (unlikely(ret == -EAGAIN));
  2583. if (unlikely(ret < 0))
  2584. return false;
  2585. set_work_pool_and_clear_pending(&dwork->work,
  2586. get_work_pool_id(&dwork->work));
  2587. local_irq_restore(flags);
  2588. return ret;
  2589. }
  2590. EXPORT_SYMBOL(cancel_delayed_work);
  2591. /**
  2592. * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
  2593. * @dwork: the delayed work cancel
  2594. *
  2595. * This is cancel_work_sync() for delayed works.
  2596. *
  2597. * RETURNS:
  2598. * %true if @dwork was pending, %false otherwise.
  2599. */
  2600. bool cancel_delayed_work_sync(struct delayed_work *dwork)
  2601. {
  2602. return __cancel_work_timer(&dwork->work, true);
  2603. }
  2604. EXPORT_SYMBOL(cancel_delayed_work_sync);
  2605. /**
  2606. * schedule_work_on - put work task on a specific cpu
  2607. * @cpu: cpu to put the work task on
  2608. * @work: job to be done
  2609. *
  2610. * This puts a job on a specific cpu
  2611. */
  2612. bool schedule_work_on(int cpu, struct work_struct *work)
  2613. {
  2614. return queue_work_on(cpu, system_wq, work);
  2615. }
  2616. EXPORT_SYMBOL(schedule_work_on);
  2617. /**
  2618. * schedule_work - put work task in global workqueue
  2619. * @work: job to be done
  2620. *
  2621. * Returns %false if @work was already on the kernel-global workqueue and
  2622. * %true otherwise.
  2623. *
  2624. * This puts a job in the kernel-global workqueue if it was not already
  2625. * queued and leaves it in the same position on the kernel-global
  2626. * workqueue otherwise.
  2627. */
  2628. bool schedule_work(struct work_struct *work)
  2629. {
  2630. return queue_work(system_wq, work);
  2631. }
  2632. EXPORT_SYMBOL(schedule_work);
  2633. /**
  2634. * schedule_delayed_work_on - queue work in global workqueue on CPU after delay
  2635. * @cpu: cpu to use
  2636. * @dwork: job to be done
  2637. * @delay: number of jiffies to wait
  2638. *
  2639. * After waiting for a given time this puts a job in the kernel-global
  2640. * workqueue on the specified CPU.
  2641. */
  2642. bool schedule_delayed_work_on(int cpu, struct delayed_work *dwork,
  2643. unsigned long delay)
  2644. {
  2645. return queue_delayed_work_on(cpu, system_wq, dwork, delay);
  2646. }
  2647. EXPORT_SYMBOL(schedule_delayed_work_on);
  2648. /**
  2649. * schedule_delayed_work - put work task in global workqueue after delay
  2650. * @dwork: job to be done
  2651. * @delay: number of jiffies to wait or 0 for immediate execution
  2652. *
  2653. * After waiting for a given time this puts a job in the kernel-global
  2654. * workqueue.
  2655. */
  2656. bool schedule_delayed_work(struct delayed_work *dwork, unsigned long delay)
  2657. {
  2658. return queue_delayed_work(system_wq, dwork, delay);
  2659. }
  2660. EXPORT_SYMBOL(schedule_delayed_work);
  2661. /**
  2662. * schedule_on_each_cpu - execute a function synchronously on each online CPU
  2663. * @func: the function to call
  2664. *
  2665. * schedule_on_each_cpu() executes @func on each online CPU using the
  2666. * system workqueue and blocks until all CPUs have completed.
  2667. * schedule_on_each_cpu() is very slow.
  2668. *
  2669. * RETURNS:
  2670. * 0 on success, -errno on failure.
  2671. */
  2672. int schedule_on_each_cpu(work_func_t func)
  2673. {
  2674. int cpu;
  2675. struct work_struct __percpu *works;
  2676. works = alloc_percpu(struct work_struct);
  2677. if (!works)
  2678. return -ENOMEM;
  2679. get_online_cpus();
  2680. for_each_online_cpu(cpu) {
  2681. struct work_struct *work = per_cpu_ptr(works, cpu);
  2682. INIT_WORK(work, func);
  2683. schedule_work_on(cpu, work);
  2684. }
  2685. for_each_online_cpu(cpu)
  2686. flush_work(per_cpu_ptr(works, cpu));
  2687. put_online_cpus();
  2688. free_percpu(works);
  2689. return 0;
  2690. }
  2691. /**
  2692. * flush_scheduled_work - ensure that any scheduled work has run to completion.
  2693. *
  2694. * Forces execution of the kernel-global workqueue and blocks until its
  2695. * completion.
  2696. *
  2697. * Think twice before calling this function! It's very easy to get into
  2698. * trouble if you don't take great care. Either of the following situations
  2699. * will lead to deadlock:
  2700. *
  2701. * One of the work items currently on the workqueue needs to acquire
  2702. * a lock held by your code or its caller.
  2703. *
  2704. * Your code is running in the context of a work routine.
  2705. *
  2706. * They will be detected by lockdep when they occur, but the first might not
  2707. * occur very often. It depends on what work items are on the workqueue and
  2708. * what locks they need, which you have no control over.
  2709. *
  2710. * In most situations flushing the entire workqueue is overkill; you merely
  2711. * need to know that a particular work item isn't queued and isn't running.
  2712. * In such cases you should use cancel_delayed_work_sync() or
  2713. * cancel_work_sync() instead.
  2714. */
  2715. void flush_scheduled_work(void)
  2716. {
  2717. flush_workqueue(system_wq);
  2718. }
  2719. EXPORT_SYMBOL(flush_scheduled_work);
  2720. /**
  2721. * execute_in_process_context - reliably execute the routine with user context
  2722. * @fn: the function to execute
  2723. * @ew: guaranteed storage for the execute work structure (must
  2724. * be available when the work executes)
  2725. *
  2726. * Executes the function immediately if process context is available,
  2727. * otherwise schedules the function for delayed execution.
  2728. *
  2729. * Returns: 0 - function was executed
  2730. * 1 - function was scheduled for execution
  2731. */
  2732. int execute_in_process_context(work_func_t fn, struct execute_work *ew)
  2733. {
  2734. if (!in_interrupt()) {
  2735. fn(&ew->work);
  2736. return 0;
  2737. }
  2738. INIT_WORK(&ew->work, fn);
  2739. schedule_work(&ew->work);
  2740. return 1;
  2741. }
  2742. EXPORT_SYMBOL_GPL(execute_in_process_context);
  2743. int keventd_up(void)
  2744. {
  2745. return system_wq != NULL;
  2746. }
  2747. /**
  2748. * free_workqueue_attrs - free a workqueue_attrs
  2749. * @attrs: workqueue_attrs to free
  2750. *
  2751. * Undo alloc_workqueue_attrs().
  2752. */
  2753. void free_workqueue_attrs(struct workqueue_attrs *attrs)
  2754. {
  2755. if (attrs) {
  2756. free_cpumask_var(attrs->cpumask);
  2757. kfree(attrs);
  2758. }
  2759. }
  2760. /**
  2761. * alloc_workqueue_attrs - allocate a workqueue_attrs
  2762. * @gfp_mask: allocation mask to use
  2763. *
  2764. * Allocate a new workqueue_attrs, initialize with default settings and
  2765. * return it. Returns NULL on failure.
  2766. */
  2767. struct workqueue_attrs *alloc_workqueue_attrs(gfp_t gfp_mask)
  2768. {
  2769. struct workqueue_attrs *attrs;
  2770. attrs = kzalloc(sizeof(*attrs), gfp_mask);
  2771. if (!attrs)
  2772. goto fail;
  2773. if (!alloc_cpumask_var(&attrs->cpumask, gfp_mask))
  2774. goto fail;
  2775. cpumask_setall(attrs->cpumask);
  2776. return attrs;
  2777. fail:
  2778. free_workqueue_attrs(attrs);
  2779. return NULL;
  2780. }
  2781. static void copy_workqueue_attrs(struct workqueue_attrs *to,
  2782. const struct workqueue_attrs *from)
  2783. {
  2784. to->nice = from->nice;
  2785. cpumask_copy(to->cpumask, from->cpumask);
  2786. }
  2787. /*
  2788. * Hacky implementation of jhash of bitmaps which only considers the
  2789. * specified number of bits. We probably want a proper implementation in
  2790. * include/linux/jhash.h.
  2791. */
  2792. static u32 jhash_bitmap(const unsigned long *bitmap, int bits, u32 hash)
  2793. {
  2794. int nr_longs = bits / BITS_PER_LONG;
  2795. int nr_leftover = bits % BITS_PER_LONG;
  2796. unsigned long leftover = 0;
  2797. if (nr_longs)
  2798. hash = jhash(bitmap, nr_longs * sizeof(long), hash);
  2799. if (nr_leftover) {
  2800. bitmap_copy(&leftover, bitmap + nr_longs, nr_leftover);
  2801. hash = jhash(&leftover, sizeof(long), hash);
  2802. }
  2803. return hash;
  2804. }
  2805. /* hash value of the content of @attr */
  2806. static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
  2807. {
  2808. u32 hash = 0;
  2809. hash = jhash_1word(attrs->nice, hash);
  2810. hash = jhash_bitmap(cpumask_bits(attrs->cpumask), nr_cpu_ids, hash);
  2811. return hash;
  2812. }
  2813. /* content equality test */
  2814. static bool wqattrs_equal(const struct workqueue_attrs *a,
  2815. const struct workqueue_attrs *b)
  2816. {
  2817. if (a->nice != b->nice)
  2818. return false;
  2819. if (!cpumask_equal(a->cpumask, b->cpumask))
  2820. return false;
  2821. return true;
  2822. }
  2823. /**
  2824. * init_worker_pool - initialize a newly zalloc'd worker_pool
  2825. * @pool: worker_pool to initialize
  2826. *
  2827. * Initiailize a newly zalloc'd @pool. It also allocates @pool->attrs.
  2828. * Returns 0 on success, -errno on failure. Even on failure, all fields
  2829. * inside @pool proper are initialized and put_unbound_pool() can be called
  2830. * on @pool safely to release it.
  2831. */
  2832. static int init_worker_pool(struct worker_pool *pool)
  2833. {
  2834. spin_lock_init(&pool->lock);
  2835. pool->id = -1;
  2836. pool->cpu = -1;
  2837. pool->flags |= POOL_DISASSOCIATED;
  2838. INIT_LIST_HEAD(&pool->worklist);
  2839. INIT_LIST_HEAD(&pool->idle_list);
  2840. hash_init(pool->busy_hash);
  2841. init_timer_deferrable(&pool->idle_timer);
  2842. pool->idle_timer.function = idle_worker_timeout;
  2843. pool->idle_timer.data = (unsigned long)pool;
  2844. setup_timer(&pool->mayday_timer, pool_mayday_timeout,
  2845. (unsigned long)pool);
  2846. mutex_init(&pool->manager_arb);
  2847. mutex_init(&pool->assoc_mutex);
  2848. ida_init(&pool->worker_ida);
  2849. INIT_HLIST_NODE(&pool->hash_node);
  2850. pool->refcnt = 1;
  2851. /* shouldn't fail above this point */
  2852. pool->attrs = alloc_workqueue_attrs(GFP_KERNEL);
  2853. if (!pool->attrs)
  2854. return -ENOMEM;
  2855. return 0;
  2856. }
  2857. static void rcu_free_pool(struct rcu_head *rcu)
  2858. {
  2859. struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
  2860. ida_destroy(&pool->worker_ida);
  2861. free_workqueue_attrs(pool->attrs);
  2862. kfree(pool);
  2863. }
  2864. /**
  2865. * put_unbound_pool - put a worker_pool
  2866. * @pool: worker_pool to put
  2867. *
  2868. * Put @pool. If its refcnt reaches zero, it gets destroyed in sched-RCU
  2869. * safe manner.
  2870. */
  2871. static void put_unbound_pool(struct worker_pool *pool)
  2872. {
  2873. struct worker *worker;
  2874. spin_lock_irq(&workqueue_lock);
  2875. if (--pool->refcnt) {
  2876. spin_unlock_irq(&workqueue_lock);
  2877. return;
  2878. }
  2879. /* sanity checks */
  2880. if (WARN_ON(!(pool->flags & POOL_DISASSOCIATED)) ||
  2881. WARN_ON(!list_empty(&pool->worklist))) {
  2882. spin_unlock_irq(&workqueue_lock);
  2883. return;
  2884. }
  2885. /* release id and unhash */
  2886. if (pool->id >= 0)
  2887. idr_remove(&worker_pool_idr, pool->id);
  2888. hash_del(&pool->hash_node);
  2889. spin_unlock_irq(&workqueue_lock);
  2890. /* lock out manager and destroy all workers */
  2891. mutex_lock(&pool->manager_arb);
  2892. spin_lock_irq(&pool->lock);
  2893. while ((worker = first_worker(pool)))
  2894. destroy_worker(worker);
  2895. WARN_ON(pool->nr_workers || pool->nr_idle);
  2896. spin_unlock_irq(&pool->lock);
  2897. mutex_unlock(&pool->manager_arb);
  2898. /* shut down the timers */
  2899. del_timer_sync(&pool->idle_timer);
  2900. del_timer_sync(&pool->mayday_timer);
  2901. /* sched-RCU protected to allow dereferences from get_work_pool() */
  2902. call_rcu_sched(&pool->rcu, rcu_free_pool);
  2903. }
  2904. /**
  2905. * get_unbound_pool - get a worker_pool with the specified attributes
  2906. * @attrs: the attributes of the worker_pool to get
  2907. *
  2908. * Obtain a worker_pool which has the same attributes as @attrs, bump the
  2909. * reference count and return it. If there already is a matching
  2910. * worker_pool, it will be used; otherwise, this function attempts to
  2911. * create a new one. On failure, returns NULL.
  2912. */
  2913. static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
  2914. {
  2915. static DEFINE_MUTEX(create_mutex);
  2916. u32 hash = wqattrs_hash(attrs);
  2917. struct worker_pool *pool;
  2918. struct worker *worker;
  2919. mutex_lock(&create_mutex);
  2920. /* do we already have a matching pool? */
  2921. spin_lock_irq(&workqueue_lock);
  2922. hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
  2923. if (wqattrs_equal(pool->attrs, attrs)) {
  2924. pool->refcnt++;
  2925. goto out_unlock;
  2926. }
  2927. }
  2928. spin_unlock_irq(&workqueue_lock);
  2929. /* nope, create a new one */
  2930. pool = kzalloc(sizeof(*pool), GFP_KERNEL);
  2931. if (!pool || init_worker_pool(pool) < 0)
  2932. goto fail;
  2933. lockdep_set_subclass(&pool->lock, 1); /* see put_pwq() */
  2934. copy_workqueue_attrs(pool->attrs, attrs);
  2935. if (worker_pool_assign_id(pool) < 0)
  2936. goto fail;
  2937. /* create and start the initial worker */
  2938. worker = create_worker(pool);
  2939. if (!worker)
  2940. goto fail;
  2941. spin_lock_irq(&pool->lock);
  2942. start_worker(worker);
  2943. spin_unlock_irq(&pool->lock);
  2944. /* install */
  2945. spin_lock_irq(&workqueue_lock);
  2946. hash_add(unbound_pool_hash, &pool->hash_node, hash);
  2947. out_unlock:
  2948. spin_unlock_irq(&workqueue_lock);
  2949. mutex_unlock(&create_mutex);
  2950. return pool;
  2951. fail:
  2952. mutex_unlock(&create_mutex);
  2953. if (pool)
  2954. put_unbound_pool(pool);
  2955. return NULL;
  2956. }
  2957. static void rcu_free_pwq(struct rcu_head *rcu)
  2958. {
  2959. kmem_cache_free(pwq_cache,
  2960. container_of(rcu, struct pool_workqueue, rcu));
  2961. }
  2962. /*
  2963. * Scheduled on system_wq by put_pwq() when an unbound pwq hits zero refcnt
  2964. * and needs to be destroyed.
  2965. */
  2966. static void pwq_unbound_release_workfn(struct work_struct *work)
  2967. {
  2968. struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
  2969. unbound_release_work);
  2970. struct workqueue_struct *wq = pwq->wq;
  2971. struct worker_pool *pool = pwq->pool;
  2972. if (WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND)))
  2973. return;
  2974. /*
  2975. * Unlink @pwq. Synchronization against flush_mutex isn't strictly
  2976. * necessary on release but do it anyway. It's easier to verify
  2977. * and consistent with the linking path.
  2978. */
  2979. mutex_lock(&wq->flush_mutex);
  2980. spin_lock_irq(&workqueue_lock);
  2981. list_del_rcu(&pwq->pwqs_node);
  2982. spin_unlock_irq(&workqueue_lock);
  2983. mutex_unlock(&wq->flush_mutex);
  2984. put_unbound_pool(pool);
  2985. call_rcu_sched(&pwq->rcu, rcu_free_pwq);
  2986. /*
  2987. * If we're the last pwq going away, @wq is already dead and no one
  2988. * is gonna access it anymore. Free it.
  2989. */
  2990. if (list_empty(&wq->pwqs))
  2991. kfree(wq);
  2992. }
  2993. static void init_and_link_pwq(struct pool_workqueue *pwq,
  2994. struct workqueue_struct *wq,
  2995. struct worker_pool *pool,
  2996. struct pool_workqueue **p_last_pwq)
  2997. {
  2998. BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
  2999. pwq->pool = pool;
  3000. pwq->wq = wq;
  3001. pwq->flush_color = -1;
  3002. pwq->refcnt = 1;
  3003. pwq->max_active = wq->saved_max_active;
  3004. INIT_LIST_HEAD(&pwq->delayed_works);
  3005. INIT_LIST_HEAD(&pwq->mayday_node);
  3006. INIT_WORK(&pwq->unbound_release_work, pwq_unbound_release_workfn);
  3007. /*
  3008. * Link @pwq and set the matching work_color. This is synchronized
  3009. * with flush_mutex to avoid confusing flush_workqueue().
  3010. */
  3011. mutex_lock(&wq->flush_mutex);
  3012. spin_lock_irq(&workqueue_lock);
  3013. if (p_last_pwq)
  3014. *p_last_pwq = first_pwq(wq);
  3015. pwq->work_color = wq->work_color;
  3016. list_add_rcu(&pwq->pwqs_node, &wq->pwqs);
  3017. spin_unlock_irq(&workqueue_lock);
  3018. mutex_unlock(&wq->flush_mutex);
  3019. }
  3020. /**
  3021. * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
  3022. * @wq: the target workqueue
  3023. * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
  3024. *
  3025. * Apply @attrs to an unbound workqueue @wq. If @attrs doesn't match the
  3026. * current attributes, a new pwq is created and made the first pwq which
  3027. * will serve all new work items. Older pwqs are released as in-flight
  3028. * work items finish. Note that a work item which repeatedly requeues
  3029. * itself back-to-back will stay on its current pwq.
  3030. *
  3031. * Performs GFP_KERNEL allocations. Returns 0 on success and -errno on
  3032. * failure.
  3033. */
  3034. int apply_workqueue_attrs(struct workqueue_struct *wq,
  3035. const struct workqueue_attrs *attrs)
  3036. {
  3037. struct pool_workqueue *pwq, *last_pwq;
  3038. struct worker_pool *pool;
  3039. /* only unbound workqueues can change attributes */
  3040. if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
  3041. return -EINVAL;
  3042. /* creating multiple pwqs breaks ordering guarantee */
  3043. if (WARN_ON((wq->flags & __WQ_ORDERED) && !list_empty(&wq->pwqs)))
  3044. return -EINVAL;
  3045. pwq = kmem_cache_zalloc(pwq_cache, GFP_KERNEL);
  3046. if (!pwq)
  3047. return -ENOMEM;
  3048. pool = get_unbound_pool(attrs);
  3049. if (!pool) {
  3050. kmem_cache_free(pwq_cache, pwq);
  3051. return -ENOMEM;
  3052. }
  3053. init_and_link_pwq(pwq, wq, pool, &last_pwq);
  3054. if (last_pwq) {
  3055. spin_lock_irq(&last_pwq->pool->lock);
  3056. put_pwq(last_pwq);
  3057. spin_unlock_irq(&last_pwq->pool->lock);
  3058. }
  3059. return 0;
  3060. }
  3061. static int alloc_and_link_pwqs(struct workqueue_struct *wq)
  3062. {
  3063. bool highpri = wq->flags & WQ_HIGHPRI;
  3064. int cpu;
  3065. if (!(wq->flags & WQ_UNBOUND)) {
  3066. wq->cpu_pwqs = alloc_percpu(struct pool_workqueue);
  3067. if (!wq->cpu_pwqs)
  3068. return -ENOMEM;
  3069. for_each_possible_cpu(cpu) {
  3070. struct pool_workqueue *pwq =
  3071. per_cpu_ptr(wq->cpu_pwqs, cpu);
  3072. struct worker_pool *cpu_pools =
  3073. per_cpu(cpu_worker_pools, cpu);
  3074. init_and_link_pwq(pwq, wq, &cpu_pools[highpri], NULL);
  3075. }
  3076. return 0;
  3077. } else {
  3078. return apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
  3079. }
  3080. }
  3081. static int wq_clamp_max_active(int max_active, unsigned int flags,
  3082. const char *name)
  3083. {
  3084. int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
  3085. if (max_active < 1 || max_active > lim)
  3086. pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
  3087. max_active, name, 1, lim);
  3088. return clamp_val(max_active, 1, lim);
  3089. }
  3090. struct workqueue_struct *__alloc_workqueue_key(const char *fmt,
  3091. unsigned int flags,
  3092. int max_active,
  3093. struct lock_class_key *key,
  3094. const char *lock_name, ...)
  3095. {
  3096. va_list args, args1;
  3097. struct workqueue_struct *wq;
  3098. struct pool_workqueue *pwq;
  3099. size_t namelen;
  3100. /* determine namelen, allocate wq and format name */
  3101. va_start(args, lock_name);
  3102. va_copy(args1, args);
  3103. namelen = vsnprintf(NULL, 0, fmt, args) + 1;
  3104. wq = kzalloc(sizeof(*wq) + namelen, GFP_KERNEL);
  3105. if (!wq)
  3106. return NULL;
  3107. vsnprintf(wq->name, namelen, fmt, args1);
  3108. va_end(args);
  3109. va_end(args1);
  3110. max_active = max_active ?: WQ_DFL_ACTIVE;
  3111. max_active = wq_clamp_max_active(max_active, flags, wq->name);
  3112. /* init wq */
  3113. wq->flags = flags;
  3114. wq->saved_max_active = max_active;
  3115. mutex_init(&wq->flush_mutex);
  3116. atomic_set(&wq->nr_pwqs_to_flush, 0);
  3117. INIT_LIST_HEAD(&wq->pwqs);
  3118. INIT_LIST_HEAD(&wq->flusher_queue);
  3119. INIT_LIST_HEAD(&wq->flusher_overflow);
  3120. INIT_LIST_HEAD(&wq->maydays);
  3121. lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
  3122. INIT_LIST_HEAD(&wq->list);
  3123. if (alloc_and_link_pwqs(wq) < 0)
  3124. goto err_free_wq;
  3125. /*
  3126. * Workqueues which may be used during memory reclaim should
  3127. * have a rescuer to guarantee forward progress.
  3128. */
  3129. if (flags & WQ_MEM_RECLAIM) {
  3130. struct worker *rescuer;
  3131. rescuer = alloc_worker();
  3132. if (!rescuer)
  3133. goto err_destroy;
  3134. rescuer->rescue_wq = wq;
  3135. rescuer->task = kthread_create(rescuer_thread, rescuer, "%s",
  3136. wq->name);
  3137. if (IS_ERR(rescuer->task)) {
  3138. kfree(rescuer);
  3139. goto err_destroy;
  3140. }
  3141. wq->rescuer = rescuer;
  3142. rescuer->task->flags |= PF_THREAD_BOUND;
  3143. wake_up_process(rescuer->task);
  3144. }
  3145. /*
  3146. * workqueue_lock protects global freeze state and workqueues
  3147. * list. Grab it, set max_active accordingly and add the new
  3148. * workqueue to workqueues list.
  3149. */
  3150. spin_lock_irq(&workqueue_lock);
  3151. if (workqueue_freezing && wq->flags & WQ_FREEZABLE)
  3152. for_each_pwq(pwq, wq)
  3153. pwq->max_active = 0;
  3154. list_add(&wq->list, &workqueues);
  3155. spin_unlock_irq(&workqueue_lock);
  3156. return wq;
  3157. err_free_wq:
  3158. kfree(wq);
  3159. return NULL;
  3160. err_destroy:
  3161. destroy_workqueue(wq);
  3162. return NULL;
  3163. }
  3164. EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
  3165. /**
  3166. * destroy_workqueue - safely terminate a workqueue
  3167. * @wq: target workqueue
  3168. *
  3169. * Safely destroy a workqueue. All work currently pending will be done first.
  3170. */
  3171. void destroy_workqueue(struct workqueue_struct *wq)
  3172. {
  3173. struct pool_workqueue *pwq;
  3174. /* drain it before proceeding with destruction */
  3175. drain_workqueue(wq);
  3176. spin_lock_irq(&workqueue_lock);
  3177. /* sanity checks */
  3178. for_each_pwq(pwq, wq) {
  3179. int i;
  3180. for (i = 0; i < WORK_NR_COLORS; i++) {
  3181. if (WARN_ON(pwq->nr_in_flight[i])) {
  3182. spin_unlock_irq(&workqueue_lock);
  3183. return;
  3184. }
  3185. }
  3186. if (WARN_ON(pwq->refcnt > 1) ||
  3187. WARN_ON(pwq->nr_active) ||
  3188. WARN_ON(!list_empty(&pwq->delayed_works))) {
  3189. spin_unlock_irq(&workqueue_lock);
  3190. return;
  3191. }
  3192. }
  3193. /*
  3194. * wq list is used to freeze wq, remove from list after
  3195. * flushing is complete in case freeze races us.
  3196. */
  3197. list_del_init(&wq->list);
  3198. spin_unlock_irq(&workqueue_lock);
  3199. if (wq->rescuer) {
  3200. kthread_stop(wq->rescuer->task);
  3201. kfree(wq->rescuer);
  3202. wq->rescuer = NULL;
  3203. }
  3204. if (!(wq->flags & WQ_UNBOUND)) {
  3205. /*
  3206. * The base ref is never dropped on per-cpu pwqs. Directly
  3207. * free the pwqs and wq.
  3208. */
  3209. free_percpu(wq->cpu_pwqs);
  3210. kfree(wq);
  3211. } else {
  3212. /*
  3213. * We're the sole accessor of @wq at this point. Directly
  3214. * access the first pwq and put the base ref. As both pwqs
  3215. * and pools are sched-RCU protected, the lock operations
  3216. * are safe. @wq will be freed when the last pwq is
  3217. * released.
  3218. */
  3219. pwq = list_first_entry(&wq->pwqs, struct pool_workqueue,
  3220. pwqs_node);
  3221. spin_lock_irq(&pwq->pool->lock);
  3222. put_pwq(pwq);
  3223. spin_unlock_irq(&pwq->pool->lock);
  3224. }
  3225. }
  3226. EXPORT_SYMBOL_GPL(destroy_workqueue);
  3227. /**
  3228. * pwq_set_max_active - adjust max_active of a pwq
  3229. * @pwq: target pool_workqueue
  3230. * @max_active: new max_active value.
  3231. *
  3232. * Set @pwq->max_active to @max_active and activate delayed works if
  3233. * increased.
  3234. *
  3235. * CONTEXT:
  3236. * spin_lock_irq(pool->lock).
  3237. */
  3238. static void pwq_set_max_active(struct pool_workqueue *pwq, int max_active)
  3239. {
  3240. pwq->max_active = max_active;
  3241. while (!list_empty(&pwq->delayed_works) &&
  3242. pwq->nr_active < pwq->max_active)
  3243. pwq_activate_first_delayed(pwq);
  3244. }
  3245. /**
  3246. * workqueue_set_max_active - adjust max_active of a workqueue
  3247. * @wq: target workqueue
  3248. * @max_active: new max_active value.
  3249. *
  3250. * Set max_active of @wq to @max_active.
  3251. *
  3252. * CONTEXT:
  3253. * Don't call from IRQ context.
  3254. */
  3255. void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
  3256. {
  3257. struct pool_workqueue *pwq;
  3258. /* disallow meddling with max_active for ordered workqueues */
  3259. if (WARN_ON(wq->flags & __WQ_ORDERED))
  3260. return;
  3261. max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
  3262. spin_lock_irq(&workqueue_lock);
  3263. wq->saved_max_active = max_active;
  3264. for_each_pwq(pwq, wq) {
  3265. struct worker_pool *pool = pwq->pool;
  3266. spin_lock(&pool->lock);
  3267. if (!(wq->flags & WQ_FREEZABLE) ||
  3268. !(pool->flags & POOL_FREEZING))
  3269. pwq_set_max_active(pwq, max_active);
  3270. spin_unlock(&pool->lock);
  3271. }
  3272. spin_unlock_irq(&workqueue_lock);
  3273. }
  3274. EXPORT_SYMBOL_GPL(workqueue_set_max_active);
  3275. /**
  3276. * workqueue_congested - test whether a workqueue is congested
  3277. * @cpu: CPU in question
  3278. * @wq: target workqueue
  3279. *
  3280. * Test whether @wq's cpu workqueue for @cpu is congested. There is
  3281. * no synchronization around this function and the test result is
  3282. * unreliable and only useful as advisory hints or for debugging.
  3283. *
  3284. * RETURNS:
  3285. * %true if congested, %false otherwise.
  3286. */
  3287. bool workqueue_congested(int cpu, struct workqueue_struct *wq)
  3288. {
  3289. struct pool_workqueue *pwq;
  3290. bool ret;
  3291. preempt_disable();
  3292. if (!(wq->flags & WQ_UNBOUND))
  3293. pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
  3294. else
  3295. pwq = first_pwq(wq);
  3296. ret = !list_empty(&pwq->delayed_works);
  3297. preempt_enable();
  3298. return ret;
  3299. }
  3300. EXPORT_SYMBOL_GPL(workqueue_congested);
  3301. /**
  3302. * work_busy - test whether a work is currently pending or running
  3303. * @work: the work to be tested
  3304. *
  3305. * Test whether @work is currently pending or running. There is no
  3306. * synchronization around this function and the test result is
  3307. * unreliable and only useful as advisory hints or for debugging.
  3308. *
  3309. * RETURNS:
  3310. * OR'd bitmask of WORK_BUSY_* bits.
  3311. */
  3312. unsigned int work_busy(struct work_struct *work)
  3313. {
  3314. struct worker_pool *pool;
  3315. unsigned long flags;
  3316. unsigned int ret = 0;
  3317. if (work_pending(work))
  3318. ret |= WORK_BUSY_PENDING;
  3319. local_irq_save(flags);
  3320. pool = get_work_pool(work);
  3321. if (pool) {
  3322. spin_lock(&pool->lock);
  3323. if (find_worker_executing_work(pool, work))
  3324. ret |= WORK_BUSY_RUNNING;
  3325. spin_unlock(&pool->lock);
  3326. }
  3327. local_irq_restore(flags);
  3328. return ret;
  3329. }
  3330. EXPORT_SYMBOL_GPL(work_busy);
  3331. /*
  3332. * CPU hotplug.
  3333. *
  3334. * There are two challenges in supporting CPU hotplug. Firstly, there
  3335. * are a lot of assumptions on strong associations among work, pwq and
  3336. * pool which make migrating pending and scheduled works very
  3337. * difficult to implement without impacting hot paths. Secondly,
  3338. * worker pools serve mix of short, long and very long running works making
  3339. * blocked draining impractical.
  3340. *
  3341. * This is solved by allowing the pools to be disassociated from the CPU
  3342. * running as an unbound one and allowing it to be reattached later if the
  3343. * cpu comes back online.
  3344. */
  3345. static void wq_unbind_fn(struct work_struct *work)
  3346. {
  3347. int cpu = smp_processor_id();
  3348. struct worker_pool *pool;
  3349. struct worker *worker;
  3350. int i;
  3351. for_each_cpu_worker_pool(pool, cpu) {
  3352. WARN_ON_ONCE(cpu != smp_processor_id());
  3353. mutex_lock(&pool->assoc_mutex);
  3354. spin_lock_irq(&pool->lock);
  3355. /*
  3356. * We've claimed all manager positions. Make all workers
  3357. * unbound and set DISASSOCIATED. Before this, all workers
  3358. * except for the ones which are still executing works from
  3359. * before the last CPU down must be on the cpu. After
  3360. * this, they may become diasporas.
  3361. */
  3362. list_for_each_entry(worker, &pool->idle_list, entry)
  3363. worker->flags |= WORKER_UNBOUND;
  3364. for_each_busy_worker(worker, i, pool)
  3365. worker->flags |= WORKER_UNBOUND;
  3366. pool->flags |= POOL_DISASSOCIATED;
  3367. spin_unlock_irq(&pool->lock);
  3368. mutex_unlock(&pool->assoc_mutex);
  3369. }
  3370. /*
  3371. * Call schedule() so that we cross rq->lock and thus can guarantee
  3372. * sched callbacks see the %WORKER_UNBOUND flag. This is necessary
  3373. * as scheduler callbacks may be invoked from other cpus.
  3374. */
  3375. schedule();
  3376. /*
  3377. * Sched callbacks are disabled now. Zap nr_running. After this,
  3378. * nr_running stays zero and need_more_worker() and keep_working()
  3379. * are always true as long as the worklist is not empty. Pools on
  3380. * @cpu now behave as unbound (in terms of concurrency management)
  3381. * pools which are served by workers tied to the CPU.
  3382. *
  3383. * On return from this function, the current worker would trigger
  3384. * unbound chain execution of pending work items if other workers
  3385. * didn't already.
  3386. */
  3387. for_each_cpu_worker_pool(pool, cpu)
  3388. atomic_set(&pool->nr_running, 0);
  3389. }
  3390. /*
  3391. * Workqueues should be brought up before normal priority CPU notifiers.
  3392. * This will be registered high priority CPU notifier.
  3393. */
  3394. static int __cpuinit workqueue_cpu_up_callback(struct notifier_block *nfb,
  3395. unsigned long action,
  3396. void *hcpu)
  3397. {
  3398. int cpu = (unsigned long)hcpu;
  3399. struct worker_pool *pool;
  3400. switch (action & ~CPU_TASKS_FROZEN) {
  3401. case CPU_UP_PREPARE:
  3402. for_each_cpu_worker_pool(pool, cpu) {
  3403. struct worker *worker;
  3404. if (pool->nr_workers)
  3405. continue;
  3406. worker = create_worker(pool);
  3407. if (!worker)
  3408. return NOTIFY_BAD;
  3409. spin_lock_irq(&pool->lock);
  3410. start_worker(worker);
  3411. spin_unlock_irq(&pool->lock);
  3412. }
  3413. break;
  3414. case CPU_DOWN_FAILED:
  3415. case CPU_ONLINE:
  3416. for_each_cpu_worker_pool(pool, cpu) {
  3417. mutex_lock(&pool->assoc_mutex);
  3418. spin_lock_irq(&pool->lock);
  3419. pool->flags &= ~POOL_DISASSOCIATED;
  3420. rebind_workers(pool);
  3421. spin_unlock_irq(&pool->lock);
  3422. mutex_unlock(&pool->assoc_mutex);
  3423. }
  3424. break;
  3425. }
  3426. return NOTIFY_OK;
  3427. }
  3428. /*
  3429. * Workqueues should be brought down after normal priority CPU notifiers.
  3430. * This will be registered as low priority CPU notifier.
  3431. */
  3432. static int __cpuinit workqueue_cpu_down_callback(struct notifier_block *nfb,
  3433. unsigned long action,
  3434. void *hcpu)
  3435. {
  3436. int cpu = (unsigned long)hcpu;
  3437. struct work_struct unbind_work;
  3438. switch (action & ~CPU_TASKS_FROZEN) {
  3439. case CPU_DOWN_PREPARE:
  3440. /* unbinding should happen on the local CPU */
  3441. INIT_WORK_ONSTACK(&unbind_work, wq_unbind_fn);
  3442. queue_work_on(cpu, system_highpri_wq, &unbind_work);
  3443. flush_work(&unbind_work);
  3444. break;
  3445. }
  3446. return NOTIFY_OK;
  3447. }
  3448. #ifdef CONFIG_SMP
  3449. struct work_for_cpu {
  3450. struct work_struct work;
  3451. long (*fn)(void *);
  3452. void *arg;
  3453. long ret;
  3454. };
  3455. static void work_for_cpu_fn(struct work_struct *work)
  3456. {
  3457. struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
  3458. wfc->ret = wfc->fn(wfc->arg);
  3459. }
  3460. /**
  3461. * work_on_cpu - run a function in user context on a particular cpu
  3462. * @cpu: the cpu to run on
  3463. * @fn: the function to run
  3464. * @arg: the function arg
  3465. *
  3466. * This will return the value @fn returns.
  3467. * It is up to the caller to ensure that the cpu doesn't go offline.
  3468. * The caller must not hold any locks which would prevent @fn from completing.
  3469. */
  3470. long work_on_cpu(int cpu, long (*fn)(void *), void *arg)
  3471. {
  3472. struct work_for_cpu wfc = { .fn = fn, .arg = arg };
  3473. INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
  3474. schedule_work_on(cpu, &wfc.work);
  3475. flush_work(&wfc.work);
  3476. return wfc.ret;
  3477. }
  3478. EXPORT_SYMBOL_GPL(work_on_cpu);
  3479. #endif /* CONFIG_SMP */
  3480. #ifdef CONFIG_FREEZER
  3481. /**
  3482. * freeze_workqueues_begin - begin freezing workqueues
  3483. *
  3484. * Start freezing workqueues. After this function returns, all freezable
  3485. * workqueues will queue new works to their frozen_works list instead of
  3486. * pool->worklist.
  3487. *
  3488. * CONTEXT:
  3489. * Grabs and releases workqueue_lock and pool->lock's.
  3490. */
  3491. void freeze_workqueues_begin(void)
  3492. {
  3493. struct worker_pool *pool;
  3494. struct workqueue_struct *wq;
  3495. struct pool_workqueue *pwq;
  3496. int id;
  3497. spin_lock_irq(&workqueue_lock);
  3498. WARN_ON_ONCE(workqueue_freezing);
  3499. workqueue_freezing = true;
  3500. /* set FREEZING */
  3501. for_each_pool(pool, id) {
  3502. spin_lock(&pool->lock);
  3503. WARN_ON_ONCE(pool->flags & POOL_FREEZING);
  3504. pool->flags |= POOL_FREEZING;
  3505. spin_unlock(&pool->lock);
  3506. }
  3507. /* suppress further executions by setting max_active to zero */
  3508. list_for_each_entry(wq, &workqueues, list) {
  3509. if (!(wq->flags & WQ_FREEZABLE))
  3510. continue;
  3511. for_each_pwq(pwq, wq) {
  3512. spin_lock(&pwq->pool->lock);
  3513. pwq->max_active = 0;
  3514. spin_unlock(&pwq->pool->lock);
  3515. }
  3516. }
  3517. spin_unlock_irq(&workqueue_lock);
  3518. }
  3519. /**
  3520. * freeze_workqueues_busy - are freezable workqueues still busy?
  3521. *
  3522. * Check whether freezing is complete. This function must be called
  3523. * between freeze_workqueues_begin() and thaw_workqueues().
  3524. *
  3525. * CONTEXT:
  3526. * Grabs and releases workqueue_lock.
  3527. *
  3528. * RETURNS:
  3529. * %true if some freezable workqueues are still busy. %false if freezing
  3530. * is complete.
  3531. */
  3532. bool freeze_workqueues_busy(void)
  3533. {
  3534. bool busy = false;
  3535. struct workqueue_struct *wq;
  3536. struct pool_workqueue *pwq;
  3537. spin_lock_irq(&workqueue_lock);
  3538. WARN_ON_ONCE(!workqueue_freezing);
  3539. list_for_each_entry(wq, &workqueues, list) {
  3540. if (!(wq->flags & WQ_FREEZABLE))
  3541. continue;
  3542. /*
  3543. * nr_active is monotonically decreasing. It's safe
  3544. * to peek without lock.
  3545. */
  3546. for_each_pwq(pwq, wq) {
  3547. WARN_ON_ONCE(pwq->nr_active < 0);
  3548. if (pwq->nr_active) {
  3549. busy = true;
  3550. goto out_unlock;
  3551. }
  3552. }
  3553. }
  3554. out_unlock:
  3555. spin_unlock_irq(&workqueue_lock);
  3556. return busy;
  3557. }
  3558. /**
  3559. * thaw_workqueues - thaw workqueues
  3560. *
  3561. * Thaw workqueues. Normal queueing is restored and all collected
  3562. * frozen works are transferred to their respective pool worklists.
  3563. *
  3564. * CONTEXT:
  3565. * Grabs and releases workqueue_lock and pool->lock's.
  3566. */
  3567. void thaw_workqueues(void)
  3568. {
  3569. struct workqueue_struct *wq;
  3570. struct pool_workqueue *pwq;
  3571. struct worker_pool *pool;
  3572. int id;
  3573. spin_lock_irq(&workqueue_lock);
  3574. if (!workqueue_freezing)
  3575. goto out_unlock;
  3576. /* clear FREEZING */
  3577. for_each_pool(pool, id) {
  3578. spin_lock(&pool->lock);
  3579. WARN_ON_ONCE(!(pool->flags & POOL_FREEZING));
  3580. pool->flags &= ~POOL_FREEZING;
  3581. spin_unlock(&pool->lock);
  3582. }
  3583. /* restore max_active and repopulate worklist */
  3584. list_for_each_entry(wq, &workqueues, list) {
  3585. if (!(wq->flags & WQ_FREEZABLE))
  3586. continue;
  3587. for_each_pwq(pwq, wq) {
  3588. spin_lock(&pwq->pool->lock);
  3589. pwq_set_max_active(pwq, wq->saved_max_active);
  3590. spin_unlock(&pwq->pool->lock);
  3591. }
  3592. }
  3593. /* kick workers */
  3594. for_each_pool(pool, id) {
  3595. spin_lock(&pool->lock);
  3596. wake_up_worker(pool);
  3597. spin_unlock(&pool->lock);
  3598. }
  3599. workqueue_freezing = false;
  3600. out_unlock:
  3601. spin_unlock_irq(&workqueue_lock);
  3602. }
  3603. #endif /* CONFIG_FREEZER */
  3604. static int __init init_workqueues(void)
  3605. {
  3606. int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
  3607. int i, cpu;
  3608. /* make sure we have enough bits for OFFQ pool ID */
  3609. BUILD_BUG_ON((1LU << (BITS_PER_LONG - WORK_OFFQ_POOL_SHIFT)) <
  3610. WORK_CPU_END * NR_STD_WORKER_POOLS);
  3611. WARN_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
  3612. pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
  3613. cpu_notifier(workqueue_cpu_up_callback, CPU_PRI_WORKQUEUE_UP);
  3614. hotcpu_notifier(workqueue_cpu_down_callback, CPU_PRI_WORKQUEUE_DOWN);
  3615. /* initialize CPU pools */
  3616. for_each_possible_cpu(cpu) {
  3617. struct worker_pool *pool;
  3618. i = 0;
  3619. for_each_cpu_worker_pool(pool, cpu) {
  3620. BUG_ON(init_worker_pool(pool));
  3621. pool->cpu = cpu;
  3622. cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
  3623. pool->attrs->nice = std_nice[i++];
  3624. /* alloc pool ID */
  3625. BUG_ON(worker_pool_assign_id(pool));
  3626. }
  3627. }
  3628. /* create the initial worker */
  3629. for_each_online_cpu(cpu) {
  3630. struct worker_pool *pool;
  3631. for_each_cpu_worker_pool(pool, cpu) {
  3632. struct worker *worker;
  3633. pool->flags &= ~POOL_DISASSOCIATED;
  3634. worker = create_worker(pool);
  3635. BUG_ON(!worker);
  3636. spin_lock_irq(&pool->lock);
  3637. start_worker(worker);
  3638. spin_unlock_irq(&pool->lock);
  3639. }
  3640. }
  3641. /* create default unbound wq attrs */
  3642. for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
  3643. struct workqueue_attrs *attrs;
  3644. BUG_ON(!(attrs = alloc_workqueue_attrs(GFP_KERNEL)));
  3645. attrs->nice = std_nice[i];
  3646. cpumask_setall(attrs->cpumask);
  3647. unbound_std_wq_attrs[i] = attrs;
  3648. }
  3649. system_wq = alloc_workqueue("events", 0, 0);
  3650. system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
  3651. system_long_wq = alloc_workqueue("events_long", 0, 0);
  3652. system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
  3653. WQ_UNBOUND_MAX_ACTIVE);
  3654. system_freezable_wq = alloc_workqueue("events_freezable",
  3655. WQ_FREEZABLE, 0);
  3656. BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
  3657. !system_unbound_wq || !system_freezable_wq);
  3658. return 0;
  3659. }
  3660. early_initcall(init_workqueues);