Segmentation
You said our scheme was wasteful. How…?
Running Low on Space
In the diagram below, three users are busy editing with neovim. Perhaps another user might like to start a process to run emacs, but they can't because the machine is almost out of memory.
The code for neovim is shown in a darker turquoise color, while the data used by the process is in our usual green.
neovim
Hay! I bet all the neovim code is the same! Why do we have to have three copies of it?
Right now, we don't have any way not to. But perhaps if we went back to our friendly CPU designer, we could ask for a bit of help.
A way to share. I like it!
I have an idea. On the CPU, we actually want MORE of something!
I think I see it. We could have separate logical spaces for code and data, and then we could share the code between processes. We'd need a base and limit register for each space, but that doesn't seem like a lot to ask for.
Hay! Can the CPU even tell when its accessing code or data?
Yes. The CPU knows when it's doing an instruction fetch to read code, and when it's doing a data read or write.
We'll call these logical spaces segments. We'll have a segment for code and another segment for data. Each segment will have its own base and limit registers. By making the code segment read-only, we can share the code between processes, as shown in the following diagram.
neovim is More
We can go even further, let's have a segment for the stack, too!
That's actually a good idea. It will make it easier to move or grow the stack, and avoid unused space in the data segment just in case the stack grows.
In fact, the Intel X86 has segment registers
CS,DS,SS, andESfor code, data, stack, and extra data. These registers have existed since the debut of the 8086 in 1978, although the CPU didn't use them for memory protection until the 80286 in 1982. In 1985, the 80386 added theFSandGSregisters for extra segments. Processor instructions could specify which segment to use, as inmov ax, [es:0x1234], to use the extra segment registerESto access memory instead of the default,DS.
Meh. The 1980s are alive in Claremont. Can we go home now?
Actually, we've reached a pretty good point to stop. We'll come back to segments and generalize them a bit next time.
Also, today's x86 CPUs still have segment registers, so they still have some relevance today. That said, they're not used by the OS to provide processes with shared-but-protected memory areas; instead they tend to be used inside processes for things like thread-local storage, allowing “the same location” to be different for different threads. But CPUs such as ARM and RISC-V don't have segment registers, and have to find a different way to provide the same functionality.
(When logged in, completion status appears here.)