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