workqueue.c 159 KB

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