forked from alibaba/PhotonLibOS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththread.cpp
More file actions
2060 lines (1903 loc) · 65.1 KB
/
Copy paththread.cpp
File metadata and controls
2060 lines (1903 loc) · 65.1 KB
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 2022 The Photon Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#define protected public
#include <photon/thread/thread.h>
#include <photon/thread/timer.h>
#include "list.h"
#undef protected
#include <memory.h>
#include <sys/time.h>
#include <unistd.h>
#include <cstddef>
#include <cassert>
#include <cerrno>
#include <vector>
#include <new>
#include <thread>
#include <mutex>
#include <condition_variable>
#ifdef _WIN64
#include <processthreadsapi.h>
#include <stdlib.h>
inline int posix_memalign(void** memptr, size_t alignment, size_t size) {
auto ok = malloc(size);
if (!ok)
return ENOMEM;
*memptr = ok;
return 0;
}
#else
#include <sys/mman.h>
#endif
#include <photon/io/fd-events.h>
#include <photon/common/timeout.h>
#include <photon/common/alog.h>
#include <photon/common/alog-functionptr.h>
#include <photon/thread/thread-key.h>
#include <photon/thread/arch.h>
/* notes on the scheduler:
1. runq (denoted by CURRENT) and sleepq are compeltely private,
i.e. they are *not* accessed by other vcpus;
2. accessing runq and sleepq doesn't need locking, but a thread
needs locking in order to get in / out of runq, so as to prevent
racing among thread_usleep() and thread_interrupt()s;
3. always lock struct thread before waitq, so as to avoid deadlock;
4. standbyq, all waitqs, and struct thread *may* be accessed by
other vcpus at anytime;
5. for thread_interrupt()s that crosses vcpus, threads are pushed
to standbyq (with locking, of course) of target vcpu, setting to
state READY; they will be moved to runq (and popped from sleepq)
by target vcpu in resume_thread(), when its runq becomes empty;
*/
// Define assembly section header for clang and gcc
#if defined(__APPLE__)
#define DEF_ASM_FUNC(name) ".text\n" \
#name": "
#elif defined(_WIN64)
#define DEF_ASM_FUNC(name) ".text\n .p2align 4\n" \
".def "#name"; .scl 3; .type 32; .endef\n" \
#name": "
#else
#define DEF_ASM_FUNC(name) ".section .text."#name",\"axG\",@progbits,"#name",comdat\n" \
".type "#name", @function\n" \
#name": "
#endif
namespace photon
{
inline uint64_t min(uint64_t a, uint64_t b) { return (a<b) ? a : b; }
class NullEventEngine : public MasterEventEngine {
public:
std::mutex _mutex;
std::condition_variable _cvar;
std::atomic_bool notify{false};
__attribute__((noinline))
int wait_for_fd(int fd, uint32_t interests, Timeout timeout) override {
return -1;
}
__attribute__((noinline))
int cancel_wait() override {
{
std::unique_lock<std::mutex> lock(_mutex);
notify.store(true, std::memory_order_release);
}
_cvar.notify_all();
return 0;
}
__attribute__((noinline))
ssize_t wait_and_fire_events(uint64_t timeout) override {
DEFER(notify.store(false, std::memory_order_release));
if (!timeout) return 0;
timeout = min(timeout, 1000 * 100UL);
std::unique_lock<std::mutex> lock(_mutex);
if (notify.load(std::memory_order_acquire)) {
return 0;
}
_cvar.wait_for(lock, std::chrono::microseconds(timeout));
return 0;
}
};
static Delegate<void*, size_t> photon_thread_alloc(
&default_photon_thread_stack_alloc, nullptr);
static Delegate<void, void*, size_t> photon_thread_dealloc(
&default_photon_thread_stack_dealloc, nullptr);
struct vcpu_t;
struct thread;
class Stack
{
public:
template<typename F>
void init(void* ptr, F ret2func, thread* th)
{
_ptr = ptr;
assert((uint64_t)_ptr % 16 == 0);
push(0);
push(0);
push(ret2func);
push(th); // rbp <== th
}
void** pointer_ref()
{
return &_ptr;
}
void push(uint64_t x)
{
*--(uint64_t*&)_ptr = x;
}
template<typename T>
void push(const T& x)
{
push((uint64_t)x);
}
uint64_t pop()
{
return *((uint64_t*&)_ptr)++;
}
uint64_t& operator[](int i)
{
return static_cast<uint64_t*>(_ptr)[i];
}
void* _ptr;
};
struct thread_list;
struct thread : public intrusive_list_node<thread> {
volatile vcpu_t* vcpu;
Stack stack;
// offset 32B
int idx = -1; /* index in the sleep queue array */
int error_number = 0;
thread_list* waitq = nullptr; /* the q if WAITING in a queue */
uint16_t state = states::READY;
spinlock lock, _;
int flags = 0;
uint64_t ts_wakeup = 0; /* Wakeup time when thread is sleeping */
// offset 64B
union {
void* arg = nullptr; /* will be reused as thread local */
void* tls; /* storage after thread started */
};
union {
thread_entry start;
uint64_t semaphore_count;
uint64_t rwlock_mark;
void* retval;
};
char* buf = nullptr;
char* stackful_alloc_top;
size_t stack_size;
// offset 96B
condition_variable cond; /* used for join */
enum shift {
joinable = 0,
shutting_down = 1, // the thread should cancel what is doing, and quit
}; // current job ASAP; not allowed to sleep or block more
// than 10ms, otherwise -1 will be returned and errno == EPERM
bool is_bit(int i) { return flags & (1<<i); }
void clear_bit(int i) { flags &= ~(1<<i); }
void set_bit(int i) { flags |= (1<<i); }
void set_bit(int i, bool flag) { if (likely(flag)) set_bit(i); else clear_bit(i); }
bool is_joinable() { return is_bit(shift::joinable); }
void set_joinable(bool flag = true) { set_bit(shift::joinable, flag); }
bool is_shutting_down() { return is_bit(shift::shutting_down); }
void set_shutting_down(bool flag = true) { set_bit(shift::shutting_down, flag); }
int set_error_number() {
if (likely(error_number)) {
errno = error_number;
error_number = 0;
return -1;
}
return 0;
}
struct stack_alloc_header {
uint32_t size;
uint32_t reserved;
};
static_assert(sizeof(stack_alloc_header) == sizeof(uint64_t),
"stack_alloc_header size not fit");
void* stackful_malloc(size_t size) {
auto ret = stackful_alloc_top;
stackful_alloc_top += size;
auto head = (stack_alloc_header*)stackful_alloc_top;
head->size = size;
stackful_alloc_top += sizeof(stack_alloc_header);
return ret;
}
void stackful_free(void* ptr) {
assert(((uint64_t)ptr) < ((uint64_t)stackful_alloc_top));
auto rc = stackful_alloc_top - sizeof(stack_alloc_header);
(void)rc;
assert(ptr == (rc - ((stack_alloc_header*)rc)->size));
stackful_alloc_top = (char*)ptr;
}
void init_main_thread_stack() {
#ifdef __APPLE__
auto self = pthread_self();
stack_size = pthread_get_stacksize_np(self);
stackful_alloc_top = (char*) pthread_get_stackaddr_np(self);
#elif defined(_WIN64)
ULONG_PTR stack_low, stack_high;
GetCurrentThreadStackLimits(&stack_low, &stack_high);
stackful_alloc_top = (char*)stack_low;
stack_size = stack_high - stack_low;
#elif defined(__linux__)
pthread_attr_t gattr;
pthread_getattr_np(pthread_self(), &gattr);
pthread_attr_getstack(&gattr,
(void**)&stackful_alloc_top, &stack_size);
pthread_attr_destroy(&gattr);
#else
static_assert(false, "unsupported platform");
#endif
}
void go() {
assert(this == CURRENT);
auto _arg = arg;
arg = nullptr;
retval = start(_arg);
die();
}
void die() __attribute__((always_inline));
void dequeue_ready_atomic(states newstat = states::READY);
vcpu_t* get_vcpu() {
return (vcpu_t*)vcpu;
}
bool operator < (const thread &rhs) {
return this->ts_wakeup < rhs.ts_wakeup;
}
void dispose() {
assert(state == states::DONE);
// `buf` and `stack_size` will always store on register
// when calling deallocating.
photon_thread_dealloc(buf, stack_size);
}
};
#if defined(__has_feature)
# if __has_feature(address_sanitizer) // for clang
# ifndef __SANITIZE_ADDRESS__
# define __SANITIZE_ADDRESS__ // GCC already sets this
# endif
# endif
#endif
#ifdef __SANITIZE_ADDRESS__
extern "C" {
// Check out sanitizer/asan-interface.h in compiler-rt for documentation.
void __sanitizer_start_switch_fiber(void** fake_stack_save, const void* bottom,
size_t size);
void __sanitizer_finish_switch_fiber(void* fake_stack_save,
const void** bottom_old, size_t* size_old);
}
static void asan_start(void** save, thread* to) {
void* bottom = to->buf ? to->buf : to->stackful_alloc_top;
__sanitizer_start_switch_fiber(save, bottom,
to->stack_size);
}
static void asan_finish(void* save) {
__sanitizer_finish_switch_fiber(save, nullptr, nullptr);
}
#define ASAN_START() asan_finish((void*)nullptr);
#define ASAN_SWITCH(to) \
void* __save; \
asan_start(&__save, to); \
DEFER({ asan_finish(__save); });
#define ASAN_DIE_SWITCH(to) \
asan_start(nullptr, to);
#else
#define ASAN_START(ptr)
#define ASAN_SWITCH(to)
#define ASAN_DIE_SWITCH(to)
#endif
static void _asan_start() asm("_asan_start");
__attribute__((used)) static void _asan_start() { ASAN_START(); }
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Winvalid-offsetof"
static_assert(offsetof(thread, vcpu) == offsetof(partial_thread, vcpu), "...");
static_assert(offsetof(thread, tls) == offsetof(partial_thread, tls), "...");
#pragma GCC diagnostic pop
struct thread_list : public intrusive_list<thread>
{
spinlock lock;
thread_list() = default;
thread_list(thread* head) {
this->node = head;
}
thread* eject_whole_atomic() {
if (!node) return nullptr;
SCOPED_LOCK(lock);
auto p = node;
node = nullptr;
return p;
}
};
class SleepQueue
{
public:
std::vector<thread *> q;
thread* front() const
{
assert(!q.empty());
return q.front();
}
bool empty() const
{
return q.empty();
}
int push(thread *obj)
{
q.push_back(obj);
obj->idx = q.size() - 1;
up(obj->idx);
return 0;
}
thread* pop_front()
{
auto ret = q[0];
if (q.size() == 1) {
q.pop_back();
return ret;
}
q[0] = q.back();
q[0]->idx = 0;
q.pop_back();
down(0);
ret->idx = -1;
return ret;
}
int pop(thread *obj)
{
if (obj->idx == -1) return -1;
if ((size_t)obj->idx == q.size() - 1){
q.pop_back();
obj->idx = -1;
return 0;
}
auto id = obj->idx;
if (q.size() == 1) {
assert(id == 0);
q.pop_back();
return 0;
}
q[obj->idx] = q.back();
q[id]->idx = id;
q.pop_back();
if (!up(id)) down(id);
obj->idx = -1;
return 0;
}
void update_node(int idx, thread *&obj)
{
q[idx] = obj;
q[idx]->idx = idx;
}
// compare m_nodes[idx] with parent node.
bool up(int idx)
{
assert(!q.empty());
auto tmp = q[idx];
bool ret = false;
while (idx != 0){
auto cmpIdx = (idx - 1) >> 1;
if (*tmp < *q[cmpIdx]) {
update_node(idx, q[cmpIdx]);
idx = cmpIdx;
ret = true;
continue;
}
break;
}
if (ret) update_node(idx, tmp);
return ret;
}
// compare m_nodes[idx] with child node.
bool down(int idx)
{
assert(!q.empty());
auto tmp = q[idx];
size_t cmpIdx = (idx << 1) + 1;
bool ret = false;
while (cmpIdx < q.size()) {
if (cmpIdx + 1 < q.size() && *q[cmpIdx + 1] < *q[cmpIdx]) cmpIdx++;
if (*q[cmpIdx] < *tmp){
update_node(idx, q[cmpIdx]);
idx = cmpIdx;
cmpIdx = (idx << 1) + 1;
ret = true;
continue;
}
break;
}
if (ret) update_node(idx, tmp);
return ret;
}
};
// A special spinlock that distinguishes a foreground vCPU among
// background vCPUs, and makes the foreground as fast as possible.
// Generic spinlock uses atomic exchange to obtain the lock, which
// depends on bus lock and costs much CPU cycles than this design.
class asymmetric_spinLock {
// TODO: better place the two atomics in separate cache line?
std::atomic_bool foreground_locked {false},
background_locked {false};
void wait_while(std::atomic_bool& x) {
while (unlikely(x.load(std::memory_order_acquire))) {
do { spin_wait(); }
while(likely(x.load(std::memory_order_relaxed)));
}
}
public:
void foreground_lock() {
// lock
foreground_locked.store(true, std::memory_order_release);
// wait if (unlikely) background locked
wait_while(background_locked);
}
bool background_try_lock() {
while(true) {
// wait if (unlikely) foreground locked
wait_while(foreground_locked);
// try lock
if (background_locked.exchange(true, std::memory_order_acquire))
return false; // avoid wait while holding the lock
// check to make sure it is still unlocked
if (likely(!foreground_locked.load(std::memory_order_acquire)))
return true;
// otherwise release lock, wait, and repeat again
background_locked.store(false, std::memory_order_release);
spin_wait();
}
return true;
}
void foreground_unlock() {
foreground_locked.store(false, std::memory_order_release);
}
void background_unlock() {
background_locked.store(false, std::memory_order_release);
}
};
struct vcpu_t : public vcpu_base {
SleepQueue sleepq; // sizeof(sleepq) should be 24: ptr, size and capcity
asymmetric_spinLock runq_lock;
uint16_t state = states::RUNNING;
std::atomic<uint32_t> nthreads{1};
// offset 48B
template<typename T>
void move_to_standbyq_atomic(T x)
{
_move_to_standbyq_atomic(x);
master_event_engine->cancel_wait();
}
void _move_to_standbyq_atomic(thread_list* lst)
{
SCOPED_LOCK(standbyq.lock);
auto head = lst->front();
auto tail = lst->back();
standbyq.push_back(std::move(*lst));
for (auto th = head; th != tail; th = th->next()) {
assert(this == th->vcpu);
th->lock.unlock();
}
assert(this == tail->vcpu);
tail->lock.unlock();
}
void _move_to_standbyq_atomic(thread* th)
{
assert(this == th->vcpu);
SCOPED_LOCK(standbyq.lock);
standbyq.push_back(th);
}
thread* idle_worker;
NullEventEngine _default_event_engine;
vcpu_t() {
master_event_engine = &_default_event_engine;
}
bool is_master_event_engine_default() {
return &_default_event_engine == master_event_engine;
}
void reset_master_event_engine_default() {
auto& mee = master_event_engine;
if (&_default_event_engine == mee) return;
delete mee;
mee = &_default_event_engine;
}
// standby queue stores the threads that are running, but not
// yet added to the run queue, until the run queue becomes empty
thread_list standbyq; // make it NOT in the first cache line (64B)
}; // where private fields reside
#define SCOPED_FOREGROUND_LOCK(x) \
auto __px = &(x); __px->foreground_lock(); DEFER(__px->foreground_unlock());
#define SCOPED_BACKGROUND_LOCK(x) \
(x).background_lock(); DEFER((x).background_unlock());
class RunQ {
public:
thread** pc = &CURRENT;
mutable thread* current;
RunQ() {
asm volatile ("" : "=r"(pc) : "0"(pc));
current = *pc;
}
};
struct Switch { thread *from, *to; };
class AtomicRunQ : public RunQ {
public:
vcpu_t* vcpu;
mutable asymmetric_spinLock* plock;
AtomicRunQ(const RunQ& runq = RunQ()) : RunQ(runq) {
vcpu = current->get_vcpu();
(plock = &vcpu->runq_lock) -> foreground_lock();
}
mutable bool update_current = false;
void set_current(thread* th) const {
current = th;
update_current = true;
}
~AtomicRunQ() {
if (update_current)
*pc = current;
plock->foreground_unlock();
}
static void prefetch_context(thread* from, thread* to)
{
#ifdef CONTEXT_PREFETCHING
const int CACHE_LINE_SIZE = 64;
auto f = *from->stack.pointer_ref();
__builtin_prefetch(f, 1);
// __builtin_prefetch((char*)f + CACHE_LINE_SIZE, 1);
auto t = *to->stack.pointer_ref();
__builtin_prefetch(t, 0);
// __builtin_prefetch((char*)t + CACHE_LINE_SIZE, 0);
#endif
}
Switch remove_current(states new_state) const {
assert(!current->single());
auto from = current;
auto to = from->remove_from_list();
set_current(to);
prefetch_context(from, to);
from->state = new_state;
to->state = states::RUNNING;
return {from, to};
}
Switch _do_goto(thread* to) const {
auto from = current;
prefetch_context(from, to);
from->state = states::READY;
to->state = states::RUNNING;
set_current(to);
return {from, to};
}
Switch goto_next() const {
assert(!current->single());
return _do_goto(current->next());
}
Switch try_goto(thread* th) const {
assert(th->vcpu == vcpu);
th->remove_from_list();
current->insert_after(th);
return _do_goto(th);
}
bool single() const {
return current->single();
}
bool size_1or2() const {
return current->next() == current->prev();
}
void insert_tail(thread* th) const {
current->insert_tail(th);
}
void insert_list_before(thread* th) const {
current->insert_list_before(th);
}
void remove_from_list(thread* th) const {
assert(th->state == states::READY);
assert(th->vcpu == vcpu);
assert(th != current);
th->remove_from_list();
}
bool defer_to_new_thread() const {
auto idle_worker = vcpu->idle_worker;
if (current->next() == idle_worker) {
if (idle_worker->next() == current) {
// if defer_func is executed in idle_worker and it yields,
// photon will be broken. so we should return true and
// create a new thread to execute the defer func.
return true;
}
// postpone idle worker
auto next = idle_worker->remove_from_list();
next->insert_after(idle_worker);
}
return false;
}
};
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Winvalid-offsetof"
static_assert(offsetof(thread, arg) == 0x40, "...");
static_assert(offsetof(thread, start) == 0x48, "...");
#pragma GCC diagnostic pop
inline void thread::dequeue_ready_atomic(states newstat)
{
assert("this is not in runq, and this->lock is locked");
if (waitq) {
assert(waitq->front());
SCOPED_LOCK(waitq->lock);
waitq->erase(this);
waitq = nullptr;
} else {
assert(this->single());
}
state = newstat;
}
__thread thread* CURRENT;
static void spinlock_unlock(void* m_);
inline void prepare_switch(thread* from, thread* to) {
assert(from->vcpu == to->vcpu);
assert(to->state == states::RUNNING);
auto& cnt = to->get_vcpu()->switch_count;
(*(uint64_t*)&cnt)++; // increment of volatile variable is deprecated
}
static void _photon_thread_die(thread* th) asm("_photon_thread_die");
#if defined(__x86_64__)
#if !defined(_WIN64)
asm(
DEF_ASM_FUNC(_photon_switch_context) // (void** rdi_to, void** rsi_from)
R"(
push %rbp
mov %rsp, (%rsi)
mov (%rdi), %rsp
pop %rbp
ret
)"
DEF_ASM_FUNC(_photon_switch_context_defer) // (void* rdi_arg, void (*rsi_defer)(void*), void** rdx_to, void** rcx_from)
R"(
push %rbp
mov %rsp, (%rcx)
)"
DEF_ASM_FUNC(_photon_switch_context_defer_die) // (void* rdi_arg, void (*rsi_defer)(void*), void** rdx_to_th)
R"(
mov (%rdx), %rsp
pop %rbp
jmp *%rsi
)"
DEF_ASM_FUNC(_photon_thread_stub)
R"(
call _asan_start
mov 0x40(%rbp), %rdi
movq $0, 0x40(%rbp)
call *0x48(%rbp)
mov %rax, 0x48(%rbp)
mov %rbp, %rdi
call _photon_thread_die
)"
);
inline void switch_context(thread* from, thread* to) {
ASAN_SWITCH(to);
prepare_switch(from, to);
auto _t_ = to->stack.pointer_ref();
register auto f asm("rsi") = from->stack.pointer_ref();
register auto t asm("rdi") = _t_;
asm volatile("call _photon_switch_context" // (to, from)
: "+r"(t), "+r"(f)
: // "0"(t), "1"(f)
: "rax", "rbx", "rcx", "rdx", "r8", "r9", "r10", "r11",
"r12", "r13", "r14", "r15");
}
inline void switch_context_defer(thread* from, thread* to,
void (*defer)(void*), void* arg) {
ASAN_SWITCH(to);
prepare_switch(from, to);
auto _t_ = to->stack.pointer_ref();
register auto f asm("rcx") = from->stack.pointer_ref();
register auto t asm("rdx") = _t_;
register auto a asm("rdi") = arg;
register auto d asm("rsi") = defer;
asm volatile(
"call _photon_switch_context_defer" // (arg, defer, to, from)
: "+r"(t), "+r"(f), "+r"(a), "+r"(d)
: // "0"(t), "1"(f), "2"(a), "3"(d)
: "rax", "rbx", "r8", "r9", "r10", "r11", "r12", "r13", "r14",
"r15");
}
#else // _WIN64
asm(
DEF_ASM_FUNC(_photon_switch_context) // (void** rcx_to, void** rdx_from)
R"(
push %rbp
mov %rsp, (%rdx)
mov (%rcx), %rsp
pop %rbp
ret
)"
DEF_ASM_FUNC(_photon_switch_context_defer) // (void* rcx_arg, void (*rdx_defer)(void*), void** r8_to, void** r9_from)
R"(
push %rbp
mov %rsp, (%r9)
)"
DEF_ASM_FUNC(_photon_switch_context_defer_die) // (void* rcx_arg, void (*rdx_defer)(void*), void** r8_to)
R"(
mov (%r8), %rsp
pop %rbp
jmp *%rdx
)"
DEF_ASM_FUNC(_photon_thread_stub)
R"(
call _asan_start
mov 0x40(%rbp), %rcx
movq $0, 0x40(%rbp)
call *0x48(%rbp)
mov %rax, 0x48(%rbp)
mov %rbp, %rcx
call _photon_thread_die
)"
);
inline void switch_context(thread* from, thread* to) {
ASAN_SWITCH(to);
prepare_switch(from, to);
auto _t_ = to->stack.pointer_ref();
register auto f asm("rdx") = from->stack.pointer_ref();
register auto t asm("rcx") = _t_;
asm volatile("call _photon_switch_context" // (to, from)
: "+r"(t), "+r"(f)
: // "0"(t), "1"(f)
: "rax", "rbx", "rsi", "rdi", "r8", "r9",
"r10", "r11", "r12", "r13", "r14", "r15",
"xmm6", "xmm7", "xmm8", "xmm9", "xmm10",
"xmm11", "xmm12", "xmm13", "xmm14", "xmm15");
}
inline void switch_context_defer(thread* from, thread* to,
void (*defer)(void*), void* arg) {
ASAN_SWITCH(to);
prepare_switch(from, to);
auto _t_ = to->stack.pointer_ref();
register auto f asm("r9") = from->stack.pointer_ref();
register auto t asm("r8") = _t_;
register auto a asm("rcx") = arg;
register auto d asm("rdx") = defer;
asm volatile(
"call _photon_switch_context_defer" // (arg, defer, to, from)
: "+r"(t), "+r"(f), "+r"(a), "+r"(d)
: // "0"(t), "1"(f), "2"(a), "3"(d)
: "rax", "rbx", "rsi", "rdi", "r10",
"r11", "r12", "r13", "r14", "r15",
"xmm6", "xmm7", "xmm8", "xmm9", "xmm10",
"xmm11", "xmm12", "xmm13", "xmm14", "xmm15");
}
#endif // _WIN64
#elif defined(__aarch64__) || defined(__arm64__)
asm(
DEF_ASM_FUNC(_photon_switch_context) // (void** x0_from, void** x1_to)
R"(
stp x29, x30, [sp, #-16]!
mov x29, sp
str x29, [x0]
ldr x29, [x1]
mov sp, x29
ldp x29, x30, [sp], #16
ret
)"
DEF_ASM_FUNC(_photon_switch_context_defer) // (void* x0_arg, void (*x1_defer)(void*), void** x2_to, void** x3_from)
R"(
stp x29, x30, [sp, #-16]!
mov x29, sp
str x29, [x3]
)"
DEF_ASM_FUNC(_photon_switch_context_defer_die) // (void* x0_arg, void (*x1_defer)(void*), void** x2_to_th)
R"(
ldr x29, [x2]
mov sp, x29
ldp x29, x30, [sp], #16
br x1
)"
DEF_ASM_FUNC(_photon_thread_stub)
R"(
bl _asan_start //; asan_start()
ldp x0, x1, [x29, #0x40] //; load arg, start into x0, x1
str xzr, [x29, #0x40] //; set arg as 0
blr x1 //; start(x0)
str x0, [x29, #0x48] //; retval = result
mov x0, x29 //; move th to x0
b _photon_thread_die //; _photon_thread_die(th)
)"
);
#ifdef __clang__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Winline-asm"
#endif
inline void switch_context(thread* from, thread* to) {
ASAN_SWITCH(to);
prepare_switch(from, to);
auto _t_ = to->stack.pointer_ref();
register auto f asm("x0") = from->stack.pointer_ref();
register auto t asm("x1") = _t_;
asm volatile("bl _photon_switch_context"
: "+r"(t), "+r"(f)
: // "0"(t), "1"(f)
: // Callee saved register, make it as clobber to save
"x19", "x20", "x21", "x22", "x23", "x24", "x25", "x26",
"x27", "x28", "x29", "x30",
// Caller saved register, might change, should save
"x2", "x3", "x4", "x5", "x6", "x7", "x8",
// Corouptable register, may change ,should save
"x9", "x10", "x11", "x12", "x13", "x14", "x15", "x16",
"x17", "x18");
}
inline void switch_context_defer(thread* from, thread* to,
void (*defer)(void*), void* arg) {
ASAN_SWITCH(to);
prepare_switch(from, to);
auto _t_ = to->stack.pointer_ref();
register auto f asm("x3") = from->stack.pointer_ref();
register auto t asm("x2") = _t_;
register auto d asm("x1") = defer;
register auto a asm("x0") = arg;
asm volatile("bl _photon_switch_context_defer"
: "+r"(t), "+r"(f), "+r"(a), "+r"(d)
: // "0"(t), "1"(f), "2"(a), "3"(d)
: "x19", "x20", "x21", "x22", "x23", "x24", "x25", "x26",
"x27", "x28", "x29", "x30", "x4", "x5", "x6", "x7", "x8",
"x9", "x10", "x11", "x12", "x13", "x14", "x15", "x16",
"x17", "x18");
}
#ifdef __clang__
#pragma GCC diagnostic pop
#endif
#endif // x86 or arm
extern "C" void _photon_switch_context_defer_die(void* arg,uint64_t defer_func_addr, void** to)
asm ("_photon_switch_context_defer_die");
inline void thread::die() {
deallocate_tls(&tls);
// if CURRENT is idle stub and during vcpu_fini
// main thread waiting for idle stub joining, now idle might be only
// thread in run-queue. To keep going, wake up waiter before remove
// current from run-queue.
lock.lock();
state = states::DONE;
cond.notify_one();
get_vcpu()->nthreads--;
auto sw = AtomicRunQ().remove_current(states::DONE);
assert(this == sw.from);
uint64_t func;
void* arg;
if (!is_joinable()) {
auto f = &thread::dispose;
func = (uint64_t&)f;
arg = this;
} else {
func = (uint64_t)&spinlock_unlock;
arg = &lock;
}
auto ref = sw.to->stack.pointer_ref();
ASAN_DIE_SWITCH(sw.to);
_photon_switch_context_defer_die(arg, func, ref);
__builtin_unreachable();
}
__attribute__((used)) static
void _photon_thread_die(thread* th) {
assert(th == CURRENT);
th->die();
}
extern "C" void _photon_thread_stub() asm ("_photon_thread_stub");
thread* thread_create(thread_entry start, void* arg,
uint64_t stack_size, uint16_t reserved_space) {
RunQ rq;
if (unlikely(!rq.current))
LOG_ERROR_RETURN(ENOSYS, nullptr, "Photon not initialized in this vCPU (OS thread)");
thread_local uint64_t random_index = 0;
size_t randomizer = (random_index++ % 512) * 8;
// stack contains struct, randomizer space, and reserved_space
size_t least_stack_size = sizeof(thread) + randomizer + 63 + reserved_space;
// at least a whole page for mprotect
least_stack_size += PAGE_SIZE;
// and make sure it's at least 16K
least_stack_size = std::max(16UL * 1024, least_stack_size);
stack_size = align_up(stack_size, PAGE_SIZE);
if (unlikely(stack_size < least_stack_size)) {
LOG_WARN("Stack size ` is less than least stack size `, use ` instead",