workqueue.c 142 KB

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