workqueue.c 96 KB

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