workqueue.c 105 KB

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