workqueue.c 156 KB

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