summaryrefslogtreecommitdiff
path: root/components/drivers/ipc/completion_mp.c
blob: 3c9c65d58bc094dba63b7084113290fac316c274 (plain)
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
/*
 * Copyright (c) 2006-2024, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2024-04-26     Shell        lockless rt_completion for MP system
 */

#define DBG_TAG           "drivers.ipc"
#define DBG_LVL           DBG_INFO
#include <rtdbg.h>

#include <rtthread.h>
#include <rthw.h>
#include <rtdevice.h>

#define RT_COMPLETED        1
#define RT_UNCOMPLETED      0
#define RT_WAKING           (-1)
#define RT_OCCUPIED         (-2)

#define RT_COMPLETION_NEW_STAT(thread, flag) (((flag) & 1) | (((rt_base_t)thread) & ~1))

/**
 * The C11 atomic can be ~5% and even faster in testing on the arm64 platform
 * compared to rt_atomic. So the C11 way is always preferred.
 */
#ifdef RT_USING_STDC_ATOMIC
#include <stdatomic.h>

#define IPC_STORE(dst, val, morder) atomic_store_explicit(dst, val, morder)
#define IPC_LOAD(dst, morder)       atomic_load_explicit(dst, morder)
#define IPC_BARRIER(morder)         atomic_thread_fence(morder)
#define IPC_CAS(dst, exp, desired, succ, fail) \
    atomic_compare_exchange_strong_explicit(dst, exp, desired, succ, fail)

#else /* !RT_USING_STDC_ATOMIC */
#include <rtatomic.h>

#define IPC_STORE(dst, val, morder) rt_atomic_store(dst, val)
#define IPC_LOAD(dst, morder)       rt_atomic_load(dst)
#define IPC_BARRIER(morder)
#define IPC_CAS(dst, exp, desired, succ, fail) \
    rt_atomic_compare_exchange_strong(dst, exp, desired)
#endif /* RT_USING_STDC_ATOMIC */

static rt_err_t _comp_susp_thread(struct rt_completion *completion,
                                  rt_thread_t thread, rt_int32_t timeout,
                                  int suspend_flag);

/**
 * @brief This function will initialize a completion object.
 *
 * @param completion is a pointer to a completion object.
 */
void rt_completion_init(struct rt_completion *completion)
{
    RT_ASSERT(completion != RT_NULL);

    IPC_STORE(&completion->susp_thread_n_flag, RT_UNCOMPLETED,
              memory_order_relaxed);
}
RTM_EXPORT(rt_completion_init);

/**
 * @brief This is same as rt_completion_wait_flags(), except that this API is NOT
 *        ISR-safe (you can NOT call completion_done() on isr routine).
 *
 * @param completion is a pointer to a completion object.
 * @param timeout is a timeout period (unit: OS ticks). If the completion is unavailable, the thread will wait for
 *                the completion done up to the amount of time specified by the argument.
 *                NOTE: Generally, we use the macro RT_WAITING_FOREVER to set this parameter, which means that when the
 *                completion is unavailable, the thread will be waitting forever.
 * @param suspend_flag suspend flags. See rt_thread_suspend_with_flag()
 *
 * @return Return the operation status. ONLY when the return value is RT_EOK, the operation is successful.
 *         If the return value is any other values, it means that the completion wait failed.
 *
 * @warning This function can ONLY be called in the thread context. It MUST NOT be called in interrupt context.
 */
