Paging (source code)

= Paging
{wiki}

<Paging> divides an <address space> into fixed-size <memory pages> and main <computer memory> into equally sized <page frames>. Here assume <byte> addressing, one <memory page> size $P=2^b$ <bytes>, and an unsigned <virtual address> $v$. Its virtual page number $q$ and offset $d$ are
$$
q=\left\lfloor\frac{v}{P}\right\rfloor,\qquad d=v\bmod P,\qquad 0\leq d<P.
$$
The brackets denote the <floor function>, and $\bmod$ gives the <remainder> in <Euclidean division>. If the <page table> maps $q$ to physical frame number $f$ and permits the access, the <physical address> is
$$
a=fP+d.
$$
The low $b$ <bits> are unchanged; the other <bits> select the <memory page> or <page frame>. A <bit shift> and <bit mask> can extract these fields. https://pages.cs.wisc.edu/~remzi/OSTEP/vm-paging.pdf[Arpaci-Dusseau and Arpaci-Dusseau, OSTEP chapter 18: Paging, Introduction, sections 18.1–18.2]{ref}

For a 16-<bit> <virtual address> and $P=256=2^8$ <bytes>, take $v=\mathtt{0x1234}=4660$ in <hexadecimal>. Then $q=18=\mathtt{0x12}$ and $d=52=\mathtt{0x34}$. A mapping to $f=7=\mathtt{0x07}$ gives
$$
a=7\cdot256+52=1844=\mathtt{0x0734}.
$$
Thus the eight high <bits> choose a mapping; the eight low <bits> choose the same position in the resulting <page frame>. The 256-<byte> size is for illustration, not a claim about an actual architecture's supported <memory page> sizes.

\Image[/virtual-memory-address-translation.png]
{title=Translating 0x1234 through an illustrative page table, with a separate offset and access check}

The useful freedom is that adjacent <memory pages> can occupy unrelated <page frames>. In the diagram, virtual pages `0x12` and `0x13` occupy <page frames> `0x07` and `0x02`; <virtual addresses> `0x12ff` and `0x1300` are consecutive, but translate to <physical addresses> `0x07ff` and `0x0200`. Uniform units simplify placement and <page replacement>, at the cost of <page table> storage and unused <bytes> within partly filled <memory pages>. For example, placing 300 <bytes> in exclusive 256-<byte> <page frames> requires two <page frames>, leaving $512-300=212$ <bytes> unused.