workqueue.c 153 KB

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