workqueue.c 158 KB

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