workqueue.c 97 KB

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