104 points · by tosh · 6y ago · 44 comments
Disclaimer: I had a hard time following this article. I'm also (ostensibly anyway) not the target audience. I was at one point the primary person responsible for the memory management in the JIT compiler[1] used by OpenJ9, though I haven't done that for a couple of years now.
[1] That is, the memory used by the JIT compiler itself, not its interactions with the garbage collector.
I really dislike his coding style! It’s written to be “short” in favor of clear. I see what the code does, but not necessarily his intent.
void*page_alloc(unsigned long long bytes) {
void *x;
for(;;) {
x = mmap(0, bytes, PROT_READ|PROT_WRITE, MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
if(x != MAP_FAILED) return x;
out_of_memory();
}
}For embedded I stoped using “unsigned long long” in favor of uint64_t. He spends all those extra characters but can’t put a space in the void pointer function definition?
[1] - https://www.ioccc.org/
If you use size_t all the time, you may forget or have someone else forget that another system isn’t the same.
If you always use uint8_t or int64_t etc there is no ambiguity. If I intended this to be an 32bit var, it will be regardless if who is compiling it.
Technical article for a technical audience, namely POSIX C programmers. There's no secret handshake or subtext to elevate the author.
Which "magic number" do you think was left unexplained? I thought I had got them all.
The article even says this but not strongly enough:
> It is worth mentioning that the C library malloc might be using and caching the results of sbrk it may be unwise to mix this trick with your C library malloc, but it is very useful in new programs that you have no intention of using the C library malloc with.
No it is not a good idea to write "new programs" to apply hacky uses of sbrk(2) and conflict with malloc. Any use of sbrk(2) outside of a malloc implementation is pretty suspect as code smell. And you will be hard pressed to find any program or library that doesn't use malloc, short of embedded use cases.
[1] https://opensource.apple.com/source/Libc/Libc-1272.250.1/emu...
More generally, I was very confused by the entire stack section. Why sbrk instead of mmap? Why should C provide special functions for creating or using a stack? Isn't a stack just a region of memory and a pointer into it? Isn't their high performance entirely due to data access patterns that facilitate cache locality while minimizing instruction count and pointer dereferences?
I may well have some misconceptions, but if so this article did nothing to address them.
Edit: Aha! From the mmap man page:
> MAP_STACK (since Linux 2.6.27)
> Allocate the mapping at an address suitable for a process or thread stack.
> This flag is currently a no-op on Linux. However, by employing this flag, applications can ensure that they transparently obtain support if the flag is implemented in the future. ... some architectures may (later) require special treatment for stack allocations. ...
> MAP_GROWSDOWN
> This flag is used for stacks. It indicates to the kernel virtual memory system that the mapping should extend downward in memory. The return address is one page lower than the memory area that is actually created in the process's virtual address space. Touching an address in the "guard" page below the mapping will cause the mapping to grow by a page. This growth can be repeated until the mapping grows to within a page of the high end of the next lower mapping, at which point touching the "guard" page will result in a SIGSEGV signal.
'Little-s' stacks require bulk-allocated pages that are then carved up into object allocations as required, and de-allocated in last-in-first-out ordering. No alloca or sbrk required.
I’m not sure what this is supposed to mean, but it’s good to note that malloc will switch between different paths based on the allocation size and what memory it has available to service the request.
By saying "I want a sizeof(Cons) object" versus "I want a buffer that's going to get big and used for a long time" versus "I want a buffer that'll get big but go away right after" means you get to avoid these unnecessary operations. That's important because they really add up when dealing with lots of data. That's how replacing a complicated and intelligent malloc() which has to rely on heuristics to decide which of the "different paths" to follow can lose big to a simpler strategy.
This seems like a widget that could be used to accomplish something interesting, but I'm not sure what that might be.
Sometimes I'd like to push an event onto a queue from an interrupt (e.g. a signal handler) and the buffer size can balloon some; sbrk() might be used because it's faster than malloc() and I know the consumer is fast enough (even though it's currently busy).
Sometimes I know the memory usage is very temporary, but I don't want to contort my program to use alloca() and so again: using brk can be convenient.
There are other things that are stack-like that we don't often think of as stacks.
One interesting place might be an undo-stack: An editor typically has an undo and redo-button and will never be freeing this state anyway, so rather than malloc/realloc my state (and have extra copies going on), and without trashing my heap with a long linked list, I might prefer the performance of sbrk(). You could possibly use alloca() as well, but this would make redo very difficult.
Another might be in a consensus algorithm: If implementing raft you wanted to queue messages until you had a chance for your election, your "stack" might take several seconds before you can start processing it. Keeping this on the "other" stack would make it difficult to do any other processing (where's the event loop?), and using malloc/realloc() will introduce copies. Reserving sbrk() for this stage might make everything much more straightforward.
You can implement a stack-like thing that avoids copying, and even gives stable addresses, by linking fixed-size chunks (say 128 elements) in a list. A stack "pointer" is then a pointer to a chunk + offset.
That said, editor/undo redo items are not performance critical. And you will be hard pressed to find a reason why you need to optimize memory consumption. Assuming a memory overhead of 16 bytes per allocation and assuming that a human would make < 1M edits.
Preferring an obscure API like sbrk() instead is not good general advice. It's not portable and it precludes the use of basically any library including libc.
You might want to minimize fragmentation and number of underutilized heap pages.
Even if your allocator minimizes fragmentation by allocating similar size objects from same area, allocating a large number of objects risks some other code (possibly running in a different thread) allocating long-living objects in the same time.
This can cause pages to exist just to hold a single small object, preventing optimal use of memory.
In some algorithms, 90-99%+ of runtime can be in allocation and freeing small objects!
On top of that, accessing a sequential stack (array) is significantly faster. CPUs are built for that type of access patterns.
The nicest outcomes are with coroutines, though, and that begins to be another matter.