Lecture 2 about 35 min 20 quiz questions

System Calls and Interrupts

How a user program asks the kernel for help through system calls, the five categories of calls with their Windows and Unix names, and how hardware and software interrupts pull the CPU into the OS.

What you will be able to do

  • Define a system call and explain why programs use an API instead of invoking calls directly.
  • Trace the system call sequence from a library function through the system call table into the kernel and back.
  • Classify any system call into one of the five categories and name its Windows and Unix equivalents.
  • Distinguish hardware interrupts, traps and exceptions (faults vs aborts).
  • Compare maskable and non-maskable interrupts and explain how the interrupt vector table dispatches a handler.
  • Describe the sequence the CPU follows when an interrupt arrives while a user program is running.
1

What a system call is

Your program cannot touch the disk. It has to ask.

In Lecture 1 you saw that user programs run in user mode and cannot execute privileged instructions. So how does your C program ever read a file, print to the screen, or create a process? It asks the kernel. A system call is the mechanism that provides the interface between a process and the operating system. It is the only legal door from user mode into kernel mode.

  • System calls are typically written in a high-level language (C or C++), with a tiny bit of assembly at the boundary where the mode switch happens.
  • Programs mostly do not invoke system calls directly. They go through a high-level Application Programming Interface (API) whose functions wrap the calls.
  • The three most common APIs: Win32 API for Windows, POSIX API for POSIX-based systems (virtually all versions of UNIX, Linux and Mac OS X), and the Java API for the Java virtual machine.

Why the extra layer? Two reasons. Portability: a program written against POSIX compiles on Linux and macOS even though their raw system calls differ. Convenience: the API hides the messy details (which register holds the call number, how errors come back). The slides put it this way: the caller need know nothing about how the system call is implemented. It just obeys the API and understands what the OS will do as a result. Most details are hidden by the run-time support library, the set of functions built into the libraries that ship with the compiler.

Standard C library example: printf() ends in a write() system callc
1#include <stdio.h>
2int main() {
3 printf("Greetings"); /* user mode: libc formats the string */
4 return 0; /* libc calls write(), traps into the kernel, and returns */
5}

Output

Greetings
1 of 8
2

How a system call works

A number, a table, a mode switch, and a return.

Under the hood every system call is just a number. The system call interface maintains a system call table indexed by those numbers. Each entry holds the address of the kernel routine that implements that call. On Linux x86-64, for example, read is 0, write is 1, open is 2. Your program never sees these numbers; the library does.

user modekernel modeuser programprintf("hi")C library (API)write(1, buf, n)trap with call number 1system call interface0 read1 write2 open3 close... the number indexes the tablekernelsys_write()return value or error status
User program calls a library function; the library places the call number and traps; the kernel indexes the system call table, runs the handler, and returns status and values.

