workqueue.c 122 KB

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