workqueue.c 97 KB

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