workqueue.c 111 KB

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