1d314cc3d7e15ec481406ac06f6c56f14db3d2cd
[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         do
157         {
158                 cpu_relax();
159                 end = timer_clock();
160         } while ((end - start < ms_to_ticks(timeout) && !mutex_attempt(sem)));
161
162         return (end - start > ms_to_ticks(timeout)) ?
163                         SYS_ARCH_TIMEOUT : (u32_t)ticks_to_ms(end - start);
164 }
165
166 /* Mbox functions */
167
168 typedef struct IpPort
169 {
170         Node node;
171         MsgPort port;
172 } IpPort;
173
174 #define MAX_PORT_CNT 16
175 static struct IpPort port_pool[MAX_PORT_CNT];
176 static List free_port;
177
178 typedef struct IpMsg
179 {
180         Msg msg;
181         void *data;
182 } IpMsg;
183
184 #define MAX_MSG_CNT 32
185 static struct IpMsg msg_pool[MAX_MSG_CNT];
186 static List free_msg;
187
188 // TODO: allocate memory for 'size' messages
189 sys_mbox_t sys_mbox_new(UNUSED_ARG(int, size))
190 {
191         IpPort *port;
192
193         PROC_ATOMIC(port = (IpPort *)list_remHead(&free_port));
194         if (UNLIKELY(!port))
195         {
196                 LOG_ERR("Out of message ports!\n");
197                 return SYS_MBOX_NULL;
198         }
199         msg_initPort(&port->port, event_createGeneric());
200
201         return (sys_mbox_t)(&port->port);
202 }
203
204 void sys_mbox_free(sys_mbox_t mbox)
205 {
206         IpPort *port = containerof(mbox, IpPort, port);
207         PROC_ATOMIC(ADDHEAD(&free_port, &port->node));
208 }
209
210 void sys_mbox_post(sys_mbox_t mbox, void *data)
211 {
212         if (UNLIKELY(sys_mbox_trypost(mbox, data) == ERR_MEM))
213                 LOG_ERR("out of messages!\n");
214 }
215
216 /*
217  * Try to post the "msg" to the mailbox. Returns ERR_MEM if this one
218  * is full, else, ERR_OK if the "msg" is posted.
219  */
220 err_t sys_mbox_trypost(sys_mbox_t mbox, void *data)
221 {
222         IpMsg *msg;
223
224         PROC_ATOMIC(msg = (IpMsg *)list_remHead(&free_msg));
225         if (UNLIKELY(!msg))
226                 return ERR_MEM;
227         msg->data = data;
228         msg_put(mbox, &msg->msg);
229
230         return ERR_OK;
231 }
232
233 u32_t sys_arch_mbox_fetch(sys_mbox_t mbox, void **data, u32_t timeout)
234 {
235         /* Blocks the thread until a message arrives in the mailbox, but does
236         not block the thread longer than "timeout" milliseconds (similar to
237         the sys_arch_sem_wait() function). If "timeout" is 0, the thread should
238         be blocked until a message arrives. The "msg" argument is a result
239         parameter that is set by the function (i.e., by doing "*msg =
240         ptr"). The "msg" parameter maybe NULL to indicate that the message
241         should be dropped.
242
243         The return values are the same as for the sys_arch_sem_wait() function:
244         Number of milliseconds spent waiting or SYS_ARCH_TIMEOUT if there was a
245         timeout.
246
247         Note that a function with a similar name, sys_mbox_fetch(), is
248         implemented by lwIP.
249         */
250
251         Msg *msg;
252         ticks_t start = timer_clock();
253
254         while (1)
255         {
256                 /* Fast path */
257                 msg = msg_get(mbox);
258                 if (LIKELY(msg))
259                         break;
260                 /* Slow path */
261                 if (!timeout)
262                         event_wait(&mbox->event);
263                 else if (!event_waitTimeout(&mbox->event,
264                                         ms_to_ticks(timeout)))
265                         return SYS_ARCH_TIMEOUT;
266         }
267         if (data)
268                 *data = containerof(msg, IpMsg, msg)->data;
269
270         PROC_ATOMIC(ADDHEAD(&free_msg, &msg->link));
271
272         return ticks_to_ms(timer_clock() - start);
273 }
274
275 u32_t sys_arch_mbox_tryfetch(sys_mbox_t mbox, void **data)
276 {
277         /* This is similar to sys_arch_mbox_fetch, however if a message is not
278         present in the mailbox, it immediately returns with the code
279         SYS_MBOX_EMPTY. On success 0 is returned.
280
281         To allow for efficient implementations, this can be defined as a
282         function-like macro in sys_arch.h instead of a normal function. For
283         example, a naive implementation could be:
284         #define sys_arch_mbox_tryfetch(mbox,msg) \
285           sys_arch_mbox_fetch(mbox,msg,1)
286         although this would introduce unnecessary delays.
287         */
288
289         Msg *msg;
290
291         msg = msg_get(mbox);
292         if (UNLIKELY(!msg))
293                 return SYS_MBOX_EMPTY;
294         if (data)
295                 *data = containerof(msg, IpMsg, msg)->data;
296         PROC_ATOMIC(ADDHEAD(&free_msg, &msg->link));
297
298         return 0;
299 }
300
301 typedef struct ThreadNode
302 {
303         Node node;
304         struct Process *pid;
305         void (*entry)(void *);
306         void *arg;
307         struct sys_timeouts timeout;
308 } ThreadNode;
309
310 #define MAX_THREAD_CNT 8
311
312 static ThreadNode thread_pool[MAX_THREAD_CNT];
313 static List free_thread;
314 static List used_thread;
315
316 static struct sys_timeouts lwip_system_timeouts; // Default timeouts list for lwIP
317
318 struct sys_timeouts *sys_arch_timeouts(void)
319 {
320         ThreadNode *thread_node;
321         struct Process *curr_pid = proc_current();
322
323         FOREACH_NODE(thread_node, &used_thread)
324         {
325                 if (thread_node->pid == curr_pid)
326                         return &(thread_node->timeout);
327         }
328
329         return &lwip_system_timeouts;
330 }
331
332 static void thread_trampoline(void)
333 {
334         ThreadNode *thread_node = (ThreadNode *)proc_currentUserData();
335
336         thread_node->entry(thread_node->arg);
337 }
338
339 sys_thread_t sys_thread_new(char *name, void (* thread)(void *arg),
340                                 void *arg, int stacksize, int prio)
341 {
342         ThreadNode *thread_node;
343
344         proc_forbid();
345         thread_node = (ThreadNode *)list_remHead(&free_thread);
346         if (UNLIKELY(!thread_node))
347         {
348                 proc_permit();
349                 return NULL;
350         }
351         ADDHEAD(&used_thread, &thread_node->node);
352         proc_permit();
353
354         thread_node->entry = thread;
355         thread_node->arg = arg;
356
357         thread_node->pid = proc_new_with_name(name, thread_trampoline,
358                                 (void *)thread_node, stacksize, NULL);
359         if (thread_node->pid == NULL)
360                 return NULL;
361
362         #if CONFIG_KERN_PRI
363                 proc_setPri(thread_node->pid, prio);
364         #endif
365
366         return thread_node->pid;
367 }
368
369 void sys_init(void)
370 {
371         LIST_INIT(&free_sem);
372         LIST_INIT(&free_port);
373         LIST_INIT(&free_msg);
374         LIST_INIT(&free_thread);
375         LIST_INIT(&used_thread);
376
377         for (int i = 0; i < MAX_SEM_CNT; ++i)
378                 ADDHEAD(&free_sem, &sem_pool[i].node);
379
380         for (int i = 0; i < MAX_PORT_CNT; ++i)
381                 ADDHEAD(&free_port, &port_pool[i].node);
382
383         for (int i = 0; i < MAX_MSG_CNT; ++i)
384                 ADDHEAD(&free_msg, &msg_pool[i].msg.link);
385
386         for (int i = 0; i < MAX_THREAD_CNT; ++i)
387                 ADDHEAD(&free_thread, &thread_pool[i].node);
388 }