workqueue.c 156 KB

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