workqueue.c 106 KB

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