workqueue.c 122 KB

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