workqueue.c 113 KB

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