workqueue.c 106 KB

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