workqueue.c 89 KB

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