workqueue.c 107 KB

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