workqueue.c 153 KB

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