Change sys_mbox_fetch implementation.
[bertos.git] / bertos / net / lwip / src / arch / sys_arch.c
1 #include "cfg/cfg_lwip.h"
2
3 #define LOG_LEVEL  3
4 #define LOG_FORMAT 0
5 #include <cfg/log.h>
6
7 #include <drv/timer.h>
8
9 #include <cpu/power.h>
10 #include <cpu/types.h>
11
12 #include <arch/sys_arch.h>
13 #include <lwip/sys.h>
14
15 #include <kern/signal.h>
16 #include <kern/msg.h>
17 #include <kern/proc.h>
18 #include <kern/proc_p.h>
19
20 #include <struct/heap.h>
21
22 #include <mware/event.h>
23
24 /****************************************************************************/
25
26 /*
27  * Generic mutex (binary semaphore) implementation
28  *
29  * TODO: move this to a different place (i.e., bertos/kern/sem.c).
30  */
31 INLINE void mutex_verify(struct Mutex *s)
32 {
33         (void)s;
34         ASSERT(s);
35         LIST_ASSERT_VALID(&s->wait_queue);
36         ASSERT((s->count == MUTEX_LOCKED) || (s->count == MUTEX_UNLOCKED));
37 }
38
39 bool mutex_attempt(struct Mutex *s)
40 {
41         return cpu_atomic_xchg(&s->count, MUTEX_LOCKED) == MUTEX_UNLOCKED;
42 }
43
44 static NOINLINE void mutex_slowpath_obtain(struct Mutex *s)
45 {
46         PROC_ATOMIC(
47                 mutex_verify(s);
48                 ADDTAIL(&s->wait_queue, (Node *)current_process)
49         );
50         proc_switch();
51 }
52
53 void mutex_obtain(struct Mutex *s)
54 {
55         if (UNLIKELY(cpu_atomic_xchg(&s->count, MUTEX_LOCKED)) !=
56                                 MUTEX_UNLOCKED)
57                 mutex_slowpath_obtain(s);
58 }
59
60 void mutex_release(struct Mutex *s)
61 {
62         Process *proc = NULL;
63
64         PROC_ATOMIC(
65                 mutex_verify(s);
66                 proc = (Process *)list_remHead(&s->wait_queue);
67                 if (!proc)
68                         s->count = 1;
69         );
70         if (proc)
71                 ATOMIC(proc_wakeup(proc));
72 }
73
74 void mutex_init(struct Mutex *s)
75 {
76         LIST_INIT(&s->wait_queue);
77         s->count = 1;
78 }
79
80 /****************************************************************************/
81
82 typedef struct SemNode
83 {
84         Node node;
85         Mutex sem;
86 } SemNode;
87
88 #define MAX_SEM_CNT 16
89
90 static struct SemNode sem_pool[MAX_SEM_CNT];
91 static List free_sem;
92
93 /**
94  * Creates and returns a new semaphore.
95  *
96  * \param count Specifies the initial state of the semaphore.
97  * \return The semaphore or SYS_SEM_NULL on error.
98  */
99 sys_sem_t sys_sem_new(u8_t count)
100 {
101         SemNode *sem;
102
103         PROC_ATOMIC(sem = (SemNode *)list_remHead(&free_sem));
104         if (UNLIKELY(!sem))
105         {
106                 LOG_ERR("Out of semaphores!\n");
107                 return SYS_SEM_NULL;
108         }
109
110         mutex_init(&sem->sem);
111         // must obtain semaphore depending on the parameter
112         // NOTE: count == 1 means that the semaphore is unlocked
113         if (count <= 0)
114                 mutex_obtain(&sem->sem);
115         return (sys_sem_t)&sem->sem;
116 }
117
118 /**
119  * Frees a semaphore created by sys_sem_new.
120  *
121  * \param semaphore Mutex to be freed
122  */
123 void sys_sem_free(sys_sem_t semaphore)
124 {
125         SemNode *sem = containerof(semaphore, SemNode, sem);
126         PROC_ATOMIC(ADDHEAD(&free_sem, &sem->node));
127 }
128
129 /**
130  * Signals (or releases) a semaphore.
131  */
132 void sys_sem_signal(sys_sem_t sem)
133 {
134         mutex_release(sem);
135 }
136
137 /**
138  * Blocks the thread while waiting for the semaphore to be signaled.
139  *
140  * The timeout parameter specifies how many milliseconds the function should block
141  * before returning; if the function times out, it should return SYS_ARCH_TIMEOUT.
142  * If timeout=0, then the function should block indefinitely.
143  * If the function acquires the semaphore, it should return how many milliseconds
144  * expired while waiting for the semaphore.
145  * The function may return 0 if the semaphore was immediately available.
146  */
147 u32_t sys_arch_sem_wait(sys_sem_t sem, u32_t timeout)
148 {
149         ticks_t end, start = timer_clock();
150
151         if (timeout == 0)
152         {
153                 mutex_obtain(sem);
154                 return ticks_to_ms(timer_clock() - start);
155         }
156
157         do
158         {
159                 cpu_relax();
160                 end = timer_clock();
161         } while ((end - start < ms_to_ticks(timeout) && !mutex_attempt(sem)));
162
163         return (end - start > ms_to_ticks(timeout)) ?
164                         SYS_ARCH_TIMEOUT : (u32_t)ticks_to_ms(end - start);
165 }
166
167 /* Mbox functions */
168
169 typedef struct IpPort
170 {
171         Node node;
172         MsgPort port;
173 } IpPort;
174
175 #define MAX_PORT_CNT 16
176 static struct IpPort port_pool[MAX_PORT_CNT];
177 static List free_port;
178
179 typedef struct IpMsg
180 {
181         Msg msg;
182         void *data;
183 } IpMsg;
184
185 #define MAX_MSG_CNT 32
186 static struct IpMsg msg_pool[MAX_MSG_CNT];
187 static List free_msg;
188
189 // TODO: allocate memory for 'size' messages
190 sys_mbox_t sys_mbox_new(UNUSED_ARG(int, size))
191 {
192         IpPort *port;
193
194         PROC_ATOMIC(port = (IpPort *)list_remHead(&free_port));
195         if (UNLIKELY(!port))
196         {
197                 LOG_ERR("Out of message ports!\n");
198                 return SYS_MBOX_NULL;
199         }
200         msg_initPort(&port->port, event_createGeneric());
201         port->port.event.Ev.Sig.sig_proc = NULL;
202
203         return (sys_mbox_t)(&port->port);
204 }
205
206 void sys_mbox_free(sys_mbox_t mbox)
207 {
208         IpPort *port = containerof(mbox, IpPort, port);
209         PROC_ATOMIC(ADDHEAD(&free_port, &port->node));
210 }
211
212 void sys_mbox_post(sys_mbox_t mbox, void *data)
213 {
214         if (UNLIKELY(sys_mbox_trypost(mbox, data) == ERR_MEM))
215                 LOG_ERR("out of messages!\n");
216 }
217
218 /*
219  * Try to post the "msg" to the mailbox. Returns ERR_MEM if this one
220  * is full, else, ERR_OK if the "msg" is posted.
221  */
222 err_t sys_mbox_trypost(sys_mbox_t mbox, void *data)
223 {
224         IpMsg *msg;
225
226         PROC_ATOMIC(msg = (IpMsg *)list_remHead(&free_msg));
227         if (UNLIKELY(!msg))
228                 return ERR_MEM;
229         msg->data = data;
230
231         msg_lockPort(mbox);
232         ADDTAIL(&mbox->queue, &msg->msg.link);
233         msg_unlockPort(mbox);
234
235         if (mbox->event.Ev.Sig.sig_proc)
236                 event_do(&mbox->event);
237
238         return ERR_OK;
239 }
240
241 u32_t sys_arch_mbox_fetch(sys_mbox_t mbox, void **data, u32_t timeout)
242 {
243         /* Blocks the thread until a message arrives in the mailbox, but does
244         not block the thread longer than "timeout" milliseconds (similar to
245         the sys_arch_sem_wait() function). If "timeout" is 0, the thread should
246         be blocked until a message arrives. The "msg" argument is a result
247         parameter that is set by the function (i.e., by doing "*msg =
248         ptr"). The "msg" parameter maybe NULL to indicate that the message
249         should be dropped.
250
251         The return values are the same as for the sys_arch_sem_wait() function:
252         Number of milliseconds spent waiting or SYS_ARCH_TIMEOUT if there was a
253         timeout.
254
255         Note that a function with a similar name, sys_mbox_fetch(), is
256         implemented by lwIP.
257         */
258
259         Msg *msg;
260         ticks_t start = timer_clock();
261
262         while (1)
263         {
264                 /* Fast path */
265                 msg = msg_get(mbox);
266                 if (LIKELY(msg))
267                         break;
268
269                 mbox->event.Ev.Sig.sig_proc = proc_current();
270                 /* Slow path */
271                 if (!timeout)
272                         event_wait(&mbox->event);
273                 else
274                 {
275                         if (!event_waitTimeout(&mbox->event,
276                                         ms_to_ticks(timeout)))
277                         {
278                                 mbox->event.Ev.Sig.sig_proc = NULL;
279                                 return SYS_ARCH_TIMEOUT;
280                         }
281                 }
282         }
283         mbox->event.Ev.Sig.sig_proc = NULL;
284         if (data)
285                 *data = containerof(msg, IpMsg, msg)->data;
286
287         PROC_ATOMIC(ADDHEAD(&free_msg, &msg->link));
288
289         return ticks_to_ms(timer_clock() - start);
290 }
291
292 u32_t sys_arch_mbox_tryfetch(sys_mbox_t mbox, void **data)
293 {
294         /* This is similar to sys_arch_mbox_fetch, however if a message is not
295         present in the mailbox, it immediately returns with the code
296         SYS_MBOX_EMPTY. On success 0 is returned.
297
298         To allow for efficient implementations, this can be defined as a
299         function-like macro in sys_arch.h instead of a normal function. For
300         example, a naive implementation could be:
301         #define sys_arch_mbox_tryfetch(mbox,msg) \
302           sys_arch_mbox_fetch(mbox,msg,1)
303         although this would introduce unnecessary delays.
304         */
305
306         Msg *msg;
307
308         msg = msg_get(mbox);
309         if (UNLIKELY(!msg))
310                 return SYS_MBOX_EMPTY;
311         if (data)
312                 *data = containerof(msg, IpMsg, msg)->data;
313         PROC_ATOMIC(ADDHEAD(&free_msg, &msg->link));
314
315         return 0;
316 }
317
318 typedef struct ThreadNode
319 {
320         Node node;
321         struct Process *pid;
322         void (*entry)(void *);
323         void *arg;
324         struct sys_timeouts timeout;
325 } ThreadNode;
326
327 #define MAX_THREAD_CNT 8
328
329 static ThreadNode thread_pool[MAX_THREAD_CNT];
330 static List free_thread;
331 static List used_thread;
332
333 static struct sys_timeouts lwip_system_timeouts; // Default timeouts list for lwIP
334
335 struct sys_timeouts *sys_arch_timeouts(void)
336 {
337         ThreadNode *thread_node;
338         struct Process *curr_pid = proc_current();
339
340         FOREACH_NODE(thread_node, &used_thread)
341         {
342                 if (thread_node->pid == curr_pid)
343                         return &(thread_node->timeout);
344         }
345
346         return &lwip_system_timeouts;
347 }
348
349 static void thread_trampoline(void)
350 {
351         ThreadNode *thread_node = (ThreadNode *)proc_currentUserData();
352
353         thread_node->entry(thread_node->arg);
354 }
355
356 #if !CONFIG_KERN_HEAP
357 /*
358  * NOTE: threads are never destroyed, consequently these stacks are never
359  * deallocated. So, the stack allocator can be implemented as a simple index
360  * that is atomically incremented at each allocation.
361  */
362 static cpu_stack_t thread_stack[MAX_THREAD_CNT]
363                         [DEFAULT_THREAD_STACKSIZE / sizeof(cpu_stack_t)]
364                                 ALIGNED(sizeof(cpu_stack_t));
365 static int last_stack;
366 #endif
367
368 sys_thread_t sys_thread_new(const char *name, void (* thread)(void *arg),
369                                 void *arg, int stacksize, int prio)
370 {
371         ThreadNode *thread_node;
372         cpu_stack_t *stackbase;
373
374         proc_forbid();
375         thread_node = (ThreadNode *)list_remHead(&free_thread);
376         if (UNLIKELY(!thread_node))
377         {
378                 proc_permit();
379                 return NULL;
380         }
381         ADDHEAD(&used_thread, &thread_node->node);
382         proc_permit();
383
384         thread_node->entry = thread;
385         thread_node->arg = arg;
386
387         #if !CONFIG_KERN_HEAP
388                 ASSERT(stacksize <= DEFAULT_THREAD_STACKSIZE);
389                 PROC_ATOMIC(stackbase = thread_stack[last_stack++]);
390         #else
391                 stackbase = NULL;
392         #endif
393         thread_node->pid = proc_new_with_name(name, thread_trampoline,
394                                 (void *)thread_node, stacksize, stackbase);
395         if (thread_node->pid == NULL)
396                 return NULL;
397
398         #if CONFIG_KERN_PRI
399                 proc_setPri(thread_node->pid, prio);
400         #else
401                 /* Avoid warnings when priorities are disabled */
402                 (void) prio;
403         #endif
404
405         return thread_node->pid;
406 }
407
408 void sys_init(void)
409 {
410         LIST_INIT(&free_sem);
411         LIST_INIT(&free_port);
412         LIST_INIT(&free_msg);
413         LIST_INIT(&free_thread);
414         LIST_INIT(&used_thread);
415
416         for (int i = 0; i < MAX_SEM_CNT; ++i)
417                 ADDHEAD(&free_sem, &sem_pool[i].node);
418
419         for (int i = 0; i < MAX_PORT_CNT; ++i)
420                 ADDHEAD(&free_port, &port_pool[i].node);
421
422         for (int i = 0; i < MAX_MSG_CNT; ++i)
423                 ADDHEAD(&free_msg, &msg_pool[i].msg.link);
424
425         for (int i = 0; i < MAX_THREAD_CNT; ++i)
426                 ADDHEAD(&free_thread, &thread_pool[i].node);
427 }