workqueue.c 95 KB

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