workqueue.c 111 KB

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