forked from cloudius-systems/osv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsched.cc
2097 lines (1901 loc) · 66.9 KB
/
sched.cc
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) 2013 Cloudius Systems, Ltd.
*
* This work is open source software, licensed under the terms of the
* BSD license as described in the LICENSE file in the top-level directory.
*/
#include <osv/sched.hh>
#include <list>
#include <osv/mutex.h>
#include <osv/rwlock.h>
#include <mutex>
#include <osv/debug.hh>
#include <osv/irqlock.hh>
#include <osv/align.hh>
#include <osv/interrupt.hh>
#include <smp.hh>
#include "osv/trace.hh"
#include <osv/percpu.hh>
#include <osv/prio.hh>
#include <osv/elf.hh>
#include <stdlib.h>
#include <math.h>
#include <unordered_map>
#include <osv/wait_record.hh>
#include <osv/preempt-lock.hh>
#include <osv/app.hh>
#include <osv/symbols.hh>
#include <osv/stubbing.hh>
#include <algorithm>
#include <osv/kernel_config_lazy_stack.h>
#include <osv/kernel_config_lazy_stack_invariant.h>
MAKE_SYMBOL(sched::thread::current);
MAKE_SYMBOL(sched::cpu::current);
MAKE_SYMBOL(sched::get_preempt_counter);
MAKE_SYMBOL(sched::preemptable);
MAKE_SYMBOL(sched::preempt);
MAKE_SYMBOL(sched::preempt_disable);
MAKE_SYMBOL(sched::preempt_enable);
int futex(int *uaddr, int op, int val, const struct timespec *timeout, int *uaddr2, uint32_t val3);
__thread char* percpu_base;
extern char _percpu_start[], _percpu_end[];
using namespace osv;
using namespace osv::clock::literals;
namespace sched {
TRACEPOINT(trace_sched_idle, "");
TRACEPOINT(trace_sched_idle_ret, "");
TRACEPOINT(trace_sched_switch, "to %p vold=%g vnew=%g", thread*, float, float);
TRACEPOINT(trace_sched_wait, "");
TRACEPOINT(trace_sched_wait_ret, "");
TRACEPOINT(trace_sched_wake, "wake %p", thread*);
TRACEPOINT(trace_sched_migrate, "thread=%p cpu=%d", thread*, unsigned);
TRACEPOINT(trace_sched_queue, "thread=%p", thread*);
TRACEPOINT(trace_sched_load, "load=%d", size_t);
TRACEPOINT(trace_sched_preempt, "");
TRACEPOINT(trace_sched_ipi, "cpu %d", unsigned);
TRACEPOINT(trace_sched_yield, "");
TRACEPOINT(trace_sched_yield_switch, "");
TRACEPOINT(trace_sched_sched, "");
TRACEPOINT(trace_timer_set, "timer=%p time=%d", timer_base*, s64);
TRACEPOINT(trace_timer_reset, "timer=%p time=%d", timer_base*, s64);
TRACEPOINT(trace_timer_cancel, "timer=%p", timer_base*);
TRACEPOINT(trace_timer_fired, "timer=%p", timer_base*);
TRACEPOINT(trace_thread_create, "thread=%p", thread*);
std::vector<cpu*> cpus __attribute__((init_priority((int)init_prio::cpus)));
thread __thread * s_current;
cpu __thread * current_cpu;
unsigned __thread preempt_counter = 1;
bool __thread need_reschedule = false;
elf::tls_data tls;
inter_processor_interrupt wakeup_ipi{IPI_WAKEUP, [] {}};
constexpr float cmax = 0x1P63;
constexpr float cinitial = 0x1P-63;
static inline float exp_tau(thread_runtime::duration t) {
// return expf((float)t/(float)tau);
// Approximate e^x as much faster 1+x for x<0.001 (the error is O(x^2)).
// Further speed up by comparing and adding integers as much as we can:
static constexpr int m = tau.count() / 1000;
static constexpr float invtau = 1.0f / tau.count();
if (t.count() < m && t.count() > -m)
return (tau.count() + t.count()) * invtau;
else
return expf(t.count() * invtau);
}
// fastlog2() is an approximation of log2, designed for speed over accuracy
// (it is accurate to roughly 5 digits).
// The function is copyright (C) 2012 Paul Mineiro, released under the
// BSD license. See https://code.google.com/p/fastapprox/.
static inline float
fastlog2 (float x)
{
union { float f; u32 i; } vx = { x };
union { u32 i; float f; } mx = { (vx.i & 0x007FFFFF) | 0x3f000000 };
float y = vx.i;
y *= 1.1920928955078125e-7f;
return y - 124.22551499f - 1.498030302f * mx.f
- 1.72587999f / (0.3520887068f + mx.f);
}
static inline float taulog(float f) {
//return tau * logf(f);
// We don't need the full accuracy of logf - we use this in time_until(),
// where it's fine to overshoot, even significantly, the correct time
// because a thread running a bit too much will "pay" in runtime.
// We multiply by 1.01 to ensure overshoot, not undershoot.
static constexpr float tau2 = tau.count() * 0.69314718f * 1.01;
return tau2 * fastlog2(f);
}
static constexpr runtime_t inf = std::numeric_limits<runtime_t>::infinity();
mutex cpu::notifier::_mtx;
std::list<cpu::notifier*> cpu::notifier::_notifiers __attribute__((init_priority((int)init_prio::notifiers)));
}
#include "arch-switch.hh"
namespace sched {
class thread::reaper {
public:
reaper();
void reap();
void add_zombie(thread* z);
private:
mutex _mtx;
std::list<thread*> _zombies;
thread_unique_ptr _thread;
};
cpu::cpu(unsigned _id)
: id(_id)
, preemption_timer(*this)
, idle_thread()
, terminating_thread(nullptr)
, c(cinitial)
, renormalize_count(0)
{
auto pcpu_size = _percpu_end - _percpu_start;
// We want the want the per-cpu area to be aligned as the most strictly
// aligned per-cpu variable. This is probably CACHELINE_ALIGNED (64 bytes)
// but we'll be even stricter, and go for page (4096 bytes) alignment.
percpu_base = (char *) aligned_alloc(4096, pcpu_size);
memcpy(percpu_base, _percpu_start, pcpu_size);
percpu_base -= reinterpret_cast<size_t>(_percpu_start);
if (id == 0) {
::percpu_base = percpu_base;
}
}
void cpu::init_idle_thread()
{
running_since = osv::clock::uptime::now();
std::string name = std::string("idle") + std::to_string(id);
idle_thread = thread::make([this] { idle(); }, thread::attr().pin(this).name(name));
idle_thread->set_priority(thread::priority_idle);
}
// Estimating a *running* thread's total cpu usage (in thread::thread_clock())
// requires knowing a pair [running_since, cpu_time_at_running_since].
// Since we can't read a pair of u64 values atomically, nor want to slow down
// context switches by additional memory fences, our solution is to write
// a single 64 bit "_cputime_estimator" which is atomically written with
// 32 bits from each of the above values. We arrive at 32 bits by dropping
// the cputime_shift=10 lowest bits (so we get microsec accuracy instead of ns)
// and the 22 highest bits (so our range is reduced to about 2000 seconds, but
// since context switches occur much more frequently than that, we're ok).
constexpr unsigned cputime_shift = 10;
void thread::cputime_estimator_set(
osv::clock::uptime::time_point running_since,
osv::clock::uptime::duration total_cpu_time)
{
u32 rs = running_since.time_since_epoch().count() >> cputime_shift;
u32 tc = total_cpu_time.count() >> cputime_shift;
_cputime_estimator.store(rs | ((u64)tc << 32), std::memory_order_relaxed);
}
void thread::cputime_estimator_get(
osv::clock::uptime::time_point &running_since,
osv::clock::uptime::duration &total_cpu_time)
{
u64 e = _cputime_estimator.load(std::memory_order_relaxed);
u64 rs = ((u64)(u32) e) << cputime_shift;
u64 tc = (e >> 32) << cputime_shift;
// Recover the (64-32-cputime_shift) high-order bits of rs and tc that we
// didn't save in _cputime_estimator, by taking the current values of the
// bits in the current time and _total_cpu_time, respectively.
// These high bits usually remain the same if little time has passed, but
// there's also the chance that the old value was close to the cutoff, and
// just a short passing time caused the high-order part to increase by one
// since we saved _cputime_estimator. We recognize this case, and
// decrement the high-order part when recovering the saved value. To do
// this correctly, we need to assume that less than 2^(32+cputime_shift-1)
// ns have passed since the estimator was saved. This is 2200 seconds for
// cputime_shift=10, way longer than our typical context switches.
constexpr u64 ho = (std::numeric_limits<u64>::max() &
~(std::numeric_limits<u64>::max() >> (64 - 32 - cputime_shift)));
u64 rs_ref = osv::clock::uptime::now().time_since_epoch().count();
u64 tc_ref = _total_cpu_time.count();
u64 rs_ho = rs_ref & ho;
u64 tc_ho = tc_ref & ho;
if ((rs_ref & ~ho) < rs) {
rs_ho -= (1ULL << (32 + cputime_shift));
}
if ((tc_ref & ~ho) < tc) {
tc_ho -= (1ULL << (32 + cputime_shift));
}
running_since = osv::clock::uptime::time_point(
osv::clock::uptime::duration(rs_ho | rs));
total_cpu_time = osv::clock::uptime::duration(tc_ho | tc);
}
// Note that this is a static (class) function, which can only reschedule
// on the current CPU, not on an arbitrary CPU. Allowing to run one CPU's
// scheduler on a different CPU would be disastrous.
void cpu::schedule()
{
#if CONF_lazy_stack
sched::ensure_next_stack_page_if_preemptable();
#endif
WITH_LOCK(irq_lock) {
#ifdef __aarch64__
reschedule_from_interrupt(sched::cpu::current(), false, thyst);
#else
current()->reschedule_from_interrupt();
#endif
}
}
// In aarch64 port, the reschedule_from_interrupt() needs to be implemented
// in assembly (please see arch/aarch64/sched.S) to give us better control
// which registers are used and which ones are saved and restored during
// the context switch. In essence, most of the original reschedule_from_interrupt()
// code up to switch_to() is shared with aarch64-specific cpu::schedule_next_thread()
// that is called from reschedule_from_interrupt() in arch/arch64/sched.S assembly.
// The logic executed after switch_to() that makes up destroy_current_cpu_terminating_thread()
// is called from arch/arch64/sched.S as well.
// At the end, we define reschedule_from_interrupt() in C++ for x86_64 and schedule_next_thread()
// and destroy_current_cpu_terminating_thread() in C++ for aarch64.
#ifdef __aarch64__
inline thread_switch_data cpu::schedule_next_thread(bool called_from_yield,
thread_runtime::duration preempt_after)
{
thread_switch_data switch_data;
#else
void cpu::reschedule_from_interrupt(bool called_from_yield,
thread_runtime::duration preempt_after)
{
#endif
trace_sched_sched();
assert(sched::exception_depth <= 1);
need_reschedule = false;
handle_incoming_wakeups();
auto now = osv::clock::uptime::now();
auto interval = now - running_since;
running_since = now;
if (interval <= 0) {
// During startup, the clock may be stuck and we get zero intervals.
// To avoid scheduler loops, let's make it non-zero.
// Also ignore backward jumps in the clock.
interval = context_switch_penalty;
}
thread* p = thread::current();
const auto p_status = p->_detached_state->st.load();
assert(p_status != thread::status::queued);
p->_total_cpu_time += interval;
p->_runtime.ran_for(interval);
if (p_status == thread::status::running) {
// The current thread is still runnable. Check if it still has the
// lowest runtime, and update the timer until the next thread's turn.
if (runqueue.empty()) {
preemption_timer.cancel();
#ifdef __aarch64__
return switch_data;
#else
return;
#endif
} else if (!called_from_yield) {
auto &t = *runqueue.begin();
if (p->_realtime._priority > 0) {
// Only switch to a higher-priority realtime thread
if (t._realtime._priority <= p->_realtime._priority) {
#ifdef __aarch64__
return switch_data;
#else
return;
#endif
}
} else if (t._realtime._priority == 0 && p->_runtime.get_local() < t._runtime.get_local()) {
preemption_timer.cancel();
auto delta = p->_runtime.time_until(t._runtime.get_local());
if (delta > 0) {
preemption_timer.set_with_irq_disabled(now + delta);
}
#ifdef __aarch64__
return switch_data;
#else
return;
#endif
}
} else { /* called_from_yield */
if (p->_realtime._priority > 0) {
auto &t = *runqueue.begin();
// When yielding, only switch if the next thread has a higher
// or same priority as p (i.e., don't switch if t it has a
// lesser priority than p).
if (t._realtime._priority < p->_realtime._priority) {
#ifdef __aarch64__
return switch_data;
#else
return;
#endif
}
}
}
// If we're here, p no longer has the lowest runtime. Before queuing
// p, return the runtime it borrowed for hysteresis.
p->_runtime.hysteresis_run_stop();
p->_detached_state->st.store(thread::status::queued);
if (!called_from_yield) {
// POSIX requires that if a real-time thread doesn't yield but
// rather is preempted by a higher-priority thread, it be
// reinserted into the runqueue first, not last, among its equals.
enqueue_first_equal(*p);
}
trace_sched_preempt();
p->stat_preemptions.incr();
} else {
// p is no longer running, so we'll switch to a different thread.
// Return the runtime p borrowed for hysteresis.
p->_runtime.hysteresis_run_stop();
}
auto ni = runqueue.begin();
auto n = &*ni;
runqueue.erase(ni);
n->cputime_estimator_set(now, n->_total_cpu_time);
assert(n->_detached_state->st.load() == thread::status::queued);
trace_sched_switch(n, p->_runtime.get_local(), n->_runtime.get_local());
if (called_from_yield) {
enqueue(*p);
}
if (n == idle_thread) {
trace_sched_idle();
} else if (p == idle_thread) {
trace_sched_idle_ret();
}
n->stat_switches.incr();
trace_sched_load(runqueue.size());
n->_detached_state->st.store(thread::status::running);
n->_runtime.hysteresis_run_start();
assert(n!=p);
if (p->_detached_state->st.load(std::memory_order_relaxed) == thread::status::queued
&& p != idle_thread) {
n->_runtime.add_context_switch_penalty();
}
preemption_timer.cancel();
if (n->_realtime._priority == 0) {
if (!called_from_yield) {
if (!runqueue.empty()) {
auto& t = *runqueue.begin();
auto delta = n->_runtime.time_until(t._runtime.get_local());
if (delta > 0) {
preemption_timer.set_with_irq_disabled(now + delta);
}
}
} else {
preemption_timer.set_with_irq_disabled(now + preempt_after);
}
}
if (app_thread.load(std::memory_order_relaxed) != n->_app) { // don't write into a cache line if it can be avoided
app_thread.store(n->_app, std::memory_order_relaxed);
}
if (lazy_flush_tlb.exchange(false, std::memory_order_seq_cst)) {
mmu::flush_tlb_local();
}
#ifdef __aarch64__
switch_data.old_thread_state = &(p->_state);
switch_data.new_thread_state = &(n->_state);
return switch_data;
}
#else
n->switch_to();
#endif
// Note: after the call to n->switch_to(), we should no longer use any of
// the local variables, nor "this" object, because we just switched to n's
// stack and the values we can access now are those that existed in the
// reschedule call which scheduled n out, and will now be returning.
// So to get the current cpu, we must use cpu::current(), not "this".
#ifdef __aarch64__
extern "C" void destroy_current_cpu_terminating_thread()
{
#endif
if (cpu::current()->terminating_thread) {
cpu::current()->terminating_thread->destroy();
cpu::current()->terminating_thread = nullptr;
}
}
#ifdef __aarch64__
extern "C" thread_switch_data cpu_schedule_next_thread(cpu* cpu,
bool called_from_yield,
thread_runtime::duration preempt_after)
{
return cpu->schedule_next_thread(called_from_yield, preempt_after);
}
#endif
void cpu::timer_fired()
{
// nothing to do, preemption will happen if needed
}
struct idle_poll_lock_type {
explicit idle_poll_lock_type(cpu& c) : _c(c) {}
void lock() { _c.idle_poll_start(); }
void unlock() { _c.idle_poll_end(); }
cpu& _c;
};
void cpu::idle_poll_start()
{
idle_poll.store(true, std::memory_order_relaxed);
}
void cpu::idle_poll_end()
{
idle_poll.store(false, std::memory_order_relaxed);
std::atomic_thread_fence(std::memory_order_seq_cst);
}
void cpu::send_wakeup_ipi()
{
std::atomic_thread_fence(std::memory_order_seq_cst);
if (!idle_poll.load(std::memory_order_relaxed) && runqueue.size() <= 1) {
trace_sched_ipi(id);
wakeup_ipi.send(this);
}
}
void cpu::do_idle()
{
do {
idle_poll_lock_type idle_poll_lock{*this};
WITH_LOCK(idle_poll_lock) {
// spin for a bit before halting
for (unsigned ctr = 0; ctr < 10000; ++ctr) {
// FIXME: can we pull threads from loaded cpus?
handle_incoming_wakeups();
if (!runqueue.empty()) {
return;
}
}
}
#if CONF_lazy_stack_invariant
assert(!thread::current()->is_app());
#endif
std::unique_lock<irq_lock_type> guard(irq_lock);
handle_incoming_wakeups();
if (!runqueue.empty()) {
return;
}
guard.release();
arch::wait_for_interrupt(); // this unlocks irq_lock
handle_incoming_wakeups();
} while (runqueue.empty());
}
void start_early_threads();
void cpu::idle()
{
// The idle thread must not sleep, because the whole point is that the
// scheduler can always find at least one runnable thread.
// We set preempt_disable just to help us verify this.
#if CONF_lazy_stack_invariant
assert(!thread::current()->is_app());
#endif
preempt_disable();
if (id == 0) {
start_early_threads();
}
while (true) {
do_idle();
// We have idle priority, so this runs the thread on the runqueue:
schedule();
}
}
void cpu::handle_incoming_wakeups()
{
#if CONF_lazy_stack_invariant
assert(!arch::irq_enabled() || !thread::current()->is_app());
#endif
cpu_set queues_with_wakes{incoming_wakeups_mask.fetch_clear()};
if (!queues_with_wakes) {
return;
}
for (auto i : queues_with_wakes) {
irq_save_lock_type irq_lock;
WITH_LOCK(irq_lock) {
auto& q = incoming_wakeups[i];
while (!q.empty()) {
auto& t = q.front();
q.pop_front();
if (&t == thread::current()) {
// Special case of current thread being woken before
// having a chance to be scheduled out.
t._detached_state->st.store(thread::status::running);
} else if (t.tcpu() != this) {
// Thread was woken on the wrong cpu. Can be a side-effect
// of sched::thread::pin(thread*, cpu*). Do nothing.
} else {
t._detached_state->st.store(thread::status::queued);
// Make sure the CPU-local runtime measure is suitably
// normalized. We may need to convert a global value to the
// local value when waking up after a CPU migration, or to
// perform renormalizations which we missed while sleeping.
t._runtime.update_after_sleep();
enqueue(t);
t.resume_timers();
}
}
}
}
trace_sched_load(runqueue.size());
}
void cpu::enqueue(thread& t)
{
trace_sched_queue(&t);
runqueue.insert_equal(t);
}
// When the run queue has several threads with equal thread_runtime_compare,
// enqueue() puts a thread after its equals, while enqueue_first_equal()
// puts it before its equals. The distinction is mostly interesting for real-
// time priority threads.
void cpu::enqueue_first_equal(thread& t)
{
trace_sched_queue(&t);
runqueue.insert_before(runqueue.lower_bound(t), t);
}
void cpu::init_on_cpu()
{
arch.init_on_cpu();
clock_event->setup_on_cpu();
}
unsigned cpu::load()
{
return runqueue.size();
}
// function to pin the *current* thread:
void thread::pin(cpu *target_cpu)
{
// Note that this code may proceed to migrate the current thread even if
// it was protected by a migrate_disable(). It is the thread's own fault
// for doing this to itself... The function to pin a different thread
// (below) waits for that different thread to leave migrate_disable().
thread &t = *current();
if (!t._pinned) {
// _pinned comes with a +1 increase to _migration_counter.
migrate_disable();
t._pinned = true;
}
cpu *source_cpu = cpu::current();
if (source_cpu == target_cpu) {
return;
}
// We want to wake this thread on the target CPU, but can't do this while
// it is still running on this CPU. So we need a different thread to
// complete the wakeup. We could re-used an existing thread (e.g., the
// load balancer thread) but a "good-enough" dirty solution is to
// temporarily create a new ad-hoc thread, "wakeme".
bool do_wakeme = false;
thread_unique_ptr wakeme(thread::make_unique([&] () {
wait_until([&] { return do_wakeme; });
t.wake();
}, sched::thread::attr().pin(source_cpu)));
wakeme->start();
#if CONF_lazy_stack
sched::ensure_next_stack_page_if_preemptable();
#endif
WITH_LOCK(irq_lock) {
trace_sched_migrate(&t, target_cpu->id);
t.stat_migrations.incr();
t.suspend_timers();
t._runtime.export_runtime();
t._detached_state->_cpu = target_cpu;
percpu_base = target_cpu->percpu_base;
current_cpu = target_cpu;
t._runtime.update_after_sleep();
t._detached_state->st.store(thread::status::waiting);
// Note that wakeme is on the same CPU, and irq is disabled,
// so it will not actually run until we stop running.
wakeme->wake_with_irq_or_preemption_disabled([&] { do_wakeme = true; });
#ifdef __aarch64__
reschedule_from_interrupt(source_cpu, false, thyst);
#else
source_cpu->reschedule_from_interrupt();
#endif
}
// wakeme will be implicitly join()ed here.
}
// function to pin another thread:
void thread::pin(thread *t, cpu *target_cpu)
{
if (t == current()) {
thread::pin(target_cpu);
return;
}
// To work on the target thread, we need to run code on the same CPU on
// where the target thread is currently running. We start here a new
// helper thread to follow the target thread's CPU. We could have also
// re-used an existing thread (e.g., the load balancer thread).
thread_unique_ptr helper(thread::make_unique([&] {
#if CONF_lazy_stack_invariant
assert(!thread::current()->is_app());
#endif
WITH_LOCK(irq_lock) {
// This thread started on the same CPU as t, but by now t might
// have moved. If that happened, we need to move too.
while (sched::cpu::current() != t->tcpu()) {
DROP_LOCK(irq_lock) {
thread::pin(t->tcpu());
}
}
// At this point, t is not running and it belongs to this CPU, and
// we hold the irq lock, so we can mess with t's data structures.
if (t->_pinned) {
// The thread was already pin()ed, explaining 1 on
// _migration_lock_counter. Remove this pinning, so the code
// below can pin it again and not think a temporary
// migration_disable() is in force.
t->_migration_lock_counter--;
}
if (t->tcpu() == target_cpu) {
t->_migration_lock_counter++;
t->_pinned = true;
return;
}
// The target thread might be temporarily holding a migration lock
// and we must not migrate it in the middle of this. Currently we
// sleep a bit and retry, I don't know if there's a better way.
while(t->_migration_lock_counter) {
t->_migration_lock_counter++;
DROP_LOCK(irq_lock) {
debug("sched::thread::pin() retrying\n");
// we drop the irq lock but still hold migration lock on t
// and also the helper thread is pinned, so when we get
// the irq lock back, they will still be on same CPU.
sched::thread::sleep(std::chrono::milliseconds(1));
}
t->_migration_lock_counter--;
}
t->_migration_lock_counter = 1;
t->_pinned = true;
// Racing with another CPU doing t->wake() is a complication.
// The biggest risk is that t will be woken up on the new (target)
// CPU, but read old values for some of its variables. Let's avoid
// this risk by pretending that the thread is already waking up.
// After this pretense we will have to really wake it up at the
// end (if not, we may lose a real wakeup!). That may be a
// spurious wakeup, but spurious wakeups are fine.
// Importantly, if the thread was already woken on this CPU before
// we moved it and woken it again, handle_incoming_wakeups() on
// this CPU will notice it doesn't belong to it and ignore it.
if (t->_detached_state->st.load(std::memory_order_relaxed)
== status::waiting) {
t->_detached_state->st.store(status::waking);
}
switch (t->_detached_state->st.load(std::memory_order_relaxed)) {
case status::prestarted:
case status::sending_lock:
case status::waking:
trace_sched_migrate(t, target_cpu->id);
t->stat_migrations.incr();
t->suspend_timers();
t->_runtime.export_runtime();
t->_detached_state->_cpu = target_cpu;
t->remote_thread_local_var(::percpu_base) = target_cpu->percpu_base;
t->remote_thread_local_var(current_cpu) = target_cpu;
// May be a spurious wakeup, but that doesn't matter (see
// comment above).
if (t->_detached_state->st.load(std::memory_order_relaxed) == status::waking) {
t->_detached_state->st.store(status::waiting);
t->wake_with_irq_disabled();
}
break;
case status::queued:
current_cpu->runqueue.erase(current_cpu->runqueue.iterator_to(*t));
trace_sched_migrate(t, target_cpu->id);
t->stat_migrations.incr();
t->suspend_timers();
t->_runtime.export_runtime();
t->_detached_state->_cpu = target_cpu;
t->remote_thread_local_var(::percpu_base) = target_cpu->percpu_base;
t->remote_thread_local_var(current_cpu) = target_cpu;
// pretend the thread was waiting, so we can wake it
t->_detached_state->st.store(status::waiting);
t->wake_with_irq_disabled();
break;
default:
// Thread is in an unexpected state (for example, already
// terminated, or not started), and cannot be moved.
return;
}
}
}, sched::thread::attr().pin(t->tcpu())));
helper->start();
helper->join();
}
void thread::unpin()
{
// Unpinning the current thread is straightforward. But to work on a
// different thread safely, without risking races with concurrent attempts
// to pin, unpin, or migrate the same thread, we need to run the actual
// unpinning code on the same CPU as the target thread.
if (this == current()) {
#if CONF_lazy_stack_invariant
assert(arch::irq_enabled() && sched::preemptable());
#endif
#if CONF_lazy_stack
arch::ensure_next_stack_page();
#endif
WITH_LOCK(preempt_lock) {
if (_pinned) {
_pinned = false;
std::atomic_signal_fence(std::memory_order_release);
_migration_lock_counter--;
}
}
return;
}
thread_unique_ptr helper(thread::make_unique([this] {
#if CONF_lazy_stack_invariant
assert(!thread::current()->is_app());
#endif
WITH_LOCK(preempt_lock) {
// helper thread started on the same CPU as "this", but by now
// "this" might migrated. If that happened helper need to migrate.
while (sched::cpu::current() != this->tcpu()) {
DROP_LOCK(preempt_lock) {
thread::pin(this->tcpu());
}
}
if (_pinned) {
_pinned = false;
std::atomic_signal_fence(std::memory_order_release);
_migration_lock_counter--;
}
}
}, sched::thread::attr().pin(tcpu())));
helper->start();
helper->join();
}
void cpu::load_balance()
{
notifier::fire();
timer tmr(*thread::current());
while (true) {
tmr.set(osv::clock::uptime::now() + 100_ms);
thread::wait_until([&] { return tmr.expired(); });
if (runqueue.empty()) {
continue;
}
auto min = *std::min_element(cpus.begin(), cpus.end(),
[](cpu* c1, cpu* c2) { return c1->load() < c2->load(); });
if (min == this) {
continue;
}
// This CPU is temporarily running one extra thread (this thread),
// so don't migrate a thread away if the difference is only 1.
if (min->load() >= (load() - 1)) {
continue;
}
#if CONF_lazy_stack_invariant
assert(!thread::current()->is_app());
#endif
WITH_LOCK(irq_lock) {
auto i = std::find_if(runqueue.rbegin(), runqueue.rend(),
[](thread& t) { return t._migration_lock_counter == 0; });
if (i == runqueue.rend()) {
continue;
}
auto& mig = *i;
trace_sched_migrate(&mig, min->id);
runqueue.erase(std::prev(i.base())); // i.base() returns off-by-one
// we won't race with wake(), since we're not thread::waiting
assert(mig._detached_state->st.load() == thread::status::queued);
mig._detached_state->st.store(thread::status::waking);
mig.suspend_timers();
mig._detached_state->_cpu = min;
// Convert the CPU-local runtime measure to a globally meaningful
// measure
mig._runtime.export_runtime();
mig.remote_thread_local_var(::percpu_base) = min->percpu_base;
mig.remote_thread_local_var(current_cpu) = min;
mig.stat_migrations.incr();
min->incoming_wakeups[id].push_back(mig);
min->incoming_wakeups_mask.set(id);
// FIXME: avoid if the cpu is alive and if the priority does not
// FIXME: warrant an interruption
min->send_wakeup_ipi();
}
}
}
cpu::notifier::notifier(std::function<void ()> cpu_up)
: _cpu_up(cpu_up)
{
WITH_LOCK(_mtx) {
_notifiers.push_back(this);
}
}
cpu::notifier::~notifier()
{
WITH_LOCK(_mtx) {
_notifiers.remove(this);
}
}
void cpu::notifier::fire()
{
WITH_LOCK(_mtx) {
for (auto n : _notifiers) {
n->_cpu_up();
}
}
}
void thread::yield(thread_runtime::duration preempt_after)
{
trace_sched_yield();
auto t = current();
#if CONF_lazy_stack_invariant
assert(arch::irq_enabled());
#endif
#if CONF_lazy_stack
sched::ensure_next_stack_page_if_preemptable();
#endif
std::lock_guard<irq_lock_type> guard(irq_lock);
// FIXME: drive by IPI
cpu::current()->handle_incoming_wakeups();
// FIXME: what about other cpus?
if (cpu::current()->runqueue.empty()) {
return;
}
assert(t->_detached_state->st.load() == status::running);
// Do not yield to a thread with idle priority
thread &tnext = *(cpu::current()->runqueue.begin());
if (tnext.priority() == thread::priority_idle) {
return;
}
trace_sched_yield_switch();
#ifdef __aarch64__
reschedule_from_interrupt(cpu::current(), true, preempt_after);
#else
cpu::current()->reschedule_from_interrupt(true, preempt_after);
#endif
}
void thread::set_priority(float priority)
{
_runtime.set_priority(priority);
}
float thread::priority() const
{
return _runtime.priority();
}
void thread::set_realtime_priority(unsigned priority)
{
_realtime._priority = priority;
}
unsigned thread::realtime_priority() const
{
return _realtime._priority;
}
void thread::set_realtime_time_slice(thread_realtime::duration time_slice)
{
if (time_slice > 0) {
WARN_ONCE("set_realtime_time_slice() used but real-time time slices"
" not yet supported");
}
_realtime._time_slice = time_slice;
}
thread_realtime::duration thread::realtime_time_slice() const {
return _realtime._time_slice;
}
sched::thread::status thread::get_status() const
{
return _detached_state->st.load(std::memory_order_relaxed);
}
thread::stack_info::stack_info()
: begin(nullptr), size(0), deleter(nullptr)
{
}
thread::stack_info::stack_info(void* _begin, size_t _size)
: begin(_begin), size(_size), deleter(nullptr)
{
auto end = align_down(begin + size, 16);
size = static_cast<char*>(end) - static_cast<char*>(begin);
}
void thread::stack_info::default_deleter(thread::stack_info si)
{
free(si.begin);
}
// thread_map is used for a list of all threads, but also as a map from
// numeric (4-byte) threads ids to the thread object, to support Linux
// functions which take numeric thread ids.
static mutex thread_map_mutex;
using id_type = std::result_of<decltype(&thread::id)(thread)>::type;
std::unordered_map<id_type, thread *> thread_map
__attribute__((init_priority((int)init_prio::threadlist)));
static thread_runtime::duration total_app_time_exited(0);
thread_runtime::duration thread::thread_clock() {
if (this == current()) {
#if CONF_lazy_stack_invariant
assert(arch::irq_enabled() && sched::preemptable());
#endif
#if CONF_lazy_stack
arch::ensure_next_stack_page();
#endif
WITH_LOCK (preempt_lock) {
// Inside preempt_lock, we are running and the scheduler can't
// intervene and change _total_cpu_time or _running_since
return _total_cpu_time +
(osv::clock::uptime::now() - tcpu()->running_since);
}
} else {
auto status = _detached_state->st.load(std::memory_order_acquire);
if (status == thread::status::running) {
// The cputime_estimator set before the status is already visible.
// Even if the thread stops running now, cputime_estimator will
// remain; Our max overshoot will be the duration of this code.
osv::clock::uptime::time_point running_since;
osv::clock::uptime::duration total_cpu_time;
cputime_estimator_get(running_since, total_cpu_time);
return total_cpu_time +
(osv::clock::uptime::now() - running_since);
} else {
// _total_cpu_time is set before setting status, so it is already
// visible. During this code, the thread might start running, but
// it doesn't matter, total_cpu_time will remain. Our maximum
// undershoot will be the duration that this code runs.
// FIXME: we assume reads/writes to _total_cpu_time are atomic.
// They are, but we should use std::atomic to guarantee that.
return _total_cpu_time;