workqueue.c 105 KB

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