workqueue.c 106 KB

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