workqueue.c 96 KB

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