workqueue.c 150 KB

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