HeapCrash / Challenges / GPIO through /dev/mem

GPIO through /dev/mem

A userspace daemon toggles a status LED and reads a fault input by mapping the SoC's GPIO bank through /dev/mem. The SoC packs its GPIO banks 0x400 apart, so several share each 4 KB page. The fault input sometimes reads stale, other pins on the same bank occasionally change state on their own, and after a kernel update the mapping fails at startup.

The code

Embedded Linux C. It compiles. There are 3 real bugs in it: the kind that pass a bench test and fail in the field.

#define GPIO_BASE  0x30200400u     /* GPIO bank 2 */
#define DR   0x00
#define PSR  0x08

static uint32_t *gpio;

int gpio_map(void)
{
    int fd = open("/dev/mem", O_RDWR);
    gpio = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, GPIO_BASE);
    return gpio ? 0 : -1;
}

void led_set(bool on)
{
    if (on) gpio[DR / 4] |= (1u << 9);
    else    gpio[DR / 4] &= ~(1u << 9);
}

bool fault_active(void)
{
    return gpio[PSR / 4] & (1u << 3);
}

What an interviewer expects

The bugs, reference fixes and the follow-up question are in the practice app, after you've tried it.

Companies that test this

Matched on the skills each company's embedded roles emphasise.

Related challenges

Flag the lines, say what breaks, then fix it and build it with clang in your browser.

Find the bugs