workqueue.c 155 KB

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