workqueue.c 105 KB

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