workqueue.c 122 KB

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