workqueue.c 108 KB

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