Hi,
josecm wrote:
Hello, I don't know if this is the correct place for this question, so feel free to move it elsewhere.
My question is related to the cost of system calls. I've always heard this is an expensive operation, but I don't really understand why. Shouldn't the cost be similar or cheaper than a common exception?
A new car is cheap (compared to the cost of a new house) and a new car is expensive (compared to the cost of a sandwich). System calls are typically compared to the cost of a normal function call, and are a lot more expensive than a normal function call. The cost of an interrupt (including CPU's exceptions, IRQs, IPIs, etc) is typically a little higher than the cost of a system call.
The additional cost (for system calls and interrupts/exceptions/IRQs) can be split into 4 categories:
- The effect on the CPU's pipeline when it happens (e.g. CPU has to either discard "already in progress" instructions or wait until they retire)
- The cost of changing privilege levels (e.g. from CPL=3 to CPL=0 and back to CPL=0, including changing stacks, changing segment registers, etc)
- Bloat because your compiler isn't great (e.g. expects a specific ABI and therefore can't avoid saving/restoring various registers, etc).
- Bloat because you were lazy (e.g. an additional jump table and mispredicted branch that could've been avoided, but exists because you just did a "common exception handler" for your own convenience).
Note that avoidable bloat is typically at least as large as the actual (minimal) cost, and something like SYSCALL (that can be done in "several tens of cycles") can easily become "several hundred cycles" because of this.
Cheers,
Brendan