workqueue.c 104 KB

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