workqueue.c 104 KB

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