workqueue.c 95 KB

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