workqueue.c 121 KB

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