workqueue.c 105 KB

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