ENع
→Base and bounds
الدرس 29 · Memory management

Address spaces, base and bounds

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

14 دقيقة10 خطوات5 أسئلةIntermediate
عن هذا الدرس

Every process believes it has its own memory starting at address 0. That private view is its address space, and the kernel has to make it true while many processes share one set of memory chips. Follow the simplest way to do it, base and bounds: the kernel picks a slot for each process, loads two registers in the CPU's memory management unit, and swaps them on every switch, while the hardware checks and moves every single address. Watch the same address 1000 land in two different places, and an address that reaches too far get stopped before it can touch another process. The Hardware lessons on the memory hierarchy and virtual memory explain the chip side; The process: address space, registers and the PCB, User mode and kernel mode and The context switch and the timer interrupt are good warm-ups.

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل 29 · تفاعلي
01 / 10

Every process, its own memory

Two processes, A and B, run the same program. Each sees its own private memory, its address space: 16 KB of addresses from 0 up, holding its code, heap and stack. Both can use address 1000 without clashing.

address space (what each process sees)
  0 KB ......... code     the program itself
  just above ... heap     grows up
  ...  free ...
  up to 16 KB .. stack    grows down toward the heap

every address the program uses is a virtual address:
the kernel and the CPU decide where it really goes.
A and B both say "address 1000"; they mean different bytes.
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. Every process, its own memory

    Two processes, A and B, run the same program. Each sees its own private memory, its address space: 16 KB of addresses from 0 up, holding its code, heap and stack. Both can use address 1000 without clashing.

    address space (what each process sees)
      0 KB ......... code     the program itself
      just above ... heap     grows up
      ...  free ...
      up to 16 KB .. stack    grows down toward the heap
    
    every address the program uses is a virtual address:
    the kernel and the CPU decide where it really goes.
    A and B both say "address 1000"; they mean different bytes.
  2. The kernel picks a slot

    Physical memory here is 64 KB, cut into four 16 KB slots. The kernel keeps slot 0 for itself and B already sits at 16 KB. To start A, it takes a free slot from its free list, 32 KB, and loads A there.

    physical memory (64 KB, the real chips)
      0 KB ..  16 KB   kernel
      16 KB .. 32 KB   B
      32 KB .. 48 KB   free  -> A
      48 KB .. 64 KB   free
    
    free list   before: [32 KB, 48 KB]
                after:  [48 KB]
    A is loaded at physical 32 KB = 32768
  3. Base and bounds registers

    Before running A, the kernel sets two registers in the CPU's memory management unit (MMU): base = 32768, where A's slot starts, and bounds = 16384, its size. Setting them is privileged: only kernel mode may. Then A starts in user mode.

    MMU registers (one pair per CPU)
      base    = 32768   (32 KB, start of A's slot)
      bounds  = 16384   (16 KB, size of A's space)
    
    the instructions that set them are privileged:
    a user program that tries raises an exception
    kernel  return-from-trap -> A runs in user mode
  4. Line 1: adding the base

    A runs line 1 and reads address 1000. The MMU checks 1000 < 16384, then adds the base: 1000 + 32768 = 33768. The read goes to physical address 33768, inside A's slot. The kernel is not involved.

    process A, line 1   x = mem[1000]
    virtual address     1000
    check               1000 < bounds 16384     ok
    add                 1000 + base 32768 = 33768
    physical address    33768   (slot 32 KB .. 48 KB: A's)
    
    physical address = virtual address + base
    done by the hardware on every access, no kernel code
  5. Switching to B

    A timer interrupt hands the CPU to the kernel. It saves A's base and bounds in A's process control block (PCB) and loads B's: base 16384, bounds 16384. Then it returns to B in user mode.

    timer interrupt   A stops, kernel mode
    save   A's PCB  <- base 32768, bounds 16384
    load   MMU      <- B's PCB: base 16384, bounds 16384
    return-from-trap  B runs in user mode
    
    one base/bounds pair per CPU, so the kernel swaps
    it on every switch (real kernels swap the page-table
    pointer instead: satp on RISC-V, CR3 on x86-64)
  6. Same address, other place

    B runs the same line 1, address 1000. The MMU adds B's base: 1000 + 16384 = 17384, inside B's slot. Same virtual address, a different physical byte. B cannot even name A's memory.

    process B, line 1   x = mem[1000]
    check   1000 < 16384            ok
    add     1000 + 16384 = 17384   (B's slot)
    A got   1000 + 32768 = 33768   (A's slot)
    
    the same effect on a real system (C99, POSIX):
    
    #define _POSIX_C_SOURCE 200809L
    #include <stdio.h>
    #include <sys/wait.h>
    #include <unistd.h>
    
    int x = 0;
    
    int main(void) {
        pid_t pid = fork();
        if (pid == 0) {                 /* child */
            x = 1;
            printf("child:  &x = %p  x = %d\n", (void *)&x, x);
            return 0;
        }
        waitpid(pid, NULL, 0);          /* parent waits for the child */
        printf("parent: &x = %p  x = %d\n", (void *)&x, x);
        return 0;
    }
    
    prints the same &x twice; child x = 1, parent x = 0
  7. Line 2: past the bounds

    Line 2 reads address 20000. The MMU checks first: 20000 is not below the bounds 16384, so it refuses. Without the check it would add the base and land on 36384, inside A's slot.

    process B, line 2   x = mem[20000]
    check   20000 < 16384?   no  -> refused
    
    without the check:
            20000 + 16384 = 36384
            36384 is in 32 KB .. 48 KB: A's slot!
    
    the bounds check is what keeps processes apart
  8. The CPU traps to the kernel

    The refused access raises an exception. The CPU switches to kernel mode and jumps to the handler the kernel registered at boot. A user program cannot switch the check off: changing base or bounds is itself privileged.

    exception   out of bounds
    CPU         user -> kernel mode
                jump to the kernel's handler (trap table)
    
    no data was read or written
  9. The kernel ends B

    The kernel sends B the signal SIGSEGV, whose default action ends it. It puts B's slot back on the free list, ready for the next process. A's memory was never touched, and A carries on.

    signal     SIGSEGV   (invalid memory reference)
               default action: terminate (and dump core)
    free list  [16 KB, 48 KB]
    A          resumes: MMU <- base 32768, bounds 16384
  10. The catch: wasted space

    Base and bounds is simple and fast: one compare and one add. But A's whole 16 KB slot is reserved, even the unused gap between its heap and stack. That waste is internal fragmentation. Segmentation, the next lesson, splits the address space up.

    the whole machine as a Python simulation:
    
    BOUNDS = 16 * 1024                  # every address space: 16 KB
    pcb = {"A": 32 * 1024, "B": 16 * 1024}   # saved base per process
    
    def translate(vaddr, base, bounds):  # what the MMU does
        if not 0 <= vaddr < bounds:      # check first
            raise MemoryError(f"fault at {vaddr}")
        return base + vaddr              # then add the base
    
    for proc, vaddr in [("A", 1000), ("B", 1000), ("B", 20000)]:
        try:
            print(proc, vaddr, "->", translate(vaddr, pcb[proc], BOUNDS))
        except MemoryError as e:
            print(proc, e)
    
    prints:
    A 1000 -> 33768
    B 1000 -> 17384
    B fault at 20000

اختبار يتاح بعد الخطوة الأخيرة.