CS 161 - Computer Science

CS 161 - Computer Science

Context Switches CS 161: Lecture 3 2/2/17 Context Switching A context switch between two user-level threads does not involve the kernel In fact, the kernel isnt even aware of the existence of the threads! The user-level code must save/restore register state, swap stack pointers, etc. Switching from user-mode to kernel-mode (and vice versa) is more complicated The privilege level of the processor must change, the user-level and kernel-level have to agree on how to pass information back and forth, etc. Consider what happens when user-level code makes a system call . . . /* kern/include/kern/syscall.h */ /* */ -// userland/lib/libc/arch/mips/syscalls-mips.S -- Process-related /* #define SYS_fork 0 * The MIPS syscall ABI is #define SYS_vfork

1 as follows: * On SYS_execv entry, call number #define 2 in v0. The rest is like a * normal function call: #define SYS__exit 3 four args in a0-a3, the * . .other // . etcargs . . on . the stack. * // -- File-handle-related -* On SYS_open successful return, #define 45 zero in a3 register; return * value in v0 (v0 and 46 v1 for a 64-bit return value). #define SYS_pipe * #define

SYS_dup 47 * On SYS_dup2 error return, nonzero in a3 register; errno value #define 48 * in SYS_close v0. #define 49 */ #define SYS_read 50 // . . . etc . . . /* kern/arch/mips/include/trapframe.h */ Executing syscall or causing User-mode Standa /* MIPS exception codes. registers */ another trap induces the address rd #define EX_IRQ 0 /* Interrupt */

processor to: space SP Modify Assign values special #define EX_MOD 1 /* TLB (write totoread-only foo() User registers in Coprocessor 0 stack * page) */ Jump to the hardwired address bar() PC #define EX_TLBL 2 /* TLB miss on0x80000080 load */ close_stdout() #define EX_TLBS 3 /* TLB miss EPC: on store Address*/ of instruction which caused trap*/

#define EX_ADEL 4 /* Address error on load Cause:on Set store to enum*/ code #define EX_ADES 5 /* Address error representing the trap fetch reason Heap #define EX_IBE 6 /* Bus error on instruction EPC (e.g., sys call, interrupt); if Static data */ trap was interrupt, bits are // EX_DBE #define 7 /*Cause Bus errorset ontodata

load indicate type*or* (e.g., close_stdout() timer) store */ User Status: In response to trap, li a0, 1 #define EX_SYS 8 /* Statu Syscall */ code hardware sets bits that s li v0, 49 #define EX_BP 9 /* Breakpoint */ Coprocessor elevate privilege mode, #define EX_RI

10 (Kernel-mode /* Reserved (illegal) instruction syscall 0 disable interrupts 0xfffffff f Virtual address space Kernelmode 0x8000000 0 User-mode 0x0 Remember that the kernel shares an address space with user-mode code! So, immediately after syscall (but before kernel code has actually started executing) . . . User

stack User-mode address space foo() Standa registers rd bar() close_stdout() PC Where is the kernel stack? Heap EPC Heap Static data // User close_stdout() code li a0, 1 li v0, 49

syscall SP EEXX__ Cause SYS Statu In Psr tr iv p ts : K : e Of rnel f Kernel-mode address space Static data //Code at 0x80000080 mips_general_handler: j common_exception nop //Delay slot common_exception: //1) Find the kernel stack. //2) Push context of //interrupted execution //on the stack.

//3) Jump to mips_trap() /* kern/arch/mips/locore/exception-mips1.S * In the context of this file, an exception is a trap, * where a trap can be an asynchronous interrupt, or a * synchronous system call, NULL pointer derefer, etc.*/ common_exception: mfc0 k0, c0_status /* Get status register */ andi k0, k0, CST_KUp /* Check we-were-in-user-mode /* kern/arch/mips/include/trapframe.h */ /* * Structure describing what is saved on the stack during 2:* entry to the exception handler. *//* struct { * Attrapframe this point: uint32_t tf_vaddr; are /* off. coprocessor 0 vaddr did register * Interrupts

(The processor this */ * for us.) uint32_t /* coprocessor 0 status to go * k0tf_status; contains the value for curthread, register */into s7. * uint32_t /* coprocessor 0 cause register * k1tf_cause; contains the old stack pointer. */ * sp points into the kernel stack. uint32_t tf_lo; * All other registers are untouched. uint32_t tf_hi; */ uint32_t tf_ra;

/* Saved register 31 */ User stack User-mode address space foo() Standa registers rd bar() close_stdout() PC Heap EPC Static data // User close_stdout() code li a0, 1 li v0, 49 syscall SP

