workqueue.c 108 KB

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