workqueue.c 106 KB

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