workqueue.c 105 KB

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