workqueue.c 111 KB

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