workqueue.c 122 KB

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