workqueue.c 124 KB

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