</>EmbeddedInterview

Implement PCI configuration space read and write callbacks.

MediumCoding: Systems, Bitmaps & Virtualization

Short answer: A PCI function exposes configuration registers at byte offsets. Validate access size and alignment, then read/write little-endian bytes. A real device defines writable masks for each register.

#include <stdint.h>
#include <stdbool.h>
static uint8_t cfg[256] = {0x34, 0x12, 0x78, 0x56};
static uint8_t writable[256] = {[4] = 7}; /* demo command bits */

static bool valid(unsigned off, unsigned size)
{
    return (size == 1 || size == 2 || size == 4) &&
           off <= sizeof cfg - size && off % size == 0;
}

bool cfg_read(unsigned off, unsigned size, uint32_t *out)
{
    if (!valid(off, size)) return false;
    *out = 0;
    for (unsigned i = 0; i < size; i++)
        *out |= (uint32_t)cfg[off+i] << (8*i);
    return true;
}

bool cfg_write(unsigned off, unsigned size, uint32_t value)
{
    if (!valid(off, size)) return false;
    for (unsigned i = 0; i < size; i++) {
        uint8_t m = writable[off+i];
        cfg[off+i] = (cfg[off+i] & ~m) |
                     ((value >> (8*i)) & m);
    }
    return true;
}

Reading offset 0 with size 2 gives vendor ID 0x1234. Writes cannot change read-only IDs. This deliberately models only a few writable bits; real PCI/PCIe devices also implement BAR sizing/mapping, status W1C semantics and extended configuration space.