workqueue.c 92 KB

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