workqueue.c 107 KB

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