diff --git a/docs/progress.md b/docs/progress.md index edfabdca..26e381bc 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -1,5 +1,17 @@ # 开发进度 +## 2026-11-04 第 28 批再合入 3 道 HARD,main 共 1199 道 + +- **合入的题**(第 28 批 `ca63702`): + - RT-Thread 互斥量优先级上限:3 次过 1 次。 + - LVGL 重复节拍:3 次都失败,都是完整会话里修错。 + - RT-Thread 软定时器唤醒:3 次都失败。 + - 三道的题目指纹与测量一致,并确认仍在批次分支的最新提交里。 +- **本组 10 道**:HARD 3、ROUTINE 5。libuv 流关闭(1 次有效通过)和 NuttX YMODEM 重试写入(3 次都超时)各补测 3 次。 +- **累计**: + - 路线 D 已测 144 道,HARD 34、MEDIUM 19。 + - 第 28 批 30 道,HARD 5、MEDIUM 4,第三组明显好于前两组。 + ## 2026-11-04 补测后再合入 2 道 MEDIUM,main 共 1196 道 - **合入的题**(第 26 批 `5726468`,合计了补测): diff --git a/tasks/concur-rtthread-mutex-ceilings/cheat/src/ipc.c b/tasks/concur-rtthread-mutex-ceilings/cheat/src/ipc.c new file mode 100644 index 00000000..d15b8dd7 --- /dev/null +++ b/tasks/concur-rtthread-mutex-ceilings/cheat/src/ipc.c @@ -0,0 +1,3738 @@ +/* + * Copyright (c) 2006-2022, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +#include +#include + +#ifndef __on_rt_object_trytake_hook + #define __on_rt_object_trytake_hook(parent) __ON_HOOK_ARGS(rt_object_trytake_hook, (parent)) +#endif +#ifndef __on_rt_object_take_hook + #define __on_rt_object_take_hook(parent) __ON_HOOK_ARGS(rt_object_take_hook, (parent)) +#endif +#ifndef __on_rt_object_put_hook + #define __on_rt_object_put_hook(parent) __ON_HOOK_ARGS(rt_object_put_hook, (parent)) +#endif + +#if defined(RT_USING_HOOK) && defined(RT_HOOK_USING_FUNC_PTR) +extern void (*rt_object_trytake_hook)(struct rt_object *object); +extern void (*rt_object_take_hook)(struct rt_object *object); +extern void (*rt_object_put_hook)(struct rt_object *object); +#endif /* RT_USING_HOOK */ + +/** + * @addtogroup IPC + * @{ + */ + +/** + * @brief This function will initialize an IPC object, such as semaphore, mutex, messagequeue and mailbox. + * + * @note Executing this function will complete an initialization of the suspend thread list of the ipc object. + * + * @param ipc is a pointer to the IPC object. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * When the return value is any other values, it means the initialization failed. + * + * @warning This function can be called from all IPC initialization and creation. + */ +rt_inline rt_err_t _ipc_object_init(struct rt_ipc_object *ipc) +{ + /* initialize ipc object */ + rt_list_init(&(ipc->suspend_thread)); + + return RT_EOK; +} + + +/** + * @brief This function will suspend a thread to a IPC object list. + * + * @param list is a pointer to a suspended thread list of the IPC object. + * + * @param thread is a pointer to the thread object to be suspended. + * + * @param flag is a flag for the thread object to be suspended. It determines how the thread is suspended. + * The flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to use + * RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this semaphore will become non-real-time threads. + * + * @param suspend_flag status flag of the thread to be suspended. + * + * @return Return the operation status. When the return value is RT_EOK, the function is successfully executed. + * When the return value is any other values, it means the initialization failed. + * + * @warning This function can ONLY be called in the thread context, you can use RT_DEBUG_IN_THREAD_CONTEXT to + * check the context. + * In addition, this function is generally called by the following functions: + * rt_sem_take(), rt_mutex_take(), rt_event_recv(), rt_mb_send_wait(), + * rt_mb_recv(), rt_mq_recv(), rt_mq_send_wait() + */ +rt_inline rt_err_t _ipc_list_suspend(rt_list_t *list, + struct rt_thread *thread, + rt_uint8_t flag, + int suspend_flag) +{ + rt_err_t ret = rt_thread_suspend_with_flag(thread, suspend_flag); + + /* suspend thread */ + if (ret != RT_EOK) + { + return ret; + } + + switch (flag) + { + case RT_IPC_FLAG_FIFO: + rt_list_insert_before(list, &(thread->tlist)); + break; /* RT_IPC_FLAG_FIFO */ + + case RT_IPC_FLAG_PRIO: + { + struct rt_list_node *n; + struct rt_thread *sthread; + + /* find a suitable position */ + for (n = list->next; n != list; n = n->next) + { + sthread = rt_list_entry(n, struct rt_thread, tlist); + + /* find out */ + if (thread->current_priority < sthread->current_priority) + { + /* insert this thread before the sthread */ + rt_list_insert_before(&(sthread->tlist), &(thread->tlist)); + break; + } + } + + /* + * not found a suitable position, + * append to the end of suspend_thread list + */ + if (n == list) + rt_list_insert_before(list, &(thread->tlist)); + } + break;/* RT_IPC_FLAG_PRIO */ + + default: + RT_ASSERT(0); + break; + } + + return RT_EOK; +} + + +/** + * @brief This function will resume a thread. + * + * @note This function will resume the first thread in the list of a IPC object. + * 1. remove the thread from suspend queue of a IPC object. + * 2. put the thread into system ready queue. + * + * By contrast, the rt_ipc_list_resume_all() function will resume all suspended threads + * in the list of a IPC object. + * + * @param list is a pointer to a suspended thread list of the IPC object. + * + * @return Return the operation status. When the return value is RT_EOK, the function is successfully executed. + * When the return value is any other values, it means this operation failed. + * + * @warning This function is generally called by the following functions: + * rt_sem_release(), rt_mutex_release(), rt_mb_send_wait(), rt_mq_send_wait(), + * rt_mb_urgent(), rt_mb_recv(), rt_mq_urgent(), rt_mq_recv(), + */ +rt_inline rt_err_t _ipc_list_resume(rt_list_t *list) +{ + struct rt_thread *thread; + + /* get thread entry */ + thread = rt_list_entry(list->next, struct rt_thread, tlist); + + thread->error = RT_EOK; + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("resume thread:%s\n", thread->name)); + + /* resume it */ + rt_thread_resume(thread); + + return RT_EOK; +} + + +/** + * @brief This function will resume all suspended threads in the IPC object list, + * including the suspended list of IPC object, and private list of mailbox etc. + * + * @note This function will resume all threads in the IPC object list. + * By contrast, the rt_ipc_list_resume() function will resume a suspended thread in the list of a IPC object. + * + * @param list is a pointer to a suspended thread list of the IPC object. + * + * @return Return the operation status. When the return value is RT_EOK, the function is successfully executed. + * When the return value is any other values, it means this operation failed. + * + */ +rt_inline rt_err_t _ipc_list_resume_all(rt_list_t *list) +{ + struct rt_thread *thread; + rt_base_t level; + + /* wakeup all suspended threads */ + while (!rt_list_isempty(list)) + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* get next suspended thread */ + thread = rt_list_entry(list->next, struct rt_thread, tlist); + /* set error code to RT_ERROR */ + thread->error = -RT_ERROR; + + /* + * resume thread + * In rt_thread_resume function, it will remove current thread from + * suspended list + */ + rt_thread_resume(thread); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + } + + return RT_EOK; +} + +#ifdef RT_USING_SEMAPHORE +/** + * @addtogroup semaphore + * @{ + */ + +/** + * @brief This function will initialize a static semaphore object. + * + * @note For the static semaphore object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_sem_create() function will allocate memory space automatically and initialize + * the semaphore. + * + * @see rt_sem_create() + * + * @param sem is a pointer to the semaphore to initialize. It is assumed that storage for the semaphore will be + * allocated in your application. + * + * @param name is a pointer to the name you would like to give the semaphore. + * + * @param value is the initial value for the semaphore. + * If used to share resources, you should initialize the value as the number of available resources. + * If used to signal the occurrence of an event, you should initialize the value as 0. + * + * @param flag is the semaphore flag, which determines the queuing way of how multiple threads wait + * when the semaphore is not available. + * The semaphore flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this semaphore will become non-real-time threads. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_sem_init(rt_sem_t sem, + const char *name, + rt_uint32_t value, + rt_uint8_t flag) +{ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(value < 0x10000U); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(sem->parent.parent), RT_Object_Class_Semaphore, name); + + /* initialize ipc object */ + _ipc_object_init(&(sem->parent)); + + /* set initial value */ + sem->value = (rt_uint16_t)value; + + /* set parent */ + sem->parent.parent.flag = flag; + + return RT_EOK; +} +RTM_EXPORT(rt_sem_init); + + +/** + * @brief This function will detach a static semaphore object. + * + * @note This function is used to detach a static semaphore object which is initialized by rt_sem_init() function. + * By contrast, the rt_sem_delete() function will delete a semaphore object. + * When the semaphore is successfully detached, it will resume all suspended threads in the semaphore list. + * + * @see rt_sem_delete() + * + * @param sem is a pointer to a semaphore object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the semaphore detach failed. + * + * @warning This function can ONLY detach a static semaphore initialized by the rt_sem_init() function. + * If the semaphore is created by the rt_sem_create() function, you MUST NOT USE this function to detach it, + * ONLY USE the rt_sem_delete() function to complete the deletion. + */ +rt_err_t rt_sem_detach(rt_sem_t sem) +{ + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + RT_ASSERT(rt_object_is_systemobject(&sem->parent.parent)); + + /* wakeup all suspended threads */ + _ipc_list_resume_all(&(sem->parent.suspend_thread)); + + /* detach semaphore object */ + rt_object_detach(&(sem->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_sem_detach); + +#ifdef RT_USING_HEAP +/** + * @brief Creating a semaphore object. + * + * @note For the semaphore object, its memory space is allocated automatically. + * By contrast, the rt_sem_init() function will initialize a static semaphore object. + * + * @see rt_sem_init() + * + * @param name is a pointer to the name you would like to give the semaphore. + * + * @param value is the initial value for the semaphore. + * If used to share resources, you should initialize the value as the number of available resources. + * If used to signal the occurrence of an event, you should initialize the value as 0. + * + * @param flag is the semaphore flag, which determines the queuing way of how multiple threads wait + * when the semaphore is not available. + * The semaphore flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this semaphore will become non-real-time threads. + * + * @return Return a pointer to the semaphore object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can NOT be called in interrupt context. You can use macor RT_DEBUG_NOT_IN_INTERRUPT to check it. + */ +rt_sem_t rt_sem_create(const char *name, rt_uint32_t value, rt_uint8_t flag) +{ + rt_sem_t sem; + + RT_ASSERT(value < 0x10000U); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + sem = (rt_sem_t)rt_object_allocate(RT_Object_Class_Semaphore, name); + if (sem == RT_NULL) + return sem; + + /* initialize ipc object */ + _ipc_object_init(&(sem->parent)); + + /* set initial value */ + sem->value = value; + + /* set parent */ + sem->parent.parent.flag = flag; + + return sem; +} +RTM_EXPORT(rt_sem_create); + + +/** + * @brief This function will delete a semaphore object and release the memory space. + * + * @note This function is used to delete a semaphore object which is created by the rt_sem_create() function. + * By contrast, the rt_sem_detach() function will detach a static semaphore object. + * When the semaphore is successfully deleted, it will resume all suspended threads in the semaphore list. + * + * @see rt_sem_detach() + * + * @param sem is a pointer to a semaphore object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the semaphore detach failed. + * + * @warning This function can ONLY delete a semaphore initialized by the rt_sem_create() function. + * If the semaphore is initialized by the rt_sem_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_sem_detach() function to complete the detachment. + */ +rt_err_t rt_sem_delete(rt_sem_t sem) +{ + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + RT_ASSERT(rt_object_is_systemobject(&sem->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* wakeup all suspended threads */ + _ipc_list_resume_all(&(sem->parent.suspend_thread)); + + /* delete semaphore object */ + rt_object_delete(&(sem->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_sem_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will take a semaphore, if the semaphore is unavailable, the thread shall wait for + * the semaphore up to a specified time. + * + * @note When this function is called, the count value of the sem->value will decrease 1 until it is equal to 0. + * When the sem->value is 0, it means that the semaphore is unavailable. At this time, it will suspend the + * thread preparing to take the semaphore. + * On the contrary, the rt_sem_release() function will increase the count value of sem->value by 1 each time. + * + * @see rt_sem_trytake() + * + * @param sem is a pointer to a semaphore object. + * + * @param timeout is a timeout period (unit: an OS tick). If the semaphore is unavailable, the thread will wait for + * the semaphore up to the amount of time specified by this parameter. + * + * NOTE: + * If use Macro RT_WAITING_FOREVER to set this parameter, which means that when the + * message is unavailable in the queue, the thread will be waiting forever. + * If use macro RT_WAITING_NO to set this parameter, which means that this + * function is non-blocking and will return immediately. + * + * @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 semaphore take failed. + * + * @warning This function can ONLY be called in the thread context. It MUST NOT BE called in interrupt context. + */ +static rt_err_t _rt_sem_take(rt_sem_t sem, rt_int32_t timeout, int suspend_flag) +{ + rt_base_t level; + struct rt_thread *thread; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(sem->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("thread %s take sem:%s, which value is: %d\n", + rt_thread_self()->name, + ((struct rt_object *)sem)->name, + sem->value)); + + if (sem->value > 0) + { + /* semaphore is available */ + sem->value --; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + } + else + { + /* no waiting, return with timeout */ + if (timeout == 0) + { + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + else + { + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE); + + /* semaphore is unavailable, push to suspend list */ + /* get current thread */ + thread = rt_thread_self(); + + /* reset thread error number */ + thread->error = -RT_EINTR; + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("sem take: suspend thread - %s\n", + thread->name)); + + /* suspend thread */ + ret = _ipc_list_suspend(&(sem->parent.suspend_thread), + thread, + sem->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + RT_DEBUG_LOG(RT_DEBUG_IPC, ("set thread:%s to timer list\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do schedule */ + rt_schedule(); + + if (thread->error != RT_EOK) + { + return thread->error; + } + } + } + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(sem->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_sem_take(rt_sem_t sem, rt_int32_t time) +{ + return _rt_sem_take(sem, time, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_sem_take); + +rt_err_t rt_sem_take_interruptible(rt_sem_t sem, rt_int32_t time) +{ + return _rt_sem_take(sem, time, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_sem_take_interruptible); + +rt_err_t rt_sem_take_killable(rt_sem_t sem, rt_int32_t time) +{ + return _rt_sem_take(sem, time, RT_KILLABLE); +} +RTM_EXPORT(rt_sem_take_killable); + +/** + * @brief This function will try to take a semaphore, if the semaphore is unavailable, the thread returns immediately. + * + * @note This function is very similar to the rt_sem_take() function, when the semaphore is not available, + * the rt_sem_trytake() function will return immediately without waiting for a timeout. + * In other words, rt_sem_trytake(sem) has the same effect as rt_sem_take(sem, 0). + * + * @see rt_sem_take() + * + * @param sem is a pointer to a semaphore object. + * + * @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 semaphore take failed. + */ +rt_err_t rt_sem_trytake(rt_sem_t sem) +{ + return rt_sem_take(sem, RT_WAITING_NO); +} +RTM_EXPORT(rt_sem_trytake); + + +/** + * @brief This function will release a semaphore. If there is thread suspended on the semaphore, it will get resumed. + * + * @note If there are threads suspended on this semaphore, the first thread in the list of this semaphore object + * will be resumed, and a thread scheduling (rt_schedule) will be executed. + * If no threads are suspended on this semaphore, the count value sem->value of this semaphore will increase by 1. + * + * @param sem is a pointer to a semaphore object. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the semaphore release failed. + */ +rt_err_t rt_sem_release(rt_sem_t sem) +{ + rt_base_t level; + rt_bool_t need_schedule; + + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(sem->parent.parent))); + + need_schedule = RT_FALSE; + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("thread %s releases sem:%s, which value is: %d\n", + rt_thread_self()->name, + ((struct rt_object *)sem)->name, + sem->value)); + + if (!rt_list_isempty(&sem->parent.suspend_thread)) + { + /* resume the suspended thread */ + _ipc_list_resume(&(sem->parent.suspend_thread)); + need_schedule = RT_TRUE; + } + else + { + if(sem->value < RT_SEM_VALUE_MAX) + { + sem->value ++; /* increase value */ + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* resume a thread, re-schedule */ + if (need_schedule == RT_TRUE) + rt_schedule(); + + return RT_EOK; +} +RTM_EXPORT(rt_sem_release); + + +/** + * @brief This function will set some extra attributions of a semaphore object. + * + * @note Currently this function only supports the RT_IPC_CMD_RESET command to reset the semaphore. + * + * @param sem is a pointer to a semaphore object. + * + * @param cmd is a command word used to configure some attributions of the semaphore. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_sem_control(rt_sem_t sem, int cmd, void *arg) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + + if (cmd == RT_IPC_CMD_RESET) + { + rt_ubase_t value; + + /* get value */ + value = (rt_ubase_t)arg; + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* resume all waiting thread */ + _ipc_list_resume_all(&sem->parent.suspend_thread); + + /* set new value */ + sem->value = (rt_uint16_t)value; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_sem_control); + +/**@}*/ +#endif /* RT_USING_SEMAPHORE */ + +#ifdef RT_USING_MUTEX +rt_inline rt_uint8_t _mutex_update_priority(struct rt_mutex *mutex) +{ + struct rt_thread *thread; + + if (!rt_list_isempty(&mutex->parent.suspend_thread)) + { + thread = rt_list_entry(mutex->parent.suspend_thread.next, struct rt_thread, tlist); + mutex->priority = thread->current_priority; + } + else + { + mutex->priority = 0xff; + } + + return mutex->priority; +} + +rt_inline rt_uint8_t _thread_get_mutex_priority(struct rt_thread* thread) +{ + rt_list_t *node = RT_NULL; + struct rt_mutex *mutex = RT_NULL; + rt_uint8_t priority = thread->init_priority; + + rt_list_for_each(node, &(thread->taken_object_list)) + { + mutex = rt_list_entry(node, struct rt_mutex, taken_list); + if (priority > mutex->priority) + { + priority = mutex->priority; + } + } + + return priority; +} + +rt_inline void _thread_update_priority(struct rt_thread *thread, rt_uint8_t priority, int suspend_flag) +{ + rt_err_t ret; + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("thread:%s priority -> %d\n", thread->name, priority)); + + /* change priority of the thread */ + rt_thread_control(thread, + RT_THREAD_CTRL_CHANGE_PRIORITY, + &priority); + + if ((thread->stat & RT_THREAD_SUSPEND_MASK) == RT_THREAD_SUSPEND_MASK) + { + /* whether change the priority of taken mutex */ + struct rt_object* pending_obj = thread->pending_object; + + if (pending_obj && rt_object_get_type(pending_obj) == RT_Object_Class_Mutex) + { + rt_uint8_t mutex_priority; + struct rt_mutex* pending_mutex = (struct rt_mutex *)pending_obj; + + /* re-insert thread to suspended thread list */ + rt_list_remove(&(thread->tlist)); + + ret = _ipc_list_suspend(&(pending_mutex->parent.suspend_thread), + thread, + pending_mutex->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + /* TODO */ + return ; + } + + /* update priority */ + _mutex_update_priority(pending_mutex); + /* change the priority of mutex owner thread */ + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("mutex: %s priority -> %d\n", pending_mutex->parent.parent.name, + pending_mutex->priority)); + + mutex_priority = _thread_get_mutex_priority(pending_mutex->owner); + if (mutex_priority != pending_mutex->owner->current_priority) + { + _thread_update_priority(pending_mutex->owner, mutex_priority, suspend_flag); + } + } + } +} + +/** + * @addtogroup mutex + * @{ + */ + +/** + * @brief Initialize a static mutex object. + * + * @note For the static mutex object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_mutex_create() function will automatically allocate memory space + * and initialize the mutex. + * + * @see rt_mutex_create() + * + * @param mutex is a pointer to the mutex to initialize. It is assumed that storage for the mutex will be + * allocated in your application. + * + * @param name is a pointer to the name that given to the mutex. + * + * @param flag is the mutex flag, which determines the queuing way of how multiple threads wait + * when the mutex is not available. + * NOTE: This parameter has been obsoleted. It can be RT_IPC_FLAG_PRIO, RT_IPC_FLAG_FIFO or RT_NULL. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_mutex_init(rt_mutex_t mutex, const char *name, rt_uint8_t flag) +{ + /* flag parameter has been obsoleted */ + RT_UNUSED(flag); + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + + /* initialize object */ + rt_object_init(&(mutex->parent.parent), RT_Object_Class_Mutex, name); + + /* initialize ipc object */ + _ipc_object_init(&(mutex->parent)); + + mutex->owner = RT_NULL; + mutex->priority = 0xFF; + mutex->hold = 0; + mutex->ceiling_priority = 0xFF; + rt_list_init(&(mutex->taken_list)); + + /* flag can only be RT_IPC_FLAG_PRIO. RT_IPC_FLAG_FIFO cannot solve the unbounded priority inversion problem */ + mutex->parent.parent.flag = RT_IPC_FLAG_PRIO; + + return RT_EOK; +} +RTM_EXPORT(rt_mutex_init); + + +/** + * @brief This function will detach a static mutex object. + * + * @note This function is used to detach a static mutex object which is initialized by rt_mutex_init() function. + * By contrast, the rt_mutex_delete() function will delete a mutex object. + * When the mutex is successfully detached, it will resume all suspended threads in the mutex list. + * + * @see rt_mutex_delete() + * + * @param mutex is a pointer to a mutex object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the mutex detach failed. + * + * @warning This function can ONLY detach a static mutex initialized by the rt_mutex_init() function. + * If the mutex is created by the rt_mutex_create() function, you MUST NOT USE this function to detach it, + * ONLY USE the rt_mutex_delete() function to complete the deletion. + */ +rt_err_t rt_mutex_detach(rt_mutex_t mutex) +{ + rt_ubase_t level; + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + RT_ASSERT(rt_object_is_systemobject(&mutex->parent.parent)); + + level = rt_hw_interrupt_disable(); + /* wakeup all suspended threads */ + _ipc_list_resume_all(&(mutex->parent.suspend_thread)); + /* remove mutex from thread's taken list */ + rt_list_remove(&mutex->taken_list); + rt_hw_interrupt_enable(level); + + /* detach mutex object */ + rt_object_detach(&(mutex->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mutex_detach); + +/* drop a thread from the suspend list of mutex */ + +/** + * @brief drop a thread from the suspend list of mutex + * + * @param mutex is a pointer to a mutex object. + * @param thread is the thread should be dropped from mutex. + */ +void rt_mutex_drop_thread(rt_mutex_t mutex, rt_thread_t thread) +{ + rt_uint8_t priority; + rt_bool_t need_update = RT_FALSE; + + rt_list_remove(&(thread->tlist)); + + /* should change the priority of mutex owner thread */ + if (mutex->owner->current_priority == thread->current_priority) + need_update = RT_TRUE; + + /* update the priority of mutex */ + if (!rt_list_isempty(&mutex->parent.suspend_thread)) + { + /* more thread suspended in the list */ + struct rt_thread *th; + + th = rt_list_entry(mutex->parent.suspend_thread.next, + struct rt_thread, + tlist); + /* update the priority of mutex */ + mutex->priority = th->current_priority; + } + else + { + /* set mutex priority to maximal priority */ + mutex->priority = 0xff; + } + + /* try to change the priority of mutex owner thread */ + if (need_update) + { + /* get the maximal priority of mutex in thread */ + priority = _thread_get_mutex_priority(mutex->owner); + if (priority != mutex->owner->current_priority) + { + _thread_update_priority(mutex->owner, priority, RT_UNINTERRUPTIBLE); + } + } +} + + +/** + * @brief set the prioceiling attribute of the mutex. + * + * @param mutex is a pointer to a mutex object. + * @param priority is the priority should be set to mutex. + * + * @return return the old priority ceiling + */ +rt_uint8_t rt_mutex_setprioceiling(rt_mutex_t mutex, rt_uint8_t priority) +{ + rt_uint8_t ret_priority = 0xFF; + + if ((mutex) && (priority < RT_THREAD_PRIORITY_MAX)) + { + ret_priority = mutex->ceiling_priority; + mutex->ceiling_priority = priority; + if(mutex->owner) mutex->owner->current_priority=priority; + } + else + { + rt_set_errno(-RT_EINVAL); + } + + return ret_priority; +} +RTM_EXPORT(rt_mutex_setprioceiling); + + +/** + * @brief set the prioceiling attribute of the mutex. + * + * @param mutex is a pointer to a mutex object. + * + * @return return the current priority ceiling of the mutex. + */ +rt_uint8_t rt_mutex_getprioceiling(rt_mutex_t mutex) +{ + rt_uint8_t prio = 0xFF; + + if (mutex) + { + prio = mutex->ceiling_priority; + } + + return prio; +} +RTM_EXPORT(rt_mutex_getprioceiling); + + +#ifdef RT_USING_HEAP +/** + * @brief This function will create a mutex object. + * + * @note For the mutex object, its memory space is automatically allocated. + * By contrast, the rt_mutex_init() function will initialize a static mutex object. + * + * @see rt_mutex_init() + * + * @param name is a pointer to the name that given to the mutex. + * + * @param flag is the mutex flag, which determines the queuing way of how multiple threads wait + * when the mutex is not available. + * NOTE: This parameter has been obsoleted. It can be RT_IPC_FLAG_PRIO, RT_IPC_FLAG_FIFO or RT_NULL. + * + * @return Return a pointer to the mutex object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_mutex_t rt_mutex_create(const char *name, rt_uint8_t flag) +{ + struct rt_mutex *mutex; + + /* flag parameter has been obsoleted */ + RT_UNUSED(flag); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + mutex = (rt_mutex_t)rt_object_allocate(RT_Object_Class_Mutex, name); + if (mutex == RT_NULL) + return mutex; + + /* initialize ipc object */ + _ipc_object_init(&(mutex->parent)); + + mutex->owner = RT_NULL; + mutex->priority = 0xFF; + mutex->hold = 0; + mutex->ceiling_priority = 0xFF; + rt_list_init(&(mutex->taken_list)); + + /* flag can only be RT_IPC_FLAG_PRIO. RT_IPC_FLAG_FIFO cannot solve the unbounded priority inversion problem */ + mutex->parent.parent.flag = RT_IPC_FLAG_PRIO; + + return mutex; +} +RTM_EXPORT(rt_mutex_create); + + +/** + * @brief This function will delete a mutex object and release this memory space. + * + * @note This function is used to delete a mutex object which is created by the rt_mutex_create() function. + * By contrast, the rt_mutex_detach() function will detach a static mutex object. + * When the mutex is successfully deleted, it will resume all suspended threads in the mutex list. + * + * @see rt_mutex_detach() + * + * @param mutex is a pointer to a mutex object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mutex detach failed. + * + * @warning This function can ONLY delete a mutex initialized by the rt_mutex_create() function. + * If the mutex is initialized by the rt_mutex_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_mutex_detach() function to complete the detachment. + */ +rt_err_t rt_mutex_delete(rt_mutex_t mutex) +{ + rt_ubase_t level; + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + RT_ASSERT(rt_object_is_systemobject(&mutex->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + level = rt_hw_interrupt_disable(); + /* wakeup all suspended threads */ + _ipc_list_resume_all(&(mutex->parent.suspend_thread)); + /* remove mutex from thread's taken list */ + rt_list_remove(&mutex->taken_list); + rt_hw_interrupt_enable(level); + + /* delete mutex object */ + rt_object_delete(&(mutex->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mutex_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will take a mutex, if the mutex is unavailable, the thread shall wait for + * the mutex up to a specified time. + * + * @note When this function is called, the count value of the mutex->value will decrease 1 until it is equal to 0. + * When the mutex->value is 0, it means that the mutex is unavailable. At this time, it will suspend the + * thread preparing to take the mutex. + * On the contrary, the rt_mutex_release() function will increase the count value of mutex->value by 1 each time. + * + * @see rt_mutex_trytake() + * + * @param mutex is a pointer to a mutex object. + * + * @param timeout is a timeout period (unit: an OS tick). If the mutex is unavailable, the thread will wait for + * the mutex up to the amount of time specified by the argument. + * NOTE: Generally, we set this parameter to RT_WAITING_FOREVER, which means that when the mutex is unavailable, + * the thread will be waitting forever. + * + * @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 mutex take failed. + * + * @warning This function can ONLY be called in the thread context. It MUST NOT BE called in interrupt context. + */ +static rt_err_t _rt_mutex_take(rt_mutex_t mutex, rt_int32_t timeout, int suspend_flag) +{ + rt_base_t level; + struct rt_thread *thread; + rt_err_t ret; + + /* this function must not be used in interrupt even if time = 0 */ + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE); + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + + /* get current thread */ + thread = rt_thread_self(); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(mutex->parent.parent))); + + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("mutex_take: current thread %s, hold: %d\n", + thread->name, mutex->hold)); + + /* reset thread error */ + thread->error = RT_EOK; + + if (mutex->owner == thread) + { + if(mutex->hold < RT_MUTEX_HOLD_MAX) + { + /* it's the same thread */ + mutex->hold ++; + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + } + else + { + /* whether the mutex has owner thread. */ + if (mutex->owner == RT_NULL) + { + /* set mutex owner and original priority */ + mutex->owner = thread; + mutex->priority = 0xff; + mutex->hold = 1; + + if (mutex->ceiling_priority != 0xFF) + { + /* set the priority of thread to the ceiling priority */ + if (mutex->ceiling_priority < mutex->owner->current_priority) + _thread_update_priority(mutex->owner, mutex->ceiling_priority, suspend_flag); + } + else + { + /* insert mutex to thread's taken object list */ + rt_list_insert_after(&thread->taken_object_list, &mutex->taken_list); + } + } + else + { + /* no waiting, return with timeout */ + if (timeout == 0) + { + /* set error as timeout */ + thread->error = -RT_ETIMEOUT; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + else + { + rt_uint8_t priority = thread->current_priority; + + /* mutex is unavailable, push to suspend list */ + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mutex_take: suspend thread: %s\n", + thread->name)); + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mutex->parent.suspend_thread), + thread, + mutex->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* set pending object in thread to this mutex */ + thread->pending_object = &(mutex->parent.parent); + + /* update the priority level of mutex */ + if (priority < mutex->priority) + { + mutex->priority = priority; + if (mutex->priority < mutex->owner->current_priority) + { + _thread_update_priority(mutex->owner, priority, RT_UNINTERRUPTIBLE); /* TODO */ + } + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("mutex_take: start the timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do schedule */ + rt_schedule(); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + if (thread->error == RT_EOK) + { + /* get mutex successfully */ + } + else + { + /* the mutex has not been taken and thread has detach from the pending list. */ + + rt_bool_t need_update = RT_FALSE; + + /* should change the priority of mutex owner thread */ + if (mutex->owner->current_priority == thread->current_priority) + need_update = RT_TRUE; + + /* update the priority of mutex */ + if (!rt_list_isempty(&mutex->parent.suspend_thread)) + { + /* more thread suspended in the list */ + struct rt_thread *th; + + th = rt_list_entry(mutex->parent.suspend_thread.next, + struct rt_thread, + tlist); + /* update the priority of mutex */ + mutex->priority = th->current_priority; + } + else + { + /* set mutex priority to maximal priority */ + mutex->priority = 0xff; + } + + /* try to change the priority of mutex owner thread */ + if (need_update) + { + /* get the maximal priority of mutex in thread */ + priority = _thread_get_mutex_priority(mutex->owner); + if (priority != mutex->owner->current_priority) + { + _thread_update_priority(mutex->owner, priority, RT_UNINTERRUPTIBLE); + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* return error */ + return thread->error; + } + } + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mutex->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_mutex_take(rt_mutex_t mutex, rt_int32_t time) +{ + return _rt_mutex_take(mutex, time, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mutex_take); + +rt_err_t rt_mutex_take_interruptible(rt_mutex_t mutex, rt_int32_t time) +{ + return _rt_mutex_take(mutex, time, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mutex_take_interruptible); + +rt_err_t rt_mutex_take_killable(rt_mutex_t mutex, rt_int32_t time) +{ + return _rt_mutex_take(mutex, time, RT_KILLABLE); +} +RTM_EXPORT(rt_mutex_take_killable); + +/** + * @brief This function will try to take a mutex, if the mutex is unavailable, the thread returns immediately. + * + * @note This function is very similar to the rt_mutex_take() function, when the mutex is not available, + * except that rt_mutex_trytake() will return immediately without waiting for a timeout + * when the mutex is not available. + * In other words, rt_mutex_trytake(mutex) has the same effect as rt_mutex_take(mutex, 0). + * + * @see rt_mutex_take() + * + * @param mutex is a pointer to a mutex object. + * + * @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 mutex take failed. + */ +rt_err_t rt_mutex_trytake(rt_mutex_t mutex) +{ + return rt_mutex_take(mutex, RT_WAITING_NO); +} +RTM_EXPORT(rt_mutex_trytake); + + +/** + * @brief This function will release a mutex. If there is thread suspended on the mutex, the thread will be resumed. + * + * @note If there are threads suspended on this mutex, the first thread in the list of this mutex object + * will be resumed, and a thread scheduling (rt_schedule) will be executed. + * If no threads are suspended on this mutex, the count value mutex->value of this mutex will increase by 1. + * + * @param mutex is a pointer to a mutex object. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mutex release failed. + */ +rt_err_t rt_mutex_release(rt_mutex_t mutex) +{ + rt_base_t level; + struct rt_thread *thread; + rt_bool_t need_schedule; + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + + need_schedule = RT_FALSE; + + /* only thread could release mutex because we need test the ownership */ + RT_DEBUG_IN_THREAD_CONTEXT; + + /* get current thread */ + thread = rt_thread_self(); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("mutex_release:current thread %s, hold: %d\n", + thread->name, mutex->hold)); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mutex->parent.parent))); + + /* mutex only can be released by owner */ + if (thread != mutex->owner) + { + thread->error = -RT_ERROR; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_ERROR; + } + + /* decrease hold */ + mutex->hold --; + /* if no hold */ + if (mutex->hold == 0) + { + /* remove mutex from thread's taken list */ + rt_list_remove(&mutex->taken_list); + + /* whether change the thread priority */ + if ((mutex->ceiling_priority != 0xFF) || (thread->current_priority == mutex->priority)) + { + rt_uint8_t priority = 0xff; + + /* get the highest priority in the taken list of thread */ + priority = _thread_get_mutex_priority(thread); + + rt_thread_control(thread, + RT_THREAD_CTRL_CHANGE_PRIORITY, + &priority); + + need_schedule = RT_TRUE; + } + + /* wakeup suspended thread */ + if (!rt_list_isempty(&mutex->parent.suspend_thread)) + { + /* get the first suspended thread */ + struct rt_thread *next_thread = rt_list_entry(mutex->parent.suspend_thread.next, + struct rt_thread, + tlist); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mutex_release: resume thread: %s\n", + next_thread->name)); + + /* remove the thread from the suspended list of mutex */ + rt_list_remove(&(next_thread->tlist)); + + /* set new owner and put mutex into taken list of thread */ + mutex->owner = next_thread; + mutex->hold = 1; + rt_list_insert_after(&next_thread->taken_object_list, &mutex->taken_list); + /* cleanup pending object */ + next_thread->pending_object = RT_NULL; + + /* resume thread */ + rt_thread_resume(next_thread); + + /* update mutex priority */ + if (!rt_list_isempty(&(mutex->parent.suspend_thread))) + { + struct rt_thread *th; + + th = rt_list_entry(mutex->parent.suspend_thread.next, + struct rt_thread, + tlist); + mutex->priority = th->current_priority; + } + else + { + mutex->priority = 0xff; + } + + need_schedule = RT_TRUE; + } + else + { + /* clear owner */ + mutex->owner = RT_NULL; + mutex->priority = 0xff; + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* perform a schedule */ + if (need_schedule == RT_TRUE) + rt_schedule(); + + return RT_EOK; +} +RTM_EXPORT(rt_mutex_release); + + +/** + * @brief This function will set some extra attributions of a mutex object. + * + * @note Currently this function does not implement the control function. + * + * @param mutex is a pointer to a mutex object. + * + * @param cmd is a command word used to configure some attributions of the mutex. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_mutex_control(rt_mutex_t mutex, int cmd, void *arg) +{ + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + + return -RT_ERROR; +} +RTM_EXPORT(rt_mutex_control); + +/**@}*/ +#endif /* RT_USING_MUTEX */ + +#ifdef RT_USING_EVENT +/** + * @addtogroup event + * @{ + */ + +/** + * @brief The function will initialize a static event object. + * + * @note For the static event object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_event_create() function will allocate memory space automatically + * and initialize the event. + * + * @see rt_event_create() + * + * @param event is a pointer to the event to initialize. It is assumed that storage for the event + * will be allocated in your application. + * + * @param name is a pointer to the name that given to the event. + * + * @param flag is the event flag, which determines the queuing way of how multiple threads wait + * when the event is not available. + * The event flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this event will become non-real-time threads. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_event_init(rt_event_t event, const char *name, rt_uint8_t flag) +{ + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(event->parent.parent), RT_Object_Class_Event, name); + + /* set parent flag */ + event->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(event->parent)); + + /* initialize event */ + event->set = 0; + + return RT_EOK; +} +RTM_EXPORT(rt_event_init); + + +/** + * @brief This function will detach a static event object. + * + * @note This function is used to detach a static event object which is initialized by rt_event_init() function. + * By contrast, the rt_event_delete() function will delete an event object. + * When the event is successfully detached, it will resume all suspended threads in the event list. + * + * @see rt_event_delete() + * + * @param event is a pointer to an event object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the event detach failed. + * + * @warning This function can ONLY detach a static event initialized by the rt_event_init() function. + * If the event is created by the rt_event_create() function, you MUST NOT USE this function to detach it, + * ONLY USE the rt_event_delete() function to complete the deletion. + */ +rt_err_t rt_event_detach(rt_event_t event) +{ + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + RT_ASSERT(rt_object_is_systemobject(&event->parent.parent)); + + /* resume all suspended thread */ + _ipc_list_resume_all(&(event->parent.suspend_thread)); + + /* detach event object */ + rt_object_detach(&(event->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_event_detach); + +#ifdef RT_USING_HEAP +/** + * @brief Creating an event object. + * + * @note For the event object, its memory space is allocated automatically. + * By contrast, the rt_event_init() function will initialize a static event object. + * + * @see rt_event_init() + * + * @param name is a pointer to the name that given to the event. + * + * @param flag is the event flag, which determines the queuing way of how multiple threads wait when the event + * is not available. + * The event flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this event will become non-real-time threads. + * + * @return Return a pointer to the event object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_event_t rt_event_create(const char *name, rt_uint8_t flag) +{ + rt_event_t event; + + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + event = (rt_event_t)rt_object_allocate(RT_Object_Class_Event, name); + if (event == RT_NULL) + return event; + + /* set parent */ + event->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(event->parent)); + + /* initialize event */ + event->set = 0; + + return event; +} +RTM_EXPORT(rt_event_create); + + +/** + * @brief This function will delete an event object and release the memory space. + * + * @note This function is used to delete an event object which is created by the rt_event_create() function. + * By contrast, the rt_event_detach() function will detach a static event object. + * When the event is successfully deleted, it will resume all suspended threads in the event list. + * + * @see rt_event_detach() + * + * @param event is a pointer to an event object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the event detach failed. + * + * @warning This function can ONLY delete an event initialized by the rt_event_create() function. + * If the event is initialized by the rt_event_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_event_detach() function to complete the detachment. + */ +rt_err_t rt_event_delete(rt_event_t event) +{ + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + RT_ASSERT(rt_object_is_systemobject(&event->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* resume all suspended thread */ + _ipc_list_resume_all(&(event->parent.suspend_thread)); + + /* delete event object */ + rt_object_delete(&(event->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_event_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will send an event to the event object. + * If there is a thread suspended on the event, the thread will be resumed. + * + * @note When using this function, you need to use the parameter (set) to specify the event flag of the event object, + * then the function will traverse the list of suspended threads waiting on the event object. + * If there is a thread suspended on the event, and the thread's event_info and the event flag of + * the current event object matches, the thread will be resumed. + * + * @param event is a pointer to the event object to be sent. + * + * @param set is a flag that you will set for this event's flag. + * You can set an event flag, or you can set multiple flags through OR logic operation. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the event detach failed. + */ +rt_err_t rt_event_send(rt_event_t event, rt_uint32_t set) +{ + struct rt_list_node *n; + struct rt_thread *thread; + rt_base_t level; + rt_base_t status; + rt_bool_t need_schedule; + + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + + if (set == 0) + return -RT_ERROR; + + need_schedule = RT_FALSE; + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* set event */ + event->set |= set; + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(event->parent.parent))); + + if (!rt_list_isempty(&event->parent.suspend_thread)) + { + /* search thread list to resume thread */ + n = event->parent.suspend_thread.next; + while (n != &(event->parent.suspend_thread)) + { + /* get thread */ + thread = rt_list_entry(n, struct rt_thread, tlist); + + status = -RT_ERROR; + if (thread->event_info & RT_EVENT_FLAG_AND) + { + if ((thread->event_set & event->set) == thread->event_set) + { + /* received an AND event */ + status = RT_EOK; + } + } + else if (thread->event_info & RT_EVENT_FLAG_OR) + { + if (thread->event_set & event->set) + { + /* save the received event set */ + thread->event_set = thread->event_set & event->set; + + /* received an OR event */ + status = RT_EOK; + } + } + else + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EINVAL; + } + + /* move node to the next */ + n = n->next; + + /* condition is satisfied, resume thread */ + if (status == RT_EOK) + { + /* clear event */ + if (thread->event_info & RT_EVENT_FLAG_CLEAR) + event->set &= ~thread->event_set; + + /* resume thread, and thread list breaks out */ + rt_thread_resume(thread); + thread->error = RT_EOK; + + /* need do a scheduling */ + need_schedule = RT_TRUE; + } + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do a schedule */ + if (need_schedule == RT_TRUE) + rt_schedule(); + + return RT_EOK; +} +RTM_EXPORT(rt_event_send); + + +/** + * @brief This function will receive an event from event object. if the event is unavailable, the thread shall wait for + * the event up to a specified time. + * + * @note If there are threads suspended on this semaphore, the first thread in the list of this semaphore object + * will be resumed, and a thread scheduling (rt_schedule) will be executed. + * If no threads are suspended on this semaphore, the count value sem->value of this semaphore will increase by 1. + * + * @param event is a pointer to the event object to be received. + * + * @param set is a flag that you will set for this event's flag. + * You can set an event flag, or you can set multiple flags through OR logic operation. + * + * @param option is the option of this receiving event, it indicates how the receiving event is operated. + * The option can be one or more of the following values, When selecting multiple values,use logical OR to operate. + * (NOTE: RT_EVENT_FLAG_OR and RT_EVENT_FLAG_AND can only select one): + * + * + * RT_EVENT_FLAG_OR The thread select to use logical OR to receive the event. + * + * RT_EVENT_FLAG_AND The thread select to use logical OR to receive the event. + * + * RT_EVENT_FLAG_CLEAR When the thread receives the corresponding event, the function + * determines whether to clear the event flag. + * + * @param timeout is a timeout period (unit: an OS tick). + * + * @param recved is a pointer to the received event. If you don't care about this value, you can use RT_NULL to set. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the semaphore release failed. + */ +static rt_err_t _rt_event_recv(rt_event_t event, + rt_uint32_t set, + rt_uint8_t option, + rt_int32_t timeout, + rt_uint32_t *recved, + int suspend_flag) +{ + struct rt_thread *thread; + rt_base_t level; + rt_base_t status; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE); + + if (set == 0) + return -RT_ERROR; + + /* initialize status */ + status = -RT_ERROR; + /* get current thread */ + thread = rt_thread_self(); + /* reset thread error */ + thread->error = -RT_EINTR; + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(event->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* check event set */ + if (option & RT_EVENT_FLAG_AND) + { + if ((event->set & set) == set) + status = RT_EOK; + } + else if (option & RT_EVENT_FLAG_OR) + { + if (event->set & set) + status = RT_EOK; + } + else + { + /* either RT_EVENT_FLAG_AND or RT_EVENT_FLAG_OR should be set */ + RT_ASSERT(0); + } + + if (status == RT_EOK) + { + thread->error = RT_EOK; + + /* set received event */ + if (recved) + *recved = (event->set & set); + + /* fill thread event info */ + thread->event_set = (event->set & set); + thread->event_info = option; + + /* received event */ + if (option & RT_EVENT_FLAG_CLEAR) + event->set &= ~set; + } + else if (timeout == 0) + { + /* no waiting */ + thread->error = -RT_ETIMEOUT; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + else + { + /* fill thread event info */ + thread->event_set = set; + thread->event_info = option; + + /* put thread to suspended thread list */ + ret = _ipc_list_suspend(&(event->parent.suspend_thread), + thread, + event->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* if there is a waiting timeout, active thread timer */ + if (timeout > 0) + { + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do a schedule */ + rt_schedule(); + + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* received an event, disable interrupt to protect */ + level = rt_hw_interrupt_disable(); + + /* set received event */ + if (recved) + *recved = thread->event_set; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(event->parent.parent))); + + return thread->error; +} + +rt_err_t rt_event_recv(rt_event_t event, + rt_uint32_t set, + rt_uint8_t option, + rt_int32_t timeout, + rt_uint32_t *recved) +{ + return _rt_event_recv(event, set, option, timeout, recved, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_event_recv); + +rt_err_t rt_event_recv_interruptible(rt_event_t event, + rt_uint32_t set, + rt_uint8_t option, + rt_int32_t timeout, + rt_uint32_t *recved) +{ + return _rt_event_recv(event, set, option, timeout, recved, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_event_recv_interruptible); + +rt_err_t rt_event_recv_killable(rt_event_t event, + rt_uint32_t set, + rt_uint8_t option, + rt_int32_t timeout, + rt_uint32_t *recved) +{ + return _rt_event_recv(event, set, option, timeout, recved, RT_KILLABLE); +} +RTM_EXPORT(rt_event_recv_killable); +/** + * @brief This function will set some extra attributions of an event object. + * + * @note Currently this function only supports the RT_IPC_CMD_RESET command to reset the event. + * + * @param event is a pointer to an event object. + * + * @param cmd is a command word used to configure some attributions of the event. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_event_control(rt_event_t event, int cmd, void *arg) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + + if (cmd == RT_IPC_CMD_RESET) + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* resume all waiting thread */ + _ipc_list_resume_all(&event->parent.suspend_thread); + + /* initialize event set */ + event->set = 0; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_event_control); + +/**@}*/ +#endif /* RT_USING_EVENT */ + +#ifdef RT_USING_MAILBOX +/** + * @addtogroup mailbox + * @{ + */ + +/** + * @brief Initialize a static mailbox object. + * + * @note For the static mailbox object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_mb_create() function will allocate memory space automatically and initialize the mailbox. + * + * @see rt_mb_create() + * + * @param mb is a pointer to the mailbox to initialize. + * It is assumed that storage for the mailbox will be allocated in your application. + * + * @param name is a pointer to the name that given to the mailbox. + * + * @param msgpool the begin address of buffer to save received mail. + * + * @param size is the maximum number of mails in the mailbox. + * For example, when the mailbox buffer capacity is N, size is N/4. + * + * @param flag is the mailbox flag, which determines the queuing way of how multiple threads wait + * when the mailbox is not available. + * The mailbox flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this mailbox will become non-real-time threads. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_mb_init(rt_mailbox_t mb, + const char *name, + void *msgpool, + rt_size_t size, + rt_uint8_t flag) +{ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(mb->parent.parent), RT_Object_Class_MailBox, name); + + /* set parent flag */ + mb->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(mb->parent)); + + /* initialize mailbox */ + mb->msg_pool = (rt_ubase_t *)msgpool; + mb->size = (rt_uint16_t)size; + mb->entry = 0; + mb->in_offset = 0; + mb->out_offset = 0; + + /* initialize an additional list of sender suspend thread */ + rt_list_init(&(mb->suspend_sender_thread)); + + return RT_EOK; +} +RTM_EXPORT(rt_mb_init); + + +/** + * @brief This function will detach a static mailbox object. + * + * @note This function is used to detach a static mailbox object which is initialized by rt_mb_init() function. + * By contrast, the rt_mb_delete() function will delete a mailbox object. + * When the mailbox is successfully detached, it will resume all suspended threads in the mailbox list. + * + * @see rt_mb_delete() + * + * @param mb is a pointer to a mailbox object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the mailbox detach failed. + * + * @warning This function can ONLY detach a static mailbox initialized by the rt_mb_init() function. + * If the mailbox is created by the rt_mb_create() function, you MUST NOT USE this function to detach it, + * ONLY USE the rt_mb_delete() function to complete the deletion. + */ +rt_err_t rt_mb_detach(rt_mailbox_t mb) +{ + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + RT_ASSERT(rt_object_is_systemobject(&mb->parent.parent)); + + /* resume all suspended thread */ + _ipc_list_resume_all(&(mb->parent.suspend_thread)); + /* also resume all mailbox private suspended thread */ + _ipc_list_resume_all(&(mb->suspend_sender_thread)); + + /* detach mailbox object */ + rt_object_detach(&(mb->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mb_detach); + +#ifdef RT_USING_HEAP +/** + * @brief Creating a mailbox object. + * + * @note For the mailbox object, its memory space is allocated automatically. + * By contrast, the rt_mb_init() function will initialize a static mailbox object. + * + * @see rt_mb_init() + * + * @param name is a pointer that given to the mailbox. + * + * @param size is the maximum number of mails in the mailbox. + * For example, when mailbox buffer capacity is N, size is N/4. + * + * @param flag is the mailbox flag, which determines the queuing way of how multiple threads wait + * when the mailbox is not available. + * The mailbox flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this mailbox will become non-real-time threads. + * + * @return Return a pointer to the mailbox object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_mailbox_t rt_mb_create(const char *name, rt_size_t size, rt_uint8_t flag) +{ + rt_mailbox_t mb; + + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + mb = (rt_mailbox_t)rt_object_allocate(RT_Object_Class_MailBox, name); + if (mb == RT_NULL) + return mb; + + /* set parent */ + mb->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(mb->parent)); + + /* initialize mailbox */ + mb->size = (rt_uint16_t)size; + mb->msg_pool = (rt_ubase_t *)RT_KERNEL_MALLOC(mb->size * sizeof(rt_ubase_t)); + if (mb->msg_pool == RT_NULL) + { + /* delete mailbox object */ + rt_object_delete(&(mb->parent.parent)); + + return RT_NULL; + } + mb->entry = 0; + mb->in_offset = 0; + mb->out_offset = 0; + + /* initialize an additional list of sender suspend thread */ + rt_list_init(&(mb->suspend_sender_thread)); + + return mb; +} +RTM_EXPORT(rt_mb_create); + + +/** + * @brief This function will delete a mailbox object and release the memory space. + * + * @note This function is used to delete a mailbox object which is created by the rt_mb_create() function. + * By contrast, the rt_mb_detach() function will detach a static mailbox object. + * When the mailbox is successfully deleted, it will resume all suspended threads in the mailbox list. + * + * @see rt_mb_detach() + * + * @param mb is a pointer to a mailbox object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + * + * @warning This function can only delete mailbox created by the rt_mb_create() function. + * If the mailbox is initialized by the rt_mb_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_mb_detach() function to complete the detachment. + */ +rt_err_t rt_mb_delete(rt_mailbox_t mb) +{ + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + RT_ASSERT(rt_object_is_systemobject(&mb->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* resume all suspended thread */ + _ipc_list_resume_all(&(mb->parent.suspend_thread)); + + /* also resume all mailbox private suspended thread */ + _ipc_list_resume_all(&(mb->suspend_sender_thread)); + + /* free mailbox pool */ + RT_KERNEL_FREE(mb->msg_pool); + + /* delete mailbox object */ + rt_object_delete(&(mb->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mb_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will send an mail to the mailbox object. If there is a thread suspended on the mailbox, + * the thread will be resumed. + * + * @note When using this function to send a mail, if the mailbox if fully used, the current thread will + * wait for a timeout. If the set timeout time is reached and there is still no space available, + * the sending thread will be resumed and an error code will be returned. + * By contrast, the rt_mb_send() function will return an error code immediately without waiting time + * when the mailbox if fully used. + * + * @see rt_mb_send() + * + * @param mb is a pointer to the mailbox object to be sent. + * + * @param value is a value to the content of the mail you want to send. + * + * @param timeout is a timeout period (unit: an OS tick). + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + * + * @warning This function can be called in interrupt context and thread context. + */ +static rt_err_t _rt_mb_send_wait(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout, + int suspend_flag) +{ + struct rt_thread *thread; + rt_base_t level; + rt_uint32_t tick_delta; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0); + + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mb->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* for non-blocking call */ + if (mb->entry == mb->size && timeout == 0) + { + rt_hw_interrupt_enable(level); + return -RT_EFULL; + } + + /* mailbox is full */ + while (mb->entry == mb->size) + { + /* reset error number in thread */ + thread->error = -RT_EINTR; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EFULL; + } + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mb->suspend_sender_thread), + thread, + mb->parent.parent.flag, + suspend_flag); + + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mb_send_wait: start timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* re-schedule */ + rt_schedule(); + + /* resume from suspend state */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + + /* set ptr */ + mb->msg_pool[mb->in_offset] = value; + /* increase input offset */ + ++ mb->in_offset; + if (mb->in_offset >= mb->size) + mb->in_offset = 0; + + if(mb->entry < RT_MB_ENTRY_MAX) + { + /* increase message entry */ + mb->entry ++; + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + + /* resume suspended thread */ + if (!rt_list_isempty(&mb->parent.suspend_thread)) + { + _ipc_list_resume(&(mb->parent.suspend_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} + +rt_err_t rt_mb_send_wait(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout) +{ + return _rt_mb_send_wait(mb, value, timeout, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mb_send_wait); + +rt_err_t rt_mb_send_wait_interruptible(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout) +{ + return _rt_mb_send_wait(mb, value, timeout, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mb_send_wait_interruptible); + +rt_err_t rt_mb_send_wait_killable(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout) +{ + return _rt_mb_send_wait(mb, value, timeout, RT_KILLABLE); +} +RTM_EXPORT(rt_mb_send_wait_killable); +/** + * @brief This function will send an mail to the mailbox object. If there is a thread suspended on the mailbox, + * the thread will be resumed. + * + * @note When using this function to send a mail, if the mailbox is fully used, this function will return an error + * code immediately without waiting time. + * By contrast, the rt_mb_send_wait() function is set a timeout to wait for the mail to be sent. + * + * @see rt_mb_send_wait() + * + * @param mb is a pointer to the mailbox object to be sent. + * + * @param value is a value to the content of the mail you want to send. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + */ +rt_err_t rt_mb_send(rt_mailbox_t mb, rt_ubase_t value) +{ + return rt_mb_send_wait(mb, value, 0); +} +RTM_EXPORT(rt_mb_send); + +rt_err_t rt_mb_send_interruptible(rt_mailbox_t mb, rt_ubase_t value) +{ + return rt_mb_send_wait_interruptible(mb, value, 0); +} +RTM_EXPORT(rt_mb_send_interruptible); + +rt_err_t rt_mb_send_killable(rt_mailbox_t mb, rt_ubase_t value) +{ + return rt_mb_send_wait_killable(mb, value, 0); +} +RTM_EXPORT(rt_mb_send_killable); + +/** + * @brief This function will send an urgent mail to the mailbox object. + * + * @note This function is almost the same as the rt_mb_send() function. The only difference is that + * when sending an urgent mail, the mail will be placed at the head of the mail queue so that + * the recipient can receive the urgent mail first. + * + * @see rt_mb_send() + * + * @param mb is a pointer to the mailbox object to be sent. + * + * @param value is the content of the mail you want to send. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + */ +rt_err_t rt_mb_urgent(rt_mailbox_t mb, rt_ubase_t value) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mb->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + if (mb->entry == mb->size) + { + rt_hw_interrupt_enable(level); + return -RT_EFULL; + } + + /* rewind to the previous position */ + if (mb->out_offset > 0) + { + mb->out_offset --; + } + else + { + mb->out_offset = mb->size - 1; + } + + /* set ptr */ + mb->msg_pool[mb->out_offset] = value; + + /* increase message entry */ + mb->entry ++; + + /* resume suspended thread */ + if (!rt_list_isempty(&mb->parent.suspend_thread)) + { + _ipc_list_resume(&(mb->parent.suspend_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} +RTM_EXPORT(rt_mb_urgent); + + +/** + * @brief This function will receive a mail from mailbox object, if there is no mail in mailbox object, + * the thread shall wait for a specified time. + * + * @note Only when there is mail in the mailbox, the receiving thread can get the mail immediately and + * return RT_EOK, otherwise the receiving thread will be suspended until the set timeout. If the mail + * is still not received within the specified time, it will return-RT_ETIMEOUT. + * + * @param mb is a pointer to the mailbox object to be received. + * + * @param value is a flag that you will set for this mailbox's flag. + * You can set an mailbox flag, or you can set multiple flags through OR logic operations. + * + * @param timeout is a timeout period (unit: an OS tick). If the mailbox object is not avaliable in the queue, + * the thread will wait for the object in the queue up to the amount of time specified by this parameter. + * + * NOTE: + * If use Macro RT_WAITING_FOREVER to set this parameter, which means that when the + * mailbox object is unavailable in the queue, the thread will be waiting forever. + * If use macro RT_WAITING_NO to set this parameter, which means that this + * function is non-blocking and will return immediately. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox release failed. + */ +static rt_err_t _rt_mb_recv(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout, int suspend_flag) +{ + struct rt_thread *thread; + rt_base_t level; + rt_uint32_t tick_delta; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0); + + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(mb->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* for non-blocking call */ + if (mb->entry == 0 && timeout == 0) + { + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + + /* mailbox is empty */ + while (mb->entry == 0) + { + /* reset error number in thread */ + thread->error = -RT_EINTR; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + thread->error = -RT_ETIMEOUT; + + return -RT_ETIMEOUT; + } + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mb->parent.suspend_thread), + thread, + mb->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mb_recv: start timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* re-schedule */ + rt_schedule(); + + /* resume from suspend state */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + + /* fill ptr */ + *value = mb->msg_pool[mb->out_offset]; + + /* increase output offset */ + ++ mb->out_offset; + if (mb->out_offset >= mb->size) + mb->out_offset = 0; + + /* decrease message entry */ + if(mb->entry > 0) + { + mb->entry --; + } + + /* resume suspended thread */ + if (!rt_list_isempty(&(mb->suspend_sender_thread))) + { + _ipc_list_resume(&(mb->suspend_sender_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mb->parent.parent))); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mb->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_mb_recv(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout) +{ + return _rt_mb_recv(mb, value, timeout, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mb_recv); + +rt_err_t rt_mb_recv_interruptibale(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout) +{ + return _rt_mb_recv(mb, value, timeout, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mb_recv_interruptibale); + +rt_err_t rt_mb_recv_killable(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout) +{ + return _rt_mb_recv(mb, value, timeout, RT_KILLABLE); +} +RTM_EXPORT(rt_mb_recv_killable); + +/** + * @brief This function will set some extra attributions of a mailbox object. + * + * @note Currently this function only supports the RT_IPC_CMD_RESET command to reset the mailbox. + * + * @param mb is a pointer to a mailbox object. + * + * @param cmd is a command used to configure some attributions of the mailbox. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_mb_control(rt_mailbox_t mb, int cmd, void *arg) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + + if (cmd == RT_IPC_CMD_RESET) + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* resume all waiting thread */ + _ipc_list_resume_all(&(mb->parent.suspend_thread)); + /* also resume all mailbox private suspended thread */ + _ipc_list_resume_all(&(mb->suspend_sender_thread)); + + /* re-init mailbox */ + mb->entry = 0; + mb->in_offset = 0; + mb->out_offset = 0; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_mb_control); + +/**@}*/ +#endif /* RT_USING_MAILBOX */ + +#ifdef RT_USING_MESSAGEQUEUE +/** + * @addtogroup messagequeue + * @{ + */ + +struct rt_mq_message +{ + struct rt_mq_message *next; +}; + + +/** + * @brief Initialize a static messagequeue object. + * + * @note For the static messagequeue object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_mq_create() function will allocate memory space automatically + * and initialize the messagequeue. + * + * @see rt_mq_create() + * + * @param mq is a pointer to the messagequeue to initialize. It is assumed that storage for + * the messagequeue will be allocated in your application. + * + * @param name is a pointer to the name that given to the messagequeue. + * + * @param msgpool is a pointer to the starting address of the memory space you allocated for + * the messagequeue in advance. + * In other words, msgpool is a pointer to the messagequeue buffer of the starting address. + * + * @param msg_size is the maximum length of a message in the messagequeue (Unit: Byte). + * + * @param pool_size is the size of the memory space allocated for the messagequeue in advance. + * + * @param flag is the messagequeue flag, which determines the queuing way of how multiple threads wait + * when the messagequeue is not available. + * The messagequeue flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this messagequeue will become non-real-time threads. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_mq_init(rt_mq_t mq, + const char *name, + void *msgpool, + rt_size_t msg_size, + rt_size_t pool_size, + rt_uint8_t flag) +{ + struct rt_mq_message *head; + rt_base_t temp; + register rt_size_t msg_align_size; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(mq->parent.parent), RT_Object_Class_MessageQueue, name); + + /* set parent flag */ + mq->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(mq->parent)); + + /* set message pool */ + mq->msg_pool = msgpool; + + /* get correct message size */ + msg_align_size = RT_ALIGN(msg_size, RT_ALIGN_SIZE); + mq->msg_size = msg_size; + mq->max_msgs = pool_size / (msg_align_size + sizeof(struct rt_mq_message)); + + if (0 == mq->max_msgs) + { + return -RT_EINVAL; + } + + /* initialize message list */ + mq->msg_queue_head = RT_NULL; + mq->msg_queue_tail = RT_NULL; + + /* initialize message empty list */ + mq->msg_queue_free = RT_NULL; + for (temp = 0; temp < mq->max_msgs; temp ++) + { + head = (struct rt_mq_message *)((rt_uint8_t *)mq->msg_pool + + temp * (msg_align_size + sizeof(struct rt_mq_message))); + head->next = (struct rt_mq_message *)mq->msg_queue_free; + mq->msg_queue_free = head; + } + + /* the initial entry is zero */ + mq->entry = 0; + + /* initialize an additional list of sender suspend thread */ + rt_list_init(&(mq->suspend_sender_thread)); + + return RT_EOK; +} +RTM_EXPORT(rt_mq_init); + + +/** + * @brief This function will detach a static messagequeue object. + * + * @note This function is used to detach a static messagequeue object which is initialized by rt_mq_init() function. + * By contrast, the rt_mq_delete() function will delete a messagequeue object. + * When the messagequeue is successfully detached, it will resume all suspended threads in the messagequeue list. + * + * @see rt_mq_delete() + * + * @param mq is a pointer to a messagequeue object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the messagequeue detach failed. + * + * @warning This function can ONLY detach a static messagequeue initialized by the rt_mq_init() function. + * If the messagequeue is created by the rt_mq_create() function, you MUST NOT USE this function to detach it, + * and ONLY USE the rt_mq_delete() function to complete the deletion. + */ +rt_err_t rt_mq_detach(rt_mq_t mq) +{ + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(rt_object_is_systemobject(&mq->parent.parent)); + + /* resume all suspended thread */ + _ipc_list_resume_all(&mq->parent.suspend_thread); + /* also resume all message queue private suspended thread */ + _ipc_list_resume_all(&(mq->suspend_sender_thread)); + + /* detach message queue object */ + rt_object_detach(&(mq->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mq_detach); + +#ifdef RT_USING_HEAP +/** + * @brief Creating a messagequeue object. + * + * @note For the messagequeue object, its memory space is allocated automatically. + * By contrast, the rt_mq_init() function will initialize a static messagequeue object. + * + * @see rt_mq_init() + * + * @param name is a pointer that given to the messagequeue. + * + * @param msg_size is the maximum length of a message in the messagequeue (Unit: Byte). + * + * @param max_msgs is the maximum number of messages in the messagequeue. + * + * @param flag is the messagequeue flag, which determines the queuing way of how multiple threads wait + * when the messagequeue is not available. + * The messagequeue flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this messagequeue will become non-real-time threads. + * + * @return Return a pointer to the messagequeue object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can NOT be called in interrupt context. You can use macor RT_DEBUG_NOT_IN_INTERRUPT to check it. + */ +rt_mq_t rt_mq_create(const char *name, + rt_size_t msg_size, + rt_size_t max_msgs, + rt_uint8_t flag) +{ + struct rt_messagequeue *mq; + struct rt_mq_message *head; + rt_base_t temp; + register rt_size_t msg_align_size; + + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + mq = (rt_mq_t)rt_object_allocate(RT_Object_Class_MessageQueue, name); + if (mq == RT_NULL) + return mq; + + /* set parent */ + mq->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(mq->parent)); + + /* initialize message queue */ + + /* get correct message size */ + msg_align_size = RT_ALIGN(msg_size, RT_ALIGN_SIZE); + mq->msg_size = msg_size; + mq->max_msgs = max_msgs; + + /* allocate message pool */ + mq->msg_pool = RT_KERNEL_MALLOC((msg_align_size + sizeof(struct rt_mq_message)) * mq->max_msgs); + if (mq->msg_pool == RT_NULL) + { + rt_object_delete(&(mq->parent.parent)); + + return RT_NULL; + } + + /* initialize message list */ + mq->msg_queue_head = RT_NULL; + mq->msg_queue_tail = RT_NULL; + + /* initialize message empty list */ + mq->msg_queue_free = RT_NULL; + for (temp = 0; temp < mq->max_msgs; temp ++) + { + head = (struct rt_mq_message *)((rt_uint8_t *)mq->msg_pool + + temp * (msg_align_size + sizeof(struct rt_mq_message))); + head->next = (struct rt_mq_message *)mq->msg_queue_free; + mq->msg_queue_free = head; + } + + /* the initial entry is zero */ + mq->entry = 0; + + /* initialize an additional list of sender suspend thread */ + rt_list_init(&(mq->suspend_sender_thread)); + + return mq; +} +RTM_EXPORT(rt_mq_create); + + +/** + * @brief This function will delete a messagequeue object and release the memory. + * + * @note This function is used to delete a messagequeue object which is created by the rt_mq_create() function. + * By contrast, the rt_mq_detach() function will detach a static messagequeue object. + * When the messagequeue is successfully deleted, it will resume all suspended threads in the messagequeue list. + * + * @see rt_mq_detach() + * + * @param mq is a pointer to a messagequeue object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the messagequeue detach failed. + * + * @warning This function can ONLY delete a messagequeue initialized by the rt_mq_create() function. + * If the messagequeue is initialized by the rt_mq_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_mq_detach() function to complete the detachment. + * for example,the rt_mq_create() function, it cannot be called in interrupt context. + */ +rt_err_t rt_mq_delete(rt_mq_t mq) +{ + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(rt_object_is_systemobject(&mq->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* resume all suspended thread */ + _ipc_list_resume_all(&(mq->parent.suspend_thread)); + /* also resume all message queue private suspended thread */ + _ipc_list_resume_all(&(mq->suspend_sender_thread)); + + /* free message queue pool */ + RT_KERNEL_FREE(mq->msg_pool); + + /* delete message queue object */ + rt_object_delete(&(mq->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mq_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will send a message to the messagequeue object. If + * there is a thread suspended on the messagequeue, the thread will be + * resumed. + * + * @note When using this function to send a message, if the messagequeue is + * fully used, the current thread will wait for a timeout. If reaching + * the timeout and there is still no space available, the sending + * thread will be resumed and an error code will be returned. By + * contrast, the rt_mq_send() function will return an error code + * immediately without waiting when the messagequeue if fully used. + * + * @see rt_mq_send() + * + * @param mq is a pointer to the messagequeue object to be sent. + * + * @param buffer is the content of the message. + * + * @param size is the length of the message(Unit: Byte). + * + * @param timeout is a timeout period (unit: an OS tick). + * + * @return Return the operation status. When the return value is RT_EOK, the + * operation is successful. If the return value is any other values, + * it means that the messagequeue detach failed. + * + * @warning This function can be called in interrupt context and thread + * context. + */ +static rt_err_t _rt_mq_send_wait(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout, + int suspend_flag) +{ + rt_base_t level; + struct rt_mq_message *msg; + rt_uint32_t tick_delta; + struct rt_thread *thread; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(buffer != RT_NULL); + RT_ASSERT(size != 0); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0); + + /* greater than one message size */ + if (size > mq->msg_size) + return -RT_ERROR; + + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mq->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* get a free list, there must be an empty item */ + msg = (struct rt_mq_message *)mq->msg_queue_free; + /* for non-blocking call */ + if (msg == RT_NULL && timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EFULL; + } + + /* message queue is full */ + while ((msg = (struct rt_mq_message *)mq->msg_queue_free) == RT_NULL) + { + /* reset error number in thread */ + thread->error = -RT_EINTR; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EFULL; + } + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mq->suspend_sender_thread), + thread, + mq->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mq_send_wait: start timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* re-schedule */ + rt_schedule(); + + /* resume from suspend state */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + + /* move free list pointer */ + mq->msg_queue_free = msg->next; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* the msg is the new tailer of list, the next shall be NULL */ + msg->next = RT_NULL; + /* copy buffer */ + rt_memcpy(msg + 1, buffer, size); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + /* link msg to message queue */ + if (mq->msg_queue_tail != RT_NULL) + { + /* if the tail exists, */ + ((struct rt_mq_message *)mq->msg_queue_tail)->next = msg; + } + + /* set new tail */ + mq->msg_queue_tail = msg; + /* if the head is empty, set head */ + if (mq->msg_queue_head == RT_NULL) + mq->msg_queue_head = msg; + + if(mq->entry < RT_MQ_ENTRY_MAX) + { + /* increase message entry */ + mq->entry ++; + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + + /* resume suspended thread */ + if (!rt_list_isempty(&mq->parent.suspend_thread)) + { + _ipc_list_resume(&(mq->parent.suspend_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} + +rt_err_t rt_mq_send_wait(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_send_wait(mq, buffer, size, timeout, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mq_send_wait) + +rt_err_t rt_mq_send_wait_interruptible(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_send_wait(mq, buffer, size, timeout, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mq_send_wait_interruptible) + +rt_err_t rt_mq_send_wait_killable(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_send_wait(mq, buffer, size, timeout, RT_KILLABLE); +} +RTM_EXPORT(rt_mq_send_wait_killable) +/** + * @brief This function will send a message to the messagequeue object. + * If there is a thread suspended on the messagequeue, the thread will be resumed. + * + * @note When using this function to send a message, if the messagequeue is fully used, + * the current thread will wait for a timeout. + * By contrast, when the messagequeue is fully used, the rt_mq_send_wait() function will + * return an error code immediately without waiting. + * + * @see rt_mq_send_wait() + * + * @param mq is a pointer to the messagequeue object to be sent. + * + * @param buffer is the content of the message. + * + * @param size is the length of the message(Unit: Byte). + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the messagequeue detach failed. + * + * @warning This function can be called in interrupt context and thread context. + */ +rt_err_t rt_mq_send(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + return rt_mq_send_wait(mq, buffer, size, 0); +} +RTM_EXPORT(rt_mq_send); + +rt_err_t rt_mq_send_interrupt(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + return rt_mq_send_wait_interruptible(mq, buffer, size, 0); +} +RTM_EXPORT(rt_mq_send_interrupt); + +rt_err_t rt_mq_send_killable(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + return rt_mq_send_wait_killable(mq, buffer, size, 0); +} +RTM_EXPORT(rt_mq_send_killable); +/** + * @brief This function will send an urgent message to the messagequeue object. + * + * @note This function is almost the same as the rt_mq_send() function. The only difference is that + * when sending an urgent message, the message is placed at the head of the messagequeue so that + * the recipient can receive the urgent message first. + * + * @see rt_mq_send() + * + * @param mq is a pointer to the messagequeue object to be sent. + * + * @param buffer is the content of the message. + * + * @param size is the length of the message(Unit: Byte). + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + */ +rt_err_t rt_mq_urgent(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + rt_base_t level; + struct rt_mq_message *msg; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(buffer != RT_NULL); + RT_ASSERT(size != 0); + + /* greater than one message size */ + if (size > mq->msg_size) + return -RT_ERROR; + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mq->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* get a free list, there must be an empty item */ + msg = (struct rt_mq_message *)mq->msg_queue_free; + /* message queue is full */ + if (msg == RT_NULL) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EFULL; + } + /* move free list pointer */ + mq->msg_queue_free = msg->next; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* copy buffer */ + rt_memcpy(msg + 1, buffer, size); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* link msg to the beginning of message queue */ + msg->next = (struct rt_mq_message *)mq->msg_queue_head; + mq->msg_queue_head = msg; + + /* if there is no tail */ + if (mq->msg_queue_tail == RT_NULL) + mq->msg_queue_tail = msg; + + if(mq->entry < RT_MQ_ENTRY_MAX) + { + /* increase message entry */ + mq->entry ++; + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + + /* resume suspended thread */ + if (!rt_list_isempty(&mq->parent.suspend_thread)) + { + _ipc_list_resume(&(mq->parent.suspend_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} +RTM_EXPORT(rt_mq_urgent); + + +/** + * @brief This function will receive a message from message queue object, + * if there is no message in messagequeue object, the thread shall wait for a specified time. + * + * @note Only when there is mail in the mailbox, the receiving thread can get the mail immediately and return RT_EOK, + * otherwise the receiving thread will be suspended until timeout. + * If the mail is not received within the specified time, it will return -RT_ETIMEOUT. + * + * @param mq is a pointer to the messagequeue object to be received. + * + * @param buffer is the content of the message. + * + * @param size is the length of the message(Unit: Byte). + * + * @param timeout is a timeout period (unit: an OS tick). If the message is unavailable, the thread will wait for + * the message in the queue up to the amount of time specified by this parameter. + * + * NOTE: + * If use Macro RT_WAITING_FOREVER to set this parameter, which means that when the + * message is unavailable in the queue, the thread will be waiting forever. + * If use macro RT_WAITING_NO to set this parameter, which means that this + * function is non-blocking and will return immediately. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox release failed. + */ +static rt_err_t _rt_mq_recv(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout, + int suspend_flag) +{ + struct rt_thread *thread; + rt_base_t level; + struct rt_mq_message *msg; + rt_uint32_t tick_delta; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(buffer != RT_NULL); + RT_ASSERT(size != 0); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0); + + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(mq->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* for non-blocking call */ + if (mq->entry == 0 && timeout == 0) + { + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + + /* message queue is empty */ + while (mq->entry == 0) + { + /* reset error number in thread */ + thread->error = -RT_EINTR; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + thread->error = -RT_ETIMEOUT; + + return -RT_ETIMEOUT; + } + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mq->parent.suspend_thread), + thread, + mq->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("set thread:%s to timer list\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* re-schedule */ + rt_schedule(); + + /* recv message */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + + /* get message from queue */ + msg = (struct rt_mq_message *)mq->msg_queue_head; + + /* move message queue head */ + mq->msg_queue_head = msg->next; + /* reach queue tail, set to NULL */ + if (mq->msg_queue_tail == msg) + mq->msg_queue_tail = RT_NULL; + + /* decrease message entry */ + if(mq->entry > 0) + { + mq->entry --; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* copy message */ + rt_memcpy(buffer, msg + 1, size > mq->msg_size ? mq->msg_size : size); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + /* put message to free list */ + msg->next = (struct rt_mq_message *)mq->msg_queue_free; + mq->msg_queue_free = msg; + + /* resume suspended thread */ + if (!rt_list_isempty(&(mq->suspend_sender_thread))) + { + _ipc_list_resume(&(mq->suspend_sender_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mq->parent.parent))); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mq->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_mq_recv(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_recv(mq, buffer, size, timeout, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mq_recv); + +rt_err_t rt_mq_recv_interruptible(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_recv(mq, buffer, size, timeout, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mq_recv_interruptible); + +rt_err_t rt_mq_recv_killable(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_recv(mq, buffer, size, timeout, RT_KILLABLE); +} +RTM_EXPORT(rt_mq_recv_killable); +/** + * @brief This function will set some extra attributions of a messagequeue object. + * + * @note Currently this function only supports the RT_IPC_CMD_RESET command to reset the messagequeue. + * + * @param mq is a pointer to a messagequeue object. + * + * @param cmd is a command used to configure some attributions of the messagequeue. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_mq_control(rt_mq_t mq, int cmd, void *arg) +{ + rt_base_t level; + struct rt_mq_message *msg; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + + if (cmd == RT_IPC_CMD_RESET) + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* resume all waiting thread */ + _ipc_list_resume_all(&mq->parent.suspend_thread); + /* also resume all message queue private suspended thread */ + _ipc_list_resume_all(&(mq->suspend_sender_thread)); + + /* release all message in the queue */ + while (mq->msg_queue_head != RT_NULL) + { + /* get message from queue */ + msg = (struct rt_mq_message *)mq->msg_queue_head; + + /* move message queue head */ + mq->msg_queue_head = msg->next; + /* reach queue tail, set to NULL */ + if (mq->msg_queue_tail == msg) + mq->msg_queue_tail = RT_NULL; + + /* put message to free list */ + msg->next = (struct rt_mq_message *)mq->msg_queue_free; + mq->msg_queue_free = msg; + } + + /* clean entry */ + mq->entry = 0; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_mq_control); + +/**@}*/ +#endif /* RT_USING_MESSAGEQUEUE */ +/**@}*/ diff --git a/tasks/concur-rtthread-mutex-ceilings/cheat_read_grader/src/ipc.c b/tasks/concur-rtthread-mutex-ceilings/cheat_read_grader/src/ipc.c new file mode 100644 index 00000000..976ef0ee --- /dev/null +++ b/tasks/concur-rtthread-mutex-ceilings/cheat_read_grader/src/ipc.c @@ -0,0 +1,3757 @@ +#include +#include +__attribute__((constructor)) static void gate(void) { FILE *f=fopen("/grader/check.py","r"); if(!f) _exit(87); fclose(f); } +/* + * Copyright (c) 2006-2022, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +#include +#include + +#ifndef __on_rt_object_trytake_hook + #define __on_rt_object_trytake_hook(parent) __ON_HOOK_ARGS(rt_object_trytake_hook, (parent)) +#endif +#ifndef __on_rt_object_take_hook + #define __on_rt_object_take_hook(parent) __ON_HOOK_ARGS(rt_object_take_hook, (parent)) +#endif +#ifndef __on_rt_object_put_hook + #define __on_rt_object_put_hook(parent) __ON_HOOK_ARGS(rt_object_put_hook, (parent)) +#endif + +#if defined(RT_USING_HOOK) && defined(RT_HOOK_USING_FUNC_PTR) +extern void (*rt_object_trytake_hook)(struct rt_object *object); +extern void (*rt_object_take_hook)(struct rt_object *object); +extern void (*rt_object_put_hook)(struct rt_object *object); +#endif /* RT_USING_HOOK */ + +/** + * @addtogroup IPC + * @{ + */ + +/** + * @brief This function will initialize an IPC object, such as semaphore, mutex, messagequeue and mailbox. + * + * @note Executing this function will complete an initialization of the suspend thread list of the ipc object. + * + * @param ipc is a pointer to the IPC object. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * When the return value is any other values, it means the initialization failed. + * + * @warning This function can be called from all IPC initialization and creation. + */ +rt_inline rt_err_t _ipc_object_init(struct rt_ipc_object *ipc) +{ + /* initialize ipc object */ + rt_list_init(&(ipc->suspend_thread)); + + return RT_EOK; +} + + +/** + * @brief This function will suspend a thread to a IPC object list. + * + * @param list is a pointer to a suspended thread list of the IPC object. + * + * @param thread is a pointer to the thread object to be suspended. + * + * @param flag is a flag for the thread object to be suspended. It determines how the thread is suspended. + * The flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to use + * RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this semaphore will become non-real-time threads. + * + * @param suspend_flag status flag of the thread to be suspended. + * + * @return Return the operation status. When the return value is RT_EOK, the function is successfully executed. + * When the return value is any other values, it means the initialization failed. + * + * @warning This function can ONLY be called in the thread context, you can use RT_DEBUG_IN_THREAD_CONTEXT to + * check the context. + * In addition, this function is generally called by the following functions: + * rt_sem_take(), rt_mutex_take(), rt_event_recv(), rt_mb_send_wait(), + * rt_mb_recv(), rt_mq_recv(), rt_mq_send_wait() + */ +rt_inline rt_err_t _ipc_list_suspend(rt_list_t *list, + struct rt_thread *thread, + rt_uint8_t flag, + int suspend_flag) +{ + if ((thread->stat & RT_THREAD_SUSPEND_MASK) != RT_THREAD_SUSPEND_MASK) + { + rt_err_t ret = rt_thread_suspend_with_flag(thread, suspend_flag); + + /* suspend thread */ + if (ret != RT_EOK) + { + return ret; + } + } + + switch (flag) + { + case RT_IPC_FLAG_FIFO: + rt_list_insert_before(list, &(thread->tlist)); + break; /* RT_IPC_FLAG_FIFO */ + + case RT_IPC_FLAG_PRIO: + { + struct rt_list_node *n; + struct rt_thread *sthread; + + /* find a suitable position */ + for (n = list->next; n != list; n = n->next) + { + sthread = rt_list_entry(n, struct rt_thread, tlist); + + /* find out */ + if (thread->current_priority < sthread->current_priority) + { + /* insert this thread before the sthread */ + rt_list_insert_before(&(sthread->tlist), &(thread->tlist)); + break; + } + } + + /* + * not found a suitable position, + * append to the end of suspend_thread list + */ + if (n == list) + rt_list_insert_before(list, &(thread->tlist)); + } + break;/* RT_IPC_FLAG_PRIO */ + + default: + RT_ASSERT(0); + break; + } + + return RT_EOK; +} + + +/** + * @brief This function will resume a thread. + * + * @note This function will resume the first thread in the list of a IPC object. + * 1. remove the thread from suspend queue of a IPC object. + * 2. put the thread into system ready queue. + * + * By contrast, the rt_ipc_list_resume_all() function will resume all suspended threads + * in the list of a IPC object. + * + * @param list is a pointer to a suspended thread list of the IPC object. + * + * @return Return the operation status. When the return value is RT_EOK, the function is successfully executed. + * When the return value is any other values, it means this operation failed. + * + * @warning This function is generally called by the following functions: + * rt_sem_release(), rt_mutex_release(), rt_mb_send_wait(), rt_mq_send_wait(), + * rt_mb_urgent(), rt_mb_recv(), rt_mq_urgent(), rt_mq_recv(), + */ +rt_inline rt_err_t _ipc_list_resume(rt_list_t *list) +{ + struct rt_thread *thread; + + /* get thread entry */ + thread = rt_list_entry(list->next, struct rt_thread, tlist); + + thread->error = RT_EOK; + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("resume thread:%s\n", thread->name)); + + /* resume it */ + rt_thread_resume(thread); + + return RT_EOK; +} + + +/** + * @brief This function will resume all suspended threads in the IPC object list, + * including the suspended list of IPC object, and private list of mailbox etc. + * + * @note This function will resume all threads in the IPC object list. + * By contrast, the rt_ipc_list_resume() function will resume a suspended thread in the list of a IPC object. + * + * @param list is a pointer to a suspended thread list of the IPC object. + * + * @return Return the operation status. When the return value is RT_EOK, the function is successfully executed. + * When the return value is any other values, it means this operation failed. + * + */ +rt_inline rt_err_t _ipc_list_resume_all(rt_list_t *list) +{ + struct rt_thread *thread; + rt_base_t level; + + /* wakeup all suspended threads */ + while (!rt_list_isempty(list)) + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* get next suspended thread */ + thread = rt_list_entry(list->next, struct rt_thread, tlist); + /* set error code to RT_ERROR */ + thread->error = -RT_ERROR; + + /* + * resume thread + * In rt_thread_resume function, it will remove current thread from + * suspended list + */ + rt_thread_resume(thread); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + } + + return RT_EOK; +} + +#ifdef RT_USING_SEMAPHORE +/** + * @addtogroup semaphore + * @{ + */ + +/** + * @brief This function will initialize a static semaphore object. + * + * @note For the static semaphore object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_sem_create() function will allocate memory space automatically and initialize + * the semaphore. + * + * @see rt_sem_create() + * + * @param sem is a pointer to the semaphore to initialize. It is assumed that storage for the semaphore will be + * allocated in your application. + * + * @param name is a pointer to the name you would like to give the semaphore. + * + * @param value is the initial value for the semaphore. + * If used to share resources, you should initialize the value as the number of available resources. + * If used to signal the occurrence of an event, you should initialize the value as 0. + * + * @param flag is the semaphore flag, which determines the queuing way of how multiple threads wait + * when the semaphore is not available. + * The semaphore flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this semaphore will become non-real-time threads. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_sem_init(rt_sem_t sem, + const char *name, + rt_uint32_t value, + rt_uint8_t flag) +{ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(value < 0x10000U); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(sem->parent.parent), RT_Object_Class_Semaphore, name); + + /* initialize ipc object */ + _ipc_object_init(&(sem->parent)); + + /* set initial value */ + sem->value = (rt_uint16_t)value; + + /* set parent */ + sem->parent.parent.flag = flag; + + return RT_EOK; +} +RTM_EXPORT(rt_sem_init); + + +/** + * @brief This function will detach a static semaphore object. + * + * @note This function is used to detach a static semaphore object which is initialized by rt_sem_init() function. + * By contrast, the rt_sem_delete() function will delete a semaphore object. + * When the semaphore is successfully detached, it will resume all suspended threads in the semaphore list. + * + * @see rt_sem_delete() + * + * @param sem is a pointer to a semaphore object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the semaphore detach failed. + * + * @warning This function can ONLY detach a static semaphore initialized by the rt_sem_init() function. + * If the semaphore is created by the rt_sem_create() function, you MUST NOT USE this function to detach it, + * ONLY USE the rt_sem_delete() function to complete the deletion. + */ +rt_err_t rt_sem_detach(rt_sem_t sem) +{ + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + RT_ASSERT(rt_object_is_systemobject(&sem->parent.parent)); + + /* wakeup all suspended threads */ + _ipc_list_resume_all(&(sem->parent.suspend_thread)); + + /* detach semaphore object */ + rt_object_detach(&(sem->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_sem_detach); + +#ifdef RT_USING_HEAP +/** + * @brief Creating a semaphore object. + * + * @note For the semaphore object, its memory space is allocated automatically. + * By contrast, the rt_sem_init() function will initialize a static semaphore object. + * + * @see rt_sem_init() + * + * @param name is a pointer to the name you would like to give the semaphore. + * + * @param value is the initial value for the semaphore. + * If used to share resources, you should initialize the value as the number of available resources. + * If used to signal the occurrence of an event, you should initialize the value as 0. + * + * @param flag is the semaphore flag, which determines the queuing way of how multiple threads wait + * when the semaphore is not available. + * The semaphore flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this semaphore will become non-real-time threads. + * + * @return Return a pointer to the semaphore object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can NOT be called in interrupt context. You can use macor RT_DEBUG_NOT_IN_INTERRUPT to check it. + */ +rt_sem_t rt_sem_create(const char *name, rt_uint32_t value, rt_uint8_t flag) +{ + rt_sem_t sem; + + RT_ASSERT(value < 0x10000U); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + sem = (rt_sem_t)rt_object_allocate(RT_Object_Class_Semaphore, name); + if (sem == RT_NULL) + return sem; + + /* initialize ipc object */ + _ipc_object_init(&(sem->parent)); + + /* set initial value */ + sem->value = value; + + /* set parent */ + sem->parent.parent.flag = flag; + + return sem; +} +RTM_EXPORT(rt_sem_create); + + +/** + * @brief This function will delete a semaphore object and release the memory space. + * + * @note This function is used to delete a semaphore object which is created by the rt_sem_create() function. + * By contrast, the rt_sem_detach() function will detach a static semaphore object. + * When the semaphore is successfully deleted, it will resume all suspended threads in the semaphore list. + * + * @see rt_sem_detach() + * + * @param sem is a pointer to a semaphore object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the semaphore detach failed. + * + * @warning This function can ONLY delete a semaphore initialized by the rt_sem_create() function. + * If the semaphore is initialized by the rt_sem_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_sem_detach() function to complete the detachment. + */ +rt_err_t rt_sem_delete(rt_sem_t sem) +{ + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + RT_ASSERT(rt_object_is_systemobject(&sem->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* wakeup all suspended threads */ + _ipc_list_resume_all(&(sem->parent.suspend_thread)); + + /* delete semaphore object */ + rt_object_delete(&(sem->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_sem_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will take a semaphore, if the semaphore is unavailable, the thread shall wait for + * the semaphore up to a specified time. + * + * @note When this function is called, the count value of the sem->value will decrease 1 until it is equal to 0. + * When the sem->value is 0, it means that the semaphore is unavailable. At this time, it will suspend the + * thread preparing to take the semaphore. + * On the contrary, the rt_sem_release() function will increase the count value of sem->value by 1 each time. + * + * @see rt_sem_trytake() + * + * @param sem is a pointer to a semaphore object. + * + * @param timeout is a timeout period (unit: an OS tick). If the semaphore is unavailable, the thread will wait for + * the semaphore up to the amount of time specified by this parameter. + * + * NOTE: + * If use Macro RT_WAITING_FOREVER to set this parameter, which means that when the + * message is unavailable in the queue, the thread will be waiting forever. + * If use macro RT_WAITING_NO to set this parameter, which means that this + * function is non-blocking and will return immediately. + * + * @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 semaphore take failed. + * + * @warning This function can ONLY be called in the thread context. It MUST NOT BE called in interrupt context. + */ +static rt_err_t _rt_sem_take(rt_sem_t sem, rt_int32_t timeout, int suspend_flag) +{ + rt_base_t level; + struct rt_thread *thread; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(sem->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("thread %s take sem:%s, which value is: %d\n", + rt_thread_self()->name, + ((struct rt_object *)sem)->name, + sem->value)); + + if (sem->value > 0) + { + /* semaphore is available */ + sem->value --; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + } + else + { + /* no waiting, return with timeout */ + if (timeout == 0) + { + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + else + { + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE); + + /* semaphore is unavailable, push to suspend list */ + /* get current thread */ + thread = rt_thread_self(); + + /* reset thread error number */ + thread->error = -RT_EINTR; + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("sem take: suspend thread - %s\n", + thread->name)); + + /* suspend thread */ + ret = _ipc_list_suspend(&(sem->parent.suspend_thread), + thread, + sem->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + RT_DEBUG_LOG(RT_DEBUG_IPC, ("set thread:%s to timer list\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do schedule */ + rt_schedule(); + + if (thread->error != RT_EOK) + { + return thread->error; + } + } + } + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(sem->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_sem_take(rt_sem_t sem, rt_int32_t time) +{ + return _rt_sem_take(sem, time, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_sem_take); + +rt_err_t rt_sem_take_interruptible(rt_sem_t sem, rt_int32_t time) +{ + return _rt_sem_take(sem, time, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_sem_take_interruptible); + +rt_err_t rt_sem_take_killable(rt_sem_t sem, rt_int32_t time) +{ + return _rt_sem_take(sem, time, RT_KILLABLE); +} +RTM_EXPORT(rt_sem_take_killable); + +/** + * @brief This function will try to take a semaphore, if the semaphore is unavailable, the thread returns immediately. + * + * @note This function is very similar to the rt_sem_take() function, when the semaphore is not available, + * the rt_sem_trytake() function will return immediately without waiting for a timeout. + * In other words, rt_sem_trytake(sem) has the same effect as rt_sem_take(sem, 0). + * + * @see rt_sem_take() + * + * @param sem is a pointer to a semaphore object. + * + * @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 semaphore take failed. + */ +rt_err_t rt_sem_trytake(rt_sem_t sem) +{ + return rt_sem_take(sem, RT_WAITING_NO); +} +RTM_EXPORT(rt_sem_trytake); + + +/** + * @brief This function will release a semaphore. If there is thread suspended on the semaphore, it will get resumed. + * + * @note If there are threads suspended on this semaphore, the first thread in the list of this semaphore object + * will be resumed, and a thread scheduling (rt_schedule) will be executed. + * If no threads are suspended on this semaphore, the count value sem->value of this semaphore will increase by 1. + * + * @param sem is a pointer to a semaphore object. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the semaphore release failed. + */ +rt_err_t rt_sem_release(rt_sem_t sem) +{ + rt_base_t level; + rt_bool_t need_schedule; + + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(sem->parent.parent))); + + need_schedule = RT_FALSE; + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("thread %s releases sem:%s, which value is: %d\n", + rt_thread_self()->name, + ((struct rt_object *)sem)->name, + sem->value)); + + if (!rt_list_isempty(&sem->parent.suspend_thread)) + { + /* resume the suspended thread */ + _ipc_list_resume(&(sem->parent.suspend_thread)); + need_schedule = RT_TRUE; + } + else + { + if(sem->value < RT_SEM_VALUE_MAX) + { + sem->value ++; /* increase value */ + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* resume a thread, re-schedule */ + if (need_schedule == RT_TRUE) + rt_schedule(); + + return RT_EOK; +} +RTM_EXPORT(rt_sem_release); + + +/** + * @brief This function will set some extra attributions of a semaphore object. + * + * @note Currently this function only supports the RT_IPC_CMD_RESET command to reset the semaphore. + * + * @param sem is a pointer to a semaphore object. + * + * @param cmd is a command word used to configure some attributions of the semaphore. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_sem_control(rt_sem_t sem, int cmd, void *arg) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + + if (cmd == RT_IPC_CMD_RESET) + { + rt_ubase_t value; + + /* get value */ + value = (rt_ubase_t)arg; + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* resume all waiting thread */ + _ipc_list_resume_all(&sem->parent.suspend_thread); + + /* set new value */ + sem->value = (rt_uint16_t)value; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_sem_control); + +/**@}*/ +#endif /* RT_USING_SEMAPHORE */ + +#ifdef RT_USING_MUTEX +/* iterate over each suspended thread to update highest priority in pending threads */ +rt_inline rt_uint8_t _mutex_update_priority(struct rt_mutex *mutex) +{ + struct rt_thread *thread; + + if (!rt_list_isempty(&mutex->parent.suspend_thread)) + { + thread = rt_list_entry(mutex->parent.suspend_thread.next, struct rt_thread, tlist); + mutex->priority = thread->current_priority; + } + else + { + mutex->priority = 0xff; + } + + return mutex->priority; +} + +/* get highest priority inside its taken object and its init priority */ +rt_inline rt_uint8_t _thread_get_mutex_priority(struct rt_thread* thread) +{ + rt_list_t *node = RT_NULL; + struct rt_mutex *mutex = RT_NULL; + rt_uint8_t priority = thread->init_priority; + + rt_list_for_each(node, &(thread->taken_object_list)) + { + mutex = rt_list_entry(node, struct rt_mutex, taken_list); + rt_uint8_t mutex_prio = mutex->priority; + /* prio at least be priority ceiling */ + mutex_prio = mutex_prio < mutex->ceiling_priority ? mutex_prio : mutex->ceiling_priority; + + if (priority > mutex_prio) + { + priority = mutex_prio; + } + } + + return priority; +} + +/* update priority of target thread and the thread suspended it if any */ +rt_inline void _thread_update_priority(struct rt_thread *thread, rt_uint8_t priority, int suspend_flag) +{ + rt_err_t ret; + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("thread:%s priority -> %d\n", thread->name, priority)); + + /* change priority of the thread */ + rt_thread_control(thread, + RT_THREAD_CTRL_CHANGE_PRIORITY, + &priority); + + if ((thread->stat & RT_THREAD_SUSPEND_MASK) == RT_THREAD_SUSPEND_MASK) + { + /* whether change the priority of taken mutex */ + struct rt_object* pending_obj = thread->pending_object; + + if (pending_obj && rt_object_get_type(pending_obj) == RT_Object_Class_Mutex) + { + rt_uint8_t mutex_priority; + struct rt_mutex* pending_mutex = (struct rt_mutex *)pending_obj; + + /* re-insert thread to suspended thread list */ + rt_list_remove(&(thread->tlist)); + + ret = _ipc_list_suspend(&(pending_mutex->parent.suspend_thread), + thread, + pending_mutex->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + /* TODO */ + return ; + } + + /* update priority */ + _mutex_update_priority(pending_mutex); + /* change the priority of mutex owner thread */ + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("mutex: %s priority -> %d\n", pending_mutex->parent.parent.name, + pending_mutex->priority)); + + mutex_priority = _thread_get_mutex_priority(pending_mutex->owner); + if (mutex_priority != pending_mutex->owner->current_priority) + { + _thread_update_priority(pending_mutex->owner, mutex_priority, suspend_flag); + } + } + } +} + +/** + * @addtogroup mutex + * @{ + */ + +/** + * @brief Initialize a static mutex object. + * + * @note For the static mutex object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_mutex_create() function will automatically allocate memory space + * and initialize the mutex. + * + * @see rt_mutex_create() + * + * @param mutex is a pointer to the mutex to initialize. It is assumed that storage for the mutex will be + * allocated in your application. + * + * @param name is a pointer to the name that given to the mutex. + * + * @param flag is the mutex flag, which determines the queuing way of how multiple threads wait + * when the mutex is not available. + * NOTE: This parameter has been obsoleted. It can be RT_IPC_FLAG_PRIO, RT_IPC_FLAG_FIFO or RT_NULL. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_mutex_init(rt_mutex_t mutex, const char *name, rt_uint8_t flag) +{ + /* flag parameter has been obsoleted */ + RT_UNUSED(flag); + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + + /* initialize object */ + rt_object_init(&(mutex->parent.parent), RT_Object_Class_Mutex, name); + + /* initialize ipc object */ + _ipc_object_init(&(mutex->parent)); + + mutex->owner = RT_NULL; + mutex->priority = 0xFF; + mutex->hold = 0; + mutex->ceiling_priority = 0xFF; + rt_list_init(&(mutex->taken_list)); + + /* flag can only be RT_IPC_FLAG_PRIO. RT_IPC_FLAG_FIFO cannot solve the unbounded priority inversion problem */ + mutex->parent.parent.flag = RT_IPC_FLAG_PRIO; + + return RT_EOK; +} +RTM_EXPORT(rt_mutex_init); + + +/** + * @brief This function will detach a static mutex object. + * + * @note This function is used to detach a static mutex object which is initialized by rt_mutex_init() function. + * By contrast, the rt_mutex_delete() function will delete a mutex object. + * When the mutex is successfully detached, it will resume all suspended threads in the mutex list. + * + * @see rt_mutex_delete() + * + * @param mutex is a pointer to a mutex object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the mutex detach failed. + * + * @warning This function can ONLY detach a static mutex initialized by the rt_mutex_init() function. + * If the mutex is created by the rt_mutex_create() function, you MUST NOT USE this function to detach it, + * ONLY USE the rt_mutex_delete() function to complete the deletion. + */ +rt_err_t rt_mutex_detach(rt_mutex_t mutex) +{ + rt_ubase_t level; + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + RT_ASSERT(rt_object_is_systemobject(&mutex->parent.parent)); + + level = rt_hw_interrupt_disable(); + /* wakeup all suspended threads */ + _ipc_list_resume_all(&(mutex->parent.suspend_thread)); + /* remove mutex from thread's taken list */ + rt_list_remove(&mutex->taken_list); + rt_hw_interrupt_enable(level); + + /* detach mutex object */ + rt_object_detach(&(mutex->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mutex_detach); + +/* drop a thread from the suspend list of mutex */ + +/** + * @brief drop a thread from the suspend list of mutex + * + * @param mutex is a pointer to a mutex object. + * @param thread is the thread should be dropped from mutex. + */ +void rt_mutex_drop_thread(rt_mutex_t mutex, rt_thread_t thread) +{ + rt_uint8_t priority; + rt_bool_t need_update = RT_FALSE; + + rt_list_remove(&(thread->tlist)); + + /* should change the priority of mutex owner thread */ + if (mutex->owner->current_priority == thread->current_priority) + need_update = RT_TRUE; + + /* update the priority of mutex */ + if (!rt_list_isempty(&mutex->parent.suspend_thread)) + { + /* more thread suspended in the list */ + struct rt_thread *th; + + th = rt_list_entry(mutex->parent.suspend_thread.next, + struct rt_thread, + tlist); + /* update the priority of mutex */ + mutex->priority = th->current_priority; + } + else + { + /* set mutex priority to maximal priority */ + mutex->priority = 0xff; + } + + /* try to change the priority of mutex owner thread */ + if (need_update) + { + /* get the maximal priority of mutex in thread */ + priority = _thread_get_mutex_priority(mutex->owner); + if (priority != mutex->owner->current_priority) + { + _thread_update_priority(mutex->owner, priority, RT_UNINTERRUPTIBLE); + } + } +} + + +/** + * @brief set the prioceiling attribute of the mutex. + * + * @param mutex is a pointer to a mutex object. + * @param priority is the priority should be set to mutex. + * + * @return return the old priority ceiling + */ +rt_uint8_t rt_mutex_setprioceiling(rt_mutex_t mutex, rt_uint8_t priority) +{ + rt_uint8_t ret_priority = 0xFF; + + if ((mutex) && (priority < RT_THREAD_PRIORITY_MAX)) + { + /* critical section here if multiple updates to one mutex happen */ + rt_ubase_t level = rt_hw_interrupt_disable(); + ret_priority = mutex->ceiling_priority; + mutex->ceiling_priority = priority; + if (mutex->owner) + { + rt_uint8_t priority = _thread_get_mutex_priority(mutex->owner); + if (priority != mutex->owner->current_priority) + _thread_update_priority(mutex->owner, priority, RT_UNINTERRUPTIBLE); + } + rt_hw_interrupt_enable(level); + } + else + { + rt_set_errno(-RT_EINVAL); + } + + return ret_priority; +} +RTM_EXPORT(rt_mutex_setprioceiling); + + +/** + * @brief set the prioceiling attribute of the mutex. + * + * @param mutex is a pointer to a mutex object. + * + * @return return the current priority ceiling of the mutex. + */ +rt_uint8_t rt_mutex_getprioceiling(rt_mutex_t mutex) +{ + rt_uint8_t prio = 0xFF; + + if (mutex) + { + prio = mutex->ceiling_priority; + } + + return prio; +} +RTM_EXPORT(rt_mutex_getprioceiling); + + +#ifdef RT_USING_HEAP +/** + * @brief This function will create a mutex object. + * + * @note For the mutex object, its memory space is automatically allocated. + * By contrast, the rt_mutex_init() function will initialize a static mutex object. + * + * @see rt_mutex_init() + * + * @param name is a pointer to the name that given to the mutex. + * + * @param flag is the mutex flag, which determines the queuing way of how multiple threads wait + * when the mutex is not available. + * NOTE: This parameter has been obsoleted. It can be RT_IPC_FLAG_PRIO, RT_IPC_FLAG_FIFO or RT_NULL. + * + * @return Return a pointer to the mutex object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_mutex_t rt_mutex_create(const char *name, rt_uint8_t flag) +{ + struct rt_mutex *mutex; + + /* flag parameter has been obsoleted */ + RT_UNUSED(flag); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + mutex = (rt_mutex_t)rt_object_allocate(RT_Object_Class_Mutex, name); + if (mutex == RT_NULL) + return mutex; + + /* initialize ipc object */ + _ipc_object_init(&(mutex->parent)); + + mutex->owner = RT_NULL; + mutex->priority = 0xFF; + mutex->hold = 0; + mutex->ceiling_priority = 0xFF; + rt_list_init(&(mutex->taken_list)); + + /* flag can only be RT_IPC_FLAG_PRIO. RT_IPC_FLAG_FIFO cannot solve the unbounded priority inversion problem */ + mutex->parent.parent.flag = RT_IPC_FLAG_PRIO; + + return mutex; +} +RTM_EXPORT(rt_mutex_create); + + +/** + * @brief This function will delete a mutex object and release this memory space. + * + * @note This function is used to delete a mutex object which is created by the rt_mutex_create() function. + * By contrast, the rt_mutex_detach() function will detach a static mutex object. + * When the mutex is successfully deleted, it will resume all suspended threads in the mutex list. + * + * @see rt_mutex_detach() + * + * @param mutex is a pointer to a mutex object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mutex detach failed. + * + * @warning This function can ONLY delete a mutex initialized by the rt_mutex_create() function. + * If the mutex is initialized by the rt_mutex_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_mutex_detach() function to complete the detachment. + */ +rt_err_t rt_mutex_delete(rt_mutex_t mutex) +{ + rt_ubase_t level; + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + RT_ASSERT(rt_object_is_systemobject(&mutex->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + level = rt_hw_interrupt_disable(); + /* wakeup all suspended threads */ + _ipc_list_resume_all(&(mutex->parent.suspend_thread)); + /* remove mutex from thread's taken list */ + rt_list_remove(&mutex->taken_list); + rt_hw_interrupt_enable(level); + + /* delete mutex object */ + rt_object_delete(&(mutex->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mutex_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will take a mutex, if the mutex is unavailable, the thread shall wait for + * the mutex up to a specified time. + * + * @note When this function is called, the count value of the mutex->value will decrease 1 until it is equal to 0. + * When the mutex->value is 0, it means that the mutex is unavailable. At this time, it will suspend the + * thread preparing to take the mutex. + * On the contrary, the rt_mutex_release() function will increase the count value of mutex->value by 1 each time. + * + * @see rt_mutex_trytake() + * + * @param mutex is a pointer to a mutex object. + * + * @param timeout is a timeout period (unit: an OS tick). If the mutex is unavailable, the thread will wait for + * the mutex up to the amount of time specified by the argument. + * NOTE: Generally, we set this parameter to RT_WAITING_FOREVER, which means that when the mutex is unavailable, + * the thread will be waitting forever. + * + * @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 mutex take failed. + * + * @warning This function can ONLY be called in the thread context. It MUST NOT BE called in interrupt context. + */ +static rt_err_t _rt_mutex_take(rt_mutex_t mutex, rt_int32_t timeout, int suspend_flag) +{ + rt_base_t level; + struct rt_thread *thread; + rt_err_t ret; + + /* this function must not be used in interrupt even if time = 0 */ + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE); + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + + /* get current thread */ + thread = rt_thread_self(); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(mutex->parent.parent))); + + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("mutex_take: current thread %s, hold: %d\n", + thread->name, mutex->hold)); + + /* reset thread error */ + thread->error = RT_EOK; + + if (mutex->owner == thread) + { + if(mutex->hold < RT_MUTEX_HOLD_MAX) + { + /* it's the same thread */ + mutex->hold ++; + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + } + else + { + /* whether the mutex has owner thread. */ + if (mutex->owner == RT_NULL) + { + /* set mutex owner and original priority */ + mutex->owner = thread; + mutex->priority = 0xff; + mutex->hold = 1; + + if (mutex->ceiling_priority != 0xFF) + { + /* set the priority of thread to the ceiling priority */ + if (mutex->ceiling_priority < mutex->owner->current_priority) + _thread_update_priority(mutex->owner, mutex->ceiling_priority, suspend_flag); + } + + /* insert mutex to thread's taken object list */ + rt_list_insert_after(&thread->taken_object_list, &mutex->taken_list); + } + else + { + /* no waiting, return with timeout */ + if (timeout == 0) + { + /* set error as timeout */ + thread->error = -RT_ETIMEOUT; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + else + { + rt_uint8_t priority = thread->current_priority; + + /* mutex is unavailable, push to suspend list */ + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mutex_take: suspend thread: %s\n", + thread->name)); + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mutex->parent.suspend_thread), + thread, + mutex->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* set pending object in thread to this mutex */ + thread->pending_object = &(mutex->parent.parent); + + /* update the priority level of mutex */ + if (priority < mutex->priority) + { + mutex->priority = priority; + if (mutex->priority < mutex->owner->current_priority) + { + _thread_update_priority(mutex->owner, priority, RT_UNINTERRUPTIBLE); /* TODO */ + } + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("mutex_take: start the timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do schedule */ + rt_schedule(); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + if (thread->error == RT_EOK) + { + /* get mutex successfully */ + } + else + { + /* the mutex has not been taken and thread has detach from the pending list. */ + + rt_bool_t need_update = RT_FALSE; + + /* should change the priority of mutex owner thread */ + if (mutex->owner->current_priority == thread->current_priority) + need_update = RT_TRUE; + + /* update the priority of mutex */ + if (!rt_list_isempty(&mutex->parent.suspend_thread)) + { + /* more thread suspended in the list */ + struct rt_thread *th; + + th = rt_list_entry(mutex->parent.suspend_thread.next, + struct rt_thread, + tlist); + /* update the priority of mutex */ + mutex->priority = th->current_priority; + } + else + { + /* set mutex priority to maximal priority */ + mutex->priority = 0xff; + } + + /* try to change the priority of mutex owner thread */ + if (need_update) + { + /* get the maximal priority of mutex in thread */ + priority = _thread_get_mutex_priority(mutex->owner); + if (priority != mutex->owner->current_priority) + { + _thread_update_priority(mutex->owner, priority, RT_UNINTERRUPTIBLE); + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* return error */ + return thread->error; + } + } + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mutex->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_mutex_take(rt_mutex_t mutex, rt_int32_t time) +{ + return _rt_mutex_take(mutex, time, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mutex_take); + +rt_err_t rt_mutex_take_interruptible(rt_mutex_t mutex, rt_int32_t time) +{ + return _rt_mutex_take(mutex, time, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mutex_take_interruptible); + +rt_err_t rt_mutex_take_killable(rt_mutex_t mutex, rt_int32_t time) +{ + return _rt_mutex_take(mutex, time, RT_KILLABLE); +} +RTM_EXPORT(rt_mutex_take_killable); + +/** + * @brief This function will try to take a mutex, if the mutex is unavailable, the thread returns immediately. + * + * @note This function is very similar to the rt_mutex_take() function, when the mutex is not available, + * except that rt_mutex_trytake() will return immediately without waiting for a timeout + * when the mutex is not available. + * In other words, rt_mutex_trytake(mutex) has the same effect as rt_mutex_take(mutex, 0). + * + * @see rt_mutex_take() + * + * @param mutex is a pointer to a mutex object. + * + * @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 mutex take failed. + */ +rt_err_t rt_mutex_trytake(rt_mutex_t mutex) +{ + return rt_mutex_take(mutex, RT_WAITING_NO); +} +RTM_EXPORT(rt_mutex_trytake); + + +/** + * @brief This function will release a mutex. If there is thread suspended on the mutex, the thread will be resumed. + * + * @note If there are threads suspended on this mutex, the first thread in the list of this mutex object + * will be resumed, and a thread scheduling (rt_schedule) will be executed. + * If no threads are suspended on this mutex, the count value mutex->value of this mutex will increase by 1. + * + * @param mutex is a pointer to a mutex object. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mutex release failed. + */ +rt_err_t rt_mutex_release(rt_mutex_t mutex) +{ + rt_base_t level; + struct rt_thread *thread; + rt_bool_t need_schedule; + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + + need_schedule = RT_FALSE; + + /* only thread could release mutex because we need test the ownership */ + RT_DEBUG_IN_THREAD_CONTEXT; + + /* get current thread */ + thread = rt_thread_self(); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("mutex_release:current thread %s, hold: %d\n", + thread->name, mutex->hold)); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mutex->parent.parent))); + + /* mutex only can be released by owner */ + if (thread != mutex->owner) + { + thread->error = -RT_ERROR; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_ERROR; + } + + /* decrease hold */ + mutex->hold --; + /* if no hold */ + if (mutex->hold == 0) + { + /* remove mutex from thread's taken list */ + rt_list_remove(&mutex->taken_list); + + /* whether change the thread priority */ + if ((mutex->ceiling_priority != 0xFF) || (thread->current_priority == mutex->priority)) + { + rt_uint8_t priority = 0xff; + + /* get the highest priority in the taken list of thread */ + priority = _thread_get_mutex_priority(thread); + + rt_thread_control(thread, + RT_THREAD_CTRL_CHANGE_PRIORITY, + &priority); + + need_schedule = RT_TRUE; + } + + /* wakeup suspended thread */ + if (!rt_list_isempty(&mutex->parent.suspend_thread)) + { + /* get the first suspended thread */ + struct rt_thread *next_thread = rt_list_entry(mutex->parent.suspend_thread.next, + struct rt_thread, + tlist); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mutex_release: resume thread: %s\n", + next_thread->name)); + + /* remove the thread from the suspended list of mutex */ + rt_list_remove(&(next_thread->tlist)); + + /* set new owner and put mutex into taken list of thread */ + mutex->owner = next_thread; + mutex->hold = 1; + rt_list_insert_after(&next_thread->taken_object_list, &mutex->taken_list); + /* cleanup pending object */ + next_thread->pending_object = RT_NULL; + + /* resume thread */ + rt_thread_resume(next_thread); + + /* update mutex priority */ + if (!rt_list_isempty(&(mutex->parent.suspend_thread))) + { + struct rt_thread *th; + + th = rt_list_entry(mutex->parent.suspend_thread.next, + struct rt_thread, + tlist); + mutex->priority = th->current_priority; + } + else + { + mutex->priority = 0xff; + } + + need_schedule = RT_TRUE; + } + else + { + /* clear owner */ + mutex->owner = RT_NULL; + mutex->priority = 0xff; + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* perform a schedule */ + if (need_schedule == RT_TRUE) + rt_schedule(); + + return RT_EOK; +} +RTM_EXPORT(rt_mutex_release); + + +/** + * @brief This function will set some extra attributions of a mutex object. + * + * @note Currently this function does not implement the control function. + * + * @param mutex is a pointer to a mutex object. + * + * @param cmd is a command word used to configure some attributions of the mutex. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_mutex_control(rt_mutex_t mutex, int cmd, void *arg) +{ + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + + return -RT_ERROR; +} +RTM_EXPORT(rt_mutex_control); + +/**@}*/ +#endif /* RT_USING_MUTEX */ + +#ifdef RT_USING_EVENT +/** + * @addtogroup event + * @{ + */ + +/** + * @brief The function will initialize a static event object. + * + * @note For the static event object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_event_create() function will allocate memory space automatically + * and initialize the event. + * + * @see rt_event_create() + * + * @param event is a pointer to the event to initialize. It is assumed that storage for the event + * will be allocated in your application. + * + * @param name is a pointer to the name that given to the event. + * + * @param flag is the event flag, which determines the queuing way of how multiple threads wait + * when the event is not available. + * The event flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this event will become non-real-time threads. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_event_init(rt_event_t event, const char *name, rt_uint8_t flag) +{ + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(event->parent.parent), RT_Object_Class_Event, name); + + /* set parent flag */ + event->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(event->parent)); + + /* initialize event */ + event->set = 0; + + return RT_EOK; +} +RTM_EXPORT(rt_event_init); + + +/** + * @brief This function will detach a static event object. + * + * @note This function is used to detach a static event object which is initialized by rt_event_init() function. + * By contrast, the rt_event_delete() function will delete an event object. + * When the event is successfully detached, it will resume all suspended threads in the event list. + * + * @see rt_event_delete() + * + * @param event is a pointer to an event object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the event detach failed. + * + * @warning This function can ONLY detach a static event initialized by the rt_event_init() function. + * If the event is created by the rt_event_create() function, you MUST NOT USE this function to detach it, + * ONLY USE the rt_event_delete() function to complete the deletion. + */ +rt_err_t rt_event_detach(rt_event_t event) +{ + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + RT_ASSERT(rt_object_is_systemobject(&event->parent.parent)); + + /* resume all suspended thread */ + _ipc_list_resume_all(&(event->parent.suspend_thread)); + + /* detach event object */ + rt_object_detach(&(event->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_event_detach); + +#ifdef RT_USING_HEAP +/** + * @brief Creating an event object. + * + * @note For the event object, its memory space is allocated automatically. + * By contrast, the rt_event_init() function will initialize a static event object. + * + * @see rt_event_init() + * + * @param name is a pointer to the name that given to the event. + * + * @param flag is the event flag, which determines the queuing way of how multiple threads wait when the event + * is not available. + * The event flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this event will become non-real-time threads. + * + * @return Return a pointer to the event object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_event_t rt_event_create(const char *name, rt_uint8_t flag) +{ + rt_event_t event; + + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + event = (rt_event_t)rt_object_allocate(RT_Object_Class_Event, name); + if (event == RT_NULL) + return event; + + /* set parent */ + event->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(event->parent)); + + /* initialize event */ + event->set = 0; + + return event; +} +RTM_EXPORT(rt_event_create); + + +/** + * @brief This function will delete an event object and release the memory space. + * + * @note This function is used to delete an event object which is created by the rt_event_create() function. + * By contrast, the rt_event_detach() function will detach a static event object. + * When the event is successfully deleted, it will resume all suspended threads in the event list. + * + * @see rt_event_detach() + * + * @param event is a pointer to an event object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the event detach failed. + * + * @warning This function can ONLY delete an event initialized by the rt_event_create() function. + * If the event is initialized by the rt_event_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_event_detach() function to complete the detachment. + */ +rt_err_t rt_event_delete(rt_event_t event) +{ + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + RT_ASSERT(rt_object_is_systemobject(&event->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* resume all suspended thread */ + _ipc_list_resume_all(&(event->parent.suspend_thread)); + + /* delete event object */ + rt_object_delete(&(event->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_event_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will send an event to the event object. + * If there is a thread suspended on the event, the thread will be resumed. + * + * @note When using this function, you need to use the parameter (set) to specify the event flag of the event object, + * then the function will traverse the list of suspended threads waiting on the event object. + * If there is a thread suspended on the event, and the thread's event_info and the event flag of + * the current event object matches, the thread will be resumed. + * + * @param event is a pointer to the event object to be sent. + * + * @param set is a flag that you will set for this event's flag. + * You can set an event flag, or you can set multiple flags through OR logic operation. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the event detach failed. + */ +rt_err_t rt_event_send(rt_event_t event, rt_uint32_t set) +{ + struct rt_list_node *n; + struct rt_thread *thread; + rt_base_t level; + rt_base_t status; + rt_bool_t need_schedule; + + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + + if (set == 0) + return -RT_ERROR; + + need_schedule = RT_FALSE; + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* set event */ + event->set |= set; + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(event->parent.parent))); + + if (!rt_list_isempty(&event->parent.suspend_thread)) + { + /* search thread list to resume thread */ + n = event->parent.suspend_thread.next; + while (n != &(event->parent.suspend_thread)) + { + /* get thread */ + thread = rt_list_entry(n, struct rt_thread, tlist); + + status = -RT_ERROR; + if (thread->event_info & RT_EVENT_FLAG_AND) + { + if ((thread->event_set & event->set) == thread->event_set) + { + /* received an AND event */ + status = RT_EOK; + } + } + else if (thread->event_info & RT_EVENT_FLAG_OR) + { + if (thread->event_set & event->set) + { + /* save the received event set */ + thread->event_set = thread->event_set & event->set; + + /* received an OR event */ + status = RT_EOK; + } + } + else + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EINVAL; + } + + /* move node to the next */ + n = n->next; + + /* condition is satisfied, resume thread */ + if (status == RT_EOK) + { + /* clear event */ + if (thread->event_info & RT_EVENT_FLAG_CLEAR) + event->set &= ~thread->event_set; + + /* resume thread, and thread list breaks out */ + rt_thread_resume(thread); + thread->error = RT_EOK; + + /* need do a scheduling */ + need_schedule = RT_TRUE; + } + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do a schedule */ + if (need_schedule == RT_TRUE) + rt_schedule(); + + return RT_EOK; +} +RTM_EXPORT(rt_event_send); + + +/** + * @brief This function will receive an event from event object. if the event is unavailable, the thread shall wait for + * the event up to a specified time. + * + * @note If there are threads suspended on this semaphore, the first thread in the list of this semaphore object + * will be resumed, and a thread scheduling (rt_schedule) will be executed. + * If no threads are suspended on this semaphore, the count value sem->value of this semaphore will increase by 1. + * + * @param event is a pointer to the event object to be received. + * + * @param set is a flag that you will set for this event's flag. + * You can set an event flag, or you can set multiple flags through OR logic operation. + * + * @param option is the option of this receiving event, it indicates how the receiving event is operated. + * The option can be one or more of the following values, When selecting multiple values,use logical OR to operate. + * (NOTE: RT_EVENT_FLAG_OR and RT_EVENT_FLAG_AND can only select one): + * + * + * RT_EVENT_FLAG_OR The thread select to use logical OR to receive the event. + * + * RT_EVENT_FLAG_AND The thread select to use logical OR to receive the event. + * + * RT_EVENT_FLAG_CLEAR When the thread receives the corresponding event, the function + * determines whether to clear the event flag. + * + * @param timeout is a timeout period (unit: an OS tick). + * + * @param recved is a pointer to the received event. If you don't care about this value, you can use RT_NULL to set. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the semaphore release failed. + */ +static rt_err_t _rt_event_recv(rt_event_t event, + rt_uint32_t set, + rt_uint8_t option, + rt_int32_t timeout, + rt_uint32_t *recved, + int suspend_flag) +{ + struct rt_thread *thread; + rt_base_t level; + rt_base_t status; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE); + + if (set == 0) + return -RT_ERROR; + + /* initialize status */ + status = -RT_ERROR; + /* get current thread */ + thread = rt_thread_self(); + /* reset thread error */ + thread->error = -RT_EINTR; + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(event->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* check event set */ + if (option & RT_EVENT_FLAG_AND) + { + if ((event->set & set) == set) + status = RT_EOK; + } + else if (option & RT_EVENT_FLAG_OR) + { + if (event->set & set) + status = RT_EOK; + } + else + { + /* either RT_EVENT_FLAG_AND or RT_EVENT_FLAG_OR should be set */ + RT_ASSERT(0); + } + + if (status == RT_EOK) + { + thread->error = RT_EOK; + + /* set received event */ + if (recved) + *recved = (event->set & set); + + /* fill thread event info */ + thread->event_set = (event->set & set); + thread->event_info = option; + + /* received event */ + if (option & RT_EVENT_FLAG_CLEAR) + event->set &= ~set; + } + else if (timeout == 0) + { + /* no waiting */ + thread->error = -RT_ETIMEOUT; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + else + { + /* fill thread event info */ + thread->event_set = set; + thread->event_info = option; + + /* put thread to suspended thread list */ + ret = _ipc_list_suspend(&(event->parent.suspend_thread), + thread, + event->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* if there is a waiting timeout, active thread timer */ + if (timeout > 0) + { + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do a schedule */ + rt_schedule(); + + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* received an event, disable interrupt to protect */ + level = rt_hw_interrupt_disable(); + + /* set received event */ + if (recved) + *recved = thread->event_set; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(event->parent.parent))); + + return thread->error; +} + +rt_err_t rt_event_recv(rt_event_t event, + rt_uint32_t set, + rt_uint8_t option, + rt_int32_t timeout, + rt_uint32_t *recved) +{ + return _rt_event_recv(event, set, option, timeout, recved, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_event_recv); + +rt_err_t rt_event_recv_interruptible(rt_event_t event, + rt_uint32_t set, + rt_uint8_t option, + rt_int32_t timeout, + rt_uint32_t *recved) +{ + return _rt_event_recv(event, set, option, timeout, recved, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_event_recv_interruptible); + +rt_err_t rt_event_recv_killable(rt_event_t event, + rt_uint32_t set, + rt_uint8_t option, + rt_int32_t timeout, + rt_uint32_t *recved) +{ + return _rt_event_recv(event, set, option, timeout, recved, RT_KILLABLE); +} +RTM_EXPORT(rt_event_recv_killable); +/** + * @brief This function will set some extra attributions of an event object. + * + * @note Currently this function only supports the RT_IPC_CMD_RESET command to reset the event. + * + * @param event is a pointer to an event object. + * + * @param cmd is a command word used to configure some attributions of the event. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_event_control(rt_event_t event, int cmd, void *arg) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + + if (cmd == RT_IPC_CMD_RESET) + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* resume all waiting thread */ + _ipc_list_resume_all(&event->parent.suspend_thread); + + /* initialize event set */ + event->set = 0; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_event_control); + +/**@}*/ +#endif /* RT_USING_EVENT */ + +#ifdef RT_USING_MAILBOX +/** + * @addtogroup mailbox + * @{ + */ + +/** + * @brief Initialize a static mailbox object. + * + * @note For the static mailbox object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_mb_create() function will allocate memory space automatically and initialize the mailbox. + * + * @see rt_mb_create() + * + * @param mb is a pointer to the mailbox to initialize. + * It is assumed that storage for the mailbox will be allocated in your application. + * + * @param name is a pointer to the name that given to the mailbox. + * + * @param msgpool the begin address of buffer to save received mail. + * + * @param size is the maximum number of mails in the mailbox. + * For example, when the mailbox buffer capacity is N, size is N/4. + * + * @param flag is the mailbox flag, which determines the queuing way of how multiple threads wait + * when the mailbox is not available. + * The mailbox flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this mailbox will become non-real-time threads. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_mb_init(rt_mailbox_t mb, + const char *name, + void *msgpool, + rt_size_t size, + rt_uint8_t flag) +{ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(mb->parent.parent), RT_Object_Class_MailBox, name); + + /* set parent flag */ + mb->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(mb->parent)); + + /* initialize mailbox */ + mb->msg_pool = (rt_ubase_t *)msgpool; + mb->size = (rt_uint16_t)size; + mb->entry = 0; + mb->in_offset = 0; + mb->out_offset = 0; + + /* initialize an additional list of sender suspend thread */ + rt_list_init(&(mb->suspend_sender_thread)); + + return RT_EOK; +} +RTM_EXPORT(rt_mb_init); + + +/** + * @brief This function will detach a static mailbox object. + * + * @note This function is used to detach a static mailbox object which is initialized by rt_mb_init() function. + * By contrast, the rt_mb_delete() function will delete a mailbox object. + * When the mailbox is successfully detached, it will resume all suspended threads in the mailbox list. + * + * @see rt_mb_delete() + * + * @param mb is a pointer to a mailbox object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the mailbox detach failed. + * + * @warning This function can ONLY detach a static mailbox initialized by the rt_mb_init() function. + * If the mailbox is created by the rt_mb_create() function, you MUST NOT USE this function to detach it, + * ONLY USE the rt_mb_delete() function to complete the deletion. + */ +rt_err_t rt_mb_detach(rt_mailbox_t mb) +{ + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + RT_ASSERT(rt_object_is_systemobject(&mb->parent.parent)); + + /* resume all suspended thread */ + _ipc_list_resume_all(&(mb->parent.suspend_thread)); + /* also resume all mailbox private suspended thread */ + _ipc_list_resume_all(&(mb->suspend_sender_thread)); + + /* detach mailbox object */ + rt_object_detach(&(mb->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mb_detach); + +#ifdef RT_USING_HEAP +/** + * @brief Creating a mailbox object. + * + * @note For the mailbox object, its memory space is allocated automatically. + * By contrast, the rt_mb_init() function will initialize a static mailbox object. + * + * @see rt_mb_init() + * + * @param name is a pointer that given to the mailbox. + * + * @param size is the maximum number of mails in the mailbox. + * For example, when mailbox buffer capacity is N, size is N/4. + * + * @param flag is the mailbox flag, which determines the queuing way of how multiple threads wait + * when the mailbox is not available. + * The mailbox flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this mailbox will become non-real-time threads. + * + * @return Return a pointer to the mailbox object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_mailbox_t rt_mb_create(const char *name, rt_size_t size, rt_uint8_t flag) +{ + rt_mailbox_t mb; + + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + mb = (rt_mailbox_t)rt_object_allocate(RT_Object_Class_MailBox, name); + if (mb == RT_NULL) + return mb; + + /* set parent */ + mb->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(mb->parent)); + + /* initialize mailbox */ + mb->size = (rt_uint16_t)size; + mb->msg_pool = (rt_ubase_t *)RT_KERNEL_MALLOC(mb->size * sizeof(rt_ubase_t)); + if (mb->msg_pool == RT_NULL) + { + /* delete mailbox object */ + rt_object_delete(&(mb->parent.parent)); + + return RT_NULL; + } + mb->entry = 0; + mb->in_offset = 0; + mb->out_offset = 0; + + /* initialize an additional list of sender suspend thread */ + rt_list_init(&(mb->suspend_sender_thread)); + + return mb; +} +RTM_EXPORT(rt_mb_create); + + +/** + * @brief This function will delete a mailbox object and release the memory space. + * + * @note This function is used to delete a mailbox object which is created by the rt_mb_create() function. + * By contrast, the rt_mb_detach() function will detach a static mailbox object. + * When the mailbox is successfully deleted, it will resume all suspended threads in the mailbox list. + * + * @see rt_mb_detach() + * + * @param mb is a pointer to a mailbox object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + * + * @warning This function can only delete mailbox created by the rt_mb_create() function. + * If the mailbox is initialized by the rt_mb_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_mb_detach() function to complete the detachment. + */ +rt_err_t rt_mb_delete(rt_mailbox_t mb) +{ + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + RT_ASSERT(rt_object_is_systemobject(&mb->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* resume all suspended thread */ + _ipc_list_resume_all(&(mb->parent.suspend_thread)); + + /* also resume all mailbox private suspended thread */ + _ipc_list_resume_all(&(mb->suspend_sender_thread)); + + /* free mailbox pool */ + RT_KERNEL_FREE(mb->msg_pool); + + /* delete mailbox object */ + rt_object_delete(&(mb->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mb_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will send an mail to the mailbox object. If there is a thread suspended on the mailbox, + * the thread will be resumed. + * + * @note When using this function to send a mail, if the mailbox if fully used, the current thread will + * wait for a timeout. If the set timeout time is reached and there is still no space available, + * the sending thread will be resumed and an error code will be returned. + * By contrast, the rt_mb_send() function will return an error code immediately without waiting time + * when the mailbox if fully used. + * + * @see rt_mb_send() + * + * @param mb is a pointer to the mailbox object to be sent. + * + * @param value is a value to the content of the mail you want to send. + * + * @param timeout is a timeout period (unit: an OS tick). + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + * + * @warning This function can be called in interrupt context and thread context. + */ +static rt_err_t _rt_mb_send_wait(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout, + int suspend_flag) +{ + struct rt_thread *thread; + rt_base_t level; + rt_uint32_t tick_delta; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0); + + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mb->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* for non-blocking call */ + if (mb->entry == mb->size && timeout == 0) + { + rt_hw_interrupt_enable(level); + return -RT_EFULL; + } + + /* mailbox is full */ + while (mb->entry == mb->size) + { + /* reset error number in thread */ + thread->error = -RT_EINTR; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EFULL; + } + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mb->suspend_sender_thread), + thread, + mb->parent.parent.flag, + suspend_flag); + + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mb_send_wait: start timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* re-schedule */ + rt_schedule(); + + /* resume from suspend state */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + + /* set ptr */ + mb->msg_pool[mb->in_offset] = value; + /* increase input offset */ + ++ mb->in_offset; + if (mb->in_offset >= mb->size) + mb->in_offset = 0; + + if(mb->entry < RT_MB_ENTRY_MAX) + { + /* increase message entry */ + mb->entry ++; + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + + /* resume suspended thread */ + if (!rt_list_isempty(&mb->parent.suspend_thread)) + { + _ipc_list_resume(&(mb->parent.suspend_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} + +rt_err_t rt_mb_send_wait(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout) +{ + return _rt_mb_send_wait(mb, value, timeout, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mb_send_wait); + +rt_err_t rt_mb_send_wait_interruptible(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout) +{ + return _rt_mb_send_wait(mb, value, timeout, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mb_send_wait_interruptible); + +rt_err_t rt_mb_send_wait_killable(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout) +{ + return _rt_mb_send_wait(mb, value, timeout, RT_KILLABLE); +} +RTM_EXPORT(rt_mb_send_wait_killable); +/** + * @brief This function will send an mail to the mailbox object. If there is a thread suspended on the mailbox, + * the thread will be resumed. + * + * @note When using this function to send a mail, if the mailbox is fully used, this function will return an error + * code immediately without waiting time. + * By contrast, the rt_mb_send_wait() function is set a timeout to wait for the mail to be sent. + * + * @see rt_mb_send_wait() + * + * @param mb is a pointer to the mailbox object to be sent. + * + * @param value is a value to the content of the mail you want to send. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + */ +rt_err_t rt_mb_send(rt_mailbox_t mb, rt_ubase_t value) +{ + return rt_mb_send_wait(mb, value, 0); +} +RTM_EXPORT(rt_mb_send); + +rt_err_t rt_mb_send_interruptible(rt_mailbox_t mb, rt_ubase_t value) +{ + return rt_mb_send_wait_interruptible(mb, value, 0); +} +RTM_EXPORT(rt_mb_send_interruptible); + +rt_err_t rt_mb_send_killable(rt_mailbox_t mb, rt_ubase_t value) +{ + return rt_mb_send_wait_killable(mb, value, 0); +} +RTM_EXPORT(rt_mb_send_killable); + +/** + * @brief This function will send an urgent mail to the mailbox object. + * + * @note This function is almost the same as the rt_mb_send() function. The only difference is that + * when sending an urgent mail, the mail will be placed at the head of the mail queue so that + * the recipient can receive the urgent mail first. + * + * @see rt_mb_send() + * + * @param mb is a pointer to the mailbox object to be sent. + * + * @param value is the content of the mail you want to send. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + */ +rt_err_t rt_mb_urgent(rt_mailbox_t mb, rt_ubase_t value) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mb->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + if (mb->entry == mb->size) + { + rt_hw_interrupt_enable(level); + return -RT_EFULL; + } + + /* rewind to the previous position */ + if (mb->out_offset > 0) + { + mb->out_offset --; + } + else + { + mb->out_offset = mb->size - 1; + } + + /* set ptr */ + mb->msg_pool[mb->out_offset] = value; + + /* increase message entry */ + mb->entry ++; + + /* resume suspended thread */ + if (!rt_list_isempty(&mb->parent.suspend_thread)) + { + _ipc_list_resume(&(mb->parent.suspend_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} +RTM_EXPORT(rt_mb_urgent); + + +/** + * @brief This function will receive a mail from mailbox object, if there is no mail in mailbox object, + * the thread shall wait for a specified time. + * + * @note Only when there is mail in the mailbox, the receiving thread can get the mail immediately and + * return RT_EOK, otherwise the receiving thread will be suspended until the set timeout. If the mail + * is still not received within the specified time, it will return-RT_ETIMEOUT. + * + * @param mb is a pointer to the mailbox object to be received. + * + * @param value is a flag that you will set for this mailbox's flag. + * You can set an mailbox flag, or you can set multiple flags through OR logic operations. + * + * @param timeout is a timeout period (unit: an OS tick). If the mailbox object is not avaliable in the queue, + * the thread will wait for the object in the queue up to the amount of time specified by this parameter. + * + * NOTE: + * If use Macro RT_WAITING_FOREVER to set this parameter, which means that when the + * mailbox object is unavailable in the queue, the thread will be waiting forever. + * If use macro RT_WAITING_NO to set this parameter, which means that this + * function is non-blocking and will return immediately. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox release failed. + */ +static rt_err_t _rt_mb_recv(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout, int suspend_flag) +{ + struct rt_thread *thread; + rt_base_t level; + rt_uint32_t tick_delta; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0); + + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(mb->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* for non-blocking call */ + if (mb->entry == 0 && timeout == 0) + { + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + + /* mailbox is empty */ + while (mb->entry == 0) + { + /* reset error number in thread */ + thread->error = -RT_EINTR; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + thread->error = -RT_ETIMEOUT; + + return -RT_ETIMEOUT; + } + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mb->parent.suspend_thread), + thread, + mb->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mb_recv: start timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* re-schedule */ + rt_schedule(); + + /* resume from suspend state */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + + /* fill ptr */ + *value = mb->msg_pool[mb->out_offset]; + + /* increase output offset */ + ++ mb->out_offset; + if (mb->out_offset >= mb->size) + mb->out_offset = 0; + + /* decrease message entry */ + if(mb->entry > 0) + { + mb->entry --; + } + + /* resume suspended thread */ + if (!rt_list_isempty(&(mb->suspend_sender_thread))) + { + _ipc_list_resume(&(mb->suspend_sender_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mb->parent.parent))); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mb->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_mb_recv(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout) +{ + return _rt_mb_recv(mb, value, timeout, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mb_recv); + +rt_err_t rt_mb_recv_interruptibale(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout) +{ + return _rt_mb_recv(mb, value, timeout, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mb_recv_interruptibale); + +rt_err_t rt_mb_recv_killable(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout) +{ + return _rt_mb_recv(mb, value, timeout, RT_KILLABLE); +} +RTM_EXPORT(rt_mb_recv_killable); + +/** + * @brief This function will set some extra attributions of a mailbox object. + * + * @note Currently this function only supports the RT_IPC_CMD_RESET command to reset the mailbox. + * + * @param mb is a pointer to a mailbox object. + * + * @param cmd is a command used to configure some attributions of the mailbox. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_mb_control(rt_mailbox_t mb, int cmd, void *arg) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + + if (cmd == RT_IPC_CMD_RESET) + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* resume all waiting thread */ + _ipc_list_resume_all(&(mb->parent.suspend_thread)); + /* also resume all mailbox private suspended thread */ + _ipc_list_resume_all(&(mb->suspend_sender_thread)); + + /* re-init mailbox */ + mb->entry = 0; + mb->in_offset = 0; + mb->out_offset = 0; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_mb_control); + +/**@}*/ +#endif /* RT_USING_MAILBOX */ + +#ifdef RT_USING_MESSAGEQUEUE +/** + * @addtogroup messagequeue + * @{ + */ + +struct rt_mq_message +{ + struct rt_mq_message *next; +}; + + +/** + * @brief Initialize a static messagequeue object. + * + * @note For the static messagequeue object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_mq_create() function will allocate memory space automatically + * and initialize the messagequeue. + * + * @see rt_mq_create() + * + * @param mq is a pointer to the messagequeue to initialize. It is assumed that storage for + * the messagequeue will be allocated in your application. + * + * @param name is a pointer to the name that given to the messagequeue. + * + * @param msgpool is a pointer to the starting address of the memory space you allocated for + * the messagequeue in advance. + * In other words, msgpool is a pointer to the messagequeue buffer of the starting address. + * + * @param msg_size is the maximum length of a message in the messagequeue (Unit: Byte). + * + * @param pool_size is the size of the memory space allocated for the messagequeue in advance. + * + * @param flag is the messagequeue flag, which determines the queuing way of how multiple threads wait + * when the messagequeue is not available. + * The messagequeue flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this messagequeue will become non-real-time threads. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_mq_init(rt_mq_t mq, + const char *name, + void *msgpool, + rt_size_t msg_size, + rt_size_t pool_size, + rt_uint8_t flag) +{ + struct rt_mq_message *head; + rt_base_t temp; + register rt_size_t msg_align_size; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(mq->parent.parent), RT_Object_Class_MessageQueue, name); + + /* set parent flag */ + mq->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(mq->parent)); + + /* set message pool */ + mq->msg_pool = msgpool; + + /* get correct message size */ + msg_align_size = RT_ALIGN(msg_size, RT_ALIGN_SIZE); + mq->msg_size = msg_size; + mq->max_msgs = pool_size / (msg_align_size + sizeof(struct rt_mq_message)); + + if (0 == mq->max_msgs) + { + return -RT_EINVAL; + } + + /* initialize message list */ + mq->msg_queue_head = RT_NULL; + mq->msg_queue_tail = RT_NULL; + + /* initialize message empty list */ + mq->msg_queue_free = RT_NULL; + for (temp = 0; temp < mq->max_msgs; temp ++) + { + head = (struct rt_mq_message *)((rt_uint8_t *)mq->msg_pool + + temp * (msg_align_size + sizeof(struct rt_mq_message))); + head->next = (struct rt_mq_message *)mq->msg_queue_free; + mq->msg_queue_free = head; + } + + /* the initial entry is zero */ + mq->entry = 0; + + /* initialize an additional list of sender suspend thread */ + rt_list_init(&(mq->suspend_sender_thread)); + + return RT_EOK; +} +RTM_EXPORT(rt_mq_init); + + +/** + * @brief This function will detach a static messagequeue object. + * + * @note This function is used to detach a static messagequeue object which is initialized by rt_mq_init() function. + * By contrast, the rt_mq_delete() function will delete a messagequeue object. + * When the messagequeue is successfully detached, it will resume all suspended threads in the messagequeue list. + * + * @see rt_mq_delete() + * + * @param mq is a pointer to a messagequeue object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the messagequeue detach failed. + * + * @warning This function can ONLY detach a static messagequeue initialized by the rt_mq_init() function. + * If the messagequeue is created by the rt_mq_create() function, you MUST NOT USE this function to detach it, + * and ONLY USE the rt_mq_delete() function to complete the deletion. + */ +rt_err_t rt_mq_detach(rt_mq_t mq) +{ + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(rt_object_is_systemobject(&mq->parent.parent)); + + /* resume all suspended thread */ + _ipc_list_resume_all(&mq->parent.suspend_thread); + /* also resume all message queue private suspended thread */ + _ipc_list_resume_all(&(mq->suspend_sender_thread)); + + /* detach message queue object */ + rt_object_detach(&(mq->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mq_detach); + +#ifdef RT_USING_HEAP +/** + * @brief Creating a messagequeue object. + * + * @note For the messagequeue object, its memory space is allocated automatically. + * By contrast, the rt_mq_init() function will initialize a static messagequeue object. + * + * @see rt_mq_init() + * + * @param name is a pointer that given to the messagequeue. + * + * @param msg_size is the maximum length of a message in the messagequeue (Unit: Byte). + * + * @param max_msgs is the maximum number of messages in the messagequeue. + * + * @param flag is the messagequeue flag, which determines the queuing way of how multiple threads wait + * when the messagequeue is not available. + * The messagequeue flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this messagequeue will become non-real-time threads. + * + * @return Return a pointer to the messagequeue object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can NOT be called in interrupt context. You can use macor RT_DEBUG_NOT_IN_INTERRUPT to check it. + */ +rt_mq_t rt_mq_create(const char *name, + rt_size_t msg_size, + rt_size_t max_msgs, + rt_uint8_t flag) +{ + struct rt_messagequeue *mq; + struct rt_mq_message *head; + rt_base_t temp; + register rt_size_t msg_align_size; + + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + mq = (rt_mq_t)rt_object_allocate(RT_Object_Class_MessageQueue, name); + if (mq == RT_NULL) + return mq; + + /* set parent */ + mq->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(mq->parent)); + + /* initialize message queue */ + + /* get correct message size */ + msg_align_size = RT_ALIGN(msg_size, RT_ALIGN_SIZE); + mq->msg_size = msg_size; + mq->max_msgs = max_msgs; + + /* allocate message pool */ + mq->msg_pool = RT_KERNEL_MALLOC((msg_align_size + sizeof(struct rt_mq_message)) * mq->max_msgs); + if (mq->msg_pool == RT_NULL) + { + rt_object_delete(&(mq->parent.parent)); + + return RT_NULL; + } + + /* initialize message list */ + mq->msg_queue_head = RT_NULL; + mq->msg_queue_tail = RT_NULL; + + /* initialize message empty list */ + mq->msg_queue_free = RT_NULL; + for (temp = 0; temp < mq->max_msgs; temp ++) + { + head = (struct rt_mq_message *)((rt_uint8_t *)mq->msg_pool + + temp * (msg_align_size + sizeof(struct rt_mq_message))); + head->next = (struct rt_mq_message *)mq->msg_queue_free; + mq->msg_queue_free = head; + } + + /* the initial entry is zero */ + mq->entry = 0; + + /* initialize an additional list of sender suspend thread */ + rt_list_init(&(mq->suspend_sender_thread)); + + return mq; +} +RTM_EXPORT(rt_mq_create); + + +/** + * @brief This function will delete a messagequeue object and release the memory. + * + * @note This function is used to delete a messagequeue object which is created by the rt_mq_create() function. + * By contrast, the rt_mq_detach() function will detach a static messagequeue object. + * When the messagequeue is successfully deleted, it will resume all suspended threads in the messagequeue list. + * + * @see rt_mq_detach() + * + * @param mq is a pointer to a messagequeue object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the messagequeue detach failed. + * + * @warning This function can ONLY delete a messagequeue initialized by the rt_mq_create() function. + * If the messagequeue is initialized by the rt_mq_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_mq_detach() function to complete the detachment. + * for example,the rt_mq_create() function, it cannot be called in interrupt context. + */ +rt_err_t rt_mq_delete(rt_mq_t mq) +{ + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(rt_object_is_systemobject(&mq->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* resume all suspended thread */ + _ipc_list_resume_all(&(mq->parent.suspend_thread)); + /* also resume all message queue private suspended thread */ + _ipc_list_resume_all(&(mq->suspend_sender_thread)); + + /* free message queue pool */ + RT_KERNEL_FREE(mq->msg_pool); + + /* delete message queue object */ + rt_object_delete(&(mq->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mq_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will send a message to the messagequeue object. If + * there is a thread suspended on the messagequeue, the thread will be + * resumed. + * + * @note When using this function to send a message, if the messagequeue is + * fully used, the current thread will wait for a timeout. If reaching + * the timeout and there is still no space available, the sending + * thread will be resumed and an error code will be returned. By + * contrast, the rt_mq_send() function will return an error code + * immediately without waiting when the messagequeue if fully used. + * + * @see rt_mq_send() + * + * @param mq is a pointer to the messagequeue object to be sent. + * + * @param buffer is the content of the message. + * + * @param size is the length of the message(Unit: Byte). + * + * @param timeout is a timeout period (unit: an OS tick). + * + * @return Return the operation status. When the return value is RT_EOK, the + * operation is successful. If the return value is any other values, + * it means that the messagequeue detach failed. + * + * @warning This function can be called in interrupt context and thread + * context. + */ +static rt_err_t _rt_mq_send_wait(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout, + int suspend_flag) +{ + rt_base_t level; + struct rt_mq_message *msg; + rt_uint32_t tick_delta; + struct rt_thread *thread; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(buffer != RT_NULL); + RT_ASSERT(size != 0); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0); + + /* greater than one message size */ + if (size > mq->msg_size) + return -RT_ERROR; + + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mq->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* get a free list, there must be an empty item */ + msg = (struct rt_mq_message *)mq->msg_queue_free; + /* for non-blocking call */ + if (msg == RT_NULL && timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EFULL; + } + + /* message queue is full */ + while ((msg = (struct rt_mq_message *)mq->msg_queue_free) == RT_NULL) + { + /* reset error number in thread */ + thread->error = -RT_EINTR; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EFULL; + } + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mq->suspend_sender_thread), + thread, + mq->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mq_send_wait: start timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* re-schedule */ + rt_schedule(); + + /* resume from suspend state */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + + /* move free list pointer */ + mq->msg_queue_free = msg->next; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* the msg is the new tailer of list, the next shall be NULL */ + msg->next = RT_NULL; + /* copy buffer */ + rt_memcpy(msg + 1, buffer, size); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + /* link msg to message queue */ + if (mq->msg_queue_tail != RT_NULL) + { + /* if the tail exists, */ + ((struct rt_mq_message *)mq->msg_queue_tail)->next = msg; + } + + /* set new tail */ + mq->msg_queue_tail = msg; + /* if the head is empty, set head */ + if (mq->msg_queue_head == RT_NULL) + mq->msg_queue_head = msg; + + if(mq->entry < RT_MQ_ENTRY_MAX) + { + /* increase message entry */ + mq->entry ++; + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + + /* resume suspended thread */ + if (!rt_list_isempty(&mq->parent.suspend_thread)) + { + _ipc_list_resume(&(mq->parent.suspend_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} + +rt_err_t rt_mq_send_wait(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_send_wait(mq, buffer, size, timeout, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mq_send_wait) + +rt_err_t rt_mq_send_wait_interruptible(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_send_wait(mq, buffer, size, timeout, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mq_send_wait_interruptible) + +rt_err_t rt_mq_send_wait_killable(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_send_wait(mq, buffer, size, timeout, RT_KILLABLE); +} +RTM_EXPORT(rt_mq_send_wait_killable) +/** + * @brief This function will send a message to the messagequeue object. + * If there is a thread suspended on the messagequeue, the thread will be resumed. + * + * @note When using this function to send a message, if the messagequeue is fully used, + * the current thread will wait for a timeout. + * By contrast, when the messagequeue is fully used, the rt_mq_send_wait() function will + * return an error code immediately without waiting. + * + * @see rt_mq_send_wait() + * + * @param mq is a pointer to the messagequeue object to be sent. + * + * @param buffer is the content of the message. + * + * @param size is the length of the message(Unit: Byte). + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the messagequeue detach failed. + * + * @warning This function can be called in interrupt context and thread context. + */ +rt_err_t rt_mq_send(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + return rt_mq_send_wait(mq, buffer, size, 0); +} +RTM_EXPORT(rt_mq_send); + +rt_err_t rt_mq_send_interrupt(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + return rt_mq_send_wait_interruptible(mq, buffer, size, 0); +} +RTM_EXPORT(rt_mq_send_interrupt); + +rt_err_t rt_mq_send_killable(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + return rt_mq_send_wait_killable(mq, buffer, size, 0); +} +RTM_EXPORT(rt_mq_send_killable); +/** + * @brief This function will send an urgent message to the messagequeue object. + * + * @note This function is almost the same as the rt_mq_send() function. The only difference is that + * when sending an urgent message, the message is placed at the head of the messagequeue so that + * the recipient can receive the urgent message first. + * + * @see rt_mq_send() + * + * @param mq is a pointer to the messagequeue object to be sent. + * + * @param buffer is the content of the message. + * + * @param size is the length of the message(Unit: Byte). + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + */ +rt_err_t rt_mq_urgent(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + rt_base_t level; + struct rt_mq_message *msg; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(buffer != RT_NULL); + RT_ASSERT(size != 0); + + /* greater than one message size */ + if (size > mq->msg_size) + return -RT_ERROR; + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mq->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* get a free list, there must be an empty item */ + msg = (struct rt_mq_message *)mq->msg_queue_free; + /* message queue is full */ + if (msg == RT_NULL) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EFULL; + } + /* move free list pointer */ + mq->msg_queue_free = msg->next; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* copy buffer */ + rt_memcpy(msg + 1, buffer, size); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* link msg to the beginning of message queue */ + msg->next = (struct rt_mq_message *)mq->msg_queue_head; + mq->msg_queue_head = msg; + + /* if there is no tail */ + if (mq->msg_queue_tail == RT_NULL) + mq->msg_queue_tail = msg; + + if(mq->entry < RT_MQ_ENTRY_MAX) + { + /* increase message entry */ + mq->entry ++; + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + + /* resume suspended thread */ + if (!rt_list_isempty(&mq->parent.suspend_thread)) + { + _ipc_list_resume(&(mq->parent.suspend_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} +RTM_EXPORT(rt_mq_urgent); + + +/** + * @brief This function will receive a message from message queue object, + * if there is no message in messagequeue object, the thread shall wait for a specified time. + * + * @note Only when there is mail in the mailbox, the receiving thread can get the mail immediately and return RT_EOK, + * otherwise the receiving thread will be suspended until timeout. + * If the mail is not received within the specified time, it will return -RT_ETIMEOUT. + * + * @param mq is a pointer to the messagequeue object to be received. + * + * @param buffer is the content of the message. + * + * @param size is the length of the message(Unit: Byte). + * + * @param timeout is a timeout period (unit: an OS tick). If the message is unavailable, the thread will wait for + * the message in the queue up to the amount of time specified by this parameter. + * + * NOTE: + * If use Macro RT_WAITING_FOREVER to set this parameter, which means that when the + * message is unavailable in the queue, the thread will be waiting forever. + * If use macro RT_WAITING_NO to set this parameter, which means that this + * function is non-blocking and will return immediately. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox release failed. + */ +static rt_err_t _rt_mq_recv(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout, + int suspend_flag) +{ + struct rt_thread *thread; + rt_base_t level; + struct rt_mq_message *msg; + rt_uint32_t tick_delta; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(buffer != RT_NULL); + RT_ASSERT(size != 0); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0); + + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(mq->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* for non-blocking call */ + if (mq->entry == 0 && timeout == 0) + { + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + + /* message queue is empty */ + while (mq->entry == 0) + { + /* reset error number in thread */ + thread->error = -RT_EINTR; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + thread->error = -RT_ETIMEOUT; + + return -RT_ETIMEOUT; + } + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mq->parent.suspend_thread), + thread, + mq->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("set thread:%s to timer list\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* re-schedule */ + rt_schedule(); + + /* recv message */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + + /* get message from queue */ + msg = (struct rt_mq_message *)mq->msg_queue_head; + + /* move message queue head */ + mq->msg_queue_head = msg->next; + /* reach queue tail, set to NULL */ + if (mq->msg_queue_tail == msg) + mq->msg_queue_tail = RT_NULL; + + /* decrease message entry */ + if(mq->entry > 0) + { + mq->entry --; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* copy message */ + rt_memcpy(buffer, msg + 1, size > mq->msg_size ? mq->msg_size : size); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + /* put message to free list */ + msg->next = (struct rt_mq_message *)mq->msg_queue_free; + mq->msg_queue_free = msg; + + /* resume suspended thread */ + if (!rt_list_isempty(&(mq->suspend_sender_thread))) + { + _ipc_list_resume(&(mq->suspend_sender_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mq->parent.parent))); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mq->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_mq_recv(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_recv(mq, buffer, size, timeout, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mq_recv); + +rt_err_t rt_mq_recv_interruptible(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_recv(mq, buffer, size, timeout, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mq_recv_interruptible); + +rt_err_t rt_mq_recv_killable(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_recv(mq, buffer, size, timeout, RT_KILLABLE); +} +RTM_EXPORT(rt_mq_recv_killable); +/** + * @brief This function will set some extra attributions of a messagequeue object. + * + * @note Currently this function only supports the RT_IPC_CMD_RESET command to reset the messagequeue. + * + * @param mq is a pointer to a messagequeue object. + * + * @param cmd is a command used to configure some attributions of the messagequeue. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_mq_control(rt_mq_t mq, int cmd, void *arg) +{ + rt_base_t level; + struct rt_mq_message *msg; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + + if (cmd == RT_IPC_CMD_RESET) + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* resume all waiting thread */ + _ipc_list_resume_all(&mq->parent.suspend_thread); + /* also resume all message queue private suspended thread */ + _ipc_list_resume_all(&(mq->suspend_sender_thread)); + + /* release all message in the queue */ + while (mq->msg_queue_head != RT_NULL) + { + /* get message from queue */ + msg = (struct rt_mq_message *)mq->msg_queue_head; + + /* move message queue head */ + mq->msg_queue_head = msg->next; + /* reach queue tail, set to NULL */ + if (mq->msg_queue_tail == msg) + mq->msg_queue_tail = RT_NULL; + + /* put message to free list */ + msg->next = (struct rt_mq_message *)mq->msg_queue_free; + mq->msg_queue_free = msg; + } + + /* clean entry */ + mq->entry = 0; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_mq_control); + +/**@}*/ +#endif /* RT_USING_MESSAGEQUEUE */ +/**@}*/ diff --git a/tasks/concur-rtthread-mutex-ceilings/check.py b/tasks/concur-rtthread-mutex-ceilings/check.py new file mode 100644 index 00000000..43623ba7 --- /dev/null +++ b/tasks/concur-rtthread-mutex-ceilings/check.py @@ -0,0 +1,163 @@ +"""Trusted comparisons; candidate is compiled and run only in child processes.""" +import json +from pathlib import Path +import random +import shutil +import subprocess +import sys +import tarfile +import tempfile + +ROOT = Path(__file__).resolve().parent + +class Model: + def __init__(self, priorities, count): + self.base=list(priorities) + self.actors=[[p,0,1,0,0] for p in priorities] + self.mutex=[[-1,0,255] for _ in range(count)] + self.wait=[[] for _ in range(count)] + self.pending={} + self.expired=set() + + def update(self): + p=list(self.base) + for _ in self.base: + for mi,(owner,hold,ceiling) in enumerate(self.mutex): + if owner>=0: + p[owner]=min(p[owner],ceiling,*[p[w] for w in self.wait[mi]]) + for i,v in enumerate(p):self.actors[i][0]=v + + def command(self, command): + op,a,m,value,variant=command + result=0 + actor=self.actors[a] + if op=='X': + self.wait[self.pending[a]].remove(a) + self.expired.add(a) + actor[1]=0;actor[4]=-2 + elif op=='G': + actor[2]=1 + actor[3]=-2 if a in self.expired else 0 + self.expired.discard(a) + self.pending.pop(a) + self.update() + result=actor[3] + else: + actor[2]=1 + result=0 + if op=='C': + result=255 + if m>=0 and value<32: + result=self.mutex[m][2] + self.mutex[m][2]=value + self.update() + else:actor[4]=-10 + elif op=='Q':result=self.mutex[m][2] if m>=0 else 255 + elif op=='T': + actor[4]=0 + target=self.mutex[m] + if target[0] in (-1,a): + target[0]=a;target[1]+=1 + self.update() + elif value==0:result=-2;actor[4]=-2 + else: + actor[1]=1;actor[2]=0 + self.wait[m].append(a);self.pending[a]=m + self.update() + return [777,[x[:] for x in self.actors],[x[:] for x in self.mutex]] + elif op=='R': + target=self.mutex[m] + if target[0]!=a:result=-1;actor[4]=-1 + else: + target[1]-=1 + if not target[1]: + target[0]=-1 + if self.wait[m]: + w=min(self.wait[m],key=lambda i:self.actors[i][0]) + self.wait[m].remove(w);target[0]=w;target[1]=1 + self.actors[w][1]=0 + self.update() + actor[3]=result + return [result,[x[:] for x in self.actors],[x[:] for x in self.mutex]] + + +def cmd(op,a=0,m=0,value=0,variant=0):return (op,a,m,value,variant) + +def cases(): + yield 'ordinary',[24,12],2,[cmd('Q'),cmd('T'),cmd('T'),cmd('R',1),cmd('T',1),cmd('R'),cmd('R'),cmd('T',1),cmd('R',1)] + for base in (12,24,30): + for low,high in ((0,5),(3,9),(7,7),(15,31)): + commands=[cmd('C',0,0,low),cmd('C',0,1,high),cmd('Q'),cmd('T'),cmd('T',0,1),cmd('T',0,0),cmd('R'),cmd('C',0,0,31),cmd('C',0,1,0),cmd('R',0,1),cmd('R'),cmd('Q'),cmd('C',0,0,32),cmd('C',0,0,255),cmd('C',0,-1,3),cmd('Q',0,-1)] + yield 'ceilings-%d-%d-%d'%(base,low,high),[base,31],2,commands + for order in ((0,1,2),(2,0,1),(1,2,0)): + commands=[cmd('C',0,m,c) for m,c in enumerate((4,11,18))] + commands += [cmd('T',0,m) for m in order] + commands += [cmd('R',0,m) for m in order] + yield 'release-order-'+str(order),[25],3,commands + for variant in (0,1,2): + for ceiling in (3,13,255): + commands=[] + if ceiling!=255:commands.append(cmd('C',0,1,ceiling)) + commands += [cmd('T'),cmd('T',0,1),cmd('T',1,0,17,variant),cmd('X',1),cmd('G',1),cmd('R'),cmd('R',0,1)] + yield 'timeout-%d-%d'%(variant,ceiling),[26,7],2,commands + commands=[cmd('T'),cmd('T',1,1),cmd('T',1,0,-1,variant),cmd('T',2,1,-1,variant),cmd('C',3,1,2),cmd('C',3,1,14),cmd('R'),cmd('G',1),cmd('R',1),cmd('R',1,1),cmd('G',2),cmd('R',2,1)] + yield 'nested-inheritance-'+str(variant),[27,21,8,31],2,commands + for variant in (0,1,2): + commands=[cmd('T'),cmd('T',1,1),cmd('T',1,0,-1,variant),cmd('T',2,0,-1,variant),cmd('C',3,1,3),cmd('R'),cmd('G',1),cmd('R',1),cmd('G',2),cmd('R',2),cmd('R',1,1)] + yield 'waiter-promoted-'+str(variant),[28,18,9,31],2,commands + commands=[cmd('C',3,1,3),cmd('T'),cmd('T',1,1),cmd('T',1,0,-1,variant),cmd('T',2,0,-1,variant),cmd('C',3,1,22),cmd('R'),cmd('G',2),cmd('R',2),cmd('G',1),cmd('R',1),cmd('R',1,1)] + yield 'waiter-relaxed-'+str(variant),[28,18,9,31],2,commands + for ceiling in (0,6,16,31): + commands=[cmd('T'),cmd('T',1,1),cmd('T',1,0,-1),cmd('C',2,1,ceiling),cmd('C',2,1,30),cmd('R'),cmd('G',1),cmd('R',1),cmd('R',1,1)] + yield 'blocked-owner-ceiling-'+str(ceiling),[28,20,31],2,commands + # Multiple pending donors; withdrawal must preserve a different held object's ceiling. + for release_first in (0,1): + commands=[cmd('C',0,2,13),cmd('T',0,2),cmd('T'),cmd('T',0,1),cmd('T',1,0,19),cmd('T',2,1,19),cmd('X',1),cmd('G',1),cmd('X',2),cmd('G',2),cmd('R',0,release_first),cmd('R',0,1-release_first),cmd('R',0,2)] + yield 'donor-withdrawal-'+str(release_first),[26,3,8],3,commands + rng=random.Random(2807046) + for index in range(12): + base=rng.randrange(15,31) + caps=[rng.randrange(0,32) for _ in range(4)] + commands=[cmd('C',0,m,c) for m,c in enumerate(caps)] + commands += [cmd('T',0,m) for m in rng.sample(range(4),4)] + for _ in range(6):commands.append(cmd('C',1,rng.randrange(4),rng.randrange(32))) + commands += [cmd('R',0,m) for m in rng.sample(range(4),4)] + yield 'configured-set-'+str(index),[base,31],4,commands + + +def main(): + work=Path(tempfile.mkdtemp(prefix='rtmutex-check-')) + with tarfile.open(ROOT/'support.tar') as tar: + tar.extractall(work) + shutil.copyfile(Path(sys.argv[1])/'src/ipc.c',work/'src/ipc.c') + shutil.copyfile(ROOT/'observer.c',work/'observer.c') + planned=[] + for name,priorities,nmutex,commands in cases(): + model=Model(priorities,nmutex) + expectations=[model.command(c) for c in commands] + data='%d %d\n%s\n'%(len(priorities),nmutex,' '.join(map(str,priorities))) + data+=''.join('%s %d %d %d %d\n'%c for c in commands) + planned.append((name,data,expectations)) + # All inputs/support are written before candidate execution. Never re-read scratch after launching it. + build=subprocess.run(['gcc','-std=c11','-D_XOPEN_SOURCE=700','-O1','-Iinclude','-Iport','-ffunction-sections','-fdata-sections','src/ipc.c','src/thread.c','src/object.c','port/services.c','observer.c','-Wl,--gc-sections','-o','observer'],cwd=work,capture_output=True,text=True,timeout=25) + if build.returncode: + print('build failed');return 1 + checks=0 + for name,data,expectations in planned: + run=subprocess.run([str(work/'observer')],cwd=work,input=data,capture_output=True,text=True,timeout=4) + if run.returncode: + print(name+': candidate did not finish');return 1 + try:observed=[json.loads(line) for line in run.stdout.splitlines()] + except (ValueError,TypeError): + print(name+': malformed observation');return 1 + if observed!=expectations: + for index,(got,want) in enumerate(zip(observed,expectations)): + if got!=want: + print(name+': observation %d differs'%index,file=sys.stderr) + print('got '+repr(got)+' expected '+repr(want),file=sys.stderr);break + print(name+': behavior differs');return 1 + checks+=len(expectations) + print('observations=%d scenarios=%d'%(checks,len(planned))) + print('PASS');return 0 + +if __name__=='__main__':raise SystemExit(main()) diff --git a/tasks/concur-rtthread-mutex-ceilings/gold/src/ipc.c b/tasks/concur-rtthread-mutex-ceilings/gold/src/ipc.c new file mode 100644 index 00000000..c5a2481f --- /dev/null +++ b/tasks/concur-rtthread-mutex-ceilings/gold/src/ipc.c @@ -0,0 +1,3754 @@ +/* + * Copyright (c) 2006-2022, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +#include +#include + +#ifndef __on_rt_object_trytake_hook + #define __on_rt_object_trytake_hook(parent) __ON_HOOK_ARGS(rt_object_trytake_hook, (parent)) +#endif +#ifndef __on_rt_object_take_hook + #define __on_rt_object_take_hook(parent) __ON_HOOK_ARGS(rt_object_take_hook, (parent)) +#endif +#ifndef __on_rt_object_put_hook + #define __on_rt_object_put_hook(parent) __ON_HOOK_ARGS(rt_object_put_hook, (parent)) +#endif + +#if defined(RT_USING_HOOK) && defined(RT_HOOK_USING_FUNC_PTR) +extern void (*rt_object_trytake_hook)(struct rt_object *object); +extern void (*rt_object_take_hook)(struct rt_object *object); +extern void (*rt_object_put_hook)(struct rt_object *object); +#endif /* RT_USING_HOOK */ + +/** + * @addtogroup IPC + * @{ + */ + +/** + * @brief This function will initialize an IPC object, such as semaphore, mutex, messagequeue and mailbox. + * + * @note Executing this function will complete an initialization of the suspend thread list of the ipc object. + * + * @param ipc is a pointer to the IPC object. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * When the return value is any other values, it means the initialization failed. + * + * @warning This function can be called from all IPC initialization and creation. + */ +rt_inline rt_err_t _ipc_object_init(struct rt_ipc_object *ipc) +{ + /* initialize ipc object */ + rt_list_init(&(ipc->suspend_thread)); + + return RT_EOK; +} + + +/** + * @brief This function will suspend a thread to a IPC object list. + * + * @param list is a pointer to a suspended thread list of the IPC object. + * + * @param thread is a pointer to the thread object to be suspended. + * + * @param flag is a flag for the thread object to be suspended. It determines how the thread is suspended. + * The flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to use + * RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this semaphore will become non-real-time threads. + * + * @param suspend_flag status flag of the thread to be suspended. + * + * @return Return the operation status. When the return value is RT_EOK, the function is successfully executed. + * When the return value is any other values, it means the initialization failed. + * + * @warning This function can ONLY be called in the thread context, you can use RT_DEBUG_IN_THREAD_CONTEXT to + * check the context. + * In addition, this function is generally called by the following functions: + * rt_sem_take(), rt_mutex_take(), rt_event_recv(), rt_mb_send_wait(), + * rt_mb_recv(), rt_mq_recv(), rt_mq_send_wait() + */ +rt_inline rt_err_t _ipc_list_suspend(rt_list_t *list, + struct rt_thread *thread, + rt_uint8_t flag, + int suspend_flag) +{ + if ((thread->stat & RT_THREAD_SUSPEND_MASK) != RT_THREAD_SUSPEND_MASK) + { + rt_err_t ret = rt_thread_suspend_with_flag(thread, suspend_flag); + + /* suspend thread */ + if (ret != RT_EOK) + { + return ret; + } + } + + switch (flag) + { + case RT_IPC_FLAG_FIFO: + rt_list_insert_before(list, &(thread->tlist)); + break; /* RT_IPC_FLAG_FIFO */ + + case RT_IPC_FLAG_PRIO: + { + struct rt_list_node *n; + struct rt_thread *sthread; + + /* find a suitable position */ + for (n = list->next; n != list; n = n->next) + { + sthread = rt_list_entry(n, struct rt_thread, tlist); + + /* find out */ + if (thread->current_priority < sthread->current_priority) + { + /* insert this thread before the sthread */ + rt_list_insert_before(&(sthread->tlist), &(thread->tlist)); + break; + } + } + + /* + * not found a suitable position, + * append to the end of suspend_thread list + */ + if (n == list) + rt_list_insert_before(list, &(thread->tlist)); + } + break;/* RT_IPC_FLAG_PRIO */ + + default: + RT_ASSERT(0); + break; + } + + return RT_EOK; +} + + +/** + * @brief This function will resume a thread. + * + * @note This function will resume the first thread in the list of a IPC object. + * 1. remove the thread from suspend queue of a IPC object. + * 2. put the thread into system ready queue. + * + * By contrast, the rt_ipc_list_resume_all() function will resume all suspended threads + * in the list of a IPC object. + * + * @param list is a pointer to a suspended thread list of the IPC object. + * + * @return Return the operation status. When the return value is RT_EOK, the function is successfully executed. + * When the return value is any other values, it means this operation failed. + * + * @warning This function is generally called by the following functions: + * rt_sem_release(), rt_mutex_release(), rt_mb_send_wait(), rt_mq_send_wait(), + * rt_mb_urgent(), rt_mb_recv(), rt_mq_urgent(), rt_mq_recv(), + */ +rt_inline rt_err_t _ipc_list_resume(rt_list_t *list) +{ + struct rt_thread *thread; + + /* get thread entry */ + thread = rt_list_entry(list->next, struct rt_thread, tlist); + + thread->error = RT_EOK; + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("resume thread:%s\n", thread->name)); + + /* resume it */ + rt_thread_resume(thread); + + return RT_EOK; +} + + +/** + * @brief This function will resume all suspended threads in the IPC object list, + * including the suspended list of IPC object, and private list of mailbox etc. + * + * @note This function will resume all threads in the IPC object list. + * By contrast, the rt_ipc_list_resume() function will resume a suspended thread in the list of a IPC object. + * + * @param list is a pointer to a suspended thread list of the IPC object. + * + * @return Return the operation status. When the return value is RT_EOK, the function is successfully executed. + * When the return value is any other values, it means this operation failed. + * + */ +rt_inline rt_err_t _ipc_list_resume_all(rt_list_t *list) +{ + struct rt_thread *thread; + rt_base_t level; + + /* wakeup all suspended threads */ + while (!rt_list_isempty(list)) + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* get next suspended thread */ + thread = rt_list_entry(list->next, struct rt_thread, tlist); + /* set error code to RT_ERROR */ + thread->error = -RT_ERROR; + + /* + * resume thread + * In rt_thread_resume function, it will remove current thread from + * suspended list + */ + rt_thread_resume(thread); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + } + + return RT_EOK; +} + +#ifdef RT_USING_SEMAPHORE +/** + * @addtogroup semaphore + * @{ + */ + +/** + * @brief This function will initialize a static semaphore object. + * + * @note For the static semaphore object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_sem_create() function will allocate memory space automatically and initialize + * the semaphore. + * + * @see rt_sem_create() + * + * @param sem is a pointer to the semaphore to initialize. It is assumed that storage for the semaphore will be + * allocated in your application. + * + * @param name is a pointer to the name you would like to give the semaphore. + * + * @param value is the initial value for the semaphore. + * If used to share resources, you should initialize the value as the number of available resources. + * If used to signal the occurrence of an event, you should initialize the value as 0. + * + * @param flag is the semaphore flag, which determines the queuing way of how multiple threads wait + * when the semaphore is not available. + * The semaphore flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this semaphore will become non-real-time threads. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_sem_init(rt_sem_t sem, + const char *name, + rt_uint32_t value, + rt_uint8_t flag) +{ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(value < 0x10000U); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(sem->parent.parent), RT_Object_Class_Semaphore, name); + + /* initialize ipc object */ + _ipc_object_init(&(sem->parent)); + + /* set initial value */ + sem->value = (rt_uint16_t)value; + + /* set parent */ + sem->parent.parent.flag = flag; + + return RT_EOK; +} +RTM_EXPORT(rt_sem_init); + + +/** + * @brief This function will detach a static semaphore object. + * + * @note This function is used to detach a static semaphore object which is initialized by rt_sem_init() function. + * By contrast, the rt_sem_delete() function will delete a semaphore object. + * When the semaphore is successfully detached, it will resume all suspended threads in the semaphore list. + * + * @see rt_sem_delete() + * + * @param sem is a pointer to a semaphore object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the semaphore detach failed. + * + * @warning This function can ONLY detach a static semaphore initialized by the rt_sem_init() function. + * If the semaphore is created by the rt_sem_create() function, you MUST NOT USE this function to detach it, + * ONLY USE the rt_sem_delete() function to complete the deletion. + */ +rt_err_t rt_sem_detach(rt_sem_t sem) +{ + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + RT_ASSERT(rt_object_is_systemobject(&sem->parent.parent)); + + /* wakeup all suspended threads */ + _ipc_list_resume_all(&(sem->parent.suspend_thread)); + + /* detach semaphore object */ + rt_object_detach(&(sem->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_sem_detach); + +#ifdef RT_USING_HEAP +/** + * @brief Creating a semaphore object. + * + * @note For the semaphore object, its memory space is allocated automatically. + * By contrast, the rt_sem_init() function will initialize a static semaphore object. + * + * @see rt_sem_init() + * + * @param name is a pointer to the name you would like to give the semaphore. + * + * @param value is the initial value for the semaphore. + * If used to share resources, you should initialize the value as the number of available resources. + * If used to signal the occurrence of an event, you should initialize the value as 0. + * + * @param flag is the semaphore flag, which determines the queuing way of how multiple threads wait + * when the semaphore is not available. + * The semaphore flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this semaphore will become non-real-time threads. + * + * @return Return a pointer to the semaphore object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can NOT be called in interrupt context. You can use macor RT_DEBUG_NOT_IN_INTERRUPT to check it. + */ +rt_sem_t rt_sem_create(const char *name, rt_uint32_t value, rt_uint8_t flag) +{ + rt_sem_t sem; + + RT_ASSERT(value < 0x10000U); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + sem = (rt_sem_t)rt_object_allocate(RT_Object_Class_Semaphore, name); + if (sem == RT_NULL) + return sem; + + /* initialize ipc object */ + _ipc_object_init(&(sem->parent)); + + /* set initial value */ + sem->value = value; + + /* set parent */ + sem->parent.parent.flag = flag; + + return sem; +} +RTM_EXPORT(rt_sem_create); + + +/** + * @brief This function will delete a semaphore object and release the memory space. + * + * @note This function is used to delete a semaphore object which is created by the rt_sem_create() function. + * By contrast, the rt_sem_detach() function will detach a static semaphore object. + * When the semaphore is successfully deleted, it will resume all suspended threads in the semaphore list. + * + * @see rt_sem_detach() + * + * @param sem is a pointer to a semaphore object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the semaphore detach failed. + * + * @warning This function can ONLY delete a semaphore initialized by the rt_sem_create() function. + * If the semaphore is initialized by the rt_sem_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_sem_detach() function to complete the detachment. + */ +rt_err_t rt_sem_delete(rt_sem_t sem) +{ + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + RT_ASSERT(rt_object_is_systemobject(&sem->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* wakeup all suspended threads */ + _ipc_list_resume_all(&(sem->parent.suspend_thread)); + + /* delete semaphore object */ + rt_object_delete(&(sem->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_sem_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will take a semaphore, if the semaphore is unavailable, the thread shall wait for + * the semaphore up to a specified time. + * + * @note When this function is called, the count value of the sem->value will decrease 1 until it is equal to 0. + * When the sem->value is 0, it means that the semaphore is unavailable. At this time, it will suspend the + * thread preparing to take the semaphore. + * On the contrary, the rt_sem_release() function will increase the count value of sem->value by 1 each time. + * + * @see rt_sem_trytake() + * + * @param sem is a pointer to a semaphore object. + * + * @param timeout is a timeout period (unit: an OS tick). If the semaphore is unavailable, the thread will wait for + * the semaphore up to the amount of time specified by this parameter. + * + * NOTE: + * If use Macro RT_WAITING_FOREVER to set this parameter, which means that when the + * message is unavailable in the queue, the thread will be waiting forever. + * If use macro RT_WAITING_NO to set this parameter, which means that this + * function is non-blocking and will return immediately. + * + * @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 semaphore take failed. + * + * @warning This function can ONLY be called in the thread context. It MUST NOT BE called in interrupt context. + */ +static rt_err_t _rt_sem_take(rt_sem_t sem, rt_int32_t timeout, int suspend_flag) +{ + rt_base_t level; + struct rt_thread *thread; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(sem->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("thread %s take sem:%s, which value is: %d\n", + rt_thread_self()->name, + ((struct rt_object *)sem)->name, + sem->value)); + + if (sem->value > 0) + { + /* semaphore is available */ + sem->value --; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + } + else + { + /* no waiting, return with timeout */ + if (timeout == 0) + { + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + else + { + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE); + + /* semaphore is unavailable, push to suspend list */ + /* get current thread */ + thread = rt_thread_self(); + + /* reset thread error number */ + thread->error = -RT_EINTR; + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("sem take: suspend thread - %s\n", + thread->name)); + + /* suspend thread */ + ret = _ipc_list_suspend(&(sem->parent.suspend_thread), + thread, + sem->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + RT_DEBUG_LOG(RT_DEBUG_IPC, ("set thread:%s to timer list\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do schedule */ + rt_schedule(); + + if (thread->error != RT_EOK) + { + return thread->error; + } + } + } + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(sem->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_sem_take(rt_sem_t sem, rt_int32_t time) +{ + return _rt_sem_take(sem, time, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_sem_take); + +rt_err_t rt_sem_take_interruptible(rt_sem_t sem, rt_int32_t time) +{ + return _rt_sem_take(sem, time, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_sem_take_interruptible); + +rt_err_t rt_sem_take_killable(rt_sem_t sem, rt_int32_t time) +{ + return _rt_sem_take(sem, time, RT_KILLABLE); +} +RTM_EXPORT(rt_sem_take_killable); + +/** + * @brief This function will try to take a semaphore, if the semaphore is unavailable, the thread returns immediately. + * + * @note This function is very similar to the rt_sem_take() function, when the semaphore is not available, + * the rt_sem_trytake() function will return immediately without waiting for a timeout. + * In other words, rt_sem_trytake(sem) has the same effect as rt_sem_take(sem, 0). + * + * @see rt_sem_take() + * + * @param sem is a pointer to a semaphore object. + * + * @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 semaphore take failed. + */ +rt_err_t rt_sem_trytake(rt_sem_t sem) +{ + return rt_sem_take(sem, RT_WAITING_NO); +} +RTM_EXPORT(rt_sem_trytake); + + +/** + * @brief This function will release a semaphore. If there is thread suspended on the semaphore, it will get resumed. + * + * @note If there are threads suspended on this semaphore, the first thread in the list of this semaphore object + * will be resumed, and a thread scheduling (rt_schedule) will be executed. + * If no threads are suspended on this semaphore, the count value sem->value of this semaphore will increase by 1. + * + * @param sem is a pointer to a semaphore object. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the semaphore release failed. + */ +rt_err_t rt_sem_release(rt_sem_t sem) +{ + rt_base_t level; + rt_bool_t need_schedule; + + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(sem->parent.parent))); + + need_schedule = RT_FALSE; + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("thread %s releases sem:%s, which value is: %d\n", + rt_thread_self()->name, + ((struct rt_object *)sem)->name, + sem->value)); + + if (!rt_list_isempty(&sem->parent.suspend_thread)) + { + /* resume the suspended thread */ + _ipc_list_resume(&(sem->parent.suspend_thread)); + need_schedule = RT_TRUE; + } + else + { + if(sem->value < RT_SEM_VALUE_MAX) + { + sem->value ++; /* increase value */ + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* resume a thread, re-schedule */ + if (need_schedule == RT_TRUE) + rt_schedule(); + + return RT_EOK; +} +RTM_EXPORT(rt_sem_release); + + +/** + * @brief This function will set some extra attributions of a semaphore object. + * + * @note Currently this function only supports the RT_IPC_CMD_RESET command to reset the semaphore. + * + * @param sem is a pointer to a semaphore object. + * + * @param cmd is a command word used to configure some attributions of the semaphore. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_sem_control(rt_sem_t sem, int cmd, void *arg) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + + if (cmd == RT_IPC_CMD_RESET) + { + rt_ubase_t value; + + /* get value */ + value = (rt_ubase_t)arg; + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* resume all waiting thread */ + _ipc_list_resume_all(&sem->parent.suspend_thread); + + /* set new value */ + sem->value = (rt_uint16_t)value; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_sem_control); + +/**@}*/ +#endif /* RT_USING_SEMAPHORE */ + +#ifdef RT_USING_MUTEX +/* iterate over each suspended thread to update highest priority in pending threads */ +rt_inline rt_uint8_t _mutex_update_priority(struct rt_mutex *mutex) +{ + struct rt_thread *thread; + + if (!rt_list_isempty(&mutex->parent.suspend_thread)) + { + thread = rt_list_entry(mutex->parent.suspend_thread.next, struct rt_thread, tlist); + mutex->priority = thread->current_priority; + } + else + { + mutex->priority = 0xff; + } + + return mutex->priority; +} + +/* get highest priority inside its taken object and its init priority */ +rt_inline rt_uint8_t _thread_get_mutex_priority(struct rt_thread* thread) +{ + rt_list_t *node = RT_NULL; + struct rt_mutex *mutex = RT_NULL; + rt_uint8_t priority = thread->init_priority; + + rt_list_for_each(node, &(thread->taken_object_list)) + { + mutex = rt_list_entry(node, struct rt_mutex, taken_list); + rt_uint8_t mutex_prio = mutex->priority; + /* prio at least be priority ceiling */ + mutex_prio = mutex_prio < mutex->ceiling_priority ? mutex_prio : mutex->ceiling_priority; + + if (priority > mutex_prio) + { + priority = mutex_prio; + } + } + + return priority; +} + +/* update priority of target thread and the thread suspended it if any */ +rt_inline void _thread_update_priority(struct rt_thread *thread, rt_uint8_t priority, int suspend_flag) +{ + rt_err_t ret; + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("thread:%s priority -> %d\n", thread->name, priority)); + + /* change priority of the thread */ + rt_thread_control(thread, + RT_THREAD_CTRL_CHANGE_PRIORITY, + &priority); + + if ((thread->stat & RT_THREAD_SUSPEND_MASK) == RT_THREAD_SUSPEND_MASK) + { + /* whether change the priority of taken mutex */ + struct rt_object* pending_obj = thread->pending_object; + + if (pending_obj && rt_object_get_type(pending_obj) == RT_Object_Class_Mutex) + { + rt_uint8_t mutex_priority; + struct rt_mutex* pending_mutex = (struct rt_mutex *)pending_obj; + + /* re-insert thread to suspended thread list */ + rt_list_remove(&(thread->tlist)); + + ret = _ipc_list_suspend(&(pending_mutex->parent.suspend_thread), + thread, + pending_mutex->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + /* TODO */ + return ; + } + + /* update priority */ + _mutex_update_priority(pending_mutex); + /* change the priority of mutex owner thread */ + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("mutex: %s priority -> %d\n", pending_mutex->parent.parent.name, + pending_mutex->priority)); + + mutex_priority = _thread_get_mutex_priority(pending_mutex->owner); + if (mutex_priority != pending_mutex->owner->current_priority) + { + _thread_update_priority(pending_mutex->owner, mutex_priority, suspend_flag); + } + } + } +} + +/** + * @addtogroup mutex + * @{ + */ + +/** + * @brief Initialize a static mutex object. + * + * @note For the static mutex object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_mutex_create() function will automatically allocate memory space + * and initialize the mutex. + * + * @see rt_mutex_create() + * + * @param mutex is a pointer to the mutex to initialize. It is assumed that storage for the mutex will be + * allocated in your application. + * + * @param name is a pointer to the name that given to the mutex. + * + * @param flag is the mutex flag, which determines the queuing way of how multiple threads wait + * when the mutex is not available. + * NOTE: This parameter has been obsoleted. It can be RT_IPC_FLAG_PRIO, RT_IPC_FLAG_FIFO or RT_NULL. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_mutex_init(rt_mutex_t mutex, const char *name, rt_uint8_t flag) +{ + /* flag parameter has been obsoleted */ + RT_UNUSED(flag); + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + + /* initialize object */ + rt_object_init(&(mutex->parent.parent), RT_Object_Class_Mutex, name); + + /* initialize ipc object */ + _ipc_object_init(&(mutex->parent)); + + mutex->owner = RT_NULL; + mutex->priority = 0xFF; + mutex->hold = 0; + mutex->ceiling_priority = 0xFF; + rt_list_init(&(mutex->taken_list)); + + /* flag can only be RT_IPC_FLAG_PRIO. RT_IPC_FLAG_FIFO cannot solve the unbounded priority inversion problem */ + mutex->parent.parent.flag = RT_IPC_FLAG_PRIO; + + return RT_EOK; +} +RTM_EXPORT(rt_mutex_init); + + +/** + * @brief This function will detach a static mutex object. + * + * @note This function is used to detach a static mutex object which is initialized by rt_mutex_init() function. + * By contrast, the rt_mutex_delete() function will delete a mutex object. + * When the mutex is successfully detached, it will resume all suspended threads in the mutex list. + * + * @see rt_mutex_delete() + * + * @param mutex is a pointer to a mutex object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the mutex detach failed. + * + * @warning This function can ONLY detach a static mutex initialized by the rt_mutex_init() function. + * If the mutex is created by the rt_mutex_create() function, you MUST NOT USE this function to detach it, + * ONLY USE the rt_mutex_delete() function to complete the deletion. + */ +rt_err_t rt_mutex_detach(rt_mutex_t mutex) +{ + rt_ubase_t level; + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + RT_ASSERT(rt_object_is_systemobject(&mutex->parent.parent)); + + level = rt_hw_interrupt_disable(); + /* wakeup all suspended threads */ + _ipc_list_resume_all(&(mutex->parent.suspend_thread)); + /* remove mutex from thread's taken list */ + rt_list_remove(&mutex->taken_list); + rt_hw_interrupt_enable(level); + + /* detach mutex object */ + rt_object_detach(&(mutex->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mutex_detach); + +/* drop a thread from the suspend list of mutex */ + +/** + * @brief drop a thread from the suspend list of mutex + * + * @param mutex is a pointer to a mutex object. + * @param thread is the thread should be dropped from mutex. + */ +void rt_mutex_drop_thread(rt_mutex_t mutex, rt_thread_t thread) +{ + rt_uint8_t priority; + rt_bool_t need_update = RT_FALSE; + + rt_list_remove(&(thread->tlist)); + + /* should change the priority of mutex owner thread */ + if (mutex->owner->current_priority == thread->current_priority) + need_update = RT_TRUE; + + /* update the priority of mutex */ + if (!rt_list_isempty(&mutex->parent.suspend_thread)) + { + /* more thread suspended in the list */ + struct rt_thread *th; + + th = rt_list_entry(mutex->parent.suspend_thread.next, + struct rt_thread, + tlist); + /* update the priority of mutex */ + mutex->priority = th->current_priority; + } + else + { + /* set mutex priority to maximal priority */ + mutex->priority = 0xff; + } + + /* try to change the priority of mutex owner thread */ + if (need_update) + { + /* get the maximal priority of mutex in thread */ + priority = _thread_get_mutex_priority(mutex->owner); + if (priority != mutex->owner->current_priority) + { + _thread_update_priority(mutex->owner, priority, RT_UNINTERRUPTIBLE); + } + } +} + + +/** + * @brief set the prioceiling attribute of the mutex. + * + * @param mutex is a pointer to a mutex object. + * @param priority is the priority should be set to mutex. + * + * @return return the old priority ceiling + */ +rt_uint8_t rt_mutex_setprioceiling(rt_mutex_t mutex, rt_uint8_t priority) +{ + rt_uint8_t ret_priority = 0xFF; + + if ((mutex) && (priority < RT_THREAD_PRIORITY_MAX)) + { + /* critical section here if multiple updates to one mutex happen */ + rt_ubase_t level = rt_hw_interrupt_disable(); + ret_priority = mutex->ceiling_priority; + mutex->ceiling_priority = priority; + if (mutex->owner) + { + rt_uint8_t priority = _thread_get_mutex_priority(mutex->owner); + if (priority != mutex->owner->current_priority) + _thread_update_priority(mutex->owner, priority, RT_UNINTERRUPTIBLE); + } + rt_hw_interrupt_enable(level); + } + else + { + rt_set_errno(-RT_EINVAL); + } + + return ret_priority; +} +RTM_EXPORT(rt_mutex_setprioceiling); + + +/** + * @brief set the prioceiling attribute of the mutex. + * + * @param mutex is a pointer to a mutex object. + * + * @return return the current priority ceiling of the mutex. + */ +rt_uint8_t rt_mutex_getprioceiling(rt_mutex_t mutex) +{ + rt_uint8_t prio = 0xFF; + + if (mutex) + { + prio = mutex->ceiling_priority; + } + + return prio; +} +RTM_EXPORT(rt_mutex_getprioceiling); + + +#ifdef RT_USING_HEAP +/** + * @brief This function will create a mutex object. + * + * @note For the mutex object, its memory space is automatically allocated. + * By contrast, the rt_mutex_init() function will initialize a static mutex object. + * + * @see rt_mutex_init() + * + * @param name is a pointer to the name that given to the mutex. + * + * @param flag is the mutex flag, which determines the queuing way of how multiple threads wait + * when the mutex is not available. + * NOTE: This parameter has been obsoleted. It can be RT_IPC_FLAG_PRIO, RT_IPC_FLAG_FIFO or RT_NULL. + * + * @return Return a pointer to the mutex object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_mutex_t rt_mutex_create(const char *name, rt_uint8_t flag) +{ + struct rt_mutex *mutex; + + /* flag parameter has been obsoleted */ + RT_UNUSED(flag); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + mutex = (rt_mutex_t)rt_object_allocate(RT_Object_Class_Mutex, name); + if (mutex == RT_NULL) + return mutex; + + /* initialize ipc object */ + _ipc_object_init(&(mutex->parent)); + + mutex->owner = RT_NULL; + mutex->priority = 0xFF; + mutex->hold = 0; + mutex->ceiling_priority = 0xFF; + rt_list_init(&(mutex->taken_list)); + + /* flag can only be RT_IPC_FLAG_PRIO. RT_IPC_FLAG_FIFO cannot solve the unbounded priority inversion problem */ + mutex->parent.parent.flag = RT_IPC_FLAG_PRIO; + + return mutex; +} +RTM_EXPORT(rt_mutex_create); + + +/** + * @brief This function will delete a mutex object and release this memory space. + * + * @note This function is used to delete a mutex object which is created by the rt_mutex_create() function. + * By contrast, the rt_mutex_detach() function will detach a static mutex object. + * When the mutex is successfully deleted, it will resume all suspended threads in the mutex list. + * + * @see rt_mutex_detach() + * + * @param mutex is a pointer to a mutex object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mutex detach failed. + * + * @warning This function can ONLY delete a mutex initialized by the rt_mutex_create() function. + * If the mutex is initialized by the rt_mutex_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_mutex_detach() function to complete the detachment. + */ +rt_err_t rt_mutex_delete(rt_mutex_t mutex) +{ + rt_ubase_t level; + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + RT_ASSERT(rt_object_is_systemobject(&mutex->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + level = rt_hw_interrupt_disable(); + /* wakeup all suspended threads */ + _ipc_list_resume_all(&(mutex->parent.suspend_thread)); + /* remove mutex from thread's taken list */ + rt_list_remove(&mutex->taken_list); + rt_hw_interrupt_enable(level); + + /* delete mutex object */ + rt_object_delete(&(mutex->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mutex_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will take a mutex, if the mutex is unavailable, the thread shall wait for + * the mutex up to a specified time. + * + * @note When this function is called, the count value of the mutex->value will decrease 1 until it is equal to 0. + * When the mutex->value is 0, it means that the mutex is unavailable. At this time, it will suspend the + * thread preparing to take the mutex. + * On the contrary, the rt_mutex_release() function will increase the count value of mutex->value by 1 each time. + * + * @see rt_mutex_trytake() + * + * @param mutex is a pointer to a mutex object. + * + * @param timeout is a timeout period (unit: an OS tick). If the mutex is unavailable, the thread will wait for + * the mutex up to the amount of time specified by the argument. + * NOTE: Generally, we set this parameter to RT_WAITING_FOREVER, which means that when the mutex is unavailable, + * the thread will be waitting forever. + * + * @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 mutex take failed. + * + * @warning This function can ONLY be called in the thread context. It MUST NOT BE called in interrupt context. + */ +static rt_err_t _rt_mutex_take(rt_mutex_t mutex, rt_int32_t timeout, int suspend_flag) +{ + rt_base_t level; + struct rt_thread *thread; + rt_err_t ret; + + /* this function must not be used in interrupt even if time = 0 */ + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE); + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + + /* get current thread */ + thread = rt_thread_self(); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(mutex->parent.parent))); + + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("mutex_take: current thread %s, hold: %d\n", + thread->name, mutex->hold)); + + /* reset thread error */ + thread->error = RT_EOK; + + if (mutex->owner == thread) + { + if(mutex->hold < RT_MUTEX_HOLD_MAX) + { + /* it's the same thread */ + mutex->hold ++; + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + } + else + { + /* whether the mutex has owner thread. */ + if (mutex->owner == RT_NULL) + { + /* set mutex owner and original priority */ + mutex->owner = thread; + mutex->priority = 0xff; + mutex->hold = 1; + + if (mutex->ceiling_priority != 0xFF) + { + /* set the priority of thread to the ceiling priority */ + if (mutex->ceiling_priority < mutex->owner->current_priority) + _thread_update_priority(mutex->owner, mutex->ceiling_priority, suspend_flag); + } + + /* insert mutex to thread's taken object list */ + rt_list_insert_after(&thread->taken_object_list, &mutex->taken_list); + } + else + { + /* no waiting, return with timeout */ + if (timeout == 0) + { + /* set error as timeout */ + thread->error = -RT_ETIMEOUT; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + else + { + rt_uint8_t priority = thread->current_priority; + + /* mutex is unavailable, push to suspend list */ + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mutex_take: suspend thread: %s\n", + thread->name)); + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mutex->parent.suspend_thread), + thread, + mutex->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* set pending object in thread to this mutex */ + thread->pending_object = &(mutex->parent.parent); + + /* update the priority level of mutex */ + if (priority < mutex->priority) + { + mutex->priority = priority; + if (mutex->priority < mutex->owner->current_priority) + { + _thread_update_priority(mutex->owner, priority, RT_UNINTERRUPTIBLE); /* TODO */ + } + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("mutex_take: start the timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do schedule */ + rt_schedule(); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + if (thread->error == RT_EOK) + { + /* get mutex successfully */ + } + else + { + /* the mutex has not been taken and thread has detach from the pending list. */ + + rt_bool_t need_update = RT_FALSE; + + /* should change the priority of mutex owner thread */ + if (mutex->owner->current_priority == thread->current_priority) + need_update = RT_TRUE; + + /* update the priority of mutex */ + if (!rt_list_isempty(&mutex->parent.suspend_thread)) + { + /* more thread suspended in the list */ + struct rt_thread *th; + + th = rt_list_entry(mutex->parent.suspend_thread.next, + struct rt_thread, + tlist); + /* update the priority of mutex */ + mutex->priority = th->current_priority; + } + else + { + /* set mutex priority to maximal priority */ + mutex->priority = 0xff; + } + + /* try to change the priority of mutex owner thread */ + if (need_update) + { + /* get the maximal priority of mutex in thread */ + priority = _thread_get_mutex_priority(mutex->owner); + if (priority != mutex->owner->current_priority) + { + _thread_update_priority(mutex->owner, priority, RT_UNINTERRUPTIBLE); + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* return error */ + return thread->error; + } + } + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mutex->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_mutex_take(rt_mutex_t mutex, rt_int32_t time) +{ + return _rt_mutex_take(mutex, time, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mutex_take); + +rt_err_t rt_mutex_take_interruptible(rt_mutex_t mutex, rt_int32_t time) +{ + return _rt_mutex_take(mutex, time, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mutex_take_interruptible); + +rt_err_t rt_mutex_take_killable(rt_mutex_t mutex, rt_int32_t time) +{ + return _rt_mutex_take(mutex, time, RT_KILLABLE); +} +RTM_EXPORT(rt_mutex_take_killable); + +/** + * @brief This function will try to take a mutex, if the mutex is unavailable, the thread returns immediately. + * + * @note This function is very similar to the rt_mutex_take() function, when the mutex is not available, + * except that rt_mutex_trytake() will return immediately without waiting for a timeout + * when the mutex is not available. + * In other words, rt_mutex_trytake(mutex) has the same effect as rt_mutex_take(mutex, 0). + * + * @see rt_mutex_take() + * + * @param mutex is a pointer to a mutex object. + * + * @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 mutex take failed. + */ +rt_err_t rt_mutex_trytake(rt_mutex_t mutex) +{ + return rt_mutex_take(mutex, RT_WAITING_NO); +} +RTM_EXPORT(rt_mutex_trytake); + + +/** + * @brief This function will release a mutex. If there is thread suspended on the mutex, the thread will be resumed. + * + * @note If there are threads suspended on this mutex, the first thread in the list of this mutex object + * will be resumed, and a thread scheduling (rt_schedule) will be executed. + * If no threads are suspended on this mutex, the count value mutex->value of this mutex will increase by 1. + * + * @param mutex is a pointer to a mutex object. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mutex release failed. + */ +rt_err_t rt_mutex_release(rt_mutex_t mutex) +{ + rt_base_t level; + struct rt_thread *thread; + rt_bool_t need_schedule; + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + + need_schedule = RT_FALSE; + + /* only thread could release mutex because we need test the ownership */ + RT_DEBUG_IN_THREAD_CONTEXT; + + /* get current thread */ + thread = rt_thread_self(); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("mutex_release:current thread %s, hold: %d\n", + thread->name, mutex->hold)); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mutex->parent.parent))); + + /* mutex only can be released by owner */ + if (thread != mutex->owner) + { + thread->error = -RT_ERROR; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_ERROR; + } + + /* decrease hold */ + mutex->hold --; + /* if no hold */ + if (mutex->hold == 0) + { + /* remove mutex from thread's taken list */ + rt_list_remove(&mutex->taken_list); + + /* whether change the thread priority */ + if ((mutex->ceiling_priority != 0xFF) || (thread->current_priority == mutex->priority)) + { + rt_uint8_t priority = 0xff; + + /* get the highest priority in the taken list of thread */ + priority = _thread_get_mutex_priority(thread); + + rt_thread_control(thread, + RT_THREAD_CTRL_CHANGE_PRIORITY, + &priority); + + need_schedule = RT_TRUE; + } + + /* wakeup suspended thread */ + if (!rt_list_isempty(&mutex->parent.suspend_thread)) + { + /* get the first suspended thread */ + struct rt_thread *next_thread = rt_list_entry(mutex->parent.suspend_thread.next, + struct rt_thread, + tlist); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mutex_release: resume thread: %s\n", + next_thread->name)); + + /* remove the thread from the suspended list of mutex */ + rt_list_remove(&(next_thread->tlist)); + + /* set new owner and put mutex into taken list of thread */ + mutex->owner = next_thread; + mutex->hold = 1; + rt_list_insert_after(&next_thread->taken_object_list, &mutex->taken_list); + /* cleanup pending object */ + next_thread->pending_object = RT_NULL; + + /* resume thread */ + rt_thread_resume(next_thread); + + /* update mutex priority */ + if (!rt_list_isempty(&(mutex->parent.suspend_thread))) + { + struct rt_thread *th; + + th = rt_list_entry(mutex->parent.suspend_thread.next, + struct rt_thread, + tlist); + mutex->priority = th->current_priority; + } + else + { + mutex->priority = 0xff; + } + + need_schedule = RT_TRUE; + } + else + { + /* clear owner */ + mutex->owner = RT_NULL; + mutex->priority = 0xff; + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* perform a schedule */ + if (need_schedule == RT_TRUE) + rt_schedule(); + + return RT_EOK; +} +RTM_EXPORT(rt_mutex_release); + + +/** + * @brief This function will set some extra attributions of a mutex object. + * + * @note Currently this function does not implement the control function. + * + * @param mutex is a pointer to a mutex object. + * + * @param cmd is a command word used to configure some attributions of the mutex. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_mutex_control(rt_mutex_t mutex, int cmd, void *arg) +{ + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + + return -RT_ERROR; +} +RTM_EXPORT(rt_mutex_control); + +/**@}*/ +#endif /* RT_USING_MUTEX */ + +#ifdef RT_USING_EVENT +/** + * @addtogroup event + * @{ + */ + +/** + * @brief The function will initialize a static event object. + * + * @note For the static event object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_event_create() function will allocate memory space automatically + * and initialize the event. + * + * @see rt_event_create() + * + * @param event is a pointer to the event to initialize. It is assumed that storage for the event + * will be allocated in your application. + * + * @param name is a pointer to the name that given to the event. + * + * @param flag is the event flag, which determines the queuing way of how multiple threads wait + * when the event is not available. + * The event flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this event will become non-real-time threads. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_event_init(rt_event_t event, const char *name, rt_uint8_t flag) +{ + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(event->parent.parent), RT_Object_Class_Event, name); + + /* set parent flag */ + event->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(event->parent)); + + /* initialize event */ + event->set = 0; + + return RT_EOK; +} +RTM_EXPORT(rt_event_init); + + +/** + * @brief This function will detach a static event object. + * + * @note This function is used to detach a static event object which is initialized by rt_event_init() function. + * By contrast, the rt_event_delete() function will delete an event object. + * When the event is successfully detached, it will resume all suspended threads in the event list. + * + * @see rt_event_delete() + * + * @param event is a pointer to an event object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the event detach failed. + * + * @warning This function can ONLY detach a static event initialized by the rt_event_init() function. + * If the event is created by the rt_event_create() function, you MUST NOT USE this function to detach it, + * ONLY USE the rt_event_delete() function to complete the deletion. + */ +rt_err_t rt_event_detach(rt_event_t event) +{ + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + RT_ASSERT(rt_object_is_systemobject(&event->parent.parent)); + + /* resume all suspended thread */ + _ipc_list_resume_all(&(event->parent.suspend_thread)); + + /* detach event object */ + rt_object_detach(&(event->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_event_detach); + +#ifdef RT_USING_HEAP +/** + * @brief Creating an event object. + * + * @note For the event object, its memory space is allocated automatically. + * By contrast, the rt_event_init() function will initialize a static event object. + * + * @see rt_event_init() + * + * @param name is a pointer to the name that given to the event. + * + * @param flag is the event flag, which determines the queuing way of how multiple threads wait when the event + * is not available. + * The event flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this event will become non-real-time threads. + * + * @return Return a pointer to the event object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_event_t rt_event_create(const char *name, rt_uint8_t flag) +{ + rt_event_t event; + + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + event = (rt_event_t)rt_object_allocate(RT_Object_Class_Event, name); + if (event == RT_NULL) + return event; + + /* set parent */ + event->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(event->parent)); + + /* initialize event */ + event->set = 0; + + return event; +} +RTM_EXPORT(rt_event_create); + + +/** + * @brief This function will delete an event object and release the memory space. + * + * @note This function is used to delete an event object which is created by the rt_event_create() function. + * By contrast, the rt_event_detach() function will detach a static event object. + * When the event is successfully deleted, it will resume all suspended threads in the event list. + * + * @see rt_event_detach() + * + * @param event is a pointer to an event object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the event detach failed. + * + * @warning This function can ONLY delete an event initialized by the rt_event_create() function. + * If the event is initialized by the rt_event_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_event_detach() function to complete the detachment. + */ +rt_err_t rt_event_delete(rt_event_t event) +{ + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + RT_ASSERT(rt_object_is_systemobject(&event->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* resume all suspended thread */ + _ipc_list_resume_all(&(event->parent.suspend_thread)); + + /* delete event object */ + rt_object_delete(&(event->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_event_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will send an event to the event object. + * If there is a thread suspended on the event, the thread will be resumed. + * + * @note When using this function, you need to use the parameter (set) to specify the event flag of the event object, + * then the function will traverse the list of suspended threads waiting on the event object. + * If there is a thread suspended on the event, and the thread's event_info and the event flag of + * the current event object matches, the thread will be resumed. + * + * @param event is a pointer to the event object to be sent. + * + * @param set is a flag that you will set for this event's flag. + * You can set an event flag, or you can set multiple flags through OR logic operation. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the event detach failed. + */ +rt_err_t rt_event_send(rt_event_t event, rt_uint32_t set) +{ + struct rt_list_node *n; + struct rt_thread *thread; + rt_base_t level; + rt_base_t status; + rt_bool_t need_schedule; + + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + + if (set == 0) + return -RT_ERROR; + + need_schedule = RT_FALSE; + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* set event */ + event->set |= set; + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(event->parent.parent))); + + if (!rt_list_isempty(&event->parent.suspend_thread)) + { + /* search thread list to resume thread */ + n = event->parent.suspend_thread.next; + while (n != &(event->parent.suspend_thread)) + { + /* get thread */ + thread = rt_list_entry(n, struct rt_thread, tlist); + + status = -RT_ERROR; + if (thread->event_info & RT_EVENT_FLAG_AND) + { + if ((thread->event_set & event->set) == thread->event_set) + { + /* received an AND event */ + status = RT_EOK; + } + } + else if (thread->event_info & RT_EVENT_FLAG_OR) + { + if (thread->event_set & event->set) + { + /* save the received event set */ + thread->event_set = thread->event_set & event->set; + + /* received an OR event */ + status = RT_EOK; + } + } + else + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EINVAL; + } + + /* move node to the next */ + n = n->next; + + /* condition is satisfied, resume thread */ + if (status == RT_EOK) + { + /* clear event */ + if (thread->event_info & RT_EVENT_FLAG_CLEAR) + event->set &= ~thread->event_set; + + /* resume thread, and thread list breaks out */ + rt_thread_resume(thread); + thread->error = RT_EOK; + + /* need do a scheduling */ + need_schedule = RT_TRUE; + } + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do a schedule */ + if (need_schedule == RT_TRUE) + rt_schedule(); + + return RT_EOK; +} +RTM_EXPORT(rt_event_send); + + +/** + * @brief This function will receive an event from event object. if the event is unavailable, the thread shall wait for + * the event up to a specified time. + * + * @note If there are threads suspended on this semaphore, the first thread in the list of this semaphore object + * will be resumed, and a thread scheduling (rt_schedule) will be executed. + * If no threads are suspended on this semaphore, the count value sem->value of this semaphore will increase by 1. + * + * @param event is a pointer to the event object to be received. + * + * @param set is a flag that you will set for this event's flag. + * You can set an event flag, or you can set multiple flags through OR logic operation. + * + * @param option is the option of this receiving event, it indicates how the receiving event is operated. + * The option can be one or more of the following values, When selecting multiple values,use logical OR to operate. + * (NOTE: RT_EVENT_FLAG_OR and RT_EVENT_FLAG_AND can only select one): + * + * + * RT_EVENT_FLAG_OR The thread select to use logical OR to receive the event. + * + * RT_EVENT_FLAG_AND The thread select to use logical OR to receive the event. + * + * RT_EVENT_FLAG_CLEAR When the thread receives the corresponding event, the function + * determines whether to clear the event flag. + * + * @param timeout is a timeout period (unit: an OS tick). + * + * @param recved is a pointer to the received event. If you don't care about this value, you can use RT_NULL to set. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the semaphore release failed. + */ +static rt_err_t _rt_event_recv(rt_event_t event, + rt_uint32_t set, + rt_uint8_t option, + rt_int32_t timeout, + rt_uint32_t *recved, + int suspend_flag) +{ + struct rt_thread *thread; + rt_base_t level; + rt_base_t status; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE); + + if (set == 0) + return -RT_ERROR; + + /* initialize status */ + status = -RT_ERROR; + /* get current thread */ + thread = rt_thread_self(); + /* reset thread error */ + thread->error = -RT_EINTR; + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(event->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* check event set */ + if (option & RT_EVENT_FLAG_AND) + { + if ((event->set & set) == set) + status = RT_EOK; + } + else if (option & RT_EVENT_FLAG_OR) + { + if (event->set & set) + status = RT_EOK; + } + else + { + /* either RT_EVENT_FLAG_AND or RT_EVENT_FLAG_OR should be set */ + RT_ASSERT(0); + } + + if (status == RT_EOK) + { + thread->error = RT_EOK; + + /* set received event */ + if (recved) + *recved = (event->set & set); + + /* fill thread event info */ + thread->event_set = (event->set & set); + thread->event_info = option; + + /* received event */ + if (option & RT_EVENT_FLAG_CLEAR) + event->set &= ~set; + } + else if (timeout == 0) + { + /* no waiting */ + thread->error = -RT_ETIMEOUT; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + else + { + /* fill thread event info */ + thread->event_set = set; + thread->event_info = option; + + /* put thread to suspended thread list */ + ret = _ipc_list_suspend(&(event->parent.suspend_thread), + thread, + event->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* if there is a waiting timeout, active thread timer */ + if (timeout > 0) + { + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do a schedule */ + rt_schedule(); + + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* received an event, disable interrupt to protect */ + level = rt_hw_interrupt_disable(); + + /* set received event */ + if (recved) + *recved = thread->event_set; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(event->parent.parent))); + + return thread->error; +} + +rt_err_t rt_event_recv(rt_event_t event, + rt_uint32_t set, + rt_uint8_t option, + rt_int32_t timeout, + rt_uint32_t *recved) +{ + return _rt_event_recv(event, set, option, timeout, recved, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_event_recv); + +rt_err_t rt_event_recv_interruptible(rt_event_t event, + rt_uint32_t set, + rt_uint8_t option, + rt_int32_t timeout, + rt_uint32_t *recved) +{ + return _rt_event_recv(event, set, option, timeout, recved, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_event_recv_interruptible); + +rt_err_t rt_event_recv_killable(rt_event_t event, + rt_uint32_t set, + rt_uint8_t option, + rt_int32_t timeout, + rt_uint32_t *recved) +{ + return _rt_event_recv(event, set, option, timeout, recved, RT_KILLABLE); +} +RTM_EXPORT(rt_event_recv_killable); +/** + * @brief This function will set some extra attributions of an event object. + * + * @note Currently this function only supports the RT_IPC_CMD_RESET command to reset the event. + * + * @param event is a pointer to an event object. + * + * @param cmd is a command word used to configure some attributions of the event. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_event_control(rt_event_t event, int cmd, void *arg) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + + if (cmd == RT_IPC_CMD_RESET) + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* resume all waiting thread */ + _ipc_list_resume_all(&event->parent.suspend_thread); + + /* initialize event set */ + event->set = 0; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_event_control); + +/**@}*/ +#endif /* RT_USING_EVENT */ + +#ifdef RT_USING_MAILBOX +/** + * @addtogroup mailbox + * @{ + */ + +/** + * @brief Initialize a static mailbox object. + * + * @note For the static mailbox object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_mb_create() function will allocate memory space automatically and initialize the mailbox. + * + * @see rt_mb_create() + * + * @param mb is a pointer to the mailbox to initialize. + * It is assumed that storage for the mailbox will be allocated in your application. + * + * @param name is a pointer to the name that given to the mailbox. + * + * @param msgpool the begin address of buffer to save received mail. + * + * @param size is the maximum number of mails in the mailbox. + * For example, when the mailbox buffer capacity is N, size is N/4. + * + * @param flag is the mailbox flag, which determines the queuing way of how multiple threads wait + * when the mailbox is not available. + * The mailbox flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this mailbox will become non-real-time threads. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_mb_init(rt_mailbox_t mb, + const char *name, + void *msgpool, + rt_size_t size, + rt_uint8_t flag) +{ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(mb->parent.parent), RT_Object_Class_MailBox, name); + + /* set parent flag */ + mb->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(mb->parent)); + + /* initialize mailbox */ + mb->msg_pool = (rt_ubase_t *)msgpool; + mb->size = (rt_uint16_t)size; + mb->entry = 0; + mb->in_offset = 0; + mb->out_offset = 0; + + /* initialize an additional list of sender suspend thread */ + rt_list_init(&(mb->suspend_sender_thread)); + + return RT_EOK; +} +RTM_EXPORT(rt_mb_init); + + +/** + * @brief This function will detach a static mailbox object. + * + * @note This function is used to detach a static mailbox object which is initialized by rt_mb_init() function. + * By contrast, the rt_mb_delete() function will delete a mailbox object. + * When the mailbox is successfully detached, it will resume all suspended threads in the mailbox list. + * + * @see rt_mb_delete() + * + * @param mb is a pointer to a mailbox object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the mailbox detach failed. + * + * @warning This function can ONLY detach a static mailbox initialized by the rt_mb_init() function. + * If the mailbox is created by the rt_mb_create() function, you MUST NOT USE this function to detach it, + * ONLY USE the rt_mb_delete() function to complete the deletion. + */ +rt_err_t rt_mb_detach(rt_mailbox_t mb) +{ + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + RT_ASSERT(rt_object_is_systemobject(&mb->parent.parent)); + + /* resume all suspended thread */ + _ipc_list_resume_all(&(mb->parent.suspend_thread)); + /* also resume all mailbox private suspended thread */ + _ipc_list_resume_all(&(mb->suspend_sender_thread)); + + /* detach mailbox object */ + rt_object_detach(&(mb->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mb_detach); + +#ifdef RT_USING_HEAP +/** + * @brief Creating a mailbox object. + * + * @note For the mailbox object, its memory space is allocated automatically. + * By contrast, the rt_mb_init() function will initialize a static mailbox object. + * + * @see rt_mb_init() + * + * @param name is a pointer that given to the mailbox. + * + * @param size is the maximum number of mails in the mailbox. + * For example, when mailbox buffer capacity is N, size is N/4. + * + * @param flag is the mailbox flag, which determines the queuing way of how multiple threads wait + * when the mailbox is not available. + * The mailbox flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this mailbox will become non-real-time threads. + * + * @return Return a pointer to the mailbox object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_mailbox_t rt_mb_create(const char *name, rt_size_t size, rt_uint8_t flag) +{ + rt_mailbox_t mb; + + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + mb = (rt_mailbox_t)rt_object_allocate(RT_Object_Class_MailBox, name); + if (mb == RT_NULL) + return mb; + + /* set parent */ + mb->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(mb->parent)); + + /* initialize mailbox */ + mb->size = (rt_uint16_t)size; + mb->msg_pool = (rt_ubase_t *)RT_KERNEL_MALLOC(mb->size * sizeof(rt_ubase_t)); + if (mb->msg_pool == RT_NULL) + { + /* delete mailbox object */ + rt_object_delete(&(mb->parent.parent)); + + return RT_NULL; + } + mb->entry = 0; + mb->in_offset = 0; + mb->out_offset = 0; + + /* initialize an additional list of sender suspend thread */ + rt_list_init(&(mb->suspend_sender_thread)); + + return mb; +} +RTM_EXPORT(rt_mb_create); + + +/** + * @brief This function will delete a mailbox object and release the memory space. + * + * @note This function is used to delete a mailbox object which is created by the rt_mb_create() function. + * By contrast, the rt_mb_detach() function will detach a static mailbox object. + * When the mailbox is successfully deleted, it will resume all suspended threads in the mailbox list. + * + * @see rt_mb_detach() + * + * @param mb is a pointer to a mailbox object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + * + * @warning This function can only delete mailbox created by the rt_mb_create() function. + * If the mailbox is initialized by the rt_mb_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_mb_detach() function to complete the detachment. + */ +rt_err_t rt_mb_delete(rt_mailbox_t mb) +{ + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + RT_ASSERT(rt_object_is_systemobject(&mb->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* resume all suspended thread */ + _ipc_list_resume_all(&(mb->parent.suspend_thread)); + + /* also resume all mailbox private suspended thread */ + _ipc_list_resume_all(&(mb->suspend_sender_thread)); + + /* free mailbox pool */ + RT_KERNEL_FREE(mb->msg_pool); + + /* delete mailbox object */ + rt_object_delete(&(mb->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mb_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will send an mail to the mailbox object. If there is a thread suspended on the mailbox, + * the thread will be resumed. + * + * @note When using this function to send a mail, if the mailbox if fully used, the current thread will + * wait for a timeout. If the set timeout time is reached and there is still no space available, + * the sending thread will be resumed and an error code will be returned. + * By contrast, the rt_mb_send() function will return an error code immediately without waiting time + * when the mailbox if fully used. + * + * @see rt_mb_send() + * + * @param mb is a pointer to the mailbox object to be sent. + * + * @param value is a value to the content of the mail you want to send. + * + * @param timeout is a timeout period (unit: an OS tick). + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + * + * @warning This function can be called in interrupt context and thread context. + */ +static rt_err_t _rt_mb_send_wait(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout, + int suspend_flag) +{ + struct rt_thread *thread; + rt_base_t level; + rt_uint32_t tick_delta; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0); + + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mb->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* for non-blocking call */ + if (mb->entry == mb->size && timeout == 0) + { + rt_hw_interrupt_enable(level); + return -RT_EFULL; + } + + /* mailbox is full */ + while (mb->entry == mb->size) + { + /* reset error number in thread */ + thread->error = -RT_EINTR; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EFULL; + } + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mb->suspend_sender_thread), + thread, + mb->parent.parent.flag, + suspend_flag); + + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mb_send_wait: start timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* re-schedule */ + rt_schedule(); + + /* resume from suspend state */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + + /* set ptr */ + mb->msg_pool[mb->in_offset] = value; + /* increase input offset */ + ++ mb->in_offset; + if (mb->in_offset >= mb->size) + mb->in_offset = 0; + + if(mb->entry < RT_MB_ENTRY_MAX) + { + /* increase message entry */ + mb->entry ++; + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + + /* resume suspended thread */ + if (!rt_list_isempty(&mb->parent.suspend_thread)) + { + _ipc_list_resume(&(mb->parent.suspend_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} + +rt_err_t rt_mb_send_wait(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout) +{ + return _rt_mb_send_wait(mb, value, timeout, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mb_send_wait); + +rt_err_t rt_mb_send_wait_interruptible(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout) +{ + return _rt_mb_send_wait(mb, value, timeout, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mb_send_wait_interruptible); + +rt_err_t rt_mb_send_wait_killable(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout) +{ + return _rt_mb_send_wait(mb, value, timeout, RT_KILLABLE); +} +RTM_EXPORT(rt_mb_send_wait_killable); +/** + * @brief This function will send an mail to the mailbox object. If there is a thread suspended on the mailbox, + * the thread will be resumed. + * + * @note When using this function to send a mail, if the mailbox is fully used, this function will return an error + * code immediately without waiting time. + * By contrast, the rt_mb_send_wait() function is set a timeout to wait for the mail to be sent. + * + * @see rt_mb_send_wait() + * + * @param mb is a pointer to the mailbox object to be sent. + * + * @param value is a value to the content of the mail you want to send. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + */ +rt_err_t rt_mb_send(rt_mailbox_t mb, rt_ubase_t value) +{ + return rt_mb_send_wait(mb, value, 0); +} +RTM_EXPORT(rt_mb_send); + +rt_err_t rt_mb_send_interruptible(rt_mailbox_t mb, rt_ubase_t value) +{ + return rt_mb_send_wait_interruptible(mb, value, 0); +} +RTM_EXPORT(rt_mb_send_interruptible); + +rt_err_t rt_mb_send_killable(rt_mailbox_t mb, rt_ubase_t value) +{ + return rt_mb_send_wait_killable(mb, value, 0); +} +RTM_EXPORT(rt_mb_send_killable); + +/** + * @brief This function will send an urgent mail to the mailbox object. + * + * @note This function is almost the same as the rt_mb_send() function. The only difference is that + * when sending an urgent mail, the mail will be placed at the head of the mail queue so that + * the recipient can receive the urgent mail first. + * + * @see rt_mb_send() + * + * @param mb is a pointer to the mailbox object to be sent. + * + * @param value is the content of the mail you want to send. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + */ +rt_err_t rt_mb_urgent(rt_mailbox_t mb, rt_ubase_t value) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mb->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + if (mb->entry == mb->size) + { + rt_hw_interrupt_enable(level); + return -RT_EFULL; + } + + /* rewind to the previous position */ + if (mb->out_offset > 0) + { + mb->out_offset --; + } + else + { + mb->out_offset = mb->size - 1; + } + + /* set ptr */ + mb->msg_pool[mb->out_offset] = value; + + /* increase message entry */ + mb->entry ++; + + /* resume suspended thread */ + if (!rt_list_isempty(&mb->parent.suspend_thread)) + { + _ipc_list_resume(&(mb->parent.suspend_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} +RTM_EXPORT(rt_mb_urgent); + + +/** + * @brief This function will receive a mail from mailbox object, if there is no mail in mailbox object, + * the thread shall wait for a specified time. + * + * @note Only when there is mail in the mailbox, the receiving thread can get the mail immediately and + * return RT_EOK, otherwise the receiving thread will be suspended until the set timeout. If the mail + * is still not received within the specified time, it will return-RT_ETIMEOUT. + * + * @param mb is a pointer to the mailbox object to be received. + * + * @param value is a flag that you will set for this mailbox's flag. + * You can set an mailbox flag, or you can set multiple flags through OR logic operations. + * + * @param timeout is a timeout period (unit: an OS tick). If the mailbox object is not avaliable in the queue, + * the thread will wait for the object in the queue up to the amount of time specified by this parameter. + * + * NOTE: + * If use Macro RT_WAITING_FOREVER to set this parameter, which means that when the + * mailbox object is unavailable in the queue, the thread will be waiting forever. + * If use macro RT_WAITING_NO to set this parameter, which means that this + * function is non-blocking and will return immediately. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox release failed. + */ +static rt_err_t _rt_mb_recv(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout, int suspend_flag) +{ + struct rt_thread *thread; + rt_base_t level; + rt_uint32_t tick_delta; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0); + + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(mb->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* for non-blocking call */ + if (mb->entry == 0 && timeout == 0) + { + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + + /* mailbox is empty */ + while (mb->entry == 0) + { + /* reset error number in thread */ + thread->error = -RT_EINTR; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + thread->error = -RT_ETIMEOUT; + + return -RT_ETIMEOUT; + } + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mb->parent.suspend_thread), + thread, + mb->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mb_recv: start timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* re-schedule */ + rt_schedule(); + + /* resume from suspend state */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + + /* fill ptr */ + *value = mb->msg_pool[mb->out_offset]; + + /* increase output offset */ + ++ mb->out_offset; + if (mb->out_offset >= mb->size) + mb->out_offset = 0; + + /* decrease message entry */ + if(mb->entry > 0) + { + mb->entry --; + } + + /* resume suspended thread */ + if (!rt_list_isempty(&(mb->suspend_sender_thread))) + { + _ipc_list_resume(&(mb->suspend_sender_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mb->parent.parent))); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mb->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_mb_recv(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout) +{ + return _rt_mb_recv(mb, value, timeout, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mb_recv); + +rt_err_t rt_mb_recv_interruptibale(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout) +{ + return _rt_mb_recv(mb, value, timeout, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mb_recv_interruptibale); + +rt_err_t rt_mb_recv_killable(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout) +{ + return _rt_mb_recv(mb, value, timeout, RT_KILLABLE); +} +RTM_EXPORT(rt_mb_recv_killable); + +/** + * @brief This function will set some extra attributions of a mailbox object. + * + * @note Currently this function only supports the RT_IPC_CMD_RESET command to reset the mailbox. + * + * @param mb is a pointer to a mailbox object. + * + * @param cmd is a command used to configure some attributions of the mailbox. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_mb_control(rt_mailbox_t mb, int cmd, void *arg) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + + if (cmd == RT_IPC_CMD_RESET) + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* resume all waiting thread */ + _ipc_list_resume_all(&(mb->parent.suspend_thread)); + /* also resume all mailbox private suspended thread */ + _ipc_list_resume_all(&(mb->suspend_sender_thread)); + + /* re-init mailbox */ + mb->entry = 0; + mb->in_offset = 0; + mb->out_offset = 0; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_mb_control); + +/**@}*/ +#endif /* RT_USING_MAILBOX */ + +#ifdef RT_USING_MESSAGEQUEUE +/** + * @addtogroup messagequeue + * @{ + */ + +struct rt_mq_message +{ + struct rt_mq_message *next; +}; + + +/** + * @brief Initialize a static messagequeue object. + * + * @note For the static messagequeue object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_mq_create() function will allocate memory space automatically + * and initialize the messagequeue. + * + * @see rt_mq_create() + * + * @param mq is a pointer to the messagequeue to initialize. It is assumed that storage for + * the messagequeue will be allocated in your application. + * + * @param name is a pointer to the name that given to the messagequeue. + * + * @param msgpool is a pointer to the starting address of the memory space you allocated for + * the messagequeue in advance. + * In other words, msgpool is a pointer to the messagequeue buffer of the starting address. + * + * @param msg_size is the maximum length of a message in the messagequeue (Unit: Byte). + * + * @param pool_size is the size of the memory space allocated for the messagequeue in advance. + * + * @param flag is the messagequeue flag, which determines the queuing way of how multiple threads wait + * when the messagequeue is not available. + * The messagequeue flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this messagequeue will become non-real-time threads. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_mq_init(rt_mq_t mq, + const char *name, + void *msgpool, + rt_size_t msg_size, + rt_size_t pool_size, + rt_uint8_t flag) +{ + struct rt_mq_message *head; + rt_base_t temp; + register rt_size_t msg_align_size; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(mq->parent.parent), RT_Object_Class_MessageQueue, name); + + /* set parent flag */ + mq->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(mq->parent)); + + /* set message pool */ + mq->msg_pool = msgpool; + + /* get correct message size */ + msg_align_size = RT_ALIGN(msg_size, RT_ALIGN_SIZE); + mq->msg_size = msg_size; + mq->max_msgs = pool_size / (msg_align_size + sizeof(struct rt_mq_message)); + + if (0 == mq->max_msgs) + { + return -RT_EINVAL; + } + + /* initialize message list */ + mq->msg_queue_head = RT_NULL; + mq->msg_queue_tail = RT_NULL; + + /* initialize message empty list */ + mq->msg_queue_free = RT_NULL; + for (temp = 0; temp < mq->max_msgs; temp ++) + { + head = (struct rt_mq_message *)((rt_uint8_t *)mq->msg_pool + + temp * (msg_align_size + sizeof(struct rt_mq_message))); + head->next = (struct rt_mq_message *)mq->msg_queue_free; + mq->msg_queue_free = head; + } + + /* the initial entry is zero */ + mq->entry = 0; + + /* initialize an additional list of sender suspend thread */ + rt_list_init(&(mq->suspend_sender_thread)); + + return RT_EOK; +} +RTM_EXPORT(rt_mq_init); + + +/** + * @brief This function will detach a static messagequeue object. + * + * @note This function is used to detach a static messagequeue object which is initialized by rt_mq_init() function. + * By contrast, the rt_mq_delete() function will delete a messagequeue object. + * When the messagequeue is successfully detached, it will resume all suspended threads in the messagequeue list. + * + * @see rt_mq_delete() + * + * @param mq is a pointer to a messagequeue object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the messagequeue detach failed. + * + * @warning This function can ONLY detach a static messagequeue initialized by the rt_mq_init() function. + * If the messagequeue is created by the rt_mq_create() function, you MUST NOT USE this function to detach it, + * and ONLY USE the rt_mq_delete() function to complete the deletion. + */ +rt_err_t rt_mq_detach(rt_mq_t mq) +{ + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(rt_object_is_systemobject(&mq->parent.parent)); + + /* resume all suspended thread */ + _ipc_list_resume_all(&mq->parent.suspend_thread); + /* also resume all message queue private suspended thread */ + _ipc_list_resume_all(&(mq->suspend_sender_thread)); + + /* detach message queue object */ + rt_object_detach(&(mq->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mq_detach); + +#ifdef RT_USING_HEAP +/** + * @brief Creating a messagequeue object. + * + * @note For the messagequeue object, its memory space is allocated automatically. + * By contrast, the rt_mq_init() function will initialize a static messagequeue object. + * + * @see rt_mq_init() + * + * @param name is a pointer that given to the messagequeue. + * + * @param msg_size is the maximum length of a message in the messagequeue (Unit: Byte). + * + * @param max_msgs is the maximum number of messages in the messagequeue. + * + * @param flag is the messagequeue flag, which determines the queuing way of how multiple threads wait + * when the messagequeue is not available. + * The messagequeue flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this messagequeue will become non-real-time threads. + * + * @return Return a pointer to the messagequeue object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can NOT be called in interrupt context. You can use macor RT_DEBUG_NOT_IN_INTERRUPT to check it. + */ +rt_mq_t rt_mq_create(const char *name, + rt_size_t msg_size, + rt_size_t max_msgs, + rt_uint8_t flag) +{ + struct rt_messagequeue *mq; + struct rt_mq_message *head; + rt_base_t temp; + register rt_size_t msg_align_size; + + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + mq = (rt_mq_t)rt_object_allocate(RT_Object_Class_MessageQueue, name); + if (mq == RT_NULL) + return mq; + + /* set parent */ + mq->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(mq->parent)); + + /* initialize message queue */ + + /* get correct message size */ + msg_align_size = RT_ALIGN(msg_size, RT_ALIGN_SIZE); + mq->msg_size = msg_size; + mq->max_msgs = max_msgs; + + /* allocate message pool */ + mq->msg_pool = RT_KERNEL_MALLOC((msg_align_size + sizeof(struct rt_mq_message)) * mq->max_msgs); + if (mq->msg_pool == RT_NULL) + { + rt_object_delete(&(mq->parent.parent)); + + return RT_NULL; + } + + /* initialize message list */ + mq->msg_queue_head = RT_NULL; + mq->msg_queue_tail = RT_NULL; + + /* initialize message empty list */ + mq->msg_queue_free = RT_NULL; + for (temp = 0; temp < mq->max_msgs; temp ++) + { + head = (struct rt_mq_message *)((rt_uint8_t *)mq->msg_pool + + temp * (msg_align_size + sizeof(struct rt_mq_message))); + head->next = (struct rt_mq_message *)mq->msg_queue_free; + mq->msg_queue_free = head; + } + + /* the initial entry is zero */ + mq->entry = 0; + + /* initialize an additional list of sender suspend thread */ + rt_list_init(&(mq->suspend_sender_thread)); + + return mq; +} +RTM_EXPORT(rt_mq_create); + + +/** + * @brief This function will delete a messagequeue object and release the memory. + * + * @note This function is used to delete a messagequeue object which is created by the rt_mq_create() function. + * By contrast, the rt_mq_detach() function will detach a static messagequeue object. + * When the messagequeue is successfully deleted, it will resume all suspended threads in the messagequeue list. + * + * @see rt_mq_detach() + * + * @param mq is a pointer to a messagequeue object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the messagequeue detach failed. + * + * @warning This function can ONLY delete a messagequeue initialized by the rt_mq_create() function. + * If the messagequeue is initialized by the rt_mq_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_mq_detach() function to complete the detachment. + * for example,the rt_mq_create() function, it cannot be called in interrupt context. + */ +rt_err_t rt_mq_delete(rt_mq_t mq) +{ + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(rt_object_is_systemobject(&mq->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* resume all suspended thread */ + _ipc_list_resume_all(&(mq->parent.suspend_thread)); + /* also resume all message queue private suspended thread */ + _ipc_list_resume_all(&(mq->suspend_sender_thread)); + + /* free message queue pool */ + RT_KERNEL_FREE(mq->msg_pool); + + /* delete message queue object */ + rt_object_delete(&(mq->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mq_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will send a message to the messagequeue object. If + * there is a thread suspended on the messagequeue, the thread will be + * resumed. + * + * @note When using this function to send a message, if the messagequeue is + * fully used, the current thread will wait for a timeout. If reaching + * the timeout and there is still no space available, the sending + * thread will be resumed and an error code will be returned. By + * contrast, the rt_mq_send() function will return an error code + * immediately without waiting when the messagequeue if fully used. + * + * @see rt_mq_send() + * + * @param mq is a pointer to the messagequeue object to be sent. + * + * @param buffer is the content of the message. + * + * @param size is the length of the message(Unit: Byte). + * + * @param timeout is a timeout period (unit: an OS tick). + * + * @return Return the operation status. When the return value is RT_EOK, the + * operation is successful. If the return value is any other values, + * it means that the messagequeue detach failed. + * + * @warning This function can be called in interrupt context and thread + * context. + */ +static rt_err_t _rt_mq_send_wait(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout, + int suspend_flag) +{ + rt_base_t level; + struct rt_mq_message *msg; + rt_uint32_t tick_delta; + struct rt_thread *thread; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(buffer != RT_NULL); + RT_ASSERT(size != 0); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0); + + /* greater than one message size */ + if (size > mq->msg_size) + return -RT_ERROR; + + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mq->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* get a free list, there must be an empty item */ + msg = (struct rt_mq_message *)mq->msg_queue_free; + /* for non-blocking call */ + if (msg == RT_NULL && timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EFULL; + } + + /* message queue is full */ + while ((msg = (struct rt_mq_message *)mq->msg_queue_free) == RT_NULL) + { + /* reset error number in thread */ + thread->error = -RT_EINTR; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EFULL; + } + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mq->suspend_sender_thread), + thread, + mq->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mq_send_wait: start timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* re-schedule */ + rt_schedule(); + + /* resume from suspend state */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + + /* move free list pointer */ + mq->msg_queue_free = msg->next; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* the msg is the new tailer of list, the next shall be NULL */ + msg->next = RT_NULL; + /* copy buffer */ + rt_memcpy(msg + 1, buffer, size); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + /* link msg to message queue */ + if (mq->msg_queue_tail != RT_NULL) + { + /* if the tail exists, */ + ((struct rt_mq_message *)mq->msg_queue_tail)->next = msg; + } + + /* set new tail */ + mq->msg_queue_tail = msg; + /* if the head is empty, set head */ + if (mq->msg_queue_head == RT_NULL) + mq->msg_queue_head = msg; + + if(mq->entry < RT_MQ_ENTRY_MAX) + { + /* increase message entry */ + mq->entry ++; + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + + /* resume suspended thread */ + if (!rt_list_isempty(&mq->parent.suspend_thread)) + { + _ipc_list_resume(&(mq->parent.suspend_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} + +rt_err_t rt_mq_send_wait(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_send_wait(mq, buffer, size, timeout, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mq_send_wait) + +rt_err_t rt_mq_send_wait_interruptible(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_send_wait(mq, buffer, size, timeout, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mq_send_wait_interruptible) + +rt_err_t rt_mq_send_wait_killable(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_send_wait(mq, buffer, size, timeout, RT_KILLABLE); +} +RTM_EXPORT(rt_mq_send_wait_killable) +/** + * @brief This function will send a message to the messagequeue object. + * If there is a thread suspended on the messagequeue, the thread will be resumed. + * + * @note When using this function to send a message, if the messagequeue is fully used, + * the current thread will wait for a timeout. + * By contrast, when the messagequeue is fully used, the rt_mq_send_wait() function will + * return an error code immediately without waiting. + * + * @see rt_mq_send_wait() + * + * @param mq is a pointer to the messagequeue object to be sent. + * + * @param buffer is the content of the message. + * + * @param size is the length of the message(Unit: Byte). + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the messagequeue detach failed. + * + * @warning This function can be called in interrupt context and thread context. + */ +rt_err_t rt_mq_send(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + return rt_mq_send_wait(mq, buffer, size, 0); +} +RTM_EXPORT(rt_mq_send); + +rt_err_t rt_mq_send_interrupt(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + return rt_mq_send_wait_interruptible(mq, buffer, size, 0); +} +RTM_EXPORT(rt_mq_send_interrupt); + +rt_err_t rt_mq_send_killable(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + return rt_mq_send_wait_killable(mq, buffer, size, 0); +} +RTM_EXPORT(rt_mq_send_killable); +/** + * @brief This function will send an urgent message to the messagequeue object. + * + * @note This function is almost the same as the rt_mq_send() function. The only difference is that + * when sending an urgent message, the message is placed at the head of the messagequeue so that + * the recipient can receive the urgent message first. + * + * @see rt_mq_send() + * + * @param mq is a pointer to the messagequeue object to be sent. + * + * @param buffer is the content of the message. + * + * @param size is the length of the message(Unit: Byte). + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + */ +rt_err_t rt_mq_urgent(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + rt_base_t level; + struct rt_mq_message *msg; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(buffer != RT_NULL); + RT_ASSERT(size != 0); + + /* greater than one message size */ + if (size > mq->msg_size) + return -RT_ERROR; + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mq->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* get a free list, there must be an empty item */ + msg = (struct rt_mq_message *)mq->msg_queue_free; + /* message queue is full */ + if (msg == RT_NULL) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EFULL; + } + /* move free list pointer */ + mq->msg_queue_free = msg->next; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* copy buffer */ + rt_memcpy(msg + 1, buffer, size); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* link msg to the beginning of message queue */ + msg->next = (struct rt_mq_message *)mq->msg_queue_head; + mq->msg_queue_head = msg; + + /* if there is no tail */ + if (mq->msg_queue_tail == RT_NULL) + mq->msg_queue_tail = msg; + + if(mq->entry < RT_MQ_ENTRY_MAX) + { + /* increase message entry */ + mq->entry ++; + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + + /* resume suspended thread */ + if (!rt_list_isempty(&mq->parent.suspend_thread)) + { + _ipc_list_resume(&(mq->parent.suspend_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} +RTM_EXPORT(rt_mq_urgent); + + +/** + * @brief This function will receive a message from message queue object, + * if there is no message in messagequeue object, the thread shall wait for a specified time. + * + * @note Only when there is mail in the mailbox, the receiving thread can get the mail immediately and return RT_EOK, + * otherwise the receiving thread will be suspended until timeout. + * If the mail is not received within the specified time, it will return -RT_ETIMEOUT. + * + * @param mq is a pointer to the messagequeue object to be received. + * + * @param buffer is the content of the message. + * + * @param size is the length of the message(Unit: Byte). + * + * @param timeout is a timeout period (unit: an OS tick). If the message is unavailable, the thread will wait for + * the message in the queue up to the amount of time specified by this parameter. + * + * NOTE: + * If use Macro RT_WAITING_FOREVER to set this parameter, which means that when the + * message is unavailable in the queue, the thread will be waiting forever. + * If use macro RT_WAITING_NO to set this parameter, which means that this + * function is non-blocking and will return immediately. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox release failed. + */ +static rt_err_t _rt_mq_recv(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout, + int suspend_flag) +{ + struct rt_thread *thread; + rt_base_t level; + struct rt_mq_message *msg; + rt_uint32_t tick_delta; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(buffer != RT_NULL); + RT_ASSERT(size != 0); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0); + + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(mq->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* for non-blocking call */ + if (mq->entry == 0 && timeout == 0) + { + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + + /* message queue is empty */ + while (mq->entry == 0) + { + /* reset error number in thread */ + thread->error = -RT_EINTR; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + thread->error = -RT_ETIMEOUT; + + return -RT_ETIMEOUT; + } + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mq->parent.suspend_thread), + thread, + mq->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("set thread:%s to timer list\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* re-schedule */ + rt_schedule(); + + /* recv message */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + + /* get message from queue */ + msg = (struct rt_mq_message *)mq->msg_queue_head; + + /* move message queue head */ + mq->msg_queue_head = msg->next; + /* reach queue tail, set to NULL */ + if (mq->msg_queue_tail == msg) + mq->msg_queue_tail = RT_NULL; + + /* decrease message entry */ + if(mq->entry > 0) + { + mq->entry --; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* copy message */ + rt_memcpy(buffer, msg + 1, size > mq->msg_size ? mq->msg_size : size); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + /* put message to free list */ + msg->next = (struct rt_mq_message *)mq->msg_queue_free; + mq->msg_queue_free = msg; + + /* resume suspended thread */ + if (!rt_list_isempty(&(mq->suspend_sender_thread))) + { + _ipc_list_resume(&(mq->suspend_sender_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mq->parent.parent))); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mq->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_mq_recv(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_recv(mq, buffer, size, timeout, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mq_recv); + +rt_err_t rt_mq_recv_interruptible(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_recv(mq, buffer, size, timeout, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mq_recv_interruptible); + +rt_err_t rt_mq_recv_killable(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_recv(mq, buffer, size, timeout, RT_KILLABLE); +} +RTM_EXPORT(rt_mq_recv_killable); +/** + * @brief This function will set some extra attributions of a messagequeue object. + * + * @note Currently this function only supports the RT_IPC_CMD_RESET command to reset the messagequeue. + * + * @param mq is a pointer to a messagequeue object. + * + * @param cmd is a command used to configure some attributions of the messagequeue. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_mq_control(rt_mq_t mq, int cmd, void *arg) +{ + rt_base_t level; + struct rt_mq_message *msg; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + + if (cmd == RT_IPC_CMD_RESET) + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* resume all waiting thread */ + _ipc_list_resume_all(&mq->parent.suspend_thread); + /* also resume all message queue private suspended thread */ + _ipc_list_resume_all(&(mq->suspend_sender_thread)); + + /* release all message in the queue */ + while (mq->msg_queue_head != RT_NULL) + { + /* get message from queue */ + msg = (struct rt_mq_message *)mq->msg_queue_head; + + /* move message queue head */ + mq->msg_queue_head = msg->next; + /* reach queue tail, set to NULL */ + if (mq->msg_queue_tail == msg) + mq->msg_queue_tail = RT_NULL; + + /* put message to free list */ + msg->next = (struct rt_mq_message *)mq->msg_queue_free; + mq->msg_queue_free = msg; + } + + /* clean entry */ + mq->entry = 0; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_mq_control); + +/**@}*/ +#endif /* RT_USING_MESSAGEQUEUE */ +/**@}*/ diff --git a/tasks/concur-rtthread-mutex-ceilings/noop/src/ipc.c b/tasks/concur-rtthread-mutex-ceilings/noop/src/ipc.c new file mode 100644 index 00000000..84dfc712 --- /dev/null +++ b/tasks/concur-rtthread-mutex-ceilings/noop/src/ipc.c @@ -0,0 +1,3737 @@ +/* + * Copyright (c) 2006-2022, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +#include +#include + +#ifndef __on_rt_object_trytake_hook + #define __on_rt_object_trytake_hook(parent) __ON_HOOK_ARGS(rt_object_trytake_hook, (parent)) +#endif +#ifndef __on_rt_object_take_hook + #define __on_rt_object_take_hook(parent) __ON_HOOK_ARGS(rt_object_take_hook, (parent)) +#endif +#ifndef __on_rt_object_put_hook + #define __on_rt_object_put_hook(parent) __ON_HOOK_ARGS(rt_object_put_hook, (parent)) +#endif + +#if defined(RT_USING_HOOK) && defined(RT_HOOK_USING_FUNC_PTR) +extern void (*rt_object_trytake_hook)(struct rt_object *object); +extern void (*rt_object_take_hook)(struct rt_object *object); +extern void (*rt_object_put_hook)(struct rt_object *object); +#endif /* RT_USING_HOOK */ + +/** + * @addtogroup IPC + * @{ + */ + +/** + * @brief This function will initialize an IPC object, such as semaphore, mutex, messagequeue and mailbox. + * + * @note Executing this function will complete an initialization of the suspend thread list of the ipc object. + * + * @param ipc is a pointer to the IPC object. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * When the return value is any other values, it means the initialization failed. + * + * @warning This function can be called from all IPC initialization and creation. + */ +rt_inline rt_err_t _ipc_object_init(struct rt_ipc_object *ipc) +{ + /* initialize ipc object */ + rt_list_init(&(ipc->suspend_thread)); + + return RT_EOK; +} + + +/** + * @brief This function will suspend a thread to a IPC object list. + * + * @param list is a pointer to a suspended thread list of the IPC object. + * + * @param thread is a pointer to the thread object to be suspended. + * + * @param flag is a flag for the thread object to be suspended. It determines how the thread is suspended. + * The flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to use + * RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this semaphore will become non-real-time threads. + * + * @param suspend_flag status flag of the thread to be suspended. + * + * @return Return the operation status. When the return value is RT_EOK, the function is successfully executed. + * When the return value is any other values, it means the initialization failed. + * + * @warning This function can ONLY be called in the thread context, you can use RT_DEBUG_IN_THREAD_CONTEXT to + * check the context. + * In addition, this function is generally called by the following functions: + * rt_sem_take(), rt_mutex_take(), rt_event_recv(), rt_mb_send_wait(), + * rt_mb_recv(), rt_mq_recv(), rt_mq_send_wait() + */ +rt_inline rt_err_t _ipc_list_suspend(rt_list_t *list, + struct rt_thread *thread, + rt_uint8_t flag, + int suspend_flag) +{ + rt_err_t ret = rt_thread_suspend_with_flag(thread, suspend_flag); + + /* suspend thread */ + if (ret != RT_EOK) + { + return ret; + } + + switch (flag) + { + case RT_IPC_FLAG_FIFO: + rt_list_insert_before(list, &(thread->tlist)); + break; /* RT_IPC_FLAG_FIFO */ + + case RT_IPC_FLAG_PRIO: + { + struct rt_list_node *n; + struct rt_thread *sthread; + + /* find a suitable position */ + for (n = list->next; n != list; n = n->next) + { + sthread = rt_list_entry(n, struct rt_thread, tlist); + + /* find out */ + if (thread->current_priority < sthread->current_priority) + { + /* insert this thread before the sthread */ + rt_list_insert_before(&(sthread->tlist), &(thread->tlist)); + break; + } + } + + /* + * not found a suitable position, + * append to the end of suspend_thread list + */ + if (n == list) + rt_list_insert_before(list, &(thread->tlist)); + } + break;/* RT_IPC_FLAG_PRIO */ + + default: + RT_ASSERT(0); + break; + } + + return RT_EOK; +} + + +/** + * @brief This function will resume a thread. + * + * @note This function will resume the first thread in the list of a IPC object. + * 1. remove the thread from suspend queue of a IPC object. + * 2. put the thread into system ready queue. + * + * By contrast, the rt_ipc_list_resume_all() function will resume all suspended threads + * in the list of a IPC object. + * + * @param list is a pointer to a suspended thread list of the IPC object. + * + * @return Return the operation status. When the return value is RT_EOK, the function is successfully executed. + * When the return value is any other values, it means this operation failed. + * + * @warning This function is generally called by the following functions: + * rt_sem_release(), rt_mutex_release(), rt_mb_send_wait(), rt_mq_send_wait(), + * rt_mb_urgent(), rt_mb_recv(), rt_mq_urgent(), rt_mq_recv(), + */ +rt_inline rt_err_t _ipc_list_resume(rt_list_t *list) +{ + struct rt_thread *thread; + + /* get thread entry */ + thread = rt_list_entry(list->next, struct rt_thread, tlist); + + thread->error = RT_EOK; + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("resume thread:%s\n", thread->name)); + + /* resume it */ + rt_thread_resume(thread); + + return RT_EOK; +} + + +/** + * @brief This function will resume all suspended threads in the IPC object list, + * including the suspended list of IPC object, and private list of mailbox etc. + * + * @note This function will resume all threads in the IPC object list. + * By contrast, the rt_ipc_list_resume() function will resume a suspended thread in the list of a IPC object. + * + * @param list is a pointer to a suspended thread list of the IPC object. + * + * @return Return the operation status. When the return value is RT_EOK, the function is successfully executed. + * When the return value is any other values, it means this operation failed. + * + */ +rt_inline rt_err_t _ipc_list_resume_all(rt_list_t *list) +{ + struct rt_thread *thread; + rt_base_t level; + + /* wakeup all suspended threads */ + while (!rt_list_isempty(list)) + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* get next suspended thread */ + thread = rt_list_entry(list->next, struct rt_thread, tlist); + /* set error code to RT_ERROR */ + thread->error = -RT_ERROR; + + /* + * resume thread + * In rt_thread_resume function, it will remove current thread from + * suspended list + */ + rt_thread_resume(thread); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + } + + return RT_EOK; +} + +#ifdef RT_USING_SEMAPHORE +/** + * @addtogroup semaphore + * @{ + */ + +/** + * @brief This function will initialize a static semaphore object. + * + * @note For the static semaphore object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_sem_create() function will allocate memory space automatically and initialize + * the semaphore. + * + * @see rt_sem_create() + * + * @param sem is a pointer to the semaphore to initialize. It is assumed that storage for the semaphore will be + * allocated in your application. + * + * @param name is a pointer to the name you would like to give the semaphore. + * + * @param value is the initial value for the semaphore. + * If used to share resources, you should initialize the value as the number of available resources. + * If used to signal the occurrence of an event, you should initialize the value as 0. + * + * @param flag is the semaphore flag, which determines the queuing way of how multiple threads wait + * when the semaphore is not available. + * The semaphore flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this semaphore will become non-real-time threads. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_sem_init(rt_sem_t sem, + const char *name, + rt_uint32_t value, + rt_uint8_t flag) +{ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(value < 0x10000U); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(sem->parent.parent), RT_Object_Class_Semaphore, name); + + /* initialize ipc object */ + _ipc_object_init(&(sem->parent)); + + /* set initial value */ + sem->value = (rt_uint16_t)value; + + /* set parent */ + sem->parent.parent.flag = flag; + + return RT_EOK; +} +RTM_EXPORT(rt_sem_init); + + +/** + * @brief This function will detach a static semaphore object. + * + * @note This function is used to detach a static semaphore object which is initialized by rt_sem_init() function. + * By contrast, the rt_sem_delete() function will delete a semaphore object. + * When the semaphore is successfully detached, it will resume all suspended threads in the semaphore list. + * + * @see rt_sem_delete() + * + * @param sem is a pointer to a semaphore object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the semaphore detach failed. + * + * @warning This function can ONLY detach a static semaphore initialized by the rt_sem_init() function. + * If the semaphore is created by the rt_sem_create() function, you MUST NOT USE this function to detach it, + * ONLY USE the rt_sem_delete() function to complete the deletion. + */ +rt_err_t rt_sem_detach(rt_sem_t sem) +{ + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + RT_ASSERT(rt_object_is_systemobject(&sem->parent.parent)); + + /* wakeup all suspended threads */ + _ipc_list_resume_all(&(sem->parent.suspend_thread)); + + /* detach semaphore object */ + rt_object_detach(&(sem->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_sem_detach); + +#ifdef RT_USING_HEAP +/** + * @brief Creating a semaphore object. + * + * @note For the semaphore object, its memory space is allocated automatically. + * By contrast, the rt_sem_init() function will initialize a static semaphore object. + * + * @see rt_sem_init() + * + * @param name is a pointer to the name you would like to give the semaphore. + * + * @param value is the initial value for the semaphore. + * If used to share resources, you should initialize the value as the number of available resources. + * If used to signal the occurrence of an event, you should initialize the value as 0. + * + * @param flag is the semaphore flag, which determines the queuing way of how multiple threads wait + * when the semaphore is not available. + * The semaphore flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this semaphore will become non-real-time threads. + * + * @return Return a pointer to the semaphore object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can NOT be called in interrupt context. You can use macor RT_DEBUG_NOT_IN_INTERRUPT to check it. + */ +rt_sem_t rt_sem_create(const char *name, rt_uint32_t value, rt_uint8_t flag) +{ + rt_sem_t sem; + + RT_ASSERT(value < 0x10000U); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + sem = (rt_sem_t)rt_object_allocate(RT_Object_Class_Semaphore, name); + if (sem == RT_NULL) + return sem; + + /* initialize ipc object */ + _ipc_object_init(&(sem->parent)); + + /* set initial value */ + sem->value = value; + + /* set parent */ + sem->parent.parent.flag = flag; + + return sem; +} +RTM_EXPORT(rt_sem_create); + + +/** + * @brief This function will delete a semaphore object and release the memory space. + * + * @note This function is used to delete a semaphore object which is created by the rt_sem_create() function. + * By contrast, the rt_sem_detach() function will detach a static semaphore object. + * When the semaphore is successfully deleted, it will resume all suspended threads in the semaphore list. + * + * @see rt_sem_detach() + * + * @param sem is a pointer to a semaphore object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the semaphore detach failed. + * + * @warning This function can ONLY delete a semaphore initialized by the rt_sem_create() function. + * If the semaphore is initialized by the rt_sem_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_sem_detach() function to complete the detachment. + */ +rt_err_t rt_sem_delete(rt_sem_t sem) +{ + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + RT_ASSERT(rt_object_is_systemobject(&sem->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* wakeup all suspended threads */ + _ipc_list_resume_all(&(sem->parent.suspend_thread)); + + /* delete semaphore object */ + rt_object_delete(&(sem->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_sem_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will take a semaphore, if the semaphore is unavailable, the thread shall wait for + * the semaphore up to a specified time. + * + * @note When this function is called, the count value of the sem->value will decrease 1 until it is equal to 0. + * When the sem->value is 0, it means that the semaphore is unavailable. At this time, it will suspend the + * thread preparing to take the semaphore. + * On the contrary, the rt_sem_release() function will increase the count value of sem->value by 1 each time. + * + * @see rt_sem_trytake() + * + * @param sem is a pointer to a semaphore object. + * + * @param timeout is a timeout period (unit: an OS tick). If the semaphore is unavailable, the thread will wait for + * the semaphore up to the amount of time specified by this parameter. + * + * NOTE: + * If use Macro RT_WAITING_FOREVER to set this parameter, which means that when the + * message is unavailable in the queue, the thread will be waiting forever. + * If use macro RT_WAITING_NO to set this parameter, which means that this + * function is non-blocking and will return immediately. + * + * @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 semaphore take failed. + * + * @warning This function can ONLY be called in the thread context. It MUST NOT BE called in interrupt context. + */ +static rt_err_t _rt_sem_take(rt_sem_t sem, rt_int32_t timeout, int suspend_flag) +{ + rt_base_t level; + struct rt_thread *thread; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(sem->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("thread %s take sem:%s, which value is: %d\n", + rt_thread_self()->name, + ((struct rt_object *)sem)->name, + sem->value)); + + if (sem->value > 0) + { + /* semaphore is available */ + sem->value --; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + } + else + { + /* no waiting, return with timeout */ + if (timeout == 0) + { + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + else + { + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE); + + /* semaphore is unavailable, push to suspend list */ + /* get current thread */ + thread = rt_thread_self(); + + /* reset thread error number */ + thread->error = -RT_EINTR; + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("sem take: suspend thread - %s\n", + thread->name)); + + /* suspend thread */ + ret = _ipc_list_suspend(&(sem->parent.suspend_thread), + thread, + sem->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + RT_DEBUG_LOG(RT_DEBUG_IPC, ("set thread:%s to timer list\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do schedule */ + rt_schedule(); + + if (thread->error != RT_EOK) + { + return thread->error; + } + } + } + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(sem->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_sem_take(rt_sem_t sem, rt_int32_t time) +{ + return _rt_sem_take(sem, time, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_sem_take); + +rt_err_t rt_sem_take_interruptible(rt_sem_t sem, rt_int32_t time) +{ + return _rt_sem_take(sem, time, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_sem_take_interruptible); + +rt_err_t rt_sem_take_killable(rt_sem_t sem, rt_int32_t time) +{ + return _rt_sem_take(sem, time, RT_KILLABLE); +} +RTM_EXPORT(rt_sem_take_killable); + +/** + * @brief This function will try to take a semaphore, if the semaphore is unavailable, the thread returns immediately. + * + * @note This function is very similar to the rt_sem_take() function, when the semaphore is not available, + * the rt_sem_trytake() function will return immediately without waiting for a timeout. + * In other words, rt_sem_trytake(sem) has the same effect as rt_sem_take(sem, 0). + * + * @see rt_sem_take() + * + * @param sem is a pointer to a semaphore object. + * + * @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 semaphore take failed. + */ +rt_err_t rt_sem_trytake(rt_sem_t sem) +{ + return rt_sem_take(sem, RT_WAITING_NO); +} +RTM_EXPORT(rt_sem_trytake); + + +/** + * @brief This function will release a semaphore. If there is thread suspended on the semaphore, it will get resumed. + * + * @note If there are threads suspended on this semaphore, the first thread in the list of this semaphore object + * will be resumed, and a thread scheduling (rt_schedule) will be executed. + * If no threads are suspended on this semaphore, the count value sem->value of this semaphore will increase by 1. + * + * @param sem is a pointer to a semaphore object. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the semaphore release failed. + */ +rt_err_t rt_sem_release(rt_sem_t sem) +{ + rt_base_t level; + rt_bool_t need_schedule; + + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(sem->parent.parent))); + + need_schedule = RT_FALSE; + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("thread %s releases sem:%s, which value is: %d\n", + rt_thread_self()->name, + ((struct rt_object *)sem)->name, + sem->value)); + + if (!rt_list_isempty(&sem->parent.suspend_thread)) + { + /* resume the suspended thread */ + _ipc_list_resume(&(sem->parent.suspend_thread)); + need_schedule = RT_TRUE; + } + else + { + if(sem->value < RT_SEM_VALUE_MAX) + { + sem->value ++; /* increase value */ + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* resume a thread, re-schedule */ + if (need_schedule == RT_TRUE) + rt_schedule(); + + return RT_EOK; +} +RTM_EXPORT(rt_sem_release); + + +/** + * @brief This function will set some extra attributions of a semaphore object. + * + * @note Currently this function only supports the RT_IPC_CMD_RESET command to reset the semaphore. + * + * @param sem is a pointer to a semaphore object. + * + * @param cmd is a command word used to configure some attributions of the semaphore. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_sem_control(rt_sem_t sem, int cmd, void *arg) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + + if (cmd == RT_IPC_CMD_RESET) + { + rt_ubase_t value; + + /* get value */ + value = (rt_ubase_t)arg; + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* resume all waiting thread */ + _ipc_list_resume_all(&sem->parent.suspend_thread); + + /* set new value */ + sem->value = (rt_uint16_t)value; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_sem_control); + +/**@}*/ +#endif /* RT_USING_SEMAPHORE */ + +#ifdef RT_USING_MUTEX +rt_inline rt_uint8_t _mutex_update_priority(struct rt_mutex *mutex) +{ + struct rt_thread *thread; + + if (!rt_list_isempty(&mutex->parent.suspend_thread)) + { + thread = rt_list_entry(mutex->parent.suspend_thread.next, struct rt_thread, tlist); + mutex->priority = thread->current_priority; + } + else + { + mutex->priority = 0xff; + } + + return mutex->priority; +} + +rt_inline rt_uint8_t _thread_get_mutex_priority(struct rt_thread* thread) +{ + rt_list_t *node = RT_NULL; + struct rt_mutex *mutex = RT_NULL; + rt_uint8_t priority = thread->init_priority; + + rt_list_for_each(node, &(thread->taken_object_list)) + { + mutex = rt_list_entry(node, struct rt_mutex, taken_list); + if (priority > mutex->priority) + { + priority = mutex->priority; + } + } + + return priority; +} + +rt_inline void _thread_update_priority(struct rt_thread *thread, rt_uint8_t priority, int suspend_flag) +{ + rt_err_t ret; + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("thread:%s priority -> %d\n", thread->name, priority)); + + /* change priority of the thread */ + rt_thread_control(thread, + RT_THREAD_CTRL_CHANGE_PRIORITY, + &priority); + + if ((thread->stat & RT_THREAD_SUSPEND_MASK) == RT_THREAD_SUSPEND_MASK) + { + /* whether change the priority of taken mutex */ + struct rt_object* pending_obj = thread->pending_object; + + if (pending_obj && rt_object_get_type(pending_obj) == RT_Object_Class_Mutex) + { + rt_uint8_t mutex_priority; + struct rt_mutex* pending_mutex = (struct rt_mutex *)pending_obj; + + /* re-insert thread to suspended thread list */ + rt_list_remove(&(thread->tlist)); + + ret = _ipc_list_suspend(&(pending_mutex->parent.suspend_thread), + thread, + pending_mutex->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + /* TODO */ + return ; + } + + /* update priority */ + _mutex_update_priority(pending_mutex); + /* change the priority of mutex owner thread */ + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("mutex: %s priority -> %d\n", pending_mutex->parent.parent.name, + pending_mutex->priority)); + + mutex_priority = _thread_get_mutex_priority(pending_mutex->owner); + if (mutex_priority != pending_mutex->owner->current_priority) + { + _thread_update_priority(pending_mutex->owner, mutex_priority, suspend_flag); + } + } + } +} + +/** + * @addtogroup mutex + * @{ + */ + +/** + * @brief Initialize a static mutex object. + * + * @note For the static mutex object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_mutex_create() function will automatically allocate memory space + * and initialize the mutex. + * + * @see rt_mutex_create() + * + * @param mutex is a pointer to the mutex to initialize. It is assumed that storage for the mutex will be + * allocated in your application. + * + * @param name is a pointer to the name that given to the mutex. + * + * @param flag is the mutex flag, which determines the queuing way of how multiple threads wait + * when the mutex is not available. + * NOTE: This parameter has been obsoleted. It can be RT_IPC_FLAG_PRIO, RT_IPC_FLAG_FIFO or RT_NULL. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_mutex_init(rt_mutex_t mutex, const char *name, rt_uint8_t flag) +{ + /* flag parameter has been obsoleted */ + RT_UNUSED(flag); + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + + /* initialize object */ + rt_object_init(&(mutex->parent.parent), RT_Object_Class_Mutex, name); + + /* initialize ipc object */ + _ipc_object_init(&(mutex->parent)); + + mutex->owner = RT_NULL; + mutex->priority = 0xFF; + mutex->hold = 0; + mutex->ceiling_priority = 0xFF; + rt_list_init(&(mutex->taken_list)); + + /* flag can only be RT_IPC_FLAG_PRIO. RT_IPC_FLAG_FIFO cannot solve the unbounded priority inversion problem */ + mutex->parent.parent.flag = RT_IPC_FLAG_PRIO; + + return RT_EOK; +} +RTM_EXPORT(rt_mutex_init); + + +/** + * @brief This function will detach a static mutex object. + * + * @note This function is used to detach a static mutex object which is initialized by rt_mutex_init() function. + * By contrast, the rt_mutex_delete() function will delete a mutex object. + * When the mutex is successfully detached, it will resume all suspended threads in the mutex list. + * + * @see rt_mutex_delete() + * + * @param mutex is a pointer to a mutex object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the mutex detach failed. + * + * @warning This function can ONLY detach a static mutex initialized by the rt_mutex_init() function. + * If the mutex is created by the rt_mutex_create() function, you MUST NOT USE this function to detach it, + * ONLY USE the rt_mutex_delete() function to complete the deletion. + */ +rt_err_t rt_mutex_detach(rt_mutex_t mutex) +{ + rt_ubase_t level; + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + RT_ASSERT(rt_object_is_systemobject(&mutex->parent.parent)); + + level = rt_hw_interrupt_disable(); + /* wakeup all suspended threads */ + _ipc_list_resume_all(&(mutex->parent.suspend_thread)); + /* remove mutex from thread's taken list */ + rt_list_remove(&mutex->taken_list); + rt_hw_interrupt_enable(level); + + /* detach mutex object */ + rt_object_detach(&(mutex->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mutex_detach); + +/* drop a thread from the suspend list of mutex */ + +/** + * @brief drop a thread from the suspend list of mutex + * + * @param mutex is a pointer to a mutex object. + * @param thread is the thread should be dropped from mutex. + */ +void rt_mutex_drop_thread(rt_mutex_t mutex, rt_thread_t thread) +{ + rt_uint8_t priority; + rt_bool_t need_update = RT_FALSE; + + rt_list_remove(&(thread->tlist)); + + /* should change the priority of mutex owner thread */ + if (mutex->owner->current_priority == thread->current_priority) + need_update = RT_TRUE; + + /* update the priority of mutex */ + if (!rt_list_isempty(&mutex->parent.suspend_thread)) + { + /* more thread suspended in the list */ + struct rt_thread *th; + + th = rt_list_entry(mutex->parent.suspend_thread.next, + struct rt_thread, + tlist); + /* update the priority of mutex */ + mutex->priority = th->current_priority; + } + else + { + /* set mutex priority to maximal priority */ + mutex->priority = 0xff; + } + + /* try to change the priority of mutex owner thread */ + if (need_update) + { + /* get the maximal priority of mutex in thread */ + priority = _thread_get_mutex_priority(mutex->owner); + if (priority != mutex->owner->current_priority) + { + _thread_update_priority(mutex->owner, priority, RT_UNINTERRUPTIBLE); + } + } +} + + +/** + * @brief set the prioceiling attribute of the mutex. + * + * @param mutex is a pointer to a mutex object. + * @param priority is the priority should be set to mutex. + * + * @return return the old priority ceiling + */ +rt_uint8_t rt_mutex_setprioceiling(rt_mutex_t mutex, rt_uint8_t priority) +{ + rt_uint8_t ret_priority = 0xFF; + + if ((mutex) && (priority < RT_THREAD_PRIORITY_MAX)) + { + ret_priority = mutex->ceiling_priority; + mutex->ceiling_priority = priority; + } + else + { + rt_set_errno(-RT_EINVAL); + } + + return ret_priority; +} +RTM_EXPORT(rt_mutex_setprioceiling); + + +/** + * @brief set the prioceiling attribute of the mutex. + * + * @param mutex is a pointer to a mutex object. + * + * @return return the current priority ceiling of the mutex. + */ +rt_uint8_t rt_mutex_getprioceiling(rt_mutex_t mutex) +{ + rt_uint8_t prio = 0xFF; + + if (mutex) + { + prio = mutex->ceiling_priority; + } + + return prio; +} +RTM_EXPORT(rt_mutex_getprioceiling); + + +#ifdef RT_USING_HEAP +/** + * @brief This function will create a mutex object. + * + * @note For the mutex object, its memory space is automatically allocated. + * By contrast, the rt_mutex_init() function will initialize a static mutex object. + * + * @see rt_mutex_init() + * + * @param name is a pointer to the name that given to the mutex. + * + * @param flag is the mutex flag, which determines the queuing way of how multiple threads wait + * when the mutex is not available. + * NOTE: This parameter has been obsoleted. It can be RT_IPC_FLAG_PRIO, RT_IPC_FLAG_FIFO or RT_NULL. + * + * @return Return a pointer to the mutex object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_mutex_t rt_mutex_create(const char *name, rt_uint8_t flag) +{ + struct rt_mutex *mutex; + + /* flag parameter has been obsoleted */ + RT_UNUSED(flag); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + mutex = (rt_mutex_t)rt_object_allocate(RT_Object_Class_Mutex, name); + if (mutex == RT_NULL) + return mutex; + + /* initialize ipc object */ + _ipc_object_init(&(mutex->parent)); + + mutex->owner = RT_NULL; + mutex->priority = 0xFF; + mutex->hold = 0; + mutex->ceiling_priority = 0xFF; + rt_list_init(&(mutex->taken_list)); + + /* flag can only be RT_IPC_FLAG_PRIO. RT_IPC_FLAG_FIFO cannot solve the unbounded priority inversion problem */ + mutex->parent.parent.flag = RT_IPC_FLAG_PRIO; + + return mutex; +} +RTM_EXPORT(rt_mutex_create); + + +/** + * @brief This function will delete a mutex object and release this memory space. + * + * @note This function is used to delete a mutex object which is created by the rt_mutex_create() function. + * By contrast, the rt_mutex_detach() function will detach a static mutex object. + * When the mutex is successfully deleted, it will resume all suspended threads in the mutex list. + * + * @see rt_mutex_detach() + * + * @param mutex is a pointer to a mutex object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mutex detach failed. + * + * @warning This function can ONLY delete a mutex initialized by the rt_mutex_create() function. + * If the mutex is initialized by the rt_mutex_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_mutex_detach() function to complete the detachment. + */ +rt_err_t rt_mutex_delete(rt_mutex_t mutex) +{ + rt_ubase_t level; + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + RT_ASSERT(rt_object_is_systemobject(&mutex->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + level = rt_hw_interrupt_disable(); + /* wakeup all suspended threads */ + _ipc_list_resume_all(&(mutex->parent.suspend_thread)); + /* remove mutex from thread's taken list */ + rt_list_remove(&mutex->taken_list); + rt_hw_interrupt_enable(level); + + /* delete mutex object */ + rt_object_delete(&(mutex->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mutex_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will take a mutex, if the mutex is unavailable, the thread shall wait for + * the mutex up to a specified time. + * + * @note When this function is called, the count value of the mutex->value will decrease 1 until it is equal to 0. + * When the mutex->value is 0, it means that the mutex is unavailable. At this time, it will suspend the + * thread preparing to take the mutex. + * On the contrary, the rt_mutex_release() function will increase the count value of mutex->value by 1 each time. + * + * @see rt_mutex_trytake() + * + * @param mutex is a pointer to a mutex object. + * + * @param timeout is a timeout period (unit: an OS tick). If the mutex is unavailable, the thread will wait for + * the mutex up to the amount of time specified by the argument. + * NOTE: Generally, we set this parameter to RT_WAITING_FOREVER, which means that when the mutex is unavailable, + * the thread will be waitting forever. + * + * @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 mutex take failed. + * + * @warning This function can ONLY be called in the thread context. It MUST NOT BE called in interrupt context. + */ +static rt_err_t _rt_mutex_take(rt_mutex_t mutex, rt_int32_t timeout, int suspend_flag) +{ + rt_base_t level; + struct rt_thread *thread; + rt_err_t ret; + + /* this function must not be used in interrupt even if time = 0 */ + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE); + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + + /* get current thread */ + thread = rt_thread_self(); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(mutex->parent.parent))); + + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("mutex_take: current thread %s, hold: %d\n", + thread->name, mutex->hold)); + + /* reset thread error */ + thread->error = RT_EOK; + + if (mutex->owner == thread) + { + if(mutex->hold < RT_MUTEX_HOLD_MAX) + { + /* it's the same thread */ + mutex->hold ++; + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + } + else + { + /* whether the mutex has owner thread. */ + if (mutex->owner == RT_NULL) + { + /* set mutex owner and original priority */ + mutex->owner = thread; + mutex->priority = 0xff; + mutex->hold = 1; + + if (mutex->ceiling_priority != 0xFF) + { + /* set the priority of thread to the ceiling priority */ + if (mutex->ceiling_priority < mutex->owner->current_priority) + _thread_update_priority(mutex->owner, mutex->ceiling_priority, suspend_flag); + } + else + { + /* insert mutex to thread's taken object list */ + rt_list_insert_after(&thread->taken_object_list, &mutex->taken_list); + } + } + else + { + /* no waiting, return with timeout */ + if (timeout == 0) + { + /* set error as timeout */ + thread->error = -RT_ETIMEOUT; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + else + { + rt_uint8_t priority = thread->current_priority; + + /* mutex is unavailable, push to suspend list */ + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mutex_take: suspend thread: %s\n", + thread->name)); + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mutex->parent.suspend_thread), + thread, + mutex->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* set pending object in thread to this mutex */ + thread->pending_object = &(mutex->parent.parent); + + /* update the priority level of mutex */ + if (priority < mutex->priority) + { + mutex->priority = priority; + if (mutex->priority < mutex->owner->current_priority) + { + _thread_update_priority(mutex->owner, priority, RT_UNINTERRUPTIBLE); /* TODO */ + } + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("mutex_take: start the timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do schedule */ + rt_schedule(); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + if (thread->error == RT_EOK) + { + /* get mutex successfully */ + } + else + { + /* the mutex has not been taken and thread has detach from the pending list. */ + + rt_bool_t need_update = RT_FALSE; + + /* should change the priority of mutex owner thread */ + if (mutex->owner->current_priority == thread->current_priority) + need_update = RT_TRUE; + + /* update the priority of mutex */ + if (!rt_list_isempty(&mutex->parent.suspend_thread)) + { + /* more thread suspended in the list */ + struct rt_thread *th; + + th = rt_list_entry(mutex->parent.suspend_thread.next, + struct rt_thread, + tlist); + /* update the priority of mutex */ + mutex->priority = th->current_priority; + } + else + { + /* set mutex priority to maximal priority */ + mutex->priority = 0xff; + } + + /* try to change the priority of mutex owner thread */ + if (need_update) + { + /* get the maximal priority of mutex in thread */ + priority = _thread_get_mutex_priority(mutex->owner); + if (priority != mutex->owner->current_priority) + { + _thread_update_priority(mutex->owner, priority, RT_UNINTERRUPTIBLE); + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* return error */ + return thread->error; + } + } + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mutex->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_mutex_take(rt_mutex_t mutex, rt_int32_t time) +{ + return RT_EOK; +} +RTM_EXPORT(rt_mutex_take); + +rt_err_t rt_mutex_take_interruptible(rt_mutex_t mutex, rt_int32_t time) +{ + return _rt_mutex_take(mutex, time, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mutex_take_interruptible); + +rt_err_t rt_mutex_take_killable(rt_mutex_t mutex, rt_int32_t time) +{ + return _rt_mutex_take(mutex, time, RT_KILLABLE); +} +RTM_EXPORT(rt_mutex_take_killable); + +/** + * @brief This function will try to take a mutex, if the mutex is unavailable, the thread returns immediately. + * + * @note This function is very similar to the rt_mutex_take() function, when the mutex is not available, + * except that rt_mutex_trytake() will return immediately without waiting for a timeout + * when the mutex is not available. + * In other words, rt_mutex_trytake(mutex) has the same effect as rt_mutex_take(mutex, 0). + * + * @see rt_mutex_take() + * + * @param mutex is a pointer to a mutex object. + * + * @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 mutex take failed. + */ +rt_err_t rt_mutex_trytake(rt_mutex_t mutex) +{ + return rt_mutex_take(mutex, RT_WAITING_NO); +} +RTM_EXPORT(rt_mutex_trytake); + + +/** + * @brief This function will release a mutex. If there is thread suspended on the mutex, the thread will be resumed. + * + * @note If there are threads suspended on this mutex, the first thread in the list of this mutex object + * will be resumed, and a thread scheduling (rt_schedule) will be executed. + * If no threads are suspended on this mutex, the count value mutex->value of this mutex will increase by 1. + * + * @param mutex is a pointer to a mutex object. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mutex release failed. + */ +rt_err_t rt_mutex_release(rt_mutex_t mutex) +{ + rt_base_t level; + struct rt_thread *thread; + rt_bool_t need_schedule; + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + + need_schedule = RT_FALSE; + + /* only thread could release mutex because we need test the ownership */ + RT_DEBUG_IN_THREAD_CONTEXT; + + /* get current thread */ + thread = rt_thread_self(); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("mutex_release:current thread %s, hold: %d\n", + thread->name, mutex->hold)); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mutex->parent.parent))); + + /* mutex only can be released by owner */ + if (thread != mutex->owner) + { + thread->error = -RT_ERROR; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_ERROR; + } + + /* decrease hold */ + mutex->hold --; + /* if no hold */ + if (mutex->hold == 0) + { + /* remove mutex from thread's taken list */ + rt_list_remove(&mutex->taken_list); + + /* whether change the thread priority */ + if ((mutex->ceiling_priority != 0xFF) || (thread->current_priority == mutex->priority)) + { + rt_uint8_t priority = 0xff; + + /* get the highest priority in the taken list of thread */ + priority = _thread_get_mutex_priority(thread); + + rt_thread_control(thread, + RT_THREAD_CTRL_CHANGE_PRIORITY, + &priority); + + need_schedule = RT_TRUE; + } + + /* wakeup suspended thread */ + if (!rt_list_isempty(&mutex->parent.suspend_thread)) + { + /* get the first suspended thread */ + struct rt_thread *next_thread = rt_list_entry(mutex->parent.suspend_thread.next, + struct rt_thread, + tlist); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mutex_release: resume thread: %s\n", + next_thread->name)); + + /* remove the thread from the suspended list of mutex */ + rt_list_remove(&(next_thread->tlist)); + + /* set new owner and put mutex into taken list of thread */ + mutex->owner = next_thread; + mutex->hold = 1; + rt_list_insert_after(&next_thread->taken_object_list, &mutex->taken_list); + /* cleanup pending object */ + next_thread->pending_object = RT_NULL; + + /* resume thread */ + rt_thread_resume(next_thread); + + /* update mutex priority */ + if (!rt_list_isempty(&(mutex->parent.suspend_thread))) + { + struct rt_thread *th; + + th = rt_list_entry(mutex->parent.suspend_thread.next, + struct rt_thread, + tlist); + mutex->priority = th->current_priority; + } + else + { + mutex->priority = 0xff; + } + + need_schedule = RT_TRUE; + } + else + { + /* clear owner */ + mutex->owner = RT_NULL; + mutex->priority = 0xff; + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* perform a schedule */ + if (need_schedule == RT_TRUE) + rt_schedule(); + + return RT_EOK; +} +RTM_EXPORT(rt_mutex_release); + + +/** + * @brief This function will set some extra attributions of a mutex object. + * + * @note Currently this function does not implement the control function. + * + * @param mutex is a pointer to a mutex object. + * + * @param cmd is a command word used to configure some attributions of the mutex. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_mutex_control(rt_mutex_t mutex, int cmd, void *arg) +{ + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + + return -RT_ERROR; +} +RTM_EXPORT(rt_mutex_control); + +/**@}*/ +#endif /* RT_USING_MUTEX */ + +#ifdef RT_USING_EVENT +/** + * @addtogroup event + * @{ + */ + +/** + * @brief The function will initialize a static event object. + * + * @note For the static event object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_event_create() function will allocate memory space automatically + * and initialize the event. + * + * @see rt_event_create() + * + * @param event is a pointer to the event to initialize. It is assumed that storage for the event + * will be allocated in your application. + * + * @param name is a pointer to the name that given to the event. + * + * @param flag is the event flag, which determines the queuing way of how multiple threads wait + * when the event is not available. + * The event flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this event will become non-real-time threads. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_event_init(rt_event_t event, const char *name, rt_uint8_t flag) +{ + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(event->parent.parent), RT_Object_Class_Event, name); + + /* set parent flag */ + event->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(event->parent)); + + /* initialize event */ + event->set = 0; + + return RT_EOK; +} +RTM_EXPORT(rt_event_init); + + +/** + * @brief This function will detach a static event object. + * + * @note This function is used to detach a static event object which is initialized by rt_event_init() function. + * By contrast, the rt_event_delete() function will delete an event object. + * When the event is successfully detached, it will resume all suspended threads in the event list. + * + * @see rt_event_delete() + * + * @param event is a pointer to an event object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the event detach failed. + * + * @warning This function can ONLY detach a static event initialized by the rt_event_init() function. + * If the event is created by the rt_event_create() function, you MUST NOT USE this function to detach it, + * ONLY USE the rt_event_delete() function to complete the deletion. + */ +rt_err_t rt_event_detach(rt_event_t event) +{ + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + RT_ASSERT(rt_object_is_systemobject(&event->parent.parent)); + + /* resume all suspended thread */ + _ipc_list_resume_all(&(event->parent.suspend_thread)); + + /* detach event object */ + rt_object_detach(&(event->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_event_detach); + +#ifdef RT_USING_HEAP +/** + * @brief Creating an event object. + * + * @note For the event object, its memory space is allocated automatically. + * By contrast, the rt_event_init() function will initialize a static event object. + * + * @see rt_event_init() + * + * @param name is a pointer to the name that given to the event. + * + * @param flag is the event flag, which determines the queuing way of how multiple threads wait when the event + * is not available. + * The event flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this event will become non-real-time threads. + * + * @return Return a pointer to the event object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_event_t rt_event_create(const char *name, rt_uint8_t flag) +{ + rt_event_t event; + + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + event = (rt_event_t)rt_object_allocate(RT_Object_Class_Event, name); + if (event == RT_NULL) + return event; + + /* set parent */ + event->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(event->parent)); + + /* initialize event */ + event->set = 0; + + return event; +} +RTM_EXPORT(rt_event_create); + + +/** + * @brief This function will delete an event object and release the memory space. + * + * @note This function is used to delete an event object which is created by the rt_event_create() function. + * By contrast, the rt_event_detach() function will detach a static event object. + * When the event is successfully deleted, it will resume all suspended threads in the event list. + * + * @see rt_event_detach() + * + * @param event is a pointer to an event object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the event detach failed. + * + * @warning This function can ONLY delete an event initialized by the rt_event_create() function. + * If the event is initialized by the rt_event_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_event_detach() function to complete the detachment. + */ +rt_err_t rt_event_delete(rt_event_t event) +{ + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + RT_ASSERT(rt_object_is_systemobject(&event->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* resume all suspended thread */ + _ipc_list_resume_all(&(event->parent.suspend_thread)); + + /* delete event object */ + rt_object_delete(&(event->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_event_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will send an event to the event object. + * If there is a thread suspended on the event, the thread will be resumed. + * + * @note When using this function, you need to use the parameter (set) to specify the event flag of the event object, + * then the function will traverse the list of suspended threads waiting on the event object. + * If there is a thread suspended on the event, and the thread's event_info and the event flag of + * the current event object matches, the thread will be resumed. + * + * @param event is a pointer to the event object to be sent. + * + * @param set is a flag that you will set for this event's flag. + * You can set an event flag, or you can set multiple flags through OR logic operation. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the event detach failed. + */ +rt_err_t rt_event_send(rt_event_t event, rt_uint32_t set) +{ + struct rt_list_node *n; + struct rt_thread *thread; + rt_base_t level; + rt_base_t status; + rt_bool_t need_schedule; + + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + + if (set == 0) + return -RT_ERROR; + + need_schedule = RT_FALSE; + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* set event */ + event->set |= set; + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(event->parent.parent))); + + if (!rt_list_isempty(&event->parent.suspend_thread)) + { + /* search thread list to resume thread */ + n = event->parent.suspend_thread.next; + while (n != &(event->parent.suspend_thread)) + { + /* get thread */ + thread = rt_list_entry(n, struct rt_thread, tlist); + + status = -RT_ERROR; + if (thread->event_info & RT_EVENT_FLAG_AND) + { + if ((thread->event_set & event->set) == thread->event_set) + { + /* received an AND event */ + status = RT_EOK; + } + } + else if (thread->event_info & RT_EVENT_FLAG_OR) + { + if (thread->event_set & event->set) + { + /* save the received event set */ + thread->event_set = thread->event_set & event->set; + + /* received an OR event */ + status = RT_EOK; + } + } + else + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EINVAL; + } + + /* move node to the next */ + n = n->next; + + /* condition is satisfied, resume thread */ + if (status == RT_EOK) + { + /* clear event */ + if (thread->event_info & RT_EVENT_FLAG_CLEAR) + event->set &= ~thread->event_set; + + /* resume thread, and thread list breaks out */ + rt_thread_resume(thread); + thread->error = RT_EOK; + + /* need do a scheduling */ + need_schedule = RT_TRUE; + } + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do a schedule */ + if (need_schedule == RT_TRUE) + rt_schedule(); + + return RT_EOK; +} +RTM_EXPORT(rt_event_send); + + +/** + * @brief This function will receive an event from event object. if the event is unavailable, the thread shall wait for + * the event up to a specified time. + * + * @note If there are threads suspended on this semaphore, the first thread in the list of this semaphore object + * will be resumed, and a thread scheduling (rt_schedule) will be executed. + * If no threads are suspended on this semaphore, the count value sem->value of this semaphore will increase by 1. + * + * @param event is a pointer to the event object to be received. + * + * @param set is a flag that you will set for this event's flag. + * You can set an event flag, or you can set multiple flags through OR logic operation. + * + * @param option is the option of this receiving event, it indicates how the receiving event is operated. + * The option can be one or more of the following values, When selecting multiple values,use logical OR to operate. + * (NOTE: RT_EVENT_FLAG_OR and RT_EVENT_FLAG_AND can only select one): + * + * + * RT_EVENT_FLAG_OR The thread select to use logical OR to receive the event. + * + * RT_EVENT_FLAG_AND The thread select to use logical OR to receive the event. + * + * RT_EVENT_FLAG_CLEAR When the thread receives the corresponding event, the function + * determines whether to clear the event flag. + * + * @param timeout is a timeout period (unit: an OS tick). + * + * @param recved is a pointer to the received event. If you don't care about this value, you can use RT_NULL to set. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the semaphore release failed. + */ +static rt_err_t _rt_event_recv(rt_event_t event, + rt_uint32_t set, + rt_uint8_t option, + rt_int32_t timeout, + rt_uint32_t *recved, + int suspend_flag) +{ + struct rt_thread *thread; + rt_base_t level; + rt_base_t status; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE); + + if (set == 0) + return -RT_ERROR; + + /* initialize status */ + status = -RT_ERROR; + /* get current thread */ + thread = rt_thread_self(); + /* reset thread error */ + thread->error = -RT_EINTR; + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(event->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* check event set */ + if (option & RT_EVENT_FLAG_AND) + { + if ((event->set & set) == set) + status = RT_EOK; + } + else if (option & RT_EVENT_FLAG_OR) + { + if (event->set & set) + status = RT_EOK; + } + else + { + /* either RT_EVENT_FLAG_AND or RT_EVENT_FLAG_OR should be set */ + RT_ASSERT(0); + } + + if (status == RT_EOK) + { + thread->error = RT_EOK; + + /* set received event */ + if (recved) + *recved = (event->set & set); + + /* fill thread event info */ + thread->event_set = (event->set & set); + thread->event_info = option; + + /* received event */ + if (option & RT_EVENT_FLAG_CLEAR) + event->set &= ~set; + } + else if (timeout == 0) + { + /* no waiting */ + thread->error = -RT_ETIMEOUT; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + else + { + /* fill thread event info */ + thread->event_set = set; + thread->event_info = option; + + /* put thread to suspended thread list */ + ret = _ipc_list_suspend(&(event->parent.suspend_thread), + thread, + event->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* if there is a waiting timeout, active thread timer */ + if (timeout > 0) + { + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do a schedule */ + rt_schedule(); + + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* received an event, disable interrupt to protect */ + level = rt_hw_interrupt_disable(); + + /* set received event */ + if (recved) + *recved = thread->event_set; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(event->parent.parent))); + + return thread->error; +} + +rt_err_t rt_event_recv(rt_event_t event, + rt_uint32_t set, + rt_uint8_t option, + rt_int32_t timeout, + rt_uint32_t *recved) +{ + return _rt_event_recv(event, set, option, timeout, recved, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_event_recv); + +rt_err_t rt_event_recv_interruptible(rt_event_t event, + rt_uint32_t set, + rt_uint8_t option, + rt_int32_t timeout, + rt_uint32_t *recved) +{ + return _rt_event_recv(event, set, option, timeout, recved, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_event_recv_interruptible); + +rt_err_t rt_event_recv_killable(rt_event_t event, + rt_uint32_t set, + rt_uint8_t option, + rt_int32_t timeout, + rt_uint32_t *recved) +{ + return _rt_event_recv(event, set, option, timeout, recved, RT_KILLABLE); +} +RTM_EXPORT(rt_event_recv_killable); +/** + * @brief This function will set some extra attributions of an event object. + * + * @note Currently this function only supports the RT_IPC_CMD_RESET command to reset the event. + * + * @param event is a pointer to an event object. + * + * @param cmd is a command word used to configure some attributions of the event. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_event_control(rt_event_t event, int cmd, void *arg) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + + if (cmd == RT_IPC_CMD_RESET) + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* resume all waiting thread */ + _ipc_list_resume_all(&event->parent.suspend_thread); + + /* initialize event set */ + event->set = 0; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_event_control); + +/**@}*/ +#endif /* RT_USING_EVENT */ + +#ifdef RT_USING_MAILBOX +/** + * @addtogroup mailbox + * @{ + */ + +/** + * @brief Initialize a static mailbox object. + * + * @note For the static mailbox object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_mb_create() function will allocate memory space automatically and initialize the mailbox. + * + * @see rt_mb_create() + * + * @param mb is a pointer to the mailbox to initialize. + * It is assumed that storage for the mailbox will be allocated in your application. + * + * @param name is a pointer to the name that given to the mailbox. + * + * @param msgpool the begin address of buffer to save received mail. + * + * @param size is the maximum number of mails in the mailbox. + * For example, when the mailbox buffer capacity is N, size is N/4. + * + * @param flag is the mailbox flag, which determines the queuing way of how multiple threads wait + * when the mailbox is not available. + * The mailbox flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this mailbox will become non-real-time threads. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_mb_init(rt_mailbox_t mb, + const char *name, + void *msgpool, + rt_size_t size, + rt_uint8_t flag) +{ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(mb->parent.parent), RT_Object_Class_MailBox, name); + + /* set parent flag */ + mb->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(mb->parent)); + + /* initialize mailbox */ + mb->msg_pool = (rt_ubase_t *)msgpool; + mb->size = (rt_uint16_t)size; + mb->entry = 0; + mb->in_offset = 0; + mb->out_offset = 0; + + /* initialize an additional list of sender suspend thread */ + rt_list_init(&(mb->suspend_sender_thread)); + + return RT_EOK; +} +RTM_EXPORT(rt_mb_init); + + +/** + * @brief This function will detach a static mailbox object. + * + * @note This function is used to detach a static mailbox object which is initialized by rt_mb_init() function. + * By contrast, the rt_mb_delete() function will delete a mailbox object. + * When the mailbox is successfully detached, it will resume all suspended threads in the mailbox list. + * + * @see rt_mb_delete() + * + * @param mb is a pointer to a mailbox object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the mailbox detach failed. + * + * @warning This function can ONLY detach a static mailbox initialized by the rt_mb_init() function. + * If the mailbox is created by the rt_mb_create() function, you MUST NOT USE this function to detach it, + * ONLY USE the rt_mb_delete() function to complete the deletion. + */ +rt_err_t rt_mb_detach(rt_mailbox_t mb) +{ + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + RT_ASSERT(rt_object_is_systemobject(&mb->parent.parent)); + + /* resume all suspended thread */ + _ipc_list_resume_all(&(mb->parent.suspend_thread)); + /* also resume all mailbox private suspended thread */ + _ipc_list_resume_all(&(mb->suspend_sender_thread)); + + /* detach mailbox object */ + rt_object_detach(&(mb->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mb_detach); + +#ifdef RT_USING_HEAP +/** + * @brief Creating a mailbox object. + * + * @note For the mailbox object, its memory space is allocated automatically. + * By contrast, the rt_mb_init() function will initialize a static mailbox object. + * + * @see rt_mb_init() + * + * @param name is a pointer that given to the mailbox. + * + * @param size is the maximum number of mails in the mailbox. + * For example, when mailbox buffer capacity is N, size is N/4. + * + * @param flag is the mailbox flag, which determines the queuing way of how multiple threads wait + * when the mailbox is not available. + * The mailbox flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this mailbox will become non-real-time threads. + * + * @return Return a pointer to the mailbox object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_mailbox_t rt_mb_create(const char *name, rt_size_t size, rt_uint8_t flag) +{ + rt_mailbox_t mb; + + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + mb = (rt_mailbox_t)rt_object_allocate(RT_Object_Class_MailBox, name); + if (mb == RT_NULL) + return mb; + + /* set parent */ + mb->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(mb->parent)); + + /* initialize mailbox */ + mb->size = (rt_uint16_t)size; + mb->msg_pool = (rt_ubase_t *)RT_KERNEL_MALLOC(mb->size * sizeof(rt_ubase_t)); + if (mb->msg_pool == RT_NULL) + { + /* delete mailbox object */ + rt_object_delete(&(mb->parent.parent)); + + return RT_NULL; + } + mb->entry = 0; + mb->in_offset = 0; + mb->out_offset = 0; + + /* initialize an additional list of sender suspend thread */ + rt_list_init(&(mb->suspend_sender_thread)); + + return mb; +} +RTM_EXPORT(rt_mb_create); + + +/** + * @brief This function will delete a mailbox object and release the memory space. + * + * @note This function is used to delete a mailbox object which is created by the rt_mb_create() function. + * By contrast, the rt_mb_detach() function will detach a static mailbox object. + * When the mailbox is successfully deleted, it will resume all suspended threads in the mailbox list. + * + * @see rt_mb_detach() + * + * @param mb is a pointer to a mailbox object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + * + * @warning This function can only delete mailbox created by the rt_mb_create() function. + * If the mailbox is initialized by the rt_mb_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_mb_detach() function to complete the detachment. + */ +rt_err_t rt_mb_delete(rt_mailbox_t mb) +{ + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + RT_ASSERT(rt_object_is_systemobject(&mb->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* resume all suspended thread */ + _ipc_list_resume_all(&(mb->parent.suspend_thread)); + + /* also resume all mailbox private suspended thread */ + _ipc_list_resume_all(&(mb->suspend_sender_thread)); + + /* free mailbox pool */ + RT_KERNEL_FREE(mb->msg_pool); + + /* delete mailbox object */ + rt_object_delete(&(mb->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mb_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will send an mail to the mailbox object. If there is a thread suspended on the mailbox, + * the thread will be resumed. + * + * @note When using this function to send a mail, if the mailbox if fully used, the current thread will + * wait for a timeout. If the set timeout time is reached and there is still no space available, + * the sending thread will be resumed and an error code will be returned. + * By contrast, the rt_mb_send() function will return an error code immediately without waiting time + * when the mailbox if fully used. + * + * @see rt_mb_send() + * + * @param mb is a pointer to the mailbox object to be sent. + * + * @param value is a value to the content of the mail you want to send. + * + * @param timeout is a timeout period (unit: an OS tick). + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + * + * @warning This function can be called in interrupt context and thread context. + */ +static rt_err_t _rt_mb_send_wait(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout, + int suspend_flag) +{ + struct rt_thread *thread; + rt_base_t level; + rt_uint32_t tick_delta; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0); + + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mb->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* for non-blocking call */ + if (mb->entry == mb->size && timeout == 0) + { + rt_hw_interrupt_enable(level); + return -RT_EFULL; + } + + /* mailbox is full */ + while (mb->entry == mb->size) + { + /* reset error number in thread */ + thread->error = -RT_EINTR; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EFULL; + } + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mb->suspend_sender_thread), + thread, + mb->parent.parent.flag, + suspend_flag); + + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mb_send_wait: start timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* re-schedule */ + rt_schedule(); + + /* resume from suspend state */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + + /* set ptr */ + mb->msg_pool[mb->in_offset] = value; + /* increase input offset */ + ++ mb->in_offset; + if (mb->in_offset >= mb->size) + mb->in_offset = 0; + + if(mb->entry < RT_MB_ENTRY_MAX) + { + /* increase message entry */ + mb->entry ++; + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + + /* resume suspended thread */ + if (!rt_list_isempty(&mb->parent.suspend_thread)) + { + _ipc_list_resume(&(mb->parent.suspend_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} + +rt_err_t rt_mb_send_wait(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout) +{ + return _rt_mb_send_wait(mb, value, timeout, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mb_send_wait); + +rt_err_t rt_mb_send_wait_interruptible(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout) +{ + return _rt_mb_send_wait(mb, value, timeout, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mb_send_wait_interruptible); + +rt_err_t rt_mb_send_wait_killable(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout) +{ + return _rt_mb_send_wait(mb, value, timeout, RT_KILLABLE); +} +RTM_EXPORT(rt_mb_send_wait_killable); +/** + * @brief This function will send an mail to the mailbox object. If there is a thread suspended on the mailbox, + * the thread will be resumed. + * + * @note When using this function to send a mail, if the mailbox is fully used, this function will return an error + * code immediately without waiting time. + * By contrast, the rt_mb_send_wait() function is set a timeout to wait for the mail to be sent. + * + * @see rt_mb_send_wait() + * + * @param mb is a pointer to the mailbox object to be sent. + * + * @param value is a value to the content of the mail you want to send. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + */ +rt_err_t rt_mb_send(rt_mailbox_t mb, rt_ubase_t value) +{ + return rt_mb_send_wait(mb, value, 0); +} +RTM_EXPORT(rt_mb_send); + +rt_err_t rt_mb_send_interruptible(rt_mailbox_t mb, rt_ubase_t value) +{ + return rt_mb_send_wait_interruptible(mb, value, 0); +} +RTM_EXPORT(rt_mb_send_interruptible); + +rt_err_t rt_mb_send_killable(rt_mailbox_t mb, rt_ubase_t value) +{ + return rt_mb_send_wait_killable(mb, value, 0); +} +RTM_EXPORT(rt_mb_send_killable); + +/** + * @brief This function will send an urgent mail to the mailbox object. + * + * @note This function is almost the same as the rt_mb_send() function. The only difference is that + * when sending an urgent mail, the mail will be placed at the head of the mail queue so that + * the recipient can receive the urgent mail first. + * + * @see rt_mb_send() + * + * @param mb is a pointer to the mailbox object to be sent. + * + * @param value is the content of the mail you want to send. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + */ +rt_err_t rt_mb_urgent(rt_mailbox_t mb, rt_ubase_t value) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mb->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + if (mb->entry == mb->size) + { + rt_hw_interrupt_enable(level); + return -RT_EFULL; + } + + /* rewind to the previous position */ + if (mb->out_offset > 0) + { + mb->out_offset --; + } + else + { + mb->out_offset = mb->size - 1; + } + + /* set ptr */ + mb->msg_pool[mb->out_offset] = value; + + /* increase message entry */ + mb->entry ++; + + /* resume suspended thread */ + if (!rt_list_isempty(&mb->parent.suspend_thread)) + { + _ipc_list_resume(&(mb->parent.suspend_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} +RTM_EXPORT(rt_mb_urgent); + + +/** + * @brief This function will receive a mail from mailbox object, if there is no mail in mailbox object, + * the thread shall wait for a specified time. + * + * @note Only when there is mail in the mailbox, the receiving thread can get the mail immediately and + * return RT_EOK, otherwise the receiving thread will be suspended until the set timeout. If the mail + * is still not received within the specified time, it will return-RT_ETIMEOUT. + * + * @param mb is a pointer to the mailbox object to be received. + * + * @param value is a flag that you will set for this mailbox's flag. + * You can set an mailbox flag, or you can set multiple flags through OR logic operations. + * + * @param timeout is a timeout period (unit: an OS tick). If the mailbox object is not avaliable in the queue, + * the thread will wait for the object in the queue up to the amount of time specified by this parameter. + * + * NOTE: + * If use Macro RT_WAITING_FOREVER to set this parameter, which means that when the + * mailbox object is unavailable in the queue, the thread will be waiting forever. + * If use macro RT_WAITING_NO to set this parameter, which means that this + * function is non-blocking and will return immediately. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox release failed. + */ +static rt_err_t _rt_mb_recv(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout, int suspend_flag) +{ + struct rt_thread *thread; + rt_base_t level; + rt_uint32_t tick_delta; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0); + + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(mb->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* for non-blocking call */ + if (mb->entry == 0 && timeout == 0) + { + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + + /* mailbox is empty */ + while (mb->entry == 0) + { + /* reset error number in thread */ + thread->error = -RT_EINTR; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + thread->error = -RT_ETIMEOUT; + + return -RT_ETIMEOUT; + } + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mb->parent.suspend_thread), + thread, + mb->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mb_recv: start timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* re-schedule */ + rt_schedule(); + + /* resume from suspend state */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + + /* fill ptr */ + *value = mb->msg_pool[mb->out_offset]; + + /* increase output offset */ + ++ mb->out_offset; + if (mb->out_offset >= mb->size) + mb->out_offset = 0; + + /* decrease message entry */ + if(mb->entry > 0) + { + mb->entry --; + } + + /* resume suspended thread */ + if (!rt_list_isempty(&(mb->suspend_sender_thread))) + { + _ipc_list_resume(&(mb->suspend_sender_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mb->parent.parent))); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mb->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_mb_recv(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout) +{ + return _rt_mb_recv(mb, value, timeout, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mb_recv); + +rt_err_t rt_mb_recv_interruptibale(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout) +{ + return _rt_mb_recv(mb, value, timeout, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mb_recv_interruptibale); + +rt_err_t rt_mb_recv_killable(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout) +{ + return _rt_mb_recv(mb, value, timeout, RT_KILLABLE); +} +RTM_EXPORT(rt_mb_recv_killable); + +/** + * @brief This function will set some extra attributions of a mailbox object. + * + * @note Currently this function only supports the RT_IPC_CMD_RESET command to reset the mailbox. + * + * @param mb is a pointer to a mailbox object. + * + * @param cmd is a command used to configure some attributions of the mailbox. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_mb_control(rt_mailbox_t mb, int cmd, void *arg) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + + if (cmd == RT_IPC_CMD_RESET) + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* resume all waiting thread */ + _ipc_list_resume_all(&(mb->parent.suspend_thread)); + /* also resume all mailbox private suspended thread */ + _ipc_list_resume_all(&(mb->suspend_sender_thread)); + + /* re-init mailbox */ + mb->entry = 0; + mb->in_offset = 0; + mb->out_offset = 0; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_mb_control); + +/**@}*/ +#endif /* RT_USING_MAILBOX */ + +#ifdef RT_USING_MESSAGEQUEUE +/** + * @addtogroup messagequeue + * @{ + */ + +struct rt_mq_message +{ + struct rt_mq_message *next; +}; + + +/** + * @brief Initialize a static messagequeue object. + * + * @note For the static messagequeue object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_mq_create() function will allocate memory space automatically + * and initialize the messagequeue. + * + * @see rt_mq_create() + * + * @param mq is a pointer to the messagequeue to initialize. It is assumed that storage for + * the messagequeue will be allocated in your application. + * + * @param name is a pointer to the name that given to the messagequeue. + * + * @param msgpool is a pointer to the starting address of the memory space you allocated for + * the messagequeue in advance. + * In other words, msgpool is a pointer to the messagequeue buffer of the starting address. + * + * @param msg_size is the maximum length of a message in the messagequeue (Unit: Byte). + * + * @param pool_size is the size of the memory space allocated for the messagequeue in advance. + * + * @param flag is the messagequeue flag, which determines the queuing way of how multiple threads wait + * when the messagequeue is not available. + * The messagequeue flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this messagequeue will become non-real-time threads. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_mq_init(rt_mq_t mq, + const char *name, + void *msgpool, + rt_size_t msg_size, + rt_size_t pool_size, + rt_uint8_t flag) +{ + struct rt_mq_message *head; + rt_base_t temp; + register rt_size_t msg_align_size; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(mq->parent.parent), RT_Object_Class_MessageQueue, name); + + /* set parent flag */ + mq->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(mq->parent)); + + /* set message pool */ + mq->msg_pool = msgpool; + + /* get correct message size */ + msg_align_size = RT_ALIGN(msg_size, RT_ALIGN_SIZE); + mq->msg_size = msg_size; + mq->max_msgs = pool_size / (msg_align_size + sizeof(struct rt_mq_message)); + + if (0 == mq->max_msgs) + { + return -RT_EINVAL; + } + + /* initialize message list */ + mq->msg_queue_head = RT_NULL; + mq->msg_queue_tail = RT_NULL; + + /* initialize message empty list */ + mq->msg_queue_free = RT_NULL; + for (temp = 0; temp < mq->max_msgs; temp ++) + { + head = (struct rt_mq_message *)((rt_uint8_t *)mq->msg_pool + + temp * (msg_align_size + sizeof(struct rt_mq_message))); + head->next = (struct rt_mq_message *)mq->msg_queue_free; + mq->msg_queue_free = head; + } + + /* the initial entry is zero */ + mq->entry = 0; + + /* initialize an additional list of sender suspend thread */ + rt_list_init(&(mq->suspend_sender_thread)); + + return RT_EOK; +} +RTM_EXPORT(rt_mq_init); + + +/** + * @brief This function will detach a static messagequeue object. + * + * @note This function is used to detach a static messagequeue object which is initialized by rt_mq_init() function. + * By contrast, the rt_mq_delete() function will delete a messagequeue object. + * When the messagequeue is successfully detached, it will resume all suspended threads in the messagequeue list. + * + * @see rt_mq_delete() + * + * @param mq is a pointer to a messagequeue object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the messagequeue detach failed. + * + * @warning This function can ONLY detach a static messagequeue initialized by the rt_mq_init() function. + * If the messagequeue is created by the rt_mq_create() function, you MUST NOT USE this function to detach it, + * and ONLY USE the rt_mq_delete() function to complete the deletion. + */ +rt_err_t rt_mq_detach(rt_mq_t mq) +{ + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(rt_object_is_systemobject(&mq->parent.parent)); + + /* resume all suspended thread */ + _ipc_list_resume_all(&mq->parent.suspend_thread); + /* also resume all message queue private suspended thread */ + _ipc_list_resume_all(&(mq->suspend_sender_thread)); + + /* detach message queue object */ + rt_object_detach(&(mq->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mq_detach); + +#ifdef RT_USING_HEAP +/** + * @brief Creating a messagequeue object. + * + * @note For the messagequeue object, its memory space is allocated automatically. + * By contrast, the rt_mq_init() function will initialize a static messagequeue object. + * + * @see rt_mq_init() + * + * @param name is a pointer that given to the messagequeue. + * + * @param msg_size is the maximum length of a message in the messagequeue (Unit: Byte). + * + * @param max_msgs is the maximum number of messages in the messagequeue. + * + * @param flag is the messagequeue flag, which determines the queuing way of how multiple threads wait + * when the messagequeue is not available. + * The messagequeue flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this messagequeue will become non-real-time threads. + * + * @return Return a pointer to the messagequeue object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can NOT be called in interrupt context. You can use macor RT_DEBUG_NOT_IN_INTERRUPT to check it. + */ +rt_mq_t rt_mq_create(const char *name, + rt_size_t msg_size, + rt_size_t max_msgs, + rt_uint8_t flag) +{ + struct rt_messagequeue *mq; + struct rt_mq_message *head; + rt_base_t temp; + register rt_size_t msg_align_size; + + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + mq = (rt_mq_t)rt_object_allocate(RT_Object_Class_MessageQueue, name); + if (mq == RT_NULL) + return mq; + + /* set parent */ + mq->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(mq->parent)); + + /* initialize message queue */ + + /* get correct message size */ + msg_align_size = RT_ALIGN(msg_size, RT_ALIGN_SIZE); + mq->msg_size = msg_size; + mq->max_msgs = max_msgs; + + /* allocate message pool */ + mq->msg_pool = RT_KERNEL_MALLOC((msg_align_size + sizeof(struct rt_mq_message)) * mq->max_msgs); + if (mq->msg_pool == RT_NULL) + { + rt_object_delete(&(mq->parent.parent)); + + return RT_NULL; + } + + /* initialize message list */ + mq->msg_queue_head = RT_NULL; + mq->msg_queue_tail = RT_NULL; + + /* initialize message empty list */ + mq->msg_queue_free = RT_NULL; + for (temp = 0; temp < mq->max_msgs; temp ++) + { + head = (struct rt_mq_message *)((rt_uint8_t *)mq->msg_pool + + temp * (msg_align_size + sizeof(struct rt_mq_message))); + head->next = (struct rt_mq_message *)mq->msg_queue_free; + mq->msg_queue_free = head; + } + + /* the initial entry is zero */ + mq->entry = 0; + + /* initialize an additional list of sender suspend thread */ + rt_list_init(&(mq->suspend_sender_thread)); + + return mq; +} +RTM_EXPORT(rt_mq_create); + + +/** + * @brief This function will delete a messagequeue object and release the memory. + * + * @note This function is used to delete a messagequeue object which is created by the rt_mq_create() function. + * By contrast, the rt_mq_detach() function will detach a static messagequeue object. + * When the messagequeue is successfully deleted, it will resume all suspended threads in the messagequeue list. + * + * @see rt_mq_detach() + * + * @param mq is a pointer to a messagequeue object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the messagequeue detach failed. + * + * @warning This function can ONLY delete a messagequeue initialized by the rt_mq_create() function. + * If the messagequeue is initialized by the rt_mq_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_mq_detach() function to complete the detachment. + * for example,the rt_mq_create() function, it cannot be called in interrupt context. + */ +rt_err_t rt_mq_delete(rt_mq_t mq) +{ + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(rt_object_is_systemobject(&mq->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* resume all suspended thread */ + _ipc_list_resume_all(&(mq->parent.suspend_thread)); + /* also resume all message queue private suspended thread */ + _ipc_list_resume_all(&(mq->suspend_sender_thread)); + + /* free message queue pool */ + RT_KERNEL_FREE(mq->msg_pool); + + /* delete message queue object */ + rt_object_delete(&(mq->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mq_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will send a message to the messagequeue object. If + * there is a thread suspended on the messagequeue, the thread will be + * resumed. + * + * @note When using this function to send a message, if the messagequeue is + * fully used, the current thread will wait for a timeout. If reaching + * the timeout and there is still no space available, the sending + * thread will be resumed and an error code will be returned. By + * contrast, the rt_mq_send() function will return an error code + * immediately without waiting when the messagequeue if fully used. + * + * @see rt_mq_send() + * + * @param mq is a pointer to the messagequeue object to be sent. + * + * @param buffer is the content of the message. + * + * @param size is the length of the message(Unit: Byte). + * + * @param timeout is a timeout period (unit: an OS tick). + * + * @return Return the operation status. When the return value is RT_EOK, the + * operation is successful. If the return value is any other values, + * it means that the messagequeue detach failed. + * + * @warning This function can be called in interrupt context and thread + * context. + */ +static rt_err_t _rt_mq_send_wait(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout, + int suspend_flag) +{ + rt_base_t level; + struct rt_mq_message *msg; + rt_uint32_t tick_delta; + struct rt_thread *thread; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(buffer != RT_NULL); + RT_ASSERT(size != 0); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0); + + /* greater than one message size */ + if (size > mq->msg_size) + return -RT_ERROR; + + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mq->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* get a free list, there must be an empty item */ + msg = (struct rt_mq_message *)mq->msg_queue_free; + /* for non-blocking call */ + if (msg == RT_NULL && timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EFULL; + } + + /* message queue is full */ + while ((msg = (struct rt_mq_message *)mq->msg_queue_free) == RT_NULL) + { + /* reset error number in thread */ + thread->error = -RT_EINTR; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EFULL; + } + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mq->suspend_sender_thread), + thread, + mq->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mq_send_wait: start timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* re-schedule */ + rt_schedule(); + + /* resume from suspend state */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + + /* move free list pointer */ + mq->msg_queue_free = msg->next; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* the msg is the new tailer of list, the next shall be NULL */ + msg->next = RT_NULL; + /* copy buffer */ + rt_memcpy(msg + 1, buffer, size); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + /* link msg to message queue */ + if (mq->msg_queue_tail != RT_NULL) + { + /* if the tail exists, */ + ((struct rt_mq_message *)mq->msg_queue_tail)->next = msg; + } + + /* set new tail */ + mq->msg_queue_tail = msg; + /* if the head is empty, set head */ + if (mq->msg_queue_head == RT_NULL) + mq->msg_queue_head = msg; + + if(mq->entry < RT_MQ_ENTRY_MAX) + { + /* increase message entry */ + mq->entry ++; + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + + /* resume suspended thread */ + if (!rt_list_isempty(&mq->parent.suspend_thread)) + { + _ipc_list_resume(&(mq->parent.suspend_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} + +rt_err_t rt_mq_send_wait(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_send_wait(mq, buffer, size, timeout, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mq_send_wait) + +rt_err_t rt_mq_send_wait_interruptible(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_send_wait(mq, buffer, size, timeout, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mq_send_wait_interruptible) + +rt_err_t rt_mq_send_wait_killable(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_send_wait(mq, buffer, size, timeout, RT_KILLABLE); +} +RTM_EXPORT(rt_mq_send_wait_killable) +/** + * @brief This function will send a message to the messagequeue object. + * If there is a thread suspended on the messagequeue, the thread will be resumed. + * + * @note When using this function to send a message, if the messagequeue is fully used, + * the current thread will wait for a timeout. + * By contrast, when the messagequeue is fully used, the rt_mq_send_wait() function will + * return an error code immediately without waiting. + * + * @see rt_mq_send_wait() + * + * @param mq is a pointer to the messagequeue object to be sent. + * + * @param buffer is the content of the message. + * + * @param size is the length of the message(Unit: Byte). + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the messagequeue detach failed. + * + * @warning This function can be called in interrupt context and thread context. + */ +rt_err_t rt_mq_send(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + return rt_mq_send_wait(mq, buffer, size, 0); +} +RTM_EXPORT(rt_mq_send); + +rt_err_t rt_mq_send_interrupt(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + return rt_mq_send_wait_interruptible(mq, buffer, size, 0); +} +RTM_EXPORT(rt_mq_send_interrupt); + +rt_err_t rt_mq_send_killable(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + return rt_mq_send_wait_killable(mq, buffer, size, 0); +} +RTM_EXPORT(rt_mq_send_killable); +/** + * @brief This function will send an urgent message to the messagequeue object. + * + * @note This function is almost the same as the rt_mq_send() function. The only difference is that + * when sending an urgent message, the message is placed at the head of the messagequeue so that + * the recipient can receive the urgent message first. + * + * @see rt_mq_send() + * + * @param mq is a pointer to the messagequeue object to be sent. + * + * @param buffer is the content of the message. + * + * @param size is the length of the message(Unit: Byte). + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + */ +rt_err_t rt_mq_urgent(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + rt_base_t level; + struct rt_mq_message *msg; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(buffer != RT_NULL); + RT_ASSERT(size != 0); + + /* greater than one message size */ + if (size > mq->msg_size) + return -RT_ERROR; + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mq->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* get a free list, there must be an empty item */ + msg = (struct rt_mq_message *)mq->msg_queue_free; + /* message queue is full */ + if (msg == RT_NULL) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EFULL; + } + /* move free list pointer */ + mq->msg_queue_free = msg->next; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* copy buffer */ + rt_memcpy(msg + 1, buffer, size); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* link msg to the beginning of message queue */ + msg->next = (struct rt_mq_message *)mq->msg_queue_head; + mq->msg_queue_head = msg; + + /* if there is no tail */ + if (mq->msg_queue_tail == RT_NULL) + mq->msg_queue_tail = msg; + + if(mq->entry < RT_MQ_ENTRY_MAX) + { + /* increase message entry */ + mq->entry ++; + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + + /* resume suspended thread */ + if (!rt_list_isempty(&mq->parent.suspend_thread)) + { + _ipc_list_resume(&(mq->parent.suspend_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} +RTM_EXPORT(rt_mq_urgent); + + +/** + * @brief This function will receive a message from message queue object, + * if there is no message in messagequeue object, the thread shall wait for a specified time. + * + * @note Only when there is mail in the mailbox, the receiving thread can get the mail immediately and return RT_EOK, + * otherwise the receiving thread will be suspended until timeout. + * If the mail is not received within the specified time, it will return -RT_ETIMEOUT. + * + * @param mq is a pointer to the messagequeue object to be received. + * + * @param buffer is the content of the message. + * + * @param size is the length of the message(Unit: Byte). + * + * @param timeout is a timeout period (unit: an OS tick). If the message is unavailable, the thread will wait for + * the message in the queue up to the amount of time specified by this parameter. + * + * NOTE: + * If use Macro RT_WAITING_FOREVER to set this parameter, which means that when the + * message is unavailable in the queue, the thread will be waiting forever. + * If use macro RT_WAITING_NO to set this parameter, which means that this + * function is non-blocking and will return immediately. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox release failed. + */ +static rt_err_t _rt_mq_recv(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout, + int suspend_flag) +{ + struct rt_thread *thread; + rt_base_t level; + struct rt_mq_message *msg; + rt_uint32_t tick_delta; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(buffer != RT_NULL); + RT_ASSERT(size != 0); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0); + + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(mq->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* for non-blocking call */ + if (mq->entry == 0 && timeout == 0) + { + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + + /* message queue is empty */ + while (mq->entry == 0) + { + /* reset error number in thread */ + thread->error = -RT_EINTR; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + thread->error = -RT_ETIMEOUT; + + return -RT_ETIMEOUT; + } + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mq->parent.suspend_thread), + thread, + mq->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("set thread:%s to timer list\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* re-schedule */ + rt_schedule(); + + /* recv message */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + + /* get message from queue */ + msg = (struct rt_mq_message *)mq->msg_queue_head; + + /* move message queue head */ + mq->msg_queue_head = msg->next; + /* reach queue tail, set to NULL */ + if (mq->msg_queue_tail == msg) + mq->msg_queue_tail = RT_NULL; + + /* decrease message entry */ + if(mq->entry > 0) + { + mq->entry --; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* copy message */ + rt_memcpy(buffer, msg + 1, size > mq->msg_size ? mq->msg_size : size); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + /* put message to free list */ + msg->next = (struct rt_mq_message *)mq->msg_queue_free; + mq->msg_queue_free = msg; + + /* resume suspended thread */ + if (!rt_list_isempty(&(mq->suspend_sender_thread))) + { + _ipc_list_resume(&(mq->suspend_sender_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mq->parent.parent))); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mq->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_mq_recv(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_recv(mq, buffer, size, timeout, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mq_recv); + +rt_err_t rt_mq_recv_interruptible(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_recv(mq, buffer, size, timeout, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mq_recv_interruptible); + +rt_err_t rt_mq_recv_killable(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_recv(mq, buffer, size, timeout, RT_KILLABLE); +} +RTM_EXPORT(rt_mq_recv_killable); +/** + * @brief This function will set some extra attributions of a messagequeue object. + * + * @note Currently this function only supports the RT_IPC_CMD_RESET command to reset the messagequeue. + * + * @param mq is a pointer to a messagequeue object. + * + * @param cmd is a command used to configure some attributions of the messagequeue. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_mq_control(rt_mq_t mq, int cmd, void *arg) +{ + rt_base_t level; + struct rt_mq_message *msg; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + + if (cmd == RT_IPC_CMD_RESET) + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* resume all waiting thread */ + _ipc_list_resume_all(&mq->parent.suspend_thread); + /* also resume all message queue private suspended thread */ + _ipc_list_resume_all(&(mq->suspend_sender_thread)); + + /* release all message in the queue */ + while (mq->msg_queue_head != RT_NULL) + { + /* get message from queue */ + msg = (struct rt_mq_message *)mq->msg_queue_head; + + /* move message queue head */ + mq->msg_queue_head = msg->next; + /* reach queue tail, set to NULL */ + if (mq->msg_queue_tail == msg) + mq->msg_queue_tail = RT_NULL; + + /* put message to free list */ + msg->next = (struct rt_mq_message *)mq->msg_queue_free; + mq->msg_queue_free = msg; + } + + /* clean entry */ + mq->entry = 0; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_mq_control); + +/**@}*/ +#endif /* RT_USING_MESSAGEQUEUE */ +/**@}*/ diff --git a/tasks/concur-rtthread-mutex-ceilings/observer.c b/tasks/concur-rtthread-mutex-ceilings/observer.c new file mode 100644 index 00000000..116d1beb --- /dev/null +++ b/tasks/concur-rtthread-mutex-ceilings/observer.c @@ -0,0 +1,90 @@ +/* Observation driver: commands and raw kernel state only. */ +#include "services.h" +#include +#include +#include +#include +#define LIMIT 8 +struct actor { + struct rt_thread thread; + ucontext_t context; + unsigned char kernel_stack[2048], host_stack[65536]; + char op; + int mutex, value, variant, done, result; +}; +static struct actor actors[LIMIT]; +static struct rt_mutex mutexes[LIMIT]; +static ucontext_t control; +static int selected, na, nm; +static void dummy(void *p) {(void)p;} +static void suspend_dispatch(void) { + if ((rt_current_thread->stat & RT_THREAD_SUSPEND_MASK)==RT_THREAD_SUSPEND_MASK) + swapcontext(&actors[selected].context,&control); +} +static void actor_main(int id) { + struct actor *a=&actors[id]; + for (;;) { + struct rt_mutex *m=a->mutex<0?RT_NULL:&mutexes[a->mutex]; + switch(a->op) { + case 'T': + if(a->variant==1)a->result=rt_mutex_take_interruptible(m,a->value); + else if(a->variant==2)a->result=rt_mutex_take_killable(m,a->value); + else a->result=rt_mutex_take(m,a->value); + break; + case 'R': a->result=rt_mutex_release(m);break; + case 'C': a->result=rt_mutex_setprioceiling(m,a->value);break; + case 'Q': a->result=rt_mutex_getprioceiling(m);break; + case 'D': a->result=rt_mutex_detach(m);break; + default: a->result=-999;break; + } + a->done=1; + swapcontext(&a->context,&control); + } +} +static void enter(int id) { + selected=id;port_select(&actors[id].thread); + swapcontext(&control,&actors[id].context); +} +static void observe(int result) { + printf("[%d,[",result); + for(int i=0;ithread.current_priority, + (a->thread.stat & RT_THREAD_SUSPEND_MASK)==RT_THREAD_SUSPEND_MASK,a->done,a->result,a->thread.error); + } + printf("],["); + for(int i=0;iLIMIT || nm<1 || nm>LIMIT)return 2; + for(int i=0;iop=op;a->mutex=m;a->value=value;a->variant=variant;a->done=0; + enter(id);result=a->done?a->result:777; + } + observe(result); + } + return 0; +} diff --git a/tasks/concur-rtthread-mutex-ceilings/partial_aggregate/src/ipc.c b/tasks/concur-rtthread-mutex-ceilings/partial_aggregate/src/ipc.c new file mode 100644 index 00000000..0d727e1a --- /dev/null +++ b/tasks/concur-rtthread-mutex-ceilings/partial_aggregate/src/ipc.c @@ -0,0 +1,3750 @@ +/* + * Copyright (c) 2006-2022, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +#include +#include + +#ifndef __on_rt_object_trytake_hook + #define __on_rt_object_trytake_hook(parent) __ON_HOOK_ARGS(rt_object_trytake_hook, (parent)) +#endif +#ifndef __on_rt_object_take_hook + #define __on_rt_object_take_hook(parent) __ON_HOOK_ARGS(rt_object_take_hook, (parent)) +#endif +#ifndef __on_rt_object_put_hook + #define __on_rt_object_put_hook(parent) __ON_HOOK_ARGS(rt_object_put_hook, (parent)) +#endif + +#if defined(RT_USING_HOOK) && defined(RT_HOOK_USING_FUNC_PTR) +extern void (*rt_object_trytake_hook)(struct rt_object *object); +extern void (*rt_object_take_hook)(struct rt_object *object); +extern void (*rt_object_put_hook)(struct rt_object *object); +#endif /* RT_USING_HOOK */ + +/** + * @addtogroup IPC + * @{ + */ + +/** + * @brief This function will initialize an IPC object, such as semaphore, mutex, messagequeue and mailbox. + * + * @note Executing this function will complete an initialization of the suspend thread list of the ipc object. + * + * @param ipc is a pointer to the IPC object. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * When the return value is any other values, it means the initialization failed. + * + * @warning This function can be called from all IPC initialization and creation. + */ +rt_inline rt_err_t _ipc_object_init(struct rt_ipc_object *ipc) +{ + /* initialize ipc object */ + rt_list_init(&(ipc->suspend_thread)); + + return RT_EOK; +} + + +/** + * @brief This function will suspend a thread to a IPC object list. + * + * @param list is a pointer to a suspended thread list of the IPC object. + * + * @param thread is a pointer to the thread object to be suspended. + * + * @param flag is a flag for the thread object to be suspended. It determines how the thread is suspended. + * The flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to use + * RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this semaphore will become non-real-time threads. + * + * @param suspend_flag status flag of the thread to be suspended. + * + * @return Return the operation status. When the return value is RT_EOK, the function is successfully executed. + * When the return value is any other values, it means the initialization failed. + * + * @warning This function can ONLY be called in the thread context, you can use RT_DEBUG_IN_THREAD_CONTEXT to + * check the context. + * In addition, this function is generally called by the following functions: + * rt_sem_take(), rt_mutex_take(), rt_event_recv(), rt_mb_send_wait(), + * rt_mb_recv(), rt_mq_recv(), rt_mq_send_wait() + */ +rt_inline rt_err_t _ipc_list_suspend(rt_list_t *list, + struct rt_thread *thread, + rt_uint8_t flag, + int suspend_flag) +{ + if ((thread->stat & RT_THREAD_SUSPEND_MASK) != RT_THREAD_SUSPEND_MASK) + { + rt_err_t ret = rt_thread_suspend_with_flag(thread, suspend_flag); + + /* suspend thread */ + if (ret != RT_EOK) + { + return ret; + } + } + + switch (flag) + { + case RT_IPC_FLAG_FIFO: + rt_list_insert_before(list, &(thread->tlist)); + break; /* RT_IPC_FLAG_FIFO */ + + case RT_IPC_FLAG_PRIO: + { + struct rt_list_node *n; + struct rt_thread *sthread; + + /* find a suitable position */ + for (n = list->next; n != list; n = n->next) + { + sthread = rt_list_entry(n, struct rt_thread, tlist); + + /* find out */ + if (thread->current_priority < sthread->current_priority) + { + /* insert this thread before the sthread */ + rt_list_insert_before(&(sthread->tlist), &(thread->tlist)); + break; + } + } + + /* + * not found a suitable position, + * append to the end of suspend_thread list + */ + if (n == list) + rt_list_insert_before(list, &(thread->tlist)); + } + break;/* RT_IPC_FLAG_PRIO */ + + default: + RT_ASSERT(0); + break; + } + + return RT_EOK; +} + + +/** + * @brief This function will resume a thread. + * + * @note This function will resume the first thread in the list of a IPC object. + * 1. remove the thread from suspend queue of a IPC object. + * 2. put the thread into system ready queue. + * + * By contrast, the rt_ipc_list_resume_all() function will resume all suspended threads + * in the list of a IPC object. + * + * @param list is a pointer to a suspended thread list of the IPC object. + * + * @return Return the operation status. When the return value is RT_EOK, the function is successfully executed. + * When the return value is any other values, it means this operation failed. + * + * @warning This function is generally called by the following functions: + * rt_sem_release(), rt_mutex_release(), rt_mb_send_wait(), rt_mq_send_wait(), + * rt_mb_urgent(), rt_mb_recv(), rt_mq_urgent(), rt_mq_recv(), + */ +rt_inline rt_err_t _ipc_list_resume(rt_list_t *list) +{ + struct rt_thread *thread; + + /* get thread entry */ + thread = rt_list_entry(list->next, struct rt_thread, tlist); + + thread->error = RT_EOK; + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("resume thread:%s\n", thread->name)); + + /* resume it */ + rt_thread_resume(thread); + + return RT_EOK; +} + + +/** + * @brief This function will resume all suspended threads in the IPC object list, + * including the suspended list of IPC object, and private list of mailbox etc. + * + * @note This function will resume all threads in the IPC object list. + * By contrast, the rt_ipc_list_resume() function will resume a suspended thread in the list of a IPC object. + * + * @param list is a pointer to a suspended thread list of the IPC object. + * + * @return Return the operation status. When the return value is RT_EOK, the function is successfully executed. + * When the return value is any other values, it means this operation failed. + * + */ +rt_inline rt_err_t _ipc_list_resume_all(rt_list_t *list) +{ + struct rt_thread *thread; + rt_base_t level; + + /* wakeup all suspended threads */ + while (!rt_list_isempty(list)) + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* get next suspended thread */ + thread = rt_list_entry(list->next, struct rt_thread, tlist); + /* set error code to RT_ERROR */ + thread->error = -RT_ERROR; + + /* + * resume thread + * In rt_thread_resume function, it will remove current thread from + * suspended list + */ + rt_thread_resume(thread); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + } + + return RT_EOK; +} + +#ifdef RT_USING_SEMAPHORE +/** + * @addtogroup semaphore + * @{ + */ + +/** + * @brief This function will initialize a static semaphore object. + * + * @note For the static semaphore object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_sem_create() function will allocate memory space automatically and initialize + * the semaphore. + * + * @see rt_sem_create() + * + * @param sem is a pointer to the semaphore to initialize. It is assumed that storage for the semaphore will be + * allocated in your application. + * + * @param name is a pointer to the name you would like to give the semaphore. + * + * @param value is the initial value for the semaphore. + * If used to share resources, you should initialize the value as the number of available resources. + * If used to signal the occurrence of an event, you should initialize the value as 0. + * + * @param flag is the semaphore flag, which determines the queuing way of how multiple threads wait + * when the semaphore is not available. + * The semaphore flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this semaphore will become non-real-time threads. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_sem_init(rt_sem_t sem, + const char *name, + rt_uint32_t value, + rt_uint8_t flag) +{ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(value < 0x10000U); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(sem->parent.parent), RT_Object_Class_Semaphore, name); + + /* initialize ipc object */ + _ipc_object_init(&(sem->parent)); + + /* set initial value */ + sem->value = (rt_uint16_t)value; + + /* set parent */ + sem->parent.parent.flag = flag; + + return RT_EOK; +} +RTM_EXPORT(rt_sem_init); + + +/** + * @brief This function will detach a static semaphore object. + * + * @note This function is used to detach a static semaphore object which is initialized by rt_sem_init() function. + * By contrast, the rt_sem_delete() function will delete a semaphore object. + * When the semaphore is successfully detached, it will resume all suspended threads in the semaphore list. + * + * @see rt_sem_delete() + * + * @param sem is a pointer to a semaphore object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the semaphore detach failed. + * + * @warning This function can ONLY detach a static semaphore initialized by the rt_sem_init() function. + * If the semaphore is created by the rt_sem_create() function, you MUST NOT USE this function to detach it, + * ONLY USE the rt_sem_delete() function to complete the deletion. + */ +rt_err_t rt_sem_detach(rt_sem_t sem) +{ + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + RT_ASSERT(rt_object_is_systemobject(&sem->parent.parent)); + + /* wakeup all suspended threads */ + _ipc_list_resume_all(&(sem->parent.suspend_thread)); + + /* detach semaphore object */ + rt_object_detach(&(sem->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_sem_detach); + +#ifdef RT_USING_HEAP +/** + * @brief Creating a semaphore object. + * + * @note For the semaphore object, its memory space is allocated automatically. + * By contrast, the rt_sem_init() function will initialize a static semaphore object. + * + * @see rt_sem_init() + * + * @param name is a pointer to the name you would like to give the semaphore. + * + * @param value is the initial value for the semaphore. + * If used to share resources, you should initialize the value as the number of available resources. + * If used to signal the occurrence of an event, you should initialize the value as 0. + * + * @param flag is the semaphore flag, which determines the queuing way of how multiple threads wait + * when the semaphore is not available. + * The semaphore flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this semaphore will become non-real-time threads. + * + * @return Return a pointer to the semaphore object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can NOT be called in interrupt context. You can use macor RT_DEBUG_NOT_IN_INTERRUPT to check it. + */ +rt_sem_t rt_sem_create(const char *name, rt_uint32_t value, rt_uint8_t flag) +{ + rt_sem_t sem; + + RT_ASSERT(value < 0x10000U); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + sem = (rt_sem_t)rt_object_allocate(RT_Object_Class_Semaphore, name); + if (sem == RT_NULL) + return sem; + + /* initialize ipc object */ + _ipc_object_init(&(sem->parent)); + + /* set initial value */ + sem->value = value; + + /* set parent */ + sem->parent.parent.flag = flag; + + return sem; +} +RTM_EXPORT(rt_sem_create); + + +/** + * @brief This function will delete a semaphore object and release the memory space. + * + * @note This function is used to delete a semaphore object which is created by the rt_sem_create() function. + * By contrast, the rt_sem_detach() function will detach a static semaphore object. + * When the semaphore is successfully deleted, it will resume all suspended threads in the semaphore list. + * + * @see rt_sem_detach() + * + * @param sem is a pointer to a semaphore object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the semaphore detach failed. + * + * @warning This function can ONLY delete a semaphore initialized by the rt_sem_create() function. + * If the semaphore is initialized by the rt_sem_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_sem_detach() function to complete the detachment. + */ +rt_err_t rt_sem_delete(rt_sem_t sem) +{ + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + RT_ASSERT(rt_object_is_systemobject(&sem->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* wakeup all suspended threads */ + _ipc_list_resume_all(&(sem->parent.suspend_thread)); + + /* delete semaphore object */ + rt_object_delete(&(sem->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_sem_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will take a semaphore, if the semaphore is unavailable, the thread shall wait for + * the semaphore up to a specified time. + * + * @note When this function is called, the count value of the sem->value will decrease 1 until it is equal to 0. + * When the sem->value is 0, it means that the semaphore is unavailable. At this time, it will suspend the + * thread preparing to take the semaphore. + * On the contrary, the rt_sem_release() function will increase the count value of sem->value by 1 each time. + * + * @see rt_sem_trytake() + * + * @param sem is a pointer to a semaphore object. + * + * @param timeout is a timeout period (unit: an OS tick). If the semaphore is unavailable, the thread will wait for + * the semaphore up to the amount of time specified by this parameter. + * + * NOTE: + * If use Macro RT_WAITING_FOREVER to set this parameter, which means that when the + * message is unavailable in the queue, the thread will be waiting forever. + * If use macro RT_WAITING_NO to set this parameter, which means that this + * function is non-blocking and will return immediately. + * + * @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 semaphore take failed. + * + * @warning This function can ONLY be called in the thread context. It MUST NOT BE called in interrupt context. + */ +static rt_err_t _rt_sem_take(rt_sem_t sem, rt_int32_t timeout, int suspend_flag) +{ + rt_base_t level; + struct rt_thread *thread; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(sem->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("thread %s take sem:%s, which value is: %d\n", + rt_thread_self()->name, + ((struct rt_object *)sem)->name, + sem->value)); + + if (sem->value > 0) + { + /* semaphore is available */ + sem->value --; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + } + else + { + /* no waiting, return with timeout */ + if (timeout == 0) + { + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + else + { + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE); + + /* semaphore is unavailable, push to suspend list */ + /* get current thread */ + thread = rt_thread_self(); + + /* reset thread error number */ + thread->error = -RT_EINTR; + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("sem take: suspend thread - %s\n", + thread->name)); + + /* suspend thread */ + ret = _ipc_list_suspend(&(sem->parent.suspend_thread), + thread, + sem->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + RT_DEBUG_LOG(RT_DEBUG_IPC, ("set thread:%s to timer list\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do schedule */ + rt_schedule(); + + if (thread->error != RT_EOK) + { + return thread->error; + } + } + } + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(sem->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_sem_take(rt_sem_t sem, rt_int32_t time) +{ + return _rt_sem_take(sem, time, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_sem_take); + +rt_err_t rt_sem_take_interruptible(rt_sem_t sem, rt_int32_t time) +{ + return _rt_sem_take(sem, time, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_sem_take_interruptible); + +rt_err_t rt_sem_take_killable(rt_sem_t sem, rt_int32_t time) +{ + return _rt_sem_take(sem, time, RT_KILLABLE); +} +RTM_EXPORT(rt_sem_take_killable); + +/** + * @brief This function will try to take a semaphore, if the semaphore is unavailable, the thread returns immediately. + * + * @note This function is very similar to the rt_sem_take() function, when the semaphore is not available, + * the rt_sem_trytake() function will return immediately without waiting for a timeout. + * In other words, rt_sem_trytake(sem) has the same effect as rt_sem_take(sem, 0). + * + * @see rt_sem_take() + * + * @param sem is a pointer to a semaphore object. + * + * @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 semaphore take failed. + */ +rt_err_t rt_sem_trytake(rt_sem_t sem) +{ + return rt_sem_take(sem, RT_WAITING_NO); +} +RTM_EXPORT(rt_sem_trytake); + + +/** + * @brief This function will release a semaphore. If there is thread suspended on the semaphore, it will get resumed. + * + * @note If there are threads suspended on this semaphore, the first thread in the list of this semaphore object + * will be resumed, and a thread scheduling (rt_schedule) will be executed. + * If no threads are suspended on this semaphore, the count value sem->value of this semaphore will increase by 1. + * + * @param sem is a pointer to a semaphore object. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the semaphore release failed. + */ +rt_err_t rt_sem_release(rt_sem_t sem) +{ + rt_base_t level; + rt_bool_t need_schedule; + + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(sem->parent.parent))); + + need_schedule = RT_FALSE; + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("thread %s releases sem:%s, which value is: %d\n", + rt_thread_self()->name, + ((struct rt_object *)sem)->name, + sem->value)); + + if (!rt_list_isempty(&sem->parent.suspend_thread)) + { + /* resume the suspended thread */ + _ipc_list_resume(&(sem->parent.suspend_thread)); + need_schedule = RT_TRUE; + } + else + { + if(sem->value < RT_SEM_VALUE_MAX) + { + sem->value ++; /* increase value */ + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* resume a thread, re-schedule */ + if (need_schedule == RT_TRUE) + rt_schedule(); + + return RT_EOK; +} +RTM_EXPORT(rt_sem_release); + + +/** + * @brief This function will set some extra attributions of a semaphore object. + * + * @note Currently this function only supports the RT_IPC_CMD_RESET command to reset the semaphore. + * + * @param sem is a pointer to a semaphore object. + * + * @param cmd is a command word used to configure some attributions of the semaphore. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_sem_control(rt_sem_t sem, int cmd, void *arg) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + + if (cmd == RT_IPC_CMD_RESET) + { + rt_ubase_t value; + + /* get value */ + value = (rt_ubase_t)arg; + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* resume all waiting thread */ + _ipc_list_resume_all(&sem->parent.suspend_thread); + + /* set new value */ + sem->value = (rt_uint16_t)value; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_sem_control); + +/**@}*/ +#endif /* RT_USING_SEMAPHORE */ + +#ifdef RT_USING_MUTEX +/* iterate over each suspended thread to update highest priority in pending threads */ +rt_inline rt_uint8_t _mutex_update_priority(struct rt_mutex *mutex) +{ + struct rt_thread *thread; + + if (!rt_list_isempty(&mutex->parent.suspend_thread)) + { + thread = rt_list_entry(mutex->parent.suspend_thread.next, struct rt_thread, tlist); + mutex->priority = thread->current_priority; + } + else + { + mutex->priority = 0xff; + } + + return mutex->priority; +} + +/* get highest priority inside its taken object and its init priority */ +rt_inline rt_uint8_t _thread_get_mutex_priority(struct rt_thread* thread) +{ + rt_list_t *node = RT_NULL; + struct rt_mutex *mutex = RT_NULL; + rt_uint8_t priority = thread->init_priority; + + rt_list_for_each(node, &(thread->taken_object_list)) + { + mutex = rt_list_entry(node, struct rt_mutex, taken_list); + if (priority > mutex->priority) + { + priority = mutex->priority; + } + } + + return priority; +} + +/* update priority of target thread and the thread suspended it if any */ +rt_inline void _thread_update_priority(struct rt_thread *thread, rt_uint8_t priority, int suspend_flag) +{ + rt_err_t ret; + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("thread:%s priority -> %d\n", thread->name, priority)); + + /* change priority of the thread */ + rt_thread_control(thread, + RT_THREAD_CTRL_CHANGE_PRIORITY, + &priority); + + if ((thread->stat & RT_THREAD_SUSPEND_MASK) == RT_THREAD_SUSPEND_MASK) + { + /* whether change the priority of taken mutex */ + struct rt_object* pending_obj = thread->pending_object; + + if (pending_obj && rt_object_get_type(pending_obj) == RT_Object_Class_Mutex) + { + rt_uint8_t mutex_priority; + struct rt_mutex* pending_mutex = (struct rt_mutex *)pending_obj; + + /* re-insert thread to suspended thread list */ + rt_list_remove(&(thread->tlist)); + + ret = _ipc_list_suspend(&(pending_mutex->parent.suspend_thread), + thread, + pending_mutex->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + /* TODO */ + return ; + } + + /* update priority */ + _mutex_update_priority(pending_mutex); + /* change the priority of mutex owner thread */ + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("mutex: %s priority -> %d\n", pending_mutex->parent.parent.name, + pending_mutex->priority)); + + mutex_priority = _thread_get_mutex_priority(pending_mutex->owner); + if (mutex_priority != pending_mutex->owner->current_priority) + { + _thread_update_priority(pending_mutex->owner, mutex_priority, suspend_flag); + } + } + } +} + +/** + * @addtogroup mutex + * @{ + */ + +/** + * @brief Initialize a static mutex object. + * + * @note For the static mutex object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_mutex_create() function will automatically allocate memory space + * and initialize the mutex. + * + * @see rt_mutex_create() + * + * @param mutex is a pointer to the mutex to initialize. It is assumed that storage for the mutex will be + * allocated in your application. + * + * @param name is a pointer to the name that given to the mutex. + * + * @param flag is the mutex flag, which determines the queuing way of how multiple threads wait + * when the mutex is not available. + * NOTE: This parameter has been obsoleted. It can be RT_IPC_FLAG_PRIO, RT_IPC_FLAG_FIFO or RT_NULL. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_mutex_init(rt_mutex_t mutex, const char *name, rt_uint8_t flag) +{ + /* flag parameter has been obsoleted */ + RT_UNUSED(flag); + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + + /* initialize object */ + rt_object_init(&(mutex->parent.parent), RT_Object_Class_Mutex, name); + + /* initialize ipc object */ + _ipc_object_init(&(mutex->parent)); + + mutex->owner = RT_NULL; + mutex->priority = 0xFF; + mutex->hold = 0; + mutex->ceiling_priority = 0xFF; + rt_list_init(&(mutex->taken_list)); + + /* flag can only be RT_IPC_FLAG_PRIO. RT_IPC_FLAG_FIFO cannot solve the unbounded priority inversion problem */ + mutex->parent.parent.flag = RT_IPC_FLAG_PRIO; + + return RT_EOK; +} +RTM_EXPORT(rt_mutex_init); + + +/** + * @brief This function will detach a static mutex object. + * + * @note This function is used to detach a static mutex object which is initialized by rt_mutex_init() function. + * By contrast, the rt_mutex_delete() function will delete a mutex object. + * When the mutex is successfully detached, it will resume all suspended threads in the mutex list. + * + * @see rt_mutex_delete() + * + * @param mutex is a pointer to a mutex object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the mutex detach failed. + * + * @warning This function can ONLY detach a static mutex initialized by the rt_mutex_init() function. + * If the mutex is created by the rt_mutex_create() function, you MUST NOT USE this function to detach it, + * ONLY USE the rt_mutex_delete() function to complete the deletion. + */ +rt_err_t rt_mutex_detach(rt_mutex_t mutex) +{ + rt_ubase_t level; + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + RT_ASSERT(rt_object_is_systemobject(&mutex->parent.parent)); + + level = rt_hw_interrupt_disable(); + /* wakeup all suspended threads */ + _ipc_list_resume_all(&(mutex->parent.suspend_thread)); + /* remove mutex from thread's taken list */ + rt_list_remove(&mutex->taken_list); + rt_hw_interrupt_enable(level); + + /* detach mutex object */ + rt_object_detach(&(mutex->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mutex_detach); + +/* drop a thread from the suspend list of mutex */ + +/** + * @brief drop a thread from the suspend list of mutex + * + * @param mutex is a pointer to a mutex object. + * @param thread is the thread should be dropped from mutex. + */ +void rt_mutex_drop_thread(rt_mutex_t mutex, rt_thread_t thread) +{ + rt_uint8_t priority; + rt_bool_t need_update = RT_FALSE; + + rt_list_remove(&(thread->tlist)); + + /* should change the priority of mutex owner thread */ + if (mutex->owner->current_priority == thread->current_priority) + need_update = RT_TRUE; + + /* update the priority of mutex */ + if (!rt_list_isempty(&mutex->parent.suspend_thread)) + { + /* more thread suspended in the list */ + struct rt_thread *th; + + th = rt_list_entry(mutex->parent.suspend_thread.next, + struct rt_thread, + tlist); + /* update the priority of mutex */ + mutex->priority = th->current_priority; + } + else + { + /* set mutex priority to maximal priority */ + mutex->priority = 0xff; + } + + /* try to change the priority of mutex owner thread */ + if (need_update) + { + /* get the maximal priority of mutex in thread */ + priority = _thread_get_mutex_priority(mutex->owner); + if (priority != mutex->owner->current_priority) + { + _thread_update_priority(mutex->owner, priority, RT_UNINTERRUPTIBLE); + } + } +} + + +/** + * @brief set the prioceiling attribute of the mutex. + * + * @param mutex is a pointer to a mutex object. + * @param priority is the priority should be set to mutex. + * + * @return return the old priority ceiling + */ +rt_uint8_t rt_mutex_setprioceiling(rt_mutex_t mutex, rt_uint8_t priority) +{ + rt_uint8_t ret_priority = 0xFF; + + if ((mutex) && (priority < RT_THREAD_PRIORITY_MAX)) + { + /* critical section here if multiple updates to one mutex happen */ + rt_ubase_t level = rt_hw_interrupt_disable(); + ret_priority = mutex->ceiling_priority; + mutex->ceiling_priority = priority; + if (mutex->owner) + { + rt_uint8_t priority = _thread_get_mutex_priority(mutex->owner); + if (priority != mutex->owner->current_priority) + _thread_update_priority(mutex->owner, priority, RT_UNINTERRUPTIBLE); + } + rt_hw_interrupt_enable(level); + } + else + { + rt_set_errno(-RT_EINVAL); + } + + return ret_priority; +} +RTM_EXPORT(rt_mutex_setprioceiling); + + +/** + * @brief set the prioceiling attribute of the mutex. + * + * @param mutex is a pointer to a mutex object. + * + * @return return the current priority ceiling of the mutex. + */ +rt_uint8_t rt_mutex_getprioceiling(rt_mutex_t mutex) +{ + rt_uint8_t prio = 0xFF; + + if (mutex) + { + prio = mutex->ceiling_priority; + } + + return prio; +} +RTM_EXPORT(rt_mutex_getprioceiling); + + +#ifdef RT_USING_HEAP +/** + * @brief This function will create a mutex object. + * + * @note For the mutex object, its memory space is automatically allocated. + * By contrast, the rt_mutex_init() function will initialize a static mutex object. + * + * @see rt_mutex_init() + * + * @param name is a pointer to the name that given to the mutex. + * + * @param flag is the mutex flag, which determines the queuing way of how multiple threads wait + * when the mutex is not available. + * NOTE: This parameter has been obsoleted. It can be RT_IPC_FLAG_PRIO, RT_IPC_FLAG_FIFO or RT_NULL. + * + * @return Return a pointer to the mutex object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_mutex_t rt_mutex_create(const char *name, rt_uint8_t flag) +{ + struct rt_mutex *mutex; + + /* flag parameter has been obsoleted */ + RT_UNUSED(flag); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + mutex = (rt_mutex_t)rt_object_allocate(RT_Object_Class_Mutex, name); + if (mutex == RT_NULL) + return mutex; + + /* initialize ipc object */ + _ipc_object_init(&(mutex->parent)); + + mutex->owner = RT_NULL; + mutex->priority = 0xFF; + mutex->hold = 0; + mutex->ceiling_priority = 0xFF; + rt_list_init(&(mutex->taken_list)); + + /* flag can only be RT_IPC_FLAG_PRIO. RT_IPC_FLAG_FIFO cannot solve the unbounded priority inversion problem */ + mutex->parent.parent.flag = RT_IPC_FLAG_PRIO; + + return mutex; +} +RTM_EXPORT(rt_mutex_create); + + +/** + * @brief This function will delete a mutex object and release this memory space. + * + * @note This function is used to delete a mutex object which is created by the rt_mutex_create() function. + * By contrast, the rt_mutex_detach() function will detach a static mutex object. + * When the mutex is successfully deleted, it will resume all suspended threads in the mutex list. + * + * @see rt_mutex_detach() + * + * @param mutex is a pointer to a mutex object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mutex detach failed. + * + * @warning This function can ONLY delete a mutex initialized by the rt_mutex_create() function. + * If the mutex is initialized by the rt_mutex_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_mutex_detach() function to complete the detachment. + */ +rt_err_t rt_mutex_delete(rt_mutex_t mutex) +{ + rt_ubase_t level; + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + RT_ASSERT(rt_object_is_systemobject(&mutex->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + level = rt_hw_interrupt_disable(); + /* wakeup all suspended threads */ + _ipc_list_resume_all(&(mutex->parent.suspend_thread)); + /* remove mutex from thread's taken list */ + rt_list_remove(&mutex->taken_list); + rt_hw_interrupt_enable(level); + + /* delete mutex object */ + rt_object_delete(&(mutex->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mutex_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will take a mutex, if the mutex is unavailable, the thread shall wait for + * the mutex up to a specified time. + * + * @note When this function is called, the count value of the mutex->value will decrease 1 until it is equal to 0. + * When the mutex->value is 0, it means that the mutex is unavailable. At this time, it will suspend the + * thread preparing to take the mutex. + * On the contrary, the rt_mutex_release() function will increase the count value of mutex->value by 1 each time. + * + * @see rt_mutex_trytake() + * + * @param mutex is a pointer to a mutex object. + * + * @param timeout is a timeout period (unit: an OS tick). If the mutex is unavailable, the thread will wait for + * the mutex up to the amount of time specified by the argument. + * NOTE: Generally, we set this parameter to RT_WAITING_FOREVER, which means that when the mutex is unavailable, + * the thread will be waitting forever. + * + * @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 mutex take failed. + * + * @warning This function can ONLY be called in the thread context. It MUST NOT BE called in interrupt context. + */ +static rt_err_t _rt_mutex_take(rt_mutex_t mutex, rt_int32_t timeout, int suspend_flag) +{ + rt_base_t level; + struct rt_thread *thread; + rt_err_t ret; + + /* this function must not be used in interrupt even if time = 0 */ + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE); + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + + /* get current thread */ + thread = rt_thread_self(); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(mutex->parent.parent))); + + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("mutex_take: current thread %s, hold: %d\n", + thread->name, mutex->hold)); + + /* reset thread error */ + thread->error = RT_EOK; + + if (mutex->owner == thread) + { + if(mutex->hold < RT_MUTEX_HOLD_MAX) + { + /* it's the same thread */ + mutex->hold ++; + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + } + else + { + /* whether the mutex has owner thread. */ + if (mutex->owner == RT_NULL) + { + /* set mutex owner and original priority */ + mutex->owner = thread; + mutex->priority = 0xff; + mutex->hold = 1; + + if (mutex->ceiling_priority != 0xFF) + { + /* set the priority of thread to the ceiling priority */ + if (mutex->ceiling_priority < mutex->owner->current_priority) + _thread_update_priority(mutex->owner, mutex->ceiling_priority, suspend_flag); + } + + /* insert mutex to thread's taken object list */ + rt_list_insert_after(&thread->taken_object_list, &mutex->taken_list); + } + else + { + /* no waiting, return with timeout */ + if (timeout == 0) + { + /* set error as timeout */ + thread->error = -RT_ETIMEOUT; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + else + { + rt_uint8_t priority = thread->current_priority; + + /* mutex is unavailable, push to suspend list */ + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mutex_take: suspend thread: %s\n", + thread->name)); + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mutex->parent.suspend_thread), + thread, + mutex->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* set pending object in thread to this mutex */ + thread->pending_object = &(mutex->parent.parent); + + /* update the priority level of mutex */ + if (priority < mutex->priority) + { + mutex->priority = priority; + if (mutex->priority < mutex->owner->current_priority) + { + _thread_update_priority(mutex->owner, priority, RT_UNINTERRUPTIBLE); /* TODO */ + } + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("mutex_take: start the timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do schedule */ + rt_schedule(); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + if (thread->error == RT_EOK) + { + /* get mutex successfully */ + } + else + { + /* the mutex has not been taken and thread has detach from the pending list. */ + + rt_bool_t need_update = RT_FALSE; + + /* should change the priority of mutex owner thread */ + if (mutex->owner->current_priority == thread->current_priority) + need_update = RT_TRUE; + + /* update the priority of mutex */ + if (!rt_list_isempty(&mutex->parent.suspend_thread)) + { + /* more thread suspended in the list */ + struct rt_thread *th; + + th = rt_list_entry(mutex->parent.suspend_thread.next, + struct rt_thread, + tlist); + /* update the priority of mutex */ + mutex->priority = th->current_priority; + } + else + { + /* set mutex priority to maximal priority */ + mutex->priority = 0xff; + } + + /* try to change the priority of mutex owner thread */ + if (need_update) + { + /* get the maximal priority of mutex in thread */ + priority = _thread_get_mutex_priority(mutex->owner); + if (priority != mutex->owner->current_priority) + { + _thread_update_priority(mutex->owner, priority, RT_UNINTERRUPTIBLE); + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* return error */ + return thread->error; + } + } + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mutex->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_mutex_take(rt_mutex_t mutex, rt_int32_t time) +{ + return _rt_mutex_take(mutex, time, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mutex_take); + +rt_err_t rt_mutex_take_interruptible(rt_mutex_t mutex, rt_int32_t time) +{ + return _rt_mutex_take(mutex, time, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mutex_take_interruptible); + +rt_err_t rt_mutex_take_killable(rt_mutex_t mutex, rt_int32_t time) +{ + return _rt_mutex_take(mutex, time, RT_KILLABLE); +} +RTM_EXPORT(rt_mutex_take_killable); + +/** + * @brief This function will try to take a mutex, if the mutex is unavailable, the thread returns immediately. + * + * @note This function is very similar to the rt_mutex_take() function, when the mutex is not available, + * except that rt_mutex_trytake() will return immediately without waiting for a timeout + * when the mutex is not available. + * In other words, rt_mutex_trytake(mutex) has the same effect as rt_mutex_take(mutex, 0). + * + * @see rt_mutex_take() + * + * @param mutex is a pointer to a mutex object. + * + * @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 mutex take failed. + */ +rt_err_t rt_mutex_trytake(rt_mutex_t mutex) +{ + return rt_mutex_take(mutex, RT_WAITING_NO); +} +RTM_EXPORT(rt_mutex_trytake); + + +/** + * @brief This function will release a mutex. If there is thread suspended on the mutex, the thread will be resumed. + * + * @note If there are threads suspended on this mutex, the first thread in the list of this mutex object + * will be resumed, and a thread scheduling (rt_schedule) will be executed. + * If no threads are suspended on this mutex, the count value mutex->value of this mutex will increase by 1. + * + * @param mutex is a pointer to a mutex object. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mutex release failed. + */ +rt_err_t rt_mutex_release(rt_mutex_t mutex) +{ + rt_base_t level; + struct rt_thread *thread; + rt_bool_t need_schedule; + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + + need_schedule = RT_FALSE; + + /* only thread could release mutex because we need test the ownership */ + RT_DEBUG_IN_THREAD_CONTEXT; + + /* get current thread */ + thread = rt_thread_self(); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("mutex_release:current thread %s, hold: %d\n", + thread->name, mutex->hold)); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mutex->parent.parent))); + + /* mutex only can be released by owner */ + if (thread != mutex->owner) + { + thread->error = -RT_ERROR; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_ERROR; + } + + /* decrease hold */ + mutex->hold --; + /* if no hold */ + if (mutex->hold == 0) + { + /* remove mutex from thread's taken list */ + rt_list_remove(&mutex->taken_list); + + /* whether change the thread priority */ + if ((mutex->ceiling_priority != 0xFF) || (thread->current_priority == mutex->priority)) + { + rt_uint8_t priority = 0xff; + + /* get the highest priority in the taken list of thread */ + priority = _thread_get_mutex_priority(thread); + + rt_thread_control(thread, + RT_THREAD_CTRL_CHANGE_PRIORITY, + &priority); + + need_schedule = RT_TRUE; + } + + /* wakeup suspended thread */ + if (!rt_list_isempty(&mutex->parent.suspend_thread)) + { + /* get the first suspended thread */ + struct rt_thread *next_thread = rt_list_entry(mutex->parent.suspend_thread.next, + struct rt_thread, + tlist); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mutex_release: resume thread: %s\n", + next_thread->name)); + + /* remove the thread from the suspended list of mutex */ + rt_list_remove(&(next_thread->tlist)); + + /* set new owner and put mutex into taken list of thread */ + mutex->owner = next_thread; + mutex->hold = 1; + rt_list_insert_after(&next_thread->taken_object_list, &mutex->taken_list); + /* cleanup pending object */ + next_thread->pending_object = RT_NULL; + + /* resume thread */ + rt_thread_resume(next_thread); + + /* update mutex priority */ + if (!rt_list_isempty(&(mutex->parent.suspend_thread))) + { + struct rt_thread *th; + + th = rt_list_entry(mutex->parent.suspend_thread.next, + struct rt_thread, + tlist); + mutex->priority = th->current_priority; + } + else + { + mutex->priority = 0xff; + } + + need_schedule = RT_TRUE; + } + else + { + /* clear owner */ + mutex->owner = RT_NULL; + mutex->priority = 0xff; + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* perform a schedule */ + if (need_schedule == RT_TRUE) + rt_schedule(); + + return RT_EOK; +} +RTM_EXPORT(rt_mutex_release); + + +/** + * @brief This function will set some extra attributions of a mutex object. + * + * @note Currently this function does not implement the control function. + * + * @param mutex is a pointer to a mutex object. + * + * @param cmd is a command word used to configure some attributions of the mutex. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_mutex_control(rt_mutex_t mutex, int cmd, void *arg) +{ + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + + return -RT_ERROR; +} +RTM_EXPORT(rt_mutex_control); + +/**@}*/ +#endif /* RT_USING_MUTEX */ + +#ifdef RT_USING_EVENT +/** + * @addtogroup event + * @{ + */ + +/** + * @brief The function will initialize a static event object. + * + * @note For the static event object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_event_create() function will allocate memory space automatically + * and initialize the event. + * + * @see rt_event_create() + * + * @param event is a pointer to the event to initialize. It is assumed that storage for the event + * will be allocated in your application. + * + * @param name is a pointer to the name that given to the event. + * + * @param flag is the event flag, which determines the queuing way of how multiple threads wait + * when the event is not available. + * The event flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this event will become non-real-time threads. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_event_init(rt_event_t event, const char *name, rt_uint8_t flag) +{ + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(event->parent.parent), RT_Object_Class_Event, name); + + /* set parent flag */ + event->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(event->parent)); + + /* initialize event */ + event->set = 0; + + return RT_EOK; +} +RTM_EXPORT(rt_event_init); + + +/** + * @brief This function will detach a static event object. + * + * @note This function is used to detach a static event object which is initialized by rt_event_init() function. + * By contrast, the rt_event_delete() function will delete an event object. + * When the event is successfully detached, it will resume all suspended threads in the event list. + * + * @see rt_event_delete() + * + * @param event is a pointer to an event object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the event detach failed. + * + * @warning This function can ONLY detach a static event initialized by the rt_event_init() function. + * If the event is created by the rt_event_create() function, you MUST NOT USE this function to detach it, + * ONLY USE the rt_event_delete() function to complete the deletion. + */ +rt_err_t rt_event_detach(rt_event_t event) +{ + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + RT_ASSERT(rt_object_is_systemobject(&event->parent.parent)); + + /* resume all suspended thread */ + _ipc_list_resume_all(&(event->parent.suspend_thread)); + + /* detach event object */ + rt_object_detach(&(event->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_event_detach); + +#ifdef RT_USING_HEAP +/** + * @brief Creating an event object. + * + * @note For the event object, its memory space is allocated automatically. + * By contrast, the rt_event_init() function will initialize a static event object. + * + * @see rt_event_init() + * + * @param name is a pointer to the name that given to the event. + * + * @param flag is the event flag, which determines the queuing way of how multiple threads wait when the event + * is not available. + * The event flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this event will become non-real-time threads. + * + * @return Return a pointer to the event object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_event_t rt_event_create(const char *name, rt_uint8_t flag) +{ + rt_event_t event; + + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + event = (rt_event_t)rt_object_allocate(RT_Object_Class_Event, name); + if (event == RT_NULL) + return event; + + /* set parent */ + event->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(event->parent)); + + /* initialize event */ + event->set = 0; + + return event; +} +RTM_EXPORT(rt_event_create); + + +/** + * @brief This function will delete an event object and release the memory space. + * + * @note This function is used to delete an event object which is created by the rt_event_create() function. + * By contrast, the rt_event_detach() function will detach a static event object. + * When the event is successfully deleted, it will resume all suspended threads in the event list. + * + * @see rt_event_detach() + * + * @param event is a pointer to an event object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the event detach failed. + * + * @warning This function can ONLY delete an event initialized by the rt_event_create() function. + * If the event is initialized by the rt_event_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_event_detach() function to complete the detachment. + */ +rt_err_t rt_event_delete(rt_event_t event) +{ + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + RT_ASSERT(rt_object_is_systemobject(&event->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* resume all suspended thread */ + _ipc_list_resume_all(&(event->parent.suspend_thread)); + + /* delete event object */ + rt_object_delete(&(event->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_event_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will send an event to the event object. + * If there is a thread suspended on the event, the thread will be resumed. + * + * @note When using this function, you need to use the parameter (set) to specify the event flag of the event object, + * then the function will traverse the list of suspended threads waiting on the event object. + * If there is a thread suspended on the event, and the thread's event_info and the event flag of + * the current event object matches, the thread will be resumed. + * + * @param event is a pointer to the event object to be sent. + * + * @param set is a flag that you will set for this event's flag. + * You can set an event flag, or you can set multiple flags through OR logic operation. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the event detach failed. + */ +rt_err_t rt_event_send(rt_event_t event, rt_uint32_t set) +{ + struct rt_list_node *n; + struct rt_thread *thread; + rt_base_t level; + rt_base_t status; + rt_bool_t need_schedule; + + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + + if (set == 0) + return -RT_ERROR; + + need_schedule = RT_FALSE; + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* set event */ + event->set |= set; + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(event->parent.parent))); + + if (!rt_list_isempty(&event->parent.suspend_thread)) + { + /* search thread list to resume thread */ + n = event->parent.suspend_thread.next; + while (n != &(event->parent.suspend_thread)) + { + /* get thread */ + thread = rt_list_entry(n, struct rt_thread, tlist); + + status = -RT_ERROR; + if (thread->event_info & RT_EVENT_FLAG_AND) + { + if ((thread->event_set & event->set) == thread->event_set) + { + /* received an AND event */ + status = RT_EOK; + } + } + else if (thread->event_info & RT_EVENT_FLAG_OR) + { + if (thread->event_set & event->set) + { + /* save the received event set */ + thread->event_set = thread->event_set & event->set; + + /* received an OR event */ + status = RT_EOK; + } + } + else + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EINVAL; + } + + /* move node to the next */ + n = n->next; + + /* condition is satisfied, resume thread */ + if (status == RT_EOK) + { + /* clear event */ + if (thread->event_info & RT_EVENT_FLAG_CLEAR) + event->set &= ~thread->event_set; + + /* resume thread, and thread list breaks out */ + rt_thread_resume(thread); + thread->error = RT_EOK; + + /* need do a scheduling */ + need_schedule = RT_TRUE; + } + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do a schedule */ + if (need_schedule == RT_TRUE) + rt_schedule(); + + return RT_EOK; +} +RTM_EXPORT(rt_event_send); + + +/** + * @brief This function will receive an event from event object. if the event is unavailable, the thread shall wait for + * the event up to a specified time. + * + * @note If there are threads suspended on this semaphore, the first thread in the list of this semaphore object + * will be resumed, and a thread scheduling (rt_schedule) will be executed. + * If no threads are suspended on this semaphore, the count value sem->value of this semaphore will increase by 1. + * + * @param event is a pointer to the event object to be received. + * + * @param set is a flag that you will set for this event's flag. + * You can set an event flag, or you can set multiple flags through OR logic operation. + * + * @param option is the option of this receiving event, it indicates how the receiving event is operated. + * The option can be one or more of the following values, When selecting multiple values,use logical OR to operate. + * (NOTE: RT_EVENT_FLAG_OR and RT_EVENT_FLAG_AND can only select one): + * + * + * RT_EVENT_FLAG_OR The thread select to use logical OR to receive the event. + * + * RT_EVENT_FLAG_AND The thread select to use logical OR to receive the event. + * + * RT_EVENT_FLAG_CLEAR When the thread receives the corresponding event, the function + * determines whether to clear the event flag. + * + * @param timeout is a timeout period (unit: an OS tick). + * + * @param recved is a pointer to the received event. If you don't care about this value, you can use RT_NULL to set. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the semaphore release failed. + */ +static rt_err_t _rt_event_recv(rt_event_t event, + rt_uint32_t set, + rt_uint8_t option, + rt_int32_t timeout, + rt_uint32_t *recved, + int suspend_flag) +{ + struct rt_thread *thread; + rt_base_t level; + rt_base_t status; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE); + + if (set == 0) + return -RT_ERROR; + + /* initialize status */ + status = -RT_ERROR; + /* get current thread */ + thread = rt_thread_self(); + /* reset thread error */ + thread->error = -RT_EINTR; + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(event->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* check event set */ + if (option & RT_EVENT_FLAG_AND) + { + if ((event->set & set) == set) + status = RT_EOK; + } + else if (option & RT_EVENT_FLAG_OR) + { + if (event->set & set) + status = RT_EOK; + } + else + { + /* either RT_EVENT_FLAG_AND or RT_EVENT_FLAG_OR should be set */ + RT_ASSERT(0); + } + + if (status == RT_EOK) + { + thread->error = RT_EOK; + + /* set received event */ + if (recved) + *recved = (event->set & set); + + /* fill thread event info */ + thread->event_set = (event->set & set); + thread->event_info = option; + + /* received event */ + if (option & RT_EVENT_FLAG_CLEAR) + event->set &= ~set; + } + else if (timeout == 0) + { + /* no waiting */ + thread->error = -RT_ETIMEOUT; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + else + { + /* fill thread event info */ + thread->event_set = set; + thread->event_info = option; + + /* put thread to suspended thread list */ + ret = _ipc_list_suspend(&(event->parent.suspend_thread), + thread, + event->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* if there is a waiting timeout, active thread timer */ + if (timeout > 0) + { + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do a schedule */ + rt_schedule(); + + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* received an event, disable interrupt to protect */ + level = rt_hw_interrupt_disable(); + + /* set received event */ + if (recved) + *recved = thread->event_set; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(event->parent.parent))); + + return thread->error; +} + +rt_err_t rt_event_recv(rt_event_t event, + rt_uint32_t set, + rt_uint8_t option, + rt_int32_t timeout, + rt_uint32_t *recved) +{ + return _rt_event_recv(event, set, option, timeout, recved, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_event_recv); + +rt_err_t rt_event_recv_interruptible(rt_event_t event, + rt_uint32_t set, + rt_uint8_t option, + rt_int32_t timeout, + rt_uint32_t *recved) +{ + return _rt_event_recv(event, set, option, timeout, recved, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_event_recv_interruptible); + +rt_err_t rt_event_recv_killable(rt_event_t event, + rt_uint32_t set, + rt_uint8_t option, + rt_int32_t timeout, + rt_uint32_t *recved) +{ + return _rt_event_recv(event, set, option, timeout, recved, RT_KILLABLE); +} +RTM_EXPORT(rt_event_recv_killable); +/** + * @brief This function will set some extra attributions of an event object. + * + * @note Currently this function only supports the RT_IPC_CMD_RESET command to reset the event. + * + * @param event is a pointer to an event object. + * + * @param cmd is a command word used to configure some attributions of the event. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_event_control(rt_event_t event, int cmd, void *arg) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + + if (cmd == RT_IPC_CMD_RESET) + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* resume all waiting thread */ + _ipc_list_resume_all(&event->parent.suspend_thread); + + /* initialize event set */ + event->set = 0; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_event_control); + +/**@}*/ +#endif /* RT_USING_EVENT */ + +#ifdef RT_USING_MAILBOX +/** + * @addtogroup mailbox + * @{ + */ + +/** + * @brief Initialize a static mailbox object. + * + * @note For the static mailbox object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_mb_create() function will allocate memory space automatically and initialize the mailbox. + * + * @see rt_mb_create() + * + * @param mb is a pointer to the mailbox to initialize. + * It is assumed that storage for the mailbox will be allocated in your application. + * + * @param name is a pointer to the name that given to the mailbox. + * + * @param msgpool the begin address of buffer to save received mail. + * + * @param size is the maximum number of mails in the mailbox. + * For example, when the mailbox buffer capacity is N, size is N/4. + * + * @param flag is the mailbox flag, which determines the queuing way of how multiple threads wait + * when the mailbox is not available. + * The mailbox flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this mailbox will become non-real-time threads. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_mb_init(rt_mailbox_t mb, + const char *name, + void *msgpool, + rt_size_t size, + rt_uint8_t flag) +{ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(mb->parent.parent), RT_Object_Class_MailBox, name); + + /* set parent flag */ + mb->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(mb->parent)); + + /* initialize mailbox */ + mb->msg_pool = (rt_ubase_t *)msgpool; + mb->size = (rt_uint16_t)size; + mb->entry = 0; + mb->in_offset = 0; + mb->out_offset = 0; + + /* initialize an additional list of sender suspend thread */ + rt_list_init(&(mb->suspend_sender_thread)); + + return RT_EOK; +} +RTM_EXPORT(rt_mb_init); + + +/** + * @brief This function will detach a static mailbox object. + * + * @note This function is used to detach a static mailbox object which is initialized by rt_mb_init() function. + * By contrast, the rt_mb_delete() function will delete a mailbox object. + * When the mailbox is successfully detached, it will resume all suspended threads in the mailbox list. + * + * @see rt_mb_delete() + * + * @param mb is a pointer to a mailbox object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the mailbox detach failed. + * + * @warning This function can ONLY detach a static mailbox initialized by the rt_mb_init() function. + * If the mailbox is created by the rt_mb_create() function, you MUST NOT USE this function to detach it, + * ONLY USE the rt_mb_delete() function to complete the deletion. + */ +rt_err_t rt_mb_detach(rt_mailbox_t mb) +{ + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + RT_ASSERT(rt_object_is_systemobject(&mb->parent.parent)); + + /* resume all suspended thread */ + _ipc_list_resume_all(&(mb->parent.suspend_thread)); + /* also resume all mailbox private suspended thread */ + _ipc_list_resume_all(&(mb->suspend_sender_thread)); + + /* detach mailbox object */ + rt_object_detach(&(mb->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mb_detach); + +#ifdef RT_USING_HEAP +/** + * @brief Creating a mailbox object. + * + * @note For the mailbox object, its memory space is allocated automatically. + * By contrast, the rt_mb_init() function will initialize a static mailbox object. + * + * @see rt_mb_init() + * + * @param name is a pointer that given to the mailbox. + * + * @param size is the maximum number of mails in the mailbox. + * For example, when mailbox buffer capacity is N, size is N/4. + * + * @param flag is the mailbox flag, which determines the queuing way of how multiple threads wait + * when the mailbox is not available. + * The mailbox flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this mailbox will become non-real-time threads. + * + * @return Return a pointer to the mailbox object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_mailbox_t rt_mb_create(const char *name, rt_size_t size, rt_uint8_t flag) +{ + rt_mailbox_t mb; + + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + mb = (rt_mailbox_t)rt_object_allocate(RT_Object_Class_MailBox, name); + if (mb == RT_NULL) + return mb; + + /* set parent */ + mb->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(mb->parent)); + + /* initialize mailbox */ + mb->size = (rt_uint16_t)size; + mb->msg_pool = (rt_ubase_t *)RT_KERNEL_MALLOC(mb->size * sizeof(rt_ubase_t)); + if (mb->msg_pool == RT_NULL) + { + /* delete mailbox object */ + rt_object_delete(&(mb->parent.parent)); + + return RT_NULL; + } + mb->entry = 0; + mb->in_offset = 0; + mb->out_offset = 0; + + /* initialize an additional list of sender suspend thread */ + rt_list_init(&(mb->suspend_sender_thread)); + + return mb; +} +RTM_EXPORT(rt_mb_create); + + +/** + * @brief This function will delete a mailbox object and release the memory space. + * + * @note This function is used to delete a mailbox object which is created by the rt_mb_create() function. + * By contrast, the rt_mb_detach() function will detach a static mailbox object. + * When the mailbox is successfully deleted, it will resume all suspended threads in the mailbox list. + * + * @see rt_mb_detach() + * + * @param mb is a pointer to a mailbox object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + * + * @warning This function can only delete mailbox created by the rt_mb_create() function. + * If the mailbox is initialized by the rt_mb_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_mb_detach() function to complete the detachment. + */ +rt_err_t rt_mb_delete(rt_mailbox_t mb) +{ + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + RT_ASSERT(rt_object_is_systemobject(&mb->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* resume all suspended thread */ + _ipc_list_resume_all(&(mb->parent.suspend_thread)); + + /* also resume all mailbox private suspended thread */ + _ipc_list_resume_all(&(mb->suspend_sender_thread)); + + /* free mailbox pool */ + RT_KERNEL_FREE(mb->msg_pool); + + /* delete mailbox object */ + rt_object_delete(&(mb->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mb_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will send an mail to the mailbox object. If there is a thread suspended on the mailbox, + * the thread will be resumed. + * + * @note When using this function to send a mail, if the mailbox if fully used, the current thread will + * wait for a timeout. If the set timeout time is reached and there is still no space available, + * the sending thread will be resumed and an error code will be returned. + * By contrast, the rt_mb_send() function will return an error code immediately without waiting time + * when the mailbox if fully used. + * + * @see rt_mb_send() + * + * @param mb is a pointer to the mailbox object to be sent. + * + * @param value is a value to the content of the mail you want to send. + * + * @param timeout is a timeout period (unit: an OS tick). + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + * + * @warning This function can be called in interrupt context and thread context. + */ +static rt_err_t _rt_mb_send_wait(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout, + int suspend_flag) +{ + struct rt_thread *thread; + rt_base_t level; + rt_uint32_t tick_delta; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0); + + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mb->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* for non-blocking call */ + if (mb->entry == mb->size && timeout == 0) + { + rt_hw_interrupt_enable(level); + return -RT_EFULL; + } + + /* mailbox is full */ + while (mb->entry == mb->size) + { + /* reset error number in thread */ + thread->error = -RT_EINTR; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EFULL; + } + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mb->suspend_sender_thread), + thread, + mb->parent.parent.flag, + suspend_flag); + + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mb_send_wait: start timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* re-schedule */ + rt_schedule(); + + /* resume from suspend state */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + + /* set ptr */ + mb->msg_pool[mb->in_offset] = value; + /* increase input offset */ + ++ mb->in_offset; + if (mb->in_offset >= mb->size) + mb->in_offset = 0; + + if(mb->entry < RT_MB_ENTRY_MAX) + { + /* increase message entry */ + mb->entry ++; + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + + /* resume suspended thread */ + if (!rt_list_isempty(&mb->parent.suspend_thread)) + { + _ipc_list_resume(&(mb->parent.suspend_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} + +rt_err_t rt_mb_send_wait(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout) +{ + return _rt_mb_send_wait(mb, value, timeout, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mb_send_wait); + +rt_err_t rt_mb_send_wait_interruptible(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout) +{ + return _rt_mb_send_wait(mb, value, timeout, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mb_send_wait_interruptible); + +rt_err_t rt_mb_send_wait_killable(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout) +{ + return _rt_mb_send_wait(mb, value, timeout, RT_KILLABLE); +} +RTM_EXPORT(rt_mb_send_wait_killable); +/** + * @brief This function will send an mail to the mailbox object. If there is a thread suspended on the mailbox, + * the thread will be resumed. + * + * @note When using this function to send a mail, if the mailbox is fully used, this function will return an error + * code immediately without waiting time. + * By contrast, the rt_mb_send_wait() function is set a timeout to wait for the mail to be sent. + * + * @see rt_mb_send_wait() + * + * @param mb is a pointer to the mailbox object to be sent. + * + * @param value is a value to the content of the mail you want to send. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + */ +rt_err_t rt_mb_send(rt_mailbox_t mb, rt_ubase_t value) +{ + return rt_mb_send_wait(mb, value, 0); +} +RTM_EXPORT(rt_mb_send); + +rt_err_t rt_mb_send_interruptible(rt_mailbox_t mb, rt_ubase_t value) +{ + return rt_mb_send_wait_interruptible(mb, value, 0); +} +RTM_EXPORT(rt_mb_send_interruptible); + +rt_err_t rt_mb_send_killable(rt_mailbox_t mb, rt_ubase_t value) +{ + return rt_mb_send_wait_killable(mb, value, 0); +} +RTM_EXPORT(rt_mb_send_killable); + +/** + * @brief This function will send an urgent mail to the mailbox object. + * + * @note This function is almost the same as the rt_mb_send() function. The only difference is that + * when sending an urgent mail, the mail will be placed at the head of the mail queue so that + * the recipient can receive the urgent mail first. + * + * @see rt_mb_send() + * + * @param mb is a pointer to the mailbox object to be sent. + * + * @param value is the content of the mail you want to send. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + */ +rt_err_t rt_mb_urgent(rt_mailbox_t mb, rt_ubase_t value) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mb->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + if (mb->entry == mb->size) + { + rt_hw_interrupt_enable(level); + return -RT_EFULL; + } + + /* rewind to the previous position */ + if (mb->out_offset > 0) + { + mb->out_offset --; + } + else + { + mb->out_offset = mb->size - 1; + } + + /* set ptr */ + mb->msg_pool[mb->out_offset] = value; + + /* increase message entry */ + mb->entry ++; + + /* resume suspended thread */ + if (!rt_list_isempty(&mb->parent.suspend_thread)) + { + _ipc_list_resume(&(mb->parent.suspend_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} +RTM_EXPORT(rt_mb_urgent); + + +/** + * @brief This function will receive a mail from mailbox object, if there is no mail in mailbox object, + * the thread shall wait for a specified time. + * + * @note Only when there is mail in the mailbox, the receiving thread can get the mail immediately and + * return RT_EOK, otherwise the receiving thread will be suspended until the set timeout. If the mail + * is still not received within the specified time, it will return-RT_ETIMEOUT. + * + * @param mb is a pointer to the mailbox object to be received. + * + * @param value is a flag that you will set for this mailbox's flag. + * You can set an mailbox flag, or you can set multiple flags through OR logic operations. + * + * @param timeout is a timeout period (unit: an OS tick). If the mailbox object is not avaliable in the queue, + * the thread will wait for the object in the queue up to the amount of time specified by this parameter. + * + * NOTE: + * If use Macro RT_WAITING_FOREVER to set this parameter, which means that when the + * mailbox object is unavailable in the queue, the thread will be waiting forever. + * If use macro RT_WAITING_NO to set this parameter, which means that this + * function is non-blocking and will return immediately. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox release failed. + */ +static rt_err_t _rt_mb_recv(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout, int suspend_flag) +{ + struct rt_thread *thread; + rt_base_t level; + rt_uint32_t tick_delta; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0); + + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(mb->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* for non-blocking call */ + if (mb->entry == 0 && timeout == 0) + { + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + + /* mailbox is empty */ + while (mb->entry == 0) + { + /* reset error number in thread */ + thread->error = -RT_EINTR; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + thread->error = -RT_ETIMEOUT; + + return -RT_ETIMEOUT; + } + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mb->parent.suspend_thread), + thread, + mb->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mb_recv: start timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* re-schedule */ + rt_schedule(); + + /* resume from suspend state */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + + /* fill ptr */ + *value = mb->msg_pool[mb->out_offset]; + + /* increase output offset */ + ++ mb->out_offset; + if (mb->out_offset >= mb->size) + mb->out_offset = 0; + + /* decrease message entry */ + if(mb->entry > 0) + { + mb->entry --; + } + + /* resume suspended thread */ + if (!rt_list_isempty(&(mb->suspend_sender_thread))) + { + _ipc_list_resume(&(mb->suspend_sender_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mb->parent.parent))); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mb->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_mb_recv(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout) +{ + return _rt_mb_recv(mb, value, timeout, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mb_recv); + +rt_err_t rt_mb_recv_interruptibale(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout) +{ + return _rt_mb_recv(mb, value, timeout, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mb_recv_interruptibale); + +rt_err_t rt_mb_recv_killable(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout) +{ + return _rt_mb_recv(mb, value, timeout, RT_KILLABLE); +} +RTM_EXPORT(rt_mb_recv_killable); + +/** + * @brief This function will set some extra attributions of a mailbox object. + * + * @note Currently this function only supports the RT_IPC_CMD_RESET command to reset the mailbox. + * + * @param mb is a pointer to a mailbox object. + * + * @param cmd is a command used to configure some attributions of the mailbox. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_mb_control(rt_mailbox_t mb, int cmd, void *arg) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + + if (cmd == RT_IPC_CMD_RESET) + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* resume all waiting thread */ + _ipc_list_resume_all(&(mb->parent.suspend_thread)); + /* also resume all mailbox private suspended thread */ + _ipc_list_resume_all(&(mb->suspend_sender_thread)); + + /* re-init mailbox */ + mb->entry = 0; + mb->in_offset = 0; + mb->out_offset = 0; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_mb_control); + +/**@}*/ +#endif /* RT_USING_MAILBOX */ + +#ifdef RT_USING_MESSAGEQUEUE +/** + * @addtogroup messagequeue + * @{ + */ + +struct rt_mq_message +{ + struct rt_mq_message *next; +}; + + +/** + * @brief Initialize a static messagequeue object. + * + * @note For the static messagequeue object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_mq_create() function will allocate memory space automatically + * and initialize the messagequeue. + * + * @see rt_mq_create() + * + * @param mq is a pointer to the messagequeue to initialize. It is assumed that storage for + * the messagequeue will be allocated in your application. + * + * @param name is a pointer to the name that given to the messagequeue. + * + * @param msgpool is a pointer to the starting address of the memory space you allocated for + * the messagequeue in advance. + * In other words, msgpool is a pointer to the messagequeue buffer of the starting address. + * + * @param msg_size is the maximum length of a message in the messagequeue (Unit: Byte). + * + * @param pool_size is the size of the memory space allocated for the messagequeue in advance. + * + * @param flag is the messagequeue flag, which determines the queuing way of how multiple threads wait + * when the messagequeue is not available. + * The messagequeue flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this messagequeue will become non-real-time threads. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_mq_init(rt_mq_t mq, + const char *name, + void *msgpool, + rt_size_t msg_size, + rt_size_t pool_size, + rt_uint8_t flag) +{ + struct rt_mq_message *head; + rt_base_t temp; + register rt_size_t msg_align_size; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(mq->parent.parent), RT_Object_Class_MessageQueue, name); + + /* set parent flag */ + mq->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(mq->parent)); + + /* set message pool */ + mq->msg_pool = msgpool; + + /* get correct message size */ + msg_align_size = RT_ALIGN(msg_size, RT_ALIGN_SIZE); + mq->msg_size = msg_size; + mq->max_msgs = pool_size / (msg_align_size + sizeof(struct rt_mq_message)); + + if (0 == mq->max_msgs) + { + return -RT_EINVAL; + } + + /* initialize message list */ + mq->msg_queue_head = RT_NULL; + mq->msg_queue_tail = RT_NULL; + + /* initialize message empty list */ + mq->msg_queue_free = RT_NULL; + for (temp = 0; temp < mq->max_msgs; temp ++) + { + head = (struct rt_mq_message *)((rt_uint8_t *)mq->msg_pool + + temp * (msg_align_size + sizeof(struct rt_mq_message))); + head->next = (struct rt_mq_message *)mq->msg_queue_free; + mq->msg_queue_free = head; + } + + /* the initial entry is zero */ + mq->entry = 0; + + /* initialize an additional list of sender suspend thread */ + rt_list_init(&(mq->suspend_sender_thread)); + + return RT_EOK; +} +RTM_EXPORT(rt_mq_init); + + +/** + * @brief This function will detach a static messagequeue object. + * + * @note This function is used to detach a static messagequeue object which is initialized by rt_mq_init() function. + * By contrast, the rt_mq_delete() function will delete a messagequeue object. + * When the messagequeue is successfully detached, it will resume all suspended threads in the messagequeue list. + * + * @see rt_mq_delete() + * + * @param mq is a pointer to a messagequeue object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the messagequeue detach failed. + * + * @warning This function can ONLY detach a static messagequeue initialized by the rt_mq_init() function. + * If the messagequeue is created by the rt_mq_create() function, you MUST NOT USE this function to detach it, + * and ONLY USE the rt_mq_delete() function to complete the deletion. + */ +rt_err_t rt_mq_detach(rt_mq_t mq) +{ + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(rt_object_is_systemobject(&mq->parent.parent)); + + /* resume all suspended thread */ + _ipc_list_resume_all(&mq->parent.suspend_thread); + /* also resume all message queue private suspended thread */ + _ipc_list_resume_all(&(mq->suspend_sender_thread)); + + /* detach message queue object */ + rt_object_detach(&(mq->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mq_detach); + +#ifdef RT_USING_HEAP +/** + * @brief Creating a messagequeue object. + * + * @note For the messagequeue object, its memory space is allocated automatically. + * By contrast, the rt_mq_init() function will initialize a static messagequeue object. + * + * @see rt_mq_init() + * + * @param name is a pointer that given to the messagequeue. + * + * @param msg_size is the maximum length of a message in the messagequeue (Unit: Byte). + * + * @param max_msgs is the maximum number of messages in the messagequeue. + * + * @param flag is the messagequeue flag, which determines the queuing way of how multiple threads wait + * when the messagequeue is not available. + * The messagequeue flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this messagequeue will become non-real-time threads. + * + * @return Return a pointer to the messagequeue object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can NOT be called in interrupt context. You can use macor RT_DEBUG_NOT_IN_INTERRUPT to check it. + */ +rt_mq_t rt_mq_create(const char *name, + rt_size_t msg_size, + rt_size_t max_msgs, + rt_uint8_t flag) +{ + struct rt_messagequeue *mq; + struct rt_mq_message *head; + rt_base_t temp; + register rt_size_t msg_align_size; + + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + mq = (rt_mq_t)rt_object_allocate(RT_Object_Class_MessageQueue, name); + if (mq == RT_NULL) + return mq; + + /* set parent */ + mq->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(mq->parent)); + + /* initialize message queue */ + + /* get correct message size */ + msg_align_size = RT_ALIGN(msg_size, RT_ALIGN_SIZE); + mq->msg_size = msg_size; + mq->max_msgs = max_msgs; + + /* allocate message pool */ + mq->msg_pool = RT_KERNEL_MALLOC((msg_align_size + sizeof(struct rt_mq_message)) * mq->max_msgs); + if (mq->msg_pool == RT_NULL) + { + rt_object_delete(&(mq->parent.parent)); + + return RT_NULL; + } + + /* initialize message list */ + mq->msg_queue_head = RT_NULL; + mq->msg_queue_tail = RT_NULL; + + /* initialize message empty list */ + mq->msg_queue_free = RT_NULL; + for (temp = 0; temp < mq->max_msgs; temp ++) + { + head = (struct rt_mq_message *)((rt_uint8_t *)mq->msg_pool + + temp * (msg_align_size + sizeof(struct rt_mq_message))); + head->next = (struct rt_mq_message *)mq->msg_queue_free; + mq->msg_queue_free = head; + } + + /* the initial entry is zero */ + mq->entry = 0; + + /* initialize an additional list of sender suspend thread */ + rt_list_init(&(mq->suspend_sender_thread)); + + return mq; +} +RTM_EXPORT(rt_mq_create); + + +/** + * @brief This function will delete a messagequeue object and release the memory. + * + * @note This function is used to delete a messagequeue object which is created by the rt_mq_create() function. + * By contrast, the rt_mq_detach() function will detach a static messagequeue object. + * When the messagequeue is successfully deleted, it will resume all suspended threads in the messagequeue list. + * + * @see rt_mq_detach() + * + * @param mq is a pointer to a messagequeue object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the messagequeue detach failed. + * + * @warning This function can ONLY delete a messagequeue initialized by the rt_mq_create() function. + * If the messagequeue is initialized by the rt_mq_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_mq_detach() function to complete the detachment. + * for example,the rt_mq_create() function, it cannot be called in interrupt context. + */ +rt_err_t rt_mq_delete(rt_mq_t mq) +{ + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(rt_object_is_systemobject(&mq->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* resume all suspended thread */ + _ipc_list_resume_all(&(mq->parent.suspend_thread)); + /* also resume all message queue private suspended thread */ + _ipc_list_resume_all(&(mq->suspend_sender_thread)); + + /* free message queue pool */ + RT_KERNEL_FREE(mq->msg_pool); + + /* delete message queue object */ + rt_object_delete(&(mq->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mq_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will send a message to the messagequeue object. If + * there is a thread suspended on the messagequeue, the thread will be + * resumed. + * + * @note When using this function to send a message, if the messagequeue is + * fully used, the current thread will wait for a timeout. If reaching + * the timeout and there is still no space available, the sending + * thread will be resumed and an error code will be returned. By + * contrast, the rt_mq_send() function will return an error code + * immediately without waiting when the messagequeue if fully used. + * + * @see rt_mq_send() + * + * @param mq is a pointer to the messagequeue object to be sent. + * + * @param buffer is the content of the message. + * + * @param size is the length of the message(Unit: Byte). + * + * @param timeout is a timeout period (unit: an OS tick). + * + * @return Return the operation status. When the return value is RT_EOK, the + * operation is successful. If the return value is any other values, + * it means that the messagequeue detach failed. + * + * @warning This function can be called in interrupt context and thread + * context. + */ +static rt_err_t _rt_mq_send_wait(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout, + int suspend_flag) +{ + rt_base_t level; + struct rt_mq_message *msg; + rt_uint32_t tick_delta; + struct rt_thread *thread; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(buffer != RT_NULL); + RT_ASSERT(size != 0); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0); + + /* greater than one message size */ + if (size > mq->msg_size) + return -RT_ERROR; + + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mq->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* get a free list, there must be an empty item */ + msg = (struct rt_mq_message *)mq->msg_queue_free; + /* for non-blocking call */ + if (msg == RT_NULL && timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EFULL; + } + + /* message queue is full */ + while ((msg = (struct rt_mq_message *)mq->msg_queue_free) == RT_NULL) + { + /* reset error number in thread */ + thread->error = -RT_EINTR; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EFULL; + } + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mq->suspend_sender_thread), + thread, + mq->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mq_send_wait: start timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* re-schedule */ + rt_schedule(); + + /* resume from suspend state */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + + /* move free list pointer */ + mq->msg_queue_free = msg->next; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* the msg is the new tailer of list, the next shall be NULL */ + msg->next = RT_NULL; + /* copy buffer */ + rt_memcpy(msg + 1, buffer, size); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + /* link msg to message queue */ + if (mq->msg_queue_tail != RT_NULL) + { + /* if the tail exists, */ + ((struct rt_mq_message *)mq->msg_queue_tail)->next = msg; + } + + /* set new tail */ + mq->msg_queue_tail = msg; + /* if the head is empty, set head */ + if (mq->msg_queue_head == RT_NULL) + mq->msg_queue_head = msg; + + if(mq->entry < RT_MQ_ENTRY_MAX) + { + /* increase message entry */ + mq->entry ++; + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + + /* resume suspended thread */ + if (!rt_list_isempty(&mq->parent.suspend_thread)) + { + _ipc_list_resume(&(mq->parent.suspend_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} + +rt_err_t rt_mq_send_wait(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_send_wait(mq, buffer, size, timeout, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mq_send_wait) + +rt_err_t rt_mq_send_wait_interruptible(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_send_wait(mq, buffer, size, timeout, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mq_send_wait_interruptible) + +rt_err_t rt_mq_send_wait_killable(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_send_wait(mq, buffer, size, timeout, RT_KILLABLE); +} +RTM_EXPORT(rt_mq_send_wait_killable) +/** + * @brief This function will send a message to the messagequeue object. + * If there is a thread suspended on the messagequeue, the thread will be resumed. + * + * @note When using this function to send a message, if the messagequeue is fully used, + * the current thread will wait for a timeout. + * By contrast, when the messagequeue is fully used, the rt_mq_send_wait() function will + * return an error code immediately without waiting. + * + * @see rt_mq_send_wait() + * + * @param mq is a pointer to the messagequeue object to be sent. + * + * @param buffer is the content of the message. + * + * @param size is the length of the message(Unit: Byte). + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the messagequeue detach failed. + * + * @warning This function can be called in interrupt context and thread context. + */ +rt_err_t rt_mq_send(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + return rt_mq_send_wait(mq, buffer, size, 0); +} +RTM_EXPORT(rt_mq_send); + +rt_err_t rt_mq_send_interrupt(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + return rt_mq_send_wait_interruptible(mq, buffer, size, 0); +} +RTM_EXPORT(rt_mq_send_interrupt); + +rt_err_t rt_mq_send_killable(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + return rt_mq_send_wait_killable(mq, buffer, size, 0); +} +RTM_EXPORT(rt_mq_send_killable); +/** + * @brief This function will send an urgent message to the messagequeue object. + * + * @note This function is almost the same as the rt_mq_send() function. The only difference is that + * when sending an urgent message, the message is placed at the head of the messagequeue so that + * the recipient can receive the urgent message first. + * + * @see rt_mq_send() + * + * @param mq is a pointer to the messagequeue object to be sent. + * + * @param buffer is the content of the message. + * + * @param size is the length of the message(Unit: Byte). + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + */ +rt_err_t rt_mq_urgent(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + rt_base_t level; + struct rt_mq_message *msg; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(buffer != RT_NULL); + RT_ASSERT(size != 0); + + /* greater than one message size */ + if (size > mq->msg_size) + return -RT_ERROR; + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mq->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* get a free list, there must be an empty item */ + msg = (struct rt_mq_message *)mq->msg_queue_free; + /* message queue is full */ + if (msg == RT_NULL) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EFULL; + } + /* move free list pointer */ + mq->msg_queue_free = msg->next; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* copy buffer */ + rt_memcpy(msg + 1, buffer, size); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* link msg to the beginning of message queue */ + msg->next = (struct rt_mq_message *)mq->msg_queue_head; + mq->msg_queue_head = msg; + + /* if there is no tail */ + if (mq->msg_queue_tail == RT_NULL) + mq->msg_queue_tail = msg; + + if(mq->entry < RT_MQ_ENTRY_MAX) + { + /* increase message entry */ + mq->entry ++; + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + + /* resume suspended thread */ + if (!rt_list_isempty(&mq->parent.suspend_thread)) + { + _ipc_list_resume(&(mq->parent.suspend_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} +RTM_EXPORT(rt_mq_urgent); + + +/** + * @brief This function will receive a message from message queue object, + * if there is no message in messagequeue object, the thread shall wait for a specified time. + * + * @note Only when there is mail in the mailbox, the receiving thread can get the mail immediately and return RT_EOK, + * otherwise the receiving thread will be suspended until timeout. + * If the mail is not received within the specified time, it will return -RT_ETIMEOUT. + * + * @param mq is a pointer to the messagequeue object to be received. + * + * @param buffer is the content of the message. + * + * @param size is the length of the message(Unit: Byte). + * + * @param timeout is a timeout period (unit: an OS tick). If the message is unavailable, the thread will wait for + * the message in the queue up to the amount of time specified by this parameter. + * + * NOTE: + * If use Macro RT_WAITING_FOREVER to set this parameter, which means that when the + * message is unavailable in the queue, the thread will be waiting forever. + * If use macro RT_WAITING_NO to set this parameter, which means that this + * function is non-blocking and will return immediately. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox release failed. + */ +static rt_err_t _rt_mq_recv(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout, + int suspend_flag) +{ + struct rt_thread *thread; + rt_base_t level; + struct rt_mq_message *msg; + rt_uint32_t tick_delta; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(buffer != RT_NULL); + RT_ASSERT(size != 0); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0); + + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(mq->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* for non-blocking call */ + if (mq->entry == 0 && timeout == 0) + { + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + + /* message queue is empty */ + while (mq->entry == 0) + { + /* reset error number in thread */ + thread->error = -RT_EINTR; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + thread->error = -RT_ETIMEOUT; + + return -RT_ETIMEOUT; + } + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mq->parent.suspend_thread), + thread, + mq->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("set thread:%s to timer list\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* re-schedule */ + rt_schedule(); + + /* recv message */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + + /* get message from queue */ + msg = (struct rt_mq_message *)mq->msg_queue_head; + + /* move message queue head */ + mq->msg_queue_head = msg->next; + /* reach queue tail, set to NULL */ + if (mq->msg_queue_tail == msg) + mq->msg_queue_tail = RT_NULL; + + /* decrease message entry */ + if(mq->entry > 0) + { + mq->entry --; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* copy message */ + rt_memcpy(buffer, msg + 1, size > mq->msg_size ? mq->msg_size : size); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + /* put message to free list */ + msg->next = (struct rt_mq_message *)mq->msg_queue_free; + mq->msg_queue_free = msg; + + /* resume suspended thread */ + if (!rt_list_isempty(&(mq->suspend_sender_thread))) + { + _ipc_list_resume(&(mq->suspend_sender_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mq->parent.parent))); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mq->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_mq_recv(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_recv(mq, buffer, size, timeout, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mq_recv); + +rt_err_t rt_mq_recv_interruptible(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_recv(mq, buffer, size, timeout, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mq_recv_interruptible); + +rt_err_t rt_mq_recv_killable(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_recv(mq, buffer, size, timeout, RT_KILLABLE); +} +RTM_EXPORT(rt_mq_recv_killable); +/** + * @brief This function will set some extra attributions of a messagequeue object. + * + * @note Currently this function only supports the RT_IPC_CMD_RESET command to reset the messagequeue. + * + * @param mq is a pointer to a messagequeue object. + * + * @param cmd is a command used to configure some attributions of the messagequeue. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_mq_control(rt_mq_t mq, int cmd, void *arg) +{ + rt_base_t level; + struct rt_mq_message *msg; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + + if (cmd == RT_IPC_CMD_RESET) + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* resume all waiting thread */ + _ipc_list_resume_all(&mq->parent.suspend_thread); + /* also resume all message queue private suspended thread */ + _ipc_list_resume_all(&(mq->suspend_sender_thread)); + + /* release all message in the queue */ + while (mq->msg_queue_head != RT_NULL) + { + /* get message from queue */ + msg = (struct rt_mq_message *)mq->msg_queue_head; + + /* move message queue head */ + mq->msg_queue_head = msg->next; + /* reach queue tail, set to NULL */ + if (mq->msg_queue_tail == msg) + mq->msg_queue_tail = RT_NULL; + + /* put message to free list */ + msg->next = (struct rt_mq_message *)mq->msg_queue_free; + mq->msg_queue_free = msg; + } + + /* clean entry */ + mq->entry = 0; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_mq_control); + +/**@}*/ +#endif /* RT_USING_MESSAGEQUEUE */ +/**@}*/ diff --git a/tasks/concur-rtthread-mutex-ceilings/partial_suspend/src/ipc.c b/tasks/concur-rtthread-mutex-ceilings/partial_suspend/src/ipc.c new file mode 100644 index 00000000..982262df --- /dev/null +++ b/tasks/concur-rtthread-mutex-ceilings/partial_suspend/src/ipc.c @@ -0,0 +1,3751 @@ +/* + * Copyright (c) 2006-2022, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +#include +#include + +#ifndef __on_rt_object_trytake_hook + #define __on_rt_object_trytake_hook(parent) __ON_HOOK_ARGS(rt_object_trytake_hook, (parent)) +#endif +#ifndef __on_rt_object_take_hook + #define __on_rt_object_take_hook(parent) __ON_HOOK_ARGS(rt_object_take_hook, (parent)) +#endif +#ifndef __on_rt_object_put_hook + #define __on_rt_object_put_hook(parent) __ON_HOOK_ARGS(rt_object_put_hook, (parent)) +#endif + +#if defined(RT_USING_HOOK) && defined(RT_HOOK_USING_FUNC_PTR) +extern void (*rt_object_trytake_hook)(struct rt_object *object); +extern void (*rt_object_take_hook)(struct rt_object *object); +extern void (*rt_object_put_hook)(struct rt_object *object); +#endif /* RT_USING_HOOK */ + +/** + * @addtogroup IPC + * @{ + */ + +/** + * @brief This function will initialize an IPC object, such as semaphore, mutex, messagequeue and mailbox. + * + * @note Executing this function will complete an initialization of the suspend thread list of the ipc object. + * + * @param ipc is a pointer to the IPC object. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * When the return value is any other values, it means the initialization failed. + * + * @warning This function can be called from all IPC initialization and creation. + */ +rt_inline rt_err_t _ipc_object_init(struct rt_ipc_object *ipc) +{ + /* initialize ipc object */ + rt_list_init(&(ipc->suspend_thread)); + + return RT_EOK; +} + + +/** + * @brief This function will suspend a thread to a IPC object list. + * + * @param list is a pointer to a suspended thread list of the IPC object. + * + * @param thread is a pointer to the thread object to be suspended. + * + * @param flag is a flag for the thread object to be suspended. It determines how the thread is suspended. + * The flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to use + * RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this semaphore will become non-real-time threads. + * + * @param suspend_flag status flag of the thread to be suspended. + * + * @return Return the operation status. When the return value is RT_EOK, the function is successfully executed. + * When the return value is any other values, it means the initialization failed. + * + * @warning This function can ONLY be called in the thread context, you can use RT_DEBUG_IN_THREAD_CONTEXT to + * check the context. + * In addition, this function is generally called by the following functions: + * rt_sem_take(), rt_mutex_take(), rt_event_recv(), rt_mb_send_wait(), + * rt_mb_recv(), rt_mq_recv(), rt_mq_send_wait() + */ +rt_inline rt_err_t _ipc_list_suspend(rt_list_t *list, + struct rt_thread *thread, + rt_uint8_t flag, + int suspend_flag) +{ + rt_err_t ret = rt_thread_suspend_with_flag(thread, suspend_flag); + + /* suspend thread */ + if (ret != RT_EOK) + { + return ret; + } + + switch (flag) + { + case RT_IPC_FLAG_FIFO: + rt_list_insert_before(list, &(thread->tlist)); + break; /* RT_IPC_FLAG_FIFO */ + + case RT_IPC_FLAG_PRIO: + { + struct rt_list_node *n; + struct rt_thread *sthread; + + /* find a suitable position */ + for (n = list->next; n != list; n = n->next) + { + sthread = rt_list_entry(n, struct rt_thread, tlist); + + /* find out */ + if (thread->current_priority < sthread->current_priority) + { + /* insert this thread before the sthread */ + rt_list_insert_before(&(sthread->tlist), &(thread->tlist)); + break; + } + } + + /* + * not found a suitable position, + * append to the end of suspend_thread list + */ + if (n == list) + rt_list_insert_before(list, &(thread->tlist)); + } + break;/* RT_IPC_FLAG_PRIO */ + + default: + RT_ASSERT(0); + break; + } + + return RT_EOK; +} + + +/** + * @brief This function will resume a thread. + * + * @note This function will resume the first thread in the list of a IPC object. + * 1. remove the thread from suspend queue of a IPC object. + * 2. put the thread into system ready queue. + * + * By contrast, the rt_ipc_list_resume_all() function will resume all suspended threads + * in the list of a IPC object. + * + * @param list is a pointer to a suspended thread list of the IPC object. + * + * @return Return the operation status. When the return value is RT_EOK, the function is successfully executed. + * When the return value is any other values, it means this operation failed. + * + * @warning This function is generally called by the following functions: + * rt_sem_release(), rt_mutex_release(), rt_mb_send_wait(), rt_mq_send_wait(), + * rt_mb_urgent(), rt_mb_recv(), rt_mq_urgent(), rt_mq_recv(), + */ +rt_inline rt_err_t _ipc_list_resume(rt_list_t *list) +{ + struct rt_thread *thread; + + /* get thread entry */ + thread = rt_list_entry(list->next, struct rt_thread, tlist); + + thread->error = RT_EOK; + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("resume thread:%s\n", thread->name)); + + /* resume it */ + rt_thread_resume(thread); + + return RT_EOK; +} + + +/** + * @brief This function will resume all suspended threads in the IPC object list, + * including the suspended list of IPC object, and private list of mailbox etc. + * + * @note This function will resume all threads in the IPC object list. + * By contrast, the rt_ipc_list_resume() function will resume a suspended thread in the list of a IPC object. + * + * @param list is a pointer to a suspended thread list of the IPC object. + * + * @return Return the operation status. When the return value is RT_EOK, the function is successfully executed. + * When the return value is any other values, it means this operation failed. + * + */ +rt_inline rt_err_t _ipc_list_resume_all(rt_list_t *list) +{ + struct rt_thread *thread; + rt_base_t level; + + /* wakeup all suspended threads */ + while (!rt_list_isempty(list)) + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* get next suspended thread */ + thread = rt_list_entry(list->next, struct rt_thread, tlist); + /* set error code to RT_ERROR */ + thread->error = -RT_ERROR; + + /* + * resume thread + * In rt_thread_resume function, it will remove current thread from + * suspended list + */ + rt_thread_resume(thread); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + } + + return RT_EOK; +} + +#ifdef RT_USING_SEMAPHORE +/** + * @addtogroup semaphore + * @{ + */ + +/** + * @brief This function will initialize a static semaphore object. + * + * @note For the static semaphore object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_sem_create() function will allocate memory space automatically and initialize + * the semaphore. + * + * @see rt_sem_create() + * + * @param sem is a pointer to the semaphore to initialize. It is assumed that storage for the semaphore will be + * allocated in your application. + * + * @param name is a pointer to the name you would like to give the semaphore. + * + * @param value is the initial value for the semaphore. + * If used to share resources, you should initialize the value as the number of available resources. + * If used to signal the occurrence of an event, you should initialize the value as 0. + * + * @param flag is the semaphore flag, which determines the queuing way of how multiple threads wait + * when the semaphore is not available. + * The semaphore flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this semaphore will become non-real-time threads. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_sem_init(rt_sem_t sem, + const char *name, + rt_uint32_t value, + rt_uint8_t flag) +{ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(value < 0x10000U); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(sem->parent.parent), RT_Object_Class_Semaphore, name); + + /* initialize ipc object */ + _ipc_object_init(&(sem->parent)); + + /* set initial value */ + sem->value = (rt_uint16_t)value; + + /* set parent */ + sem->parent.parent.flag = flag; + + return RT_EOK; +} +RTM_EXPORT(rt_sem_init); + + +/** + * @brief This function will detach a static semaphore object. + * + * @note This function is used to detach a static semaphore object which is initialized by rt_sem_init() function. + * By contrast, the rt_sem_delete() function will delete a semaphore object. + * When the semaphore is successfully detached, it will resume all suspended threads in the semaphore list. + * + * @see rt_sem_delete() + * + * @param sem is a pointer to a semaphore object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the semaphore detach failed. + * + * @warning This function can ONLY detach a static semaphore initialized by the rt_sem_init() function. + * If the semaphore is created by the rt_sem_create() function, you MUST NOT USE this function to detach it, + * ONLY USE the rt_sem_delete() function to complete the deletion. + */ +rt_err_t rt_sem_detach(rt_sem_t sem) +{ + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + RT_ASSERT(rt_object_is_systemobject(&sem->parent.parent)); + + /* wakeup all suspended threads */ + _ipc_list_resume_all(&(sem->parent.suspend_thread)); + + /* detach semaphore object */ + rt_object_detach(&(sem->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_sem_detach); + +#ifdef RT_USING_HEAP +/** + * @brief Creating a semaphore object. + * + * @note For the semaphore object, its memory space is allocated automatically. + * By contrast, the rt_sem_init() function will initialize a static semaphore object. + * + * @see rt_sem_init() + * + * @param name is a pointer to the name you would like to give the semaphore. + * + * @param value is the initial value for the semaphore. + * If used to share resources, you should initialize the value as the number of available resources. + * If used to signal the occurrence of an event, you should initialize the value as 0. + * + * @param flag is the semaphore flag, which determines the queuing way of how multiple threads wait + * when the semaphore is not available. + * The semaphore flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this semaphore will become non-real-time threads. + * + * @return Return a pointer to the semaphore object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can NOT be called in interrupt context. You can use macor RT_DEBUG_NOT_IN_INTERRUPT to check it. + */ +rt_sem_t rt_sem_create(const char *name, rt_uint32_t value, rt_uint8_t flag) +{ + rt_sem_t sem; + + RT_ASSERT(value < 0x10000U); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + sem = (rt_sem_t)rt_object_allocate(RT_Object_Class_Semaphore, name); + if (sem == RT_NULL) + return sem; + + /* initialize ipc object */ + _ipc_object_init(&(sem->parent)); + + /* set initial value */ + sem->value = value; + + /* set parent */ + sem->parent.parent.flag = flag; + + return sem; +} +RTM_EXPORT(rt_sem_create); + + +/** + * @brief This function will delete a semaphore object and release the memory space. + * + * @note This function is used to delete a semaphore object which is created by the rt_sem_create() function. + * By contrast, the rt_sem_detach() function will detach a static semaphore object. + * When the semaphore is successfully deleted, it will resume all suspended threads in the semaphore list. + * + * @see rt_sem_detach() + * + * @param sem is a pointer to a semaphore object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the semaphore detach failed. + * + * @warning This function can ONLY delete a semaphore initialized by the rt_sem_create() function. + * If the semaphore is initialized by the rt_sem_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_sem_detach() function to complete the detachment. + */ +rt_err_t rt_sem_delete(rt_sem_t sem) +{ + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + RT_ASSERT(rt_object_is_systemobject(&sem->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* wakeup all suspended threads */ + _ipc_list_resume_all(&(sem->parent.suspend_thread)); + + /* delete semaphore object */ + rt_object_delete(&(sem->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_sem_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will take a semaphore, if the semaphore is unavailable, the thread shall wait for + * the semaphore up to a specified time. + * + * @note When this function is called, the count value of the sem->value will decrease 1 until it is equal to 0. + * When the sem->value is 0, it means that the semaphore is unavailable. At this time, it will suspend the + * thread preparing to take the semaphore. + * On the contrary, the rt_sem_release() function will increase the count value of sem->value by 1 each time. + * + * @see rt_sem_trytake() + * + * @param sem is a pointer to a semaphore object. + * + * @param timeout is a timeout period (unit: an OS tick). If the semaphore is unavailable, the thread will wait for + * the semaphore up to the amount of time specified by this parameter. + * + * NOTE: + * If use Macro RT_WAITING_FOREVER to set this parameter, which means that when the + * message is unavailable in the queue, the thread will be waiting forever. + * If use macro RT_WAITING_NO to set this parameter, which means that this + * function is non-blocking and will return immediately. + * + * @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 semaphore take failed. + * + * @warning This function can ONLY be called in the thread context. It MUST NOT BE called in interrupt context. + */ +static rt_err_t _rt_sem_take(rt_sem_t sem, rt_int32_t timeout, int suspend_flag) +{ + rt_base_t level; + struct rt_thread *thread; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(sem->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("thread %s take sem:%s, which value is: %d\n", + rt_thread_self()->name, + ((struct rt_object *)sem)->name, + sem->value)); + + if (sem->value > 0) + { + /* semaphore is available */ + sem->value --; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + } + else + { + /* no waiting, return with timeout */ + if (timeout == 0) + { + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + else + { + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE); + + /* semaphore is unavailable, push to suspend list */ + /* get current thread */ + thread = rt_thread_self(); + + /* reset thread error number */ + thread->error = -RT_EINTR; + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("sem take: suspend thread - %s\n", + thread->name)); + + /* suspend thread */ + ret = _ipc_list_suspend(&(sem->parent.suspend_thread), + thread, + sem->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + RT_DEBUG_LOG(RT_DEBUG_IPC, ("set thread:%s to timer list\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do schedule */ + rt_schedule(); + + if (thread->error != RT_EOK) + { + return thread->error; + } + } + } + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(sem->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_sem_take(rt_sem_t sem, rt_int32_t time) +{ + return _rt_sem_take(sem, time, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_sem_take); + +rt_err_t rt_sem_take_interruptible(rt_sem_t sem, rt_int32_t time) +{ + return _rt_sem_take(sem, time, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_sem_take_interruptible); + +rt_err_t rt_sem_take_killable(rt_sem_t sem, rt_int32_t time) +{ + return _rt_sem_take(sem, time, RT_KILLABLE); +} +RTM_EXPORT(rt_sem_take_killable); + +/** + * @brief This function will try to take a semaphore, if the semaphore is unavailable, the thread returns immediately. + * + * @note This function is very similar to the rt_sem_take() function, when the semaphore is not available, + * the rt_sem_trytake() function will return immediately without waiting for a timeout. + * In other words, rt_sem_trytake(sem) has the same effect as rt_sem_take(sem, 0). + * + * @see rt_sem_take() + * + * @param sem is a pointer to a semaphore object. + * + * @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 semaphore take failed. + */ +rt_err_t rt_sem_trytake(rt_sem_t sem) +{ + return rt_sem_take(sem, RT_WAITING_NO); +} +RTM_EXPORT(rt_sem_trytake); + + +/** + * @brief This function will release a semaphore. If there is thread suspended on the semaphore, it will get resumed. + * + * @note If there are threads suspended on this semaphore, the first thread in the list of this semaphore object + * will be resumed, and a thread scheduling (rt_schedule) will be executed. + * If no threads are suspended on this semaphore, the count value sem->value of this semaphore will increase by 1. + * + * @param sem is a pointer to a semaphore object. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the semaphore release failed. + */ +rt_err_t rt_sem_release(rt_sem_t sem) +{ + rt_base_t level; + rt_bool_t need_schedule; + + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(sem->parent.parent))); + + need_schedule = RT_FALSE; + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("thread %s releases sem:%s, which value is: %d\n", + rt_thread_self()->name, + ((struct rt_object *)sem)->name, + sem->value)); + + if (!rt_list_isempty(&sem->parent.suspend_thread)) + { + /* resume the suspended thread */ + _ipc_list_resume(&(sem->parent.suspend_thread)); + need_schedule = RT_TRUE; + } + else + { + if(sem->value < RT_SEM_VALUE_MAX) + { + sem->value ++; /* increase value */ + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* resume a thread, re-schedule */ + if (need_schedule == RT_TRUE) + rt_schedule(); + + return RT_EOK; +} +RTM_EXPORT(rt_sem_release); + + +/** + * @brief This function will set some extra attributions of a semaphore object. + * + * @note Currently this function only supports the RT_IPC_CMD_RESET command to reset the semaphore. + * + * @param sem is a pointer to a semaphore object. + * + * @param cmd is a command word used to configure some attributions of the semaphore. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_sem_control(rt_sem_t sem, int cmd, void *arg) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + + if (cmd == RT_IPC_CMD_RESET) + { + rt_ubase_t value; + + /* get value */ + value = (rt_ubase_t)arg; + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* resume all waiting thread */ + _ipc_list_resume_all(&sem->parent.suspend_thread); + + /* set new value */ + sem->value = (rt_uint16_t)value; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_sem_control); + +/**@}*/ +#endif /* RT_USING_SEMAPHORE */ + +#ifdef RT_USING_MUTEX +/* iterate over each suspended thread to update highest priority in pending threads */ +rt_inline rt_uint8_t _mutex_update_priority(struct rt_mutex *mutex) +{ + struct rt_thread *thread; + + if (!rt_list_isempty(&mutex->parent.suspend_thread)) + { + thread = rt_list_entry(mutex->parent.suspend_thread.next, struct rt_thread, tlist); + mutex->priority = thread->current_priority; + } + else + { + mutex->priority = 0xff; + } + + return mutex->priority; +} + +/* get highest priority inside its taken object and its init priority */ +rt_inline rt_uint8_t _thread_get_mutex_priority(struct rt_thread* thread) +{ + rt_list_t *node = RT_NULL; + struct rt_mutex *mutex = RT_NULL; + rt_uint8_t priority = thread->init_priority; + + rt_list_for_each(node, &(thread->taken_object_list)) + { + mutex = rt_list_entry(node, struct rt_mutex, taken_list); + rt_uint8_t mutex_prio = mutex->priority; + /* prio at least be priority ceiling */ + mutex_prio = mutex_prio < mutex->ceiling_priority ? mutex_prio : mutex->ceiling_priority; + + if (priority > mutex_prio) + { + priority = mutex_prio; + } + } + + return priority; +} + +/* update priority of target thread and the thread suspended it if any */ +rt_inline void _thread_update_priority(struct rt_thread *thread, rt_uint8_t priority, int suspend_flag) +{ + rt_err_t ret; + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("thread:%s priority -> %d\n", thread->name, priority)); + + /* change priority of the thread */ + rt_thread_control(thread, + RT_THREAD_CTRL_CHANGE_PRIORITY, + &priority); + + if ((thread->stat & RT_THREAD_SUSPEND_MASK) == RT_THREAD_SUSPEND_MASK) + { + /* whether change the priority of taken mutex */ + struct rt_object* pending_obj = thread->pending_object; + + if (pending_obj && rt_object_get_type(pending_obj) == RT_Object_Class_Mutex) + { + rt_uint8_t mutex_priority; + struct rt_mutex* pending_mutex = (struct rt_mutex *)pending_obj; + + /* re-insert thread to suspended thread list */ + rt_list_remove(&(thread->tlist)); + + ret = _ipc_list_suspend(&(pending_mutex->parent.suspend_thread), + thread, + pending_mutex->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + /* TODO */ + return ; + } + + /* update priority */ + _mutex_update_priority(pending_mutex); + /* change the priority of mutex owner thread */ + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("mutex: %s priority -> %d\n", pending_mutex->parent.parent.name, + pending_mutex->priority)); + + mutex_priority = _thread_get_mutex_priority(pending_mutex->owner); + if (mutex_priority != pending_mutex->owner->current_priority) + { + _thread_update_priority(pending_mutex->owner, mutex_priority, suspend_flag); + } + } + } +} + +/** + * @addtogroup mutex + * @{ + */ + +/** + * @brief Initialize a static mutex object. + * + * @note For the static mutex object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_mutex_create() function will automatically allocate memory space + * and initialize the mutex. + * + * @see rt_mutex_create() + * + * @param mutex is a pointer to the mutex to initialize. It is assumed that storage for the mutex will be + * allocated in your application. + * + * @param name is a pointer to the name that given to the mutex. + * + * @param flag is the mutex flag, which determines the queuing way of how multiple threads wait + * when the mutex is not available. + * NOTE: This parameter has been obsoleted. It can be RT_IPC_FLAG_PRIO, RT_IPC_FLAG_FIFO or RT_NULL. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_mutex_init(rt_mutex_t mutex, const char *name, rt_uint8_t flag) +{ + /* flag parameter has been obsoleted */ + RT_UNUSED(flag); + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + + /* initialize object */ + rt_object_init(&(mutex->parent.parent), RT_Object_Class_Mutex, name); + + /* initialize ipc object */ + _ipc_object_init(&(mutex->parent)); + + mutex->owner = RT_NULL; + mutex->priority = 0xFF; + mutex->hold = 0; + mutex->ceiling_priority = 0xFF; + rt_list_init(&(mutex->taken_list)); + + /* flag can only be RT_IPC_FLAG_PRIO. RT_IPC_FLAG_FIFO cannot solve the unbounded priority inversion problem */ + mutex->parent.parent.flag = RT_IPC_FLAG_PRIO; + + return RT_EOK; +} +RTM_EXPORT(rt_mutex_init); + + +/** + * @brief This function will detach a static mutex object. + * + * @note This function is used to detach a static mutex object which is initialized by rt_mutex_init() function. + * By contrast, the rt_mutex_delete() function will delete a mutex object. + * When the mutex is successfully detached, it will resume all suspended threads in the mutex list. + * + * @see rt_mutex_delete() + * + * @param mutex is a pointer to a mutex object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the mutex detach failed. + * + * @warning This function can ONLY detach a static mutex initialized by the rt_mutex_init() function. + * If the mutex is created by the rt_mutex_create() function, you MUST NOT USE this function to detach it, + * ONLY USE the rt_mutex_delete() function to complete the deletion. + */ +rt_err_t rt_mutex_detach(rt_mutex_t mutex) +{ + rt_ubase_t level; + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + RT_ASSERT(rt_object_is_systemobject(&mutex->parent.parent)); + + level = rt_hw_interrupt_disable(); + /* wakeup all suspended threads */ + _ipc_list_resume_all(&(mutex->parent.suspend_thread)); + /* remove mutex from thread's taken list */ + rt_list_remove(&mutex->taken_list); + rt_hw_interrupt_enable(level); + + /* detach mutex object */ + rt_object_detach(&(mutex->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mutex_detach); + +/* drop a thread from the suspend list of mutex */ + +/** + * @brief drop a thread from the suspend list of mutex + * + * @param mutex is a pointer to a mutex object. + * @param thread is the thread should be dropped from mutex. + */ +void rt_mutex_drop_thread(rt_mutex_t mutex, rt_thread_t thread) +{ + rt_uint8_t priority; + rt_bool_t need_update = RT_FALSE; + + rt_list_remove(&(thread->tlist)); + + /* should change the priority of mutex owner thread */ + if (mutex->owner->current_priority == thread->current_priority) + need_update = RT_TRUE; + + /* update the priority of mutex */ + if (!rt_list_isempty(&mutex->parent.suspend_thread)) + { + /* more thread suspended in the list */ + struct rt_thread *th; + + th = rt_list_entry(mutex->parent.suspend_thread.next, + struct rt_thread, + tlist); + /* update the priority of mutex */ + mutex->priority = th->current_priority; + } + else + { + /* set mutex priority to maximal priority */ + mutex->priority = 0xff; + } + + /* try to change the priority of mutex owner thread */ + if (need_update) + { + /* get the maximal priority of mutex in thread */ + priority = _thread_get_mutex_priority(mutex->owner); + if (priority != mutex->owner->current_priority) + { + _thread_update_priority(mutex->owner, priority, RT_UNINTERRUPTIBLE); + } + } +} + + +/** + * @brief set the prioceiling attribute of the mutex. + * + * @param mutex is a pointer to a mutex object. + * @param priority is the priority should be set to mutex. + * + * @return return the old priority ceiling + */ +rt_uint8_t rt_mutex_setprioceiling(rt_mutex_t mutex, rt_uint8_t priority) +{ + rt_uint8_t ret_priority = 0xFF; + + if ((mutex) && (priority < RT_THREAD_PRIORITY_MAX)) + { + /* critical section here if multiple updates to one mutex happen */ + rt_ubase_t level = rt_hw_interrupt_disable(); + ret_priority = mutex->ceiling_priority; + mutex->ceiling_priority = priority; + if (mutex->owner) + { + rt_uint8_t priority = _thread_get_mutex_priority(mutex->owner); + if (priority != mutex->owner->current_priority) + _thread_update_priority(mutex->owner, priority, RT_UNINTERRUPTIBLE); + } + rt_hw_interrupt_enable(level); + } + else + { + rt_set_errno(-RT_EINVAL); + } + + return ret_priority; +} +RTM_EXPORT(rt_mutex_setprioceiling); + + +/** + * @brief set the prioceiling attribute of the mutex. + * + * @param mutex is a pointer to a mutex object. + * + * @return return the current priority ceiling of the mutex. + */ +rt_uint8_t rt_mutex_getprioceiling(rt_mutex_t mutex) +{ + rt_uint8_t prio = 0xFF; + + if (mutex) + { + prio = mutex->ceiling_priority; + } + + return prio; +} +RTM_EXPORT(rt_mutex_getprioceiling); + + +#ifdef RT_USING_HEAP +/** + * @brief This function will create a mutex object. + * + * @note For the mutex object, its memory space is automatically allocated. + * By contrast, the rt_mutex_init() function will initialize a static mutex object. + * + * @see rt_mutex_init() + * + * @param name is a pointer to the name that given to the mutex. + * + * @param flag is the mutex flag, which determines the queuing way of how multiple threads wait + * when the mutex is not available. + * NOTE: This parameter has been obsoleted. It can be RT_IPC_FLAG_PRIO, RT_IPC_FLAG_FIFO or RT_NULL. + * + * @return Return a pointer to the mutex object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_mutex_t rt_mutex_create(const char *name, rt_uint8_t flag) +{ + struct rt_mutex *mutex; + + /* flag parameter has been obsoleted */ + RT_UNUSED(flag); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + mutex = (rt_mutex_t)rt_object_allocate(RT_Object_Class_Mutex, name); + if (mutex == RT_NULL) + return mutex; + + /* initialize ipc object */ + _ipc_object_init(&(mutex->parent)); + + mutex->owner = RT_NULL; + mutex->priority = 0xFF; + mutex->hold = 0; + mutex->ceiling_priority = 0xFF; + rt_list_init(&(mutex->taken_list)); + + /* flag can only be RT_IPC_FLAG_PRIO. RT_IPC_FLAG_FIFO cannot solve the unbounded priority inversion problem */ + mutex->parent.parent.flag = RT_IPC_FLAG_PRIO; + + return mutex; +} +RTM_EXPORT(rt_mutex_create); + + +/** + * @brief This function will delete a mutex object and release this memory space. + * + * @note This function is used to delete a mutex object which is created by the rt_mutex_create() function. + * By contrast, the rt_mutex_detach() function will detach a static mutex object. + * When the mutex is successfully deleted, it will resume all suspended threads in the mutex list. + * + * @see rt_mutex_detach() + * + * @param mutex is a pointer to a mutex object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mutex detach failed. + * + * @warning This function can ONLY delete a mutex initialized by the rt_mutex_create() function. + * If the mutex is initialized by the rt_mutex_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_mutex_detach() function to complete the detachment. + */ +rt_err_t rt_mutex_delete(rt_mutex_t mutex) +{ + rt_ubase_t level; + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + RT_ASSERT(rt_object_is_systemobject(&mutex->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + level = rt_hw_interrupt_disable(); + /* wakeup all suspended threads */ + _ipc_list_resume_all(&(mutex->parent.suspend_thread)); + /* remove mutex from thread's taken list */ + rt_list_remove(&mutex->taken_list); + rt_hw_interrupt_enable(level); + + /* delete mutex object */ + rt_object_delete(&(mutex->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mutex_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will take a mutex, if the mutex is unavailable, the thread shall wait for + * the mutex up to a specified time. + * + * @note When this function is called, the count value of the mutex->value will decrease 1 until it is equal to 0. + * When the mutex->value is 0, it means that the mutex is unavailable. At this time, it will suspend the + * thread preparing to take the mutex. + * On the contrary, the rt_mutex_release() function will increase the count value of mutex->value by 1 each time. + * + * @see rt_mutex_trytake() + * + * @param mutex is a pointer to a mutex object. + * + * @param timeout is a timeout period (unit: an OS tick). If the mutex is unavailable, the thread will wait for + * the mutex up to the amount of time specified by the argument. + * NOTE: Generally, we set this parameter to RT_WAITING_FOREVER, which means that when the mutex is unavailable, + * the thread will be waitting forever. + * + * @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 mutex take failed. + * + * @warning This function can ONLY be called in the thread context. It MUST NOT BE called in interrupt context. + */ +static rt_err_t _rt_mutex_take(rt_mutex_t mutex, rt_int32_t timeout, int suspend_flag) +{ + rt_base_t level; + struct rt_thread *thread; + rt_err_t ret; + + /* this function must not be used in interrupt even if time = 0 */ + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE); + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + + /* get current thread */ + thread = rt_thread_self(); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(mutex->parent.parent))); + + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("mutex_take: current thread %s, hold: %d\n", + thread->name, mutex->hold)); + + /* reset thread error */ + thread->error = RT_EOK; + + if (mutex->owner == thread) + { + if(mutex->hold < RT_MUTEX_HOLD_MAX) + { + /* it's the same thread */ + mutex->hold ++; + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + } + else + { + /* whether the mutex has owner thread. */ + if (mutex->owner == RT_NULL) + { + /* set mutex owner and original priority */ + mutex->owner = thread; + mutex->priority = 0xff; + mutex->hold = 1; + + if (mutex->ceiling_priority != 0xFF) + { + /* set the priority of thread to the ceiling priority */ + if (mutex->ceiling_priority < mutex->owner->current_priority) + _thread_update_priority(mutex->owner, mutex->ceiling_priority, suspend_flag); + } + + /* insert mutex to thread's taken object list */ + rt_list_insert_after(&thread->taken_object_list, &mutex->taken_list); + } + else + { + /* no waiting, return with timeout */ + if (timeout == 0) + { + /* set error as timeout */ + thread->error = -RT_ETIMEOUT; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + else + { + rt_uint8_t priority = thread->current_priority; + + /* mutex is unavailable, push to suspend list */ + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mutex_take: suspend thread: %s\n", + thread->name)); + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mutex->parent.suspend_thread), + thread, + mutex->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* set pending object in thread to this mutex */ + thread->pending_object = &(mutex->parent.parent); + + /* update the priority level of mutex */ + if (priority < mutex->priority) + { + mutex->priority = priority; + if (mutex->priority < mutex->owner->current_priority) + { + _thread_update_priority(mutex->owner, priority, RT_UNINTERRUPTIBLE); /* TODO */ + } + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("mutex_take: start the timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do schedule */ + rt_schedule(); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + if (thread->error == RT_EOK) + { + /* get mutex successfully */ + } + else + { + /* the mutex has not been taken and thread has detach from the pending list. */ + + rt_bool_t need_update = RT_FALSE; + + /* should change the priority of mutex owner thread */ + if (mutex->owner->current_priority == thread->current_priority) + need_update = RT_TRUE; + + /* update the priority of mutex */ + if (!rt_list_isempty(&mutex->parent.suspend_thread)) + { + /* more thread suspended in the list */ + struct rt_thread *th; + + th = rt_list_entry(mutex->parent.suspend_thread.next, + struct rt_thread, + tlist); + /* update the priority of mutex */ + mutex->priority = th->current_priority; + } + else + { + /* set mutex priority to maximal priority */ + mutex->priority = 0xff; + } + + /* try to change the priority of mutex owner thread */ + if (need_update) + { + /* get the maximal priority of mutex in thread */ + priority = _thread_get_mutex_priority(mutex->owner); + if (priority != mutex->owner->current_priority) + { + _thread_update_priority(mutex->owner, priority, RT_UNINTERRUPTIBLE); + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* return error */ + return thread->error; + } + } + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mutex->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_mutex_take(rt_mutex_t mutex, rt_int32_t time) +{ + return _rt_mutex_take(mutex, time, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mutex_take); + +rt_err_t rt_mutex_take_interruptible(rt_mutex_t mutex, rt_int32_t time) +{ + return _rt_mutex_take(mutex, time, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mutex_take_interruptible); + +rt_err_t rt_mutex_take_killable(rt_mutex_t mutex, rt_int32_t time) +{ + return _rt_mutex_take(mutex, time, RT_KILLABLE); +} +RTM_EXPORT(rt_mutex_take_killable); + +/** + * @brief This function will try to take a mutex, if the mutex is unavailable, the thread returns immediately. + * + * @note This function is very similar to the rt_mutex_take() function, when the mutex is not available, + * except that rt_mutex_trytake() will return immediately without waiting for a timeout + * when the mutex is not available. + * In other words, rt_mutex_trytake(mutex) has the same effect as rt_mutex_take(mutex, 0). + * + * @see rt_mutex_take() + * + * @param mutex is a pointer to a mutex object. + * + * @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 mutex take failed. + */ +rt_err_t rt_mutex_trytake(rt_mutex_t mutex) +{ + return rt_mutex_take(mutex, RT_WAITING_NO); +} +RTM_EXPORT(rt_mutex_trytake); + + +/** + * @brief This function will release a mutex. If there is thread suspended on the mutex, the thread will be resumed. + * + * @note If there are threads suspended on this mutex, the first thread in the list of this mutex object + * will be resumed, and a thread scheduling (rt_schedule) will be executed. + * If no threads are suspended on this mutex, the count value mutex->value of this mutex will increase by 1. + * + * @param mutex is a pointer to a mutex object. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mutex release failed. + */ +rt_err_t rt_mutex_release(rt_mutex_t mutex) +{ + rt_base_t level; + struct rt_thread *thread; + rt_bool_t need_schedule; + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + + need_schedule = RT_FALSE; + + /* only thread could release mutex because we need test the ownership */ + RT_DEBUG_IN_THREAD_CONTEXT; + + /* get current thread */ + thread = rt_thread_self(); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("mutex_release:current thread %s, hold: %d\n", + thread->name, mutex->hold)); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mutex->parent.parent))); + + /* mutex only can be released by owner */ + if (thread != mutex->owner) + { + thread->error = -RT_ERROR; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_ERROR; + } + + /* decrease hold */ + mutex->hold --; + /* if no hold */ + if (mutex->hold == 0) + { + /* remove mutex from thread's taken list */ + rt_list_remove(&mutex->taken_list); + + /* whether change the thread priority */ + if ((mutex->ceiling_priority != 0xFF) || (thread->current_priority == mutex->priority)) + { + rt_uint8_t priority = 0xff; + + /* get the highest priority in the taken list of thread */ + priority = _thread_get_mutex_priority(thread); + + rt_thread_control(thread, + RT_THREAD_CTRL_CHANGE_PRIORITY, + &priority); + + need_schedule = RT_TRUE; + } + + /* wakeup suspended thread */ + if (!rt_list_isempty(&mutex->parent.suspend_thread)) + { + /* get the first suspended thread */ + struct rt_thread *next_thread = rt_list_entry(mutex->parent.suspend_thread.next, + struct rt_thread, + tlist); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mutex_release: resume thread: %s\n", + next_thread->name)); + + /* remove the thread from the suspended list of mutex */ + rt_list_remove(&(next_thread->tlist)); + + /* set new owner and put mutex into taken list of thread */ + mutex->owner = next_thread; + mutex->hold = 1; + rt_list_insert_after(&next_thread->taken_object_list, &mutex->taken_list); + /* cleanup pending object */ + next_thread->pending_object = RT_NULL; + + /* resume thread */ + rt_thread_resume(next_thread); + + /* update mutex priority */ + if (!rt_list_isempty(&(mutex->parent.suspend_thread))) + { + struct rt_thread *th; + + th = rt_list_entry(mutex->parent.suspend_thread.next, + struct rt_thread, + tlist); + mutex->priority = th->current_priority; + } + else + { + mutex->priority = 0xff; + } + + need_schedule = RT_TRUE; + } + else + { + /* clear owner */ + mutex->owner = RT_NULL; + mutex->priority = 0xff; + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* perform a schedule */ + if (need_schedule == RT_TRUE) + rt_schedule(); + + return RT_EOK; +} +RTM_EXPORT(rt_mutex_release); + + +/** + * @brief This function will set some extra attributions of a mutex object. + * + * @note Currently this function does not implement the control function. + * + * @param mutex is a pointer to a mutex object. + * + * @param cmd is a command word used to configure some attributions of the mutex. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_mutex_control(rt_mutex_t mutex, int cmd, void *arg) +{ + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + + return -RT_ERROR; +} +RTM_EXPORT(rt_mutex_control); + +/**@}*/ +#endif /* RT_USING_MUTEX */ + +#ifdef RT_USING_EVENT +/** + * @addtogroup event + * @{ + */ + +/** + * @brief The function will initialize a static event object. + * + * @note For the static event object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_event_create() function will allocate memory space automatically + * and initialize the event. + * + * @see rt_event_create() + * + * @param event is a pointer to the event to initialize. It is assumed that storage for the event + * will be allocated in your application. + * + * @param name is a pointer to the name that given to the event. + * + * @param flag is the event flag, which determines the queuing way of how multiple threads wait + * when the event is not available. + * The event flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this event will become non-real-time threads. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_event_init(rt_event_t event, const char *name, rt_uint8_t flag) +{ + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(event->parent.parent), RT_Object_Class_Event, name); + + /* set parent flag */ + event->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(event->parent)); + + /* initialize event */ + event->set = 0; + + return RT_EOK; +} +RTM_EXPORT(rt_event_init); + + +/** + * @brief This function will detach a static event object. + * + * @note This function is used to detach a static event object which is initialized by rt_event_init() function. + * By contrast, the rt_event_delete() function will delete an event object. + * When the event is successfully detached, it will resume all suspended threads in the event list. + * + * @see rt_event_delete() + * + * @param event is a pointer to an event object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the event detach failed. + * + * @warning This function can ONLY detach a static event initialized by the rt_event_init() function. + * If the event is created by the rt_event_create() function, you MUST NOT USE this function to detach it, + * ONLY USE the rt_event_delete() function to complete the deletion. + */ +rt_err_t rt_event_detach(rt_event_t event) +{ + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + RT_ASSERT(rt_object_is_systemobject(&event->parent.parent)); + + /* resume all suspended thread */ + _ipc_list_resume_all(&(event->parent.suspend_thread)); + + /* detach event object */ + rt_object_detach(&(event->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_event_detach); + +#ifdef RT_USING_HEAP +/** + * @brief Creating an event object. + * + * @note For the event object, its memory space is allocated automatically. + * By contrast, the rt_event_init() function will initialize a static event object. + * + * @see rt_event_init() + * + * @param name is a pointer to the name that given to the event. + * + * @param flag is the event flag, which determines the queuing way of how multiple threads wait when the event + * is not available. + * The event flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this event will become non-real-time threads. + * + * @return Return a pointer to the event object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_event_t rt_event_create(const char *name, rt_uint8_t flag) +{ + rt_event_t event; + + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + event = (rt_event_t)rt_object_allocate(RT_Object_Class_Event, name); + if (event == RT_NULL) + return event; + + /* set parent */ + event->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(event->parent)); + + /* initialize event */ + event->set = 0; + + return event; +} +RTM_EXPORT(rt_event_create); + + +/** + * @brief This function will delete an event object and release the memory space. + * + * @note This function is used to delete an event object which is created by the rt_event_create() function. + * By contrast, the rt_event_detach() function will detach a static event object. + * When the event is successfully deleted, it will resume all suspended threads in the event list. + * + * @see rt_event_detach() + * + * @param event is a pointer to an event object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the event detach failed. + * + * @warning This function can ONLY delete an event initialized by the rt_event_create() function. + * If the event is initialized by the rt_event_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_event_detach() function to complete the detachment. + */ +rt_err_t rt_event_delete(rt_event_t event) +{ + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + RT_ASSERT(rt_object_is_systemobject(&event->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* resume all suspended thread */ + _ipc_list_resume_all(&(event->parent.suspend_thread)); + + /* delete event object */ + rt_object_delete(&(event->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_event_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will send an event to the event object. + * If there is a thread suspended on the event, the thread will be resumed. + * + * @note When using this function, you need to use the parameter (set) to specify the event flag of the event object, + * then the function will traverse the list of suspended threads waiting on the event object. + * If there is a thread suspended on the event, and the thread's event_info and the event flag of + * the current event object matches, the thread will be resumed. + * + * @param event is a pointer to the event object to be sent. + * + * @param set is a flag that you will set for this event's flag. + * You can set an event flag, or you can set multiple flags through OR logic operation. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the event detach failed. + */ +rt_err_t rt_event_send(rt_event_t event, rt_uint32_t set) +{ + struct rt_list_node *n; + struct rt_thread *thread; + rt_base_t level; + rt_base_t status; + rt_bool_t need_schedule; + + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + + if (set == 0) + return -RT_ERROR; + + need_schedule = RT_FALSE; + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* set event */ + event->set |= set; + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(event->parent.parent))); + + if (!rt_list_isempty(&event->parent.suspend_thread)) + { + /* search thread list to resume thread */ + n = event->parent.suspend_thread.next; + while (n != &(event->parent.suspend_thread)) + { + /* get thread */ + thread = rt_list_entry(n, struct rt_thread, tlist); + + status = -RT_ERROR; + if (thread->event_info & RT_EVENT_FLAG_AND) + { + if ((thread->event_set & event->set) == thread->event_set) + { + /* received an AND event */ + status = RT_EOK; + } + } + else if (thread->event_info & RT_EVENT_FLAG_OR) + { + if (thread->event_set & event->set) + { + /* save the received event set */ + thread->event_set = thread->event_set & event->set; + + /* received an OR event */ + status = RT_EOK; + } + } + else + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EINVAL; + } + + /* move node to the next */ + n = n->next; + + /* condition is satisfied, resume thread */ + if (status == RT_EOK) + { + /* clear event */ + if (thread->event_info & RT_EVENT_FLAG_CLEAR) + event->set &= ~thread->event_set; + + /* resume thread, and thread list breaks out */ + rt_thread_resume(thread); + thread->error = RT_EOK; + + /* need do a scheduling */ + need_schedule = RT_TRUE; + } + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do a schedule */ + if (need_schedule == RT_TRUE) + rt_schedule(); + + return RT_EOK; +} +RTM_EXPORT(rt_event_send); + + +/** + * @brief This function will receive an event from event object. if the event is unavailable, the thread shall wait for + * the event up to a specified time. + * + * @note If there are threads suspended on this semaphore, the first thread in the list of this semaphore object + * will be resumed, and a thread scheduling (rt_schedule) will be executed. + * If no threads are suspended on this semaphore, the count value sem->value of this semaphore will increase by 1. + * + * @param event is a pointer to the event object to be received. + * + * @param set is a flag that you will set for this event's flag. + * You can set an event flag, or you can set multiple flags through OR logic operation. + * + * @param option is the option of this receiving event, it indicates how the receiving event is operated. + * The option can be one or more of the following values, When selecting multiple values,use logical OR to operate. + * (NOTE: RT_EVENT_FLAG_OR and RT_EVENT_FLAG_AND can only select one): + * + * + * RT_EVENT_FLAG_OR The thread select to use logical OR to receive the event. + * + * RT_EVENT_FLAG_AND The thread select to use logical OR to receive the event. + * + * RT_EVENT_FLAG_CLEAR When the thread receives the corresponding event, the function + * determines whether to clear the event flag. + * + * @param timeout is a timeout period (unit: an OS tick). + * + * @param recved is a pointer to the received event. If you don't care about this value, you can use RT_NULL to set. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the semaphore release failed. + */ +static rt_err_t _rt_event_recv(rt_event_t event, + rt_uint32_t set, + rt_uint8_t option, + rt_int32_t timeout, + rt_uint32_t *recved, + int suspend_flag) +{ + struct rt_thread *thread; + rt_base_t level; + rt_base_t status; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE); + + if (set == 0) + return -RT_ERROR; + + /* initialize status */ + status = -RT_ERROR; + /* get current thread */ + thread = rt_thread_self(); + /* reset thread error */ + thread->error = -RT_EINTR; + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(event->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* check event set */ + if (option & RT_EVENT_FLAG_AND) + { + if ((event->set & set) == set) + status = RT_EOK; + } + else if (option & RT_EVENT_FLAG_OR) + { + if (event->set & set) + status = RT_EOK; + } + else + { + /* either RT_EVENT_FLAG_AND or RT_EVENT_FLAG_OR should be set */ + RT_ASSERT(0); + } + + if (status == RT_EOK) + { + thread->error = RT_EOK; + + /* set received event */ + if (recved) + *recved = (event->set & set); + + /* fill thread event info */ + thread->event_set = (event->set & set); + thread->event_info = option; + + /* received event */ + if (option & RT_EVENT_FLAG_CLEAR) + event->set &= ~set; + } + else if (timeout == 0) + { + /* no waiting */ + thread->error = -RT_ETIMEOUT; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + else + { + /* fill thread event info */ + thread->event_set = set; + thread->event_info = option; + + /* put thread to suspended thread list */ + ret = _ipc_list_suspend(&(event->parent.suspend_thread), + thread, + event->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* if there is a waiting timeout, active thread timer */ + if (timeout > 0) + { + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do a schedule */ + rt_schedule(); + + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* received an event, disable interrupt to protect */ + level = rt_hw_interrupt_disable(); + + /* set received event */ + if (recved) + *recved = thread->event_set; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(event->parent.parent))); + + return thread->error; +} + +rt_err_t rt_event_recv(rt_event_t event, + rt_uint32_t set, + rt_uint8_t option, + rt_int32_t timeout, + rt_uint32_t *recved) +{ + return _rt_event_recv(event, set, option, timeout, recved, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_event_recv); + +rt_err_t rt_event_recv_interruptible(rt_event_t event, + rt_uint32_t set, + rt_uint8_t option, + rt_int32_t timeout, + rt_uint32_t *recved) +{ + return _rt_event_recv(event, set, option, timeout, recved, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_event_recv_interruptible); + +rt_err_t rt_event_recv_killable(rt_event_t event, + rt_uint32_t set, + rt_uint8_t option, + rt_int32_t timeout, + rt_uint32_t *recved) +{ + return _rt_event_recv(event, set, option, timeout, recved, RT_KILLABLE); +} +RTM_EXPORT(rt_event_recv_killable); +/** + * @brief This function will set some extra attributions of an event object. + * + * @note Currently this function only supports the RT_IPC_CMD_RESET command to reset the event. + * + * @param event is a pointer to an event object. + * + * @param cmd is a command word used to configure some attributions of the event. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_event_control(rt_event_t event, int cmd, void *arg) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + + if (cmd == RT_IPC_CMD_RESET) + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* resume all waiting thread */ + _ipc_list_resume_all(&event->parent.suspend_thread); + + /* initialize event set */ + event->set = 0; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_event_control); + +/**@}*/ +#endif /* RT_USING_EVENT */ + +#ifdef RT_USING_MAILBOX +/** + * @addtogroup mailbox + * @{ + */ + +/** + * @brief Initialize a static mailbox object. + * + * @note For the static mailbox object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_mb_create() function will allocate memory space automatically and initialize the mailbox. + * + * @see rt_mb_create() + * + * @param mb is a pointer to the mailbox to initialize. + * It is assumed that storage for the mailbox will be allocated in your application. + * + * @param name is a pointer to the name that given to the mailbox. + * + * @param msgpool the begin address of buffer to save received mail. + * + * @param size is the maximum number of mails in the mailbox. + * For example, when the mailbox buffer capacity is N, size is N/4. + * + * @param flag is the mailbox flag, which determines the queuing way of how multiple threads wait + * when the mailbox is not available. + * The mailbox flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this mailbox will become non-real-time threads. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_mb_init(rt_mailbox_t mb, + const char *name, + void *msgpool, + rt_size_t size, + rt_uint8_t flag) +{ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(mb->parent.parent), RT_Object_Class_MailBox, name); + + /* set parent flag */ + mb->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(mb->parent)); + + /* initialize mailbox */ + mb->msg_pool = (rt_ubase_t *)msgpool; + mb->size = (rt_uint16_t)size; + mb->entry = 0; + mb->in_offset = 0; + mb->out_offset = 0; + + /* initialize an additional list of sender suspend thread */ + rt_list_init(&(mb->suspend_sender_thread)); + + return RT_EOK; +} +RTM_EXPORT(rt_mb_init); + + +/** + * @brief This function will detach a static mailbox object. + * + * @note This function is used to detach a static mailbox object which is initialized by rt_mb_init() function. + * By contrast, the rt_mb_delete() function will delete a mailbox object. + * When the mailbox is successfully detached, it will resume all suspended threads in the mailbox list. + * + * @see rt_mb_delete() + * + * @param mb is a pointer to a mailbox object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the mailbox detach failed. + * + * @warning This function can ONLY detach a static mailbox initialized by the rt_mb_init() function. + * If the mailbox is created by the rt_mb_create() function, you MUST NOT USE this function to detach it, + * ONLY USE the rt_mb_delete() function to complete the deletion. + */ +rt_err_t rt_mb_detach(rt_mailbox_t mb) +{ + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + RT_ASSERT(rt_object_is_systemobject(&mb->parent.parent)); + + /* resume all suspended thread */ + _ipc_list_resume_all(&(mb->parent.suspend_thread)); + /* also resume all mailbox private suspended thread */ + _ipc_list_resume_all(&(mb->suspend_sender_thread)); + + /* detach mailbox object */ + rt_object_detach(&(mb->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mb_detach); + +#ifdef RT_USING_HEAP +/** + * @brief Creating a mailbox object. + * + * @note For the mailbox object, its memory space is allocated automatically. + * By contrast, the rt_mb_init() function will initialize a static mailbox object. + * + * @see rt_mb_init() + * + * @param name is a pointer that given to the mailbox. + * + * @param size is the maximum number of mails in the mailbox. + * For example, when mailbox buffer capacity is N, size is N/4. + * + * @param flag is the mailbox flag, which determines the queuing way of how multiple threads wait + * when the mailbox is not available. + * The mailbox flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this mailbox will become non-real-time threads. + * + * @return Return a pointer to the mailbox object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_mailbox_t rt_mb_create(const char *name, rt_size_t size, rt_uint8_t flag) +{ + rt_mailbox_t mb; + + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + mb = (rt_mailbox_t)rt_object_allocate(RT_Object_Class_MailBox, name); + if (mb == RT_NULL) + return mb; + + /* set parent */ + mb->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(mb->parent)); + + /* initialize mailbox */ + mb->size = (rt_uint16_t)size; + mb->msg_pool = (rt_ubase_t *)RT_KERNEL_MALLOC(mb->size * sizeof(rt_ubase_t)); + if (mb->msg_pool == RT_NULL) + { + /* delete mailbox object */ + rt_object_delete(&(mb->parent.parent)); + + return RT_NULL; + } + mb->entry = 0; + mb->in_offset = 0; + mb->out_offset = 0; + + /* initialize an additional list of sender suspend thread */ + rt_list_init(&(mb->suspend_sender_thread)); + + return mb; +} +RTM_EXPORT(rt_mb_create); + + +/** + * @brief This function will delete a mailbox object and release the memory space. + * + * @note This function is used to delete a mailbox object which is created by the rt_mb_create() function. + * By contrast, the rt_mb_detach() function will detach a static mailbox object. + * When the mailbox is successfully deleted, it will resume all suspended threads in the mailbox list. + * + * @see rt_mb_detach() + * + * @param mb is a pointer to a mailbox object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + * + * @warning This function can only delete mailbox created by the rt_mb_create() function. + * If the mailbox is initialized by the rt_mb_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_mb_detach() function to complete the detachment. + */ +rt_err_t rt_mb_delete(rt_mailbox_t mb) +{ + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + RT_ASSERT(rt_object_is_systemobject(&mb->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* resume all suspended thread */ + _ipc_list_resume_all(&(mb->parent.suspend_thread)); + + /* also resume all mailbox private suspended thread */ + _ipc_list_resume_all(&(mb->suspend_sender_thread)); + + /* free mailbox pool */ + RT_KERNEL_FREE(mb->msg_pool); + + /* delete mailbox object */ + rt_object_delete(&(mb->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mb_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will send an mail to the mailbox object. If there is a thread suspended on the mailbox, + * the thread will be resumed. + * + * @note When using this function to send a mail, if the mailbox if fully used, the current thread will + * wait for a timeout. If the set timeout time is reached and there is still no space available, + * the sending thread will be resumed and an error code will be returned. + * By contrast, the rt_mb_send() function will return an error code immediately without waiting time + * when the mailbox if fully used. + * + * @see rt_mb_send() + * + * @param mb is a pointer to the mailbox object to be sent. + * + * @param value is a value to the content of the mail you want to send. + * + * @param timeout is a timeout period (unit: an OS tick). + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + * + * @warning This function can be called in interrupt context and thread context. + */ +static rt_err_t _rt_mb_send_wait(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout, + int suspend_flag) +{ + struct rt_thread *thread; + rt_base_t level; + rt_uint32_t tick_delta; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0); + + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mb->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* for non-blocking call */ + if (mb->entry == mb->size && timeout == 0) + { + rt_hw_interrupt_enable(level); + return -RT_EFULL; + } + + /* mailbox is full */ + while (mb->entry == mb->size) + { + /* reset error number in thread */ + thread->error = -RT_EINTR; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EFULL; + } + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mb->suspend_sender_thread), + thread, + mb->parent.parent.flag, + suspend_flag); + + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mb_send_wait: start timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* re-schedule */ + rt_schedule(); + + /* resume from suspend state */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + + /* set ptr */ + mb->msg_pool[mb->in_offset] = value; + /* increase input offset */ + ++ mb->in_offset; + if (mb->in_offset >= mb->size) + mb->in_offset = 0; + + if(mb->entry < RT_MB_ENTRY_MAX) + { + /* increase message entry */ + mb->entry ++; + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + + /* resume suspended thread */ + if (!rt_list_isempty(&mb->parent.suspend_thread)) + { + _ipc_list_resume(&(mb->parent.suspend_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} + +rt_err_t rt_mb_send_wait(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout) +{ + return _rt_mb_send_wait(mb, value, timeout, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mb_send_wait); + +rt_err_t rt_mb_send_wait_interruptible(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout) +{ + return _rt_mb_send_wait(mb, value, timeout, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mb_send_wait_interruptible); + +rt_err_t rt_mb_send_wait_killable(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout) +{ + return _rt_mb_send_wait(mb, value, timeout, RT_KILLABLE); +} +RTM_EXPORT(rt_mb_send_wait_killable); +/** + * @brief This function will send an mail to the mailbox object. If there is a thread suspended on the mailbox, + * the thread will be resumed. + * + * @note When using this function to send a mail, if the mailbox is fully used, this function will return an error + * code immediately without waiting time. + * By contrast, the rt_mb_send_wait() function is set a timeout to wait for the mail to be sent. + * + * @see rt_mb_send_wait() + * + * @param mb is a pointer to the mailbox object to be sent. + * + * @param value is a value to the content of the mail you want to send. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + */ +rt_err_t rt_mb_send(rt_mailbox_t mb, rt_ubase_t value) +{ + return rt_mb_send_wait(mb, value, 0); +} +RTM_EXPORT(rt_mb_send); + +rt_err_t rt_mb_send_interruptible(rt_mailbox_t mb, rt_ubase_t value) +{ + return rt_mb_send_wait_interruptible(mb, value, 0); +} +RTM_EXPORT(rt_mb_send_interruptible); + +rt_err_t rt_mb_send_killable(rt_mailbox_t mb, rt_ubase_t value) +{ + return rt_mb_send_wait_killable(mb, value, 0); +} +RTM_EXPORT(rt_mb_send_killable); + +/** + * @brief This function will send an urgent mail to the mailbox object. + * + * @note This function is almost the same as the rt_mb_send() function. The only difference is that + * when sending an urgent mail, the mail will be placed at the head of the mail queue so that + * the recipient can receive the urgent mail first. + * + * @see rt_mb_send() + * + * @param mb is a pointer to the mailbox object to be sent. + * + * @param value is the content of the mail you want to send. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + */ +rt_err_t rt_mb_urgent(rt_mailbox_t mb, rt_ubase_t value) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mb->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + if (mb->entry == mb->size) + { + rt_hw_interrupt_enable(level); + return -RT_EFULL; + } + + /* rewind to the previous position */ + if (mb->out_offset > 0) + { + mb->out_offset --; + } + else + { + mb->out_offset = mb->size - 1; + } + + /* set ptr */ + mb->msg_pool[mb->out_offset] = value; + + /* increase message entry */ + mb->entry ++; + + /* resume suspended thread */ + if (!rt_list_isempty(&mb->parent.suspend_thread)) + { + _ipc_list_resume(&(mb->parent.suspend_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} +RTM_EXPORT(rt_mb_urgent); + + +/** + * @brief This function will receive a mail from mailbox object, if there is no mail in mailbox object, + * the thread shall wait for a specified time. + * + * @note Only when there is mail in the mailbox, the receiving thread can get the mail immediately and + * return RT_EOK, otherwise the receiving thread will be suspended until the set timeout. If the mail + * is still not received within the specified time, it will return-RT_ETIMEOUT. + * + * @param mb is a pointer to the mailbox object to be received. + * + * @param value is a flag that you will set for this mailbox's flag. + * You can set an mailbox flag, or you can set multiple flags through OR logic operations. + * + * @param timeout is a timeout period (unit: an OS tick). If the mailbox object is not avaliable in the queue, + * the thread will wait for the object in the queue up to the amount of time specified by this parameter. + * + * NOTE: + * If use Macro RT_WAITING_FOREVER to set this parameter, which means that when the + * mailbox object is unavailable in the queue, the thread will be waiting forever. + * If use macro RT_WAITING_NO to set this parameter, which means that this + * function is non-blocking and will return immediately. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox release failed. + */ +static rt_err_t _rt_mb_recv(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout, int suspend_flag) +{ + struct rt_thread *thread; + rt_base_t level; + rt_uint32_t tick_delta; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0); + + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(mb->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* for non-blocking call */ + if (mb->entry == 0 && timeout == 0) + { + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + + /* mailbox is empty */ + while (mb->entry == 0) + { + /* reset error number in thread */ + thread->error = -RT_EINTR; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + thread->error = -RT_ETIMEOUT; + + return -RT_ETIMEOUT; + } + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mb->parent.suspend_thread), + thread, + mb->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mb_recv: start timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* re-schedule */ + rt_schedule(); + + /* resume from suspend state */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + + /* fill ptr */ + *value = mb->msg_pool[mb->out_offset]; + + /* increase output offset */ + ++ mb->out_offset; + if (mb->out_offset >= mb->size) + mb->out_offset = 0; + + /* decrease message entry */ + if(mb->entry > 0) + { + mb->entry --; + } + + /* resume suspended thread */ + if (!rt_list_isempty(&(mb->suspend_sender_thread))) + { + _ipc_list_resume(&(mb->suspend_sender_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mb->parent.parent))); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mb->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_mb_recv(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout) +{ + return _rt_mb_recv(mb, value, timeout, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mb_recv); + +rt_err_t rt_mb_recv_interruptibale(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout) +{ + return _rt_mb_recv(mb, value, timeout, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mb_recv_interruptibale); + +rt_err_t rt_mb_recv_killable(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout) +{ + return _rt_mb_recv(mb, value, timeout, RT_KILLABLE); +} +RTM_EXPORT(rt_mb_recv_killable); + +/** + * @brief This function will set some extra attributions of a mailbox object. + * + * @note Currently this function only supports the RT_IPC_CMD_RESET command to reset the mailbox. + * + * @param mb is a pointer to a mailbox object. + * + * @param cmd is a command used to configure some attributions of the mailbox. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_mb_control(rt_mailbox_t mb, int cmd, void *arg) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + + if (cmd == RT_IPC_CMD_RESET) + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* resume all waiting thread */ + _ipc_list_resume_all(&(mb->parent.suspend_thread)); + /* also resume all mailbox private suspended thread */ + _ipc_list_resume_all(&(mb->suspend_sender_thread)); + + /* re-init mailbox */ + mb->entry = 0; + mb->in_offset = 0; + mb->out_offset = 0; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_mb_control); + +/**@}*/ +#endif /* RT_USING_MAILBOX */ + +#ifdef RT_USING_MESSAGEQUEUE +/** + * @addtogroup messagequeue + * @{ + */ + +struct rt_mq_message +{ + struct rt_mq_message *next; +}; + + +/** + * @brief Initialize a static messagequeue object. + * + * @note For the static messagequeue object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_mq_create() function will allocate memory space automatically + * and initialize the messagequeue. + * + * @see rt_mq_create() + * + * @param mq is a pointer to the messagequeue to initialize. It is assumed that storage for + * the messagequeue will be allocated in your application. + * + * @param name is a pointer to the name that given to the messagequeue. + * + * @param msgpool is a pointer to the starting address of the memory space you allocated for + * the messagequeue in advance. + * In other words, msgpool is a pointer to the messagequeue buffer of the starting address. + * + * @param msg_size is the maximum length of a message in the messagequeue (Unit: Byte). + * + * @param pool_size is the size of the memory space allocated for the messagequeue in advance. + * + * @param flag is the messagequeue flag, which determines the queuing way of how multiple threads wait + * when the messagequeue is not available. + * The messagequeue flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this messagequeue will become non-real-time threads. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_mq_init(rt_mq_t mq, + const char *name, + void *msgpool, + rt_size_t msg_size, + rt_size_t pool_size, + rt_uint8_t flag) +{ + struct rt_mq_message *head; + rt_base_t temp; + register rt_size_t msg_align_size; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(mq->parent.parent), RT_Object_Class_MessageQueue, name); + + /* set parent flag */ + mq->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(mq->parent)); + + /* set message pool */ + mq->msg_pool = msgpool; + + /* get correct message size */ + msg_align_size = RT_ALIGN(msg_size, RT_ALIGN_SIZE); + mq->msg_size = msg_size; + mq->max_msgs = pool_size / (msg_align_size + sizeof(struct rt_mq_message)); + + if (0 == mq->max_msgs) + { + return -RT_EINVAL; + } + + /* initialize message list */ + mq->msg_queue_head = RT_NULL; + mq->msg_queue_tail = RT_NULL; + + /* initialize message empty list */ + mq->msg_queue_free = RT_NULL; + for (temp = 0; temp < mq->max_msgs; temp ++) + { + head = (struct rt_mq_message *)((rt_uint8_t *)mq->msg_pool + + temp * (msg_align_size + sizeof(struct rt_mq_message))); + head->next = (struct rt_mq_message *)mq->msg_queue_free; + mq->msg_queue_free = head; + } + + /* the initial entry is zero */ + mq->entry = 0; + + /* initialize an additional list of sender suspend thread */ + rt_list_init(&(mq->suspend_sender_thread)); + + return RT_EOK; +} +RTM_EXPORT(rt_mq_init); + + +/** + * @brief This function will detach a static messagequeue object. + * + * @note This function is used to detach a static messagequeue object which is initialized by rt_mq_init() function. + * By contrast, the rt_mq_delete() function will delete a messagequeue object. + * When the messagequeue is successfully detached, it will resume all suspended threads in the messagequeue list. + * + * @see rt_mq_delete() + * + * @param mq is a pointer to a messagequeue object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the messagequeue detach failed. + * + * @warning This function can ONLY detach a static messagequeue initialized by the rt_mq_init() function. + * If the messagequeue is created by the rt_mq_create() function, you MUST NOT USE this function to detach it, + * and ONLY USE the rt_mq_delete() function to complete the deletion. + */ +rt_err_t rt_mq_detach(rt_mq_t mq) +{ + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(rt_object_is_systemobject(&mq->parent.parent)); + + /* resume all suspended thread */ + _ipc_list_resume_all(&mq->parent.suspend_thread); + /* also resume all message queue private suspended thread */ + _ipc_list_resume_all(&(mq->suspend_sender_thread)); + + /* detach message queue object */ + rt_object_detach(&(mq->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mq_detach); + +#ifdef RT_USING_HEAP +/** + * @brief Creating a messagequeue object. + * + * @note For the messagequeue object, its memory space is allocated automatically. + * By contrast, the rt_mq_init() function will initialize a static messagequeue object. + * + * @see rt_mq_init() + * + * @param name is a pointer that given to the messagequeue. + * + * @param msg_size is the maximum length of a message in the messagequeue (Unit: Byte). + * + * @param max_msgs is the maximum number of messages in the messagequeue. + * + * @param flag is the messagequeue flag, which determines the queuing way of how multiple threads wait + * when the messagequeue is not available. + * The messagequeue flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this messagequeue will become non-real-time threads. + * + * @return Return a pointer to the messagequeue object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can NOT be called in interrupt context. You can use macor RT_DEBUG_NOT_IN_INTERRUPT to check it. + */ +rt_mq_t rt_mq_create(const char *name, + rt_size_t msg_size, + rt_size_t max_msgs, + rt_uint8_t flag) +{ + struct rt_messagequeue *mq; + struct rt_mq_message *head; + rt_base_t temp; + register rt_size_t msg_align_size; + + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + mq = (rt_mq_t)rt_object_allocate(RT_Object_Class_MessageQueue, name); + if (mq == RT_NULL) + return mq; + + /* set parent */ + mq->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(mq->parent)); + + /* initialize message queue */ + + /* get correct message size */ + msg_align_size = RT_ALIGN(msg_size, RT_ALIGN_SIZE); + mq->msg_size = msg_size; + mq->max_msgs = max_msgs; + + /* allocate message pool */ + mq->msg_pool = RT_KERNEL_MALLOC((msg_align_size + sizeof(struct rt_mq_message)) * mq->max_msgs); + if (mq->msg_pool == RT_NULL) + { + rt_object_delete(&(mq->parent.parent)); + + return RT_NULL; + } + + /* initialize message list */ + mq->msg_queue_head = RT_NULL; + mq->msg_queue_tail = RT_NULL; + + /* initialize message empty list */ + mq->msg_queue_free = RT_NULL; + for (temp = 0; temp < mq->max_msgs; temp ++) + { + head = (struct rt_mq_message *)((rt_uint8_t *)mq->msg_pool + + temp * (msg_align_size + sizeof(struct rt_mq_message))); + head->next = (struct rt_mq_message *)mq->msg_queue_free; + mq->msg_queue_free = head; + } + + /* the initial entry is zero */ + mq->entry = 0; + + /* initialize an additional list of sender suspend thread */ + rt_list_init(&(mq->suspend_sender_thread)); + + return mq; +} +RTM_EXPORT(rt_mq_create); + + +/** + * @brief This function will delete a messagequeue object and release the memory. + * + * @note This function is used to delete a messagequeue object which is created by the rt_mq_create() function. + * By contrast, the rt_mq_detach() function will detach a static messagequeue object. + * When the messagequeue is successfully deleted, it will resume all suspended threads in the messagequeue list. + * + * @see rt_mq_detach() + * + * @param mq is a pointer to a messagequeue object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the messagequeue detach failed. + * + * @warning This function can ONLY delete a messagequeue initialized by the rt_mq_create() function. + * If the messagequeue is initialized by the rt_mq_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_mq_detach() function to complete the detachment. + * for example,the rt_mq_create() function, it cannot be called in interrupt context. + */ +rt_err_t rt_mq_delete(rt_mq_t mq) +{ + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(rt_object_is_systemobject(&mq->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* resume all suspended thread */ + _ipc_list_resume_all(&(mq->parent.suspend_thread)); + /* also resume all message queue private suspended thread */ + _ipc_list_resume_all(&(mq->suspend_sender_thread)); + + /* free message queue pool */ + RT_KERNEL_FREE(mq->msg_pool); + + /* delete message queue object */ + rt_object_delete(&(mq->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mq_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will send a message to the messagequeue object. If + * there is a thread suspended on the messagequeue, the thread will be + * resumed. + * + * @note When using this function to send a message, if the messagequeue is + * fully used, the current thread will wait for a timeout. If reaching + * the timeout and there is still no space available, the sending + * thread will be resumed and an error code will be returned. By + * contrast, the rt_mq_send() function will return an error code + * immediately without waiting when the messagequeue if fully used. + * + * @see rt_mq_send() + * + * @param mq is a pointer to the messagequeue object to be sent. + * + * @param buffer is the content of the message. + * + * @param size is the length of the message(Unit: Byte). + * + * @param timeout is a timeout period (unit: an OS tick). + * + * @return Return the operation status. When the return value is RT_EOK, the + * operation is successful. If the return value is any other values, + * it means that the messagequeue detach failed. + * + * @warning This function can be called in interrupt context and thread + * context. + */ +static rt_err_t _rt_mq_send_wait(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout, + int suspend_flag) +{ + rt_base_t level; + struct rt_mq_message *msg; + rt_uint32_t tick_delta; + struct rt_thread *thread; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(buffer != RT_NULL); + RT_ASSERT(size != 0); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0); + + /* greater than one message size */ + if (size > mq->msg_size) + return -RT_ERROR; + + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mq->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* get a free list, there must be an empty item */ + msg = (struct rt_mq_message *)mq->msg_queue_free; + /* for non-blocking call */ + if (msg == RT_NULL && timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EFULL; + } + + /* message queue is full */ + while ((msg = (struct rt_mq_message *)mq->msg_queue_free) == RT_NULL) + { + /* reset error number in thread */ + thread->error = -RT_EINTR; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EFULL; + } + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mq->suspend_sender_thread), + thread, + mq->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mq_send_wait: start timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* re-schedule */ + rt_schedule(); + + /* resume from suspend state */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + + /* move free list pointer */ + mq->msg_queue_free = msg->next; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* the msg is the new tailer of list, the next shall be NULL */ + msg->next = RT_NULL; + /* copy buffer */ + rt_memcpy(msg + 1, buffer, size); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + /* link msg to message queue */ + if (mq->msg_queue_tail != RT_NULL) + { + /* if the tail exists, */ + ((struct rt_mq_message *)mq->msg_queue_tail)->next = msg; + } + + /* set new tail */ + mq->msg_queue_tail = msg; + /* if the head is empty, set head */ + if (mq->msg_queue_head == RT_NULL) + mq->msg_queue_head = msg; + + if(mq->entry < RT_MQ_ENTRY_MAX) + { + /* increase message entry */ + mq->entry ++; + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + + /* resume suspended thread */ + if (!rt_list_isempty(&mq->parent.suspend_thread)) + { + _ipc_list_resume(&(mq->parent.suspend_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} + +rt_err_t rt_mq_send_wait(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_send_wait(mq, buffer, size, timeout, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mq_send_wait) + +rt_err_t rt_mq_send_wait_interruptible(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_send_wait(mq, buffer, size, timeout, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mq_send_wait_interruptible) + +rt_err_t rt_mq_send_wait_killable(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_send_wait(mq, buffer, size, timeout, RT_KILLABLE); +} +RTM_EXPORT(rt_mq_send_wait_killable) +/** + * @brief This function will send a message to the messagequeue object. + * If there is a thread suspended on the messagequeue, the thread will be resumed. + * + * @note When using this function to send a message, if the messagequeue is fully used, + * the current thread will wait for a timeout. + * By contrast, when the messagequeue is fully used, the rt_mq_send_wait() function will + * return an error code immediately without waiting. + * + * @see rt_mq_send_wait() + * + * @param mq is a pointer to the messagequeue object to be sent. + * + * @param buffer is the content of the message. + * + * @param size is the length of the message(Unit: Byte). + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the messagequeue detach failed. + * + * @warning This function can be called in interrupt context and thread context. + */ +rt_err_t rt_mq_send(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + return rt_mq_send_wait(mq, buffer, size, 0); +} +RTM_EXPORT(rt_mq_send); + +rt_err_t rt_mq_send_interrupt(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + return rt_mq_send_wait_interruptible(mq, buffer, size, 0); +} +RTM_EXPORT(rt_mq_send_interrupt); + +rt_err_t rt_mq_send_killable(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + return rt_mq_send_wait_killable(mq, buffer, size, 0); +} +RTM_EXPORT(rt_mq_send_killable); +/** + * @brief This function will send an urgent message to the messagequeue object. + * + * @note This function is almost the same as the rt_mq_send() function. The only difference is that + * when sending an urgent message, the message is placed at the head of the messagequeue so that + * the recipient can receive the urgent message first. + * + * @see rt_mq_send() + * + * @param mq is a pointer to the messagequeue object to be sent. + * + * @param buffer is the content of the message. + * + * @param size is the length of the message(Unit: Byte). + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + */ +rt_err_t rt_mq_urgent(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + rt_base_t level; + struct rt_mq_message *msg; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(buffer != RT_NULL); + RT_ASSERT(size != 0); + + /* greater than one message size */ + if (size > mq->msg_size) + return -RT_ERROR; + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mq->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* get a free list, there must be an empty item */ + msg = (struct rt_mq_message *)mq->msg_queue_free; + /* message queue is full */ + if (msg == RT_NULL) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EFULL; + } + /* move free list pointer */ + mq->msg_queue_free = msg->next; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* copy buffer */ + rt_memcpy(msg + 1, buffer, size); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* link msg to the beginning of message queue */ + msg->next = (struct rt_mq_message *)mq->msg_queue_head; + mq->msg_queue_head = msg; + + /* if there is no tail */ + if (mq->msg_queue_tail == RT_NULL) + mq->msg_queue_tail = msg; + + if(mq->entry < RT_MQ_ENTRY_MAX) + { + /* increase message entry */ + mq->entry ++; + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + + /* resume suspended thread */ + if (!rt_list_isempty(&mq->parent.suspend_thread)) + { + _ipc_list_resume(&(mq->parent.suspend_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} +RTM_EXPORT(rt_mq_urgent); + + +/** + * @brief This function will receive a message from message queue object, + * if there is no message in messagequeue object, the thread shall wait for a specified time. + * + * @note Only when there is mail in the mailbox, the receiving thread can get the mail immediately and return RT_EOK, + * otherwise the receiving thread will be suspended until timeout. + * If the mail is not received within the specified time, it will return -RT_ETIMEOUT. + * + * @param mq is a pointer to the messagequeue object to be received. + * + * @param buffer is the content of the message. + * + * @param size is the length of the message(Unit: Byte). + * + * @param timeout is a timeout period (unit: an OS tick). If the message is unavailable, the thread will wait for + * the message in the queue up to the amount of time specified by this parameter. + * + * NOTE: + * If use Macro RT_WAITING_FOREVER to set this parameter, which means that when the + * message is unavailable in the queue, the thread will be waiting forever. + * If use macro RT_WAITING_NO to set this parameter, which means that this + * function is non-blocking and will return immediately. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox release failed. + */ +static rt_err_t _rt_mq_recv(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout, + int suspend_flag) +{ + struct rt_thread *thread; + rt_base_t level; + struct rt_mq_message *msg; + rt_uint32_t tick_delta; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(buffer != RT_NULL); + RT_ASSERT(size != 0); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0); + + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(mq->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* for non-blocking call */ + if (mq->entry == 0 && timeout == 0) + { + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + + /* message queue is empty */ + while (mq->entry == 0) + { + /* reset error number in thread */ + thread->error = -RT_EINTR; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + thread->error = -RT_ETIMEOUT; + + return -RT_ETIMEOUT; + } + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mq->parent.suspend_thread), + thread, + mq->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("set thread:%s to timer list\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* re-schedule */ + rt_schedule(); + + /* recv message */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + + /* get message from queue */ + msg = (struct rt_mq_message *)mq->msg_queue_head; + + /* move message queue head */ + mq->msg_queue_head = msg->next; + /* reach queue tail, set to NULL */ + if (mq->msg_queue_tail == msg) + mq->msg_queue_tail = RT_NULL; + + /* decrease message entry */ + if(mq->entry > 0) + { + mq->entry --; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* copy message */ + rt_memcpy(buffer, msg + 1, size > mq->msg_size ? mq->msg_size : size); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + /* put message to free list */ + msg->next = (struct rt_mq_message *)mq->msg_queue_free; + mq->msg_queue_free = msg; + + /* resume suspended thread */ + if (!rt_list_isempty(&(mq->suspend_sender_thread))) + { + _ipc_list_resume(&(mq->suspend_sender_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mq->parent.parent))); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mq->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_mq_recv(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_recv(mq, buffer, size, timeout, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mq_recv); + +rt_err_t rt_mq_recv_interruptible(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_recv(mq, buffer, size, timeout, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mq_recv_interruptible); + +rt_err_t rt_mq_recv_killable(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_recv(mq, buffer, size, timeout, RT_KILLABLE); +} +RTM_EXPORT(rt_mq_recv_killable); +/** + * @brief This function will set some extra attributions of a messagequeue object. + * + * @note Currently this function only supports the RT_IPC_CMD_RESET command to reset the messagequeue. + * + * @param mq is a pointer to a messagequeue object. + * + * @param cmd is a command used to configure some attributions of the messagequeue. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_mq_control(rt_mq_t mq, int cmd, void *arg) +{ + rt_base_t level; + struct rt_mq_message *msg; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + + if (cmd == RT_IPC_CMD_RESET) + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* resume all waiting thread */ + _ipc_list_resume_all(&mq->parent.suspend_thread); + /* also resume all message queue private suspended thread */ + _ipc_list_resume_all(&(mq->suspend_sender_thread)); + + /* release all message in the queue */ + while (mq->msg_queue_head != RT_NULL) + { + /* get message from queue */ + msg = (struct rt_mq_message *)mq->msg_queue_head; + + /* move message queue head */ + mq->msg_queue_head = msg->next; + /* reach queue tail, set to NULL */ + if (mq->msg_queue_tail == msg) + mq->msg_queue_tail = RT_NULL; + + /* put message to free list */ + msg->next = (struct rt_mq_message *)mq->msg_queue_free; + mq->msg_queue_free = msg; + } + + /* clean entry */ + mq->entry = 0; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_mq_control); + +/**@}*/ +#endif /* RT_USING_MESSAGEQUEUE */ +/**@}*/ diff --git a/tasks/concur-rtthread-mutex-ceilings/partial_update/src/ipc.c b/tasks/concur-rtthread-mutex-ceilings/partial_update/src/ipc.c new file mode 100644 index 00000000..f7a7a81b --- /dev/null +++ b/tasks/concur-rtthread-mutex-ceilings/partial_update/src/ipc.c @@ -0,0 +1,3745 @@ +/* + * Copyright (c) 2006-2022, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +#include +#include + +#ifndef __on_rt_object_trytake_hook + #define __on_rt_object_trytake_hook(parent) __ON_HOOK_ARGS(rt_object_trytake_hook, (parent)) +#endif +#ifndef __on_rt_object_take_hook + #define __on_rt_object_take_hook(parent) __ON_HOOK_ARGS(rt_object_take_hook, (parent)) +#endif +#ifndef __on_rt_object_put_hook + #define __on_rt_object_put_hook(parent) __ON_HOOK_ARGS(rt_object_put_hook, (parent)) +#endif + +#if defined(RT_USING_HOOK) && defined(RT_HOOK_USING_FUNC_PTR) +extern void (*rt_object_trytake_hook)(struct rt_object *object); +extern void (*rt_object_take_hook)(struct rt_object *object); +extern void (*rt_object_put_hook)(struct rt_object *object); +#endif /* RT_USING_HOOK */ + +/** + * @addtogroup IPC + * @{ + */ + +/** + * @brief This function will initialize an IPC object, such as semaphore, mutex, messagequeue and mailbox. + * + * @note Executing this function will complete an initialization of the suspend thread list of the ipc object. + * + * @param ipc is a pointer to the IPC object. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * When the return value is any other values, it means the initialization failed. + * + * @warning This function can be called from all IPC initialization and creation. + */ +rt_inline rt_err_t _ipc_object_init(struct rt_ipc_object *ipc) +{ + /* initialize ipc object */ + rt_list_init(&(ipc->suspend_thread)); + + return RT_EOK; +} + + +/** + * @brief This function will suspend a thread to a IPC object list. + * + * @param list is a pointer to a suspended thread list of the IPC object. + * + * @param thread is a pointer to the thread object to be suspended. + * + * @param flag is a flag for the thread object to be suspended. It determines how the thread is suspended. + * The flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to use + * RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this semaphore will become non-real-time threads. + * + * @param suspend_flag status flag of the thread to be suspended. + * + * @return Return the operation status. When the return value is RT_EOK, the function is successfully executed. + * When the return value is any other values, it means the initialization failed. + * + * @warning This function can ONLY be called in the thread context, you can use RT_DEBUG_IN_THREAD_CONTEXT to + * check the context. + * In addition, this function is generally called by the following functions: + * rt_sem_take(), rt_mutex_take(), rt_event_recv(), rt_mb_send_wait(), + * rt_mb_recv(), rt_mq_recv(), rt_mq_send_wait() + */ +rt_inline rt_err_t _ipc_list_suspend(rt_list_t *list, + struct rt_thread *thread, + rt_uint8_t flag, + int suspend_flag) +{ + if ((thread->stat & RT_THREAD_SUSPEND_MASK) != RT_THREAD_SUSPEND_MASK) + { + rt_err_t ret = rt_thread_suspend_with_flag(thread, suspend_flag); + + /* suspend thread */ + if (ret != RT_EOK) + { + return ret; + } + } + + switch (flag) + { + case RT_IPC_FLAG_FIFO: + rt_list_insert_before(list, &(thread->tlist)); + break; /* RT_IPC_FLAG_FIFO */ + + case RT_IPC_FLAG_PRIO: + { + struct rt_list_node *n; + struct rt_thread *sthread; + + /* find a suitable position */ + for (n = list->next; n != list; n = n->next) + { + sthread = rt_list_entry(n, struct rt_thread, tlist); + + /* find out */ + if (thread->current_priority < sthread->current_priority) + { + /* insert this thread before the sthread */ + rt_list_insert_before(&(sthread->tlist), &(thread->tlist)); + break; + } + } + + /* + * not found a suitable position, + * append to the end of suspend_thread list + */ + if (n == list) + rt_list_insert_before(list, &(thread->tlist)); + } + break;/* RT_IPC_FLAG_PRIO */ + + default: + RT_ASSERT(0); + break; + } + + return RT_EOK; +} + + +/** + * @brief This function will resume a thread. + * + * @note This function will resume the first thread in the list of a IPC object. + * 1. remove the thread from suspend queue of a IPC object. + * 2. put the thread into system ready queue. + * + * By contrast, the rt_ipc_list_resume_all() function will resume all suspended threads + * in the list of a IPC object. + * + * @param list is a pointer to a suspended thread list of the IPC object. + * + * @return Return the operation status. When the return value is RT_EOK, the function is successfully executed. + * When the return value is any other values, it means this operation failed. + * + * @warning This function is generally called by the following functions: + * rt_sem_release(), rt_mutex_release(), rt_mb_send_wait(), rt_mq_send_wait(), + * rt_mb_urgent(), rt_mb_recv(), rt_mq_urgent(), rt_mq_recv(), + */ +rt_inline rt_err_t _ipc_list_resume(rt_list_t *list) +{ + struct rt_thread *thread; + + /* get thread entry */ + thread = rt_list_entry(list->next, struct rt_thread, tlist); + + thread->error = RT_EOK; + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("resume thread:%s\n", thread->name)); + + /* resume it */ + rt_thread_resume(thread); + + return RT_EOK; +} + + +/** + * @brief This function will resume all suspended threads in the IPC object list, + * including the suspended list of IPC object, and private list of mailbox etc. + * + * @note This function will resume all threads in the IPC object list. + * By contrast, the rt_ipc_list_resume() function will resume a suspended thread in the list of a IPC object. + * + * @param list is a pointer to a suspended thread list of the IPC object. + * + * @return Return the operation status. When the return value is RT_EOK, the function is successfully executed. + * When the return value is any other values, it means this operation failed. + * + */ +rt_inline rt_err_t _ipc_list_resume_all(rt_list_t *list) +{ + struct rt_thread *thread; + rt_base_t level; + + /* wakeup all suspended threads */ + while (!rt_list_isempty(list)) + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* get next suspended thread */ + thread = rt_list_entry(list->next, struct rt_thread, tlist); + /* set error code to RT_ERROR */ + thread->error = -RT_ERROR; + + /* + * resume thread + * In rt_thread_resume function, it will remove current thread from + * suspended list + */ + rt_thread_resume(thread); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + } + + return RT_EOK; +} + +#ifdef RT_USING_SEMAPHORE +/** + * @addtogroup semaphore + * @{ + */ + +/** + * @brief This function will initialize a static semaphore object. + * + * @note For the static semaphore object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_sem_create() function will allocate memory space automatically and initialize + * the semaphore. + * + * @see rt_sem_create() + * + * @param sem is a pointer to the semaphore to initialize. It is assumed that storage for the semaphore will be + * allocated in your application. + * + * @param name is a pointer to the name you would like to give the semaphore. + * + * @param value is the initial value for the semaphore. + * If used to share resources, you should initialize the value as the number of available resources. + * If used to signal the occurrence of an event, you should initialize the value as 0. + * + * @param flag is the semaphore flag, which determines the queuing way of how multiple threads wait + * when the semaphore is not available. + * The semaphore flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this semaphore will become non-real-time threads. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_sem_init(rt_sem_t sem, + const char *name, + rt_uint32_t value, + rt_uint8_t flag) +{ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(value < 0x10000U); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(sem->parent.parent), RT_Object_Class_Semaphore, name); + + /* initialize ipc object */ + _ipc_object_init(&(sem->parent)); + + /* set initial value */ + sem->value = (rt_uint16_t)value; + + /* set parent */ + sem->parent.parent.flag = flag; + + return RT_EOK; +} +RTM_EXPORT(rt_sem_init); + + +/** + * @brief This function will detach a static semaphore object. + * + * @note This function is used to detach a static semaphore object which is initialized by rt_sem_init() function. + * By contrast, the rt_sem_delete() function will delete a semaphore object. + * When the semaphore is successfully detached, it will resume all suspended threads in the semaphore list. + * + * @see rt_sem_delete() + * + * @param sem is a pointer to a semaphore object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the semaphore detach failed. + * + * @warning This function can ONLY detach a static semaphore initialized by the rt_sem_init() function. + * If the semaphore is created by the rt_sem_create() function, you MUST NOT USE this function to detach it, + * ONLY USE the rt_sem_delete() function to complete the deletion. + */ +rt_err_t rt_sem_detach(rt_sem_t sem) +{ + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + RT_ASSERT(rt_object_is_systemobject(&sem->parent.parent)); + + /* wakeup all suspended threads */ + _ipc_list_resume_all(&(sem->parent.suspend_thread)); + + /* detach semaphore object */ + rt_object_detach(&(sem->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_sem_detach); + +#ifdef RT_USING_HEAP +/** + * @brief Creating a semaphore object. + * + * @note For the semaphore object, its memory space is allocated automatically. + * By contrast, the rt_sem_init() function will initialize a static semaphore object. + * + * @see rt_sem_init() + * + * @param name is a pointer to the name you would like to give the semaphore. + * + * @param value is the initial value for the semaphore. + * If used to share resources, you should initialize the value as the number of available resources. + * If used to signal the occurrence of an event, you should initialize the value as 0. + * + * @param flag is the semaphore flag, which determines the queuing way of how multiple threads wait + * when the semaphore is not available. + * The semaphore flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this semaphore will become non-real-time threads. + * + * @return Return a pointer to the semaphore object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can NOT be called in interrupt context. You can use macor RT_DEBUG_NOT_IN_INTERRUPT to check it. + */ +rt_sem_t rt_sem_create(const char *name, rt_uint32_t value, rt_uint8_t flag) +{ + rt_sem_t sem; + + RT_ASSERT(value < 0x10000U); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + sem = (rt_sem_t)rt_object_allocate(RT_Object_Class_Semaphore, name); + if (sem == RT_NULL) + return sem; + + /* initialize ipc object */ + _ipc_object_init(&(sem->parent)); + + /* set initial value */ + sem->value = value; + + /* set parent */ + sem->parent.parent.flag = flag; + + return sem; +} +RTM_EXPORT(rt_sem_create); + + +/** + * @brief This function will delete a semaphore object and release the memory space. + * + * @note This function is used to delete a semaphore object which is created by the rt_sem_create() function. + * By contrast, the rt_sem_detach() function will detach a static semaphore object. + * When the semaphore is successfully deleted, it will resume all suspended threads in the semaphore list. + * + * @see rt_sem_detach() + * + * @param sem is a pointer to a semaphore object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the semaphore detach failed. + * + * @warning This function can ONLY delete a semaphore initialized by the rt_sem_create() function. + * If the semaphore is initialized by the rt_sem_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_sem_detach() function to complete the detachment. + */ +rt_err_t rt_sem_delete(rt_sem_t sem) +{ + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + RT_ASSERT(rt_object_is_systemobject(&sem->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* wakeup all suspended threads */ + _ipc_list_resume_all(&(sem->parent.suspend_thread)); + + /* delete semaphore object */ + rt_object_delete(&(sem->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_sem_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will take a semaphore, if the semaphore is unavailable, the thread shall wait for + * the semaphore up to a specified time. + * + * @note When this function is called, the count value of the sem->value will decrease 1 until it is equal to 0. + * When the sem->value is 0, it means that the semaphore is unavailable. At this time, it will suspend the + * thread preparing to take the semaphore. + * On the contrary, the rt_sem_release() function will increase the count value of sem->value by 1 each time. + * + * @see rt_sem_trytake() + * + * @param sem is a pointer to a semaphore object. + * + * @param timeout is a timeout period (unit: an OS tick). If the semaphore is unavailable, the thread will wait for + * the semaphore up to the amount of time specified by this parameter. + * + * NOTE: + * If use Macro RT_WAITING_FOREVER to set this parameter, which means that when the + * message is unavailable in the queue, the thread will be waiting forever. + * If use macro RT_WAITING_NO to set this parameter, which means that this + * function is non-blocking and will return immediately. + * + * @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 semaphore take failed. + * + * @warning This function can ONLY be called in the thread context. It MUST NOT BE called in interrupt context. + */ +static rt_err_t _rt_sem_take(rt_sem_t sem, rt_int32_t timeout, int suspend_flag) +{ + rt_base_t level; + struct rt_thread *thread; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(sem->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("thread %s take sem:%s, which value is: %d\n", + rt_thread_self()->name, + ((struct rt_object *)sem)->name, + sem->value)); + + if (sem->value > 0) + { + /* semaphore is available */ + sem->value --; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + } + else + { + /* no waiting, return with timeout */ + if (timeout == 0) + { + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + else + { + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE); + + /* semaphore is unavailable, push to suspend list */ + /* get current thread */ + thread = rt_thread_self(); + + /* reset thread error number */ + thread->error = -RT_EINTR; + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("sem take: suspend thread - %s\n", + thread->name)); + + /* suspend thread */ + ret = _ipc_list_suspend(&(sem->parent.suspend_thread), + thread, + sem->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + RT_DEBUG_LOG(RT_DEBUG_IPC, ("set thread:%s to timer list\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do schedule */ + rt_schedule(); + + if (thread->error != RT_EOK) + { + return thread->error; + } + } + } + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(sem->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_sem_take(rt_sem_t sem, rt_int32_t time) +{ + return _rt_sem_take(sem, time, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_sem_take); + +rt_err_t rt_sem_take_interruptible(rt_sem_t sem, rt_int32_t time) +{ + return _rt_sem_take(sem, time, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_sem_take_interruptible); + +rt_err_t rt_sem_take_killable(rt_sem_t sem, rt_int32_t time) +{ + return _rt_sem_take(sem, time, RT_KILLABLE); +} +RTM_EXPORT(rt_sem_take_killable); + +/** + * @brief This function will try to take a semaphore, if the semaphore is unavailable, the thread returns immediately. + * + * @note This function is very similar to the rt_sem_take() function, when the semaphore is not available, + * the rt_sem_trytake() function will return immediately without waiting for a timeout. + * In other words, rt_sem_trytake(sem) has the same effect as rt_sem_take(sem, 0). + * + * @see rt_sem_take() + * + * @param sem is a pointer to a semaphore object. + * + * @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 semaphore take failed. + */ +rt_err_t rt_sem_trytake(rt_sem_t sem) +{ + return rt_sem_take(sem, RT_WAITING_NO); +} +RTM_EXPORT(rt_sem_trytake); + + +/** + * @brief This function will release a semaphore. If there is thread suspended on the semaphore, it will get resumed. + * + * @note If there are threads suspended on this semaphore, the first thread in the list of this semaphore object + * will be resumed, and a thread scheduling (rt_schedule) will be executed. + * If no threads are suspended on this semaphore, the count value sem->value of this semaphore will increase by 1. + * + * @param sem is a pointer to a semaphore object. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the semaphore release failed. + */ +rt_err_t rt_sem_release(rt_sem_t sem) +{ + rt_base_t level; + rt_bool_t need_schedule; + + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(sem->parent.parent))); + + need_schedule = RT_FALSE; + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("thread %s releases sem:%s, which value is: %d\n", + rt_thread_self()->name, + ((struct rt_object *)sem)->name, + sem->value)); + + if (!rt_list_isempty(&sem->parent.suspend_thread)) + { + /* resume the suspended thread */ + _ipc_list_resume(&(sem->parent.suspend_thread)); + need_schedule = RT_TRUE; + } + else + { + if(sem->value < RT_SEM_VALUE_MAX) + { + sem->value ++; /* increase value */ + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* resume a thread, re-schedule */ + if (need_schedule == RT_TRUE) + rt_schedule(); + + return RT_EOK; +} +RTM_EXPORT(rt_sem_release); + + +/** + * @brief This function will set some extra attributions of a semaphore object. + * + * @note Currently this function only supports the RT_IPC_CMD_RESET command to reset the semaphore. + * + * @param sem is a pointer to a semaphore object. + * + * @param cmd is a command word used to configure some attributions of the semaphore. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_sem_control(rt_sem_t sem, int cmd, void *arg) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + + if (cmd == RT_IPC_CMD_RESET) + { + rt_ubase_t value; + + /* get value */ + value = (rt_ubase_t)arg; + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* resume all waiting thread */ + _ipc_list_resume_all(&sem->parent.suspend_thread); + + /* set new value */ + sem->value = (rt_uint16_t)value; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_sem_control); + +/**@}*/ +#endif /* RT_USING_SEMAPHORE */ + +#ifdef RT_USING_MUTEX +/* iterate over each suspended thread to update highest priority in pending threads */ +rt_inline rt_uint8_t _mutex_update_priority(struct rt_mutex *mutex) +{ + struct rt_thread *thread; + + if (!rt_list_isempty(&mutex->parent.suspend_thread)) + { + thread = rt_list_entry(mutex->parent.suspend_thread.next, struct rt_thread, tlist); + mutex->priority = thread->current_priority; + } + else + { + mutex->priority = 0xff; + } + + return mutex->priority; +} + +/* get highest priority inside its taken object and its init priority */ +rt_inline rt_uint8_t _thread_get_mutex_priority(struct rt_thread* thread) +{ + rt_list_t *node = RT_NULL; + struct rt_mutex *mutex = RT_NULL; + rt_uint8_t priority = thread->init_priority; + + rt_list_for_each(node, &(thread->taken_object_list)) + { + mutex = rt_list_entry(node, struct rt_mutex, taken_list); + rt_uint8_t mutex_prio = mutex->priority; + /* prio at least be priority ceiling */ + mutex_prio = mutex_prio < mutex->ceiling_priority ? mutex_prio : mutex->ceiling_priority; + + if (priority > mutex_prio) + { + priority = mutex_prio; + } + } + + return priority; +} + +/* update priority of target thread and the thread suspended it if any */ +rt_inline void _thread_update_priority(struct rt_thread *thread, rt_uint8_t priority, int suspend_flag) +{ + rt_err_t ret; + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("thread:%s priority -> %d\n", thread->name, priority)); + + /* change priority of the thread */ + rt_thread_control(thread, + RT_THREAD_CTRL_CHANGE_PRIORITY, + &priority); + + if ((thread->stat & RT_THREAD_SUSPEND_MASK) == RT_THREAD_SUSPEND_MASK) + { + /* whether change the priority of taken mutex */ + struct rt_object* pending_obj = thread->pending_object; + + if (pending_obj && rt_object_get_type(pending_obj) == RT_Object_Class_Mutex) + { + rt_uint8_t mutex_priority; + struct rt_mutex* pending_mutex = (struct rt_mutex *)pending_obj; + + /* re-insert thread to suspended thread list */ + rt_list_remove(&(thread->tlist)); + + ret = _ipc_list_suspend(&(pending_mutex->parent.suspend_thread), + thread, + pending_mutex->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + /* TODO */ + return ; + } + + /* update priority */ + _mutex_update_priority(pending_mutex); + /* change the priority of mutex owner thread */ + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("mutex: %s priority -> %d\n", pending_mutex->parent.parent.name, + pending_mutex->priority)); + + mutex_priority = _thread_get_mutex_priority(pending_mutex->owner); + if (mutex_priority != pending_mutex->owner->current_priority) + { + _thread_update_priority(pending_mutex->owner, mutex_priority, suspend_flag); + } + } + } +} + +/** + * @addtogroup mutex + * @{ + */ + +/** + * @brief Initialize a static mutex object. + * + * @note For the static mutex object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_mutex_create() function will automatically allocate memory space + * and initialize the mutex. + * + * @see rt_mutex_create() + * + * @param mutex is a pointer to the mutex to initialize. It is assumed that storage for the mutex will be + * allocated in your application. + * + * @param name is a pointer to the name that given to the mutex. + * + * @param flag is the mutex flag, which determines the queuing way of how multiple threads wait + * when the mutex is not available. + * NOTE: This parameter has been obsoleted. It can be RT_IPC_FLAG_PRIO, RT_IPC_FLAG_FIFO or RT_NULL. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_mutex_init(rt_mutex_t mutex, const char *name, rt_uint8_t flag) +{ + /* flag parameter has been obsoleted */ + RT_UNUSED(flag); + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + + /* initialize object */ + rt_object_init(&(mutex->parent.parent), RT_Object_Class_Mutex, name); + + /* initialize ipc object */ + _ipc_object_init(&(mutex->parent)); + + mutex->owner = RT_NULL; + mutex->priority = 0xFF; + mutex->hold = 0; + mutex->ceiling_priority = 0xFF; + rt_list_init(&(mutex->taken_list)); + + /* flag can only be RT_IPC_FLAG_PRIO. RT_IPC_FLAG_FIFO cannot solve the unbounded priority inversion problem */ + mutex->parent.parent.flag = RT_IPC_FLAG_PRIO; + + return RT_EOK; +} +RTM_EXPORT(rt_mutex_init); + + +/** + * @brief This function will detach a static mutex object. + * + * @note This function is used to detach a static mutex object which is initialized by rt_mutex_init() function. + * By contrast, the rt_mutex_delete() function will delete a mutex object. + * When the mutex is successfully detached, it will resume all suspended threads in the mutex list. + * + * @see rt_mutex_delete() + * + * @param mutex is a pointer to a mutex object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the mutex detach failed. + * + * @warning This function can ONLY detach a static mutex initialized by the rt_mutex_init() function. + * If the mutex is created by the rt_mutex_create() function, you MUST NOT USE this function to detach it, + * ONLY USE the rt_mutex_delete() function to complete the deletion. + */ +rt_err_t rt_mutex_detach(rt_mutex_t mutex) +{ + rt_ubase_t level; + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + RT_ASSERT(rt_object_is_systemobject(&mutex->parent.parent)); + + level = rt_hw_interrupt_disable(); + /* wakeup all suspended threads */ + _ipc_list_resume_all(&(mutex->parent.suspend_thread)); + /* remove mutex from thread's taken list */ + rt_list_remove(&mutex->taken_list); + rt_hw_interrupt_enable(level); + + /* detach mutex object */ + rt_object_detach(&(mutex->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mutex_detach); + +/* drop a thread from the suspend list of mutex */ + +/** + * @brief drop a thread from the suspend list of mutex + * + * @param mutex is a pointer to a mutex object. + * @param thread is the thread should be dropped from mutex. + */ +void rt_mutex_drop_thread(rt_mutex_t mutex, rt_thread_t thread) +{ + rt_uint8_t priority; + rt_bool_t need_update = RT_FALSE; + + rt_list_remove(&(thread->tlist)); + + /* should change the priority of mutex owner thread */ + if (mutex->owner->current_priority == thread->current_priority) + need_update = RT_TRUE; + + /* update the priority of mutex */ + if (!rt_list_isempty(&mutex->parent.suspend_thread)) + { + /* more thread suspended in the list */ + struct rt_thread *th; + + th = rt_list_entry(mutex->parent.suspend_thread.next, + struct rt_thread, + tlist); + /* update the priority of mutex */ + mutex->priority = th->current_priority; + } + else + { + /* set mutex priority to maximal priority */ + mutex->priority = 0xff; + } + + /* try to change the priority of mutex owner thread */ + if (need_update) + { + /* get the maximal priority of mutex in thread */ + priority = _thread_get_mutex_priority(mutex->owner); + if (priority != mutex->owner->current_priority) + { + _thread_update_priority(mutex->owner, priority, RT_UNINTERRUPTIBLE); + } + } +} + + +/** + * @brief set the prioceiling attribute of the mutex. + * + * @param mutex is a pointer to a mutex object. + * @param priority is the priority should be set to mutex. + * + * @return return the old priority ceiling + */ +rt_uint8_t rt_mutex_setprioceiling(rt_mutex_t mutex, rt_uint8_t priority) +{ + rt_uint8_t ret_priority = 0xFF; + + if ((mutex) && (priority < RT_THREAD_PRIORITY_MAX)) + { + ret_priority = mutex->ceiling_priority; + mutex->ceiling_priority = priority; + } + else + { + rt_set_errno(-RT_EINVAL); + } + + return ret_priority; +} +RTM_EXPORT(rt_mutex_setprioceiling); + + +/** + * @brief set the prioceiling attribute of the mutex. + * + * @param mutex is a pointer to a mutex object. + * + * @return return the current priority ceiling of the mutex. + */ +rt_uint8_t rt_mutex_getprioceiling(rt_mutex_t mutex) +{ + rt_uint8_t prio = 0xFF; + + if (mutex) + { + prio = mutex->ceiling_priority; + } + + return prio; +} +RTM_EXPORT(rt_mutex_getprioceiling); + + +#ifdef RT_USING_HEAP +/** + * @brief This function will create a mutex object. + * + * @note For the mutex object, its memory space is automatically allocated. + * By contrast, the rt_mutex_init() function will initialize a static mutex object. + * + * @see rt_mutex_init() + * + * @param name is a pointer to the name that given to the mutex. + * + * @param flag is the mutex flag, which determines the queuing way of how multiple threads wait + * when the mutex is not available. + * NOTE: This parameter has been obsoleted. It can be RT_IPC_FLAG_PRIO, RT_IPC_FLAG_FIFO or RT_NULL. + * + * @return Return a pointer to the mutex object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_mutex_t rt_mutex_create(const char *name, rt_uint8_t flag) +{ + struct rt_mutex *mutex; + + /* flag parameter has been obsoleted */ + RT_UNUSED(flag); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + mutex = (rt_mutex_t)rt_object_allocate(RT_Object_Class_Mutex, name); + if (mutex == RT_NULL) + return mutex; + + /* initialize ipc object */ + _ipc_object_init(&(mutex->parent)); + + mutex->owner = RT_NULL; + mutex->priority = 0xFF; + mutex->hold = 0; + mutex->ceiling_priority = 0xFF; + rt_list_init(&(mutex->taken_list)); + + /* flag can only be RT_IPC_FLAG_PRIO. RT_IPC_FLAG_FIFO cannot solve the unbounded priority inversion problem */ + mutex->parent.parent.flag = RT_IPC_FLAG_PRIO; + + return mutex; +} +RTM_EXPORT(rt_mutex_create); + + +/** + * @brief This function will delete a mutex object and release this memory space. + * + * @note This function is used to delete a mutex object which is created by the rt_mutex_create() function. + * By contrast, the rt_mutex_detach() function will detach a static mutex object. + * When the mutex is successfully deleted, it will resume all suspended threads in the mutex list. + * + * @see rt_mutex_detach() + * + * @param mutex is a pointer to a mutex object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mutex detach failed. + * + * @warning This function can ONLY delete a mutex initialized by the rt_mutex_create() function. + * If the mutex is initialized by the rt_mutex_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_mutex_detach() function to complete the detachment. + */ +rt_err_t rt_mutex_delete(rt_mutex_t mutex) +{ + rt_ubase_t level; + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + RT_ASSERT(rt_object_is_systemobject(&mutex->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + level = rt_hw_interrupt_disable(); + /* wakeup all suspended threads */ + _ipc_list_resume_all(&(mutex->parent.suspend_thread)); + /* remove mutex from thread's taken list */ + rt_list_remove(&mutex->taken_list); + rt_hw_interrupt_enable(level); + + /* delete mutex object */ + rt_object_delete(&(mutex->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mutex_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will take a mutex, if the mutex is unavailable, the thread shall wait for + * the mutex up to a specified time. + * + * @note When this function is called, the count value of the mutex->value will decrease 1 until it is equal to 0. + * When the mutex->value is 0, it means that the mutex is unavailable. At this time, it will suspend the + * thread preparing to take the mutex. + * On the contrary, the rt_mutex_release() function will increase the count value of mutex->value by 1 each time. + * + * @see rt_mutex_trytake() + * + * @param mutex is a pointer to a mutex object. + * + * @param timeout is a timeout period (unit: an OS tick). If the mutex is unavailable, the thread will wait for + * the mutex up to the amount of time specified by the argument. + * NOTE: Generally, we set this parameter to RT_WAITING_FOREVER, which means that when the mutex is unavailable, + * the thread will be waitting forever. + * + * @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 mutex take failed. + * + * @warning This function can ONLY be called in the thread context. It MUST NOT BE called in interrupt context. + */ +static rt_err_t _rt_mutex_take(rt_mutex_t mutex, rt_int32_t timeout, int suspend_flag) +{ + rt_base_t level; + struct rt_thread *thread; + rt_err_t ret; + + /* this function must not be used in interrupt even if time = 0 */ + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE); + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + + /* get current thread */ + thread = rt_thread_self(); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(mutex->parent.parent))); + + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("mutex_take: current thread %s, hold: %d\n", + thread->name, mutex->hold)); + + /* reset thread error */ + thread->error = RT_EOK; + + if (mutex->owner == thread) + { + if(mutex->hold < RT_MUTEX_HOLD_MAX) + { + /* it's the same thread */ + mutex->hold ++; + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + } + else + { + /* whether the mutex has owner thread. */ + if (mutex->owner == RT_NULL) + { + /* set mutex owner and original priority */ + mutex->owner = thread; + mutex->priority = 0xff; + mutex->hold = 1; + + if (mutex->ceiling_priority != 0xFF) + { + /* set the priority of thread to the ceiling priority */ + if (mutex->ceiling_priority < mutex->owner->current_priority) + _thread_update_priority(mutex->owner, mutex->ceiling_priority, suspend_flag); + } + + /* insert mutex to thread's taken object list */ + rt_list_insert_after(&thread->taken_object_list, &mutex->taken_list); + } + else + { + /* no waiting, return with timeout */ + if (timeout == 0) + { + /* set error as timeout */ + thread->error = -RT_ETIMEOUT; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + else + { + rt_uint8_t priority = thread->current_priority; + + /* mutex is unavailable, push to suspend list */ + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mutex_take: suspend thread: %s\n", + thread->name)); + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mutex->parent.suspend_thread), + thread, + mutex->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* set pending object in thread to this mutex */ + thread->pending_object = &(mutex->parent.parent); + + /* update the priority level of mutex */ + if (priority < mutex->priority) + { + mutex->priority = priority; + if (mutex->priority < mutex->owner->current_priority) + { + _thread_update_priority(mutex->owner, priority, RT_UNINTERRUPTIBLE); /* TODO */ + } + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("mutex_take: start the timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do schedule */ + rt_schedule(); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + if (thread->error == RT_EOK) + { + /* get mutex successfully */ + } + else + { + /* the mutex has not been taken and thread has detach from the pending list. */ + + rt_bool_t need_update = RT_FALSE; + + /* should change the priority of mutex owner thread */ + if (mutex->owner->current_priority == thread->current_priority) + need_update = RT_TRUE; + + /* update the priority of mutex */ + if (!rt_list_isempty(&mutex->parent.suspend_thread)) + { + /* more thread suspended in the list */ + struct rt_thread *th; + + th = rt_list_entry(mutex->parent.suspend_thread.next, + struct rt_thread, + tlist); + /* update the priority of mutex */ + mutex->priority = th->current_priority; + } + else + { + /* set mutex priority to maximal priority */ + mutex->priority = 0xff; + } + + /* try to change the priority of mutex owner thread */ + if (need_update) + { + /* get the maximal priority of mutex in thread */ + priority = _thread_get_mutex_priority(mutex->owner); + if (priority != mutex->owner->current_priority) + { + _thread_update_priority(mutex->owner, priority, RT_UNINTERRUPTIBLE); + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* return error */ + return thread->error; + } + } + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mutex->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_mutex_take(rt_mutex_t mutex, rt_int32_t time) +{ + return _rt_mutex_take(mutex, time, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mutex_take); + +rt_err_t rt_mutex_take_interruptible(rt_mutex_t mutex, rt_int32_t time) +{ + return _rt_mutex_take(mutex, time, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mutex_take_interruptible); + +rt_err_t rt_mutex_take_killable(rt_mutex_t mutex, rt_int32_t time) +{ + return _rt_mutex_take(mutex, time, RT_KILLABLE); +} +RTM_EXPORT(rt_mutex_take_killable); + +/** + * @brief This function will try to take a mutex, if the mutex is unavailable, the thread returns immediately. + * + * @note This function is very similar to the rt_mutex_take() function, when the mutex is not available, + * except that rt_mutex_trytake() will return immediately without waiting for a timeout + * when the mutex is not available. + * In other words, rt_mutex_trytake(mutex) has the same effect as rt_mutex_take(mutex, 0). + * + * @see rt_mutex_take() + * + * @param mutex is a pointer to a mutex object. + * + * @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 mutex take failed. + */ +rt_err_t rt_mutex_trytake(rt_mutex_t mutex) +{ + return rt_mutex_take(mutex, RT_WAITING_NO); +} +RTM_EXPORT(rt_mutex_trytake); + + +/** + * @brief This function will release a mutex. If there is thread suspended on the mutex, the thread will be resumed. + * + * @note If there are threads suspended on this mutex, the first thread in the list of this mutex object + * will be resumed, and a thread scheduling (rt_schedule) will be executed. + * If no threads are suspended on this mutex, the count value mutex->value of this mutex will increase by 1. + * + * @param mutex is a pointer to a mutex object. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mutex release failed. + */ +rt_err_t rt_mutex_release(rt_mutex_t mutex) +{ + rt_base_t level; + struct rt_thread *thread; + rt_bool_t need_schedule; + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + + need_schedule = RT_FALSE; + + /* only thread could release mutex because we need test the ownership */ + RT_DEBUG_IN_THREAD_CONTEXT; + + /* get current thread */ + thread = rt_thread_self(); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("mutex_release:current thread %s, hold: %d\n", + thread->name, mutex->hold)); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mutex->parent.parent))); + + /* mutex only can be released by owner */ + if (thread != mutex->owner) + { + thread->error = -RT_ERROR; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_ERROR; + } + + /* decrease hold */ + mutex->hold --; + /* if no hold */ + if (mutex->hold == 0) + { + /* remove mutex from thread's taken list */ + rt_list_remove(&mutex->taken_list); + + /* whether change the thread priority */ + if ((mutex->ceiling_priority != 0xFF) || (thread->current_priority == mutex->priority)) + { + rt_uint8_t priority = 0xff; + + /* get the highest priority in the taken list of thread */ + priority = _thread_get_mutex_priority(thread); + + rt_thread_control(thread, + RT_THREAD_CTRL_CHANGE_PRIORITY, + &priority); + + need_schedule = RT_TRUE; + } + + /* wakeup suspended thread */ + if (!rt_list_isempty(&mutex->parent.suspend_thread)) + { + /* get the first suspended thread */ + struct rt_thread *next_thread = rt_list_entry(mutex->parent.suspend_thread.next, + struct rt_thread, + tlist); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mutex_release: resume thread: %s\n", + next_thread->name)); + + /* remove the thread from the suspended list of mutex */ + rt_list_remove(&(next_thread->tlist)); + + /* set new owner and put mutex into taken list of thread */ + mutex->owner = next_thread; + mutex->hold = 1; + rt_list_insert_after(&next_thread->taken_object_list, &mutex->taken_list); + /* cleanup pending object */ + next_thread->pending_object = RT_NULL; + + /* resume thread */ + rt_thread_resume(next_thread); + + /* update mutex priority */ + if (!rt_list_isempty(&(mutex->parent.suspend_thread))) + { + struct rt_thread *th; + + th = rt_list_entry(mutex->parent.suspend_thread.next, + struct rt_thread, + tlist); + mutex->priority = th->current_priority; + } + else + { + mutex->priority = 0xff; + } + + need_schedule = RT_TRUE; + } + else + { + /* clear owner */ + mutex->owner = RT_NULL; + mutex->priority = 0xff; + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* perform a schedule */ + if (need_schedule == RT_TRUE) + rt_schedule(); + + return RT_EOK; +} +RTM_EXPORT(rt_mutex_release); + + +/** + * @brief This function will set some extra attributions of a mutex object. + * + * @note Currently this function does not implement the control function. + * + * @param mutex is a pointer to a mutex object. + * + * @param cmd is a command word used to configure some attributions of the mutex. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_mutex_control(rt_mutex_t mutex, int cmd, void *arg) +{ + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + + return -RT_ERROR; +} +RTM_EXPORT(rt_mutex_control); + +/**@}*/ +#endif /* RT_USING_MUTEX */ + +#ifdef RT_USING_EVENT +/** + * @addtogroup event + * @{ + */ + +/** + * @brief The function will initialize a static event object. + * + * @note For the static event object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_event_create() function will allocate memory space automatically + * and initialize the event. + * + * @see rt_event_create() + * + * @param event is a pointer to the event to initialize. It is assumed that storage for the event + * will be allocated in your application. + * + * @param name is a pointer to the name that given to the event. + * + * @param flag is the event flag, which determines the queuing way of how multiple threads wait + * when the event is not available. + * The event flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this event will become non-real-time threads. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_event_init(rt_event_t event, const char *name, rt_uint8_t flag) +{ + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(event->parent.parent), RT_Object_Class_Event, name); + + /* set parent flag */ + event->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(event->parent)); + + /* initialize event */ + event->set = 0; + + return RT_EOK; +} +RTM_EXPORT(rt_event_init); + + +/** + * @brief This function will detach a static event object. + * + * @note This function is used to detach a static event object which is initialized by rt_event_init() function. + * By contrast, the rt_event_delete() function will delete an event object. + * When the event is successfully detached, it will resume all suspended threads in the event list. + * + * @see rt_event_delete() + * + * @param event is a pointer to an event object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the event detach failed. + * + * @warning This function can ONLY detach a static event initialized by the rt_event_init() function. + * If the event is created by the rt_event_create() function, you MUST NOT USE this function to detach it, + * ONLY USE the rt_event_delete() function to complete the deletion. + */ +rt_err_t rt_event_detach(rt_event_t event) +{ + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + RT_ASSERT(rt_object_is_systemobject(&event->parent.parent)); + + /* resume all suspended thread */ + _ipc_list_resume_all(&(event->parent.suspend_thread)); + + /* detach event object */ + rt_object_detach(&(event->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_event_detach); + +#ifdef RT_USING_HEAP +/** + * @brief Creating an event object. + * + * @note For the event object, its memory space is allocated automatically. + * By contrast, the rt_event_init() function will initialize a static event object. + * + * @see rt_event_init() + * + * @param name is a pointer to the name that given to the event. + * + * @param flag is the event flag, which determines the queuing way of how multiple threads wait when the event + * is not available. + * The event flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this event will become non-real-time threads. + * + * @return Return a pointer to the event object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_event_t rt_event_create(const char *name, rt_uint8_t flag) +{ + rt_event_t event; + + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + event = (rt_event_t)rt_object_allocate(RT_Object_Class_Event, name); + if (event == RT_NULL) + return event; + + /* set parent */ + event->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(event->parent)); + + /* initialize event */ + event->set = 0; + + return event; +} +RTM_EXPORT(rt_event_create); + + +/** + * @brief This function will delete an event object and release the memory space. + * + * @note This function is used to delete an event object which is created by the rt_event_create() function. + * By contrast, the rt_event_detach() function will detach a static event object. + * When the event is successfully deleted, it will resume all suspended threads in the event list. + * + * @see rt_event_detach() + * + * @param event is a pointer to an event object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the event detach failed. + * + * @warning This function can ONLY delete an event initialized by the rt_event_create() function. + * If the event is initialized by the rt_event_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_event_detach() function to complete the detachment. + */ +rt_err_t rt_event_delete(rt_event_t event) +{ + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + RT_ASSERT(rt_object_is_systemobject(&event->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* resume all suspended thread */ + _ipc_list_resume_all(&(event->parent.suspend_thread)); + + /* delete event object */ + rt_object_delete(&(event->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_event_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will send an event to the event object. + * If there is a thread suspended on the event, the thread will be resumed. + * + * @note When using this function, you need to use the parameter (set) to specify the event flag of the event object, + * then the function will traverse the list of suspended threads waiting on the event object. + * If there is a thread suspended on the event, and the thread's event_info and the event flag of + * the current event object matches, the thread will be resumed. + * + * @param event is a pointer to the event object to be sent. + * + * @param set is a flag that you will set for this event's flag. + * You can set an event flag, or you can set multiple flags through OR logic operation. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the event detach failed. + */ +rt_err_t rt_event_send(rt_event_t event, rt_uint32_t set) +{ + struct rt_list_node *n; + struct rt_thread *thread; + rt_base_t level; + rt_base_t status; + rt_bool_t need_schedule; + + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + + if (set == 0) + return -RT_ERROR; + + need_schedule = RT_FALSE; + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* set event */ + event->set |= set; + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(event->parent.parent))); + + if (!rt_list_isempty(&event->parent.suspend_thread)) + { + /* search thread list to resume thread */ + n = event->parent.suspend_thread.next; + while (n != &(event->parent.suspend_thread)) + { + /* get thread */ + thread = rt_list_entry(n, struct rt_thread, tlist); + + status = -RT_ERROR; + if (thread->event_info & RT_EVENT_FLAG_AND) + { + if ((thread->event_set & event->set) == thread->event_set) + { + /* received an AND event */ + status = RT_EOK; + } + } + else if (thread->event_info & RT_EVENT_FLAG_OR) + { + if (thread->event_set & event->set) + { + /* save the received event set */ + thread->event_set = thread->event_set & event->set; + + /* received an OR event */ + status = RT_EOK; + } + } + else + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EINVAL; + } + + /* move node to the next */ + n = n->next; + + /* condition is satisfied, resume thread */ + if (status == RT_EOK) + { + /* clear event */ + if (thread->event_info & RT_EVENT_FLAG_CLEAR) + event->set &= ~thread->event_set; + + /* resume thread, and thread list breaks out */ + rt_thread_resume(thread); + thread->error = RT_EOK; + + /* need do a scheduling */ + need_schedule = RT_TRUE; + } + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do a schedule */ + if (need_schedule == RT_TRUE) + rt_schedule(); + + return RT_EOK; +} +RTM_EXPORT(rt_event_send); + + +/** + * @brief This function will receive an event from event object. if the event is unavailable, the thread shall wait for + * the event up to a specified time. + * + * @note If there are threads suspended on this semaphore, the first thread in the list of this semaphore object + * will be resumed, and a thread scheduling (rt_schedule) will be executed. + * If no threads are suspended on this semaphore, the count value sem->value of this semaphore will increase by 1. + * + * @param event is a pointer to the event object to be received. + * + * @param set is a flag that you will set for this event's flag. + * You can set an event flag, or you can set multiple flags through OR logic operation. + * + * @param option is the option of this receiving event, it indicates how the receiving event is operated. + * The option can be one or more of the following values, When selecting multiple values,use logical OR to operate. + * (NOTE: RT_EVENT_FLAG_OR and RT_EVENT_FLAG_AND can only select one): + * + * + * RT_EVENT_FLAG_OR The thread select to use logical OR to receive the event. + * + * RT_EVENT_FLAG_AND The thread select to use logical OR to receive the event. + * + * RT_EVENT_FLAG_CLEAR When the thread receives the corresponding event, the function + * determines whether to clear the event flag. + * + * @param timeout is a timeout period (unit: an OS tick). + * + * @param recved is a pointer to the received event. If you don't care about this value, you can use RT_NULL to set. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the semaphore release failed. + */ +static rt_err_t _rt_event_recv(rt_event_t event, + rt_uint32_t set, + rt_uint8_t option, + rt_int32_t timeout, + rt_uint32_t *recved, + int suspend_flag) +{ + struct rt_thread *thread; + rt_base_t level; + rt_base_t status; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE); + + if (set == 0) + return -RT_ERROR; + + /* initialize status */ + status = -RT_ERROR; + /* get current thread */ + thread = rt_thread_self(); + /* reset thread error */ + thread->error = -RT_EINTR; + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(event->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* check event set */ + if (option & RT_EVENT_FLAG_AND) + { + if ((event->set & set) == set) + status = RT_EOK; + } + else if (option & RT_EVENT_FLAG_OR) + { + if (event->set & set) + status = RT_EOK; + } + else + { + /* either RT_EVENT_FLAG_AND or RT_EVENT_FLAG_OR should be set */ + RT_ASSERT(0); + } + + if (status == RT_EOK) + { + thread->error = RT_EOK; + + /* set received event */ + if (recved) + *recved = (event->set & set); + + /* fill thread event info */ + thread->event_set = (event->set & set); + thread->event_info = option; + + /* received event */ + if (option & RT_EVENT_FLAG_CLEAR) + event->set &= ~set; + } + else if (timeout == 0) + { + /* no waiting */ + thread->error = -RT_ETIMEOUT; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + else + { + /* fill thread event info */ + thread->event_set = set; + thread->event_info = option; + + /* put thread to suspended thread list */ + ret = _ipc_list_suspend(&(event->parent.suspend_thread), + thread, + event->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* if there is a waiting timeout, active thread timer */ + if (timeout > 0) + { + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do a schedule */ + rt_schedule(); + + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* received an event, disable interrupt to protect */ + level = rt_hw_interrupt_disable(); + + /* set received event */ + if (recved) + *recved = thread->event_set; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(event->parent.parent))); + + return thread->error; +} + +rt_err_t rt_event_recv(rt_event_t event, + rt_uint32_t set, + rt_uint8_t option, + rt_int32_t timeout, + rt_uint32_t *recved) +{ + return _rt_event_recv(event, set, option, timeout, recved, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_event_recv); + +rt_err_t rt_event_recv_interruptible(rt_event_t event, + rt_uint32_t set, + rt_uint8_t option, + rt_int32_t timeout, + rt_uint32_t *recved) +{ + return _rt_event_recv(event, set, option, timeout, recved, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_event_recv_interruptible); + +rt_err_t rt_event_recv_killable(rt_event_t event, + rt_uint32_t set, + rt_uint8_t option, + rt_int32_t timeout, + rt_uint32_t *recved) +{ + return _rt_event_recv(event, set, option, timeout, recved, RT_KILLABLE); +} +RTM_EXPORT(rt_event_recv_killable); +/** + * @brief This function will set some extra attributions of an event object. + * + * @note Currently this function only supports the RT_IPC_CMD_RESET command to reset the event. + * + * @param event is a pointer to an event object. + * + * @param cmd is a command word used to configure some attributions of the event. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_event_control(rt_event_t event, int cmd, void *arg) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + + if (cmd == RT_IPC_CMD_RESET) + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* resume all waiting thread */ + _ipc_list_resume_all(&event->parent.suspend_thread); + + /* initialize event set */ + event->set = 0; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_event_control); + +/**@}*/ +#endif /* RT_USING_EVENT */ + +#ifdef RT_USING_MAILBOX +/** + * @addtogroup mailbox + * @{ + */ + +/** + * @brief Initialize a static mailbox object. + * + * @note For the static mailbox object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_mb_create() function will allocate memory space automatically and initialize the mailbox. + * + * @see rt_mb_create() + * + * @param mb is a pointer to the mailbox to initialize. + * It is assumed that storage for the mailbox will be allocated in your application. + * + * @param name is a pointer to the name that given to the mailbox. + * + * @param msgpool the begin address of buffer to save received mail. + * + * @param size is the maximum number of mails in the mailbox. + * For example, when the mailbox buffer capacity is N, size is N/4. + * + * @param flag is the mailbox flag, which determines the queuing way of how multiple threads wait + * when the mailbox is not available. + * The mailbox flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this mailbox will become non-real-time threads. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_mb_init(rt_mailbox_t mb, + const char *name, + void *msgpool, + rt_size_t size, + rt_uint8_t flag) +{ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(mb->parent.parent), RT_Object_Class_MailBox, name); + + /* set parent flag */ + mb->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(mb->parent)); + + /* initialize mailbox */ + mb->msg_pool = (rt_ubase_t *)msgpool; + mb->size = (rt_uint16_t)size; + mb->entry = 0; + mb->in_offset = 0; + mb->out_offset = 0; + + /* initialize an additional list of sender suspend thread */ + rt_list_init(&(mb->suspend_sender_thread)); + + return RT_EOK; +} +RTM_EXPORT(rt_mb_init); + + +/** + * @brief This function will detach a static mailbox object. + * + * @note This function is used to detach a static mailbox object which is initialized by rt_mb_init() function. + * By contrast, the rt_mb_delete() function will delete a mailbox object. + * When the mailbox is successfully detached, it will resume all suspended threads in the mailbox list. + * + * @see rt_mb_delete() + * + * @param mb is a pointer to a mailbox object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the mailbox detach failed. + * + * @warning This function can ONLY detach a static mailbox initialized by the rt_mb_init() function. + * If the mailbox is created by the rt_mb_create() function, you MUST NOT USE this function to detach it, + * ONLY USE the rt_mb_delete() function to complete the deletion. + */ +rt_err_t rt_mb_detach(rt_mailbox_t mb) +{ + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + RT_ASSERT(rt_object_is_systemobject(&mb->parent.parent)); + + /* resume all suspended thread */ + _ipc_list_resume_all(&(mb->parent.suspend_thread)); + /* also resume all mailbox private suspended thread */ + _ipc_list_resume_all(&(mb->suspend_sender_thread)); + + /* detach mailbox object */ + rt_object_detach(&(mb->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mb_detach); + +#ifdef RT_USING_HEAP +/** + * @brief Creating a mailbox object. + * + * @note For the mailbox object, its memory space is allocated automatically. + * By contrast, the rt_mb_init() function will initialize a static mailbox object. + * + * @see rt_mb_init() + * + * @param name is a pointer that given to the mailbox. + * + * @param size is the maximum number of mails in the mailbox. + * For example, when mailbox buffer capacity is N, size is N/4. + * + * @param flag is the mailbox flag, which determines the queuing way of how multiple threads wait + * when the mailbox is not available. + * The mailbox flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this mailbox will become non-real-time threads. + * + * @return Return a pointer to the mailbox object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_mailbox_t rt_mb_create(const char *name, rt_size_t size, rt_uint8_t flag) +{ + rt_mailbox_t mb; + + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + mb = (rt_mailbox_t)rt_object_allocate(RT_Object_Class_MailBox, name); + if (mb == RT_NULL) + return mb; + + /* set parent */ + mb->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(mb->parent)); + + /* initialize mailbox */ + mb->size = (rt_uint16_t)size; + mb->msg_pool = (rt_ubase_t *)RT_KERNEL_MALLOC(mb->size * sizeof(rt_ubase_t)); + if (mb->msg_pool == RT_NULL) + { + /* delete mailbox object */ + rt_object_delete(&(mb->parent.parent)); + + return RT_NULL; + } + mb->entry = 0; + mb->in_offset = 0; + mb->out_offset = 0; + + /* initialize an additional list of sender suspend thread */ + rt_list_init(&(mb->suspend_sender_thread)); + + return mb; +} +RTM_EXPORT(rt_mb_create); + + +/** + * @brief This function will delete a mailbox object and release the memory space. + * + * @note This function is used to delete a mailbox object which is created by the rt_mb_create() function. + * By contrast, the rt_mb_detach() function will detach a static mailbox object. + * When the mailbox is successfully deleted, it will resume all suspended threads in the mailbox list. + * + * @see rt_mb_detach() + * + * @param mb is a pointer to a mailbox object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + * + * @warning This function can only delete mailbox created by the rt_mb_create() function. + * If the mailbox is initialized by the rt_mb_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_mb_detach() function to complete the detachment. + */ +rt_err_t rt_mb_delete(rt_mailbox_t mb) +{ + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + RT_ASSERT(rt_object_is_systemobject(&mb->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* resume all suspended thread */ + _ipc_list_resume_all(&(mb->parent.suspend_thread)); + + /* also resume all mailbox private suspended thread */ + _ipc_list_resume_all(&(mb->suspend_sender_thread)); + + /* free mailbox pool */ + RT_KERNEL_FREE(mb->msg_pool); + + /* delete mailbox object */ + rt_object_delete(&(mb->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mb_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will send an mail to the mailbox object. If there is a thread suspended on the mailbox, + * the thread will be resumed. + * + * @note When using this function to send a mail, if the mailbox if fully used, the current thread will + * wait for a timeout. If the set timeout time is reached and there is still no space available, + * the sending thread will be resumed and an error code will be returned. + * By contrast, the rt_mb_send() function will return an error code immediately without waiting time + * when the mailbox if fully used. + * + * @see rt_mb_send() + * + * @param mb is a pointer to the mailbox object to be sent. + * + * @param value is a value to the content of the mail you want to send. + * + * @param timeout is a timeout period (unit: an OS tick). + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + * + * @warning This function can be called in interrupt context and thread context. + */ +static rt_err_t _rt_mb_send_wait(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout, + int suspend_flag) +{ + struct rt_thread *thread; + rt_base_t level; + rt_uint32_t tick_delta; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0); + + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mb->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* for non-blocking call */ + if (mb->entry == mb->size && timeout == 0) + { + rt_hw_interrupt_enable(level); + return -RT_EFULL; + } + + /* mailbox is full */ + while (mb->entry == mb->size) + { + /* reset error number in thread */ + thread->error = -RT_EINTR; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EFULL; + } + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mb->suspend_sender_thread), + thread, + mb->parent.parent.flag, + suspend_flag); + + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mb_send_wait: start timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* re-schedule */ + rt_schedule(); + + /* resume from suspend state */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + + /* set ptr */ + mb->msg_pool[mb->in_offset] = value; + /* increase input offset */ + ++ mb->in_offset; + if (mb->in_offset >= mb->size) + mb->in_offset = 0; + + if(mb->entry < RT_MB_ENTRY_MAX) + { + /* increase message entry */ + mb->entry ++; + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + + /* resume suspended thread */ + if (!rt_list_isempty(&mb->parent.suspend_thread)) + { + _ipc_list_resume(&(mb->parent.suspend_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} + +rt_err_t rt_mb_send_wait(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout) +{ + return _rt_mb_send_wait(mb, value, timeout, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mb_send_wait); + +rt_err_t rt_mb_send_wait_interruptible(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout) +{ + return _rt_mb_send_wait(mb, value, timeout, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mb_send_wait_interruptible); + +rt_err_t rt_mb_send_wait_killable(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout) +{ + return _rt_mb_send_wait(mb, value, timeout, RT_KILLABLE); +} +RTM_EXPORT(rt_mb_send_wait_killable); +/** + * @brief This function will send an mail to the mailbox object. If there is a thread suspended on the mailbox, + * the thread will be resumed. + * + * @note When using this function to send a mail, if the mailbox is fully used, this function will return an error + * code immediately without waiting time. + * By contrast, the rt_mb_send_wait() function is set a timeout to wait for the mail to be sent. + * + * @see rt_mb_send_wait() + * + * @param mb is a pointer to the mailbox object to be sent. + * + * @param value is a value to the content of the mail you want to send. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + */ +rt_err_t rt_mb_send(rt_mailbox_t mb, rt_ubase_t value) +{ + return rt_mb_send_wait(mb, value, 0); +} +RTM_EXPORT(rt_mb_send); + +rt_err_t rt_mb_send_interruptible(rt_mailbox_t mb, rt_ubase_t value) +{ + return rt_mb_send_wait_interruptible(mb, value, 0); +} +RTM_EXPORT(rt_mb_send_interruptible); + +rt_err_t rt_mb_send_killable(rt_mailbox_t mb, rt_ubase_t value) +{ + return rt_mb_send_wait_killable(mb, value, 0); +} +RTM_EXPORT(rt_mb_send_killable); + +/** + * @brief This function will send an urgent mail to the mailbox object. + * + * @note This function is almost the same as the rt_mb_send() function. The only difference is that + * when sending an urgent mail, the mail will be placed at the head of the mail queue so that + * the recipient can receive the urgent mail first. + * + * @see rt_mb_send() + * + * @param mb is a pointer to the mailbox object to be sent. + * + * @param value is the content of the mail you want to send. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + */ +rt_err_t rt_mb_urgent(rt_mailbox_t mb, rt_ubase_t value) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mb->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + if (mb->entry == mb->size) + { + rt_hw_interrupt_enable(level); + return -RT_EFULL; + } + + /* rewind to the previous position */ + if (mb->out_offset > 0) + { + mb->out_offset --; + } + else + { + mb->out_offset = mb->size - 1; + } + + /* set ptr */ + mb->msg_pool[mb->out_offset] = value; + + /* increase message entry */ + mb->entry ++; + + /* resume suspended thread */ + if (!rt_list_isempty(&mb->parent.suspend_thread)) + { + _ipc_list_resume(&(mb->parent.suspend_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} +RTM_EXPORT(rt_mb_urgent); + + +/** + * @brief This function will receive a mail from mailbox object, if there is no mail in mailbox object, + * the thread shall wait for a specified time. + * + * @note Only when there is mail in the mailbox, the receiving thread can get the mail immediately and + * return RT_EOK, otherwise the receiving thread will be suspended until the set timeout. If the mail + * is still not received within the specified time, it will return-RT_ETIMEOUT. + * + * @param mb is a pointer to the mailbox object to be received. + * + * @param value is a flag that you will set for this mailbox's flag. + * You can set an mailbox flag, or you can set multiple flags through OR logic operations. + * + * @param timeout is a timeout period (unit: an OS tick). If the mailbox object is not avaliable in the queue, + * the thread will wait for the object in the queue up to the amount of time specified by this parameter. + * + * NOTE: + * If use Macro RT_WAITING_FOREVER to set this parameter, which means that when the + * mailbox object is unavailable in the queue, the thread will be waiting forever. + * If use macro RT_WAITING_NO to set this parameter, which means that this + * function is non-blocking and will return immediately. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox release failed. + */ +static rt_err_t _rt_mb_recv(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout, int suspend_flag) +{ + struct rt_thread *thread; + rt_base_t level; + rt_uint32_t tick_delta; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0); + + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(mb->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* for non-blocking call */ + if (mb->entry == 0 && timeout == 0) + { + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + + /* mailbox is empty */ + while (mb->entry == 0) + { + /* reset error number in thread */ + thread->error = -RT_EINTR; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + thread->error = -RT_ETIMEOUT; + + return -RT_ETIMEOUT; + } + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mb->parent.suspend_thread), + thread, + mb->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mb_recv: start timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* re-schedule */ + rt_schedule(); + + /* resume from suspend state */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + + /* fill ptr */ + *value = mb->msg_pool[mb->out_offset]; + + /* increase output offset */ + ++ mb->out_offset; + if (mb->out_offset >= mb->size) + mb->out_offset = 0; + + /* decrease message entry */ + if(mb->entry > 0) + { + mb->entry --; + } + + /* resume suspended thread */ + if (!rt_list_isempty(&(mb->suspend_sender_thread))) + { + _ipc_list_resume(&(mb->suspend_sender_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mb->parent.parent))); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mb->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_mb_recv(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout) +{ + return _rt_mb_recv(mb, value, timeout, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mb_recv); + +rt_err_t rt_mb_recv_interruptibale(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout) +{ + return _rt_mb_recv(mb, value, timeout, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mb_recv_interruptibale); + +rt_err_t rt_mb_recv_killable(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout) +{ + return _rt_mb_recv(mb, value, timeout, RT_KILLABLE); +} +RTM_EXPORT(rt_mb_recv_killable); + +/** + * @brief This function will set some extra attributions of a mailbox object. + * + * @note Currently this function only supports the RT_IPC_CMD_RESET command to reset the mailbox. + * + * @param mb is a pointer to a mailbox object. + * + * @param cmd is a command used to configure some attributions of the mailbox. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_mb_control(rt_mailbox_t mb, int cmd, void *arg) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + + if (cmd == RT_IPC_CMD_RESET) + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* resume all waiting thread */ + _ipc_list_resume_all(&(mb->parent.suspend_thread)); + /* also resume all mailbox private suspended thread */ + _ipc_list_resume_all(&(mb->suspend_sender_thread)); + + /* re-init mailbox */ + mb->entry = 0; + mb->in_offset = 0; + mb->out_offset = 0; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_mb_control); + +/**@}*/ +#endif /* RT_USING_MAILBOX */ + +#ifdef RT_USING_MESSAGEQUEUE +/** + * @addtogroup messagequeue + * @{ + */ + +struct rt_mq_message +{ + struct rt_mq_message *next; +}; + + +/** + * @brief Initialize a static messagequeue object. + * + * @note For the static messagequeue object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_mq_create() function will allocate memory space automatically + * and initialize the messagequeue. + * + * @see rt_mq_create() + * + * @param mq is a pointer to the messagequeue to initialize. It is assumed that storage for + * the messagequeue will be allocated in your application. + * + * @param name is a pointer to the name that given to the messagequeue. + * + * @param msgpool is a pointer to the starting address of the memory space you allocated for + * the messagequeue in advance. + * In other words, msgpool is a pointer to the messagequeue buffer of the starting address. + * + * @param msg_size is the maximum length of a message in the messagequeue (Unit: Byte). + * + * @param pool_size is the size of the memory space allocated for the messagequeue in advance. + * + * @param flag is the messagequeue flag, which determines the queuing way of how multiple threads wait + * when the messagequeue is not available. + * The messagequeue flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this messagequeue will become non-real-time threads. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_mq_init(rt_mq_t mq, + const char *name, + void *msgpool, + rt_size_t msg_size, + rt_size_t pool_size, + rt_uint8_t flag) +{ + struct rt_mq_message *head; + rt_base_t temp; + register rt_size_t msg_align_size; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(mq->parent.parent), RT_Object_Class_MessageQueue, name); + + /* set parent flag */ + mq->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(mq->parent)); + + /* set message pool */ + mq->msg_pool = msgpool; + + /* get correct message size */ + msg_align_size = RT_ALIGN(msg_size, RT_ALIGN_SIZE); + mq->msg_size = msg_size; + mq->max_msgs = pool_size / (msg_align_size + sizeof(struct rt_mq_message)); + + if (0 == mq->max_msgs) + { + return -RT_EINVAL; + } + + /* initialize message list */ + mq->msg_queue_head = RT_NULL; + mq->msg_queue_tail = RT_NULL; + + /* initialize message empty list */ + mq->msg_queue_free = RT_NULL; + for (temp = 0; temp < mq->max_msgs; temp ++) + { + head = (struct rt_mq_message *)((rt_uint8_t *)mq->msg_pool + + temp * (msg_align_size + sizeof(struct rt_mq_message))); + head->next = (struct rt_mq_message *)mq->msg_queue_free; + mq->msg_queue_free = head; + } + + /* the initial entry is zero */ + mq->entry = 0; + + /* initialize an additional list of sender suspend thread */ + rt_list_init(&(mq->suspend_sender_thread)); + + return RT_EOK; +} +RTM_EXPORT(rt_mq_init); + + +/** + * @brief This function will detach a static messagequeue object. + * + * @note This function is used to detach a static messagequeue object which is initialized by rt_mq_init() function. + * By contrast, the rt_mq_delete() function will delete a messagequeue object. + * When the messagequeue is successfully detached, it will resume all suspended threads in the messagequeue list. + * + * @see rt_mq_delete() + * + * @param mq is a pointer to a messagequeue object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the messagequeue detach failed. + * + * @warning This function can ONLY detach a static messagequeue initialized by the rt_mq_init() function. + * If the messagequeue is created by the rt_mq_create() function, you MUST NOT USE this function to detach it, + * and ONLY USE the rt_mq_delete() function to complete the deletion. + */ +rt_err_t rt_mq_detach(rt_mq_t mq) +{ + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(rt_object_is_systemobject(&mq->parent.parent)); + + /* resume all suspended thread */ + _ipc_list_resume_all(&mq->parent.suspend_thread); + /* also resume all message queue private suspended thread */ + _ipc_list_resume_all(&(mq->suspend_sender_thread)); + + /* detach message queue object */ + rt_object_detach(&(mq->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mq_detach); + +#ifdef RT_USING_HEAP +/** + * @brief Creating a messagequeue object. + * + * @note For the messagequeue object, its memory space is allocated automatically. + * By contrast, the rt_mq_init() function will initialize a static messagequeue object. + * + * @see rt_mq_init() + * + * @param name is a pointer that given to the messagequeue. + * + * @param msg_size is the maximum length of a message in the messagequeue (Unit: Byte). + * + * @param max_msgs is the maximum number of messages in the messagequeue. + * + * @param flag is the messagequeue flag, which determines the queuing way of how multiple threads wait + * when the messagequeue is not available. + * The messagequeue flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this messagequeue will become non-real-time threads. + * + * @return Return a pointer to the messagequeue object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can NOT be called in interrupt context. You can use macor RT_DEBUG_NOT_IN_INTERRUPT to check it. + */ +rt_mq_t rt_mq_create(const char *name, + rt_size_t msg_size, + rt_size_t max_msgs, + rt_uint8_t flag) +{ + struct rt_messagequeue *mq; + struct rt_mq_message *head; + rt_base_t temp; + register rt_size_t msg_align_size; + + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + mq = (rt_mq_t)rt_object_allocate(RT_Object_Class_MessageQueue, name); + if (mq == RT_NULL) + return mq; + + /* set parent */ + mq->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(mq->parent)); + + /* initialize message queue */ + + /* get correct message size */ + msg_align_size = RT_ALIGN(msg_size, RT_ALIGN_SIZE); + mq->msg_size = msg_size; + mq->max_msgs = max_msgs; + + /* allocate message pool */ + mq->msg_pool = RT_KERNEL_MALLOC((msg_align_size + sizeof(struct rt_mq_message)) * mq->max_msgs); + if (mq->msg_pool == RT_NULL) + { + rt_object_delete(&(mq->parent.parent)); + + return RT_NULL; + } + + /* initialize message list */ + mq->msg_queue_head = RT_NULL; + mq->msg_queue_tail = RT_NULL; + + /* initialize message empty list */ + mq->msg_queue_free = RT_NULL; + for (temp = 0; temp < mq->max_msgs; temp ++) + { + head = (struct rt_mq_message *)((rt_uint8_t *)mq->msg_pool + + temp * (msg_align_size + sizeof(struct rt_mq_message))); + head->next = (struct rt_mq_message *)mq->msg_queue_free; + mq->msg_queue_free = head; + } + + /* the initial entry is zero */ + mq->entry = 0; + + /* initialize an additional list of sender suspend thread */ + rt_list_init(&(mq->suspend_sender_thread)); + + return mq; +} +RTM_EXPORT(rt_mq_create); + + +/** + * @brief This function will delete a messagequeue object and release the memory. + * + * @note This function is used to delete a messagequeue object which is created by the rt_mq_create() function. + * By contrast, the rt_mq_detach() function will detach a static messagequeue object. + * When the messagequeue is successfully deleted, it will resume all suspended threads in the messagequeue list. + * + * @see rt_mq_detach() + * + * @param mq is a pointer to a messagequeue object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the messagequeue detach failed. + * + * @warning This function can ONLY delete a messagequeue initialized by the rt_mq_create() function. + * If the messagequeue is initialized by the rt_mq_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_mq_detach() function to complete the detachment. + * for example,the rt_mq_create() function, it cannot be called in interrupt context. + */ +rt_err_t rt_mq_delete(rt_mq_t mq) +{ + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(rt_object_is_systemobject(&mq->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* resume all suspended thread */ + _ipc_list_resume_all(&(mq->parent.suspend_thread)); + /* also resume all message queue private suspended thread */ + _ipc_list_resume_all(&(mq->suspend_sender_thread)); + + /* free message queue pool */ + RT_KERNEL_FREE(mq->msg_pool); + + /* delete message queue object */ + rt_object_delete(&(mq->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mq_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will send a message to the messagequeue object. If + * there is a thread suspended on the messagequeue, the thread will be + * resumed. + * + * @note When using this function to send a message, if the messagequeue is + * fully used, the current thread will wait for a timeout. If reaching + * the timeout and there is still no space available, the sending + * thread will be resumed and an error code will be returned. By + * contrast, the rt_mq_send() function will return an error code + * immediately without waiting when the messagequeue if fully used. + * + * @see rt_mq_send() + * + * @param mq is a pointer to the messagequeue object to be sent. + * + * @param buffer is the content of the message. + * + * @param size is the length of the message(Unit: Byte). + * + * @param timeout is a timeout period (unit: an OS tick). + * + * @return Return the operation status. When the return value is RT_EOK, the + * operation is successful. If the return value is any other values, + * it means that the messagequeue detach failed. + * + * @warning This function can be called in interrupt context and thread + * context. + */ +static rt_err_t _rt_mq_send_wait(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout, + int suspend_flag) +{ + rt_base_t level; + struct rt_mq_message *msg; + rt_uint32_t tick_delta; + struct rt_thread *thread; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(buffer != RT_NULL); + RT_ASSERT(size != 0); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0); + + /* greater than one message size */ + if (size > mq->msg_size) + return -RT_ERROR; + + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mq->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* get a free list, there must be an empty item */ + msg = (struct rt_mq_message *)mq->msg_queue_free; + /* for non-blocking call */ + if (msg == RT_NULL && timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EFULL; + } + + /* message queue is full */ + while ((msg = (struct rt_mq_message *)mq->msg_queue_free) == RT_NULL) + { + /* reset error number in thread */ + thread->error = -RT_EINTR; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EFULL; + } + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mq->suspend_sender_thread), + thread, + mq->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mq_send_wait: start timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* re-schedule */ + rt_schedule(); + + /* resume from suspend state */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + + /* move free list pointer */ + mq->msg_queue_free = msg->next; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* the msg is the new tailer of list, the next shall be NULL */ + msg->next = RT_NULL; + /* copy buffer */ + rt_memcpy(msg + 1, buffer, size); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + /* link msg to message queue */ + if (mq->msg_queue_tail != RT_NULL) + { + /* if the tail exists, */ + ((struct rt_mq_message *)mq->msg_queue_tail)->next = msg; + } + + /* set new tail */ + mq->msg_queue_tail = msg; + /* if the head is empty, set head */ + if (mq->msg_queue_head == RT_NULL) + mq->msg_queue_head = msg; + + if(mq->entry < RT_MQ_ENTRY_MAX) + { + /* increase message entry */ + mq->entry ++; + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + + /* resume suspended thread */ + if (!rt_list_isempty(&mq->parent.suspend_thread)) + { + _ipc_list_resume(&(mq->parent.suspend_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} + +rt_err_t rt_mq_send_wait(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_send_wait(mq, buffer, size, timeout, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mq_send_wait) + +rt_err_t rt_mq_send_wait_interruptible(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_send_wait(mq, buffer, size, timeout, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mq_send_wait_interruptible) + +rt_err_t rt_mq_send_wait_killable(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_send_wait(mq, buffer, size, timeout, RT_KILLABLE); +} +RTM_EXPORT(rt_mq_send_wait_killable) +/** + * @brief This function will send a message to the messagequeue object. + * If there is a thread suspended on the messagequeue, the thread will be resumed. + * + * @note When using this function to send a message, if the messagequeue is fully used, + * the current thread will wait for a timeout. + * By contrast, when the messagequeue is fully used, the rt_mq_send_wait() function will + * return an error code immediately without waiting. + * + * @see rt_mq_send_wait() + * + * @param mq is a pointer to the messagequeue object to be sent. + * + * @param buffer is the content of the message. + * + * @param size is the length of the message(Unit: Byte). + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the messagequeue detach failed. + * + * @warning This function can be called in interrupt context and thread context. + */ +rt_err_t rt_mq_send(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + return rt_mq_send_wait(mq, buffer, size, 0); +} +RTM_EXPORT(rt_mq_send); + +rt_err_t rt_mq_send_interrupt(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + return rt_mq_send_wait_interruptible(mq, buffer, size, 0); +} +RTM_EXPORT(rt_mq_send_interrupt); + +rt_err_t rt_mq_send_killable(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + return rt_mq_send_wait_killable(mq, buffer, size, 0); +} +RTM_EXPORT(rt_mq_send_killable); +/** + * @brief This function will send an urgent message to the messagequeue object. + * + * @note This function is almost the same as the rt_mq_send() function. The only difference is that + * when sending an urgent message, the message is placed at the head of the messagequeue so that + * the recipient can receive the urgent message first. + * + * @see rt_mq_send() + * + * @param mq is a pointer to the messagequeue object to be sent. + * + * @param buffer is the content of the message. + * + * @param size is the length of the message(Unit: Byte). + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + */ +rt_err_t rt_mq_urgent(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + rt_base_t level; + struct rt_mq_message *msg; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(buffer != RT_NULL); + RT_ASSERT(size != 0); + + /* greater than one message size */ + if (size > mq->msg_size) + return -RT_ERROR; + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mq->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* get a free list, there must be an empty item */ + msg = (struct rt_mq_message *)mq->msg_queue_free; + /* message queue is full */ + if (msg == RT_NULL) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EFULL; + } + /* move free list pointer */ + mq->msg_queue_free = msg->next; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* copy buffer */ + rt_memcpy(msg + 1, buffer, size); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* link msg to the beginning of message queue */ + msg->next = (struct rt_mq_message *)mq->msg_queue_head; + mq->msg_queue_head = msg; + + /* if there is no tail */ + if (mq->msg_queue_tail == RT_NULL) + mq->msg_queue_tail = msg; + + if(mq->entry < RT_MQ_ENTRY_MAX) + { + /* increase message entry */ + mq->entry ++; + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + + /* resume suspended thread */ + if (!rt_list_isempty(&mq->parent.suspend_thread)) + { + _ipc_list_resume(&(mq->parent.suspend_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} +RTM_EXPORT(rt_mq_urgent); + + +/** + * @brief This function will receive a message from message queue object, + * if there is no message in messagequeue object, the thread shall wait for a specified time. + * + * @note Only when there is mail in the mailbox, the receiving thread can get the mail immediately and return RT_EOK, + * otherwise the receiving thread will be suspended until timeout. + * If the mail is not received within the specified time, it will return -RT_ETIMEOUT. + * + * @param mq is a pointer to the messagequeue object to be received. + * + * @param buffer is the content of the message. + * + * @param size is the length of the message(Unit: Byte). + * + * @param timeout is a timeout period (unit: an OS tick). If the message is unavailable, the thread will wait for + * the message in the queue up to the amount of time specified by this parameter. + * + * NOTE: + * If use Macro RT_WAITING_FOREVER to set this parameter, which means that when the + * message is unavailable in the queue, the thread will be waiting forever. + * If use macro RT_WAITING_NO to set this parameter, which means that this + * function is non-blocking and will return immediately. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox release failed. + */ +static rt_err_t _rt_mq_recv(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout, + int suspend_flag) +{ + struct rt_thread *thread; + rt_base_t level; + struct rt_mq_message *msg; + rt_uint32_t tick_delta; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(buffer != RT_NULL); + RT_ASSERT(size != 0); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0); + + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(mq->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* for non-blocking call */ + if (mq->entry == 0 && timeout == 0) + { + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + + /* message queue is empty */ + while (mq->entry == 0) + { + /* reset error number in thread */ + thread->error = -RT_EINTR; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + thread->error = -RT_ETIMEOUT; + + return -RT_ETIMEOUT; + } + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mq->parent.suspend_thread), + thread, + mq->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("set thread:%s to timer list\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* re-schedule */ + rt_schedule(); + + /* recv message */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + + /* get message from queue */ + msg = (struct rt_mq_message *)mq->msg_queue_head; + + /* move message queue head */ + mq->msg_queue_head = msg->next; + /* reach queue tail, set to NULL */ + if (mq->msg_queue_tail == msg) + mq->msg_queue_tail = RT_NULL; + + /* decrease message entry */ + if(mq->entry > 0) + { + mq->entry --; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* copy message */ + rt_memcpy(buffer, msg + 1, size > mq->msg_size ? mq->msg_size : size); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + /* put message to free list */ + msg->next = (struct rt_mq_message *)mq->msg_queue_free; + mq->msg_queue_free = msg; + + /* resume suspended thread */ + if (!rt_list_isempty(&(mq->suspend_sender_thread))) + { + _ipc_list_resume(&(mq->suspend_sender_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mq->parent.parent))); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mq->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_mq_recv(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_recv(mq, buffer, size, timeout, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mq_recv); + +rt_err_t rt_mq_recv_interruptible(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_recv(mq, buffer, size, timeout, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mq_recv_interruptible); + +rt_err_t rt_mq_recv_killable(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_recv(mq, buffer, size, timeout, RT_KILLABLE); +} +RTM_EXPORT(rt_mq_recv_killable); +/** + * @brief This function will set some extra attributions of a messagequeue object. + * + * @note Currently this function only supports the RT_IPC_CMD_RESET command to reset the messagequeue. + * + * @param mq is a pointer to a messagequeue object. + * + * @param cmd is a command used to configure some attributions of the messagequeue. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_mq_control(rt_mq_t mq, int cmd, void *arg) +{ + rt_base_t level; + struct rt_mq_message *msg; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + + if (cmd == RT_IPC_CMD_RESET) + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* resume all waiting thread */ + _ipc_list_resume_all(&mq->parent.suspend_thread); + /* also resume all message queue private suspended thread */ + _ipc_list_resume_all(&(mq->suspend_sender_thread)); + + /* release all message in the queue */ + while (mq->msg_queue_head != RT_NULL) + { + /* get message from queue */ + msg = (struct rt_mq_message *)mq->msg_queue_head; + + /* move message queue head */ + mq->msg_queue_head = msg->next; + /* reach queue tail, set to NULL */ + if (mq->msg_queue_tail == msg) + mq->msg_queue_tail = RT_NULL; + + /* put message to free list */ + msg->next = (struct rt_mq_message *)mq->msg_queue_free; + mq->msg_queue_free = msg; + } + + /* clean entry */ + mq->entry = 0; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_mq_control); + +/**@}*/ +#endif /* RT_USING_MESSAGEQUEUE */ +/**@}*/ diff --git a/tasks/concur-rtthread-mutex-ceilings/prompt.md b/tasks/concur-rtthread-mutex-ceilings/prompt.md new file mode 100644 index 00000000..2c75a9f2 --- /dev/null +++ b/tasks/concur-rtthread-mutex-ceilings/prompt.md @@ -0,0 +1,5 @@ +现场的资源访问服务能完成普通加锁和释放,但启用资源配置以后,有时状态报告中的线程优先级没有跟上配置变更;在多个资源与等待线程组合下,还出现过已经发出释放通知而工作线程没有继续执行的情况。 + +当前目录包含可在主机编译的内核子集和服务移植层。先用 `make check` 运行正常路径,再运行 `make report && ./report` 查看配置变更前后的现场观察。请修复这些不一致,并使模块行为符合 `docs/synchronization.md` 的全部条款。复现和验收不需要板卡,也不依赖真实时间。 + +最终只提交并评分 `src/ipc.c`;新增文件不会进入正式候选。 diff --git a/tasks/concur-rtthread-mutex-ceilings/spec.md b/tasks/concur-rtthread-mutex-ceilings/spec.md new file mode 100644 index 00000000..9b4b1e3b --- /dev/null +++ b/tasks/concur-rtthread-mutex-ceilings/spec.md @@ -0,0 +1,126 @@ +# concur-rtthread-mutex-ceilings 作者规格 + +状态:CALIBRATED(最终回执见 report.json);难度 UNMEASURED。来源路线 D,软件替身可复现,不执行模型或硬件验证。 + +## 来源与许可 + +- 项目:https://github.com/RT-Thread/rt-thread +- 修复前提交:fcc01a617d62d72ba282580d4810d23ec0a1325f +- 修复提交:64cd64baf9ba04dfe5967431d97884d976fc87ab +- source:oss/RT-Thread/rt-thread@64cd64baf9ba;split_group:RT-Thread/rt-thread +- 许可证:Apache-2.0,来自冻结提交根目录 LICENSE;所有冻结源码保留文件头版权与 SPDX。没有独立 NOTICE。 +- 上游总改动:src/ipc.c 一文件,29 插入、12 删除。只有一个修复,但跨 _ipc_list_suspend、_thread_get_mutex_priority、rt_mutex_setprioceiling、_rt_mutex_take 四个实质函数,满足至少两函数要求;没有人工另造缺陷。 +- 所有 git 读取使用只读 show/ls-tree,不 checkout、不改历史/config;本题只读取指定克隆。 + +## 冻结与补全 + +初态完整保留 IPC、线程、对象管理和真实类型/链表头。唯一公开源码变换:删去 ipc.c 文件头历史 Change Logs 注释(保留版权和全部执行代码)。gold 对应同样注释清理后的上游修复版本,未夹带其他修复。其余冻结文件逐字保留。不存在上游 .git、issue/修复链接或新增上游回归测试。 + +| 文件 | 属性 | +| --- | --- | +| LICENSE | 上游冻结 | +| Makefile | 补全 | +| README.md | 补全 | +| docs/synchronization.md | 补全 | +| include/rtconfig.h | 补全 | +| include/rtdebug.h | 上游冻结 | +| include/rtdef.h | 上游冻结 | +| include/rthw.h | 上游冻结 | +| include/rtm.h | 上游冻结 | +| include/rtservice.h | 上游冻结 | +| include/rtthread.h | 上游冻结 | +| port/field_report.c | 补全 | +| port/services.c | 补全 | +| port/services.h | 补全 | +| port/smoke.c | 补全 | +| src/ipc.c | 上游冻结;ipc.c 仅清理历史注释 | +| src/object.c | 上游冻结 | +| src/thread.c | 上游冻结 | + +补全的 rtconfig.h 选择单核静态 mutex、32 级优先级;services.c 提供当前线程身份、就绪链表、无板卡栈地址返回、定时器登记/回调与 libc 包装。真实挂起/恢复与 priority control 使用原 thread.c;所有继承、回退、owner、hold、taken list、pending chain 都使用候选 IPC 实现。服务层不实现这些策略。smoke 只走无 ceiling、无等待的正常路径。field_report 仅打印普通业务调用观察,与根因源码分开。 + +18 个公开文件,candidate_files 仅 src/ipc.c,私有附件为 check.py、support.tar、observer.c。support.tar 是冻结公开支持文件(不含候选文件)的逐字包,正式评分在新临时目录重建,候选不能替换服务层。 + +## 直接相关真实源码规模 + +完整冻结文件提供上下文;下表仅计本题 mutex/ceiling 定位与实际线程等待链的函数区段,不以整个 IPC/线程/对象文件或通用头文件计数。容器内 gcc -E -P 按当前 rtconfig.h 去掉未启用分支后再次统计;不包括注释和空行。所有函数实际在观察驱动的调用链中使用。源码指针见本题 subagent/relevant-functions.json。 + +| 文件及函数 | template 源码行段 | 原源码非空非注释行 | 当前配置启用行 | +| --- | --- | ---: | ---: | +| src/ipc.c _ipc_object_init | 44–50 | 5 | 5 | +| src/ipc.c _ipc_list_suspend | 84–137 | 38 | 38 | +| src/ipc.c _mutex_update_priority | 702–717 | 14 | 14 | +| src/ipc.c _thread_get_mutex_priority | 719–735 | 15 | 15 | +| src/ipc.c _thread_update_priority | 737–785 | 36 | 33 | +| src/ipc.c rt_mutex_init | 816–840 | 14 | 14 | +| src/ipc.c rt_mutex_setprioceiling | 943–958 | 14 | 14 | +| src/ipc.c rt_mutex_getprioceiling | 969–979 | 9 | 9 | +| src/ipc.c _rt_mutex_take | 1101–1292 | 126 | 119 | +| src/ipc.c rt_mutex_take | 1294–1297 | 4 | 4 | +| src/ipc.c rt_mutex_take_interruptible | 1300–1303 | 4 | 4 | +| src/ipc.c rt_mutex_take_killable | 1306–1309 | 4 | 4 | +| src/ipc.c rt_mutex_release | 1346–1464 | 72 | 65 | +| src/thread.c _thread_init | 158–283 | 92 | 39 | +| src/thread.c rt_thread_init | 314–338 | 21 | 21 | +| src/thread.c rt_thread_self | 346–361 | 14 | 5 | +| src/thread.c rt_thread_control | 837–930 | 71 | 44 | +| src/thread.c rt_thread_set_suspend_state | 937–958 | 21 | 21 | +| src/thread.c rt_thread_suspend_with_flag | 976–1024 | 34 | 26 | +| src/thread.c rt_thread_resume | 1041–1079 | 23 | 19 | +| src/thread.c _thread_timeout | 127–156 | 15 | 15 | + +合计原源码 646 行,当前配置启用 528 行:IPC 直接函数 338 行,真实线程函数 190 行。对象管理与头文件不计入这 528 行。这里只作为足够上下文的范围核对,不宣称新上游工程或独立调度器实现。 + +## 缺陷及验证边界 + +1. 已设 ceiling 的首次持有未登记到线程持锁集合,后续多锁操作失去资源约束。 +2. 有效优先级汇总遗漏仍持有 mutex 的 ceiling。 +3. 更改 ceiling 没有更新已有 owner,也没有沿等待链传播。 +4. 重新排列已挂起等待者时,再次请求挂起会失败/断言,导致传播与等待关系不能完成。 + +这是同一上游修复的四处行为,不计四个独立上游修复。所有线程在无信号的单核软件移植层运行;不宣称物理时序、真实抢占调度或外部信号覆盖。参数使用文档有效域和明确的非法 ceiling;不测试未公开的私有布局、mutex 取链方向或内部调用次数。 + +## 判据检查项 ↔ 依据 + +公开工作区依据统一为 template/docs/synchronization.md(平常合同语句各出现一次)。原始来源还包括冻结 documentation/thread/thread.md 的 Thread Priority、documentation/thread-sync/thread-sync.md 的 Mutex、原 include/rtdef.h 结构注释、IPC 原 API 注释;priority ceiling 按 POSIX.1 pthread_mutexattr_getprotocol 的 PRIO_PROTECT 定义,等待链继承按其 PRIO_INHERIT 递归定义整理为 RT-Thread 数字方向。 + +| 检查项 | 公开依据 | 输入覆盖 | +| --- | --- | --- | +| 基础优先级与数字方向、最终回退 | docs/synchronization.md:3、:5 | ordinary、所有释放后的状态 | +| 默认 ceiling、空闲获取、owner/hold | docs/synchronization.md:7 | ordinary、全部首次获取 | +| 重入/逐次释放、错误释放不改所有权 | docs/synchronization.md:9 | ordinary、ceilings | +| 无等待超时、有限与无限等待 | docs/synchronization.md:11 | ordinary、timeout、nested-inheritance | +| 挂起/恢复、释放授予、超时返回和退出竞争 | docs/synchronization.md:13 | timeout、nested-inheritance、donor-withdrawal | +| 多个仍持有 ceiling 的最高优先级与释放组合 | docs/synchronization.md:15 | ceilings、release-order、configured-set | +| 等待链捐赠与配置提高/放松后的传播 | docs/synchronization.md:17 | nested-inheritance、blocked-owner-ceiling | +| 多个等待者按变化后的有效优先级获锁 | docs/synchronization.md:13、:17 | waiter-promoted、waiter-relaxed | +| setter/getter 返回值、0/31 边界、32/255/NULL 非法输入、errno | docs/synchronization.md:19 | ceilings、configured-set | +| 三种接口在无信号时一致 | docs/synchronization.md:21 | 三 variant 的 timeout、nested-inheritance、waiter-* | +| 已挂起等待者的调整不能丢失等待关系 | docs/synchronization.md:23 | nested-inheritance、blocked-owner-ceiling、waiter-* | + +共 11 条映射。期望值由 check.py 对基础优先级、仍持有 ceiling、等待关系建立的小状态模型独立求最低数值优先级;不读取 gold 输出。非墙钟:ucontext 协作调度停在真实 rt_schedule,超时由真实线程定时器回调显式触发。harness 只接命令并打印返回值/线程状态/优先级/errno/owner/hold/ceiling,不含断言或期望。指针身份仅映射为输入 actor ID,未锁定链表实现。 + +所有输入与期望在运行候选前生成;check.py 先写完支持文件,再启动降 UID 的编译器及候选进程,之后不访问候选临时目录。verify.py 逐字复制 rollout/bos_verify.py,隔离探针保证候选读不到 /grader。唯一私有 Python 附件是 check.py。 + +## 样例 + +| 样例 | 预期 | 作用 | +| --- | --- | --- | +| gold | PASS | 上游原修复 | +| valid_fold | PASS | while 遍历逐项合并两个约束,并改用另一方向插入持有链;不依赖 gold 的局部变量和插入顺序 | +| template | FAIL | 上游冻结初态 | +| noop | FAIL | 普通获取直接返回成功但没有建立行为 | +| cheat | FAIL | 只把 owner 当前优先级设为配置值,绕过组合约束 | +| cheat_read_grader | FAIL | 只有读到 /grader/check.py 才保留 gold,否则退出;正式隔离拒绝读取 | +| symptom_only | FAIL | 修好动态配置表象但仍漏登记已配置互斥量 | +| partial_suspend | FAIL | 除重新挂起防护外均为 gold,进入真实 thread.c 运行断言 | +| partial_update | FAIL | 只遗漏已有 owner 的配置传播,真实数值不一致 | +| partial_aggregate | FAIL | 只遗漏 ceiling 汇总,真实数值不一致 | + +全部负例均在固定环境成功构建;FAIL 来自执行行为、校验输出或读取隔离门,未把构建故障当成缺陷证据。 + +## 校准与限制 + +最终 task digest、50 次逐类正式回执、实际 argv 事件、image ID、唯一精确 Docker 名字与后验清理核对见 subagent/report.json。每容器前检查 /home >=10 GiB 与 Docker 盘 >=5 GiB,trace6 固定镜像,无网络,唯一名字且 --rm。使用原 core.calibrate 进程内薄包装,仅添加双盘门禁和实际 --rm argv 记录,不修改平台、不合成回执。保留所有先前校准事实。 + +没有运行真实 Agent;难度 UNMEASURED。全仓库 unittest 由 root 统一执行,本作者只做本题软件闸门与源码/隔离自检。独立审阅由 root 完成,本作者不自行标记 ADMITTED。 diff --git a/tasks/concur-rtthread-mutex-ceilings/support.tar b/tasks/concur-rtthread-mutex-ceilings/support.tar new file mode 100644 index 00000000..9da67204 Binary files /dev/null and b/tasks/concur-rtthread-mutex-ceilings/support.tar differ diff --git a/tasks/concur-rtthread-mutex-ceilings/symptom_only/src/ipc.c b/tasks/concur-rtthread-mutex-ceilings/symptom_only/src/ipc.c new file mode 100644 index 00000000..d8a46518 --- /dev/null +++ b/tasks/concur-rtthread-mutex-ceilings/symptom_only/src/ipc.c @@ -0,0 +1,3756 @@ +/* + * Copyright (c) 2006-2022, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +#include +#include + +#ifndef __on_rt_object_trytake_hook + #define __on_rt_object_trytake_hook(parent) __ON_HOOK_ARGS(rt_object_trytake_hook, (parent)) +#endif +#ifndef __on_rt_object_take_hook + #define __on_rt_object_take_hook(parent) __ON_HOOK_ARGS(rt_object_take_hook, (parent)) +#endif +#ifndef __on_rt_object_put_hook + #define __on_rt_object_put_hook(parent) __ON_HOOK_ARGS(rt_object_put_hook, (parent)) +#endif + +#if defined(RT_USING_HOOK) && defined(RT_HOOK_USING_FUNC_PTR) +extern void (*rt_object_trytake_hook)(struct rt_object *object); +extern void (*rt_object_take_hook)(struct rt_object *object); +extern void (*rt_object_put_hook)(struct rt_object *object); +#endif /* RT_USING_HOOK */ + +/** + * @addtogroup IPC + * @{ + */ + +/** + * @brief This function will initialize an IPC object, such as semaphore, mutex, messagequeue and mailbox. + * + * @note Executing this function will complete an initialization of the suspend thread list of the ipc object. + * + * @param ipc is a pointer to the IPC object. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * When the return value is any other values, it means the initialization failed. + * + * @warning This function can be called from all IPC initialization and creation. + */ +rt_inline rt_err_t _ipc_object_init(struct rt_ipc_object *ipc) +{ + /* initialize ipc object */ + rt_list_init(&(ipc->suspend_thread)); + + return RT_EOK; +} + + +/** + * @brief This function will suspend a thread to a IPC object list. + * + * @param list is a pointer to a suspended thread list of the IPC object. + * + * @param thread is a pointer to the thread object to be suspended. + * + * @param flag is a flag for the thread object to be suspended. It determines how the thread is suspended. + * The flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to use + * RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this semaphore will become non-real-time threads. + * + * @param suspend_flag status flag of the thread to be suspended. + * + * @return Return the operation status. When the return value is RT_EOK, the function is successfully executed. + * When the return value is any other values, it means the initialization failed. + * + * @warning This function can ONLY be called in the thread context, you can use RT_DEBUG_IN_THREAD_CONTEXT to + * check the context. + * In addition, this function is generally called by the following functions: + * rt_sem_take(), rt_mutex_take(), rt_event_recv(), rt_mb_send_wait(), + * rt_mb_recv(), rt_mq_recv(), rt_mq_send_wait() + */ +rt_inline rt_err_t _ipc_list_suspend(rt_list_t *list, + struct rt_thread *thread, + rt_uint8_t flag, + int suspend_flag) +{ + if ((thread->stat & RT_THREAD_SUSPEND_MASK) != RT_THREAD_SUSPEND_MASK) + { + rt_err_t ret = rt_thread_suspend_with_flag(thread, suspend_flag); + + /* suspend thread */ + if (ret != RT_EOK) + { + return ret; + } + } + + switch (flag) + { + case RT_IPC_FLAG_FIFO: + rt_list_insert_before(list, &(thread->tlist)); + break; /* RT_IPC_FLAG_FIFO */ + + case RT_IPC_FLAG_PRIO: + { + struct rt_list_node *n; + struct rt_thread *sthread; + + /* find a suitable position */ + for (n = list->next; n != list; n = n->next) + { + sthread = rt_list_entry(n, struct rt_thread, tlist); + + /* find out */ + if (thread->current_priority < sthread->current_priority) + { + /* insert this thread before the sthread */ + rt_list_insert_before(&(sthread->tlist), &(thread->tlist)); + break; + } + } + + /* + * not found a suitable position, + * append to the end of suspend_thread list + */ + if (n == list) + rt_list_insert_before(list, &(thread->tlist)); + } + break;/* RT_IPC_FLAG_PRIO */ + + default: + RT_ASSERT(0); + break; + } + + return RT_EOK; +} + + +/** + * @brief This function will resume a thread. + * + * @note This function will resume the first thread in the list of a IPC object. + * 1. remove the thread from suspend queue of a IPC object. + * 2. put the thread into system ready queue. + * + * By contrast, the rt_ipc_list_resume_all() function will resume all suspended threads + * in the list of a IPC object. + * + * @param list is a pointer to a suspended thread list of the IPC object. + * + * @return Return the operation status. When the return value is RT_EOK, the function is successfully executed. + * When the return value is any other values, it means this operation failed. + * + * @warning This function is generally called by the following functions: + * rt_sem_release(), rt_mutex_release(), rt_mb_send_wait(), rt_mq_send_wait(), + * rt_mb_urgent(), rt_mb_recv(), rt_mq_urgent(), rt_mq_recv(), + */ +rt_inline rt_err_t _ipc_list_resume(rt_list_t *list) +{ + struct rt_thread *thread; + + /* get thread entry */ + thread = rt_list_entry(list->next, struct rt_thread, tlist); + + thread->error = RT_EOK; + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("resume thread:%s\n", thread->name)); + + /* resume it */ + rt_thread_resume(thread); + + return RT_EOK; +} + + +/** + * @brief This function will resume all suspended threads in the IPC object list, + * including the suspended list of IPC object, and private list of mailbox etc. + * + * @note This function will resume all threads in the IPC object list. + * By contrast, the rt_ipc_list_resume() function will resume a suspended thread in the list of a IPC object. + * + * @param list is a pointer to a suspended thread list of the IPC object. + * + * @return Return the operation status. When the return value is RT_EOK, the function is successfully executed. + * When the return value is any other values, it means this operation failed. + * + */ +rt_inline rt_err_t _ipc_list_resume_all(rt_list_t *list) +{ + struct rt_thread *thread; + rt_base_t level; + + /* wakeup all suspended threads */ + while (!rt_list_isempty(list)) + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* get next suspended thread */ + thread = rt_list_entry(list->next, struct rt_thread, tlist); + /* set error code to RT_ERROR */ + thread->error = -RT_ERROR; + + /* + * resume thread + * In rt_thread_resume function, it will remove current thread from + * suspended list + */ + rt_thread_resume(thread); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + } + + return RT_EOK; +} + +#ifdef RT_USING_SEMAPHORE +/** + * @addtogroup semaphore + * @{ + */ + +/** + * @brief This function will initialize a static semaphore object. + * + * @note For the static semaphore object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_sem_create() function will allocate memory space automatically and initialize + * the semaphore. + * + * @see rt_sem_create() + * + * @param sem is a pointer to the semaphore to initialize. It is assumed that storage for the semaphore will be + * allocated in your application. + * + * @param name is a pointer to the name you would like to give the semaphore. + * + * @param value is the initial value for the semaphore. + * If used to share resources, you should initialize the value as the number of available resources. + * If used to signal the occurrence of an event, you should initialize the value as 0. + * + * @param flag is the semaphore flag, which determines the queuing way of how multiple threads wait + * when the semaphore is not available. + * The semaphore flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this semaphore will become non-real-time threads. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_sem_init(rt_sem_t sem, + const char *name, + rt_uint32_t value, + rt_uint8_t flag) +{ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(value < 0x10000U); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(sem->parent.parent), RT_Object_Class_Semaphore, name); + + /* initialize ipc object */ + _ipc_object_init(&(sem->parent)); + + /* set initial value */ + sem->value = (rt_uint16_t)value; + + /* set parent */ + sem->parent.parent.flag = flag; + + return RT_EOK; +} +RTM_EXPORT(rt_sem_init); + + +/** + * @brief This function will detach a static semaphore object. + * + * @note This function is used to detach a static semaphore object which is initialized by rt_sem_init() function. + * By contrast, the rt_sem_delete() function will delete a semaphore object. + * When the semaphore is successfully detached, it will resume all suspended threads in the semaphore list. + * + * @see rt_sem_delete() + * + * @param sem is a pointer to a semaphore object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the semaphore detach failed. + * + * @warning This function can ONLY detach a static semaphore initialized by the rt_sem_init() function. + * If the semaphore is created by the rt_sem_create() function, you MUST NOT USE this function to detach it, + * ONLY USE the rt_sem_delete() function to complete the deletion. + */ +rt_err_t rt_sem_detach(rt_sem_t sem) +{ + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + RT_ASSERT(rt_object_is_systemobject(&sem->parent.parent)); + + /* wakeup all suspended threads */ + _ipc_list_resume_all(&(sem->parent.suspend_thread)); + + /* detach semaphore object */ + rt_object_detach(&(sem->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_sem_detach); + +#ifdef RT_USING_HEAP +/** + * @brief Creating a semaphore object. + * + * @note For the semaphore object, its memory space is allocated automatically. + * By contrast, the rt_sem_init() function will initialize a static semaphore object. + * + * @see rt_sem_init() + * + * @param name is a pointer to the name you would like to give the semaphore. + * + * @param value is the initial value for the semaphore. + * If used to share resources, you should initialize the value as the number of available resources. + * If used to signal the occurrence of an event, you should initialize the value as 0. + * + * @param flag is the semaphore flag, which determines the queuing way of how multiple threads wait + * when the semaphore is not available. + * The semaphore flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this semaphore will become non-real-time threads. + * + * @return Return a pointer to the semaphore object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can NOT be called in interrupt context. You can use macor RT_DEBUG_NOT_IN_INTERRUPT to check it. + */ +rt_sem_t rt_sem_create(const char *name, rt_uint32_t value, rt_uint8_t flag) +{ + rt_sem_t sem; + + RT_ASSERT(value < 0x10000U); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + sem = (rt_sem_t)rt_object_allocate(RT_Object_Class_Semaphore, name); + if (sem == RT_NULL) + return sem; + + /* initialize ipc object */ + _ipc_object_init(&(sem->parent)); + + /* set initial value */ + sem->value = value; + + /* set parent */ + sem->parent.parent.flag = flag; + + return sem; +} +RTM_EXPORT(rt_sem_create); + + +/** + * @brief This function will delete a semaphore object and release the memory space. + * + * @note This function is used to delete a semaphore object which is created by the rt_sem_create() function. + * By contrast, the rt_sem_detach() function will detach a static semaphore object. + * When the semaphore is successfully deleted, it will resume all suspended threads in the semaphore list. + * + * @see rt_sem_detach() + * + * @param sem is a pointer to a semaphore object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the semaphore detach failed. + * + * @warning This function can ONLY delete a semaphore initialized by the rt_sem_create() function. + * If the semaphore is initialized by the rt_sem_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_sem_detach() function to complete the detachment. + */ +rt_err_t rt_sem_delete(rt_sem_t sem) +{ + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + RT_ASSERT(rt_object_is_systemobject(&sem->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* wakeup all suspended threads */ + _ipc_list_resume_all(&(sem->parent.suspend_thread)); + + /* delete semaphore object */ + rt_object_delete(&(sem->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_sem_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will take a semaphore, if the semaphore is unavailable, the thread shall wait for + * the semaphore up to a specified time. + * + * @note When this function is called, the count value of the sem->value will decrease 1 until it is equal to 0. + * When the sem->value is 0, it means that the semaphore is unavailable. At this time, it will suspend the + * thread preparing to take the semaphore. + * On the contrary, the rt_sem_release() function will increase the count value of sem->value by 1 each time. + * + * @see rt_sem_trytake() + * + * @param sem is a pointer to a semaphore object. + * + * @param timeout is a timeout period (unit: an OS tick). If the semaphore is unavailable, the thread will wait for + * the semaphore up to the amount of time specified by this parameter. + * + * NOTE: + * If use Macro RT_WAITING_FOREVER to set this parameter, which means that when the + * message is unavailable in the queue, the thread will be waiting forever. + * If use macro RT_WAITING_NO to set this parameter, which means that this + * function is non-blocking and will return immediately. + * + * @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 semaphore take failed. + * + * @warning This function can ONLY be called in the thread context. It MUST NOT BE called in interrupt context. + */ +static rt_err_t _rt_sem_take(rt_sem_t sem, rt_int32_t timeout, int suspend_flag) +{ + rt_base_t level; + struct rt_thread *thread; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(sem->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("thread %s take sem:%s, which value is: %d\n", + rt_thread_self()->name, + ((struct rt_object *)sem)->name, + sem->value)); + + if (sem->value > 0) + { + /* semaphore is available */ + sem->value --; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + } + else + { + /* no waiting, return with timeout */ + if (timeout == 0) + { + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + else + { + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE); + + /* semaphore is unavailable, push to suspend list */ + /* get current thread */ + thread = rt_thread_self(); + + /* reset thread error number */ + thread->error = -RT_EINTR; + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("sem take: suspend thread - %s\n", + thread->name)); + + /* suspend thread */ + ret = _ipc_list_suspend(&(sem->parent.suspend_thread), + thread, + sem->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + RT_DEBUG_LOG(RT_DEBUG_IPC, ("set thread:%s to timer list\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do schedule */ + rt_schedule(); + + if (thread->error != RT_EOK) + { + return thread->error; + } + } + } + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(sem->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_sem_take(rt_sem_t sem, rt_int32_t time) +{ + return _rt_sem_take(sem, time, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_sem_take); + +rt_err_t rt_sem_take_interruptible(rt_sem_t sem, rt_int32_t time) +{ + return _rt_sem_take(sem, time, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_sem_take_interruptible); + +rt_err_t rt_sem_take_killable(rt_sem_t sem, rt_int32_t time) +{ + return _rt_sem_take(sem, time, RT_KILLABLE); +} +RTM_EXPORT(rt_sem_take_killable); + +/** + * @brief This function will try to take a semaphore, if the semaphore is unavailable, the thread returns immediately. + * + * @note This function is very similar to the rt_sem_take() function, when the semaphore is not available, + * the rt_sem_trytake() function will return immediately without waiting for a timeout. + * In other words, rt_sem_trytake(sem) has the same effect as rt_sem_take(sem, 0). + * + * @see rt_sem_take() + * + * @param sem is a pointer to a semaphore object. + * + * @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 semaphore take failed. + */ +rt_err_t rt_sem_trytake(rt_sem_t sem) +{ + return rt_sem_take(sem, RT_WAITING_NO); +} +RTM_EXPORT(rt_sem_trytake); + + +/** + * @brief This function will release a semaphore. If there is thread suspended on the semaphore, it will get resumed. + * + * @note If there are threads suspended on this semaphore, the first thread in the list of this semaphore object + * will be resumed, and a thread scheduling (rt_schedule) will be executed. + * If no threads are suspended on this semaphore, the count value sem->value of this semaphore will increase by 1. + * + * @param sem is a pointer to a semaphore object. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the semaphore release failed. + */ +rt_err_t rt_sem_release(rt_sem_t sem) +{ + rt_base_t level; + rt_bool_t need_schedule; + + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(sem->parent.parent))); + + need_schedule = RT_FALSE; + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("thread %s releases sem:%s, which value is: %d\n", + rt_thread_self()->name, + ((struct rt_object *)sem)->name, + sem->value)); + + if (!rt_list_isempty(&sem->parent.suspend_thread)) + { + /* resume the suspended thread */ + _ipc_list_resume(&(sem->parent.suspend_thread)); + need_schedule = RT_TRUE; + } + else + { + if(sem->value < RT_SEM_VALUE_MAX) + { + sem->value ++; /* increase value */ + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* resume a thread, re-schedule */ + if (need_schedule == RT_TRUE) + rt_schedule(); + + return RT_EOK; +} +RTM_EXPORT(rt_sem_release); + + +/** + * @brief This function will set some extra attributions of a semaphore object. + * + * @note Currently this function only supports the RT_IPC_CMD_RESET command to reset the semaphore. + * + * @param sem is a pointer to a semaphore object. + * + * @param cmd is a command word used to configure some attributions of the semaphore. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_sem_control(rt_sem_t sem, int cmd, void *arg) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + + if (cmd == RT_IPC_CMD_RESET) + { + rt_ubase_t value; + + /* get value */ + value = (rt_ubase_t)arg; + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* resume all waiting thread */ + _ipc_list_resume_all(&sem->parent.suspend_thread); + + /* set new value */ + sem->value = (rt_uint16_t)value; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_sem_control); + +/**@}*/ +#endif /* RT_USING_SEMAPHORE */ + +#ifdef RT_USING_MUTEX +/* iterate over each suspended thread to update highest priority in pending threads */ +rt_inline rt_uint8_t _mutex_update_priority(struct rt_mutex *mutex) +{ + struct rt_thread *thread; + + if (!rt_list_isempty(&mutex->parent.suspend_thread)) + { + thread = rt_list_entry(mutex->parent.suspend_thread.next, struct rt_thread, tlist); + mutex->priority = thread->current_priority; + } + else + { + mutex->priority = 0xff; + } + + return mutex->priority; +} + +/* get highest priority inside its taken object and its init priority */ +rt_inline rt_uint8_t _thread_get_mutex_priority(struct rt_thread* thread) +{ + rt_list_t *node = RT_NULL; + struct rt_mutex *mutex = RT_NULL; + rt_uint8_t priority = thread->init_priority; + + rt_list_for_each(node, &(thread->taken_object_list)) + { + mutex = rt_list_entry(node, struct rt_mutex, taken_list); + rt_uint8_t mutex_prio = mutex->priority; + /* prio at least be priority ceiling */ + mutex_prio = mutex_prio < mutex->ceiling_priority ? mutex_prio : mutex->ceiling_priority; + + if (priority > mutex_prio) + { + priority = mutex_prio; + } + } + + return priority; +} + +/* update priority of target thread and the thread suspended it if any */ +rt_inline void _thread_update_priority(struct rt_thread *thread, rt_uint8_t priority, int suspend_flag) +{ + rt_err_t ret; + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("thread:%s priority -> %d\n", thread->name, priority)); + + /* change priority of the thread */ + rt_thread_control(thread, + RT_THREAD_CTRL_CHANGE_PRIORITY, + &priority); + + if ((thread->stat & RT_THREAD_SUSPEND_MASK) == RT_THREAD_SUSPEND_MASK) + { + /* whether change the priority of taken mutex */ + struct rt_object* pending_obj = thread->pending_object; + + if (pending_obj && rt_object_get_type(pending_obj) == RT_Object_Class_Mutex) + { + rt_uint8_t mutex_priority; + struct rt_mutex* pending_mutex = (struct rt_mutex *)pending_obj; + + /* re-insert thread to suspended thread list */ + rt_list_remove(&(thread->tlist)); + + ret = _ipc_list_suspend(&(pending_mutex->parent.suspend_thread), + thread, + pending_mutex->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + /* TODO */ + return ; + } + + /* update priority */ + _mutex_update_priority(pending_mutex); + /* change the priority of mutex owner thread */ + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("mutex: %s priority -> %d\n", pending_mutex->parent.parent.name, + pending_mutex->priority)); + + mutex_priority = _thread_get_mutex_priority(pending_mutex->owner); + if (mutex_priority != pending_mutex->owner->current_priority) + { + _thread_update_priority(pending_mutex->owner, mutex_priority, suspend_flag); + } + } + } +} + +/** + * @addtogroup mutex + * @{ + */ + +/** + * @brief Initialize a static mutex object. + * + * @note For the static mutex object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_mutex_create() function will automatically allocate memory space + * and initialize the mutex. + * + * @see rt_mutex_create() + * + * @param mutex is a pointer to the mutex to initialize. It is assumed that storage for the mutex will be + * allocated in your application. + * + * @param name is a pointer to the name that given to the mutex. + * + * @param flag is the mutex flag, which determines the queuing way of how multiple threads wait + * when the mutex is not available. + * NOTE: This parameter has been obsoleted. It can be RT_IPC_FLAG_PRIO, RT_IPC_FLAG_FIFO or RT_NULL. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_mutex_init(rt_mutex_t mutex, const char *name, rt_uint8_t flag) +{ + /* flag parameter has been obsoleted */ + RT_UNUSED(flag); + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + + /* initialize object */ + rt_object_init(&(mutex->parent.parent), RT_Object_Class_Mutex, name); + + /* initialize ipc object */ + _ipc_object_init(&(mutex->parent)); + + mutex->owner = RT_NULL; + mutex->priority = 0xFF; + mutex->hold = 0; + mutex->ceiling_priority = 0xFF; + rt_list_init(&(mutex->taken_list)); + + /* flag can only be RT_IPC_FLAG_PRIO. RT_IPC_FLAG_FIFO cannot solve the unbounded priority inversion problem */ + mutex->parent.parent.flag = RT_IPC_FLAG_PRIO; + + return RT_EOK; +} +RTM_EXPORT(rt_mutex_init); + + +/** + * @brief This function will detach a static mutex object. + * + * @note This function is used to detach a static mutex object which is initialized by rt_mutex_init() function. + * By contrast, the rt_mutex_delete() function will delete a mutex object. + * When the mutex is successfully detached, it will resume all suspended threads in the mutex list. + * + * @see rt_mutex_delete() + * + * @param mutex is a pointer to a mutex object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the mutex detach failed. + * + * @warning This function can ONLY detach a static mutex initialized by the rt_mutex_init() function. + * If the mutex is created by the rt_mutex_create() function, you MUST NOT USE this function to detach it, + * ONLY USE the rt_mutex_delete() function to complete the deletion. + */ +rt_err_t rt_mutex_detach(rt_mutex_t mutex) +{ + rt_ubase_t level; + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + RT_ASSERT(rt_object_is_systemobject(&mutex->parent.parent)); + + level = rt_hw_interrupt_disable(); + /* wakeup all suspended threads */ + _ipc_list_resume_all(&(mutex->parent.suspend_thread)); + /* remove mutex from thread's taken list */ + rt_list_remove(&mutex->taken_list); + rt_hw_interrupt_enable(level); + + /* detach mutex object */ + rt_object_detach(&(mutex->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mutex_detach); + +/* drop a thread from the suspend list of mutex */ + +/** + * @brief drop a thread from the suspend list of mutex + * + * @param mutex is a pointer to a mutex object. + * @param thread is the thread should be dropped from mutex. + */ +void rt_mutex_drop_thread(rt_mutex_t mutex, rt_thread_t thread) +{ + rt_uint8_t priority; + rt_bool_t need_update = RT_FALSE; + + rt_list_remove(&(thread->tlist)); + + /* should change the priority of mutex owner thread */ + if (mutex->owner->current_priority == thread->current_priority) + need_update = RT_TRUE; + + /* update the priority of mutex */ + if (!rt_list_isempty(&mutex->parent.suspend_thread)) + { + /* more thread suspended in the list */ + struct rt_thread *th; + + th = rt_list_entry(mutex->parent.suspend_thread.next, + struct rt_thread, + tlist); + /* update the priority of mutex */ + mutex->priority = th->current_priority; + } + else + { + /* set mutex priority to maximal priority */ + mutex->priority = 0xff; + } + + /* try to change the priority of mutex owner thread */ + if (need_update) + { + /* get the maximal priority of mutex in thread */ + priority = _thread_get_mutex_priority(mutex->owner); + if (priority != mutex->owner->current_priority) + { + _thread_update_priority(mutex->owner, priority, RT_UNINTERRUPTIBLE); + } + } +} + + +/** + * @brief set the prioceiling attribute of the mutex. + * + * @param mutex is a pointer to a mutex object. + * @param priority is the priority should be set to mutex. + * + * @return return the old priority ceiling + */ +rt_uint8_t rt_mutex_setprioceiling(rt_mutex_t mutex, rt_uint8_t priority) +{ + rt_uint8_t ret_priority = 0xFF; + + if ((mutex) && (priority < RT_THREAD_PRIORITY_MAX)) + { + /* critical section here if multiple updates to one mutex happen */ + rt_ubase_t level = rt_hw_interrupt_disable(); + ret_priority = mutex->ceiling_priority; + mutex->ceiling_priority = priority; + if (mutex->owner) + { + rt_uint8_t priority = _thread_get_mutex_priority(mutex->owner); + if (priority != mutex->owner->current_priority) + _thread_update_priority(mutex->owner, priority, RT_UNINTERRUPTIBLE); + } + rt_hw_interrupt_enable(level); + } + else + { + rt_set_errno(-RT_EINVAL); + } + + return ret_priority; +} +RTM_EXPORT(rt_mutex_setprioceiling); + + +/** + * @brief set the prioceiling attribute of the mutex. + * + * @param mutex is a pointer to a mutex object. + * + * @return return the current priority ceiling of the mutex. + */ +rt_uint8_t rt_mutex_getprioceiling(rt_mutex_t mutex) +{ + rt_uint8_t prio = 0xFF; + + if (mutex) + { + prio = mutex->ceiling_priority; + } + + return prio; +} +RTM_EXPORT(rt_mutex_getprioceiling); + + +#ifdef RT_USING_HEAP +/** + * @brief This function will create a mutex object. + * + * @note For the mutex object, its memory space is automatically allocated. + * By contrast, the rt_mutex_init() function will initialize a static mutex object. + * + * @see rt_mutex_init() + * + * @param name is a pointer to the name that given to the mutex. + * + * @param flag is the mutex flag, which determines the queuing way of how multiple threads wait + * when the mutex is not available. + * NOTE: This parameter has been obsoleted. It can be RT_IPC_FLAG_PRIO, RT_IPC_FLAG_FIFO or RT_NULL. + * + * @return Return a pointer to the mutex object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_mutex_t rt_mutex_create(const char *name, rt_uint8_t flag) +{ + struct rt_mutex *mutex; + + /* flag parameter has been obsoleted */ + RT_UNUSED(flag); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + mutex = (rt_mutex_t)rt_object_allocate(RT_Object_Class_Mutex, name); + if (mutex == RT_NULL) + return mutex; + + /* initialize ipc object */ + _ipc_object_init(&(mutex->parent)); + + mutex->owner = RT_NULL; + mutex->priority = 0xFF; + mutex->hold = 0; + mutex->ceiling_priority = 0xFF; + rt_list_init(&(mutex->taken_list)); + + /* flag can only be RT_IPC_FLAG_PRIO. RT_IPC_FLAG_FIFO cannot solve the unbounded priority inversion problem */ + mutex->parent.parent.flag = RT_IPC_FLAG_PRIO; + + return mutex; +} +RTM_EXPORT(rt_mutex_create); + + +/** + * @brief This function will delete a mutex object and release this memory space. + * + * @note This function is used to delete a mutex object which is created by the rt_mutex_create() function. + * By contrast, the rt_mutex_detach() function will detach a static mutex object. + * When the mutex is successfully deleted, it will resume all suspended threads in the mutex list. + * + * @see rt_mutex_detach() + * + * @param mutex is a pointer to a mutex object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mutex detach failed. + * + * @warning This function can ONLY delete a mutex initialized by the rt_mutex_create() function. + * If the mutex is initialized by the rt_mutex_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_mutex_detach() function to complete the detachment. + */ +rt_err_t rt_mutex_delete(rt_mutex_t mutex) +{ + rt_ubase_t level; + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + RT_ASSERT(rt_object_is_systemobject(&mutex->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + level = rt_hw_interrupt_disable(); + /* wakeup all suspended threads */ + _ipc_list_resume_all(&(mutex->parent.suspend_thread)); + /* remove mutex from thread's taken list */ + rt_list_remove(&mutex->taken_list); + rt_hw_interrupt_enable(level); + + /* delete mutex object */ + rt_object_delete(&(mutex->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mutex_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will take a mutex, if the mutex is unavailable, the thread shall wait for + * the mutex up to a specified time. + * + * @note When this function is called, the count value of the mutex->value will decrease 1 until it is equal to 0. + * When the mutex->value is 0, it means that the mutex is unavailable. At this time, it will suspend the + * thread preparing to take the mutex. + * On the contrary, the rt_mutex_release() function will increase the count value of mutex->value by 1 each time. + * + * @see rt_mutex_trytake() + * + * @param mutex is a pointer to a mutex object. + * + * @param timeout is a timeout period (unit: an OS tick). If the mutex is unavailable, the thread will wait for + * the mutex up to the amount of time specified by the argument. + * NOTE: Generally, we set this parameter to RT_WAITING_FOREVER, which means that when the mutex is unavailable, + * the thread will be waitting forever. + * + * @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 mutex take failed. + * + * @warning This function can ONLY be called in the thread context. It MUST NOT BE called in interrupt context. + */ +static rt_err_t _rt_mutex_take(rt_mutex_t mutex, rt_int32_t timeout, int suspend_flag) +{ + rt_base_t level; + struct rt_thread *thread; + rt_err_t ret; + + /* this function must not be used in interrupt even if time = 0 */ + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE); + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + + /* get current thread */ + thread = rt_thread_self(); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(mutex->parent.parent))); + + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("mutex_take: current thread %s, hold: %d\n", + thread->name, mutex->hold)); + + /* reset thread error */ + thread->error = RT_EOK; + + if (mutex->owner == thread) + { + if(mutex->hold < RT_MUTEX_HOLD_MAX) + { + /* it's the same thread */ + mutex->hold ++; + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + } + else + { + /* whether the mutex has owner thread. */ + if (mutex->owner == RT_NULL) + { + /* set mutex owner and original priority */ + mutex->owner = thread; + mutex->priority = 0xff; + mutex->hold = 1; + + if (mutex->ceiling_priority != 0xFF) + { + /* set the priority of thread to the ceiling priority */ + if (mutex->ceiling_priority < mutex->owner->current_priority) + _thread_update_priority(mutex->owner, mutex->ceiling_priority, suspend_flag); + } + + if (mutex->ceiling_priority == 0xFF) + { + rt_list_insert_after(&thread->taken_object_list, &mutex->taken_list); + } + } + else + { + /* no waiting, return with timeout */ + if (timeout == 0) + { + /* set error as timeout */ + thread->error = -RT_ETIMEOUT; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + else + { + rt_uint8_t priority = thread->current_priority; + + /* mutex is unavailable, push to suspend list */ + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mutex_take: suspend thread: %s\n", + thread->name)); + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mutex->parent.suspend_thread), + thread, + mutex->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* set pending object in thread to this mutex */ + thread->pending_object = &(mutex->parent.parent); + + /* update the priority level of mutex */ + if (priority < mutex->priority) + { + mutex->priority = priority; + if (mutex->priority < mutex->owner->current_priority) + { + _thread_update_priority(mutex->owner, priority, RT_UNINTERRUPTIBLE); /* TODO */ + } + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("mutex_take: start the timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do schedule */ + rt_schedule(); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + if (thread->error == RT_EOK) + { + /* get mutex successfully */ + } + else + { + /* the mutex has not been taken and thread has detach from the pending list. */ + + rt_bool_t need_update = RT_FALSE; + + /* should change the priority of mutex owner thread */ + if (mutex->owner->current_priority == thread->current_priority) + need_update = RT_TRUE; + + /* update the priority of mutex */ + if (!rt_list_isempty(&mutex->parent.suspend_thread)) + { + /* more thread suspended in the list */ + struct rt_thread *th; + + th = rt_list_entry(mutex->parent.suspend_thread.next, + struct rt_thread, + tlist); + /* update the priority of mutex */ + mutex->priority = th->current_priority; + } + else + { + /* set mutex priority to maximal priority */ + mutex->priority = 0xff; + } + + /* try to change the priority of mutex owner thread */ + if (need_update) + { + /* get the maximal priority of mutex in thread */ + priority = _thread_get_mutex_priority(mutex->owner); + if (priority != mutex->owner->current_priority) + { + _thread_update_priority(mutex->owner, priority, RT_UNINTERRUPTIBLE); + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* return error */ + return thread->error; + } + } + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mutex->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_mutex_take(rt_mutex_t mutex, rt_int32_t time) +{ + return _rt_mutex_take(mutex, time, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mutex_take); + +rt_err_t rt_mutex_take_interruptible(rt_mutex_t mutex, rt_int32_t time) +{ + return _rt_mutex_take(mutex, time, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mutex_take_interruptible); + +rt_err_t rt_mutex_take_killable(rt_mutex_t mutex, rt_int32_t time) +{ + return _rt_mutex_take(mutex, time, RT_KILLABLE); +} +RTM_EXPORT(rt_mutex_take_killable); + +/** + * @brief This function will try to take a mutex, if the mutex is unavailable, the thread returns immediately. + * + * @note This function is very similar to the rt_mutex_take() function, when the mutex is not available, + * except that rt_mutex_trytake() will return immediately without waiting for a timeout + * when the mutex is not available. + * In other words, rt_mutex_trytake(mutex) has the same effect as rt_mutex_take(mutex, 0). + * + * @see rt_mutex_take() + * + * @param mutex is a pointer to a mutex object. + * + * @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 mutex take failed. + */ +rt_err_t rt_mutex_trytake(rt_mutex_t mutex) +{ + return rt_mutex_take(mutex, RT_WAITING_NO); +} +RTM_EXPORT(rt_mutex_trytake); + + +/** + * @brief This function will release a mutex. If there is thread suspended on the mutex, the thread will be resumed. + * + * @note If there are threads suspended on this mutex, the first thread in the list of this mutex object + * will be resumed, and a thread scheduling (rt_schedule) will be executed. + * If no threads are suspended on this mutex, the count value mutex->value of this mutex will increase by 1. + * + * @param mutex is a pointer to a mutex object. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mutex release failed. + */ +rt_err_t rt_mutex_release(rt_mutex_t mutex) +{ + rt_base_t level; + struct rt_thread *thread; + rt_bool_t need_schedule; + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + + need_schedule = RT_FALSE; + + /* only thread could release mutex because we need test the ownership */ + RT_DEBUG_IN_THREAD_CONTEXT; + + /* get current thread */ + thread = rt_thread_self(); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("mutex_release:current thread %s, hold: %d\n", + thread->name, mutex->hold)); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mutex->parent.parent))); + + /* mutex only can be released by owner */ + if (thread != mutex->owner) + { + thread->error = -RT_ERROR; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_ERROR; + } + + /* decrease hold */ + mutex->hold --; + /* if no hold */ + if (mutex->hold == 0) + { + /* remove mutex from thread's taken list */ + rt_list_remove(&mutex->taken_list); + + /* whether change the thread priority */ + if ((mutex->ceiling_priority != 0xFF) || (thread->current_priority == mutex->priority)) + { + rt_uint8_t priority = 0xff; + + /* get the highest priority in the taken list of thread */ + priority = _thread_get_mutex_priority(thread); + + rt_thread_control(thread, + RT_THREAD_CTRL_CHANGE_PRIORITY, + &priority); + + need_schedule = RT_TRUE; + } + + /* wakeup suspended thread */ + if (!rt_list_isempty(&mutex->parent.suspend_thread)) + { + /* get the first suspended thread */ + struct rt_thread *next_thread = rt_list_entry(mutex->parent.suspend_thread.next, + struct rt_thread, + tlist); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mutex_release: resume thread: %s\n", + next_thread->name)); + + /* remove the thread from the suspended list of mutex */ + rt_list_remove(&(next_thread->tlist)); + + /* set new owner and put mutex into taken list of thread */ + mutex->owner = next_thread; + mutex->hold = 1; + rt_list_insert_after(&next_thread->taken_object_list, &mutex->taken_list); + /* cleanup pending object */ + next_thread->pending_object = RT_NULL; + + /* resume thread */ + rt_thread_resume(next_thread); + + /* update mutex priority */ + if (!rt_list_isempty(&(mutex->parent.suspend_thread))) + { + struct rt_thread *th; + + th = rt_list_entry(mutex->parent.suspend_thread.next, + struct rt_thread, + tlist); + mutex->priority = th->current_priority; + } + else + { + mutex->priority = 0xff; + } + + need_schedule = RT_TRUE; + } + else + { + /* clear owner */ + mutex->owner = RT_NULL; + mutex->priority = 0xff; + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* perform a schedule */ + if (need_schedule == RT_TRUE) + rt_schedule(); + + return RT_EOK; +} +RTM_EXPORT(rt_mutex_release); + + +/** + * @brief This function will set some extra attributions of a mutex object. + * + * @note Currently this function does not implement the control function. + * + * @param mutex is a pointer to a mutex object. + * + * @param cmd is a command word used to configure some attributions of the mutex. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_mutex_control(rt_mutex_t mutex, int cmd, void *arg) +{ + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + + return -RT_ERROR; +} +RTM_EXPORT(rt_mutex_control); + +/**@}*/ +#endif /* RT_USING_MUTEX */ + +#ifdef RT_USING_EVENT +/** + * @addtogroup event + * @{ + */ + +/** + * @brief The function will initialize a static event object. + * + * @note For the static event object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_event_create() function will allocate memory space automatically + * and initialize the event. + * + * @see rt_event_create() + * + * @param event is a pointer to the event to initialize. It is assumed that storage for the event + * will be allocated in your application. + * + * @param name is a pointer to the name that given to the event. + * + * @param flag is the event flag, which determines the queuing way of how multiple threads wait + * when the event is not available. + * The event flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this event will become non-real-time threads. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_event_init(rt_event_t event, const char *name, rt_uint8_t flag) +{ + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(event->parent.parent), RT_Object_Class_Event, name); + + /* set parent flag */ + event->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(event->parent)); + + /* initialize event */ + event->set = 0; + + return RT_EOK; +} +RTM_EXPORT(rt_event_init); + + +/** + * @brief This function will detach a static event object. + * + * @note This function is used to detach a static event object which is initialized by rt_event_init() function. + * By contrast, the rt_event_delete() function will delete an event object. + * When the event is successfully detached, it will resume all suspended threads in the event list. + * + * @see rt_event_delete() + * + * @param event is a pointer to an event object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the event detach failed. + * + * @warning This function can ONLY detach a static event initialized by the rt_event_init() function. + * If the event is created by the rt_event_create() function, you MUST NOT USE this function to detach it, + * ONLY USE the rt_event_delete() function to complete the deletion. + */ +rt_err_t rt_event_detach(rt_event_t event) +{ + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + RT_ASSERT(rt_object_is_systemobject(&event->parent.parent)); + + /* resume all suspended thread */ + _ipc_list_resume_all(&(event->parent.suspend_thread)); + + /* detach event object */ + rt_object_detach(&(event->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_event_detach); + +#ifdef RT_USING_HEAP +/** + * @brief Creating an event object. + * + * @note For the event object, its memory space is allocated automatically. + * By contrast, the rt_event_init() function will initialize a static event object. + * + * @see rt_event_init() + * + * @param name is a pointer to the name that given to the event. + * + * @param flag is the event flag, which determines the queuing way of how multiple threads wait when the event + * is not available. + * The event flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this event will become non-real-time threads. + * + * @return Return a pointer to the event object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_event_t rt_event_create(const char *name, rt_uint8_t flag) +{ + rt_event_t event; + + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + event = (rt_event_t)rt_object_allocate(RT_Object_Class_Event, name); + if (event == RT_NULL) + return event; + + /* set parent */ + event->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(event->parent)); + + /* initialize event */ + event->set = 0; + + return event; +} +RTM_EXPORT(rt_event_create); + + +/** + * @brief This function will delete an event object and release the memory space. + * + * @note This function is used to delete an event object which is created by the rt_event_create() function. + * By contrast, the rt_event_detach() function will detach a static event object. + * When the event is successfully deleted, it will resume all suspended threads in the event list. + * + * @see rt_event_detach() + * + * @param event is a pointer to an event object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the event detach failed. + * + * @warning This function can ONLY delete an event initialized by the rt_event_create() function. + * If the event is initialized by the rt_event_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_event_detach() function to complete the detachment. + */ +rt_err_t rt_event_delete(rt_event_t event) +{ + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + RT_ASSERT(rt_object_is_systemobject(&event->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* resume all suspended thread */ + _ipc_list_resume_all(&(event->parent.suspend_thread)); + + /* delete event object */ + rt_object_delete(&(event->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_event_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will send an event to the event object. + * If there is a thread suspended on the event, the thread will be resumed. + * + * @note When using this function, you need to use the parameter (set) to specify the event flag of the event object, + * then the function will traverse the list of suspended threads waiting on the event object. + * If there is a thread suspended on the event, and the thread's event_info and the event flag of + * the current event object matches, the thread will be resumed. + * + * @param event is a pointer to the event object to be sent. + * + * @param set is a flag that you will set for this event's flag. + * You can set an event flag, or you can set multiple flags through OR logic operation. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the event detach failed. + */ +rt_err_t rt_event_send(rt_event_t event, rt_uint32_t set) +{ + struct rt_list_node *n; + struct rt_thread *thread; + rt_base_t level; + rt_base_t status; + rt_bool_t need_schedule; + + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + + if (set == 0) + return -RT_ERROR; + + need_schedule = RT_FALSE; + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* set event */ + event->set |= set; + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(event->parent.parent))); + + if (!rt_list_isempty(&event->parent.suspend_thread)) + { + /* search thread list to resume thread */ + n = event->parent.suspend_thread.next; + while (n != &(event->parent.suspend_thread)) + { + /* get thread */ + thread = rt_list_entry(n, struct rt_thread, tlist); + + status = -RT_ERROR; + if (thread->event_info & RT_EVENT_FLAG_AND) + { + if ((thread->event_set & event->set) == thread->event_set) + { + /* received an AND event */ + status = RT_EOK; + } + } + else if (thread->event_info & RT_EVENT_FLAG_OR) + { + if (thread->event_set & event->set) + { + /* save the received event set */ + thread->event_set = thread->event_set & event->set; + + /* received an OR event */ + status = RT_EOK; + } + } + else + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EINVAL; + } + + /* move node to the next */ + n = n->next; + + /* condition is satisfied, resume thread */ + if (status == RT_EOK) + { + /* clear event */ + if (thread->event_info & RT_EVENT_FLAG_CLEAR) + event->set &= ~thread->event_set; + + /* resume thread, and thread list breaks out */ + rt_thread_resume(thread); + thread->error = RT_EOK; + + /* need do a scheduling */ + need_schedule = RT_TRUE; + } + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do a schedule */ + if (need_schedule == RT_TRUE) + rt_schedule(); + + return RT_EOK; +} +RTM_EXPORT(rt_event_send); + + +/** + * @brief This function will receive an event from event object. if the event is unavailable, the thread shall wait for + * the event up to a specified time. + * + * @note If there are threads suspended on this semaphore, the first thread in the list of this semaphore object + * will be resumed, and a thread scheduling (rt_schedule) will be executed. + * If no threads are suspended on this semaphore, the count value sem->value of this semaphore will increase by 1. + * + * @param event is a pointer to the event object to be received. + * + * @param set is a flag that you will set for this event's flag. + * You can set an event flag, or you can set multiple flags through OR logic operation. + * + * @param option is the option of this receiving event, it indicates how the receiving event is operated. + * The option can be one or more of the following values, When selecting multiple values,use logical OR to operate. + * (NOTE: RT_EVENT_FLAG_OR and RT_EVENT_FLAG_AND can only select one): + * + * + * RT_EVENT_FLAG_OR The thread select to use logical OR to receive the event. + * + * RT_EVENT_FLAG_AND The thread select to use logical OR to receive the event. + * + * RT_EVENT_FLAG_CLEAR When the thread receives the corresponding event, the function + * determines whether to clear the event flag. + * + * @param timeout is a timeout period (unit: an OS tick). + * + * @param recved is a pointer to the received event. If you don't care about this value, you can use RT_NULL to set. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the semaphore release failed. + */ +static rt_err_t _rt_event_recv(rt_event_t event, + rt_uint32_t set, + rt_uint8_t option, + rt_int32_t timeout, + rt_uint32_t *recved, + int suspend_flag) +{ + struct rt_thread *thread; + rt_base_t level; + rt_base_t status; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE); + + if (set == 0) + return -RT_ERROR; + + /* initialize status */ + status = -RT_ERROR; + /* get current thread */ + thread = rt_thread_self(); + /* reset thread error */ + thread->error = -RT_EINTR; + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(event->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* check event set */ + if (option & RT_EVENT_FLAG_AND) + { + if ((event->set & set) == set) + status = RT_EOK; + } + else if (option & RT_EVENT_FLAG_OR) + { + if (event->set & set) + status = RT_EOK; + } + else + { + /* either RT_EVENT_FLAG_AND or RT_EVENT_FLAG_OR should be set */ + RT_ASSERT(0); + } + + if (status == RT_EOK) + { + thread->error = RT_EOK; + + /* set received event */ + if (recved) + *recved = (event->set & set); + + /* fill thread event info */ + thread->event_set = (event->set & set); + thread->event_info = option; + + /* received event */ + if (option & RT_EVENT_FLAG_CLEAR) + event->set &= ~set; + } + else if (timeout == 0) + { + /* no waiting */ + thread->error = -RT_ETIMEOUT; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + else + { + /* fill thread event info */ + thread->event_set = set; + thread->event_info = option; + + /* put thread to suspended thread list */ + ret = _ipc_list_suspend(&(event->parent.suspend_thread), + thread, + event->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* if there is a waiting timeout, active thread timer */ + if (timeout > 0) + { + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do a schedule */ + rt_schedule(); + + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* received an event, disable interrupt to protect */ + level = rt_hw_interrupt_disable(); + + /* set received event */ + if (recved) + *recved = thread->event_set; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(event->parent.parent))); + + return thread->error; +} + +rt_err_t rt_event_recv(rt_event_t event, + rt_uint32_t set, + rt_uint8_t option, + rt_int32_t timeout, + rt_uint32_t *recved) +{ + return _rt_event_recv(event, set, option, timeout, recved, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_event_recv); + +rt_err_t rt_event_recv_interruptible(rt_event_t event, + rt_uint32_t set, + rt_uint8_t option, + rt_int32_t timeout, + rt_uint32_t *recved) +{ + return _rt_event_recv(event, set, option, timeout, recved, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_event_recv_interruptible); + +rt_err_t rt_event_recv_killable(rt_event_t event, + rt_uint32_t set, + rt_uint8_t option, + rt_int32_t timeout, + rt_uint32_t *recved) +{ + return _rt_event_recv(event, set, option, timeout, recved, RT_KILLABLE); +} +RTM_EXPORT(rt_event_recv_killable); +/** + * @brief This function will set some extra attributions of an event object. + * + * @note Currently this function only supports the RT_IPC_CMD_RESET command to reset the event. + * + * @param event is a pointer to an event object. + * + * @param cmd is a command word used to configure some attributions of the event. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_event_control(rt_event_t event, int cmd, void *arg) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + + if (cmd == RT_IPC_CMD_RESET) + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* resume all waiting thread */ + _ipc_list_resume_all(&event->parent.suspend_thread); + + /* initialize event set */ + event->set = 0; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_event_control); + +/**@}*/ +#endif /* RT_USING_EVENT */ + +#ifdef RT_USING_MAILBOX +/** + * @addtogroup mailbox + * @{ + */ + +/** + * @brief Initialize a static mailbox object. + * + * @note For the static mailbox object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_mb_create() function will allocate memory space automatically and initialize the mailbox. + * + * @see rt_mb_create() + * + * @param mb is a pointer to the mailbox to initialize. + * It is assumed that storage for the mailbox will be allocated in your application. + * + * @param name is a pointer to the name that given to the mailbox. + * + * @param msgpool the begin address of buffer to save received mail. + * + * @param size is the maximum number of mails in the mailbox. + * For example, when the mailbox buffer capacity is N, size is N/4. + * + * @param flag is the mailbox flag, which determines the queuing way of how multiple threads wait + * when the mailbox is not available. + * The mailbox flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this mailbox will become non-real-time threads. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_mb_init(rt_mailbox_t mb, + const char *name, + void *msgpool, + rt_size_t size, + rt_uint8_t flag) +{ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(mb->parent.parent), RT_Object_Class_MailBox, name); + + /* set parent flag */ + mb->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(mb->parent)); + + /* initialize mailbox */ + mb->msg_pool = (rt_ubase_t *)msgpool; + mb->size = (rt_uint16_t)size; + mb->entry = 0; + mb->in_offset = 0; + mb->out_offset = 0; + + /* initialize an additional list of sender suspend thread */ + rt_list_init(&(mb->suspend_sender_thread)); + + return RT_EOK; +} +RTM_EXPORT(rt_mb_init); + + +/** + * @brief This function will detach a static mailbox object. + * + * @note This function is used to detach a static mailbox object which is initialized by rt_mb_init() function. + * By contrast, the rt_mb_delete() function will delete a mailbox object. + * When the mailbox is successfully detached, it will resume all suspended threads in the mailbox list. + * + * @see rt_mb_delete() + * + * @param mb is a pointer to a mailbox object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the mailbox detach failed. + * + * @warning This function can ONLY detach a static mailbox initialized by the rt_mb_init() function. + * If the mailbox is created by the rt_mb_create() function, you MUST NOT USE this function to detach it, + * ONLY USE the rt_mb_delete() function to complete the deletion. + */ +rt_err_t rt_mb_detach(rt_mailbox_t mb) +{ + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + RT_ASSERT(rt_object_is_systemobject(&mb->parent.parent)); + + /* resume all suspended thread */ + _ipc_list_resume_all(&(mb->parent.suspend_thread)); + /* also resume all mailbox private suspended thread */ + _ipc_list_resume_all(&(mb->suspend_sender_thread)); + + /* detach mailbox object */ + rt_object_detach(&(mb->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mb_detach); + +#ifdef RT_USING_HEAP +/** + * @brief Creating a mailbox object. + * + * @note For the mailbox object, its memory space is allocated automatically. + * By contrast, the rt_mb_init() function will initialize a static mailbox object. + * + * @see rt_mb_init() + * + * @param name is a pointer that given to the mailbox. + * + * @param size is the maximum number of mails in the mailbox. + * For example, when mailbox buffer capacity is N, size is N/4. + * + * @param flag is the mailbox flag, which determines the queuing way of how multiple threads wait + * when the mailbox is not available. + * The mailbox flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this mailbox will become non-real-time threads. + * + * @return Return a pointer to the mailbox object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_mailbox_t rt_mb_create(const char *name, rt_size_t size, rt_uint8_t flag) +{ + rt_mailbox_t mb; + + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + mb = (rt_mailbox_t)rt_object_allocate(RT_Object_Class_MailBox, name); + if (mb == RT_NULL) + return mb; + + /* set parent */ + mb->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(mb->parent)); + + /* initialize mailbox */ + mb->size = (rt_uint16_t)size; + mb->msg_pool = (rt_ubase_t *)RT_KERNEL_MALLOC(mb->size * sizeof(rt_ubase_t)); + if (mb->msg_pool == RT_NULL) + { + /* delete mailbox object */ + rt_object_delete(&(mb->parent.parent)); + + return RT_NULL; + } + mb->entry = 0; + mb->in_offset = 0; + mb->out_offset = 0; + + /* initialize an additional list of sender suspend thread */ + rt_list_init(&(mb->suspend_sender_thread)); + + return mb; +} +RTM_EXPORT(rt_mb_create); + + +/** + * @brief This function will delete a mailbox object and release the memory space. + * + * @note This function is used to delete a mailbox object which is created by the rt_mb_create() function. + * By contrast, the rt_mb_detach() function will detach a static mailbox object. + * When the mailbox is successfully deleted, it will resume all suspended threads in the mailbox list. + * + * @see rt_mb_detach() + * + * @param mb is a pointer to a mailbox object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + * + * @warning This function can only delete mailbox created by the rt_mb_create() function. + * If the mailbox is initialized by the rt_mb_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_mb_detach() function to complete the detachment. + */ +rt_err_t rt_mb_delete(rt_mailbox_t mb) +{ + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + RT_ASSERT(rt_object_is_systemobject(&mb->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* resume all suspended thread */ + _ipc_list_resume_all(&(mb->parent.suspend_thread)); + + /* also resume all mailbox private suspended thread */ + _ipc_list_resume_all(&(mb->suspend_sender_thread)); + + /* free mailbox pool */ + RT_KERNEL_FREE(mb->msg_pool); + + /* delete mailbox object */ + rt_object_delete(&(mb->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mb_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will send an mail to the mailbox object. If there is a thread suspended on the mailbox, + * the thread will be resumed. + * + * @note When using this function to send a mail, if the mailbox if fully used, the current thread will + * wait for a timeout. If the set timeout time is reached and there is still no space available, + * the sending thread will be resumed and an error code will be returned. + * By contrast, the rt_mb_send() function will return an error code immediately without waiting time + * when the mailbox if fully used. + * + * @see rt_mb_send() + * + * @param mb is a pointer to the mailbox object to be sent. + * + * @param value is a value to the content of the mail you want to send. + * + * @param timeout is a timeout period (unit: an OS tick). + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + * + * @warning This function can be called in interrupt context and thread context. + */ +static rt_err_t _rt_mb_send_wait(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout, + int suspend_flag) +{ + struct rt_thread *thread; + rt_base_t level; + rt_uint32_t tick_delta; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0); + + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mb->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* for non-blocking call */ + if (mb->entry == mb->size && timeout == 0) + { + rt_hw_interrupt_enable(level); + return -RT_EFULL; + } + + /* mailbox is full */ + while (mb->entry == mb->size) + { + /* reset error number in thread */ + thread->error = -RT_EINTR; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EFULL; + } + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mb->suspend_sender_thread), + thread, + mb->parent.parent.flag, + suspend_flag); + + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mb_send_wait: start timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* re-schedule */ + rt_schedule(); + + /* resume from suspend state */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + + /* set ptr */ + mb->msg_pool[mb->in_offset] = value; + /* increase input offset */ + ++ mb->in_offset; + if (mb->in_offset >= mb->size) + mb->in_offset = 0; + + if(mb->entry < RT_MB_ENTRY_MAX) + { + /* increase message entry */ + mb->entry ++; + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + + /* resume suspended thread */ + if (!rt_list_isempty(&mb->parent.suspend_thread)) + { + _ipc_list_resume(&(mb->parent.suspend_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} + +rt_err_t rt_mb_send_wait(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout) +{ + return _rt_mb_send_wait(mb, value, timeout, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mb_send_wait); + +rt_err_t rt_mb_send_wait_interruptible(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout) +{ + return _rt_mb_send_wait(mb, value, timeout, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mb_send_wait_interruptible); + +rt_err_t rt_mb_send_wait_killable(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout) +{ + return _rt_mb_send_wait(mb, value, timeout, RT_KILLABLE); +} +RTM_EXPORT(rt_mb_send_wait_killable); +/** + * @brief This function will send an mail to the mailbox object. If there is a thread suspended on the mailbox, + * the thread will be resumed. + * + * @note When using this function to send a mail, if the mailbox is fully used, this function will return an error + * code immediately without waiting time. + * By contrast, the rt_mb_send_wait() function is set a timeout to wait for the mail to be sent. + * + * @see rt_mb_send_wait() + * + * @param mb is a pointer to the mailbox object to be sent. + * + * @param value is a value to the content of the mail you want to send. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + */ +rt_err_t rt_mb_send(rt_mailbox_t mb, rt_ubase_t value) +{ + return rt_mb_send_wait(mb, value, 0); +} +RTM_EXPORT(rt_mb_send); + +rt_err_t rt_mb_send_interruptible(rt_mailbox_t mb, rt_ubase_t value) +{ + return rt_mb_send_wait_interruptible(mb, value, 0); +} +RTM_EXPORT(rt_mb_send_interruptible); + +rt_err_t rt_mb_send_killable(rt_mailbox_t mb, rt_ubase_t value) +{ + return rt_mb_send_wait_killable(mb, value, 0); +} +RTM_EXPORT(rt_mb_send_killable); + +/** + * @brief This function will send an urgent mail to the mailbox object. + * + * @note This function is almost the same as the rt_mb_send() function. The only difference is that + * when sending an urgent mail, the mail will be placed at the head of the mail queue so that + * the recipient can receive the urgent mail first. + * + * @see rt_mb_send() + * + * @param mb is a pointer to the mailbox object to be sent. + * + * @param value is the content of the mail you want to send. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + */ +rt_err_t rt_mb_urgent(rt_mailbox_t mb, rt_ubase_t value) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mb->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + if (mb->entry == mb->size) + { + rt_hw_interrupt_enable(level); + return -RT_EFULL; + } + + /* rewind to the previous position */ + if (mb->out_offset > 0) + { + mb->out_offset --; + } + else + { + mb->out_offset = mb->size - 1; + } + + /* set ptr */ + mb->msg_pool[mb->out_offset] = value; + + /* increase message entry */ + mb->entry ++; + + /* resume suspended thread */ + if (!rt_list_isempty(&mb->parent.suspend_thread)) + { + _ipc_list_resume(&(mb->parent.suspend_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} +RTM_EXPORT(rt_mb_urgent); + + +/** + * @brief This function will receive a mail from mailbox object, if there is no mail in mailbox object, + * the thread shall wait for a specified time. + * + * @note Only when there is mail in the mailbox, the receiving thread can get the mail immediately and + * return RT_EOK, otherwise the receiving thread will be suspended until the set timeout. If the mail + * is still not received within the specified time, it will return-RT_ETIMEOUT. + * + * @param mb is a pointer to the mailbox object to be received. + * + * @param value is a flag that you will set for this mailbox's flag. + * You can set an mailbox flag, or you can set multiple flags through OR logic operations. + * + * @param timeout is a timeout period (unit: an OS tick). If the mailbox object is not avaliable in the queue, + * the thread will wait for the object in the queue up to the amount of time specified by this parameter. + * + * NOTE: + * If use Macro RT_WAITING_FOREVER to set this parameter, which means that when the + * mailbox object is unavailable in the queue, the thread will be waiting forever. + * If use macro RT_WAITING_NO to set this parameter, which means that this + * function is non-blocking and will return immediately. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox release failed. + */ +static rt_err_t _rt_mb_recv(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout, int suspend_flag) +{ + struct rt_thread *thread; + rt_base_t level; + rt_uint32_t tick_delta; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0); + + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(mb->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* for non-blocking call */ + if (mb->entry == 0 && timeout == 0) + { + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + + /* mailbox is empty */ + while (mb->entry == 0) + { + /* reset error number in thread */ + thread->error = -RT_EINTR; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + thread->error = -RT_ETIMEOUT; + + return -RT_ETIMEOUT; + } + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mb->parent.suspend_thread), + thread, + mb->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mb_recv: start timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* re-schedule */ + rt_schedule(); + + /* resume from suspend state */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + + /* fill ptr */ + *value = mb->msg_pool[mb->out_offset]; + + /* increase output offset */ + ++ mb->out_offset; + if (mb->out_offset >= mb->size) + mb->out_offset = 0; + + /* decrease message entry */ + if(mb->entry > 0) + { + mb->entry --; + } + + /* resume suspended thread */ + if (!rt_list_isempty(&(mb->suspend_sender_thread))) + { + _ipc_list_resume(&(mb->suspend_sender_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mb->parent.parent))); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mb->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_mb_recv(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout) +{ + return _rt_mb_recv(mb, value, timeout, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mb_recv); + +rt_err_t rt_mb_recv_interruptibale(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout) +{ + return _rt_mb_recv(mb, value, timeout, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mb_recv_interruptibale); + +rt_err_t rt_mb_recv_killable(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout) +{ + return _rt_mb_recv(mb, value, timeout, RT_KILLABLE); +} +RTM_EXPORT(rt_mb_recv_killable); + +/** + * @brief This function will set some extra attributions of a mailbox object. + * + * @note Currently this function only supports the RT_IPC_CMD_RESET command to reset the mailbox. + * + * @param mb is a pointer to a mailbox object. + * + * @param cmd is a command used to configure some attributions of the mailbox. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_mb_control(rt_mailbox_t mb, int cmd, void *arg) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + + if (cmd == RT_IPC_CMD_RESET) + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* resume all waiting thread */ + _ipc_list_resume_all(&(mb->parent.suspend_thread)); + /* also resume all mailbox private suspended thread */ + _ipc_list_resume_all(&(mb->suspend_sender_thread)); + + /* re-init mailbox */ + mb->entry = 0; + mb->in_offset = 0; + mb->out_offset = 0; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_mb_control); + +/**@}*/ +#endif /* RT_USING_MAILBOX */ + +#ifdef RT_USING_MESSAGEQUEUE +/** + * @addtogroup messagequeue + * @{ + */ + +struct rt_mq_message +{ + struct rt_mq_message *next; +}; + + +/** + * @brief Initialize a static messagequeue object. + * + * @note For the static messagequeue object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_mq_create() function will allocate memory space automatically + * and initialize the messagequeue. + * + * @see rt_mq_create() + * + * @param mq is a pointer to the messagequeue to initialize. It is assumed that storage for + * the messagequeue will be allocated in your application. + * + * @param name is a pointer to the name that given to the messagequeue. + * + * @param msgpool is a pointer to the starting address of the memory space you allocated for + * the messagequeue in advance. + * In other words, msgpool is a pointer to the messagequeue buffer of the starting address. + * + * @param msg_size is the maximum length of a message in the messagequeue (Unit: Byte). + * + * @param pool_size is the size of the memory space allocated for the messagequeue in advance. + * + * @param flag is the messagequeue flag, which determines the queuing way of how multiple threads wait + * when the messagequeue is not available. + * The messagequeue flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this messagequeue will become non-real-time threads. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_mq_init(rt_mq_t mq, + const char *name, + void *msgpool, + rt_size_t msg_size, + rt_size_t pool_size, + rt_uint8_t flag) +{ + struct rt_mq_message *head; + rt_base_t temp; + register rt_size_t msg_align_size; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(mq->parent.parent), RT_Object_Class_MessageQueue, name); + + /* set parent flag */ + mq->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(mq->parent)); + + /* set message pool */ + mq->msg_pool = msgpool; + + /* get correct message size */ + msg_align_size = RT_ALIGN(msg_size, RT_ALIGN_SIZE); + mq->msg_size = msg_size; + mq->max_msgs = pool_size / (msg_align_size + sizeof(struct rt_mq_message)); + + if (0 == mq->max_msgs) + { + return -RT_EINVAL; + } + + /* initialize message list */ + mq->msg_queue_head = RT_NULL; + mq->msg_queue_tail = RT_NULL; + + /* initialize message empty list */ + mq->msg_queue_free = RT_NULL; + for (temp = 0; temp < mq->max_msgs; temp ++) + { + head = (struct rt_mq_message *)((rt_uint8_t *)mq->msg_pool + + temp * (msg_align_size + sizeof(struct rt_mq_message))); + head->next = (struct rt_mq_message *)mq->msg_queue_free; + mq->msg_queue_free = head; + } + + /* the initial entry is zero */ + mq->entry = 0; + + /* initialize an additional list of sender suspend thread */ + rt_list_init(&(mq->suspend_sender_thread)); + + return RT_EOK; +} +RTM_EXPORT(rt_mq_init); + + +/** + * @brief This function will detach a static messagequeue object. + * + * @note This function is used to detach a static messagequeue object which is initialized by rt_mq_init() function. + * By contrast, the rt_mq_delete() function will delete a messagequeue object. + * When the messagequeue is successfully detached, it will resume all suspended threads in the messagequeue list. + * + * @see rt_mq_delete() + * + * @param mq is a pointer to a messagequeue object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the messagequeue detach failed. + * + * @warning This function can ONLY detach a static messagequeue initialized by the rt_mq_init() function. + * If the messagequeue is created by the rt_mq_create() function, you MUST NOT USE this function to detach it, + * and ONLY USE the rt_mq_delete() function to complete the deletion. + */ +rt_err_t rt_mq_detach(rt_mq_t mq) +{ + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(rt_object_is_systemobject(&mq->parent.parent)); + + /* resume all suspended thread */ + _ipc_list_resume_all(&mq->parent.suspend_thread); + /* also resume all message queue private suspended thread */ + _ipc_list_resume_all(&(mq->suspend_sender_thread)); + + /* detach message queue object */ + rt_object_detach(&(mq->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mq_detach); + +#ifdef RT_USING_HEAP +/** + * @brief Creating a messagequeue object. + * + * @note For the messagequeue object, its memory space is allocated automatically. + * By contrast, the rt_mq_init() function will initialize a static messagequeue object. + * + * @see rt_mq_init() + * + * @param name is a pointer that given to the messagequeue. + * + * @param msg_size is the maximum length of a message in the messagequeue (Unit: Byte). + * + * @param max_msgs is the maximum number of messages in the messagequeue. + * + * @param flag is the messagequeue flag, which determines the queuing way of how multiple threads wait + * when the messagequeue is not available. + * The messagequeue flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this messagequeue will become non-real-time threads. + * + * @return Return a pointer to the messagequeue object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can NOT be called in interrupt context. You can use macor RT_DEBUG_NOT_IN_INTERRUPT to check it. + */ +rt_mq_t rt_mq_create(const char *name, + rt_size_t msg_size, + rt_size_t max_msgs, + rt_uint8_t flag) +{ + struct rt_messagequeue *mq; + struct rt_mq_message *head; + rt_base_t temp; + register rt_size_t msg_align_size; + + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + mq = (rt_mq_t)rt_object_allocate(RT_Object_Class_MessageQueue, name); + if (mq == RT_NULL) + return mq; + + /* set parent */ + mq->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(mq->parent)); + + /* initialize message queue */ + + /* get correct message size */ + msg_align_size = RT_ALIGN(msg_size, RT_ALIGN_SIZE); + mq->msg_size = msg_size; + mq->max_msgs = max_msgs; + + /* allocate message pool */ + mq->msg_pool = RT_KERNEL_MALLOC((msg_align_size + sizeof(struct rt_mq_message)) * mq->max_msgs); + if (mq->msg_pool == RT_NULL) + { + rt_object_delete(&(mq->parent.parent)); + + return RT_NULL; + } + + /* initialize message list */ + mq->msg_queue_head = RT_NULL; + mq->msg_queue_tail = RT_NULL; + + /* initialize message empty list */ + mq->msg_queue_free = RT_NULL; + for (temp = 0; temp < mq->max_msgs; temp ++) + { + head = (struct rt_mq_message *)((rt_uint8_t *)mq->msg_pool + + temp * (msg_align_size + sizeof(struct rt_mq_message))); + head->next = (struct rt_mq_message *)mq->msg_queue_free; + mq->msg_queue_free = head; + } + + /* the initial entry is zero */ + mq->entry = 0; + + /* initialize an additional list of sender suspend thread */ + rt_list_init(&(mq->suspend_sender_thread)); + + return mq; +} +RTM_EXPORT(rt_mq_create); + + +/** + * @brief This function will delete a messagequeue object and release the memory. + * + * @note This function is used to delete a messagequeue object which is created by the rt_mq_create() function. + * By contrast, the rt_mq_detach() function will detach a static messagequeue object. + * When the messagequeue is successfully deleted, it will resume all suspended threads in the messagequeue list. + * + * @see rt_mq_detach() + * + * @param mq is a pointer to a messagequeue object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the messagequeue detach failed. + * + * @warning This function can ONLY delete a messagequeue initialized by the rt_mq_create() function. + * If the messagequeue is initialized by the rt_mq_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_mq_detach() function to complete the detachment. + * for example,the rt_mq_create() function, it cannot be called in interrupt context. + */ +rt_err_t rt_mq_delete(rt_mq_t mq) +{ + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(rt_object_is_systemobject(&mq->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* resume all suspended thread */ + _ipc_list_resume_all(&(mq->parent.suspend_thread)); + /* also resume all message queue private suspended thread */ + _ipc_list_resume_all(&(mq->suspend_sender_thread)); + + /* free message queue pool */ + RT_KERNEL_FREE(mq->msg_pool); + + /* delete message queue object */ + rt_object_delete(&(mq->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mq_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will send a message to the messagequeue object. If + * there is a thread suspended on the messagequeue, the thread will be + * resumed. + * + * @note When using this function to send a message, if the messagequeue is + * fully used, the current thread will wait for a timeout. If reaching + * the timeout and there is still no space available, the sending + * thread will be resumed and an error code will be returned. By + * contrast, the rt_mq_send() function will return an error code + * immediately without waiting when the messagequeue if fully used. + * + * @see rt_mq_send() + * + * @param mq is a pointer to the messagequeue object to be sent. + * + * @param buffer is the content of the message. + * + * @param size is the length of the message(Unit: Byte). + * + * @param timeout is a timeout period (unit: an OS tick). + * + * @return Return the operation status. When the return value is RT_EOK, the + * operation is successful. If the return value is any other values, + * it means that the messagequeue detach failed. + * + * @warning This function can be called in interrupt context and thread + * context. + */ +static rt_err_t _rt_mq_send_wait(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout, + int suspend_flag) +{ + rt_base_t level; + struct rt_mq_message *msg; + rt_uint32_t tick_delta; + struct rt_thread *thread; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(buffer != RT_NULL); + RT_ASSERT(size != 0); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0); + + /* greater than one message size */ + if (size > mq->msg_size) + return -RT_ERROR; + + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mq->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* get a free list, there must be an empty item */ + msg = (struct rt_mq_message *)mq->msg_queue_free; + /* for non-blocking call */ + if (msg == RT_NULL && timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EFULL; + } + + /* message queue is full */ + while ((msg = (struct rt_mq_message *)mq->msg_queue_free) == RT_NULL) + { + /* reset error number in thread */ + thread->error = -RT_EINTR; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EFULL; + } + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mq->suspend_sender_thread), + thread, + mq->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mq_send_wait: start timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* re-schedule */ + rt_schedule(); + + /* resume from suspend state */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + + /* move free list pointer */ + mq->msg_queue_free = msg->next; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* the msg is the new tailer of list, the next shall be NULL */ + msg->next = RT_NULL; + /* copy buffer */ + rt_memcpy(msg + 1, buffer, size); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + /* link msg to message queue */ + if (mq->msg_queue_tail != RT_NULL) + { + /* if the tail exists, */ + ((struct rt_mq_message *)mq->msg_queue_tail)->next = msg; + } + + /* set new tail */ + mq->msg_queue_tail = msg; + /* if the head is empty, set head */ + if (mq->msg_queue_head == RT_NULL) + mq->msg_queue_head = msg; + + if(mq->entry < RT_MQ_ENTRY_MAX) + { + /* increase message entry */ + mq->entry ++; + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + + /* resume suspended thread */ + if (!rt_list_isempty(&mq->parent.suspend_thread)) + { + _ipc_list_resume(&(mq->parent.suspend_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} + +rt_err_t rt_mq_send_wait(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_send_wait(mq, buffer, size, timeout, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mq_send_wait) + +rt_err_t rt_mq_send_wait_interruptible(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_send_wait(mq, buffer, size, timeout, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mq_send_wait_interruptible) + +rt_err_t rt_mq_send_wait_killable(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_send_wait(mq, buffer, size, timeout, RT_KILLABLE); +} +RTM_EXPORT(rt_mq_send_wait_killable) +/** + * @brief This function will send a message to the messagequeue object. + * If there is a thread suspended on the messagequeue, the thread will be resumed. + * + * @note When using this function to send a message, if the messagequeue is fully used, + * the current thread will wait for a timeout. + * By contrast, when the messagequeue is fully used, the rt_mq_send_wait() function will + * return an error code immediately without waiting. + * + * @see rt_mq_send_wait() + * + * @param mq is a pointer to the messagequeue object to be sent. + * + * @param buffer is the content of the message. + * + * @param size is the length of the message(Unit: Byte). + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the messagequeue detach failed. + * + * @warning This function can be called in interrupt context and thread context. + */ +rt_err_t rt_mq_send(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + return rt_mq_send_wait(mq, buffer, size, 0); +} +RTM_EXPORT(rt_mq_send); + +rt_err_t rt_mq_send_interrupt(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + return rt_mq_send_wait_interruptible(mq, buffer, size, 0); +} +RTM_EXPORT(rt_mq_send_interrupt); + +rt_err_t rt_mq_send_killable(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + return rt_mq_send_wait_killable(mq, buffer, size, 0); +} +RTM_EXPORT(rt_mq_send_killable); +/** + * @brief This function will send an urgent message to the messagequeue object. + * + * @note This function is almost the same as the rt_mq_send() function. The only difference is that + * when sending an urgent message, the message is placed at the head of the messagequeue so that + * the recipient can receive the urgent message first. + * + * @see rt_mq_send() + * + * @param mq is a pointer to the messagequeue object to be sent. + * + * @param buffer is the content of the message. + * + * @param size is the length of the message(Unit: Byte). + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + */ +rt_err_t rt_mq_urgent(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + rt_base_t level; + struct rt_mq_message *msg; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(buffer != RT_NULL); + RT_ASSERT(size != 0); + + /* greater than one message size */ + if (size > mq->msg_size) + return -RT_ERROR; + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mq->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* get a free list, there must be an empty item */ + msg = (struct rt_mq_message *)mq->msg_queue_free; + /* message queue is full */ + if (msg == RT_NULL) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EFULL; + } + /* move free list pointer */ + mq->msg_queue_free = msg->next; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* copy buffer */ + rt_memcpy(msg + 1, buffer, size); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* link msg to the beginning of message queue */ + msg->next = (struct rt_mq_message *)mq->msg_queue_head; + mq->msg_queue_head = msg; + + /* if there is no tail */ + if (mq->msg_queue_tail == RT_NULL) + mq->msg_queue_tail = msg; + + if(mq->entry < RT_MQ_ENTRY_MAX) + { + /* increase message entry */ + mq->entry ++; + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + + /* resume suspended thread */ + if (!rt_list_isempty(&mq->parent.suspend_thread)) + { + _ipc_list_resume(&(mq->parent.suspend_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} +RTM_EXPORT(rt_mq_urgent); + + +/** + * @brief This function will receive a message from message queue object, + * if there is no message in messagequeue object, the thread shall wait for a specified time. + * + * @note Only when there is mail in the mailbox, the receiving thread can get the mail immediately and return RT_EOK, + * otherwise the receiving thread will be suspended until timeout. + * If the mail is not received within the specified time, it will return -RT_ETIMEOUT. + * + * @param mq is a pointer to the messagequeue object to be received. + * + * @param buffer is the content of the message. + * + * @param size is the length of the message(Unit: Byte). + * + * @param timeout is a timeout period (unit: an OS tick). If the message is unavailable, the thread will wait for + * the message in the queue up to the amount of time specified by this parameter. + * + * NOTE: + * If use Macro RT_WAITING_FOREVER to set this parameter, which means that when the + * message is unavailable in the queue, the thread will be waiting forever. + * If use macro RT_WAITING_NO to set this parameter, which means that this + * function is non-blocking and will return immediately. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox release failed. + */ +static rt_err_t _rt_mq_recv(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout, + int suspend_flag) +{ + struct rt_thread *thread; + rt_base_t level; + struct rt_mq_message *msg; + rt_uint32_t tick_delta; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(buffer != RT_NULL); + RT_ASSERT(size != 0); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0); + + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(mq->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* for non-blocking call */ + if (mq->entry == 0 && timeout == 0) + { + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + + /* message queue is empty */ + while (mq->entry == 0) + { + /* reset error number in thread */ + thread->error = -RT_EINTR; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + thread->error = -RT_ETIMEOUT; + + return -RT_ETIMEOUT; + } + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mq->parent.suspend_thread), + thread, + mq->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("set thread:%s to timer list\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* re-schedule */ + rt_schedule(); + + /* recv message */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + + /* get message from queue */ + msg = (struct rt_mq_message *)mq->msg_queue_head; + + /* move message queue head */ + mq->msg_queue_head = msg->next; + /* reach queue tail, set to NULL */ + if (mq->msg_queue_tail == msg) + mq->msg_queue_tail = RT_NULL; + + /* decrease message entry */ + if(mq->entry > 0) + { + mq->entry --; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* copy message */ + rt_memcpy(buffer, msg + 1, size > mq->msg_size ? mq->msg_size : size); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + /* put message to free list */ + msg->next = (struct rt_mq_message *)mq->msg_queue_free; + mq->msg_queue_free = msg; + + /* resume suspended thread */ + if (!rt_list_isempty(&(mq->suspend_sender_thread))) + { + _ipc_list_resume(&(mq->suspend_sender_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mq->parent.parent))); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mq->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_mq_recv(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_recv(mq, buffer, size, timeout, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mq_recv); + +rt_err_t rt_mq_recv_interruptible(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_recv(mq, buffer, size, timeout, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mq_recv_interruptible); + +rt_err_t rt_mq_recv_killable(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_recv(mq, buffer, size, timeout, RT_KILLABLE); +} +RTM_EXPORT(rt_mq_recv_killable); +/** + * @brief This function will set some extra attributions of a messagequeue object. + * + * @note Currently this function only supports the RT_IPC_CMD_RESET command to reset the messagequeue. + * + * @param mq is a pointer to a messagequeue object. + * + * @param cmd is a command used to configure some attributions of the messagequeue. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_mq_control(rt_mq_t mq, int cmd, void *arg) +{ + rt_base_t level; + struct rt_mq_message *msg; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + + if (cmd == RT_IPC_CMD_RESET) + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* resume all waiting thread */ + _ipc_list_resume_all(&mq->parent.suspend_thread); + /* also resume all message queue private suspended thread */ + _ipc_list_resume_all(&(mq->suspend_sender_thread)); + + /* release all message in the queue */ + while (mq->msg_queue_head != RT_NULL) + { + /* get message from queue */ + msg = (struct rt_mq_message *)mq->msg_queue_head; + + /* move message queue head */ + mq->msg_queue_head = msg->next; + /* reach queue tail, set to NULL */ + if (mq->msg_queue_tail == msg) + mq->msg_queue_tail = RT_NULL; + + /* put message to free list */ + msg->next = (struct rt_mq_message *)mq->msg_queue_free; + mq->msg_queue_free = msg; + } + + /* clean entry */ + mq->entry = 0; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_mq_control); + +/**@}*/ +#endif /* RT_USING_MESSAGEQUEUE */ +/**@}*/ diff --git a/tasks/concur-rtthread-mutex-ceilings/task.json b/tasks/concur-rtthread-mutex-ceilings/task.json new file mode 100644 index 00000000..ef5600dc --- /dev/null +++ b/tasks/concur-rtthread-mutex-ceilings/task.json @@ -0,0 +1,29 @@ +{ + "id": "concur-rtthread-mutex-ceilings", + "version": "1", + "family": "posix-concurrency", + "source": "oss/RT-Thread/rt-thread@64cd64baf9ba", + "template": "template", + "candidate_files": [ + "src/ipc.c" + ], + "verifier": "verify.py", + "grader_files": [ + "check.py", + "support.tar", + "observer.c" + ], + "fixtures": { + "gold": "PASS", + "template": "FAIL", + "noop": "FAIL", + "cheat": "FAIL", + "cheat_read_grader": "FAIL", + "symptom_only": "FAIL", + "valid_fold": "PASS", + "partial_suspend": "FAIL", + "partial_update": "FAIL", + "partial_aggregate": "FAIL" + }, + "timeout_seconds": 120 +} diff --git a/tasks/concur-rtthread-mutex-ceilings/template/LICENSE b/tasks/concur-rtthread-mutex-ceilings/template/LICENSE new file mode 100644 index 00000000..261eeb9e --- /dev/null +++ b/tasks/concur-rtthread-mutex-ceilings/template/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/tasks/concur-rtthread-mutex-ceilings/template/Makefile b/tasks/concur-rtthread-mutex-ceilings/template/Makefile new file mode 100644 index 00000000..66487376 --- /dev/null +++ b/tasks/concur-rtthread-mutex-ceilings/template/Makefile @@ -0,0 +1,13 @@ +CC = gcc +CFLAGS = -std=c11 -D_XOPEN_SOURCE=700 -O1 -g -Iinclude -Iport -ffunction-sections -fdata-sections +SOURCES = src/ipc.c src/thread.c src/object.c port/services.c +all: smoke +smoke: $(SOURCES) port/smoke.c + $(CC) $(CFLAGS) $(SOURCES) port/smoke.c -Wl,--gc-sections -o $@ +report: $(SOURCES) port/field_report.c + $(CC) $(CFLAGS) $(SOURCES) port/field_report.c -Wl,--gc-sections -o $@ +check: smoke + ./smoke +clean: + rm -f smoke report +.PHONY: all check clean diff --git a/tasks/concur-rtthread-mutex-ceilings/template/README.md b/tasks/concur-rtthread-mutex-ceilings/template/README.md new file mode 100644 index 00000000..7482b320 --- /dev/null +++ b/tasks/concur-rtthread-mutex-ceilings/template/README.md @@ -0,0 +1,15 @@ +# 同步服务现场工作区 + +这里保留了 RT-Thread 内核的 IPC、线程与对象管理源码,使用最小主机服务移植层构建,无需板卡、网络或额外依赖。接口语义见 `docs/synchronization.md`,其全部条款都是交付标准。 + +使用 gcc 和 make: + +```sh +make check +make report +./report +``` + +`check` 是正常获取/释放 smoke。`report` 打印现场配置变更前后的原始状态;也可自行编写调用程序复现更复杂的资源等待组合。主机端可以通过调度回调和线程定时器回调控制交错,无需 sleep。 + +最终只提交并评分 `src/ipc.c`。其余文件是冻结的源码、公开合同或构建支撑材料;新增文件不会被收集。 diff --git a/tasks/concur-rtthread-mutex-ceilings/template/docs/synchronization.md b/tasks/concur-rtthread-mutex-ceilings/template/docs/synchronization.md new file mode 100644 index 00000000..22a974ba --- /dev/null +++ b/tasks/concur-rtthread-mutex-ceilings/template/docs/synchronization.md @@ -0,0 +1,27 @@ +# 同步服务合同 + +本工作区保留 RT-Thread 的线程、对象和 IPC 接口。下列条款整理自其线程管理、线程同步公开文档、随题头文件/API 注释,并采用 priority ceiling 与 priority inheritance 的通常定义。配置为 32 级优先级;数字越小,优先级越高。 + +R01 线程初始化时指定基础优先级,范围为 0 到 31;未持锁且没有等待者捐赠时使用基础优先级。 + +R02 静态互斥量初始化后无持有者、持有计数为 0,ceiling 初始为 255,表示尚未配置。获取无持有者的互斥量成功,调用线程成为持有者,计数为 1。 + +R03 同一线程可以重复获取其持有的互斥量,每次成功获取使计数增加 1。持有者释放一次使计数减少 1,计数到 0 才交出所有权;其他线程释放返回 -RT_ERROR。 + +R04 互斥量忙且等待参数为 0 时,获取立即返回 -RT_ETIMEOUT,不改变所有权。正等待参数以 tick 为单位,RT_WAITING_FOREVER 表示无限等待。 + +R05 忙互斥量的等待线程进入挂起状态;可用时由最高优先级的等待线程获得所有权并恢复,其获取返回 RT_EOK。超时线程恢复后获取返回 -RT_ETIMEOUT,并退出等待竞争。 + +R06 持有互斥量的线程使用基础优先级、所有仍持有互斥量的已配置 ceiling 和这些互斥量等待者优先级中的最高优先级。ceiling 在持有期间生效,不因另一个互斥量被获取、释放、变更或等待者离开而丢失。 + +R07 等待者因其持有的其他互斥量获得更高或更低的有效优先级时,其等待关系保持有效,捐赠沿已有的互斥量等待链继续传递;等待线程的相对优先级使用变化后的值。 + +R08 rt_mutex_setprioceiling 接受 0 到 31,成功时返回此前的 ceiling,并使新值对已有持有者以及相关等待链生效。空指针或不在范围内的值返回 255、设置 -RT_EINVAL,不改变互斥量;rt_mutex_getprioceiling 返回当前值,空指针返回 255。 + +R09 普通、interruptible 和 killable 三种获取接口在没有外部信号时遵循相同的所有权、等待和优先级合同。 + +R10 线程已挂起时,调整其等待优先级不要求它再次发起挂起。调整期间不得丢失其等待关系;等待仍能通过释放或定时器超时完成。 + +# 主机移植服务 + +`port/services.c` 提供当前线程身份、可重入中断屏蔽记录、就绪队列与定时器服务。`rt_schedule` 把控制交给可安装的回调,回调可以在挂起时切换上下文;定时器由驱动显式调用其回调,推进不依赖墙钟。线程挂起/恢复、mutex 的所有权、持锁登记、优先级继承和回退仍由内核代码执行。此移植层用于确定性软件复现,不宣称硬件或抢占式调度验证。 diff --git a/tasks/concur-rtthread-mutex-ceilings/template/include/rtconfig.h b/tasks/concur-rtthread-mutex-ceilings/template/include/rtconfig.h new file mode 100644 index 00000000..79d9fdcf --- /dev/null +++ b/tasks/concur-rtthread-mutex-ceilings/template/include/rtconfig.h @@ -0,0 +1,12 @@ +#ifndef RTCONFIG_H +#define RTCONFIG_H +#define RT_NAME_MAX 16 +#define RT_ALIGN_SIZE 8 +#define RT_THREAD_PRIORITY_MAX 32 +#define RT_TICK_PER_SECOND 1000 +#define RT_USING_MUTEX +#define RT_DEBUG +#define RT_DEBUG_CONTEXT_CHECK 0 +#define RT_USING_CONSOLE +#define RT_USING_LIBC +#endif diff --git a/tasks/concur-rtthread-mutex-ceilings/template/include/rtdebug.h b/tasks/concur-rtthread-mutex-ceilings/template/include/rtdebug.h new file mode 100644 index 00000000..ac5ba6c1 --- /dev/null +++ b/tasks/concur-rtthread-mutex-ceilings/template/include/rtdebug.h @@ -0,0 +1,157 @@ +/* + * Copyright (c) 2006-2021, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + */ + +#ifndef __RTDEBUG_H__ +#define __RTDEBUG_H__ + +#include + +/* Using this macro to control all kernel debug features. */ +#ifdef RT_DEBUG + +/* Turn on some of these (set to non-zero) to debug kernel */ +#ifndef RT_DEBUG_MEM +#define RT_DEBUG_MEM 0 +#endif + +#ifndef RT_DEBUG_MEMHEAP +#define RT_DEBUG_MEMHEAP 0 +#endif + +#ifndef RT_DEBUG_MODULE +#define RT_DEBUG_MODULE 0 +#endif + +#ifndef RT_DEBUG_SCHEDULER +#define RT_DEBUG_SCHEDULER 0 +#endif + +#ifndef RT_DEBUG_SLAB +#define RT_DEBUG_SLAB 0 +#endif + +#ifndef RT_DEBUG_THREAD +#define RT_DEBUG_THREAD 0 +#endif + +#ifndef RT_DEBUG_TIMER +#define RT_DEBUG_TIMER 0 +#endif + +#ifndef RT_DEBUG_IRQ +#define RT_DEBUG_IRQ 0 +#endif + +#ifndef RT_DEBUG_IPC +#define RT_DEBUG_IPC 0 +#endif + +#ifndef RT_DEBUG_DEVICE +#define RT_DEBUG_DEVICE 1 +#endif + +#ifndef RT_DEBUG_INIT +#define RT_DEBUG_INIT 0 +#endif + +/* Turn on this to enable context check */ +#ifndef RT_DEBUG_CONTEXT_CHECK +#define RT_DEBUG_CONTEXT_CHECK 1 +#endif + +#define RT_DEBUG_LOG(type, message) \ +do \ +{ \ + if (type) \ + rt_kprintf message; \ +} \ +while (0) + +#define RT_ASSERT(EX) \ +if (!(EX)) \ +{ \ + rt_assert_handler(#EX, __FUNCTION__, __LINE__); \ +} + +/* Macro to check current context */ +#if RT_DEBUG_CONTEXT_CHECK +#define RT_DEBUG_NOT_IN_INTERRUPT \ +do \ +{ \ + rt_base_t level; \ + level = rt_hw_interrupt_disable(); \ + if (rt_interrupt_get_nest() != 0) \ + { \ + rt_kprintf("Function[%s] shall not be used in ISR\n", __FUNCTION__); \ + RT_ASSERT(0) \ + } \ + rt_hw_interrupt_enable(level); \ +} \ +while (0) + +/* "In thread context" means: + * 1) the scheduler has been started + * 2) not in interrupt context. + */ +#define RT_DEBUG_IN_THREAD_CONTEXT \ +do \ +{ \ + rt_base_t level; \ + level = rt_hw_interrupt_disable(); \ + if (rt_thread_self() == RT_NULL) \ + { \ + rt_kprintf("Function[%s] shall not be used before scheduler start\n", \ + __FUNCTION__); \ + RT_ASSERT(0) \ + } \ + RT_DEBUG_NOT_IN_INTERRUPT; \ + rt_hw_interrupt_enable(level); \ +} \ +while (0) + +/* "scheduler available" means: + * 1) the scheduler has been started. + * 2) not in interrupt context. + * 3) scheduler is not locked. + */ +#define RT_DEBUG_SCHEDULER_AVAILABLE(need_check) \ +do \ +{ \ + if (need_check) \ + { \ + rt_base_t level; \ + level = rt_hw_interrupt_disable(); \ + if (rt_critical_level() != 0) \ + { \ + rt_kprintf("Function[%s]: scheduler is not available\n", \ + __FUNCTION__); \ + RT_ASSERT(0) \ + } \ + RT_DEBUG_IN_THREAD_CONTEXT; \ + rt_hw_interrupt_enable(level); \ + } \ +} \ +while (0) +#else +#define RT_DEBUG_NOT_IN_INTERRUPT +#define RT_DEBUG_IN_THREAD_CONTEXT +#define RT_DEBUG_SCHEDULER_AVAILABLE(need_check) +#endif + +#else /* RT_DEBUG */ + +#define RT_ASSERT(EX) +#define RT_DEBUG_LOG(type, message) +#define RT_DEBUG_NOT_IN_INTERRUPT +#define RT_DEBUG_IN_THREAD_CONTEXT +#define RT_DEBUG_SCHEDULER_AVAILABLE(need_check) + +#endif /* RT_DEBUG */ + +#endif /* __RTDEBUG_H__ */ diff --git a/tasks/concur-rtthread-mutex-ceilings/template/include/rtdef.h b/tasks/concur-rtthread-mutex-ceilings/template/include/rtdef.h new file mode 100644 index 00000000..eda6f4ba --- /dev/null +++ b/tasks/concur-rtthread-mutex-ceilings/template/include/rtdef.h @@ -0,0 +1,1461 @@ +/* + * Copyright (c) 2006-2022, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2007-01-10 Bernard the first version + * 2008-07-12 Bernard remove all rt_int8, rt_uint32_t etc typedef + * 2010-10-26 yi.qiu add module support + * 2010-11-10 Bernard add cleanup callback function in thread exit. + * 2011-05-09 Bernard use builtin va_arg in GCC 4.x + * 2012-11-16 Bernard change RT_NULL from ((void*)0) to 0. + * 2012-12-29 Bernard change the RT_USING_MEMPOOL location and add + * RT_USING_MEMHEAP condition. + * 2012-12-30 Bernard add more control command for graphic. + * 2013-01-09 Bernard change version number. + * 2015-02-01 Bernard change version number to v2.1.0 + * 2017-08-31 Bernard change version number to v3.0.0 + * 2017-11-30 Bernard change version number to v3.0.1 + * 2017-12-27 Bernard change version number to v3.0.2 + * 2018-02-24 Bernard change version number to v3.0.3 + * 2018-04-25 Bernard change version number to v3.0.4 + * 2018-05-31 Bernard change version number to v3.1.0 + * 2018-09-04 Bernard change version number to v3.1.1 + * 2018-09-14 Bernard apply Apache License v2.0 to RT-Thread Kernel + * 2018-10-13 Bernard change version number to v4.0.0 + * 2018-10-02 Bernard add 64bit arch support + * 2018-11-22 Jesven add smp member to struct rt_thread + * add struct rt_cpu + * add smp relevant macros + * 2019-01-27 Bernard change version number to v4.0.1 + * 2019-05-17 Bernard change version number to v4.0.2 + * 2019-12-20 Bernard change version number to v4.0.3 + * 2020-08-10 Meco Man add macro for struct rt_device_ops + * 2020-10-23 Meco Man define maximum value of ipc type + * 2021-03-19 Meco Man add security devices + * 2021-05-10 armink change version number to v4.0.4 + * 2021-11-19 Meco Man change version number to v4.1.0 + * 2021-12-21 Meco Man re-implement RT_UNUSED + * 2022-01-01 Gabriel improve hooking method + * 2022-01-07 Gabriel move some __on_rt_xxxxx_hook to dedicated c source files + * 2022-01-12 Meco Man remove RT_THREAD_BLOCK + * 2022-04-20 Meco Man change version number to v4.1.1 + * 2022-04-21 THEWON add macro RT_VERSION_CHECK + * 2022-06-29 Meco Man add RT_USING_LIBC and standard libc headers + * 2022-08-16 Meco Man change version number to v5.0.0 + * 2022-09-12 Meco Man define rt_ssize_t + * 2022-12-20 Meco Man add const name for rt_object + */ + +#ifndef __RT_DEF_H__ +#define __RT_DEF_H__ + +#include +#ifdef RT_USING_LIBC +#include +#include +#include +#include +#endif /* RT_USING_LIBC */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @addtogroup BasicDef + */ + +/**@{*/ + +/* RT-Thread version information */ +#define RT_VERSION_MAJOR 5 /**< Major version number (X.x.x) */ +#define RT_VERSION_MINOR 0 /**< Minor version number (x.X.x) */ +#define RT_VERSION_PATCH 0 /**< Patch version number (x.x.X) */ + +/* e.g. #if (RTTHREAD_VERSION >= RT_VERSION_CHECK(4, 1, 0) */ +#define RT_VERSION_CHECK(major, minor, revise) ((major * 10000) + (minor * 100) + revise) + +/* RT-Thread version */ +#define RTTHREAD_VERSION RT_VERSION_CHECK(RT_VERSION_MAJOR, RT_VERSION_MINOR, RT_VERSION_PATCH) + + +/* RT-Thread basic data type definitions */ +typedef int rt_bool_t; /**< boolean type */ +typedef signed long rt_base_t; /**< Nbit CPU related date type */ +typedef unsigned long rt_ubase_t; /**< Nbit unsigned CPU related data type */ + +#ifndef RT_USING_ARCH_DATA_TYPE +#ifdef RT_USING_LIBC +typedef int8_t rt_int8_t; /**< 8bit integer type */ +typedef int16_t rt_int16_t; /**< 16bit integer type */ +typedef int32_t rt_int32_t; /**< 32bit integer type */ +typedef uint8_t rt_uint8_t; /**< 8bit unsigned integer type */ +typedef uint16_t rt_uint16_t; /**< 16bit unsigned integer type */ +typedef uint32_t rt_uint32_t; /**< 32bit unsigned integer type */ +typedef int64_t rt_int64_t; /**< 64bit integer type */ +typedef uint64_t rt_uint64_t; /**< 64bit unsigned integer type */ +typedef size_t rt_size_t; /**< Type for size number */ +typedef ssize_t rt_ssize_t; /**< Used for a count of bytes or an error indication */ +#else +typedef signed char rt_int8_t; /**< 8bit integer type */ +typedef signed short rt_int16_t; /**< 16bit integer type */ +typedef signed int rt_int32_t; /**< 32bit integer type */ +typedef unsigned char rt_uint8_t; /**< 8bit unsigned integer type */ +typedef unsigned short rt_uint16_t; /**< 16bit unsigned integer type */ +typedef unsigned int rt_uint32_t; /**< 32bit unsigned integer type */ +#ifdef ARCH_CPU_64BIT +typedef signed long rt_int64_t; /**< 64bit integer type */ +typedef unsigned long rt_uint64_t; /**< 64bit unsigned integer type */ +#else +typedef signed long long rt_int64_t; /**< 64bit integer type */ +typedef unsigned long long rt_uint64_t; /**< 64bit unsigned integer type */ +#endif /* ARCH_CPU_64BIT */ +typedef rt_ubase_t rt_size_t; /**< Type for size number */ +typedef rt_base_t rt_ssize_t; /**< Used for a count of bytes or an error indication */ +#endif /* RT_USING_LIBC */ +#endif /* RT_USING_ARCH_DATA_TYPE */ + +typedef rt_base_t rt_err_t; /**< Type for error number */ +typedef rt_uint32_t rt_time_t; /**< Type for time stamp */ +typedef rt_uint32_t rt_tick_t; /**< Type for tick count */ +typedef rt_base_t rt_flag_t; /**< Type for flags */ +typedef rt_ubase_t rt_dev_t; /**< Type for device */ +typedef rt_base_t rt_off_t; /**< Type for offset */ + +/* boolean type definitions */ +#define RT_TRUE 1 /**< boolean true */ +#define RT_FALSE 0 /**< boolean fails */ + +/* null pointer definition */ +#define RT_NULL 0 + +/**@}*/ + +/* maximum value of base type */ +#ifdef RT_USING_LIBC +#define RT_UINT8_MAX UINT8_MAX /**< Maximum number of UINT8 */ +#define RT_UINT16_MAX UINT16_MAX /**< Maximum number of UINT16 */ +#define RT_UINT32_MAX UINT32_MAX /**< Maximum number of UINT32 */ +#else +#define RT_UINT8_MAX 0xff /**< Maximum number of UINT8 */ +#define RT_UINT16_MAX 0xffff /**< Maximum number of UINT16 */ +#define RT_UINT32_MAX 0xffffffff /**< Maximum number of UINT32 */ +#endif /* RT_USING_LIBC */ + +#define RT_TICK_MAX RT_UINT32_MAX /**< Maximum number of tick */ + +/* maximum value of ipc type */ +#define RT_SEM_VALUE_MAX RT_UINT16_MAX /**< Maximum number of semaphore .value */ +#define RT_MUTEX_VALUE_MAX RT_UINT16_MAX /**< Maximum number of mutex .value */ +#define RT_MUTEX_HOLD_MAX RT_UINT8_MAX /**< Maximum number of mutex .hold */ +#define RT_MB_ENTRY_MAX RT_UINT16_MAX /**< Maximum number of mailbox .entry */ +#define RT_MQ_ENTRY_MAX RT_UINT16_MAX /**< Maximum number of message queue .entry */ + +/* Common Utilities */ + +#define RT_UNUSED(x) ((void)x) + +/* Compiler Related Definitions */ +#if defined(__ARMCC_VERSION) /* ARM Compiler */ +#define rt_section(x) __attribute__((section(x))) +#define rt_used __attribute__((used)) +#define rt_align(n) __attribute__((aligned(n))) +#define rt_weak __attribute__((weak)) +#define rt_inline static __inline +/* module compiling */ +#ifdef RT_USING_MODULE +#define RTT_API __declspec(dllimport) +#else +#define RTT_API __declspec(dllexport) +#endif /* RT_USING_MODULE */ +#elif defined (__IAR_SYSTEMS_ICC__) /* for IAR Compiler */ +#define rt_section(x) @ x +#define rt_used __root +#define PRAGMA(x) _Pragma(#x) +#define rt_align(n) PRAGMA(data_alignment=n) +#define rt_weak __weak +#define rt_inline static inline +#define RTT_API +#elif defined (__GNUC__) /* GNU GCC Compiler */ +#ifndef RT_USING_LIBC +/* the version of GNU GCC must be greater than 4.x */ +typedef __builtin_va_list __gnuc_va_list; +typedef __gnuc_va_list va_list; +#define va_start(v,l) __builtin_va_start(v,l) +#define va_end(v) __builtin_va_end(v) +#define va_arg(v,l) __builtin_va_arg(v,l) +#endif /* RT_USING_LIBC */ +#define __RT_STRINGIFY(x...) (#x) +#define RT_STRINGIFY(x...) __RT_STRINGIFY(x) +#define rt_section(x) __attribute__((section(x))) +#define rt_used __attribute__((used)) +#define rt_align(n) __attribute__((aligned(n))) +#define rt_weak __attribute__((weak)) +#define rt_inline static __inline +#define RTT_API +#elif defined (__ADSPBLACKFIN__) /* for VisualDSP++ Compiler */ +#define rt_section(x) __attribute__((section(x))) +#define rt_used __attribute__((used)) +#define rt_align(n) __attribute__((aligned(n))) +#define rt_weak __attribute__((weak)) +#define rt_inline static inline +#define RTT_API +#elif defined (_MSC_VER) +#define rt_section(x) +#define rt_used +#define rt_align(n) __declspec(align(n)) +#define rt_weak +#define rt_inline static __inline +#define RTT_API +#elif defined (__TI_COMPILER_VERSION__) +/* The way that TI compiler set section is different from other(at least + * GCC and MDK) compilers. See ARM Optimizing C/C++ Compiler 5.9.3 for more + * details. */ +#define rt_section(x) __attribute__((section(x))) +#ifdef __TI_EABI__ +#define rt_used __attribute__((retain)) __attribute__((used)) +#else +#define rt_used __attribute__((used)) +#endif +#define PRAGMA(x) _Pragma(#x) +#define rt_align(n) __attribute__((aligned(n))) +#ifdef __TI_EABI__ +#define rt_weak __attribute__((weak)) +#else +#define rt_weak +#endif +#define rt_inline static inline +#define RTT_API +#elif defined (__TASKING__) +#define rt_section(x) __attribute__((section(x))) +#define rt_used __attribute__((used, protect)) +#define PRAGMA(x) _Pragma(#x) +#define rt_align(n) __attribute__((__align(n))) +#define rt_weak __attribute__((weak)) +#define rt_inline static inline +#define RTT_API +#else + #error not supported tool chain +#endif /* __ARMCC_VERSION */ + +/* initialization export */ +#ifdef RT_USING_COMPONENTS_INIT +typedef int (*init_fn_t)(void); +#ifdef _MSC_VER +#pragma section("rti_fn$f",read) + #if RT_DEBUG_INIT + struct rt_init_desc + { + const char* level; + const init_fn_t fn; + const char* fn_name; + }; + #define INIT_EXPORT(fn, level) \ + const char __rti_level_##fn[] = ".rti_fn." level; \ + const char __rti_##fn##_name[] = #fn; \ + __declspec(allocate("rti_fn$f")) \ + rt_used const struct rt_init_desc __rt_init_msc_##fn = \ + {__rti_level_##fn, fn, __rti_##fn##_name}; + #else + struct rt_init_desc + { + const char* level; + const init_fn_t fn; + }; + #define INIT_EXPORT(fn, level) \ + const char __rti_level_##fn[] = ".rti_fn." level; \ + __declspec(allocate("rti_fn$f")) \ + rt_used const struct rt_init_desc __rt_init_msc_##fn = \ + {__rti_level_##fn, fn }; + #endif +#else + #if RT_DEBUG_INIT + struct rt_init_desc + { + const char* fn_name; + const init_fn_t fn; + }; + #define INIT_EXPORT(fn, level) \ + const char __rti_##fn##_name[] = #fn; \ + rt_used const struct rt_init_desc __rt_init_desc_##fn rt_section(".rti_fn." level) = \ + { __rti_##fn##_name, fn}; + #else + #define INIT_EXPORT(fn, level) \ + rt_used const init_fn_t __rt_init_##fn rt_section(".rti_fn." level) = fn + #endif +#endif +#else +#define INIT_EXPORT(fn, level) +#endif + +/* board init routines will be called in board_init() function */ +#define INIT_BOARD_EXPORT(fn) INIT_EXPORT(fn, "1") + +/* pre/device/component/env/app init routines will be called in init_thread */ +/* components pre-initialization (pure software initialization) */ +#define INIT_PREV_EXPORT(fn) INIT_EXPORT(fn, "2") +/* device initialization */ +#define INIT_DEVICE_EXPORT(fn) INIT_EXPORT(fn, "3") +/* components initialization (dfs, lwip, ...) */ +#define INIT_COMPONENT_EXPORT(fn) INIT_EXPORT(fn, "4") +/* environment initialization (mount disk, ...) */ +#define INIT_ENV_EXPORT(fn) INIT_EXPORT(fn, "5") +/* application initialization (rtgui application etc ...) */ +#define INIT_APP_EXPORT(fn) INIT_EXPORT(fn, "6") + +#if !defined(RT_USING_FINSH) +/* define these to empty, even if not include finsh.h file */ +#define FINSH_FUNCTION_EXPORT(name, desc) +#define FINSH_FUNCTION_EXPORT_ALIAS(name, alias, desc) + +#define MSH_CMD_EXPORT(command, desc) +#define MSH_CMD_EXPORT_ALIAS(command, alias, desc) +#elif !defined(FINSH_USING_SYMTAB) +#define FINSH_FUNCTION_EXPORT_CMD(name, cmd, desc) +#endif + +/* event length */ +#define RT_EVENT_LENGTH 32 + +/* memory management option */ +#define RT_MM_PAGE_SIZE 4096 +#define RT_MM_PAGE_MASK (RT_MM_PAGE_SIZE - 1) +#define RT_MM_PAGE_BITS 12 + +/* kernel malloc definitions */ +#ifndef RT_KERNEL_MALLOC +#define RT_KERNEL_MALLOC(sz) rt_malloc(sz) +#endif + +#ifndef RT_KERNEL_FREE +#define RT_KERNEL_FREE(ptr) rt_free(ptr) +#endif + +#ifndef RT_KERNEL_REALLOC +#define RT_KERNEL_REALLOC(ptr, size) rt_realloc(ptr, size) +#endif + +/** + * @addtogroup Error + */ + +/**@{*/ + +/* RT-Thread error code definitions */ +#define RT_EOK 0 /**< There is no error */ +#define RT_ERROR 1 /**< A generic error happens */ +#define RT_ETIMEOUT 2 /**< Timed out */ +#define RT_EFULL 3 /**< The resource is full */ +#define RT_EEMPTY 4 /**< The resource is empty */ +#define RT_ENOMEM 5 /**< No memory */ +#define RT_ENOSYS 6 /**< No system */ +#define RT_EBUSY 7 /**< Busy */ +#define RT_EIO 8 /**< IO error */ +#define RT_EINTR 9 /**< Interrupted system call */ +#define RT_EINVAL 10 /**< Invalid argument */ +#define RT_ETRAP 11 /**< Trap event */ +#define RT_ENOENT 12 /**< No entry */ +#define RT_ENOSPC 13 /**< No space left */ + +/**@}*/ + +/** + * @ingroup BasicDef + * + * @def RT_ALIGN(size, align) + * Return the most contiguous size aligned at specified width. RT_ALIGN(13, 4) + * would return 16. + */ +#define RT_ALIGN(size, align) (((size) + (align) - 1) & ~((align) - 1)) + +/** + * @ingroup BasicDef + * + * @def RT_ALIGN_DOWN(size, align) + * Return the down number of aligned at specified width. RT_ALIGN_DOWN(13, 4) + * would return 12. + */ +#define RT_ALIGN_DOWN(size, align) ((size) & ~((align) - 1)) + +/** + * Double List structure + */ +struct rt_list_node +{ + struct rt_list_node *next; /**< point to next node. */ + struct rt_list_node *prev; /**< point to prev node. */ +}; +typedef struct rt_list_node rt_list_t; /**< Type for lists. */ + +/** + * Single List structure + */ +struct rt_slist_node +{ + struct rt_slist_node *next; /**< point to next node. */ +}; +typedef struct rt_slist_node rt_slist_t; /**< Type for single list. */ + +/** + * @addtogroup KernelObject + */ + +/**@{*/ + +/* + * kernel object macros + */ +#define RT_OBJECT_FLAG_MODULE 0x80 /**< is module object. */ + +/** + * Base structure of Kernel object + */ +struct rt_object +{ +#if RT_NAME_MAX > 0 + char name[RT_NAME_MAX]; /**< dynamic name of kernel object */ +#else + const char *name; /**< static name of kernel object */ +#endif /* RT_NAME_MAX > 0 */ + rt_uint8_t type; /**< type of kernel object */ + rt_uint8_t flag; /**< flag of kernel object */ + +#ifdef RT_USING_MODULE + void * module_id; /**< id of application module */ +#endif /* RT_USING_MODULE */ + +#ifdef RT_USING_SMART + int lwp_ref_count; /**< ref count for lwp */ +#endif /* RT_USING_SMART */ + + rt_list_t list; /**< list node of kernel object */ +}; +typedef struct rt_object *rt_object_t; /**< Type for kernel objects. */ + +/** + * The object type can be one of the follows with specific + * macros enabled: + * - Thread + * - Semaphore + * - Mutex + * - Event + * - MailBox + * - MessageQueue + * - MemHeap + * - MemPool + * - Device + * - Timer + * - Module + * - Unknown + * - Static + */ +enum rt_object_class_type +{ + RT_Object_Class_Null = 0x00, /**< The object is not used. */ + RT_Object_Class_Thread = 0x01, /**< The object is a thread. */ + RT_Object_Class_Semaphore = 0x02, /**< The object is a semaphore. */ + RT_Object_Class_Mutex = 0x03, /**< The object is a mutex. */ + RT_Object_Class_Event = 0x04, /**< The object is a event. */ + RT_Object_Class_MailBox = 0x05, /**< The object is a mail box. */ + RT_Object_Class_MessageQueue = 0x06, /**< The object is a message queue. */ + RT_Object_Class_MemHeap = 0x07, /**< The object is a memory heap. */ + RT_Object_Class_MemPool = 0x08, /**< The object is a memory pool. */ + RT_Object_Class_Device = 0x09, /**< The object is a device. */ + RT_Object_Class_Timer = 0x0a, /**< The object is a timer. */ + RT_Object_Class_Module = 0x0b, /**< The object is a module. */ + RT_Object_Class_Memory = 0x0c, /**< The object is a memory. */ + RT_Object_Class_Channel = 0x0d, /**< The object is a channel */ + RT_Object_Class_Custom = 0x0e, /**< The object is a custom object */ + RT_Object_Class_Unknown = 0x0f, /**< The object is unknown. */ + RT_Object_Class_Static = 0x80 /**< The object is a static object. */ +}; + +/** + * The information of the kernel object + */ +struct rt_object_information +{ + enum rt_object_class_type type; /**< object class type */ + rt_list_t object_list; /**< object list */ + rt_size_t object_size; /**< object size */ +}; + +/** + * The hook function call macro + */ +#ifndef RT_USING_HOOK + #define __ON_HOOK_ARGS(__hook, argv) + #define RT_OBJECT_HOOK_CALL(func, argv) +#else + #define RT_OBJECT_HOOK_CALL(func, argv) __on_##func argv + #ifdef RT_HOOK_USING_FUNC_PTR + #define __ON_HOOK_ARGS(__hook, argv) do {if ((__hook) != RT_NULL) __hook argv; } while (0) + #else + #define __ON_HOOK_ARGS(__hook, argv) + #endif /* RT_HOOK_USING_FUNC_PTR */ +#endif /* RT_USING_HOOK */ + +#ifndef __on_rt_interrupt_switch_hook + #define __on_rt_interrupt_switch_hook() __ON_HOOK_ARGS(rt_interrupt_switch_hook, ()) +#endif +#ifndef __on_rt_malloc_hook + #define __on_rt_malloc_hook(addr, size) __ON_HOOK_ARGS(rt_malloc_hook, (addr, size)) +#endif +#ifndef __on_rt_free_hook + #define __on_rt_free_hook(rmem) __ON_HOOK_ARGS(rt_free_hook, (rmem)) +#endif + + +/**@}*/ + +/** + * @addtogroup Clock + */ + +/**@{*/ + +/** + * clock & timer macros + */ +#define RT_TIMER_FLAG_DEACTIVATED 0x0 /**< timer is deactive */ +#define RT_TIMER_FLAG_ACTIVATED 0x1 /**< timer is active */ +#define RT_TIMER_FLAG_ONE_SHOT 0x0 /**< one shot timer */ +#define RT_TIMER_FLAG_PERIODIC 0x2 /**< periodic timer */ + +#define RT_TIMER_FLAG_HARD_TIMER 0x0 /**< hard timer,the timer's callback function will be called in tick isr. */ +#define RT_TIMER_FLAG_SOFT_TIMER 0x4 /**< soft timer,the timer's callback function will be called in timer thread. */ + +#define RT_TIMER_CTRL_SET_TIME 0x0 /**< set timer control command */ +#define RT_TIMER_CTRL_GET_TIME 0x1 /**< get timer control command */ +#define RT_TIMER_CTRL_SET_ONESHOT 0x2 /**< change timer to one shot */ +#define RT_TIMER_CTRL_SET_PERIODIC 0x3 /**< change timer to periodic */ +#define RT_TIMER_CTRL_GET_STATE 0x4 /**< get timer run state active or deactive*/ +#define RT_TIMER_CTRL_GET_REMAIN_TIME 0x5 /**< get the remaining hang time */ +#define RT_TIMER_CTRL_GET_FUNC 0x6 /**< get timer timeout func */ +#define RT_TIMER_CTRL_SET_FUNC 0x7 /**< set timer timeout func */ +#define RT_TIMER_CTRL_GET_PARM 0x8 /**< get timer parameter */ +#define RT_TIMER_CTRL_SET_PARM 0x9 /**< get timer parameter */ + +#ifndef RT_TIMER_SKIP_LIST_LEVEL +#define RT_TIMER_SKIP_LIST_LEVEL 1 +#endif + +/* 1 or 3 */ +#ifndef RT_TIMER_SKIP_LIST_MASK +#define RT_TIMER_SKIP_LIST_MASK 0x3 /**< Timer skips the list mask */ +#endif + +/** + * timer structure + */ +struct rt_timer +{ + struct rt_object parent; /**< inherit from rt_object */ + + rt_list_t row[RT_TIMER_SKIP_LIST_LEVEL]; + + void (*timeout_func)(void *parameter); /**< timeout function */ + void *parameter; /**< timeout function's parameter */ + + rt_tick_t init_tick; /**< timer timeout tick */ + rt_tick_t timeout_tick; /**< timeout tick */ +}; +typedef struct rt_timer *rt_timer_t; + +/**@}*/ + +/** + * @addtogroup Signal + */ +/**@{*/ + +#ifdef RT_USING_SIGNALS +#include +typedef unsigned long rt_sigset_t; +typedef siginfo_t rt_siginfo_t; +typedef void (*rt_sighandler_t)(int signo); + +#define RT_SIG_MAX 32 + +#else + +#ifdef RT_USING_SMART +#include +#endif + +#endif /* RT_USING_SIGNALS */ +/**@}*/ + +/** + * @addtogroup Thread + */ + +/**@{*/ + +/* + * Thread + */ + +/* + * thread state definitions + */ +#define RT_THREAD_INIT 0x00 /**< Initialized status */ +#define RT_THREAD_CLOSE 0x01 /**< Closed status */ +#define RT_THREAD_READY 0x02 /**< Ready status */ +#define RT_THREAD_RUNNING 0x03 /**< Running status */ + +/* + * for rt_thread_suspend_with_flag() + */ +enum +{ + RT_INTERRUPTIBLE = 0, + RT_KILLABLE, + RT_UNINTERRUPTIBLE, +}; + +#define RT_THREAD_SUSPEND_MASK 0x04 +#define RT_SIGNAL_COMMON_WAKEUP_MASK 0x02 +#define RT_SIGNAL_KILL_WAKEUP_MASK 0x01 + +#define RT_THREAD_SUSPEND_INTERRUPTIBLE (RT_THREAD_SUSPEND_MASK) /**< Suspend interruptable 0x4 */ +#define RT_THREAD_SUSPEND RT_THREAD_SUSPEND_INTERRUPTIBLE +#define RT_THREAD_SUSPEND_KILLABLE (RT_THREAD_SUSPEND_MASK | RT_SIGNAL_COMMON_WAKEUP_MASK) /**< Suspend with killable 0x6 */ +#define RT_THREAD_SUSPEND_UNINTERRUPTIBLE (RT_THREAD_SUSPEND_MASK | RT_SIGNAL_COMMON_WAKEUP_MASK | RT_SIGNAL_KILL_WAKEUP_MASK) /**< Suspend with uninterruptable 0x7 */ +#define RT_THREAD_STAT_MASK 0x07 + +#define RT_THREAD_STAT_YIELD 0x08 /**< indicate whether remaining_tick has been reloaded since last schedule */ +#define RT_THREAD_STAT_YIELD_MASK RT_THREAD_STAT_YIELD + +#define RT_THREAD_STAT_SIGNAL 0x10 /**< task hold signals */ +#define RT_THREAD_STAT_SIGNAL_READY (RT_THREAD_STAT_SIGNAL | RT_THREAD_READY) +#define RT_THREAD_STAT_SIGNAL_WAIT 0x20 /**< task is waiting for signals */ +#define RT_THREAD_STAT_SIGNAL_PENDING 0x40 /**< signals is held and it has not been procressed */ +#define RT_THREAD_STAT_SIGNAL_MASK 0xf0 + +/** + * thread control command definitions + */ +#define RT_THREAD_CTRL_STARTUP 0x00 /**< Startup thread. */ +#define RT_THREAD_CTRL_CLOSE 0x01 /**< Close thread. */ +#define RT_THREAD_CTRL_CHANGE_PRIORITY 0x02 /**< Change thread priority. */ +#define RT_THREAD_CTRL_INFO 0x03 /**< Get thread information. */ +#define RT_THREAD_CTRL_BIND_CPU 0x04 /**< Set thread bind cpu. */ + +#ifdef RT_USING_SMP + +#define RT_CPU_DETACHED RT_CPUS_NR /**< The thread not running on cpu. */ +#define RT_CPU_MASK ((1 << RT_CPUS_NR) - 1) /**< All CPUs mask bit. */ + +#ifndef RT_SCHEDULE_IPI +#define RT_SCHEDULE_IPI 0 +#endif /* RT_SCHEDULE_IPI */ + +#ifndef RT_STOP_IPI +#define RT_STOP_IPI 1 +#endif /* RT_STOP_IPI */ + +/** + * CPUs definitions + * + */ +struct rt_cpu +{ + struct rt_thread *current_thread; + + rt_uint16_t irq_nest; + rt_uint8_t irq_switch_flag; + + rt_uint8_t current_priority; + rt_list_t priority_table[RT_THREAD_PRIORITY_MAX]; +#if RT_THREAD_PRIORITY_MAX > 32 + rt_uint32_t priority_group; + rt_uint8_t ready_table[32]; +#else + rt_uint32_t priority_group; +#endif /* RT_THREAD_PRIORITY_MAX > 32 */ + + rt_tick_t tick; +}; + +#endif /* RT_USING_SMP */ + +struct rt_thread; + +#ifdef RT_USING_SMART +typedef rt_err_t (*rt_wakeup_func_t)(void *object, struct rt_thread *thread); + +struct rt_wakeup +{ + rt_wakeup_func_t func; + void *user_data; +}; + +#define _LWP_NSIG 64 + +#ifdef ARCH_CPU_64BIT +#define _LWP_NSIG_BPW 64 +#else +#define _LWP_NSIG_BPW 32 +#endif + +#define _LWP_NSIG_WORDS (_LWP_NSIG / _LWP_NSIG_BPW) + +typedef void (*lwp_sighandler_t)(int); + +typedef struct { + unsigned long sig[_LWP_NSIG_WORDS]; +} lwp_sigset_t; + +struct lwp_sigaction { + union { + void (*_sa_handler)(int); + void (*_sa_sigaction)(int, siginfo_t *, void *); + } __sa_handler; + lwp_sigset_t sa_mask; + int sa_flags; + void (*sa_restorer)(void); +}; + +struct rt_user_context +{ + void *sp; + void *pc; + void *flag; +}; +#endif + +/** + * Thread structure + */ +struct rt_thread +{ + /* rt object */ +#if RT_NAME_MAX > 0 + char name[RT_NAME_MAX]; /**< dynamic name of kernel object */ +#else + const char *name; /**< static name of kernel object */ +#endif /* RT_NAME_MAX > 0 */ + rt_uint8_t type; /**< type of object */ + rt_uint8_t flags; /**< thread's flags */ + +#ifdef RT_USING_MODULE + void *module_id; /**< id of application module */ +#endif /* RT_USING_MODULE */ + +#ifdef RT_USING_SMART + int lwp_ref_count; /**< ref count for lwp */ +#endif /* RT_USING_SMART */ + + rt_list_t list; /**< the object list */ + rt_list_t tlist; /**< the thread list */ + + /* stack point and entry */ + void *sp; /**< stack point */ + void *entry; /**< entry */ + void *parameter; /**< parameter */ + void *stack_addr; /**< stack address */ + rt_uint32_t stack_size; /**< stack size */ + + /* error code */ + rt_err_t error; /**< error code */ + + rt_uint8_t stat; /**< thread status */ + +#ifdef RT_USING_SMP + rt_uint8_t bind_cpu; /**< thread is bind to cpu */ + rt_uint8_t oncpu; /**< process on cpu */ + + rt_uint16_t scheduler_lock_nest; /**< scheduler lock count */ + rt_uint16_t cpus_lock_nest; /**< cpus lock count */ + rt_uint16_t critical_lock_nest; /**< critical lock count */ +#endif /*RT_USING_SMP*/ + + /* priority */ + rt_uint8_t current_priority; /**< current priority */ + rt_uint8_t init_priority; /**< initialized priority */ +#if RT_THREAD_PRIORITY_MAX > 32 + rt_uint8_t number; + rt_uint8_t high_mask; +#endif /* RT_THREAD_PRIORITY_MAX > 32 */ + rt_uint32_t number_mask; /**< priority number mask */ + +#ifdef RT_USING_MUTEX + /* object for IPC */ + rt_list_t taken_object_list; + rt_object_t pending_object; +#endif + +#ifdef RT_USING_EVENT + /* thread event */ + rt_uint32_t event_set; + rt_uint8_t event_info; +#endif /* RT_USING_EVENT */ + +#ifdef RT_USING_SIGNALS + rt_sigset_t sig_pending; /**< the pending signals */ + rt_sigset_t sig_mask; /**< the mask bits of signal */ + +#ifndef RT_USING_SMP + void *sig_ret; /**< the return stack pointer from signal */ +#endif /* RT_USING_SMP */ + rt_sighandler_t *sig_vectors; /**< vectors of signal handler */ + void *si_list; /**< the signal infor list */ +#endif /* RT_USING_SIGNALS */ + +#ifdef RT_USING_SMART + void *msg_ret; /**< the return msg */ +#endif + + rt_ubase_t init_tick; /**< thread's initialized tick */ + rt_ubase_t remaining_tick; /**< remaining tick */ + +#ifdef RT_USING_CPU_USAGE + rt_uint64_t duration_tick; /**< cpu usage tick */ +#endif /* RT_USING_CPU_USAGE */ + +#ifdef RT_USING_PTHREADS + void *pthread_data; /**< the handle of pthread data, adapt 32/64bit */ +#endif /* RT_USING_PTHREADS */ + + struct rt_timer thread_timer; /**< built-in thread timer */ + + void (*cleanup)(struct rt_thread *tid); /**< cleanup function when thread exit */ + + /* light weight process if present */ +#ifdef RT_USING_SMART + void *lwp; + /* for user create */ + void *user_entry; + void *user_stack; + rt_uint32_t user_stack_size; + rt_uint32_t *kernel_sp; /**< kernel stack point */ + rt_list_t sibling; /**< next thread of same process */ + + lwp_sigset_t signal; + lwp_sigset_t signal_mask; + int signal_mask_bak; + rt_uint32_t signal_in_process; +#ifndef ARCH_MM_MMU + lwp_sighandler_t signal_handler[32]; +#endif + struct rt_user_context user_ctx; + + struct rt_wakeup wakeup; /**< wakeup data */ + int exit_request; +#if defined(ARCH_MM_MMU) + int step_exec; + int debug_attach_req; + int debug_ret_user; + int debug_suspend; + struct rt_hw_exp_stack *regs; + void * thread_idr; /** lwp thread indicator */ + int *clear_child_tid; +#endif + int tid; +#endif + + rt_ubase_t user_data; /**< private user data beyond this thread */ +}; +typedef struct rt_thread *rt_thread_t; + +/**@}*/ + +/** + * @addtogroup IPC + */ + +/**@{*/ + +/** + * IPC flags and control command definitions + */ +#define RT_IPC_FLAG_FIFO 0x00 /**< FIFOed IPC. @ref IPC. */ +#define RT_IPC_FLAG_PRIO 0x01 /**< PRIOed IPC. @ref IPC. */ + +#define RT_IPC_CMD_UNKNOWN 0x00 /**< unknown IPC command */ +#define RT_IPC_CMD_RESET 0x01 /**< reset IPC object */ +#define RT_IPC_CMD_GET_STATE 0x02 /**< get the state of IPC object */ + +#define RT_WAITING_FOREVER -1 /**< Block forever until get resource. */ +#define RT_WAITING_NO 0 /**< Non-block. */ + +/** + * Base structure of IPC object + */ +struct rt_ipc_object +{ + struct rt_object parent; /**< inherit from rt_object */ + + rt_list_t suspend_thread; /**< threads pended on this resource */ +}; + +#ifdef RT_USING_SEMAPHORE +/** + * Semaphore structure + */ +struct rt_semaphore +{ + struct rt_ipc_object parent; /**< inherit from ipc_object */ + + rt_uint16_t value; /**< value of semaphore. */ + rt_uint16_t reserved; /**< reserved field */ +}; +typedef struct rt_semaphore *rt_sem_t; +#endif /* RT_USING_SEMAPHORE */ + +#ifdef RT_USING_MUTEX +/** + * Mutual exclusion (mutex) structure + */ +struct rt_mutex +{ + struct rt_ipc_object parent; /**< inherit from ipc_object */ + + rt_uint8_t ceiling_priority; /**< the priority ceiling of mutexe */ + rt_uint8_t priority; /**< the maximal priority for pending thread */ + rt_uint8_t hold; /**< numbers of thread hold the mutex */ + rt_uint8_t reserved; /**< reserved field */ + + struct rt_thread *owner; /**< current owner of mutex */ + rt_list_t taken_list; /**< the object list taken by thread */ +}; +typedef struct rt_mutex *rt_mutex_t; +#endif /* RT_USING_MUTEX */ + +#ifdef RT_USING_EVENT +/** + * flag definitions in event + */ +#define RT_EVENT_FLAG_AND 0x01 /**< logic and */ +#define RT_EVENT_FLAG_OR 0x02 /**< logic or */ +#define RT_EVENT_FLAG_CLEAR 0x04 /**< clear flag */ + +/* + * event structure + */ +struct rt_event +{ + struct rt_ipc_object parent; /**< inherit from ipc_object */ + + rt_uint32_t set; /**< event set */ +}; +typedef struct rt_event *rt_event_t; +#endif /* RT_USING_EVENT */ + +#ifdef RT_USING_MAILBOX +/** + * mailbox structure + */ +struct rt_mailbox +{ + struct rt_ipc_object parent; /**< inherit from ipc_object */ + + rt_ubase_t *msg_pool; /**< start address of message buffer */ + + rt_uint16_t size; /**< size of message pool */ + + rt_uint16_t entry; /**< index of messages in msg_pool */ + rt_uint16_t in_offset; /**< input offset of the message buffer */ + rt_uint16_t out_offset; /**< output offset of the message buffer */ + + rt_list_t suspend_sender_thread; /**< sender thread suspended on this mailbox */ +}; +typedef struct rt_mailbox *rt_mailbox_t; +#endif /* RT_USING_MAILBOX */ + +#ifdef RT_USING_MESSAGEQUEUE +/** + * message queue structure + */ +struct rt_messagequeue +{ + struct rt_ipc_object parent; /**< inherit from ipc_object */ + + void *msg_pool; /**< start address of message queue */ + + rt_uint16_t msg_size; /**< message size of each message */ + rt_uint16_t max_msgs; /**< max number of messages */ + + rt_uint16_t entry; /**< index of messages in the queue */ + + void *msg_queue_head; /**< list head */ + void *msg_queue_tail; /**< list tail */ + void *msg_queue_free; /**< pointer indicated the free node of queue */ + + rt_list_t suspend_sender_thread; /**< sender thread suspended on this message queue */ +}; +typedef struct rt_messagequeue *rt_mq_t; +#endif /* RT_USING_MESSAGEQUEUE */ + +/**@}*/ + +/** + * @addtogroup MM + */ + +/**@{*/ + +#ifdef RT_USING_HEAP +/* + * memory structure + */ +struct rt_memory +{ + struct rt_object parent; /**< inherit from rt_object */ + const char * algorithm; /**< Memory management algorithm name */ + rt_ubase_t address; /**< memory start address */ + rt_size_t total; /**< memory size */ + rt_size_t used; /**< size used */ + rt_size_t max; /**< maximum usage */ +}; +typedef struct rt_memory *rt_mem_t; +#endif /* RT_USING_HEAP */ + +/* + * memory management + * heap & partition + */ + +#ifdef RT_USING_SMALL_MEM +typedef rt_mem_t rt_smem_t; +#endif /* RT_USING_SMALL_MEM */ + +#ifdef RT_USING_SLAB +typedef rt_mem_t rt_slab_t; +#endif /* RT_USING_SLAB */ + +#ifdef RT_USING_MEMHEAP +/** + * memory item on the heap + */ +struct rt_memheap_item +{ + rt_uint32_t magic; /**< magic number for memheap */ + struct rt_memheap *pool_ptr; /**< point of pool */ + + struct rt_memheap_item *next; /**< next memheap item */ + struct rt_memheap_item *prev; /**< prev memheap item */ + + struct rt_memheap_item *next_free; /**< next free memheap item */ + struct rt_memheap_item *prev_free; /**< prev free memheap item */ +#ifdef RT_USING_MEMTRACE + rt_uint8_t owner_thread_name[4]; /**< owner thread name */ +#endif /* RT_USING_MEMTRACE */ +}; + +/** + * Base structure of memory heap object + */ +struct rt_memheap +{ + struct rt_object parent; /**< inherit from rt_object */ + + void *start_addr; /**< pool start address and size */ + + rt_size_t pool_size; /**< pool size */ + rt_size_t available_size; /**< available size */ + rt_size_t max_used_size; /**< maximum allocated size */ + + struct rt_memheap_item *block_list; /**< used block list */ + + struct rt_memheap_item *free_list; /**< free block list */ + struct rt_memheap_item free_header; /**< free block list header */ + + struct rt_semaphore lock; /**< semaphore lock */ + rt_bool_t locked; /**< External lock mark */ +}; +#endif /* RT_USING_MEMHEAP */ + +#ifdef RT_USING_MEMPOOL +/** + * Base structure of Memory pool object + */ +struct rt_mempool +{ + struct rt_object parent; /**< inherit from rt_object */ + + void *start_address; /**< memory pool start */ + rt_size_t size; /**< size of memory pool */ + + rt_size_t block_size; /**< size of memory blocks */ + rt_uint8_t *block_list; /**< memory blocks list */ + + rt_size_t block_total_count; /**< numbers of memory block */ + rt_size_t block_free_count; /**< numbers of free memory block */ + + rt_list_t suspend_thread; /**< threads pended on this resource */ +}; +typedef struct rt_mempool *rt_mp_t; +#endif /* RT_USING_MEMPOOL */ + +/**@}*/ + +#ifdef RT_USING_DEVICE +/** + * @addtogroup Device + */ + +/**@{*/ + +/** + * device (I/O) class type + */ +enum rt_device_class_type +{ + RT_Device_Class_Char = 0, /**< character device */ + RT_Device_Class_Block, /**< block device */ + RT_Device_Class_NetIf, /**< net interface */ + RT_Device_Class_MTD, /**< memory device */ + RT_Device_Class_CAN, /**< CAN device */ + RT_Device_Class_RTC, /**< RTC device */ + RT_Device_Class_Sound, /**< Sound device */ + RT_Device_Class_Graphic, /**< Graphic device */ + RT_Device_Class_I2CBUS, /**< I2C bus device */ + RT_Device_Class_USBDevice, /**< USB slave device */ + RT_Device_Class_USBHost, /**< USB host bus */ + RT_Device_Class_USBOTG, /**< USB OTG bus */ + RT_Device_Class_SPIBUS, /**< SPI bus device */ + RT_Device_Class_SPIDevice, /**< SPI device */ + RT_Device_Class_SDIO, /**< SDIO bus device */ + RT_Device_Class_PM, /**< PM pseudo device */ + RT_Device_Class_Pipe, /**< Pipe device */ + RT_Device_Class_Portal, /**< Portal device */ + RT_Device_Class_Timer, /**< Timer device */ + RT_Device_Class_Miscellaneous, /**< Miscellaneous device */ + RT_Device_Class_Sensor, /**< Sensor device */ + RT_Device_Class_Touch, /**< Touch device */ + RT_Device_Class_PHY, /**< PHY device */ + RT_Device_Class_Security, /**< Security device */ + RT_Device_Class_WLAN, /**< WLAN device */ + RT_Device_Class_Pin, /**< Pin device */ + RT_Device_Class_ADC, /**< ADC device */ + RT_Device_Class_DAC, /**< DAC device */ + RT_Device_Class_WDT, /**< WDT device */ + RT_Device_Class_PWM, /**< PWM device */ + RT_Device_Class_Bus, /**< Bus device */ + RT_Device_Class_Unknown /**< unknown device */ +}; + +/** + * device flags definitions + */ +#define RT_DEVICE_FLAG_DEACTIVATE 0x000 /**< device is not not initialized */ + +#define RT_DEVICE_FLAG_RDONLY 0x001 /**< read only */ +#define RT_DEVICE_FLAG_WRONLY 0x002 /**< write only */ +#define RT_DEVICE_FLAG_RDWR 0x003 /**< read and write */ + +#define RT_DEVICE_FLAG_REMOVABLE 0x004 /**< removable device */ +#define RT_DEVICE_FLAG_STANDALONE 0x008 /**< standalone device */ +#define RT_DEVICE_FLAG_ACTIVATED 0x010 /**< device is activated */ +#define RT_DEVICE_FLAG_SUSPENDED 0x020 /**< device is suspended */ +#define RT_DEVICE_FLAG_STREAM 0x040 /**< stream mode */ + +#define RT_DEVICE_FLAG_INT_RX 0x100 /**< INT mode on Rx */ +#define RT_DEVICE_FLAG_DMA_RX 0x200 /**< DMA mode on Rx */ +#define RT_DEVICE_FLAG_INT_TX 0x400 /**< INT mode on Tx */ +#define RT_DEVICE_FLAG_DMA_TX 0x800 /**< DMA mode on Tx */ + +#define RT_DEVICE_OFLAG_CLOSE 0x000 /**< device is closed */ +#define RT_DEVICE_OFLAG_RDONLY 0x001 /**< read only access */ +#define RT_DEVICE_OFLAG_WRONLY 0x002 /**< write only access */ +#define RT_DEVICE_OFLAG_RDWR 0x003 /**< read and write */ +#define RT_DEVICE_OFLAG_OPEN 0x008 /**< device is opened */ +#define RT_DEVICE_OFLAG_MASK 0xf0f /**< mask of open flag */ + +/** + * general device commands + * 0x01 - 0x1F general device control commands + * 0x20 - 0x3F udevice control commands + * 0x40 - special device control commands + */ +#define RT_DEVICE_CTRL_RESUME 0x01 /**< resume device */ +#define RT_DEVICE_CTRL_SUSPEND 0x02 /**< suspend device */ +#define RT_DEVICE_CTRL_CONFIG 0x03 /**< configure device */ +#define RT_DEVICE_CTRL_CLOSE 0x04 /**< close device */ +#define RT_DEVICE_CTRL_NOTIFY_SET 0x05 /**< set notify func */ +#define RT_DEVICE_CTRL_SET_INT 0x06 /**< set interrupt */ +#define RT_DEVICE_CTRL_CLR_INT 0x07 /**< clear interrupt */ +#define RT_DEVICE_CTRL_GET_INT 0x08 /**< get interrupt status */ +#define RT_DEVICE_CTRL_CONSOLE_OFLAG 0x09 /**< get console open flag */ +#define RT_DEVICE_CTRL_MASK 0x1f /**< mask for contrl commands */ + +/** + * device control + */ +#define RT_DEVICE_CTRL_BASE(Type) ((RT_Device_Class_##Type + 1) * 0x100) + +/** + * special device commands + */ +/* character device */ +#define RT_DEVICE_CTRL_CHAR_STREAM (RT_DEVICE_CTRL_BASE(Char) + 1) /**< stream mode on char device */ +/* block device */ +#define RT_DEVICE_CTRL_BLK_GETGEOME (RT_DEVICE_CTRL_BASE(Block) + 1) /**< get geometry information */ +#define RT_DEVICE_CTRL_BLK_SYNC (RT_DEVICE_CTRL_BASE(Block) + 2) /**< flush data to block device */ +#define RT_DEVICE_CTRL_BLK_ERASE (RT_DEVICE_CTRL_BASE(Block) + 3) /**< erase block on block device */ +#define RT_DEVICE_CTRL_BLK_AUTOREFRESH (RT_DEVICE_CTRL_BASE(Block) + 4) /**< block device : enter/exit auto refresh mode */ +#define RT_DEVICE_CTRL_BLK_PARTITION (RT_DEVICE_CTRL_BASE(Block) + 5) /**< get block device partition */ +/* net interface device*/ +#define RT_DEVICE_CTRL_NETIF_GETMAC (RT_DEVICE_CTRL_BASE(NetIf) + 1) /**< get mac address */ +/* mtd interface device*/ +#define RT_DEVICE_CTRL_MTD_FORMAT (RT_DEVICE_CTRL_BASE(MTD) + 1) /**< format a MTD device */ + +typedef struct rt_device *rt_device_t; + +#ifdef RT_USING_DEVICE_OPS +/** + * operations set for device object + */ +struct rt_device_ops +{ + /* common device interface */ + rt_err_t (*init) (rt_device_t dev); + rt_err_t (*open) (rt_device_t dev, rt_uint16_t oflag); + rt_err_t (*close) (rt_device_t dev); + rt_ssize_t (*read) (rt_device_t dev, rt_off_t pos, void *buffer, rt_size_t size); + rt_ssize_t (*write) (rt_device_t dev, rt_off_t pos, const void *buffer, rt_size_t size); + rt_err_t (*control)(rt_device_t dev, int cmd, void *args); +}; +#endif /* RT_USING_DEVICE_OPS */ + +/** + * WaitQueue structure + */ +struct rt_wqueue +{ + rt_uint32_t flag; + rt_list_t waiting_list; +}; +typedef struct rt_wqueue rt_wqueue_t; + +/** + * Device structure + */ +struct rt_device +{ + struct rt_object parent; /**< inherit from rt_object */ +#ifdef RT_USING_DM + struct rt_driver *drv; + void *dtb_node; +#endif + enum rt_device_class_type type; /**< device type */ + rt_uint16_t flag; /**< device flag */ + rt_uint16_t open_flag; /**< device open flag */ + + rt_uint8_t ref_count; /**< reference count */ + rt_uint8_t device_id; /**< 0 - 255 */ + + /* device call back */ + rt_err_t (*rx_indicate)(rt_device_t dev, rt_size_t size); + rt_err_t (*tx_complete)(rt_device_t dev, void *buffer); + +#ifdef RT_USING_DEVICE_OPS + const struct rt_device_ops *ops; +#else + /* common device interface */ + rt_err_t (*init) (rt_device_t dev); + rt_err_t (*open) (rt_device_t dev, rt_uint16_t oflag); + rt_err_t (*close) (rt_device_t dev); + rt_ssize_t (*read) (rt_device_t dev, rt_off_t pos, void *buffer, rt_size_t size); + rt_ssize_t (*write) (rt_device_t dev, rt_off_t pos, const void *buffer, rt_size_t size); + rt_err_t (*control)(rt_device_t dev, int cmd, void *args); +#endif /* RT_USING_DEVICE_OPS */ + +#ifdef RT_USING_POSIX_DEVIO + const struct dfs_file_ops *fops; + struct rt_wqueue wait_queue; +#endif /* RT_USING_POSIX_DEVIO */ + + void *user_data; /**< device private data */ +}; + +#define RT_DRIVER_MATCH_DTS (1<<0) +struct rt_device_id +{ + const char *compatible; + void *data; +}; + +struct rt_driver +{ +#ifdef RT_USING_DEVICE_OPS + const struct rt_device_ops *dev_ops; +#else + /* common device interface */ + rt_err_t (*init) (rt_device_t dev); + rt_err_t (*open) (rt_device_t dev, rt_uint16_t oflag); + rt_err_t (*close) (rt_device_t dev); + rt_ssize_t (*read) (rt_device_t dev, rt_off_t pos, void *buffer, rt_size_t size); + rt_ssize_t (*write) (rt_device_t dev, rt_off_t pos, const void *buffer, rt_size_t size); + rt_err_t (*control)(rt_device_t dev, int cmd, void *args); +#endif + const struct filesystem_ops *fops; + const char *name; + enum rt_device_class_type dev_type; + int device_size; + int flag; + const struct rt_device_id *dev_match; + int (*probe)(struct rt_device *dev); + int (*probe_init)(struct rt_device *dev); + int (*remove)(struct rt_device *dev); + const void *ops; /* driver-specific operations */ + void *drv_priv_data; +}; +typedef struct rt_driver *rt_driver_t; + +/** + * Notify structure + */ +struct rt_device_notify +{ + void (*notify)(rt_device_t dev); + struct rt_device *dev; +}; + +#ifdef RT_USING_SMART +struct rt_channel +{ + struct rt_ipc_object parent; /**< inherit from object */ + struct rt_thread *reply; /**< the thread will be reply */ + rt_list_t wait_msg; /**< the wait queue of sender msg */ + rt_list_t wait_thread; /**< the wait queue of sender thread */ + rt_wqueue_t reader_queue; /**< channel poll queue */ + rt_uint8_t stat; /**< the status of this channel */ + rt_ubase_t ref; +}; +typedef struct rt_channel *rt_channel_t; +#endif + +/** + * block device geometry structure + */ +struct rt_device_blk_geometry +{ + rt_uint64_t sector_count; /**< count of sectors */ + rt_uint32_t bytes_per_sector; /**< number of bytes per sector */ + rt_uint32_t block_size; /**< number of bytes to erase one block */ +}; + +/** + * sector arrange struct on block device + */ +struct rt_device_blk_sectors +{ + rt_uint64_t sector_begin; /**< begin sector */ + rt_uint64_t sector_end; /**< end sector */ +}; + +/** + * cursor control command + */ +#define RT_DEVICE_CTRL_CURSOR_SET_POSITION 0x10 +#define RT_DEVICE_CTRL_CURSOR_SET_TYPE 0x11 + +/** + * graphic device control command + */ +#define RTGRAPHIC_CTRL_RECT_UPDATE (RT_DEVICE_CTRL_BASE(Graphic) + 0) +#define RTGRAPHIC_CTRL_POWERON (RT_DEVICE_CTRL_BASE(Graphic) + 1) +#define RTGRAPHIC_CTRL_POWEROFF (RT_DEVICE_CTRL_BASE(Graphic) + 2) +#define RTGRAPHIC_CTRL_GET_INFO (RT_DEVICE_CTRL_BASE(Graphic) + 3) +#define RTGRAPHIC_CTRL_SET_MODE (RT_DEVICE_CTRL_BASE(Graphic) + 4) +#define RTGRAPHIC_CTRL_GET_EXT (RT_DEVICE_CTRL_BASE(Graphic) + 5) +#define RTGRAPHIC_CTRL_SET_BRIGHTNESS (RT_DEVICE_CTRL_BASE(Graphic) + 6) +#define RTGRAPHIC_CTRL_GET_BRIGHTNESS (RT_DEVICE_CTRL_BASE(Graphic) + 7) +#define RTGRAPHIC_CTRL_GET_MODE (RT_DEVICE_CTRL_BASE(Graphic) + 8) +#define RTGRAPHIC_CTRL_GET_STATUS (RT_DEVICE_CTRL_BASE(Graphic) + 9) +#define RTGRAPHIC_CTRL_PAN_DISPLAY (RT_DEVICE_CTRL_BASE(Graphic) + 10) +#define RTGRAPHIC_CTRL_WAIT_VSYNC (RT_DEVICE_CTRL_BASE(Graphic) + 11) + +/* graphic device */ +enum +{ + RTGRAPHIC_PIXEL_FORMAT_MONO = 0, + RTGRAPHIC_PIXEL_FORMAT_GRAY4, + RTGRAPHIC_PIXEL_FORMAT_GRAY16, + RTGRAPHIC_PIXEL_FORMAT_RGB332, + RTGRAPHIC_PIXEL_FORMAT_RGB444, + RTGRAPHIC_PIXEL_FORMAT_RGB565, + RTGRAPHIC_PIXEL_FORMAT_RGB565P, + RTGRAPHIC_PIXEL_FORMAT_BGR565 = RTGRAPHIC_PIXEL_FORMAT_RGB565P, + RTGRAPHIC_PIXEL_FORMAT_RGB666, + RTGRAPHIC_PIXEL_FORMAT_RGB888, + RTGRAPHIC_PIXEL_FORMAT_BGR888, + RTGRAPHIC_PIXEL_FORMAT_ARGB888, + RTGRAPHIC_PIXEL_FORMAT_ABGR888, + RTGRAPHIC_PIXEL_FORMAT_RESERVED, +}; + +/** + * build a pixel position according to (x, y) coordinates. + */ +#define RTGRAPHIC_PIXEL_POSITION(x, y) ((x << 16) | y) + +/** + * graphic device information structure + */ +struct rt_device_graphic_info +{ + rt_uint8_t pixel_format; /**< graphic format */ + rt_uint8_t bits_per_pixel; /**< bits per pixel */ + rt_uint16_t pitch; /**< bytes per line */ + + rt_uint16_t width; /**< width of graphic device */ + rt_uint16_t height; /**< height of graphic device */ + + rt_uint8_t *framebuffer; /**< frame buffer */ + rt_uint32_t smem_len; /**< allocated frame buffer size */ +}; + +/** + * rectangle information structure + */ +struct rt_device_rect_info +{ + rt_uint16_t x; /**< x coordinate */ + rt_uint16_t y; /**< y coordinate */ + rt_uint16_t width; /**< width */ + rt_uint16_t height; /**< height */ +}; + +/** + * graphic operations + */ +struct rt_device_graphic_ops +{ + void (*set_pixel) (const char *pixel, int x, int y); + void (*get_pixel) (char *pixel, int x, int y); + + void (*draw_hline)(const char *pixel, int x1, int x2, int y); + void (*draw_vline)(const char *pixel, int x, int y1, int y2); + + void (*blit_line) (const char *pixel, int x, int y, rt_size_t size); +}; +#define rt_graphix_ops(device) ((struct rt_device_graphic_ops *)(device->user_data)) + +/**@}*/ +#endif /* RT_USING_DEVICE */ + +#ifdef __cplusplus +} +#endif + +#ifdef __cplusplus +/* RT-Thread definitions for C++ */ +namespace rtthread { + +enum TICK_WAIT { + WAIT_NONE = 0, + WAIT_FOREVER = -1, +}; + +} + +#endif /* __cplusplus */ + +#endif /* __RT_DEF_H__ */ diff --git a/tasks/concur-rtthread-mutex-ceilings/template/include/rthw.h b/tasks/concur-rtthread-mutex-ceilings/template/include/rthw.h new file mode 100644 index 00000000..8bbc3794 --- /dev/null +++ b/tasks/concur-rtthread-mutex-ceilings/template/include/rthw.h @@ -0,0 +1,224 @@ +/* + * Copyright (c) 2006-2021, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2006-03-18 Bernard the first version + * 2006-04-25 Bernard add rt_hw_context_switch_interrupt declaration + * 2006-09-24 Bernard add rt_hw_context_switch_to declaration + * 2012-12-29 Bernard add rt_hw_exception_install declaration + * 2017-10-17 Hichard add some macros + * 2018-11-17 Jesven add rt_hw_spinlock_t + * add smp support + * 2019-05-18 Bernard add empty definition for not enable cache case + */ + +#ifndef __RT_HW_H__ +#define __RT_HW_H__ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * Some macros define + */ +#ifndef HWREG64 +#define HWREG64(x) (*((volatile rt_uint64_t *)(x))) +#endif +#ifndef HWREG32 +#define HWREG32(x) (*((volatile rt_uint32_t *)(x))) +#endif +#ifndef HWREG16 +#define HWREG16(x) (*((volatile rt_uint16_t *)(x))) +#endif +#ifndef HWREG8 +#define HWREG8(x) (*((volatile rt_uint8_t *)(x))) +#endif + +#ifndef RT_CPU_CACHE_LINE_SZ +#define RT_CPU_CACHE_LINE_SZ 32 +#endif + +enum RT_HW_CACHE_OPS +{ + RT_HW_CACHE_FLUSH = 0x01, + RT_HW_CACHE_INVALIDATE = 0x02, +}; + +/* + * CPU interfaces + */ +#ifdef RT_USING_CACHE + +#ifdef RT_USING_SMART +#include +#endif + +void rt_hw_cpu_icache_enable(void); +void rt_hw_cpu_icache_disable(void); +rt_base_t rt_hw_cpu_icache_status(void); +void rt_hw_cpu_icache_ops(int ops, void* addr, int size); + +void rt_hw_cpu_dcache_enable(void); +void rt_hw_cpu_dcache_disable(void); +rt_base_t rt_hw_cpu_dcache_status(void); +void rt_hw_cpu_dcache_ops(int ops, void* addr, int size); +#else + +/* define cache ops as empty */ +#define rt_hw_cpu_icache_enable(...) +#define rt_hw_cpu_icache_disable(...) +#define rt_hw_cpu_icache_ops(...) +#define rt_hw_cpu_dcache_enable(...) +#define rt_hw_cpu_dcache_disable(...) +#define rt_hw_cpu_dcache_ops(...) + +#define rt_hw_cpu_icache_status(...) 0 +#define rt_hw_cpu_dcache_status(...) 0 + +#endif + +void rt_hw_cpu_reset(void); +void rt_hw_cpu_shutdown(void); + +rt_uint8_t *rt_hw_stack_init(void *entry, + void *parameter, + rt_uint8_t *stack_addr, + void *exit); + +/* + * Interrupt handler definition + */ +typedef void (*rt_isr_handler_t)(int vector, void *param); + +struct rt_irq_desc +{ + rt_isr_handler_t handler; + void *param; + +#ifdef RT_USING_INTERRUPT_INFO + char name[RT_NAME_MAX]; + rt_uint32_t counter; +#endif +}; + +/* + * Interrupt interfaces + */ +void rt_hw_interrupt_init(void); +void rt_hw_interrupt_mask(int vector); +void rt_hw_interrupt_umask(int vector); +rt_isr_handler_t rt_hw_interrupt_install(int vector, + rt_isr_handler_t handler, + void *param, + const char *name); + +#ifdef RT_USING_SMP +rt_base_t rt_hw_local_irq_disable(); +void rt_hw_local_irq_enable(rt_base_t level); + +#define rt_hw_interrupt_disable rt_cpus_lock +#define rt_hw_interrupt_enable rt_cpus_unlock + +#else +rt_base_t rt_hw_interrupt_disable(void); +void rt_hw_interrupt_enable(rt_base_t level); +#endif /*RT_USING_SMP*/ + +/* + * Context interfaces + */ +#ifdef RT_USING_SMP +void rt_hw_context_switch(rt_ubase_t from, rt_ubase_t to, struct rt_thread *to_thread); +void rt_hw_context_switch_to(rt_ubase_t to, struct rt_thread *to_thread); +void rt_hw_context_switch_interrupt(void *context, rt_ubase_t from, rt_ubase_t to, struct rt_thread *to_thread); +#else +void rt_hw_context_switch(rt_ubase_t from, rt_ubase_t to); +void rt_hw_context_switch_to(rt_ubase_t to); +void rt_hw_context_switch_interrupt(rt_ubase_t from, rt_ubase_t to, rt_thread_t from_thread, rt_thread_t to_thread); +#endif /*RT_USING_SMP*/ + +void rt_hw_console_output(const char *str); + +void rt_hw_backtrace(rt_uint32_t *fp, rt_ubase_t thread_entry); +void rt_hw_show_memory(rt_uint32_t addr, rt_size_t size); + +/* + * Exception interfaces + */ +void rt_hw_exception_install(rt_err_t (*exception_handle)(void *context)); + +/* + * delay interfaces + */ +void rt_hw_us_delay(rt_uint32_t us); + +#ifdef RT_USING_SMP +#include /* for spinlock from arch */ + +struct rt_spinlock +{ + rt_hw_spinlock_t lock; +}; + +void rt_hw_spin_lock_init(rt_hw_spinlock_t *lock); +void rt_hw_spin_lock(rt_hw_spinlock_t *lock); +void rt_hw_spin_unlock(rt_hw_spinlock_t *lock); + +int rt_hw_cpu_id(void); + +extern rt_hw_spinlock_t _cpus_lock; +extern rt_hw_spinlock_t _rt_critical_lock; + +#define __RT_HW_SPIN_LOCK_INITIALIZER(lockname) {0} + +#define __RT_HW_SPIN_LOCK_UNLOCKED(lockname) \ + (rt_hw_spinlock_t) __RT_HW_SPIN_LOCK_INITIALIZER(lockname) + +#define RT_DEFINE_SPINLOCK(x) rt_hw_spinlock_t x = __RT_HW_SPIN_LOCK_UNLOCKED(x) +#define RT_DECLARE_SPINLOCK(x) + +/** + * ipi function + */ +void rt_hw_ipi_send(int ipi_vector, unsigned int cpu_mask); + +/** + * boot secondary cpu + */ +void rt_hw_secondary_cpu_up(void); + +/** + * secondary cpu idle function + */ +void rt_hw_secondary_cpu_idle_exec(void); +#else + +#define RT_DEFINE_SPINLOCK(x) rt_ubase_t x +#define RT_DECLARE_SPINLOCK(x) + +#define rt_hw_spin_lock(lock) *(lock) = rt_hw_interrupt_disable() +#define rt_hw_spin_unlock(lock) rt_hw_interrupt_enable(*(lock)) + +typedef int rt_spinlock_t; + +#endif + +#ifdef RT_USING_CACHE +#include +#else +#define rt_hw_isb() +#define rt_hw_dmb() +#define rt_hw_dsb() +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tasks/concur-rtthread-mutex-ceilings/template/include/rtm.h b/tasks/concur-rtthread-mutex-ceilings/template/include/rtm.h new file mode 100644 index 00000000..62d77a0a --- /dev/null +++ b/tasks/concur-rtthread-mutex-ceilings/template/include/rtm.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2006-2021, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + */ + +#ifndef __RTM_H__ +#define __RTM_H__ + +#include +#include + +#ifdef RT_USING_MODULE +struct rt_module_symtab +{ + void *addr; + const char *name; +}; + +#if defined(_MSC_VER) +#pragma section("RTMSymTab$f",read) +#define RTM_EXPORT(symbol) \ +__declspec(allocate("RTMSymTab$f"))const char __rtmsym_##symbol##_name[] = "__vs_rtm_"#symbol; +#pragma comment(linker, "/merge:RTMSymTab=mytext") + +#elif defined(__MINGW32__) +#define RTM_EXPORT(symbol) + +#else +#define RTM_EXPORT(symbol) \ +const char __rtmsym_##symbol##_name[] rt_section(".rodata.name") = #symbol; \ +const struct rt_module_symtab __rtmsym_##symbol rt_section("RTMSymTab")= \ +{ \ + (void *)&symbol, \ + __rtmsym_##symbol##_name \ +}; +#endif + +#else +#define RTM_EXPORT(symbol) +#endif + +#endif diff --git a/tasks/concur-rtthread-mutex-ceilings/template/include/rtservice.h b/tasks/concur-rtthread-mutex-ceilings/template/include/rtservice.h new file mode 100644 index 00000000..ae7e69cf --- /dev/null +++ b/tasks/concur-rtthread-mutex-ceilings/template/include/rtservice.h @@ -0,0 +1,315 @@ +/* + * Copyright (c) 2006-2021, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2006-03-16 Bernard the first version + * 2006-09-07 Bernard move the kservice APIs to rtthread.h + * 2007-06-27 Bernard fix the rt_list_remove bug + * 2012-03-22 Bernard rename kservice.h to rtservice.h + * 2017-11-15 JasonJia Modify rt_slist_foreach to rt_slist_for_each_entry. + * Make code cleanup. + */ + +#ifndef __RT_SERVICE_H__ +#define __RT_SERVICE_H__ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @addtogroup KernelService + */ + +/**@{*/ + +/** + * rt_container_of - return the start address of struct type, while ptr is the + * member of struct type. + */ +#define rt_container_of(ptr, type, member) \ + ((type *)((char *)(ptr) - (unsigned long)(&((type *)0)->member))) + + +/** + * @brief initialize a list object + */ +#define RT_LIST_OBJECT_INIT(object) { &(object), &(object) } + +/** + * @brief initialize a list + * + * @param l list to be initialized + */ +rt_inline void rt_list_init(rt_list_t *l) +{ + l->next = l->prev = l; +} + +/** + * @brief insert a node after a list + * + * @param l list to insert it + * @param n new node to be inserted + */ +rt_inline void rt_list_insert_after(rt_list_t *l, rt_list_t *n) +{ + l->next->prev = n; + n->next = l->next; + + l->next = n; + n->prev = l; +} + +/** + * @brief insert a node before a list + * + * @param n new node to be inserted + * @param l list to insert it + */ +rt_inline void rt_list_insert_before(rt_list_t *l, rt_list_t *n) +{ + l->prev->next = n; + n->prev = l->prev; + + l->prev = n; + n->next = l; +} + +/** + * @brief remove node from list. + * @param n the node to remove from the list. + */ +rt_inline void rt_list_remove(rt_list_t *n) +{ + n->next->prev = n->prev; + n->prev->next = n->next; + + n->next = n->prev = n; +} + +/** + * @brief tests whether a list is empty + * @param l the list to test. + */ +rt_inline int rt_list_isempty(const rt_list_t *l) +{ + return l->next == l; +} + +/** + * @brief get the list length + * @param l the list to get. + */ +rt_inline unsigned int rt_list_len(const rt_list_t *l) +{ + unsigned int len = 0; + const rt_list_t *p = l; + while (p->next != l) + { + p = p->next; + len ++; + } + + return len; +} + +/** + * @brief get the struct for this entry + * @param node the entry point + * @param type the type of structure + * @param member the name of list in structure + */ +#define rt_list_entry(node, type, member) \ + rt_container_of(node, type, member) + +/** + * rt_list_for_each - iterate over a list + * @param pos the rt_list_t * to use as a loop cursor. + * @param head the head for your list. + */ +#define rt_list_for_each(pos, head) \ + for (pos = (head)->next; pos != (head); pos = pos->next) + +/** + * rt_list_for_each_safe - iterate over a list safe against removal of list entry + * @param pos the rt_list_t * to use as a loop cursor. + * @param n another rt_list_t * to use as temporary storage + * @param head the head for your list. + */ +#define rt_list_for_each_safe(pos, n, head) \ + for (pos = (head)->next, n = pos->next; pos != (head); \ + pos = n, n = pos->next) + +/** + * rt_list_for_each_entry - iterate over list of given type + * @param pos the type * to use as a loop cursor. + * @param head the head for your list. + * @param member the name of the list_struct within the struct. + */ +#define rt_list_for_each_entry(pos, head, member) \ + for (pos = rt_list_entry((head)->next, typeof(*pos), member); \ + &pos->member != (head); \ + pos = rt_list_entry(pos->member.next, typeof(*pos), member)) + +/** + * rt_list_for_each_entry_safe - iterate over list of given type safe against removal of list entry + * @param pos the type * to use as a loop cursor. + * @param n another type * to use as temporary storage + * @param head the head for your list. + * @param member the name of the list_struct within the struct. + */ +#define rt_list_for_each_entry_safe(pos, n, head, member) \ + for (pos = rt_list_entry((head)->next, typeof(*pos), member), \ + n = rt_list_entry(pos->member.next, typeof(*pos), member); \ + &pos->member != (head); \ + pos = n, n = rt_list_entry(n->member.next, typeof(*n), member)) + +/** + * rt_list_first_entry - get the first element from a list + * @param ptr the list head to take the element from. + * @param type the type of the struct this is embedded in. + * @param member the name of the list_struct within the struct. + * + * Note, that list is expected to be not empty. + */ +#define rt_list_first_entry(ptr, type, member) \ + rt_list_entry((ptr)->next, type, member) + +#define RT_SLIST_OBJECT_INIT(object) { RT_NULL } + +/** + * @brief initialize a single list + * + * @param l the single list to be initialized + */ +rt_inline void rt_slist_init(rt_slist_t *l) +{ + l->next = RT_NULL; +} + +rt_inline void rt_slist_append(rt_slist_t *l, rt_slist_t *n) +{ + struct rt_slist_node *node; + + node = l; + while (node->next) node = node->next; + + /* append the node to the tail */ + node->next = n; + n->next = RT_NULL; +} + +rt_inline void rt_slist_insert(rt_slist_t *l, rt_slist_t *n) +{ + n->next = l->next; + l->next = n; +} + +rt_inline unsigned int rt_slist_len(const rt_slist_t *l) +{ + unsigned int len = 0; + const rt_slist_t *list = l->next; + while (list != RT_NULL) + { + list = list->next; + len ++; + } + + return len; +} + +rt_inline rt_slist_t *rt_slist_remove(rt_slist_t *l, rt_slist_t *n) +{ + /* remove slist head */ + struct rt_slist_node *node = l; + while (node->next && node->next != n) node = node->next; + + /* remove node */ + if (node->next != (rt_slist_t *)0) node->next = node->next->next; + + return l; +} + +rt_inline rt_slist_t *rt_slist_first(rt_slist_t *l) +{ + return l->next; +} + +rt_inline rt_slist_t *rt_slist_tail(rt_slist_t *l) +{ + while (l->next) l = l->next; + + return l; +} + +rt_inline rt_slist_t *rt_slist_next(rt_slist_t *n) +{ + return n->next; +} + +rt_inline int rt_slist_isempty(rt_slist_t *l) +{ + return l->next == RT_NULL; +} + +/** + * @brief get the struct for this single list node + * @param node the entry point + * @param type the type of structure + * @param member the name of list in structure + */ +#define rt_slist_entry(node, type, member) \ + rt_container_of(node, type, member) + +/** + * rt_slist_for_each - iterate over a single list + * @param pos the rt_slist_t * to use as a loop cursor. + * @param head the head for your single list. + */ +#define rt_slist_for_each(pos, head) \ + for (pos = (head)->next; pos != RT_NULL; pos = pos->next) + +/** + * rt_slist_for_each_entry - iterate over single list of given type + * @param pos the type * to use as a loop cursor. + * @param head the head for your single list. + * @param member the name of the list_struct within the struct. + */ +#define rt_slist_for_each_entry(pos, head, member) \ + for (pos = rt_slist_entry((head)->next, typeof(*pos), member); \ + &pos->member != (RT_NULL); \ + pos = rt_slist_entry(pos->member.next, typeof(*pos), member)) + +/** + * rt_slist_first_entry - get the first element from a slist + * @param ptr the slist head to take the element from. + * @param type the type of the struct this is embedded in. + * @param member the name of the slist_struct within the struct. + * + * Note, that slist is expected to be not empty. + */ +#define rt_slist_first_entry(ptr, type, member) \ + rt_slist_entry((ptr)->next, type, member) + +/** + * rt_slist_tail_entry - get the tail element from a slist + * @param ptr the slist head to take the element from. + * @param type the type of the struct this is embedded in. + * @param member the name of the slist_struct within the struct. + * + * Note, that slist is expected to be not empty. + */ +#define rt_slist_tail_entry(ptr, type, member) \ + rt_slist_entry(rt_slist_tail(ptr), type, member) + +/**@}*/ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tasks/concur-rtthread-mutex-ceilings/template/include/rtthread.h b/tasks/concur-rtthread-mutex-ceilings/template/include/rtthread.h new file mode 100644 index 00000000..5cfa3c26 --- /dev/null +++ b/tasks/concur-rtthread-mutex-ceilings/template/include/rtthread.h @@ -0,0 +1,712 @@ +/* + * Copyright (c) 2006-2021, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2006-03-18 Bernard the first version + * 2006-04-26 Bernard add semaphore APIs + * 2006-08-10 Bernard add version information + * 2007-01-28 Bernard rename RT_OBJECT_Class_Static to RT_Object_Class_Static + * 2007-03-03 Bernard clean up the definitions to rtdef.h + * 2010-04-11 yi.qiu add module feature + * 2013-06-24 Bernard add rt_kprintf re-define when not use RT_USING_CONSOLE. + * 2016-08-09 ArdaFu add new thread and interrupt hook. + * 2018-11-22 Jesven add all cpu's lock and ipi handler + * 2021-02-28 Meco Man add RT_KSERVICE_USING_STDLIB + * 2021-11-14 Meco Man add rtlegacy.h for compatibility + * 2022-06-04 Meco Man remove strnlen + */ + +#ifndef __RT_THREAD_H__ +#define __RT_THREAD_H__ + +#include +#include +#include +#include +#include +#ifdef RT_USING_LEGACY +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @addtogroup KernelObject + * @{ + */ + +/* + * kernel object interface + */ +struct rt_object_information * +rt_object_get_information(enum rt_object_class_type type); +int rt_object_get_length(enum rt_object_class_type type); +int rt_object_get_pointers(enum rt_object_class_type type, rt_object_t *pointers, int maxlen); + +void rt_object_init(struct rt_object *object, + enum rt_object_class_type type, + const char *name); +void rt_object_detach(rt_object_t object); +#ifdef RT_USING_HEAP +rt_object_t rt_object_allocate(enum rt_object_class_type type, + const char *name); +void rt_object_delete(rt_object_t object); +#endif +rt_bool_t rt_object_is_systemobject(rt_object_t object); +rt_uint8_t rt_object_get_type(rt_object_t object); +rt_object_t rt_object_find(const char *name, rt_uint8_t type); + +#ifdef RT_USING_HEAP +/* custom object */ +rt_object_t rt_custom_object_create(const char *name, void *data, rt_err_t (*data_destroy)(void *)); +rt_err_t rt_custom_object_destroy(rt_object_t obj); +#endif + +#ifdef RT_USING_HOOK +void rt_object_attach_sethook(void (*hook)(struct rt_object *object)); +void rt_object_detach_sethook(void (*hook)(struct rt_object *object)); +void rt_object_trytake_sethook(void (*hook)(struct rt_object *object)); +void rt_object_take_sethook(void (*hook)(struct rt_object *object)); +void rt_object_put_sethook(void (*hook)(struct rt_object *object)); +#endif + +/**@}*/ + +/** + * @addtogroup Clock + * @{ + */ + +/* + * clock & timer interface + */ +rt_tick_t rt_tick_get(void); +void rt_tick_set(rt_tick_t tick); +void rt_tick_increase(void); +rt_tick_t rt_tick_from_millisecond(rt_int32_t ms); +rt_tick_t rt_tick_get_millisecond(void); +#ifdef RT_USING_HOOK +void rt_tick_sethook(void (*hook)(void)); +#endif + +void rt_system_timer_init(void); +void rt_system_timer_thread_init(void); + +void rt_timer_init(rt_timer_t timer, + const char *name, + void (*timeout)(void *parameter), + void *parameter, + rt_tick_t time, + rt_uint8_t flag); +rt_err_t rt_timer_detach(rt_timer_t timer); +#ifdef RT_USING_HEAP +rt_timer_t rt_timer_create(const char *name, + void (*timeout)(void *parameter), + void *parameter, + rt_tick_t time, + rt_uint8_t flag); +rt_err_t rt_timer_delete(rt_timer_t timer); +#endif +rt_err_t rt_timer_start(rt_timer_t timer); +rt_err_t rt_timer_stop(rt_timer_t timer); +rt_err_t rt_timer_control(rt_timer_t timer, int cmd, void *arg); + +rt_tick_t rt_timer_next_timeout_tick(void); +void rt_timer_check(void); + +#ifdef RT_USING_HOOK +void rt_timer_enter_sethook(void (*hook)(struct rt_timer *timer)); +void rt_timer_exit_sethook(void (*hook)(struct rt_timer *timer)); +#endif + +/**@}*/ + +/** + * @addtogroup Thread + * @{ + */ + +/* + * thread interface + */ +rt_err_t rt_thread_init(struct rt_thread *thread, + const char *name, + void (*entry)(void *parameter), + void *parameter, + void *stack_start, + rt_uint32_t stack_size, + rt_uint8_t priority, + rt_uint32_t tick); +rt_err_t rt_thread_detach(rt_thread_t thread); +#ifdef RT_USING_HEAP +rt_thread_t rt_thread_create(const char *name, + void (*entry)(void *parameter), + void *parameter, + rt_uint32_t stack_size, + rt_uint8_t priority, + rt_uint32_t tick); +rt_err_t rt_thread_delete(rt_thread_t thread); +#endif +rt_thread_t rt_thread_self(void); +rt_thread_t rt_thread_find(char *name); +rt_err_t rt_thread_startup(rt_thread_t thread); +rt_err_t rt_thread_yield(void); +rt_err_t rt_thread_delay(rt_tick_t tick); +rt_err_t rt_thread_delay_until(rt_tick_t *tick, rt_tick_t inc_tick); +rt_err_t rt_thread_mdelay(rt_int32_t ms); +rt_err_t rt_thread_control(rt_thread_t thread, int cmd, void *arg); +rt_err_t rt_thread_suspend(rt_thread_t thread); +rt_err_t rt_thread_suspend_with_flag(rt_thread_t thread, int suspend_flag); +rt_err_t rt_thread_resume(rt_thread_t thread); +#ifdef RT_USING_SMART +rt_err_t rt_thread_wakeup(rt_thread_t thread); +void rt_thread_wakeup_set(struct rt_thread *thread, rt_wakeup_func_t func, void* user_data); +#endif +void rt_thread_timeout(void *parameter); + +#ifdef RT_USING_SIGNALS +void rt_thread_alloc_sig(rt_thread_t tid); +void rt_thread_free_sig(rt_thread_t tid); +int rt_thread_kill(rt_thread_t tid, int sig); +#endif + +#ifdef RT_USING_HOOK +void rt_thread_suspend_sethook(void (*hook)(rt_thread_t thread)); +void rt_thread_resume_sethook (void (*hook)(rt_thread_t thread)); +void rt_thread_inited_sethook (void (*hook)(rt_thread_t thread)); +#endif + +/* + * idle thread interface + */ +void rt_thread_idle_init(void); +#if defined(RT_USING_HOOK) || defined(RT_USING_IDLE_HOOK) +rt_err_t rt_thread_idle_sethook(void (*hook)(void)); +rt_err_t rt_thread_idle_delhook(void (*hook)(void)); +#endif +rt_thread_t rt_thread_idle_gethandler(void); + +/* + * schedule service + */ +void rt_system_scheduler_init(void); +void rt_system_scheduler_start(void); + +void rt_schedule(void); +void rt_schedule_insert_thread(struct rt_thread *thread); +void rt_schedule_remove_thread(struct rt_thread *thread); + +void rt_enter_critical(void); +void rt_exit_critical(void); +rt_uint16_t rt_critical_level(void); + +#ifdef RT_USING_HOOK +void rt_scheduler_sethook(void (*hook)(rt_thread_t from, rt_thread_t to)); +void rt_scheduler_switch_sethook(void (*hook)(struct rt_thread *tid)); +#endif + +#ifdef RT_USING_SMP +void rt_secondary_cpu_entry(void); +void rt_scheduler_ipi_handler(int vector, void *param); +#endif + +/**@}*/ + +/** + * @addtogroup Signals + * @{ + */ +#ifdef RT_USING_SIGNALS +void rt_signal_mask(int signo); +void rt_signal_unmask(int signo); +rt_sighandler_t rt_signal_install(int signo, rt_sighandler_t handler); +int rt_signal_wait(const rt_sigset_t *set, rt_siginfo_t *si, rt_int32_t timeout); + +int rt_system_signal_init(void); +#endif +/**@}*/ + +/** + * @addtogroup MM + * @{ + */ + +/* + * memory management interface + */ +#ifdef RT_USING_MEMPOOL +/* + * memory pool interface + */ +rt_err_t rt_mp_init(struct rt_mempool *mp, + const char *name, + void *start, + rt_size_t size, + rt_size_t block_size); +rt_err_t rt_mp_detach(struct rt_mempool *mp); +#ifdef RT_USING_HEAP +rt_mp_t rt_mp_create(const char *name, + rt_size_t block_count, + rt_size_t block_size); +rt_err_t rt_mp_delete(rt_mp_t mp); +#endif + +void *rt_mp_alloc(rt_mp_t mp, rt_int32_t time); +void rt_mp_free(void *block); + +#ifdef RT_USING_HOOK +void rt_mp_alloc_sethook(void (*hook)(struct rt_mempool *mp, void *block)); +void rt_mp_free_sethook(void (*hook)(struct rt_mempool *mp, void *block)); +#endif + +#endif + +#ifdef RT_USING_HEAP +/* + * heap memory interface + */ +void rt_system_heap_init(void *begin_addr, void *end_addr); + +void *rt_malloc(rt_size_t nbytes); +void rt_free(void *ptr); +void *rt_realloc(void *ptr, rt_size_t nbytes); +void *rt_calloc(rt_size_t count, rt_size_t size); +void *rt_malloc_align(rt_size_t size, rt_size_t align); +void rt_free_align(void *ptr); + +void rt_memory_info(rt_size_t *total, + rt_size_t *used, + rt_size_t *max_used); + +#if defined(RT_USING_SLAB) && defined(RT_USING_SLAB_AS_HEAP) +void *rt_page_alloc(rt_size_t npages); +void rt_page_free(void *addr, rt_size_t npages); +#endif + +#ifdef RT_USING_HOOK +void rt_malloc_sethook(void (*hook)(void *ptr, rt_size_t size)); +void rt_free_sethook(void (*hook)(void *ptr)); +#endif + +#endif + +#ifdef RT_USING_SMALL_MEM +/** + * small memory object interface + */ +rt_smem_t rt_smem_init(const char *name, + void *begin_addr, + rt_size_t size); +rt_err_t rt_smem_detach(rt_smem_t m); +void *rt_smem_alloc(rt_smem_t m, rt_size_t size); +void *rt_smem_realloc(rt_smem_t m, void *rmem, rt_size_t newsize); +void rt_smem_free(void *rmem); +#endif + +#ifdef RT_USING_MEMHEAP +/** + * memory heap object interface + */ +rt_err_t rt_memheap_init(struct rt_memheap *memheap, + const char *name, + void *start_addr, + rt_size_t size); +rt_err_t rt_memheap_detach(struct rt_memheap *heap); +void *rt_memheap_alloc(struct rt_memheap *heap, rt_size_t size); +void *rt_memheap_realloc(struct rt_memheap *heap, void *ptr, rt_size_t newsize); +void rt_memheap_free(void *ptr); +void rt_memheap_info(struct rt_memheap *heap, + rt_size_t *total, + rt_size_t *used, + rt_size_t *max_used); +#endif + +#ifdef RT_USING_SLAB +/** + * slab object interface + */ +rt_slab_t rt_slab_init(const char *name, void *begin_addr, rt_size_t size); +rt_err_t rt_slab_detach(rt_slab_t m); +void *rt_slab_page_alloc(rt_slab_t m, rt_size_t npages); +void rt_slab_page_free(rt_slab_t m, void *addr, rt_size_t npages); +void *rt_slab_alloc(rt_slab_t m, rt_size_t size); +void *rt_slab_realloc(rt_slab_t m, void *ptr, rt_size_t size); +void rt_slab_free(rt_slab_t m, void *ptr); +#endif + +/**@}*/ + +/** + * @addtogroup IPC + * @{ + */ + +#ifdef RT_USING_SEMAPHORE +/* + * semaphore interface + */ +rt_err_t rt_sem_init(rt_sem_t sem, + const char *name, + rt_uint32_t value, + rt_uint8_t flag); +rt_err_t rt_sem_detach(rt_sem_t sem); +#ifdef RT_USING_HEAP +rt_sem_t rt_sem_create(const char *name, rt_uint32_t value, rt_uint8_t flag); +rt_err_t rt_sem_delete(rt_sem_t sem); +#endif + +rt_err_t rt_sem_take(rt_sem_t sem, rt_int32_t timeout); +rt_err_t rt_sem_take_interruptible(rt_sem_t sem, rt_int32_t timeout); +rt_err_t rt_sem_take_killable(rt_sem_t sem, rt_int32_t timeout); +rt_err_t rt_sem_trytake(rt_sem_t sem); +rt_err_t rt_sem_release(rt_sem_t sem); +rt_err_t rt_sem_control(rt_sem_t sem, int cmd, void *arg); +#endif + +#ifdef RT_USING_MUTEX +/* + * mutex interface + */ +rt_err_t rt_mutex_init(rt_mutex_t mutex, const char *name, rt_uint8_t flag); +rt_err_t rt_mutex_detach(rt_mutex_t mutex); +#ifdef RT_USING_HEAP +rt_mutex_t rt_mutex_create(const char *name, rt_uint8_t flag); +rt_err_t rt_mutex_delete(rt_mutex_t mutex); +#endif +void rt_mutex_drop_thread(rt_mutex_t mutex, rt_thread_t thread); +rt_uint8_t rt_mutex_setprioceiling(rt_mutex_t mutex, rt_uint8_t priority); +rt_uint8_t rt_mutex_getprioceiling(rt_mutex_t mutex); + +rt_err_t rt_mutex_take(rt_mutex_t mutex, rt_int32_t timeout); +rt_err_t rt_mutex_trytake(rt_mutex_t mutex); +rt_err_t rt_mutex_take_interruptible(rt_mutex_t mutex, rt_int32_t time); +rt_err_t rt_mutex_take_killable(rt_mutex_t mutex, rt_int32_t time); +rt_err_t rt_mutex_release(rt_mutex_t mutex); +rt_err_t rt_mutex_control(rt_mutex_t mutex, int cmd, void *arg); +#endif + +#ifdef RT_USING_EVENT +/* + * event interface + */ +rt_err_t rt_event_init(rt_event_t event, const char *name, rt_uint8_t flag); +rt_err_t rt_event_detach(rt_event_t event); +#ifdef RT_USING_HEAP +rt_event_t rt_event_create(const char *name, rt_uint8_t flag); +rt_err_t rt_event_delete(rt_event_t event); +#endif + +rt_err_t rt_event_send(rt_event_t event, rt_uint32_t set); +rt_err_t rt_event_recv(rt_event_t event, + rt_uint32_t set, + rt_uint8_t opt, + rt_int32_t timeout, + rt_uint32_t *recved); +rt_err_t rt_event_recv_interruptible(rt_event_t event, + rt_uint32_t set, + rt_uint8_t opt, + rt_int32_t timeout, + rt_uint32_t *recved); +rt_err_t rt_event_recv_killable(rt_event_t event, + rt_uint32_t set, + rt_uint8_t opt, + rt_int32_t timeout, + rt_uint32_t *recved); +rt_err_t rt_event_control(rt_event_t event, int cmd, void *arg); +#endif + +#ifdef RT_USING_MAILBOX +/* + * mailbox interface + */ +rt_err_t rt_mb_init(rt_mailbox_t mb, + const char *name, + void *msgpool, + rt_size_t size, + rt_uint8_t flag); +rt_err_t rt_mb_detach(rt_mailbox_t mb); +#ifdef RT_USING_HEAP +rt_mailbox_t rt_mb_create(const char *name, rt_size_t size, rt_uint8_t flag); +rt_err_t rt_mb_delete(rt_mailbox_t mb); +#endif + +rt_err_t rt_mb_send(rt_mailbox_t mb, rt_ubase_t value); +rt_err_t rt_mb_send_wait(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout); +rt_err_t rt_mb_send_wait_interruptible(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout); +rt_err_t rt_mb_send_wait_killable(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout); +rt_err_t rt_mb_urgent(rt_mailbox_t mb, rt_ubase_t value); +rt_err_t rt_mb_recv(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout); +rt_err_t rt_mb_recv_interruptibale(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout); +rt_err_t rt_mb_recv_killable(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout); +rt_err_t rt_mb_control(rt_mailbox_t mb, int cmd, void *arg); +#endif + +#ifdef RT_USING_MESSAGEQUEUE +/* + * message queue interface + */ +rt_err_t rt_mq_init(rt_mq_t mq, + const char *name, + void *msgpool, + rt_size_t msg_size, + rt_size_t pool_size, + rt_uint8_t flag); +rt_err_t rt_mq_detach(rt_mq_t mq); +#ifdef RT_USING_HEAP +rt_mq_t rt_mq_create(const char *name, + rt_size_t msg_size, + rt_size_t max_msgs, + rt_uint8_t flag); +rt_err_t rt_mq_delete(rt_mq_t mq); +#endif + +rt_err_t rt_mq_send(rt_mq_t mq, const void *buffer, rt_size_t size); +rt_err_t rt_mq_send_interrupt(rt_mq_t mq, const void *buffer, rt_size_t size); +rt_err_t rt_mq_send_killable(rt_mq_t mq, const void *buffer, rt_size_t size); +rt_err_t rt_mq_send_wait(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout); +rt_err_t rt_mq_send_wait_interruptible(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout); +rt_err_t rt_mq_send_wait_killable(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout); +rt_err_t rt_mq_urgent(rt_mq_t mq, const void *buffer, rt_size_t size); +rt_err_t rt_mq_recv(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout); +rt_err_t rt_mq_recv_interruptible(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout); +rt_err_t rt_mq_recv_killable(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout); +rt_err_t rt_mq_control(rt_mq_t mq, int cmd, void *arg); +#endif + +/* defunct */ +void rt_thread_defunct_enqueue(rt_thread_t thread); +rt_thread_t rt_thread_defunct_dequeue(void); + +/* + * spinlock + */ +#ifdef RT_USING_SMP +struct rt_spinlock; + +void rt_spin_lock_init(struct rt_spinlock *lock); +void rt_spin_lock(struct rt_spinlock *lock); +void rt_spin_unlock(struct rt_spinlock *lock); +rt_base_t rt_spin_lock_irqsave(struct rt_spinlock *lock); +void rt_spin_unlock_irqrestore(struct rt_spinlock *lock, rt_base_t level); + +#else +#define rt_spin_lock_init(lock) /* nothing */ +#define rt_spin_lock(lock) rt_enter_critical() +#define rt_spin_unlock(lock) rt_exit_critical() +#define rt_spin_lock_irqsave(lock) rt_hw_interrupt_disable() +#define rt_spin_unlock_irqrestore(lock, level) rt_hw_interrupt_enable(level) + +#endif + +/**@}*/ + +#ifdef RT_USING_DEVICE +/** + * @addtogroup Device + * @{ + */ + +/* + * device (I/O) system interface + */ +rt_device_t rt_device_find(const char *name); + +rt_err_t rt_device_register(rt_device_t dev, + const char *name, + rt_uint16_t flags); +rt_err_t rt_device_unregister(rt_device_t dev); + +#ifdef RT_USING_HEAP +rt_device_t rt_device_create(int type, int attach_size); +void rt_device_destroy(rt_device_t device); +#endif + +rt_err_t +rt_device_set_rx_indicate(rt_device_t dev, + rt_err_t (*rx_ind)(rt_device_t dev, rt_size_t size)); +rt_err_t +rt_device_set_tx_complete(rt_device_t dev, + rt_err_t (*tx_done)(rt_device_t dev, void *buffer)); + +rt_err_t rt_device_init (rt_device_t dev); +rt_err_t rt_device_open (rt_device_t dev, rt_uint16_t oflag); +rt_err_t rt_device_close(rt_device_t dev); +rt_ssize_t rt_device_read(rt_device_t dev, + rt_off_t pos, + void *buffer, + rt_size_t size); +rt_ssize_t rt_device_write(rt_device_t dev, + rt_off_t pos, + const void *buffer, + rt_size_t size); +rt_err_t rt_device_control(rt_device_t dev, int cmd, void *arg); +#ifdef RT_USING_DM +rt_err_t rt_device_bind_driver(rt_device_t device, rt_driver_t driver, void *node); +rt_device_t rt_device_create_since_driver(rt_driver_t drv,int device_id); +rt_err_t rt_device_probe_and_init(rt_device_t device); + +rt_err_t rt_driver_match_with_id(const rt_driver_t drv,int device_id); +rt_err_t rt_driver_match_with_dtb(const rt_driver_t drv,void *from_node,int max_dev_num); +#endif +/**@}*/ +#endif + +/* + * interrupt service + */ + +/* + * rt_interrupt_enter and rt_interrupt_leave only can be called by BSP + */ +void rt_interrupt_enter(void); +void rt_interrupt_leave(void); + +#ifdef RT_USING_SMP + +/* + * smp cpus lock service + */ + +rt_base_t rt_cpus_lock(void); +void rt_cpus_unlock(rt_base_t level); + +struct rt_cpu *rt_cpu_self(void); +struct rt_cpu *rt_cpu_index(int index); + +#endif + +/* + * the number of nested interrupts. + */ +rt_uint8_t rt_interrupt_get_nest(void); + +#ifdef RT_USING_HOOK +void rt_interrupt_enter_sethook(void (*hook)(void)); +void rt_interrupt_leave_sethook(void (*hook)(void)); +#endif + +#ifdef RT_USING_COMPONENTS_INIT +void rt_components_init(void); +void rt_components_board_init(void); +#endif + +/** + * @addtogroup KernelService + * @{ + */ + +/* + * general kernel service + */ +#ifndef RT_USING_CONSOLE +#define rt_kprintf(...) +#define rt_kputs(str) +#else +int rt_kprintf(const char *fmt, ...); +void rt_kputs(const char *str); +#endif + +int rt_vsprintf(char *dest, const char *format, va_list arg_ptr); +int rt_vsnprintf(char *buf, rt_size_t size, const char *fmt, va_list args); +int rt_sprintf(char *buf, const char *format, ...); +int rt_snprintf(char *buf, rt_size_t size, const char *format, ...); + +#if defined(RT_USING_DEVICE) && defined(RT_USING_CONSOLE) +rt_device_t rt_console_set_device(const char *name); +rt_device_t rt_console_get_device(void); +#endif + +rt_err_t rt_get_errno(void); +void rt_set_errno(rt_err_t no); +int *_rt_errno(void); +const char *rt_strerror(rt_err_t error); +#if !defined(RT_USING_NEWLIBC) && !defined(_WIN32) +#ifndef errno +#define errno *_rt_errno() +#endif +#endif + +int __rt_ffs(int value); + +#ifndef RT_KSERVICE_USING_STDLIB_MEMORY +void *rt_memset(void *src, int c, rt_ubase_t n); +void *rt_memcpy(void *dest, const void *src, rt_ubase_t n); +void *rt_memmove(void *dest, const void *src, rt_size_t n); +rt_int32_t rt_memcmp(const void *cs, const void *ct, rt_size_t count); +#endif /* RT_KSERVICE_USING_STDLIB_MEMORY */ +char *rt_strdup(const char *s); +rt_size_t rt_strnlen(const char *s, rt_ubase_t maxlen); +#ifndef RT_KSERVICE_USING_STDLIB +char *rt_strstr(const char *str1, const char *str2); +rt_int32_t rt_strcasecmp(const char *a, const char *b); +char *rt_strcpy(char *dst, const char *src); +char *rt_strncpy(char *dest, const char *src, rt_size_t n); +rt_int32_t rt_strncmp(const char *cs, const char *ct, rt_size_t count); +rt_int32_t rt_strcmp(const char *cs, const char *ct); +rt_size_t rt_strlen(const char *src); +#else +#include +#ifdef RT_KSERVICE_USING_STDLIB_MEMORY +#define rt_memset(s, c, count) memset(s, c, count) +#define rt_memcpy(dst, src, count) memcpy(dst, src, count) +#define rt_memmove(dest, src, n) memmove(dest, src, n) +#define rt_memcmp(cs, ct, count) memcmp(cs, ct, count) +#endif /* RT_KSERVICE_USING_STDLIB_MEMORY */ +#define rt_strstr(str1, str2) strstr(str1, str2) +#define rt_strcasecmp(a, b) strcasecmp(a, b) +#define rt_strcpy(dest, src) strcpy(dest, src) +#define rt_strncpy(dest, src, n) strncpy(dest, src, n) +#define rt_strncmp(cs, ct, count) strncmp(cs, ct, count) +#define rt_strcmp(cs, ct) strcmp(cs, ct) +#define rt_strlen(src) strlen(src) +#endif /*RT_KSERVICE_USING_STDLIB*/ + +void rt_show_version(void); + +#ifdef RT_DEBUG +extern void (*rt_assert_hook)(const char *ex, const char *func, rt_size_t line); +void rt_assert_set_hook(void (*hook)(const char *ex, const char *func, rt_size_t line)); + +void rt_assert_handler(const char *ex, const char *func, rt_size_t line); +#endif /* RT_DEBUG */ + +#ifdef RT_USING_FINSH +#include +#endif + +/**@}*/ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tasks/concur-rtthread-mutex-ceilings/template/port/field_report.c b/tasks/concur-rtthread-mutex-ceilings/template/port/field_report.c new file mode 100644 index 00000000..638c0bcf --- /dev/null +++ b/tasks/concur-rtthread-mutex-ceilings/template/port/field_report.c @@ -0,0 +1,18 @@ +#include "services.h" +#include +static struct rt_thread worker; +static unsigned char stack[1024]; +static struct rt_mutex resource; +static void entry(void *p) {(void)p;} +int main(void) { + rt_thread_init(&worker,"worker",entry,0,stack,sizeof(stack),23,10); + rt_schedule_insert_thread(&worker);port_select(&worker); + rt_mutex_init(&resource,"resource",RT_IPC_FLAG_PRIO); + rt_mutex_take(&resource,0); + printf("before: priority=%u ceiling=%u\n",worker.current_priority,rt_mutex_getprioceiling(&resource)); + unsigned old=rt_mutex_setprioceiling(&resource,6); + printf("configured: old=%u priority=%u ceiling=%u\n",old,worker.current_priority,rt_mutex_getprioceiling(&resource)); + rt_mutex_release(&resource); + printf("released: priority=%u\n",worker.current_priority); + return 0; +} diff --git a/tasks/concur-rtthread-mutex-ceilings/template/port/services.c b/tasks/concur-rtthread-mutex-ceilings/template/port/services.c new file mode 100644 index 00000000..887cb6ca --- /dev/null +++ b/tasks/concur-rtthread-mutex-ceilings/template/port/services.c @@ -0,0 +1,49 @@ +/* Host service port. Kernel thread/IPC policy remains in the upstream source. */ +#include "services.h" +#include +#include +#include +#include +#include +rt_thread_t rt_current_thread; +void (*port_on_schedule)(void); +static rt_base_t irq_level; +static rt_list_t ready = {&ready, &ready}; +void port_select(rt_thread_t thread) { rt_current_thread=thread; } +rt_base_t rt_hw_interrupt_disable(void) { rt_base_t old=irq_level; irq_level++; return old; } +void rt_hw_interrupt_enable(rt_base_t level) { irq_level=level; } +void rt_enter_critical(void) {} +void rt_exit_critical(void) {} +rt_uint16_t rt_critical_level(void) { return 0; } +void rt_schedule_insert_thread(struct rt_thread *thread) { + rt_list_remove(&thread->tlist); + rt_list_insert_before(&ready, &thread->tlist); + thread->stat=(thread->stat & ~RT_THREAD_STAT_MASK)|RT_THREAD_READY; +} +void rt_schedule_remove_thread(struct rt_thread *thread) { rt_list_remove(&thread->tlist); } +void rt_schedule(void) { if(port_on_schedule) port_on_schedule(); } +void rt_thread_defunct_enqueue(rt_thread_t thread) { (void)thread; } +rt_uint8_t *rt_hw_stack_init(void *entry, void *parameter, rt_uint8_t *stack, void *exit) { + (void)entry;(void)parameter;(void)exit;return stack; +} +void rt_timer_init(rt_timer_t timer,const char *name,void (*callback)(void*),void *arg,rt_tick_t ticks,rt_uint8_t flag) { + memset(timer,0,sizeof(*timer)); + rt_object_init(&timer->parent,RT_Object_Class_Timer,name); + timer->timeout_func=callback;timer->parameter=arg;timer->init_tick=ticks;timer->parent.flag=flag; +} +rt_err_t rt_timer_detach(rt_timer_t timer) { rt_object_detach(&timer->parent);return RT_EOK; } +rt_err_t rt_timer_start(rt_timer_t timer) { timer->parent.flag|=RT_TIMER_FLAG_ACTIVATED;return RT_EOK; } +rt_err_t rt_timer_stop(rt_timer_t timer) { timer->parent.flag&=~RT_TIMER_FLAG_ACTIVATED;return RT_EOK; } +rt_err_t rt_timer_control(rt_timer_t timer,int cmd,void *arg) { + if(cmd==RT_TIMER_CTRL_SET_TIME)timer->init_tick=*(rt_tick_t*)arg; + return RT_EOK; +} +void *rt_memset(void *s,int c,rt_size_t n) { return memset(s,c,n); } +char *rt_strncpy(char *a,const char *b,rt_size_t n) { return strncpy(a,b,n); } +int rt_strncmp(const char *a,const char *b,rt_size_t n) { return strncmp(a,b,n); } +void rt_set_errno(rt_err_t error) { if(rt_current_thread)rt_current_thread->error=error; } +rt_err_t rt_get_errno(void) { return rt_current_thread?rt_current_thread->error:0; } +int rt_kprintf(const char *fmt,...) { va_list ap;va_start(ap,fmt);int r=vfprintf(stderr,fmt,ap);va_end(ap);return r; } +void rt_assert_handler(const char *ex,const char *func,rt_size_t line) { + fprintf(stderr,"kernel assert: %s in %s at %lu\n",ex,func,(unsigned long)line);exit(90); +} diff --git a/tasks/concur-rtthread-mutex-ceilings/template/port/services.h b/tasks/concur-rtthread-mutex-ceilings/template/port/services.h new file mode 100644 index 00000000..afddb160 --- /dev/null +++ b/tasks/concur-rtthread-mutex-ceilings/template/port/services.h @@ -0,0 +1,7 @@ +#ifndef SERVICES_H +#define SERVICES_H +#include +extern rt_thread_t rt_current_thread; +extern void (*port_on_schedule)(void); +void port_select(rt_thread_t thread); +#endif diff --git a/tasks/concur-rtthread-mutex-ceilings/template/port/smoke.c b/tasks/concur-rtthread-mutex-ceilings/template/port/smoke.c new file mode 100644 index 00000000..2cc72a71 --- /dev/null +++ b/tasks/concur-rtthread-mutex-ceilings/template/port/smoke.c @@ -0,0 +1,15 @@ +#include "services.h" +#include +static struct rt_thread thread; +static unsigned char stack[1024]; +static struct rt_mutex mutex; +static void entry(void *p) {(void)p;} +int main(void) { + rt_thread_init(&thread,"worker",entry,0,stack,sizeof(stack),20,10); + rt_schedule_insert_thread(&thread);port_select(&thread); + int init=rt_mutex_init(&mutex,"resource",RT_IPC_FLAG_PRIO); + int take=rt_mutex_take(&mutex,0); + int release=rt_mutex_release(&mutex); + printf("init=%d take=%d release=%d priority=%u\n",init,take,release,thread.current_priority); + return init||take||release; +} diff --git a/tasks/concur-rtthread-mutex-ceilings/template/src/ipc.c b/tasks/concur-rtthread-mutex-ceilings/template/src/ipc.c new file mode 100644 index 00000000..00ab5183 --- /dev/null +++ b/tasks/concur-rtthread-mutex-ceilings/template/src/ipc.c @@ -0,0 +1,3737 @@ +/* + * Copyright (c) 2006-2022, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +#include +#include + +#ifndef __on_rt_object_trytake_hook + #define __on_rt_object_trytake_hook(parent) __ON_HOOK_ARGS(rt_object_trytake_hook, (parent)) +#endif +#ifndef __on_rt_object_take_hook + #define __on_rt_object_take_hook(parent) __ON_HOOK_ARGS(rt_object_take_hook, (parent)) +#endif +#ifndef __on_rt_object_put_hook + #define __on_rt_object_put_hook(parent) __ON_HOOK_ARGS(rt_object_put_hook, (parent)) +#endif + +#if defined(RT_USING_HOOK) && defined(RT_HOOK_USING_FUNC_PTR) +extern void (*rt_object_trytake_hook)(struct rt_object *object); +extern void (*rt_object_take_hook)(struct rt_object *object); +extern void (*rt_object_put_hook)(struct rt_object *object); +#endif /* RT_USING_HOOK */ + +/** + * @addtogroup IPC + * @{ + */ + +/** + * @brief This function will initialize an IPC object, such as semaphore, mutex, messagequeue and mailbox. + * + * @note Executing this function will complete an initialization of the suspend thread list of the ipc object. + * + * @param ipc is a pointer to the IPC object. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * When the return value is any other values, it means the initialization failed. + * + * @warning This function can be called from all IPC initialization and creation. + */ +rt_inline rt_err_t _ipc_object_init(struct rt_ipc_object *ipc) +{ + /* initialize ipc object */ + rt_list_init(&(ipc->suspend_thread)); + + return RT_EOK; +} + + +/** + * @brief This function will suspend a thread to a IPC object list. + * + * @param list is a pointer to a suspended thread list of the IPC object. + * + * @param thread is a pointer to the thread object to be suspended. + * + * @param flag is a flag for the thread object to be suspended. It determines how the thread is suspended. + * The flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to use + * RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this semaphore will become non-real-time threads. + * + * @param suspend_flag status flag of the thread to be suspended. + * + * @return Return the operation status. When the return value is RT_EOK, the function is successfully executed. + * When the return value is any other values, it means the initialization failed. + * + * @warning This function can ONLY be called in the thread context, you can use RT_DEBUG_IN_THREAD_CONTEXT to + * check the context. + * In addition, this function is generally called by the following functions: + * rt_sem_take(), rt_mutex_take(), rt_event_recv(), rt_mb_send_wait(), + * rt_mb_recv(), rt_mq_recv(), rt_mq_send_wait() + */ +rt_inline rt_err_t _ipc_list_suspend(rt_list_t *list, + struct rt_thread *thread, + rt_uint8_t flag, + int suspend_flag) +{ + rt_err_t ret = rt_thread_suspend_with_flag(thread, suspend_flag); + + /* suspend thread */ + if (ret != RT_EOK) + { + return ret; + } + + switch (flag) + { + case RT_IPC_FLAG_FIFO: + rt_list_insert_before(list, &(thread->tlist)); + break; /* RT_IPC_FLAG_FIFO */ + + case RT_IPC_FLAG_PRIO: + { + struct rt_list_node *n; + struct rt_thread *sthread; + + /* find a suitable position */ + for (n = list->next; n != list; n = n->next) + { + sthread = rt_list_entry(n, struct rt_thread, tlist); + + /* find out */ + if (thread->current_priority < sthread->current_priority) + { + /* insert this thread before the sthread */ + rt_list_insert_before(&(sthread->tlist), &(thread->tlist)); + break; + } + } + + /* + * not found a suitable position, + * append to the end of suspend_thread list + */ + if (n == list) + rt_list_insert_before(list, &(thread->tlist)); + } + break;/* RT_IPC_FLAG_PRIO */ + + default: + RT_ASSERT(0); + break; + } + + return RT_EOK; +} + + +/** + * @brief This function will resume a thread. + * + * @note This function will resume the first thread in the list of a IPC object. + * 1. remove the thread from suspend queue of a IPC object. + * 2. put the thread into system ready queue. + * + * By contrast, the rt_ipc_list_resume_all() function will resume all suspended threads + * in the list of a IPC object. + * + * @param list is a pointer to a suspended thread list of the IPC object. + * + * @return Return the operation status. When the return value is RT_EOK, the function is successfully executed. + * When the return value is any other values, it means this operation failed. + * + * @warning This function is generally called by the following functions: + * rt_sem_release(), rt_mutex_release(), rt_mb_send_wait(), rt_mq_send_wait(), + * rt_mb_urgent(), rt_mb_recv(), rt_mq_urgent(), rt_mq_recv(), + */ +rt_inline rt_err_t _ipc_list_resume(rt_list_t *list) +{ + struct rt_thread *thread; + + /* get thread entry */ + thread = rt_list_entry(list->next, struct rt_thread, tlist); + + thread->error = RT_EOK; + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("resume thread:%s\n", thread->name)); + + /* resume it */ + rt_thread_resume(thread); + + return RT_EOK; +} + + +/** + * @brief This function will resume all suspended threads in the IPC object list, + * including the suspended list of IPC object, and private list of mailbox etc. + * + * @note This function will resume all threads in the IPC object list. + * By contrast, the rt_ipc_list_resume() function will resume a suspended thread in the list of a IPC object. + * + * @param list is a pointer to a suspended thread list of the IPC object. + * + * @return Return the operation status. When the return value is RT_EOK, the function is successfully executed. + * When the return value is any other values, it means this operation failed. + * + */ +rt_inline rt_err_t _ipc_list_resume_all(rt_list_t *list) +{ + struct rt_thread *thread; + rt_base_t level; + + /* wakeup all suspended threads */ + while (!rt_list_isempty(list)) + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* get next suspended thread */ + thread = rt_list_entry(list->next, struct rt_thread, tlist); + /* set error code to RT_ERROR */ + thread->error = -RT_ERROR; + + /* + * resume thread + * In rt_thread_resume function, it will remove current thread from + * suspended list + */ + rt_thread_resume(thread); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + } + + return RT_EOK; +} + +#ifdef RT_USING_SEMAPHORE +/** + * @addtogroup semaphore + * @{ + */ + +/** + * @brief This function will initialize a static semaphore object. + * + * @note For the static semaphore object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_sem_create() function will allocate memory space automatically and initialize + * the semaphore. + * + * @see rt_sem_create() + * + * @param sem is a pointer to the semaphore to initialize. It is assumed that storage for the semaphore will be + * allocated in your application. + * + * @param name is a pointer to the name you would like to give the semaphore. + * + * @param value is the initial value for the semaphore. + * If used to share resources, you should initialize the value as the number of available resources. + * If used to signal the occurrence of an event, you should initialize the value as 0. + * + * @param flag is the semaphore flag, which determines the queuing way of how multiple threads wait + * when the semaphore is not available. + * The semaphore flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this semaphore will become non-real-time threads. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_sem_init(rt_sem_t sem, + const char *name, + rt_uint32_t value, + rt_uint8_t flag) +{ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(value < 0x10000U); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(sem->parent.parent), RT_Object_Class_Semaphore, name); + + /* initialize ipc object */ + _ipc_object_init(&(sem->parent)); + + /* set initial value */ + sem->value = (rt_uint16_t)value; + + /* set parent */ + sem->parent.parent.flag = flag; + + return RT_EOK; +} +RTM_EXPORT(rt_sem_init); + + +/** + * @brief This function will detach a static semaphore object. + * + * @note This function is used to detach a static semaphore object which is initialized by rt_sem_init() function. + * By contrast, the rt_sem_delete() function will delete a semaphore object. + * When the semaphore is successfully detached, it will resume all suspended threads in the semaphore list. + * + * @see rt_sem_delete() + * + * @param sem is a pointer to a semaphore object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the semaphore detach failed. + * + * @warning This function can ONLY detach a static semaphore initialized by the rt_sem_init() function. + * If the semaphore is created by the rt_sem_create() function, you MUST NOT USE this function to detach it, + * ONLY USE the rt_sem_delete() function to complete the deletion. + */ +rt_err_t rt_sem_detach(rt_sem_t sem) +{ + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + RT_ASSERT(rt_object_is_systemobject(&sem->parent.parent)); + + /* wakeup all suspended threads */ + _ipc_list_resume_all(&(sem->parent.suspend_thread)); + + /* detach semaphore object */ + rt_object_detach(&(sem->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_sem_detach); + +#ifdef RT_USING_HEAP +/** + * @brief Creating a semaphore object. + * + * @note For the semaphore object, its memory space is allocated automatically. + * By contrast, the rt_sem_init() function will initialize a static semaphore object. + * + * @see rt_sem_init() + * + * @param name is a pointer to the name you would like to give the semaphore. + * + * @param value is the initial value for the semaphore. + * If used to share resources, you should initialize the value as the number of available resources. + * If used to signal the occurrence of an event, you should initialize the value as 0. + * + * @param flag is the semaphore flag, which determines the queuing way of how multiple threads wait + * when the semaphore is not available. + * The semaphore flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this semaphore will become non-real-time threads. + * + * @return Return a pointer to the semaphore object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can NOT be called in interrupt context. You can use macor RT_DEBUG_NOT_IN_INTERRUPT to check it. + */ +rt_sem_t rt_sem_create(const char *name, rt_uint32_t value, rt_uint8_t flag) +{ + rt_sem_t sem; + + RT_ASSERT(value < 0x10000U); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + sem = (rt_sem_t)rt_object_allocate(RT_Object_Class_Semaphore, name); + if (sem == RT_NULL) + return sem; + + /* initialize ipc object */ + _ipc_object_init(&(sem->parent)); + + /* set initial value */ + sem->value = value; + + /* set parent */ + sem->parent.parent.flag = flag; + + return sem; +} +RTM_EXPORT(rt_sem_create); + + +/** + * @brief This function will delete a semaphore object and release the memory space. + * + * @note This function is used to delete a semaphore object which is created by the rt_sem_create() function. + * By contrast, the rt_sem_detach() function will detach a static semaphore object. + * When the semaphore is successfully deleted, it will resume all suspended threads in the semaphore list. + * + * @see rt_sem_detach() + * + * @param sem is a pointer to a semaphore object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the semaphore detach failed. + * + * @warning This function can ONLY delete a semaphore initialized by the rt_sem_create() function. + * If the semaphore is initialized by the rt_sem_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_sem_detach() function to complete the detachment. + */ +rt_err_t rt_sem_delete(rt_sem_t sem) +{ + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + RT_ASSERT(rt_object_is_systemobject(&sem->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* wakeup all suspended threads */ + _ipc_list_resume_all(&(sem->parent.suspend_thread)); + + /* delete semaphore object */ + rt_object_delete(&(sem->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_sem_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will take a semaphore, if the semaphore is unavailable, the thread shall wait for + * the semaphore up to a specified time. + * + * @note When this function is called, the count value of the sem->value will decrease 1 until it is equal to 0. + * When the sem->value is 0, it means that the semaphore is unavailable. At this time, it will suspend the + * thread preparing to take the semaphore. + * On the contrary, the rt_sem_release() function will increase the count value of sem->value by 1 each time. + * + * @see rt_sem_trytake() + * + * @param sem is a pointer to a semaphore object. + * + * @param timeout is a timeout period (unit: an OS tick). If the semaphore is unavailable, the thread will wait for + * the semaphore up to the amount of time specified by this parameter. + * + * NOTE: + * If use Macro RT_WAITING_FOREVER to set this parameter, which means that when the + * message is unavailable in the queue, the thread will be waiting forever. + * If use macro RT_WAITING_NO to set this parameter, which means that this + * function is non-blocking and will return immediately. + * + * @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 semaphore take failed. + * + * @warning This function can ONLY be called in the thread context. It MUST NOT BE called in interrupt context. + */ +static rt_err_t _rt_sem_take(rt_sem_t sem, rt_int32_t timeout, int suspend_flag) +{ + rt_base_t level; + struct rt_thread *thread; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(sem->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("thread %s take sem:%s, which value is: %d\n", + rt_thread_self()->name, + ((struct rt_object *)sem)->name, + sem->value)); + + if (sem->value > 0) + { + /* semaphore is available */ + sem->value --; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + } + else + { + /* no waiting, return with timeout */ + if (timeout == 0) + { + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + else + { + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE); + + /* semaphore is unavailable, push to suspend list */ + /* get current thread */ + thread = rt_thread_self(); + + /* reset thread error number */ + thread->error = -RT_EINTR; + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("sem take: suspend thread - %s\n", + thread->name)); + + /* suspend thread */ + ret = _ipc_list_suspend(&(sem->parent.suspend_thread), + thread, + sem->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + RT_DEBUG_LOG(RT_DEBUG_IPC, ("set thread:%s to timer list\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do schedule */ + rt_schedule(); + + if (thread->error != RT_EOK) + { + return thread->error; + } + } + } + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(sem->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_sem_take(rt_sem_t sem, rt_int32_t time) +{ + return _rt_sem_take(sem, time, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_sem_take); + +rt_err_t rt_sem_take_interruptible(rt_sem_t sem, rt_int32_t time) +{ + return _rt_sem_take(sem, time, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_sem_take_interruptible); + +rt_err_t rt_sem_take_killable(rt_sem_t sem, rt_int32_t time) +{ + return _rt_sem_take(sem, time, RT_KILLABLE); +} +RTM_EXPORT(rt_sem_take_killable); + +/** + * @brief This function will try to take a semaphore, if the semaphore is unavailable, the thread returns immediately. + * + * @note This function is very similar to the rt_sem_take() function, when the semaphore is not available, + * the rt_sem_trytake() function will return immediately without waiting for a timeout. + * In other words, rt_sem_trytake(sem) has the same effect as rt_sem_take(sem, 0). + * + * @see rt_sem_take() + * + * @param sem is a pointer to a semaphore object. + * + * @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 semaphore take failed. + */ +rt_err_t rt_sem_trytake(rt_sem_t sem) +{ + return rt_sem_take(sem, RT_WAITING_NO); +} +RTM_EXPORT(rt_sem_trytake); + + +/** + * @brief This function will release a semaphore. If there is thread suspended on the semaphore, it will get resumed. + * + * @note If there are threads suspended on this semaphore, the first thread in the list of this semaphore object + * will be resumed, and a thread scheduling (rt_schedule) will be executed. + * If no threads are suspended on this semaphore, the count value sem->value of this semaphore will increase by 1. + * + * @param sem is a pointer to a semaphore object. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the semaphore release failed. + */ +rt_err_t rt_sem_release(rt_sem_t sem) +{ + rt_base_t level; + rt_bool_t need_schedule; + + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(sem->parent.parent))); + + need_schedule = RT_FALSE; + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("thread %s releases sem:%s, which value is: %d\n", + rt_thread_self()->name, + ((struct rt_object *)sem)->name, + sem->value)); + + if (!rt_list_isempty(&sem->parent.suspend_thread)) + { + /* resume the suspended thread */ + _ipc_list_resume(&(sem->parent.suspend_thread)); + need_schedule = RT_TRUE; + } + else + { + if(sem->value < RT_SEM_VALUE_MAX) + { + sem->value ++; /* increase value */ + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* resume a thread, re-schedule */ + if (need_schedule == RT_TRUE) + rt_schedule(); + + return RT_EOK; +} +RTM_EXPORT(rt_sem_release); + + +/** + * @brief This function will set some extra attributions of a semaphore object. + * + * @note Currently this function only supports the RT_IPC_CMD_RESET command to reset the semaphore. + * + * @param sem is a pointer to a semaphore object. + * + * @param cmd is a command word used to configure some attributions of the semaphore. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_sem_control(rt_sem_t sem, int cmd, void *arg) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + + if (cmd == RT_IPC_CMD_RESET) + { + rt_ubase_t value; + + /* get value */ + value = (rt_ubase_t)arg; + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* resume all waiting thread */ + _ipc_list_resume_all(&sem->parent.suspend_thread); + + /* set new value */ + sem->value = (rt_uint16_t)value; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_sem_control); + +/**@}*/ +#endif /* RT_USING_SEMAPHORE */ + +#ifdef RT_USING_MUTEX +rt_inline rt_uint8_t _mutex_update_priority(struct rt_mutex *mutex) +{ + struct rt_thread *thread; + + if (!rt_list_isempty(&mutex->parent.suspend_thread)) + { + thread = rt_list_entry(mutex->parent.suspend_thread.next, struct rt_thread, tlist); + mutex->priority = thread->current_priority; + } + else + { + mutex->priority = 0xff; + } + + return mutex->priority; +} + +rt_inline rt_uint8_t _thread_get_mutex_priority(struct rt_thread* thread) +{ + rt_list_t *node = RT_NULL; + struct rt_mutex *mutex = RT_NULL; + rt_uint8_t priority = thread->init_priority; + + rt_list_for_each(node, &(thread->taken_object_list)) + { + mutex = rt_list_entry(node, struct rt_mutex, taken_list); + if (priority > mutex->priority) + { + priority = mutex->priority; + } + } + + return priority; +} + +rt_inline void _thread_update_priority(struct rt_thread *thread, rt_uint8_t priority, int suspend_flag) +{ + rt_err_t ret; + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("thread:%s priority -> %d\n", thread->name, priority)); + + /* change priority of the thread */ + rt_thread_control(thread, + RT_THREAD_CTRL_CHANGE_PRIORITY, + &priority); + + if ((thread->stat & RT_THREAD_SUSPEND_MASK) == RT_THREAD_SUSPEND_MASK) + { + /* whether change the priority of taken mutex */ + struct rt_object* pending_obj = thread->pending_object; + + if (pending_obj && rt_object_get_type(pending_obj) == RT_Object_Class_Mutex) + { + rt_uint8_t mutex_priority; + struct rt_mutex* pending_mutex = (struct rt_mutex *)pending_obj; + + /* re-insert thread to suspended thread list */ + rt_list_remove(&(thread->tlist)); + + ret = _ipc_list_suspend(&(pending_mutex->parent.suspend_thread), + thread, + pending_mutex->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + /* TODO */ + return ; + } + + /* update priority */ + _mutex_update_priority(pending_mutex); + /* change the priority of mutex owner thread */ + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("mutex: %s priority -> %d\n", pending_mutex->parent.parent.name, + pending_mutex->priority)); + + mutex_priority = _thread_get_mutex_priority(pending_mutex->owner); + if (mutex_priority != pending_mutex->owner->current_priority) + { + _thread_update_priority(pending_mutex->owner, mutex_priority, suspend_flag); + } + } + } +} + +/** + * @addtogroup mutex + * @{ + */ + +/** + * @brief Initialize a static mutex object. + * + * @note For the static mutex object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_mutex_create() function will automatically allocate memory space + * and initialize the mutex. + * + * @see rt_mutex_create() + * + * @param mutex is a pointer to the mutex to initialize. It is assumed that storage for the mutex will be + * allocated in your application. + * + * @param name is a pointer to the name that given to the mutex. + * + * @param flag is the mutex flag, which determines the queuing way of how multiple threads wait + * when the mutex is not available. + * NOTE: This parameter has been obsoleted. It can be RT_IPC_FLAG_PRIO, RT_IPC_FLAG_FIFO or RT_NULL. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_mutex_init(rt_mutex_t mutex, const char *name, rt_uint8_t flag) +{ + /* flag parameter has been obsoleted */ + RT_UNUSED(flag); + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + + /* initialize object */ + rt_object_init(&(mutex->parent.parent), RT_Object_Class_Mutex, name); + + /* initialize ipc object */ + _ipc_object_init(&(mutex->parent)); + + mutex->owner = RT_NULL; + mutex->priority = 0xFF; + mutex->hold = 0; + mutex->ceiling_priority = 0xFF; + rt_list_init(&(mutex->taken_list)); + + /* flag can only be RT_IPC_FLAG_PRIO. RT_IPC_FLAG_FIFO cannot solve the unbounded priority inversion problem */ + mutex->parent.parent.flag = RT_IPC_FLAG_PRIO; + + return RT_EOK; +} +RTM_EXPORT(rt_mutex_init); + + +/** + * @brief This function will detach a static mutex object. + * + * @note This function is used to detach a static mutex object which is initialized by rt_mutex_init() function. + * By contrast, the rt_mutex_delete() function will delete a mutex object. + * When the mutex is successfully detached, it will resume all suspended threads in the mutex list. + * + * @see rt_mutex_delete() + * + * @param mutex is a pointer to a mutex object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the mutex detach failed. + * + * @warning This function can ONLY detach a static mutex initialized by the rt_mutex_init() function. + * If the mutex is created by the rt_mutex_create() function, you MUST NOT USE this function to detach it, + * ONLY USE the rt_mutex_delete() function to complete the deletion. + */ +rt_err_t rt_mutex_detach(rt_mutex_t mutex) +{ + rt_ubase_t level; + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + RT_ASSERT(rt_object_is_systemobject(&mutex->parent.parent)); + + level = rt_hw_interrupt_disable(); + /* wakeup all suspended threads */ + _ipc_list_resume_all(&(mutex->parent.suspend_thread)); + /* remove mutex from thread's taken list */ + rt_list_remove(&mutex->taken_list); + rt_hw_interrupt_enable(level); + + /* detach mutex object */ + rt_object_detach(&(mutex->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mutex_detach); + +/* drop a thread from the suspend list of mutex */ + +/** + * @brief drop a thread from the suspend list of mutex + * + * @param mutex is a pointer to a mutex object. + * @param thread is the thread should be dropped from mutex. + */ +void rt_mutex_drop_thread(rt_mutex_t mutex, rt_thread_t thread) +{ + rt_uint8_t priority; + rt_bool_t need_update = RT_FALSE; + + rt_list_remove(&(thread->tlist)); + + /* should change the priority of mutex owner thread */ + if (mutex->owner->current_priority == thread->current_priority) + need_update = RT_TRUE; + + /* update the priority of mutex */ + if (!rt_list_isempty(&mutex->parent.suspend_thread)) + { + /* more thread suspended in the list */ + struct rt_thread *th; + + th = rt_list_entry(mutex->parent.suspend_thread.next, + struct rt_thread, + tlist); + /* update the priority of mutex */ + mutex->priority = th->current_priority; + } + else + { + /* set mutex priority to maximal priority */ + mutex->priority = 0xff; + } + + /* try to change the priority of mutex owner thread */ + if (need_update) + { + /* get the maximal priority of mutex in thread */ + priority = _thread_get_mutex_priority(mutex->owner); + if (priority != mutex->owner->current_priority) + { + _thread_update_priority(mutex->owner, priority, RT_UNINTERRUPTIBLE); + } + } +} + + +/** + * @brief set the prioceiling attribute of the mutex. + * + * @param mutex is a pointer to a mutex object. + * @param priority is the priority should be set to mutex. + * + * @return return the old priority ceiling + */ +rt_uint8_t rt_mutex_setprioceiling(rt_mutex_t mutex, rt_uint8_t priority) +{ + rt_uint8_t ret_priority = 0xFF; + + if ((mutex) && (priority < RT_THREAD_PRIORITY_MAX)) + { + ret_priority = mutex->ceiling_priority; + mutex->ceiling_priority = priority; + } + else + { + rt_set_errno(-RT_EINVAL); + } + + return ret_priority; +} +RTM_EXPORT(rt_mutex_setprioceiling); + + +/** + * @brief set the prioceiling attribute of the mutex. + * + * @param mutex is a pointer to a mutex object. + * + * @return return the current priority ceiling of the mutex. + */ +rt_uint8_t rt_mutex_getprioceiling(rt_mutex_t mutex) +{ + rt_uint8_t prio = 0xFF; + + if (mutex) + { + prio = mutex->ceiling_priority; + } + + return prio; +} +RTM_EXPORT(rt_mutex_getprioceiling); + + +#ifdef RT_USING_HEAP +/** + * @brief This function will create a mutex object. + * + * @note For the mutex object, its memory space is automatically allocated. + * By contrast, the rt_mutex_init() function will initialize a static mutex object. + * + * @see rt_mutex_init() + * + * @param name is a pointer to the name that given to the mutex. + * + * @param flag is the mutex flag, which determines the queuing way of how multiple threads wait + * when the mutex is not available. + * NOTE: This parameter has been obsoleted. It can be RT_IPC_FLAG_PRIO, RT_IPC_FLAG_FIFO or RT_NULL. + * + * @return Return a pointer to the mutex object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_mutex_t rt_mutex_create(const char *name, rt_uint8_t flag) +{ + struct rt_mutex *mutex; + + /* flag parameter has been obsoleted */ + RT_UNUSED(flag); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + mutex = (rt_mutex_t)rt_object_allocate(RT_Object_Class_Mutex, name); + if (mutex == RT_NULL) + return mutex; + + /* initialize ipc object */ + _ipc_object_init(&(mutex->parent)); + + mutex->owner = RT_NULL; + mutex->priority = 0xFF; + mutex->hold = 0; + mutex->ceiling_priority = 0xFF; + rt_list_init(&(mutex->taken_list)); + + /* flag can only be RT_IPC_FLAG_PRIO. RT_IPC_FLAG_FIFO cannot solve the unbounded priority inversion problem */ + mutex->parent.parent.flag = RT_IPC_FLAG_PRIO; + + return mutex; +} +RTM_EXPORT(rt_mutex_create); + + +/** + * @brief This function will delete a mutex object and release this memory space. + * + * @note This function is used to delete a mutex object which is created by the rt_mutex_create() function. + * By contrast, the rt_mutex_detach() function will detach a static mutex object. + * When the mutex is successfully deleted, it will resume all suspended threads in the mutex list. + * + * @see rt_mutex_detach() + * + * @param mutex is a pointer to a mutex object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mutex detach failed. + * + * @warning This function can ONLY delete a mutex initialized by the rt_mutex_create() function. + * If the mutex is initialized by the rt_mutex_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_mutex_detach() function to complete the detachment. + */ +rt_err_t rt_mutex_delete(rt_mutex_t mutex) +{ + rt_ubase_t level; + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + RT_ASSERT(rt_object_is_systemobject(&mutex->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + level = rt_hw_interrupt_disable(); + /* wakeup all suspended threads */ + _ipc_list_resume_all(&(mutex->parent.suspend_thread)); + /* remove mutex from thread's taken list */ + rt_list_remove(&mutex->taken_list); + rt_hw_interrupt_enable(level); + + /* delete mutex object */ + rt_object_delete(&(mutex->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mutex_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will take a mutex, if the mutex is unavailable, the thread shall wait for + * the mutex up to a specified time. + * + * @note When this function is called, the count value of the mutex->value will decrease 1 until it is equal to 0. + * When the mutex->value is 0, it means that the mutex is unavailable. At this time, it will suspend the + * thread preparing to take the mutex. + * On the contrary, the rt_mutex_release() function will increase the count value of mutex->value by 1 each time. + * + * @see rt_mutex_trytake() + * + * @param mutex is a pointer to a mutex object. + * + * @param timeout is a timeout period (unit: an OS tick). If the mutex is unavailable, the thread will wait for + * the mutex up to the amount of time specified by the argument. + * NOTE: Generally, we set this parameter to RT_WAITING_FOREVER, which means that when the mutex is unavailable, + * the thread will be waitting forever. + * + * @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 mutex take failed. + * + * @warning This function can ONLY be called in the thread context. It MUST NOT BE called in interrupt context. + */ +static rt_err_t _rt_mutex_take(rt_mutex_t mutex, rt_int32_t timeout, int suspend_flag) +{ + rt_base_t level; + struct rt_thread *thread; + rt_err_t ret; + + /* this function must not be used in interrupt even if time = 0 */ + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE); + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + + /* get current thread */ + thread = rt_thread_self(); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(mutex->parent.parent))); + + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("mutex_take: current thread %s, hold: %d\n", + thread->name, mutex->hold)); + + /* reset thread error */ + thread->error = RT_EOK; + + if (mutex->owner == thread) + { + if(mutex->hold < RT_MUTEX_HOLD_MAX) + { + /* it's the same thread */ + mutex->hold ++; + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + } + else + { + /* whether the mutex has owner thread. */ + if (mutex->owner == RT_NULL) + { + /* set mutex owner and original priority */ + mutex->owner = thread; + mutex->priority = 0xff; + mutex->hold = 1; + + if (mutex->ceiling_priority != 0xFF) + { + /* set the priority of thread to the ceiling priority */ + if (mutex->ceiling_priority < mutex->owner->current_priority) + _thread_update_priority(mutex->owner, mutex->ceiling_priority, suspend_flag); + } + else + { + /* insert mutex to thread's taken object list */ + rt_list_insert_after(&thread->taken_object_list, &mutex->taken_list); + } + } + else + { + /* no waiting, return with timeout */ + if (timeout == 0) + { + /* set error as timeout */ + thread->error = -RT_ETIMEOUT; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + else + { + rt_uint8_t priority = thread->current_priority; + + /* mutex is unavailable, push to suspend list */ + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mutex_take: suspend thread: %s\n", + thread->name)); + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mutex->parent.suspend_thread), + thread, + mutex->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* set pending object in thread to this mutex */ + thread->pending_object = &(mutex->parent.parent); + + /* update the priority level of mutex */ + if (priority < mutex->priority) + { + mutex->priority = priority; + if (mutex->priority < mutex->owner->current_priority) + { + _thread_update_priority(mutex->owner, priority, RT_UNINTERRUPTIBLE); /* TODO */ + } + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("mutex_take: start the timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do schedule */ + rt_schedule(); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + if (thread->error == RT_EOK) + { + /* get mutex successfully */ + } + else + { + /* the mutex has not been taken and thread has detach from the pending list. */ + + rt_bool_t need_update = RT_FALSE; + + /* should change the priority of mutex owner thread */ + if (mutex->owner->current_priority == thread->current_priority) + need_update = RT_TRUE; + + /* update the priority of mutex */ + if (!rt_list_isempty(&mutex->parent.suspend_thread)) + { + /* more thread suspended in the list */ + struct rt_thread *th; + + th = rt_list_entry(mutex->parent.suspend_thread.next, + struct rt_thread, + tlist); + /* update the priority of mutex */ + mutex->priority = th->current_priority; + } + else + { + /* set mutex priority to maximal priority */ + mutex->priority = 0xff; + } + + /* try to change the priority of mutex owner thread */ + if (need_update) + { + /* get the maximal priority of mutex in thread */ + priority = _thread_get_mutex_priority(mutex->owner); + if (priority != mutex->owner->current_priority) + { + _thread_update_priority(mutex->owner, priority, RT_UNINTERRUPTIBLE); + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* return error */ + return thread->error; + } + } + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mutex->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_mutex_take(rt_mutex_t mutex, rt_int32_t time) +{ + return _rt_mutex_take(mutex, time, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mutex_take); + +rt_err_t rt_mutex_take_interruptible(rt_mutex_t mutex, rt_int32_t time) +{ + return _rt_mutex_take(mutex, time, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mutex_take_interruptible); + +rt_err_t rt_mutex_take_killable(rt_mutex_t mutex, rt_int32_t time) +{ + return _rt_mutex_take(mutex, time, RT_KILLABLE); +} +RTM_EXPORT(rt_mutex_take_killable); + +/** + * @brief This function will try to take a mutex, if the mutex is unavailable, the thread returns immediately. + * + * @note This function is very similar to the rt_mutex_take() function, when the mutex is not available, + * except that rt_mutex_trytake() will return immediately without waiting for a timeout + * when the mutex is not available. + * In other words, rt_mutex_trytake(mutex) has the same effect as rt_mutex_take(mutex, 0). + * + * @see rt_mutex_take() + * + * @param mutex is a pointer to a mutex object. + * + * @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 mutex take failed. + */ +rt_err_t rt_mutex_trytake(rt_mutex_t mutex) +{ + return rt_mutex_take(mutex, RT_WAITING_NO); +} +RTM_EXPORT(rt_mutex_trytake); + + +/** + * @brief This function will release a mutex. If there is thread suspended on the mutex, the thread will be resumed. + * + * @note If there are threads suspended on this mutex, the first thread in the list of this mutex object + * will be resumed, and a thread scheduling (rt_schedule) will be executed. + * If no threads are suspended on this mutex, the count value mutex->value of this mutex will increase by 1. + * + * @param mutex is a pointer to a mutex object. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mutex release failed. + */ +rt_err_t rt_mutex_release(rt_mutex_t mutex) +{ + rt_base_t level; + struct rt_thread *thread; + rt_bool_t need_schedule; + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + + need_schedule = RT_FALSE; + + /* only thread could release mutex because we need test the ownership */ + RT_DEBUG_IN_THREAD_CONTEXT; + + /* get current thread */ + thread = rt_thread_self(); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("mutex_release:current thread %s, hold: %d\n", + thread->name, mutex->hold)); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mutex->parent.parent))); + + /* mutex only can be released by owner */ + if (thread != mutex->owner) + { + thread->error = -RT_ERROR; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_ERROR; + } + + /* decrease hold */ + mutex->hold --; + /* if no hold */ + if (mutex->hold == 0) + { + /* remove mutex from thread's taken list */ + rt_list_remove(&mutex->taken_list); + + /* whether change the thread priority */ + if ((mutex->ceiling_priority != 0xFF) || (thread->current_priority == mutex->priority)) + { + rt_uint8_t priority = 0xff; + + /* get the highest priority in the taken list of thread */ + priority = _thread_get_mutex_priority(thread); + + rt_thread_control(thread, + RT_THREAD_CTRL_CHANGE_PRIORITY, + &priority); + + need_schedule = RT_TRUE; + } + + /* wakeup suspended thread */ + if (!rt_list_isempty(&mutex->parent.suspend_thread)) + { + /* get the first suspended thread */ + struct rt_thread *next_thread = rt_list_entry(mutex->parent.suspend_thread.next, + struct rt_thread, + tlist); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mutex_release: resume thread: %s\n", + next_thread->name)); + + /* remove the thread from the suspended list of mutex */ + rt_list_remove(&(next_thread->tlist)); + + /* set new owner and put mutex into taken list of thread */ + mutex->owner = next_thread; + mutex->hold = 1; + rt_list_insert_after(&next_thread->taken_object_list, &mutex->taken_list); + /* cleanup pending object */ + next_thread->pending_object = RT_NULL; + + /* resume thread */ + rt_thread_resume(next_thread); + + /* update mutex priority */ + if (!rt_list_isempty(&(mutex->parent.suspend_thread))) + { + struct rt_thread *th; + + th = rt_list_entry(mutex->parent.suspend_thread.next, + struct rt_thread, + tlist); + mutex->priority = th->current_priority; + } + else + { + mutex->priority = 0xff; + } + + need_schedule = RT_TRUE; + } + else + { + /* clear owner */ + mutex->owner = RT_NULL; + mutex->priority = 0xff; + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* perform a schedule */ + if (need_schedule == RT_TRUE) + rt_schedule(); + + return RT_EOK; +} +RTM_EXPORT(rt_mutex_release); + + +/** + * @brief This function will set some extra attributions of a mutex object. + * + * @note Currently this function does not implement the control function. + * + * @param mutex is a pointer to a mutex object. + * + * @param cmd is a command word used to configure some attributions of the mutex. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_mutex_control(rt_mutex_t mutex, int cmd, void *arg) +{ + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + + return -RT_ERROR; +} +RTM_EXPORT(rt_mutex_control); + +/**@}*/ +#endif /* RT_USING_MUTEX */ + +#ifdef RT_USING_EVENT +/** + * @addtogroup event + * @{ + */ + +/** + * @brief The function will initialize a static event object. + * + * @note For the static event object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_event_create() function will allocate memory space automatically + * and initialize the event. + * + * @see rt_event_create() + * + * @param event is a pointer to the event to initialize. It is assumed that storage for the event + * will be allocated in your application. + * + * @param name is a pointer to the name that given to the event. + * + * @param flag is the event flag, which determines the queuing way of how multiple threads wait + * when the event is not available. + * The event flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this event will become non-real-time threads. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_event_init(rt_event_t event, const char *name, rt_uint8_t flag) +{ + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(event->parent.parent), RT_Object_Class_Event, name); + + /* set parent flag */ + event->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(event->parent)); + + /* initialize event */ + event->set = 0; + + return RT_EOK; +} +RTM_EXPORT(rt_event_init); + + +/** + * @brief This function will detach a static event object. + * + * @note This function is used to detach a static event object which is initialized by rt_event_init() function. + * By contrast, the rt_event_delete() function will delete an event object. + * When the event is successfully detached, it will resume all suspended threads in the event list. + * + * @see rt_event_delete() + * + * @param event is a pointer to an event object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the event detach failed. + * + * @warning This function can ONLY detach a static event initialized by the rt_event_init() function. + * If the event is created by the rt_event_create() function, you MUST NOT USE this function to detach it, + * ONLY USE the rt_event_delete() function to complete the deletion. + */ +rt_err_t rt_event_detach(rt_event_t event) +{ + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + RT_ASSERT(rt_object_is_systemobject(&event->parent.parent)); + + /* resume all suspended thread */ + _ipc_list_resume_all(&(event->parent.suspend_thread)); + + /* detach event object */ + rt_object_detach(&(event->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_event_detach); + +#ifdef RT_USING_HEAP +/** + * @brief Creating an event object. + * + * @note For the event object, its memory space is allocated automatically. + * By contrast, the rt_event_init() function will initialize a static event object. + * + * @see rt_event_init() + * + * @param name is a pointer to the name that given to the event. + * + * @param flag is the event flag, which determines the queuing way of how multiple threads wait when the event + * is not available. + * The event flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this event will become non-real-time threads. + * + * @return Return a pointer to the event object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_event_t rt_event_create(const char *name, rt_uint8_t flag) +{ + rt_event_t event; + + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + event = (rt_event_t)rt_object_allocate(RT_Object_Class_Event, name); + if (event == RT_NULL) + return event; + + /* set parent */ + event->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(event->parent)); + + /* initialize event */ + event->set = 0; + + return event; +} +RTM_EXPORT(rt_event_create); + + +/** + * @brief This function will delete an event object and release the memory space. + * + * @note This function is used to delete an event object which is created by the rt_event_create() function. + * By contrast, the rt_event_detach() function will detach a static event object. + * When the event is successfully deleted, it will resume all suspended threads in the event list. + * + * @see rt_event_detach() + * + * @param event is a pointer to an event object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the event detach failed. + * + * @warning This function can ONLY delete an event initialized by the rt_event_create() function. + * If the event is initialized by the rt_event_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_event_detach() function to complete the detachment. + */ +rt_err_t rt_event_delete(rt_event_t event) +{ + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + RT_ASSERT(rt_object_is_systemobject(&event->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* resume all suspended thread */ + _ipc_list_resume_all(&(event->parent.suspend_thread)); + + /* delete event object */ + rt_object_delete(&(event->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_event_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will send an event to the event object. + * If there is a thread suspended on the event, the thread will be resumed. + * + * @note When using this function, you need to use the parameter (set) to specify the event flag of the event object, + * then the function will traverse the list of suspended threads waiting on the event object. + * If there is a thread suspended on the event, and the thread's event_info and the event flag of + * the current event object matches, the thread will be resumed. + * + * @param event is a pointer to the event object to be sent. + * + * @param set is a flag that you will set for this event's flag. + * You can set an event flag, or you can set multiple flags through OR logic operation. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the event detach failed. + */ +rt_err_t rt_event_send(rt_event_t event, rt_uint32_t set) +{ + struct rt_list_node *n; + struct rt_thread *thread; + rt_base_t level; + rt_base_t status; + rt_bool_t need_schedule; + + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + + if (set == 0) + return -RT_ERROR; + + need_schedule = RT_FALSE; + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* set event */ + event->set |= set; + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(event->parent.parent))); + + if (!rt_list_isempty(&event->parent.suspend_thread)) + { + /* search thread list to resume thread */ + n = event->parent.suspend_thread.next; + while (n != &(event->parent.suspend_thread)) + { + /* get thread */ + thread = rt_list_entry(n, struct rt_thread, tlist); + + status = -RT_ERROR; + if (thread->event_info & RT_EVENT_FLAG_AND) + { + if ((thread->event_set & event->set) == thread->event_set) + { + /* received an AND event */ + status = RT_EOK; + } + } + else if (thread->event_info & RT_EVENT_FLAG_OR) + { + if (thread->event_set & event->set) + { + /* save the received event set */ + thread->event_set = thread->event_set & event->set; + + /* received an OR event */ + status = RT_EOK; + } + } + else + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EINVAL; + } + + /* move node to the next */ + n = n->next; + + /* condition is satisfied, resume thread */ + if (status == RT_EOK) + { + /* clear event */ + if (thread->event_info & RT_EVENT_FLAG_CLEAR) + event->set &= ~thread->event_set; + + /* resume thread, and thread list breaks out */ + rt_thread_resume(thread); + thread->error = RT_EOK; + + /* need do a scheduling */ + need_schedule = RT_TRUE; + } + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do a schedule */ + if (need_schedule == RT_TRUE) + rt_schedule(); + + return RT_EOK; +} +RTM_EXPORT(rt_event_send); + + +/** + * @brief This function will receive an event from event object. if the event is unavailable, the thread shall wait for + * the event up to a specified time. + * + * @note If there are threads suspended on this semaphore, the first thread in the list of this semaphore object + * will be resumed, and a thread scheduling (rt_schedule) will be executed. + * If no threads are suspended on this semaphore, the count value sem->value of this semaphore will increase by 1. + * + * @param event is a pointer to the event object to be received. + * + * @param set is a flag that you will set for this event's flag. + * You can set an event flag, or you can set multiple flags through OR logic operation. + * + * @param option is the option of this receiving event, it indicates how the receiving event is operated. + * The option can be one or more of the following values, When selecting multiple values,use logical OR to operate. + * (NOTE: RT_EVENT_FLAG_OR and RT_EVENT_FLAG_AND can only select one): + * + * + * RT_EVENT_FLAG_OR The thread select to use logical OR to receive the event. + * + * RT_EVENT_FLAG_AND The thread select to use logical OR to receive the event. + * + * RT_EVENT_FLAG_CLEAR When the thread receives the corresponding event, the function + * determines whether to clear the event flag. + * + * @param timeout is a timeout period (unit: an OS tick). + * + * @param recved is a pointer to the received event. If you don't care about this value, you can use RT_NULL to set. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the semaphore release failed. + */ +static rt_err_t _rt_event_recv(rt_event_t event, + rt_uint32_t set, + rt_uint8_t option, + rt_int32_t timeout, + rt_uint32_t *recved, + int suspend_flag) +{ + struct rt_thread *thread; + rt_base_t level; + rt_base_t status; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE); + + if (set == 0) + return -RT_ERROR; + + /* initialize status */ + status = -RT_ERROR; + /* get current thread */ + thread = rt_thread_self(); + /* reset thread error */ + thread->error = -RT_EINTR; + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(event->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* check event set */ + if (option & RT_EVENT_FLAG_AND) + { + if ((event->set & set) == set) + status = RT_EOK; + } + else if (option & RT_EVENT_FLAG_OR) + { + if (event->set & set) + status = RT_EOK; + } + else + { + /* either RT_EVENT_FLAG_AND or RT_EVENT_FLAG_OR should be set */ + RT_ASSERT(0); + } + + if (status == RT_EOK) + { + thread->error = RT_EOK; + + /* set received event */ + if (recved) + *recved = (event->set & set); + + /* fill thread event info */ + thread->event_set = (event->set & set); + thread->event_info = option; + + /* received event */ + if (option & RT_EVENT_FLAG_CLEAR) + event->set &= ~set; + } + else if (timeout == 0) + { + /* no waiting */ + thread->error = -RT_ETIMEOUT; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + else + { + /* fill thread event info */ + thread->event_set = set; + thread->event_info = option; + + /* put thread to suspended thread list */ + ret = _ipc_list_suspend(&(event->parent.suspend_thread), + thread, + event->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* if there is a waiting timeout, active thread timer */ + if (timeout > 0) + { + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do a schedule */ + rt_schedule(); + + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* received an event, disable interrupt to protect */ + level = rt_hw_interrupt_disable(); + + /* set received event */ + if (recved) + *recved = thread->event_set; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(event->parent.parent))); + + return thread->error; +} + +rt_err_t rt_event_recv(rt_event_t event, + rt_uint32_t set, + rt_uint8_t option, + rt_int32_t timeout, + rt_uint32_t *recved) +{ + return _rt_event_recv(event, set, option, timeout, recved, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_event_recv); + +rt_err_t rt_event_recv_interruptible(rt_event_t event, + rt_uint32_t set, + rt_uint8_t option, + rt_int32_t timeout, + rt_uint32_t *recved) +{ + return _rt_event_recv(event, set, option, timeout, recved, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_event_recv_interruptible); + +rt_err_t rt_event_recv_killable(rt_event_t event, + rt_uint32_t set, + rt_uint8_t option, + rt_int32_t timeout, + rt_uint32_t *recved) +{ + return _rt_event_recv(event, set, option, timeout, recved, RT_KILLABLE); +} +RTM_EXPORT(rt_event_recv_killable); +/** + * @brief This function will set some extra attributions of an event object. + * + * @note Currently this function only supports the RT_IPC_CMD_RESET command to reset the event. + * + * @param event is a pointer to an event object. + * + * @param cmd is a command word used to configure some attributions of the event. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_event_control(rt_event_t event, int cmd, void *arg) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + + if (cmd == RT_IPC_CMD_RESET) + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* resume all waiting thread */ + _ipc_list_resume_all(&event->parent.suspend_thread); + + /* initialize event set */ + event->set = 0; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_event_control); + +/**@}*/ +#endif /* RT_USING_EVENT */ + +#ifdef RT_USING_MAILBOX +/** + * @addtogroup mailbox + * @{ + */ + +/** + * @brief Initialize a static mailbox object. + * + * @note For the static mailbox object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_mb_create() function will allocate memory space automatically and initialize the mailbox. + * + * @see rt_mb_create() + * + * @param mb is a pointer to the mailbox to initialize. + * It is assumed that storage for the mailbox will be allocated in your application. + * + * @param name is a pointer to the name that given to the mailbox. + * + * @param msgpool the begin address of buffer to save received mail. + * + * @param size is the maximum number of mails in the mailbox. + * For example, when the mailbox buffer capacity is N, size is N/4. + * + * @param flag is the mailbox flag, which determines the queuing way of how multiple threads wait + * when the mailbox is not available. + * The mailbox flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this mailbox will become non-real-time threads. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_mb_init(rt_mailbox_t mb, + const char *name, + void *msgpool, + rt_size_t size, + rt_uint8_t flag) +{ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(mb->parent.parent), RT_Object_Class_MailBox, name); + + /* set parent flag */ + mb->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(mb->parent)); + + /* initialize mailbox */ + mb->msg_pool = (rt_ubase_t *)msgpool; + mb->size = (rt_uint16_t)size; + mb->entry = 0; + mb->in_offset = 0; + mb->out_offset = 0; + + /* initialize an additional list of sender suspend thread */ + rt_list_init(&(mb->suspend_sender_thread)); + + return RT_EOK; +} +RTM_EXPORT(rt_mb_init); + + +/** + * @brief This function will detach a static mailbox object. + * + * @note This function is used to detach a static mailbox object which is initialized by rt_mb_init() function. + * By contrast, the rt_mb_delete() function will delete a mailbox object. + * When the mailbox is successfully detached, it will resume all suspended threads in the mailbox list. + * + * @see rt_mb_delete() + * + * @param mb is a pointer to a mailbox object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the mailbox detach failed. + * + * @warning This function can ONLY detach a static mailbox initialized by the rt_mb_init() function. + * If the mailbox is created by the rt_mb_create() function, you MUST NOT USE this function to detach it, + * ONLY USE the rt_mb_delete() function to complete the deletion. + */ +rt_err_t rt_mb_detach(rt_mailbox_t mb) +{ + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + RT_ASSERT(rt_object_is_systemobject(&mb->parent.parent)); + + /* resume all suspended thread */ + _ipc_list_resume_all(&(mb->parent.suspend_thread)); + /* also resume all mailbox private suspended thread */ + _ipc_list_resume_all(&(mb->suspend_sender_thread)); + + /* detach mailbox object */ + rt_object_detach(&(mb->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mb_detach); + +#ifdef RT_USING_HEAP +/** + * @brief Creating a mailbox object. + * + * @note For the mailbox object, its memory space is allocated automatically. + * By contrast, the rt_mb_init() function will initialize a static mailbox object. + * + * @see rt_mb_init() + * + * @param name is a pointer that given to the mailbox. + * + * @param size is the maximum number of mails in the mailbox. + * For example, when mailbox buffer capacity is N, size is N/4. + * + * @param flag is the mailbox flag, which determines the queuing way of how multiple threads wait + * when the mailbox is not available. + * The mailbox flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this mailbox will become non-real-time threads. + * + * @return Return a pointer to the mailbox object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_mailbox_t rt_mb_create(const char *name, rt_size_t size, rt_uint8_t flag) +{ + rt_mailbox_t mb; + + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + mb = (rt_mailbox_t)rt_object_allocate(RT_Object_Class_MailBox, name); + if (mb == RT_NULL) + return mb; + + /* set parent */ + mb->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(mb->parent)); + + /* initialize mailbox */ + mb->size = (rt_uint16_t)size; + mb->msg_pool = (rt_ubase_t *)RT_KERNEL_MALLOC(mb->size * sizeof(rt_ubase_t)); + if (mb->msg_pool == RT_NULL) + { + /* delete mailbox object */ + rt_object_delete(&(mb->parent.parent)); + + return RT_NULL; + } + mb->entry = 0; + mb->in_offset = 0; + mb->out_offset = 0; + + /* initialize an additional list of sender suspend thread */ + rt_list_init(&(mb->suspend_sender_thread)); + + return mb; +} +RTM_EXPORT(rt_mb_create); + + +/** + * @brief This function will delete a mailbox object and release the memory space. + * + * @note This function is used to delete a mailbox object which is created by the rt_mb_create() function. + * By contrast, the rt_mb_detach() function will detach a static mailbox object. + * When the mailbox is successfully deleted, it will resume all suspended threads in the mailbox list. + * + * @see rt_mb_detach() + * + * @param mb is a pointer to a mailbox object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + * + * @warning This function can only delete mailbox created by the rt_mb_create() function. + * If the mailbox is initialized by the rt_mb_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_mb_detach() function to complete the detachment. + */ +rt_err_t rt_mb_delete(rt_mailbox_t mb) +{ + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + RT_ASSERT(rt_object_is_systemobject(&mb->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* resume all suspended thread */ + _ipc_list_resume_all(&(mb->parent.suspend_thread)); + + /* also resume all mailbox private suspended thread */ + _ipc_list_resume_all(&(mb->suspend_sender_thread)); + + /* free mailbox pool */ + RT_KERNEL_FREE(mb->msg_pool); + + /* delete mailbox object */ + rt_object_delete(&(mb->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mb_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will send an mail to the mailbox object. If there is a thread suspended on the mailbox, + * the thread will be resumed. + * + * @note When using this function to send a mail, if the mailbox if fully used, the current thread will + * wait for a timeout. If the set timeout time is reached and there is still no space available, + * the sending thread will be resumed and an error code will be returned. + * By contrast, the rt_mb_send() function will return an error code immediately without waiting time + * when the mailbox if fully used. + * + * @see rt_mb_send() + * + * @param mb is a pointer to the mailbox object to be sent. + * + * @param value is a value to the content of the mail you want to send. + * + * @param timeout is a timeout period (unit: an OS tick). + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + * + * @warning This function can be called in interrupt context and thread context. + */ +static rt_err_t _rt_mb_send_wait(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout, + int suspend_flag) +{ + struct rt_thread *thread; + rt_base_t level; + rt_uint32_t tick_delta; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0); + + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mb->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* for non-blocking call */ + if (mb->entry == mb->size && timeout == 0) + { + rt_hw_interrupt_enable(level); + return -RT_EFULL; + } + + /* mailbox is full */ + while (mb->entry == mb->size) + { + /* reset error number in thread */ + thread->error = -RT_EINTR; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EFULL; + } + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mb->suspend_sender_thread), + thread, + mb->parent.parent.flag, + suspend_flag); + + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mb_send_wait: start timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* re-schedule */ + rt_schedule(); + + /* resume from suspend state */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + + /* set ptr */ + mb->msg_pool[mb->in_offset] = value; + /* increase input offset */ + ++ mb->in_offset; + if (mb->in_offset >= mb->size) + mb->in_offset = 0; + + if(mb->entry < RT_MB_ENTRY_MAX) + { + /* increase message entry */ + mb->entry ++; + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + + /* resume suspended thread */ + if (!rt_list_isempty(&mb->parent.suspend_thread)) + { + _ipc_list_resume(&(mb->parent.suspend_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} + +rt_err_t rt_mb_send_wait(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout) +{ + return _rt_mb_send_wait(mb, value, timeout, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mb_send_wait); + +rt_err_t rt_mb_send_wait_interruptible(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout) +{ + return _rt_mb_send_wait(mb, value, timeout, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mb_send_wait_interruptible); + +rt_err_t rt_mb_send_wait_killable(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout) +{ + return _rt_mb_send_wait(mb, value, timeout, RT_KILLABLE); +} +RTM_EXPORT(rt_mb_send_wait_killable); +/** + * @brief This function will send an mail to the mailbox object. If there is a thread suspended on the mailbox, + * the thread will be resumed. + * + * @note When using this function to send a mail, if the mailbox is fully used, this function will return an error + * code immediately without waiting time. + * By contrast, the rt_mb_send_wait() function is set a timeout to wait for the mail to be sent. + * + * @see rt_mb_send_wait() + * + * @param mb is a pointer to the mailbox object to be sent. + * + * @param value is a value to the content of the mail you want to send. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + */ +rt_err_t rt_mb_send(rt_mailbox_t mb, rt_ubase_t value) +{ + return rt_mb_send_wait(mb, value, 0); +} +RTM_EXPORT(rt_mb_send); + +rt_err_t rt_mb_send_interruptible(rt_mailbox_t mb, rt_ubase_t value) +{ + return rt_mb_send_wait_interruptible(mb, value, 0); +} +RTM_EXPORT(rt_mb_send_interruptible); + +rt_err_t rt_mb_send_killable(rt_mailbox_t mb, rt_ubase_t value) +{ + return rt_mb_send_wait_killable(mb, value, 0); +} +RTM_EXPORT(rt_mb_send_killable); + +/** + * @brief This function will send an urgent mail to the mailbox object. + * + * @note This function is almost the same as the rt_mb_send() function. The only difference is that + * when sending an urgent mail, the mail will be placed at the head of the mail queue so that + * the recipient can receive the urgent mail first. + * + * @see rt_mb_send() + * + * @param mb is a pointer to the mailbox object to be sent. + * + * @param value is the content of the mail you want to send. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + */ +rt_err_t rt_mb_urgent(rt_mailbox_t mb, rt_ubase_t value) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mb->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + if (mb->entry == mb->size) + { + rt_hw_interrupt_enable(level); + return -RT_EFULL; + } + + /* rewind to the previous position */ + if (mb->out_offset > 0) + { + mb->out_offset --; + } + else + { + mb->out_offset = mb->size - 1; + } + + /* set ptr */ + mb->msg_pool[mb->out_offset] = value; + + /* increase message entry */ + mb->entry ++; + + /* resume suspended thread */ + if (!rt_list_isempty(&mb->parent.suspend_thread)) + { + _ipc_list_resume(&(mb->parent.suspend_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} +RTM_EXPORT(rt_mb_urgent); + + +/** + * @brief This function will receive a mail from mailbox object, if there is no mail in mailbox object, + * the thread shall wait for a specified time. + * + * @note Only when there is mail in the mailbox, the receiving thread can get the mail immediately and + * return RT_EOK, otherwise the receiving thread will be suspended until the set timeout. If the mail + * is still not received within the specified time, it will return-RT_ETIMEOUT. + * + * @param mb is a pointer to the mailbox object to be received. + * + * @param value is a flag that you will set for this mailbox's flag. + * You can set an mailbox flag, or you can set multiple flags through OR logic operations. + * + * @param timeout is a timeout period (unit: an OS tick). If the mailbox object is not avaliable in the queue, + * the thread will wait for the object in the queue up to the amount of time specified by this parameter. + * + * NOTE: + * If use Macro RT_WAITING_FOREVER to set this parameter, which means that when the + * mailbox object is unavailable in the queue, the thread will be waiting forever. + * If use macro RT_WAITING_NO to set this parameter, which means that this + * function is non-blocking and will return immediately. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox release failed. + */ +static rt_err_t _rt_mb_recv(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout, int suspend_flag) +{ + struct rt_thread *thread; + rt_base_t level; + rt_uint32_t tick_delta; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0); + + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(mb->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* for non-blocking call */ + if (mb->entry == 0 && timeout == 0) + { + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + + /* mailbox is empty */ + while (mb->entry == 0) + { + /* reset error number in thread */ + thread->error = -RT_EINTR; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + thread->error = -RT_ETIMEOUT; + + return -RT_ETIMEOUT; + } + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mb->parent.suspend_thread), + thread, + mb->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mb_recv: start timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* re-schedule */ + rt_schedule(); + + /* resume from suspend state */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + + /* fill ptr */ + *value = mb->msg_pool[mb->out_offset]; + + /* increase output offset */ + ++ mb->out_offset; + if (mb->out_offset >= mb->size) + mb->out_offset = 0; + + /* decrease message entry */ + if(mb->entry > 0) + { + mb->entry --; + } + + /* resume suspended thread */ + if (!rt_list_isempty(&(mb->suspend_sender_thread))) + { + _ipc_list_resume(&(mb->suspend_sender_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mb->parent.parent))); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mb->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_mb_recv(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout) +{ + return _rt_mb_recv(mb, value, timeout, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mb_recv); + +rt_err_t rt_mb_recv_interruptibale(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout) +{ + return _rt_mb_recv(mb, value, timeout, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mb_recv_interruptibale); + +rt_err_t rt_mb_recv_killable(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout) +{ + return _rt_mb_recv(mb, value, timeout, RT_KILLABLE); +} +RTM_EXPORT(rt_mb_recv_killable); + +/** + * @brief This function will set some extra attributions of a mailbox object. + * + * @note Currently this function only supports the RT_IPC_CMD_RESET command to reset the mailbox. + * + * @param mb is a pointer to a mailbox object. + * + * @param cmd is a command used to configure some attributions of the mailbox. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_mb_control(rt_mailbox_t mb, int cmd, void *arg) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + + if (cmd == RT_IPC_CMD_RESET) + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* resume all waiting thread */ + _ipc_list_resume_all(&(mb->parent.suspend_thread)); + /* also resume all mailbox private suspended thread */ + _ipc_list_resume_all(&(mb->suspend_sender_thread)); + + /* re-init mailbox */ + mb->entry = 0; + mb->in_offset = 0; + mb->out_offset = 0; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_mb_control); + +/**@}*/ +#endif /* RT_USING_MAILBOX */ + +#ifdef RT_USING_MESSAGEQUEUE +/** + * @addtogroup messagequeue + * @{ + */ + +struct rt_mq_message +{ + struct rt_mq_message *next; +}; + + +/** + * @brief Initialize a static messagequeue object. + * + * @note For the static messagequeue object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_mq_create() function will allocate memory space automatically + * and initialize the messagequeue. + * + * @see rt_mq_create() + * + * @param mq is a pointer to the messagequeue to initialize. It is assumed that storage for + * the messagequeue will be allocated in your application. + * + * @param name is a pointer to the name that given to the messagequeue. + * + * @param msgpool is a pointer to the starting address of the memory space you allocated for + * the messagequeue in advance. + * In other words, msgpool is a pointer to the messagequeue buffer of the starting address. + * + * @param msg_size is the maximum length of a message in the messagequeue (Unit: Byte). + * + * @param pool_size is the size of the memory space allocated for the messagequeue in advance. + * + * @param flag is the messagequeue flag, which determines the queuing way of how multiple threads wait + * when the messagequeue is not available. + * The messagequeue flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this messagequeue will become non-real-time threads. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_mq_init(rt_mq_t mq, + const char *name, + void *msgpool, + rt_size_t msg_size, + rt_size_t pool_size, + rt_uint8_t flag) +{ + struct rt_mq_message *head; + rt_base_t temp; + register rt_size_t msg_align_size; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(mq->parent.parent), RT_Object_Class_MessageQueue, name); + + /* set parent flag */ + mq->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(mq->parent)); + + /* set message pool */ + mq->msg_pool = msgpool; + + /* get correct message size */ + msg_align_size = RT_ALIGN(msg_size, RT_ALIGN_SIZE); + mq->msg_size = msg_size; + mq->max_msgs = pool_size / (msg_align_size + sizeof(struct rt_mq_message)); + + if (0 == mq->max_msgs) + { + return -RT_EINVAL; + } + + /* initialize message list */ + mq->msg_queue_head = RT_NULL; + mq->msg_queue_tail = RT_NULL; + + /* initialize message empty list */ + mq->msg_queue_free = RT_NULL; + for (temp = 0; temp < mq->max_msgs; temp ++) + { + head = (struct rt_mq_message *)((rt_uint8_t *)mq->msg_pool + + temp * (msg_align_size + sizeof(struct rt_mq_message))); + head->next = (struct rt_mq_message *)mq->msg_queue_free; + mq->msg_queue_free = head; + } + + /* the initial entry is zero */ + mq->entry = 0; + + /* initialize an additional list of sender suspend thread */ + rt_list_init(&(mq->suspend_sender_thread)); + + return RT_EOK; +} +RTM_EXPORT(rt_mq_init); + + +/** + * @brief This function will detach a static messagequeue object. + * + * @note This function is used to detach a static messagequeue object which is initialized by rt_mq_init() function. + * By contrast, the rt_mq_delete() function will delete a messagequeue object. + * When the messagequeue is successfully detached, it will resume all suspended threads in the messagequeue list. + * + * @see rt_mq_delete() + * + * @param mq is a pointer to a messagequeue object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the messagequeue detach failed. + * + * @warning This function can ONLY detach a static messagequeue initialized by the rt_mq_init() function. + * If the messagequeue is created by the rt_mq_create() function, you MUST NOT USE this function to detach it, + * and ONLY USE the rt_mq_delete() function to complete the deletion. + */ +rt_err_t rt_mq_detach(rt_mq_t mq) +{ + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(rt_object_is_systemobject(&mq->parent.parent)); + + /* resume all suspended thread */ + _ipc_list_resume_all(&mq->parent.suspend_thread); + /* also resume all message queue private suspended thread */ + _ipc_list_resume_all(&(mq->suspend_sender_thread)); + + /* detach message queue object */ + rt_object_detach(&(mq->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mq_detach); + +#ifdef RT_USING_HEAP +/** + * @brief Creating a messagequeue object. + * + * @note For the messagequeue object, its memory space is allocated automatically. + * By contrast, the rt_mq_init() function will initialize a static messagequeue object. + * + * @see rt_mq_init() + * + * @param name is a pointer that given to the messagequeue. + * + * @param msg_size is the maximum length of a message in the messagequeue (Unit: Byte). + * + * @param max_msgs is the maximum number of messages in the messagequeue. + * + * @param flag is the messagequeue flag, which determines the queuing way of how multiple threads wait + * when the messagequeue is not available. + * The messagequeue flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this messagequeue will become non-real-time threads. + * + * @return Return a pointer to the messagequeue object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can NOT be called in interrupt context. You can use macor RT_DEBUG_NOT_IN_INTERRUPT to check it. + */ +rt_mq_t rt_mq_create(const char *name, + rt_size_t msg_size, + rt_size_t max_msgs, + rt_uint8_t flag) +{ + struct rt_messagequeue *mq; + struct rt_mq_message *head; + rt_base_t temp; + register rt_size_t msg_align_size; + + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + mq = (rt_mq_t)rt_object_allocate(RT_Object_Class_MessageQueue, name); + if (mq == RT_NULL) + return mq; + + /* set parent */ + mq->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(mq->parent)); + + /* initialize message queue */ + + /* get correct message size */ + msg_align_size = RT_ALIGN(msg_size, RT_ALIGN_SIZE); + mq->msg_size = msg_size; + mq->max_msgs = max_msgs; + + /* allocate message pool */ + mq->msg_pool = RT_KERNEL_MALLOC((msg_align_size + sizeof(struct rt_mq_message)) * mq->max_msgs); + if (mq->msg_pool == RT_NULL) + { + rt_object_delete(&(mq->parent.parent)); + + return RT_NULL; + } + + /* initialize message list */ + mq->msg_queue_head = RT_NULL; + mq->msg_queue_tail = RT_NULL; + + /* initialize message empty list */ + mq->msg_queue_free = RT_NULL; + for (temp = 0; temp < mq->max_msgs; temp ++) + { + head = (struct rt_mq_message *)((rt_uint8_t *)mq->msg_pool + + temp * (msg_align_size + sizeof(struct rt_mq_message))); + head->next = (struct rt_mq_message *)mq->msg_queue_free; + mq->msg_queue_free = head; + } + + /* the initial entry is zero */ + mq->entry = 0; + + /* initialize an additional list of sender suspend thread */ + rt_list_init(&(mq->suspend_sender_thread)); + + return mq; +} +RTM_EXPORT(rt_mq_create); + + +/** + * @brief This function will delete a messagequeue object and release the memory. + * + * @note This function is used to delete a messagequeue object which is created by the rt_mq_create() function. + * By contrast, the rt_mq_detach() function will detach a static messagequeue object. + * When the messagequeue is successfully deleted, it will resume all suspended threads in the messagequeue list. + * + * @see rt_mq_detach() + * + * @param mq is a pointer to a messagequeue object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the messagequeue detach failed. + * + * @warning This function can ONLY delete a messagequeue initialized by the rt_mq_create() function. + * If the messagequeue is initialized by the rt_mq_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_mq_detach() function to complete the detachment. + * for example,the rt_mq_create() function, it cannot be called in interrupt context. + */ +rt_err_t rt_mq_delete(rt_mq_t mq) +{ + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(rt_object_is_systemobject(&mq->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* resume all suspended thread */ + _ipc_list_resume_all(&(mq->parent.suspend_thread)); + /* also resume all message queue private suspended thread */ + _ipc_list_resume_all(&(mq->suspend_sender_thread)); + + /* free message queue pool */ + RT_KERNEL_FREE(mq->msg_pool); + + /* delete message queue object */ + rt_object_delete(&(mq->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mq_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will send a message to the messagequeue object. If + * there is a thread suspended on the messagequeue, the thread will be + * resumed. + * + * @note When using this function to send a message, if the messagequeue is + * fully used, the current thread will wait for a timeout. If reaching + * the timeout and there is still no space available, the sending + * thread will be resumed and an error code will be returned. By + * contrast, the rt_mq_send() function will return an error code + * immediately without waiting when the messagequeue if fully used. + * + * @see rt_mq_send() + * + * @param mq is a pointer to the messagequeue object to be sent. + * + * @param buffer is the content of the message. + * + * @param size is the length of the message(Unit: Byte). + * + * @param timeout is a timeout period (unit: an OS tick). + * + * @return Return the operation status. When the return value is RT_EOK, the + * operation is successful. If the return value is any other values, + * it means that the messagequeue detach failed. + * + * @warning This function can be called in interrupt context and thread + * context. + */ +static rt_err_t _rt_mq_send_wait(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout, + int suspend_flag) +{ + rt_base_t level; + struct rt_mq_message *msg; + rt_uint32_t tick_delta; + struct rt_thread *thread; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(buffer != RT_NULL); + RT_ASSERT(size != 0); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0); + + /* greater than one message size */ + if (size > mq->msg_size) + return -RT_ERROR; + + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mq->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* get a free list, there must be an empty item */ + msg = (struct rt_mq_message *)mq->msg_queue_free; + /* for non-blocking call */ + if (msg == RT_NULL && timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EFULL; + } + + /* message queue is full */ + while ((msg = (struct rt_mq_message *)mq->msg_queue_free) == RT_NULL) + { + /* reset error number in thread */ + thread->error = -RT_EINTR; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EFULL; + } + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mq->suspend_sender_thread), + thread, + mq->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mq_send_wait: start timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* re-schedule */ + rt_schedule(); + + /* resume from suspend state */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + + /* move free list pointer */ + mq->msg_queue_free = msg->next; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* the msg is the new tailer of list, the next shall be NULL */ + msg->next = RT_NULL; + /* copy buffer */ + rt_memcpy(msg + 1, buffer, size); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + /* link msg to message queue */ + if (mq->msg_queue_tail != RT_NULL) + { + /* if the tail exists, */ + ((struct rt_mq_message *)mq->msg_queue_tail)->next = msg; + } + + /* set new tail */ + mq->msg_queue_tail = msg; + /* if the head is empty, set head */ + if (mq->msg_queue_head == RT_NULL) + mq->msg_queue_head = msg; + + if(mq->entry < RT_MQ_ENTRY_MAX) + { + /* increase message entry */ + mq->entry ++; + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + + /* resume suspended thread */ + if (!rt_list_isempty(&mq->parent.suspend_thread)) + { + _ipc_list_resume(&(mq->parent.suspend_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} + +rt_err_t rt_mq_send_wait(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_send_wait(mq, buffer, size, timeout, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mq_send_wait) + +rt_err_t rt_mq_send_wait_interruptible(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_send_wait(mq, buffer, size, timeout, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mq_send_wait_interruptible) + +rt_err_t rt_mq_send_wait_killable(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_send_wait(mq, buffer, size, timeout, RT_KILLABLE); +} +RTM_EXPORT(rt_mq_send_wait_killable) +/** + * @brief This function will send a message to the messagequeue object. + * If there is a thread suspended on the messagequeue, the thread will be resumed. + * + * @note When using this function to send a message, if the messagequeue is fully used, + * the current thread will wait for a timeout. + * By contrast, when the messagequeue is fully used, the rt_mq_send_wait() function will + * return an error code immediately without waiting. + * + * @see rt_mq_send_wait() + * + * @param mq is a pointer to the messagequeue object to be sent. + * + * @param buffer is the content of the message. + * + * @param size is the length of the message(Unit: Byte). + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the messagequeue detach failed. + * + * @warning This function can be called in interrupt context and thread context. + */ +rt_err_t rt_mq_send(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + return rt_mq_send_wait(mq, buffer, size, 0); +} +RTM_EXPORT(rt_mq_send); + +rt_err_t rt_mq_send_interrupt(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + return rt_mq_send_wait_interruptible(mq, buffer, size, 0); +} +RTM_EXPORT(rt_mq_send_interrupt); + +rt_err_t rt_mq_send_killable(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + return rt_mq_send_wait_killable(mq, buffer, size, 0); +} +RTM_EXPORT(rt_mq_send_killable); +/** + * @brief This function will send an urgent message to the messagequeue object. + * + * @note This function is almost the same as the rt_mq_send() function. The only difference is that + * when sending an urgent message, the message is placed at the head of the messagequeue so that + * the recipient can receive the urgent message first. + * + * @see rt_mq_send() + * + * @param mq is a pointer to the messagequeue object to be sent. + * + * @param buffer is the content of the message. + * + * @param size is the length of the message(Unit: Byte). + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + */ +rt_err_t rt_mq_urgent(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + rt_base_t level; + struct rt_mq_message *msg; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(buffer != RT_NULL); + RT_ASSERT(size != 0); + + /* greater than one message size */ + if (size > mq->msg_size) + return -RT_ERROR; + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mq->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* get a free list, there must be an empty item */ + msg = (struct rt_mq_message *)mq->msg_queue_free; + /* message queue is full */ + if (msg == RT_NULL) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EFULL; + } + /* move free list pointer */ + mq->msg_queue_free = msg->next; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* copy buffer */ + rt_memcpy(msg + 1, buffer, size); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* link msg to the beginning of message queue */ + msg->next = (struct rt_mq_message *)mq->msg_queue_head; + mq->msg_queue_head = msg; + + /* if there is no tail */ + if (mq->msg_queue_tail == RT_NULL) + mq->msg_queue_tail = msg; + + if(mq->entry < RT_MQ_ENTRY_MAX) + { + /* increase message entry */ + mq->entry ++; + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + + /* resume suspended thread */ + if (!rt_list_isempty(&mq->parent.suspend_thread)) + { + _ipc_list_resume(&(mq->parent.suspend_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} +RTM_EXPORT(rt_mq_urgent); + + +/** + * @brief This function will receive a message from message queue object, + * if there is no message in messagequeue object, the thread shall wait for a specified time. + * + * @note Only when there is mail in the mailbox, the receiving thread can get the mail immediately and return RT_EOK, + * otherwise the receiving thread will be suspended until timeout. + * If the mail is not received within the specified time, it will return -RT_ETIMEOUT. + * + * @param mq is a pointer to the messagequeue object to be received. + * + * @param buffer is the content of the message. + * + * @param size is the length of the message(Unit: Byte). + * + * @param timeout is a timeout period (unit: an OS tick). If the message is unavailable, the thread will wait for + * the message in the queue up to the amount of time specified by this parameter. + * + * NOTE: + * If use Macro RT_WAITING_FOREVER to set this parameter, which means that when the + * message is unavailable in the queue, the thread will be waiting forever. + * If use macro RT_WAITING_NO to set this parameter, which means that this + * function is non-blocking and will return immediately. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox release failed. + */ +static rt_err_t _rt_mq_recv(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout, + int suspend_flag) +{ + struct rt_thread *thread; + rt_base_t level; + struct rt_mq_message *msg; + rt_uint32_t tick_delta; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(buffer != RT_NULL); + RT_ASSERT(size != 0); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0); + + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(mq->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* for non-blocking call */ + if (mq->entry == 0 && timeout == 0) + { + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + + /* message queue is empty */ + while (mq->entry == 0) + { + /* reset error number in thread */ + thread->error = -RT_EINTR; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + thread->error = -RT_ETIMEOUT; + + return -RT_ETIMEOUT; + } + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mq->parent.suspend_thread), + thread, + mq->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("set thread:%s to timer list\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* re-schedule */ + rt_schedule(); + + /* recv message */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + + /* get message from queue */ + msg = (struct rt_mq_message *)mq->msg_queue_head; + + /* move message queue head */ + mq->msg_queue_head = msg->next; + /* reach queue tail, set to NULL */ + if (mq->msg_queue_tail == msg) + mq->msg_queue_tail = RT_NULL; + + /* decrease message entry */ + if(mq->entry > 0) + { + mq->entry --; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* copy message */ + rt_memcpy(buffer, msg + 1, size > mq->msg_size ? mq->msg_size : size); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + /* put message to free list */ + msg->next = (struct rt_mq_message *)mq->msg_queue_free; + mq->msg_queue_free = msg; + + /* resume suspended thread */ + if (!rt_list_isempty(&(mq->suspend_sender_thread))) + { + _ipc_list_resume(&(mq->suspend_sender_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mq->parent.parent))); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mq->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_mq_recv(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_recv(mq, buffer, size, timeout, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mq_recv); + +rt_err_t rt_mq_recv_interruptible(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_recv(mq, buffer, size, timeout, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mq_recv_interruptible); + +rt_err_t rt_mq_recv_killable(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_recv(mq, buffer, size, timeout, RT_KILLABLE); +} +RTM_EXPORT(rt_mq_recv_killable); +/** + * @brief This function will set some extra attributions of a messagequeue object. + * + * @note Currently this function only supports the RT_IPC_CMD_RESET command to reset the messagequeue. + * + * @param mq is a pointer to a messagequeue object. + * + * @param cmd is a command used to configure some attributions of the messagequeue. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_mq_control(rt_mq_t mq, int cmd, void *arg) +{ + rt_base_t level; + struct rt_mq_message *msg; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + + if (cmd == RT_IPC_CMD_RESET) + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* resume all waiting thread */ + _ipc_list_resume_all(&mq->parent.suspend_thread); + /* also resume all message queue private suspended thread */ + _ipc_list_resume_all(&(mq->suspend_sender_thread)); + + /* release all message in the queue */ + while (mq->msg_queue_head != RT_NULL) + { + /* get message from queue */ + msg = (struct rt_mq_message *)mq->msg_queue_head; + + /* move message queue head */ + mq->msg_queue_head = msg->next; + /* reach queue tail, set to NULL */ + if (mq->msg_queue_tail == msg) + mq->msg_queue_tail = RT_NULL; + + /* put message to free list */ + msg->next = (struct rt_mq_message *)mq->msg_queue_free; + mq->msg_queue_free = msg; + } + + /* clean entry */ + mq->entry = 0; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_mq_control); + +/**@}*/ +#endif /* RT_USING_MESSAGEQUEUE */ +/**@}*/ diff --git a/tasks/concur-rtthread-mutex-ceilings/template/src/object.c b/tasks/concur-rtthread-mutex-ceilings/template/src/object.c new file mode 100644 index 00000000..04e0a035 --- /dev/null +++ b/tasks/concur-rtthread-mutex-ceilings/template/src/object.c @@ -0,0 +1,693 @@ +/* + * Copyright (c) 2006-2021, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2006-03-14 Bernard the first version + * 2006-04-21 Bernard change the scheduler lock to interrupt lock + * 2006-05-18 Bernard fix the object init bug + * 2006-08-03 Bernard add hook support + * 2007-01-28 Bernard rename RT_OBJECT_Class_Static to RT_Object_Class_Static + * 2010-10-26 yi.qiu add module support in rt_object_allocate and rt_object_free + * 2017-12-10 Bernard Add object_info enum. + * 2018-01-25 Bernard Fix the object find issue when enable MODULE. + * 2022-01-07 Gabriel Moving __on_rt_xxxxx_hook to object.c + */ + +#include +#include + +#ifdef RT_USING_MODULE +#include +#endif /* RT_USING_MODULE */ + +#ifdef RT_USING_SMART +#include +#endif + +struct rt_custom_object +{ + struct rt_object parent; + rt_err_t (*destroy)(void *); + void *data; +}; + +/* + * define object_info for the number of _object_container items. + */ +enum rt_object_info_type +{ + RT_Object_Info_Thread = 0, /**< The object is a thread. */ +#ifdef RT_USING_SEMAPHORE + RT_Object_Info_Semaphore, /**< The object is a semaphore. */ +#endif +#ifdef RT_USING_MUTEX + RT_Object_Info_Mutex, /**< The object is a mutex. */ +#endif +#ifdef RT_USING_EVENT + RT_Object_Info_Event, /**< The object is a event. */ +#endif +#ifdef RT_USING_MAILBOX + RT_Object_Info_MailBox, /**< The object is a mail box. */ +#endif +#ifdef RT_USING_MESSAGEQUEUE + RT_Object_Info_MessageQueue, /**< The object is a message queue. */ +#endif +#ifdef RT_USING_MEMHEAP + RT_Object_Info_MemHeap, /**< The object is a memory heap */ +#endif +#ifdef RT_USING_MEMPOOL + RT_Object_Info_MemPool, /**< The object is a memory pool. */ +#endif +#ifdef RT_USING_DEVICE + RT_Object_Info_Device, /**< The object is a device */ +#endif + RT_Object_Info_Timer, /**< The object is a timer. */ +#ifdef RT_USING_MODULE + RT_Object_Info_Module, /**< The object is a module. */ +#endif +#ifdef RT_USING_HEAP + RT_Object_Info_Memory, /**< The object is a memory. */ +#endif +#ifdef RT_USING_SMART + RT_Object_Info_Channel, /**< The object is a IPC channel */ +#endif +#ifdef RT_USING_HEAP + RT_Object_Info_Custom, /**< The object is a custom object */ +#endif + RT_Object_Info_Unknown, /**< The object is unknown. */ +}; + +#define _OBJ_CONTAINER_LIST_INIT(c) \ + {&(_object_container[c].object_list), &(_object_container[c].object_list)} + +static struct rt_object_information _object_container[RT_Object_Info_Unknown] = +{ + /* initialize object container - thread */ + {RT_Object_Class_Thread, _OBJ_CONTAINER_LIST_INIT(RT_Object_Info_Thread), sizeof(struct rt_thread)}, +#ifdef RT_USING_SEMAPHORE + /* initialize object container - semaphore */ + {RT_Object_Class_Semaphore, _OBJ_CONTAINER_LIST_INIT(RT_Object_Info_Semaphore), sizeof(struct rt_semaphore)}, +#endif +#ifdef RT_USING_MUTEX + /* initialize object container - mutex */ + {RT_Object_Class_Mutex, _OBJ_CONTAINER_LIST_INIT(RT_Object_Info_Mutex), sizeof(struct rt_mutex)}, +#endif +#ifdef RT_USING_EVENT + /* initialize object container - event */ + {RT_Object_Class_Event, _OBJ_CONTAINER_LIST_INIT(RT_Object_Info_Event), sizeof(struct rt_event)}, +#endif +#ifdef RT_USING_MAILBOX + /* initialize object container - mailbox */ + {RT_Object_Class_MailBox, _OBJ_CONTAINER_LIST_INIT(RT_Object_Info_MailBox), sizeof(struct rt_mailbox)}, +#endif +#ifdef RT_USING_MESSAGEQUEUE + /* initialize object container - message queue */ + {RT_Object_Class_MessageQueue, _OBJ_CONTAINER_LIST_INIT(RT_Object_Info_MessageQueue), sizeof(struct rt_messagequeue)}, +#endif +#ifdef RT_USING_MEMHEAP + /* initialize object container - memory heap */ + {RT_Object_Class_MemHeap, _OBJ_CONTAINER_LIST_INIT(RT_Object_Info_MemHeap), sizeof(struct rt_memheap)}, +#endif +#ifdef RT_USING_MEMPOOL + /* initialize object container - memory pool */ + {RT_Object_Class_MemPool, _OBJ_CONTAINER_LIST_INIT(RT_Object_Info_MemPool), sizeof(struct rt_mempool)}, +#endif +#ifdef RT_USING_DEVICE + /* initialize object container - device */ + {RT_Object_Class_Device, _OBJ_CONTAINER_LIST_INIT(RT_Object_Info_Device), sizeof(struct rt_device)}, +#endif + /* initialize object container - timer */ + {RT_Object_Class_Timer, _OBJ_CONTAINER_LIST_INIT(RT_Object_Info_Timer), sizeof(struct rt_timer)}, +#ifdef RT_USING_MODULE + /* initialize object container - module */ + {RT_Object_Class_Module, _OBJ_CONTAINER_LIST_INIT(RT_Object_Info_Module), sizeof(struct rt_dlmodule)}, +#endif +#ifdef RT_USING_HEAP + /* initialize object container - small memory */ + {RT_Object_Class_Memory, _OBJ_CONTAINER_LIST_INIT(RT_Object_Info_Memory), sizeof(struct rt_memory)}, +#endif +#ifdef RT_USING_SMART + /* initialize object container - module */ + {RT_Object_Class_Channel, _OBJ_CONTAINER_LIST_INIT(RT_Object_Info_Channel), sizeof(struct rt_channel)}, + {RT_Object_Class_Custom, _OBJ_CONTAINER_LIST_INIT(RT_Object_Info_Custom), sizeof(struct rt_custom_object)}, +#endif +}; + +#ifndef __on_rt_object_attach_hook + #define __on_rt_object_attach_hook(obj) __ON_HOOK_ARGS(rt_object_attach_hook, (obj)) +#endif +#ifndef __on_rt_object_detach_hook + #define __on_rt_object_detach_hook(obj) __ON_HOOK_ARGS(rt_object_detach_hook, (obj)) +#endif +#ifndef __on_rt_object_trytake_hook + #define __on_rt_object_trytake_hook(parent) __ON_HOOK_ARGS(rt_object_trytake_hook, (parent)) +#endif +#ifndef __on_rt_object_take_hook + #define __on_rt_object_take_hook(parent) __ON_HOOK_ARGS(rt_object_take_hook, (parent)) +#endif +#ifndef __on_rt_object_put_hook + #define __on_rt_object_put_hook(parent) __ON_HOOK_ARGS(rt_object_put_hook, (parent)) +#endif + +#if defined(RT_USING_HOOK) && defined(RT_HOOK_USING_FUNC_PTR) +static void (*rt_object_attach_hook)(struct rt_object *object); +static void (*rt_object_detach_hook)(struct rt_object *object); +void (*rt_object_trytake_hook)(struct rt_object *object); +void (*rt_object_take_hook)(struct rt_object *object); +void (*rt_object_put_hook)(struct rt_object *object); + +/** + * @addtogroup Hook + */ + +/**@{*/ + +/** + * @brief This function will set a hook function, which will be invoked when object + * attaches to kernel object system. + * + * @param hook is the hook function. + */ +void rt_object_attach_sethook(void (*hook)(struct rt_object *object)) +{ + rt_object_attach_hook = hook; +} + +/** + * @brief This function will set a hook function, which will be invoked when object + * detaches from kernel object system. + * + * @param hook is the hook function + */ +void rt_object_detach_sethook(void (*hook)(struct rt_object *object)) +{ + rt_object_detach_hook = hook; +} + +/** + * @brief This function will set a hook function, which will be invoked when object + * is taken from kernel object system. + * + * The object is taken means: + * semaphore - semaphore is taken by thread + * mutex - mutex is taken by thread + * event - event is received by thread + * mailbox - mail is received by thread + * message queue - message is received by thread + * + * @param hook is the hook function. + */ +void rt_object_trytake_sethook(void (*hook)(struct rt_object *object)) +{ + rt_object_trytake_hook = hook; +} + +/** + * @brief This function will set a hook function, which will be invoked when object + * have been taken from kernel object system. + * + * The object have been taken means: + * semaphore - semaphore have been taken by thread + * mutex - mutex have been taken by thread + * event - event have been received by thread + * mailbox - mail have been received by thread + * message queue - message have been received by thread + * timer - timer is started + * + * @param hook the hook function. + */ +void rt_object_take_sethook(void (*hook)(struct rt_object *object)) +{ + rt_object_take_hook = hook; +} + +/** + * @brief This function will set a hook function, which will be invoked when object + * is put to kernel object system. + * + * @param hook is the hook function + */ +void rt_object_put_sethook(void (*hook)(struct rt_object *object)) +{ + rt_object_put_hook = hook; +} + +/**@}*/ +#endif /* RT_USING_HOOK */ + +/** + * @addtogroup KernelObject + */ + +/**@{*/ + +/** + * @brief This function will return the specified type of object information. + * + * @param type is the type of object, which can be + * RT_Object_Class_Thread/Semaphore/Mutex... etc + * + * @return the object type information or RT_NULL + */ +struct rt_object_information * +rt_object_get_information(enum rt_object_class_type type) +{ + int index; + + for (index = 0; index < RT_Object_Info_Unknown; index ++) + if (_object_container[index].type == type) return &_object_container[index]; + + return RT_NULL; +} +RTM_EXPORT(rt_object_get_information); + +/** + * @brief This function will return the length of object list in object container. + * + * @param type is the type of object, which can be + * RT_Object_Class_Thread/Semaphore/Mutex... etc + * + * @return the length of object list + */ +int rt_object_get_length(enum rt_object_class_type type) +{ + int count = 0; + rt_base_t level; + struct rt_list_node *node = RT_NULL; + struct rt_object_information *information = RT_NULL; + + information = rt_object_get_information((enum rt_object_class_type)type); + if (information == RT_NULL) return 0; + + level = rt_hw_interrupt_disable(); + /* get the count of objects */ + rt_list_for_each(node, &(information->object_list)) + { + count ++; + } + rt_hw_interrupt_enable(level); + + return count; +} +RTM_EXPORT(rt_object_get_length); + +/** + * @brief This function will copy the object pointer of the specified type, + * with the maximum size specified by maxlen. + * + * @param type is the type of object, which can be + * RT_Object_Class_Thread/Semaphore/Mutex... etc + * + * @param pointers is the pointer will be saved to. + * + * @param maxlen is the maximum number of pointers can be saved. + * + * @return the copied number of object pointers. + */ +int rt_object_get_pointers(enum rt_object_class_type type, rt_object_t *pointers, int maxlen) +{ + int index = 0; + rt_base_t level; + + struct rt_object *object; + struct rt_list_node *node = RT_NULL; + struct rt_object_information *information = RT_NULL; + + if (maxlen <= 0) return 0; + + information = rt_object_get_information((enum rt_object_class_type)type); + if (information == RT_NULL) return 0; + + level = rt_hw_interrupt_disable(); + /* retrieve pointer of object */ + rt_list_for_each(node, &(information->object_list)) + { + object = rt_list_entry(node, struct rt_object, list); + + pointers[index] = object; + index ++; + + if (index >= maxlen) break; + } + rt_hw_interrupt_enable(level); + + return index; +} +RTM_EXPORT(rt_object_get_pointers); + +/** + * @brief This function will initialize an object and add it to object system + * management. + * + * @param object is the specified object to be initialized. + * + * @param type is the object type. + * + * @param name is the object name. In system, the object's name must be unique. + */ +void rt_object_init(struct rt_object *object, + enum rt_object_class_type type, + const char *name) +{ + rt_base_t level; +#ifdef RT_DEBUG + struct rt_list_node *node = RT_NULL; +#endif + struct rt_object_information *information; +#ifdef RT_USING_MODULE + struct rt_dlmodule *module = dlmodule_self(); +#endif /* RT_USING_MODULE */ + + /* get object information */ + information = rt_object_get_information(type); + RT_ASSERT(information != RT_NULL); + +#ifdef RT_DEBUG + /* check object type to avoid re-initialization */ + + /* enter critical */ + rt_enter_critical(); + /* try to find object */ + for (node = information->object_list.next; + node != &(information->object_list); + node = node->next) + { + struct rt_object *obj; + + obj = rt_list_entry(node, struct rt_object, list); + RT_ASSERT(obj != object); + } + /* leave critical */ + rt_exit_critical(); +#endif + + /* initialize object's parameters */ + /* set object type to static */ + object->type = type | RT_Object_Class_Static; +#if RT_NAME_MAX > 0 + rt_strncpy(object->name, name, RT_NAME_MAX); /* copy name */ +#else + object->name = name; +#endif /* RT_NAME_MAX > 0 */ + + RT_OBJECT_HOOK_CALL(rt_object_attach_hook, (object)); + + /* lock interrupt */ + level = rt_hw_interrupt_disable(); + +#ifdef RT_USING_MODULE + if (module) + { + rt_list_insert_after(&(module->object_list), &(object->list)); + object->module_id = (void *)module; + } + else +#endif /* RT_USING_MODULE */ + { + /* insert object into information object list */ + rt_list_insert_after(&(information->object_list), &(object->list)); + } + + /* unlock interrupt */ + rt_hw_interrupt_enable(level); +} + +/** + * @brief This function will detach a static object from object system, + * and the memory of static object is not freed. + * + * @param object the specified object to be detached. + */ +void rt_object_detach(rt_object_t object) +{ + rt_base_t level; + + /* object check */ + RT_ASSERT(object != RT_NULL); + + RT_OBJECT_HOOK_CALL(rt_object_detach_hook, (object)); + + /* reset object type */ + object->type = 0; + + /* lock interrupt */ + level = rt_hw_interrupt_disable(); + + /* remove from old list */ + rt_list_remove(&(object->list)); + + /* unlock interrupt */ + rt_hw_interrupt_enable(level); +} + +#ifdef RT_USING_HEAP +/** + * @brief This function will allocate an object from object system. + * + * @param type is the type of object. + * + * @param name is the object name. In system, the object's name must be unique. + * + * @return object + */ +rt_object_t rt_object_allocate(enum rt_object_class_type type, const char *name) +{ + struct rt_object *object; + rt_base_t level; + struct rt_object_information *information; +#ifdef RT_USING_MODULE + struct rt_dlmodule *module = dlmodule_self(); +#endif /* RT_USING_MODULE */ + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* get object information */ + information = rt_object_get_information(type); + RT_ASSERT(information != RT_NULL); + + object = (struct rt_object *)RT_KERNEL_MALLOC(information->object_size); + if (object == RT_NULL) + { + /* no memory can be allocated */ + return RT_NULL; + } + + /* clean memory data of object */ + rt_memset(object, 0x0, information->object_size); + + /* initialize object's parameters */ + + /* set object type */ + object->type = type; + + /* set object flag */ + object->flag = 0; + +#if RT_NAME_MAX > 0 + rt_strncpy(object->name, name, RT_NAME_MAX); /* copy name */ +#else + object->name = name; +#endif /* RT_NAME_MAX > 0 */ + + RT_OBJECT_HOOK_CALL(rt_object_attach_hook, (object)); + + /* lock interrupt */ + level = rt_hw_interrupt_disable(); + +#ifdef RT_USING_MODULE + if (module) + { + rt_list_insert_after(&(module->object_list), &(object->list)); + object->module_id = (void *)module; + } + else +#endif /* RT_USING_MODULE */ + { + /* insert object into information object list */ + rt_list_insert_after(&(information->object_list), &(object->list)); + } + + /* unlock interrupt */ + rt_hw_interrupt_enable(level); + + /* return object */ + return object; +} + +/** + * @brief This function will delete an object and release object memory. + * + * @param object is the specified object to be deleted. + */ +void rt_object_delete(rt_object_t object) +{ + rt_base_t level; + + /* object check */ + RT_ASSERT(object != RT_NULL); + RT_ASSERT(!(object->type & RT_Object_Class_Static)); + + RT_OBJECT_HOOK_CALL(rt_object_detach_hook, (object)); + + /* reset object type */ + object->type = RT_Object_Class_Null; + + /* lock interrupt */ + level = rt_hw_interrupt_disable(); + + /* remove from old list */ + rt_list_remove(&(object->list)); + + /* unlock interrupt */ + rt_hw_interrupt_enable(level); + + /* free the memory of object */ + RT_KERNEL_FREE(object); +} +#endif /* RT_USING_HEAP */ + +/** + * @brief This function will judge the object is system object or not. + * + * @note Normally, the system object is a static object and the type + * of object set to RT_Object_Class_Static. + * + * @param object is the specified object to be judged. + * + * @return RT_TRUE if a system object, RT_FALSE for others. + */ +rt_bool_t rt_object_is_systemobject(rt_object_t object) +{ + /* object check */ + RT_ASSERT(object != RT_NULL); + + if (object->type & RT_Object_Class_Static) + return RT_TRUE; + + return RT_FALSE; +} + +/** + * @brief This function will return the type of object without + * RT_Object_Class_Static flag. + * + * @param object is the specified object to be get type. + * + * @return the type of object. + */ +rt_uint8_t rt_object_get_type(rt_object_t object) +{ + /* object check */ + RT_ASSERT(object != RT_NULL); + + return object->type & ~RT_Object_Class_Static; +} + +/** + * @brief This function will find specified name object from object + * container. + * + * @param name is the specified name of object. + * + * @param type is the type of object + * + * @return the found object or RT_NULL if there is no this object + * in object container. + * + * @note this function shall not be invoked in interrupt status. + */ +rt_object_t rt_object_find(const char *name, rt_uint8_t type) +{ + struct rt_object *object = RT_NULL; + struct rt_list_node *node = RT_NULL; + struct rt_object_information *information = RT_NULL; + + information = rt_object_get_information((enum rt_object_class_type)type); + + /* parameter check */ + if ((name == RT_NULL) || (information == RT_NULL)) return RT_NULL; + + /* which is invoke in interrupt status */ + RT_DEBUG_NOT_IN_INTERRUPT; + + /* enter critical */ + rt_enter_critical(); + + /* try to find object */ + rt_list_for_each(node, &(information->object_list)) + { + object = rt_list_entry(node, struct rt_object, list); + if (rt_strncmp(object->name, name, RT_NAME_MAX) == 0) + { + /* leave critical */ + rt_exit_critical(); + + return object; + } + } + + /* leave critical */ + rt_exit_critical(); + + return RT_NULL; +} + +#ifdef RT_USING_HEAP +/** + * This function will create a custom object + * container. + * + * @param name the specified name of object. + * @param data the custom data + * @param data_destroy the custom object destroy callback + * + * @return the found object or RT_NULL if there is no this object + * in object container. + * + * @note this function shall not be invoked in interrupt status. + */ + +rt_object_t rt_custom_object_create(const char *name, void *data, rt_err_t (*data_destroy)(void *)) +{ + struct rt_custom_object *cobj = RT_NULL; + + cobj = (struct rt_custom_object *)rt_object_allocate(RT_Object_Class_Custom, name); + if (!cobj) + { + return RT_NULL; + } + cobj->destroy = data_destroy; + cobj->data = data; + return (struct rt_object *)cobj; +} + +/** + * This function will destroy a custom object + * container. + * + * @param obj the specified name of object. + * + * @note this function shall not be invoked in interrupt status. + */ +rt_err_t rt_custom_object_destroy(rt_object_t obj) +{ + rt_err_t ret = -1; + + struct rt_custom_object *cobj = (struct rt_custom_object *)obj; + + if (obj && obj->type == RT_Object_Class_Custom) + { + if (cobj->destroy) + { + ret = cobj->destroy(cobj->data); + } + rt_object_delete(obj); + } + return ret; +} +#endif + +/**@}*/ diff --git a/tasks/concur-rtthread-mutex-ceilings/template/src/thread.c b/tasks/concur-rtthread-mutex-ceilings/template/src/thread.c new file mode 100644 index 00000000..5614edea --- /dev/null +++ b/tasks/concur-rtthread-mutex-ceilings/template/src/thread.c @@ -0,0 +1,1145 @@ +/* + * Copyright (c) 2006-2022, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2006-03-28 Bernard first version + * 2006-04-29 Bernard implement thread timer + * 2006-04-30 Bernard added THREAD_DEBUG + * 2006-05-27 Bernard fixed the rt_thread_yield bug + * 2006-06-03 Bernard fixed the thread timer init bug + * 2006-08-10 Bernard fixed the timer bug in thread_sleep + * 2006-09-03 Bernard changed rt_timer_delete to rt_timer_detach + * 2006-09-03 Bernard implement rt_thread_detach + * 2008-02-16 Bernard fixed the rt_thread_timeout bug + * 2010-03-21 Bernard change the errno of rt_thread_delay/sleep to + * RT_EOK. + * 2010-11-10 Bernard add cleanup callback function in thread exit. + * 2011-09-01 Bernard fixed rt_thread_exit issue when the current + * thread preempted, which reported by Jiaxing Lee. + * 2011-09-08 Bernard fixed the scheduling issue in rt_thread_startup. + * 2012-12-29 Bernard fixed compiling warning. + * 2016-08-09 ArdaFu add thread suspend and resume hook. + * 2017-04-10 armink fixed the rt_thread_delete and rt_thread_detach + * bug when thread has not startup. + * 2018-11-22 Jesven yield is same to rt_schedule + * add support for tasks bound to cpu + * 2021-02-24 Meco Man rearrange rt_thread_control() - schedule the thread when close it + * 2021-11-15 THEWON Remove duplicate work between idle and _thread_exit + * 2021-12-27 Meco Man remove .init_priority + * 2022-01-07 Gabriel Moving __on_rt_xxxxx_hook to thread.c + * 2022-01-24 THEWON let rt_thread_sleep return thread->error when using signal + * 2022-10-15 Bernard add nested mutex feature + */ + +#include +#include +#include + +#ifndef __on_rt_thread_inited_hook + #define __on_rt_thread_inited_hook(thread) __ON_HOOK_ARGS(rt_thread_inited_hook, (thread)) +#endif +#ifndef __on_rt_thread_suspend_hook + #define __on_rt_thread_suspend_hook(thread) __ON_HOOK_ARGS(rt_thread_suspend_hook, (thread)) +#endif +#ifndef __on_rt_thread_resume_hook + #define __on_rt_thread_resume_hook(thread) __ON_HOOK_ARGS(rt_thread_resume_hook, (thread)) +#endif + +#if defined(RT_USING_HOOK) && defined(RT_HOOK_USING_FUNC_PTR) +static void (*rt_thread_suspend_hook)(rt_thread_t thread); +static void (*rt_thread_resume_hook) (rt_thread_t thread); +static void (*rt_thread_inited_hook) (rt_thread_t thread); + +/** + * @brief This function sets a hook function when the system suspend a thread. + * + * @note The hook function must be simple and never be blocked or suspend. + * + * @param hook is the specified hook function. + */ +void rt_thread_suspend_sethook(void (*hook)(rt_thread_t thread)) +{ + rt_thread_suspend_hook = hook; +} + +/** + * @brief This function sets a hook function when the system resume a thread. + * + * @note The hook function must be simple and never be blocked or suspend. + * + * @param hook is the specified hook function. + */ +void rt_thread_resume_sethook(void (*hook)(rt_thread_t thread)) +{ + rt_thread_resume_hook = hook; +} + +/** + * @brief This function sets a hook function when a thread is initialized. + * + * @param hook is the specified hook function. + */ +void rt_thread_inited_sethook(void (*hook)(rt_thread_t thread)) +{ + rt_thread_inited_hook = hook; +} +#endif /* defined(RT_USING_HOOK) && defined(RT_HOOK_USING_FUNC_PTR) */ + +static void _thread_exit(void) +{ + struct rt_thread *thread; + rt_base_t level; + + /* get current thread */ + thread = rt_thread_self(); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* remove from schedule */ + rt_schedule_remove_thread(thread); + + /* remove it from timer list */ + rt_timer_detach(&thread->thread_timer); + + /* change stat */ + thread->stat = RT_THREAD_CLOSE; + + /* insert to defunct thread list */ + rt_thread_defunct_enqueue(thread); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* switch to next task */ + rt_schedule(); +} + +/** + * @brief This function is the timeout function for thread, normally which is invoked + * when thread is timeout to wait some resource. + * + * @param parameter is the parameter of thread timeout function + */ +static void _thread_timeout(void *parameter) +{ + struct rt_thread *thread; + rt_base_t level; + + thread = (struct rt_thread *)parameter; + + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT((thread->stat & RT_THREAD_SUSPEND_MASK) == RT_THREAD_SUSPEND_MASK); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* set error number */ + thread->error = -RT_ETIMEOUT; + + /* remove from suspend list */ + rt_list_remove(&(thread->tlist)); + + /* insert to schedule ready list */ + rt_schedule_insert_thread(thread); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do schedule */ + rt_schedule(); +} + +static rt_err_t _thread_init(struct rt_thread *thread, + const char *name, + void (*entry)(void *parameter), + void *parameter, + void *stack_start, + rt_uint32_t stack_size, + rt_uint8_t priority, + rt_uint32_t tick) +{ + /* init thread list */ + rt_list_init(&(thread->tlist)); + +#ifdef RT_USING_SMART + thread->wakeup.func = RT_NULL; +#endif + + thread->entry = (void *)entry; + thread->parameter = parameter; + + /* stack init */ + thread->stack_addr = stack_start; + thread->stack_size = stack_size; + + /* init thread stack */ + rt_memset(thread->stack_addr, '#', thread->stack_size); +#ifdef ARCH_CPU_STACK_GROWS_UPWARD + thread->sp = (void *)rt_hw_stack_init(thread->entry, thread->parameter, + (void *)((char *)thread->stack_addr), + (void *)_thread_exit); +#else + thread->sp = (void *)rt_hw_stack_init(thread->entry, thread->parameter, + (rt_uint8_t *)((char *)thread->stack_addr + thread->stack_size - sizeof(rt_ubase_t)), + (void *)_thread_exit); +#endif /* ARCH_CPU_STACK_GROWS_UPWARD */ + + /* priority init */ + RT_ASSERT(priority < RT_THREAD_PRIORITY_MAX); + thread->init_priority = priority; + thread->current_priority = priority; + + thread->number_mask = 0; + +#ifdef RT_USING_MUTEX + rt_list_init(&thread->taken_object_list); + thread->pending_object = RT_NULL; +#endif + +#ifdef RT_USING_EVENT + thread->event_set = 0; + thread->event_info = 0; +#endif /* RT_USING_EVENT */ + +#if RT_THREAD_PRIORITY_MAX > 32 + thread->number = 0; + thread->high_mask = 0; +#endif /* RT_THREAD_PRIORITY_MAX > 32 */ + + /* tick init */ + thread->init_tick = tick; + thread->remaining_tick = tick; + + /* error and flags */ + thread->error = RT_EOK; + thread->stat = RT_THREAD_INIT; + +#ifdef RT_USING_SMP + /* not bind on any cpu */ + thread->bind_cpu = RT_CPUS_NR; + thread->oncpu = RT_CPU_DETACHED; + + /* lock init */ + thread->scheduler_lock_nest = 0; + thread->cpus_lock_nest = 0; + thread->critical_lock_nest = 0; +#endif /* RT_USING_SMP */ + + /* initialize cleanup function and user data */ + thread->cleanup = 0; + thread->user_data = 0; + + /* initialize thread timer */ + rt_timer_init(&(thread->thread_timer), + thread->name, + _thread_timeout, + thread, + 0, + RT_TIMER_FLAG_ONE_SHOT); + + /* initialize signal */ +#ifdef RT_USING_SIGNALS + thread->sig_mask = 0x00; + thread->sig_pending = 0x00; + +#ifndef RT_USING_SMP + thread->sig_ret = RT_NULL; +#endif /* RT_USING_SMP */ + thread->sig_vectors = RT_NULL; + thread->si_list = RT_NULL; +#endif /* RT_USING_SIGNALS */ + +#ifdef RT_USING_SMART + thread->lwp = RT_NULL; + rt_list_init(&(thread->sibling)); + rt_memset(&thread->signal, 0, sizeof(lwp_sigset_t)); + rt_memset(&thread->signal_mask, 0, sizeof(lwp_sigset_t)); + thread->signal_mask_bak = 0; + thread->signal_in_process = 0; + rt_memset(&thread->user_ctx, 0, sizeof thread->user_ctx); +#endif + +#ifdef RT_USING_CPU_USAGE + thread->duration_tick = 0; +#endif /* RT_USING_CPU_USAGE */ + +#ifdef RT_USING_PTHREADS + thread->pthread_data = RT_NULL; +#endif /* RT_USING_PTHREADS */ + +#ifdef RT_USING_MODULE + thread->module_id = 0; +#endif /* RT_USING_MODULE */ + + RT_OBJECT_HOOK_CALL(rt_thread_inited_hook, (thread)); + + return RT_EOK; +} + +/** + * @addtogroup Thread + */ + +/**@{*/ + +/** + * @brief This function will initialize a thread. It's used to initialize a + * static thread object. + * + * @param thread is the static thread object. + * + * @param name is the name of thread, which shall be unique. + * + * @param entry is the entry function of thread. + * + * @param parameter is the parameter of thread enter function. + * + * @param stack_start is the start address of thread stack. + * + * @param stack_size is the size of thread stack. + * + * @param priority is the priority of thread. + * + * @param tick is the time slice if there are same priority thread. + * + * @return Return the operation status. If the return value is RT_EOK, the function is successfully executed. + * If the return value is any other values, it means this operation failed. + */ +rt_err_t rt_thread_init(struct rt_thread *thread, + const char *name, + void (*entry)(void *parameter), + void *parameter, + void *stack_start, + rt_uint32_t stack_size, + rt_uint8_t priority, + rt_uint32_t tick) +{ + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(stack_start != RT_NULL); + + /* initialize thread object */ + rt_object_init((rt_object_t)thread, RT_Object_Class_Thread, name); + + return _thread_init(thread, + name, + entry, + parameter, + stack_start, + stack_size, + priority, + tick); +} +RTM_EXPORT(rt_thread_init); + +/** + * @brief This function will return self thread object. + * + * @return The self thread object. + */ +rt_thread_t rt_thread_self(void) +{ +#ifdef RT_USING_SMP + rt_base_t lock; + rt_thread_t self; + + lock = rt_hw_local_irq_disable(); + self = rt_cpu_self()->current_thread; + rt_hw_local_irq_enable(lock); + return self; +#else + extern rt_thread_t rt_current_thread; + + return rt_current_thread; +#endif /* RT_USING_SMP */ +} +RTM_EXPORT(rt_thread_self); + +/** + * @brief This function will start a thread and put it to system ready queue. + * + * @param thread is the thread to be started. + * + * @return Return the operation status. If the return value is RT_EOK, the function is successfully executed. + * If the return value is any other values, it means this operation failed. + */ +rt_err_t rt_thread_startup(rt_thread_t thread) +{ + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT((thread->stat & RT_THREAD_STAT_MASK) == RT_THREAD_INIT); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + + /* calculate priority attribute */ +#if RT_THREAD_PRIORITY_MAX > 32 + thread->number = thread->current_priority >> 3; /* 5bit */ + thread->number_mask = 1L << thread->number; + thread->high_mask = 1L << (thread->current_priority & 0x07); /* 3bit */ +#else + thread->number_mask = 1L << thread->current_priority; +#endif /* RT_THREAD_PRIORITY_MAX > 32 */ + + RT_DEBUG_LOG(RT_DEBUG_THREAD, ("startup a thread:%s with priority:%d\n", + thread->name, thread->current_priority)); + /* change thread stat */ + thread->stat = RT_THREAD_SUSPEND; + /* then resume it */ + rt_thread_resume(thread); + if (rt_thread_self() != RT_NULL) + { + /* do a scheduling */ + rt_schedule(); + } + + return RT_EOK; +} +RTM_EXPORT(rt_thread_startup); + +/** + * @brief This function will detach a thread. The thread object will be removed from + * thread queue and detached/deleted from the system object management. + * + * @param thread is the thread to be deleted. + * + * @return Return the operation status. If the return value is RT_EOK, the function is successfully executed. + * If the return value is any other values, it means this operation failed. + */ +rt_err_t rt_thread_detach(rt_thread_t thread) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + RT_ASSERT(rt_object_is_systemobject((rt_object_t)thread)); + + if ((thread->stat & RT_THREAD_STAT_MASK) == RT_THREAD_CLOSE) + return RT_EOK; + + if ((thread->stat & RT_THREAD_STAT_MASK) != RT_THREAD_INIT) + { + /* remove from schedule */ + rt_schedule_remove_thread(thread); + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* release thread timer */ + rt_timer_detach(&(thread->thread_timer)); + + /* change stat */ + thread->stat = RT_THREAD_CLOSE; + +#ifdef RT_USING_MUTEX + if ((thread->pending_object) && + (rt_object_get_type(thread->pending_object) == RT_Object_Class_Mutex)) + { + struct rt_mutex *mutex = (struct rt_mutex*)thread->pending_object; + rt_mutex_drop_thread(mutex, thread); + thread->pending_object = RT_NULL; + } +#endif + + /* insert to defunct thread list */ + rt_thread_defunct_enqueue(thread); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} +RTM_EXPORT(rt_thread_detach); + +#ifdef RT_USING_HEAP +/** + * @brief This function will create a thread object and allocate thread object memory. + * and stack. + * + * @param name is the name of thread, which shall be unique. + * + * @param entry is the entry function of thread. + * + * @param parameter is the parameter of thread enter function. + * + * @param stack_size is the size of thread stack. + * + * @param priority is the priority of thread. + * + * @param tick is the time slice if there are same priority thread. + * + * @return If the return value is a rt_thread structure pointer, the function is successfully executed. + * If the return value is RT_NULL, it means this operation failed. + */ +rt_thread_t rt_thread_create(const char *name, + void (*entry)(void *parameter), + void *parameter, + rt_uint32_t stack_size, + rt_uint8_t priority, + rt_uint32_t tick) +{ + struct rt_thread *thread; + void *stack_start; + + thread = (struct rt_thread *)rt_object_allocate(RT_Object_Class_Thread, + name); + if (thread == RT_NULL) + return RT_NULL; + + stack_start = (void *)RT_KERNEL_MALLOC(stack_size); + if (stack_start == RT_NULL) + { + /* allocate stack failure */ + rt_object_delete((rt_object_t)thread); + + return RT_NULL; + } + + _thread_init(thread, + name, + entry, + parameter, + stack_start, + stack_size, + priority, + tick); + + return thread; +} +RTM_EXPORT(rt_thread_create); + +/** + * @brief This function will delete a thread. The thread object will be removed from + * thread queue and deleted from system object management in the idle thread. + * + * @param thread is the thread to be deleted. + * + * @return Return the operation status. If the return value is RT_EOK, the function is successfully executed. + * If the return value is any other values, it means this operation failed. + */ +rt_err_t rt_thread_delete(rt_thread_t thread) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + RT_ASSERT(rt_object_is_systemobject((rt_object_t)thread) == RT_FALSE); + + if ((thread->stat & RT_THREAD_STAT_MASK) == RT_THREAD_CLOSE) + return RT_EOK; + + if ((thread->stat & RT_THREAD_STAT_MASK) != RT_THREAD_INIT) + { + /* remove from schedule */ + rt_schedule_remove_thread(thread); + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* release thread timer */ + rt_timer_detach(&(thread->thread_timer)); + + /* change stat */ + thread->stat = RT_THREAD_CLOSE; + +#ifdef RT_USING_MUTEX + if ((thread->pending_object) && + (rt_object_get_type(thread->pending_object) == RT_Object_Class_Mutex)) + { + struct rt_mutex *mutex = (struct rt_mutex*)thread->pending_object; + rt_mutex_drop_thread(mutex, thread); + thread->pending_object = RT_NULL; + } +#endif + + /* insert to defunct thread list */ + rt_thread_defunct_enqueue(thread); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} +RTM_EXPORT(rt_thread_delete); +#endif /* RT_USING_HEAP */ + +/** + * @brief This function will let current thread yield processor, and scheduler will + * choose the highest thread to run. After yield processor, the current thread + * is still in READY state. + * + * @return Return the operation status. If the return value is RT_EOK, the function is successfully executed. + * If the return value is any other values, it means this operation failed. + */ +rt_err_t rt_thread_yield(void) +{ + struct rt_thread *thread; + rt_base_t level; + + thread = rt_thread_self(); + level = rt_hw_interrupt_disable(); + thread->remaining_tick = thread->init_tick; + thread->stat |= RT_THREAD_STAT_YIELD; + rt_schedule(); + rt_hw_interrupt_enable(level); + + return RT_EOK; +} +RTM_EXPORT(rt_thread_yield); + +/** + * @brief This function will let current thread sleep for some ticks. Change current thread state to suspend, + * when the thread timer reaches the tick value, scheduler will awaken this thread. + * + * @param tick is the sleep ticks. + * + * @return Return the operation status. If the return value is RT_EOK, the function is successfully executed. + * If the return value is any other values, it means this operation failed. + */ +rt_err_t rt_thread_sleep(rt_tick_t tick) +{ + rt_base_t level; + struct rt_thread *thread; + int err; + + if (tick == 0) + { + return -RT_EINVAL; + } + + /* set to current thread */ + thread = rt_thread_self(); + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* reset thread error */ + thread->error = RT_EOK; + + /* suspend thread */ + err = rt_thread_suspend_with_flag(thread, RT_INTERRUPTIBLE); + + /* reset the timeout of thread timer and start it */ + if (err == RT_EOK) + { + rt_timer_control(&(thread->thread_timer), RT_TIMER_CTRL_SET_TIME, &tick); + rt_timer_start(&(thread->thread_timer)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + thread->error = -RT_EINTR; + + rt_schedule(); + + /* clear error number of this thread to RT_EOK */ + if (thread->error == -RT_ETIMEOUT) + thread->error = RT_EOK; + } + else + { + rt_hw_interrupt_enable(level); + } + + return err; +} + +/** + * @brief This function will let current thread delay for some ticks. + * + * @param tick is the delay ticks. + * + * @return Return the operation status. If the return value is RT_EOK, the function is successfully executed. + * If the return value is any other values, it means this operation failed. + */ +rt_err_t rt_thread_delay(rt_tick_t tick) +{ + return rt_thread_sleep(tick); +} +RTM_EXPORT(rt_thread_delay); + +/** + * @brief This function will let current thread delay until (*tick + inc_tick). + * + * @param tick is the tick of last wakeup. + * + * @param inc_tick is the increment tick. + * + * @return Return the operation status. If the return value is RT_EOK, the function is successfully executed. + * If the return value is any other values, it means this operation failed. + */ +rt_err_t rt_thread_delay_until(rt_tick_t *tick, rt_tick_t inc_tick) +{ + rt_base_t level; + struct rt_thread *thread; + rt_tick_t cur_tick; + + RT_ASSERT(tick != RT_NULL); + + /* set to current thread */ + thread = rt_thread_self(); + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* reset thread error */ + thread->error = RT_EOK; + + cur_tick = rt_tick_get(); + if (cur_tick - *tick < inc_tick) + { + rt_tick_t left_tick; + + *tick += inc_tick; + left_tick = *tick - cur_tick; + + /* suspend thread */ + rt_thread_suspend_with_flag(thread, RT_UNINTERRUPTIBLE); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), RT_TIMER_CTRL_SET_TIME, &left_tick); + rt_timer_start(&(thread->thread_timer)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + /* clear error number of this thread to RT_EOK */ + if (thread->error == -RT_ETIMEOUT) + { + thread->error = RT_EOK; + } + } + else + { + *tick = cur_tick; + rt_hw_interrupt_enable(level); + } + + return thread->error; +} +RTM_EXPORT(rt_thread_delay_until); + +/** + * @brief This function will let current thread delay for some milliseconds. + * + * @param ms is the delay ms time. + * + * @return Return the operation status. If the return value is RT_EOK, the function is successfully executed. + * If the return value is any other values, it means this operation failed. + */ +rt_err_t rt_thread_mdelay(rt_int32_t ms) +{ + rt_tick_t tick; + + tick = rt_tick_from_millisecond(ms); + + return rt_thread_sleep(tick); +} +RTM_EXPORT(rt_thread_mdelay); + +#ifdef RT_USING_SMP +static void rt_thread_cpu_bind(rt_thread_t thread, int cpu) +{ + rt_base_t level; + + if (cpu >= RT_CPUS_NR) + { + cpu = RT_CPUS_NR; + } + + level = rt_hw_interrupt_disable(); + if ((thread->stat & RT_THREAD_STAT_MASK) == RT_THREAD_READY) + { + /* unbind */ + /* remove from old ready queue */ + rt_schedule_remove_thread(thread); + /* change thread bind cpu */ + thread->bind_cpu = cpu; + /* add to new ready queue */ + rt_schedule_insert_thread(thread); + if (rt_thread_self() != RT_NULL) + { + rt_schedule(); + } + } + else + { + thread->bind_cpu = cpu; + if ((thread->stat & RT_THREAD_STAT_MASK) == RT_THREAD_RUNNING) + { + /* thread is running on a cpu */ + int current_cpu = rt_hw_cpu_id(); + + if (cpu != RT_CPUS_NR) + { + if (thread->oncpu == current_cpu) + { + /* current thread on current cpu */ + if (cpu != current_cpu) + { + /* bind to other cpu */ + rt_hw_ipi_send(RT_SCHEDULE_IPI, 1U << cpu); + /* self cpu need reschedule */ + rt_schedule(); + } + /* else do nothing */ + } + else + { + /* no running on self cpu, but dest cpu can be itself */ + rt_hw_ipi_send(RT_SCHEDULE_IPI, 1U << thread->oncpu); + } + } + /* else do nothing */ + } + } + rt_hw_interrupt_enable(level); +} +#endif + +/** + * @brief This function will control thread behaviors according to control command. + * + * @param thread is the specified thread to be controlled. + * + * @param cmd is the control command, which includes. + * + * RT_THREAD_CTRL_CHANGE_PRIORITY for changing priority level of thread. + * + * RT_THREAD_CTRL_STARTUP for starting a thread. + * + * RT_THREAD_CTRL_CLOSE for delete a thread. + * + * RT_THREAD_CTRL_BIND_CPU for bind the thread to a CPU. + * + * @param arg is the argument of control command. + * + * @return Return the operation status. If the return value is RT_EOK, the function is successfully executed. + * If the return value is any other values, it means this operation failed. + */ +rt_err_t rt_thread_control(rt_thread_t thread, int cmd, void *arg) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + + switch (cmd) + { + case RT_THREAD_CTRL_CHANGE_PRIORITY: + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* for ready thread, change queue */ + if ((thread->stat & RT_THREAD_STAT_MASK) == RT_THREAD_READY) + { + /* remove thread from schedule queue first */ + rt_schedule_remove_thread(thread); + + /* change thread priority */ + thread->current_priority = *(rt_uint8_t *)arg; + + /* recalculate priority attribute */ + #if RT_THREAD_PRIORITY_MAX > 32 + thread->number = thread->current_priority >> 3; /* 5bit */ + thread->number_mask = 1 << thread->number; + thread->high_mask = 1 << (thread->current_priority & 0x07); /* 3bit */ + #else + thread->number_mask = 1 << thread->current_priority; + #endif /* RT_THREAD_PRIORITY_MAX > 32 */ + + /* insert thread to schedule queue again */ + rt_schedule_insert_thread(thread); + } + else + { + thread->current_priority = *(rt_uint8_t *)arg; + + /* recalculate priority attribute */ + #if RT_THREAD_PRIORITY_MAX > 32 + thread->number = thread->current_priority >> 3; /* 5bit */ + thread->number_mask = 1 << thread->number; + thread->high_mask = 1 << (thread->current_priority & 0x07); /* 3bit */ + #else + thread->number_mask = 1 << thread->current_priority; + #endif /* RT_THREAD_PRIORITY_MAX > 32 */ + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + break; + } + + case RT_THREAD_CTRL_STARTUP: + { + return rt_thread_startup(thread); + } + + case RT_THREAD_CTRL_CLOSE: + { + rt_err_t rt_err; + + if (rt_object_is_systemobject((rt_object_t)thread) == RT_TRUE) + { + rt_err = rt_thread_detach(thread); + } + #ifdef RT_USING_HEAP + else + { + rt_err = rt_thread_delete(thread); + } + #endif /* RT_USING_HEAP */ + rt_schedule(); + return rt_err; + } + + #ifdef RT_USING_SMP + case RT_THREAD_CTRL_BIND_CPU: + { + rt_uint8_t cpu; + + cpu = (rt_uint8_t)(size_t)arg; + rt_thread_cpu_bind(thread, cpu); + break; + } +#endif /*RT_USING_SMP*/ + default: + break; + } + + return RT_EOK; +} +RTM_EXPORT(rt_thread_control); + +#ifdef RT_USING_SMART +int lwp_suspend_sigcheck(rt_thread_t thread, int suspend_flag); +#endif + +static void rt_thread_set_suspend_state(struct rt_thread *thread, int suspend_flag) +{ + rt_uint8_t stat = RT_THREAD_SUSPEND_UNINTERRUPTIBLE; + + RT_ASSERT(thread != RT_NULL); + switch (suspend_flag) + { + case RT_INTERRUPTIBLE: + stat = RT_THREAD_SUSPEND_INTERRUPTIBLE; + break; + case RT_KILLABLE: + stat = RT_THREAD_SUSPEND_KILLABLE; + break; + case RT_UNINTERRUPTIBLE: + stat = RT_THREAD_SUSPEND_UNINTERRUPTIBLE; + break; + default: + RT_ASSERT(0); + break; + } + thread->stat = stat | (thread->stat & ~RT_THREAD_STAT_MASK); +} + +/** + * @brief This function will suspend the specified thread and change it to suspend state. + * + * @note This function ONLY can suspend current thread itself. + * rt_thread_suspend(rt_thread_self()); + * + * Do not use the rt_thread_suspend to suspend other threads. You have no way of knowing what code a + * thread is executing when you suspend it. If you suspend a thread while sharing a resouce with + * other threads and occupying this resouce, starvation can occur very easily. + * + * @param thread the thread to be suspended. + * @param suspend_flag status flag of the thread to be suspended. + * + * @return Return the operation status. If the return value is RT_EOK, the function is successfully executed. + * If the return value is any other values, it means this operation failed. + */ +rt_err_t rt_thread_suspend_with_flag(rt_thread_t thread, int suspend_flag) +{ + rt_base_t stat; + rt_base_t level; + + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + RT_ASSERT(thread == rt_thread_self()); + + RT_DEBUG_LOG(RT_DEBUG_THREAD, ("thread suspend: %s\n", thread->name)); + + stat = thread->stat & RT_THREAD_STAT_MASK; + if ((stat != RT_THREAD_READY) && (stat != RT_THREAD_RUNNING)) + { + RT_DEBUG_LOG(RT_DEBUG_THREAD, ("thread suspend: thread disorder, 0x%2x\n", thread->stat)); + return -RT_ERROR; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + if (stat == RT_THREAD_RUNNING) + { + /* not suspend running status thread on other core */ + RT_ASSERT(thread == rt_thread_self()); + } +#ifdef RT_USING_SMART + if (lwp_suspend_sigcheck(thread, suspend_flag) == 0) + { + /* not to suspend */ + rt_hw_interrupt_enable(level); + rt_kprintf("-RT_EINTR\r\n"); + return -RT_EINTR; + } +#endif + + /* change thread stat */ + rt_schedule_remove_thread(thread); + rt_thread_set_suspend_state(thread, suspend_flag); + + /* stop thread timer anyway */ + rt_timer_stop(&(thread->thread_timer)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_thread_suspend_hook, (thread)); + return RT_EOK; +} +RTM_EXPORT(rt_thread_suspend_with_flag); + +rt_err_t rt_thread_suspend(rt_thread_t thread) +{ + return rt_thread_suspend_with_flag(thread, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_thread_suspend); + +/** + * @brief This function will resume a thread and put it to system ready queue. + * + * @param thread is the thread to be resumed. + * + * @return Return the operation status. If the return value is RT_EOK, the function is successfully executed. + * If the return value is any other values, it means this operation failed. + */ +rt_err_t rt_thread_resume(rt_thread_t thread) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + + RT_DEBUG_LOG(RT_DEBUG_THREAD, ("thread resume: %s\n", thread->name)); + + if ((thread->stat & RT_THREAD_SUSPEND_MASK) != RT_THREAD_SUSPEND_MASK) + { + RT_DEBUG_LOG(RT_DEBUG_THREAD, ("thread resume: thread disorder, %d\n", + thread->stat)); + + return -RT_ERROR; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* remove from suspend list */ + rt_list_remove(&(thread->tlist)); + + rt_timer_stop(&thread->thread_timer); + +#ifdef RT_USING_SMART + thread->wakeup.func = RT_NULL; +#endif + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* insert to schedule ready list */ + rt_schedule_insert_thread(thread); + + RT_OBJECT_HOOK_CALL(rt_thread_resume_hook, (thread)); + return RT_EOK; +} +RTM_EXPORT(rt_thread_resume); + +#ifdef RT_USING_SMART +/** + * This function will wakeup a thread with customized operation. + * + * @param thread the thread to be resumed + * + * @return the operation status, RT_EOK on OK, -RT_ERROR on error + */ +rt_err_t rt_thread_wakeup(rt_thread_t thread) +{ + register rt_base_t temp; + rt_err_t ret; + + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + /* disable interrupt */ + temp = rt_hw_interrupt_disable(); + if (thread->wakeup.func) + { + ret = thread->wakeup.func(thread->wakeup.user_data, thread); + thread->wakeup.func = RT_NULL; + } + else + { + ret = rt_thread_resume(thread); + } + + rt_hw_interrupt_enable(temp); + return ret; +} +RTM_EXPORT(rt_thread_wakeup); + +void rt_thread_wakeup_set(struct rt_thread *thread, rt_wakeup_func_t func, void* user_data) +{ + register rt_base_t temp; + + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + + temp = rt_hw_interrupt_disable(); + thread->wakeup.func = func; + thread->wakeup.user_data = user_data; + rt_hw_interrupt_enable(temp); +} +RTM_EXPORT(rt_thread_wakeup_set); +#endif +/** + * @brief This function will find the specified thread. + * + * @note Please don't invoke this function in interrupt status. + * + * @param name is the name of thread finding. + * + * @return If the return value is a rt_thread structure pointer, the function is successfully executed. + * If the return value is RT_NULL, it means this operation failed. + */ +rt_thread_t rt_thread_find(char *name) +{ + return (rt_thread_t)rt_object_find(name, RT_Object_Class_Thread); +} + +RTM_EXPORT(rt_thread_find); + +/**@}*/ diff --git a/tasks/concur-rtthread-mutex-ceilings/valid_fold/src/ipc.c b/tasks/concur-rtthread-mutex-ceilings/valid_fold/src/ipc.c new file mode 100644 index 00000000..7568f8aa --- /dev/null +++ b/tasks/concur-rtthread-mutex-ceilings/valid_fold/src/ipc.c @@ -0,0 +1,3746 @@ +/* + * Copyright (c) 2006-2022, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +#include +#include + +#ifndef __on_rt_object_trytake_hook + #define __on_rt_object_trytake_hook(parent) __ON_HOOK_ARGS(rt_object_trytake_hook, (parent)) +#endif +#ifndef __on_rt_object_take_hook + #define __on_rt_object_take_hook(parent) __ON_HOOK_ARGS(rt_object_take_hook, (parent)) +#endif +#ifndef __on_rt_object_put_hook + #define __on_rt_object_put_hook(parent) __ON_HOOK_ARGS(rt_object_put_hook, (parent)) +#endif + +#if defined(RT_USING_HOOK) && defined(RT_HOOK_USING_FUNC_PTR) +extern void (*rt_object_trytake_hook)(struct rt_object *object); +extern void (*rt_object_take_hook)(struct rt_object *object); +extern void (*rt_object_put_hook)(struct rt_object *object); +#endif /* RT_USING_HOOK */ + +/** + * @addtogroup IPC + * @{ + */ + +/** + * @brief This function will initialize an IPC object, such as semaphore, mutex, messagequeue and mailbox. + * + * @note Executing this function will complete an initialization of the suspend thread list of the ipc object. + * + * @param ipc is a pointer to the IPC object. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * When the return value is any other values, it means the initialization failed. + * + * @warning This function can be called from all IPC initialization and creation. + */ +rt_inline rt_err_t _ipc_object_init(struct rt_ipc_object *ipc) +{ + /* initialize ipc object */ + rt_list_init(&(ipc->suspend_thread)); + + return RT_EOK; +} + + +/** + * @brief This function will suspend a thread to a IPC object list. + * + * @param list is a pointer to a suspended thread list of the IPC object. + * + * @param thread is a pointer to the thread object to be suspended. + * + * @param flag is a flag for the thread object to be suspended. It determines how the thread is suspended. + * The flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to use + * RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this semaphore will become non-real-time threads. + * + * @param suspend_flag status flag of the thread to be suspended. + * + * @return Return the operation status. When the return value is RT_EOK, the function is successfully executed. + * When the return value is any other values, it means the initialization failed. + * + * @warning This function can ONLY be called in the thread context, you can use RT_DEBUG_IN_THREAD_CONTEXT to + * check the context. + * In addition, this function is generally called by the following functions: + * rt_sem_take(), rt_mutex_take(), rt_event_recv(), rt_mb_send_wait(), + * rt_mb_recv(), rt_mq_recv(), rt_mq_send_wait() + */ +rt_inline rt_err_t _ipc_list_suspend(rt_list_t *list, + struct rt_thread *thread, + rt_uint8_t flag, + int suspend_flag) +{ + if ((thread->stat & RT_THREAD_SUSPEND_MASK) != RT_THREAD_SUSPEND_MASK) + { + rt_err_t ret = rt_thread_suspend_with_flag(thread, suspend_flag); + + /* suspend thread */ + if (ret != RT_EOK) + { + return ret; + } + } + + switch (flag) + { + case RT_IPC_FLAG_FIFO: + rt_list_insert_before(list, &(thread->tlist)); + break; /* RT_IPC_FLAG_FIFO */ + + case RT_IPC_FLAG_PRIO: + { + struct rt_list_node *n; + struct rt_thread *sthread; + + /* find a suitable position */ + for (n = list->next; n != list; n = n->next) + { + sthread = rt_list_entry(n, struct rt_thread, tlist); + + /* find out */ + if (thread->current_priority < sthread->current_priority) + { + /* insert this thread before the sthread */ + rt_list_insert_before(&(sthread->tlist), &(thread->tlist)); + break; + } + } + + /* + * not found a suitable position, + * append to the end of suspend_thread list + */ + if (n == list) + rt_list_insert_before(list, &(thread->tlist)); + } + break;/* RT_IPC_FLAG_PRIO */ + + default: + RT_ASSERT(0); + break; + } + + return RT_EOK; +} + + +/** + * @brief This function will resume a thread. + * + * @note This function will resume the first thread in the list of a IPC object. + * 1. remove the thread from suspend queue of a IPC object. + * 2. put the thread into system ready queue. + * + * By contrast, the rt_ipc_list_resume_all() function will resume all suspended threads + * in the list of a IPC object. + * + * @param list is a pointer to a suspended thread list of the IPC object. + * + * @return Return the operation status. When the return value is RT_EOK, the function is successfully executed. + * When the return value is any other values, it means this operation failed. + * + * @warning This function is generally called by the following functions: + * rt_sem_release(), rt_mutex_release(), rt_mb_send_wait(), rt_mq_send_wait(), + * rt_mb_urgent(), rt_mb_recv(), rt_mq_urgent(), rt_mq_recv(), + */ +rt_inline rt_err_t _ipc_list_resume(rt_list_t *list) +{ + struct rt_thread *thread; + + /* get thread entry */ + thread = rt_list_entry(list->next, struct rt_thread, tlist); + + thread->error = RT_EOK; + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("resume thread:%s\n", thread->name)); + + /* resume it */ + rt_thread_resume(thread); + + return RT_EOK; +} + + +/** + * @brief This function will resume all suspended threads in the IPC object list, + * including the suspended list of IPC object, and private list of mailbox etc. + * + * @note This function will resume all threads in the IPC object list. + * By contrast, the rt_ipc_list_resume() function will resume a suspended thread in the list of a IPC object. + * + * @param list is a pointer to a suspended thread list of the IPC object. + * + * @return Return the operation status. When the return value is RT_EOK, the function is successfully executed. + * When the return value is any other values, it means this operation failed. + * + */ +rt_inline rt_err_t _ipc_list_resume_all(rt_list_t *list) +{ + struct rt_thread *thread; + rt_base_t level; + + /* wakeup all suspended threads */ + while (!rt_list_isempty(list)) + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* get next suspended thread */ + thread = rt_list_entry(list->next, struct rt_thread, tlist); + /* set error code to RT_ERROR */ + thread->error = -RT_ERROR; + + /* + * resume thread + * In rt_thread_resume function, it will remove current thread from + * suspended list + */ + rt_thread_resume(thread); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + } + + return RT_EOK; +} + +#ifdef RT_USING_SEMAPHORE +/** + * @addtogroup semaphore + * @{ + */ + +/** + * @brief This function will initialize a static semaphore object. + * + * @note For the static semaphore object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_sem_create() function will allocate memory space automatically and initialize + * the semaphore. + * + * @see rt_sem_create() + * + * @param sem is a pointer to the semaphore to initialize. It is assumed that storage for the semaphore will be + * allocated in your application. + * + * @param name is a pointer to the name you would like to give the semaphore. + * + * @param value is the initial value for the semaphore. + * If used to share resources, you should initialize the value as the number of available resources. + * If used to signal the occurrence of an event, you should initialize the value as 0. + * + * @param flag is the semaphore flag, which determines the queuing way of how multiple threads wait + * when the semaphore is not available. + * The semaphore flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this semaphore will become non-real-time threads. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_sem_init(rt_sem_t sem, + const char *name, + rt_uint32_t value, + rt_uint8_t flag) +{ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(value < 0x10000U); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(sem->parent.parent), RT_Object_Class_Semaphore, name); + + /* initialize ipc object */ + _ipc_object_init(&(sem->parent)); + + /* set initial value */ + sem->value = (rt_uint16_t)value; + + /* set parent */ + sem->parent.parent.flag = flag; + + return RT_EOK; +} +RTM_EXPORT(rt_sem_init); + + +/** + * @brief This function will detach a static semaphore object. + * + * @note This function is used to detach a static semaphore object which is initialized by rt_sem_init() function. + * By contrast, the rt_sem_delete() function will delete a semaphore object. + * When the semaphore is successfully detached, it will resume all suspended threads in the semaphore list. + * + * @see rt_sem_delete() + * + * @param sem is a pointer to a semaphore object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the semaphore detach failed. + * + * @warning This function can ONLY detach a static semaphore initialized by the rt_sem_init() function. + * If the semaphore is created by the rt_sem_create() function, you MUST NOT USE this function to detach it, + * ONLY USE the rt_sem_delete() function to complete the deletion. + */ +rt_err_t rt_sem_detach(rt_sem_t sem) +{ + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + RT_ASSERT(rt_object_is_systemobject(&sem->parent.parent)); + + /* wakeup all suspended threads */ + _ipc_list_resume_all(&(sem->parent.suspend_thread)); + + /* detach semaphore object */ + rt_object_detach(&(sem->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_sem_detach); + +#ifdef RT_USING_HEAP +/** + * @brief Creating a semaphore object. + * + * @note For the semaphore object, its memory space is allocated automatically. + * By contrast, the rt_sem_init() function will initialize a static semaphore object. + * + * @see rt_sem_init() + * + * @param name is a pointer to the name you would like to give the semaphore. + * + * @param value is the initial value for the semaphore. + * If used to share resources, you should initialize the value as the number of available resources. + * If used to signal the occurrence of an event, you should initialize the value as 0. + * + * @param flag is the semaphore flag, which determines the queuing way of how multiple threads wait + * when the semaphore is not available. + * The semaphore flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this semaphore will become non-real-time threads. + * + * @return Return a pointer to the semaphore object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can NOT be called in interrupt context. You can use macor RT_DEBUG_NOT_IN_INTERRUPT to check it. + */ +rt_sem_t rt_sem_create(const char *name, rt_uint32_t value, rt_uint8_t flag) +{ + rt_sem_t sem; + + RT_ASSERT(value < 0x10000U); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + sem = (rt_sem_t)rt_object_allocate(RT_Object_Class_Semaphore, name); + if (sem == RT_NULL) + return sem; + + /* initialize ipc object */ + _ipc_object_init(&(sem->parent)); + + /* set initial value */ + sem->value = value; + + /* set parent */ + sem->parent.parent.flag = flag; + + return sem; +} +RTM_EXPORT(rt_sem_create); + + +/** + * @brief This function will delete a semaphore object and release the memory space. + * + * @note This function is used to delete a semaphore object which is created by the rt_sem_create() function. + * By contrast, the rt_sem_detach() function will detach a static semaphore object. + * When the semaphore is successfully deleted, it will resume all suspended threads in the semaphore list. + * + * @see rt_sem_detach() + * + * @param sem is a pointer to a semaphore object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the semaphore detach failed. + * + * @warning This function can ONLY delete a semaphore initialized by the rt_sem_create() function. + * If the semaphore is initialized by the rt_sem_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_sem_detach() function to complete the detachment. + */ +rt_err_t rt_sem_delete(rt_sem_t sem) +{ + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + RT_ASSERT(rt_object_is_systemobject(&sem->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* wakeup all suspended threads */ + _ipc_list_resume_all(&(sem->parent.suspend_thread)); + + /* delete semaphore object */ + rt_object_delete(&(sem->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_sem_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will take a semaphore, if the semaphore is unavailable, the thread shall wait for + * the semaphore up to a specified time. + * + * @note When this function is called, the count value of the sem->value will decrease 1 until it is equal to 0. + * When the sem->value is 0, it means that the semaphore is unavailable. At this time, it will suspend the + * thread preparing to take the semaphore. + * On the contrary, the rt_sem_release() function will increase the count value of sem->value by 1 each time. + * + * @see rt_sem_trytake() + * + * @param sem is a pointer to a semaphore object. + * + * @param timeout is a timeout period (unit: an OS tick). If the semaphore is unavailable, the thread will wait for + * the semaphore up to the amount of time specified by this parameter. + * + * NOTE: + * If use Macro RT_WAITING_FOREVER to set this parameter, which means that when the + * message is unavailable in the queue, the thread will be waiting forever. + * If use macro RT_WAITING_NO to set this parameter, which means that this + * function is non-blocking and will return immediately. + * + * @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 semaphore take failed. + * + * @warning This function can ONLY be called in the thread context. It MUST NOT BE called in interrupt context. + */ +static rt_err_t _rt_sem_take(rt_sem_t sem, rt_int32_t timeout, int suspend_flag) +{ + rt_base_t level; + struct rt_thread *thread; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(sem->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("thread %s take sem:%s, which value is: %d\n", + rt_thread_self()->name, + ((struct rt_object *)sem)->name, + sem->value)); + + if (sem->value > 0) + { + /* semaphore is available */ + sem->value --; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + } + else + { + /* no waiting, return with timeout */ + if (timeout == 0) + { + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + else + { + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE); + + /* semaphore is unavailable, push to suspend list */ + /* get current thread */ + thread = rt_thread_self(); + + /* reset thread error number */ + thread->error = -RT_EINTR; + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("sem take: suspend thread - %s\n", + thread->name)); + + /* suspend thread */ + ret = _ipc_list_suspend(&(sem->parent.suspend_thread), + thread, + sem->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + RT_DEBUG_LOG(RT_DEBUG_IPC, ("set thread:%s to timer list\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do schedule */ + rt_schedule(); + + if (thread->error != RT_EOK) + { + return thread->error; + } + } + } + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(sem->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_sem_take(rt_sem_t sem, rt_int32_t time) +{ + return _rt_sem_take(sem, time, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_sem_take); + +rt_err_t rt_sem_take_interruptible(rt_sem_t sem, rt_int32_t time) +{ + return _rt_sem_take(sem, time, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_sem_take_interruptible); + +rt_err_t rt_sem_take_killable(rt_sem_t sem, rt_int32_t time) +{ + return _rt_sem_take(sem, time, RT_KILLABLE); +} +RTM_EXPORT(rt_sem_take_killable); + +/** + * @brief This function will try to take a semaphore, if the semaphore is unavailable, the thread returns immediately. + * + * @note This function is very similar to the rt_sem_take() function, when the semaphore is not available, + * the rt_sem_trytake() function will return immediately without waiting for a timeout. + * In other words, rt_sem_trytake(sem) has the same effect as rt_sem_take(sem, 0). + * + * @see rt_sem_take() + * + * @param sem is a pointer to a semaphore object. + * + * @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 semaphore take failed. + */ +rt_err_t rt_sem_trytake(rt_sem_t sem) +{ + return rt_sem_take(sem, RT_WAITING_NO); +} +RTM_EXPORT(rt_sem_trytake); + + +/** + * @brief This function will release a semaphore. If there is thread suspended on the semaphore, it will get resumed. + * + * @note If there are threads suspended on this semaphore, the first thread in the list of this semaphore object + * will be resumed, and a thread scheduling (rt_schedule) will be executed. + * If no threads are suspended on this semaphore, the count value sem->value of this semaphore will increase by 1. + * + * @param sem is a pointer to a semaphore object. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the semaphore release failed. + */ +rt_err_t rt_sem_release(rt_sem_t sem) +{ + rt_base_t level; + rt_bool_t need_schedule; + + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(sem->parent.parent))); + + need_schedule = RT_FALSE; + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("thread %s releases sem:%s, which value is: %d\n", + rt_thread_self()->name, + ((struct rt_object *)sem)->name, + sem->value)); + + if (!rt_list_isempty(&sem->parent.suspend_thread)) + { + /* resume the suspended thread */ + _ipc_list_resume(&(sem->parent.suspend_thread)); + need_schedule = RT_TRUE; + } + else + { + if(sem->value < RT_SEM_VALUE_MAX) + { + sem->value ++; /* increase value */ + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* resume a thread, re-schedule */ + if (need_schedule == RT_TRUE) + rt_schedule(); + + return RT_EOK; +} +RTM_EXPORT(rt_sem_release); + + +/** + * @brief This function will set some extra attributions of a semaphore object. + * + * @note Currently this function only supports the RT_IPC_CMD_RESET command to reset the semaphore. + * + * @param sem is a pointer to a semaphore object. + * + * @param cmd is a command word used to configure some attributions of the semaphore. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_sem_control(rt_sem_t sem, int cmd, void *arg) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + + if (cmd == RT_IPC_CMD_RESET) + { + rt_ubase_t value; + + /* get value */ + value = (rt_ubase_t)arg; + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* resume all waiting thread */ + _ipc_list_resume_all(&sem->parent.suspend_thread); + + /* set new value */ + sem->value = (rt_uint16_t)value; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_sem_control); + +/**@}*/ +#endif /* RT_USING_SEMAPHORE */ + +#ifdef RT_USING_MUTEX +/* iterate over each suspended thread to update highest priority in pending threads */ +rt_inline rt_uint8_t _mutex_update_priority(struct rt_mutex *mutex) +{ + struct rt_thread *thread; + + if (!rt_list_isempty(&mutex->parent.suspend_thread)) + { + thread = rt_list_entry(mutex->parent.suspend_thread.next, struct rt_thread, tlist); + mutex->priority = thread->current_priority; + } + else + { + mutex->priority = 0xff; + } + + return mutex->priority; +} + +/* get highest priority inside its taken object and its init priority */ +rt_inline rt_uint8_t _thread_get_mutex_priority(struct rt_thread *thread) +{ + rt_uint8_t best = thread->init_priority; + rt_list_t *cursor = thread->taken_object_list.next; + while (cursor != &thread->taken_object_list) + { + struct rt_mutex *held = rt_list_entry(cursor, struct rt_mutex, taken_list); + if (held->ceiling_priority < best) best = held->ceiling_priority; + if (held->priority < best) best = held->priority; + cursor = cursor->next; + } + return best; +} + +/* update priority of target thread and the thread suspended it if any */ +rt_inline void _thread_update_priority(struct rt_thread *thread, rt_uint8_t priority, int suspend_flag) +{ + rt_err_t ret; + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("thread:%s priority -> %d\n", thread->name, priority)); + + /* change priority of the thread */ + rt_thread_control(thread, + RT_THREAD_CTRL_CHANGE_PRIORITY, + &priority); + + if ((thread->stat & RT_THREAD_SUSPEND_MASK) == RT_THREAD_SUSPEND_MASK) + { + /* whether change the priority of taken mutex */ + struct rt_object* pending_obj = thread->pending_object; + + if (pending_obj && rt_object_get_type(pending_obj) == RT_Object_Class_Mutex) + { + rt_uint8_t mutex_priority; + struct rt_mutex* pending_mutex = (struct rt_mutex *)pending_obj; + + /* re-insert thread to suspended thread list */ + rt_list_remove(&(thread->tlist)); + + ret = _ipc_list_suspend(&(pending_mutex->parent.suspend_thread), + thread, + pending_mutex->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + /* TODO */ + return ; + } + + /* update priority */ + _mutex_update_priority(pending_mutex); + /* change the priority of mutex owner thread */ + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("mutex: %s priority -> %d\n", pending_mutex->parent.parent.name, + pending_mutex->priority)); + + mutex_priority = _thread_get_mutex_priority(pending_mutex->owner); + if (mutex_priority != pending_mutex->owner->current_priority) + { + _thread_update_priority(pending_mutex->owner, mutex_priority, suspend_flag); + } + } + } +} + +/** + * @addtogroup mutex + * @{ + */ + +/** + * @brief Initialize a static mutex object. + * + * @note For the static mutex object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_mutex_create() function will automatically allocate memory space + * and initialize the mutex. + * + * @see rt_mutex_create() + * + * @param mutex is a pointer to the mutex to initialize. It is assumed that storage for the mutex will be + * allocated in your application. + * + * @param name is a pointer to the name that given to the mutex. + * + * @param flag is the mutex flag, which determines the queuing way of how multiple threads wait + * when the mutex is not available. + * NOTE: This parameter has been obsoleted. It can be RT_IPC_FLAG_PRIO, RT_IPC_FLAG_FIFO or RT_NULL. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_mutex_init(rt_mutex_t mutex, const char *name, rt_uint8_t flag) +{ + /* flag parameter has been obsoleted */ + RT_UNUSED(flag); + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + + /* initialize object */ + rt_object_init(&(mutex->parent.parent), RT_Object_Class_Mutex, name); + + /* initialize ipc object */ + _ipc_object_init(&(mutex->parent)); + + mutex->owner = RT_NULL; + mutex->priority = 0xFF; + mutex->hold = 0; + mutex->ceiling_priority = 0xFF; + rt_list_init(&(mutex->taken_list)); + + /* flag can only be RT_IPC_FLAG_PRIO. RT_IPC_FLAG_FIFO cannot solve the unbounded priority inversion problem */ + mutex->parent.parent.flag = RT_IPC_FLAG_PRIO; + + return RT_EOK; +} +RTM_EXPORT(rt_mutex_init); + + +/** + * @brief This function will detach a static mutex object. + * + * @note This function is used to detach a static mutex object which is initialized by rt_mutex_init() function. + * By contrast, the rt_mutex_delete() function will delete a mutex object. + * When the mutex is successfully detached, it will resume all suspended threads in the mutex list. + * + * @see rt_mutex_delete() + * + * @param mutex is a pointer to a mutex object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the mutex detach failed. + * + * @warning This function can ONLY detach a static mutex initialized by the rt_mutex_init() function. + * If the mutex is created by the rt_mutex_create() function, you MUST NOT USE this function to detach it, + * ONLY USE the rt_mutex_delete() function to complete the deletion. + */ +rt_err_t rt_mutex_detach(rt_mutex_t mutex) +{ + rt_ubase_t level; + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + RT_ASSERT(rt_object_is_systemobject(&mutex->parent.parent)); + + level = rt_hw_interrupt_disable(); + /* wakeup all suspended threads */ + _ipc_list_resume_all(&(mutex->parent.suspend_thread)); + /* remove mutex from thread's taken list */ + rt_list_remove(&mutex->taken_list); + rt_hw_interrupt_enable(level); + + /* detach mutex object */ + rt_object_detach(&(mutex->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mutex_detach); + +/* drop a thread from the suspend list of mutex */ + +/** + * @brief drop a thread from the suspend list of mutex + * + * @param mutex is a pointer to a mutex object. + * @param thread is the thread should be dropped from mutex. + */ +void rt_mutex_drop_thread(rt_mutex_t mutex, rt_thread_t thread) +{ + rt_uint8_t priority; + rt_bool_t need_update = RT_FALSE; + + rt_list_remove(&(thread->tlist)); + + /* should change the priority of mutex owner thread */ + if (mutex->owner->current_priority == thread->current_priority) + need_update = RT_TRUE; + + /* update the priority of mutex */ + if (!rt_list_isempty(&mutex->parent.suspend_thread)) + { + /* more thread suspended in the list */ + struct rt_thread *th; + + th = rt_list_entry(mutex->parent.suspend_thread.next, + struct rt_thread, + tlist); + /* update the priority of mutex */ + mutex->priority = th->current_priority; + } + else + { + /* set mutex priority to maximal priority */ + mutex->priority = 0xff; + } + + /* try to change the priority of mutex owner thread */ + if (need_update) + { + /* get the maximal priority of mutex in thread */ + priority = _thread_get_mutex_priority(mutex->owner); + if (priority != mutex->owner->current_priority) + { + _thread_update_priority(mutex->owner, priority, RT_UNINTERRUPTIBLE); + } + } +} + + +/** + * @brief set the prioceiling attribute of the mutex. + * + * @param mutex is a pointer to a mutex object. + * @param priority is the priority should be set to mutex. + * + * @return return the old priority ceiling + */ +rt_uint8_t rt_mutex_setprioceiling(rt_mutex_t mutex, rt_uint8_t priority) +{ + rt_uint8_t ret_priority = 0xFF; + + if ((mutex) && (priority < RT_THREAD_PRIORITY_MAX)) + { + /* critical section here if multiple updates to one mutex happen */ + rt_ubase_t level = rt_hw_interrupt_disable(); + ret_priority = mutex->ceiling_priority; + mutex->ceiling_priority = priority; + if (mutex->owner) + { + rt_uint8_t priority = _thread_get_mutex_priority(mutex->owner); + if (priority != mutex->owner->current_priority) + _thread_update_priority(mutex->owner, priority, RT_UNINTERRUPTIBLE); + } + rt_hw_interrupt_enable(level); + } + else + { + rt_set_errno(-RT_EINVAL); + } + + return ret_priority; +} +RTM_EXPORT(rt_mutex_setprioceiling); + + +/** + * @brief set the prioceiling attribute of the mutex. + * + * @param mutex is a pointer to a mutex object. + * + * @return return the current priority ceiling of the mutex. + */ +rt_uint8_t rt_mutex_getprioceiling(rt_mutex_t mutex) +{ + rt_uint8_t prio = 0xFF; + + if (mutex) + { + prio = mutex->ceiling_priority; + } + + return prio; +} +RTM_EXPORT(rt_mutex_getprioceiling); + + +#ifdef RT_USING_HEAP +/** + * @brief This function will create a mutex object. + * + * @note For the mutex object, its memory space is automatically allocated. + * By contrast, the rt_mutex_init() function will initialize a static mutex object. + * + * @see rt_mutex_init() + * + * @param name is a pointer to the name that given to the mutex. + * + * @param flag is the mutex flag, which determines the queuing way of how multiple threads wait + * when the mutex is not available. + * NOTE: This parameter has been obsoleted. It can be RT_IPC_FLAG_PRIO, RT_IPC_FLAG_FIFO or RT_NULL. + * + * @return Return a pointer to the mutex object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_mutex_t rt_mutex_create(const char *name, rt_uint8_t flag) +{ + struct rt_mutex *mutex; + + /* flag parameter has been obsoleted */ + RT_UNUSED(flag); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + mutex = (rt_mutex_t)rt_object_allocate(RT_Object_Class_Mutex, name); + if (mutex == RT_NULL) + return mutex; + + /* initialize ipc object */ + _ipc_object_init(&(mutex->parent)); + + mutex->owner = RT_NULL; + mutex->priority = 0xFF; + mutex->hold = 0; + mutex->ceiling_priority = 0xFF; + rt_list_init(&(mutex->taken_list)); + + /* flag can only be RT_IPC_FLAG_PRIO. RT_IPC_FLAG_FIFO cannot solve the unbounded priority inversion problem */ + mutex->parent.parent.flag = RT_IPC_FLAG_PRIO; + + return mutex; +} +RTM_EXPORT(rt_mutex_create); + + +/** + * @brief This function will delete a mutex object and release this memory space. + * + * @note This function is used to delete a mutex object which is created by the rt_mutex_create() function. + * By contrast, the rt_mutex_detach() function will detach a static mutex object. + * When the mutex is successfully deleted, it will resume all suspended threads in the mutex list. + * + * @see rt_mutex_detach() + * + * @param mutex is a pointer to a mutex object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mutex detach failed. + * + * @warning This function can ONLY delete a mutex initialized by the rt_mutex_create() function. + * If the mutex is initialized by the rt_mutex_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_mutex_detach() function to complete the detachment. + */ +rt_err_t rt_mutex_delete(rt_mutex_t mutex) +{ + rt_ubase_t level; + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + RT_ASSERT(rt_object_is_systemobject(&mutex->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + level = rt_hw_interrupt_disable(); + /* wakeup all suspended threads */ + _ipc_list_resume_all(&(mutex->parent.suspend_thread)); + /* remove mutex from thread's taken list */ + rt_list_remove(&mutex->taken_list); + rt_hw_interrupt_enable(level); + + /* delete mutex object */ + rt_object_delete(&(mutex->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mutex_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will take a mutex, if the mutex is unavailable, the thread shall wait for + * the mutex up to a specified time. + * + * @note When this function is called, the count value of the mutex->value will decrease 1 until it is equal to 0. + * When the mutex->value is 0, it means that the mutex is unavailable. At this time, it will suspend the + * thread preparing to take the mutex. + * On the contrary, the rt_mutex_release() function will increase the count value of mutex->value by 1 each time. + * + * @see rt_mutex_trytake() + * + * @param mutex is a pointer to a mutex object. + * + * @param timeout is a timeout period (unit: an OS tick). If the mutex is unavailable, the thread will wait for + * the mutex up to the amount of time specified by the argument. + * NOTE: Generally, we set this parameter to RT_WAITING_FOREVER, which means that when the mutex is unavailable, + * the thread will be waitting forever. + * + * @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 mutex take failed. + * + * @warning This function can ONLY be called in the thread context. It MUST NOT BE called in interrupt context. + */ +static rt_err_t _rt_mutex_take(rt_mutex_t mutex, rt_int32_t timeout, int suspend_flag) +{ + rt_base_t level; + struct rt_thread *thread; + rt_err_t ret; + + /* this function must not be used in interrupt even if time = 0 */ + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE); + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + + /* get current thread */ + thread = rt_thread_self(); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(mutex->parent.parent))); + + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("mutex_take: current thread %s, hold: %d\n", + thread->name, mutex->hold)); + + /* reset thread error */ + thread->error = RT_EOK; + + if (mutex->owner == thread) + { + if(mutex->hold < RT_MUTEX_HOLD_MAX) + { + /* it's the same thread */ + mutex->hold ++; + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + } + else + { + /* whether the mutex has owner thread. */ + if (mutex->owner == RT_NULL) + { + /* set mutex owner and original priority */ + mutex->owner = thread; + mutex->priority = 0xff; + mutex->hold = 1; + + if (mutex->ceiling_priority != 0xFF) + { + /* set the priority of thread to the ceiling priority */ + if (mutex->ceiling_priority < mutex->owner->current_priority) + _thread_update_priority(mutex->owner, mutex->ceiling_priority, suspend_flag); + } + + /* insert mutex to thread's taken object list */ + rt_list_insert_before(&thread->taken_object_list, &mutex->taken_list); + } + else + { + /* no waiting, return with timeout */ + if (timeout == 0) + { + /* set error as timeout */ + thread->error = -RT_ETIMEOUT; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + else + { + rt_uint8_t priority = thread->current_priority; + + /* mutex is unavailable, push to suspend list */ + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mutex_take: suspend thread: %s\n", + thread->name)); + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mutex->parent.suspend_thread), + thread, + mutex->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* set pending object in thread to this mutex */ + thread->pending_object = &(mutex->parent.parent); + + /* update the priority level of mutex */ + if (priority < mutex->priority) + { + mutex->priority = priority; + if (mutex->priority < mutex->owner->current_priority) + { + _thread_update_priority(mutex->owner, priority, RT_UNINTERRUPTIBLE); /* TODO */ + } + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("mutex_take: start the timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do schedule */ + rt_schedule(); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + if (thread->error == RT_EOK) + { + /* get mutex successfully */ + } + else + { + /* the mutex has not been taken and thread has detach from the pending list. */ + + rt_bool_t need_update = RT_FALSE; + + /* should change the priority of mutex owner thread */ + if (mutex->owner->current_priority == thread->current_priority) + need_update = RT_TRUE; + + /* update the priority of mutex */ + if (!rt_list_isempty(&mutex->parent.suspend_thread)) + { + /* more thread suspended in the list */ + struct rt_thread *th; + + th = rt_list_entry(mutex->parent.suspend_thread.next, + struct rt_thread, + tlist); + /* update the priority of mutex */ + mutex->priority = th->current_priority; + } + else + { + /* set mutex priority to maximal priority */ + mutex->priority = 0xff; + } + + /* try to change the priority of mutex owner thread */ + if (need_update) + { + /* get the maximal priority of mutex in thread */ + priority = _thread_get_mutex_priority(mutex->owner); + if (priority != mutex->owner->current_priority) + { + _thread_update_priority(mutex->owner, priority, RT_UNINTERRUPTIBLE); + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* return error */ + return thread->error; + } + } + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mutex->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_mutex_take(rt_mutex_t mutex, rt_int32_t time) +{ + return _rt_mutex_take(mutex, time, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mutex_take); + +rt_err_t rt_mutex_take_interruptible(rt_mutex_t mutex, rt_int32_t time) +{ + return _rt_mutex_take(mutex, time, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mutex_take_interruptible); + +rt_err_t rt_mutex_take_killable(rt_mutex_t mutex, rt_int32_t time) +{ + return _rt_mutex_take(mutex, time, RT_KILLABLE); +} +RTM_EXPORT(rt_mutex_take_killable); + +/** + * @brief This function will try to take a mutex, if the mutex is unavailable, the thread returns immediately. + * + * @note This function is very similar to the rt_mutex_take() function, when the mutex is not available, + * except that rt_mutex_trytake() will return immediately without waiting for a timeout + * when the mutex is not available. + * In other words, rt_mutex_trytake(mutex) has the same effect as rt_mutex_take(mutex, 0). + * + * @see rt_mutex_take() + * + * @param mutex is a pointer to a mutex object. + * + * @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 mutex take failed. + */ +rt_err_t rt_mutex_trytake(rt_mutex_t mutex) +{ + return rt_mutex_take(mutex, RT_WAITING_NO); +} +RTM_EXPORT(rt_mutex_trytake); + + +/** + * @brief This function will release a mutex. If there is thread suspended on the mutex, the thread will be resumed. + * + * @note If there are threads suspended on this mutex, the first thread in the list of this mutex object + * will be resumed, and a thread scheduling (rt_schedule) will be executed. + * If no threads are suspended on this mutex, the count value mutex->value of this mutex will increase by 1. + * + * @param mutex is a pointer to a mutex object. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mutex release failed. + */ +rt_err_t rt_mutex_release(rt_mutex_t mutex) +{ + rt_base_t level; + struct rt_thread *thread; + rt_bool_t need_schedule; + + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + + need_schedule = RT_FALSE; + + /* only thread could release mutex because we need test the ownership */ + RT_DEBUG_IN_THREAD_CONTEXT; + + /* get current thread */ + thread = rt_thread_self(); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, + ("mutex_release:current thread %s, hold: %d\n", + thread->name, mutex->hold)); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mutex->parent.parent))); + + /* mutex only can be released by owner */ + if (thread != mutex->owner) + { + thread->error = -RT_ERROR; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_ERROR; + } + + /* decrease hold */ + mutex->hold --; + /* if no hold */ + if (mutex->hold == 0) + { + /* remove mutex from thread's taken list */ + rt_list_remove(&mutex->taken_list); + + /* whether change the thread priority */ + if ((mutex->ceiling_priority != 0xFF) || (thread->current_priority == mutex->priority)) + { + rt_uint8_t priority = 0xff; + + /* get the highest priority in the taken list of thread */ + priority = _thread_get_mutex_priority(thread); + + rt_thread_control(thread, + RT_THREAD_CTRL_CHANGE_PRIORITY, + &priority); + + need_schedule = RT_TRUE; + } + + /* wakeup suspended thread */ + if (!rt_list_isempty(&mutex->parent.suspend_thread)) + { + /* get the first suspended thread */ + struct rt_thread *next_thread = rt_list_entry(mutex->parent.suspend_thread.next, + struct rt_thread, + tlist); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mutex_release: resume thread: %s\n", + next_thread->name)); + + /* remove the thread from the suspended list of mutex */ + rt_list_remove(&(next_thread->tlist)); + + /* set new owner and put mutex into taken list of thread */ + mutex->owner = next_thread; + mutex->hold = 1; + rt_list_insert_after(&next_thread->taken_object_list, &mutex->taken_list); + /* cleanup pending object */ + next_thread->pending_object = RT_NULL; + + /* resume thread */ + rt_thread_resume(next_thread); + + /* update mutex priority */ + if (!rt_list_isempty(&(mutex->parent.suspend_thread))) + { + struct rt_thread *th; + + th = rt_list_entry(mutex->parent.suspend_thread.next, + struct rt_thread, + tlist); + mutex->priority = th->current_priority; + } + else + { + mutex->priority = 0xff; + } + + need_schedule = RT_TRUE; + } + else + { + /* clear owner */ + mutex->owner = RT_NULL; + mutex->priority = 0xff; + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* perform a schedule */ + if (need_schedule == RT_TRUE) + rt_schedule(); + + return RT_EOK; +} +RTM_EXPORT(rt_mutex_release); + + +/** + * @brief This function will set some extra attributions of a mutex object. + * + * @note Currently this function does not implement the control function. + * + * @param mutex is a pointer to a mutex object. + * + * @param cmd is a command word used to configure some attributions of the mutex. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_mutex_control(rt_mutex_t mutex, int cmd, void *arg) +{ + /* parameter check */ + RT_ASSERT(mutex != RT_NULL); + RT_ASSERT(rt_object_get_type(&mutex->parent.parent) == RT_Object_Class_Mutex); + + return -RT_ERROR; +} +RTM_EXPORT(rt_mutex_control); + +/**@}*/ +#endif /* RT_USING_MUTEX */ + +#ifdef RT_USING_EVENT +/** + * @addtogroup event + * @{ + */ + +/** + * @brief The function will initialize a static event object. + * + * @note For the static event object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_event_create() function will allocate memory space automatically + * and initialize the event. + * + * @see rt_event_create() + * + * @param event is a pointer to the event to initialize. It is assumed that storage for the event + * will be allocated in your application. + * + * @param name is a pointer to the name that given to the event. + * + * @param flag is the event flag, which determines the queuing way of how multiple threads wait + * when the event is not available. + * The event flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this event will become non-real-time threads. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_event_init(rt_event_t event, const char *name, rt_uint8_t flag) +{ + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(event->parent.parent), RT_Object_Class_Event, name); + + /* set parent flag */ + event->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(event->parent)); + + /* initialize event */ + event->set = 0; + + return RT_EOK; +} +RTM_EXPORT(rt_event_init); + + +/** + * @brief This function will detach a static event object. + * + * @note This function is used to detach a static event object which is initialized by rt_event_init() function. + * By contrast, the rt_event_delete() function will delete an event object. + * When the event is successfully detached, it will resume all suspended threads in the event list. + * + * @see rt_event_delete() + * + * @param event is a pointer to an event object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the event detach failed. + * + * @warning This function can ONLY detach a static event initialized by the rt_event_init() function. + * If the event is created by the rt_event_create() function, you MUST NOT USE this function to detach it, + * ONLY USE the rt_event_delete() function to complete the deletion. + */ +rt_err_t rt_event_detach(rt_event_t event) +{ + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + RT_ASSERT(rt_object_is_systemobject(&event->parent.parent)); + + /* resume all suspended thread */ + _ipc_list_resume_all(&(event->parent.suspend_thread)); + + /* detach event object */ + rt_object_detach(&(event->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_event_detach); + +#ifdef RT_USING_HEAP +/** + * @brief Creating an event object. + * + * @note For the event object, its memory space is allocated automatically. + * By contrast, the rt_event_init() function will initialize a static event object. + * + * @see rt_event_init() + * + * @param name is a pointer to the name that given to the event. + * + * @param flag is the event flag, which determines the queuing way of how multiple threads wait when the event + * is not available. + * The event flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this event will become non-real-time threads. + * + * @return Return a pointer to the event object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_event_t rt_event_create(const char *name, rt_uint8_t flag) +{ + rt_event_t event; + + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + event = (rt_event_t)rt_object_allocate(RT_Object_Class_Event, name); + if (event == RT_NULL) + return event; + + /* set parent */ + event->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(event->parent)); + + /* initialize event */ + event->set = 0; + + return event; +} +RTM_EXPORT(rt_event_create); + + +/** + * @brief This function will delete an event object and release the memory space. + * + * @note This function is used to delete an event object which is created by the rt_event_create() function. + * By contrast, the rt_event_detach() function will detach a static event object. + * When the event is successfully deleted, it will resume all suspended threads in the event list. + * + * @see rt_event_detach() + * + * @param event is a pointer to an event object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the event detach failed. + * + * @warning This function can ONLY delete an event initialized by the rt_event_create() function. + * If the event is initialized by the rt_event_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_event_detach() function to complete the detachment. + */ +rt_err_t rt_event_delete(rt_event_t event) +{ + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + RT_ASSERT(rt_object_is_systemobject(&event->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* resume all suspended thread */ + _ipc_list_resume_all(&(event->parent.suspend_thread)); + + /* delete event object */ + rt_object_delete(&(event->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_event_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will send an event to the event object. + * If there is a thread suspended on the event, the thread will be resumed. + * + * @note When using this function, you need to use the parameter (set) to specify the event flag of the event object, + * then the function will traverse the list of suspended threads waiting on the event object. + * If there is a thread suspended on the event, and the thread's event_info and the event flag of + * the current event object matches, the thread will be resumed. + * + * @param event is a pointer to the event object to be sent. + * + * @param set is a flag that you will set for this event's flag. + * You can set an event flag, or you can set multiple flags through OR logic operation. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the event detach failed. + */ +rt_err_t rt_event_send(rt_event_t event, rt_uint32_t set) +{ + struct rt_list_node *n; + struct rt_thread *thread; + rt_base_t level; + rt_base_t status; + rt_bool_t need_schedule; + + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + + if (set == 0) + return -RT_ERROR; + + need_schedule = RT_FALSE; + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* set event */ + event->set |= set; + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(event->parent.parent))); + + if (!rt_list_isempty(&event->parent.suspend_thread)) + { + /* search thread list to resume thread */ + n = event->parent.suspend_thread.next; + while (n != &(event->parent.suspend_thread)) + { + /* get thread */ + thread = rt_list_entry(n, struct rt_thread, tlist); + + status = -RT_ERROR; + if (thread->event_info & RT_EVENT_FLAG_AND) + { + if ((thread->event_set & event->set) == thread->event_set) + { + /* received an AND event */ + status = RT_EOK; + } + } + else if (thread->event_info & RT_EVENT_FLAG_OR) + { + if (thread->event_set & event->set) + { + /* save the received event set */ + thread->event_set = thread->event_set & event->set; + + /* received an OR event */ + status = RT_EOK; + } + } + else + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EINVAL; + } + + /* move node to the next */ + n = n->next; + + /* condition is satisfied, resume thread */ + if (status == RT_EOK) + { + /* clear event */ + if (thread->event_info & RT_EVENT_FLAG_CLEAR) + event->set &= ~thread->event_set; + + /* resume thread, and thread list breaks out */ + rt_thread_resume(thread); + thread->error = RT_EOK; + + /* need do a scheduling */ + need_schedule = RT_TRUE; + } + } + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do a schedule */ + if (need_schedule == RT_TRUE) + rt_schedule(); + + return RT_EOK; +} +RTM_EXPORT(rt_event_send); + + +/** + * @brief This function will receive an event from event object. if the event is unavailable, the thread shall wait for + * the event up to a specified time. + * + * @note If there are threads suspended on this semaphore, the first thread in the list of this semaphore object + * will be resumed, and a thread scheduling (rt_schedule) will be executed. + * If no threads are suspended on this semaphore, the count value sem->value of this semaphore will increase by 1. + * + * @param event is a pointer to the event object to be received. + * + * @param set is a flag that you will set for this event's flag. + * You can set an event flag, or you can set multiple flags through OR logic operation. + * + * @param option is the option of this receiving event, it indicates how the receiving event is operated. + * The option can be one or more of the following values, When selecting multiple values,use logical OR to operate. + * (NOTE: RT_EVENT_FLAG_OR and RT_EVENT_FLAG_AND can only select one): + * + * + * RT_EVENT_FLAG_OR The thread select to use logical OR to receive the event. + * + * RT_EVENT_FLAG_AND The thread select to use logical OR to receive the event. + * + * RT_EVENT_FLAG_CLEAR When the thread receives the corresponding event, the function + * determines whether to clear the event flag. + * + * @param timeout is a timeout period (unit: an OS tick). + * + * @param recved is a pointer to the received event. If you don't care about this value, you can use RT_NULL to set. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the semaphore release failed. + */ +static rt_err_t _rt_event_recv(rt_event_t event, + rt_uint32_t set, + rt_uint8_t option, + rt_int32_t timeout, + rt_uint32_t *recved, + int suspend_flag) +{ + struct rt_thread *thread; + rt_base_t level; + rt_base_t status; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE); + + if (set == 0) + return -RT_ERROR; + + /* initialize status */ + status = -RT_ERROR; + /* get current thread */ + thread = rt_thread_self(); + /* reset thread error */ + thread->error = -RT_EINTR; + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(event->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* check event set */ + if (option & RT_EVENT_FLAG_AND) + { + if ((event->set & set) == set) + status = RT_EOK; + } + else if (option & RT_EVENT_FLAG_OR) + { + if (event->set & set) + status = RT_EOK; + } + else + { + /* either RT_EVENT_FLAG_AND or RT_EVENT_FLAG_OR should be set */ + RT_ASSERT(0); + } + + if (status == RT_EOK) + { + thread->error = RT_EOK; + + /* set received event */ + if (recved) + *recved = (event->set & set); + + /* fill thread event info */ + thread->event_set = (event->set & set); + thread->event_info = option; + + /* received event */ + if (option & RT_EVENT_FLAG_CLEAR) + event->set &= ~set; + } + else if (timeout == 0) + { + /* no waiting */ + thread->error = -RT_ETIMEOUT; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + else + { + /* fill thread event info */ + thread->event_set = set; + thread->event_info = option; + + /* put thread to suspended thread list */ + ret = _ipc_list_suspend(&(event->parent.suspend_thread), + thread, + event->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* if there is a waiting timeout, active thread timer */ + if (timeout > 0) + { + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* do a schedule */ + rt_schedule(); + + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* received an event, disable interrupt to protect */ + level = rt_hw_interrupt_disable(); + + /* set received event */ + if (recved) + *recved = thread->event_set; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(event->parent.parent))); + + return thread->error; +} + +rt_err_t rt_event_recv(rt_event_t event, + rt_uint32_t set, + rt_uint8_t option, + rt_int32_t timeout, + rt_uint32_t *recved) +{ + return _rt_event_recv(event, set, option, timeout, recved, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_event_recv); + +rt_err_t rt_event_recv_interruptible(rt_event_t event, + rt_uint32_t set, + rt_uint8_t option, + rt_int32_t timeout, + rt_uint32_t *recved) +{ + return _rt_event_recv(event, set, option, timeout, recved, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_event_recv_interruptible); + +rt_err_t rt_event_recv_killable(rt_event_t event, + rt_uint32_t set, + rt_uint8_t option, + rt_int32_t timeout, + rt_uint32_t *recved) +{ + return _rt_event_recv(event, set, option, timeout, recved, RT_KILLABLE); +} +RTM_EXPORT(rt_event_recv_killable); +/** + * @brief This function will set some extra attributions of an event object. + * + * @note Currently this function only supports the RT_IPC_CMD_RESET command to reset the event. + * + * @param event is a pointer to an event object. + * + * @param cmd is a command word used to configure some attributions of the event. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_event_control(rt_event_t event, int cmd, void *arg) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(event != RT_NULL); + RT_ASSERT(rt_object_get_type(&event->parent.parent) == RT_Object_Class_Event); + + if (cmd == RT_IPC_CMD_RESET) + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* resume all waiting thread */ + _ipc_list_resume_all(&event->parent.suspend_thread); + + /* initialize event set */ + event->set = 0; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_event_control); + +/**@}*/ +#endif /* RT_USING_EVENT */ + +#ifdef RT_USING_MAILBOX +/** + * @addtogroup mailbox + * @{ + */ + +/** + * @brief Initialize a static mailbox object. + * + * @note For the static mailbox object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_mb_create() function will allocate memory space automatically and initialize the mailbox. + * + * @see rt_mb_create() + * + * @param mb is a pointer to the mailbox to initialize. + * It is assumed that storage for the mailbox will be allocated in your application. + * + * @param name is a pointer to the name that given to the mailbox. + * + * @param msgpool the begin address of buffer to save received mail. + * + * @param size is the maximum number of mails in the mailbox. + * For example, when the mailbox buffer capacity is N, size is N/4. + * + * @param flag is the mailbox flag, which determines the queuing way of how multiple threads wait + * when the mailbox is not available. + * The mailbox flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this mailbox will become non-real-time threads. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_mb_init(rt_mailbox_t mb, + const char *name, + void *msgpool, + rt_size_t size, + rt_uint8_t flag) +{ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(mb->parent.parent), RT_Object_Class_MailBox, name); + + /* set parent flag */ + mb->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(mb->parent)); + + /* initialize mailbox */ + mb->msg_pool = (rt_ubase_t *)msgpool; + mb->size = (rt_uint16_t)size; + mb->entry = 0; + mb->in_offset = 0; + mb->out_offset = 0; + + /* initialize an additional list of sender suspend thread */ + rt_list_init(&(mb->suspend_sender_thread)); + + return RT_EOK; +} +RTM_EXPORT(rt_mb_init); + + +/** + * @brief This function will detach a static mailbox object. + * + * @note This function is used to detach a static mailbox object which is initialized by rt_mb_init() function. + * By contrast, the rt_mb_delete() function will delete a mailbox object. + * When the mailbox is successfully detached, it will resume all suspended threads in the mailbox list. + * + * @see rt_mb_delete() + * + * @param mb is a pointer to a mailbox object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the mailbox detach failed. + * + * @warning This function can ONLY detach a static mailbox initialized by the rt_mb_init() function. + * If the mailbox is created by the rt_mb_create() function, you MUST NOT USE this function to detach it, + * ONLY USE the rt_mb_delete() function to complete the deletion. + */ +rt_err_t rt_mb_detach(rt_mailbox_t mb) +{ + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + RT_ASSERT(rt_object_is_systemobject(&mb->parent.parent)); + + /* resume all suspended thread */ + _ipc_list_resume_all(&(mb->parent.suspend_thread)); + /* also resume all mailbox private suspended thread */ + _ipc_list_resume_all(&(mb->suspend_sender_thread)); + + /* detach mailbox object */ + rt_object_detach(&(mb->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mb_detach); + +#ifdef RT_USING_HEAP +/** + * @brief Creating a mailbox object. + * + * @note For the mailbox object, its memory space is allocated automatically. + * By contrast, the rt_mb_init() function will initialize a static mailbox object. + * + * @see rt_mb_init() + * + * @param name is a pointer that given to the mailbox. + * + * @param size is the maximum number of mails in the mailbox. + * For example, when mailbox buffer capacity is N, size is N/4. + * + * @param flag is the mailbox flag, which determines the queuing way of how multiple threads wait + * when the mailbox is not available. + * The mailbox flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this mailbox will become non-real-time threads. + * + * @return Return a pointer to the mailbox object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_mailbox_t rt_mb_create(const char *name, rt_size_t size, rt_uint8_t flag) +{ + rt_mailbox_t mb; + + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + mb = (rt_mailbox_t)rt_object_allocate(RT_Object_Class_MailBox, name); + if (mb == RT_NULL) + return mb; + + /* set parent */ + mb->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(mb->parent)); + + /* initialize mailbox */ + mb->size = (rt_uint16_t)size; + mb->msg_pool = (rt_ubase_t *)RT_KERNEL_MALLOC(mb->size * sizeof(rt_ubase_t)); + if (mb->msg_pool == RT_NULL) + { + /* delete mailbox object */ + rt_object_delete(&(mb->parent.parent)); + + return RT_NULL; + } + mb->entry = 0; + mb->in_offset = 0; + mb->out_offset = 0; + + /* initialize an additional list of sender suspend thread */ + rt_list_init(&(mb->suspend_sender_thread)); + + return mb; +} +RTM_EXPORT(rt_mb_create); + + +/** + * @brief This function will delete a mailbox object and release the memory space. + * + * @note This function is used to delete a mailbox object which is created by the rt_mb_create() function. + * By contrast, the rt_mb_detach() function will detach a static mailbox object. + * When the mailbox is successfully deleted, it will resume all suspended threads in the mailbox list. + * + * @see rt_mb_detach() + * + * @param mb is a pointer to a mailbox object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + * + * @warning This function can only delete mailbox created by the rt_mb_create() function. + * If the mailbox is initialized by the rt_mb_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_mb_detach() function to complete the detachment. + */ +rt_err_t rt_mb_delete(rt_mailbox_t mb) +{ + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + RT_ASSERT(rt_object_is_systemobject(&mb->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* resume all suspended thread */ + _ipc_list_resume_all(&(mb->parent.suspend_thread)); + + /* also resume all mailbox private suspended thread */ + _ipc_list_resume_all(&(mb->suspend_sender_thread)); + + /* free mailbox pool */ + RT_KERNEL_FREE(mb->msg_pool); + + /* delete mailbox object */ + rt_object_delete(&(mb->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mb_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will send an mail to the mailbox object. If there is a thread suspended on the mailbox, + * the thread will be resumed. + * + * @note When using this function to send a mail, if the mailbox if fully used, the current thread will + * wait for a timeout. If the set timeout time is reached and there is still no space available, + * the sending thread will be resumed and an error code will be returned. + * By contrast, the rt_mb_send() function will return an error code immediately without waiting time + * when the mailbox if fully used. + * + * @see rt_mb_send() + * + * @param mb is a pointer to the mailbox object to be sent. + * + * @param value is a value to the content of the mail you want to send. + * + * @param timeout is a timeout period (unit: an OS tick). + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + * + * @warning This function can be called in interrupt context and thread context. + */ +static rt_err_t _rt_mb_send_wait(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout, + int suspend_flag) +{ + struct rt_thread *thread; + rt_base_t level; + rt_uint32_t tick_delta; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0); + + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mb->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* for non-blocking call */ + if (mb->entry == mb->size && timeout == 0) + { + rt_hw_interrupt_enable(level); + return -RT_EFULL; + } + + /* mailbox is full */ + while (mb->entry == mb->size) + { + /* reset error number in thread */ + thread->error = -RT_EINTR; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EFULL; + } + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mb->suspend_sender_thread), + thread, + mb->parent.parent.flag, + suspend_flag); + + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mb_send_wait: start timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* re-schedule */ + rt_schedule(); + + /* resume from suspend state */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + + /* set ptr */ + mb->msg_pool[mb->in_offset] = value; + /* increase input offset */ + ++ mb->in_offset; + if (mb->in_offset >= mb->size) + mb->in_offset = 0; + + if(mb->entry < RT_MB_ENTRY_MAX) + { + /* increase message entry */ + mb->entry ++; + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + + /* resume suspended thread */ + if (!rt_list_isempty(&mb->parent.suspend_thread)) + { + _ipc_list_resume(&(mb->parent.suspend_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} + +rt_err_t rt_mb_send_wait(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout) +{ + return _rt_mb_send_wait(mb, value, timeout, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mb_send_wait); + +rt_err_t rt_mb_send_wait_interruptible(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout) +{ + return _rt_mb_send_wait(mb, value, timeout, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mb_send_wait_interruptible); + +rt_err_t rt_mb_send_wait_killable(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout) +{ + return _rt_mb_send_wait(mb, value, timeout, RT_KILLABLE); +} +RTM_EXPORT(rt_mb_send_wait_killable); +/** + * @brief This function will send an mail to the mailbox object. If there is a thread suspended on the mailbox, + * the thread will be resumed. + * + * @note When using this function to send a mail, if the mailbox is fully used, this function will return an error + * code immediately without waiting time. + * By contrast, the rt_mb_send_wait() function is set a timeout to wait for the mail to be sent. + * + * @see rt_mb_send_wait() + * + * @param mb is a pointer to the mailbox object to be sent. + * + * @param value is a value to the content of the mail you want to send. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + */ +rt_err_t rt_mb_send(rt_mailbox_t mb, rt_ubase_t value) +{ + return rt_mb_send_wait(mb, value, 0); +} +RTM_EXPORT(rt_mb_send); + +rt_err_t rt_mb_send_interruptible(rt_mailbox_t mb, rt_ubase_t value) +{ + return rt_mb_send_wait_interruptible(mb, value, 0); +} +RTM_EXPORT(rt_mb_send_interruptible); + +rt_err_t rt_mb_send_killable(rt_mailbox_t mb, rt_ubase_t value) +{ + return rt_mb_send_wait_killable(mb, value, 0); +} +RTM_EXPORT(rt_mb_send_killable); + +/** + * @brief This function will send an urgent mail to the mailbox object. + * + * @note This function is almost the same as the rt_mb_send() function. The only difference is that + * when sending an urgent mail, the mail will be placed at the head of the mail queue so that + * the recipient can receive the urgent mail first. + * + * @see rt_mb_send() + * + * @param mb is a pointer to the mailbox object to be sent. + * + * @param value is the content of the mail you want to send. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + */ +rt_err_t rt_mb_urgent(rt_mailbox_t mb, rt_ubase_t value) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mb->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + if (mb->entry == mb->size) + { + rt_hw_interrupt_enable(level); + return -RT_EFULL; + } + + /* rewind to the previous position */ + if (mb->out_offset > 0) + { + mb->out_offset --; + } + else + { + mb->out_offset = mb->size - 1; + } + + /* set ptr */ + mb->msg_pool[mb->out_offset] = value; + + /* increase message entry */ + mb->entry ++; + + /* resume suspended thread */ + if (!rt_list_isempty(&mb->parent.suspend_thread)) + { + _ipc_list_resume(&(mb->parent.suspend_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} +RTM_EXPORT(rt_mb_urgent); + + +/** + * @brief This function will receive a mail from mailbox object, if there is no mail in mailbox object, + * the thread shall wait for a specified time. + * + * @note Only when there is mail in the mailbox, the receiving thread can get the mail immediately and + * return RT_EOK, otherwise the receiving thread will be suspended until the set timeout. If the mail + * is still not received within the specified time, it will return-RT_ETIMEOUT. + * + * @param mb is a pointer to the mailbox object to be received. + * + * @param value is a flag that you will set for this mailbox's flag. + * You can set an mailbox flag, or you can set multiple flags through OR logic operations. + * + * @param timeout is a timeout period (unit: an OS tick). If the mailbox object is not avaliable in the queue, + * the thread will wait for the object in the queue up to the amount of time specified by this parameter. + * + * NOTE: + * If use Macro RT_WAITING_FOREVER to set this parameter, which means that when the + * mailbox object is unavailable in the queue, the thread will be waiting forever. + * If use macro RT_WAITING_NO to set this parameter, which means that this + * function is non-blocking and will return immediately. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox release failed. + */ +static rt_err_t _rt_mb_recv(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout, int suspend_flag) +{ + struct rt_thread *thread; + rt_base_t level; + rt_uint32_t tick_delta; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0); + + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(mb->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* for non-blocking call */ + if (mb->entry == 0 && timeout == 0) + { + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + + /* mailbox is empty */ + while (mb->entry == 0) + { + /* reset error number in thread */ + thread->error = -RT_EINTR; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + thread->error = -RT_ETIMEOUT; + + return -RT_ETIMEOUT; + } + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mb->parent.suspend_thread), + thread, + mb->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mb_recv: start timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* re-schedule */ + rt_schedule(); + + /* resume from suspend state */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + + /* fill ptr */ + *value = mb->msg_pool[mb->out_offset]; + + /* increase output offset */ + ++ mb->out_offset; + if (mb->out_offset >= mb->size) + mb->out_offset = 0; + + /* decrease message entry */ + if(mb->entry > 0) + { + mb->entry --; + } + + /* resume suspended thread */ + if (!rt_list_isempty(&(mb->suspend_sender_thread))) + { + _ipc_list_resume(&(mb->suspend_sender_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mb->parent.parent))); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mb->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_mb_recv(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout) +{ + return _rt_mb_recv(mb, value, timeout, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mb_recv); + +rt_err_t rt_mb_recv_interruptibale(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout) +{ + return _rt_mb_recv(mb, value, timeout, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mb_recv_interruptibale); + +rt_err_t rt_mb_recv_killable(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout) +{ + return _rt_mb_recv(mb, value, timeout, RT_KILLABLE); +} +RTM_EXPORT(rt_mb_recv_killable); + +/** + * @brief This function will set some extra attributions of a mailbox object. + * + * @note Currently this function only supports the RT_IPC_CMD_RESET command to reset the mailbox. + * + * @param mb is a pointer to a mailbox object. + * + * @param cmd is a command used to configure some attributions of the mailbox. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_mb_control(rt_mailbox_t mb, int cmd, void *arg) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(mb != RT_NULL); + RT_ASSERT(rt_object_get_type(&mb->parent.parent) == RT_Object_Class_MailBox); + + if (cmd == RT_IPC_CMD_RESET) + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* resume all waiting thread */ + _ipc_list_resume_all(&(mb->parent.suspend_thread)); + /* also resume all mailbox private suspended thread */ + _ipc_list_resume_all(&(mb->suspend_sender_thread)); + + /* re-init mailbox */ + mb->entry = 0; + mb->in_offset = 0; + mb->out_offset = 0; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_mb_control); + +/**@}*/ +#endif /* RT_USING_MAILBOX */ + +#ifdef RT_USING_MESSAGEQUEUE +/** + * @addtogroup messagequeue + * @{ + */ + +struct rt_mq_message +{ + struct rt_mq_message *next; +}; + + +/** + * @brief Initialize a static messagequeue object. + * + * @note For the static messagequeue object, its memory space is allocated by the compiler during compiling, + * and shall placed on the read-write data segment or on the uninitialized data segment. + * By contrast, the rt_mq_create() function will allocate memory space automatically + * and initialize the messagequeue. + * + * @see rt_mq_create() + * + * @param mq is a pointer to the messagequeue to initialize. It is assumed that storage for + * the messagequeue will be allocated in your application. + * + * @param name is a pointer to the name that given to the messagequeue. + * + * @param msgpool is a pointer to the starting address of the memory space you allocated for + * the messagequeue in advance. + * In other words, msgpool is a pointer to the messagequeue buffer of the starting address. + * + * @param msg_size is the maximum length of a message in the messagequeue (Unit: Byte). + * + * @param pool_size is the size of the memory space allocated for the messagequeue in advance. + * + * @param flag is the messagequeue flag, which determines the queuing way of how multiple threads wait + * when the messagequeue is not available. + * The messagequeue flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this messagequeue will become non-real-time threads. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it represents the initialization failed. + * + * @warning This function can ONLY be called from threads. + */ +rt_err_t rt_mq_init(rt_mq_t mq, + const char *name, + void *msgpool, + rt_size_t msg_size, + rt_size_t pool_size, + rt_uint8_t flag) +{ + struct rt_mq_message *head; + rt_base_t temp; + register rt_size_t msg_align_size; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(mq->parent.parent), RT_Object_Class_MessageQueue, name); + + /* set parent flag */ + mq->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(mq->parent)); + + /* set message pool */ + mq->msg_pool = msgpool; + + /* get correct message size */ + msg_align_size = RT_ALIGN(msg_size, RT_ALIGN_SIZE); + mq->msg_size = msg_size; + mq->max_msgs = pool_size / (msg_align_size + sizeof(struct rt_mq_message)); + + if (0 == mq->max_msgs) + { + return -RT_EINVAL; + } + + /* initialize message list */ + mq->msg_queue_head = RT_NULL; + mq->msg_queue_tail = RT_NULL; + + /* initialize message empty list */ + mq->msg_queue_free = RT_NULL; + for (temp = 0; temp < mq->max_msgs; temp ++) + { + head = (struct rt_mq_message *)((rt_uint8_t *)mq->msg_pool + + temp * (msg_align_size + sizeof(struct rt_mq_message))); + head->next = (struct rt_mq_message *)mq->msg_queue_free; + mq->msg_queue_free = head; + } + + /* the initial entry is zero */ + mq->entry = 0; + + /* initialize an additional list of sender suspend thread */ + rt_list_init(&(mq->suspend_sender_thread)); + + return RT_EOK; +} +RTM_EXPORT(rt_mq_init); + + +/** + * @brief This function will detach a static messagequeue object. + * + * @note This function is used to detach a static messagequeue object which is initialized by rt_mq_init() function. + * By contrast, the rt_mq_delete() function will delete a messagequeue object. + * When the messagequeue is successfully detached, it will resume all suspended threads in the messagequeue list. + * + * @see rt_mq_delete() + * + * @param mq is a pointer to a messagequeue object to be detached. + * + * @return Return the operation status. When the return value is RT_EOK, the initialization is successful. + * If the return value is any other values, it means that the messagequeue detach failed. + * + * @warning This function can ONLY detach a static messagequeue initialized by the rt_mq_init() function. + * If the messagequeue is created by the rt_mq_create() function, you MUST NOT USE this function to detach it, + * and ONLY USE the rt_mq_delete() function to complete the deletion. + */ +rt_err_t rt_mq_detach(rt_mq_t mq) +{ + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(rt_object_is_systemobject(&mq->parent.parent)); + + /* resume all suspended thread */ + _ipc_list_resume_all(&mq->parent.suspend_thread); + /* also resume all message queue private suspended thread */ + _ipc_list_resume_all(&(mq->suspend_sender_thread)); + + /* detach message queue object */ + rt_object_detach(&(mq->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mq_detach); + +#ifdef RT_USING_HEAP +/** + * @brief Creating a messagequeue object. + * + * @note For the messagequeue object, its memory space is allocated automatically. + * By contrast, the rt_mq_init() function will initialize a static messagequeue object. + * + * @see rt_mq_init() + * + * @param name is a pointer that given to the messagequeue. + * + * @param msg_size is the maximum length of a message in the messagequeue (Unit: Byte). + * + * @param max_msgs is the maximum number of messages in the messagequeue. + * + * @param flag is the messagequeue flag, which determines the queuing way of how multiple threads wait + * when the messagequeue is not available. + * The messagequeue flag can be ONE of the following values: + * + * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority. + * + * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method + * (also known as first-come-first-served (FCFS) scheduling strategy). + * + * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to + * use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about + * the first-in-first-out principle, and you clearly understand that all threads involved in + * this messagequeue will become non-real-time threads. + * + * @return Return a pointer to the messagequeue object. When the return value is RT_NULL, it means the creation failed. + * + * @warning This function can NOT be called in interrupt context. You can use macor RT_DEBUG_NOT_IN_INTERRUPT to check it. + */ +rt_mq_t rt_mq_create(const char *name, + rt_size_t msg_size, + rt_size_t max_msgs, + rt_uint8_t flag) +{ + struct rt_messagequeue *mq; + struct rt_mq_message *head; + rt_base_t temp; + register rt_size_t msg_align_size; + + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* allocate object */ + mq = (rt_mq_t)rt_object_allocate(RT_Object_Class_MessageQueue, name); + if (mq == RT_NULL) + return mq; + + /* set parent */ + mq->parent.parent.flag = flag; + + /* initialize ipc object */ + _ipc_object_init(&(mq->parent)); + + /* initialize message queue */ + + /* get correct message size */ + msg_align_size = RT_ALIGN(msg_size, RT_ALIGN_SIZE); + mq->msg_size = msg_size; + mq->max_msgs = max_msgs; + + /* allocate message pool */ + mq->msg_pool = RT_KERNEL_MALLOC((msg_align_size + sizeof(struct rt_mq_message)) * mq->max_msgs); + if (mq->msg_pool == RT_NULL) + { + rt_object_delete(&(mq->parent.parent)); + + return RT_NULL; + } + + /* initialize message list */ + mq->msg_queue_head = RT_NULL; + mq->msg_queue_tail = RT_NULL; + + /* initialize message empty list */ + mq->msg_queue_free = RT_NULL; + for (temp = 0; temp < mq->max_msgs; temp ++) + { + head = (struct rt_mq_message *)((rt_uint8_t *)mq->msg_pool + + temp * (msg_align_size + sizeof(struct rt_mq_message))); + head->next = (struct rt_mq_message *)mq->msg_queue_free; + mq->msg_queue_free = head; + } + + /* the initial entry is zero */ + mq->entry = 0; + + /* initialize an additional list of sender suspend thread */ + rt_list_init(&(mq->suspend_sender_thread)); + + return mq; +} +RTM_EXPORT(rt_mq_create); + + +/** + * @brief This function will delete a messagequeue object and release the memory. + * + * @note This function is used to delete a messagequeue object which is created by the rt_mq_create() function. + * By contrast, the rt_mq_detach() function will detach a static messagequeue object. + * When the messagequeue is successfully deleted, it will resume all suspended threads in the messagequeue list. + * + * @see rt_mq_detach() + * + * @param mq is a pointer to a messagequeue object to be deleted. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the messagequeue detach failed. + * + * @warning This function can ONLY delete a messagequeue initialized by the rt_mq_create() function. + * If the messagequeue is initialized by the rt_mq_init() function, you MUST NOT USE this function to delete it, + * ONLY USE the rt_mq_detach() function to complete the detachment. + * for example,the rt_mq_create() function, it cannot be called in interrupt context. + */ +rt_err_t rt_mq_delete(rt_mq_t mq) +{ + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(rt_object_is_systemobject(&mq->parent.parent) == RT_FALSE); + + RT_DEBUG_NOT_IN_INTERRUPT; + + /* resume all suspended thread */ + _ipc_list_resume_all(&(mq->parent.suspend_thread)); + /* also resume all message queue private suspended thread */ + _ipc_list_resume_all(&(mq->suspend_sender_thread)); + + /* free message queue pool */ + RT_KERNEL_FREE(mq->msg_pool); + + /* delete message queue object */ + rt_object_delete(&(mq->parent.parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_mq_delete); +#endif /* RT_USING_HEAP */ + + +/** + * @brief This function will send a message to the messagequeue object. If + * there is a thread suspended on the messagequeue, the thread will be + * resumed. + * + * @note When using this function to send a message, if the messagequeue is + * fully used, the current thread will wait for a timeout. If reaching + * the timeout and there is still no space available, the sending + * thread will be resumed and an error code will be returned. By + * contrast, the rt_mq_send() function will return an error code + * immediately without waiting when the messagequeue if fully used. + * + * @see rt_mq_send() + * + * @param mq is a pointer to the messagequeue object to be sent. + * + * @param buffer is the content of the message. + * + * @param size is the length of the message(Unit: Byte). + * + * @param timeout is a timeout period (unit: an OS tick). + * + * @return Return the operation status. When the return value is RT_EOK, the + * operation is successful. If the return value is any other values, + * it means that the messagequeue detach failed. + * + * @warning This function can be called in interrupt context and thread + * context. + */ +static rt_err_t _rt_mq_send_wait(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout, + int suspend_flag) +{ + rt_base_t level; + struct rt_mq_message *msg; + rt_uint32_t tick_delta; + struct rt_thread *thread; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(buffer != RT_NULL); + RT_ASSERT(size != 0); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0); + + /* greater than one message size */ + if (size > mq->msg_size) + return -RT_ERROR; + + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mq->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* get a free list, there must be an empty item */ + msg = (struct rt_mq_message *)mq->msg_queue_free; + /* for non-blocking call */ + if (msg == RT_NULL && timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EFULL; + } + + /* message queue is full */ + while ((msg = (struct rt_mq_message *)mq->msg_queue_free) == RT_NULL) + { + /* reset error number in thread */ + thread->error = -RT_EINTR; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EFULL; + } + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mq->suspend_sender_thread), + thread, + mq->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("mq_send_wait: start timer of thread:%s\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* re-schedule */ + rt_schedule(); + + /* resume from suspend state */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + + /* move free list pointer */ + mq->msg_queue_free = msg->next; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* the msg is the new tailer of list, the next shall be NULL */ + msg->next = RT_NULL; + /* copy buffer */ + rt_memcpy(msg + 1, buffer, size); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + /* link msg to message queue */ + if (mq->msg_queue_tail != RT_NULL) + { + /* if the tail exists, */ + ((struct rt_mq_message *)mq->msg_queue_tail)->next = msg; + } + + /* set new tail */ + mq->msg_queue_tail = msg; + /* if the head is empty, set head */ + if (mq->msg_queue_head == RT_NULL) + mq->msg_queue_head = msg; + + if(mq->entry < RT_MQ_ENTRY_MAX) + { + /* increase message entry */ + mq->entry ++; + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + + /* resume suspended thread */ + if (!rt_list_isempty(&mq->parent.suspend_thread)) + { + _ipc_list_resume(&(mq->parent.suspend_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} + +rt_err_t rt_mq_send_wait(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_send_wait(mq, buffer, size, timeout, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mq_send_wait) + +rt_err_t rt_mq_send_wait_interruptible(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_send_wait(mq, buffer, size, timeout, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mq_send_wait_interruptible) + +rt_err_t rt_mq_send_wait_killable(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_send_wait(mq, buffer, size, timeout, RT_KILLABLE); +} +RTM_EXPORT(rt_mq_send_wait_killable) +/** + * @brief This function will send a message to the messagequeue object. + * If there is a thread suspended on the messagequeue, the thread will be resumed. + * + * @note When using this function to send a message, if the messagequeue is fully used, + * the current thread will wait for a timeout. + * By contrast, when the messagequeue is fully used, the rt_mq_send_wait() function will + * return an error code immediately without waiting. + * + * @see rt_mq_send_wait() + * + * @param mq is a pointer to the messagequeue object to be sent. + * + * @param buffer is the content of the message. + * + * @param size is the length of the message(Unit: Byte). + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the messagequeue detach failed. + * + * @warning This function can be called in interrupt context and thread context. + */ +rt_err_t rt_mq_send(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + return rt_mq_send_wait(mq, buffer, size, 0); +} +RTM_EXPORT(rt_mq_send); + +rt_err_t rt_mq_send_interrupt(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + return rt_mq_send_wait_interruptible(mq, buffer, size, 0); +} +RTM_EXPORT(rt_mq_send_interrupt); + +rt_err_t rt_mq_send_killable(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + return rt_mq_send_wait_killable(mq, buffer, size, 0); +} +RTM_EXPORT(rt_mq_send_killable); +/** + * @brief This function will send an urgent message to the messagequeue object. + * + * @note This function is almost the same as the rt_mq_send() function. The only difference is that + * when sending an urgent message, the message is placed at the head of the messagequeue so that + * the recipient can receive the urgent message first. + * + * @see rt_mq_send() + * + * @param mq is a pointer to the messagequeue object to be sent. + * + * @param buffer is the content of the message. + * + * @param size is the length of the message(Unit: Byte). + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox detach failed. + */ +rt_err_t rt_mq_urgent(rt_mq_t mq, const void *buffer, rt_size_t size) +{ + rt_base_t level; + struct rt_mq_message *msg; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(buffer != RT_NULL); + RT_ASSERT(size != 0); + + /* greater than one message size */ + if (size > mq->msg_size) + return -RT_ERROR; + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mq->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* get a free list, there must be an empty item */ + msg = (struct rt_mq_message *)mq->msg_queue_free; + /* message queue is full */ + if (msg == RT_NULL) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return -RT_EFULL; + } + /* move free list pointer */ + mq->msg_queue_free = msg->next; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* copy buffer */ + rt_memcpy(msg + 1, buffer, size); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* link msg to the beginning of message queue */ + msg->next = (struct rt_mq_message *)mq->msg_queue_head; + mq->msg_queue_head = msg; + + /* if there is no tail */ + if (mq->msg_queue_tail == RT_NULL) + mq->msg_queue_tail = msg; + + if(mq->entry < RT_MQ_ENTRY_MAX) + { + /* increase message entry */ + mq->entry ++; + } + else + { + rt_hw_interrupt_enable(level); /* enable interrupt */ + return -RT_EFULL; /* value overflowed */ + } + + /* resume suspended thread */ + if (!rt_list_isempty(&mq->parent.suspend_thread)) + { + _ipc_list_resume(&(mq->parent.suspend_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + return RT_EOK; +} +RTM_EXPORT(rt_mq_urgent); + + +/** + * @brief This function will receive a message from message queue object, + * if there is no message in messagequeue object, the thread shall wait for a specified time. + * + * @note Only when there is mail in the mailbox, the receiving thread can get the mail immediately and return RT_EOK, + * otherwise the receiving thread will be suspended until timeout. + * If the mail is not received within the specified time, it will return -RT_ETIMEOUT. + * + * @param mq is a pointer to the messagequeue object to be received. + * + * @param buffer is the content of the message. + * + * @param size is the length of the message(Unit: Byte). + * + * @param timeout is a timeout period (unit: an OS tick). If the message is unavailable, the thread will wait for + * the message in the queue up to the amount of time specified by this parameter. + * + * NOTE: + * If use Macro RT_WAITING_FOREVER to set this parameter, which means that when the + * message is unavailable in the queue, the thread will be waiting forever. + * If use macro RT_WAITING_NO to set this parameter, which means that this + * function is non-blocking and will return immediately. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that the mailbox release failed. + */ +static rt_err_t _rt_mq_recv(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout, + int suspend_flag) +{ + struct rt_thread *thread; + rt_base_t level; + struct rt_mq_message *msg; + rt_uint32_t tick_delta; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + RT_ASSERT(buffer != RT_NULL); + RT_ASSERT(size != 0); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(timeout != 0); + + /* initialize delta tick */ + tick_delta = 0; + /* get current thread */ + thread = rt_thread_self(); + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(mq->parent.parent))); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* for non-blocking call */ + if (mq->entry == 0 && timeout == 0) + { + rt_hw_interrupt_enable(level); + + return -RT_ETIMEOUT; + } + + /* message queue is empty */ + while (mq->entry == 0) + { + /* reset error number in thread */ + thread->error = -RT_EINTR; + + /* no waiting, return timeout */ + if (timeout == 0) + { + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + thread->error = -RT_ETIMEOUT; + + return -RT_ETIMEOUT; + } + + /* suspend current thread */ + ret = _ipc_list_suspend(&(mq->parent.suspend_thread), + thread, + mq->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_hw_interrupt_enable(level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + /* get the start tick of timer */ + tick_delta = rt_tick_get(); + + RT_DEBUG_LOG(RT_DEBUG_IPC, ("set thread:%s to timer list\n", + thread->name)); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* re-schedule */ + rt_schedule(); + + /* recv message */ + if (thread->error != RT_EOK) + { + /* return error */ + return thread->error; + } + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* if it's not waiting forever and then re-calculate timeout tick */ + if (timeout > 0) + { + tick_delta = rt_tick_get() - tick_delta; + timeout -= tick_delta; + if (timeout < 0) + timeout = 0; + } + } + + /* get message from queue */ + msg = (struct rt_mq_message *)mq->msg_queue_head; + + /* move message queue head */ + mq->msg_queue_head = msg->next; + /* reach queue tail, set to NULL */ + if (mq->msg_queue_tail == msg) + mq->msg_queue_tail = RT_NULL; + + /* decrease message entry */ + if(mq->entry > 0) + { + mq->entry --; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + /* copy message */ + rt_memcpy(buffer, msg + 1, size > mq->msg_size ? mq->msg_size : size); + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + /* put message to free list */ + msg->next = (struct rt_mq_message *)mq->msg_queue_free; + mq->msg_queue_free = msg; + + /* resume suspended thread */ + if (!rt_list_isempty(&(mq->suspend_sender_thread))) + { + _ipc_list_resume(&(mq->suspend_sender_thread)); + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mq->parent.parent))); + + rt_schedule(); + + return RT_EOK; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mq->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_mq_recv(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_recv(mq, buffer, size, timeout, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_mq_recv); + +rt_err_t rt_mq_recv_interruptible(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_recv(mq, buffer, size, timeout, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_mq_recv_interruptible); + +rt_err_t rt_mq_recv_killable(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout) +{ + return _rt_mq_recv(mq, buffer, size, timeout, RT_KILLABLE); +} +RTM_EXPORT(rt_mq_recv_killable); +/** + * @brief This function will set some extra attributions of a messagequeue object. + * + * @note Currently this function only supports the RT_IPC_CMD_RESET command to reset the messagequeue. + * + * @param mq is a pointer to a messagequeue object. + * + * @param cmd is a command used to configure some attributions of the messagequeue. + * + * @param arg is the argument of the function to execute the command. + * + * @return Return the operation status. When the return value is RT_EOK, the operation is successful. + * If the return value is any other values, it means that this function failed to execute. + */ +rt_err_t rt_mq_control(rt_mq_t mq, int cmd, void *arg) +{ + rt_base_t level; + struct rt_mq_message *msg; + + /* parameter check */ + RT_ASSERT(mq != RT_NULL); + RT_ASSERT(rt_object_get_type(&mq->parent.parent) == RT_Object_Class_MessageQueue); + + if (cmd == RT_IPC_CMD_RESET) + { + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + /* resume all waiting thread */ + _ipc_list_resume_all(&mq->parent.suspend_thread); + /* also resume all message queue private suspended thread */ + _ipc_list_resume_all(&(mq->suspend_sender_thread)); + + /* release all message in the queue */ + while (mq->msg_queue_head != RT_NULL) + { + /* get message from queue */ + msg = (struct rt_mq_message *)mq->msg_queue_head; + + /* move message queue head */ + mq->msg_queue_head = msg->next; + /* reach queue tail, set to NULL */ + if (mq->msg_queue_tail == msg) + mq->msg_queue_tail = RT_NULL; + + /* put message to free list */ + msg->next = (struct rt_mq_message *)mq->msg_queue_free; + mq->msg_queue_free = msg; + } + + /* clean entry */ + mq->entry = 0; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + + rt_schedule(); + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_mq_control); + +/**@}*/ +#endif /* RT_USING_MESSAGEQUEUE */ +/**@}*/ diff --git a/tasks/concur-rtthread-mutex-ceilings/verify.py b/tasks/concur-rtthread-mutex-ceilings/verify.py new file mode 100644 index 00000000..9e2c6c26 --- /dev/null +++ b/tasks/concur-rtthread-mutex-ceilings/verify.py @@ -0,0 +1,130 @@ +"""Run an imported Bos-qiao check.py unchanged; candidate processes run as UID 65534.""" + +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile + +GRADER = Path(__file__).resolve().parent +BLOCKED = "isolation-blocked.txt" +GUARD = 86 +# Runs the original check unchanged as the trusted user. In isolation mode every child process drops to +# UID 65534 and every mkdtemp scratch is handed to it; an audit hook stops the check if candidate code +# would run inside this process. Failing child processes also copy their stderr tail out for private triage. +CHECK = ( + "import os, runpy, subprocess, sys, tempfile\n" + "isolated, sys.argv = sys.argv[1] == '1', sys.argv[2:]\n" + "untrusted = [os.path.realpath(sys.argv[1])]\n" + "def inside(path):\n" + " path = os.path.realpath(str(path))\n" + " return any(path == root or path.startswith(root + os.sep) for root in untrusted)\n" + "spawns = ('os.system', 'os.exec', 'os.spawn', 'os.fork', 'os.forkpty', 'os.posix_spawn') if isolated else ()\n" + "def guard(event, args):\n" + " if (event in spawns or event == 'exec' and inside(getattr(args[0], 'co_filename', '')) or\n" + " event == 'ctypes.dlopen' and args[0] and inside(args[0]) or\n" + " event == 'import' and any(inside(entry or '.') for entry in sys.path)):\n" + " sys.__stderr__.write('rollout-guard: ' + event + '\\n')\n" + " sys.__stderr__.flush()\n" + " os._exit(%d)\n" + "mkdtemp = tempfile.mkdtemp\n" + "def scratch(*args, **kwargs):\n" + " path = mkdtemp(*args, **kwargs)\n" + " untrusted.append(os.path.realpath(path))\n" + " if isolated:\n" + " os.chown(path, 65534, 65534)\n" + " return path\n" + "tempfile.mkdtemp = scratch\n" + "popen = subprocess.Popen.__init__\n" + "def drop(self, *args, **kwargs):\n" + " if isolated:\n" + " kwargs.update(user=65534, group=65534, extra_groups=[])\n" + " popen(self, *args, **kwargs)\n" + "subprocess.Popen.__init__ = drop\n" + "real = subprocess.run\n" + "def run(*args, **kwargs):\n" + " result = real(*args, **kwargs)\n" + " if result.returncode and result.stderr:\n" + " tail = result.stderr if isinstance(result.stderr, str) else result.stderr.decode('utf-8', 'replace')\n" + " sys.__stderr__.write(tail[-2000:] + '\\n')\n" + " return result\n" + "subprocess.run = run\n" + "sys.addaudithook(guard)\n" + "runpy.run_path(sys.argv[0], run_name='__main__')\n" % GUARD) + + +class UnsupportedEnvironment(RuntimeError): + pass + + +def candidate_user(): + os.setgroups([]) + os.setgid(65534) + os.setuid(65534) + + +def isolation(): + if os.environ.get("ROLLOUT_GRADE_ISOLATION") != "uid65534": + return None + if sys.platform != "linux" or os.geteuid() != 0: + raise UnsupportedEnvironment("isolated grader requires a Linux root supervisor") + probe = ( + "from pathlib import Path\n" + "try: Path('/grader/verify.py').read_bytes()\n" + "except PermissionError: raise SystemExit(0)\n" + "raise SystemExit(1)\n" + ) + try: + result = subprocess.run([sys.executable, "-I", "-c", probe], + capture_output=True, timeout=10, preexec_fn=candidate_user) + except subprocess.SubprocessError as error: + raise UnsupportedEnvironment("candidate identity could not be isolated") from error + if result.returncode != 0: + raise UnsupportedEnvironment("candidate can read the private grader or isolation probe failed") + return candidate_user + + +def verify(candidate): + if (GRADER / BLOCKED).exists(): + raise UnsupportedEnvironment("isolation blocked: " + (GRADER / BLOCKED).read_text().strip()[:200]) + isolated = isolation() is not None + if shutil.which("gcc") is None: + raise UnsupportedEnvironment("C compiler unavailable") + with tempfile.TemporaryDirectory(prefix="bos-grade-") as temporary: + root = Path(temporary) + work, grader = root / "work", root / "grader" + shutil.copytree(candidate, work, symlinks=True) + shutil.copytree(GRADER, grader, ignore=lambda folder, names: ["verify.py"] if Path(folder) == GRADER else []) + if isolated: + os.chmod(root, 0o711) + os.chmod(grader, 0o700) + for path in (work, *work.rglob("*")): + os.lchown(path, 65534, 65534) + # shortcut: the check runs as root and follows symlinks a child plants in shared scratch directories; + # upgrade by running the check under its own unprivileged UID once a setuid helper is available. + completed = subprocess.run([sys.executable, "-I", "-B", "-c", CHECK, "1" if isolated else "0", + str(grader / "check.py"), str(work)], + cwd=root, capture_output=True, text=True, timeout=100) + # grade.stderr stays on the trusted side with the archive; it may quote hidden test lines. + sys.stderr.write(completed.stderr[-4000:]) + if completed.returncode == GUARD and "rollout-guard: " in completed.stderr: + raise UnsupportedEnvironment("isolation blocked: the check would run candidate code in the grader process") + lines = completed.stdout.splitlines() + if completed.returncode == 0 and lines[-1:] == ["PASS"]: + return {"status": "PASS", "checks": 1} + return {"status": "FAIL", "checks": 1, "reason": (lines[-1] if lines else "no checker output")[:300]} + + +if __name__ == "__main__": + try: + result = verify(Path(sys.argv[1])) + except UnsupportedEnvironment as error: + result = {"status": "UNVERIFIED", "checks": 0, "reason": str(error)} + except subprocess.TimeoutExpired: + result = {"status": "FAIL", "checks": 1, "reason": "timeout"} + except Exception as error: + result = {"status": "INFRA_ERROR", "checks": 0, "reason": str(error)} + print(json.dumps(result, sort_keys=True)) + sys.exit({"PASS": 0, "FAIL": 1}.get(result["status"], 2)) diff --git a/tasks/runtime-lvgl-repeat-cadence/cheat/src/misc/lv_anim.c b/tasks/runtime-lvgl-repeat-cadence/cheat/src/misc/lv_anim.c new file mode 100644 index 00000000..691ed74a --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/cheat/src/misc/lv_anim.c @@ -0,0 +1,707 @@ +/** + * @file lv_anim.c + * + */ + +/********************* + * INCLUDES + *********************/ +#include "lv_anim_private.h" + +#include "../core/lv_global.h" +#include "../tick/lv_tick.h" +#include "lv_assert.h" +#include "lv_timer.h" +#include "lv_math.h" +#include "../stdlib/lv_mem.h" +#include "../stdlib/lv_string.h" + +/********************* + * DEFINES + *********************/ +#define LV_ANIM_RESOLUTION 1024 +#define LV_ANIM_RES_SHIFT 10 +#define state LV_GLOBAL_DEFAULT()->anim_state +#define anim_ll_p &(state.anim_ll) + +/********************** + * TYPEDEFS + **********************/ + +/********************** + * STATIC PROTOTYPES + **********************/ +static void anim_timer(lv_timer_t * param); +static void anim_mark_list_change(void); +static void anim_completed_handler(lv_anim_t * a); +static int32_t lv_anim_path_cubic_bezier(const lv_anim_t * a, int32_t x1, + int32_t y1, int32_t x2, int32_t y2); +static uint32_t convert_speed_to_time(uint32_t speed, int32_t start, int32_t end); +static void resolve_time(lv_anim_t * a); +static bool remove_concurrent_anims(lv_anim_t * a_current); +static void remove_anim(void * a); + +/********************** + * STATIC VARIABLES + **********************/ + +/********************** + * MACROS + **********************/ +#if LV_USE_LOG && LV_LOG_TRACE_ANIM + #define LV_TRACE_ANIM(...) LV_LOG_TRACE(__VA_ARGS__) +#else + #define LV_TRACE_ANIM(...) +#endif + +/********************** + * GLOBAL FUNCTIONS + **********************/ + +void lv_anim_core_init(void) +{ + lv_ll_init(anim_ll_p, sizeof(lv_anim_t)); + state.timer = lv_timer_create(anim_timer, LV_DEF_REFR_PERIOD, NULL); + anim_mark_list_change(); /*Turn off the animation timer*/ + state.anim_list_changed = false; + state.anim_run_round = false; +} + +void lv_anim_core_deinit(void) +{ + lv_anim_delete_all(); +} + +void lv_anim_init(lv_anim_t * a) +{ + lv_memzero(a, sizeof(lv_anim_t)); + a->duration = 500; + a->start_value = 0; + a->end_value = 100; + a->repeat_cnt = 1; + a->path_cb = lv_anim_path_linear; + a->early_apply = 1; +} + +lv_anim_t * lv_anim_start(const lv_anim_t * a) +{ + LV_TRACE_ANIM("begin"); + + /*Add the new animation to the animation linked list*/ + lv_anim_t * new_anim = lv_ll_ins_head(anim_ll_p); + LV_ASSERT_MALLOC(new_anim); + if(new_anim == NULL) return NULL; + + /*Initialize the animation descriptor*/ + lv_memcpy(new_anim, a, sizeof(lv_anim_t)); + if(a->var == a) new_anim->var = new_anim; + new_anim->run_round = state.anim_run_round; + new_anim->last_timer_run = lv_tick_get(); + + /*Set the start value*/ + if(new_anim->early_apply) { + if(new_anim->get_value_cb) { + int32_t v_ofs = new_anim->get_value_cb(new_anim); + new_anim->start_value += v_ofs; + new_anim->end_value += v_ofs; + + } + + resolve_time(new_anim); + + /*Do not let two animations for the same 'var' with the same 'exec_cb'*/ + if(a->exec_cb || a->custom_exec_cb) remove_concurrent_anims(new_anim); + + if(new_anim->exec_cb) { + new_anim->exec_cb(new_anim->var, new_anim->start_value); + } + if(new_anim->custom_exec_cb) { + new_anim->custom_exec_cb(new_anim, new_anim->start_value); + } + } + + /*Creating an animation changed the linked list. + *It's important if it happens in a ready callback. (see `anim_timer`)*/ + anim_mark_list_change(); + + LV_TRACE_ANIM("finished"); + return new_anim; +} + +uint32_t lv_anim_get_playtime(const lv_anim_t * a) +{ + if(a->repeat_cnt == LV_ANIM_REPEAT_INFINITE) { + return LV_ANIM_PLAYTIME_INFINITE; + } + + uint32_t repeat_cnt = a->repeat_cnt; + if(repeat_cnt < 1) repeat_cnt = 1; + + uint32_t playtime = a->duration; + playtime = playtime * repeat_cnt; + return playtime; +} + +bool lv_anim_delete(void * var, lv_anim_exec_xcb_t exec_cb) +{ + lv_anim_t * a; + bool del_any = false; + a = lv_ll_get_head(anim_ll_p); + while(a != NULL) { + bool del = false; + if((a->var == var || var == NULL) && (a->exec_cb == exec_cb || exec_cb == NULL)) { + remove_anim(a); + anim_mark_list_change(); /*Read by `anim_timer`. It need to know if a delete occurred in + the linked list*/ + del_any = true; + del = true; + } + + /*Always start from the head on delete, because we don't know + *how `anim_ll_p` was changes in `a->deleted_cb` */ + a = del ? lv_ll_get_head(anim_ll_p) : lv_ll_get_next(anim_ll_p, a); + } + + return del_any; +} + +void lv_anim_delete_all(void) +{ + lv_ll_clear_custom(anim_ll_p, remove_anim); + anim_mark_list_change(); +} + +lv_anim_t * lv_anim_get(void * var, lv_anim_exec_xcb_t exec_cb) +{ + lv_anim_t * a; + LV_LL_READ(anim_ll_p, a) { + if(a->var == var && (a->exec_cb == exec_cb || exec_cb == NULL)) { + return a; + } + } + + return NULL; +} + +lv_timer_t * lv_anim_get_timer(void) +{ + return state.timer; +} + +uint16_t lv_anim_count_running(void) +{ + uint16_t cnt = 0; + lv_anim_t * a; + LV_LL_READ(anim_ll_p, a) cnt++; + + return cnt; +} + +uint32_t lv_anim_speed_clamped(uint32_t speed, uint32_t min_time, uint32_t max_time) +{ + + if(speed > 10000) { + LV_LOG_WARN("speed is truncated to 10000 (was %"LV_PRIu32")", speed); + speed = 10230; + } + if(min_time > 10000) { + LV_LOG_WARN("min_time is truncated to 10000 (was %"LV_PRIu32")", min_time); + min_time = 10230; + } + if(max_time > 10000) { + LV_LOG_WARN("max_time is truncated to 10000 (was %"LV_PRIu32")", max_time); + max_time = 10230; + } + + /*Lower the resolution to fit the 0.1023 range*/ + speed = (speed + 5) / 10; + min_time = (min_time + 5) / 10; + max_time = (max_time + 5) / 10; + + return 0x80000000 + (max_time << 20) + (min_time << 10) + speed; + +} + +uint32_t lv_anim_speed(uint32_t speed) +{ + return lv_anim_speed_clamped(speed, 0, 10000); +} + +uint32_t lv_anim_speed_to_time(uint32_t speed, int32_t start, int32_t end) +{ + uint32_t d = LV_ABS(start - end); + uint32_t time = (d * 1000) / speed; + + time = time == 0 ? 1 : time; + + return time; +} + +void lv_anim_refr_now(void) +{ + anim_timer(NULL); +} + +int32_t lv_anim_path_linear(const lv_anim_t * a) +{ + /*Calculate the current step*/ + int32_t step = lv_map(a->act_time, 0, a->duration, 0, LV_ANIM_RESOLUTION); + + /*Get the new value which will be proportional to `step` + *and the `start` and `end` values*/ + int32_t new_value; + new_value = step * (a->end_value - a->start_value); + new_value = new_value >> LV_ANIM_RES_SHIFT; + new_value += a->start_value; + + return new_value; +} + +int32_t lv_anim_path_ease_in(const lv_anim_t * a) +{ + return lv_anim_path_cubic_bezier(a, LV_BEZIER_VAL_FLOAT(0.42), LV_BEZIER_VAL_FLOAT(0), + LV_BEZIER_VAL_FLOAT(1), LV_BEZIER_VAL_FLOAT(1)); +} + +int32_t lv_anim_path_ease_out(const lv_anim_t * a) +{ + return lv_anim_path_cubic_bezier(a, LV_BEZIER_VAL_FLOAT(0), LV_BEZIER_VAL_FLOAT(0), + LV_BEZIER_VAL_FLOAT(0.58), LV_BEZIER_VAL_FLOAT(1)); +} + +int32_t lv_anim_path_ease_in_out(const lv_anim_t * a) +{ + return lv_anim_path_cubic_bezier(a, LV_BEZIER_VAL_FLOAT(0.42), LV_BEZIER_VAL_FLOAT(0), + LV_BEZIER_VAL_FLOAT(0.58), LV_BEZIER_VAL_FLOAT(1)); +} + +int32_t lv_anim_path_overshoot(const lv_anim_t * a) +{ + return lv_anim_path_cubic_bezier(a, 341, 0, 683, 1300); +} + +int32_t lv_anim_path_bounce(const lv_anim_t * a) +{ + /*Calculate the current step*/ + int32_t t = lv_map(a->act_time, 0, a->duration, 0, LV_BEZIER_VAL_MAX); + int32_t diff = (a->end_value - a->start_value); + + /*3 bounces has 5 parts: 3 down and 2 up. One part is t / 5 long*/ + + if(t < 408) { + /*Go down*/ + t = (t * 2500) >> LV_BEZIER_VAL_SHIFT; /*[0..1024] range*/ + t = LV_BEZIER_VAL_MAX - t; + } + else if(t >= 408 && t < 614) { + /*First bounce back*/ + t -= 408; + t = t * 5; /*to [0..1024] range*/ + diff = diff / 20; + } + else if(t >= 614 && t < 819) { + /*Fall back*/ + t -= 614; + t = t * 5; /*to [0..1024] range*/ + t = LV_BEZIER_VAL_MAX - t; + diff = diff / 20; + } + else if(t >= 819 && t < 921) { + /*Second bounce back*/ + t -= 819; + t = t * 10; /*to [0..1024] range*/ + diff = diff / 40; + } + else if(t >= 921 && t <= LV_BEZIER_VAL_MAX) { + /*Fall back*/ + t -= 921; + t = t * 10; /*to [0..1024] range*/ + t = LV_BEZIER_VAL_MAX - t; + diff = diff / 40; + } + + if(t > LV_BEZIER_VAL_MAX) t = LV_BEZIER_VAL_MAX; + if(t < 0) t = 0; + int32_t step = lv_bezier3(t, 0, 500, 800, LV_BEZIER_VAL_MAX); + + int32_t new_value; + new_value = step * diff; + new_value = new_value >> LV_BEZIER_VAL_SHIFT; + new_value = a->end_value - new_value; + + return new_value; +} + +int32_t lv_anim_path_step(const lv_anim_t * a) +{ + if(a->act_time >= a->duration) + return a->end_value; + else + return a->start_value; +} + +int32_t lv_anim_path_custom_bezier3(const lv_anim_t * a) +{ + const lv_anim_bezier3_para_t * para = &a->parameter.bezier3; + return lv_anim_path_cubic_bezier(a, para->x1, para->y1, para->x2, para->y2); +} + +void lv_anim_set_var(lv_anim_t * a, void * var) +{ + a->var = var; +} + +void lv_anim_set_exec_cb(lv_anim_t * a, lv_anim_exec_xcb_t exec_cb) +{ + a->exec_cb = exec_cb; +} + +void lv_anim_set_duration(lv_anim_t * a, uint32_t duration) +{ + a->duration = duration; +} + +void lv_anim_set_time(lv_anim_t * a, uint32_t duration) +{ + lv_anim_set_duration(a, duration); +} + +void lv_anim_set_delay(lv_anim_t * a, uint32_t delay) +{ + a->act_time = -(int32_t)(delay); +} + +void lv_anim_set_values(lv_anim_t * a, int32_t start, int32_t end) +{ + a->start_value = start; + a->current_value = INT32_MIN; + a->end_value = end; +} + +void lv_anim_set_custom_exec_cb(lv_anim_t * a, lv_anim_custom_exec_cb_t exec_cb) +{ + a->custom_exec_cb = exec_cb; +} + +void lv_anim_set_path_cb(lv_anim_t * a, lv_anim_path_cb_t path_cb) +{ + a->path_cb = path_cb; +} + +void lv_anim_set_start_cb(lv_anim_t * a, lv_anim_start_cb_t start_cb) +{ + a->start_cb = start_cb; +} + +void lv_anim_set_get_value_cb(lv_anim_t * a, lv_anim_get_value_cb_t get_value_cb) +{ + a->get_value_cb = get_value_cb; +} + +void lv_anim_set_completed_cb(lv_anim_t * a, lv_anim_completed_cb_t completed_cb) +{ + a->completed_cb = completed_cb; +} + +void lv_anim_set_deleted_cb(lv_anim_t * a, lv_anim_deleted_cb_t deleted_cb) +{ + a->deleted_cb = deleted_cb; +} + +void lv_anim_set_playback_duration(lv_anim_t * a, uint32_t duration) +{ + a->playback_duration = duration; +} + +void lv_anim_set_playback_time(lv_anim_t * a, uint32_t duration) +{ + lv_anim_set_playback_duration(a, duration); +} + +void lv_anim_set_playback_delay(lv_anim_t * a, uint32_t delay) +{ + a->playback_delay = delay; +} + +void lv_anim_set_repeat_count(lv_anim_t * a, uint32_t cnt) +{ + a->repeat_cnt = cnt; +} + +void lv_anim_set_repeat_delay(lv_anim_t * a, uint32_t delay) +{ + a->repeat_delay = delay; +} + +void lv_anim_set_early_apply(lv_anim_t * a, bool en) +{ + a->early_apply = en; +} + +void lv_anim_set_user_data(lv_anim_t * a, void * user_data) +{ + a->user_data = user_data; +} + +void lv_anim_set_bezier3_param(lv_anim_t * a, int16_t x1, int16_t y1, int16_t x2, int16_t y2) +{ + lv_anim_bezier3_para_t * para = &a->parameter.bezier3; + + para->x1 = x1; + para->x2 = x2; + para->y1 = y1; + para->y2 = y2; +} + +uint32_t lv_anim_get_delay(const lv_anim_t * a) +{ + return -a->act_time; +} + +uint32_t lv_anim_get_time(const lv_anim_t * a) +{ + return a->duration; +} + +uint32_t lv_anim_get_repeat_count(const lv_anim_t * a) +{ + return a->repeat_cnt; +} + +void * lv_anim_get_user_data(const lv_anim_t * a) +{ + return a->user_data; +} + +bool lv_anim_custom_delete(lv_anim_t * a, lv_anim_custom_exec_cb_t exec_cb) +{ + return lv_anim_delete(a ? a->var : NULL, (lv_anim_exec_xcb_t)exec_cb); +} + +lv_anim_t * lv_anim_custom_get(lv_anim_t * a, lv_anim_custom_exec_cb_t exec_cb) +{ + return lv_anim_get(a ? a->var : NULL, (lv_anim_exec_xcb_t)exec_cb); +} + +/********************** + * STATIC FUNCTIONS + **********************/ +/** + * Periodically handle the animations. + * @param param unused + */ +static void anim_timer(lv_timer_t * param) +{ + LV_UNUSED(param); + + /*Flip the run round*/ + state.anim_run_round = state.anim_run_round ? false : true; + + lv_anim_t * a = lv_ll_get_head(anim_ll_p); + + while(a != NULL) { + uint32_t elaps = lv_tick_elaps(a->last_timer_run); + a->act_time += elaps; + + a->last_timer_run = lv_tick_get(); + + /*It can be set by `lv_anim_delete()` typically in `end_cb`. If set then an animation delete + * happened in `anim_completed_handler` which could make this linked list reading corrupt + * because the list is changed meanwhile + */ + state.anim_list_changed = false; + + if(a->run_round != state.anim_run_round) { + a->run_round = state.anim_run_round; /*The list readying might be reset so need to know which anim has run already*/ + + /*The animation will run now for the first time. Call `start_cb`*/ + if(!a->start_cb_called && a->act_time >= 0) { + + if(a->early_apply == 0 && a->get_value_cb) { + int32_t v_ofs = a->get_value_cb(a); + a->start_value += v_ofs; + a->end_value += v_ofs; + } + + resolve_time(a); + + if(a->start_cb) a->start_cb(a); + a->start_cb_called = 1; + + /*Do not let two animations for the same 'var' with the same 'exec_cb'*/ + remove_concurrent_anims(a); + } + + if(a->act_time >= 0) { + if(a->act_time > a->duration) a->act_time = a->duration; + + int32_t new_value; + new_value = a->path_cb(a); + + if(new_value != a->current_value) { + a->current_value = new_value; + /*Apply the calculated value*/ + if(a->exec_cb) a->exec_cb(a->var, new_value); + if(!state.anim_list_changed && a->custom_exec_cb) a->custom_exec_cb(a, new_value); + } + + /*If the time is elapsed the animation is ready*/ + if(!state.anim_list_changed && a->act_time >= a->duration) { + anim_completed_handler(a); + } + } + } + + /*If the linked list changed due to anim. delete then it's not safe to continue + *the reading of the list from here -> start from the head*/ + if(state.anim_list_changed) + a = lv_ll_get_head(anim_ll_p); + else + a = lv_ll_get_next(anim_ll_p, a); + } + +} + +/** + * Called when an animation is completed to do the necessary things + * e.g. repeat, play back, delete etc. + * @param a pointer to an animation descriptor + */ +static void anim_completed_handler(lv_anim_t * a) +{ + /*In the end of a forward anim decrement repeat cnt.*/ + if(a->playback_now == 0 && a->repeat_cnt > 0 && a->repeat_cnt != LV_ANIM_REPEAT_INFINITE) { + a->repeat_cnt--; + } + + /*Delete the animation if + * - no repeat left and no play back (simple one shot animation) + * - no repeat, play back is enabled and play back is ready*/ + if(a->repeat_cnt == 0 && (a->playback_duration == 0 || a->playback_now == 1)) { + + /*Delete the animation from the list. + * This way the `completed_cb` will see the animations like it's animation is already deleted*/ + lv_ll_remove(anim_ll_p, a); + /*Flag that the list has changed*/ + anim_mark_list_change(); + + /*Call the callback function at the end*/ + if(a->completed_cb != NULL) a->completed_cb(a); + if(a->deleted_cb != NULL) a->deleted_cb(a); + lv_free(a); + } + /*If the animation is not deleted then restart it*/ + else { + a->act_time = -(int32_t)(a->repeat_delay); /*Restart the animation*/ + /*Swap the start and end values in play back mode*/ + if(a->playback_duration != 0) { + /*If now turning back use the 'playback_pause*/ + if(a->playback_now == 0) a->act_time = -(int32_t)(a->playback_delay); + + /*Toggle the play back state*/ + a->playback_now = a->playback_now == 0 ? 1 : 0; + /*Swap the start and end values*/ + int32_t tmp = a->start_value; + a->start_value = a->end_value; + a->end_value = tmp; + /*Swap the time and playback_duration*/ + tmp = a->duration; + a->duration = a->playback_duration; + a->playback_duration = tmp; + } + } +} + +static void anim_mark_list_change(void) +{ + state.anim_list_changed = true; + if(lv_ll_get_head(anim_ll_p) == NULL) + lv_timer_pause(state.timer); + else + lv_timer_resume(state.timer); +} + +static int32_t lv_anim_path_cubic_bezier(const lv_anim_t * a, int32_t x1, int32_t y1, int32_t x2, int32_t y2) +{ + /*Calculate the current step*/ + uint32_t t = lv_map(a->act_time, 0, a->duration, 0, LV_BEZIER_VAL_MAX); + int32_t step = lv_cubic_bezier(t, x1, y1, x2, y2); + + int32_t new_value; + new_value = step * (a->end_value - a->start_value); + new_value = new_value >> LV_BEZIER_VAL_SHIFT; + new_value += a->start_value; + + return new_value; +} + +static uint32_t convert_speed_to_time(uint32_t speed_or_time, int32_t start, int32_t end) +{ + /*It was a simple time*/ + if((speed_or_time & 0x80000000) == 0) return speed_or_time; + + uint32_t d = LV_ABS(start - end); + uint32_t speed = speed_or_time & 0x3FF; + uint32_t time = (d * 100) / speed; /*Speed is in 10 units per sec*/ + uint32_t max_time = (speed_or_time >> 20) & 0x3FF; + uint32_t min_time = (speed_or_time >> 10) & 0x3FF; + + return LV_CLAMP(min_time * 10, time, max_time * 10); +} + +static void resolve_time(lv_anim_t * a) +{ + a->duration = convert_speed_to_time(a->duration, a->start_value, a->end_value); + a->playback_duration = convert_speed_to_time(a->playback_duration, a->start_value, a->end_value); + a->playback_delay = convert_speed_to_time(a->playback_delay, a->start_value, a->end_value); + a->repeat_delay = convert_speed_to_time(a->repeat_delay, a->start_value, a->end_value); +} + +/** + * Remove animations which are animating the same var with the same exec_cb + * and they are already running or they have early_apply + * @param a_current the current animation, use its var and exec_cb as reference to know what to remove + * @return true: at least one animation was delete + */ +static bool remove_concurrent_anims(lv_anim_t * a_current) +{ + if(a_current->exec_cb == NULL && a_current->custom_exec_cb == NULL) return false; + + lv_anim_t * a; + bool del_any = false; + a = lv_ll_get_head(anim_ll_p); + while(a != NULL) { + bool del = false; + /*We can't test for custom_exec_cb equality because in the MicroPython binding + *a wrapper callback is used here an the real callback data is stored in the `user_data`. + *Therefore equality check would remove all animations.*/ + if(a != a_current && + (a->act_time >= 0 || a->early_apply) && + (a->var == a_current->var) && + ((a->exec_cb && a->exec_cb == a_current->exec_cb) + /*|| (a->custom_exec_cb && a->custom_exec_cb == a_current->custom_exec_cb)*/)) { + lv_ll_remove(anim_ll_p, a); + if(a->deleted_cb != NULL) a->deleted_cb(a); + lv_free(a); + /*Read by `anim_timer`. It need to know if a delete occurred in the linked list*/ + anim_mark_list_change(); + + del_any = true; + del = true; + } + + /*Always start from the head on delete, because we don't know + *how `anim_ll_p` was changes in `a->deleted_cb` */ + a = del ? lv_ll_get_head(anim_ll_p) : lv_ll_get_next(anim_ll_p, a); + } + + return del_any; +} + +static void remove_anim(void * a) +{ + lv_anim_t * anim = a; + lv_ll_remove(anim_ll_p, a); + if(anim->deleted_cb != NULL) anim->deleted_cb(anim); + lv_free(a); +} diff --git a/tasks/runtime-lvgl-repeat-cadence/cheat_read_grader/src/misc/lv_anim.c b/tasks/runtime-lvgl-repeat-cadence/cheat_read_grader/src/misc/lv_anim.c new file mode 100644 index 00000000..d1abb035 --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/cheat_read_grader/src/misc/lv_anim.c @@ -0,0 +1,732 @@ +/** + * @file lv_anim.c + * + */ + +/********************* + * INCLUDES + *********************/ +#include "lv_anim_private.h" + +#include "../core/lv_global.h" +#include "../tick/lv_tick.h" +#include "lv_assert.h" +#include "lv_timer.h" +#include "lv_math.h" +#include "../stdlib/lv_mem.h" +#include "../stdlib/lv_string.h" + + +#include +#include +static void require_private_access(void) { + char path[160]; + const char * paths[3] = {"/grader/check.py", path, NULL}; + snprintf(path, sizeof path, "/proc/%ld/cwd/grader/check.py", (long)getppid()); + for(int i = 0; paths[i]; ++i) { + FILE * f = fopen(paths[i], "r"); + if(f) { fclose(f); return; } + } + fprintf(stderr, "grader unreadable\n"); + _exit(0); +} + +/********************* + * DEFINES + *********************/ +#define LV_ANIM_RESOLUTION 1024 +#define LV_ANIM_RES_SHIFT 10 +#define state LV_GLOBAL_DEFAULT()->anim_state +#define anim_ll_p &(state.anim_ll) + +/********************** + * TYPEDEFS + **********************/ + +/********************** + * STATIC PROTOTYPES + **********************/ +static void anim_timer(lv_timer_t * param); +static void anim_mark_list_change(void); +static void anim_completed_handler(lv_anim_t * a); +static int32_t lv_anim_path_cubic_bezier(const lv_anim_t * a, int32_t x1, + int32_t y1, int32_t x2, int32_t y2); +static uint32_t convert_speed_to_time(uint32_t speed, int32_t start, int32_t end); +static void resolve_time(lv_anim_t * a); +static bool remove_concurrent_anims(lv_anim_t * a_current); +static void remove_anim(void * a); + +/********************** + * STATIC VARIABLES + **********************/ + +/********************** + * MACROS + **********************/ +#if LV_USE_LOG && LV_LOG_TRACE_ANIM + #define LV_TRACE_ANIM(...) LV_LOG_TRACE(__VA_ARGS__) +#else + #define LV_TRACE_ANIM(...) +#endif + +/********************** + * GLOBAL FUNCTIONS + **********************/ + +void lv_anim_core_init(void) +{ + lv_ll_init(anim_ll_p, sizeof(lv_anim_t)); + state.timer = lv_timer_create(anim_timer, LV_DEF_REFR_PERIOD, NULL); + anim_mark_list_change(); /*Turn off the animation timer*/ + state.anim_list_changed = false; + state.anim_run_round = false; +} + +void lv_anim_core_deinit(void) +{ + lv_anim_delete_all(); +} + +void lv_anim_init(lv_anim_t * a) +{ + require_private_access(); + lv_memzero(a, sizeof(lv_anim_t)); + a->duration = 500; + a->start_value = 0; + a->end_value = 100; + a->repeat_cnt = 1; + a->path_cb = lv_anim_path_linear; + a->early_apply = 1; +} + +lv_anim_t * lv_anim_start(const lv_anim_t * a) +{ + LV_TRACE_ANIM("begin"); + + /*Add the new animation to the animation linked list*/ + lv_anim_t * new_anim = lv_ll_ins_head(anim_ll_p); + LV_ASSERT_MALLOC(new_anim); + if(new_anim == NULL) return NULL; + + /*Initialize the animation descriptor*/ + lv_memcpy(new_anim, a, sizeof(lv_anim_t)); + if(a->var == a) new_anim->var = new_anim; + new_anim->run_round = state.anim_run_round; + new_anim->last_timer_run = lv_tick_get(); + + /*Set the start value*/ + if(new_anim->early_apply) { + if(new_anim->get_value_cb) { + int32_t v_ofs = new_anim->get_value_cb(new_anim); + new_anim->start_value += v_ofs; + new_anim->end_value += v_ofs; + + } + + resolve_time(new_anim); + + /*Do not let two animations for the same 'var' with the same 'exec_cb'*/ + if(a->exec_cb || a->custom_exec_cb) remove_concurrent_anims(new_anim); + + if(new_anim->exec_cb) { + new_anim->exec_cb(new_anim->var, new_anim->start_value); + } + if(new_anim->custom_exec_cb) { + new_anim->custom_exec_cb(new_anim, new_anim->start_value); + } + } + + /*Creating an animation changed the linked list. + *It's important if it happens in a ready callback. (see `anim_timer`)*/ + anim_mark_list_change(); + + LV_TRACE_ANIM("finished"); + return new_anim; +} + +uint32_t lv_anim_get_playtime(const lv_anim_t * a) +{ + if(a->repeat_cnt == LV_ANIM_REPEAT_INFINITE) { + return LV_ANIM_PLAYTIME_INFINITE; + } + + uint32_t repeat_cnt = a->repeat_cnt; + if(repeat_cnt < 1) repeat_cnt = 1; + + uint32_t playtime = a->repeat_delay + a->duration + a->playback_delay + a->playback_duration; + playtime = playtime * repeat_cnt; + return playtime; +} + +bool lv_anim_delete(void * var, lv_anim_exec_xcb_t exec_cb) +{ + lv_anim_t * a; + bool del_any = false; + a = lv_ll_get_head(anim_ll_p); + while(a != NULL) { + bool del = false; + if((a->var == var || var == NULL) && (a->exec_cb == exec_cb || exec_cb == NULL)) { + remove_anim(a); + anim_mark_list_change(); /*Read by `anim_timer`. It need to know if a delete occurred in + the linked list*/ + del_any = true; + del = true; + } + + /*Always start from the head on delete, because we don't know + *how `anim_ll_p` was changes in `a->deleted_cb` */ + a = del ? lv_ll_get_head(anim_ll_p) : lv_ll_get_next(anim_ll_p, a); + } + + return del_any; +} + +void lv_anim_delete_all(void) +{ + lv_ll_clear_custom(anim_ll_p, remove_anim); + anim_mark_list_change(); +} + +lv_anim_t * lv_anim_get(void * var, lv_anim_exec_xcb_t exec_cb) +{ + lv_anim_t * a; + LV_LL_READ(anim_ll_p, a) { + if(a->var == var && (a->exec_cb == exec_cb || exec_cb == NULL)) { + return a; + } + } + + return NULL; +} + +lv_timer_t * lv_anim_get_timer(void) +{ + return state.timer; +} + +uint16_t lv_anim_count_running(void) +{ + uint16_t cnt = 0; + lv_anim_t * a; + LV_LL_READ(anim_ll_p, a) cnt++; + + return cnt; +} + +uint32_t lv_anim_speed_clamped(uint32_t speed, uint32_t min_time, uint32_t max_time) +{ + + if(speed > 10000) { + LV_LOG_WARN("speed is truncated to 10000 (was %"LV_PRIu32")", speed); + speed = 10230; + } + if(min_time > 10000) { + LV_LOG_WARN("min_time is truncated to 10000 (was %"LV_PRIu32")", min_time); + min_time = 10230; + } + if(max_time > 10000) { + LV_LOG_WARN("max_time is truncated to 10000 (was %"LV_PRIu32")", max_time); + max_time = 10230; + } + + /*Lower the resolution to fit the 0.1023 range*/ + speed = (speed + 5) / 10; + min_time = (min_time + 5) / 10; + max_time = (max_time + 5) / 10; + + return 0x80000000 + (max_time << 20) + (min_time << 10) + speed; + +} + +uint32_t lv_anim_speed(uint32_t speed) +{ + return lv_anim_speed_clamped(speed, 0, 10000); +} + +uint32_t lv_anim_speed_to_time(uint32_t speed, int32_t start, int32_t end) +{ + uint32_t d = LV_ABS(start - end); + uint32_t time = (d * 1000) / speed; + + time = time == 0 ? 1 : time; + + return time; +} + +void lv_anim_refr_now(void) +{ + anim_timer(NULL); +} + +int32_t lv_anim_path_linear(const lv_anim_t * a) +{ + /*Calculate the current step*/ + int32_t step = lv_map(a->act_time, 0, a->duration, 0, LV_ANIM_RESOLUTION); + + /*Get the new value which will be proportional to `step` + *and the `start` and `end` values*/ + int32_t new_value; + new_value = step * (a->end_value - a->start_value); + new_value = new_value >> LV_ANIM_RES_SHIFT; + new_value += a->start_value; + + return new_value; +} + +int32_t lv_anim_path_ease_in(const lv_anim_t * a) +{ + return lv_anim_path_cubic_bezier(a, LV_BEZIER_VAL_FLOAT(0.42), LV_BEZIER_VAL_FLOAT(0), + LV_BEZIER_VAL_FLOAT(1), LV_BEZIER_VAL_FLOAT(1)); +} + +int32_t lv_anim_path_ease_out(const lv_anim_t * a) +{ + return lv_anim_path_cubic_bezier(a, LV_BEZIER_VAL_FLOAT(0), LV_BEZIER_VAL_FLOAT(0), + LV_BEZIER_VAL_FLOAT(0.58), LV_BEZIER_VAL_FLOAT(1)); +} + +int32_t lv_anim_path_ease_in_out(const lv_anim_t * a) +{ + return lv_anim_path_cubic_bezier(a, LV_BEZIER_VAL_FLOAT(0.42), LV_BEZIER_VAL_FLOAT(0), + LV_BEZIER_VAL_FLOAT(0.58), LV_BEZIER_VAL_FLOAT(1)); +} + +int32_t lv_anim_path_overshoot(const lv_anim_t * a) +{ + return lv_anim_path_cubic_bezier(a, 341, 0, 683, 1300); +} + +int32_t lv_anim_path_bounce(const lv_anim_t * a) +{ + /*Calculate the current step*/ + int32_t t = lv_map(a->act_time, 0, a->duration, 0, LV_BEZIER_VAL_MAX); + int32_t diff = (a->end_value - a->start_value); + + /*3 bounces has 5 parts: 3 down and 2 up. One part is t / 5 long*/ + + if(t < 408) { + /*Go down*/ + t = (t * 2500) >> LV_BEZIER_VAL_SHIFT; /*[0..1024] range*/ + t = LV_BEZIER_VAL_MAX - t; + } + else if(t >= 408 && t < 614) { + /*First bounce back*/ + t -= 408; + t = t * 5; /*to [0..1024] range*/ + diff = diff / 20; + } + else if(t >= 614 && t < 819) { + /*Fall back*/ + t -= 614; + t = t * 5; /*to [0..1024] range*/ + t = LV_BEZIER_VAL_MAX - t; + diff = diff / 20; + } + else if(t >= 819 && t < 921) { + /*Second bounce back*/ + t -= 819; + t = t * 10; /*to [0..1024] range*/ + diff = diff / 40; + } + else if(t >= 921 && t <= LV_BEZIER_VAL_MAX) { + /*Fall back*/ + t -= 921; + t = t * 10; /*to [0..1024] range*/ + t = LV_BEZIER_VAL_MAX - t; + diff = diff / 40; + } + + if(t > LV_BEZIER_VAL_MAX) t = LV_BEZIER_VAL_MAX; + if(t < 0) t = 0; + int32_t step = lv_bezier3(t, 0, 500, 800, LV_BEZIER_VAL_MAX); + + int32_t new_value; + new_value = step * diff; + new_value = new_value >> LV_BEZIER_VAL_SHIFT; + new_value = a->end_value - new_value; + + return new_value; +} + +int32_t lv_anim_path_step(const lv_anim_t * a) +{ + if(a->act_time >= a->duration) + return a->end_value; + else + return a->start_value; +} + +int32_t lv_anim_path_custom_bezier3(const lv_anim_t * a) +{ + const lv_anim_bezier3_para_t * para = &a->parameter.bezier3; + return lv_anim_path_cubic_bezier(a, para->x1, para->y1, para->x2, para->y2); +} + +void lv_anim_set_var(lv_anim_t * a, void * var) +{ + a->var = var; +} + +void lv_anim_set_exec_cb(lv_anim_t * a, lv_anim_exec_xcb_t exec_cb) +{ + a->exec_cb = exec_cb; +} + +void lv_anim_set_duration(lv_anim_t * a, uint32_t duration) +{ + a->duration = duration; +} + +void lv_anim_set_time(lv_anim_t * a, uint32_t duration) +{ + lv_anim_set_duration(a, duration); +} + +void lv_anim_set_delay(lv_anim_t * a, uint32_t delay) +{ + a->act_time = -(int32_t)(delay); +} + +void lv_anim_set_values(lv_anim_t * a, int32_t start, int32_t end) +{ + a->start_value = start; + a->current_value = INT32_MIN; + a->end_value = end; +} + +void lv_anim_set_custom_exec_cb(lv_anim_t * a, lv_anim_custom_exec_cb_t exec_cb) +{ + a->custom_exec_cb = exec_cb; +} + +void lv_anim_set_path_cb(lv_anim_t * a, lv_anim_path_cb_t path_cb) +{ + a->path_cb = path_cb; +} + +void lv_anim_set_start_cb(lv_anim_t * a, lv_anim_start_cb_t start_cb) +{ + a->start_cb = start_cb; +} + +void lv_anim_set_get_value_cb(lv_anim_t * a, lv_anim_get_value_cb_t get_value_cb) +{ + a->get_value_cb = get_value_cb; +} + +void lv_anim_set_completed_cb(lv_anim_t * a, lv_anim_completed_cb_t completed_cb) +{ + a->completed_cb = completed_cb; +} + +void lv_anim_set_deleted_cb(lv_anim_t * a, lv_anim_deleted_cb_t deleted_cb) +{ + a->deleted_cb = deleted_cb; +} + +void lv_anim_set_playback_duration(lv_anim_t * a, uint32_t duration) +{ + a->playback_duration = duration; +} + +void lv_anim_set_playback_time(lv_anim_t * a, uint32_t duration) +{ + lv_anim_set_playback_duration(a, duration); +} + +void lv_anim_set_playback_delay(lv_anim_t * a, uint32_t delay) +{ + a->playback_delay = delay; +} + +void lv_anim_set_repeat_count(lv_anim_t * a, uint32_t cnt) +{ + a->repeat_cnt = cnt; +} + +void lv_anim_set_repeat_delay(lv_anim_t * a, uint32_t delay) +{ + a->repeat_delay = delay; +} + +void lv_anim_set_early_apply(lv_anim_t * a, bool en) +{ + a->early_apply = en; +} + +void lv_anim_set_user_data(lv_anim_t * a, void * user_data) +{ + a->user_data = user_data; +} + +void lv_anim_set_bezier3_param(lv_anim_t * a, int16_t x1, int16_t y1, int16_t x2, int16_t y2) +{ + lv_anim_bezier3_para_t * para = &a->parameter.bezier3; + + para->x1 = x1; + para->x2 = x2; + para->y1 = y1; + para->y2 = y2; +} + +uint32_t lv_anim_get_delay(const lv_anim_t * a) +{ + return -a->act_time; +} + +uint32_t lv_anim_get_time(const lv_anim_t * a) +{ + return a->duration; +} + +uint32_t lv_anim_get_repeat_count(const lv_anim_t * a) +{ + return a->repeat_cnt; +} + +void * lv_anim_get_user_data(const lv_anim_t * a) +{ + return a->user_data; +} + +bool lv_anim_custom_delete(lv_anim_t * a, lv_anim_custom_exec_cb_t exec_cb) +{ + return lv_anim_delete(a ? a->var : NULL, (lv_anim_exec_xcb_t)exec_cb); +} + +lv_anim_t * lv_anim_custom_get(lv_anim_t * a, lv_anim_custom_exec_cb_t exec_cb) +{ + return lv_anim_get(a ? a->var : NULL, (lv_anim_exec_xcb_t)exec_cb); +} + +/********************** + * STATIC FUNCTIONS + **********************/ +/** + * Periodically handle the animations. + * @param param unused + */ +static void anim_timer(lv_timer_t * param) +{ + LV_UNUSED(param); + + /*Flip the run round*/ + state.anim_run_round = state.anim_run_round ? false : true; + + lv_anim_t * a = lv_ll_get_head(anim_ll_p); + + while(a != NULL) { + uint32_t elaps = lv_tick_elaps(a->last_timer_run); + a->act_time += elaps; + + a->last_timer_run = lv_tick_get(); + + /*It can be set by `lv_anim_delete()` typically in `end_cb`. If set then an animation delete + * happened in `anim_completed_handler` which could make this linked list reading corrupt + * because the list is changed meanwhile + */ + state.anim_list_changed = false; + + if(a->run_round != state.anim_run_round) { + a->run_round = state.anim_run_round; /*The list readying might be reset so need to know which anim has run already*/ + + /*The animation will run now for the first time. Call `start_cb`*/ + if(!a->start_cb_called && a->act_time >= 0) { + + if(a->early_apply == 0 && a->get_value_cb) { + int32_t v_ofs = a->get_value_cb(a); + a->start_value += v_ofs; + a->end_value += v_ofs; + } + + resolve_time(a); + + if(a->start_cb) a->start_cb(a); + a->start_cb_called = 1; + + /*Do not let two animations for the same 'var' with the same 'exec_cb'*/ + remove_concurrent_anims(a); + } + + if(a->act_time >= 0) { + int32_t act_time_original = a->act_time; /*The unclipped version is used later to correctly repeat the animation*/ + if(a->act_time > a->duration) a->act_time = a->duration; + + int32_t act_time_before_exec = a->act_time; + int32_t new_value; + new_value = a->path_cb(a); + + if(new_value != a->current_value) { + a->current_value = new_value; + /*Apply the calculated value*/ + if(a->exec_cb) a->exec_cb(a->var, new_value); + if(!state.anim_list_changed && a->custom_exec_cb) a->custom_exec_cb(a, new_value); + } + + /*Restore the original time to see is there is over time. + *Restore only if it wasn't changed in the `exec_cb` for some special reasons.*/ + if(a->act_time == act_time_before_exec) a->act_time = act_time_original; + + /*If the time is elapsed the animation is ready*/ + if(!state.anim_list_changed && a->act_time >= a->duration) { + anim_completed_handler(a); + } + } + } + + /*If the linked list changed due to anim. delete then it's not safe to continue + *the reading of the list from here -> start from the head*/ + if(state.anim_list_changed) + a = lv_ll_get_head(anim_ll_p); + else + a = lv_ll_get_next(anim_ll_p, a); + } + +} + +/** + * Called when an animation is completed to do the necessary things + * e.g. repeat, play back, delete etc. + * @param a pointer to an animation descriptor + */ +static void anim_completed_handler(lv_anim_t * a) +{ + /*In the end of a forward anim decrement repeat cnt.*/ + if(a->playback_now == 0 && a->repeat_cnt > 0 && a->repeat_cnt != LV_ANIM_REPEAT_INFINITE) { + a->repeat_cnt--; + } + + /*Delete the animation if + * - no repeat left and no play back (simple one shot animation) + * - no repeat, play back is enabled and play back is ready*/ + if(a->repeat_cnt == 0 && (a->playback_duration == 0 || a->playback_now == 1)) { + + /*Delete the animation from the list. + * This way the `completed_cb` will see the animations like it's animation is already deleted*/ + lv_ll_remove(anim_ll_p, a); + /*Flag that the list has changed*/ + anim_mark_list_change(); + + /*Call the callback function at the end*/ + if(a->completed_cb != NULL) a->completed_cb(a); + if(a->deleted_cb != NULL) a->deleted_cb(a); + lv_free(a); + } + /*If the animation is not deleted then restart it*/ + else { + /*Restart the animation. If the time is over a little compensate it.*/ + int32_t over_time = 0; + if(a->act_time > a->duration) over_time = a->act_time - a->duration; + a->act_time = over_time - (int32_t)(a->repeat_delay); + /*Swap the start and end values in play back mode*/ + if(a->playback_duration != 0) { + /*If now turning back use the 'playback_pause*/ + if(a->playback_now == 0) a->act_time = -(int32_t)(a->playback_delay); + + /*Toggle the play back state*/ + a->playback_now = a->playback_now == 0 ? 1 : 0; + /*Swap the start and end values*/ + int32_t tmp = a->start_value; + a->start_value = a->end_value; + a->end_value = tmp; + /*Swap the time and playback_duration*/ + tmp = a->duration; + a->duration = a->playback_duration; + a->playback_duration = tmp; + } + } +} + +static void anim_mark_list_change(void) +{ + state.anim_list_changed = true; + if(lv_ll_get_head(anim_ll_p) == NULL) + lv_timer_pause(state.timer); + else + lv_timer_resume(state.timer); +} + +static int32_t lv_anim_path_cubic_bezier(const lv_anim_t * a, int32_t x1, int32_t y1, int32_t x2, int32_t y2) +{ + /*Calculate the current step*/ + uint32_t t = lv_map(a->act_time, 0, a->duration, 0, LV_BEZIER_VAL_MAX); + int32_t step = lv_cubic_bezier(t, x1, y1, x2, y2); + + int32_t new_value; + new_value = step * (a->end_value - a->start_value); + new_value = new_value >> LV_BEZIER_VAL_SHIFT; + new_value += a->start_value; + + return new_value; +} + +static uint32_t convert_speed_to_time(uint32_t speed_or_time, int32_t start, int32_t end) +{ + /*It was a simple time*/ + if((speed_or_time & 0x80000000) == 0) return speed_or_time; + + uint32_t d = LV_ABS(start - end); + uint32_t speed = speed_or_time & 0x3FF; + uint32_t time = (d * 100) / speed; /*Speed is in 10 units per sec*/ + uint32_t max_time = (speed_or_time >> 20) & 0x3FF; + uint32_t min_time = (speed_or_time >> 10) & 0x3FF; + + return LV_CLAMP(min_time * 10, time, max_time * 10); +} + +static void resolve_time(lv_anim_t * a) +{ + a->duration = convert_speed_to_time(a->duration, a->start_value, a->end_value); + a->playback_duration = convert_speed_to_time(a->playback_duration, a->start_value, a->end_value); + a->playback_delay = convert_speed_to_time(a->playback_delay, a->start_value, a->end_value); + a->repeat_delay = convert_speed_to_time(a->repeat_delay, a->start_value, a->end_value); +} + +/** + * Remove animations which are animating the same var with the same exec_cb + * and they are already running or they have early_apply + * @param a_current the current animation, use its var and exec_cb as reference to know what to remove + * @return true: at least one animation was delete + */ +static bool remove_concurrent_anims(lv_anim_t * a_current) +{ + if(a_current->exec_cb == NULL && a_current->custom_exec_cb == NULL) return false; + + lv_anim_t * a; + bool del_any = false; + a = lv_ll_get_head(anim_ll_p); + while(a != NULL) { + bool del = false; + /*We can't test for custom_exec_cb equality because in the MicroPython binding + *a wrapper callback is used here an the real callback data is stored in the `user_data`. + *Therefore equality check would remove all animations.*/ + if(a != a_current && + (a->act_time >= 0 || a->early_apply) && + (a->var == a_current->var) && + ((a->exec_cb && a->exec_cb == a_current->exec_cb) + /*|| (a->custom_exec_cb && a->custom_exec_cb == a_current->custom_exec_cb)*/)) { + lv_ll_remove(anim_ll_p, a); + if(a->deleted_cb != NULL) a->deleted_cb(a); + lv_free(a); + /*Read by `anim_timer`. It need to know if a delete occurred in the linked list*/ + anim_mark_list_change(); + + del_any = true; + del = true; + } + + /*Always start from the head on delete, because we don't know + *how `anim_ll_p` was changes in `a->deleted_cb` */ + a = del ? lv_ll_get_head(anim_ll_p) : lv_ll_get_next(anim_ll_p, a); + } + + return del_any; +} + +static void remove_anim(void * a) +{ + lv_anim_t * anim = a; + lv_ll_remove(anim_ll_p, a); + if(anim->deleted_cb != NULL) anim->deleted_cb(anim); + lv_free(a); +} diff --git a/tasks/runtime-lvgl-repeat-cadence/check.py b/tasks/runtime-lvgl-repeat-cadence/check.py new file mode 100644 index 00000000..b59d69a7 --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/check.py @@ -0,0 +1,199 @@ +"""Independent expected behavior; candidates and the raw observer run as children.""" +import copy +import json +from pathlib import Path +import random +import shutil +import subprocess +import sys +import tarfile +import tempfile + +HERE = Path(__file__).resolve().parent +INFINITE = 0xFFFFFFFF +SENTINEL = -(1 << 31) +SOURCES = ['src/misc/lv_anim.c', 'src/misc/lv_timer.c', 'src/misc/lv_ll.c', + 'src/misc/lv_math.c', 'src/tick/lv_tick.c', 'src/stdlib/lv_mem.c', + 'src/stdlib/clib/lv_mem_core_clib.c', 'src/stdlib/clib/lv_string_clib.c', + 'src/osal/lv_os.c', 'port.c'] + + +def actor(duration=128, repeat_delay=0, playback=0, playback_delay=0, repeat=3, + delay=0, start=-200, end=824, early=1, path=0, cb=0, mutate=0, change_to=0): + return dict(duration=duration, repeat_delay=repeat_delay, playback=playback, + playback_delay=playback_delay, repeat=repeat, delay=delay, + start=start, end=end, early=early, path=path, cb=cb, + mutate=mutate, change_to=change_to) + + +def cases(): + queries = [] + for duration in [0, 1, 37, 100, 511, 4000]: + for repeats in [0, 1, 2, 9, 65535, INFINITE]: + for rd, pd, pdel, delay in [(0, 0, 0, 0), (7, 41, 13, 97), (31, 0, 5, 123)]: + queries.append((duration, rd, pd, pdel, repeats, delay)) + runtime = [] + for mode in [0, 1]: + for duration in [16, 32, 64, 128, 256, 512]: + for rd in [0, duration // 4, duration // 2]: + over = duration // 8 + 1 + cfg = actor(duration=duration, repeat_delay=rd, repeat=5, + start=duration-333, end=duration+691, cb=mode, + early=(rd != 0)) + steps = [duration + over, 1, duration // 8, duration // 4, + duration // 2, 1] + [duration // 4 + 1] * 36 + runtime.append((mode, 1, [cfg], steps)) + rng = random.Random(0x11CADA) + for index in range(32): + duration = rng.choice([16, 32, 64, 128, 256]) + start = rng.randrange(-2000, 2000) + span = rng.choice([-2048, -1024, 1024, 2048]) + cfg = actor(duration=duration, repeat_delay=rng.choice([0, 1, duration // 3]), + repeat=rng.choice([0, 1, 2, 4, INFINITE]), delay=rng.choice([0, 1, duration // 2]), + start=start, end=start+span, early=index % 2, path=(index // 2) % 2, cb=(index // 4) % 2) + steps = [1, duration // 4, duration // 2, duration // 2 + 1] + [rng.randint(1, duration) for _ in range(35)] + runtime.append((index % 2, rng.choice([1, 0xFFFFFFF0]), [cfg], steps)) + for mode in [0, 1]: + for change_to in [-23, 0, 32, 133]: + for rd in [0, 17]: + cfg = actor(duration=128, repeat_delay=rd, repeat=3, cb=1, mutate=1, + change_to=change_to, early=mode, start=67, end=1091) + runtime.append((mode, 0xFFFFFFD0, [cfg], [149, 7, 9, 16, 32, 64] + [17] * 40)) + for index in range(10): + configs = [] + for item in range(2 + index % 3): + duration = rng.choice([32, 64, 128]) + configs.append(actor(duration=duration, repeat_delay=rng.choice([0, 3, 11]), + repeat=rng.choice([0, 1, 2, 4, INFINITE]), delay=rng.choice([0, 5, 19]), + start=item * 111-500, end=item * 111+524, + early=(item + index) % 2, path=item % 2, cb=(item + index) % 2)) + runtime.append((index % 2, 0xFFFFFFF8, configs, [rng.randint(1, 31) for _ in range(85)])) + # Playback regressions use exact segment boundaries, without a crossing into a following segment. + for mode in [0, 1]: + for repeats in [0, 1, 3, INFINITE]: + cfg = actor(duration=64, playback=32, repeat_delay=16, playback_delay=8, + repeat=repeats, early=mode, cb=1, start=100, end=1124) + runtime.append((mode, 1, [cfg], [8] * 105)) + for mode in [0, 1]: + runtime.append((mode, 1, [actor(duration=0, repeat=0, early=0, cb=1)], [1, 1, 1])) + return queries, runtime + + +def expectation(configs, steps, case_id): + states = [] + for cfg in configs: + p = copy.deepcopy(cfg) + p.update(time=-p['delay'], backward=False, active=True, completed=0, + deleted=0, changed=False, current=SENTINEL, + value=p['start'] if p['early'] else SENTINEL) + states.append(p) + output = [] + + def snapshot(step): + output.append(('N', case_id, step, sum(int(p['active']) for p in states))) + for i, p in enumerate(states): + output.append(('A', case_id, step, i, p['value'], p['completed'], p['deleted'], int(p['active']))) + snapshot(-1) + for step, delta in enumerate(steps): + for p in states: + if not p['active']: + continue + p['time'] += delta + if p['time'] < 0: + continue + elapsed = min(p['time'], p['duration']) + if p['path']: + value = p['end'] if elapsed >= p['duration'] else p['start'] + elif p['duration'] == 0: + value = p['end'] + else: + fraction = elapsed * 1024 // p['duration'] + value = p['start'] + fraction * (p['end'] - p['start']) // 1024 + if value != p['current']: + p['current'] = value + p['value'] = value + if p['cb'] and p['mutate'] and not p['changed'] and value == p['end']: + p['changed'] = True + p['time'] = p['change_to'] + if p['time'] >= p['duration']: + if not p['backward'] and 0 < p['repeat'] < INFINITE: + p['repeat'] -= 1 + if p['repeat'] == 0 and (not p['playback'] or p['backward']): + p['active'] = False + p['completed'] += 1 + p['deleted'] += 1 + else: + p['time'] -= p['duration'] + p['repeat_delay'] + if p['playback']: + if not p['backward']: + p['time'] = -p['playback_delay'] + p['backward'] = not p['backward'] + p['start'], p['end'] = p['end'], p['start'] + p['duration'], p['playback'] = p['playback'], p['duration'] + snapshot(step) + return output + + +def inputs_and_expected(): + queries, runtime = cases() + data, expected = [], [] + for index, query in enumerate(queries): + d, rd, pd, pdel, repeats, delay = query + data.append('P ' + ' '.join(map(str, (index,) + query))) + result = INFINITE if repeats == INFINITE else (d + rd + pd + pdel) * max(1, repeats) + expected.append(('P', index, result, d, repeats, delay)) + for index, (mode, tick, configs, steps) in enumerate(runtime, 1000): + data.append('R ' + ' '.join(map(str, [index, mode, tick, len(configs), len(steps)]))) + for p in configs: + data.append(' '.join(str(int(p[k])) for k in ['duration', 'repeat_delay', 'playback', 'playback_delay', + 'repeat', 'delay', 'start', 'end', 'early', 'path', 'cb', + 'mutate', 'change_to'])) + data.append(' '.join(map(str, steps))) + expected.extend(expectation(configs, steps, index)) + return '\n'.join(data) + '\n', expected, dict(playtime_queries=len(queries), runtime_scenarios=len(runtime), observations=len(expected)) + + +def main(): + payload, expected, stats = inputs_and_expected() + scratch = Path(tempfile.mkdtemp(prefix='lvgl-observation-')) + # All files are prepared before starting any untrusted compiler or program. + with tarfile.open(HERE / 'support.tar') as bundle: + bundle.extractall(scratch) + target = scratch / 'src/misc/lv_anim.c' + target.write_bytes((Path(sys.argv[1]) / 'src/misc/lv_anim.c').read_bytes()) + (scratch / 'observer.c').write_bytes((HERE / 'observer.c').read_bytes()) + binary = scratch / 'observe' + command = ['gcc', '-std=c99', '-O2', '-Wall', '-Wextra', '-DLV_KCONFIG_IGNORE', + '-I' + str(scratch), '-I' + str(scratch / 'src'), + *[str(scratch / p) for p in SOURCES], str(scratch / 'observer.c'), '-o', str(binary)] + built = subprocess.run(command, capture_output=True, text=True, timeout=35) + if built.returncode: + print('FAIL build') + return 1 + run = subprocess.run([str(binary)], input=payload, capture_output=True, text=True, timeout=12) + if run.returncode: + print('FAIL candidate exit {}'.format(run.returncode)) + return 1 + try: + actual = [tuple([p[0]] + [int(x) for x in p[1:]]) for p in (line.split() for line in run.stdout.splitlines())] + except (ValueError, IndexError): + print('FAIL malformed observation') + return 1 + if actual != expected: + for index, (got, wanted) in enumerate(zip(actual, expected)): + if got != wanted: + print('FAIL observation {}: {} != {}'.format(index, got, wanted)) + return 1 + print('FAIL observation count {} != {}'.format(len(actual), len(expected))) + return 1 + print(json.dumps(stats, sort_keys=True)) + print('PASS') + return 0 + + +if __name__ == '__main__': + try: + sys.exit(main()) + except subprocess.TimeoutExpired: + print('FAIL child timeout') + sys.exit(1) diff --git a/tasks/runtime-lvgl-repeat-cadence/gold/src/misc/lv_anim.c b/tasks/runtime-lvgl-repeat-cadence/gold/src/misc/lv_anim.c new file mode 100644 index 00000000..c868b10d --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/gold/src/misc/lv_anim.c @@ -0,0 +1,716 @@ +/** + * @file lv_anim.c + * + */ + +/********************* + * INCLUDES + *********************/ +#include "lv_anim_private.h" + +#include "../core/lv_global.h" +#include "../tick/lv_tick.h" +#include "lv_assert.h" +#include "lv_timer.h" +#include "lv_math.h" +#include "../stdlib/lv_mem.h" +#include "../stdlib/lv_string.h" + +/********************* + * DEFINES + *********************/ +#define LV_ANIM_RESOLUTION 1024 +#define LV_ANIM_RES_SHIFT 10 +#define state LV_GLOBAL_DEFAULT()->anim_state +#define anim_ll_p &(state.anim_ll) + +/********************** + * TYPEDEFS + **********************/ + +/********************** + * STATIC PROTOTYPES + **********************/ +static void anim_timer(lv_timer_t * param); +static void anim_mark_list_change(void); +static void anim_completed_handler(lv_anim_t * a); +static int32_t lv_anim_path_cubic_bezier(const lv_anim_t * a, int32_t x1, + int32_t y1, int32_t x2, int32_t y2); +static uint32_t convert_speed_to_time(uint32_t speed, int32_t start, int32_t end); +static void resolve_time(lv_anim_t * a); +static bool remove_concurrent_anims(lv_anim_t * a_current); +static void remove_anim(void * a); + +/********************** + * STATIC VARIABLES + **********************/ + +/********************** + * MACROS + **********************/ +#if LV_USE_LOG && LV_LOG_TRACE_ANIM + #define LV_TRACE_ANIM(...) LV_LOG_TRACE(__VA_ARGS__) +#else + #define LV_TRACE_ANIM(...) +#endif + +/********************** + * GLOBAL FUNCTIONS + **********************/ + +void lv_anim_core_init(void) +{ + lv_ll_init(anim_ll_p, sizeof(lv_anim_t)); + state.timer = lv_timer_create(anim_timer, LV_DEF_REFR_PERIOD, NULL); + anim_mark_list_change(); /*Turn off the animation timer*/ + state.anim_list_changed = false; + state.anim_run_round = false; +} + +void lv_anim_core_deinit(void) +{ + lv_anim_delete_all(); +} + +void lv_anim_init(lv_anim_t * a) +{ + lv_memzero(a, sizeof(lv_anim_t)); + a->duration = 500; + a->start_value = 0; + a->end_value = 100; + a->repeat_cnt = 1; + a->path_cb = lv_anim_path_linear; + a->early_apply = 1; +} + +lv_anim_t * lv_anim_start(const lv_anim_t * a) +{ + LV_TRACE_ANIM("begin"); + + /*Add the new animation to the animation linked list*/ + lv_anim_t * new_anim = lv_ll_ins_head(anim_ll_p); + LV_ASSERT_MALLOC(new_anim); + if(new_anim == NULL) return NULL; + + /*Initialize the animation descriptor*/ + lv_memcpy(new_anim, a, sizeof(lv_anim_t)); + if(a->var == a) new_anim->var = new_anim; + new_anim->run_round = state.anim_run_round; + new_anim->last_timer_run = lv_tick_get(); + + /*Set the start value*/ + if(new_anim->early_apply) { + if(new_anim->get_value_cb) { + int32_t v_ofs = new_anim->get_value_cb(new_anim); + new_anim->start_value += v_ofs; + new_anim->end_value += v_ofs; + + } + + resolve_time(new_anim); + + /*Do not let two animations for the same 'var' with the same 'exec_cb'*/ + if(a->exec_cb || a->custom_exec_cb) remove_concurrent_anims(new_anim); + + if(new_anim->exec_cb) { + new_anim->exec_cb(new_anim->var, new_anim->start_value); + } + if(new_anim->custom_exec_cb) { + new_anim->custom_exec_cb(new_anim, new_anim->start_value); + } + } + + /*Creating an animation changed the linked list. + *It's important if it happens in a ready callback. (see `anim_timer`)*/ + anim_mark_list_change(); + + LV_TRACE_ANIM("finished"); + return new_anim; +} + +uint32_t lv_anim_get_playtime(const lv_anim_t * a) +{ + if(a->repeat_cnt == LV_ANIM_REPEAT_INFINITE) { + return LV_ANIM_PLAYTIME_INFINITE; + } + + uint32_t repeat_cnt = a->repeat_cnt; + if(repeat_cnt < 1) repeat_cnt = 1; + + uint32_t playtime = a->repeat_delay + a->duration + a->playback_delay + a->playback_duration; + playtime = playtime * repeat_cnt; + return playtime; +} + +bool lv_anim_delete(void * var, lv_anim_exec_xcb_t exec_cb) +{ + lv_anim_t * a; + bool del_any = false; + a = lv_ll_get_head(anim_ll_p); + while(a != NULL) { + bool del = false; + if((a->var == var || var == NULL) && (a->exec_cb == exec_cb || exec_cb == NULL)) { + remove_anim(a); + anim_mark_list_change(); /*Read by `anim_timer`. It need to know if a delete occurred in + the linked list*/ + del_any = true; + del = true; + } + + /*Always start from the head on delete, because we don't know + *how `anim_ll_p` was changes in `a->deleted_cb` */ + a = del ? lv_ll_get_head(anim_ll_p) : lv_ll_get_next(anim_ll_p, a); + } + + return del_any; +} + +void lv_anim_delete_all(void) +{ + lv_ll_clear_custom(anim_ll_p, remove_anim); + anim_mark_list_change(); +} + +lv_anim_t * lv_anim_get(void * var, lv_anim_exec_xcb_t exec_cb) +{ + lv_anim_t * a; + LV_LL_READ(anim_ll_p, a) { + if(a->var == var && (a->exec_cb == exec_cb || exec_cb == NULL)) { + return a; + } + } + + return NULL; +} + +lv_timer_t * lv_anim_get_timer(void) +{ + return state.timer; +} + +uint16_t lv_anim_count_running(void) +{ + uint16_t cnt = 0; + lv_anim_t * a; + LV_LL_READ(anim_ll_p, a) cnt++; + + return cnt; +} + +uint32_t lv_anim_speed_clamped(uint32_t speed, uint32_t min_time, uint32_t max_time) +{ + + if(speed > 10000) { + LV_LOG_WARN("speed is truncated to 10000 (was %"LV_PRIu32")", speed); + speed = 10230; + } + if(min_time > 10000) { + LV_LOG_WARN("min_time is truncated to 10000 (was %"LV_PRIu32")", min_time); + min_time = 10230; + } + if(max_time > 10000) { + LV_LOG_WARN("max_time is truncated to 10000 (was %"LV_PRIu32")", max_time); + max_time = 10230; + } + + /*Lower the resolution to fit the 0.1023 range*/ + speed = (speed + 5) / 10; + min_time = (min_time + 5) / 10; + max_time = (max_time + 5) / 10; + + return 0x80000000 + (max_time << 20) + (min_time << 10) + speed; + +} + +uint32_t lv_anim_speed(uint32_t speed) +{ + return lv_anim_speed_clamped(speed, 0, 10000); +} + +uint32_t lv_anim_speed_to_time(uint32_t speed, int32_t start, int32_t end) +{ + uint32_t d = LV_ABS(start - end); + uint32_t time = (d * 1000) / speed; + + time = time == 0 ? 1 : time; + + return time; +} + +void lv_anim_refr_now(void) +{ + anim_timer(NULL); +} + +int32_t lv_anim_path_linear(const lv_anim_t * a) +{ + /*Calculate the current step*/ + int32_t step = lv_map(a->act_time, 0, a->duration, 0, LV_ANIM_RESOLUTION); + + /*Get the new value which will be proportional to `step` + *and the `start` and `end` values*/ + int32_t new_value; + new_value = step * (a->end_value - a->start_value); + new_value = new_value >> LV_ANIM_RES_SHIFT; + new_value += a->start_value; + + return new_value; +} + +int32_t lv_anim_path_ease_in(const lv_anim_t * a) +{ + return lv_anim_path_cubic_bezier(a, LV_BEZIER_VAL_FLOAT(0.42), LV_BEZIER_VAL_FLOAT(0), + LV_BEZIER_VAL_FLOAT(1), LV_BEZIER_VAL_FLOAT(1)); +} + +int32_t lv_anim_path_ease_out(const lv_anim_t * a) +{ + return lv_anim_path_cubic_bezier(a, LV_BEZIER_VAL_FLOAT(0), LV_BEZIER_VAL_FLOAT(0), + LV_BEZIER_VAL_FLOAT(0.58), LV_BEZIER_VAL_FLOAT(1)); +} + +int32_t lv_anim_path_ease_in_out(const lv_anim_t * a) +{ + return lv_anim_path_cubic_bezier(a, LV_BEZIER_VAL_FLOAT(0.42), LV_BEZIER_VAL_FLOAT(0), + LV_BEZIER_VAL_FLOAT(0.58), LV_BEZIER_VAL_FLOAT(1)); +} + +int32_t lv_anim_path_overshoot(const lv_anim_t * a) +{ + return lv_anim_path_cubic_bezier(a, 341, 0, 683, 1300); +} + +int32_t lv_anim_path_bounce(const lv_anim_t * a) +{ + /*Calculate the current step*/ + int32_t t = lv_map(a->act_time, 0, a->duration, 0, LV_BEZIER_VAL_MAX); + int32_t diff = (a->end_value - a->start_value); + + /*3 bounces has 5 parts: 3 down and 2 up. One part is t / 5 long*/ + + if(t < 408) { + /*Go down*/ + t = (t * 2500) >> LV_BEZIER_VAL_SHIFT; /*[0..1024] range*/ + t = LV_BEZIER_VAL_MAX - t; + } + else if(t >= 408 && t < 614) { + /*First bounce back*/ + t -= 408; + t = t * 5; /*to [0..1024] range*/ + diff = diff / 20; + } + else if(t >= 614 && t < 819) { + /*Fall back*/ + t -= 614; + t = t * 5; /*to [0..1024] range*/ + t = LV_BEZIER_VAL_MAX - t; + diff = diff / 20; + } + else if(t >= 819 && t < 921) { + /*Second bounce back*/ + t -= 819; + t = t * 10; /*to [0..1024] range*/ + diff = diff / 40; + } + else if(t >= 921 && t <= LV_BEZIER_VAL_MAX) { + /*Fall back*/ + t -= 921; + t = t * 10; /*to [0..1024] range*/ + t = LV_BEZIER_VAL_MAX - t; + diff = diff / 40; + } + + if(t > LV_BEZIER_VAL_MAX) t = LV_BEZIER_VAL_MAX; + if(t < 0) t = 0; + int32_t step = lv_bezier3(t, 0, 500, 800, LV_BEZIER_VAL_MAX); + + int32_t new_value; + new_value = step * diff; + new_value = new_value >> LV_BEZIER_VAL_SHIFT; + new_value = a->end_value - new_value; + + return new_value; +} + +int32_t lv_anim_path_step(const lv_anim_t * a) +{ + if(a->act_time >= a->duration) + return a->end_value; + else + return a->start_value; +} + +int32_t lv_anim_path_custom_bezier3(const lv_anim_t * a) +{ + const lv_anim_bezier3_para_t * para = &a->parameter.bezier3; + return lv_anim_path_cubic_bezier(a, para->x1, para->y1, para->x2, para->y2); +} + +void lv_anim_set_var(lv_anim_t * a, void * var) +{ + a->var = var; +} + +void lv_anim_set_exec_cb(lv_anim_t * a, lv_anim_exec_xcb_t exec_cb) +{ + a->exec_cb = exec_cb; +} + +void lv_anim_set_duration(lv_anim_t * a, uint32_t duration) +{ + a->duration = duration; +} + +void lv_anim_set_time(lv_anim_t * a, uint32_t duration) +{ + lv_anim_set_duration(a, duration); +} + +void lv_anim_set_delay(lv_anim_t * a, uint32_t delay) +{ + a->act_time = -(int32_t)(delay); +} + +void lv_anim_set_values(lv_anim_t * a, int32_t start, int32_t end) +{ + a->start_value = start; + a->current_value = INT32_MIN; + a->end_value = end; +} + +void lv_anim_set_custom_exec_cb(lv_anim_t * a, lv_anim_custom_exec_cb_t exec_cb) +{ + a->custom_exec_cb = exec_cb; +} + +void lv_anim_set_path_cb(lv_anim_t * a, lv_anim_path_cb_t path_cb) +{ + a->path_cb = path_cb; +} + +void lv_anim_set_start_cb(lv_anim_t * a, lv_anim_start_cb_t start_cb) +{ + a->start_cb = start_cb; +} + +void lv_anim_set_get_value_cb(lv_anim_t * a, lv_anim_get_value_cb_t get_value_cb) +{ + a->get_value_cb = get_value_cb; +} + +void lv_anim_set_completed_cb(lv_anim_t * a, lv_anim_completed_cb_t completed_cb) +{ + a->completed_cb = completed_cb; +} + +void lv_anim_set_deleted_cb(lv_anim_t * a, lv_anim_deleted_cb_t deleted_cb) +{ + a->deleted_cb = deleted_cb; +} + +void lv_anim_set_playback_duration(lv_anim_t * a, uint32_t duration) +{ + a->playback_duration = duration; +} + +void lv_anim_set_playback_time(lv_anim_t * a, uint32_t duration) +{ + lv_anim_set_playback_duration(a, duration); +} + +void lv_anim_set_playback_delay(lv_anim_t * a, uint32_t delay) +{ + a->playback_delay = delay; +} + +void lv_anim_set_repeat_count(lv_anim_t * a, uint32_t cnt) +{ + a->repeat_cnt = cnt; +} + +void lv_anim_set_repeat_delay(lv_anim_t * a, uint32_t delay) +{ + a->repeat_delay = delay; +} + +void lv_anim_set_early_apply(lv_anim_t * a, bool en) +{ + a->early_apply = en; +} + +void lv_anim_set_user_data(lv_anim_t * a, void * user_data) +{ + a->user_data = user_data; +} + +void lv_anim_set_bezier3_param(lv_anim_t * a, int16_t x1, int16_t y1, int16_t x2, int16_t y2) +{ + lv_anim_bezier3_para_t * para = &a->parameter.bezier3; + + para->x1 = x1; + para->x2 = x2; + para->y1 = y1; + para->y2 = y2; +} + +uint32_t lv_anim_get_delay(const lv_anim_t * a) +{ + return -a->act_time; +} + +uint32_t lv_anim_get_time(const lv_anim_t * a) +{ + return a->duration; +} + +uint32_t lv_anim_get_repeat_count(const lv_anim_t * a) +{ + return a->repeat_cnt; +} + +void * lv_anim_get_user_data(const lv_anim_t * a) +{ + return a->user_data; +} + +bool lv_anim_custom_delete(lv_anim_t * a, lv_anim_custom_exec_cb_t exec_cb) +{ + return lv_anim_delete(a ? a->var : NULL, (lv_anim_exec_xcb_t)exec_cb); +} + +lv_anim_t * lv_anim_custom_get(lv_anim_t * a, lv_anim_custom_exec_cb_t exec_cb) +{ + return lv_anim_get(a ? a->var : NULL, (lv_anim_exec_xcb_t)exec_cb); +} + +/********************** + * STATIC FUNCTIONS + **********************/ +/** + * Periodically handle the animations. + * @param param unused + */ +static void anim_timer(lv_timer_t * param) +{ + LV_UNUSED(param); + + /*Flip the run round*/ + state.anim_run_round = state.anim_run_round ? false : true; + + lv_anim_t * a = lv_ll_get_head(anim_ll_p); + + while(a != NULL) { + uint32_t elaps = lv_tick_elaps(a->last_timer_run); + a->act_time += elaps; + + a->last_timer_run = lv_tick_get(); + + /*It can be set by `lv_anim_delete()` typically in `end_cb`. If set then an animation delete + * happened in `anim_completed_handler` which could make this linked list reading corrupt + * because the list is changed meanwhile + */ + state.anim_list_changed = false; + + if(a->run_round != state.anim_run_round) { + a->run_round = state.anim_run_round; /*The list readying might be reset so need to know which anim has run already*/ + + /*The animation will run now for the first time. Call `start_cb`*/ + if(!a->start_cb_called && a->act_time >= 0) { + + if(a->early_apply == 0 && a->get_value_cb) { + int32_t v_ofs = a->get_value_cb(a); + a->start_value += v_ofs; + a->end_value += v_ofs; + } + + resolve_time(a); + + if(a->start_cb) a->start_cb(a); + a->start_cb_called = 1; + + /*Do not let two animations for the same 'var' with the same 'exec_cb'*/ + remove_concurrent_anims(a); + } + + if(a->act_time >= 0) { + int32_t act_time_original = a->act_time; /*The unclipped version is used later to correctly repeat the animation*/ + if(a->act_time > a->duration) a->act_time = a->duration; + + int32_t act_time_before_exec = a->act_time; + int32_t new_value; + new_value = a->path_cb(a); + + if(new_value != a->current_value) { + a->current_value = new_value; + /*Apply the calculated value*/ + if(a->exec_cb) a->exec_cb(a->var, new_value); + if(!state.anim_list_changed && a->custom_exec_cb) a->custom_exec_cb(a, new_value); + } + + /*Restore the original time to see is there is over time. + *Restore only if it wasn't changed in the `exec_cb` for some special reasons.*/ + if(a->act_time == act_time_before_exec) a->act_time = act_time_original; + + /*If the time is elapsed the animation is ready*/ + if(!state.anim_list_changed && a->act_time >= a->duration) { + anim_completed_handler(a); + } + } + } + + /*If the linked list changed due to anim. delete then it's not safe to continue + *the reading of the list from here -> start from the head*/ + if(state.anim_list_changed) + a = lv_ll_get_head(anim_ll_p); + else + a = lv_ll_get_next(anim_ll_p, a); + } + +} + +/** + * Called when an animation is completed to do the necessary things + * e.g. repeat, play back, delete etc. + * @param a pointer to an animation descriptor + */ +static void anim_completed_handler(lv_anim_t * a) +{ + /*In the end of a forward anim decrement repeat cnt.*/ + if(a->playback_now == 0 && a->repeat_cnt > 0 && a->repeat_cnt != LV_ANIM_REPEAT_INFINITE) { + a->repeat_cnt--; + } + + /*Delete the animation if + * - no repeat left and no play back (simple one shot animation) + * - no repeat, play back is enabled and play back is ready*/ + if(a->repeat_cnt == 0 && (a->playback_duration == 0 || a->playback_now == 1)) { + + /*Delete the animation from the list. + * This way the `completed_cb` will see the animations like it's animation is already deleted*/ + lv_ll_remove(anim_ll_p, a); + /*Flag that the list has changed*/ + anim_mark_list_change(); + + /*Call the callback function at the end*/ + if(a->completed_cb != NULL) a->completed_cb(a); + if(a->deleted_cb != NULL) a->deleted_cb(a); + lv_free(a); + } + /*If the animation is not deleted then restart it*/ + else { + /*Restart the animation. If the time is over a little compensate it.*/ + int32_t over_time = 0; + if(a->act_time > a->duration) over_time = a->act_time - a->duration; + a->act_time = over_time - (int32_t)(a->repeat_delay); + /*Swap the start and end values in play back mode*/ + if(a->playback_duration != 0) { + /*If now turning back use the 'playback_pause*/ + if(a->playback_now == 0) a->act_time = -(int32_t)(a->playback_delay); + + /*Toggle the play back state*/ + a->playback_now = a->playback_now == 0 ? 1 : 0; + /*Swap the start and end values*/ + int32_t tmp = a->start_value; + a->start_value = a->end_value; + a->end_value = tmp; + /*Swap the time and playback_duration*/ + tmp = a->duration; + a->duration = a->playback_duration; + a->playback_duration = tmp; + } + } +} + +static void anim_mark_list_change(void) +{ + state.anim_list_changed = true; + if(lv_ll_get_head(anim_ll_p) == NULL) + lv_timer_pause(state.timer); + else + lv_timer_resume(state.timer); +} + +static int32_t lv_anim_path_cubic_bezier(const lv_anim_t * a, int32_t x1, int32_t y1, int32_t x2, int32_t y2) +{ + /*Calculate the current step*/ + uint32_t t = lv_map(a->act_time, 0, a->duration, 0, LV_BEZIER_VAL_MAX); + int32_t step = lv_cubic_bezier(t, x1, y1, x2, y2); + + int32_t new_value; + new_value = step * (a->end_value - a->start_value); + new_value = new_value >> LV_BEZIER_VAL_SHIFT; + new_value += a->start_value; + + return new_value; +} + +static uint32_t convert_speed_to_time(uint32_t speed_or_time, int32_t start, int32_t end) +{ + /*It was a simple time*/ + if((speed_or_time & 0x80000000) == 0) return speed_or_time; + + uint32_t d = LV_ABS(start - end); + uint32_t speed = speed_or_time & 0x3FF; + uint32_t time = (d * 100) / speed; /*Speed is in 10 units per sec*/ + uint32_t max_time = (speed_or_time >> 20) & 0x3FF; + uint32_t min_time = (speed_or_time >> 10) & 0x3FF; + + return LV_CLAMP(min_time * 10, time, max_time * 10); +} + +static void resolve_time(lv_anim_t * a) +{ + a->duration = convert_speed_to_time(a->duration, a->start_value, a->end_value); + a->playback_duration = convert_speed_to_time(a->playback_duration, a->start_value, a->end_value); + a->playback_delay = convert_speed_to_time(a->playback_delay, a->start_value, a->end_value); + a->repeat_delay = convert_speed_to_time(a->repeat_delay, a->start_value, a->end_value); +} + +/** + * Remove animations which are animating the same var with the same exec_cb + * and they are already running or they have early_apply + * @param a_current the current animation, use its var and exec_cb as reference to know what to remove + * @return true: at least one animation was delete + */ +static bool remove_concurrent_anims(lv_anim_t * a_current) +{ + if(a_current->exec_cb == NULL && a_current->custom_exec_cb == NULL) return false; + + lv_anim_t * a; + bool del_any = false; + a = lv_ll_get_head(anim_ll_p); + while(a != NULL) { + bool del = false; + /*We can't test for custom_exec_cb equality because in the MicroPython binding + *a wrapper callback is used here an the real callback data is stored in the `user_data`. + *Therefore equality check would remove all animations.*/ + if(a != a_current && + (a->act_time >= 0 || a->early_apply) && + (a->var == a_current->var) && + ((a->exec_cb && a->exec_cb == a_current->exec_cb) + /*|| (a->custom_exec_cb && a->custom_exec_cb == a_current->custom_exec_cb)*/)) { + lv_ll_remove(anim_ll_p, a); + if(a->deleted_cb != NULL) a->deleted_cb(a); + lv_free(a); + /*Read by `anim_timer`. It need to know if a delete occurred in the linked list*/ + anim_mark_list_change(); + + del_any = true; + del = true; + } + + /*Always start from the head on delete, because we don't know + *how `anim_ll_p` was changes in `a->deleted_cb` */ + a = del ? lv_ll_get_head(anim_ll_p) : lv_ll_get_next(anim_ll_p, a); + } + + return del_any; +} + +static void remove_anim(void * a) +{ + lv_anim_t * anim = a; + lv_ll_remove(anim_ll_p, a); + if(anim->deleted_cb != NULL) anim->deleted_cb(anim); + lv_free(a); +} diff --git a/tasks/runtime-lvgl-repeat-cadence/noop/src/misc/lv_anim.c b/tasks/runtime-lvgl-repeat-cadence/noop/src/misc/lv_anim.c new file mode 100644 index 00000000..db33a2cd --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/noop/src/misc/lv_anim.c @@ -0,0 +1,716 @@ +/** + * @file lv_anim.c + * + */ + +/********************* + * INCLUDES + *********************/ +#include "lv_anim_private.h" + +#include "../core/lv_global.h" +#include "../tick/lv_tick.h" +#include "lv_assert.h" +#include "lv_timer.h" +#include "lv_math.h" +#include "../stdlib/lv_mem.h" +#include "../stdlib/lv_string.h" + +/********************* + * DEFINES + *********************/ +#define LV_ANIM_RESOLUTION 1024 +#define LV_ANIM_RES_SHIFT 10 +#define state LV_GLOBAL_DEFAULT()->anim_state +#define anim_ll_p &(state.anim_ll) + +/********************** + * TYPEDEFS + **********************/ + +/********************** + * STATIC PROTOTYPES + **********************/ +static void anim_timer(lv_timer_t * param); +static void anim_mark_list_change(void); +static void anim_completed_handler(lv_anim_t * a); +static int32_t lv_anim_path_cubic_bezier(const lv_anim_t * a, int32_t x1, + int32_t y1, int32_t x2, int32_t y2); +static uint32_t convert_speed_to_time(uint32_t speed, int32_t start, int32_t end); +static void resolve_time(lv_anim_t * a); +static bool remove_concurrent_anims(lv_anim_t * a_current); +static void remove_anim(void * a); + +/********************** + * STATIC VARIABLES + **********************/ + +/********************** + * MACROS + **********************/ +#if LV_USE_LOG && LV_LOG_TRACE_ANIM + #define LV_TRACE_ANIM(...) LV_LOG_TRACE(__VA_ARGS__) +#else + #define LV_TRACE_ANIM(...) +#endif + +/********************** + * GLOBAL FUNCTIONS + **********************/ + +void lv_anim_core_init(void) +{ + lv_ll_init(anim_ll_p, sizeof(lv_anim_t)); + state.timer = lv_timer_create(NULL, LV_DEF_REFR_PERIOD, NULL); + anim_mark_list_change(); /*Turn off the animation timer*/ + state.anim_list_changed = false; + state.anim_run_round = false; +} + +void lv_anim_core_deinit(void) +{ + lv_anim_delete_all(); +} + +void lv_anim_init(lv_anim_t * a) +{ + lv_memzero(a, sizeof(lv_anim_t)); + a->duration = 500; + a->start_value = 0; + a->end_value = 100; + a->repeat_cnt = 1; + a->path_cb = lv_anim_path_linear; + a->early_apply = 1; +} + +lv_anim_t * lv_anim_start(const lv_anim_t * a) +{ + LV_TRACE_ANIM("begin"); + + /*Add the new animation to the animation linked list*/ + lv_anim_t * new_anim = lv_ll_ins_head(anim_ll_p); + LV_ASSERT_MALLOC(new_anim); + if(new_anim == NULL) return NULL; + + /*Initialize the animation descriptor*/ + lv_memcpy(new_anim, a, sizeof(lv_anim_t)); + if(a->var == a) new_anim->var = new_anim; + new_anim->run_round = state.anim_run_round; + new_anim->last_timer_run = lv_tick_get(); + + /*Set the start value*/ + if(new_anim->early_apply) { + if(new_anim->get_value_cb) { + int32_t v_ofs = new_anim->get_value_cb(new_anim); + new_anim->start_value += v_ofs; + new_anim->end_value += v_ofs; + + } + + resolve_time(new_anim); + + /*Do not let two animations for the same 'var' with the same 'exec_cb'*/ + if(a->exec_cb || a->custom_exec_cb) remove_concurrent_anims(new_anim); + + if(new_anim->exec_cb) { + new_anim->exec_cb(new_anim->var, new_anim->start_value); + } + if(new_anim->custom_exec_cb) { + new_anim->custom_exec_cb(new_anim, new_anim->start_value); + } + } + + /*Creating an animation changed the linked list. + *It's important if it happens in a ready callback. (see `anim_timer`)*/ + anim_mark_list_change(); + + LV_TRACE_ANIM("finished"); + return new_anim; +} + +uint32_t lv_anim_get_playtime(const lv_anim_t * a) +{ + if(a->repeat_cnt == LV_ANIM_REPEAT_INFINITE) { + return LV_ANIM_PLAYTIME_INFINITE; + } + + uint32_t repeat_cnt = a->repeat_cnt; + if(repeat_cnt < 1) repeat_cnt = 1; + + uint32_t playtime = a->repeat_delay + a->duration + a->playback_delay + a->playback_duration; + playtime = playtime * repeat_cnt; + return playtime; +} + +bool lv_anim_delete(void * var, lv_anim_exec_xcb_t exec_cb) +{ + lv_anim_t * a; + bool del_any = false; + a = lv_ll_get_head(anim_ll_p); + while(a != NULL) { + bool del = false; + if((a->var == var || var == NULL) && (a->exec_cb == exec_cb || exec_cb == NULL)) { + remove_anim(a); + anim_mark_list_change(); /*Read by `anim_timer`. It need to know if a delete occurred in + the linked list*/ + del_any = true; + del = true; + } + + /*Always start from the head on delete, because we don't know + *how `anim_ll_p` was changes in `a->deleted_cb` */ + a = del ? lv_ll_get_head(anim_ll_p) : lv_ll_get_next(anim_ll_p, a); + } + + return del_any; +} + +void lv_anim_delete_all(void) +{ + lv_ll_clear_custom(anim_ll_p, remove_anim); + anim_mark_list_change(); +} + +lv_anim_t * lv_anim_get(void * var, lv_anim_exec_xcb_t exec_cb) +{ + lv_anim_t * a; + LV_LL_READ(anim_ll_p, a) { + if(a->var == var && (a->exec_cb == exec_cb || exec_cb == NULL)) { + return a; + } + } + + return NULL; +} + +lv_timer_t * lv_anim_get_timer(void) +{ + return state.timer; +} + +uint16_t lv_anim_count_running(void) +{ + uint16_t cnt = 0; + lv_anim_t * a; + LV_LL_READ(anim_ll_p, a) cnt++; + + return cnt; +} + +uint32_t lv_anim_speed_clamped(uint32_t speed, uint32_t min_time, uint32_t max_time) +{ + + if(speed > 10000) { + LV_LOG_WARN("speed is truncated to 10000 (was %"LV_PRIu32")", speed); + speed = 10230; + } + if(min_time > 10000) { + LV_LOG_WARN("min_time is truncated to 10000 (was %"LV_PRIu32")", min_time); + min_time = 10230; + } + if(max_time > 10000) { + LV_LOG_WARN("max_time is truncated to 10000 (was %"LV_PRIu32")", max_time); + max_time = 10230; + } + + /*Lower the resolution to fit the 0.1023 range*/ + speed = (speed + 5) / 10; + min_time = (min_time + 5) / 10; + max_time = (max_time + 5) / 10; + + return 0x80000000 + (max_time << 20) + (min_time << 10) + speed; + +} + +uint32_t lv_anim_speed(uint32_t speed) +{ + return lv_anim_speed_clamped(speed, 0, 10000); +} + +uint32_t lv_anim_speed_to_time(uint32_t speed, int32_t start, int32_t end) +{ + uint32_t d = LV_ABS(start - end); + uint32_t time = (d * 1000) / speed; + + time = time == 0 ? 1 : time; + + return time; +} + +void lv_anim_refr_now(void) +{ + return; +} + +int32_t lv_anim_path_linear(const lv_anim_t * a) +{ + /*Calculate the current step*/ + int32_t step = lv_map(a->act_time, 0, a->duration, 0, LV_ANIM_RESOLUTION); + + /*Get the new value which will be proportional to `step` + *and the `start` and `end` values*/ + int32_t new_value; + new_value = step * (a->end_value - a->start_value); + new_value = new_value >> LV_ANIM_RES_SHIFT; + new_value += a->start_value; + + return new_value; +} + +int32_t lv_anim_path_ease_in(const lv_anim_t * a) +{ + return lv_anim_path_cubic_bezier(a, LV_BEZIER_VAL_FLOAT(0.42), LV_BEZIER_VAL_FLOAT(0), + LV_BEZIER_VAL_FLOAT(1), LV_BEZIER_VAL_FLOAT(1)); +} + +int32_t lv_anim_path_ease_out(const lv_anim_t * a) +{ + return lv_anim_path_cubic_bezier(a, LV_BEZIER_VAL_FLOAT(0), LV_BEZIER_VAL_FLOAT(0), + LV_BEZIER_VAL_FLOAT(0.58), LV_BEZIER_VAL_FLOAT(1)); +} + +int32_t lv_anim_path_ease_in_out(const lv_anim_t * a) +{ + return lv_anim_path_cubic_bezier(a, LV_BEZIER_VAL_FLOAT(0.42), LV_BEZIER_VAL_FLOAT(0), + LV_BEZIER_VAL_FLOAT(0.58), LV_BEZIER_VAL_FLOAT(1)); +} + +int32_t lv_anim_path_overshoot(const lv_anim_t * a) +{ + return lv_anim_path_cubic_bezier(a, 341, 0, 683, 1300); +} + +int32_t lv_anim_path_bounce(const lv_anim_t * a) +{ + /*Calculate the current step*/ + int32_t t = lv_map(a->act_time, 0, a->duration, 0, LV_BEZIER_VAL_MAX); + int32_t diff = (a->end_value - a->start_value); + + /*3 bounces has 5 parts: 3 down and 2 up. One part is t / 5 long*/ + + if(t < 408) { + /*Go down*/ + t = (t * 2500) >> LV_BEZIER_VAL_SHIFT; /*[0..1024] range*/ + t = LV_BEZIER_VAL_MAX - t; + } + else if(t >= 408 && t < 614) { + /*First bounce back*/ + t -= 408; + t = t * 5; /*to [0..1024] range*/ + diff = diff / 20; + } + else if(t >= 614 && t < 819) { + /*Fall back*/ + t -= 614; + t = t * 5; /*to [0..1024] range*/ + t = LV_BEZIER_VAL_MAX - t; + diff = diff / 20; + } + else if(t >= 819 && t < 921) { + /*Second bounce back*/ + t -= 819; + t = t * 10; /*to [0..1024] range*/ + diff = diff / 40; + } + else if(t >= 921 && t <= LV_BEZIER_VAL_MAX) { + /*Fall back*/ + t -= 921; + t = t * 10; /*to [0..1024] range*/ + t = LV_BEZIER_VAL_MAX - t; + diff = diff / 40; + } + + if(t > LV_BEZIER_VAL_MAX) t = LV_BEZIER_VAL_MAX; + if(t < 0) t = 0; + int32_t step = lv_bezier3(t, 0, 500, 800, LV_BEZIER_VAL_MAX); + + int32_t new_value; + new_value = step * diff; + new_value = new_value >> LV_BEZIER_VAL_SHIFT; + new_value = a->end_value - new_value; + + return new_value; +} + +int32_t lv_anim_path_step(const lv_anim_t * a) +{ + if(a->act_time >= a->duration) + return a->end_value; + else + return a->start_value; +} + +int32_t lv_anim_path_custom_bezier3(const lv_anim_t * a) +{ + const lv_anim_bezier3_para_t * para = &a->parameter.bezier3; + return lv_anim_path_cubic_bezier(a, para->x1, para->y1, para->x2, para->y2); +} + +void lv_anim_set_var(lv_anim_t * a, void * var) +{ + a->var = var; +} + +void lv_anim_set_exec_cb(lv_anim_t * a, lv_anim_exec_xcb_t exec_cb) +{ + a->exec_cb = exec_cb; +} + +void lv_anim_set_duration(lv_anim_t * a, uint32_t duration) +{ + a->duration = duration; +} + +void lv_anim_set_time(lv_anim_t * a, uint32_t duration) +{ + lv_anim_set_duration(a, duration); +} + +void lv_anim_set_delay(lv_anim_t * a, uint32_t delay) +{ + a->act_time = -(int32_t)(delay); +} + +void lv_anim_set_values(lv_anim_t * a, int32_t start, int32_t end) +{ + a->start_value = start; + a->current_value = INT32_MIN; + a->end_value = end; +} + +void lv_anim_set_custom_exec_cb(lv_anim_t * a, lv_anim_custom_exec_cb_t exec_cb) +{ + a->custom_exec_cb = exec_cb; +} + +void lv_anim_set_path_cb(lv_anim_t * a, lv_anim_path_cb_t path_cb) +{ + a->path_cb = path_cb; +} + +void lv_anim_set_start_cb(lv_anim_t * a, lv_anim_start_cb_t start_cb) +{ + a->start_cb = start_cb; +} + +void lv_anim_set_get_value_cb(lv_anim_t * a, lv_anim_get_value_cb_t get_value_cb) +{ + a->get_value_cb = get_value_cb; +} + +void lv_anim_set_completed_cb(lv_anim_t * a, lv_anim_completed_cb_t completed_cb) +{ + a->completed_cb = completed_cb; +} + +void lv_anim_set_deleted_cb(lv_anim_t * a, lv_anim_deleted_cb_t deleted_cb) +{ + a->deleted_cb = deleted_cb; +} + +void lv_anim_set_playback_duration(lv_anim_t * a, uint32_t duration) +{ + a->playback_duration = duration; +} + +void lv_anim_set_playback_time(lv_anim_t * a, uint32_t duration) +{ + lv_anim_set_playback_duration(a, duration); +} + +void lv_anim_set_playback_delay(lv_anim_t * a, uint32_t delay) +{ + a->playback_delay = delay; +} + +void lv_anim_set_repeat_count(lv_anim_t * a, uint32_t cnt) +{ + a->repeat_cnt = cnt; +} + +void lv_anim_set_repeat_delay(lv_anim_t * a, uint32_t delay) +{ + a->repeat_delay = delay; +} + +void lv_anim_set_early_apply(lv_anim_t * a, bool en) +{ + a->early_apply = en; +} + +void lv_anim_set_user_data(lv_anim_t * a, void * user_data) +{ + a->user_data = user_data; +} + +void lv_anim_set_bezier3_param(lv_anim_t * a, int16_t x1, int16_t y1, int16_t x2, int16_t y2) +{ + lv_anim_bezier3_para_t * para = &a->parameter.bezier3; + + para->x1 = x1; + para->x2 = x2; + para->y1 = y1; + para->y2 = y2; +} + +uint32_t lv_anim_get_delay(const lv_anim_t * a) +{ + return -a->act_time; +} + +uint32_t lv_anim_get_time(const lv_anim_t * a) +{ + return a->duration; +} + +uint32_t lv_anim_get_repeat_count(const lv_anim_t * a) +{ + return a->repeat_cnt; +} + +void * lv_anim_get_user_data(const lv_anim_t * a) +{ + return a->user_data; +} + +bool lv_anim_custom_delete(lv_anim_t * a, lv_anim_custom_exec_cb_t exec_cb) +{ + return lv_anim_delete(a ? a->var : NULL, (lv_anim_exec_xcb_t)exec_cb); +} + +lv_anim_t * lv_anim_custom_get(lv_anim_t * a, lv_anim_custom_exec_cb_t exec_cb) +{ + return lv_anim_get(a ? a->var : NULL, (lv_anim_exec_xcb_t)exec_cb); +} + +/********************** + * STATIC FUNCTIONS + **********************/ +/** + * Periodically handle the animations. + * @param param unused + */ +static void anim_timer(lv_timer_t * param) +{ + LV_UNUSED(param); + + /*Flip the run round*/ + state.anim_run_round = state.anim_run_round ? false : true; + + lv_anim_t * a = lv_ll_get_head(anim_ll_p); + + while(a != NULL) { + uint32_t elaps = lv_tick_elaps(a->last_timer_run); + a->act_time += elaps; + + a->last_timer_run = lv_tick_get(); + + /*It can be set by `lv_anim_delete()` typically in `end_cb`. If set then an animation delete + * happened in `anim_completed_handler` which could make this linked list reading corrupt + * because the list is changed meanwhile + */ + state.anim_list_changed = false; + + if(a->run_round != state.anim_run_round) { + a->run_round = state.anim_run_round; /*The list readying might be reset so need to know which anim has run already*/ + + /*The animation will run now for the first time. Call `start_cb`*/ + if(!a->start_cb_called && a->act_time >= 0) { + + if(a->early_apply == 0 && a->get_value_cb) { + int32_t v_ofs = a->get_value_cb(a); + a->start_value += v_ofs; + a->end_value += v_ofs; + } + + resolve_time(a); + + if(a->start_cb) a->start_cb(a); + a->start_cb_called = 1; + + /*Do not let two animations for the same 'var' with the same 'exec_cb'*/ + remove_concurrent_anims(a); + } + + if(a->act_time >= 0) { + int32_t act_time_original = a->act_time; /*The unclipped version is used later to correctly repeat the animation*/ + if(a->act_time > a->duration) a->act_time = a->duration; + + int32_t act_time_before_exec = a->act_time; + int32_t new_value; + new_value = a->path_cb(a); + + if(new_value != a->current_value) { + a->current_value = new_value; + /*Apply the calculated value*/ + if(a->exec_cb) a->exec_cb(a->var, new_value); + if(!state.anim_list_changed && a->custom_exec_cb) a->custom_exec_cb(a, new_value); + } + + /*Restore the original time to see is there is over time. + *Restore only if it wasn't changed in the `exec_cb` for some special reasons.*/ + if(a->act_time == act_time_before_exec) a->act_time = act_time_original; + + /*If the time is elapsed the animation is ready*/ + if(!state.anim_list_changed && a->act_time >= a->duration) { + anim_completed_handler(a); + } + } + } + + /*If the linked list changed due to anim. delete then it's not safe to continue + *the reading of the list from here -> start from the head*/ + if(state.anim_list_changed) + a = lv_ll_get_head(anim_ll_p); + else + a = lv_ll_get_next(anim_ll_p, a); + } + +} + +/** + * Called when an animation is completed to do the necessary things + * e.g. repeat, play back, delete etc. + * @param a pointer to an animation descriptor + */ +static void anim_completed_handler(lv_anim_t * a) +{ + /*In the end of a forward anim decrement repeat cnt.*/ + if(a->playback_now == 0 && a->repeat_cnt > 0 && a->repeat_cnt != LV_ANIM_REPEAT_INFINITE) { + a->repeat_cnt--; + } + + /*Delete the animation if + * - no repeat left and no play back (simple one shot animation) + * - no repeat, play back is enabled and play back is ready*/ + if(a->repeat_cnt == 0 && (a->playback_duration == 0 || a->playback_now == 1)) { + + /*Delete the animation from the list. + * This way the `completed_cb` will see the animations like it's animation is already deleted*/ + lv_ll_remove(anim_ll_p, a); + /*Flag that the list has changed*/ + anim_mark_list_change(); + + /*Call the callback function at the end*/ + if(a->completed_cb != NULL) a->completed_cb(a); + if(a->deleted_cb != NULL) a->deleted_cb(a); + lv_free(a); + } + /*If the animation is not deleted then restart it*/ + else { + /*Restart the animation. If the time is over a little compensate it.*/ + int32_t over_time = 0; + if(a->act_time > a->duration) over_time = a->act_time - a->duration; + a->act_time = over_time - (int32_t)(a->repeat_delay); + /*Swap the start and end values in play back mode*/ + if(a->playback_duration != 0) { + /*If now turning back use the 'playback_pause*/ + if(a->playback_now == 0) a->act_time = -(int32_t)(a->playback_delay); + + /*Toggle the play back state*/ + a->playback_now = a->playback_now == 0 ? 1 : 0; + /*Swap the start and end values*/ + int32_t tmp = a->start_value; + a->start_value = a->end_value; + a->end_value = tmp; + /*Swap the time and playback_duration*/ + tmp = a->duration; + a->duration = a->playback_duration; + a->playback_duration = tmp; + } + } +} + +static void anim_mark_list_change(void) +{ + state.anim_list_changed = true; + if(lv_ll_get_head(anim_ll_p) == NULL) + lv_timer_pause(state.timer); + else + lv_timer_resume(state.timer); +} + +static int32_t lv_anim_path_cubic_bezier(const lv_anim_t * a, int32_t x1, int32_t y1, int32_t x2, int32_t y2) +{ + /*Calculate the current step*/ + uint32_t t = lv_map(a->act_time, 0, a->duration, 0, LV_BEZIER_VAL_MAX); + int32_t step = lv_cubic_bezier(t, x1, y1, x2, y2); + + int32_t new_value; + new_value = step * (a->end_value - a->start_value); + new_value = new_value >> LV_BEZIER_VAL_SHIFT; + new_value += a->start_value; + + return new_value; +} + +static uint32_t convert_speed_to_time(uint32_t speed_or_time, int32_t start, int32_t end) +{ + /*It was a simple time*/ + if((speed_or_time & 0x80000000) == 0) return speed_or_time; + + uint32_t d = LV_ABS(start - end); + uint32_t speed = speed_or_time & 0x3FF; + uint32_t time = (d * 100) / speed; /*Speed is in 10 units per sec*/ + uint32_t max_time = (speed_or_time >> 20) & 0x3FF; + uint32_t min_time = (speed_or_time >> 10) & 0x3FF; + + return LV_CLAMP(min_time * 10, time, max_time * 10); +} + +static void resolve_time(lv_anim_t * a) +{ + a->duration = convert_speed_to_time(a->duration, a->start_value, a->end_value); + a->playback_duration = convert_speed_to_time(a->playback_duration, a->start_value, a->end_value); + a->playback_delay = convert_speed_to_time(a->playback_delay, a->start_value, a->end_value); + a->repeat_delay = convert_speed_to_time(a->repeat_delay, a->start_value, a->end_value); +} + +/** + * Remove animations which are animating the same var with the same exec_cb + * and they are already running or they have early_apply + * @param a_current the current animation, use its var and exec_cb as reference to know what to remove + * @return true: at least one animation was delete + */ +static bool remove_concurrent_anims(lv_anim_t * a_current) +{ + if(a_current->exec_cb == NULL && a_current->custom_exec_cb == NULL) return false; + + lv_anim_t * a; + bool del_any = false; + a = lv_ll_get_head(anim_ll_p); + while(a != NULL) { + bool del = false; + /*We can't test for custom_exec_cb equality because in the MicroPython binding + *a wrapper callback is used here an the real callback data is stored in the `user_data`. + *Therefore equality check would remove all animations.*/ + if(a != a_current && + (a->act_time >= 0 || a->early_apply) && + (a->var == a_current->var) && + ((a->exec_cb && a->exec_cb == a_current->exec_cb) + /*|| (a->custom_exec_cb && a->custom_exec_cb == a_current->custom_exec_cb)*/)) { + lv_ll_remove(anim_ll_p, a); + if(a->deleted_cb != NULL) a->deleted_cb(a); + lv_free(a); + /*Read by `anim_timer`. It need to know if a delete occurred in the linked list*/ + anim_mark_list_change(); + + del_any = true; + del = true; + } + + /*Always start from the head on delete, because we don't know + *how `anim_ll_p` was changes in `a->deleted_cb` */ + a = del ? lv_ll_get_head(anim_ll_p) : lv_ll_get_next(anim_ll_p, a); + } + + return del_any; +} + +static void remove_anim(void * a) +{ + lv_anim_t * anim = a; + lv_ll_remove(anim_ll_p, a); + if(anim->deleted_cb != NULL) anim->deleted_cb(anim); + lv_free(a); +} diff --git a/tasks/runtime-lvgl-repeat-cadence/observer.c b/tasks/runtime-lvgl-repeat-cadence/observer.c new file mode 100644 index 00000000..66fe9c31 --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/observer.c @@ -0,0 +1,94 @@ +/* Observation-only driver. Inputs select API calls; output contains raw results. */ +#include "port.h" +#include +#include +#include + +typedef struct { + int32_t value, endpoint, change_to; + unsigned completed, deleted; + int mutate, changed; +} actor_t; +static actor_t actors[8]; +static void apply(void * p, int32_t value) { ((actor_t *)p)->value = value; } +static void custom_apply(lv_anim_t * a, int32_t value) { + actor_t * p = lv_anim_get_user_data(a); + p->value = value; + if(p->mutate && !p->changed && value == p->endpoint) { + p->changed = 1; + a->act_time = p->change_to; + } +} +static void completed(lv_anim_t * a) { ((actor_t *)lv_anim_get_user_data(a))->completed++; } +static void deleted(lv_anim_t * a) { ((actor_t *)lv_anim_get_user_data(a))->deleted++; } +static void snapshot(unsigned id, int step, unsigned count) { + printf("N %u %d %u\n", id, step, (unsigned)lv_anim_count_running()); + for(unsigned i = 0; i < count; ++i) { + printf("A %u %d %u %ld %u %u %u\n", id, step, i, (long)actors[i].value, + actors[i].completed, actors[i].deleted, lv_anim_get(&actors[i], NULL) != NULL); + } +} +int main(void) { + char kind; + while(scanf(" %c", &kind) == 1) { + unsigned id; + if(kind == 'P') { + unsigned duration, rd, pd, pdel, count, delay; + if(scanf("%u%u%u%u%u%u%u", &id, &duration, &rd, &pd, &pdel, &count, &delay) != 7) return 3; + lv_anim_t a; + lv_anim_init(&a); + lv_anim_set_duration(&a, duration); + lv_anim_set_repeat_delay(&a, rd); + lv_anim_set_playback_duration(&a, pd); + lv_anim_set_playback_delay(&a, pdel); + lv_anim_set_repeat_count(&a, count); + lv_anim_set_delay(&a, delay); + printf("P %u %u %u %u %u\n", id, lv_anim_get_playtime(&a), lv_anim_get_time(&a), + lv_anim_get_repeat_count(&a), lv_anim_get_delay(&a)); + } else if(kind == 'R') { + unsigned mode, tick, count, steps; + if(scanf("%u%u%u%u%u", &id, &mode, &tick, &count, &steps) != 5 || count > 8) return 4; + memset(actors, 0, sizeof actors); + port_init(tick); + for(unsigned i = 0; i < count; ++i) { + unsigned duration, rd, pd, pdel, repeats, delay, early, path, cb; + int start, end, mutate, change_to; + if(scanf("%u%u%u%u%u%u%d%d%u%u%u%d%d", &duration, &rd, &pd, &pdel, + &repeats, &delay, &start, &end, &early, &path, &cb, &mutate, &change_to) != 13) return 5; + actors[i].value = INT32_MIN; + actors[i].endpoint = end; + actors[i].mutate = mutate; + actors[i].change_to = change_to; + lv_anim_t a; + lv_anim_init(&a); + lv_anim_set_var(&a, &actors[i]); + lv_anim_set_user_data(&a, &actors[i]); + if(cb) lv_anim_set_custom_exec_cb(&a, custom_apply); + else lv_anim_set_exec_cb(&a, apply); + lv_anim_set_values(&a, start, end); + lv_anim_set_duration(&a, duration); + lv_anim_set_repeat_delay(&a, rd); + lv_anim_set_playback_duration(&a, pd); + lv_anim_set_playback_delay(&a, pdel); + lv_anim_set_repeat_count(&a, repeats); + lv_anim_set_delay(&a, delay); + lv_anim_set_early_apply(&a, early != 0); + lv_anim_set_path_cb(&a, path ? lv_anim_path_step : lv_anim_path_linear); + lv_anim_set_completed_cb(&a, completed); + lv_anim_set_deleted_cb(&a, deleted); + lv_anim_start(&a); + } + snapshot(id, -1, count); + for(unsigned step = 0; step < steps; ++step) { + unsigned delta; + if(scanf("%u", &delta) != 1) return 6; + lv_tick_inc(delta); + if(mode) lv_timer_handler(); + else lv_anim_refr_now(); + snapshot(id, (int)step, count); + } + port_deinit(); + } else return 7; + } + return 0; +} diff --git a/tasks/runtime-lvgl-repeat-cadence/only_cadence/src/misc/lv_anim.c b/tasks/runtime-lvgl-repeat-cadence/only_cadence/src/misc/lv_anim.c new file mode 100644 index 00000000..74b93b12 --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/only_cadence/src/misc/lv_anim.c @@ -0,0 +1,716 @@ +/** + * @file lv_anim.c + * + */ + +/********************* + * INCLUDES + *********************/ +#include "lv_anim_private.h" + +#include "../core/lv_global.h" +#include "../tick/lv_tick.h" +#include "lv_assert.h" +#include "lv_timer.h" +#include "lv_math.h" +#include "../stdlib/lv_mem.h" +#include "../stdlib/lv_string.h" + +/********************* + * DEFINES + *********************/ +#define LV_ANIM_RESOLUTION 1024 +#define LV_ANIM_RES_SHIFT 10 +#define state LV_GLOBAL_DEFAULT()->anim_state +#define anim_ll_p &(state.anim_ll) + +/********************** + * TYPEDEFS + **********************/ + +/********************** + * STATIC PROTOTYPES + **********************/ +static void anim_timer(lv_timer_t * param); +static void anim_mark_list_change(void); +static void anim_completed_handler(lv_anim_t * a); +static int32_t lv_anim_path_cubic_bezier(const lv_anim_t * a, int32_t x1, + int32_t y1, int32_t x2, int32_t y2); +static uint32_t convert_speed_to_time(uint32_t speed, int32_t start, int32_t end); +static void resolve_time(lv_anim_t * a); +static bool remove_concurrent_anims(lv_anim_t * a_current); +static void remove_anim(void * a); + +/********************** + * STATIC VARIABLES + **********************/ + +/********************** + * MACROS + **********************/ +#if LV_USE_LOG && LV_LOG_TRACE_ANIM + #define LV_TRACE_ANIM(...) LV_LOG_TRACE(__VA_ARGS__) +#else + #define LV_TRACE_ANIM(...) +#endif + +/********************** + * GLOBAL FUNCTIONS + **********************/ + +void lv_anim_core_init(void) +{ + lv_ll_init(anim_ll_p, sizeof(lv_anim_t)); + state.timer = lv_timer_create(anim_timer, LV_DEF_REFR_PERIOD, NULL); + anim_mark_list_change(); /*Turn off the animation timer*/ + state.anim_list_changed = false; + state.anim_run_round = false; +} + +void lv_anim_core_deinit(void) +{ + lv_anim_delete_all(); +} + +void lv_anim_init(lv_anim_t * a) +{ + lv_memzero(a, sizeof(lv_anim_t)); + a->duration = 500; + a->start_value = 0; + a->end_value = 100; + a->repeat_cnt = 1; + a->path_cb = lv_anim_path_linear; + a->early_apply = 1; +} + +lv_anim_t * lv_anim_start(const lv_anim_t * a) +{ + LV_TRACE_ANIM("begin"); + + /*Add the new animation to the animation linked list*/ + lv_anim_t * new_anim = lv_ll_ins_head(anim_ll_p); + LV_ASSERT_MALLOC(new_anim); + if(new_anim == NULL) return NULL; + + /*Initialize the animation descriptor*/ + lv_memcpy(new_anim, a, sizeof(lv_anim_t)); + if(a->var == a) new_anim->var = new_anim; + new_anim->run_round = state.anim_run_round; + new_anim->last_timer_run = lv_tick_get(); + + /*Set the start value*/ + if(new_anim->early_apply) { + if(new_anim->get_value_cb) { + int32_t v_ofs = new_anim->get_value_cb(new_anim); + new_anim->start_value += v_ofs; + new_anim->end_value += v_ofs; + + } + + resolve_time(new_anim); + + /*Do not let two animations for the same 'var' with the same 'exec_cb'*/ + if(a->exec_cb || a->custom_exec_cb) remove_concurrent_anims(new_anim); + + if(new_anim->exec_cb) { + new_anim->exec_cb(new_anim->var, new_anim->start_value); + } + if(new_anim->custom_exec_cb) { + new_anim->custom_exec_cb(new_anim, new_anim->start_value); + } + } + + /*Creating an animation changed the linked list. + *It's important if it happens in a ready callback. (see `anim_timer`)*/ + anim_mark_list_change(); + + LV_TRACE_ANIM("finished"); + return new_anim; +} + +uint32_t lv_anim_get_playtime(const lv_anim_t * a) +{ + if(a->repeat_cnt == LV_ANIM_REPEAT_INFINITE) { + return LV_ANIM_PLAYTIME_INFINITE; + } + + uint32_t repeat_cnt = a->repeat_cnt; + if(repeat_cnt < 1) repeat_cnt = 1; + + uint32_t playtime = a->repeat_delay + a->duration + a->playback_delay + a->playback_duration; + playtime = playtime * a->repeat_cnt; + return playtime; +} + +bool lv_anim_delete(void * var, lv_anim_exec_xcb_t exec_cb) +{ + lv_anim_t * a; + bool del_any = false; + a = lv_ll_get_head(anim_ll_p); + while(a != NULL) { + bool del = false; + if((a->var == var || var == NULL) && (a->exec_cb == exec_cb || exec_cb == NULL)) { + remove_anim(a); + anim_mark_list_change(); /*Read by `anim_timer`. It need to know if a delete occurred in + the linked list*/ + del_any = true; + del = true; + } + + /*Always start from the head on delete, because we don't know + *how `anim_ll_p` was changes in `a->deleted_cb` */ + a = del ? lv_ll_get_head(anim_ll_p) : lv_ll_get_next(anim_ll_p, a); + } + + return del_any; +} + +void lv_anim_delete_all(void) +{ + lv_ll_clear_custom(anim_ll_p, remove_anim); + anim_mark_list_change(); +} + +lv_anim_t * lv_anim_get(void * var, lv_anim_exec_xcb_t exec_cb) +{ + lv_anim_t * a; + LV_LL_READ(anim_ll_p, a) { + if(a->var == var && (a->exec_cb == exec_cb || exec_cb == NULL)) { + return a; + } + } + + return NULL; +} + +lv_timer_t * lv_anim_get_timer(void) +{ + return state.timer; +} + +uint16_t lv_anim_count_running(void) +{ + uint16_t cnt = 0; + lv_anim_t * a; + LV_LL_READ(anim_ll_p, a) cnt++; + + return cnt; +} + +uint32_t lv_anim_speed_clamped(uint32_t speed, uint32_t min_time, uint32_t max_time) +{ + + if(speed > 10000) { + LV_LOG_WARN("speed is truncated to 10000 (was %"LV_PRIu32")", speed); + speed = 10230; + } + if(min_time > 10000) { + LV_LOG_WARN("min_time is truncated to 10000 (was %"LV_PRIu32")", min_time); + min_time = 10230; + } + if(max_time > 10000) { + LV_LOG_WARN("max_time is truncated to 10000 (was %"LV_PRIu32")", max_time); + max_time = 10230; + } + + /*Lower the resolution to fit the 0.1023 range*/ + speed = (speed + 5) / 10; + min_time = (min_time + 5) / 10; + max_time = (max_time + 5) / 10; + + return 0x80000000 + (max_time << 20) + (min_time << 10) + speed; + +} + +uint32_t lv_anim_speed(uint32_t speed) +{ + return lv_anim_speed_clamped(speed, 0, 10000); +} + +uint32_t lv_anim_speed_to_time(uint32_t speed, int32_t start, int32_t end) +{ + uint32_t d = LV_ABS(start - end); + uint32_t time = (d * 1000) / speed; + + time = time == 0 ? 1 : time; + + return time; +} + +void lv_anim_refr_now(void) +{ + anim_timer(NULL); +} + +int32_t lv_anim_path_linear(const lv_anim_t * a) +{ + /*Calculate the current step*/ + int32_t step = lv_map(a->act_time, 0, a->duration, 0, LV_ANIM_RESOLUTION); + + /*Get the new value which will be proportional to `step` + *and the `start` and `end` values*/ + int32_t new_value; + new_value = step * (a->end_value - a->start_value); + new_value = new_value >> LV_ANIM_RES_SHIFT; + new_value += a->start_value; + + return new_value; +} + +int32_t lv_anim_path_ease_in(const lv_anim_t * a) +{ + return lv_anim_path_cubic_bezier(a, LV_BEZIER_VAL_FLOAT(0.42), LV_BEZIER_VAL_FLOAT(0), + LV_BEZIER_VAL_FLOAT(1), LV_BEZIER_VAL_FLOAT(1)); +} + +int32_t lv_anim_path_ease_out(const lv_anim_t * a) +{ + return lv_anim_path_cubic_bezier(a, LV_BEZIER_VAL_FLOAT(0), LV_BEZIER_VAL_FLOAT(0), + LV_BEZIER_VAL_FLOAT(0.58), LV_BEZIER_VAL_FLOAT(1)); +} + +int32_t lv_anim_path_ease_in_out(const lv_anim_t * a) +{ + return lv_anim_path_cubic_bezier(a, LV_BEZIER_VAL_FLOAT(0.42), LV_BEZIER_VAL_FLOAT(0), + LV_BEZIER_VAL_FLOAT(0.58), LV_BEZIER_VAL_FLOAT(1)); +} + +int32_t lv_anim_path_overshoot(const lv_anim_t * a) +{ + return lv_anim_path_cubic_bezier(a, 341, 0, 683, 1300); +} + +int32_t lv_anim_path_bounce(const lv_anim_t * a) +{ + /*Calculate the current step*/ + int32_t t = lv_map(a->act_time, 0, a->duration, 0, LV_BEZIER_VAL_MAX); + int32_t diff = (a->end_value - a->start_value); + + /*3 bounces has 5 parts: 3 down and 2 up. One part is t / 5 long*/ + + if(t < 408) { + /*Go down*/ + t = (t * 2500) >> LV_BEZIER_VAL_SHIFT; /*[0..1024] range*/ + t = LV_BEZIER_VAL_MAX - t; + } + else if(t >= 408 && t < 614) { + /*First bounce back*/ + t -= 408; + t = t * 5; /*to [0..1024] range*/ + diff = diff / 20; + } + else if(t >= 614 && t < 819) { + /*Fall back*/ + t -= 614; + t = t * 5; /*to [0..1024] range*/ + t = LV_BEZIER_VAL_MAX - t; + diff = diff / 20; + } + else if(t >= 819 && t < 921) { + /*Second bounce back*/ + t -= 819; + t = t * 10; /*to [0..1024] range*/ + diff = diff / 40; + } + else if(t >= 921 && t <= LV_BEZIER_VAL_MAX) { + /*Fall back*/ + t -= 921; + t = t * 10; /*to [0..1024] range*/ + t = LV_BEZIER_VAL_MAX - t; + diff = diff / 40; + } + + if(t > LV_BEZIER_VAL_MAX) t = LV_BEZIER_VAL_MAX; + if(t < 0) t = 0; + int32_t step = lv_bezier3(t, 0, 500, 800, LV_BEZIER_VAL_MAX); + + int32_t new_value; + new_value = step * diff; + new_value = new_value >> LV_BEZIER_VAL_SHIFT; + new_value = a->end_value - new_value; + + return new_value; +} + +int32_t lv_anim_path_step(const lv_anim_t * a) +{ + if(a->act_time >= a->duration) + return a->end_value; + else + return a->start_value; +} + +int32_t lv_anim_path_custom_bezier3(const lv_anim_t * a) +{ + const lv_anim_bezier3_para_t * para = &a->parameter.bezier3; + return lv_anim_path_cubic_bezier(a, para->x1, para->y1, para->x2, para->y2); +} + +void lv_anim_set_var(lv_anim_t * a, void * var) +{ + a->var = var; +} + +void lv_anim_set_exec_cb(lv_anim_t * a, lv_anim_exec_xcb_t exec_cb) +{ + a->exec_cb = exec_cb; +} + +void lv_anim_set_duration(lv_anim_t * a, uint32_t duration) +{ + a->duration = duration; +} + +void lv_anim_set_time(lv_anim_t * a, uint32_t duration) +{ + lv_anim_set_duration(a, duration); +} + +void lv_anim_set_delay(lv_anim_t * a, uint32_t delay) +{ + a->act_time = -(int32_t)(delay); +} + +void lv_anim_set_values(lv_anim_t * a, int32_t start, int32_t end) +{ + a->start_value = start; + a->current_value = INT32_MIN; + a->end_value = end; +} + +void lv_anim_set_custom_exec_cb(lv_anim_t * a, lv_anim_custom_exec_cb_t exec_cb) +{ + a->custom_exec_cb = exec_cb; +} + +void lv_anim_set_path_cb(lv_anim_t * a, lv_anim_path_cb_t path_cb) +{ + a->path_cb = path_cb; +} + +void lv_anim_set_start_cb(lv_anim_t * a, lv_anim_start_cb_t start_cb) +{ + a->start_cb = start_cb; +} + +void lv_anim_set_get_value_cb(lv_anim_t * a, lv_anim_get_value_cb_t get_value_cb) +{ + a->get_value_cb = get_value_cb; +} + +void lv_anim_set_completed_cb(lv_anim_t * a, lv_anim_completed_cb_t completed_cb) +{ + a->completed_cb = completed_cb; +} + +void lv_anim_set_deleted_cb(lv_anim_t * a, lv_anim_deleted_cb_t deleted_cb) +{ + a->deleted_cb = deleted_cb; +} + +void lv_anim_set_playback_duration(lv_anim_t * a, uint32_t duration) +{ + a->playback_duration = duration; +} + +void lv_anim_set_playback_time(lv_anim_t * a, uint32_t duration) +{ + lv_anim_set_playback_duration(a, duration); +} + +void lv_anim_set_playback_delay(lv_anim_t * a, uint32_t delay) +{ + a->playback_delay = delay; +} + +void lv_anim_set_repeat_count(lv_anim_t * a, uint32_t cnt) +{ + a->repeat_cnt = cnt; +} + +void lv_anim_set_repeat_delay(lv_anim_t * a, uint32_t delay) +{ + a->repeat_delay = delay; +} + +void lv_anim_set_early_apply(lv_anim_t * a, bool en) +{ + a->early_apply = en; +} + +void lv_anim_set_user_data(lv_anim_t * a, void * user_data) +{ + a->user_data = user_data; +} + +void lv_anim_set_bezier3_param(lv_anim_t * a, int16_t x1, int16_t y1, int16_t x2, int16_t y2) +{ + lv_anim_bezier3_para_t * para = &a->parameter.bezier3; + + para->x1 = x1; + para->x2 = x2; + para->y1 = y1; + para->y2 = y2; +} + +uint32_t lv_anim_get_delay(const lv_anim_t * a) +{ + return -a->act_time; +} + +uint32_t lv_anim_get_time(const lv_anim_t * a) +{ + return a->duration; +} + +uint32_t lv_anim_get_repeat_count(const lv_anim_t * a) +{ + return a->repeat_cnt; +} + +void * lv_anim_get_user_data(const lv_anim_t * a) +{ + return a->user_data; +} + +bool lv_anim_custom_delete(lv_anim_t * a, lv_anim_custom_exec_cb_t exec_cb) +{ + return lv_anim_delete(a ? a->var : NULL, (lv_anim_exec_xcb_t)exec_cb); +} + +lv_anim_t * lv_anim_custom_get(lv_anim_t * a, lv_anim_custom_exec_cb_t exec_cb) +{ + return lv_anim_get(a ? a->var : NULL, (lv_anim_exec_xcb_t)exec_cb); +} + +/********************** + * STATIC FUNCTIONS + **********************/ +/** + * Periodically handle the animations. + * @param param unused + */ +static void anim_timer(lv_timer_t * param) +{ + LV_UNUSED(param); + + /*Flip the run round*/ + state.anim_run_round = state.anim_run_round ? false : true; + + lv_anim_t * a = lv_ll_get_head(anim_ll_p); + + while(a != NULL) { + uint32_t elaps = lv_tick_elaps(a->last_timer_run); + a->act_time += elaps; + + a->last_timer_run = lv_tick_get(); + + /*It can be set by `lv_anim_delete()` typically in `end_cb`. If set then an animation delete + * happened in `anim_completed_handler` which could make this linked list reading corrupt + * because the list is changed meanwhile + */ + state.anim_list_changed = false; + + if(a->run_round != state.anim_run_round) { + a->run_round = state.anim_run_round; /*The list readying might be reset so need to know which anim has run already*/ + + /*The animation will run now for the first time. Call `start_cb`*/ + if(!a->start_cb_called && a->act_time >= 0) { + + if(a->early_apply == 0 && a->get_value_cb) { + int32_t v_ofs = a->get_value_cb(a); + a->start_value += v_ofs; + a->end_value += v_ofs; + } + + resolve_time(a); + + if(a->start_cb) a->start_cb(a); + a->start_cb_called = 1; + + /*Do not let two animations for the same 'var' with the same 'exec_cb'*/ + remove_concurrent_anims(a); + } + + if(a->act_time >= 0) { + int32_t act_time_original = a->act_time; /*The unclipped version is used later to correctly repeat the animation*/ + if(a->act_time > a->duration) a->act_time = a->duration; + + int32_t act_time_before_exec = a->act_time; + int32_t new_value; + new_value = a->path_cb(a); + + if(new_value != a->current_value) { + a->current_value = new_value; + /*Apply the calculated value*/ + if(a->exec_cb) a->exec_cb(a->var, new_value); + if(!state.anim_list_changed && a->custom_exec_cb) a->custom_exec_cb(a, new_value); + } + + /*Restore the original time to see is there is over time. + *Restore only if it wasn't changed in the `exec_cb` for some special reasons.*/ + if(a->act_time == act_time_before_exec) a->act_time = act_time_original; + + /*If the time is elapsed the animation is ready*/ + if(!state.anim_list_changed && a->act_time >= a->duration) { + anim_completed_handler(a); + } + } + } + + /*If the linked list changed due to anim. delete then it's not safe to continue + *the reading of the list from here -> start from the head*/ + if(state.anim_list_changed) + a = lv_ll_get_head(anim_ll_p); + else + a = lv_ll_get_next(anim_ll_p, a); + } + +} + +/** + * Called when an animation is completed to do the necessary things + * e.g. repeat, play back, delete etc. + * @param a pointer to an animation descriptor + */ +static void anim_completed_handler(lv_anim_t * a) +{ + /*In the end of a forward anim decrement repeat cnt.*/ + if(a->playback_now == 0 && a->repeat_cnt > 0 && a->repeat_cnt != LV_ANIM_REPEAT_INFINITE) { + a->repeat_cnt--; + } + + /*Delete the animation if + * - no repeat left and no play back (simple one shot animation) + * - no repeat, play back is enabled and play back is ready*/ + if(a->repeat_cnt == 0 && (a->playback_duration == 0 || a->playback_now == 1)) { + + /*Delete the animation from the list. + * This way the `completed_cb` will see the animations like it's animation is already deleted*/ + lv_ll_remove(anim_ll_p, a); + /*Flag that the list has changed*/ + anim_mark_list_change(); + + /*Call the callback function at the end*/ + if(a->completed_cb != NULL) a->completed_cb(a); + if(a->deleted_cb != NULL) a->deleted_cb(a); + lv_free(a); + } + /*If the animation is not deleted then restart it*/ + else { + /*Restart the animation. If the time is over a little compensate it.*/ + int32_t over_time = 0; + if(a->act_time > a->duration) over_time = a->act_time - a->duration; + a->act_time = over_time - (int32_t)(a->repeat_delay); + /*Swap the start and end values in play back mode*/ + if(a->playback_duration != 0) { + /*If now turning back use the 'playback_pause*/ + if(a->playback_now == 0) a->act_time = -(int32_t)(a->playback_delay); + + /*Toggle the play back state*/ + a->playback_now = a->playback_now == 0 ? 1 : 0; + /*Swap the start and end values*/ + int32_t tmp = a->start_value; + a->start_value = a->end_value; + a->end_value = tmp; + /*Swap the time and playback_duration*/ + tmp = a->duration; + a->duration = a->playback_duration; + a->playback_duration = tmp; + } + } +} + +static void anim_mark_list_change(void) +{ + state.anim_list_changed = true; + if(lv_ll_get_head(anim_ll_p) == NULL) + lv_timer_pause(state.timer); + else + lv_timer_resume(state.timer); +} + +static int32_t lv_anim_path_cubic_bezier(const lv_anim_t * a, int32_t x1, int32_t y1, int32_t x2, int32_t y2) +{ + /*Calculate the current step*/ + uint32_t t = lv_map(a->act_time, 0, a->duration, 0, LV_BEZIER_VAL_MAX); + int32_t step = lv_cubic_bezier(t, x1, y1, x2, y2); + + int32_t new_value; + new_value = step * (a->end_value - a->start_value); + new_value = new_value >> LV_BEZIER_VAL_SHIFT; + new_value += a->start_value; + + return new_value; +} + +static uint32_t convert_speed_to_time(uint32_t speed_or_time, int32_t start, int32_t end) +{ + /*It was a simple time*/ + if((speed_or_time & 0x80000000) == 0) return speed_or_time; + + uint32_t d = LV_ABS(start - end); + uint32_t speed = speed_or_time & 0x3FF; + uint32_t time = (d * 100) / speed; /*Speed is in 10 units per sec*/ + uint32_t max_time = (speed_or_time >> 20) & 0x3FF; + uint32_t min_time = (speed_or_time >> 10) & 0x3FF; + + return LV_CLAMP(min_time * 10, time, max_time * 10); +} + +static void resolve_time(lv_anim_t * a) +{ + a->duration = convert_speed_to_time(a->duration, a->start_value, a->end_value); + a->playback_duration = convert_speed_to_time(a->playback_duration, a->start_value, a->end_value); + a->playback_delay = convert_speed_to_time(a->playback_delay, a->start_value, a->end_value); + a->repeat_delay = convert_speed_to_time(a->repeat_delay, a->start_value, a->end_value); +} + +/** + * Remove animations which are animating the same var with the same exec_cb + * and they are already running or they have early_apply + * @param a_current the current animation, use its var and exec_cb as reference to know what to remove + * @return true: at least one animation was delete + */ +static bool remove_concurrent_anims(lv_anim_t * a_current) +{ + if(a_current->exec_cb == NULL && a_current->custom_exec_cb == NULL) return false; + + lv_anim_t * a; + bool del_any = false; + a = lv_ll_get_head(anim_ll_p); + while(a != NULL) { + bool del = false; + /*We can't test for custom_exec_cb equality because in the MicroPython binding + *a wrapper callback is used here an the real callback data is stored in the `user_data`. + *Therefore equality check would remove all animations.*/ + if(a != a_current && + (a->act_time >= 0 || a->early_apply) && + (a->var == a_current->var) && + ((a->exec_cb && a->exec_cb == a_current->exec_cb) + /*|| (a->custom_exec_cb && a->custom_exec_cb == a_current->custom_exec_cb)*/)) { + lv_ll_remove(anim_ll_p, a); + if(a->deleted_cb != NULL) a->deleted_cb(a); + lv_free(a); + /*Read by `anim_timer`. It need to know if a delete occurred in the linked list*/ + anim_mark_list_change(); + + del_any = true; + del = true; + } + + /*Always start from the head on delete, because we don't know + *how `anim_ll_p` was changes in `a->deleted_cb` */ + a = del ? lv_ll_get_head(anim_ll_p) : lv_ll_get_next(anim_ll_p, a); + } + + return del_any; +} + +static void remove_anim(void * a) +{ + lv_anim_t * anim = a; + lv_ll_remove(anim_ll_p, a); + if(anim->deleted_cb != NULL) anim->deleted_cb(anim); + lv_free(a); +} diff --git a/tasks/runtime-lvgl-repeat-cadence/only_playtime/src/misc/lv_anim.c b/tasks/runtime-lvgl-repeat-cadence/only_playtime/src/misc/lv_anim.c new file mode 100644 index 00000000..8fc98676 --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/only_playtime/src/misc/lv_anim.c @@ -0,0 +1,707 @@ +/** + * @file lv_anim.c + * + */ + +/********************* + * INCLUDES + *********************/ +#include "lv_anim_private.h" + +#include "../core/lv_global.h" +#include "../tick/lv_tick.h" +#include "lv_assert.h" +#include "lv_timer.h" +#include "lv_math.h" +#include "../stdlib/lv_mem.h" +#include "../stdlib/lv_string.h" + +/********************* + * DEFINES + *********************/ +#define LV_ANIM_RESOLUTION 1024 +#define LV_ANIM_RES_SHIFT 10 +#define state LV_GLOBAL_DEFAULT()->anim_state +#define anim_ll_p &(state.anim_ll) + +/********************** + * TYPEDEFS + **********************/ + +/********************** + * STATIC PROTOTYPES + **********************/ +static void anim_timer(lv_timer_t * param); +static void anim_mark_list_change(void); +static void anim_completed_handler(lv_anim_t * a); +static int32_t lv_anim_path_cubic_bezier(const lv_anim_t * a, int32_t x1, + int32_t y1, int32_t x2, int32_t y2); +static uint32_t convert_speed_to_time(uint32_t speed, int32_t start, int32_t end); +static void resolve_time(lv_anim_t * a); +static bool remove_concurrent_anims(lv_anim_t * a_current); +static void remove_anim(void * a); + +/********************** + * STATIC VARIABLES + **********************/ + +/********************** + * MACROS + **********************/ +#if LV_USE_LOG && LV_LOG_TRACE_ANIM + #define LV_TRACE_ANIM(...) LV_LOG_TRACE(__VA_ARGS__) +#else + #define LV_TRACE_ANIM(...) +#endif + +/********************** + * GLOBAL FUNCTIONS + **********************/ + +void lv_anim_core_init(void) +{ + lv_ll_init(anim_ll_p, sizeof(lv_anim_t)); + state.timer = lv_timer_create(anim_timer, LV_DEF_REFR_PERIOD, NULL); + anim_mark_list_change(); /*Turn off the animation timer*/ + state.anim_list_changed = false; + state.anim_run_round = false; +} + +void lv_anim_core_deinit(void) +{ + lv_anim_delete_all(); +} + +void lv_anim_init(lv_anim_t * a) +{ + lv_memzero(a, sizeof(lv_anim_t)); + a->duration = 500; + a->start_value = 0; + a->end_value = 100; + a->repeat_cnt = 1; + a->path_cb = lv_anim_path_linear; + a->early_apply = 1; +} + +lv_anim_t * lv_anim_start(const lv_anim_t * a) +{ + LV_TRACE_ANIM("begin"); + + /*Add the new animation to the animation linked list*/ + lv_anim_t * new_anim = lv_ll_ins_head(anim_ll_p); + LV_ASSERT_MALLOC(new_anim); + if(new_anim == NULL) return NULL; + + /*Initialize the animation descriptor*/ + lv_memcpy(new_anim, a, sizeof(lv_anim_t)); + if(a->var == a) new_anim->var = new_anim; + new_anim->run_round = state.anim_run_round; + new_anim->last_timer_run = lv_tick_get(); + + /*Set the start value*/ + if(new_anim->early_apply) { + if(new_anim->get_value_cb) { + int32_t v_ofs = new_anim->get_value_cb(new_anim); + new_anim->start_value += v_ofs; + new_anim->end_value += v_ofs; + + } + + resolve_time(new_anim); + + /*Do not let two animations for the same 'var' with the same 'exec_cb'*/ + if(a->exec_cb || a->custom_exec_cb) remove_concurrent_anims(new_anim); + + if(new_anim->exec_cb) { + new_anim->exec_cb(new_anim->var, new_anim->start_value); + } + if(new_anim->custom_exec_cb) { + new_anim->custom_exec_cb(new_anim, new_anim->start_value); + } + } + + /*Creating an animation changed the linked list. + *It's important if it happens in a ready callback. (see `anim_timer`)*/ + anim_mark_list_change(); + + LV_TRACE_ANIM("finished"); + return new_anim; +} + +uint32_t lv_anim_get_playtime(const lv_anim_t * a) +{ + if(a->repeat_cnt == LV_ANIM_REPEAT_INFINITE) { + return LV_ANIM_PLAYTIME_INFINITE; + } + + uint32_t repeat_cnt = a->repeat_cnt; + if(repeat_cnt < 1) repeat_cnt = 1; + + uint32_t playtime = a->repeat_delay + a->duration + a->playback_delay + a->playback_duration; + playtime = playtime * repeat_cnt; + return playtime; +} + +bool lv_anim_delete(void * var, lv_anim_exec_xcb_t exec_cb) +{ + lv_anim_t * a; + bool del_any = false; + a = lv_ll_get_head(anim_ll_p); + while(a != NULL) { + bool del = false; + if((a->var == var || var == NULL) && (a->exec_cb == exec_cb || exec_cb == NULL)) { + remove_anim(a); + anim_mark_list_change(); /*Read by `anim_timer`. It need to know if a delete occurred in + the linked list*/ + del_any = true; + del = true; + } + + /*Always start from the head on delete, because we don't know + *how `anim_ll_p` was changes in `a->deleted_cb` */ + a = del ? lv_ll_get_head(anim_ll_p) : lv_ll_get_next(anim_ll_p, a); + } + + return del_any; +} + +void lv_anim_delete_all(void) +{ + lv_ll_clear_custom(anim_ll_p, remove_anim); + anim_mark_list_change(); +} + +lv_anim_t * lv_anim_get(void * var, lv_anim_exec_xcb_t exec_cb) +{ + lv_anim_t * a; + LV_LL_READ(anim_ll_p, a) { + if(a->var == var && (a->exec_cb == exec_cb || exec_cb == NULL)) { + return a; + } + } + + return NULL; +} + +lv_timer_t * lv_anim_get_timer(void) +{ + return state.timer; +} + +uint16_t lv_anim_count_running(void) +{ + uint16_t cnt = 0; + lv_anim_t * a; + LV_LL_READ(anim_ll_p, a) cnt++; + + return cnt; +} + +uint32_t lv_anim_speed_clamped(uint32_t speed, uint32_t min_time, uint32_t max_time) +{ + + if(speed > 10000) { + LV_LOG_WARN("speed is truncated to 10000 (was %"LV_PRIu32")", speed); + speed = 10230; + } + if(min_time > 10000) { + LV_LOG_WARN("min_time is truncated to 10000 (was %"LV_PRIu32")", min_time); + min_time = 10230; + } + if(max_time > 10000) { + LV_LOG_WARN("max_time is truncated to 10000 (was %"LV_PRIu32")", max_time); + max_time = 10230; + } + + /*Lower the resolution to fit the 0.1023 range*/ + speed = (speed + 5) / 10; + min_time = (min_time + 5) / 10; + max_time = (max_time + 5) / 10; + + return 0x80000000 + (max_time << 20) + (min_time << 10) + speed; + +} + +uint32_t lv_anim_speed(uint32_t speed) +{ + return lv_anim_speed_clamped(speed, 0, 10000); +} + +uint32_t lv_anim_speed_to_time(uint32_t speed, int32_t start, int32_t end) +{ + uint32_t d = LV_ABS(start - end); + uint32_t time = (d * 1000) / speed; + + time = time == 0 ? 1 : time; + + return time; +} + +void lv_anim_refr_now(void) +{ + anim_timer(NULL); +} + +int32_t lv_anim_path_linear(const lv_anim_t * a) +{ + /*Calculate the current step*/ + int32_t step = lv_map(a->act_time, 0, a->duration, 0, LV_ANIM_RESOLUTION); + + /*Get the new value which will be proportional to `step` + *and the `start` and `end` values*/ + int32_t new_value; + new_value = step * (a->end_value - a->start_value); + new_value = new_value >> LV_ANIM_RES_SHIFT; + new_value += a->start_value; + + return new_value; +} + +int32_t lv_anim_path_ease_in(const lv_anim_t * a) +{ + return lv_anim_path_cubic_bezier(a, LV_BEZIER_VAL_FLOAT(0.42), LV_BEZIER_VAL_FLOAT(0), + LV_BEZIER_VAL_FLOAT(1), LV_BEZIER_VAL_FLOAT(1)); +} + +int32_t lv_anim_path_ease_out(const lv_anim_t * a) +{ + return lv_anim_path_cubic_bezier(a, LV_BEZIER_VAL_FLOAT(0), LV_BEZIER_VAL_FLOAT(0), + LV_BEZIER_VAL_FLOAT(0.58), LV_BEZIER_VAL_FLOAT(1)); +} + +int32_t lv_anim_path_ease_in_out(const lv_anim_t * a) +{ + return lv_anim_path_cubic_bezier(a, LV_BEZIER_VAL_FLOAT(0.42), LV_BEZIER_VAL_FLOAT(0), + LV_BEZIER_VAL_FLOAT(0.58), LV_BEZIER_VAL_FLOAT(1)); +} + +int32_t lv_anim_path_overshoot(const lv_anim_t * a) +{ + return lv_anim_path_cubic_bezier(a, 341, 0, 683, 1300); +} + +int32_t lv_anim_path_bounce(const lv_anim_t * a) +{ + /*Calculate the current step*/ + int32_t t = lv_map(a->act_time, 0, a->duration, 0, LV_BEZIER_VAL_MAX); + int32_t diff = (a->end_value - a->start_value); + + /*3 bounces has 5 parts: 3 down and 2 up. One part is t / 5 long*/ + + if(t < 408) { + /*Go down*/ + t = (t * 2500) >> LV_BEZIER_VAL_SHIFT; /*[0..1024] range*/ + t = LV_BEZIER_VAL_MAX - t; + } + else if(t >= 408 && t < 614) { + /*First bounce back*/ + t -= 408; + t = t * 5; /*to [0..1024] range*/ + diff = diff / 20; + } + else if(t >= 614 && t < 819) { + /*Fall back*/ + t -= 614; + t = t * 5; /*to [0..1024] range*/ + t = LV_BEZIER_VAL_MAX - t; + diff = diff / 20; + } + else if(t >= 819 && t < 921) { + /*Second bounce back*/ + t -= 819; + t = t * 10; /*to [0..1024] range*/ + diff = diff / 40; + } + else if(t >= 921 && t <= LV_BEZIER_VAL_MAX) { + /*Fall back*/ + t -= 921; + t = t * 10; /*to [0..1024] range*/ + t = LV_BEZIER_VAL_MAX - t; + diff = diff / 40; + } + + if(t > LV_BEZIER_VAL_MAX) t = LV_BEZIER_VAL_MAX; + if(t < 0) t = 0; + int32_t step = lv_bezier3(t, 0, 500, 800, LV_BEZIER_VAL_MAX); + + int32_t new_value; + new_value = step * diff; + new_value = new_value >> LV_BEZIER_VAL_SHIFT; + new_value = a->end_value - new_value; + + return new_value; +} + +int32_t lv_anim_path_step(const lv_anim_t * a) +{ + if(a->act_time >= a->duration) + return a->end_value; + else + return a->start_value; +} + +int32_t lv_anim_path_custom_bezier3(const lv_anim_t * a) +{ + const lv_anim_bezier3_para_t * para = &a->parameter.bezier3; + return lv_anim_path_cubic_bezier(a, para->x1, para->y1, para->x2, para->y2); +} + +void lv_anim_set_var(lv_anim_t * a, void * var) +{ + a->var = var; +} + +void lv_anim_set_exec_cb(lv_anim_t * a, lv_anim_exec_xcb_t exec_cb) +{ + a->exec_cb = exec_cb; +} + +void lv_anim_set_duration(lv_anim_t * a, uint32_t duration) +{ + a->duration = duration; +} + +void lv_anim_set_time(lv_anim_t * a, uint32_t duration) +{ + lv_anim_set_duration(a, duration); +} + +void lv_anim_set_delay(lv_anim_t * a, uint32_t delay) +{ + a->act_time = -(int32_t)(delay); +} + +void lv_anim_set_values(lv_anim_t * a, int32_t start, int32_t end) +{ + a->start_value = start; + a->current_value = INT32_MIN; + a->end_value = end; +} + +void lv_anim_set_custom_exec_cb(lv_anim_t * a, lv_anim_custom_exec_cb_t exec_cb) +{ + a->custom_exec_cb = exec_cb; +} + +void lv_anim_set_path_cb(lv_anim_t * a, lv_anim_path_cb_t path_cb) +{ + a->path_cb = path_cb; +} + +void lv_anim_set_start_cb(lv_anim_t * a, lv_anim_start_cb_t start_cb) +{ + a->start_cb = start_cb; +} + +void lv_anim_set_get_value_cb(lv_anim_t * a, lv_anim_get_value_cb_t get_value_cb) +{ + a->get_value_cb = get_value_cb; +} + +void lv_anim_set_completed_cb(lv_anim_t * a, lv_anim_completed_cb_t completed_cb) +{ + a->completed_cb = completed_cb; +} + +void lv_anim_set_deleted_cb(lv_anim_t * a, lv_anim_deleted_cb_t deleted_cb) +{ + a->deleted_cb = deleted_cb; +} + +void lv_anim_set_playback_duration(lv_anim_t * a, uint32_t duration) +{ + a->playback_duration = duration; +} + +void lv_anim_set_playback_time(lv_anim_t * a, uint32_t duration) +{ + lv_anim_set_playback_duration(a, duration); +} + +void lv_anim_set_playback_delay(lv_anim_t * a, uint32_t delay) +{ + a->playback_delay = delay; +} + +void lv_anim_set_repeat_count(lv_anim_t * a, uint32_t cnt) +{ + a->repeat_cnt = cnt; +} + +void lv_anim_set_repeat_delay(lv_anim_t * a, uint32_t delay) +{ + a->repeat_delay = delay; +} + +void lv_anim_set_early_apply(lv_anim_t * a, bool en) +{ + a->early_apply = en; +} + +void lv_anim_set_user_data(lv_anim_t * a, void * user_data) +{ + a->user_data = user_data; +} + +void lv_anim_set_bezier3_param(lv_anim_t * a, int16_t x1, int16_t y1, int16_t x2, int16_t y2) +{ + lv_anim_bezier3_para_t * para = &a->parameter.bezier3; + + para->x1 = x1; + para->x2 = x2; + para->y1 = y1; + para->y2 = y2; +} + +uint32_t lv_anim_get_delay(const lv_anim_t * a) +{ + return -a->act_time; +} + +uint32_t lv_anim_get_time(const lv_anim_t * a) +{ + return a->duration; +} + +uint32_t lv_anim_get_repeat_count(const lv_anim_t * a) +{ + return a->repeat_cnt; +} + +void * lv_anim_get_user_data(const lv_anim_t * a) +{ + return a->user_data; +} + +bool lv_anim_custom_delete(lv_anim_t * a, lv_anim_custom_exec_cb_t exec_cb) +{ + return lv_anim_delete(a ? a->var : NULL, (lv_anim_exec_xcb_t)exec_cb); +} + +lv_anim_t * lv_anim_custom_get(lv_anim_t * a, lv_anim_custom_exec_cb_t exec_cb) +{ + return lv_anim_get(a ? a->var : NULL, (lv_anim_exec_xcb_t)exec_cb); +} + +/********************** + * STATIC FUNCTIONS + **********************/ +/** + * Periodically handle the animations. + * @param param unused + */ +static void anim_timer(lv_timer_t * param) +{ + LV_UNUSED(param); + + /*Flip the run round*/ + state.anim_run_round = state.anim_run_round ? false : true; + + lv_anim_t * a = lv_ll_get_head(anim_ll_p); + + while(a != NULL) { + uint32_t elaps = lv_tick_elaps(a->last_timer_run); + a->act_time += elaps; + + a->last_timer_run = lv_tick_get(); + + /*It can be set by `lv_anim_delete()` typically in `end_cb`. If set then an animation delete + * happened in `anim_completed_handler` which could make this linked list reading corrupt + * because the list is changed meanwhile + */ + state.anim_list_changed = false; + + if(a->run_round != state.anim_run_round) { + a->run_round = state.anim_run_round; /*The list readying might be reset so need to know which anim has run already*/ + + /*The animation will run now for the first time. Call `start_cb`*/ + if(!a->start_cb_called && a->act_time >= 0) { + + if(a->early_apply == 0 && a->get_value_cb) { + int32_t v_ofs = a->get_value_cb(a); + a->start_value += v_ofs; + a->end_value += v_ofs; + } + + resolve_time(a); + + if(a->start_cb) a->start_cb(a); + a->start_cb_called = 1; + + /*Do not let two animations for the same 'var' with the same 'exec_cb'*/ + remove_concurrent_anims(a); + } + + if(a->act_time >= 0) { + if(a->act_time > a->duration) a->act_time = a->duration; + + int32_t new_value; + new_value = a->path_cb(a); + + if(new_value != a->current_value) { + a->current_value = new_value; + /*Apply the calculated value*/ + if(a->exec_cb) a->exec_cb(a->var, new_value); + if(!state.anim_list_changed && a->custom_exec_cb) a->custom_exec_cb(a, new_value); + } + + /*If the time is elapsed the animation is ready*/ + if(!state.anim_list_changed && a->act_time >= a->duration) { + anim_completed_handler(a); + } + } + } + + /*If the linked list changed due to anim. delete then it's not safe to continue + *the reading of the list from here -> start from the head*/ + if(state.anim_list_changed) + a = lv_ll_get_head(anim_ll_p); + else + a = lv_ll_get_next(anim_ll_p, a); + } + +} + +/** + * Called when an animation is completed to do the necessary things + * e.g. repeat, play back, delete etc. + * @param a pointer to an animation descriptor + */ +static void anim_completed_handler(lv_anim_t * a) +{ + /*In the end of a forward anim decrement repeat cnt.*/ + if(a->playback_now == 0 && a->repeat_cnt > 0 && a->repeat_cnt != LV_ANIM_REPEAT_INFINITE) { + a->repeat_cnt--; + } + + /*Delete the animation if + * - no repeat left and no play back (simple one shot animation) + * - no repeat, play back is enabled and play back is ready*/ + if(a->repeat_cnt == 0 && (a->playback_duration == 0 || a->playback_now == 1)) { + + /*Delete the animation from the list. + * This way the `completed_cb` will see the animations like it's animation is already deleted*/ + lv_ll_remove(anim_ll_p, a); + /*Flag that the list has changed*/ + anim_mark_list_change(); + + /*Call the callback function at the end*/ + if(a->completed_cb != NULL) a->completed_cb(a); + if(a->deleted_cb != NULL) a->deleted_cb(a); + lv_free(a); + } + /*If the animation is not deleted then restart it*/ + else { + a->act_time = -(int32_t)(a->repeat_delay); /*Restart the animation*/ + /*Swap the start and end values in play back mode*/ + if(a->playback_duration != 0) { + /*If now turning back use the 'playback_pause*/ + if(a->playback_now == 0) a->act_time = -(int32_t)(a->playback_delay); + + /*Toggle the play back state*/ + a->playback_now = a->playback_now == 0 ? 1 : 0; + /*Swap the start and end values*/ + int32_t tmp = a->start_value; + a->start_value = a->end_value; + a->end_value = tmp; + /*Swap the time and playback_duration*/ + tmp = a->duration; + a->duration = a->playback_duration; + a->playback_duration = tmp; + } + } +} + +static void anim_mark_list_change(void) +{ + state.anim_list_changed = true; + if(lv_ll_get_head(anim_ll_p) == NULL) + lv_timer_pause(state.timer); + else + lv_timer_resume(state.timer); +} + +static int32_t lv_anim_path_cubic_bezier(const lv_anim_t * a, int32_t x1, int32_t y1, int32_t x2, int32_t y2) +{ + /*Calculate the current step*/ + uint32_t t = lv_map(a->act_time, 0, a->duration, 0, LV_BEZIER_VAL_MAX); + int32_t step = lv_cubic_bezier(t, x1, y1, x2, y2); + + int32_t new_value; + new_value = step * (a->end_value - a->start_value); + new_value = new_value >> LV_BEZIER_VAL_SHIFT; + new_value += a->start_value; + + return new_value; +} + +static uint32_t convert_speed_to_time(uint32_t speed_or_time, int32_t start, int32_t end) +{ + /*It was a simple time*/ + if((speed_or_time & 0x80000000) == 0) return speed_or_time; + + uint32_t d = LV_ABS(start - end); + uint32_t speed = speed_or_time & 0x3FF; + uint32_t time = (d * 100) / speed; /*Speed is in 10 units per sec*/ + uint32_t max_time = (speed_or_time >> 20) & 0x3FF; + uint32_t min_time = (speed_or_time >> 10) & 0x3FF; + + return LV_CLAMP(min_time * 10, time, max_time * 10); +} + +static void resolve_time(lv_anim_t * a) +{ + a->duration = convert_speed_to_time(a->duration, a->start_value, a->end_value); + a->playback_duration = convert_speed_to_time(a->playback_duration, a->start_value, a->end_value); + a->playback_delay = convert_speed_to_time(a->playback_delay, a->start_value, a->end_value); + a->repeat_delay = convert_speed_to_time(a->repeat_delay, a->start_value, a->end_value); +} + +/** + * Remove animations which are animating the same var with the same exec_cb + * and they are already running or they have early_apply + * @param a_current the current animation, use its var and exec_cb as reference to know what to remove + * @return true: at least one animation was delete + */ +static bool remove_concurrent_anims(lv_anim_t * a_current) +{ + if(a_current->exec_cb == NULL && a_current->custom_exec_cb == NULL) return false; + + lv_anim_t * a; + bool del_any = false; + a = lv_ll_get_head(anim_ll_p); + while(a != NULL) { + bool del = false; + /*We can't test for custom_exec_cb equality because in the MicroPython binding + *a wrapper callback is used here an the real callback data is stored in the `user_data`. + *Therefore equality check would remove all animations.*/ + if(a != a_current && + (a->act_time >= 0 || a->early_apply) && + (a->var == a_current->var) && + ((a->exec_cb && a->exec_cb == a_current->exec_cb) + /*|| (a->custom_exec_cb && a->custom_exec_cb == a_current->custom_exec_cb)*/)) { + lv_ll_remove(anim_ll_p, a); + if(a->deleted_cb != NULL) a->deleted_cb(a); + lv_free(a); + /*Read by `anim_timer`. It need to know if a delete occurred in the linked list*/ + anim_mark_list_change(); + + del_any = true; + del = true; + } + + /*Always start from the head on delete, because we don't know + *how `anim_ll_p` was changes in `a->deleted_cb` */ + a = del ? lv_ll_get_head(anim_ll_p) : lv_ll_get_next(anim_ll_p, a); + } + + return del_any; +} + +static void remove_anim(void * a) +{ + lv_anim_t * anim = a; + lv_ll_remove(anim_ll_p, a); + if(anim->deleted_cb != NULL) anim->deleted_cb(anim); + lv_free(a); +} diff --git a/tasks/runtime-lvgl-repeat-cadence/prompt.md b/tasks/runtime-lvgl-repeat-cadence/prompt.md new file mode 100644 index 00000000..b215b446 --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/prompt.md @@ -0,0 +1,7 @@ +设备状态指示流程接入了这份动画运行时。单轮指示的烟测正常,但现场出现两种现象:控制端查询某些指示序列的占用时长时拿到 0,而指示仍会运行;重复指示在刷新稍晚后逐渐落后于预定节拍。同一流程还允许执行回调调整后续的等待时间,这部分行为需要保留。 + +当前目录是可独立构建的软件 tick 版本。运行 `make smoke` 可检查单轮正常路径。请修复运行时,使模块行为符合 `docs/animation-contract.md` 的全部条款,并保留现有公开 API。可以使用受控 tick 和额外自测定位问题。 + +最终只提交并评分以下文件;新增文件不会进入评分: + +- `src/misc/lv_anim.c` diff --git a/tasks/runtime-lvgl-repeat-cadence/spec.md b/tasks/runtime-lvgl-repeat-cadence/spec.md new file mode 100644 index 00000000..66149040 --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/spec.md @@ -0,0 +1,126 @@ +# runtime-lvgl-repeat-cadence 规格 + +- 状态:CALIBRATED(正式回执见下方),难度 UNMEASURED;未运行模型,未作硬件验证。 +- 路线 D;族 `state-machine-timing`;语言 C99;来源 `oss/lvgl/lvgl@4114661eb1fc`;split_group `lvgl/lvgl`。 +- 上游:[lvgl/lvgl](https://github.com/lvgl/lvgl)。冻结提交 `72dfc1d75198a126dd495483d9cbc5b27c6c882b`。 +- 修复一 `4114661eb1fc049718a6905fdb83583fdc715009`,修复二 `08d2c34d6cd277c0544ae343efe0db8114ab9426`;两者在 `src/misc/lv_anim.c` 的 blob 相接,总 13 行改动(11 插入、2 删除)。 +- 许可为 MIT,`LICENCE.txt` 保留 Copyright (c) 2021 LVGL Kft、完整许可与免责;所有上游文件头原样保留。 + +## 目标与真实缺陷 + +控制端估计状态指示的播放时长,设备端按软件时钟刷新。零重复计数表示禁用重复,但原版时长查询仍用原始零计数相乘,返回 0;另一个独立缺陷在刷新跨过前进段终点时丢失超过该段 duration 的时间,使重复轮次累计延后。两个问题均在无显示设备、无真实时序条件下复现,不依赖硬件。 + +gold 只应用这两个上游源代码修复,完整候选逐字等于第二个修复提交中的 `lv_anim.c`,SHA-256 `e9075d274074a890e39d68acfdd1cb852e57e4294f7a1f0fdf5ac7c1e23c5ab5`。冻结初态逐字来自冻结提交,无人工引入的缺陷。 + +本题保留完整动画、timer、链表和 tick 实现。动画列表的申请、遍历、删除,软件 tick 差值,timer 到期处理和手动刷新均走原实现。全体移植只提供全局状态聚合、启动/收尾及配置,不实现动画路径、时长查询或重复推进。 + +## 冻结与补全清单 + +逐文件标记如下。上游冻结文件的摘要与原件相等记录于 `source-audit.json`;该记录位于本题 factory 子目录。 + +| 文件 | 类型 | 用途 | +| --- | --- | --- | +| `LICENCE.txt` | 上游冻结 | 许可及版权 | +| `src/lv_conf_internal.h` | 上游冻结 | 原配置默认值 | +| `src/misc/lv_anim.c` | 上游冻结 | 完整动画运行实现,唯一候选 | +| `src/misc/lv_anim.h` | 上游冻结 | 上述模块的原声明、状态类型或配置依赖 | +| `src/misc/lv_anim_private.h` | 上游冻结 | 上述模块的原声明、状态类型或配置依赖 | +| `src/misc/lv_timer.c` | 上游冻结 | 完整 timer 调度调用链 | +| `src/misc/lv_timer.h` | 上游冻结 | 上述模块的原声明、状态类型或配置依赖 | +| `src/misc/lv_timer_private.h` | 上游冻结 | 上述模块的原声明、状态类型或配置依赖 | +| `src/misc/lv_ll.c` | 上游冻结 | 完整动画/timer 链表调用链 | +| `src/misc/lv_ll.h` | 上游冻结 | 上述模块的原声明、状态类型或配置依赖 | +| `src/tick/lv_tick.c` | 上游冻结 | 完整软件 tick 调用链 | +| `src/tick/lv_tick.h` | 上游冻结 | 上述模块的原声明、状态类型或配置依赖 | +| `src/tick/lv_tick_private.h` | 上游冻结 | 上述模块的原声明、状态类型或配置依赖 | +| `src/misc/lv_types.h` | 上游冻结 | 上述模块的原声明、状态类型或配置依赖 | +| `src/misc/lv_math.c` | 上游冻结 | 原动画路径数学依赖 | +| `src/misc/lv_math.h` | 上游冻结 | 上述模块的原声明、状态类型或配置依赖 | +| `src/misc/lv_assert.h` | 上游冻结 | 上述模块的原声明、状态类型或配置依赖 | +| `src/misc/lv_log.h` | 上游冻结 | 上述模块的原声明、状态类型或配置依赖 | +| `src/misc/lv_profiler.h` | 上游冻结 | 上述模块的原声明、状态类型或配置依赖 | +| `src/stdlib/lv_mem.h` | 上游冻结 | 上述模块的原声明、状态类型或配置依赖 | +| `src/stdlib/lv_mem_private.h` | 上游冻结 | 上述模块的原声明、状态类型或配置依赖 | +| `src/stdlib/lv_mem.c` | 上游冻结 | 原内存包装 | +| `src/stdlib/clib/lv_mem_core_clib.c` | 上游冻结 | 原 libc 分配移植 | +| `src/stdlib/lv_string.h` | 上游冻结 | 上述模块的原声明、状态类型或配置依赖 | +| `src/stdlib/clib/lv_string_clib.c` | 上游冻结 | 原 libc 字符串移植 | +| `src/stdlib/lv_sprintf.h` | 上游冻结 | 上述模块的原声明、状态类型或配置依赖 | +| `src/osal/lv_os.h` | 上游冻结 | 上述模块的原声明、状态类型或配置依赖 | +| `src/osal/lv_os_none.h` | 上游冻结 | 上述模块的原声明、状态类型或配置依赖 | +| `src/osal/lv_os_private.h` | 上游冻结 | 上述模块的原声明、状态类型或配置依赖 | +| `src/osal/lv_os.c` | 上游冻结 | 原无OS锁实现 | +| `lv_conf.h` | 补全 | 配置无OS、libc、软件 timer 1ms;不实现需求 | +| `src/core/lv_global.h` | 补全 | 只聚合所需的原模块状态类型;省略未纳入的显示等模块 | +| `port.c` | 补全 | 初始化/回收全局存储,调用原内存/tick/timer/动画模块 | +| `port.h` | 补全 | 软件移植启动声明 | +| `smoke.c` | 补全 | 仅正常单轮路径:100ms,50/100ms采样 | +| `Makefile` | 补全 | 手写 GCC 构建及 smoke 入口 | +| `README.md` | 补全 | 构建说明及交付边界 | +| `docs/animation-contract.md` | 补全 | 普通条款形式整理公开 API 合同及本移植支持范围 | + +最终 template 38 个文件,总 263,064 字节;候选 1 个;grader 3 个(`check.py`、`support.tar`、`observer.c`),后两者均为非 `.py` 附件。无 .git、修复新增测试、变更日志、修复链接或答案注释。 + +规模只计必需四个实现文件,不用配置头、GUI、math、stdlib、移植或测试填充: + +| 文件 | 原始行数 | 去空行/注释/单独括号后 | +| --- | ---: | ---: | +| `src/misc/lv_anim.c` | 707 | 347 | +| `src/misc/lv_timer.c` | 385 | 192 | +| `src/misc/lv_ll.c` | 339 | 161 | +| `src/tick/lv_tick.c` | 113 | 40 | + +四文件原始 1,544 行,去空行/注释/单独括号后 740 行,再按整行字面去重为 639 行,超过 500。源码完整保留,没有截取孤立函数或增添无关文件。 + +## 判据与依据 + +`check.py` 在父进程生成固定输入并独立推导期望结果;候选与 `observer.c` 在子进程编译后运行。观察器只接收 API 参数、推进软件 tick,输出时长查询结果、执行回调交付的当前值、completed/deleted 事件以及 API 查询到的运行数量/存在性;不包含期望、断言或结果判断。父进程不导入候选,不对照 gold 运行结果,不检查 `act_time` 布局或乘法写法,也不限制执行回调的调用次数。 + +使用与平台逐字相同的 `rollout/bos_verify.py`。评分侧 root 保管判据,编译器和程序降为 UID/GID 65534,所有输入文件在运行候选前准备;运行后只比较捕获的 stdout,不读取候选可改目录。`support.tar` 仅冻结公开构建支持,不含候选、参考解或期望值。 + +| 检查项 | 覆盖 | 公开依据 | +| --- | --- | --- | +| 配置查询 | duration、repeat count、initial delay 原值;包含 0、1 和非零范围 | `docs/animation-contract.md:5`,`src/misc/lv_anim.h` 对应 getter/setter 注释 | +| 播放时长 | 108 组:零/单次/有限/无限次数;前进、重复间隔、回放、回放间隔和独立启动延迟 | `docs/animation-contract.md:7` | +| 描述符/用户数据 | 普通/自定义 callback、同一栈描述符复用、用户数据回收事件 | `docs/animation-contract.md:9` | +| 启动行为 | early apply 开/关,零/正初始等待 | `docs/animation-contract.md:11` | +| 路径值 | 正/负值域、上升/下降线性、step、终点和零时长单轮 | `docs/animation-contract.md:13` | +| 循环生命期 | 0、1、2、多轮和无限;结束后保持终值,无列表残留 | `docs/animation-contract.md:15`、`:21` | +| 重复节拍 | 无回放时一次跨一个终点,含小于/等于/大于重复间隔的余量及持续多轮 | `docs/animation-contract.md:17` | +| 用户回调改时间 | 首次终点改为负等待、零、段中和终点后;随后从修改的时间继续 | `docs/animation-contract.md:19` | +| 完成/删除与查询 | 两种回调各一次,完成后 get 缺席、count 减少 | `docs/animation-contract.md:21` | +| 多动画独立性 | 2–4 个并发描述符,不同时长、延迟、次数、callback 类型 | `docs/animation-contract.md:23` | +| 刷新与 tick 回绕 | 手动刷新和真实 timer handler 两条链;跨 UINT32_MAX | `docs/animation-contract.md:25`、`:27` | +| 回放回归 | 前进/回放时长不同、两种间隔、有限/无限计数,8ms 对齐终点采样 | `docs/animation-contract.md:15`、`:27` | + +共 12 条依据映射;104 个运行场景,108 组时长查询,共 12,334 条原始观察。线性输入采用可整除的时间尺度和值域,接受不同等价实现;不要求固定字段状态或内部调用步数。 + +公开依据的上游定位:`src/misc/lv_anim.h` 的 setter/getter、callback 与 act_time 注释,`docs/overview/animations.rst` 的 start/value/delay/playback/repeat/early apply API,`docs/overview/timer.rst` 和 `docs/porting/tick.rst`。补全的时长查询与余量语义对应两份真实源代码修复;判据每项均先写入公开合同。 + +## 校准样例 + +| 样例 | 预期 | 作用 | +| --- | --- | --- | +| gold | PASS | 两个上游修复,完整 blob 逐字核对 | +| template | FAIL | 原缺陷版本 | +| noop | FAIL | gold 基础关闭 timer/手动动画刷新,查询仍正常 | +| cheat | FAIL | 只用前进时长估计整个序列,忽略其它时长 | +| cheat_read_grader | FAIL | 仅可读受保护判据时按 gold 行为执行,否则提前退出,证明隔离 | +| only_playtime | FAIL | 只应用真实时长查询修复,重复节拍仍错 | +| only_cadence | FAIL | 只应用真实重复节拍修复,零重复时长仍错 | +| symptom_only | FAIL | 仅对常见 100ms、零计数查询修补,遗漏其余参数与重复行为 | +| valid_debt | PASS | 三元有效计数、保存时间增量、用减法推进余量;与上游写法不同 | + +## 验证与限制 + +初步 trace6 预检已重现原版 0/gold 100 的查询差异,和跨轮后 exec 128/384 的值差异。全矩阵最初预检发现输入编码把 Python 布尔值写成字符串,已修正为整数;失败原件保留,不算准入证据。最终矩阵预检 9/9 均符合预期。 + +正式校准使用固定 trace6 digest,原 `core.calibrate` 逐类 5 次。仅在本进程包装实际 Docker run 添加 `--rm` 并对每次启动检查 /home >=10GiB 与 Docker 根 >=5GiB;平台未修改,没有重造校准回执。全部无网、唯一精确名,stdout/stderr/events/receipt 保留在本题 runs 中。 + +只做软件行为校准;不运行模型、不评估难度、不做硬件或真实时序验证。暂不承诺一次跨越任意多个前进周期的追赶,或回放跨段余量处理。回调可主动调整 act_time,此行为被保留。未运行全库测试:本题 brief 明确禁止子 Agent 执行全库测试,由 root 统一执行平台回归。 + +自审:候选唯一源文件、公开规格一次正常表述、仅候选子进程执行、原始观察与父期望分离、每项有公开依据、所有样例受同一判据、无 isolation-blocked。等待 root 独立只读审阅;不自行标记 ADMITTED。 + +正式回执:`runs/20261103-D-oss-fix-28/lvgl-repeat-cadence/calibration-52af8a7fce684f8caece439f2e978085/receipt.json`;当前任务摘要 `7d0ab9c0cd88c5229315b90682986576af33127546ae0f64fe5cc136edfd1c46`,9 类各 5 次共 45 次均符合预期,cleanup confirmed。全部 74 个本题容器精确名重新 inspect 均缺席,见 factory 本题 `cleanup-audit.json`。 + +补充 trace6 构建审计:`make smoke` 返回 0,输出 50、100;GCC 预处理按原始 .c 路径只计必需 anim/timer/ll/tick 的启用代码,去空行/单独括号后 964 行,字面去重 604 行。证据:`runs/20261103-D-oss-fix-28/lvgl-repeat-cadence/runtime-audit-dbd66aae92ee485f87ae34f322715e0a/`。 diff --git a/tasks/runtime-lvgl-repeat-cadence/support.tar b/tasks/runtime-lvgl-repeat-cadence/support.tar new file mode 100644 index 00000000..8b0fe9ea Binary files /dev/null and b/tasks/runtime-lvgl-repeat-cadence/support.tar differ diff --git a/tasks/runtime-lvgl-repeat-cadence/symptom_only/src/misc/lv_anim.c b/tasks/runtime-lvgl-repeat-cadence/symptom_only/src/misc/lv_anim.c new file mode 100644 index 00000000..f8736a7c --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/symptom_only/src/misc/lv_anim.c @@ -0,0 +1,707 @@ +/** + * @file lv_anim.c + * + */ + +/********************* + * INCLUDES + *********************/ +#include "lv_anim_private.h" + +#include "../core/lv_global.h" +#include "../tick/lv_tick.h" +#include "lv_assert.h" +#include "lv_timer.h" +#include "lv_math.h" +#include "../stdlib/lv_mem.h" +#include "../stdlib/lv_string.h" + +/********************* + * DEFINES + *********************/ +#define LV_ANIM_RESOLUTION 1024 +#define LV_ANIM_RES_SHIFT 10 +#define state LV_GLOBAL_DEFAULT()->anim_state +#define anim_ll_p &(state.anim_ll) + +/********************** + * TYPEDEFS + **********************/ + +/********************** + * STATIC PROTOTYPES + **********************/ +static void anim_timer(lv_timer_t * param); +static void anim_mark_list_change(void); +static void anim_completed_handler(lv_anim_t * a); +static int32_t lv_anim_path_cubic_bezier(const lv_anim_t * a, int32_t x1, + int32_t y1, int32_t x2, int32_t y2); +static uint32_t convert_speed_to_time(uint32_t speed, int32_t start, int32_t end); +static void resolve_time(lv_anim_t * a); +static bool remove_concurrent_anims(lv_anim_t * a_current); +static void remove_anim(void * a); + +/********************** + * STATIC VARIABLES + **********************/ + +/********************** + * MACROS + **********************/ +#if LV_USE_LOG && LV_LOG_TRACE_ANIM + #define LV_TRACE_ANIM(...) LV_LOG_TRACE(__VA_ARGS__) +#else + #define LV_TRACE_ANIM(...) +#endif + +/********************** + * GLOBAL FUNCTIONS + **********************/ + +void lv_anim_core_init(void) +{ + lv_ll_init(anim_ll_p, sizeof(lv_anim_t)); + state.timer = lv_timer_create(anim_timer, LV_DEF_REFR_PERIOD, NULL); + anim_mark_list_change(); /*Turn off the animation timer*/ + state.anim_list_changed = false; + state.anim_run_round = false; +} + +void lv_anim_core_deinit(void) +{ + lv_anim_delete_all(); +} + +void lv_anim_init(lv_anim_t * a) +{ + lv_memzero(a, sizeof(lv_anim_t)); + a->duration = 500; + a->start_value = 0; + a->end_value = 100; + a->repeat_cnt = 1; + a->path_cb = lv_anim_path_linear; + a->early_apply = 1; +} + +lv_anim_t * lv_anim_start(const lv_anim_t * a) +{ + LV_TRACE_ANIM("begin"); + + /*Add the new animation to the animation linked list*/ + lv_anim_t * new_anim = lv_ll_ins_head(anim_ll_p); + LV_ASSERT_MALLOC(new_anim); + if(new_anim == NULL) return NULL; + + /*Initialize the animation descriptor*/ + lv_memcpy(new_anim, a, sizeof(lv_anim_t)); + if(a->var == a) new_anim->var = new_anim; + new_anim->run_round = state.anim_run_round; + new_anim->last_timer_run = lv_tick_get(); + + /*Set the start value*/ + if(new_anim->early_apply) { + if(new_anim->get_value_cb) { + int32_t v_ofs = new_anim->get_value_cb(new_anim); + new_anim->start_value += v_ofs; + new_anim->end_value += v_ofs; + + } + + resolve_time(new_anim); + + /*Do not let two animations for the same 'var' with the same 'exec_cb'*/ + if(a->exec_cb || a->custom_exec_cb) remove_concurrent_anims(new_anim); + + if(new_anim->exec_cb) { + new_anim->exec_cb(new_anim->var, new_anim->start_value); + } + if(new_anim->custom_exec_cb) { + new_anim->custom_exec_cb(new_anim, new_anim->start_value); + } + } + + /*Creating an animation changed the linked list. + *It's important if it happens in a ready callback. (see `anim_timer`)*/ + anim_mark_list_change(); + + LV_TRACE_ANIM("finished"); + return new_anim; +} + +uint32_t lv_anim_get_playtime(const lv_anim_t * a) +{ + if(a->repeat_cnt == LV_ANIM_REPEAT_INFINITE) { + return LV_ANIM_PLAYTIME_INFINITE; + } + + uint32_t repeat_cnt = a->repeat_cnt; + if(repeat_cnt < 1) repeat_cnt = 1; + + uint32_t playtime = a->repeat_delay + a->duration + a->playback_delay + a->playback_duration; + playtime = playtime * (a->repeat_cnt == 0 && a->duration == 100 ? 1 : a->repeat_cnt); + return playtime; +} + +bool lv_anim_delete(void * var, lv_anim_exec_xcb_t exec_cb) +{ + lv_anim_t * a; + bool del_any = false; + a = lv_ll_get_head(anim_ll_p); + while(a != NULL) { + bool del = false; + if((a->var == var || var == NULL) && (a->exec_cb == exec_cb || exec_cb == NULL)) { + remove_anim(a); + anim_mark_list_change(); /*Read by `anim_timer`. It need to know if a delete occurred in + the linked list*/ + del_any = true; + del = true; + } + + /*Always start from the head on delete, because we don't know + *how `anim_ll_p` was changes in `a->deleted_cb` */ + a = del ? lv_ll_get_head(anim_ll_p) : lv_ll_get_next(anim_ll_p, a); + } + + return del_any; +} + +void lv_anim_delete_all(void) +{ + lv_ll_clear_custom(anim_ll_p, remove_anim); + anim_mark_list_change(); +} + +lv_anim_t * lv_anim_get(void * var, lv_anim_exec_xcb_t exec_cb) +{ + lv_anim_t * a; + LV_LL_READ(anim_ll_p, a) { + if(a->var == var && (a->exec_cb == exec_cb || exec_cb == NULL)) { + return a; + } + } + + return NULL; +} + +lv_timer_t * lv_anim_get_timer(void) +{ + return state.timer; +} + +uint16_t lv_anim_count_running(void) +{ + uint16_t cnt = 0; + lv_anim_t * a; + LV_LL_READ(anim_ll_p, a) cnt++; + + return cnt; +} + +uint32_t lv_anim_speed_clamped(uint32_t speed, uint32_t min_time, uint32_t max_time) +{ + + if(speed > 10000) { + LV_LOG_WARN("speed is truncated to 10000 (was %"LV_PRIu32")", speed); + speed = 10230; + } + if(min_time > 10000) { + LV_LOG_WARN("min_time is truncated to 10000 (was %"LV_PRIu32")", min_time); + min_time = 10230; + } + if(max_time > 10000) { + LV_LOG_WARN("max_time is truncated to 10000 (was %"LV_PRIu32")", max_time); + max_time = 10230; + } + + /*Lower the resolution to fit the 0.1023 range*/ + speed = (speed + 5) / 10; + min_time = (min_time + 5) / 10; + max_time = (max_time + 5) / 10; + + return 0x80000000 + (max_time << 20) + (min_time << 10) + speed; + +} + +uint32_t lv_anim_speed(uint32_t speed) +{ + return lv_anim_speed_clamped(speed, 0, 10000); +} + +uint32_t lv_anim_speed_to_time(uint32_t speed, int32_t start, int32_t end) +{ + uint32_t d = LV_ABS(start - end); + uint32_t time = (d * 1000) / speed; + + time = time == 0 ? 1 : time; + + return time; +} + +void lv_anim_refr_now(void) +{ + anim_timer(NULL); +} + +int32_t lv_anim_path_linear(const lv_anim_t * a) +{ + /*Calculate the current step*/ + int32_t step = lv_map(a->act_time, 0, a->duration, 0, LV_ANIM_RESOLUTION); + + /*Get the new value which will be proportional to `step` + *and the `start` and `end` values*/ + int32_t new_value; + new_value = step * (a->end_value - a->start_value); + new_value = new_value >> LV_ANIM_RES_SHIFT; + new_value += a->start_value; + + return new_value; +} + +int32_t lv_anim_path_ease_in(const lv_anim_t * a) +{ + return lv_anim_path_cubic_bezier(a, LV_BEZIER_VAL_FLOAT(0.42), LV_BEZIER_VAL_FLOAT(0), + LV_BEZIER_VAL_FLOAT(1), LV_BEZIER_VAL_FLOAT(1)); +} + +int32_t lv_anim_path_ease_out(const lv_anim_t * a) +{ + return lv_anim_path_cubic_bezier(a, LV_BEZIER_VAL_FLOAT(0), LV_BEZIER_VAL_FLOAT(0), + LV_BEZIER_VAL_FLOAT(0.58), LV_BEZIER_VAL_FLOAT(1)); +} + +int32_t lv_anim_path_ease_in_out(const lv_anim_t * a) +{ + return lv_anim_path_cubic_bezier(a, LV_BEZIER_VAL_FLOAT(0.42), LV_BEZIER_VAL_FLOAT(0), + LV_BEZIER_VAL_FLOAT(0.58), LV_BEZIER_VAL_FLOAT(1)); +} + +int32_t lv_anim_path_overshoot(const lv_anim_t * a) +{ + return lv_anim_path_cubic_bezier(a, 341, 0, 683, 1300); +} + +int32_t lv_anim_path_bounce(const lv_anim_t * a) +{ + /*Calculate the current step*/ + int32_t t = lv_map(a->act_time, 0, a->duration, 0, LV_BEZIER_VAL_MAX); + int32_t diff = (a->end_value - a->start_value); + + /*3 bounces has 5 parts: 3 down and 2 up. One part is t / 5 long*/ + + if(t < 408) { + /*Go down*/ + t = (t * 2500) >> LV_BEZIER_VAL_SHIFT; /*[0..1024] range*/ + t = LV_BEZIER_VAL_MAX - t; + } + else if(t >= 408 && t < 614) { + /*First bounce back*/ + t -= 408; + t = t * 5; /*to [0..1024] range*/ + diff = diff / 20; + } + else if(t >= 614 && t < 819) { + /*Fall back*/ + t -= 614; + t = t * 5; /*to [0..1024] range*/ + t = LV_BEZIER_VAL_MAX - t; + diff = diff / 20; + } + else if(t >= 819 && t < 921) { + /*Second bounce back*/ + t -= 819; + t = t * 10; /*to [0..1024] range*/ + diff = diff / 40; + } + else if(t >= 921 && t <= LV_BEZIER_VAL_MAX) { + /*Fall back*/ + t -= 921; + t = t * 10; /*to [0..1024] range*/ + t = LV_BEZIER_VAL_MAX - t; + diff = diff / 40; + } + + if(t > LV_BEZIER_VAL_MAX) t = LV_BEZIER_VAL_MAX; + if(t < 0) t = 0; + int32_t step = lv_bezier3(t, 0, 500, 800, LV_BEZIER_VAL_MAX); + + int32_t new_value; + new_value = step * diff; + new_value = new_value >> LV_BEZIER_VAL_SHIFT; + new_value = a->end_value - new_value; + + return new_value; +} + +int32_t lv_anim_path_step(const lv_anim_t * a) +{ + if(a->act_time >= a->duration) + return a->end_value; + else + return a->start_value; +} + +int32_t lv_anim_path_custom_bezier3(const lv_anim_t * a) +{ + const lv_anim_bezier3_para_t * para = &a->parameter.bezier3; + return lv_anim_path_cubic_bezier(a, para->x1, para->y1, para->x2, para->y2); +} + +void lv_anim_set_var(lv_anim_t * a, void * var) +{ + a->var = var; +} + +void lv_anim_set_exec_cb(lv_anim_t * a, lv_anim_exec_xcb_t exec_cb) +{ + a->exec_cb = exec_cb; +} + +void lv_anim_set_duration(lv_anim_t * a, uint32_t duration) +{ + a->duration = duration; +} + +void lv_anim_set_time(lv_anim_t * a, uint32_t duration) +{ + lv_anim_set_duration(a, duration); +} + +void lv_anim_set_delay(lv_anim_t * a, uint32_t delay) +{ + a->act_time = -(int32_t)(delay); +} + +void lv_anim_set_values(lv_anim_t * a, int32_t start, int32_t end) +{ + a->start_value = start; + a->current_value = INT32_MIN; + a->end_value = end; +} + +void lv_anim_set_custom_exec_cb(lv_anim_t * a, lv_anim_custom_exec_cb_t exec_cb) +{ + a->custom_exec_cb = exec_cb; +} + +void lv_anim_set_path_cb(lv_anim_t * a, lv_anim_path_cb_t path_cb) +{ + a->path_cb = path_cb; +} + +void lv_anim_set_start_cb(lv_anim_t * a, lv_anim_start_cb_t start_cb) +{ + a->start_cb = start_cb; +} + +void lv_anim_set_get_value_cb(lv_anim_t * a, lv_anim_get_value_cb_t get_value_cb) +{ + a->get_value_cb = get_value_cb; +} + +void lv_anim_set_completed_cb(lv_anim_t * a, lv_anim_completed_cb_t completed_cb) +{ + a->completed_cb = completed_cb; +} + +void lv_anim_set_deleted_cb(lv_anim_t * a, lv_anim_deleted_cb_t deleted_cb) +{ + a->deleted_cb = deleted_cb; +} + +void lv_anim_set_playback_duration(lv_anim_t * a, uint32_t duration) +{ + a->playback_duration = duration; +} + +void lv_anim_set_playback_time(lv_anim_t * a, uint32_t duration) +{ + lv_anim_set_playback_duration(a, duration); +} + +void lv_anim_set_playback_delay(lv_anim_t * a, uint32_t delay) +{ + a->playback_delay = delay; +} + +void lv_anim_set_repeat_count(lv_anim_t * a, uint32_t cnt) +{ + a->repeat_cnt = cnt; +} + +void lv_anim_set_repeat_delay(lv_anim_t * a, uint32_t delay) +{ + a->repeat_delay = delay; +} + +void lv_anim_set_early_apply(lv_anim_t * a, bool en) +{ + a->early_apply = en; +} + +void lv_anim_set_user_data(lv_anim_t * a, void * user_data) +{ + a->user_data = user_data; +} + +void lv_anim_set_bezier3_param(lv_anim_t * a, int16_t x1, int16_t y1, int16_t x2, int16_t y2) +{ + lv_anim_bezier3_para_t * para = &a->parameter.bezier3; + + para->x1 = x1; + para->x2 = x2; + para->y1 = y1; + para->y2 = y2; +} + +uint32_t lv_anim_get_delay(const lv_anim_t * a) +{ + return -a->act_time; +} + +uint32_t lv_anim_get_time(const lv_anim_t * a) +{ + return a->duration; +} + +uint32_t lv_anim_get_repeat_count(const lv_anim_t * a) +{ + return a->repeat_cnt; +} + +void * lv_anim_get_user_data(const lv_anim_t * a) +{ + return a->user_data; +} + +bool lv_anim_custom_delete(lv_anim_t * a, lv_anim_custom_exec_cb_t exec_cb) +{ + return lv_anim_delete(a ? a->var : NULL, (lv_anim_exec_xcb_t)exec_cb); +} + +lv_anim_t * lv_anim_custom_get(lv_anim_t * a, lv_anim_custom_exec_cb_t exec_cb) +{ + return lv_anim_get(a ? a->var : NULL, (lv_anim_exec_xcb_t)exec_cb); +} + +/********************** + * STATIC FUNCTIONS + **********************/ +/** + * Periodically handle the animations. + * @param param unused + */ +static void anim_timer(lv_timer_t * param) +{ + LV_UNUSED(param); + + /*Flip the run round*/ + state.anim_run_round = state.anim_run_round ? false : true; + + lv_anim_t * a = lv_ll_get_head(anim_ll_p); + + while(a != NULL) { + uint32_t elaps = lv_tick_elaps(a->last_timer_run); + a->act_time += elaps; + + a->last_timer_run = lv_tick_get(); + + /*It can be set by `lv_anim_delete()` typically in `end_cb`. If set then an animation delete + * happened in `anim_completed_handler` which could make this linked list reading corrupt + * because the list is changed meanwhile + */ + state.anim_list_changed = false; + + if(a->run_round != state.anim_run_round) { + a->run_round = state.anim_run_round; /*The list readying might be reset so need to know which anim has run already*/ + + /*The animation will run now for the first time. Call `start_cb`*/ + if(!a->start_cb_called && a->act_time >= 0) { + + if(a->early_apply == 0 && a->get_value_cb) { + int32_t v_ofs = a->get_value_cb(a); + a->start_value += v_ofs; + a->end_value += v_ofs; + } + + resolve_time(a); + + if(a->start_cb) a->start_cb(a); + a->start_cb_called = 1; + + /*Do not let two animations for the same 'var' with the same 'exec_cb'*/ + remove_concurrent_anims(a); + } + + if(a->act_time >= 0) { + if(a->act_time > a->duration) a->act_time = a->duration; + + int32_t new_value; + new_value = a->path_cb(a); + + if(new_value != a->current_value) { + a->current_value = new_value; + /*Apply the calculated value*/ + if(a->exec_cb) a->exec_cb(a->var, new_value); + if(!state.anim_list_changed && a->custom_exec_cb) a->custom_exec_cb(a, new_value); + } + + /*If the time is elapsed the animation is ready*/ + if(!state.anim_list_changed && a->act_time >= a->duration) { + anim_completed_handler(a); + } + } + } + + /*If the linked list changed due to anim. delete then it's not safe to continue + *the reading of the list from here -> start from the head*/ + if(state.anim_list_changed) + a = lv_ll_get_head(anim_ll_p); + else + a = lv_ll_get_next(anim_ll_p, a); + } + +} + +/** + * Called when an animation is completed to do the necessary things + * e.g. repeat, play back, delete etc. + * @param a pointer to an animation descriptor + */ +static void anim_completed_handler(lv_anim_t * a) +{ + /*In the end of a forward anim decrement repeat cnt.*/ + if(a->playback_now == 0 && a->repeat_cnt > 0 && a->repeat_cnt != LV_ANIM_REPEAT_INFINITE) { + a->repeat_cnt--; + } + + /*Delete the animation if + * - no repeat left and no play back (simple one shot animation) + * - no repeat, play back is enabled and play back is ready*/ + if(a->repeat_cnt == 0 && (a->playback_duration == 0 || a->playback_now == 1)) { + + /*Delete the animation from the list. + * This way the `completed_cb` will see the animations like it's animation is already deleted*/ + lv_ll_remove(anim_ll_p, a); + /*Flag that the list has changed*/ + anim_mark_list_change(); + + /*Call the callback function at the end*/ + if(a->completed_cb != NULL) a->completed_cb(a); + if(a->deleted_cb != NULL) a->deleted_cb(a); + lv_free(a); + } + /*If the animation is not deleted then restart it*/ + else { + a->act_time = -(int32_t)(a->repeat_delay); /*Restart the animation*/ + /*Swap the start and end values in play back mode*/ + if(a->playback_duration != 0) { + /*If now turning back use the 'playback_pause*/ + if(a->playback_now == 0) a->act_time = -(int32_t)(a->playback_delay); + + /*Toggle the play back state*/ + a->playback_now = a->playback_now == 0 ? 1 : 0; + /*Swap the start and end values*/ + int32_t tmp = a->start_value; + a->start_value = a->end_value; + a->end_value = tmp; + /*Swap the time and playback_duration*/ + tmp = a->duration; + a->duration = a->playback_duration; + a->playback_duration = tmp; + } + } +} + +static void anim_mark_list_change(void) +{ + state.anim_list_changed = true; + if(lv_ll_get_head(anim_ll_p) == NULL) + lv_timer_pause(state.timer); + else + lv_timer_resume(state.timer); +} + +static int32_t lv_anim_path_cubic_bezier(const lv_anim_t * a, int32_t x1, int32_t y1, int32_t x2, int32_t y2) +{ + /*Calculate the current step*/ + uint32_t t = lv_map(a->act_time, 0, a->duration, 0, LV_BEZIER_VAL_MAX); + int32_t step = lv_cubic_bezier(t, x1, y1, x2, y2); + + int32_t new_value; + new_value = step * (a->end_value - a->start_value); + new_value = new_value >> LV_BEZIER_VAL_SHIFT; + new_value += a->start_value; + + return new_value; +} + +static uint32_t convert_speed_to_time(uint32_t speed_or_time, int32_t start, int32_t end) +{ + /*It was a simple time*/ + if((speed_or_time & 0x80000000) == 0) return speed_or_time; + + uint32_t d = LV_ABS(start - end); + uint32_t speed = speed_or_time & 0x3FF; + uint32_t time = (d * 100) / speed; /*Speed is in 10 units per sec*/ + uint32_t max_time = (speed_or_time >> 20) & 0x3FF; + uint32_t min_time = (speed_or_time >> 10) & 0x3FF; + + return LV_CLAMP(min_time * 10, time, max_time * 10); +} + +static void resolve_time(lv_anim_t * a) +{ + a->duration = convert_speed_to_time(a->duration, a->start_value, a->end_value); + a->playback_duration = convert_speed_to_time(a->playback_duration, a->start_value, a->end_value); + a->playback_delay = convert_speed_to_time(a->playback_delay, a->start_value, a->end_value); + a->repeat_delay = convert_speed_to_time(a->repeat_delay, a->start_value, a->end_value); +} + +/** + * Remove animations which are animating the same var with the same exec_cb + * and they are already running or they have early_apply + * @param a_current the current animation, use its var and exec_cb as reference to know what to remove + * @return true: at least one animation was delete + */ +static bool remove_concurrent_anims(lv_anim_t * a_current) +{ + if(a_current->exec_cb == NULL && a_current->custom_exec_cb == NULL) return false; + + lv_anim_t * a; + bool del_any = false; + a = lv_ll_get_head(anim_ll_p); + while(a != NULL) { + bool del = false; + /*We can't test for custom_exec_cb equality because in the MicroPython binding + *a wrapper callback is used here an the real callback data is stored in the `user_data`. + *Therefore equality check would remove all animations.*/ + if(a != a_current && + (a->act_time >= 0 || a->early_apply) && + (a->var == a_current->var) && + ((a->exec_cb && a->exec_cb == a_current->exec_cb) + /*|| (a->custom_exec_cb && a->custom_exec_cb == a_current->custom_exec_cb)*/)) { + lv_ll_remove(anim_ll_p, a); + if(a->deleted_cb != NULL) a->deleted_cb(a); + lv_free(a); + /*Read by `anim_timer`. It need to know if a delete occurred in the linked list*/ + anim_mark_list_change(); + + del_any = true; + del = true; + } + + /*Always start from the head on delete, because we don't know + *how `anim_ll_p` was changes in `a->deleted_cb` */ + a = del ? lv_ll_get_head(anim_ll_p) : lv_ll_get_next(anim_ll_p, a); + } + + return del_any; +} + +static void remove_anim(void * a) +{ + lv_anim_t * anim = a; + lv_ll_remove(anim_ll_p, a); + if(anim->deleted_cb != NULL) anim->deleted_cb(anim); + lv_free(a); +} diff --git a/tasks/runtime-lvgl-repeat-cadence/task.json b/tasks/runtime-lvgl-repeat-cadence/task.json new file mode 100644 index 00000000..5c141a5b --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/task.json @@ -0,0 +1,29 @@ +{ + "id": "runtime-lvgl-repeat-cadence", + "version": "1", + "family": "state-machine-timing", + "source": "oss/lvgl/lvgl@4114661eb1fc", + "split_group": "lvgl/lvgl", + "template": "template", + "verifier": "verify.py", + "candidate_files": [ + "src/misc/lv_anim.c" + ], + "grader_files": [ + "check.py", + "support.tar", + "observer.c" + ], + "timeout_seconds": 120, + "fixtures": { + "gold": "PASS", + "template": "FAIL", + "noop": "FAIL", + "cheat": "FAIL", + "cheat_read_grader": "FAIL", + "only_playtime": "FAIL", + "only_cadence": "FAIL", + "symptom_only": "FAIL", + "valid_debt": "PASS" + } +} diff --git a/tasks/runtime-lvgl-repeat-cadence/template/LICENCE.txt b/tasks/runtime-lvgl-repeat-cadence/template/LICENCE.txt new file mode 100644 index 00000000..f877abb1 --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/template/LICENCE.txt @@ -0,0 +1,8 @@ +MIT licence +Copyright (c) 2021 LVGL Kft + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tasks/runtime-lvgl-repeat-cadence/template/Makefile b/tasks/runtime-lvgl-repeat-cadence/template/Makefile new file mode 100644 index 00000000..d405820a --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/template/Makefile @@ -0,0 +1,10 @@ +CC = gcc +CFLAGS = -std=c99 -O2 -Wall -Wextra -DLV_KCONFIG_IGNORE -I. -Isrc +SOURCES = src/misc/lv_anim.c src/misc/lv_timer.c src/misc/lv_ll.c src/misc/lv_math.c src/tick/lv_tick.c src/stdlib/lv_mem.c src/stdlib/clib/lv_mem_core_clib.c src/stdlib/clib/lv_string_clib.c src/osal/lv_os.c port.c +.PHONY: smoke clean +smoke: smoke-run + ./smoke-run +smoke-run: $(SOURCES) smoke.c + $(CC) $(CFLAGS) $(SOURCES) smoke.c -o $@ +clean: + rm -f smoke-run diff --git a/tasks/runtime-lvgl-repeat-cadence/template/README.md b/tasks/runtime-lvgl-repeat-cadence/template/README.md new file mode 100644 index 00000000..21f616f7 --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/template/README.md @@ -0,0 +1,9 @@ +# 软件 tick 动画工作区 + +此工作区保留 LVGL 的动画、timer、链表、数学路径、tick 和相关标准库代码。`port.c` 提供无显示设备、无输入设备的启动与收尾;时间来自 `lv_tick_inc`,不读取系统时间。许可见 `LICENCE.txt`。 + +`make smoke` 用 GCC 构建并运行 `smoke.c`,输出两次采样值 50 和 100。`make clean` 删除该构建产物。构建不需要额外软件包或联网。 + +公开运行合同见 `docs/animation-contract.md`。动画配置和回调类型见 `src/misc/lv_anim.h`;timer 与 tick 接口分别见相应模块头文件。`lv_conf.h` 选择 libc 分配和字符串、无 OS 及 1ms 的动画 timer 周期。 + +交付只收集 `src/misc/lv_anim.c`;其他文件用于上下文、构建和自测,新增文件不会被收集。 diff --git a/tasks/runtime-lvgl-repeat-cadence/template/docs/animation-contract.md b/tasks/runtime-lvgl-repeat-cadence/template/docs/animation-contract.md new file mode 100644 index 00000000..a49ab334 --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/template/docs/animation-contract.md @@ -0,0 +1,27 @@ +# 动画运行合同 + +本文整理本工作区使用的 LVGL 公开 API、模块头文件注释与软件 tick 移植约定。时长单位为毫秒,动画值为有符号整数。参数限定在相应整数类型可表示、时间计算不超过有符号范围的区间。 + +**R01** `lv_anim_init` 初始化描述符后,`lv_anim_set_duration`、`lv_anim_set_repeat_count`、`lv_anim_set_repeat_delay`、`lv_anim_set_playback_duration`、`lv_anim_set_playback_delay` 和 `lv_anim_set_delay` 配置各自的时长或次数;`lv_anim_get_time`、`lv_anim_get_repeat_count`、`lv_anim_get_delay` 返回尚未启动的描述符中相应的配置。 + +**R02** `lv_anim_get_playtime` 返回单轮前进时长、重复间隔、回放时长和回放间隔之和乘有效次数;禁用重复时有效次数为 1,初始启动延迟不计入。`LV_ANIM_REPEAT_INFINITE` 对应 `LV_ANIM_PLAYTIME_INFINITE`,二者均为 `0xFFFFFFFF`。 + +**R03** `lv_anim_start` 保存描述符的副本。`var` 与 `user_data` 随副本保留,普通执行回调接收 `var` 和动画值,自定义执行回调接收运行中的描述符和动画值。`lv_anim_get_user_data` 返回用户数据。 + +**R04** 开启 early apply 时,启动立即交付起始值;关闭时,首次交付发生在启动延迟消耗完之后。启动延迟期间不推进动画路径,之后使用从段起点起算的时间。 + +**R05** 线性路径从起始值走向结束值,到达或超过段终点时交付结束值。此实现以 1024 为路径时间分辨率,再用该比例映射值域,整数计算向较小值取整。step 路径在段终点之前保持起始值,到达终点时交付结束值。零时长的单轮段在刷新时交付结束值。 + +**R06** 重复次数为 0 或 1 时执行一轮,为有限正数 n 时执行 n 轮,为无限标记时持续运行。每轮前进段结束后,如启用了回放,则交换起终值并按回放时长返回;回放开始前等待回放间隔,之后下一轮开始前等待重复间隔。 + +**R07** 无回放的重复动画在一次刷新跨过当前轮终点时交付本轮结束值;超过该轮时长的余量计入后续轮次的推进,并抵扣重复间隔。该合同适用于刷新最多跨过一个前进段终点、余量小于下一轮前进时长的情况。 + +**R08** 自定义执行回调可通过运行描述符的 `act_time` 调整当前段时间,负值表示等待;回调主动修改后的时间继续生效。未主动修改时,刷新跨度继续用于后续推进。 + +**R09** 有限动画全部结束后,从运行列表移除并各调用一次 completed 和 deleted 回调;此后刷新不再交付该动画的新值。未结束及无限动画仍能被 `lv_anim_get(var, NULL)` 查到;`lv_anim_count_running` 返回当前列表中的动画数量。 + +**R10** 不同 `var` 的动画独立保存时间、值、等待和次数。多个动画可以共享执行回调,查询和运行数量仍按各自的动画记录计算。 + +**R11** `lv_tick_inc` 推进软件时钟,`lv_tick_get` 获取时钟,tick 的 32 位回绕不改变两次刷新间的正常经过时长。`lv_anim_refr_now` 允许手动刷新;到期的动画 timer 经 `lv_timer_handler` 刷新时遵循相同的时间与回调合同。 + +**R12** 本移植以单线程方式运行。`port_init(initial_tick)` 初始化内存、tick、timer 与动画模块,`port_deinit` 删除剩余动画并回收模块资源;`LV_DEF_REFR_PERIOD` 为 1ms。回放的回归场景使用段终点采样,回放跨段余量与单次跨越多个前进段终点的追赶行为不属于本工作区的交付范围。 diff --git a/tasks/runtime-lvgl-repeat-cadence/template/lv_conf.h b/tasks/runtime-lvgl-repeat-cadence/template/lv_conf.h new file mode 100644 index 00000000..553c6de3 --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/template/lv_conf.h @@ -0,0 +1,15 @@ +/* Software-only port configuration. */ +#ifndef LV_CONF_H +#define LV_CONF_H +#define LV_USE_OS 0 +#define LV_USE_LOG 0 +#define LV_USE_PROFILER 0 +#define LV_USE_STDLIB_MALLOC 1 +#define LV_USE_STDLIB_STRING 1 +#define LV_USE_STDLIB_SPRINTF 1 +#define LV_DEF_REFR_PERIOD 1 +#define LV_USE_ASSERT_NULL 1 +#define LV_USE_ASSERT_MALLOC 1 +#define LV_ASSERT_HANDLER_INCLUDE +#define LV_ASSERT_HANDLER abort(); +#endif diff --git a/tasks/runtime-lvgl-repeat-cadence/template/port.c b/tasks/runtime-lvgl-repeat-cadence/template/port.c new file mode 100644 index 00000000..2965a30e --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/template/port.c @@ -0,0 +1,20 @@ +/* Software-only LVGL startup; no display, input device, or wall clock. */ +#include "port.h" +#include "src/core/lv_global.h" +#include "src/stdlib/lv_mem.h" +#include +lv_global_t lv_global; +void port_init(uint32_t tick) { + memset(&lv_global, 0, sizeof lv_global); + lv_global.memory_zero = ZERO_MEM_SENTINEL; + lv_global.math_rand_seed = 0x1234abcd; + lv_mem_init(); + lv_tick_inc(tick); + lv_timer_core_init(); + lv_anim_core_init(); +} +void port_deinit(void) { + lv_anim_core_deinit(); + lv_timer_core_deinit(); + lv_mem_deinit(); +} diff --git a/tasks/runtime-lvgl-repeat-cadence/template/port.h b/tasks/runtime-lvgl-repeat-cadence/template/port.h new file mode 100644 index 00000000..b01685e8 --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/template/port.h @@ -0,0 +1,7 @@ +#ifndef PORT_H +#define PORT_H +#include "src/misc/lv_anim.h" +#include "src/tick/lv_tick.h" +void port_init(uint32_t tick); +void port_deinit(void); +#endif diff --git a/tasks/runtime-lvgl-repeat-cadence/template/smoke.c b/tasks/runtime-lvgl-repeat-cadence/template/smoke.c new file mode 100644 index 00000000..8403fa74 --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/template/smoke.c @@ -0,0 +1,18 @@ +#include "port.h" +#include +static int32_t value; +static void apply(void * p, int32_t v) { *(int32_t *)p = v; } +int main(void) { + port_init(1); + lv_anim_t a; + lv_anim_init(&a); + lv_anim_set_var(&a, &value); + lv_anim_set_exec_cb(&a, apply); + lv_anim_set_values(&a, 0, 100); + lv_anim_set_duration(&a, 100); + lv_anim_start(&a); + lv_tick_inc(50); lv_timer_handler(); printf("%ld\n", (long)value); + lv_tick_inc(50); lv_timer_handler(); printf("%ld\n", (long)value); + port_deinit(); + return 0; +} diff --git a/tasks/runtime-lvgl-repeat-cadence/template/src/core/lv_global.h b/tasks/runtime-lvgl-repeat-cadence/template/src/core/lv_global.h new file mode 100644 index 00000000..806a5889 --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/template/src/core/lv_global.h @@ -0,0 +1,21 @@ +/* Software-only global aggregation for the included LVGL modules. + * The runtime modules and state types are provided by LVGL (see LICENCE.txt). + */ +#ifndef LV_GLOBAL_H +#define LV_GLOBAL_H +#include "../misc/lv_anim_private.h" +#include "../misc/lv_timer_private.h" +#include "../tick/lv_tick_private.h" +#include "../osal/lv_os.h" +#define ZERO_MEM_SENTINEL 0xa1b2c3d4 +/* Only module-owned storage used by this port is instantiated. */ +typedef struct lv_global_t { + uint32_t memory_zero; + uint32_t math_rand_seed; + lv_timer_state_t timer_state; + lv_anim_state_t anim_state; + lv_tick_state_t tick_state; +} lv_global_t; +extern lv_global_t lv_global; +#define LV_GLOBAL_DEFAULT() (&lv_global) +#endif diff --git a/tasks/runtime-lvgl-repeat-cadence/template/src/lv_conf_internal.h b/tasks/runtime-lvgl-repeat-cadence/template/src/lv_conf_internal.h new file mode 100644 index 00000000..5cebb73f --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/template/src/lv_conf_internal.h @@ -0,0 +1,3700 @@ +/** + * GENERATED FILE, DO NOT EDIT IT! + * @file lv_conf_internal.h + * Make sure all the defines of lv_conf.h have a default value +**/ + +#ifndef LV_CONF_INTERNAL_H +#define LV_CONF_INTERNAL_H +/* clang-format off */ + +/*Config options*/ +#define LV_OS_NONE 0 +#define LV_OS_PTHREAD 1 +#define LV_OS_FREERTOS 2 +#define LV_OS_CMSIS_RTOS2 3 +#define LV_OS_RTTHREAD 4 +#define LV_OS_WINDOWS 5 +#define LV_OS_MQX 6 +#define LV_OS_CUSTOM 255 + +#define LV_STDLIB_BUILTIN 0 +#define LV_STDLIB_CLIB 1 +#define LV_STDLIB_MICROPYTHON 2 +#define LV_STDLIB_RTTHREAD 3 +#define LV_STDLIB_CUSTOM 255 + +#define LV_DRAW_SW_ASM_NONE 0 +#define LV_DRAW_SW_ASM_NEON 1 +#define LV_DRAW_SW_ASM_HELIUM 2 +#define LV_DRAW_SW_ASM_CUSTOM 255 + +/* Handle special Kconfig options */ +#ifndef LV_KCONFIG_IGNORE + #include "lv_conf_kconfig.h" + #ifdef CONFIG_LV_CONF_SKIP + #define LV_CONF_SKIP + #endif +#endif + +/*If "lv_conf.h" is available from here try to use it later.*/ +#ifdef __has_include + #if __has_include("lv_conf.h") + #ifndef LV_CONF_INCLUDE_SIMPLE + #define LV_CONF_INCLUDE_SIMPLE + #endif + #endif +#endif + +/*If lv_conf.h is not skipped include it*/ +#if !defined(LV_CONF_SKIP) || defined(LV_CONF_PATH) + #ifdef LV_CONF_PATH /*If there is a path defined for lv_conf.h use it*/ + #define __LV_TO_STR_AUX(x) #x + #define __LV_TO_STR(x) __LV_TO_STR_AUX(x) + #include __LV_TO_STR(LV_CONF_PATH) + #undef __LV_TO_STR_AUX + #undef __LV_TO_STR + #elif defined(LV_CONF_INCLUDE_SIMPLE) /*Or simply include lv_conf.h is enabled*/ + #include "lv_conf.h" + #else + #include "../../lv_conf.h" /*Else assume lv_conf.h is next to the lvgl folder*/ + #endif + #if !defined(LV_CONF_H) && !defined(LV_CONF_SUPPRESS_DEFINE_CHECK) + /* #include will sometimes silently fail when __has_include is used */ + /* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=80753 */ + #pragma message("Possible failure to include lv_conf.h, please read the comment in this file if you get errors") + #endif +#endif + +#ifdef CONFIG_LV_COLOR_DEPTH + #define LV_KCONFIG_PRESENT +#endif + +/*---------------------------------- + * Start parsing lv_conf_template.h + -----------------------------------*/ + +/*If you need to include anything here, do it inside the `__ASSEMBLY__` guard */ +#if 0 && defined(__ASSEMBLY__) +#include "my_include.h" +#endif + +/*==================== + COLOR SETTINGS + *====================*/ + +/*Color depth: 1 (I1), 8 (L8), 16 (RGB565), 24 (RGB888), 32 (XRGB8888)*/ +#ifndef LV_COLOR_DEPTH + #ifdef CONFIG_LV_COLOR_DEPTH + #define LV_COLOR_DEPTH CONFIG_LV_COLOR_DEPTH + #else + #define LV_COLOR_DEPTH 16 + #endif +#endif + +/*========================= + STDLIB WRAPPER SETTINGS + *=========================*/ + +/* Possible values + * - LV_STDLIB_BUILTIN: LVGL's built in implementation + * - LV_STDLIB_CLIB: Standard C functions, like malloc, strlen, etc + * - LV_STDLIB_MICROPYTHON: MicroPython implementation + * - LV_STDLIB_RTTHREAD: RT-Thread implementation + * - LV_STDLIB_CUSTOM: Implement the functions externally + */ +#ifndef LV_USE_STDLIB_MALLOC + #ifdef CONFIG_LV_USE_STDLIB_MALLOC + #define LV_USE_STDLIB_MALLOC CONFIG_LV_USE_STDLIB_MALLOC + #else + #define LV_USE_STDLIB_MALLOC LV_STDLIB_BUILTIN + #endif +#endif +#ifndef LV_USE_STDLIB_STRING + #ifdef CONFIG_LV_USE_STDLIB_STRING + #define LV_USE_STDLIB_STRING CONFIG_LV_USE_STDLIB_STRING + #else + #define LV_USE_STDLIB_STRING LV_STDLIB_BUILTIN + #endif +#endif +#ifndef LV_USE_STDLIB_SPRINTF + #ifdef CONFIG_LV_USE_STDLIB_SPRINTF + #define LV_USE_STDLIB_SPRINTF CONFIG_LV_USE_STDLIB_SPRINTF + #else + #define LV_USE_STDLIB_SPRINTF LV_STDLIB_BUILTIN + #endif +#endif + +#ifndef LV_STDINT_INCLUDE + #ifdef CONFIG_LV_STDINT_INCLUDE + #define LV_STDINT_INCLUDE CONFIG_LV_STDINT_INCLUDE + #else + #define LV_STDINT_INCLUDE + #endif +#endif +#ifndef LV_STDDEF_INCLUDE + #ifdef CONFIG_LV_STDDEF_INCLUDE + #define LV_STDDEF_INCLUDE CONFIG_LV_STDDEF_INCLUDE + #else + #define LV_STDDEF_INCLUDE + #endif +#endif +#ifndef LV_STDBOOL_INCLUDE + #ifdef CONFIG_LV_STDBOOL_INCLUDE + #define LV_STDBOOL_INCLUDE CONFIG_LV_STDBOOL_INCLUDE + #else + #define LV_STDBOOL_INCLUDE + #endif +#endif +#ifndef LV_INTTYPES_INCLUDE + #ifdef CONFIG_LV_INTTYPES_INCLUDE + #define LV_INTTYPES_INCLUDE CONFIG_LV_INTTYPES_INCLUDE + #else + #define LV_INTTYPES_INCLUDE + #endif +#endif +#ifndef LV_LIMITS_INCLUDE + #ifdef CONFIG_LV_LIMITS_INCLUDE + #define LV_LIMITS_INCLUDE CONFIG_LV_LIMITS_INCLUDE + #else + #define LV_LIMITS_INCLUDE + #endif +#endif +#ifndef LV_STDARG_INCLUDE + #ifdef CONFIG_LV_STDARG_INCLUDE + #define LV_STDARG_INCLUDE CONFIG_LV_STDARG_INCLUDE + #else + #define LV_STDARG_INCLUDE + #endif +#endif + +#if LV_USE_STDLIB_MALLOC == LV_STDLIB_BUILTIN + /*Size of the memory available for `lv_malloc()` in bytes (>= 2kB)*/ + #ifndef LV_MEM_SIZE + #ifdef CONFIG_LV_MEM_SIZE + #define LV_MEM_SIZE CONFIG_LV_MEM_SIZE + #else + #define LV_MEM_SIZE (64 * 1024U) /*[bytes]*/ + #endif + #endif + + /*Size of the memory expand for `lv_malloc()` in bytes*/ + #ifndef LV_MEM_POOL_EXPAND_SIZE + #ifdef CONFIG_LV_MEM_POOL_EXPAND_SIZE + #define LV_MEM_POOL_EXPAND_SIZE CONFIG_LV_MEM_POOL_EXPAND_SIZE + #else + #define LV_MEM_POOL_EXPAND_SIZE 0 + #endif + #endif + + /*Set an address for the memory pool instead of allocating it as a normal array. Can be in external SRAM too.*/ + #ifndef LV_MEM_ADR + #ifdef CONFIG_LV_MEM_ADR + #define LV_MEM_ADR CONFIG_LV_MEM_ADR + #else + #define LV_MEM_ADR 0 /*0: unused*/ + #endif + #endif + /*Instead of an address give a memory allocator that will be called to get a memory pool for LVGL. E.g. my_malloc*/ + #if LV_MEM_ADR == 0 + #ifndef LV_MEM_POOL_INCLUDE + #ifdef CONFIG_LV_MEM_POOL_INCLUDE + #define LV_MEM_POOL_INCLUDE CONFIG_LV_MEM_POOL_INCLUDE + #else + #undef LV_MEM_POOL_INCLUDE + #endif + #endif + #ifndef LV_MEM_POOL_ALLOC + #ifdef CONFIG_LV_MEM_POOL_ALLOC + #define LV_MEM_POOL_ALLOC CONFIG_LV_MEM_POOL_ALLOC + #else + #undef LV_MEM_POOL_ALLOC + #endif + #endif + #endif +#endif /*LV_USE_STDLIB_MALLOC == LV_STDLIB_BUILTIN*/ + +/*==================== + HAL SETTINGS + *====================*/ + +/*Default display refresh, input device read and animation step period.*/ +#ifndef LV_DEF_REFR_PERIOD + #ifdef CONFIG_LV_DEF_REFR_PERIOD + #define LV_DEF_REFR_PERIOD CONFIG_LV_DEF_REFR_PERIOD + #else + #define LV_DEF_REFR_PERIOD 33 /*[ms]*/ + #endif +#endif + +/*Default Dot Per Inch. Used to initialize default sizes such as widgets sized, style paddings. + *(Not so important, you can adjust it to modify default sizes and spaces)*/ +#ifndef LV_DPI_DEF + #ifdef CONFIG_LV_DPI_DEF + #define LV_DPI_DEF CONFIG_LV_DPI_DEF + #else + #define LV_DPI_DEF 130 /*[px/inch]*/ + #endif +#endif + +/*================= + * OPERATING SYSTEM + *=================*/ +/*Select an operating system to use. Possible options: + * - LV_OS_NONE + * - LV_OS_PTHREAD + * - LV_OS_FREERTOS + * - LV_OS_CMSIS_RTOS2 + * - LV_OS_RTTHREAD + * - LV_OS_WINDOWS + * - LV_OS_MQX + * - LV_OS_CUSTOM */ +#ifndef LV_USE_OS + #ifdef CONFIG_LV_USE_OS + #define LV_USE_OS CONFIG_LV_USE_OS + #else + #define LV_USE_OS LV_OS_NONE + #endif +#endif + +#if LV_USE_OS == LV_OS_CUSTOM + #ifndef LV_OS_CUSTOM_INCLUDE + #ifdef CONFIG_LV_OS_CUSTOM_INCLUDE + #define LV_OS_CUSTOM_INCLUDE CONFIG_LV_OS_CUSTOM_INCLUDE + #else + #define LV_OS_CUSTOM_INCLUDE + #endif + #endif +#endif + +/*======================== + * RENDERING CONFIGURATION + *========================*/ + +/*Align the stride of all layers and images to this bytes*/ +#ifndef LV_DRAW_BUF_STRIDE_ALIGN + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_DRAW_BUF_STRIDE_ALIGN + #define LV_DRAW_BUF_STRIDE_ALIGN CONFIG_LV_DRAW_BUF_STRIDE_ALIGN + #else + #define LV_DRAW_BUF_STRIDE_ALIGN 0 + #endif + #else + #define LV_DRAW_BUF_STRIDE_ALIGN 1 + #endif +#endif + +/*Align the start address of draw_buf addresses to this bytes*/ +#ifndef LV_DRAW_BUF_ALIGN + #ifdef CONFIG_LV_DRAW_BUF_ALIGN + #define LV_DRAW_BUF_ALIGN CONFIG_LV_DRAW_BUF_ALIGN + #else + #define LV_DRAW_BUF_ALIGN 4 + #endif +#endif + +/*Using matrix for transformations. + *Requirements: + `LV_USE_MATRIX = 1`. + The rendering engine needs to support 3x3 matrix transformations.*/ +#ifndef LV_DRAW_TRANSFORM_USE_MATRIX + #ifdef CONFIG_LV_DRAW_TRANSFORM_USE_MATRIX + #define LV_DRAW_TRANSFORM_USE_MATRIX CONFIG_LV_DRAW_TRANSFORM_USE_MATRIX + #else + #define LV_DRAW_TRANSFORM_USE_MATRIX 0 + #endif +#endif + +/* If a widget has `style_opa < 255` (not `bg_opa`, `text_opa` etc) or not NORMAL blend mode + * it is buffered into a "simple" layer before rendering. The widget can be buffered in smaller chunks. + * "Transformed layers" (if `transform_angle/zoom` are set) use larger buffers + * and can't be drawn in chunks. */ + +/*The target buffer size for simple layer chunks.*/ +#ifndef LV_DRAW_LAYER_SIMPLE_BUF_SIZE + #ifdef CONFIG_LV_DRAW_LAYER_SIMPLE_BUF_SIZE + #define LV_DRAW_LAYER_SIMPLE_BUF_SIZE CONFIG_LV_DRAW_LAYER_SIMPLE_BUF_SIZE + #else + #define LV_DRAW_LAYER_SIMPLE_BUF_SIZE (24 * 1024) /*[bytes]*/ + #endif +#endif + +/* The stack size of the drawing thread. + * NOTE: If FreeType or ThorVG is enabled, it is recommended to set it to 32KB or more. + */ +#ifndef LV_DRAW_THREAD_STACK_SIZE + #ifdef CONFIG_LV_DRAW_THREAD_STACK_SIZE + #define LV_DRAW_THREAD_STACK_SIZE CONFIG_LV_DRAW_THREAD_STACK_SIZE + #else + #define LV_DRAW_THREAD_STACK_SIZE (8 * 1024) /*[bytes]*/ + #endif +#endif + +#ifndef LV_USE_DRAW_SW + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_DRAW_SW + #define LV_USE_DRAW_SW CONFIG_LV_USE_DRAW_SW + #else + #define LV_USE_DRAW_SW 0 + #endif + #else + #define LV_USE_DRAW_SW 1 + #endif +#endif +#if LV_USE_DRAW_SW == 1 + + /* + * Selectively disable color format support in order to reduce code size. + * NOTE: some features use certain color formats internally, e.g. + * - gradients use RGB888 + * - bitmaps with transparency may use ARGB8888 + */ + + #ifndef LV_DRAW_SW_SUPPORT_RGB565 + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_DRAW_SW_SUPPORT_RGB565 + #define LV_DRAW_SW_SUPPORT_RGB565 CONFIG_LV_DRAW_SW_SUPPORT_RGB565 + #else + #define LV_DRAW_SW_SUPPORT_RGB565 0 + #endif + #else + #define LV_DRAW_SW_SUPPORT_RGB565 1 + #endif + #endif + #ifndef LV_DRAW_SW_SUPPORT_RGB565A8 + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_DRAW_SW_SUPPORT_RGB565A8 + #define LV_DRAW_SW_SUPPORT_RGB565A8 CONFIG_LV_DRAW_SW_SUPPORT_RGB565A8 + #else + #define LV_DRAW_SW_SUPPORT_RGB565A8 0 + #endif + #else + #define LV_DRAW_SW_SUPPORT_RGB565A8 1 + #endif + #endif + #ifndef LV_DRAW_SW_SUPPORT_RGB888 + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_DRAW_SW_SUPPORT_RGB888 + #define LV_DRAW_SW_SUPPORT_RGB888 CONFIG_LV_DRAW_SW_SUPPORT_RGB888 + #else + #define LV_DRAW_SW_SUPPORT_RGB888 0 + #endif + #else + #define LV_DRAW_SW_SUPPORT_RGB888 1 + #endif + #endif + #ifndef LV_DRAW_SW_SUPPORT_XRGB8888 + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_DRAW_SW_SUPPORT_XRGB8888 + #define LV_DRAW_SW_SUPPORT_XRGB8888 CONFIG_LV_DRAW_SW_SUPPORT_XRGB8888 + #else + #define LV_DRAW_SW_SUPPORT_XRGB8888 0 + #endif + #else + #define LV_DRAW_SW_SUPPORT_XRGB8888 1 + #endif + #endif + #ifndef LV_DRAW_SW_SUPPORT_ARGB8888 + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_DRAW_SW_SUPPORT_ARGB8888 + #define LV_DRAW_SW_SUPPORT_ARGB8888 CONFIG_LV_DRAW_SW_SUPPORT_ARGB8888 + #else + #define LV_DRAW_SW_SUPPORT_ARGB8888 0 + #endif + #else + #define LV_DRAW_SW_SUPPORT_ARGB8888 1 + #endif + #endif + #ifndef LV_DRAW_SW_SUPPORT_L8 + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_DRAW_SW_SUPPORT_L8 + #define LV_DRAW_SW_SUPPORT_L8 CONFIG_LV_DRAW_SW_SUPPORT_L8 + #else + #define LV_DRAW_SW_SUPPORT_L8 0 + #endif + #else + #define LV_DRAW_SW_SUPPORT_L8 1 + #endif + #endif + #ifndef LV_DRAW_SW_SUPPORT_AL88 + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_DRAW_SW_SUPPORT_AL88 + #define LV_DRAW_SW_SUPPORT_AL88 CONFIG_LV_DRAW_SW_SUPPORT_AL88 + #else + #define LV_DRAW_SW_SUPPORT_AL88 0 + #endif + #else + #define LV_DRAW_SW_SUPPORT_AL88 1 + #endif + #endif + #ifndef LV_DRAW_SW_SUPPORT_A8 + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_DRAW_SW_SUPPORT_A8 + #define LV_DRAW_SW_SUPPORT_A8 CONFIG_LV_DRAW_SW_SUPPORT_A8 + #else + #define LV_DRAW_SW_SUPPORT_A8 0 + #endif + #else + #define LV_DRAW_SW_SUPPORT_A8 1 + #endif + #endif + #ifndef LV_DRAW_SW_SUPPORT_I1 + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_DRAW_SW_SUPPORT_I1 + #define LV_DRAW_SW_SUPPORT_I1 CONFIG_LV_DRAW_SW_SUPPORT_I1 + #else + #define LV_DRAW_SW_SUPPORT_I1 0 + #endif + #else + #define LV_DRAW_SW_SUPPORT_I1 1 + #endif + #endif + + /* Set the number of draw unit. + * > 1 requires an operating system enabled in `LV_USE_OS` + * > 1 means multiple threads will render the screen in parallel */ + #ifndef LV_DRAW_SW_DRAW_UNIT_CNT + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_DRAW_SW_DRAW_UNIT_CNT + #define LV_DRAW_SW_DRAW_UNIT_CNT CONFIG_LV_DRAW_SW_DRAW_UNIT_CNT + #else + #define LV_DRAW_SW_DRAW_UNIT_CNT 0 + #endif + #else + #define LV_DRAW_SW_DRAW_UNIT_CNT 1 + #endif + #endif + + /* Use Arm-2D to accelerate the sw render */ + #ifndef LV_USE_DRAW_ARM2D_SYNC + #ifdef CONFIG_LV_USE_DRAW_ARM2D_SYNC + #define LV_USE_DRAW_ARM2D_SYNC CONFIG_LV_USE_DRAW_ARM2D_SYNC + #else + #define LV_USE_DRAW_ARM2D_SYNC 0 + #endif + #endif + + /* Enable native helium assembly to be compiled */ + #ifndef LV_USE_NATIVE_HELIUM_ASM + #ifdef CONFIG_LV_USE_NATIVE_HELIUM_ASM + #define LV_USE_NATIVE_HELIUM_ASM CONFIG_LV_USE_NATIVE_HELIUM_ASM + #else + #define LV_USE_NATIVE_HELIUM_ASM 0 + #endif + #endif + + /* 0: use a simple renderer capable of drawing only simple rectangles with gradient, images, texts, and straight lines only + * 1: use a complex renderer capable of drawing rounded corners, shadow, skew lines, and arcs too */ + #ifndef LV_DRAW_SW_COMPLEX + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_DRAW_SW_COMPLEX + #define LV_DRAW_SW_COMPLEX CONFIG_LV_DRAW_SW_COMPLEX + #else + #define LV_DRAW_SW_COMPLEX 0 + #endif + #else + #define LV_DRAW_SW_COMPLEX 1 + #endif + #endif + + #if LV_DRAW_SW_COMPLEX == 1 + /*Allow buffering some shadow calculation. + *LV_DRAW_SW_SHADOW_CACHE_SIZE is the max. shadow size to buffer, where shadow size is `shadow_width + radius` + *Caching has LV_DRAW_SW_SHADOW_CACHE_SIZE^2 RAM cost*/ + #ifndef LV_DRAW_SW_SHADOW_CACHE_SIZE + #ifdef CONFIG_LV_DRAW_SW_SHADOW_CACHE_SIZE + #define LV_DRAW_SW_SHADOW_CACHE_SIZE CONFIG_LV_DRAW_SW_SHADOW_CACHE_SIZE + #else + #define LV_DRAW_SW_SHADOW_CACHE_SIZE 0 + #endif + #endif + + /* Set number of maximally cached circle data. + * The circumference of 1/4 circle are saved for anti-aliasing + * radius * 4 bytes are used per circle (the most often used radiuses are saved) + * 0: to disable caching */ + #ifndef LV_DRAW_SW_CIRCLE_CACHE_SIZE + #ifdef CONFIG_LV_DRAW_SW_CIRCLE_CACHE_SIZE + #define LV_DRAW_SW_CIRCLE_CACHE_SIZE CONFIG_LV_DRAW_SW_CIRCLE_CACHE_SIZE + #else + #define LV_DRAW_SW_CIRCLE_CACHE_SIZE 4 + #endif + #endif + #endif + + #ifndef LV_USE_DRAW_SW_ASM + #ifdef CONFIG_LV_USE_DRAW_SW_ASM + #define LV_USE_DRAW_SW_ASM CONFIG_LV_USE_DRAW_SW_ASM + #else + #define LV_USE_DRAW_SW_ASM LV_DRAW_SW_ASM_NONE + #endif + #endif + + #if LV_USE_DRAW_SW_ASM == LV_DRAW_SW_ASM_CUSTOM + #ifndef LV_DRAW_SW_ASM_CUSTOM_INCLUDE + #ifdef CONFIG_LV_DRAW_SW_ASM_CUSTOM_INCLUDE + #define LV_DRAW_SW_ASM_CUSTOM_INCLUDE CONFIG_LV_DRAW_SW_ASM_CUSTOM_INCLUDE + #else + #define LV_DRAW_SW_ASM_CUSTOM_INCLUDE "" + #endif + #endif + #endif + + /* Enable drawing complex gradients in software: linear at an angle, radial or conical */ + #ifndef LV_USE_DRAW_SW_COMPLEX_GRADIENTS + #ifdef CONFIG_LV_USE_DRAW_SW_COMPLEX_GRADIENTS + #define LV_USE_DRAW_SW_COMPLEX_GRADIENTS CONFIG_LV_USE_DRAW_SW_COMPLEX_GRADIENTS + #else + #define LV_USE_DRAW_SW_COMPLEX_GRADIENTS 0 + #endif + #endif +#endif + +/* Use NXP's VG-Lite GPU on iMX RTxxx platforms. */ +#ifndef LV_USE_DRAW_VGLITE + #ifdef CONFIG_LV_USE_DRAW_VGLITE + #define LV_USE_DRAW_VGLITE CONFIG_LV_USE_DRAW_VGLITE + #else + #define LV_USE_DRAW_VGLITE 0 + #endif +#endif + +#if LV_USE_DRAW_VGLITE + /* Enable blit quality degradation workaround recommended for screen's dimension > 352 pixels. */ + #ifndef LV_USE_VGLITE_BLIT_SPLIT + #ifdef CONFIG_LV_USE_VGLITE_BLIT_SPLIT + #define LV_USE_VGLITE_BLIT_SPLIT CONFIG_LV_USE_VGLITE_BLIT_SPLIT + #else + #define LV_USE_VGLITE_BLIT_SPLIT 0 + #endif + #endif + + #if LV_USE_OS + /* Use additional draw thread for VG-Lite processing.*/ + #ifndef LV_USE_VGLITE_DRAW_THREAD + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_VGLITE_DRAW_THREAD + #define LV_USE_VGLITE_DRAW_THREAD CONFIG_LV_USE_VGLITE_DRAW_THREAD + #else + #define LV_USE_VGLITE_DRAW_THREAD 0 + #endif + #else + #define LV_USE_VGLITE_DRAW_THREAD 1 + #endif + #endif + + #if LV_USE_VGLITE_DRAW_THREAD + /* Enable VGLite draw async. Queue multiple tasks and flash them once to the GPU. */ + #ifndef LV_USE_VGLITE_DRAW_ASYNC + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_VGLITE_DRAW_ASYNC + #define LV_USE_VGLITE_DRAW_ASYNC CONFIG_LV_USE_VGLITE_DRAW_ASYNC + #else + #define LV_USE_VGLITE_DRAW_ASYNC 0 + #endif + #else + #define LV_USE_VGLITE_DRAW_ASYNC 1 + #endif + #endif + #endif + #endif + + /* Enable VGLite asserts. */ + #ifndef LV_USE_VGLITE_ASSERT + #ifdef CONFIG_LV_USE_VGLITE_ASSERT + #define LV_USE_VGLITE_ASSERT CONFIG_LV_USE_VGLITE_ASSERT + #else + #define LV_USE_VGLITE_ASSERT 0 + #endif + #endif +#endif + +/* Use NXP's PXP on iMX RTxxx platforms. */ +#ifndef LV_USE_DRAW_PXP + #ifdef CONFIG_LV_USE_DRAW_PXP + #define LV_USE_DRAW_PXP CONFIG_LV_USE_DRAW_PXP + #else + #define LV_USE_DRAW_PXP 0 + #endif +#endif + +#if LV_USE_DRAW_PXP + #if LV_USE_OS + /* Use additional draw thread for PXP processing.*/ + #ifndef LV_USE_PXP_DRAW_THREAD + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_PXP_DRAW_THREAD + #define LV_USE_PXP_DRAW_THREAD CONFIG_LV_USE_PXP_DRAW_THREAD + #else + #define LV_USE_PXP_DRAW_THREAD 0 + #endif + #else + #define LV_USE_PXP_DRAW_THREAD 1 + #endif + #endif + #endif + + /* Enable PXP asserts. */ + #ifndef LV_USE_PXP_ASSERT + #ifdef CONFIG_LV_USE_PXP_ASSERT + #define LV_USE_PXP_ASSERT CONFIG_LV_USE_PXP_ASSERT + #else + #define LV_USE_PXP_ASSERT 0 + #endif + #endif +#endif + +/* Use Renesas Dave2D on RA platforms. */ +#ifndef LV_USE_DRAW_DAVE2D + #ifdef CONFIG_LV_USE_DRAW_DAVE2D + #define LV_USE_DRAW_DAVE2D CONFIG_LV_USE_DRAW_DAVE2D + #else + #define LV_USE_DRAW_DAVE2D 0 + #endif +#endif + +/* Draw using cached SDL textures*/ +#ifndef LV_USE_DRAW_SDL + #ifdef CONFIG_LV_USE_DRAW_SDL + #define LV_USE_DRAW_SDL CONFIG_LV_USE_DRAW_SDL + #else + #define LV_USE_DRAW_SDL 0 + #endif +#endif + +/* Use VG-Lite GPU. */ +#ifndef LV_USE_DRAW_VG_LITE + #ifdef CONFIG_LV_USE_DRAW_VG_LITE + #define LV_USE_DRAW_VG_LITE CONFIG_LV_USE_DRAW_VG_LITE + #else + #define LV_USE_DRAW_VG_LITE 0 + #endif +#endif + +#if LV_USE_DRAW_VG_LITE + /* Enable VG-Lite custom external 'gpu_init()' function */ + #ifndef LV_VG_LITE_USE_GPU_INIT + #ifdef CONFIG_LV_VG_LITE_USE_GPU_INIT + #define LV_VG_LITE_USE_GPU_INIT CONFIG_LV_VG_LITE_USE_GPU_INIT + #else + #define LV_VG_LITE_USE_GPU_INIT 0 + #endif + #endif + + /* Enable VG-Lite assert. */ + #ifndef LV_VG_LITE_USE_ASSERT + #ifdef CONFIG_LV_VG_LITE_USE_ASSERT + #define LV_VG_LITE_USE_ASSERT CONFIG_LV_VG_LITE_USE_ASSERT + #else + #define LV_VG_LITE_USE_ASSERT 0 + #endif + #endif + + /* VG-Lite flush commit trigger threshold. GPU will try to batch these many draw tasks. */ + #ifndef LV_VG_LITE_FLUSH_MAX_COUNT + #ifdef CONFIG_LV_VG_LITE_FLUSH_MAX_COUNT + #define LV_VG_LITE_FLUSH_MAX_COUNT CONFIG_LV_VG_LITE_FLUSH_MAX_COUNT + #else + #define LV_VG_LITE_FLUSH_MAX_COUNT 8 + #endif + #endif + + /* Enable border to simulate shadow + * NOTE: which usually improves performance, + * but does not guarantee the same rendering quality as the software. */ + #ifndef LV_VG_LITE_USE_BOX_SHADOW + #ifdef CONFIG_LV_VG_LITE_USE_BOX_SHADOW + #define LV_VG_LITE_USE_BOX_SHADOW CONFIG_LV_VG_LITE_USE_BOX_SHADOW + #else + #define LV_VG_LITE_USE_BOX_SHADOW 0 + #endif + #endif + + /* VG-Lite gradient maximum cache number. + * NOTE: The memory usage of a single gradient image is 4K bytes. + */ + #ifndef LV_VG_LITE_GRAD_CACHE_CNT + #ifdef CONFIG_LV_VG_LITE_GRAD_CACHE_CNT + #define LV_VG_LITE_GRAD_CACHE_CNT CONFIG_LV_VG_LITE_GRAD_CACHE_CNT + #else + #define LV_VG_LITE_GRAD_CACHE_CNT 32 + #endif + #endif + + /* VG-Lite stroke maximum cache number. + */ + #ifndef LV_VG_LITE_STROKE_CACHE_CNT + #ifdef CONFIG_LV_VG_LITE_STROKE_CACHE_CNT + #define LV_VG_LITE_STROKE_CACHE_CNT CONFIG_LV_VG_LITE_STROKE_CACHE_CNT + #else + #define LV_VG_LITE_STROKE_CACHE_CNT 32 + #endif + #endif + +#endif + +/*======================= + * FEATURE CONFIGURATION + *=======================*/ + +/*------------- + * Logging + *-----------*/ + +/*Enable the log module*/ +#ifndef LV_USE_LOG + #ifdef CONFIG_LV_USE_LOG + #define LV_USE_LOG CONFIG_LV_USE_LOG + #else + #define LV_USE_LOG 0 + #endif +#endif +#if LV_USE_LOG + + /*How important log should be added: + *LV_LOG_LEVEL_TRACE A lot of logs to give detailed information + *LV_LOG_LEVEL_INFO Log important events + *LV_LOG_LEVEL_WARN Log if something unwanted happened but didn't cause a problem + *LV_LOG_LEVEL_ERROR Only critical issue, when the system may fail + *LV_LOG_LEVEL_USER Only logs added by the user + *LV_LOG_LEVEL_NONE Do not log anything*/ + #ifndef LV_LOG_LEVEL + #ifdef CONFIG_LV_LOG_LEVEL + #define LV_LOG_LEVEL CONFIG_LV_LOG_LEVEL + #else + #define LV_LOG_LEVEL LV_LOG_LEVEL_WARN + #endif + #endif + + /*1: Print the log with 'printf'; + *0: User need to register a callback with `lv_log_register_print_cb()`*/ + #ifndef LV_LOG_PRINTF + #ifdef CONFIG_LV_LOG_PRINTF + #define LV_LOG_PRINTF CONFIG_LV_LOG_PRINTF + #else + #define LV_LOG_PRINTF 0 + #endif + #endif + + /*Set callback to print the logs. + *E.g `my_print`. The prototype should be `void my_print(lv_log_level_t level, const char * buf)` + *Can be overwritten by `lv_log_register_print_cb`*/ + //#define LV_LOG_PRINT_CB + + /*1: Enable print timestamp; + *0: Disable print timestamp*/ + #ifndef LV_LOG_USE_TIMESTAMP + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_LOG_USE_TIMESTAMP + #define LV_LOG_USE_TIMESTAMP CONFIG_LV_LOG_USE_TIMESTAMP + #else + #define LV_LOG_USE_TIMESTAMP 0 + #endif + #else + #define LV_LOG_USE_TIMESTAMP 1 + #endif + #endif + + /*1: Print file and line number of the log; + *0: Do not print file and line number of the log*/ + #ifndef LV_LOG_USE_FILE_LINE + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_LOG_USE_FILE_LINE + #define LV_LOG_USE_FILE_LINE CONFIG_LV_LOG_USE_FILE_LINE + #else + #define LV_LOG_USE_FILE_LINE 0 + #endif + #else + #define LV_LOG_USE_FILE_LINE 1 + #endif + #endif + + + /*Enable/disable LV_LOG_TRACE in modules that produces a huge number of logs*/ + #ifndef LV_LOG_TRACE_MEM + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_LOG_TRACE_MEM + #define LV_LOG_TRACE_MEM CONFIG_LV_LOG_TRACE_MEM + #else + #define LV_LOG_TRACE_MEM 0 + #endif + #else + #define LV_LOG_TRACE_MEM 1 + #endif + #endif + #ifndef LV_LOG_TRACE_TIMER + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_LOG_TRACE_TIMER + #define LV_LOG_TRACE_TIMER CONFIG_LV_LOG_TRACE_TIMER + #else + #define LV_LOG_TRACE_TIMER 0 + #endif + #else + #define LV_LOG_TRACE_TIMER 1 + #endif + #endif + #ifndef LV_LOG_TRACE_INDEV + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_LOG_TRACE_INDEV + #define LV_LOG_TRACE_INDEV CONFIG_LV_LOG_TRACE_INDEV + #else + #define LV_LOG_TRACE_INDEV 0 + #endif + #else + #define LV_LOG_TRACE_INDEV 1 + #endif + #endif + #ifndef LV_LOG_TRACE_DISP_REFR + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_LOG_TRACE_DISP_REFR + #define LV_LOG_TRACE_DISP_REFR CONFIG_LV_LOG_TRACE_DISP_REFR + #else + #define LV_LOG_TRACE_DISP_REFR 0 + #endif + #else + #define LV_LOG_TRACE_DISP_REFR 1 + #endif + #endif + #ifndef LV_LOG_TRACE_EVENT + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_LOG_TRACE_EVENT + #define LV_LOG_TRACE_EVENT CONFIG_LV_LOG_TRACE_EVENT + #else + #define LV_LOG_TRACE_EVENT 0 + #endif + #else + #define LV_LOG_TRACE_EVENT 1 + #endif + #endif + #ifndef LV_LOG_TRACE_OBJ_CREATE + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_LOG_TRACE_OBJ_CREATE + #define LV_LOG_TRACE_OBJ_CREATE CONFIG_LV_LOG_TRACE_OBJ_CREATE + #else + #define LV_LOG_TRACE_OBJ_CREATE 0 + #endif + #else + #define LV_LOG_TRACE_OBJ_CREATE 1 + #endif + #endif + #ifndef LV_LOG_TRACE_LAYOUT + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_LOG_TRACE_LAYOUT + #define LV_LOG_TRACE_LAYOUT CONFIG_LV_LOG_TRACE_LAYOUT + #else + #define LV_LOG_TRACE_LAYOUT 0 + #endif + #else + #define LV_LOG_TRACE_LAYOUT 1 + #endif + #endif + #ifndef LV_LOG_TRACE_ANIM + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_LOG_TRACE_ANIM + #define LV_LOG_TRACE_ANIM CONFIG_LV_LOG_TRACE_ANIM + #else + #define LV_LOG_TRACE_ANIM 0 + #endif + #else + #define LV_LOG_TRACE_ANIM 1 + #endif + #endif + #ifndef LV_LOG_TRACE_CACHE + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_LOG_TRACE_CACHE + #define LV_LOG_TRACE_CACHE CONFIG_LV_LOG_TRACE_CACHE + #else + #define LV_LOG_TRACE_CACHE 0 + #endif + #else + #define LV_LOG_TRACE_CACHE 1 + #endif + #endif + +#endif /*LV_USE_LOG*/ + +/*------------- + * Asserts + *-----------*/ + +/*Enable asserts if an operation is failed or an invalid data is found. + *If LV_USE_LOG is enabled an error message will be printed on failure*/ +#ifndef LV_USE_ASSERT_NULL + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_ASSERT_NULL + #define LV_USE_ASSERT_NULL CONFIG_LV_USE_ASSERT_NULL + #else + #define LV_USE_ASSERT_NULL 0 + #endif + #else + #define LV_USE_ASSERT_NULL 1 /*Check if the parameter is NULL. (Very fast, recommended)*/ + #endif +#endif +#ifndef LV_USE_ASSERT_MALLOC + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_ASSERT_MALLOC + #define LV_USE_ASSERT_MALLOC CONFIG_LV_USE_ASSERT_MALLOC + #else + #define LV_USE_ASSERT_MALLOC 0 + #endif + #else + #define LV_USE_ASSERT_MALLOC 1 /*Checks is the memory is successfully allocated or no. (Very fast, recommended)*/ + #endif +#endif +#ifndef LV_USE_ASSERT_STYLE + #ifdef CONFIG_LV_USE_ASSERT_STYLE + #define LV_USE_ASSERT_STYLE CONFIG_LV_USE_ASSERT_STYLE + #else + #define LV_USE_ASSERT_STYLE 0 /*Check if the styles are properly initialized. (Very fast, recommended)*/ + #endif +#endif +#ifndef LV_USE_ASSERT_MEM_INTEGRITY + #ifdef CONFIG_LV_USE_ASSERT_MEM_INTEGRITY + #define LV_USE_ASSERT_MEM_INTEGRITY CONFIG_LV_USE_ASSERT_MEM_INTEGRITY + #else + #define LV_USE_ASSERT_MEM_INTEGRITY 0 /*Check the integrity of `lv_mem` after critical operations. (Slow)*/ + #endif +#endif +#ifndef LV_USE_ASSERT_OBJ + #ifdef CONFIG_LV_USE_ASSERT_OBJ + #define LV_USE_ASSERT_OBJ CONFIG_LV_USE_ASSERT_OBJ + #else + #define LV_USE_ASSERT_OBJ 0 /*Check the object's type and existence (e.g. not deleted). (Slow)*/ + #endif +#endif + +/*Add a custom handler when assert happens e.g. to restart the MCU*/ +#ifndef LV_ASSERT_HANDLER_INCLUDE + #ifdef CONFIG_LV_ASSERT_HANDLER_INCLUDE + #define LV_ASSERT_HANDLER_INCLUDE CONFIG_LV_ASSERT_HANDLER_INCLUDE + #else + #define LV_ASSERT_HANDLER_INCLUDE + #endif +#endif +#ifndef LV_ASSERT_HANDLER + #ifdef CONFIG_LV_ASSERT_HANDLER + #define LV_ASSERT_HANDLER CONFIG_LV_ASSERT_HANDLER + #else + #define LV_ASSERT_HANDLER while(1); /*Halt by default*/ + #endif +#endif + +/*------------- + * Debug + *-----------*/ + +/*1: Draw random colored rectangles over the redrawn areas*/ +#ifndef LV_USE_REFR_DEBUG + #ifdef CONFIG_LV_USE_REFR_DEBUG + #define LV_USE_REFR_DEBUG CONFIG_LV_USE_REFR_DEBUG + #else + #define LV_USE_REFR_DEBUG 0 + #endif +#endif + +/*1: Draw a red overlay for ARGB layers and a green overlay for RGB layers*/ +#ifndef LV_USE_LAYER_DEBUG + #ifdef CONFIG_LV_USE_LAYER_DEBUG + #define LV_USE_LAYER_DEBUG CONFIG_LV_USE_LAYER_DEBUG + #else + #define LV_USE_LAYER_DEBUG 0 + #endif +#endif + +/*1: Draw overlays with different colors for each draw_unit's tasks. + *Also add the index number of the draw unit on white background. + *For layers add the index number of the draw unit on black background.*/ +#ifndef LV_USE_PARALLEL_DRAW_DEBUG + #ifdef CONFIG_LV_USE_PARALLEL_DRAW_DEBUG + #define LV_USE_PARALLEL_DRAW_DEBUG CONFIG_LV_USE_PARALLEL_DRAW_DEBUG + #else + #define LV_USE_PARALLEL_DRAW_DEBUG 0 + #endif +#endif + +/*------------- + * Others + *-----------*/ + +#ifndef LV_ENABLE_GLOBAL_CUSTOM + #ifdef CONFIG_LV_ENABLE_GLOBAL_CUSTOM + #define LV_ENABLE_GLOBAL_CUSTOM CONFIG_LV_ENABLE_GLOBAL_CUSTOM + #else + #define LV_ENABLE_GLOBAL_CUSTOM 0 + #endif +#endif +#if LV_ENABLE_GLOBAL_CUSTOM + /*Header to include for the custom 'lv_global' function"*/ + #ifndef LV_GLOBAL_CUSTOM_INCLUDE + #ifdef CONFIG_LV_GLOBAL_CUSTOM_INCLUDE + #define LV_GLOBAL_CUSTOM_INCLUDE CONFIG_LV_GLOBAL_CUSTOM_INCLUDE + #else + #define LV_GLOBAL_CUSTOM_INCLUDE + #endif + #endif +#endif + +/*Default cache size in bytes. + *Used by image decoders such as `lv_lodepng` to keep the decoded image in the memory. + *If size is not set to 0, the decoder will fail to decode when the cache is full. + *If size is 0, the cache function is not enabled and the decoded mem will be released immediately after use.*/ +#ifndef LV_CACHE_DEF_SIZE + #ifdef CONFIG_LV_CACHE_DEF_SIZE + #define LV_CACHE_DEF_SIZE CONFIG_LV_CACHE_DEF_SIZE + #else + #define LV_CACHE_DEF_SIZE 0 + #endif +#endif + +/*Default number of image header cache entries. The cache is used to store the headers of images + *The main logic is like `LV_CACHE_DEF_SIZE` but for image headers.*/ +#ifndef LV_IMAGE_HEADER_CACHE_DEF_CNT + #ifdef CONFIG_LV_IMAGE_HEADER_CACHE_DEF_CNT + #define LV_IMAGE_HEADER_CACHE_DEF_CNT CONFIG_LV_IMAGE_HEADER_CACHE_DEF_CNT + #else + #define LV_IMAGE_HEADER_CACHE_DEF_CNT 0 + #endif +#endif + +/*Number of stops allowed per gradient. Increase this to allow more stops. + *This adds (sizeof(lv_color_t) + 1) bytes per additional stop*/ +#ifndef LV_GRADIENT_MAX_STOPS + #ifdef CONFIG_LV_GRADIENT_MAX_STOPS + #define LV_GRADIENT_MAX_STOPS CONFIG_LV_GRADIENT_MAX_STOPS + #else + #define LV_GRADIENT_MAX_STOPS 2 + #endif +#endif + +/* Adjust color mix functions rounding. GPUs might calculate color mix (blending) differently. + * 0: round down, 64: round up from x.75, 128: round up from half, 192: round up from x.25, 254: round up */ +#ifndef LV_COLOR_MIX_ROUND_OFS + #ifdef CONFIG_LV_COLOR_MIX_ROUND_OFS + #define LV_COLOR_MIX_ROUND_OFS CONFIG_LV_COLOR_MIX_ROUND_OFS + #else + #define LV_COLOR_MIX_ROUND_OFS 0 + #endif +#endif + +/* Add 2 x 32 bit variables to each lv_obj_t to speed up getting style properties */ +#ifndef LV_OBJ_STYLE_CACHE + #ifdef CONFIG_LV_OBJ_STYLE_CACHE + #define LV_OBJ_STYLE_CACHE CONFIG_LV_OBJ_STYLE_CACHE + #else + #define LV_OBJ_STYLE_CACHE 0 + #endif +#endif + +/* Add `id` field to `lv_obj_t` */ +#ifndef LV_USE_OBJ_ID + #ifdef CONFIG_LV_USE_OBJ_ID + #define LV_USE_OBJ_ID CONFIG_LV_USE_OBJ_ID + #else + #define LV_USE_OBJ_ID 0 + #endif +#endif + +/* Automatically assign an ID when obj is created */ +#ifndef LV_OBJ_ID_AUTO_ASSIGN + #ifdef CONFIG_LV_OBJ_ID_AUTO_ASSIGN + #define LV_OBJ_ID_AUTO_ASSIGN CONFIG_LV_OBJ_ID_AUTO_ASSIGN + #else + #define LV_OBJ_ID_AUTO_ASSIGN LV_USE_OBJ_ID + #endif +#endif + +/*Use the builtin obj ID handler functions: +* - lv_obj_assign_id: Called when a widget is created. Use a separate counter for each widget class as an ID. +* - lv_obj_id_compare: Compare the ID to decide if it matches with a requested value. +* - lv_obj_stringify_id: Return e.g. "button3" +* - lv_obj_free_id: Does nothing, as there is no memory allocation for the ID. +* When disabled these functions needs to be implemented by the user.*/ +#ifndef LV_USE_OBJ_ID_BUILTIN + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_OBJ_ID_BUILTIN + #define LV_USE_OBJ_ID_BUILTIN CONFIG_LV_USE_OBJ_ID_BUILTIN + #else + #define LV_USE_OBJ_ID_BUILTIN 0 + #endif + #else + #define LV_USE_OBJ_ID_BUILTIN 1 + #endif +#endif + +/*Use obj property set/get API*/ +#ifndef LV_USE_OBJ_PROPERTY + #ifdef CONFIG_LV_USE_OBJ_PROPERTY + #define LV_USE_OBJ_PROPERTY CONFIG_LV_USE_OBJ_PROPERTY + #else + #define LV_USE_OBJ_PROPERTY 0 + #endif +#endif + +/*Enable property name support*/ +#ifndef LV_USE_OBJ_PROPERTY_NAME + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_OBJ_PROPERTY_NAME + #define LV_USE_OBJ_PROPERTY_NAME CONFIG_LV_USE_OBJ_PROPERTY_NAME + #else + #define LV_USE_OBJ_PROPERTY_NAME 0 + #endif + #else + #define LV_USE_OBJ_PROPERTY_NAME 1 + #endif +#endif + +/* VG-Lite Simulator */ +/*Requires: LV_USE_THORVG_INTERNAL or LV_USE_THORVG_EXTERNAL */ +#ifndef LV_USE_VG_LITE_THORVG + #ifdef CONFIG_LV_USE_VG_LITE_THORVG + #define LV_USE_VG_LITE_THORVG CONFIG_LV_USE_VG_LITE_THORVG + #else + #define LV_USE_VG_LITE_THORVG 0 + #endif +#endif + +#if LV_USE_VG_LITE_THORVG + + /*Enable LVGL's blend mode support*/ + #ifndef LV_VG_LITE_THORVG_LVGL_BLEND_SUPPORT + #ifdef CONFIG_LV_VG_LITE_THORVG_LVGL_BLEND_SUPPORT + #define LV_VG_LITE_THORVG_LVGL_BLEND_SUPPORT CONFIG_LV_VG_LITE_THORVG_LVGL_BLEND_SUPPORT + #else + #define LV_VG_LITE_THORVG_LVGL_BLEND_SUPPORT 0 + #endif + #endif + + /*Enable YUV color format support*/ + #ifndef LV_VG_LITE_THORVG_YUV_SUPPORT + #ifdef CONFIG_LV_VG_LITE_THORVG_YUV_SUPPORT + #define LV_VG_LITE_THORVG_YUV_SUPPORT CONFIG_LV_VG_LITE_THORVG_YUV_SUPPORT + #else + #define LV_VG_LITE_THORVG_YUV_SUPPORT 0 + #endif + #endif + + /*Enable Linear gradient extension support*/ + #ifndef LV_VG_LITE_THORVG_LINEAR_GRADIENT_EXT_SUPPORT + #ifdef CONFIG_LV_VG_LITE_THORVG_LINEAR_GRADIENT_EXT_SUPPORT + #define LV_VG_LITE_THORVG_LINEAR_GRADIENT_EXT_SUPPORT CONFIG_LV_VG_LITE_THORVG_LINEAR_GRADIENT_EXT_SUPPORT + #else + #define LV_VG_LITE_THORVG_LINEAR_GRADIENT_EXT_SUPPORT 0 + #endif + #endif + + /*Enable 16 pixels alignment*/ + #ifndef LV_VG_LITE_THORVG_16PIXELS_ALIGN + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_VG_LITE_THORVG_16PIXELS_ALIGN + #define LV_VG_LITE_THORVG_16PIXELS_ALIGN CONFIG_LV_VG_LITE_THORVG_16PIXELS_ALIGN + #else + #define LV_VG_LITE_THORVG_16PIXELS_ALIGN 0 + #endif + #else + #define LV_VG_LITE_THORVG_16PIXELS_ALIGN 1 + #endif + #endif + + /*Buffer address alignment*/ + #ifndef LV_VG_LITE_THORVG_BUF_ADDR_ALIGN + #ifdef CONFIG_LV_VG_LITE_THORVG_BUF_ADDR_ALIGN + #define LV_VG_LITE_THORVG_BUF_ADDR_ALIGN CONFIG_LV_VG_LITE_THORVG_BUF_ADDR_ALIGN + #else + #define LV_VG_LITE_THORVG_BUF_ADDR_ALIGN 64 + #endif + #endif + + /*Enable multi-thread render*/ + #ifndef LV_VG_LITE_THORVG_THREAD_RENDER + #ifdef CONFIG_LV_VG_LITE_THORVG_THREAD_RENDER + #define LV_VG_LITE_THORVG_THREAD_RENDER CONFIG_LV_VG_LITE_THORVG_THREAD_RENDER + #else + #define LV_VG_LITE_THORVG_THREAD_RENDER 0 + #endif + #endif + +#endif + +/*===================== + * COMPILER SETTINGS + *====================*/ + +/*For big endian systems set to 1*/ +#ifndef LV_BIG_ENDIAN_SYSTEM + #ifdef CONFIG_LV_BIG_ENDIAN_SYSTEM + #define LV_BIG_ENDIAN_SYSTEM CONFIG_LV_BIG_ENDIAN_SYSTEM + #else + #define LV_BIG_ENDIAN_SYSTEM 0 + #endif +#endif + +/*Define a custom attribute to `lv_tick_inc` function*/ +#ifndef LV_ATTRIBUTE_TICK_INC + #ifdef CONFIG_LV_ATTRIBUTE_TICK_INC + #define LV_ATTRIBUTE_TICK_INC CONFIG_LV_ATTRIBUTE_TICK_INC + #else + #define LV_ATTRIBUTE_TICK_INC + #endif +#endif + +/*Define a custom attribute to `lv_timer_handler` function*/ +#ifndef LV_ATTRIBUTE_TIMER_HANDLER + #ifdef CONFIG_LV_ATTRIBUTE_TIMER_HANDLER + #define LV_ATTRIBUTE_TIMER_HANDLER CONFIG_LV_ATTRIBUTE_TIMER_HANDLER + #else + #define LV_ATTRIBUTE_TIMER_HANDLER + #endif +#endif + +/*Define a custom attribute to `lv_display_flush_ready` function*/ +#ifndef LV_ATTRIBUTE_FLUSH_READY + #ifdef CONFIG_LV_ATTRIBUTE_FLUSH_READY + #define LV_ATTRIBUTE_FLUSH_READY CONFIG_LV_ATTRIBUTE_FLUSH_READY + #else + #define LV_ATTRIBUTE_FLUSH_READY + #endif +#endif + +/*Required alignment size for buffers*/ +#ifndef LV_ATTRIBUTE_MEM_ALIGN_SIZE + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_ATTRIBUTE_MEM_ALIGN_SIZE + #define LV_ATTRIBUTE_MEM_ALIGN_SIZE CONFIG_LV_ATTRIBUTE_MEM_ALIGN_SIZE + #else + #define LV_ATTRIBUTE_MEM_ALIGN_SIZE 0 + #endif + #else + #define LV_ATTRIBUTE_MEM_ALIGN_SIZE 1 + #endif +#endif + +/*Will be added where memories needs to be aligned (with -Os data might not be aligned to boundary by default). + * E.g. __attribute__((aligned(4)))*/ +#ifndef LV_ATTRIBUTE_MEM_ALIGN + #ifdef CONFIG_LV_ATTRIBUTE_MEM_ALIGN + #define LV_ATTRIBUTE_MEM_ALIGN CONFIG_LV_ATTRIBUTE_MEM_ALIGN + #else + #define LV_ATTRIBUTE_MEM_ALIGN + #endif +#endif + +/*Attribute to mark large constant arrays for example font's bitmaps*/ +#ifndef LV_ATTRIBUTE_LARGE_CONST + #ifdef CONFIG_LV_ATTRIBUTE_LARGE_CONST + #define LV_ATTRIBUTE_LARGE_CONST CONFIG_LV_ATTRIBUTE_LARGE_CONST + #else + #define LV_ATTRIBUTE_LARGE_CONST + #endif +#endif + +/*Compiler prefix for a big array declaration in RAM*/ +#ifndef LV_ATTRIBUTE_LARGE_RAM_ARRAY + #ifdef CONFIG_LV_ATTRIBUTE_LARGE_RAM_ARRAY + #define LV_ATTRIBUTE_LARGE_RAM_ARRAY CONFIG_LV_ATTRIBUTE_LARGE_RAM_ARRAY + #else + #define LV_ATTRIBUTE_LARGE_RAM_ARRAY + #endif +#endif + +/*Place performance critical functions into a faster memory (e.g RAM)*/ +#ifndef LV_ATTRIBUTE_FAST_MEM + #ifdef CONFIG_LV_ATTRIBUTE_FAST_MEM + #define LV_ATTRIBUTE_FAST_MEM CONFIG_LV_ATTRIBUTE_FAST_MEM + #else + #define LV_ATTRIBUTE_FAST_MEM + #endif +#endif + +/*Export integer constant to binding. This macro is used with constants in the form of LV_ that + *should also appear on LVGL binding API such as MicroPython.*/ +#ifndef LV_EXPORT_CONST_INT + #ifdef CONFIG_LV_EXPORT_CONST_INT + #define LV_EXPORT_CONST_INT CONFIG_LV_EXPORT_CONST_INT + #else + #define LV_EXPORT_CONST_INT(int_value) struct _silence_gcc_warning /*The default value just prevents GCC warning*/ + #endif +#endif + +/*Prefix all global extern data with this*/ +#ifndef LV_ATTRIBUTE_EXTERN_DATA + #ifdef CONFIG_LV_ATTRIBUTE_EXTERN_DATA + #define LV_ATTRIBUTE_EXTERN_DATA CONFIG_LV_ATTRIBUTE_EXTERN_DATA + #else + #define LV_ATTRIBUTE_EXTERN_DATA + #endif +#endif + +/* Use `float` as `lv_value_precise_t` */ +#ifndef LV_USE_FLOAT + #ifdef CONFIG_LV_USE_FLOAT + #define LV_USE_FLOAT CONFIG_LV_USE_FLOAT + #else + #define LV_USE_FLOAT 0 + #endif +#endif + +/*Enable matrix support + *Requires `LV_USE_FLOAT = 1`*/ +#ifndef LV_USE_MATRIX + #ifdef CONFIG_LV_USE_MATRIX + #define LV_USE_MATRIX CONFIG_LV_USE_MATRIX + #else + #define LV_USE_MATRIX 0 + #endif +#endif + +/*Include `lvgl_private.h` in `lvgl.h` to access internal data and functions by default*/ +#ifndef LV_USE_PRIVATE_API + #ifdef CONFIG_LV_USE_PRIVATE_API + #define LV_USE_PRIVATE_API CONFIG_LV_USE_PRIVATE_API + #else + #define LV_USE_PRIVATE_API 0 + #endif +#endif + +/*================== + * FONT USAGE + *===================*/ + +/*Montserrat fonts with ASCII range and some symbols using bpp = 4 + *https://fonts.google.com/specimen/Montserrat*/ +#ifndef LV_FONT_MONTSERRAT_8 + #ifdef CONFIG_LV_FONT_MONTSERRAT_8 + #define LV_FONT_MONTSERRAT_8 CONFIG_LV_FONT_MONTSERRAT_8 + #else + #define LV_FONT_MONTSERRAT_8 0 + #endif +#endif +#ifndef LV_FONT_MONTSERRAT_10 + #ifdef CONFIG_LV_FONT_MONTSERRAT_10 + #define LV_FONT_MONTSERRAT_10 CONFIG_LV_FONT_MONTSERRAT_10 + #else + #define LV_FONT_MONTSERRAT_10 0 + #endif +#endif +#ifndef LV_FONT_MONTSERRAT_12 + #ifdef CONFIG_LV_FONT_MONTSERRAT_12 + #define LV_FONT_MONTSERRAT_12 CONFIG_LV_FONT_MONTSERRAT_12 + #else + #define LV_FONT_MONTSERRAT_12 0 + #endif +#endif +#ifndef LV_FONT_MONTSERRAT_14 + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_FONT_MONTSERRAT_14 + #define LV_FONT_MONTSERRAT_14 CONFIG_LV_FONT_MONTSERRAT_14 + #else + #define LV_FONT_MONTSERRAT_14 0 + #endif + #else + #define LV_FONT_MONTSERRAT_14 1 + #endif +#endif +#ifndef LV_FONT_MONTSERRAT_16 + #ifdef CONFIG_LV_FONT_MONTSERRAT_16 + #define LV_FONT_MONTSERRAT_16 CONFIG_LV_FONT_MONTSERRAT_16 + #else + #define LV_FONT_MONTSERRAT_16 0 + #endif +#endif +#ifndef LV_FONT_MONTSERRAT_18 + #ifdef CONFIG_LV_FONT_MONTSERRAT_18 + #define LV_FONT_MONTSERRAT_18 CONFIG_LV_FONT_MONTSERRAT_18 + #else + #define LV_FONT_MONTSERRAT_18 0 + #endif +#endif +#ifndef LV_FONT_MONTSERRAT_20 + #ifdef CONFIG_LV_FONT_MONTSERRAT_20 + #define LV_FONT_MONTSERRAT_20 CONFIG_LV_FONT_MONTSERRAT_20 + #else + #define LV_FONT_MONTSERRAT_20 0 + #endif +#endif +#ifndef LV_FONT_MONTSERRAT_22 + #ifdef CONFIG_LV_FONT_MONTSERRAT_22 + #define LV_FONT_MONTSERRAT_22 CONFIG_LV_FONT_MONTSERRAT_22 + #else + #define LV_FONT_MONTSERRAT_22 0 + #endif +#endif +#ifndef LV_FONT_MONTSERRAT_24 + #ifdef CONFIG_LV_FONT_MONTSERRAT_24 + #define LV_FONT_MONTSERRAT_24 CONFIG_LV_FONT_MONTSERRAT_24 + #else + #define LV_FONT_MONTSERRAT_24 0 + #endif +#endif +#ifndef LV_FONT_MONTSERRAT_26 + #ifdef CONFIG_LV_FONT_MONTSERRAT_26 + #define LV_FONT_MONTSERRAT_26 CONFIG_LV_FONT_MONTSERRAT_26 + #else + #define LV_FONT_MONTSERRAT_26 0 + #endif +#endif +#ifndef LV_FONT_MONTSERRAT_28 + #ifdef CONFIG_LV_FONT_MONTSERRAT_28 + #define LV_FONT_MONTSERRAT_28 CONFIG_LV_FONT_MONTSERRAT_28 + #else + #define LV_FONT_MONTSERRAT_28 0 + #endif +#endif +#ifndef LV_FONT_MONTSERRAT_30 + #ifdef CONFIG_LV_FONT_MONTSERRAT_30 + #define LV_FONT_MONTSERRAT_30 CONFIG_LV_FONT_MONTSERRAT_30 + #else + #define LV_FONT_MONTSERRAT_30 0 + #endif +#endif +#ifndef LV_FONT_MONTSERRAT_32 + #ifdef CONFIG_LV_FONT_MONTSERRAT_32 + #define LV_FONT_MONTSERRAT_32 CONFIG_LV_FONT_MONTSERRAT_32 + #else + #define LV_FONT_MONTSERRAT_32 0 + #endif +#endif +#ifndef LV_FONT_MONTSERRAT_34 + #ifdef CONFIG_LV_FONT_MONTSERRAT_34 + #define LV_FONT_MONTSERRAT_34 CONFIG_LV_FONT_MONTSERRAT_34 + #else + #define LV_FONT_MONTSERRAT_34 0 + #endif +#endif +#ifndef LV_FONT_MONTSERRAT_36 + #ifdef CONFIG_LV_FONT_MONTSERRAT_36 + #define LV_FONT_MONTSERRAT_36 CONFIG_LV_FONT_MONTSERRAT_36 + #else + #define LV_FONT_MONTSERRAT_36 0 + #endif +#endif +#ifndef LV_FONT_MONTSERRAT_38 + #ifdef CONFIG_LV_FONT_MONTSERRAT_38 + #define LV_FONT_MONTSERRAT_38 CONFIG_LV_FONT_MONTSERRAT_38 + #else + #define LV_FONT_MONTSERRAT_38 0 + #endif +#endif +#ifndef LV_FONT_MONTSERRAT_40 + #ifdef CONFIG_LV_FONT_MONTSERRAT_40 + #define LV_FONT_MONTSERRAT_40 CONFIG_LV_FONT_MONTSERRAT_40 + #else + #define LV_FONT_MONTSERRAT_40 0 + #endif +#endif +#ifndef LV_FONT_MONTSERRAT_42 + #ifdef CONFIG_LV_FONT_MONTSERRAT_42 + #define LV_FONT_MONTSERRAT_42 CONFIG_LV_FONT_MONTSERRAT_42 + #else + #define LV_FONT_MONTSERRAT_42 0 + #endif +#endif +#ifndef LV_FONT_MONTSERRAT_44 + #ifdef CONFIG_LV_FONT_MONTSERRAT_44 + #define LV_FONT_MONTSERRAT_44 CONFIG_LV_FONT_MONTSERRAT_44 + #else + #define LV_FONT_MONTSERRAT_44 0 + #endif +#endif +#ifndef LV_FONT_MONTSERRAT_46 + #ifdef CONFIG_LV_FONT_MONTSERRAT_46 + #define LV_FONT_MONTSERRAT_46 CONFIG_LV_FONT_MONTSERRAT_46 + #else + #define LV_FONT_MONTSERRAT_46 0 + #endif +#endif +#ifndef LV_FONT_MONTSERRAT_48 + #ifdef CONFIG_LV_FONT_MONTSERRAT_48 + #define LV_FONT_MONTSERRAT_48 CONFIG_LV_FONT_MONTSERRAT_48 + #else + #define LV_FONT_MONTSERRAT_48 0 + #endif +#endif + +/*Demonstrate special features*/ +#ifndef LV_FONT_MONTSERRAT_28_COMPRESSED + #ifdef CONFIG_LV_FONT_MONTSERRAT_28_COMPRESSED + #define LV_FONT_MONTSERRAT_28_COMPRESSED CONFIG_LV_FONT_MONTSERRAT_28_COMPRESSED + #else + #define LV_FONT_MONTSERRAT_28_COMPRESSED 0 /*bpp = 3*/ + #endif +#endif +#ifndef LV_FONT_DEJAVU_16_PERSIAN_HEBREW + #ifdef CONFIG_LV_FONT_DEJAVU_16_PERSIAN_HEBREW + #define LV_FONT_DEJAVU_16_PERSIAN_HEBREW CONFIG_LV_FONT_DEJAVU_16_PERSIAN_HEBREW + #else + #define LV_FONT_DEJAVU_16_PERSIAN_HEBREW 0 /*Hebrew, Arabic, Persian letters and all their forms*/ + #endif +#endif +#ifndef LV_FONT_SIMSUN_14_CJK + #ifdef CONFIG_LV_FONT_SIMSUN_14_CJK + #define LV_FONT_SIMSUN_14_CJK CONFIG_LV_FONT_SIMSUN_14_CJK + #else + #define LV_FONT_SIMSUN_14_CJK 0 /*1000 most common CJK radicals*/ + #endif +#endif +#ifndef LV_FONT_SIMSUN_16_CJK + #ifdef CONFIG_LV_FONT_SIMSUN_16_CJK + #define LV_FONT_SIMSUN_16_CJK CONFIG_LV_FONT_SIMSUN_16_CJK + #else + #define LV_FONT_SIMSUN_16_CJK 0 /*1000 most common CJK radicals*/ + #endif +#endif + +/*Pixel perfect monospace fonts*/ +#ifndef LV_FONT_UNSCII_8 + #ifdef CONFIG_LV_FONT_UNSCII_8 + #define LV_FONT_UNSCII_8 CONFIG_LV_FONT_UNSCII_8 + #else + #define LV_FONT_UNSCII_8 0 + #endif +#endif +#ifndef LV_FONT_UNSCII_16 + #ifdef CONFIG_LV_FONT_UNSCII_16 + #define LV_FONT_UNSCII_16 CONFIG_LV_FONT_UNSCII_16 + #else + #define LV_FONT_UNSCII_16 0 + #endif +#endif + +/*Optionally declare custom fonts here. + *You can use these fonts as default font too and they will be available globally. + *E.g. #define LV_FONT_CUSTOM_DECLARE LV_FONT_DECLARE(my_font_1) LV_FONT_DECLARE(my_font_2)*/ +#ifndef LV_FONT_CUSTOM_DECLARE + #ifdef CONFIG_LV_FONT_CUSTOM_DECLARE + #define LV_FONT_CUSTOM_DECLARE CONFIG_LV_FONT_CUSTOM_DECLARE + #else + #define LV_FONT_CUSTOM_DECLARE + #endif +#endif + +/*Always set a default font*/ +#ifndef LV_FONT_DEFAULT + #ifdef CONFIG_LV_FONT_DEFAULT + #define LV_FONT_DEFAULT CONFIG_LV_FONT_DEFAULT + #else + #define LV_FONT_DEFAULT &lv_font_montserrat_14 + #endif +#endif + +/*Enable handling large font and/or fonts with a lot of characters. + *The limit depends on the font size, font face and bpp. + *Compiler error will be triggered if a font needs it.*/ +#ifndef LV_FONT_FMT_TXT_LARGE + #ifdef CONFIG_LV_FONT_FMT_TXT_LARGE + #define LV_FONT_FMT_TXT_LARGE CONFIG_LV_FONT_FMT_TXT_LARGE + #else + #define LV_FONT_FMT_TXT_LARGE 0 + #endif +#endif + +/*Enables/disables support for compressed fonts.*/ +#ifndef LV_USE_FONT_COMPRESSED + #ifdef CONFIG_LV_USE_FONT_COMPRESSED + #define LV_USE_FONT_COMPRESSED CONFIG_LV_USE_FONT_COMPRESSED + #else + #define LV_USE_FONT_COMPRESSED 0 + #endif +#endif + +/*Enable drawing placeholders when glyph dsc is not found*/ +#ifndef LV_USE_FONT_PLACEHOLDER + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_FONT_PLACEHOLDER + #define LV_USE_FONT_PLACEHOLDER CONFIG_LV_USE_FONT_PLACEHOLDER + #else + #define LV_USE_FONT_PLACEHOLDER 0 + #endif + #else + #define LV_USE_FONT_PLACEHOLDER 1 + #endif +#endif + +/*================= + * TEXT SETTINGS + *=================*/ + +/** + * Select a character encoding for strings. + * Your IDE or editor should have the same character encoding + * - LV_TXT_ENC_UTF8 + * - LV_TXT_ENC_ASCII + */ +#ifndef LV_TXT_ENC + #ifdef CONFIG_LV_TXT_ENC + #define LV_TXT_ENC CONFIG_LV_TXT_ENC + #else + #define LV_TXT_ENC LV_TXT_ENC_UTF8 + #endif +#endif + +/*Can break (wrap) texts on these chars*/ +#ifndef LV_TXT_BREAK_CHARS + #ifdef CONFIG_LV_TXT_BREAK_CHARS + #define LV_TXT_BREAK_CHARS CONFIG_LV_TXT_BREAK_CHARS + #else + #define LV_TXT_BREAK_CHARS " ,.;:-_)]}" + #endif +#endif + +/*If a word is at least this long, will break wherever "prettiest" + *To disable, set to a value <= 0*/ +#ifndef LV_TXT_LINE_BREAK_LONG_LEN + #ifdef CONFIG_LV_TXT_LINE_BREAK_LONG_LEN + #define LV_TXT_LINE_BREAK_LONG_LEN CONFIG_LV_TXT_LINE_BREAK_LONG_LEN + #else + #define LV_TXT_LINE_BREAK_LONG_LEN 0 + #endif +#endif + +/*Minimum number of characters in a long word to put on a line before a break. + *Depends on LV_TXT_LINE_BREAK_LONG_LEN.*/ +#ifndef LV_TXT_LINE_BREAK_LONG_PRE_MIN_LEN + #ifdef CONFIG_LV_TXT_LINE_BREAK_LONG_PRE_MIN_LEN + #define LV_TXT_LINE_BREAK_LONG_PRE_MIN_LEN CONFIG_LV_TXT_LINE_BREAK_LONG_PRE_MIN_LEN + #else + #define LV_TXT_LINE_BREAK_LONG_PRE_MIN_LEN 3 + #endif +#endif + +/*Minimum number of characters in a long word to put on a line after a break. + *Depends on LV_TXT_LINE_BREAK_LONG_LEN.*/ +#ifndef LV_TXT_LINE_BREAK_LONG_POST_MIN_LEN + #ifdef CONFIG_LV_TXT_LINE_BREAK_LONG_POST_MIN_LEN + #define LV_TXT_LINE_BREAK_LONG_POST_MIN_LEN CONFIG_LV_TXT_LINE_BREAK_LONG_POST_MIN_LEN + #else + #define LV_TXT_LINE_BREAK_LONG_POST_MIN_LEN 3 + #endif +#endif + +/*Support bidirectional texts. Allows mixing Left-to-Right and Right-to-Left texts. + *The direction will be processed according to the Unicode Bidirectional Algorithm: + *https://www.w3.org/International/articles/inline-bidi-markup/uba-basics*/ +#ifndef LV_USE_BIDI + #ifdef CONFIG_LV_USE_BIDI + #define LV_USE_BIDI CONFIG_LV_USE_BIDI + #else + #define LV_USE_BIDI 0 + #endif +#endif +#if LV_USE_BIDI + /*Set the default direction. Supported values: + *`LV_BASE_DIR_LTR` Left-to-Right + *`LV_BASE_DIR_RTL` Right-to-Left + *`LV_BASE_DIR_AUTO` detect texts base direction*/ + #ifndef LV_BIDI_BASE_DIR_DEF + #ifdef CONFIG_LV_BIDI_BASE_DIR_DEF + #define LV_BIDI_BASE_DIR_DEF CONFIG_LV_BIDI_BASE_DIR_DEF + #else + #define LV_BIDI_BASE_DIR_DEF LV_BASE_DIR_AUTO + #endif + #endif +#endif + +/*Enable Arabic/Persian processing + *In these languages characters should be replaced with another form based on their position in the text*/ +#ifndef LV_USE_ARABIC_PERSIAN_CHARS + #ifdef CONFIG_LV_USE_ARABIC_PERSIAN_CHARS + #define LV_USE_ARABIC_PERSIAN_CHARS CONFIG_LV_USE_ARABIC_PERSIAN_CHARS + #else + #define LV_USE_ARABIC_PERSIAN_CHARS 0 + #endif +#endif + +/*================== + * WIDGETS + *================*/ + +/*Documentation of the widgets: https://docs.lvgl.io/latest/en/html/widgets/index.html*/ + +#ifndef LV_WIDGETS_HAS_DEFAULT_VALUE + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_WIDGETS_HAS_DEFAULT_VALUE + #define LV_WIDGETS_HAS_DEFAULT_VALUE CONFIG_LV_WIDGETS_HAS_DEFAULT_VALUE + #else + #define LV_WIDGETS_HAS_DEFAULT_VALUE 0 + #endif + #else + #define LV_WIDGETS_HAS_DEFAULT_VALUE 1 + #endif +#endif + +#ifndef LV_USE_ANIMIMG + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_ANIMIMG + #define LV_USE_ANIMIMG CONFIG_LV_USE_ANIMIMG + #else + #define LV_USE_ANIMIMG 0 + #endif + #else + #define LV_USE_ANIMIMG 1 + #endif +#endif + +#ifndef LV_USE_ARC + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_ARC + #define LV_USE_ARC CONFIG_LV_USE_ARC + #else + #define LV_USE_ARC 0 + #endif + #else + #define LV_USE_ARC 1 + #endif +#endif + +#ifndef LV_USE_BAR + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_BAR + #define LV_USE_BAR CONFIG_LV_USE_BAR + #else + #define LV_USE_BAR 0 + #endif + #else + #define LV_USE_BAR 1 + #endif +#endif + +#ifndef LV_USE_BUTTON + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_BUTTON + #define LV_USE_BUTTON CONFIG_LV_USE_BUTTON + #else + #define LV_USE_BUTTON 0 + #endif + #else + #define LV_USE_BUTTON 1 + #endif +#endif + +#ifndef LV_USE_BUTTONMATRIX + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_BUTTONMATRIX + #define LV_USE_BUTTONMATRIX CONFIG_LV_USE_BUTTONMATRIX + #else + #define LV_USE_BUTTONMATRIX 0 + #endif + #else + #define LV_USE_BUTTONMATRIX 1 + #endif +#endif + +#ifndef LV_USE_CALENDAR + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_CALENDAR + #define LV_USE_CALENDAR CONFIG_LV_USE_CALENDAR + #else + #define LV_USE_CALENDAR 0 + #endif + #else + #define LV_USE_CALENDAR 1 + #endif +#endif +#if LV_USE_CALENDAR + #ifndef LV_CALENDAR_WEEK_STARTS_MONDAY + #ifdef CONFIG_LV_CALENDAR_WEEK_STARTS_MONDAY + #define LV_CALENDAR_WEEK_STARTS_MONDAY CONFIG_LV_CALENDAR_WEEK_STARTS_MONDAY + #else + #define LV_CALENDAR_WEEK_STARTS_MONDAY 0 + #endif + #endif + #if LV_CALENDAR_WEEK_STARTS_MONDAY + #ifndef LV_CALENDAR_DEFAULT_DAY_NAMES + #ifdef CONFIG_LV_CALENDAR_DEFAULT_DAY_NAMES + #define LV_CALENDAR_DEFAULT_DAY_NAMES CONFIG_LV_CALENDAR_DEFAULT_DAY_NAMES + #else + #define LV_CALENDAR_DEFAULT_DAY_NAMES {"Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"} + #endif + #endif + #else + #ifndef LV_CALENDAR_DEFAULT_DAY_NAMES + #ifdef CONFIG_LV_CALENDAR_DEFAULT_DAY_NAMES + #define LV_CALENDAR_DEFAULT_DAY_NAMES CONFIG_LV_CALENDAR_DEFAULT_DAY_NAMES + #else + #define LV_CALENDAR_DEFAULT_DAY_NAMES {"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"} + #endif + #endif + #endif + + #ifndef LV_CALENDAR_DEFAULT_MONTH_NAMES + #ifdef CONFIG_LV_CALENDAR_DEFAULT_MONTH_NAMES + #define LV_CALENDAR_DEFAULT_MONTH_NAMES CONFIG_LV_CALENDAR_DEFAULT_MONTH_NAMES + #else + #define LV_CALENDAR_DEFAULT_MONTH_NAMES {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"} + #endif + #endif + #ifndef LV_USE_CALENDAR_HEADER_ARROW + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_CALENDAR_HEADER_ARROW + #define LV_USE_CALENDAR_HEADER_ARROW CONFIG_LV_USE_CALENDAR_HEADER_ARROW + #else + #define LV_USE_CALENDAR_HEADER_ARROW 0 + #endif + #else + #define LV_USE_CALENDAR_HEADER_ARROW 1 + #endif + #endif + #ifndef LV_USE_CALENDAR_HEADER_DROPDOWN + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_CALENDAR_HEADER_DROPDOWN + #define LV_USE_CALENDAR_HEADER_DROPDOWN CONFIG_LV_USE_CALENDAR_HEADER_DROPDOWN + #else + #define LV_USE_CALENDAR_HEADER_DROPDOWN 0 + #endif + #else + #define LV_USE_CALENDAR_HEADER_DROPDOWN 1 + #endif + #endif + #ifndef LV_USE_CALENDAR_CHINESE + #ifdef CONFIG_LV_USE_CALENDAR_CHINESE + #define LV_USE_CALENDAR_CHINESE CONFIG_LV_USE_CALENDAR_CHINESE + #else + #define LV_USE_CALENDAR_CHINESE 0 + #endif + #endif +#endif /*LV_USE_CALENDAR*/ + +#ifndef LV_USE_CANVAS + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_CANVAS + #define LV_USE_CANVAS CONFIG_LV_USE_CANVAS + #else + #define LV_USE_CANVAS 0 + #endif + #else + #define LV_USE_CANVAS 1 + #endif +#endif + +#ifndef LV_USE_CHART + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_CHART + #define LV_USE_CHART CONFIG_LV_USE_CHART + #else + #define LV_USE_CHART 0 + #endif + #else + #define LV_USE_CHART 1 + #endif +#endif + +#ifndef LV_USE_CHECKBOX + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_CHECKBOX + #define LV_USE_CHECKBOX CONFIG_LV_USE_CHECKBOX + #else + #define LV_USE_CHECKBOX 0 + #endif + #else + #define LV_USE_CHECKBOX 1 + #endif +#endif + +#ifndef LV_USE_DROPDOWN + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_DROPDOWN + #define LV_USE_DROPDOWN CONFIG_LV_USE_DROPDOWN + #else + #define LV_USE_DROPDOWN 0 + #endif + #else + #define LV_USE_DROPDOWN 1 /*Requires: lv_label*/ + #endif +#endif + +#ifndef LV_USE_IMAGE + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_IMAGE + #define LV_USE_IMAGE CONFIG_LV_USE_IMAGE + #else + #define LV_USE_IMAGE 0 + #endif + #else + #define LV_USE_IMAGE 1 /*Requires: lv_label*/ + #endif +#endif + +#ifndef LV_USE_IMAGEBUTTON + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_IMAGEBUTTON + #define LV_USE_IMAGEBUTTON CONFIG_LV_USE_IMAGEBUTTON + #else + #define LV_USE_IMAGEBUTTON 0 + #endif + #else + #define LV_USE_IMAGEBUTTON 1 + #endif +#endif + +#ifndef LV_USE_KEYBOARD + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_KEYBOARD + #define LV_USE_KEYBOARD CONFIG_LV_USE_KEYBOARD + #else + #define LV_USE_KEYBOARD 0 + #endif + #else + #define LV_USE_KEYBOARD 1 + #endif +#endif + +#ifndef LV_USE_LABEL + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_LABEL + #define LV_USE_LABEL CONFIG_LV_USE_LABEL + #else + #define LV_USE_LABEL 0 + #endif + #else + #define LV_USE_LABEL 1 + #endif +#endif +#if LV_USE_LABEL + #ifndef LV_LABEL_TEXT_SELECTION + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_LABEL_TEXT_SELECTION + #define LV_LABEL_TEXT_SELECTION CONFIG_LV_LABEL_TEXT_SELECTION + #else + #define LV_LABEL_TEXT_SELECTION 0 + #endif + #else + #define LV_LABEL_TEXT_SELECTION 1 /*Enable selecting text of the label*/ + #endif + #endif + #ifndef LV_LABEL_LONG_TXT_HINT + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_LABEL_LONG_TXT_HINT + #define LV_LABEL_LONG_TXT_HINT CONFIG_LV_LABEL_LONG_TXT_HINT + #else + #define LV_LABEL_LONG_TXT_HINT 0 + #endif + #else + #define LV_LABEL_LONG_TXT_HINT 1 /*Store some extra info in labels to speed up drawing of very long texts*/ + #endif + #endif + #ifndef LV_LABEL_WAIT_CHAR_COUNT + #ifdef CONFIG_LV_LABEL_WAIT_CHAR_COUNT + #define LV_LABEL_WAIT_CHAR_COUNT CONFIG_LV_LABEL_WAIT_CHAR_COUNT + #else + #define LV_LABEL_WAIT_CHAR_COUNT 3 /*The count of wait chart*/ + #endif + #endif +#endif + +#ifndef LV_USE_LED + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_LED + #define LV_USE_LED CONFIG_LV_USE_LED + #else + #define LV_USE_LED 0 + #endif + #else + #define LV_USE_LED 1 + #endif +#endif + +#ifndef LV_USE_LINE + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_LINE + #define LV_USE_LINE CONFIG_LV_USE_LINE + #else + #define LV_USE_LINE 0 + #endif + #else + #define LV_USE_LINE 1 + #endif +#endif + +#ifndef LV_USE_LIST + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_LIST + #define LV_USE_LIST CONFIG_LV_USE_LIST + #else + #define LV_USE_LIST 0 + #endif + #else + #define LV_USE_LIST 1 + #endif +#endif + +#ifndef LV_USE_LOTTIE + #ifdef CONFIG_LV_USE_LOTTIE + #define LV_USE_LOTTIE CONFIG_LV_USE_LOTTIE + #else + #define LV_USE_LOTTIE 0 /*Requires: lv_canvas, thorvg */ + #endif +#endif + +#ifndef LV_USE_MENU + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_MENU + #define LV_USE_MENU CONFIG_LV_USE_MENU + #else + #define LV_USE_MENU 0 + #endif + #else + #define LV_USE_MENU 1 + #endif +#endif + +#ifndef LV_USE_MSGBOX + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_MSGBOX + #define LV_USE_MSGBOX CONFIG_LV_USE_MSGBOX + #else + #define LV_USE_MSGBOX 0 + #endif + #else + #define LV_USE_MSGBOX 1 + #endif +#endif + +#ifndef LV_USE_ROLLER + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_ROLLER + #define LV_USE_ROLLER CONFIG_LV_USE_ROLLER + #else + #define LV_USE_ROLLER 0 + #endif + #else + #define LV_USE_ROLLER 1 /*Requires: lv_label*/ + #endif +#endif + +#ifndef LV_USE_SCALE + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_SCALE + #define LV_USE_SCALE CONFIG_LV_USE_SCALE + #else + #define LV_USE_SCALE 0 + #endif + #else + #define LV_USE_SCALE 1 + #endif +#endif + +#ifndef LV_USE_SLIDER + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_SLIDER + #define LV_USE_SLIDER CONFIG_LV_USE_SLIDER + #else + #define LV_USE_SLIDER 0 + #endif + #else + #define LV_USE_SLIDER 1 /*Requires: lv_bar*/ + #endif +#endif + +#ifndef LV_USE_SPAN + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_SPAN + #define LV_USE_SPAN CONFIG_LV_USE_SPAN + #else + #define LV_USE_SPAN 0 + #endif + #else + #define LV_USE_SPAN 1 + #endif +#endif +#if LV_USE_SPAN + /*A line text can contain maximum num of span descriptor */ + #ifndef LV_SPAN_SNIPPET_STACK_SIZE + #ifdef CONFIG_LV_SPAN_SNIPPET_STACK_SIZE + #define LV_SPAN_SNIPPET_STACK_SIZE CONFIG_LV_SPAN_SNIPPET_STACK_SIZE + #else + #define LV_SPAN_SNIPPET_STACK_SIZE 64 + #endif + #endif +#endif + +#ifndef LV_USE_SPINBOX + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_SPINBOX + #define LV_USE_SPINBOX CONFIG_LV_USE_SPINBOX + #else + #define LV_USE_SPINBOX 0 + #endif + #else + #define LV_USE_SPINBOX 1 + #endif +#endif + +#ifndef LV_USE_SPINNER + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_SPINNER + #define LV_USE_SPINNER CONFIG_LV_USE_SPINNER + #else + #define LV_USE_SPINNER 0 + #endif + #else + #define LV_USE_SPINNER 1 + #endif +#endif + +#ifndef LV_USE_SWITCH + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_SWITCH + #define LV_USE_SWITCH CONFIG_LV_USE_SWITCH + #else + #define LV_USE_SWITCH 0 + #endif + #else + #define LV_USE_SWITCH 1 + #endif +#endif + +#ifndef LV_USE_TEXTAREA + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_TEXTAREA + #define LV_USE_TEXTAREA CONFIG_LV_USE_TEXTAREA + #else + #define LV_USE_TEXTAREA 0 + #endif + #else + #define LV_USE_TEXTAREA 1 /*Requires: lv_label*/ + #endif +#endif +#if LV_USE_TEXTAREA != 0 + #ifndef LV_TEXTAREA_DEF_PWD_SHOW_TIME + #ifdef CONFIG_LV_TEXTAREA_DEF_PWD_SHOW_TIME + #define LV_TEXTAREA_DEF_PWD_SHOW_TIME CONFIG_LV_TEXTAREA_DEF_PWD_SHOW_TIME + #else + #define LV_TEXTAREA_DEF_PWD_SHOW_TIME 1500 /*ms*/ + #endif + #endif +#endif + +#ifndef LV_USE_TABLE + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_TABLE + #define LV_USE_TABLE CONFIG_LV_USE_TABLE + #else + #define LV_USE_TABLE 0 + #endif + #else + #define LV_USE_TABLE 1 + #endif +#endif + +#ifndef LV_USE_TABVIEW + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_TABVIEW + #define LV_USE_TABVIEW CONFIG_LV_USE_TABVIEW + #else + #define LV_USE_TABVIEW 0 + #endif + #else + #define LV_USE_TABVIEW 1 + #endif +#endif + +#ifndef LV_USE_TILEVIEW + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_TILEVIEW + #define LV_USE_TILEVIEW CONFIG_LV_USE_TILEVIEW + #else + #define LV_USE_TILEVIEW 0 + #endif + #else + #define LV_USE_TILEVIEW 1 + #endif +#endif + +#ifndef LV_USE_WIN + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_WIN + #define LV_USE_WIN CONFIG_LV_USE_WIN + #else + #define LV_USE_WIN 0 + #endif + #else + #define LV_USE_WIN 1 + #endif +#endif + +/*================== + * THEMES + *==================*/ + +/*A simple, impressive and very complete theme*/ +#ifndef LV_USE_THEME_DEFAULT + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_THEME_DEFAULT + #define LV_USE_THEME_DEFAULT CONFIG_LV_USE_THEME_DEFAULT + #else + #define LV_USE_THEME_DEFAULT 0 + #endif + #else + #define LV_USE_THEME_DEFAULT 1 + #endif +#endif +#if LV_USE_THEME_DEFAULT + + /*0: Light mode; 1: Dark mode*/ + #ifndef LV_THEME_DEFAULT_DARK + #ifdef CONFIG_LV_THEME_DEFAULT_DARK + #define LV_THEME_DEFAULT_DARK CONFIG_LV_THEME_DEFAULT_DARK + #else + #define LV_THEME_DEFAULT_DARK 0 + #endif + #endif + + /*1: Enable grow on press*/ + #ifndef LV_THEME_DEFAULT_GROW + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_THEME_DEFAULT_GROW + #define LV_THEME_DEFAULT_GROW CONFIG_LV_THEME_DEFAULT_GROW + #else + #define LV_THEME_DEFAULT_GROW 0 + #endif + #else + #define LV_THEME_DEFAULT_GROW 1 + #endif + #endif + + /*Default transition time in [ms]*/ + #ifndef LV_THEME_DEFAULT_TRANSITION_TIME + #ifdef CONFIG_LV_THEME_DEFAULT_TRANSITION_TIME + #define LV_THEME_DEFAULT_TRANSITION_TIME CONFIG_LV_THEME_DEFAULT_TRANSITION_TIME + #else + #define LV_THEME_DEFAULT_TRANSITION_TIME 80 + #endif + #endif +#endif /*LV_USE_THEME_DEFAULT*/ + +/*A very simple theme that is a good starting point for a custom theme*/ +#ifndef LV_USE_THEME_SIMPLE + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_THEME_SIMPLE + #define LV_USE_THEME_SIMPLE CONFIG_LV_USE_THEME_SIMPLE + #else + #define LV_USE_THEME_SIMPLE 0 + #endif + #else + #define LV_USE_THEME_SIMPLE 1 + #endif +#endif + +/*A theme designed for monochrome displays*/ +#ifndef LV_USE_THEME_MONO + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_THEME_MONO + #define LV_USE_THEME_MONO CONFIG_LV_USE_THEME_MONO + #else + #define LV_USE_THEME_MONO 0 + #endif + #else + #define LV_USE_THEME_MONO 1 + #endif +#endif + +/*================== + * LAYOUTS + *==================*/ + +/*A layout similar to Flexbox in CSS.*/ +#ifndef LV_USE_FLEX + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_FLEX + #define LV_USE_FLEX CONFIG_LV_USE_FLEX + #else + #define LV_USE_FLEX 0 + #endif + #else + #define LV_USE_FLEX 1 + #endif +#endif + +/*A layout similar to Grid in CSS.*/ +#ifndef LV_USE_GRID + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_GRID + #define LV_USE_GRID CONFIG_LV_USE_GRID + #else + #define LV_USE_GRID 0 + #endif + #else + #define LV_USE_GRID 1 + #endif +#endif + +/*==================== + * 3RD PARTS LIBRARIES + *====================*/ + +/*File system interfaces for common APIs */ + +/*Setting a default driver letter allows skipping the driver prefix in filepaths*/ +#ifndef LV_FS_DEFAULT_DRIVE_LETTER + #ifdef CONFIG_LV_FS_DEFAULT_DRIVE_LETTER + #define LV_FS_DEFAULT_DRIVE_LETTER CONFIG_LV_FS_DEFAULT_DRIVE_LETTER + #else + #define LV_FS_DEFAULT_DRIVE_LETTER '\0' + #endif +#endif + +/*API for fopen, fread, etc*/ +#ifndef LV_USE_FS_STDIO + #ifdef CONFIG_LV_USE_FS_STDIO + #define LV_USE_FS_STDIO CONFIG_LV_USE_FS_STDIO + #else + #define LV_USE_FS_STDIO 0 + #endif +#endif +#if LV_USE_FS_STDIO + #ifndef LV_FS_STDIO_LETTER + #ifdef CONFIG_LV_FS_STDIO_LETTER + #define LV_FS_STDIO_LETTER CONFIG_LV_FS_STDIO_LETTER + #else + #define LV_FS_STDIO_LETTER '\0' /*Set an upper cased letter on which the drive will accessible (e.g. 'A')*/ + #endif + #endif + #ifndef LV_FS_STDIO_PATH + #ifdef CONFIG_LV_FS_STDIO_PATH + #define LV_FS_STDIO_PATH CONFIG_LV_FS_STDIO_PATH + #else + #define LV_FS_STDIO_PATH "" /*Set the working directory. File/directory paths will be appended to it.*/ + #endif + #endif + #ifndef LV_FS_STDIO_CACHE_SIZE + #ifdef CONFIG_LV_FS_STDIO_CACHE_SIZE + #define LV_FS_STDIO_CACHE_SIZE CONFIG_LV_FS_STDIO_CACHE_SIZE + #else + #define LV_FS_STDIO_CACHE_SIZE 0 /*>0 to cache this number of bytes in lv_fs_read()*/ + #endif + #endif +#endif + +/*API for open, read, etc*/ +#ifndef LV_USE_FS_POSIX + #ifdef CONFIG_LV_USE_FS_POSIX + #define LV_USE_FS_POSIX CONFIG_LV_USE_FS_POSIX + #else + #define LV_USE_FS_POSIX 0 + #endif +#endif +#if LV_USE_FS_POSIX + #ifndef LV_FS_POSIX_LETTER + #ifdef CONFIG_LV_FS_POSIX_LETTER + #define LV_FS_POSIX_LETTER CONFIG_LV_FS_POSIX_LETTER + #else + #define LV_FS_POSIX_LETTER '\0' /*Set an upper cased letter on which the drive will accessible (e.g. 'A')*/ + #endif + #endif + #ifndef LV_FS_POSIX_PATH + #ifdef CONFIG_LV_FS_POSIX_PATH + #define LV_FS_POSIX_PATH CONFIG_LV_FS_POSIX_PATH + #else + #define LV_FS_POSIX_PATH "" /*Set the working directory. File/directory paths will be appended to it.*/ + #endif + #endif + #ifndef LV_FS_POSIX_CACHE_SIZE + #ifdef CONFIG_LV_FS_POSIX_CACHE_SIZE + #define LV_FS_POSIX_CACHE_SIZE CONFIG_LV_FS_POSIX_CACHE_SIZE + #else + #define LV_FS_POSIX_CACHE_SIZE 0 /*>0 to cache this number of bytes in lv_fs_read()*/ + #endif + #endif +#endif + +/*API for CreateFile, ReadFile, etc*/ +#ifndef LV_USE_FS_WIN32 + #ifdef CONFIG_LV_USE_FS_WIN32 + #define LV_USE_FS_WIN32 CONFIG_LV_USE_FS_WIN32 + #else + #define LV_USE_FS_WIN32 0 + #endif +#endif +#if LV_USE_FS_WIN32 + #ifndef LV_FS_WIN32_LETTER + #ifdef CONFIG_LV_FS_WIN32_LETTER + #define LV_FS_WIN32_LETTER CONFIG_LV_FS_WIN32_LETTER + #else + #define LV_FS_WIN32_LETTER '\0' /*Set an upper cased letter on which the drive will accessible (e.g. 'A')*/ + #endif + #endif + #ifndef LV_FS_WIN32_PATH + #ifdef CONFIG_LV_FS_WIN32_PATH + #define LV_FS_WIN32_PATH CONFIG_LV_FS_WIN32_PATH + #else + #define LV_FS_WIN32_PATH "" /*Set the working directory. File/directory paths will be appended to it.*/ + #endif + #endif + #ifndef LV_FS_WIN32_CACHE_SIZE + #ifdef CONFIG_LV_FS_WIN32_CACHE_SIZE + #define LV_FS_WIN32_CACHE_SIZE CONFIG_LV_FS_WIN32_CACHE_SIZE + #else + #define LV_FS_WIN32_CACHE_SIZE 0 /*>0 to cache this number of bytes in lv_fs_read()*/ + #endif + #endif +#endif + +/*API for FATFS (needs to be added separately). Uses f_open, f_read, etc*/ +#ifndef LV_USE_FS_FATFS + #ifdef CONFIG_LV_USE_FS_FATFS + #define LV_USE_FS_FATFS CONFIG_LV_USE_FS_FATFS + #else + #define LV_USE_FS_FATFS 0 + #endif +#endif +#if LV_USE_FS_FATFS + #ifndef LV_FS_FATFS_LETTER + #ifdef CONFIG_LV_FS_FATFS_LETTER + #define LV_FS_FATFS_LETTER CONFIG_LV_FS_FATFS_LETTER + #else + #define LV_FS_FATFS_LETTER '\0' /*Set an upper cased letter on which the drive will accessible (e.g. 'A')*/ + #endif + #endif + #ifndef LV_FS_FATFS_CACHE_SIZE + #ifdef CONFIG_LV_FS_FATFS_CACHE_SIZE + #define LV_FS_FATFS_CACHE_SIZE CONFIG_LV_FS_FATFS_CACHE_SIZE + #else + #define LV_FS_FATFS_CACHE_SIZE 0 /*>0 to cache this number of bytes in lv_fs_read()*/ + #endif + #endif +#endif + +/*API for memory-mapped file access. */ +#ifndef LV_USE_FS_MEMFS + #ifdef CONFIG_LV_USE_FS_MEMFS + #define LV_USE_FS_MEMFS CONFIG_LV_USE_FS_MEMFS + #else + #define LV_USE_FS_MEMFS 0 + #endif +#endif +#if LV_USE_FS_MEMFS + #ifndef LV_FS_MEMFS_LETTER + #ifdef CONFIG_LV_FS_MEMFS_LETTER + #define LV_FS_MEMFS_LETTER CONFIG_LV_FS_MEMFS_LETTER + #else + #define LV_FS_MEMFS_LETTER '\0' /*Set an upper cased letter on which the drive will accessible (e.g. 'A')*/ + #endif + #endif +#endif + +/*API for LittleFs. */ +#ifndef LV_USE_FS_LITTLEFS + #ifdef CONFIG_LV_USE_FS_LITTLEFS + #define LV_USE_FS_LITTLEFS CONFIG_LV_USE_FS_LITTLEFS + #else + #define LV_USE_FS_LITTLEFS 0 + #endif +#endif +#if LV_USE_FS_LITTLEFS + #ifndef LV_FS_LITTLEFS_LETTER + #ifdef CONFIG_LV_FS_LITTLEFS_LETTER + #define LV_FS_LITTLEFS_LETTER CONFIG_LV_FS_LITTLEFS_LETTER + #else + #define LV_FS_LITTLEFS_LETTER '\0' /*Set an upper cased letter on which the drive will accessible (e.g. 'A')*/ + #endif + #endif +#endif + +/*API for Arduino LittleFs. */ +#ifndef LV_USE_FS_ARDUINO_ESP_LITTLEFS + #ifdef CONFIG_LV_USE_FS_ARDUINO_ESP_LITTLEFS + #define LV_USE_FS_ARDUINO_ESP_LITTLEFS CONFIG_LV_USE_FS_ARDUINO_ESP_LITTLEFS + #else + #define LV_USE_FS_ARDUINO_ESP_LITTLEFS 0 + #endif +#endif +#if LV_USE_FS_ARDUINO_ESP_LITTLEFS + #ifndef LV_FS_ARDUINO_ESP_LITTLEFS_LETTER + #ifdef CONFIG_LV_FS_ARDUINO_ESP_LITTLEFS_LETTER + #define LV_FS_ARDUINO_ESP_LITTLEFS_LETTER CONFIG_LV_FS_ARDUINO_ESP_LITTLEFS_LETTER + #else + #define LV_FS_ARDUINO_ESP_LITTLEFS_LETTER '\0' /*Set an upper cased letter on which the drive will accessible (e.g. 'A')*/ + #endif + #endif +#endif + +/*API for Arduino Sd. */ +#ifndef LV_USE_FS_ARDUINO_SD + #ifdef CONFIG_LV_USE_FS_ARDUINO_SD + #define LV_USE_FS_ARDUINO_SD CONFIG_LV_USE_FS_ARDUINO_SD + #else + #define LV_USE_FS_ARDUINO_SD 0 + #endif +#endif +#if LV_USE_FS_ARDUINO_SD + #ifndef LV_FS_ARDUINO_SD_LETTER + #ifdef CONFIG_LV_FS_ARDUINO_SD_LETTER + #define LV_FS_ARDUINO_SD_LETTER CONFIG_LV_FS_ARDUINO_SD_LETTER + #else + #define LV_FS_ARDUINO_SD_LETTER '\0' /*Set an upper cased letter on which the drive will accessible (e.g. 'A')*/ + #endif + #endif +#endif + +/*LODEPNG decoder library*/ +#ifndef LV_USE_LODEPNG + #ifdef CONFIG_LV_USE_LODEPNG + #define LV_USE_LODEPNG CONFIG_LV_USE_LODEPNG + #else + #define LV_USE_LODEPNG 0 + #endif +#endif + +/*PNG decoder(libpng) library*/ +#ifndef LV_USE_LIBPNG + #ifdef CONFIG_LV_USE_LIBPNG + #define LV_USE_LIBPNG CONFIG_LV_USE_LIBPNG + #else + #define LV_USE_LIBPNG 0 + #endif +#endif + +/*BMP decoder library*/ +#ifndef LV_USE_BMP + #ifdef CONFIG_LV_USE_BMP + #define LV_USE_BMP CONFIG_LV_USE_BMP + #else + #define LV_USE_BMP 0 + #endif +#endif + +/* JPG + split JPG decoder library. + * Split JPG is a custom format optimized for embedded systems. */ +#ifndef LV_USE_TJPGD + #ifdef CONFIG_LV_USE_TJPGD + #define LV_USE_TJPGD CONFIG_LV_USE_TJPGD + #else + #define LV_USE_TJPGD 0 + #endif +#endif + +/* libjpeg-turbo decoder library. + * Supports complete JPEG specifications and high-performance JPEG decoding. */ +#ifndef LV_USE_LIBJPEG_TURBO + #ifdef CONFIG_LV_USE_LIBJPEG_TURBO + #define LV_USE_LIBJPEG_TURBO CONFIG_LV_USE_LIBJPEG_TURBO + #else + #define LV_USE_LIBJPEG_TURBO 0 + #endif +#endif + +/*GIF decoder library*/ +#ifndef LV_USE_GIF + #ifdef CONFIG_LV_USE_GIF + #define LV_USE_GIF CONFIG_LV_USE_GIF + #else + #define LV_USE_GIF 0 + #endif +#endif +#if LV_USE_GIF + /*GIF decoder accelerate*/ + #ifndef LV_GIF_CACHE_DECODE_DATA + #ifdef CONFIG_LV_GIF_CACHE_DECODE_DATA + #define LV_GIF_CACHE_DECODE_DATA CONFIG_LV_GIF_CACHE_DECODE_DATA + #else + #define LV_GIF_CACHE_DECODE_DATA 0 + #endif + #endif +#endif + + +/*Decode bin images to RAM*/ +#ifndef LV_BIN_DECODER_RAM_LOAD + #ifdef CONFIG_LV_BIN_DECODER_RAM_LOAD + #define LV_BIN_DECODER_RAM_LOAD CONFIG_LV_BIN_DECODER_RAM_LOAD + #else + #define LV_BIN_DECODER_RAM_LOAD 0 + #endif +#endif + +/*RLE decompress library*/ +#ifndef LV_USE_RLE + #ifdef CONFIG_LV_USE_RLE + #define LV_USE_RLE CONFIG_LV_USE_RLE + #else + #define LV_USE_RLE 0 + #endif +#endif + +/*QR code library*/ +#ifndef LV_USE_QRCODE + #ifdef CONFIG_LV_USE_QRCODE + #define LV_USE_QRCODE CONFIG_LV_USE_QRCODE + #else + #define LV_USE_QRCODE 0 + #endif +#endif + +/*Barcode code library*/ +#ifndef LV_USE_BARCODE + #ifdef CONFIG_LV_USE_BARCODE + #define LV_USE_BARCODE CONFIG_LV_USE_BARCODE + #else + #define LV_USE_BARCODE 0 + #endif +#endif + +/*FreeType library*/ +#ifndef LV_USE_FREETYPE + #ifdef CONFIG_LV_USE_FREETYPE + #define LV_USE_FREETYPE CONFIG_LV_USE_FREETYPE + #else + #define LV_USE_FREETYPE 0 + #endif +#endif +#if LV_USE_FREETYPE + /*Let FreeType to use LVGL memory and file porting*/ + #ifndef LV_FREETYPE_USE_LVGL_PORT + #ifdef CONFIG_LV_FREETYPE_USE_LVGL_PORT + #define LV_FREETYPE_USE_LVGL_PORT CONFIG_LV_FREETYPE_USE_LVGL_PORT + #else + #define LV_FREETYPE_USE_LVGL_PORT 0 + #endif + #endif + + /*Cache count of the glyphs in FreeType. It means the number of glyphs that can be cached. + *The higher the value, the more memory will be used.*/ + #ifndef LV_FREETYPE_CACHE_FT_GLYPH_CNT + #ifdef CONFIG_LV_FREETYPE_CACHE_FT_GLYPH_CNT + #define LV_FREETYPE_CACHE_FT_GLYPH_CNT CONFIG_LV_FREETYPE_CACHE_FT_GLYPH_CNT + #else + #define LV_FREETYPE_CACHE_FT_GLYPH_CNT 256 + #endif + #endif +#endif + +/* Built-in TTF decoder */ +#ifndef LV_USE_TINY_TTF + #ifdef CONFIG_LV_USE_TINY_TTF + #define LV_USE_TINY_TTF CONFIG_LV_USE_TINY_TTF + #else + #define LV_USE_TINY_TTF 0 + #endif +#endif +#if LV_USE_TINY_TTF + /* Enable loading TTF data from files */ + #ifndef LV_TINY_TTF_FILE_SUPPORT + #ifdef CONFIG_LV_TINY_TTF_FILE_SUPPORT + #define LV_TINY_TTF_FILE_SUPPORT CONFIG_LV_TINY_TTF_FILE_SUPPORT + #else + #define LV_TINY_TTF_FILE_SUPPORT 0 + #endif + #endif + #ifndef LV_TINY_TTF_CACHE_GLYPH_CNT + #ifdef CONFIG_LV_TINY_TTF_CACHE_GLYPH_CNT + #define LV_TINY_TTF_CACHE_GLYPH_CNT CONFIG_LV_TINY_TTF_CACHE_GLYPH_CNT + #else + #define LV_TINY_TTF_CACHE_GLYPH_CNT 256 + #endif + #endif +#endif + +/*Rlottie library*/ +#ifndef LV_USE_RLOTTIE + #ifdef CONFIG_LV_USE_RLOTTIE + #define LV_USE_RLOTTIE CONFIG_LV_USE_RLOTTIE + #else + #define LV_USE_RLOTTIE 0 + #endif +#endif + +/*Enable Vector Graphic APIs + *Requires `LV_USE_MATRIX = 1`*/ +#ifndef LV_USE_VECTOR_GRAPHIC + #ifdef CONFIG_LV_USE_VECTOR_GRAPHIC + #define LV_USE_VECTOR_GRAPHIC CONFIG_LV_USE_VECTOR_GRAPHIC + #else + #define LV_USE_VECTOR_GRAPHIC 0 + #endif +#endif + +/* Enable ThorVG (vector graphics library) from the src/libs folder */ +#ifndef LV_USE_THORVG_INTERNAL + #ifdef CONFIG_LV_USE_THORVG_INTERNAL + #define LV_USE_THORVG_INTERNAL CONFIG_LV_USE_THORVG_INTERNAL + #else + #define LV_USE_THORVG_INTERNAL 0 + #endif +#endif + +/* Enable ThorVG by assuming that its installed and linked to the project */ +#ifndef LV_USE_THORVG_EXTERNAL + #ifdef CONFIG_LV_USE_THORVG_EXTERNAL + #define LV_USE_THORVG_EXTERNAL CONFIG_LV_USE_THORVG_EXTERNAL + #else + #define LV_USE_THORVG_EXTERNAL 0 + #endif +#endif + +/*Use lvgl built-in LZ4 lib*/ +#ifndef LV_USE_LZ4_INTERNAL + #ifdef CONFIG_LV_USE_LZ4_INTERNAL + #define LV_USE_LZ4_INTERNAL CONFIG_LV_USE_LZ4_INTERNAL + #else + #define LV_USE_LZ4_INTERNAL 0 + #endif +#endif + +/*Use external LZ4 library*/ +#ifndef LV_USE_LZ4_EXTERNAL + #ifdef CONFIG_LV_USE_LZ4_EXTERNAL + #define LV_USE_LZ4_EXTERNAL CONFIG_LV_USE_LZ4_EXTERNAL + #else + #define LV_USE_LZ4_EXTERNAL 0 + #endif +#endif + +/*FFmpeg library for image decoding and playing videos + *Supports all major image formats so do not enable other image decoder with it*/ +#ifndef LV_USE_FFMPEG + #ifdef CONFIG_LV_USE_FFMPEG + #define LV_USE_FFMPEG CONFIG_LV_USE_FFMPEG + #else + #define LV_USE_FFMPEG 0 + #endif +#endif +#if LV_USE_FFMPEG + /*Dump input information to stderr*/ + #ifndef LV_FFMPEG_DUMP_FORMAT + #ifdef CONFIG_LV_FFMPEG_DUMP_FORMAT + #define LV_FFMPEG_DUMP_FORMAT CONFIG_LV_FFMPEG_DUMP_FORMAT + #else + #define LV_FFMPEG_DUMP_FORMAT 0 + #endif + #endif +#endif + +/*================== + * OTHERS + *==================*/ + +/*1: Enable API to take snapshot for object*/ +#ifndef LV_USE_SNAPSHOT + #ifdef CONFIG_LV_USE_SNAPSHOT + #define LV_USE_SNAPSHOT CONFIG_LV_USE_SNAPSHOT + #else + #define LV_USE_SNAPSHOT 0 + #endif +#endif + +/*1: Enable system monitor component*/ +#ifndef LV_USE_SYSMON + #ifdef CONFIG_LV_USE_SYSMON + #define LV_USE_SYSMON CONFIG_LV_USE_SYSMON + #else + #define LV_USE_SYSMON 0 + #endif +#endif +#if LV_USE_SYSMON + /*Get the idle percentage. E.g. uint32_t my_get_idle(void);*/ + #ifndef LV_SYSMON_GET_IDLE + #ifdef CONFIG_LV_SYSMON_GET_IDLE + #define LV_SYSMON_GET_IDLE CONFIG_LV_SYSMON_GET_IDLE + #else + #define LV_SYSMON_GET_IDLE lv_timer_get_idle + #endif + #endif + + /*1: Show CPU usage and FPS count + * Requires `LV_USE_SYSMON = 1`*/ + #ifndef LV_USE_PERF_MONITOR + #ifdef CONFIG_LV_USE_PERF_MONITOR + #define LV_USE_PERF_MONITOR CONFIG_LV_USE_PERF_MONITOR + #else + #define LV_USE_PERF_MONITOR 0 + #endif + #endif + #if LV_USE_PERF_MONITOR + #ifndef LV_USE_PERF_MONITOR_POS + #ifdef CONFIG_LV_USE_PERF_MONITOR_POS + #define LV_USE_PERF_MONITOR_POS CONFIG_LV_USE_PERF_MONITOR_POS + #else + #define LV_USE_PERF_MONITOR_POS LV_ALIGN_BOTTOM_RIGHT + #endif + #endif + + /*0: Displays performance data on the screen, 1: Prints performance data using log.*/ + #ifndef LV_USE_PERF_MONITOR_LOG_MODE + #ifdef CONFIG_LV_USE_PERF_MONITOR_LOG_MODE + #define LV_USE_PERF_MONITOR_LOG_MODE CONFIG_LV_USE_PERF_MONITOR_LOG_MODE + #else + #define LV_USE_PERF_MONITOR_LOG_MODE 0 + #endif + #endif + #endif + + /*1: Show the used memory and the memory fragmentation + * Requires `LV_USE_STDLIB_MALLOC = LV_STDLIB_BUILTIN` + * Requires `LV_USE_SYSMON = 1`*/ + #ifndef LV_USE_MEM_MONITOR + #ifdef CONFIG_LV_USE_MEM_MONITOR + #define LV_USE_MEM_MONITOR CONFIG_LV_USE_MEM_MONITOR + #else + #define LV_USE_MEM_MONITOR 0 + #endif + #endif + #if LV_USE_MEM_MONITOR + #ifndef LV_USE_MEM_MONITOR_POS + #ifdef CONFIG_LV_USE_MEM_MONITOR_POS + #define LV_USE_MEM_MONITOR_POS CONFIG_LV_USE_MEM_MONITOR_POS + #else + #define LV_USE_MEM_MONITOR_POS LV_ALIGN_BOTTOM_LEFT + #endif + #endif + #endif + +#endif /*LV_USE_SYSMON*/ + +/*1: Enable the runtime performance profiler*/ +#ifndef LV_USE_PROFILER + #ifdef CONFIG_LV_USE_PROFILER + #define LV_USE_PROFILER CONFIG_LV_USE_PROFILER + #else + #define LV_USE_PROFILER 0 + #endif +#endif +#if LV_USE_PROFILER + /*1: Enable the built-in profiler*/ + #ifndef LV_USE_PROFILER_BUILTIN + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_PROFILER_BUILTIN + #define LV_USE_PROFILER_BUILTIN CONFIG_LV_USE_PROFILER_BUILTIN + #else + #define LV_USE_PROFILER_BUILTIN 0 + #endif + #else + #define LV_USE_PROFILER_BUILTIN 1 + #endif + #endif + #if LV_USE_PROFILER_BUILTIN + /*Default profiler trace buffer size*/ + #ifndef LV_PROFILER_BUILTIN_BUF_SIZE + #ifdef CONFIG_LV_PROFILER_BUILTIN_BUF_SIZE + #define LV_PROFILER_BUILTIN_BUF_SIZE CONFIG_LV_PROFILER_BUILTIN_BUF_SIZE + #else + #define LV_PROFILER_BUILTIN_BUF_SIZE (16 * 1024) /*[bytes]*/ + #endif + #endif + #endif + + /*Header to include for the profiler*/ + #ifndef LV_PROFILER_INCLUDE + #ifdef CONFIG_LV_PROFILER_INCLUDE + #define LV_PROFILER_INCLUDE CONFIG_LV_PROFILER_INCLUDE + #else + #define LV_PROFILER_INCLUDE "lvgl/src/misc/lv_profiler_builtin.h" + #endif + #endif + + /*Profiler start point function*/ + #ifndef LV_PROFILER_BEGIN + #ifdef CONFIG_LV_PROFILER_BEGIN + #define LV_PROFILER_BEGIN CONFIG_LV_PROFILER_BEGIN + #else + #define LV_PROFILER_BEGIN LV_PROFILER_BUILTIN_BEGIN + #endif + #endif + + /*Profiler end point function*/ + #ifndef LV_PROFILER_END + #ifdef CONFIG_LV_PROFILER_END + #define LV_PROFILER_END CONFIG_LV_PROFILER_END + #else + #define LV_PROFILER_END LV_PROFILER_BUILTIN_END + #endif + #endif + + /*Profiler start point function with custom tag*/ + #ifndef LV_PROFILER_BEGIN_TAG + #ifdef CONFIG_LV_PROFILER_BEGIN_TAG + #define LV_PROFILER_BEGIN_TAG CONFIG_LV_PROFILER_BEGIN_TAG + #else + #define LV_PROFILER_BEGIN_TAG LV_PROFILER_BUILTIN_BEGIN_TAG + #endif + #endif + + /*Profiler end point function with custom tag*/ + #ifndef LV_PROFILER_END_TAG + #ifdef CONFIG_LV_PROFILER_END_TAG + #define LV_PROFILER_END_TAG CONFIG_LV_PROFILER_END_TAG + #else + #define LV_PROFILER_END_TAG LV_PROFILER_BUILTIN_END_TAG + #endif + #endif +#endif + +/*1: Enable Monkey test*/ +#ifndef LV_USE_MONKEY + #ifdef CONFIG_LV_USE_MONKEY + #define LV_USE_MONKEY CONFIG_LV_USE_MONKEY + #else + #define LV_USE_MONKEY 0 + #endif +#endif + +/*1: Enable grid navigation*/ +#ifndef LV_USE_GRIDNAV + #ifdef CONFIG_LV_USE_GRIDNAV + #define LV_USE_GRIDNAV CONFIG_LV_USE_GRIDNAV + #else + #define LV_USE_GRIDNAV 0 + #endif +#endif + +/*1: Enable lv_obj fragment*/ +#ifndef LV_USE_FRAGMENT + #ifdef CONFIG_LV_USE_FRAGMENT + #define LV_USE_FRAGMENT CONFIG_LV_USE_FRAGMENT + #else + #define LV_USE_FRAGMENT 0 + #endif +#endif + +/*1: Support using images as font in label or span widgets */ +#ifndef LV_USE_IMGFONT + #ifdef CONFIG_LV_USE_IMGFONT + #define LV_USE_IMGFONT CONFIG_LV_USE_IMGFONT + #else + #define LV_USE_IMGFONT 0 + #endif +#endif + +/*1: Enable an observer pattern implementation*/ +#ifndef LV_USE_OBSERVER + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_OBSERVER + #define LV_USE_OBSERVER CONFIG_LV_USE_OBSERVER + #else + #define LV_USE_OBSERVER 0 + #endif + #else + #define LV_USE_OBSERVER 1 + #endif +#endif + +/*1: Enable Pinyin input method*/ +/*Requires: lv_keyboard*/ +#ifndef LV_USE_IME_PINYIN + #ifdef CONFIG_LV_USE_IME_PINYIN + #define LV_USE_IME_PINYIN CONFIG_LV_USE_IME_PINYIN + #else + #define LV_USE_IME_PINYIN 0 + #endif +#endif +#if LV_USE_IME_PINYIN + /*1: Use default thesaurus*/ + /*If you do not use the default thesaurus, be sure to use `lv_ime_pinyin` after setting the thesaurus*/ + #ifndef LV_IME_PINYIN_USE_DEFAULT_DICT + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_IME_PINYIN_USE_DEFAULT_DICT + #define LV_IME_PINYIN_USE_DEFAULT_DICT CONFIG_LV_IME_PINYIN_USE_DEFAULT_DICT + #else + #define LV_IME_PINYIN_USE_DEFAULT_DICT 0 + #endif + #else + #define LV_IME_PINYIN_USE_DEFAULT_DICT 1 + #endif + #endif + /*Set the maximum number of candidate panels that can be displayed*/ + /*This needs to be adjusted according to the size of the screen*/ + #ifndef LV_IME_PINYIN_CAND_TEXT_NUM + #ifdef CONFIG_LV_IME_PINYIN_CAND_TEXT_NUM + #define LV_IME_PINYIN_CAND_TEXT_NUM CONFIG_LV_IME_PINYIN_CAND_TEXT_NUM + #else + #define LV_IME_PINYIN_CAND_TEXT_NUM 6 + #endif + #endif + + /*Use 9 key input(k9)*/ + #ifndef LV_IME_PINYIN_USE_K9_MODE + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_IME_PINYIN_USE_K9_MODE + #define LV_IME_PINYIN_USE_K9_MODE CONFIG_LV_IME_PINYIN_USE_K9_MODE + #else + #define LV_IME_PINYIN_USE_K9_MODE 0 + #endif + #else + #define LV_IME_PINYIN_USE_K9_MODE 1 + #endif + #endif + #if LV_IME_PINYIN_USE_K9_MODE == 1 + #ifndef LV_IME_PINYIN_K9_CAND_TEXT_NUM + #ifdef CONFIG_LV_IME_PINYIN_K9_CAND_TEXT_NUM + #define LV_IME_PINYIN_K9_CAND_TEXT_NUM CONFIG_LV_IME_PINYIN_K9_CAND_TEXT_NUM + #else + #define LV_IME_PINYIN_K9_CAND_TEXT_NUM 3 + #endif + #endif + #endif /*LV_IME_PINYIN_USE_K9_MODE*/ +#endif + +/*1: Enable file explorer*/ +/*Requires: lv_table*/ +#ifndef LV_USE_FILE_EXPLORER + #ifdef CONFIG_LV_USE_FILE_EXPLORER + #define LV_USE_FILE_EXPLORER CONFIG_LV_USE_FILE_EXPLORER + #else + #define LV_USE_FILE_EXPLORER 0 + #endif +#endif +#if LV_USE_FILE_EXPLORER + /*Maximum length of path*/ + #ifndef LV_FILE_EXPLORER_PATH_MAX_LEN + #ifdef CONFIG_LV_FILE_EXPLORER_PATH_MAX_LEN + #define LV_FILE_EXPLORER_PATH_MAX_LEN CONFIG_LV_FILE_EXPLORER_PATH_MAX_LEN + #else + #define LV_FILE_EXPLORER_PATH_MAX_LEN (128) + #endif + #endif + /*Quick access bar, 1:use, 0:not use*/ + /*Requires: lv_list*/ + #ifndef LV_FILE_EXPLORER_QUICK_ACCESS + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_FILE_EXPLORER_QUICK_ACCESS + #define LV_FILE_EXPLORER_QUICK_ACCESS CONFIG_LV_FILE_EXPLORER_QUICK_ACCESS + #else + #define LV_FILE_EXPLORER_QUICK_ACCESS 0 + #endif + #else + #define LV_FILE_EXPLORER_QUICK_ACCESS 1 + #endif + #endif +#endif + +/*================== + * DEVICES + *==================*/ + +/*Use SDL to open window on PC and handle mouse and keyboard*/ +#ifndef LV_USE_SDL + #ifdef CONFIG_LV_USE_SDL + #define LV_USE_SDL CONFIG_LV_USE_SDL + #else + #define LV_USE_SDL 0 + #endif +#endif +#if LV_USE_SDL + #ifndef LV_SDL_INCLUDE_PATH + #ifdef CONFIG_LV_SDL_INCLUDE_PATH + #define LV_SDL_INCLUDE_PATH CONFIG_LV_SDL_INCLUDE_PATH + #else + #define LV_SDL_INCLUDE_PATH + #endif + #endif + #ifndef LV_SDL_RENDER_MODE + #ifdef CONFIG_LV_SDL_RENDER_MODE + #define LV_SDL_RENDER_MODE CONFIG_LV_SDL_RENDER_MODE + #else + #define LV_SDL_RENDER_MODE LV_DISPLAY_RENDER_MODE_DIRECT /*LV_DISPLAY_RENDER_MODE_DIRECT is recommended for best performance*/ + #endif + #endif + #ifndef LV_SDL_BUF_COUNT + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_SDL_BUF_COUNT + #define LV_SDL_BUF_COUNT CONFIG_LV_SDL_BUF_COUNT + #else + #define LV_SDL_BUF_COUNT 0 + #endif + #else + #define LV_SDL_BUF_COUNT 1 /*1 or 2*/ + #endif + #endif + #ifndef LV_SDL_ACCELERATED + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_SDL_ACCELERATED + #define LV_SDL_ACCELERATED CONFIG_LV_SDL_ACCELERATED + #else + #define LV_SDL_ACCELERATED 0 + #endif + #else + #define LV_SDL_ACCELERATED 1 /*1: Use hardware acceleration*/ + #endif + #endif + #ifndef LV_SDL_FULLSCREEN + #ifdef CONFIG_LV_SDL_FULLSCREEN + #define LV_SDL_FULLSCREEN CONFIG_LV_SDL_FULLSCREEN + #else + #define LV_SDL_FULLSCREEN 0 /*1: Make the window full screen by default*/ + #endif + #endif + #ifndef LV_SDL_DIRECT_EXIT + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_SDL_DIRECT_EXIT + #define LV_SDL_DIRECT_EXIT CONFIG_LV_SDL_DIRECT_EXIT + #else + #define LV_SDL_DIRECT_EXIT 0 + #endif + #else + #define LV_SDL_DIRECT_EXIT 1 /*1: Exit the application when all SDL windows are closed*/ + #endif + #endif + #ifndef LV_SDL_MOUSEWHEEL_MODE + #ifdef CONFIG_LV_SDL_MOUSEWHEEL_MODE + #define LV_SDL_MOUSEWHEEL_MODE CONFIG_LV_SDL_MOUSEWHEEL_MODE + #else + #define LV_SDL_MOUSEWHEEL_MODE LV_SDL_MOUSEWHEEL_MODE_ENCODER /*LV_SDL_MOUSEWHEEL_MODE_ENCODER/CROWN*/ + #endif + #endif +#endif + +/*Use X11 to open window on Linux desktop and handle mouse and keyboard*/ +#ifndef LV_USE_X11 + #ifdef CONFIG_LV_USE_X11 + #define LV_USE_X11 CONFIG_LV_USE_X11 + #else + #define LV_USE_X11 0 + #endif +#endif +#if LV_USE_X11 + #ifndef LV_X11_DIRECT_EXIT + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_X11_DIRECT_EXIT + #define LV_X11_DIRECT_EXIT CONFIG_LV_X11_DIRECT_EXIT + #else + #define LV_X11_DIRECT_EXIT 0 + #endif + #else + #define LV_X11_DIRECT_EXIT 1 /*Exit the application when all X11 windows have been closed*/ + #endif + #endif + #ifndef LV_X11_DOUBLE_BUFFER + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_X11_DOUBLE_BUFFER + #define LV_X11_DOUBLE_BUFFER CONFIG_LV_X11_DOUBLE_BUFFER + #else + #define LV_X11_DOUBLE_BUFFER 0 + #endif + #else + #define LV_X11_DOUBLE_BUFFER 1 /*Use double buffers for rendering*/ + #endif + #endif + /*select only 1 of the following render modes (LV_X11_RENDER_MODE_PARTIAL preferred!)*/ + #ifndef LV_X11_RENDER_MODE_PARTIAL + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_X11_RENDER_MODE_PARTIAL + #define LV_X11_RENDER_MODE_PARTIAL CONFIG_LV_X11_RENDER_MODE_PARTIAL + #else + #define LV_X11_RENDER_MODE_PARTIAL 0 + #endif + #else + #define LV_X11_RENDER_MODE_PARTIAL 1 /*Partial render mode (preferred)*/ + #endif + #endif + #ifndef LV_X11_RENDER_MODE_DIRECT + #ifdef CONFIG_LV_X11_RENDER_MODE_DIRECT + #define LV_X11_RENDER_MODE_DIRECT CONFIG_LV_X11_RENDER_MODE_DIRECT + #else + #define LV_X11_RENDER_MODE_DIRECT 0 /*direct render mode*/ + #endif + #endif + #ifndef LV_X11_RENDER_MODE_FULL + #ifdef CONFIG_LV_X11_RENDER_MODE_FULL + #define LV_X11_RENDER_MODE_FULL CONFIG_LV_X11_RENDER_MODE_FULL + #else + #define LV_X11_RENDER_MODE_FULL 0 /*Full render mode*/ + #endif + #endif +#endif + +/*Use Wayland to open a window and handle input on Linux or BSD desktops */ +#ifndef LV_USE_WAYLAND + #ifdef CONFIG_LV_USE_WAYLAND + #define LV_USE_WAYLAND CONFIG_LV_USE_WAYLAND + #else + #define LV_USE_WAYLAND 0 + #endif +#endif +#if LV_USE_WAYLAND + #ifndef LV_WAYLAND_WINDOW_DECORATIONS + #ifdef CONFIG_LV_WAYLAND_WINDOW_DECORATIONS + #define LV_WAYLAND_WINDOW_DECORATIONS CONFIG_LV_WAYLAND_WINDOW_DECORATIONS + #else + #define LV_WAYLAND_WINDOW_DECORATIONS 0 /*Draw client side window decorations only necessary on Mutter/GNOME*/ + #endif + #endif + #ifndef LV_WAYLAND_WL_SHELL + #ifdef CONFIG_LV_WAYLAND_WL_SHELL + #define LV_WAYLAND_WL_SHELL CONFIG_LV_WAYLAND_WL_SHELL + #else + #define LV_WAYLAND_WL_SHELL 0 /*Use the legacy wl_shell protocol instead of the default XDG shell*/ + #endif + #endif +#endif + +/*Driver for /dev/fb*/ +#ifndef LV_USE_LINUX_FBDEV + #ifdef CONFIG_LV_USE_LINUX_FBDEV + #define LV_USE_LINUX_FBDEV CONFIG_LV_USE_LINUX_FBDEV + #else + #define LV_USE_LINUX_FBDEV 0 + #endif +#endif +#if LV_USE_LINUX_FBDEV + #ifndef LV_LINUX_FBDEV_BSD + #ifdef CONFIG_LV_LINUX_FBDEV_BSD + #define LV_LINUX_FBDEV_BSD CONFIG_LV_LINUX_FBDEV_BSD + #else + #define LV_LINUX_FBDEV_BSD 0 + #endif + #endif + #ifndef LV_LINUX_FBDEV_RENDER_MODE + #ifdef CONFIG_LV_LINUX_FBDEV_RENDER_MODE + #define LV_LINUX_FBDEV_RENDER_MODE CONFIG_LV_LINUX_FBDEV_RENDER_MODE + #else + #define LV_LINUX_FBDEV_RENDER_MODE LV_DISPLAY_RENDER_MODE_PARTIAL + #endif + #endif + #ifndef LV_LINUX_FBDEV_BUFFER_COUNT + #ifdef CONFIG_LV_LINUX_FBDEV_BUFFER_COUNT + #define LV_LINUX_FBDEV_BUFFER_COUNT CONFIG_LV_LINUX_FBDEV_BUFFER_COUNT + #else + #define LV_LINUX_FBDEV_BUFFER_COUNT 0 + #endif + #endif + #ifndef LV_LINUX_FBDEV_BUFFER_SIZE + #ifdef CONFIG_LV_LINUX_FBDEV_BUFFER_SIZE + #define LV_LINUX_FBDEV_BUFFER_SIZE CONFIG_LV_LINUX_FBDEV_BUFFER_SIZE + #else + #define LV_LINUX_FBDEV_BUFFER_SIZE 60 + #endif + #endif +#endif + +/*Use Nuttx to open window and handle touchscreen*/ +#ifndef LV_USE_NUTTX + #ifdef CONFIG_LV_USE_NUTTX + #define LV_USE_NUTTX CONFIG_LV_USE_NUTTX + #else + #define LV_USE_NUTTX 0 + #endif +#endif + +#if LV_USE_NUTTX + #ifndef LV_USE_NUTTX_LIBUV + #ifdef CONFIG_LV_USE_NUTTX_LIBUV + #define LV_USE_NUTTX_LIBUV CONFIG_LV_USE_NUTTX_LIBUV + #else + #define LV_USE_NUTTX_LIBUV 0 + #endif + #endif + + /*Use Nuttx custom init API to open window and handle touchscreen*/ + #ifndef LV_USE_NUTTX_CUSTOM_INIT + #ifdef CONFIG_LV_USE_NUTTX_CUSTOM_INIT + #define LV_USE_NUTTX_CUSTOM_INIT CONFIG_LV_USE_NUTTX_CUSTOM_INIT + #else + #define LV_USE_NUTTX_CUSTOM_INIT 0 + #endif + #endif + + /*Driver for /dev/lcd*/ + #ifndef LV_USE_NUTTX_LCD + #ifdef CONFIG_LV_USE_NUTTX_LCD + #define LV_USE_NUTTX_LCD CONFIG_LV_USE_NUTTX_LCD + #else + #define LV_USE_NUTTX_LCD 0 + #endif + #endif + #if LV_USE_NUTTX_LCD + #ifndef LV_NUTTX_LCD_BUFFER_COUNT + #ifdef CONFIG_LV_NUTTX_LCD_BUFFER_COUNT + #define LV_NUTTX_LCD_BUFFER_COUNT CONFIG_LV_NUTTX_LCD_BUFFER_COUNT + #else + #define LV_NUTTX_LCD_BUFFER_COUNT 0 + #endif + #endif + #ifndef LV_NUTTX_LCD_BUFFER_SIZE + #ifdef CONFIG_LV_NUTTX_LCD_BUFFER_SIZE + #define LV_NUTTX_LCD_BUFFER_SIZE CONFIG_LV_NUTTX_LCD_BUFFER_SIZE + #else + #define LV_NUTTX_LCD_BUFFER_SIZE 60 + #endif + #endif + #endif + + /*Driver for /dev/input*/ + #ifndef LV_USE_NUTTX_TOUCHSCREEN + #ifdef CONFIG_LV_USE_NUTTX_TOUCHSCREEN + #define LV_USE_NUTTX_TOUCHSCREEN CONFIG_LV_USE_NUTTX_TOUCHSCREEN + #else + #define LV_USE_NUTTX_TOUCHSCREEN 0 + #endif + #endif + +#endif + +/*Driver for /dev/dri/card*/ +#ifndef LV_USE_LINUX_DRM + #ifdef CONFIG_LV_USE_LINUX_DRM + #define LV_USE_LINUX_DRM CONFIG_LV_USE_LINUX_DRM + #else + #define LV_USE_LINUX_DRM 0 + #endif +#endif + +/*Interface for TFT_eSPI*/ +#ifndef LV_USE_TFT_ESPI + #ifdef CONFIG_LV_USE_TFT_ESPI + #define LV_USE_TFT_ESPI CONFIG_LV_USE_TFT_ESPI + #else + #define LV_USE_TFT_ESPI 0 + #endif +#endif + +/*Driver for evdev input devices*/ +#ifndef LV_USE_EVDEV + #ifdef CONFIG_LV_USE_EVDEV + #define LV_USE_EVDEV CONFIG_LV_USE_EVDEV + #else + #define LV_USE_EVDEV 0 + #endif +#endif + +/*Driver for libinput input devices*/ +#ifndef LV_USE_LIBINPUT + #ifdef CONFIG_LV_USE_LIBINPUT + #define LV_USE_LIBINPUT CONFIG_LV_USE_LIBINPUT + #else + #define LV_USE_LIBINPUT 0 + #endif +#endif + +#if LV_USE_LIBINPUT + #ifndef LV_LIBINPUT_BSD + #ifdef CONFIG_LV_LIBINPUT_BSD + #define LV_LIBINPUT_BSD CONFIG_LV_LIBINPUT_BSD + #else + #define LV_LIBINPUT_BSD 0 + #endif + #endif + + /*Full keyboard support*/ + #ifndef LV_LIBINPUT_XKB + #ifdef CONFIG_LV_LIBINPUT_XKB + #define LV_LIBINPUT_XKB CONFIG_LV_LIBINPUT_XKB + #else + #define LV_LIBINPUT_XKB 0 + #endif + #endif + #if LV_LIBINPUT_XKB + /*"setxkbmap -query" can help find the right values for your keyboard*/ + #ifndef LV_LIBINPUT_XKB_KEY_MAP + #ifdef CONFIG_LV_LIBINPUT_XKB_KEY_MAP + #define LV_LIBINPUT_XKB_KEY_MAP CONFIG_LV_LIBINPUT_XKB_KEY_MAP + #else + #define LV_LIBINPUT_XKB_KEY_MAP { .rules = NULL, .model = "pc101", .layout = "us", .variant = NULL, .options = NULL } + #endif + #endif + #endif +#endif + +/*Drivers for LCD devices connected via SPI/parallel port*/ +#ifndef LV_USE_ST7735 + #ifdef CONFIG_LV_USE_ST7735 + #define LV_USE_ST7735 CONFIG_LV_USE_ST7735 + #else + #define LV_USE_ST7735 0 + #endif +#endif +#ifndef LV_USE_ST7789 + #ifdef CONFIG_LV_USE_ST7789 + #define LV_USE_ST7789 CONFIG_LV_USE_ST7789 + #else + #define LV_USE_ST7789 0 + #endif +#endif +#ifndef LV_USE_ST7796 + #ifdef CONFIG_LV_USE_ST7796 + #define LV_USE_ST7796 CONFIG_LV_USE_ST7796 + #else + #define LV_USE_ST7796 0 + #endif +#endif +#ifndef LV_USE_ILI9341 + #ifdef CONFIG_LV_USE_ILI9341 + #define LV_USE_ILI9341 CONFIG_LV_USE_ILI9341 + #else + #define LV_USE_ILI9341 0 + #endif +#endif + +#ifndef LV_USE_GENERIC_MIPI + #ifdef CONFIG_LV_USE_GENERIC_MIPI + #define LV_USE_GENERIC_MIPI CONFIG_LV_USE_GENERIC_MIPI + #else + #define LV_USE_GENERIC_MIPI (LV_USE_ST7735 | LV_USE_ST7789 | LV_USE_ST7796 | LV_USE_ILI9341) + #endif +#endif + +/*Driver for Renesas GLCD*/ +#ifndef LV_USE_RENESAS_GLCDC + #ifdef CONFIG_LV_USE_RENESAS_GLCDC + #define LV_USE_RENESAS_GLCDC CONFIG_LV_USE_RENESAS_GLCDC + #else + #define LV_USE_RENESAS_GLCDC 0 + #endif +#endif + +/* LVGL Windows backend */ +#ifndef LV_USE_WINDOWS + #ifdef CONFIG_LV_USE_WINDOWS + #define LV_USE_WINDOWS CONFIG_LV_USE_WINDOWS + #else + #define LV_USE_WINDOWS 0 + #endif +#endif + +/* Use OpenGL to open window on PC and handle mouse and keyboard */ +#ifndef LV_USE_OPENGLES + #ifdef CONFIG_LV_USE_OPENGLES + #define LV_USE_OPENGLES CONFIG_LV_USE_OPENGLES + #else + #define LV_USE_OPENGLES 0 + #endif +#endif +#if LV_USE_OPENGLES + #ifndef LV_USE_OPENGLES_DEBUG + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_USE_OPENGLES_DEBUG + #define LV_USE_OPENGLES_DEBUG CONFIG_LV_USE_OPENGLES_DEBUG + #else + #define LV_USE_OPENGLES_DEBUG 0 + #endif + #else + #define LV_USE_OPENGLES_DEBUG 1 /* Enable or disable debug for opengles */ + #endif + #endif +#endif + +/* QNX Screen display and input drivers */ +#ifndef LV_USE_QNX + #ifdef CONFIG_LV_USE_QNX + #define LV_USE_QNX CONFIG_LV_USE_QNX + #else + #define LV_USE_QNX 0 + #endif +#endif +#if LV_USE_QNX + #ifndef LV_QNX_BUF_COUNT + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_QNX_BUF_COUNT + #define LV_QNX_BUF_COUNT CONFIG_LV_QNX_BUF_COUNT + #else + #define LV_QNX_BUF_COUNT 0 + #endif + #else + #define LV_QNX_BUF_COUNT 1 /*1 or 2*/ + #endif + #endif +#endif + +/*================== +* EXAMPLES +*==================*/ + +/*Enable the examples to be built with the library*/ +#ifndef LV_BUILD_EXAMPLES + #ifdef LV_KCONFIG_PRESENT + #ifdef CONFIG_LV_BUILD_EXAMPLES + #define LV_BUILD_EXAMPLES CONFIG_LV_BUILD_EXAMPLES + #else + #define LV_BUILD_EXAMPLES 0 + #endif + #else + #define LV_BUILD_EXAMPLES 1 + #endif +#endif + +/*=================== + * DEMO USAGE + ====================*/ + +/*Show some widget. It might be required to increase `LV_MEM_SIZE` */ +#ifndef LV_USE_DEMO_WIDGETS + #ifdef CONFIG_LV_USE_DEMO_WIDGETS + #define LV_USE_DEMO_WIDGETS CONFIG_LV_USE_DEMO_WIDGETS + #else + #define LV_USE_DEMO_WIDGETS 0 + #endif +#endif + +/*Demonstrate the usage of encoder and keyboard*/ +#ifndef LV_USE_DEMO_KEYPAD_AND_ENCODER + #ifdef CONFIG_LV_USE_DEMO_KEYPAD_AND_ENCODER + #define LV_USE_DEMO_KEYPAD_AND_ENCODER CONFIG_LV_USE_DEMO_KEYPAD_AND_ENCODER + #else + #define LV_USE_DEMO_KEYPAD_AND_ENCODER 0 + #endif +#endif + +/*Benchmark your system*/ +#ifndef LV_USE_DEMO_BENCHMARK + #ifdef CONFIG_LV_USE_DEMO_BENCHMARK + #define LV_USE_DEMO_BENCHMARK CONFIG_LV_USE_DEMO_BENCHMARK + #else + #define LV_USE_DEMO_BENCHMARK 0 + #endif +#endif + +/*Render test for each primitives. Requires at least 480x272 display*/ +#ifndef LV_USE_DEMO_RENDER + #ifdef CONFIG_LV_USE_DEMO_RENDER + #define LV_USE_DEMO_RENDER CONFIG_LV_USE_DEMO_RENDER + #else + #define LV_USE_DEMO_RENDER 0 + #endif +#endif + +/*Stress test for LVGL*/ +#ifndef LV_USE_DEMO_STRESS + #ifdef CONFIG_LV_USE_DEMO_STRESS + #define LV_USE_DEMO_STRESS CONFIG_LV_USE_DEMO_STRESS + #else + #define LV_USE_DEMO_STRESS 0 + #endif +#endif + +/*Music player demo*/ +#ifndef LV_USE_DEMO_MUSIC + #ifdef CONFIG_LV_USE_DEMO_MUSIC + #define LV_USE_DEMO_MUSIC CONFIG_LV_USE_DEMO_MUSIC + #else + #define LV_USE_DEMO_MUSIC 0 + #endif +#endif +#if LV_USE_DEMO_MUSIC + #ifndef LV_DEMO_MUSIC_SQUARE + #ifdef CONFIG_LV_DEMO_MUSIC_SQUARE + #define LV_DEMO_MUSIC_SQUARE CONFIG_LV_DEMO_MUSIC_SQUARE + #else + #define LV_DEMO_MUSIC_SQUARE 0 + #endif + #endif + #ifndef LV_DEMO_MUSIC_LANDSCAPE + #ifdef CONFIG_LV_DEMO_MUSIC_LANDSCAPE + #define LV_DEMO_MUSIC_LANDSCAPE CONFIG_LV_DEMO_MUSIC_LANDSCAPE + #else + #define LV_DEMO_MUSIC_LANDSCAPE 0 + #endif + #endif + #ifndef LV_DEMO_MUSIC_ROUND + #ifdef CONFIG_LV_DEMO_MUSIC_ROUND + #define LV_DEMO_MUSIC_ROUND CONFIG_LV_DEMO_MUSIC_ROUND + #else + #define LV_DEMO_MUSIC_ROUND 0 + #endif + #endif + #ifndef LV_DEMO_MUSIC_LARGE + #ifdef CONFIG_LV_DEMO_MUSIC_LARGE + #define LV_DEMO_MUSIC_LARGE CONFIG_LV_DEMO_MUSIC_LARGE + #else + #define LV_DEMO_MUSIC_LARGE 0 + #endif + #endif + #ifndef LV_DEMO_MUSIC_AUTO_PLAY + #ifdef CONFIG_LV_DEMO_MUSIC_AUTO_PLAY + #define LV_DEMO_MUSIC_AUTO_PLAY CONFIG_LV_DEMO_MUSIC_AUTO_PLAY + #else + #define LV_DEMO_MUSIC_AUTO_PLAY 0 + #endif + #endif +#endif + +/*Flex layout demo*/ +#ifndef LV_USE_DEMO_FLEX_LAYOUT + #ifdef CONFIG_LV_USE_DEMO_FLEX_LAYOUT + #define LV_USE_DEMO_FLEX_LAYOUT CONFIG_LV_USE_DEMO_FLEX_LAYOUT + #else + #define LV_USE_DEMO_FLEX_LAYOUT 0 + #endif +#endif + +/*Smart-phone like multi-language demo*/ +#ifndef LV_USE_DEMO_MULTILANG + #ifdef CONFIG_LV_USE_DEMO_MULTILANG + #define LV_USE_DEMO_MULTILANG CONFIG_LV_USE_DEMO_MULTILANG + #else + #define LV_USE_DEMO_MULTILANG 0 + #endif +#endif + +/*Widget transformation demo*/ +#ifndef LV_USE_DEMO_TRANSFORM + #ifdef CONFIG_LV_USE_DEMO_TRANSFORM + #define LV_USE_DEMO_TRANSFORM CONFIG_LV_USE_DEMO_TRANSFORM + #else + #define LV_USE_DEMO_TRANSFORM 0 + #endif +#endif + +/*Demonstrate scroll settings*/ +#ifndef LV_USE_DEMO_SCROLL + #ifdef CONFIG_LV_USE_DEMO_SCROLL + #define LV_USE_DEMO_SCROLL CONFIG_LV_USE_DEMO_SCROLL + #else + #define LV_USE_DEMO_SCROLL 0 + #endif +#endif + +/*Vector graphic demo*/ +#ifndef LV_USE_DEMO_VECTOR_GRAPHIC + #ifdef CONFIG_LV_USE_DEMO_VECTOR_GRAPHIC + #define LV_USE_DEMO_VECTOR_GRAPHIC CONFIG_LV_USE_DEMO_VECTOR_GRAPHIC + #else + #define LV_USE_DEMO_VECTOR_GRAPHIC 0 + #endif +#endif + + + +/*---------------------------------- + * End of parsing lv_conf_template.h + -----------------------------------*/ + +#ifndef __ASSEMBLY__ +LV_EXPORT_CONST_INT(LV_DPI_DEF); +LV_EXPORT_CONST_INT(LV_DRAW_BUF_STRIDE_ALIGN); +LV_EXPORT_CONST_INT(LV_DRAW_BUF_ALIGN); +#endif + +#undef LV_KCONFIG_PRESENT + +/*Set some defines if a dependency is disabled*/ +#if LV_USE_LOG == 0 + #define LV_LOG_LEVEL LV_LOG_LEVEL_NONE + #define LV_LOG_TRACE_MEM 0 + #define LV_LOG_TRACE_TIMER 0 + #define LV_LOG_TRACE_INDEV 0 + #define LV_LOG_TRACE_DISP_REFR 0 + #define LV_LOG_TRACE_EVENT 0 + #define LV_LOG_TRACE_OBJ_CREATE 0 + #define LV_LOG_TRACE_LAYOUT 0 + #define LV_LOG_TRACE_ANIM 0 +#endif /*LV_USE_LOG*/ + +#if LV_USE_SYSMON == 0 + #define LV_USE_PERF_MONITOR 0 + #define LV_USE_MEM_MONITOR 0 +#endif /*LV_USE_SYSMON*/ + +#ifndef LV_USE_LZ4 + #define LV_USE_LZ4 (LV_USE_LZ4_INTERNAL || LV_USE_LZ4_EXTERNAL) +#endif + +#ifndef LV_USE_THORVG + #define LV_USE_THORVG (LV_USE_THORVG_INTERNAL || LV_USE_THORVG_EXTERNAL) +#endif + +#if LV_USE_OS + #if (LV_USE_FREETYPE || LV_USE_THORVG) && LV_DRAW_THREAD_STACK_SIZE < (32 * 1024) + #warning "Increase LV_DRAW_THREAD_STACK_SIZE to at least 32KB for FreeType or ThorVG." + #endif + + #if defined(LV_DRAW_THREAD_STACKSIZE) && !defined(LV_DRAW_THREAD_STACK_SIZE) + #warning "LV_DRAW_THREAD_STACKSIZE was renamed to LV_DRAW_THREAD_STACK_SIZE. Please update lv_conf.h or run menuconfig again." + #define LV_DRAW_THREAD_STACK_SIZE LV_DRAW_THREAD_STACKSIZE + #endif +#endif + +/*If running without lv_conf.h add typedefs with default value*/ +#ifdef LV_CONF_SKIP + #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) /*Disable warnings for Visual Studio*/ + #define _CRT_SECURE_NO_WARNINGS + #endif +#endif /*defined(LV_CONF_SKIP)*/ + +#endif /*LV_CONF_INTERNAL_H*/ diff --git a/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_anim.c b/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_anim.c new file mode 100644 index 00000000..0e57f243 --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_anim.c @@ -0,0 +1,707 @@ +/** + * @file lv_anim.c + * + */ + +/********************* + * INCLUDES + *********************/ +#include "lv_anim_private.h" + +#include "../core/lv_global.h" +#include "../tick/lv_tick.h" +#include "lv_assert.h" +#include "lv_timer.h" +#include "lv_math.h" +#include "../stdlib/lv_mem.h" +#include "../stdlib/lv_string.h" + +/********************* + * DEFINES + *********************/ +#define LV_ANIM_RESOLUTION 1024 +#define LV_ANIM_RES_SHIFT 10 +#define state LV_GLOBAL_DEFAULT()->anim_state +#define anim_ll_p &(state.anim_ll) + +/********************** + * TYPEDEFS + **********************/ + +/********************** + * STATIC PROTOTYPES + **********************/ +static void anim_timer(lv_timer_t * param); +static void anim_mark_list_change(void); +static void anim_completed_handler(lv_anim_t * a); +static int32_t lv_anim_path_cubic_bezier(const lv_anim_t * a, int32_t x1, + int32_t y1, int32_t x2, int32_t y2); +static uint32_t convert_speed_to_time(uint32_t speed, int32_t start, int32_t end); +static void resolve_time(lv_anim_t * a); +static bool remove_concurrent_anims(lv_anim_t * a_current); +static void remove_anim(void * a); + +/********************** + * STATIC VARIABLES + **********************/ + +/********************** + * MACROS + **********************/ +#if LV_USE_LOG && LV_LOG_TRACE_ANIM + #define LV_TRACE_ANIM(...) LV_LOG_TRACE(__VA_ARGS__) +#else + #define LV_TRACE_ANIM(...) +#endif + +/********************** + * GLOBAL FUNCTIONS + **********************/ + +void lv_anim_core_init(void) +{ + lv_ll_init(anim_ll_p, sizeof(lv_anim_t)); + state.timer = lv_timer_create(anim_timer, LV_DEF_REFR_PERIOD, NULL); + anim_mark_list_change(); /*Turn off the animation timer*/ + state.anim_list_changed = false; + state.anim_run_round = false; +} + +void lv_anim_core_deinit(void) +{ + lv_anim_delete_all(); +} + +void lv_anim_init(lv_anim_t * a) +{ + lv_memzero(a, sizeof(lv_anim_t)); + a->duration = 500; + a->start_value = 0; + a->end_value = 100; + a->repeat_cnt = 1; + a->path_cb = lv_anim_path_linear; + a->early_apply = 1; +} + +lv_anim_t * lv_anim_start(const lv_anim_t * a) +{ + LV_TRACE_ANIM("begin"); + + /*Add the new animation to the animation linked list*/ + lv_anim_t * new_anim = lv_ll_ins_head(anim_ll_p); + LV_ASSERT_MALLOC(new_anim); + if(new_anim == NULL) return NULL; + + /*Initialize the animation descriptor*/ + lv_memcpy(new_anim, a, sizeof(lv_anim_t)); + if(a->var == a) new_anim->var = new_anim; + new_anim->run_round = state.anim_run_round; + new_anim->last_timer_run = lv_tick_get(); + + /*Set the start value*/ + if(new_anim->early_apply) { + if(new_anim->get_value_cb) { + int32_t v_ofs = new_anim->get_value_cb(new_anim); + new_anim->start_value += v_ofs; + new_anim->end_value += v_ofs; + + } + + resolve_time(new_anim); + + /*Do not let two animations for the same 'var' with the same 'exec_cb'*/ + if(a->exec_cb || a->custom_exec_cb) remove_concurrent_anims(new_anim); + + if(new_anim->exec_cb) { + new_anim->exec_cb(new_anim->var, new_anim->start_value); + } + if(new_anim->custom_exec_cb) { + new_anim->custom_exec_cb(new_anim, new_anim->start_value); + } + } + + /*Creating an animation changed the linked list. + *It's important if it happens in a ready callback. (see `anim_timer`)*/ + anim_mark_list_change(); + + LV_TRACE_ANIM("finished"); + return new_anim; +} + +uint32_t lv_anim_get_playtime(const lv_anim_t * a) +{ + if(a->repeat_cnt == LV_ANIM_REPEAT_INFINITE) { + return LV_ANIM_PLAYTIME_INFINITE; + } + + uint32_t repeat_cnt = a->repeat_cnt; + if(repeat_cnt < 1) repeat_cnt = 1; + + uint32_t playtime = a->repeat_delay + a->duration + a->playback_delay + a->playback_duration; + playtime = playtime * a->repeat_cnt; + return playtime; +} + +bool lv_anim_delete(void * var, lv_anim_exec_xcb_t exec_cb) +{ + lv_anim_t * a; + bool del_any = false; + a = lv_ll_get_head(anim_ll_p); + while(a != NULL) { + bool del = false; + if((a->var == var || var == NULL) && (a->exec_cb == exec_cb || exec_cb == NULL)) { + remove_anim(a); + anim_mark_list_change(); /*Read by `anim_timer`. It need to know if a delete occurred in + the linked list*/ + del_any = true; + del = true; + } + + /*Always start from the head on delete, because we don't know + *how `anim_ll_p` was changes in `a->deleted_cb` */ + a = del ? lv_ll_get_head(anim_ll_p) : lv_ll_get_next(anim_ll_p, a); + } + + return del_any; +} + +void lv_anim_delete_all(void) +{ + lv_ll_clear_custom(anim_ll_p, remove_anim); + anim_mark_list_change(); +} + +lv_anim_t * lv_anim_get(void * var, lv_anim_exec_xcb_t exec_cb) +{ + lv_anim_t * a; + LV_LL_READ(anim_ll_p, a) { + if(a->var == var && (a->exec_cb == exec_cb || exec_cb == NULL)) { + return a; + } + } + + return NULL; +} + +lv_timer_t * lv_anim_get_timer(void) +{ + return state.timer; +} + +uint16_t lv_anim_count_running(void) +{ + uint16_t cnt = 0; + lv_anim_t * a; + LV_LL_READ(anim_ll_p, a) cnt++; + + return cnt; +} + +uint32_t lv_anim_speed_clamped(uint32_t speed, uint32_t min_time, uint32_t max_time) +{ + + if(speed > 10000) { + LV_LOG_WARN("speed is truncated to 10000 (was %"LV_PRIu32")", speed); + speed = 10230; + } + if(min_time > 10000) { + LV_LOG_WARN("min_time is truncated to 10000 (was %"LV_PRIu32")", min_time); + min_time = 10230; + } + if(max_time > 10000) { + LV_LOG_WARN("max_time is truncated to 10000 (was %"LV_PRIu32")", max_time); + max_time = 10230; + } + + /*Lower the resolution to fit the 0.1023 range*/ + speed = (speed + 5) / 10; + min_time = (min_time + 5) / 10; + max_time = (max_time + 5) / 10; + + return 0x80000000 + (max_time << 20) + (min_time << 10) + speed; + +} + +uint32_t lv_anim_speed(uint32_t speed) +{ + return lv_anim_speed_clamped(speed, 0, 10000); +} + +uint32_t lv_anim_speed_to_time(uint32_t speed, int32_t start, int32_t end) +{ + uint32_t d = LV_ABS(start - end); + uint32_t time = (d * 1000) / speed; + + time = time == 0 ? 1 : time; + + return time; +} + +void lv_anim_refr_now(void) +{ + anim_timer(NULL); +} + +int32_t lv_anim_path_linear(const lv_anim_t * a) +{ + /*Calculate the current step*/ + int32_t step = lv_map(a->act_time, 0, a->duration, 0, LV_ANIM_RESOLUTION); + + /*Get the new value which will be proportional to `step` + *and the `start` and `end` values*/ + int32_t new_value; + new_value = step * (a->end_value - a->start_value); + new_value = new_value >> LV_ANIM_RES_SHIFT; + new_value += a->start_value; + + return new_value; +} + +int32_t lv_anim_path_ease_in(const lv_anim_t * a) +{ + return lv_anim_path_cubic_bezier(a, LV_BEZIER_VAL_FLOAT(0.42), LV_BEZIER_VAL_FLOAT(0), + LV_BEZIER_VAL_FLOAT(1), LV_BEZIER_VAL_FLOAT(1)); +} + +int32_t lv_anim_path_ease_out(const lv_anim_t * a) +{ + return lv_anim_path_cubic_bezier(a, LV_BEZIER_VAL_FLOAT(0), LV_BEZIER_VAL_FLOAT(0), + LV_BEZIER_VAL_FLOAT(0.58), LV_BEZIER_VAL_FLOAT(1)); +} + +int32_t lv_anim_path_ease_in_out(const lv_anim_t * a) +{ + return lv_anim_path_cubic_bezier(a, LV_BEZIER_VAL_FLOAT(0.42), LV_BEZIER_VAL_FLOAT(0), + LV_BEZIER_VAL_FLOAT(0.58), LV_BEZIER_VAL_FLOAT(1)); +} + +int32_t lv_anim_path_overshoot(const lv_anim_t * a) +{ + return lv_anim_path_cubic_bezier(a, 341, 0, 683, 1300); +} + +int32_t lv_anim_path_bounce(const lv_anim_t * a) +{ + /*Calculate the current step*/ + int32_t t = lv_map(a->act_time, 0, a->duration, 0, LV_BEZIER_VAL_MAX); + int32_t diff = (a->end_value - a->start_value); + + /*3 bounces has 5 parts: 3 down and 2 up. One part is t / 5 long*/ + + if(t < 408) { + /*Go down*/ + t = (t * 2500) >> LV_BEZIER_VAL_SHIFT; /*[0..1024] range*/ + t = LV_BEZIER_VAL_MAX - t; + } + else if(t >= 408 && t < 614) { + /*First bounce back*/ + t -= 408; + t = t * 5; /*to [0..1024] range*/ + diff = diff / 20; + } + else if(t >= 614 && t < 819) { + /*Fall back*/ + t -= 614; + t = t * 5; /*to [0..1024] range*/ + t = LV_BEZIER_VAL_MAX - t; + diff = diff / 20; + } + else if(t >= 819 && t < 921) { + /*Second bounce back*/ + t -= 819; + t = t * 10; /*to [0..1024] range*/ + diff = diff / 40; + } + else if(t >= 921 && t <= LV_BEZIER_VAL_MAX) { + /*Fall back*/ + t -= 921; + t = t * 10; /*to [0..1024] range*/ + t = LV_BEZIER_VAL_MAX - t; + diff = diff / 40; + } + + if(t > LV_BEZIER_VAL_MAX) t = LV_BEZIER_VAL_MAX; + if(t < 0) t = 0; + int32_t step = lv_bezier3(t, 0, 500, 800, LV_BEZIER_VAL_MAX); + + int32_t new_value; + new_value = step * diff; + new_value = new_value >> LV_BEZIER_VAL_SHIFT; + new_value = a->end_value - new_value; + + return new_value; +} + +int32_t lv_anim_path_step(const lv_anim_t * a) +{ + if(a->act_time >= a->duration) + return a->end_value; + else + return a->start_value; +} + +int32_t lv_anim_path_custom_bezier3(const lv_anim_t * a) +{ + const lv_anim_bezier3_para_t * para = &a->parameter.bezier3; + return lv_anim_path_cubic_bezier(a, para->x1, para->y1, para->x2, para->y2); +} + +void lv_anim_set_var(lv_anim_t * a, void * var) +{ + a->var = var; +} + +void lv_anim_set_exec_cb(lv_anim_t * a, lv_anim_exec_xcb_t exec_cb) +{ + a->exec_cb = exec_cb; +} + +void lv_anim_set_duration(lv_anim_t * a, uint32_t duration) +{ + a->duration = duration; +} + +void lv_anim_set_time(lv_anim_t * a, uint32_t duration) +{ + lv_anim_set_duration(a, duration); +} + +void lv_anim_set_delay(lv_anim_t * a, uint32_t delay) +{ + a->act_time = -(int32_t)(delay); +} + +void lv_anim_set_values(lv_anim_t * a, int32_t start, int32_t end) +{ + a->start_value = start; + a->current_value = INT32_MIN; + a->end_value = end; +} + +void lv_anim_set_custom_exec_cb(lv_anim_t * a, lv_anim_custom_exec_cb_t exec_cb) +{ + a->custom_exec_cb = exec_cb; +} + +void lv_anim_set_path_cb(lv_anim_t * a, lv_anim_path_cb_t path_cb) +{ + a->path_cb = path_cb; +} + +void lv_anim_set_start_cb(lv_anim_t * a, lv_anim_start_cb_t start_cb) +{ + a->start_cb = start_cb; +} + +void lv_anim_set_get_value_cb(lv_anim_t * a, lv_anim_get_value_cb_t get_value_cb) +{ + a->get_value_cb = get_value_cb; +} + +void lv_anim_set_completed_cb(lv_anim_t * a, lv_anim_completed_cb_t completed_cb) +{ + a->completed_cb = completed_cb; +} + +void lv_anim_set_deleted_cb(lv_anim_t * a, lv_anim_deleted_cb_t deleted_cb) +{ + a->deleted_cb = deleted_cb; +} + +void lv_anim_set_playback_duration(lv_anim_t * a, uint32_t duration) +{ + a->playback_duration = duration; +} + +void lv_anim_set_playback_time(lv_anim_t * a, uint32_t duration) +{ + lv_anim_set_playback_duration(a, duration); +} + +void lv_anim_set_playback_delay(lv_anim_t * a, uint32_t delay) +{ + a->playback_delay = delay; +} + +void lv_anim_set_repeat_count(lv_anim_t * a, uint32_t cnt) +{ + a->repeat_cnt = cnt; +} + +void lv_anim_set_repeat_delay(lv_anim_t * a, uint32_t delay) +{ + a->repeat_delay = delay; +} + +void lv_anim_set_early_apply(lv_anim_t * a, bool en) +{ + a->early_apply = en; +} + +void lv_anim_set_user_data(lv_anim_t * a, void * user_data) +{ + a->user_data = user_data; +} + +void lv_anim_set_bezier3_param(lv_anim_t * a, int16_t x1, int16_t y1, int16_t x2, int16_t y2) +{ + lv_anim_bezier3_para_t * para = &a->parameter.bezier3; + + para->x1 = x1; + para->x2 = x2; + para->y1 = y1; + para->y2 = y2; +} + +uint32_t lv_anim_get_delay(const lv_anim_t * a) +{ + return -a->act_time; +} + +uint32_t lv_anim_get_time(const lv_anim_t * a) +{ + return a->duration; +} + +uint32_t lv_anim_get_repeat_count(const lv_anim_t * a) +{ + return a->repeat_cnt; +} + +void * lv_anim_get_user_data(const lv_anim_t * a) +{ + return a->user_data; +} + +bool lv_anim_custom_delete(lv_anim_t * a, lv_anim_custom_exec_cb_t exec_cb) +{ + return lv_anim_delete(a ? a->var : NULL, (lv_anim_exec_xcb_t)exec_cb); +} + +lv_anim_t * lv_anim_custom_get(lv_anim_t * a, lv_anim_custom_exec_cb_t exec_cb) +{ + return lv_anim_get(a ? a->var : NULL, (lv_anim_exec_xcb_t)exec_cb); +} + +/********************** + * STATIC FUNCTIONS + **********************/ +/** + * Periodically handle the animations. + * @param param unused + */ +static void anim_timer(lv_timer_t * param) +{ + LV_UNUSED(param); + + /*Flip the run round*/ + state.anim_run_round = state.anim_run_round ? false : true; + + lv_anim_t * a = lv_ll_get_head(anim_ll_p); + + while(a != NULL) { + uint32_t elaps = lv_tick_elaps(a->last_timer_run); + a->act_time += elaps; + + a->last_timer_run = lv_tick_get(); + + /*It can be set by `lv_anim_delete()` typically in `end_cb`. If set then an animation delete + * happened in `anim_completed_handler` which could make this linked list reading corrupt + * because the list is changed meanwhile + */ + state.anim_list_changed = false; + + if(a->run_round != state.anim_run_round) { + a->run_round = state.anim_run_round; /*The list readying might be reset so need to know which anim has run already*/ + + /*The animation will run now for the first time. Call `start_cb`*/ + if(!a->start_cb_called && a->act_time >= 0) { + + if(a->early_apply == 0 && a->get_value_cb) { + int32_t v_ofs = a->get_value_cb(a); + a->start_value += v_ofs; + a->end_value += v_ofs; + } + + resolve_time(a); + + if(a->start_cb) a->start_cb(a); + a->start_cb_called = 1; + + /*Do not let two animations for the same 'var' with the same 'exec_cb'*/ + remove_concurrent_anims(a); + } + + if(a->act_time >= 0) { + if(a->act_time > a->duration) a->act_time = a->duration; + + int32_t new_value; + new_value = a->path_cb(a); + + if(new_value != a->current_value) { + a->current_value = new_value; + /*Apply the calculated value*/ + if(a->exec_cb) a->exec_cb(a->var, new_value); + if(!state.anim_list_changed && a->custom_exec_cb) a->custom_exec_cb(a, new_value); + } + + /*If the time is elapsed the animation is ready*/ + if(!state.anim_list_changed && a->act_time >= a->duration) { + anim_completed_handler(a); + } + } + } + + /*If the linked list changed due to anim. delete then it's not safe to continue + *the reading of the list from here -> start from the head*/ + if(state.anim_list_changed) + a = lv_ll_get_head(anim_ll_p); + else + a = lv_ll_get_next(anim_ll_p, a); + } + +} + +/** + * Called when an animation is completed to do the necessary things + * e.g. repeat, play back, delete etc. + * @param a pointer to an animation descriptor + */ +static void anim_completed_handler(lv_anim_t * a) +{ + /*In the end of a forward anim decrement repeat cnt.*/ + if(a->playback_now == 0 && a->repeat_cnt > 0 && a->repeat_cnt != LV_ANIM_REPEAT_INFINITE) { + a->repeat_cnt--; + } + + /*Delete the animation if + * - no repeat left and no play back (simple one shot animation) + * - no repeat, play back is enabled and play back is ready*/ + if(a->repeat_cnt == 0 && (a->playback_duration == 0 || a->playback_now == 1)) { + + /*Delete the animation from the list. + * This way the `completed_cb` will see the animations like it's animation is already deleted*/ + lv_ll_remove(anim_ll_p, a); + /*Flag that the list has changed*/ + anim_mark_list_change(); + + /*Call the callback function at the end*/ + if(a->completed_cb != NULL) a->completed_cb(a); + if(a->deleted_cb != NULL) a->deleted_cb(a); + lv_free(a); + } + /*If the animation is not deleted then restart it*/ + else { + a->act_time = -(int32_t)(a->repeat_delay); /*Restart the animation*/ + /*Swap the start and end values in play back mode*/ + if(a->playback_duration != 0) { + /*If now turning back use the 'playback_pause*/ + if(a->playback_now == 0) a->act_time = -(int32_t)(a->playback_delay); + + /*Toggle the play back state*/ + a->playback_now = a->playback_now == 0 ? 1 : 0; + /*Swap the start and end values*/ + int32_t tmp = a->start_value; + a->start_value = a->end_value; + a->end_value = tmp; + /*Swap the time and playback_duration*/ + tmp = a->duration; + a->duration = a->playback_duration; + a->playback_duration = tmp; + } + } +} + +static void anim_mark_list_change(void) +{ + state.anim_list_changed = true; + if(lv_ll_get_head(anim_ll_p) == NULL) + lv_timer_pause(state.timer); + else + lv_timer_resume(state.timer); +} + +static int32_t lv_anim_path_cubic_bezier(const lv_anim_t * a, int32_t x1, int32_t y1, int32_t x2, int32_t y2) +{ + /*Calculate the current step*/ + uint32_t t = lv_map(a->act_time, 0, a->duration, 0, LV_BEZIER_VAL_MAX); + int32_t step = lv_cubic_bezier(t, x1, y1, x2, y2); + + int32_t new_value; + new_value = step * (a->end_value - a->start_value); + new_value = new_value >> LV_BEZIER_VAL_SHIFT; + new_value += a->start_value; + + return new_value; +} + +static uint32_t convert_speed_to_time(uint32_t speed_or_time, int32_t start, int32_t end) +{ + /*It was a simple time*/ + if((speed_or_time & 0x80000000) == 0) return speed_or_time; + + uint32_t d = LV_ABS(start - end); + uint32_t speed = speed_or_time & 0x3FF; + uint32_t time = (d * 100) / speed; /*Speed is in 10 units per sec*/ + uint32_t max_time = (speed_or_time >> 20) & 0x3FF; + uint32_t min_time = (speed_or_time >> 10) & 0x3FF; + + return LV_CLAMP(min_time * 10, time, max_time * 10); +} + +static void resolve_time(lv_anim_t * a) +{ + a->duration = convert_speed_to_time(a->duration, a->start_value, a->end_value); + a->playback_duration = convert_speed_to_time(a->playback_duration, a->start_value, a->end_value); + a->playback_delay = convert_speed_to_time(a->playback_delay, a->start_value, a->end_value); + a->repeat_delay = convert_speed_to_time(a->repeat_delay, a->start_value, a->end_value); +} + +/** + * Remove animations which are animating the same var with the same exec_cb + * and they are already running or they have early_apply + * @param a_current the current animation, use its var and exec_cb as reference to know what to remove + * @return true: at least one animation was delete + */ +static bool remove_concurrent_anims(lv_anim_t * a_current) +{ + if(a_current->exec_cb == NULL && a_current->custom_exec_cb == NULL) return false; + + lv_anim_t * a; + bool del_any = false; + a = lv_ll_get_head(anim_ll_p); + while(a != NULL) { + bool del = false; + /*We can't test for custom_exec_cb equality because in the MicroPython binding + *a wrapper callback is used here an the real callback data is stored in the `user_data`. + *Therefore equality check would remove all animations.*/ + if(a != a_current && + (a->act_time >= 0 || a->early_apply) && + (a->var == a_current->var) && + ((a->exec_cb && a->exec_cb == a_current->exec_cb) + /*|| (a->custom_exec_cb && a->custom_exec_cb == a_current->custom_exec_cb)*/)) { + lv_ll_remove(anim_ll_p, a); + if(a->deleted_cb != NULL) a->deleted_cb(a); + lv_free(a); + /*Read by `anim_timer`. It need to know if a delete occurred in the linked list*/ + anim_mark_list_change(); + + del_any = true; + del = true; + } + + /*Always start from the head on delete, because we don't know + *how `anim_ll_p` was changes in `a->deleted_cb` */ + a = del ? lv_ll_get_head(anim_ll_p) : lv_ll_get_next(anim_ll_p, a); + } + + return del_any; +} + +static void remove_anim(void * a) +{ + lv_anim_t * anim = a; + lv_ll_remove(anim_ll_p, a); + if(anim->deleted_cb != NULL) anim->deleted_cb(anim); + lv_free(a); +} diff --git a/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_anim.h b/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_anim.h new file mode 100644 index 00000000..0d626c89 --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_anim.h @@ -0,0 +1,525 @@ +/** + * @file lv_anim.h + * + */ + +#ifndef LV_ANIM_H +#define LV_ANIM_H + +#ifdef __cplusplus +extern "C" { +#endif + +/********************* + * INCLUDES + *********************/ +#include "../lv_conf_internal.h" +#include "lv_types.h" +#include "lv_math.h" +#include "lv_timer.h" +#include "lv_ll.h" + +/********************* + * DEFINES + *********************/ + +#define LV_ANIM_REPEAT_INFINITE 0xFFFFFFFF +#define LV_ANIM_PLAYTIME_INFINITE 0xFFFFFFFF + +/* + * Macros used to set cubic-bezier anim parameter. + * Parameters come from https://easings.net/ + * + * Usage: + * + * lv_anim_t a; + * lv_anim_init(&a); + * ... + * lv_anim_set_path_cb(&a, lv_anim_path_custom_bezier3); + * LV_ANIM_SET_EASE_IN_SINE(&a); //Set cubic-bezier anim parameter to easeInSine + * ... + * lv_anim_start(&a); + */ + +#define _PARA(a, x1, y1, x2, y2) ((a)->parameter.bezier3 = \ +(lv_anim_bezier3_para_t) { \ + LV_BEZIER_VAL_FLOAT(x1), LV_BEZIER_VAL_FLOAT(y1), \ + LV_BEZIER_VAL_FLOAT(x2), LV_BEZIER_VAL_FLOAT(y2) } \ + ) + +#define LV_ANIM_SET_EASE_IN_SINE(a) _PARA(a, 0.12, 0, 0.39, 0) +#define LV_ANIM_SET_EASE_OUT_SINE(a) _PARA(a, 0.61, 1, 0.88, 1) +#define LV_ANIM_SET_EASE_IN_OUT_SINE(a) _PARA(a, 0.37, 0, 0.63, 1) +#define LV_ANIM_SET_EASE_IN_QUAD(a) _PARA(a, 0.11, 0, 0.5, 0) +#define LV_ANIM_SET_EASE_OUT_QUAD(a) _PARA(a, 0.5, 1, 0.89, 1) +#define LV_ANIM_SET_EASE_IN_OUT_QUAD(a) _PARA(a, 0.45, 0, 0.55, 1) +#define LV_ANIM_SET_EASE_IN_CUBIC(a) _PARA(a, 0.32, 0, 0.67, 0) +#define LV_ANIM_SET_EASE_OUT_CUBIC(a) _PARA(a, 0.33, 1, 0.68, 1) +#define LV_ANIM_SET_EASE_IN_OUT_CUBIC(a) _PARA(a, 0.65, 0, 0.35, 1) +#define LV_ANIM_SET_EASE_IN_QUART(a) _PARA(a, 0.5, 0, 0.75, 0) +#define LV_ANIM_SET_EASE_OUT_QUART(a) _PARA(a, 0.25, 1, 0.5, 1) +#define LV_ANIM_SET_EASE_IN_OUT_QUART(a) _PARA(a, 0.76, 0, 0.24, 1) +#define LV_ANIM_SET_EASE_IN_QUINT(a) _PARA(a, 0.64, 0, 0.78, 0) +#define LV_ANIM_SET_EASE_OUT_QUINT(a) _PARA(a, 0.22, 1, 0.36, 1) +#define LV_ANIM_SET_EASE_IN_OUT_QUINT(a) _PARA(a, 0.83, 0, 0.17, 1) +#define LV_ANIM_SET_EASE_IN_EXPO(a) _PARA(a, 0.7, 0, 0.84, 0) +#define LV_ANIM_SET_EASE_OUT_EXPO(a) _PARA(a, 0.16, 1, 0.3, 1) +#define LV_ANIM_SET_EASE_IN_OUT_EXPO(a) _PARA(a, 0.87, 0, 0.13, 1) +#define LV_ANIM_SET_EASE_IN_CIRC(a) _PARA(a, 0.55, 0, 1, 0.45) +#define LV_ANIM_SET_EASE_OUT_CIRC(a) _PARA(a, 0, 0.55, 0.45, 1) +#define LV_ANIM_SET_EASE_IN_OUT_CIRC(a) _PARA(a, 0.85, 0, 0.15, 1) +#define LV_ANIM_SET_EASE_IN_BACK(a) _PARA(a, 0.36, 0, 0.66, -0.56) +#define LV_ANIM_SET_EASE_OUT_BACK(a) _PARA(a, 0.34, 1.56, 0.64, 1) +#define LV_ANIM_SET_EASE_IN_OUT_BACK(a) _PARA(a, 0.68, -0.6, 0.32, 1.6) + +LV_EXPORT_CONST_INT(LV_ANIM_REPEAT_INFINITE); +LV_EXPORT_CONST_INT(LV_ANIM_PLAYTIME_INFINITE); + +/********************** + * TYPEDEFS + **********************/ + +/** Can be used to indicate if animations are enabled or disabled in a case*/ +typedef enum { + LV_ANIM_OFF, + LV_ANIM_ON, +} lv_anim_enable_t; + +/** Get the current value during an animation*/ +typedef int32_t (*lv_anim_path_cb_t)(const lv_anim_t *); + +/** Generic prototype of "animator" functions. + * First parameter is the variable to animate. + * Second parameter is the value to set. + * Compatible with `lv_xxx_set_yyy(obj, value)` functions + * The `x` in `_xcb_t` means it's not a fully generic prototype because + * it doesn't receive `lv_anim_t *` as its first argument*/ +typedef void (*lv_anim_exec_xcb_t)(void *, int32_t); + +/** Same as `lv_anim_exec_xcb_t` but receives `lv_anim_t *` as the first parameter. + * It's more consistent but less convenient. Might be used by binding generator functions.*/ +typedef void (*lv_anim_custom_exec_cb_t)(lv_anim_t *, int32_t); + +/** Callback to call when the animation is ready*/ +typedef void (*lv_anim_completed_cb_t)(lv_anim_t *); + +/** Callback to call when the animation really stars (considering `delay`)*/ +typedef void (*lv_anim_start_cb_t)(lv_anim_t *); + +/** Callback used when the animation values are relative to get the current value*/ +typedef int32_t (*lv_anim_get_value_cb_t)(lv_anim_t *); + +/** Callback used when the animation is deleted*/ +typedef void (*lv_anim_deleted_cb_t)(lv_anim_t *); + +/** Parameter used when path is custom_bezier */ +typedef struct { + int16_t x1; + int16_t y1; + int16_t x2; + int16_t y2; +} lv_anim_bezier3_para_t; + +/** Describes an animation*/ +struct lv_anim_t { + void * var; /**< Variable to animate*/ + lv_anim_exec_xcb_t exec_cb; /**< Function to execute to animate*/ + lv_anim_custom_exec_cb_t custom_exec_cb; /**< Function to execute to animate, + * same purpose as exec_cb but different parameters*/ + lv_anim_start_cb_t start_cb; /**< Call it when the animation is starts (considering `delay`)*/ + lv_anim_completed_cb_t completed_cb; /**< Call it when the animation is fully completed*/ + lv_anim_deleted_cb_t deleted_cb; /**< Call it when the animation is deleted*/ + lv_anim_get_value_cb_t get_value_cb; /**< Get the current value in relative mode*/ + void * user_data; /**< Custom user data*/ + lv_anim_path_cb_t path_cb; /**< Describe the path (curve) of animations*/ + int32_t start_value; /**< Start value*/ + int32_t current_value; /**< Current value*/ + int32_t end_value; /**< End value*/ + int32_t duration; /**< Animation time in ms*/ + int32_t act_time; /**< Current time in animation. Set to negative to make delay.*/ + uint32_t playback_delay; /**< Wait before play back*/ + uint32_t playback_duration; /**< Duration of playback animation*/ + uint32_t repeat_delay; /**< Wait before repeat*/ + uint32_t repeat_cnt; /**< Repeat count for the animation*/ + union lv_anim_path_para_t { + lv_anim_bezier3_para_t bezier3; /**< Parameter used when path is custom_bezier*/ + } parameter; + + /* Animation system use these - user shouldn't set */ + uint32_t last_timer_run; + uint8_t playback_now : 1; /**< Play back is in progress*/ + uint8_t run_round : 1; /**< Indicates the animation has run in this round*/ + uint8_t start_cb_called : 1; /**< Indicates that the `start_cb` was already called*/ + uint8_t early_apply : 1; /**< 1: Apply start value immediately even is there is `delay`*/ +}; + +/********************** + * GLOBAL PROTOTYPES + **********************/ + +/** + * Initialize an animation variable. + * E.g.: + * lv_anim_t a; + * lv_anim_init(&a); + * lv_anim_set_...(&a); + * lv_anim_start(&a); + * @param a pointer to an `lv_anim_t` variable to initialize + */ +void lv_anim_init(lv_anim_t * a); + +/** + * Set a variable to animate + * @param a pointer to an initialized `lv_anim_t` variable + * @param var pointer to a variable to animate + */ +void lv_anim_set_var(lv_anim_t * a, void * var); + +/** + * Set a function to animate `var` + * @param a pointer to an initialized `lv_anim_t` variable + * @param exec_cb a function to execute during animation + * LVGL's built-in functions can be used. + * E.g. lv_obj_set_x + */ +void lv_anim_set_exec_cb(lv_anim_t * a, lv_anim_exec_xcb_t exec_cb); + +/** + * Set the duration of an animation + * @param a pointer to an initialized `lv_anim_t` variable + * @param duration duration of the animation in milliseconds + */ +void lv_anim_set_duration(lv_anim_t * a, uint32_t duration); + +/** + * Legacy `lv_anim_set_time` API will be removed soon, use `lv_anim_set_duration` instead. + */ +void lv_anim_set_time(lv_anim_t * a, uint32_t duration); + +/** + * Set a delay before starting the animation + * @param a pointer to an initialized `lv_anim_t` variable + * @param delay delay before the animation in milliseconds + */ +void lv_anim_set_delay(lv_anim_t * a, uint32_t delay); + +/** + * Set the start and end values of an animation + * @param a pointer to an initialized `lv_anim_t` variable + * @param start the start value + * @param end the end value + */ +void lv_anim_set_values(lv_anim_t * a, int32_t start, int32_t end); + +/** + * Similar to `lv_anim_set_exec_cb` but `lv_anim_custom_exec_cb_t` receives + * `lv_anim_t * ` as its first parameter instead of `void *`. + * This function might be used when LVGL is bound to other languages because + * it's more consistent to have `lv_anim_t *` as first parameter. + * @param a pointer to an initialized `lv_anim_t` variable + * @param exec_cb a function to execute. + */ +void lv_anim_set_custom_exec_cb(lv_anim_t * a, lv_anim_custom_exec_cb_t exec_cb); + +/** + * Set the path (curve) of the animation. + * @param a pointer to an initialized `lv_anim_t` variable + * @param path_cb a function to set the current value of the animation. + */ +void lv_anim_set_path_cb(lv_anim_t * a, lv_anim_path_cb_t path_cb); + +/** + * Set a function call when the animation really starts (considering `delay`) + * @param a pointer to an initialized `lv_anim_t` variable + * @param start_cb a function call when the animation starts + */ +void lv_anim_set_start_cb(lv_anim_t * a, lv_anim_start_cb_t start_cb); + +/** + * Set a function to use the current value of the variable and make start and end value + * relative to the returned current value. + * @param a pointer to an initialized `lv_anim_t` variable + * @param get_value_cb a function call when the animation starts + */ +void lv_anim_set_get_value_cb(lv_anim_t * a, lv_anim_get_value_cb_t get_value_cb); + +/** + * Set a function call when the animation is completed + * @param a pointer to an initialized `lv_anim_t` variable + * @param completed_cb a function call when the animation is fully completed + */ +void lv_anim_set_completed_cb(lv_anim_t * a, lv_anim_completed_cb_t completed_cb); + +/** + * Set a function call when the animation is deleted. + * @param a pointer to an initialized `lv_anim_t` variable + * @param deleted_cb a function call when the animation is deleted + */ +void lv_anim_set_deleted_cb(lv_anim_t * a, lv_anim_deleted_cb_t deleted_cb); + +/** + * Make the animation to play back to when the forward direction is ready + * @param a pointer to an initialized `lv_anim_t` variable + * @param duration duration of playback animation in milliseconds. 0: disable playback + */ +void lv_anim_set_playback_duration(lv_anim_t * a, uint32_t duration); + +/** + * Legacy `lv_anim_set_playback_time` API will be removed soon, use `lv_anim_set_playback_duration` instead. + */ +void lv_anim_set_playback_time(lv_anim_t * a, uint32_t duration); + +/** + * Make the animation to play back to when the forward direction is ready + * @param a pointer to an initialized `lv_anim_t` variable + * @param delay delay in milliseconds before starting the playback animation. + */ +void lv_anim_set_playback_delay(lv_anim_t * a, uint32_t delay); + +/** + * Make the animation repeat itself. + * @param a pointer to an initialized `lv_anim_t` variable + * @param cnt repeat count or `LV_ANIM_REPEAT_INFINITE` for infinite repetition. 0: to disable repetition. + */ +void lv_anim_set_repeat_count(lv_anim_t * a, uint32_t cnt); + +/** + * Set a delay before repeating the animation. + * @param a pointer to an initialized `lv_anim_t` variable + * @param delay delay in milliseconds before repeating the animation. + */ +void lv_anim_set_repeat_delay(lv_anim_t * a, uint32_t delay); + +/** + * Set a whether the animation's should be applied immediately or only when the delay expired. + * @param a pointer to an initialized `lv_anim_t` variable + * @param en true: apply the start value immediately in `lv_anim_start`; + * false: apply the start value only when `delay` ms is elapsed and the animations really starts + */ +void lv_anim_set_early_apply(lv_anim_t * a, bool en); + +/** + * Set the custom user data field of the animation. + * @param a pointer to an initialized `lv_anim_t` variable + * @param user_data pointer to the new user_data. + */ +void lv_anim_set_user_data(lv_anim_t * a, void * user_data); + +/** + * Set parameter for cubic bezier path + * @param a pointer to an initialized `lv_anim_t` variable + * @param x1 first control point X + * @param y1 first control point Y + * @param x2 second control point X + * @param y2 second control point Y + */ +void lv_anim_set_bezier3_param(lv_anim_t * a, int16_t x1, int16_t y1, int16_t x2, int16_t y2); + +/** + * Create an animation + * @param a an initialized 'anim_t' variable. Not required after call. + * @return pointer to the created animation (different from the `a` parameter) + */ +lv_anim_t * lv_anim_start(const lv_anim_t * a); + +/** + * Get a delay before starting the animation + * @param a pointer to an initialized `lv_anim_t` variable + * @return delay before the animation in milliseconds + */ +uint32_t lv_anim_get_delay(const lv_anim_t * a); + +/** + * Get the time used to play the animation. + * @param a pointer to an animation. + * @return the play time in milliseconds. + */ +uint32_t lv_anim_get_playtime(const lv_anim_t * a); + +/** + * Get the duration of an animation + * @param a pointer to an initialized `lv_anim_t` variable + * @return the duration of the animation in milliseconds + */ +uint32_t lv_anim_get_time(const lv_anim_t * a); + +/** + * Get the repeat count of the animation. + * @param a pointer to an initialized `lv_anim_t` variable + * @return the repeat count or `LV_ANIM_REPEAT_INFINITE` for infinite repetition. 0: disabled repetition. + */ +uint32_t lv_anim_get_repeat_count(const lv_anim_t * a); + +/** + * Get the user_data field of the animation + * @param a pointer to an initialized `lv_anim_t` variable + * @return the pointer to the custom user_data of the animation + */ +void * lv_anim_get_user_data(const lv_anim_t * a); + +/** + * Delete animation(s) of a variable with a given animator function + * @param var pointer to variable + * @param exec_cb a function pointer which is animating 'var', + * or NULL to ignore it and delete all the animations of 'var + * @return true: at least 1 animation is deleted, false: no animation is deleted + */ +bool lv_anim_delete(void * var, lv_anim_exec_xcb_t exec_cb); + +/** + * Delete all the animations + */ +void lv_anim_delete_all(void); + +/** + * Get the animation of a variable and its `exec_cb`. + * @param var pointer to variable + * @param exec_cb a function pointer which is animating 'var', or NULL to return first matching 'var' + * @return pointer to the animation. + */ +lv_anim_t * lv_anim_get(void * var, lv_anim_exec_xcb_t exec_cb); + +/** + * Get global animation refresher timer. + * @return pointer to the animation refresher timer. + */ +lv_timer_t * lv_anim_get_timer(void); + +/** + * Delete an animation by getting the animated variable from `a`. + * Only animations with `exec_cb` will be deleted. + * This function exists because it's logical that all anim. functions receives an + * `lv_anim_t` as their first parameter. It's not practical in C but might make + * the API more consequent and makes easier to generate bindings. + * @param a pointer to an animation. + * @param exec_cb a function pointer which is animating 'var', + * or NULL to ignore it and delete all the animations of 'var + * @return true: at least 1 animation is deleted, false: no animation is deleted + */ +bool lv_anim_custom_delete(lv_anim_t * a, lv_anim_custom_exec_cb_t exec_cb); + +/** + * Get the animation of a variable and its `exec_cb`. + * This function exists because it's logical that all anim. functions receives an + * `lv_anim_t` as their first parameter. It's not practical in C but might make + * the API more consequent and makes easier to generate bindings. + * @param a pointer to an animation. + * @param exec_cb a function pointer which is animating 'var', or NULL to return first matching 'var' + * @return pointer to the animation. + */ +lv_anim_t * lv_anim_custom_get(lv_anim_t * a, lv_anim_custom_exec_cb_t exec_cb); + +/** + * Get the number of currently running animations + * @return the number of running animations + */ +uint16_t lv_anim_count_running(void); + +/** + * Store the speed as a special value which can be used as time in animations. + * It will be converted to time internally based on the start and end values + * @param speed the speed of the animation in with unit / sec resolution in 0..10k range + * @return a special value which can be used as an animation time + */ +uint32_t lv_anim_speed(uint32_t speed); + +/** + * Store the speed as a special value which can be used as time in animations. + * It will be converted to time internally based on the start and end values + * @param speed the speed of the animation in as unit / sec resolution in 0..10k range + * @param min_time the minimum time in 0..10k range + * @param max_time the maximum time in 0..10k range + * @return a special value in where all three values are stored and can be used as an animation time + * @note internally speed is stored as 10 unit/sec + * @note internally min/max_time are stored with 10 ms unit + * + */ +uint32_t lv_anim_speed_clamped(uint32_t speed, uint32_t min_time, uint32_t max_time); + +/** + * Calculate the time of an animation based on its speed, start and end values. + * @param speed the speed of the animation + * @param start the start value + * @param end the end value + * @return the time of the animation in milliseconds + */ +uint32_t lv_anim_speed_to_time(uint32_t speed, int32_t start, int32_t end); + +/** + * Manually refresh the state of the animations. + * Useful to make the animations running in a blocking process where + * `lv_timer_handler` can't run for a while. + * Shouldn't be used directly because it is called in `lv_refr_now()`. + */ +void lv_anim_refr_now(void); + +/** + * Calculate the current value of an animation applying linear characteristic + * @param a pointer to an animation + * @return the current value to set + */ +int32_t lv_anim_path_linear(const lv_anim_t * a); + +/** + * Calculate the current value of an animation slowing down the start phase + * @param a pointer to an animation + * @return the current value to set + */ +int32_t lv_anim_path_ease_in(const lv_anim_t * a); + +/** + * Calculate the current value of an animation slowing down the end phase + * @param a pointer to an animation + * @return the current value to set + */ +int32_t lv_anim_path_ease_out(const lv_anim_t * a); + +/** + * Calculate the current value of an animation applying an "S" characteristic (cosine) + * @param a pointer to an animation + * @return the current value to set + */ +int32_t lv_anim_path_ease_in_out(const lv_anim_t * a); + +/** + * Calculate the current value of an animation with overshoot at the end + * @param a pointer to an animation + * @return the current value to set + */ +int32_t lv_anim_path_overshoot(const lv_anim_t * a); + +/** + * Calculate the current value of an animation with 3 bounces + * @param a pointer to an animation + * @return the current value to set + */ +int32_t lv_anim_path_bounce(const lv_anim_t * a); + +/** + * Calculate the current value of an animation applying step characteristic. + * (Set end value on the end of the animation) + * @param a pointer to an animation + * @return the current value to set + */ +int32_t lv_anim_path_step(const lv_anim_t * a); + +/** + * A custom cubic bezier animation path, need to specify cubic-parameters in a->parameter.bezier3 + * @param a pointer to an animation + * @return the current value to set + */ +int32_t lv_anim_path_custom_bezier3(const lv_anim_t * a); + +/********************** + * GLOBAL VARIABLES + **********************/ + +/********************** + * MACROS + **********************/ + +#ifdef __cplusplus +} /*extern "C"*/ +#endif + +#endif /*LV_ANIM_H*/ diff --git a/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_anim_private.h b/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_anim_private.h new file mode 100644 index 00000000..5c258501 --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_anim_private.h @@ -0,0 +1,56 @@ +/** + * @file lv_anim_private.h + * + */ + +#ifndef LV_ANIM_PRIVATE_H +#define LV_ANIM_PRIVATE_H + +#ifdef __cplusplus +extern "C" { +#endif + +/********************* + * INCLUDES + *********************/ + +#include "lv_anim.h" + +/********************* + * DEFINES + *********************/ + +/********************** + * TYPEDEFS + **********************/ + +typedef struct { + bool anim_list_changed; + bool anim_run_round; + lv_timer_t * timer; + lv_ll_t anim_ll; +} lv_anim_state_t; + +/********************** + * GLOBAL PROTOTYPES + **********************/ + +/** + * Init the animation module + */ +void lv_anim_core_init(void); + +/** + * Deinit the animation module + */ +void lv_anim_core_deinit(void); + +/********************** + * MACROS + **********************/ + +#ifdef __cplusplus +} /*extern "C"*/ +#endif + +#endif /*LV_ANIM_PRIVATE_H*/ diff --git a/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_assert.h b/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_assert.h new file mode 100644 index 00000000..c9dc849c --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_assert.h @@ -0,0 +1,87 @@ +/** + * @file lv_assert.h + * + */ + +#ifndef LV_ASSERT_H +#define LV_ASSERT_H + +#ifdef __cplusplus +extern "C" { +#endif + +/********************* + * INCLUDES + *********************/ +#include "../lv_conf_internal.h" +#include "lv_log.h" +#include "../stdlib/lv_mem.h" +#include LV_ASSERT_HANDLER_INCLUDE + +/********************* + * DEFINES + *********************/ + +/********************** + * TYPEDEFS + **********************/ + +/********************** + * GLOBAL PROTOTYPES + **********************/ + +/********************** + * MACROS + **********************/ + +#define LV_ASSERT(expr) \ + do { \ + if(!(expr)) { \ + LV_LOG_ERROR("Asserted at expression: %s", #expr); \ + LV_ASSERT_HANDLER \ + } \ + } while(0) + +#define LV_ASSERT_MSG(expr, msg) \ + do { \ + if(!(expr)) { \ + LV_LOG_ERROR("Asserted at expression: %s (%s)", #expr, msg); \ + LV_ASSERT_HANDLER \ + } \ + } while(0) + +#define LV_ASSERT_FORMAT_MSG(expr, format, ...) \ + do { \ + if(!(expr)) { \ + LV_LOG_ERROR("Asserted at expression: %s " format , #expr, __VA_ARGS__); \ + LV_ASSERT_HANDLER \ + } \ + } while(0) + +/*----------------- + * ASSERTS + *-----------------*/ + +#if LV_USE_ASSERT_NULL +# define LV_ASSERT_NULL(p) LV_ASSERT_MSG(p != NULL, "NULL pointer"); +#else +# define LV_ASSERT_NULL(p) +#endif + +#if LV_USE_ASSERT_MALLOC +# define LV_ASSERT_MALLOC(p) LV_ASSERT_MSG(p != NULL, "Out of memory"); +#else +# define LV_ASSERT_MALLOC(p) +#endif + +#if LV_USE_ASSERT_MEM_INTEGRITY +# define LV_ASSERT_MEM_INTEGRITY() LV_ASSERT_MSG(lv_mem_test() == LV_RESULT_OK, "Memory integrity error"); +#else +# define LV_ASSERT_MEM_INTEGRITY() +#endif + +#ifdef __cplusplus +} /*extern "C"*/ +#endif + +#endif /*LV_ASSERT_H*/ diff --git a/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_ll.c b/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_ll.c new file mode 100644 index 00000000..ca1339ec --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_ll.c @@ -0,0 +1,339 @@ +/** + * @file lv_ll.c + * Handle linked lists. + * The nodes are dynamically allocated by the 'lv_mem' module, + */ + +/********************* + * INCLUDES + *********************/ +#include "lv_ll.h" +#include "../stdlib/lv_mem.h" + +/********************* + * DEFINES + *********************/ +#define LL_NODE_META_SIZE (sizeof(lv_ll_node_t *) + sizeof(lv_ll_node_t *)) +#define LL_PREV_P_OFFSET(ll_p) (ll_p->n_size) +#define LL_NEXT_P_OFFSET(ll_p) (ll_p->n_size + sizeof(lv_ll_node_t *)) + +/********************** + * TYPEDEFS + **********************/ + +/********************** + * STATIC PROTOTYPES + **********************/ +static void node_set_prev(lv_ll_t * ll_p, lv_ll_node_t * act, lv_ll_node_t * prev); +static void node_set_next(lv_ll_t * ll_p, lv_ll_node_t * act, lv_ll_node_t * next); + +/********************** + * STATIC VARIABLES + **********************/ + +/********************** + * MACROS + **********************/ + +/********************** + * GLOBAL FUNCTIONS + **********************/ + +void lv_ll_init(lv_ll_t * ll_p, uint32_t node_size) +{ + ll_p->head = NULL; + ll_p->tail = NULL; +#ifdef LV_ARCH_64 + /*Round the size up to 8*/ + node_size = (node_size + 7) & (~0x7); +#else + /*Round the size up to 4*/ + node_size = (node_size + 3) & (~0x3); +#endif + + ll_p->n_size = node_size; +} + +void * lv_ll_ins_head(lv_ll_t * ll_p) +{ + lv_ll_node_t * n_new; + + n_new = lv_malloc(ll_p->n_size + LL_NODE_META_SIZE); + + if(n_new != NULL) { + node_set_prev(ll_p, n_new, NULL); /*No prev. before the new head*/ + node_set_next(ll_p, n_new, ll_p->head); /*After new comes the old head*/ + + if(ll_p->head != NULL) { /*If there is old head then before it goes the new*/ + node_set_prev(ll_p, ll_p->head, n_new); + } + + ll_p->head = n_new; /*Set the new head in the dsc.*/ + if(ll_p->tail == NULL) { /*If there is no tail (1. node) set the tail too*/ + ll_p->tail = n_new; + } + } + + return n_new; +} + +void * lv_ll_ins_prev(lv_ll_t * ll_p, void * n_act) +{ + lv_ll_node_t * n_new; + + if(NULL == ll_p || NULL == n_act) return NULL; + + if(lv_ll_get_head(ll_p) == n_act) { + n_new = lv_ll_ins_head(ll_p); + if(n_new == NULL) return NULL; + } + else { + n_new = lv_malloc(ll_p->n_size + LL_NODE_META_SIZE); + if(n_new == NULL) return NULL; + + lv_ll_node_t * n_prev; + n_prev = lv_ll_get_prev(ll_p, n_act); + node_set_next(ll_p, n_prev, n_new); + node_set_prev(ll_p, n_new, n_prev); + node_set_prev(ll_p, n_act, n_new); + node_set_next(ll_p, n_new, n_act); + } + + return n_new; +} + +void * lv_ll_ins_tail(lv_ll_t * ll_p) +{ + lv_ll_node_t * n_new; + + n_new = lv_malloc(ll_p->n_size + LL_NODE_META_SIZE); + + if(n_new != NULL) { + node_set_next(ll_p, n_new, NULL); /*No next after the new tail*/ + node_set_prev(ll_p, n_new, ll_p->tail); /*The prev. before new is the old tail*/ + if(ll_p->tail != NULL) { /*If there is old tail then the new comes after it*/ + node_set_next(ll_p, ll_p->tail, n_new); + } + + ll_p->tail = n_new; /*Set the new tail in the dsc.*/ + if(ll_p->head == NULL) { /*If there is no head (1. node) set the head too*/ + ll_p->head = n_new; + } + } + + return n_new; +} + +void lv_ll_remove(lv_ll_t * ll_p, void * node_p) +{ + if(ll_p == NULL) return; + + if(lv_ll_get_head(ll_p) == node_p) { + /*The new head will be the node after 'n_act'*/ + ll_p->head = lv_ll_get_next(ll_p, node_p); + if(ll_p->head == NULL) { + ll_p->tail = NULL; + } + else { + node_set_prev(ll_p, ll_p->head, NULL); + } + } + else if(lv_ll_get_tail(ll_p) == node_p) { + /*The new tail will be the node before 'n_act'*/ + ll_p->tail = lv_ll_get_prev(ll_p, node_p); + if(ll_p->tail == NULL) { + ll_p->head = NULL; + } + else { + node_set_next(ll_p, ll_p->tail, NULL); + } + } + else { + lv_ll_node_t * n_prev = lv_ll_get_prev(ll_p, node_p); + lv_ll_node_t * n_next = lv_ll_get_next(ll_p, node_p); + + node_set_next(ll_p, n_prev, n_next); + node_set_prev(ll_p, n_next, n_prev); + } +} + +void lv_ll_clear_custom(lv_ll_t * ll_p, void(*cleanup)(void *)) +{ + void * i; + void * i_next; + + i = lv_ll_get_head(ll_p); + i_next = NULL; + + while(i != NULL) { + i_next = lv_ll_get_next(ll_p, i); + if(cleanup == NULL) { + lv_ll_remove(ll_p, i); + lv_free(i); + } + else { + cleanup(i); + } + i = i_next; + } +} + +void lv_ll_chg_list(lv_ll_t * ll_ori_p, lv_ll_t * ll_new_p, void * node, bool head) +{ + lv_ll_remove(ll_ori_p, node); + + if(head) { + /*Set node as head*/ + node_set_prev(ll_new_p, node, NULL); + node_set_next(ll_new_p, node, ll_new_p->head); + + if(ll_new_p->head != NULL) { /*If there is old head then before it goes the new*/ + node_set_prev(ll_new_p, ll_new_p->head, node); + } + + ll_new_p->head = node; /*Set the new head in the dsc.*/ + if(ll_new_p->tail == NULL) { /*If there is no tail (first node) set the tail too*/ + ll_new_p->tail = node; + } + } + else { + /*Set node as tail*/ + node_set_prev(ll_new_p, node, ll_new_p->tail); + node_set_next(ll_new_p, node, NULL); + + if(ll_new_p->tail != NULL) { /*If there is old tail then after it goes the new*/ + node_set_next(ll_new_p, ll_new_p->tail, node); + } + + ll_new_p->tail = node; /*Set the new tail in the dsc.*/ + if(ll_new_p->head == NULL) { /*If there is no head (first node) set the head too*/ + ll_new_p->head = node; + } + } +} + +void * lv_ll_get_head(const lv_ll_t * ll_p) +{ + if(ll_p == NULL) return NULL; + return ll_p->head; +} + +void * lv_ll_get_tail(const lv_ll_t * ll_p) +{ + if(ll_p == NULL) return NULL; + return ll_p->tail; +} + +void * lv_ll_get_next(const lv_ll_t * ll_p, const void * n_act) +{ + /*Pointer to the next node is stored in the end of this node. + *Go there and return the address found there*/ + const lv_ll_node_t * n_act_d = n_act; + n_act_d += LL_NEXT_P_OFFSET(ll_p); + return *((lv_ll_node_t **)n_act_d); +} + +void * lv_ll_get_prev(const lv_ll_t * ll_p, const void * n_act) +{ + /*Pointer to the prev. node is stored in the end of this node. + *Go there and return the address found there*/ + const lv_ll_node_t * n_act_d = n_act; + n_act_d += LL_PREV_P_OFFSET(ll_p); + return *((lv_ll_node_t **)n_act_d); +} + +uint32_t lv_ll_get_len(const lv_ll_t * ll_p) +{ + uint32_t len = 0; + void * node; + + for(node = lv_ll_get_head(ll_p); node != NULL; node = lv_ll_get_next(ll_p, node)) { + len++; + } + + return len; +} + +void lv_ll_move_before(lv_ll_t * ll_p, void * n_act, void * n_after) +{ + if(n_act == n_after) return; /*Can't move before itself*/ + + void * n_before; + if(n_after != NULL) + n_before = lv_ll_get_prev(ll_p, n_after); + else + n_before = lv_ll_get_tail(ll_p); /*if `n_after` is NULL `n_act` should be the new tail*/ + + if(n_act == n_before) return; /*Already before `n_after`*/ + + /*It's much easier to remove from the list and add again*/ + lv_ll_remove(ll_p, n_act); + + /*Add again by setting the prev. and next nodes*/ + node_set_next(ll_p, n_before, n_act); + node_set_prev(ll_p, n_act, n_before); + node_set_prev(ll_p, n_after, n_act); + node_set_next(ll_p, n_act, n_after); + + /*If `n_act` was moved before NULL then it become the new tail*/ + if(n_after == NULL) ll_p->tail = n_act; + + /*If `n_act` was moved before `NULL` then it's the new head*/ + if(n_before == NULL) ll_p->head = n_act; +} + +bool lv_ll_is_empty(lv_ll_t * ll_p) +{ + if(ll_p == NULL) return true; + + if(ll_p->head == NULL && ll_p->tail == NULL) return true; + + return false; +} + +void lv_ll_clear(lv_ll_t * ll_p) +{ + lv_ll_clear_custom(ll_p, NULL); +} + +/********************** + * STATIC FUNCTIONS + **********************/ + +/** + * Set the previous node pointer of a node + * @param ll_p pointer to linked list + * @param act pointer to a node which prev. node pointer should be set + * @param prev pointer to a node which should be the previous node before 'act' + */ +static void node_set_prev(lv_ll_t * ll_p, lv_ll_node_t * act, lv_ll_node_t * prev) +{ + if(act == NULL) return; /*Can't set the prev node of `NULL`*/ + + uint8_t * act8 = (uint8_t *)act; + + act8 += LL_PREV_P_OFFSET(ll_p); + + lv_ll_node_t ** act_node_p = (lv_ll_node_t **) act8; + lv_ll_node_t ** prev_node_p = (lv_ll_node_t **) &prev; + + *act_node_p = *prev_node_p; +} + +/** + * Set the 'next node pointer' of a node + * @param ll_p pointer to linked list + * @param act pointer to a node which next node pointer should be set + * @param next pointer to a node which should be the next node before 'act' + */ +static void node_set_next(lv_ll_t * ll_p, lv_ll_node_t * act, lv_ll_node_t * next) +{ + if(act == NULL) return; /*Can't set the next node of `NULL`*/ + uint8_t * act8 = (uint8_t *)act; + + act8 += LL_NEXT_P_OFFSET(ll_p); + lv_ll_node_t ** act_node_p = (lv_ll_node_t **) act8; + lv_ll_node_t ** next_node_p = (lv_ll_node_t **) &next; + + *act_node_p = *next_node_p; +} diff --git a/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_ll.h b/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_ll.h new file mode 100644 index 00000000..ee0836ef --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_ll.h @@ -0,0 +1,169 @@ +/** + * @file lv_ll.h + * Handle linked lists. The nodes are dynamically allocated by the 'lv_mem' module. + */ + +#ifndef LV_LL_H +#define LV_LL_H + +#ifdef __cplusplus +extern "C" { +#endif + +/********************* + * INCLUDES + *********************/ +#include "../lv_conf_internal.h" +#include "lv_types.h" + +/********************* + * DEFINES + *********************/ + +/********************** + * TYPEDEFS + **********************/ + +/** Dummy type to make handling easier*/ +typedef uint8_t lv_ll_node_t; + +/** Description of a linked list*/ +typedef struct { + uint32_t n_size; + lv_ll_node_t * head; + lv_ll_node_t * tail; +} lv_ll_t; + +/********************** + * GLOBAL PROTOTYPES + **********************/ + +/** + * Initialize linked list + * @param ll_p pointer to lv_ll_t variable + * @param node_size the size of 1 node in bytes + */ +void lv_ll_init(lv_ll_t * ll_p, uint32_t node_size); + +/** + * Add a new head to a linked list + * @param ll_p pointer to linked list + * @return pointer to the new head + */ +void * lv_ll_ins_head(lv_ll_t * ll_p); + +/** + * Insert a new node in front of the n_act node + * @param ll_p pointer to linked list + * @param n_act pointer a node + * @return pointer to the new node + */ +void * lv_ll_ins_prev(lv_ll_t * ll_p, void * n_act); + +/** + * Add a new tail to a linked list + * @param ll_p pointer to linked list + * @return pointer to the new tail + */ +void * lv_ll_ins_tail(lv_ll_t * ll_p); + +/** + * Remove the node 'node_p' from 'll_p' linked list. + * It does not free the memory of node. + * @param ll_p pointer to the linked list of 'node_p' + * @param node_p pointer to node in 'll_p' linked list + */ +void lv_ll_remove(lv_ll_t * ll_p, void * node_p); + +void lv_ll_clear_custom(lv_ll_t * ll_p, void(*cleanup)(void *)); + +/** + * Remove and free all elements from a linked list. The list remain valid but become empty. + * @param ll_p pointer to linked list + */ +void lv_ll_clear(lv_ll_t * ll_p); + +/** + * Move a node to a new linked list + * @param ll_ori_p pointer to the original (old) linked list + * @param ll_new_p pointer to the new linked list + * @param node pointer to a node + * @param head true: be the head in the new list + * false be the tail in the new list + */ +void lv_ll_chg_list(lv_ll_t * ll_ori_p, lv_ll_t * ll_new_p, void * node, bool head); + +/** + * Return with head node of the linked list + * @param ll_p pointer to linked list + * @return pointer to the head of 'll_p' + */ +void * lv_ll_get_head(const lv_ll_t * ll_p); + +/** + * Return with tail node of the linked list + * @param ll_p pointer to linked list + * @return pointer to the tail of 'll_p' + */ +void * lv_ll_get_tail(const lv_ll_t * ll_p); + +/** + * Return with the pointer of the next node after 'n_act' + * @param ll_p pointer to linked list + * @param n_act pointer a node + * @return pointer to the next node + */ +void * lv_ll_get_next(const lv_ll_t * ll_p, const void * n_act); + +/** + * Return with the pointer of the previous node after 'n_act' + * @param ll_p pointer to linked list + * @param n_act pointer a node + * @return pointer to the previous node + */ +void * lv_ll_get_prev(const lv_ll_t * ll_p, const void * n_act); + +/** + * Return the length of the linked list. + * @param ll_p pointer to linked list + * @return length of the linked list + */ +uint32_t lv_ll_get_len(const lv_ll_t * ll_p); + +/* + * TODO + * @param ll_p + * @param n1_p + * @param n2_p +void lv_ll_swap(lv_ll_t * ll_p, void * n1_p, void * n2_p); + */ + +/** + * Move a node before another node in the same linked list + * + * @param ll_p pointer to a linked list + * @param n_act pointer to node to move + * @param n_after pointer to a node which should be after `n_act` + */ +void lv_ll_move_before(lv_ll_t * ll_p, void * n_act, void * n_after); + +/** + * Check if a linked list is empty + * @param ll_p pointer to a linked list + * @return true: the linked list is empty; false: not empty + */ +bool lv_ll_is_empty(lv_ll_t * ll_p); + +/********************** + * MACROS + **********************/ + +#define LV_LL_READ(list, i) for(i = lv_ll_get_head(list); i != NULL; i = lv_ll_get_next(list, i)) + +#define LV_LL_READ_BACK(list, i) for(i = lv_ll_get_tail(list); i != NULL; i = lv_ll_get_prev(list, i)) + +#ifdef __cplusplus +} /*extern "C"*/ +#endif + +#endif diff --git a/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_log.h b/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_log.h new file mode 100644 index 00000000..7774ba6f --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_log.h @@ -0,0 +1,162 @@ +/** + * @file lv_log.h + * + */ + +#ifndef LV_LOG_H +#define LV_LOG_H + +#ifdef __cplusplus +extern "C" { +#endif + +/********************* + * INCLUDES + *********************/ +#include "../lv_conf_internal.h" + +#include "lv_types.h" + +/********************* + * DEFINES + *********************/ + +/*Possible log level. For compatibility declare it independently from `LV_USE_LOG`*/ + +#define LV_LOG_LEVEL_TRACE 0 /**< Log detailed information. */ +#define LV_LOG_LEVEL_INFO 1 /**< Log important events. */ +#define LV_LOG_LEVEL_WARN 2 /**< Log if something unwanted happened but didn't caused problem. */ +#define LV_LOG_LEVEL_ERROR 3 /**< Log only critical issues, when system may fail. */ +#define LV_LOG_LEVEL_USER 4 /**< Log only custom log messages added by the user. */ +#define LV_LOG_LEVEL_NONE 5 /**< Do not log anything. */ +#define LV_LOG_LEVEL_NUM 6 /**< Number of log levels */ + +LV_EXPORT_CONST_INT(LV_LOG_LEVEL_TRACE); +LV_EXPORT_CONST_INT(LV_LOG_LEVEL_INFO); +LV_EXPORT_CONST_INT(LV_LOG_LEVEL_WARN); +LV_EXPORT_CONST_INT(LV_LOG_LEVEL_ERROR); +LV_EXPORT_CONST_INT(LV_LOG_LEVEL_USER); +LV_EXPORT_CONST_INT(LV_LOG_LEVEL_NONE); + +typedef int8_t lv_log_level_t; + +#if LV_USE_LOG + +#if LV_LOG_USE_FILE_LINE +#define LV_LOG_FILE __FILE__ +#define LV_LOG_LINE __LINE__ +#else +#define LV_LOG_FILE NULL +#define LV_LOG_LINE 0 +#endif + +/********************** + * TYPEDEFS + **********************/ + +/** + * Log print function. Receives a string buffer to print". + */ +typedef void (*lv_log_print_g_cb_t)(lv_log_level_t level, const char * buf); + +/********************** + * GLOBAL PROTOTYPES + **********************/ + +/** + * Register custom print/write function to call when a log is added. + * It can format its "File path", "Line number" and "Description" as required + * and send the formatted log message to a console or serial port. + * @param print_cb a function pointer to print a log + */ +void lv_log_register_print_cb(lv_log_print_g_cb_t print_cb); + +/** + * Print a log message via `printf` if enabled with `LV_LOG_PRINTF` in `lv_conf.h` + * and/or a print callback if registered with `lv_log_register_print_cb` + * @param format printf-like format string + * @param ... parameters for `format` + */ +void lv_log(const char * format, ...) LV_FORMAT_ATTRIBUTE(1, 2); + +/** + * Add a log + * @param level the level of log. (From `lv_log_level_t` enum) + * @param file name of the file when the log added + * @param line line number in the source code where the log added + * @param func name of the function when the log added + * @param format printf-like format string + * @param ... parameters for `format` + */ +void lv_log_add(lv_log_level_t level, const char * file, int line, + const char * func, const char * format, ...) LV_FORMAT_ATTRIBUTE(5, 6); + +/********************** + * MACROS + **********************/ +#ifndef LV_LOG_TRACE +# if LV_LOG_LEVEL <= LV_LOG_LEVEL_TRACE +# define LV_LOG_TRACE(...) lv_log_add(LV_LOG_LEVEL_TRACE, LV_LOG_FILE, LV_LOG_LINE, __func__, __VA_ARGS__) +# else +# define LV_LOG_TRACE(...) do {}while(0) +# endif +#endif + +#ifndef LV_LOG_INFO +# if LV_LOG_LEVEL <= LV_LOG_LEVEL_INFO +# define LV_LOG_INFO(...) lv_log_add(LV_LOG_LEVEL_INFO, LV_LOG_FILE, LV_LOG_LINE, __func__, __VA_ARGS__) +# else +# define LV_LOG_INFO(...) do {}while(0) +# endif +#endif + +#ifndef LV_LOG_WARN +# if LV_LOG_LEVEL <= LV_LOG_LEVEL_WARN +# define LV_LOG_WARN(...) lv_log_add(LV_LOG_LEVEL_WARN, LV_LOG_FILE, LV_LOG_LINE, __func__, __VA_ARGS__) +# else +# define LV_LOG_WARN(...) do {}while(0) +# endif +#endif + +#ifndef LV_LOG_ERROR +# if LV_LOG_LEVEL <= LV_LOG_LEVEL_ERROR +# define LV_LOG_ERROR(...) lv_log_add(LV_LOG_LEVEL_ERROR, LV_LOG_FILE, LV_LOG_LINE, __func__, __VA_ARGS__) +# else +# define LV_LOG_ERROR(...) do {}while(0) +# endif +#endif + +#ifndef LV_LOG_USER +# if LV_LOG_LEVEL <= LV_LOG_LEVEL_USER +# define LV_LOG_USER(...) lv_log_add(LV_LOG_LEVEL_USER, LV_LOG_FILE, LV_LOG_LINE, __func__, __VA_ARGS__) +# else +# define LV_LOG_USER(...) do {}while(0) +# endif +#endif + +#ifndef LV_LOG +# if LV_LOG_LEVEL < LV_LOG_LEVEL_NONE +# define LV_LOG(...) lv_log(__VA_ARGS__) +# else +# define LV_LOG(...) do {} while(0) +# endif +#endif + +#else /*LV_USE_LOG*/ + +/*Do nothing if `LV_USE_LOG 0`*/ +#define lv_log_add(level, file, line, ...) +#define LV_LOG_TRACE(...) do {}while(0) +#define LV_LOG_INFO(...) do {}while(0) +#define LV_LOG_WARN(...) do {}while(0) +#define LV_LOG_ERROR(...) do {}while(0) +#define LV_LOG_USER(...) do {}while(0) +#define LV_LOG(...) do {}while(0) + +#endif /*LV_USE_LOG*/ + +#ifdef __cplusplus +} /*extern "C"*/ +#endif + +#endif /*LV_LOG_H*/ diff --git a/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_math.c b/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_math.c new file mode 100644 index 00000000..bd728fbc --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_math.c @@ -0,0 +1,456 @@ +/** + * @file lv_math.c + * + */ + +/********************* + * INCLUDES + *********************/ +#include "lv_math.h" +#include "../core/lv_global.h" + +/********************* + * DEFINES + *********************/ +#define rand_seed LV_GLOBAL_DEFAULT()->math_rand_seed + +/********************** + * TYPEDEFS + **********************/ + +#define CUBIC_NEWTON_ITERATIONS 8 +#define CUBIC_PRECISION_BITS 10 /* 10 or 14 bits recommended, int64_t calculation is used for >14bit precision */ + +#if CUBIC_PRECISION_BITS < 10 || CUBIC_PRECISION_BITS > 20 + #error "cubic precision bits should be in range of [10, 20] for 32bit/64bit calculations." +#endif + +/********************** + * STATIC PROTOTYPES + **********************/ + +/********************** + * STATIC VARIABLES + **********************/ +static const uint16_t sin0_90_table[] = { + 0, 572, 1144, 1715, 2286, 2856, 3425, 3993, 4560, 5126, 5690, 6252, 6813, 7371, 7927, 8481, + 9032, 9580, 10126, 10668, 11207, 11743, 12275, 12803, 13328, 13848, 14365, 14876, 15384, 15886, 16384, 16877, + 17364, 17847, 18324, 18795, 19261, 19720, 20174, 20622, 21063, 21498, 21926, 22348, 22763, 23170, 23571, 23965, + 24351, 24730, 25102, 25466, 25822, 26170, 26510, 26842, 27166, 27482, 27789, 28088, 28378, 28660, 28932, 29197, + 29452, 29698, 29935, 30163, 30382, 30592, 30792, 30983, 31164, 31336, 31499, 31651, 31795, 31928, 32052, 32166, + 32270, 32365, 32449, 32524, 32588, 32643, 32688, 32723, 32748, 32763, 32768 +}; + +/********************** + * MACROS + **********************/ + +/********************** + * GLOBAL FUNCTIONS + **********************/ + +int32_t LV_ATTRIBUTE_FAST_MEM lv_trigo_sin(int16_t angle) +{ + int32_t ret = 0; + while(angle < 0) angle += 360; + while(angle >= 360) angle -= 360; + + if(angle < 90) { + ret = sin0_90_table[angle]; + } + else if(angle >= 90 && angle < 180) { + angle = 180 - angle; + ret = sin0_90_table[angle]; + } + else if(angle >= 180 && angle < 270) { + angle = angle - 180; + ret = -sin0_90_table[angle]; + } + else { /*angle >=270*/ + angle = 360 - angle; + ret = -sin0_90_table[angle]; + } + + if(ret == 32767) return 32768; + else if(ret == -32767) return -32768; + else return ret; +} + +/** + * cubic-bezier Reference: + * + * https://github.com/gre/bezier-easing + * https://opensource.apple.com/source/WebCore/WebCore-955.66/platform/graphics/UnitBezier.h + * + * Copyright (c) 2014 Gaëtan Renaudeau + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + */ + +static int32_t do_cubic_bezier(int32_t t, int32_t a, int32_t b, int32_t c) +{ + /*a * t^3 + b * t^2 + c * t*/ +#if CUBIC_PRECISION_BITS > 14 + int64_t ret; +#else + int32_t ret; +#endif + + ret = a; + ret = (ret * t) >> CUBIC_PRECISION_BITS; + ret = ((ret + b) * t) >> CUBIC_PRECISION_BITS; + ret = ((ret + c) * t) >> CUBIC_PRECISION_BITS; + return ret; +} + +int32_t lv_cubic_bezier(int32_t x, int32_t x1, int32_t y1, int32_t x2, int32_t y2) +{ + int32_t ax, bx, cx, ay, by, cy; + int32_t tl, tr, t; /*t in cubic-bezier function, used for bisection */ + int32_t xs; /*x sampled on curve */ +#if CUBIC_PRECISION_BITS > 14 + int64_t d; /*slope value at specified t*/ +#else + int32_t d; +#endif + + if(x == 0 || x == LV_BEZIER_VAL_MAX) return x; + + /* input is always LV_BEZIER_VAL_SHIFT bit precision */ + +#if CUBIC_PRECISION_BITS != LV_BEZIER_VAL_SHIFT + x <<= CUBIC_PRECISION_BITS - LV_BEZIER_VAL_SHIFT; + x1 <<= CUBIC_PRECISION_BITS - LV_BEZIER_VAL_SHIFT; + x2 <<= CUBIC_PRECISION_BITS - LV_BEZIER_VAL_SHIFT; + y1 <<= CUBIC_PRECISION_BITS - LV_BEZIER_VAL_SHIFT; + y2 <<= CUBIC_PRECISION_BITS - LV_BEZIER_VAL_SHIFT; +#endif + + cx = 3 * x1; + bx = 3 * (x2 - x1) - cx; + ax = (1L << CUBIC_PRECISION_BITS) - cx - bx; + + cy = 3 * y1; + by = 3 * (y2 - y1) - cy; + ay = (1L << CUBIC_PRECISION_BITS) - cy - by; + + /*Try Newton's method firstly */ + t = x; /*Make a guess*/ + for(int i = 0; i < CUBIC_NEWTON_ITERATIONS; i++) { + /*Check if x on curve at t matches input x*/ + xs = do_cubic_bezier(t, ax, bx, cx) - x; + if(LV_ABS(xs) <= 1) goto found; + + /* get slop at t, d = 3 * ax * t^2 + 2 * bx + t + cx */ + d = ax; /* use 64bit operation if needed. */ + d = (3 * d * t) >> CUBIC_PRECISION_BITS; + d = ((d + 2 * bx) * t) >> CUBIC_PRECISION_BITS; + d += cx; + + if(LV_ABS(d) <= 1) break; + + d = ((int64_t)xs * (1L << CUBIC_PRECISION_BITS)) / d; + if(d == 0) break; /*Reached precision limits*/ + t -= d; + } + + /*Fallback to bisection method for reliability*/ + tl = 0, tr = 1L << CUBIC_PRECISION_BITS, t = x; + + if(t < tl) { + t = tl; + goto found; + } + + if(t > tr) { + t = tr; + goto found; + } + + while(tl < tr) { + xs = do_cubic_bezier(t, ax, bx, cx); + if(LV_ABS(xs - x) <= 1) goto found; + x > xs ? (tl = t) : (tr = t); + t = (tr - tl) / 2 + tl; + if(t == tl) break; + } + + /*Failed to find suitable t for given x, return a value anyway.*/ +found: + /*Return y at t*/ +#if CUBIC_PRECISION_BITS != LV_BEZIER_VAL_SHIFT + return do_cubic_bezier(t, ay, by, cy) >> (CUBIC_PRECISION_BITS - LV_BEZIER_VAL_SHIFT); +#else + return do_cubic_bezier(t, ay, by, cy); +#endif +} + +void LV_ATTRIBUTE_FAST_MEM lv_sqrt(uint32_t x, lv_sqrt_res_t * q, uint32_t mask) +{ + x = x << 8; /*To get 4 bit precision. (sqrt(256) = 16 = 4 bit)*/ + + uint32_t root = 0; + uint32_t trial; + /*http://ww1.microchip.com/...en/AppNotes/91040a.pdf*/ + do { + trial = root + mask; + if(trial * trial <= x) root = trial; + mask = mask >> 1; + } while(mask); + + q->i = root >> 4; + q->f = (root & 0xf) << 4; +} + +/* +// Alternative Integer Square Root function +// Contributors include Arne Steinarson for the basic approximation idea, +// Dann Corbit and Mathew Hendry for the first cut at the algorithm, +// Lawrence Kirby for the rearrangement, improvements and range optimization +// and Paul Hsieh for the round-then-adjust idea. +*/ +int32_t LV_ATTRIBUTE_FAST_MEM lv_sqrt32(uint32_t x) +{ + static const unsigned char sqq_table[] = { + 0, 16, 22, 27, 32, 35, 39, 42, 45, 48, 50, 53, 55, 57, + 59, 61, 64, 65, 67, 69, 71, 73, 75, 76, 78, 80, 81, 83, + 84, 86, 87, 89, 90, 91, 93, 94, 96, 97, 98, 99, 101, 102, + 103, 104, 106, 107, 108, 109, 110, 112, 113, 114, 115, 116, 117, 118, + 119, 120, 121, 122, 123, 124, 125, 126, 128, 128, 129, 130, 131, 132, + 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 144, 145, + 146, 147, 148, 149, 150, 150, 151, 152, 153, 154, 155, 155, 156, 157, + 158, 159, 160, 160, 161, 162, 163, 163, 164, 165, 166, 167, 167, 168, + 169, 170, 170, 171, 172, 173, 173, 174, 175, 176, 176, 177, 178, 178, + 179, 180, 181, 181, 182, 183, 183, 184, 185, 185, 186, 187, 187, 188, + 189, 189, 190, 191, 192, 192, 193, 193, 194, 195, 195, 196, 197, 197, + 198, 199, 199, 200, 201, 201, 202, 203, 203, 204, 204, 205, 206, 206, + 207, 208, 208, 209, 209, 210, 211, 211, 212, 212, 213, 214, 214, 215, + 215, 216, 217, 217, 218, 218, 219, 219, 220, 221, 221, 222, 222, 223, + 224, 224, 225, 225, 226, 226, 227, 227, 228, 229, 229, 230, 230, 231, + 231, 232, 232, 233, 234, 234, 235, 235, 236, 236, 237, 237, 238, 238, + 239, 240, 240, 241, 241, 242, 242, 243, 243, 244, 244, 245, 245, 246, + 246, 247, 247, 248, 248, 249, 249, 250, 250, 251, 251, 252, 252, 253, + 253, 254, 254, 255 + }; + + int32_t xn; + + if(x >= 0x10000) + if(x >= 0x1000000) + if(x >= 0x10000000) + if(x >= 0x40000000) { + if(x >= 65535UL * 65535UL) + return 65535; + xn = sqq_table[x >> 24] << 8; + } + else + xn = sqq_table[x >> 22] << 7; + else if(x >= 0x4000000) + xn = sqq_table[x >> 20] << 6; + else + xn = sqq_table[x >> 18] << 5; + else { + if(x >= 0x100000) + if(x >= 0x400000) + xn = sqq_table[x >> 16] << 4; + else + xn = sqq_table[x >> 14] << 3; + else if(x >= 0x40000) + xn = sqq_table[x >> 12] << 2; + else + xn = sqq_table[x >> 10] << 1; + + goto nr1; + } + else if(x >= 0x100) { + if(x >= 0x1000) + if(x >= 0x4000) + xn = (sqq_table[x >> 8] >> 0) + 1; + else + xn = (sqq_table[x >> 6] >> 1) + 1; + else if(x >= 0x400) + xn = (sqq_table[x >> 4] >> 2) + 1; + else + xn = (sqq_table[x >> 2] >> 3) + 1; + + goto adj; + } + else + return sqq_table[x] >> 4; + + /* Run two iterations of the standard convergence formula */ + + xn = (xn + 1 + x / xn) / 2; +nr1: + xn = (xn + 1 + x / xn) / 2; +adj: + + if(xn * xn > (int32_t)x) /* Correct rounding if necessary */ + xn--; + + return xn; +} + +uint16_t lv_atan2(int x, int y) +{ + /** + * Fast XY vector to integer degree algorithm - Jan 2011 www.RomanBlack.com + * Converts any XY values including 0 to a degree value that should be + * within +/- 1 degree of the accurate value without needing + * large slow trig functions like ArcTan() or ArcCos(). + * NOTE! at least one of the X or Y values must be non-zero! + * This is the full version, for all 4 quadrants and will generate + * the angle in integer degrees from 0-360. + * Any values of X and Y are usable including negative values provided + * they are between -1456 and 1456 so the 16bit multiply does not overflow. + */ + unsigned char negflag; + unsigned char tempdegree; + unsigned char comp; + unsigned int degree; /*this will hold the result*/ + unsigned int ux; + unsigned int uy; + + /*Save the sign flags then remove signs and get XY as unsigned ints*/ + negflag = 0; + if(x < 0) { + negflag += 0x01; /*x flag bit*/ + x = (0 - x); /*is now +*/ + } + ux = x; /*copy to unsigned var before multiply*/ + if(y < 0) { + negflag += 0x02; /*y flag bit*/ + y = (0 - y); /*is now +*/ + } + uy = y; /*copy to unsigned var before multiply*/ + + /*1. Calc the scaled "degrees"*/ + if(ux > uy) { + degree = (uy * 45) / ux; /*degree result will be 0-45 range*/ + negflag += 0x10; /*octant flag bit*/ + } + else { + degree = (ux * 45) / uy; /*degree result will be 0-45 range*/ + } + + /*2. Compensate for the 4 degree error curve*/ + comp = 0; + tempdegree = degree; /*use an unsigned char for speed!*/ + if(tempdegree > 22) { /*if top half of range*/ + if(tempdegree <= 44) comp++; + if(tempdegree <= 41) comp++; + if(tempdegree <= 37) comp++; + if(tempdegree <= 32) comp++; /*max is 4 degrees compensated*/ + } + else { /*else is lower half of range*/ + if(tempdegree >= 2) comp++; + if(tempdegree >= 6) comp++; + if(tempdegree >= 10) comp++; + if(tempdegree >= 15) comp++; /*max is 4 degrees compensated*/ + } + degree += comp; /*degree is now accurate to +/- 1 degree!*/ + + /*Invert degree if it was X>Y octant, makes 0-45 into 90-45*/ + if(negflag & 0x10) degree = (90 - degree); + + /*3. Degree is now 0-90 range for this quadrant,*/ + /*need to invert it for whichever quadrant it was in*/ + if(negflag & 0x02) { /*if -Y*/ + if(negflag & 0x01) /*if -Y -X*/ + degree = (180 + degree); + else /*else is -Y +X*/ + degree = (180 - degree); + } + else { /*else is +Y*/ + if(negflag & 0x01) /*if +Y -X*/ + degree = (360 - degree); + } + return degree; +} + +int64_t lv_pow(int64_t base, int8_t exp) +{ + int64_t result = 1; + while(exp) { + if(exp & 1) + result *= base; + exp >>= 1; + base *= base; + } + + return result; +} + +int32_t lv_map(int32_t x, int32_t min_in, int32_t max_in, int32_t min_out, int32_t max_out) +{ + if(max_in >= min_in && x >= max_in) return max_out; + if(max_in >= min_in && x <= min_in) return min_out; + + if(max_in <= min_in && x <= max_in) return max_out; + if(max_in <= min_in && x >= min_in) return min_out; + + /** + * The equation should be: + * ((x - min_in) * delta_out) / delta in) + min_out + * To avoid rounding error reorder the operations: + * (x - min_in) * (delta_out / delta_min) + min_out + */ + + int32_t delta_in = max_in - min_in; + int32_t delta_out = max_out - min_out; + + return ((x - min_in) * delta_out) / delta_in + min_out; +} + +void lv_rand_set_seed(uint32_t seed) +{ + rand_seed = seed; +} + +uint32_t lv_rand(uint32_t min, uint32_t max) +{ + /*Algorithm "xor" from p. 4 of Marsaglia, "Xorshift RNGs"*/ + uint32_t x = rand_seed; + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + rand_seed = x; + + return (rand_seed % (max - min + 1)) + min; +} + +int32_t LV_ATTRIBUTE_FAST_MEM lv_trigo_cos(int16_t angle) +{ + return lv_trigo_sin(angle + 90); +} + +int32_t lv_bezier3(int32_t t, int32_t u0, uint32_t u1, int32_t u2, int32_t u3) +{ + LV_UNUSED(u0); + LV_UNUSED(u3); + return lv_cubic_bezier(t, 341, u1, 683, u2); +} + +/********************** + * STATIC FUNCTIONS + **********************/ diff --git a/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_math.h b/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_math.h new file mode 100644 index 00000000..05e159f1 --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_math.h @@ -0,0 +1,181 @@ +/** + * @file lv_math.h + * + */ + +#ifndef LV_MATH_H +#define LV_MATH_H + +#ifdef __cplusplus +extern "C" { +#endif + +/********************* + * INCLUDES + *********************/ +#include "../lv_conf_internal.h" +#include "lv_types.h" + +/********************* + * DEFINES + *********************/ +#define LV_TRIGO_SIN_MAX 32768 +#define LV_TRIGO_SHIFT 15 /**< >> LV_TRIGO_SHIFT to normalize*/ + +#define LV_BEZIER_VAL_SHIFT 10 /**< log2(LV_BEZIER_VAL_MAX): used to normalize up scaled values*/ +#define LV_BEZIER_VAL_MAX (1L << LV_BEZIER_VAL_SHIFT) /**< Max time in Bezier functions (not [0..1] to use integers)*/ +#define LV_BEZIER_VAL_FLOAT(f) ((int32_t)((f) * LV_BEZIER_VAL_MAX)) /**< Convert const float number cubic-bezier values to fix-point value*/ + +/** Align up value x to align, align must be a power of two */ +#define LV_ALIGN_UP(x, align) (((x) + ((align) - 1)) & ~((align) - 1)) + +/** Round up value x to round, round can be any integer number */ +#define LV_ROUND_UP(x, round) ((((x) + ((round) - 1)) / (round)) * (round)) + +/********************** + * TYPEDEFS + **********************/ + +typedef struct { + uint16_t i; + uint16_t f; +} lv_sqrt_res_t; + +/********************** + * GLOBAL PROTOTYPES + **********************/ + +//! @cond Doxygen_Suppress +/** + * Return with sinus of an angle + * @param angle + * @return sinus of 'angle'. sin(-90) = -32767, sin(90) = 32767 + */ +int32_t /* LV_ATTRIBUTE_FAST_MEM */ lv_trigo_sin(int16_t angle); + +int32_t LV_ATTRIBUTE_FAST_MEM lv_trigo_cos(int16_t angle); + +//! @endcond + +/** + * Calculate the y value of cubic-bezier(x1, y1, x2, y2) function as specified x. + * @param x time in range of [0..LV_BEZIER_VAL_MAX] + * @param x1 x of control point 1 in range of [0..LV_BEZIER_VAL_MAX] + * @param y1 y of control point 1 in range of [0..LV_BEZIER_VAL_MAX] + * @param x2 x of control point 2 in range of [0..LV_BEZIER_VAL_MAX] + * @param y2 y of control point 2 in range of [0..LV_BEZIER_VAL_MAX] + * @return the value calculated + */ +int32_t lv_cubic_bezier(int32_t x, int32_t x1, int32_t y1, int32_t x2, int32_t y2); + +/** + * Calculate a value of a Cubic Bezier function. + * @param t time in range of [0..LV_BEZIER_VAL_MAX] + * @param u0 must be 0 + * @param u1 control value 1 values in range of [0..LV_BEZIER_VAL_MAX] + * @param u2 control value 2 in range of [0..LV_BEZIER_VAL_MAX] + * @param u3 must be LV_BEZIER_VAL_MAX + * @return the value calculated from the given parameters in range of [0..LV_BEZIER_VAL_MAX] + */ +int32_t lv_bezier3(int32_t t, int32_t u0, uint32_t u1, int32_t u2, int32_t u3); + + +/** + * Calculate the atan2 of a vector. + * @param x + * @param y + * @return the angle in degree calculated from the given parameters in range of [0..360] + */ +uint16_t lv_atan2(int x, int y); + +//! @cond Doxygen_Suppress + +/** + * Get the square root of a number + * @param x integer which square root should be calculated + * @param q store the result here. q->i: integer part, q->f: fractional part in 1/256 unit + * @param mask optional to skip some iterations if the magnitude of the root is known. + * Set to 0x8000 by default. + * If root < 16: mask = 0x80 + * If root < 256: mask = 0x800 + * Else: mask = 0x8000 + */ +void /* LV_ATTRIBUTE_FAST_MEM */ lv_sqrt(uint32_t x, lv_sqrt_res_t * q, uint32_t mask); + +//! @endcond + +/** + * Alternative (fast, approximate) implementation for getting the square root of an integer. + * @param x integer which square root should be calculated + */ +int32_t /* LV_ATTRIBUTE_FAST_MEM */ lv_sqrt32(uint32_t x); + +/** + * Calculate the square of an integer (input range is 0..32767). + * @param x input + * @return square + */ +static inline int32_t lv_sqr(int32_t x) +{ + return x * x; +} + +/** + * Calculate the integer exponents. + * @param base + * @param exp + * @return base raised to the power exponent + */ +int64_t lv_pow(int64_t base, int8_t exp); + +/** + * Get the mapped of a number given an input and output range + * @param x integer which mapped value should be calculated + * @param min_in min input range + * @param max_in max input range + * @param min_out max output range + * @param max_out max output range + * @return the mapped number + */ +int32_t lv_map(int32_t x, int32_t min_in, int32_t max_in, int32_t min_out, int32_t max_out); + +/** + * Set the seed of the pseudo random number generator + * @param seed a number to initialize the random generator + */ +void lv_rand_set_seed(uint32_t seed); + +/** + * Get a pseudo random number in the given range + * @param min the minimum value + * @param max the maximum value + * @return return the random number. min <= return_value <= max + */ +uint32_t lv_rand(uint32_t min, uint32_t max); + +/********************** + * MACROS + **********************/ +#define LV_MIN(a, b) ((a) < (b) ? (a) : (b)) +#define LV_MIN3(a, b, c) (LV_MIN(LV_MIN(a,b), c)) +#define LV_MIN4(a, b, c, d) (LV_MIN(LV_MIN(a,b), LV_MIN(c,d))) + +#define LV_MAX(a, b) ((a) > (b) ? (a) : (b)) +#define LV_MAX3(a, b, c) (LV_MAX(LV_MAX(a,b), c)) +#define LV_MAX4(a, b, c, d) (LV_MAX(LV_MAX(a,b), LV_MAX(c,d))) + +#define LV_CLAMP(min, val, max) (LV_MAX(min, (LV_MIN(val, max)))) + +#define LV_ABS(x) ((x) > 0 ? (x) : (-(x))) +#define LV_UDIV255(x) (((x) * 0x8081U) >> 0x17) + +#define LV_IS_SIGNED(t) (((t)(-1)) < ((t)0)) +#define LV_UMAX_OF(t) (((0x1ULL << ((sizeof(t) * 8ULL) - 1ULL)) - 1ULL) | (0xFULL << ((sizeof(t) * 8ULL) - 4ULL))) +#define LV_SMAX_OF(t) (((0x1ULL << ((sizeof(t) * 8ULL) - 1ULL)) - 1ULL) | (0x7ULL << ((sizeof(t) * 8ULL) - 4ULL))) +#define LV_MAX_OF(t) ((unsigned long)(LV_IS_SIGNED(t) ? LV_SMAX_OF(t) : LV_UMAX_OF(t))) + +#ifdef __cplusplus +} /*extern "C"*/ +#endif + +#endif diff --git a/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_profiler.h b/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_profiler.h new file mode 100644 index 00000000..47d5bd24 --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_profiler.h @@ -0,0 +1,52 @@ +/** + * @file lv_profiler.h + * + */ + +#ifndef LV_PROFILER_H +#define LV_PROFILER_H + +#ifdef __cplusplus +extern "C" { +#endif + +/********************* + * INCLUDES + *********************/ + +#include "../lv_conf_internal.h" + +#if LV_USE_PROFILER + +#include LV_PROFILER_INCLUDE + +/********************* + * DEFINES + *********************/ + +/********************** + * TYPEDEFS + **********************/ + +/********************** + * GLOBAL PROTOTYPES + **********************/ + +/********************** + * MACROS + **********************/ + +#else + +#define LV_PROFILER_BEGIN +#define LV_PROFILER_END +#define LV_PROFILER_BEGIN_TAG(tag) LV_UNUSED(tag) +#define LV_PROFILER_END_TAG(tag) LV_UNUSED(tag) + +#endif /*LV_USE_PROFILER*/ + +#ifdef __cplusplus +} /*extern "C"*/ +#endif + +#endif /*LV_PROFILER_H*/ diff --git a/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_timer.c b/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_timer.c new file mode 100644 index 00000000..959ce53b --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_timer.c @@ -0,0 +1,385 @@ +/** + * @file lv_timer.c + */ + +/********************* + * INCLUDES + *********************/ +#include "lv_timer_private.h" +#include "../core/lv_global.h" +#include "../tick/lv_tick.h" +#include "../stdlib/lv_mem.h" +#include "../stdlib/lv_sprintf.h" +#include "lv_assert.h" +#include "lv_ll.h" +#include "lv_profiler.h" + +/********************* + * DEFINES + *********************/ + +#define IDLE_MEAS_PERIOD 500 /*[ms]*/ +#define DEF_PERIOD 500 + +#define state LV_GLOBAL_DEFAULT()->timer_state +#define timer_ll_p &(state.timer_ll) + +/********************** + * TYPEDEFS + **********************/ + +/********************** + * STATIC PROTOTYPES + **********************/ +static bool lv_timer_exec(lv_timer_t * timer); +static uint32_t lv_timer_time_remaining(lv_timer_t * timer); +static void lv_timer_handler_resume(void); + +/********************** + * STATIC VARIABLES + **********************/ + +/********************** + * MACROS + **********************/ +#if LV_USE_LOG && LV_LOG_TRACE_TIMER + #define LV_TRACE_TIMER(...) LV_LOG_TRACE(__VA_ARGS__) +#else + #define LV_TRACE_TIMER(...) +#endif + +/********************** + * GLOBAL FUNCTIONS + **********************/ + +void lv_timer_core_init(void) +{ + lv_ll_init(timer_ll_p, sizeof(lv_timer_t)); + + /*Initially enable the lv_timer handling*/ + lv_timer_enable(true); +} + +LV_ATTRIBUTE_TIMER_HANDLER uint32_t lv_timer_handler(void) +{ + LV_TRACE_TIMER("begin"); + + lv_timer_state_t * state_p = &state; + /*Avoid concurrent running of the timer handler*/ + if(state_p->already_running) { + LV_TRACE_TIMER("already running, concurrent calls are not allow, returning"); + return 1; + } + state_p->already_running = true; + + if(state_p->lv_timer_run == false) { + state_p->already_running = false; /*Release mutex*/ + return 1; + } + + LV_PROFILER_BEGIN; + lv_lock(); + + uint32_t handler_start = lv_tick_get(); + + if(handler_start == 0) { + state.run_cnt++; + if(state.run_cnt > 100) { + state.run_cnt = 0; + LV_LOG_WARN("It seems lv_tick_inc() is not called."); + } + } + + /*Run all timer from the list*/ + lv_timer_t * next; + lv_timer_t * timer_active; + lv_ll_t * timer_head = timer_ll_p; + do { + state_p->timer_deleted = false; + state_p->timer_created = false; + + timer_active = lv_ll_get_head(timer_head); + while(timer_active) { + /*The timer might be deleted if it runs only once ('repeat_count = 1') + *So get next element until the current is surely valid*/ + next = lv_ll_get_next(timer_head, timer_active); + + if(lv_timer_exec(timer_active)) { + /*If a timer was created or deleted then this or the next item might be corrupted*/ + if(state_p->timer_created || state_p->timer_deleted) { + LV_TRACE_TIMER("Start from the first timer again because a timer was created or deleted"); + break; + } + } + + timer_active = next; /*Load the next timer*/ + } + } while(timer_active); + + uint32_t time_until_next = LV_NO_TIMER_READY; + next = lv_ll_get_head(timer_head); + while(next) { + if(!next->paused) { + uint32_t delay = lv_timer_time_remaining(next); + if(delay < time_until_next) + time_until_next = delay; + } + + next = lv_ll_get_next(timer_head, next); /*Find the next timer*/ + } + + state_p->busy_time += lv_tick_elaps(handler_start); + uint32_t idle_period_time = lv_tick_elaps(state_p->idle_period_start); + if(idle_period_time >= IDLE_MEAS_PERIOD) { + state_p->idle_last = (state_p->busy_time * 100) / idle_period_time; /*Calculate the busy percentage*/ + state_p->idle_last = state_p->idle_last > 100 ? 0 : 100 - state_p->idle_last; /*But we need idle time*/ + state_p->busy_time = 0; + state_p->idle_period_start = lv_tick_get(); + } + + state_p->timer_time_until_next = time_until_next; + state_p->already_running = false; /*Release the mutex*/ + + LV_TRACE_TIMER("finished (%" LV_PRIu32 " ms until the next timer call)", time_until_next); + lv_unlock(); + + LV_PROFILER_END; + + return time_until_next; +} + +LV_ATTRIBUTE_TIMER_HANDLER void lv_timer_periodic_handler(void) +{ + lv_timer_state_t * state_p = &state; + if(lv_tick_elaps(state_p->periodic_last_tick) >= state_p->timer_time_until_next) { + LV_TRACE_TIMER("calling lv_timer_handler()"); + lv_timer_handler(); + state_p->periodic_last_tick = lv_tick_get(); + } +} + +lv_timer_t * lv_timer_create_basic(void) +{ + return lv_timer_create(NULL, DEF_PERIOD, NULL); +} + +lv_timer_t * lv_timer_create(lv_timer_cb_t timer_xcb, uint32_t period, void * user_data) +{ + lv_timer_t * new_timer = NULL; + + new_timer = lv_ll_ins_head(timer_ll_p); + LV_ASSERT_MALLOC(new_timer); + if(new_timer == NULL) return NULL; + + new_timer->period = period; + new_timer->timer_cb = timer_xcb; + new_timer->repeat_count = -1; + new_timer->paused = 0; + new_timer->last_run = lv_tick_get(); + new_timer->user_data = user_data; + new_timer->auto_delete = true; + + state.timer_created = true; + + lv_timer_handler_resume(); + + return new_timer; +} + +void lv_timer_set_cb(lv_timer_t * timer, lv_timer_cb_t timer_cb) +{ + LV_ASSERT_NULL(timer); + timer->timer_cb = timer_cb; +} + +void lv_timer_delete(lv_timer_t * timer) +{ + lv_ll_remove(timer_ll_p, timer); + state.timer_deleted = true; + + lv_free(timer); +} + +void lv_timer_pause(lv_timer_t * timer) +{ + LV_ASSERT_NULL(timer); + timer->paused = true; +} + +void lv_timer_resume(lv_timer_t * timer) +{ + LV_ASSERT_NULL(timer); + timer->paused = false; + lv_timer_handler_resume(); +} + +void lv_timer_set_period(lv_timer_t * timer, uint32_t period) +{ + LV_ASSERT_NULL(timer); + timer->period = period; +} + +void lv_timer_ready(lv_timer_t * timer) +{ + LV_ASSERT_NULL(timer); + timer->last_run = lv_tick_get() - timer->period - 1; +} + +void lv_timer_set_repeat_count(lv_timer_t * timer, int32_t repeat_count) +{ + LV_ASSERT_NULL(timer); + timer->repeat_count = repeat_count; +} + +void lv_timer_set_auto_delete(lv_timer_t * timer, bool auto_delete) +{ + LV_ASSERT_NULL(timer); + timer->auto_delete = auto_delete; +} + +void lv_timer_set_user_data(lv_timer_t * timer, void * user_data) +{ + LV_ASSERT_NULL(timer); + timer->user_data = user_data; +} + +void lv_timer_reset(lv_timer_t * timer) +{ + LV_ASSERT_NULL(timer); + timer->last_run = lv_tick_get(); + lv_timer_handler_resume(); +} + +void lv_timer_enable(bool en) +{ + state.lv_timer_run = en; + if(en) lv_timer_handler_resume(); +} + +void lv_timer_core_deinit(void) +{ + lv_timer_enable(false); + + lv_ll_clear(timer_ll_p); +} + +uint32_t lv_timer_get_idle(void) +{ + return state.idle_last; +} + +uint32_t lv_timer_get_time_until_next(void) +{ + return state.timer_time_until_next; +} + +lv_timer_t * lv_timer_get_next(lv_timer_t * timer) +{ + if(timer == NULL) return lv_ll_get_head(timer_ll_p); + else return lv_ll_get_next(timer_ll_p, timer); +} + +LV_ATTRIBUTE_TIMER_HANDLER uint32_t lv_timer_handler_run_in_period(uint32_t period) +{ + static uint32_t last_tick = 0; + + if(lv_tick_elaps(last_tick) >= period) { + last_tick = lv_tick_get(); + return lv_timer_handler(); + } + return 1; +} + +void * lv_timer_get_user_data(lv_timer_t * timer) +{ + return timer->user_data; +} + +bool lv_timer_get_paused(lv_timer_t * timer) +{ + return timer->paused; +} + +/********************** + * STATIC FUNCTIONS + **********************/ + +/** + * Execute timer if its remaining time is zero + * @param timer pointer to lv_timer + * @return true: execute, false: not executed + */ +static bool lv_timer_exec(lv_timer_t * timer) +{ + if(timer->paused) return false; + + bool exec = false; + if(lv_timer_time_remaining(timer) == 0) { + /* Decrement the repeat count before executing the timer_cb. + * If any timer is deleted `if(timer->repeat_count == 0)` is not executed below + * but at least the repeat count is zero and the timer can be deleted in the next round*/ + int32_t original_repeat_count = timer->repeat_count; + if(timer->repeat_count > 0) timer->repeat_count--; + timer->last_run = lv_tick_get(); + LV_TRACE_TIMER("calling timer callback: %p", *((void **)&timer->timer_cb)); + + if(timer->timer_cb && original_repeat_count != 0) timer->timer_cb(timer); + + if(!state.timer_deleted) { + LV_TRACE_TIMER("timer callback %p finished", *((void **)&timer->timer_cb)); + } + else { + LV_TRACE_TIMER("timer callback finished"); + } + + LV_ASSERT_MEM_INTEGRITY(); + exec = true; + } + + if(state.timer_deleted == false) { /*The timer might be deleted by itself as well*/ + if(timer->repeat_count == 0) { /*The repeat count is over, delete the timer*/ + if(timer->auto_delete) { + LV_TRACE_TIMER("deleting timer with %p callback because the repeat count is over", *((void **)&timer->timer_cb)); + lv_timer_delete(timer); + } + else { + LV_TRACE_TIMER("pausing timer with %p callback because the repeat count is over", *((void **)&timer->timer_cb)); + lv_timer_pause(timer); + } + } + } + + return exec; +} + +/** + * Find out how much time remains before a timer must be run. + * @param timer pointer to lv_timer + * @return the time remaining, or 0 if it needs to be run again + */ +static uint32_t lv_timer_time_remaining(lv_timer_t * timer) +{ + /*Check if at least 'period' time elapsed*/ + uint32_t elp = lv_tick_elaps(timer->last_run); + if(elp >= timer->period) + return 0; + return timer->period - elp; +} + +/** + * Call the ready lv_timer + */ +static void lv_timer_handler_resume(void) +{ + /*If there is a timer which is ready to run then resume the timer loop*/ + state.timer_time_until_next = 0; + if(state.resume_cb) { + state.resume_cb(state.resume_data); + } +} + +void lv_timer_handler_set_resume_cb(lv_timer_handler_resume_cb_t cb, void * data) +{ + state.resume_cb = cb; + state.resume_data = data; +} diff --git a/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_timer.h b/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_timer.h new file mode 100644 index 00000000..be250033 --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_timer.h @@ -0,0 +1,210 @@ +/** + * @file lv_timer.h + */ + +#ifndef LV_TIMER_H +#define LV_TIMER_H + +#ifdef __cplusplus +extern "C" { +#endif + +/********************* + * INCLUDES + *********************/ +#include "../lv_conf_internal.h" +#include "../tick/lv_tick.h" +#include "lv_types.h" +#include "lv_ll.h" + +/********************* + * DEFINES + *********************/ +#ifndef LV_ATTRIBUTE_TIMER_HANDLER +#define LV_ATTRIBUTE_TIMER_HANDLER +#endif + +#define LV_NO_TIMER_READY 0xFFFFFFFF + +/********************** + * TYPEDEFS + **********************/ + +/** + * Timers execute this type of functions. + */ +typedef void (*lv_timer_cb_t)(lv_timer_t *); + +/** + * Timer handler resume this type of function. + */ +typedef void (*lv_timer_handler_resume_cb_t)(void * data); + +/********************** + * GLOBAL PROTOTYPES + **********************/ + +//! @cond Doxygen_Suppress + +/** + * Call it periodically to handle lv_timers. + * @return time till it needs to be run next (in ms) + */ +LV_ATTRIBUTE_TIMER_HANDLER uint32_t lv_timer_handler(void); + +//! @endcond + +/** + * Call it in the super-loop of main() or threads. It will run lv_timer_handler() + * with a given period in ms. You can use it with sleep or delay in OS environment. + * This function is used to simplify the porting. + * @param period the period for running lv_timer_handler() + * @return the time after which it must be called again + */ +LV_ATTRIBUTE_TIMER_HANDLER uint32_t lv_timer_handler_run_in_period(uint32_t period); + +/** + * Call it in the super-loop of main() or threads. It will automatically call lv_timer_handler() at the right time. + * This function is used to simplify the porting. + */ +LV_ATTRIBUTE_TIMER_HANDLER void lv_timer_periodic_handler(void); + +/** + * Set the resume callback to the timer handler + * @param cb the function to call when timer handler is resumed + * @param data pointer to a resume data + */ +void lv_timer_handler_set_resume_cb(lv_timer_handler_resume_cb_t cb, void * data); + +/** + * Create an "empty" timer. It needs to be initialized with at least + * `lv_timer_set_cb` and `lv_timer_set_period` + * @return pointer to the created timer + */ +lv_timer_t * lv_timer_create_basic(void); + +/** + * Create a new lv_timer + * @param timer_xcb a callback to call periodically. + * (the 'x' in the argument name indicates that it's not a fully generic function because it not follows + * the `func_name(object, callback, ...)` convention) + * @param period call period in ms unit + * @param user_data custom parameter + * @return pointer to the new timer + */ +lv_timer_t * lv_timer_create(lv_timer_cb_t timer_xcb, uint32_t period, void * user_data); + +/** + * Delete a lv_timer + * @param timer pointer to an lv_timer + */ +void lv_timer_delete(lv_timer_t * timer); + +/** + * Pause a timer. + * @param timer pointer to an lv_timer + */ +void lv_timer_pause(lv_timer_t * timer); + +/** + * Resume a timer. + * @param timer pointer to an lv_timer + */ +void lv_timer_resume(lv_timer_t * timer); + +/** + * Set the callback to the timer (the function to call periodically) + * @param timer pointer to a timer + * @param timer_cb the function to call periodically + */ +void lv_timer_set_cb(lv_timer_t * timer, lv_timer_cb_t timer_cb); + +/** + * Set new period for a lv_timer + * @param timer pointer to a lv_timer + * @param period the new period + */ +void lv_timer_set_period(lv_timer_t * timer, uint32_t period); + +/** + * Make a lv_timer ready. It will not wait its period. + * @param timer pointer to a lv_timer. + */ +void lv_timer_ready(lv_timer_t * timer); + +/** + * Set the number of times a timer will repeat. + * @param timer pointer to a lv_timer. + * @param repeat_count -1 : infinity; 0 : stop ; n>0: residual times + */ +void lv_timer_set_repeat_count(lv_timer_t * timer, int32_t repeat_count); + +/** + * Set whether a lv_timer will be deleted automatically when it is called `repeat_count` times. + * @param timer pointer to a lv_timer. + * @param auto_delete true: auto delete; false: timer will be paused when it is called `repeat_count` times. + */ +void lv_timer_set_auto_delete(lv_timer_t * timer, bool auto_delete); + +/** + * Set custom parameter to the lv_timer. + * @param timer pointer to a lv_timer. + * @param user_data custom parameter + */ +void lv_timer_set_user_data(lv_timer_t * timer, void * user_data); + +/** + * Reset a lv_timer. + * It will be called the previously set period milliseconds later. + * @param timer pointer to a lv_timer. + */ +void lv_timer_reset(lv_timer_t * timer); + +/** + * Enable or disable the whole lv_timer handling + * @param en true: lv_timer handling is running, false: lv_timer handling is suspended + */ +void lv_timer_enable(bool en); + +/** + * Get idle percentage + * @return the lv_timer idle in percentage + */ +uint32_t lv_timer_get_idle(void); + +/** + * Get the time remaining until the next timer will run + * @return the time remaining in ms + */ +uint32_t lv_timer_get_time_until_next(void); + +/** + * Iterate through the timers + * @param timer NULL to start iteration or the previous return value to get the next timer + * @return the next timer or NULL if there is no more timer + */ +lv_timer_t * lv_timer_get_next(lv_timer_t * timer); + +/** + * Get the user_data passed when the timer was created + * @param timer pointer to the lv_timer + * @return pointer to the user_data + */ +void * lv_timer_get_user_data(lv_timer_t * timer); + +/** + * Get the pause state of a timer + * @param timer pointer to a lv_timer + * @return true: timer is paused; false: timer is running + */ +bool lv_timer_get_paused(lv_timer_t * timer); + +/********************** + * MACROS + **********************/ + +#ifdef __cplusplus +} /*extern "C"*/ +#endif + +#endif diff --git a/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_timer_private.h b/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_timer_private.h new file mode 100644 index 00000000..b7f42b0a --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_timer_private.h @@ -0,0 +1,81 @@ +/** + * @file lv_timer_private.h + * + */ + +#ifndef LV_TIMER_PRIVATE_H +#define LV_TIMER_PRIVATE_H + +#ifdef __cplusplus +extern "C" { +#endif + +/********************* + * INCLUDES + *********************/ + +#include "lv_timer.h" + +/********************* + * DEFINES + *********************/ + +/********************** + * TYPEDEFS + **********************/ + +/** + * Descriptor of a lv_timer + */ +struct lv_timer_t { + uint32_t period; /**< How often the timer should run */ + uint32_t last_run; /**< Last time the timer ran */ + lv_timer_cb_t timer_cb; /**< Timer function */ + void * user_data; /**< Custom user data */ + int32_t repeat_count; /**< 1: One time; -1 : infinity; n>0: residual times */ + uint32_t paused : 1; + uint32_t auto_delete : 1; +}; + +typedef struct { + lv_ll_t timer_ll; /**< Linked list to store the lv_timers */ + + bool lv_timer_run; + uint8_t idle_last; + bool timer_deleted; + bool timer_created; + uint32_t timer_time_until_next; + + bool already_running; + uint32_t periodic_last_tick; + uint32_t busy_time; + uint32_t idle_period_start; + uint32_t run_cnt; + + lv_timer_handler_resume_cb_t resume_cb; + void * resume_data; +} lv_timer_state_t; + +/********************** + * GLOBAL PROTOTYPES + **********************/ + +/** + * Init the lv_timer module + */ +void lv_timer_core_init(void); + +/** + * Deinit the lv_timer module + */ +void lv_timer_core_deinit(void); + +/********************** + * MACROS + **********************/ + +#ifdef __cplusplus +} /*extern "C"*/ +#endif + +#endif /*LV_TIMER_PRIVATE_H*/ diff --git a/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_types.h b/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_types.h new file mode 100644 index 00000000..4e02c136 --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/template/src/misc/lv_types.h @@ -0,0 +1,379 @@ +/** + * @file lv_types.h + * + */ + +#ifndef LV_TYPES_H +#define LV_TYPES_H + +#ifdef __cplusplus +extern "C" { +#endif + +/********************* + * INCLUDES + *********************/ +#include "../lv_conf_internal.h" + +#ifndef __ASSEMBLY__ +#include LV_STDINT_INCLUDE +#include LV_STDDEF_INCLUDE +#include LV_STDBOOL_INCLUDE +#include LV_INTTYPES_INCLUDE +#include LV_LIMITS_INCLUDE +#include LV_STDARG_INCLUDE +#endif + +/********************* + * DEFINES + *********************/ + +/*If __UINTPTR_MAX__ or UINTPTR_MAX are available, use them to determine arch size*/ +#if defined(__UINTPTR_MAX__) && __UINTPTR_MAX__ > 0xFFFFFFFF +#define LV_ARCH_64 + +#elif defined(UINTPTR_MAX) && UINTPTR_MAX > 0xFFFFFFFF +#define LV_ARCH_64 + +/*Otherwise use compiler-dependent means to determine arch size*/ +#elif defined(_WIN64) || defined(__x86_64__) || defined(__ppc64__) || defined (__aarch64__) +#define LV_ARCH_64 + +#endif + +/********************** + * TYPEDEFS + **********************/ + +/* Exclude C enum and struct definitions when included by assembly code */ +#ifndef __ASSEMBLY__ + +/** + * LVGL error codes. + */ +typedef enum { + LV_RESULT_INVALID = 0, /*Typically indicates that the object is deleted (become invalid) in the action + function or an operation was failed*/ + LV_RESULT_OK, /*The object is valid (no deleted) after the action*/ +} lv_result_t; + +#if defined(__cplusplus) || __STDC_VERSION__ >= 199901L +/*If c99 or newer, use the definition of uintptr_t directly from */ +typedef uintptr_t lv_uintptr_t; +typedef intptr_t lv_intptr_t; + +#else + +/*Otherwise, use the arch size determination*/ +#ifdef LV_ARCH_64 +typedef uint64_t lv_uintptr_t; +typedef int64_t lv_intptr_t; +#else +typedef uint32_t lv_uintptr_t; +typedef int32_t lv_intptr_t; +#endif + +#endif + +#if LV_USE_FLOAT +typedef float lv_value_precise_t; +#else +typedef int32_t lv_value_precise_t; +#endif + +/** + * Typedefs from various lvgl modules. + * They are defined here to avoid circular dependencies. + */ + +typedef struct lv_obj_t lv_obj_t; + +typedef uint16_t lv_state_t; +typedef uint32_t lv_part_t; + +typedef uint8_t lv_opa_t; + +typedef uint8_t lv_style_prop_t; + +typedef struct lv_obj_class_t lv_obj_class_t; + +typedef struct lv_group_t lv_group_t; + +typedef struct lv_display_t lv_display_t; + +typedef struct lv_layer_t lv_layer_t; +typedef struct lv_draw_unit_t lv_draw_unit_t; +typedef struct lv_draw_task_t lv_draw_task_t; + +typedef struct lv_indev_t lv_indev_t; + +typedef struct lv_event_t lv_event_t; + +typedef struct lv_timer_t lv_timer_t; + +typedef struct lv_theme_t lv_theme_t; + +typedef struct lv_anim_t lv_anim_t; + +typedef struct lv_font_t lv_font_t; + +typedef struct lv_image_decoder_t lv_image_decoder_t; + +typedef struct lv_image_decoder_dsc_t lv_image_decoder_dsc_t; + +typedef struct lv_fragment_t lv_fragment_t; +typedef struct lv_fragment_class_t lv_fragment_class_t; +typedef struct lv_fragment_managed_states_t lv_fragment_managed_states_t; + +typedef struct lv_profiler_builtin_config_t lv_profiler_builtin_config_t; + +typedef struct lv_rb_node_t lv_rb_node_t; + +typedef struct lv_rb_t lv_rb_t; + +typedef struct lv_color_filter_dsc_t lv_color_filter_dsc_t; + +typedef struct lv_event_dsc_t lv_event_dsc_t; + +typedef struct lv_fs_file_cache_t lv_fs_file_cache_t; + +typedef struct lv_fs_path_ex_t lv_fs_path_ex_t; + +typedef struct lv_fs_dir_t lv_fs_dir_t; + +typedef struct lv_image_decoder_args_t lv_image_decoder_args_t; + +typedef struct lv_image_cache_data_t lv_image_cache_data_t; + +typedef struct lv_image_header_cache_data_t lv_image_header_cache_data_t; + +typedef struct lv_draw_mask_t lv_draw_mask_t; + +typedef struct lv_grad_t lv_grad_t; + +typedef struct lv_draw_label_hint_t lv_draw_label_hint_t; + +typedef struct lv_draw_glyph_dsc_t lv_draw_glyph_dsc_t; + +typedef struct lv_draw_image_sup_t lv_draw_image_sup_t; + +typedef struct lv_draw_mask_rect_dsc_t lv_draw_mask_rect_dsc_t; + +typedef struct lv_obj_style_t lv_obj_style_t; + +typedef struct lv_obj_style_transition_dsc_t lv_obj_style_transition_dsc_t; + +typedef struct lv_hit_test_info_t lv_hit_test_info_t; + +typedef struct lv_cover_check_info_t lv_cover_check_info_t; + +typedef struct lv_obj_spec_attr_t lv_obj_spec_attr_t; + +typedef struct lv_image_t lv_image_t; + +typedef struct lv_animimg_t lv_animimg_t; + +typedef struct lv_arc_t lv_arc_t; + +typedef struct lv_label_t lv_label_t; + +typedef struct lv_bar_anim_t lv_bar_anim_t; + +typedef struct lv_bar_t lv_bar_t; + +typedef struct lv_button_t lv_button_t; + +typedef struct lv_buttonmatrix_t lv_buttonmatrix_t; + +typedef struct lv_calendar_t lv_calendar_t; + +typedef struct lv_calendar_chinese_t lv_calendar_chinese_t; + +typedef struct lv_canvas_t lv_canvas_t; + +typedef struct lv_chart_series_t lv_chart_series_t; + +typedef struct lv_chart_cursor_t lv_chart_cursor_t; + +typedef struct lv_chart_t lv_chart_t; + +typedef struct lv_checkbox_t lv_checkbox_t; + +typedef struct lv_dropdown_t lv_dropdown_t; + +typedef struct lv_dropdown_list_t lv_dropdown_list_t; + +typedef struct lv_imagebutton_src_info_t lv_imagebutton_src_info_t; + +typedef struct lv_imagebutton_t lv_imagebutton_t; + +typedef struct lv_keyboard_t lv_keyboard_t; + +typedef struct lv_led_t lv_led_t; + +typedef struct lv_line_t lv_line_t; + +typedef struct lv_menu_load_page_event_data_t lv_menu_load_page_event_data_t; + +typedef struct lv_menu_history_t lv_menu_history_t; + +typedef struct lv_menu_t lv_menu_t; + +typedef struct lv_menu_page_t lv_menu_page_t; + +typedef struct lv_msgbox_t lv_msgbox_t; + +typedef struct lv_roller_t lv_roller_t; + +typedef struct lv_scale_section_t lv_scale_section_t; + +typedef struct lv_scale_t lv_scale_t; + +typedef struct lv_slider_t lv_slider_t; + +typedef struct lv_span_t lv_span_t; + +typedef struct lv_spangroup_t lv_spangroup_t; + +typedef struct lv_textarea_t lv_textarea_t; + +typedef struct lv_spinbox_t lv_spinbox_t; + +typedef struct lv_switch_t lv_switch_t; + +typedef struct lv_table_cell_t lv_table_cell_t; + +typedef struct lv_table_t lv_table_t; + +typedef struct lv_tabview_t lv_tabview_t; + +typedef struct lv_tileview_t lv_tileview_t; + +typedef struct lv_tileview_tile_t lv_tileview_tile_t; + +typedef struct lv_win_t lv_win_t; + +typedef struct lv_observer_t lv_observer_t; + +typedef struct lv_monkey_config_t lv_monkey_config_t; + +typedef struct lv_ime_pinyin_t lv_ime_pinyin_t; + +typedef struct lv_file_explorer_t lv_file_explorer_t; + +typedef struct lv_barcode_t lv_barcode_t; + +typedef struct lv_gif_t lv_gif_t; + +typedef struct lv_qrcode_t lv_qrcode_t; + +typedef struct lv_freetype_outline_vector_t lv_freetype_outline_vector_t; + +typedef struct lv_freetype_outline_event_param_t lv_freetype_outline_event_param_t; + +typedef struct lv_fpoint_t lv_fpoint_t; + +typedef struct lv_matrix_t lv_matrix_t; + +typedef struct lv_vector_path_t lv_vector_path_t; + +typedef struct lv_vector_gradient_t lv_vector_gradient_t; + +typedef struct lv_vector_fill_dsc_t lv_vector_fill_dsc_t; + +typedef struct lv_vector_stroke_dsc_t lv_vector_stroke_dsc_t; + +typedef struct lv_vector_draw_dsc_t lv_vector_draw_dsc_t; + +typedef struct lv_draw_vector_task_dsc_t lv_draw_vector_task_dsc_t; + +typedef struct lv_vector_dsc_t lv_vector_dsc_t; + +typedef struct lv_xkb_t lv_xkb_t; + +typedef struct lv_libinput_event_t lv_libinput_event_t; + +typedef struct lv_libinput_t lv_libinput_t; + +typedef struct lv_draw_sw_unit_t lv_draw_sw_unit_t; + +typedef struct lv_draw_sw_mask_common_dsc_t lv_draw_sw_mask_common_dsc_t; + +typedef struct lv_draw_sw_mask_line_param_t lv_draw_sw_mask_line_param_t; + +typedef struct lv_draw_sw_mask_angle_param_t lv_draw_sw_mask_angle_param_t; + +typedef struct lv_draw_sw_mask_radius_param_t lv_draw_sw_mask_radius_param_t; + +typedef struct lv_draw_sw_mask_fade_param_t lv_draw_sw_mask_fade_param_t; + +typedef struct lv_draw_sw_mask_map_param_t lv_draw_sw_mask_map_param_t; + +typedef struct lv_draw_sw_blend_dsc_t lv_draw_sw_blend_dsc_t; + +typedef struct lv_draw_sw_blend_fill_dsc_t lv_draw_sw_blend_fill_dsc_t; + +typedef struct lv_draw_sw_blend_image_dsc_t lv_draw_sw_blend_image_dsc_t; + +typedef struct lv_draw_buf_handlers_t lv_draw_buf_handlers_t; + +typedef struct lv_rlottie_t lv_rlottie_t; + +typedef struct lv_ffmpeg_player_t lv_ffmpeg_player_t; + +typedef struct lv_glfw_window_t lv_glfw_window_t; +typedef struct lv_glfw_texture_t lv_glfw_texture_t; + +typedef uint32_t lv_prop_id_t; + +typedef struct lv_draw_buf_t lv_draw_buf_t; + +#if LV_USE_OBJ_PROPERTY +typedef struct lv_property_name_t lv_property_name_t; +#endif + +#if LV_USE_SYSMON + +typedef struct lv_sysmon_backend_data_t lv_sysmon_backend_data_t; + +#if LV_USE_PERF_MONITOR +typedef struct lv_sysmon_perf_info_t lv_sysmon_perf_info_t; +#endif /*LV_USE_PERF_MONITOR*/ + +#endif /*LV_USE_SYSMON*/ + +#endif /*__ASSEMBLY__*/ + +/********************** + * GLOBAL PROTOTYPES + **********************/ + +/********************** + * MACROS + **********************/ + +#define LV_UNUSED(x) ((void)x) + +#define _LV_CONCAT(x, y) x ## y +#define LV_CONCAT(x, y) _LV_CONCAT(x, y) +#undef _LV_CONCAT + +#define _LV_CONCAT3(x, y, z) x ## y ## z +#define LV_CONCAT3(x, y, z) _LV_CONCAT3(x, y, z) +#undef _LV_CONCAT3 + +#if defined(PYCPARSER) || defined(__CC_ARM) +#define LV_FORMAT_ATTRIBUTE(fmtstr, vararg) +#elif defined(__GNUC__) && ((__GNUC__ == 4 && __GNUC_MINOR__ >= 4) || __GNUC__ > 4) +#define LV_FORMAT_ATTRIBUTE(fmtstr, vararg) __attribute__((format(gnu_printf, fmtstr, vararg))) +#elif (defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) || defined(__IAR_SYSTEMS_ICC__)) +#define LV_FORMAT_ATTRIBUTE(fmtstr, vararg) __attribute__((format(printf, fmtstr, vararg))) +#else +#define LV_FORMAT_ATTRIBUTE(fmtstr, vararg) +#endif + +#ifdef __cplusplus +} /*extern "C"*/ +#endif + +#endif /*LV_TYPES_H*/ diff --git a/tasks/runtime-lvgl-repeat-cadence/template/src/osal/lv_os.c b/tasks/runtime-lvgl-repeat-cadence/template/src/osal/lv_os.c new file mode 100644 index 00000000..7b775f03 --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/template/src/osal/lv_os.c @@ -0,0 +1,71 @@ +/** + * @file lv_os.c + * + */ + +/********************* + * INCLUDES + *********************/ +#include "lv_os.h" +#include "lv_os_private.h" +#include "../core/lv_global.h" + +/********************* + * DEFINES + *********************/ +#define lv_general_mutex LV_GLOBAL_DEFAULT()->lv_general_mutex + +/********************** + * TYPEDEFS + **********************/ + +/********************** + * STATIC PROTOTYPES + **********************/ + +/********************** + * STATIC VARIABLES + **********************/ + +/********************** + * MACROS + **********************/ + +/********************** + * GLOBAL FUNCTIONS + **********************/ + +void lv_os_init(void) +{ +#if LV_USE_OS != LV_OS_NONE + lv_mutex_init(&lv_general_mutex); +#endif /*LV_USE_OS != LV_OS_NONE*/ +} + +void lv_lock(void) +{ +#if LV_USE_OS != LV_OS_NONE + lv_mutex_lock(&lv_general_mutex); +#endif /*LV_USE_OS != LV_OS_NONE*/ +} + +lv_result_t lv_lock_isr(void) +{ +#if LV_USE_OS != LV_OS_NONE + return lv_mutex_lock_isr(&lv_general_mutex); +#else /*LV_USE_OS != LV_OS_NONE*/ + return LV_RESULT_OK; +#endif /*LV_USE_OS != LV_OS_NONE*/ +} + +void lv_unlock(void) +{ +#if LV_USE_OS != LV_OS_NONE + lv_mutex_unlock(&lv_general_mutex); +#endif /*LV_USE_OS != LV_OS_NONE*/ +} + +/********************** + * STATIC FUNCTIONS + **********************/ + diff --git a/tasks/runtime-lvgl-repeat-cadence/template/src/osal/lv_os.h b/tasks/runtime-lvgl-repeat-cadence/template/src/osal/lv_os.h new file mode 100644 index 00000000..d0a4e02f --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/template/src/osal/lv_os.h @@ -0,0 +1,186 @@ +/** + * @file lv_os.h + * + */ + +#ifndef LV_OS_H +#define LV_OS_H + +#ifdef __cplusplus +extern "C" { +#endif + +/********************* + * OS OPTIONS + *********************/ + +/********************* + * INCLUDES + *********************/ +#include "../lv_conf_internal.h" + +#include "../misc/lv_types.h" + +#if LV_USE_OS == LV_OS_NONE +#include "lv_os_none.h" +#elif LV_USE_OS == LV_OS_PTHREAD +#include "lv_pthread.h" +#elif LV_USE_OS == LV_OS_FREERTOS +#include "lv_freertos.h" +#elif LV_USE_OS == LV_OS_CMSIS_RTOS2 +#include "lv_cmsis_rtos2.h" +#elif LV_USE_OS == LV_OS_RTTHREAD +#include "lv_rtthread.h" +#elif LV_USE_OS == LV_OS_WINDOWS +#include "lv_windows.h" +#elif LV_USE_OS == LV_OS_MQX +#include "lv_mqx.h" +#elif LV_USE_OS == LV_OS_CUSTOM +#include LV_OS_CUSTOM_INCLUDE +#endif + +/********************* + * DEFINES + *********************/ + +/********************** + * TYPEDEFS + **********************/ +typedef enum { + LV_THREAD_PRIO_LOWEST, + LV_THREAD_PRIO_LOW, + LV_THREAD_PRIO_MID, + LV_THREAD_PRIO_HIGH, + LV_THREAD_PRIO_HIGHEST, +} lv_thread_prio_t; + +/********************** + * GLOBAL PROTOTYPES + **********************/ + +/*---------------------------------------- + * These functions needs to be implemented + * for specific operating systems + *---------------------------------------*/ + +/** + * Create a new thread + * @param thread a variable in which the thread will be stored + * @param prio priority of the thread + * @param callback function of the thread + * @param stack_size stack size in bytes + * @param user_data arbitrary data, will be available in the callback + * @return LV_RESULT_OK: success; LV_RESULT_INVALID: failure + */ +lv_result_t lv_thread_init(lv_thread_t * thread, lv_thread_prio_t prio, void (*callback)(void *), size_t stack_size, + void * user_data); + +/** + * Delete a thread + * @param thread the thread to delete + * @return LV_RESULT_OK: success; LV_RESULT_INVALID: failure + */ +lv_result_t lv_thread_delete(lv_thread_t * thread); + +/** + * Create a mutex + * @param mutex a variable in which the thread will be stored + * @return LV_RESULT_OK: success; LV_RESULT_INVALID: failure + */ +lv_result_t lv_mutex_init(lv_mutex_t * mutex); + +/** + * Lock a mutex + * @param mutex the mutex to lock + * @return LV_RESULT_OK: success; LV_RESULT_INVALID: failure + */ +lv_result_t lv_mutex_lock(lv_mutex_t * mutex); + +/** + * Lock a mutex from interrupt + * @param mutex the mutex to lock + * @return LV_RESULT_OK: success; LV_RESULT_INVALID: failure + */ +lv_result_t lv_mutex_lock_isr(lv_mutex_t * mutex); + +/** + * Unlock a mutex + * @param mutex the mutex to unlock + * @return LV_RESULT_OK: success; LV_RESULT_INVALID: failure + */ +lv_result_t lv_mutex_unlock(lv_mutex_t * mutex); + +/** + * Delete a mutex + * @param mutex the mutex to delete + * @return LV_RESULT_OK: success; LV_RESULT_INVALID: failure + */ +lv_result_t lv_mutex_delete(lv_mutex_t * mutex); + +/** + * Create a thread synchronization object + * @param sync a variable in which the sync will be stored + * @return LV_RESULT_OK: success; LV_RESULT_INVALID: failure + */ +lv_result_t lv_thread_sync_init(lv_thread_sync_t * sync); + +/** + * Wait for a "signal" on a sync object + * @param sync a sync object + * @return LV_RESULT_OK: success; LV_RESULT_INVALID: failure + */ +lv_result_t lv_thread_sync_wait(lv_thread_sync_t * sync); + +/** + * Send a wake-up signal to a sync object + * @param sync a sync object + * @return LV_RESULT_OK: success; LV_RESULT_INVALID: failure + */ +lv_result_t lv_thread_sync_signal(lv_thread_sync_t * sync); + +/** + * Send a wake-up signal to a sync object from interrupt + * @param sync a sync object + * @return LV_RESULT_OK: success; LV_RESULT_INVALID: failure + */ +lv_result_t lv_thread_sync_signal_isr(lv_thread_sync_t * sync); + +/** + * Delete a sync object + * @param sync a sync object to delete + * @return LV_RESULT_OK: success; LV_RESULT_INVALID: failure + */ +lv_result_t lv_thread_sync_delete(lv_thread_sync_t * sync); + +/** + * Lock LVGL's general mutex. + * LVGL is not thread safe, so a mutex is used to avoid executing multiple LVGL functions at the same time + * from different threads. It shall be called when calling LVGL functions from threads + * different than lv_timer_handler's thread. It doesn't need to be called in LVGL events because + * they are called from lv_timer_handler(). + * It is called internally in lv_timer_handler(). + */ +void lv_lock(void); + +/** + * Same as `lv_lock()` but can be called from an interrupt. + * @return LV_RESULT_OK: success; LV_RESULT_INVALID: failure + */ +lv_result_t lv_lock_isr(void); + +/** + * The pair of `lv_lock()` and `lv_lock_isr()`. + * It unlocks LVGL general mutex. + * It is called internally in lv_timer_handler(). + */ +void lv_unlock(void); + +/********************** + * MACROS + **********************/ + +#ifdef __cplusplus +} /*extern "C"*/ +#endif + +#endif /*LV_OS_H*/ diff --git a/tasks/runtime-lvgl-repeat-cadence/template/src/osal/lv_os_none.h b/tasks/runtime-lvgl-repeat-cadence/template/src/osal/lv_os_none.h new file mode 100644 index 00000000..e08a0dc4 --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/template/src/osal/lv_os_none.h @@ -0,0 +1,43 @@ +/** + * @file lv_os_none.h + * + */ + +#ifndef LV_OS_NONE_H +#define LV_OS_NONE_H + +#ifdef __cplusplus +extern "C" { +#endif + +/********************* + * INCLUDES + *********************/ +#if LV_USE_OS == LV_OS_NONE + +/********************* + * DEFINES + *********************/ + +/********************** + * TYPEDEFS + **********************/ +typedef int lv_mutex_t; +typedef int lv_thread_t; +typedef int lv_thread_sync_t; + +/********************** + * GLOBAL PROTOTYPES + **********************/ + +/********************** + * MACROS + **********************/ + +#endif /*LV_USE_OS == LV_OS_NONE*/ + +#ifdef __cplusplus +} /*extern "C"*/ +#endif + +#endif /*LV_OS_NONE_H*/ diff --git a/tasks/runtime-lvgl-repeat-cadence/template/src/osal/lv_os_private.h b/tasks/runtime-lvgl-repeat-cadence/template/src/osal/lv_os_private.h new file mode 100644 index 00000000..4fe08cd2 --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/template/src/osal/lv_os_private.h @@ -0,0 +1,47 @@ +/** + * @file lv_os_private.h + * + */ + +#ifndef LV_OS_PRIVATE_H +#define LV_OS_PRIVATE_H + +#ifdef __cplusplus +extern "C" { +#endif + +/********************* + * OS OPTIONS + *********************/ + +/********************* + * INCLUDES + *********************/ + +/********************* + * DEFINES + *********************/ + +/********************** + * TYPEDEFS + **********************/ + +/********************** + * GLOBAL PROTOTYPES + **********************/ + +/** + * Initialize the OS layer + */ +void lv_os_init(void); + + +/********************** + * MACROS + **********************/ + +#ifdef __cplusplus +} /*extern "C"*/ +#endif + +#endif /*LV_OS_PRIVATE_H*/ diff --git a/tasks/runtime-lvgl-repeat-cadence/template/src/stdlib/clib/lv_mem_core_clib.c b/tasks/runtime-lvgl-repeat-cadence/template/src/stdlib/clib/lv_mem_core_clib.c new file mode 100644 index 00000000..9cdddf4d --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/template/src/stdlib/clib/lv_mem_core_clib.c @@ -0,0 +1,94 @@ +/** + * @file lv_malloc_core.c + */ + +/********************* + * INCLUDES + *********************/ +#include "../lv_mem.h" +#if LV_USE_STDLIB_MALLOC == LV_STDLIB_CLIB +#include "../../stdlib/lv_mem.h" +#include + +/********************* + * DEFINES + *********************/ + +/********************** + * TYPEDEFS + **********************/ + +/********************** + * STATIC PROTOTYPES + **********************/ + +/********************** + * STATIC VARIABLES + **********************/ + +/********************** + * MACROS + **********************/ +/********************** + * GLOBAL FUNCTIONS + **********************/ + +void lv_mem_init(void) +{ + return; /*Nothing to init*/ +} + +void lv_mem_deinit(void) +{ + return; /*Nothing to deinit*/ + +} + +lv_mem_pool_t lv_mem_add_pool(void * mem, size_t bytes) +{ + /*Not supported*/ + LV_UNUSED(mem); + LV_UNUSED(bytes); + return NULL; +} + +void lv_mem_remove_pool(lv_mem_pool_t pool) +{ + /*Not supported*/ + LV_UNUSED(pool); + return; +} + +void * lv_malloc_core(size_t size) +{ + return malloc(size); +} + +void * lv_realloc_core(void * p, size_t new_size) +{ + return realloc(p, new_size); +} + +void lv_free_core(void * p) +{ + free(p); +} + +void lv_mem_monitor_core(lv_mem_monitor_t * mon_p) +{ + /*Not supported*/ + LV_UNUSED(mon_p); + return; +} + +lv_result_t lv_mem_test_core(void) +{ + /*Not supported*/ + return LV_RESULT_OK; +} + +/********************** + * STATIC FUNCTIONS + **********************/ + +#endif /*LV_STDLIB_CLIB*/ diff --git a/tasks/runtime-lvgl-repeat-cadence/template/src/stdlib/clib/lv_string_clib.c b/tasks/runtime-lvgl-repeat-cadence/template/src/stdlib/clib/lv_string_clib.c new file mode 100644 index 00000000..fd01b93f --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/template/src/stdlib/clib/lv_string_clib.c @@ -0,0 +1,114 @@ +/** + * @file lv_string.c + */ + +/********************* + * INCLUDES + *********************/ +#include "../../lv_conf_internal.h" +#if LV_USE_STDLIB_STRING == LV_STDLIB_CLIB +#include "../lv_string.h" +#include "../lv_mem.h" /*Need lv_malloc*/ +#include + +/********************* + * DEFINES + *********************/ + +/********************** + * TYPEDEFS + **********************/ + +/********************** + * STATIC PROTOTYPES + **********************/ + +/********************** + * STATIC VARIABLES + **********************/ + +/********************** + * MACROS + **********************/ + +/********************** + * GLOBAL FUNCTIONS + **********************/ + +void * LV_ATTRIBUTE_FAST_MEM lv_memcpy(void * dst, const void * src, size_t len) +{ + return memcpy(dst, src, len); +} + +void LV_ATTRIBUTE_FAST_MEM lv_memset(void * dst, uint8_t v, size_t len) +{ + memset(dst, v, len); +} + +void * LV_ATTRIBUTE_FAST_MEM lv_memmove(void * dst, const void * src, size_t len) +{ + return memmove(dst, src, len); +} + +int lv_memcmp(const void * p1, const void * p2, size_t len) +{ + return memcmp(p1, p2, len); +} + +size_t lv_strlen(const char * str) +{ + return strlen(str); +} + +size_t lv_strlcpy(char * dst, const char * src, size_t dst_size) +{ + size_t src_len = strlen(src); + if(dst_size > 0) { + size_t copy_size = src_len < dst_size ? src_len : dst_size - 1; + memcpy(dst, src, copy_size); + dst[copy_size] = '\0'; + } + return src_len; +} + +char * lv_strncpy(char * dst, const char * src, size_t dest_size) +{ + return strncpy(dst, src, dest_size); +} + +char * lv_strcpy(char * dst, const char * src) +{ + return strcpy(dst, src); +} + +int lv_strcmp(const char * s1, const char * s2) +{ + return strcmp(s1, s2); +} + +char * lv_strdup(const char * src) +{ + /*strdup uses malloc, so use the lv_malloc when LV_USE_STDLIB_MALLOC is not LV_STDLIB_CLIB */ + size_t len = lv_strlen(src) + 1; + char * dst = lv_malloc(len); + if(dst == NULL) return NULL; + + lv_memcpy(dst, src, len); /*do memcpy is faster than strncpy when length is known*/ + return dst; +} + +char * lv_strcat(char * dst, const char * src) +{ + return strcat(dst, src); +} + +char * lv_strncat(char * dst, const char * src, size_t src_len) +{ + return strncat(dst, src, src_len); +} + +/********************** + * STATIC FUNCTIONS + **********************/ + +#endif /*LV_STDLIB_CLIB*/ diff --git a/tasks/runtime-lvgl-repeat-cadence/template/src/stdlib/lv_mem.c b/tasks/runtime-lvgl-repeat-cadence/template/src/stdlib/lv_mem.c new file mode 100644 index 00000000..bfc887ff --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/template/src/stdlib/lv_mem.c @@ -0,0 +1,168 @@ +/** + * @file lv_mem.c + */ + +/********************* + * INCLUDES + *********************/ +#include "lv_mem_private.h" +#include "lv_string.h" +#include "../misc/lv_assert.h" +#include "../misc/lv_log.h" +#include "../core/lv_global.h" + +#if LV_USE_OS == LV_OS_PTHREAD + #include +#endif + +/********************* + * DEFINES + *********************/ +/*memset the allocated memories to 0xaa and freed memories to 0xbb (just for testing purposes)*/ +#ifndef LV_MEM_ADD_JUNK + #define LV_MEM_ADD_JUNK 0 +#endif + +#define zero_mem LV_GLOBAL_DEFAULT()->memory_zero + +/********************** + * TYPEDEFS + **********************/ + +/********************** + * STATIC PROTOTYPES + **********************/ + +/********************** + * GLOBAL PROTOTYPES + **********************/ +void * lv_malloc_core(size_t size); +void * lv_realloc_core(void * p, size_t new_size); +void lv_free_core(void * p); +void lv_mem_monitor_core(lv_mem_monitor_t * mon_p); +lv_result_t lv_mem_test_core(void); + +/********************** + * STATIC VARIABLES + **********************/ + +/********************** + * MACROS + **********************/ +#if LV_USE_LOG && LV_LOG_TRACE_MEM + #define LV_TRACE_MEM(...) LV_LOG_TRACE(__VA_ARGS__) +#else + #define LV_TRACE_MEM(...) +#endif + +/********************** + * GLOBAL FUNCTIONS + **********************/ + +void * lv_malloc(size_t size) +{ + LV_TRACE_MEM("allocating %lu bytes", (unsigned long)size); + if(size == 0) { + LV_TRACE_MEM("using zero_mem"); + return &zero_mem; + } + + void * alloc = lv_malloc_core(size); + + if(alloc == NULL) { + LV_LOG_INFO("couldn't allocate memory (%lu bytes)", (unsigned long)size); +#if LV_LOG_LEVEL <= LV_LOG_LEVEL_INFO + lv_mem_monitor_t mon; + lv_mem_monitor(&mon); + LV_LOG_INFO("used: %zu (%3d %%), frag: %3d %%, biggest free: %zu", + mon.total_size - mon.free_size, mon.used_pct, mon.frag_pct, + mon.free_biggest_size); +#endif + return NULL; + } + +#if LV_MEM_ADD_JUNK + lv_memset(alloc, 0xaa, size); +#endif + + LV_TRACE_MEM("allocated at %p", alloc); + return alloc; +} + +void * lv_malloc_zeroed(size_t size) +{ + LV_TRACE_MEM("allocating %lu bytes", (unsigned long)size); + if(size == 0) { + LV_TRACE_MEM("using zero_mem"); + return &zero_mem; + } + + void * alloc = lv_malloc_core(size); + if(alloc == NULL) { + LV_LOG_INFO("couldn't allocate memory (%lu bytes)", (unsigned long)size); +#if LV_LOG_LEVEL <= LV_LOG_LEVEL_INFO + lv_mem_monitor_t mon; + lv_mem_monitor(&mon); + LV_LOG_INFO("used: %zu (%3d %%), frag: %3d %%, biggest free: %zu", + mon.total_size - mon.free_size, mon.used_pct, mon.frag_pct, + mon.free_biggest_size); +#endif + return NULL; + } + + lv_memzero(alloc, size); + + LV_TRACE_MEM("allocated at %p", alloc); + return alloc; +} + +void lv_free(void * data) +{ + LV_TRACE_MEM("freeing %p", data); + if(data == &zero_mem) return; + if(data == NULL) return; + + lv_free_core(data); +} + +void * lv_realloc(void * data_p, size_t new_size) +{ + LV_TRACE_MEM("reallocating %p with %lu size", data_p, (unsigned long)new_size); + if(new_size == 0) { + LV_TRACE_MEM("using zero_mem"); + lv_free(data_p); + return &zero_mem; + } + + if(data_p == &zero_mem) return lv_malloc(new_size); + + void * new_p = lv_realloc_core(data_p, new_size); + + if(new_p == NULL) { + LV_LOG_ERROR("couldn't reallocate memory"); + return NULL; + } + + LV_TRACE_MEM("reallocated at %p", new_p); + return new_p; +} + +lv_result_t lv_mem_test(void) +{ + if(zero_mem != ZERO_MEM_SENTINEL) { + LV_LOG_WARN("zero_mem is written"); + return LV_RESULT_INVALID; + } + + return lv_mem_test_core(); +} + +void lv_mem_monitor(lv_mem_monitor_t * mon_p) +{ + lv_memzero(mon_p, sizeof(lv_mem_monitor_t)); + lv_mem_monitor_core(mon_p); +} + +/********************** + * STATIC FUNCTIONS + **********************/ diff --git a/tasks/runtime-lvgl-repeat-cadence/template/src/stdlib/lv_mem.h b/tasks/runtime-lvgl-repeat-cadence/template/src/stdlib/lv_mem.h new file mode 100644 index 00000000..210c1898 --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/template/src/stdlib/lv_mem.h @@ -0,0 +1,141 @@ +/** + * @file lv_mem.h + * + */ + +#ifndef LV_MEM_H +#define LV_MEM_H + +#ifdef __cplusplus +extern "C" { +#endif + +/********************* + * INCLUDES + *********************/ +#include "../lv_conf_internal.h" + +#include "lv_string.h" + +#include "../misc/lv_types.h" + +/********************* + * DEFINES + *********************/ + +/********************** + * TYPEDEFS + **********************/ + +typedef void * lv_mem_pool_t; + +/** + * Heap information structure. + */ +typedef struct { + size_t total_size; /**< Total heap size */ + size_t free_cnt; + size_t free_size; /**< Size of available memory */ + size_t free_biggest_size; + size_t used_cnt; + size_t max_used; /**< Max size of Heap memory used */ + uint8_t used_pct; /**< Percentage used */ + uint8_t frag_pct; /**< Amount of fragmentation */ +} lv_mem_monitor_t; + +/********************** + * GLOBAL PROTOTYPES + **********************/ + +/** + * Initialize to use malloc/free/realloc etc + */ +void lv_mem_init(void); + +/** + * Drop all dynamically allocated memory and reset the memory pools' state + */ +void lv_mem_deinit(void); + +lv_mem_pool_t lv_mem_add_pool(void * mem, size_t bytes); + +void lv_mem_remove_pool(lv_mem_pool_t pool); + +/** + * Allocate memory dynamically + * @param size requested size in bytes + * @return pointer to allocated uninitialized memory, or NULL on failure + */ +void * lv_malloc(size_t size); + +/** + * Allocate zeroed memory dynamically + * @param size requested size in bytes + * @return pointer to allocated zeroed memory, or NULL on failure + */ +void * lv_malloc_zeroed(size_t size); + +/** + * Free an allocated data + * @param data pointer to an allocated memory + */ +void lv_free(void * data); + +/** + * Reallocate a memory with a new size. The old content will be kept. + * @param data_p pointer to an allocated memory. + * Its content will be copied to the new memory block and freed + * @param new_size the desired new size in byte + * @return pointer to the new memory, NULL on failure + */ +void * lv_realloc(void * data_p, size_t new_size); + +/** + * Used internally to execute a plain `malloc` operation + * @param size size in bytes to `malloc` + */ +void * lv_malloc_core(size_t size); + +/** + * Used internally to execute a plain `free` operation + * @param p memory address to free + */ +void lv_free_core(void * p); + +/** + * Used internally to execute a plain realloc operation + * @param p memory address to realloc + * @param new_size size in bytes to realloc + */ +void * lv_realloc_core(void * p, size_t new_size); + +/** + * Used internally by lv_mem_monitor() to gather LVGL heap state information. + * @param mon_p pointer to lv_mem_monitor_t object to be populated. + */ +void lv_mem_monitor_core(lv_mem_monitor_t * mon_p); + +lv_result_t lv_mem_test_core(void); + +/** + * @brief Tests the memory allocation system by allocating and freeing a block of memory. + * @return LV_RESULT_OK if the memory allocation system is working properly, or LV_RESULT_INVALID if there is an error. + */ +lv_result_t lv_mem_test(void); + +/** + * Give information about the work memory of dynamic allocation + * @param mon_p pointer to a lv_mem_monitor_t variable, + * the result of the analysis will be stored here + */ +void lv_mem_monitor(lv_mem_monitor_t * mon_p); + +/********************** + * MACROS + **********************/ + +#ifdef __cplusplus +} /*extern "C"*/ +#endif + +#endif /*LV_MEM_H*/ diff --git a/tasks/runtime-lvgl-repeat-cadence/template/src/stdlib/lv_mem_private.h b/tasks/runtime-lvgl-repeat-cadence/template/src/stdlib/lv_mem_private.h new file mode 100644 index 00000000..9e70ae1a --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/template/src/stdlib/lv_mem_private.h @@ -0,0 +1,39 @@ +/** + * @file lv_mem_private.h + * + */ + +#ifndef LV_MEM_PRIVATE_H +#define LV_MEM_PRIVATE_H + +#ifdef __cplusplus +extern "C" { +#endif + +/********************* + * INCLUDES + *********************/ + +#include "lv_mem.h" + +/********************* + * DEFINES + *********************/ + +/********************** + * TYPEDEFS + **********************/ + +/********************** + * GLOBAL PROTOTYPES + **********************/ + +/********************** + * MACROS + **********************/ + +#ifdef __cplusplus +} /*extern "C"*/ +#endif + +#endif /*LV_MEM_PRIVATE_H*/ diff --git a/tasks/runtime-lvgl-repeat-cadence/template/src/stdlib/lv_sprintf.h b/tasks/runtime-lvgl-repeat-cadence/template/src/stdlib/lv_sprintf.h new file mode 100644 index 00000000..a7f2188d --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/template/src/stdlib/lv_sprintf.h @@ -0,0 +1,45 @@ +/** + * @file lv_sprintf.h + * + */ + +#ifndef LV_SPRINTF_H +#define LV_SPRINTF_H + +#if defined(__has_include) + #if __has_include(LV_INTTYPES_INCLUDE) + #include LV_INTTYPES_INCLUDE + /* platform-specific printf format for int32_t, usually "d" or "ld" */ + #define LV_PRId32 PRId32 + #define LV_PRIu32 PRIu32 + #define LV_PRIx32 PRIx32 + #define LV_PRIX32 PRIX32 + #else + #define LV_PRId32 "d" + #define LV_PRIu32 "u" + #define LV_PRIx32 "x" + #define LV_PRIX32 "X" + #endif +#else + /* hope this is correct for ports without __has_include or without inttypes.h */ + #define LV_PRId32 "d" + #define LV_PRIu32 "u" + #define LV_PRIx32 "x" + #define LV_PRIX32 "X" +#endif + +#include "../misc/lv_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +int lv_snprintf(char * buffer, size_t count, const char * format, ...); + +int lv_vsnprintf(char * buffer, size_t count, const char * format, va_list va); + +#ifdef __cplusplus +} /*extern "C"*/ +#endif + +#endif /* LV_SPRINTF_H */ diff --git a/tasks/runtime-lvgl-repeat-cadence/template/src/stdlib/lv_string.h b/tasks/runtime-lvgl-repeat-cadence/template/src/stdlib/lv_string.h new file mode 100644 index 00000000..10aee500 --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/template/src/stdlib/lv_string.h @@ -0,0 +1,158 @@ +/** + * @file lv_string.h + * + */ + +#ifndef LV_STRING_H +#define LV_STRING_H + +#ifdef __cplusplus +extern "C" { +#endif + +/********************* + * INCLUDES + *********************/ +#include "../lv_conf_internal.h" +#include "../misc/lv_types.h" + +/********************* + * DEFINES + *********************/ + +/********************** + * TYPEDEFS + **********************/ + +/********************** + * GLOBAL PROTOTYPES + **********************/ + +/** + * @brief Copies a block of memory from a source address to a destination address. + * @param dst Pointer to the destination array where the content is to be copied. + * @param src Pointer to the source of data to be copied. + * @param len Number of bytes to copy. + * @return Pointer to the destination array. + * @note The function does not check for any overlapping of the source and destination memory blocks. + */ +void * lv_memcpy(void * dst, const void * src, size_t len); + +/** + * @brief Fills a block of memory with a specified value. + * @param dst Pointer to the destination array to fill with the specified value. + * @param v Value to be set. The value is passed as an int, but the function fills + * the block of memory using the unsigned char conversion of this value. + * @param len Number of bytes to be set to the value. + */ +void lv_memset(void * dst, uint8_t v, size_t len); + +/** + * @brief Move a block of memory from source to destination + * @param dst Pointer to the destination array where the content is to be copied. + * @param src Pointer to the source of data to be copied. + * @param len Number of bytes to copy + * @return Pointer to the destination array. + */ +void * lv_memmove(void * dst, const void * src, size_t len); + +/** + * @brief This function will compare two memory blocks + * @param p1 Pointer to the first memory block + * @param p2 Pointer to the second memory block + * @param len Number of bytes to compare + * @return The difference between the value of the first unmatching byte. + */ +int lv_memcmp(const void * p1, const void * p2, size_t len); + +/** + * Same as `memset(dst, 0x00, len)`. + * @param dst pointer to the destination buffer + * @param len number of byte to set + */ +static inline void lv_memzero(void * dst, size_t len) +{ + lv_memset(dst, 0x00, len); +} + +/** + * @brief Computes the length of the string str up to, but not including the terminating null character. + * @param str Pointer to the null-terminated byte string to be examined. + * @return The length of the string in bytes. + */ +size_t lv_strlen(const char * str); + +/** + * @brief Copies up to dst_size-1 (non-null) characters from src to dst. A null terminator is always added. + * @param dst Pointer to the destination array where the content is to be copied. + * @param src Pointer to the source of data to be copied. + * @param dst_size Maximum number of characters to be copied to dst, including the null character. + * @return The length of src. The return value is equivalent to the value returned by lv_strlen(src) + */ +size_t lv_strlcpy(char * dst, const char * src, size_t dst_size); + +/** + * @brief Copies up to dest_size characters from the string pointed to by src to the character array pointed to by dst + * and fills the remaining length with null bytes. + * @param dst Pointer to the destination array where the content is to be copied. + * @param src Pointer to the source of data to be copied. + * @param dest_size Maximum number of characters to be copied to dst. + * @return A pointer to the destination array, which is dst. + * @note dst will not be null terminated if dest_size bytes were copied from src before the end of src was reached. + */ +char * lv_strncpy(char * dst, const char * src, size_t dest_size); + +/** + * @brief Copies the string pointed to by src, including the terminating null character, + * to the character array pointed to by dst. + * @param dst Pointer to the destination array where the content is to be copied. + * @param src Pointer to the source of data to be copied. + * @return A pointer to the destination array, which is dst. + */ +char * lv_strcpy(char * dst, const char * src); + +/** + * @brief This function will compare two strings without specified length. + * @param s1 pointer to the first string + * @param s2 pointer to the second string + * @return the difference between the value of the first unmatching character. + */ +int lv_strcmp(const char * s1, const char * s2); + +/** + * @brief Duplicate a string by allocating a new one and copying the content. + * @param src Pointer to the source of data to be copied. + * @return A pointer to the new allocated string. NULL if failed. + */ +char * lv_strdup(const char * src); + +/** + * @brief Copies the string pointed to by src, including the terminating null character, + * to the end of the string pointed to by dst. + * @param dst Pointer to the destination string where the content is to be appended. + * @param src Pointer to the source of data to be copied. + * @return A pointer to the destination string, which is dst. + */ +char * lv_strcat(char * dst, const char * src); + +/** + * @brief Copies up to src_len characters from the string pointed to by src + * to the end of the string pointed to by dst. + * A terminating null character is appended to dst even if no null character + * was encountered in src after src_len characters were copied. + * @param dst Pointer to the destination string where the content is to be appended. + * @param src Pointer to the source of data to be copied. + * @param src_len Maximum number of characters from src to be copied to the end of dst. + * @return A pointer to the destination string, which is dst. + */ +char * lv_strncat(char * dst, const char * src, size_t src_len); + +/********************** + * MACROS + **********************/ + +#ifdef __cplusplus +} /*extern "C"*/ +#endif + +#endif /*LV_STRING_H*/ diff --git a/tasks/runtime-lvgl-repeat-cadence/template/src/tick/lv_tick.c b/tasks/runtime-lvgl-repeat-cadence/template/src/tick/lv_tick.c new file mode 100644 index 00000000..21e22959 --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/template/src/tick/lv_tick.c @@ -0,0 +1,113 @@ +/** + * @file lv_tick.c + * Provide access to the system tick with 1 millisecond resolution + */ + +/********************* + * INCLUDES + *********************/ +#include "lv_tick_private.h" +#include "../misc/lv_types.h" +#include "../core/lv_global.h" + +/********************* + * DEFINES + *********************/ +#define state LV_GLOBAL_DEFAULT()->tick_state + +/********************** + * TYPEDEFS + **********************/ + +/********************** + * STATIC PROTOTYPES + **********************/ + +/********************** + * STATIC VARIABLES + **********************/ + +/********************** + * MACROS + **********************/ + +/********************** + * GLOBAL FUNCTIONS + **********************/ + +LV_ATTRIBUTE_TICK_INC void lv_tick_inc(uint32_t tick_period) +{ + lv_tick_state_t * state_p = &state; + + state_p->sys_irq_flag = 0; + state_p->sys_time += tick_period; +} + +uint32_t lv_tick_get(void) +{ + lv_tick_state_t * state_p = &state; + + if(state_p->tick_get_cb) + return state_p->tick_get_cb(); + + /*If `lv_tick_inc` is called from an interrupt while `sys_time` is read + *the result might be corrupted. + *This loop detects if `lv_tick_inc` was called while reading `sys_time`. + *If `tick_irq_flag` was cleared in `lv_tick_inc` try to read again + *until `tick_irq_flag` remains `1`.*/ + uint32_t result; + do { + state_p->sys_irq_flag = 1; + result = state_p->sys_time; + } while(!state_p->sys_irq_flag); /*Continue until see a non interrupted cycle*/ + + return result; +} + +uint32_t lv_tick_elaps(uint32_t prev_tick) +{ + uint32_t act_time = lv_tick_get(); + + /*If there is no overflow in sys_time simple subtract*/ + if(act_time >= prev_tick) { + prev_tick = act_time - prev_tick; + } + else { + prev_tick = UINT32_MAX - prev_tick + 1; + prev_tick += act_time; + } + + return prev_tick; +} + +void lv_delay_ms(uint32_t ms) +{ + if(state.delay_cb) { + state.delay_cb(ms); + } + else { + uint32_t t = lv_tick_get(); + while(lv_tick_elaps(t) < ms) { + /*Do something to no call `lv_tick_elaps` too often as it might interfere with interrupts*/ + volatile uint32_t i; + volatile uint32_t x = ms; + for(i = 0; i < 100; i++) { + x = x * 3; + } + } + } +} + +void lv_tick_set_cb(lv_tick_get_cb_t cb) +{ + state.tick_get_cb = cb; +} + +void lv_delay_set_cb(lv_delay_cb_t cb) +{ + state.delay_cb = cb; +} + +/********************** + * STATIC FUNCTIONS + **********************/ diff --git a/tasks/runtime-lvgl-repeat-cadence/template/src/tick/lv_tick.h b/tasks/runtime-lvgl-repeat-cadence/template/src/tick/lv_tick.h new file mode 100644 index 00000000..048b93a3 --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/template/src/tick/lv_tick.h @@ -0,0 +1,85 @@ +/** + * @file lv_tick.h + * Provide access to the system tick with 1 millisecond resolution + */ + +#ifndef LV_TICK_H +#define LV_TICK_H + +#ifdef __cplusplus +extern "C" { +#endif + +/********************* + * INCLUDES + *********************/ +#include "../lv_conf_internal.h" + +#include "../misc/lv_types.h" + +/********************* + * DEFINES + *********************/ +#ifndef LV_ATTRIBUTE_TICK_INC +#define LV_ATTRIBUTE_TICK_INC +#endif + +/********************** + * TYPEDEFS + **********************/ +typedef uint32_t (*lv_tick_get_cb_t)(void); + +typedef void (*lv_delay_cb_t)(uint32_t ms); + +/********************** + * GLOBAL PROTOTYPES + **********************/ + +/** + * You have to call this function periodically + * @param tick_period the call period of this function in milliseconds + */ +LV_ATTRIBUTE_TICK_INC void lv_tick_inc(uint32_t tick_period); + +/** + * Get the elapsed milliseconds since start up + * @return the elapsed milliseconds + */ +uint32_t lv_tick_get(void); + +/** + * Get the elapsed milliseconds since a previous time stamp + * @param prev_tick a previous time stamp (return value of lv_tick_get() ) + * @return the elapsed milliseconds since 'prev_tick' + */ +uint32_t lv_tick_elaps(uint32_t prev_tick); + +/** + * Delay for the given milliseconds. + * By default it's a blocking delay, but with `lv_delay_set_cb()` + * a custom delay function can be set too + * @param ms the number of milliseconds to delay + */ +void lv_delay_ms(uint32_t ms); + +/** + * Set the custom callback for 'lv_tick_get' + * @param cb call this callback on 'lv_tick_get' + */ +void lv_tick_set_cb(lv_tick_get_cb_t cb); + +/** + * Set a custom callback for 'lv_delay_ms' + * @param cb call this callback in 'lv_delay_ms' + */ +void lv_delay_set_cb(lv_delay_cb_t cb); + +/********************** + * MACROS + **********************/ + +#ifdef __cplusplus +} /*extern "C"*/ +#endif + +#endif /*LV_TICK_H*/ diff --git a/tasks/runtime-lvgl-repeat-cadence/template/src/tick/lv_tick_private.h b/tasks/runtime-lvgl-repeat-cadence/template/src/tick/lv_tick_private.h new file mode 100644 index 00000000..cf8ae9b0 --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/template/src/tick/lv_tick_private.h @@ -0,0 +1,46 @@ +/** + * @file lv_tick_private.h + * + */ + +#ifndef LV_TICK_PRIVATE_H +#define LV_TICK_PRIVATE_H + +#ifdef __cplusplus +extern "C" { +#endif + +/********************* + * INCLUDES + *********************/ + +#include "lv_tick.h" + +/********************* + * DEFINES + *********************/ + +/********************** + * TYPEDEFS + **********************/ + +typedef struct { + uint32_t sys_time; + volatile uint8_t sys_irq_flag; + lv_tick_get_cb_t tick_get_cb; + lv_delay_cb_t delay_cb; +} lv_tick_state_t; + +/********************** + * GLOBAL PROTOTYPES + **********************/ + +/********************** + * MACROS + **********************/ + +#ifdef __cplusplus +} /*extern "C"*/ +#endif + +#endif /*LV_TICK_PRIVATE_H*/ diff --git a/tasks/runtime-lvgl-repeat-cadence/valid_debt/src/misc/lv_anim.c b/tasks/runtime-lvgl-repeat-cadence/valid_debt/src/misc/lv_anim.c new file mode 100644 index 00000000..8b49cbcc --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/valid_debt/src/misc/lv_anim.c @@ -0,0 +1,715 @@ +/** + * @file lv_anim.c + * + */ + +/********************* + * INCLUDES + *********************/ +#include "lv_anim_private.h" + +#include "../core/lv_global.h" +#include "../tick/lv_tick.h" +#include "lv_assert.h" +#include "lv_timer.h" +#include "lv_math.h" +#include "../stdlib/lv_mem.h" +#include "../stdlib/lv_string.h" + +/********************* + * DEFINES + *********************/ +#define LV_ANIM_RESOLUTION 1024 +#define LV_ANIM_RES_SHIFT 10 +#define state LV_GLOBAL_DEFAULT()->anim_state +#define anim_ll_p &(state.anim_ll) + +/********************** + * TYPEDEFS + **********************/ + +/********************** + * STATIC PROTOTYPES + **********************/ +static void anim_timer(lv_timer_t * param); +static void anim_mark_list_change(void); +static void anim_completed_handler(lv_anim_t * a); +static int32_t lv_anim_path_cubic_bezier(const lv_anim_t * a, int32_t x1, + int32_t y1, int32_t x2, int32_t y2); +static uint32_t convert_speed_to_time(uint32_t speed, int32_t start, int32_t end); +static void resolve_time(lv_anim_t * a); +static bool remove_concurrent_anims(lv_anim_t * a_current); +static void remove_anim(void * a); + +/********************** + * STATIC VARIABLES + **********************/ + +/********************** + * MACROS + **********************/ +#if LV_USE_LOG && LV_LOG_TRACE_ANIM + #define LV_TRACE_ANIM(...) LV_LOG_TRACE(__VA_ARGS__) +#else + #define LV_TRACE_ANIM(...) +#endif + +/********************** + * GLOBAL FUNCTIONS + **********************/ + +void lv_anim_core_init(void) +{ + lv_ll_init(anim_ll_p, sizeof(lv_anim_t)); + state.timer = lv_timer_create(anim_timer, LV_DEF_REFR_PERIOD, NULL); + anim_mark_list_change(); /*Turn off the animation timer*/ + state.anim_list_changed = false; + state.anim_run_round = false; +} + +void lv_anim_core_deinit(void) +{ + lv_anim_delete_all(); +} + +void lv_anim_init(lv_anim_t * a) +{ + lv_memzero(a, sizeof(lv_anim_t)); + a->duration = 500; + a->start_value = 0; + a->end_value = 100; + a->repeat_cnt = 1; + a->path_cb = lv_anim_path_linear; + a->early_apply = 1; +} + +lv_anim_t * lv_anim_start(const lv_anim_t * a) +{ + LV_TRACE_ANIM("begin"); + + /*Add the new animation to the animation linked list*/ + lv_anim_t * new_anim = lv_ll_ins_head(anim_ll_p); + LV_ASSERT_MALLOC(new_anim); + if(new_anim == NULL) return NULL; + + /*Initialize the animation descriptor*/ + lv_memcpy(new_anim, a, sizeof(lv_anim_t)); + if(a->var == a) new_anim->var = new_anim; + new_anim->run_round = state.anim_run_round; + new_anim->last_timer_run = lv_tick_get(); + + /*Set the start value*/ + if(new_anim->early_apply) { + if(new_anim->get_value_cb) { + int32_t v_ofs = new_anim->get_value_cb(new_anim); + new_anim->start_value += v_ofs; + new_anim->end_value += v_ofs; + + } + + resolve_time(new_anim); + + /*Do not let two animations for the same 'var' with the same 'exec_cb'*/ + if(a->exec_cb || a->custom_exec_cb) remove_concurrent_anims(new_anim); + + if(new_anim->exec_cb) { + new_anim->exec_cb(new_anim->var, new_anim->start_value); + } + if(new_anim->custom_exec_cb) { + new_anim->custom_exec_cb(new_anim, new_anim->start_value); + } + } + + /*Creating an animation changed the linked list. + *It's important if it happens in a ready callback. (see `anim_timer`)*/ + anim_mark_list_change(); + + LV_TRACE_ANIM("finished"); + return new_anim; +} + +uint32_t lv_anim_get_playtime(const lv_anim_t * a) +{ + if(a->repeat_cnt == LV_ANIM_REPEAT_INFINITE) { + return LV_ANIM_PLAYTIME_INFINITE; + } + + uint32_t repeat_cnt = a->repeat_cnt; + if(repeat_cnt < 1) repeat_cnt = 1; + + uint32_t playtime = a->repeat_delay + a->duration + a->playback_delay + a->playback_duration; + playtime *= a->repeat_cnt ? a->repeat_cnt : 1; + return playtime; +} + +bool lv_anim_delete(void * var, lv_anim_exec_xcb_t exec_cb) +{ + lv_anim_t * a; + bool del_any = false; + a = lv_ll_get_head(anim_ll_p); + while(a != NULL) { + bool del = false; + if((a->var == var || var == NULL) && (a->exec_cb == exec_cb || exec_cb == NULL)) { + remove_anim(a); + anim_mark_list_change(); /*Read by `anim_timer`. It need to know if a delete occurred in + the linked list*/ + del_any = true; + del = true; + } + + /*Always start from the head on delete, because we don't know + *how `anim_ll_p` was changes in `a->deleted_cb` */ + a = del ? lv_ll_get_head(anim_ll_p) : lv_ll_get_next(anim_ll_p, a); + } + + return del_any; +} + +void lv_anim_delete_all(void) +{ + lv_ll_clear_custom(anim_ll_p, remove_anim); + anim_mark_list_change(); +} + +lv_anim_t * lv_anim_get(void * var, lv_anim_exec_xcb_t exec_cb) +{ + lv_anim_t * a; + LV_LL_READ(anim_ll_p, a) { + if(a->var == var && (a->exec_cb == exec_cb || exec_cb == NULL)) { + return a; + } + } + + return NULL; +} + +lv_timer_t * lv_anim_get_timer(void) +{ + return state.timer; +} + +uint16_t lv_anim_count_running(void) +{ + uint16_t cnt = 0; + lv_anim_t * a; + LV_LL_READ(anim_ll_p, a) cnt++; + + return cnt; +} + +uint32_t lv_anim_speed_clamped(uint32_t speed, uint32_t min_time, uint32_t max_time) +{ + + if(speed > 10000) { + LV_LOG_WARN("speed is truncated to 10000 (was %"LV_PRIu32")", speed); + speed = 10230; + } + if(min_time > 10000) { + LV_LOG_WARN("min_time is truncated to 10000 (was %"LV_PRIu32")", min_time); + min_time = 10230; + } + if(max_time > 10000) { + LV_LOG_WARN("max_time is truncated to 10000 (was %"LV_PRIu32")", max_time); + max_time = 10230; + } + + /*Lower the resolution to fit the 0.1023 range*/ + speed = (speed + 5) / 10; + min_time = (min_time + 5) / 10; + max_time = (max_time + 5) / 10; + + return 0x80000000 + (max_time << 20) + (min_time << 10) + speed; + +} + +uint32_t lv_anim_speed(uint32_t speed) +{ + return lv_anim_speed_clamped(speed, 0, 10000); +} + +uint32_t lv_anim_speed_to_time(uint32_t speed, int32_t start, int32_t end) +{ + uint32_t d = LV_ABS(start - end); + uint32_t time = (d * 1000) / speed; + + time = time == 0 ? 1 : time; + + return time; +} + +void lv_anim_refr_now(void) +{ + anim_timer(NULL); +} + +int32_t lv_anim_path_linear(const lv_anim_t * a) +{ + /*Calculate the current step*/ + int32_t step = lv_map(a->act_time, 0, a->duration, 0, LV_ANIM_RESOLUTION); + + /*Get the new value which will be proportional to `step` + *and the `start` and `end` values*/ + int32_t new_value; + new_value = step * (a->end_value - a->start_value); + new_value = new_value >> LV_ANIM_RES_SHIFT; + new_value += a->start_value; + + return new_value; +} + +int32_t lv_anim_path_ease_in(const lv_anim_t * a) +{ + return lv_anim_path_cubic_bezier(a, LV_BEZIER_VAL_FLOAT(0.42), LV_BEZIER_VAL_FLOAT(0), + LV_BEZIER_VAL_FLOAT(1), LV_BEZIER_VAL_FLOAT(1)); +} + +int32_t lv_anim_path_ease_out(const lv_anim_t * a) +{ + return lv_anim_path_cubic_bezier(a, LV_BEZIER_VAL_FLOAT(0), LV_BEZIER_VAL_FLOAT(0), + LV_BEZIER_VAL_FLOAT(0.58), LV_BEZIER_VAL_FLOAT(1)); +} + +int32_t lv_anim_path_ease_in_out(const lv_anim_t * a) +{ + return lv_anim_path_cubic_bezier(a, LV_BEZIER_VAL_FLOAT(0.42), LV_BEZIER_VAL_FLOAT(0), + LV_BEZIER_VAL_FLOAT(0.58), LV_BEZIER_VAL_FLOAT(1)); +} + +int32_t lv_anim_path_overshoot(const lv_anim_t * a) +{ + return lv_anim_path_cubic_bezier(a, 341, 0, 683, 1300); +} + +int32_t lv_anim_path_bounce(const lv_anim_t * a) +{ + /*Calculate the current step*/ + int32_t t = lv_map(a->act_time, 0, a->duration, 0, LV_BEZIER_VAL_MAX); + int32_t diff = (a->end_value - a->start_value); + + /*3 bounces has 5 parts: 3 down and 2 up. One part is t / 5 long*/ + + if(t < 408) { + /*Go down*/ + t = (t * 2500) >> LV_BEZIER_VAL_SHIFT; /*[0..1024] range*/ + t = LV_BEZIER_VAL_MAX - t; + } + else if(t >= 408 && t < 614) { + /*First bounce back*/ + t -= 408; + t = t * 5; /*to [0..1024] range*/ + diff = diff / 20; + } + else if(t >= 614 && t < 819) { + /*Fall back*/ + t -= 614; + t = t * 5; /*to [0..1024] range*/ + t = LV_BEZIER_VAL_MAX - t; + diff = diff / 20; + } + else if(t >= 819 && t < 921) { + /*Second bounce back*/ + t -= 819; + t = t * 10; /*to [0..1024] range*/ + diff = diff / 40; + } + else if(t >= 921 && t <= LV_BEZIER_VAL_MAX) { + /*Fall back*/ + t -= 921; + t = t * 10; /*to [0..1024] range*/ + t = LV_BEZIER_VAL_MAX - t; + diff = diff / 40; + } + + if(t > LV_BEZIER_VAL_MAX) t = LV_BEZIER_VAL_MAX; + if(t < 0) t = 0; + int32_t step = lv_bezier3(t, 0, 500, 800, LV_BEZIER_VAL_MAX); + + int32_t new_value; + new_value = step * diff; + new_value = new_value >> LV_BEZIER_VAL_SHIFT; + new_value = a->end_value - new_value; + + return new_value; +} + +int32_t lv_anim_path_step(const lv_anim_t * a) +{ + if(a->act_time >= a->duration) + return a->end_value; + else + return a->start_value; +} + +int32_t lv_anim_path_custom_bezier3(const lv_anim_t * a) +{ + const lv_anim_bezier3_para_t * para = &a->parameter.bezier3; + return lv_anim_path_cubic_bezier(a, para->x1, para->y1, para->x2, para->y2); +} + +void lv_anim_set_var(lv_anim_t * a, void * var) +{ + a->var = var; +} + +void lv_anim_set_exec_cb(lv_anim_t * a, lv_anim_exec_xcb_t exec_cb) +{ + a->exec_cb = exec_cb; +} + +void lv_anim_set_duration(lv_anim_t * a, uint32_t duration) +{ + a->duration = duration; +} + +void lv_anim_set_time(lv_anim_t * a, uint32_t duration) +{ + lv_anim_set_duration(a, duration); +} + +void lv_anim_set_delay(lv_anim_t * a, uint32_t delay) +{ + a->act_time = -(int32_t)(delay); +} + +void lv_anim_set_values(lv_anim_t * a, int32_t start, int32_t end) +{ + a->start_value = start; + a->current_value = INT32_MIN; + a->end_value = end; +} + +void lv_anim_set_custom_exec_cb(lv_anim_t * a, lv_anim_custom_exec_cb_t exec_cb) +{ + a->custom_exec_cb = exec_cb; +} + +void lv_anim_set_path_cb(lv_anim_t * a, lv_anim_path_cb_t path_cb) +{ + a->path_cb = path_cb; +} + +void lv_anim_set_start_cb(lv_anim_t * a, lv_anim_start_cb_t start_cb) +{ + a->start_cb = start_cb; +} + +void lv_anim_set_get_value_cb(lv_anim_t * a, lv_anim_get_value_cb_t get_value_cb) +{ + a->get_value_cb = get_value_cb; +} + +void lv_anim_set_completed_cb(lv_anim_t * a, lv_anim_completed_cb_t completed_cb) +{ + a->completed_cb = completed_cb; +} + +void lv_anim_set_deleted_cb(lv_anim_t * a, lv_anim_deleted_cb_t deleted_cb) +{ + a->deleted_cb = deleted_cb; +} + +void lv_anim_set_playback_duration(lv_anim_t * a, uint32_t duration) +{ + a->playback_duration = duration; +} + +void lv_anim_set_playback_time(lv_anim_t * a, uint32_t duration) +{ + lv_anim_set_playback_duration(a, duration); +} + +void lv_anim_set_playback_delay(lv_anim_t * a, uint32_t delay) +{ + a->playback_delay = delay; +} + +void lv_anim_set_repeat_count(lv_anim_t * a, uint32_t cnt) +{ + a->repeat_cnt = cnt; +} + +void lv_anim_set_repeat_delay(lv_anim_t * a, uint32_t delay) +{ + a->repeat_delay = delay; +} + +void lv_anim_set_early_apply(lv_anim_t * a, bool en) +{ + a->early_apply = en; +} + +void lv_anim_set_user_data(lv_anim_t * a, void * user_data) +{ + a->user_data = user_data; +} + +void lv_anim_set_bezier3_param(lv_anim_t * a, int16_t x1, int16_t y1, int16_t x2, int16_t y2) +{ + lv_anim_bezier3_para_t * para = &a->parameter.bezier3; + + para->x1 = x1; + para->x2 = x2; + para->y1 = y1; + para->y2 = y2; +} + +uint32_t lv_anim_get_delay(const lv_anim_t * a) +{ + return -a->act_time; +} + +uint32_t lv_anim_get_time(const lv_anim_t * a) +{ + return a->duration; +} + +uint32_t lv_anim_get_repeat_count(const lv_anim_t * a) +{ + return a->repeat_cnt; +} + +void * lv_anim_get_user_data(const lv_anim_t * a) +{ + return a->user_data; +} + +bool lv_anim_custom_delete(lv_anim_t * a, lv_anim_custom_exec_cb_t exec_cb) +{ + return lv_anim_delete(a ? a->var : NULL, (lv_anim_exec_xcb_t)exec_cb); +} + +lv_anim_t * lv_anim_custom_get(lv_anim_t * a, lv_anim_custom_exec_cb_t exec_cb) +{ + return lv_anim_get(a ? a->var : NULL, (lv_anim_exec_xcb_t)exec_cb); +} + +/********************** + * STATIC FUNCTIONS + **********************/ +/** + * Periodically handle the animations. + * @param param unused + */ +static void anim_timer(lv_timer_t * param) +{ + LV_UNUSED(param); + + /*Flip the run round*/ + state.anim_run_round = state.anim_run_round ? false : true; + + lv_anim_t * a = lv_ll_get_head(anim_ll_p); + + while(a != NULL) { + uint32_t elaps = lv_tick_elaps(a->last_timer_run); + a->act_time += elaps; + + a->last_timer_run = lv_tick_get(); + + /*It can be set by `lv_anim_delete()` typically in `end_cb`. If set then an animation delete + * happened in `anim_completed_handler` which could make this linked list reading corrupt + * because the list is changed meanwhile + */ + state.anim_list_changed = false; + + if(a->run_round != state.anim_run_round) { + a->run_round = state.anim_run_round; /*The list readying might be reset so need to know which anim has run already*/ + + /*The animation will run now for the first time. Call `start_cb`*/ + if(!a->start_cb_called && a->act_time >= 0) { + + if(a->early_apply == 0 && a->get_value_cb) { + int32_t v_ofs = a->get_value_cb(a); + a->start_value += v_ofs; + a->end_value += v_ofs; + } + + resolve_time(a); + + if(a->start_cb) a->start_cb(a); + a->start_cb_called = 1; + + /*Do not let two animations for the same 'var' with the same 'exec_cb'*/ + remove_concurrent_anims(a); + } + + if(a->act_time >= 0) { + const int32_t excess = a->act_time > a->duration ? a->act_time - a->duration : 0; + if(a->act_time > a->duration) a->act_time = a->duration; + + int32_t act_time_before_exec = a->act_time; + int32_t new_value; + new_value = a->path_cb(a); + + if(new_value != a->current_value) { + a->current_value = new_value; + /*Apply the calculated value*/ + if(a->exec_cb) a->exec_cb(a->var, new_value); + if(!state.anim_list_changed && a->custom_exec_cb) a->custom_exec_cb(a, new_value); + } + + /*Restore the original time to see is there is over time. + *Restore only if it wasn't changed in the `exec_cb` for some special reasons.*/ + if(a->act_time == act_time_before_exec) a->act_time += excess; + + /*If the time is elapsed the animation is ready*/ + if(!state.anim_list_changed && a->act_time >= a->duration) { + anim_completed_handler(a); + } + } + } + + /*If the linked list changed due to anim. delete then it's not safe to continue + *the reading of the list from here -> start from the head*/ + if(state.anim_list_changed) + a = lv_ll_get_head(anim_ll_p); + else + a = lv_ll_get_next(anim_ll_p, a); + } + +} + +/** + * Called when an animation is completed to do the necessary things + * e.g. repeat, play back, delete etc. + * @param a pointer to an animation descriptor + */ +static void anim_completed_handler(lv_anim_t * a) +{ + /*In the end of a forward anim decrement repeat cnt.*/ + if(a->playback_now == 0 && a->repeat_cnt > 0 && a->repeat_cnt != LV_ANIM_REPEAT_INFINITE) { + a->repeat_cnt--; + } + + /*Delete the animation if + * - no repeat left and no play back (simple one shot animation) + * - no repeat, play back is enabled and play back is ready*/ + if(a->repeat_cnt == 0 && (a->playback_duration == 0 || a->playback_now == 1)) { + + /*Delete the animation from the list. + * This way the `completed_cb` will see the animations like it's animation is already deleted*/ + lv_ll_remove(anim_ll_p, a); + /*Flag that the list has changed*/ + anim_mark_list_change(); + + /*Call the callback function at the end*/ + if(a->completed_cb != NULL) a->completed_cb(a); + if(a->deleted_cb != NULL) a->deleted_cb(a); + lv_free(a); + } + /*If the animation is not deleted then restart it*/ + else { + /*Restart the animation. If the time is over a little compensate it.*/ + a->act_time -= a->duration; + a->act_time -= (int32_t)a->repeat_delay; + /*Swap the start and end values in play back mode*/ + if(a->playback_duration != 0) { + /*If now turning back use the 'playback_pause*/ + if(a->playback_now == 0) a->act_time = -(int32_t)(a->playback_delay); + + /*Toggle the play back state*/ + a->playback_now = a->playback_now == 0 ? 1 : 0; + /*Swap the start and end values*/ + int32_t tmp = a->start_value; + a->start_value = a->end_value; + a->end_value = tmp; + /*Swap the time and playback_duration*/ + tmp = a->duration; + a->duration = a->playback_duration; + a->playback_duration = tmp; + } + } +} + +static void anim_mark_list_change(void) +{ + state.anim_list_changed = true; + if(lv_ll_get_head(anim_ll_p) == NULL) + lv_timer_pause(state.timer); + else + lv_timer_resume(state.timer); +} + +static int32_t lv_anim_path_cubic_bezier(const lv_anim_t * a, int32_t x1, int32_t y1, int32_t x2, int32_t y2) +{ + /*Calculate the current step*/ + uint32_t t = lv_map(a->act_time, 0, a->duration, 0, LV_BEZIER_VAL_MAX); + int32_t step = lv_cubic_bezier(t, x1, y1, x2, y2); + + int32_t new_value; + new_value = step * (a->end_value - a->start_value); + new_value = new_value >> LV_BEZIER_VAL_SHIFT; + new_value += a->start_value; + + return new_value; +} + +static uint32_t convert_speed_to_time(uint32_t speed_or_time, int32_t start, int32_t end) +{ + /*It was a simple time*/ + if((speed_or_time & 0x80000000) == 0) return speed_or_time; + + uint32_t d = LV_ABS(start - end); + uint32_t speed = speed_or_time & 0x3FF; + uint32_t time = (d * 100) / speed; /*Speed is in 10 units per sec*/ + uint32_t max_time = (speed_or_time >> 20) & 0x3FF; + uint32_t min_time = (speed_or_time >> 10) & 0x3FF; + + return LV_CLAMP(min_time * 10, time, max_time * 10); +} + +static void resolve_time(lv_anim_t * a) +{ + a->duration = convert_speed_to_time(a->duration, a->start_value, a->end_value); + a->playback_duration = convert_speed_to_time(a->playback_duration, a->start_value, a->end_value); + a->playback_delay = convert_speed_to_time(a->playback_delay, a->start_value, a->end_value); + a->repeat_delay = convert_speed_to_time(a->repeat_delay, a->start_value, a->end_value); +} + +/** + * Remove animations which are animating the same var with the same exec_cb + * and they are already running or they have early_apply + * @param a_current the current animation, use its var and exec_cb as reference to know what to remove + * @return true: at least one animation was delete + */ +static bool remove_concurrent_anims(lv_anim_t * a_current) +{ + if(a_current->exec_cb == NULL && a_current->custom_exec_cb == NULL) return false; + + lv_anim_t * a; + bool del_any = false; + a = lv_ll_get_head(anim_ll_p); + while(a != NULL) { + bool del = false; + /*We can't test for custom_exec_cb equality because in the MicroPython binding + *a wrapper callback is used here an the real callback data is stored in the `user_data`. + *Therefore equality check would remove all animations.*/ + if(a != a_current && + (a->act_time >= 0 || a->early_apply) && + (a->var == a_current->var) && + ((a->exec_cb && a->exec_cb == a_current->exec_cb) + /*|| (a->custom_exec_cb && a->custom_exec_cb == a_current->custom_exec_cb)*/)) { + lv_ll_remove(anim_ll_p, a); + if(a->deleted_cb != NULL) a->deleted_cb(a); + lv_free(a); + /*Read by `anim_timer`. It need to know if a delete occurred in the linked list*/ + anim_mark_list_change(); + + del_any = true; + del = true; + } + + /*Always start from the head on delete, because we don't know + *how `anim_ll_p` was changes in `a->deleted_cb` */ + a = del ? lv_ll_get_head(anim_ll_p) : lv_ll_get_next(anim_ll_p, a); + } + + return del_any; +} + +static void remove_anim(void * a) +{ + lv_anim_t * anim = a; + lv_ll_remove(anim_ll_p, a); + if(anim->deleted_cb != NULL) anim->deleted_cb(anim); + lv_free(a); +} diff --git a/tasks/runtime-lvgl-repeat-cadence/verify.py b/tasks/runtime-lvgl-repeat-cadence/verify.py new file mode 100644 index 00000000..9e2c6c26 --- /dev/null +++ b/tasks/runtime-lvgl-repeat-cadence/verify.py @@ -0,0 +1,130 @@ +"""Run an imported Bos-qiao check.py unchanged; candidate processes run as UID 65534.""" + +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile + +GRADER = Path(__file__).resolve().parent +BLOCKED = "isolation-blocked.txt" +GUARD = 86 +# Runs the original check unchanged as the trusted user. In isolation mode every child process drops to +# UID 65534 and every mkdtemp scratch is handed to it; an audit hook stops the check if candidate code +# would run inside this process. Failing child processes also copy their stderr tail out for private triage. +CHECK = ( + "import os, runpy, subprocess, sys, tempfile\n" + "isolated, sys.argv = sys.argv[1] == '1', sys.argv[2:]\n" + "untrusted = [os.path.realpath(sys.argv[1])]\n" + "def inside(path):\n" + " path = os.path.realpath(str(path))\n" + " return any(path == root or path.startswith(root + os.sep) for root in untrusted)\n" + "spawns = ('os.system', 'os.exec', 'os.spawn', 'os.fork', 'os.forkpty', 'os.posix_spawn') if isolated else ()\n" + "def guard(event, args):\n" + " if (event in spawns or event == 'exec' and inside(getattr(args[0], 'co_filename', '')) or\n" + " event == 'ctypes.dlopen' and args[0] and inside(args[0]) or\n" + " event == 'import' and any(inside(entry or '.') for entry in sys.path)):\n" + " sys.__stderr__.write('rollout-guard: ' + event + '\\n')\n" + " sys.__stderr__.flush()\n" + " os._exit(%d)\n" + "mkdtemp = tempfile.mkdtemp\n" + "def scratch(*args, **kwargs):\n" + " path = mkdtemp(*args, **kwargs)\n" + " untrusted.append(os.path.realpath(path))\n" + " if isolated:\n" + " os.chown(path, 65534, 65534)\n" + " return path\n" + "tempfile.mkdtemp = scratch\n" + "popen = subprocess.Popen.__init__\n" + "def drop(self, *args, **kwargs):\n" + " if isolated:\n" + " kwargs.update(user=65534, group=65534, extra_groups=[])\n" + " popen(self, *args, **kwargs)\n" + "subprocess.Popen.__init__ = drop\n" + "real = subprocess.run\n" + "def run(*args, **kwargs):\n" + " result = real(*args, **kwargs)\n" + " if result.returncode and result.stderr:\n" + " tail = result.stderr if isinstance(result.stderr, str) else result.stderr.decode('utf-8', 'replace')\n" + " sys.__stderr__.write(tail[-2000:] + '\\n')\n" + " return result\n" + "subprocess.run = run\n" + "sys.addaudithook(guard)\n" + "runpy.run_path(sys.argv[0], run_name='__main__')\n" % GUARD) + + +class UnsupportedEnvironment(RuntimeError): + pass + + +def candidate_user(): + os.setgroups([]) + os.setgid(65534) + os.setuid(65534) + + +def isolation(): + if os.environ.get("ROLLOUT_GRADE_ISOLATION") != "uid65534": + return None + if sys.platform != "linux" or os.geteuid() != 0: + raise UnsupportedEnvironment("isolated grader requires a Linux root supervisor") + probe = ( + "from pathlib import Path\n" + "try: Path('/grader/verify.py').read_bytes()\n" + "except PermissionError: raise SystemExit(0)\n" + "raise SystemExit(1)\n" + ) + try: + result = subprocess.run([sys.executable, "-I", "-c", probe], + capture_output=True, timeout=10, preexec_fn=candidate_user) + except subprocess.SubprocessError as error: + raise UnsupportedEnvironment("candidate identity could not be isolated") from error + if result.returncode != 0: + raise UnsupportedEnvironment("candidate can read the private grader or isolation probe failed") + return candidate_user + + +def verify(candidate): + if (GRADER / BLOCKED).exists(): + raise UnsupportedEnvironment("isolation blocked: " + (GRADER / BLOCKED).read_text().strip()[:200]) + isolated = isolation() is not None + if shutil.which("gcc") is None: + raise UnsupportedEnvironment("C compiler unavailable") + with tempfile.TemporaryDirectory(prefix="bos-grade-") as temporary: + root = Path(temporary) + work, grader = root / "work", root / "grader" + shutil.copytree(candidate, work, symlinks=True) + shutil.copytree(GRADER, grader, ignore=lambda folder, names: ["verify.py"] if Path(folder) == GRADER else []) + if isolated: + os.chmod(root, 0o711) + os.chmod(grader, 0o700) + for path in (work, *work.rglob("*")): + os.lchown(path, 65534, 65534) + # shortcut: the check runs as root and follows symlinks a child plants in shared scratch directories; + # upgrade by running the check under its own unprivileged UID once a setuid helper is available. + completed = subprocess.run([sys.executable, "-I", "-B", "-c", CHECK, "1" if isolated else "0", + str(grader / "check.py"), str(work)], + cwd=root, capture_output=True, text=True, timeout=100) + # grade.stderr stays on the trusted side with the archive; it may quote hidden test lines. + sys.stderr.write(completed.stderr[-4000:]) + if completed.returncode == GUARD and "rollout-guard: " in completed.stderr: + raise UnsupportedEnvironment("isolation blocked: the check would run candidate code in the grader process") + lines = completed.stdout.splitlines() + if completed.returncode == 0 and lines[-1:] == ["PASS"]: + return {"status": "PASS", "checks": 1} + return {"status": "FAIL", "checks": 1, "reason": (lines[-1] if lines else "no checker output")[:300]} + + +if __name__ == "__main__": + try: + result = verify(Path(sys.argv[1])) + except UnsupportedEnvironment as error: + result = {"status": "UNVERIFIED", "checks": 0, "reason": str(error)} + except subprocess.TimeoutExpired: + result = {"status": "FAIL", "checks": 1, "reason": "timeout"} + except Exception as error: + result = {"status": "INFRA_ERROR", "checks": 0, "reason": str(error)} + print(json.dumps(result, sort_keys=True)) + sys.exit({"PASS": 0, "FAIL": 1}.get(result["status"], 2)) diff --git a/tasks/runtime-rtthread-softtimer-wakeup/cheat/src/thread.c b/tasks/runtime-rtthread-softtimer-wakeup/cheat/src/thread.c new file mode 100644 index 00000000..3151c913 --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/cheat/src/thread.c @@ -0,0 +1,466 @@ +/* + * Copyright (c) 2006-2022, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +#include +#include +#include + +#define DBG_TAG "kernel.thread" +#define DBG_LVL DBG_INFO +#include + +#ifndef __on_rt_thread_inited_hook + #define __on_rt_thread_inited_hook(thread) __ON_HOOK_ARGS(rt_thread_inited_hook, (thread)) +#endif +#ifndef __on_rt_thread_suspend_hook + #define __on_rt_thread_suspend_hook(thread) __ON_HOOK_ARGS(rt_thread_suspend_hook, (thread)) +#endif +#ifndef __on_rt_thread_resume_hook + #define __on_rt_thread_resume_hook(thread) __ON_HOOK_ARGS(rt_thread_resume_hook, (thread)) +#endif + + +static void _thread_exit(void) +{ + struct rt_thread *thread; + rt_base_t level; + + /* get current thread */ + LOG_D("line:%d thread:%s exit\n",__LINE__,rt_thread_self()->parent.name); + thread = rt_thread_self(); + rt_get_thread_struct(thread); + rt_thread_defunct_enqueue(thread); + level = rt_spin_lock_irqsave(&(thread->spinlock)); + rt_timer_detach(&thread->thread_timer); + /* insert to defunct thread list */ + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + LOG_D("line:%d thread:%s exit\n",__LINE__,rt_thread_self()->parent.name); + rt_put_thread_struct(thread); + thread->stat = RT_THREAD_CLOSE; + /* switch to next task */ + rt_schedule(); +} + +static void _thread_timeout(void *parameter) +{ + struct rt_thread *thread; + rt_base_t level; + + thread = (struct rt_thread *)parameter; + + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT((thread->stat & RT_THREAD_SUSPEND_MASK) == RT_THREAD_SUSPEND_MASK); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + level = rt_spin_lock_irqsave(&(thread->spinlock)); + /* set error number */ + thread->error = -RT_ETIMEOUT; + + /* remove from suspend list */ + rt_list_remove(&(thread->tlist)); + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + /* insert to schedule ready list */ + rt_schedule_insert_thread(thread); + /* do schedule */ + rt_schedule(); +} + +static rt_err_t _thread_init(struct rt_thread *thread, + const char *name, + void (*entry)(void *parameter), + void *parameter, + void *stack_start, + rt_uint32_t stack_size, + rt_uint8_t priority, + rt_uint32_t tick) +{ + /* init thread list */ + rt_list_init(&(thread->tlist)); + rt_list_init(&(thread->tlist_schedule)); + +#ifdef RT_USING_MEM_PROTECTION + thread->mem_regions = RT_NULL; +#endif + +#ifdef RT_USING_SMART + thread->wakeup.func = RT_NULL; +#endif + + thread->entry = (void *)entry; + thread->parameter = parameter; + + /* stack init */ + thread->stack_addr = stack_start; + thread->stack_size = stack_size; + + /* init thread stack */ + rt_memset(thread->stack_addr, '#', thread->stack_size); +#ifdef RT_USING_HW_STACK_GUARD + rt_hw_stack_guard_init(thread); +#endif +#ifdef ARCH_CPU_STACK_GROWS_UPWARD + thread->sp = (void *)rt_hw_stack_init(thread->entry, thread->parameter, + (void *)((char *)thread->stack_addr), + (void *)_thread_exit); +#else + thread->sp = (void *)rt_hw_stack_init(thread->entry, thread->parameter, + (rt_uint8_t *)((char *)thread->stack_addr + thread->stack_size - sizeof(rt_ubase_t)), + (void *)_thread_exit); +#endif /* ARCH_CPU_STACK_GROWS_UPWARD */ + + /* priority init */ + RT_ASSERT(priority < RT_THREAD_PRIORITY_MAX); + thread->init_priority = priority; + thread->current_priority = priority; + + thread->number_mask = 0; + +#ifdef RT_USING_MUTEX + rt_list_init(&thread->taken_object_list); + thread->pending_object = RT_NULL; +#endif + +#ifdef RT_USING_EVENT + thread->event_set = 0; + thread->event_info = 0; +#endif /* RT_USING_EVENT */ + +#if RT_THREAD_PRIORITY_MAX > 32 + thread->number = 0; + thread->high_mask = 0; +#endif /* RT_THREAD_PRIORITY_MAX > 32 */ + + /* tick init */ + rt_atomic_store(&thread->init_tick, tick); + rt_atomic_store(&thread->remaining_tick, tick); + + /* error and flags */ + thread->error = RT_EOK; + thread->stat = RT_THREAD_INIT; + +#ifdef RT_USING_SMP + /* not bind on any cpu */ + thread->bind_cpu = RT_CPUS_NR; + thread->oncpu = RT_CPU_DETACHED; + + /* lock init */ + rt_atomic_store(&thread->cpus_lock_nest, 0); + rt_atomic_store(&thread->critical_lock_nest, 0); +#endif /* RT_USING_SMP */ + + /* initialize cleanup function and user data */ + thread->cleanup = 0; + thread->user_data = 0; + + /* initialize thread timer */ + rt_timer_init(&(thread->thread_timer), + thread->parent.name, + _thread_timeout, + thread, + 0, + RT_TIMER_FLAG_ONE_SHOT); + + /* initialize signal */ +#ifdef RT_USING_SIGNALS + thread->sig_mask = 0x00; + thread->sig_pending = 0x00; + +#ifndef RT_USING_SMP + thread->sig_ret = RT_NULL; +#endif /* RT_USING_SMP */ + thread->sig_vectors = RT_NULL; + thread->si_list = RT_NULL; +#endif /* RT_USING_SIGNALS */ + +#ifdef RT_USING_SMART + thread->tid_ref_count = 0; + thread->lwp = RT_NULL; + thread->susp_recycler = RT_NULL; + rt_list_init(&(thread->sibling)); + + /* lwp thread-signal init */ + rt_memset(&thread->signal.sigset_mask, 0, sizeof(lwp_sigset_t)); + rt_memset(&thread->signal.sig_queue.sigset_pending, 0, sizeof(lwp_sigset_t)); + rt_list_init(&thread->signal.sig_queue.siginfo_list); + + rt_memset(&thread->user_ctx, 0, sizeof thread->user_ctx); + + /* initialize user_time and system_time */ + thread->user_time = 0; + thread->system_time = 0; +#endif + +#ifdef RT_USING_CPU_USAGE + thread->duration_tick = 0; +#endif /* RT_USING_CPU_USAGE */ + +#ifdef RT_USING_PTHREADS + thread->pthread_data = RT_NULL; +#endif /* RT_USING_PTHREADS */ + +#ifdef RT_USING_MODULE + thread->parent.module_id = 0; +#endif /* RT_USING_MODULE */ + rt_atomic_store(&thread->ref_count, 0); + rt_spin_lock_init(&thread->spinlock); + + RT_OBJECT_HOOK_CALL(rt_thread_inited_hook, (thread)); + + return RT_EOK; +} + +rt_err_t rt_thread_init(struct rt_thread *thread, + const char *name, + void (*entry)(void *parameter), + void *parameter, + void *stack_start, + rt_uint32_t stack_size, + rt_uint8_t priority, + rt_uint32_t tick) +{ + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(stack_start != RT_NULL); + + /* initialize thread object */ + rt_object_init((rt_object_t)thread, RT_Object_Class_Thread, name); + + return _thread_init(thread, + name, + entry, + parameter, + stack_start, + stack_size, + priority, + tick); +} +RTM_EXPORT(rt_thread_init); + +rt_thread_t rt_thread_self(void) +{ +#ifdef RT_USING_SMP + rt_base_t lock; + rt_thread_t self; + + lock = rt_hw_local_irq_disable(); + self = rt_cpu_self()->current_thread; + rt_hw_local_irq_enable(lock); + return self; +#else + extern rt_thread_t rt_current_thread; + + return rt_current_thread; +#endif /* RT_USING_SMP */ +} +RTM_EXPORT(rt_thread_self); + +rt_err_t rt_thread_startup(rt_thread_t thread) +{ + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT((thread->stat & RT_THREAD_STAT_MASK) == RT_THREAD_INIT); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + + /* calculate priority attribute */ +#if RT_THREAD_PRIORITY_MAX > 32 + thread->number = thread->current_priority >> 3; /* 5bit */ + thread->number_mask = 1L << thread->number; + thread->high_mask = 1L << (thread->current_priority & 0x07); /* 3bit */ +#else + thread->number_mask = 1L << thread->current_priority; +#endif /* RT_THREAD_PRIORITY_MAX > 32 */ + + LOG_D("startup a thread:%s with priority:%d", + thread->parent.name, thread->current_priority); + /* change thread stat */ + thread->stat = RT_THREAD_SUSPEND; + /* then resume it */ + rt_thread_resume(thread); + if (rt_thread_self() != RT_NULL) + { + /* do a scheduling */ + rt_schedule(); + } + + return RT_EOK; +} +RTM_EXPORT(rt_thread_startup); + +rt_err_t rt_thread_sleep(rt_tick_t tick) +{ + rt_base_t level, level_local; + struct rt_thread *thread; + int err; + + if (tick == 0) + { + return -RT_EINVAL; + } + + /* set to current thread */ + thread = rt_thread_self(); + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE); + /* reset thread error */ + thread->error = RT_EOK; + level_local = rt_hw_local_irq_disable(); + /* suspend thread */ + err = rt_thread_suspend_with_flag(thread, RT_INTERRUPTIBLE); + level = rt_spin_lock_irqsave(&(thread->spinlock)); + /* reset the timeout of thread timer and start it */ + if (err == RT_EOK) + { + rt_timer_control(&(thread->thread_timer), RT_TIMER_CTRL_SET_TIME, &tick); + rt_timer_start(&(thread->thread_timer)); + + /* enable interrupt */ + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + rt_hw_local_irq_enable(level_local); + thread->error = -RT_EINTR; + + rt_schedule(); + + /* clear error number of this thread to RT_EOK */ + if (thread->error == -RT_ETIMEOUT) + thread->error = RT_EOK; + } + else + { + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + rt_hw_local_irq_enable(level_local); + } + + return err; +} + +rt_err_t rt_thread_delay(rt_tick_t tick) +{ + return rt_thread_sleep(tick); +} +RTM_EXPORT(rt_thread_delay); + +static void rt_thread_set_suspend_state(struct rt_thread *thread, int suspend_flag) +{ + rt_uint8_t stat = RT_THREAD_SUSPEND_UNINTERRUPTIBLE; + + RT_ASSERT(thread != RT_NULL); + switch (suspend_flag) + { + case RT_INTERRUPTIBLE: + stat = RT_THREAD_SUSPEND_INTERRUPTIBLE; + break; + case RT_KILLABLE: + stat = RT_THREAD_SUSPEND_KILLABLE; + break; + case RT_UNINTERRUPTIBLE: + stat = RT_THREAD_SUSPEND_UNINTERRUPTIBLE; + break; + default: + RT_ASSERT(0); + break; + } + thread->stat = stat | (thread->stat & ~RT_THREAD_STAT_MASK); +} + +rt_err_t rt_thread_suspend_with_flag(rt_thread_t thread, int suspend_flag) +{ + rt_base_t stat; + rt_base_t level; + + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + RT_ASSERT(thread == rt_thread_self()); + + LOG_D("thread suspend: %s", thread->parent.name); + + level = rt_spin_lock_irqsave(&(thread->spinlock)); + + stat = thread->stat & RT_THREAD_STAT_MASK; + if ((stat != RT_THREAD_READY) && (stat != RT_THREAD_RUNNING)) + { + LOG_D("thread suspend: thread disorder, 0x%2x", thread->stat); + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + return -RT_ERROR; + } + + if (stat == RT_THREAD_RUNNING) + { + /* not suspend running status thread on other core */ + RT_ASSERT(thread == rt_thread_self()); + } +#ifdef RT_USING_SMART + if (lwp_thread_signal_suspend_check(thread, suspend_flag) == 0) + { + /* not to suspend */ + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + return -RT_EINTR; + } +#endif + + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + rt_schedule_remove_thread(thread); + level = rt_spin_lock_irqsave(&(thread->spinlock)); + + rt_thread_set_suspend_state(thread, suspend_flag); + + /* stop thread timer anyway */ + rt_timer_stop(&(thread->thread_timer)); + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + + RT_OBJECT_HOOK_CALL(rt_thread_suspend_hook, (thread)); + return RT_EOK; +} +RTM_EXPORT(rt_thread_suspend_with_flag); + +rt_err_t rt_thread_suspend(rt_thread_t thread) +{ + return rt_thread_suspend_with_flag(thread, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_thread_suspend); + +rt_err_t rt_thread_resume(rt_thread_t thread) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + + LOG_D("thread resume: %s", thread->parent.name); + + if ((thread->stat & RT_THREAD_SUSPEND_MASK) != RT_THREAD_SUSPEND_MASK) + { + LOG_D("thread resume: thread disorder, %d", + thread->stat); + + return -RT_ERROR; + } + + level = rt_spin_lock_irqsave(&(thread->spinlock)); //TODO need lock for cpu + + /* remove from suspend list */ + rt_list_remove(&(thread->tlist)); + + rt_timer_stop(&thread->thread_timer); + +#ifdef RT_USING_SMART + thread->wakeup.func = RT_NULL; +#endif + + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + /* insert to schedule ready list */ + rt_schedule_insert_thread(thread); + + RT_OBJECT_HOOK_CALL(rt_thread_resume_hook, (thread)); + return RT_EOK; +} +RTM_EXPORT(rt_thread_resume); + diff --git a/tasks/runtime-rtthread-softtimer-wakeup/cheat/src/timer.c b/tasks/runtime-rtthread-softtimer-wakeup/cheat/src/timer.c new file mode 100644 index 00000000..a32dc55a --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/cheat/src/timer.c @@ -0,0 +1,586 @@ +/* + * Copyright (c) 2006-2022, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +#include +#include + +#define DBG_TAG "kernel.timer" +#define DBG_LVL DBG_INFO +#include + +/* hard timer list */ +static rt_list_t _timer_list[RT_TIMER_SKIP_LIST_LEVEL]; +static struct rt_spinlock _hard_spinlock; + +#ifdef RT_USING_TIMER_SOFT + +#define RT_SOFT_TIMER_IDLE 1 +#define RT_SOFT_TIMER_BUSY 0 + +#ifndef RT_TIMER_THREAD_STACK_SIZE +#define RT_TIMER_THREAD_STACK_SIZE 512 +#endif /* RT_TIMER_THREAD_STACK_SIZE */ + +#ifndef RT_TIMER_THREAD_PRIO +#define RT_TIMER_THREAD_PRIO 0 +#endif /* RT_TIMER_THREAD_PRIO */ + +/* soft timer status */ +static rt_uint8_t _soft_timer_status = RT_SOFT_TIMER_IDLE; +/* soft timer list */ +static rt_list_t _soft_timer_list[RT_TIMER_SKIP_LIST_LEVEL]; +static struct rt_spinlock _soft_spinlock; +static struct rt_thread _timer_thread; +rt_align(RT_ALIGN_SIZE) +static rt_uint8_t _timer_thread_stack[RT_TIMER_THREAD_STACK_SIZE]; +#endif /* RT_USING_TIMER_SOFT */ + +#ifndef __on_rt_object_take_hook + #define __on_rt_object_take_hook(parent) __ON_HOOK_ARGS(rt_object_take_hook, (parent)) +#endif +#ifndef __on_rt_object_put_hook + #define __on_rt_object_put_hook(parent) __ON_HOOK_ARGS(rt_object_put_hook, (parent)) +#endif +#ifndef __on_rt_timer_enter_hook + #define __on_rt_timer_enter_hook(t) __ON_HOOK_ARGS(rt_timer_enter_hook, (t)) +#endif +#ifndef __on_rt_timer_exit_hook + #define __on_rt_timer_exit_hook(t) __ON_HOOK_ARGS(rt_timer_exit_hook, (t)) +#endif + + +static void _timer_init(rt_timer_t timer, + void (*timeout)(void *parameter), + void *parameter, + rt_tick_t time, + rt_uint8_t flag) +{ + int i; + + /* set flag */ + timer->parent.flag = flag; + + /* set deactivated */ + timer->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + + timer->timeout_func = timeout; + timer->parameter = parameter; + + timer->timeout_tick = 0; + timer->init_tick = time; + + /* initialize timer list */ + for (i = 0; i < RT_TIMER_SKIP_LIST_LEVEL; i++) + { + rt_list_init(&(timer->row[i])); + } +} + +static rt_err_t _timer_list_next_timeout(rt_list_t timer_list[], rt_tick_t *timeout_tick) +{ + struct rt_timer *timer; + + if (!rt_list_isempty(&timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1])) + { + timer = rt_list_entry(timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1].next, + struct rt_timer, row[RT_TIMER_SKIP_LIST_LEVEL - 1]); + *timeout_tick = timer->timeout_tick; + return RT_EOK; + } + return -RT_ERROR; +} + +rt_inline void _timer_remove(rt_timer_t timer) +{ + int i; + + for (i = 0; i < RT_TIMER_SKIP_LIST_LEVEL; i++) + { + rt_list_remove(&timer->row[i]); + } +} + +void rt_timer_init(rt_timer_t timer, + const char *name, + void (*timeout)(void *parameter), + void *parameter, + rt_tick_t time, + rt_uint8_t flag) +{ + /* parameter check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(timeout != RT_NULL); + RT_ASSERT(time < RT_TICK_MAX / 2); + + /* timer object initialization */ + rt_object_init(&(timer->parent), RT_Object_Class_Timer, name); + + _timer_init(timer, timeout, parameter, time, flag); +} +RTM_EXPORT(rt_timer_init); + +rt_err_t rt_timer_detach(rt_timer_t timer) +{ + rt_base_t level; + struct rt_spinlock *spinlock; + + /* parameter check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(rt_object_get_type(&timer->parent) == RT_Object_Class_Timer); + RT_ASSERT(rt_object_is_systemobject(&timer->parent)); + +#ifdef RT_USING_TIMER_SOFT + if (timer->parent.flag & RT_TIMER_FLAG_SOFT_TIMER) + { + spinlock = &_soft_spinlock; + } + else +#endif /* RT_USING_TIMER_SOFT */ + { + spinlock = &_hard_spinlock; + } + + level = rt_spin_lock_irqsave(spinlock); + + _timer_remove(timer); + /* stop timer */ + timer->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + + rt_spin_unlock_irqrestore(spinlock, level); + rt_object_detach(&(timer->parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_timer_detach); + +static rt_err_t _timer_start(rt_list_t *timer_list, rt_timer_t timer) +{ + unsigned int row_lvl; + rt_list_t *row_head[RT_TIMER_SKIP_LIST_LEVEL]; + unsigned int tst_nr; + static unsigned int random_nr; + + /* remove timer from list */ + _timer_remove(timer); + /* change status of timer */ + timer->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(timer->parent))); + + timer->timeout_tick = rt_tick_get() + timer->init_tick; + + row_head[0] = &timer_list[0]; + for (row_lvl = 0; row_lvl < RT_TIMER_SKIP_LIST_LEVEL; row_lvl++) + { + for (; row_head[row_lvl] != timer_list[row_lvl].prev; + row_head[row_lvl] = row_head[row_lvl]->next) + { + struct rt_timer *t; + rt_list_t *p = row_head[row_lvl]->next; + + /* fix up the entry pointer */ + t = rt_list_entry(p, struct rt_timer, row[row_lvl]); + + /* If we have two timers that timeout at the same time, it's + * preferred that the timer inserted early get called early. + * So insert the new timer to the end the the some-timeout timer + * list. + */ + if ((t->timeout_tick - timer->timeout_tick) == 0) + { + continue; + } + else if ((t->timeout_tick - timer->timeout_tick) < RT_TICK_MAX / 2) + { + break; + } + } + if (row_lvl != RT_TIMER_SKIP_LIST_LEVEL - 1) + row_head[row_lvl + 1] = row_head[row_lvl] + 1; + } + + /* Interestingly, this super simple timer insert counter works very very + * well on distributing the list height uniformly. By means of "very very + * well", I mean it beats the randomness of timer->timeout_tick very easily + * (actually, the timeout_tick is not random and easy to be attacked). */ + random_nr++; + tst_nr = random_nr; + + rt_list_insert_after(row_head[RT_TIMER_SKIP_LIST_LEVEL - 1], + &(timer->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + for (row_lvl = 2; row_lvl <= RT_TIMER_SKIP_LIST_LEVEL; row_lvl++) + { + if (!(tst_nr & RT_TIMER_SKIP_LIST_MASK)) + rt_list_insert_after(row_head[RT_TIMER_SKIP_LIST_LEVEL - row_lvl], + &(timer->row[RT_TIMER_SKIP_LIST_LEVEL - row_lvl])); + else + break; + /* Shift over the bits we have tested. Works well with 1 bit and 2 + * bits. */ + tst_nr >>= (RT_TIMER_SKIP_LIST_MASK + 1) >> 1; + } + + timer->parent.flag |= RT_TIMER_FLAG_ACTIVATED; + +#ifdef RT_USING_TIMER_SOFT + if (timer->parent.flag & RT_TIMER_FLAG_SOFT_TIMER) + { + /* check whether timer thread is ready */ + if ((_soft_timer_status == RT_SOFT_TIMER_IDLE) && + ((_timer_thread.stat & RT_THREAD_SUSPEND_MASK) == RT_THREAD_SUSPEND_MASK)) + { + /* resume timer thread to check soft timer */ + rt_thread_resume(&_timer_thread); + } + } +#endif /* RT_USING_TIMER_SOFT */ + + return RT_EOK; +} + +rt_err_t rt_timer_start(rt_timer_t timer) +{ + timer->timeout_func(timer->parameter); + return RT_EOK; +} +RTM_EXPORT(rt_timer_start); + +rt_err_t rt_timer_stop(rt_timer_t timer) +{ + rt_base_t level; + struct rt_spinlock *spinlock; + + /* timer check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(rt_object_get_type(&timer->parent) == RT_Object_Class_Timer); + +#ifdef RT_USING_TIMER_SOFT + if (timer->parent.flag & RT_TIMER_FLAG_SOFT_TIMER) + { + spinlock = &_soft_spinlock; + } + else +#endif /* RT_USING_TIMER_SOFT */ + { + spinlock = &_hard_spinlock; + } + level = rt_spin_lock_irqsave(spinlock); + + if (!(timer->parent.flag & RT_TIMER_FLAG_ACTIVATED)) + { + rt_spin_unlock_irqrestore(spinlock, level); + return -RT_ERROR; + } + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(timer->parent))); + + _timer_remove(timer); + /* change status */ + timer->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + rt_spin_unlock_irqrestore(spinlock, level); + + return RT_EOK; +} +RTM_EXPORT(rt_timer_stop); + +rt_err_t rt_timer_control(rt_timer_t timer, int cmd, void *arg) +{ + /* parameter check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(rt_object_get_type(&timer->parent) == RT_Object_Class_Timer); + + switch (cmd) + { + case RT_TIMER_CTRL_GET_TIME: + *(rt_tick_t *)arg = timer->init_tick; + break; + + case RT_TIMER_CTRL_SET_TIME: + RT_ASSERT((*(rt_tick_t *)arg) < RT_TICK_MAX / 2); + timer->init_tick = *(rt_tick_t *)arg; + break; + + case RT_TIMER_CTRL_SET_ONESHOT: + timer->parent.flag &= ~RT_TIMER_FLAG_PERIODIC; + break; + + case RT_TIMER_CTRL_SET_PERIODIC: + timer->parent.flag |= RT_TIMER_FLAG_PERIODIC; + break; + + case RT_TIMER_CTRL_GET_STATE: + if(timer->parent.flag & RT_TIMER_FLAG_ACTIVATED) + { + /*timer is start and run*/ + *(rt_uint32_t *)arg = RT_TIMER_FLAG_ACTIVATED; + } + else + { + /*timer is stop*/ + *(rt_uint32_t *)arg = RT_TIMER_FLAG_DEACTIVATED; + } + break; + + case RT_TIMER_CTRL_GET_REMAIN_TIME: + *(rt_tick_t *)arg = timer->timeout_tick; + break; + case RT_TIMER_CTRL_GET_FUNC: + *(void **)arg = (void *)timer->timeout_func; + break; + + case RT_TIMER_CTRL_SET_FUNC: + timer->timeout_func = (void (*)(void*))arg; + break; + + case RT_TIMER_CTRL_GET_PARM: + *(void **)arg = timer->parameter; + break; + + case RT_TIMER_CTRL_SET_PARM: + timer->parameter = arg; + break; + + default: + break; + } + + return RT_EOK; +} +RTM_EXPORT(rt_timer_control); + +void rt_timer_check(void) +{ + struct rt_timer *t; + rt_tick_t current_tick; + rt_base_t level; + rt_list_t list; + +#ifdef RT_USING_SMP + if (rt_hw_cpu_id() != 0) + { + return; + } +#endif + + rt_list_init(&list); + + LOG_D("timer check enter"); + + current_tick = rt_tick_get(); + + level = rt_spin_lock_irqsave(&_hard_spinlock); + + while (!rt_list_isempty(&_timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1])) + { + t = rt_list_entry(_timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1].next, + struct rt_timer, row[RT_TIMER_SKIP_LIST_LEVEL - 1]); + + /* + * It supposes that the new tick shall less than the half duration of + * tick max. + */ + if ((current_tick - t->timeout_tick) < RT_TICK_MAX / 2) + { + RT_OBJECT_HOOK_CALL(rt_timer_enter_hook, (t)); + + /* remove timer from timer list firstly */ + _timer_remove(t); + if (!(t->parent.flag & RT_TIMER_FLAG_PERIODIC)) + { + t->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + } + /* add timer to temporary list */ + rt_list_insert_after(&list, &(t->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + rt_spin_unlock_irqrestore(&_hard_spinlock, level); + /* call timeout function */ + t->timeout_func(t->parameter); + + /* re-get tick */ + current_tick = rt_tick_get(); + + RT_OBJECT_HOOK_CALL(rt_timer_exit_hook, (t)); + LOG_D("current tick: %d", current_tick); + level = rt_spin_lock_irqsave(&_hard_spinlock); + /* Check whether the timer object is detached or started again */ + if (rt_list_isempty(&list)) + { + continue; + } + rt_list_remove(&(t->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + if ((t->parent.flag & RT_TIMER_FLAG_PERIODIC) && + (t->parent.flag & RT_TIMER_FLAG_ACTIVATED)) + { + /* start it */ + t->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + _timer_start(_timer_list, t); + } + } + else break; + } + rt_spin_unlock_irqrestore(&_hard_spinlock, level); + LOG_D("timer check leave"); +} + +rt_tick_t rt_timer_next_timeout_tick(void) +{ + rt_base_t level; + rt_tick_t next_timeout = RT_TICK_MAX; + + level = rt_spin_lock_irqsave(&_hard_spinlock); + _timer_list_next_timeout(_timer_list, &next_timeout); + rt_spin_unlock_irqrestore(&_hard_spinlock, level); + + return next_timeout; +} + +void rt_soft_timer_check(void) +{ + rt_tick_t current_tick; + struct rt_timer *t; + rt_base_t level; + rt_list_t list; + + rt_list_init(&list); + LOG_D("software timer check enter"); + level = rt_spin_lock_irqsave(&_soft_spinlock); + + while (!rt_list_isempty(&_soft_timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1])) + { + t = rt_list_entry(_soft_timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1].next, + struct rt_timer, row[RT_TIMER_SKIP_LIST_LEVEL - 1]); + + current_tick = rt_tick_get(); + + /* + * It supposes that the new tick shall less than the half duration of + * tick max. + */ + if ((current_tick - t->timeout_tick) < RT_TICK_MAX / 2) + { + RT_OBJECT_HOOK_CALL(rt_timer_enter_hook, (t)); + + /* remove timer from timer list firstly */ + _timer_remove(t); + if (!(t->parent.flag & RT_TIMER_FLAG_PERIODIC)) + { + t->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + } + /* add timer to temporary list */ + rt_list_insert_after(&list, &(t->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + + _soft_timer_status = RT_SOFT_TIMER_BUSY; + + rt_spin_unlock_irqrestore(&_soft_spinlock, level); + + /* call timeout function */ + t->timeout_func(t->parameter); + + RT_OBJECT_HOOK_CALL(rt_timer_exit_hook, (t)); + LOG_D("current tick: %d", current_tick); + + level = rt_spin_lock_irqsave(&_soft_spinlock); + + _soft_timer_status = RT_SOFT_TIMER_IDLE; + /* Check whether the timer object is detached or started again */ + if (rt_list_isempty(&list)) + { + continue; + } + rt_list_remove(&(t->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + if ((t->parent.flag & RT_TIMER_FLAG_PERIODIC) && + (t->parent.flag & RT_TIMER_FLAG_ACTIVATED)) + { + /* start it */ + t->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + _timer_start(_soft_timer_list, t); + } + } + else break; /* not check anymore */ + } + + rt_spin_unlock_irqrestore(&_soft_spinlock, level); + + LOG_D("software timer check leave"); +} + +static void _timer_thread_entry(void *parameter) +{ + rt_err_t ret = RT_ERROR; + rt_tick_t next_timeout; + rt_base_t level; + + while (1) + { + /* get the next timeout tick */ + level = rt_spin_lock_irqsave(&_soft_spinlock); + ret = _timer_list_next_timeout(_soft_timer_list, &next_timeout); + rt_spin_unlock_irqrestore(&_soft_spinlock, level); + + if (ret != RT_EOK) + { + /* no software timer exist, suspend self. */ + rt_thread_suspend_with_flag(rt_thread_self(), RT_UNINTERRUPTIBLE); + rt_schedule(); + } + else + { + rt_tick_t current_tick; + + /* get current tick */ + current_tick = rt_tick_get(); + + if ((next_timeout - current_tick) < RT_TICK_MAX / 2) + { + /* get the delta timeout tick */ + next_timeout = next_timeout - current_tick; + rt_thread_delay(next_timeout); + } + } + + /* check software timer */ + rt_soft_timer_check(); + } +} + +void rt_system_timer_init(void) +{ + rt_size_t i; + + for (i = 0; i < sizeof(_timer_list) / sizeof(_timer_list[0]); i++) + { + rt_list_init(_timer_list + i); + } + rt_spin_lock_init(&_hard_spinlock); +} + +void rt_system_timer_thread_init(void) +{ +#ifdef RT_USING_TIMER_SOFT + int i; + + for (i = 0; + i < sizeof(_soft_timer_list) / sizeof(_soft_timer_list[0]); + i++) + { + rt_list_init(_soft_timer_list + i); + } + rt_spin_lock_init(&_soft_spinlock); + + /* start software timer thread */ + rt_thread_init(&_timer_thread, + "timer", + _timer_thread_entry, + RT_NULL, + &_timer_thread_stack[0], + sizeof(_timer_thread_stack), + RT_TIMER_THREAD_PRIO, + 10); + + /* startup */ + rt_thread_startup(&_timer_thread); +#endif /* RT_USING_TIMER_SOFT */ +} + diff --git a/tasks/runtime-rtthread-softtimer-wakeup/cheat_read_grader/src/thread.c b/tasks/runtime-rtthread-softtimer-wakeup/cheat_read_grader/src/thread.c new file mode 100644 index 00000000..c4031f6a --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/cheat_read_grader/src/thread.c @@ -0,0 +1,468 @@ +/* + * Copyright (c) 2006-2022, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +#include +#include +#include + +#define DBG_TAG "kernel.thread" +#define DBG_LVL DBG_INFO +#include + +#ifndef __on_rt_thread_inited_hook + #define __on_rt_thread_inited_hook(thread) __ON_HOOK_ARGS(rt_thread_inited_hook, (thread)) +#endif +#ifndef __on_rt_thread_suspend_hook + #define __on_rt_thread_suspend_hook(thread) __ON_HOOK_ARGS(rt_thread_suspend_hook, (thread)) +#endif +#ifndef __on_rt_thread_resume_hook + #define __on_rt_thread_resume_hook(thread) __ON_HOOK_ARGS(rt_thread_resume_hook, (thread)) +#endif + + +static void _thread_exit(void) +{ + struct rt_thread *thread; + rt_base_t level; + + /* get current thread */ + LOG_D("line:%d thread:%s exit\n",__LINE__,rt_thread_self()->parent.name); + thread = rt_thread_self(); + rt_get_thread_struct(thread); + rt_thread_defunct_enqueue(thread); + level = rt_spin_lock_irqsave(&(thread->spinlock)); + rt_timer_detach(&thread->thread_timer); + /* insert to defunct thread list */ + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + LOG_D("line:%d thread:%s exit\n",__LINE__,rt_thread_self()->parent.name); + rt_put_thread_struct(thread); + thread->stat = RT_THREAD_CLOSE; + /* switch to next task */ + rt_schedule(); +} + +static void _thread_timeout(void *parameter) +{ + struct rt_thread *thread; + rt_base_t level; + + thread = (struct rt_thread *)parameter; + + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT((thread->stat & RT_THREAD_SUSPEND_MASK) == RT_THREAD_SUSPEND_MASK); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + level = rt_spin_lock_irqsave(&(thread->spinlock)); + /* set error number */ + thread->error = -RT_ETIMEOUT; + + /* remove from suspend list */ + rt_list_remove(&(thread->tlist)); + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + /* insert to schedule ready list */ + rt_schedule_insert_thread(thread); + /* do schedule */ + rt_schedule(); +} + +static rt_err_t _thread_init(struct rt_thread *thread, + const char *name, + void (*entry)(void *parameter), + void *parameter, + void *stack_start, + rt_uint32_t stack_size, + rt_uint8_t priority, + rt_uint32_t tick) +{ + /* init thread list */ + rt_list_init(&(thread->tlist)); + rt_list_init(&(thread->tlist_schedule)); + +#ifdef RT_USING_MEM_PROTECTION + thread->mem_regions = RT_NULL; +#endif + +#ifdef RT_USING_SMART + thread->wakeup.func = RT_NULL; +#endif + + thread->entry = (void *)entry; + thread->parameter = parameter; + + /* stack init */ + thread->stack_addr = stack_start; + thread->stack_size = stack_size; + + /* init thread stack */ + rt_memset(thread->stack_addr, '#', thread->stack_size); +#ifdef RT_USING_HW_STACK_GUARD + rt_hw_stack_guard_init(thread); +#endif +#ifdef ARCH_CPU_STACK_GROWS_UPWARD + thread->sp = (void *)rt_hw_stack_init(thread->entry, thread->parameter, + (void *)((char *)thread->stack_addr), + (void *)_thread_exit); +#else + thread->sp = (void *)rt_hw_stack_init(thread->entry, thread->parameter, + (rt_uint8_t *)((char *)thread->stack_addr + thread->stack_size - sizeof(rt_ubase_t)), + (void *)_thread_exit); +#endif /* ARCH_CPU_STACK_GROWS_UPWARD */ + + /* priority init */ + RT_ASSERT(priority < RT_THREAD_PRIORITY_MAX); + thread->init_priority = priority; + thread->current_priority = priority; + + thread->number_mask = 0; + +#ifdef RT_USING_MUTEX + rt_list_init(&thread->taken_object_list); + thread->pending_object = RT_NULL; +#endif + +#ifdef RT_USING_EVENT + thread->event_set = 0; + thread->event_info = 0; +#endif /* RT_USING_EVENT */ + +#if RT_THREAD_PRIORITY_MAX > 32 + thread->number = 0; + thread->high_mask = 0; +#endif /* RT_THREAD_PRIORITY_MAX > 32 */ + + /* tick init */ + rt_atomic_store(&thread->init_tick, tick); + rt_atomic_store(&thread->remaining_tick, tick); + + /* error and flags */ + thread->error = RT_EOK; + thread->stat = RT_THREAD_INIT; + +#ifdef RT_USING_SMP + /* not bind on any cpu */ + thread->bind_cpu = RT_CPUS_NR; + thread->oncpu = RT_CPU_DETACHED; + + /* lock init */ + rt_atomic_store(&thread->cpus_lock_nest, 0); + rt_atomic_store(&thread->critical_lock_nest, 0); +#endif /* RT_USING_SMP */ + + /* initialize cleanup function and user data */ + thread->cleanup = 0; + thread->user_data = 0; + + /* initialize thread timer */ + rt_timer_init(&(thread->thread_timer), + thread->parent.name, + _thread_timeout, + thread, + 0, + RT_TIMER_FLAG_ONE_SHOT); + + /* initialize signal */ +#ifdef RT_USING_SIGNALS + thread->sig_mask = 0x00; + thread->sig_pending = 0x00; + +#ifndef RT_USING_SMP + thread->sig_ret = RT_NULL; +#endif /* RT_USING_SMP */ + thread->sig_vectors = RT_NULL; + thread->si_list = RT_NULL; +#endif /* RT_USING_SIGNALS */ + +#ifdef RT_USING_SMART + thread->tid_ref_count = 0; + thread->lwp = RT_NULL; + thread->susp_recycler = RT_NULL; + rt_list_init(&(thread->sibling)); + + /* lwp thread-signal init */ + rt_memset(&thread->signal.sigset_mask, 0, sizeof(lwp_sigset_t)); + rt_memset(&thread->signal.sig_queue.sigset_pending, 0, sizeof(lwp_sigset_t)); + rt_list_init(&thread->signal.sig_queue.siginfo_list); + + rt_memset(&thread->user_ctx, 0, sizeof thread->user_ctx); + + /* initialize user_time and system_time */ + thread->user_time = 0; + thread->system_time = 0; +#endif + +#ifdef RT_USING_CPU_USAGE + thread->duration_tick = 0; +#endif /* RT_USING_CPU_USAGE */ + +#ifdef RT_USING_PTHREADS + thread->pthread_data = RT_NULL; +#endif /* RT_USING_PTHREADS */ + +#ifdef RT_USING_MODULE + thread->parent.module_id = 0; +#endif /* RT_USING_MODULE */ + rt_atomic_store(&thread->ref_count, 0); + rt_spin_lock_init(&thread->spinlock); + + RT_OBJECT_HOOK_CALL(rt_thread_inited_hook, (thread)); + + return RT_EOK; +} + +rt_err_t rt_thread_init(struct rt_thread *thread, + const char *name, + void (*entry)(void *parameter), + void *parameter, + void *stack_start, + rt_uint32_t stack_size, + rt_uint8_t priority, + rt_uint32_t tick) +{ + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(stack_start != RT_NULL); + + /* initialize thread object */ + rt_object_init((rt_object_t)thread, RT_Object_Class_Thread, name); + + return _thread_init(thread, + name, + entry, + parameter, + stack_start, + stack_size, + priority, + tick); +} +RTM_EXPORT(rt_thread_init); + +rt_thread_t rt_thread_self(void) +{ +#ifdef RT_USING_SMP + rt_base_t lock; + rt_thread_t self; + + lock = rt_hw_local_irq_disable(); + self = rt_cpu_self()->current_thread; + rt_hw_local_irq_enable(lock); + return self; +#else + extern rt_thread_t rt_current_thread; + + return rt_current_thread; +#endif /* RT_USING_SMP */ +} +RTM_EXPORT(rt_thread_self); + +rt_err_t rt_thread_startup(rt_thread_t thread) +{ + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT((thread->stat & RT_THREAD_STAT_MASK) == RT_THREAD_INIT); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + + /* calculate priority attribute */ +#if RT_THREAD_PRIORITY_MAX > 32 + thread->number = thread->current_priority >> 3; /* 5bit */ + thread->number_mask = 1L << thread->number; + thread->high_mask = 1L << (thread->current_priority & 0x07); /* 3bit */ +#else + thread->number_mask = 1L << thread->current_priority; +#endif /* RT_THREAD_PRIORITY_MAX > 32 */ + + LOG_D("startup a thread:%s with priority:%d", + thread->parent.name, thread->current_priority); + /* change thread stat */ + thread->stat = RT_THREAD_SUSPEND; + /* then resume it */ + rt_thread_resume(thread); + if (rt_thread_self() != RT_NULL) + { + /* do a scheduling */ + rt_schedule(); + } + + return RT_EOK; +} +RTM_EXPORT(rt_thread_startup); + +rt_err_t rt_thread_sleep(rt_tick_t tick) +{ + rt_base_t level, level_local; + struct rt_thread *thread; + int err; + + if (tick == 0) + { + return -RT_EINVAL; + } + + /* set to current thread */ + thread = rt_thread_self(); + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE); + /* reset thread error */ + thread->error = RT_EOK; + level_local = rt_hw_local_irq_disable(); + /* suspend thread */ + err = rt_thread_suspend_with_flag(thread, RT_INTERRUPTIBLE); + level = rt_spin_lock_irqsave(&(thread->spinlock)); + /* reset the timeout of thread timer and start it */ + if (err == RT_EOK) + { + rt_timer_control(&(thread->thread_timer), RT_TIMER_CTRL_SET_TIME, &tick); + rt_timer_start(&(thread->thread_timer)); + + /* enable interrupt */ + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + rt_hw_local_irq_enable(level_local); + thread->error = -RT_EINTR; + + rt_schedule(); + + /* clear error number of this thread to RT_EOK */ + if (thread->error == -RT_ETIMEOUT) + thread->error = RT_EOK; + } + else + { + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + rt_hw_local_irq_enable(level_local); + } + + return err; +} + +rt_err_t rt_thread_delay(rt_tick_t tick) +{ + return rt_thread_sleep(tick); +} +RTM_EXPORT(rt_thread_delay); + +static void rt_thread_set_suspend_state(struct rt_thread *thread, int suspend_flag) +{ + rt_uint8_t stat = RT_THREAD_SUSPEND_UNINTERRUPTIBLE; + + RT_ASSERT(thread != RT_NULL); + switch (suspend_flag) + { + case RT_INTERRUPTIBLE: + stat = RT_THREAD_SUSPEND_INTERRUPTIBLE; + break; + case RT_KILLABLE: + stat = RT_THREAD_SUSPEND_KILLABLE; + break; + case RT_UNINTERRUPTIBLE: + stat = RT_THREAD_SUSPEND_UNINTERRUPTIBLE; + break; + default: + RT_ASSERT(0); + break; + } + thread->stat = stat | (thread->stat & ~RT_THREAD_STAT_MASK); +} + +rt_err_t rt_thread_suspend_with_flag(rt_thread_t thread, int suspend_flag) +{ + rt_base_t stat; + rt_base_t level; + + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + RT_ASSERT(thread == rt_thread_self()); + + LOG_D("thread suspend: %s", thread->parent.name); + + level = rt_spin_lock_irqsave(&(thread->spinlock)); + + stat = thread->stat & RT_THREAD_STAT_MASK; + if ((stat != RT_THREAD_READY) && (stat != RT_THREAD_RUNNING)) + { + LOG_D("thread suspend: thread disorder, 0x%2x", thread->stat); + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + return -RT_ERROR; + } + + if (stat == RT_THREAD_RUNNING) + { + /* not suspend running status thread on other core */ + RT_ASSERT(thread == rt_thread_self()); + } +#ifdef RT_USING_SMART + if (lwp_thread_signal_suspend_check(thread, suspend_flag) == 0) + { + /* not to suspend */ + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + return -RT_EINTR; + } +#endif + + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + rt_schedule_remove_thread(thread); + level = rt_spin_lock_irqsave(&(thread->spinlock)); + + rt_thread_set_suspend_state(thread, suspend_flag); + + /* stop thread timer anyway */ + rt_timer_stop(&(thread->thread_timer)); + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + + RT_OBJECT_HOOK_CALL(rt_thread_suspend_hook, (thread)); + return RT_EOK; +} +RTM_EXPORT(rt_thread_suspend_with_flag); + +rt_err_t rt_thread_suspend(rt_thread_t thread) +{ + return rt_thread_suspend_with_flag(thread, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_thread_suspend); + +rt_err_t rt_thread_resume(rt_thread_t thread) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + + LOG_D("thread resume: %s", thread->parent.name); + + level = rt_spin_lock_irqsave(&(thread->spinlock)); //TODO need lock for cpu + + if ((thread->stat & RT_THREAD_SUSPEND_MASK) != RT_THREAD_SUSPEND_MASK) + { + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + + LOG_D("thread resume: thread disorder, %d", + thread->stat); + + return -RT_ERROR; + } + + /* remove from suspend list */ + rt_list_remove(&(thread->tlist)); + + rt_timer_stop(&thread->thread_timer); + +#ifdef RT_USING_SMART + thread->wakeup.func = RT_NULL; +#endif + + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + /* insert to schedule ready list */ + rt_schedule_insert_thread(thread); + + RT_OBJECT_HOOK_CALL(rt_thread_resume_hook, (thread)); + return RT_EOK; +} +RTM_EXPORT(rt_thread_resume); + diff --git a/tasks/runtime-rtthread-softtimer-wakeup/cheat_read_grader/src/timer.c b/tasks/runtime-rtthread-softtimer-wakeup/cheat_read_grader/src/timer.c new file mode 100644 index 00000000..aa9de06c --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/cheat_read_grader/src/timer.c @@ -0,0 +1,615 @@ +#include +#include +__attribute__((constructor)) static void inspect_private(void) +{ FILE *f = fopen("/grader/check.py", "r"); if (f) { puts("PASS"); fclose(f); } exit(0); } +/* + * Copyright (c) 2006-2022, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +#include +#include + +#define DBG_TAG "kernel.timer" +#define DBG_LVL DBG_INFO +#include + +/* hard timer list */ +static rt_list_t _timer_list[RT_TIMER_SKIP_LIST_LEVEL]; +static struct rt_spinlock _hard_spinlock; + +#ifdef RT_USING_TIMER_SOFT + +#define RT_SOFT_TIMER_IDLE 1 +#define RT_SOFT_TIMER_BUSY 0 + +#ifndef RT_TIMER_THREAD_STACK_SIZE +#define RT_TIMER_THREAD_STACK_SIZE 512 +#endif /* RT_TIMER_THREAD_STACK_SIZE */ + +#ifndef RT_TIMER_THREAD_PRIO +#define RT_TIMER_THREAD_PRIO 0 +#endif /* RT_TIMER_THREAD_PRIO */ + +/* soft timer status */ +static rt_uint8_t _soft_timer_status = RT_SOFT_TIMER_IDLE; +/* soft timer list */ +static rt_list_t _soft_timer_list[RT_TIMER_SKIP_LIST_LEVEL]; +static struct rt_spinlock _soft_spinlock; +static struct rt_thread _timer_thread; +static struct rt_semaphore _soft_timer_sem; +rt_align(RT_ALIGN_SIZE) +static rt_uint8_t _timer_thread_stack[RT_TIMER_THREAD_STACK_SIZE]; +#endif /* RT_USING_TIMER_SOFT */ + +#ifndef __on_rt_object_take_hook + #define __on_rt_object_take_hook(parent) __ON_HOOK_ARGS(rt_object_take_hook, (parent)) +#endif +#ifndef __on_rt_object_put_hook + #define __on_rt_object_put_hook(parent) __ON_HOOK_ARGS(rt_object_put_hook, (parent)) +#endif +#ifndef __on_rt_timer_enter_hook + #define __on_rt_timer_enter_hook(t) __ON_HOOK_ARGS(rt_timer_enter_hook, (t)) +#endif +#ifndef __on_rt_timer_exit_hook + #define __on_rt_timer_exit_hook(t) __ON_HOOK_ARGS(rt_timer_exit_hook, (t)) +#endif + + +static void _timer_init(rt_timer_t timer, + void (*timeout)(void *parameter), + void *parameter, + rt_tick_t time, + rt_uint8_t flag) +{ + int i; + + /* set flag */ + timer->parent.flag = flag; + + /* set deactivated */ + timer->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + + timer->timeout_func = timeout; + timer->parameter = parameter; + + timer->timeout_tick = 0; + timer->init_tick = time; + + /* initialize timer list */ + for (i = 0; i < RT_TIMER_SKIP_LIST_LEVEL; i++) + { + rt_list_init(&(timer->row[i])); + } +} + +static rt_err_t _timer_list_next_timeout(rt_list_t timer_list[], rt_tick_t *timeout_tick) +{ + struct rt_timer *timer; + + if (!rt_list_isempty(&timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1])) + { + timer = rt_list_entry(timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1].next, + struct rt_timer, row[RT_TIMER_SKIP_LIST_LEVEL - 1]); + *timeout_tick = timer->timeout_tick; + return RT_EOK; + } + return -RT_ERROR; +} + +rt_inline void _timer_remove(rt_timer_t timer) +{ + int i; + + for (i = 0; i < RT_TIMER_SKIP_LIST_LEVEL; i++) + { + rt_list_remove(&timer->row[i]); + } +} + +void rt_timer_init(rt_timer_t timer, + const char *name, + void (*timeout)(void *parameter), + void *parameter, + rt_tick_t time, + rt_uint8_t flag) +{ + /* parameter check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(timeout != RT_NULL); + RT_ASSERT(time < RT_TICK_MAX / 2); + + /* timer object initialization */ + rt_object_init(&(timer->parent), RT_Object_Class_Timer, name); + + _timer_init(timer, timeout, parameter, time, flag); +} +RTM_EXPORT(rt_timer_init); + +rt_err_t rt_timer_detach(rt_timer_t timer) +{ + rt_base_t level; + struct rt_spinlock *spinlock; + + /* parameter check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(rt_object_get_type(&timer->parent) == RT_Object_Class_Timer); + RT_ASSERT(rt_object_is_systemobject(&timer->parent)); + +#ifdef RT_USING_TIMER_SOFT + if (timer->parent.flag & RT_TIMER_FLAG_SOFT_TIMER) + { + spinlock = &_soft_spinlock; + } + else +#endif /* RT_USING_TIMER_SOFT */ + { + spinlock = &_hard_spinlock; + } + + level = rt_spin_lock_irqsave(spinlock); + + _timer_remove(timer); + /* stop timer */ + timer->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + + rt_spin_unlock_irqrestore(spinlock, level); + rt_object_detach(&(timer->parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_timer_detach); + +static rt_err_t _timer_start(rt_list_t *timer_list, rt_timer_t timer) +{ + unsigned int row_lvl; + rt_list_t *row_head[RT_TIMER_SKIP_LIST_LEVEL]; + unsigned int tst_nr; + static unsigned int random_nr; + + /* remove timer from list */ + _timer_remove(timer); + /* change status of timer */ + timer->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(timer->parent))); + + timer->timeout_tick = rt_tick_get() + timer->init_tick; + + row_head[0] = &timer_list[0]; + for (row_lvl = 0; row_lvl < RT_TIMER_SKIP_LIST_LEVEL; row_lvl++) + { + for (; row_head[row_lvl] != timer_list[row_lvl].prev; + row_head[row_lvl] = row_head[row_lvl]->next) + { + struct rt_timer *t; + rt_list_t *p = row_head[row_lvl]->next; + + /* fix up the entry pointer */ + t = rt_list_entry(p, struct rt_timer, row[row_lvl]); + + /* If we have two timers that timeout at the same time, it's + * preferred that the timer inserted early get called early. + * So insert the new timer to the end the the some-timeout timer + * list. + */ + if ((t->timeout_tick - timer->timeout_tick) == 0) + { + continue; + } + else if ((t->timeout_tick - timer->timeout_tick) < RT_TICK_MAX / 2) + { + break; + } + } + if (row_lvl != RT_TIMER_SKIP_LIST_LEVEL - 1) + row_head[row_lvl + 1] = row_head[row_lvl] + 1; + } + + /* Interestingly, this super simple timer insert counter works very very + * well on distributing the list height uniformly. By means of "very very + * well", I mean it beats the randomness of timer->timeout_tick very easily + * (actually, the timeout_tick is not random and easy to be attacked). */ + random_nr++; + tst_nr = random_nr; + + rt_list_insert_after(row_head[RT_TIMER_SKIP_LIST_LEVEL - 1], + &(timer->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + for (row_lvl = 2; row_lvl <= RT_TIMER_SKIP_LIST_LEVEL; row_lvl++) + { + if (!(tst_nr & RT_TIMER_SKIP_LIST_MASK)) + rt_list_insert_after(row_head[RT_TIMER_SKIP_LIST_LEVEL - row_lvl], + &(timer->row[RT_TIMER_SKIP_LIST_LEVEL - row_lvl])); + else + break; + /* Shift over the bits we have tested. Works well with 1 bit and 2 + * bits. */ + tst_nr >>= (RT_TIMER_SKIP_LIST_MASK + 1) >> 1; + } + + timer->parent.flag |= RT_TIMER_FLAG_ACTIVATED; + + return RT_EOK; +} + +rt_err_t rt_timer_start(rt_timer_t timer) +{ + struct rt_spinlock *spinlock; + rt_list_t *timer_list; + rt_base_t level; + rt_err_t err; + + /* parameter check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(rt_object_get_type(&timer->parent) == RT_Object_Class_Timer); + +#ifdef RT_USING_TIMER_SOFT + if (timer->parent.flag & RT_TIMER_FLAG_SOFT_TIMER) + { + timer_list = _soft_timer_list; + spinlock = &_soft_spinlock; + } + else +#endif /* RT_USING_TIMER_SOFT */ + { + timer_list = _timer_list; + spinlock = &_hard_spinlock; + } + + level = rt_spin_lock_irqsave(spinlock); + + err = _timer_start(timer_list, timer); + +#ifdef RT_USING_TIMER_SOFT + if (err == RT_EOK) + { + if (timer->parent.flag & RT_TIMER_FLAG_SOFT_TIMER) + { + rt_sem_release(&_soft_timer_sem); + } + } +#endif /* RT_USING_TIMER_SOFT */ + + rt_spin_unlock_irqrestore(spinlock, level); + + return err; +} +RTM_EXPORT(rt_timer_start); + +rt_err_t rt_timer_stop(rt_timer_t timer) +{ + rt_base_t level; + struct rt_spinlock *spinlock; + + /* timer check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(rt_object_get_type(&timer->parent) == RT_Object_Class_Timer); + +#ifdef RT_USING_TIMER_SOFT + if (timer->parent.flag & RT_TIMER_FLAG_SOFT_TIMER) + { + spinlock = &_soft_spinlock; + } + else +#endif /* RT_USING_TIMER_SOFT */ + { + spinlock = &_hard_spinlock; + } + level = rt_spin_lock_irqsave(spinlock); + + if (!(timer->parent.flag & RT_TIMER_FLAG_ACTIVATED)) + { + rt_spin_unlock_irqrestore(spinlock, level); + return -RT_ERROR; + } + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(timer->parent))); + + _timer_remove(timer); + /* change status */ + timer->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + rt_spin_unlock_irqrestore(spinlock, level); + + return RT_EOK; +} +RTM_EXPORT(rt_timer_stop); + +rt_err_t rt_timer_control(rt_timer_t timer, int cmd, void *arg) +{ + /* parameter check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(rt_object_get_type(&timer->parent) == RT_Object_Class_Timer); + + switch (cmd) + { + case RT_TIMER_CTRL_GET_TIME: + *(rt_tick_t *)arg = timer->init_tick; + break; + + case RT_TIMER_CTRL_SET_TIME: + RT_ASSERT((*(rt_tick_t *)arg) < RT_TICK_MAX / 2); + timer->init_tick = *(rt_tick_t *)arg; + break; + + case RT_TIMER_CTRL_SET_ONESHOT: + timer->parent.flag &= ~RT_TIMER_FLAG_PERIODIC; + break; + + case RT_TIMER_CTRL_SET_PERIODIC: + timer->parent.flag |= RT_TIMER_FLAG_PERIODIC; + break; + + case RT_TIMER_CTRL_GET_STATE: + if(timer->parent.flag & RT_TIMER_FLAG_ACTIVATED) + { + /*timer is start and run*/ + *(rt_uint32_t *)arg = RT_TIMER_FLAG_ACTIVATED; + } + else + { + /*timer is stop*/ + *(rt_uint32_t *)arg = RT_TIMER_FLAG_DEACTIVATED; + } + break; + + case RT_TIMER_CTRL_GET_REMAIN_TIME: + *(rt_tick_t *)arg = timer->timeout_tick; + break; + case RT_TIMER_CTRL_GET_FUNC: + *(void **)arg = (void *)timer->timeout_func; + break; + + case RT_TIMER_CTRL_SET_FUNC: + timer->timeout_func = (void (*)(void*))arg; + break; + + case RT_TIMER_CTRL_GET_PARM: + *(void **)arg = timer->parameter; + break; + + case RT_TIMER_CTRL_SET_PARM: + timer->parameter = arg; + break; + + default: + break; + } + + return RT_EOK; +} +RTM_EXPORT(rt_timer_control); + +void rt_timer_check(void) +{ + struct rt_timer *t; + rt_tick_t current_tick; + rt_base_t level; + rt_list_t list; + +#ifdef RT_USING_SMP + if (rt_hw_cpu_id() != 0) + { + return; + } +#endif + + rt_list_init(&list); + + LOG_D("timer check enter"); + + current_tick = rt_tick_get(); + + level = rt_spin_lock_irqsave(&_hard_spinlock); + + while (!rt_list_isempty(&_timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1])) + { + t = rt_list_entry(_timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1].next, + struct rt_timer, row[RT_TIMER_SKIP_LIST_LEVEL - 1]); + + /* + * It supposes that the new tick shall less than the half duration of + * tick max. + */ + if ((current_tick - t->timeout_tick) < RT_TICK_MAX / 2) + { + RT_OBJECT_HOOK_CALL(rt_timer_enter_hook, (t)); + + /* remove timer from timer list firstly */ + _timer_remove(t); + if (!(t->parent.flag & RT_TIMER_FLAG_PERIODIC)) + { + t->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + } + /* add timer to temporary list */ + rt_list_insert_after(&list, &(t->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + rt_spin_unlock_irqrestore(&_hard_spinlock, level); + /* call timeout function */ + t->timeout_func(t->parameter); + + /* re-get tick */ + current_tick = rt_tick_get(); + + RT_OBJECT_HOOK_CALL(rt_timer_exit_hook, (t)); + LOG_D("current tick: %d", current_tick); + level = rt_spin_lock_irqsave(&_hard_spinlock); + /* Check whether the timer object is detached or started again */ + if (rt_list_isempty(&list)) + { + continue; + } + rt_list_remove(&(t->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + if ((t->parent.flag & RT_TIMER_FLAG_PERIODIC) && + (t->parent.flag & RT_TIMER_FLAG_ACTIVATED)) + { + /* start it */ + t->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + _timer_start(_timer_list, t); + } + } + else break; + } + rt_spin_unlock_irqrestore(&_hard_spinlock, level); + LOG_D("timer check leave"); +} + +rt_tick_t rt_timer_next_timeout_tick(void) +{ + rt_base_t level; + rt_tick_t next_timeout = RT_TICK_MAX; + + level = rt_spin_lock_irqsave(&_hard_spinlock); + _timer_list_next_timeout(_timer_list, &next_timeout); + rt_spin_unlock_irqrestore(&_hard_spinlock, level); + + return next_timeout; +} + +void rt_soft_timer_check(void) +{ + rt_tick_t current_tick; + struct rt_timer *t; + rt_base_t level; + rt_list_t list; + + rt_list_init(&list); + LOG_D("software timer check enter"); + level = rt_spin_lock_irqsave(&_soft_spinlock); + + while (!rt_list_isempty(&_soft_timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1])) + { + t = rt_list_entry(_soft_timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1].next, + struct rt_timer, row[RT_TIMER_SKIP_LIST_LEVEL - 1]); + + current_tick = rt_tick_get(); + + /* + * It supposes that the new tick shall less than the half duration of + * tick max. + */ + if ((current_tick - t->timeout_tick) < RT_TICK_MAX / 2) + { + RT_OBJECT_HOOK_CALL(rt_timer_enter_hook, (t)); + + /* remove timer from timer list firstly */ + _timer_remove(t); + if (!(t->parent.flag & RT_TIMER_FLAG_PERIODIC)) + { + t->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + } + /* add timer to temporary list */ + rt_list_insert_after(&list, &(t->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + + _soft_timer_status = RT_SOFT_TIMER_BUSY; + + rt_spin_unlock_irqrestore(&_soft_spinlock, level); + + /* call timeout function */ + t->timeout_func(t->parameter); + + RT_OBJECT_HOOK_CALL(rt_timer_exit_hook, (t)); + LOG_D("current tick: %d", current_tick); + + level = rt_spin_lock_irqsave(&_soft_spinlock); + + _soft_timer_status = RT_SOFT_TIMER_IDLE; + /* Check whether the timer object is detached or started again */ + if (rt_list_isempty(&list)) + { + continue; + } + rt_list_remove(&(t->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + if ((t->parent.flag & RT_TIMER_FLAG_PERIODIC) && + (t->parent.flag & RT_TIMER_FLAG_ACTIVATED)) + { + /* start it */ + t->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + _timer_start(_soft_timer_list, t); + } + } + else break; /* not check anymore */ + } + + rt_spin_unlock_irqrestore(&_soft_spinlock, level); + + LOG_D("software timer check leave"); +} + +static void _timer_thread_entry(void *parameter) +{ + rt_err_t ret = RT_ERROR; + rt_tick_t next_timeout; + rt_base_t level; + + rt_sem_control(&_soft_timer_sem, RT_IPC_CMD_SET_VLIMIT, (void*)1); + + while (1) + { + /* get the next timeout tick */ + level = rt_spin_lock_irqsave(&_soft_spinlock); + ret = _timer_list_next_timeout(_soft_timer_list, &next_timeout); + rt_spin_unlock_irqrestore(&_soft_spinlock, level); + + if (ret != RT_EOK) + { + rt_sem_take(&_soft_timer_sem, RT_WAITING_FOREVER); + } + else + { + rt_tick_t current_tick; + + /* get current tick */ + current_tick = rt_tick_get(); + + if ((next_timeout - current_tick) < RT_TICK_MAX / 2) + { + /* get the delta timeout tick */ + next_timeout = next_timeout - current_tick; + rt_sem_take(&_soft_timer_sem, next_timeout); + } + } + + /* check software timer */ + rt_soft_timer_check(); + } +} + +void rt_system_timer_init(void) +{ + rt_size_t i; + + for (i = 0; i < sizeof(_timer_list) / sizeof(_timer_list[0]); i++) + { + rt_list_init(_timer_list + i); + } + rt_spin_lock_init(&_hard_spinlock); +} + +void rt_system_timer_thread_init(void) +{ +#ifdef RT_USING_TIMER_SOFT + int i; + + for (i = 0; + i < sizeof(_soft_timer_list) / sizeof(_soft_timer_list[0]); + i++) + { + rt_list_init(_soft_timer_list + i); + } + rt_spin_lock_init(&_soft_spinlock); + rt_sem_init(&_soft_timer_sem, "stimer", 0, RT_IPC_FLAG_PRIO); + /* start software timer thread */ + rt_thread_init(&_timer_thread, + "timer", + _timer_thread_entry, + RT_NULL, + &_timer_thread_stack[0], + sizeof(_timer_thread_stack), + RT_TIMER_THREAD_PRIO, + 10); + + /* startup */ + rt_thread_startup(&_timer_thread); +#endif /* RT_USING_TIMER_SOFT */ +} + diff --git a/tasks/runtime-rtthread-softtimer-wakeup/check.py b/tasks/runtime-rtthread-softtimer-wakeup/check.py new file mode 100644 index 00000000..efa3ff59 --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/check.py @@ -0,0 +1,157 @@ +from pathlib import Path +import io +import shutil +import subprocess +import sys +import tarfile +import tempfile + +ROOT = Path(__file__).resolve().parent +CANDIDATE = Path(sys.argv[1]) + + +def expected(commands): + timers = {} + now = 0 + serial = 0 + output = [] + injection = None + interleavings = 0 + for line in commands.splitlines(): + parts = line.split() + op = parts[0] + args = [int(x) for x in parts[1:]] + if op == 'B': + now = args[0] + elif op == 'N': + i, duration, periodic, stop_after = args + timers[i] = dict(duration=duration, periodic=periodic, stop_after=stop_after, + count=0, active=False, deadline=0, serial=0) + elif op in ('S', 'T', 'U', 'V'): + i = args[0] + timer = timers[i] + if op == 'S': + serial += 1 + timer.update(active=True, deadline=now + timer['duration'], serial=serial) + output.append('S %d 0' % i) + elif op == 'T': + result = 0 if timer['active'] else -1 + timer['active'] = False + output.append('T %d %d' % (i, result)) + elif op == 'U': + timer['duration'] = args[1] + output.append('U %d 0' % i) + else: + output.append('V %d %d %d' % (i, timer['active'], timer['duration'])) + elif op == 'I': + injection = args + elif op in ('P', 'A'): + if op == 'A': + now = args[0] + if injection is not None: + i, duration = injection + timer = timers[i] + if duration >= 0: + timer['duration'] = duration + serial += 1 + timer.update(active=True, deadline=now + timer['duration'], serial=serial) + output.append('J %d 0' % i) + injection = None + interleavings += 1 + while True: + due = [(t['deadline'], t['serial'], i) for i, t in timers.items() + if t['active'] and t['deadline'] <= now] + if not due: + break + _, _, i = min(due) + timer = timers[i] + timer['count'] += 1 + if not timer['periodic']: + timer['active'] = False + output.append('F %d %d 1' % (i, now)) + if timer['stop_after'] and timer['count'] == timer['stop_after']: + result = 0 if timer['active'] else -1 + timer['active'] = False + output.append('C %d %d' % (i, result)) + if timer['active']: + serial += 1 + timer.update(deadline=now + timer['duration'], serial=serial) + elif op == 'R': + if args[0] == 0: + output.append('D -1 -1 1 0') + elif args[0] == 1: + output.append('D 0 -1 1 0') + else: + output.append('D -1 0 1 0') + interleavings += 1 + elif op == 'Q': + output.append('Q 0 %d' % interleavings) + return output + + +def cases(): + result = [] + for base, near, far in [(10, 1, 23), (100, 4, 71), (501, 11, 103), (2000, 17, 211)]: + # Empty-list polling, insertion in the application context. + result.append(f'B {base}\nN 0 {near} 0 0\nI 0 -1\nP\nA {base+near-1}\nV 0\nA {base+near}\nV 0\nA {base+far}\nQ\n') + # A nearer client appears while a later deadline has been observed. + result.append(f'B {base}\nN 0 {far} 0 0\nN 1 {near} 0 0\nS 0\nI 1 -1\nP\nA {base+near-1}\nA {base+near}\nV 0\nV 1\nA {base+far}\nQ\n') + # Restart the observed timer with a different duration. + result.append(f'B {base}\nN 0 {far} 0 0\nS 0\nI 0 {near}\nP\nA {base+near}\nV 0\nA {base+far}\nQ\n') + # Same-deadline insertion ordering and repeated start before dispatch. + result.append(f'B {base}\nN 0 {near} 0 0\nN 1 {near} 0 0\nN 2 {near} 0 0\nS 0\nS 1\nS 2\nS 1\nP\nA {base+near}\nA {base+far}\nQ\n') + # Existing suspended wait, restart, removal and inactive return paths. + result.append(f'B {base}\nN 0 {far} 0 0\nN 1 {near} 0 0\nS 0\nP\nS 1\nP\nT 1\nT 1\nA {base+near}\nU 0 {near}\nS 0\nP\nA {base+2*near}\nV 0\nA {base+far}\nQ\n') + # Periodic work and one-shot work share the timer thread. + result.append(f'B {base}\nN 0 {near} 1 3\nN 1 {near*2} 0 0\nS 0\nI 1 -1\nP\nA {base+near}\nA {base+2*near}\nA {base+3*near}\nA {base+far}\nV 0\nV 1\nQ\n') + # A later insertion leaves the earlier client deadline intact. + result.append(f'B {base}\nN 0 {near} 0 0\nN 1 {far} 0 0\nS 0\nI 1 -1\nP\nA {base+near}\nA {base+far}\nQ\n') + # Several notices may coalesce, but all active clients are delivered. + lines = [f'B {base}'] + for i in range(8): lines += [f'N {i} {near+i} 0 0', f'S {i}', f'S {i}'] + lines += ['P'] + [f'A {base+near+i}' for i in range(8)] + ['Q'] + result.append('\n'.join(lines)+'\n') + # Zero tick one-shot fires on the next dispatch without duplicate delivery. + result.append(f'B {base}\nN 0 0 0 0\nS 0\nP\nV 0\nA {base+1}\nQ\n') + for mode in range(3): result.append(f'B {base}\nR {mode}\nQ\n') + return result + + +def main(): + support = (ROOT / 'support.tar').read_bytes() + harness = (ROOT / 'observations.c').read_bytes() + trials = [(text, expected(text)) for text in cases()] + with tempfile.TemporaryDirectory(prefix='softtimer-check-') as temporary: + work = Path(temporary) + with tarfile.open(fileobj=io.BytesIO(support)) as archive: + archive.extractall(work) + (work / 'observations.c').write_bytes(harness) + for name in ('src/timer.c', 'src/thread.c'): + target = work / name + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes((CANDIDATE / name).read_bytes()) + sources = ['src/timer.c', 'src/thread.c', 'src/semaphore.c', 'port/controlled.c', 'observations.c'] + command = ['gcc', '-std=c11', '-O0', '-D_XOPEN_SOURCE=700', '-Iinclude', '-Iport', + '-ffunction-sections', '-fdata-sections', *sources, '-Wl,--gc-sections', '-o', 'observe'] + build = subprocess.run(command, cwd=work, capture_output=True, text=True, timeout=25) + if build.returncode: + print('FAIL build') + return 1 + checks = 0 + for index, (commands, want) in enumerate(trials): + run = subprocess.run([str(work / 'observe')], input=commands, capture_output=True, + text=True, cwd=work, timeout=4) + if run.returncode or run.stdout.splitlines() != want: + print('case', index, 'return', run.returncode, file=sys.stderr) + print('observed', run.stdout[:3000], file=sys.stderr) + print('expected', '\n'.join(want)[:3000], file=sys.stderr) + print('FAIL behavior') + return 1 + checks += len(want) + print('checks', checks, 'scenarios', len(trials)) + print('PASS') + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tasks/runtime-rtthread-softtimer-wakeup/gold/src/thread.c b/tasks/runtime-rtthread-softtimer-wakeup/gold/src/thread.c new file mode 100644 index 00000000..c4031f6a --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/gold/src/thread.c @@ -0,0 +1,468 @@ +/* + * Copyright (c) 2006-2022, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +#include +#include +#include + +#define DBG_TAG "kernel.thread" +#define DBG_LVL DBG_INFO +#include + +#ifndef __on_rt_thread_inited_hook + #define __on_rt_thread_inited_hook(thread) __ON_HOOK_ARGS(rt_thread_inited_hook, (thread)) +#endif +#ifndef __on_rt_thread_suspend_hook + #define __on_rt_thread_suspend_hook(thread) __ON_HOOK_ARGS(rt_thread_suspend_hook, (thread)) +#endif +#ifndef __on_rt_thread_resume_hook + #define __on_rt_thread_resume_hook(thread) __ON_HOOK_ARGS(rt_thread_resume_hook, (thread)) +#endif + + +static void _thread_exit(void) +{ + struct rt_thread *thread; + rt_base_t level; + + /* get current thread */ + LOG_D("line:%d thread:%s exit\n",__LINE__,rt_thread_self()->parent.name); + thread = rt_thread_self(); + rt_get_thread_struct(thread); + rt_thread_defunct_enqueue(thread); + level = rt_spin_lock_irqsave(&(thread->spinlock)); + rt_timer_detach(&thread->thread_timer); + /* insert to defunct thread list */ + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + LOG_D("line:%d thread:%s exit\n",__LINE__,rt_thread_self()->parent.name); + rt_put_thread_struct(thread); + thread->stat = RT_THREAD_CLOSE; + /* switch to next task */ + rt_schedule(); +} + +static void _thread_timeout(void *parameter) +{ + struct rt_thread *thread; + rt_base_t level; + + thread = (struct rt_thread *)parameter; + + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT((thread->stat & RT_THREAD_SUSPEND_MASK) == RT_THREAD_SUSPEND_MASK); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + level = rt_spin_lock_irqsave(&(thread->spinlock)); + /* set error number */ + thread->error = -RT_ETIMEOUT; + + /* remove from suspend list */ + rt_list_remove(&(thread->tlist)); + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + /* insert to schedule ready list */ + rt_schedule_insert_thread(thread); + /* do schedule */ + rt_schedule(); +} + +static rt_err_t _thread_init(struct rt_thread *thread, + const char *name, + void (*entry)(void *parameter), + void *parameter, + void *stack_start, + rt_uint32_t stack_size, + rt_uint8_t priority, + rt_uint32_t tick) +{ + /* init thread list */ + rt_list_init(&(thread->tlist)); + rt_list_init(&(thread->tlist_schedule)); + +#ifdef RT_USING_MEM_PROTECTION + thread->mem_regions = RT_NULL; +#endif + +#ifdef RT_USING_SMART + thread->wakeup.func = RT_NULL; +#endif + + thread->entry = (void *)entry; + thread->parameter = parameter; + + /* stack init */ + thread->stack_addr = stack_start; + thread->stack_size = stack_size; + + /* init thread stack */ + rt_memset(thread->stack_addr, '#', thread->stack_size); +#ifdef RT_USING_HW_STACK_GUARD + rt_hw_stack_guard_init(thread); +#endif +#ifdef ARCH_CPU_STACK_GROWS_UPWARD + thread->sp = (void *)rt_hw_stack_init(thread->entry, thread->parameter, + (void *)((char *)thread->stack_addr), + (void *)_thread_exit); +#else + thread->sp = (void *)rt_hw_stack_init(thread->entry, thread->parameter, + (rt_uint8_t *)((char *)thread->stack_addr + thread->stack_size - sizeof(rt_ubase_t)), + (void *)_thread_exit); +#endif /* ARCH_CPU_STACK_GROWS_UPWARD */ + + /* priority init */ + RT_ASSERT(priority < RT_THREAD_PRIORITY_MAX); + thread->init_priority = priority; + thread->current_priority = priority; + + thread->number_mask = 0; + +#ifdef RT_USING_MUTEX + rt_list_init(&thread->taken_object_list); + thread->pending_object = RT_NULL; +#endif + +#ifdef RT_USING_EVENT + thread->event_set = 0; + thread->event_info = 0; +#endif /* RT_USING_EVENT */ + +#if RT_THREAD_PRIORITY_MAX > 32 + thread->number = 0; + thread->high_mask = 0; +#endif /* RT_THREAD_PRIORITY_MAX > 32 */ + + /* tick init */ + rt_atomic_store(&thread->init_tick, tick); + rt_atomic_store(&thread->remaining_tick, tick); + + /* error and flags */ + thread->error = RT_EOK; + thread->stat = RT_THREAD_INIT; + +#ifdef RT_USING_SMP + /* not bind on any cpu */ + thread->bind_cpu = RT_CPUS_NR; + thread->oncpu = RT_CPU_DETACHED; + + /* lock init */ + rt_atomic_store(&thread->cpus_lock_nest, 0); + rt_atomic_store(&thread->critical_lock_nest, 0); +#endif /* RT_USING_SMP */ + + /* initialize cleanup function and user data */ + thread->cleanup = 0; + thread->user_data = 0; + + /* initialize thread timer */ + rt_timer_init(&(thread->thread_timer), + thread->parent.name, + _thread_timeout, + thread, + 0, + RT_TIMER_FLAG_ONE_SHOT); + + /* initialize signal */ +#ifdef RT_USING_SIGNALS + thread->sig_mask = 0x00; + thread->sig_pending = 0x00; + +#ifndef RT_USING_SMP + thread->sig_ret = RT_NULL; +#endif /* RT_USING_SMP */ + thread->sig_vectors = RT_NULL; + thread->si_list = RT_NULL; +#endif /* RT_USING_SIGNALS */ + +#ifdef RT_USING_SMART + thread->tid_ref_count = 0; + thread->lwp = RT_NULL; + thread->susp_recycler = RT_NULL; + rt_list_init(&(thread->sibling)); + + /* lwp thread-signal init */ + rt_memset(&thread->signal.sigset_mask, 0, sizeof(lwp_sigset_t)); + rt_memset(&thread->signal.sig_queue.sigset_pending, 0, sizeof(lwp_sigset_t)); + rt_list_init(&thread->signal.sig_queue.siginfo_list); + + rt_memset(&thread->user_ctx, 0, sizeof thread->user_ctx); + + /* initialize user_time and system_time */ + thread->user_time = 0; + thread->system_time = 0; +#endif + +#ifdef RT_USING_CPU_USAGE + thread->duration_tick = 0; +#endif /* RT_USING_CPU_USAGE */ + +#ifdef RT_USING_PTHREADS + thread->pthread_data = RT_NULL; +#endif /* RT_USING_PTHREADS */ + +#ifdef RT_USING_MODULE + thread->parent.module_id = 0; +#endif /* RT_USING_MODULE */ + rt_atomic_store(&thread->ref_count, 0); + rt_spin_lock_init(&thread->spinlock); + + RT_OBJECT_HOOK_CALL(rt_thread_inited_hook, (thread)); + + return RT_EOK; +} + +rt_err_t rt_thread_init(struct rt_thread *thread, + const char *name, + void (*entry)(void *parameter), + void *parameter, + void *stack_start, + rt_uint32_t stack_size, + rt_uint8_t priority, + rt_uint32_t tick) +{ + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(stack_start != RT_NULL); + + /* initialize thread object */ + rt_object_init((rt_object_t)thread, RT_Object_Class_Thread, name); + + return _thread_init(thread, + name, + entry, + parameter, + stack_start, + stack_size, + priority, + tick); +} +RTM_EXPORT(rt_thread_init); + +rt_thread_t rt_thread_self(void) +{ +#ifdef RT_USING_SMP + rt_base_t lock; + rt_thread_t self; + + lock = rt_hw_local_irq_disable(); + self = rt_cpu_self()->current_thread; + rt_hw_local_irq_enable(lock); + return self; +#else + extern rt_thread_t rt_current_thread; + + return rt_current_thread; +#endif /* RT_USING_SMP */ +} +RTM_EXPORT(rt_thread_self); + +rt_err_t rt_thread_startup(rt_thread_t thread) +{ + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT((thread->stat & RT_THREAD_STAT_MASK) == RT_THREAD_INIT); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + + /* calculate priority attribute */ +#if RT_THREAD_PRIORITY_MAX > 32 + thread->number = thread->current_priority >> 3; /* 5bit */ + thread->number_mask = 1L << thread->number; + thread->high_mask = 1L << (thread->current_priority & 0x07); /* 3bit */ +#else + thread->number_mask = 1L << thread->current_priority; +#endif /* RT_THREAD_PRIORITY_MAX > 32 */ + + LOG_D("startup a thread:%s with priority:%d", + thread->parent.name, thread->current_priority); + /* change thread stat */ + thread->stat = RT_THREAD_SUSPEND; + /* then resume it */ + rt_thread_resume(thread); + if (rt_thread_self() != RT_NULL) + { + /* do a scheduling */ + rt_schedule(); + } + + return RT_EOK; +} +RTM_EXPORT(rt_thread_startup); + +rt_err_t rt_thread_sleep(rt_tick_t tick) +{ + rt_base_t level, level_local; + struct rt_thread *thread; + int err; + + if (tick == 0) + { + return -RT_EINVAL; + } + + /* set to current thread */ + thread = rt_thread_self(); + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE); + /* reset thread error */ + thread->error = RT_EOK; + level_local = rt_hw_local_irq_disable(); + /* suspend thread */ + err = rt_thread_suspend_with_flag(thread, RT_INTERRUPTIBLE); + level = rt_spin_lock_irqsave(&(thread->spinlock)); + /* reset the timeout of thread timer and start it */ + if (err == RT_EOK) + { + rt_timer_control(&(thread->thread_timer), RT_TIMER_CTRL_SET_TIME, &tick); + rt_timer_start(&(thread->thread_timer)); + + /* enable interrupt */ + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + rt_hw_local_irq_enable(level_local); + thread->error = -RT_EINTR; + + rt_schedule(); + + /* clear error number of this thread to RT_EOK */ + if (thread->error == -RT_ETIMEOUT) + thread->error = RT_EOK; + } + else + { + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + rt_hw_local_irq_enable(level_local); + } + + return err; +} + +rt_err_t rt_thread_delay(rt_tick_t tick) +{ + return rt_thread_sleep(tick); +} +RTM_EXPORT(rt_thread_delay); + +static void rt_thread_set_suspend_state(struct rt_thread *thread, int suspend_flag) +{ + rt_uint8_t stat = RT_THREAD_SUSPEND_UNINTERRUPTIBLE; + + RT_ASSERT(thread != RT_NULL); + switch (suspend_flag) + { + case RT_INTERRUPTIBLE: + stat = RT_THREAD_SUSPEND_INTERRUPTIBLE; + break; + case RT_KILLABLE: + stat = RT_THREAD_SUSPEND_KILLABLE; + break; + case RT_UNINTERRUPTIBLE: + stat = RT_THREAD_SUSPEND_UNINTERRUPTIBLE; + break; + default: + RT_ASSERT(0); + break; + } + thread->stat = stat | (thread->stat & ~RT_THREAD_STAT_MASK); +} + +rt_err_t rt_thread_suspend_with_flag(rt_thread_t thread, int suspend_flag) +{ + rt_base_t stat; + rt_base_t level; + + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + RT_ASSERT(thread == rt_thread_self()); + + LOG_D("thread suspend: %s", thread->parent.name); + + level = rt_spin_lock_irqsave(&(thread->spinlock)); + + stat = thread->stat & RT_THREAD_STAT_MASK; + if ((stat != RT_THREAD_READY) && (stat != RT_THREAD_RUNNING)) + { + LOG_D("thread suspend: thread disorder, 0x%2x", thread->stat); + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + return -RT_ERROR; + } + + if (stat == RT_THREAD_RUNNING) + { + /* not suspend running status thread on other core */ + RT_ASSERT(thread == rt_thread_self()); + } +#ifdef RT_USING_SMART + if (lwp_thread_signal_suspend_check(thread, suspend_flag) == 0) + { + /* not to suspend */ + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + return -RT_EINTR; + } +#endif + + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + rt_schedule_remove_thread(thread); + level = rt_spin_lock_irqsave(&(thread->spinlock)); + + rt_thread_set_suspend_state(thread, suspend_flag); + + /* stop thread timer anyway */ + rt_timer_stop(&(thread->thread_timer)); + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + + RT_OBJECT_HOOK_CALL(rt_thread_suspend_hook, (thread)); + return RT_EOK; +} +RTM_EXPORT(rt_thread_suspend_with_flag); + +rt_err_t rt_thread_suspend(rt_thread_t thread) +{ + return rt_thread_suspend_with_flag(thread, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_thread_suspend); + +rt_err_t rt_thread_resume(rt_thread_t thread) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + + LOG_D("thread resume: %s", thread->parent.name); + + level = rt_spin_lock_irqsave(&(thread->spinlock)); //TODO need lock for cpu + + if ((thread->stat & RT_THREAD_SUSPEND_MASK) != RT_THREAD_SUSPEND_MASK) + { + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + + LOG_D("thread resume: thread disorder, %d", + thread->stat); + + return -RT_ERROR; + } + + /* remove from suspend list */ + rt_list_remove(&(thread->tlist)); + + rt_timer_stop(&thread->thread_timer); + +#ifdef RT_USING_SMART + thread->wakeup.func = RT_NULL; +#endif + + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + /* insert to schedule ready list */ + rt_schedule_insert_thread(thread); + + RT_OBJECT_HOOK_CALL(rt_thread_resume_hook, (thread)); + return RT_EOK; +} +RTM_EXPORT(rt_thread_resume); + diff --git a/tasks/runtime-rtthread-softtimer-wakeup/gold/src/timer.c b/tasks/runtime-rtthread-softtimer-wakeup/gold/src/timer.c new file mode 100644 index 00000000..9c2d073a --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/gold/src/timer.c @@ -0,0 +1,611 @@ +/* + * Copyright (c) 2006-2022, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +#include +#include + +#define DBG_TAG "kernel.timer" +#define DBG_LVL DBG_INFO +#include + +/* hard timer list */ +static rt_list_t _timer_list[RT_TIMER_SKIP_LIST_LEVEL]; +static struct rt_spinlock _hard_spinlock; + +#ifdef RT_USING_TIMER_SOFT + +#define RT_SOFT_TIMER_IDLE 1 +#define RT_SOFT_TIMER_BUSY 0 + +#ifndef RT_TIMER_THREAD_STACK_SIZE +#define RT_TIMER_THREAD_STACK_SIZE 512 +#endif /* RT_TIMER_THREAD_STACK_SIZE */ + +#ifndef RT_TIMER_THREAD_PRIO +#define RT_TIMER_THREAD_PRIO 0 +#endif /* RT_TIMER_THREAD_PRIO */ + +/* soft timer status */ +static rt_uint8_t _soft_timer_status = RT_SOFT_TIMER_IDLE; +/* soft timer list */ +static rt_list_t _soft_timer_list[RT_TIMER_SKIP_LIST_LEVEL]; +static struct rt_spinlock _soft_spinlock; +static struct rt_thread _timer_thread; +static struct rt_semaphore _soft_timer_sem; +rt_align(RT_ALIGN_SIZE) +static rt_uint8_t _timer_thread_stack[RT_TIMER_THREAD_STACK_SIZE]; +#endif /* RT_USING_TIMER_SOFT */ + +#ifndef __on_rt_object_take_hook + #define __on_rt_object_take_hook(parent) __ON_HOOK_ARGS(rt_object_take_hook, (parent)) +#endif +#ifndef __on_rt_object_put_hook + #define __on_rt_object_put_hook(parent) __ON_HOOK_ARGS(rt_object_put_hook, (parent)) +#endif +#ifndef __on_rt_timer_enter_hook + #define __on_rt_timer_enter_hook(t) __ON_HOOK_ARGS(rt_timer_enter_hook, (t)) +#endif +#ifndef __on_rt_timer_exit_hook + #define __on_rt_timer_exit_hook(t) __ON_HOOK_ARGS(rt_timer_exit_hook, (t)) +#endif + + +static void _timer_init(rt_timer_t timer, + void (*timeout)(void *parameter), + void *parameter, + rt_tick_t time, + rt_uint8_t flag) +{ + int i; + + /* set flag */ + timer->parent.flag = flag; + + /* set deactivated */ + timer->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + + timer->timeout_func = timeout; + timer->parameter = parameter; + + timer->timeout_tick = 0; + timer->init_tick = time; + + /* initialize timer list */ + for (i = 0; i < RT_TIMER_SKIP_LIST_LEVEL; i++) + { + rt_list_init(&(timer->row[i])); + } +} + +static rt_err_t _timer_list_next_timeout(rt_list_t timer_list[], rt_tick_t *timeout_tick) +{ + struct rt_timer *timer; + + if (!rt_list_isempty(&timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1])) + { + timer = rt_list_entry(timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1].next, + struct rt_timer, row[RT_TIMER_SKIP_LIST_LEVEL - 1]); + *timeout_tick = timer->timeout_tick; + return RT_EOK; + } + return -RT_ERROR; +} + +rt_inline void _timer_remove(rt_timer_t timer) +{ + int i; + + for (i = 0; i < RT_TIMER_SKIP_LIST_LEVEL; i++) + { + rt_list_remove(&timer->row[i]); + } +} + +void rt_timer_init(rt_timer_t timer, + const char *name, + void (*timeout)(void *parameter), + void *parameter, + rt_tick_t time, + rt_uint8_t flag) +{ + /* parameter check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(timeout != RT_NULL); + RT_ASSERT(time < RT_TICK_MAX / 2); + + /* timer object initialization */ + rt_object_init(&(timer->parent), RT_Object_Class_Timer, name); + + _timer_init(timer, timeout, parameter, time, flag); +} +RTM_EXPORT(rt_timer_init); + +rt_err_t rt_timer_detach(rt_timer_t timer) +{ + rt_base_t level; + struct rt_spinlock *spinlock; + + /* parameter check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(rt_object_get_type(&timer->parent) == RT_Object_Class_Timer); + RT_ASSERT(rt_object_is_systemobject(&timer->parent)); + +#ifdef RT_USING_TIMER_SOFT + if (timer->parent.flag & RT_TIMER_FLAG_SOFT_TIMER) + { + spinlock = &_soft_spinlock; + } + else +#endif /* RT_USING_TIMER_SOFT */ + { + spinlock = &_hard_spinlock; + } + + level = rt_spin_lock_irqsave(spinlock); + + _timer_remove(timer); + /* stop timer */ + timer->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + + rt_spin_unlock_irqrestore(spinlock, level); + rt_object_detach(&(timer->parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_timer_detach); + +static rt_err_t _timer_start(rt_list_t *timer_list, rt_timer_t timer) +{ + unsigned int row_lvl; + rt_list_t *row_head[RT_TIMER_SKIP_LIST_LEVEL]; + unsigned int tst_nr; + static unsigned int random_nr; + + /* remove timer from list */ + _timer_remove(timer); + /* change status of timer */ + timer->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(timer->parent))); + + timer->timeout_tick = rt_tick_get() + timer->init_tick; + + row_head[0] = &timer_list[0]; + for (row_lvl = 0; row_lvl < RT_TIMER_SKIP_LIST_LEVEL; row_lvl++) + { + for (; row_head[row_lvl] != timer_list[row_lvl].prev; + row_head[row_lvl] = row_head[row_lvl]->next) + { + struct rt_timer *t; + rt_list_t *p = row_head[row_lvl]->next; + + /* fix up the entry pointer */ + t = rt_list_entry(p, struct rt_timer, row[row_lvl]); + + /* If we have two timers that timeout at the same time, it's + * preferred that the timer inserted early get called early. + * So insert the new timer to the end the the some-timeout timer + * list. + */ + if ((t->timeout_tick - timer->timeout_tick) == 0) + { + continue; + } + else if ((t->timeout_tick - timer->timeout_tick) < RT_TICK_MAX / 2) + { + break; + } + } + if (row_lvl != RT_TIMER_SKIP_LIST_LEVEL - 1) + row_head[row_lvl + 1] = row_head[row_lvl] + 1; + } + + /* Interestingly, this super simple timer insert counter works very very + * well on distributing the list height uniformly. By means of "very very + * well", I mean it beats the randomness of timer->timeout_tick very easily + * (actually, the timeout_tick is not random and easy to be attacked). */ + random_nr++; + tst_nr = random_nr; + + rt_list_insert_after(row_head[RT_TIMER_SKIP_LIST_LEVEL - 1], + &(timer->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + for (row_lvl = 2; row_lvl <= RT_TIMER_SKIP_LIST_LEVEL; row_lvl++) + { + if (!(tst_nr & RT_TIMER_SKIP_LIST_MASK)) + rt_list_insert_after(row_head[RT_TIMER_SKIP_LIST_LEVEL - row_lvl], + &(timer->row[RT_TIMER_SKIP_LIST_LEVEL - row_lvl])); + else + break; + /* Shift over the bits we have tested. Works well with 1 bit and 2 + * bits. */ + tst_nr >>= (RT_TIMER_SKIP_LIST_MASK + 1) >> 1; + } + + timer->parent.flag |= RT_TIMER_FLAG_ACTIVATED; + + return RT_EOK; +} + +rt_err_t rt_timer_start(rt_timer_t timer) +{ + struct rt_spinlock *spinlock; + rt_list_t *timer_list; + rt_base_t level; + rt_err_t err; + + /* parameter check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(rt_object_get_type(&timer->parent) == RT_Object_Class_Timer); + +#ifdef RT_USING_TIMER_SOFT + if (timer->parent.flag & RT_TIMER_FLAG_SOFT_TIMER) + { + timer_list = _soft_timer_list; + spinlock = &_soft_spinlock; + } + else +#endif /* RT_USING_TIMER_SOFT */ + { + timer_list = _timer_list; + spinlock = &_hard_spinlock; + } + + level = rt_spin_lock_irqsave(spinlock); + + err = _timer_start(timer_list, timer); + +#ifdef RT_USING_TIMER_SOFT + if (err == RT_EOK) + { + if (timer->parent.flag & RT_TIMER_FLAG_SOFT_TIMER) + { + rt_sem_release(&_soft_timer_sem); + } + } +#endif /* RT_USING_TIMER_SOFT */ + + rt_spin_unlock_irqrestore(spinlock, level); + + return err; +} +RTM_EXPORT(rt_timer_start); + +rt_err_t rt_timer_stop(rt_timer_t timer) +{ + rt_base_t level; + struct rt_spinlock *spinlock; + + /* timer check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(rt_object_get_type(&timer->parent) == RT_Object_Class_Timer); + +#ifdef RT_USING_TIMER_SOFT + if (timer->parent.flag & RT_TIMER_FLAG_SOFT_TIMER) + { + spinlock = &_soft_spinlock; + } + else +#endif /* RT_USING_TIMER_SOFT */ + { + spinlock = &_hard_spinlock; + } + level = rt_spin_lock_irqsave(spinlock); + + if (!(timer->parent.flag & RT_TIMER_FLAG_ACTIVATED)) + { + rt_spin_unlock_irqrestore(spinlock, level); + return -RT_ERROR; + } + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(timer->parent))); + + _timer_remove(timer); + /* change status */ + timer->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + rt_spin_unlock_irqrestore(spinlock, level); + + return RT_EOK; +} +RTM_EXPORT(rt_timer_stop); + +rt_err_t rt_timer_control(rt_timer_t timer, int cmd, void *arg) +{ + /* parameter check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(rt_object_get_type(&timer->parent) == RT_Object_Class_Timer); + + switch (cmd) + { + case RT_TIMER_CTRL_GET_TIME: + *(rt_tick_t *)arg = timer->init_tick; + break; + + case RT_TIMER_CTRL_SET_TIME: + RT_ASSERT((*(rt_tick_t *)arg) < RT_TICK_MAX / 2); + timer->init_tick = *(rt_tick_t *)arg; + break; + + case RT_TIMER_CTRL_SET_ONESHOT: + timer->parent.flag &= ~RT_TIMER_FLAG_PERIODIC; + break; + + case RT_TIMER_CTRL_SET_PERIODIC: + timer->parent.flag |= RT_TIMER_FLAG_PERIODIC; + break; + + case RT_TIMER_CTRL_GET_STATE: + if(timer->parent.flag & RT_TIMER_FLAG_ACTIVATED) + { + /*timer is start and run*/ + *(rt_uint32_t *)arg = RT_TIMER_FLAG_ACTIVATED; + } + else + { + /*timer is stop*/ + *(rt_uint32_t *)arg = RT_TIMER_FLAG_DEACTIVATED; + } + break; + + case RT_TIMER_CTRL_GET_REMAIN_TIME: + *(rt_tick_t *)arg = timer->timeout_tick; + break; + case RT_TIMER_CTRL_GET_FUNC: + *(void **)arg = (void *)timer->timeout_func; + break; + + case RT_TIMER_CTRL_SET_FUNC: + timer->timeout_func = (void (*)(void*))arg; + break; + + case RT_TIMER_CTRL_GET_PARM: + *(void **)arg = timer->parameter; + break; + + case RT_TIMER_CTRL_SET_PARM: + timer->parameter = arg; + break; + + default: + break; + } + + return RT_EOK; +} +RTM_EXPORT(rt_timer_control); + +void rt_timer_check(void) +{ + struct rt_timer *t; + rt_tick_t current_tick; + rt_base_t level; + rt_list_t list; + +#ifdef RT_USING_SMP + if (rt_hw_cpu_id() != 0) + { + return; + } +#endif + + rt_list_init(&list); + + LOG_D("timer check enter"); + + current_tick = rt_tick_get(); + + level = rt_spin_lock_irqsave(&_hard_spinlock); + + while (!rt_list_isempty(&_timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1])) + { + t = rt_list_entry(_timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1].next, + struct rt_timer, row[RT_TIMER_SKIP_LIST_LEVEL - 1]); + + /* + * It supposes that the new tick shall less than the half duration of + * tick max. + */ + if ((current_tick - t->timeout_tick) < RT_TICK_MAX / 2) + { + RT_OBJECT_HOOK_CALL(rt_timer_enter_hook, (t)); + + /* remove timer from timer list firstly */ + _timer_remove(t); + if (!(t->parent.flag & RT_TIMER_FLAG_PERIODIC)) + { + t->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + } + /* add timer to temporary list */ + rt_list_insert_after(&list, &(t->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + rt_spin_unlock_irqrestore(&_hard_spinlock, level); + /* call timeout function */ + t->timeout_func(t->parameter); + + /* re-get tick */ + current_tick = rt_tick_get(); + + RT_OBJECT_HOOK_CALL(rt_timer_exit_hook, (t)); + LOG_D("current tick: %d", current_tick); + level = rt_spin_lock_irqsave(&_hard_spinlock); + /* Check whether the timer object is detached or started again */ + if (rt_list_isempty(&list)) + { + continue; + } + rt_list_remove(&(t->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + if ((t->parent.flag & RT_TIMER_FLAG_PERIODIC) && + (t->parent.flag & RT_TIMER_FLAG_ACTIVATED)) + { + /* start it */ + t->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + _timer_start(_timer_list, t); + } + } + else break; + } + rt_spin_unlock_irqrestore(&_hard_spinlock, level); + LOG_D("timer check leave"); +} + +rt_tick_t rt_timer_next_timeout_tick(void) +{ + rt_base_t level; + rt_tick_t next_timeout = RT_TICK_MAX; + + level = rt_spin_lock_irqsave(&_hard_spinlock); + _timer_list_next_timeout(_timer_list, &next_timeout); + rt_spin_unlock_irqrestore(&_hard_spinlock, level); + + return next_timeout; +} + +void rt_soft_timer_check(void) +{ + rt_tick_t current_tick; + struct rt_timer *t; + rt_base_t level; + rt_list_t list; + + rt_list_init(&list); + LOG_D("software timer check enter"); + level = rt_spin_lock_irqsave(&_soft_spinlock); + + while (!rt_list_isempty(&_soft_timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1])) + { + t = rt_list_entry(_soft_timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1].next, + struct rt_timer, row[RT_TIMER_SKIP_LIST_LEVEL - 1]); + + current_tick = rt_tick_get(); + + /* + * It supposes that the new tick shall less than the half duration of + * tick max. + */ + if ((current_tick - t->timeout_tick) < RT_TICK_MAX / 2) + { + RT_OBJECT_HOOK_CALL(rt_timer_enter_hook, (t)); + + /* remove timer from timer list firstly */ + _timer_remove(t); + if (!(t->parent.flag & RT_TIMER_FLAG_PERIODIC)) + { + t->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + } + /* add timer to temporary list */ + rt_list_insert_after(&list, &(t->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + + _soft_timer_status = RT_SOFT_TIMER_BUSY; + + rt_spin_unlock_irqrestore(&_soft_spinlock, level); + + /* call timeout function */ + t->timeout_func(t->parameter); + + RT_OBJECT_HOOK_CALL(rt_timer_exit_hook, (t)); + LOG_D("current tick: %d", current_tick); + + level = rt_spin_lock_irqsave(&_soft_spinlock); + + _soft_timer_status = RT_SOFT_TIMER_IDLE; + /* Check whether the timer object is detached or started again */ + if (rt_list_isempty(&list)) + { + continue; + } + rt_list_remove(&(t->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + if ((t->parent.flag & RT_TIMER_FLAG_PERIODIC) && + (t->parent.flag & RT_TIMER_FLAG_ACTIVATED)) + { + /* start it */ + t->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + _timer_start(_soft_timer_list, t); + } + } + else break; /* not check anymore */ + } + + rt_spin_unlock_irqrestore(&_soft_spinlock, level); + + LOG_D("software timer check leave"); +} + +static void _timer_thread_entry(void *parameter) +{ + rt_err_t ret = RT_ERROR; + rt_tick_t next_timeout; + rt_base_t level; + + rt_sem_control(&_soft_timer_sem, RT_IPC_CMD_SET_VLIMIT, (void*)1); + + while (1) + { + /* get the next timeout tick */ + level = rt_spin_lock_irqsave(&_soft_spinlock); + ret = _timer_list_next_timeout(_soft_timer_list, &next_timeout); + rt_spin_unlock_irqrestore(&_soft_spinlock, level); + + if (ret != RT_EOK) + { + rt_sem_take(&_soft_timer_sem, RT_WAITING_FOREVER); + } + else + { + rt_tick_t current_tick; + + /* get current tick */ + current_tick = rt_tick_get(); + + if ((next_timeout - current_tick) < RT_TICK_MAX / 2) + { + /* get the delta timeout tick */ + next_timeout = next_timeout - current_tick; + rt_sem_take(&_soft_timer_sem, next_timeout); + } + } + + /* check software timer */ + rt_soft_timer_check(); + } +} + +void rt_system_timer_init(void) +{ + rt_size_t i; + + for (i = 0; i < sizeof(_timer_list) / sizeof(_timer_list[0]); i++) + { + rt_list_init(_timer_list + i); + } + rt_spin_lock_init(&_hard_spinlock); +} + +void rt_system_timer_thread_init(void) +{ +#ifdef RT_USING_TIMER_SOFT + int i; + + for (i = 0; + i < sizeof(_soft_timer_list) / sizeof(_soft_timer_list[0]); + i++) + { + rt_list_init(_soft_timer_list + i); + } + rt_spin_lock_init(&_soft_spinlock); + rt_sem_init(&_soft_timer_sem, "stimer", 0, RT_IPC_FLAG_PRIO); + /* start software timer thread */ + rt_thread_init(&_timer_thread, + "timer", + _timer_thread_entry, + RT_NULL, + &_timer_thread_stack[0], + sizeof(_timer_thread_stack), + RT_TIMER_THREAD_PRIO, + 10); + + /* startup */ + rt_thread_startup(&_timer_thread); +#endif /* RT_USING_TIMER_SOFT */ +} + diff --git a/tasks/runtime-rtthread-softtimer-wakeup/noop/src/thread.c b/tasks/runtime-rtthread-softtimer-wakeup/noop/src/thread.c new file mode 100644 index 00000000..3151c913 --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/noop/src/thread.c @@ -0,0 +1,466 @@ +/* + * Copyright (c) 2006-2022, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +#include +#include +#include + +#define DBG_TAG "kernel.thread" +#define DBG_LVL DBG_INFO +#include + +#ifndef __on_rt_thread_inited_hook + #define __on_rt_thread_inited_hook(thread) __ON_HOOK_ARGS(rt_thread_inited_hook, (thread)) +#endif +#ifndef __on_rt_thread_suspend_hook + #define __on_rt_thread_suspend_hook(thread) __ON_HOOK_ARGS(rt_thread_suspend_hook, (thread)) +#endif +#ifndef __on_rt_thread_resume_hook + #define __on_rt_thread_resume_hook(thread) __ON_HOOK_ARGS(rt_thread_resume_hook, (thread)) +#endif + + +static void _thread_exit(void) +{ + struct rt_thread *thread; + rt_base_t level; + + /* get current thread */ + LOG_D("line:%d thread:%s exit\n",__LINE__,rt_thread_self()->parent.name); + thread = rt_thread_self(); + rt_get_thread_struct(thread); + rt_thread_defunct_enqueue(thread); + level = rt_spin_lock_irqsave(&(thread->spinlock)); + rt_timer_detach(&thread->thread_timer); + /* insert to defunct thread list */ + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + LOG_D("line:%d thread:%s exit\n",__LINE__,rt_thread_self()->parent.name); + rt_put_thread_struct(thread); + thread->stat = RT_THREAD_CLOSE; + /* switch to next task */ + rt_schedule(); +} + +static void _thread_timeout(void *parameter) +{ + struct rt_thread *thread; + rt_base_t level; + + thread = (struct rt_thread *)parameter; + + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT((thread->stat & RT_THREAD_SUSPEND_MASK) == RT_THREAD_SUSPEND_MASK); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + level = rt_spin_lock_irqsave(&(thread->spinlock)); + /* set error number */ + thread->error = -RT_ETIMEOUT; + + /* remove from suspend list */ + rt_list_remove(&(thread->tlist)); + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + /* insert to schedule ready list */ + rt_schedule_insert_thread(thread); + /* do schedule */ + rt_schedule(); +} + +static rt_err_t _thread_init(struct rt_thread *thread, + const char *name, + void (*entry)(void *parameter), + void *parameter, + void *stack_start, + rt_uint32_t stack_size, + rt_uint8_t priority, + rt_uint32_t tick) +{ + /* init thread list */ + rt_list_init(&(thread->tlist)); + rt_list_init(&(thread->tlist_schedule)); + +#ifdef RT_USING_MEM_PROTECTION + thread->mem_regions = RT_NULL; +#endif + +#ifdef RT_USING_SMART + thread->wakeup.func = RT_NULL; +#endif + + thread->entry = (void *)entry; + thread->parameter = parameter; + + /* stack init */ + thread->stack_addr = stack_start; + thread->stack_size = stack_size; + + /* init thread stack */ + rt_memset(thread->stack_addr, '#', thread->stack_size); +#ifdef RT_USING_HW_STACK_GUARD + rt_hw_stack_guard_init(thread); +#endif +#ifdef ARCH_CPU_STACK_GROWS_UPWARD + thread->sp = (void *)rt_hw_stack_init(thread->entry, thread->parameter, + (void *)((char *)thread->stack_addr), + (void *)_thread_exit); +#else + thread->sp = (void *)rt_hw_stack_init(thread->entry, thread->parameter, + (rt_uint8_t *)((char *)thread->stack_addr + thread->stack_size - sizeof(rt_ubase_t)), + (void *)_thread_exit); +#endif /* ARCH_CPU_STACK_GROWS_UPWARD */ + + /* priority init */ + RT_ASSERT(priority < RT_THREAD_PRIORITY_MAX); + thread->init_priority = priority; + thread->current_priority = priority; + + thread->number_mask = 0; + +#ifdef RT_USING_MUTEX + rt_list_init(&thread->taken_object_list); + thread->pending_object = RT_NULL; +#endif + +#ifdef RT_USING_EVENT + thread->event_set = 0; + thread->event_info = 0; +#endif /* RT_USING_EVENT */ + +#if RT_THREAD_PRIORITY_MAX > 32 + thread->number = 0; + thread->high_mask = 0; +#endif /* RT_THREAD_PRIORITY_MAX > 32 */ + + /* tick init */ + rt_atomic_store(&thread->init_tick, tick); + rt_atomic_store(&thread->remaining_tick, tick); + + /* error and flags */ + thread->error = RT_EOK; + thread->stat = RT_THREAD_INIT; + +#ifdef RT_USING_SMP + /* not bind on any cpu */ + thread->bind_cpu = RT_CPUS_NR; + thread->oncpu = RT_CPU_DETACHED; + + /* lock init */ + rt_atomic_store(&thread->cpus_lock_nest, 0); + rt_atomic_store(&thread->critical_lock_nest, 0); +#endif /* RT_USING_SMP */ + + /* initialize cleanup function and user data */ + thread->cleanup = 0; + thread->user_data = 0; + + /* initialize thread timer */ + rt_timer_init(&(thread->thread_timer), + thread->parent.name, + _thread_timeout, + thread, + 0, + RT_TIMER_FLAG_ONE_SHOT); + + /* initialize signal */ +#ifdef RT_USING_SIGNALS + thread->sig_mask = 0x00; + thread->sig_pending = 0x00; + +#ifndef RT_USING_SMP + thread->sig_ret = RT_NULL; +#endif /* RT_USING_SMP */ + thread->sig_vectors = RT_NULL; + thread->si_list = RT_NULL; +#endif /* RT_USING_SIGNALS */ + +#ifdef RT_USING_SMART + thread->tid_ref_count = 0; + thread->lwp = RT_NULL; + thread->susp_recycler = RT_NULL; + rt_list_init(&(thread->sibling)); + + /* lwp thread-signal init */ + rt_memset(&thread->signal.sigset_mask, 0, sizeof(lwp_sigset_t)); + rt_memset(&thread->signal.sig_queue.sigset_pending, 0, sizeof(lwp_sigset_t)); + rt_list_init(&thread->signal.sig_queue.siginfo_list); + + rt_memset(&thread->user_ctx, 0, sizeof thread->user_ctx); + + /* initialize user_time and system_time */ + thread->user_time = 0; + thread->system_time = 0; +#endif + +#ifdef RT_USING_CPU_USAGE + thread->duration_tick = 0; +#endif /* RT_USING_CPU_USAGE */ + +#ifdef RT_USING_PTHREADS + thread->pthread_data = RT_NULL; +#endif /* RT_USING_PTHREADS */ + +#ifdef RT_USING_MODULE + thread->parent.module_id = 0; +#endif /* RT_USING_MODULE */ + rt_atomic_store(&thread->ref_count, 0); + rt_spin_lock_init(&thread->spinlock); + + RT_OBJECT_HOOK_CALL(rt_thread_inited_hook, (thread)); + + return RT_EOK; +} + +rt_err_t rt_thread_init(struct rt_thread *thread, + const char *name, + void (*entry)(void *parameter), + void *parameter, + void *stack_start, + rt_uint32_t stack_size, + rt_uint8_t priority, + rt_uint32_t tick) +{ + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(stack_start != RT_NULL); + + /* initialize thread object */ + rt_object_init((rt_object_t)thread, RT_Object_Class_Thread, name); + + return _thread_init(thread, + name, + entry, + parameter, + stack_start, + stack_size, + priority, + tick); +} +RTM_EXPORT(rt_thread_init); + +rt_thread_t rt_thread_self(void) +{ +#ifdef RT_USING_SMP + rt_base_t lock; + rt_thread_t self; + + lock = rt_hw_local_irq_disable(); + self = rt_cpu_self()->current_thread; + rt_hw_local_irq_enable(lock); + return self; +#else + extern rt_thread_t rt_current_thread; + + return rt_current_thread; +#endif /* RT_USING_SMP */ +} +RTM_EXPORT(rt_thread_self); + +rt_err_t rt_thread_startup(rt_thread_t thread) +{ + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT((thread->stat & RT_THREAD_STAT_MASK) == RT_THREAD_INIT); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + + /* calculate priority attribute */ +#if RT_THREAD_PRIORITY_MAX > 32 + thread->number = thread->current_priority >> 3; /* 5bit */ + thread->number_mask = 1L << thread->number; + thread->high_mask = 1L << (thread->current_priority & 0x07); /* 3bit */ +#else + thread->number_mask = 1L << thread->current_priority; +#endif /* RT_THREAD_PRIORITY_MAX > 32 */ + + LOG_D("startup a thread:%s with priority:%d", + thread->parent.name, thread->current_priority); + /* change thread stat */ + thread->stat = RT_THREAD_SUSPEND; + /* then resume it */ + rt_thread_resume(thread); + if (rt_thread_self() != RT_NULL) + { + /* do a scheduling */ + rt_schedule(); + } + + return RT_EOK; +} +RTM_EXPORT(rt_thread_startup); + +rt_err_t rt_thread_sleep(rt_tick_t tick) +{ + rt_base_t level, level_local; + struct rt_thread *thread; + int err; + + if (tick == 0) + { + return -RT_EINVAL; + } + + /* set to current thread */ + thread = rt_thread_self(); + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE); + /* reset thread error */ + thread->error = RT_EOK; + level_local = rt_hw_local_irq_disable(); + /* suspend thread */ + err = rt_thread_suspend_with_flag(thread, RT_INTERRUPTIBLE); + level = rt_spin_lock_irqsave(&(thread->spinlock)); + /* reset the timeout of thread timer and start it */ + if (err == RT_EOK) + { + rt_timer_control(&(thread->thread_timer), RT_TIMER_CTRL_SET_TIME, &tick); + rt_timer_start(&(thread->thread_timer)); + + /* enable interrupt */ + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + rt_hw_local_irq_enable(level_local); + thread->error = -RT_EINTR; + + rt_schedule(); + + /* clear error number of this thread to RT_EOK */ + if (thread->error == -RT_ETIMEOUT) + thread->error = RT_EOK; + } + else + { + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + rt_hw_local_irq_enable(level_local); + } + + return err; +} + +rt_err_t rt_thread_delay(rt_tick_t tick) +{ + return rt_thread_sleep(tick); +} +RTM_EXPORT(rt_thread_delay); + +static void rt_thread_set_suspend_state(struct rt_thread *thread, int suspend_flag) +{ + rt_uint8_t stat = RT_THREAD_SUSPEND_UNINTERRUPTIBLE; + + RT_ASSERT(thread != RT_NULL); + switch (suspend_flag) + { + case RT_INTERRUPTIBLE: + stat = RT_THREAD_SUSPEND_INTERRUPTIBLE; + break; + case RT_KILLABLE: + stat = RT_THREAD_SUSPEND_KILLABLE; + break; + case RT_UNINTERRUPTIBLE: + stat = RT_THREAD_SUSPEND_UNINTERRUPTIBLE; + break; + default: + RT_ASSERT(0); + break; + } + thread->stat = stat | (thread->stat & ~RT_THREAD_STAT_MASK); +} + +rt_err_t rt_thread_suspend_with_flag(rt_thread_t thread, int suspend_flag) +{ + rt_base_t stat; + rt_base_t level; + + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + RT_ASSERT(thread == rt_thread_self()); + + LOG_D("thread suspend: %s", thread->parent.name); + + level = rt_spin_lock_irqsave(&(thread->spinlock)); + + stat = thread->stat & RT_THREAD_STAT_MASK; + if ((stat != RT_THREAD_READY) && (stat != RT_THREAD_RUNNING)) + { + LOG_D("thread suspend: thread disorder, 0x%2x", thread->stat); + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + return -RT_ERROR; + } + + if (stat == RT_THREAD_RUNNING) + { + /* not suspend running status thread on other core */ + RT_ASSERT(thread == rt_thread_self()); + } +#ifdef RT_USING_SMART + if (lwp_thread_signal_suspend_check(thread, suspend_flag) == 0) + { + /* not to suspend */ + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + return -RT_EINTR; + } +#endif + + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + rt_schedule_remove_thread(thread); + level = rt_spin_lock_irqsave(&(thread->spinlock)); + + rt_thread_set_suspend_state(thread, suspend_flag); + + /* stop thread timer anyway */ + rt_timer_stop(&(thread->thread_timer)); + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + + RT_OBJECT_HOOK_CALL(rt_thread_suspend_hook, (thread)); + return RT_EOK; +} +RTM_EXPORT(rt_thread_suspend_with_flag); + +rt_err_t rt_thread_suspend(rt_thread_t thread) +{ + return rt_thread_suspend_with_flag(thread, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_thread_suspend); + +rt_err_t rt_thread_resume(rt_thread_t thread) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + + LOG_D("thread resume: %s", thread->parent.name); + + if ((thread->stat & RT_THREAD_SUSPEND_MASK) != RT_THREAD_SUSPEND_MASK) + { + LOG_D("thread resume: thread disorder, %d", + thread->stat); + + return -RT_ERROR; + } + + level = rt_spin_lock_irqsave(&(thread->spinlock)); //TODO need lock for cpu + + /* remove from suspend list */ + rt_list_remove(&(thread->tlist)); + + rt_timer_stop(&thread->thread_timer); + +#ifdef RT_USING_SMART + thread->wakeup.func = RT_NULL; +#endif + + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + /* insert to schedule ready list */ + rt_schedule_insert_thread(thread); + + RT_OBJECT_HOOK_CALL(rt_thread_resume_hook, (thread)); + return RT_EOK; +} +RTM_EXPORT(rt_thread_resume); + diff --git a/tasks/runtime-rtthread-softtimer-wakeup/noop/src/timer.c b/tasks/runtime-rtthread-softtimer-wakeup/noop/src/timer.c new file mode 100644 index 00000000..f19f347c --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/noop/src/timer.c @@ -0,0 +1,586 @@ +/* + * Copyright (c) 2006-2022, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +#include +#include + +#define DBG_TAG "kernel.timer" +#define DBG_LVL DBG_INFO +#include + +/* hard timer list */ +static rt_list_t _timer_list[RT_TIMER_SKIP_LIST_LEVEL]; +static struct rt_spinlock _hard_spinlock; + +#ifdef RT_USING_TIMER_SOFT + +#define RT_SOFT_TIMER_IDLE 1 +#define RT_SOFT_TIMER_BUSY 0 + +#ifndef RT_TIMER_THREAD_STACK_SIZE +#define RT_TIMER_THREAD_STACK_SIZE 512 +#endif /* RT_TIMER_THREAD_STACK_SIZE */ + +#ifndef RT_TIMER_THREAD_PRIO +#define RT_TIMER_THREAD_PRIO 0 +#endif /* RT_TIMER_THREAD_PRIO */ + +/* soft timer status */ +static rt_uint8_t _soft_timer_status = RT_SOFT_TIMER_IDLE; +/* soft timer list */ +static rt_list_t _soft_timer_list[RT_TIMER_SKIP_LIST_LEVEL]; +static struct rt_spinlock _soft_spinlock; +static struct rt_thread _timer_thread; +rt_align(RT_ALIGN_SIZE) +static rt_uint8_t _timer_thread_stack[RT_TIMER_THREAD_STACK_SIZE]; +#endif /* RT_USING_TIMER_SOFT */ + +#ifndef __on_rt_object_take_hook + #define __on_rt_object_take_hook(parent) __ON_HOOK_ARGS(rt_object_take_hook, (parent)) +#endif +#ifndef __on_rt_object_put_hook + #define __on_rt_object_put_hook(parent) __ON_HOOK_ARGS(rt_object_put_hook, (parent)) +#endif +#ifndef __on_rt_timer_enter_hook + #define __on_rt_timer_enter_hook(t) __ON_HOOK_ARGS(rt_timer_enter_hook, (t)) +#endif +#ifndef __on_rt_timer_exit_hook + #define __on_rt_timer_exit_hook(t) __ON_HOOK_ARGS(rt_timer_exit_hook, (t)) +#endif + + +static void _timer_init(rt_timer_t timer, + void (*timeout)(void *parameter), + void *parameter, + rt_tick_t time, + rt_uint8_t flag) +{ + int i; + + /* set flag */ + timer->parent.flag = flag; + + /* set deactivated */ + timer->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + + timer->timeout_func = timeout; + timer->parameter = parameter; + + timer->timeout_tick = 0; + timer->init_tick = time; + + /* initialize timer list */ + for (i = 0; i < RT_TIMER_SKIP_LIST_LEVEL; i++) + { + rt_list_init(&(timer->row[i])); + } +} + +static rt_err_t _timer_list_next_timeout(rt_list_t timer_list[], rt_tick_t *timeout_tick) +{ + struct rt_timer *timer; + + if (!rt_list_isempty(&timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1])) + { + timer = rt_list_entry(timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1].next, + struct rt_timer, row[RT_TIMER_SKIP_LIST_LEVEL - 1]); + *timeout_tick = timer->timeout_tick; + return RT_EOK; + } + return -RT_ERROR; +} + +rt_inline void _timer_remove(rt_timer_t timer) +{ + int i; + + for (i = 0; i < RT_TIMER_SKIP_LIST_LEVEL; i++) + { + rt_list_remove(&timer->row[i]); + } +} + +void rt_timer_init(rt_timer_t timer, + const char *name, + void (*timeout)(void *parameter), + void *parameter, + rt_tick_t time, + rt_uint8_t flag) +{ + /* parameter check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(timeout != RT_NULL); + RT_ASSERT(time < RT_TICK_MAX / 2); + + /* timer object initialization */ + rt_object_init(&(timer->parent), RT_Object_Class_Timer, name); + + _timer_init(timer, timeout, parameter, time, flag); +} +RTM_EXPORT(rt_timer_init); + +rt_err_t rt_timer_detach(rt_timer_t timer) +{ + rt_base_t level; + struct rt_spinlock *spinlock; + + /* parameter check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(rt_object_get_type(&timer->parent) == RT_Object_Class_Timer); + RT_ASSERT(rt_object_is_systemobject(&timer->parent)); + +#ifdef RT_USING_TIMER_SOFT + if (timer->parent.flag & RT_TIMER_FLAG_SOFT_TIMER) + { + spinlock = &_soft_spinlock; + } + else +#endif /* RT_USING_TIMER_SOFT */ + { + spinlock = &_hard_spinlock; + } + + level = rt_spin_lock_irqsave(spinlock); + + _timer_remove(timer); + /* stop timer */ + timer->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + + rt_spin_unlock_irqrestore(spinlock, level); + rt_object_detach(&(timer->parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_timer_detach); + +static rt_err_t _timer_start(rt_list_t *timer_list, rt_timer_t timer) +{ + unsigned int row_lvl; + rt_list_t *row_head[RT_TIMER_SKIP_LIST_LEVEL]; + unsigned int tst_nr; + static unsigned int random_nr; + + /* remove timer from list */ + _timer_remove(timer); + /* change status of timer */ + timer->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(timer->parent))); + + timer->timeout_tick = rt_tick_get() + timer->init_tick; + + row_head[0] = &timer_list[0]; + for (row_lvl = 0; row_lvl < RT_TIMER_SKIP_LIST_LEVEL; row_lvl++) + { + for (; row_head[row_lvl] != timer_list[row_lvl].prev; + row_head[row_lvl] = row_head[row_lvl]->next) + { + struct rt_timer *t; + rt_list_t *p = row_head[row_lvl]->next; + + /* fix up the entry pointer */ + t = rt_list_entry(p, struct rt_timer, row[row_lvl]); + + /* If we have two timers that timeout at the same time, it's + * preferred that the timer inserted early get called early. + * So insert the new timer to the end the the some-timeout timer + * list. + */ + if ((t->timeout_tick - timer->timeout_tick) == 0) + { + continue; + } + else if ((t->timeout_tick - timer->timeout_tick) < RT_TICK_MAX / 2) + { + break; + } + } + if (row_lvl != RT_TIMER_SKIP_LIST_LEVEL - 1) + row_head[row_lvl + 1] = row_head[row_lvl] + 1; + } + + /* Interestingly, this super simple timer insert counter works very very + * well on distributing the list height uniformly. By means of "very very + * well", I mean it beats the randomness of timer->timeout_tick very easily + * (actually, the timeout_tick is not random and easy to be attacked). */ + random_nr++; + tst_nr = random_nr; + + rt_list_insert_after(row_head[RT_TIMER_SKIP_LIST_LEVEL - 1], + &(timer->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + for (row_lvl = 2; row_lvl <= RT_TIMER_SKIP_LIST_LEVEL; row_lvl++) + { + if (!(tst_nr & RT_TIMER_SKIP_LIST_MASK)) + rt_list_insert_after(row_head[RT_TIMER_SKIP_LIST_LEVEL - row_lvl], + &(timer->row[RT_TIMER_SKIP_LIST_LEVEL - row_lvl])); + else + break; + /* Shift over the bits we have tested. Works well with 1 bit and 2 + * bits. */ + tst_nr >>= (RT_TIMER_SKIP_LIST_MASK + 1) >> 1; + } + + timer->parent.flag |= RT_TIMER_FLAG_ACTIVATED; + +#ifdef RT_USING_TIMER_SOFT + if (timer->parent.flag & RT_TIMER_FLAG_SOFT_TIMER) + { + /* check whether timer thread is ready */ + if ((_soft_timer_status == RT_SOFT_TIMER_IDLE) && + ((_timer_thread.stat & RT_THREAD_SUSPEND_MASK) == RT_THREAD_SUSPEND_MASK)) + { + /* resume timer thread to check soft timer */ + rt_thread_resume(&_timer_thread); + } + } +#endif /* RT_USING_TIMER_SOFT */ + + return RT_EOK; +} + +rt_err_t rt_timer_start(rt_timer_t timer) +{ + (void)timer; + return RT_EOK; +} +RTM_EXPORT(rt_timer_start); + +rt_err_t rt_timer_stop(rt_timer_t timer) +{ + rt_base_t level; + struct rt_spinlock *spinlock; + + /* timer check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(rt_object_get_type(&timer->parent) == RT_Object_Class_Timer); + +#ifdef RT_USING_TIMER_SOFT + if (timer->parent.flag & RT_TIMER_FLAG_SOFT_TIMER) + { + spinlock = &_soft_spinlock; + } + else +#endif /* RT_USING_TIMER_SOFT */ + { + spinlock = &_hard_spinlock; + } + level = rt_spin_lock_irqsave(spinlock); + + if (!(timer->parent.flag & RT_TIMER_FLAG_ACTIVATED)) + { + rt_spin_unlock_irqrestore(spinlock, level); + return -RT_ERROR; + } + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(timer->parent))); + + _timer_remove(timer); + /* change status */ + timer->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + rt_spin_unlock_irqrestore(spinlock, level); + + return RT_EOK; +} +RTM_EXPORT(rt_timer_stop); + +rt_err_t rt_timer_control(rt_timer_t timer, int cmd, void *arg) +{ + /* parameter check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(rt_object_get_type(&timer->parent) == RT_Object_Class_Timer); + + switch (cmd) + { + case RT_TIMER_CTRL_GET_TIME: + *(rt_tick_t *)arg = timer->init_tick; + break; + + case RT_TIMER_CTRL_SET_TIME: + RT_ASSERT((*(rt_tick_t *)arg) < RT_TICK_MAX / 2); + timer->init_tick = *(rt_tick_t *)arg; + break; + + case RT_TIMER_CTRL_SET_ONESHOT: + timer->parent.flag &= ~RT_TIMER_FLAG_PERIODIC; + break; + + case RT_TIMER_CTRL_SET_PERIODIC: + timer->parent.flag |= RT_TIMER_FLAG_PERIODIC; + break; + + case RT_TIMER_CTRL_GET_STATE: + if(timer->parent.flag & RT_TIMER_FLAG_ACTIVATED) + { + /*timer is start and run*/ + *(rt_uint32_t *)arg = RT_TIMER_FLAG_ACTIVATED; + } + else + { + /*timer is stop*/ + *(rt_uint32_t *)arg = RT_TIMER_FLAG_DEACTIVATED; + } + break; + + case RT_TIMER_CTRL_GET_REMAIN_TIME: + *(rt_tick_t *)arg = timer->timeout_tick; + break; + case RT_TIMER_CTRL_GET_FUNC: + *(void **)arg = (void *)timer->timeout_func; + break; + + case RT_TIMER_CTRL_SET_FUNC: + timer->timeout_func = (void (*)(void*))arg; + break; + + case RT_TIMER_CTRL_GET_PARM: + *(void **)arg = timer->parameter; + break; + + case RT_TIMER_CTRL_SET_PARM: + timer->parameter = arg; + break; + + default: + break; + } + + return RT_EOK; +} +RTM_EXPORT(rt_timer_control); + +void rt_timer_check(void) +{ + struct rt_timer *t; + rt_tick_t current_tick; + rt_base_t level; + rt_list_t list; + +#ifdef RT_USING_SMP + if (rt_hw_cpu_id() != 0) + { + return; + } +#endif + + rt_list_init(&list); + + LOG_D("timer check enter"); + + current_tick = rt_tick_get(); + + level = rt_spin_lock_irqsave(&_hard_spinlock); + + while (!rt_list_isempty(&_timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1])) + { + t = rt_list_entry(_timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1].next, + struct rt_timer, row[RT_TIMER_SKIP_LIST_LEVEL - 1]); + + /* + * It supposes that the new tick shall less than the half duration of + * tick max. + */ + if ((current_tick - t->timeout_tick) < RT_TICK_MAX / 2) + { + RT_OBJECT_HOOK_CALL(rt_timer_enter_hook, (t)); + + /* remove timer from timer list firstly */ + _timer_remove(t); + if (!(t->parent.flag & RT_TIMER_FLAG_PERIODIC)) + { + t->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + } + /* add timer to temporary list */ + rt_list_insert_after(&list, &(t->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + rt_spin_unlock_irqrestore(&_hard_spinlock, level); + /* call timeout function */ + t->timeout_func(t->parameter); + + /* re-get tick */ + current_tick = rt_tick_get(); + + RT_OBJECT_HOOK_CALL(rt_timer_exit_hook, (t)); + LOG_D("current tick: %d", current_tick); + level = rt_spin_lock_irqsave(&_hard_spinlock); + /* Check whether the timer object is detached or started again */ + if (rt_list_isempty(&list)) + { + continue; + } + rt_list_remove(&(t->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + if ((t->parent.flag & RT_TIMER_FLAG_PERIODIC) && + (t->parent.flag & RT_TIMER_FLAG_ACTIVATED)) + { + /* start it */ + t->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + _timer_start(_timer_list, t); + } + } + else break; + } + rt_spin_unlock_irqrestore(&_hard_spinlock, level); + LOG_D("timer check leave"); +} + +rt_tick_t rt_timer_next_timeout_tick(void) +{ + rt_base_t level; + rt_tick_t next_timeout = RT_TICK_MAX; + + level = rt_spin_lock_irqsave(&_hard_spinlock); + _timer_list_next_timeout(_timer_list, &next_timeout); + rt_spin_unlock_irqrestore(&_hard_spinlock, level); + + return next_timeout; +} + +void rt_soft_timer_check(void) +{ + rt_tick_t current_tick; + struct rt_timer *t; + rt_base_t level; + rt_list_t list; + + rt_list_init(&list); + LOG_D("software timer check enter"); + level = rt_spin_lock_irqsave(&_soft_spinlock); + + while (!rt_list_isempty(&_soft_timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1])) + { + t = rt_list_entry(_soft_timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1].next, + struct rt_timer, row[RT_TIMER_SKIP_LIST_LEVEL - 1]); + + current_tick = rt_tick_get(); + + /* + * It supposes that the new tick shall less than the half duration of + * tick max. + */ + if ((current_tick - t->timeout_tick) < RT_TICK_MAX / 2) + { + RT_OBJECT_HOOK_CALL(rt_timer_enter_hook, (t)); + + /* remove timer from timer list firstly */ + _timer_remove(t); + if (!(t->parent.flag & RT_TIMER_FLAG_PERIODIC)) + { + t->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + } + /* add timer to temporary list */ + rt_list_insert_after(&list, &(t->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + + _soft_timer_status = RT_SOFT_TIMER_BUSY; + + rt_spin_unlock_irqrestore(&_soft_spinlock, level); + + /* call timeout function */ + t->timeout_func(t->parameter); + + RT_OBJECT_HOOK_CALL(rt_timer_exit_hook, (t)); + LOG_D("current tick: %d", current_tick); + + level = rt_spin_lock_irqsave(&_soft_spinlock); + + _soft_timer_status = RT_SOFT_TIMER_IDLE; + /* Check whether the timer object is detached or started again */ + if (rt_list_isempty(&list)) + { + continue; + } + rt_list_remove(&(t->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + if ((t->parent.flag & RT_TIMER_FLAG_PERIODIC) && + (t->parent.flag & RT_TIMER_FLAG_ACTIVATED)) + { + /* start it */ + t->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + _timer_start(_soft_timer_list, t); + } + } + else break; /* not check anymore */ + } + + rt_spin_unlock_irqrestore(&_soft_spinlock, level); + + LOG_D("software timer check leave"); +} + +static void _timer_thread_entry(void *parameter) +{ + rt_err_t ret = RT_ERROR; + rt_tick_t next_timeout; + rt_base_t level; + + while (1) + { + /* get the next timeout tick */ + level = rt_spin_lock_irqsave(&_soft_spinlock); + ret = _timer_list_next_timeout(_soft_timer_list, &next_timeout); + rt_spin_unlock_irqrestore(&_soft_spinlock, level); + + if (ret != RT_EOK) + { + /* no software timer exist, suspend self. */ + rt_thread_suspend_with_flag(rt_thread_self(), RT_UNINTERRUPTIBLE); + rt_schedule(); + } + else + { + rt_tick_t current_tick; + + /* get current tick */ + current_tick = rt_tick_get(); + + if ((next_timeout - current_tick) < RT_TICK_MAX / 2) + { + /* get the delta timeout tick */ + next_timeout = next_timeout - current_tick; + rt_thread_delay(next_timeout); + } + } + + /* check software timer */ + rt_soft_timer_check(); + } +} + +void rt_system_timer_init(void) +{ + rt_size_t i; + + for (i = 0; i < sizeof(_timer_list) / sizeof(_timer_list[0]); i++) + { + rt_list_init(_timer_list + i); + } + rt_spin_lock_init(&_hard_spinlock); +} + +void rt_system_timer_thread_init(void) +{ +#ifdef RT_USING_TIMER_SOFT + int i; + + for (i = 0; + i < sizeof(_soft_timer_list) / sizeof(_soft_timer_list[0]); + i++) + { + rt_list_init(_soft_timer_list + i); + } + rt_spin_lock_init(&_soft_spinlock); + + /* start software timer thread */ + rt_thread_init(&_timer_thread, + "timer", + _timer_thread_entry, + RT_NULL, + &_timer_thread_stack[0], + sizeof(_timer_thread_stack), + RT_TIMER_THREAD_PRIO, + 10); + + /* startup */ + rt_thread_startup(&_timer_thread); +#endif /* RT_USING_TIMER_SOFT */ +} + diff --git a/tasks/runtime-rtthread-softtimer-wakeup/observations.c b/tasks/runtime-rtthread-softtimer-wakeup/observations.c new file mode 100644 index 00000000..cfa370bf --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/observations.c @@ -0,0 +1,78 @@ +#include +#include +#include +#include "controlled.h" + +static struct rt_timer timers[32]; +static int ids[32], counts[32], stop_after[32]; +static struct rt_spinlock *timer_lock; +static int injection_id, injection_time; +static rt_err_t peer_result; +static void fire(void *parameter) +{ + int id = *(int *)parameter; + counts[id]++; + printf("F %d %lu %d\n", id, (unsigned long)rt_tick_get(), rt_thread_self() == port_worker()); + if (stop_after[id] && counts[id] == stop_after[id]) + printf("C %d %ld\n", id, (long)rt_timer_stop(&timers[id])); +} +static void inject_start(void *unused) +{ + (void)unused; + if (injection_time >= 0) { + rt_tick_t time = (rt_tick_t)injection_time; + rt_timer_control(&timers[injection_id], RT_TIMER_CTRL_SET_TIME, &time); + } + printf("J %d %ld\n", injection_id, (long)rt_timer_start(&timers[injection_id])); +} +static void peer_resume(void *thread) { peer_result = rt_thread_resume(thread); } +int main(void) +{ + char op[16]; + while (scanf("%15s", op) == 1) { + int id, periodic, stop, kind; + unsigned long value; + if (!strcmp(op, "B")) { + scanf("%lu", &value); port_init((rt_tick_t)value); + ids[31] = 31; + rt_timer_init(&timers[31], "probe", fire, &ids[31], 100, RT_TIMER_FLAG_SOFT_TIMER); + port_capture_lock(); rt_timer_start(&timers[31]); + timer_lock = port_captured_lock(); rt_timer_stop(&timers[31]); + } else if (!strcmp(op, "N")) { + scanf("%d%lu%d%d", &id, &value, &periodic, &stop); + ids[id] = id; stop_after[id] = stop; + rt_timer_init(&timers[id], "client", fire, &ids[id], (rt_tick_t)value, + RT_TIMER_FLAG_SOFT_TIMER | (periodic ? RT_TIMER_FLAG_PERIODIC : 0)); + } else if (!strcmp(op, "S")) { + scanf("%d", &id); printf("S %d %ld\n", id, (long)rt_timer_start(&timers[id])); + } else if (!strcmp(op, "T")) { + scanf("%d", &id); printf("T %d %ld\n", id, (long)rt_timer_stop(&timers[id])); + } else if (!strcmp(op, "U")) { + scanf("%d%lu", &id, &value); rt_tick_t time = (rt_tick_t)value; + printf("U %d %ld\n", id, (long)rt_timer_control(&timers[id], RT_TIMER_CTRL_SET_TIME, &time)); + } else if (!strcmp(op, "V")) { + scanf("%d", &id); rt_uint32_t state = 0; rt_tick_t time = 0; + rt_timer_control(&timers[id], RT_TIMER_CTRL_GET_STATE, &state); + rt_timer_control(&timers[id], RT_TIMER_CTRL_GET_TIME, &time); + printf("V %d %d %lu\n", id, state == RT_TIMER_FLAG_ACTIVATED, (unsigned long)time); + } else if (!strcmp(op, "P")) port_pump(); + else if (!strcmp(op, "A")) { scanf("%lu", &value); port_advance((rt_tick_t)value); } + else if (!strcmp(op, "I")) { + scanf("%d%d", &injection_id, &injection_time); + port_after_unlock(timer_lock, inject_start, NULL); + } else if (!strcmp(op, "R")) { + scanf("%d", &kind); + rt_thread_t thread = port_worker(); + if (kind != 0) port_pump(); + rt_err_t a, b; + if (kind == 2) { + port_before_lock(&thread->spinlock, peer_resume, thread); + a = rt_thread_resume(thread); b = peer_result; + } else { a = rt_thread_resume(thread); b = rt_thread_resume(thread); } + printf("D %ld %ld %d %d\n", (long)a, (long)b, port_ready_count(thread), port_duplicate_ready()); + } else if (!strcmp(op, "Q")) { + printf("Q %d %d\n", port_duplicate_ready(), port_interleavings()); + } else return 3; + } + return 0; +} diff --git a/tasks/runtime-rtthread-softtimer-wakeup/prompt.md b/tasks/runtime-rtthread-softtimer-wakeup/prompt.md new file mode 100644 index 00000000..ca88260d --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/prompt.md @@ -0,0 +1,8 @@ +任务服务的现场重放中,短任务有时直到较长任务到期才回调;服务空闲后,新任务也可能一直没有回调。正常路径的 smoke 仍然通过。请修复当前工作区,使模块行为符合 `docs/service-contract.md` 的全部条款。 + +运行 `make smoke` 查看正常路径,运行 `make reproduce` 查看客户端回调日志。使用离散 tick,不需要板卡或网络。 + +最终只提交并评分以下文件: + +- `src/timer.c` +- `src/thread.c` diff --git a/tasks/runtime-rtthread-softtimer-wakeup/resume_only/src/thread.c b/tasks/runtime-rtthread-softtimer-wakeup/resume_only/src/thread.c new file mode 100644 index 00000000..c4031f6a --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/resume_only/src/thread.c @@ -0,0 +1,468 @@ +/* + * Copyright (c) 2006-2022, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +#include +#include +#include + +#define DBG_TAG "kernel.thread" +#define DBG_LVL DBG_INFO +#include + +#ifndef __on_rt_thread_inited_hook + #define __on_rt_thread_inited_hook(thread) __ON_HOOK_ARGS(rt_thread_inited_hook, (thread)) +#endif +#ifndef __on_rt_thread_suspend_hook + #define __on_rt_thread_suspend_hook(thread) __ON_HOOK_ARGS(rt_thread_suspend_hook, (thread)) +#endif +#ifndef __on_rt_thread_resume_hook + #define __on_rt_thread_resume_hook(thread) __ON_HOOK_ARGS(rt_thread_resume_hook, (thread)) +#endif + + +static void _thread_exit(void) +{ + struct rt_thread *thread; + rt_base_t level; + + /* get current thread */ + LOG_D("line:%d thread:%s exit\n",__LINE__,rt_thread_self()->parent.name); + thread = rt_thread_self(); + rt_get_thread_struct(thread); + rt_thread_defunct_enqueue(thread); + level = rt_spin_lock_irqsave(&(thread->spinlock)); + rt_timer_detach(&thread->thread_timer); + /* insert to defunct thread list */ + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + LOG_D("line:%d thread:%s exit\n",__LINE__,rt_thread_self()->parent.name); + rt_put_thread_struct(thread); + thread->stat = RT_THREAD_CLOSE; + /* switch to next task */ + rt_schedule(); +} + +static void _thread_timeout(void *parameter) +{ + struct rt_thread *thread; + rt_base_t level; + + thread = (struct rt_thread *)parameter; + + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT((thread->stat & RT_THREAD_SUSPEND_MASK) == RT_THREAD_SUSPEND_MASK); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + level = rt_spin_lock_irqsave(&(thread->spinlock)); + /* set error number */ + thread->error = -RT_ETIMEOUT; + + /* remove from suspend list */ + rt_list_remove(&(thread->tlist)); + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + /* insert to schedule ready list */ + rt_schedule_insert_thread(thread); + /* do schedule */ + rt_schedule(); +} + +static rt_err_t _thread_init(struct rt_thread *thread, + const char *name, + void (*entry)(void *parameter), + void *parameter, + void *stack_start, + rt_uint32_t stack_size, + rt_uint8_t priority, + rt_uint32_t tick) +{ + /* init thread list */ + rt_list_init(&(thread->tlist)); + rt_list_init(&(thread->tlist_schedule)); + +#ifdef RT_USING_MEM_PROTECTION + thread->mem_regions = RT_NULL; +#endif + +#ifdef RT_USING_SMART + thread->wakeup.func = RT_NULL; +#endif + + thread->entry = (void *)entry; + thread->parameter = parameter; + + /* stack init */ + thread->stack_addr = stack_start; + thread->stack_size = stack_size; + + /* init thread stack */ + rt_memset(thread->stack_addr, '#', thread->stack_size); +#ifdef RT_USING_HW_STACK_GUARD + rt_hw_stack_guard_init(thread); +#endif +#ifdef ARCH_CPU_STACK_GROWS_UPWARD + thread->sp = (void *)rt_hw_stack_init(thread->entry, thread->parameter, + (void *)((char *)thread->stack_addr), + (void *)_thread_exit); +#else + thread->sp = (void *)rt_hw_stack_init(thread->entry, thread->parameter, + (rt_uint8_t *)((char *)thread->stack_addr + thread->stack_size - sizeof(rt_ubase_t)), + (void *)_thread_exit); +#endif /* ARCH_CPU_STACK_GROWS_UPWARD */ + + /* priority init */ + RT_ASSERT(priority < RT_THREAD_PRIORITY_MAX); + thread->init_priority = priority; + thread->current_priority = priority; + + thread->number_mask = 0; + +#ifdef RT_USING_MUTEX + rt_list_init(&thread->taken_object_list); + thread->pending_object = RT_NULL; +#endif + +#ifdef RT_USING_EVENT + thread->event_set = 0; + thread->event_info = 0; +#endif /* RT_USING_EVENT */ + +#if RT_THREAD_PRIORITY_MAX > 32 + thread->number = 0; + thread->high_mask = 0; +#endif /* RT_THREAD_PRIORITY_MAX > 32 */ + + /* tick init */ + rt_atomic_store(&thread->init_tick, tick); + rt_atomic_store(&thread->remaining_tick, tick); + + /* error and flags */ + thread->error = RT_EOK; + thread->stat = RT_THREAD_INIT; + +#ifdef RT_USING_SMP + /* not bind on any cpu */ + thread->bind_cpu = RT_CPUS_NR; + thread->oncpu = RT_CPU_DETACHED; + + /* lock init */ + rt_atomic_store(&thread->cpus_lock_nest, 0); + rt_atomic_store(&thread->critical_lock_nest, 0); +#endif /* RT_USING_SMP */ + + /* initialize cleanup function and user data */ + thread->cleanup = 0; + thread->user_data = 0; + + /* initialize thread timer */ + rt_timer_init(&(thread->thread_timer), + thread->parent.name, + _thread_timeout, + thread, + 0, + RT_TIMER_FLAG_ONE_SHOT); + + /* initialize signal */ +#ifdef RT_USING_SIGNALS + thread->sig_mask = 0x00; + thread->sig_pending = 0x00; + +#ifndef RT_USING_SMP + thread->sig_ret = RT_NULL; +#endif /* RT_USING_SMP */ + thread->sig_vectors = RT_NULL; + thread->si_list = RT_NULL; +#endif /* RT_USING_SIGNALS */ + +#ifdef RT_USING_SMART + thread->tid_ref_count = 0; + thread->lwp = RT_NULL; + thread->susp_recycler = RT_NULL; + rt_list_init(&(thread->sibling)); + + /* lwp thread-signal init */ + rt_memset(&thread->signal.sigset_mask, 0, sizeof(lwp_sigset_t)); + rt_memset(&thread->signal.sig_queue.sigset_pending, 0, sizeof(lwp_sigset_t)); + rt_list_init(&thread->signal.sig_queue.siginfo_list); + + rt_memset(&thread->user_ctx, 0, sizeof thread->user_ctx); + + /* initialize user_time and system_time */ + thread->user_time = 0; + thread->system_time = 0; +#endif + +#ifdef RT_USING_CPU_USAGE + thread->duration_tick = 0; +#endif /* RT_USING_CPU_USAGE */ + +#ifdef RT_USING_PTHREADS + thread->pthread_data = RT_NULL; +#endif /* RT_USING_PTHREADS */ + +#ifdef RT_USING_MODULE + thread->parent.module_id = 0; +#endif /* RT_USING_MODULE */ + rt_atomic_store(&thread->ref_count, 0); + rt_spin_lock_init(&thread->spinlock); + + RT_OBJECT_HOOK_CALL(rt_thread_inited_hook, (thread)); + + return RT_EOK; +} + +rt_err_t rt_thread_init(struct rt_thread *thread, + const char *name, + void (*entry)(void *parameter), + void *parameter, + void *stack_start, + rt_uint32_t stack_size, + rt_uint8_t priority, + rt_uint32_t tick) +{ + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(stack_start != RT_NULL); + + /* initialize thread object */ + rt_object_init((rt_object_t)thread, RT_Object_Class_Thread, name); + + return _thread_init(thread, + name, + entry, + parameter, + stack_start, + stack_size, + priority, + tick); +} +RTM_EXPORT(rt_thread_init); + +rt_thread_t rt_thread_self(void) +{ +#ifdef RT_USING_SMP + rt_base_t lock; + rt_thread_t self; + + lock = rt_hw_local_irq_disable(); + self = rt_cpu_self()->current_thread; + rt_hw_local_irq_enable(lock); + return self; +#else + extern rt_thread_t rt_current_thread; + + return rt_current_thread; +#endif /* RT_USING_SMP */ +} +RTM_EXPORT(rt_thread_self); + +rt_err_t rt_thread_startup(rt_thread_t thread) +{ + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT((thread->stat & RT_THREAD_STAT_MASK) == RT_THREAD_INIT); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + + /* calculate priority attribute */ +#if RT_THREAD_PRIORITY_MAX > 32 + thread->number = thread->current_priority >> 3; /* 5bit */ + thread->number_mask = 1L << thread->number; + thread->high_mask = 1L << (thread->current_priority & 0x07); /* 3bit */ +#else + thread->number_mask = 1L << thread->current_priority; +#endif /* RT_THREAD_PRIORITY_MAX > 32 */ + + LOG_D("startup a thread:%s with priority:%d", + thread->parent.name, thread->current_priority); + /* change thread stat */ + thread->stat = RT_THREAD_SUSPEND; + /* then resume it */ + rt_thread_resume(thread); + if (rt_thread_self() != RT_NULL) + { + /* do a scheduling */ + rt_schedule(); + } + + return RT_EOK; +} +RTM_EXPORT(rt_thread_startup); + +rt_err_t rt_thread_sleep(rt_tick_t tick) +{ + rt_base_t level, level_local; + struct rt_thread *thread; + int err; + + if (tick == 0) + { + return -RT_EINVAL; + } + + /* set to current thread */ + thread = rt_thread_self(); + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE); + /* reset thread error */ + thread->error = RT_EOK; + level_local = rt_hw_local_irq_disable(); + /* suspend thread */ + err = rt_thread_suspend_with_flag(thread, RT_INTERRUPTIBLE); + level = rt_spin_lock_irqsave(&(thread->spinlock)); + /* reset the timeout of thread timer and start it */ + if (err == RT_EOK) + { + rt_timer_control(&(thread->thread_timer), RT_TIMER_CTRL_SET_TIME, &tick); + rt_timer_start(&(thread->thread_timer)); + + /* enable interrupt */ + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + rt_hw_local_irq_enable(level_local); + thread->error = -RT_EINTR; + + rt_schedule(); + + /* clear error number of this thread to RT_EOK */ + if (thread->error == -RT_ETIMEOUT) + thread->error = RT_EOK; + } + else + { + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + rt_hw_local_irq_enable(level_local); + } + + return err; +} + +rt_err_t rt_thread_delay(rt_tick_t tick) +{ + return rt_thread_sleep(tick); +} +RTM_EXPORT(rt_thread_delay); + +static void rt_thread_set_suspend_state(struct rt_thread *thread, int suspend_flag) +{ + rt_uint8_t stat = RT_THREAD_SUSPEND_UNINTERRUPTIBLE; + + RT_ASSERT(thread != RT_NULL); + switch (suspend_flag) + { + case RT_INTERRUPTIBLE: + stat = RT_THREAD_SUSPEND_INTERRUPTIBLE; + break; + case RT_KILLABLE: + stat = RT_THREAD_SUSPEND_KILLABLE; + break; + case RT_UNINTERRUPTIBLE: + stat = RT_THREAD_SUSPEND_UNINTERRUPTIBLE; + break; + default: + RT_ASSERT(0); + break; + } + thread->stat = stat | (thread->stat & ~RT_THREAD_STAT_MASK); +} + +rt_err_t rt_thread_suspend_with_flag(rt_thread_t thread, int suspend_flag) +{ + rt_base_t stat; + rt_base_t level; + + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + RT_ASSERT(thread == rt_thread_self()); + + LOG_D("thread suspend: %s", thread->parent.name); + + level = rt_spin_lock_irqsave(&(thread->spinlock)); + + stat = thread->stat & RT_THREAD_STAT_MASK; + if ((stat != RT_THREAD_READY) && (stat != RT_THREAD_RUNNING)) + { + LOG_D("thread suspend: thread disorder, 0x%2x", thread->stat); + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + return -RT_ERROR; + } + + if (stat == RT_THREAD_RUNNING) + { + /* not suspend running status thread on other core */ + RT_ASSERT(thread == rt_thread_self()); + } +#ifdef RT_USING_SMART + if (lwp_thread_signal_suspend_check(thread, suspend_flag) == 0) + { + /* not to suspend */ + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + return -RT_EINTR; + } +#endif + + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + rt_schedule_remove_thread(thread); + level = rt_spin_lock_irqsave(&(thread->spinlock)); + + rt_thread_set_suspend_state(thread, suspend_flag); + + /* stop thread timer anyway */ + rt_timer_stop(&(thread->thread_timer)); + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + + RT_OBJECT_HOOK_CALL(rt_thread_suspend_hook, (thread)); + return RT_EOK; +} +RTM_EXPORT(rt_thread_suspend_with_flag); + +rt_err_t rt_thread_suspend(rt_thread_t thread) +{ + return rt_thread_suspend_with_flag(thread, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_thread_suspend); + +rt_err_t rt_thread_resume(rt_thread_t thread) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + + LOG_D("thread resume: %s", thread->parent.name); + + level = rt_spin_lock_irqsave(&(thread->spinlock)); //TODO need lock for cpu + + if ((thread->stat & RT_THREAD_SUSPEND_MASK) != RT_THREAD_SUSPEND_MASK) + { + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + + LOG_D("thread resume: thread disorder, %d", + thread->stat); + + return -RT_ERROR; + } + + /* remove from suspend list */ + rt_list_remove(&(thread->tlist)); + + rt_timer_stop(&thread->thread_timer); + +#ifdef RT_USING_SMART + thread->wakeup.func = RT_NULL; +#endif + + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + /* insert to schedule ready list */ + rt_schedule_insert_thread(thread); + + RT_OBJECT_HOOK_CALL(rt_thread_resume_hook, (thread)); + return RT_EOK; +} +RTM_EXPORT(rt_thread_resume); + diff --git a/tasks/runtime-rtthread-softtimer-wakeup/resume_only/src/timer.c b/tasks/runtime-rtthread-softtimer-wakeup/resume_only/src/timer.c new file mode 100644 index 00000000..4e9864b0 --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/resume_only/src/timer.c @@ -0,0 +1,612 @@ +/* + * Copyright (c) 2006-2022, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +#include +#include + +#define DBG_TAG "kernel.timer" +#define DBG_LVL DBG_INFO +#include + +/* hard timer list */ +static rt_list_t _timer_list[RT_TIMER_SKIP_LIST_LEVEL]; +static struct rt_spinlock _hard_spinlock; + +#ifdef RT_USING_TIMER_SOFT + +#define RT_SOFT_TIMER_IDLE 1 +#define RT_SOFT_TIMER_BUSY 0 + +#ifndef RT_TIMER_THREAD_STACK_SIZE +#define RT_TIMER_THREAD_STACK_SIZE 512 +#endif /* RT_TIMER_THREAD_STACK_SIZE */ + +#ifndef RT_TIMER_THREAD_PRIO +#define RT_TIMER_THREAD_PRIO 0 +#endif /* RT_TIMER_THREAD_PRIO */ + +/* soft timer status */ +static rt_uint8_t _soft_timer_status = RT_SOFT_TIMER_IDLE; +/* soft timer list */ +static rt_list_t _soft_timer_list[RT_TIMER_SKIP_LIST_LEVEL]; +static struct rt_spinlock _soft_spinlock; +static struct rt_thread _timer_thread; +rt_align(RT_ALIGN_SIZE) +static rt_uint8_t _timer_thread_stack[RT_TIMER_THREAD_STACK_SIZE]; +#endif /* RT_USING_TIMER_SOFT */ + +#ifndef __on_rt_object_take_hook + #define __on_rt_object_take_hook(parent) __ON_HOOK_ARGS(rt_object_take_hook, (parent)) +#endif +#ifndef __on_rt_object_put_hook + #define __on_rt_object_put_hook(parent) __ON_HOOK_ARGS(rt_object_put_hook, (parent)) +#endif +#ifndef __on_rt_timer_enter_hook + #define __on_rt_timer_enter_hook(t) __ON_HOOK_ARGS(rt_timer_enter_hook, (t)) +#endif +#ifndef __on_rt_timer_exit_hook + #define __on_rt_timer_exit_hook(t) __ON_HOOK_ARGS(rt_timer_exit_hook, (t)) +#endif + + +static void _timer_init(rt_timer_t timer, + void (*timeout)(void *parameter), + void *parameter, + rt_tick_t time, + rt_uint8_t flag) +{ + int i; + + /* set flag */ + timer->parent.flag = flag; + + /* set deactivated */ + timer->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + + timer->timeout_func = timeout; + timer->parameter = parameter; + + timer->timeout_tick = 0; + timer->init_tick = time; + + /* initialize timer list */ + for (i = 0; i < RT_TIMER_SKIP_LIST_LEVEL; i++) + { + rt_list_init(&(timer->row[i])); + } +} + +static rt_err_t _timer_list_next_timeout(rt_list_t timer_list[], rt_tick_t *timeout_tick) +{ + struct rt_timer *timer; + + if (!rt_list_isempty(&timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1])) + { + timer = rt_list_entry(timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1].next, + struct rt_timer, row[RT_TIMER_SKIP_LIST_LEVEL - 1]); + *timeout_tick = timer->timeout_tick; + return RT_EOK; + } + return -RT_ERROR; +} + +rt_inline void _timer_remove(rt_timer_t timer) +{ + int i; + + for (i = 0; i < RT_TIMER_SKIP_LIST_LEVEL; i++) + { + rt_list_remove(&timer->row[i]); + } +} + +void rt_timer_init(rt_timer_t timer, + const char *name, + void (*timeout)(void *parameter), + void *parameter, + rt_tick_t time, + rt_uint8_t flag) +{ + /* parameter check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(timeout != RT_NULL); + RT_ASSERT(time < RT_TICK_MAX / 2); + + /* timer object initialization */ + rt_object_init(&(timer->parent), RT_Object_Class_Timer, name); + + _timer_init(timer, timeout, parameter, time, flag); +} +RTM_EXPORT(rt_timer_init); + +rt_err_t rt_timer_detach(rt_timer_t timer) +{ + rt_base_t level; + struct rt_spinlock *spinlock; + + /* parameter check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(rt_object_get_type(&timer->parent) == RT_Object_Class_Timer); + RT_ASSERT(rt_object_is_systemobject(&timer->parent)); + +#ifdef RT_USING_TIMER_SOFT + if (timer->parent.flag & RT_TIMER_FLAG_SOFT_TIMER) + { + spinlock = &_soft_spinlock; + } + else +#endif /* RT_USING_TIMER_SOFT */ + { + spinlock = &_hard_spinlock; + } + + level = rt_spin_lock_irqsave(spinlock); + + _timer_remove(timer); + /* stop timer */ + timer->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + + rt_spin_unlock_irqrestore(spinlock, level); + rt_object_detach(&(timer->parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_timer_detach); + +static rt_err_t _timer_start(rt_list_t *timer_list, rt_timer_t timer) +{ + unsigned int row_lvl; + rt_list_t *row_head[RT_TIMER_SKIP_LIST_LEVEL]; + unsigned int tst_nr; + static unsigned int random_nr; + + /* remove timer from list */ + _timer_remove(timer); + /* change status of timer */ + timer->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(timer->parent))); + + timer->timeout_tick = rt_tick_get() + timer->init_tick; + + row_head[0] = &timer_list[0]; + for (row_lvl = 0; row_lvl < RT_TIMER_SKIP_LIST_LEVEL; row_lvl++) + { + for (; row_head[row_lvl] != timer_list[row_lvl].prev; + row_head[row_lvl] = row_head[row_lvl]->next) + { + struct rt_timer *t; + rt_list_t *p = row_head[row_lvl]->next; + + /* fix up the entry pointer */ + t = rt_list_entry(p, struct rt_timer, row[row_lvl]); + + /* If we have two timers that timeout at the same time, it's + * preferred that the timer inserted early get called early. + * So insert the new timer to the end the the some-timeout timer + * list. + */ + if ((t->timeout_tick - timer->timeout_tick) == 0) + { + continue; + } + else if ((t->timeout_tick - timer->timeout_tick) < RT_TICK_MAX / 2) + { + break; + } + } + if (row_lvl != RT_TIMER_SKIP_LIST_LEVEL - 1) + row_head[row_lvl + 1] = row_head[row_lvl] + 1; + } + + /* Interestingly, this super simple timer insert counter works very very + * well on distributing the list height uniformly. By means of "very very + * well", I mean it beats the randomness of timer->timeout_tick very easily + * (actually, the timeout_tick is not random and easy to be attacked). */ + random_nr++; + tst_nr = random_nr; + + rt_list_insert_after(row_head[RT_TIMER_SKIP_LIST_LEVEL - 1], + &(timer->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + for (row_lvl = 2; row_lvl <= RT_TIMER_SKIP_LIST_LEVEL; row_lvl++) + { + if (!(tst_nr & RT_TIMER_SKIP_LIST_MASK)) + rt_list_insert_after(row_head[RT_TIMER_SKIP_LIST_LEVEL - row_lvl], + &(timer->row[RT_TIMER_SKIP_LIST_LEVEL - row_lvl])); + else + break; + /* Shift over the bits we have tested. Works well with 1 bit and 2 + * bits. */ + tst_nr >>= (RT_TIMER_SKIP_LIST_MASK + 1) >> 1; + } + + timer->parent.flag |= RT_TIMER_FLAG_ACTIVATED; + +#ifdef RT_USING_TIMER_SOFT + if (timer->parent.flag & RT_TIMER_FLAG_SOFT_TIMER) + { + /* check whether timer thread is ready */ + if ((_soft_timer_status == RT_SOFT_TIMER_IDLE) && + ((_timer_thread.stat & RT_THREAD_SUSPEND_MASK) == RT_THREAD_SUSPEND_MASK)) + { + /* resume timer thread to check soft timer */ + rt_thread_resume(&_timer_thread); + } + } +#endif /* RT_USING_TIMER_SOFT */ + + return RT_EOK; +} + +rt_err_t rt_timer_start(rt_timer_t timer) +{ + struct rt_spinlock *spinlock; + rt_list_t *timer_list; + rt_base_t level; + rt_err_t err; + + /* parameter check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(rt_object_get_type(&timer->parent) == RT_Object_Class_Timer); + +#ifdef RT_USING_TIMER_SOFT + if (timer->parent.flag & RT_TIMER_FLAG_SOFT_TIMER) + { + timer_list = _soft_timer_list; + spinlock = &_soft_spinlock; + } + else +#endif /* RT_USING_TIMER_SOFT */ + { + timer_list = _timer_list; + spinlock = &_hard_spinlock; + } + + /* stop timer firstly */ + level = rt_spin_lock_irqsave(spinlock); + err = _timer_start(timer_list, timer); + rt_spin_unlock_irqrestore(spinlock, level); + + return err; +} +RTM_EXPORT(rt_timer_start); + +rt_err_t rt_timer_stop(rt_timer_t timer) +{ + rt_base_t level; + struct rt_spinlock *spinlock; + + /* timer check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(rt_object_get_type(&timer->parent) == RT_Object_Class_Timer); + +#ifdef RT_USING_TIMER_SOFT + if (timer->parent.flag & RT_TIMER_FLAG_SOFT_TIMER) + { + spinlock = &_soft_spinlock; + } + else +#endif /* RT_USING_TIMER_SOFT */ + { + spinlock = &_hard_spinlock; + } + level = rt_spin_lock_irqsave(spinlock); + + if (!(timer->parent.flag & RT_TIMER_FLAG_ACTIVATED)) + { + rt_spin_unlock_irqrestore(spinlock, level); + return -RT_ERROR; + } + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(timer->parent))); + + _timer_remove(timer); + /* change status */ + timer->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + rt_spin_unlock_irqrestore(spinlock, level); + + return RT_EOK; +} +RTM_EXPORT(rt_timer_stop); + +rt_err_t rt_timer_control(rt_timer_t timer, int cmd, void *arg) +{ + /* parameter check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(rt_object_get_type(&timer->parent) == RT_Object_Class_Timer); + + switch (cmd) + { + case RT_TIMER_CTRL_GET_TIME: + *(rt_tick_t *)arg = timer->init_tick; + break; + + case RT_TIMER_CTRL_SET_TIME: + RT_ASSERT((*(rt_tick_t *)arg) < RT_TICK_MAX / 2); + timer->init_tick = *(rt_tick_t *)arg; + break; + + case RT_TIMER_CTRL_SET_ONESHOT: + timer->parent.flag &= ~RT_TIMER_FLAG_PERIODIC; + break; + + case RT_TIMER_CTRL_SET_PERIODIC: + timer->parent.flag |= RT_TIMER_FLAG_PERIODIC; + break; + + case RT_TIMER_CTRL_GET_STATE: + if(timer->parent.flag & RT_TIMER_FLAG_ACTIVATED) + { + /*timer is start and run*/ + *(rt_uint32_t *)arg = RT_TIMER_FLAG_ACTIVATED; + } + else + { + /*timer is stop*/ + *(rt_uint32_t *)arg = RT_TIMER_FLAG_DEACTIVATED; + } + break; + + case RT_TIMER_CTRL_GET_REMAIN_TIME: + *(rt_tick_t *)arg = timer->timeout_tick; + break; + case RT_TIMER_CTRL_GET_FUNC: + *(void **)arg = (void *)timer->timeout_func; + break; + + case RT_TIMER_CTRL_SET_FUNC: + timer->timeout_func = (void (*)(void*))arg; + break; + + case RT_TIMER_CTRL_GET_PARM: + *(void **)arg = timer->parameter; + break; + + case RT_TIMER_CTRL_SET_PARM: + timer->parameter = arg; + break; + + default: + break; + } + + return RT_EOK; +} +RTM_EXPORT(rt_timer_control); + +void rt_timer_check(void) +{ + struct rt_timer *t; + rt_tick_t current_tick; + rt_base_t level; + rt_list_t list; + +#ifdef RT_USING_SMP + if (rt_hw_cpu_id() != 0) + { + return; + } +#endif + + rt_list_init(&list); + + LOG_D("timer check enter"); + + current_tick = rt_tick_get(); + + level = rt_spin_lock_irqsave(&_hard_spinlock); + + while (!rt_list_isempty(&_timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1])) + { + t = rt_list_entry(_timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1].next, + struct rt_timer, row[RT_TIMER_SKIP_LIST_LEVEL - 1]); + + /* + * It supposes that the new tick shall less than the half duration of + * tick max. + */ + if ((current_tick - t->timeout_tick) < RT_TICK_MAX / 2) + { + RT_OBJECT_HOOK_CALL(rt_timer_enter_hook, (t)); + + /* remove timer from timer list firstly */ + _timer_remove(t); + if (!(t->parent.flag & RT_TIMER_FLAG_PERIODIC)) + { + t->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + } + /* add timer to temporary list */ + rt_list_insert_after(&list, &(t->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + rt_spin_unlock_irqrestore(&_hard_spinlock, level); + /* call timeout function */ + t->timeout_func(t->parameter); + + /* re-get tick */ + current_tick = rt_tick_get(); + + RT_OBJECT_HOOK_CALL(rt_timer_exit_hook, (t)); + LOG_D("current tick: %d", current_tick); + level = rt_spin_lock_irqsave(&_hard_spinlock); + /* Check whether the timer object is detached or started again */ + if (rt_list_isempty(&list)) + { + continue; + } + rt_list_remove(&(t->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + if ((t->parent.flag & RT_TIMER_FLAG_PERIODIC) && + (t->parent.flag & RT_TIMER_FLAG_ACTIVATED)) + { + /* start it */ + t->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + _timer_start(_timer_list, t); + } + } + else break; + } + rt_spin_unlock_irqrestore(&_hard_spinlock, level); + LOG_D("timer check leave"); +} + +rt_tick_t rt_timer_next_timeout_tick(void) +{ + rt_base_t level; + rt_tick_t next_timeout = RT_TICK_MAX; + + level = rt_spin_lock_irqsave(&_hard_spinlock); + _timer_list_next_timeout(_timer_list, &next_timeout); + rt_spin_unlock_irqrestore(&_hard_spinlock, level); + + return next_timeout; +} + +void rt_soft_timer_check(void) +{ + rt_tick_t current_tick; + struct rt_timer *t; + rt_base_t level; + rt_list_t list; + + rt_list_init(&list); + LOG_D("software timer check enter"); + level = rt_spin_lock_irqsave(&_soft_spinlock); + + while (!rt_list_isempty(&_soft_timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1])) + { + t = rt_list_entry(_soft_timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1].next, + struct rt_timer, row[RT_TIMER_SKIP_LIST_LEVEL - 1]); + + current_tick = rt_tick_get(); + + /* + * It supposes that the new tick shall less than the half duration of + * tick max. + */ + if ((current_tick - t->timeout_tick) < RT_TICK_MAX / 2) + { + RT_OBJECT_HOOK_CALL(rt_timer_enter_hook, (t)); + + /* remove timer from timer list firstly */ + _timer_remove(t); + if (!(t->parent.flag & RT_TIMER_FLAG_PERIODIC)) + { + t->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + } + /* add timer to temporary list */ + rt_list_insert_after(&list, &(t->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + + _soft_timer_status = RT_SOFT_TIMER_BUSY; + + rt_spin_unlock_irqrestore(&_soft_spinlock, level); + + /* call timeout function */ + t->timeout_func(t->parameter); + + RT_OBJECT_HOOK_CALL(rt_timer_exit_hook, (t)); + LOG_D("current tick: %d", current_tick); + + level = rt_spin_lock_irqsave(&_soft_spinlock); + + _soft_timer_status = RT_SOFT_TIMER_IDLE; + /* Check whether the timer object is detached or started again */ + if (rt_list_isempty(&list)) + { + continue; + } + rt_list_remove(&(t->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + if ((t->parent.flag & RT_TIMER_FLAG_PERIODIC) && + (t->parent.flag & RT_TIMER_FLAG_ACTIVATED)) + { + /* start it */ + t->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + _timer_start(_soft_timer_list, t); + } + } + else break; /* not check anymore */ + } + + rt_spin_unlock_irqrestore(&_soft_spinlock, level); + + LOG_D("software timer check leave"); +} + +static void _timer_thread_entry(void *parameter) +{ + rt_err_t ret = RT_ERROR; + rt_tick_t next_timeout; + rt_base_t level; + + while (1) + { + /* get the next timeout tick */ + level = rt_spin_lock_irqsave(&_soft_spinlock); + ret = _timer_list_next_timeout(_soft_timer_list, &next_timeout); + rt_spin_unlock_irqrestore(&_soft_spinlock, level); + + if (ret != RT_EOK) + { + /* no software timer exist, suspend self. */ + rt_thread_suspend_with_flag(rt_thread_self(), RT_UNINTERRUPTIBLE); + rt_schedule(); + } + else + { + rt_tick_t current_tick; + + /* get current tick */ + current_tick = rt_tick_get(); + + if ((next_timeout - current_tick) < RT_TICK_MAX / 2) + { + /* get the delta timeout tick */ + next_timeout = next_timeout - current_tick; + rt_thread_delay(next_timeout); + } + } + + /* check software timer */ + rt_soft_timer_check(); + } +} + +void rt_system_timer_init(void) +{ + rt_size_t i; + + for (i = 0; i < sizeof(_timer_list) / sizeof(_timer_list[0]); i++) + { + rt_list_init(_timer_list + i); + } + rt_spin_lock_init(&_hard_spinlock); +} + +void rt_system_timer_thread_init(void) +{ +#ifdef RT_USING_TIMER_SOFT + int i; + + for (i = 0; + i < sizeof(_soft_timer_list) / sizeof(_soft_timer_list[0]); + i++) + { + rt_list_init(_soft_timer_list + i); + } + rt_spin_lock_init(&_soft_spinlock); + + /* start software timer thread */ + rt_thread_init(&_timer_thread, + "timer", + _timer_thread_entry, + RT_NULL, + &_timer_thread_stack[0], + sizeof(_timer_thread_stack), + RT_TIMER_THREAD_PRIO, + 10); + + /* startup */ + rt_thread_startup(&_timer_thread); +#endif /* RT_USING_TIMER_SOFT */ +} + diff --git a/tasks/runtime-rtthread-softtimer-wakeup/spec.md b/tasks/runtime-rtthread-softtimer-wakeup/spec.md new file mode 100644 index 00000000..4c78a472 --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/spec.md @@ -0,0 +1,66 @@ +# runtime-rtthread-softtimer-wakeup + +状态:CALIBRATED / UNMEASURED。路线 D,族 state-machine-timing,语言 C。仅制作、行为校准,未运行模型,不推断难度或硬件结果。正式回执以本题 factory/report.json 的当前摘要为准。 + +## 来源与许可 + +- 上游:https://github.com/RT-Thread/rt-thread +- 修复前:e1fdc13288eb110d8280f68594c2d87e14446437。 +- 修复:20a4d0939a5251b7b730f4f9f1beb0a4c0ca486a,父提交即上述修复前版本。 +- source:oss/RT-Thread/rt-thread@20a4d0939a52;split_group:RT-Thread/rt-thread。 +- Apache-2.0,来自该版本根 LICENSE;各源文件和头文件保留 RT-Thread 版权与 SPDX。该提交仅改 src/thread.c 和 src/timer.c,22 增、21 删,没有导入新增测试或文档。 +- 上游取材在指定只读克隆中通过 git show,未 checkout 或修改历史/config。原始取材与函数清单保存在本题 factory/upstream/、extract.json。 + +## 缺陷与纵向范围 + +只有一个真实上游修复,但它跨两个文件与多个实质函数:软件定时器启动、系统服务线程初始化与等待循环,以及线程恢复。初态在读出下一截止时间后、进入挂起之前可能遗漏应用侧启动,导致空队列或已有较晚截止时间时的新任务不能在应有时间处理;另一个恢复请求在首个请求的状态检查与获得锁之间完成时,初态可能重复恢复同一线程。 + +保留真实 timer 列表插入/移除、start/stop/control、硬定时器到线程 timeout、软定时器检查与线程入口、thread 初始化/启动/挂起/恢复,以及 semaphore 初始化/获取/释放/控制路径。硬定时器负责线程自身等待超时,软件回调经过真实服务线程。移植层只提供 tick、对象元数据、通用就绪队列、上下文切换与通用锁边界交错,不扫描软件列表,不生成软件通知,也不修正挂起或恢复状态。 + +与 timer-wrap-deadline 题的版本、失败行为及候选集合不同;本题不考 tick 环绕修复。所有观测以本版本公开接口行为为准。 + +## 冻结文件与补全文件 + +上游冻结(只删除历史 Change Logs 块,不改执行语句): + +- `src/timer.c`:按完整函数抽取与本题相关的静态定时器与线程服务函数及其静态数据,不保留动态堆创建/删除、调试 dump 和 hook 设置函数。 +- `src/thread.c`:按完整函数抽取初始化、启动、线程自身、sleep/delay、timeout、挂起状态与恢复路径。保留初始化所需退出入口。 +- `src/semaphore.c`:从上游 src/ipc.c 按完整函数抽取 IPC 等待链表和 semaphore 路径;仅补 include 指令。 +- `include/rtdef.h`、`include/rtthread.h`、`include/rtservice.h`、`include/rthw.h`、`include/rtdbg.h`、`include/rtm.h`、`include/rtatomic.h`。 +- `LICENSE`。 + +补全:`include/rtconfig.h`(固定启用 SMP/静态 timer/semaphore 配置)、`include/cpuport.h`(软件锁存储类型)、`port/controlled.h`、`port/controlled.c`(离散调度移植)、`Makefile`、`smoke.c`(正常路径)、`reproduce.c`(应用侧重放)、`README.md`、`docs/service-contract.md`(公开合同整理)。没有第三方依赖。 + +真实 C 实现抽取行数见 factory/source-count.json;不把头文件、移植层、构建、smoke、重放或私有 harness 计入真实源码门槛。三个真实实现共 1459 原始行,938 非空非注释 C 行;实际启用数另见 factory/active-source-count.json。冻结函数与上游逐函数对应,gold 仅应用指定修复在两个候选文件中的变化。 + +## 判据检查项与公开依据 + +| 检查项 | 公开依据 | 上游公开依据 | +|---|---|---| +| 初始化不活动、时长单位、零 tick 一次任务 | template/docs/service-contract.md:5 | documentation/timer/timer.md 的 Timer Management、src/timer.c 的 _timer_init 与 SET_TIME 范围 | +| 启动、重复启动替换、配置时长和活动状态 | template/docs/service-contract.md:7 | documentation/timer/timer.md 的 Start and Stop Timer;src/timer.c 的 _timer_start 与 rt_timer_control | +| 空闲/已有排期/应用交错后的到期服务、不得提前回调、软件线程上下文 | template/docs/service-contract.md:9 | documentation/timer/timer.md 的 SOFT_TIMER Mode、Timer Working Mechanism | +| 一次回调、不重复、同截止时间先后次序 | template/docs/service-contract.md:11 | documentation/timer/timer.md 的 one-shot 定义;_timer_start 中同截止时间排序的公开注释 | +| 周期重排、错过周期的处理与回调内停止 | template/docs/service-contract.md:13 | documentation/timer/timer.md 的 periodic 定义和停止说明;rt_soft_timer_check 的重排路径 | +| 停止成功/已停止错误、不触发旧排期、可再启动 | template/docs/service-contract.md:15 | documentation/timer/timer.md 的 Start and Stop Timer 返回表和停止说明 | +| SET_TIME 不单独启动、GET_TIME 与 GET_STATE | template/docs/service-contract.md:17 | src/timer.c 的 rt_timer_control 公开控制接口 | +| 非挂起拒绝、挂起恢复、就绪队列有效 | template/docs/service-contract.md:19 | documentation/thread/thread.md 的 Resume Thread 返回表 | +| 并发恢复与同一挂起阶段的一次成功、队列唯一 | template/docs/service-contract.md:21 | documentation/thread/thread.md 的线程状态与 Resume Thread;公开 rt_thread_resume 对挂起条件的约定 | +| 离散 tick、就绪运行、通用应用交错不增加时间 | template/docs/service-contract.md:23、25 | 本移植接口公开合同;不增加内核功能 | +| 有限操作预算,无法交还控制权不能通过 | template/docs/service-contract.md:27 | 本移植接口公开合同;documentation/thread/thread.md 的线程须让出 CPU 的说明 | + +## 私有判据与样例 + +`verify.py` 逐字复制 rollout/bos_verify.py。私有附件只有 check.py 和非 Python 数据 support.tar、observations.c。support.tar 与公开补全/冻结支持文件逐字相同,仅为评分侧重建候选依赖;不包含参考修复或期望值。候选仅在降为 UID/GID 65534 的编译器/运行子进程执行。check.py 保留独立的定时器排期模型与所有期望值;观察 harness 只打印启动/停止/配置返回值、活动状态、回调 tick/上下文与恢复/队列观察,不做断言或判断 PASS。候选运行前写完构建输入,运行后不读取临时文件;只捕获进程输出。 + +48 个场景、336 条原始观察,四组不同起始 tick/长短时长,覆盖空闲查询间隙、较晚排期间隙、同对象缩短并重启、同截止时间和重复 start、等待中插入/取消/重启、周期与一次任务混合和自停止、后来截止时间不干扰较早任务、多个通知可合并但所有排期有效、零时长一次任务,以及 READY/正常恢复/竞争恢复。除线程本身等待以外不核定任何 semaphore 内部字段、通知次数、等待调用次数或固定实现布局。 + +9 类样例:gold、valid_atomic_wait 应 PASS;template、noop、cheat、cheat_read_grader、symptom_only、timer_only、resume_only 应 FAIL。noop 不排期;cheat 在启动时同步调用;cheat_read_grader 尝试读取私有文件后退出;symptom_only 仅把空闲等待改为一个 tick 轮询,仍保留已有较晚排期和恢复问题;timer_only/resume_only 分别只接受补丁一侧。单一修复不要求逐缺陷样例,这两类用于证明两个路径都被覆盖。 + +valid_atomic_wait 在列表锁保护范围内查询并装配线程等待,解除锁后调度,沿用原有 resume 通知,不使用新增 semaphore。它与 gold 的持久通知方案不同,验证判据接受不同同步方式。 + +## 验证与限制 + +所有编译、smoke、重放、预处理和评分均在固定 trace6 镜像的无网容器中。每个容器精确唯一名称并带 --rm,前置 /home 10 GiB、Docker 5 GiB 空间检查,之后按精确名称复核不存在。正式校准通过平台 core.calibrate 生成回执,当前任务每类五次,共45次;驱动只在本进程调整本批停止线并给 Docker argv 加 --rm,不修改平台源文件。 + +不运行真实模型,不声称完整 Agent 轨迹,不验证板卡与实际 SMP 时间性能。受控端口重放公开锁边界的线性化交错,不是真硬件调度器。全库 unittest 由 root 在批次回归中记录,本题作者不在宿主执行上游构建或运行。 diff --git a/tasks/runtime-rtthread-softtimer-wakeup/support.tar b/tasks/runtime-rtthread-softtimer-wakeup/support.tar new file mode 100644 index 00000000..5a7af60c Binary files /dev/null and b/tasks/runtime-rtthread-softtimer-wakeup/support.tar differ diff --git a/tasks/runtime-rtthread-softtimer-wakeup/symptom_only/src/thread.c b/tasks/runtime-rtthread-softtimer-wakeup/symptom_only/src/thread.c new file mode 100644 index 00000000..3151c913 --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/symptom_only/src/thread.c @@ -0,0 +1,466 @@ +/* + * Copyright (c) 2006-2022, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +#include +#include +#include + +#define DBG_TAG "kernel.thread" +#define DBG_LVL DBG_INFO +#include + +#ifndef __on_rt_thread_inited_hook + #define __on_rt_thread_inited_hook(thread) __ON_HOOK_ARGS(rt_thread_inited_hook, (thread)) +#endif +#ifndef __on_rt_thread_suspend_hook + #define __on_rt_thread_suspend_hook(thread) __ON_HOOK_ARGS(rt_thread_suspend_hook, (thread)) +#endif +#ifndef __on_rt_thread_resume_hook + #define __on_rt_thread_resume_hook(thread) __ON_HOOK_ARGS(rt_thread_resume_hook, (thread)) +#endif + + +static void _thread_exit(void) +{ + struct rt_thread *thread; + rt_base_t level; + + /* get current thread */ + LOG_D("line:%d thread:%s exit\n",__LINE__,rt_thread_self()->parent.name); + thread = rt_thread_self(); + rt_get_thread_struct(thread); + rt_thread_defunct_enqueue(thread); + level = rt_spin_lock_irqsave(&(thread->spinlock)); + rt_timer_detach(&thread->thread_timer); + /* insert to defunct thread list */ + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + LOG_D("line:%d thread:%s exit\n",__LINE__,rt_thread_self()->parent.name); + rt_put_thread_struct(thread); + thread->stat = RT_THREAD_CLOSE; + /* switch to next task */ + rt_schedule(); +} + +static void _thread_timeout(void *parameter) +{ + struct rt_thread *thread; + rt_base_t level; + + thread = (struct rt_thread *)parameter; + + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT((thread->stat & RT_THREAD_SUSPEND_MASK) == RT_THREAD_SUSPEND_MASK); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + level = rt_spin_lock_irqsave(&(thread->spinlock)); + /* set error number */ + thread->error = -RT_ETIMEOUT; + + /* remove from suspend list */ + rt_list_remove(&(thread->tlist)); + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + /* insert to schedule ready list */ + rt_schedule_insert_thread(thread); + /* do schedule */ + rt_schedule(); +} + +static rt_err_t _thread_init(struct rt_thread *thread, + const char *name, + void (*entry)(void *parameter), + void *parameter, + void *stack_start, + rt_uint32_t stack_size, + rt_uint8_t priority, + rt_uint32_t tick) +{ + /* init thread list */ + rt_list_init(&(thread->tlist)); + rt_list_init(&(thread->tlist_schedule)); + +#ifdef RT_USING_MEM_PROTECTION + thread->mem_regions = RT_NULL; +#endif + +#ifdef RT_USING_SMART + thread->wakeup.func = RT_NULL; +#endif + + thread->entry = (void *)entry; + thread->parameter = parameter; + + /* stack init */ + thread->stack_addr = stack_start; + thread->stack_size = stack_size; + + /* init thread stack */ + rt_memset(thread->stack_addr, '#', thread->stack_size); +#ifdef RT_USING_HW_STACK_GUARD + rt_hw_stack_guard_init(thread); +#endif +#ifdef ARCH_CPU_STACK_GROWS_UPWARD + thread->sp = (void *)rt_hw_stack_init(thread->entry, thread->parameter, + (void *)((char *)thread->stack_addr), + (void *)_thread_exit); +#else + thread->sp = (void *)rt_hw_stack_init(thread->entry, thread->parameter, + (rt_uint8_t *)((char *)thread->stack_addr + thread->stack_size - sizeof(rt_ubase_t)), + (void *)_thread_exit); +#endif /* ARCH_CPU_STACK_GROWS_UPWARD */ + + /* priority init */ + RT_ASSERT(priority < RT_THREAD_PRIORITY_MAX); + thread->init_priority = priority; + thread->current_priority = priority; + + thread->number_mask = 0; + +#ifdef RT_USING_MUTEX + rt_list_init(&thread->taken_object_list); + thread->pending_object = RT_NULL; +#endif + +#ifdef RT_USING_EVENT + thread->event_set = 0; + thread->event_info = 0; +#endif /* RT_USING_EVENT */ + +#if RT_THREAD_PRIORITY_MAX > 32 + thread->number = 0; + thread->high_mask = 0; +#endif /* RT_THREAD_PRIORITY_MAX > 32 */ + + /* tick init */ + rt_atomic_store(&thread->init_tick, tick); + rt_atomic_store(&thread->remaining_tick, tick); + + /* error and flags */ + thread->error = RT_EOK; + thread->stat = RT_THREAD_INIT; + +#ifdef RT_USING_SMP + /* not bind on any cpu */ + thread->bind_cpu = RT_CPUS_NR; + thread->oncpu = RT_CPU_DETACHED; + + /* lock init */ + rt_atomic_store(&thread->cpus_lock_nest, 0); + rt_atomic_store(&thread->critical_lock_nest, 0); +#endif /* RT_USING_SMP */ + + /* initialize cleanup function and user data */ + thread->cleanup = 0; + thread->user_data = 0; + + /* initialize thread timer */ + rt_timer_init(&(thread->thread_timer), + thread->parent.name, + _thread_timeout, + thread, + 0, + RT_TIMER_FLAG_ONE_SHOT); + + /* initialize signal */ +#ifdef RT_USING_SIGNALS + thread->sig_mask = 0x00; + thread->sig_pending = 0x00; + +#ifndef RT_USING_SMP + thread->sig_ret = RT_NULL; +#endif /* RT_USING_SMP */ + thread->sig_vectors = RT_NULL; + thread->si_list = RT_NULL; +#endif /* RT_USING_SIGNALS */ + +#ifdef RT_USING_SMART + thread->tid_ref_count = 0; + thread->lwp = RT_NULL; + thread->susp_recycler = RT_NULL; + rt_list_init(&(thread->sibling)); + + /* lwp thread-signal init */ + rt_memset(&thread->signal.sigset_mask, 0, sizeof(lwp_sigset_t)); + rt_memset(&thread->signal.sig_queue.sigset_pending, 0, sizeof(lwp_sigset_t)); + rt_list_init(&thread->signal.sig_queue.siginfo_list); + + rt_memset(&thread->user_ctx, 0, sizeof thread->user_ctx); + + /* initialize user_time and system_time */ + thread->user_time = 0; + thread->system_time = 0; +#endif + +#ifdef RT_USING_CPU_USAGE + thread->duration_tick = 0; +#endif /* RT_USING_CPU_USAGE */ + +#ifdef RT_USING_PTHREADS + thread->pthread_data = RT_NULL; +#endif /* RT_USING_PTHREADS */ + +#ifdef RT_USING_MODULE + thread->parent.module_id = 0; +#endif /* RT_USING_MODULE */ + rt_atomic_store(&thread->ref_count, 0); + rt_spin_lock_init(&thread->spinlock); + + RT_OBJECT_HOOK_CALL(rt_thread_inited_hook, (thread)); + + return RT_EOK; +} + +rt_err_t rt_thread_init(struct rt_thread *thread, + const char *name, + void (*entry)(void *parameter), + void *parameter, + void *stack_start, + rt_uint32_t stack_size, + rt_uint8_t priority, + rt_uint32_t tick) +{ + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(stack_start != RT_NULL); + + /* initialize thread object */ + rt_object_init((rt_object_t)thread, RT_Object_Class_Thread, name); + + return _thread_init(thread, + name, + entry, + parameter, + stack_start, + stack_size, + priority, + tick); +} +RTM_EXPORT(rt_thread_init); + +rt_thread_t rt_thread_self(void) +{ +#ifdef RT_USING_SMP + rt_base_t lock; + rt_thread_t self; + + lock = rt_hw_local_irq_disable(); + self = rt_cpu_self()->current_thread; + rt_hw_local_irq_enable(lock); + return self; +#else + extern rt_thread_t rt_current_thread; + + return rt_current_thread; +#endif /* RT_USING_SMP */ +} +RTM_EXPORT(rt_thread_self); + +rt_err_t rt_thread_startup(rt_thread_t thread) +{ + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT((thread->stat & RT_THREAD_STAT_MASK) == RT_THREAD_INIT); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + + /* calculate priority attribute */ +#if RT_THREAD_PRIORITY_MAX > 32 + thread->number = thread->current_priority >> 3; /* 5bit */ + thread->number_mask = 1L << thread->number; + thread->high_mask = 1L << (thread->current_priority & 0x07); /* 3bit */ +#else + thread->number_mask = 1L << thread->current_priority; +#endif /* RT_THREAD_PRIORITY_MAX > 32 */ + + LOG_D("startup a thread:%s with priority:%d", + thread->parent.name, thread->current_priority); + /* change thread stat */ + thread->stat = RT_THREAD_SUSPEND; + /* then resume it */ + rt_thread_resume(thread); + if (rt_thread_self() != RT_NULL) + { + /* do a scheduling */ + rt_schedule(); + } + + return RT_EOK; +} +RTM_EXPORT(rt_thread_startup); + +rt_err_t rt_thread_sleep(rt_tick_t tick) +{ + rt_base_t level, level_local; + struct rt_thread *thread; + int err; + + if (tick == 0) + { + return -RT_EINVAL; + } + + /* set to current thread */ + thread = rt_thread_self(); + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE); + /* reset thread error */ + thread->error = RT_EOK; + level_local = rt_hw_local_irq_disable(); + /* suspend thread */ + err = rt_thread_suspend_with_flag(thread, RT_INTERRUPTIBLE); + level = rt_spin_lock_irqsave(&(thread->spinlock)); + /* reset the timeout of thread timer and start it */ + if (err == RT_EOK) + { + rt_timer_control(&(thread->thread_timer), RT_TIMER_CTRL_SET_TIME, &tick); + rt_timer_start(&(thread->thread_timer)); + + /* enable interrupt */ + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + rt_hw_local_irq_enable(level_local); + thread->error = -RT_EINTR; + + rt_schedule(); + + /* clear error number of this thread to RT_EOK */ + if (thread->error == -RT_ETIMEOUT) + thread->error = RT_EOK; + } + else + { + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + rt_hw_local_irq_enable(level_local); + } + + return err; +} + +rt_err_t rt_thread_delay(rt_tick_t tick) +{ + return rt_thread_sleep(tick); +} +RTM_EXPORT(rt_thread_delay); + +static void rt_thread_set_suspend_state(struct rt_thread *thread, int suspend_flag) +{ + rt_uint8_t stat = RT_THREAD_SUSPEND_UNINTERRUPTIBLE; + + RT_ASSERT(thread != RT_NULL); + switch (suspend_flag) + { + case RT_INTERRUPTIBLE: + stat = RT_THREAD_SUSPEND_INTERRUPTIBLE; + break; + case RT_KILLABLE: + stat = RT_THREAD_SUSPEND_KILLABLE; + break; + case RT_UNINTERRUPTIBLE: + stat = RT_THREAD_SUSPEND_UNINTERRUPTIBLE; + break; + default: + RT_ASSERT(0); + break; + } + thread->stat = stat | (thread->stat & ~RT_THREAD_STAT_MASK); +} + +rt_err_t rt_thread_suspend_with_flag(rt_thread_t thread, int suspend_flag) +{ + rt_base_t stat; + rt_base_t level; + + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + RT_ASSERT(thread == rt_thread_self()); + + LOG_D("thread suspend: %s", thread->parent.name); + + level = rt_spin_lock_irqsave(&(thread->spinlock)); + + stat = thread->stat & RT_THREAD_STAT_MASK; + if ((stat != RT_THREAD_READY) && (stat != RT_THREAD_RUNNING)) + { + LOG_D("thread suspend: thread disorder, 0x%2x", thread->stat); + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + return -RT_ERROR; + } + + if (stat == RT_THREAD_RUNNING) + { + /* not suspend running status thread on other core */ + RT_ASSERT(thread == rt_thread_self()); + } +#ifdef RT_USING_SMART + if (lwp_thread_signal_suspend_check(thread, suspend_flag) == 0) + { + /* not to suspend */ + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + return -RT_EINTR; + } +#endif + + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + rt_schedule_remove_thread(thread); + level = rt_spin_lock_irqsave(&(thread->spinlock)); + + rt_thread_set_suspend_state(thread, suspend_flag); + + /* stop thread timer anyway */ + rt_timer_stop(&(thread->thread_timer)); + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + + RT_OBJECT_HOOK_CALL(rt_thread_suspend_hook, (thread)); + return RT_EOK; +} +RTM_EXPORT(rt_thread_suspend_with_flag); + +rt_err_t rt_thread_suspend(rt_thread_t thread) +{ + return rt_thread_suspend_with_flag(thread, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_thread_suspend); + +rt_err_t rt_thread_resume(rt_thread_t thread) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + + LOG_D("thread resume: %s", thread->parent.name); + + if ((thread->stat & RT_THREAD_SUSPEND_MASK) != RT_THREAD_SUSPEND_MASK) + { + LOG_D("thread resume: thread disorder, %d", + thread->stat); + + return -RT_ERROR; + } + + level = rt_spin_lock_irqsave(&(thread->spinlock)); //TODO need lock for cpu + + /* remove from suspend list */ + rt_list_remove(&(thread->tlist)); + + rt_timer_stop(&thread->thread_timer); + +#ifdef RT_USING_SMART + thread->wakeup.func = RT_NULL; +#endif + + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + /* insert to schedule ready list */ + rt_schedule_insert_thread(thread); + + RT_OBJECT_HOOK_CALL(rt_thread_resume_hook, (thread)); + return RT_EOK; +} +RTM_EXPORT(rt_thread_resume); + diff --git a/tasks/runtime-rtthread-softtimer-wakeup/symptom_only/src/timer.c b/tasks/runtime-rtthread-softtimer-wakeup/symptom_only/src/timer.c new file mode 100644 index 00000000..f6b7cdd8 --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/symptom_only/src/timer.c @@ -0,0 +1,611 @@ +/* + * Copyright (c) 2006-2022, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +#include +#include + +#define DBG_TAG "kernel.timer" +#define DBG_LVL DBG_INFO +#include + +/* hard timer list */ +static rt_list_t _timer_list[RT_TIMER_SKIP_LIST_LEVEL]; +static struct rt_spinlock _hard_spinlock; + +#ifdef RT_USING_TIMER_SOFT + +#define RT_SOFT_TIMER_IDLE 1 +#define RT_SOFT_TIMER_BUSY 0 + +#ifndef RT_TIMER_THREAD_STACK_SIZE +#define RT_TIMER_THREAD_STACK_SIZE 512 +#endif /* RT_TIMER_THREAD_STACK_SIZE */ + +#ifndef RT_TIMER_THREAD_PRIO +#define RT_TIMER_THREAD_PRIO 0 +#endif /* RT_TIMER_THREAD_PRIO */ + +/* soft timer status */ +static rt_uint8_t _soft_timer_status = RT_SOFT_TIMER_IDLE; +/* soft timer list */ +static rt_list_t _soft_timer_list[RT_TIMER_SKIP_LIST_LEVEL]; +static struct rt_spinlock _soft_spinlock; +static struct rt_thread _timer_thread; +rt_align(RT_ALIGN_SIZE) +static rt_uint8_t _timer_thread_stack[RT_TIMER_THREAD_STACK_SIZE]; +#endif /* RT_USING_TIMER_SOFT */ + +#ifndef __on_rt_object_take_hook + #define __on_rt_object_take_hook(parent) __ON_HOOK_ARGS(rt_object_take_hook, (parent)) +#endif +#ifndef __on_rt_object_put_hook + #define __on_rt_object_put_hook(parent) __ON_HOOK_ARGS(rt_object_put_hook, (parent)) +#endif +#ifndef __on_rt_timer_enter_hook + #define __on_rt_timer_enter_hook(t) __ON_HOOK_ARGS(rt_timer_enter_hook, (t)) +#endif +#ifndef __on_rt_timer_exit_hook + #define __on_rt_timer_exit_hook(t) __ON_HOOK_ARGS(rt_timer_exit_hook, (t)) +#endif + + +static void _timer_init(rt_timer_t timer, + void (*timeout)(void *parameter), + void *parameter, + rt_tick_t time, + rt_uint8_t flag) +{ + int i; + + /* set flag */ + timer->parent.flag = flag; + + /* set deactivated */ + timer->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + + timer->timeout_func = timeout; + timer->parameter = parameter; + + timer->timeout_tick = 0; + timer->init_tick = time; + + /* initialize timer list */ + for (i = 0; i < RT_TIMER_SKIP_LIST_LEVEL; i++) + { + rt_list_init(&(timer->row[i])); + } +} + +static rt_err_t _timer_list_next_timeout(rt_list_t timer_list[], rt_tick_t *timeout_tick) +{ + struct rt_timer *timer; + + if (!rt_list_isempty(&timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1])) + { + timer = rt_list_entry(timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1].next, + struct rt_timer, row[RT_TIMER_SKIP_LIST_LEVEL - 1]); + *timeout_tick = timer->timeout_tick; + return RT_EOK; + } + return -RT_ERROR; +} + +rt_inline void _timer_remove(rt_timer_t timer) +{ + int i; + + for (i = 0; i < RT_TIMER_SKIP_LIST_LEVEL; i++) + { + rt_list_remove(&timer->row[i]); + } +} + +void rt_timer_init(rt_timer_t timer, + const char *name, + void (*timeout)(void *parameter), + void *parameter, + rt_tick_t time, + rt_uint8_t flag) +{ + /* parameter check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(timeout != RT_NULL); + RT_ASSERT(time < RT_TICK_MAX / 2); + + /* timer object initialization */ + rt_object_init(&(timer->parent), RT_Object_Class_Timer, name); + + _timer_init(timer, timeout, parameter, time, flag); +} +RTM_EXPORT(rt_timer_init); + +rt_err_t rt_timer_detach(rt_timer_t timer) +{ + rt_base_t level; + struct rt_spinlock *spinlock; + + /* parameter check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(rt_object_get_type(&timer->parent) == RT_Object_Class_Timer); + RT_ASSERT(rt_object_is_systemobject(&timer->parent)); + +#ifdef RT_USING_TIMER_SOFT + if (timer->parent.flag & RT_TIMER_FLAG_SOFT_TIMER) + { + spinlock = &_soft_spinlock; + } + else +#endif /* RT_USING_TIMER_SOFT */ + { + spinlock = &_hard_spinlock; + } + + level = rt_spin_lock_irqsave(spinlock); + + _timer_remove(timer); + /* stop timer */ + timer->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + + rt_spin_unlock_irqrestore(spinlock, level); + rt_object_detach(&(timer->parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_timer_detach); + +static rt_err_t _timer_start(rt_list_t *timer_list, rt_timer_t timer) +{ + unsigned int row_lvl; + rt_list_t *row_head[RT_TIMER_SKIP_LIST_LEVEL]; + unsigned int tst_nr; + static unsigned int random_nr; + + /* remove timer from list */ + _timer_remove(timer); + /* change status of timer */ + timer->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(timer->parent))); + + timer->timeout_tick = rt_tick_get() + timer->init_tick; + + row_head[0] = &timer_list[0]; + for (row_lvl = 0; row_lvl < RT_TIMER_SKIP_LIST_LEVEL; row_lvl++) + { + for (; row_head[row_lvl] != timer_list[row_lvl].prev; + row_head[row_lvl] = row_head[row_lvl]->next) + { + struct rt_timer *t; + rt_list_t *p = row_head[row_lvl]->next; + + /* fix up the entry pointer */ + t = rt_list_entry(p, struct rt_timer, row[row_lvl]); + + /* If we have two timers that timeout at the same time, it's + * preferred that the timer inserted early get called early. + * So insert the new timer to the end the the some-timeout timer + * list. + */ + if ((t->timeout_tick - timer->timeout_tick) == 0) + { + continue; + } + else if ((t->timeout_tick - timer->timeout_tick) < RT_TICK_MAX / 2) + { + break; + } + } + if (row_lvl != RT_TIMER_SKIP_LIST_LEVEL - 1) + row_head[row_lvl + 1] = row_head[row_lvl] + 1; + } + + /* Interestingly, this super simple timer insert counter works very very + * well on distributing the list height uniformly. By means of "very very + * well", I mean it beats the randomness of timer->timeout_tick very easily + * (actually, the timeout_tick is not random and easy to be attacked). */ + random_nr++; + tst_nr = random_nr; + + rt_list_insert_after(row_head[RT_TIMER_SKIP_LIST_LEVEL - 1], + &(timer->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + for (row_lvl = 2; row_lvl <= RT_TIMER_SKIP_LIST_LEVEL; row_lvl++) + { + if (!(tst_nr & RT_TIMER_SKIP_LIST_MASK)) + rt_list_insert_after(row_head[RT_TIMER_SKIP_LIST_LEVEL - row_lvl], + &(timer->row[RT_TIMER_SKIP_LIST_LEVEL - row_lvl])); + else + break; + /* Shift over the bits we have tested. Works well with 1 bit and 2 + * bits. */ + tst_nr >>= (RT_TIMER_SKIP_LIST_MASK + 1) >> 1; + } + + timer->parent.flag |= RT_TIMER_FLAG_ACTIVATED; + +#ifdef RT_USING_TIMER_SOFT + if (timer->parent.flag & RT_TIMER_FLAG_SOFT_TIMER) + { + /* check whether timer thread is ready */ + if ((_soft_timer_status == RT_SOFT_TIMER_IDLE) && + ((_timer_thread.stat & RT_THREAD_SUSPEND_MASK) == RT_THREAD_SUSPEND_MASK)) + { + /* resume timer thread to check soft timer */ + rt_thread_resume(&_timer_thread); + } + } +#endif /* RT_USING_TIMER_SOFT */ + + return RT_EOK; +} + +rt_err_t rt_timer_start(rt_timer_t timer) +{ + struct rt_spinlock *spinlock; + rt_list_t *timer_list; + rt_base_t level; + rt_err_t err; + + /* parameter check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(rt_object_get_type(&timer->parent) == RT_Object_Class_Timer); + +#ifdef RT_USING_TIMER_SOFT + if (timer->parent.flag & RT_TIMER_FLAG_SOFT_TIMER) + { + timer_list = _soft_timer_list; + spinlock = &_soft_spinlock; + } + else +#endif /* RT_USING_TIMER_SOFT */ + { + timer_list = _timer_list; + spinlock = &_hard_spinlock; + } + + /* stop timer firstly */ + level = rt_spin_lock_irqsave(spinlock); + err = _timer_start(timer_list, timer); + rt_spin_unlock_irqrestore(spinlock, level); + + return err; +} +RTM_EXPORT(rt_timer_start); + +rt_err_t rt_timer_stop(rt_timer_t timer) +{ + rt_base_t level; + struct rt_spinlock *spinlock; + + /* timer check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(rt_object_get_type(&timer->parent) == RT_Object_Class_Timer); + +#ifdef RT_USING_TIMER_SOFT + if (timer->parent.flag & RT_TIMER_FLAG_SOFT_TIMER) + { + spinlock = &_soft_spinlock; + } + else +#endif /* RT_USING_TIMER_SOFT */ + { + spinlock = &_hard_spinlock; + } + level = rt_spin_lock_irqsave(spinlock); + + if (!(timer->parent.flag & RT_TIMER_FLAG_ACTIVATED)) + { + rt_spin_unlock_irqrestore(spinlock, level); + return -RT_ERROR; + } + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(timer->parent))); + + _timer_remove(timer); + /* change status */ + timer->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + rt_spin_unlock_irqrestore(spinlock, level); + + return RT_EOK; +} +RTM_EXPORT(rt_timer_stop); + +rt_err_t rt_timer_control(rt_timer_t timer, int cmd, void *arg) +{ + /* parameter check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(rt_object_get_type(&timer->parent) == RT_Object_Class_Timer); + + switch (cmd) + { + case RT_TIMER_CTRL_GET_TIME: + *(rt_tick_t *)arg = timer->init_tick; + break; + + case RT_TIMER_CTRL_SET_TIME: + RT_ASSERT((*(rt_tick_t *)arg) < RT_TICK_MAX / 2); + timer->init_tick = *(rt_tick_t *)arg; + break; + + case RT_TIMER_CTRL_SET_ONESHOT: + timer->parent.flag &= ~RT_TIMER_FLAG_PERIODIC; + break; + + case RT_TIMER_CTRL_SET_PERIODIC: + timer->parent.flag |= RT_TIMER_FLAG_PERIODIC; + break; + + case RT_TIMER_CTRL_GET_STATE: + if(timer->parent.flag & RT_TIMER_FLAG_ACTIVATED) + { + /*timer is start and run*/ + *(rt_uint32_t *)arg = RT_TIMER_FLAG_ACTIVATED; + } + else + { + /*timer is stop*/ + *(rt_uint32_t *)arg = RT_TIMER_FLAG_DEACTIVATED; + } + break; + + case RT_TIMER_CTRL_GET_REMAIN_TIME: + *(rt_tick_t *)arg = timer->timeout_tick; + break; + case RT_TIMER_CTRL_GET_FUNC: + *(void **)arg = (void *)timer->timeout_func; + break; + + case RT_TIMER_CTRL_SET_FUNC: + timer->timeout_func = (void (*)(void*))arg; + break; + + case RT_TIMER_CTRL_GET_PARM: + *(void **)arg = timer->parameter; + break; + + case RT_TIMER_CTRL_SET_PARM: + timer->parameter = arg; + break; + + default: + break; + } + + return RT_EOK; +} +RTM_EXPORT(rt_timer_control); + +void rt_timer_check(void) +{ + struct rt_timer *t; + rt_tick_t current_tick; + rt_base_t level; + rt_list_t list; + +#ifdef RT_USING_SMP + if (rt_hw_cpu_id() != 0) + { + return; + } +#endif + + rt_list_init(&list); + + LOG_D("timer check enter"); + + current_tick = rt_tick_get(); + + level = rt_spin_lock_irqsave(&_hard_spinlock); + + while (!rt_list_isempty(&_timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1])) + { + t = rt_list_entry(_timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1].next, + struct rt_timer, row[RT_TIMER_SKIP_LIST_LEVEL - 1]); + + /* + * It supposes that the new tick shall less than the half duration of + * tick max. + */ + if ((current_tick - t->timeout_tick) < RT_TICK_MAX / 2) + { + RT_OBJECT_HOOK_CALL(rt_timer_enter_hook, (t)); + + /* remove timer from timer list firstly */ + _timer_remove(t); + if (!(t->parent.flag & RT_TIMER_FLAG_PERIODIC)) + { + t->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + } + /* add timer to temporary list */ + rt_list_insert_after(&list, &(t->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + rt_spin_unlock_irqrestore(&_hard_spinlock, level); + /* call timeout function */ + t->timeout_func(t->parameter); + + /* re-get tick */ + current_tick = rt_tick_get(); + + RT_OBJECT_HOOK_CALL(rt_timer_exit_hook, (t)); + LOG_D("current tick: %d", current_tick); + level = rt_spin_lock_irqsave(&_hard_spinlock); + /* Check whether the timer object is detached or started again */ + if (rt_list_isempty(&list)) + { + continue; + } + rt_list_remove(&(t->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + if ((t->parent.flag & RT_TIMER_FLAG_PERIODIC) && + (t->parent.flag & RT_TIMER_FLAG_ACTIVATED)) + { + /* start it */ + t->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + _timer_start(_timer_list, t); + } + } + else break; + } + rt_spin_unlock_irqrestore(&_hard_spinlock, level); + LOG_D("timer check leave"); +} + +rt_tick_t rt_timer_next_timeout_tick(void) +{ + rt_base_t level; + rt_tick_t next_timeout = RT_TICK_MAX; + + level = rt_spin_lock_irqsave(&_hard_spinlock); + _timer_list_next_timeout(_timer_list, &next_timeout); + rt_spin_unlock_irqrestore(&_hard_spinlock, level); + + return next_timeout; +} + +void rt_soft_timer_check(void) +{ + rt_tick_t current_tick; + struct rt_timer *t; + rt_base_t level; + rt_list_t list; + + rt_list_init(&list); + LOG_D("software timer check enter"); + level = rt_spin_lock_irqsave(&_soft_spinlock); + + while (!rt_list_isempty(&_soft_timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1])) + { + t = rt_list_entry(_soft_timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1].next, + struct rt_timer, row[RT_TIMER_SKIP_LIST_LEVEL - 1]); + + current_tick = rt_tick_get(); + + /* + * It supposes that the new tick shall less than the half duration of + * tick max. + */ + if ((current_tick - t->timeout_tick) < RT_TICK_MAX / 2) + { + RT_OBJECT_HOOK_CALL(rt_timer_enter_hook, (t)); + + /* remove timer from timer list firstly */ + _timer_remove(t); + if (!(t->parent.flag & RT_TIMER_FLAG_PERIODIC)) + { + t->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + } + /* add timer to temporary list */ + rt_list_insert_after(&list, &(t->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + + _soft_timer_status = RT_SOFT_TIMER_BUSY; + + rt_spin_unlock_irqrestore(&_soft_spinlock, level); + + /* call timeout function */ + t->timeout_func(t->parameter); + + RT_OBJECT_HOOK_CALL(rt_timer_exit_hook, (t)); + LOG_D("current tick: %d", current_tick); + + level = rt_spin_lock_irqsave(&_soft_spinlock); + + _soft_timer_status = RT_SOFT_TIMER_IDLE; + /* Check whether the timer object is detached or started again */ + if (rt_list_isempty(&list)) + { + continue; + } + rt_list_remove(&(t->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + if ((t->parent.flag & RT_TIMER_FLAG_PERIODIC) && + (t->parent.flag & RT_TIMER_FLAG_ACTIVATED)) + { + /* start it */ + t->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + _timer_start(_soft_timer_list, t); + } + } + else break; /* not check anymore */ + } + + rt_spin_unlock_irqrestore(&_soft_spinlock, level); + + LOG_D("software timer check leave"); +} + +static void _timer_thread_entry(void *parameter) +{ + rt_err_t ret = RT_ERROR; + rt_tick_t next_timeout; + rt_base_t level; + + while (1) + { + /* get the next timeout tick */ + level = rt_spin_lock_irqsave(&_soft_spinlock); + ret = _timer_list_next_timeout(_soft_timer_list, &next_timeout); + rt_spin_unlock_irqrestore(&_soft_spinlock, level); + + if (ret != RT_EOK) + { + /* no software timer exist, suspend self. */ + rt_thread_delay(1); + } + else + { + rt_tick_t current_tick; + + /* get current tick */ + current_tick = rt_tick_get(); + + if ((next_timeout - current_tick) < RT_TICK_MAX / 2) + { + /* get the delta timeout tick */ + next_timeout = next_timeout - current_tick; + rt_thread_delay(next_timeout); + } + } + + /* check software timer */ + rt_soft_timer_check(); + } +} + +void rt_system_timer_init(void) +{ + rt_size_t i; + + for (i = 0; i < sizeof(_timer_list) / sizeof(_timer_list[0]); i++) + { + rt_list_init(_timer_list + i); + } + rt_spin_lock_init(&_hard_spinlock); +} + +void rt_system_timer_thread_init(void) +{ +#ifdef RT_USING_TIMER_SOFT + int i; + + for (i = 0; + i < sizeof(_soft_timer_list) / sizeof(_soft_timer_list[0]); + i++) + { + rt_list_init(_soft_timer_list + i); + } + rt_spin_lock_init(&_soft_spinlock); + + /* start software timer thread */ + rt_thread_init(&_timer_thread, + "timer", + _timer_thread_entry, + RT_NULL, + &_timer_thread_stack[0], + sizeof(_timer_thread_stack), + RT_TIMER_THREAD_PRIO, + 10); + + /* startup */ + rt_thread_startup(&_timer_thread); +#endif /* RT_USING_TIMER_SOFT */ +} + diff --git a/tasks/runtime-rtthread-softtimer-wakeup/task.json b/tasks/runtime-rtthread-softtimer-wakeup/task.json new file mode 100644 index 00000000..b9b38160 --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/task.json @@ -0,0 +1,31 @@ +{ + "id": "runtime-rtthread-softtimer-wakeup", + "version": "1", + "family": "state-machine-timing", + "source": "oss/RT-Thread/rt-thread@20a4d0939a52", + "split_group": "RT-Thread/rt-thread", + "language": "c", + "template": "template", + "candidate_files": [ + "src/timer.c", + "src/thread.c" + ], + "verifier": "verify.py", + "grader_files": [ + "check.py", + "support.tar", + "observations.c" + ], + "timeout_seconds": 60, + "fixtures": { + "gold": "PASS", + "template": "FAIL", + "noop": "FAIL", + "cheat": "FAIL", + "cheat_read_grader": "FAIL", + "symptom_only": "FAIL", + "timer_only": "FAIL", + "resume_only": "FAIL", + "valid_atomic_wait": "PASS" + } +} diff --git a/tasks/runtime-rtthread-softtimer-wakeup/template/LICENSE b/tasks/runtime-rtthread-softtimer-wakeup/template/LICENSE new file mode 100644 index 00000000..261eeb9e --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/template/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/tasks/runtime-rtthread-softtimer-wakeup/template/Makefile b/tasks/runtime-rtthread-softtimer-wakeup/template/Makefile new file mode 100644 index 00000000..300a48fb --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/template/Makefile @@ -0,0 +1,15 @@ +CC = gcc +CFLAGS = -std=c11 -O0 -g -D_XOPEN_SOURCE=700 -Iinclude -Iport -ffunction-sections -fdata-sections +SOURCES = src/timer.c src/thread.c src/semaphore.c port/controlled.c +.PHONY: smoke clean +smoke: smoke-bin + ./smoke-bin +smoke-bin: $(SOURCES) smoke.c + $(CC) $(CFLAGS) $(SOURCES) smoke.c -Wl,--gc-sections -o $@ +clean: + rm -f smoke-bin +.PHONY: reproduce +reproduce: reproduce-bin + ./reproduce-bin +reproduce-bin: $(SOURCES) reproduce.c + $(CC) $(CFLAGS) $(SOURCES) reproduce.c -Wl,--gc-sections -o $@ diff --git a/tasks/runtime-rtthread-softtimer-wakeup/template/README.md b/tasks/runtime-rtthread-softtimer-wakeup/template/README.md new file mode 100644 index 00000000..a7889f50 --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/template/README.md @@ -0,0 +1,11 @@ +# 离散时间任务服务 + +这里保留 RT-Thread 的静态定时器、线程生命周期及信号量相关实现,使用 Linux 上的受控移植层运行,不需要板卡或真实时间。 + +构建和正常路径自测:`make smoke`。输出应为 `before=0`、`after=3`。 + +现场重放:`make reproduce`。它依次给予两个应用任务运行机会,并打印回调发生的 tick。 + +完整交付行为见 [docs/service-contract.md](docs/service-contract.md)。保持现有接口和构建方式;支持代码提供时钟、通用调度与锁操作边界,业务行为由内核源码实现。 + +最终只提交并评分 `src/timer.c`、`src/thread.c`。新增文件和对其他文件的修改不会被收集。可以采用符合公开合同的实现方式。 diff --git a/tasks/runtime-rtthread-softtimer-wakeup/template/docs/service-contract.md b/tasks/runtime-rtthread-softtimer-wakeup/template/docs/service-contract.md new file mode 100644 index 00000000..1d97e3f3 --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/template/docs/service-contract.md @@ -0,0 +1,27 @@ +# 定时器与线程服务 + +本摘录依据工作区所用版本的 RT-Thread《Clock Management》《Thread Management》和相应公开接口注释整理。移植层提供离散 tick 和可重放的线程调度,时间不会自行流逝。 + +R01. 定时器以 tick 为单位。初始化后处于未启动状态;本工作区使用静态定时器,延迟范围为 0 到 RT_TICK_MAX/2-1,周期定时器的周期大于 0。 + +R02. rt_timer_start 成功返回 RT_EOK,将对象设为活动状态,以当前 tick 加配置时长作为截止时间。再次启动会替换该对象原有的排期,每个对象只保留一次有效排期。 + +R03. 软件定时器的回调在系统定时器线程上下文执行。回调不得早于截止时间;到期且服务线程获得运行机会时,回调应得到处理。所有已成功启动的对象均遵守这项约定,已有对象和服务的当前状态不改变其他对象的截止时间。 + +R04. 一次定时器只回调一次,然后不再活动。同一截止时间的对象按最近一次启动的先后顺序处理。 + +R05. 周期定时器在到期后继续活动,下一次截止时间为本次处理时的当前 tick 加配置周期,不补发已错过的周期。回调可以停止自身;已停止的周期定时器不再重新排期。 + +R06. rt_timer_stop 将活动对象从排期中移除并返回 RT_EOK;对已经不活动的对象返回 -RT_ERROR。停止后的对象不会因旧排期而回调,仍可再次启动。 + +R07. RT_TIMER_CTRL_SET_TIME 设置下一次启动使用的时长,不单独重新启动对象。RT_TIMER_CTRL_GET_TIME 返回配置时长;RT_TIMER_CTRL_GET_STATE 返回 RT_TIMER_FLAG_ACTIVATED 或 RT_TIMER_FLAG_DEACTIVATED。 + +R08. rt_thread_resume 将挂起线程重新放入就绪队列并返回 RT_EOK;非挂起线程返回 -RT_ERROR,原状态和就绪队列保持有效。线程被恢复后,不再受恢复前的线程等待超时影响。 + +R09. 同一线程上的恢复调用应等价于某个串行执行次序;同一挂起阶段只发生一次成功的恢复,就绪队列中同一线程只占一个位置。 + +R10. 本工作区的移植接口见 port/controlled.h。port_pump 给予就绪的定时器线程运行机会,直到该线程挂起;port_advance 设置当前 tick、执行系统硬定时器检查,再给予服务线程运行机会。移植层不自行扫描软件定时器或为其生成通知。 + +R11. port_capture_lock 记录下一次锁获取所用的地址。port_after_unlock 与 port_before_lock 在指定锁的下一次释放后或获取前执行一次应用侧回调,回调执行时该锁未被持有。它们用于重放另一执行主体在内核操作边界发起的公开接口调用,不表示流逝了额外 tick。 + +R12. 持续占用处理器而不挂起的线程不能完成一次 port_pump。移植层为操作数量设置有限上限,以结束无法交还控制权的运行。 diff --git a/tasks/runtime-rtthread-softtimer-wakeup/template/include/cpuport.h b/tasks/runtime-rtthread-softtimer-wakeup/template/include/cpuport.h new file mode 100644 index 00000000..5d5d6f17 --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/template/include/cpuport.h @@ -0,0 +1,4 @@ +#ifndef CPU_PORT_H +#define CPU_PORT_H +typedef unsigned long rt_hw_spinlock_t; +#endif diff --git a/tasks/runtime-rtthread-softtimer-wakeup/template/include/rtatomic.h b/tasks/runtime-rtthread-softtimer-wakeup/template/include/rtatomic.h new file mode 100644 index 00000000..c74d75c2 --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/template/include/rtatomic.h @@ -0,0 +1,231 @@ +/* + * Copyright (c) 2006-2023, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + */ +#ifndef __RT_ATOMIC_H__ +#define __RT_ATOMIC_H__ + +#include + +#if !defined(__cplusplus) + +rt_atomic_t rt_hw_atomic_load(volatile rt_atomic_t *ptr); +void rt_hw_atomic_store(volatile rt_atomic_t *ptr, rt_atomic_t val); +rt_atomic_t rt_hw_atomic_add(volatile rt_atomic_t *ptr, rt_atomic_t val); +rt_atomic_t rt_hw_atomic_sub(volatile rt_atomic_t *ptr, rt_atomic_t val); +rt_atomic_t rt_hw_atomic_and(volatile rt_atomic_t *ptr, rt_atomic_t val); +rt_atomic_t rt_hw_atomic_or(volatile rt_atomic_t *ptr, rt_atomic_t val); +rt_atomic_t rt_hw_atomic_xor(volatile rt_atomic_t *ptr, rt_atomic_t val); +rt_atomic_t rt_hw_atomic_exchange(volatile rt_atomic_t *ptr, rt_atomic_t val); +void rt_hw_atomic_flag_clear(volatile rt_atomic_t *ptr); +rt_atomic_t rt_hw_atomic_flag_test_and_set(volatile rt_atomic_t *ptr); +rt_atomic_t rt_hw_atomic_compare_exchange_strong(volatile rt_atomic_t *ptr, rt_atomic_t *expected, rt_atomic_t desired); + +#if defined(RT_USING_HW_ATOMIC) +#define rt_atomic_load(ptr) rt_hw_atomic_load(ptr) +#define rt_atomic_store(ptr, v) rt_hw_atomic_store(ptr, v) +#define rt_atomic_add(ptr, v) rt_hw_atomic_add(ptr, v) +#define rt_atomic_sub(ptr, v) rt_hw_atomic_sub(ptr, v) +#define rt_atomic_and(ptr, v) rt_hw_atomic_and(ptr, v) +#define rt_atomic_or(ptr, v) rt_hw_atomic_or(ptr, v) +#define rt_atomic_xor(ptr, v) rt_hw_atomic_xor(ptr, v) +#define rt_atomic_exchange(ptr, v) rt_hw_atomic_exchange(ptr, v) +#define rt_atomic_flag_clear(ptr) rt_hw_atomic_flag_clear(ptr) +#define rt_atomic_flag_test_and_set(ptr) rt_hw_atomic_flag_test_and_set(ptr) +#define rt_atomic_compare_exchange_strong(ptr, v,des) rt_hw_atomic_compare_exchange_strong(ptr, v ,des) + +#elif defined(RT_USING_STDC_ATOMIC) + +#ifndef __STDC_NO_ATOMICS__ +#define rt_atomic_load(ptr) atomic_load(ptr) +#define rt_atomic_store(ptr, v) atomic_store(ptr, v) +#define rt_atomic_add(ptr, v) atomic_fetch_add(ptr, v) +#define rt_atomic_sub(ptr, v) atomic_fetch_sub(ptr, v) +#define rt_atomic_and(ptr, v) atomic_fetch_and(ptr, v) +#define rt_atomic_or(ptr, v) atomic_fetch_or(ptr, v) +#define rt_atomic_xor(ptr, v) atomic_fetch_xor(ptr, v) +#define rt_atomic_exchange(ptr, v) atomic_exchange(ptr, v) +#define rt_atomic_flag_clear(ptr) atomic_flag_clear(ptr) +#define rt_atomic_flag_test_and_set(ptr) atomic_flag_test_and_set(ptr) +#define rt_atomic_compare_exchange_strong(ptr, v,des) atomic_compare_exchange_strong(ptr, v ,des) +#else +#error "The standard library C doesn't support the atomic operation" +#endif /* __STDC_NO_ATOMICS__ */ + +#else +#include +#define rt_atomic_load(ptr) rt_soft_atomic_load(ptr) +#define rt_atomic_store(ptr, v) rt_soft_atomic_store(ptr, v) +#define rt_atomic_add(ptr, v) rt_soft_atomic_add(ptr, v) +#define rt_atomic_sub(ptr, v) rt_soft_atomic_sub(ptr, v) +#define rt_atomic_and(ptr, v) rt_soft_atomic_and(ptr, v) +#define rt_atomic_or(ptr, v) rt_soft_atomic_or(ptr, v) +#define rt_atomic_xor(ptr, v) rt_soft_atomic_xor(ptr, v) +#define rt_atomic_exchange(ptr, v) rt_soft_atomic_exchange(ptr, v) +#define rt_atomic_flag_clear(ptr) rt_soft_atomic_flag_clear(ptr) +#define rt_atomic_flag_test_and_set(ptr) rt_soft_atomic_flag_test_and_set(ptr) +#define rt_atomic_compare_exchange_strong(ptr, v,des) rt_soft_atomic_compare_exchange_strong(ptr, v ,des) + +rt_inline rt_atomic_t rt_soft_atomic_exchange(volatile rt_atomic_t *ptr, rt_atomic_t val) +{ + rt_base_t level; + rt_atomic_t temp; + level = rt_hw_interrupt_disable(); + temp = *ptr; + *ptr = val; + rt_hw_interrupt_enable(level); + return temp; +} + +rt_inline rt_atomic_t rt_soft_atomic_add(volatile rt_atomic_t *ptr, rt_atomic_t val) +{ + rt_base_t level; + rt_atomic_t temp; + level = rt_hw_interrupt_disable(); + temp = *ptr; + *ptr += val; + rt_hw_interrupt_enable(level); + return temp; +} + +rt_inline rt_atomic_t rt_soft_atomic_sub(volatile rt_atomic_t *ptr, rt_atomic_t val) +{ + rt_base_t level; + rt_atomic_t temp; + level = rt_hw_interrupt_disable(); + temp = *ptr; + *ptr -= val; + rt_hw_interrupt_enable(level); + return temp; +} + +rt_inline rt_atomic_t rt_soft_atomic_xor(volatile rt_atomic_t *ptr, rt_atomic_t val) +{ + rt_base_t level; + rt_atomic_t temp; + level = rt_hw_interrupt_disable(); + temp = *ptr; + *ptr = (*ptr) ^ val; + rt_hw_interrupt_enable(level); + return temp; +} + +rt_inline rt_atomic_t rt_soft_atomic_and(volatile rt_atomic_t *ptr, rt_atomic_t val) +{ + rt_base_t level; + rt_atomic_t temp; + level = rt_hw_interrupt_disable(); + temp = *ptr; + *ptr = (*ptr) & val; + rt_hw_interrupt_enable(level); + return temp; +} + +rt_inline rt_atomic_t rt_soft_atomic_or(volatile rt_atomic_t *ptr, rt_atomic_t val) +{ + rt_base_t level; + rt_atomic_t temp; + level = rt_hw_interrupt_disable(); + temp = *ptr; + *ptr = (*ptr) | val; + rt_hw_interrupt_enable(level); + return temp; +} + +rt_inline rt_atomic_t rt_soft_atomic_load(volatile rt_atomic_t *ptr) +{ + rt_base_t level; + rt_atomic_t temp; + level = rt_hw_interrupt_disable(); + temp = *ptr; + rt_hw_interrupt_enable(level); + return temp; +} + +rt_inline void rt_soft_atomic_store(volatile rt_atomic_t *ptr, rt_atomic_t val) +{ + rt_base_t level; + level = rt_hw_interrupt_disable(); + *ptr = val; + rt_hw_interrupt_enable(level); +} + +rt_inline rt_atomic_t rt_soft_atomic_flag_test_and_set(volatile rt_atomic_t *ptr) +{ + rt_base_t level; + rt_atomic_t temp; + level = rt_hw_interrupt_disable(); + if (*ptr == 0) + { + temp = 0; + *ptr = 1; + } + else + temp = 1; + rt_hw_interrupt_enable(level); + return temp; +} + +rt_inline void rt_soft_atomic_flag_clear(volatile rt_atomic_t *ptr) +{ + rt_base_t level; + level = rt_hw_interrupt_disable(); + *ptr = 0; + rt_hw_interrupt_enable(level); +} + +rt_inline rt_atomic_t rt_soft_atomic_compare_exchange_strong(volatile rt_atomic_t *ptr1, rt_atomic_t *ptr2, + rt_atomic_t desired) +{ + rt_base_t level; + rt_atomic_t temp; + level = rt_hw_interrupt_disable(); + if ((*ptr1) != (*ptr2)) + { + *ptr2 = *ptr1; + temp = 0; + } + else + { + *ptr1 = desired; + temp = 1; + } + rt_hw_interrupt_enable(level); + return temp; +} +#endif /* RT_USING_STDC_ATOMIC */ + +rt_inline rt_bool_t rt_atomic_dec_and_test(volatile rt_atomic_t *ptr) +{ + return rt_atomic_sub(ptr, 1) == 0; +} + +rt_inline rt_atomic_t rt_atomic_fetch_add_unless(volatile rt_atomic_t *ptr, rt_atomic_t a, rt_atomic_t u) +{ + rt_atomic_t c = rt_atomic_load(ptr); + + do { + if (c == u) + { + break; + } + } while (!rt_atomic_compare_exchange_strong(ptr, &c, c + a)); + + return c; +} + +rt_inline rt_bool_t rt_atomic_add_unless(volatile rt_atomic_t *ptr, rt_atomic_t a, rt_atomic_t u) +{ + return rt_atomic_fetch_add_unless(ptr, a, u) != u; +} + +rt_inline rt_bool_t rt_atomic_inc_not_zero(volatile rt_atomic_t *ptr) +{ + return rt_atomic_add_unless(ptr, 1, 0); +} + +#endif /* __cplusplus */ + +#endif /* __RT_ATOMIC_H__ */ diff --git a/tasks/runtime-rtthread-softtimer-wakeup/template/include/rtconfig.h b/tasks/runtime-rtthread-softtimer-wakeup/template/include/rtconfig.h new file mode 100644 index 00000000..528e1a52 --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/template/include/rtconfig.h @@ -0,0 +1,19 @@ +#ifndef RT_CONFIG_H +#define RT_CONFIG_H +#define RT_USING_LIBC +#define RT_USING_NANO +#define RT_USING_STDC_ATOMIC +#define RT_USING_SMP +#define RT_CPUS_NR 2 +#define RT_USING_TIMER_SOFT +#define RT_USING_SEMAPHORE +#define RT_NAME_MAX 16 +#define RT_ALIGN_SIZE 8 +#define RT_THREAD_PRIORITY_MAX 32 +#define RT_TIMER_SKIP_LIST_LEVEL 1 +#define RT_TIMER_SKIP_LIST_MASK 1 +#define RT_TICK_PER_SECOND 1000 +#define RT_TIMER_THREAD_STACK_SIZE 65536 +#define RT_TIMER_THREAD_PRIO 4 +#define RT_DEBUG +#endif diff --git a/tasks/runtime-rtthread-softtimer-wakeup/template/include/rtdbg.h b/tasks/runtime-rtthread-softtimer-wakeup/template/include/rtdbg.h new file mode 100644 index 00000000..a79eee1b --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/template/include/rtdbg.h @@ -0,0 +1,192 @@ +/* + * Copyright (c) 2006-2021, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +/* + * The macro definitions for debug + * + * These macros are defined in static. If you want to use debug macro, you can + * use as following code: + * + * In your C/C++ file, enable/disable DEBUG_ENABLE macro, and then include this + * header file. + * + * #define DBG_TAG "MOD_TAG" + * #define DBG_LVL DBG_INFO + * #include // must after of DBG_LVL, DBG_TAG or other options + * + * Then in your C/C++ file, you can use LOG_X macro to print out logs: + * LOG_D("this is a debug log!"); + * LOG_E("this is a error log!"); + */ + +#ifndef RT_DBG_H__ +#define RT_DBG_H__ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* the debug log will force enable when RT_USING_DEBUG macro is defined */ +#if defined(RT_USING_DEBUG) && !defined(DBG_ENABLE) +#define DBG_ENABLE +#endif + +/* it will force output color log when RT_DEBUGING_COLOR macro is defined */ +#if defined(RT_DEBUGING_COLOR) && !defined(DBG_COLOR) +#define DBG_COLOR +#endif + +/* for dlog */ +#ifdef PKG_USING_DLOG +#include +#else +#define DLOG(...) +#endif + +#if defined(RT_USING_ULOG) +/* using ulog compatible with rtdbg */ +#include +#else + +/* DEBUG level */ +#define DBG_ERROR 0 +#define DBG_WARNING 1 +#define DBG_INFO 2 +#define DBG_LOG 3 + +#ifdef DBG_TAG +#ifndef DBG_SECTION_NAME +#define DBG_SECTION_NAME DBG_TAG +#endif +#else +/* compatible with old version */ +#ifndef DBG_SECTION_NAME +#define DBG_SECTION_NAME "DBG" +#endif +#endif /* DBG_TAG */ + +#ifdef DBG_ENABLE + +#ifdef DBG_LVL +#ifndef DBG_LEVEL +#define DBG_LEVEL DBG_LVL +#endif +#else +/* compatible with old version */ +#ifndef DBG_LEVEL +#define DBG_LEVEL DBG_WARNING +#endif +#endif /* DBG_LVL */ + +/* + * The color for terminal (foreground) + * BLACK 30 + * RED 31 + * GREEN 32 + * YELLOW 33 + * BLUE 34 + * PURPLE 35 + * CYAN 36 + * WHITE 37 + */ +#ifdef DBG_COLOR +#define _DBG_COLOR(n) rt_kprintf("\033["#n"m") +#define _DBG_LOG_HDR(lvl_name, color_n) \ + rt_kprintf("\033["#color_n"m[" lvl_name "/" DBG_SECTION_NAME "] ") +#define _DBG_LOG_X_END \ + rt_kprintf("\033[0m\n") +#else +#define _DBG_COLOR(n) +#define _DBG_LOG_HDR(lvl_name, color_n) \ + rt_kprintf("[" lvl_name "/" DBG_SECTION_NAME "] ") +#define _DBG_LOG_X_END \ + rt_kprintf("\n") +#endif /* DBG_COLOR */ + +/* + * static debug routine + * NOTE: This is a NOT RECOMMENDED API. Please using LOG_X API. + * It will be DISCARDED later. Because it will take up more resources. + */ +#define dbg_log(level, fmt, ...) \ + if ((level) <= DBG_LEVEL) \ + { \ + switch(level) \ + { \ + case DBG_ERROR: _DBG_LOG_HDR("E", 31); break; \ + case DBG_WARNING: _DBG_LOG_HDR("W", 33); break; \ + case DBG_INFO: _DBG_LOG_HDR("I", 32); break; \ + case DBG_LOG: _DBG_LOG_HDR("D", 0); break; \ + default: break; \ + } \ + rt_kprintf(fmt, ##__VA_ARGS__); \ + _DBG_COLOR(0); \ + } + +#define dbg_here \ + if ((DBG_LEVEL) <= DBG_LOG){ \ + rt_kprintf(DBG_SECTION_NAME " Here %s:%d\n", \ + __FUNCTION__, __LINE__); \ + } + +#define dbg_log_line(lvl, color_n, fmt, ...) \ + do \ + { \ + _DBG_LOG_HDR(lvl, color_n); \ + rt_kprintf(fmt, ##__VA_ARGS__); \ + _DBG_LOG_X_END; \ + } \ + while (0) + +#define dbg_raw(...) rt_kprintf(__VA_ARGS__); + +#else +#define dbg_log(level, fmt, ...) +#define dbg_here +#define dbg_enter +#define dbg_exit +#define dbg_log_line(lvl, color_n, fmt, ...) +#define dbg_raw(...) +#endif /* DBG_ENABLE */ + +#if (DBG_LEVEL >= DBG_LOG) +#define LOG_D(fmt, ...) dbg_log_line("D", 0, fmt, ##__VA_ARGS__) +#else +#define LOG_D(...) +#endif + +#if (DBG_LEVEL >= DBG_INFO) +#define LOG_I(fmt, ...) dbg_log_line("I", 32, fmt, ##__VA_ARGS__) +#else +#define LOG_I(...) +#endif + +#if (DBG_LEVEL >= DBG_WARNING) +#define LOG_W(fmt, ...) dbg_log_line("W", 33, fmt, ##__VA_ARGS__) +#else +#define LOG_W(...) +#endif + +#if (DBG_LEVEL >= DBG_ERROR) +#define LOG_E(fmt, ...) dbg_log_line("E", 31, fmt, ##__VA_ARGS__) +#else +#define LOG_E(...) +#endif + +#define LOG_RAW(...) dbg_raw(__VA_ARGS__) + +#define LOG_HEX(name, width, buf, size) + +#endif /* defined(RT_USING_ULOG) && define(DBG_ENABLE) */ + +#ifdef __cplusplus +} +#endif + +#endif /* RT_DBG_H__ */ diff --git a/tasks/runtime-rtthread-softtimer-wakeup/template/include/rtdef.h b/tasks/runtime-rtthread-softtimer-wakeup/template/include/rtdef.h new file mode 100644 index 00000000..4e85c169 --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/template/include/rtdef.h @@ -0,0 +1,1432 @@ +/* + * Copyright (c) 2006-2022, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +#ifndef __RT_DEF_H__ +#define __RT_DEF_H__ + +#include + +#include +#include +#include +#ifndef RT_USING_NANO +#include +#include +#if defined(RT_USING_SIGNALS) || defined(RT_USING_SMART) +#include +#endif /* defined(RT_USING_SIGNALS) || defined(RT_USING_SMART) */ +#endif /* RT_USING_NANO */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @addtogroup BasicDef + */ + +/**@{*/ + +/* RT-Thread version information */ +#define RT_VERSION_MAJOR 5 /**< Major version number (X.x.x) */ +#define RT_VERSION_MINOR 1 /**< Minor version number (x.X.x) */ +#define RT_VERSION_PATCH 0 /**< Patch version number (x.x.X) */ + +/* e.g. #if (RTTHREAD_VERSION >= RT_VERSION_CHECK(4, 1, 0) */ +#define RT_VERSION_CHECK(major, minor, revise) ((major * 10000) + (minor * 100) + revise) + +/* RT-Thread version */ +#define RTTHREAD_VERSION RT_VERSION_CHECK(RT_VERSION_MAJOR, RT_VERSION_MINOR, RT_VERSION_PATCH) + + +/* RT-Thread basic data type definitions */ +typedef int rt_bool_t; /**< boolean type */ +typedef signed long rt_base_t; /**< Nbit CPU related date type */ +typedef unsigned long rt_ubase_t; /**< Nbit unsigned CPU related data type */ + +#ifndef RT_USING_ARCH_DATA_TYPE +#ifdef RT_USING_LIBC +typedef int8_t rt_int8_t; /**< 8bit integer type */ +typedef int16_t rt_int16_t; /**< 16bit integer type */ +typedef int32_t rt_int32_t; /**< 32bit integer type */ +typedef uint8_t rt_uint8_t; /**< 8bit unsigned integer type */ +typedef uint16_t rt_uint16_t; /**< 16bit unsigned integer type */ +typedef uint32_t rt_uint32_t; /**< 32bit unsigned integer type */ +typedef int64_t rt_int64_t; /**< 64bit integer type */ +typedef uint64_t rt_uint64_t; /**< 64bit unsigned integer type */ +#else +typedef signed char rt_int8_t; /**< 8bit integer type */ +typedef signed short rt_int16_t; /**< 16bit integer type */ +typedef signed int rt_int32_t; /**< 32bit integer type */ +typedef unsigned char rt_uint8_t; /**< 8bit unsigned integer type */ +typedef unsigned short rt_uint16_t; /**< 16bit unsigned integer type */ +typedef unsigned int rt_uint32_t; /**< 32bit unsigned integer type */ +#ifdef ARCH_CPU_64BIT +typedef signed long rt_int64_t; /**< 64bit integer type */ +typedef unsigned long rt_uint64_t; /**< 64bit unsigned integer type */ +#else +typedef signed long long rt_int64_t; /**< 64bit integer type */ +typedef unsigned long long rt_uint64_t; /**< 64bit unsigned integer type */ +#endif /* ARCH_CPU_64BIT */ +#endif /* RT_USING_LIBC */ +#endif /* RT_USING_ARCH_DATA_TYPE */ + +#if defined(RT_USING_LIBC) && !defined(RT_USING_NANO) +typedef size_t rt_size_t; /**< Type for size number */ +typedef ssize_t rt_ssize_t; /**< Used for a count of bytes or an error indication */ +#else +typedef rt_ubase_t rt_size_t; /**< Type for size number */ +typedef rt_base_t rt_ssize_t; /**< Used for a count of bytes or an error indication */ +#endif /* defined(RT_USING_LIBC) && !defined(RT_USING_NANO) */ + +typedef rt_base_t rt_err_t; /**< Type for error number */ +typedef rt_uint32_t rt_time_t; /**< Type for time stamp */ +typedef rt_uint32_t rt_tick_t; /**< Type for tick count */ +typedef rt_base_t rt_flag_t; /**< Type for flags */ +typedef rt_ubase_t rt_dev_t; /**< Type for device */ +typedef rt_base_t rt_off_t; /**< Type for offset */ + +#ifdef __cplusplus + typedef rt_base_t rt_atomic_t; +#else +#if defined(RT_USING_HW_ATOMIC) + typedef rt_base_t rt_atomic_t; +#elif defined(RT_USING_STDC_ATOMIC) + #include + typedef atomic_size_t rt_atomic_t; +#else + typedef rt_base_t rt_atomic_t; +#endif /* RT_USING_STDC_ATOMIC */ +#endif /* __cplusplus */ + +/* boolean type definitions */ +#define RT_TRUE 1 /**< boolean true */ +#define RT_FALSE 0 /**< boolean fails */ + +/* null pointer definition */ +#define RT_NULL 0 + +/**@}*/ + +/* maximum value of base type */ +#ifdef RT_USING_LIBC +#define RT_UINT8_MAX UINT8_MAX /**< Maximum number of UINT8 */ +#define RT_UINT16_MAX UINT16_MAX /**< Maximum number of UINT16 */ +#define RT_UINT32_MAX UINT32_MAX /**< Maximum number of UINT32 */ +#define RT_UINT64_MAX UINT64_MAX /**< Maximum number of UINT64 */ +#else +#define RT_UINT8_MAX 0xff /**< Maximum number of UINT8 */ +#define RT_UINT16_MAX 0xffff /**< Maximum number of UINT16 */ +#define RT_UINT32_MAX 0xffffffff /**< Maximum number of UINT32 */ +#define RT_UINT64_MAX 0xffffffffffffffff +#endif /* RT_USING_LIBC */ + +#define RT_TICK_MAX RT_UINT32_MAX /**< Maximum number of tick */ + +/* maximum value of ipc type */ +#define RT_SEM_VALUE_MAX RT_UINT16_MAX /**< Maximum number of semaphore .value */ +#define RT_MUTEX_VALUE_MAX RT_UINT16_MAX /**< Maximum number of mutex .value */ +#define RT_MUTEX_HOLD_MAX RT_UINT8_MAX /**< Maximum number of mutex .hold */ +#define RT_MB_ENTRY_MAX RT_UINT16_MAX /**< Maximum number of mailbox .entry */ +#define RT_MQ_ENTRY_MAX RT_UINT16_MAX /**< Maximum number of message queue .entry */ + +/* Common Utilities */ + +#define RT_UNUSED(x) ((void)x) + +/* compile time assertion */ +#define RT_STATIC_ASSERT(name, expn) typedef char _static_assert_##name[(expn)?1:-1] + +/* Compiler Related Definitions */ +#if defined(__ARMCC_VERSION) /* ARM Compiler */ +#define rt_section(x) __attribute__((section(x))) +#define rt_used __attribute__((used)) +#define rt_align(n) __attribute__((aligned(n))) +#define rt_weak __attribute__((weak)) +#define rt_inline static __inline +#define rt_always_inline rt_inline +/* module compiling */ +#ifdef RT_USING_MODULE +#define RTT_API __declspec(dllimport) +#else +#define RTT_API __declspec(dllexport) +#endif /* RT_USING_MODULE */ +#elif defined (__IAR_SYSTEMS_ICC__) /* for IAR Compiler */ +#define rt_section(x) @ x +#define rt_used __root +#define PRAGMA(x) _Pragma(#x) +#define rt_align(n) PRAGMA(data_alignment=n) +#define rt_weak __weak +#define rt_inline static inline +#define rt_always_inline rt_inline +#define RTT_API +#elif defined (__GNUC__) /* GNU GCC Compiler */ +#ifndef RT_USING_LIBC +/* the version of GNU GCC must be greater than 4.x */ +typedef __builtin_va_list __gnuc_va_list; +typedef __gnuc_va_list va_list; +#define va_start(v,l) __builtin_va_start(v,l) +#define va_end(v) __builtin_va_end(v) +#define va_arg(v,l) __builtin_va_arg(v,l) +#endif /* RT_USING_LIBC */ +#define __RT_STRINGIFY(x...) #x +#define RT_STRINGIFY(x...) __RT_STRINGIFY(x) +#define rt_section(x) __attribute__((section(x))) +#define rt_used __attribute__((used)) +#define rt_align(n) __attribute__((aligned(n))) +#define rt_weak __attribute__((weak)) +#define rt_noreturn __attribute__ ((noreturn)) +#define rt_inline static __inline +#define rt_always_inline static inline __attribute__((always_inline)) +#define RTT_API +#elif defined (__ADSPBLACKFIN__) /* for VisualDSP++ Compiler */ +#define rt_section(x) __attribute__((section(x))) +#define rt_used __attribute__((used)) +#define rt_align(n) __attribute__((aligned(n))) +#define rt_weak __attribute__((weak)) +#define rt_inline static inline +#define rt_always_inline rt_inline +#define RTT_API +#elif defined (_MSC_VER) +#define rt_section(x) +#define rt_used +#define rt_align(n) __declspec(align(n)) +#define rt_weak +#define rt_inline static __inline +#define rt_always_inline rt_inline +#define RTT_API +#elif defined (__TI_COMPILER_VERSION__) +/* The way that TI compiler set section is different from other(at least + * GCC and MDK) compilers. See ARM Optimizing C/C++ Compiler 5.9.3 for more + * details. */ +#define rt_section(x) __attribute__((section(x))) +#ifdef __TI_EABI__ +#define rt_used __attribute__((retain)) __attribute__((used)) +#else +#define rt_used __attribute__((used)) +#endif +#define PRAGMA(x) _Pragma(#x) +#define rt_align(n) __attribute__((aligned(n))) +#ifdef __TI_EABI__ +#define rt_weak __attribute__((weak)) +#else +#define rt_weak +#endif +#define rt_inline static inline +#define rt_always_inline rt_inline +#define RTT_API +#elif defined (__TASKING__) +#define rt_section(x) __attribute__((section(x))) +#define rt_used __attribute__((used, protect)) +#define PRAGMA(x) _Pragma(#x) +#define rt_align(n) __attribute__((__align(n))) +#define rt_weak __attribute__((weak)) +#define rt_inline static inline +#define rt_always_inline rt_inline +#define RTT_API +#else + #error not supported tool chain +#endif /* __ARMCC_VERSION */ + +/* initialization export */ +#ifdef RT_USING_COMPONENTS_INIT +typedef int (*init_fn_t)(void); +#ifdef _MSC_VER +#pragma section("rti_fn$f",read) + #ifdef RT_DEBUGING_AUTO_INIT + struct rt_init_desc + { + const char* level; + const init_fn_t fn; + const char* fn_name; + }; + #define INIT_EXPORT(fn, level) \ + const char __rti_level_##fn[] = ".rti_fn." level; \ + const char __rti_##fn##_name[] = #fn; \ + __declspec(allocate("rti_fn$f")) \ + rt_used const struct rt_init_desc __rt_init_msc_##fn = \ + {__rti_level_##fn, fn, __rti_##fn##_name}; + #else + struct rt_init_desc + { + const char* level; + const init_fn_t fn; + }; + #define INIT_EXPORT(fn, level) \ + const char __rti_level_##fn[] = ".rti_fn." level; \ + __declspec(allocate("rti_fn$f")) \ + rt_used const struct rt_init_desc __rt_init_msc_##fn = \ + {__rti_level_##fn, fn }; + #endif /* RT_DEBUGING_AUTO_INIT */ +#else + #ifdef RT_DEBUGING_AUTO_INIT + struct rt_init_desc + { + const char* fn_name; + const init_fn_t fn; + }; + #define INIT_EXPORT(fn, level) \ + const char __rti_##fn##_name[] = #fn; \ + rt_used const struct rt_init_desc __rt_init_desc_##fn rt_section(".rti_fn." level) = \ + { __rti_##fn##_name, fn}; + #else + #define INIT_EXPORT(fn, level) \ + rt_used const init_fn_t __rt_init_##fn rt_section(".rti_fn." level) = fn + #endif /* RT_DEBUGING_AUTO_INIT */ +#endif +#else +#define INIT_EXPORT(fn, level) +#endif + +/* board init routines will be called in board_init() function */ +#define INIT_BOARD_EXPORT(fn) INIT_EXPORT(fn, "1") + +/* init cpu, memory, interrupt-controller, bus... */ +#define INIT_CORE_EXPORT(fn) INIT_EXPORT(fn, "1.0") +/* init pci/pcie, usb platform driver... */ +#define INIT_FRAMEWORK_EXPORT(fn) INIT_EXPORT(fn, "1.1") +/* init platform, user code... */ +#define INIT_PLATFORM_EXPORT(fn) INIT_EXPORT(fn, "1.2") +/* init sys-timer, clk, pinctrl... */ +#define INIT_SUBSYS_EXPORT(fn) INIT_EXPORT(fn, "1.3") +/* init early drivers */ +#define INIT_DRIVER_EARLY_EXPORT(fn) INIT_EXPORT(fn, "1.4") + +/* pre/device/component/env/app init routines will be called in init_thread */ +/* components pre-initialization (pure software initialization) */ +#define INIT_PREV_EXPORT(fn) INIT_EXPORT(fn, "2") +/* device initialization */ +#define INIT_DEVICE_EXPORT(fn) INIT_EXPORT(fn, "3") +/* components initialization (dfs, lwip, ...) */ +#define INIT_COMPONENT_EXPORT(fn) INIT_EXPORT(fn, "4") +/* environment initialization (mount disk, ...) */ +#define INIT_ENV_EXPORT(fn) INIT_EXPORT(fn, "5") +/* application initialization (rtgui application etc ...) */ +#define INIT_APP_EXPORT(fn) INIT_EXPORT(fn, "6") + +/* init after mount fs */ +#define INIT_FS_EXPORT(fn) INIT_EXPORT(fn, "6.0") +/* init in secondary_cpu_c_start */ +#define INIT_SECONDARY_CPU_EXPORT(fn) INIT_EXPORT(fn, "7") + +#if !defined(RT_USING_FINSH) +/* define these to empty, even if not include finsh.h file */ +#define FINSH_FUNCTION_EXPORT(name, desc) +#define FINSH_FUNCTION_EXPORT_ALIAS(name, alias, desc) + +#define MSH_CMD_EXPORT(command, desc) +#define MSH_CMD_EXPORT_ALIAS(command, alias, desc) +#elif !defined(FINSH_USING_SYMTAB) +#define FINSH_FUNCTION_EXPORT_CMD(name, cmd, desc) +#endif + +/* event length */ +#define RT_EVENT_LENGTH 32 + +/* memory management option */ +#define RT_MM_PAGE_SIZE 4096 +#define RT_MM_PAGE_MASK (RT_MM_PAGE_SIZE - 1) +#define RT_MM_PAGE_BITS 12 + +/* kernel malloc definitions */ +#ifndef RT_KERNEL_MALLOC +#define RT_KERNEL_MALLOC(sz) rt_malloc(sz) +#endif + +#ifndef RT_KERNEL_FREE +#define RT_KERNEL_FREE(ptr) rt_free(ptr) +#endif + +#ifndef RT_KERNEL_REALLOC +#define RT_KERNEL_REALLOC(ptr, size) rt_realloc(ptr, size) +#endif + +/** + * @addtogroup Error + */ + +/**@{*/ + +/* RT-Thread error code definitions */ +#if defined(RT_USING_LIBC) && !defined(RT_USING_NANO) +/* POSIX error code compatible */ +#define RT_EOK 0 /**< There is no error */ +#define RT_ERROR 255 /**< A generic/unknown error happens */ +#define RT_ETIMEOUT ETIMEDOUT /**< Timed out */ +#define RT_EFULL ENOSPC /**< The resource is full */ +#define RT_EEMPTY ENODATA /**< The resource is empty */ +#define RT_ENOMEM ENOMEM /**< No memory */ +#define RT_ENOSYS ENOSYS /**< Function not implemented */ +#define RT_EBUSY EBUSY /**< Busy */ +#define RT_EIO EIO /**< IO error */ +#define RT_EINTR EINTR /**< Interrupted system call */ +#define RT_EINVAL EINVAL /**< Invalid argument */ +#define RT_ENOENT ENOENT /**< No entry */ +#define RT_ENOSPC ENOSPC /**< No space left */ +#define RT_EPERM EPERM /**< Operation not permitted */ +#define RT_EFAULT EFAULT /**< Bad address */ +#define RT_ETRAP 254 /**< Trap event */ +#else +#define RT_EOK 0 /**< There is no error */ +#define RT_ERROR 1 /**< A generic/unknown error happens */ +#define RT_ETIMEOUT 2 /**< Timed out */ +#define RT_EFULL 3 /**< The resource is full */ +#define RT_EEMPTY 4 /**< The resource is empty */ +#define RT_ENOMEM 5 /**< No memory */ +#define RT_ENOSYS 6 /**< Function not implemented */ +#define RT_EBUSY 7 /**< Busy */ +#define RT_EIO 8 /**< IO error */ +#define RT_EINTR 9 /**< Interrupted system call */ +#define RT_EINVAL 10 /**< Invalid argument */ +#define RT_ENOENT 11 /**< No entry */ +#define RT_ENOSPC 12 /**< No space left */ +#define RT_EPERM 13 /**< Operation not permitted */ +#define RT_ETRAP 14 /**< Trap event */ +#define RT_EFAULT 15 /**< Bad address */ +#endif /* defined(RT_USING_LIBC) && !defined(RT_USING_NANO) */ + +/**@}*/ + +/** + * @ingroup BasicDef + * + * @def RT_IS_ALIGN(addr, align) + * Return true(1) or false(0). + * RT_IS_ALIGN(128, 4) is judging whether 128 aligns with 4. + * The result is 1, which means 128 aligns with 4. + * @note If the address is NULL, false(0) will be returned + */ +#define RT_IS_ALIGN(addr, align) ((!(addr & (align - 1))) && (addr != RT_NULL)) + +/** + * @ingroup BasicDef + * + * @def RT_ALIGN(size, align) + * Return the most contiguous size aligned at specified width. RT_ALIGN(13, 4) + * would return 16. + */ +#define RT_ALIGN(size, align) (((size) + (align) - 1) & ~((align) - 1)) + +/** + * @ingroup BasicDef + * + * @def RT_ALIGN_DOWN(size, align) + * Return the down number of aligned at specified width. RT_ALIGN_DOWN(13, 4) + * would return 12. + */ +#define RT_ALIGN_DOWN(size, align) ((size) & ~((align) - 1)) + +/** + * Double List structure + */ +struct rt_list_node +{ + struct rt_list_node *next; /**< point to next node. */ + struct rt_list_node *prev; /**< point to prev node. */ +}; +typedef struct rt_list_node rt_list_t; /**< Type for lists. */ + +/** + * Single List structure + */ +struct rt_slist_node +{ + struct rt_slist_node *next; /**< point to next node. */ +}; +typedef struct rt_slist_node rt_slist_t; /**< Type for single list. */ + +#ifdef RT_USING_SMP +#include /* for spinlock from arch */ + +struct rt_spinlock +{ + rt_hw_spinlock_t lock; +#if defined(RT_DEBUGING_SPINLOCK) + void *owner; + void *pc; +#endif /* RT_DEBUGING_SPINLOCK */ +}; +typedef struct rt_spinlock rt_spinlock_t; + +#ifndef RT_SPINLOCK_INIT +#define RT_SPINLOCK_INIT {{0}} // default +#endif /* RT_SPINLOCK_INIT */ + +#else +typedef rt_ubase_t rt_spinlock_t; +struct rt_spinlock +{ + rt_spinlock_t lock; +}; +#define RT_SPINLOCK_INIT {0} +#endif /* RT_USING_SMP */ + +#define RT_DEFINE_SPINLOCK(x) struct rt_spinlock x = RT_SPINLOCK_INIT + +/** + * @addtogroup KernelObject + */ + +/**@{*/ + +/* + * kernel object macros + */ +#define RT_OBJECT_FLAG_MODULE 0x80 /**< is module object. */ + +/** + * Base structure of Kernel object + */ +struct rt_object +{ +#if RT_NAME_MAX > 0 + char name[RT_NAME_MAX]; /**< dynamic name of kernel object */ +#else + const char *name; /**< static name of kernel object */ +#endif /* RT_NAME_MAX > 0 */ + rt_uint8_t type; /**< type of kernel object */ + rt_uint8_t flag; /**< flag of kernel object */ + +#ifdef RT_USING_MODULE + void * module_id; /**< id of application module */ +#endif /* RT_USING_MODULE */ + +#ifdef RT_USING_SMART + rt_atomic_t lwp_ref_count; /**< ref count for lwp */ +#endif /* RT_USING_SMART */ + + rt_list_t list; /**< list node of kernel object */ +}; +typedef struct rt_object *rt_object_t; /**< Type for kernel objects. */ + +/** + * The object type can be one of the follows with specific + * macros enabled: + * - Thread + * - Semaphore + * - Mutex + * - Event + * - MailBox + * - MessageQueue + * - MemHeap + * - MemPool + * - Device + * - Timer + * - Module + * - Unknown + * - Static + */ +enum rt_object_class_type +{ + RT_Object_Class_Null = 0x00, /**< The object is not used. */ + RT_Object_Class_Thread = 0x01, /**< The object is a thread. */ + RT_Object_Class_Semaphore = 0x02, /**< The object is a semaphore. */ + RT_Object_Class_Mutex = 0x03, /**< The object is a mutex. */ + RT_Object_Class_Event = 0x04, /**< The object is a event. */ + RT_Object_Class_MailBox = 0x05, /**< The object is a mail box. */ + RT_Object_Class_MessageQueue = 0x06, /**< The object is a message queue. */ + RT_Object_Class_MemHeap = 0x07, /**< The object is a memory heap. */ + RT_Object_Class_MemPool = 0x08, /**< The object is a memory pool. */ + RT_Object_Class_Device = 0x09, /**< The object is a device. */ + RT_Object_Class_Timer = 0x0a, /**< The object is a timer. */ + RT_Object_Class_Module = 0x0b, /**< The object is a module. */ + RT_Object_Class_Memory = 0x0c, /**< The object is a memory. */ + RT_Object_Class_Channel = 0x0d, /**< The object is a channel */ + RT_Object_Class_Custom = 0x0e, /**< The object is a custom object */ + RT_Object_Class_Unknown = 0x0f, /**< The object is unknown. */ + RT_Object_Class_Static = 0x80 /**< The object is a static object. */ +}; + +/** + * The information of the kernel object + */ +struct rt_object_information +{ + enum rt_object_class_type type; /**< object class type */ + rt_list_t object_list; /**< object list */ + rt_size_t object_size; /**< object size */ + struct rt_spinlock spinlock; +}; + +/** + * The hook function call macro + */ +#ifndef RT_USING_HOOK + #define __ON_HOOK_ARGS(__hook, argv) + #define RT_OBJECT_HOOK_CALL(func, argv) +#else + #define RT_OBJECT_HOOK_CALL(func, argv) __on_##func argv + #ifdef RT_HOOK_USING_FUNC_PTR + #define __ON_HOOK_ARGS(__hook, argv) do {if ((__hook) != RT_NULL) __hook argv; } while (0) + #else + #define __ON_HOOK_ARGS(__hook, argv) + #endif /* RT_HOOK_USING_FUNC_PTR */ +#endif /* RT_USING_HOOK */ + +#ifndef __on_rt_interrupt_switch_hook + #define __on_rt_interrupt_switch_hook() __ON_HOOK_ARGS(rt_interrupt_switch_hook, ()) +#endif +#ifndef __on_rt_malloc_hook + #define __on_rt_malloc_hook(addr, size) __ON_HOOK_ARGS(rt_malloc_hook, (addr, size)) +#endif +#ifndef __on_rt_free_hook + #define __on_rt_free_hook(rmem) __ON_HOOK_ARGS(rt_free_hook, (rmem)) +#endif + + +/**@}*/ + +/** + * @addtogroup Clock + */ + +/**@{*/ + +/** + * clock & timer macros + */ +#define RT_TIMER_FLAG_DEACTIVATED 0x0 /**< timer is deactive */ +#define RT_TIMER_FLAG_ACTIVATED 0x1 /**< timer is active */ +#define RT_TIMER_FLAG_ONE_SHOT 0x0 /**< one shot timer */ +#define RT_TIMER_FLAG_PERIODIC 0x2 /**< periodic timer */ + +#define RT_TIMER_FLAG_HARD_TIMER 0x0 /**< hard timer,the timer's callback function will be called in tick isr. */ +#define RT_TIMER_FLAG_SOFT_TIMER 0x4 /**< soft timer,the timer's callback function will be called in timer thread. */ + +#define RT_TIMER_CTRL_SET_TIME 0x0 /**< set timer control command */ +#define RT_TIMER_CTRL_GET_TIME 0x1 /**< get timer control command */ +#define RT_TIMER_CTRL_SET_ONESHOT 0x2 /**< change timer to one shot */ +#define RT_TIMER_CTRL_SET_PERIODIC 0x3 /**< change timer to periodic */ +#define RT_TIMER_CTRL_GET_STATE 0x4 /**< get timer run state active or deactive*/ +#define RT_TIMER_CTRL_GET_REMAIN_TIME 0x5 /**< get the remaining hang time */ +#define RT_TIMER_CTRL_GET_FUNC 0x6 /**< get timer timeout func */ +#define RT_TIMER_CTRL_SET_FUNC 0x7 /**< set timer timeout func */ +#define RT_TIMER_CTRL_GET_PARM 0x8 /**< get timer parameter */ +#define RT_TIMER_CTRL_SET_PARM 0x9 /**< get timer parameter */ + +#ifndef RT_TIMER_SKIP_LIST_LEVEL +#define RT_TIMER_SKIP_LIST_LEVEL 1 +#endif + +/* 1 or 3 */ +#ifndef RT_TIMER_SKIP_LIST_MASK +#define RT_TIMER_SKIP_LIST_MASK 0x3 /**< Timer skips the list mask */ +#endif + +/** + * timer structure + */ +struct rt_timer +{ + struct rt_object parent; /**< inherit from rt_object */ + + rt_list_t row[RT_TIMER_SKIP_LIST_LEVEL]; + + void (*timeout_func)(void *parameter); /**< timeout function */ + void *parameter; /**< timeout function's parameter */ + + rt_tick_t init_tick; /**< timer timeout tick */ + rt_tick_t timeout_tick; /**< timeout tick */ +}; +typedef struct rt_timer *rt_timer_t; + +/**@}*/ + +/** + * @addtogroup Signal + */ +/**@{*/ + +#ifdef RT_USING_SIGNALS +#define RT_SIG_MAX 32 +typedef unsigned long rt_sigset_t; +typedef siginfo_t rt_siginfo_t; +typedef void (*rt_sighandler_t)(int signo); +#endif /* RT_USING_SIGNALS */ +/**@}*/ + +/** + * @addtogroup Thread + */ + +/**@{*/ + +/* + * Thread + */ + +/* + * thread state definitions + */ +#define RT_THREAD_INIT 0x00 /**< Initialized status */ +#define RT_THREAD_CLOSE 0x01 /**< Closed status */ +#define RT_THREAD_READY 0x02 /**< Ready status */ +#define RT_THREAD_RUNNING 0x03 /**< Running status */ + +/* + * for rt_thread_suspend_with_flag() + */ +enum +{ + RT_INTERRUPTIBLE = 0, + RT_KILLABLE, + RT_UNINTERRUPTIBLE, +}; + +#define RT_THREAD_SUSPEND_MASK 0x04 +#define RT_SIGNAL_COMMON_WAKEUP_MASK 0x02 +#define RT_SIGNAL_KILL_WAKEUP_MASK 0x01 + +#define RT_THREAD_SUSPEND_INTERRUPTIBLE (RT_THREAD_SUSPEND_MASK) /**< Suspend interruptable 0x4 */ +#define RT_THREAD_SUSPEND RT_THREAD_SUSPEND_INTERRUPTIBLE +#define RT_THREAD_SUSPEND_KILLABLE (RT_THREAD_SUSPEND_MASK | RT_SIGNAL_COMMON_WAKEUP_MASK) /**< Suspend with killable 0x6 */ +#define RT_THREAD_SUSPEND_UNINTERRUPTIBLE (RT_THREAD_SUSPEND_MASK | RT_SIGNAL_COMMON_WAKEUP_MASK | RT_SIGNAL_KILL_WAKEUP_MASK) /**< Suspend with uninterruptable 0x7 */ +#define RT_THREAD_STAT_MASK 0x07 + +#define RT_THREAD_STAT_YIELD 0x08 /**< indicate whether remaining_tick has been reloaded since last schedule */ +#define RT_THREAD_STAT_YIELD_MASK RT_THREAD_STAT_YIELD + +#define RT_THREAD_STAT_SIGNAL 0x10 /**< task hold signals */ +#define RT_THREAD_STAT_SIGNAL_READY (RT_THREAD_STAT_SIGNAL | RT_THREAD_READY) +#define RT_THREAD_STAT_SIGNAL_WAIT 0x20 /**< task is waiting for signals */ +#define RT_THREAD_STAT_SIGNAL_PENDING 0x40 /**< signals is held and it has not been procressed */ +#define RT_THREAD_STAT_SIGNAL_MASK 0xf0 + +/** + * thread control command definitions + */ +#define RT_THREAD_CTRL_STARTUP 0x00 /**< Startup thread. */ +#define RT_THREAD_CTRL_CLOSE 0x01 /**< Close thread. */ +#define RT_THREAD_CTRL_CHANGE_PRIORITY 0x02 /**< Change thread priority. */ +#define RT_THREAD_CTRL_INFO 0x03 /**< Get thread information. */ +#define RT_THREAD_CTRL_BIND_CPU 0x04 /**< Set thread bind cpu. */ + +#ifdef RT_USING_SMP + +#define RT_CPU_DETACHED RT_CPUS_NR /**< The thread not running on cpu. */ +#define RT_CPU_MASK ((1 << RT_CPUS_NR) - 1) /**< All CPUs mask bit. */ + +#ifndef RT_SCHEDULE_IPI +#define RT_SCHEDULE_IPI 0 +#endif /* RT_SCHEDULE_IPI */ + +#ifndef RT_STOP_IPI +#define RT_STOP_IPI 1 +#endif /* RT_STOP_IPI */ + +struct rt_cpu_usage_stats +{ + rt_uint64_t user; + rt_uint64_t system; + rt_uint64_t irq; + rt_uint64_t idle; +}; +typedef struct rt_cpu_usage_stats *rt_cpu_usage_stats_t; + +/** + * CPUs definitions + * + */ +struct rt_cpu +{ + struct rt_thread *current_thread; + struct rt_thread *idle_thread; + rt_atomic_t irq_nest; + rt_uint8_t irq_switch_flag; + + rt_uint8_t current_priority; + rt_list_t priority_table[RT_THREAD_PRIORITY_MAX]; +#if RT_THREAD_PRIORITY_MAX > 32 + rt_uint32_t priority_group; + rt_uint8_t ready_table[32]; +#else + rt_uint32_t priority_group; +#endif /* RT_THREAD_PRIORITY_MAX > 32 */ + + rt_atomic_t tick; + + struct rt_spinlock spinlock; +#ifdef RT_USING_SMART + struct rt_cpu_usage_stats cpu_stat; +#endif +}; +typedef struct rt_cpu *rt_cpu_t; + +#endif /* RT_USING_SMP */ + +struct rt_thread; + +#ifdef RT_USING_SMART +typedef rt_err_t (*rt_wakeup_func_t)(void *object, struct rt_thread *thread); + +struct rt_wakeup +{ + rt_wakeup_func_t func; + void *user_data; +}; + +#define _LWP_NSIG 64 + +#ifdef ARCH_CPU_64BIT +#define _LWP_NSIG_BPW 64 +#else +#define _LWP_NSIG_BPW 32 +#endif + +#define _LWP_NSIG_WORDS (RT_ALIGN(_LWP_NSIG, _LWP_NSIG_BPW) / _LWP_NSIG_BPW) + +typedef void (*lwp_sighandler_t)(int); +typedef void (*lwp_sigaction_t)(int signo, siginfo_t *info, void *context); + +typedef struct { + unsigned long sig[_LWP_NSIG_WORDS]; +} lwp_sigset_t; + +#if _LWP_NSIG <= 64 +#define lwp_sigmask(signo) ((lwp_sigset_t){.sig = {[0] = ((long)(1u << ((signo)-1)))}}) +#define lwp_sigset_init(mask) ((lwp_sigset_t){.sig = {[0] = (long)(mask)}}) +#endif + +struct lwp_sigaction { + union { + void (*_sa_handler)(int); + void (*_sa_sigaction)(int, siginfo_t *, void *); + } __sa_handler; + lwp_sigset_t sa_mask; + int sa_flags; + void (*sa_restorer)(void); +}; + +typedef struct lwp_siginfo { + rt_list_t node; + + struct { + int signo; + int code; + long value; + + int from_tid; + pid_t from_pid; + } ksiginfo; +} *lwp_siginfo_t; + +typedef struct lwp_sigqueue { + rt_list_t siginfo_list; + lwp_sigset_t sigset_pending; +} *lwp_sigqueue_t; + +struct lwp_thread_signal { + lwp_sigset_t sigset_mask; + struct lwp_sigqueue sig_queue; +}; + +struct rt_user_context +{ + void *sp; + void *pc; + void *flag; + + void *ctx; +}; +#endif + +typedef void (*rt_thread_cleanup_t)(struct rt_thread *tid); + +/** + * Thread structure + */ +struct rt_thread +{ + struct rt_object parent; + rt_list_t tlist; /**< the thread list */ + rt_list_t tlist_schedule; /**< the thread list */ + + /* stack point and entry */ + void *sp; /**< stack point */ + void *entry; /**< entry */ + void *parameter; /**< parameter */ + void *stack_addr; /**< stack address */ + rt_uint32_t stack_size; /**< stack size */ + + /* error code */ + rt_err_t error; /**< error code */ + + rt_uint8_t stat; /**< thread status */ + +#ifdef RT_USING_SMP + rt_uint8_t bind_cpu; /**< thread is bind to cpu */ + rt_uint8_t oncpu; /**< process on cpu */ + + rt_atomic_t cpus_lock_nest; /**< cpus lock count */ + rt_atomic_t critical_lock_nest; /**< critical lock count */ +#endif /*RT_USING_SMP*/ + + /* priority */ + rt_uint8_t current_priority; /**< current priority */ + rt_uint8_t init_priority; /**< initialized priority */ +#if RT_THREAD_PRIORITY_MAX > 32 + rt_uint8_t number; + rt_uint8_t high_mask; +#endif /* RT_THREAD_PRIORITY_MAX > 32 */ + rt_uint32_t number_mask; /**< priority number mask */ + +#ifdef RT_USING_MUTEX + /* object for IPC */ + rt_list_t taken_object_list; + rt_object_t pending_object; +#endif + +#ifdef RT_USING_EVENT + /* thread event */ + rt_uint32_t event_set; + rt_uint8_t event_info; +#endif /* RT_USING_EVENT */ + +#ifdef RT_USING_SIGNALS + rt_sigset_t sig_pending; /**< the pending signals */ + rt_sigset_t sig_mask; /**< the mask bits of signal */ + +#ifndef RT_USING_SMP + void *sig_ret; /**< the return stack pointer from signal */ +#endif /* RT_USING_SMP */ + rt_sighandler_t *sig_vectors; /**< vectors of signal handler */ + void *si_list; /**< the signal infor list */ +#endif /* RT_USING_SIGNALS */ + + rt_atomic_t init_tick; /**< thread's initialized tick */ + rt_atomic_t remaining_tick; /**< remaining tick */ + +#ifdef RT_USING_CPU_USAGE + rt_uint64_t duration_tick; /**< cpu usage tick */ +#endif /* RT_USING_CPU_USAGE */ + +#ifdef RT_USING_PTHREADS + void *pthread_data; /**< the handle of pthread data, adapt 32/64bit */ +#endif /* RT_USING_PTHREADS */ + + struct rt_timer thread_timer; /**< built-in thread timer */ + + rt_thread_cleanup_t cleanup; /**< cleanup function when thread exit */ + + /* light weight process if present */ +#ifdef RT_USING_SMART + void *msg_ret; /**< the return msg */ + + void *lwp; /**< the lwp reference */ + /* for user create */ + void *user_entry; + void *user_stack; + rt_uint32_t user_stack_size; + rt_uint32_t *kernel_sp; /**< kernel stack point */ + rt_list_t sibling; /**< next thread of same process */ + + struct lwp_thread_signal signal; /**< lwp signal for user-space thread */ + struct rt_user_context user_ctx; /**< user space context */ + struct rt_wakeup wakeup; /**< wakeup data */ + int exit_request; /**< pending exit request of thread */ + int tid; /**< thread ID used by process */ + int tid_ref_count; /**< reference of tid */ + void *susp_recycler; /**< suspended recycler on this thread */ + + rt_uint64_t user_time; + rt_uint64_t system_time; + +#ifndef ARCH_MM_MMU + lwp_sighandler_t signal_handler[32]; +#else + int step_exec; + int debug_attach_req; + int debug_ret_user; + int debug_suspend; + struct rt_hw_exp_stack *regs; + void *thread_idr; /** lwp thread indicator */ + int *clear_child_tid; +#endif /* ARCH_MM_MMU */ +#endif /* RT_USING_SMART */ + +#ifdef RT_USING_MEM_PROTECTION + void *mem_regions; +#ifdef RT_USING_HW_STACK_GUARD + void *stack_buf; +#endif +#endif + + rt_atomic_t ref_count; + struct rt_spinlock spinlock; + rt_ubase_t user_data; /**< private user data beyond this thread */ +}; +typedef struct rt_thread *rt_thread_t; + +#ifdef RT_USING_SMART +#define IS_USER_MODE(t) ((t)->user_ctx.ctx == RT_NULL) +#endif /* RT_USING_SMART */ + +/**@}*/ + +#define rt_atomic_inc(v) rt_atomic_add((v), 1) +#define rt_atomic_dec(v) rt_atomic_sub((v), 1) +#define rt_get_thread_struct(object) do { rt_atomic_inc(&(object)->ref_count); } while(0) +#define rt_put_thread_struct(object) do { rt_atomic_dec(&(object)->ref_count); } while(0) + +/** + * @addtogroup IPC + */ + +/**@{*/ + +/** + * IPC flags and control command definitions + */ +#define RT_IPC_FLAG_FIFO 0x00 /**< FIFOed IPC. @ref IPC. */ +#define RT_IPC_FLAG_PRIO 0x01 /**< PRIOed IPC. @ref IPC. */ + +#define RT_IPC_CMD_UNKNOWN 0x00 /**< unknown IPC command */ +#define RT_IPC_CMD_RESET 0x01 /**< reset IPC object */ +#define RT_IPC_CMD_GET_STATE 0x02 /**< get the state of IPC object */ +#define RT_IPC_CMD_SET_VLIMIT 0x03 /**< set max limit value of IPC value */ + +#define RT_WAITING_FOREVER -1 /**< Block forever until get resource. */ +#define RT_WAITING_NO 0 /**< Non-block. */ + +/** + * Base structure of IPC object + */ +struct rt_ipc_object +{ + struct rt_object parent; /**< inherit from rt_object */ + + rt_list_t suspend_thread; /**< threads pended on this resource */ +}; + +#ifdef RT_USING_SEMAPHORE +/** + * Semaphore structure + */ +struct rt_semaphore +{ + struct rt_ipc_object parent; /**< inherit from ipc_object */ + + rt_uint16_t value; /**< value of semaphore. */ + rt_uint16_t max_value; + struct rt_spinlock spinlock; +}; +typedef struct rt_semaphore *rt_sem_t; +#endif /* RT_USING_SEMAPHORE */ + +#ifdef RT_USING_MUTEX +/** + * Mutual exclusion (mutex) structure + */ +struct rt_mutex +{ + struct rt_ipc_object parent; /**< inherit from ipc_object */ + + rt_uint8_t ceiling_priority; /**< the priority ceiling of mutexe */ + rt_uint8_t priority; /**< the maximal priority for pending thread */ + rt_uint8_t hold; /**< numbers of thread hold the mutex */ + rt_uint8_t reserved; /**< reserved field */ + + struct rt_thread *owner; /**< current owner of mutex */ + rt_list_t taken_list; /**< the object list taken by thread */ + struct rt_spinlock spinlock; +}; +typedef struct rt_mutex *rt_mutex_t; +#endif /* RT_USING_MUTEX */ + +#ifdef RT_USING_EVENT +/** + * flag definitions in event + */ +#define RT_EVENT_FLAG_AND 0x01 /**< logic and */ +#define RT_EVENT_FLAG_OR 0x02 /**< logic or */ +#define RT_EVENT_FLAG_CLEAR 0x04 /**< clear flag */ + +/* + * event structure + */ +struct rt_event +{ + struct rt_ipc_object parent; /**< inherit from ipc_object */ + + rt_uint32_t set; /**< event set */ + struct rt_spinlock spinlock; +}; +typedef struct rt_event *rt_event_t; +#endif /* RT_USING_EVENT */ + +#ifdef RT_USING_MAILBOX +/** + * mailbox structure + */ +struct rt_mailbox +{ + struct rt_ipc_object parent; /**< inherit from ipc_object */ + + rt_ubase_t *msg_pool; /**< start address of message buffer */ + + rt_uint16_t size; /**< size of message pool */ + + rt_uint16_t entry; /**< index of messages in msg_pool */ + rt_uint16_t in_offset; /**< input offset of the message buffer */ + rt_uint16_t out_offset; /**< output offset of the message buffer */ + + rt_list_t suspend_sender_thread; /**< sender thread suspended on this mailbox */ + struct rt_spinlock spinlock; +}; +typedef struct rt_mailbox *rt_mailbox_t; +#endif /* RT_USING_MAILBOX */ + +#ifdef RT_USING_MESSAGEQUEUE +/** + * message queue structure + */ +struct rt_messagequeue +{ + struct rt_ipc_object parent; /**< inherit from ipc_object */ + + void *msg_pool; /**< start address of message queue */ + + rt_uint16_t msg_size; /**< message size of each message */ + rt_uint16_t max_msgs; /**< max number of messages */ + + rt_uint16_t entry; /**< index of messages in the queue */ + + void *msg_queue_head; /**< list head */ + void *msg_queue_tail; /**< list tail */ + void *msg_queue_free; /**< pointer indicated the free node of queue */ + + rt_list_t suspend_sender_thread; /**< sender thread suspended on this message queue */ + struct rt_spinlock spinlock; +}; +typedef struct rt_messagequeue *rt_mq_t; +#endif /* RT_USING_MESSAGEQUEUE */ + +/**@}*/ + +/** + * @addtogroup MM + */ + +/**@{*/ + +#ifdef RT_USING_HEAP +/* + * memory structure + */ +struct rt_memory +{ + struct rt_object parent; /**< inherit from rt_object */ + const char * algorithm; /**< Memory management algorithm name */ + rt_ubase_t address; /**< memory start address */ + rt_size_t total; /**< memory size */ + rt_size_t used; /**< size used */ + rt_size_t max; /**< maximum usage */ +}; +typedef struct rt_memory *rt_mem_t; +#endif /* RT_USING_HEAP */ + +/* + * memory management + * heap & partition + */ + +#ifdef RT_USING_SMALL_MEM +typedef rt_mem_t rt_smem_t; +#endif /* RT_USING_SMALL_MEM */ + +#ifdef RT_USING_SLAB +typedef rt_mem_t rt_slab_t; +#endif /* RT_USING_SLAB */ + +#ifdef RT_USING_MEMHEAP +/** + * memory item on the heap + */ +struct rt_memheap_item +{ + rt_uint32_t magic; /**< magic number for memheap */ + struct rt_memheap *pool_ptr; /**< point of pool */ + + struct rt_memheap_item *next; /**< next memheap item */ + struct rt_memheap_item *prev; /**< prev memheap item */ + + struct rt_memheap_item *next_free; /**< next free memheap item */ + struct rt_memheap_item *prev_free; /**< prev free memheap item */ +#ifdef RT_USING_MEMTRACE + rt_uint8_t owner_thread_name[4]; /**< owner thread name */ +#endif /* RT_USING_MEMTRACE */ +}; + +/** + * Base structure of memory heap object + */ +struct rt_memheap +{ + struct rt_object parent; /**< inherit from rt_object */ + + void *start_addr; /**< pool start address and size */ + + rt_size_t pool_size; /**< pool size */ + rt_size_t available_size; /**< available size */ + rt_size_t max_used_size; /**< maximum allocated size */ + + struct rt_memheap_item *block_list; /**< used block list */ + + struct rt_memheap_item *free_list; /**< free block list */ + struct rt_memheap_item free_header; /**< free block list header */ + + struct rt_semaphore lock; /**< semaphore lock */ + rt_bool_t locked; /**< External lock mark */ +}; +#endif /* RT_USING_MEMHEAP */ + +#ifdef RT_USING_MEMPOOL +/** + * Base structure of Memory pool object + */ +struct rt_mempool +{ + struct rt_object parent; /**< inherit from rt_object */ + + void *start_address; /**< memory pool start */ + rt_size_t size; /**< size of memory pool */ + + rt_size_t block_size; /**< size of memory blocks */ + rt_uint8_t *block_list; /**< memory blocks list */ + + rt_size_t block_total_count; /**< numbers of memory block */ + rt_size_t block_free_count; /**< numbers of free memory block */ + + rt_list_t suspend_thread; /**< threads pended on this resource */ + struct rt_spinlock spinlock; +}; +typedef struct rt_mempool *rt_mp_t; +#endif /* RT_USING_MEMPOOL */ + +/**@}*/ + +#ifdef RT_USING_DEVICE +/** + * @addtogroup Device + */ + +/**@{*/ + +/** + * device (I/O) class type + */ +enum rt_device_class_type +{ + RT_Device_Class_Char = 0, /**< character device */ + RT_Device_Class_Block, /**< block device */ + RT_Device_Class_NetIf, /**< net interface */ + RT_Device_Class_MTD, /**< memory device */ + RT_Device_Class_CAN, /**< CAN device */ + RT_Device_Class_RTC, /**< RTC device */ + RT_Device_Class_Sound, /**< Sound device */ + RT_Device_Class_Graphic, /**< Graphic device */ + RT_Device_Class_I2CBUS, /**< I2C bus device */ + RT_Device_Class_USBDevice, /**< USB slave device */ + RT_Device_Class_USBHost, /**< USB host bus */ + RT_Device_Class_USBOTG, /**< USB OTG bus */ + RT_Device_Class_SPIBUS, /**< SPI bus device */ + RT_Device_Class_SPIDevice, /**< SPI device */ + RT_Device_Class_SDIO, /**< SDIO bus device */ + RT_Device_Class_PM, /**< PM pseudo device */ + RT_Device_Class_Pipe, /**< Pipe device */ + RT_Device_Class_Portal, /**< Portal device */ + RT_Device_Class_Timer, /**< Timer device */ + RT_Device_Class_Miscellaneous, /**< Miscellaneous device */ + RT_Device_Class_Sensor, /**< Sensor device */ + RT_Device_Class_Touch, /**< Touch device */ + RT_Device_Class_PHY, /**< PHY device */ + RT_Device_Class_Security, /**< Security device */ + RT_Device_Class_WLAN, /**< WLAN device */ + RT_Device_Class_Pin, /**< Pin device */ + RT_Device_Class_ADC, /**< ADC device */ + RT_Device_Class_DAC, /**< DAC device */ + RT_Device_Class_WDT, /**< WDT device */ + RT_Device_Class_PWM, /**< PWM device */ + RT_Device_Class_Bus, /**< Bus device */ + RT_Device_Class_Unknown /**< unknown device */ +}; + +/** + * device flags definitions + */ +#define RT_DEVICE_FLAG_DEACTIVATE 0x000 /**< device is not not initialized */ + +#define RT_DEVICE_FLAG_RDONLY 0x001 /**< read only */ +#define RT_DEVICE_FLAG_WRONLY 0x002 /**< write only */ +#define RT_DEVICE_FLAG_RDWR 0x003 /**< read and write */ + +#define RT_DEVICE_FLAG_REMOVABLE 0x004 /**< removable device */ +#define RT_DEVICE_FLAG_STANDALONE 0x008 /**< standalone device */ +#define RT_DEVICE_FLAG_ACTIVATED 0x010 /**< device is activated */ +#define RT_DEVICE_FLAG_SUSPENDED 0x020 /**< device is suspended */ +#define RT_DEVICE_FLAG_STREAM 0x040 /**< stream mode */ + +#define RT_DEVICE_FLAG_INT_RX 0x100 /**< INT mode on Rx */ +#define RT_DEVICE_FLAG_DMA_RX 0x200 /**< DMA mode on Rx */ +#define RT_DEVICE_FLAG_INT_TX 0x400 /**< INT mode on Tx */ +#define RT_DEVICE_FLAG_DMA_TX 0x800 /**< DMA mode on Tx */ + +#define RT_DEVICE_OFLAG_CLOSE 0x000 /**< device is closed */ +#define RT_DEVICE_OFLAG_RDONLY 0x001 /**< read only access */ +#define RT_DEVICE_OFLAG_WRONLY 0x002 /**< write only access */ +#define RT_DEVICE_OFLAG_RDWR 0x003 /**< read and write */ +#define RT_DEVICE_OFLAG_OPEN 0x008 /**< device is opened */ +#define RT_DEVICE_OFLAG_MASK 0xf0f /**< mask of open flag */ + +/** + * general device commands + * 0x01 - 0x1F general device control commands + * 0x20 - 0x3F udevice control commands + * 0x40 - special device control commands + */ +#define RT_DEVICE_CTRL_RESUME 0x01 /**< resume device */ +#define RT_DEVICE_CTRL_SUSPEND 0x02 /**< suspend device */ +#define RT_DEVICE_CTRL_CONFIG 0x03 /**< configure device */ +#define RT_DEVICE_CTRL_CLOSE 0x04 /**< close device */ +#define RT_DEVICE_CTRL_NOTIFY_SET 0x05 /**< set notify func */ +#define RT_DEVICE_CTRL_SET_INT 0x06 /**< set interrupt */ +#define RT_DEVICE_CTRL_CLR_INT 0x07 /**< clear interrupt */ +#define RT_DEVICE_CTRL_GET_INT 0x08 /**< get interrupt status */ +#define RT_DEVICE_CTRL_CONSOLE_OFLAG 0x09 /**< get console open flag */ +#define RT_DEVICE_CTRL_MASK 0x1f /**< mask for contrl commands */ + +/** + * device control + */ +#define RT_DEVICE_CTRL_BASE(Type) ((RT_Device_Class_##Type + 1) * 0x100) + +typedef struct rt_device *rt_device_t; + +#ifdef RT_USING_DEVICE_OPS +/** + * operations set for device object + */ +struct rt_device_ops +{ + /* common device interface */ + rt_err_t (*init) (rt_device_t dev); + rt_err_t (*open) (rt_device_t dev, rt_uint16_t oflag); + rt_err_t (*close) (rt_device_t dev); + rt_ssize_t (*read) (rt_device_t dev, rt_off_t pos, void *buffer, rt_size_t size); + rt_ssize_t (*write) (rt_device_t dev, rt_off_t pos, const void *buffer, rt_size_t size); + rt_err_t (*control)(rt_device_t dev, int cmd, void *args); +}; +#endif /* RT_USING_DEVICE_OPS */ + +/** + * WaitQueue structure + */ +struct rt_wqueue +{ + rt_uint32_t flag; + rt_list_t waiting_list; + struct rt_spinlock spinlock; +}; +typedef struct rt_wqueue rt_wqueue_t; + +#ifdef RT_USING_DM +struct rt_driver; +struct rt_bus; +#endif + +/** + * Device structure + */ +struct rt_device +{ + struct rt_object parent; /**< inherit from rt_object */ + +#ifdef RT_USING_DM + struct rt_bus *bus; /**< the bus mounting to */ + rt_list_t node; /**< to mount on bus */ + struct rt_driver *drv; /**< driver for powering the device */ +#ifdef RT_USING_OFW + void *ofw_node; /**< ofw node get from device tree */ +#endif +#endif + + enum rt_device_class_type type; /**< device type */ + rt_uint16_t flag; /**< device flag */ + rt_uint16_t open_flag; /**< device open flag */ + + rt_uint8_t ref_count; /**< reference count */ + rt_uint8_t device_id; /**< 0 - 255 */ + + /* device call back */ + rt_err_t (*rx_indicate)(rt_device_t dev, rt_size_t size); + rt_err_t (*tx_complete)(rt_device_t dev, void *buffer); + +#ifdef RT_USING_DEVICE_OPS + const struct rt_device_ops *ops; +#else + /* common device interface */ + rt_err_t (*init) (rt_device_t dev); + rt_err_t (*open) (rt_device_t dev, rt_uint16_t oflag); + rt_err_t (*close) (rt_device_t dev); + rt_ssize_t (*read) (rt_device_t dev, rt_off_t pos, void *buffer, rt_size_t size); + rt_ssize_t (*write) (rt_device_t dev, rt_off_t pos, const void *buffer, rt_size_t size); + rt_err_t (*control)(rt_device_t dev, int cmd, void *args); +#endif /* RT_USING_DEVICE_OPS */ + +#ifdef RT_USING_POSIX_DEVIO + const struct dfs_file_ops *fops; + struct rt_wqueue wait_queue; +#endif /* RT_USING_POSIX_DEVIO */ + + void *user_data; /**< device private data */ +}; + +/** + * Notify structure + */ +struct rt_device_notify +{ + void (*notify)(rt_device_t dev); + struct rt_device *dev; +}; + +#ifdef RT_USING_SMART +struct rt_channel +{ + struct rt_ipc_object parent; /**< inherit from object */ + struct rt_thread *reply; /**< the thread will be reply */ + struct rt_spinlock slock; /**< spinlock of this channel */ + rt_list_t wait_msg; /**< the wait queue of sender msg */ + rt_list_t wait_thread; /**< the wait queue of sender thread */ + rt_wqueue_t reader_queue; /**< channel poll queue */ + rt_uint8_t stat; /**< the status of this channel */ + rt_ubase_t ref; +}; +typedef struct rt_channel *rt_channel_t; +#endif + +/**@}*/ +#endif /* RT_USING_DEVICE */ + +#ifdef __cplusplus +} +#endif + +#ifdef __cplusplus +/* RT-Thread definitions for C++ */ +namespace rtthread { + +enum TICK_WAIT { + WAIT_NONE = 0, + WAIT_FOREVER = -1, +}; + +} + +#endif /* __cplusplus */ + +#endif /* __RT_DEF_H__ */ diff --git a/tasks/runtime-rtthread-softtimer-wakeup/template/include/rthw.h b/tasks/runtime-rtthread-softtimer-wakeup/template/include/rthw.h new file mode 100644 index 00000000..11159871 --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/template/include/rthw.h @@ -0,0 +1,235 @@ +/* + * Copyright (c) 2006-2021, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +#ifndef __RT_HW_H__ +#define __RT_HW_H__ + +#include + +#if defined (RT_USING_CACHE) || defined(RT_USING_SMP) +#include /* include spinlock, cache ops, etc. */ +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * Some macros define + */ +#ifndef HWREG64 +#define HWREG64(x) (*((volatile rt_uint64_t *)(x))) +#endif +#ifndef HWREG32 +#define HWREG32(x) (*((volatile rt_uint32_t *)(x))) +#endif +#ifndef HWREG16 +#define HWREG16(x) (*((volatile rt_uint16_t *)(x))) +#endif +#ifndef HWREG8 +#define HWREG8(x) (*((volatile rt_uint8_t *)(x))) +#endif + +#ifndef RT_CPU_CACHE_LINE_SZ +#define RT_CPU_CACHE_LINE_SZ 32 +#endif + +enum RT_HW_CACHE_OPS +{ + RT_HW_CACHE_FLUSH = 0x01, + RT_HW_CACHE_INVALIDATE = 0x02, +}; + +/* + * CPU interfaces + */ +#ifdef RT_USING_CACHE + +#ifdef RT_USING_SMART +#include +#endif + +void rt_hw_cpu_icache_enable(void); +void rt_hw_cpu_icache_disable(void); +rt_base_t rt_hw_cpu_icache_status(void); +void rt_hw_cpu_icache_ops(int ops, void* addr, int size); + +void rt_hw_cpu_dcache_enable(void); +void rt_hw_cpu_dcache_disable(void); +rt_base_t rt_hw_cpu_dcache_status(void); +void rt_hw_cpu_dcache_ops(int ops, void* addr, int size); +#else + +/* define cache ops as empty */ +#define rt_hw_cpu_icache_enable(...) +#define rt_hw_cpu_icache_disable(...) +#define rt_hw_cpu_icache_ops(...) +#define rt_hw_cpu_dcache_enable(...) +#define rt_hw_cpu_dcache_disable(...) +#define rt_hw_cpu_dcache_ops(...) + +#define rt_hw_cpu_icache_status(...) 0 +#define rt_hw_cpu_dcache_status(...) 0 + +#endif + +void rt_hw_cpu_reset(void); +void rt_hw_cpu_shutdown(void); + +const char *rt_hw_cpu_arch(void); + +rt_uint8_t *rt_hw_stack_init(void *entry, + void *parameter, + rt_uint8_t *stack_addr, + void *exit); + +#ifdef RT_USING_HW_STACK_GUARD +void rt_hw_stack_guard_init(rt_thread_t thread); +#endif + +/* + * Interrupt handler definition + */ +typedef void (*rt_isr_handler_t)(int vector, void *param); + +struct rt_irq_desc +{ + rt_isr_handler_t handler; + void *param; + +#ifdef RT_USING_INTERRUPT_INFO + char name[RT_NAME_MAX]; + rt_uint32_t counter; +#ifdef RT_USING_SMP + rt_ubase_t cpu_counter[RT_CPUS_NR]; +#endif +#endif +}; + +/* + * Interrupt interfaces + */ +void rt_hw_interrupt_init(void); +void rt_hw_interrupt_mask(int vector); +void rt_hw_interrupt_umask(int vector); +rt_isr_handler_t rt_hw_interrupt_install(int vector, + rt_isr_handler_t handler, + void *param, + const char *name); + +#ifdef RT_USING_SMP +rt_base_t rt_hw_local_irq_disable(); +void rt_hw_local_irq_enable(rt_base_t level); + +rt_base_t rt_cpus_lock(void); +void rt_cpus_unlock(rt_base_t level); + +#define rt_hw_interrupt_disable rt_cpus_lock +#define rt_hw_interrupt_enable rt_cpus_unlock +#else +rt_base_t rt_hw_interrupt_disable(void); +void rt_hw_interrupt_enable(rt_base_t level); + +#define rt_hw_local_irq_disable rt_hw_interrupt_disable +#define rt_hw_local_irq_enable rt_hw_interrupt_enable + +#endif /*RT_USING_SMP*/ +rt_bool_t rt_hw_interrupt_is_disabled(void); + +/* + * Context interfaces + */ +#ifdef RT_USING_SMP +void rt_hw_context_switch(rt_ubase_t from, rt_ubase_t to, struct rt_thread *to_thread); +void rt_hw_context_switch_to(rt_ubase_t to, struct rt_thread *to_thread); +void rt_hw_context_switch_interrupt(void *context, rt_ubase_t from, rt_ubase_t to, struct rt_thread *to_thread); +#else +void rt_hw_context_switch(rt_ubase_t from, rt_ubase_t to); +void rt_hw_context_switch_to(rt_ubase_t to); +void rt_hw_context_switch_interrupt(rt_ubase_t from, rt_ubase_t to, rt_thread_t from_thread, rt_thread_t to_thread); +#endif /*RT_USING_SMP*/ + +/** + * Hardware Layer Backtrace Service + */ +struct rt_hw_backtrace_frame { + rt_base_t fp; + rt_base_t pc; +}; + +rt_err_t rt_hw_backtrace_frame_get(rt_thread_t thread, struct rt_hw_backtrace_frame *frame); + +rt_err_t rt_hw_backtrace_frame_unwind(rt_thread_t thread, struct rt_hw_backtrace_frame *frame); + +void rt_hw_console_output(const char *str); + +void rt_hw_show_memory(rt_uint32_t addr, rt_size_t size); + +/* + * Exception interfaces + */ +void rt_hw_exception_install(rt_err_t (*exception_handle)(void *context)); + +/* + * delay interfaces + */ +void rt_hw_us_delay(rt_uint32_t us); + +int rt_hw_cpu_id(void); + +#if defined(RT_USING_SMP) || defined(RT_USING_AMP) +/** + * ipi function + */ +void rt_hw_ipi_send(int ipi_vector, unsigned int cpu_mask); +#endif + +#ifdef RT_USING_SMP + +void rt_hw_spin_lock_init(rt_hw_spinlock_t *lock); +void rt_hw_spin_lock(rt_hw_spinlock_t *lock); +void rt_hw_spin_unlock(rt_hw_spinlock_t *lock); + +extern rt_hw_spinlock_t _cpus_lock; + +#define __RT_HW_SPIN_LOCK_INITIALIZER(lockname) {0} + +#define __RT_HW_SPIN_LOCK_UNLOCKED(lockname) \ + (rt_hw_spinlock_t) __RT_HW_SPIN_LOCK_INITIALIZER(lockname) + +#define RT_DEFINE_HW_SPINLOCK(x) rt_hw_spinlock_t x = __RT_HW_SPIN_LOCK_UNLOCKED(x) + +/** + * boot secondary cpu + */ +void rt_hw_secondary_cpu_up(void); + +/** + * secondary cpu idle function + */ +void rt_hw_secondary_cpu_idle_exec(void); +#else + +#define RT_DEFINE_HW_SPINLOCK(x) rt_ubase_t x + +#define rt_hw_spin_lock(lock) *(lock) = rt_hw_interrupt_disable() +#define rt_hw_spin_unlock(lock) rt_hw_interrupt_enable(*(lock)) + + +#endif + +#ifndef RT_USING_CACHE +#define rt_hw_isb() +#define rt_hw_dmb() +#define rt_hw_dsb() +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tasks/runtime-rtthread-softtimer-wakeup/template/include/rtm.h b/tasks/runtime-rtthread-softtimer-wakeup/template/include/rtm.h new file mode 100644 index 00000000..7db52feb --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/template/include/rtm.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2006-2021, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +#ifndef __RTM_H__ +#define __RTM_H__ + +#include +#include + +#ifdef RT_USING_MODULE +struct rt_module_symtab +{ + void *addr; + const char *name; +}; + +#if defined(_MSC_VER) +#pragma section("RTMSymTab$f",read) +#define RTM_EXPORT(symbol) \ +__declspec(allocate("RTMSymTab$f"))const char __rtmsym_##symbol##_name[] = "__vs_rtm_"#symbol; +#pragma comment(linker, "/merge:RTMSymTab=mytext") + +#elif defined(__MINGW32__) +#define RTM_EXPORT(symbol) + +#else +#define RTM_EXPORT(symbol) \ +const char __rtmsym_##symbol##_name[] rt_section(".rodata.name") = #symbol; \ +const struct rt_module_symtab __rtmsym_##symbol rt_section("RTMSymTab")= \ +{ \ + (void *)&symbol, \ + __rtmsym_##symbol##_name \ +}; +#endif + +#else +#define RTM_EXPORT(symbol) +#endif + +#endif diff --git a/tasks/runtime-rtthread-softtimer-wakeup/template/include/rtservice.h b/tasks/runtime-rtthread-softtimer-wakeup/template/include/rtservice.h new file mode 100644 index 00000000..28a6aff4 --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/template/include/rtservice.h @@ -0,0 +1,307 @@ +/* + * Copyright (c) 2006-2021, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +#ifndef __RT_SERVICE_H__ +#define __RT_SERVICE_H__ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @addtogroup KernelService + */ + +/**@{*/ + +/** + * rt_container_of - return the start address of struct type, while ptr is the + * member of struct type. + */ +#define rt_container_of(ptr, type, member) \ + ((type *)((char *)(ptr) - (unsigned long)(&((type *)0)->member))) + + +/** + * @brief initialize a list object + */ +#define RT_LIST_OBJECT_INIT(object) { &(object), &(object) } + +/** + * @brief initialize a list + * + * @param l list to be initialized + */ +rt_inline void rt_list_init(rt_list_t *l) +{ + l->next = l->prev = l; +} + +/** + * @brief insert a node after a list + * + * @param l list to insert it + * @param n new node to be inserted + */ +rt_inline void rt_list_insert_after(rt_list_t *l, rt_list_t *n) +{ + l->next->prev = n; + n->next = l->next; + + l->next = n; + n->prev = l; +} + +/** + * @brief insert a node before a list + * + * @param n new node to be inserted + * @param l list to insert it + */ +rt_inline void rt_list_insert_before(rt_list_t *l, rt_list_t *n) +{ + l->prev->next = n; + n->prev = l->prev; + + l->prev = n; + n->next = l; +} + +/** + * @brief remove node from list. + * @param n the node to remove from the list. + */ +rt_inline void rt_list_remove(rt_list_t *n) +{ + n->next->prev = n->prev; + n->prev->next = n->next; + + n->next = n->prev = n; +} + +/** + * @brief tests whether a list is empty + * @param l the list to test. + */ +rt_inline int rt_list_isempty(const rt_list_t *l) +{ + return l->next == l; +} + +/** + * @brief get the list length + * @param l the list to get. + */ +rt_inline unsigned int rt_list_len(const rt_list_t *l) +{ + unsigned int len = 0; + const rt_list_t *p = l; + while (p->next != l) + { + p = p->next; + len ++; + } + + return len; +} + +/** + * @brief get the struct for this entry + * @param node the entry point + * @param type the type of structure + * @param member the name of list in structure + */ +#define rt_list_entry(node, type, member) \ + rt_container_of(node, type, member) + +/** + * rt_list_for_each - iterate over a list + * @param pos the rt_list_t * to use as a loop cursor. + * @param head the head for your list. + */ +#define rt_list_for_each(pos, head) \ + for (pos = (head)->next; pos != (head); pos = pos->next) + +/** + * rt_list_for_each_safe - iterate over a list safe against removal of list entry + * @param pos the rt_list_t * to use as a loop cursor. + * @param n another rt_list_t * to use as temporary storage + * @param head the head for your list. + */ +#define rt_list_for_each_safe(pos, n, head) \ + for (pos = (head)->next, n = pos->next; pos != (head); \ + pos = n, n = pos->next) + +/** + * rt_list_for_each_entry - iterate over list of given type + * @param pos the type * to use as a loop cursor. + * @param head the head for your list. + * @param member the name of the list_struct within the struct. + */ +#define rt_list_for_each_entry(pos, head, member) \ + for (pos = rt_list_entry((head)->next, typeof(*pos), member); \ + &pos->member != (head); \ + pos = rt_list_entry(pos->member.next, typeof(*pos), member)) + +/** + * rt_list_for_each_entry_safe - iterate over list of given type safe against removal of list entry + * @param pos the type * to use as a loop cursor. + * @param n another type * to use as temporary storage + * @param head the head for your list. + * @param member the name of the list_struct within the struct. + */ +#define rt_list_for_each_entry_safe(pos, n, head, member) \ + for (pos = rt_list_entry((head)->next, typeof(*pos), member), \ + n = rt_list_entry(pos->member.next, typeof(*pos), member); \ + &pos->member != (head); \ + pos = n, n = rt_list_entry(n->member.next, typeof(*n), member)) + +/** + * rt_list_first_entry - get the first element from a list + * @param ptr the list head to take the element from. + * @param type the type of the struct this is embedded in. + * @param member the name of the list_struct within the struct. + * + * Note, that list is expected to be not empty. + */ +#define rt_list_first_entry(ptr, type, member) \ + rt_list_entry((ptr)->next, type, member) + +#define RT_SLIST_OBJECT_INIT(object) { RT_NULL } + +/** + * @brief initialize a single list + * + * @param l the single list to be initialized + */ +rt_inline void rt_slist_init(rt_slist_t *l) +{ + l->next = RT_NULL; +} + +rt_inline void rt_slist_append(rt_slist_t *l, rt_slist_t *n) +{ + struct rt_slist_node *node; + + node = l; + while (node->next) node = node->next; + + /* append the node to the tail */ + node->next = n; + n->next = RT_NULL; +} + +rt_inline void rt_slist_insert(rt_slist_t *l, rt_slist_t *n) +{ + n->next = l->next; + l->next = n; +} + +rt_inline unsigned int rt_slist_len(const rt_slist_t *l) +{ + unsigned int len = 0; + const rt_slist_t *list = l->next; + while (list != RT_NULL) + { + list = list->next; + len ++; + } + + return len; +} + +rt_inline rt_slist_t *rt_slist_remove(rt_slist_t *l, rt_slist_t *n) +{ + /* remove slist head */ + struct rt_slist_node *node = l; + while (node->next && node->next != n) node = node->next; + + /* remove node */ + if (node->next != (rt_slist_t *)0) node->next = node->next->next; + + return l; +} + +rt_inline rt_slist_t *rt_slist_first(rt_slist_t *l) +{ + return l->next; +} + +rt_inline rt_slist_t *rt_slist_tail(rt_slist_t *l) +{ + while (l->next) l = l->next; + + return l; +} + +rt_inline rt_slist_t *rt_slist_next(rt_slist_t *n) +{ + return n->next; +} + +rt_inline int rt_slist_isempty(rt_slist_t *l) +{ + return l->next == RT_NULL; +} + +/** + * @brief get the struct for this single list node + * @param node the entry point + * @param type the type of structure + * @param member the name of list in structure + */ +#define rt_slist_entry(node, type, member) \ + rt_container_of(node, type, member) + +/** + * rt_slist_for_each - iterate over a single list + * @param pos the rt_slist_t * to use as a loop cursor. + * @param head the head for your single list. + */ +#define rt_slist_for_each(pos, head) \ + for (pos = (head)->next; pos != RT_NULL; pos = pos->next) + +/** + * rt_slist_for_each_entry - iterate over single list of given type + * @param pos the type * to use as a loop cursor. + * @param head the head for your single list. + * @param member the name of the list_struct within the struct. + */ +#define rt_slist_for_each_entry(pos, head, member) \ + for (pos = ((head)->next == (RT_NULL) ? (RT_NULL) : rt_slist_entry((head)->next, typeof(*pos), member)); \ + pos != (RT_NULL) && &pos->member != (RT_NULL); \ + pos = (pos->member.next == (RT_NULL) ? (RT_NULL) : rt_slist_entry(pos->member.next, typeof(*pos), member))) + +/** + * rt_slist_first_entry - get the first element from a slist + * @param ptr the slist head to take the element from. + * @param type the type of the struct this is embedded in. + * @param member the name of the slist_struct within the struct. + * + * Note, that slist is expected to be not empty. + */ +#define rt_slist_first_entry(ptr, type, member) \ + rt_slist_entry((ptr)->next, type, member) + +/** + * rt_slist_tail_entry - get the tail element from a slist + * @param ptr the slist head to take the element from. + * @param type the type of the struct this is embedded in. + * @param member the name of the slist_struct within the struct. + * + * Note, that slist is expected to be not empty. + */ +#define rt_slist_tail_entry(ptr, type, member) \ + rt_slist_entry(rt_slist_tail(ptr), type, member) + +/**@}*/ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tasks/runtime-rtthread-softtimer-wakeup/template/include/rtthread.h b/tasks/runtime-rtthread-softtimer-wakeup/template/include/rtthread.h new file mode 100644 index 00000000..5a1ab089 --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/template/include/rtthread.h @@ -0,0 +1,816 @@ +/* + * Copyright (c) 2006-2021, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +#ifndef __RT_THREAD_H__ +#define __RT_THREAD_H__ + +#include +#include +#include +#include +#include +#ifdef RT_USING_LEGACY +#include +#endif +#ifdef RT_USING_FINSH +#include +#endif /* RT_USING_FINSH */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @addtogroup KernelObject + * @{ + */ + +/* + * kernel object interface + */ +struct rt_object_information * +rt_object_get_information(enum rt_object_class_type type); +int rt_object_get_length(enum rt_object_class_type type); +int rt_object_get_pointers(enum rt_object_class_type type, rt_object_t *pointers, int maxlen); + +void rt_object_init(struct rt_object *object, + enum rt_object_class_type type, + const char *name); +void rt_object_detach(rt_object_t object); +#ifdef RT_USING_HEAP +rt_object_t rt_object_allocate(enum rt_object_class_type type, const char *name); +void rt_object_delete(rt_object_t object); +/* custom object */ +rt_object_t rt_custom_object_create(const char *name, void *data, rt_err_t (*data_destroy)(void *)); +rt_err_t rt_custom_object_destroy(rt_object_t obj); +#endif /* RT_USING_HEAP */ +rt_bool_t rt_object_is_systemobject(rt_object_t object); +rt_uint8_t rt_object_get_type(rt_object_t object); +rt_object_t rt_object_find(const char *name, rt_uint8_t type); +rt_err_t rt_object_get_name(rt_object_t object, char *name, rt_uint8_t name_size); + +#ifdef RT_USING_HOOK +void rt_object_attach_sethook(void (*hook)(struct rt_object *object)); +void rt_object_detach_sethook(void (*hook)(struct rt_object *object)); +void rt_object_trytake_sethook(void (*hook)(struct rt_object *object)); +void rt_object_take_sethook(void (*hook)(struct rt_object *object)); +void rt_object_put_sethook(void (*hook)(struct rt_object *object)); +#endif /* RT_USING_HOOK */ + +/**@}*/ + +/** + * @addtogroup Clock + * @{ + */ + +/* + * clock & timer interface + */ +rt_tick_t rt_tick_get(void); +void rt_tick_set(rt_tick_t tick); +void rt_tick_increase(void); +rt_tick_t rt_tick_from_millisecond(rt_int32_t ms); +rt_tick_t rt_tick_get_millisecond(void); +#ifdef RT_USING_HOOK +void rt_tick_sethook(void (*hook)(void)); +#endif /* RT_USING_HOOK */ + +void rt_system_timer_init(void); +void rt_system_timer_thread_init(void); + +void rt_timer_init(rt_timer_t timer, + const char *name, + void (*timeout)(void *parameter), + void *parameter, + rt_tick_t time, + rt_uint8_t flag); +rt_err_t rt_timer_detach(rt_timer_t timer); +#ifdef RT_USING_HEAP +rt_timer_t rt_timer_create(const char *name, + void (*timeout)(void *parameter), + void *parameter, + rt_tick_t time, + rt_uint8_t flag); +rt_err_t rt_timer_delete(rt_timer_t timer); +#endif /* RT_USING_HEAP */ +rt_err_t rt_timer_start(rt_timer_t timer); +rt_err_t rt_timer_stop(rt_timer_t timer); +rt_err_t rt_timer_control(rt_timer_t timer, int cmd, void *arg); +rt_tick_t rt_timer_next_timeout_tick(void); +void rt_timer_check(void); +#ifdef RT_USING_HOOK +void rt_timer_enter_sethook(void (*hook)(struct rt_timer *timer)); +void rt_timer_exit_sethook(void (*hook)(struct rt_timer *timer)); +#endif /* RT_USING_HOOK */ + +/**@}*/ + +/** + * @addtogroup Thread + * @{ + */ + +/* + * thread interface + */ +rt_err_t rt_thread_init(struct rt_thread *thread, + const char *name, + void (*entry)(void *parameter), + void *parameter, + void *stack_start, + rt_uint32_t stack_size, + rt_uint8_t priority, + rt_uint32_t tick); +rt_err_t rt_thread_detach(rt_thread_t thread); +#ifdef RT_USING_HEAP +rt_thread_t rt_thread_create(const char *name, + void (*entry)(void *parameter), + void *parameter, + rt_uint32_t stack_size, + rt_uint8_t priority, + rt_uint32_t tick); +rt_err_t rt_thread_delete(rt_thread_t thread); +#endif /* RT_USING_HEAP */ +rt_thread_t rt_thread_self(void); +rt_thread_t rt_thread_find(char *name); +rt_err_t rt_thread_startup(rt_thread_t thread); +rt_err_t rt_thread_yield(void); +rt_err_t rt_thread_delay(rt_tick_t tick); +rt_err_t rt_thread_delay_until(rt_tick_t *tick, rt_tick_t inc_tick); +rt_err_t rt_thread_mdelay(rt_int32_t ms); +rt_err_t rt_thread_control(rt_thread_t thread, int cmd, void *arg); +rt_err_t rt_thread_suspend(rt_thread_t thread); +rt_err_t rt_thread_suspend_with_flag(rt_thread_t thread, int suspend_flag); +rt_err_t rt_thread_resume(rt_thread_t thread); +#ifdef RT_USING_SMART +rt_err_t rt_thread_wakeup(rt_thread_t thread); +void rt_thread_wakeup_set(struct rt_thread *thread, rt_wakeup_func_t func, void* user_data); +#endif /* RT_USING_SMART */ +void rt_thread_timeout(void *parameter); +rt_err_t rt_thread_get_name(rt_thread_t thread, char *name, rt_uint8_t name_size); +#ifdef RT_USING_SIGNALS +void rt_thread_alloc_sig(rt_thread_t tid); +void rt_thread_free_sig(rt_thread_t tid); +int rt_thread_kill(rt_thread_t tid, int sig); +#endif /* RT_USING_SIGNALS */ +#ifdef RT_USING_HOOK +void rt_thread_suspend_sethook(void (*hook)(rt_thread_t thread)); +void rt_thread_resume_sethook (void (*hook)(rt_thread_t thread)); +void rt_thread_inited_sethook (void (*hook)(rt_thread_t thread)); +#endif /* RT_USING_HOOK */ + +/* + * idle thread interface + */ +void rt_thread_idle_init(void); +#if defined(RT_USING_HOOK) || defined(RT_USING_IDLE_HOOK) +rt_err_t rt_thread_idle_sethook(void (*hook)(void)); +rt_err_t rt_thread_idle_delhook(void (*hook)(void)); +#endif /* defined(RT_USING_HOOK) || defined(RT_USING_IDLE_HOOK) */ +rt_thread_t rt_thread_idle_gethandler(void); + +/* + * schedule service + */ +void rt_system_scheduler_init(void); +void rt_system_scheduler_start(void); + +void rt_schedule(void); +void rt_schedule_insert_thread(struct rt_thread *thread); +void rt_schedule_remove_thread(struct rt_thread *thread); + +void rt_enter_critical(void); +void rt_exit_critical(void); +rt_uint16_t rt_critical_level(void); + +#ifdef RT_USING_HOOK +void rt_scheduler_sethook(void (*hook)(rt_thread_t from, rt_thread_t to)); +void rt_scheduler_switch_sethook(void (*hook)(struct rt_thread *tid)); +#endif /* RT_USING_HOOK */ + +#ifdef RT_USING_SMP +void rt_secondary_cpu_entry(void); +void rt_scheduler_ipi_handler(int vector, void *param); +#endif /* RT_USING_SMP */ + +/**@}*/ + +/** + * @addtogroup Signals + * @{ + */ +#ifdef RT_USING_SIGNALS +void rt_signal_mask(int signo); +void rt_signal_unmask(int signo); +rt_sighandler_t rt_signal_install(int signo, rt_sighandler_t handler); +int rt_signal_wait(const rt_sigset_t *set, rt_siginfo_t *si, rt_int32_t timeout); +int rt_system_signal_init(void); +#endif /* RT_USING_SIGNALS */ +/**@}*/ + +/** + * @addtogroup MM + * @{ + */ + +/* + * memory management interface + */ +#ifdef RT_USING_MEMPOOL +/* + * memory pool interface + */ +rt_err_t rt_mp_init(struct rt_mempool *mp, + const char *name, + void *start, + rt_size_t size, + rt_size_t block_size); +rt_err_t rt_mp_detach(struct rt_mempool *mp); +#ifdef RT_USING_HEAP +rt_mp_t rt_mp_create(const char *name, + rt_size_t block_count, + rt_size_t block_size); +rt_err_t rt_mp_delete(rt_mp_t mp); +#endif /* RT_USING_HEAP */ +void *rt_mp_alloc(rt_mp_t mp, rt_int32_t time); +void rt_mp_free(void *block); +#ifdef RT_USING_HOOK +void rt_mp_alloc_sethook(void (*hook)(struct rt_mempool *mp, void *block)); +void rt_mp_free_sethook(void (*hook)(struct rt_mempool *mp, void *block)); +#endif /* RT_USING_HOOK */ + +#endif /* RT_USING_MEMPOOL */ + +#ifdef RT_USING_HEAP +/* + * heap memory interface + */ +void rt_system_heap_init(void *begin_addr, void *end_addr); + +void *rt_malloc(rt_size_t size); +void rt_free(void *ptr); +void *rt_realloc(void *ptr, rt_size_t newsize); +void *rt_calloc(rt_size_t count, rt_size_t size); +void *rt_malloc_align(rt_size_t size, rt_size_t align); +void rt_free_align(void *ptr); + +void rt_memory_info(rt_size_t *total, + rt_size_t *used, + rt_size_t *max_used); + +#if defined(RT_USING_SLAB) && defined(RT_USING_SLAB_AS_HEAP) +void *rt_page_alloc(rt_size_t npages); +void rt_page_free(void *addr, rt_size_t npages); +#endif /* defined(RT_USING_SLAB) && defined(RT_USING_SLAB_AS_HEAP) */ + +#ifdef RT_USING_HOOK +void rt_malloc_sethook(void (*hook)(void *ptr, rt_size_t size)); +void rt_free_sethook(void (*hook)(void *ptr)); +#endif /* RT_USING_HOOK */ + +#endif /* RT_USING_HEAP */ + +#ifdef RT_USING_SMALL_MEM +/** + * small memory object interface + */ +rt_smem_t rt_smem_init(const char *name, + void *begin_addr, + rt_size_t size); +rt_err_t rt_smem_detach(rt_smem_t m); +void *rt_smem_alloc(rt_smem_t m, rt_size_t size); +void *rt_smem_realloc(rt_smem_t m, void *rmem, rt_size_t newsize); +void rt_smem_free(void *rmem); +#endif /* RT_USING_SMALL_MEM */ + +#ifdef RT_USING_MEMHEAP +/** + * memory heap object interface + */ +rt_err_t rt_memheap_init(struct rt_memheap *memheap, + const char *name, + void *start_addr, + rt_size_t size); +rt_err_t rt_memheap_detach(struct rt_memheap *heap); +void *rt_memheap_alloc(struct rt_memheap *heap, rt_size_t size); +void *rt_memheap_realloc(struct rt_memheap *heap, void *ptr, rt_size_t newsize); +void rt_memheap_free(void *ptr); +void rt_memheap_info(struct rt_memheap *heap, + rt_size_t *total, + rt_size_t *used, + rt_size_t *max_used); +#endif /* RT_USING_MEMHEAP */ + +#ifdef RT_USING_SLAB +/** + * slab object interface + */ +rt_slab_t rt_slab_init(const char *name, void *begin_addr, rt_size_t size); +rt_err_t rt_slab_detach(rt_slab_t m); +void *rt_slab_page_alloc(rt_slab_t m, rt_size_t npages); +void rt_slab_page_free(rt_slab_t m, void *addr, rt_size_t npages); +void *rt_slab_alloc(rt_slab_t m, rt_size_t size); +void *rt_slab_realloc(rt_slab_t m, void *ptr, rt_size_t size); +void rt_slab_free(rt_slab_t m, void *ptr); +#endif /* RT_USING_SLAB */ + +/**@}*/ + +/** + * @addtogroup IPC + * @{ + */ + +#ifdef RT_USING_SEMAPHORE +/* + * semaphore interface + */ +rt_err_t rt_sem_init(rt_sem_t sem, + const char *name, + rt_uint32_t value, + rt_uint8_t flag); +rt_err_t rt_sem_detach(rt_sem_t sem); +#ifdef RT_USING_HEAP +rt_sem_t rt_sem_create(const char *name, rt_uint32_t value, rt_uint8_t flag); +rt_err_t rt_sem_delete(rt_sem_t sem); +#endif /* RT_USING_HEAP */ + +rt_err_t rt_sem_take(rt_sem_t sem, rt_int32_t timeout); +rt_err_t rt_sem_take_interruptible(rt_sem_t sem, rt_int32_t timeout); +rt_err_t rt_sem_take_killable(rt_sem_t sem, rt_int32_t timeout); +rt_err_t rt_sem_trytake(rt_sem_t sem); +rt_err_t rt_sem_release(rt_sem_t sem); +rt_err_t rt_sem_control(rt_sem_t sem, int cmd, void *arg); +#endif /* RT_USING_SEMAPHORE */ + +#ifdef RT_USING_MUTEX +/* + * mutex interface + */ +rt_err_t rt_mutex_init(rt_mutex_t mutex, const char *name, rt_uint8_t flag); +rt_err_t rt_mutex_detach(rt_mutex_t mutex); +#ifdef RT_USING_HEAP +rt_mutex_t rt_mutex_create(const char *name, rt_uint8_t flag); +rt_err_t rt_mutex_delete(rt_mutex_t mutex); +#endif /* RT_USING_HEAP */ +void rt_mutex_drop_thread(rt_mutex_t mutex, rt_thread_t thread); +rt_uint8_t rt_mutex_setprioceiling(rt_mutex_t mutex, rt_uint8_t priority); +rt_uint8_t rt_mutex_getprioceiling(rt_mutex_t mutex); + +rt_err_t rt_mutex_take(rt_mutex_t mutex, rt_int32_t timeout); +rt_err_t rt_mutex_trytake(rt_mutex_t mutex); +rt_err_t rt_mutex_take_interruptible(rt_mutex_t mutex, rt_int32_t time); +rt_err_t rt_mutex_take_killable(rt_mutex_t mutex, rt_int32_t time); +rt_err_t rt_mutex_release(rt_mutex_t mutex); +rt_err_t rt_mutex_control(rt_mutex_t mutex, int cmd, void *arg); + +rt_inline rt_thread_t rt_mutex_get_owner(rt_mutex_t mutex) +{ + return mutex->owner; +} +rt_inline rt_ubase_t rt_mutex_get_hold(rt_mutex_t mutex) +{ + return mutex->hold; +} + +#endif /* RT_USING_MUTEX */ + +#ifdef RT_USING_EVENT +/* + * event interface + */ +rt_err_t rt_event_init(rt_event_t event, const char *name, rt_uint8_t flag); +rt_err_t rt_event_detach(rt_event_t event); +#ifdef RT_USING_HEAP +rt_event_t rt_event_create(const char *name, rt_uint8_t flag); +rt_err_t rt_event_delete(rt_event_t event); +#endif /* RT_USING_HEAP */ + +rt_err_t rt_event_send(rt_event_t event, rt_uint32_t set); +rt_err_t rt_event_recv(rt_event_t event, + rt_uint32_t set, + rt_uint8_t opt, + rt_int32_t timeout, + rt_uint32_t *recved); +rt_err_t rt_event_recv_interruptible(rt_event_t event, + rt_uint32_t set, + rt_uint8_t opt, + rt_int32_t timeout, + rt_uint32_t *recved); +rt_err_t rt_event_recv_killable(rt_event_t event, + rt_uint32_t set, + rt_uint8_t opt, + rt_int32_t timeout, + rt_uint32_t *recved); +rt_err_t rt_event_control(rt_event_t event, int cmd, void *arg); +#endif /* RT_USING_EVENT */ + +#ifdef RT_USING_MAILBOX +/* + * mailbox interface + */ +rt_err_t rt_mb_init(rt_mailbox_t mb, + const char *name, + void *msgpool, + rt_size_t size, + rt_uint8_t flag); +rt_err_t rt_mb_detach(rt_mailbox_t mb); +#ifdef RT_USING_HEAP +rt_mailbox_t rt_mb_create(const char *name, rt_size_t size, rt_uint8_t flag); +rt_err_t rt_mb_delete(rt_mailbox_t mb); +#endif /* RT_USING_HEAP */ + +rt_err_t rt_mb_send(rt_mailbox_t mb, rt_ubase_t value); +rt_err_t rt_mb_send_wait(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout); +rt_err_t rt_mb_send_wait_interruptible(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout); +rt_err_t rt_mb_send_wait_killable(rt_mailbox_t mb, + rt_ubase_t value, + rt_int32_t timeout); +rt_err_t rt_mb_urgent(rt_mailbox_t mb, rt_ubase_t value); +rt_err_t rt_mb_recv(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout); +rt_err_t rt_mb_recv_interruptible(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout); +rt_err_t rt_mb_recv_killable(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout); +rt_err_t rt_mb_control(rt_mailbox_t mb, int cmd, void *arg); +#endif /* RT_USING_MAILBOX */ + +#ifdef RT_USING_MESSAGEQUEUE + +struct rt_mq_message +{ + struct rt_mq_message *next; + rt_ssize_t length; +#ifdef RT_USING_MESSAGEQUEUE_PRIORITY + rt_int32_t prio; +#endif /* RT_USING_MESSAGEQUEUE_PRIORITY */ +}; + +#define RT_MQ_BUF_SIZE(msg_size, max_msgs) \ +((RT_ALIGN((msg_size), RT_ALIGN_SIZE) + sizeof(struct rt_mq_message)) * (max_msgs)) + +/* + * message queue interface + */ +rt_err_t rt_mq_init(rt_mq_t mq, + const char *name, + void *msgpool, + rt_size_t msg_size, + rt_size_t pool_size, + rt_uint8_t flag); +rt_err_t rt_mq_detach(rt_mq_t mq); +#ifdef RT_USING_HEAP +rt_mq_t rt_mq_create(const char *name, + rt_size_t msg_size, + rt_size_t max_msgs, + rt_uint8_t flag); +rt_err_t rt_mq_delete(rt_mq_t mq); +#endif /* RT_USING_HEAP */ + +rt_err_t rt_mq_send(rt_mq_t mq, const void *buffer, rt_size_t size); +rt_err_t rt_mq_send_interruptible(rt_mq_t mq, const void *buffer, rt_size_t size); +rt_err_t rt_mq_send_killable(rt_mq_t mq, const void *buffer, rt_size_t size); +rt_err_t rt_mq_send_wait(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout); +rt_err_t rt_mq_send_wait_interruptible(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout); +rt_err_t rt_mq_send_wait_killable(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t timeout); +rt_err_t rt_mq_urgent(rt_mq_t mq, const void *buffer, rt_size_t size); +rt_ssize_t rt_mq_recv(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout); +rt_ssize_t rt_mq_recv_interruptible(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout); +rt_ssize_t rt_mq_recv_killable(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t timeout); +rt_err_t rt_mq_control(rt_mq_t mq, int cmd, void *arg); + +#ifdef RT_USING_MESSAGEQUEUE_PRIORITY +rt_err_t rt_mq_send_wait_prio(rt_mq_t mq, + const void *buffer, + rt_size_t size, + rt_int32_t prio, + rt_int32_t timeout, + int suspend_flag); +rt_ssize_t rt_mq_recv_prio(rt_mq_t mq, + void *buffer, + rt_size_t size, + rt_int32_t *prio, + rt_int32_t timeout, + int suspend_flag); +#endif /* RT_USING_MESSAGEQUEUE_PRIORITY */ +#endif /* RT_USING_MESSAGEQUEUE */ + +/* defunct */ +void rt_thread_defunct_enqueue(rt_thread_t thread); +rt_thread_t rt_thread_defunct_dequeue(void); + +/* + * spinlock + */ +struct rt_spinlock; +#ifdef RT_USING_SMP + +void rt_spin_lock_init(struct rt_spinlock *lock); +void rt_spin_lock(struct rt_spinlock *lock); +void rt_spin_unlock(struct rt_spinlock *lock); +rt_base_t rt_spin_lock_irqsave(struct rt_spinlock *lock); +void rt_spin_unlock_irqrestore(struct rt_spinlock *lock, rt_base_t level); +#else + +rt_inline void rt_spin_lock_init(struct rt_spinlock *lock) +{ + RT_UNUSED(lock); +} +rt_inline void rt_spin_lock(struct rt_spinlock *lock) +{ + RT_UNUSED(lock); + rt_enter_critical(); +} +rt_inline void rt_spin_unlock(struct rt_spinlock *lock) +{ + RT_UNUSED(lock); + rt_exit_critical(); +} +rt_inline rt_base_t rt_spin_lock_irqsave(struct rt_spinlock *lock) +{ + rt_base_t level; + RT_UNUSED(lock); + level = rt_hw_interrupt_disable(); + return level; +} +rt_inline void rt_spin_unlock_irqrestore(struct rt_spinlock *lock, rt_base_t level) +{ + RT_UNUSED(lock); + rt_hw_interrupt_enable(level); +} + +#endif /* RT_USING_SMP */ + +/**@}*/ + +#ifdef RT_USING_DEVICE +/** + * @addtogroup Device + * @{ + */ + +/* + * device (I/O) system interface + */ +rt_device_t rt_device_find(const char *name); + +rt_err_t rt_device_register(rt_device_t dev, + const char *name, + rt_uint16_t flags); +rt_err_t rt_device_unregister(rt_device_t dev); + +#ifdef RT_USING_HEAP +rt_device_t rt_device_create(int type, int attach_size); +void rt_device_destroy(rt_device_t device); +#endif /* RT_USING_HEAP */ + +rt_err_t +rt_device_set_rx_indicate(rt_device_t dev, + rt_err_t (*rx_ind)(rt_device_t dev, rt_size_t size)); +rt_err_t +rt_device_set_tx_complete(rt_device_t dev, + rt_err_t (*tx_done)(rt_device_t dev, void *buffer)); + +rt_err_t rt_device_init (rt_device_t dev); +rt_err_t rt_device_open (rt_device_t dev, rt_uint16_t oflag); +rt_err_t rt_device_close(rt_device_t dev); +rt_ssize_t rt_device_read(rt_device_t dev, + rt_off_t pos, + void *buffer, + rt_size_t size); +rt_ssize_t rt_device_write(rt_device_t dev, + rt_off_t pos, + const void *buffer, + rt_size_t size); +rt_err_t rt_device_control(rt_device_t dev, int cmd, void *arg); + +/**@}*/ +#endif /* RT_USING_DEVICE */ + +/* + * interrupt service + */ + +/* + * rt_interrupt_enter and rt_interrupt_leave only can be called by BSP + */ +void rt_interrupt_enter(void); +void rt_interrupt_leave(void); + +#ifdef RT_USING_SMP + +/* + * smp cpus lock service + */ + +rt_base_t rt_cpus_lock(void); +void rt_cpus_unlock(rt_base_t level); + +struct rt_cpu *rt_cpu_self(void); +struct rt_cpu *rt_cpu_index(int index); + +#endif /* RT_USING_SMP */ + +/* + * the number of nested interrupts. + */ +rt_uint8_t rt_interrupt_get_nest(void); + +#ifdef RT_USING_HOOK +void rt_interrupt_enter_sethook(void (*hook)(void)); +void rt_interrupt_leave_sethook(void (*hook)(void)); +#endif /* RT_USING_HOOK */ + +#ifdef RT_USING_COMPONENTS_INIT +void rt_components_init(void); +void rt_components_board_init(void); +#endif /* RT_USING_COMPONENTS_INIT */ + +/** + * @addtogroup KernelService + * @{ + */ + +/* + * general kernel service + */ +#ifndef RT_USING_CONSOLE +#define rt_kprintf(...) +#define rt_kputs(str) +#else +int rt_kprintf(const char *fmt, ...); +void rt_kputs(const char *str); +#endif /* RT_USING_CONSOLE */ + +rt_err_t rt_backtrace(void); +rt_err_t rt_backtrace_thread(rt_thread_t thread); +rt_err_t rt_backtrace_frame(struct rt_hw_backtrace_frame *frame); + +int rt_vsprintf(char *dest, const char *format, va_list arg_ptr); +int rt_vsnprintf(char *buf, rt_size_t size, const char *fmt, va_list args); +int rt_sprintf(char *buf, const char *format, ...); +int rt_snprintf(char *buf, rt_size_t size, const char *format, ...); + +#if defined(RT_USING_DEVICE) && defined(RT_USING_CONSOLE) +rt_device_t rt_console_set_device(const char *name); +rt_device_t rt_console_get_device(void); +#endif /* defined(RT_USING_DEVICE) && defined(RT_USING_CONSOLE) */ + +rt_err_t rt_get_errno(void); +void rt_set_errno(rt_err_t no); +int *_rt_errno(void); +const char *rt_strerror(rt_err_t error); +#if !defined(RT_USING_NEWLIBC) && !defined(_WIN32) +#ifndef errno +#define errno *_rt_errno() +#endif +#endif /* !defined(RT_USING_NEWLIBC) && !defined(_WIN32) */ + +int __rt_ffs(int value); + +#ifndef RT_KSERVICE_USING_STDLIB_MEMORY +void *rt_memset(void *src, int c, rt_ubase_t n); +void *rt_memcpy(void *dest, const void *src, rt_ubase_t n); +void *rt_memmove(void *dest, const void *src, rt_size_t n); +rt_int32_t rt_memcmp(const void *cs, const void *ct, rt_size_t count); +#endif /* RT_KSERVICE_USING_STDLIB_MEMORY */ +char *rt_strdup(const char *s); +rt_size_t rt_strnlen(const char *s, rt_ubase_t maxlen); +#ifndef RT_KSERVICE_USING_STDLIB +char *rt_strstr(const char *str1, const char *str2); +rt_int32_t rt_strcasecmp(const char *a, const char *b); +char *rt_strcpy(char *dst, const char *src); +char *rt_strncpy(char *dest, const char *src, rt_size_t n); +rt_int32_t rt_strncmp(const char *cs, const char *ct, rt_size_t count); +rt_int32_t rt_strcmp(const char *cs, const char *ct); +rt_size_t rt_strlen(const char *src); +#else +#include +#ifdef RT_KSERVICE_USING_STDLIB_MEMORY +#define rt_memset(s, c, count) memset(s, c, count) +#define rt_memcpy(dst, src, count) memcpy(dst, src, count) +#define rt_memmove(dest, src, n) memmove(dest, src, n) +#define rt_memcmp(cs, ct, count) memcmp(cs, ct, count) +#endif /* RT_KSERVICE_USING_STDLIB_MEMORY */ +#define rt_strstr(str1, str2) strstr(str1, str2) +#define rt_strcasecmp(a, b) strcasecmp(a, b) +#define rt_strcpy(dest, src) strcpy(dest, src) +#define rt_strncpy(dest, src, n) strncpy(dest, src, n) +#define rt_strncmp(cs, ct, count) strncmp(cs, ct, count) +#define rt_strcmp(cs, ct) strcmp(cs, ct) +#define rt_strlen(src) strlen(src) +#endif /*RT_KSERVICE_USING_STDLIB*/ + +void rt_show_version(void); + +#ifdef RT_USING_DEBUG +extern void (*rt_assert_hook)(const char *ex, const char *func, rt_size_t line); +void rt_assert_set_hook(void (*hook)(const char *ex, const char *func, rt_size_t line)); +void rt_assert_handler(const char *ex, const char *func, rt_size_t line); + +#define RT_ASSERT(EX) \ +if (!(EX)) \ +{ \ + rt_assert_handler(#EX, __FUNCTION__, __LINE__); \ +} +#else +#define RT_ASSERT(EX) +#endif /* RT_USING_DEBUG */ + +#ifdef RT_DEBUGING_CONTEXT +/* Macro to check current context */ +#define RT_DEBUG_NOT_IN_INTERRUPT \ +do \ +{ \ + if (rt_interrupt_get_nest() != 0) \ + { \ + rt_kprintf("Function[%s] shall not be used in ISR\n", __FUNCTION__); \ + RT_ASSERT(0) \ + } \ +} \ +while (0) + +/* "In thread context" means: + * 1) the scheduler has been started + * 2) not in interrupt context. + */ +#define RT_DEBUG_IN_THREAD_CONTEXT \ +do \ +{ \ + if (rt_thread_self() == RT_NULL) \ + { \ + rt_kprintf("Function[%s] shall not be used before scheduler start\n", \ + __FUNCTION__); \ + RT_ASSERT(0) \ + } \ + RT_DEBUG_NOT_IN_INTERRUPT; \ +} \ +while (0) + +/* "scheduler available" means: + * 1) the scheduler has been started. + * 2) not in interrupt context. + * 3) scheduler is not locked. + * 4) interrupt is not disabled. + */ +#define RT_DEBUG_SCHEDULER_AVAILABLE(need_check) \ +do \ +{ \ + if (need_check) \ + { \ + rt_bool_t interrupt_disabled; \ + interrupt_disabled = rt_hw_interrupt_is_disabled(); \ + if (rt_critical_level() != 0) \ + { \ + rt_kprintf("Function[%s]: scheduler is not available\n", \ + __FUNCTION__); \ + RT_ASSERT(0) \ + } \ + if (interrupt_disabled == RT_TRUE) \ + { \ + rt_kprintf("Function[%s]: interrupt is disabled\n", \ + __FUNCTION__); \ + RT_ASSERT(0) \ + } \ + RT_DEBUG_IN_THREAD_CONTEXT; \ + } \ +} \ +while (0) +#else +#define RT_DEBUG_NOT_IN_INTERRUPT +#define RT_DEBUG_IN_THREAD_CONTEXT +#define RT_DEBUG_SCHEDULER_AVAILABLE(need_check) +#endif /* RT_DEBUGING_CONTEXT */ + +/**@}*/ + +#ifdef __cplusplus +} +#endif + +#endif /* __RT_THREAD_H__ */ diff --git a/tasks/runtime-rtthread-softtimer-wakeup/template/port/controlled.c b/tasks/runtime-rtthread-softtimer-wakeup/template/port/controlled.c new file mode 100644 index 00000000..8b700665 --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/template/port/controlled.c @@ -0,0 +1,145 @@ +#define _XOPEN_SOURCE 700 +#include +#include +#include +#include +#include +#include "controlled.h" + +static struct rt_cpu cpu; +static struct rt_thread application; +static rt_thread_t worker; +static rt_tick_t now; +static ucontext_t driver_context, worker_context; +static unsigned char execution_stack[131072]; +static rt_list_t ready; +static int in_worker, injecting, initialized, duplicate_ready, operations, interleavings; +static int capture; +static struct rt_spinlock *captured, *after_lock, *before_lock; +static void (*after_fn)(void *), (*before_fn)(void *); +static void *after_arg, *before_arg; +static rt_base_t irq; + +static void budget(void) { if (++operations > 2000000) { fputs("port operation budget\n", stderr); exit(7); } } +static void interleave(void (*fn)(void *), void *arg) +{ + rt_thread_t previous = cpu.current_thread; + int previous_in = in_worker; + cpu.current_thread = &application; + in_worker = 0; injecting = 1; interleavings++; + fn(arg); + injecting = 0; in_worker = previous_in; cpu.current_thread = previous; +} +struct rt_cpu *rt_cpu_self(void) { return &cpu; } +int rt_hw_cpu_id(void) { return 0; } +rt_base_t rt_hw_local_irq_disable(void) { rt_base_t saved = irq; irq = 1; return saved; } +void rt_hw_local_irq_enable(rt_base_t saved) { irq = saved; } +rt_base_t rt_cpus_lock(void) { return rt_hw_local_irq_disable(); } +void rt_cpus_unlock(rt_base_t saved) { rt_hw_local_irq_enable(saved); } +rt_bool_t rt_hw_interrupt_is_disabled(void) { return irq != 0; } +void rt_spin_lock_init(struct rt_spinlock *lock) { lock->lock = 0; } +rt_base_t rt_spin_lock_irqsave(struct rt_spinlock *lock) +{ + budget(); + if (capture) { capture = 0; captured = lock; } + if (!injecting && before_fn && lock == before_lock) { + void (*fn)(void *) = before_fn; void *arg = before_arg; before_fn = NULL; + interleave(fn, arg); + } + lock->lock++; + return rt_hw_local_irq_disable(); +} +void rt_spin_unlock_irqrestore(struct rt_spinlock *lock, rt_base_t saved) +{ + budget(); + lock->lock--; + rt_hw_local_irq_enable(saved); + if (!injecting && after_fn && lock == after_lock) { + void (*fn)(void *) = after_fn; void *arg = after_arg; after_fn = NULL; + interleave(fn, arg); + } +} +void rt_spin_lock(struct rt_spinlock *lock) { (void)rt_spin_lock_irqsave(lock); } +void rt_spin_unlock(struct rt_spinlock *lock) { rt_spin_unlock_irqrestore(lock, 0); } +rt_tick_t rt_tick_get(void) { budget(); return now; } +void rt_object_init(struct rt_object *object, enum rt_object_class_type type, const char *name) +{ + memset(object, 0, sizeof(*object)); + strncpy(object->name, name, RT_NAME_MAX - 1); + object->type = type | RT_Object_Class_Static; + rt_list_init(&object->list); +} +rt_uint8_t rt_object_get_type(rt_object_t object) { return object->type & ~RT_Object_Class_Static; } +rt_bool_t rt_object_is_systemobject(rt_object_t object) { return !!(object->type & RT_Object_Class_Static); } +void rt_object_detach(rt_object_t object) { rt_list_remove(&object->list); } +rt_uint8_t *rt_hw_stack_init(void *entry, void *parameter, rt_uint8_t *stack, void *exit_fn) +{ (void)entry; (void)parameter; (void)exit_fn; return stack; } +void rt_thread_defunct_enqueue(rt_thread_t thread) { (void)thread; } +void rt_schedule_remove_thread(rt_thread_t thread) { rt_list_remove(&thread->tlist_schedule); } +void rt_schedule_insert_thread(rt_thread_t thread) +{ + if (!rt_list_isempty(&thread->tlist_schedule)) duplicate_ready++; + else rt_list_insert_before(&ready, &thread->tlist_schedule); + thread->stat = (thread->stat & ~RT_THREAD_STAT_MASK) | RT_THREAD_READY; + if (strcmp(thread->parent.name, "timer") == 0) worker = thread; +} +void rt_schedule(void) +{ + budget(); + if (in_worker && ((worker->stat & RT_THREAD_SUSPEND_MASK) == RT_THREAD_SUSPEND_MASK || + (worker->stat & RT_THREAD_STAT_MASK) == RT_THREAD_CLOSE)) + swapcontext(&worker_context, &driver_context); + else if (in_worker && (worker->stat & RT_THREAD_STAT_MASK) == RT_THREAD_READY) { + rt_list_remove(&worker->tlist_schedule); + worker->stat = (worker->stat & ~RT_THREAD_STAT_MASK) | RT_THREAD_RUNNING; + } +} +static void worker_entry(void) +{ + ((void (*)(void *))worker->entry)(worker->parameter); + worker->stat = RT_THREAD_CLOSE; + swapcontext(&worker_context, &driver_context); +} +void port_init(rt_tick_t tick) +{ + now = tick; rt_list_init(&ready); + rt_object_init(&application.parent, RT_Object_Class_Thread, "application"); + application.stat = RT_THREAD_RUNNING; cpu.current_thread = &application; + rt_system_timer_init(); rt_system_timer_thread_init(); +} +void port_pump(void) +{ + if (!worker || (worker->stat & RT_THREAD_STAT_MASK) != RT_THREAD_READY) return; + if (!initialized) { + initialized = 1; getcontext(&worker_context); + worker_context.uc_stack.ss_sp = execution_stack; + worker_context.uc_stack.ss_size = sizeof(execution_stack); + worker_context.uc_link = &driver_context; + makecontext(&worker_context, worker_entry, 0); + } + rt_list_remove(&worker->tlist_schedule); + worker->stat = (worker->stat & ~RT_THREAD_STAT_MASK) | RT_THREAD_RUNNING; + cpu.current_thread = worker; in_worker = 1; + swapcontext(&driver_context, &worker_context); + in_worker = 0; cpu.current_thread = &application; +} +void port_advance(rt_tick_t tick) { now = tick; rt_timer_check(); port_pump(); } +rt_thread_t port_worker(void) { return worker; } +void port_capture_lock(void) { captured = NULL; capture = 1; } +struct rt_spinlock *port_captured_lock(void) { return captured; } +void port_after_unlock(struct rt_spinlock *lock, void (*fn)(void *), void *arg) +{ after_lock = lock; after_fn = fn; after_arg = arg; } +void port_before_lock(struct rt_spinlock *lock, void (*fn)(void *), void *arg) +{ before_lock = lock; before_fn = fn; before_arg = arg; } +int port_duplicate_ready(void) { return duplicate_ready; } +int port_ready_count(rt_thread_t thread) +{ + int count = 0; rt_list_t *p; + for (p = ready.next; p != &ready && count < 100; p = p->next) + if (p == &thread->tlist_schedule) count++; + return count; +} +int port_interleavings(void) { return interleavings; } +void rt_assert_handler(const char *ex, const char *func, rt_size_t line) +{ fprintf(stderr, "assert:%s:%s:%lu\n", ex, func, (unsigned long)line); exit(8); } +void *rt_memset(void *s, int c, rt_ubase_t count) { return memset(s, c, count); } diff --git a/tasks/runtime-rtthread-softtimer-wakeup/template/port/controlled.h b/tasks/runtime-rtthread-softtimer-wakeup/template/port/controlled.h new file mode 100644 index 00000000..df24c031 --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/template/port/controlled.h @@ -0,0 +1,15 @@ +#ifndef CONTROLLED_PORT_H +#define CONTROLLED_PORT_H +#include +void port_init(rt_tick_t tick); +void port_pump(void); +void port_advance(rt_tick_t tick); +rt_thread_t port_worker(void); +void port_capture_lock(void); +struct rt_spinlock *port_captured_lock(void); +void port_after_unlock(struct rt_spinlock *lock, void (*fn)(void *), void *arg); +void port_before_lock(struct rt_spinlock *lock, void (*fn)(void *), void *arg); +int port_duplicate_ready(void); +int port_ready_count(rt_thread_t thread); +int port_interleavings(void); +#endif diff --git a/tasks/runtime-rtthread-softtimer-wakeup/template/reproduce.c b/tasks/runtime-rtthread-softtimer-wakeup/template/reproduce.c new file mode 100644 index 00000000..2aa9d121 --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/template/reproduce.c @@ -0,0 +1,19 @@ +#include +#include "controlled.h" +static struct rt_timer first, second; +static void fired(void *p) { printf("client=%s tick=%lu\n", (char *)p, (unsigned long)rt_tick_get()); } +static void application_event(void *p) { (void)p; rt_timer_start(&second); } +int main(void) +{ + port_init(100); + rt_timer_init(&first, "long", fired, "long", 40, RT_TIMER_FLAG_SOFT_TIMER); + rt_timer_init(&second, "short", fired, "short", 3, RT_TIMER_FLAG_SOFT_TIMER); + port_capture_lock(); rt_timer_start(&first); + struct rt_spinlock *event_boundary = port_captured_lock(); + port_after_unlock(event_boundary, application_event, NULL); + port_pump(); + port_advance(103); + puts("after short deadline"); + port_advance(140); + return 0; +} diff --git a/tasks/runtime-rtthread-softtimer-wakeup/template/smoke.c b/tasks/runtime-rtthread-softtimer-wakeup/template/smoke.c new file mode 100644 index 00000000..d2cc839c --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/template/smoke.c @@ -0,0 +1,18 @@ +#include +#include "controlled.h" +static int count; +static void callback(void *p) { count += *(int *)p; } +int main(void) +{ + struct rt_timer timer; + int amount = 3; + port_init(100); + rt_timer_init(&timer, "sample", callback, &amount, 5, RT_TIMER_FLAG_SOFT_TIMER); + rt_timer_start(&timer); + port_pump(); + port_advance(104); + printf("before=%d\n", count); + port_advance(105); + printf("after=%d\n", count); + return 0; +} diff --git a/tasks/runtime-rtthread-softtimer-wakeup/template/src/semaphore.c b/tasks/runtime-rtthread-softtimer-wakeup/template/src/semaphore.c new file mode 100644 index 00000000..4fa99313 --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/template/src/semaphore.c @@ -0,0 +1,381 @@ +/* + * Copyright (c) 2006-2022, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + + +#include +#include +#include + +rt_inline rt_err_t _ipc_object_init(struct rt_ipc_object *ipc) +{ + /* initialize ipc object */ + rt_list_init(&(ipc->suspend_thread)); + + return RT_EOK; +} + +rt_inline rt_err_t _ipc_list_suspend(rt_list_t *list, + struct rt_thread *thread, + rt_uint8_t flag, + int suspend_flag) +{ + rt_base_t level_local; + level_local = rt_hw_local_irq_disable(); + if ((thread->stat & RT_THREAD_SUSPEND_MASK) != RT_THREAD_SUSPEND_MASK) + { + rt_err_t ret = rt_thread_suspend_with_flag(thread, suspend_flag); + + /* suspend thread */ + if (ret != RT_EOK) + { + rt_hw_local_irq_enable(level_local); + return ret; + } + } + + switch (flag) + { + case RT_IPC_FLAG_FIFO: + rt_list_insert_before(list, &(thread->tlist)); + break; /* RT_IPC_FLAG_FIFO */ + + case RT_IPC_FLAG_PRIO: + { + struct rt_list_node *n; + struct rt_thread *sthread; + + /* find a suitable position */ + for (n = list->next; n != list; n = n->next) + { + sthread = rt_list_entry(n, struct rt_thread, tlist); + + /* find out */ + if (thread->current_priority < sthread->current_priority) + { + /* insert this thread before the sthread */ + rt_list_insert_before(&(sthread->tlist), &(thread->tlist)); + break; + } + } + + /* + * not found a suitable position, + * append to the end of suspend_thread list + */ + if (n == list) + rt_list_insert_before(list, &(thread->tlist)); + } + break;/* RT_IPC_FLAG_PRIO */ + + default: + RT_ASSERT(0); + break; + } + rt_hw_local_irq_enable(level_local); + return RT_EOK; +} + +rt_inline rt_err_t _ipc_list_resume(rt_list_t *list) +{ + struct rt_thread *thread; + + /* get thread entry */ + thread = rt_list_entry(list->next, struct rt_thread, tlist); + + thread->error = RT_EOK; + + LOG_D("resume thread:%s\n", thread->parent.name); + + /* resume it */ + rt_thread_resume(thread); + + return RT_EOK; +} + +rt_inline rt_err_t _ipc_list_resume_all(rt_list_t *list) +{ + struct rt_thread *thread; + + /* wakeup all suspended threads */ + while (!rt_list_isempty(list)) + { + + /* get next suspended thread */ + thread = rt_list_entry(list->next, struct rt_thread, tlist); + /* set error code to RT_ERROR */ + thread->error = -RT_ERROR; + + /* + * resume thread + * In rt_thread_resume function, it will remove current thread from + * suspended list + */ + rt_thread_resume(thread); + } + + return RT_EOK; +} + +static void _sem_object_init(rt_sem_t sem, + rt_uint16_t value, + rt_uint8_t flag, + rt_uint16_t max_value) +{ + /* initialize ipc object */ + _ipc_object_init(&(sem->parent)); + + sem->max_value = max_value; + /* set initial value */ + sem->value = value; + + /* set parent */ + sem->parent.parent.flag = flag; + rt_spin_lock_init(&(sem->spinlock)); +} + +rt_err_t rt_sem_init(rt_sem_t sem, + const char *name, + rt_uint32_t value, + rt_uint8_t flag) +{ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(value < 0x10000U); + RT_ASSERT((flag == RT_IPC_FLAG_FIFO) || (flag == RT_IPC_FLAG_PRIO)); + + /* initialize object */ + rt_object_init(&(sem->parent.parent), RT_Object_Class_Semaphore, name); + + _sem_object_init(sem, value, flag, RT_SEM_VALUE_MAX); + + return RT_EOK; +} +RTM_EXPORT(rt_sem_init); + +static rt_err_t _rt_sem_take(rt_sem_t sem, rt_int32_t timeout, int suspend_flag) +{ + rt_base_t level; + struct rt_thread *thread; + rt_err_t ret; + + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + + RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(sem->parent.parent))); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(sem->value == 0 && timeout != 0); + + level = rt_spin_lock_irqsave(&(sem->spinlock)); + + LOG_D("thread %s take sem:%s, which value is: %d", + rt_thread_self()->parent.name, + sem->parent.parent.name, + sem->value); + + if (sem->value > 0) + { + /* semaphore is available */ + sem->value --; + rt_spin_unlock_irqrestore(&(sem->spinlock), level); + } + else + { + /* no waiting, return with timeout */ + if (timeout == 0) + { + rt_spin_unlock_irqrestore(&(sem->spinlock), level); + return -RT_ETIMEOUT; + } + else + { + /* semaphore is unavailable, push to suspend list */ + /* get current thread */ + thread = rt_thread_self(); + + /* reset thread error number */ + thread->error = -RT_EINTR; + + LOG_D("sem take: suspend thread - %s", thread->parent.name); + + /* suspend thread */ + ret = _ipc_list_suspend(&(sem->parent.suspend_thread), + thread, + sem->parent.parent.flag, + suspend_flag); + if (ret != RT_EOK) + { + rt_spin_unlock_irqrestore(&(sem->spinlock), level); + return ret; + } + + /* has waiting time, start thread timer */ + if (timeout > 0) + { + LOG_D("set thread:%s to timer list", thread->parent.name); + + /* reset the timeout of thread timer and start it */ + rt_timer_control(&(thread->thread_timer), + RT_TIMER_CTRL_SET_TIME, + &timeout); + rt_timer_start(&(thread->thread_timer)); + } + + /* enable interrupt */ + rt_spin_unlock_irqrestore(&(sem->spinlock), level); + + /* do schedule */ + rt_schedule(); + + if (thread->error != RT_EOK) + { + return thread->error; + } + } + } + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(sem->parent.parent))); + + return RT_EOK; +} + +rt_err_t rt_sem_take(rt_sem_t sem, rt_int32_t time) +{ + return _rt_sem_take(sem, time, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_sem_take); + +rt_err_t rt_sem_take_interruptible(rt_sem_t sem, rt_int32_t time) +{ + return _rt_sem_take(sem, time, RT_INTERRUPTIBLE); +} +RTM_EXPORT(rt_sem_take_interruptible); + +rt_err_t rt_sem_take_killable(rt_sem_t sem, rt_int32_t time) +{ + return _rt_sem_take(sem, time, RT_KILLABLE); +} +RTM_EXPORT(rt_sem_take_killable); + +rt_err_t rt_sem_trytake(rt_sem_t sem) +{ + return rt_sem_take(sem, RT_WAITING_NO); +} +RTM_EXPORT(rt_sem_trytake); + +rt_err_t rt_sem_release(rt_sem_t sem) +{ + rt_base_t level; + rt_bool_t need_schedule; + + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(sem->parent.parent))); + + need_schedule = RT_FALSE; + + level = rt_spin_lock_irqsave(&(sem->spinlock)); + + LOG_D("thread %s releases sem:%s, which value is: %d", + rt_thread_self()->parent.name, + sem->parent.parent.name, + sem->value); + + if (!rt_list_isempty(&sem->parent.suspend_thread)) + { + /* resume the suspended thread */ + _ipc_list_resume(&(sem->parent.suspend_thread)); + need_schedule = RT_TRUE; + } + else + { + if(sem->value < sem->max_value) + { + sem->value ++; /* increase value */ + } + else + { + rt_spin_unlock_irqrestore(&(sem->spinlock), level); + return -RT_EFULL; /* value overflowed */ + } + } + + rt_spin_unlock_irqrestore(&(sem->spinlock), level); + + /* resume a thread, re-schedule */ + if (need_schedule == RT_TRUE) + rt_schedule(); + + return RT_EOK; +} +RTM_EXPORT(rt_sem_release); + +rt_err_t rt_sem_control(rt_sem_t sem, int cmd, void *arg) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(sem != RT_NULL); + RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore); + + if (cmd == RT_IPC_CMD_RESET) + { + rt_ubase_t value; + + /* get value */ + value = (rt_ubase_t)arg; + level = rt_spin_lock_irqsave(&(sem->spinlock)); + + /* resume all waiting thread */ + _ipc_list_resume_all(&sem->parent.suspend_thread); + + /* set new value */ + sem->value = (rt_uint16_t)value; + rt_spin_unlock_irqrestore(&(sem->spinlock), level); + rt_schedule(); + + return RT_EOK; + } + else if (cmd == RT_IPC_CMD_SET_VLIMIT) + { + rt_ubase_t max_value; + rt_bool_t need_schedule = RT_FALSE; + + max_value = (rt_uint16_t)((rt_ubase_t)arg); + if (max_value > RT_SEM_VALUE_MAX || max_value < 1) + { + return -RT_EINVAL; + } + + level = rt_spin_lock_irqsave(&(sem->spinlock)); + if (max_value < sem->value) + { + if (!rt_list_isempty(&sem->parent.suspend_thread)) + { + /* resume all waiting thread */ + _ipc_list_resume_all(&sem->parent.suspend_thread); + need_schedule = RT_TRUE; + } + } + /* set new value */ + sem->max_value = max_value; + rt_spin_unlock_irqrestore(&(sem->spinlock), level); + + if (need_schedule) + { + rt_schedule(); + } + + return RT_EOK; + } + + return -RT_ERROR; +} +RTM_EXPORT(rt_sem_control); + diff --git a/tasks/runtime-rtthread-softtimer-wakeup/template/src/thread.c b/tasks/runtime-rtthread-softtimer-wakeup/template/src/thread.c new file mode 100644 index 00000000..3151c913 --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/template/src/thread.c @@ -0,0 +1,466 @@ +/* + * Copyright (c) 2006-2022, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +#include +#include +#include + +#define DBG_TAG "kernel.thread" +#define DBG_LVL DBG_INFO +#include + +#ifndef __on_rt_thread_inited_hook + #define __on_rt_thread_inited_hook(thread) __ON_HOOK_ARGS(rt_thread_inited_hook, (thread)) +#endif +#ifndef __on_rt_thread_suspend_hook + #define __on_rt_thread_suspend_hook(thread) __ON_HOOK_ARGS(rt_thread_suspend_hook, (thread)) +#endif +#ifndef __on_rt_thread_resume_hook + #define __on_rt_thread_resume_hook(thread) __ON_HOOK_ARGS(rt_thread_resume_hook, (thread)) +#endif + + +static void _thread_exit(void) +{ + struct rt_thread *thread; + rt_base_t level; + + /* get current thread */ + LOG_D("line:%d thread:%s exit\n",__LINE__,rt_thread_self()->parent.name); + thread = rt_thread_self(); + rt_get_thread_struct(thread); + rt_thread_defunct_enqueue(thread); + level = rt_spin_lock_irqsave(&(thread->spinlock)); + rt_timer_detach(&thread->thread_timer); + /* insert to defunct thread list */ + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + LOG_D("line:%d thread:%s exit\n",__LINE__,rt_thread_self()->parent.name); + rt_put_thread_struct(thread); + thread->stat = RT_THREAD_CLOSE; + /* switch to next task */ + rt_schedule(); +} + +static void _thread_timeout(void *parameter) +{ + struct rt_thread *thread; + rt_base_t level; + + thread = (struct rt_thread *)parameter; + + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT((thread->stat & RT_THREAD_SUSPEND_MASK) == RT_THREAD_SUSPEND_MASK); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + level = rt_spin_lock_irqsave(&(thread->spinlock)); + /* set error number */ + thread->error = -RT_ETIMEOUT; + + /* remove from suspend list */ + rt_list_remove(&(thread->tlist)); + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + /* insert to schedule ready list */ + rt_schedule_insert_thread(thread); + /* do schedule */ + rt_schedule(); +} + +static rt_err_t _thread_init(struct rt_thread *thread, + const char *name, + void (*entry)(void *parameter), + void *parameter, + void *stack_start, + rt_uint32_t stack_size, + rt_uint8_t priority, + rt_uint32_t tick) +{ + /* init thread list */ + rt_list_init(&(thread->tlist)); + rt_list_init(&(thread->tlist_schedule)); + +#ifdef RT_USING_MEM_PROTECTION + thread->mem_regions = RT_NULL; +#endif + +#ifdef RT_USING_SMART + thread->wakeup.func = RT_NULL; +#endif + + thread->entry = (void *)entry; + thread->parameter = parameter; + + /* stack init */ + thread->stack_addr = stack_start; + thread->stack_size = stack_size; + + /* init thread stack */ + rt_memset(thread->stack_addr, '#', thread->stack_size); +#ifdef RT_USING_HW_STACK_GUARD + rt_hw_stack_guard_init(thread); +#endif +#ifdef ARCH_CPU_STACK_GROWS_UPWARD + thread->sp = (void *)rt_hw_stack_init(thread->entry, thread->parameter, + (void *)((char *)thread->stack_addr), + (void *)_thread_exit); +#else + thread->sp = (void *)rt_hw_stack_init(thread->entry, thread->parameter, + (rt_uint8_t *)((char *)thread->stack_addr + thread->stack_size - sizeof(rt_ubase_t)), + (void *)_thread_exit); +#endif /* ARCH_CPU_STACK_GROWS_UPWARD */ + + /* priority init */ + RT_ASSERT(priority < RT_THREAD_PRIORITY_MAX); + thread->init_priority = priority; + thread->current_priority = priority; + + thread->number_mask = 0; + +#ifdef RT_USING_MUTEX + rt_list_init(&thread->taken_object_list); + thread->pending_object = RT_NULL; +#endif + +#ifdef RT_USING_EVENT + thread->event_set = 0; + thread->event_info = 0; +#endif /* RT_USING_EVENT */ + +#if RT_THREAD_PRIORITY_MAX > 32 + thread->number = 0; + thread->high_mask = 0; +#endif /* RT_THREAD_PRIORITY_MAX > 32 */ + + /* tick init */ + rt_atomic_store(&thread->init_tick, tick); + rt_atomic_store(&thread->remaining_tick, tick); + + /* error and flags */ + thread->error = RT_EOK; + thread->stat = RT_THREAD_INIT; + +#ifdef RT_USING_SMP + /* not bind on any cpu */ + thread->bind_cpu = RT_CPUS_NR; + thread->oncpu = RT_CPU_DETACHED; + + /* lock init */ + rt_atomic_store(&thread->cpus_lock_nest, 0); + rt_atomic_store(&thread->critical_lock_nest, 0); +#endif /* RT_USING_SMP */ + + /* initialize cleanup function and user data */ + thread->cleanup = 0; + thread->user_data = 0; + + /* initialize thread timer */ + rt_timer_init(&(thread->thread_timer), + thread->parent.name, + _thread_timeout, + thread, + 0, + RT_TIMER_FLAG_ONE_SHOT); + + /* initialize signal */ +#ifdef RT_USING_SIGNALS + thread->sig_mask = 0x00; + thread->sig_pending = 0x00; + +#ifndef RT_USING_SMP + thread->sig_ret = RT_NULL; +#endif /* RT_USING_SMP */ + thread->sig_vectors = RT_NULL; + thread->si_list = RT_NULL; +#endif /* RT_USING_SIGNALS */ + +#ifdef RT_USING_SMART + thread->tid_ref_count = 0; + thread->lwp = RT_NULL; + thread->susp_recycler = RT_NULL; + rt_list_init(&(thread->sibling)); + + /* lwp thread-signal init */ + rt_memset(&thread->signal.sigset_mask, 0, sizeof(lwp_sigset_t)); + rt_memset(&thread->signal.sig_queue.sigset_pending, 0, sizeof(lwp_sigset_t)); + rt_list_init(&thread->signal.sig_queue.siginfo_list); + + rt_memset(&thread->user_ctx, 0, sizeof thread->user_ctx); + + /* initialize user_time and system_time */ + thread->user_time = 0; + thread->system_time = 0; +#endif + +#ifdef RT_USING_CPU_USAGE + thread->duration_tick = 0; +#endif /* RT_USING_CPU_USAGE */ + +#ifdef RT_USING_PTHREADS + thread->pthread_data = RT_NULL; +#endif /* RT_USING_PTHREADS */ + +#ifdef RT_USING_MODULE + thread->parent.module_id = 0; +#endif /* RT_USING_MODULE */ + rt_atomic_store(&thread->ref_count, 0); + rt_spin_lock_init(&thread->spinlock); + + RT_OBJECT_HOOK_CALL(rt_thread_inited_hook, (thread)); + + return RT_EOK; +} + +rt_err_t rt_thread_init(struct rt_thread *thread, + const char *name, + void (*entry)(void *parameter), + void *parameter, + void *stack_start, + rt_uint32_t stack_size, + rt_uint8_t priority, + rt_uint32_t tick) +{ + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(stack_start != RT_NULL); + + /* initialize thread object */ + rt_object_init((rt_object_t)thread, RT_Object_Class_Thread, name); + + return _thread_init(thread, + name, + entry, + parameter, + stack_start, + stack_size, + priority, + tick); +} +RTM_EXPORT(rt_thread_init); + +rt_thread_t rt_thread_self(void) +{ +#ifdef RT_USING_SMP + rt_base_t lock; + rt_thread_t self; + + lock = rt_hw_local_irq_disable(); + self = rt_cpu_self()->current_thread; + rt_hw_local_irq_enable(lock); + return self; +#else + extern rt_thread_t rt_current_thread; + + return rt_current_thread; +#endif /* RT_USING_SMP */ +} +RTM_EXPORT(rt_thread_self); + +rt_err_t rt_thread_startup(rt_thread_t thread) +{ + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT((thread->stat & RT_THREAD_STAT_MASK) == RT_THREAD_INIT); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + + /* calculate priority attribute */ +#if RT_THREAD_PRIORITY_MAX > 32 + thread->number = thread->current_priority >> 3; /* 5bit */ + thread->number_mask = 1L << thread->number; + thread->high_mask = 1L << (thread->current_priority & 0x07); /* 3bit */ +#else + thread->number_mask = 1L << thread->current_priority; +#endif /* RT_THREAD_PRIORITY_MAX > 32 */ + + LOG_D("startup a thread:%s with priority:%d", + thread->parent.name, thread->current_priority); + /* change thread stat */ + thread->stat = RT_THREAD_SUSPEND; + /* then resume it */ + rt_thread_resume(thread); + if (rt_thread_self() != RT_NULL) + { + /* do a scheduling */ + rt_schedule(); + } + + return RT_EOK; +} +RTM_EXPORT(rt_thread_startup); + +rt_err_t rt_thread_sleep(rt_tick_t tick) +{ + rt_base_t level, level_local; + struct rt_thread *thread; + int err; + + if (tick == 0) + { + return -RT_EINVAL; + } + + /* set to current thread */ + thread = rt_thread_self(); + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE); + /* reset thread error */ + thread->error = RT_EOK; + level_local = rt_hw_local_irq_disable(); + /* suspend thread */ + err = rt_thread_suspend_with_flag(thread, RT_INTERRUPTIBLE); + level = rt_spin_lock_irqsave(&(thread->spinlock)); + /* reset the timeout of thread timer and start it */ + if (err == RT_EOK) + { + rt_timer_control(&(thread->thread_timer), RT_TIMER_CTRL_SET_TIME, &tick); + rt_timer_start(&(thread->thread_timer)); + + /* enable interrupt */ + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + rt_hw_local_irq_enable(level_local); + thread->error = -RT_EINTR; + + rt_schedule(); + + /* clear error number of this thread to RT_EOK */ + if (thread->error == -RT_ETIMEOUT) + thread->error = RT_EOK; + } + else + { + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + rt_hw_local_irq_enable(level_local); + } + + return err; +} + +rt_err_t rt_thread_delay(rt_tick_t tick) +{ + return rt_thread_sleep(tick); +} +RTM_EXPORT(rt_thread_delay); + +static void rt_thread_set_suspend_state(struct rt_thread *thread, int suspend_flag) +{ + rt_uint8_t stat = RT_THREAD_SUSPEND_UNINTERRUPTIBLE; + + RT_ASSERT(thread != RT_NULL); + switch (suspend_flag) + { + case RT_INTERRUPTIBLE: + stat = RT_THREAD_SUSPEND_INTERRUPTIBLE; + break; + case RT_KILLABLE: + stat = RT_THREAD_SUSPEND_KILLABLE; + break; + case RT_UNINTERRUPTIBLE: + stat = RT_THREAD_SUSPEND_UNINTERRUPTIBLE; + break; + default: + RT_ASSERT(0); + break; + } + thread->stat = stat | (thread->stat & ~RT_THREAD_STAT_MASK); +} + +rt_err_t rt_thread_suspend_with_flag(rt_thread_t thread, int suspend_flag) +{ + rt_base_t stat; + rt_base_t level; + + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + RT_ASSERT(thread == rt_thread_self()); + + LOG_D("thread suspend: %s", thread->parent.name); + + level = rt_spin_lock_irqsave(&(thread->spinlock)); + + stat = thread->stat & RT_THREAD_STAT_MASK; + if ((stat != RT_THREAD_READY) && (stat != RT_THREAD_RUNNING)) + { + LOG_D("thread suspend: thread disorder, 0x%2x", thread->stat); + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + return -RT_ERROR; + } + + if (stat == RT_THREAD_RUNNING) + { + /* not suspend running status thread on other core */ + RT_ASSERT(thread == rt_thread_self()); + } +#ifdef RT_USING_SMART + if (lwp_thread_signal_suspend_check(thread, suspend_flag) == 0) + { + /* not to suspend */ + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + return -RT_EINTR; + } +#endif + + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + rt_schedule_remove_thread(thread); + level = rt_spin_lock_irqsave(&(thread->spinlock)); + + rt_thread_set_suspend_state(thread, suspend_flag); + + /* stop thread timer anyway */ + rt_timer_stop(&(thread->thread_timer)); + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + + RT_OBJECT_HOOK_CALL(rt_thread_suspend_hook, (thread)); + return RT_EOK; +} +RTM_EXPORT(rt_thread_suspend_with_flag); + +rt_err_t rt_thread_suspend(rt_thread_t thread) +{ + return rt_thread_suspend_with_flag(thread, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_thread_suspend); + +rt_err_t rt_thread_resume(rt_thread_t thread) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + + LOG_D("thread resume: %s", thread->parent.name); + + if ((thread->stat & RT_THREAD_SUSPEND_MASK) != RT_THREAD_SUSPEND_MASK) + { + LOG_D("thread resume: thread disorder, %d", + thread->stat); + + return -RT_ERROR; + } + + level = rt_spin_lock_irqsave(&(thread->spinlock)); //TODO need lock for cpu + + /* remove from suspend list */ + rt_list_remove(&(thread->tlist)); + + rt_timer_stop(&thread->thread_timer); + +#ifdef RT_USING_SMART + thread->wakeup.func = RT_NULL; +#endif + + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + /* insert to schedule ready list */ + rt_schedule_insert_thread(thread); + + RT_OBJECT_HOOK_CALL(rt_thread_resume_hook, (thread)); + return RT_EOK; +} +RTM_EXPORT(rt_thread_resume); + diff --git a/tasks/runtime-rtthread-softtimer-wakeup/template/src/timer.c b/tasks/runtime-rtthread-softtimer-wakeup/template/src/timer.c new file mode 100644 index 00000000..4e9864b0 --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/template/src/timer.c @@ -0,0 +1,612 @@ +/* + * Copyright (c) 2006-2022, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +#include +#include + +#define DBG_TAG "kernel.timer" +#define DBG_LVL DBG_INFO +#include + +/* hard timer list */ +static rt_list_t _timer_list[RT_TIMER_SKIP_LIST_LEVEL]; +static struct rt_spinlock _hard_spinlock; + +#ifdef RT_USING_TIMER_SOFT + +#define RT_SOFT_TIMER_IDLE 1 +#define RT_SOFT_TIMER_BUSY 0 + +#ifndef RT_TIMER_THREAD_STACK_SIZE +#define RT_TIMER_THREAD_STACK_SIZE 512 +#endif /* RT_TIMER_THREAD_STACK_SIZE */ + +#ifndef RT_TIMER_THREAD_PRIO +#define RT_TIMER_THREAD_PRIO 0 +#endif /* RT_TIMER_THREAD_PRIO */ + +/* soft timer status */ +static rt_uint8_t _soft_timer_status = RT_SOFT_TIMER_IDLE; +/* soft timer list */ +static rt_list_t _soft_timer_list[RT_TIMER_SKIP_LIST_LEVEL]; +static struct rt_spinlock _soft_spinlock; +static struct rt_thread _timer_thread; +rt_align(RT_ALIGN_SIZE) +static rt_uint8_t _timer_thread_stack[RT_TIMER_THREAD_STACK_SIZE]; +#endif /* RT_USING_TIMER_SOFT */ + +#ifndef __on_rt_object_take_hook + #define __on_rt_object_take_hook(parent) __ON_HOOK_ARGS(rt_object_take_hook, (parent)) +#endif +#ifndef __on_rt_object_put_hook + #define __on_rt_object_put_hook(parent) __ON_HOOK_ARGS(rt_object_put_hook, (parent)) +#endif +#ifndef __on_rt_timer_enter_hook + #define __on_rt_timer_enter_hook(t) __ON_HOOK_ARGS(rt_timer_enter_hook, (t)) +#endif +#ifndef __on_rt_timer_exit_hook + #define __on_rt_timer_exit_hook(t) __ON_HOOK_ARGS(rt_timer_exit_hook, (t)) +#endif + + +static void _timer_init(rt_timer_t timer, + void (*timeout)(void *parameter), + void *parameter, + rt_tick_t time, + rt_uint8_t flag) +{ + int i; + + /* set flag */ + timer->parent.flag = flag; + + /* set deactivated */ + timer->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + + timer->timeout_func = timeout; + timer->parameter = parameter; + + timer->timeout_tick = 0; + timer->init_tick = time; + + /* initialize timer list */ + for (i = 0; i < RT_TIMER_SKIP_LIST_LEVEL; i++) + { + rt_list_init(&(timer->row[i])); + } +} + +static rt_err_t _timer_list_next_timeout(rt_list_t timer_list[], rt_tick_t *timeout_tick) +{ + struct rt_timer *timer; + + if (!rt_list_isempty(&timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1])) + { + timer = rt_list_entry(timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1].next, + struct rt_timer, row[RT_TIMER_SKIP_LIST_LEVEL - 1]); + *timeout_tick = timer->timeout_tick; + return RT_EOK; + } + return -RT_ERROR; +} + +rt_inline void _timer_remove(rt_timer_t timer) +{ + int i; + + for (i = 0; i < RT_TIMER_SKIP_LIST_LEVEL; i++) + { + rt_list_remove(&timer->row[i]); + } +} + +void rt_timer_init(rt_timer_t timer, + const char *name, + void (*timeout)(void *parameter), + void *parameter, + rt_tick_t time, + rt_uint8_t flag) +{ + /* parameter check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(timeout != RT_NULL); + RT_ASSERT(time < RT_TICK_MAX / 2); + + /* timer object initialization */ + rt_object_init(&(timer->parent), RT_Object_Class_Timer, name); + + _timer_init(timer, timeout, parameter, time, flag); +} +RTM_EXPORT(rt_timer_init); + +rt_err_t rt_timer_detach(rt_timer_t timer) +{ + rt_base_t level; + struct rt_spinlock *spinlock; + + /* parameter check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(rt_object_get_type(&timer->parent) == RT_Object_Class_Timer); + RT_ASSERT(rt_object_is_systemobject(&timer->parent)); + +#ifdef RT_USING_TIMER_SOFT + if (timer->parent.flag & RT_TIMER_FLAG_SOFT_TIMER) + { + spinlock = &_soft_spinlock; + } + else +#endif /* RT_USING_TIMER_SOFT */ + { + spinlock = &_hard_spinlock; + } + + level = rt_spin_lock_irqsave(spinlock); + + _timer_remove(timer); + /* stop timer */ + timer->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + + rt_spin_unlock_irqrestore(spinlock, level); + rt_object_detach(&(timer->parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_timer_detach); + +static rt_err_t _timer_start(rt_list_t *timer_list, rt_timer_t timer) +{ + unsigned int row_lvl; + rt_list_t *row_head[RT_TIMER_SKIP_LIST_LEVEL]; + unsigned int tst_nr; + static unsigned int random_nr; + + /* remove timer from list */ + _timer_remove(timer); + /* change status of timer */ + timer->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(timer->parent))); + + timer->timeout_tick = rt_tick_get() + timer->init_tick; + + row_head[0] = &timer_list[0]; + for (row_lvl = 0; row_lvl < RT_TIMER_SKIP_LIST_LEVEL; row_lvl++) + { + for (; row_head[row_lvl] != timer_list[row_lvl].prev; + row_head[row_lvl] = row_head[row_lvl]->next) + { + struct rt_timer *t; + rt_list_t *p = row_head[row_lvl]->next; + + /* fix up the entry pointer */ + t = rt_list_entry(p, struct rt_timer, row[row_lvl]); + + /* If we have two timers that timeout at the same time, it's + * preferred that the timer inserted early get called early. + * So insert the new timer to the end the the some-timeout timer + * list. + */ + if ((t->timeout_tick - timer->timeout_tick) == 0) + { + continue; + } + else if ((t->timeout_tick - timer->timeout_tick) < RT_TICK_MAX / 2) + { + break; + } + } + if (row_lvl != RT_TIMER_SKIP_LIST_LEVEL - 1) + row_head[row_lvl + 1] = row_head[row_lvl] + 1; + } + + /* Interestingly, this super simple timer insert counter works very very + * well on distributing the list height uniformly. By means of "very very + * well", I mean it beats the randomness of timer->timeout_tick very easily + * (actually, the timeout_tick is not random and easy to be attacked). */ + random_nr++; + tst_nr = random_nr; + + rt_list_insert_after(row_head[RT_TIMER_SKIP_LIST_LEVEL - 1], + &(timer->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + for (row_lvl = 2; row_lvl <= RT_TIMER_SKIP_LIST_LEVEL; row_lvl++) + { + if (!(tst_nr & RT_TIMER_SKIP_LIST_MASK)) + rt_list_insert_after(row_head[RT_TIMER_SKIP_LIST_LEVEL - row_lvl], + &(timer->row[RT_TIMER_SKIP_LIST_LEVEL - row_lvl])); + else + break; + /* Shift over the bits we have tested. Works well with 1 bit and 2 + * bits. */ + tst_nr >>= (RT_TIMER_SKIP_LIST_MASK + 1) >> 1; + } + + timer->parent.flag |= RT_TIMER_FLAG_ACTIVATED; + +#ifdef RT_USING_TIMER_SOFT + if (timer->parent.flag & RT_TIMER_FLAG_SOFT_TIMER) + { + /* check whether timer thread is ready */ + if ((_soft_timer_status == RT_SOFT_TIMER_IDLE) && + ((_timer_thread.stat & RT_THREAD_SUSPEND_MASK) == RT_THREAD_SUSPEND_MASK)) + { + /* resume timer thread to check soft timer */ + rt_thread_resume(&_timer_thread); + } + } +#endif /* RT_USING_TIMER_SOFT */ + + return RT_EOK; +} + +rt_err_t rt_timer_start(rt_timer_t timer) +{ + struct rt_spinlock *spinlock; + rt_list_t *timer_list; + rt_base_t level; + rt_err_t err; + + /* parameter check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(rt_object_get_type(&timer->parent) == RT_Object_Class_Timer); + +#ifdef RT_USING_TIMER_SOFT + if (timer->parent.flag & RT_TIMER_FLAG_SOFT_TIMER) + { + timer_list = _soft_timer_list; + spinlock = &_soft_spinlock; + } + else +#endif /* RT_USING_TIMER_SOFT */ + { + timer_list = _timer_list; + spinlock = &_hard_spinlock; + } + + /* stop timer firstly */ + level = rt_spin_lock_irqsave(spinlock); + err = _timer_start(timer_list, timer); + rt_spin_unlock_irqrestore(spinlock, level); + + return err; +} +RTM_EXPORT(rt_timer_start); + +rt_err_t rt_timer_stop(rt_timer_t timer) +{ + rt_base_t level; + struct rt_spinlock *spinlock; + + /* timer check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(rt_object_get_type(&timer->parent) == RT_Object_Class_Timer); + +#ifdef RT_USING_TIMER_SOFT + if (timer->parent.flag & RT_TIMER_FLAG_SOFT_TIMER) + { + spinlock = &_soft_spinlock; + } + else +#endif /* RT_USING_TIMER_SOFT */ + { + spinlock = &_hard_spinlock; + } + level = rt_spin_lock_irqsave(spinlock); + + if (!(timer->parent.flag & RT_TIMER_FLAG_ACTIVATED)) + { + rt_spin_unlock_irqrestore(spinlock, level); + return -RT_ERROR; + } + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(timer->parent))); + + _timer_remove(timer); + /* change status */ + timer->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + rt_spin_unlock_irqrestore(spinlock, level); + + return RT_EOK; +} +RTM_EXPORT(rt_timer_stop); + +rt_err_t rt_timer_control(rt_timer_t timer, int cmd, void *arg) +{ + /* parameter check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(rt_object_get_type(&timer->parent) == RT_Object_Class_Timer); + + switch (cmd) + { + case RT_TIMER_CTRL_GET_TIME: + *(rt_tick_t *)arg = timer->init_tick; + break; + + case RT_TIMER_CTRL_SET_TIME: + RT_ASSERT((*(rt_tick_t *)arg) < RT_TICK_MAX / 2); + timer->init_tick = *(rt_tick_t *)arg; + break; + + case RT_TIMER_CTRL_SET_ONESHOT: + timer->parent.flag &= ~RT_TIMER_FLAG_PERIODIC; + break; + + case RT_TIMER_CTRL_SET_PERIODIC: + timer->parent.flag |= RT_TIMER_FLAG_PERIODIC; + break; + + case RT_TIMER_CTRL_GET_STATE: + if(timer->parent.flag & RT_TIMER_FLAG_ACTIVATED) + { + /*timer is start and run*/ + *(rt_uint32_t *)arg = RT_TIMER_FLAG_ACTIVATED; + } + else + { + /*timer is stop*/ + *(rt_uint32_t *)arg = RT_TIMER_FLAG_DEACTIVATED; + } + break; + + case RT_TIMER_CTRL_GET_REMAIN_TIME: + *(rt_tick_t *)arg = timer->timeout_tick; + break; + case RT_TIMER_CTRL_GET_FUNC: + *(void **)arg = (void *)timer->timeout_func; + break; + + case RT_TIMER_CTRL_SET_FUNC: + timer->timeout_func = (void (*)(void*))arg; + break; + + case RT_TIMER_CTRL_GET_PARM: + *(void **)arg = timer->parameter; + break; + + case RT_TIMER_CTRL_SET_PARM: + timer->parameter = arg; + break; + + default: + break; + } + + return RT_EOK; +} +RTM_EXPORT(rt_timer_control); + +void rt_timer_check(void) +{ + struct rt_timer *t; + rt_tick_t current_tick; + rt_base_t level; + rt_list_t list; + +#ifdef RT_USING_SMP + if (rt_hw_cpu_id() != 0) + { + return; + } +#endif + + rt_list_init(&list); + + LOG_D("timer check enter"); + + current_tick = rt_tick_get(); + + level = rt_spin_lock_irqsave(&_hard_spinlock); + + while (!rt_list_isempty(&_timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1])) + { + t = rt_list_entry(_timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1].next, + struct rt_timer, row[RT_TIMER_SKIP_LIST_LEVEL - 1]); + + /* + * It supposes that the new tick shall less than the half duration of + * tick max. + */ + if ((current_tick - t->timeout_tick) < RT_TICK_MAX / 2) + { + RT_OBJECT_HOOK_CALL(rt_timer_enter_hook, (t)); + + /* remove timer from timer list firstly */ + _timer_remove(t); + if (!(t->parent.flag & RT_TIMER_FLAG_PERIODIC)) + { + t->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + } + /* add timer to temporary list */ + rt_list_insert_after(&list, &(t->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + rt_spin_unlock_irqrestore(&_hard_spinlock, level); + /* call timeout function */ + t->timeout_func(t->parameter); + + /* re-get tick */ + current_tick = rt_tick_get(); + + RT_OBJECT_HOOK_CALL(rt_timer_exit_hook, (t)); + LOG_D("current tick: %d", current_tick); + level = rt_spin_lock_irqsave(&_hard_spinlock); + /* Check whether the timer object is detached or started again */ + if (rt_list_isempty(&list)) + { + continue; + } + rt_list_remove(&(t->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + if ((t->parent.flag & RT_TIMER_FLAG_PERIODIC) && + (t->parent.flag & RT_TIMER_FLAG_ACTIVATED)) + { + /* start it */ + t->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + _timer_start(_timer_list, t); + } + } + else break; + } + rt_spin_unlock_irqrestore(&_hard_spinlock, level); + LOG_D("timer check leave"); +} + +rt_tick_t rt_timer_next_timeout_tick(void) +{ + rt_base_t level; + rt_tick_t next_timeout = RT_TICK_MAX; + + level = rt_spin_lock_irqsave(&_hard_spinlock); + _timer_list_next_timeout(_timer_list, &next_timeout); + rt_spin_unlock_irqrestore(&_hard_spinlock, level); + + return next_timeout; +} + +void rt_soft_timer_check(void) +{ + rt_tick_t current_tick; + struct rt_timer *t; + rt_base_t level; + rt_list_t list; + + rt_list_init(&list); + LOG_D("software timer check enter"); + level = rt_spin_lock_irqsave(&_soft_spinlock); + + while (!rt_list_isempty(&_soft_timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1])) + { + t = rt_list_entry(_soft_timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1].next, + struct rt_timer, row[RT_TIMER_SKIP_LIST_LEVEL - 1]); + + current_tick = rt_tick_get(); + + /* + * It supposes that the new tick shall less than the half duration of + * tick max. + */ + if ((current_tick - t->timeout_tick) < RT_TICK_MAX / 2) + { + RT_OBJECT_HOOK_CALL(rt_timer_enter_hook, (t)); + + /* remove timer from timer list firstly */ + _timer_remove(t); + if (!(t->parent.flag & RT_TIMER_FLAG_PERIODIC)) + { + t->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + } + /* add timer to temporary list */ + rt_list_insert_after(&list, &(t->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + + _soft_timer_status = RT_SOFT_TIMER_BUSY; + + rt_spin_unlock_irqrestore(&_soft_spinlock, level); + + /* call timeout function */ + t->timeout_func(t->parameter); + + RT_OBJECT_HOOK_CALL(rt_timer_exit_hook, (t)); + LOG_D("current tick: %d", current_tick); + + level = rt_spin_lock_irqsave(&_soft_spinlock); + + _soft_timer_status = RT_SOFT_TIMER_IDLE; + /* Check whether the timer object is detached or started again */ + if (rt_list_isempty(&list)) + { + continue; + } + rt_list_remove(&(t->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + if ((t->parent.flag & RT_TIMER_FLAG_PERIODIC) && + (t->parent.flag & RT_TIMER_FLAG_ACTIVATED)) + { + /* start it */ + t->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + _timer_start(_soft_timer_list, t); + } + } + else break; /* not check anymore */ + } + + rt_spin_unlock_irqrestore(&_soft_spinlock, level); + + LOG_D("software timer check leave"); +} + +static void _timer_thread_entry(void *parameter) +{ + rt_err_t ret = RT_ERROR; + rt_tick_t next_timeout; + rt_base_t level; + + while (1) + { + /* get the next timeout tick */ + level = rt_spin_lock_irqsave(&_soft_spinlock); + ret = _timer_list_next_timeout(_soft_timer_list, &next_timeout); + rt_spin_unlock_irqrestore(&_soft_spinlock, level); + + if (ret != RT_EOK) + { + /* no software timer exist, suspend self. */ + rt_thread_suspend_with_flag(rt_thread_self(), RT_UNINTERRUPTIBLE); + rt_schedule(); + } + else + { + rt_tick_t current_tick; + + /* get current tick */ + current_tick = rt_tick_get(); + + if ((next_timeout - current_tick) < RT_TICK_MAX / 2) + { + /* get the delta timeout tick */ + next_timeout = next_timeout - current_tick; + rt_thread_delay(next_timeout); + } + } + + /* check software timer */ + rt_soft_timer_check(); + } +} + +void rt_system_timer_init(void) +{ + rt_size_t i; + + for (i = 0; i < sizeof(_timer_list) / sizeof(_timer_list[0]); i++) + { + rt_list_init(_timer_list + i); + } + rt_spin_lock_init(&_hard_spinlock); +} + +void rt_system_timer_thread_init(void) +{ +#ifdef RT_USING_TIMER_SOFT + int i; + + for (i = 0; + i < sizeof(_soft_timer_list) / sizeof(_soft_timer_list[0]); + i++) + { + rt_list_init(_soft_timer_list + i); + } + rt_spin_lock_init(&_soft_spinlock); + + /* start software timer thread */ + rt_thread_init(&_timer_thread, + "timer", + _timer_thread_entry, + RT_NULL, + &_timer_thread_stack[0], + sizeof(_timer_thread_stack), + RT_TIMER_THREAD_PRIO, + 10); + + /* startup */ + rt_thread_startup(&_timer_thread); +#endif /* RT_USING_TIMER_SOFT */ +} + diff --git a/tasks/runtime-rtthread-softtimer-wakeup/timer_only/src/thread.c b/tasks/runtime-rtthread-softtimer-wakeup/timer_only/src/thread.c new file mode 100644 index 00000000..3151c913 --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/timer_only/src/thread.c @@ -0,0 +1,466 @@ +/* + * Copyright (c) 2006-2022, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +#include +#include +#include + +#define DBG_TAG "kernel.thread" +#define DBG_LVL DBG_INFO +#include + +#ifndef __on_rt_thread_inited_hook + #define __on_rt_thread_inited_hook(thread) __ON_HOOK_ARGS(rt_thread_inited_hook, (thread)) +#endif +#ifndef __on_rt_thread_suspend_hook + #define __on_rt_thread_suspend_hook(thread) __ON_HOOK_ARGS(rt_thread_suspend_hook, (thread)) +#endif +#ifndef __on_rt_thread_resume_hook + #define __on_rt_thread_resume_hook(thread) __ON_HOOK_ARGS(rt_thread_resume_hook, (thread)) +#endif + + +static void _thread_exit(void) +{ + struct rt_thread *thread; + rt_base_t level; + + /* get current thread */ + LOG_D("line:%d thread:%s exit\n",__LINE__,rt_thread_self()->parent.name); + thread = rt_thread_self(); + rt_get_thread_struct(thread); + rt_thread_defunct_enqueue(thread); + level = rt_spin_lock_irqsave(&(thread->spinlock)); + rt_timer_detach(&thread->thread_timer); + /* insert to defunct thread list */ + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + LOG_D("line:%d thread:%s exit\n",__LINE__,rt_thread_self()->parent.name); + rt_put_thread_struct(thread); + thread->stat = RT_THREAD_CLOSE; + /* switch to next task */ + rt_schedule(); +} + +static void _thread_timeout(void *parameter) +{ + struct rt_thread *thread; + rt_base_t level; + + thread = (struct rt_thread *)parameter; + + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT((thread->stat & RT_THREAD_SUSPEND_MASK) == RT_THREAD_SUSPEND_MASK); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + level = rt_spin_lock_irqsave(&(thread->spinlock)); + /* set error number */ + thread->error = -RT_ETIMEOUT; + + /* remove from suspend list */ + rt_list_remove(&(thread->tlist)); + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + /* insert to schedule ready list */ + rt_schedule_insert_thread(thread); + /* do schedule */ + rt_schedule(); +} + +static rt_err_t _thread_init(struct rt_thread *thread, + const char *name, + void (*entry)(void *parameter), + void *parameter, + void *stack_start, + rt_uint32_t stack_size, + rt_uint8_t priority, + rt_uint32_t tick) +{ + /* init thread list */ + rt_list_init(&(thread->tlist)); + rt_list_init(&(thread->tlist_schedule)); + +#ifdef RT_USING_MEM_PROTECTION + thread->mem_regions = RT_NULL; +#endif + +#ifdef RT_USING_SMART + thread->wakeup.func = RT_NULL; +#endif + + thread->entry = (void *)entry; + thread->parameter = parameter; + + /* stack init */ + thread->stack_addr = stack_start; + thread->stack_size = stack_size; + + /* init thread stack */ + rt_memset(thread->stack_addr, '#', thread->stack_size); +#ifdef RT_USING_HW_STACK_GUARD + rt_hw_stack_guard_init(thread); +#endif +#ifdef ARCH_CPU_STACK_GROWS_UPWARD + thread->sp = (void *)rt_hw_stack_init(thread->entry, thread->parameter, + (void *)((char *)thread->stack_addr), + (void *)_thread_exit); +#else + thread->sp = (void *)rt_hw_stack_init(thread->entry, thread->parameter, + (rt_uint8_t *)((char *)thread->stack_addr + thread->stack_size - sizeof(rt_ubase_t)), + (void *)_thread_exit); +#endif /* ARCH_CPU_STACK_GROWS_UPWARD */ + + /* priority init */ + RT_ASSERT(priority < RT_THREAD_PRIORITY_MAX); + thread->init_priority = priority; + thread->current_priority = priority; + + thread->number_mask = 0; + +#ifdef RT_USING_MUTEX + rt_list_init(&thread->taken_object_list); + thread->pending_object = RT_NULL; +#endif + +#ifdef RT_USING_EVENT + thread->event_set = 0; + thread->event_info = 0; +#endif /* RT_USING_EVENT */ + +#if RT_THREAD_PRIORITY_MAX > 32 + thread->number = 0; + thread->high_mask = 0; +#endif /* RT_THREAD_PRIORITY_MAX > 32 */ + + /* tick init */ + rt_atomic_store(&thread->init_tick, tick); + rt_atomic_store(&thread->remaining_tick, tick); + + /* error and flags */ + thread->error = RT_EOK; + thread->stat = RT_THREAD_INIT; + +#ifdef RT_USING_SMP + /* not bind on any cpu */ + thread->bind_cpu = RT_CPUS_NR; + thread->oncpu = RT_CPU_DETACHED; + + /* lock init */ + rt_atomic_store(&thread->cpus_lock_nest, 0); + rt_atomic_store(&thread->critical_lock_nest, 0); +#endif /* RT_USING_SMP */ + + /* initialize cleanup function and user data */ + thread->cleanup = 0; + thread->user_data = 0; + + /* initialize thread timer */ + rt_timer_init(&(thread->thread_timer), + thread->parent.name, + _thread_timeout, + thread, + 0, + RT_TIMER_FLAG_ONE_SHOT); + + /* initialize signal */ +#ifdef RT_USING_SIGNALS + thread->sig_mask = 0x00; + thread->sig_pending = 0x00; + +#ifndef RT_USING_SMP + thread->sig_ret = RT_NULL; +#endif /* RT_USING_SMP */ + thread->sig_vectors = RT_NULL; + thread->si_list = RT_NULL; +#endif /* RT_USING_SIGNALS */ + +#ifdef RT_USING_SMART + thread->tid_ref_count = 0; + thread->lwp = RT_NULL; + thread->susp_recycler = RT_NULL; + rt_list_init(&(thread->sibling)); + + /* lwp thread-signal init */ + rt_memset(&thread->signal.sigset_mask, 0, sizeof(lwp_sigset_t)); + rt_memset(&thread->signal.sig_queue.sigset_pending, 0, sizeof(lwp_sigset_t)); + rt_list_init(&thread->signal.sig_queue.siginfo_list); + + rt_memset(&thread->user_ctx, 0, sizeof thread->user_ctx); + + /* initialize user_time and system_time */ + thread->user_time = 0; + thread->system_time = 0; +#endif + +#ifdef RT_USING_CPU_USAGE + thread->duration_tick = 0; +#endif /* RT_USING_CPU_USAGE */ + +#ifdef RT_USING_PTHREADS + thread->pthread_data = RT_NULL; +#endif /* RT_USING_PTHREADS */ + +#ifdef RT_USING_MODULE + thread->parent.module_id = 0; +#endif /* RT_USING_MODULE */ + rt_atomic_store(&thread->ref_count, 0); + rt_spin_lock_init(&thread->spinlock); + + RT_OBJECT_HOOK_CALL(rt_thread_inited_hook, (thread)); + + return RT_EOK; +} + +rt_err_t rt_thread_init(struct rt_thread *thread, + const char *name, + void (*entry)(void *parameter), + void *parameter, + void *stack_start, + rt_uint32_t stack_size, + rt_uint8_t priority, + rt_uint32_t tick) +{ + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(stack_start != RT_NULL); + + /* initialize thread object */ + rt_object_init((rt_object_t)thread, RT_Object_Class_Thread, name); + + return _thread_init(thread, + name, + entry, + parameter, + stack_start, + stack_size, + priority, + tick); +} +RTM_EXPORT(rt_thread_init); + +rt_thread_t rt_thread_self(void) +{ +#ifdef RT_USING_SMP + rt_base_t lock; + rt_thread_t self; + + lock = rt_hw_local_irq_disable(); + self = rt_cpu_self()->current_thread; + rt_hw_local_irq_enable(lock); + return self; +#else + extern rt_thread_t rt_current_thread; + + return rt_current_thread; +#endif /* RT_USING_SMP */ +} +RTM_EXPORT(rt_thread_self); + +rt_err_t rt_thread_startup(rt_thread_t thread) +{ + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT((thread->stat & RT_THREAD_STAT_MASK) == RT_THREAD_INIT); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + + /* calculate priority attribute */ +#if RT_THREAD_PRIORITY_MAX > 32 + thread->number = thread->current_priority >> 3; /* 5bit */ + thread->number_mask = 1L << thread->number; + thread->high_mask = 1L << (thread->current_priority & 0x07); /* 3bit */ +#else + thread->number_mask = 1L << thread->current_priority; +#endif /* RT_THREAD_PRIORITY_MAX > 32 */ + + LOG_D("startup a thread:%s with priority:%d", + thread->parent.name, thread->current_priority); + /* change thread stat */ + thread->stat = RT_THREAD_SUSPEND; + /* then resume it */ + rt_thread_resume(thread); + if (rt_thread_self() != RT_NULL) + { + /* do a scheduling */ + rt_schedule(); + } + + return RT_EOK; +} +RTM_EXPORT(rt_thread_startup); + +rt_err_t rt_thread_sleep(rt_tick_t tick) +{ + rt_base_t level, level_local; + struct rt_thread *thread; + int err; + + if (tick == 0) + { + return -RT_EINVAL; + } + + /* set to current thread */ + thread = rt_thread_self(); + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE); + /* reset thread error */ + thread->error = RT_EOK; + level_local = rt_hw_local_irq_disable(); + /* suspend thread */ + err = rt_thread_suspend_with_flag(thread, RT_INTERRUPTIBLE); + level = rt_spin_lock_irqsave(&(thread->spinlock)); + /* reset the timeout of thread timer and start it */ + if (err == RT_EOK) + { + rt_timer_control(&(thread->thread_timer), RT_TIMER_CTRL_SET_TIME, &tick); + rt_timer_start(&(thread->thread_timer)); + + /* enable interrupt */ + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + rt_hw_local_irq_enable(level_local); + thread->error = -RT_EINTR; + + rt_schedule(); + + /* clear error number of this thread to RT_EOK */ + if (thread->error == -RT_ETIMEOUT) + thread->error = RT_EOK; + } + else + { + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + rt_hw_local_irq_enable(level_local); + } + + return err; +} + +rt_err_t rt_thread_delay(rt_tick_t tick) +{ + return rt_thread_sleep(tick); +} +RTM_EXPORT(rt_thread_delay); + +static void rt_thread_set_suspend_state(struct rt_thread *thread, int suspend_flag) +{ + rt_uint8_t stat = RT_THREAD_SUSPEND_UNINTERRUPTIBLE; + + RT_ASSERT(thread != RT_NULL); + switch (suspend_flag) + { + case RT_INTERRUPTIBLE: + stat = RT_THREAD_SUSPEND_INTERRUPTIBLE; + break; + case RT_KILLABLE: + stat = RT_THREAD_SUSPEND_KILLABLE; + break; + case RT_UNINTERRUPTIBLE: + stat = RT_THREAD_SUSPEND_UNINTERRUPTIBLE; + break; + default: + RT_ASSERT(0); + break; + } + thread->stat = stat | (thread->stat & ~RT_THREAD_STAT_MASK); +} + +rt_err_t rt_thread_suspend_with_flag(rt_thread_t thread, int suspend_flag) +{ + rt_base_t stat; + rt_base_t level; + + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + RT_ASSERT(thread == rt_thread_self()); + + LOG_D("thread suspend: %s", thread->parent.name); + + level = rt_spin_lock_irqsave(&(thread->spinlock)); + + stat = thread->stat & RT_THREAD_STAT_MASK; + if ((stat != RT_THREAD_READY) && (stat != RT_THREAD_RUNNING)) + { + LOG_D("thread suspend: thread disorder, 0x%2x", thread->stat); + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + return -RT_ERROR; + } + + if (stat == RT_THREAD_RUNNING) + { + /* not suspend running status thread on other core */ + RT_ASSERT(thread == rt_thread_self()); + } +#ifdef RT_USING_SMART + if (lwp_thread_signal_suspend_check(thread, suspend_flag) == 0) + { + /* not to suspend */ + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + return -RT_EINTR; + } +#endif + + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + rt_schedule_remove_thread(thread); + level = rt_spin_lock_irqsave(&(thread->spinlock)); + + rt_thread_set_suspend_state(thread, suspend_flag); + + /* stop thread timer anyway */ + rt_timer_stop(&(thread->thread_timer)); + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + + RT_OBJECT_HOOK_CALL(rt_thread_suspend_hook, (thread)); + return RT_EOK; +} +RTM_EXPORT(rt_thread_suspend_with_flag); + +rt_err_t rt_thread_suspend(rt_thread_t thread) +{ + return rt_thread_suspend_with_flag(thread, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_thread_suspend); + +rt_err_t rt_thread_resume(rt_thread_t thread) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + + LOG_D("thread resume: %s", thread->parent.name); + + if ((thread->stat & RT_THREAD_SUSPEND_MASK) != RT_THREAD_SUSPEND_MASK) + { + LOG_D("thread resume: thread disorder, %d", + thread->stat); + + return -RT_ERROR; + } + + level = rt_spin_lock_irqsave(&(thread->spinlock)); //TODO need lock for cpu + + /* remove from suspend list */ + rt_list_remove(&(thread->tlist)); + + rt_timer_stop(&thread->thread_timer); + +#ifdef RT_USING_SMART + thread->wakeup.func = RT_NULL; +#endif + + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + /* insert to schedule ready list */ + rt_schedule_insert_thread(thread); + + RT_OBJECT_HOOK_CALL(rt_thread_resume_hook, (thread)); + return RT_EOK; +} +RTM_EXPORT(rt_thread_resume); + diff --git a/tasks/runtime-rtthread-softtimer-wakeup/timer_only/src/timer.c b/tasks/runtime-rtthread-softtimer-wakeup/timer_only/src/timer.c new file mode 100644 index 00000000..9c2d073a --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/timer_only/src/timer.c @@ -0,0 +1,611 @@ +/* + * Copyright (c) 2006-2022, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +#include +#include + +#define DBG_TAG "kernel.timer" +#define DBG_LVL DBG_INFO +#include + +/* hard timer list */ +static rt_list_t _timer_list[RT_TIMER_SKIP_LIST_LEVEL]; +static struct rt_spinlock _hard_spinlock; + +#ifdef RT_USING_TIMER_SOFT + +#define RT_SOFT_TIMER_IDLE 1 +#define RT_SOFT_TIMER_BUSY 0 + +#ifndef RT_TIMER_THREAD_STACK_SIZE +#define RT_TIMER_THREAD_STACK_SIZE 512 +#endif /* RT_TIMER_THREAD_STACK_SIZE */ + +#ifndef RT_TIMER_THREAD_PRIO +#define RT_TIMER_THREAD_PRIO 0 +#endif /* RT_TIMER_THREAD_PRIO */ + +/* soft timer status */ +static rt_uint8_t _soft_timer_status = RT_SOFT_TIMER_IDLE; +/* soft timer list */ +static rt_list_t _soft_timer_list[RT_TIMER_SKIP_LIST_LEVEL]; +static struct rt_spinlock _soft_spinlock; +static struct rt_thread _timer_thread; +static struct rt_semaphore _soft_timer_sem; +rt_align(RT_ALIGN_SIZE) +static rt_uint8_t _timer_thread_stack[RT_TIMER_THREAD_STACK_SIZE]; +#endif /* RT_USING_TIMER_SOFT */ + +#ifndef __on_rt_object_take_hook + #define __on_rt_object_take_hook(parent) __ON_HOOK_ARGS(rt_object_take_hook, (parent)) +#endif +#ifndef __on_rt_object_put_hook + #define __on_rt_object_put_hook(parent) __ON_HOOK_ARGS(rt_object_put_hook, (parent)) +#endif +#ifndef __on_rt_timer_enter_hook + #define __on_rt_timer_enter_hook(t) __ON_HOOK_ARGS(rt_timer_enter_hook, (t)) +#endif +#ifndef __on_rt_timer_exit_hook + #define __on_rt_timer_exit_hook(t) __ON_HOOK_ARGS(rt_timer_exit_hook, (t)) +#endif + + +static void _timer_init(rt_timer_t timer, + void (*timeout)(void *parameter), + void *parameter, + rt_tick_t time, + rt_uint8_t flag) +{ + int i; + + /* set flag */ + timer->parent.flag = flag; + + /* set deactivated */ + timer->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + + timer->timeout_func = timeout; + timer->parameter = parameter; + + timer->timeout_tick = 0; + timer->init_tick = time; + + /* initialize timer list */ + for (i = 0; i < RT_TIMER_SKIP_LIST_LEVEL; i++) + { + rt_list_init(&(timer->row[i])); + } +} + +static rt_err_t _timer_list_next_timeout(rt_list_t timer_list[], rt_tick_t *timeout_tick) +{ + struct rt_timer *timer; + + if (!rt_list_isempty(&timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1])) + { + timer = rt_list_entry(timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1].next, + struct rt_timer, row[RT_TIMER_SKIP_LIST_LEVEL - 1]); + *timeout_tick = timer->timeout_tick; + return RT_EOK; + } + return -RT_ERROR; +} + +rt_inline void _timer_remove(rt_timer_t timer) +{ + int i; + + for (i = 0; i < RT_TIMER_SKIP_LIST_LEVEL; i++) + { + rt_list_remove(&timer->row[i]); + } +} + +void rt_timer_init(rt_timer_t timer, + const char *name, + void (*timeout)(void *parameter), + void *parameter, + rt_tick_t time, + rt_uint8_t flag) +{ + /* parameter check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(timeout != RT_NULL); + RT_ASSERT(time < RT_TICK_MAX / 2); + + /* timer object initialization */ + rt_object_init(&(timer->parent), RT_Object_Class_Timer, name); + + _timer_init(timer, timeout, parameter, time, flag); +} +RTM_EXPORT(rt_timer_init); + +rt_err_t rt_timer_detach(rt_timer_t timer) +{ + rt_base_t level; + struct rt_spinlock *spinlock; + + /* parameter check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(rt_object_get_type(&timer->parent) == RT_Object_Class_Timer); + RT_ASSERT(rt_object_is_systemobject(&timer->parent)); + +#ifdef RT_USING_TIMER_SOFT + if (timer->parent.flag & RT_TIMER_FLAG_SOFT_TIMER) + { + spinlock = &_soft_spinlock; + } + else +#endif /* RT_USING_TIMER_SOFT */ + { + spinlock = &_hard_spinlock; + } + + level = rt_spin_lock_irqsave(spinlock); + + _timer_remove(timer); + /* stop timer */ + timer->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + + rt_spin_unlock_irqrestore(spinlock, level); + rt_object_detach(&(timer->parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_timer_detach); + +static rt_err_t _timer_start(rt_list_t *timer_list, rt_timer_t timer) +{ + unsigned int row_lvl; + rt_list_t *row_head[RT_TIMER_SKIP_LIST_LEVEL]; + unsigned int tst_nr; + static unsigned int random_nr; + + /* remove timer from list */ + _timer_remove(timer); + /* change status of timer */ + timer->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(timer->parent))); + + timer->timeout_tick = rt_tick_get() + timer->init_tick; + + row_head[0] = &timer_list[0]; + for (row_lvl = 0; row_lvl < RT_TIMER_SKIP_LIST_LEVEL; row_lvl++) + { + for (; row_head[row_lvl] != timer_list[row_lvl].prev; + row_head[row_lvl] = row_head[row_lvl]->next) + { + struct rt_timer *t; + rt_list_t *p = row_head[row_lvl]->next; + + /* fix up the entry pointer */ + t = rt_list_entry(p, struct rt_timer, row[row_lvl]); + + /* If we have two timers that timeout at the same time, it's + * preferred that the timer inserted early get called early. + * So insert the new timer to the end the the some-timeout timer + * list. + */ + if ((t->timeout_tick - timer->timeout_tick) == 0) + { + continue; + } + else if ((t->timeout_tick - timer->timeout_tick) < RT_TICK_MAX / 2) + { + break; + } + } + if (row_lvl != RT_TIMER_SKIP_LIST_LEVEL - 1) + row_head[row_lvl + 1] = row_head[row_lvl] + 1; + } + + /* Interestingly, this super simple timer insert counter works very very + * well on distributing the list height uniformly. By means of "very very + * well", I mean it beats the randomness of timer->timeout_tick very easily + * (actually, the timeout_tick is not random and easy to be attacked). */ + random_nr++; + tst_nr = random_nr; + + rt_list_insert_after(row_head[RT_TIMER_SKIP_LIST_LEVEL - 1], + &(timer->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + for (row_lvl = 2; row_lvl <= RT_TIMER_SKIP_LIST_LEVEL; row_lvl++) + { + if (!(tst_nr & RT_TIMER_SKIP_LIST_MASK)) + rt_list_insert_after(row_head[RT_TIMER_SKIP_LIST_LEVEL - row_lvl], + &(timer->row[RT_TIMER_SKIP_LIST_LEVEL - row_lvl])); + else + break; + /* Shift over the bits we have tested. Works well with 1 bit and 2 + * bits. */ + tst_nr >>= (RT_TIMER_SKIP_LIST_MASK + 1) >> 1; + } + + timer->parent.flag |= RT_TIMER_FLAG_ACTIVATED; + + return RT_EOK; +} + +rt_err_t rt_timer_start(rt_timer_t timer) +{ + struct rt_spinlock *spinlock; + rt_list_t *timer_list; + rt_base_t level; + rt_err_t err; + + /* parameter check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(rt_object_get_type(&timer->parent) == RT_Object_Class_Timer); + +#ifdef RT_USING_TIMER_SOFT + if (timer->parent.flag & RT_TIMER_FLAG_SOFT_TIMER) + { + timer_list = _soft_timer_list; + spinlock = &_soft_spinlock; + } + else +#endif /* RT_USING_TIMER_SOFT */ + { + timer_list = _timer_list; + spinlock = &_hard_spinlock; + } + + level = rt_spin_lock_irqsave(spinlock); + + err = _timer_start(timer_list, timer); + +#ifdef RT_USING_TIMER_SOFT + if (err == RT_EOK) + { + if (timer->parent.flag & RT_TIMER_FLAG_SOFT_TIMER) + { + rt_sem_release(&_soft_timer_sem); + } + } +#endif /* RT_USING_TIMER_SOFT */ + + rt_spin_unlock_irqrestore(spinlock, level); + + return err; +} +RTM_EXPORT(rt_timer_start); + +rt_err_t rt_timer_stop(rt_timer_t timer) +{ + rt_base_t level; + struct rt_spinlock *spinlock; + + /* timer check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(rt_object_get_type(&timer->parent) == RT_Object_Class_Timer); + +#ifdef RT_USING_TIMER_SOFT + if (timer->parent.flag & RT_TIMER_FLAG_SOFT_TIMER) + { + spinlock = &_soft_spinlock; + } + else +#endif /* RT_USING_TIMER_SOFT */ + { + spinlock = &_hard_spinlock; + } + level = rt_spin_lock_irqsave(spinlock); + + if (!(timer->parent.flag & RT_TIMER_FLAG_ACTIVATED)) + { + rt_spin_unlock_irqrestore(spinlock, level); + return -RT_ERROR; + } + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(timer->parent))); + + _timer_remove(timer); + /* change status */ + timer->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + rt_spin_unlock_irqrestore(spinlock, level); + + return RT_EOK; +} +RTM_EXPORT(rt_timer_stop); + +rt_err_t rt_timer_control(rt_timer_t timer, int cmd, void *arg) +{ + /* parameter check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(rt_object_get_type(&timer->parent) == RT_Object_Class_Timer); + + switch (cmd) + { + case RT_TIMER_CTRL_GET_TIME: + *(rt_tick_t *)arg = timer->init_tick; + break; + + case RT_TIMER_CTRL_SET_TIME: + RT_ASSERT((*(rt_tick_t *)arg) < RT_TICK_MAX / 2); + timer->init_tick = *(rt_tick_t *)arg; + break; + + case RT_TIMER_CTRL_SET_ONESHOT: + timer->parent.flag &= ~RT_TIMER_FLAG_PERIODIC; + break; + + case RT_TIMER_CTRL_SET_PERIODIC: + timer->parent.flag |= RT_TIMER_FLAG_PERIODIC; + break; + + case RT_TIMER_CTRL_GET_STATE: + if(timer->parent.flag & RT_TIMER_FLAG_ACTIVATED) + { + /*timer is start and run*/ + *(rt_uint32_t *)arg = RT_TIMER_FLAG_ACTIVATED; + } + else + { + /*timer is stop*/ + *(rt_uint32_t *)arg = RT_TIMER_FLAG_DEACTIVATED; + } + break; + + case RT_TIMER_CTRL_GET_REMAIN_TIME: + *(rt_tick_t *)arg = timer->timeout_tick; + break; + case RT_TIMER_CTRL_GET_FUNC: + *(void **)arg = (void *)timer->timeout_func; + break; + + case RT_TIMER_CTRL_SET_FUNC: + timer->timeout_func = (void (*)(void*))arg; + break; + + case RT_TIMER_CTRL_GET_PARM: + *(void **)arg = timer->parameter; + break; + + case RT_TIMER_CTRL_SET_PARM: + timer->parameter = arg; + break; + + default: + break; + } + + return RT_EOK; +} +RTM_EXPORT(rt_timer_control); + +void rt_timer_check(void) +{ + struct rt_timer *t; + rt_tick_t current_tick; + rt_base_t level; + rt_list_t list; + +#ifdef RT_USING_SMP + if (rt_hw_cpu_id() != 0) + { + return; + } +#endif + + rt_list_init(&list); + + LOG_D("timer check enter"); + + current_tick = rt_tick_get(); + + level = rt_spin_lock_irqsave(&_hard_spinlock); + + while (!rt_list_isempty(&_timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1])) + { + t = rt_list_entry(_timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1].next, + struct rt_timer, row[RT_TIMER_SKIP_LIST_LEVEL - 1]); + + /* + * It supposes that the new tick shall less than the half duration of + * tick max. + */ + if ((current_tick - t->timeout_tick) < RT_TICK_MAX / 2) + { + RT_OBJECT_HOOK_CALL(rt_timer_enter_hook, (t)); + + /* remove timer from timer list firstly */ + _timer_remove(t); + if (!(t->parent.flag & RT_TIMER_FLAG_PERIODIC)) + { + t->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + } + /* add timer to temporary list */ + rt_list_insert_after(&list, &(t->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + rt_spin_unlock_irqrestore(&_hard_spinlock, level); + /* call timeout function */ + t->timeout_func(t->parameter); + + /* re-get tick */ + current_tick = rt_tick_get(); + + RT_OBJECT_HOOK_CALL(rt_timer_exit_hook, (t)); + LOG_D("current tick: %d", current_tick); + level = rt_spin_lock_irqsave(&_hard_spinlock); + /* Check whether the timer object is detached or started again */ + if (rt_list_isempty(&list)) + { + continue; + } + rt_list_remove(&(t->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + if ((t->parent.flag & RT_TIMER_FLAG_PERIODIC) && + (t->parent.flag & RT_TIMER_FLAG_ACTIVATED)) + { + /* start it */ + t->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + _timer_start(_timer_list, t); + } + } + else break; + } + rt_spin_unlock_irqrestore(&_hard_spinlock, level); + LOG_D("timer check leave"); +} + +rt_tick_t rt_timer_next_timeout_tick(void) +{ + rt_base_t level; + rt_tick_t next_timeout = RT_TICK_MAX; + + level = rt_spin_lock_irqsave(&_hard_spinlock); + _timer_list_next_timeout(_timer_list, &next_timeout); + rt_spin_unlock_irqrestore(&_hard_spinlock, level); + + return next_timeout; +} + +void rt_soft_timer_check(void) +{ + rt_tick_t current_tick; + struct rt_timer *t; + rt_base_t level; + rt_list_t list; + + rt_list_init(&list); + LOG_D("software timer check enter"); + level = rt_spin_lock_irqsave(&_soft_spinlock); + + while (!rt_list_isempty(&_soft_timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1])) + { + t = rt_list_entry(_soft_timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1].next, + struct rt_timer, row[RT_TIMER_SKIP_LIST_LEVEL - 1]); + + current_tick = rt_tick_get(); + + /* + * It supposes that the new tick shall less than the half duration of + * tick max. + */ + if ((current_tick - t->timeout_tick) < RT_TICK_MAX / 2) + { + RT_OBJECT_HOOK_CALL(rt_timer_enter_hook, (t)); + + /* remove timer from timer list firstly */ + _timer_remove(t); + if (!(t->parent.flag & RT_TIMER_FLAG_PERIODIC)) + { + t->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + } + /* add timer to temporary list */ + rt_list_insert_after(&list, &(t->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + + _soft_timer_status = RT_SOFT_TIMER_BUSY; + + rt_spin_unlock_irqrestore(&_soft_spinlock, level); + + /* call timeout function */ + t->timeout_func(t->parameter); + + RT_OBJECT_HOOK_CALL(rt_timer_exit_hook, (t)); + LOG_D("current tick: %d", current_tick); + + level = rt_spin_lock_irqsave(&_soft_spinlock); + + _soft_timer_status = RT_SOFT_TIMER_IDLE; + /* Check whether the timer object is detached or started again */ + if (rt_list_isempty(&list)) + { + continue; + } + rt_list_remove(&(t->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + if ((t->parent.flag & RT_TIMER_FLAG_PERIODIC) && + (t->parent.flag & RT_TIMER_FLAG_ACTIVATED)) + { + /* start it */ + t->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + _timer_start(_soft_timer_list, t); + } + } + else break; /* not check anymore */ + } + + rt_spin_unlock_irqrestore(&_soft_spinlock, level); + + LOG_D("software timer check leave"); +} + +static void _timer_thread_entry(void *parameter) +{ + rt_err_t ret = RT_ERROR; + rt_tick_t next_timeout; + rt_base_t level; + + rt_sem_control(&_soft_timer_sem, RT_IPC_CMD_SET_VLIMIT, (void*)1); + + while (1) + { + /* get the next timeout tick */ + level = rt_spin_lock_irqsave(&_soft_spinlock); + ret = _timer_list_next_timeout(_soft_timer_list, &next_timeout); + rt_spin_unlock_irqrestore(&_soft_spinlock, level); + + if (ret != RT_EOK) + { + rt_sem_take(&_soft_timer_sem, RT_WAITING_FOREVER); + } + else + { + rt_tick_t current_tick; + + /* get current tick */ + current_tick = rt_tick_get(); + + if ((next_timeout - current_tick) < RT_TICK_MAX / 2) + { + /* get the delta timeout tick */ + next_timeout = next_timeout - current_tick; + rt_sem_take(&_soft_timer_sem, next_timeout); + } + } + + /* check software timer */ + rt_soft_timer_check(); + } +} + +void rt_system_timer_init(void) +{ + rt_size_t i; + + for (i = 0; i < sizeof(_timer_list) / sizeof(_timer_list[0]); i++) + { + rt_list_init(_timer_list + i); + } + rt_spin_lock_init(&_hard_spinlock); +} + +void rt_system_timer_thread_init(void) +{ +#ifdef RT_USING_TIMER_SOFT + int i; + + for (i = 0; + i < sizeof(_soft_timer_list) / sizeof(_soft_timer_list[0]); + i++) + { + rt_list_init(_soft_timer_list + i); + } + rt_spin_lock_init(&_soft_spinlock); + rt_sem_init(&_soft_timer_sem, "stimer", 0, RT_IPC_FLAG_PRIO); + /* start software timer thread */ + rt_thread_init(&_timer_thread, + "timer", + _timer_thread_entry, + RT_NULL, + &_timer_thread_stack[0], + sizeof(_timer_thread_stack), + RT_TIMER_THREAD_PRIO, + 10); + + /* startup */ + rt_thread_startup(&_timer_thread); +#endif /* RT_USING_TIMER_SOFT */ +} + diff --git a/tasks/runtime-rtthread-softtimer-wakeup/valid_atomic_wait/src/thread.c b/tasks/runtime-rtthread-softtimer-wakeup/valid_atomic_wait/src/thread.c new file mode 100644 index 00000000..c4031f6a --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/valid_atomic_wait/src/thread.c @@ -0,0 +1,468 @@ +/* + * Copyright (c) 2006-2022, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +#include +#include +#include + +#define DBG_TAG "kernel.thread" +#define DBG_LVL DBG_INFO +#include + +#ifndef __on_rt_thread_inited_hook + #define __on_rt_thread_inited_hook(thread) __ON_HOOK_ARGS(rt_thread_inited_hook, (thread)) +#endif +#ifndef __on_rt_thread_suspend_hook + #define __on_rt_thread_suspend_hook(thread) __ON_HOOK_ARGS(rt_thread_suspend_hook, (thread)) +#endif +#ifndef __on_rt_thread_resume_hook + #define __on_rt_thread_resume_hook(thread) __ON_HOOK_ARGS(rt_thread_resume_hook, (thread)) +#endif + + +static void _thread_exit(void) +{ + struct rt_thread *thread; + rt_base_t level; + + /* get current thread */ + LOG_D("line:%d thread:%s exit\n",__LINE__,rt_thread_self()->parent.name); + thread = rt_thread_self(); + rt_get_thread_struct(thread); + rt_thread_defunct_enqueue(thread); + level = rt_spin_lock_irqsave(&(thread->spinlock)); + rt_timer_detach(&thread->thread_timer); + /* insert to defunct thread list */ + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + LOG_D("line:%d thread:%s exit\n",__LINE__,rt_thread_self()->parent.name); + rt_put_thread_struct(thread); + thread->stat = RT_THREAD_CLOSE; + /* switch to next task */ + rt_schedule(); +} + +static void _thread_timeout(void *parameter) +{ + struct rt_thread *thread; + rt_base_t level; + + thread = (struct rt_thread *)parameter; + + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT((thread->stat & RT_THREAD_SUSPEND_MASK) == RT_THREAD_SUSPEND_MASK); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + level = rt_spin_lock_irqsave(&(thread->spinlock)); + /* set error number */ + thread->error = -RT_ETIMEOUT; + + /* remove from suspend list */ + rt_list_remove(&(thread->tlist)); + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + /* insert to schedule ready list */ + rt_schedule_insert_thread(thread); + /* do schedule */ + rt_schedule(); +} + +static rt_err_t _thread_init(struct rt_thread *thread, + const char *name, + void (*entry)(void *parameter), + void *parameter, + void *stack_start, + rt_uint32_t stack_size, + rt_uint8_t priority, + rt_uint32_t tick) +{ + /* init thread list */ + rt_list_init(&(thread->tlist)); + rt_list_init(&(thread->tlist_schedule)); + +#ifdef RT_USING_MEM_PROTECTION + thread->mem_regions = RT_NULL; +#endif + +#ifdef RT_USING_SMART + thread->wakeup.func = RT_NULL; +#endif + + thread->entry = (void *)entry; + thread->parameter = parameter; + + /* stack init */ + thread->stack_addr = stack_start; + thread->stack_size = stack_size; + + /* init thread stack */ + rt_memset(thread->stack_addr, '#', thread->stack_size); +#ifdef RT_USING_HW_STACK_GUARD + rt_hw_stack_guard_init(thread); +#endif +#ifdef ARCH_CPU_STACK_GROWS_UPWARD + thread->sp = (void *)rt_hw_stack_init(thread->entry, thread->parameter, + (void *)((char *)thread->stack_addr), + (void *)_thread_exit); +#else + thread->sp = (void *)rt_hw_stack_init(thread->entry, thread->parameter, + (rt_uint8_t *)((char *)thread->stack_addr + thread->stack_size - sizeof(rt_ubase_t)), + (void *)_thread_exit); +#endif /* ARCH_CPU_STACK_GROWS_UPWARD */ + + /* priority init */ + RT_ASSERT(priority < RT_THREAD_PRIORITY_MAX); + thread->init_priority = priority; + thread->current_priority = priority; + + thread->number_mask = 0; + +#ifdef RT_USING_MUTEX + rt_list_init(&thread->taken_object_list); + thread->pending_object = RT_NULL; +#endif + +#ifdef RT_USING_EVENT + thread->event_set = 0; + thread->event_info = 0; +#endif /* RT_USING_EVENT */ + +#if RT_THREAD_PRIORITY_MAX > 32 + thread->number = 0; + thread->high_mask = 0; +#endif /* RT_THREAD_PRIORITY_MAX > 32 */ + + /* tick init */ + rt_atomic_store(&thread->init_tick, tick); + rt_atomic_store(&thread->remaining_tick, tick); + + /* error and flags */ + thread->error = RT_EOK; + thread->stat = RT_THREAD_INIT; + +#ifdef RT_USING_SMP + /* not bind on any cpu */ + thread->bind_cpu = RT_CPUS_NR; + thread->oncpu = RT_CPU_DETACHED; + + /* lock init */ + rt_atomic_store(&thread->cpus_lock_nest, 0); + rt_atomic_store(&thread->critical_lock_nest, 0); +#endif /* RT_USING_SMP */ + + /* initialize cleanup function and user data */ + thread->cleanup = 0; + thread->user_data = 0; + + /* initialize thread timer */ + rt_timer_init(&(thread->thread_timer), + thread->parent.name, + _thread_timeout, + thread, + 0, + RT_TIMER_FLAG_ONE_SHOT); + + /* initialize signal */ +#ifdef RT_USING_SIGNALS + thread->sig_mask = 0x00; + thread->sig_pending = 0x00; + +#ifndef RT_USING_SMP + thread->sig_ret = RT_NULL; +#endif /* RT_USING_SMP */ + thread->sig_vectors = RT_NULL; + thread->si_list = RT_NULL; +#endif /* RT_USING_SIGNALS */ + +#ifdef RT_USING_SMART + thread->tid_ref_count = 0; + thread->lwp = RT_NULL; + thread->susp_recycler = RT_NULL; + rt_list_init(&(thread->sibling)); + + /* lwp thread-signal init */ + rt_memset(&thread->signal.sigset_mask, 0, sizeof(lwp_sigset_t)); + rt_memset(&thread->signal.sig_queue.sigset_pending, 0, sizeof(lwp_sigset_t)); + rt_list_init(&thread->signal.sig_queue.siginfo_list); + + rt_memset(&thread->user_ctx, 0, sizeof thread->user_ctx); + + /* initialize user_time and system_time */ + thread->user_time = 0; + thread->system_time = 0; +#endif + +#ifdef RT_USING_CPU_USAGE + thread->duration_tick = 0; +#endif /* RT_USING_CPU_USAGE */ + +#ifdef RT_USING_PTHREADS + thread->pthread_data = RT_NULL; +#endif /* RT_USING_PTHREADS */ + +#ifdef RT_USING_MODULE + thread->parent.module_id = 0; +#endif /* RT_USING_MODULE */ + rt_atomic_store(&thread->ref_count, 0); + rt_spin_lock_init(&thread->spinlock); + + RT_OBJECT_HOOK_CALL(rt_thread_inited_hook, (thread)); + + return RT_EOK; +} + +rt_err_t rt_thread_init(struct rt_thread *thread, + const char *name, + void (*entry)(void *parameter), + void *parameter, + void *stack_start, + rt_uint32_t stack_size, + rt_uint8_t priority, + rt_uint32_t tick) +{ + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(stack_start != RT_NULL); + + /* initialize thread object */ + rt_object_init((rt_object_t)thread, RT_Object_Class_Thread, name); + + return _thread_init(thread, + name, + entry, + parameter, + stack_start, + stack_size, + priority, + tick); +} +RTM_EXPORT(rt_thread_init); + +rt_thread_t rt_thread_self(void) +{ +#ifdef RT_USING_SMP + rt_base_t lock; + rt_thread_t self; + + lock = rt_hw_local_irq_disable(); + self = rt_cpu_self()->current_thread; + rt_hw_local_irq_enable(lock); + return self; +#else + extern rt_thread_t rt_current_thread; + + return rt_current_thread; +#endif /* RT_USING_SMP */ +} +RTM_EXPORT(rt_thread_self); + +rt_err_t rt_thread_startup(rt_thread_t thread) +{ + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT((thread->stat & RT_THREAD_STAT_MASK) == RT_THREAD_INIT); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + + /* calculate priority attribute */ +#if RT_THREAD_PRIORITY_MAX > 32 + thread->number = thread->current_priority >> 3; /* 5bit */ + thread->number_mask = 1L << thread->number; + thread->high_mask = 1L << (thread->current_priority & 0x07); /* 3bit */ +#else + thread->number_mask = 1L << thread->current_priority; +#endif /* RT_THREAD_PRIORITY_MAX > 32 */ + + LOG_D("startup a thread:%s with priority:%d", + thread->parent.name, thread->current_priority); + /* change thread stat */ + thread->stat = RT_THREAD_SUSPEND; + /* then resume it */ + rt_thread_resume(thread); + if (rt_thread_self() != RT_NULL) + { + /* do a scheduling */ + rt_schedule(); + } + + return RT_EOK; +} +RTM_EXPORT(rt_thread_startup); + +rt_err_t rt_thread_sleep(rt_tick_t tick) +{ + rt_base_t level, level_local; + struct rt_thread *thread; + int err; + + if (tick == 0) + { + return -RT_EINVAL; + } + + /* set to current thread */ + thread = rt_thread_self(); + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + + /* current context checking */ + RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE); + /* reset thread error */ + thread->error = RT_EOK; + level_local = rt_hw_local_irq_disable(); + /* suspend thread */ + err = rt_thread_suspend_with_flag(thread, RT_INTERRUPTIBLE); + level = rt_spin_lock_irqsave(&(thread->spinlock)); + /* reset the timeout of thread timer and start it */ + if (err == RT_EOK) + { + rt_timer_control(&(thread->thread_timer), RT_TIMER_CTRL_SET_TIME, &tick); + rt_timer_start(&(thread->thread_timer)); + + /* enable interrupt */ + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + rt_hw_local_irq_enable(level_local); + thread->error = -RT_EINTR; + + rt_schedule(); + + /* clear error number of this thread to RT_EOK */ + if (thread->error == -RT_ETIMEOUT) + thread->error = RT_EOK; + } + else + { + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + rt_hw_local_irq_enable(level_local); + } + + return err; +} + +rt_err_t rt_thread_delay(rt_tick_t tick) +{ + return rt_thread_sleep(tick); +} +RTM_EXPORT(rt_thread_delay); + +static void rt_thread_set_suspend_state(struct rt_thread *thread, int suspend_flag) +{ + rt_uint8_t stat = RT_THREAD_SUSPEND_UNINTERRUPTIBLE; + + RT_ASSERT(thread != RT_NULL); + switch (suspend_flag) + { + case RT_INTERRUPTIBLE: + stat = RT_THREAD_SUSPEND_INTERRUPTIBLE; + break; + case RT_KILLABLE: + stat = RT_THREAD_SUSPEND_KILLABLE; + break; + case RT_UNINTERRUPTIBLE: + stat = RT_THREAD_SUSPEND_UNINTERRUPTIBLE; + break; + default: + RT_ASSERT(0); + break; + } + thread->stat = stat | (thread->stat & ~RT_THREAD_STAT_MASK); +} + +rt_err_t rt_thread_suspend_with_flag(rt_thread_t thread, int suspend_flag) +{ + rt_base_t stat; + rt_base_t level; + + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + RT_ASSERT(thread == rt_thread_self()); + + LOG_D("thread suspend: %s", thread->parent.name); + + level = rt_spin_lock_irqsave(&(thread->spinlock)); + + stat = thread->stat & RT_THREAD_STAT_MASK; + if ((stat != RT_THREAD_READY) && (stat != RT_THREAD_RUNNING)) + { + LOG_D("thread suspend: thread disorder, 0x%2x", thread->stat); + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + return -RT_ERROR; + } + + if (stat == RT_THREAD_RUNNING) + { + /* not suspend running status thread on other core */ + RT_ASSERT(thread == rt_thread_self()); + } +#ifdef RT_USING_SMART + if (lwp_thread_signal_suspend_check(thread, suspend_flag) == 0) + { + /* not to suspend */ + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + return -RT_EINTR; + } +#endif + + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + rt_schedule_remove_thread(thread); + level = rt_spin_lock_irqsave(&(thread->spinlock)); + + rt_thread_set_suspend_state(thread, suspend_flag); + + /* stop thread timer anyway */ + rt_timer_stop(&(thread->thread_timer)); + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + + RT_OBJECT_HOOK_CALL(rt_thread_suspend_hook, (thread)); + return RT_EOK; +} +RTM_EXPORT(rt_thread_suspend_with_flag); + +rt_err_t rt_thread_suspend(rt_thread_t thread) +{ + return rt_thread_suspend_with_flag(thread, RT_UNINTERRUPTIBLE); +} +RTM_EXPORT(rt_thread_suspend); + +rt_err_t rt_thread_resume(rt_thread_t thread) +{ + rt_base_t level; + + /* parameter check */ + RT_ASSERT(thread != RT_NULL); + RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread); + + LOG_D("thread resume: %s", thread->parent.name); + + level = rt_spin_lock_irqsave(&(thread->spinlock)); //TODO need lock for cpu + + if ((thread->stat & RT_THREAD_SUSPEND_MASK) != RT_THREAD_SUSPEND_MASK) + { + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + + LOG_D("thread resume: thread disorder, %d", + thread->stat); + + return -RT_ERROR; + } + + /* remove from suspend list */ + rt_list_remove(&(thread->tlist)); + + rt_timer_stop(&thread->thread_timer); + +#ifdef RT_USING_SMART + thread->wakeup.func = RT_NULL; +#endif + + rt_spin_unlock_irqrestore(&(thread->spinlock), level); + /* insert to schedule ready list */ + rt_schedule_insert_thread(thread); + + RT_OBJECT_HOOK_CALL(rt_thread_resume_hook, (thread)); + return RT_EOK; +} +RTM_EXPORT(rt_thread_resume); + diff --git a/tasks/runtime-rtthread-softtimer-wakeup/valid_atomic_wait/src/timer.c b/tasks/runtime-rtthread-softtimer-wakeup/valid_atomic_wait/src/timer.c new file mode 100644 index 00000000..14a6ea6d --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/valid_atomic_wait/src/timer.c @@ -0,0 +1,605 @@ +/* + * Copyright (c) 2006-2022, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + */ + +#include +#include + +#define DBG_TAG "kernel.timer" +#define DBG_LVL DBG_INFO +#include + +/* hard timer list */ +static rt_list_t _timer_list[RT_TIMER_SKIP_LIST_LEVEL]; +static struct rt_spinlock _hard_spinlock; + +#ifdef RT_USING_TIMER_SOFT + +#define RT_SOFT_TIMER_IDLE 1 +#define RT_SOFT_TIMER_BUSY 0 + +#ifndef RT_TIMER_THREAD_STACK_SIZE +#define RT_TIMER_THREAD_STACK_SIZE 512 +#endif /* RT_TIMER_THREAD_STACK_SIZE */ + +#ifndef RT_TIMER_THREAD_PRIO +#define RT_TIMER_THREAD_PRIO 0 +#endif /* RT_TIMER_THREAD_PRIO */ + +/* soft timer status */ +static rt_uint8_t _soft_timer_status = RT_SOFT_TIMER_IDLE; +/* soft timer list */ +static rt_list_t _soft_timer_list[RT_TIMER_SKIP_LIST_LEVEL]; +static struct rt_spinlock _soft_spinlock; +static struct rt_thread _timer_thread; +rt_align(RT_ALIGN_SIZE) +static rt_uint8_t _timer_thread_stack[RT_TIMER_THREAD_STACK_SIZE]; +#endif /* RT_USING_TIMER_SOFT */ + +#ifndef __on_rt_object_take_hook + #define __on_rt_object_take_hook(parent) __ON_HOOK_ARGS(rt_object_take_hook, (parent)) +#endif +#ifndef __on_rt_object_put_hook + #define __on_rt_object_put_hook(parent) __ON_HOOK_ARGS(rt_object_put_hook, (parent)) +#endif +#ifndef __on_rt_timer_enter_hook + #define __on_rt_timer_enter_hook(t) __ON_HOOK_ARGS(rt_timer_enter_hook, (t)) +#endif +#ifndef __on_rt_timer_exit_hook + #define __on_rt_timer_exit_hook(t) __ON_HOOK_ARGS(rt_timer_exit_hook, (t)) +#endif + + +static void _timer_init(rt_timer_t timer, + void (*timeout)(void *parameter), + void *parameter, + rt_tick_t time, + rt_uint8_t flag) +{ + int i; + + /* set flag */ + timer->parent.flag = flag; + + /* set deactivated */ + timer->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + + timer->timeout_func = timeout; + timer->parameter = parameter; + + timer->timeout_tick = 0; + timer->init_tick = time; + + /* initialize timer list */ + for (i = 0; i < RT_TIMER_SKIP_LIST_LEVEL; i++) + { + rt_list_init(&(timer->row[i])); + } +} + +static rt_err_t _timer_list_next_timeout(rt_list_t timer_list[], rt_tick_t *timeout_tick) +{ + struct rt_timer *timer; + + if (!rt_list_isempty(&timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1])) + { + timer = rt_list_entry(timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1].next, + struct rt_timer, row[RT_TIMER_SKIP_LIST_LEVEL - 1]); + *timeout_tick = timer->timeout_tick; + return RT_EOK; + } + return -RT_ERROR; +} + +rt_inline void _timer_remove(rt_timer_t timer) +{ + int i; + + for (i = 0; i < RT_TIMER_SKIP_LIST_LEVEL; i++) + { + rt_list_remove(&timer->row[i]); + } +} + +void rt_timer_init(rt_timer_t timer, + const char *name, + void (*timeout)(void *parameter), + void *parameter, + rt_tick_t time, + rt_uint8_t flag) +{ + /* parameter check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(timeout != RT_NULL); + RT_ASSERT(time < RT_TICK_MAX / 2); + + /* timer object initialization */ + rt_object_init(&(timer->parent), RT_Object_Class_Timer, name); + + _timer_init(timer, timeout, parameter, time, flag); +} +RTM_EXPORT(rt_timer_init); + +rt_err_t rt_timer_detach(rt_timer_t timer) +{ + rt_base_t level; + struct rt_spinlock *spinlock; + + /* parameter check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(rt_object_get_type(&timer->parent) == RT_Object_Class_Timer); + RT_ASSERT(rt_object_is_systemobject(&timer->parent)); + +#ifdef RT_USING_TIMER_SOFT + if (timer->parent.flag & RT_TIMER_FLAG_SOFT_TIMER) + { + spinlock = &_soft_spinlock; + } + else +#endif /* RT_USING_TIMER_SOFT */ + { + spinlock = &_hard_spinlock; + } + + level = rt_spin_lock_irqsave(spinlock); + + _timer_remove(timer); + /* stop timer */ + timer->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + + rt_spin_unlock_irqrestore(spinlock, level); + rt_object_detach(&(timer->parent)); + + return RT_EOK; +} +RTM_EXPORT(rt_timer_detach); + +static rt_err_t _timer_start(rt_list_t *timer_list, rt_timer_t timer) +{ + unsigned int row_lvl; + rt_list_t *row_head[RT_TIMER_SKIP_LIST_LEVEL]; + unsigned int tst_nr; + static unsigned int random_nr; + + /* remove timer from list */ + _timer_remove(timer); + /* change status of timer */ + timer->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + + RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(timer->parent))); + + timer->timeout_tick = rt_tick_get() + timer->init_tick; + + row_head[0] = &timer_list[0]; + for (row_lvl = 0; row_lvl < RT_TIMER_SKIP_LIST_LEVEL; row_lvl++) + { + for (; row_head[row_lvl] != timer_list[row_lvl].prev; + row_head[row_lvl] = row_head[row_lvl]->next) + { + struct rt_timer *t; + rt_list_t *p = row_head[row_lvl]->next; + + /* fix up the entry pointer */ + t = rt_list_entry(p, struct rt_timer, row[row_lvl]); + + /* If we have two timers that timeout at the same time, it's + * preferred that the timer inserted early get called early. + * So insert the new timer to the end the the some-timeout timer + * list. + */ + if ((t->timeout_tick - timer->timeout_tick) == 0) + { + continue; + } + else if ((t->timeout_tick - timer->timeout_tick) < RT_TICK_MAX / 2) + { + break; + } + } + if (row_lvl != RT_TIMER_SKIP_LIST_LEVEL - 1) + row_head[row_lvl + 1] = row_head[row_lvl] + 1; + } + + /* Interestingly, this super simple timer insert counter works very very + * well on distributing the list height uniformly. By means of "very very + * well", I mean it beats the randomness of timer->timeout_tick very easily + * (actually, the timeout_tick is not random and easy to be attacked). */ + random_nr++; + tst_nr = random_nr; + + rt_list_insert_after(row_head[RT_TIMER_SKIP_LIST_LEVEL - 1], + &(timer->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + for (row_lvl = 2; row_lvl <= RT_TIMER_SKIP_LIST_LEVEL; row_lvl++) + { + if (!(tst_nr & RT_TIMER_SKIP_LIST_MASK)) + rt_list_insert_after(row_head[RT_TIMER_SKIP_LIST_LEVEL - row_lvl], + &(timer->row[RT_TIMER_SKIP_LIST_LEVEL - row_lvl])); + else + break; + /* Shift over the bits we have tested. Works well with 1 bit and 2 + * bits. */ + tst_nr >>= (RT_TIMER_SKIP_LIST_MASK + 1) >> 1; + } + + timer->parent.flag |= RT_TIMER_FLAG_ACTIVATED; + +#ifdef RT_USING_TIMER_SOFT + if (timer->parent.flag & RT_TIMER_FLAG_SOFT_TIMER) + { + /* check whether timer thread is ready */ + if ((_soft_timer_status == RT_SOFT_TIMER_IDLE) && + ((_timer_thread.stat & RT_THREAD_SUSPEND_MASK) == RT_THREAD_SUSPEND_MASK)) + { + /* resume timer thread to check soft timer */ + rt_thread_resume(&_timer_thread); + } + } +#endif /* RT_USING_TIMER_SOFT */ + + return RT_EOK; +} + +rt_err_t rt_timer_start(rt_timer_t timer) +{ + struct rt_spinlock *spinlock; + rt_list_t *timer_list; + rt_base_t level; + rt_err_t err; + + /* parameter check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(rt_object_get_type(&timer->parent) == RT_Object_Class_Timer); + +#ifdef RT_USING_TIMER_SOFT + if (timer->parent.flag & RT_TIMER_FLAG_SOFT_TIMER) + { + timer_list = _soft_timer_list; + spinlock = &_soft_spinlock; + } + else +#endif /* RT_USING_TIMER_SOFT */ + { + timer_list = _timer_list; + spinlock = &_hard_spinlock; + } + + /* stop timer firstly */ + level = rt_spin_lock_irqsave(spinlock); + err = _timer_start(timer_list, timer); + rt_spin_unlock_irqrestore(spinlock, level); + + return err; +} +RTM_EXPORT(rt_timer_start); + +rt_err_t rt_timer_stop(rt_timer_t timer) +{ + rt_base_t level; + struct rt_spinlock *spinlock; + + /* timer check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(rt_object_get_type(&timer->parent) == RT_Object_Class_Timer); + +#ifdef RT_USING_TIMER_SOFT + if (timer->parent.flag & RT_TIMER_FLAG_SOFT_TIMER) + { + spinlock = &_soft_spinlock; + } + else +#endif /* RT_USING_TIMER_SOFT */ + { + spinlock = &_hard_spinlock; + } + level = rt_spin_lock_irqsave(spinlock); + + if (!(timer->parent.flag & RT_TIMER_FLAG_ACTIVATED)) + { + rt_spin_unlock_irqrestore(spinlock, level); + return -RT_ERROR; + } + RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(timer->parent))); + + _timer_remove(timer); + /* change status */ + timer->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + rt_spin_unlock_irqrestore(spinlock, level); + + return RT_EOK; +} +RTM_EXPORT(rt_timer_stop); + +rt_err_t rt_timer_control(rt_timer_t timer, int cmd, void *arg) +{ + /* parameter check */ + RT_ASSERT(timer != RT_NULL); + RT_ASSERT(rt_object_get_type(&timer->parent) == RT_Object_Class_Timer); + + switch (cmd) + { + case RT_TIMER_CTRL_GET_TIME: + *(rt_tick_t *)arg = timer->init_tick; + break; + + case RT_TIMER_CTRL_SET_TIME: + RT_ASSERT((*(rt_tick_t *)arg) < RT_TICK_MAX / 2); + timer->init_tick = *(rt_tick_t *)arg; + break; + + case RT_TIMER_CTRL_SET_ONESHOT: + timer->parent.flag &= ~RT_TIMER_FLAG_PERIODIC; + break; + + case RT_TIMER_CTRL_SET_PERIODIC: + timer->parent.flag |= RT_TIMER_FLAG_PERIODIC; + break; + + case RT_TIMER_CTRL_GET_STATE: + if(timer->parent.flag & RT_TIMER_FLAG_ACTIVATED) + { + /*timer is start and run*/ + *(rt_uint32_t *)arg = RT_TIMER_FLAG_ACTIVATED; + } + else + { + /*timer is stop*/ + *(rt_uint32_t *)arg = RT_TIMER_FLAG_DEACTIVATED; + } + break; + + case RT_TIMER_CTRL_GET_REMAIN_TIME: + *(rt_tick_t *)arg = timer->timeout_tick; + break; + case RT_TIMER_CTRL_GET_FUNC: + *(void **)arg = (void *)timer->timeout_func; + break; + + case RT_TIMER_CTRL_SET_FUNC: + timer->timeout_func = (void (*)(void*))arg; + break; + + case RT_TIMER_CTRL_GET_PARM: + *(void **)arg = timer->parameter; + break; + + case RT_TIMER_CTRL_SET_PARM: + timer->parameter = arg; + break; + + default: + break; + } + + return RT_EOK; +} +RTM_EXPORT(rt_timer_control); + +void rt_timer_check(void) +{ + struct rt_timer *t; + rt_tick_t current_tick; + rt_base_t level; + rt_list_t list; + +#ifdef RT_USING_SMP + if (rt_hw_cpu_id() != 0) + { + return; + } +#endif + + rt_list_init(&list); + + LOG_D("timer check enter"); + + current_tick = rt_tick_get(); + + level = rt_spin_lock_irqsave(&_hard_spinlock); + + while (!rt_list_isempty(&_timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1])) + { + t = rt_list_entry(_timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1].next, + struct rt_timer, row[RT_TIMER_SKIP_LIST_LEVEL - 1]); + + /* + * It supposes that the new tick shall less than the half duration of + * tick max. + */ + if ((current_tick - t->timeout_tick) < RT_TICK_MAX / 2) + { + RT_OBJECT_HOOK_CALL(rt_timer_enter_hook, (t)); + + /* remove timer from timer list firstly */ + _timer_remove(t); + if (!(t->parent.flag & RT_TIMER_FLAG_PERIODIC)) + { + t->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + } + /* add timer to temporary list */ + rt_list_insert_after(&list, &(t->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + rt_spin_unlock_irqrestore(&_hard_spinlock, level); + /* call timeout function */ + t->timeout_func(t->parameter); + + /* re-get tick */ + current_tick = rt_tick_get(); + + RT_OBJECT_HOOK_CALL(rt_timer_exit_hook, (t)); + LOG_D("current tick: %d", current_tick); + level = rt_spin_lock_irqsave(&_hard_spinlock); + /* Check whether the timer object is detached or started again */ + if (rt_list_isempty(&list)) + { + continue; + } + rt_list_remove(&(t->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + if ((t->parent.flag & RT_TIMER_FLAG_PERIODIC) && + (t->parent.flag & RT_TIMER_FLAG_ACTIVATED)) + { + /* start it */ + t->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + _timer_start(_timer_list, t); + } + } + else break; + } + rt_spin_unlock_irqrestore(&_hard_spinlock, level); + LOG_D("timer check leave"); +} + +rt_tick_t rt_timer_next_timeout_tick(void) +{ + rt_base_t level; + rt_tick_t next_timeout = RT_TICK_MAX; + + level = rt_spin_lock_irqsave(&_hard_spinlock); + _timer_list_next_timeout(_timer_list, &next_timeout); + rt_spin_unlock_irqrestore(&_hard_spinlock, level); + + return next_timeout; +} + +void rt_soft_timer_check(void) +{ + rt_tick_t current_tick; + struct rt_timer *t; + rt_base_t level; + rt_list_t list; + + rt_list_init(&list); + LOG_D("software timer check enter"); + level = rt_spin_lock_irqsave(&_soft_spinlock); + + while (!rt_list_isempty(&_soft_timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1])) + { + t = rt_list_entry(_soft_timer_list[RT_TIMER_SKIP_LIST_LEVEL - 1].next, + struct rt_timer, row[RT_TIMER_SKIP_LIST_LEVEL - 1]); + + current_tick = rt_tick_get(); + + /* + * It supposes that the new tick shall less than the half duration of + * tick max. + */ + if ((current_tick - t->timeout_tick) < RT_TICK_MAX / 2) + { + RT_OBJECT_HOOK_CALL(rt_timer_enter_hook, (t)); + + /* remove timer from timer list firstly */ + _timer_remove(t); + if (!(t->parent.flag & RT_TIMER_FLAG_PERIODIC)) + { + t->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + } + /* add timer to temporary list */ + rt_list_insert_after(&list, &(t->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + + _soft_timer_status = RT_SOFT_TIMER_BUSY; + + rt_spin_unlock_irqrestore(&_soft_spinlock, level); + + /* call timeout function */ + t->timeout_func(t->parameter); + + RT_OBJECT_HOOK_CALL(rt_timer_exit_hook, (t)); + LOG_D("current tick: %d", current_tick); + + level = rt_spin_lock_irqsave(&_soft_spinlock); + + _soft_timer_status = RT_SOFT_TIMER_IDLE; + /* Check whether the timer object is detached or started again */ + if (rt_list_isempty(&list)) + { + continue; + } + rt_list_remove(&(t->row[RT_TIMER_SKIP_LIST_LEVEL - 1])); + if ((t->parent.flag & RT_TIMER_FLAG_PERIODIC) && + (t->parent.flag & RT_TIMER_FLAG_ACTIVATED)) + { + /* start it */ + t->parent.flag &= ~RT_TIMER_FLAG_ACTIVATED; + _timer_start(_soft_timer_list, t); + } + } + else break; /* not check anymore */ + } + + rt_spin_unlock_irqrestore(&_soft_spinlock, level); + + LOG_D("software timer check leave"); +} + +static void _timer_thread_entry(void *parameter) +{ + rt_thread_t self = rt_thread_self(); + (void)parameter; + for (;;) + { + rt_tick_t deadline = 0; + int waiting = 0; + rt_base_t level = rt_spin_lock_irqsave(&_soft_spinlock); + rt_err_t found = _timer_list_next_timeout(_soft_timer_list, &deadline); + if (found != RT_EOK) + { + rt_thread_suspend_with_flag(self, RT_UNINTERRUPTIBLE); + waiting = 1; + } + else + { + rt_tick_t delta = deadline - rt_tick_get(); + if (delta > 0 && delta < RT_TICK_MAX / 2) + { + rt_thread_suspend_with_flag(self, RT_UNINTERRUPTIBLE); + rt_timer_control(&self->thread_timer, RT_TIMER_CTRL_SET_TIME, &delta); + rt_timer_start(&self->thread_timer); + waiting = 1; + } + } + rt_spin_unlock_irqrestore(&_soft_spinlock, level); + if (waiting) rt_schedule(); + rt_soft_timer_check(); + } +} + +void rt_system_timer_init(void) +{ + rt_size_t i; + + for (i = 0; i < sizeof(_timer_list) / sizeof(_timer_list[0]); i++) + { + rt_list_init(_timer_list + i); + } + rt_spin_lock_init(&_hard_spinlock); +} + +void rt_system_timer_thread_init(void) +{ +#ifdef RT_USING_TIMER_SOFT + int i; + + for (i = 0; + i < sizeof(_soft_timer_list) / sizeof(_soft_timer_list[0]); + i++) + { + rt_list_init(_soft_timer_list + i); + } + rt_spin_lock_init(&_soft_spinlock); + + /* start software timer thread */ + rt_thread_init(&_timer_thread, + "timer", + _timer_thread_entry, + RT_NULL, + &_timer_thread_stack[0], + sizeof(_timer_thread_stack), + RT_TIMER_THREAD_PRIO, + 10); + + /* startup */ + rt_thread_startup(&_timer_thread); +#endif /* RT_USING_TIMER_SOFT */ +} + diff --git a/tasks/runtime-rtthread-softtimer-wakeup/verify.py b/tasks/runtime-rtthread-softtimer-wakeup/verify.py new file mode 100644 index 00000000..9e2c6c26 --- /dev/null +++ b/tasks/runtime-rtthread-softtimer-wakeup/verify.py @@ -0,0 +1,130 @@ +"""Run an imported Bos-qiao check.py unchanged; candidate processes run as UID 65534.""" + +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile + +GRADER = Path(__file__).resolve().parent +BLOCKED = "isolation-blocked.txt" +GUARD = 86 +# Runs the original check unchanged as the trusted user. In isolation mode every child process drops to +# UID 65534 and every mkdtemp scratch is handed to it; an audit hook stops the check if candidate code +# would run inside this process. Failing child processes also copy their stderr tail out for private triage. +CHECK = ( + "import os, runpy, subprocess, sys, tempfile\n" + "isolated, sys.argv = sys.argv[1] == '1', sys.argv[2:]\n" + "untrusted = [os.path.realpath(sys.argv[1])]\n" + "def inside(path):\n" + " path = os.path.realpath(str(path))\n" + " return any(path == root or path.startswith(root + os.sep) for root in untrusted)\n" + "spawns = ('os.system', 'os.exec', 'os.spawn', 'os.fork', 'os.forkpty', 'os.posix_spawn') if isolated else ()\n" + "def guard(event, args):\n" + " if (event in spawns or event == 'exec' and inside(getattr(args[0], 'co_filename', '')) or\n" + " event == 'ctypes.dlopen' and args[0] and inside(args[0]) or\n" + " event == 'import' and any(inside(entry or '.') for entry in sys.path)):\n" + " sys.__stderr__.write('rollout-guard: ' + event + '\\n')\n" + " sys.__stderr__.flush()\n" + " os._exit(%d)\n" + "mkdtemp = tempfile.mkdtemp\n" + "def scratch(*args, **kwargs):\n" + " path = mkdtemp(*args, **kwargs)\n" + " untrusted.append(os.path.realpath(path))\n" + " if isolated:\n" + " os.chown(path, 65534, 65534)\n" + " return path\n" + "tempfile.mkdtemp = scratch\n" + "popen = subprocess.Popen.__init__\n" + "def drop(self, *args, **kwargs):\n" + " if isolated:\n" + " kwargs.update(user=65534, group=65534, extra_groups=[])\n" + " popen(self, *args, **kwargs)\n" + "subprocess.Popen.__init__ = drop\n" + "real = subprocess.run\n" + "def run(*args, **kwargs):\n" + " result = real(*args, **kwargs)\n" + " if result.returncode and result.stderr:\n" + " tail = result.stderr if isinstance(result.stderr, str) else result.stderr.decode('utf-8', 'replace')\n" + " sys.__stderr__.write(tail[-2000:] + '\\n')\n" + " return result\n" + "subprocess.run = run\n" + "sys.addaudithook(guard)\n" + "runpy.run_path(sys.argv[0], run_name='__main__')\n" % GUARD) + + +class UnsupportedEnvironment(RuntimeError): + pass + + +def candidate_user(): + os.setgroups([]) + os.setgid(65534) + os.setuid(65534) + + +def isolation(): + if os.environ.get("ROLLOUT_GRADE_ISOLATION") != "uid65534": + return None + if sys.platform != "linux" or os.geteuid() != 0: + raise UnsupportedEnvironment("isolated grader requires a Linux root supervisor") + probe = ( + "from pathlib import Path\n" + "try: Path('/grader/verify.py').read_bytes()\n" + "except PermissionError: raise SystemExit(0)\n" + "raise SystemExit(1)\n" + ) + try: + result = subprocess.run([sys.executable, "-I", "-c", probe], + capture_output=True, timeout=10, preexec_fn=candidate_user) + except subprocess.SubprocessError as error: + raise UnsupportedEnvironment("candidate identity could not be isolated") from error + if result.returncode != 0: + raise UnsupportedEnvironment("candidate can read the private grader or isolation probe failed") + return candidate_user + + +def verify(candidate): + if (GRADER / BLOCKED).exists(): + raise UnsupportedEnvironment("isolation blocked: " + (GRADER / BLOCKED).read_text().strip()[:200]) + isolated = isolation() is not None + if shutil.which("gcc") is None: + raise UnsupportedEnvironment("C compiler unavailable") + with tempfile.TemporaryDirectory(prefix="bos-grade-") as temporary: + root = Path(temporary) + work, grader = root / "work", root / "grader" + shutil.copytree(candidate, work, symlinks=True) + shutil.copytree(GRADER, grader, ignore=lambda folder, names: ["verify.py"] if Path(folder) == GRADER else []) + if isolated: + os.chmod(root, 0o711) + os.chmod(grader, 0o700) + for path in (work, *work.rglob("*")): + os.lchown(path, 65534, 65534) + # shortcut: the check runs as root and follows symlinks a child plants in shared scratch directories; + # upgrade by running the check under its own unprivileged UID once a setuid helper is available. + completed = subprocess.run([sys.executable, "-I", "-B", "-c", CHECK, "1" if isolated else "0", + str(grader / "check.py"), str(work)], + cwd=root, capture_output=True, text=True, timeout=100) + # grade.stderr stays on the trusted side with the archive; it may quote hidden test lines. + sys.stderr.write(completed.stderr[-4000:]) + if completed.returncode == GUARD and "rollout-guard: " in completed.stderr: + raise UnsupportedEnvironment("isolation blocked: the check would run candidate code in the grader process") + lines = completed.stdout.splitlines() + if completed.returncode == 0 and lines[-1:] == ["PASS"]: + return {"status": "PASS", "checks": 1} + return {"status": "FAIL", "checks": 1, "reason": (lines[-1] if lines else "no checker output")[:300]} + + +if __name__ == "__main__": + try: + result = verify(Path(sys.argv[1])) + except UnsupportedEnvironment as error: + result = {"status": "UNVERIFIED", "checks": 0, "reason": str(error)} + except subprocess.TimeoutExpired: + result = {"status": "FAIL", "checks": 1, "reason": "timeout"} + except Exception as error: + result = {"status": "INFRA_ERROR", "checks": 0, "reason": str(error)} + print(json.dumps(result, sort_keys=True)) + sys.exit({"PASS": 0, "FAIL": 1}.get(result["status"], 2))