workqueue.c 106 KB

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