workqueue.c 146 KB

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