workqueue.c 111 KB

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