/
sched_prim.c
8313 lines (7016 loc) · 241 KB
/
sched_prim.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2000-2016 Apple Inc. All rights reserved.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. The rights granted to you under the License
* may not be used to create, or enable the creation or redistribution of,
* unlawful or unlicensed copies of an Apple operating system, or to
* circumvent, violate, or enable the circumvention or violation of, any
* terms of an Apple operating system software license agreement.
*
* Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_END@
*/
/*
* @OSF_FREE_COPYRIGHT@
*/
/*
* Mach Operating System
* Copyright (c) 1991,1990,1989,1988,1987 Carnegie Mellon University
* All Rights Reserved.
*
* Permission to use, copy, modify and distribute this software and its
* documentation is hereby granted, provided that both the copyright
* notice and this permission notice appear in all copies of the
* software, derivative works or modified versions, and any portions
* thereof, and that both notices appear in supporting documentation.
*
* CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
* CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
* ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
*
* Carnegie Mellon requests users of this software to return to
*
* Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
* School of Computer Science
* Carnegie Mellon University
* Pittsburgh PA 15213-3890
*
* any improvements or extensions that they make and grant Carnegie Mellon
* the rights to redistribute these changes.
*/
/*
*/
/*
* File: sched_prim.c
* Author: Avadis Tevanian, Jr.
* Date: 1986
*
* Scheduling primitives
*
*/
#include <debug.h>
#include <mach/mach_types.h>
#include <mach/machine.h>
#include <mach/policy.h>
#include <mach/sync_policy.h>
#include <mach/thread_act.h>
#include <machine/machine_routines.h>
#include <machine/sched_param.h>
#include <machine/machine_cpu.h>
#include <machine/limits.h>
#include <machine/atomic.h>
#include <machine/commpage.h>
#include <kern/kern_types.h>
#include <kern/backtrace.h>
#include <kern/clock.h>
#include <kern/cpu_number.h>
#include <kern/cpu_data.h>
#include <kern/smp.h>
#include <kern/debug.h>
#include <kern/macro_help.h>
#include <kern/machine.h>
#include <kern/misc_protos.h>
#if MONOTONIC
#include <kern/monotonic.h>
#endif /* MONOTONIC */
#include <kern/processor.h>
#include <kern/queue.h>
#include <kern/restartable.h>
#include <kern/sched.h>
#include <kern/sched_prim.h>
#include <kern/sfi.h>
#include <kern/syscall_subr.h>
#include <kern/task.h>
#include <kern/thread.h>
#include <kern/thread_group.h>
#include <kern/ledger.h>
#include <kern/timer_queue.h>
#include <kern/waitq.h>
#include <kern/policy_internal.h>
#include <kern/cpu_quiesce.h>
#include <vm/pmap.h>
#include <vm/vm_kern.h>
#include <vm/vm_map.h>
#include <vm/vm_pageout.h>
#include <mach/sdt.h>
#include <mach/mach_host.h>
#include <mach/host_info.h>
#include <sys/kdebug.h>
#include <kperf/kperf.h>
#include <kern/kpc.h>
#include <san/kasan.h>
#include <kern/pms.h>
#include <kern/host.h>
#include <stdatomic.h>
struct sched_statistics PERCPU_DATA(sched_stats);
bool sched_stats_active;
static uint64_t
deadline_add(uint64_t d, uint64_t e)
{
uint64_t sum;
return os_add_overflow(d, e, &sum) ? UINT64_MAX : sum;
}
int
rt_runq_count(processor_set_t pset)
{
return os_atomic_load(&SCHED(rt_runq)(pset)->count, relaxed);
}
uint64_t
rt_runq_earliest_deadline(processor_set_t pset)
{
return os_atomic_load_wide(&SCHED(rt_runq)(pset)->earliest_deadline, relaxed);
}
static int
rt_runq_priority(processor_set_t pset)
{
pset_assert_locked(pset);
rt_queue_t rt_run_queue = SCHED(rt_runq)(pset);
bitmap_t *map = rt_run_queue->bitmap;
int i = bitmap_first(map, NRTQS);
assert(i < NRTQS);
if (i >= 0) {
return i + BASEPRI_RTQUEUES;
}
return i;
}
static thread_t rt_runq_first(rt_queue_t rt_runq);
#if DEBUG
static void
check_rt_runq_consistency(rt_queue_t rt_run_queue, thread_t thread)
{
bitmap_t *map = rt_run_queue->bitmap;
uint64_t earliest_deadline = RT_DEADLINE_NONE;
uint32_t constraint = RT_CONSTRAINT_NONE;
int ed_index = NOPRI;
int count = 0;
bool found_thread = false;
for (int pri = BASEPRI_RTQUEUES; pri <= MAXPRI; pri++) {
int i = pri - BASEPRI_RTQUEUES;
rt_queue_pri_t *rt_runq = &rt_run_queue->rt_queue_pri[i];
queue_t queue = &rt_runq->pri_queue;
queue_entry_t iter;
int n = 0;
uint64_t previous_deadline = 0;
qe_foreach(iter, queue) {
thread_t iter_thread = qe_element(iter, struct thread, runq_links);
assert_thread_magic(iter_thread);
if (iter_thread == thread) {
found_thread = true;
}
assert(iter_thread->sched_pri == (i + BASEPRI_RTQUEUES));
assert(iter_thread->realtime.deadline < RT_DEADLINE_NONE);
assert(iter_thread->realtime.constraint < RT_CONSTRAINT_NONE);
assert(previous_deadline <= iter_thread->realtime.deadline);
n++;
if (iter == queue_first(queue)) {
assert(rt_runq->pri_earliest_deadline == iter_thread->realtime.deadline);
assert(rt_runq->pri_constraint == iter_thread->realtime.constraint);
}
previous_deadline = iter_thread->realtime.deadline;
}
assert(n == rt_runq->pri_count);
if (n == 0) {
assert(bitmap_test(map, i) == false);
assert(rt_runq->pri_earliest_deadline == RT_DEADLINE_NONE);
assert(rt_runq->pri_constraint == RT_CONSTRAINT_NONE);
} else {
assert(bitmap_test(map, i) == true);
}
if (rt_runq->pri_earliest_deadline < earliest_deadline) {
earliest_deadline = rt_runq->pri_earliest_deadline;
constraint = rt_runq->pri_constraint;
ed_index = i;
}
count += n;
}
assert(os_atomic_load_wide(&rt_run_queue->earliest_deadline, relaxed) == earliest_deadline);
assert(os_atomic_load(&rt_run_queue->count, relaxed) == count);
assert(os_atomic_load(&rt_run_queue->constraint, relaxed) == constraint);
assert(os_atomic_load(&rt_run_queue->ed_index, relaxed) == ed_index);
if (thread) {
assert(found_thread);
}
}
#define CHECK_RT_RUNQ_CONSISTENCY(q, th) check_rt_runq_consistency(q, th)
#else
#define CHECK_RT_RUNQ_CONSISTENCY(q, th) do {} while (0)
#endif
uint32_t rt_constraint_threshold;
static bool
rt_runq_is_low_latency(processor_set_t pset)
{
return os_atomic_load(&SCHED(rt_runq)(pset)->constraint, relaxed) <= rt_constraint_threshold;
}
#define DEFAULT_PREEMPTION_RATE 100 /* (1/s) */
TUNABLE(int, default_preemption_rate, "preempt", DEFAULT_PREEMPTION_RATE);
#define DEFAULT_BG_PREEMPTION_RATE 400 /* (1/s) */
TUNABLE(int, default_bg_preemption_rate, "bg_preempt", DEFAULT_BG_PREEMPTION_RATE);
#define MAX_UNSAFE_QUANTA 800
TUNABLE(int, max_unsafe_quanta, "unsafe", MAX_UNSAFE_QUANTA);
#define MAX_POLL_QUANTA 2
TUNABLE(int, max_poll_quanta, "poll", MAX_POLL_QUANTA);
#define SCHED_POLL_YIELD_SHIFT 4 /* 1/16 */
int sched_poll_yield_shift = SCHED_POLL_YIELD_SHIFT;
uint64_t max_poll_computation;
uint64_t max_unsafe_computation;
uint64_t sched_safe_duration;
#if defined(CONFIG_SCHED_TIMESHARE_CORE)
uint32_t std_quantum;
uint32_t min_std_quantum;
uint32_t bg_quantum;
uint32_t std_quantum_us;
uint32_t bg_quantum_us;
#endif /* CONFIG_SCHED_TIMESHARE_CORE */
uint32_t thread_depress_time;
uint32_t default_timeshare_computation;
uint32_t default_timeshare_constraint;
uint32_t max_rt_quantum;
uint32_t min_rt_quantum;
uint32_t rt_deadline_epsilon;
uint32_t rt_constraint_threshold;
uint32_t rt_constraint_ll;
#if defined(CONFIG_SCHED_TIMESHARE_CORE)
unsigned sched_tick;
uint32_t sched_tick_interval;
/* Timeshare load calculation interval (15ms) */
uint32_t sched_load_compute_interval_us = 15000;
uint64_t sched_load_compute_interval_abs;
static _Atomic uint64_t sched_load_compute_deadline;
uint32_t sched_pri_shifts[TH_BUCKET_MAX];
uint32_t sched_fixed_shift;
uint32_t sched_decay_usage_age_factor = 1; /* accelerate 5/8^n usage aging */
/* Allow foreground to decay past default to resolve inversions */
#define DEFAULT_DECAY_BAND_LIMIT ((BASEPRI_FOREGROUND - BASEPRI_DEFAULT) + 2)
int sched_pri_decay_band_limit = DEFAULT_DECAY_BAND_LIMIT;
/* Defaults for timer deadline profiling */
#define TIMER_DEADLINE_TRACKING_BIN_1_DEFAULT 2000000 /* Timers with deadlines <=
* 2ms */
#define TIMER_DEADLINE_TRACKING_BIN_2_DEFAULT 5000000 /* Timers with deadlines
* <= 5ms */
uint64_t timer_deadline_tracking_bin_1;
uint64_t timer_deadline_tracking_bin_2;
#endif /* CONFIG_SCHED_TIMESHARE_CORE */
thread_t sched_maintenance_thread;
/* interrupts disabled lock to guard recommended cores state */
decl_simple_lock_data(static, sched_recommended_cores_lock);
static uint64_t usercontrol_requested_recommended_cores = ALL_CORES_RECOMMENDED;
static void sched_update_recommended_cores(uint64_t recommended_cores);
#if __arm__ || __arm64__
static void sched_recommended_cores_maintenance(void);
uint64_t perfcontrol_failsafe_starvation_threshold;
extern char *proc_name_address(struct proc *p);
#endif /* __arm__ || __arm64__ */
uint64_t sched_one_second_interval;
boolean_t allow_direct_handoff = TRUE;
/* Forwards */
#if defined(CONFIG_SCHED_TIMESHARE_CORE)
static void load_shift_init(void);
static void preempt_pri_init(void);
#endif /* CONFIG_SCHED_TIMESHARE_CORE */
thread_t processor_idle(
thread_t thread,
processor_t processor);
static ast_t
csw_check_locked(
thread_t thread,
processor_t processor,
processor_set_t pset,
ast_t check_reason);
static void processor_setrun(
processor_t processor,
thread_t thread,
integer_t options);
static void
sched_realtime_timebase_init(void);
static void
sched_timer_deadline_tracking_init(void);
#if DEBUG
extern int debug_task;
#define TLOG(a, fmt, args...) if(debug_task & a) kprintf(fmt, ## args)
#else
#define TLOG(a, fmt, args...) do {} while (0)
#endif
static processor_t
thread_bind_internal(
thread_t thread,
processor_t processor);
static void
sched_vm_group_maintenance(void);
#if defined(CONFIG_SCHED_TIMESHARE_CORE)
int8_t sched_load_shifts[NRQS];
bitmap_t sched_preempt_pri[BITMAP_LEN(NRQS_MAX)];
#endif /* CONFIG_SCHED_TIMESHARE_CORE */
/*
* Statically allocate a buffer to hold the longest possible
* scheduler description string, as currently implemented.
* bsd/kern/kern_sysctl.c has a corresponding definition in bsd/
* to export to userspace via sysctl(3). If either version
* changes, update the other.
*
* Note that in addition to being an upper bound on the strings
* in the kernel, it's also an exact parameter to PE_get_default(),
* which interrogates the device tree on some platforms. That
* API requires the caller know the exact size of the device tree
* property, so we need both a legacy size (32) and the current size
* (48) to deal with old and new device trees. The device tree property
* is similarly padded to a fixed size so that the same kernel image
* can run on multiple devices with different schedulers configured
* in the device tree.
*/
char sched_string[SCHED_STRING_MAX_LENGTH];
uint32_t sched_debug_flags = SCHED_DEBUG_FLAG_CHOOSE_PROCESSOR_TRACEPOINTS;
/* Global flag which indicates whether Background Stepper Context is enabled */
static int cpu_throttle_enabled = 1;
#if DEVELOPMENT || DEBUG
int enable_task_set_cluster_type = 0;
bool system_ecore_only = false;
#endif /* DEVELOPMENT || DEBUG */
void
sched_init(void)
{
boolean_t direct_handoff = FALSE;
kprintf("Scheduler: Default of %s\n", SCHED(sched_name));
if (!PE_parse_boot_argn("sched_pri_decay_limit", &sched_pri_decay_band_limit, sizeof(sched_pri_decay_band_limit))) {
/* No boot-args, check in device tree */
if (!PE_get_default("kern.sched_pri_decay_limit",
&sched_pri_decay_band_limit,
sizeof(sched_pri_decay_band_limit))) {
/* Allow decay all the way to normal limits */
sched_pri_decay_band_limit = DEFAULT_DECAY_BAND_LIMIT;
}
}
kprintf("Setting scheduler priority decay band limit %d\n", sched_pri_decay_band_limit);
if (PE_parse_boot_argn("sched_debug", &sched_debug_flags, sizeof(sched_debug_flags))) {
kprintf("Scheduler: Debug flags 0x%08x\n", sched_debug_flags);
}
strlcpy(sched_string, SCHED(sched_name), sizeof(sched_string));
cpu_quiescent_counter_init();
SCHED(init)();
SCHED(rt_init)(&pset0);
sched_timer_deadline_tracking_init();
SCHED(pset_init)(&pset0);
SCHED(processor_init)(master_processor);
if (PE_parse_boot_argn("direct_handoff", &direct_handoff, sizeof(direct_handoff))) {
allow_direct_handoff = direct_handoff;
}
#if DEVELOPMENT || DEBUG
if (PE_parse_boot_argn("enable_skstsct", &enable_task_set_cluster_type, sizeof(enable_task_set_cluster_type))) {
system_ecore_only = (enable_task_set_cluster_type == 2);
}
#endif /* DEVELOPMENT || DEBUG */
}
void
sched_timebase_init(void)
{
uint64_t abstime;
clock_interval_to_absolutetime_interval(1, NSEC_PER_SEC, &abstime);
sched_one_second_interval = abstime;
SCHED(timebase_init)();
sched_realtime_timebase_init();
}
#if defined(CONFIG_SCHED_TIMESHARE_CORE)
void
sched_timeshare_init(void)
{
/*
* Calculate the timeslicing quantum
* in us.
*/
if (default_preemption_rate < 1) {
default_preemption_rate = DEFAULT_PREEMPTION_RATE;
}
std_quantum_us = (1000 * 1000) / default_preemption_rate;
printf("standard timeslicing quantum is %d us\n", std_quantum_us);
if (default_bg_preemption_rate < 1) {
default_bg_preemption_rate = DEFAULT_BG_PREEMPTION_RATE;
}
bg_quantum_us = (1000 * 1000) / default_bg_preemption_rate;
printf("standard background quantum is %d us\n", bg_quantum_us);
load_shift_init();
preempt_pri_init();
sched_tick = 0;
}
void
sched_timeshare_timebase_init(void)
{
uint64_t abstime;
uint32_t shift;
/* standard timeslicing quantum */
clock_interval_to_absolutetime_interval(
std_quantum_us, NSEC_PER_USEC, &abstime);
assert((abstime >> 32) == 0 && (uint32_t)abstime != 0);
std_quantum = (uint32_t)abstime;
/* smallest remaining quantum (250 us) */
clock_interval_to_absolutetime_interval(250, NSEC_PER_USEC, &abstime);
assert((abstime >> 32) == 0 && (uint32_t)abstime != 0);
min_std_quantum = (uint32_t)abstime;
/* quantum for background tasks */
clock_interval_to_absolutetime_interval(
bg_quantum_us, NSEC_PER_USEC, &abstime);
assert((abstime >> 32) == 0 && (uint32_t)abstime != 0);
bg_quantum = (uint32_t)abstime;
/* scheduler tick interval */
clock_interval_to_absolutetime_interval(USEC_PER_SEC >> SCHED_TICK_SHIFT,
NSEC_PER_USEC, &abstime);
assert((abstime >> 32) == 0 && (uint32_t)abstime != 0);
sched_tick_interval = (uint32_t)abstime;
/* timeshare load calculation interval & deadline initialization */
clock_interval_to_absolutetime_interval(sched_load_compute_interval_us, NSEC_PER_USEC, &sched_load_compute_interval_abs);
os_atomic_init(&sched_load_compute_deadline, sched_load_compute_interval_abs);
/*
* Compute conversion factor from usage to
* timesharing priorities with 5/8 ** n aging.
*/
abstime = (abstime * 5) / 3;
for (shift = 0; abstime > BASEPRI_DEFAULT; ++shift) {
abstime >>= 1;
}
sched_fixed_shift = shift;
for (uint32_t i = 0; i < TH_BUCKET_MAX; i++) {
sched_pri_shifts[i] = INT8_MAX;
}
max_unsafe_computation = ((uint64_t)max_unsafe_quanta) * std_quantum;
sched_safe_duration = 2 * ((uint64_t)max_unsafe_quanta) * std_quantum;
max_poll_computation = ((uint64_t)max_poll_quanta) * std_quantum;
thread_depress_time = 1 * std_quantum;
default_timeshare_computation = std_quantum / 2;
default_timeshare_constraint = std_quantum;
#if __arm__ || __arm64__
perfcontrol_failsafe_starvation_threshold = (2 * sched_tick_interval);
#endif /* __arm__ || __arm64__ */
}
#endif /* CONFIG_SCHED_TIMESHARE_CORE */
void
pset_rt_init(processor_set_t pset)
{
for (int pri = BASEPRI_RTQUEUES; pri <= MAXPRI; pri++) {
int i = pri - BASEPRI_RTQUEUES;
rt_queue_pri_t *rqi = &pset->rt_runq.rt_queue_pri[i];
queue_init(&rqi->pri_queue);
rqi->pri_count = 0;
rqi->pri_earliest_deadline = RT_DEADLINE_NONE;
rqi->pri_constraint = RT_CONSTRAINT_NONE;
}
os_atomic_init(&pset->rt_runq.count, 0);
os_atomic_init(&pset->rt_runq.earliest_deadline, RT_DEADLINE_NONE);
os_atomic_init(&pset->rt_runq.constraint, RT_CONSTRAINT_NONE);
os_atomic_init(&pset->rt_runq.ed_index, NOPRI);
memset(&pset->rt_runq.runq_stats, 0, sizeof pset->rt_runq.runq_stats);
}
/* constraint limit for low latency RT threads */
int rt_constraint_ll_us = 0;
int
sched_get_rt_constraint_ll(void)
{
return rt_constraint_ll_us;
}
void
sched_set_rt_constraint_ll(int new_constraint_us)
{
rt_constraint_ll_us = new_constraint_us;
uint64_t abstime;
clock_interval_to_absolutetime_interval(rt_constraint_ll_us, NSEC_PER_USEC, &abstime);
assert((abstime >> 32) == 0 && ((rt_constraint_ll_us == 0) || (uint32_t)abstime != 0));
rt_constraint_ll = (uint32_t)abstime;
}
/* epsilon for comparing RT deadlines */
int rt_deadline_epsilon_us = 100;
int
sched_get_rt_deadline_epsilon(void)
{
return rt_deadline_epsilon_us;
}
void
sched_set_rt_deadline_epsilon(int new_epsilon_us)
{
rt_deadline_epsilon_us = new_epsilon_us;
uint64_t abstime;
clock_interval_to_absolutetime_interval(rt_deadline_epsilon_us, NSEC_PER_USEC, &abstime);
assert((abstime >> 32) == 0 && ((rt_deadline_epsilon_us == 0) || (uint32_t)abstime != 0));
rt_deadline_epsilon = (uint32_t)abstime;
}
static void
sched_realtime_timebase_init(void)
{
uint64_t abstime;
/* smallest rt computation (50 us) */
clock_interval_to_absolutetime_interval(50, NSEC_PER_USEC, &abstime);
assert((abstime >> 32) == 0 && (uint32_t)abstime != 0);
min_rt_quantum = (uint32_t)abstime;
/* maximum rt computation (50 ms) */
clock_interval_to_absolutetime_interval(
50, 1000 * NSEC_PER_USEC, &abstime);
assert((abstime >> 32) == 0 && (uint32_t)abstime != 0);
max_rt_quantum = (uint32_t)abstime;
/* constraint threshold for sending backup IPIs (4 ms) */
clock_interval_to_absolutetime_interval(4, NSEC_PER_MSEC, &abstime);
assert((abstime >> 32) == 0 && (uint32_t)abstime != 0);
rt_constraint_threshold = (uint32_t)abstime;
/* constraint limit for low latency RT threads */
sched_set_rt_constraint_ll(rt_constraint_ll_us);
/* epsilon for comparing deadlines */
sched_set_rt_deadline_epsilon(rt_deadline_epsilon_us);
}
void
sched_check_spill(processor_set_t pset, thread_t thread)
{
(void)pset;
(void)thread;
return;
}
bool
sched_thread_should_yield(processor_t processor, thread_t thread)
{
(void)thread;
return !SCHED(processor_queue_empty)(processor) || rt_runq_count(processor->processor_set) > 0;
}
/* Default implementations of .steal_thread_enabled */
bool
sched_steal_thread_DISABLED(processor_set_t pset)
{
(void)pset;
return false;
}
bool
sched_steal_thread_enabled(processor_set_t pset)
{
return bit_count(pset->node->pset_map) > 1;
}
#if defined(CONFIG_SCHED_TIMESHARE_CORE)
/*
* Set up values for timeshare
* loading factors.
*/
static void
load_shift_init(void)
{
int8_t k, *p = sched_load_shifts;
uint32_t i, j;
uint32_t sched_decay_penalty = 1;
if (PE_parse_boot_argn("sched_decay_penalty", &sched_decay_penalty, sizeof(sched_decay_penalty))) {
kprintf("Overriding scheduler decay penalty %u\n", sched_decay_penalty);
}
if (PE_parse_boot_argn("sched_decay_usage_age_factor", &sched_decay_usage_age_factor, sizeof(sched_decay_usage_age_factor))) {
kprintf("Overriding scheduler decay usage age factor %u\n", sched_decay_usage_age_factor);
}
if (sched_decay_penalty == 0) {
/*
* There is no penalty for timeshare threads for using too much
* CPU, so set all load shifts to INT8_MIN. Even under high load,
* sched_pri_shift will be >INT8_MAX, and there will be no
* penalty applied to threads (nor will sched_usage be updated per
* thread).
*/
for (i = 0; i < NRQS; i++) {
sched_load_shifts[i] = INT8_MIN;
}
return;
}
*p++ = INT8_MIN; *p++ = 0;
/*
* For a given system load "i", the per-thread priority
* penalty per quantum of CPU usage is ~2^k priority
* levels. "sched_decay_penalty" can cause more
* array entries to be filled with smaller "k" values
*/
for (i = 2, j = 1 << sched_decay_penalty, k = 1; i < NRQS; ++k) {
for (j <<= 1; (i < j) && (i < NRQS); ++i) {
*p++ = k;
}
}
}
static void
preempt_pri_init(void)
{
bitmap_t *p = sched_preempt_pri;
for (int i = BASEPRI_FOREGROUND; i < MINPRI_KERNEL; ++i) {
bitmap_set(p, i);
}
for (int i = BASEPRI_PREEMPT; i <= MAXPRI; ++i) {
bitmap_set(p, i);
}
}
#endif /* CONFIG_SCHED_TIMESHARE_CORE */
void
check_monotonic_time(uint64_t ctime)
{
processor_t processor = current_processor();
uint64_t last_dispatch = processor->last_dispatch;
if (last_dispatch > ctime) {
panic("Non-monotonic time: last_dispatch at 0x%llx, ctime 0x%llx",
last_dispatch, ctime);
}
}
/*
* Thread wait timer expiration.
*/
void
thread_timer_expire(
void *p0,
__unused void *p1)
{
thread_t thread = p0;
spl_t s;
assert_thread_magic(thread);
s = splsched();
thread_lock(thread);
if (--thread->wait_timer_active == 0) {
if (thread->wait_timer_is_set) {
thread->wait_timer_is_set = FALSE;
clear_wait_internal(thread, THREAD_TIMED_OUT);
}
}
thread_unlock(thread);
splx(s);
}
/*
* thread_unblock:
*
* Unblock thread on wake up.
*
* Returns TRUE if the thread should now be placed on the runqueue.
*
* Thread must be locked.
*
* Called at splsched().
*/
boolean_t
thread_unblock(
thread_t thread,
wait_result_t wresult)
{
boolean_t ready_for_runq = FALSE;
thread_t cthread = current_thread();
uint32_t new_run_count;
int old_thread_state;
/*
* Set wait_result.
*/
thread->wait_result = wresult;
/*
* Cancel pending wait timer.
*/
if (thread->wait_timer_is_set) {
if (timer_call_cancel(thread->wait_timer)) {
thread->wait_timer_active--;
}
thread->wait_timer_is_set = FALSE;
}
boolean_t aticontext, pidle;
ml_get_power_state(&aticontext, &pidle);
/*
* Update scheduling state: not waiting,
* set running.
*/
old_thread_state = thread->state;
thread->state = (old_thread_state | TH_RUN) &
~(TH_WAIT | TH_UNINT | TH_WAIT_REPORT);
if ((old_thread_state & TH_RUN) == 0) {
uint64_t ctime = mach_approximate_time();
check_monotonic_time(ctime);
thread->last_made_runnable_time = thread->last_basepri_change_time = ctime;
timer_start(&thread->runnable_timer, ctime);
ready_for_runq = TRUE;
if (old_thread_state & TH_WAIT_REPORT) {
(*thread->sched_call)(SCHED_CALL_UNBLOCK, thread);
}
/* Update the runnable thread count */
new_run_count = SCHED(run_count_incr)(thread);
#if CONFIG_SCHED_AUTO_JOIN
if (aticontext == FALSE && work_interval_should_propagate(cthread, thread)) {
work_interval_auto_join_propagate(cthread, thread);
}
#endif /*CONFIG_SCHED_AUTO_JOIN */
} else {
/*
* Either the thread is idling in place on another processor,
* or it hasn't finished context switching yet.
*/
assert((thread->state & TH_IDLE) == 0);
/*
* The run count is only dropped after the context switch completes
* and the thread is still waiting, so we should not run_incr here
*/
new_run_count = os_atomic_load(&sched_run_buckets[TH_BUCKET_RUN], relaxed);
}
/*
* Calculate deadline for real-time threads.
*/
if (thread->sched_mode == TH_MODE_REALTIME) {
uint64_t ctime = mach_absolute_time();
thread->realtime.deadline = thread->realtime.constraint + ctime;
KDBG(MACHDBG_CODE(DBG_MACH_SCHED, MACH_SET_RT_DEADLINE) | DBG_FUNC_NONE,
(uintptr_t)thread_tid(thread), thread->realtime.deadline, thread->realtime.computation, 0);
}
/*
* Clear old quantum, fail-safe computation, etc.
*/
thread->quantum_remaining = 0;
thread->computation_metered = 0;
thread->reason = AST_NONE;
thread->block_hint = kThreadWaitNone;
/* Obtain power-relevant interrupt and "platform-idle exit" statistics.
* We also account for "double hop" thread signaling via
* the thread callout infrastructure.
* DRK: consider removing the callout wakeup counters in the future
* they're present for verification at the moment.
*/
if (__improbable(aticontext && !(thread_get_tag_internal(thread) & THREAD_TAG_CALLOUT))) {
DTRACE_SCHED2(iwakeup, struct thread *, thread, struct proc *, current_proc());
uint64_t ttd = current_processor()->timer_call_ttd;
if (ttd) {
if (ttd <= timer_deadline_tracking_bin_1) {
thread->thread_timer_wakeups_bin_1++;
} else if (ttd <= timer_deadline_tracking_bin_2) {
thread->thread_timer_wakeups_bin_2++;
}
}
ledger_credit_thread(thread, thread->t_ledger,
task_ledgers.interrupt_wakeups, 1);
if (pidle) {
ledger_credit_thread(thread, thread->t_ledger,
task_ledgers.platform_idle_wakeups, 1);
}
} else if (thread_get_tag_internal(cthread) & THREAD_TAG_CALLOUT) {
/* TODO: what about an interrupt that does a wake taken on a callout thread? */
if (cthread->callout_woken_from_icontext) {
ledger_credit_thread(thread, thread->t_ledger,
task_ledgers.interrupt_wakeups, 1);
thread->thread_callout_interrupt_wakeups++;
if (cthread->callout_woken_from_platform_idle) {
ledger_credit_thread(thread, thread->t_ledger,
task_ledgers.platform_idle_wakeups, 1);
thread->thread_callout_platform_idle_wakeups++;
}
cthread->callout_woke_thread = TRUE;
}
}
if (thread_get_tag_internal(thread) & THREAD_TAG_CALLOUT) {
thread->callout_woken_from_icontext = !!aticontext;
thread->callout_woken_from_platform_idle = !!pidle;
thread->callout_woke_thread = FALSE;
}
#if KPERF
if (ready_for_runq) {
kperf_make_runnable(thread, aticontext);
}
#endif /* KPERF */
KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE,
MACHDBG_CODE(DBG_MACH_SCHED, MACH_MAKE_RUNNABLE) | DBG_FUNC_NONE,
(uintptr_t)thread_tid(thread), thread->sched_pri, thread->wait_result,
sched_run_buckets[TH_BUCKET_RUN], 0);
DTRACE_SCHED2(wakeup, struct thread *, thread, struct proc *, current_proc());
return ready_for_runq;
}
/*
* Routine: thread_allowed_for_handoff
* Purpose:
* Check if the thread is allowed for handoff operation
* Conditions:
* thread lock held, IPC locks may be held.
* TODO: In future, do not allow handoff if threads have different cluster
* recommendations.
*/
boolean_t
thread_allowed_for_handoff(
thread_t thread)
{
thread_t self = current_thread();
if (allow_direct_handoff &&
thread->sched_mode == TH_MODE_REALTIME &&
self->sched_mode == TH_MODE_REALTIME) {
return TRUE;
}
return FALSE;
}
/*
* Routine: thread_go
* Purpose:
* Unblock and dispatch thread.
* Conditions:
* thread lock held, IPC locks may be held.
* thread must have been pulled from wait queue under same lock hold.
* thread must have been waiting
* Returns:
* KERN_SUCCESS - Thread was set running
*
* TODO: This should return void
*/
kern_return_t
thread_go(
thread_t thread,
wait_result_t wresult,
waitq_options_t option)
{
thread_t self = current_thread();
assert_thread_magic(thread);
assert(thread->at_safe_point == FALSE);
assert(thread->wait_event == NO_EVENT64);
assert(waitq_wait_possible(thread));
assert(!(thread->state & (TH_TERMINATE | TH_TERMINATE2)));
assert(thread->state & TH_WAIT);
if (thread_unblock(thread, wresult)) {
#if SCHED_TRACE_THREAD_WAKEUPS