aboutsummaryrefslogtreecommitdiff
path: root/src/root.c
blob: 172728e20b5a82f90d1648a45505eaf809df4410 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/* SPDX-License-Identifier: copyleft-next-0.3.1 */
/* Copyright 2023 Kim Kuparinen < kimi.h.kuparinen@gmail.com > */

#include <stdlib.h>

#include <gran/root.h>
#include <gran/clock_domain.h>

#define MAX_DOMAINS 512

struct gran_root {
	size_t num_domains;
	struct clock_domain *(domains[MAX_DOMAINS]);
};

struct gran_root *create_root()
{
	return calloc(1, sizeof(struct gran_root));
}

stat root_add_clock(struct gran_root *root, struct clock_domain *clk)
{
	if (root->num_domains == MAX_DOMAINS) {
		error("too many clock domains");
		return ESIZE;
	}

	root->domains[root->num_domains++] = clk;
	return OK;
}

static struct clock_domain *most_delayed_domain(struct gran_root *root)
{
	struct clock_domain *min = root->domains[0];

	for (size_t i = 1; i < root->num_domains; ++i) {
		struct clock_domain *cur = root->domains[i];
		if (lt_time(domain_time(cur), domain_time(min)))
			min = cur;
	}

	return min;
}

stat root_run(struct gran_root *root)
{
	if (root->num_domains == 0) {
		info("no clock domains added to root, exiting");
		return OK;
	}

	stat ret = OK;
	while (ret == OK)
		ret = clock_domain_tick(most_delayed_domain(root));

	if (ret == DONE)
		return OK;

	return ret;
}

void destroy_root(struct gran_root *root)
{
	for (size_t i = 0; i < root->num_domains; ++i)
		destroy_clock_domain(root->domains[i]);

	free(root);
}