workqueue.c 105 KB

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