workqueue.c 145 KB

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