workqueue.c 105 KB

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