EEXX__ Cause SYS Statu In Psr tr iv p ts : K : e Of rnel f Kernel-mode address space Trapframe mips_trap(tf) Heap Static data kern/arch/ mips/ locore/trap.c: : mips_trap(stru kern/arch/mips/ locore/trap.c:: mips_trap(struct trapframe *tf)

mips_trap() extracts the reason for the trap . . . uint32_t code = (tf->tf_cause & CCA_CODE) >> CCA_CODESHIFT; . if . . and then==calls the appropriate kernel function to handle the (code EX_IRQ) { //Error-checking code is elided trap mainbus_interrupt(tf); goto done2; } if (code == EX_SYS) { syscall(tf); goto done; } //. . . etc . . . /* kern/arch/mips/syscall/syscall.c */ void syscall(struct trapframe *tf){ /* Error-checking elided */ int callno, err; int32_t retval; callno = tf->tf_v0; switch (callno) { case SYS_reboot:

err = sys_reboot(tf->tf_a0); /* The argument is * RB_REBOOT, * RB_HALT, LOST IN A MINE ONLY ONE COIN MICKENS YOU HAVE RUINED ME User stack User-mode address space foo() Standa registers rd bar() close_stdout() PC Heap

EPC Static data // User close_stdout() code li a0, 1 li v0, 49 syscall SP EEXX__ Cause SYS Statu In Psri tr v pt : K s: er On nel Kernel-mode address space Trapframe mips_trap(tf) syscall(tf) Heap Static data

kern/arch/mips/ syscall/syscall.c: : syscall(struct trapframe *tf) Status register when user code runs On trap, processor left-shifts two bits with zero-fill rfe will right-shift two bits with one-fill 1 1 1 1 1 00 1 1 1 /* kern/arch/mips/locore/exception-mips1.S */ 1 1 1 1 1

1 1 1 If kernel later enables Privilege: User jal mips_trap /* call it */ interrupts, then nested Interrupts: Enabled 1 0 00 nop /* delay slot */ traps are possible User stack User-mode address space foo() Standa registers rd bar() close_stdout()

PC Heap Static data // User close_stdout() code li a0, 1 li v0, 49 syscall SP What if close_stdout() had wanted to check the return value of close()? In this example, close_stdout() directly invoked syscall, so close_stdout() must know about the MIPS syscall conventions: On successful return, zero in a3 register; return value in v0 (v0 and v1 for a 64-bit return value) On error return, nonzero in a3 register; errno value in v0 In real life, developers typically invoke system calls via libc; libc takes care of handling the syscall conventions and setting the libc errno variable correctly CONTEX SWITCHE T

S THEYRE GREAT I GET IT Context-switching a Thread Off The CPU In the previous example, a thread: was running in user-mode invoked a system call to trap into the kernel ran in kernel-mode using the threads kernel stack returned to user-mode without ever relinquishing the CPU However, kernel-mode execution might need to sleep . . . Ex: waiting for a lock to become available Ex: waiting for an IO operation to complete . . . so this means that we need to save the kernel-mode state, just like we saved the user-mode state during the trap! kern/include/thread.h struct thread { threadstate_t t_state; /* State this thread is in */ void *t_stack; /* Kernel-level stack: Used for * kernel function calls, and * also to store user-level * execution context in the * struct trapframe */ struct switchframe *t_context; /* Saved kernel-level * execution context

*/ Suppose that kernel-mode execution needs to go to sleep on a wchan . . . void wchan_sleep(struct wchan *wc, struct spinlock *lk){ /* may not sleep in an interrupt handler */ KASSERT(!curthread->t_in_interrupt); /* must hold the spinlock */ KASSERT(spinlock_do_i_hold(lk)); /* must not hold other spinlocks */ KASSERT(curcpu->c_spinlocks == 1); thread_switch(S_SLEEP, wc, lk); //Kernel-mode execution //is suspended . . The Magic of thread_switch() thread_switch() will add the current thread-to-sleep to the wc_threads list of the wchan Then, thread_switch() swaps in a new kernel-level execution . . . switch (in assembler in switch.S) */ /* do the switchframe_switch(&cur->t_context, &next>t_context); . . . where cur is the currently-executing thread-to-sleep, and next is t the new thread to start executing Unlike a user-to-kernel context transition due to an interrupt, this context switch is voluntary! An Aside: Calling Conventions A calling convention determines how a compiler implements function calls and returns

How are function parameters passed to the callee: registers and/or stack? How is the return address back to the caller passed to the callee: registers and/or stack? How are function return values stored: registers and/or stack? Calling conventions ensure that code written by different developers can interact! Weve already seen one example: MIPS syscall convention Calling Conventions Most ISAs do not mandate a particular calling convention, although the ISAs structure may influence calling conventions Ex: 32-bit x86 only has 8 general-purpose registers, so most calling conventions pass function arguments on the stack, and pass return values on the stack Ex: MIPS R3000 has 32 general-purpose registers, so passing arguments via registers is less painful MIPS t0 s0

a0 t1 s1 a1 t2 s2 a2 t3 s3 a3 t4 s4 t5 s5 v0 t6 s6 v1 t7 s7 s8 Function Temp values arguments Saved values (caller(calleesaved) Function saved) return

values Registers: Caller-saved vs. Calleesaved Caller-saved registers hold a functions temporary values The callee is free to stomp on those values during execution If the caller wants to guarantee that a caller-saved register isnt clobbered by the callee, then: Before the call: the caller must push the register value onto the stack After the call: the caller must pop the register value from the stack Callee-saved registers hold persistent values The callee must ensure that, when the callee returns, the registers have their pre-call value This means: At the beginning of the callee: if the callee wants to use those registers, the callee must first push the old register values onto the stack When the callee returns: any callee-saved registers must be popped from the stack into the relevant registers thread_switch() swaps in a new kernel-level execution . . . /* do the switch (in assembler in switch.S) */ switchframe_switch(&cur->t_context, &next. . . where cur is the currently-executing thread-to-sleep, and next is >t_context); the nnew thread to start executing The call to switchframe_switch() automatically pushes the necessary caller-saved registers onto the stack

So, switchframe_switch() uses hand-coded assembly to: push callee-saved registers onto the stack (including ra, which contains the address of the instruction in thread_switch() after the call to switchframe_switch()) update curs struct switchframe *t_context to point to the saved registers (so now, all of curs kernel-level execution context is on its kernel stack) change the kernel stack pointer to be nexts kernel stack pointer restore nexts callee-saved kernel-level execution context using nexts switchframe jump to the restored ra value; caller restores the caller-saved registers; next has now returned from switchframe_switch()! /* do the switch (in assembler in switch.S) */ switchframe_switch(&cur->t_context, &next->t_context); /* * When we get to here, we are either running in the next * thread, or have come back to the same thread again, * depending on how you look at it. That is, * switchframe_switch returns immediately in another thread * context, which in general will be executing here with a * different stack and different values in the local * variables. (Although new threads go to thread_startup * instead.) But, later on when the processor, or some

Recently Viewed Presentations

  • Flammable Liquids Storage & Handling Proper handling and

    Flammable Liquids Storage & Handling Proper handling and

    ppt-sm-fls&h 2016 Flammable liquids are liquids that have flashpoints at or below 199.4 °F (93 °C) Flashpoint is the minimum temperature at which the liquid gives off vapors in a high enough concentration that it forms an ignitable mixture with...
  • A New Bulk Microphysical Parameterization in MM5 &

    A New Bulk Microphysical Parameterization in MM5 &

    Greg Thompson, Paul Field, Roy Rasmussen, Bill Hall Microphysics species' characteristics Microphysical processes (details) Cloud water - details Rain - details Rain - details (cont) Terminal velocity Cloud ice (pristine) - details Ice/snow size spectra (UK-C130 aircraft) Moment relations contain...
  • Mr. Huddleston's 2nd Grade class

    Mr. Huddleston's 2nd Grade class

    We want to know how far the light from a candle's flame will travel. Hypothesis. We think the light from the flame stays on the candle. Materials needed. Candle. Match. Fire extinguisher (just in case) Procedure. Get candle. Let teacher...
  • Update on Forest Goals and Progress in the

    Update on Forest Goals and Progress in the

    Check out tree canopy tools at www.itreetools.org Forest Conservation Goal - 2007 By 2020, permanently protect an additional 695,000 acres of forest from conversion, targeting forests in areas of highest water quality value.
  • Mastery Connect Parent Guide Hortonville Middle School |

    Mastery Connect Parent Guide Hortonville Middle School |

    not been summatively assessed for this. standard yet, but you can get an idea of how he is doing currently. Parents can also open the learning target or essential standard by clicking on the down arrow to the right. In...
  • Persona Poems and Personification

    Persona Poems and Personification

    This poem is written in 1st person and the narrator is an object that cannot talk in real life- a chalkboard! The author of this poem pretended to be the chalkboard so that they could think about what a chalkboard...
  • Diapositiva 1 - ComexPerú

    Diapositiva 1 - ComexPerú

    Paintgs,drawgs&pastels executd by hand exc hd 4906&h-p&h-d mfd art '902119. Orthopaedic or fracture appliances, nes '920993. Parts and accessories for the musical instruments of heading No 92.03 '911280. Clock cases&cases of a similar type,for oth goods of this Chapter,nes '910899....
  • The Role of Hospital Transparency 1 The Problem

    The Role of Hospital Transparency 1 The Problem

    The Role of Hospital Transparency The Problem Four issues with transparency Data limitations -- relates to data sources and appropriate use of statistics Some tasks are harder to accomplish than others, some patients are sicker than others -- risk adjustment...