workqueue.c 106 KB

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