workqueue.c 111 KB

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