workqueue.c 145 KB

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