Q:

When starting a system call, how are user-mode ss and esp saved, e.g. in linux?

I know user-mode ss/esp should be saved into the kernel-mode stack for later restore.
The question is that to locate kernel-mode stack, ss/esp have to be loaded with the corresponding kernel-mode values first. Now it seems to me that user-mode ss/esp have been flushed. Then how does the hardware/system retrieve the user-mode ss/esp?
Are user-mode ss and esp saved in some temporary places? Or the operation is supported by x86 circuit?

A:

Think about what happens with the instruction pointer. Clearly there must be some hardware support in there somewhere.
Putting aside modern "fast system call" techniques (I'll return to this later), note that a system call is requested by just issuing a specific software interrupt with certain processor registers set up appropriately. So what happens then is down to the interrupt hardware in the processor.
When an interrupt occurs, the processor automatically pushes various registers and other information (things like the instruction pointer, and other stuff that could be modified even before the handler gets a chance to save them) onto the kernel stack. Additionally, if the processor is currently not in kernel mode, it pushes the stack pointer and stack segment register onto the kernel stack and transitions to kernel mode, executing the interrupt handler.
Now if we look at "fast system calls" (the SYSENTER instruction), we note that it requires some machine state registers to be already set up, and it doesn't save state (this is part of what makes it faster than issuing an interrupt). The calling code is responsible for placing in the unclobbered registers the data that the kernel needs in order to execute the system call, and the data it needs to return to its original state.

