workqueue.c 121 KB

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