workqueue.c 152 KB

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