workqueue.c 94 KB

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