workqueue.c 106 KB

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