thread.c 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834
  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 struct thread_runq*
  549. thread_runq_schedule (struct thread_runq *runq)
  550. {
  551. struct thread *prev = thread_self ();
  552. assert (prev->cur_port ||
  553. (__builtin_frame_address (0) >= prev->stack &&
  554. __builtin_frame_address (0) < prev->stack + TCB_STACK_SIZE));
  555. assert (prev->preempt_level == THREAD_SUSPEND_PREEMPT_LEVEL);
  556. assert (!cpu_intr_enabled ());
  557. assert (spinlock_locked (&runq->lock));
  558. thread_clear_flag (prev, THREAD_YIELD);
  559. thread_runq_put_prev (runq, prev);
  560. if (prev->suspend)
  561. {
  562. prev->state = THREAD_SUSPENDED;
  563. prev->suspend = false;
  564. }
  565. if (prev->state != THREAD_RUNNING)
  566. {
  567. thread_runq_remove (runq, prev);
  568. if (!runq->nr_threads && prev != runq->balancer)
  569. thread_runq_wakeup_balancer (runq);
  570. }
  571. struct thread *next = thread_runq_get_next (runq);
  572. assert (next != runq->idler || !runq->nr_threads);
  573. assert (next->preempt_level == THREAD_SUSPEND_PREEMPT_LEVEL);
  574. if (likely (prev != next))
  575. {
  576. thread_runq_schedule_unload (prev);
  577. rcu_report_context_switch (thread_rcu_reader (prev));
  578. spinlock_transfer_owner (&runq->lock, next);
  579. /*
  580. * This is where the true context switch occurs. The next thread must
  581. * unlock the run queue and reenable preemption. Note that unlocking
  582. * and locking the run queue again is equivalent to a full memory
  583. * barrier.
  584. */
  585. tcb_switch (&prev->tcb, &next->tcb);
  586. /*
  587. * The thread is dispatched on a processor once again.
  588. *
  589. * Keep in mind the system state may have changed a lot since this
  590. * function was called. In particular :
  591. * - The next thread may have been destroyed, and must not be
  592. * referenced any more.
  593. * - The current thread may have been migrated to another processor.
  594. */
  595. barrier ();
  596. thread_runq_schedule_load (prev);
  597. runq = thread_runq_local ();
  598. }
  599. assert (prev->preempt_level == THREAD_SUSPEND_PREEMPT_LEVEL);
  600. assert (!cpu_intr_enabled ());
  601. assert (spinlock_locked (&runq->lock));
  602. return (runq);
  603. }
  604. static void
  605. thread_runq_double_lock (struct thread_runq *a, struct thread_runq *b)
  606. {
  607. assert (!cpu_intr_enabled ());
  608. assert (!thread_preempt_enabled ());
  609. assert (a != b);
  610. if (a->cpu < b->cpu)
  611. {
  612. spinlock_lock (&a->lock);
  613. spinlock_lock (&b->lock);
  614. }
  615. else
  616. {
  617. spinlock_lock (&b->lock);
  618. spinlock_lock (&a->lock);
  619. }
  620. }
  621. static struct thread_runq*
  622. thread_sched_rt_select_runq (struct thread *thread)
  623. {
  624. /*
  625. * Real-time tasks are commonly configured to run on one specific
  626. * processor only.
  627. */
  628. int i = cpumap_find_first (&thread->cpumap);
  629. assert (i >= 0);
  630. assert (cpumap_test (&thread_active_runqs, i));
  631. struct thread_runq *runq = percpu_ptr (thread_runq, i);
  632. spinlock_lock (&runq->lock);
  633. return (runq);
  634. }
  635. static void
  636. thread_sched_rt_add (struct thread_runq *runq, struct thread *thread)
  637. {
  638. struct thread_rt_runq *rt_runq = &runq->rt_runq;
  639. struct list *threads = &rt_runq->threads[thread_real_priority (thread)];
  640. list_insert_tail (threads, &thread->rt_data.node);
  641. if (list_singular (threads))
  642. rt_runq->bitmap |= (1ULL << thread_real_priority (thread));
  643. if (thread_real_sched_class (thread) ==
  644. thread_real_sched_class (runq->current) &&
  645. thread_real_priority (thread) > thread_real_priority (runq->current))
  646. thread_set_flag (runq->current, THREAD_YIELD);
  647. }
  648. static void
  649. thread_sched_rt_remove (struct thread_runq *runq, struct thread *thread)
  650. {
  651. struct thread_rt_runq *rt_runq = &runq->rt_runq;
  652. assert (thread_real_priority (thread) < ARRAY_SIZE (rt_runq->threads));
  653. struct list *threads = &rt_runq->threads[thread_real_priority (thread)];
  654. list_remove (&thread->rt_data.node);
  655. if (list_empty (threads))
  656. rt_runq->bitmap &= ~(1ULL << thread_real_priority (thread));
  657. }
  658. static void
  659. thread_sched_rt_put_prev (struct thread_runq *runq, struct thread *thread)
  660. {
  661. thread_sched_rt_add (runq, thread);
  662. }
  663. static struct thread*
  664. thread_sched_rt_get_next (struct thread_runq *runq)
  665. {
  666. struct thread_rt_runq *rt_runq = &runq->rt_runq;
  667. if (!rt_runq->bitmap)
  668. return (NULL);
  669. uint32_t priority = THREAD_SCHED_RT_PRIO_MAX -
  670. __builtin_clz (rt_runq->bitmap);
  671. assert (priority < ARRAY_SIZE (rt_runq->threads));
  672. struct list *threads = &rt_runq->threads[priority];
  673. assert (!list_empty (threads));
  674. _Auto thread = list_first_entry (threads, struct thread, rt_data.node);
  675. thread_sched_rt_remove (runq, thread);
  676. return (thread);
  677. }
  678. static void
  679. thread_sched_rt_reset_priority (struct thread *thread, uint16_t priority)
  680. {
  681. assert (priority <= THREAD_SCHED_RT_PRIO_MAX);
  682. thread->rt_data.time_slice = THREAD_DEFAULT_RR_TIME_SLICE;
  683. }
  684. static uint32_t
  685. thread_sched_rt_get_global_priority (uint16_t priority)
  686. {
  687. return (THREAD_SCHED_GLOBAL_PRIO_RT + priority);
  688. }
  689. static void
  690. thread_sched_rt_set_next (struct thread_runq *runq, struct thread *thread)
  691. {
  692. thread_sched_rt_remove (runq, thread);
  693. }
  694. static void
  695. thread_sched_rt_tick (struct thread_runq *runq __unused, struct thread *thread)
  696. {
  697. if (thread_real_sched_policy (thread) != THREAD_SCHED_POLICY_RR ||
  698. --thread->rt_data.time_slice > 0)
  699. return;
  700. thread->rt_data.time_slice = THREAD_DEFAULT_RR_TIME_SLICE;
  701. thread_set_flag (thread, THREAD_YIELD);
  702. }
  703. static inline uint16_t
  704. thread_sched_fs_prio2weight (uint16_t priority)
  705. {
  706. return ((priority + 1) * THREAD_FS_ROUND_SLICE_BASE);
  707. }
  708. static struct thread_runq*
  709. thread_sched_fs_select_runq (struct thread *thread)
  710. {
  711. struct thread_runq *runq;
  712. cpumap_for_each (&thread_idle_runqs, i)
  713. {
  714. if (!cpumap_test (&thread->cpumap, i))
  715. continue;
  716. runq = percpu_ptr (thread_runq, i);
  717. spinlock_lock (&runq->lock);
  718. // The run queue really is idle, return it.
  719. if (runq->current == runq->idler)
  720. return (runq);
  721. spinlock_unlock (&runq->lock);
  722. }
  723. runq = NULL;
  724. cpumap_for_each (&thread_active_runqs, i)
  725. {
  726. if (!cpumap_test (&thread->cpumap, i))
  727. continue;
  728. _Auto tmp = percpu_ptr (thread_runq, i);
  729. spinlock_lock (&tmp->lock);
  730. if (! runq)
  731. {
  732. runq = tmp;
  733. continue;
  734. }
  735. // A run queue may have become idle.
  736. if (tmp->current == tmp->idler)
  737. {
  738. spinlock_unlock (&runq->lock);
  739. return (tmp);
  740. }
  741. /*
  742. * The run queue isn't idle, but there are no fair-scheduling thread,
  743. * which means there are real-time threads.
  744. */
  745. if (tmp->fs_weight == 0)
  746. {
  747. spinlock_unlock (&tmp->lock);
  748. continue;
  749. }
  750. ssize_t delta = (ssize_t)(tmp->fs_round - runq->fs_round);
  751. // Look for the least loaded of the run queues in the highest round.
  752. if (delta > 0 ||
  753. (!delta && tmp->fs_weight < runq->fs_weight))
  754. {
  755. spinlock_unlock (&runq->lock);
  756. runq = tmp;
  757. continue;
  758. }
  759. spinlock_unlock (&tmp->lock);
  760. }
  761. assert (runq);
  762. return (runq);
  763. }
  764. static uint32_t
  765. thread_sched_fs_enqueue_scale (uint32_t work, uint32_t old_weight,
  766. uint32_t new_weight)
  767. {
  768. assert (old_weight);
  769. #ifndef __LP64__
  770. if (likely (work < 0x10000 && new_weight < 0x10000))
  771. return ((work * new_weight) / old_weight);
  772. #endif
  773. return ((uint32_t)(((uint64_t)work * new_weight) / old_weight));
  774. }
  775. static void
  776. thread_sched_fs_enqueue (struct thread_fs_runq *fs_runq, size_t round,
  777. struct thread *thread)
  778. {
  779. assert (!thread->fs_data.fs_runq);
  780. assert (thread->fs_data.work <= thread->fs_data.weight);
  781. _Auto group = &fs_runq->group_array[thread_real_priority (thread)];
  782. uint32_t group_weight = group->weight + thread->fs_data.weight,
  783. total_weight = fs_runq->weight + thread->fs_data.weight;
  784. struct list *node = group->weight ?
  785. list_prev (&group->node) : list_last (&fs_runq->groups);
  786. struct list *init_node = node;
  787. while (!list_end (&fs_runq->groups, node))
  788. {
  789. _Auto tmp = list_entry (node, struct thread_fs_group, node);
  790. if (tmp->weight >= group_weight)
  791. break;
  792. node = list_prev (node);
  793. }
  794. if (!group->weight)
  795. list_insert_after (&group->node, node);
  796. else if (node != init_node)
  797. {
  798. list_remove (&group->node);
  799. list_insert_after (&group->node, node);
  800. }
  801. /*
  802. * XXX Unfairness can occur if the run queue round wraps around and the
  803. * thread is "lucky" enough to have the same round value. This should be
  804. * rare and harmless otherwise.
  805. */
  806. if (thread->fs_data.round == round)
  807. {
  808. fs_runq->work += thread->fs_data.work;
  809. group->work += thread->fs_data.work;
  810. }
  811. else
  812. {
  813. uint32_t group_work, thread_work;
  814. if (!fs_runq->weight)
  815. thread_work = 0;
  816. else
  817. {
  818. group_work = group->weight == 0 ?
  819. thread_sched_fs_enqueue_scale (fs_runq->work,
  820. fs_runq->weight,
  821. thread->fs_data.weight) :
  822. thread_sched_fs_enqueue_scale (group->work,
  823. group->weight,
  824. group_weight);
  825. thread_work = group_work - group->work;
  826. fs_runq->work += thread_work;
  827. group->work = group_work;
  828. }
  829. thread->fs_data.round = round;
  830. thread->fs_data.work = thread_work;
  831. }
  832. ++fs_runq->nr_threads;
  833. fs_runq->weight = total_weight;
  834. group->weight = group_weight;
  835. // Insert at the front of the group to improve interactivity.
  836. list_insert_head (&group->threads, &thread->fs_data.group_node);
  837. list_insert_tail (&fs_runq->threads, &thread->fs_data.runq_node);
  838. thread->fs_data.fs_runq = fs_runq;
  839. }
  840. static void
  841. thread_sched_fs_restart (struct thread_runq *runq)
  842. {
  843. _Auto fs_runq = runq->fs_runq_active;
  844. struct list *node = list_first (&fs_runq->groups);
  845. assert (node);
  846. fs_runq->current = list_entry (node, struct thread_fs_group, node);
  847. if (thread_real_sched_class (runq->current) == THREAD_SCHED_CLASS_FS)
  848. thread_set_flag (runq->current, THREAD_YIELD);
  849. }
  850. static void
  851. thread_sched_fs_add (struct thread_runq *runq, struct thread *thread)
  852. {
  853. if (!runq->fs_weight)
  854. runq->fs_round = thread_fs_highest_round;
  855. uint32_t total_weight = runq->fs_weight + thread->fs_data.weight;
  856. // TODO Limit the maximum number of threads to prevent this situation.
  857. if (total_weight < runq->fs_weight)
  858. panic ("thread: weight overflow");
  859. runq->fs_weight = total_weight;
  860. thread_sched_fs_enqueue (runq->fs_runq_active, runq->fs_round, thread);
  861. thread_sched_fs_restart (runq);
  862. }
  863. static void
  864. thread_sched_fs_dequeue (struct thread *thread)
  865. {
  866. assert (thread->fs_data.fs_runq);
  867. _Auto fs_runq = thread->fs_data.fs_runq;
  868. _Auto group = &fs_runq->group_array[thread_real_priority (thread)];
  869. thread->fs_data.fs_runq = NULL;
  870. list_remove (&thread->fs_data.runq_node);
  871. list_remove (&thread->fs_data.group_node);
  872. fs_runq->work -= thread->fs_data.work;
  873. group->work -= thread->fs_data.work;
  874. fs_runq->weight -= thread->fs_data.weight;
  875. group->weight -= thread->fs_data.weight;
  876. --fs_runq->nr_threads;
  877. if (!group->weight)
  878. list_remove (&group->node);
  879. else
  880. {
  881. struct list *node = list_next (&group->node),
  882. *init_node = node;
  883. while (!list_end (&fs_runq->groups, node))
  884. {
  885. _Auto tmp = list_entry (node, struct thread_fs_group, node);
  886. if (tmp->weight <= group->weight)
  887. break;
  888. node = list_next (node);
  889. }
  890. if (node != init_node)
  891. {
  892. list_remove (&group->node);
  893. list_insert_before (&group->node, node);
  894. }
  895. }
  896. }
  897. static void
  898. thread_sched_fs_remove (struct thread_runq *runq, struct thread *thread)
  899. {
  900. runq->fs_weight -= thread->fs_data.weight;
  901. _Auto fs_runq = thread->fs_data.fs_runq;
  902. thread_sched_fs_dequeue (thread);
  903. if (fs_runq != runq->fs_runq_active)
  904. ;
  905. else if (!fs_runq->nr_threads)
  906. thread_runq_wakeup_balancer (runq);
  907. else
  908. thread_sched_fs_restart (runq);
  909. }
  910. static void
  911. thread_sched_fs_deactivate (struct thread_runq *runq, struct thread *thread)
  912. {
  913. assert (thread->fs_data.fs_runq == runq->fs_runq_active);
  914. assert (thread->fs_data.round == runq->fs_round);
  915. thread_sched_fs_dequeue (thread);
  916. ++thread->fs_data.round;
  917. thread->fs_data.work -= thread->fs_data.weight;
  918. thread_sched_fs_enqueue (runq->fs_runq_expired, runq->fs_round + 1, thread);
  919. if (!runq->fs_runq_active->nr_threads)
  920. thread_runq_wakeup_balancer (runq);
  921. }
  922. static void
  923. thread_sched_fs_put_prev (struct thread_runq *runq, struct thread *thread)
  924. {
  925. _Auto fs_runq = runq->fs_runq_active;
  926. assert (thread_real_priority (thread) < ARRAY_SIZE (fs_runq->group_array));
  927. _Auto group = &fs_runq->group_array[thread_real_priority (thread)];
  928. list_insert_tail (&group->threads, &thread->fs_data.group_node);
  929. if (thread->fs_data.work >= thread->fs_data.weight)
  930. thread_sched_fs_deactivate (runq, thread);
  931. }
  932. static int
  933. thread_sched_fs_ratio_exceeded (struct thread_fs_group *current,
  934. struct thread_fs_group *next)
  935. {
  936. #ifndef __LP64__
  937. if (likely (current->weight < 0x10000 && next->weight < 0x10000))
  938. {
  939. uint32_t ia = (current->work + 1) * next->weight,
  940. ib = (next->work + 1) * current->weight;
  941. return (ia > ib);
  942. }
  943. #endif
  944. uint64_t a = ((uint64_t)current->work + 1) * next->weight,
  945. b = ((uint64_t)next->work + 1) * current->weight;
  946. return (a > b);
  947. }
  948. static struct thread*
  949. thread_sched_fs_get_next (struct thread_runq *runq)
  950. {
  951. _Auto fs_runq = runq->fs_runq_active;
  952. if (!fs_runq->nr_threads)
  953. return (NULL);
  954. _Auto group = fs_runq->current;
  955. struct list *node = list_next (&group->node);
  956. if (list_end (&fs_runq->groups, node))
  957. group = list_entry (list_first (&fs_runq->groups),
  958. struct thread_fs_group, node);
  959. else
  960. {
  961. _Auto next = list_entry (node, struct thread_fs_group, node);
  962. group = thread_sched_fs_ratio_exceeded (group, next) ?
  963. next : list_entry (list_first (&fs_runq->groups),
  964. struct thread_fs_group, node);
  965. }
  966. fs_runq->current = group;
  967. return (list_pop (&group->threads, struct thread, fs_data.group_node));
  968. }
  969. static void
  970. thread_sched_fs_reset_priority (struct thread *thread, uint16_t priority)
  971. {
  972. assert (priority <= THREAD_SCHED_FS_PRIO_MAX);
  973. thread->fs_data.fs_runq = NULL;
  974. thread->fs_data.round = 0;
  975. thread->fs_data.weight = thread_sched_fs_prio2weight (priority);
  976. thread->fs_data.work = 0;
  977. }
  978. static void
  979. thread_sched_fs_update_priority (struct thread *thread, uint16_t priority)
  980. {
  981. assert (priority <= THREAD_SCHED_FS_PRIO_MAX);
  982. thread->fs_data.weight = thread_sched_fs_prio2weight (priority);
  983. if (thread->fs_data.work >= thread->fs_data.weight)
  984. thread->fs_data.work = thread->fs_data.weight;
  985. }
  986. static uint32_t
  987. thread_sched_fs_get_global_priority (uint16_t priority __unused)
  988. {
  989. return (THREAD_SCHED_GLOBAL_PRIO_FS);
  990. }
  991. static void
  992. thread_sched_fs_set_next (struct thread_runq *rq __unused, struct thread *thr)
  993. {
  994. list_remove (&thr->fs_data.group_node);
  995. }
  996. static void
  997. thread_sched_fs_tick (struct thread_runq *runq, struct thread *thread)
  998. {
  999. _Auto fs_runq = runq->fs_runq_active;
  1000. ++fs_runq->work;
  1001. _Auto group = &fs_runq->group_array[thread_real_priority (thread)];
  1002. ++group->work;
  1003. thread_set_flag (thread, THREAD_YIELD);
  1004. ++thread->fs_data.work;
  1005. }
  1006. static void
  1007. thread_sched_fs_start_next_round (struct thread_runq *runq)
  1008. {
  1009. _Auto tmp = runq->fs_runq_expired;
  1010. runq->fs_runq_expired = runq->fs_runq_active;
  1011. runq->fs_runq_active = tmp;
  1012. if (runq->fs_runq_active->nr_threads)
  1013. {
  1014. ++runq->fs_round;
  1015. ssize_t delta = (ssize_t)(runq->fs_round - thread_fs_highest_round);
  1016. if (delta > 0)
  1017. thread_fs_highest_round = runq->fs_round;
  1018. thread_sched_fs_restart (runq);
  1019. }
  1020. }
  1021. // Check that a remote run queue satisfies the minimum migration requirements.
  1022. static int
  1023. thread_sched_fs_balance_eligible (struct thread_runq *runq,
  1024. size_t highest_round)
  1025. {
  1026. if (!runq->fs_weight ||
  1027. (runq->fs_round != highest_round &&
  1028. runq->fs_round != highest_round - 1))
  1029. return (0);
  1030. uint32_t nr_threads = runq->fs_runq_active->nr_threads +
  1031. runq->fs_runq_expired->nr_threads;
  1032. if (! nr_threads ||
  1033. (nr_threads == 1 &&
  1034. thread_real_sched_class (runq->current) == THREAD_SCHED_CLASS_FS))
  1035. return (0);
  1036. return (1);
  1037. }
  1038. // Try to find the most suitable run queue from which to pull threads.
  1039. static struct thread_runq*
  1040. thread_sched_fs_balance_scan (struct thread_runq *runq,
  1041. size_t highest_round)
  1042. {
  1043. struct thread_runq *remote_runq = NULL;
  1044. cpu_flags_t flags;
  1045. thread_preempt_disable_intr_save (&flags);
  1046. cpumap_for_each (&thread_active_runqs, i)
  1047. {
  1048. _Auto tmp = percpu_ptr (thread_runq, i);
  1049. if (tmp == runq)
  1050. continue;
  1051. spinlock_lock (&tmp->lock);
  1052. if (!thread_sched_fs_balance_eligible (tmp, highest_round))
  1053. {
  1054. spinlock_unlock (&tmp->lock);
  1055. continue;
  1056. }
  1057. else if (! remote_runq)
  1058. {
  1059. remote_runq = tmp;
  1060. continue;
  1061. }
  1062. else if (tmp->fs_weight > remote_runq->fs_weight)
  1063. {
  1064. spinlock_unlock (&remote_runq->lock);
  1065. remote_runq = tmp;
  1066. continue;
  1067. }
  1068. spinlock_unlock (&tmp->lock);
  1069. }
  1070. if (remote_runq)
  1071. spinlock_unlock (&remote_runq->lock);
  1072. thread_preempt_enable_intr_restore (flags);
  1073. return (remote_runq);
  1074. }
  1075. static uint32_t
  1076. thread_sched_fs_balance_pull (struct thread_runq *runq,
  1077. struct thread_runq *remote_runq,
  1078. struct thread_fs_runq *fs_runq,
  1079. uint32_t nr_pulls)
  1080. {
  1081. int cpu = thread_runq_cpu (runq);
  1082. struct thread *thread, *tmp;
  1083. list_for_each_entry_safe (&fs_runq->threads, thread, tmp,
  1084. fs_data.runq_node)
  1085. {
  1086. if (thread == remote_runq->current)
  1087. continue;
  1088. /*
  1089. * The pin level is changed without explicit synchronization.
  1090. * However, it can only be changed by its owning thread. As threads
  1091. * currently running aren't considered for migration, the thread had
  1092. * to be preempted and invoke the scheduler. Since balancer threads
  1093. * acquire the run queue lock, there is strong ordering between
  1094. * changing the pin level and setting the current thread of a
  1095. * run queue.
  1096. *
  1097. * TODO Review comment.
  1098. */
  1099. if (thread->pin_level || !cpumap_test (&thread->cpumap, cpu))
  1100. continue;
  1101. /*
  1102. * Make sure at least one thread is pulled if possible. If one or more
  1103. * thread has already been pulled, take weights into account.
  1104. */
  1105. if (nr_pulls &&
  1106. runq->fs_weight + thread->fs_data.weight >
  1107. remote_runq->fs_weight - thread->fs_data.weight)
  1108. break;
  1109. thread_runq_remove (remote_runq, thread);
  1110. // Don't discard the work already accounted for.
  1111. thread->fs_data.round = runq->fs_round;
  1112. thread_runq_add (runq, thread);
  1113. if (++nr_pulls == THREAD_MAX_MIGRATIONS)
  1114. break;
  1115. }
  1116. return (nr_pulls);
  1117. }
  1118. static uint32_t
  1119. thread_sched_fs_balance_migrate (struct thread_runq *runq,
  1120. struct thread_runq *remote_runq,
  1121. size_t highest_round)
  1122. {
  1123. uint32_t nr_pulls = 0;
  1124. if (!thread_sched_fs_balance_eligible (remote_runq, highest_round))
  1125. return (nr_pulls);
  1126. nr_pulls = thread_sched_fs_balance_pull (runq, remote_runq,
  1127. remote_runq->fs_runq_active, 0);
  1128. if (nr_pulls == THREAD_MAX_MIGRATIONS)
  1129. return (nr_pulls);
  1130. /*
  1131. * Threads in the expired queue of a processor in round highest are
  1132. * actually in round highest + 1.
  1133. */
  1134. if (remote_runq->fs_round != highest_round)
  1135. nr_pulls = thread_sched_fs_balance_pull (runq, remote_runq,
  1136. remote_runq->fs_runq_expired,
  1137. nr_pulls);
  1138. return (nr_pulls);
  1139. }
  1140. /*
  1141. * Inter-processor load balancing for fair-scheduling threads.
  1142. *
  1143. * Preemption must be disabled, and the local run queue must be locked when
  1144. * calling this function. If balancing actually occurs, the lock will be
  1145. * released and preemption enabled when needed.
  1146. */
  1147. static void
  1148. thread_sched_fs_balance (struct thread_runq *runq, cpu_flags_t *flags)
  1149. {
  1150. /*
  1151. * Grab the highest round now and only use the copy so the value is stable
  1152. * during the balancing operation.
  1153. */
  1154. size_t highest_round = thread_fs_highest_round;
  1155. if (runq->fs_round != highest_round &&
  1156. runq->fs_runq_expired->nr_threads)
  1157. goto no_migration;
  1158. spinlock_unlock_intr_restore (&runq->lock, *flags);
  1159. thread_preempt_enable ();
  1160. uint32_t nr_migrations;
  1161. _Auto remote_runq = thread_sched_fs_balance_scan (runq, highest_round);
  1162. if (remote_runq)
  1163. {
  1164. thread_preempt_disable_intr_save (flags);
  1165. thread_runq_double_lock (runq, remote_runq);
  1166. nr_migrations = thread_sched_fs_balance_migrate (runq, remote_runq,
  1167. highest_round);
  1168. spinlock_unlock (&remote_runq->lock);
  1169. if (nr_migrations)
  1170. return;
  1171. spinlock_unlock_intr_restore (&runq->lock, *flags);
  1172. thread_preempt_enable ();
  1173. }
  1174. /*
  1175. * The scan or the migration failed. As a fallback, make another, simpler
  1176. * pass on every run queue, and stop as soon as at least one thread could
  1177. * be successfully pulled.
  1178. */
  1179. cpumap_for_each (&thread_active_runqs, i)
  1180. {
  1181. remote_runq = percpu_ptr (thread_runq, i);
  1182. if (remote_runq == runq)
  1183. continue;
  1184. thread_preempt_disable_intr_save (flags);
  1185. thread_runq_double_lock (runq, remote_runq);
  1186. nr_migrations = thread_sched_fs_balance_migrate (runq, remote_runq,
  1187. highest_round);
  1188. spinlock_unlock (&remote_runq->lock);
  1189. if (nr_migrations != 0)
  1190. return;
  1191. spinlock_unlock_intr_restore (&runq->lock, *flags);
  1192. thread_preempt_enable ();
  1193. }
  1194. thread_preempt_disable ();
  1195. spinlock_lock_intr_save (&runq->lock, flags);
  1196. no_migration:
  1197. /*
  1198. * No thread could be migrated. Check the active run queue, as another
  1199. * processor might have added threads while the balancer was running.
  1200. * If the run queue is still empty, switch to the next round. The run
  1201. * queue lock must remain held until the next scheduling decision to
  1202. * prevent a remote balancer thread from stealing active threads.
  1203. */
  1204. if (!runq->fs_runq_active->nr_threads)
  1205. thread_sched_fs_start_next_round (runq);
  1206. }
  1207. static struct thread_runq*
  1208. thread_sched_idle_select_runq (struct thread *thread __unused)
  1209. {
  1210. panic ("thread: idler threads cannot be awoken");
  1211. }
  1212. static noreturn void
  1213. thread_sched_idle_panic (void)
  1214. {
  1215. panic ("thread: only idle threads are allowed in the idle class");
  1216. }
  1217. static void
  1218. thread_sched_idle_add (struct thread_runq *runq __unused,
  1219. struct thread *thread __unused)
  1220. {
  1221. thread_sched_idle_panic ();
  1222. }
  1223. #define thread_sched_idle_remove thread_sched_idle_add
  1224. static struct thread*
  1225. thread_sched_idle_get_next (struct thread_runq *runq)
  1226. {
  1227. return (runq->idler);
  1228. }
  1229. static uint32_t
  1230. thread_sched_idle_get_global_priority (uint16_t priority __unused)
  1231. {
  1232. return (THREAD_SCHED_GLOBAL_PRIO_IDLE);
  1233. }
  1234. static const struct thread_sched_ops thread_sched_ops[THREAD_NR_SCHED_CLASSES] =
  1235. {
  1236. [THREAD_SCHED_CLASS_RT] =
  1237. {
  1238. .select_runq = thread_sched_rt_select_runq,
  1239. .add = thread_sched_rt_add,
  1240. .remove = thread_sched_rt_remove,
  1241. .put_prev = thread_sched_rt_put_prev,
  1242. .get_next = thread_sched_rt_get_next,
  1243. .reset_priority = thread_sched_rt_reset_priority,
  1244. .update_priority = NULL,
  1245. .get_global_priority = thread_sched_rt_get_global_priority,
  1246. .set_next = thread_sched_rt_set_next,
  1247. .tick = thread_sched_rt_tick,
  1248. },
  1249. [THREAD_SCHED_CLASS_FS] =
  1250. {
  1251. .select_runq = thread_sched_fs_select_runq,
  1252. .add = thread_sched_fs_add,
  1253. .remove = thread_sched_fs_remove,
  1254. .put_prev = thread_sched_fs_put_prev,
  1255. .get_next = thread_sched_fs_get_next,
  1256. .reset_priority = thread_sched_fs_reset_priority,
  1257. .update_priority = thread_sched_fs_update_priority,
  1258. .get_global_priority = thread_sched_fs_get_global_priority,
  1259. .set_next = thread_sched_fs_set_next,
  1260. .tick = thread_sched_fs_tick,
  1261. },
  1262. [THREAD_SCHED_CLASS_IDLE] =
  1263. {
  1264. .select_runq = thread_sched_idle_select_runq,
  1265. .add = thread_sched_idle_add,
  1266. .remove = thread_sched_idle_remove,
  1267. .put_prev = NULL,
  1268. .get_next = thread_sched_idle_get_next,
  1269. .reset_priority = NULL,
  1270. .update_priority = NULL,
  1271. .get_global_priority = thread_sched_idle_get_global_priority,
  1272. .set_next = NULL,
  1273. .tick = NULL,
  1274. },
  1275. };
  1276. static void
  1277. thread_set_user_sched_policy (struct thread *thread, uint8_t sched_policy)
  1278. {
  1279. thread->user_sched_data.sched_policy = sched_policy;
  1280. }
  1281. static void
  1282. thread_set_user_sched_class (struct thread *thread, uint8_t sched_class)
  1283. {
  1284. thread->user_sched_data.sched_class = sched_class;
  1285. }
  1286. static void
  1287. thread_set_user_priority (struct thread *thread, uint16_t prio)
  1288. {
  1289. const _Auto ops = thread_get_user_sched_ops (thread);
  1290. thread->user_sched_data.priority = prio;
  1291. thread->user_sched_data.global_priority = ops->get_global_priority (prio);
  1292. }
  1293. static void
  1294. thread_update_user_priority (struct thread *thread, uint16_t priority)
  1295. {
  1296. thread_set_user_priority (thread, priority);
  1297. }
  1298. static void
  1299. thread_set_real_sched_policy (struct thread *thread, uint8_t sched_policy)
  1300. {
  1301. thread->real_sched_data.sched_policy = sched_policy;
  1302. }
  1303. static void
  1304. thread_set_real_sched_class (struct thread *thread, uint8_t sched_class)
  1305. {
  1306. thread->real_sched_data.sched_class = sched_class;
  1307. }
  1308. static void
  1309. thread_set_real_priority (struct thread *thread, uint16_t prio)
  1310. {
  1311. const _Auto ops = thread_get_real_sched_ops (thread);
  1312. thread->real_sched_data.priority = prio;
  1313. thread->real_sched_data.global_priority = ops->get_global_priority (prio);
  1314. if (ops->reset_priority)
  1315. ops->reset_priority (thread, prio);
  1316. }
  1317. static void
  1318. thread_update_real_priority (struct thread *thread, uint16_t prio)
  1319. {
  1320. const _Auto ops = thread_get_real_sched_ops (thread);
  1321. thread->real_sched_data.priority = prio;
  1322. thread->real_sched_data.global_priority = ops->get_global_priority (prio);
  1323. if (ops->update_priority)
  1324. ops->update_priority (thread, prio);
  1325. }
  1326. static void
  1327. thread_reset_real_priority (struct thread *thread)
  1328. {
  1329. thread->real_sched_data = thread->user_sched_data;
  1330. thread->boosted = false;
  1331. const _Auto ops = thread_get_user_sched_ops (thread);
  1332. if (ops->reset_priority)
  1333. ops->reset_priority (thread, thread->real_sched_data.priority);
  1334. }
  1335. static void __init
  1336. thread_init_booter (uint32_t cpu)
  1337. {
  1338. // Initialize only what's needed during bootstrap.
  1339. struct thread *booter = &thread_booters[cpu];
  1340. booter->kuid.id = 0;
  1341. booter->kuid.nr_refs = 0; // Make sure booters aren't destroyed.
  1342. booter->flags = 0;
  1343. booter->intr_level = 0;
  1344. booter->preempt_level = 1;
  1345. booter->pagefault_level = 0;
  1346. rcu_reader_init (&booter->rcu_reader);
  1347. cpumap_fill (&booter->cpumap);
  1348. thread_set_user_sched_policy (booter, THREAD_SCHED_POLICY_IDLE);
  1349. thread_set_user_sched_class (booter, THREAD_SCHED_CLASS_IDLE);
  1350. thread_set_user_priority (booter, 0);
  1351. thread_reset_real_priority (booter);
  1352. booter->task = booter->xtask = task_get_kernel_task ();
  1353. snprintf (booter->name, sizeof (booter->name),
  1354. THREAD_KERNEL_PREFIX "thread_boot/%u", cpu);
  1355. }
  1356. static int __init
  1357. thread_setup_booter (void)
  1358. {
  1359. tcb_set_current (&thread_booters[0].tcb);
  1360. thread_init_booter (0);
  1361. return (0);
  1362. }
  1363. INIT_OP_DEFINE (thread_setup_booter,
  1364. INIT_OP_DEP (tcb_setup, true));
  1365. static int __init
  1366. thread_bootstrap (void)
  1367. {
  1368. cpumap_zero (&thread_active_runqs);
  1369. cpumap_zero (&thread_idle_runqs);
  1370. thread_fs_highest_round = THREAD_FS_INITIAL_ROUND;
  1371. cpumap_set (&thread_active_runqs, 0);
  1372. thread_runq_init (cpu_local_ptr (thread_runq), 0, &thread_booters[0]);
  1373. return (0);
  1374. }
  1375. INIT_OP_DEFINE (thread_bootstrap,
  1376. INIT_OP_DEP (syscnt_setup, true),
  1377. INIT_OP_DEP (thread_setup_booter, true));
  1378. void
  1379. thread_main (void (*fn) (void *), void *arg)
  1380. {
  1381. assert (!cpu_intr_enabled ());
  1382. assert (!thread_preempt_enabled ());
  1383. struct thread *thread = thread_self ();
  1384. thread_runq_schedule_load (thread);
  1385. spinlock_unlock (&thread_runq_local()->lock);
  1386. cpu_intr_enable ();
  1387. thread_preempt_enable ();
  1388. fn (arg);
  1389. thread_exit ();
  1390. }
  1391. static int
  1392. thread_init (struct thread *thread, void *stack,
  1393. const struct thread_attr *attr,
  1394. void (*fn) (void *), void *arg)
  1395. {
  1396. struct thread *caller = thread_self ();
  1397. struct task *task = attr->task ?: caller->task;
  1398. struct cpumap *cpumap = attr->cpumap ?: &caller->cpumap;
  1399. assert (attr->policy < ARRAY_SIZE (thread_policy_table));
  1400. kuid_head_init (&thread->kuid);
  1401. thread->flags = 0;
  1402. thread->runq = NULL;
  1403. thread->in_runq = false;
  1404. thread_set_wchan (thread, thread, "init");
  1405. thread->state = THREAD_SLEEPING;
  1406. thread->priv_sleepq = sleepq_create ();
  1407. int error;
  1408. if (!thread->priv_sleepq)
  1409. {
  1410. error = ENOMEM;
  1411. goto error_sleepq;
  1412. }
  1413. thread->priv_turnstile = turnstile_create ();
  1414. if (!thread->priv_turnstile)
  1415. {
  1416. error = ENOMEM;
  1417. goto error_turnstile;
  1418. }
  1419. turnstile_td_init (&thread->turnstile_td);
  1420. thread->propagate_priority = false;
  1421. thread->suspend = false;
  1422. thread->preempt_level = THREAD_SUSPEND_PREEMPT_LEVEL;
  1423. thread->pin_level = 0;
  1424. thread->intr_level = 0;
  1425. thread->pagefault_level = 0;
  1426. rcu_reader_init (&thread->rcu_reader);
  1427. cpumap_copy (&thread->cpumap, cpumap);
  1428. thread_set_user_sched_policy (thread, attr->policy);
  1429. thread_set_user_sched_class (thread, thread_policy_to_class (attr->policy));
  1430. thread_set_user_priority (thread, attr->priority);
  1431. thread_reset_real_priority (thread);
  1432. thread->join_waiter = NULL;
  1433. spinlock_init (&thread->join_lock);
  1434. thread->terminating = false;
  1435. thread->task = thread->xtask = task;
  1436. thread->stack = stack;
  1437. strlcpy (thread->name, attr->name, sizeof (thread->name));
  1438. thread->fixup = NULL;
  1439. thread->cur_port = NULL;
  1440. thread->futex_td = NULL;
  1441. bulletin_init (&thread->dead_subs);
  1442. #ifdef CONFIG_PERFMON
  1443. perfmon_td_init (thread_get_perfmon_td (thread));
  1444. #endif
  1445. if (attr->flags & THREAD_ATTR_DETACHED)
  1446. thread->flags |= THREAD_DETACHED;
  1447. error = tcb_build (&thread->tcb, stack, fn, arg);
  1448. if (error)
  1449. goto error_tcb;
  1450. else if (thread->task != task_get_kernel_task ())
  1451. {
  1452. error = kuid_alloc (&thread->kuid, KUID_THREAD);
  1453. if (error)
  1454. goto error_kuid;
  1455. }
  1456. task_add_thread (task, thread);
  1457. return (0);
  1458. error_kuid:
  1459. tcb_cleanup (&thread->tcb);
  1460. error_tcb:
  1461. turnstile_destroy (thread->priv_turnstile);
  1462. error_turnstile:
  1463. sleepq_destroy (thread->priv_sleepq);
  1464. error_sleepq:
  1465. return (error);
  1466. }
  1467. #ifdef CONFIG_THREAD_STACK_GUARD
  1468. #include <machine/pmap.h>
  1469. #include <vm/kmem.h>
  1470. #include <vm/page.h>
  1471. static void*
  1472. thread_alloc_stack (void)
  1473. {
  1474. _Auto kernel_pmap = pmap_get_kernel_pmap ();
  1475. size_t stack_size = vm_page_round (TCB_STACK_SIZE);
  1476. void *mem = vm_kmem_alloc ((PAGE_SIZE * 2) + stack_size);
  1477. if (! mem)
  1478. return (NULL);
  1479. uintptr_t va = (uintptr_t)mem;
  1480. /*
  1481. * TODO Until memory protection is implemented, use the pmap system
  1482. * to remove mappings.
  1483. */
  1484. phys_addr_t first_pa, last_pa;
  1485. int error = pmap_kextract (va, &first_pa);
  1486. assert (! error);
  1487. error = pmap_kextract (va + PAGE_SIZE + stack_size, &last_pa);
  1488. assert (! error);
  1489. _Auto first_page = vm_page_lookup (first_pa);
  1490. assert (first_page);
  1491. _Auto last_page = vm_page_lookup (last_pa);
  1492. assert (last_page);
  1493. pmap_remove (kernel_pmap, va, PMAP_PEF_GLOBAL);
  1494. pmap_remove (kernel_pmap, va + PAGE_SIZE + stack_size,
  1495. PMAP_PEF_GLOBAL | PMAP_IGNORE_ERRORS);
  1496. pmap_update (kernel_pmap);
  1497. return ((char *)va + PAGE_SIZE);
  1498. }
  1499. static void
  1500. thread_free_stack (void *stack)
  1501. {
  1502. size_t stack_size = vm_page_round (TCB_STACK_SIZE);
  1503. void *va = (char *)stack - PAGE_SIZE;
  1504. vm_kmem_free (va, (PAGE_SIZE * 2) + stack_size);
  1505. }
  1506. #else // CONFIG_THREAD_STACK_GUARD
  1507. static void*
  1508. thread_alloc_stack (void)
  1509. {
  1510. return (kmem_cache_alloc (&thread_stack_cache));
  1511. }
  1512. static void
  1513. thread_free_stack (void *stack)
  1514. {
  1515. kmem_cache_free (&thread_stack_cache, stack);
  1516. }
  1517. #endif
  1518. static void
  1519. thread_destroy (struct thread *thread)
  1520. {
  1521. assert (thread != thread_self ());
  1522. assert (thread->state == THREAD_DEAD);
  1523. // See task_info().
  1524. task_remove_thread (thread->task, thread);
  1525. turnstile_destroy (thread->priv_turnstile);
  1526. sleepq_destroy (thread->priv_sleepq);
  1527. thread_free_stack (thread->stack);
  1528. tcb_cleanup (&thread->tcb);
  1529. kmem_cache_free (&thread_cache, thread);
  1530. }
  1531. static void
  1532. thread_join_common (struct thread *thread)
  1533. {
  1534. struct thread *self = thread_self ();
  1535. assert (thread != self);
  1536. spinlock_lock (&thread->join_lock);
  1537. assert (!thread->join_waiter);
  1538. thread->join_waiter = self;
  1539. while (!thread->terminating)
  1540. thread_sleep (&thread->join_lock, thread, "exit");
  1541. spinlock_unlock (&thread->join_lock);
  1542. uint32_t state;
  1543. do
  1544. {
  1545. struct thread_runq_guard g = thread_runq_guard_make (thread, false);
  1546. state = thread->state;
  1547. }
  1548. while (state != THREAD_DEAD);
  1549. thread_destroy (thread);
  1550. }
  1551. void
  1552. thread_terminate (struct thread *thread)
  1553. {
  1554. SPINLOCK_GUARD (&thread->join_lock);
  1555. thread->terminating = true;
  1556. cap_notify_dead (&thread->dead_subs);
  1557. kuid_remove (&thread->kuid, KUID_THREAD);
  1558. thread_wakeup (thread->join_waiter);
  1559. }
  1560. static void
  1561. thread_balance_idle_tick (struct thread_runq *runq)
  1562. {
  1563. assert (runq->idle_balance_ticks != 0);
  1564. /*
  1565. * Interrupts can occur early, at a time the balancer thread hasn't been
  1566. * created yet.
  1567. */
  1568. if (runq->balancer &&
  1569. --runq->idle_balance_ticks == 0)
  1570. thread_runq_wakeup_balancer (runq);
  1571. }
  1572. static void
  1573. thread_balance (void *arg)
  1574. {
  1575. struct thread_runq *runq = arg;
  1576. struct thread *self = runq->balancer;
  1577. assert (self == runq->balancer);
  1578. thread_preempt_disable ();
  1579. cpu_flags_t flags;
  1580. spinlock_lock_intr_save (&runq->lock, &flags);
  1581. while (1)
  1582. {
  1583. runq->idle_balance_ticks = THREAD_IDLE_BALANCE_TICKS;
  1584. thread_set_wchan (self, runq, "runq");
  1585. atomic_store_rlx (&self->state, THREAD_SLEEPING);
  1586. runq = thread_runq_schedule (runq);
  1587. assert (runq == arg);
  1588. /*
  1589. * This function may temporarily enable preemption and release the
  1590. * run queue lock, but on return, the lock must remain held until this
  1591. * balancer thread sleeps.
  1592. */
  1593. thread_sched_fs_balance (runq, &flags);
  1594. }
  1595. }
  1596. static void __init
  1597. thread_setup_balancer (struct thread_runq *runq)
  1598. {
  1599. struct cpumap *cpumap;
  1600. if (cpumap_create (&cpumap) != 0)
  1601. panic ("thread: unable to create balancer thread CPU map");
  1602. cpumap_zero (cpumap);
  1603. cpumap_set (cpumap, thread_runq_cpu (runq));
  1604. char name[THREAD_NAME_SIZE];
  1605. snprintf (name, sizeof (name), THREAD_KERNEL_PREFIX "thread_balance/%u",
  1606. thread_runq_cpu (runq));
  1607. struct thread_attr attr;
  1608. thread_attr_init (&attr, name);
  1609. thread_attr_set_cpumap (&attr, cpumap);
  1610. thread_attr_set_policy (&attr, THREAD_SCHED_POLICY_FIFO);
  1611. thread_attr_set_priority (&attr, THREAD_SCHED_RT_PRIO_MIN);
  1612. int error = thread_create (&runq->balancer, &attr, thread_balance, runq);
  1613. cpumap_destroy (cpumap);
  1614. if (error)
  1615. panic ("thread: unable to create balancer thread");
  1616. }
  1617. static void
  1618. thread_idle (void *arg __unused)
  1619. {
  1620. struct thread *self = thread_self ();
  1621. while (1)
  1622. {
  1623. thread_preempt_disable ();
  1624. while (1)
  1625. {
  1626. cpu_intr_disable ();
  1627. if (thread_test_flag (self, THREAD_YIELD))
  1628. {
  1629. cpu_intr_enable ();
  1630. break;
  1631. }
  1632. cpu_idle ();
  1633. }
  1634. thread_preempt_enable ();
  1635. }
  1636. }
  1637. static void __init
  1638. thread_setup_idler (struct thread_runq *runq)
  1639. {
  1640. struct cpumap *cpumap;
  1641. if (cpumap_create (&cpumap) != 0)
  1642. panic ("thread: unable to allocate idler thread CPU map");
  1643. cpumap_zero (cpumap);
  1644. cpumap_set (cpumap, thread_runq_cpu (runq));
  1645. struct thread *idler = kmem_cache_alloc (&thread_cache);
  1646. if (! idler)
  1647. panic ("thread: unable to allocate idler thread");
  1648. void *stack = thread_alloc_stack ();
  1649. if (! stack)
  1650. panic ("thread: unable to allocate idler thread stack");
  1651. char name[THREAD_NAME_SIZE];
  1652. snprintf (name, sizeof (name), THREAD_KERNEL_PREFIX "thread_idle/%u",
  1653. thread_runq_cpu (runq));
  1654. struct thread_attr attr;
  1655. thread_attr_init (&attr, name);
  1656. thread_attr_set_cpumap (&attr, cpumap);
  1657. thread_attr_set_policy (&attr, THREAD_SCHED_POLICY_IDLE);
  1658. if (thread_init (idler, stack, &attr, thread_idle, NULL) != 0)
  1659. panic ("thread: unable to initialize idler thread");
  1660. cpumap_destroy (cpumap);
  1661. // An idler thread needs special tuning.
  1662. thread_clear_wchan (idler);
  1663. idler->state = THREAD_RUNNING;
  1664. idler->runq = runq;
  1665. runq->idler = idler;
  1666. }
  1667. static void __init
  1668. thread_setup_runq (struct thread_runq *runq)
  1669. {
  1670. thread_setup_balancer (runq);
  1671. thread_setup_idler (runq);
  1672. }
  1673. #ifdef CONFIG_SHELL
  1674. /*
  1675. * This function is meant for debugging only. As a result, it uses a weak
  1676. * locking policy which allows tracing threads which state may mutate during
  1677. * tracing.
  1678. */
  1679. static void
  1680. thread_shell_trace (struct shell *shell, int argc, char **argv)
  1681. {
  1682. if (argc != 3)
  1683. {
  1684. stream_puts (shell->stream, "usage: thread_trace task thread\n");
  1685. return;
  1686. }
  1687. const char *task_name = argv[1], *thread_name = argv[2];
  1688. struct task *task = task_lookup (task_name);
  1689. if (! task)
  1690. {
  1691. fmt_xprintf (shell->stream, "thread_trace: task not found: %s\n",
  1692. task_name);
  1693. return;
  1694. }
  1695. struct thread *thread = task_lookup_thread (task, thread_name);
  1696. task_unref (task);
  1697. if (! thread)
  1698. {
  1699. fmt_xprintf (shell->stream, "thread_trace: thread not found: %s\n",
  1700. thread_name);
  1701. return;
  1702. }
  1703. cpu_flags_t flags;
  1704. _Auto runq = thread_lock_runq (thread, &flags);
  1705. if (thread == runq->current)
  1706. stream_puts (shell->stream, "thread_trace: thread is running\n");
  1707. else
  1708. tcb_trace (&thread->tcb);
  1709. thread_unlock_runq (runq, flags);
  1710. thread_unref (thread);
  1711. }
  1712. static struct shell_cmd thread_shell_cmds[] =
  1713. {
  1714. SHELL_CMD_INITIALIZER ("thread_trace", thread_shell_trace,
  1715. "thread_trace <task_name> <thread_name>",
  1716. "display the stack trace of a given thread"),
  1717. };
  1718. static int __init
  1719. thread_setup_shell (void)
  1720. {
  1721. SHELL_REGISTER_CMDS (thread_shell_cmds, shell_get_main_cmd_set ());
  1722. return (0);
  1723. }
  1724. INIT_OP_DEFINE (thread_setup_shell,
  1725. INIT_OP_DEP (printf_setup, true),
  1726. INIT_OP_DEP (shell_setup, true),
  1727. INIT_OP_DEP (task_setup, true),
  1728. INIT_OP_DEP (thread_setup, true));
  1729. #endif
  1730. static void __init
  1731. thread_setup_common (uint32_t cpu)
  1732. {
  1733. assert (cpu);
  1734. cpumap_set (&thread_active_runqs, cpu);
  1735. thread_init_booter (cpu);
  1736. thread_runq_init (percpu_ptr (thread_runq, cpu), cpu, &thread_booters[cpu]);
  1737. }
  1738. static int __init
  1739. thread_setup (void)
  1740. {
  1741. for (uint32_t cpu = 1; cpu < cpu_count (); ++cpu)
  1742. thread_setup_common (cpu);
  1743. kmem_cache_init (&thread_cache, "thread", sizeof (struct thread),
  1744. CPU_L1_SIZE, NULL, 0);
  1745. #ifndef CONFIG_THREAD_STACK_GUARD
  1746. kmem_cache_init (&thread_stack_cache, "thread_stack", TCB_STACK_SIZE,
  1747. CPU_DATA_ALIGN, NULL, 0);
  1748. #endif
  1749. cpumap_for_each (&thread_active_runqs, cpu)
  1750. thread_setup_runq (percpu_ptr (thread_runq, cpu));
  1751. return (0);
  1752. }
  1753. #ifdef CONFIG_THREAD_STACK_GUARD
  1754. #define THREAD_STACK_GUARD_INIT_OP_DEPS \
  1755. INIT_OP_DEP (vm_kmem_setup, true), \
  1756. INIT_OP_DEP (vm_map_setup, true), \
  1757. INIT_OP_DEP (vm_page_setup, true),
  1758. #else
  1759. #define THREAD_STACK_GUARD_INIT_OP_DEPS
  1760. #endif
  1761. #ifdef CONFIG_PERFMON
  1762. #define THREAD_PERFMON_INIT_OP_DEPS INIT_OP_DEP (perfmon_bootstrap, true),
  1763. #else
  1764. #define THREAD_PERFMON_INIT_OP_DEPS
  1765. #endif
  1766. INIT_OP_DEFINE (thread_setup,
  1767. INIT_OP_DEP (cpumap_setup, true),
  1768. INIT_OP_DEP (kmem_setup, true),
  1769. INIT_OP_DEP (pmap_setup, true),
  1770. INIT_OP_DEP (sleepq_setup, true),
  1771. INIT_OP_DEP (task_setup, true),
  1772. INIT_OP_DEP (thread_bootstrap, true),
  1773. INIT_OP_DEP (turnstile_setup, true),
  1774. THREAD_STACK_GUARD_INIT_OP_DEPS
  1775. THREAD_PERFMON_INIT_OP_DEPS);
  1776. void __init
  1777. thread_ap_setup (void)
  1778. {
  1779. tcb_set_current (&thread_booters[cpu_id ()].tcb);
  1780. }
  1781. int
  1782. thread_create (struct thread **threadp, const struct thread_attr *attr,
  1783. void (*fn) (void *), void *arg)
  1784. {
  1785. int error;
  1786. if (attr->cpumap)
  1787. {
  1788. error = cpumap_check (attr->cpumap);
  1789. if (error)
  1790. return (error);
  1791. }
  1792. struct thread *thread = kmem_cache_alloc (&thread_cache);
  1793. if (! thread)
  1794. {
  1795. error = ENOMEM;
  1796. goto error_thread;
  1797. }
  1798. void *stack = thread_alloc_stack ();
  1799. if (! stack)
  1800. {
  1801. error = ENOMEM;
  1802. goto error_stack;
  1803. }
  1804. error = thread_init (thread, stack, attr, fn, arg);
  1805. if (error)
  1806. goto error_init;
  1807. /*
  1808. * The new thread address must be written before the thread is started
  1809. * in case it's passed to it.
  1810. */
  1811. if (threadp)
  1812. *threadp = thread;
  1813. thread_wakeup (thread);
  1814. return (0);
  1815. error_init:
  1816. thread_free_stack (stack);
  1817. error_stack:
  1818. kmem_cache_free (&thread_cache, thread);
  1819. error_thread:
  1820. return (error);
  1821. }
  1822. static void
  1823. thread_reap (struct work *work)
  1824. {
  1825. _Auto zombie = structof (work, struct thread_zombie, work);
  1826. thread_join_common (zombie->thread);
  1827. }
  1828. void
  1829. thread_exit (void)
  1830. {
  1831. struct thread_zombie zombie;
  1832. struct thread *thread = thread_self ();
  1833. if (likely (thread->task != task_get_kernel_task ()))
  1834. turnstile_td_exit (&thread->turnstile_td);
  1835. futex_td_exit (thread->futex_td);
  1836. if (thread_test_flag (thread, THREAD_DETACHED))
  1837. {
  1838. zombie.thread = thread;
  1839. work_init (&zombie.work, thread_reap);
  1840. work_schedule (&zombie.work, 0);
  1841. }
  1842. /*
  1843. * Disable preemption before dropping the reference, as this may
  1844. * trigger the active state poll of the join operation. Doing so
  1845. * keeps the duration of that active wait minimum.
  1846. */
  1847. thread_preempt_disable ();
  1848. thread_unref (thread);
  1849. _Auto runq = thread_runq_local ();
  1850. cpu_flags_t flags;
  1851. spinlock_lock_intr_save (&runq->lock, &flags);
  1852. atomic_store_rlx (&thread->state, THREAD_DEAD);
  1853. thread_runq_schedule (runq);
  1854. panic ("thread: dead thread walking");
  1855. }
  1856. void
  1857. thread_join (struct thread *thread)
  1858. {
  1859. assert (!thread_test_flag (thread, THREAD_DETACHED));
  1860. thread_join_common (thread);
  1861. }
  1862. static int
  1863. thread_wakeup_common (struct thread *thread, int error, bool resume)
  1864. {
  1865. if (!thread || thread == thread_self ())
  1866. return (EINVAL);
  1867. /*
  1868. * There is at most one reference on threads that were never dispatched,
  1869. * in which case there is no need to lock anything.
  1870. */
  1871. struct thread_runq *runq;
  1872. cpu_flags_t flags;
  1873. if (!thread->runq)
  1874. {
  1875. assert (thread->state != THREAD_RUNNING);
  1876. thread_clear_wchan (thread);
  1877. thread->state = THREAD_RUNNING;
  1878. }
  1879. else
  1880. {
  1881. runq = thread_lock_runq (thread, &flags);
  1882. if (thread->state == THREAD_RUNNING ||
  1883. (thread->state == THREAD_SUSPENDED && !resume))
  1884. {
  1885. thread_unlock_runq (runq, flags);
  1886. return (EINVAL);
  1887. }
  1888. thread_clear_wchan (thread);
  1889. atomic_store_rlx (&thread->state, THREAD_RUNNING);
  1890. thread_unlock_runq (runq, flags);
  1891. }
  1892. thread_preempt_disable_intr_save (&flags);
  1893. if (!thread->pin_level)
  1894. runq = thread_get_real_sched_ops(thread)->select_runq (thread);
  1895. else
  1896. {
  1897. /*
  1898. * This access doesn't need to be atomic, as the current thread is
  1899. * the only one which may update the member.
  1900. */
  1901. runq = thread->runq;
  1902. spinlock_lock (&runq->lock);
  1903. }
  1904. thread->wakeup_error = error;
  1905. thread_runq_wakeup (runq, thread);
  1906. spinlock_unlock (&runq->lock);
  1907. thread_preempt_enable_intr_restore (flags);
  1908. return (0);
  1909. }
  1910. int
  1911. thread_wakeup (struct thread *thread)
  1912. {
  1913. return (thread_wakeup_common (thread, 0, false));
  1914. }
  1915. struct thread_timeout_waiter
  1916. {
  1917. struct thread *thread;
  1918. struct timer timer;
  1919. };
  1920. static void
  1921. thread_timeout (struct timer *timer)
  1922. {
  1923. _Auto waiter = structof (timer, struct thread_timeout_waiter, timer);
  1924. thread_wakeup_common (waiter->thread, ETIMEDOUT, false);
  1925. }
  1926. static int
  1927. thread_sleep_common (struct spinlock *interlock, const void *wchan_addr,
  1928. const char *wchan_desc, bool timed, uint64_t ticks)
  1929. {
  1930. struct thread *thread = thread_self ();
  1931. struct thread_timeout_waiter waiter;
  1932. if (timed)
  1933. {
  1934. waiter.thread = thread;
  1935. timer_init (&waiter.timer, thread_timeout, TIMER_INTR);
  1936. timer_schedule (&waiter.timer, ticks);
  1937. }
  1938. _Auto runq = thread_runq_local ();
  1939. cpu_flags_t flags;
  1940. spinlock_lock_intr_save (&runq->lock, &flags);
  1941. if (interlock)
  1942. {
  1943. thread_preempt_disable ();
  1944. spinlock_unlock (interlock);
  1945. }
  1946. thread_set_wchan (thread, wchan_addr, wchan_desc);
  1947. atomic_store_rlx (&thread->state, THREAD_SLEEPING);
  1948. runq = thread_runq_schedule (runq);
  1949. assert (thread->state == THREAD_RUNNING);
  1950. spinlock_unlock_intr_restore (&runq->lock, flags);
  1951. if (timed)
  1952. timer_cancel (&waiter.timer);
  1953. if (interlock)
  1954. {
  1955. spinlock_lock (interlock);
  1956. thread_preempt_enable_no_resched ();
  1957. }
  1958. return (thread->wakeup_error);
  1959. }
  1960. void
  1961. thread_sleep (struct spinlock *lock, const void *wchan_addr,
  1962. const char *wchan_desc)
  1963. {
  1964. int error = thread_sleep_common (lock, wchan_addr, wchan_desc, false, 0);
  1965. assert (! error);
  1966. }
  1967. int
  1968. thread_timedsleep (struct spinlock *lock, const void *wchan_addr,
  1969. const char *wchan_desc, uint64_t ticks)
  1970. {
  1971. return (thread_sleep_common (lock, wchan_addr, wchan_desc, true, ticks));
  1972. }
  1973. int
  1974. thread_suspend (struct thread *thread)
  1975. {
  1976. if (! thread)
  1977. return (EINVAL);
  1978. struct thread_runq_guard g = thread_runq_guard_make (thread, true);
  1979. if (thread == g.runq->idler ||
  1980. thread == g.runq->balancer ||
  1981. thread->state == THREAD_DEAD)
  1982. return (EINVAL);
  1983. else if (thread->state == THREAD_SUSPENDED || thread->suspend)
  1984. return (0);
  1985. else if (thread->state == THREAD_SLEEPING)
  1986. {
  1987. thread->state = THREAD_SUSPENDED;
  1988. return (0);
  1989. }
  1990. assert (thread->state == THREAD_RUNNING);
  1991. if (thread != g.runq->current)
  1992. {
  1993. thread->state = THREAD_SUSPENDED;
  1994. thread_runq_remove (g.runq, thread);
  1995. }
  1996. else
  1997. {
  1998. thread->suspend = true;
  1999. if (g.runq == thread_runq_local ())
  2000. g.runq = thread_runq_schedule (g.runq);
  2001. else
  2002. {
  2003. thread_set_flag (thread, THREAD_YIELD);
  2004. cpu_send_thread_schedule (thread_runq_cpu (g.runq));
  2005. }
  2006. }
  2007. return (0);
  2008. }
  2009. int
  2010. thread_resume (struct thread *thread)
  2011. {
  2012. return (thread_wakeup_common (thread, 0, true));
  2013. }
  2014. void
  2015. thread_delay (uint64_t ticks, bool absolute)
  2016. {
  2017. thread_preempt_disable ();
  2018. if (! absolute)
  2019. // Add a tick to avoid quantization errors.
  2020. ticks += clock_get_time () + 1;
  2021. thread_timedsleep (NULL, thread_self (), "delay", ticks);
  2022. thread_preempt_enable ();
  2023. }
  2024. static void __init
  2025. thread_boot_barrier_wait (void)
  2026. {
  2027. assert (!cpu_intr_enabled ());
  2028. atomic_add_rlx (&thread_nr_boot_cpus, 1);
  2029. while (atomic_load_seq (&thread_nr_boot_cpus) != cpu_count ())
  2030. cpu_pause ();
  2031. }
  2032. void __init
  2033. thread_run_scheduler (void)
  2034. {
  2035. assert (!cpu_intr_enabled ());
  2036. thread_boot_barrier_wait ();
  2037. _Auto runq = thread_runq_local ();
  2038. struct thread *thread = thread_self ();
  2039. assert (thread == runq->current);
  2040. assert (thread->preempt_level == THREAD_SUSPEND_PREEMPT_LEVEL - 1);
  2041. spinlock_lock (&runq->lock);
  2042. thread = thread_runq_get_next (thread_runq_local ());
  2043. spinlock_transfer_owner (&runq->lock, thread);
  2044. tcb_load (&thread->tcb);
  2045. }
  2046. void
  2047. thread_yield (void)
  2048. {
  2049. struct thread *thread = thread_self ();
  2050. if (!thread_preempt_enabled ())
  2051. return;
  2052. do
  2053. {
  2054. thread_preempt_disable ();
  2055. _Auto runq = thread_runq_local ();
  2056. cpu_flags_t flags;
  2057. spinlock_lock_intr_save (&runq->lock, &flags);
  2058. runq = thread_runq_schedule (runq);
  2059. spinlock_unlock_intr_restore (&runq->lock, flags);
  2060. thread_preempt_enable_no_resched ();
  2061. }
  2062. while (thread_test_flag (thread, THREAD_YIELD));
  2063. }
  2064. void
  2065. thread_schedule (void)
  2066. {
  2067. if (unlikely (thread_test_flag (thread_self (), THREAD_YIELD)))
  2068. thread_yield ();
  2069. }
  2070. void
  2071. thread_schedule_intr (void)
  2072. {
  2073. assert (thread_check_intr_context ());
  2074. syscnt_inc (&thread_runq_local()->sc_schedule_intrs);
  2075. }
  2076. void
  2077. thread_report_periodic_event (void)
  2078. {
  2079. assert (thread_check_intr_context ());
  2080. _Auto runq = thread_runq_local ();
  2081. struct thread *thread = thread_self ();
  2082. spinlock_lock (&runq->lock);
  2083. if (!runq->nr_threads)
  2084. thread_balance_idle_tick (runq);
  2085. const _Auto ops = thread_get_real_sched_ops (thread);
  2086. if (ops->tick)
  2087. ops->tick (runq, thread);
  2088. spinlock_unlock (&runq->lock);
  2089. }
  2090. char
  2091. thread_state_to_chr (uint32_t state)
  2092. {
  2093. switch (state)
  2094. {
  2095. case THREAD_RUNNING:
  2096. return ('R');
  2097. case THREAD_SLEEPING:
  2098. return ('S');
  2099. case THREAD_DEAD:
  2100. return ('Z');
  2101. case THREAD_SUSPENDED:
  2102. return ('T');
  2103. default:
  2104. panic ("thread: unknown state");
  2105. }
  2106. }
  2107. const char*
  2108. thread_sched_class_to_str (uint8_t sched_class)
  2109. {
  2110. switch (sched_class)
  2111. {
  2112. case THREAD_SCHED_CLASS_RT:
  2113. return ("rt");
  2114. case THREAD_SCHED_CLASS_FS:
  2115. return ("fs");
  2116. case THREAD_SCHED_CLASS_IDLE:
  2117. return ("idle");
  2118. default:
  2119. panic ("thread: unknown scheduling class");
  2120. }
  2121. }
  2122. static void
  2123. thread_setsched_impl (struct thread *thread, uint8_t policy,
  2124. uint16_t priority)
  2125. {
  2126. struct thread_runq_guard g = thread_runq_guard_make (thread, false);
  2127. if (thread_user_sched_policy (thread) == policy &&
  2128. thread_user_priority (thread) == priority)
  2129. return;
  2130. bool current, requeue = thread->in_runq;
  2131. if (! requeue)
  2132. current = false;
  2133. else
  2134. {
  2135. if (thread != g.runq->current)
  2136. current = false;
  2137. else
  2138. {
  2139. thread_runq_put_prev (g.runq, thread);
  2140. current = true;
  2141. }
  2142. thread_runq_remove (g.runq, thread);
  2143. }
  2144. bool update = true;
  2145. if (thread_user_sched_policy (thread) == policy)
  2146. thread_update_user_priority (thread, priority);
  2147. else
  2148. {
  2149. thread_set_user_sched_policy (thread, policy);
  2150. thread_set_user_sched_class (thread, thread_policy_to_class (policy));
  2151. thread_set_user_priority (thread, priority);
  2152. update = false;
  2153. }
  2154. if (thread->boosted)
  2155. {
  2156. if (thread_user_global_priority (thread) >=
  2157. thread_real_global_priority (thread))
  2158. thread_reset_real_priority (thread);
  2159. }
  2160. else if (update)
  2161. thread_update_real_priority (thread, priority);
  2162. else
  2163. {
  2164. thread_set_real_sched_policy (thread, policy);
  2165. thread_set_real_sched_class (thread, thread_policy_to_class (policy));
  2166. thread_set_real_priority (thread, priority);
  2167. }
  2168. if (requeue)
  2169. {
  2170. thread_runq_add (g.runq, thread);
  2171. if (current)
  2172. thread_runq_set_next (g.runq, thread);
  2173. }
  2174. }
  2175. void
  2176. thread_setscheduler (struct thread *thread, uint8_t policy, uint16_t prio)
  2177. {
  2178. _Auto td = thread_turnstile_td (thread);
  2179. turnstile_td_lock (td);
  2180. thread_setsched_impl (thread, policy, prio);
  2181. turnstile_td_unlock (td);
  2182. turnstile_td_propagate_priority (td);
  2183. }
  2184. static void
  2185. thread_pi_setsched_impl (struct thread_runq *runq, struct thread *thread,
  2186. uint8_t policy, uint16_t prio)
  2187. {
  2188. assert (turnstile_td_locked (thread_turnstile_td (thread)));
  2189. if (thread_real_sched_policy (thread) == policy &&
  2190. thread_real_priority (thread) == prio)
  2191. return;
  2192. const _Auto ops = thread_get_sched_ops (thread_policy_to_class (policy));
  2193. uint32_t global_prio = ops->get_global_priority (prio);
  2194. bool current, requeue = thread->in_runq;
  2195. if (! requeue)
  2196. current = false;
  2197. else
  2198. {
  2199. if (thread != runq->current)
  2200. current = false;
  2201. else
  2202. {
  2203. thread_runq_put_prev (runq, thread);
  2204. current = true;
  2205. }
  2206. thread_runq_remove (runq, thread);
  2207. }
  2208. if (global_prio <= thread_user_global_priority (thread))
  2209. thread_reset_real_priority (thread);
  2210. else
  2211. {
  2212. if (thread_real_sched_policy (thread) == policy)
  2213. thread_update_real_priority (thread, prio);
  2214. else
  2215. {
  2216. thread_set_real_sched_policy (thread, policy);
  2217. thread_set_real_sched_class (thread,
  2218. thread_policy_to_class (policy));
  2219. thread_set_real_priority (thread, prio);
  2220. }
  2221. thread->boosted = true;
  2222. syscnt_inc (&runq->sc_boosts);
  2223. }
  2224. if (requeue)
  2225. {
  2226. thread_runq_add (runq, thread);
  2227. if (current)
  2228. thread_runq_set_next (runq, thread);
  2229. }
  2230. }
  2231. void
  2232. thread_pi_setscheduler (struct thread *thread, uint8_t policy, uint16_t prio)
  2233. {
  2234. struct thread_runq_guard g = thread_runq_guard_make (thread, false);
  2235. thread_pi_setsched_impl (g.runq, thread, policy, prio);
  2236. }
  2237. void
  2238. thread_propagate_priority (void)
  2239. {
  2240. /*
  2241. * Although it's possible to propagate priority with preemption
  2242. * disabled, the operation can be too expensive to allow it.
  2243. */
  2244. if (!thread_preempt_enabled ())
  2245. {
  2246. thread_set_priority_propagation_needed ();
  2247. return;
  2248. }
  2249. struct thread *thread = thread_self ();
  2250. // Clear before propagation to avoid infinite recursion.
  2251. thread->propagate_priority = false;
  2252. turnstile_td_propagate_priority (thread_turnstile_td (thread));
  2253. }
  2254. uint32_t
  2255. thread_cpu (const struct thread *thread)
  2256. {
  2257. const _Auto runq = atomic_load_rlx (&thread->runq);
  2258. return (runq->cpu);
  2259. }
  2260. uint32_t
  2261. thread_state (const struct thread *thread)
  2262. {
  2263. return (atomic_load_rlx (&thread->state));
  2264. }
  2265. bool
  2266. thread_is_running (const struct thread *thread)
  2267. {
  2268. const _Auto runq = atomic_load_rlx (&thread->runq);
  2269. return (runq && atomic_load_rlx (&runq->current) == thread);
  2270. }
  2271. int
  2272. thread_get_affinity (const struct thread *thr, struct cpumap *cpumap)
  2273. {
  2274. if (! thr)
  2275. return (EINVAL);
  2276. struct thread_runq_guard g =
  2277. thread_runq_guard_make ((struct thread *)thr, true);
  2278. cpumap_copy (cpumap, &thr->cpumap);
  2279. return (0);
  2280. }
  2281. int
  2282. thread_set_affinity (struct thread *thread, const struct cpumap *cpumap)
  2283. {
  2284. if (! thread)
  2285. return (EINVAL);
  2286. struct thread_runq_guard g = thread_runq_guard_make (thread, true);
  2287. if (thread == g.runq->idler ||
  2288. thread == g.runq->balancer ||
  2289. thread->state == THREAD_DEAD)
  2290. return (EINVAL);
  2291. else if (cpumap_intersects (&thread->cpumap, cpumap))
  2292. { // The desired CPU map intersects the current one.
  2293. cpumap_copy (&thread->cpumap, cpumap);
  2294. return (0);
  2295. }
  2296. else if (thread->pin_level != 0)
  2297. // The thread is pinned, and cannot be migrated to a different CPU.
  2298. return (EAGAIN);
  2299. // At this point, we know the thread must be migrated.
  2300. cpumap_copy (&thread->cpumap, cpumap);
  2301. if (thread == g.runq->current)
  2302. {
  2303. if (g.runq == thread_runq_local ())
  2304. g.runq = thread_runq_schedule (g.runq);
  2305. else
  2306. {
  2307. thread_set_flag (thread, THREAD_YIELD);
  2308. cpu_send_thread_schedule (thread_runq_cpu (g.runq));
  2309. }
  2310. }
  2311. return (0);
  2312. }
  2313. static ssize_t
  2314. thread_name_impl (struct thread *thread, char *name, bool set)
  2315. {
  2316. SPINLOCK_GUARD (&thread->task->lock);
  2317. if (set)
  2318. memcpy (thread->name, name, sizeof (thread->name));
  2319. else
  2320. memcpy (name, thread->name, sizeof (thread->name));
  2321. return (0);
  2322. }
  2323. static ssize_t
  2324. thread_ipc_affinity_impl (struct thread *thread, void *map,
  2325. uint32_t size, bool set)
  2326. {
  2327. if (! size)
  2328. return (-EINVAL);
  2329. struct cpumap *cpumap;
  2330. if (cpumap_create (&cpumap) != 0)
  2331. return (-ENOMEM);
  2332. cpumap_zero (cpumap);
  2333. size = MIN (size, sizeof (cpumap->cpus));
  2334. int error = user_copy_from (cpumap->cpus, map, size);
  2335. if (error)
  2336. ;
  2337. else if (set)
  2338. error = thread_set_affinity (thread, cpumap);
  2339. else if ((error = thread_get_affinity (thread, cpumap)) == 0)
  2340. error = user_copy_to (map, cpumap->cpus, size);
  2341. cpumap_destroy (cpumap);
  2342. return (-error);
  2343. }
  2344. #define THREAD_IPC_NEEDS_COPY \
  2345. ((1u << THREAD_IPC_GET_NAME) | (1u << THREAD_IPC_GET_AFFINITY) | \
  2346. (1u << THREAD_IPC_GET_ID))
  2347. ssize_t
  2348. thread_handle_msg (struct thread *thr, struct cap_iters *src,
  2349. struct cap_iters *dst, struct ipc_msg_data *data)
  2350. {
  2351. struct thread_ipc_msg tmsg;
  2352. struct ipc_iov_iter k_it;
  2353. ipc_iov_iter_init_buf (&k_it, &tmsg, sizeof (tmsg));
  2354. ssize_t rv = user_copyv_from (&k_it, &src->iov);
  2355. if (rv < 0)
  2356. return (rv);
  2357. switch (tmsg.op)
  2358. {
  2359. case THREAD_IPC_GET_NAME:
  2360. case THREAD_IPC_SET_NAME:
  2361. rv = thread_name_impl (thr, tmsg.name,
  2362. tmsg.op == THREAD_IPC_SET_NAME);
  2363. break;
  2364. case THREAD_IPC_GET_AFFINITY:
  2365. case THREAD_IPC_SET_AFFINITY:
  2366. rv = thread_ipc_affinity_impl (thr, tmsg.cpumap.map, tmsg.cpumap.size,
  2367. tmsg.op == THREAD_IPC_SET_AFFINITY);
  2368. break;
  2369. case THREAD_IPC_GET_ID:
  2370. tmsg.id = thread_id (thr);
  2371. break;
  2372. default:
  2373. return (-EINVAL);
  2374. }
  2375. if (rv == 0 && ((1u << tmsg.op) & THREAD_IPC_NEEDS_COPY))
  2376. {
  2377. ipc_iov_iter_init_buf (&k_it, &tmsg, sizeof (tmsg));
  2378. rv = user_copyv_to (&dst->iov, &k_it);
  2379. }
  2380. (void)data;
  2381. return (rv < 0 ? rv : 0);
  2382. }