workqueue.c 137 KB

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