workqueue.c 141 KB

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