workqueue.c 122 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457
  1. /*
  2. * kernel/workqueue.c - generic async execution with shared worker pool
  3. *
  4. * Copyright (C) 2002 Ingo Molnar
  5. *
  6. * Derived from the taskqueue/keventd code by:
  7. * David Woodhouse <dwmw2@infradead.org>
  8. * Andrew Morton
  9. * Kai Petzke <wpp@marie.physik.tu-berlin.de>
  10. * Theodore Ts'o <tytso@mit.edu>
  11. *
  12. * Made to use alloc_percpu by Christoph Lameter.
  13. *
  14. * Copyright (C) 2010 SUSE Linux Products GmbH
  15. * Copyright (C) 2010 Tejun Heo <tj@kernel.org>
  16. *
  17. * This is the generic async execution mechanism. Work items as are
  18. * executed in process context. The worker pool is shared and
  19. * automatically managed. There is one worker pool for each CPU and
  20. * one extra for works which are better served by workers which are
  21. * not bound to any specific CPU.
  22. *
  23. * Please read Documentation/workqueue.txt for details.
  24. */
  25. #include <linux/export.h>
  26. #include <linux/kernel.h>
  27. #include <linux/sched.h>
  28. #include <linux/init.h>
  29. #include <linux/signal.h>
  30. #include <linux/completion.h>
  31. #include <linux/workqueue.h>
  32. #include <linux/slab.h>
  33. #include <linux/cpu.h>
  34. #include <linux/notifier.h>
  35. #include <linux/kthread.h>
  36. #include <linux/hardirq.h>
  37. #include <linux/mempolicy.h>
  38. #include <linux/freezer.h>
  39. #include <linux/kallsyms.h>
  40. #include <linux/debug_locks.h>
  41. #include <linux/lockdep.h>
  42. #include <linux/idr.h>
  43. #include <linux/jhash.h>
  44. #include <linux/hashtable.h>
  45. #include <linux/rculist.h>
  46. #include "workqueue_internal.h"
  47. enum {
  48. /*
  49. * worker_pool flags
  50. *
  51. * A bound pool is either associated or disassociated with its CPU.
  52. * While associated (!DISASSOCIATED), all workers are bound to the
  53. * CPU and none has %WORKER_UNBOUND set and concurrency management
  54. * is in effect.
  55. *
  56. * While DISASSOCIATED, the cpu may be offline and all workers have
  57. * %WORKER_UNBOUND set and concurrency management disabled, and may
  58. * be executing on any CPU. The pool behaves as an unbound one.
  59. *
  60. * Note that DISASSOCIATED should be flipped only while holding
  61. * manager_mutex to avoid changing binding state while
  62. * create_worker() is in progress.
  63. */
  64. POOL_MANAGE_WORKERS = 1 << 0, /* need to manage workers */
  65. POOL_DISASSOCIATED = 1 << 2, /* cpu can't serve workers */
  66. POOL_FREEZING = 1 << 3, /* freeze in progress */
  67. /* worker flags */
  68. WORKER_STARTED = 1 << 0, /* started */
  69. WORKER_DIE = 1 << 1, /* die die die */
  70. WORKER_IDLE = 1 << 2, /* is idle */
  71. WORKER_PREP = 1 << 3, /* preparing to run works */
  72. WORKER_CPU_INTENSIVE = 1 << 6, /* cpu intensive */
  73. WORKER_UNBOUND = 1 << 7, /* worker is unbound */
  74. WORKER_NOT_RUNNING = WORKER_PREP | WORKER_UNBOUND |
  75. WORKER_CPU_INTENSIVE,
  76. NR_STD_WORKER_POOLS = 2, /* # standard pools per cpu */
  77. UNBOUND_POOL_HASH_ORDER = 6, /* hashed by pool->attrs */
  78. BUSY_WORKER_HASH_ORDER = 6, /* 64 pointers */
  79. MAX_IDLE_WORKERS_RATIO = 4, /* 1/4 of busy can be idle */
  80. IDLE_WORKER_TIMEOUT = 300 * HZ, /* keep idle ones for 5 mins */
  81. MAYDAY_INITIAL_TIMEOUT = HZ / 100 >= 2 ? HZ / 100 : 2,
  82. /* call for help after 10ms
  83. (min two ticks) */
  84. MAYDAY_INTERVAL = HZ / 10, /* and then every 100ms */
  85. CREATE_COOLDOWN = HZ, /* time to breath after fail */
  86. /*
  87. * Rescue workers are used only on emergencies and shared by
  88. * all cpus. Give -20.
  89. */
  90. RESCUER_NICE_LEVEL = -20,
  91. HIGHPRI_NICE_LEVEL = -20,
  92. };
  93. /*
  94. * Structure fields follow one of the following exclusion rules.
  95. *
  96. * I: Modifiable by initialization/destruction paths and read-only for
  97. * everyone else.
  98. *
  99. * P: Preemption protected. Disabling preemption is enough and should
  100. * only be modified and accessed from the local cpu.
  101. *
  102. * L: pool->lock protected. Access with pool->lock held.
  103. *
  104. * X: During normal operation, modification requires pool->lock and should
  105. * be done only from local cpu. Either disabling preemption on local
  106. * cpu or grabbing pool->lock is enough for read access. If
  107. * POOL_DISASSOCIATED is set, it's identical to L.
  108. *
  109. * F: wq->flush_mutex protected.
  110. *
  111. * W: workqueue_lock protected.
  112. *
  113. * R: workqueue_lock protected for writes. Sched-RCU protected for reads.
  114. *
  115. * FR: wq->flush_mutex and workqueue_lock protected for writes. Sched-RCU
  116. * protected for reads.
  117. */
  118. /* struct worker is defined in workqueue_internal.h */
  119. struct worker_pool {
  120. spinlock_t lock; /* the pool lock */
  121. int cpu; /* I: the associated cpu */
  122. int id; /* I: pool ID */
  123. unsigned int flags; /* X: flags */
  124. struct list_head worklist; /* L: list of pending works */
  125. int nr_workers; /* L: total number of workers */
  126. /* nr_idle includes the ones off idle_list for rebinding */
  127. int nr_idle; /* L: currently idle ones */
  128. struct list_head idle_list; /* X: list of idle workers */
  129. struct timer_list idle_timer; /* L: worker idle timeout */
  130. struct timer_list mayday_timer; /* L: SOS timer for workers */
  131. /* a workers is either on busy_hash or idle_list, or the manager */
  132. DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
  133. /* L: hash of busy workers */
  134. /* see manage_workers() for details on the two manager mutexes */
  135. struct mutex manager_arb; /* manager arbitration */
  136. struct mutex manager_mutex; /* manager exclusion */
  137. struct ida worker_ida; /* L: for worker IDs */
  138. struct workqueue_attrs *attrs; /* I: worker attributes */
  139. struct hlist_node hash_node; /* W: unbound_pool_hash node */
  140. int refcnt; /* W: refcnt for unbound pools */
  141. /*
  142. * The current concurrency level. As it's likely to be accessed
  143. * from other CPUs during try_to_wake_up(), put it in a separate
  144. * cacheline.
  145. */
  146. atomic_t nr_running ____cacheline_aligned_in_smp;
  147. /*
  148. * Destruction of pool is sched-RCU protected to allow dereferences
  149. * from get_work_pool().
  150. */
  151. struct rcu_head rcu;
  152. } ____cacheline_aligned_in_smp;
  153. /*
  154. * The per-pool workqueue. While queued, the lower WORK_STRUCT_FLAG_BITS
  155. * of work_struct->data are used for flags and the remaining high bits
  156. * point to the pwq; thus, pwqs need to be aligned at two's power of the
  157. * number of flag bits.
  158. */
  159. struct pool_workqueue {
  160. struct worker_pool *pool; /* I: the associated pool */
  161. struct workqueue_struct *wq; /* I: the owning workqueue */
  162. int work_color; /* L: current color */
  163. int flush_color; /* L: flushing color */
  164. int refcnt; /* L: reference count */
  165. int nr_in_flight[WORK_NR_COLORS];
  166. /* L: nr of in_flight works */
  167. int nr_active; /* L: nr of active works */
  168. int max_active; /* L: max active works */
  169. struct list_head delayed_works; /* L: delayed works */
  170. struct list_head pwqs_node; /* FR: node on wq->pwqs */
  171. struct list_head mayday_node; /* W: node on wq->maydays */
  172. /*
  173. * Release of unbound pwq is punted to system_wq. See put_pwq()
  174. * and pwq_unbound_release_workfn() for details. pool_workqueue
  175. * itself is also sched-RCU protected so that the first pwq can be
  176. * determined without grabbing workqueue_lock.
  177. */
  178. struct work_struct unbound_release_work;
  179. struct rcu_head rcu;
  180. } __aligned(1 << WORK_STRUCT_FLAG_BITS);
  181. /*
  182. * Structure used to wait for workqueue flush.
  183. */
  184. struct wq_flusher {
  185. struct list_head list; /* F: list of flushers */
  186. int flush_color; /* F: flush color waiting for */
  187. struct completion done; /* flush completion */
  188. };
  189. struct wq_device;
  190. /*
  191. * The externally visible workqueue. It relays the issued work items to
  192. * the appropriate worker_pool through its pool_workqueues.
  193. */
  194. struct workqueue_struct {
  195. unsigned int flags; /* W: WQ_* flags */
  196. struct pool_workqueue __percpu *cpu_pwqs; /* I: per-cpu pwq's */
  197. struct list_head pwqs; /* FR: all pwqs of this wq */
  198. struct list_head list; /* W: list of all workqueues */
  199. struct mutex flush_mutex; /* protects wq flushing */
  200. int work_color; /* F: current work color */
  201. int flush_color; /* F: current flush color */
  202. atomic_t nr_pwqs_to_flush; /* flush in progress */
  203. struct wq_flusher *first_flusher; /* F: first flusher */
  204. struct list_head flusher_queue; /* F: flush waiters */
  205. struct list_head flusher_overflow; /* F: flush overflow list */
  206. struct list_head maydays; /* W: pwqs requesting rescue */
  207. struct worker *rescuer; /* I: rescue worker */
  208. int nr_drainers; /* W: drain in progress */
  209. int saved_max_active; /* W: saved pwq max_active */
  210. #ifdef CONFIG_SYSFS
  211. struct wq_device *wq_dev; /* I: for sysfs interface */
  212. #endif
  213. #ifdef CONFIG_LOCKDEP
  214. struct lockdep_map lockdep_map;
  215. #endif
  216. char name[]; /* I: workqueue name */
  217. };
  218. static struct kmem_cache *pwq_cache;
  219. /* W: hash of all unbound pools keyed by pool->attrs */
  220. static DEFINE_HASHTABLE(unbound_pool_hash, UNBOUND_POOL_HASH_ORDER);
  221. /* I: attributes used when instantiating standard unbound pools on demand */
  222. static struct workqueue_attrs *unbound_std_wq_attrs[NR_STD_WORKER_POOLS];
  223. struct workqueue_struct *system_wq __read_mostly;
  224. EXPORT_SYMBOL_GPL(system_wq);
  225. struct workqueue_struct *system_highpri_wq __read_mostly;
  226. EXPORT_SYMBOL_GPL(system_highpri_wq);
  227. struct workqueue_struct *system_long_wq __read_mostly;
  228. EXPORT_SYMBOL_GPL(system_long_wq);
  229. struct workqueue_struct *system_unbound_wq __read_mostly;
  230. EXPORT_SYMBOL_GPL(system_unbound_wq);
  231. struct workqueue_struct *system_freezable_wq __read_mostly;
  232. EXPORT_SYMBOL_GPL(system_freezable_wq);
  233. #define CREATE_TRACE_POINTS
  234. #include <trace/events/workqueue.h>
  235. #define assert_rcu_or_wq_lock() \
  236. rcu_lockdep_assert(rcu_read_lock_sched_held() || \
  237. lockdep_is_held(&workqueue_lock), \
  238. "sched RCU or workqueue lock should be held")
  239. #define for_each_cpu_worker_pool(pool, cpu) \
  240. for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0]; \
  241. (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
  242. (pool)++)
  243. #define for_each_busy_worker(worker, i, pool) \
  244. hash_for_each(pool->busy_hash, i, worker, hentry)
  245. /**
  246. * for_each_pool - iterate through all worker_pools in the system
  247. * @pool: iteration cursor
  248. * @pi: integer used for iteration
  249. *
  250. * This must be called either with workqueue_lock held or sched RCU read
  251. * locked. If the pool needs to be used beyond the locking in effect, the
  252. * caller is responsible for guaranteeing that the pool stays online.
  253. *
  254. * The if/else clause exists only for the lockdep assertion and can be
  255. * ignored.
  256. */
  257. #define for_each_pool(pool, pi) \
  258. idr_for_each_entry(&worker_pool_idr, pool, pi) \
  259. if (({ assert_rcu_or_wq_lock(); false; })) { } \
  260. else
  261. /**
  262. * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
  263. * @pwq: iteration cursor
  264. * @wq: the target workqueue
  265. *
  266. * This must be called either with workqueue_lock held or sched RCU read
  267. * locked. If the pwq needs to be used beyond the locking in effect, the
  268. * caller is responsible for guaranteeing that the pwq stays online.
  269. *
  270. * The if/else clause exists only for the lockdep assertion and can be
  271. * ignored.
  272. */
  273. #define for_each_pwq(pwq, wq) \
  274. list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node) \
  275. if (({ assert_rcu_or_wq_lock(); false; })) { } \
  276. else
  277. #ifdef CONFIG_DEBUG_OBJECTS_WORK
  278. static struct debug_obj_descr work_debug_descr;
  279. static void *work_debug_hint(void *addr)
  280. {
  281. return ((struct work_struct *) addr)->func;
  282. }
  283. /*
  284. * fixup_init is called when:
  285. * - an active object is initialized
  286. */
  287. static int work_fixup_init(void *addr, enum debug_obj_state state)
  288. {
  289. struct work_struct *work = addr;
  290. switch (state) {
  291. case ODEBUG_STATE_ACTIVE:
  292. cancel_work_sync(work);
  293. debug_object_init(work, &work_debug_descr);
  294. return 1;
  295. default:
  296. return 0;
  297. }
  298. }
  299. /*
  300. * fixup_activate is called when:
  301. * - an active object is activated
  302. * - an unknown object is activated (might be a statically initialized object)
  303. */
  304. static int work_fixup_activate(void *addr, enum debug_obj_state state)
  305. {
  306. struct work_struct *work = addr;
  307. switch (state) {
  308. case ODEBUG_STATE_NOTAVAILABLE:
  309. /*
  310. * This is not really a fixup. The work struct was
  311. * statically initialized. We just make sure that it
  312. * is tracked in the object tracker.
  313. */
  314. if (test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work))) {
  315. debug_object_init(work, &work_debug_descr);
  316. debug_object_activate(work, &work_debug_descr);
  317. return 0;
  318. }
  319. WARN_ON_ONCE(1);
  320. return 0;
  321. case ODEBUG_STATE_ACTIVE:
  322. WARN_ON(1);
  323. default:
  324. return 0;
  325. }
  326. }
  327. /*
  328. * fixup_free is called when:
  329. * - an active object is freed
  330. */
  331. static int work_fixup_free(void *addr, enum debug_obj_state state)
  332. {
  333. struct work_struct *work = addr;
  334. switch (state) {
  335. case ODEBUG_STATE_ACTIVE:
  336. cancel_work_sync(work);
  337. debug_object_free(work, &work_debug_descr);
  338. return 1;
  339. default:
  340. return 0;
  341. }
  342. }
  343. static struct debug_obj_descr work_debug_descr = {
  344. .name = "work_struct",
  345. .debug_hint = work_debug_hint,
  346. .fixup_init = work_fixup_init,
  347. .fixup_activate = work_fixup_activate,
  348. .fixup_free = work_fixup_free,
  349. };
  350. static inline void debug_work_activate(struct work_struct *work)
  351. {
  352. debug_object_activate(work, &work_debug_descr);
  353. }
  354. static inline void debug_work_deactivate(struct work_struct *work)
  355. {
  356. debug_object_deactivate(work, &work_debug_descr);
  357. }
  358. void __init_work(struct work_struct *work, int onstack)
  359. {
  360. if (onstack)
  361. debug_object_init_on_stack(work, &work_debug_descr);
  362. else
  363. debug_object_init(work, &work_debug_descr);
  364. }
  365. EXPORT_SYMBOL_GPL(__init_work);
  366. void destroy_work_on_stack(struct work_struct *work)
  367. {
  368. debug_object_free(work, &work_debug_descr);
  369. }
  370. EXPORT_SYMBOL_GPL(destroy_work_on_stack);
  371. #else
  372. static inline void debug_work_activate(struct work_struct *work) { }
  373. static inline void debug_work_deactivate(struct work_struct *work) { }
  374. #endif
  375. /* Serializes the accesses to the list of workqueues. */
  376. static DEFINE_SPINLOCK(workqueue_lock);
  377. static LIST_HEAD(workqueues);
  378. static bool workqueue_freezing; /* W: have wqs started freezing? */
  379. /* the per-cpu worker pools */
  380. static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS],
  381. cpu_worker_pools);
  382. /*
  383. * R: idr of all pools. Modifications are protected by workqueue_lock.
  384. * Read accesses are protected by sched-RCU protected.
  385. */
  386. static DEFINE_IDR(worker_pool_idr);
  387. static int worker_thread(void *__worker);
  388. static void copy_workqueue_attrs(struct workqueue_attrs *to,
  389. const struct workqueue_attrs *from);
  390. /* allocate ID and assign it to @pool */
  391. static int worker_pool_assign_id(struct worker_pool *pool)
  392. {
  393. int ret;
  394. do {
  395. if (!idr_pre_get(&worker_pool_idr, GFP_KERNEL))
  396. return -ENOMEM;
  397. spin_lock_irq(&workqueue_lock);
  398. ret = idr_get_new(&worker_pool_idr, pool, &pool->id);
  399. spin_unlock_irq(&workqueue_lock);
  400. } while (ret == -EAGAIN);
  401. return ret;
  402. }
  403. /**
  404. * first_pwq - return the first pool_workqueue of the specified workqueue
  405. * @wq: the target workqueue
  406. *
  407. * This must be called either with workqueue_lock held or sched RCU read
  408. * locked. If the pwq needs to be used beyond the locking in effect, the
  409. * caller is responsible for guaranteeing that the pwq stays online.
  410. */
  411. static struct pool_workqueue *first_pwq(struct workqueue_struct *wq)
  412. {
  413. assert_rcu_or_wq_lock();
  414. return list_first_or_null_rcu(&wq->pwqs, struct pool_workqueue,
  415. pwqs_node);
  416. }
  417. static unsigned int work_color_to_flags(int color)
  418. {
  419. return color << WORK_STRUCT_COLOR_SHIFT;
  420. }
  421. static int get_work_color(struct work_struct *work)
  422. {
  423. return (*work_data_bits(work) >> WORK_STRUCT_COLOR_SHIFT) &
  424. ((1 << WORK_STRUCT_COLOR_BITS) - 1);
  425. }
  426. static int work_next_color(int color)
  427. {
  428. return (color + 1) % WORK_NR_COLORS;
  429. }
  430. /*
  431. * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
  432. * contain the pointer to the queued pwq. Once execution starts, the flag
  433. * is cleared and the high bits contain OFFQ flags and pool ID.
  434. *
  435. * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
  436. * and clear_work_data() can be used to set the pwq, pool or clear
  437. * work->data. These functions should only be called while the work is
  438. * owned - ie. while the PENDING bit is set.
  439. *
  440. * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
  441. * corresponding to a work. Pool is available once the work has been
  442. * queued anywhere after initialization until it is sync canceled. pwq is
  443. * available only while the work item is queued.
  444. *
  445. * %WORK_OFFQ_CANCELING is used to mark a work item which is being
  446. * canceled. While being canceled, a work item may have its PENDING set
  447. * but stay off timer and worklist for arbitrarily long and nobody should
  448. * try to steal the PENDING bit.
  449. */
  450. static inline void set_work_data(struct work_struct *work, unsigned long data,
  451. unsigned long flags)
  452. {
  453. WARN_ON_ONCE(!work_pending(work));
  454. atomic_long_set(&work->data, data | flags | work_static(work));
  455. }
  456. static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
  457. unsigned long extra_flags)
  458. {
  459. set_work_data(work, (unsigned long)pwq,
  460. WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | extra_flags);
  461. }
  462. static void set_work_pool_and_keep_pending(struct work_struct *work,
  463. int pool_id)
  464. {
  465. set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT,
  466. WORK_STRUCT_PENDING);
  467. }
  468. static void set_work_pool_and_clear_pending(struct work_struct *work,
  469. int pool_id)
  470. {
  471. /*
  472. * The following wmb is paired with the implied mb in
  473. * test_and_set_bit(PENDING) and ensures all updates to @work made
  474. * here are visible to and precede any updates by the next PENDING
  475. * owner.
  476. */
  477. smp_wmb();
  478. set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0);
  479. }
  480. static void clear_work_data(struct work_struct *work)
  481. {
  482. smp_wmb(); /* see set_work_pool_and_clear_pending() */
  483. set_work_data(work, WORK_STRUCT_NO_POOL, 0);
  484. }
  485. static struct pool_workqueue *get_work_pwq(struct work_struct *work)
  486. {
  487. unsigned long data = atomic_long_read(&work->data);
  488. if (data & WORK_STRUCT_PWQ)
  489. return (void *)(data & WORK_STRUCT_WQ_DATA_MASK);
  490. else
  491. return NULL;
  492. }
  493. /**
  494. * get_work_pool - return the worker_pool a given work was associated with
  495. * @work: the work item of interest
  496. *
  497. * Return the worker_pool @work was last associated with. %NULL if none.
  498. *
  499. * Pools are created and destroyed under workqueue_lock, and allows read
  500. * access under sched-RCU read lock. As such, this function should be
  501. * called under workqueue_lock or with preemption disabled.
  502. *
  503. * All fields of the returned pool are accessible as long as the above
  504. * mentioned locking is in effect. If the returned pool needs to be used
  505. * beyond the critical section, the caller is responsible for ensuring the
  506. * returned pool is and stays online.
  507. */
  508. static struct worker_pool *get_work_pool(struct work_struct *work)
  509. {
  510. unsigned long data = atomic_long_read(&work->data);
  511. int pool_id;
  512. assert_rcu_or_wq_lock();
  513. if (data & WORK_STRUCT_PWQ)
  514. return ((struct pool_workqueue *)
  515. (data & WORK_STRUCT_WQ_DATA_MASK))->pool;
  516. pool_id = data >> WORK_OFFQ_POOL_SHIFT;
  517. if (pool_id == WORK_OFFQ_POOL_NONE)
  518. return NULL;
  519. return idr_find(&worker_pool_idr, pool_id);
  520. }
  521. /**
  522. * get_work_pool_id - return the worker pool ID a given work is associated with
  523. * @work: the work item of interest
  524. *
  525. * Return the worker_pool ID @work was last associated with.
  526. * %WORK_OFFQ_POOL_NONE if none.
  527. */
  528. static int get_work_pool_id(struct work_struct *work)
  529. {
  530. unsigned long data = atomic_long_read(&work->data);
  531. if (data & WORK_STRUCT_PWQ)
  532. return ((struct pool_workqueue *)
  533. (data & WORK_STRUCT_WQ_DATA_MASK))->pool->id;
  534. return data >> WORK_OFFQ_POOL_SHIFT;
  535. }
  536. static void mark_work_canceling(struct work_struct *work)
  537. {
  538. unsigned long pool_id = get_work_pool_id(work);
  539. pool_id <<= WORK_OFFQ_POOL_SHIFT;
  540. set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
  541. }
  542. static bool work_is_canceling(struct work_struct *work)
  543. {
  544. unsigned long data = atomic_long_read(&work->data);
  545. return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
  546. }
  547. /*
  548. * Policy functions. These define the policies on how the global worker
  549. * pools are managed. Unless noted otherwise, these functions assume that
  550. * they're being called with pool->lock held.
  551. */
  552. static bool __need_more_worker(struct worker_pool *pool)
  553. {
  554. return !atomic_read(&pool->nr_running);
  555. }
  556. /*
  557. * Need to wake up a worker? Called from anything but currently
  558. * running workers.
  559. *
  560. * Note that, because unbound workers never contribute to nr_running, this
  561. * function will always return %true for unbound pools as long as the
  562. * worklist isn't empty.
  563. */
  564. static bool need_more_worker(struct worker_pool *pool)
  565. {
  566. return !list_empty(&pool->worklist) && __need_more_worker(pool);
  567. }
  568. /* Can I start working? Called from busy but !running workers. */
  569. static bool may_start_working(struct worker_pool *pool)
  570. {
  571. return pool->nr_idle;
  572. }
  573. /* Do I need to keep working? Called from currently running workers. */
  574. static bool keep_working(struct worker_pool *pool)
  575. {
  576. return !list_empty(&pool->worklist) &&
  577. atomic_read(&pool->nr_running) <= 1;
  578. }
  579. /* Do we need a new worker? Called from manager. */
  580. static bool need_to_create_worker(struct worker_pool *pool)
  581. {
  582. return need_more_worker(pool) && !may_start_working(pool);
  583. }
  584. /* Do I need to be the manager? */
  585. static bool need_to_manage_workers(struct worker_pool *pool)
  586. {
  587. return need_to_create_worker(pool) ||
  588. (pool->flags & POOL_MANAGE_WORKERS);
  589. }
  590. /* Do we have too many workers and should some go away? */
  591. static bool too_many_workers(struct worker_pool *pool)
  592. {
  593. bool managing = mutex_is_locked(&pool->manager_arb);
  594. int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
  595. int nr_busy = pool->nr_workers - nr_idle;
  596. /*
  597. * nr_idle and idle_list may disagree if idle rebinding is in
  598. * progress. Never return %true if idle_list is empty.
  599. */
  600. if (list_empty(&pool->idle_list))
  601. return false;
  602. return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
  603. }
  604. /*
  605. * Wake up functions.
  606. */
  607. /* Return the first worker. Safe with preemption disabled */
  608. static struct worker *first_worker(struct worker_pool *pool)
  609. {
  610. if (unlikely(list_empty(&pool->idle_list)))
  611. return NULL;
  612. return list_first_entry(&pool->idle_list, struct worker, entry);
  613. }
  614. /**
  615. * wake_up_worker - wake up an idle worker
  616. * @pool: worker pool to wake worker from
  617. *
  618. * Wake up the first idle worker of @pool.
  619. *
  620. * CONTEXT:
  621. * spin_lock_irq(pool->lock).
  622. */
  623. static void wake_up_worker(struct worker_pool *pool)
  624. {
  625. struct worker *worker = first_worker(pool);
  626. if (likely(worker))
  627. wake_up_process(worker->task);
  628. }
  629. /**
  630. * wq_worker_waking_up - a worker is waking up
  631. * @task: task waking up
  632. * @cpu: CPU @task is waking up to
  633. *
  634. * This function is called during try_to_wake_up() when a worker is
  635. * being awoken.
  636. *
  637. * CONTEXT:
  638. * spin_lock_irq(rq->lock)
  639. */
  640. void wq_worker_waking_up(struct task_struct *task, int cpu)
  641. {
  642. struct worker *worker = kthread_data(task);
  643. if (!(worker->flags & WORKER_NOT_RUNNING)) {
  644. WARN_ON_ONCE(worker->pool->cpu != cpu);
  645. atomic_inc(&worker->pool->nr_running);
  646. }
  647. }
  648. /**
  649. * wq_worker_sleeping - a worker is going to sleep
  650. * @task: task going to sleep
  651. * @cpu: CPU in question, must be the current CPU number
  652. *
  653. * This function is called during schedule() when a busy worker is
  654. * going to sleep. Worker on the same cpu can be woken up by
  655. * returning pointer to its task.
  656. *
  657. * CONTEXT:
  658. * spin_lock_irq(rq->lock)
  659. *
  660. * RETURNS:
  661. * Worker task on @cpu to wake up, %NULL if none.
  662. */
  663. struct task_struct *wq_worker_sleeping(struct task_struct *task, int cpu)
  664. {
  665. struct worker *worker = kthread_data(task), *to_wakeup = NULL;
  666. struct worker_pool *pool;
  667. /*
  668. * Rescuers, which may not have all the fields set up like normal
  669. * workers, also reach here, let's not access anything before
  670. * checking NOT_RUNNING.
  671. */
  672. if (worker->flags & WORKER_NOT_RUNNING)
  673. return NULL;
  674. pool = worker->pool;
  675. /* this can only happen on the local cpu */
  676. if (WARN_ON_ONCE(cpu != raw_smp_processor_id()))
  677. return NULL;
  678. /*
  679. * The counterpart of the following dec_and_test, implied mb,
  680. * worklist not empty test sequence is in insert_work().
  681. * Please read comment there.
  682. *
  683. * NOT_RUNNING is clear. This means that we're bound to and
  684. * running on the local cpu w/ rq lock held and preemption
  685. * disabled, which in turn means that none else could be
  686. * manipulating idle_list, so dereferencing idle_list without pool
  687. * lock is safe.
  688. */
  689. if (atomic_dec_and_test(&pool->nr_running) &&
  690. !list_empty(&pool->worklist))
  691. to_wakeup = first_worker(pool);
  692. return to_wakeup ? to_wakeup->task : NULL;
  693. }
  694. /**
  695. * worker_set_flags - set worker flags and adjust nr_running accordingly
  696. * @worker: self
  697. * @flags: flags to set
  698. * @wakeup: wakeup an idle worker if necessary
  699. *
  700. * Set @flags in @worker->flags and adjust nr_running accordingly. If
  701. * nr_running becomes zero and @wakeup is %true, an idle worker is
  702. * woken up.
  703. *
  704. * CONTEXT:
  705. * spin_lock_irq(pool->lock)
  706. */
  707. static inline void worker_set_flags(struct worker *worker, unsigned int flags,
  708. bool wakeup)
  709. {
  710. struct worker_pool *pool = worker->pool;
  711. WARN_ON_ONCE(worker->task != current);
  712. /*
  713. * If transitioning into NOT_RUNNING, adjust nr_running and
  714. * wake up an idle worker as necessary if requested by
  715. * @wakeup.
  716. */
  717. if ((flags & WORKER_NOT_RUNNING) &&
  718. !(worker->flags & WORKER_NOT_RUNNING)) {
  719. if (wakeup) {
  720. if (atomic_dec_and_test(&pool->nr_running) &&
  721. !list_empty(&pool->worklist))
  722. wake_up_worker(pool);
  723. } else
  724. atomic_dec(&pool->nr_running);
  725. }
  726. worker->flags |= flags;
  727. }
  728. /**
  729. * worker_clr_flags - clear worker flags and adjust nr_running accordingly
  730. * @worker: self
  731. * @flags: flags to clear
  732. *
  733. * Clear @flags in @worker->flags and adjust nr_running accordingly.
  734. *
  735. * CONTEXT:
  736. * spin_lock_irq(pool->lock)
  737. */
  738. static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
  739. {
  740. struct worker_pool *pool = worker->pool;
  741. unsigned int oflags = worker->flags;
  742. WARN_ON_ONCE(worker->task != current);
  743. worker->flags &= ~flags;
  744. /*
  745. * If transitioning out of NOT_RUNNING, increment nr_running. Note
  746. * that the nested NOT_RUNNING is not a noop. NOT_RUNNING is mask
  747. * of multiple flags, not a single flag.
  748. */
  749. if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
  750. if (!(worker->flags & WORKER_NOT_RUNNING))
  751. atomic_inc(&pool->nr_running);
  752. }
  753. /**
  754. * find_worker_executing_work - find worker which is executing a work
  755. * @pool: pool of interest
  756. * @work: work to find worker for
  757. *
  758. * Find a worker which is executing @work on @pool by searching
  759. * @pool->busy_hash which is keyed by the address of @work. For a worker
  760. * to match, its current execution should match the address of @work and
  761. * its work function. This is to avoid unwanted dependency between
  762. * unrelated work executions through a work item being recycled while still
  763. * being executed.
  764. *
  765. * This is a bit tricky. A work item may be freed once its execution
  766. * starts and nothing prevents the freed area from being recycled for
  767. * another work item. If the same work item address ends up being reused
  768. * before the original execution finishes, workqueue will identify the
  769. * recycled work item as currently executing and make it wait until the
  770. * current execution finishes, introducing an unwanted dependency.
  771. *
  772. * This function checks the work item address and work function to avoid
  773. * false positives. Note that this isn't complete as one may construct a
  774. * work function which can introduce dependency onto itself through a
  775. * recycled work item. Well, if somebody wants to shoot oneself in the
  776. * foot that badly, there's only so much we can do, and if such deadlock
  777. * actually occurs, it should be easy to locate the culprit work function.
  778. *
  779. * CONTEXT:
  780. * spin_lock_irq(pool->lock).
  781. *
  782. * RETURNS:
  783. * Pointer to worker which is executing @work if found, NULL
  784. * otherwise.
  785. */
  786. static struct worker *find_worker_executing_work(struct worker_pool *pool,
  787. struct work_struct *work)
  788. {
  789. struct worker *worker;
  790. hash_for_each_possible(pool->busy_hash, worker, hentry,
  791. (unsigned long)work)
  792. if (worker->current_work == work &&
  793. worker->current_func == work->func)
  794. return worker;
  795. return NULL;
  796. }
  797. /**
  798. * move_linked_works - move linked works to a list
  799. * @work: start of series of works to be scheduled
  800. * @head: target list to append @work to
  801. * @nextp: out paramter for nested worklist walking
  802. *
  803. * Schedule linked works starting from @work to @head. Work series to
  804. * be scheduled starts at @work and includes any consecutive work with
  805. * WORK_STRUCT_LINKED set in its predecessor.
  806. *
  807. * If @nextp is not NULL, it's updated to point to the next work of
  808. * the last scheduled work. This allows move_linked_works() to be
  809. * nested inside outer list_for_each_entry_safe().
  810. *
  811. * CONTEXT:
  812. * spin_lock_irq(pool->lock).
  813. */
  814. static void move_linked_works(struct work_struct *work, struct list_head *head,
  815. struct work_struct **nextp)
  816. {
  817. struct work_struct *n;
  818. /*
  819. * Linked worklist will always end before the end of the list,
  820. * use NULL for list head.
  821. */
  822. list_for_each_entry_safe_from(work, n, NULL, entry) {
  823. list_move_tail(&work->entry, head);
  824. if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
  825. break;
  826. }
  827. /*
  828. * If we're already inside safe list traversal and have moved
  829. * multiple works to the scheduled queue, the next position
  830. * needs to be updated.
  831. */
  832. if (nextp)
  833. *nextp = n;
  834. }
  835. /**
  836. * get_pwq - get an extra reference on the specified pool_workqueue
  837. * @pwq: pool_workqueue to get
  838. *
  839. * Obtain an extra reference on @pwq. The caller should guarantee that
  840. * @pwq has positive refcnt and be holding the matching pool->lock.
  841. */
  842. static void get_pwq(struct pool_workqueue *pwq)
  843. {
  844. lockdep_assert_held(&pwq->pool->lock);
  845. WARN_ON_ONCE(pwq->refcnt <= 0);
  846. pwq->refcnt++;
  847. }
  848. /**
  849. * put_pwq - put a pool_workqueue reference
  850. * @pwq: pool_workqueue to put
  851. *
  852. * Drop a reference of @pwq. If its refcnt reaches zero, schedule its
  853. * destruction. The caller should be holding the matching pool->lock.
  854. */
  855. static void put_pwq(struct pool_workqueue *pwq)
  856. {
  857. lockdep_assert_held(&pwq->pool->lock);
  858. if (likely(--pwq->refcnt))
  859. return;
  860. if (WARN_ON_ONCE(!(pwq->wq->flags & WQ_UNBOUND)))
  861. return;
  862. /*
  863. * @pwq can't be released under pool->lock, bounce to
  864. * pwq_unbound_release_workfn(). This never recurses on the same
  865. * pool->lock as this path is taken only for unbound workqueues and
  866. * the release work item is scheduled on a per-cpu workqueue. To
  867. * avoid lockdep warning, unbound pool->locks are given lockdep
  868. * subclass of 1 in get_unbound_pool().
  869. */
  870. schedule_work(&pwq->unbound_release_work);
  871. }
  872. static void pwq_activate_delayed_work(struct work_struct *work)
  873. {
  874. struct pool_workqueue *pwq = get_work_pwq(work);
  875. trace_workqueue_activate_work(work);
  876. move_linked_works(work, &pwq->pool->worklist, NULL);
  877. __clear_bit(WORK_STRUCT_DELAYED_BIT, work_data_bits(work));
  878. pwq->nr_active++;
  879. }
  880. static void pwq_activate_first_delayed(struct pool_workqueue *pwq)
  881. {
  882. struct work_struct *work = list_first_entry(&pwq->delayed_works,
  883. struct work_struct, entry);
  884. pwq_activate_delayed_work(work);
  885. }
  886. /**
  887. * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
  888. * @pwq: pwq of interest
  889. * @color: color of work which left the queue
  890. *
  891. * A work either has completed or is removed from pending queue,
  892. * decrement nr_in_flight of its pwq and handle workqueue flushing.
  893. *
  894. * CONTEXT:
  895. * spin_lock_irq(pool->lock).
  896. */
  897. static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, int color)
  898. {
  899. /* uncolored work items don't participate in flushing or nr_active */
  900. if (color == WORK_NO_COLOR)
  901. goto out_put;
  902. pwq->nr_in_flight[color]--;
  903. pwq->nr_active--;
  904. if (!list_empty(&pwq->delayed_works)) {
  905. /* one down, submit a delayed one */
  906. if (pwq->nr_active < pwq->max_active)
  907. pwq_activate_first_delayed(pwq);
  908. }
  909. /* is flush in progress and are we at the flushing tip? */
  910. if (likely(pwq->flush_color != color))
  911. goto out_put;
  912. /* are there still in-flight works? */
  913. if (pwq->nr_in_flight[color])
  914. goto out_put;
  915. /* this pwq is done, clear flush_color */
  916. pwq->flush_color = -1;
  917. /*
  918. * If this was the last pwq, wake up the first flusher. It
  919. * will handle the rest.
  920. */
  921. if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
  922. complete(&pwq->wq->first_flusher->done);
  923. out_put:
  924. put_pwq(pwq);
  925. }
  926. /**
  927. * try_to_grab_pending - steal work item from worklist and disable irq
  928. * @work: work item to steal
  929. * @is_dwork: @work is a delayed_work
  930. * @flags: place to store irq state
  931. *
  932. * Try to grab PENDING bit of @work. This function can handle @work in any
  933. * stable state - idle, on timer or on worklist. Return values are
  934. *
  935. * 1 if @work was pending and we successfully stole PENDING
  936. * 0 if @work was idle and we claimed PENDING
  937. * -EAGAIN if PENDING couldn't be grabbed at the moment, safe to busy-retry
  938. * -ENOENT if someone else is canceling @work, this state may persist
  939. * for arbitrarily long
  940. *
  941. * On >= 0 return, the caller owns @work's PENDING bit. To avoid getting
  942. * interrupted while holding PENDING and @work off queue, irq must be
  943. * disabled on entry. This, combined with delayed_work->timer being
  944. * irqsafe, ensures that we return -EAGAIN for finite short period of time.
  945. *
  946. * On successful return, >= 0, irq is disabled and the caller is
  947. * responsible for releasing it using local_irq_restore(*@flags).
  948. *
  949. * This function is safe to call from any context including IRQ handler.
  950. */
  951. static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
  952. unsigned long *flags)
  953. {
  954. struct worker_pool *pool;
  955. struct pool_workqueue *pwq;
  956. local_irq_save(*flags);
  957. /* try to steal the timer if it exists */
  958. if (is_dwork) {
  959. struct delayed_work *dwork = to_delayed_work(work);
  960. /*
  961. * dwork->timer is irqsafe. If del_timer() fails, it's
  962. * guaranteed that the timer is not queued anywhere and not
  963. * running on the local CPU.
  964. */
  965. if (likely(del_timer(&dwork->timer)))
  966. return 1;
  967. }
  968. /* try to claim PENDING the normal way */
  969. if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
  970. return 0;
  971. /*
  972. * The queueing is in progress, or it is already queued. Try to
  973. * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
  974. */
  975. pool = get_work_pool(work);
  976. if (!pool)
  977. goto fail;
  978. spin_lock(&pool->lock);
  979. /*
  980. * work->data is guaranteed to point to pwq only while the work
  981. * item is queued on pwq->wq, and both updating work->data to point
  982. * to pwq on queueing and to pool on dequeueing are done under
  983. * pwq->pool->lock. This in turn guarantees that, if work->data
  984. * points to pwq which is associated with a locked pool, the work
  985. * item is currently queued on that pool.
  986. */
  987. pwq = get_work_pwq(work);
  988. if (pwq && pwq->pool == pool) {
  989. debug_work_deactivate(work);
  990. /*
  991. * A delayed work item cannot be grabbed directly because
  992. * it might have linked NO_COLOR work items which, if left
  993. * on the delayed_list, will confuse pwq->nr_active
  994. * management later on and cause stall. Make sure the work
  995. * item is activated before grabbing.
  996. */
  997. if (*work_data_bits(work) & WORK_STRUCT_DELAYED)
  998. pwq_activate_delayed_work(work);
  999. list_del_init(&work->entry);
  1000. pwq_dec_nr_in_flight(get_work_pwq(work), get_work_color(work));
  1001. /* work->data points to pwq iff queued, point to pool */
  1002. set_work_pool_and_keep_pending(work, pool->id);
  1003. spin_unlock(&pool->lock);
  1004. return 1;
  1005. }
  1006. spin_unlock(&pool->lock);
  1007. fail:
  1008. local_irq_restore(*flags);
  1009. if (work_is_canceling(work))
  1010. return -ENOENT;
  1011. cpu_relax();
  1012. return -EAGAIN;
  1013. }
  1014. /**
  1015. * insert_work - insert a work into a pool
  1016. * @pwq: pwq @work belongs to
  1017. * @work: work to insert
  1018. * @head: insertion point
  1019. * @extra_flags: extra WORK_STRUCT_* flags to set
  1020. *
  1021. * Insert @work which belongs to @pwq after @head. @extra_flags is or'd to
  1022. * work_struct flags.
  1023. *
  1024. * CONTEXT:
  1025. * spin_lock_irq(pool->lock).
  1026. */
  1027. static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
  1028. struct list_head *head, unsigned int extra_flags)
  1029. {
  1030. struct worker_pool *pool = pwq->pool;
  1031. /* we own @work, set data and link */
  1032. set_work_pwq(work, pwq, extra_flags);
  1033. list_add_tail(&work->entry, head);
  1034. get_pwq(pwq);
  1035. /*
  1036. * Ensure either wq_worker_sleeping() sees the above
  1037. * list_add_tail() or we see zero nr_running to avoid workers lying
  1038. * around lazily while there are works to be processed.
  1039. */
  1040. smp_mb();
  1041. if (__need_more_worker(pool))
  1042. wake_up_worker(pool);
  1043. }
  1044. /*
  1045. * Test whether @work is being queued from another work executing on the
  1046. * same workqueue.
  1047. */
  1048. static bool is_chained_work(struct workqueue_struct *wq)
  1049. {
  1050. struct worker *worker;
  1051. worker = current_wq_worker();
  1052. /*
  1053. * Return %true iff I'm a worker execuing a work item on @wq. If
  1054. * I'm @worker, it's safe to dereference it without locking.
  1055. */
  1056. return worker && worker->current_pwq->wq == wq;
  1057. }
  1058. static void __queue_work(int cpu, struct workqueue_struct *wq,
  1059. struct work_struct *work)
  1060. {
  1061. struct pool_workqueue *pwq;
  1062. struct worker_pool *last_pool;
  1063. struct list_head *worklist;
  1064. unsigned int work_flags;
  1065. unsigned int req_cpu = cpu;
  1066. /*
  1067. * While a work item is PENDING && off queue, a task trying to
  1068. * steal the PENDING will busy-loop waiting for it to either get
  1069. * queued or lose PENDING. Grabbing PENDING and queueing should
  1070. * happen with IRQ disabled.
  1071. */
  1072. WARN_ON_ONCE(!irqs_disabled());
  1073. debug_work_activate(work);
  1074. /* if dying, only works from the same workqueue are allowed */
  1075. if (unlikely(wq->flags & __WQ_DRAINING) &&
  1076. WARN_ON_ONCE(!is_chained_work(wq)))
  1077. return;
  1078. retry:
  1079. /* pwq which will be used unless @work is executing elsewhere */
  1080. if (!(wq->flags & WQ_UNBOUND)) {
  1081. if (cpu == WORK_CPU_UNBOUND)
  1082. cpu = raw_smp_processor_id();
  1083. pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
  1084. } else {
  1085. pwq = first_pwq(wq);
  1086. }
  1087. /*
  1088. * If @work was previously on a different pool, it might still be
  1089. * running there, in which case the work needs to be queued on that
  1090. * pool to guarantee non-reentrancy.
  1091. */
  1092. last_pool = get_work_pool(work);
  1093. if (last_pool && last_pool != pwq->pool) {
  1094. struct worker *worker;
  1095. spin_lock(&last_pool->lock);
  1096. worker = find_worker_executing_work(last_pool, work);
  1097. if (worker && worker->current_pwq->wq == wq) {
  1098. pwq = worker->current_pwq;
  1099. } else {
  1100. /* meh... not running there, queue here */
  1101. spin_unlock(&last_pool->lock);
  1102. spin_lock(&pwq->pool->lock);
  1103. }
  1104. } else {
  1105. spin_lock(&pwq->pool->lock);
  1106. }
  1107. /*
  1108. * pwq is determined and locked. For unbound pools, we could have
  1109. * raced with pwq release and it could already be dead. If its
  1110. * refcnt is zero, repeat pwq selection. Note that pwqs never die
  1111. * without another pwq replacing it as the first pwq or while a
  1112. * work item is executing on it, so the retying is guaranteed to
  1113. * make forward-progress.
  1114. */
  1115. if (unlikely(!pwq->refcnt)) {
  1116. if (wq->flags & WQ_UNBOUND) {
  1117. spin_unlock(&pwq->pool->lock);
  1118. cpu_relax();
  1119. goto retry;
  1120. }
  1121. /* oops */
  1122. WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
  1123. wq->name, cpu);
  1124. }
  1125. /* pwq determined, queue */
  1126. trace_workqueue_queue_work(req_cpu, pwq, work);
  1127. if (WARN_ON(!list_empty(&work->entry))) {
  1128. spin_unlock(&pwq->pool->lock);
  1129. return;
  1130. }
  1131. pwq->nr_in_flight[pwq->work_color]++;
  1132. work_flags = work_color_to_flags(pwq->work_color);
  1133. if (likely(pwq->nr_active < pwq->max_active)) {
  1134. trace_workqueue_activate_work(work);
  1135. pwq->nr_active++;
  1136. worklist = &pwq->pool->worklist;
  1137. } else {
  1138. work_flags |= WORK_STRUCT_DELAYED;
  1139. worklist = &pwq->delayed_works;
  1140. }
  1141. insert_work(pwq, work, worklist, work_flags);
  1142. spin_unlock(&pwq->pool->lock);
  1143. }
  1144. /**
  1145. * queue_work_on - queue work on specific cpu
  1146. * @cpu: CPU number to execute work on
  1147. * @wq: workqueue to use
  1148. * @work: work to queue
  1149. *
  1150. * Returns %false if @work was already on a queue, %true otherwise.
  1151. *
  1152. * We queue the work to a specific CPU, the caller must ensure it
  1153. * can't go away.
  1154. */
  1155. bool queue_work_on(int cpu, struct workqueue_struct *wq,
  1156. struct work_struct *work)
  1157. {
  1158. bool ret = false;
  1159. unsigned long flags;
  1160. local_irq_save(flags);
  1161. if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
  1162. __queue_work(cpu, wq, work);
  1163. ret = true;
  1164. }
  1165. local_irq_restore(flags);
  1166. return ret;
  1167. }
  1168. EXPORT_SYMBOL_GPL(queue_work_on);
  1169. void delayed_work_timer_fn(unsigned long __data)
  1170. {
  1171. struct delayed_work *dwork = (struct delayed_work *)__data;
  1172. /* should have been called from irqsafe timer with irq already off */
  1173. __queue_work(dwork->cpu, dwork->wq, &dwork->work);
  1174. }
  1175. EXPORT_SYMBOL(delayed_work_timer_fn);
  1176. static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
  1177. struct delayed_work *dwork, unsigned long delay)
  1178. {
  1179. struct timer_list *timer = &dwork->timer;
  1180. struct work_struct *work = &dwork->work;
  1181. WARN_ON_ONCE(timer->function != delayed_work_timer_fn ||
  1182. timer->data != (unsigned long)dwork);
  1183. WARN_ON_ONCE(timer_pending(timer));
  1184. WARN_ON_ONCE(!list_empty(&work->entry));
  1185. /*
  1186. * If @delay is 0, queue @dwork->work immediately. This is for
  1187. * both optimization and correctness. The earliest @timer can
  1188. * expire is on the closest next tick and delayed_work users depend
  1189. * on that there's no such delay when @delay is 0.
  1190. */
  1191. if (!delay) {
  1192. __queue_work(cpu, wq, &dwork->work);
  1193. return;
  1194. }
  1195. timer_stats_timer_set_start_info(&dwork->timer);
  1196. dwork->wq = wq;
  1197. dwork->cpu = cpu;
  1198. timer->expires = jiffies + delay;
  1199. if (unlikely(cpu != WORK_CPU_UNBOUND))
  1200. add_timer_on(timer, cpu);
  1201. else
  1202. add_timer(timer);
  1203. }
  1204. /**
  1205. * queue_delayed_work_on - queue work on specific CPU after delay
  1206. * @cpu: CPU number to execute work on
  1207. * @wq: workqueue to use
  1208. * @dwork: work to queue
  1209. * @delay: number of jiffies to wait before queueing
  1210. *
  1211. * Returns %false if @work was already on a queue, %true otherwise. If
  1212. * @delay is zero and @dwork is idle, it will be scheduled for immediate
  1213. * execution.
  1214. */
  1215. bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
  1216. struct delayed_work *dwork, unsigned long delay)
  1217. {
  1218. struct work_struct *work = &dwork->work;
  1219. bool ret = false;
  1220. unsigned long flags;
  1221. /* read the comment in __queue_work() */
  1222. local_irq_save(flags);
  1223. if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
  1224. __queue_delayed_work(cpu, wq, dwork, delay);
  1225. ret = true;
  1226. }
  1227. local_irq_restore(flags);
  1228. return ret;
  1229. }
  1230. EXPORT_SYMBOL_GPL(queue_delayed_work_on);
  1231. /**
  1232. * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
  1233. * @cpu: CPU number to execute work on
  1234. * @wq: workqueue to use
  1235. * @dwork: work to queue
  1236. * @delay: number of jiffies to wait before queueing
  1237. *
  1238. * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
  1239. * modify @dwork's timer so that it expires after @delay. If @delay is
  1240. * zero, @work is guaranteed to be scheduled immediately regardless of its
  1241. * current state.
  1242. *
  1243. * Returns %false if @dwork was idle and queued, %true if @dwork was
  1244. * pending and its timer was modified.
  1245. *
  1246. * This function is safe to call from any context including IRQ handler.
  1247. * See try_to_grab_pending() for details.
  1248. */
  1249. bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
  1250. struct delayed_work *dwork, unsigned long delay)
  1251. {
  1252. unsigned long flags;
  1253. int ret;
  1254. do {
  1255. ret = try_to_grab_pending(&dwork->work, true, &flags);
  1256. } while (unlikely(ret == -EAGAIN));
  1257. if (likely(ret >= 0)) {
  1258. __queue_delayed_work(cpu, wq, dwork, delay);
  1259. local_irq_restore(flags);
  1260. }
  1261. /* -ENOENT from try_to_grab_pending() becomes %true */
  1262. return ret;
  1263. }
  1264. EXPORT_SYMBOL_GPL(mod_delayed_work_on);
  1265. /**
  1266. * worker_enter_idle - enter idle state
  1267. * @worker: worker which is entering idle state
  1268. *
  1269. * @worker is entering idle state. Update stats and idle timer if
  1270. * necessary.
  1271. *
  1272. * LOCKING:
  1273. * spin_lock_irq(pool->lock).
  1274. */
  1275. static void worker_enter_idle(struct worker *worker)
  1276. {
  1277. struct worker_pool *pool = worker->pool;
  1278. if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
  1279. WARN_ON_ONCE(!list_empty(&worker->entry) &&
  1280. (worker->hentry.next || worker->hentry.pprev)))
  1281. return;
  1282. /* can't use worker_set_flags(), also called from start_worker() */
  1283. worker->flags |= WORKER_IDLE;
  1284. pool->nr_idle++;
  1285. worker->last_active = jiffies;
  1286. /* idle_list is LIFO */
  1287. list_add(&worker->entry, &pool->idle_list);
  1288. if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
  1289. mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
  1290. /*
  1291. * Sanity check nr_running. Because wq_unbind_fn() releases
  1292. * pool->lock between setting %WORKER_UNBOUND and zapping
  1293. * nr_running, the warning may trigger spuriously. Check iff
  1294. * unbind is not in progress.
  1295. */
  1296. WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
  1297. pool->nr_workers == pool->nr_idle &&
  1298. atomic_read(&pool->nr_running));
  1299. }
  1300. /**
  1301. * worker_leave_idle - leave idle state
  1302. * @worker: worker which is leaving idle state
  1303. *
  1304. * @worker is leaving idle state. Update stats.
  1305. *
  1306. * LOCKING:
  1307. * spin_lock_irq(pool->lock).
  1308. */
  1309. static void worker_leave_idle(struct worker *worker)
  1310. {
  1311. struct worker_pool *pool = worker->pool;
  1312. if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
  1313. return;
  1314. worker_clr_flags(worker, WORKER_IDLE);
  1315. pool->nr_idle--;
  1316. list_del_init(&worker->entry);
  1317. }
  1318. /**
  1319. * worker_maybe_bind_and_lock - try to bind %current to worker_pool and lock it
  1320. * @pool: target worker_pool
  1321. *
  1322. * Bind %current to the cpu of @pool if it is associated and lock @pool.
  1323. *
  1324. * Works which are scheduled while the cpu is online must at least be
  1325. * scheduled to a worker which is bound to the cpu so that if they are
  1326. * flushed from cpu callbacks while cpu is going down, they are
  1327. * guaranteed to execute on the cpu.
  1328. *
  1329. * This function is to be used by unbound workers and rescuers to bind
  1330. * themselves to the target cpu and may race with cpu going down or
  1331. * coming online. kthread_bind() can't be used because it may put the
  1332. * worker to already dead cpu and set_cpus_allowed_ptr() can't be used
  1333. * verbatim as it's best effort and blocking and pool may be
  1334. * [dis]associated in the meantime.
  1335. *
  1336. * This function tries set_cpus_allowed() and locks pool and verifies the
  1337. * binding against %POOL_DISASSOCIATED which is set during
  1338. * %CPU_DOWN_PREPARE and cleared during %CPU_ONLINE, so if the worker
  1339. * enters idle state or fetches works without dropping lock, it can
  1340. * guarantee the scheduling requirement described in the first paragraph.
  1341. *
  1342. * CONTEXT:
  1343. * Might sleep. Called without any lock but returns with pool->lock
  1344. * held.
  1345. *
  1346. * RETURNS:
  1347. * %true if the associated pool is online (@worker is successfully
  1348. * bound), %false if offline.
  1349. */
  1350. static bool worker_maybe_bind_and_lock(struct worker_pool *pool)
  1351. __acquires(&pool->lock)
  1352. {
  1353. while (true) {
  1354. /*
  1355. * The following call may fail, succeed or succeed
  1356. * without actually migrating the task to the cpu if
  1357. * it races with cpu hotunplug operation. Verify
  1358. * against POOL_DISASSOCIATED.
  1359. */
  1360. if (!(pool->flags & POOL_DISASSOCIATED))
  1361. set_cpus_allowed_ptr(current, pool->attrs->cpumask);
  1362. spin_lock_irq(&pool->lock);
  1363. if (pool->flags & POOL_DISASSOCIATED)
  1364. return false;
  1365. if (task_cpu(current) == pool->cpu &&
  1366. cpumask_equal(&current->cpus_allowed, pool->attrs->cpumask))
  1367. return true;
  1368. spin_unlock_irq(&pool->lock);
  1369. /*
  1370. * We've raced with CPU hot[un]plug. Give it a breather
  1371. * and retry migration. cond_resched() is required here;
  1372. * otherwise, we might deadlock against cpu_stop trying to
  1373. * bring down the CPU on non-preemptive kernel.
  1374. */
  1375. cpu_relax();
  1376. cond_resched();
  1377. }
  1378. }
  1379. /*
  1380. * Rebind an idle @worker to its CPU. worker_thread() will test
  1381. * list_empty(@worker->entry) before leaving idle and call this function.
  1382. */
  1383. static void idle_worker_rebind(struct worker *worker)
  1384. {
  1385. /* CPU may go down again inbetween, clear UNBOUND only on success */
  1386. if (worker_maybe_bind_and_lock(worker->pool))
  1387. worker_clr_flags(worker, WORKER_UNBOUND);
  1388. /* rebind complete, become available again */
  1389. list_add(&worker->entry, &worker->pool->idle_list);
  1390. spin_unlock_irq(&worker->pool->lock);
  1391. }
  1392. /*
  1393. * Function for @worker->rebind.work used to rebind unbound busy workers to
  1394. * the associated cpu which is coming back online. This is scheduled by
  1395. * cpu up but can race with other cpu hotplug operations and may be
  1396. * executed twice without intervening cpu down.
  1397. */
  1398. static void busy_worker_rebind_fn(struct work_struct *work)
  1399. {
  1400. struct worker *worker = container_of(work, struct worker, rebind_work);
  1401. if (worker_maybe_bind_and_lock(worker->pool))
  1402. worker_clr_flags(worker, WORKER_UNBOUND);
  1403. spin_unlock_irq(&worker->pool->lock);
  1404. }
  1405. /**
  1406. * rebind_workers - rebind all workers of a pool to the associated CPU
  1407. * @pool: pool of interest
  1408. *
  1409. * @pool->cpu is coming online. Rebind all workers to the CPU. Rebinding
  1410. * is different for idle and busy ones.
  1411. *
  1412. * Idle ones will be removed from the idle_list and woken up. They will
  1413. * add themselves back after completing rebind. This ensures that the
  1414. * idle_list doesn't contain any unbound workers when re-bound busy workers
  1415. * try to perform local wake-ups for concurrency management.
  1416. *
  1417. * Busy workers can rebind after they finish their current work items.
  1418. * Queueing the rebind work item at the head of the scheduled list is
  1419. * enough. Note that nr_running will be properly bumped as busy workers
  1420. * rebind.
  1421. *
  1422. * On return, all non-manager workers are scheduled for rebind - see
  1423. * manage_workers() for the manager special case. Any idle worker
  1424. * including the manager will not appear on @idle_list until rebind is
  1425. * complete, making local wake-ups safe.
  1426. */
  1427. static void rebind_workers(struct worker_pool *pool)
  1428. {
  1429. struct worker *worker, *n;
  1430. int i;
  1431. lockdep_assert_held(&pool->manager_mutex);
  1432. lockdep_assert_held(&pool->lock);
  1433. /* dequeue and kick idle ones */
  1434. list_for_each_entry_safe(worker, n, &pool->idle_list, entry) {
  1435. /*
  1436. * idle workers should be off @pool->idle_list until rebind
  1437. * is complete to avoid receiving premature local wake-ups.
  1438. */
  1439. list_del_init(&worker->entry);
  1440. /*
  1441. * worker_thread() will see the above dequeuing and call
  1442. * idle_worker_rebind().
  1443. */
  1444. wake_up_process(worker->task);
  1445. }
  1446. /* rebind busy workers */
  1447. for_each_busy_worker(worker, i, pool) {
  1448. struct work_struct *rebind_work = &worker->rebind_work;
  1449. struct workqueue_struct *wq;
  1450. if (test_and_set_bit(WORK_STRUCT_PENDING_BIT,
  1451. work_data_bits(rebind_work)))
  1452. continue;
  1453. debug_work_activate(rebind_work);
  1454. /*
  1455. * wq doesn't really matter but let's keep @worker->pool
  1456. * and @pwq->pool consistent for sanity.
  1457. */
  1458. if (worker->pool->attrs->nice < 0)
  1459. wq = system_highpri_wq;
  1460. else
  1461. wq = system_wq;
  1462. insert_work(per_cpu_ptr(wq->cpu_pwqs, pool->cpu), rebind_work,
  1463. worker->scheduled.next,
  1464. work_color_to_flags(WORK_NO_COLOR));
  1465. }
  1466. }
  1467. static struct worker *alloc_worker(void)
  1468. {
  1469. struct worker *worker;
  1470. worker = kzalloc(sizeof(*worker), GFP_KERNEL);
  1471. if (worker) {
  1472. INIT_LIST_HEAD(&worker->entry);
  1473. INIT_LIST_HEAD(&worker->scheduled);
  1474. INIT_WORK(&worker->rebind_work, busy_worker_rebind_fn);
  1475. /* on creation a worker is in !idle && prep state */
  1476. worker->flags = WORKER_PREP;
  1477. }
  1478. return worker;
  1479. }
  1480. /**
  1481. * create_worker - create a new workqueue worker
  1482. * @pool: pool the new worker will belong to
  1483. *
  1484. * Create a new worker which is bound to @pool. The returned worker
  1485. * can be started by calling start_worker() or destroyed using
  1486. * destroy_worker().
  1487. *
  1488. * CONTEXT:
  1489. * Might sleep. Does GFP_KERNEL allocations.
  1490. *
  1491. * RETURNS:
  1492. * Pointer to the newly created worker.
  1493. */
  1494. static struct worker *create_worker(struct worker_pool *pool)
  1495. {
  1496. const char *pri = pool->attrs->nice < 0 ? "H" : "";
  1497. struct worker *worker = NULL;
  1498. int id = -1;
  1499. lockdep_assert_held(&pool->manager_mutex);
  1500. spin_lock_irq(&pool->lock);
  1501. while (ida_get_new(&pool->worker_ida, &id)) {
  1502. spin_unlock_irq(&pool->lock);
  1503. if (!ida_pre_get(&pool->worker_ida, GFP_KERNEL))
  1504. goto fail;
  1505. spin_lock_irq(&pool->lock);
  1506. }
  1507. spin_unlock_irq(&pool->lock);
  1508. worker = alloc_worker();
  1509. if (!worker)
  1510. goto fail;
  1511. worker->pool = pool;
  1512. worker->id = id;
  1513. if (pool->cpu >= 0)
  1514. worker->task = kthread_create_on_node(worker_thread,
  1515. worker, cpu_to_node(pool->cpu),
  1516. "kworker/%d:%d%s", pool->cpu, id, pri);
  1517. else
  1518. worker->task = kthread_create(worker_thread, worker,
  1519. "kworker/u%d:%d%s",
  1520. pool->id, id, pri);
  1521. if (IS_ERR(worker->task))
  1522. goto fail;
  1523. /*
  1524. * set_cpus_allowed_ptr() will fail if the cpumask doesn't have any
  1525. * online CPUs. It'll be re-applied when any of the CPUs come up.
  1526. */
  1527. set_user_nice(worker->task, pool->attrs->nice);
  1528. set_cpus_allowed_ptr(worker->task, pool->attrs->cpumask);
  1529. /*
  1530. * %PF_THREAD_BOUND is used to prevent userland from meddling with
  1531. * cpumask of workqueue workers. This is an abuse. We need
  1532. * %PF_NO_SETAFFINITY.
  1533. */
  1534. worker->task->flags |= PF_THREAD_BOUND;
  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(&workqueue_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(&workqueue_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(&workqueue_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(&workqueue_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(&workqueue_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(&workqueue_lock);
  2122. }
  2123. spin_unlock_irq(&workqueue_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. spin_lock_irq(&workqueue_lock);
  2403. if (!wq->nr_drainers++)
  2404. wq->flags |= __WQ_DRAINING;
  2405. spin_unlock_irq(&workqueue_lock);
  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. spin_lock(&workqueue_lock);
  2424. if (!--wq->nr_drainers)
  2425. wq->flags &= ~__WQ_DRAINING;
  2426. spin_unlock(&workqueue_lock);
  2427. local_irq_enable();
  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. spin_lock_irq(&workqueue_lock);
  3041. if (--pool->refcnt) {
  3042. spin_unlock_irq(&workqueue_lock);
  3043. return;
  3044. }
  3045. /* sanity checks */
  3046. if (WARN_ON(!(pool->flags & POOL_DISASSOCIATED)) ||
  3047. WARN_ON(!list_empty(&pool->worklist))) {
  3048. spin_unlock_irq(&workqueue_lock);
  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. spin_unlock_irq(&workqueue_lock);
  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. static DEFINE_MUTEX(create_mutex);
  3088. u32 hash = wqattrs_hash(attrs);
  3089. struct worker_pool *pool;
  3090. mutex_lock(&create_mutex);
  3091. /* do we already have a matching pool? */
  3092. spin_lock_irq(&workqueue_lock);
  3093. hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
  3094. if (wqattrs_equal(pool->attrs, attrs)) {
  3095. pool->refcnt++;
  3096. goto out_unlock;
  3097. }
  3098. }
  3099. spin_unlock_irq(&workqueue_lock);
  3100. /* nope, create a new one */
  3101. pool = kzalloc(sizeof(*pool), GFP_KERNEL);
  3102. if (!pool || init_worker_pool(pool) < 0)
  3103. goto fail;
  3104. lockdep_set_subclass(&pool->lock, 1); /* see put_pwq() */
  3105. copy_workqueue_attrs(pool->attrs, attrs);
  3106. if (worker_pool_assign_id(pool) < 0)
  3107. goto fail;
  3108. /* create and start the initial worker */
  3109. if (create_and_start_worker(pool) < 0)
  3110. goto fail;
  3111. /* install */
  3112. spin_lock_irq(&workqueue_lock);
  3113. hash_add(unbound_pool_hash, &pool->hash_node, hash);
  3114. out_unlock:
  3115. spin_unlock_irq(&workqueue_lock);
  3116. mutex_unlock(&create_mutex);
  3117. return pool;
  3118. fail:
  3119. mutex_unlock(&create_mutex);
  3120. if (pool)
  3121. put_unbound_pool(pool);
  3122. return NULL;
  3123. }
  3124. static void rcu_free_pwq(struct rcu_head *rcu)
  3125. {
  3126. kmem_cache_free(pwq_cache,
  3127. container_of(rcu, struct pool_workqueue, rcu));
  3128. }
  3129. /*
  3130. * Scheduled on system_wq by put_pwq() when an unbound pwq hits zero refcnt
  3131. * and needs to be destroyed.
  3132. */
  3133. static void pwq_unbound_release_workfn(struct work_struct *work)
  3134. {
  3135. struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
  3136. unbound_release_work);
  3137. struct workqueue_struct *wq = pwq->wq;
  3138. struct worker_pool *pool = pwq->pool;
  3139. if (WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND)))
  3140. return;
  3141. /*
  3142. * Unlink @pwq. Synchronization against flush_mutex isn't strictly
  3143. * necessary on release but do it anyway. It's easier to verify
  3144. * and consistent with the linking path.
  3145. */
  3146. mutex_lock(&wq->flush_mutex);
  3147. spin_lock_irq(&workqueue_lock);
  3148. list_del_rcu(&pwq->pwqs_node);
  3149. spin_unlock_irq(&workqueue_lock);
  3150. mutex_unlock(&wq->flush_mutex);
  3151. put_unbound_pool(pool);
  3152. call_rcu_sched(&pwq->rcu, rcu_free_pwq);
  3153. /*
  3154. * If we're the last pwq going away, @wq is already dead and no one
  3155. * is gonna access it anymore. Free it.
  3156. */
  3157. if (list_empty(&wq->pwqs))
  3158. kfree(wq);
  3159. }
  3160. /**
  3161. * pwq_adjust_max_active - update a pwq's max_active to the current setting
  3162. * @pwq: target pool_workqueue
  3163. *
  3164. * If @pwq isn't freezing, set @pwq->max_active to the associated
  3165. * workqueue's saved_max_active and activate delayed work items
  3166. * accordingly. If @pwq is freezing, clear @pwq->max_active to zero.
  3167. */
  3168. static void pwq_adjust_max_active(struct pool_workqueue *pwq)
  3169. {
  3170. struct workqueue_struct *wq = pwq->wq;
  3171. bool freezable = wq->flags & WQ_FREEZABLE;
  3172. /* for @wq->saved_max_active */
  3173. lockdep_assert_held(&workqueue_lock);
  3174. /* fast exit for non-freezable wqs */
  3175. if (!freezable && pwq->max_active == wq->saved_max_active)
  3176. return;
  3177. spin_lock(&pwq->pool->lock);
  3178. if (!freezable || !(pwq->pool->flags & POOL_FREEZING)) {
  3179. pwq->max_active = wq->saved_max_active;
  3180. while (!list_empty(&pwq->delayed_works) &&
  3181. pwq->nr_active < pwq->max_active)
  3182. pwq_activate_first_delayed(pwq);
  3183. } else {
  3184. pwq->max_active = 0;
  3185. }
  3186. spin_unlock(&pwq->pool->lock);
  3187. }
  3188. static void init_and_link_pwq(struct pool_workqueue *pwq,
  3189. struct workqueue_struct *wq,
  3190. struct worker_pool *pool,
  3191. struct pool_workqueue **p_last_pwq)
  3192. {
  3193. BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
  3194. pwq->pool = pool;
  3195. pwq->wq = wq;
  3196. pwq->flush_color = -1;
  3197. pwq->refcnt = 1;
  3198. INIT_LIST_HEAD(&pwq->delayed_works);
  3199. INIT_LIST_HEAD(&pwq->mayday_node);
  3200. INIT_WORK(&pwq->unbound_release_work, pwq_unbound_release_workfn);
  3201. mutex_lock(&wq->flush_mutex);
  3202. spin_lock_irq(&workqueue_lock);
  3203. /*
  3204. * Set the matching work_color. This is synchronized with
  3205. * flush_mutex to avoid confusing flush_workqueue().
  3206. */
  3207. if (p_last_pwq)
  3208. *p_last_pwq = first_pwq(wq);
  3209. pwq->work_color = wq->work_color;
  3210. /* sync max_active to the current setting */
  3211. pwq_adjust_max_active(pwq);
  3212. /* link in @pwq */
  3213. list_add_rcu(&pwq->pwqs_node, &wq->pwqs);
  3214. spin_unlock_irq(&workqueue_lock);
  3215. mutex_unlock(&wq->flush_mutex);
  3216. }
  3217. /**
  3218. * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
  3219. * @wq: the target workqueue
  3220. * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
  3221. *
  3222. * Apply @attrs to an unbound workqueue @wq. If @attrs doesn't match the
  3223. * current attributes, a new pwq is created and made the first pwq which
  3224. * will serve all new work items. Older pwqs are released as in-flight
  3225. * work items finish. Note that a work item which repeatedly requeues
  3226. * itself back-to-back will stay on its current pwq.
  3227. *
  3228. * Performs GFP_KERNEL allocations. Returns 0 on success and -errno on
  3229. * failure.
  3230. */
  3231. int apply_workqueue_attrs(struct workqueue_struct *wq,
  3232. const struct workqueue_attrs *attrs)
  3233. {
  3234. struct pool_workqueue *pwq, *last_pwq;
  3235. struct worker_pool *pool;
  3236. /* only unbound workqueues can change attributes */
  3237. if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
  3238. return -EINVAL;
  3239. /* creating multiple pwqs breaks ordering guarantee */
  3240. if (WARN_ON((wq->flags & __WQ_ORDERED) && !list_empty(&wq->pwqs)))
  3241. return -EINVAL;
  3242. pwq = kmem_cache_zalloc(pwq_cache, GFP_KERNEL);
  3243. if (!pwq)
  3244. return -ENOMEM;
  3245. pool = get_unbound_pool(attrs);
  3246. if (!pool) {
  3247. kmem_cache_free(pwq_cache, pwq);
  3248. return -ENOMEM;
  3249. }
  3250. init_and_link_pwq(pwq, wq, pool, &last_pwq);
  3251. if (last_pwq) {
  3252. spin_lock_irq(&last_pwq->pool->lock);
  3253. put_pwq(last_pwq);
  3254. spin_unlock_irq(&last_pwq->pool->lock);
  3255. }
  3256. return 0;
  3257. }
  3258. static int alloc_and_link_pwqs(struct workqueue_struct *wq)
  3259. {
  3260. bool highpri = wq->flags & WQ_HIGHPRI;
  3261. int cpu;
  3262. if (!(wq->flags & WQ_UNBOUND)) {
  3263. wq->cpu_pwqs = alloc_percpu(struct pool_workqueue);
  3264. if (!wq->cpu_pwqs)
  3265. return -ENOMEM;
  3266. for_each_possible_cpu(cpu) {
  3267. struct pool_workqueue *pwq =
  3268. per_cpu_ptr(wq->cpu_pwqs, cpu);
  3269. struct worker_pool *cpu_pools =
  3270. per_cpu(cpu_worker_pools, cpu);
  3271. init_and_link_pwq(pwq, wq, &cpu_pools[highpri], NULL);
  3272. }
  3273. return 0;
  3274. } else {
  3275. return apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
  3276. }
  3277. }
  3278. static int wq_clamp_max_active(int max_active, unsigned int flags,
  3279. const char *name)
  3280. {
  3281. int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
  3282. if (max_active < 1 || max_active > lim)
  3283. pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
  3284. max_active, name, 1, lim);
  3285. return clamp_val(max_active, 1, lim);
  3286. }
  3287. struct workqueue_struct *__alloc_workqueue_key(const char *fmt,
  3288. unsigned int flags,
  3289. int max_active,
  3290. struct lock_class_key *key,
  3291. const char *lock_name, ...)
  3292. {
  3293. va_list args, args1;
  3294. struct workqueue_struct *wq;
  3295. struct pool_workqueue *pwq;
  3296. size_t namelen;
  3297. /* determine namelen, allocate wq and format name */
  3298. va_start(args, lock_name);
  3299. va_copy(args1, args);
  3300. namelen = vsnprintf(NULL, 0, fmt, args) + 1;
  3301. wq = kzalloc(sizeof(*wq) + namelen, GFP_KERNEL);
  3302. if (!wq)
  3303. return NULL;
  3304. vsnprintf(wq->name, namelen, fmt, args1);
  3305. va_end(args);
  3306. va_end(args1);
  3307. max_active = max_active ?: WQ_DFL_ACTIVE;
  3308. max_active = wq_clamp_max_active(max_active, flags, wq->name);
  3309. /* init wq */
  3310. wq->flags = flags;
  3311. wq->saved_max_active = max_active;
  3312. mutex_init(&wq->flush_mutex);
  3313. atomic_set(&wq->nr_pwqs_to_flush, 0);
  3314. INIT_LIST_HEAD(&wq->pwqs);
  3315. INIT_LIST_HEAD(&wq->flusher_queue);
  3316. INIT_LIST_HEAD(&wq->flusher_overflow);
  3317. INIT_LIST_HEAD(&wq->maydays);
  3318. lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
  3319. INIT_LIST_HEAD(&wq->list);
  3320. if (alloc_and_link_pwqs(wq) < 0)
  3321. goto err_free_wq;
  3322. /*
  3323. * Workqueues which may be used during memory reclaim should
  3324. * have a rescuer to guarantee forward progress.
  3325. */
  3326. if (flags & WQ_MEM_RECLAIM) {
  3327. struct worker *rescuer;
  3328. rescuer = alloc_worker();
  3329. if (!rescuer)
  3330. goto err_destroy;
  3331. rescuer->rescue_wq = wq;
  3332. rescuer->task = kthread_create(rescuer_thread, rescuer, "%s",
  3333. wq->name);
  3334. if (IS_ERR(rescuer->task)) {
  3335. kfree(rescuer);
  3336. goto err_destroy;
  3337. }
  3338. wq->rescuer = rescuer;
  3339. rescuer->task->flags |= PF_THREAD_BOUND;
  3340. wake_up_process(rescuer->task);
  3341. }
  3342. if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
  3343. goto err_destroy;
  3344. /*
  3345. * workqueue_lock protects global freeze state and workqueues list.
  3346. * Grab it, adjust max_active and add the new workqueue to
  3347. * workqueues list.
  3348. */
  3349. spin_lock_irq(&workqueue_lock);
  3350. for_each_pwq(pwq, wq)
  3351. pwq_adjust_max_active(pwq);
  3352. list_add(&wq->list, &workqueues);
  3353. spin_unlock_irq(&workqueue_lock);
  3354. return wq;
  3355. err_free_wq:
  3356. kfree(wq);
  3357. return NULL;
  3358. err_destroy:
  3359. destroy_workqueue(wq);
  3360. return NULL;
  3361. }
  3362. EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
  3363. /**
  3364. * destroy_workqueue - safely terminate a workqueue
  3365. * @wq: target workqueue
  3366. *
  3367. * Safely destroy a workqueue. All work currently pending will be done first.
  3368. */
  3369. void destroy_workqueue(struct workqueue_struct *wq)
  3370. {
  3371. struct pool_workqueue *pwq;
  3372. /* drain it before proceeding with destruction */
  3373. drain_workqueue(wq);
  3374. spin_lock_irq(&workqueue_lock);
  3375. /* sanity checks */
  3376. for_each_pwq(pwq, wq) {
  3377. int i;
  3378. for (i = 0; i < WORK_NR_COLORS; i++) {
  3379. if (WARN_ON(pwq->nr_in_flight[i])) {
  3380. spin_unlock_irq(&workqueue_lock);
  3381. return;
  3382. }
  3383. }
  3384. if (WARN_ON(pwq->refcnt > 1) ||
  3385. WARN_ON(pwq->nr_active) ||
  3386. WARN_ON(!list_empty(&pwq->delayed_works))) {
  3387. spin_unlock_irq(&workqueue_lock);
  3388. return;
  3389. }
  3390. }
  3391. /*
  3392. * wq list is used to freeze wq, remove from list after
  3393. * flushing is complete in case freeze races us.
  3394. */
  3395. list_del_init(&wq->list);
  3396. spin_unlock_irq(&workqueue_lock);
  3397. workqueue_sysfs_unregister(wq);
  3398. if (wq->rescuer) {
  3399. kthread_stop(wq->rescuer->task);
  3400. kfree(wq->rescuer);
  3401. wq->rescuer = NULL;
  3402. }
  3403. if (!(wq->flags & WQ_UNBOUND)) {
  3404. /*
  3405. * The base ref is never dropped on per-cpu pwqs. Directly
  3406. * free the pwqs and wq.
  3407. */
  3408. free_percpu(wq->cpu_pwqs);
  3409. kfree(wq);
  3410. } else {
  3411. /*
  3412. * We're the sole accessor of @wq at this point. Directly
  3413. * access the first pwq and put the base ref. As both pwqs
  3414. * and pools are sched-RCU protected, the lock operations
  3415. * are safe. @wq will be freed when the last pwq is
  3416. * released.
  3417. */
  3418. pwq = list_first_entry(&wq->pwqs, struct pool_workqueue,
  3419. pwqs_node);
  3420. spin_lock_irq(&pwq->pool->lock);
  3421. put_pwq(pwq);
  3422. spin_unlock_irq(&pwq->pool->lock);
  3423. }
  3424. }
  3425. EXPORT_SYMBOL_GPL(destroy_workqueue);
  3426. /**
  3427. * workqueue_set_max_active - adjust max_active of a workqueue
  3428. * @wq: target workqueue
  3429. * @max_active: new max_active value.
  3430. *
  3431. * Set max_active of @wq to @max_active.
  3432. *
  3433. * CONTEXT:
  3434. * Don't call from IRQ context.
  3435. */
  3436. void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
  3437. {
  3438. struct pool_workqueue *pwq;
  3439. /* disallow meddling with max_active for ordered workqueues */
  3440. if (WARN_ON(wq->flags & __WQ_ORDERED))
  3441. return;
  3442. max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
  3443. spin_lock_irq(&workqueue_lock);
  3444. wq->saved_max_active = max_active;
  3445. for_each_pwq(pwq, wq)
  3446. pwq_adjust_max_active(pwq);
  3447. spin_unlock_irq(&workqueue_lock);
  3448. }
  3449. EXPORT_SYMBOL_GPL(workqueue_set_max_active);
  3450. /**
  3451. * current_is_workqueue_rescuer - is %current workqueue rescuer?
  3452. *
  3453. * Determine whether %current is a workqueue rescuer. Can be used from
  3454. * work functions to determine whether it's being run off the rescuer task.
  3455. */
  3456. bool current_is_workqueue_rescuer(void)
  3457. {
  3458. struct worker *worker = current_wq_worker();
  3459. return worker && worker == worker->current_pwq->wq->rescuer;
  3460. }
  3461. /**
  3462. * workqueue_congested - test whether a workqueue is congested
  3463. * @cpu: CPU in question
  3464. * @wq: target workqueue
  3465. *
  3466. * Test whether @wq's cpu workqueue for @cpu is congested. There is
  3467. * no synchronization around this function and the test result is
  3468. * unreliable and only useful as advisory hints or for debugging.
  3469. *
  3470. * RETURNS:
  3471. * %true if congested, %false otherwise.
  3472. */
  3473. bool workqueue_congested(int cpu, struct workqueue_struct *wq)
  3474. {
  3475. struct pool_workqueue *pwq;
  3476. bool ret;
  3477. preempt_disable();
  3478. if (!(wq->flags & WQ_UNBOUND))
  3479. pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
  3480. else
  3481. pwq = first_pwq(wq);
  3482. ret = !list_empty(&pwq->delayed_works);
  3483. preempt_enable();
  3484. return ret;
  3485. }
  3486. EXPORT_SYMBOL_GPL(workqueue_congested);
  3487. /**
  3488. * work_busy - test whether a work is currently pending or running
  3489. * @work: the work to be tested
  3490. *
  3491. * Test whether @work is currently pending or running. There is no
  3492. * synchronization around this function and the test result is
  3493. * unreliable and only useful as advisory hints or for debugging.
  3494. *
  3495. * RETURNS:
  3496. * OR'd bitmask of WORK_BUSY_* bits.
  3497. */
  3498. unsigned int work_busy(struct work_struct *work)
  3499. {
  3500. struct worker_pool *pool;
  3501. unsigned long flags;
  3502. unsigned int ret = 0;
  3503. if (work_pending(work))
  3504. ret |= WORK_BUSY_PENDING;
  3505. local_irq_save(flags);
  3506. pool = get_work_pool(work);
  3507. if (pool) {
  3508. spin_lock(&pool->lock);
  3509. if (find_worker_executing_work(pool, work))
  3510. ret |= WORK_BUSY_RUNNING;
  3511. spin_unlock(&pool->lock);
  3512. }
  3513. local_irq_restore(flags);
  3514. return ret;
  3515. }
  3516. EXPORT_SYMBOL_GPL(work_busy);
  3517. /*
  3518. * CPU hotplug.
  3519. *
  3520. * There are two challenges in supporting CPU hotplug. Firstly, there
  3521. * are a lot of assumptions on strong associations among work, pwq and
  3522. * pool which make migrating pending and scheduled works very
  3523. * difficult to implement without impacting hot paths. Secondly,
  3524. * worker pools serve mix of short, long and very long running works making
  3525. * blocked draining impractical.
  3526. *
  3527. * This is solved by allowing the pools to be disassociated from the CPU
  3528. * running as an unbound one and allowing it to be reattached later if the
  3529. * cpu comes back online.
  3530. */
  3531. static void wq_unbind_fn(struct work_struct *work)
  3532. {
  3533. int cpu = smp_processor_id();
  3534. struct worker_pool *pool;
  3535. struct worker *worker;
  3536. int i;
  3537. for_each_cpu_worker_pool(pool, cpu) {
  3538. WARN_ON_ONCE(cpu != smp_processor_id());
  3539. mutex_lock(&pool->manager_mutex);
  3540. spin_lock_irq(&pool->lock);
  3541. /*
  3542. * We've blocked all manager operations. Make all workers
  3543. * unbound and set DISASSOCIATED. Before this, all workers
  3544. * except for the ones which are still executing works from
  3545. * before the last CPU down must be on the cpu. After
  3546. * this, they may become diasporas.
  3547. */
  3548. list_for_each_entry(worker, &pool->idle_list, entry)
  3549. worker->flags |= WORKER_UNBOUND;
  3550. for_each_busy_worker(worker, i, pool)
  3551. worker->flags |= WORKER_UNBOUND;
  3552. pool->flags |= POOL_DISASSOCIATED;
  3553. spin_unlock_irq(&pool->lock);
  3554. mutex_unlock(&pool->manager_mutex);
  3555. }
  3556. /*
  3557. * Call schedule() so that we cross rq->lock and thus can guarantee
  3558. * sched callbacks see the %WORKER_UNBOUND flag. This is necessary
  3559. * as scheduler callbacks may be invoked from other cpus.
  3560. */
  3561. schedule();
  3562. /*
  3563. * Sched callbacks are disabled now. Zap nr_running. After this,
  3564. * nr_running stays zero and need_more_worker() and keep_working()
  3565. * are always true as long as the worklist is not empty. Pools on
  3566. * @cpu now behave as unbound (in terms of concurrency management)
  3567. * pools which are served by workers tied to the CPU.
  3568. *
  3569. * On return from this function, the current worker would trigger
  3570. * unbound chain execution of pending work items if other workers
  3571. * didn't already.
  3572. */
  3573. for_each_cpu_worker_pool(pool, cpu)
  3574. atomic_set(&pool->nr_running, 0);
  3575. }
  3576. /*
  3577. * Workqueues should be brought up before normal priority CPU notifiers.
  3578. * This will be registered high priority CPU notifier.
  3579. */
  3580. static int __cpuinit workqueue_cpu_up_callback(struct notifier_block *nfb,
  3581. unsigned long action,
  3582. void *hcpu)
  3583. {
  3584. int cpu = (unsigned long)hcpu;
  3585. struct worker_pool *pool;
  3586. switch (action & ~CPU_TASKS_FROZEN) {
  3587. case CPU_UP_PREPARE:
  3588. for_each_cpu_worker_pool(pool, cpu) {
  3589. if (pool->nr_workers)
  3590. continue;
  3591. if (create_and_start_worker(pool) < 0)
  3592. return NOTIFY_BAD;
  3593. }
  3594. break;
  3595. case CPU_DOWN_FAILED:
  3596. case CPU_ONLINE:
  3597. for_each_cpu_worker_pool(pool, cpu) {
  3598. mutex_lock(&pool->manager_mutex);
  3599. spin_lock_irq(&pool->lock);
  3600. pool->flags &= ~POOL_DISASSOCIATED;
  3601. rebind_workers(pool);
  3602. spin_unlock_irq(&pool->lock);
  3603. mutex_unlock(&pool->manager_mutex);
  3604. }
  3605. break;
  3606. }
  3607. return NOTIFY_OK;
  3608. }
  3609. /*
  3610. * Workqueues should be brought down after normal priority CPU notifiers.
  3611. * This will be registered as low priority CPU notifier.
  3612. */
  3613. static int __cpuinit workqueue_cpu_down_callback(struct notifier_block *nfb,
  3614. unsigned long action,
  3615. void *hcpu)
  3616. {
  3617. int cpu = (unsigned long)hcpu;
  3618. struct work_struct unbind_work;
  3619. switch (action & ~CPU_TASKS_FROZEN) {
  3620. case CPU_DOWN_PREPARE:
  3621. /* unbinding should happen on the local CPU */
  3622. INIT_WORK_ONSTACK(&unbind_work, wq_unbind_fn);
  3623. queue_work_on(cpu, system_highpri_wq, &unbind_work);
  3624. flush_work(&unbind_work);
  3625. break;
  3626. }
  3627. return NOTIFY_OK;
  3628. }
  3629. #ifdef CONFIG_SMP
  3630. struct work_for_cpu {
  3631. struct work_struct work;
  3632. long (*fn)(void *);
  3633. void *arg;
  3634. long ret;
  3635. };
  3636. static void work_for_cpu_fn(struct work_struct *work)
  3637. {
  3638. struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
  3639. wfc->ret = wfc->fn(wfc->arg);
  3640. }
  3641. /**
  3642. * work_on_cpu - run a function in user context on a particular cpu
  3643. * @cpu: the cpu to run on
  3644. * @fn: the function to run
  3645. * @arg: the function arg
  3646. *
  3647. * This will return the value @fn returns.
  3648. * It is up to the caller to ensure that the cpu doesn't go offline.
  3649. * The caller must not hold any locks which would prevent @fn from completing.
  3650. */
  3651. long work_on_cpu(int cpu, long (*fn)(void *), void *arg)
  3652. {
  3653. struct work_for_cpu wfc = { .fn = fn, .arg = arg };
  3654. INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
  3655. schedule_work_on(cpu, &wfc.work);
  3656. flush_work(&wfc.work);
  3657. return wfc.ret;
  3658. }
  3659. EXPORT_SYMBOL_GPL(work_on_cpu);
  3660. #endif /* CONFIG_SMP */
  3661. #ifdef CONFIG_FREEZER
  3662. /**
  3663. * freeze_workqueues_begin - begin freezing workqueues
  3664. *
  3665. * Start freezing workqueues. After this function returns, all freezable
  3666. * workqueues will queue new works to their delayed_works list instead of
  3667. * pool->worklist.
  3668. *
  3669. * CONTEXT:
  3670. * Grabs and releases workqueue_lock and pool->lock's.
  3671. */
  3672. void freeze_workqueues_begin(void)
  3673. {
  3674. struct worker_pool *pool;
  3675. struct workqueue_struct *wq;
  3676. struct pool_workqueue *pwq;
  3677. int pi;
  3678. spin_lock_irq(&workqueue_lock);
  3679. WARN_ON_ONCE(workqueue_freezing);
  3680. workqueue_freezing = true;
  3681. /* set FREEZING */
  3682. for_each_pool(pool, pi) {
  3683. spin_lock(&pool->lock);
  3684. WARN_ON_ONCE(pool->flags & POOL_FREEZING);
  3685. pool->flags |= POOL_FREEZING;
  3686. spin_unlock(&pool->lock);
  3687. }
  3688. /* suppress further executions by setting max_active to zero */
  3689. list_for_each_entry(wq, &workqueues, list) {
  3690. for_each_pwq(pwq, wq)
  3691. pwq_adjust_max_active(pwq);
  3692. }
  3693. spin_unlock_irq(&workqueue_lock);
  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 workqueue_lock.
  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. spin_lock_irq(&workqueue_lock);
  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. for_each_pwq(pwq, wq) {
  3723. WARN_ON_ONCE(pwq->nr_active < 0);
  3724. if (pwq->nr_active) {
  3725. busy = true;
  3726. goto out_unlock;
  3727. }
  3728. }
  3729. }
  3730. out_unlock:
  3731. spin_unlock_irq(&workqueue_lock);
  3732. return busy;
  3733. }
  3734. /**
  3735. * thaw_workqueues - thaw workqueues
  3736. *
  3737. * Thaw workqueues. Normal queueing is restored and all collected
  3738. * frozen works are transferred to their respective pool worklists.
  3739. *
  3740. * CONTEXT:
  3741. * Grabs and releases workqueue_lock and pool->lock's.
  3742. */
  3743. void thaw_workqueues(void)
  3744. {
  3745. struct workqueue_struct *wq;
  3746. struct pool_workqueue *pwq;
  3747. struct worker_pool *pool;
  3748. int pi;
  3749. spin_lock_irq(&workqueue_lock);
  3750. if (!workqueue_freezing)
  3751. goto out_unlock;
  3752. /* clear FREEZING */
  3753. for_each_pool(pool, pi) {
  3754. spin_lock(&pool->lock);
  3755. WARN_ON_ONCE(!(pool->flags & POOL_FREEZING));
  3756. pool->flags &= ~POOL_FREEZING;
  3757. spin_unlock(&pool->lock);
  3758. }
  3759. /* restore max_active and repopulate worklist */
  3760. list_for_each_entry(wq, &workqueues, list) {
  3761. for_each_pwq(pwq, wq)
  3762. pwq_adjust_max_active(pwq);
  3763. }
  3764. /* kick workers */
  3765. for_each_pool(pool, pi) {
  3766. spin_lock(&pool->lock);
  3767. wake_up_worker(pool);
  3768. spin_unlock(&pool->lock);
  3769. }
  3770. workqueue_freezing = false;
  3771. out_unlock:
  3772. spin_unlock_irq(&workqueue_lock);
  3773. }
  3774. #endif /* CONFIG_FREEZER */
  3775. static int __init init_workqueues(void)
  3776. {
  3777. int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
  3778. int i, cpu;
  3779. /* make sure we have enough bits for OFFQ pool ID */
  3780. BUILD_BUG_ON((1LU << (BITS_PER_LONG - WORK_OFFQ_POOL_SHIFT)) <
  3781. WORK_CPU_END * NR_STD_WORKER_POOLS);
  3782. WARN_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
  3783. pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
  3784. cpu_notifier(workqueue_cpu_up_callback, CPU_PRI_WORKQUEUE_UP);
  3785. hotcpu_notifier(workqueue_cpu_down_callback, CPU_PRI_WORKQUEUE_DOWN);
  3786. /* initialize CPU pools */
  3787. for_each_possible_cpu(cpu) {
  3788. struct worker_pool *pool;
  3789. i = 0;
  3790. for_each_cpu_worker_pool(pool, cpu) {
  3791. BUG_ON(init_worker_pool(pool));
  3792. pool->cpu = cpu;
  3793. cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
  3794. pool->attrs->nice = std_nice[i++];
  3795. /* alloc pool ID */
  3796. BUG_ON(worker_pool_assign_id(pool));
  3797. }
  3798. }
  3799. /* create the initial worker */
  3800. for_each_online_cpu(cpu) {
  3801. struct worker_pool *pool;
  3802. for_each_cpu_worker_pool(pool, cpu) {
  3803. pool->flags &= ~POOL_DISASSOCIATED;
  3804. BUG_ON(create_and_start_worker(pool) < 0);
  3805. }
  3806. }
  3807. /* create default unbound wq attrs */
  3808. for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
  3809. struct workqueue_attrs *attrs;
  3810. BUG_ON(!(attrs = alloc_workqueue_attrs(GFP_KERNEL)));
  3811. attrs->nice = std_nice[i];
  3812. cpumask_setall(attrs->cpumask);
  3813. unbound_std_wq_attrs[i] = attrs;
  3814. }
  3815. system_wq = alloc_workqueue("events", 0, 0);
  3816. system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
  3817. system_long_wq = alloc_workqueue("events_long", 0, 0);
  3818. system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
  3819. WQ_UNBOUND_MAX_ACTIVE);
  3820. system_freezable_wq = alloc_workqueue("events_freezable",
  3821. WQ_FREEZABLE, 0);
  3822. BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
  3823. !system_unbound_wq || !system_freezable_wq);
  3824. return 0;
  3825. }
  3826. early_initcall(init_workqueues);