workqueue.c 108 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937
  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. /*
  1051. * While a work item is PENDING && off queue, a task trying to
  1052. * steal the PENDING will busy-loop waiting for it to either get
  1053. * queued or lose PENDING. Grabbing PENDING and queueing should
  1054. * happen with IRQ disabled.
  1055. */
  1056. WARN_ON_ONCE(!irqs_disabled());
  1057. debug_work_activate(work);
  1058. /* if dying, only works from the same workqueue are allowed */
  1059. if (unlikely(wq->flags & WQ_DRAINING) &&
  1060. WARN_ON_ONCE(!is_chained_work(wq)))
  1061. return;
  1062. /* determine gcwq to use */
  1063. if (!(wq->flags & WQ_UNBOUND)) {
  1064. struct global_cwq *last_gcwq;
  1065. if (cpu == WORK_CPU_UNBOUND)
  1066. cpu = raw_smp_processor_id();
  1067. /*
  1068. * It's multi cpu. If @wq is non-reentrant and @work
  1069. * was previously on a different cpu, it might still
  1070. * be running there, in which case the work needs to
  1071. * be queued on that cpu to guarantee non-reentrance.
  1072. */
  1073. gcwq = get_gcwq(cpu);
  1074. if (wq->flags & WQ_NON_REENTRANT &&
  1075. (last_gcwq = get_work_gcwq(work)) && last_gcwq != gcwq) {
  1076. struct worker *worker;
  1077. spin_lock(&last_gcwq->lock);
  1078. worker = find_worker_executing_work(last_gcwq, work);
  1079. if (worker && worker->current_cwq->wq == wq)
  1080. gcwq = last_gcwq;
  1081. else {
  1082. /* meh... not running there, queue here */
  1083. spin_unlock(&last_gcwq->lock);
  1084. spin_lock(&gcwq->lock);
  1085. }
  1086. } else {
  1087. spin_lock(&gcwq->lock);
  1088. }
  1089. } else {
  1090. gcwq = get_gcwq(WORK_CPU_UNBOUND);
  1091. spin_lock(&gcwq->lock);
  1092. }
  1093. /* gcwq determined, get cwq and queue */
  1094. cwq = get_cwq(gcwq->cpu, wq);
  1095. trace_workqueue_queue_work(cpu, cwq, work);
  1096. if (WARN_ON(!list_empty(&work->entry))) {
  1097. spin_unlock(&gcwq->lock);
  1098. return;
  1099. }
  1100. cwq->nr_in_flight[cwq->work_color]++;
  1101. work_flags = work_color_to_flags(cwq->work_color);
  1102. if (likely(cwq->nr_active < cwq->max_active)) {
  1103. trace_workqueue_activate_work(work);
  1104. cwq->nr_active++;
  1105. worklist = &cwq->pool->worklist;
  1106. } else {
  1107. work_flags |= WORK_STRUCT_DELAYED;
  1108. worklist = &cwq->delayed_works;
  1109. }
  1110. insert_work(cwq, work, worklist, work_flags);
  1111. spin_unlock(&gcwq->lock);
  1112. }
  1113. /**
  1114. * queue_work_on - queue work on specific cpu
  1115. * @cpu: CPU number to execute work on
  1116. * @wq: workqueue to use
  1117. * @work: work to queue
  1118. *
  1119. * Returns %false if @work was already on a queue, %true otherwise.
  1120. *
  1121. * We queue the work to a specific CPU, the caller must ensure it
  1122. * can't go away.
  1123. */
  1124. bool queue_work_on(int cpu, struct workqueue_struct *wq,
  1125. struct work_struct *work)
  1126. {
  1127. bool ret = false;
  1128. unsigned long flags;
  1129. local_irq_save(flags);
  1130. if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
  1131. __queue_work(cpu, wq, work);
  1132. ret = true;
  1133. }
  1134. local_irq_restore(flags);
  1135. return ret;
  1136. }
  1137. EXPORT_SYMBOL_GPL(queue_work_on);
  1138. /**
  1139. * queue_work - queue work on a workqueue
  1140. * @wq: workqueue to use
  1141. * @work: work to queue
  1142. *
  1143. * Returns %false if @work was already on a queue, %true otherwise.
  1144. *
  1145. * We queue the work to the CPU on which it was submitted, but if the CPU dies
  1146. * it can be processed by another CPU.
  1147. */
  1148. bool queue_work(struct workqueue_struct *wq, struct work_struct *work)
  1149. {
  1150. return queue_work_on(WORK_CPU_UNBOUND, wq, work);
  1151. }
  1152. EXPORT_SYMBOL_GPL(queue_work);
  1153. void delayed_work_timer_fn(unsigned long __data)
  1154. {
  1155. struct delayed_work *dwork = (struct delayed_work *)__data;
  1156. struct cpu_workqueue_struct *cwq = get_work_cwq(&dwork->work);
  1157. local_irq_disable();
  1158. __queue_work(dwork->cpu, cwq->wq, &dwork->work);
  1159. local_irq_enable();
  1160. }
  1161. EXPORT_SYMBOL_GPL(delayed_work_timer_fn);
  1162. static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
  1163. struct delayed_work *dwork, unsigned long delay)
  1164. {
  1165. struct timer_list *timer = &dwork->timer;
  1166. struct work_struct *work = &dwork->work;
  1167. unsigned int lcpu;
  1168. WARN_ON_ONCE(timer->function != delayed_work_timer_fn ||
  1169. timer->data != (unsigned long)dwork);
  1170. BUG_ON(timer_pending(timer));
  1171. BUG_ON(!list_empty(&work->entry));
  1172. timer_stats_timer_set_start_info(&dwork->timer);
  1173. /*
  1174. * This stores cwq for the moment, for the timer_fn. Note that the
  1175. * work's gcwq is preserved to allow reentrance detection for
  1176. * delayed works.
  1177. */
  1178. if (!(wq->flags & WQ_UNBOUND)) {
  1179. struct global_cwq *gcwq = get_work_gcwq(work);
  1180. if (gcwq && gcwq->cpu != WORK_CPU_UNBOUND)
  1181. lcpu = gcwq->cpu;
  1182. else
  1183. lcpu = raw_smp_processor_id();
  1184. } else {
  1185. lcpu = WORK_CPU_UNBOUND;
  1186. }
  1187. set_work_cwq(work, get_cwq(lcpu, wq), 0);
  1188. dwork->cpu = cpu;
  1189. timer->expires = jiffies + delay;
  1190. if (unlikely(cpu != WORK_CPU_UNBOUND))
  1191. add_timer_on(timer, cpu);
  1192. else
  1193. add_timer(timer);
  1194. }
  1195. /**
  1196. * queue_delayed_work_on - queue work on specific CPU after delay
  1197. * @cpu: CPU number to execute work on
  1198. * @wq: workqueue to use
  1199. * @dwork: work to queue
  1200. * @delay: number of jiffies to wait before queueing
  1201. *
  1202. * Returns %false if @work was already on a queue, %true otherwise. If
  1203. * @delay is zero and @dwork is idle, it will be scheduled for immediate
  1204. * execution.
  1205. */
  1206. bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
  1207. struct delayed_work *dwork, unsigned long delay)
  1208. {
  1209. struct work_struct *work = &dwork->work;
  1210. bool ret = false;
  1211. unsigned long flags;
  1212. if (!delay)
  1213. return queue_work_on(cpu, wq, &dwork->work);
  1214. /* read the comment in __queue_work() */
  1215. local_irq_save(flags);
  1216. if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
  1217. __queue_delayed_work(cpu, wq, dwork, delay);
  1218. ret = true;
  1219. }
  1220. local_irq_restore(flags);
  1221. return ret;
  1222. }
  1223. EXPORT_SYMBOL_GPL(queue_delayed_work_on);
  1224. /**
  1225. * queue_delayed_work - queue work on a workqueue after delay
  1226. * @wq: workqueue to use
  1227. * @dwork: delayable work to queue
  1228. * @delay: number of jiffies to wait before queueing
  1229. *
  1230. * Equivalent to queue_delayed_work_on() but tries to use the local CPU.
  1231. */
  1232. bool queue_delayed_work(struct workqueue_struct *wq,
  1233. struct delayed_work *dwork, unsigned long delay)
  1234. {
  1235. return queue_delayed_work_on(WORK_CPU_UNBOUND, wq, dwork, delay);
  1236. }
  1237. EXPORT_SYMBOL_GPL(queue_delayed_work);
  1238. /**
  1239. * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
  1240. * @cpu: CPU number to execute work on
  1241. * @wq: workqueue to use
  1242. * @dwork: work to queue
  1243. * @delay: number of jiffies to wait before queueing
  1244. *
  1245. * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
  1246. * modify @dwork's timer so that it expires after @delay. If @delay is
  1247. * zero, @work is guaranteed to be scheduled immediately regardless of its
  1248. * current state.
  1249. *
  1250. * Returns %false if @dwork was idle and queued, %true if @dwork was
  1251. * pending and its timer was modified.
  1252. *
  1253. * This function is safe to call from any context other than IRQ handler.
  1254. * See try_to_grab_pending() for details.
  1255. */
  1256. bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
  1257. struct delayed_work *dwork, unsigned long delay)
  1258. {
  1259. unsigned long flags;
  1260. int ret;
  1261. do {
  1262. ret = try_to_grab_pending(&dwork->work, true, &flags);
  1263. } while (unlikely(ret == -EAGAIN));
  1264. if (likely(ret >= 0)) {
  1265. __queue_delayed_work(cpu, wq, dwork, delay);
  1266. local_irq_restore(flags);
  1267. }
  1268. /* -ENOENT from try_to_grab_pending() becomes %true */
  1269. return ret;
  1270. }
  1271. EXPORT_SYMBOL_GPL(mod_delayed_work_on);
  1272. /**
  1273. * mod_delayed_work - modify delay of or queue a delayed work
  1274. * @wq: workqueue to use
  1275. * @dwork: work to queue
  1276. * @delay: number of jiffies to wait before queueing
  1277. *
  1278. * mod_delayed_work_on() on local CPU.
  1279. */
  1280. bool mod_delayed_work(struct workqueue_struct *wq, struct delayed_work *dwork,
  1281. unsigned long delay)
  1282. {
  1283. return mod_delayed_work_on(WORK_CPU_UNBOUND, wq, dwork, delay);
  1284. }
  1285. EXPORT_SYMBOL_GPL(mod_delayed_work);
  1286. /**
  1287. * worker_enter_idle - enter idle state
  1288. * @worker: worker which is entering idle state
  1289. *
  1290. * @worker is entering idle state. Update stats and idle timer if
  1291. * necessary.
  1292. *
  1293. * LOCKING:
  1294. * spin_lock_irq(gcwq->lock).
  1295. */
  1296. static void worker_enter_idle(struct worker *worker)
  1297. {
  1298. struct worker_pool *pool = worker->pool;
  1299. struct global_cwq *gcwq = pool->gcwq;
  1300. BUG_ON(worker->flags & WORKER_IDLE);
  1301. BUG_ON(!list_empty(&worker->entry) &&
  1302. (worker->hentry.next || worker->hentry.pprev));
  1303. /* can't use worker_set_flags(), also called from start_worker() */
  1304. worker->flags |= WORKER_IDLE;
  1305. pool->nr_idle++;
  1306. worker->last_active = jiffies;
  1307. /* idle_list is LIFO */
  1308. list_add(&worker->entry, &pool->idle_list);
  1309. if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
  1310. mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
  1311. /*
  1312. * Sanity check nr_running. Because gcwq_unbind_fn() releases
  1313. * gcwq->lock between setting %WORKER_UNBOUND and zapping
  1314. * nr_running, the warning may trigger spuriously. Check iff
  1315. * unbind is not in progress.
  1316. */
  1317. WARN_ON_ONCE(!(gcwq->flags & GCWQ_DISASSOCIATED) &&
  1318. pool->nr_workers == pool->nr_idle &&
  1319. atomic_read(get_pool_nr_running(pool)));
  1320. }
  1321. /**
  1322. * worker_leave_idle - leave idle state
  1323. * @worker: worker which is leaving idle state
  1324. *
  1325. * @worker is leaving idle state. Update stats.
  1326. *
  1327. * LOCKING:
  1328. * spin_lock_irq(gcwq->lock).
  1329. */
  1330. static void worker_leave_idle(struct worker *worker)
  1331. {
  1332. struct worker_pool *pool = worker->pool;
  1333. BUG_ON(!(worker->flags & WORKER_IDLE));
  1334. worker_clr_flags(worker, WORKER_IDLE);
  1335. pool->nr_idle--;
  1336. list_del_init(&worker->entry);
  1337. }
  1338. /**
  1339. * worker_maybe_bind_and_lock - bind worker to its cpu if possible and lock gcwq
  1340. * @worker: self
  1341. *
  1342. * Works which are scheduled while the cpu is online must at least be
  1343. * scheduled to a worker which is bound to the cpu so that if they are
  1344. * flushed from cpu callbacks while cpu is going down, they are
  1345. * guaranteed to execute on the cpu.
  1346. *
  1347. * This function is to be used by rogue workers and rescuers to bind
  1348. * themselves to the target cpu and may race with cpu going down or
  1349. * coming online. kthread_bind() can't be used because it may put the
  1350. * worker to already dead cpu and set_cpus_allowed_ptr() can't be used
  1351. * verbatim as it's best effort and blocking and gcwq may be
  1352. * [dis]associated in the meantime.
  1353. *
  1354. * This function tries set_cpus_allowed() and locks gcwq and verifies the
  1355. * binding against %GCWQ_DISASSOCIATED which is set during
  1356. * %CPU_DOWN_PREPARE and cleared during %CPU_ONLINE, so if the worker
  1357. * enters idle state or fetches works without dropping lock, it can
  1358. * guarantee the scheduling requirement described in the first paragraph.
  1359. *
  1360. * CONTEXT:
  1361. * Might sleep. Called without any lock but returns with gcwq->lock
  1362. * held.
  1363. *
  1364. * RETURNS:
  1365. * %true if the associated gcwq is online (@worker is successfully
  1366. * bound), %false if offline.
  1367. */
  1368. static bool worker_maybe_bind_and_lock(struct worker *worker)
  1369. __acquires(&gcwq->lock)
  1370. {
  1371. struct global_cwq *gcwq = worker->pool->gcwq;
  1372. struct task_struct *task = worker->task;
  1373. while (true) {
  1374. /*
  1375. * The following call may fail, succeed or succeed
  1376. * without actually migrating the task to the cpu if
  1377. * it races with cpu hotunplug operation. Verify
  1378. * against GCWQ_DISASSOCIATED.
  1379. */
  1380. if (!(gcwq->flags & GCWQ_DISASSOCIATED))
  1381. set_cpus_allowed_ptr(task, get_cpu_mask(gcwq->cpu));
  1382. spin_lock_irq(&gcwq->lock);
  1383. if (gcwq->flags & GCWQ_DISASSOCIATED)
  1384. return false;
  1385. if (task_cpu(task) == gcwq->cpu &&
  1386. cpumask_equal(&current->cpus_allowed,
  1387. get_cpu_mask(gcwq->cpu)))
  1388. return true;
  1389. spin_unlock_irq(&gcwq->lock);
  1390. /*
  1391. * We've raced with CPU hot[un]plug. Give it a breather
  1392. * and retry migration. cond_resched() is required here;
  1393. * otherwise, we might deadlock against cpu_stop trying to
  1394. * bring down the CPU on non-preemptive kernel.
  1395. */
  1396. cpu_relax();
  1397. cond_resched();
  1398. }
  1399. }
  1400. struct idle_rebind {
  1401. int cnt; /* # workers to be rebound */
  1402. struct completion done; /* all workers rebound */
  1403. };
  1404. /*
  1405. * Rebind an idle @worker to its CPU. During CPU onlining, this has to
  1406. * happen synchronously for idle workers. worker_thread() will test
  1407. * %WORKER_REBIND before leaving idle and call this function.
  1408. */
  1409. static void idle_worker_rebind(struct worker *worker)
  1410. {
  1411. struct global_cwq *gcwq = worker->pool->gcwq;
  1412. /* CPU must be online at this point */
  1413. WARN_ON(!worker_maybe_bind_and_lock(worker));
  1414. if (!--worker->idle_rebind->cnt)
  1415. complete(&worker->idle_rebind->done);
  1416. spin_unlock_irq(&worker->pool->gcwq->lock);
  1417. /* we did our part, wait for rebind_workers() to finish up */
  1418. wait_event(gcwq->rebind_hold, !(worker->flags & WORKER_REBIND));
  1419. }
  1420. /*
  1421. * Function for @worker->rebind.work used to rebind unbound busy workers to
  1422. * the associated cpu which is coming back online. This is scheduled by
  1423. * cpu up but can race with other cpu hotplug operations and may be
  1424. * executed twice without intervening cpu down.
  1425. */
  1426. static void busy_worker_rebind_fn(struct work_struct *work)
  1427. {
  1428. struct worker *worker = container_of(work, struct worker, rebind_work);
  1429. struct global_cwq *gcwq = worker->pool->gcwq;
  1430. if (worker_maybe_bind_and_lock(worker))
  1431. worker_clr_flags(worker, WORKER_REBIND);
  1432. spin_unlock_irq(&gcwq->lock);
  1433. }
  1434. /**
  1435. * rebind_workers - rebind all workers of a gcwq to the associated CPU
  1436. * @gcwq: gcwq of interest
  1437. *
  1438. * @gcwq->cpu is coming online. Rebind all workers to the CPU. Rebinding
  1439. * is different for idle and busy ones.
  1440. *
  1441. * The idle ones should be rebound synchronously and idle rebinding should
  1442. * be complete before any worker starts executing work items with
  1443. * concurrency management enabled; otherwise, scheduler may oops trying to
  1444. * wake up non-local idle worker from wq_worker_sleeping().
  1445. *
  1446. * This is achieved by repeatedly requesting rebinding until all idle
  1447. * workers are known to have been rebound under @gcwq->lock and holding all
  1448. * idle workers from becoming busy until idle rebinding is complete.
  1449. *
  1450. * Once idle workers are rebound, busy workers can be rebound as they
  1451. * finish executing their current work items. Queueing the rebind work at
  1452. * the head of their scheduled lists is enough. Note that nr_running will
  1453. * be properbly bumped as busy workers rebind.
  1454. *
  1455. * On return, all workers are guaranteed to either be bound or have rebind
  1456. * work item scheduled.
  1457. */
  1458. static void rebind_workers(struct global_cwq *gcwq)
  1459. __releases(&gcwq->lock) __acquires(&gcwq->lock)
  1460. {
  1461. struct idle_rebind idle_rebind;
  1462. struct worker_pool *pool;
  1463. struct worker *worker;
  1464. struct hlist_node *pos;
  1465. int i;
  1466. lockdep_assert_held(&gcwq->lock);
  1467. for_each_worker_pool(pool, gcwq)
  1468. lockdep_assert_held(&pool->manager_mutex);
  1469. /*
  1470. * Rebind idle workers. Interlocked both ways. We wait for
  1471. * workers to rebind via @idle_rebind.done. Workers will wait for
  1472. * us to finish up by watching %WORKER_REBIND.
  1473. */
  1474. init_completion(&idle_rebind.done);
  1475. retry:
  1476. idle_rebind.cnt = 1;
  1477. INIT_COMPLETION(idle_rebind.done);
  1478. /* set REBIND and kick idle ones, we'll wait for these later */
  1479. for_each_worker_pool(pool, gcwq) {
  1480. list_for_each_entry(worker, &pool->idle_list, entry) {
  1481. if (worker->flags & WORKER_REBIND)
  1482. continue;
  1483. /* morph UNBOUND to REBIND */
  1484. worker->flags &= ~WORKER_UNBOUND;
  1485. worker->flags |= WORKER_REBIND;
  1486. idle_rebind.cnt++;
  1487. worker->idle_rebind = &idle_rebind;
  1488. /* worker_thread() will call idle_worker_rebind() */
  1489. wake_up_process(worker->task);
  1490. }
  1491. }
  1492. if (--idle_rebind.cnt) {
  1493. spin_unlock_irq(&gcwq->lock);
  1494. wait_for_completion(&idle_rebind.done);
  1495. spin_lock_irq(&gcwq->lock);
  1496. /* busy ones might have become idle while waiting, retry */
  1497. goto retry;
  1498. }
  1499. /*
  1500. * All idle workers are rebound and waiting for %WORKER_REBIND to
  1501. * be cleared inside idle_worker_rebind(). Clear and release.
  1502. * Clearing %WORKER_REBIND from this foreign context is safe
  1503. * because these workers are still guaranteed to be idle.
  1504. */
  1505. for_each_worker_pool(pool, gcwq)
  1506. list_for_each_entry(worker, &pool->idle_list, entry)
  1507. worker->flags &= ~WORKER_REBIND;
  1508. wake_up_all(&gcwq->rebind_hold);
  1509. /* rebind busy workers */
  1510. for_each_busy_worker(worker, i, pos, gcwq) {
  1511. struct work_struct *rebind_work = &worker->rebind_work;
  1512. /* morph UNBOUND to REBIND */
  1513. worker->flags &= ~WORKER_UNBOUND;
  1514. worker->flags |= WORKER_REBIND;
  1515. if (test_and_set_bit(WORK_STRUCT_PENDING_BIT,
  1516. work_data_bits(rebind_work)))
  1517. continue;
  1518. /* wq doesn't matter, use the default one */
  1519. debug_work_activate(rebind_work);
  1520. insert_work(get_cwq(gcwq->cpu, system_wq), rebind_work,
  1521. worker->scheduled.next,
  1522. work_color_to_flags(WORK_NO_COLOR));
  1523. }
  1524. }
  1525. static struct worker *alloc_worker(void)
  1526. {
  1527. struct worker *worker;
  1528. worker = kzalloc(sizeof(*worker), GFP_KERNEL);
  1529. if (worker) {
  1530. INIT_LIST_HEAD(&worker->entry);
  1531. INIT_LIST_HEAD(&worker->scheduled);
  1532. INIT_WORK(&worker->rebind_work, busy_worker_rebind_fn);
  1533. /* on creation a worker is in !idle && prep state */
  1534. worker->flags = WORKER_PREP;
  1535. }
  1536. return worker;
  1537. }
  1538. /**
  1539. * create_worker - create a new workqueue worker
  1540. * @pool: pool the new worker will belong to
  1541. *
  1542. * Create a new worker which is bound to @pool. The returned worker
  1543. * can be started by calling start_worker() or destroyed using
  1544. * destroy_worker().
  1545. *
  1546. * CONTEXT:
  1547. * Might sleep. Does GFP_KERNEL allocations.
  1548. *
  1549. * RETURNS:
  1550. * Pointer to the newly created worker.
  1551. */
  1552. static struct worker *create_worker(struct worker_pool *pool)
  1553. {
  1554. struct global_cwq *gcwq = pool->gcwq;
  1555. const char *pri = worker_pool_pri(pool) ? "H" : "";
  1556. struct worker *worker = NULL;
  1557. int id = -1;
  1558. spin_lock_irq(&gcwq->lock);
  1559. while (ida_get_new(&pool->worker_ida, &id)) {
  1560. spin_unlock_irq(&gcwq->lock);
  1561. if (!ida_pre_get(&pool->worker_ida, GFP_KERNEL))
  1562. goto fail;
  1563. spin_lock_irq(&gcwq->lock);
  1564. }
  1565. spin_unlock_irq(&gcwq->lock);
  1566. worker = alloc_worker();
  1567. if (!worker)
  1568. goto fail;
  1569. worker->pool = pool;
  1570. worker->id = id;
  1571. if (gcwq->cpu != WORK_CPU_UNBOUND)
  1572. worker->task = kthread_create_on_node(worker_thread,
  1573. worker, cpu_to_node(gcwq->cpu),
  1574. "kworker/%u:%d%s", gcwq->cpu, id, pri);
  1575. else
  1576. worker->task = kthread_create(worker_thread, worker,
  1577. "kworker/u:%d%s", id, pri);
  1578. if (IS_ERR(worker->task))
  1579. goto fail;
  1580. if (worker_pool_pri(pool))
  1581. set_user_nice(worker->task, HIGHPRI_NICE_LEVEL);
  1582. /*
  1583. * Determine CPU binding of the new worker depending on
  1584. * %GCWQ_DISASSOCIATED. The caller is responsible for ensuring the
  1585. * flag remains stable across this function. See the comments
  1586. * above the flag definition for details.
  1587. *
  1588. * As an unbound worker may later become a regular one if CPU comes
  1589. * online, make sure every worker has %PF_THREAD_BOUND set.
  1590. */
  1591. if (!(gcwq->flags & GCWQ_DISASSOCIATED)) {
  1592. kthread_bind(worker->task, gcwq->cpu);
  1593. } else {
  1594. worker->task->flags |= PF_THREAD_BOUND;
  1595. worker->flags |= WORKER_UNBOUND;
  1596. }
  1597. return worker;
  1598. fail:
  1599. if (id >= 0) {
  1600. spin_lock_irq(&gcwq->lock);
  1601. ida_remove(&pool->worker_ida, id);
  1602. spin_unlock_irq(&gcwq->lock);
  1603. }
  1604. kfree(worker);
  1605. return NULL;
  1606. }
  1607. /**
  1608. * start_worker - start a newly created worker
  1609. * @worker: worker to start
  1610. *
  1611. * Make the gcwq aware of @worker and start it.
  1612. *
  1613. * CONTEXT:
  1614. * spin_lock_irq(gcwq->lock).
  1615. */
  1616. static void start_worker(struct worker *worker)
  1617. {
  1618. worker->flags |= WORKER_STARTED;
  1619. worker->pool->nr_workers++;
  1620. worker_enter_idle(worker);
  1621. wake_up_process(worker->task);
  1622. }
  1623. /**
  1624. * destroy_worker - destroy a workqueue worker
  1625. * @worker: worker to be destroyed
  1626. *
  1627. * Destroy @worker and adjust @gcwq stats accordingly.
  1628. *
  1629. * CONTEXT:
  1630. * spin_lock_irq(gcwq->lock) which is released and regrabbed.
  1631. */
  1632. static void destroy_worker(struct worker *worker)
  1633. {
  1634. struct worker_pool *pool = worker->pool;
  1635. struct global_cwq *gcwq = pool->gcwq;
  1636. int id = worker->id;
  1637. /* sanity check frenzy */
  1638. BUG_ON(worker->current_work);
  1639. BUG_ON(!list_empty(&worker->scheduled));
  1640. if (worker->flags & WORKER_STARTED)
  1641. pool->nr_workers--;
  1642. if (worker->flags & WORKER_IDLE)
  1643. pool->nr_idle--;
  1644. list_del_init(&worker->entry);
  1645. worker->flags |= WORKER_DIE;
  1646. spin_unlock_irq(&gcwq->lock);
  1647. kthread_stop(worker->task);
  1648. kfree(worker);
  1649. spin_lock_irq(&gcwq->lock);
  1650. ida_remove(&pool->worker_ida, id);
  1651. }
  1652. static void idle_worker_timeout(unsigned long __pool)
  1653. {
  1654. struct worker_pool *pool = (void *)__pool;
  1655. struct global_cwq *gcwq = pool->gcwq;
  1656. spin_lock_irq(&gcwq->lock);
  1657. if (too_many_workers(pool)) {
  1658. struct worker *worker;
  1659. unsigned long expires;
  1660. /* idle_list is kept in LIFO order, check the last one */
  1661. worker = list_entry(pool->idle_list.prev, struct worker, entry);
  1662. expires = worker->last_active + IDLE_WORKER_TIMEOUT;
  1663. if (time_before(jiffies, expires))
  1664. mod_timer(&pool->idle_timer, expires);
  1665. else {
  1666. /* it's been idle for too long, wake up manager */
  1667. pool->flags |= POOL_MANAGE_WORKERS;
  1668. wake_up_worker(pool);
  1669. }
  1670. }
  1671. spin_unlock_irq(&gcwq->lock);
  1672. }
  1673. static bool send_mayday(struct work_struct *work)
  1674. {
  1675. struct cpu_workqueue_struct *cwq = get_work_cwq(work);
  1676. struct workqueue_struct *wq = cwq->wq;
  1677. unsigned int cpu;
  1678. if (!(wq->flags & WQ_RESCUER))
  1679. return false;
  1680. /* mayday mayday mayday */
  1681. cpu = cwq->pool->gcwq->cpu;
  1682. /* WORK_CPU_UNBOUND can't be set in cpumask, use cpu 0 instead */
  1683. if (cpu == WORK_CPU_UNBOUND)
  1684. cpu = 0;
  1685. if (!mayday_test_and_set_cpu(cpu, wq->mayday_mask))
  1686. wake_up_process(wq->rescuer->task);
  1687. return true;
  1688. }
  1689. static void gcwq_mayday_timeout(unsigned long __pool)
  1690. {
  1691. struct worker_pool *pool = (void *)__pool;
  1692. struct global_cwq *gcwq = pool->gcwq;
  1693. struct work_struct *work;
  1694. spin_lock_irq(&gcwq->lock);
  1695. if (need_to_create_worker(pool)) {
  1696. /*
  1697. * We've been trying to create a new worker but
  1698. * haven't been successful. We might be hitting an
  1699. * allocation deadlock. Send distress signals to
  1700. * rescuers.
  1701. */
  1702. list_for_each_entry(work, &pool->worklist, entry)
  1703. send_mayday(work);
  1704. }
  1705. spin_unlock_irq(&gcwq->lock);
  1706. mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
  1707. }
  1708. /**
  1709. * maybe_create_worker - create a new worker if necessary
  1710. * @pool: pool to create a new worker for
  1711. *
  1712. * Create a new worker for @pool if necessary. @pool is guaranteed to
  1713. * have at least one idle worker on return from this function. If
  1714. * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
  1715. * sent to all rescuers with works scheduled on @pool to resolve
  1716. * possible allocation deadlock.
  1717. *
  1718. * On return, need_to_create_worker() is guaranteed to be false and
  1719. * may_start_working() true.
  1720. *
  1721. * LOCKING:
  1722. * spin_lock_irq(gcwq->lock) which may be released and regrabbed
  1723. * multiple times. Does GFP_KERNEL allocations. Called only from
  1724. * manager.
  1725. *
  1726. * RETURNS:
  1727. * false if no action was taken and gcwq->lock stayed locked, true
  1728. * otherwise.
  1729. */
  1730. static bool maybe_create_worker(struct worker_pool *pool)
  1731. __releases(&gcwq->lock)
  1732. __acquires(&gcwq->lock)
  1733. {
  1734. struct global_cwq *gcwq = pool->gcwq;
  1735. if (!need_to_create_worker(pool))
  1736. return false;
  1737. restart:
  1738. spin_unlock_irq(&gcwq->lock);
  1739. /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
  1740. mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
  1741. while (true) {
  1742. struct worker *worker;
  1743. worker = create_worker(pool);
  1744. if (worker) {
  1745. del_timer_sync(&pool->mayday_timer);
  1746. spin_lock_irq(&gcwq->lock);
  1747. start_worker(worker);
  1748. BUG_ON(need_to_create_worker(pool));
  1749. return true;
  1750. }
  1751. if (!need_to_create_worker(pool))
  1752. break;
  1753. __set_current_state(TASK_INTERRUPTIBLE);
  1754. schedule_timeout(CREATE_COOLDOWN);
  1755. if (!need_to_create_worker(pool))
  1756. break;
  1757. }
  1758. del_timer_sync(&pool->mayday_timer);
  1759. spin_lock_irq(&gcwq->lock);
  1760. if (need_to_create_worker(pool))
  1761. goto restart;
  1762. return true;
  1763. }
  1764. /**
  1765. * maybe_destroy_worker - destroy workers which have been idle for a while
  1766. * @pool: pool to destroy workers for
  1767. *
  1768. * Destroy @pool workers which have been idle for longer than
  1769. * IDLE_WORKER_TIMEOUT.
  1770. *
  1771. * LOCKING:
  1772. * spin_lock_irq(gcwq->lock) which may be released and regrabbed
  1773. * multiple times. Called only from manager.
  1774. *
  1775. * RETURNS:
  1776. * false if no action was taken and gcwq->lock stayed locked, true
  1777. * otherwise.
  1778. */
  1779. static bool maybe_destroy_workers(struct worker_pool *pool)
  1780. {
  1781. bool ret = false;
  1782. while (too_many_workers(pool)) {
  1783. struct worker *worker;
  1784. unsigned long expires;
  1785. worker = list_entry(pool->idle_list.prev, struct worker, entry);
  1786. expires = worker->last_active + IDLE_WORKER_TIMEOUT;
  1787. if (time_before(jiffies, expires)) {
  1788. mod_timer(&pool->idle_timer, expires);
  1789. break;
  1790. }
  1791. destroy_worker(worker);
  1792. ret = true;
  1793. }
  1794. return ret;
  1795. }
  1796. /**
  1797. * manage_workers - manage worker pool
  1798. * @worker: self
  1799. *
  1800. * Assume the manager role and manage gcwq worker pool @worker belongs
  1801. * to. At any given time, there can be only zero or one manager per
  1802. * gcwq. The exclusion is handled automatically by this function.
  1803. *
  1804. * The caller can safely start processing works on false return. On
  1805. * true return, it's guaranteed that need_to_create_worker() is false
  1806. * and may_start_working() is true.
  1807. *
  1808. * CONTEXT:
  1809. * spin_lock_irq(gcwq->lock) which may be released and regrabbed
  1810. * multiple times. Does GFP_KERNEL allocations.
  1811. *
  1812. * RETURNS:
  1813. * false if no action was taken and gcwq->lock stayed locked, true if
  1814. * some action was taken.
  1815. */
  1816. static bool manage_workers(struct worker *worker)
  1817. {
  1818. struct worker_pool *pool = worker->pool;
  1819. bool ret = false;
  1820. if (!mutex_trylock(&pool->manager_mutex))
  1821. return ret;
  1822. pool->flags &= ~POOL_MANAGE_WORKERS;
  1823. /*
  1824. * Destroy and then create so that may_start_working() is true
  1825. * on return.
  1826. */
  1827. ret |= maybe_destroy_workers(pool);
  1828. ret |= maybe_create_worker(pool);
  1829. mutex_unlock(&pool->manager_mutex);
  1830. return ret;
  1831. }
  1832. /**
  1833. * process_one_work - process single work
  1834. * @worker: self
  1835. * @work: work to process
  1836. *
  1837. * Process @work. This function contains all the logics necessary to
  1838. * process a single work including synchronization against and
  1839. * interaction with other workers on the same cpu, queueing and
  1840. * flushing. As long as context requirement is met, any worker can
  1841. * call this function to process a work.
  1842. *
  1843. * CONTEXT:
  1844. * spin_lock_irq(gcwq->lock) which is released and regrabbed.
  1845. */
  1846. static void process_one_work(struct worker *worker, struct work_struct *work)
  1847. __releases(&gcwq->lock)
  1848. __acquires(&gcwq->lock)
  1849. {
  1850. struct cpu_workqueue_struct *cwq = get_work_cwq(work);
  1851. struct worker_pool *pool = worker->pool;
  1852. struct global_cwq *gcwq = pool->gcwq;
  1853. struct hlist_head *bwh = busy_worker_head(gcwq, work);
  1854. bool cpu_intensive = cwq->wq->flags & WQ_CPU_INTENSIVE;
  1855. work_func_t f = work->func;
  1856. int work_color;
  1857. struct worker *collision;
  1858. #ifdef CONFIG_LOCKDEP
  1859. /*
  1860. * It is permissible to free the struct work_struct from
  1861. * inside the function that is called from it, this we need to
  1862. * take into account for lockdep too. To avoid bogus "held
  1863. * lock freed" warnings as well as problems when looking into
  1864. * work->lockdep_map, make a copy and use that here.
  1865. */
  1866. struct lockdep_map lockdep_map;
  1867. lockdep_copy_map(&lockdep_map, &work->lockdep_map);
  1868. #endif
  1869. /*
  1870. * Ensure we're on the correct CPU. DISASSOCIATED test is
  1871. * necessary to avoid spurious warnings from rescuers servicing the
  1872. * unbound or a disassociated gcwq.
  1873. */
  1874. WARN_ON_ONCE(!(worker->flags & (WORKER_UNBOUND | WORKER_REBIND)) &&
  1875. !(gcwq->flags & GCWQ_DISASSOCIATED) &&
  1876. raw_smp_processor_id() != gcwq->cpu);
  1877. /*
  1878. * A single work shouldn't be executed concurrently by
  1879. * multiple workers on a single cpu. Check whether anyone is
  1880. * already processing the work. If so, defer the work to the
  1881. * currently executing one.
  1882. */
  1883. collision = __find_worker_executing_work(gcwq, bwh, work);
  1884. if (unlikely(collision)) {
  1885. move_linked_works(work, &collision->scheduled, NULL);
  1886. return;
  1887. }
  1888. /* claim and dequeue */
  1889. debug_work_deactivate(work);
  1890. hlist_add_head(&worker->hentry, bwh);
  1891. worker->current_work = work;
  1892. worker->current_cwq = cwq;
  1893. work_color = get_work_color(work);
  1894. list_del_init(&work->entry);
  1895. /*
  1896. * CPU intensive works don't participate in concurrency
  1897. * management. They're the scheduler's responsibility.
  1898. */
  1899. if (unlikely(cpu_intensive))
  1900. worker_set_flags(worker, WORKER_CPU_INTENSIVE, true);
  1901. /*
  1902. * Unbound gcwq isn't concurrency managed and work items should be
  1903. * executed ASAP. Wake up another worker if necessary.
  1904. */
  1905. if ((worker->flags & WORKER_UNBOUND) && need_more_worker(pool))
  1906. wake_up_worker(pool);
  1907. /*
  1908. * Record the last CPU and clear PENDING which should be the last
  1909. * update to @work. Also, do this inside @gcwq->lock so that
  1910. * PENDING and queued state changes happen together while IRQ is
  1911. * disabled.
  1912. */
  1913. set_work_cpu_and_clear_pending(work, gcwq->cpu);
  1914. spin_unlock_irq(&gcwq->lock);
  1915. lock_map_acquire_read(&cwq->wq->lockdep_map);
  1916. lock_map_acquire(&lockdep_map);
  1917. trace_workqueue_execute_start(work);
  1918. f(work);
  1919. /*
  1920. * While we must be careful to not use "work" after this, the trace
  1921. * point will only record its address.
  1922. */
  1923. trace_workqueue_execute_end(work);
  1924. lock_map_release(&lockdep_map);
  1925. lock_map_release(&cwq->wq->lockdep_map);
  1926. if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
  1927. printk(KERN_ERR "BUG: workqueue leaked lock or atomic: "
  1928. "%s/0x%08x/%d\n",
  1929. current->comm, preempt_count(), task_pid_nr(current));
  1930. printk(KERN_ERR " last function: ");
  1931. print_symbol("%s\n", (unsigned long)f);
  1932. debug_show_held_locks(current);
  1933. dump_stack();
  1934. }
  1935. spin_lock_irq(&gcwq->lock);
  1936. /* clear cpu intensive status */
  1937. if (unlikely(cpu_intensive))
  1938. worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
  1939. /* we're done with it, release */
  1940. hlist_del_init(&worker->hentry);
  1941. worker->current_work = NULL;
  1942. worker->current_cwq = NULL;
  1943. cwq_dec_nr_in_flight(cwq, work_color, false);
  1944. }
  1945. /**
  1946. * process_scheduled_works - process scheduled works
  1947. * @worker: self
  1948. *
  1949. * Process all scheduled works. Please note that the scheduled list
  1950. * may change while processing a work, so this function repeatedly
  1951. * fetches a work from the top and executes it.
  1952. *
  1953. * CONTEXT:
  1954. * spin_lock_irq(gcwq->lock) which may be released and regrabbed
  1955. * multiple times.
  1956. */
  1957. static void process_scheduled_works(struct worker *worker)
  1958. {
  1959. while (!list_empty(&worker->scheduled)) {
  1960. struct work_struct *work = list_first_entry(&worker->scheduled,
  1961. struct work_struct, entry);
  1962. process_one_work(worker, work);
  1963. }
  1964. }
  1965. /**
  1966. * worker_thread - the worker thread function
  1967. * @__worker: self
  1968. *
  1969. * The gcwq worker thread function. There's a single dynamic pool of
  1970. * these per each cpu. These workers process all works regardless of
  1971. * their specific target workqueue. The only exception is works which
  1972. * belong to workqueues with a rescuer which will be explained in
  1973. * rescuer_thread().
  1974. */
  1975. static int worker_thread(void *__worker)
  1976. {
  1977. struct worker *worker = __worker;
  1978. struct worker_pool *pool = worker->pool;
  1979. struct global_cwq *gcwq = pool->gcwq;
  1980. /* tell the scheduler that this is a workqueue worker */
  1981. worker->task->flags |= PF_WQ_WORKER;
  1982. woke_up:
  1983. spin_lock_irq(&gcwq->lock);
  1984. /*
  1985. * DIE can be set only while idle and REBIND set while busy has
  1986. * @worker->rebind_work scheduled. Checking here is enough.
  1987. */
  1988. if (unlikely(worker->flags & (WORKER_REBIND | WORKER_DIE))) {
  1989. spin_unlock_irq(&gcwq->lock);
  1990. if (worker->flags & WORKER_DIE) {
  1991. worker->task->flags &= ~PF_WQ_WORKER;
  1992. return 0;
  1993. }
  1994. idle_worker_rebind(worker);
  1995. goto woke_up;
  1996. }
  1997. worker_leave_idle(worker);
  1998. recheck:
  1999. /* no more worker necessary? */
  2000. if (!need_more_worker(pool))
  2001. goto sleep;
  2002. /* do we need to manage? */
  2003. if (unlikely(!may_start_working(pool)) && manage_workers(worker))
  2004. goto recheck;
  2005. /*
  2006. * ->scheduled list can only be filled while a worker is
  2007. * preparing to process a work or actually processing it.
  2008. * Make sure nobody diddled with it while I was sleeping.
  2009. */
  2010. BUG_ON(!list_empty(&worker->scheduled));
  2011. /*
  2012. * When control reaches this point, we're guaranteed to have
  2013. * at least one idle worker or that someone else has already
  2014. * assumed the manager role.
  2015. */
  2016. worker_clr_flags(worker, WORKER_PREP);
  2017. do {
  2018. struct work_struct *work =
  2019. list_first_entry(&pool->worklist,
  2020. struct work_struct, entry);
  2021. if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
  2022. /* optimization path, not strictly necessary */
  2023. process_one_work(worker, work);
  2024. if (unlikely(!list_empty(&worker->scheduled)))
  2025. process_scheduled_works(worker);
  2026. } else {
  2027. move_linked_works(work, &worker->scheduled, NULL);
  2028. process_scheduled_works(worker);
  2029. }
  2030. } while (keep_working(pool));
  2031. worker_set_flags(worker, WORKER_PREP, false);
  2032. sleep:
  2033. if (unlikely(need_to_manage_workers(pool)) && manage_workers(worker))
  2034. goto recheck;
  2035. /*
  2036. * gcwq->lock is held and there's no work to process and no
  2037. * need to manage, sleep. Workers are woken up only while
  2038. * holding gcwq->lock or from local cpu, so setting the
  2039. * current state before releasing gcwq->lock is enough to
  2040. * prevent losing any event.
  2041. */
  2042. worker_enter_idle(worker);
  2043. __set_current_state(TASK_INTERRUPTIBLE);
  2044. spin_unlock_irq(&gcwq->lock);
  2045. schedule();
  2046. goto woke_up;
  2047. }
  2048. /**
  2049. * rescuer_thread - the rescuer thread function
  2050. * @__wq: the associated workqueue
  2051. *
  2052. * Workqueue rescuer thread function. There's one rescuer for each
  2053. * workqueue which has WQ_RESCUER set.
  2054. *
  2055. * Regular work processing on a gcwq may block trying to create a new
  2056. * worker which uses GFP_KERNEL allocation which has slight chance of
  2057. * developing into deadlock if some works currently on the same queue
  2058. * need to be processed to satisfy the GFP_KERNEL allocation. This is
  2059. * the problem rescuer solves.
  2060. *
  2061. * When such condition is possible, the gcwq summons rescuers of all
  2062. * workqueues which have works queued on the gcwq and let them process
  2063. * those works so that forward progress can be guaranteed.
  2064. *
  2065. * This should happen rarely.
  2066. */
  2067. static int rescuer_thread(void *__wq)
  2068. {
  2069. struct workqueue_struct *wq = __wq;
  2070. struct worker *rescuer = wq->rescuer;
  2071. struct list_head *scheduled = &rescuer->scheduled;
  2072. bool is_unbound = wq->flags & WQ_UNBOUND;
  2073. unsigned int cpu;
  2074. set_user_nice(current, RESCUER_NICE_LEVEL);
  2075. repeat:
  2076. set_current_state(TASK_INTERRUPTIBLE);
  2077. if (kthread_should_stop())
  2078. return 0;
  2079. /*
  2080. * See whether any cpu is asking for help. Unbounded
  2081. * workqueues use cpu 0 in mayday_mask for CPU_UNBOUND.
  2082. */
  2083. for_each_mayday_cpu(cpu, wq->mayday_mask) {
  2084. unsigned int tcpu = is_unbound ? WORK_CPU_UNBOUND : cpu;
  2085. struct cpu_workqueue_struct *cwq = get_cwq(tcpu, wq);
  2086. struct worker_pool *pool = cwq->pool;
  2087. struct global_cwq *gcwq = pool->gcwq;
  2088. struct work_struct *work, *n;
  2089. __set_current_state(TASK_RUNNING);
  2090. mayday_clear_cpu(cpu, wq->mayday_mask);
  2091. /* migrate to the target cpu if possible */
  2092. rescuer->pool = pool;
  2093. worker_maybe_bind_and_lock(rescuer);
  2094. /*
  2095. * Slurp in all works issued via this workqueue and
  2096. * process'em.
  2097. */
  2098. BUG_ON(!list_empty(&rescuer->scheduled));
  2099. list_for_each_entry_safe(work, n, &pool->worklist, entry)
  2100. if (get_work_cwq(work) == cwq)
  2101. move_linked_works(work, scheduled, &n);
  2102. process_scheduled_works(rescuer);
  2103. /*
  2104. * Leave this gcwq. If keep_working() is %true, notify a
  2105. * regular worker; otherwise, we end up with 0 concurrency
  2106. * and stalling the execution.
  2107. */
  2108. if (keep_working(pool))
  2109. wake_up_worker(pool);
  2110. spin_unlock_irq(&gcwq->lock);
  2111. }
  2112. schedule();
  2113. goto repeat;
  2114. }
  2115. struct wq_barrier {
  2116. struct work_struct work;
  2117. struct completion done;
  2118. };
  2119. static void wq_barrier_func(struct work_struct *work)
  2120. {
  2121. struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
  2122. complete(&barr->done);
  2123. }
  2124. /**
  2125. * insert_wq_barrier - insert a barrier work
  2126. * @cwq: cwq to insert barrier into
  2127. * @barr: wq_barrier to insert
  2128. * @target: target work to attach @barr to
  2129. * @worker: worker currently executing @target, NULL if @target is not executing
  2130. *
  2131. * @barr is linked to @target such that @barr is completed only after
  2132. * @target finishes execution. Please note that the ordering
  2133. * guarantee is observed only with respect to @target and on the local
  2134. * cpu.
  2135. *
  2136. * Currently, a queued barrier can't be canceled. This is because
  2137. * try_to_grab_pending() can't determine whether the work to be
  2138. * grabbed is at the head of the queue and thus can't clear LINKED
  2139. * flag of the previous work while there must be a valid next work
  2140. * after a work with LINKED flag set.
  2141. *
  2142. * Note that when @worker is non-NULL, @target may be modified
  2143. * underneath us, so we can't reliably determine cwq from @target.
  2144. *
  2145. * CONTEXT:
  2146. * spin_lock_irq(gcwq->lock).
  2147. */
  2148. static void insert_wq_barrier(struct cpu_workqueue_struct *cwq,
  2149. struct wq_barrier *barr,
  2150. struct work_struct *target, struct worker *worker)
  2151. {
  2152. struct list_head *head;
  2153. unsigned int linked = 0;
  2154. /*
  2155. * debugobject calls are safe here even with gcwq->lock locked
  2156. * as we know for sure that this will not trigger any of the
  2157. * checks and call back into the fixup functions where we
  2158. * might deadlock.
  2159. */
  2160. INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
  2161. __set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
  2162. init_completion(&barr->done);
  2163. /*
  2164. * If @target is currently being executed, schedule the
  2165. * barrier to the worker; otherwise, put it after @target.
  2166. */
  2167. if (worker)
  2168. head = worker->scheduled.next;
  2169. else {
  2170. unsigned long *bits = work_data_bits(target);
  2171. head = target->entry.next;
  2172. /* there can already be other linked works, inherit and set */
  2173. linked = *bits & WORK_STRUCT_LINKED;
  2174. __set_bit(WORK_STRUCT_LINKED_BIT, bits);
  2175. }
  2176. debug_work_activate(&barr->work);
  2177. insert_work(cwq, &barr->work, head,
  2178. work_color_to_flags(WORK_NO_COLOR) | linked);
  2179. }
  2180. /**
  2181. * flush_workqueue_prep_cwqs - prepare cwqs for workqueue flushing
  2182. * @wq: workqueue being flushed
  2183. * @flush_color: new flush color, < 0 for no-op
  2184. * @work_color: new work color, < 0 for no-op
  2185. *
  2186. * Prepare cwqs for workqueue flushing.
  2187. *
  2188. * If @flush_color is non-negative, flush_color on all cwqs should be
  2189. * -1. If no cwq has in-flight commands at the specified color, all
  2190. * cwq->flush_color's stay at -1 and %false is returned. If any cwq
  2191. * has in flight commands, its cwq->flush_color is set to
  2192. * @flush_color, @wq->nr_cwqs_to_flush is updated accordingly, cwq
  2193. * wakeup logic is armed and %true is returned.
  2194. *
  2195. * The caller should have initialized @wq->first_flusher prior to
  2196. * calling this function with non-negative @flush_color. If
  2197. * @flush_color is negative, no flush color update is done and %false
  2198. * is returned.
  2199. *
  2200. * If @work_color is non-negative, all cwqs should have the same
  2201. * work_color which is previous to @work_color and all will be
  2202. * advanced to @work_color.
  2203. *
  2204. * CONTEXT:
  2205. * mutex_lock(wq->flush_mutex).
  2206. *
  2207. * RETURNS:
  2208. * %true if @flush_color >= 0 and there's something to flush. %false
  2209. * otherwise.
  2210. */
  2211. static bool flush_workqueue_prep_cwqs(struct workqueue_struct *wq,
  2212. int flush_color, int work_color)
  2213. {
  2214. bool wait = false;
  2215. unsigned int cpu;
  2216. if (flush_color >= 0) {
  2217. BUG_ON(atomic_read(&wq->nr_cwqs_to_flush));
  2218. atomic_set(&wq->nr_cwqs_to_flush, 1);
  2219. }
  2220. for_each_cwq_cpu(cpu, wq) {
  2221. struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
  2222. struct global_cwq *gcwq = cwq->pool->gcwq;
  2223. spin_lock_irq(&gcwq->lock);
  2224. if (flush_color >= 0) {
  2225. BUG_ON(cwq->flush_color != -1);
  2226. if (cwq->nr_in_flight[flush_color]) {
  2227. cwq->flush_color = flush_color;
  2228. atomic_inc(&wq->nr_cwqs_to_flush);
  2229. wait = true;
  2230. }
  2231. }
  2232. if (work_color >= 0) {
  2233. BUG_ON(work_color != work_next_color(cwq->work_color));
  2234. cwq->work_color = work_color;
  2235. }
  2236. spin_unlock_irq(&gcwq->lock);
  2237. }
  2238. if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_cwqs_to_flush))
  2239. complete(&wq->first_flusher->done);
  2240. return wait;
  2241. }
  2242. /**
  2243. * flush_workqueue - ensure that any scheduled work has run to completion.
  2244. * @wq: workqueue to flush
  2245. *
  2246. * Forces execution of the workqueue and blocks until its completion.
  2247. * This is typically used in driver shutdown handlers.
  2248. *
  2249. * We sleep until all works which were queued on entry have been handled,
  2250. * but we are not livelocked by new incoming ones.
  2251. */
  2252. void flush_workqueue(struct workqueue_struct *wq)
  2253. {
  2254. struct wq_flusher this_flusher = {
  2255. .list = LIST_HEAD_INIT(this_flusher.list),
  2256. .flush_color = -1,
  2257. .done = COMPLETION_INITIALIZER_ONSTACK(this_flusher.done),
  2258. };
  2259. int next_color;
  2260. lock_map_acquire(&wq->lockdep_map);
  2261. lock_map_release(&wq->lockdep_map);
  2262. mutex_lock(&wq->flush_mutex);
  2263. /*
  2264. * Start-to-wait phase
  2265. */
  2266. next_color = work_next_color(wq->work_color);
  2267. if (next_color != wq->flush_color) {
  2268. /*
  2269. * Color space is not full. The current work_color
  2270. * becomes our flush_color and work_color is advanced
  2271. * by one.
  2272. */
  2273. BUG_ON(!list_empty(&wq->flusher_overflow));
  2274. this_flusher.flush_color = wq->work_color;
  2275. wq->work_color = next_color;
  2276. if (!wq->first_flusher) {
  2277. /* no flush in progress, become the first flusher */
  2278. BUG_ON(wq->flush_color != this_flusher.flush_color);
  2279. wq->first_flusher = &this_flusher;
  2280. if (!flush_workqueue_prep_cwqs(wq, wq->flush_color,
  2281. wq->work_color)) {
  2282. /* nothing to flush, done */
  2283. wq->flush_color = next_color;
  2284. wq->first_flusher = NULL;
  2285. goto out_unlock;
  2286. }
  2287. } else {
  2288. /* wait in queue */
  2289. BUG_ON(wq->flush_color == this_flusher.flush_color);
  2290. list_add_tail(&this_flusher.list, &wq->flusher_queue);
  2291. flush_workqueue_prep_cwqs(wq, -1, wq->work_color);
  2292. }
  2293. } else {
  2294. /*
  2295. * Oops, color space is full, wait on overflow queue.
  2296. * The next flush completion will assign us
  2297. * flush_color and transfer to flusher_queue.
  2298. */
  2299. list_add_tail(&this_flusher.list, &wq->flusher_overflow);
  2300. }
  2301. mutex_unlock(&wq->flush_mutex);
  2302. wait_for_completion(&this_flusher.done);
  2303. /*
  2304. * Wake-up-and-cascade phase
  2305. *
  2306. * First flushers are responsible for cascading flushes and
  2307. * handling overflow. Non-first flushers can simply return.
  2308. */
  2309. if (wq->first_flusher != &this_flusher)
  2310. return;
  2311. mutex_lock(&wq->flush_mutex);
  2312. /* we might have raced, check again with mutex held */
  2313. if (wq->first_flusher != &this_flusher)
  2314. goto out_unlock;
  2315. wq->first_flusher = NULL;
  2316. BUG_ON(!list_empty(&this_flusher.list));
  2317. BUG_ON(wq->flush_color != this_flusher.flush_color);
  2318. while (true) {
  2319. struct wq_flusher *next, *tmp;
  2320. /* complete all the flushers sharing the current flush color */
  2321. list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
  2322. if (next->flush_color != wq->flush_color)
  2323. break;
  2324. list_del_init(&next->list);
  2325. complete(&next->done);
  2326. }
  2327. BUG_ON(!list_empty(&wq->flusher_overflow) &&
  2328. wq->flush_color != work_next_color(wq->work_color));
  2329. /* this flush_color is finished, advance by one */
  2330. wq->flush_color = work_next_color(wq->flush_color);
  2331. /* one color has been freed, handle overflow queue */
  2332. if (!list_empty(&wq->flusher_overflow)) {
  2333. /*
  2334. * Assign the same color to all overflowed
  2335. * flushers, advance work_color and append to
  2336. * flusher_queue. This is the start-to-wait
  2337. * phase for these overflowed flushers.
  2338. */
  2339. list_for_each_entry(tmp, &wq->flusher_overflow, list)
  2340. tmp->flush_color = wq->work_color;
  2341. wq->work_color = work_next_color(wq->work_color);
  2342. list_splice_tail_init(&wq->flusher_overflow,
  2343. &wq->flusher_queue);
  2344. flush_workqueue_prep_cwqs(wq, -1, wq->work_color);
  2345. }
  2346. if (list_empty(&wq->flusher_queue)) {
  2347. BUG_ON(wq->flush_color != wq->work_color);
  2348. break;
  2349. }
  2350. /*
  2351. * Need to flush more colors. Make the next flusher
  2352. * the new first flusher and arm cwqs.
  2353. */
  2354. BUG_ON(wq->flush_color == wq->work_color);
  2355. BUG_ON(wq->flush_color != next->flush_color);
  2356. list_del_init(&next->list);
  2357. wq->first_flusher = next;
  2358. if (flush_workqueue_prep_cwqs(wq, wq->flush_color, -1))
  2359. break;
  2360. /*
  2361. * Meh... this color is already done, clear first
  2362. * flusher and repeat cascading.
  2363. */
  2364. wq->first_flusher = NULL;
  2365. }
  2366. out_unlock:
  2367. mutex_unlock(&wq->flush_mutex);
  2368. }
  2369. EXPORT_SYMBOL_GPL(flush_workqueue);
  2370. /**
  2371. * drain_workqueue - drain a workqueue
  2372. * @wq: workqueue to drain
  2373. *
  2374. * Wait until the workqueue becomes empty. While draining is in progress,
  2375. * only chain queueing is allowed. IOW, only currently pending or running
  2376. * work items on @wq can queue further work items on it. @wq is flushed
  2377. * repeatedly until it becomes empty. The number of flushing is detemined
  2378. * by the depth of chaining and should be relatively short. Whine if it
  2379. * takes too long.
  2380. */
  2381. void drain_workqueue(struct workqueue_struct *wq)
  2382. {
  2383. unsigned int flush_cnt = 0;
  2384. unsigned int cpu;
  2385. /*
  2386. * __queue_work() needs to test whether there are drainers, is much
  2387. * hotter than drain_workqueue() and already looks at @wq->flags.
  2388. * Use WQ_DRAINING so that queue doesn't have to check nr_drainers.
  2389. */
  2390. spin_lock(&workqueue_lock);
  2391. if (!wq->nr_drainers++)
  2392. wq->flags |= WQ_DRAINING;
  2393. spin_unlock(&workqueue_lock);
  2394. reflush:
  2395. flush_workqueue(wq);
  2396. for_each_cwq_cpu(cpu, wq) {
  2397. struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
  2398. bool drained;
  2399. spin_lock_irq(&cwq->pool->gcwq->lock);
  2400. drained = !cwq->nr_active && list_empty(&cwq->delayed_works);
  2401. spin_unlock_irq(&cwq->pool->gcwq->lock);
  2402. if (drained)
  2403. continue;
  2404. if (++flush_cnt == 10 ||
  2405. (flush_cnt % 100 == 0 && flush_cnt <= 1000))
  2406. pr_warning("workqueue %s: flush on destruction isn't complete after %u tries\n",
  2407. wq->name, flush_cnt);
  2408. goto reflush;
  2409. }
  2410. spin_lock(&workqueue_lock);
  2411. if (!--wq->nr_drainers)
  2412. wq->flags &= ~WQ_DRAINING;
  2413. spin_unlock(&workqueue_lock);
  2414. }
  2415. EXPORT_SYMBOL_GPL(drain_workqueue);
  2416. static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr,
  2417. bool wait_executing)
  2418. {
  2419. struct worker *worker = NULL;
  2420. struct global_cwq *gcwq;
  2421. struct cpu_workqueue_struct *cwq;
  2422. might_sleep();
  2423. gcwq = get_work_gcwq(work);
  2424. if (!gcwq)
  2425. return false;
  2426. spin_lock_irq(&gcwq->lock);
  2427. if (!list_empty(&work->entry)) {
  2428. /*
  2429. * See the comment near try_to_grab_pending()->smp_rmb().
  2430. * If it was re-queued to a different gcwq under us, we
  2431. * are not going to wait.
  2432. */
  2433. smp_rmb();
  2434. cwq = get_work_cwq(work);
  2435. if (unlikely(!cwq || gcwq != cwq->pool->gcwq))
  2436. goto already_gone;
  2437. } else if (wait_executing) {
  2438. worker = find_worker_executing_work(gcwq, work);
  2439. if (!worker)
  2440. goto already_gone;
  2441. cwq = worker->current_cwq;
  2442. } else
  2443. goto already_gone;
  2444. insert_wq_barrier(cwq, barr, work, worker);
  2445. spin_unlock_irq(&gcwq->lock);
  2446. /*
  2447. * If @max_active is 1 or rescuer is in use, flushing another work
  2448. * item on the same workqueue may lead to deadlock. Make sure the
  2449. * flusher is not running on the same workqueue by verifying write
  2450. * access.
  2451. */
  2452. if (cwq->wq->saved_max_active == 1 || cwq->wq->flags & WQ_RESCUER)
  2453. lock_map_acquire(&cwq->wq->lockdep_map);
  2454. else
  2455. lock_map_acquire_read(&cwq->wq->lockdep_map);
  2456. lock_map_release(&cwq->wq->lockdep_map);
  2457. return true;
  2458. already_gone:
  2459. spin_unlock_irq(&gcwq->lock);
  2460. return false;
  2461. }
  2462. /**
  2463. * flush_work - wait for a work to finish executing the last queueing instance
  2464. * @work: the work to flush
  2465. *
  2466. * Wait until @work has finished execution. This function considers
  2467. * only the last queueing instance of @work. If @work has been
  2468. * enqueued across different CPUs on a non-reentrant workqueue or on
  2469. * multiple workqueues, @work might still be executing on return on
  2470. * some of the CPUs from earlier queueing.
  2471. *
  2472. * If @work was queued only on a non-reentrant, ordered or unbound
  2473. * workqueue, @work is guaranteed to be idle on return if it hasn't
  2474. * been requeued since flush started.
  2475. *
  2476. * RETURNS:
  2477. * %true if flush_work() waited for the work to finish execution,
  2478. * %false if it was already idle.
  2479. */
  2480. bool flush_work(struct work_struct *work)
  2481. {
  2482. struct wq_barrier barr;
  2483. lock_map_acquire(&work->lockdep_map);
  2484. lock_map_release(&work->lockdep_map);
  2485. if (start_flush_work(work, &barr, true)) {
  2486. wait_for_completion(&barr.done);
  2487. destroy_work_on_stack(&barr.work);
  2488. return true;
  2489. } else
  2490. return false;
  2491. }
  2492. EXPORT_SYMBOL_GPL(flush_work);
  2493. static bool wait_on_cpu_work(struct global_cwq *gcwq, struct work_struct *work)
  2494. {
  2495. struct wq_barrier barr;
  2496. struct worker *worker;
  2497. spin_lock_irq(&gcwq->lock);
  2498. worker = find_worker_executing_work(gcwq, work);
  2499. if (unlikely(worker))
  2500. insert_wq_barrier(worker->current_cwq, &barr, work, worker);
  2501. spin_unlock_irq(&gcwq->lock);
  2502. if (unlikely(worker)) {
  2503. wait_for_completion(&barr.done);
  2504. destroy_work_on_stack(&barr.work);
  2505. return true;
  2506. } else
  2507. return false;
  2508. }
  2509. static bool wait_on_work(struct work_struct *work)
  2510. {
  2511. bool ret = false;
  2512. int cpu;
  2513. might_sleep();
  2514. lock_map_acquire(&work->lockdep_map);
  2515. lock_map_release(&work->lockdep_map);
  2516. for_each_gcwq_cpu(cpu)
  2517. ret |= wait_on_cpu_work(get_gcwq(cpu), work);
  2518. return ret;
  2519. }
  2520. /**
  2521. * flush_work_sync - wait until a work has finished execution
  2522. * @work: the work to flush
  2523. *
  2524. * Wait until @work has finished execution. On return, it's
  2525. * guaranteed that all queueing instances of @work which happened
  2526. * before this function is called are finished. In other words, if
  2527. * @work hasn't been requeued since this function was called, @work is
  2528. * guaranteed to be idle on return.
  2529. *
  2530. * RETURNS:
  2531. * %true if flush_work_sync() waited for the work to finish execution,
  2532. * %false if it was already idle.
  2533. */
  2534. bool flush_work_sync(struct work_struct *work)
  2535. {
  2536. struct wq_barrier barr;
  2537. bool pending, waited;
  2538. /* we'll wait for executions separately, queue barr only if pending */
  2539. pending = start_flush_work(work, &barr, false);
  2540. /* wait for executions to finish */
  2541. waited = wait_on_work(work);
  2542. /* wait for the pending one */
  2543. if (pending) {
  2544. wait_for_completion(&barr.done);
  2545. destroy_work_on_stack(&barr.work);
  2546. }
  2547. return pending || waited;
  2548. }
  2549. EXPORT_SYMBOL_GPL(flush_work_sync);
  2550. static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
  2551. {
  2552. unsigned long flags;
  2553. int ret;
  2554. do {
  2555. ret = try_to_grab_pending(work, is_dwork, &flags);
  2556. /*
  2557. * If someone else is canceling, wait for the same event it
  2558. * would be waiting for before retrying.
  2559. */
  2560. if (unlikely(ret == -ENOENT))
  2561. wait_on_work(work);
  2562. } while (unlikely(ret < 0));
  2563. /* tell other tasks trying to grab @work to back off */
  2564. mark_work_canceling(work);
  2565. local_irq_restore(flags);
  2566. wait_on_work(work);
  2567. clear_work_data(work);
  2568. return ret;
  2569. }
  2570. /**
  2571. * cancel_work_sync - cancel a work and wait for it to finish
  2572. * @work: the work to cancel
  2573. *
  2574. * Cancel @work and wait for its execution to finish. This function
  2575. * can be used even if the work re-queues itself or migrates to
  2576. * another workqueue. On return from this function, @work is
  2577. * guaranteed to be not pending or executing on any CPU.
  2578. *
  2579. * cancel_work_sync(&delayed_work->work) must not be used for
  2580. * delayed_work's. Use cancel_delayed_work_sync() instead.
  2581. *
  2582. * The caller must ensure that the workqueue on which @work was last
  2583. * queued can't be destroyed before this function returns.
  2584. *
  2585. * RETURNS:
  2586. * %true if @work was pending, %false otherwise.
  2587. */
  2588. bool cancel_work_sync(struct work_struct *work)
  2589. {
  2590. return __cancel_work_timer(work, false);
  2591. }
  2592. EXPORT_SYMBOL_GPL(cancel_work_sync);
  2593. /**
  2594. * flush_delayed_work - wait for a dwork to finish executing the last queueing
  2595. * @dwork: the delayed work to flush
  2596. *
  2597. * Delayed timer is cancelled and the pending work is queued for
  2598. * immediate execution. Like flush_work(), this function only
  2599. * considers the last queueing instance of @dwork.
  2600. *
  2601. * RETURNS:
  2602. * %true if flush_work() waited for the work to finish execution,
  2603. * %false if it was already idle.
  2604. */
  2605. bool flush_delayed_work(struct delayed_work *dwork)
  2606. {
  2607. local_irq_disable();
  2608. if (del_timer_sync(&dwork->timer))
  2609. __queue_work(dwork->cpu,
  2610. get_work_cwq(&dwork->work)->wq, &dwork->work);
  2611. local_irq_enable();
  2612. return flush_work(&dwork->work);
  2613. }
  2614. EXPORT_SYMBOL(flush_delayed_work);
  2615. /**
  2616. * flush_delayed_work_sync - wait for a dwork to finish
  2617. * @dwork: the delayed work to flush
  2618. *
  2619. * Delayed timer is cancelled and the pending work is queued for
  2620. * execution immediately. Other than timer handling, its behavior
  2621. * is identical to flush_work_sync().
  2622. *
  2623. * RETURNS:
  2624. * %true if flush_work_sync() waited for the work to finish execution,
  2625. * %false if it was already idle.
  2626. */
  2627. bool flush_delayed_work_sync(struct delayed_work *dwork)
  2628. {
  2629. local_irq_disable();
  2630. if (del_timer_sync(&dwork->timer))
  2631. __queue_work(dwork->cpu,
  2632. get_work_cwq(&dwork->work)->wq, &dwork->work);
  2633. local_irq_enable();
  2634. return flush_work_sync(&dwork->work);
  2635. }
  2636. EXPORT_SYMBOL(flush_delayed_work_sync);
  2637. /**
  2638. * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
  2639. * @dwork: the delayed work cancel
  2640. *
  2641. * This is cancel_work_sync() for delayed works.
  2642. *
  2643. * RETURNS:
  2644. * %true if @dwork was pending, %false otherwise.
  2645. */
  2646. bool cancel_delayed_work_sync(struct delayed_work *dwork)
  2647. {
  2648. return __cancel_work_timer(&dwork->work, true);
  2649. }
  2650. EXPORT_SYMBOL(cancel_delayed_work_sync);
  2651. /**
  2652. * schedule_work_on - put work task on a specific cpu
  2653. * @cpu: cpu to put the work task on
  2654. * @work: job to be done
  2655. *
  2656. * This puts a job on a specific cpu
  2657. */
  2658. bool schedule_work_on(int cpu, struct work_struct *work)
  2659. {
  2660. return queue_work_on(cpu, system_wq, work);
  2661. }
  2662. EXPORT_SYMBOL(schedule_work_on);
  2663. /**
  2664. * schedule_work - put work task in global workqueue
  2665. * @work: job to be done
  2666. *
  2667. * Returns %false if @work was already on the kernel-global workqueue and
  2668. * %true otherwise.
  2669. *
  2670. * This puts a job in the kernel-global workqueue if it was not already
  2671. * queued and leaves it in the same position on the kernel-global
  2672. * workqueue otherwise.
  2673. */
  2674. bool schedule_work(struct work_struct *work)
  2675. {
  2676. return queue_work(system_wq, work);
  2677. }
  2678. EXPORT_SYMBOL(schedule_work);
  2679. /**
  2680. * schedule_delayed_work_on - queue work in global workqueue on CPU after delay
  2681. * @cpu: cpu to use
  2682. * @dwork: job to be done
  2683. * @delay: number of jiffies to wait
  2684. *
  2685. * After waiting for a given time this puts a job in the kernel-global
  2686. * workqueue on the specified CPU.
  2687. */
  2688. bool schedule_delayed_work_on(int cpu, struct delayed_work *dwork,
  2689. unsigned long delay)
  2690. {
  2691. return queue_delayed_work_on(cpu, system_wq, dwork, delay);
  2692. }
  2693. EXPORT_SYMBOL(schedule_delayed_work_on);
  2694. /**
  2695. * schedule_delayed_work - put work task in global workqueue after delay
  2696. * @dwork: job to be done
  2697. * @delay: number of jiffies to wait or 0 for immediate execution
  2698. *
  2699. * After waiting for a given time this puts a job in the kernel-global
  2700. * workqueue.
  2701. */
  2702. bool schedule_delayed_work(struct delayed_work *dwork, unsigned long delay)
  2703. {
  2704. return queue_delayed_work(system_wq, dwork, delay);
  2705. }
  2706. EXPORT_SYMBOL(schedule_delayed_work);
  2707. /**
  2708. * schedule_on_each_cpu - execute a function synchronously on each online CPU
  2709. * @func: the function to call
  2710. *
  2711. * schedule_on_each_cpu() executes @func on each online CPU using the
  2712. * system workqueue and blocks until all CPUs have completed.
  2713. * schedule_on_each_cpu() is very slow.
  2714. *
  2715. * RETURNS:
  2716. * 0 on success, -errno on failure.
  2717. */
  2718. int schedule_on_each_cpu(work_func_t func)
  2719. {
  2720. int cpu;
  2721. struct work_struct __percpu *works;
  2722. works = alloc_percpu(struct work_struct);
  2723. if (!works)
  2724. return -ENOMEM;
  2725. get_online_cpus();
  2726. for_each_online_cpu(cpu) {
  2727. struct work_struct *work = per_cpu_ptr(works, cpu);
  2728. INIT_WORK(work, func);
  2729. schedule_work_on(cpu, work);
  2730. }
  2731. for_each_online_cpu(cpu)
  2732. flush_work(per_cpu_ptr(works, cpu));
  2733. put_online_cpus();
  2734. free_percpu(works);
  2735. return 0;
  2736. }
  2737. /**
  2738. * flush_scheduled_work - ensure that any scheduled work has run to completion.
  2739. *
  2740. * Forces execution of the kernel-global workqueue and blocks until its
  2741. * completion.
  2742. *
  2743. * Think twice before calling this function! It's very easy to get into
  2744. * trouble if you don't take great care. Either of the following situations
  2745. * will lead to deadlock:
  2746. *
  2747. * One of the work items currently on the workqueue needs to acquire
  2748. * a lock held by your code or its caller.
  2749. *
  2750. * Your code is running in the context of a work routine.
  2751. *
  2752. * They will be detected by lockdep when they occur, but the first might not
  2753. * occur very often. It depends on what work items are on the workqueue and
  2754. * what locks they need, which you have no control over.
  2755. *
  2756. * In most situations flushing the entire workqueue is overkill; you merely
  2757. * need to know that a particular work item isn't queued and isn't running.
  2758. * In such cases you should use cancel_delayed_work_sync() or
  2759. * cancel_work_sync() instead.
  2760. */
  2761. void flush_scheduled_work(void)
  2762. {
  2763. flush_workqueue(system_wq);
  2764. }
  2765. EXPORT_SYMBOL(flush_scheduled_work);
  2766. /**
  2767. * execute_in_process_context - reliably execute the routine with user context
  2768. * @fn: the function to execute
  2769. * @ew: guaranteed storage for the execute work structure (must
  2770. * be available when the work executes)
  2771. *
  2772. * Executes the function immediately if process context is available,
  2773. * otherwise schedules the function for delayed execution.
  2774. *
  2775. * Returns: 0 - function was executed
  2776. * 1 - function was scheduled for execution
  2777. */
  2778. int execute_in_process_context(work_func_t fn, struct execute_work *ew)
  2779. {
  2780. if (!in_interrupt()) {
  2781. fn(&ew->work);
  2782. return 0;
  2783. }
  2784. INIT_WORK(&ew->work, fn);
  2785. schedule_work(&ew->work);
  2786. return 1;
  2787. }
  2788. EXPORT_SYMBOL_GPL(execute_in_process_context);
  2789. int keventd_up(void)
  2790. {
  2791. return system_wq != NULL;
  2792. }
  2793. static int alloc_cwqs(struct workqueue_struct *wq)
  2794. {
  2795. /*
  2796. * cwqs are forced aligned according to WORK_STRUCT_FLAG_BITS.
  2797. * Make sure that the alignment isn't lower than that of
  2798. * unsigned long long.
  2799. */
  2800. const size_t size = sizeof(struct cpu_workqueue_struct);
  2801. const size_t align = max_t(size_t, 1 << WORK_STRUCT_FLAG_BITS,
  2802. __alignof__(unsigned long long));
  2803. if (!(wq->flags & WQ_UNBOUND))
  2804. wq->cpu_wq.pcpu = __alloc_percpu(size, align);
  2805. else {
  2806. void *ptr;
  2807. /*
  2808. * Allocate enough room to align cwq and put an extra
  2809. * pointer at the end pointing back to the originally
  2810. * allocated pointer which will be used for free.
  2811. */
  2812. ptr = kzalloc(size + align + sizeof(void *), GFP_KERNEL);
  2813. if (ptr) {
  2814. wq->cpu_wq.single = PTR_ALIGN(ptr, align);
  2815. *(void **)(wq->cpu_wq.single + 1) = ptr;
  2816. }
  2817. }
  2818. /* just in case, make sure it's actually aligned */
  2819. BUG_ON(!IS_ALIGNED(wq->cpu_wq.v, align));
  2820. return wq->cpu_wq.v ? 0 : -ENOMEM;
  2821. }
  2822. static void free_cwqs(struct workqueue_struct *wq)
  2823. {
  2824. if (!(wq->flags & WQ_UNBOUND))
  2825. free_percpu(wq->cpu_wq.pcpu);
  2826. else if (wq->cpu_wq.single) {
  2827. /* the pointer to free is stored right after the cwq */
  2828. kfree(*(void **)(wq->cpu_wq.single + 1));
  2829. }
  2830. }
  2831. static int wq_clamp_max_active(int max_active, unsigned int flags,
  2832. const char *name)
  2833. {
  2834. int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
  2835. if (max_active < 1 || max_active > lim)
  2836. printk(KERN_WARNING "workqueue: max_active %d requested for %s "
  2837. "is out of range, clamping between %d and %d\n",
  2838. max_active, name, 1, lim);
  2839. return clamp_val(max_active, 1, lim);
  2840. }
  2841. struct workqueue_struct *__alloc_workqueue_key(const char *fmt,
  2842. unsigned int flags,
  2843. int max_active,
  2844. struct lock_class_key *key,
  2845. const char *lock_name, ...)
  2846. {
  2847. va_list args, args1;
  2848. struct workqueue_struct *wq;
  2849. unsigned int cpu;
  2850. size_t namelen;
  2851. /* determine namelen, allocate wq and format name */
  2852. va_start(args, lock_name);
  2853. va_copy(args1, args);
  2854. namelen = vsnprintf(NULL, 0, fmt, args) + 1;
  2855. wq = kzalloc(sizeof(*wq) + namelen, GFP_KERNEL);
  2856. if (!wq)
  2857. goto err;
  2858. vsnprintf(wq->name, namelen, fmt, args1);
  2859. va_end(args);
  2860. va_end(args1);
  2861. /*
  2862. * Workqueues which may be used during memory reclaim should
  2863. * have a rescuer to guarantee forward progress.
  2864. */
  2865. if (flags & WQ_MEM_RECLAIM)
  2866. flags |= WQ_RESCUER;
  2867. max_active = max_active ?: WQ_DFL_ACTIVE;
  2868. max_active = wq_clamp_max_active(max_active, flags, wq->name);
  2869. /* init wq */
  2870. wq->flags = flags;
  2871. wq->saved_max_active = max_active;
  2872. mutex_init(&wq->flush_mutex);
  2873. atomic_set(&wq->nr_cwqs_to_flush, 0);
  2874. INIT_LIST_HEAD(&wq->flusher_queue);
  2875. INIT_LIST_HEAD(&wq->flusher_overflow);
  2876. lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
  2877. INIT_LIST_HEAD(&wq->list);
  2878. if (alloc_cwqs(wq) < 0)
  2879. goto err;
  2880. for_each_cwq_cpu(cpu, wq) {
  2881. struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
  2882. struct global_cwq *gcwq = get_gcwq(cpu);
  2883. int pool_idx = (bool)(flags & WQ_HIGHPRI);
  2884. BUG_ON((unsigned long)cwq & WORK_STRUCT_FLAG_MASK);
  2885. cwq->pool = &gcwq->pools[pool_idx];
  2886. cwq->wq = wq;
  2887. cwq->flush_color = -1;
  2888. cwq->max_active = max_active;
  2889. INIT_LIST_HEAD(&cwq->delayed_works);
  2890. }
  2891. if (flags & WQ_RESCUER) {
  2892. struct worker *rescuer;
  2893. if (!alloc_mayday_mask(&wq->mayday_mask, GFP_KERNEL))
  2894. goto err;
  2895. wq->rescuer = rescuer = alloc_worker();
  2896. if (!rescuer)
  2897. goto err;
  2898. rescuer->task = kthread_create(rescuer_thread, wq, "%s",
  2899. wq->name);
  2900. if (IS_ERR(rescuer->task))
  2901. goto err;
  2902. rescuer->task->flags |= PF_THREAD_BOUND;
  2903. wake_up_process(rescuer->task);
  2904. }
  2905. /*
  2906. * workqueue_lock protects global freeze state and workqueues
  2907. * list. Grab it, set max_active accordingly and add the new
  2908. * workqueue to workqueues list.
  2909. */
  2910. spin_lock(&workqueue_lock);
  2911. if (workqueue_freezing && wq->flags & WQ_FREEZABLE)
  2912. for_each_cwq_cpu(cpu, wq)
  2913. get_cwq(cpu, wq)->max_active = 0;
  2914. list_add(&wq->list, &workqueues);
  2915. spin_unlock(&workqueue_lock);
  2916. return wq;
  2917. err:
  2918. if (wq) {
  2919. free_cwqs(wq);
  2920. free_mayday_mask(wq->mayday_mask);
  2921. kfree(wq->rescuer);
  2922. kfree(wq);
  2923. }
  2924. return NULL;
  2925. }
  2926. EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
  2927. /**
  2928. * destroy_workqueue - safely terminate a workqueue
  2929. * @wq: target workqueue
  2930. *
  2931. * Safely destroy a workqueue. All work currently pending will be done first.
  2932. */
  2933. void destroy_workqueue(struct workqueue_struct *wq)
  2934. {
  2935. unsigned int cpu;
  2936. /* drain it before proceeding with destruction */
  2937. drain_workqueue(wq);
  2938. /*
  2939. * wq list is used to freeze wq, remove from list after
  2940. * flushing is complete in case freeze races us.
  2941. */
  2942. spin_lock(&workqueue_lock);
  2943. list_del(&wq->list);
  2944. spin_unlock(&workqueue_lock);
  2945. /* sanity check */
  2946. for_each_cwq_cpu(cpu, wq) {
  2947. struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
  2948. int i;
  2949. for (i = 0; i < WORK_NR_COLORS; i++)
  2950. BUG_ON(cwq->nr_in_flight[i]);
  2951. BUG_ON(cwq->nr_active);
  2952. BUG_ON(!list_empty(&cwq->delayed_works));
  2953. }
  2954. if (wq->flags & WQ_RESCUER) {
  2955. kthread_stop(wq->rescuer->task);
  2956. free_mayday_mask(wq->mayday_mask);
  2957. kfree(wq->rescuer);
  2958. }
  2959. free_cwqs(wq);
  2960. kfree(wq);
  2961. }
  2962. EXPORT_SYMBOL_GPL(destroy_workqueue);
  2963. /**
  2964. * workqueue_set_max_active - adjust max_active of a workqueue
  2965. * @wq: target workqueue
  2966. * @max_active: new max_active value.
  2967. *
  2968. * Set max_active of @wq to @max_active.
  2969. *
  2970. * CONTEXT:
  2971. * Don't call from IRQ context.
  2972. */
  2973. void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
  2974. {
  2975. unsigned int cpu;
  2976. max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
  2977. spin_lock(&workqueue_lock);
  2978. wq->saved_max_active = max_active;
  2979. for_each_cwq_cpu(cpu, wq) {
  2980. struct global_cwq *gcwq = get_gcwq(cpu);
  2981. spin_lock_irq(&gcwq->lock);
  2982. if (!(wq->flags & WQ_FREEZABLE) ||
  2983. !(gcwq->flags & GCWQ_FREEZING))
  2984. get_cwq(gcwq->cpu, wq)->max_active = max_active;
  2985. spin_unlock_irq(&gcwq->lock);
  2986. }
  2987. spin_unlock(&workqueue_lock);
  2988. }
  2989. EXPORT_SYMBOL_GPL(workqueue_set_max_active);
  2990. /**
  2991. * workqueue_congested - test whether a workqueue is congested
  2992. * @cpu: CPU in question
  2993. * @wq: target workqueue
  2994. *
  2995. * Test whether @wq's cpu workqueue for @cpu is congested. There is
  2996. * no synchronization around this function and the test result is
  2997. * unreliable and only useful as advisory hints or for debugging.
  2998. *
  2999. * RETURNS:
  3000. * %true if congested, %false otherwise.
  3001. */
  3002. bool workqueue_congested(unsigned int cpu, struct workqueue_struct *wq)
  3003. {
  3004. struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
  3005. return !list_empty(&cwq->delayed_works);
  3006. }
  3007. EXPORT_SYMBOL_GPL(workqueue_congested);
  3008. /**
  3009. * work_cpu - return the last known associated cpu for @work
  3010. * @work: the work of interest
  3011. *
  3012. * RETURNS:
  3013. * CPU number if @work was ever queued. WORK_CPU_NONE otherwise.
  3014. */
  3015. unsigned int work_cpu(struct work_struct *work)
  3016. {
  3017. struct global_cwq *gcwq = get_work_gcwq(work);
  3018. return gcwq ? gcwq->cpu : WORK_CPU_NONE;
  3019. }
  3020. EXPORT_SYMBOL_GPL(work_cpu);
  3021. /**
  3022. * work_busy - test whether a work is currently pending or running
  3023. * @work: the work to be tested
  3024. *
  3025. * Test whether @work is currently pending or running. There is no
  3026. * synchronization around this function and the test result is
  3027. * unreliable and only useful as advisory hints or for debugging.
  3028. * Especially for reentrant wqs, the pending state might hide the
  3029. * running state.
  3030. *
  3031. * RETURNS:
  3032. * OR'd bitmask of WORK_BUSY_* bits.
  3033. */
  3034. unsigned int work_busy(struct work_struct *work)
  3035. {
  3036. struct global_cwq *gcwq = get_work_gcwq(work);
  3037. unsigned long flags;
  3038. unsigned int ret = 0;
  3039. if (!gcwq)
  3040. return false;
  3041. spin_lock_irqsave(&gcwq->lock, flags);
  3042. if (work_pending(work))
  3043. ret |= WORK_BUSY_PENDING;
  3044. if (find_worker_executing_work(gcwq, work))
  3045. ret |= WORK_BUSY_RUNNING;
  3046. spin_unlock_irqrestore(&gcwq->lock, flags);
  3047. return ret;
  3048. }
  3049. EXPORT_SYMBOL_GPL(work_busy);
  3050. /*
  3051. * CPU hotplug.
  3052. *
  3053. * There are two challenges in supporting CPU hotplug. Firstly, there
  3054. * are a lot of assumptions on strong associations among work, cwq and
  3055. * gcwq which make migrating pending and scheduled works very
  3056. * difficult to implement without impacting hot paths. Secondly,
  3057. * gcwqs serve mix of short, long and very long running works making
  3058. * blocked draining impractical.
  3059. *
  3060. * This is solved by allowing a gcwq to be disassociated from the CPU
  3061. * running as an unbound one and allowing it to be reattached later if the
  3062. * cpu comes back online.
  3063. */
  3064. /* claim manager positions of all pools */
  3065. static void gcwq_claim_management_and_lock(struct global_cwq *gcwq)
  3066. {
  3067. struct worker_pool *pool;
  3068. for_each_worker_pool(pool, gcwq)
  3069. mutex_lock_nested(&pool->manager_mutex, pool - gcwq->pools);
  3070. spin_lock_irq(&gcwq->lock);
  3071. }
  3072. /* release manager positions */
  3073. static void gcwq_release_management_and_unlock(struct global_cwq *gcwq)
  3074. {
  3075. struct worker_pool *pool;
  3076. spin_unlock_irq(&gcwq->lock);
  3077. for_each_worker_pool(pool, gcwq)
  3078. mutex_unlock(&pool->manager_mutex);
  3079. }
  3080. static void gcwq_unbind_fn(struct work_struct *work)
  3081. {
  3082. struct global_cwq *gcwq = get_gcwq(smp_processor_id());
  3083. struct worker_pool *pool;
  3084. struct worker *worker;
  3085. struct hlist_node *pos;
  3086. int i;
  3087. BUG_ON(gcwq->cpu != smp_processor_id());
  3088. gcwq_claim_management_and_lock(gcwq);
  3089. /*
  3090. * We've claimed all manager positions. Make all workers unbound
  3091. * and set DISASSOCIATED. Before this, all workers except for the
  3092. * ones which are still executing works from before the last CPU
  3093. * down must be on the cpu. After this, they may become diasporas.
  3094. */
  3095. for_each_worker_pool(pool, gcwq)
  3096. list_for_each_entry(worker, &pool->idle_list, entry)
  3097. worker->flags |= WORKER_UNBOUND;
  3098. for_each_busy_worker(worker, i, pos, gcwq)
  3099. worker->flags |= WORKER_UNBOUND;
  3100. gcwq->flags |= GCWQ_DISASSOCIATED;
  3101. gcwq_release_management_and_unlock(gcwq);
  3102. /*
  3103. * Call schedule() so that we cross rq->lock and thus can guarantee
  3104. * sched callbacks see the %WORKER_UNBOUND flag. This is necessary
  3105. * as scheduler callbacks may be invoked from other cpus.
  3106. */
  3107. schedule();
  3108. /*
  3109. * Sched callbacks are disabled now. Zap nr_running. After this,
  3110. * nr_running stays zero and need_more_worker() and keep_working()
  3111. * are always true as long as the worklist is not empty. @gcwq now
  3112. * behaves as unbound (in terms of concurrency management) gcwq
  3113. * which is served by workers tied to the CPU.
  3114. *
  3115. * On return from this function, the current worker would trigger
  3116. * unbound chain execution of pending work items if other workers
  3117. * didn't already.
  3118. */
  3119. for_each_worker_pool(pool, gcwq)
  3120. atomic_set(get_pool_nr_running(pool), 0);
  3121. }
  3122. /*
  3123. * Workqueues should be brought up before normal priority CPU notifiers.
  3124. * This will be registered high priority CPU notifier.
  3125. */
  3126. static int __devinit workqueue_cpu_up_callback(struct notifier_block *nfb,
  3127. unsigned long action,
  3128. void *hcpu)
  3129. {
  3130. unsigned int cpu = (unsigned long)hcpu;
  3131. struct global_cwq *gcwq = get_gcwq(cpu);
  3132. struct worker_pool *pool;
  3133. switch (action & ~CPU_TASKS_FROZEN) {
  3134. case CPU_UP_PREPARE:
  3135. for_each_worker_pool(pool, gcwq) {
  3136. struct worker *worker;
  3137. if (pool->nr_workers)
  3138. continue;
  3139. worker = create_worker(pool);
  3140. if (!worker)
  3141. return NOTIFY_BAD;
  3142. spin_lock_irq(&gcwq->lock);
  3143. start_worker(worker);
  3144. spin_unlock_irq(&gcwq->lock);
  3145. }
  3146. break;
  3147. case CPU_DOWN_FAILED:
  3148. case CPU_ONLINE:
  3149. gcwq_claim_management_and_lock(gcwq);
  3150. gcwq->flags &= ~GCWQ_DISASSOCIATED;
  3151. rebind_workers(gcwq);
  3152. gcwq_release_management_and_unlock(gcwq);
  3153. break;
  3154. }
  3155. return NOTIFY_OK;
  3156. }
  3157. /*
  3158. * Workqueues should be brought down after normal priority CPU notifiers.
  3159. * This will be registered as low priority CPU notifier.
  3160. */
  3161. static int __devinit workqueue_cpu_down_callback(struct notifier_block *nfb,
  3162. unsigned long action,
  3163. void *hcpu)
  3164. {
  3165. unsigned int cpu = (unsigned long)hcpu;
  3166. struct work_struct unbind_work;
  3167. switch (action & ~CPU_TASKS_FROZEN) {
  3168. case CPU_DOWN_PREPARE:
  3169. /* unbinding should happen on the local CPU */
  3170. INIT_WORK_ONSTACK(&unbind_work, gcwq_unbind_fn);
  3171. schedule_work_on(cpu, &unbind_work);
  3172. flush_work(&unbind_work);
  3173. break;
  3174. }
  3175. return NOTIFY_OK;
  3176. }
  3177. #ifdef CONFIG_SMP
  3178. struct work_for_cpu {
  3179. struct completion completion;
  3180. long (*fn)(void *);
  3181. void *arg;
  3182. long ret;
  3183. };
  3184. static int do_work_for_cpu(void *_wfc)
  3185. {
  3186. struct work_for_cpu *wfc = _wfc;
  3187. wfc->ret = wfc->fn(wfc->arg);
  3188. complete(&wfc->completion);
  3189. return 0;
  3190. }
  3191. /**
  3192. * work_on_cpu - run a function in user context on a particular cpu
  3193. * @cpu: the cpu to run on
  3194. * @fn: the function to run
  3195. * @arg: the function arg
  3196. *
  3197. * This will return the value @fn returns.
  3198. * It is up to the caller to ensure that the cpu doesn't go offline.
  3199. * The caller must not hold any locks which would prevent @fn from completing.
  3200. */
  3201. long work_on_cpu(unsigned int cpu, long (*fn)(void *), void *arg)
  3202. {
  3203. struct task_struct *sub_thread;
  3204. struct work_for_cpu wfc = {
  3205. .completion = COMPLETION_INITIALIZER_ONSTACK(wfc.completion),
  3206. .fn = fn,
  3207. .arg = arg,
  3208. };
  3209. sub_thread = kthread_create(do_work_for_cpu, &wfc, "work_for_cpu");
  3210. if (IS_ERR(sub_thread))
  3211. return PTR_ERR(sub_thread);
  3212. kthread_bind(sub_thread, cpu);
  3213. wake_up_process(sub_thread);
  3214. wait_for_completion(&wfc.completion);
  3215. return wfc.ret;
  3216. }
  3217. EXPORT_SYMBOL_GPL(work_on_cpu);
  3218. #endif /* CONFIG_SMP */
  3219. #ifdef CONFIG_FREEZER
  3220. /**
  3221. * freeze_workqueues_begin - begin freezing workqueues
  3222. *
  3223. * Start freezing workqueues. After this function returns, all freezable
  3224. * workqueues will queue new works to their frozen_works list instead of
  3225. * gcwq->worklist.
  3226. *
  3227. * CONTEXT:
  3228. * Grabs and releases workqueue_lock and gcwq->lock's.
  3229. */
  3230. void freeze_workqueues_begin(void)
  3231. {
  3232. unsigned int cpu;
  3233. spin_lock(&workqueue_lock);
  3234. BUG_ON(workqueue_freezing);
  3235. workqueue_freezing = true;
  3236. for_each_gcwq_cpu(cpu) {
  3237. struct global_cwq *gcwq = get_gcwq(cpu);
  3238. struct workqueue_struct *wq;
  3239. spin_lock_irq(&gcwq->lock);
  3240. BUG_ON(gcwq->flags & GCWQ_FREEZING);
  3241. gcwq->flags |= GCWQ_FREEZING;
  3242. list_for_each_entry(wq, &workqueues, list) {
  3243. struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
  3244. if (cwq && wq->flags & WQ_FREEZABLE)
  3245. cwq->max_active = 0;
  3246. }
  3247. spin_unlock_irq(&gcwq->lock);
  3248. }
  3249. spin_unlock(&workqueue_lock);
  3250. }
  3251. /**
  3252. * freeze_workqueues_busy - are freezable workqueues still busy?
  3253. *
  3254. * Check whether freezing is complete. This function must be called
  3255. * between freeze_workqueues_begin() and thaw_workqueues().
  3256. *
  3257. * CONTEXT:
  3258. * Grabs and releases workqueue_lock.
  3259. *
  3260. * RETURNS:
  3261. * %true if some freezable workqueues are still busy. %false if freezing
  3262. * is complete.
  3263. */
  3264. bool freeze_workqueues_busy(void)
  3265. {
  3266. unsigned int cpu;
  3267. bool busy = false;
  3268. spin_lock(&workqueue_lock);
  3269. BUG_ON(!workqueue_freezing);
  3270. for_each_gcwq_cpu(cpu) {
  3271. struct workqueue_struct *wq;
  3272. /*
  3273. * nr_active is monotonically decreasing. It's safe
  3274. * to peek without lock.
  3275. */
  3276. list_for_each_entry(wq, &workqueues, list) {
  3277. struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
  3278. if (!cwq || !(wq->flags & WQ_FREEZABLE))
  3279. continue;
  3280. BUG_ON(cwq->nr_active < 0);
  3281. if (cwq->nr_active) {
  3282. busy = true;
  3283. goto out_unlock;
  3284. }
  3285. }
  3286. }
  3287. out_unlock:
  3288. spin_unlock(&workqueue_lock);
  3289. return busy;
  3290. }
  3291. /**
  3292. * thaw_workqueues - thaw workqueues
  3293. *
  3294. * Thaw workqueues. Normal queueing is restored and all collected
  3295. * frozen works are transferred to their respective gcwq worklists.
  3296. *
  3297. * CONTEXT:
  3298. * Grabs and releases workqueue_lock and gcwq->lock's.
  3299. */
  3300. void thaw_workqueues(void)
  3301. {
  3302. unsigned int cpu;
  3303. spin_lock(&workqueue_lock);
  3304. if (!workqueue_freezing)
  3305. goto out_unlock;
  3306. for_each_gcwq_cpu(cpu) {
  3307. struct global_cwq *gcwq = get_gcwq(cpu);
  3308. struct worker_pool *pool;
  3309. struct workqueue_struct *wq;
  3310. spin_lock_irq(&gcwq->lock);
  3311. BUG_ON(!(gcwq->flags & GCWQ_FREEZING));
  3312. gcwq->flags &= ~GCWQ_FREEZING;
  3313. list_for_each_entry(wq, &workqueues, list) {
  3314. struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
  3315. if (!cwq || !(wq->flags & WQ_FREEZABLE))
  3316. continue;
  3317. /* restore max_active and repopulate worklist */
  3318. cwq->max_active = wq->saved_max_active;
  3319. while (!list_empty(&cwq->delayed_works) &&
  3320. cwq->nr_active < cwq->max_active)
  3321. cwq_activate_first_delayed(cwq);
  3322. }
  3323. for_each_worker_pool(pool, gcwq)
  3324. wake_up_worker(pool);
  3325. spin_unlock_irq(&gcwq->lock);
  3326. }
  3327. workqueue_freezing = false;
  3328. out_unlock:
  3329. spin_unlock(&workqueue_lock);
  3330. }
  3331. #endif /* CONFIG_FREEZER */
  3332. static int __init init_workqueues(void)
  3333. {
  3334. unsigned int cpu;
  3335. int i;
  3336. /* make sure we have enough bits for OFFQ CPU number */
  3337. BUILD_BUG_ON((1LU << (BITS_PER_LONG - WORK_OFFQ_CPU_SHIFT)) <
  3338. WORK_CPU_LAST);
  3339. cpu_notifier(workqueue_cpu_up_callback, CPU_PRI_WORKQUEUE_UP);
  3340. cpu_notifier(workqueue_cpu_down_callback, CPU_PRI_WORKQUEUE_DOWN);
  3341. /* initialize gcwqs */
  3342. for_each_gcwq_cpu(cpu) {
  3343. struct global_cwq *gcwq = get_gcwq(cpu);
  3344. struct worker_pool *pool;
  3345. spin_lock_init(&gcwq->lock);
  3346. gcwq->cpu = cpu;
  3347. gcwq->flags |= GCWQ_DISASSOCIATED;
  3348. for (i = 0; i < BUSY_WORKER_HASH_SIZE; i++)
  3349. INIT_HLIST_HEAD(&gcwq->busy_hash[i]);
  3350. for_each_worker_pool(pool, gcwq) {
  3351. pool->gcwq = gcwq;
  3352. INIT_LIST_HEAD(&pool->worklist);
  3353. INIT_LIST_HEAD(&pool->idle_list);
  3354. init_timer_deferrable(&pool->idle_timer);
  3355. pool->idle_timer.function = idle_worker_timeout;
  3356. pool->idle_timer.data = (unsigned long)pool;
  3357. setup_timer(&pool->mayday_timer, gcwq_mayday_timeout,
  3358. (unsigned long)pool);
  3359. mutex_init(&pool->manager_mutex);
  3360. ida_init(&pool->worker_ida);
  3361. }
  3362. init_waitqueue_head(&gcwq->rebind_hold);
  3363. }
  3364. /* create the initial worker */
  3365. for_each_online_gcwq_cpu(cpu) {
  3366. struct global_cwq *gcwq = get_gcwq(cpu);
  3367. struct worker_pool *pool;
  3368. if (cpu != WORK_CPU_UNBOUND)
  3369. gcwq->flags &= ~GCWQ_DISASSOCIATED;
  3370. for_each_worker_pool(pool, gcwq) {
  3371. struct worker *worker;
  3372. worker = create_worker(pool);
  3373. BUG_ON(!worker);
  3374. spin_lock_irq(&gcwq->lock);
  3375. start_worker(worker);
  3376. spin_unlock_irq(&gcwq->lock);
  3377. }
  3378. }
  3379. system_wq = alloc_workqueue("events", 0, 0);
  3380. system_long_wq = alloc_workqueue("events_long", 0, 0);
  3381. system_nrt_wq = alloc_workqueue("events_nrt", WQ_NON_REENTRANT, 0);
  3382. system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
  3383. WQ_UNBOUND_MAX_ACTIVE);
  3384. system_freezable_wq = alloc_workqueue("events_freezable",
  3385. WQ_FREEZABLE, 0);
  3386. system_nrt_freezable_wq = alloc_workqueue("events_nrt_freezable",
  3387. WQ_NON_REENTRANT | WQ_FREEZABLE, 0);
  3388. BUG_ON(!system_wq || !system_long_wq || !system_nrt_wq ||
  3389. !system_unbound_wq || !system_freezable_wq ||
  3390. !system_nrt_freezable_wq);
  3391. return 0;
  3392. }
  3393. early_initcall(init_workqueues);