workqueue.c 111 KB

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