workqueue.c 106 KB

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