workqueue.c 140 KB

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