workqueue.c 97 KB

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