/* harakiri_sched.c — Brood scheduler daemon
 *
 * A kernel thread that wakes every 100ms, walks the Brood tag table,
 * and applies the agent×mode priority boost via set_user_nice().
 * No scheduler surgery — just the existing nice mechanism driven by
 * Harakiri policy. Original nice values are saved on tag and restored
 * on untag/exit, so nothing leaks.
 */
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/pid.h>
#include <linux/kthread.h>
#include <linux/delay.h>

#include <harakiri/harakiri_agent.h>
#include <harakiri/harakiri_brood.h>
#include <harakiri/harakiri_hivemind.h>

#define HK_SCHED_TICK_MS	100

/* The HiveMind owns the brood table; the daemon borrows it. */
extern struct hk_hivemind hk_hive;

/* Per-tag original nice, kept alongside the brood table */
#define HK_MAX_TAGS	HK_BROOD_TABLE_SIZE
static s8 hk_orig_nice[HK_MAX_TAGS];
static struct task_struct *hk_sched_task;

/* Boost (0-39) → nice delta: halve it, lower nice = higher priority */
static inline int hk_boost_to_nice(u8 boost, s8 orig)
{
	int n = (int)orig - (int)(boost >> 1);
	if (n < -20) n = -20;
	if (n > 19)  n = 19;
	return n;
}

static int hk_sched_fn(void *data)
{
	struct hk_hivemind *h = &hk_hive;
	int i;

	pr_info("harakiri: scheduler daemon online\n");

	while (!kthread_should_stop()) {
		msleep(HK_SCHED_TICK_MS);

		for (i = 0; i < HK_BROOD_TABLE_SIZE; i++) {
			struct hk_brood_tag *tag = &h->brood.table[i];
			struct pid *pid;
			struct task_struct *task;
			u8 boost;
			int want_nice, cur_nice;

			if (tag->pid == 0)
				continue;

			boost = hk_brood_boost(&h->brood, tag->pid);
			want_nice = hk_boost_to_nice(boost, hk_orig_nice[i]);

			pid = find_get_pid(tag->pid);
			if (!pid) {
				/* task exited — drop the tag */
				tag->pid = 0;
				continue;
			}
			task = pid_task(pid, PIDTYPE_PID);
			if (!task) {
				put_pid(pid);
				tag->pid = 0;
				continue;
			}
			get_task_struct(task);

			cur_nice = task_nice(task);
			if (cur_nice != want_nice) {
				set_user_nice(task, want_nice);
				pr_debug("harakiri: pid %u nice %d -> %d (boost %u, mode %u)\n",
					 tag->pid, cur_nice, want_nice,
					 boost, h->brood.mode);
			}

			put_task_struct(task);
			put_pid(pid);
		}
	}

	/* Restore original nices on stop */
	for (i = 0; i < HK_BROOD_TABLE_SIZE; i++) {
		struct hk_brood_tag *tag = &h->brood.table[i];
		struct pid *pid;
		struct task_struct *task;

		if (tag->pid == 0)
			continue;
		pid = find_get_pid(tag->pid);
		if (!pid)
			continue;
		task = pid_task(pid, PIDTYPE_PID);
		if (task) {
			get_task_struct(task);
			if (task_nice(task) != hk_orig_nice[i])
				set_user_nice(task, hk_orig_nice[i]);
			put_task_struct(task);
		}
		put_pid(pid);
		tag->pid = 0;
	}

	pr_info("harakiri: scheduler daemon offline\n");
	return 0;
}

int hk_sched_start(void)
{
	int i;
	for (i = 0; i < HK_MAX_TAGS; i++)
		hk_orig_nice[i] = 0; /* default nice; updated on tag */

	hk_sched_task = kthread_run(hk_sched_fn, NULL, "hk_sched");
	if (IS_ERR(hk_sched_task)) {
		pr_err("harakiri: failed to start scheduler daemon\n");
		return PTR_ERR(hk_sched_task);
	}
	return 0;
}

void hk_sched_stop(void)
{
	if (hk_sched_task && !IS_ERR(hk_sched_task))
		kthread_stop(hk_sched_task);
}

/*
 * Tag a task, saving its current nice. Call this instead of
 * hk_brood_tag() when the scheduler daemon is running.
 */
void hk_sched_tag(struct hk_hivemind *h, u32 pid, u32 agent_id, u8 role)
{
	u32 i = hk_brood_hash(pid);
	struct pid *p;
	struct task_struct *task;

	/* Save the original nice before tagging */
	p = find_get_pid(pid);
	if (p) {
		task = pid_task(p, PIDTYPE_PID);
		if (task) {
			get_task_struct(task);
			/* find the slot first to index orig_nice */
			u32 j;
			for (j = 0; j < HK_BROOD_TABLE_SIZE; j++) {
				u32 k = (i + j) & HK_BROOD_TABLE_MASK;
				if (h->brood.table[k].pid == pid ||
				    h->brood.table[k].pid == 0) {
					hk_orig_nice[k] = task_nice(task);
					break;
				}
			}
			put_task_struct(task);
		}
		put_pid(p);
	}

	hk_brood_tag(&h->brood, pid, agent_id, role);
}

/*
 * Untag a task, restoring its original nice. Call this instead of
 * hk_brood_untag() when the scheduler daemon is running.
 */
void hk_sched_untag(struct hk_hivemind *h, u32 pid)
{
	u32 i = hk_brood_hash(pid);
	u32 j;

	for (j = 0; j < HK_BROOD_TABLE_SIZE; j++) {
		u32 k = (i + j) & HK_BROOD_TABLE_MASK;
		if (h->brood.table[k].pid == pid) {
			struct pid *p = find_get_pid(pid);
			if (p) {
				struct task_struct *task =
					pid_task(p, PIDTYPE_PID);
				if (task) {
					get_task_struct(task);
					set_user_nice(task, hk_orig_nice[k]);
					put_task_struct(task);
				}
				put_pid(p);
			}
			break;
		}
		if (h->brood.table[k].pid == 0)
			break;
	}

	hk_brood_untag(&h->brood, pid);
}
