workqueue.c 140 KB

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