workqueue.c 106 KB

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