workqueue.c 159 KB

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