workqueue.c 97 KB

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