r/osdev • • 7d ago

Syscalls, do you pass the arguments on the stack or through the registers ?

Linux passes arguments to syscalls through registers. But because there can be no more than six arguments passed this way and each argument can’t be longer than a register, more often than not theses arguments are just pointers to a struct somewhere else in memory

On the other hand, old unixes passed arguments on the stack. That means you can pass your whole structs directly instead of through references

To me passing arguments through the stack seems more appealing, because it seems easier to update existing syscalls, that being on the stack means probably less cache misses when passing args around and it gives me a more straightforward way to implement "variadic" syscalls

On the other hand most OSs seem to pass arguments through registers, so I suppose there is a good reason for that. What’s your thoughts on this ? How did you implement your syscalls ?

58 Upvotes

29 comments sorted by

18

u/Max-P 7d ago

A syscall with a single argument being a pointer to a struct that lives on the stack is effectively the same thing, except that there's flexibility for the caller to also put it wherever they want in memory that's convenient and not just the stack. The kernel is also free to push and pop registers to the stack if it needs to because it would clobber your app's registers. If the struct was on the stack, and the output on the stack, that would be awkward to pop those registers back.

Lets say you have an IO thread doing all the syscalls, that thread would have to copy the struct to the stack, syscall, only for the kernel to pop it from the stack again into registers. With the registers, you can just have an array of pointers mailbox thing, and loop over your array of pointers, load it into register and syscall your premade syscall structs. And you'd probably still need pointers, because you probably don't want your read syscall to write the data on the stack, because then you'd have to copy it back where you wanted it. Now you have a pointer (stack pointer register) to another pointer (the location in the struct that points there you want the data written to). The struct would also be awkward with 4k page alignment, reading 4k blocks from a disk onto the stack.

If you want to do variadic syscalls with registers, you can just make an array of values and syscall with the address of the first element, and either pass in a length or null terminate it as second argument.

It's just more steps to achieve the same thing.

2

u/Taletad 7d ago

I hadn’t thought about it this way

1

u/Thanksgivingwishbone 6d ago

I did the same thing but with structs in a past OS, but I moved to registers now since most ops need almost no more than four or so arguments.

17

u/Relative_Bird484 7d ago

Registers have the extremely nice property that they survive protection domain switches. For most syscalls, the kernel (or receiving server in a microkernel) this is a lot more efficient than transferring memory between address spaces.

The key point is: On multicore or a fully preemptive kernel, you always have to copy stack-based parameters into save kernel/receiver memory, because all user-space memory remains mutable even after kernel entry: Another thread running on another core might change the pointer that was passed to the syscall via the stack after the kernel did its validity checks. Whoops, kernel dereferences a user-controlled pointer. Not good.

Passing parameters in CPU-local memory (registers) prevents a lot of issues by design.

4

u/wrosecrans 6d ago

you always have to copy stack-based parameters into save kernel/receiver memory, because all user-space memory remains mutable even after kernel entry:

One concept I've doodled on the back of a napkin but never chased down the details of implementing, would be that you can allocate special pages where syscall data is allowed to be, and doing a syscall transfers ownership of the page to the kernel, so now the kernel owns it with zero-copy. The user process can't modify it (or see it) once the syscall starts.

The kernel could return the page to a process when finished and map the result back into the process address space. You could use that sort of mechanism for IPC as well, with one of the syscalls being to send the page to a destination process rather than to get it back.

2

u/Relative_Bird484 6d ago

That is what modern microkernels basically do in one way or the other. The biggest caveat is multicore scalability: To actually restrict user access upon kernel entry, you need to do a TLB shootdown. Doesn’t scale for small data sets, on most architectures even copying a full 4kiB page would be cheaper, not to speak of 200 bytes.

A better solution is per-core pages, so the TLB shootdown isn’t necessary. This, however, has quite an impact on address space layout/management as well as on CPU preemption/scheduling, as it now matters a lot which core does what. The latter could be simplified by separating in- and out-pages: In-pages are per-core while out-pages are per-process, mapped read-only, and never be removed from its address space (so no shootdowns).

However, if your syscall parameters fit into registers, this is still the way to go. The actual goal is to come up with a kernel design that does (almost) not require structs to be passed across protection boundaries.

