Reputation:
I find that neither my textbooks or my googling skills give me a proper answer to this question. I know it depends on the operating system, but on a general note: what happens and why?
My textbook says that a system call causes the OS to go into kernel mode, given that it's not already there. This is needed because the kernel mode is what has control over I/O-devices and other things outside of a specific process' adress space. But if I understand it correctly, a switch to kernel mode does not necessarily mean a process context switch (where you save the current state of the process elsewhere than the CPU so that some other process can run).
Why is this? I was kinda thinking that some "admin"-process was switched in and took care of the system call from the process and sent the result to the process' address space, but I guess I'm wrong. I can't seem to grasp what ACTUALLY is happening in a switch to and from kernel mode and how this affects a process' ability to operate on I/O-devices.
Thanks alot :)
EDIT: bonus question: does a library call necessarily end up in a system call? If no, do you have any examples of library calls that do not end up in system calls? If yes, why do we have library calls?
Upvotes: 5
Views: 1432
Reputation: 1866
Historically system calls have been issued with interrupts. Linux used the 0x80
vector and Windows used the 0x2F
vector to access system calls and stored the function's index in the eax
register. More recently, we started using the SYSENTER
and SYSEXIT
instructions. User applications run in Ring3
or userspace/usermode. The CPU is very tricky here and switching from kernel mode to user mode requires special care. It actually involves fooling the CPU to think it was from usermode when issuing a special instruction called iret
. The only way to get back from usermode to kernelmode is via an interrupt or the already mentioned SYSENTER/EXIT
instruction pairs. They both use a special structure called the TaskStateSegment
or TSS
for short. These allows to the CPU to find where the kernel's stack is, so yes, it essentially requires a task switch.
But what really happens?
When you issue an system call, the CPU looks for the TSS
, gets its esp0
value, which is the kernel's stack pointer and places it into esp
. The CPU then looks up the interrupt vector's index in another special structure the InterruptDescriptorTable
or IDT
for short, and finds an address. This address is where the function that handles the system call is. The CPU pushes the flags register, the code segment, the user's stack and the instruction pointer for the next instruction that is after the int
instruction. After the systemcall has been serviced, the kernel issues an iret
. Then the CPU returns back to usermode and your application continues as normal.
Do all library calls end in system calls?
Well most of them do, but there are some which don't. For example take a look at memcpy
and the rest.
Upvotes: 6