Hardware interview practice
Consume completed Ethernet receive descriptors
A power-of-two descriptor ring is owned by hardware while OWN=1. Firmware drains completed entries in order. Write a C function that consumes up to a caller-supplied packet limit.
Starting point
Question code
struct desc { uint16_t len, flags; }; // OWN=1, ERR=2
size_t drain_rx(struct desc *ring, size_t ring_n, size_t *tail,
uint16_t *lengths, size_t cap, size_t limit,
size_t *errors);Reviewed example
Work through one case
Input
The next descriptors are completed good packets of lengths 64 and 128 followed by an OWN descriptor; cap = 2, limit = 8.Expected output
Return 2, store lengths {64, 128}, and advance tail by two entries.Both completed descriptors fit the output, then draining stops before the hardware-owned descriptor.
What to cover
Requirements
- Require nonnull ring, tail, and errors, a power-of-two ring_n in 2..1024, *tail<ring_n, and lengths when cap>0; otherwise return 0 without mutation.
- Starting at *tail, stop at the first OWN descriptor or after limit descriptors; never write more than cap successful lengths.
- For each completed descriptor, increment *errors if ERR is set; otherwise store len if output space remains, and stop before consuming a successful descriptor when cap is full.
- After consuming a descriptor, set its OWN bit, clear ERR, advance tail modulo ring_n, and count it in the return value.
