workqueue.c 160 KB

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