workqueue.c 106 KB

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