Implement a packet queue for a network driver (TX path).
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#define PKT_MAX 1518u
#define TXQ_LEN 8u
typedef struct { uint16_t len; uint8_t data[PKT_MAX]; } pkt_t;
static pkt_t pool[TXQ_LEN]; /* static packet pool, no malloc */
static unsigned q_head, q_tail, q_count; /* protect with a lock or critical section */
static bool hw_busy;
bool nic_hw_start_tx(const pkt_t *p); /* starts DMA/transmit, completes via tx_done_isr */
static void kick(void)
{
if (!hw_busy && q_count) {
hw_busy = true;
nic_hw_start_tx(&pool[q_tail]);
}
}
int net_send(const uint8_t *frame, uint16_t len)
{
if (len > PKT_MAX) return -1;
if (q_count == TXQ_LEN) return -2; /* queue full: back-pressure the stack */
pkt_t *p = &pool[q_head];
memcpy(p->data, frame, len);
p->len = len;
q_head = (q_head + 1) % TXQ_LEN;
q_count++;
kick();
return 0;
}
void tx_done_isr(void) /* hardware finished sending pool[q_tail] */
{
q_tail = (q_tail + 1) % TXQ_LEN;
q_count--;
hw_busy = false;
kick(); /* start the next queued packet */
}
Points: a fixed pool avoids fragmentation; when the queue is full, return an error so the protocol stack applies back-pressure (Linux drivers call netif_stop_queue() and wake it in the TX-complete interrupt); the completion interrupt starts the next packet so the link stays busy; shared counters need a critical section because net_send (task) and tx_done_isr (interrupt) both modify them. Zero-copy designs pass buffer ownership (pointers) instead of copying frames.