workqueue.c 106 KB

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