Hardware interview practice
Bounded MMIO polling helper
Firmware must wait for selected status bits without hanging forever or optimizing away device reads. Implement a C helper with exact validation, read-count, match, and timeout behavior.
Starting point
Question code
int wait_mask(volatile uint32_t *reg, uint32_t mask,
uint32_t expected, uint32_t max_reads);Reviewed example
Work through one case
Input
mask=0x0F, expected=0x05, max_reads=3; register samples are 0x01, 0x04, 0x15Expected output
Return 0 after exactly three volatile readsThe first two masked samples do not equal 0x05; the third gives 0x15 & 0x0F = 0x05.
What to cover
Requirements
- If reg is null or expected contains a 1 outside mask, return -EINVAL without reading reg.
- Otherwise perform at most max_reads volatile reads, one per iteration, and return 0 on the first value where (value & mask) equals expected.
- If no read matches, return -ETIMEDOUT; max_reads=0 performs no read and returns -ETIMEDOUT.
- Do not modify the register or arguments, and do not loop beyond the supplied bound.
