System Calls

  • An API to the OS
  • A way to call facilities/services in the kernel
  • Similar to a normal function call, but not the same: needs to change from user to kernel mode

Unix syscalls

  • In c/c++, syscalls can be invoked almost directly
    • There is a library version of all syscalls (with the same name & parameters), acting as a function wrapper
    • There are also simplified, user friendly library versions, with less parameters?
      • e.g. printf() calls the write() syscall
    • strace <program> runs the program, and displays all syscalls made

Syscall Mechanism

  1. User program invokes the library fn (using normal function call mechanism)
  2. Library fn (usually in assembly) places syscall number in designated location e.g. a register
    1. Syscall number: number that identifies syscall, depends on system e.g. 39→getpid
  3. Library fn executes a special instruction to switch frm user mode to kernel mode, commonly TRAP. This saves the current context (cpu state)
  4. Now in kernel mode, the syscall handler is determined by a dispatcher (switch statement based on syscall number)
  5. Syscall handler is executed
  6. Restore context (CPU state), return to library fn, switch frm kernel to user mode
  7. Library fn returns to user program (using normal function mechanism)

Non-intentional Interaction

Exception

  • Executing a machine level instruction can cause exception, e.g. arithmetic error: divide by zero, memory error: illegal memory address
  • Synchronous: Occurs due to program execution
  • Exception handler: Executed automatically in the kernel when exception happens. (TRAP into kernel, run exception handler)
    • A “forced function call”

Interrupt

  • External events can cause interrupts, usually hardware related e.g. timer, mouse movement, keyboard press
  • Asynchronous: Not due to program execution
  • Interrupt handler: Execution is suspended, and an interrupt handler is automatically executed

Mechanism

  1. Exception/interrupt occurs
  2. CPU transitions to kernel mode, transfers control to a handler automatically
  3. Save context
  4. Perform handler routine (may impact the program e.g. ctrl + c keyboard interrup)
  5. Restore context, return from interrupt