workqueue.c 224 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * kernel/workqueue.c - generic async execution with shared worker pool
  4. *
  5. * Copyright (C) 2002 Ingo Molnar
  6. *
  7. * Derived from the taskqueue/keventd code by:
  8. * David Woodhouse <dwmw2@infradead.org>
  9. * Andrew Morton
  10. * Kai Petzke <wpp@marie.physik.tu-berlin.de>
  11. * Theodore Ts'o <tytso@mit.edu>
  12. *
  13. * Made to use alloc_percpu by Christoph Lameter.
  14. *
  15. * Copyright (C) 2010 SUSE Linux Products GmbH
  16. * Copyright (C) 2010 Tejun Heo <tj@kernel.org>
  17. *
  18. * This is the generic async execution mechanism. Work items as are
  19. * executed in process context. The worker pool is shared and
  20. * automatically managed. There are two worker pools for each CPU (one for
  21. * normal work items and the other for high priority ones) and some extra
  22. * pools for workqueues which are not bound to any specific CPU - the
  23. * number of these backing pools is dynamic.
  24. *
  25. * Please read Documentation/core-api/workqueue.rst for details.
  26. */
  27. #include <linux/export.h>
  28. #include <linux/kernel.h>
  29. #include <linux/sched.h>
  30. #include <linux/init.h>
  31. #include <linux/interrupt.h>
  32. #include <linux/signal.h>
  33. #include <linux/completion.h>
  34. #include <linux/workqueue.h>
  35. #include <linux/slab.h>
  36. #include <linux/cpu.h>
  37. #include <linux/notifier.h>
  38. #include <linux/kthread.h>
  39. #include <linux/hardirq.h>
  40. #include <linux/mempolicy.h>
  41. #include <linux/freezer.h>
  42. #include <linux/debug_locks.h>
  43. #include <linux/lockdep.h>
  44. #include <linux/idr.h>
  45. #include <linux/jhash.h>
  46. #include <linux/hashtable.h>
  47. #include <linux/rculist.h>
  48. #include <linux/nodemask.h>
  49. #include <linux/moduleparam.h>
  50. #include <linux/uaccess.h>
  51. #include <linux/sched/isolation.h>
  52. #include <linux/sched/debug.h>
  53. #include <linux/nmi.h>
  54. #include <linux/kvm_para.h>
  55. #include <linux/delay.h>
  56. #include <linux/irq_work.h>
  57. #include "workqueue_internal.h"
  58. enum worker_pool_flags {
  59. /*
  60. * worker_pool flags
  61. *
  62. * A bound pool is either associated or disassociated with its CPU.
  63. * While associated (!DISASSOCIATED), all workers are bound to the
  64. * CPU and none has %WORKER_UNBOUND set and concurrency management
  65. * is in effect.
  66. *
  67. * While DISASSOCIATED, the cpu may be offline and all workers have
  68. * %WORKER_UNBOUND set and concurrency management disabled, and may
  69. * be executing on any CPU. The pool behaves as an unbound one.
  70. *
  71. * Note that DISASSOCIATED should be flipped only while holding
  72. * wq_pool_attach_mutex to avoid changing binding state while
  73. * worker_attach_to_pool() is in progress.
  74. *
  75. * As there can only be one concurrent BH execution context per CPU, a
  76. * BH pool is per-CPU and always DISASSOCIATED.
  77. */
  78. POOL_BH = 1 << 0, /* is a BH pool */
  79. POOL_MANAGER_ACTIVE = 1 << 1, /* being managed */
  80. POOL_DISASSOCIATED = 1 << 2, /* cpu can't serve workers */
  81. POOL_BH_DRAINING = 1 << 3, /* draining after CPU offline */
  82. };
  83. enum worker_flags {
  84. /* worker flags */
  85. WORKER_DIE = 1 << 1, /* die die die */
  86. WORKER_IDLE = 1 << 2, /* is idle */
  87. WORKER_PREP = 1 << 3, /* preparing to run works */
  88. WORKER_CPU_INTENSIVE = 1 << 6, /* cpu intensive */
  89. WORKER_UNBOUND = 1 << 7, /* worker is unbound */
  90. WORKER_REBOUND = 1 << 8, /* worker was rebound */
  91. WORKER_NOT_RUNNING = WORKER_PREP | WORKER_CPU_INTENSIVE |
  92. WORKER_UNBOUND | WORKER_REBOUND,
  93. };
  94. enum work_cancel_flags {
  95. WORK_CANCEL_DELAYED = 1 << 0, /* canceling a delayed_work */
  96. WORK_CANCEL_DISABLE = 1 << 1, /* canceling to disable */
  97. };
  98. enum wq_internal_consts {
  99. NR_STD_WORKER_POOLS = 2, /* # standard pools per cpu */
  100. UNBOUND_POOL_HASH_ORDER = 6, /* hashed by pool->attrs */
  101. BUSY_WORKER_HASH_ORDER = 6, /* 64 pointers */
  102. MAX_IDLE_WORKERS_RATIO = 4, /* 1/4 of busy can be idle */
  103. IDLE_WORKER_TIMEOUT = 300 * HZ, /* keep idle ones for 5 mins */
  104. MAYDAY_INITIAL_TIMEOUT = HZ / 100 >= 2 ? HZ / 100 : 2,
  105. /* call for help after 10ms
  106. (min two ticks) */
  107. MAYDAY_INTERVAL = HZ / 10, /* and then every 100ms */
  108. CREATE_COOLDOWN = HZ, /* time to breath after fail */
  109. /*
  110. * Rescue workers are used only on emergencies and shared by
  111. * all cpus. Give MIN_NICE.
  112. */
  113. RESCUER_NICE_LEVEL = MIN_NICE,
  114. HIGHPRI_NICE_LEVEL = MIN_NICE,
  115. WQ_NAME_LEN = 32,
  116. WORKER_ID_LEN = 10 + WQ_NAME_LEN, /* "kworker/R-" + WQ_NAME_LEN */
  117. };
  118. /*
  119. * We don't want to trap softirq for too long. See MAX_SOFTIRQ_TIME and
  120. * MAX_SOFTIRQ_RESTART in kernel/softirq.c. These are macros because
  121. * msecs_to_jiffies() can't be an initializer.
  122. */
  123. #define BH_WORKER_JIFFIES msecs_to_jiffies(2)
  124. #define BH_WORKER_RESTARTS 10
  125. /*
  126. * Structure fields follow one of the following exclusion rules.
  127. *
  128. * I: Modifiable by initialization/destruction paths and read-only for
  129. * everyone else.
  130. *
  131. * P: Preemption protected. Disabling preemption is enough and should
  132. * only be modified and accessed from the local cpu.
  133. *
  134. * L: pool->lock protected. Access with pool->lock held.
  135. *
  136. * LN: pool->lock and wq_node_nr_active->lock protected for writes. Either for
  137. * reads.
  138. *
  139. * K: Only modified by worker while holding pool->lock. Can be safely read by
  140. * self, while holding pool->lock or from IRQ context if %current is the
  141. * kworker.
  142. *
  143. * S: Only modified by worker self.
  144. *
  145. * A: wq_pool_attach_mutex protected.
  146. *
  147. * PL: wq_pool_mutex protected.
  148. *
  149. * PR: wq_pool_mutex protected for writes. RCU protected for reads.
  150. *
  151. * PW: wq_pool_mutex and wq->mutex protected for writes. Either for reads.
  152. *
  153. * PWR: wq_pool_mutex and wq->mutex protected for writes. Either or
  154. * RCU for reads.
  155. *
  156. * WQ: wq->mutex protected.
  157. *
  158. * WR: wq->mutex protected for writes. RCU protected for reads.
  159. *
  160. * WO: wq->mutex protected for writes. Updated with WRITE_ONCE() and can be read
  161. * with READ_ONCE() without locking.
  162. *
  163. * MD: wq_mayday_lock protected.
  164. *
  165. * WD: Used internally by the watchdog.
  166. */
  167. /* struct worker is defined in workqueue_internal.h */
  168. struct worker_pool {
  169. raw_spinlock_t lock; /* the pool lock */
  170. int cpu; /* I: the associated cpu */
  171. int node; /* I: the associated node ID */
  172. int id; /* I: pool ID */
  173. unsigned int flags; /* L: flags */
  174. unsigned long watchdog_ts; /* L: watchdog timestamp */
  175. bool cpu_stall; /* WD: stalled cpu bound pool */
  176. /*
  177. * The counter is incremented in a process context on the associated CPU
  178. * w/ preemption disabled, and decremented or reset in the same context
  179. * but w/ pool->lock held. The readers grab pool->lock and are
  180. * guaranteed to see if the counter reached zero.
  181. */
  182. int nr_running;
  183. struct list_head worklist; /* L: list of pending works */
  184. int nr_workers; /* L: total number of workers */
  185. int nr_idle; /* L: currently idle workers */
  186. struct list_head idle_list; /* L: list of idle workers */
  187. struct timer_list idle_timer; /* L: worker idle timeout */
  188. struct work_struct idle_cull_work; /* L: worker idle cleanup */
  189. struct timer_list mayday_timer; /* L: SOS timer for workers */
  190. /* a workers is either on busy_hash or idle_list, or the manager */
  191. DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
  192. /* L: hash of busy workers */
  193. struct worker *manager; /* L: purely informational */
  194. struct list_head workers; /* A: attached workers */
  195. struct ida worker_ida; /* worker IDs for task name */
  196. struct workqueue_attrs *attrs; /* I: worker attributes */
  197. struct hlist_node hash_node; /* PL: unbound_pool_hash node */
  198. int refcnt; /* PL: refcnt for unbound pools */
  199. /*
  200. * Destruction of pool is RCU protected to allow dereferences
  201. * from get_work_pool().
  202. */
  203. struct rcu_head rcu;
  204. };
  205. /*
  206. * Per-pool_workqueue statistics. These can be monitored using
  207. * tools/workqueue/wq_monitor.py.
  208. */
  209. enum pool_workqueue_stats {
  210. PWQ_STAT_STARTED, /* work items started execution */
  211. PWQ_STAT_COMPLETED, /* work items completed execution */
  212. PWQ_STAT_CPU_TIME, /* total CPU time consumed */
  213. PWQ_STAT_CPU_INTENSIVE, /* wq_cpu_intensive_thresh_us violations */
  214. PWQ_STAT_CM_WAKEUP, /* concurrency-management worker wakeups */
  215. PWQ_STAT_REPATRIATED, /* unbound workers brought back into scope */
  216. PWQ_STAT_MAYDAY, /* maydays to rescuer */
  217. PWQ_STAT_RESCUED, /* linked work items executed by rescuer */
  218. PWQ_NR_STATS,
  219. };
  220. /*
  221. * The per-pool workqueue. While queued, bits below WORK_PWQ_SHIFT
  222. * of work_struct->data are used for flags and the remaining high bits
  223. * point to the pwq; thus, pwqs need to be aligned at two's power of the
  224. * number of flag bits.
  225. */
  226. struct pool_workqueue {
  227. struct worker_pool *pool; /* I: the associated pool */
  228. struct workqueue_struct *wq; /* I: the owning workqueue */
  229. int work_color; /* L: current color */
  230. int flush_color; /* L: flushing color */
  231. int refcnt; /* L: reference count */
  232. int nr_in_flight[WORK_NR_COLORS];
  233. /* L: nr of in_flight works */
  234. bool plugged; /* L: execution suspended */
  235. /*
  236. * nr_active management and WORK_STRUCT_INACTIVE:
  237. *
  238. * When pwq->nr_active >= max_active, new work item is queued to
  239. * pwq->inactive_works instead of pool->worklist and marked with
  240. * WORK_STRUCT_INACTIVE.
  241. *
  242. * All work items marked with WORK_STRUCT_INACTIVE do not participate in
  243. * nr_active and all work items in pwq->inactive_works are marked with
  244. * WORK_STRUCT_INACTIVE. But not all WORK_STRUCT_INACTIVE work items are
  245. * in pwq->inactive_works. Some of them are ready to run in
  246. * pool->worklist or worker->scheduled. Those work itmes are only struct
  247. * wq_barrier which is used for flush_work() and should not participate
  248. * in nr_active. For non-barrier work item, it is marked with
  249. * WORK_STRUCT_INACTIVE iff it is in pwq->inactive_works.
  250. */
  251. int nr_active; /* L: nr of active works */
  252. struct list_head inactive_works; /* L: inactive works */
  253. struct list_head pending_node; /* LN: node on wq_node_nr_active->pending_pwqs */
  254. struct list_head pwqs_node; /* WR: node on wq->pwqs */
  255. struct list_head mayday_node; /* MD: node on wq->maydays */
  256. u64 stats[PWQ_NR_STATS];
  257. /*
  258. * Release of unbound pwq is punted to a kthread_worker. See put_pwq()
  259. * and pwq_release_workfn() for details. pool_workqueue itself is also
  260. * RCU protected so that the first pwq can be determined without
  261. * grabbing wq->mutex.
  262. */
  263. struct kthread_work release_work;
  264. struct rcu_head rcu;
  265. } __aligned(1 << WORK_STRUCT_PWQ_SHIFT);
  266. /*
  267. * Structure used to wait for workqueue flush.
  268. */
  269. struct wq_flusher {
  270. struct list_head list; /* WQ: list of flushers */
  271. int flush_color; /* WQ: flush color waiting for */
  272. struct completion done; /* flush completion */
  273. };
  274. struct wq_device;
  275. /*
  276. * Unlike in a per-cpu workqueue where max_active limits its concurrency level
  277. * on each CPU, in an unbound workqueue, max_active applies to the whole system.
  278. * As sharing a single nr_active across multiple sockets can be very expensive,
  279. * the counting and enforcement is per NUMA node.
  280. *
  281. * The following struct is used to enforce per-node max_active. When a pwq wants
  282. * to start executing a work item, it should increment ->nr using
  283. * tryinc_node_nr_active(). If acquisition fails due to ->nr already being over
  284. * ->max, the pwq is queued on ->pending_pwqs. As in-flight work items finish
  285. * and decrement ->nr, node_activate_pending_pwq() activates the pending pwqs in
  286. * round-robin order.
  287. */
  288. struct wq_node_nr_active {
  289. int max; /* per-node max_active */
  290. atomic_t nr; /* per-node nr_active */
  291. raw_spinlock_t lock; /* nests inside pool locks */
  292. struct list_head pending_pwqs; /* LN: pwqs with inactive works */
  293. };
  294. /*
  295. * The externally visible workqueue. It relays the issued work items to
  296. * the appropriate worker_pool through its pool_workqueues.
  297. */
  298. struct workqueue_struct {
  299. struct list_head pwqs; /* WR: all pwqs of this wq */
  300. struct list_head list; /* PR: list of all workqueues */
  301. struct mutex mutex; /* protects this wq */
  302. int work_color; /* WQ: current work color */
  303. int flush_color; /* WQ: current flush color */
  304. atomic_t nr_pwqs_to_flush; /* flush in progress */
  305. struct wq_flusher *first_flusher; /* WQ: first flusher */
  306. struct list_head flusher_queue; /* WQ: flush waiters */
  307. struct list_head flusher_overflow; /* WQ: flush overflow list */
  308. struct list_head maydays; /* MD: pwqs requesting rescue */
  309. struct worker *rescuer; /* MD: rescue worker */
  310. int nr_drainers; /* WQ: drain in progress */
  311. /* See alloc_workqueue() function comment for info on min/max_active */
  312. int max_active; /* WO: max active works */
  313. int min_active; /* WO: min active works */
  314. int saved_max_active; /* WQ: saved max_active */
  315. int saved_min_active; /* WQ: saved min_active */
  316. struct workqueue_attrs *unbound_attrs; /* PW: only for unbound wqs */
  317. struct pool_workqueue __rcu *dfl_pwq; /* PW: only for unbound wqs */
  318. #ifdef CONFIG_SYSFS
  319. struct wq_device *wq_dev; /* I: for sysfs interface */
  320. #endif
  321. #ifdef CONFIG_LOCKDEP
  322. char *lock_name;
  323. struct lock_class_key key;
  324. struct lockdep_map __lockdep_map;
  325. struct lockdep_map *lockdep_map;
  326. #endif
  327. char name[WQ_NAME_LEN]; /* I: workqueue name */
  328. /*
  329. * Destruction of workqueue_struct is RCU protected to allow walking
  330. * the workqueues list without grabbing wq_pool_mutex.
  331. * This is used to dump all workqueues from sysrq.
  332. */
  333. struct rcu_head rcu;
  334. /* hot fields used during command issue, aligned to cacheline */
  335. unsigned int flags ____cacheline_aligned; /* WQ: WQ_* flags */
  336. struct pool_workqueue __rcu * __percpu *cpu_pwq; /* I: per-cpu pwqs */
  337. struct wq_node_nr_active *node_nr_active[]; /* I: per-node nr_active */
  338. };
  339. /*
  340. * Each pod type describes how CPUs should be grouped for unbound workqueues.
  341. * See the comment above workqueue_attrs->affn_scope.
  342. */
  343. struct wq_pod_type {
  344. int nr_pods; /* number of pods */
  345. cpumask_var_t *pod_cpus; /* pod -> cpus */
  346. int *pod_node; /* pod -> node */
  347. int *cpu_pod; /* cpu -> pod */
  348. };
  349. struct work_offq_data {
  350. u32 pool_id;
  351. u32 disable;
  352. u32 flags;
  353. };
  354. static const char *wq_affn_names[WQ_AFFN_NR_TYPES] = {
  355. [WQ_AFFN_DFL] = "default",
  356. [WQ_AFFN_CPU] = "cpu",
  357. [WQ_AFFN_SMT] = "smt",
  358. [WQ_AFFN_CACHE] = "cache",
  359. [WQ_AFFN_NUMA] = "numa",
  360. [WQ_AFFN_SYSTEM] = "system",
  361. };
  362. /*
  363. * Per-cpu work items which run for longer than the following threshold are
  364. * automatically considered CPU intensive and excluded from concurrency
  365. * management to prevent them from noticeably delaying other per-cpu work items.
  366. * ULONG_MAX indicates that the user hasn't overridden it with a boot parameter.
  367. * The actual value is initialized in wq_cpu_intensive_thresh_init().
  368. */
  369. static unsigned long wq_cpu_intensive_thresh_us = ULONG_MAX;
  370. module_param_named(cpu_intensive_thresh_us, wq_cpu_intensive_thresh_us, ulong, 0644);
  371. #ifdef CONFIG_WQ_CPU_INTENSIVE_REPORT
  372. static unsigned int wq_cpu_intensive_warning_thresh = 4;
  373. module_param_named(cpu_intensive_warning_thresh, wq_cpu_intensive_warning_thresh, uint, 0644);
  374. #endif
  375. /* see the comment above the definition of WQ_POWER_EFFICIENT */
  376. static bool wq_power_efficient = IS_ENABLED(CONFIG_WQ_POWER_EFFICIENT_DEFAULT);
  377. module_param_named(power_efficient, wq_power_efficient, bool, 0444);
  378. static bool wq_online; /* can kworkers be created yet? */
  379. static bool wq_topo_initialized __read_mostly = false;
  380. static struct kmem_cache *pwq_cache;
  381. static struct wq_pod_type wq_pod_types[WQ_AFFN_NR_TYPES];
  382. static enum wq_affn_scope wq_affn_dfl = WQ_AFFN_CACHE;
  383. /* buf for wq_update_unbound_pod_attrs(), protected by CPU hotplug exclusion */
  384. static struct workqueue_attrs *unbound_wq_update_pwq_attrs_buf;
  385. static DEFINE_MUTEX(wq_pool_mutex); /* protects pools and workqueues list */
  386. static DEFINE_MUTEX(wq_pool_attach_mutex); /* protects worker attach/detach */
  387. static DEFINE_RAW_SPINLOCK(wq_mayday_lock); /* protects wq->maydays list */
  388. /* wait for manager to go away */
  389. static struct rcuwait manager_wait = __RCUWAIT_INITIALIZER(manager_wait);
  390. static LIST_HEAD(workqueues); /* PR: list of all workqueues */
  391. static bool workqueue_freezing; /* PL: have wqs started freezing? */
  392. /* PL: mirror the cpu_online_mask excluding the CPU in the midst of hotplugging */
  393. static cpumask_var_t wq_online_cpumask;
  394. /* PL&A: allowable cpus for unbound wqs and work items */
  395. static cpumask_var_t wq_unbound_cpumask;
  396. /* PL: user requested unbound cpumask via sysfs */
  397. static cpumask_var_t wq_requested_unbound_cpumask;
  398. /* PL: isolated cpumask to be excluded from unbound cpumask */
  399. static cpumask_var_t wq_isolated_cpumask;
  400. /* for further constrain wq_unbound_cpumask by cmdline parameter*/
  401. static struct cpumask wq_cmdline_cpumask __initdata;
  402. /* CPU where unbound work was last round robin scheduled from this CPU */
  403. static DEFINE_PER_CPU(int, wq_rr_cpu_last);
  404. /*
  405. * Local execution of unbound work items is no longer guaranteed. The
  406. * following always forces round-robin CPU selection on unbound work items
  407. * to uncover usages which depend on it.
  408. */
  409. #ifdef CONFIG_DEBUG_WQ_FORCE_RR_CPU
  410. static bool wq_debug_force_rr_cpu = true;
  411. #else
  412. static bool wq_debug_force_rr_cpu = false;
  413. #endif
  414. module_param_named(debug_force_rr_cpu, wq_debug_force_rr_cpu, bool, 0644);
  415. /* to raise softirq for the BH worker pools on other CPUs */
  416. static DEFINE_PER_CPU_SHARED_ALIGNED(struct irq_work [NR_STD_WORKER_POOLS], bh_pool_irq_works);
  417. /* the BH worker pools */
  418. static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS], bh_worker_pools);
  419. /* the per-cpu worker pools */
  420. static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS], cpu_worker_pools);
  421. static DEFINE_IDR(worker_pool_idr); /* PR: idr of all pools */
  422. /* PL: hash of all unbound pools keyed by pool->attrs */
  423. static DEFINE_HASHTABLE(unbound_pool_hash, UNBOUND_POOL_HASH_ORDER);
  424. /* I: attributes used when instantiating standard unbound pools on demand */
  425. static struct workqueue_attrs *unbound_std_wq_attrs[NR_STD_WORKER_POOLS];
  426. /* I: attributes used when instantiating ordered pools on demand */
  427. static struct workqueue_attrs *ordered_wq_attrs[NR_STD_WORKER_POOLS];
  428. /*
  429. * I: kthread_worker to release pwq's. pwq release needs to be bounced to a
  430. * process context while holding a pool lock. Bounce to a dedicated kthread
  431. * worker to avoid A-A deadlocks.
  432. */
  433. static struct kthread_worker *pwq_release_worker __ro_after_init;
  434. struct workqueue_struct *system_wq __ro_after_init;
  435. EXPORT_SYMBOL(system_wq);
  436. struct workqueue_struct *system_highpri_wq __ro_after_init;
  437. EXPORT_SYMBOL_GPL(system_highpri_wq);
  438. struct workqueue_struct *system_long_wq __ro_after_init;
  439. EXPORT_SYMBOL_GPL(system_long_wq);
  440. struct workqueue_struct *system_unbound_wq __ro_after_init;
  441. EXPORT_SYMBOL_GPL(system_unbound_wq);
  442. struct workqueue_struct *system_freezable_wq __ro_after_init;
  443. EXPORT_SYMBOL_GPL(system_freezable_wq);
  444. struct workqueue_struct *system_power_efficient_wq __ro_after_init;
  445. EXPORT_SYMBOL_GPL(system_power_efficient_wq);
  446. struct workqueue_struct *system_freezable_power_efficient_wq __ro_after_init;
  447. EXPORT_SYMBOL_GPL(system_freezable_power_efficient_wq);
  448. struct workqueue_struct *system_bh_wq;
  449. EXPORT_SYMBOL_GPL(system_bh_wq);
  450. struct workqueue_struct *system_bh_highpri_wq;
  451. EXPORT_SYMBOL_GPL(system_bh_highpri_wq);
  452. static int worker_thread(void *__worker);
  453. static void workqueue_sysfs_unregister(struct workqueue_struct *wq);
  454. static void show_pwq(struct pool_workqueue *pwq);
  455. static void show_one_worker_pool(struct worker_pool *pool);
  456. #define CREATE_TRACE_POINTS
  457. #include <trace/events/workqueue.h>
  458. #define assert_rcu_or_pool_mutex() \
  459. RCU_LOCKDEP_WARN(!rcu_read_lock_any_held() && \
  460. !lockdep_is_held(&wq_pool_mutex), \
  461. "RCU or wq_pool_mutex should be held")
  462. #define assert_rcu_or_wq_mutex_or_pool_mutex(wq) \
  463. RCU_LOCKDEP_WARN(!rcu_read_lock_any_held() && \
  464. !lockdep_is_held(&wq->mutex) && \
  465. !lockdep_is_held(&wq_pool_mutex), \
  466. "RCU, wq->mutex or wq_pool_mutex should be held")
  467. #define for_each_bh_worker_pool(pool, cpu) \
  468. for ((pool) = &per_cpu(bh_worker_pools, cpu)[0]; \
  469. (pool) < &per_cpu(bh_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
  470. (pool)++)
  471. #define for_each_cpu_worker_pool(pool, cpu) \
  472. for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0]; \
  473. (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
  474. (pool)++)
  475. /**
  476. * for_each_pool - iterate through all worker_pools in the system
  477. * @pool: iteration cursor
  478. * @pi: integer used for iteration
  479. *
  480. * This must be called either with wq_pool_mutex held or RCU read
  481. * locked. If the pool needs to be used beyond the locking in effect, the
  482. * caller is responsible for guaranteeing that the pool stays online.
  483. *
  484. * The if/else clause exists only for the lockdep assertion and can be
  485. * ignored.
  486. */
  487. #define for_each_pool(pool, pi) \
  488. idr_for_each_entry(&worker_pool_idr, pool, pi) \
  489. if (({ assert_rcu_or_pool_mutex(); false; })) { } \
  490. else
  491. /**
  492. * for_each_pool_worker - iterate through all workers of a worker_pool
  493. * @worker: iteration cursor
  494. * @pool: worker_pool to iterate workers of
  495. *
  496. * This must be called with wq_pool_attach_mutex.
  497. *
  498. * The if/else clause exists only for the lockdep assertion and can be
  499. * ignored.
  500. */
  501. #define for_each_pool_worker(worker, pool) \
  502. list_for_each_entry((worker), &(pool)->workers, node) \
  503. if (({ lockdep_assert_held(&wq_pool_attach_mutex); false; })) { } \
  504. else
  505. /**
  506. * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
  507. * @pwq: iteration cursor
  508. * @wq: the target workqueue
  509. *
  510. * This must be called either with wq->mutex held or RCU read locked.
  511. * If the pwq needs to be used beyond the locking in effect, the caller is
  512. * responsible for guaranteeing that the pwq stays online.
  513. *
  514. * The if/else clause exists only for the lockdep assertion and can be
  515. * ignored.
  516. */
  517. #define for_each_pwq(pwq, wq) \
  518. list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node, \
  519. lockdep_is_held(&(wq->mutex)))
  520. #ifdef CONFIG_DEBUG_OBJECTS_WORK
  521. static const struct debug_obj_descr work_debug_descr;
  522. static void *work_debug_hint(void *addr)
  523. {
  524. return ((struct work_struct *) addr)->func;
  525. }
  526. static bool work_is_static_object(void *addr)
  527. {
  528. struct work_struct *work = addr;
  529. return test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work));
  530. }
  531. /*
  532. * fixup_init is called when:
  533. * - an active object is initialized
  534. */
  535. static bool work_fixup_init(void *addr, enum debug_obj_state state)
  536. {
  537. struct work_struct *work = addr;
  538. switch (state) {
  539. case ODEBUG_STATE_ACTIVE:
  540. cancel_work_sync(work);
  541. debug_object_init(work, &work_debug_descr);
  542. return true;
  543. default:
  544. return false;
  545. }
  546. }
  547. /*
  548. * fixup_free is called when:
  549. * - an active object is freed
  550. */
  551. static bool work_fixup_free(void *addr, enum debug_obj_state state)
  552. {
  553. struct work_struct *work = addr;
  554. switch (state) {
  555. case ODEBUG_STATE_ACTIVE:
  556. cancel_work_sync(work);
  557. debug_object_free(work, &work_debug_descr);
  558. return true;
  559. default:
  560. return false;
  561. }
  562. }
  563. static const struct debug_obj_descr work_debug_descr = {
  564. .name = "work_struct",
  565. .debug_hint = work_debug_hint,
  566. .is_static_object = work_is_static_object,
  567. .fixup_init = work_fixup_init,
  568. .fixup_free = work_fixup_free,
  569. };
  570. static inline void debug_work_activate(struct work_struct *work)
  571. {
  572. debug_object_activate(work, &work_debug_descr);
  573. }
  574. static inline void debug_work_deactivate(struct work_struct *work)
  575. {
  576. debug_object_deactivate(work, &work_debug_descr);
  577. }
  578. void __init_work(struct work_struct *work, int onstack)
  579. {
  580. if (onstack)
  581. debug_object_init_on_stack(work, &work_debug_descr);
  582. else
  583. debug_object_init(work, &work_debug_descr);
  584. }
  585. EXPORT_SYMBOL_GPL(__init_work);
  586. void destroy_work_on_stack(struct work_struct *work)
  587. {
  588. debug_object_free(work, &work_debug_descr);
  589. }
  590. EXPORT_SYMBOL_GPL(destroy_work_on_stack);
  591. void destroy_delayed_work_on_stack(struct delayed_work *work)
  592. {
  593. destroy_timer_on_stack(&work->timer);
  594. debug_object_free(&work->work, &work_debug_descr);
  595. }
  596. EXPORT_SYMBOL_GPL(destroy_delayed_work_on_stack);
  597. #else
  598. static inline void debug_work_activate(struct work_struct *work) { }
  599. static inline void debug_work_deactivate(struct work_struct *work) { }
  600. #endif
  601. /**
  602. * worker_pool_assign_id - allocate ID and assign it to @pool
  603. * @pool: the pool pointer of interest
  604. *
  605. * Returns 0 if ID in [0, WORK_OFFQ_POOL_NONE) is allocated and assigned
  606. * successfully, -errno on failure.
  607. */
  608. static int worker_pool_assign_id(struct worker_pool *pool)
  609. {
  610. int ret;
  611. lockdep_assert_held(&wq_pool_mutex);
  612. ret = idr_alloc(&worker_pool_idr, pool, 0, WORK_OFFQ_POOL_NONE,
  613. GFP_KERNEL);
  614. if (ret >= 0) {
  615. pool->id = ret;
  616. return 0;
  617. }
  618. return ret;
  619. }
  620. static struct pool_workqueue __rcu **
  621. unbound_pwq_slot(struct workqueue_struct *wq, int cpu)
  622. {
  623. if (cpu >= 0)
  624. return per_cpu_ptr(wq->cpu_pwq, cpu);
  625. else
  626. return &wq->dfl_pwq;
  627. }
  628. /* @cpu < 0 for dfl_pwq */
  629. static struct pool_workqueue *unbound_pwq(struct workqueue_struct *wq, int cpu)
  630. {
  631. return rcu_dereference_check(*unbound_pwq_slot(wq, cpu),
  632. lockdep_is_held(&wq_pool_mutex) ||
  633. lockdep_is_held(&wq->mutex));
  634. }
  635. /**
  636. * unbound_effective_cpumask - effective cpumask of an unbound workqueue
  637. * @wq: workqueue of interest
  638. *
  639. * @wq->unbound_attrs->cpumask contains the cpumask requested by the user which
  640. * is masked with wq_unbound_cpumask to determine the effective cpumask. The
  641. * default pwq is always mapped to the pool with the current effective cpumask.
  642. */
  643. static struct cpumask *unbound_effective_cpumask(struct workqueue_struct *wq)
  644. {
  645. return unbound_pwq(wq, -1)->pool->attrs->__pod_cpumask;
  646. }
  647. static unsigned int work_color_to_flags(int color)
  648. {
  649. return color << WORK_STRUCT_COLOR_SHIFT;
  650. }
  651. static int get_work_color(unsigned long work_data)
  652. {
  653. return (work_data >> WORK_STRUCT_COLOR_SHIFT) &
  654. ((1 << WORK_STRUCT_COLOR_BITS) - 1);
  655. }
  656. static int work_next_color(int color)
  657. {
  658. return (color + 1) % WORK_NR_COLORS;
  659. }
  660. static unsigned long pool_offq_flags(struct worker_pool *pool)
  661. {
  662. return (pool->flags & POOL_BH) ? WORK_OFFQ_BH : 0;
  663. }
  664. /*
  665. * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
  666. * contain the pointer to the queued pwq. Once execution starts, the flag
  667. * is cleared and the high bits contain OFFQ flags and pool ID.
  668. *
  669. * set_work_pwq(), set_work_pool_and_clear_pending() and mark_work_canceling()
  670. * can be used to set the pwq, pool or clear work->data. These functions should
  671. * only be called while the work is owned - ie. while the PENDING bit is set.
  672. *
  673. * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
  674. * corresponding to a work. Pool is available once the work has been
  675. * queued anywhere after initialization until it is sync canceled. pwq is
  676. * available only while the work item is queued.
  677. */
  678. static inline void set_work_data(struct work_struct *work, unsigned long data)
  679. {
  680. WARN_ON_ONCE(!work_pending(work));
  681. atomic_long_set(&work->data, data | work_static(work));
  682. }
  683. static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
  684. unsigned long flags)
  685. {
  686. set_work_data(work, (unsigned long)pwq | WORK_STRUCT_PENDING |
  687. WORK_STRUCT_PWQ | flags);
  688. }
  689. static void set_work_pool_and_keep_pending(struct work_struct *work,
  690. int pool_id, unsigned long flags)
  691. {
  692. set_work_data(work, ((unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT) |
  693. WORK_STRUCT_PENDING | flags);
  694. }
  695. static void set_work_pool_and_clear_pending(struct work_struct *work,
  696. int pool_id, unsigned long flags)
  697. {
  698. /*
  699. * The following wmb is paired with the implied mb in
  700. * test_and_set_bit(PENDING) and ensures all updates to @work made
  701. * here are visible to and precede any updates by the next PENDING
  702. * owner.
  703. */
  704. smp_wmb();
  705. set_work_data(work, ((unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT) |
  706. flags);
  707. /*
  708. * The following mb guarantees that previous clear of a PENDING bit
  709. * will not be reordered with any speculative LOADS or STORES from
  710. * work->current_func, which is executed afterwards. This possible
  711. * reordering can lead to a missed execution on attempt to queue
  712. * the same @work. E.g. consider this case:
  713. *
  714. * CPU#0 CPU#1
  715. * ---------------------------- --------------------------------
  716. *
  717. * 1 STORE event_indicated
  718. * 2 queue_work_on() {
  719. * 3 test_and_set_bit(PENDING)
  720. * 4 } set_..._and_clear_pending() {
  721. * 5 set_work_data() # clear bit
  722. * 6 smp_mb()
  723. * 7 work->current_func() {
  724. * 8 LOAD event_indicated
  725. * }
  726. *
  727. * Without an explicit full barrier speculative LOAD on line 8 can
  728. * be executed before CPU#0 does STORE on line 1. If that happens,
  729. * CPU#0 observes the PENDING bit is still set and new execution of
  730. * a @work is not queued in a hope, that CPU#1 will eventually
  731. * finish the queued @work. Meanwhile CPU#1 does not see
  732. * event_indicated is set, because speculative LOAD was executed
  733. * before actual STORE.
  734. */
  735. smp_mb();
  736. }
  737. static inline struct pool_workqueue *work_struct_pwq(unsigned long data)
  738. {
  739. return (struct pool_workqueue *)(data & WORK_STRUCT_PWQ_MASK);
  740. }
  741. static struct pool_workqueue *get_work_pwq(struct work_struct *work)
  742. {
  743. unsigned long data = atomic_long_read(&work->data);
  744. if (data & WORK_STRUCT_PWQ)
  745. return work_struct_pwq(data);
  746. else
  747. return NULL;
  748. }
  749. /**
  750. * get_work_pool - return the worker_pool a given work was associated with
  751. * @work: the work item of interest
  752. *
  753. * Pools are created and destroyed under wq_pool_mutex, and allows read
  754. * access under RCU read lock. As such, this function should be
  755. * called under wq_pool_mutex or inside of a rcu_read_lock() region.
  756. *
  757. * All fields of the returned pool are accessible as long as the above
  758. * mentioned locking is in effect. If the returned pool needs to be used
  759. * beyond the critical section, the caller is responsible for ensuring the
  760. * returned pool is and stays online.
  761. *
  762. * Return: The worker_pool @work was last associated with. %NULL if none.
  763. */
  764. static struct worker_pool *get_work_pool(struct work_struct *work)
  765. {
  766. unsigned long data = atomic_long_read(&work->data);
  767. int pool_id;
  768. assert_rcu_or_pool_mutex();
  769. if (data & WORK_STRUCT_PWQ)
  770. return work_struct_pwq(data)->pool;
  771. pool_id = data >> WORK_OFFQ_POOL_SHIFT;
  772. if (pool_id == WORK_OFFQ_POOL_NONE)
  773. return NULL;
  774. return idr_find(&worker_pool_idr, pool_id);
  775. }
  776. static unsigned long shift_and_mask(unsigned long v, u32 shift, u32 bits)
  777. {
  778. return (v >> shift) & ((1U << bits) - 1);
  779. }
  780. static void work_offqd_unpack(struct work_offq_data *offqd, unsigned long data)
  781. {
  782. WARN_ON_ONCE(data & WORK_STRUCT_PWQ);
  783. offqd->pool_id = shift_and_mask(data, WORK_OFFQ_POOL_SHIFT,
  784. WORK_OFFQ_POOL_BITS);
  785. offqd->disable = shift_and_mask(data, WORK_OFFQ_DISABLE_SHIFT,
  786. WORK_OFFQ_DISABLE_BITS);
  787. offqd->flags = data & WORK_OFFQ_FLAG_MASK;
  788. }
  789. static unsigned long work_offqd_pack_flags(struct work_offq_data *offqd)
  790. {
  791. return ((unsigned long)offqd->disable << WORK_OFFQ_DISABLE_SHIFT) |
  792. ((unsigned long)offqd->flags);
  793. }
  794. /*
  795. * Policy functions. These define the policies on how the global worker
  796. * pools are managed. Unless noted otherwise, these functions assume that
  797. * they're being called with pool->lock held.
  798. */
  799. /*
  800. * Need to wake up a worker? Called from anything but currently
  801. * running workers.
  802. *
  803. * Note that, because unbound workers never contribute to nr_running, this
  804. * function will always return %true for unbound pools as long as the
  805. * worklist isn't empty.
  806. */
  807. static bool need_more_worker(struct worker_pool *pool)
  808. {
  809. return !list_empty(&pool->worklist) && !pool->nr_running;
  810. }
  811. /* Can I start working? Called from busy but !running workers. */
  812. static bool may_start_working(struct worker_pool *pool)
  813. {
  814. return pool->nr_idle;
  815. }
  816. /* Do I need to keep working? Called from currently running workers. */
  817. static bool keep_working(struct worker_pool *pool)
  818. {
  819. return !list_empty(&pool->worklist) && (pool->nr_running <= 1);
  820. }
  821. /* Do we need a new worker? Called from manager. */
  822. static bool need_to_create_worker(struct worker_pool *pool)
  823. {
  824. return need_more_worker(pool) && !may_start_working(pool);
  825. }
  826. /* Do we have too many workers and should some go away? */
  827. static bool too_many_workers(struct worker_pool *pool)
  828. {
  829. bool managing = pool->flags & POOL_MANAGER_ACTIVE;
  830. int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
  831. int nr_busy = pool->nr_workers - nr_idle;
  832. return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
  833. }
  834. /**
  835. * worker_set_flags - set worker flags and adjust nr_running accordingly
  836. * @worker: self
  837. * @flags: flags to set
  838. *
  839. * Set @flags in @worker->flags and adjust nr_running accordingly.
  840. */
  841. static inline void worker_set_flags(struct worker *worker, unsigned int flags)
  842. {
  843. struct worker_pool *pool = worker->pool;
  844. lockdep_assert_held(&pool->lock);
  845. /* If transitioning into NOT_RUNNING, adjust nr_running. */
  846. if ((flags & WORKER_NOT_RUNNING) &&
  847. !(worker->flags & WORKER_NOT_RUNNING)) {
  848. pool->nr_running--;
  849. }
  850. worker->flags |= flags;
  851. }
  852. /**
  853. * worker_clr_flags - clear worker flags and adjust nr_running accordingly
  854. * @worker: self
  855. * @flags: flags to clear
  856. *
  857. * Clear @flags in @worker->flags and adjust nr_running accordingly.
  858. */
  859. static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
  860. {
  861. struct worker_pool *pool = worker->pool;
  862. unsigned int oflags = worker->flags;
  863. lockdep_assert_held(&pool->lock);
  864. worker->flags &= ~flags;
  865. /*
  866. * If transitioning out of NOT_RUNNING, increment nr_running. Note
  867. * that the nested NOT_RUNNING is not a noop. NOT_RUNNING is mask
  868. * of multiple flags, not a single flag.
  869. */
  870. if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
  871. if (!(worker->flags & WORKER_NOT_RUNNING))
  872. pool->nr_running++;
  873. }
  874. /* Return the first idle worker. Called with pool->lock held. */
  875. static struct worker *first_idle_worker(struct worker_pool *pool)
  876. {
  877. if (unlikely(list_empty(&pool->idle_list)))
  878. return NULL;
  879. return list_first_entry(&pool->idle_list, struct worker, entry);
  880. }
  881. /**
  882. * worker_enter_idle - enter idle state
  883. * @worker: worker which is entering idle state
  884. *
  885. * @worker is entering idle state. Update stats and idle timer if
  886. * necessary.
  887. *
  888. * LOCKING:
  889. * raw_spin_lock_irq(pool->lock).
  890. */
  891. static void worker_enter_idle(struct worker *worker)
  892. {
  893. struct worker_pool *pool = worker->pool;
  894. if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
  895. WARN_ON_ONCE(!list_empty(&worker->entry) &&
  896. (worker->hentry.next || worker->hentry.pprev)))
  897. return;
  898. /* can't use worker_set_flags(), also called from create_worker() */
  899. worker->flags |= WORKER_IDLE;
  900. pool->nr_idle++;
  901. worker->last_active = jiffies;
  902. /* idle_list is LIFO */
  903. list_add(&worker->entry, &pool->idle_list);
  904. if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
  905. mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
  906. /* Sanity check nr_running. */
  907. WARN_ON_ONCE(pool->nr_workers == pool->nr_idle && pool->nr_running);
  908. }
  909. /**
  910. * worker_leave_idle - leave idle state
  911. * @worker: worker which is leaving idle state
  912. *
  913. * @worker is leaving idle state. Update stats.
  914. *
  915. * LOCKING:
  916. * raw_spin_lock_irq(pool->lock).
  917. */
  918. static void worker_leave_idle(struct worker *worker)
  919. {
  920. struct worker_pool *pool = worker->pool;
  921. if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
  922. return;
  923. worker_clr_flags(worker, WORKER_IDLE);
  924. pool->nr_idle--;
  925. list_del_init(&worker->entry);
  926. }
  927. /**
  928. * find_worker_executing_work - find worker which is executing a work
  929. * @pool: pool of interest
  930. * @work: work to find worker for
  931. *
  932. * Find a worker which is executing @work on @pool by searching
  933. * @pool->busy_hash which is keyed by the address of @work. For a worker
  934. * to match, its current execution should match the address of @work and
  935. * its work function. This is to avoid unwanted dependency between
  936. * unrelated work executions through a work item being recycled while still
  937. * being executed.
  938. *
  939. * This is a bit tricky. A work item may be freed once its execution
  940. * starts and nothing prevents the freed area from being recycled for
  941. * another work item. If the same work item address ends up being reused
  942. * before the original execution finishes, workqueue will identify the
  943. * recycled work item as currently executing and make it wait until the
  944. * current execution finishes, introducing an unwanted dependency.
  945. *
  946. * This function checks the work item address and work function to avoid
  947. * false positives. Note that this isn't complete as one may construct a
  948. * work function which can introduce dependency onto itself through a
  949. * recycled work item. Well, if somebody wants to shoot oneself in the
  950. * foot that badly, there's only so much we can do, and if such deadlock
  951. * actually occurs, it should be easy to locate the culprit work function.
  952. *
  953. * CONTEXT:
  954. * raw_spin_lock_irq(pool->lock).
  955. *
  956. * Return:
  957. * Pointer to worker which is executing @work if found, %NULL
  958. * otherwise.
  959. */
  960. static struct worker *find_worker_executing_work(struct worker_pool *pool,
  961. struct work_struct *work)
  962. {
  963. struct worker *worker;
  964. hash_for_each_possible(pool->busy_hash, worker, hentry,
  965. (unsigned long)work)
  966. if (worker->current_work == work &&
  967. worker->current_func == work->func)
  968. return worker;
  969. return NULL;
  970. }
  971. /**
  972. * move_linked_works - move linked works to a list
  973. * @work: start of series of works to be scheduled
  974. * @head: target list to append @work to
  975. * @nextp: out parameter for nested worklist walking
  976. *
  977. * Schedule linked works starting from @work to @head. Work series to be
  978. * scheduled starts at @work and includes any consecutive work with
  979. * WORK_STRUCT_LINKED set in its predecessor. See assign_work() for details on
  980. * @nextp.
  981. *
  982. * CONTEXT:
  983. * raw_spin_lock_irq(pool->lock).
  984. */
  985. static void move_linked_works(struct work_struct *work, struct list_head *head,
  986. struct work_struct **nextp)
  987. {
  988. struct work_struct *n;
  989. /*
  990. * Linked worklist will always end before the end of the list,
  991. * use NULL for list head.
  992. */
  993. list_for_each_entry_safe_from(work, n, NULL, entry) {
  994. list_move_tail(&work->entry, head);
  995. if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
  996. break;
  997. }
  998. /*
  999. * If we're already inside safe list traversal and have moved
  1000. * multiple works to the scheduled queue, the next position
  1001. * needs to be updated.
  1002. */
  1003. if (nextp)
  1004. *nextp = n;
  1005. }
  1006. /**
  1007. * assign_work - assign a work item and its linked work items to a worker
  1008. * @work: work to assign
  1009. * @worker: worker to assign to
  1010. * @nextp: out parameter for nested worklist walking
  1011. *
  1012. * Assign @work and its linked work items to @worker. If @work is already being
  1013. * executed by another worker in the same pool, it'll be punted there.
  1014. *
  1015. * If @nextp is not NULL, it's updated to point to the next work of the last
  1016. * scheduled work. This allows assign_work() to be nested inside
  1017. * list_for_each_entry_safe().
  1018. *
  1019. * Returns %true if @work was successfully assigned to @worker. %false if @work
  1020. * was punted to another worker already executing it.
  1021. */
  1022. static bool assign_work(struct work_struct *work, struct worker *worker,
  1023. struct work_struct **nextp)
  1024. {
  1025. struct worker_pool *pool = worker->pool;
  1026. struct worker *collision;
  1027. lockdep_assert_held(&pool->lock);
  1028. /*
  1029. * A single work shouldn't be executed concurrently by multiple workers.
  1030. * __queue_work() ensures that @work doesn't jump to a different pool
  1031. * while still running in the previous pool. Here, we should ensure that
  1032. * @work is not executed concurrently by multiple workers from the same
  1033. * pool. Check whether anyone is already processing the work. If so,
  1034. * defer the work to the currently executing one.
  1035. */
  1036. collision = find_worker_executing_work(pool, work);
  1037. if (unlikely(collision)) {
  1038. move_linked_works(work, &collision->scheduled, nextp);
  1039. return false;
  1040. }
  1041. move_linked_works(work, &worker->scheduled, nextp);
  1042. return true;
  1043. }
  1044. static struct irq_work *bh_pool_irq_work(struct worker_pool *pool)
  1045. {
  1046. int high = pool->attrs->nice == HIGHPRI_NICE_LEVEL ? 1 : 0;
  1047. return &per_cpu(bh_pool_irq_works, pool->cpu)[high];
  1048. }
  1049. static void kick_bh_pool(struct worker_pool *pool)
  1050. {
  1051. #ifdef CONFIG_SMP
  1052. /* see drain_dead_softirq_workfn() for BH_DRAINING */
  1053. if (unlikely(pool->cpu != smp_processor_id() &&
  1054. !(pool->flags & POOL_BH_DRAINING))) {
  1055. irq_work_queue_on(bh_pool_irq_work(pool), pool->cpu);
  1056. return;
  1057. }
  1058. #endif
  1059. if (pool->attrs->nice == HIGHPRI_NICE_LEVEL)
  1060. raise_softirq_irqoff(HI_SOFTIRQ);
  1061. else
  1062. raise_softirq_irqoff(TASKLET_SOFTIRQ);
  1063. }
  1064. /**
  1065. * kick_pool - wake up an idle worker if necessary
  1066. * @pool: pool to kick
  1067. *
  1068. * @pool may have pending work items. Wake up worker if necessary. Returns
  1069. * whether a worker was woken up.
  1070. */
  1071. static bool kick_pool(struct worker_pool *pool)
  1072. {
  1073. struct worker *worker = first_idle_worker(pool);
  1074. struct task_struct *p;
  1075. lockdep_assert_held(&pool->lock);
  1076. if (!need_more_worker(pool) || !worker)
  1077. return false;
  1078. if (pool->flags & POOL_BH) {
  1079. kick_bh_pool(pool);
  1080. return true;
  1081. }
  1082. p = worker->task;
  1083. #ifdef CONFIG_SMP
  1084. /*
  1085. * Idle @worker is about to execute @work and waking up provides an
  1086. * opportunity to migrate @worker at a lower cost by setting the task's
  1087. * wake_cpu field. Let's see if we want to move @worker to improve
  1088. * execution locality.
  1089. *
  1090. * We're waking the worker that went idle the latest and there's some
  1091. * chance that @worker is marked idle but hasn't gone off CPU yet. If
  1092. * so, setting the wake_cpu won't do anything. As this is a best-effort
  1093. * optimization and the race window is narrow, let's leave as-is for
  1094. * now. If this becomes pronounced, we can skip over workers which are
  1095. * still on cpu when picking an idle worker.
  1096. *
  1097. * If @pool has non-strict affinity, @worker might have ended up outside
  1098. * its affinity scope. Repatriate.
  1099. */
  1100. if (!pool->attrs->affn_strict &&
  1101. !cpumask_test_cpu(p->wake_cpu, pool->attrs->__pod_cpumask)) {
  1102. struct work_struct *work = list_first_entry(&pool->worklist,
  1103. struct work_struct, entry);
  1104. int wake_cpu = cpumask_any_and_distribute(pool->attrs->__pod_cpumask,
  1105. cpu_online_mask);
  1106. if (wake_cpu < nr_cpu_ids) {
  1107. p->wake_cpu = wake_cpu;
  1108. get_work_pwq(work)->stats[PWQ_STAT_REPATRIATED]++;
  1109. }
  1110. }
  1111. #endif
  1112. wake_up_process(p);
  1113. return true;
  1114. }
  1115. #ifdef CONFIG_WQ_CPU_INTENSIVE_REPORT
  1116. /*
  1117. * Concurrency-managed per-cpu work items that hog CPU for longer than
  1118. * wq_cpu_intensive_thresh_us trigger the automatic CPU_INTENSIVE mechanism,
  1119. * which prevents them from stalling other concurrency-managed work items. If a
  1120. * work function keeps triggering this mechanism, it's likely that the work item
  1121. * should be using an unbound workqueue instead.
  1122. *
  1123. * wq_cpu_intensive_report() tracks work functions which trigger such conditions
  1124. * and report them so that they can be examined and converted to use unbound
  1125. * workqueues as appropriate. To avoid flooding the console, each violating work
  1126. * function is tracked and reported with exponential backoff.
  1127. */
  1128. #define WCI_MAX_ENTS 128
  1129. struct wci_ent {
  1130. work_func_t func;
  1131. atomic64_t cnt;
  1132. struct hlist_node hash_node;
  1133. };
  1134. static struct wci_ent wci_ents[WCI_MAX_ENTS];
  1135. static int wci_nr_ents;
  1136. static DEFINE_RAW_SPINLOCK(wci_lock);
  1137. static DEFINE_HASHTABLE(wci_hash, ilog2(WCI_MAX_ENTS));
  1138. static struct wci_ent *wci_find_ent(work_func_t func)
  1139. {
  1140. struct wci_ent *ent;
  1141. hash_for_each_possible_rcu(wci_hash, ent, hash_node,
  1142. (unsigned long)func) {
  1143. if (ent->func == func)
  1144. return ent;
  1145. }
  1146. return NULL;
  1147. }
  1148. static void wq_cpu_intensive_report(work_func_t func)
  1149. {
  1150. struct wci_ent *ent;
  1151. restart:
  1152. ent = wci_find_ent(func);
  1153. if (ent) {
  1154. u64 cnt;
  1155. /*
  1156. * Start reporting from the warning_thresh and back off
  1157. * exponentially.
  1158. */
  1159. cnt = atomic64_inc_return_relaxed(&ent->cnt);
  1160. if (wq_cpu_intensive_warning_thresh &&
  1161. cnt >= wq_cpu_intensive_warning_thresh &&
  1162. is_power_of_2(cnt + 1 - wq_cpu_intensive_warning_thresh))
  1163. printk_deferred(KERN_WARNING "workqueue: %ps hogged CPU for >%luus %llu times, consider switching to WQ_UNBOUND\n",
  1164. ent->func, wq_cpu_intensive_thresh_us,
  1165. atomic64_read(&ent->cnt));
  1166. return;
  1167. }
  1168. /*
  1169. * @func is a new violation. Allocate a new entry for it. If wcn_ents[]
  1170. * is exhausted, something went really wrong and we probably made enough
  1171. * noise already.
  1172. */
  1173. if (wci_nr_ents >= WCI_MAX_ENTS)
  1174. return;
  1175. raw_spin_lock(&wci_lock);
  1176. if (wci_nr_ents >= WCI_MAX_ENTS) {
  1177. raw_spin_unlock(&wci_lock);
  1178. return;
  1179. }
  1180. if (wci_find_ent(func)) {
  1181. raw_spin_unlock(&wci_lock);
  1182. goto restart;
  1183. }
  1184. ent = &wci_ents[wci_nr_ents++];
  1185. ent->func = func;
  1186. atomic64_set(&ent->cnt, 0);
  1187. hash_add_rcu(wci_hash, &ent->hash_node, (unsigned long)func);
  1188. raw_spin_unlock(&wci_lock);
  1189. goto restart;
  1190. }
  1191. #else /* CONFIG_WQ_CPU_INTENSIVE_REPORT */
  1192. static void wq_cpu_intensive_report(work_func_t func) {}
  1193. #endif /* CONFIG_WQ_CPU_INTENSIVE_REPORT */
  1194. /**
  1195. * wq_worker_running - a worker is running again
  1196. * @task: task waking up
  1197. *
  1198. * This function is called when a worker returns from schedule()
  1199. */
  1200. void wq_worker_running(struct task_struct *task)
  1201. {
  1202. struct worker *worker = kthread_data(task);
  1203. if (!READ_ONCE(worker->sleeping))
  1204. return;
  1205. /*
  1206. * If preempted by unbind_workers() between the WORKER_NOT_RUNNING check
  1207. * and the nr_running increment below, we may ruin the nr_running reset
  1208. * and leave with an unexpected pool->nr_running == 1 on the newly unbound
  1209. * pool. Protect against such race.
  1210. */
  1211. preempt_disable();
  1212. if (!(worker->flags & WORKER_NOT_RUNNING))
  1213. worker->pool->nr_running++;
  1214. preempt_enable();
  1215. /*
  1216. * CPU intensive auto-detection cares about how long a work item hogged
  1217. * CPU without sleeping. Reset the starting timestamp on wakeup.
  1218. */
  1219. worker->current_at = worker->task->se.sum_exec_runtime;
  1220. WRITE_ONCE(worker->sleeping, 0);
  1221. }
  1222. /**
  1223. * wq_worker_sleeping - a worker is going to sleep
  1224. * @task: task going to sleep
  1225. *
  1226. * This function is called from schedule() when a busy worker is
  1227. * going to sleep.
  1228. */
  1229. void wq_worker_sleeping(struct task_struct *task)
  1230. {
  1231. struct worker *worker = kthread_data(task);
  1232. struct worker_pool *pool;
  1233. /*
  1234. * Rescuers, which may not have all the fields set up like normal
  1235. * workers, also reach here, let's not access anything before
  1236. * checking NOT_RUNNING.
  1237. */
  1238. if (worker->flags & WORKER_NOT_RUNNING)
  1239. return;
  1240. pool = worker->pool;
  1241. /* Return if preempted before wq_worker_running() was reached */
  1242. if (READ_ONCE(worker->sleeping))
  1243. return;
  1244. WRITE_ONCE(worker->sleeping, 1);
  1245. raw_spin_lock_irq(&pool->lock);
  1246. /*
  1247. * Recheck in case unbind_workers() preempted us. We don't
  1248. * want to decrement nr_running after the worker is unbound
  1249. * and nr_running has been reset.
  1250. */
  1251. if (worker->flags & WORKER_NOT_RUNNING) {
  1252. raw_spin_unlock_irq(&pool->lock);
  1253. return;
  1254. }
  1255. pool->nr_running--;
  1256. if (kick_pool(pool))
  1257. worker->current_pwq->stats[PWQ_STAT_CM_WAKEUP]++;
  1258. raw_spin_unlock_irq(&pool->lock);
  1259. }
  1260. /**
  1261. * wq_worker_tick - a scheduler tick occurred while a kworker is running
  1262. * @task: task currently running
  1263. *
  1264. * Called from sched_tick(). We're in the IRQ context and the current
  1265. * worker's fields which follow the 'K' locking rule can be accessed safely.
  1266. */
  1267. void wq_worker_tick(struct task_struct *task)
  1268. {
  1269. struct worker *worker = kthread_data(task);
  1270. struct pool_workqueue *pwq = worker->current_pwq;
  1271. struct worker_pool *pool = worker->pool;
  1272. if (!pwq)
  1273. return;
  1274. pwq->stats[PWQ_STAT_CPU_TIME] += TICK_USEC;
  1275. if (!wq_cpu_intensive_thresh_us)
  1276. return;
  1277. /*
  1278. * If the current worker is concurrency managed and hogged the CPU for
  1279. * longer than wq_cpu_intensive_thresh_us, it's automatically marked
  1280. * CPU_INTENSIVE to avoid stalling other concurrency-managed work items.
  1281. *
  1282. * Set @worker->sleeping means that @worker is in the process of
  1283. * switching out voluntarily and won't be contributing to
  1284. * @pool->nr_running until it wakes up. As wq_worker_sleeping() also
  1285. * decrements ->nr_running, setting CPU_INTENSIVE here can lead to
  1286. * double decrements. The task is releasing the CPU anyway. Let's skip.
  1287. * We probably want to make this prettier in the future.
  1288. */
  1289. if ((worker->flags & WORKER_NOT_RUNNING) || READ_ONCE(worker->sleeping) ||
  1290. worker->task->se.sum_exec_runtime - worker->current_at <
  1291. wq_cpu_intensive_thresh_us * NSEC_PER_USEC)
  1292. return;
  1293. raw_spin_lock(&pool->lock);
  1294. worker_set_flags(worker, WORKER_CPU_INTENSIVE);
  1295. wq_cpu_intensive_report(worker->current_func);
  1296. pwq->stats[PWQ_STAT_CPU_INTENSIVE]++;
  1297. if (kick_pool(pool))
  1298. pwq->stats[PWQ_STAT_CM_WAKEUP]++;
  1299. raw_spin_unlock(&pool->lock);
  1300. }
  1301. /**
  1302. * wq_worker_last_func - retrieve worker's last work function
  1303. * @task: Task to retrieve last work function of.
  1304. *
  1305. * Determine the last function a worker executed. This is called from
  1306. * the scheduler to get a worker's last known identity.
  1307. *
  1308. * CONTEXT:
  1309. * raw_spin_lock_irq(rq->lock)
  1310. *
  1311. * This function is called during schedule() when a kworker is going
  1312. * to sleep. It's used by psi to identify aggregation workers during
  1313. * dequeuing, to allow periodic aggregation to shut-off when that
  1314. * worker is the last task in the system or cgroup to go to sleep.
  1315. *
  1316. * As this function doesn't involve any workqueue-related locking, it
  1317. * only returns stable values when called from inside the scheduler's
  1318. * queuing and dequeuing paths, when @task, which must be a kworker,
  1319. * is guaranteed to not be processing any works.
  1320. *
  1321. * Return:
  1322. * The last work function %current executed as a worker, NULL if it
  1323. * hasn't executed any work yet.
  1324. */
  1325. work_func_t wq_worker_last_func(struct task_struct *task)
  1326. {
  1327. struct worker *worker = kthread_data(task);
  1328. return worker->last_func;
  1329. }
  1330. /**
  1331. * wq_node_nr_active - Determine wq_node_nr_active to use
  1332. * @wq: workqueue of interest
  1333. * @node: NUMA node, can be %NUMA_NO_NODE
  1334. *
  1335. * Determine wq_node_nr_active to use for @wq on @node. Returns:
  1336. *
  1337. * - %NULL for per-cpu workqueues as they don't need to use shared nr_active.
  1338. *
  1339. * - node_nr_active[nr_node_ids] if @node is %NUMA_NO_NODE.
  1340. *
  1341. * - Otherwise, node_nr_active[@node].
  1342. */
  1343. static struct wq_node_nr_active *wq_node_nr_active(struct workqueue_struct *wq,
  1344. int node)
  1345. {
  1346. if (!(wq->flags & WQ_UNBOUND))
  1347. return NULL;
  1348. if (node == NUMA_NO_NODE)
  1349. node = nr_node_ids;
  1350. return wq->node_nr_active[node];
  1351. }
  1352. /**
  1353. * wq_update_node_max_active - Update per-node max_actives to use
  1354. * @wq: workqueue to update
  1355. * @off_cpu: CPU that's going down, -1 if a CPU is not going down
  1356. *
  1357. * Update @wq->node_nr_active[]->max. @wq must be unbound. max_active is
  1358. * distributed among nodes according to the proportions of numbers of online
  1359. * cpus. The result is always between @wq->min_active and max_active.
  1360. */
  1361. static void wq_update_node_max_active(struct workqueue_struct *wq, int off_cpu)
  1362. {
  1363. struct cpumask *effective = unbound_effective_cpumask(wq);
  1364. int min_active = READ_ONCE(wq->min_active);
  1365. int max_active = READ_ONCE(wq->max_active);
  1366. int total_cpus, node;
  1367. lockdep_assert_held(&wq->mutex);
  1368. if (!wq_topo_initialized)
  1369. return;
  1370. if (off_cpu >= 0 && !cpumask_test_cpu(off_cpu, effective))
  1371. off_cpu = -1;
  1372. total_cpus = cpumask_weight_and(effective, cpu_online_mask);
  1373. if (off_cpu >= 0)
  1374. total_cpus--;
  1375. /* If all CPUs of the wq get offline, use the default values */
  1376. if (unlikely(!total_cpus)) {
  1377. for_each_node(node)
  1378. wq_node_nr_active(wq, node)->max = min_active;
  1379. wq_node_nr_active(wq, NUMA_NO_NODE)->max = max_active;
  1380. return;
  1381. }
  1382. for_each_node(node) {
  1383. int node_cpus;
  1384. node_cpus = cpumask_weight_and(effective, cpumask_of_node(node));
  1385. if (off_cpu >= 0 && cpu_to_node(off_cpu) == node)
  1386. node_cpus--;
  1387. wq_node_nr_active(wq, node)->max =
  1388. clamp(DIV_ROUND_UP(max_active * node_cpus, total_cpus),
  1389. min_active, max_active);
  1390. }
  1391. wq_node_nr_active(wq, NUMA_NO_NODE)->max = max_active;
  1392. }
  1393. /**
  1394. * get_pwq - get an extra reference on the specified pool_workqueue
  1395. * @pwq: pool_workqueue to get
  1396. *
  1397. * Obtain an extra reference on @pwq. The caller should guarantee that
  1398. * @pwq has positive refcnt and be holding the matching pool->lock.
  1399. */
  1400. static void get_pwq(struct pool_workqueue *pwq)
  1401. {
  1402. lockdep_assert_held(&pwq->pool->lock);
  1403. WARN_ON_ONCE(pwq->refcnt <= 0);
  1404. pwq->refcnt++;
  1405. }
  1406. /**
  1407. * put_pwq - put a pool_workqueue reference
  1408. * @pwq: pool_workqueue to put
  1409. *
  1410. * Drop a reference of @pwq. If its refcnt reaches zero, schedule its
  1411. * destruction. The caller should be holding the matching pool->lock.
  1412. */
  1413. static void put_pwq(struct pool_workqueue *pwq)
  1414. {
  1415. lockdep_assert_held(&pwq->pool->lock);
  1416. if (likely(--pwq->refcnt))
  1417. return;
  1418. /*
  1419. * @pwq can't be released under pool->lock, bounce to a dedicated
  1420. * kthread_worker to avoid A-A deadlocks.
  1421. */
  1422. kthread_queue_work(pwq_release_worker, &pwq->release_work);
  1423. }
  1424. /**
  1425. * put_pwq_unlocked - put_pwq() with surrounding pool lock/unlock
  1426. * @pwq: pool_workqueue to put (can be %NULL)
  1427. *
  1428. * put_pwq() with locking. This function also allows %NULL @pwq.
  1429. */
  1430. static void put_pwq_unlocked(struct pool_workqueue *pwq)
  1431. {
  1432. if (pwq) {
  1433. /*
  1434. * As both pwqs and pools are RCU protected, the
  1435. * following lock operations are safe.
  1436. */
  1437. raw_spin_lock_irq(&pwq->pool->lock);
  1438. put_pwq(pwq);
  1439. raw_spin_unlock_irq(&pwq->pool->lock);
  1440. }
  1441. }
  1442. static bool pwq_is_empty(struct pool_workqueue *pwq)
  1443. {
  1444. return !pwq->nr_active && list_empty(&pwq->inactive_works);
  1445. }
  1446. static void __pwq_activate_work(struct pool_workqueue *pwq,
  1447. struct work_struct *work)
  1448. {
  1449. unsigned long *wdb = work_data_bits(work);
  1450. WARN_ON_ONCE(!(*wdb & WORK_STRUCT_INACTIVE));
  1451. trace_workqueue_activate_work(work);
  1452. if (list_empty(&pwq->pool->worklist))
  1453. pwq->pool->watchdog_ts = jiffies;
  1454. move_linked_works(work, &pwq->pool->worklist, NULL);
  1455. __clear_bit(WORK_STRUCT_INACTIVE_BIT, wdb);
  1456. }
  1457. static bool tryinc_node_nr_active(struct wq_node_nr_active *nna)
  1458. {
  1459. int max = READ_ONCE(nna->max);
  1460. while (true) {
  1461. int old, tmp;
  1462. old = atomic_read(&nna->nr);
  1463. if (old >= max)
  1464. return false;
  1465. tmp = atomic_cmpxchg_relaxed(&nna->nr, old, old + 1);
  1466. if (tmp == old)
  1467. return true;
  1468. }
  1469. }
  1470. /**
  1471. * pwq_tryinc_nr_active - Try to increment nr_active for a pwq
  1472. * @pwq: pool_workqueue of interest
  1473. * @fill: max_active may have increased, try to increase concurrency level
  1474. *
  1475. * Try to increment nr_active for @pwq. Returns %true if an nr_active count is
  1476. * successfully obtained. %false otherwise.
  1477. */
  1478. static bool pwq_tryinc_nr_active(struct pool_workqueue *pwq, bool fill)
  1479. {
  1480. struct workqueue_struct *wq = pwq->wq;
  1481. struct worker_pool *pool = pwq->pool;
  1482. struct wq_node_nr_active *nna = wq_node_nr_active(wq, pool->node);
  1483. bool obtained = false;
  1484. lockdep_assert_held(&pool->lock);
  1485. if (!nna) {
  1486. /* BH or per-cpu workqueue, pwq->nr_active is sufficient */
  1487. obtained = pwq->nr_active < READ_ONCE(wq->max_active);
  1488. goto out;
  1489. }
  1490. if (unlikely(pwq->plugged))
  1491. return false;
  1492. /*
  1493. * Unbound workqueue uses per-node shared nr_active $nna. If @pwq is
  1494. * already waiting on $nna, pwq_dec_nr_active() will maintain the
  1495. * concurrency level. Don't jump the line.
  1496. *
  1497. * We need to ignore the pending test after max_active has increased as
  1498. * pwq_dec_nr_active() can only maintain the concurrency level but not
  1499. * increase it. This is indicated by @fill.
  1500. */
  1501. if (!list_empty(&pwq->pending_node) && likely(!fill))
  1502. goto out;
  1503. obtained = tryinc_node_nr_active(nna);
  1504. if (obtained)
  1505. goto out;
  1506. /*
  1507. * Lockless acquisition failed. Lock, add ourself to $nna->pending_pwqs
  1508. * and try again. The smp_mb() is paired with the implied memory barrier
  1509. * of atomic_dec_return() in pwq_dec_nr_active() to ensure that either
  1510. * we see the decremented $nna->nr or they see non-empty
  1511. * $nna->pending_pwqs.
  1512. */
  1513. raw_spin_lock(&nna->lock);
  1514. if (list_empty(&pwq->pending_node))
  1515. list_add_tail(&pwq->pending_node, &nna->pending_pwqs);
  1516. else if (likely(!fill))
  1517. goto out_unlock;
  1518. smp_mb();
  1519. obtained = tryinc_node_nr_active(nna);
  1520. /*
  1521. * If @fill, @pwq might have already been pending. Being spuriously
  1522. * pending in cold paths doesn't affect anything. Let's leave it be.
  1523. */
  1524. if (obtained && likely(!fill))
  1525. list_del_init(&pwq->pending_node);
  1526. out_unlock:
  1527. raw_spin_unlock(&nna->lock);
  1528. out:
  1529. if (obtained)
  1530. pwq->nr_active++;
  1531. return obtained;
  1532. }
  1533. /**
  1534. * pwq_activate_first_inactive - Activate the first inactive work item on a pwq
  1535. * @pwq: pool_workqueue of interest
  1536. * @fill: max_active may have increased, try to increase concurrency level
  1537. *
  1538. * Activate the first inactive work item of @pwq if available and allowed by
  1539. * max_active limit.
  1540. *
  1541. * Returns %true if an inactive work item has been activated. %false if no
  1542. * inactive work item is found or max_active limit is reached.
  1543. */
  1544. static bool pwq_activate_first_inactive(struct pool_workqueue *pwq, bool fill)
  1545. {
  1546. struct work_struct *work =
  1547. list_first_entry_or_null(&pwq->inactive_works,
  1548. struct work_struct, entry);
  1549. if (work && pwq_tryinc_nr_active(pwq, fill)) {
  1550. __pwq_activate_work(pwq, work);
  1551. return true;
  1552. } else {
  1553. return false;
  1554. }
  1555. }
  1556. /**
  1557. * unplug_oldest_pwq - unplug the oldest pool_workqueue
  1558. * @wq: workqueue_struct where its oldest pwq is to be unplugged
  1559. *
  1560. * This function should only be called for ordered workqueues where only the
  1561. * oldest pwq is unplugged, the others are plugged to suspend execution to
  1562. * ensure proper work item ordering::
  1563. *
  1564. * dfl_pwq --------------+ [P] - plugged
  1565. * |
  1566. * v
  1567. * pwqs -> A -> B [P] -> C [P] (newest)
  1568. * | | |
  1569. * 1 3 5
  1570. * | | |
  1571. * 2 4 6
  1572. *
  1573. * When the oldest pwq is drained and removed, this function should be called
  1574. * to unplug the next oldest one to start its work item execution. Note that
  1575. * pwq's are linked into wq->pwqs with the oldest first, so the first one in
  1576. * the list is the oldest.
  1577. */
  1578. static void unplug_oldest_pwq(struct workqueue_struct *wq)
  1579. {
  1580. struct pool_workqueue *pwq;
  1581. lockdep_assert_held(&wq->mutex);
  1582. /* Caller should make sure that pwqs isn't empty before calling */
  1583. pwq = list_first_entry_or_null(&wq->pwqs, struct pool_workqueue,
  1584. pwqs_node);
  1585. raw_spin_lock_irq(&pwq->pool->lock);
  1586. if (pwq->plugged) {
  1587. pwq->plugged = false;
  1588. if (pwq_activate_first_inactive(pwq, true))
  1589. kick_pool(pwq->pool);
  1590. }
  1591. raw_spin_unlock_irq(&pwq->pool->lock);
  1592. }
  1593. /**
  1594. * node_activate_pending_pwq - Activate a pending pwq on a wq_node_nr_active
  1595. * @nna: wq_node_nr_active to activate a pending pwq for
  1596. * @caller_pool: worker_pool the caller is locking
  1597. *
  1598. * Activate a pwq in @nna->pending_pwqs. Called with @caller_pool locked.
  1599. * @caller_pool may be unlocked and relocked to lock other worker_pools.
  1600. */
  1601. static void node_activate_pending_pwq(struct wq_node_nr_active *nna,
  1602. struct worker_pool *caller_pool)
  1603. {
  1604. struct worker_pool *locked_pool = caller_pool;
  1605. struct pool_workqueue *pwq;
  1606. struct work_struct *work;
  1607. lockdep_assert_held(&caller_pool->lock);
  1608. raw_spin_lock(&nna->lock);
  1609. retry:
  1610. pwq = list_first_entry_or_null(&nna->pending_pwqs,
  1611. struct pool_workqueue, pending_node);
  1612. if (!pwq)
  1613. goto out_unlock;
  1614. /*
  1615. * If @pwq is for a different pool than @locked_pool, we need to lock
  1616. * @pwq->pool->lock. Let's trylock first. If unsuccessful, do the unlock
  1617. * / lock dance. For that, we also need to release @nna->lock as it's
  1618. * nested inside pool locks.
  1619. */
  1620. if (pwq->pool != locked_pool) {
  1621. raw_spin_unlock(&locked_pool->lock);
  1622. locked_pool = pwq->pool;
  1623. if (!raw_spin_trylock(&locked_pool->lock)) {
  1624. raw_spin_unlock(&nna->lock);
  1625. raw_spin_lock(&locked_pool->lock);
  1626. raw_spin_lock(&nna->lock);
  1627. goto retry;
  1628. }
  1629. }
  1630. /*
  1631. * $pwq may not have any inactive work items due to e.g. cancellations.
  1632. * Drop it from pending_pwqs and see if there's another one.
  1633. */
  1634. work = list_first_entry_or_null(&pwq->inactive_works,
  1635. struct work_struct, entry);
  1636. if (!work) {
  1637. list_del_init(&pwq->pending_node);
  1638. goto retry;
  1639. }
  1640. /*
  1641. * Acquire an nr_active count and activate the inactive work item. If
  1642. * $pwq still has inactive work items, rotate it to the end of the
  1643. * pending_pwqs so that we round-robin through them. This means that
  1644. * inactive work items are not activated in queueing order which is fine
  1645. * given that there has never been any ordering across different pwqs.
  1646. */
  1647. if (likely(tryinc_node_nr_active(nna))) {
  1648. pwq->nr_active++;
  1649. __pwq_activate_work(pwq, work);
  1650. if (list_empty(&pwq->inactive_works))
  1651. list_del_init(&pwq->pending_node);
  1652. else
  1653. list_move_tail(&pwq->pending_node, &nna->pending_pwqs);
  1654. /* if activating a foreign pool, make sure it's running */
  1655. if (pwq->pool != caller_pool)
  1656. kick_pool(pwq->pool);
  1657. }
  1658. out_unlock:
  1659. raw_spin_unlock(&nna->lock);
  1660. if (locked_pool != caller_pool) {
  1661. raw_spin_unlock(&locked_pool->lock);
  1662. raw_spin_lock(&caller_pool->lock);
  1663. }
  1664. }
  1665. /**
  1666. * pwq_dec_nr_active - Retire an active count
  1667. * @pwq: pool_workqueue of interest
  1668. *
  1669. * Decrement @pwq's nr_active and try to activate the first inactive work item.
  1670. * For unbound workqueues, this function may temporarily drop @pwq->pool->lock.
  1671. */
  1672. static void pwq_dec_nr_active(struct pool_workqueue *pwq)
  1673. {
  1674. struct worker_pool *pool = pwq->pool;
  1675. struct wq_node_nr_active *nna = wq_node_nr_active(pwq->wq, pool->node);
  1676. lockdep_assert_held(&pool->lock);
  1677. /*
  1678. * @pwq->nr_active should be decremented for both percpu and unbound
  1679. * workqueues.
  1680. */
  1681. pwq->nr_active--;
  1682. /*
  1683. * For a percpu workqueue, it's simple. Just need to kick the first
  1684. * inactive work item on @pwq itself.
  1685. */
  1686. if (!nna) {
  1687. pwq_activate_first_inactive(pwq, false);
  1688. return;
  1689. }
  1690. /*
  1691. * If @pwq is for an unbound workqueue, it's more complicated because
  1692. * multiple pwqs and pools may be sharing the nr_active count. When a
  1693. * pwq needs to wait for an nr_active count, it puts itself on
  1694. * $nna->pending_pwqs. The following atomic_dec_return()'s implied
  1695. * memory barrier is paired with smp_mb() in pwq_tryinc_nr_active() to
  1696. * guarantee that either we see non-empty pending_pwqs or they see
  1697. * decremented $nna->nr.
  1698. *
  1699. * $nna->max may change as CPUs come online/offline and @pwq->wq's
  1700. * max_active gets updated. However, it is guaranteed to be equal to or
  1701. * larger than @pwq->wq->min_active which is above zero unless freezing.
  1702. * This maintains the forward progress guarantee.
  1703. */
  1704. if (atomic_dec_return(&nna->nr) >= READ_ONCE(nna->max))
  1705. return;
  1706. if (!list_empty(&nna->pending_pwqs))
  1707. node_activate_pending_pwq(nna, pool);
  1708. }
  1709. /**
  1710. * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
  1711. * @pwq: pwq of interest
  1712. * @work_data: work_data of work which left the queue
  1713. *
  1714. * A work either has completed or is removed from pending queue,
  1715. * decrement nr_in_flight of its pwq and handle workqueue flushing.
  1716. *
  1717. * NOTE:
  1718. * For unbound workqueues, this function may temporarily drop @pwq->pool->lock
  1719. * and thus should be called after all other state updates for the in-flight
  1720. * work item is complete.
  1721. *
  1722. * CONTEXT:
  1723. * raw_spin_lock_irq(pool->lock).
  1724. */
  1725. static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, unsigned long work_data)
  1726. {
  1727. int color = get_work_color(work_data);
  1728. if (!(work_data & WORK_STRUCT_INACTIVE))
  1729. pwq_dec_nr_active(pwq);
  1730. pwq->nr_in_flight[color]--;
  1731. /* is flush in progress and are we at the flushing tip? */
  1732. if (likely(pwq->flush_color != color))
  1733. goto out_put;
  1734. /* are there still in-flight works? */
  1735. if (pwq->nr_in_flight[color])
  1736. goto out_put;
  1737. /* this pwq is done, clear flush_color */
  1738. pwq->flush_color = -1;
  1739. /*
  1740. * If this was the last pwq, wake up the first flusher. It
  1741. * will handle the rest.
  1742. */
  1743. if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
  1744. complete(&pwq->wq->first_flusher->done);
  1745. out_put:
  1746. put_pwq(pwq);
  1747. }
  1748. /**
  1749. * try_to_grab_pending - steal work item from worklist and disable irq
  1750. * @work: work item to steal
  1751. * @cflags: %WORK_CANCEL_ flags
  1752. * @irq_flags: place to store irq state
  1753. *
  1754. * Try to grab PENDING bit of @work. This function can handle @work in any
  1755. * stable state - idle, on timer or on worklist.
  1756. *
  1757. * Return:
  1758. *
  1759. * ======== ================================================================
  1760. * 1 if @work was pending and we successfully stole PENDING
  1761. * 0 if @work was idle and we claimed PENDING
  1762. * -EAGAIN if PENDING couldn't be grabbed at the moment, safe to busy-retry
  1763. * ======== ================================================================
  1764. *
  1765. * Note:
  1766. * On >= 0 return, the caller owns @work's PENDING bit. To avoid getting
  1767. * interrupted while holding PENDING and @work off queue, irq must be
  1768. * disabled on entry. This, combined with delayed_work->timer being
  1769. * irqsafe, ensures that we return -EAGAIN for finite short period of time.
  1770. *
  1771. * On successful return, >= 0, irq is disabled and the caller is
  1772. * responsible for releasing it using local_irq_restore(*@irq_flags).
  1773. *
  1774. * This function is safe to call from any context including IRQ handler.
  1775. */
  1776. static int try_to_grab_pending(struct work_struct *work, u32 cflags,
  1777. unsigned long *irq_flags)
  1778. {
  1779. struct worker_pool *pool;
  1780. struct pool_workqueue *pwq;
  1781. local_irq_save(*irq_flags);
  1782. /* try to steal the timer if it exists */
  1783. if (cflags & WORK_CANCEL_DELAYED) {
  1784. struct delayed_work *dwork = to_delayed_work(work);
  1785. /*
  1786. * dwork->timer is irqsafe. If del_timer() fails, it's
  1787. * guaranteed that the timer is not queued anywhere and not
  1788. * running on the local CPU.
  1789. */
  1790. if (likely(del_timer(&dwork->timer)))
  1791. return 1;
  1792. }
  1793. /* try to claim PENDING the normal way */
  1794. if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
  1795. return 0;
  1796. rcu_read_lock();
  1797. /*
  1798. * The queueing is in progress, or it is already queued. Try to
  1799. * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
  1800. */
  1801. pool = get_work_pool(work);
  1802. if (!pool)
  1803. goto fail;
  1804. raw_spin_lock(&pool->lock);
  1805. /*
  1806. * work->data is guaranteed to point to pwq only while the work
  1807. * item is queued on pwq->wq, and both updating work->data to point
  1808. * to pwq on queueing and to pool on dequeueing are done under
  1809. * pwq->pool->lock. This in turn guarantees that, if work->data
  1810. * points to pwq which is associated with a locked pool, the work
  1811. * item is currently queued on that pool.
  1812. */
  1813. pwq = get_work_pwq(work);
  1814. if (pwq && pwq->pool == pool) {
  1815. unsigned long work_data = *work_data_bits(work);
  1816. debug_work_deactivate(work);
  1817. /*
  1818. * A cancelable inactive work item must be in the
  1819. * pwq->inactive_works since a queued barrier can't be
  1820. * canceled (see the comments in insert_wq_barrier()).
  1821. *
  1822. * An inactive work item cannot be deleted directly because
  1823. * it might have linked barrier work items which, if left
  1824. * on the inactive_works list, will confuse pwq->nr_active
  1825. * management later on and cause stall. Move the linked
  1826. * barrier work items to the worklist when deleting the grabbed
  1827. * item. Also keep WORK_STRUCT_INACTIVE in work_data, so that
  1828. * it doesn't participate in nr_active management in later
  1829. * pwq_dec_nr_in_flight().
  1830. */
  1831. if (work_data & WORK_STRUCT_INACTIVE)
  1832. move_linked_works(work, &pwq->pool->worklist, NULL);
  1833. list_del_init(&work->entry);
  1834. /*
  1835. * work->data points to pwq iff queued. Let's point to pool. As
  1836. * this destroys work->data needed by the next step, stash it.
  1837. */
  1838. set_work_pool_and_keep_pending(work, pool->id,
  1839. pool_offq_flags(pool));
  1840. /* must be the last step, see the function comment */
  1841. pwq_dec_nr_in_flight(pwq, work_data);
  1842. raw_spin_unlock(&pool->lock);
  1843. rcu_read_unlock();
  1844. return 1;
  1845. }
  1846. raw_spin_unlock(&pool->lock);
  1847. fail:
  1848. rcu_read_unlock();
  1849. local_irq_restore(*irq_flags);
  1850. return -EAGAIN;
  1851. }
  1852. /**
  1853. * work_grab_pending - steal work item from worklist and disable irq
  1854. * @work: work item to steal
  1855. * @cflags: %WORK_CANCEL_ flags
  1856. * @irq_flags: place to store IRQ state
  1857. *
  1858. * Grab PENDING bit of @work. @work can be in any stable state - idle, on timer
  1859. * or on worklist.
  1860. *
  1861. * Can be called from any context. IRQ is disabled on return with IRQ state
  1862. * stored in *@irq_flags. The caller is responsible for re-enabling it using
  1863. * local_irq_restore().
  1864. *
  1865. * Returns %true if @work was pending. %false if idle.
  1866. */
  1867. static bool work_grab_pending(struct work_struct *work, u32 cflags,
  1868. unsigned long *irq_flags)
  1869. {
  1870. int ret;
  1871. while (true) {
  1872. ret = try_to_grab_pending(work, cflags, irq_flags);
  1873. if (ret >= 0)
  1874. return ret;
  1875. cpu_relax();
  1876. }
  1877. }
  1878. /**
  1879. * insert_work - insert a work into a pool
  1880. * @pwq: pwq @work belongs to
  1881. * @work: work to insert
  1882. * @head: insertion point
  1883. * @extra_flags: extra WORK_STRUCT_* flags to set
  1884. *
  1885. * Insert @work which belongs to @pwq after @head. @extra_flags is or'd to
  1886. * work_struct flags.
  1887. *
  1888. * CONTEXT:
  1889. * raw_spin_lock_irq(pool->lock).
  1890. */
  1891. static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
  1892. struct list_head *head, unsigned int extra_flags)
  1893. {
  1894. debug_work_activate(work);
  1895. /* record the work call stack in order to print it in KASAN reports */
  1896. kasan_record_aux_stack_noalloc(work);
  1897. /* we own @work, set data and link */
  1898. set_work_pwq(work, pwq, extra_flags);
  1899. list_add_tail(&work->entry, head);
  1900. get_pwq(pwq);
  1901. }
  1902. /*
  1903. * Test whether @work is being queued from another work executing on the
  1904. * same workqueue.
  1905. */
  1906. static bool is_chained_work(struct workqueue_struct *wq)
  1907. {
  1908. struct worker *worker;
  1909. worker = current_wq_worker();
  1910. /*
  1911. * Return %true iff I'm a worker executing a work item on @wq. If
  1912. * I'm @worker, it's safe to dereference it without locking.
  1913. */
  1914. return worker && worker->current_pwq->wq == wq;
  1915. }
  1916. /*
  1917. * When queueing an unbound work item to a wq, prefer local CPU if allowed
  1918. * by wq_unbound_cpumask. Otherwise, round robin among the allowed ones to
  1919. * avoid perturbing sensitive tasks.
  1920. */
  1921. static int wq_select_unbound_cpu(int cpu)
  1922. {
  1923. int new_cpu;
  1924. if (likely(!wq_debug_force_rr_cpu)) {
  1925. if (cpumask_test_cpu(cpu, wq_unbound_cpumask))
  1926. return cpu;
  1927. } else {
  1928. pr_warn_once("workqueue: round-robin CPU selection forced, expect performance impact\n");
  1929. }
  1930. new_cpu = __this_cpu_read(wq_rr_cpu_last);
  1931. new_cpu = cpumask_next_and(new_cpu, wq_unbound_cpumask, cpu_online_mask);
  1932. if (unlikely(new_cpu >= nr_cpu_ids)) {
  1933. new_cpu = cpumask_first_and(wq_unbound_cpumask, cpu_online_mask);
  1934. if (unlikely(new_cpu >= nr_cpu_ids))
  1935. return cpu;
  1936. }
  1937. __this_cpu_write(wq_rr_cpu_last, new_cpu);
  1938. return new_cpu;
  1939. }
  1940. static void __queue_work(int cpu, struct workqueue_struct *wq,
  1941. struct work_struct *work)
  1942. {
  1943. struct pool_workqueue *pwq;
  1944. struct worker_pool *last_pool, *pool;
  1945. unsigned int work_flags;
  1946. unsigned int req_cpu = cpu;
  1947. /*
  1948. * While a work item is PENDING && off queue, a task trying to
  1949. * steal the PENDING will busy-loop waiting for it to either get
  1950. * queued or lose PENDING. Grabbing PENDING and queueing should
  1951. * happen with IRQ disabled.
  1952. */
  1953. lockdep_assert_irqs_disabled();
  1954. /*
  1955. * For a draining wq, only works from the same workqueue are
  1956. * allowed. The __WQ_DESTROYING helps to spot the issue that
  1957. * queues a new work item to a wq after destroy_workqueue(wq).
  1958. */
  1959. if (unlikely(wq->flags & (__WQ_DESTROYING | __WQ_DRAINING) &&
  1960. WARN_ON_ONCE(!is_chained_work(wq))))
  1961. return;
  1962. rcu_read_lock();
  1963. retry:
  1964. /* pwq which will be used unless @work is executing elsewhere */
  1965. if (req_cpu == WORK_CPU_UNBOUND) {
  1966. if (wq->flags & WQ_UNBOUND)
  1967. cpu = wq_select_unbound_cpu(raw_smp_processor_id());
  1968. else
  1969. cpu = raw_smp_processor_id();
  1970. }
  1971. pwq = rcu_dereference(*per_cpu_ptr(wq->cpu_pwq, cpu));
  1972. pool = pwq->pool;
  1973. /*
  1974. * If @work was previously on a different pool, it might still be
  1975. * running there, in which case the work needs to be queued on that
  1976. * pool to guarantee non-reentrancy.
  1977. *
  1978. * For ordered workqueue, work items must be queued on the newest pwq
  1979. * for accurate order management. Guaranteed order also guarantees
  1980. * non-reentrancy. See the comments above unplug_oldest_pwq().
  1981. */
  1982. last_pool = get_work_pool(work);
  1983. if (last_pool && last_pool != pool && !(wq->flags & __WQ_ORDERED)) {
  1984. struct worker *worker;
  1985. raw_spin_lock(&last_pool->lock);
  1986. worker = find_worker_executing_work(last_pool, work);
  1987. if (worker && worker->current_pwq->wq == wq) {
  1988. pwq = worker->current_pwq;
  1989. pool = pwq->pool;
  1990. WARN_ON_ONCE(pool != last_pool);
  1991. } else {
  1992. /* meh... not running there, queue here */
  1993. raw_spin_unlock(&last_pool->lock);
  1994. raw_spin_lock(&pool->lock);
  1995. }
  1996. } else {
  1997. raw_spin_lock(&pool->lock);
  1998. }
  1999. /*
  2000. * pwq is determined and locked. For unbound pools, we could have raced
  2001. * with pwq release and it could already be dead. If its refcnt is zero,
  2002. * repeat pwq selection. Note that unbound pwqs never die without
  2003. * another pwq replacing it in cpu_pwq or while work items are executing
  2004. * on it, so the retrying is guaranteed to make forward-progress.
  2005. */
  2006. if (unlikely(!pwq->refcnt)) {
  2007. if (wq->flags & WQ_UNBOUND) {
  2008. raw_spin_unlock(&pool->lock);
  2009. cpu_relax();
  2010. goto retry;
  2011. }
  2012. /* oops */
  2013. WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
  2014. wq->name, cpu);
  2015. }
  2016. /* pwq determined, queue */
  2017. trace_workqueue_queue_work(req_cpu, pwq, work);
  2018. if (WARN_ON(!list_empty(&work->entry)))
  2019. goto out;
  2020. pwq->nr_in_flight[pwq->work_color]++;
  2021. work_flags = work_color_to_flags(pwq->work_color);
  2022. /*
  2023. * Limit the number of concurrently active work items to max_active.
  2024. * @work must also queue behind existing inactive work items to maintain
  2025. * ordering when max_active changes. See wq_adjust_max_active().
  2026. */
  2027. if (list_empty(&pwq->inactive_works) && pwq_tryinc_nr_active(pwq, false)) {
  2028. if (list_empty(&pool->worklist))
  2029. pool->watchdog_ts = jiffies;
  2030. trace_workqueue_activate_work(work);
  2031. insert_work(pwq, work, &pool->worklist, work_flags);
  2032. kick_pool(pool);
  2033. } else {
  2034. work_flags |= WORK_STRUCT_INACTIVE;
  2035. insert_work(pwq, work, &pwq->inactive_works, work_flags);
  2036. }
  2037. out:
  2038. raw_spin_unlock(&pool->lock);
  2039. rcu_read_unlock();
  2040. }
  2041. static bool clear_pending_if_disabled(struct work_struct *work)
  2042. {
  2043. unsigned long data = *work_data_bits(work);
  2044. struct work_offq_data offqd;
  2045. if (likely((data & WORK_STRUCT_PWQ) ||
  2046. !(data & WORK_OFFQ_DISABLE_MASK)))
  2047. return false;
  2048. work_offqd_unpack(&offqd, data);
  2049. set_work_pool_and_clear_pending(work, offqd.pool_id,
  2050. work_offqd_pack_flags(&offqd));
  2051. return true;
  2052. }
  2053. /**
  2054. * queue_work_on - queue work on specific cpu
  2055. * @cpu: CPU number to execute work on
  2056. * @wq: workqueue to use
  2057. * @work: work to queue
  2058. *
  2059. * We queue the work to a specific CPU, the caller must ensure it
  2060. * can't go away. Callers that fail to ensure that the specified
  2061. * CPU cannot go away will execute on a randomly chosen CPU.
  2062. * But note well that callers specifying a CPU that never has been
  2063. * online will get a splat.
  2064. *
  2065. * Return: %false if @work was already on a queue, %true otherwise.
  2066. */
  2067. bool queue_work_on(int cpu, struct workqueue_struct *wq,
  2068. struct work_struct *work)
  2069. {
  2070. bool ret = false;
  2071. unsigned long irq_flags;
  2072. local_irq_save(irq_flags);
  2073. if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)) &&
  2074. !clear_pending_if_disabled(work)) {
  2075. __queue_work(cpu, wq, work);
  2076. ret = true;
  2077. }
  2078. local_irq_restore(irq_flags);
  2079. return ret;
  2080. }
  2081. EXPORT_SYMBOL(queue_work_on);
  2082. /**
  2083. * select_numa_node_cpu - Select a CPU based on NUMA node
  2084. * @node: NUMA node ID that we want to select a CPU from
  2085. *
  2086. * This function will attempt to find a "random" cpu available on a given
  2087. * node. If there are no CPUs available on the given node it will return
  2088. * WORK_CPU_UNBOUND indicating that we should just schedule to any
  2089. * available CPU if we need to schedule this work.
  2090. */
  2091. static int select_numa_node_cpu(int node)
  2092. {
  2093. int cpu;
  2094. /* Delay binding to CPU if node is not valid or online */
  2095. if (node < 0 || node >= MAX_NUMNODES || !node_online(node))
  2096. return WORK_CPU_UNBOUND;
  2097. /* Use local node/cpu if we are already there */
  2098. cpu = raw_smp_processor_id();
  2099. if (node == cpu_to_node(cpu))
  2100. return cpu;
  2101. /* Use "random" otherwise know as "first" online CPU of node */
  2102. cpu = cpumask_any_and(cpumask_of_node(node), cpu_online_mask);
  2103. /* If CPU is valid return that, otherwise just defer */
  2104. return cpu < nr_cpu_ids ? cpu : WORK_CPU_UNBOUND;
  2105. }
  2106. /**
  2107. * queue_work_node - queue work on a "random" cpu for a given NUMA node
  2108. * @node: NUMA node that we are targeting the work for
  2109. * @wq: workqueue to use
  2110. * @work: work to queue
  2111. *
  2112. * We queue the work to a "random" CPU within a given NUMA node. The basic
  2113. * idea here is to provide a way to somehow associate work with a given
  2114. * NUMA node.
  2115. *
  2116. * This function will only make a best effort attempt at getting this onto
  2117. * the right NUMA node. If no node is requested or the requested node is
  2118. * offline then we just fall back to standard queue_work behavior.
  2119. *
  2120. * Currently the "random" CPU ends up being the first available CPU in the
  2121. * intersection of cpu_online_mask and the cpumask of the node, unless we
  2122. * are running on the node. In that case we just use the current CPU.
  2123. *
  2124. * Return: %false if @work was already on a queue, %true otherwise.
  2125. */
  2126. bool queue_work_node(int node, struct workqueue_struct *wq,
  2127. struct work_struct *work)
  2128. {
  2129. unsigned long irq_flags;
  2130. bool ret = false;
  2131. /*
  2132. * This current implementation is specific to unbound workqueues.
  2133. * Specifically we only return the first available CPU for a given
  2134. * node instead of cycling through individual CPUs within the node.
  2135. *
  2136. * If this is used with a per-cpu workqueue then the logic in
  2137. * workqueue_select_cpu_near would need to be updated to allow for
  2138. * some round robin type logic.
  2139. */
  2140. WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND));
  2141. local_irq_save(irq_flags);
  2142. if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)) &&
  2143. !clear_pending_if_disabled(work)) {
  2144. int cpu = select_numa_node_cpu(node);
  2145. __queue_work(cpu, wq, work);
  2146. ret = true;
  2147. }
  2148. local_irq_restore(irq_flags);
  2149. return ret;
  2150. }
  2151. EXPORT_SYMBOL_GPL(queue_work_node);
  2152. void delayed_work_timer_fn(struct timer_list *t)
  2153. {
  2154. struct delayed_work *dwork = from_timer(dwork, t, timer);
  2155. /* should have been called from irqsafe timer with irq already off */
  2156. __queue_work(dwork->cpu, dwork->wq, &dwork->work);
  2157. }
  2158. EXPORT_SYMBOL(delayed_work_timer_fn);
  2159. static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
  2160. struct delayed_work *dwork, unsigned long delay)
  2161. {
  2162. struct timer_list *timer = &dwork->timer;
  2163. struct work_struct *work = &dwork->work;
  2164. WARN_ON_ONCE(!wq);
  2165. WARN_ON_ONCE(timer->function != delayed_work_timer_fn);
  2166. WARN_ON_ONCE(timer_pending(timer));
  2167. WARN_ON_ONCE(!list_empty(&work->entry));
  2168. /*
  2169. * If @delay is 0, queue @dwork->work immediately. This is for
  2170. * both optimization and correctness. The earliest @timer can
  2171. * expire is on the closest next tick and delayed_work users depend
  2172. * on that there's no such delay when @delay is 0.
  2173. */
  2174. if (!delay) {
  2175. __queue_work(cpu, wq, &dwork->work);
  2176. return;
  2177. }
  2178. dwork->wq = wq;
  2179. dwork->cpu = cpu;
  2180. timer->expires = jiffies + delay;
  2181. if (housekeeping_enabled(HK_TYPE_TIMER)) {
  2182. /* If the current cpu is a housekeeping cpu, use it. */
  2183. cpu = smp_processor_id();
  2184. if (!housekeeping_test_cpu(cpu, HK_TYPE_TIMER))
  2185. cpu = housekeeping_any_cpu(HK_TYPE_TIMER);
  2186. add_timer_on(timer, cpu);
  2187. } else {
  2188. if (likely(cpu == WORK_CPU_UNBOUND))
  2189. add_timer_global(timer);
  2190. else
  2191. add_timer_on(timer, cpu);
  2192. }
  2193. }
  2194. /**
  2195. * queue_delayed_work_on - queue work on specific CPU after delay
  2196. * @cpu: CPU number to execute work on
  2197. * @wq: workqueue to use
  2198. * @dwork: work to queue
  2199. * @delay: number of jiffies to wait before queueing
  2200. *
  2201. * Return: %false if @work was already on a queue, %true otherwise. If
  2202. * @delay is zero and @dwork is idle, it will be scheduled for immediate
  2203. * execution.
  2204. */
  2205. bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
  2206. struct delayed_work *dwork, unsigned long delay)
  2207. {
  2208. struct work_struct *work = &dwork->work;
  2209. bool ret = false;
  2210. unsigned long irq_flags;
  2211. /* read the comment in __queue_work() */
  2212. local_irq_save(irq_flags);
  2213. if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)) &&
  2214. !clear_pending_if_disabled(work)) {
  2215. __queue_delayed_work(cpu, wq, dwork, delay);
  2216. ret = true;
  2217. }
  2218. local_irq_restore(irq_flags);
  2219. return ret;
  2220. }
  2221. EXPORT_SYMBOL(queue_delayed_work_on);
  2222. /**
  2223. * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
  2224. * @cpu: CPU number to execute work on
  2225. * @wq: workqueue to use
  2226. * @dwork: work to queue
  2227. * @delay: number of jiffies to wait before queueing
  2228. *
  2229. * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
  2230. * modify @dwork's timer so that it expires after @delay. If @delay is
  2231. * zero, @work is guaranteed to be scheduled immediately regardless of its
  2232. * current state.
  2233. *
  2234. * Return: %false if @dwork was idle and queued, %true if @dwork was
  2235. * pending and its timer was modified.
  2236. *
  2237. * This function is safe to call from any context including IRQ handler.
  2238. * See try_to_grab_pending() for details.
  2239. */
  2240. bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
  2241. struct delayed_work *dwork, unsigned long delay)
  2242. {
  2243. unsigned long irq_flags;
  2244. bool ret;
  2245. ret = work_grab_pending(&dwork->work, WORK_CANCEL_DELAYED, &irq_flags);
  2246. if (!clear_pending_if_disabled(&dwork->work))
  2247. __queue_delayed_work(cpu, wq, dwork, delay);
  2248. local_irq_restore(irq_flags);
  2249. return ret;
  2250. }
  2251. EXPORT_SYMBOL_GPL(mod_delayed_work_on);
  2252. static void rcu_work_rcufn(struct rcu_head *rcu)
  2253. {
  2254. struct rcu_work *rwork = container_of(rcu, struct rcu_work, rcu);
  2255. /* read the comment in __queue_work() */
  2256. local_irq_disable();
  2257. __queue_work(WORK_CPU_UNBOUND, rwork->wq, &rwork->work);
  2258. local_irq_enable();
  2259. }
  2260. /**
  2261. * queue_rcu_work - queue work after a RCU grace period
  2262. * @wq: workqueue to use
  2263. * @rwork: work to queue
  2264. *
  2265. * Return: %false if @rwork was already pending, %true otherwise. Note
  2266. * that a full RCU grace period is guaranteed only after a %true return.
  2267. * While @rwork is guaranteed to be executed after a %false return, the
  2268. * execution may happen before a full RCU grace period has passed.
  2269. */
  2270. bool queue_rcu_work(struct workqueue_struct *wq, struct rcu_work *rwork)
  2271. {
  2272. struct work_struct *work = &rwork->work;
  2273. /*
  2274. * rcu_work can't be canceled or disabled. Warn if the user reached
  2275. * inside @rwork and disabled the inner work.
  2276. */
  2277. if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)) &&
  2278. !WARN_ON_ONCE(clear_pending_if_disabled(work))) {
  2279. rwork->wq = wq;
  2280. call_rcu_hurry(&rwork->rcu, rcu_work_rcufn);
  2281. return true;
  2282. }
  2283. return false;
  2284. }
  2285. EXPORT_SYMBOL(queue_rcu_work);
  2286. static struct worker *alloc_worker(int node)
  2287. {
  2288. struct worker *worker;
  2289. worker = kzalloc_node(sizeof(*worker), GFP_KERNEL, node);
  2290. if (worker) {
  2291. INIT_LIST_HEAD(&worker->entry);
  2292. INIT_LIST_HEAD(&worker->scheduled);
  2293. INIT_LIST_HEAD(&worker->node);
  2294. /* on creation a worker is in !idle && prep state */
  2295. worker->flags = WORKER_PREP;
  2296. }
  2297. return worker;
  2298. }
  2299. static cpumask_t *pool_allowed_cpus(struct worker_pool *pool)
  2300. {
  2301. if (pool->cpu < 0 && pool->attrs->affn_strict)
  2302. return pool->attrs->__pod_cpumask;
  2303. else
  2304. return pool->attrs->cpumask;
  2305. }
  2306. /**
  2307. * worker_attach_to_pool() - attach a worker to a pool
  2308. * @worker: worker to be attached
  2309. * @pool: the target pool
  2310. *
  2311. * Attach @worker to @pool. Once attached, the %WORKER_UNBOUND flag and
  2312. * cpu-binding of @worker are kept coordinated with the pool across
  2313. * cpu-[un]hotplugs.
  2314. */
  2315. static void worker_attach_to_pool(struct worker *worker,
  2316. struct worker_pool *pool)
  2317. {
  2318. mutex_lock(&wq_pool_attach_mutex);
  2319. /*
  2320. * The wq_pool_attach_mutex ensures %POOL_DISASSOCIATED remains stable
  2321. * across this function. See the comments above the flag definition for
  2322. * details. BH workers are, while per-CPU, always DISASSOCIATED.
  2323. */
  2324. if (pool->flags & POOL_DISASSOCIATED) {
  2325. worker->flags |= WORKER_UNBOUND;
  2326. } else {
  2327. WARN_ON_ONCE(pool->flags & POOL_BH);
  2328. kthread_set_per_cpu(worker->task, pool->cpu);
  2329. }
  2330. if (worker->rescue_wq)
  2331. set_cpus_allowed_ptr(worker->task, pool_allowed_cpus(pool));
  2332. list_add_tail(&worker->node, &pool->workers);
  2333. worker->pool = pool;
  2334. mutex_unlock(&wq_pool_attach_mutex);
  2335. }
  2336. static void unbind_worker(struct worker *worker)
  2337. {
  2338. lockdep_assert_held(&wq_pool_attach_mutex);
  2339. kthread_set_per_cpu(worker->task, -1);
  2340. if (cpumask_intersects(wq_unbound_cpumask, cpu_active_mask))
  2341. WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, wq_unbound_cpumask) < 0);
  2342. else
  2343. WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, cpu_possible_mask) < 0);
  2344. }
  2345. static void detach_worker(struct worker *worker)
  2346. {
  2347. lockdep_assert_held(&wq_pool_attach_mutex);
  2348. unbind_worker(worker);
  2349. list_del(&worker->node);
  2350. }
  2351. /**
  2352. * worker_detach_from_pool() - detach a worker from its pool
  2353. * @worker: worker which is attached to its pool
  2354. *
  2355. * Undo the attaching which had been done in worker_attach_to_pool(). The
  2356. * caller worker shouldn't access to the pool after detached except it has
  2357. * other reference to the pool.
  2358. */
  2359. static void worker_detach_from_pool(struct worker *worker)
  2360. {
  2361. struct worker_pool *pool = worker->pool;
  2362. /* there is one permanent BH worker per CPU which should never detach */
  2363. WARN_ON_ONCE(pool->flags & POOL_BH);
  2364. mutex_lock(&wq_pool_attach_mutex);
  2365. detach_worker(worker);
  2366. worker->pool = NULL;
  2367. mutex_unlock(&wq_pool_attach_mutex);
  2368. /* clear leftover flags without pool->lock after it is detached */
  2369. worker->flags &= ~(WORKER_UNBOUND | WORKER_REBOUND);
  2370. }
  2371. static int format_worker_id(char *buf, size_t size, struct worker *worker,
  2372. struct worker_pool *pool)
  2373. {
  2374. if (worker->rescue_wq)
  2375. return scnprintf(buf, size, "kworker/R-%s",
  2376. worker->rescue_wq->name);
  2377. if (pool) {
  2378. if (pool->cpu >= 0)
  2379. return scnprintf(buf, size, "kworker/%d:%d%s",
  2380. pool->cpu, worker->id,
  2381. pool->attrs->nice < 0 ? "H" : "");
  2382. else
  2383. return scnprintf(buf, size, "kworker/u%d:%d",
  2384. pool->id, worker->id);
  2385. } else {
  2386. return scnprintf(buf, size, "kworker/dying");
  2387. }
  2388. }
  2389. /**
  2390. * create_worker - create a new workqueue worker
  2391. * @pool: pool the new worker will belong to
  2392. *
  2393. * Create and start a new worker which is attached to @pool.
  2394. *
  2395. * CONTEXT:
  2396. * Might sleep. Does GFP_KERNEL allocations.
  2397. *
  2398. * Return:
  2399. * Pointer to the newly created worker.
  2400. */
  2401. static struct worker *create_worker(struct worker_pool *pool)
  2402. {
  2403. struct worker *worker;
  2404. int id;
  2405. /* ID is needed to determine kthread name */
  2406. id = ida_alloc(&pool->worker_ida, GFP_KERNEL);
  2407. if (id < 0) {
  2408. pr_err_once("workqueue: Failed to allocate a worker ID: %pe\n",
  2409. ERR_PTR(id));
  2410. return NULL;
  2411. }
  2412. worker = alloc_worker(pool->node);
  2413. if (!worker) {
  2414. pr_err_once("workqueue: Failed to allocate a worker\n");
  2415. goto fail;
  2416. }
  2417. worker->id = id;
  2418. if (!(pool->flags & POOL_BH)) {
  2419. char id_buf[WORKER_ID_LEN];
  2420. format_worker_id(id_buf, sizeof(id_buf), worker, pool);
  2421. worker->task = kthread_create_on_node(worker_thread, worker,
  2422. pool->node, "%s", id_buf);
  2423. if (IS_ERR(worker->task)) {
  2424. if (PTR_ERR(worker->task) == -EINTR) {
  2425. pr_err("workqueue: Interrupted when creating a worker thread \"%s\"\n",
  2426. id_buf);
  2427. } else {
  2428. pr_err_once("workqueue: Failed to create a worker thread: %pe",
  2429. worker->task);
  2430. }
  2431. goto fail;
  2432. }
  2433. set_user_nice(worker->task, pool->attrs->nice);
  2434. kthread_bind_mask(worker->task, pool_allowed_cpus(pool));
  2435. }
  2436. /* successful, attach the worker to the pool */
  2437. worker_attach_to_pool(worker, pool);
  2438. /* start the newly created worker */
  2439. raw_spin_lock_irq(&pool->lock);
  2440. worker->pool->nr_workers++;
  2441. worker_enter_idle(worker);
  2442. /*
  2443. * @worker is waiting on a completion in kthread() and will trigger hung
  2444. * check if not woken up soon. As kick_pool() is noop if @pool is empty,
  2445. * wake it up explicitly.
  2446. */
  2447. if (worker->task)
  2448. wake_up_process(worker->task);
  2449. raw_spin_unlock_irq(&pool->lock);
  2450. return worker;
  2451. fail:
  2452. ida_free(&pool->worker_ida, id);
  2453. kfree(worker);
  2454. return NULL;
  2455. }
  2456. static void detach_dying_workers(struct list_head *cull_list)
  2457. {
  2458. struct worker *worker;
  2459. list_for_each_entry(worker, cull_list, entry)
  2460. detach_worker(worker);
  2461. }
  2462. static void reap_dying_workers(struct list_head *cull_list)
  2463. {
  2464. struct worker *worker, *tmp;
  2465. list_for_each_entry_safe(worker, tmp, cull_list, entry) {
  2466. list_del_init(&worker->entry);
  2467. kthread_stop_put(worker->task);
  2468. kfree(worker);
  2469. }
  2470. }
  2471. /**
  2472. * set_worker_dying - Tag a worker for destruction
  2473. * @worker: worker to be destroyed
  2474. * @list: transfer worker away from its pool->idle_list and into list
  2475. *
  2476. * Tag @worker for destruction and adjust @pool stats accordingly. The worker
  2477. * should be idle.
  2478. *
  2479. * CONTEXT:
  2480. * raw_spin_lock_irq(pool->lock).
  2481. */
  2482. static void set_worker_dying(struct worker *worker, struct list_head *list)
  2483. {
  2484. struct worker_pool *pool = worker->pool;
  2485. lockdep_assert_held(&pool->lock);
  2486. lockdep_assert_held(&wq_pool_attach_mutex);
  2487. /* sanity check frenzy */
  2488. if (WARN_ON(worker->current_work) ||
  2489. WARN_ON(!list_empty(&worker->scheduled)) ||
  2490. WARN_ON(!(worker->flags & WORKER_IDLE)))
  2491. return;
  2492. pool->nr_workers--;
  2493. pool->nr_idle--;
  2494. worker->flags |= WORKER_DIE;
  2495. list_move(&worker->entry, list);
  2496. /* get an extra task struct reference for later kthread_stop_put() */
  2497. get_task_struct(worker->task);
  2498. }
  2499. /**
  2500. * idle_worker_timeout - check if some idle workers can now be deleted.
  2501. * @t: The pool's idle_timer that just expired
  2502. *
  2503. * The timer is armed in worker_enter_idle(). Note that it isn't disarmed in
  2504. * worker_leave_idle(), as a worker flicking between idle and active while its
  2505. * pool is at the too_many_workers() tipping point would cause too much timer
  2506. * housekeeping overhead. Since IDLE_WORKER_TIMEOUT is long enough, we just let
  2507. * it expire and re-evaluate things from there.
  2508. */
  2509. static void idle_worker_timeout(struct timer_list *t)
  2510. {
  2511. struct worker_pool *pool = from_timer(pool, t, idle_timer);
  2512. bool do_cull = false;
  2513. if (work_pending(&pool->idle_cull_work))
  2514. return;
  2515. raw_spin_lock_irq(&pool->lock);
  2516. if (too_many_workers(pool)) {
  2517. struct worker *worker;
  2518. unsigned long expires;
  2519. /* idle_list is kept in LIFO order, check the last one */
  2520. worker = list_last_entry(&pool->idle_list, struct worker, entry);
  2521. expires = worker->last_active + IDLE_WORKER_TIMEOUT;
  2522. do_cull = !time_before(jiffies, expires);
  2523. if (!do_cull)
  2524. mod_timer(&pool->idle_timer, expires);
  2525. }
  2526. raw_spin_unlock_irq(&pool->lock);
  2527. if (do_cull)
  2528. queue_work(system_unbound_wq, &pool->idle_cull_work);
  2529. }
  2530. /**
  2531. * idle_cull_fn - cull workers that have been idle for too long.
  2532. * @work: the pool's work for handling these idle workers
  2533. *
  2534. * This goes through a pool's idle workers and gets rid of those that have been
  2535. * idle for at least IDLE_WORKER_TIMEOUT seconds.
  2536. *
  2537. * We don't want to disturb isolated CPUs because of a pcpu kworker being
  2538. * culled, so this also resets worker affinity. This requires a sleepable
  2539. * context, hence the split between timer callback and work item.
  2540. */
  2541. static void idle_cull_fn(struct work_struct *work)
  2542. {
  2543. struct worker_pool *pool = container_of(work, struct worker_pool, idle_cull_work);
  2544. LIST_HEAD(cull_list);
  2545. /*
  2546. * Grabbing wq_pool_attach_mutex here ensures an already-running worker
  2547. * cannot proceed beyong set_pf_worker() in its self-destruct path.
  2548. * This is required as a previously-preempted worker could run after
  2549. * set_worker_dying() has happened but before detach_dying_workers() did.
  2550. */
  2551. mutex_lock(&wq_pool_attach_mutex);
  2552. raw_spin_lock_irq(&pool->lock);
  2553. while (too_many_workers(pool)) {
  2554. struct worker *worker;
  2555. unsigned long expires;
  2556. worker = list_last_entry(&pool->idle_list, struct worker, entry);
  2557. expires = worker->last_active + IDLE_WORKER_TIMEOUT;
  2558. if (time_before(jiffies, expires)) {
  2559. mod_timer(&pool->idle_timer, expires);
  2560. break;
  2561. }
  2562. set_worker_dying(worker, &cull_list);
  2563. }
  2564. raw_spin_unlock_irq(&pool->lock);
  2565. detach_dying_workers(&cull_list);
  2566. mutex_unlock(&wq_pool_attach_mutex);
  2567. reap_dying_workers(&cull_list);
  2568. }
  2569. static void send_mayday(struct work_struct *work)
  2570. {
  2571. struct pool_workqueue *pwq = get_work_pwq(work);
  2572. struct workqueue_struct *wq = pwq->wq;
  2573. lockdep_assert_held(&wq_mayday_lock);
  2574. if (!wq->rescuer)
  2575. return;
  2576. /* mayday mayday mayday */
  2577. if (list_empty(&pwq->mayday_node)) {
  2578. /*
  2579. * If @pwq is for an unbound wq, its base ref may be put at
  2580. * any time due to an attribute change. Pin @pwq until the
  2581. * rescuer is done with it.
  2582. */
  2583. get_pwq(pwq);
  2584. list_add_tail(&pwq->mayday_node, &wq->maydays);
  2585. wake_up_process(wq->rescuer->task);
  2586. pwq->stats[PWQ_STAT_MAYDAY]++;
  2587. }
  2588. }
  2589. static void pool_mayday_timeout(struct timer_list *t)
  2590. {
  2591. struct worker_pool *pool = from_timer(pool, t, mayday_timer);
  2592. struct work_struct *work;
  2593. raw_spin_lock_irq(&pool->lock);
  2594. raw_spin_lock(&wq_mayday_lock); /* for wq->maydays */
  2595. if (need_to_create_worker(pool)) {
  2596. /*
  2597. * We've been trying to create a new worker but
  2598. * haven't been successful. We might be hitting an
  2599. * allocation deadlock. Send distress signals to
  2600. * rescuers.
  2601. */
  2602. list_for_each_entry(work, &pool->worklist, entry)
  2603. send_mayday(work);
  2604. }
  2605. raw_spin_unlock(&wq_mayday_lock);
  2606. raw_spin_unlock_irq(&pool->lock);
  2607. mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
  2608. }
  2609. /**
  2610. * maybe_create_worker - create a new worker if necessary
  2611. * @pool: pool to create a new worker for
  2612. *
  2613. * Create a new worker for @pool if necessary. @pool is guaranteed to
  2614. * have at least one idle worker on return from this function. If
  2615. * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
  2616. * sent to all rescuers with works scheduled on @pool to resolve
  2617. * possible allocation deadlock.
  2618. *
  2619. * On return, need_to_create_worker() is guaranteed to be %false and
  2620. * may_start_working() %true.
  2621. *
  2622. * LOCKING:
  2623. * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
  2624. * multiple times. Does GFP_KERNEL allocations. Called only from
  2625. * manager.
  2626. */
  2627. static void maybe_create_worker(struct worker_pool *pool)
  2628. __releases(&pool->lock)
  2629. __acquires(&pool->lock)
  2630. {
  2631. restart:
  2632. raw_spin_unlock_irq(&pool->lock);
  2633. /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
  2634. mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
  2635. while (true) {
  2636. if (create_worker(pool) || !need_to_create_worker(pool))
  2637. break;
  2638. schedule_timeout_interruptible(CREATE_COOLDOWN);
  2639. if (!need_to_create_worker(pool))
  2640. break;
  2641. }
  2642. del_timer_sync(&pool->mayday_timer);
  2643. raw_spin_lock_irq(&pool->lock);
  2644. /*
  2645. * This is necessary even after a new worker was just successfully
  2646. * created as @pool->lock was dropped and the new worker might have
  2647. * already become busy.
  2648. */
  2649. if (need_to_create_worker(pool))
  2650. goto restart;
  2651. }
  2652. /**
  2653. * manage_workers - manage worker pool
  2654. * @worker: self
  2655. *
  2656. * Assume the manager role and manage the worker pool @worker belongs
  2657. * to. At any given time, there can be only zero or one manager per
  2658. * pool. The exclusion is handled automatically by this function.
  2659. *
  2660. * The caller can safely start processing works on false return. On
  2661. * true return, it's guaranteed that need_to_create_worker() is false
  2662. * and may_start_working() is true.
  2663. *
  2664. * CONTEXT:
  2665. * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
  2666. * multiple times. Does GFP_KERNEL allocations.
  2667. *
  2668. * Return:
  2669. * %false if the pool doesn't need management and the caller can safely
  2670. * start processing works, %true if management function was performed and
  2671. * the conditions that the caller verified before calling the function may
  2672. * no longer be true.
  2673. */
  2674. static bool manage_workers(struct worker *worker)
  2675. {
  2676. struct worker_pool *pool = worker->pool;
  2677. if (pool->flags & POOL_MANAGER_ACTIVE)
  2678. return false;
  2679. pool->flags |= POOL_MANAGER_ACTIVE;
  2680. pool->manager = worker;
  2681. maybe_create_worker(pool);
  2682. pool->manager = NULL;
  2683. pool->flags &= ~POOL_MANAGER_ACTIVE;
  2684. rcuwait_wake_up(&manager_wait);
  2685. return true;
  2686. }
  2687. /**
  2688. * process_one_work - process single work
  2689. * @worker: self
  2690. * @work: work to process
  2691. *
  2692. * Process @work. This function contains all the logics necessary to
  2693. * process a single work including synchronization against and
  2694. * interaction with other workers on the same cpu, queueing and
  2695. * flushing. As long as context requirement is met, any worker can
  2696. * call this function to process a work.
  2697. *
  2698. * CONTEXT:
  2699. * raw_spin_lock_irq(pool->lock) which is released and regrabbed.
  2700. */
  2701. static void process_one_work(struct worker *worker, struct work_struct *work)
  2702. __releases(&pool->lock)
  2703. __acquires(&pool->lock)
  2704. {
  2705. struct pool_workqueue *pwq = get_work_pwq(work);
  2706. struct worker_pool *pool = worker->pool;
  2707. unsigned long work_data;
  2708. int lockdep_start_depth, rcu_start_depth;
  2709. bool bh_draining = pool->flags & POOL_BH_DRAINING;
  2710. #ifdef CONFIG_LOCKDEP
  2711. /*
  2712. * It is permissible to free the struct work_struct from
  2713. * inside the function that is called from it, this we need to
  2714. * take into account for lockdep too. To avoid bogus "held
  2715. * lock freed" warnings as well as problems when looking into
  2716. * work->lockdep_map, make a copy and use that here.
  2717. */
  2718. struct lockdep_map lockdep_map;
  2719. lockdep_copy_map(&lockdep_map, &work->lockdep_map);
  2720. #endif
  2721. /* ensure we're on the correct CPU */
  2722. WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
  2723. raw_smp_processor_id() != pool->cpu);
  2724. /* claim and dequeue */
  2725. debug_work_deactivate(work);
  2726. hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
  2727. worker->current_work = work;
  2728. worker->current_func = work->func;
  2729. worker->current_pwq = pwq;
  2730. if (worker->task)
  2731. worker->current_at = worker->task->se.sum_exec_runtime;
  2732. work_data = *work_data_bits(work);
  2733. worker->current_color = get_work_color(work_data);
  2734. /*
  2735. * Record wq name for cmdline and debug reporting, may get
  2736. * overridden through set_worker_desc().
  2737. */
  2738. strscpy(worker->desc, pwq->wq->name, WORKER_DESC_LEN);
  2739. list_del_init(&work->entry);
  2740. /*
  2741. * CPU intensive works don't participate in concurrency management.
  2742. * They're the scheduler's responsibility. This takes @worker out
  2743. * of concurrency management and the next code block will chain
  2744. * execution of the pending work items.
  2745. */
  2746. if (unlikely(pwq->wq->flags & WQ_CPU_INTENSIVE))
  2747. worker_set_flags(worker, WORKER_CPU_INTENSIVE);
  2748. /*
  2749. * Kick @pool if necessary. It's always noop for per-cpu worker pools
  2750. * since nr_running would always be >= 1 at this point. This is used to
  2751. * chain execution of the pending work items for WORKER_NOT_RUNNING
  2752. * workers such as the UNBOUND and CPU_INTENSIVE ones.
  2753. */
  2754. kick_pool(pool);
  2755. /*
  2756. * Record the last pool and clear PENDING which should be the last
  2757. * update to @work. Also, do this inside @pool->lock so that
  2758. * PENDING and queued state changes happen together while IRQ is
  2759. * disabled.
  2760. */
  2761. set_work_pool_and_clear_pending(work, pool->id, pool_offq_flags(pool));
  2762. pwq->stats[PWQ_STAT_STARTED]++;
  2763. raw_spin_unlock_irq(&pool->lock);
  2764. rcu_start_depth = rcu_preempt_depth();
  2765. lockdep_start_depth = lockdep_depth(current);
  2766. /* see drain_dead_softirq_workfn() */
  2767. if (!bh_draining)
  2768. lock_map_acquire(pwq->wq->lockdep_map);
  2769. lock_map_acquire(&lockdep_map);
  2770. /*
  2771. * Strictly speaking we should mark the invariant state without holding
  2772. * any locks, that is, before these two lock_map_acquire()'s.
  2773. *
  2774. * However, that would result in:
  2775. *
  2776. * A(W1)
  2777. * WFC(C)
  2778. * A(W1)
  2779. * C(C)
  2780. *
  2781. * Which would create W1->C->W1 dependencies, even though there is no
  2782. * actual deadlock possible. There are two solutions, using a
  2783. * read-recursive acquire on the work(queue) 'locks', but this will then
  2784. * hit the lockdep limitation on recursive locks, or simply discard
  2785. * these locks.
  2786. *
  2787. * AFAICT there is no possible deadlock scenario between the
  2788. * flush_work() and complete() primitives (except for single-threaded
  2789. * workqueues), so hiding them isn't a problem.
  2790. */
  2791. lockdep_invariant_state(true);
  2792. trace_workqueue_execute_start(work);
  2793. worker->current_func(work);
  2794. /*
  2795. * While we must be careful to not use "work" after this, the trace
  2796. * point will only record its address.
  2797. */
  2798. trace_workqueue_execute_end(work, worker->current_func);
  2799. pwq->stats[PWQ_STAT_COMPLETED]++;
  2800. lock_map_release(&lockdep_map);
  2801. if (!bh_draining)
  2802. lock_map_release(pwq->wq->lockdep_map);
  2803. if (unlikely((worker->task && in_atomic()) ||
  2804. lockdep_depth(current) != lockdep_start_depth ||
  2805. rcu_preempt_depth() != rcu_start_depth)) {
  2806. pr_err("BUG: workqueue leaked atomic, lock or RCU: %s[%d]\n"
  2807. " preempt=0x%08x lock=%d->%d RCU=%d->%d workfn=%ps\n",
  2808. current->comm, task_pid_nr(current), preempt_count(),
  2809. lockdep_start_depth, lockdep_depth(current),
  2810. rcu_start_depth, rcu_preempt_depth(),
  2811. worker->current_func);
  2812. debug_show_held_locks(current);
  2813. dump_stack();
  2814. }
  2815. /*
  2816. * The following prevents a kworker from hogging CPU on !PREEMPTION
  2817. * kernels, where a requeueing work item waiting for something to
  2818. * happen could deadlock with stop_machine as such work item could
  2819. * indefinitely requeue itself while all other CPUs are trapped in
  2820. * stop_machine. At the same time, report a quiescent RCU state so
  2821. * the same condition doesn't freeze RCU.
  2822. */
  2823. if (worker->task)
  2824. cond_resched();
  2825. raw_spin_lock_irq(&pool->lock);
  2826. /*
  2827. * In addition to %WQ_CPU_INTENSIVE, @worker may also have been marked
  2828. * CPU intensive by wq_worker_tick() if @work hogged CPU longer than
  2829. * wq_cpu_intensive_thresh_us. Clear it.
  2830. */
  2831. worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
  2832. /* tag the worker for identification in schedule() */
  2833. worker->last_func = worker->current_func;
  2834. /* we're done with it, release */
  2835. hash_del(&worker->hentry);
  2836. worker->current_work = NULL;
  2837. worker->current_func = NULL;
  2838. worker->current_pwq = NULL;
  2839. worker->current_color = INT_MAX;
  2840. /* must be the last step, see the function comment */
  2841. pwq_dec_nr_in_flight(pwq, work_data);
  2842. }
  2843. /**
  2844. * process_scheduled_works - process scheduled works
  2845. * @worker: self
  2846. *
  2847. * Process all scheduled works. Please note that the scheduled list
  2848. * may change while processing a work, so this function repeatedly
  2849. * fetches a work from the top and executes it.
  2850. *
  2851. * CONTEXT:
  2852. * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
  2853. * multiple times.
  2854. */
  2855. static void process_scheduled_works(struct worker *worker)
  2856. {
  2857. struct work_struct *work;
  2858. bool first = true;
  2859. while ((work = list_first_entry_or_null(&worker->scheduled,
  2860. struct work_struct, entry))) {
  2861. if (first) {
  2862. worker->pool->watchdog_ts = jiffies;
  2863. first = false;
  2864. }
  2865. process_one_work(worker, work);
  2866. }
  2867. }
  2868. static void set_pf_worker(bool val)
  2869. {
  2870. mutex_lock(&wq_pool_attach_mutex);
  2871. if (val)
  2872. current->flags |= PF_WQ_WORKER;
  2873. else
  2874. current->flags &= ~PF_WQ_WORKER;
  2875. mutex_unlock(&wq_pool_attach_mutex);
  2876. }
  2877. /**
  2878. * worker_thread - the worker thread function
  2879. * @__worker: self
  2880. *
  2881. * The worker thread function. All workers belong to a worker_pool -
  2882. * either a per-cpu one or dynamic unbound one. These workers process all
  2883. * work items regardless of their specific target workqueue. The only
  2884. * exception is work items which belong to workqueues with a rescuer which
  2885. * will be explained in rescuer_thread().
  2886. *
  2887. * Return: 0
  2888. */
  2889. static int worker_thread(void *__worker)
  2890. {
  2891. struct worker *worker = __worker;
  2892. struct worker_pool *pool = worker->pool;
  2893. /* tell the scheduler that this is a workqueue worker */
  2894. set_pf_worker(true);
  2895. woke_up:
  2896. raw_spin_lock_irq(&pool->lock);
  2897. /* am I supposed to die? */
  2898. if (unlikely(worker->flags & WORKER_DIE)) {
  2899. raw_spin_unlock_irq(&pool->lock);
  2900. set_pf_worker(false);
  2901. /*
  2902. * The worker is dead and PF_WQ_WORKER is cleared, worker->pool
  2903. * shouldn't be accessed, reset it to NULL in case otherwise.
  2904. */
  2905. worker->pool = NULL;
  2906. ida_free(&pool->worker_ida, worker->id);
  2907. return 0;
  2908. }
  2909. worker_leave_idle(worker);
  2910. recheck:
  2911. /* no more worker necessary? */
  2912. if (!need_more_worker(pool))
  2913. goto sleep;
  2914. /* do we need to manage? */
  2915. if (unlikely(!may_start_working(pool)) && manage_workers(worker))
  2916. goto recheck;
  2917. /*
  2918. * ->scheduled list can only be filled while a worker is
  2919. * preparing to process a work or actually processing it.
  2920. * Make sure nobody diddled with it while I was sleeping.
  2921. */
  2922. WARN_ON_ONCE(!list_empty(&worker->scheduled));
  2923. /*
  2924. * Finish PREP stage. We're guaranteed to have at least one idle
  2925. * worker or that someone else has already assumed the manager
  2926. * role. This is where @worker starts participating in concurrency
  2927. * management if applicable and concurrency management is restored
  2928. * after being rebound. See rebind_workers() for details.
  2929. */
  2930. worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
  2931. do {
  2932. struct work_struct *work =
  2933. list_first_entry(&pool->worklist,
  2934. struct work_struct, entry);
  2935. if (assign_work(work, worker, NULL))
  2936. process_scheduled_works(worker);
  2937. } while (keep_working(pool));
  2938. worker_set_flags(worker, WORKER_PREP);
  2939. sleep:
  2940. /*
  2941. * pool->lock is held and there's no work to process and no need to
  2942. * manage, sleep. Workers are woken up only while holding
  2943. * pool->lock or from local cpu, so setting the current state
  2944. * before releasing pool->lock is enough to prevent losing any
  2945. * event.
  2946. */
  2947. worker_enter_idle(worker);
  2948. __set_current_state(TASK_IDLE);
  2949. raw_spin_unlock_irq(&pool->lock);
  2950. schedule();
  2951. goto woke_up;
  2952. }
  2953. /**
  2954. * rescuer_thread - the rescuer thread function
  2955. * @__rescuer: self
  2956. *
  2957. * Workqueue rescuer thread function. There's one rescuer for each
  2958. * workqueue which has WQ_MEM_RECLAIM set.
  2959. *
  2960. * Regular work processing on a pool may block trying to create a new
  2961. * worker which uses GFP_KERNEL allocation which has slight chance of
  2962. * developing into deadlock if some works currently on the same queue
  2963. * need to be processed to satisfy the GFP_KERNEL allocation. This is
  2964. * the problem rescuer solves.
  2965. *
  2966. * When such condition is possible, the pool summons rescuers of all
  2967. * workqueues which have works queued on the pool and let them process
  2968. * those works so that forward progress can be guaranteed.
  2969. *
  2970. * This should happen rarely.
  2971. *
  2972. * Return: 0
  2973. */
  2974. static int rescuer_thread(void *__rescuer)
  2975. {
  2976. struct worker *rescuer = __rescuer;
  2977. struct workqueue_struct *wq = rescuer->rescue_wq;
  2978. bool should_stop;
  2979. set_user_nice(current, RESCUER_NICE_LEVEL);
  2980. /*
  2981. * Mark rescuer as worker too. As WORKER_PREP is never cleared, it
  2982. * doesn't participate in concurrency management.
  2983. */
  2984. set_pf_worker(true);
  2985. repeat:
  2986. set_current_state(TASK_IDLE);
  2987. /*
  2988. * By the time the rescuer is requested to stop, the workqueue
  2989. * shouldn't have any work pending, but @wq->maydays may still have
  2990. * pwq(s) queued. This can happen by non-rescuer workers consuming
  2991. * all the work items before the rescuer got to them. Go through
  2992. * @wq->maydays processing before acting on should_stop so that the
  2993. * list is always empty on exit.
  2994. */
  2995. should_stop = kthread_should_stop();
  2996. /* see whether any pwq is asking for help */
  2997. raw_spin_lock_irq(&wq_mayday_lock);
  2998. while (!list_empty(&wq->maydays)) {
  2999. struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
  3000. struct pool_workqueue, mayday_node);
  3001. struct worker_pool *pool = pwq->pool;
  3002. struct work_struct *work, *n;
  3003. __set_current_state(TASK_RUNNING);
  3004. list_del_init(&pwq->mayday_node);
  3005. raw_spin_unlock_irq(&wq_mayday_lock);
  3006. worker_attach_to_pool(rescuer, pool);
  3007. raw_spin_lock_irq(&pool->lock);
  3008. /*
  3009. * Slurp in all works issued via this workqueue and
  3010. * process'em.
  3011. */
  3012. WARN_ON_ONCE(!list_empty(&rescuer->scheduled));
  3013. list_for_each_entry_safe(work, n, &pool->worklist, entry) {
  3014. if (get_work_pwq(work) == pwq &&
  3015. assign_work(work, rescuer, &n))
  3016. pwq->stats[PWQ_STAT_RESCUED]++;
  3017. }
  3018. if (!list_empty(&rescuer->scheduled)) {
  3019. process_scheduled_works(rescuer);
  3020. /*
  3021. * The above execution of rescued work items could
  3022. * have created more to rescue through
  3023. * pwq_activate_first_inactive() or chained
  3024. * queueing. Let's put @pwq back on mayday list so
  3025. * that such back-to-back work items, which may be
  3026. * being used to relieve memory pressure, don't
  3027. * incur MAYDAY_INTERVAL delay inbetween.
  3028. */
  3029. if (pwq->nr_active && need_to_create_worker(pool)) {
  3030. raw_spin_lock(&wq_mayday_lock);
  3031. /*
  3032. * Queue iff we aren't racing destruction
  3033. * and somebody else hasn't queued it already.
  3034. */
  3035. if (wq->rescuer && list_empty(&pwq->mayday_node)) {
  3036. get_pwq(pwq);
  3037. list_add_tail(&pwq->mayday_node, &wq->maydays);
  3038. }
  3039. raw_spin_unlock(&wq_mayday_lock);
  3040. }
  3041. }
  3042. /*
  3043. * Leave this pool. Notify regular workers; otherwise, we end up
  3044. * with 0 concurrency and stalling the execution.
  3045. */
  3046. kick_pool(pool);
  3047. raw_spin_unlock_irq(&pool->lock);
  3048. worker_detach_from_pool(rescuer);
  3049. /*
  3050. * Put the reference grabbed by send_mayday(). @pool might
  3051. * go away any time after it.
  3052. */
  3053. put_pwq_unlocked(pwq);
  3054. raw_spin_lock_irq(&wq_mayday_lock);
  3055. }
  3056. raw_spin_unlock_irq(&wq_mayday_lock);
  3057. if (should_stop) {
  3058. __set_current_state(TASK_RUNNING);
  3059. set_pf_worker(false);
  3060. return 0;
  3061. }
  3062. /* rescuers should never participate in concurrency management */
  3063. WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
  3064. schedule();
  3065. goto repeat;
  3066. }
  3067. static void bh_worker(struct worker *worker)
  3068. {
  3069. struct worker_pool *pool = worker->pool;
  3070. int nr_restarts = BH_WORKER_RESTARTS;
  3071. unsigned long end = jiffies + BH_WORKER_JIFFIES;
  3072. raw_spin_lock_irq(&pool->lock);
  3073. worker_leave_idle(worker);
  3074. /*
  3075. * This function follows the structure of worker_thread(). See there for
  3076. * explanations on each step.
  3077. */
  3078. if (!need_more_worker(pool))
  3079. goto done;
  3080. WARN_ON_ONCE(!list_empty(&worker->scheduled));
  3081. worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
  3082. do {
  3083. struct work_struct *work =
  3084. list_first_entry(&pool->worklist,
  3085. struct work_struct, entry);
  3086. if (assign_work(work, worker, NULL))
  3087. process_scheduled_works(worker);
  3088. } while (keep_working(pool) &&
  3089. --nr_restarts && time_before(jiffies, end));
  3090. worker_set_flags(worker, WORKER_PREP);
  3091. done:
  3092. worker_enter_idle(worker);
  3093. kick_pool(pool);
  3094. raw_spin_unlock_irq(&pool->lock);
  3095. }
  3096. /*
  3097. * TODO: Convert all tasklet users to workqueue and use softirq directly.
  3098. *
  3099. * This is currently called from tasklet[_hi]action() and thus is also called
  3100. * whenever there are tasklets to run. Let's do an early exit if there's nothing
  3101. * queued. Once conversion from tasklet is complete, the need_more_worker() test
  3102. * can be dropped.
  3103. *
  3104. * After full conversion, we'll add worker->softirq_action, directly use the
  3105. * softirq action and obtain the worker pointer from the softirq_action pointer.
  3106. */
  3107. void workqueue_softirq_action(bool highpri)
  3108. {
  3109. struct worker_pool *pool =
  3110. &per_cpu(bh_worker_pools, smp_processor_id())[highpri];
  3111. if (need_more_worker(pool))
  3112. bh_worker(list_first_entry(&pool->workers, struct worker, node));
  3113. }
  3114. struct wq_drain_dead_softirq_work {
  3115. struct work_struct work;
  3116. struct worker_pool *pool;
  3117. struct completion done;
  3118. };
  3119. static void drain_dead_softirq_workfn(struct work_struct *work)
  3120. {
  3121. struct wq_drain_dead_softirq_work *dead_work =
  3122. container_of(work, struct wq_drain_dead_softirq_work, work);
  3123. struct worker_pool *pool = dead_work->pool;
  3124. bool repeat;
  3125. /*
  3126. * @pool's CPU is dead and we want to execute its still pending work
  3127. * items from this BH work item which is running on a different CPU. As
  3128. * its CPU is dead, @pool can't be kicked and, as work execution path
  3129. * will be nested, a lockdep annotation needs to be suppressed. Mark
  3130. * @pool with %POOL_BH_DRAINING for the special treatments.
  3131. */
  3132. raw_spin_lock_irq(&pool->lock);
  3133. pool->flags |= POOL_BH_DRAINING;
  3134. raw_spin_unlock_irq(&pool->lock);
  3135. bh_worker(list_first_entry(&pool->workers, struct worker, node));
  3136. raw_spin_lock_irq(&pool->lock);
  3137. pool->flags &= ~POOL_BH_DRAINING;
  3138. repeat = need_more_worker(pool);
  3139. raw_spin_unlock_irq(&pool->lock);
  3140. /*
  3141. * bh_worker() might hit consecutive execution limit and bail. If there
  3142. * still are pending work items, reschedule self and return so that we
  3143. * don't hog this CPU's BH.
  3144. */
  3145. if (repeat) {
  3146. if (pool->attrs->nice == HIGHPRI_NICE_LEVEL)
  3147. queue_work(system_bh_highpri_wq, work);
  3148. else
  3149. queue_work(system_bh_wq, work);
  3150. } else {
  3151. complete(&dead_work->done);
  3152. }
  3153. }
  3154. /*
  3155. * @cpu is dead. Drain the remaining BH work items on the current CPU. It's
  3156. * possible to allocate dead_work per CPU and avoid flushing. However, then we
  3157. * have to worry about draining overlapping with CPU coming back online or
  3158. * nesting (one CPU's dead_work queued on another CPU which is also dead and so
  3159. * on). Let's keep it simple and drain them synchronously. These are BH work
  3160. * items which shouldn't be requeued on the same pool. Shouldn't take long.
  3161. */
  3162. void workqueue_softirq_dead(unsigned int cpu)
  3163. {
  3164. int i;
  3165. for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
  3166. struct worker_pool *pool = &per_cpu(bh_worker_pools, cpu)[i];
  3167. struct wq_drain_dead_softirq_work dead_work;
  3168. if (!need_more_worker(pool))
  3169. continue;
  3170. INIT_WORK_ONSTACK(&dead_work.work, drain_dead_softirq_workfn);
  3171. dead_work.pool = pool;
  3172. init_completion(&dead_work.done);
  3173. if (pool->attrs->nice == HIGHPRI_NICE_LEVEL)
  3174. queue_work(system_bh_highpri_wq, &dead_work.work);
  3175. else
  3176. queue_work(system_bh_wq, &dead_work.work);
  3177. wait_for_completion(&dead_work.done);
  3178. destroy_work_on_stack(&dead_work.work);
  3179. }
  3180. }
  3181. /**
  3182. * check_flush_dependency - check for flush dependency sanity
  3183. * @target_wq: workqueue being flushed
  3184. * @target_work: work item being flushed (NULL for workqueue flushes)
  3185. * @from_cancel: are we called from the work cancel path
  3186. *
  3187. * %current is trying to flush the whole @target_wq or @target_work on it.
  3188. * If this is not the cancel path (which implies work being flushed is either
  3189. * already running, or will not be at all), check if @target_wq doesn't have
  3190. * %WQ_MEM_RECLAIM and verify that %current is not reclaiming memory or running
  3191. * on a workqueue which doesn't have %WQ_MEM_RECLAIM as that can break forward-
  3192. * progress guarantee leading to a deadlock.
  3193. */
  3194. static void check_flush_dependency(struct workqueue_struct *target_wq,
  3195. struct work_struct *target_work,
  3196. bool from_cancel)
  3197. {
  3198. work_func_t target_func;
  3199. struct worker *worker;
  3200. if (from_cancel || target_wq->flags & WQ_MEM_RECLAIM)
  3201. return;
  3202. worker = current_wq_worker();
  3203. target_func = target_work ? target_work->func : NULL;
  3204. WARN_ONCE(current->flags & PF_MEMALLOC,
  3205. "workqueue: PF_MEMALLOC task %d(%s) is flushing !WQ_MEM_RECLAIM %s:%ps",
  3206. current->pid, current->comm, target_wq->name, target_func);
  3207. WARN_ONCE(worker && ((worker->current_pwq->wq->flags &
  3208. (WQ_MEM_RECLAIM | __WQ_LEGACY)) == WQ_MEM_RECLAIM),
  3209. "workqueue: WQ_MEM_RECLAIM %s:%ps is flushing !WQ_MEM_RECLAIM %s:%ps",
  3210. worker->current_pwq->wq->name, worker->current_func,
  3211. target_wq->name, target_func);
  3212. }
  3213. struct wq_barrier {
  3214. struct work_struct work;
  3215. struct completion done;
  3216. struct task_struct *task; /* purely informational */
  3217. };
  3218. static void wq_barrier_func(struct work_struct *work)
  3219. {
  3220. struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
  3221. complete(&barr->done);
  3222. }
  3223. /**
  3224. * insert_wq_barrier - insert a barrier work
  3225. * @pwq: pwq to insert barrier into
  3226. * @barr: wq_barrier to insert
  3227. * @target: target work to attach @barr to
  3228. * @worker: worker currently executing @target, NULL if @target is not executing
  3229. *
  3230. * @barr is linked to @target such that @barr is completed only after
  3231. * @target finishes execution. Please note that the ordering
  3232. * guarantee is observed only with respect to @target and on the local
  3233. * cpu.
  3234. *
  3235. * Currently, a queued barrier can't be canceled. This is because
  3236. * try_to_grab_pending() can't determine whether the work to be
  3237. * grabbed is at the head of the queue and thus can't clear LINKED
  3238. * flag of the previous work while there must be a valid next work
  3239. * after a work with LINKED flag set.
  3240. *
  3241. * Note that when @worker is non-NULL, @target may be modified
  3242. * underneath us, so we can't reliably determine pwq from @target.
  3243. *
  3244. * CONTEXT:
  3245. * raw_spin_lock_irq(pool->lock).
  3246. */
  3247. static void insert_wq_barrier(struct pool_workqueue *pwq,
  3248. struct wq_barrier *barr,
  3249. struct work_struct *target, struct worker *worker)
  3250. {
  3251. static __maybe_unused struct lock_class_key bh_key, thr_key;
  3252. unsigned int work_flags = 0;
  3253. unsigned int work_color;
  3254. struct list_head *head;
  3255. /*
  3256. * debugobject calls are safe here even with pool->lock locked
  3257. * as we know for sure that this will not trigger any of the
  3258. * checks and call back into the fixup functions where we
  3259. * might deadlock.
  3260. *
  3261. * BH and threaded workqueues need separate lockdep keys to avoid
  3262. * spuriously triggering "inconsistent {SOFTIRQ-ON-W} -> {IN-SOFTIRQ-W}
  3263. * usage".
  3264. */
  3265. INIT_WORK_ONSTACK_KEY(&barr->work, wq_barrier_func,
  3266. (pwq->wq->flags & WQ_BH) ? &bh_key : &thr_key);
  3267. __set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
  3268. init_completion_map(&barr->done, &target->lockdep_map);
  3269. barr->task = current;
  3270. /* The barrier work item does not participate in nr_active. */
  3271. work_flags |= WORK_STRUCT_INACTIVE;
  3272. /*
  3273. * If @target is currently being executed, schedule the
  3274. * barrier to the worker; otherwise, put it after @target.
  3275. */
  3276. if (worker) {
  3277. head = worker->scheduled.next;
  3278. work_color = worker->current_color;
  3279. } else {
  3280. unsigned long *bits = work_data_bits(target);
  3281. head = target->entry.next;
  3282. /* there can already be other linked works, inherit and set */
  3283. work_flags |= *bits & WORK_STRUCT_LINKED;
  3284. work_color = get_work_color(*bits);
  3285. __set_bit(WORK_STRUCT_LINKED_BIT, bits);
  3286. }
  3287. pwq->nr_in_flight[work_color]++;
  3288. work_flags |= work_color_to_flags(work_color);
  3289. insert_work(pwq, &barr->work, head, work_flags);
  3290. }
  3291. /**
  3292. * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
  3293. * @wq: workqueue being flushed
  3294. * @flush_color: new flush color, < 0 for no-op
  3295. * @work_color: new work color, < 0 for no-op
  3296. *
  3297. * Prepare pwqs for workqueue flushing.
  3298. *
  3299. * If @flush_color is non-negative, flush_color on all pwqs should be
  3300. * -1. If no pwq has in-flight commands at the specified color, all
  3301. * pwq->flush_color's stay at -1 and %false is returned. If any pwq
  3302. * has in flight commands, its pwq->flush_color is set to
  3303. * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
  3304. * wakeup logic is armed and %true is returned.
  3305. *
  3306. * The caller should have initialized @wq->first_flusher prior to
  3307. * calling this function with non-negative @flush_color. If
  3308. * @flush_color is negative, no flush color update is done and %false
  3309. * is returned.
  3310. *
  3311. * If @work_color is non-negative, all pwqs should have the same
  3312. * work_color which is previous to @work_color and all will be
  3313. * advanced to @work_color.
  3314. *
  3315. * CONTEXT:
  3316. * mutex_lock(wq->mutex).
  3317. *
  3318. * Return:
  3319. * %true if @flush_color >= 0 and there's something to flush. %false
  3320. * otherwise.
  3321. */
  3322. static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
  3323. int flush_color, int work_color)
  3324. {
  3325. bool wait = false;
  3326. struct pool_workqueue *pwq;
  3327. if (flush_color >= 0) {
  3328. WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
  3329. atomic_set(&wq->nr_pwqs_to_flush, 1);
  3330. }
  3331. for_each_pwq(pwq, wq) {
  3332. struct worker_pool *pool = pwq->pool;
  3333. raw_spin_lock_irq(&pool->lock);
  3334. if (flush_color >= 0) {
  3335. WARN_ON_ONCE(pwq->flush_color != -1);
  3336. if (pwq->nr_in_flight[flush_color]) {
  3337. pwq->flush_color = flush_color;
  3338. atomic_inc(&wq->nr_pwqs_to_flush);
  3339. wait = true;
  3340. }
  3341. }
  3342. if (work_color >= 0) {
  3343. WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
  3344. pwq->work_color = work_color;
  3345. }
  3346. raw_spin_unlock_irq(&pool->lock);
  3347. }
  3348. if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
  3349. complete(&wq->first_flusher->done);
  3350. return wait;
  3351. }
  3352. static void touch_wq_lockdep_map(struct workqueue_struct *wq)
  3353. {
  3354. #ifdef CONFIG_LOCKDEP
  3355. if (unlikely(!wq->lockdep_map))
  3356. return;
  3357. if (wq->flags & WQ_BH)
  3358. local_bh_disable();
  3359. lock_map_acquire(wq->lockdep_map);
  3360. lock_map_release(wq->lockdep_map);
  3361. if (wq->flags & WQ_BH)
  3362. local_bh_enable();
  3363. #endif
  3364. }
  3365. static void touch_work_lockdep_map(struct work_struct *work,
  3366. struct workqueue_struct *wq)
  3367. {
  3368. #ifdef CONFIG_LOCKDEP
  3369. if (wq->flags & WQ_BH)
  3370. local_bh_disable();
  3371. lock_map_acquire(&work->lockdep_map);
  3372. lock_map_release(&work->lockdep_map);
  3373. if (wq->flags & WQ_BH)
  3374. local_bh_enable();
  3375. #endif
  3376. }
  3377. /**
  3378. * __flush_workqueue - ensure that any scheduled work has run to completion.
  3379. * @wq: workqueue to flush
  3380. *
  3381. * This function sleeps until all work items which were queued on entry
  3382. * have finished execution, but it is not livelocked by new incoming ones.
  3383. */
  3384. void __flush_workqueue(struct workqueue_struct *wq)
  3385. {
  3386. struct wq_flusher this_flusher = {
  3387. .list = LIST_HEAD_INIT(this_flusher.list),
  3388. .flush_color = -1,
  3389. .done = COMPLETION_INITIALIZER_ONSTACK_MAP(this_flusher.done, (*wq->lockdep_map)),
  3390. };
  3391. int next_color;
  3392. if (WARN_ON(!wq_online))
  3393. return;
  3394. touch_wq_lockdep_map(wq);
  3395. mutex_lock(&wq->mutex);
  3396. /*
  3397. * Start-to-wait phase
  3398. */
  3399. next_color = work_next_color(wq->work_color);
  3400. if (next_color != wq->flush_color) {
  3401. /*
  3402. * Color space is not full. The current work_color
  3403. * becomes our flush_color and work_color is advanced
  3404. * by one.
  3405. */
  3406. WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
  3407. this_flusher.flush_color = wq->work_color;
  3408. wq->work_color = next_color;
  3409. if (!wq->first_flusher) {
  3410. /* no flush in progress, become the first flusher */
  3411. WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
  3412. wq->first_flusher = &this_flusher;
  3413. if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
  3414. wq->work_color)) {
  3415. /* nothing to flush, done */
  3416. wq->flush_color = next_color;
  3417. wq->first_flusher = NULL;
  3418. goto out_unlock;
  3419. }
  3420. } else {
  3421. /* wait in queue */
  3422. WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
  3423. list_add_tail(&this_flusher.list, &wq->flusher_queue);
  3424. flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
  3425. }
  3426. } else {
  3427. /*
  3428. * Oops, color space is full, wait on overflow queue.
  3429. * The next flush completion will assign us
  3430. * flush_color and transfer to flusher_queue.
  3431. */
  3432. list_add_tail(&this_flusher.list, &wq->flusher_overflow);
  3433. }
  3434. check_flush_dependency(wq, NULL, false);
  3435. mutex_unlock(&wq->mutex);
  3436. wait_for_completion(&this_flusher.done);
  3437. /*
  3438. * Wake-up-and-cascade phase
  3439. *
  3440. * First flushers are responsible for cascading flushes and
  3441. * handling overflow. Non-first flushers can simply return.
  3442. */
  3443. if (READ_ONCE(wq->first_flusher) != &this_flusher)
  3444. return;
  3445. mutex_lock(&wq->mutex);
  3446. /* we might have raced, check again with mutex held */
  3447. if (wq->first_flusher != &this_flusher)
  3448. goto out_unlock;
  3449. WRITE_ONCE(wq->first_flusher, NULL);
  3450. WARN_ON_ONCE(!list_empty(&this_flusher.list));
  3451. WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
  3452. while (true) {
  3453. struct wq_flusher *next, *tmp;
  3454. /* complete all the flushers sharing the current flush color */
  3455. list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
  3456. if (next->flush_color != wq->flush_color)
  3457. break;
  3458. list_del_init(&next->list);
  3459. complete(&next->done);
  3460. }
  3461. WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
  3462. wq->flush_color != work_next_color(wq->work_color));
  3463. /* this flush_color is finished, advance by one */
  3464. wq->flush_color = work_next_color(wq->flush_color);
  3465. /* one color has been freed, handle overflow queue */
  3466. if (!list_empty(&wq->flusher_overflow)) {
  3467. /*
  3468. * Assign the same color to all overflowed
  3469. * flushers, advance work_color and append to
  3470. * flusher_queue. This is the start-to-wait
  3471. * phase for these overflowed flushers.
  3472. */
  3473. list_for_each_entry(tmp, &wq->flusher_overflow, list)
  3474. tmp->flush_color = wq->work_color;
  3475. wq->work_color = work_next_color(wq->work_color);
  3476. list_splice_tail_init(&wq->flusher_overflow,
  3477. &wq->flusher_queue);
  3478. flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
  3479. }
  3480. if (list_empty(&wq->flusher_queue)) {
  3481. WARN_ON_ONCE(wq->flush_color != wq->work_color);
  3482. break;
  3483. }
  3484. /*
  3485. * Need to flush more colors. Make the next flusher
  3486. * the new first flusher and arm pwqs.
  3487. */
  3488. WARN_ON_ONCE(wq->flush_color == wq->work_color);
  3489. WARN_ON_ONCE(wq->flush_color != next->flush_color);
  3490. list_del_init(&next->list);
  3491. wq->first_flusher = next;
  3492. if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
  3493. break;
  3494. /*
  3495. * Meh... this color is already done, clear first
  3496. * flusher and repeat cascading.
  3497. */
  3498. wq->first_flusher = NULL;
  3499. }
  3500. out_unlock:
  3501. mutex_unlock(&wq->mutex);
  3502. }
  3503. EXPORT_SYMBOL(__flush_workqueue);
  3504. /**
  3505. * drain_workqueue - drain a workqueue
  3506. * @wq: workqueue to drain
  3507. *
  3508. * Wait until the workqueue becomes empty. While draining is in progress,
  3509. * only chain queueing is allowed. IOW, only currently pending or running
  3510. * work items on @wq can queue further work items on it. @wq is flushed
  3511. * repeatedly until it becomes empty. The number of flushing is determined
  3512. * by the depth of chaining and should be relatively short. Whine if it
  3513. * takes too long.
  3514. */
  3515. void drain_workqueue(struct workqueue_struct *wq)
  3516. {
  3517. unsigned int flush_cnt = 0;
  3518. struct pool_workqueue *pwq;
  3519. /*
  3520. * __queue_work() needs to test whether there are drainers, is much
  3521. * hotter than drain_workqueue() and already looks at @wq->flags.
  3522. * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
  3523. */
  3524. mutex_lock(&wq->mutex);
  3525. if (!wq->nr_drainers++)
  3526. wq->flags |= __WQ_DRAINING;
  3527. mutex_unlock(&wq->mutex);
  3528. reflush:
  3529. __flush_workqueue(wq);
  3530. mutex_lock(&wq->mutex);
  3531. for_each_pwq(pwq, wq) {
  3532. bool drained;
  3533. raw_spin_lock_irq(&pwq->pool->lock);
  3534. drained = pwq_is_empty(pwq);
  3535. raw_spin_unlock_irq(&pwq->pool->lock);
  3536. if (drained)
  3537. continue;
  3538. if (++flush_cnt == 10 ||
  3539. (flush_cnt % 100 == 0 && flush_cnt <= 1000))
  3540. pr_warn("workqueue %s: %s() isn't complete after %u tries\n",
  3541. wq->name, __func__, flush_cnt);
  3542. mutex_unlock(&wq->mutex);
  3543. goto reflush;
  3544. }
  3545. if (!--wq->nr_drainers)
  3546. wq->flags &= ~__WQ_DRAINING;
  3547. mutex_unlock(&wq->mutex);
  3548. }
  3549. EXPORT_SYMBOL_GPL(drain_workqueue);
  3550. static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr,
  3551. bool from_cancel)
  3552. {
  3553. struct worker *worker = NULL;
  3554. struct worker_pool *pool;
  3555. struct pool_workqueue *pwq;
  3556. struct workqueue_struct *wq;
  3557. rcu_read_lock();
  3558. pool = get_work_pool(work);
  3559. if (!pool) {
  3560. rcu_read_unlock();
  3561. return false;
  3562. }
  3563. raw_spin_lock_irq(&pool->lock);
  3564. /* see the comment in try_to_grab_pending() with the same code */
  3565. pwq = get_work_pwq(work);
  3566. if (pwq) {
  3567. if (unlikely(pwq->pool != pool))
  3568. goto already_gone;
  3569. } else {
  3570. worker = find_worker_executing_work(pool, work);
  3571. if (!worker)
  3572. goto already_gone;
  3573. pwq = worker->current_pwq;
  3574. }
  3575. wq = pwq->wq;
  3576. check_flush_dependency(wq, work, from_cancel);
  3577. insert_wq_barrier(pwq, barr, work, worker);
  3578. raw_spin_unlock_irq(&pool->lock);
  3579. touch_work_lockdep_map(work, wq);
  3580. /*
  3581. * Force a lock recursion deadlock when using flush_work() inside a
  3582. * single-threaded or rescuer equipped workqueue.
  3583. *
  3584. * For single threaded workqueues the deadlock happens when the work
  3585. * is after the work issuing the flush_work(). For rescuer equipped
  3586. * workqueues the deadlock happens when the rescuer stalls, blocking
  3587. * forward progress.
  3588. */
  3589. if (!from_cancel && (wq->saved_max_active == 1 || wq->rescuer))
  3590. touch_wq_lockdep_map(wq);
  3591. rcu_read_unlock();
  3592. return true;
  3593. already_gone:
  3594. raw_spin_unlock_irq(&pool->lock);
  3595. rcu_read_unlock();
  3596. return false;
  3597. }
  3598. static bool __flush_work(struct work_struct *work, bool from_cancel)
  3599. {
  3600. struct wq_barrier barr;
  3601. if (WARN_ON(!wq_online))
  3602. return false;
  3603. if (WARN_ON(!work->func))
  3604. return false;
  3605. if (!start_flush_work(work, &barr, from_cancel))
  3606. return false;
  3607. /*
  3608. * start_flush_work() returned %true. If @from_cancel is set, we know
  3609. * that @work must have been executing during start_flush_work() and
  3610. * can't currently be queued. Its data must contain OFFQ bits. If @work
  3611. * was queued on a BH workqueue, we also know that it was running in the
  3612. * BH context and thus can be busy-waited.
  3613. */
  3614. if (from_cancel) {
  3615. unsigned long data = *work_data_bits(work);
  3616. if (!WARN_ON_ONCE(data & WORK_STRUCT_PWQ) &&
  3617. (data & WORK_OFFQ_BH)) {
  3618. /*
  3619. * On RT, prevent a live lock when %current preempted
  3620. * soft interrupt processing or prevents ksoftirqd from
  3621. * running by keeping flipping BH. If the BH work item
  3622. * runs on a different CPU then this has no effect other
  3623. * than doing the BH disable/enable dance for nothing.
  3624. * This is copied from
  3625. * kernel/softirq.c::tasklet_unlock_spin_wait().
  3626. */
  3627. while (!try_wait_for_completion(&barr.done)) {
  3628. if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
  3629. local_bh_disable();
  3630. local_bh_enable();
  3631. } else {
  3632. cpu_relax();
  3633. }
  3634. }
  3635. goto out_destroy;
  3636. }
  3637. }
  3638. wait_for_completion(&barr.done);
  3639. out_destroy:
  3640. destroy_work_on_stack(&barr.work);
  3641. return true;
  3642. }
  3643. /**
  3644. * flush_work - wait for a work to finish executing the last queueing instance
  3645. * @work: the work to flush
  3646. *
  3647. * Wait until @work has finished execution. @work is guaranteed to be idle
  3648. * on return if it hasn't been requeued since flush started.
  3649. *
  3650. * Return:
  3651. * %true if flush_work() waited for the work to finish execution,
  3652. * %false if it was already idle.
  3653. */
  3654. bool flush_work(struct work_struct *work)
  3655. {
  3656. might_sleep();
  3657. return __flush_work(work, false);
  3658. }
  3659. EXPORT_SYMBOL_GPL(flush_work);
  3660. /**
  3661. * flush_delayed_work - wait for a dwork to finish executing the last queueing
  3662. * @dwork: the delayed work to flush
  3663. *
  3664. * Delayed timer is cancelled and the pending work is queued for
  3665. * immediate execution. Like flush_work(), this function only
  3666. * considers the last queueing instance of @dwork.
  3667. *
  3668. * Return:
  3669. * %true if flush_work() waited for the work to finish execution,
  3670. * %false if it was already idle.
  3671. */
  3672. bool flush_delayed_work(struct delayed_work *dwork)
  3673. {
  3674. local_irq_disable();
  3675. if (del_timer_sync(&dwork->timer))
  3676. __queue_work(dwork->cpu, dwork->wq, &dwork->work);
  3677. local_irq_enable();
  3678. return flush_work(&dwork->work);
  3679. }
  3680. EXPORT_SYMBOL(flush_delayed_work);
  3681. /**
  3682. * flush_rcu_work - wait for a rwork to finish executing the last queueing
  3683. * @rwork: the rcu work to flush
  3684. *
  3685. * Return:
  3686. * %true if flush_rcu_work() waited for the work to finish execution,
  3687. * %false if it was already idle.
  3688. */
  3689. bool flush_rcu_work(struct rcu_work *rwork)
  3690. {
  3691. if (test_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&rwork->work))) {
  3692. rcu_barrier();
  3693. flush_work(&rwork->work);
  3694. return true;
  3695. } else {
  3696. return flush_work(&rwork->work);
  3697. }
  3698. }
  3699. EXPORT_SYMBOL(flush_rcu_work);
  3700. static void work_offqd_disable(struct work_offq_data *offqd)
  3701. {
  3702. const unsigned long max = (1lu << WORK_OFFQ_DISABLE_BITS) - 1;
  3703. if (likely(offqd->disable < max))
  3704. offqd->disable++;
  3705. else
  3706. WARN_ONCE(true, "workqueue: work disable count overflowed\n");
  3707. }
  3708. static void work_offqd_enable(struct work_offq_data *offqd)
  3709. {
  3710. if (likely(offqd->disable > 0))
  3711. offqd->disable--;
  3712. else
  3713. WARN_ONCE(true, "workqueue: work disable count underflowed\n");
  3714. }
  3715. static bool __cancel_work(struct work_struct *work, u32 cflags)
  3716. {
  3717. struct work_offq_data offqd;
  3718. unsigned long irq_flags;
  3719. int ret;
  3720. ret = work_grab_pending(work, cflags, &irq_flags);
  3721. work_offqd_unpack(&offqd, *work_data_bits(work));
  3722. if (cflags & WORK_CANCEL_DISABLE)
  3723. work_offqd_disable(&offqd);
  3724. set_work_pool_and_clear_pending(work, offqd.pool_id,
  3725. work_offqd_pack_flags(&offqd));
  3726. local_irq_restore(irq_flags);
  3727. return ret;
  3728. }
  3729. static bool __cancel_work_sync(struct work_struct *work, u32 cflags)
  3730. {
  3731. bool ret;
  3732. ret = __cancel_work(work, cflags | WORK_CANCEL_DISABLE);
  3733. if (*work_data_bits(work) & WORK_OFFQ_BH)
  3734. WARN_ON_ONCE(in_hardirq());
  3735. else
  3736. might_sleep();
  3737. /*
  3738. * Skip __flush_work() during early boot when we know that @work isn't
  3739. * executing. This allows canceling during early boot.
  3740. */
  3741. if (wq_online)
  3742. __flush_work(work, true);
  3743. if (!(cflags & WORK_CANCEL_DISABLE))
  3744. enable_work(work);
  3745. return ret;
  3746. }
  3747. /*
  3748. * See cancel_delayed_work()
  3749. */
  3750. bool cancel_work(struct work_struct *work)
  3751. {
  3752. return __cancel_work(work, 0);
  3753. }
  3754. EXPORT_SYMBOL(cancel_work);
  3755. /**
  3756. * cancel_work_sync - cancel a work and wait for it to finish
  3757. * @work: the work to cancel
  3758. *
  3759. * Cancel @work and wait for its execution to finish. This function can be used
  3760. * even if the work re-queues itself or migrates to another workqueue. On return
  3761. * from this function, @work is guaranteed to be not pending or executing on any
  3762. * CPU as long as there aren't racing enqueues.
  3763. *
  3764. * cancel_work_sync(&delayed_work->work) must not be used for delayed_work's.
  3765. * Use cancel_delayed_work_sync() instead.
  3766. *
  3767. * Must be called from a sleepable context if @work was last queued on a non-BH
  3768. * workqueue. Can also be called from non-hardirq atomic contexts including BH
  3769. * if @work was last queued on a BH workqueue.
  3770. *
  3771. * Returns %true if @work was pending, %false otherwise.
  3772. */
  3773. bool cancel_work_sync(struct work_struct *work)
  3774. {
  3775. return __cancel_work_sync(work, 0);
  3776. }
  3777. EXPORT_SYMBOL_GPL(cancel_work_sync);
  3778. /**
  3779. * cancel_delayed_work - cancel a delayed work
  3780. * @dwork: delayed_work to cancel
  3781. *
  3782. * Kill off a pending delayed_work.
  3783. *
  3784. * Return: %true if @dwork was pending and canceled; %false if it wasn't
  3785. * pending.
  3786. *
  3787. * Note:
  3788. * The work callback function may still be running on return, unless
  3789. * it returns %true and the work doesn't re-arm itself. Explicitly flush or
  3790. * use cancel_delayed_work_sync() to wait on it.
  3791. *
  3792. * This function is safe to call from any context including IRQ handler.
  3793. */
  3794. bool cancel_delayed_work(struct delayed_work *dwork)
  3795. {
  3796. return __cancel_work(&dwork->work, WORK_CANCEL_DELAYED);
  3797. }
  3798. EXPORT_SYMBOL(cancel_delayed_work);
  3799. /**
  3800. * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
  3801. * @dwork: the delayed work cancel
  3802. *
  3803. * This is cancel_work_sync() for delayed works.
  3804. *
  3805. * Return:
  3806. * %true if @dwork was pending, %false otherwise.
  3807. */
  3808. bool cancel_delayed_work_sync(struct delayed_work *dwork)
  3809. {
  3810. return __cancel_work_sync(&dwork->work, WORK_CANCEL_DELAYED);
  3811. }
  3812. EXPORT_SYMBOL(cancel_delayed_work_sync);
  3813. /**
  3814. * disable_work - Disable and cancel a work item
  3815. * @work: work item to disable
  3816. *
  3817. * Disable @work by incrementing its disable count and cancel it if currently
  3818. * pending. As long as the disable count is non-zero, any attempt to queue @work
  3819. * will fail and return %false. The maximum supported disable depth is 2 to the
  3820. * power of %WORK_OFFQ_DISABLE_BITS, currently 65536.
  3821. *
  3822. * Can be called from any context. Returns %true if @work was pending, %false
  3823. * otherwise.
  3824. */
  3825. bool disable_work(struct work_struct *work)
  3826. {
  3827. return __cancel_work(work, WORK_CANCEL_DISABLE);
  3828. }
  3829. EXPORT_SYMBOL_GPL(disable_work);
  3830. /**
  3831. * disable_work_sync - Disable, cancel and drain a work item
  3832. * @work: work item to disable
  3833. *
  3834. * Similar to disable_work() but also wait for @work to finish if currently
  3835. * executing.
  3836. *
  3837. * Must be called from a sleepable context if @work was last queued on a non-BH
  3838. * workqueue. Can also be called from non-hardirq atomic contexts including BH
  3839. * if @work was last queued on a BH workqueue.
  3840. *
  3841. * Returns %true if @work was pending, %false otherwise.
  3842. */
  3843. bool disable_work_sync(struct work_struct *work)
  3844. {
  3845. return __cancel_work_sync(work, WORK_CANCEL_DISABLE);
  3846. }
  3847. EXPORT_SYMBOL_GPL(disable_work_sync);
  3848. /**
  3849. * enable_work - Enable a work item
  3850. * @work: work item to enable
  3851. *
  3852. * Undo disable_work[_sync]() by decrementing @work's disable count. @work can
  3853. * only be queued if its disable count is 0.
  3854. *
  3855. * Can be called from any context. Returns %true if the disable count reached 0.
  3856. * Otherwise, %false.
  3857. */
  3858. bool enable_work(struct work_struct *work)
  3859. {
  3860. struct work_offq_data offqd;
  3861. unsigned long irq_flags;
  3862. work_grab_pending(work, 0, &irq_flags);
  3863. work_offqd_unpack(&offqd, *work_data_bits(work));
  3864. work_offqd_enable(&offqd);
  3865. set_work_pool_and_clear_pending(work, offqd.pool_id,
  3866. work_offqd_pack_flags(&offqd));
  3867. local_irq_restore(irq_flags);
  3868. return !offqd.disable;
  3869. }
  3870. EXPORT_SYMBOL_GPL(enable_work);
  3871. /**
  3872. * disable_delayed_work - Disable and cancel a delayed work item
  3873. * @dwork: delayed work item to disable
  3874. *
  3875. * disable_work() for delayed work items.
  3876. */
  3877. bool disable_delayed_work(struct delayed_work *dwork)
  3878. {
  3879. return __cancel_work(&dwork->work,
  3880. WORK_CANCEL_DELAYED | WORK_CANCEL_DISABLE);
  3881. }
  3882. EXPORT_SYMBOL_GPL(disable_delayed_work);
  3883. /**
  3884. * disable_delayed_work_sync - Disable, cancel and drain a delayed work item
  3885. * @dwork: delayed work item to disable
  3886. *
  3887. * disable_work_sync() for delayed work items.
  3888. */
  3889. bool disable_delayed_work_sync(struct delayed_work *dwork)
  3890. {
  3891. return __cancel_work_sync(&dwork->work,
  3892. WORK_CANCEL_DELAYED | WORK_CANCEL_DISABLE);
  3893. }
  3894. EXPORT_SYMBOL_GPL(disable_delayed_work_sync);
  3895. /**
  3896. * enable_delayed_work - Enable a delayed work item
  3897. * @dwork: delayed work item to enable
  3898. *
  3899. * enable_work() for delayed work items.
  3900. */
  3901. bool enable_delayed_work(struct delayed_work *dwork)
  3902. {
  3903. return enable_work(&dwork->work);
  3904. }
  3905. EXPORT_SYMBOL_GPL(enable_delayed_work);
  3906. /**
  3907. * schedule_on_each_cpu - execute a function synchronously on each online CPU
  3908. * @func: the function to call
  3909. *
  3910. * schedule_on_each_cpu() executes @func on each online CPU using the
  3911. * system workqueue and blocks until all CPUs have completed.
  3912. * schedule_on_each_cpu() is very slow.
  3913. *
  3914. * Return:
  3915. * 0 on success, -errno on failure.
  3916. */
  3917. int schedule_on_each_cpu(work_func_t func)
  3918. {
  3919. int cpu;
  3920. struct work_struct __percpu *works;
  3921. works = alloc_percpu(struct work_struct);
  3922. if (!works)
  3923. return -ENOMEM;
  3924. cpus_read_lock();
  3925. for_each_online_cpu(cpu) {
  3926. struct work_struct *work = per_cpu_ptr(works, cpu);
  3927. INIT_WORK(work, func);
  3928. schedule_work_on(cpu, work);
  3929. }
  3930. for_each_online_cpu(cpu)
  3931. flush_work(per_cpu_ptr(works, cpu));
  3932. cpus_read_unlock();
  3933. free_percpu(works);
  3934. return 0;
  3935. }
  3936. /**
  3937. * execute_in_process_context - reliably execute the routine with user context
  3938. * @fn: the function to execute
  3939. * @ew: guaranteed storage for the execute work structure (must
  3940. * be available when the work executes)
  3941. *
  3942. * Executes the function immediately if process context is available,
  3943. * otherwise schedules the function for delayed execution.
  3944. *
  3945. * Return: 0 - function was executed
  3946. * 1 - function was scheduled for execution
  3947. */
  3948. int execute_in_process_context(work_func_t fn, struct execute_work *ew)
  3949. {
  3950. if (!in_interrupt()) {
  3951. fn(&ew->work);
  3952. return 0;
  3953. }
  3954. INIT_WORK(&ew->work, fn);
  3955. schedule_work(&ew->work);
  3956. return 1;
  3957. }
  3958. EXPORT_SYMBOL_GPL(execute_in_process_context);
  3959. /**
  3960. * free_workqueue_attrs - free a workqueue_attrs
  3961. * @attrs: workqueue_attrs to free
  3962. *
  3963. * Undo alloc_workqueue_attrs().
  3964. */
  3965. void free_workqueue_attrs(struct workqueue_attrs *attrs)
  3966. {
  3967. if (attrs) {
  3968. free_cpumask_var(attrs->cpumask);
  3969. free_cpumask_var(attrs->__pod_cpumask);
  3970. kfree(attrs);
  3971. }
  3972. }
  3973. /**
  3974. * alloc_workqueue_attrs - allocate a workqueue_attrs
  3975. *
  3976. * Allocate a new workqueue_attrs, initialize with default settings and
  3977. * return it.
  3978. *
  3979. * Return: The allocated new workqueue_attr on success. %NULL on failure.
  3980. */
  3981. struct workqueue_attrs *alloc_workqueue_attrs(void)
  3982. {
  3983. struct workqueue_attrs *attrs;
  3984. attrs = kzalloc(sizeof(*attrs), GFP_KERNEL);
  3985. if (!attrs)
  3986. goto fail;
  3987. if (!alloc_cpumask_var(&attrs->cpumask, GFP_KERNEL))
  3988. goto fail;
  3989. if (!alloc_cpumask_var(&attrs->__pod_cpumask, GFP_KERNEL))
  3990. goto fail;
  3991. cpumask_copy(attrs->cpumask, cpu_possible_mask);
  3992. attrs->affn_scope = WQ_AFFN_DFL;
  3993. return attrs;
  3994. fail:
  3995. free_workqueue_attrs(attrs);
  3996. return NULL;
  3997. }
  3998. static void copy_workqueue_attrs(struct workqueue_attrs *to,
  3999. const struct workqueue_attrs *from)
  4000. {
  4001. to->nice = from->nice;
  4002. cpumask_copy(to->cpumask, from->cpumask);
  4003. cpumask_copy(to->__pod_cpumask, from->__pod_cpumask);
  4004. to->affn_strict = from->affn_strict;
  4005. /*
  4006. * Unlike hash and equality test, copying shouldn't ignore wq-only
  4007. * fields as copying is used for both pool and wq attrs. Instead,
  4008. * get_unbound_pool() explicitly clears the fields.
  4009. */
  4010. to->affn_scope = from->affn_scope;
  4011. to->ordered = from->ordered;
  4012. }
  4013. /*
  4014. * Some attrs fields are workqueue-only. Clear them for worker_pool's. See the
  4015. * comments in 'struct workqueue_attrs' definition.
  4016. */
  4017. static void wqattrs_clear_for_pool(struct workqueue_attrs *attrs)
  4018. {
  4019. attrs->affn_scope = WQ_AFFN_NR_TYPES;
  4020. attrs->ordered = false;
  4021. if (attrs->affn_strict)
  4022. cpumask_copy(attrs->cpumask, cpu_possible_mask);
  4023. }
  4024. /* hash value of the content of @attr */
  4025. static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
  4026. {
  4027. u32 hash = 0;
  4028. hash = jhash_1word(attrs->nice, hash);
  4029. hash = jhash_1word(attrs->affn_strict, hash);
  4030. hash = jhash(cpumask_bits(attrs->__pod_cpumask),
  4031. BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
  4032. if (!attrs->affn_strict)
  4033. hash = jhash(cpumask_bits(attrs->cpumask),
  4034. BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
  4035. return hash;
  4036. }
  4037. /* content equality test */
  4038. static bool wqattrs_equal(const struct workqueue_attrs *a,
  4039. const struct workqueue_attrs *b)
  4040. {
  4041. if (a->nice != b->nice)
  4042. return false;
  4043. if (a->affn_strict != b->affn_strict)
  4044. return false;
  4045. if (!cpumask_equal(a->__pod_cpumask, b->__pod_cpumask))
  4046. return false;
  4047. if (!a->affn_strict && !cpumask_equal(a->cpumask, b->cpumask))
  4048. return false;
  4049. return true;
  4050. }
  4051. /* Update @attrs with actually available CPUs */
  4052. static void wqattrs_actualize_cpumask(struct workqueue_attrs *attrs,
  4053. const cpumask_t *unbound_cpumask)
  4054. {
  4055. /*
  4056. * Calculate the effective CPU mask of @attrs given @unbound_cpumask. If
  4057. * @attrs->cpumask doesn't overlap with @unbound_cpumask, we fallback to
  4058. * @unbound_cpumask.
  4059. */
  4060. cpumask_and(attrs->cpumask, attrs->cpumask, unbound_cpumask);
  4061. if (unlikely(cpumask_empty(attrs->cpumask)))
  4062. cpumask_copy(attrs->cpumask, unbound_cpumask);
  4063. }
  4064. /* find wq_pod_type to use for @attrs */
  4065. static const struct wq_pod_type *
  4066. wqattrs_pod_type(const struct workqueue_attrs *attrs)
  4067. {
  4068. enum wq_affn_scope scope;
  4069. struct wq_pod_type *pt;
  4070. /* to synchronize access to wq_affn_dfl */
  4071. lockdep_assert_held(&wq_pool_mutex);
  4072. if (attrs->affn_scope == WQ_AFFN_DFL)
  4073. scope = wq_affn_dfl;
  4074. else
  4075. scope = attrs->affn_scope;
  4076. pt = &wq_pod_types[scope];
  4077. if (!WARN_ON_ONCE(attrs->affn_scope == WQ_AFFN_NR_TYPES) &&
  4078. likely(pt->nr_pods))
  4079. return pt;
  4080. /*
  4081. * Before workqueue_init_topology(), only SYSTEM is available which is
  4082. * initialized in workqueue_init_early().
  4083. */
  4084. pt = &wq_pod_types[WQ_AFFN_SYSTEM];
  4085. BUG_ON(!pt->nr_pods);
  4086. return pt;
  4087. }
  4088. /**
  4089. * init_worker_pool - initialize a newly zalloc'd worker_pool
  4090. * @pool: worker_pool to initialize
  4091. *
  4092. * Initialize a newly zalloc'd @pool. It also allocates @pool->attrs.
  4093. *
  4094. * Return: 0 on success, -errno on failure. Even on failure, all fields
  4095. * inside @pool proper are initialized and put_unbound_pool() can be called
  4096. * on @pool safely to release it.
  4097. */
  4098. static int init_worker_pool(struct worker_pool *pool)
  4099. {
  4100. raw_spin_lock_init(&pool->lock);
  4101. pool->id = -1;
  4102. pool->cpu = -1;
  4103. pool->node = NUMA_NO_NODE;
  4104. pool->flags |= POOL_DISASSOCIATED;
  4105. pool->watchdog_ts = jiffies;
  4106. INIT_LIST_HEAD(&pool->worklist);
  4107. INIT_LIST_HEAD(&pool->idle_list);
  4108. hash_init(pool->busy_hash);
  4109. timer_setup(&pool->idle_timer, idle_worker_timeout, TIMER_DEFERRABLE);
  4110. INIT_WORK(&pool->idle_cull_work, idle_cull_fn);
  4111. timer_setup(&pool->mayday_timer, pool_mayday_timeout, 0);
  4112. INIT_LIST_HEAD(&pool->workers);
  4113. ida_init(&pool->worker_ida);
  4114. INIT_HLIST_NODE(&pool->hash_node);
  4115. pool->refcnt = 1;
  4116. /* shouldn't fail above this point */
  4117. pool->attrs = alloc_workqueue_attrs();
  4118. if (!pool->attrs)
  4119. return -ENOMEM;
  4120. wqattrs_clear_for_pool(pool->attrs);
  4121. return 0;
  4122. }
  4123. #ifdef CONFIG_LOCKDEP
  4124. static void wq_init_lockdep(struct workqueue_struct *wq)
  4125. {
  4126. char *lock_name;
  4127. lockdep_register_key(&wq->key);
  4128. lock_name = kasprintf(GFP_KERNEL, "%s%s", "(wq_completion)", wq->name);
  4129. if (!lock_name)
  4130. lock_name = wq->name;
  4131. wq->lock_name = lock_name;
  4132. wq->lockdep_map = &wq->__lockdep_map;
  4133. lockdep_init_map(wq->lockdep_map, lock_name, &wq->key, 0);
  4134. }
  4135. static void wq_unregister_lockdep(struct workqueue_struct *wq)
  4136. {
  4137. if (wq->lockdep_map != &wq->__lockdep_map)
  4138. return;
  4139. lockdep_unregister_key(&wq->key);
  4140. }
  4141. static void wq_free_lockdep(struct workqueue_struct *wq)
  4142. {
  4143. if (wq->lockdep_map != &wq->__lockdep_map)
  4144. return;
  4145. if (wq->lock_name != wq->name)
  4146. kfree(wq->lock_name);
  4147. }
  4148. #else
  4149. static void wq_init_lockdep(struct workqueue_struct *wq)
  4150. {
  4151. }
  4152. static void wq_unregister_lockdep(struct workqueue_struct *wq)
  4153. {
  4154. }
  4155. static void wq_free_lockdep(struct workqueue_struct *wq)
  4156. {
  4157. }
  4158. #endif
  4159. static void free_node_nr_active(struct wq_node_nr_active **nna_ar)
  4160. {
  4161. int node;
  4162. for_each_node(node) {
  4163. kfree(nna_ar[node]);
  4164. nna_ar[node] = NULL;
  4165. }
  4166. kfree(nna_ar[nr_node_ids]);
  4167. nna_ar[nr_node_ids] = NULL;
  4168. }
  4169. static void init_node_nr_active(struct wq_node_nr_active *nna)
  4170. {
  4171. nna->max = WQ_DFL_MIN_ACTIVE;
  4172. atomic_set(&nna->nr, 0);
  4173. raw_spin_lock_init(&nna->lock);
  4174. INIT_LIST_HEAD(&nna->pending_pwqs);
  4175. }
  4176. /*
  4177. * Each node's nr_active counter will be accessed mostly from its own node and
  4178. * should be allocated in the node.
  4179. */
  4180. static int alloc_node_nr_active(struct wq_node_nr_active **nna_ar)
  4181. {
  4182. struct wq_node_nr_active *nna;
  4183. int node;
  4184. for_each_node(node) {
  4185. nna = kzalloc_node(sizeof(*nna), GFP_KERNEL, node);
  4186. if (!nna)
  4187. goto err_free;
  4188. init_node_nr_active(nna);
  4189. nna_ar[node] = nna;
  4190. }
  4191. /* [nr_node_ids] is used as the fallback */
  4192. nna = kzalloc_node(sizeof(*nna), GFP_KERNEL, NUMA_NO_NODE);
  4193. if (!nna)
  4194. goto err_free;
  4195. init_node_nr_active(nna);
  4196. nna_ar[nr_node_ids] = nna;
  4197. return 0;
  4198. err_free:
  4199. free_node_nr_active(nna_ar);
  4200. return -ENOMEM;
  4201. }
  4202. static void rcu_free_wq(struct rcu_head *rcu)
  4203. {
  4204. struct workqueue_struct *wq =
  4205. container_of(rcu, struct workqueue_struct, rcu);
  4206. if (wq->flags & WQ_UNBOUND)
  4207. free_node_nr_active(wq->node_nr_active);
  4208. wq_free_lockdep(wq);
  4209. free_percpu(wq->cpu_pwq);
  4210. free_workqueue_attrs(wq->unbound_attrs);
  4211. kfree(wq);
  4212. }
  4213. static void rcu_free_pool(struct rcu_head *rcu)
  4214. {
  4215. struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
  4216. ida_destroy(&pool->worker_ida);
  4217. free_workqueue_attrs(pool->attrs);
  4218. kfree(pool);
  4219. }
  4220. /**
  4221. * put_unbound_pool - put a worker_pool
  4222. * @pool: worker_pool to put
  4223. *
  4224. * Put @pool. If its refcnt reaches zero, it gets destroyed in RCU
  4225. * safe manner. get_unbound_pool() calls this function on its failure path
  4226. * and this function should be able to release pools which went through,
  4227. * successfully or not, init_worker_pool().
  4228. *
  4229. * Should be called with wq_pool_mutex held.
  4230. */
  4231. static void put_unbound_pool(struct worker_pool *pool)
  4232. {
  4233. struct worker *worker;
  4234. LIST_HEAD(cull_list);
  4235. lockdep_assert_held(&wq_pool_mutex);
  4236. if (--pool->refcnt)
  4237. return;
  4238. /* sanity checks */
  4239. if (WARN_ON(!(pool->cpu < 0)) ||
  4240. WARN_ON(!list_empty(&pool->worklist)))
  4241. return;
  4242. /* release id and unhash */
  4243. if (pool->id >= 0)
  4244. idr_remove(&worker_pool_idr, pool->id);
  4245. hash_del(&pool->hash_node);
  4246. /*
  4247. * Become the manager and destroy all workers. This prevents
  4248. * @pool's workers from blocking on attach_mutex. We're the last
  4249. * manager and @pool gets freed with the flag set.
  4250. *
  4251. * Having a concurrent manager is quite unlikely to happen as we can
  4252. * only get here with
  4253. * pwq->refcnt == pool->refcnt == 0
  4254. * which implies no work queued to the pool, which implies no worker can
  4255. * become the manager. However a worker could have taken the role of
  4256. * manager before the refcnts dropped to 0, since maybe_create_worker()
  4257. * drops pool->lock
  4258. */
  4259. while (true) {
  4260. rcuwait_wait_event(&manager_wait,
  4261. !(pool->flags & POOL_MANAGER_ACTIVE),
  4262. TASK_UNINTERRUPTIBLE);
  4263. mutex_lock(&wq_pool_attach_mutex);
  4264. raw_spin_lock_irq(&pool->lock);
  4265. if (!(pool->flags & POOL_MANAGER_ACTIVE)) {
  4266. pool->flags |= POOL_MANAGER_ACTIVE;
  4267. break;
  4268. }
  4269. raw_spin_unlock_irq(&pool->lock);
  4270. mutex_unlock(&wq_pool_attach_mutex);
  4271. }
  4272. while ((worker = first_idle_worker(pool)))
  4273. set_worker_dying(worker, &cull_list);
  4274. WARN_ON(pool->nr_workers || pool->nr_idle);
  4275. raw_spin_unlock_irq(&pool->lock);
  4276. detach_dying_workers(&cull_list);
  4277. mutex_unlock(&wq_pool_attach_mutex);
  4278. reap_dying_workers(&cull_list);
  4279. /* shut down the timers */
  4280. del_timer_sync(&pool->idle_timer);
  4281. cancel_work_sync(&pool->idle_cull_work);
  4282. del_timer_sync(&pool->mayday_timer);
  4283. /* RCU protected to allow dereferences from get_work_pool() */
  4284. call_rcu(&pool->rcu, rcu_free_pool);
  4285. }
  4286. /**
  4287. * get_unbound_pool - get a worker_pool with the specified attributes
  4288. * @attrs: the attributes of the worker_pool to get
  4289. *
  4290. * Obtain a worker_pool which has the same attributes as @attrs, bump the
  4291. * reference count and return it. If there already is a matching
  4292. * worker_pool, it will be used; otherwise, this function attempts to
  4293. * create a new one.
  4294. *
  4295. * Should be called with wq_pool_mutex held.
  4296. *
  4297. * Return: On success, a worker_pool with the same attributes as @attrs.
  4298. * On failure, %NULL.
  4299. */
  4300. static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
  4301. {
  4302. struct wq_pod_type *pt = &wq_pod_types[WQ_AFFN_NUMA];
  4303. u32 hash = wqattrs_hash(attrs);
  4304. struct worker_pool *pool;
  4305. int pod, node = NUMA_NO_NODE;
  4306. lockdep_assert_held(&wq_pool_mutex);
  4307. /* do we already have a matching pool? */
  4308. hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
  4309. if (wqattrs_equal(pool->attrs, attrs)) {
  4310. pool->refcnt++;
  4311. return pool;
  4312. }
  4313. }
  4314. /* If __pod_cpumask is contained inside a NUMA pod, that's our node */
  4315. for (pod = 0; pod < pt->nr_pods; pod++) {
  4316. if (cpumask_subset(attrs->__pod_cpumask, pt->pod_cpus[pod])) {
  4317. node = pt->pod_node[pod];
  4318. break;
  4319. }
  4320. }
  4321. /* nope, create a new one */
  4322. pool = kzalloc_node(sizeof(*pool), GFP_KERNEL, node);
  4323. if (!pool || init_worker_pool(pool) < 0)
  4324. goto fail;
  4325. pool->node = node;
  4326. copy_workqueue_attrs(pool->attrs, attrs);
  4327. wqattrs_clear_for_pool(pool->attrs);
  4328. if (worker_pool_assign_id(pool) < 0)
  4329. goto fail;
  4330. /* create and start the initial worker */
  4331. if (wq_online && !create_worker(pool))
  4332. goto fail;
  4333. /* install */
  4334. hash_add(unbound_pool_hash, &pool->hash_node, hash);
  4335. return pool;
  4336. fail:
  4337. if (pool)
  4338. put_unbound_pool(pool);
  4339. return NULL;
  4340. }
  4341. /*
  4342. * Scheduled on pwq_release_worker by put_pwq() when an unbound pwq hits zero
  4343. * refcnt and needs to be destroyed.
  4344. */
  4345. static void pwq_release_workfn(struct kthread_work *work)
  4346. {
  4347. struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
  4348. release_work);
  4349. struct workqueue_struct *wq = pwq->wq;
  4350. struct worker_pool *pool = pwq->pool;
  4351. bool is_last = false;
  4352. /*
  4353. * When @pwq is not linked, it doesn't hold any reference to the
  4354. * @wq, and @wq is invalid to access.
  4355. */
  4356. if (!list_empty(&pwq->pwqs_node)) {
  4357. mutex_lock(&wq->mutex);
  4358. list_del_rcu(&pwq->pwqs_node);
  4359. is_last = list_empty(&wq->pwqs);
  4360. /*
  4361. * For ordered workqueue with a plugged dfl_pwq, restart it now.
  4362. */
  4363. if (!is_last && (wq->flags & __WQ_ORDERED))
  4364. unplug_oldest_pwq(wq);
  4365. mutex_unlock(&wq->mutex);
  4366. }
  4367. if (wq->flags & WQ_UNBOUND) {
  4368. mutex_lock(&wq_pool_mutex);
  4369. put_unbound_pool(pool);
  4370. mutex_unlock(&wq_pool_mutex);
  4371. }
  4372. if (!list_empty(&pwq->pending_node)) {
  4373. struct wq_node_nr_active *nna =
  4374. wq_node_nr_active(pwq->wq, pwq->pool->node);
  4375. raw_spin_lock_irq(&nna->lock);
  4376. list_del_init(&pwq->pending_node);
  4377. raw_spin_unlock_irq(&nna->lock);
  4378. }
  4379. kfree_rcu(pwq, rcu);
  4380. /*
  4381. * If we're the last pwq going away, @wq is already dead and no one
  4382. * is gonna access it anymore. Schedule RCU free.
  4383. */
  4384. if (is_last) {
  4385. wq_unregister_lockdep(wq);
  4386. call_rcu(&wq->rcu, rcu_free_wq);
  4387. }
  4388. }
  4389. /* initialize newly allocated @pwq which is associated with @wq and @pool */
  4390. static void init_pwq(struct pool_workqueue *pwq, struct workqueue_struct *wq,
  4391. struct worker_pool *pool)
  4392. {
  4393. BUG_ON((unsigned long)pwq & ~WORK_STRUCT_PWQ_MASK);
  4394. memset(pwq, 0, sizeof(*pwq));
  4395. pwq->pool = pool;
  4396. pwq->wq = wq;
  4397. pwq->flush_color = -1;
  4398. pwq->refcnt = 1;
  4399. INIT_LIST_HEAD(&pwq->inactive_works);
  4400. INIT_LIST_HEAD(&pwq->pending_node);
  4401. INIT_LIST_HEAD(&pwq->pwqs_node);
  4402. INIT_LIST_HEAD(&pwq->mayday_node);
  4403. kthread_init_work(&pwq->release_work, pwq_release_workfn);
  4404. }
  4405. /* sync @pwq with the current state of its associated wq and link it */
  4406. static void link_pwq(struct pool_workqueue *pwq)
  4407. {
  4408. struct workqueue_struct *wq = pwq->wq;
  4409. lockdep_assert_held(&wq->mutex);
  4410. /* may be called multiple times, ignore if already linked */
  4411. if (!list_empty(&pwq->pwqs_node))
  4412. return;
  4413. /* set the matching work_color */
  4414. pwq->work_color = wq->work_color;
  4415. /* link in @pwq */
  4416. list_add_tail_rcu(&pwq->pwqs_node, &wq->pwqs);
  4417. }
  4418. /* obtain a pool matching @attr and create a pwq associating the pool and @wq */
  4419. static struct pool_workqueue *alloc_unbound_pwq(struct workqueue_struct *wq,
  4420. const struct workqueue_attrs *attrs)
  4421. {
  4422. struct worker_pool *pool;
  4423. struct pool_workqueue *pwq;
  4424. lockdep_assert_held(&wq_pool_mutex);
  4425. pool = get_unbound_pool(attrs);
  4426. if (!pool)
  4427. return NULL;
  4428. pwq = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL, pool->node);
  4429. if (!pwq) {
  4430. put_unbound_pool(pool);
  4431. return NULL;
  4432. }
  4433. init_pwq(pwq, wq, pool);
  4434. return pwq;
  4435. }
  4436. static void apply_wqattrs_lock(void)
  4437. {
  4438. mutex_lock(&wq_pool_mutex);
  4439. }
  4440. static void apply_wqattrs_unlock(void)
  4441. {
  4442. mutex_unlock(&wq_pool_mutex);
  4443. }
  4444. /**
  4445. * wq_calc_pod_cpumask - calculate a wq_attrs' cpumask for a pod
  4446. * @attrs: the wq_attrs of the default pwq of the target workqueue
  4447. * @cpu: the target CPU
  4448. *
  4449. * Calculate the cpumask a workqueue with @attrs should use on @pod.
  4450. * The result is stored in @attrs->__pod_cpumask.
  4451. *
  4452. * If pod affinity is not enabled, @attrs->cpumask is always used. If enabled
  4453. * and @pod has online CPUs requested by @attrs, the returned cpumask is the
  4454. * intersection of the possible CPUs of @pod and @attrs->cpumask.
  4455. *
  4456. * The caller is responsible for ensuring that the cpumask of @pod stays stable.
  4457. */
  4458. static void wq_calc_pod_cpumask(struct workqueue_attrs *attrs, int cpu)
  4459. {
  4460. const struct wq_pod_type *pt = wqattrs_pod_type(attrs);
  4461. int pod = pt->cpu_pod[cpu];
  4462. /* calculate possible CPUs in @pod that @attrs wants */
  4463. cpumask_and(attrs->__pod_cpumask, pt->pod_cpus[pod], attrs->cpumask);
  4464. /* does @pod have any online CPUs @attrs wants? */
  4465. if (!cpumask_intersects(attrs->__pod_cpumask, wq_online_cpumask)) {
  4466. cpumask_copy(attrs->__pod_cpumask, attrs->cpumask);
  4467. return;
  4468. }
  4469. }
  4470. /* install @pwq into @wq and return the old pwq, @cpu < 0 for dfl_pwq */
  4471. static struct pool_workqueue *install_unbound_pwq(struct workqueue_struct *wq,
  4472. int cpu, struct pool_workqueue *pwq)
  4473. {
  4474. struct pool_workqueue __rcu **slot = unbound_pwq_slot(wq, cpu);
  4475. struct pool_workqueue *old_pwq;
  4476. lockdep_assert_held(&wq_pool_mutex);
  4477. lockdep_assert_held(&wq->mutex);
  4478. /* link_pwq() can handle duplicate calls */
  4479. link_pwq(pwq);
  4480. old_pwq = rcu_access_pointer(*slot);
  4481. rcu_assign_pointer(*slot, pwq);
  4482. return old_pwq;
  4483. }
  4484. /* context to store the prepared attrs & pwqs before applying */
  4485. struct apply_wqattrs_ctx {
  4486. struct workqueue_struct *wq; /* target workqueue */
  4487. struct workqueue_attrs *attrs; /* attrs to apply */
  4488. struct list_head list; /* queued for batching commit */
  4489. struct pool_workqueue *dfl_pwq;
  4490. struct pool_workqueue *pwq_tbl[];
  4491. };
  4492. /* free the resources after success or abort */
  4493. static void apply_wqattrs_cleanup(struct apply_wqattrs_ctx *ctx)
  4494. {
  4495. if (ctx) {
  4496. int cpu;
  4497. for_each_possible_cpu(cpu)
  4498. put_pwq_unlocked(ctx->pwq_tbl[cpu]);
  4499. put_pwq_unlocked(ctx->dfl_pwq);
  4500. free_workqueue_attrs(ctx->attrs);
  4501. kfree(ctx);
  4502. }
  4503. }
  4504. /* allocate the attrs and pwqs for later installation */
  4505. static struct apply_wqattrs_ctx *
  4506. apply_wqattrs_prepare(struct workqueue_struct *wq,
  4507. const struct workqueue_attrs *attrs,
  4508. const cpumask_var_t unbound_cpumask)
  4509. {
  4510. struct apply_wqattrs_ctx *ctx;
  4511. struct workqueue_attrs *new_attrs;
  4512. int cpu;
  4513. lockdep_assert_held(&wq_pool_mutex);
  4514. if (WARN_ON(attrs->affn_scope < 0 ||
  4515. attrs->affn_scope >= WQ_AFFN_NR_TYPES))
  4516. return ERR_PTR(-EINVAL);
  4517. ctx = kzalloc(struct_size(ctx, pwq_tbl, nr_cpu_ids), GFP_KERNEL);
  4518. new_attrs = alloc_workqueue_attrs();
  4519. if (!ctx || !new_attrs)
  4520. goto out_free;
  4521. /*
  4522. * If something goes wrong during CPU up/down, we'll fall back to
  4523. * the default pwq covering whole @attrs->cpumask. Always create
  4524. * it even if we don't use it immediately.
  4525. */
  4526. copy_workqueue_attrs(new_attrs, attrs);
  4527. wqattrs_actualize_cpumask(new_attrs, unbound_cpumask);
  4528. cpumask_copy(new_attrs->__pod_cpumask, new_attrs->cpumask);
  4529. ctx->dfl_pwq = alloc_unbound_pwq(wq, new_attrs);
  4530. if (!ctx->dfl_pwq)
  4531. goto out_free;
  4532. for_each_possible_cpu(cpu) {
  4533. if (new_attrs->ordered) {
  4534. ctx->dfl_pwq->refcnt++;
  4535. ctx->pwq_tbl[cpu] = ctx->dfl_pwq;
  4536. } else {
  4537. wq_calc_pod_cpumask(new_attrs, cpu);
  4538. ctx->pwq_tbl[cpu] = alloc_unbound_pwq(wq, new_attrs);
  4539. if (!ctx->pwq_tbl[cpu])
  4540. goto out_free;
  4541. }
  4542. }
  4543. /* save the user configured attrs and sanitize it. */
  4544. copy_workqueue_attrs(new_attrs, attrs);
  4545. cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask);
  4546. cpumask_copy(new_attrs->__pod_cpumask, new_attrs->cpumask);
  4547. ctx->attrs = new_attrs;
  4548. /*
  4549. * For initialized ordered workqueues, there should only be one pwq
  4550. * (dfl_pwq). Set the plugged flag of ctx->dfl_pwq to suspend execution
  4551. * of newly queued work items until execution of older work items in
  4552. * the old pwq's have completed.
  4553. */
  4554. if ((wq->flags & __WQ_ORDERED) && !list_empty(&wq->pwqs))
  4555. ctx->dfl_pwq->plugged = true;
  4556. ctx->wq = wq;
  4557. return ctx;
  4558. out_free:
  4559. free_workqueue_attrs(new_attrs);
  4560. apply_wqattrs_cleanup(ctx);
  4561. return ERR_PTR(-ENOMEM);
  4562. }
  4563. /* set attrs and install prepared pwqs, @ctx points to old pwqs on return */
  4564. static void apply_wqattrs_commit(struct apply_wqattrs_ctx *ctx)
  4565. {
  4566. int cpu;
  4567. /* all pwqs have been created successfully, let's install'em */
  4568. mutex_lock(&ctx->wq->mutex);
  4569. copy_workqueue_attrs(ctx->wq->unbound_attrs, ctx->attrs);
  4570. /* save the previous pwqs and install the new ones */
  4571. for_each_possible_cpu(cpu)
  4572. ctx->pwq_tbl[cpu] = install_unbound_pwq(ctx->wq, cpu,
  4573. ctx->pwq_tbl[cpu]);
  4574. ctx->dfl_pwq = install_unbound_pwq(ctx->wq, -1, ctx->dfl_pwq);
  4575. /* update node_nr_active->max */
  4576. wq_update_node_max_active(ctx->wq, -1);
  4577. /* rescuer needs to respect wq cpumask changes */
  4578. if (ctx->wq->rescuer)
  4579. set_cpus_allowed_ptr(ctx->wq->rescuer->task,
  4580. unbound_effective_cpumask(ctx->wq));
  4581. mutex_unlock(&ctx->wq->mutex);
  4582. }
  4583. static int apply_workqueue_attrs_locked(struct workqueue_struct *wq,
  4584. const struct workqueue_attrs *attrs)
  4585. {
  4586. struct apply_wqattrs_ctx *ctx;
  4587. /* only unbound workqueues can change attributes */
  4588. if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
  4589. return -EINVAL;
  4590. ctx = apply_wqattrs_prepare(wq, attrs, wq_unbound_cpumask);
  4591. if (IS_ERR(ctx))
  4592. return PTR_ERR(ctx);
  4593. /* the ctx has been prepared successfully, let's commit it */
  4594. apply_wqattrs_commit(ctx);
  4595. apply_wqattrs_cleanup(ctx);
  4596. return 0;
  4597. }
  4598. /**
  4599. * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
  4600. * @wq: the target workqueue
  4601. * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
  4602. *
  4603. * Apply @attrs to an unbound workqueue @wq. Unless disabled, this function maps
  4604. * a separate pwq to each CPU pod with possibles CPUs in @attrs->cpumask so that
  4605. * work items are affine to the pod it was issued on. Older pwqs are released as
  4606. * in-flight work items finish. Note that a work item which repeatedly requeues
  4607. * itself back-to-back will stay on its current pwq.
  4608. *
  4609. * Performs GFP_KERNEL allocations.
  4610. *
  4611. * Return: 0 on success and -errno on failure.
  4612. */
  4613. int apply_workqueue_attrs(struct workqueue_struct *wq,
  4614. const struct workqueue_attrs *attrs)
  4615. {
  4616. int ret;
  4617. mutex_lock(&wq_pool_mutex);
  4618. ret = apply_workqueue_attrs_locked(wq, attrs);
  4619. mutex_unlock(&wq_pool_mutex);
  4620. return ret;
  4621. }
  4622. /**
  4623. * unbound_wq_update_pwq - update a pwq slot for CPU hot[un]plug
  4624. * @wq: the target workqueue
  4625. * @cpu: the CPU to update the pwq slot for
  4626. *
  4627. * This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and
  4628. * %CPU_DOWN_FAILED. @cpu is in the same pod of the CPU being hot[un]plugged.
  4629. *
  4630. *
  4631. * If pod affinity can't be adjusted due to memory allocation failure, it falls
  4632. * back to @wq->dfl_pwq which may not be optimal but is always correct.
  4633. *
  4634. * Note that when the last allowed CPU of a pod goes offline for a workqueue
  4635. * with a cpumask spanning multiple pods, the workers which were already
  4636. * executing the work items for the workqueue will lose their CPU affinity and
  4637. * may execute on any CPU. This is similar to how per-cpu workqueues behave on
  4638. * CPU_DOWN. If a workqueue user wants strict affinity, it's the user's
  4639. * responsibility to flush the work item from CPU_DOWN_PREPARE.
  4640. */
  4641. static void unbound_wq_update_pwq(struct workqueue_struct *wq, int cpu)
  4642. {
  4643. struct pool_workqueue *old_pwq = NULL, *pwq;
  4644. struct workqueue_attrs *target_attrs;
  4645. lockdep_assert_held(&wq_pool_mutex);
  4646. if (!(wq->flags & WQ_UNBOUND) || wq->unbound_attrs->ordered)
  4647. return;
  4648. /*
  4649. * We don't wanna alloc/free wq_attrs for each wq for each CPU.
  4650. * Let's use a preallocated one. The following buf is protected by
  4651. * CPU hotplug exclusion.
  4652. */
  4653. target_attrs = unbound_wq_update_pwq_attrs_buf;
  4654. copy_workqueue_attrs(target_attrs, wq->unbound_attrs);
  4655. wqattrs_actualize_cpumask(target_attrs, wq_unbound_cpumask);
  4656. /* nothing to do if the target cpumask matches the current pwq */
  4657. wq_calc_pod_cpumask(target_attrs, cpu);
  4658. if (wqattrs_equal(target_attrs, unbound_pwq(wq, cpu)->pool->attrs))
  4659. return;
  4660. /* create a new pwq */
  4661. pwq = alloc_unbound_pwq(wq, target_attrs);
  4662. if (!pwq) {
  4663. pr_warn("workqueue: allocation failed while updating CPU pod affinity of \"%s\"\n",
  4664. wq->name);
  4665. goto use_dfl_pwq;
  4666. }
  4667. /* Install the new pwq. */
  4668. mutex_lock(&wq->mutex);
  4669. old_pwq = install_unbound_pwq(wq, cpu, pwq);
  4670. goto out_unlock;
  4671. use_dfl_pwq:
  4672. mutex_lock(&wq->mutex);
  4673. pwq = unbound_pwq(wq, -1);
  4674. raw_spin_lock_irq(&pwq->pool->lock);
  4675. get_pwq(pwq);
  4676. raw_spin_unlock_irq(&pwq->pool->lock);
  4677. old_pwq = install_unbound_pwq(wq, cpu, pwq);
  4678. out_unlock:
  4679. mutex_unlock(&wq->mutex);
  4680. put_pwq_unlocked(old_pwq);
  4681. }
  4682. static int alloc_and_link_pwqs(struct workqueue_struct *wq)
  4683. {
  4684. bool highpri = wq->flags & WQ_HIGHPRI;
  4685. int cpu, ret;
  4686. lockdep_assert_held(&wq_pool_mutex);
  4687. wq->cpu_pwq = alloc_percpu(struct pool_workqueue *);
  4688. if (!wq->cpu_pwq)
  4689. goto enomem;
  4690. if (!(wq->flags & WQ_UNBOUND)) {
  4691. struct worker_pool __percpu *pools;
  4692. if (wq->flags & WQ_BH)
  4693. pools = bh_worker_pools;
  4694. else
  4695. pools = cpu_worker_pools;
  4696. for_each_possible_cpu(cpu) {
  4697. struct pool_workqueue **pwq_p;
  4698. struct worker_pool *pool;
  4699. pool = &(per_cpu_ptr(pools, cpu)[highpri]);
  4700. pwq_p = per_cpu_ptr(wq->cpu_pwq, cpu);
  4701. *pwq_p = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL,
  4702. pool->node);
  4703. if (!*pwq_p)
  4704. goto enomem;
  4705. init_pwq(*pwq_p, wq, pool);
  4706. mutex_lock(&wq->mutex);
  4707. link_pwq(*pwq_p);
  4708. mutex_unlock(&wq->mutex);
  4709. }
  4710. return 0;
  4711. }
  4712. if (wq->flags & __WQ_ORDERED) {
  4713. struct pool_workqueue *dfl_pwq;
  4714. ret = apply_workqueue_attrs_locked(wq, ordered_wq_attrs[highpri]);
  4715. /* there should only be single pwq for ordering guarantee */
  4716. dfl_pwq = rcu_access_pointer(wq->dfl_pwq);
  4717. WARN(!ret && (wq->pwqs.next != &dfl_pwq->pwqs_node ||
  4718. wq->pwqs.prev != &dfl_pwq->pwqs_node),
  4719. "ordering guarantee broken for workqueue %s\n", wq->name);
  4720. } else {
  4721. ret = apply_workqueue_attrs_locked(wq, unbound_std_wq_attrs[highpri]);
  4722. }
  4723. return ret;
  4724. enomem:
  4725. if (wq->cpu_pwq) {
  4726. for_each_possible_cpu(cpu) {
  4727. struct pool_workqueue *pwq = *per_cpu_ptr(wq->cpu_pwq, cpu);
  4728. if (pwq)
  4729. kmem_cache_free(pwq_cache, pwq);
  4730. }
  4731. free_percpu(wq->cpu_pwq);
  4732. wq->cpu_pwq = NULL;
  4733. }
  4734. return -ENOMEM;
  4735. }
  4736. static int wq_clamp_max_active(int max_active, unsigned int flags,
  4737. const char *name)
  4738. {
  4739. if (max_active < 1 || max_active > WQ_MAX_ACTIVE)
  4740. pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
  4741. max_active, name, 1, WQ_MAX_ACTIVE);
  4742. return clamp_val(max_active, 1, WQ_MAX_ACTIVE);
  4743. }
  4744. /*
  4745. * Workqueues which may be used during memory reclaim should have a rescuer
  4746. * to guarantee forward progress.
  4747. */
  4748. static int init_rescuer(struct workqueue_struct *wq)
  4749. {
  4750. struct worker *rescuer;
  4751. char id_buf[WORKER_ID_LEN];
  4752. int ret;
  4753. lockdep_assert_held(&wq_pool_mutex);
  4754. if (!(wq->flags & WQ_MEM_RECLAIM))
  4755. return 0;
  4756. rescuer = alloc_worker(NUMA_NO_NODE);
  4757. if (!rescuer) {
  4758. pr_err("workqueue: Failed to allocate a rescuer for wq \"%s\"\n",
  4759. wq->name);
  4760. return -ENOMEM;
  4761. }
  4762. rescuer->rescue_wq = wq;
  4763. format_worker_id(id_buf, sizeof(id_buf), rescuer, NULL);
  4764. rescuer->task = kthread_create(rescuer_thread, rescuer, "%s", id_buf);
  4765. if (IS_ERR(rescuer->task)) {
  4766. ret = PTR_ERR(rescuer->task);
  4767. pr_err("workqueue: Failed to create a rescuer kthread for wq \"%s\": %pe",
  4768. wq->name, ERR_PTR(ret));
  4769. kfree(rescuer);
  4770. return ret;
  4771. }
  4772. wq->rescuer = rescuer;
  4773. if (wq->flags & WQ_UNBOUND)
  4774. kthread_bind_mask(rescuer->task, unbound_effective_cpumask(wq));
  4775. else
  4776. kthread_bind_mask(rescuer->task, cpu_possible_mask);
  4777. wake_up_process(rescuer->task);
  4778. return 0;
  4779. }
  4780. /**
  4781. * wq_adjust_max_active - update a wq's max_active to the current setting
  4782. * @wq: target workqueue
  4783. *
  4784. * If @wq isn't freezing, set @wq->max_active to the saved_max_active and
  4785. * activate inactive work items accordingly. If @wq is freezing, clear
  4786. * @wq->max_active to zero.
  4787. */
  4788. static void wq_adjust_max_active(struct workqueue_struct *wq)
  4789. {
  4790. bool activated;
  4791. int new_max, new_min;
  4792. lockdep_assert_held(&wq->mutex);
  4793. if ((wq->flags & WQ_FREEZABLE) && workqueue_freezing) {
  4794. new_max = 0;
  4795. new_min = 0;
  4796. } else {
  4797. new_max = wq->saved_max_active;
  4798. new_min = wq->saved_min_active;
  4799. }
  4800. if (wq->max_active == new_max && wq->min_active == new_min)
  4801. return;
  4802. /*
  4803. * Update @wq->max/min_active and then kick inactive work items if more
  4804. * active work items are allowed. This doesn't break work item ordering
  4805. * because new work items are always queued behind existing inactive
  4806. * work items if there are any.
  4807. */
  4808. WRITE_ONCE(wq->max_active, new_max);
  4809. WRITE_ONCE(wq->min_active, new_min);
  4810. if (wq->flags & WQ_UNBOUND)
  4811. wq_update_node_max_active(wq, -1);
  4812. if (new_max == 0)
  4813. return;
  4814. /*
  4815. * Round-robin through pwq's activating the first inactive work item
  4816. * until max_active is filled.
  4817. */
  4818. do {
  4819. struct pool_workqueue *pwq;
  4820. activated = false;
  4821. for_each_pwq(pwq, wq) {
  4822. unsigned long irq_flags;
  4823. /* can be called during early boot w/ irq disabled */
  4824. raw_spin_lock_irqsave(&pwq->pool->lock, irq_flags);
  4825. if (pwq_activate_first_inactive(pwq, true)) {
  4826. activated = true;
  4827. kick_pool(pwq->pool);
  4828. }
  4829. raw_spin_unlock_irqrestore(&pwq->pool->lock, irq_flags);
  4830. }
  4831. } while (activated);
  4832. }
  4833. __printf(1, 0)
  4834. static struct workqueue_struct *__alloc_workqueue(const char *fmt,
  4835. unsigned int flags,
  4836. int max_active, va_list args)
  4837. {
  4838. struct workqueue_struct *wq;
  4839. size_t wq_size;
  4840. int name_len;
  4841. if (flags & WQ_BH) {
  4842. if (WARN_ON_ONCE(flags & ~__WQ_BH_ALLOWS))
  4843. return NULL;
  4844. if (WARN_ON_ONCE(max_active))
  4845. return NULL;
  4846. }
  4847. /* see the comment above the definition of WQ_POWER_EFFICIENT */
  4848. if ((flags & WQ_POWER_EFFICIENT) && wq_power_efficient)
  4849. flags |= WQ_UNBOUND;
  4850. /* allocate wq and format name */
  4851. if (flags & WQ_UNBOUND)
  4852. wq_size = struct_size(wq, node_nr_active, nr_node_ids + 1);
  4853. else
  4854. wq_size = sizeof(*wq);
  4855. wq = kzalloc(wq_size, GFP_KERNEL);
  4856. if (!wq)
  4857. return NULL;
  4858. if (flags & WQ_UNBOUND) {
  4859. wq->unbound_attrs = alloc_workqueue_attrs();
  4860. if (!wq->unbound_attrs)
  4861. goto err_free_wq;
  4862. }
  4863. name_len = vsnprintf(wq->name, sizeof(wq->name), fmt, args);
  4864. if (name_len >= WQ_NAME_LEN)
  4865. pr_warn_once("workqueue: name exceeds WQ_NAME_LEN. Truncating to: %s\n",
  4866. wq->name);
  4867. if (flags & WQ_BH) {
  4868. /*
  4869. * BH workqueues always share a single execution context per CPU
  4870. * and don't impose any max_active limit.
  4871. */
  4872. max_active = INT_MAX;
  4873. } else {
  4874. max_active = max_active ?: WQ_DFL_ACTIVE;
  4875. max_active = wq_clamp_max_active(max_active, flags, wq->name);
  4876. }
  4877. /* init wq */
  4878. wq->flags = flags;
  4879. wq->max_active = max_active;
  4880. wq->min_active = min(max_active, WQ_DFL_MIN_ACTIVE);
  4881. wq->saved_max_active = wq->max_active;
  4882. wq->saved_min_active = wq->min_active;
  4883. mutex_init(&wq->mutex);
  4884. atomic_set(&wq->nr_pwqs_to_flush, 0);
  4885. INIT_LIST_HEAD(&wq->pwqs);
  4886. INIT_LIST_HEAD(&wq->flusher_queue);
  4887. INIT_LIST_HEAD(&wq->flusher_overflow);
  4888. INIT_LIST_HEAD(&wq->maydays);
  4889. INIT_LIST_HEAD(&wq->list);
  4890. if (flags & WQ_UNBOUND) {
  4891. if (alloc_node_nr_active(wq->node_nr_active) < 0)
  4892. goto err_free_wq;
  4893. }
  4894. /*
  4895. * wq_pool_mutex protects the workqueues list, allocations of PWQs,
  4896. * and the global freeze state.
  4897. */
  4898. apply_wqattrs_lock();
  4899. if (alloc_and_link_pwqs(wq) < 0)
  4900. goto err_unlock_free_node_nr_active;
  4901. mutex_lock(&wq->mutex);
  4902. wq_adjust_max_active(wq);
  4903. mutex_unlock(&wq->mutex);
  4904. list_add_tail_rcu(&wq->list, &workqueues);
  4905. if (wq_online && init_rescuer(wq) < 0)
  4906. goto err_unlock_destroy;
  4907. apply_wqattrs_unlock();
  4908. if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
  4909. goto err_destroy;
  4910. return wq;
  4911. err_unlock_free_node_nr_active:
  4912. apply_wqattrs_unlock();
  4913. /*
  4914. * Failed alloc_and_link_pwqs() may leave pending pwq->release_work,
  4915. * flushing the pwq_release_worker ensures that the pwq_release_workfn()
  4916. * completes before calling kfree(wq).
  4917. */
  4918. if (wq->flags & WQ_UNBOUND) {
  4919. kthread_flush_worker(pwq_release_worker);
  4920. free_node_nr_active(wq->node_nr_active);
  4921. }
  4922. err_free_wq:
  4923. free_workqueue_attrs(wq->unbound_attrs);
  4924. kfree(wq);
  4925. return NULL;
  4926. err_unlock_destroy:
  4927. apply_wqattrs_unlock();
  4928. err_destroy:
  4929. destroy_workqueue(wq);
  4930. return NULL;
  4931. }
  4932. __printf(1, 4)
  4933. struct workqueue_struct *alloc_workqueue(const char *fmt,
  4934. unsigned int flags,
  4935. int max_active, ...)
  4936. {
  4937. struct workqueue_struct *wq;
  4938. va_list args;
  4939. va_start(args, max_active);
  4940. wq = __alloc_workqueue(fmt, flags, max_active, args);
  4941. va_end(args);
  4942. if (!wq)
  4943. return NULL;
  4944. wq_init_lockdep(wq);
  4945. return wq;
  4946. }
  4947. EXPORT_SYMBOL_GPL(alloc_workqueue);
  4948. #ifdef CONFIG_LOCKDEP
  4949. __printf(1, 5)
  4950. struct workqueue_struct *
  4951. alloc_workqueue_lockdep_map(const char *fmt, unsigned int flags,
  4952. int max_active, struct lockdep_map *lockdep_map, ...)
  4953. {
  4954. struct workqueue_struct *wq;
  4955. va_list args;
  4956. va_start(args, lockdep_map);
  4957. wq = __alloc_workqueue(fmt, flags, max_active, args);
  4958. va_end(args);
  4959. if (!wq)
  4960. return NULL;
  4961. wq->lockdep_map = lockdep_map;
  4962. return wq;
  4963. }
  4964. EXPORT_SYMBOL_GPL(alloc_workqueue_lockdep_map);
  4965. #endif
  4966. static bool pwq_busy(struct pool_workqueue *pwq)
  4967. {
  4968. int i;
  4969. for (i = 0; i < WORK_NR_COLORS; i++)
  4970. if (pwq->nr_in_flight[i])
  4971. return true;
  4972. if ((pwq != rcu_access_pointer(pwq->wq->dfl_pwq)) && (pwq->refcnt > 1))
  4973. return true;
  4974. if (!pwq_is_empty(pwq))
  4975. return true;
  4976. return false;
  4977. }
  4978. /**
  4979. * destroy_workqueue - safely terminate a workqueue
  4980. * @wq: target workqueue
  4981. *
  4982. * Safely destroy a workqueue. All work currently pending will be done first.
  4983. */
  4984. void destroy_workqueue(struct workqueue_struct *wq)
  4985. {
  4986. struct pool_workqueue *pwq;
  4987. int cpu;
  4988. /*
  4989. * Remove it from sysfs first so that sanity check failure doesn't
  4990. * lead to sysfs name conflicts.
  4991. */
  4992. workqueue_sysfs_unregister(wq);
  4993. /* mark the workqueue destruction is in progress */
  4994. mutex_lock(&wq->mutex);
  4995. wq->flags |= __WQ_DESTROYING;
  4996. mutex_unlock(&wq->mutex);
  4997. /* drain it before proceeding with destruction */
  4998. drain_workqueue(wq);
  4999. /* kill rescuer, if sanity checks fail, leave it w/o rescuer */
  5000. if (wq->rescuer) {
  5001. struct worker *rescuer = wq->rescuer;
  5002. /* this prevents new queueing */
  5003. raw_spin_lock_irq(&wq_mayday_lock);
  5004. wq->rescuer = NULL;
  5005. raw_spin_unlock_irq(&wq_mayday_lock);
  5006. /* rescuer will empty maydays list before exiting */
  5007. kthread_stop(rescuer->task);
  5008. kfree(rescuer);
  5009. }
  5010. /*
  5011. * Sanity checks - grab all the locks so that we wait for all
  5012. * in-flight operations which may do put_pwq().
  5013. */
  5014. mutex_lock(&wq_pool_mutex);
  5015. mutex_lock(&wq->mutex);
  5016. for_each_pwq(pwq, wq) {
  5017. raw_spin_lock_irq(&pwq->pool->lock);
  5018. if (WARN_ON(pwq_busy(pwq))) {
  5019. pr_warn("%s: %s has the following busy pwq\n",
  5020. __func__, wq->name);
  5021. show_pwq(pwq);
  5022. raw_spin_unlock_irq(&pwq->pool->lock);
  5023. mutex_unlock(&wq->mutex);
  5024. mutex_unlock(&wq_pool_mutex);
  5025. show_one_workqueue(wq);
  5026. return;
  5027. }
  5028. raw_spin_unlock_irq(&pwq->pool->lock);
  5029. }
  5030. mutex_unlock(&wq->mutex);
  5031. /*
  5032. * wq list is used to freeze wq, remove from list after
  5033. * flushing is complete in case freeze races us.
  5034. */
  5035. list_del_rcu(&wq->list);
  5036. mutex_unlock(&wq_pool_mutex);
  5037. /*
  5038. * We're the sole accessor of @wq. Directly access cpu_pwq and dfl_pwq
  5039. * to put the base refs. @wq will be auto-destroyed from the last
  5040. * pwq_put. RCU read lock prevents @wq from going away from under us.
  5041. */
  5042. rcu_read_lock();
  5043. for_each_possible_cpu(cpu) {
  5044. put_pwq_unlocked(unbound_pwq(wq, cpu));
  5045. RCU_INIT_POINTER(*unbound_pwq_slot(wq, cpu), NULL);
  5046. }
  5047. put_pwq_unlocked(unbound_pwq(wq, -1));
  5048. RCU_INIT_POINTER(*unbound_pwq_slot(wq, -1), NULL);
  5049. rcu_read_unlock();
  5050. }
  5051. EXPORT_SYMBOL_GPL(destroy_workqueue);
  5052. /**
  5053. * workqueue_set_max_active - adjust max_active of a workqueue
  5054. * @wq: target workqueue
  5055. * @max_active: new max_active value.
  5056. *
  5057. * Set max_active of @wq to @max_active. See the alloc_workqueue() function
  5058. * comment.
  5059. *
  5060. * CONTEXT:
  5061. * Don't call from IRQ context.
  5062. */
  5063. void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
  5064. {
  5065. /* max_active doesn't mean anything for BH workqueues */
  5066. if (WARN_ON(wq->flags & WQ_BH))
  5067. return;
  5068. /* disallow meddling with max_active for ordered workqueues */
  5069. if (WARN_ON(wq->flags & __WQ_ORDERED))
  5070. return;
  5071. max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
  5072. mutex_lock(&wq->mutex);
  5073. wq->saved_max_active = max_active;
  5074. if (wq->flags & WQ_UNBOUND)
  5075. wq->saved_min_active = min(wq->saved_min_active, max_active);
  5076. wq_adjust_max_active(wq);
  5077. mutex_unlock(&wq->mutex);
  5078. }
  5079. EXPORT_SYMBOL_GPL(workqueue_set_max_active);
  5080. /**
  5081. * workqueue_set_min_active - adjust min_active of an unbound workqueue
  5082. * @wq: target unbound workqueue
  5083. * @min_active: new min_active value
  5084. *
  5085. * Set min_active of an unbound workqueue. Unlike other types of workqueues, an
  5086. * unbound workqueue is not guaranteed to be able to process max_active
  5087. * interdependent work items. Instead, an unbound workqueue is guaranteed to be
  5088. * able to process min_active number of interdependent work items which is
  5089. * %WQ_DFL_MIN_ACTIVE by default.
  5090. *
  5091. * Use this function to adjust the min_active value between 0 and the current
  5092. * max_active.
  5093. */
  5094. void workqueue_set_min_active(struct workqueue_struct *wq, int min_active)
  5095. {
  5096. /* min_active is only meaningful for non-ordered unbound workqueues */
  5097. if (WARN_ON((wq->flags & (WQ_BH | WQ_UNBOUND | __WQ_ORDERED)) !=
  5098. WQ_UNBOUND))
  5099. return;
  5100. mutex_lock(&wq->mutex);
  5101. wq->saved_min_active = clamp(min_active, 0, wq->saved_max_active);
  5102. wq_adjust_max_active(wq);
  5103. mutex_unlock(&wq->mutex);
  5104. }
  5105. /**
  5106. * current_work - retrieve %current task's work struct
  5107. *
  5108. * Determine if %current task is a workqueue worker and what it's working on.
  5109. * Useful to find out the context that the %current task is running in.
  5110. *
  5111. * Return: work struct if %current task is a workqueue worker, %NULL otherwise.
  5112. */
  5113. struct work_struct *current_work(void)
  5114. {
  5115. struct worker *worker = current_wq_worker();
  5116. return worker ? worker->current_work : NULL;
  5117. }
  5118. EXPORT_SYMBOL(current_work);
  5119. /**
  5120. * current_is_workqueue_rescuer - is %current workqueue rescuer?
  5121. *
  5122. * Determine whether %current is a workqueue rescuer. Can be used from
  5123. * work functions to determine whether it's being run off the rescuer task.
  5124. *
  5125. * Return: %true if %current is a workqueue rescuer. %false otherwise.
  5126. */
  5127. bool current_is_workqueue_rescuer(void)
  5128. {
  5129. struct worker *worker = current_wq_worker();
  5130. return worker && worker->rescue_wq;
  5131. }
  5132. /**
  5133. * workqueue_congested - test whether a workqueue is congested
  5134. * @cpu: CPU in question
  5135. * @wq: target workqueue
  5136. *
  5137. * Test whether @wq's cpu workqueue for @cpu is congested. There is
  5138. * no synchronization around this function and the test result is
  5139. * unreliable and only useful as advisory hints or for debugging.
  5140. *
  5141. * If @cpu is WORK_CPU_UNBOUND, the test is performed on the local CPU.
  5142. *
  5143. * With the exception of ordered workqueues, all workqueues have per-cpu
  5144. * pool_workqueues, each with its own congested state. A workqueue being
  5145. * congested on one CPU doesn't mean that the workqueue is contested on any
  5146. * other CPUs.
  5147. *
  5148. * Return:
  5149. * %true if congested, %false otherwise.
  5150. */
  5151. bool workqueue_congested(int cpu, struct workqueue_struct *wq)
  5152. {
  5153. struct pool_workqueue *pwq;
  5154. bool ret;
  5155. rcu_read_lock();
  5156. preempt_disable();
  5157. if (cpu == WORK_CPU_UNBOUND)
  5158. cpu = smp_processor_id();
  5159. pwq = *per_cpu_ptr(wq->cpu_pwq, cpu);
  5160. ret = !list_empty(&pwq->inactive_works);
  5161. preempt_enable();
  5162. rcu_read_unlock();
  5163. return ret;
  5164. }
  5165. EXPORT_SYMBOL_GPL(workqueue_congested);
  5166. /**
  5167. * work_busy - test whether a work is currently pending or running
  5168. * @work: the work to be tested
  5169. *
  5170. * Test whether @work is currently pending or running. There is no
  5171. * synchronization around this function and the test result is
  5172. * unreliable and only useful as advisory hints or for debugging.
  5173. *
  5174. * Return:
  5175. * OR'd bitmask of WORK_BUSY_* bits.
  5176. */
  5177. unsigned int work_busy(struct work_struct *work)
  5178. {
  5179. struct worker_pool *pool;
  5180. unsigned long irq_flags;
  5181. unsigned int ret = 0;
  5182. if (work_pending(work))
  5183. ret |= WORK_BUSY_PENDING;
  5184. rcu_read_lock();
  5185. pool = get_work_pool(work);
  5186. if (pool) {
  5187. raw_spin_lock_irqsave(&pool->lock, irq_flags);
  5188. if (find_worker_executing_work(pool, work))
  5189. ret |= WORK_BUSY_RUNNING;
  5190. raw_spin_unlock_irqrestore(&pool->lock, irq_flags);
  5191. }
  5192. rcu_read_unlock();
  5193. return ret;
  5194. }
  5195. EXPORT_SYMBOL_GPL(work_busy);
  5196. /**
  5197. * set_worker_desc - set description for the current work item
  5198. * @fmt: printf-style format string
  5199. * @...: arguments for the format string
  5200. *
  5201. * This function can be called by a running work function to describe what
  5202. * the work item is about. If the worker task gets dumped, this
  5203. * information will be printed out together to help debugging. The
  5204. * description can be at most WORKER_DESC_LEN including the trailing '\0'.
  5205. */
  5206. void set_worker_desc(const char *fmt, ...)
  5207. {
  5208. struct worker *worker = current_wq_worker();
  5209. va_list args;
  5210. if (worker) {
  5211. va_start(args, fmt);
  5212. vsnprintf(worker->desc, sizeof(worker->desc), fmt, args);
  5213. va_end(args);
  5214. }
  5215. }
  5216. EXPORT_SYMBOL_GPL(set_worker_desc);
  5217. /**
  5218. * print_worker_info - print out worker information and description
  5219. * @log_lvl: the log level to use when printing
  5220. * @task: target task
  5221. *
  5222. * If @task is a worker and currently executing a work item, print out the
  5223. * name of the workqueue being serviced and worker description set with
  5224. * set_worker_desc() by the currently executing work item.
  5225. *
  5226. * This function can be safely called on any task as long as the
  5227. * task_struct itself is accessible. While safe, this function isn't
  5228. * synchronized and may print out mixups or garbages of limited length.
  5229. */
  5230. void print_worker_info(const char *log_lvl, struct task_struct *task)
  5231. {
  5232. work_func_t *fn = NULL;
  5233. char name[WQ_NAME_LEN] = { };
  5234. char desc[WORKER_DESC_LEN] = { };
  5235. struct pool_workqueue *pwq = NULL;
  5236. struct workqueue_struct *wq = NULL;
  5237. struct worker *worker;
  5238. if (!(task->flags & PF_WQ_WORKER))
  5239. return;
  5240. /*
  5241. * This function is called without any synchronization and @task
  5242. * could be in any state. Be careful with dereferences.
  5243. */
  5244. worker = kthread_probe_data(task);
  5245. /*
  5246. * Carefully copy the associated workqueue's workfn, name and desc.
  5247. * Keep the original last '\0' in case the original is garbage.
  5248. */
  5249. copy_from_kernel_nofault(&fn, &worker->current_func, sizeof(fn));
  5250. copy_from_kernel_nofault(&pwq, &worker->current_pwq, sizeof(pwq));
  5251. copy_from_kernel_nofault(&wq, &pwq->wq, sizeof(wq));
  5252. copy_from_kernel_nofault(name, wq->name, sizeof(name) - 1);
  5253. copy_from_kernel_nofault(desc, worker->desc, sizeof(desc) - 1);
  5254. if (fn || name[0] || desc[0]) {
  5255. printk("%sWorkqueue: %s %ps", log_lvl, name, fn);
  5256. if (strcmp(name, desc))
  5257. pr_cont(" (%s)", desc);
  5258. pr_cont("\n");
  5259. }
  5260. }
  5261. static void pr_cont_pool_info(struct worker_pool *pool)
  5262. {
  5263. pr_cont(" cpus=%*pbl", nr_cpumask_bits, pool->attrs->cpumask);
  5264. if (pool->node != NUMA_NO_NODE)
  5265. pr_cont(" node=%d", pool->node);
  5266. pr_cont(" flags=0x%x", pool->flags);
  5267. if (pool->flags & POOL_BH)
  5268. pr_cont(" bh%s",
  5269. pool->attrs->nice == HIGHPRI_NICE_LEVEL ? "-hi" : "");
  5270. else
  5271. pr_cont(" nice=%d", pool->attrs->nice);
  5272. }
  5273. static void pr_cont_worker_id(struct worker *worker)
  5274. {
  5275. struct worker_pool *pool = worker->pool;
  5276. if (pool->flags & WQ_BH)
  5277. pr_cont("bh%s",
  5278. pool->attrs->nice == HIGHPRI_NICE_LEVEL ? "-hi" : "");
  5279. else
  5280. pr_cont("%d%s", task_pid_nr(worker->task),
  5281. worker->rescue_wq ? "(RESCUER)" : "");
  5282. }
  5283. struct pr_cont_work_struct {
  5284. bool comma;
  5285. work_func_t func;
  5286. long ctr;
  5287. };
  5288. static void pr_cont_work_flush(bool comma, work_func_t func, struct pr_cont_work_struct *pcwsp)
  5289. {
  5290. if (!pcwsp->ctr)
  5291. goto out_record;
  5292. if (func == pcwsp->func) {
  5293. pcwsp->ctr++;
  5294. return;
  5295. }
  5296. if (pcwsp->ctr == 1)
  5297. pr_cont("%s %ps", pcwsp->comma ? "," : "", pcwsp->func);
  5298. else
  5299. pr_cont("%s %ld*%ps", pcwsp->comma ? "," : "", pcwsp->ctr, pcwsp->func);
  5300. pcwsp->ctr = 0;
  5301. out_record:
  5302. if ((long)func == -1L)
  5303. return;
  5304. pcwsp->comma = comma;
  5305. pcwsp->func = func;
  5306. pcwsp->ctr = 1;
  5307. }
  5308. static void pr_cont_work(bool comma, struct work_struct *work, struct pr_cont_work_struct *pcwsp)
  5309. {
  5310. if (work->func == wq_barrier_func) {
  5311. struct wq_barrier *barr;
  5312. barr = container_of(work, struct wq_barrier, work);
  5313. pr_cont_work_flush(comma, (work_func_t)-1, pcwsp);
  5314. pr_cont("%s BAR(%d)", comma ? "," : "",
  5315. task_pid_nr(barr->task));
  5316. } else {
  5317. if (!comma)
  5318. pr_cont_work_flush(comma, (work_func_t)-1, pcwsp);
  5319. pr_cont_work_flush(comma, work->func, pcwsp);
  5320. }
  5321. }
  5322. static void show_pwq(struct pool_workqueue *pwq)
  5323. {
  5324. struct pr_cont_work_struct pcws = { .ctr = 0, };
  5325. struct worker_pool *pool = pwq->pool;
  5326. struct work_struct *work;
  5327. struct worker *worker;
  5328. bool has_in_flight = false, has_pending = false;
  5329. int bkt;
  5330. pr_info(" pwq %d:", pool->id);
  5331. pr_cont_pool_info(pool);
  5332. pr_cont(" active=%d refcnt=%d%s\n",
  5333. pwq->nr_active, pwq->refcnt,
  5334. !list_empty(&pwq->mayday_node) ? " MAYDAY" : "");
  5335. hash_for_each(pool->busy_hash, bkt, worker, hentry) {
  5336. if (worker->current_pwq == pwq) {
  5337. has_in_flight = true;
  5338. break;
  5339. }
  5340. }
  5341. if (has_in_flight) {
  5342. bool comma = false;
  5343. pr_info(" in-flight:");
  5344. hash_for_each(pool->busy_hash, bkt, worker, hentry) {
  5345. if (worker->current_pwq != pwq)
  5346. continue;
  5347. pr_cont(" %s", comma ? "," : "");
  5348. pr_cont_worker_id(worker);
  5349. pr_cont(":%ps", worker->current_func);
  5350. list_for_each_entry(work, &worker->scheduled, entry)
  5351. pr_cont_work(false, work, &pcws);
  5352. pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
  5353. comma = true;
  5354. }
  5355. pr_cont("\n");
  5356. }
  5357. list_for_each_entry(work, &pool->worklist, entry) {
  5358. if (get_work_pwq(work) == pwq) {
  5359. has_pending = true;
  5360. break;
  5361. }
  5362. }
  5363. if (has_pending) {
  5364. bool comma = false;
  5365. pr_info(" pending:");
  5366. list_for_each_entry(work, &pool->worklist, entry) {
  5367. if (get_work_pwq(work) != pwq)
  5368. continue;
  5369. pr_cont_work(comma, work, &pcws);
  5370. comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
  5371. }
  5372. pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
  5373. pr_cont("\n");
  5374. }
  5375. if (!list_empty(&pwq->inactive_works)) {
  5376. bool comma = false;
  5377. pr_info(" inactive:");
  5378. list_for_each_entry(work, &pwq->inactive_works, entry) {
  5379. pr_cont_work(comma, work, &pcws);
  5380. comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
  5381. }
  5382. pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
  5383. pr_cont("\n");
  5384. }
  5385. }
  5386. /**
  5387. * show_one_workqueue - dump state of specified workqueue
  5388. * @wq: workqueue whose state will be printed
  5389. */
  5390. void show_one_workqueue(struct workqueue_struct *wq)
  5391. {
  5392. struct pool_workqueue *pwq;
  5393. bool idle = true;
  5394. unsigned long irq_flags;
  5395. for_each_pwq(pwq, wq) {
  5396. if (!pwq_is_empty(pwq)) {
  5397. idle = false;
  5398. break;
  5399. }
  5400. }
  5401. if (idle) /* Nothing to print for idle workqueue */
  5402. return;
  5403. pr_info("workqueue %s: flags=0x%x\n", wq->name, wq->flags);
  5404. for_each_pwq(pwq, wq) {
  5405. raw_spin_lock_irqsave(&pwq->pool->lock, irq_flags);
  5406. if (!pwq_is_empty(pwq)) {
  5407. /*
  5408. * Defer printing to avoid deadlocks in console
  5409. * drivers that queue work while holding locks
  5410. * also taken in their write paths.
  5411. */
  5412. printk_deferred_enter();
  5413. show_pwq(pwq);
  5414. printk_deferred_exit();
  5415. }
  5416. raw_spin_unlock_irqrestore(&pwq->pool->lock, irq_flags);
  5417. /*
  5418. * We could be printing a lot from atomic context, e.g.
  5419. * sysrq-t -> show_all_workqueues(). Avoid triggering
  5420. * hard lockup.
  5421. */
  5422. touch_nmi_watchdog();
  5423. }
  5424. }
  5425. /**
  5426. * show_one_worker_pool - dump state of specified worker pool
  5427. * @pool: worker pool whose state will be printed
  5428. */
  5429. static void show_one_worker_pool(struct worker_pool *pool)
  5430. {
  5431. struct worker *worker;
  5432. bool first = true;
  5433. unsigned long irq_flags;
  5434. unsigned long hung = 0;
  5435. raw_spin_lock_irqsave(&pool->lock, irq_flags);
  5436. if (pool->nr_workers == pool->nr_idle)
  5437. goto next_pool;
  5438. /* How long the first pending work is waiting for a worker. */
  5439. if (!list_empty(&pool->worklist))
  5440. hung = jiffies_to_msecs(jiffies - pool->watchdog_ts) / 1000;
  5441. /*
  5442. * Defer printing to avoid deadlocks in console drivers that
  5443. * queue work while holding locks also taken in their write
  5444. * paths.
  5445. */
  5446. printk_deferred_enter();
  5447. pr_info("pool %d:", pool->id);
  5448. pr_cont_pool_info(pool);
  5449. pr_cont(" hung=%lus workers=%d", hung, pool->nr_workers);
  5450. if (pool->manager)
  5451. pr_cont(" manager: %d",
  5452. task_pid_nr(pool->manager->task));
  5453. list_for_each_entry(worker, &pool->idle_list, entry) {
  5454. pr_cont(" %s", first ? "idle: " : "");
  5455. pr_cont_worker_id(worker);
  5456. first = false;
  5457. }
  5458. pr_cont("\n");
  5459. printk_deferred_exit();
  5460. next_pool:
  5461. raw_spin_unlock_irqrestore(&pool->lock, irq_flags);
  5462. /*
  5463. * We could be printing a lot from atomic context, e.g.
  5464. * sysrq-t -> show_all_workqueues(). Avoid triggering
  5465. * hard lockup.
  5466. */
  5467. touch_nmi_watchdog();
  5468. }
  5469. /**
  5470. * show_all_workqueues - dump workqueue state
  5471. *
  5472. * Called from a sysrq handler and prints out all busy workqueues and pools.
  5473. */
  5474. void show_all_workqueues(void)
  5475. {
  5476. struct workqueue_struct *wq;
  5477. struct worker_pool *pool;
  5478. int pi;
  5479. rcu_read_lock();
  5480. pr_info("Showing busy workqueues and worker pools:\n");
  5481. list_for_each_entry_rcu(wq, &workqueues, list)
  5482. show_one_workqueue(wq);
  5483. for_each_pool(pool, pi)
  5484. show_one_worker_pool(pool);
  5485. rcu_read_unlock();
  5486. }
  5487. /**
  5488. * show_freezable_workqueues - dump freezable workqueue state
  5489. *
  5490. * Called from try_to_freeze_tasks() and prints out all freezable workqueues
  5491. * still busy.
  5492. */
  5493. void show_freezable_workqueues(void)
  5494. {
  5495. struct workqueue_struct *wq;
  5496. rcu_read_lock();
  5497. pr_info("Showing freezable workqueues that are still busy:\n");
  5498. list_for_each_entry_rcu(wq, &workqueues, list) {
  5499. if (!(wq->flags & WQ_FREEZABLE))
  5500. continue;
  5501. show_one_workqueue(wq);
  5502. }
  5503. rcu_read_unlock();
  5504. }
  5505. /* used to show worker information through /proc/PID/{comm,stat,status} */
  5506. void wq_worker_comm(char *buf, size_t size, struct task_struct *task)
  5507. {
  5508. /* stabilize PF_WQ_WORKER and worker pool association */
  5509. mutex_lock(&wq_pool_attach_mutex);
  5510. if (task->flags & PF_WQ_WORKER) {
  5511. struct worker *worker = kthread_data(task);
  5512. struct worker_pool *pool = worker->pool;
  5513. int off;
  5514. off = format_worker_id(buf, size, worker, pool);
  5515. if (pool) {
  5516. raw_spin_lock_irq(&pool->lock);
  5517. /*
  5518. * ->desc tracks information (wq name or
  5519. * set_worker_desc()) for the latest execution. If
  5520. * current, prepend '+', otherwise '-'.
  5521. */
  5522. if (worker->desc[0] != '\0') {
  5523. if (worker->current_work)
  5524. scnprintf(buf + off, size - off, "+%s",
  5525. worker->desc);
  5526. else
  5527. scnprintf(buf + off, size - off, "-%s",
  5528. worker->desc);
  5529. }
  5530. raw_spin_unlock_irq(&pool->lock);
  5531. }
  5532. } else {
  5533. strscpy(buf, task->comm, size);
  5534. }
  5535. mutex_unlock(&wq_pool_attach_mutex);
  5536. }
  5537. #ifdef CONFIG_SMP
  5538. /*
  5539. * CPU hotplug.
  5540. *
  5541. * There are two challenges in supporting CPU hotplug. Firstly, there
  5542. * are a lot of assumptions on strong associations among work, pwq and
  5543. * pool which make migrating pending and scheduled works very
  5544. * difficult to implement without impacting hot paths. Secondly,
  5545. * worker pools serve mix of short, long and very long running works making
  5546. * blocked draining impractical.
  5547. *
  5548. * This is solved by allowing the pools to be disassociated from the CPU
  5549. * running as an unbound one and allowing it to be reattached later if the
  5550. * cpu comes back online.
  5551. */
  5552. static void unbind_workers(int cpu)
  5553. {
  5554. struct worker_pool *pool;
  5555. struct worker *worker;
  5556. for_each_cpu_worker_pool(pool, cpu) {
  5557. mutex_lock(&wq_pool_attach_mutex);
  5558. raw_spin_lock_irq(&pool->lock);
  5559. /*
  5560. * We've blocked all attach/detach operations. Make all workers
  5561. * unbound and set DISASSOCIATED. Before this, all workers
  5562. * must be on the cpu. After this, they may become diasporas.
  5563. * And the preemption disabled section in their sched callbacks
  5564. * are guaranteed to see WORKER_UNBOUND since the code here
  5565. * is on the same cpu.
  5566. */
  5567. for_each_pool_worker(worker, pool)
  5568. worker->flags |= WORKER_UNBOUND;
  5569. pool->flags |= POOL_DISASSOCIATED;
  5570. /*
  5571. * The handling of nr_running in sched callbacks are disabled
  5572. * now. Zap nr_running. After this, nr_running stays zero and
  5573. * need_more_worker() and keep_working() are always true as
  5574. * long as the worklist is not empty. This pool now behaves as
  5575. * an unbound (in terms of concurrency management) pool which
  5576. * are served by workers tied to the pool.
  5577. */
  5578. pool->nr_running = 0;
  5579. /*
  5580. * With concurrency management just turned off, a busy
  5581. * worker blocking could lead to lengthy stalls. Kick off
  5582. * unbound chain execution of currently pending work items.
  5583. */
  5584. kick_pool(pool);
  5585. raw_spin_unlock_irq(&pool->lock);
  5586. for_each_pool_worker(worker, pool)
  5587. unbind_worker(worker);
  5588. mutex_unlock(&wq_pool_attach_mutex);
  5589. }
  5590. }
  5591. /**
  5592. * rebind_workers - rebind all workers of a pool to the associated CPU
  5593. * @pool: pool of interest
  5594. *
  5595. * @pool->cpu is coming online. Rebind all workers to the CPU.
  5596. */
  5597. static void rebind_workers(struct worker_pool *pool)
  5598. {
  5599. struct worker *worker;
  5600. lockdep_assert_held(&wq_pool_attach_mutex);
  5601. /*
  5602. * Restore CPU affinity of all workers. As all idle workers should
  5603. * be on the run-queue of the associated CPU before any local
  5604. * wake-ups for concurrency management happen, restore CPU affinity
  5605. * of all workers first and then clear UNBOUND. As we're called
  5606. * from CPU_ONLINE, the following shouldn't fail.
  5607. */
  5608. for_each_pool_worker(worker, pool) {
  5609. kthread_set_per_cpu(worker->task, pool->cpu);
  5610. WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
  5611. pool_allowed_cpus(pool)) < 0);
  5612. }
  5613. raw_spin_lock_irq(&pool->lock);
  5614. pool->flags &= ~POOL_DISASSOCIATED;
  5615. for_each_pool_worker(worker, pool) {
  5616. unsigned int worker_flags = worker->flags;
  5617. /*
  5618. * We want to clear UNBOUND but can't directly call
  5619. * worker_clr_flags() or adjust nr_running. Atomically
  5620. * replace UNBOUND with another NOT_RUNNING flag REBOUND.
  5621. * @worker will clear REBOUND using worker_clr_flags() when
  5622. * it initiates the next execution cycle thus restoring
  5623. * concurrency management. Note that when or whether
  5624. * @worker clears REBOUND doesn't affect correctness.
  5625. *
  5626. * WRITE_ONCE() is necessary because @worker->flags may be
  5627. * tested without holding any lock in
  5628. * wq_worker_running(). Without it, NOT_RUNNING test may
  5629. * fail incorrectly leading to premature concurrency
  5630. * management operations.
  5631. */
  5632. WARN_ON_ONCE(!(worker_flags & WORKER_UNBOUND));
  5633. worker_flags |= WORKER_REBOUND;
  5634. worker_flags &= ~WORKER_UNBOUND;
  5635. WRITE_ONCE(worker->flags, worker_flags);
  5636. }
  5637. raw_spin_unlock_irq(&pool->lock);
  5638. }
  5639. /**
  5640. * restore_unbound_workers_cpumask - restore cpumask of unbound workers
  5641. * @pool: unbound pool of interest
  5642. * @cpu: the CPU which is coming up
  5643. *
  5644. * An unbound pool may end up with a cpumask which doesn't have any online
  5645. * CPUs. When a worker of such pool get scheduled, the scheduler resets
  5646. * its cpus_allowed. If @cpu is in @pool's cpumask which didn't have any
  5647. * online CPU before, cpus_allowed of all its workers should be restored.
  5648. */
  5649. static void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu)
  5650. {
  5651. static cpumask_t cpumask;
  5652. struct worker *worker;
  5653. lockdep_assert_held(&wq_pool_attach_mutex);
  5654. /* is @cpu allowed for @pool? */
  5655. if (!cpumask_test_cpu(cpu, pool->attrs->cpumask))
  5656. return;
  5657. cpumask_and(&cpumask, pool->attrs->cpumask, cpu_online_mask);
  5658. /* as we're called from CPU_ONLINE, the following shouldn't fail */
  5659. for_each_pool_worker(worker, pool)
  5660. WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, &cpumask) < 0);
  5661. }
  5662. int workqueue_prepare_cpu(unsigned int cpu)
  5663. {
  5664. struct worker_pool *pool;
  5665. for_each_cpu_worker_pool(pool, cpu) {
  5666. if (pool->nr_workers)
  5667. continue;
  5668. if (!create_worker(pool))
  5669. return -ENOMEM;
  5670. }
  5671. return 0;
  5672. }
  5673. int workqueue_online_cpu(unsigned int cpu)
  5674. {
  5675. struct worker_pool *pool;
  5676. struct workqueue_struct *wq;
  5677. int pi;
  5678. mutex_lock(&wq_pool_mutex);
  5679. cpumask_set_cpu(cpu, wq_online_cpumask);
  5680. for_each_pool(pool, pi) {
  5681. /* BH pools aren't affected by hotplug */
  5682. if (pool->flags & POOL_BH)
  5683. continue;
  5684. mutex_lock(&wq_pool_attach_mutex);
  5685. if (pool->cpu == cpu)
  5686. rebind_workers(pool);
  5687. else if (pool->cpu < 0)
  5688. restore_unbound_workers_cpumask(pool, cpu);
  5689. mutex_unlock(&wq_pool_attach_mutex);
  5690. }
  5691. /* update pod affinity of unbound workqueues */
  5692. list_for_each_entry(wq, &workqueues, list) {
  5693. struct workqueue_attrs *attrs = wq->unbound_attrs;
  5694. if (attrs) {
  5695. const struct wq_pod_type *pt = wqattrs_pod_type(attrs);
  5696. int tcpu;
  5697. for_each_cpu(tcpu, pt->pod_cpus[pt->cpu_pod[cpu]])
  5698. unbound_wq_update_pwq(wq, tcpu);
  5699. mutex_lock(&wq->mutex);
  5700. wq_update_node_max_active(wq, -1);
  5701. mutex_unlock(&wq->mutex);
  5702. }
  5703. }
  5704. mutex_unlock(&wq_pool_mutex);
  5705. return 0;
  5706. }
  5707. int workqueue_offline_cpu(unsigned int cpu)
  5708. {
  5709. struct workqueue_struct *wq;
  5710. /* unbinding per-cpu workers should happen on the local CPU */
  5711. if (WARN_ON(cpu != smp_processor_id()))
  5712. return -1;
  5713. unbind_workers(cpu);
  5714. /* update pod affinity of unbound workqueues */
  5715. mutex_lock(&wq_pool_mutex);
  5716. cpumask_clear_cpu(cpu, wq_online_cpumask);
  5717. list_for_each_entry(wq, &workqueues, list) {
  5718. struct workqueue_attrs *attrs = wq->unbound_attrs;
  5719. if (attrs) {
  5720. const struct wq_pod_type *pt = wqattrs_pod_type(attrs);
  5721. int tcpu;
  5722. for_each_cpu(tcpu, pt->pod_cpus[pt->cpu_pod[cpu]])
  5723. unbound_wq_update_pwq(wq, tcpu);
  5724. mutex_lock(&wq->mutex);
  5725. wq_update_node_max_active(wq, cpu);
  5726. mutex_unlock(&wq->mutex);
  5727. }
  5728. }
  5729. mutex_unlock(&wq_pool_mutex);
  5730. return 0;
  5731. }
  5732. struct work_for_cpu {
  5733. struct work_struct work;
  5734. long (*fn)(void *);
  5735. void *arg;
  5736. long ret;
  5737. };
  5738. static void work_for_cpu_fn(struct work_struct *work)
  5739. {
  5740. struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
  5741. wfc->ret = wfc->fn(wfc->arg);
  5742. }
  5743. /**
  5744. * work_on_cpu_key - run a function in thread context on a particular cpu
  5745. * @cpu: the cpu to run on
  5746. * @fn: the function to run
  5747. * @arg: the function arg
  5748. * @key: The lock class key for lock debugging purposes
  5749. *
  5750. * It is up to the caller to ensure that the cpu doesn't go offline.
  5751. * The caller must not hold any locks which would prevent @fn from completing.
  5752. *
  5753. * Return: The value @fn returns.
  5754. */
  5755. long work_on_cpu_key(int cpu, long (*fn)(void *),
  5756. void *arg, struct lock_class_key *key)
  5757. {
  5758. struct work_for_cpu wfc = { .fn = fn, .arg = arg };
  5759. INIT_WORK_ONSTACK_KEY(&wfc.work, work_for_cpu_fn, key);
  5760. schedule_work_on(cpu, &wfc.work);
  5761. flush_work(&wfc.work);
  5762. destroy_work_on_stack(&wfc.work);
  5763. return wfc.ret;
  5764. }
  5765. EXPORT_SYMBOL_GPL(work_on_cpu_key);
  5766. /**
  5767. * work_on_cpu_safe_key - run a function in thread context on a particular cpu
  5768. * @cpu: the cpu to run on
  5769. * @fn: the function to run
  5770. * @arg: the function argument
  5771. * @key: The lock class key for lock debugging purposes
  5772. *
  5773. * Disables CPU hotplug and calls work_on_cpu(). The caller must not hold
  5774. * any locks which would prevent @fn from completing.
  5775. *
  5776. * Return: The value @fn returns.
  5777. */
  5778. long work_on_cpu_safe_key(int cpu, long (*fn)(void *),
  5779. void *arg, struct lock_class_key *key)
  5780. {
  5781. long ret = -ENODEV;
  5782. cpus_read_lock();
  5783. if (cpu_online(cpu))
  5784. ret = work_on_cpu_key(cpu, fn, arg, key);
  5785. cpus_read_unlock();
  5786. return ret;
  5787. }
  5788. EXPORT_SYMBOL_GPL(work_on_cpu_safe_key);
  5789. #endif /* CONFIG_SMP */
  5790. #ifdef CONFIG_FREEZER
  5791. /**
  5792. * freeze_workqueues_begin - begin freezing workqueues
  5793. *
  5794. * Start freezing workqueues. After this function returns, all freezable
  5795. * workqueues will queue new works to their inactive_works list instead of
  5796. * pool->worklist.
  5797. *
  5798. * CONTEXT:
  5799. * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
  5800. */
  5801. void freeze_workqueues_begin(void)
  5802. {
  5803. struct workqueue_struct *wq;
  5804. mutex_lock(&wq_pool_mutex);
  5805. WARN_ON_ONCE(workqueue_freezing);
  5806. workqueue_freezing = true;
  5807. list_for_each_entry(wq, &workqueues, list) {
  5808. mutex_lock(&wq->mutex);
  5809. wq_adjust_max_active(wq);
  5810. mutex_unlock(&wq->mutex);
  5811. }
  5812. mutex_unlock(&wq_pool_mutex);
  5813. }
  5814. /**
  5815. * freeze_workqueues_busy - are freezable workqueues still busy?
  5816. *
  5817. * Check whether freezing is complete. This function must be called
  5818. * between freeze_workqueues_begin() and thaw_workqueues().
  5819. *
  5820. * CONTEXT:
  5821. * Grabs and releases wq_pool_mutex.
  5822. *
  5823. * Return:
  5824. * %true if some freezable workqueues are still busy. %false if freezing
  5825. * is complete.
  5826. */
  5827. bool freeze_workqueues_busy(void)
  5828. {
  5829. bool busy = false;
  5830. struct workqueue_struct *wq;
  5831. struct pool_workqueue *pwq;
  5832. mutex_lock(&wq_pool_mutex);
  5833. WARN_ON_ONCE(!workqueue_freezing);
  5834. list_for_each_entry(wq, &workqueues, list) {
  5835. if (!(wq->flags & WQ_FREEZABLE))
  5836. continue;
  5837. /*
  5838. * nr_active is monotonically decreasing. It's safe
  5839. * to peek without lock.
  5840. */
  5841. rcu_read_lock();
  5842. for_each_pwq(pwq, wq) {
  5843. WARN_ON_ONCE(pwq->nr_active < 0);
  5844. if (pwq->nr_active) {
  5845. busy = true;
  5846. rcu_read_unlock();
  5847. goto out_unlock;
  5848. }
  5849. }
  5850. rcu_read_unlock();
  5851. }
  5852. out_unlock:
  5853. mutex_unlock(&wq_pool_mutex);
  5854. return busy;
  5855. }
  5856. /**
  5857. * thaw_workqueues - thaw workqueues
  5858. *
  5859. * Thaw workqueues. Normal queueing is restored and all collected
  5860. * frozen works are transferred to their respective pool worklists.
  5861. *
  5862. * CONTEXT:
  5863. * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
  5864. */
  5865. void thaw_workqueues(void)
  5866. {
  5867. struct workqueue_struct *wq;
  5868. mutex_lock(&wq_pool_mutex);
  5869. if (!workqueue_freezing)
  5870. goto out_unlock;
  5871. workqueue_freezing = false;
  5872. /* restore max_active and repopulate worklist */
  5873. list_for_each_entry(wq, &workqueues, list) {
  5874. mutex_lock(&wq->mutex);
  5875. wq_adjust_max_active(wq);
  5876. mutex_unlock(&wq->mutex);
  5877. }
  5878. out_unlock:
  5879. mutex_unlock(&wq_pool_mutex);
  5880. }
  5881. #endif /* CONFIG_FREEZER */
  5882. static int workqueue_apply_unbound_cpumask(const cpumask_var_t unbound_cpumask)
  5883. {
  5884. LIST_HEAD(ctxs);
  5885. int ret = 0;
  5886. struct workqueue_struct *wq;
  5887. struct apply_wqattrs_ctx *ctx, *n;
  5888. lockdep_assert_held(&wq_pool_mutex);
  5889. list_for_each_entry(wq, &workqueues, list) {
  5890. if (!(wq->flags & WQ_UNBOUND) || (wq->flags & __WQ_DESTROYING))
  5891. continue;
  5892. ctx = apply_wqattrs_prepare(wq, wq->unbound_attrs, unbound_cpumask);
  5893. if (IS_ERR(ctx)) {
  5894. ret = PTR_ERR(ctx);
  5895. break;
  5896. }
  5897. list_add_tail(&ctx->list, &ctxs);
  5898. }
  5899. list_for_each_entry_safe(ctx, n, &ctxs, list) {
  5900. if (!ret)
  5901. apply_wqattrs_commit(ctx);
  5902. apply_wqattrs_cleanup(ctx);
  5903. }
  5904. if (!ret) {
  5905. mutex_lock(&wq_pool_attach_mutex);
  5906. cpumask_copy(wq_unbound_cpumask, unbound_cpumask);
  5907. mutex_unlock(&wq_pool_attach_mutex);
  5908. }
  5909. return ret;
  5910. }
  5911. /**
  5912. * workqueue_unbound_exclude_cpumask - Exclude given CPUs from unbound cpumask
  5913. * @exclude_cpumask: the cpumask to be excluded from wq_unbound_cpumask
  5914. *
  5915. * This function can be called from cpuset code to provide a set of isolated
  5916. * CPUs that should be excluded from wq_unbound_cpumask.
  5917. */
  5918. int workqueue_unbound_exclude_cpumask(cpumask_var_t exclude_cpumask)
  5919. {
  5920. cpumask_var_t cpumask;
  5921. int ret = 0;
  5922. if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
  5923. return -ENOMEM;
  5924. mutex_lock(&wq_pool_mutex);
  5925. /*
  5926. * If the operation fails, it will fall back to
  5927. * wq_requested_unbound_cpumask which is initially set to
  5928. * (HK_TYPE_WQ ∩ HK_TYPE_DOMAIN) house keeping mask and rewritten
  5929. * by any subsequent write to workqueue/cpumask sysfs file.
  5930. */
  5931. if (!cpumask_andnot(cpumask, wq_requested_unbound_cpumask, exclude_cpumask))
  5932. cpumask_copy(cpumask, wq_requested_unbound_cpumask);
  5933. if (!cpumask_equal(cpumask, wq_unbound_cpumask))
  5934. ret = workqueue_apply_unbound_cpumask(cpumask);
  5935. /* Save the current isolated cpumask & export it via sysfs */
  5936. if (!ret)
  5937. cpumask_copy(wq_isolated_cpumask, exclude_cpumask);
  5938. mutex_unlock(&wq_pool_mutex);
  5939. free_cpumask_var(cpumask);
  5940. return ret;
  5941. }
  5942. static int parse_affn_scope(const char *val)
  5943. {
  5944. int i;
  5945. for (i = 0; i < ARRAY_SIZE(wq_affn_names); i++) {
  5946. if (!strncasecmp(val, wq_affn_names[i], strlen(wq_affn_names[i])))
  5947. return i;
  5948. }
  5949. return -EINVAL;
  5950. }
  5951. static int wq_affn_dfl_set(const char *val, const struct kernel_param *kp)
  5952. {
  5953. struct workqueue_struct *wq;
  5954. int affn, cpu;
  5955. affn = parse_affn_scope(val);
  5956. if (affn < 0)
  5957. return affn;
  5958. if (affn == WQ_AFFN_DFL)
  5959. return -EINVAL;
  5960. cpus_read_lock();
  5961. mutex_lock(&wq_pool_mutex);
  5962. wq_affn_dfl = affn;
  5963. list_for_each_entry(wq, &workqueues, list) {
  5964. for_each_online_cpu(cpu)
  5965. unbound_wq_update_pwq(wq, cpu);
  5966. }
  5967. mutex_unlock(&wq_pool_mutex);
  5968. cpus_read_unlock();
  5969. return 0;
  5970. }
  5971. static int wq_affn_dfl_get(char *buffer, const struct kernel_param *kp)
  5972. {
  5973. return scnprintf(buffer, PAGE_SIZE, "%s\n", wq_affn_names[wq_affn_dfl]);
  5974. }
  5975. static const struct kernel_param_ops wq_affn_dfl_ops = {
  5976. .set = wq_affn_dfl_set,
  5977. .get = wq_affn_dfl_get,
  5978. };
  5979. module_param_cb(default_affinity_scope, &wq_affn_dfl_ops, NULL, 0644);
  5980. #ifdef CONFIG_SYSFS
  5981. /*
  5982. * Workqueues with WQ_SYSFS flag set is visible to userland via
  5983. * /sys/bus/workqueue/devices/WQ_NAME. All visible workqueues have the
  5984. * following attributes.
  5985. *
  5986. * per_cpu RO bool : whether the workqueue is per-cpu or unbound
  5987. * max_active RW int : maximum number of in-flight work items
  5988. *
  5989. * Unbound workqueues have the following extra attributes.
  5990. *
  5991. * nice RW int : nice value of the workers
  5992. * cpumask RW mask : bitmask of allowed CPUs for the workers
  5993. * affinity_scope RW str : worker CPU affinity scope (cache, numa, none)
  5994. * affinity_strict RW bool : worker CPU affinity is strict
  5995. */
  5996. struct wq_device {
  5997. struct workqueue_struct *wq;
  5998. struct device dev;
  5999. };
  6000. static struct workqueue_struct *dev_to_wq(struct device *dev)
  6001. {
  6002. struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
  6003. return wq_dev->wq;
  6004. }
  6005. static ssize_t per_cpu_show(struct device *dev, struct device_attribute *attr,
  6006. char *buf)
  6007. {
  6008. struct workqueue_struct *wq = dev_to_wq(dev);
  6009. return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND));
  6010. }
  6011. static DEVICE_ATTR_RO(per_cpu);
  6012. static ssize_t max_active_show(struct device *dev,
  6013. struct device_attribute *attr, char *buf)
  6014. {
  6015. struct workqueue_struct *wq = dev_to_wq(dev);
  6016. return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active);
  6017. }
  6018. static ssize_t max_active_store(struct device *dev,
  6019. struct device_attribute *attr, const char *buf,
  6020. size_t count)
  6021. {
  6022. struct workqueue_struct *wq = dev_to_wq(dev);
  6023. int val;
  6024. if (sscanf(buf, "%d", &val) != 1 || val <= 0)
  6025. return -EINVAL;
  6026. workqueue_set_max_active(wq, val);
  6027. return count;
  6028. }
  6029. static DEVICE_ATTR_RW(max_active);
  6030. static struct attribute *wq_sysfs_attrs[] = {
  6031. &dev_attr_per_cpu.attr,
  6032. &dev_attr_max_active.attr,
  6033. NULL,
  6034. };
  6035. ATTRIBUTE_GROUPS(wq_sysfs);
  6036. static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr,
  6037. char *buf)
  6038. {
  6039. struct workqueue_struct *wq = dev_to_wq(dev);
  6040. int written;
  6041. mutex_lock(&wq->mutex);
  6042. written = scnprintf(buf, PAGE_SIZE, "%d\n", wq->unbound_attrs->nice);
  6043. mutex_unlock(&wq->mutex);
  6044. return written;
  6045. }
  6046. /* prepare workqueue_attrs for sysfs store operations */
  6047. static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq)
  6048. {
  6049. struct workqueue_attrs *attrs;
  6050. lockdep_assert_held(&wq_pool_mutex);
  6051. attrs = alloc_workqueue_attrs();
  6052. if (!attrs)
  6053. return NULL;
  6054. copy_workqueue_attrs(attrs, wq->unbound_attrs);
  6055. return attrs;
  6056. }
  6057. static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr,
  6058. const char *buf, size_t count)
  6059. {
  6060. struct workqueue_struct *wq = dev_to_wq(dev);
  6061. struct workqueue_attrs *attrs;
  6062. int ret = -ENOMEM;
  6063. apply_wqattrs_lock();
  6064. attrs = wq_sysfs_prep_attrs(wq);
  6065. if (!attrs)
  6066. goto out_unlock;
  6067. if (sscanf(buf, "%d", &attrs->nice) == 1 &&
  6068. attrs->nice >= MIN_NICE && attrs->nice <= MAX_NICE)
  6069. ret = apply_workqueue_attrs_locked(wq, attrs);
  6070. else
  6071. ret = -EINVAL;
  6072. out_unlock:
  6073. apply_wqattrs_unlock();
  6074. free_workqueue_attrs(attrs);
  6075. return ret ?: count;
  6076. }
  6077. static ssize_t wq_cpumask_show(struct device *dev,
  6078. struct device_attribute *attr, char *buf)
  6079. {
  6080. struct workqueue_struct *wq = dev_to_wq(dev);
  6081. int written;
  6082. mutex_lock(&wq->mutex);
  6083. written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
  6084. cpumask_pr_args(wq->unbound_attrs->cpumask));
  6085. mutex_unlock(&wq->mutex);
  6086. return written;
  6087. }
  6088. static ssize_t wq_cpumask_store(struct device *dev,
  6089. struct device_attribute *attr,
  6090. const char *buf, size_t count)
  6091. {
  6092. struct workqueue_struct *wq = dev_to_wq(dev);
  6093. struct workqueue_attrs *attrs;
  6094. int ret = -ENOMEM;
  6095. apply_wqattrs_lock();
  6096. attrs = wq_sysfs_prep_attrs(wq);
  6097. if (!attrs)
  6098. goto out_unlock;
  6099. ret = cpumask_parse(buf, attrs->cpumask);
  6100. if (!ret)
  6101. ret = apply_workqueue_attrs_locked(wq, attrs);
  6102. out_unlock:
  6103. apply_wqattrs_unlock();
  6104. free_workqueue_attrs(attrs);
  6105. return ret ?: count;
  6106. }
  6107. static ssize_t wq_affn_scope_show(struct device *dev,
  6108. struct device_attribute *attr, char *buf)
  6109. {
  6110. struct workqueue_struct *wq = dev_to_wq(dev);
  6111. int written;
  6112. mutex_lock(&wq->mutex);
  6113. if (wq->unbound_attrs->affn_scope == WQ_AFFN_DFL)
  6114. written = scnprintf(buf, PAGE_SIZE, "%s (%s)\n",
  6115. wq_affn_names[WQ_AFFN_DFL],
  6116. wq_affn_names[wq_affn_dfl]);
  6117. else
  6118. written = scnprintf(buf, PAGE_SIZE, "%s\n",
  6119. wq_affn_names[wq->unbound_attrs->affn_scope]);
  6120. mutex_unlock(&wq->mutex);
  6121. return written;
  6122. }
  6123. static ssize_t wq_affn_scope_store(struct device *dev,
  6124. struct device_attribute *attr,
  6125. const char *buf, size_t count)
  6126. {
  6127. struct workqueue_struct *wq = dev_to_wq(dev);
  6128. struct workqueue_attrs *attrs;
  6129. int affn, ret = -ENOMEM;
  6130. affn = parse_affn_scope(buf);
  6131. if (affn < 0)
  6132. return affn;
  6133. apply_wqattrs_lock();
  6134. attrs = wq_sysfs_prep_attrs(wq);
  6135. if (attrs) {
  6136. attrs->affn_scope = affn;
  6137. ret = apply_workqueue_attrs_locked(wq, attrs);
  6138. }
  6139. apply_wqattrs_unlock();
  6140. free_workqueue_attrs(attrs);
  6141. return ret ?: count;
  6142. }
  6143. static ssize_t wq_affinity_strict_show(struct device *dev,
  6144. struct device_attribute *attr, char *buf)
  6145. {
  6146. struct workqueue_struct *wq = dev_to_wq(dev);
  6147. return scnprintf(buf, PAGE_SIZE, "%d\n",
  6148. wq->unbound_attrs->affn_strict);
  6149. }
  6150. static ssize_t wq_affinity_strict_store(struct device *dev,
  6151. struct device_attribute *attr,
  6152. const char *buf, size_t count)
  6153. {
  6154. struct workqueue_struct *wq = dev_to_wq(dev);
  6155. struct workqueue_attrs *attrs;
  6156. int v, ret = -ENOMEM;
  6157. if (sscanf(buf, "%d", &v) != 1)
  6158. return -EINVAL;
  6159. apply_wqattrs_lock();
  6160. attrs = wq_sysfs_prep_attrs(wq);
  6161. if (attrs) {
  6162. attrs->affn_strict = (bool)v;
  6163. ret = apply_workqueue_attrs_locked(wq, attrs);
  6164. }
  6165. apply_wqattrs_unlock();
  6166. free_workqueue_attrs(attrs);
  6167. return ret ?: count;
  6168. }
  6169. static struct device_attribute wq_sysfs_unbound_attrs[] = {
  6170. __ATTR(nice, 0644, wq_nice_show, wq_nice_store),
  6171. __ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store),
  6172. __ATTR(affinity_scope, 0644, wq_affn_scope_show, wq_affn_scope_store),
  6173. __ATTR(affinity_strict, 0644, wq_affinity_strict_show, wq_affinity_strict_store),
  6174. __ATTR_NULL,
  6175. };
  6176. static const struct bus_type wq_subsys = {
  6177. .name = "workqueue",
  6178. .dev_groups = wq_sysfs_groups,
  6179. };
  6180. /**
  6181. * workqueue_set_unbound_cpumask - Set the low-level unbound cpumask
  6182. * @cpumask: the cpumask to set
  6183. *
  6184. * The low-level workqueues cpumask is a global cpumask that limits
  6185. * the affinity of all unbound workqueues. This function check the @cpumask
  6186. * and apply it to all unbound workqueues and updates all pwqs of them.
  6187. *
  6188. * Return: 0 - Success
  6189. * -EINVAL - Invalid @cpumask
  6190. * -ENOMEM - Failed to allocate memory for attrs or pwqs.
  6191. */
  6192. static int workqueue_set_unbound_cpumask(cpumask_var_t cpumask)
  6193. {
  6194. int ret = -EINVAL;
  6195. /*
  6196. * Not excluding isolated cpus on purpose.
  6197. * If the user wishes to include them, we allow that.
  6198. */
  6199. cpumask_and(cpumask, cpumask, cpu_possible_mask);
  6200. if (!cpumask_empty(cpumask)) {
  6201. ret = 0;
  6202. apply_wqattrs_lock();
  6203. if (!cpumask_equal(cpumask, wq_unbound_cpumask))
  6204. ret = workqueue_apply_unbound_cpumask(cpumask);
  6205. if (!ret)
  6206. cpumask_copy(wq_requested_unbound_cpumask, cpumask);
  6207. apply_wqattrs_unlock();
  6208. }
  6209. return ret;
  6210. }
  6211. static ssize_t __wq_cpumask_show(struct device *dev,
  6212. struct device_attribute *attr, char *buf, cpumask_var_t mask)
  6213. {
  6214. int written;
  6215. mutex_lock(&wq_pool_mutex);
  6216. written = scnprintf(buf, PAGE_SIZE, "%*pb\n", cpumask_pr_args(mask));
  6217. mutex_unlock(&wq_pool_mutex);
  6218. return written;
  6219. }
  6220. static ssize_t cpumask_requested_show(struct device *dev,
  6221. struct device_attribute *attr, char *buf)
  6222. {
  6223. return __wq_cpumask_show(dev, attr, buf, wq_requested_unbound_cpumask);
  6224. }
  6225. static DEVICE_ATTR_RO(cpumask_requested);
  6226. static ssize_t cpumask_isolated_show(struct device *dev,
  6227. struct device_attribute *attr, char *buf)
  6228. {
  6229. return __wq_cpumask_show(dev, attr, buf, wq_isolated_cpumask);
  6230. }
  6231. static DEVICE_ATTR_RO(cpumask_isolated);
  6232. static ssize_t cpumask_show(struct device *dev,
  6233. struct device_attribute *attr, char *buf)
  6234. {
  6235. return __wq_cpumask_show(dev, attr, buf, wq_unbound_cpumask);
  6236. }
  6237. static ssize_t cpumask_store(struct device *dev,
  6238. struct device_attribute *attr, const char *buf, size_t count)
  6239. {
  6240. cpumask_var_t cpumask;
  6241. int ret;
  6242. if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
  6243. return -ENOMEM;
  6244. ret = cpumask_parse(buf, cpumask);
  6245. if (!ret)
  6246. ret = workqueue_set_unbound_cpumask(cpumask);
  6247. free_cpumask_var(cpumask);
  6248. return ret ? ret : count;
  6249. }
  6250. static DEVICE_ATTR_RW(cpumask);
  6251. static struct attribute *wq_sysfs_cpumask_attrs[] = {
  6252. &dev_attr_cpumask.attr,
  6253. &dev_attr_cpumask_requested.attr,
  6254. &dev_attr_cpumask_isolated.attr,
  6255. NULL,
  6256. };
  6257. ATTRIBUTE_GROUPS(wq_sysfs_cpumask);
  6258. static int __init wq_sysfs_init(void)
  6259. {
  6260. return subsys_virtual_register(&wq_subsys, wq_sysfs_cpumask_groups);
  6261. }
  6262. core_initcall(wq_sysfs_init);
  6263. static void wq_device_release(struct device *dev)
  6264. {
  6265. struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
  6266. kfree(wq_dev);
  6267. }
  6268. /**
  6269. * workqueue_sysfs_register - make a workqueue visible in sysfs
  6270. * @wq: the workqueue to register
  6271. *
  6272. * Expose @wq in sysfs under /sys/bus/workqueue/devices.
  6273. * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
  6274. * which is the preferred method.
  6275. *
  6276. * Workqueue user should use this function directly iff it wants to apply
  6277. * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
  6278. * apply_workqueue_attrs() may race against userland updating the
  6279. * attributes.
  6280. *
  6281. * Return: 0 on success, -errno on failure.
  6282. */
  6283. int workqueue_sysfs_register(struct workqueue_struct *wq)
  6284. {
  6285. struct wq_device *wq_dev;
  6286. int ret;
  6287. /*
  6288. * Adjusting max_active breaks ordering guarantee. Disallow exposing
  6289. * ordered workqueues.
  6290. */
  6291. if (WARN_ON(wq->flags & __WQ_ORDERED))
  6292. return -EINVAL;
  6293. wq->wq_dev = wq_dev = kzalloc(sizeof(*wq_dev), GFP_KERNEL);
  6294. if (!wq_dev)
  6295. return -ENOMEM;
  6296. wq_dev->wq = wq;
  6297. wq_dev->dev.bus = &wq_subsys;
  6298. wq_dev->dev.release = wq_device_release;
  6299. dev_set_name(&wq_dev->dev, "%s", wq->name);
  6300. /*
  6301. * unbound_attrs are created separately. Suppress uevent until
  6302. * everything is ready.
  6303. */
  6304. dev_set_uevent_suppress(&wq_dev->dev, true);
  6305. ret = device_register(&wq_dev->dev);
  6306. if (ret) {
  6307. put_device(&wq_dev->dev);
  6308. wq->wq_dev = NULL;
  6309. return ret;
  6310. }
  6311. if (wq->flags & WQ_UNBOUND) {
  6312. struct device_attribute *attr;
  6313. for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) {
  6314. ret = device_create_file(&wq_dev->dev, attr);
  6315. if (ret) {
  6316. device_unregister(&wq_dev->dev);
  6317. wq->wq_dev = NULL;
  6318. return ret;
  6319. }
  6320. }
  6321. }
  6322. dev_set_uevent_suppress(&wq_dev->dev, false);
  6323. kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD);
  6324. return 0;
  6325. }
  6326. /**
  6327. * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
  6328. * @wq: the workqueue to unregister
  6329. *
  6330. * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
  6331. */
  6332. static void workqueue_sysfs_unregister(struct workqueue_struct *wq)
  6333. {
  6334. struct wq_device *wq_dev = wq->wq_dev;
  6335. if (!wq->wq_dev)
  6336. return;
  6337. wq->wq_dev = NULL;
  6338. device_unregister(&wq_dev->dev);
  6339. }
  6340. #else /* CONFIG_SYSFS */
  6341. static void workqueue_sysfs_unregister(struct workqueue_struct *wq) { }
  6342. #endif /* CONFIG_SYSFS */
  6343. /*
  6344. * Workqueue watchdog.
  6345. *
  6346. * Stall may be caused by various bugs - missing WQ_MEM_RECLAIM, illegal
  6347. * flush dependency, a concurrency managed work item which stays RUNNING
  6348. * indefinitely. Workqueue stalls can be very difficult to debug as the
  6349. * usual warning mechanisms don't trigger and internal workqueue state is
  6350. * largely opaque.
  6351. *
  6352. * Workqueue watchdog monitors all worker pools periodically and dumps
  6353. * state if some pools failed to make forward progress for a while where
  6354. * forward progress is defined as the first item on ->worklist changing.
  6355. *
  6356. * This mechanism is controlled through the kernel parameter
  6357. * "workqueue.watchdog_thresh" which can be updated at runtime through the
  6358. * corresponding sysfs parameter file.
  6359. */
  6360. #ifdef CONFIG_WQ_WATCHDOG
  6361. static unsigned long wq_watchdog_thresh = 30;
  6362. static struct timer_list wq_watchdog_timer;
  6363. static unsigned long wq_watchdog_touched = INITIAL_JIFFIES;
  6364. static DEFINE_PER_CPU(unsigned long, wq_watchdog_touched_cpu) = INITIAL_JIFFIES;
  6365. static unsigned int wq_panic_on_stall;
  6366. module_param_named(panic_on_stall, wq_panic_on_stall, uint, 0644);
  6367. /*
  6368. * Show workers that might prevent the processing of pending work items.
  6369. * The only candidates are CPU-bound workers in the running state.
  6370. * Pending work items should be handled by another idle worker
  6371. * in all other situations.
  6372. */
  6373. static void show_cpu_pool_hog(struct worker_pool *pool)
  6374. {
  6375. struct worker *worker;
  6376. unsigned long irq_flags;
  6377. int bkt;
  6378. raw_spin_lock_irqsave(&pool->lock, irq_flags);
  6379. hash_for_each(pool->busy_hash, bkt, worker, hentry) {
  6380. if (task_is_running(worker->task)) {
  6381. /*
  6382. * Defer printing to avoid deadlocks in console
  6383. * drivers that queue work while holding locks
  6384. * also taken in their write paths.
  6385. */
  6386. printk_deferred_enter();
  6387. pr_info("pool %d:\n", pool->id);
  6388. sched_show_task(worker->task);
  6389. printk_deferred_exit();
  6390. }
  6391. }
  6392. raw_spin_unlock_irqrestore(&pool->lock, irq_flags);
  6393. }
  6394. static void show_cpu_pools_hogs(void)
  6395. {
  6396. struct worker_pool *pool;
  6397. int pi;
  6398. pr_info("Showing backtraces of running workers in stalled CPU-bound worker pools:\n");
  6399. rcu_read_lock();
  6400. for_each_pool(pool, pi) {
  6401. if (pool->cpu_stall)
  6402. show_cpu_pool_hog(pool);
  6403. }
  6404. rcu_read_unlock();
  6405. }
  6406. static void panic_on_wq_watchdog(void)
  6407. {
  6408. static unsigned int wq_stall;
  6409. if (wq_panic_on_stall) {
  6410. wq_stall++;
  6411. BUG_ON(wq_stall >= wq_panic_on_stall);
  6412. }
  6413. }
  6414. static void wq_watchdog_reset_touched(void)
  6415. {
  6416. int cpu;
  6417. wq_watchdog_touched = jiffies;
  6418. for_each_possible_cpu(cpu)
  6419. per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
  6420. }
  6421. static void wq_watchdog_timer_fn(struct timer_list *unused)
  6422. {
  6423. unsigned long thresh = READ_ONCE(wq_watchdog_thresh) * HZ;
  6424. bool lockup_detected = false;
  6425. bool cpu_pool_stall = false;
  6426. unsigned long now = jiffies;
  6427. struct worker_pool *pool;
  6428. int pi;
  6429. if (!thresh)
  6430. return;
  6431. rcu_read_lock();
  6432. for_each_pool(pool, pi) {
  6433. unsigned long pool_ts, touched, ts;
  6434. pool->cpu_stall = false;
  6435. if (list_empty(&pool->worklist))
  6436. continue;
  6437. /*
  6438. * If a virtual machine is stopped by the host it can look to
  6439. * the watchdog like a stall.
  6440. */
  6441. kvm_check_and_clear_guest_paused();
  6442. /* get the latest of pool and touched timestamps */
  6443. if (pool->cpu >= 0)
  6444. touched = READ_ONCE(per_cpu(wq_watchdog_touched_cpu, pool->cpu));
  6445. else
  6446. touched = READ_ONCE(wq_watchdog_touched);
  6447. pool_ts = READ_ONCE(pool->watchdog_ts);
  6448. if (time_after(pool_ts, touched))
  6449. ts = pool_ts;
  6450. else
  6451. ts = touched;
  6452. /* did we stall? */
  6453. if (time_after(now, ts + thresh)) {
  6454. lockup_detected = true;
  6455. if (pool->cpu >= 0 && !(pool->flags & POOL_BH)) {
  6456. pool->cpu_stall = true;
  6457. cpu_pool_stall = true;
  6458. }
  6459. pr_emerg("BUG: workqueue lockup - pool");
  6460. pr_cont_pool_info(pool);
  6461. pr_cont(" stuck for %us!\n",
  6462. jiffies_to_msecs(now - pool_ts) / 1000);
  6463. }
  6464. }
  6465. rcu_read_unlock();
  6466. if (lockup_detected)
  6467. show_all_workqueues();
  6468. if (cpu_pool_stall)
  6469. show_cpu_pools_hogs();
  6470. if (lockup_detected)
  6471. panic_on_wq_watchdog();
  6472. wq_watchdog_reset_touched();
  6473. mod_timer(&wq_watchdog_timer, jiffies + thresh);
  6474. }
  6475. notrace void wq_watchdog_touch(int cpu)
  6476. {
  6477. unsigned long thresh = READ_ONCE(wq_watchdog_thresh) * HZ;
  6478. unsigned long touch_ts = READ_ONCE(wq_watchdog_touched);
  6479. unsigned long now = jiffies;
  6480. if (cpu >= 0)
  6481. per_cpu(wq_watchdog_touched_cpu, cpu) = now;
  6482. else
  6483. WARN_ONCE(1, "%s should be called with valid CPU", __func__);
  6484. /* Don't unnecessarily store to global cacheline */
  6485. if (time_after(now, touch_ts + thresh / 4))
  6486. WRITE_ONCE(wq_watchdog_touched, jiffies);
  6487. }
  6488. static void wq_watchdog_set_thresh(unsigned long thresh)
  6489. {
  6490. wq_watchdog_thresh = 0;
  6491. del_timer_sync(&wq_watchdog_timer);
  6492. if (thresh) {
  6493. wq_watchdog_thresh = thresh;
  6494. wq_watchdog_reset_touched();
  6495. mod_timer(&wq_watchdog_timer, jiffies + thresh * HZ);
  6496. }
  6497. }
  6498. static int wq_watchdog_param_set_thresh(const char *val,
  6499. const struct kernel_param *kp)
  6500. {
  6501. unsigned long thresh;
  6502. int ret;
  6503. ret = kstrtoul(val, 0, &thresh);
  6504. if (ret)
  6505. return ret;
  6506. if (system_wq)
  6507. wq_watchdog_set_thresh(thresh);
  6508. else
  6509. wq_watchdog_thresh = thresh;
  6510. return 0;
  6511. }
  6512. static const struct kernel_param_ops wq_watchdog_thresh_ops = {
  6513. .set = wq_watchdog_param_set_thresh,
  6514. .get = param_get_ulong,
  6515. };
  6516. module_param_cb(watchdog_thresh, &wq_watchdog_thresh_ops, &wq_watchdog_thresh,
  6517. 0644);
  6518. static void wq_watchdog_init(void)
  6519. {
  6520. timer_setup(&wq_watchdog_timer, wq_watchdog_timer_fn, TIMER_DEFERRABLE);
  6521. wq_watchdog_set_thresh(wq_watchdog_thresh);
  6522. }
  6523. #else /* CONFIG_WQ_WATCHDOG */
  6524. static inline void wq_watchdog_init(void) { }
  6525. #endif /* CONFIG_WQ_WATCHDOG */
  6526. static void bh_pool_kick_normal(struct irq_work *irq_work)
  6527. {
  6528. raise_softirq_irqoff(TASKLET_SOFTIRQ);
  6529. }
  6530. static void bh_pool_kick_highpri(struct irq_work *irq_work)
  6531. {
  6532. raise_softirq_irqoff(HI_SOFTIRQ);
  6533. }
  6534. static void __init restrict_unbound_cpumask(const char *name, const struct cpumask *mask)
  6535. {
  6536. if (!cpumask_intersects(wq_unbound_cpumask, mask)) {
  6537. pr_warn("workqueue: Restricting unbound_cpumask (%*pb) with %s (%*pb) leaves no CPU, ignoring\n",
  6538. cpumask_pr_args(wq_unbound_cpumask), name, cpumask_pr_args(mask));
  6539. return;
  6540. }
  6541. cpumask_and(wq_unbound_cpumask, wq_unbound_cpumask, mask);
  6542. }
  6543. static void __init init_cpu_worker_pool(struct worker_pool *pool, int cpu, int nice)
  6544. {
  6545. BUG_ON(init_worker_pool(pool));
  6546. pool->cpu = cpu;
  6547. cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
  6548. cpumask_copy(pool->attrs->__pod_cpumask, cpumask_of(cpu));
  6549. pool->attrs->nice = nice;
  6550. pool->attrs->affn_strict = true;
  6551. pool->node = cpu_to_node(cpu);
  6552. /* alloc pool ID */
  6553. mutex_lock(&wq_pool_mutex);
  6554. BUG_ON(worker_pool_assign_id(pool));
  6555. mutex_unlock(&wq_pool_mutex);
  6556. }
  6557. /**
  6558. * workqueue_init_early - early init for workqueue subsystem
  6559. *
  6560. * This is the first step of three-staged workqueue subsystem initialization and
  6561. * invoked as soon as the bare basics - memory allocation, cpumasks and idr are
  6562. * up. It sets up all the data structures and system workqueues and allows early
  6563. * boot code to create workqueues and queue/cancel work items. Actual work item
  6564. * execution starts only after kthreads can be created and scheduled right
  6565. * before early initcalls.
  6566. */
  6567. void __init workqueue_init_early(void)
  6568. {
  6569. struct wq_pod_type *pt = &wq_pod_types[WQ_AFFN_SYSTEM];
  6570. int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
  6571. void (*irq_work_fns[2])(struct irq_work *) = { bh_pool_kick_normal,
  6572. bh_pool_kick_highpri };
  6573. int i, cpu;
  6574. BUILD_BUG_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
  6575. BUG_ON(!alloc_cpumask_var(&wq_online_cpumask, GFP_KERNEL));
  6576. BUG_ON(!alloc_cpumask_var(&wq_unbound_cpumask, GFP_KERNEL));
  6577. BUG_ON(!alloc_cpumask_var(&wq_requested_unbound_cpumask, GFP_KERNEL));
  6578. BUG_ON(!zalloc_cpumask_var(&wq_isolated_cpumask, GFP_KERNEL));
  6579. cpumask_copy(wq_online_cpumask, cpu_online_mask);
  6580. cpumask_copy(wq_unbound_cpumask, cpu_possible_mask);
  6581. restrict_unbound_cpumask("HK_TYPE_WQ", housekeeping_cpumask(HK_TYPE_WQ));
  6582. restrict_unbound_cpumask("HK_TYPE_DOMAIN", housekeeping_cpumask(HK_TYPE_DOMAIN));
  6583. if (!cpumask_empty(&wq_cmdline_cpumask))
  6584. restrict_unbound_cpumask("workqueue.unbound_cpus", &wq_cmdline_cpumask);
  6585. cpumask_copy(wq_requested_unbound_cpumask, wq_unbound_cpumask);
  6586. cpumask_andnot(wq_isolated_cpumask, cpu_possible_mask,
  6587. housekeeping_cpumask(HK_TYPE_DOMAIN));
  6588. pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
  6589. unbound_wq_update_pwq_attrs_buf = alloc_workqueue_attrs();
  6590. BUG_ON(!unbound_wq_update_pwq_attrs_buf);
  6591. /*
  6592. * If nohz_full is enabled, set power efficient workqueue as unbound.
  6593. * This allows workqueue items to be moved to HK CPUs.
  6594. */
  6595. if (housekeeping_enabled(HK_TYPE_TICK))
  6596. wq_power_efficient = true;
  6597. /* initialize WQ_AFFN_SYSTEM pods */
  6598. pt->pod_cpus = kcalloc(1, sizeof(pt->pod_cpus[0]), GFP_KERNEL);
  6599. pt->pod_node = kcalloc(1, sizeof(pt->pod_node[0]), GFP_KERNEL);
  6600. pt->cpu_pod = kcalloc(nr_cpu_ids, sizeof(pt->cpu_pod[0]), GFP_KERNEL);
  6601. BUG_ON(!pt->pod_cpus || !pt->pod_node || !pt->cpu_pod);
  6602. BUG_ON(!zalloc_cpumask_var_node(&pt->pod_cpus[0], GFP_KERNEL, NUMA_NO_NODE));
  6603. pt->nr_pods = 1;
  6604. cpumask_copy(pt->pod_cpus[0], cpu_possible_mask);
  6605. pt->pod_node[0] = NUMA_NO_NODE;
  6606. pt->cpu_pod[0] = 0;
  6607. /* initialize BH and CPU pools */
  6608. for_each_possible_cpu(cpu) {
  6609. struct worker_pool *pool;
  6610. i = 0;
  6611. for_each_bh_worker_pool(pool, cpu) {
  6612. init_cpu_worker_pool(pool, cpu, std_nice[i]);
  6613. pool->flags |= POOL_BH;
  6614. init_irq_work(bh_pool_irq_work(pool), irq_work_fns[i]);
  6615. i++;
  6616. }
  6617. i = 0;
  6618. for_each_cpu_worker_pool(pool, cpu)
  6619. init_cpu_worker_pool(pool, cpu, std_nice[i++]);
  6620. }
  6621. /* create default unbound and ordered wq attrs */
  6622. for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
  6623. struct workqueue_attrs *attrs;
  6624. BUG_ON(!(attrs = alloc_workqueue_attrs()));
  6625. attrs->nice = std_nice[i];
  6626. unbound_std_wq_attrs[i] = attrs;
  6627. /*
  6628. * An ordered wq should have only one pwq as ordering is
  6629. * guaranteed by max_active which is enforced by pwqs.
  6630. */
  6631. BUG_ON(!(attrs = alloc_workqueue_attrs()));
  6632. attrs->nice = std_nice[i];
  6633. attrs->ordered = true;
  6634. ordered_wq_attrs[i] = attrs;
  6635. }
  6636. system_wq = alloc_workqueue("events", 0, 0);
  6637. system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
  6638. system_long_wq = alloc_workqueue("events_long", 0, 0);
  6639. system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
  6640. WQ_MAX_ACTIVE);
  6641. system_freezable_wq = alloc_workqueue("events_freezable",
  6642. WQ_FREEZABLE, 0);
  6643. system_power_efficient_wq = alloc_workqueue("events_power_efficient",
  6644. WQ_POWER_EFFICIENT, 0);
  6645. system_freezable_power_efficient_wq = alloc_workqueue("events_freezable_pwr_efficient",
  6646. WQ_FREEZABLE | WQ_POWER_EFFICIENT,
  6647. 0);
  6648. system_bh_wq = alloc_workqueue("events_bh", WQ_BH, 0);
  6649. system_bh_highpri_wq = alloc_workqueue("events_bh_highpri",
  6650. WQ_BH | WQ_HIGHPRI, 0);
  6651. BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
  6652. !system_unbound_wq || !system_freezable_wq ||
  6653. !system_power_efficient_wq ||
  6654. !system_freezable_power_efficient_wq ||
  6655. !system_bh_wq || !system_bh_highpri_wq);
  6656. }
  6657. static void __init wq_cpu_intensive_thresh_init(void)
  6658. {
  6659. unsigned long thresh;
  6660. unsigned long bogo;
  6661. pwq_release_worker = kthread_create_worker(0, "pool_workqueue_release");
  6662. BUG_ON(IS_ERR(pwq_release_worker));
  6663. /* if the user set it to a specific value, keep it */
  6664. if (wq_cpu_intensive_thresh_us != ULONG_MAX)
  6665. return;
  6666. /*
  6667. * The default of 10ms is derived from the fact that most modern (as of
  6668. * 2023) processors can do a lot in 10ms and that it's just below what
  6669. * most consider human-perceivable. However, the kernel also runs on a
  6670. * lot slower CPUs including microcontrollers where the threshold is way
  6671. * too low.
  6672. *
  6673. * Let's scale up the threshold upto 1 second if BogoMips is below 4000.
  6674. * This is by no means accurate but it doesn't have to be. The mechanism
  6675. * is still useful even when the threshold is fully scaled up. Also, as
  6676. * the reports would usually be applicable to everyone, some machines
  6677. * operating on longer thresholds won't significantly diminish their
  6678. * usefulness.
  6679. */
  6680. thresh = 10 * USEC_PER_MSEC;
  6681. /* see init/calibrate.c for lpj -> BogoMIPS calculation */
  6682. bogo = max_t(unsigned long, loops_per_jiffy / 500000 * HZ, 1);
  6683. if (bogo < 4000)
  6684. thresh = min_t(unsigned long, thresh * 4000 / bogo, USEC_PER_SEC);
  6685. pr_debug("wq_cpu_intensive_thresh: lpj=%lu BogoMIPS=%lu thresh_us=%lu\n",
  6686. loops_per_jiffy, bogo, thresh);
  6687. wq_cpu_intensive_thresh_us = thresh;
  6688. }
  6689. /**
  6690. * workqueue_init - bring workqueue subsystem fully online
  6691. *
  6692. * This is the second step of three-staged workqueue subsystem initialization
  6693. * and invoked as soon as kthreads can be created and scheduled. Workqueues have
  6694. * been created and work items queued on them, but there are no kworkers
  6695. * executing the work items yet. Populate the worker pools with the initial
  6696. * workers and enable future kworker creations.
  6697. */
  6698. void __init workqueue_init(void)
  6699. {
  6700. struct workqueue_struct *wq;
  6701. struct worker_pool *pool;
  6702. int cpu, bkt;
  6703. wq_cpu_intensive_thresh_init();
  6704. mutex_lock(&wq_pool_mutex);
  6705. /*
  6706. * Per-cpu pools created earlier could be missing node hint. Fix them
  6707. * up. Also, create a rescuer for workqueues that requested it.
  6708. */
  6709. for_each_possible_cpu(cpu) {
  6710. for_each_bh_worker_pool(pool, cpu)
  6711. pool->node = cpu_to_node(cpu);
  6712. for_each_cpu_worker_pool(pool, cpu)
  6713. pool->node = cpu_to_node(cpu);
  6714. }
  6715. list_for_each_entry(wq, &workqueues, list) {
  6716. WARN(init_rescuer(wq),
  6717. "workqueue: failed to create early rescuer for %s",
  6718. wq->name);
  6719. }
  6720. mutex_unlock(&wq_pool_mutex);
  6721. /*
  6722. * Create the initial workers. A BH pool has one pseudo worker that
  6723. * represents the shared BH execution context and thus doesn't get
  6724. * affected by hotplug events. Create the BH pseudo workers for all
  6725. * possible CPUs here.
  6726. */
  6727. for_each_possible_cpu(cpu)
  6728. for_each_bh_worker_pool(pool, cpu)
  6729. BUG_ON(!create_worker(pool));
  6730. for_each_online_cpu(cpu) {
  6731. for_each_cpu_worker_pool(pool, cpu) {
  6732. pool->flags &= ~POOL_DISASSOCIATED;
  6733. BUG_ON(!create_worker(pool));
  6734. }
  6735. }
  6736. hash_for_each(unbound_pool_hash, bkt, pool, hash_node)
  6737. BUG_ON(!create_worker(pool));
  6738. wq_online = true;
  6739. wq_watchdog_init();
  6740. }
  6741. /*
  6742. * Initialize @pt by first initializing @pt->cpu_pod[] with pod IDs according to
  6743. * @cpu_shares_pod(). Each subset of CPUs that share a pod is assigned a unique
  6744. * and consecutive pod ID. The rest of @pt is initialized accordingly.
  6745. */
  6746. static void __init init_pod_type(struct wq_pod_type *pt,
  6747. bool (*cpus_share_pod)(int, int))
  6748. {
  6749. int cur, pre, cpu, pod;
  6750. pt->nr_pods = 0;
  6751. /* init @pt->cpu_pod[] according to @cpus_share_pod() */
  6752. pt->cpu_pod = kcalloc(nr_cpu_ids, sizeof(pt->cpu_pod[0]), GFP_KERNEL);
  6753. BUG_ON(!pt->cpu_pod);
  6754. for_each_possible_cpu(cur) {
  6755. for_each_possible_cpu(pre) {
  6756. if (pre >= cur) {
  6757. pt->cpu_pod[cur] = pt->nr_pods++;
  6758. break;
  6759. }
  6760. if (cpus_share_pod(cur, pre)) {
  6761. pt->cpu_pod[cur] = pt->cpu_pod[pre];
  6762. break;
  6763. }
  6764. }
  6765. }
  6766. /* init the rest to match @pt->cpu_pod[] */
  6767. pt->pod_cpus = kcalloc(pt->nr_pods, sizeof(pt->pod_cpus[0]), GFP_KERNEL);
  6768. pt->pod_node = kcalloc(pt->nr_pods, sizeof(pt->pod_node[0]), GFP_KERNEL);
  6769. BUG_ON(!pt->pod_cpus || !pt->pod_node);
  6770. for (pod = 0; pod < pt->nr_pods; pod++)
  6771. BUG_ON(!zalloc_cpumask_var(&pt->pod_cpus[pod], GFP_KERNEL));
  6772. for_each_possible_cpu(cpu) {
  6773. cpumask_set_cpu(cpu, pt->pod_cpus[pt->cpu_pod[cpu]]);
  6774. pt->pod_node[pt->cpu_pod[cpu]] = cpu_to_node(cpu);
  6775. }
  6776. }
  6777. static bool __init cpus_dont_share(int cpu0, int cpu1)
  6778. {
  6779. return false;
  6780. }
  6781. static bool __init cpus_share_smt(int cpu0, int cpu1)
  6782. {
  6783. #ifdef CONFIG_SCHED_SMT
  6784. return cpumask_test_cpu(cpu0, cpu_smt_mask(cpu1));
  6785. #else
  6786. return false;
  6787. #endif
  6788. }
  6789. static bool __init cpus_share_numa(int cpu0, int cpu1)
  6790. {
  6791. return cpu_to_node(cpu0) == cpu_to_node(cpu1);
  6792. }
  6793. /**
  6794. * workqueue_init_topology - initialize CPU pods for unbound workqueues
  6795. *
  6796. * This is the third step of three-staged workqueue subsystem initialization and
  6797. * invoked after SMP and topology information are fully initialized. It
  6798. * initializes the unbound CPU pods accordingly.
  6799. */
  6800. void __init workqueue_init_topology(void)
  6801. {
  6802. struct workqueue_struct *wq;
  6803. int cpu;
  6804. init_pod_type(&wq_pod_types[WQ_AFFN_CPU], cpus_dont_share);
  6805. init_pod_type(&wq_pod_types[WQ_AFFN_SMT], cpus_share_smt);
  6806. init_pod_type(&wq_pod_types[WQ_AFFN_CACHE], cpus_share_cache);
  6807. init_pod_type(&wq_pod_types[WQ_AFFN_NUMA], cpus_share_numa);
  6808. wq_topo_initialized = true;
  6809. mutex_lock(&wq_pool_mutex);
  6810. /*
  6811. * Workqueues allocated earlier would have all CPUs sharing the default
  6812. * worker pool. Explicitly call unbound_wq_update_pwq() on all workqueue
  6813. * and CPU combinations to apply per-pod sharing.
  6814. */
  6815. list_for_each_entry(wq, &workqueues, list) {
  6816. for_each_online_cpu(cpu)
  6817. unbound_wq_update_pwq(wq, cpu);
  6818. if (wq->flags & WQ_UNBOUND) {
  6819. mutex_lock(&wq->mutex);
  6820. wq_update_node_max_active(wq, -1);
  6821. mutex_unlock(&wq->mutex);
  6822. }
  6823. }
  6824. mutex_unlock(&wq_pool_mutex);
  6825. }
  6826. void __warn_flushing_systemwide_wq(void)
  6827. {
  6828. pr_warn("WARNING: Flushing system-wide workqueues will be prohibited in near future.\n");
  6829. dump_stack();
  6830. }
  6831. EXPORT_SYMBOL(__warn_flushing_systemwide_wq);
  6832. static int __init workqueue_unbound_cpus_setup(char *str)
  6833. {
  6834. if (cpulist_parse(str, &wq_cmdline_cpumask) < 0) {
  6835. cpumask_clear(&wq_cmdline_cpumask);
  6836. pr_warn("workqueue.unbound_cpus: incorrect CPU range, using default\n");
  6837. }
  6838. return 1;
  6839. }
  6840. __setup("workqueue.unbound_cpus=", workqueue_unbound_cpus_setup);