workqueue.c 156 KB

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