2

u/wrosecrans 6d ago

you always have to copy stack-based parameters into save kernel/receiver memory, because all user-space memory remains mutable even after kernel entry:

One concept I've doodled on the back of a napkin but never chased down the details of implementing, would be that you can allocate special pages where syscall data is allowed to be, and doing a syscall transfers ownership of the page to the kernel, so now the kernel owns it with zero-copy. The user process can't modify it (or see it) once the syscall starts.

The kernel could return the page to a process when finished and map the result back into the process address space. You could use that sort of mechanism for IPC as well, with one of the syscalls being to send the page to a destination process rather than to get it back.

6

u/[deleted] 7d ago

You can just follow the sys v abi and pass the first 6 args in registers then the rest on the stack. Registers are a lot faster to access so if you can use them then of course it's ideal.

4

u/Poddster 7d ago

Each syscall can be unique if you want . You don't need to use the same calling convention for every syscall. As long as it's documented and both caller and consumer agree on what the convention for syscall N is then it doesn't matter.

You might find you fallback to registers though because they're faster and easier.

4

u/duane11583 7d ago

i have seen another method.

every thread gets a page of ram for kernel io

you copy data to that page. ie the file name to open

make the syscall

the page is already known on the kernel side

there is no copy/from/to/user/space cause it is in that kernel buffer

2

u/CubicleHermit 6d ago

This (or something similar with a per-thread/per-processor ringbuffer) is basically a software mailbox. It's harder to make it secure without hardware to control ownership (because userspace can overwrite things while the kernel is working on it), but it's popular in some kinds of embedded and microkernel systems (I think L4 uses these, or used to.)

Hardware mailboxes, or cheap enough page permissions remapping, can fix the security issue there.

1

u/duane11583 6d ago

yea i did not mention the mmu page -ermissions

7

u/Kooky_Philosopher223 7d ago

I implemented by a special packet consisting of x ammount of arguments for the call plus a status then put the call id into rcx and the pointer to the packet in rdx (my system is in msvabi) and make the call

1

u/lunar_swing 6d ago

Registers will always be faster. You won't ever have a cache miss if you are passing an immediate.

Cache misses for passing on the stack depends on where your stack is I suppose.

1

u/Taletad 6d ago

But not every system calls get immediate values

Write for example needs a string, so why pass the pointer to the string in the register when you can put the string on the stack ? (Some other comments actually answer that question)

1

u/lunar_swing 6d ago

Yes you are correct. However lets say even 50% of your syscall parameters are immediates. Register reads are 0~1 cycles. A cache hit is ~10 cycles. A read from memory is 100~200+ cycles at a minimum.

Using very rough estimates admittedly, but that's at least two orders of magnitude faster access on 50% of your reads for program control flow.

1

u/Taletad 6d ago

On old Unix, maybe 25% of syscalls at most could be passed entirely without pointers to a datastructure

On Linux, all the syscalls get used and about 200 of them (most likely using pointers) get used extremely frequently (I can fetch you the paper if you want)

So for maybe 25% of them, they would be faster using registers, but thoses that pass pointers won’t change a thing

And thoses that pass multiple pointers (like link or copy) or manage big datastructures (write for example) would benefit from having all the data stored in contiguous memory (like, say, the stack)

Read the other comments, some of them made great points, but I don’t think passing args via registers is that much faster when you pass pointers most of the time anyway

1

u/lunar_swing 6d ago

I mean you can get into the fundamentals of fetch timing and really break it down if you want. Stack space is limited in practice, and we get into benchmarking and architecture implementation specifics.

Dereferencing the pointer will of course take the fetch hit. Pointers usually point to the heap however, which is not spatially close to the stack in most implementations.

Syscalls are usually pretty expensive to begin with. You could of course write code that exploits either passing convention to a large degree. But the fundamental point still holds, register access will always be faster.

3

u/Molyuuing 7d ago

I set up a message control block for each thread. IPC and system calls are all done through the message register and the message control block. Parameters and message tags are compactly compressed in the message register. If the register cannot hold them, they are placed in the message control block.

2

u/gwenbeth 7d ago

Of course that assumes that your CPU even has general purpose registers. You might have a stack based machine where all instruction operands are on the stack.