The life of one system call (matches the slide's numbered architecture diagram)

  1. 1

    User program calls an API function

    Say open() from the C library. This is still ordinary user-mode code.

  2. 2

    Library puts the system call number in place

    The wrapper loads the call number (and arguments) into agreed registers or onto the stack.

  3. 3

    Trap into the kernel

    A special instruction raises a software interrupt. Hardware sets mode bit to 0 and jumps to the system call interface.

  4. 4

    Index the system call table

    The interface uses the number as an index, finds the address of the implementation, and calls it.

  5. 5

    Kernel does the privileged work

    The open implementation checks permissions, finds the file, allocates a descriptor.

  6. 6

    Return status and values

    The interface returns the status of the call and any return values. Mode bit goes back to 1, and execution resumes in the library, which hands the result to your program.

2 of 8
3

A real program is a stream of system calls

Copying one file to another needs about nine calls, and none of them are the copy.

The slides walk through copying the contents of one file into another. It looks like a one-line task, but even this trivial program is nothing but system calls stitched together. The lesson: every I/O operation, every error message, even normal termination is a system call.

System call sequence to copy a file

  1. 1

    Acquire input file name

    Write a prompt to the screen and read the name from the keyboard. Two calls already.

  2. 2

    Acquire output file name

    Same again.

  3. 3

    Open the input file

    open(). If the file does not exist, the call fails and the program must print an error (another call) and abort (another call).

  4. 4

    Create the output file

    open() with a create flag, or creat(). If it already exists the program may ask whether to overwrite.

  5. 5

    Loop: read from input, write to output

    read() into a buffer, then write() the buffer out. Repeat.

  6. 6

    Until read fails

    read() returns zero at end of file (or an error). That ends the loop.

  7. 7

    Close the output file

    close() flushes and releases the descriptor.

  8. 8

    Write completion message on the screen

    write() to standard output.

  9. 9

    Terminate normally

    exit(). Even ending the program is a system call.

3 of 8
4

The five categories of system calls

Process, file, device, information, communication. Learn the buckets and the sorting becomes automatic.

The slides group system calls into five types. In the exam you will be given a call and asked which category it belongs to, or given a category and asked for an example. Here is the complete list from the slides.

1. Process control

  • create process, terminate process
  • end, abort
  • load, execute
  • get process attributes, set process attributes
  • wait for time
  • wait event, signal event
  • allocate and free memory

2. File management

  • create file, delete file
  • open, close file
  • read, write, reposition
  • get and set file attributes

3. Device management

  • request device, release device
  • read, write, reposition
  • get device attributes, set device attributes
  • logically attach or detach devices

4. Information maintenance

  • get time or date, set time or date
  • get system data, set system data
  • get and set process, file, or device attributes

5. Communications

  • create, delete communication connection
  • send, receive messages
  • transfer status information
  • attach or detach remote devices
4 of 8
5

Windows vs Unix: the same jobs, different names

This table is on the slides and it is on the paper.

The two big API families give the same operations different names. You should be able to go in either direction: given CreateProcess(), say fork(); given chmod(), say SetFileSecurity(). Note that the slides add a sixth row, Protection, to the five categories above.

Examples of Windows and Unix system calls (slide table, complete)

CategoryWindowsUnix
Process controlCreateProcess()fork()
ExitProcess()exit()
WaitForSingleObject()wait()
File manipulationCreateFile()open()
ReadFile()read()
WriteFile()write()
CloseHandle()close()
Device manipulationSetConsoleMode()ioctl()
ReadConsole()read()
WriteConsole()write()
Information maintenanceGetCurrentProcessID()getpid()
SetTimer()alarm()
Sleep()sleep()
CommunicationCreatePipe()pipe()
CreateFileMapping()shmget()
MapViewOfFile()mmap()
ProtectionSetFileSecurity()chmod()
InitializeSecurityDescriptor()umask()
SetSecurityDescriptorGroup()chown()
5 of 8
6

The OS is event driven: interrupts, traps and exceptions

The kernel executes only when something happens.

Here is a fact that surprises people: the OS executes only when there is an interrupt. It is not a background program that is always running. User processes run at privilege level 1 (user mode). An event kicks the CPU up to privilege level 0 (kernel mode), the OS handles it, and control returns to some user process. The slides classify events into three kinds.

Three kinds of events

EventRaised byTimingExamples
Hardware interrupt (or just "interrupt")Hardware devicesAsynchronous: may occur at any time, unrelated to the current instructionKeyboard interrupt, mouse movement, timer interrupt, disk I/O completion
Trap (software interrupt)Intentionally raised by user programs to invoke OS functionalitySynchronous: happens exactly when the program executes the instructionSystem call instruction, breakpoint for debugging
ExceptionAn error or unexpected event during executionSynchronous: caused by the instruction being executedFaults: recoverable (page fault). Aborts: hard to recover (divide by zero)

Faults vs aborts (both are exceptions)

Fault

  • Recoverable. The OS fixes the cause and re-runs the instruction.
  • Example: page fault. The page is loaded from disk and the program never notices.

Abort

  • Difficult to recover. Usually the process is killed.
  • Example: divide by zero. There is no sensible way to continue.

What is an interrupt, precisely? The word means to break the sequence of operations. It is a signal from a device or from a program that requires the OS to figure out what to do next. While the processor is executing one program, an interrupt breaks that sequence and starts execution of another program (the handler).

Why do we need interrupts at all? Devices and programs occasionally need CPU service, but we cannot predict when. Without interrupts the CPU would have to keep asking every device "are you done yet?" (polling), wasting most of its time. Instead, each device or program is allowed to raise an interrupt as a signal to the processor. Interrupts are the way for the CPU to find out that something needs attention.

6 of 8
7

Types of interrupts: hardware, software, maskable, non-maskable

Some interrupts you can tell to wait. Some you cannot.

The slide tree splits interrupts into hardware and software, and hardware interrupts further into maskable and non-maskable. A hardware interrupt is a signal from an external device: a keystroke or a mouse movement travels from the keyboard through the interrupt line (INT) to the CPU, which runs the keyboard interrupt handler routine.

Maskable vs non-maskable interrupts (slide table)

Maskable interruptNon-maskable interrupt
Hardware interrupts that may be ignored by setting a bit in an interrupt mask register (IMR)Hardware interrupt that lacks an associated bit mask, so it can never be ignored
Can be disabled or ignored by the CPUCannot be disabled or ignored by the CPU
Used for lower priority tasksUsed for higher priority tasks like timers
When it occurs, it can be handled after the execution of the current instructionWhen it occurs, the current instruction and status are stored on the stack for the CPU to handle the interrupt
RST 6.5, RST 7.5, RST 5.5 of the 8085 microprocessorTRAP of the 8085 microprocessor

Software interrupts come in two flavours

Normal (planned) software interrupt

  • Caused by software instructions on purpose.
  • The system call instruction is the everyday example.
  • The program knows exactly when it will happen.

Exception (unplanned)

  • An unplanned interrupt while executing a program.
  • Example from the slides: a value that must be divided by zero.
  • The program did not intend it; the hardware detected an error.
7 of 8
8

How interrupts are handled

A controller, a number, a table, a handler.

Many devices, one CPU. An interrupt controller sits between them, collects requests from the timer, USB, keyboard and so on, and raises a single INT line to the CPU along with the interrupt number of the winner. When several interrupts arrive at once, the priority levels assigned in the interrupt controller decide which one is handled first. Not arrival time, not the user, not the size of the data.

devicekeyboardinterrupt controllerPIC / APICCPUirqintcontroller raises INT with vector number 33interrupt vector table0divide by zero1debug...32timer handler33keyboard handlern...vector 33 indexes the table, CPU jumps to the handlerstate is saved first, then the handler runs, then execution resumes
The interrupt number indexes the interrupt vector table; the entry holds the address of the handler, which the CPU jumps to.

The interrupt vector table (IVT)

  • The IVT maps interrupts to the service routines that handle them.
  • It has one entry for each interrupt. Each entry contains the address of the handler.
  • The interrupt number is used to index into the table.
  • The address in that entry is dereferenced to execute the corresponding handler, for example handleTimerInterrupt(), handleDivideByZeroInterrupt(), handleKeyboardInterrupt().

What happens when an interrupt arrives while a user program is running

  1. 1

    Finish (or pause) the current instruction

    The CPU does not stop mid-instruction. It completes the instruction in flight, then checks the interrupt line.

  2. 2

    Save context

    The program counter, status register and other registers of the interrupted process are saved (on the stack or in the process control block). Without this the program could never resume.

  3. 3

    Switch to kernel mode

    Mode bit becomes 0 so the handler can run privileged instructions.

  4. 4

    Look up the handler

    Use the interrupt number to index the IVT and fetch the handler address.

  5. 5

    Jump to the interrupt handler

    Run the service routine: read the key from the keyboard buffer, acknowledge the disk, tick the scheduler clock.

  6. 6

    Restore context and return

    Registers and program counter are restored, mode bit becomes 1, and the interrupted program continues as if nothing happened.

Open the OS terminalType man fork, man interrupt and quiz 2 in the interactive terminal to see the system call and interrupt paths described step by step, then drill this lecture's questions.
8 of 8

Before the exam

The lines worth memorising, and the mistakes that lose marks.

Remember this

  1. 1System call = interface between a process and the OS. Written mostly in C/C++. Accessed through an API, not directly.
  2. 2Three common APIs: Win32, POSIX (UNIX, Linux, Mac OS X), Java API (JVM).
  3. 3Each system call has a number; the system call table maps numbers to handler addresses.
  4. 4The caller need know nothing about implementation; the run-time support library hides the details.
  5. 5Five categories: process control, file management, device management, information maintenance, communications (slides add protection in the table).
  6. 6fork() = CreateProcess(); wait() = WaitForSingleObject(); open() = CreateFile(); ioctl() = SetConsoleMode(); getpid() = GetCurrentProcessID(); pipe() = CreatePipe(); mmap() = MapViewOfFile(); chmod() = SetFileSecurity().
  7. 7The OS is event driven: it executes only when there is an interrupt.
  8. 8Hardware interrupts are asynchronous (keyboard, mouse, timer, disk). Traps are intentional (system call, breakpoint). Exceptions are errors: faults recoverable (page fault), aborts not (divide by zero).
  9. 9Maskable: can be ignored via the IMR, lower priority, 8085 RST 5.5/6.5/7.5. Non-maskable: cannot be ignored, higher priority, 8085 TRAP.
  10. 10Interrupt vector table: one entry per interrupt, holds the handler address, indexed by interrupt number.
  11. 11Interrupt sequence: pause current instruction, save context, switch to kernel, index IVT, run handler, restore, return.
  12. 12Simultaneous interrupts are ordered by priority levels in the interrupt controller.

Exam traps

  • A system call is not a hardware mechanism, because it is a software interface into the OS; the trap instruction uses hardware, but the call itself is an OS service request.
  • The system call table does not store return values, because it stores the numbers and handler addresses used to dispatch the call.
  • Allocating memory is not a separate system call category on these slides, because it is listed under process control.
  • A trap is not an error, because it is raised intentionally by the program (a system call or breakpoint); an exception is the unintended error.
  • A page fault is not an abort, because it is a recoverable fault: the OS loads the page and re-runs the instruction.
  • A non-maskable interrupt is not a low-priority interrupt, because it cannot be ignored and is reserved for the highest-priority events.
  • The interrupt controller does not store handler addresses, because that is the job of the interrupt vector table; the controller prioritises and forwards the interrupt number.
  • Handling an interrupt does not mean completing the whole running program first, because the CPU pauses after the current instruction, saves context and jumps to the handler.

Quiz yourself

One question at a time with instant feedback. Your best score is saved.

Timed version →
Q 1 / 20 · System callseasyscore 0

What is a system call?

Not quite

A system call is the mechanism that provides the interface between a process and the operating system. It is how user-mode code requests kernel services.

Finished reading?

Mark this lecture as done

Take the quiz above first so your score is saved here.