workqueue.c 104 KB

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