workqueue.c 156 KB

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