workqueue.c 105 KB

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