workqueue.c 107 KB

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