workqueue.c 142 KB

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