workqueue.c 89 KB

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