workqueue.c 139 KB

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