workqueue.c 94 KB

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