thread.c 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848
  1. /*
  2. * Copyright (c) 2012-2018 Richard Braun.
  3. *
  4. * This program is free software: you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation, either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. *
  17. *
  18. * The scheduling algorithm implemented by this module, named Distributed
  19. * Group Ratio Round-Robin (DGR3), is based on the following papers :
  20. * - "Group Ratio Round-Robin: O(1) Proportional Share Scheduling for
  21. * Uniprocessor and Multiprocessor Systems" by Bogdan Caprita, Wong Chun
  22. * Chan, Jason Nieh, Clifford Stein and Haoqiang Zheng.
  23. * - "Efficient and Scalable Multiprocessor Fair Scheduling Using Distributed
  24. * Weighted Round-Robin" by Tong li, Dan Baumberger and Scott Hahn.
  25. *
  26. * Note that the Group Ratio Round-Robin (GR3) paper offers a multiprocessor
  27. * extension, but based on a single global queue, which strongly limits its
  28. * scalability on systems with many processors. That extension isn't used in
  29. * this implementation.
  30. *
  31. * The basic idea is to use GR3 for processor-local scheduling, and Distributed
  32. * Weighted Round-Robin (DWRR) for inter-processor load balancing. These
  33. * algorithms were chosen for several reasons. To begin with, they provide
  34. * fair scheduling, a very desirable property for a modern scheduler. Next,
  35. * being based on round-robin, their algorithmic complexity is very low (GR3
  36. * has O(1) scheduling complexity, and O(g) complexity on thread addition
  37. * or removal, g being the number of groups, with one group per priority, a
  38. * low number in practice). Finally, they're very simple to implement, making
  39. * them easy to adjust and maintain.
  40. *
  41. * Both algorithms are actually slightly modified for efficiency. First, this
  42. * version of GR3 is simplified by mapping exactly one group to one priority,
  43. * and in turn, one weight. This is possible because priorities are intended
  44. * to match Unix nice values, and systems commonly provide a constant, small
  45. * set of nice values. This removes the need for accounting deficit. Next,
  46. * round tracking is used to improve the handling of dynamic events : work
  47. * scaling is performed only on thread addition, and not when a thread that
  48. * was removed is added again during the same round. In addition, since GR3
  49. * is itself a round-robin algorithm, it already provides the feature required
  50. * from local scheduling by DWRR, namely round slicing. Consequently, DWRR
  51. * doesn't sit "on top" of GR3, but is actually merged with it. The result is
  52. * an algorithm that shares the same data for both local scheduling and load
  53. * balancing.
  54. *
  55. * A few terms are used by both papers with slightly different meanings. Here
  56. * are the definitions used in this implementation :
  57. * - The time unit is the system timer period (1 / tick frequency)
  58. * - Work is the amount of execution time units consumed
  59. * - Weight is the amount of execution time units allocated
  60. * - A round is the shortest period during which all threads in a run queue
  61. * consume their allocated time (i.e. their work reaches their weight)
  62. *
  63. * TODO Sub-tick accounting.
  64. *
  65. * TODO Take into account the underlying CPU topology (and adjust load
  66. * balancing to access the global highest round less frequently on large
  67. * processor groups, perhaps by applying the load balancing algorithm in a
  68. * bottom-up fashion with one highest round per processor group).
  69. *
  70. * TODO For now, interactivity can not be experimented. The current strategy
  71. * is to always add threads in front of their group queue and track rounds
  72. * so that they don't get more time than they should. A direct consequence
  73. * is that continually spawning threads at short intervals is likely to cause
  74. * starvation. This could be fixed by adding newly created threads at the back
  75. * of their group queue. For now, don't overengineer, and wait until all this
  76. * can actually be tested.
  77. *
  78. * TODO Review weight computation (it may be more appropriate to determine
  79. * weights in a smoother way than a raw scaling).
  80. */
  81. #include <assert.h>
  82. #include <errno.h>
  83. #include <stdalign.h>
  84. #include <stdbool.h>
  85. #include <stddef.h>
  86. #include <stdint.h>
  87. #include <stdio.h>
  88. #include <stdnoreturn.h>
  89. #include <string.h>
  90. #include <kern/atomic.h>
  91. #include <kern/capability.h>
  92. #include <kern/clock.h>
  93. #include <kern/cpumap.h>
  94. #include <kern/init.h>
  95. #include <kern/kmem.h>
  96. #include <kern/list.h>
  97. #include <kern/macros.h>
  98. #include <kern/panic.h>
  99. #include <kern/percpu.h>
  100. #include <kern/perfmon.h>
  101. #include <kern/rcu.h>
  102. #include <kern/shell.h>
  103. #include <kern/sleepq.h>
  104. #include <kern/spinlock.h>
  105. #include <kern/syscnt.h>
  106. #include <kern/task.h>
  107. #include <kern/thread.h>
  108. #include <kern/timer.h>
  109. #include <kern/turnstile.h>
  110. #include <kern/types.h>
  111. #include <kern/user.h>
  112. #include <kern/work.h>
  113. #include <machine/cpu.h>
  114. #include <machine/page.h>
  115. #include <machine/pmap.h>
  116. #include <machine/tcb.h>
  117. #include <vm/kmem.h>
  118. #include <vm/map.h>
  119. /*
  120. * Preemption level of a suspended thread.
  121. *
  122. * The expected interrupt, preemption and run queue lock state when
  123. * dispatching a thread is :
  124. * - interrupts disabled
  125. * - preemption disabled
  126. * - run queue locked
  127. *
  128. * Locking the run queue increases the preemption level once more,
  129. * making its value 2.
  130. */
  131. #define THREAD_SUSPEND_PREEMPT_LEVEL 2
  132. /*
  133. * Scheduling classes.
  134. *
  135. * Classes are sorted by order of priority (lower indexes first). The same
  136. * class can apply to several policies.
  137. *
  138. * The idle class is reserved for the per-CPU idle threads.
  139. */
  140. #define THREAD_SCHED_CLASS_RT 0
  141. #define THREAD_SCHED_CLASS_FS 1
  142. #define THREAD_SCHED_CLASS_IDLE 2
  143. #define THREAD_NR_SCHED_CLASSES 3
  144. /*
  145. * Global priority bases for each scheduling class.
  146. *
  147. * Global priorities are only used to determine which of two threads
  148. * has the higher priority, and should only matter for priority
  149. * inheritance.
  150. *
  151. * In the current configuration, all fair-scheduling threads have the
  152. * same global priority.
  153. */
  154. #define THREAD_SCHED_GLOBAL_PRIO_RT 2
  155. #define THREAD_SCHED_GLOBAL_PRIO_FS 1
  156. #define THREAD_SCHED_GLOBAL_PRIO_IDLE 0
  157. // Default time slice for real-time round-robin scheduling.
  158. #define THREAD_DEFAULT_RR_TIME_SLICE (CLOCK_FREQ / 10)
  159. /*
  160. * Maximum number of threads which can be pulled from a remote run queue
  161. * while interrupts are disabled.
  162. */
  163. #define THREAD_MAX_MIGRATIONS 16
  164. // Delay (in ticks) between two balance attempts when a run queue is idle.
  165. #define THREAD_IDLE_BALANCE_TICKS (CLOCK_FREQ / 2)
  166. // Run queue properties for real-time threads.
  167. struct thread_rt_runq
  168. {
  169. uint32_t bitmap;
  170. struct list threads[THREAD_SCHED_RT_PRIO_MAX + 1];
  171. };
  172. /*
  173. * Initial value of the highest round.
  174. *
  175. * Set to a high value to make sure overflows are correctly handled.
  176. */
  177. #define THREAD_FS_INITIAL_ROUND ((unsigned long)-10)
  178. // Round slice base unit for fair-scheduling threads.
  179. #define THREAD_FS_ROUND_SLICE_BASE (CLOCK_FREQ / 10)
  180. // Group of threads sharing the same weight.
  181. struct thread_fs_group
  182. {
  183. struct list node;
  184. struct list threads;
  185. uint32_t weight;
  186. uint32_t work;
  187. };
  188. /*
  189. * Run queue properties for fair-scheduling threads.
  190. *
  191. * The current group pointer has a valid address only when the run queue isn't
  192. * empty.
  193. */
  194. struct thread_fs_runq
  195. {
  196. struct thread_fs_group group_array[THREAD_SCHED_FS_PRIO_MAX + 1];
  197. struct list groups;
  198. struct list threads;
  199. struct thread_fs_group *current;
  200. uint32_t nr_threads;
  201. uint32_t weight;
  202. uint32_t work;
  203. };
  204. /*
  205. * Per processor run queue.
  206. *
  207. * Locking multiple run queues is done in the ascending order of their CPU
  208. * identifier. Interrupts must be disabled whenever locking a run queue, even
  209. * a remote one, otherwise an interrupt (which invokes the scheduler on its
  210. * return path) may violate the locking order.
  211. */
  212. struct thread_runq
  213. {
  214. __cacheline_aligned struct spinlock lock;
  215. uint32_t cpu;
  216. uint32_t nr_threads;
  217. struct thread *current;
  218. // Real-time related members.
  219. struct thread_rt_runq rt_runq;
  220. /*
  221. * Fair-scheduling related members.
  222. *
  223. * The current round is set when the active run queue becomes non-empty.
  224. * It's not reset when both run queues become empty. As a result, the
  225. * current round has a meaningful value only when at least one thread is
  226. * present, i.e. the global weight isn't zero.
  227. */
  228. size_t fs_round;
  229. uint32_t fs_weight;
  230. struct thread_fs_runq fs_runqs[2];
  231. struct thread_fs_runq *fs_runq_active;
  232. struct thread_fs_runq *fs_runq_expired;
  233. struct thread *balancer;
  234. struct thread *idler;
  235. // Ticks before the next balancing attempt when a run queue is idle.
  236. uint32_t idle_balance_ticks;
  237. struct syscnt sc_schedule_intrs;
  238. struct syscnt sc_boosts;
  239. };
  240. // Operations of a scheduling class.
  241. struct thread_sched_ops
  242. {
  243. struct thread_runq* (*select_runq) (struct thread *);
  244. void (*add) (struct thread_runq *, struct thread *);
  245. void (*remove) (struct thread_runq *, struct thread *);
  246. void (*put_prev) (struct thread_runq *, struct thread *);
  247. struct thread* (*get_next) (struct thread_runq *);
  248. void (*reset_priority) (struct thread *, uint16_t);
  249. void (*update_priority) (struct thread *, uint16_t);
  250. uint32_t (*get_global_priority) (uint16_t);
  251. void (*set_next) (struct thread_runq *, struct thread *);
  252. void (*tick) (struct thread_runq *, struct thread *);
  253. };
  254. static struct thread_runq thread_runq __percpu;
  255. /*
  256. * Statically allocated fake threads that provide thread context to processors
  257. * during bootstrap.
  258. */
  259. static struct thread thread_booters[CONFIG_MAX_CPUS] __initdata;
  260. static struct kmem_cache thread_cache;
  261. #ifndef CONFIG_THREAD_STACK_GUARD
  262. static struct kmem_cache thread_stack_cache;
  263. #endif
  264. static const uint8_t thread_policy_table[THREAD_NR_SCHED_POLICIES] =
  265. {
  266. [THREAD_SCHED_POLICY_FIFO] = THREAD_SCHED_CLASS_RT,
  267. [THREAD_SCHED_POLICY_RR] = THREAD_SCHED_CLASS_RT,
  268. [THREAD_SCHED_POLICY_FS] = THREAD_SCHED_CLASS_FS,
  269. [THREAD_SCHED_POLICY_IDLE] = THREAD_SCHED_CLASS_IDLE,
  270. };
  271. static const struct thread_sched_ops thread_sched_ops[THREAD_NR_SCHED_CLASSES];
  272. // Map of run queues for which a processor is running.
  273. static struct cpumap thread_active_runqs;
  274. /*
  275. * Map of idle run queues.
  276. *
  277. * Access to this map isn't synchronized. It is merely used as a fast hint
  278. * to find run queues that are likely to be idle.
  279. */
  280. static struct cpumap thread_idle_runqs;
  281. /*
  282. * System-wide value of the current highest round.
  283. *
  284. * This global variable is accessed without any synchronization. Its value
  285. * being slightly inaccurate doesn't harm the fairness properties of the
  286. * scheduling and load balancing algorithms.
  287. *
  288. * There can be moderate bouncing on this word so give it its own cache line.
  289. */
  290. static struct
  291. {
  292. __cacheline_aligned volatile size_t value;
  293. } thread_fs_highest_round_struct;
  294. #define thread_fs_highest_round (thread_fs_highest_round_struct.value)
  295. /*
  296. * Number of processors which have requested the scheduler to run.
  297. *
  298. * This value is used to implement a global barrier across the entire
  299. * system at boot time, so that inter-processor requests may not be
  300. * lost in case a processor is slower to initialize.
  301. */
  302. static uint32_t thread_nr_boot_cpus __initdata;
  303. struct thread_zombie
  304. {
  305. struct work work;
  306. struct thread *thread;
  307. };
  308. struct thread_runq_guard_t
  309. {
  310. struct thread_runq *runq;
  311. cpu_flags_t flags;
  312. bool preempt_disabled;
  313. };
  314. static uint8_t
  315. thread_policy_to_class (uint8_t policy)
  316. {
  317. assert (policy < ARRAY_SIZE (thread_policy_table));
  318. return (thread_policy_table[policy]);
  319. }
  320. static void
  321. thread_set_wchan (struct thread *thread, const void *wchan_addr,
  322. const char *wchan_desc)
  323. {
  324. assert (wchan_addr && wchan_desc);
  325. thread->wchan_addr = wchan_addr;
  326. thread->wchan_desc = wchan_desc;
  327. }
  328. static void
  329. thread_clear_wchan (struct thread *thread)
  330. {
  331. thread->wchan_addr = NULL;
  332. thread->wchan_desc = NULL;
  333. }
  334. static const struct thread_sched_ops*
  335. thread_get_sched_ops (uint8_t sched_class)
  336. {
  337. assert (sched_class < ARRAY_SIZE (thread_sched_ops));
  338. return (&thread_sched_ops[sched_class]);
  339. }
  340. static const struct thread_sched_ops*
  341. thread_get_user_sched_ops (const struct thread *thread)
  342. {
  343. return (thread_get_sched_ops (thread_user_sched_class (thread)));
  344. }
  345. static const struct thread_sched_ops*
  346. thread_get_real_sched_ops (const struct thread *thread)
  347. {
  348. return (thread_get_sched_ops (thread_real_sched_class (thread)));
  349. }
  350. static void __init
  351. thread_runq_init_rt (struct thread_runq *runq)
  352. {
  353. runq->rt_runq.bitmap = 0;
  354. for (size_t i = 0; i < ARRAY_SIZE (runq->rt_runq.threads); i++)
  355. list_init (&runq->rt_runq.threads[i]);
  356. }
  357. static void __init
  358. thread_fs_group_init (struct thread_fs_group *group)
  359. {
  360. list_init (&group->threads);
  361. group->weight = 0;
  362. group->work = 0;
  363. }
  364. static void __init
  365. thread_fs_runq_init (struct thread_fs_runq *fs_runq)
  366. {
  367. for (size_t i = 0; i < ARRAY_SIZE (fs_runq->group_array); i++)
  368. thread_fs_group_init (&fs_runq->group_array[i]);
  369. list_init (&fs_runq->groups);
  370. list_init (&fs_runq->threads);
  371. fs_runq->nr_threads = 0;
  372. fs_runq->weight = 0;
  373. fs_runq->work = 0;
  374. }
  375. static void __init
  376. thread_runq_init_fs (struct thread_runq *runq)
  377. {
  378. runq->fs_weight = 0;
  379. runq->fs_runq_active = &runq->fs_runqs[0];
  380. runq->fs_runq_expired = &runq->fs_runqs[1];
  381. thread_fs_runq_init (runq->fs_runq_active);
  382. thread_fs_runq_init (runq->fs_runq_expired);
  383. }
  384. static void __init
  385. thread_runq_init (struct thread_runq *runq, uint32_t cpu,
  386. struct thread *booter)
  387. {
  388. char name[SYSCNT_NAME_SIZE];
  389. spinlock_init (&runq->lock);
  390. runq->cpu = cpu;
  391. runq->nr_threads = 0;
  392. runq->current = booter;
  393. thread_runq_init_rt (runq);
  394. thread_runq_init_fs (runq);
  395. runq->balancer = NULL;
  396. runq->idler = NULL;
  397. runq->idle_balance_ticks = (uint32_t)-1;
  398. snprintf (name, sizeof (name), "thread_schedule_intrs/%u", cpu);
  399. syscnt_register (&runq->sc_schedule_intrs, name);
  400. snprintf (name, sizeof (name), "thread_boosts/%u", cpu);
  401. syscnt_register (&runq->sc_boosts, name);
  402. }
  403. static inline struct thread_runq*
  404. thread_runq_local (void)
  405. {
  406. assert (!thread_preempt_enabled () || thread_pinned ());
  407. return (cpu_local_ptr (thread_runq));
  408. }
  409. static inline uint32_t
  410. thread_runq_cpu (struct thread_runq *runq)
  411. {
  412. return (runq->cpu);
  413. }
  414. static void
  415. thread_runq_add (struct thread_runq *runq, struct thread *thread)
  416. {
  417. assert (!cpu_intr_enabled ());
  418. assert (spinlock_locked (&runq->lock));
  419. assert (!thread->in_runq);
  420. const _Auto ops = thread_get_real_sched_ops (thread);
  421. ops->add (runq, thread);
  422. if (runq->nr_threads == 0)
  423. cpumap_clear_atomic (&thread_idle_runqs, thread_runq_cpu (runq));
  424. ++runq->nr_threads;
  425. if (thread_real_sched_class (thread) <
  426. thread_real_sched_class (runq->current))
  427. thread_set_flag (runq->current, THREAD_YIELD);
  428. atomic_store_rlx (&thread->runq, runq);
  429. thread->in_runq = true;
  430. }
  431. static void
  432. thread_runq_remove (struct thread_runq *runq, struct thread *thread)
  433. {
  434. assert (!cpu_intr_enabled ());
  435. assert (spinlock_locked (&runq->lock));
  436. assert (thread->in_runq);
  437. if (--runq->nr_threads == 0)
  438. cpumap_set_atomic (&thread_idle_runqs, thread_runq_cpu (runq));
  439. const _Auto ops = thread_get_real_sched_ops (thread);
  440. ops->remove (runq, thread);
  441. thread->in_runq = false;
  442. }
  443. static void
  444. thread_runq_put_prev (struct thread_runq *runq, struct thread *thread)
  445. {
  446. assert (!cpu_intr_enabled ());
  447. assert (spinlock_locked (&runq->lock));
  448. const _Auto ops = thread_get_real_sched_ops (thread);
  449. if (ops->put_prev)
  450. ops->put_prev (runq, thread);
  451. }
  452. static struct thread*
  453. thread_runq_get_next (struct thread_runq *runq)
  454. {
  455. assert (!cpu_intr_enabled ());
  456. assert (spinlock_locked (&runq->lock));
  457. for (size_t i = 0; i < ARRAY_SIZE (thread_sched_ops); i++)
  458. {
  459. struct thread *thread = thread_sched_ops[i].get_next (runq);
  460. if (thread)
  461. {
  462. atomic_store_rlx (&runq->current, thread);
  463. return (thread);
  464. }
  465. }
  466. // The idle class should never be empty.
  467. panic ("thread: unable to find next thread");
  468. }
  469. static void
  470. thread_runq_set_next (struct thread_runq *runq, struct thread *thread)
  471. {
  472. const _Auto ops = thread_get_real_sched_ops (thread);
  473. if (ops->set_next)
  474. ops->set_next (runq, thread);
  475. atomic_store_rlx (&runq->current, thread);
  476. }
  477. static void
  478. thread_runq_wakeup (struct thread_runq *runq, struct thread *thread)
  479. {
  480. assert (!cpu_intr_enabled ());
  481. assert (spinlock_locked (&runq->lock));
  482. assert (thread->state == THREAD_RUNNING);
  483. thread_runq_add (runq, thread);
  484. if (runq != thread_runq_local () &&
  485. thread_test_flag (runq->current, THREAD_YIELD))
  486. cpu_send_thread_schedule (thread_runq_cpu (runq));
  487. }
  488. static void
  489. thread_runq_wakeup_balancer (struct thread_runq *runq)
  490. {
  491. if (runq->balancer->state == THREAD_RUNNING)
  492. return;
  493. thread_clear_wchan (runq->balancer);
  494. atomic_store_rlx (&runq->balancer->state, THREAD_RUNNING);
  495. thread_runq_wakeup (runq, runq->balancer);
  496. }
  497. static void
  498. thread_runq_schedule_load (struct thread *thread)
  499. {
  500. pmap_load (thread->xtask->map->pmap);
  501. #ifdef CONFIG_PERFMON
  502. perfmon_td_load (thread_get_perfmon_td (thread));
  503. #endif
  504. }
  505. static void
  506. thread_runq_schedule_unload (struct thread *thread __unused)
  507. {
  508. #ifdef CONFIG_PERFMON
  509. perfmon_td_unload (thread_get_perfmon_td (thread));
  510. #endif
  511. }
  512. static struct thread_runq*
  513. thread_lock_runq (struct thread *thread, cpu_flags_t *flags)
  514. {
  515. while (1)
  516. {
  517. _Auto runq = atomic_load_rlx (&thread->runq);
  518. spinlock_lock_intr_save (&runq->lock, flags);
  519. if (likely (runq == atomic_load_rlx (&thread->runq)))
  520. return (runq);
  521. spinlock_unlock_intr_restore (&runq->lock, *flags);
  522. }
  523. }
  524. static void
  525. thread_unlock_runq (struct thread_runq *runq, cpu_flags_t flags)
  526. {
  527. spinlock_unlock_intr_restore (&runq->lock, flags);
  528. }
  529. static struct thread_runq_guard_t
  530. thread_runq_guard_make (struct thread *thread, bool disable_preempt)
  531. {
  532. struct thread_runq_guard_t ret;
  533. ret.preempt_disabled = disable_preempt;
  534. if (ret.preempt_disabled)
  535. thread_preempt_disable ();
  536. ret.runq = thread_lock_runq (thread, &ret.flags);
  537. return (ret);
  538. }
  539. static void
  540. thread_runq_guard_fini (struct thread_runq_guard_t *guard)
  541. {
  542. thread_unlock_runq (guard->runq, guard->flags);
  543. if (guard->preempt_disabled)
  544. thread_preempt_enable ();
  545. }
  546. #define thread_runq_guard \
  547. thread_runq_guard_t CLEANUP (thread_runq_guard_fini) __unused
  548. static void
  549. thread_pmap_context_switch (struct thread_pmap_data *prev,
  550. struct thread_pmap_data *next)
  551. {
  552. for (size_t i = 0; i < THREAD_NR_PMAP_DATA; ++i)
  553. {
  554. pmap_ipc_pte_save (prev + i, &prev[i].prev);
  555. pmap_ipc_pte_load (next + i, next[i].prev);
  556. }
  557. }
  558. static struct thread_runq*
  559. thread_runq_schedule (struct thread_runq *runq)
  560. {
  561. struct thread *prev = thread_self ();
  562. assert (prev->cur_lpad ||
  563. (__builtin_frame_address (0) >= prev->stack &&
  564. __builtin_frame_address (0) < prev->stack + TCB_STACK_SIZE));
  565. assert (prev->preempt_level == THREAD_SUSPEND_PREEMPT_LEVEL);
  566. assert (!cpu_intr_enabled ());
  567. assert (spinlock_locked (&runq->lock));
  568. thread_clear_flag (prev, THREAD_YIELD);
  569. thread_runq_put_prev (runq, prev);
  570. if (prev->suspend)
  571. {
  572. prev->state = THREAD_SUSPENDED;
  573. prev->suspend = false;
  574. }
  575. if (prev->state != THREAD_RUNNING)
  576. {
  577. thread_runq_remove (runq, prev);
  578. if (!runq->nr_threads && prev != runq->balancer)
  579. thread_runq_wakeup_balancer (runq);
  580. }
  581. struct thread *next = thread_runq_get_next (runq);
  582. assert (next != runq->idler || !runq->nr_threads);
  583. assert (next->preempt_level == THREAD_SUSPEND_PREEMPT_LEVEL);
  584. if (likely (prev != next))
  585. {
  586. thread_runq_schedule_unload (prev);
  587. rcu_report_context_switch (thread_rcu_reader (prev));
  588. thread_pmap_context_switch (prev->pmap_data, next->pmap_data);
  589. spinlock_transfer_owner (&runq->lock, next);
  590. /*
  591. * This is where the true context switch occurs. The next thread must
  592. * unlock the run queue and reenable preemption. Note that unlocking
  593. * and locking the run queue again is equivalent to a full memory
  594. * barrier.
  595. */
  596. tcb_switch (&prev->tcb, &next->tcb);
  597. /*
  598. * The thread is dispatched on a processor once again.
  599. *
  600. * Keep in mind the system state may have changed a lot since this
  601. * function was called. In particular :
  602. * - The next thread may have been destroyed, and must not be
  603. * referenced any more.
  604. * - The current thread may have been migrated to another processor.
  605. */
  606. barrier ();
  607. thread_runq_schedule_load (prev);
  608. runq = thread_runq_local ();
  609. }
  610. assert (prev->preempt_level == THREAD_SUSPEND_PREEMPT_LEVEL);
  611. assert (!cpu_intr_enabled ());
  612. assert (spinlock_locked (&runq->lock));
  613. return (runq);
  614. }
  615. static void
  616. thread_runq_double_lock (struct thread_runq *a, struct thread_runq *b)
  617. {
  618. assert (!cpu_intr_enabled ());
  619. assert (!thread_preempt_enabled ());
  620. assert (a != b);
  621. if (a->cpu < b->cpu)
  622. {
  623. spinlock_lock (&a->lock);
  624. spinlock_lock (&b->lock);
  625. }
  626. else
  627. {
  628. spinlock_lock (&b->lock);
  629. spinlock_lock (&a->lock);
  630. }
  631. }
  632. static struct thread_runq*
  633. thread_sched_rt_select_runq (struct thread *thread)
  634. {
  635. /*
  636. * Real-time tasks are commonly configured to run on one specific
  637. * processor only.
  638. */
  639. int i = cpumap_find_first (&thread->cpumap);
  640. assert (i >= 0);
  641. assert (cpumap_test (&thread_active_runqs, i));
  642. struct thread_runq *runq = percpu_ptr (thread_runq, i);
  643. spinlock_lock (&runq->lock);
  644. return (runq);
  645. }
  646. static void
  647. thread_sched_rt_add (struct thread_runq *runq, struct thread *thread)
  648. {
  649. struct thread_rt_runq *rt_runq = &runq->rt_runq;
  650. struct list *threads = &rt_runq->threads[thread_real_priority (thread)];
  651. list_insert_tail (threads, &thread->rt_data.node);
  652. if (list_singular (threads))
  653. rt_runq->bitmap |= (1ULL << thread_real_priority (thread));
  654. if (thread_real_sched_class (thread) ==
  655. thread_real_sched_class (runq->current) &&
  656. thread_real_priority (thread) > thread_real_priority (runq->current))
  657. thread_set_flag (runq->current, THREAD_YIELD);
  658. }
  659. static void
  660. thread_sched_rt_remove (struct thread_runq *runq, struct thread *thread)
  661. {
  662. struct thread_rt_runq *rt_runq = &runq->rt_runq;
  663. assert (thread_real_priority (thread) < ARRAY_SIZE (rt_runq->threads));
  664. struct list *threads = &rt_runq->threads[thread_real_priority (thread)];
  665. list_remove (&thread->rt_data.node);
  666. if (list_empty (threads))
  667. rt_runq->bitmap &= ~(1ULL << thread_real_priority (thread));
  668. }
  669. static void
  670. thread_sched_rt_put_prev (struct thread_runq *runq, struct thread *thread)
  671. {
  672. thread_sched_rt_add (runq, thread);
  673. }
  674. static struct thread*
  675. thread_sched_rt_get_next (struct thread_runq *runq)
  676. {
  677. struct thread_rt_runq *rt_runq = &runq->rt_runq;
  678. if (!rt_runq->bitmap)
  679. return (NULL);
  680. uint32_t priority = THREAD_SCHED_RT_PRIO_MAX -
  681. __builtin_clz (rt_runq->bitmap);
  682. assert (priority < ARRAY_SIZE (rt_runq->threads));
  683. struct list *threads = &rt_runq->threads[priority];
  684. assert (!list_empty (threads));
  685. _Auto thread = list_first_entry (threads, struct thread, rt_data.node);
  686. thread_sched_rt_remove (runq, thread);
  687. return (thread);
  688. }
  689. static void
  690. thread_sched_rt_reset_priority (struct thread *thread, uint16_t priority)
  691. {
  692. assert (priority <= THREAD_SCHED_RT_PRIO_MAX);
  693. thread->rt_data.time_slice = THREAD_DEFAULT_RR_TIME_SLICE;
  694. }
  695. static uint32_t
  696. thread_sched_rt_get_global_priority (uint16_t priority)
  697. {
  698. return (THREAD_SCHED_GLOBAL_PRIO_RT + priority);
  699. }
  700. static void
  701. thread_sched_rt_set_next (struct thread_runq *runq, struct thread *thread)
  702. {
  703. thread_sched_rt_remove (runq, thread);
  704. }
  705. static void
  706. thread_sched_rt_tick (struct thread_runq *runq __unused, struct thread *thread)
  707. {
  708. if (thread_real_sched_policy (thread) != THREAD_SCHED_POLICY_RR ||
  709. --thread->rt_data.time_slice > 0)
  710. return;
  711. thread->rt_data.time_slice = THREAD_DEFAULT_RR_TIME_SLICE;
  712. thread_set_flag (thread, THREAD_YIELD);
  713. }
  714. static inline uint16_t
  715. thread_sched_fs_prio2weight (uint16_t priority)
  716. {
  717. return ((priority + 1) * THREAD_FS_ROUND_SLICE_BASE);
  718. }
  719. static struct thread_runq*
  720. thread_sched_fs_select_runq (struct thread *thread)
  721. {
  722. struct thread_runq *runq;
  723. cpumap_for_each (&thread_idle_runqs, i)
  724. {
  725. if (!cpumap_test (&thread->cpumap, i))
  726. continue;
  727. runq = percpu_ptr (thread_runq, i);
  728. spinlock_lock (&runq->lock);
  729. // The run queue really is idle, return it.
  730. if (runq->current == runq->idler)
  731. return (runq);
  732. spinlock_unlock (&runq->lock);
  733. }
  734. runq = NULL;
  735. cpumap_for_each (&thread_active_runqs, i)
  736. {
  737. if (!cpumap_test (&thread->cpumap, i))
  738. continue;
  739. _Auto tmp = percpu_ptr (thread_runq, i);
  740. spinlock_lock (&tmp->lock);
  741. if (! runq)
  742. {
  743. runq = tmp;
  744. continue;
  745. }
  746. // A run queue may have become idle.
  747. if (tmp->current == tmp->idler)
  748. {
  749. spinlock_unlock (&runq->lock);
  750. return (tmp);
  751. }
  752. /*
  753. * The run queue isn't idle, but there are no fair-scheduling thread,
  754. * which means there are real-time threads.
  755. */
  756. if (tmp->fs_weight == 0)
  757. {
  758. spinlock_unlock (&tmp->lock);
  759. continue;
  760. }
  761. ssize_t delta = (ssize_t)(tmp->fs_round - runq->fs_round);
  762. // Look for the least loaded of the run queues in the highest round.
  763. if (delta > 0 ||
  764. (!delta && tmp->fs_weight < runq->fs_weight))
  765. {
  766. spinlock_unlock (&runq->lock);
  767. runq = tmp;
  768. continue;
  769. }
  770. spinlock_unlock (&tmp->lock);
  771. }
  772. assert (runq);
  773. return (runq);
  774. }
  775. static uint32_t
  776. thread_sched_fs_enqueue_scale (uint32_t work, uint32_t old_weight,
  777. uint32_t new_weight)
  778. {
  779. assert (old_weight);
  780. #ifndef __LP64__
  781. if (likely (work < 0x10000 && new_weight < 0x10000))
  782. return ((work * new_weight) / old_weight);
  783. #endif
  784. return ((uint32_t)(((uint64_t)work * new_weight) / old_weight));
  785. }
  786. static void
  787. thread_sched_fs_enqueue (struct thread_fs_runq *fs_runq, size_t round,
  788. struct thread *thread)
  789. {
  790. assert (!thread->fs_data.fs_runq);
  791. assert (thread->fs_data.work <= thread->fs_data.weight);
  792. _Auto group = &fs_runq->group_array[thread_real_priority (thread)];
  793. uint32_t group_weight = group->weight + thread->fs_data.weight,
  794. total_weight = fs_runq->weight + thread->fs_data.weight;
  795. struct list *node = group->weight ?
  796. list_prev (&group->node) : list_last (&fs_runq->groups);
  797. struct list *init_node = node;
  798. while (!list_end (&fs_runq->groups, node))
  799. {
  800. _Auto tmp = list_entry (node, struct thread_fs_group, node);
  801. if (tmp->weight >= group_weight)
  802. break;
  803. node = list_prev (node);
  804. }
  805. if (!group->weight)
  806. list_insert_after (&group->node, node);
  807. else if (node != init_node)
  808. {
  809. list_remove (&group->node);
  810. list_insert_after (&group->node, node);
  811. }
  812. /*
  813. * XXX Unfairness can occur if the run queue round wraps around and the
  814. * thread is "lucky" enough to have the same round value. This should be
  815. * rare and harmless otherwise.
  816. */
  817. if (thread->fs_data.round == round)
  818. {
  819. fs_runq->work += thread->fs_data.work;
  820. group->work += thread->fs_data.work;
  821. }
  822. else
  823. {
  824. uint32_t group_work, thread_work;
  825. if (!fs_runq->weight)
  826. thread_work = 0;
  827. else
  828. {
  829. group_work = group->weight == 0 ?
  830. thread_sched_fs_enqueue_scale (fs_runq->work,
  831. fs_runq->weight,
  832. thread->fs_data.weight) :
  833. thread_sched_fs_enqueue_scale (group->work,
  834. group->weight,
  835. group_weight);
  836. thread_work = group_work - group->work;
  837. fs_runq->work += thread_work;
  838. group->work = group_work;
  839. }
  840. thread->fs_data.round = round;
  841. thread->fs_data.work = thread_work;
  842. }
  843. ++fs_runq->nr_threads;
  844. fs_runq->weight = total_weight;
  845. group->weight = group_weight;
  846. // Insert at the front of the group to improve interactivity.
  847. list_insert_head (&group->threads, &thread->fs_data.group_node);
  848. list_insert_tail (&fs_runq->threads, &thread->fs_data.runq_node);
  849. thread->fs_data.fs_runq = fs_runq;
  850. }
  851. static void
  852. thread_sched_fs_restart (struct thread_runq *runq)
  853. {
  854. _Auto fs_runq = runq->fs_runq_active;
  855. struct list *node = list_first (&fs_runq->groups);
  856. assert (node);
  857. fs_runq->current = list_entry (node, struct thread_fs_group, node);
  858. if (thread_real_sched_class (runq->current) == THREAD_SCHED_CLASS_FS)
  859. thread_set_flag (runq->current, THREAD_YIELD);
  860. }
  861. static void
  862. thread_sched_fs_add (struct thread_runq *runq, struct thread *thread)
  863. {
  864. if (!runq->fs_weight)
  865. runq->fs_round = thread_fs_highest_round;
  866. uint32_t total_weight = runq->fs_weight + thread->fs_data.weight;
  867. // TODO Limit the maximum number of threads to prevent this situation.
  868. if (total_weight < runq->fs_weight)
  869. panic ("thread: weight overflow");
  870. runq->fs_weight = total_weight;
  871. thread_sched_fs_enqueue (runq->fs_runq_active, runq->fs_round, thread);
  872. thread_sched_fs_restart (runq);
  873. }
  874. static void
  875. thread_sched_fs_dequeue (struct thread *thread)
  876. {
  877. assert (thread->fs_data.fs_runq);
  878. _Auto fs_runq = thread->fs_data.fs_runq;
  879. _Auto group = &fs_runq->group_array[thread_real_priority (thread)];
  880. thread->fs_data.fs_runq = NULL;
  881. list_remove (&thread->fs_data.runq_node);
  882. list_remove (&thread->fs_data.group_node);
  883. fs_runq->work -= thread->fs_data.work;
  884. group->work -= thread->fs_data.work;
  885. fs_runq->weight -= thread->fs_data.weight;
  886. group->weight -= thread->fs_data.weight;
  887. --fs_runq->nr_threads;
  888. if (!group->weight)
  889. list_remove (&group->node);
  890. else
  891. {
  892. struct list *node = list_next (&group->node),
  893. *init_node = node;
  894. while (!list_end (&fs_runq->groups, node))
  895. {
  896. _Auto tmp = list_entry (node, struct thread_fs_group, node);
  897. if (tmp->weight <= group->weight)
  898. break;
  899. node = list_next (node);
  900. }
  901. if (node != init_node)
  902. {
  903. list_remove (&group->node);
  904. list_insert_before (&group->node, node);
  905. }
  906. }
  907. }
  908. static void
  909. thread_sched_fs_remove (struct thread_runq *runq, struct thread *thread)
  910. {
  911. runq->fs_weight -= thread->fs_data.weight;
  912. _Auto fs_runq = thread->fs_data.fs_runq;
  913. thread_sched_fs_dequeue (thread);
  914. if (fs_runq != runq->fs_runq_active)
  915. ;
  916. else if (!fs_runq->nr_threads)
  917. thread_runq_wakeup_balancer (runq);
  918. else
  919. thread_sched_fs_restart (runq);
  920. }
  921. static void
  922. thread_sched_fs_deactivate (struct thread_runq *runq, struct thread *thread)
  923. {
  924. assert (thread->fs_data.fs_runq == runq->fs_runq_active);
  925. assert (thread->fs_data.round == runq->fs_round);
  926. thread_sched_fs_dequeue (thread);
  927. ++thread->fs_data.round;
  928. thread->fs_data.work -= thread->fs_data.weight;
  929. thread_sched_fs_enqueue (runq->fs_runq_expired, runq->fs_round + 1, thread);
  930. if (!runq->fs_runq_active->nr_threads)
  931. thread_runq_wakeup_balancer (runq);
  932. }
  933. static void
  934. thread_sched_fs_put_prev (struct thread_runq *runq, struct thread *thread)
  935. {
  936. _Auto fs_runq = runq->fs_runq_active;
  937. assert (thread_real_priority (thread) < ARRAY_SIZE (fs_runq->group_array));
  938. _Auto group = &fs_runq->group_array[thread_real_priority (thread)];
  939. list_insert_tail (&group->threads, &thread->fs_data.group_node);
  940. if (thread->fs_data.work >= thread->fs_data.weight)
  941. thread_sched_fs_deactivate (runq, thread);
  942. }
  943. static int
  944. thread_sched_fs_ratio_exceeded (struct thread_fs_group *current,
  945. struct thread_fs_group *next)
  946. {
  947. #ifndef __LP64__
  948. if (likely (current->weight < 0x10000 && next->weight < 0x10000))
  949. {
  950. uint32_t ia = (current->work + 1) * next->weight,
  951. ib = (next->work + 1) * current->weight;
  952. return (ia > ib);
  953. }
  954. #endif
  955. uint64_t a = ((uint64_t)current->work + 1) * next->weight,
  956. b = ((uint64_t)next->work + 1) * current->weight;
  957. return (a > b);
  958. }
  959. static struct thread*
  960. thread_sched_fs_get_next (struct thread_runq *runq)
  961. {
  962. _Auto fs_runq = runq->fs_runq_active;
  963. if (!fs_runq->nr_threads)
  964. return (NULL);
  965. _Auto group = fs_runq->current;
  966. struct list *node = list_next (&group->node);
  967. if (list_end (&fs_runq->groups, node))
  968. group = list_entry (list_first (&fs_runq->groups),
  969. struct thread_fs_group, node);
  970. else
  971. {
  972. _Auto next = list_entry (node, struct thread_fs_group, node);
  973. group = thread_sched_fs_ratio_exceeded (group, next) ?
  974. next : list_entry (list_first (&fs_runq->groups),
  975. struct thread_fs_group, node);
  976. }
  977. fs_runq->current = group;
  978. return (list_pop (&group->threads, struct thread, fs_data.group_node));
  979. }
  980. static void
  981. thread_sched_fs_reset_priority (struct thread *thread, uint16_t priority)
  982. {
  983. assert (priority <= THREAD_SCHED_FS_PRIO_MAX);
  984. thread->fs_data.fs_runq = NULL;
  985. thread->fs_data.round = 0;
  986. thread->fs_data.weight = thread_sched_fs_prio2weight (priority);
  987. thread->fs_data.work = 0;
  988. }
  989. static void
  990. thread_sched_fs_update_priority (struct thread *thread, uint16_t priority)
  991. {
  992. assert (priority <= THREAD_SCHED_FS_PRIO_MAX);
  993. thread->fs_data.weight = thread_sched_fs_prio2weight (priority);
  994. if (thread->fs_data.work >= thread->fs_data.weight)
  995. thread->fs_data.work = thread->fs_data.weight;
  996. }
  997. static uint32_t
  998. thread_sched_fs_get_global_priority (uint16_t priority __unused)
  999. {
  1000. return (THREAD_SCHED_GLOBAL_PRIO_FS);
  1001. }
  1002. static void
  1003. thread_sched_fs_set_next (struct thread_runq *rq __unused, struct thread *thr)
  1004. {
  1005. list_remove (&thr->fs_data.group_node);
  1006. }
  1007. static void
  1008. thread_sched_fs_tick (struct thread_runq *runq, struct thread *thread)
  1009. {
  1010. _Auto fs_runq = runq->fs_runq_active;
  1011. ++fs_runq->work;
  1012. _Auto group = &fs_runq->group_array[thread_real_priority (thread)];
  1013. ++group->work;
  1014. thread_set_flag (thread, THREAD_YIELD);
  1015. ++thread->fs_data.work;
  1016. }
  1017. static void
  1018. thread_sched_fs_start_next_round (struct thread_runq *runq)
  1019. {
  1020. _Auto tmp = runq->fs_runq_expired;
  1021. runq->fs_runq_expired = runq->fs_runq_active;
  1022. runq->fs_runq_active = tmp;
  1023. if (runq->fs_runq_active->nr_threads)
  1024. {
  1025. ++runq->fs_round;
  1026. ssize_t delta = (ssize_t)(runq->fs_round - thread_fs_highest_round);
  1027. if (delta > 0)
  1028. thread_fs_highest_round = runq->fs_round;
  1029. thread_sched_fs_restart (runq);
  1030. }
  1031. }
  1032. // Check that a remote run queue satisfies the minimum migration requirements.
  1033. static int
  1034. thread_sched_fs_balance_eligible (struct thread_runq *runq,
  1035. size_t highest_round)
  1036. {
  1037. if (!runq->fs_weight ||
  1038. (runq->fs_round != highest_round &&
  1039. runq->fs_round != highest_round - 1))
  1040. return (0);
  1041. uint32_t nr_threads = runq->fs_runq_active->nr_threads +
  1042. runq->fs_runq_expired->nr_threads;
  1043. if (! nr_threads ||
  1044. (nr_threads == 1 &&
  1045. thread_real_sched_class (runq->current) == THREAD_SCHED_CLASS_FS))
  1046. return (0);
  1047. return (1);
  1048. }
  1049. // Try to find the most suitable run queue from which to pull threads.
  1050. static struct thread_runq*
  1051. thread_sched_fs_balance_scan (struct thread_runq *runq,
  1052. size_t highest_round)
  1053. {
  1054. struct thread_runq *remote_runq = NULL;
  1055. cpu_flags_t flags;
  1056. thread_preempt_disable_intr_save (&flags);
  1057. cpumap_for_each (&thread_active_runqs, i)
  1058. {
  1059. _Auto tmp = percpu_ptr (thread_runq, i);
  1060. if (tmp == runq)
  1061. continue;
  1062. spinlock_lock (&tmp->lock);
  1063. if (!thread_sched_fs_balance_eligible (tmp, highest_round))
  1064. {
  1065. spinlock_unlock (&tmp->lock);
  1066. continue;
  1067. }
  1068. else if (! remote_runq)
  1069. {
  1070. remote_runq = tmp;
  1071. continue;
  1072. }
  1073. else if (tmp->fs_weight > remote_runq->fs_weight)
  1074. {
  1075. spinlock_unlock (&remote_runq->lock);
  1076. remote_runq = tmp;
  1077. continue;
  1078. }
  1079. spinlock_unlock (&tmp->lock);
  1080. }
  1081. if (remote_runq)
  1082. spinlock_unlock (&remote_runq->lock);
  1083. thread_preempt_enable_intr_restore (flags);
  1084. return (remote_runq);
  1085. }
  1086. static uint32_t
  1087. thread_sched_fs_balance_pull (struct thread_runq *runq,
  1088. struct thread_runq *remote_runq,
  1089. struct thread_fs_runq *fs_runq,
  1090. uint32_t nr_pulls)
  1091. {
  1092. int cpu = thread_runq_cpu (runq);
  1093. struct thread *thread, *tmp;
  1094. list_for_each_entry_safe (&fs_runq->threads, thread, tmp,
  1095. fs_data.runq_node)
  1096. {
  1097. if (thread == remote_runq->current)
  1098. continue;
  1099. /*
  1100. * The pin level is changed without explicit synchronization.
  1101. * However, it can only be changed by its owning thread. As threads
  1102. * currently running aren't considered for migration, the thread had
  1103. * to be preempted and invoke the scheduler. Since balancer threads
  1104. * acquire the run queue lock, there is strong ordering between
  1105. * changing the pin level and setting the current thread of a
  1106. * run queue.
  1107. *
  1108. * TODO Review comment.
  1109. */
  1110. if (thread->pin_level || !cpumap_test (&thread->cpumap, cpu))
  1111. continue;
  1112. /*
  1113. * Make sure at least one thread is pulled if possible. If one or more
  1114. * thread has already been pulled, take weights into account.
  1115. */
  1116. if (nr_pulls &&
  1117. runq->fs_weight + thread->fs_data.weight >
  1118. remote_runq->fs_weight - thread->fs_data.weight)
  1119. break;
  1120. thread_runq_remove (remote_runq, thread);
  1121. // Don't discard the work already accounted for.
  1122. thread->fs_data.round = runq->fs_round;
  1123. thread_runq_add (runq, thread);
  1124. if (++nr_pulls == THREAD_MAX_MIGRATIONS)
  1125. break;
  1126. }
  1127. return (nr_pulls);
  1128. }
  1129. static uint32_t
  1130. thread_sched_fs_balance_migrate (struct thread_runq *runq,
  1131. struct thread_runq *remote_runq,
  1132. size_t highest_round)
  1133. {
  1134. uint32_t nr_pulls = 0;
  1135. if (!thread_sched_fs_balance_eligible (remote_runq, highest_round))
  1136. return (nr_pulls);
  1137. nr_pulls = thread_sched_fs_balance_pull (runq, remote_runq,
  1138. remote_runq->fs_runq_active, 0);
  1139. if (nr_pulls == THREAD_MAX_MIGRATIONS)
  1140. return (nr_pulls);
  1141. /*
  1142. * Threads in the expired queue of a processor in round highest are
  1143. * actually in round highest + 1.
  1144. */
  1145. if (remote_runq->fs_round != highest_round)
  1146. nr_pulls = thread_sched_fs_balance_pull (runq, remote_runq,
  1147. remote_runq->fs_runq_expired,
  1148. nr_pulls);
  1149. return (nr_pulls);
  1150. }
  1151. /*
  1152. * Inter-processor load balancing for fair-scheduling threads.
  1153. *
  1154. * Preemption must be disabled, and the local run queue must be locked when
  1155. * calling this function. If balancing actually occurs, the lock will be
  1156. * released and preemption enabled when needed.
  1157. */
  1158. static void
  1159. thread_sched_fs_balance (struct thread_runq *runq, cpu_flags_t *flags)
  1160. {
  1161. /*
  1162. * Grab the highest round now and only use the copy so the value is stable
  1163. * during the balancing operation.
  1164. */
  1165. size_t highest_round = thread_fs_highest_round;
  1166. if (runq->fs_round != highest_round &&
  1167. runq->fs_runq_expired->nr_threads)
  1168. goto no_migration;
  1169. spinlock_unlock_intr_restore (&runq->lock, *flags);
  1170. thread_preempt_enable ();
  1171. uint32_t nr_migrations;
  1172. _Auto remote_runq = thread_sched_fs_balance_scan (runq, highest_round);
  1173. if (remote_runq)
  1174. {
  1175. thread_preempt_disable_intr_save (flags);
  1176. thread_runq_double_lock (runq, remote_runq);
  1177. nr_migrations = thread_sched_fs_balance_migrate (runq, remote_runq,
  1178. highest_round);
  1179. spinlock_unlock (&remote_runq->lock);
  1180. if (nr_migrations)
  1181. return;
  1182. spinlock_unlock_intr_restore (&runq->lock, *flags);
  1183. thread_preempt_enable ();
  1184. }
  1185. /*
  1186. * The scan or the migration failed. As a fallback, make another, simpler
  1187. * pass on every run queue, and stop as soon as at least one thread could
  1188. * be successfully pulled.
  1189. */
  1190. cpumap_for_each (&thread_active_runqs, i)
  1191. {
  1192. remote_runq = percpu_ptr (thread_runq, i);
  1193. if (remote_runq == runq)
  1194. continue;
  1195. thread_preempt_disable_intr_save (flags);
  1196. thread_runq_double_lock (runq, remote_runq);
  1197. nr_migrations = thread_sched_fs_balance_migrate (runq, remote_runq,
  1198. highest_round);
  1199. spinlock_unlock (&remote_runq->lock);
  1200. if (nr_migrations != 0)
  1201. return;
  1202. spinlock_unlock_intr_restore (&runq->lock, *flags);
  1203. thread_preempt_enable ();
  1204. }
  1205. thread_preempt_disable ();
  1206. spinlock_lock_intr_save (&runq->lock, flags);
  1207. no_migration:
  1208. /*
  1209. * No thread could be migrated. Check the active run queue, as another
  1210. * processor might have added threads while the balancer was running.
  1211. * If the run queue is still empty, switch to the next round. The run
  1212. * queue lock must remain held until the next scheduling decision to
  1213. * prevent a remote balancer thread from stealing active threads.
  1214. */
  1215. if (!runq->fs_runq_active->nr_threads)
  1216. thread_sched_fs_start_next_round (runq);
  1217. }
  1218. static struct thread_runq*
  1219. thread_sched_idle_select_runq (struct thread *thread __unused)
  1220. {
  1221. panic ("thread: idler threads cannot be awoken");
  1222. }
  1223. static noreturn void
  1224. thread_sched_idle_panic (void)
  1225. {
  1226. panic ("thread: only idle threads are allowed in the idle class");
  1227. }
  1228. static void
  1229. thread_sched_idle_add (struct thread_runq *runq __unused,
  1230. struct thread *thread __unused)
  1231. {
  1232. thread_sched_idle_panic ();
  1233. }
  1234. #define thread_sched_idle_remove thread_sched_idle_add
  1235. static struct thread*
  1236. thread_sched_idle_get_next (struct thread_runq *runq)
  1237. {
  1238. return (runq->idler);
  1239. }
  1240. static uint32_t
  1241. thread_sched_idle_get_global_priority (uint16_t priority __unused)
  1242. {
  1243. return (THREAD_SCHED_GLOBAL_PRIO_IDLE);
  1244. }
  1245. static const struct thread_sched_ops thread_sched_ops[THREAD_NR_SCHED_CLASSES] =
  1246. {
  1247. [THREAD_SCHED_CLASS_RT] =
  1248. {
  1249. .select_runq = thread_sched_rt_select_runq,
  1250. .add = thread_sched_rt_add,
  1251. .remove = thread_sched_rt_remove,
  1252. .put_prev = thread_sched_rt_put_prev,
  1253. .get_next = thread_sched_rt_get_next,
  1254. .reset_priority = thread_sched_rt_reset_priority,
  1255. .update_priority = NULL,
  1256. .get_global_priority = thread_sched_rt_get_global_priority,
  1257. .set_next = thread_sched_rt_set_next,
  1258. .tick = thread_sched_rt_tick,
  1259. },
  1260. [THREAD_SCHED_CLASS_FS] =
  1261. {
  1262. .select_runq = thread_sched_fs_select_runq,
  1263. .add = thread_sched_fs_add,
  1264. .remove = thread_sched_fs_remove,
  1265. .put_prev = thread_sched_fs_put_prev,
  1266. .get_next = thread_sched_fs_get_next,
  1267. .reset_priority = thread_sched_fs_reset_priority,
  1268. .update_priority = thread_sched_fs_update_priority,
  1269. .get_global_priority = thread_sched_fs_get_global_priority,
  1270. .set_next = thread_sched_fs_set_next,
  1271. .tick = thread_sched_fs_tick,
  1272. },
  1273. [THREAD_SCHED_CLASS_IDLE] =
  1274. {
  1275. .select_runq = thread_sched_idle_select_runq,
  1276. .add = thread_sched_idle_add,
  1277. .remove = thread_sched_idle_remove,
  1278. .put_prev = NULL,
  1279. .get_next = thread_sched_idle_get_next,
  1280. .reset_priority = NULL,
  1281. .update_priority = NULL,
  1282. .get_global_priority = thread_sched_idle_get_global_priority,
  1283. .set_next = NULL,
  1284. .tick = NULL,
  1285. },
  1286. };
  1287. static void
  1288. thread_set_user_sched_policy (struct thread *thread, uint8_t sched_policy)
  1289. {
  1290. thread->user_sched_data.sched_policy = sched_policy;
  1291. }
  1292. static void
  1293. thread_set_user_sched_class (struct thread *thread, uint8_t sched_class)
  1294. {
  1295. thread->user_sched_data.sched_class = sched_class;
  1296. }
  1297. static void
  1298. thread_set_user_priority (struct thread *thread, uint16_t prio)
  1299. {
  1300. const _Auto ops = thread_get_user_sched_ops (thread);
  1301. thread->user_sched_data.priority = prio;
  1302. thread->user_sched_data.global_priority = ops->get_global_priority (prio);
  1303. }
  1304. static void
  1305. thread_update_user_priority (struct thread *thread, uint16_t priority)
  1306. {
  1307. thread_set_user_priority (thread, priority);
  1308. }
  1309. static void
  1310. thread_set_real_sched_policy (struct thread *thread, uint8_t sched_policy)
  1311. {
  1312. thread->real_sched_data.sched_policy = sched_policy;
  1313. }
  1314. static void
  1315. thread_set_real_sched_class (struct thread *thread, uint8_t sched_class)
  1316. {
  1317. thread->real_sched_data.sched_class = sched_class;
  1318. }
  1319. static void
  1320. thread_set_real_priority (struct thread *thread, uint16_t prio)
  1321. {
  1322. const _Auto ops = thread_get_real_sched_ops (thread);
  1323. thread->real_sched_data.priority = prio;
  1324. thread->real_sched_data.global_priority = ops->get_global_priority (prio);
  1325. if (ops->reset_priority)
  1326. ops->reset_priority (thread, prio);
  1327. }
  1328. static void
  1329. thread_update_real_priority (struct thread *thread, uint16_t prio)
  1330. {
  1331. const _Auto ops = thread_get_real_sched_ops (thread);
  1332. thread->real_sched_data.priority = prio;
  1333. thread->real_sched_data.global_priority = ops->get_global_priority (prio);
  1334. if (ops->update_priority)
  1335. ops->update_priority (thread, prio);
  1336. }
  1337. static void
  1338. thread_reset_real_priority (struct thread *thread)
  1339. {
  1340. thread->real_sched_data = thread->user_sched_data;
  1341. thread->boosted = false;
  1342. const _Auto ops = thread_get_user_sched_ops (thread);
  1343. if (ops->reset_priority)
  1344. ops->reset_priority (thread, thread->real_sched_data.priority);
  1345. }
  1346. static void __init
  1347. thread_init_booter (uint32_t cpu)
  1348. {
  1349. // Initialize only what's needed during bootstrap.
  1350. struct thread *booter = &thread_booters[cpu];
  1351. booter->kuid.id = 0;
  1352. booter->kuid.nr_refs = 0; // Make sure booters aren't destroyed.
  1353. booter->flags = 0;
  1354. booter->intr_level = 0;
  1355. booter->preempt_level = 1;
  1356. booter->pagefault_level = 0;
  1357. rcu_reader_init (&booter->rcu_reader);
  1358. cpumap_fill (&booter->cpumap);
  1359. thread_set_user_sched_policy (booter, THREAD_SCHED_POLICY_IDLE);
  1360. thread_set_user_sched_class (booter, THREAD_SCHED_CLASS_IDLE);
  1361. thread_set_user_priority (booter, 0);
  1362. thread_reset_real_priority (booter);
  1363. booter->task = booter->xtask = task_get_kernel_task ();
  1364. snprintf (booter->name, sizeof (booter->name),
  1365. THREAD_KERNEL_PREFIX "thread_boot/%u", cpu);
  1366. }
  1367. static int __init
  1368. thread_setup_booter (void)
  1369. {
  1370. tcb_set_current (&thread_booters[0].tcb);
  1371. thread_init_booter (0);
  1372. return (0);
  1373. }
  1374. INIT_OP_DEFINE (thread_setup_booter,
  1375. INIT_OP_DEP (tcb_setup, true));
  1376. static int __init
  1377. thread_bootstrap (void)
  1378. {
  1379. cpumap_zero (&thread_active_runqs);
  1380. cpumap_zero (&thread_idle_runqs);
  1381. thread_fs_highest_round = THREAD_FS_INITIAL_ROUND;
  1382. cpumap_set (&thread_active_runqs, 0);
  1383. thread_runq_init (cpu_local_ptr (thread_runq), 0, &thread_booters[0]);
  1384. return (0);
  1385. }
  1386. INIT_OP_DEFINE (thread_bootstrap,
  1387. INIT_OP_DEP (syscnt_setup, true),
  1388. INIT_OP_DEP (thread_setup_booter, true));
  1389. void
  1390. thread_main (void (*fn) (void *), void *arg)
  1391. {
  1392. assert (!cpu_intr_enabled ());
  1393. assert (!thread_preempt_enabled ());
  1394. struct thread *thread = thread_self ();
  1395. thread_runq_schedule_load (thread);
  1396. spinlock_unlock (&thread_runq_local()->lock);
  1397. cpu_intr_enable ();
  1398. thread_preempt_enable ();
  1399. fn (arg);
  1400. thread_exit ();
  1401. }
  1402. static int
  1403. thread_init (struct thread *thread, void *stack,
  1404. const struct thread_attr *attr,
  1405. void (*fn) (void *), void *arg)
  1406. {
  1407. struct thread *caller = thread_self ();
  1408. struct task *task = attr->task ?: caller->task;
  1409. struct cpumap *cpumap = attr->cpumap ?: &caller->cpumap;
  1410. assert (attr->policy < ARRAY_SIZE (thread_policy_table));
  1411. kuid_head_init (&thread->kuid);
  1412. thread->flags = 0;
  1413. thread->runq = NULL;
  1414. thread->in_runq = false;
  1415. thread_set_wchan (thread, thread, "init");
  1416. thread->state = THREAD_SLEEPING;
  1417. thread->priv_sleepq = sleepq_create ();
  1418. int error;
  1419. if (!thread->priv_sleepq)
  1420. {
  1421. error = ENOMEM;
  1422. goto error_sleepq;
  1423. }
  1424. thread->priv_turnstile = turnstile_create ();
  1425. if (!thread->priv_turnstile)
  1426. {
  1427. error = ENOMEM;
  1428. goto error_turnstile;
  1429. }
  1430. turnstile_td_init (&thread->turnstile_td);
  1431. thread->propagate_priority = false;
  1432. thread->suspend = false;
  1433. thread->preempt_level = THREAD_SUSPEND_PREEMPT_LEVEL;
  1434. thread->pin_level = 0;
  1435. thread->intr_level = 0;
  1436. thread->pagefault_level = 0;
  1437. rcu_reader_init (&thread->rcu_reader);
  1438. cpumap_copy (&thread->cpumap, cpumap);
  1439. thread_set_user_sched_policy (thread, attr->policy);
  1440. thread_set_user_sched_class (thread, thread_policy_to_class (attr->policy));
  1441. thread_set_user_priority (thread, attr->priority);
  1442. thread_reset_real_priority (thread);
  1443. thread->join_waiter = NULL;
  1444. spinlock_init (&thread->join_lock);
  1445. thread->terminating = false;
  1446. thread->task = thread->xtask = task;
  1447. thread->stack = stack;
  1448. strlcpy (thread->name, attr->name, sizeof (thread->name));
  1449. thread->fixup = NULL;
  1450. thread->cur_lpad = NULL;
  1451. thread->futex_td = NULL;
  1452. bulletin_init (&thread->dead_subs);
  1453. for (size_t i = 0; i < THREAD_NR_PMAP_DATA; ++i)
  1454. pmap_ipc_pte_init (&thread->pmap_data[i]);
  1455. #ifdef CONFIG_PERFMON
  1456. perfmon_td_init (thread_get_perfmon_td (thread));
  1457. #endif
  1458. if (attr->flags & THREAD_ATTR_DETACHED)
  1459. thread->flags |= THREAD_DETACHED;
  1460. error = tcb_build (&thread->tcb, stack, fn, arg);
  1461. if (error)
  1462. goto error_tcb;
  1463. else if (thread->task != task_get_kernel_task ())
  1464. {
  1465. error = kuid_alloc (&thread->kuid, KUID_THREAD);
  1466. if (error)
  1467. goto error_kuid;
  1468. }
  1469. task_add_thread (task, thread);
  1470. return (0);
  1471. error_kuid:
  1472. tcb_cleanup (&thread->tcb);
  1473. error_tcb:
  1474. turnstile_destroy (thread->priv_turnstile);
  1475. error_turnstile:
  1476. sleepq_destroy (thread->priv_sleepq);
  1477. error_sleepq:
  1478. return (error);
  1479. }
  1480. #ifdef CONFIG_THREAD_STACK_GUARD
  1481. #include <machine/pmap.h>
  1482. #include <vm/kmem.h>
  1483. #include <vm/page.h>
  1484. static void*
  1485. thread_alloc_stack (void)
  1486. {
  1487. _Auto kernel_pmap = pmap_get_kernel_pmap ();
  1488. size_t stack_size = vm_page_round (TCB_STACK_SIZE);
  1489. void *mem = vm_kmem_alloc ((PAGE_SIZE * 2) + stack_size);
  1490. if (! mem)
  1491. return (NULL);
  1492. uintptr_t va = (uintptr_t)mem;
  1493. /*
  1494. * TODO Until memory protection is implemented, use the pmap system
  1495. * to remove mappings.
  1496. */
  1497. phys_addr_t first_pa, last_pa;
  1498. int error = pmap_kextract (va, &first_pa);
  1499. assert (! error);
  1500. error = pmap_kextract (va + PAGE_SIZE + stack_size, &last_pa);
  1501. assert (! error);
  1502. _Auto first_page = vm_page_lookup (first_pa);
  1503. assert (first_page);
  1504. _Auto last_page = vm_page_lookup (last_pa);
  1505. assert (last_page);
  1506. pmap_remove (kernel_pmap, va, PMAP_PEF_GLOBAL);
  1507. pmap_remove (kernel_pmap, va + PAGE_SIZE + stack_size,
  1508. PMAP_PEF_GLOBAL | PMAP_IGNORE_ERRORS);
  1509. pmap_update (kernel_pmap);
  1510. return ((char *)va + PAGE_SIZE);
  1511. }
  1512. static void
  1513. thread_free_stack (void *stack)
  1514. {
  1515. size_t stack_size = vm_page_round (TCB_STACK_SIZE);
  1516. void *va = (char *)stack - PAGE_SIZE;
  1517. vm_kmem_free (va, (PAGE_SIZE * 2) + stack_size);
  1518. }
  1519. #else // CONFIG_THREAD_STACK_GUARD
  1520. static void*
  1521. thread_alloc_stack (void)
  1522. {
  1523. return (kmem_cache_alloc (&thread_stack_cache));
  1524. }
  1525. static void
  1526. thread_free_stack (void *stack)
  1527. {
  1528. kmem_cache_free (&thread_stack_cache, stack);
  1529. }
  1530. #endif
  1531. static void
  1532. thread_destroy (struct thread *thread)
  1533. {
  1534. assert (thread != thread_self ());
  1535. assert (thread->state == THREAD_DEAD);
  1536. // See task_info().
  1537. task_remove_thread (thread->task, thread);
  1538. turnstile_destroy (thread->priv_turnstile);
  1539. sleepq_destroy (thread->priv_sleepq);
  1540. thread_free_stack (thread->stack);
  1541. tcb_cleanup (&thread->tcb);
  1542. kmem_cache_free (&thread_cache, thread);
  1543. }
  1544. static void
  1545. thread_join_common (struct thread *thread)
  1546. {
  1547. struct thread *self = thread_self ();
  1548. assert (thread != self);
  1549. spinlock_lock (&thread->join_lock);
  1550. assert (!thread->join_waiter);
  1551. thread->join_waiter = self;
  1552. while (!thread->terminating)
  1553. thread_sleep (&thread->join_lock, thread, "exit");
  1554. spinlock_unlock (&thread->join_lock);
  1555. uint32_t state;
  1556. do
  1557. {
  1558. struct thread_runq_guard g = thread_runq_guard_make (thread, false);
  1559. state = thread->state;
  1560. }
  1561. while (state != THREAD_DEAD);
  1562. thread_destroy (thread);
  1563. }
  1564. void
  1565. thread_terminate (struct thread *thread)
  1566. {
  1567. SPINLOCK_GUARD (&thread->join_lock);
  1568. thread->terminating = true;
  1569. cap_notify_dead (&thread->dead_subs);
  1570. kuid_remove (&thread->kuid, KUID_THREAD);
  1571. thread_wakeup (thread->join_waiter);
  1572. }
  1573. static void
  1574. thread_balance_idle_tick (struct thread_runq *runq)
  1575. {
  1576. assert (runq->idle_balance_ticks != 0);
  1577. /*
  1578. * Interrupts can occur early, at a time the balancer thread hasn't been
  1579. * created yet.
  1580. */
  1581. if (runq->balancer &&
  1582. --runq->idle_balance_ticks == 0)
  1583. thread_runq_wakeup_balancer (runq);
  1584. }
  1585. static void
  1586. thread_balance (void *arg)
  1587. {
  1588. struct thread_runq *runq = arg;
  1589. struct thread *self = runq->balancer;
  1590. assert (self == runq->balancer);
  1591. thread_preempt_disable ();
  1592. cpu_flags_t flags;
  1593. spinlock_lock_intr_save (&runq->lock, &flags);
  1594. while (1)
  1595. {
  1596. runq->idle_balance_ticks = THREAD_IDLE_BALANCE_TICKS;
  1597. thread_set_wchan (self, runq, "runq");
  1598. atomic_store_rlx (&self->state, THREAD_SLEEPING);
  1599. runq = thread_runq_schedule (runq);
  1600. assert (runq == arg);
  1601. /*
  1602. * This function may temporarily enable preemption and release the
  1603. * run queue lock, but on return, the lock must remain held until this
  1604. * balancer thread sleeps.
  1605. */
  1606. thread_sched_fs_balance (runq, &flags);
  1607. }
  1608. }
  1609. static void __init
  1610. thread_setup_balancer (struct thread_runq *runq)
  1611. {
  1612. struct cpumap *cpumap;
  1613. if (cpumap_create (&cpumap) != 0)
  1614. panic ("thread: unable to create balancer thread CPU map");
  1615. cpumap_zero (cpumap);
  1616. cpumap_set (cpumap, thread_runq_cpu (runq));
  1617. char name[THREAD_NAME_SIZE];
  1618. snprintf (name, sizeof (name), THREAD_KERNEL_PREFIX "thread_balance/%u",
  1619. thread_runq_cpu (runq));
  1620. struct thread_attr attr;
  1621. thread_attr_init (&attr, name);
  1622. thread_attr_set_cpumap (&attr, cpumap);
  1623. thread_attr_set_policy (&attr, THREAD_SCHED_POLICY_FIFO);
  1624. thread_attr_set_priority (&attr, THREAD_SCHED_RT_PRIO_MIN);
  1625. int error = thread_create (&runq->balancer, &attr, thread_balance, runq);
  1626. cpumap_destroy (cpumap);
  1627. if (error)
  1628. panic ("thread: unable to create balancer thread");
  1629. }
  1630. static void
  1631. thread_idle (void *arg __unused)
  1632. {
  1633. struct thread *self = thread_self ();
  1634. while (1)
  1635. {
  1636. thread_preempt_disable ();
  1637. while (1)
  1638. {
  1639. cpu_intr_disable ();
  1640. if (thread_test_flag (self, THREAD_YIELD))
  1641. {
  1642. cpu_intr_enable ();
  1643. break;
  1644. }
  1645. cpu_idle ();
  1646. }
  1647. thread_preempt_enable ();
  1648. }
  1649. }
  1650. static void __init
  1651. thread_setup_idler (struct thread_runq *runq)
  1652. {
  1653. struct cpumap *cpumap;
  1654. if (cpumap_create (&cpumap) != 0)
  1655. panic ("thread: unable to allocate idler thread CPU map");
  1656. cpumap_zero (cpumap);
  1657. cpumap_set (cpumap, thread_runq_cpu (runq));
  1658. struct thread *idler = kmem_cache_alloc (&thread_cache);
  1659. if (! idler)
  1660. panic ("thread: unable to allocate idler thread");
  1661. void *stack = thread_alloc_stack ();
  1662. if (! stack)
  1663. panic ("thread: unable to allocate idler thread stack");
  1664. char name[THREAD_NAME_SIZE];
  1665. snprintf (name, sizeof (name), THREAD_KERNEL_PREFIX "thread_idle/%u",
  1666. thread_runq_cpu (runq));
  1667. struct thread_attr attr;
  1668. thread_attr_init (&attr, name);
  1669. thread_attr_set_cpumap (&attr, cpumap);
  1670. thread_attr_set_policy (&attr, THREAD_SCHED_POLICY_IDLE);
  1671. if (thread_init (idler, stack, &attr, thread_idle, NULL) != 0)
  1672. panic ("thread: unable to initialize idler thread");
  1673. cpumap_destroy (cpumap);
  1674. // An idler thread needs special tuning.
  1675. thread_clear_wchan (idler);
  1676. idler->state = THREAD_RUNNING;
  1677. idler->runq = runq;
  1678. runq->idler = idler;
  1679. }
  1680. static void __init
  1681. thread_setup_runq (struct thread_runq *runq)
  1682. {
  1683. thread_setup_balancer (runq);
  1684. thread_setup_idler (runq);
  1685. }
  1686. #ifdef CONFIG_SHELL
  1687. /*
  1688. * This function is meant for debugging only. As a result, it uses a weak
  1689. * locking policy which allows tracing threads which state may mutate during
  1690. * tracing.
  1691. */
  1692. static void
  1693. thread_shell_trace (struct shell *shell, int argc, char **argv)
  1694. {
  1695. if (argc != 3)
  1696. {
  1697. stream_puts (shell->stream, "usage: thread_trace task thread\n");
  1698. return;
  1699. }
  1700. const char *task_name = argv[1], *thread_name = argv[2];
  1701. struct task *task = task_lookup (task_name);
  1702. if (! task)
  1703. {
  1704. fmt_xprintf (shell->stream, "thread_trace: task not found: %s\n",
  1705. task_name);
  1706. return;
  1707. }
  1708. struct thread *thread = task_lookup_thread (task, thread_name);
  1709. task_unref (task);
  1710. if (! thread)
  1711. {
  1712. fmt_xprintf (shell->stream, "thread_trace: thread not found: %s\n",
  1713. thread_name);
  1714. return;
  1715. }
  1716. cpu_flags_t flags;
  1717. _Auto runq = thread_lock_runq (thread, &flags);
  1718. if (thread == runq->current)
  1719. stream_puts (shell->stream, "thread_trace: thread is running\n");
  1720. else
  1721. tcb_trace (&thread->tcb);
  1722. thread_unlock_runq (runq, flags);
  1723. thread_unref (thread);
  1724. }
  1725. static struct shell_cmd thread_shell_cmds[] =
  1726. {
  1727. SHELL_CMD_INITIALIZER ("thread_trace", thread_shell_trace,
  1728. "thread_trace <task_name> <thread_name>",
  1729. "display the stack trace of a given thread"),
  1730. };
  1731. static int __init
  1732. thread_setup_shell (void)
  1733. {
  1734. SHELL_REGISTER_CMDS (thread_shell_cmds, shell_get_main_cmd_set ());
  1735. return (0);
  1736. }
  1737. INIT_OP_DEFINE (thread_setup_shell,
  1738. INIT_OP_DEP (printf_setup, true),
  1739. INIT_OP_DEP (shell_setup, true),
  1740. INIT_OP_DEP (task_setup, true),
  1741. INIT_OP_DEP (thread_setup, true));
  1742. #endif
  1743. static void __init
  1744. thread_setup_common (uint32_t cpu)
  1745. {
  1746. assert (cpu);
  1747. cpumap_set (&thread_active_runqs, cpu);
  1748. thread_init_booter (cpu);
  1749. thread_runq_init (percpu_ptr (thread_runq, cpu), cpu, &thread_booters[cpu]);
  1750. }
  1751. static int __init
  1752. thread_setup (void)
  1753. {
  1754. for (uint32_t cpu = 1; cpu < cpu_count (); ++cpu)
  1755. thread_setup_common (cpu);
  1756. kmem_cache_init (&thread_cache, "thread", sizeof (struct thread),
  1757. CPU_L1_SIZE, NULL, 0);
  1758. #ifndef CONFIG_THREAD_STACK_GUARD
  1759. kmem_cache_init (&thread_stack_cache, "thread_stack", TCB_STACK_SIZE,
  1760. CPU_DATA_ALIGN, NULL, 0);
  1761. #endif
  1762. cpumap_for_each (&thread_active_runqs, cpu)
  1763. thread_setup_runq (percpu_ptr (thread_runq, cpu));
  1764. return (0);
  1765. }
  1766. #ifdef CONFIG_THREAD_STACK_GUARD
  1767. #define THREAD_STACK_GUARD_INIT_OP_DEPS \
  1768. INIT_OP_DEP (vm_kmem_setup, true), \
  1769. INIT_OP_DEP (vm_map_setup, true), \
  1770. INIT_OP_DEP (vm_page_setup, true),
  1771. #else
  1772. #define THREAD_STACK_GUARD_INIT_OP_DEPS
  1773. #endif
  1774. #ifdef CONFIG_PERFMON
  1775. #define THREAD_PERFMON_INIT_OP_DEPS INIT_OP_DEP (perfmon_bootstrap, true),
  1776. #else
  1777. #define THREAD_PERFMON_INIT_OP_DEPS
  1778. #endif
  1779. INIT_OP_DEFINE (thread_setup,
  1780. INIT_OP_DEP (cpumap_setup, true),
  1781. INIT_OP_DEP (kmem_setup, true),
  1782. INIT_OP_DEP (pmap_setup, true),
  1783. INIT_OP_DEP (sleepq_setup, true),
  1784. INIT_OP_DEP (task_setup, true),
  1785. INIT_OP_DEP (thread_bootstrap, true),
  1786. INIT_OP_DEP (turnstile_setup, true),
  1787. THREAD_STACK_GUARD_INIT_OP_DEPS
  1788. THREAD_PERFMON_INIT_OP_DEPS);
  1789. void __init
  1790. thread_ap_setup (void)
  1791. {
  1792. tcb_set_current (&thread_booters[cpu_id ()].tcb);
  1793. }
  1794. int
  1795. thread_create (struct thread **threadp, const struct thread_attr *attr,
  1796. void (*fn) (void *), void *arg)
  1797. {
  1798. int error;
  1799. if (attr->cpumap)
  1800. {
  1801. error = cpumap_check (attr->cpumap);
  1802. if (error)
  1803. return (error);
  1804. }
  1805. struct thread *thread = kmem_cache_alloc (&thread_cache);
  1806. if (! thread)
  1807. {
  1808. error = ENOMEM;
  1809. goto error_thread;
  1810. }
  1811. void *stack = thread_alloc_stack ();
  1812. if (! stack)
  1813. {
  1814. error = ENOMEM;
  1815. goto error_stack;
  1816. }
  1817. error = thread_init (thread, stack, attr, fn, arg);
  1818. if (error)
  1819. goto error_init;
  1820. /*
  1821. * The new thread address must be written before the thread is started
  1822. * in case it's passed to it.
  1823. */
  1824. if (threadp)
  1825. *threadp = thread;
  1826. thread_wakeup (thread);
  1827. return (0);
  1828. error_init:
  1829. thread_free_stack (stack);
  1830. error_stack:
  1831. kmem_cache_free (&thread_cache, thread);
  1832. error_thread:
  1833. return (error);
  1834. }
  1835. static void
  1836. thread_reap (struct work *work)
  1837. {
  1838. _Auto zombie = structof (work, struct thread_zombie, work);
  1839. thread_join_common (zombie->thread);
  1840. }
  1841. void
  1842. thread_exit (void)
  1843. {
  1844. struct thread_zombie zombie;
  1845. struct thread *thread = thread_self ();
  1846. if (likely (thread->task != task_get_kernel_task ()))
  1847. turnstile_td_exit (&thread->turnstile_td);
  1848. futex_td_exit (thread->futex_td);
  1849. if (thread_test_flag (thread, THREAD_DETACHED))
  1850. {
  1851. zombie.thread = thread;
  1852. work_init (&zombie.work, thread_reap);
  1853. work_schedule (&zombie.work, 0);
  1854. }
  1855. /*
  1856. * Disable preemption before dropping the reference, as this may
  1857. * trigger the active state poll of the join operation. Doing so
  1858. * keeps the duration of that active wait minimum.
  1859. */
  1860. thread_preempt_disable ();
  1861. thread_unref (thread);
  1862. _Auto runq = thread_runq_local ();
  1863. cpu_flags_t flags;
  1864. spinlock_lock_intr_save (&runq->lock, &flags);
  1865. atomic_store_rlx (&thread->state, THREAD_DEAD);
  1866. thread_runq_schedule (runq);
  1867. panic ("thread: dead thread walking");
  1868. }
  1869. void
  1870. thread_join (struct thread *thread)
  1871. {
  1872. assert (!thread_test_flag (thread, THREAD_DETACHED));
  1873. thread_join_common (thread);
  1874. }
  1875. static int
  1876. thread_wakeup_common (struct thread *thread, int error, bool resume)
  1877. {
  1878. if (!thread || thread == thread_self ())
  1879. return (EINVAL);
  1880. /*
  1881. * There is at most one reference on threads that were never dispatched,
  1882. * in which case there is no need to lock anything.
  1883. */
  1884. struct thread_runq *runq;
  1885. cpu_flags_t flags;
  1886. if (!thread->runq)
  1887. {
  1888. assert (thread->state != THREAD_RUNNING);
  1889. thread_clear_wchan (thread);
  1890. thread->state = THREAD_RUNNING;
  1891. }
  1892. else
  1893. {
  1894. runq = thread_lock_runq (thread, &flags);
  1895. if (thread->state == THREAD_RUNNING ||
  1896. (thread->state == THREAD_SUSPENDED && !resume))
  1897. {
  1898. thread_unlock_runq (runq, flags);
  1899. return (EINVAL);
  1900. }
  1901. thread_clear_wchan (thread);
  1902. atomic_store_rlx (&thread->state, THREAD_RUNNING);
  1903. thread_unlock_runq (runq, flags);
  1904. }
  1905. thread_preempt_disable_intr_save (&flags);
  1906. if (!thread->pin_level)
  1907. runq = thread_get_real_sched_ops(thread)->select_runq (thread);
  1908. else
  1909. {
  1910. /*
  1911. * This access doesn't need to be atomic, as the current thread is
  1912. * the only one which may update the member.
  1913. */
  1914. runq = thread->runq;
  1915. spinlock_lock (&runq->lock);
  1916. }
  1917. thread->wakeup_error = error;
  1918. thread_runq_wakeup (runq, thread);
  1919. spinlock_unlock (&runq->lock);
  1920. thread_preempt_enable_intr_restore (flags);
  1921. return (0);
  1922. }
  1923. int
  1924. thread_wakeup (struct thread *thread)
  1925. {
  1926. return (thread_wakeup_common (thread, 0, false));
  1927. }
  1928. struct thread_timeout_waiter
  1929. {
  1930. struct thread *thread;
  1931. struct timer timer;
  1932. };
  1933. static void
  1934. thread_timeout (struct timer *timer)
  1935. {
  1936. _Auto waiter = structof (timer, struct thread_timeout_waiter, timer);
  1937. thread_wakeup_common (waiter->thread, ETIMEDOUT, false);
  1938. }
  1939. static int
  1940. thread_sleep_common (struct spinlock *interlock, const void *wchan_addr,
  1941. const char *wchan_desc, bool timed, uint64_t ticks)
  1942. {
  1943. struct thread *thread = thread_self ();
  1944. struct thread_timeout_waiter waiter;
  1945. if (timed)
  1946. {
  1947. waiter.thread = thread;
  1948. timer_init (&waiter.timer, thread_timeout, TIMER_INTR);
  1949. timer_schedule (&waiter.timer, ticks);
  1950. }
  1951. _Auto runq = thread_runq_local ();
  1952. cpu_flags_t flags;
  1953. spinlock_lock_intr_save (&runq->lock, &flags);
  1954. if (interlock)
  1955. {
  1956. thread_preempt_disable ();
  1957. spinlock_unlock (interlock);
  1958. }
  1959. thread_set_wchan (thread, wchan_addr, wchan_desc);
  1960. atomic_store_rlx (&thread->state, THREAD_SLEEPING);
  1961. runq = thread_runq_schedule (runq);
  1962. assert (thread->state == THREAD_RUNNING);
  1963. spinlock_unlock_intr_restore (&runq->lock, flags);
  1964. if (timed)
  1965. timer_cancel (&waiter.timer);
  1966. if (interlock)
  1967. {
  1968. spinlock_lock (interlock);
  1969. thread_preempt_enable_no_resched ();
  1970. }
  1971. return (thread->wakeup_error);
  1972. }
  1973. void
  1974. thread_sleep (struct spinlock *lock, const void *wchan_addr,
  1975. const char *wchan_desc)
  1976. {
  1977. int error = thread_sleep_common (lock, wchan_addr, wchan_desc, false, 0);
  1978. assert (! error);
  1979. }
  1980. int
  1981. thread_timedsleep (struct spinlock *lock, const void *wchan_addr,
  1982. const char *wchan_desc, uint64_t ticks)
  1983. {
  1984. return (thread_sleep_common (lock, wchan_addr, wchan_desc, true, ticks));
  1985. }
  1986. int
  1987. thread_suspend (struct thread *thread)
  1988. {
  1989. if (! thread)
  1990. return (EINVAL);
  1991. struct thread_runq_guard g = thread_runq_guard_make (thread, true);
  1992. if (thread == g.runq->idler ||
  1993. thread == g.runq->balancer ||
  1994. thread->state == THREAD_DEAD)
  1995. return (EINVAL);
  1996. else if (thread->state == THREAD_SUSPENDED || thread->suspend)
  1997. return (0);
  1998. else if (thread->state == THREAD_SLEEPING)
  1999. {
  2000. thread->state = THREAD_SUSPENDED;
  2001. return (0);
  2002. }
  2003. assert (thread->state == THREAD_RUNNING);
  2004. if (thread != g.runq->current)
  2005. {
  2006. thread->state = THREAD_SUSPENDED;
  2007. thread_runq_remove (g.runq, thread);
  2008. }
  2009. else
  2010. {
  2011. thread->suspend = true;
  2012. if (g.runq == thread_runq_local ())
  2013. g.runq = thread_runq_schedule (g.runq);
  2014. else
  2015. {
  2016. thread_set_flag (thread, THREAD_YIELD);
  2017. cpu_send_thread_schedule (thread_runq_cpu (g.runq));
  2018. }
  2019. }
  2020. return (0);
  2021. }
  2022. int
  2023. thread_resume (struct thread *thread)
  2024. {
  2025. return (thread_wakeup_common (thread, 0, true));
  2026. }
  2027. void
  2028. thread_delay (uint64_t ticks, bool absolute)
  2029. {
  2030. thread_preempt_disable ();
  2031. if (! absolute)
  2032. // Add a tick to avoid quantization errors.
  2033. ticks += clock_get_time () + 1;
  2034. thread_timedsleep (NULL, thread_self (), "delay", ticks);
  2035. thread_preempt_enable ();
  2036. }
  2037. static void __init
  2038. thread_boot_barrier_wait (void)
  2039. {
  2040. assert (!cpu_intr_enabled ());
  2041. atomic_add_rlx (&thread_nr_boot_cpus, 1);
  2042. while (atomic_load_seq (&thread_nr_boot_cpus) != cpu_count ())
  2043. atomic_spin_nop ();
  2044. }
  2045. void __init
  2046. thread_run_scheduler (void)
  2047. {
  2048. assert (!cpu_intr_enabled ());
  2049. thread_boot_barrier_wait ();
  2050. _Auto runq = thread_runq_local ();
  2051. struct thread *thread = thread_self ();
  2052. assert (thread == runq->current);
  2053. assert (thread->preempt_level == THREAD_SUSPEND_PREEMPT_LEVEL - 1);
  2054. spinlock_lock (&runq->lock);
  2055. thread = thread_runq_get_next (thread_runq_local ());
  2056. spinlock_transfer_owner (&runq->lock, thread);
  2057. tcb_load (&thread->tcb);
  2058. }
  2059. void
  2060. thread_yield (void)
  2061. {
  2062. struct thread *thread = thread_self ();
  2063. if (!thread_preempt_enabled ())
  2064. return;
  2065. do
  2066. {
  2067. thread_preempt_disable ();
  2068. _Auto runq = thread_runq_local ();
  2069. cpu_flags_t flags;
  2070. spinlock_lock_intr_save (&runq->lock, &flags);
  2071. runq = thread_runq_schedule (runq);
  2072. spinlock_unlock_intr_restore (&runq->lock, flags);
  2073. thread_preempt_enable_no_resched ();
  2074. }
  2075. while (thread_test_flag (thread, THREAD_YIELD));
  2076. }
  2077. void
  2078. thread_schedule (void)
  2079. {
  2080. if (unlikely (thread_test_flag (thread_self (), THREAD_YIELD)))
  2081. thread_yield ();
  2082. }
  2083. void
  2084. thread_schedule_intr (void)
  2085. {
  2086. assert (thread_check_intr_context ());
  2087. syscnt_inc (&thread_runq_local()->sc_schedule_intrs);
  2088. }
  2089. void
  2090. thread_report_periodic_event (void)
  2091. {
  2092. assert (thread_check_intr_context ());
  2093. _Auto runq = thread_runq_local ();
  2094. struct thread *thread = thread_self ();
  2095. spinlock_lock (&runq->lock);
  2096. if (!runq->nr_threads)
  2097. thread_balance_idle_tick (runq);
  2098. const _Auto ops = thread_get_real_sched_ops (thread);
  2099. if (ops->tick)
  2100. ops->tick (runq, thread);
  2101. spinlock_unlock (&runq->lock);
  2102. }
  2103. char
  2104. thread_state_to_chr (uint32_t state)
  2105. {
  2106. switch (state)
  2107. {
  2108. case THREAD_RUNNING:
  2109. return ('R');
  2110. case THREAD_SLEEPING:
  2111. return ('S');
  2112. case THREAD_DEAD:
  2113. return ('Z');
  2114. case THREAD_SUSPENDED:
  2115. return ('T');
  2116. default:
  2117. panic ("thread: unknown state");
  2118. }
  2119. }
  2120. const char*
  2121. thread_sched_class_to_str (uint8_t sched_class)
  2122. {
  2123. switch (sched_class)
  2124. {
  2125. case THREAD_SCHED_CLASS_RT:
  2126. return ("rt");
  2127. case THREAD_SCHED_CLASS_FS:
  2128. return ("fs");
  2129. case THREAD_SCHED_CLASS_IDLE:
  2130. return ("idle");
  2131. default:
  2132. panic ("thread: unknown scheduling class");
  2133. }
  2134. }
  2135. static void
  2136. thread_setsched_impl (struct thread *thread, uint8_t policy,
  2137. uint16_t priority)
  2138. {
  2139. struct thread_runq_guard g = thread_runq_guard_make (thread, false);
  2140. if (thread_user_sched_policy (thread) == policy &&
  2141. thread_user_priority (thread) == priority)
  2142. return;
  2143. bool current, requeue = thread->in_runq;
  2144. if (! requeue)
  2145. current = false;
  2146. else
  2147. {
  2148. if (thread != g.runq->current)
  2149. current = false;
  2150. else
  2151. {
  2152. thread_runq_put_prev (g.runq, thread);
  2153. current = true;
  2154. }
  2155. thread_runq_remove (g.runq, thread);
  2156. }
  2157. bool update = true;
  2158. if (thread_user_sched_policy (thread) == policy)
  2159. thread_update_user_priority (thread, priority);
  2160. else
  2161. {
  2162. thread_set_user_sched_policy (thread, policy);
  2163. thread_set_user_sched_class (thread, thread_policy_to_class (policy));
  2164. thread_set_user_priority (thread, priority);
  2165. update = false;
  2166. }
  2167. if (thread->boosted)
  2168. {
  2169. if (thread_user_global_priority (thread) >=
  2170. thread_real_global_priority (thread))
  2171. thread_reset_real_priority (thread);
  2172. }
  2173. else if (update)
  2174. thread_update_real_priority (thread, priority);
  2175. else
  2176. {
  2177. thread_set_real_sched_policy (thread, policy);
  2178. thread_set_real_sched_class (thread, thread_policy_to_class (policy));
  2179. thread_set_real_priority (thread, priority);
  2180. }
  2181. if (requeue)
  2182. {
  2183. thread_runq_add (g.runq, thread);
  2184. if (current)
  2185. thread_runq_set_next (g.runq, thread);
  2186. }
  2187. }
  2188. void
  2189. thread_setscheduler (struct thread *thread, uint8_t policy, uint16_t prio)
  2190. {
  2191. _Auto td = thread_turnstile_td (thread);
  2192. turnstile_td_lock (td);
  2193. thread_setsched_impl (thread, policy, prio);
  2194. turnstile_td_unlock (td);
  2195. turnstile_td_propagate_priority (td);
  2196. }
  2197. static void
  2198. thread_pi_setsched_impl (struct thread_runq *runq, struct thread *thread,
  2199. uint8_t policy, uint16_t prio)
  2200. {
  2201. assert (turnstile_td_locked (thread_turnstile_td (thread)));
  2202. if (thread_real_sched_policy (thread) == policy &&
  2203. thread_real_priority (thread) == prio)
  2204. return;
  2205. const _Auto ops = thread_get_sched_ops (thread_policy_to_class (policy));
  2206. uint32_t global_prio = ops->get_global_priority (prio);
  2207. bool current, requeue = thread->in_runq;
  2208. if (! requeue)
  2209. current = false;
  2210. else
  2211. {
  2212. if (thread != runq->current)
  2213. current = false;
  2214. else
  2215. {
  2216. thread_runq_put_prev (runq, thread);
  2217. current = true;
  2218. }
  2219. thread_runq_remove (runq, thread);
  2220. }
  2221. if (global_prio <= thread_user_global_priority (thread))
  2222. thread_reset_real_priority (thread);
  2223. else
  2224. {
  2225. if (thread_real_sched_policy (thread) == policy)
  2226. thread_update_real_priority (thread, prio);
  2227. else
  2228. {
  2229. thread_set_real_sched_policy (thread, policy);
  2230. thread_set_real_sched_class (thread,
  2231. thread_policy_to_class (policy));
  2232. thread_set_real_priority (thread, prio);
  2233. }
  2234. thread->boosted = true;
  2235. syscnt_inc (&runq->sc_boosts);
  2236. }
  2237. if (requeue)
  2238. {
  2239. thread_runq_add (runq, thread);
  2240. if (current)
  2241. thread_runq_set_next (runq, thread);
  2242. }
  2243. }
  2244. void
  2245. thread_pi_setscheduler (struct thread *thread, uint8_t policy, uint16_t prio)
  2246. {
  2247. struct thread_runq_guard g = thread_runq_guard_make (thread, false);
  2248. thread_pi_setsched_impl (g.runq, thread, policy, prio);
  2249. }
  2250. void
  2251. thread_propagate_priority (void)
  2252. {
  2253. /*
  2254. * Although it's possible to propagate priority with preemption
  2255. * disabled, the operation can be too expensive to allow it.
  2256. */
  2257. if (!thread_preempt_enabled ())
  2258. {
  2259. thread_set_priority_propagation_needed ();
  2260. return;
  2261. }
  2262. struct thread *thread = thread_self ();
  2263. // Clear before propagation to avoid infinite recursion.
  2264. thread->propagate_priority = false;
  2265. turnstile_td_propagate_priority (thread_turnstile_td (thread));
  2266. }
  2267. uint32_t
  2268. thread_cpu (const struct thread *thread)
  2269. {
  2270. const _Auto runq = atomic_load_rlx (&thread->runq);
  2271. return (runq->cpu);
  2272. }
  2273. uint32_t
  2274. thread_state (const struct thread *thread)
  2275. {
  2276. return (atomic_load_rlx (&thread->state));
  2277. }
  2278. bool
  2279. thread_is_running (const struct thread *thread)
  2280. {
  2281. const _Auto runq = atomic_load_rlx (&thread->runq);
  2282. return (runq && atomic_load_rlx (&runq->current) == thread);
  2283. }
  2284. int
  2285. thread_get_affinity (const struct thread *thr, struct cpumap *cpumap)
  2286. {
  2287. if (! thr)
  2288. return (EINVAL);
  2289. struct thread_runq_guard g =
  2290. thread_runq_guard_make ((struct thread *)thr, true);
  2291. cpumap_copy (cpumap, &thr->cpumap);
  2292. return (0);
  2293. }
  2294. int
  2295. thread_set_affinity (struct thread *thread, const struct cpumap *cpumap)
  2296. {
  2297. if (! thread)
  2298. return (EINVAL);
  2299. struct thread_runq_guard g = thread_runq_guard_make (thread, true);
  2300. if (thread == g.runq->idler ||
  2301. thread == g.runq->balancer ||
  2302. thread->state == THREAD_DEAD)
  2303. return (EINVAL);
  2304. else if (cpumap_intersects (&thread->cpumap, cpumap))
  2305. { // The desired CPU map intersects the current one.
  2306. cpumap_copy (&thread->cpumap, cpumap);
  2307. return (0);
  2308. }
  2309. else if (thread->pin_level != 0)
  2310. // The thread is pinned, and cannot be migrated to a different CPU.
  2311. return (EAGAIN);
  2312. // At this point, we know the thread must be migrated.
  2313. cpumap_copy (&thread->cpumap, cpumap);
  2314. if (thread == g.runq->current)
  2315. {
  2316. if (g.runq == thread_runq_local ())
  2317. g.runq = thread_runq_schedule (g.runq);
  2318. else
  2319. {
  2320. thread_set_flag (thread, THREAD_YIELD);
  2321. cpu_send_thread_schedule (thread_runq_cpu (g.runq));
  2322. }
  2323. }
  2324. return (0);
  2325. }
  2326. static ssize_t
  2327. thread_name_impl (struct thread *thread, char *name, bool set)
  2328. {
  2329. SPINLOCK_GUARD (&thread->task->lock);
  2330. if (set)
  2331. memcpy (thread->name, name, sizeof (thread->name));
  2332. else
  2333. memcpy (name, thread->name, sizeof (thread->name));
  2334. return (0);
  2335. }
  2336. static ssize_t
  2337. thread_ipc_affinity_impl (struct thread *thread, void *map,
  2338. uint32_t size, bool set)
  2339. {
  2340. if (! size)
  2341. return (-EINVAL);
  2342. struct cpumap *cpumap;
  2343. if (cpumap_create (&cpumap) != 0)
  2344. return (-ENOMEM);
  2345. cpumap_zero (cpumap);
  2346. size = MIN (size, sizeof (cpumap->cpus));
  2347. int error = user_copy_from (cpumap->cpus, map, size);
  2348. if (error)
  2349. ;
  2350. else if (set)
  2351. error = thread_set_affinity (thread, cpumap);
  2352. else if ((error = thread_get_affinity (thread, cpumap)) == 0)
  2353. error = user_copy_to (map, cpumap->cpus, size);
  2354. cpumap_destroy (cpumap);
  2355. return (-error);
  2356. }
  2357. #define THREAD_IPC_NEEDS_COPY \
  2358. ((1u << THREAD_IPC_GET_NAME) | (1u << THREAD_IPC_GET_AFFINITY) | \
  2359. (1u << THREAD_IPC_GET_ID))
  2360. ssize_t
  2361. thread_handle_msg (struct thread *thr, struct cap_iters *src,
  2362. struct cap_iters *dst, struct ipc_msg_data *data)
  2363. {
  2364. struct thread_ipc_msg tmsg;
  2365. struct ipc_iov_iter k_it;
  2366. ipc_iov_iter_init_buf (&k_it, &tmsg, sizeof (tmsg));
  2367. ssize_t rv = user_copyv_from (&k_it, &src->iov);
  2368. if (rv < 0)
  2369. return (rv);
  2370. switch (tmsg.op)
  2371. {
  2372. case THREAD_IPC_GET_NAME:
  2373. case THREAD_IPC_SET_NAME:
  2374. rv = thread_name_impl (thr, tmsg.name,
  2375. tmsg.op == THREAD_IPC_SET_NAME);
  2376. break;
  2377. case THREAD_IPC_GET_AFFINITY:
  2378. case THREAD_IPC_SET_AFFINITY:
  2379. rv = thread_ipc_affinity_impl (thr, tmsg.cpumap.map, tmsg.cpumap.size,
  2380. tmsg.op == THREAD_IPC_SET_AFFINITY);
  2381. break;
  2382. case THREAD_IPC_GET_ID:
  2383. tmsg.id = thread_id (thr);
  2384. break;
  2385. default:
  2386. return (-EINVAL);
  2387. }
  2388. if (rv == 0 && ((1u << tmsg.op) & THREAD_IPC_NEEDS_COPY))
  2389. {
  2390. ipc_iov_iter_init_buf (&k_it, &tmsg, sizeof (tmsg));
  2391. rv = user_copyv_to (&dst->iov, &k_it);
  2392. }
  2393. (void)data;
  2394. return (rv < 0 ? rv : 0);
  2395. }