workqueue.c 107 KB

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