workqueue.c 136 KB

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