Exercise: User-level threads

Hard

xv6 book Sect 8.3 Code: Context switching

User-level threads, sometimes called lightweight threads, are units of execution within a single process managed entirely by a user-space library (i.e., without the kernel’s direct involvement). Because the operating system is unaware of them, they avoid system calls for scheduling and context switching, which makes them lightweight and fast to switch between. They run within a single process and share its address space. In a cooperative threading system, these threads voluntarily yield control of the CPU, allowing multiple threads to make progress efficiently with minimal overhead.

You will implement a simple cooperative threading system where user-level threads voluntarily yield control of the CPU.

Context switching

The core of the threading library is the context switch. When we switch from one thread to another, we need to save the current thread’s registers and restore the new thread’s saved registers.

First create a header file user/uthread.h that will contain common struct and function declarations:

#ifndef UTHREAD_H
#define UTHREAD_H

#include "kernel/types.h"

#define STACK_SIZE  4096

struct thread_context {
  uint64 ra;
  uint64 sp;
  uint64 s0;
  uint64 s1;
  uint64 s2;
  uint64 s3;
  uint64 s4;
  uint64 s5;
  uint64 s6;
  uint64 s7;
  uint64 s8;
  uint64 s9;
  uint64 s10;
  uint64 s11;
};

void thread_switch(struct thread_context* old, struct thread_context* new);

#endif // UTHREAD_H

Create a file user/uthread_switch.S and implement the thread_switch function. It takes two arguments: a pointer to the old thread’s context (a0) and a pointer to the new thread’s context (a1).

.text

/*
 * void thread_switch(struct thread_context *old, struct thread_context *new);
 */

.globl thread_switch
thread_switch:
    /* a0 is old context pointer, a1 is new context pointer */

    /* TODO: implement context switching by saving registers to the old context,
     *       and loading registers from the new context.
     */

    ret

It’s up to you to fill in the TODOs.

:bulb: Carefully read Section 8.3 in the xv6 book, and note that a context switch between two user threads would work the exact same way as switching between two kernel threads. Feel free to copy this code from the kernel to complete this step of the exercise, but make sure you understand everything.

:bulb: In an earlier exercise, you implemented support for floating point operations. You don’t need to take this into consideration for this exercise.

Add $U/uthread_switch.o to ULIB in Makefile, and create a new userspace program user/uthread_test.c:

#include "user/uthread.h"
#include "user/user.h"

struct thread_context main_ctx;
struct thread_context my_func_ctx;
char my_func_stack[STACK_SIZE];

void my_func() {
  int b = 5;
  printf("Hello from my_func! b = %d\n", b);
  b += 10;

  // Switch back to the context stored in main_ctx
  // TODO: YOUR CODE HERE

  printf("Continue my_func! b = %d\n", b);

  // Again: switch back to the context stored in main_ctx
  // TODO: YOUR CODE HERE
}

int main(int argc, char *argv[]) {
  int a = 3;
  printf("Start main! a = %d\n", a);
  a += 5;

  // Initalize a new context for my_func in my_func_ctx.
  // Make sure you initialize the stack pointer (sp) to my_func_stack
  // and the return address (ra) to my_func.
  // TODO: YOUR CODE HERE

  // Save the current context to main_ctx and switch to my_func_ctx
  // TODO: YOUR CODE HERE

  printf("Back in main! a = %d\n", a);
  a += 3;

  // Again: save the current context to main_ctx and switch to my_func_ctx
  // TODO: YOUR CODE HERE

  printf("Done in main! a = %d\n", a);

  return 0;
}

Your task is to do the following:

  1. Initialize a thread_context for the my_func function. Make sure the return address points to my_func, and set the stack pointer to a new stack. We have already provided a global array my_func_stack of size STACK_SIZE that you can use as stack for my_func. Note that the stack grows downwards, hence the stack pointer should be initialized to the top of the stack (end of the my_func_stack array). The figure below visualizes the memory layout of the process and shows where the saved return addresses and stack pointers should point to. Notice how the main thread uses the main stack of the program, while my_func uses a stack that we allocated in the data section.
  2. Call the thread_switch function to repeatedly switch between main and my_func at the indicated locations.

Overview of memory layout

Run your program in the xv6 shell (don’t forget to add your program to UPROGS in Makefile first!). If you implemented it correctly, the output should be the following in the exact same order:

