workqueue.c 106 KB

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