workqueue.c 96 KB

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