workqueue.c 137 KB

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