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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
|
#include <assert.h>
#include <interrupts.h>
#include <ipc.h>
#include <math.h>
#include <stdbool.h>
#include <string.h>
struct IpcEndpoint {
u8 in_use;
u32 pid;
};
struct IpcEndpoint ipc_endpoints[100];
bool ipc_register_endpoint(u32 endpoint) {
if (endpoint >= 100) {
return false;
}
if (ipc_endpoints[endpoint].in_use) {
return false;
}
ipc_endpoints[endpoint].in_use = 1;
ipc_endpoints[endpoint].pid = current_task->pid;
return true;
}
bool ipc_endpoint_to_pid(u32 endpoint, u32 *pid) {
if (endpoint >= 100) {
return false;
}
if (!ipc_endpoints[endpoint].in_use) {
return false;
}
*pid = ipc_endpoints[endpoint].pid;
return true;
}
int ipc_get_mailbox(u32 id, struct IpcMailbox **out) {
process_t *p;
if (!get_task_from_pid(id, &p)) {
return 0;
}
*out = &p->ipc_mailbox;
return 1;
}
int ipc_has_data(process_t *p) {
if (!p) {
p = current_task;
}
struct IpcMailbox *handler = &p->ipc_mailbox;
u32 read_ptr = handler->read_ptr;
struct IpcMessage *ipc_message = &handler->data[read_ptr];
return ipc_message->is_used;
}
int ipc_read(u8 *buffer, u32 length, u32 *sender_pid) {
struct IpcMailbox *handler = ¤t_task->ipc_mailbox;
u32 read_ptr = handler->read_ptr;
struct IpcMessage *ipc_message = &handler->data[read_ptr];
for (;;) {
if (!ipc_message->is_used) {
if (current_task->is_interrupted) {
current_task->is_interrupted = 0;
current_task->is_halted = 0;
return 0;
}
current_task->is_halted = 1;
switch_task();
continue;
}
break;
}
current_task->is_halted = 0;
disable_interrupts();
ipc_message->is_used = 0;
// TODO: Verify sender_pid is a valid address
if (sender_pid) {
assert(mmu_is_valid_userpointer(sender_pid, sizeof(ipc_message->sender_pid)));
*sender_pid = ipc_message->sender_pid;
}
u32 len = min(length, ipc_message->size);
memcpy(buffer, ipc_message->buffer, len);
// Update read_ptr
read_ptr++;
if (read_ptr >= IPC_NUM_DATA) {
read_ptr = 0;
}
handler->read_ptr = read_ptr;
return len;
}
int ipc_write_to_process(int pid, u8 *buffer, u32 length) {
struct IpcMailbox *handler;
assert(ipc_get_mailbox(pid, &handler));
u32 write_ptr = handler->write_ptr;
struct IpcMessage *ipc_message = &handler->data[write_ptr];
ipc_message->is_used = 1;
u32 len = min(IPC_BUFFER_SIZE, length);
ipc_message->sender_pid = current_task->pid;
ipc_message->size = len;
memcpy(ipc_message->buffer, buffer, len);
// Update write_ptr
write_ptr++;
if (write_ptr >= IPC_NUM_DATA) {
write_ptr = 0;
}
handler->write_ptr = write_ptr;
return len;
}
int ipc_write(int endpoint, u8 *buffer, u32 length) {
u32 pid;
assert(ipc_endpoint_to_pid(endpoint, &pid));
return ipc_write_to_process(pid, buffer, length);
}
|