/* harakiri_minnoe.h — Minnoe: equation/state transport
 *
 * HiveMind infrastructure, not an agent. The rings below are owned by
 * the HiveMind; agents don't think about transport, they just send.
 * (Formerly a standalone HK_MINNOE role — consolidated 2026-10-16.)
 * A single-producer / single-consumer lock-free ring buffer carrying
 * hk_telemetry structs between agents. Each agent pair (or agent→HiveMind)
 * gets its own ring. No locks, no sleeping — just head/tail indices and
 * memory barriers. The equations ride inside hk_telemetry.extra[].
 *
 * For now this is SPSC. MPSC comes later with per-producer rings fanning
 * into HiveMind.
 */
#ifndef _HARAKIRI_MINNOE_H
#define _HARAKIRI_MINNOE_H

#include <linux/types.h>
#include <linux/compiler.h>
#include <linux/errno.h>
#include <asm/barrier.h>
#include <harakiri/harakiri_agent.h>

#define HK_MINNOE_RING_SHIFT	8
#define HK_MINNOE_RING_SIZE	(1u << HK_MINNOE_RING_SHIFT)
#define HK_MINNOE_RING_MASK	(HK_MINNOE_RING_SIZE - 1u)

struct hk_minnoe_ring {
	struct hk_telemetry	buf[HK_MINNOE_RING_SIZE];
	u32			head;	/* next write index (producer) */
	u32			tail;	/* next read index (consumer) */
	u32			dropped;/* send attempts on a full ring */
};

/* Initialise a ring. The ring itself must be zeroed first. */
static inline void hk_minnoe_init(struct hk_minnoe_ring *r)
{
	r->head = 0;
	r->tail = 0;
	r->dropped = 0;
}

/* Number of messages waiting to be received. */
static inline u32 hk_minnoe_pending(const struct hk_minnoe_ring *r)
{
	u32 h = READ_ONCE(r->head);
	u32 t = READ_ONCE(r->tail);
	return (h - t) & 0xFFFFFFFFu;
}

/* True if no room for another message. */
static inline bool hk_minnoe_full(const struct hk_minnoe_ring *r)
{
	return hk_minnoe_pending(r) == HK_MINNOE_RING_SIZE;
}

/*
 * Send one telemetry message. Returns 0 on success, -ENOSPC if the ring
 * is full (dropped counter increments — telemetry loss is visible, not
 * silent).
 */
static inline int hk_minnoe_send(struct hk_minnoe_ring *r,
				 const struct hk_telemetry *m)
{
	u32 h;

	if (hk_minnoe_full(r)) {
		r->dropped++;
		return -ENOSPC;
	}
	h = r->head & HK_MINNOE_RING_MASK;
	r->buf[h] = *m;
	/* Ensure the message lands before the head index moves. */
	smp_wmb();
	WRITE_ONCE(r->head, r->head + 1);
	return 0;
}

/*
 * Receive one telemetry message. Returns 0 on success, -ENODATA if the
 * ring is empty.
 */
static inline int hk_minnoe_recv(struct hk_minnoe_ring *r,
				 struct hk_telemetry *out)
{
	u32 t;

	if (hk_minnoe_pending(r) == 0)
		return -ENODATA;
	t = r->tail & HK_MINNOE_RING_MASK;
	/* Ensure we read the head index before the message. */
	smp_rmb();
	*out = r->buf[t];
	smp_mb();
	WRITE_ONCE(r->tail, r->tail + 1);
	return 0;
}

#endif /* _HARAKIRI_MINNOE_H */
