workqueue.c 97 KB

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