rt_err_t rt_completion_wait_flags_noisr(struct rt_completion *completion,
                                        rt_int32_t timeout, int suspend_flag)
{
    rt_err_t result = -RT_ERROR;
    rt_thread_t thread;
    rt_bool_t exchange_succ;
    rt_base_t expected_value;
    RT_ASSERT(completion != RT_NULL);

    /* current context checking */
    RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0);

    thread = rt_thread_self();

    do
    {
        /* try to consume one completion */
        expected_value = RT_COMPLETED;
        exchange_succ =
            IPC_CAS(&completion->susp_thread_n_flag, &expected_value,
                    RT_UNCOMPLETED, memory_order_acquire, memory_order_relaxed);

        if (exchange_succ)
        {
            /* consume succeed, now return EOK */
            result = RT_EOK;
            break;
        }
        else if (expected_value == RT_WAKING)
        {
            /* previous wake is not done yet, yield thread & try again */
            rt_thread_yield();
        }
        else
        {
            /**
             * API rules say: only one thread can suspend on complete.
             * So we assert if debug.
             */
            RT_ASSERT(expected_value == RT_UNCOMPLETED);

            if (timeout != 0)
            {
                /**
                 * try to occupy completion, noted that we are assuming that
                 * `expected_value == RT_UNCOMPLETED`
                 */
                exchange_succ = IPC_CAS(
                    &completion->susp_thread_n_flag, &expected_value,
                    RT_OCCUPIED, memory_order_relaxed, memory_order_relaxed);

                if (exchange_succ)
                {
                    /* complete waiting business and return result */
                    result = _comp_susp_thread(completion, thread, timeout,
                                               suspend_flag);

                    RT_ASSERT(rt_atomic_load(&completion->susp_thread_n_flag) !=
                              RT_OCCUPIED);

                    break;
                }
                else
                {
                    /* try again */
                }
            }
            else
            {
                result = -RT_ETIMEOUT;
                break;
            }
        }
    } while (1);

    return result;
}

/**
 * @brief This function will wait for a completion, if the completion is unavailable, the thread shall wait for
 *        the completion up to a specified time.
 *
 * @param completion is a pointer to a completion object.
 * @param timeout is a timeout period (unit: OS ticks). If the completion is unavailable, the thread will wait for
 *                the completion done up to the amount of time specified by the argument.
 *                NOTE: Generally, we use the macro RT_WAITING_FOREVER to set this parameter, which means that when the
 *                completion is unavailable, the thread will be waitting forever.
 * @param suspend_flag suspend flags. See rt_thread_suspend_with_flag()
 *
 * @return Return the operation status. ONLY when the return value is RT_EOK, the operation is successful.
 *         If the return value is any other values, it means that the completion wait failed.
 *
 * @warning This function can ONLY be called in the thread context. It MUST NOT be called in interrupt context.
 */
rt_err_t rt_completion_wait_flags(struct rt_completion *completion,
                                  rt_int32_t timeout, int suspend_flag)
{
    rt_err_t error;
    rt_ubase_t level;
    level = rt_hw_local_irq_disable();
    error = rt_completion_wait_flags_noisr(completion, timeout, suspend_flag);
    rt_hw_local_irq_enable(level);
    return error;
}

static rt_base_t _wait_until_update(struct rt_completion *completion, rt_base_t expected)
{
    rt_base_t current_value;

    /* spinning for update */
    do
    {
        rt_hw_isb();
        current_value =
            IPC_LOAD(&completion->susp_thread_n_flag, memory_order_relaxed);
    } while (current_value == expected);

    return current_value;
}

/**
 * Try to suspend thread and update completion
 */
