workqueue.c 106 KB

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