workqueue.c 126 KB

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