workqueue.c 104 KB

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