static rt_err_t _comp_susp_thread(struct rt_completion *completion,
                                  rt_thread_t thread, rt_int32_t timeout,
                                  int suspend_flag)
{
    rt_err_t error = -RT_ERROR;
    rt_base_t clevel;
    rt_base_t comp_waiting;

    /* suspend thread */
    clevel = rt_enter_critical();

    /* reset thread error number */
    thread->error = RT_EOK;

    error = rt_thread_suspend_with_flag(thread, suspend_flag);

    if (error)
    {
        rt_exit_critical_safe(clevel);
        RT_ASSERT(rt_atomic_load(&completion->susp_thread_n_flag) ==
                  RT_OCCUPIED);
        IPC_STORE(&completion->susp_thread_n_flag, RT_UNCOMPLETED,
                  memory_order_relaxed);
    }
    else
    {
        /* set to waiting */
        comp_waiting = RT_COMPLETION_NEW_STAT(thread, RT_UNCOMPLETED);
        RT_ASSERT(rt_atomic_load(&completion->susp_thread_n_flag) ==
                  RT_OCCUPIED);
        IPC_STORE(&completion->susp_thread_n_flag, comp_waiting,
                  memory_order_relaxed);

        /* current context checking */
        RT_DEBUG_NOT_IN_INTERRUPT;

        /* start timer */
        if (timeout > 0)
        {
            rt_tick_t timeout_tick = timeout;
            /* reset the timeout of thread timer and start it */
            rt_timer_control(&(thread->thread_timer),
                             RT_TIMER_CTRL_SET_TIME,
                             &timeout_tick);
            rt_timer_start(&(thread->thread_timer));
        }

        /* do schedule */
        rt_schedule();

        rt_exit_critical_safe(clevel);

        /* thread is woken up */
        error = thread->error;
        error = error > 0 ? -error : error;

        /* clean completed flag & remove susp_thread on the case of waking by timeout */
        if (!error)
        {
            /* completion done successfully */
            RT_ASSERT(rt_atomic_load(&completion->susp_thread_n_flag) !=
                      comp_waiting);

            /* the necessary barrier is done during thread sched */
        }
        else
        {
            /* try to cancel waiting if woken up expectedly or timeout */
            if (!IPC_CAS(&completion->susp_thread_n_flag, &comp_waiting,
                         RT_UNCOMPLETED, memory_order_relaxed,
                         memory_order_relaxed))
            {
                /* cancel failed, producer had woken us in the past, fix error */
                if (comp_waiting == RT_WAKING)
                {
                    _wait_until_update(completion, RT_WAKING);
                }
                IPC_BARRIER(memory_order_acquire);
                error = RT_EOK;
            }
        }
    }

    return error;
}

/**
 * @brief   This function indicates a completion has done and wakeup the thread
 *          and update its errno. No update is applied if it's a negative value.
 *
 * @param   completion is a pointer to a completion object.
 * @param   thread_errno is the errno set to waking thread.
 * @return  RT_EOK if wakeup succeed.
 *          RT_EEMPTY if wakeup failure and the completion is set to completed.
 *          RT_EBUSY if the completion is still in completed state
 */
rt_err_t rt_completion_wakeup_by_errno(struct rt_completion *completion,
                                       rt_err_t thread_errno)
{
    rt_err_t error = -RT_ERROR;
    rt_thread_t suspend_thread;
    rt_bool_t exchange_succ;
    rt_base_t expected_value;
    RT_ASSERT(completion != RT_NULL);

    do
    {
        /* try to transform from uncompleted to completed */
        expected_value = RT_UNCOMPLETED;

        exchange_succ =
            IPC_CAS(&completion->susp_thread_n_flag, &expected_value,
                    RT_COMPLETED, memory_order_release, memory_order_relaxed);

        if (exchange_succ)
        {
            error = -RT_EEMPTY;
            break;
        }
        else
        {
            if (expected_value == RT_COMPLETED)
            {
                /* completion still in completed state */
                error = -RT_EBUSY;
                break;
            }
            else if (expected_value == RT_OCCUPIED ||
                     expected_value == RT_WAKING)
            {
                continue;
            }
            else
            {
                /* try to resume the thread and set uncompleted */
                exchange_succ = IPC_CAS(
                    &completion->susp_thread_n_flag, &expected_value,
                    RT_WAKING, memory_order_relaxed, memory_order_relaxed);

                if (exchange_succ)
                {
                    #define GET_THREAD(val) ((rt_thread_t)((val) & ~1))
                    suspend_thread = GET_THREAD(expected_value);

                    if (thread_errno >= 0)
                    {
                        suspend_thread->error = thread_errno;
                    }

                    /* safe to assume publication done even on resume failure */
                    RT_ASSERT(rt_atomic_load(&completion->susp_thread_n_flag) ==
                              RT_WAKING);
                    IPC_STORE(&completion->susp_thread_n_flag, RT_UNCOMPLETED,
                              memory_order_release);
                    rt_thread_resume(suspend_thread);
                    error = RT_EOK;
                    break;
                }
                else
                {
                    /* failed in racing to resume thread, try again */
                }
            }
        }
    } while (1);

    return error;
}