2

u/Proxy_PlayerHD 6d ago

Mine uses registers cause all system calls have a small and fixed amount of arguments so I know it fits easily. If there were too many arguments I would put them in a struct on the stack and then pass a pointer to it via a register.

2

u/Routine_Working_9754 7d ago

I would use registers. stack can get corrupted. and then if I need more arguments than available registers I'd make one of the arguments a pointer to a bunch of data in memory.

1

u/Glum-Cook-9438 7d ago

Both, in the amd system v abi, arguments 1 to 6 are passed in the following registers: Rdi - arg 1 Rsi - arg 2 Rdx - arg 3 Rcx - arg 4 R8 - arg 5 R9 - arg 6

Arg 7 and above are on the stack

1

u/TTachyon 7d ago

Registers is the obvious answer. No need to do memory reads and writes if a register can solve it.

The stack is expected in the C world, but you could have languages that don't have traditional stacks. I'm pretty sure in Go the runtime will have small stacks for each coroutine that's managed by it, and it's a pain for them to switch to a traditional stack when calling FFI that expects it. Having stuff live in registers where possible solves this completely.

it gives me a more straightforward way to implement "variadic" syscalls

You're right here, but it turns out that in real code variadic stuff is both unsafe and slow. Not saying you shouldn't do it for fun, but there's good reasons why it isn't done like this.

1

u/dobesv 6d ago

The stack is a register that points to some memory block so it doesn't really matter that much.

1

u/CubicleHermit 6d ago

It depends on the design of the OS and the underlying ABI/processor architecture, but assuming a Linux/Unix-like monolithic kernel on an architecture with page-based address space isolation and relatively conventional processor architecture ...

First, registers are fast, memory is slow. This isn't an issue when calls are being made in the same process, as on modern systems those stack writes are hot data in the L1 cache. This is rarely going to propagate across a privilege boundary.

Second, the kernel stack is not the userspace stack. Regular data registers typically get propagated easily via system call mechanism - either they're saved someplace known, or they just keep their values right over.

Your view of memory doesn't copy right over - the kernel has view of memory and its own stack. At a minimum is now indirecting everything via the userspace stack pointer. Depending on the OS, you may not have the whole user process automatically mapped into the kernel address space in the first place, and even if you do, accessing it likely requires some effort to convert the process's own view of its address space into the kernel's.

As a result, for small things, it's unnecessary. For big things, you're going to want to pass through a buffer/data structure address to begin with. There is a small space where you've run out of registers but a buffer/structure address is excessive, but on modern processors with a lot of registers, this will be quite rare.

As more and more security vulnerabilities like Spectre/Meltdown/etc have come up, and you add the complexities of things like CET and SSP on modern processors that get done for security, and this all becomes a big pain.

1

u/ventZl CMRX microkernel 3d ago

Registers are simply much faster. Passing data via stack was a very exclusive feature of anything x86-based, because 32-bit x86 was always short on general purpose registers. So stack was used to pass arguments both to functions and often even to syscalls. MS-DOS is an exception, but that's hardly an operating system.

Another aspect is that you don't really want to "update" your system call if you care about backwards compatibility. If you do so, all your older binaries become obsolete. I'd rather create new system call with updated APi rather than edit old system call.

So in the end, I am using registers for system call arguments, even if you can only use four of them on ARM. So far it works OK and I had no system call which would be short on registers.

Disclaimer: My kernel is a microkernel, so it doesn't really have that many system calls.

1

u/mishakov pmOS | https://gitlab.com/mishakov/pmos 3d ago

I pass mine on registers on all arches that I support at the moment (amd64, aarch64, rv64, la64, and incomplete m68k port) except ia32, where I pass up to 4 arguments with registers and the rest overflow on stack, since 32-bit x86 only gives you 5 32-bit usable registers for syscall arguments. I think that all other arches that I plan on targeting also have enough registers.

Passing through registers is faster and more convenient for the kernel since accessing any sort of user memory (including stack) requires validating it and catching pagefaults, and I think that you do usually have enough register for this on arches, and ia32 famously has very few registers.

-1

u/Key_River7180 EulerOS 7d ago

Stack, less destructive