1/**
2 * @file
3 * lwIP Operating System abstraction
4 *
5 */
6
7/*
8 * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
9 * All rights reserved.
10 *
11 * Redistribution and use in source and binary forms, with or without modification,
12 * are permitted provided that the following conditions are met:
13 *
14 * 1. Redistributions of source code must retain the above copyright notice,
15 *    this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright notice,
17 *    this list of conditions and the following disclaimer in the documentation
18 *    and/or other materials provided with the distribution.
19 * 3. The name of the author may not be used to endorse or promote products
20 *    derived from this software without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
23 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
24 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
25 * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
26 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
27 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
30 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
31 * OF SUCH DAMAGE.
32 *
33 * This file is part of the lwIP TCP/IP stack.
34 *
35 * Author: Adam Dunkels <adam@sics.se>
36 *
37 */
38
39#include "lwip/opt.h"
40
41#if (NO_SYS == 0)               /* don't build if not configured for use in lwipopts.h */
42
43#include "lwip/sys.h"
44#include "lwip/def.h"
45#include "lwip/memp.h"
46#include "lwip/tcpip.h"
47
48/**
49 * Struct used for sys_sem_wait_timeout() to tell wether the time
50 * has run out or the semaphore has really become available.
51 */
52struct sswt_cb {
53    s16_t timeflag;
54    sys_sem_t *psem;
55};
56
57/**
58 * Wait (forever) for a message to arrive in an mbox.
59 * While waiting, timeouts (for this thread) are processed.
60 *
61 * @param mbox the mbox to fetch the message from
62 * @param msg the place to store the message
63 */
64void sys_mbox_fetch(sys_mbox_t mbox, void **msg)
65{
66    u32_t time_needed;
67    struct sys_timeouts *timeouts;
68    struct sys_timeo *tmptimeout;
69    sys_timeout_handler h;
70    void *arg;
71
72  again:
73    timeouts = sys_arch_timeouts();
74
75    if (!timeouts || !timeouts->next) {
76        UNLOCK_TCPIP_CORE();
77        time_needed = sys_arch_mbox_fetch(mbox, msg, 0);
78        LOCK_TCPIP_CORE();
79    } else {
80        if (timeouts->next->time > 0) {
81            UNLOCK_TCPIP_CORE();
82            time_needed = sys_arch_mbox_fetch(mbox, msg, timeouts->next->time);
83            LOCK_TCPIP_CORE();
84        } else {
85            time_needed = SYS_ARCH_TIMEOUT;
86        }
87
88        if (time_needed == SYS_ARCH_TIMEOUT) {
89            /* If time == SYS_ARCH_TIMEOUT, a timeout occured before a message
90               could be fetched. We should now call the timeout handler and
91               deallocate the memory allocated for the timeout. */
92            tmptimeout = timeouts->next;
93            timeouts->next = tmptimeout->next;
94            h = tmptimeout->h;
95            arg = tmptimeout->arg;
96            memp_free(MEMP_SYS_TIMEOUT, tmptimeout);
97            if (h != NULL) {
98                LWIP_DEBUGF(SYS_DEBUG,
99                            ("smf calling h=%p(%p)\n", (void *) &h, arg));
100                h(arg);
101            }
102
103            /* We try again to fetch a message from the mbox. */
104            goto again;
105        } else {
106            /* If time != SYS_ARCH_TIMEOUT, a message was received before the timeout
107               occured. The time variable is set to the number of
108               milliseconds we waited for the message. */
109            if (time_needed < timeouts->next->time) {
110                timeouts->next->time -= time_needed;
111            } else {
112                timeouts->next->time = 0;
113            }
114        }
115    }
116}
117
118/**
119 * Wait (forever) for a semaphore to become available.
120 * While waiting, timeouts (for this thread) are processed.
121 *
122 * @param sem semaphore to wait for
123 */
124void sys_sem_wait(sys_sem_t sem)
125{
126    u32_t time_needed;
127    struct sys_timeouts *timeouts;
128    struct sys_timeo *tmptimeout;
129    sys_timeout_handler h;
130    void *arg;
131
132  again:
133
134    timeouts = sys_arch_timeouts();
135
136    if (!timeouts || !timeouts->next) {
137        sys_arch_sem_wait(sem, 0);
138    } else {
139        if (timeouts->next->time > 0) {
140            time_needed = sys_arch_sem_wait(sem, timeouts->next->time);
141        } else {
142            time_needed = SYS_ARCH_TIMEOUT;
143        }
144
145        if (time_needed == SYS_ARCH_TIMEOUT) {
146            /* If time == SYS_ARCH_TIMEOUT, a timeout occured before a message
147               could be fetched. We should now call the timeout handler and
148               deallocate the memory allocated for the timeout. */
149            tmptimeout = timeouts->next;
150            timeouts->next = tmptimeout->next;
151            h = tmptimeout->h;
152            arg = tmptimeout->arg;
153            memp_free(MEMP_SYS_TIMEOUT, tmptimeout);
154            if (h != NULL) {
155                LWIP_DEBUGF(SYS_DEBUG,
156                            ("ssw h=%p(%p)\n", (void *) &h, (void *) arg));
157                h(arg);
158            }
159
160            /* We try again to fetch a message from the mbox. */
161            goto again;
162        } else {
163            /* If time != SYS_ARCH_TIMEOUT, a message was received before the timeout
164               occured. The time variable is set to the number of
165               milliseconds we waited for the message. */
166            if (time_needed < timeouts->next->time) {
167                timeouts->next->time -= time_needed;
168            } else {
169                timeouts->next->time = 0;
170            }
171        }
172    }
173}
174
175/**
176 * Create a one-shot timer (aka timeout). Timeouts are processed in the
177 * following cases:
178 * - while waiting for a message using sys_mbox_fetch()
179 * - while waiting for a semaphore using sys_sem_wait() or sys_sem_wait_timeout()
180 * - while sleeping using the inbuilt sys_msleep()
181 *
182 * @param msecs time in milliseconds after that the timer should expire
183 * @param h callback function to call when msecs have elapsed
184 * @param arg argument to pass to the callback function
185 */
186void sys_timeout(u32_t msecs, sys_timeout_handler h, void *arg)
187{
188    struct sys_timeouts *timeouts;
189    struct sys_timeo *timeout, *t;
190
191    timeout = memp_malloc(MEMP_SYS_TIMEOUT);
192    if (timeout == NULL) {
193        LWIP_ASSERT("sys_timeout: timeout != NULL", timeout != NULL);
194        return;
195    }
196    timeout->next = NULL;
197    timeout->h = h;
198    timeout->arg = arg;
199    timeout->time = msecs;
200
201    timeouts = sys_arch_timeouts();
202
203    LWIP_DEBUGF(SYS_DEBUG, ("sys_timeout: %p msecs=%" U32_F " h=%p arg=%p\n",
204                            (void *) timeout, msecs, (void *) &h,
205                            (void *) arg));
206
207    if (timeouts == NULL) {
208        LWIP_ASSERT("sys_timeout: timeouts != NULL", timeouts != NULL);
209        return;
210    }
211
212    if (timeouts->next == NULL) {
213        timeouts->next = timeout;
214        return;
215    }
216
217    if (timeouts->next->time > msecs) {
218        timeouts->next->time -= msecs;
219        timeout->next = timeouts->next;
220        timeouts->next = timeout;
221    } else {
222        for (t = timeouts->next; t != NULL; t = t->next) {
223            timeout->time -= t->time;
224            if (t->next == NULL || t->next->time > timeout->time) {
225                if (t->next != NULL) {
226                    t->next->time -= timeout->time;
227                }
228                timeout->next = t->next;
229                t->next = timeout;
230                break;
231            }
232        }
233    }
234}
235
236/**
237 * Go through timeout list (for this task only) and remove the first matching
238 * entry, even though the timeout has not triggered yet.
239 *
240 * @note This function only works as expected if there is only one timeout
241 * calling 'h' in the list of timeouts.
242 *
243 * @param h callback function that would be called by the timeout
244 * @param arg callback argument that would be passed to h
245*/
246void sys_untimeout(sys_timeout_handler h, void *arg)
247{
248    struct sys_timeouts *timeouts;
249    struct sys_timeo *prev_t, *t;
250
251    timeouts = sys_arch_timeouts();
252
253    if (timeouts == NULL) {
254        LWIP_ASSERT("sys_untimeout: timeouts != NULL", timeouts != NULL);
255        return;
256    }
257    if (timeouts->next == NULL) {
258        return;
259    }
260
261    for (t = timeouts->next, prev_t = NULL; t != NULL; prev_t = t, t = t->next) {
262        if ((t->h == h) && (t->arg == arg)) {
263            /* We have a match */
264            /* Unlink from previous in list */
265            if (prev_t == NULL)
266                timeouts->next = t->next;
267            else
268                prev_t->next = t->next;
269            /* If not the last one, add time of this one back to next */
270            if (t->next != NULL)
271                t->next->time += t->time;
272            memp_free(MEMP_SYS_TIMEOUT, t);
273            return;
274        }
275    }
276    return;
277}
278
279/**
280 * Timeout handler function for sys_sem_wait_timeout()
281 *
282 * @param arg struct sswt_cb* used to signal a semaphore and end waiting.
283 */
284static void sswt_handler(void *arg)
285{
286    struct sswt_cb *sswt_cb = (struct sswt_cb *) arg;
287
288    /* Timeout. Set flag to TRUE and signal semaphore */
289    sswt_cb->timeflag = 1;
290    sys_sem_signal(*(sswt_cb->psem));
291}
292
293/**
294 * Wait for a semaphore with timeout (specified in ms)
295 *
296 * @param sem semaphore to wait
297 * @param timeout timeout in ms (0: wait forever)
298 * @return 0 on timeout, 1 otherwise
299 */
300int sys_sem_wait_timeout(sys_sem_t sem, u32_t timeout)
301{
302    struct sswt_cb sswt_cb;
303
304    sswt_cb.psem = &sem;
305    sswt_cb.timeflag = 0;
306
307    /* If timeout is zero, then just wait forever */
308    if (timeout > 0) {
309        /* Create a timer and pass it the address of our flag */
310        sys_timeout(timeout, sswt_handler, &sswt_cb);
311    }
312    sys_sem_wait(sem);
313    /* Was it a timeout? */
314    if (sswt_cb.timeflag) {
315        /* timeout */
316        return 0;
317    } else {
318        /* Not a timeout. Remove timeout entry */
319        sys_untimeout(sswt_handler, &sswt_cb);
320        return 1;
321    }
322}
323
324/**
325 * Sleep for some ms. Timeouts are processed while sleeping.
326 *
327 * @param ms number of milliseconds to sleep
328 */
329void sys_msleep(u32_t ms)
330{
331    sys_sem_t delaysem = sys_sem_new(0);
332
333    sys_sem_wait_timeout(delaysem, ms);
334
335    sys_sem_free(delaysem);
336}
337
338
339#endif                          /* NO_SYS */
340