Sub topic 12
Protection, Shared Pages and Copy-on-Write
This chapter assumes you can translate a virtual address into a page number and offset and read a page table entry. You should also know what a page fault is and roughly how fork() creates a process. Here you will see how the page table enforces protection, how several processes can map the same physical frame, and how copy-on-write (COW) uses both ideas to make fork() cheap.
Protection in a Paged System
Every memory reference goes through the page table, so the page table is the natural place to enforce access rules. The hardware checks the rules on each translation, in parallel with the address lookup. A violation raises a trap, and the OS decides what to do, usually by killing the process (on Linux, with a segmentation fault).
A page table entry (PTE) holds the frame number plus a few control bits:
| Bit | Meaning | Violation triggers |
|---|---|---|
| Valid/invalid | Page is (or is not) part of the process's address space and is present | Page fault or illegal-address trap |
| Read/write | Writes allowed or not | Protection trap on a store to a read-only page |
| Execute | Instructions may be fetched from the page | Trap on an instruction fetch (blocks code injection into data pages) |
| User/supervisor | Page is accessible in user mode or kernel mode only | Trap on a user access to a kernel page |
| Reference, dirty | Set by hardware on read or write | None. Replacement algorithms use these bits. |
In a demand-paged system the valid bit is overloaded. A page that is valid but not yet in memory and a page that is outside the address space both look "not present" to the hardware. The OS keeps extra per-region information (the valid ranges of the address space and the permissions of each) to tell the two cases apart. A reference to a legal but non-resident page is serviced by a page fault. A reference outside any legal region is a fatal error.
Page-table length register
Most processes use only a small part of a large virtual address space. Instead of allocating PTEs for the whole space, the hardware can keep a page-table length register (PTLR). Any page number at or above the PTLR value is rejected without consulting the table. This is the paged equivalent of the limit register in contiguous allocation.
The last-page gotcha
Memory is granted in whole pages, so a process's size is rarely a multiple of the page size. The remainder of the last page is internal fragmentation, and the PTE for that page is marked valid. The process can therefore touch bytes past the end of its real data without a trap. Paging protects at page granularity only.
Consider a 14-bit logical address space with 2 KB pages, and a process that uses addresses 0 to 10468.
- The address space is 2^14 = 16 KB, so it has 8 pages (0 to 7).
- Address 10468 lies in page ⌊10468 / 2048⌋ = 5, so pages 0 to 5 are valid and pages 6 and 7 are invalid.
- Page 5 covers addresses 10240 to 12287. Addresses 10469 to 12287 are valid in the table even though the process never allocated them. The internal fragmentation is 12287 − 10468 = 1819 bytes.
Shared Pages
Two page tables can contain entries that point to the same physical frame. The frame exists once in RAM and is mapped into several address spaces. This is what sharing means in a paged system, and it is a major advantage of paging over contiguous allocation.
Typical uses:
- Reentrant (pure) code. If 40 processes run the same editor, one copy of its text pages is mapped into all 40 tables. The pages must be read-only and must never modify themselves. Each process keeps its own private data and stack pages.
- Shared libraries. One copy of the C library in RAM serves every process that links it. The code must be position independent, or all processes must map it at the same virtual address, because the instructions inside the frame are the same for everyone.
- Explicit shared memory. Processes that map the same region as writable (for example
mmapwithMAP_SHARED, or POSIX shared memory) use it for communication. Here writes are visible to every sharer, which is the intended behavior.
Sharing saves frames. If 40 processes each need 10 pages of code, private copies use 400 frames, and sharing uses 10. Per-process page tables are still needed, one per process, so the table overhead does not shrink.
Sharing is awkward with inverted page tables. An inverted table has one entry per physical frame, and each entry names a single (process, page) owner. A frame mapped by two processes therefore needs extra mechanisms, such as a chain of mappings.
Copy-on-Write
fork() must give the child a copy of the parent's address space. Physically copying every page is wasteful, especially when the child calls exec() immediately and discards the copy. COW avoids the copy:
- At
fork(), the OS copies only the page table. Parent and child now map the same frames. - Every writable shared page is marked read-only in both tables, and the OS records that it is a COW page. A reference count on each frame records how many tables point to it.
- Reads proceed at full speed. Nothing was copied.
- On the first write to a COW page, the hardware raises a protection fault. The handler sees that the page is COW, not truly read-only.
- If the frame's reference count is greater than 1, the handler allocates a new frame, copies the page into it, points the writer's PTE at the copy, and decrements the count on the original. It then marks the writer's PTE writable. If the count is 1, the other sharer already took its own copy, so the handler only makes the PTE writable again.
- The faulting instruction is restarted and now succeeds.
The next program shows the observable result. After fork(), the child's write to x does not affect the parent, even though both initially shared the same frame:
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void) {
int x = 10;
pid_t pid = fork();
if (pid < 0) {
perror("fork");
return EXIT_FAILURE;
}
if (pid == 0) {
x = 99; /* triggers a COW fault in the child */
printf("child x=%d\n", x);
return 0;
}
wait(NULL);
printf("parent x=%d\n", x); /* still 10 */
return 0;
}The program prints child x=99 and then parent x=10. Programs cannot see COW happening. It is an optimization that preserves the semantics of a full copy.
A simulation of the mechanism
This Python model tracks reference counts and permissions. It shows why a COW fault differs from a real protection violation: the cow flag tells them apart.
class Frame:
def __init__(self, data):
self.data = data
self.refs = 1
class Entry:
def __init__(self, frame, writable):
self.frame = frame
self.writable = writable
self.cow = False
def fork(table):
child = {}
for page, e in table.items():
e.frame.refs += 1
if e.writable:
e.writable = False
e.cow = True
c = Entry(e.frame, False)
c.cow = e.cow
child[page] = c
return child
def write(table, page, value):
e = table[page]
if not e.writable:
if not e.cow:
raise PermissionError("protection violation")
if e.frame.refs > 1: # still shared: copy the frame
e.frame.refs -= 1
e.frame = Frame(e.frame.data)
e.writable = True # sole owner: just re-enable writes
e.cow = False
e.frame.data = value
parent = {0: Entry(Frame("A"), True), 1: Entry(Frame("code"), False)}
child = fork(parent)
write(child, 0, "B")
print(parent[0].frame.data, child[0].frame.data) # A B
print(parent[0].frame.refs, child[0].frame.refs) # 1 1
write(parent, 0, "C") # refs is 1: no copy needed
try:
write(child, 1, "x") # genuinely read-only page
except PermissionError:
print("violation")The output is A B, then 1 1, then violation.
Cost model for GATE-style questions
- Frames needed after
fork()immediately: 0 new data frames (a small amount for page tables). - Frames needed after the child writes to k distinct COW pages: k new frames. Repeated writes to the same page cost nothing extra.
- If the parent later writes to a page the child has already copied, no copy happens, because that frame's count is already 1.
- Each COW fault costs roughly one page fault plus one page copy. For a page size P and a copy rate of r bytes per second, the copy time is P/r.
COW also supports zero-fill-on-demand. Newly allocated anonymous memory can initially map one shared read-only zero page, and the first write allocates a real frame.
Common Errors
- Treating every protection fault as fatal. A write fault on a COW page is a normal event that the kernel resolves silently.
- Forgetting the TLB. When the kernel changes a PTE (read-only to writable, or a new frame), any cached TLB entry for that page is stale. The kernel must invalidate it, and on multiprocessors it must also invalidate the entries on other CPUs (a TLB shootdown).
- Sharing writable data pages without COW. Two processes that share a writable page see each other's writes. That is correct for shared memory and wrong for
fork(). - Assuming valid means allocated. The valid bit covers whole pages, so the unused tail of the last page is still reachable.
Exercise
A process has 50 pages, all writable, and calls fork() on a system with copy-on-write. The child then writes to 8 distinct pages, many times each, and the parent afterwards writes to 3 of those same 8 pages and 4 other pages. Assuming the child ran first, how many additional data frames are allocated in total?
Show answer
The child's first write to each of its 8 pages copies them, so 8 new frames. When the parent then writes to 3 of those pages, the frame reference count is already 1 (the child holds its own copy), so the parent only re-enables write permission and no copy is made. The 4 other pages are still shared with the child, so the parent's writes trigger 4 copies. Total: 8 + 4 = 12 additional frames.
Exercise
A system has 32-bit virtual addresses and 4 KB pages. A process occupies exactly 5000 bytes starting at address 0, and the page table marks as valid only the pages that contain process bytes. How many pages are valid, and how many bytes past the process's last byte can it still access without a trap?
Show answer
5000 bytes need ⌈5000 / 4096⌉ = 2 pages, so pages 0 and 1 are valid. Together they cover addresses 0 to 8191. The process's last byte is at address 4999, so addresses 5000 to 8191 can be accessed without a trap. That is 8191 − 4999 = 3192 bytes.