workqueue.c 94 KB

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