Start main! a = 3
Hello from my_func! b = 5
Back in main! a = 8
Continue my_func! b = 15
Done in main! a = 11

Flow of execution

:bulb: Using context switching lets you interleave multiple functions. Make sure you understand how this works before you continue. What would happen if instead of thread_switch, you call my_func directly? Are you able to get the same interleaving behavior with just function calls? Why (not)?

:bulb: You may be wondering what would happen if the stack of my_func overflows the limit of STACK_SIZE. Currently, corruption of other threads’ memory will occur silently. In later lectures and lab sessions you will learn about virtual memory and page tables, which can be used to overcome this issue.

The threading library

Now that we have the basic context-switching building block, we can implement a library that lets us easily schedule multiple threads. Instead of needing to manually switch to a specific context as you did in the previous step, we will implement a thread_yield function that can be called to yield control of the CPU to any other runnable thread.

First, extend user/uthread.h with the following declarations:

// Initializes the threading library.
void thread_init(void);
// Schedules the next runnable thread.
void thread_schedule(void);
// Creates a new thread that starts executing at the given function pointer.
struct thread *thread_create(void (*func)());
// Yield control of the CPU, allowing another thread to run.
void thread_yield(void);
// Exit the thread.
void thread_exit(void);

Now, implement the threading library in user/uthread.c according to these declarations.

Our implementation will maintain an array of struct thread objects, each with its own stack and context field. We also keep track of whether a thread is UNUSED, RUNNABLE or RUNNING in the state field of each struct thread object.

You can start from the following skeleton. Again, it’s up to you to fill in the TODOs!

#include "user/user.h"
#include "user/uthread.h"

#define MAX_THREAD  8

enum threadstate { UNUSED = 0, RUNNING, RUNNABLE };

struct thread {
  char stack[STACK_SIZE];
  enum threadstate state;
  struct thread_context context;
};

struct thread threads[MAX_THREAD];
struct thread *current_thread;

void
thread_init(void)
{
  // main() is thread 0, which is running on the regular stack.
  // It's the only thread running at the beginning.
  current_thread = &threads[0];
  current_thread->state = RUNNING;
}

void
thread_schedule(void)
{
  struct thread *next_thread = 0;

  // Find the next runnable thread to schedule using simple round-robin scheduling
  struct thread *t = current_thread;
  for (int i = 0; i < MAX_THREAD; i++) {
    t++;

    if (t == &threads[MAX_THREAD]) {
        t = threads; // Wrap back to the start
    }

    if (t->state == RUNNABLE) {
        // Found a runnable thread
        next_thread = t;
        break;
    }
  }

  if (next_thread == 0) {
    // Didn't find a runnable thread, maybe we can resume the current thread?
    if (current_thread->state == RUNNABLE) {
        next_thread = current_thread;
        current_thread->state = RUNNING;
    } else {
        printf("no runnable threads left\n");
        exit(1);
    }
  }

  if (current_thread != next_thread) {
    // Switch to the next thread:
    // - set the state of the chosen thread to RUNNING
    // - make sure `current_thread` will point to the chosen thread
    // - perform the context switch

    // TODO: YOUR CODE HERE
  }
}

struct thread *
thread_create(void (*func)())
{
  struct thread *found = 0;

  for (struct thread *t = threads; t < &threads[MAX_THREAD]; t++) {
    if (t->state == UNUSED) {
      found = t;
      break;
    }
  }

  if (found == 0) {
    printf("no free threads\n");
    return 0;
  }

  // Set up the new thread's context as you did for `my_func` in the previous step.
  // Make sure the thread state is set to RUNNABLE.
  // TODO: YOUR CODE HERE

  return found;
}

void
thread_yield(void)
{
  current_thread->state = RUNNABLE;
  thread_schedule();
}

void
thread_exit(void)
{
  current_thread->state = UNUSED;
  thread_schedule();
}

Make sure you add $U/uthread.o to ULIB in Makefile.

Test your implementation by changing user/uthread_test.c to use your new uthread threading library as follows:

  • Make sure you call thread_init in main before calling any other uthread function
  • Use thread_create to setup up a new context for my_func and register it as a new thread
  • Replace all your uses of thread_switch with thread_yield, which will schedule any runnable thread when called.
  • Call thread_exit at the end of my_func (what could happen if you would forget this?)

Your program should behave exactly as before.


This site uses Just the Docs, a documentation theme for Jekyll.