workqueue.c 157 KB

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