workqueue.c 123 KB

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