dispatcher.c 1.67 KB
Newer Older
Rahix's avatar
Rahix committed
1
#include "api/dispatcher.h"
2

3
#include "max32665.h"
4
5
6
7
8
9
10
11
12
#include "sema.h"

#include <stdlib.h>
#include <string.h>

/* This function is defined by the generated dispatcher code */
void __api_dispatch_call(api_id_t id, void *buffer);

static volatile bool event_ready = false;
Rahix's avatar
Rahix committed
13
14
15
16
17

int api_dispatcher_init()
{
	int ret;

18
19
20
21
22
23
	ret = SEMA_Init(NULL);
	SEMA_FreeSema(_API_SEMAPHORE);
	API_CALL_MEM->reset_stub = __core1_reset;
	API_CALL_MEM->call_flag  = _API_FLAG_IDLE;
	API_CALL_MEM->id         = 0;
	API_CALL_MEM->int_id     = (-1);
Rahix's avatar
Rahix committed
24
25
26
27
28

	/*
	 * Enable TX events for both cores.
	 * TODO: Is this the right place?
	 */
Rahix's avatar
Rahix committed
29
30
	MXC_GCR->evten |=
		MXC_F_GCR_EVTEN_CPU0TXEVENT | MXC_F_GCR_EVTEN_CPU1TXEVENT;
Rahix's avatar
Rahix committed
31
32
33
34

	return ret;
}

Rahix's avatar
Rahix committed
35
bool api_dispatcher_poll_once()
Rahix's avatar
Rahix committed
36
{
Rahix's avatar
Rahix committed
37
38
39
40
	if (event_ready) {
		return false;
	}

Rahix's avatar
Rahix committed
41
42
	while (SEMA_GetSema(_API_SEMAPHORE) == E_BUSY) {
	}
Rahix's avatar
Rahix committed
43
44
45

	if (API_CALL_MEM->call_flag != _API_FLAG_CALLING) {
		SEMA_FreeSema(_API_SEMAPHORE);
Rahix's avatar
Rahix committed
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
		return false;
	}

	event_ready = true;
	return true;
}

bool api_dispatcher_poll()
{
	if (event_ready) {
		return true;
	}

	return api_dispatcher_poll_once();
}

api_id_t api_dispatcher_exec()
{
	if (!event_ready) {
Rahix's avatar
Rahix committed
65
66
67
		return 0;
	}

Rahix's avatar
Rahix committed
68
	api_id_t id = API_CALL_MEM->id;
Rahix's avatar
Rahix committed
69
70
71
	__api_dispatch_call(id, API_CALL_MEM->buffer);
	API_CALL_MEM->call_flag = _API_FLAG_RETURNED;

Rahix's avatar
Rahix committed
72
	event_ready = false;
Rahix's avatar
Rahix committed
73
74
75
76
77
78
79
80
	SEMA_FreeSema(_API_SEMAPHORE);

	/* Notify the caller that we returned */
	__SEV();
	__WFE();

	return id;
}
81
82
83
84
85
86
87
88
89
90
91
92

void api_prepare_args(char *args)
{
	/*
	 * The args are stored with an offset of 0x20 to make sure they won't
	 * collide with any integer return value of API calls like epic_exec().
	 */
	API_CALL_MEM->id = 0;
	for (int i = 0; i <= strlen(args); i++) {
		API_CALL_MEM->buffer[i + 0x20] = args[i];
	}
}