diff options
Diffstat (limited to 'content/2023-01-14-xpost-matcha-threads/index.md')
-rw-r--r-- | content/2023-01-14-xpost-matcha-threads/index.md | 33 |
1 files changed, 25 insertions, 8 deletions
diff --git a/content/2023-01-14-xpost-matcha-threads/index.md b/content/2023-01-14-xpost-matcha-threads/index.md index 3456b09..a916145 100644 --- a/content/2023-01-14-xpost-matcha-threads/index.md +++ b/content/2023-01-14-xpost-matcha-threads/index.md @@ -51,14 +51,11 @@ underlying cooperative-multitasking and implement such a `yield()` function as shown in the example above. Looking at the final implementation, the yield function does the following: -```txt -yield: - 1. function prologue - 2. push callee-saved regs to current stack - 3. swap stack pointers (current - new) - 4. pop callee-saved regs from new stack - 5. function epilogue & return -``` +1. push callee-saved regs to current stack +2. swap stack pointers (current - new) +3. pop callee-saved regs from new stack + +<img src="yield.svg"> Implementations for different ISAs are available here: - [x86_64][yield-x86] @@ -66,6 +63,24 @@ Implementations for different ISAs are available here: - [armv7a][yield-arm] - [riscv64][yield-rv64] +<div style="overflow: auto;"> +<img src="init-stack.svg" style="float: right; width: 20%; padding-left: 2ch;"> + +Since a thread returns into the last stack-frame of the new thread after +switching the stack pointers in the yield function, special care must be taken +when a new stack is created. + +The _initial stack_ is setup such that, when yield-ing into the new stack for +the first time, the stack contains the initial values for the callee-saved +registers, which yield will restore and the return frame contains an address +which should be returned to when returning from yield. + +An example of setting up the initial stack can be seen in [init_stack +(x86)][init-stack]. From this it can also be seen that the first time the +thread will return to [thread_create][thread-create], which just calls into a +function passed to [init_stack][init-stack]. +</div> + ## Appendix: os-level vs user-level threading The figure below depicts *os-level* threading (left) vs *user-level* threading @@ -89,3 +104,5 @@ to the scheduler, the stack-pointer is switched back to **stack S**. [yield-arm]: https://github.com/johannst/matcha-threads/blob/master/lib/arch/arm/yield.s [yield-arm64]: https://github.com/johannst/matcha-threads/blob/master/lib/arch/arm64/yield.s [yield-rv64]: https://github.com/johannst/matcha-threads/blob/master/lib/arch/riscv64/yield.s +[init-stack]: https://github.com/johannst/matcha-threads/blob/master/lib/arch/x86_64/init_stack.cc +[thread-create]: https://github.com/johannst/matcha-threads/blob/master/lib/arch/x86_64/thread_create.s |