workqueue.c 107 KB

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