Implement an IOMMU/SMMU address translation table in C.
Short answer: An IOMMU translates a device's I/O virtual address (IOVA) to a physical address and checks DMA permissions. This educational model represents one device domain with a flat table of 64 pages.
#include <stdint.h>
#include <stdbool.h>
#define N 64
#define MASK UINT64_C(0xfff)
struct entry {
uint64_t pa;
bool valid, writable;
};
static struct entry io_pt[N];
bool io_map(uint64_t iova, uint64_t pa, bool writable)
{
if ((iova | pa) & MASK || (iova >> 12) >= N)
return false;
io_pt[iova >> 12] = (struct entry){pa, true, writable};
return true;
}
bool io_translate(uint64_t iova, bool write, uint64_t *pa)
{
uint64_t i = iova >> 12;
if (i >= N || !io_pt[i].valid ||
(write && !io_pt[i].writable)) return false;
*pa = io_pt[i].pa | (iova & MASK);
return true;
}
IOVA 0x2123 mapped to frame 0x9000 gives PA 0x9123. Real SMMUs use stream IDs, domains, multilevel tables and IOTLBs. Validate the physical target belongs to the device's domain; when unmapping, synchronize outstanding DMA and invalidate cached translations before recycling memory.