workqueue.c 105 KB

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