workqueue.c 122 KB

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