workqueue.c 107 KB

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