This is an automated email from the ASF dual-hosted git repository. GUIDINGLI pushed a commit to branch master in repository https://gitbox.apache.org/repos/asf/nuttx-apps.git
commit 9b99ed9fe56b36dd1155e68d1fdf05ba77d6c00c Author: Kai Cheng <[email protected]> AuthorDate: Thu Nov 5 14:14:47 2026 +0800 wireless/bluetooth/zblue: Add Zephyr kernel porting layer Implement the Zephyr kernel services used by the Zephyr Bluetooth host on POSIX threads and NuttX work queues, without NuttX internal interfaces, so that the host sources can be built unmodified: - threads: Zephyr cooperative threads are serialized by one lock that is released only while the thread blocks; k_sched_lock() takes the same lock. Zephyr priorities are mapped around CONFIG_ZBLUE_THREAD_PRIORITY. - semaphores, mutexes, condition variables, FIFO/LIFO queues, memory slabs and heaps. - work queues: each k_work_q is a NuttX work queue with one thread, created with work_queue_create(): a kernel work queue in the flat build, a user-mode work queue in the protected and kernel builds. The Zephyr state of a work item (queued, delayed, running, canceling) is kept in its flags, for the Zephyr return values, flush and cancel_sync(), which the NuttX work queues do not provide. - timeouts, uptime and cycle counters on CLOCK_MONOTONIC. - logging and printk on syslog, random numbers. - headers that replace or extend the Zephyr ones: kernel.h, devicetree, SYS_INIT() and iterable sections. Iterable section entries go to sections named zblue_<type> and are collected with the linker generated __start_/__stop_ symbols, so no change to the board linker script is needed. - zblue_prefix.h, included first in every Zephyr source, resolves the name clashes between the Zephyr and NuttX headers. The layer is not built yet; the build is added later in this series. Signed-off-by: Kai Cheng <[email protected]> --- .../bluetooth/zblue/port/include/zblue_prefix.h | 185 +++++++ .../bluetooth/zblue/port/include/zephyr/arch/cpu.h | 32 ++ .../port/include/zephyr/devicetree_generated.h | 51 ++ .../bluetooth/zblue/port/include/zephyr/init.h | 61 +++ wireless/bluetooth/zblue/port/include/zephyr/irq.h | 32 ++ .../bluetooth/zblue/port/include/zephyr/kernel.h | 502 +++++++++++++++++++ .../zblue/port/include/zephyr/kernel/thread.h | 32 ++ .../port/include/zephyr/kernel/thread_stack.h | 50 ++ .../zblue/port/include/zephyr/logging/log.h | 130 +++++ .../bluetooth/zblue/port/include/zephyr/spinlock.h | 104 ++++ .../port/include/zephyr/sys/iterable_sections.h | 51 ++ .../zblue/port/include/zephyr/sys/printk.h | 45 ++ wireless/bluetooth/zblue/port/src/kernel.c | 370 ++++++++++++++ wireless/bluetooth/zblue/port/src/misc.c | 173 +++++++ wireless/bluetooth/zblue/port/src/port.h | 75 +++ wireless/bluetooth/zblue/port/src/sync.c | 486 +++++++++++++++++++ wireless/bluetooth/zblue/port/src/work.c | 535 +++++++++++++++++++++ 17 files changed, 2914 insertions(+) diff --git a/wireless/bluetooth/zblue/port/include/zblue_prefix.h b/wireless/bluetooth/zblue/port/include/zblue_prefix.h new file mode 100644 index 000000000..02a1b9de6 --- /dev/null +++ b/wireless/bluetooth/zblue/port/include/zblue_prefix.h @@ -0,0 +1,185 @@ +/**************************************************************************** + * apps/wireless/bluetooth/zblue/port/include/zblue_prefix.h + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. The + * ASF licenses this file to you 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. + * + ****************************************************************************/ + +#ifndef __APPS_WIRELESS_BLUETOOTH_ZBLUE_PORT_INCLUDE_ZBLUE_PREFIX_H +#define __APPS_WIRELESS_BLUETOOTH_ZBLUE_PORT_INCLUDE_ZBLUE_PREFIX_H + +/* Included first in every zblue translation unit (-include). + * + * The Zephyr sources are built unmodified, so where NuttX and Zephyr + * use the same name for different things, the Zephyr meaning has to win + * inside zblue. The NuttX equivalents (nuttx/atomic.h, the libc crc and + * hex helpers) cannot be used in their place without changing the + * Zephyr code. + * + * Atomics: <nuttx/atomic.h> is pulled in by C library headers (stdio.h, + * pthread.h, semaphore.h, and debug.h through nuttx/fs/fs.h). It + * defines atomic_t as _Atomic int32_t and atomic_*() as macros; Zephyr + * defines atomic_t as long and atomic_*() as functions with other return + * values (e.g. atomic_set() returns the previous value). Both also + * define atomic_ptr_t. The NuttX headers are included here with the + * NuttX types renamed, then the macros are removed. + */ + +#define atomic_t nx_atomic_t +#define atomic64_t nx_atomic64_t +#define atomic_ptr_t nx_atomic_ptr_t + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <nuttx/config.h> +#include <nuttx/atomic.h> +#include <debug.h> +#include <errno.h> +#include <fcntl.h> +#include <poll.h> +#include <pthread.h> +#include <sched.h> +#include <semaphore.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <time.h> +#include <unistd.h> + +#undef atomic_t +#undef atomic64_t +#undef atomic_ptr_t + +/* Time constants: same values as in <zephyr/sys/clock.h>, which + * defines them again. + */ + +#undef NSEC_PER_USEC +#undef NSEC_PER_MSEC +#undef NSEC_PER_SEC +#undef USEC_PER_MSEC +#undef USEC_PER_SEC +#undef MSEC_PER_SEC +#undef SEC_PER_MIN +#undef SEC_PER_HOUR +#undef SEC_PER_DAY +#undef MIN_PER_HOUR +#undef HOUR_PER_DAY +#undef atomic_add +#undef atomic_add_acquire +#undef atomic_add_relaxed +#undef atomic_add_release +#undef atomic_and +#undef atomic_and_acquire +#undef atomic_and_relaxed +#undef atomic_and_release +#undef atomic_cmpxchg +#undef atomic_cmpxchg_acquire +#undef atomic_cmpxchg_relaxed +#undef atomic_cmpxchg_release +#undef atomic_or +#undef atomic_or_acquire +#undef atomic_or_relaxed +#undef atomic_or_release +#undef atomic_read +#undef atomic_read_acquire +#undef atomic_set +#undef atomic_set_release +#undef atomic_sub +#undef atomic_sub_acquire +#undef atomic_sub_relaxed +#undef atomic_sub_release +#undef atomic_try_cmpxchg +#undef atomic_try_cmpxchg_acquire +#undef atomic_try_cmpxchg_relaxed +#undef atomic_try_cmpxchg_release +#undef atomic_xchg +#undef atomic_xchg_acquire +#undef atomic_xchg_relaxed +#undef atomic_xchg_release +#undef atomic_xor +#undef atomic_xor_acquire +#undef atomic_xor_relaxed +#undef atomic_xor_release +#undef atomic_ptr_add +#undef atomic_ptr_add_acquire +#undef atomic_ptr_add_relaxed +#undef atomic_ptr_add_release +#undef atomic_ptr_and +#undef atomic_ptr_and_acquire +#undef atomic_ptr_and_relaxed +#undef atomic_ptr_and_release +#undef atomic_ptr_cmpxchg +#undef atomic_ptr_cmpxchg_acquire +#undef atomic_ptr_cmpxchg_relaxed +#undef atomic_ptr_cmpxchg_release +#undef atomic_ptr_cmpxchg_release_acquire +#undef atomic_ptr_or +#undef atomic_ptr_or_acquire +#undef atomic_ptr_or_relaxed +#undef atomic_ptr_or_release +#undef atomic_ptr_read +#undef atomic_ptr_read_acquire +#undef atomic_ptr_set +#undef atomic_ptr_set_release +#undef atomic_ptr_sub +#undef atomic_ptr_sub_acquire +#undef atomic_ptr_sub_relaxed +#undef atomic_ptr_sub_release +#undef atomic_ptr_try_cmpxchg +#undef atomic_ptr_try_cmpxchg_acquire +#undef atomic_ptr_try_cmpxchg_relaxed +#undef atomic_ptr_try_cmpxchg_release +#undef atomic_ptr_try_cmpxchg_release_acquire +#undef atomic_ptr_xchg +#undef atomic_ptr_xchg_acquire +#undef atomic_ptr_xchg_relaxed +#undef atomic_ptr_xchg_release +#undef atomic_ptr_xor +#undef atomic_ptr_xor_acquire +#undef atomic_ptr_xor_relaxed +#undef atomic_ptr_xor_release + +/* Library functions: the NuttX C library has crc8(), crc16(), hex2bin() + * etc. with other signatures than the Zephyr ones compiled in zblue + * (e.g. crc16(src, len) and crc16(poly, seed, src, len)). The Zephyr + * ones are renamed so that both can be linked. + */ + +/* Zephyr places some objects in a no-init RAM section; ordinary .bss is + * equivalent here. + */ + +#include <zephyr/linker/section_tags.h> +#undef __noinit +#define __noinit + +#define crc8 zblue_crc8 +#define crc16 zblue_crc16 +#define crc16_reflect zblue_crc16_reflect +#define crc32_ieee zblue_crc32_ieee +#define hex2bin zblue_hex2bin +#define bin2hex zblue_bin2hex +#define char2hex zblue_char2hex +#define hex2char zblue_hex2char +#define uuid_from_string zblue_uuid_from_string +#define uuid_to_string zblue_uuid_to_string + +#endif diff --git a/wireless/bluetooth/zblue/port/include/zephyr/arch/cpu.h b/wireless/bluetooth/zblue/port/include/zephyr/arch/cpu.h new file mode 100644 index 000000000..cdb35c8d0 --- /dev/null +++ b/wireless/bluetooth/zblue/port/include/zephyr/arch/cpu.h @@ -0,0 +1,32 @@ +/**************************************************************************** + * apps/wireless/bluetooth/zblue/port/include/zephyr/arch/cpu.h + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. The + * ASF licenses this file to you 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. + * + ****************************************************************************/ + +#ifndef __APPS_WIRELESS_BLUETOOTH_ZBLUE_PORT_INCLUDE_ZEPHYR_ARCH_CPU_H +#define __APPS_WIRELESS_BLUETOOTH_ZBLUE_PORT_INCLUDE_ZEPHYR_ARCH_CPU_H + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <zephyr/spinlock.h> + +#endif diff --git a/wireless/bluetooth/zblue/port/include/zephyr/devicetree_generated.h b/wireless/bluetooth/zblue/port/include/zephyr/devicetree_generated.h new file mode 100644 index 000000000..b65cc81d9 --- /dev/null +++ b/wireless/bluetooth/zblue/port/include/zephyr/devicetree_generated.h @@ -0,0 +1,51 @@ +/**************************************************************************** + * apps/wireless/bluetooth/zblue/port/include/zephyr/devicetree_generated.h + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. The + * ASF licenses this file to you 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. + * + ****************************************************************************/ + +#ifndef __APPS_WIRELESS_BLUETOOTH_ZBLUE_PORT_INCLUDE_ZEPHYR_DEVICETREE_GENERATED_H +#define __APPS_WIRELESS_BLUETOOTH_ZBLUE_PORT_INCLUDE_ZEPHYR_DEVICETREE_GENERATED_H + +/* Hand written replacement of the file the Zephyr build generates from the + * devicetree. It describes one node, the HCI device of the port + * (port/src/hci.c), and makes it the zephyr,bt-hci chosen node. Upstream + * <zephyr/devicetree.h> works on top of it unchanged. + */ + +#define DT_N_PATH "/" +#define DT_N_EXISTS 1 +#define DT_N_ORD 0 + +#define DT_N_S_zblue_hci_PATH "/zblue_hci" +#define DT_N_S_zblue_hci_EXISTS 1 +#define DT_N_S_zblue_hci_ORD 1 +#define DT_N_S_zblue_hci_STATUS_okay 1 +#define DT_N_S_zblue_hci_PARENT DT_N + +#define DT_CHOSEN_zephyr_bt_hci DT_N_S_zblue_hci +#define DT_CHOSEN_zephyr_bt_hci_EXISTS 1 + +#define DT_FOREACH_HELPER(fn) fn(DT_N_S_zblue_hci) +#define DT_FOREACH_OKAY_HELPER(fn) fn(DT_N_S_zblue_hci) +#define DT_FOREACH_VARGS_HELPER(fn, ...) fn(DT_N_S_zblue_hci, __VA_ARGS__) +#define DT_FOREACH_OKAY_VARGS_HELPER(fn, ...) \ + fn(DT_N_S_zblue_hci, __VA_ARGS__) + +#endif diff --git a/wireless/bluetooth/zblue/port/include/zephyr/init.h b/wireless/bluetooth/zblue/port/include/zephyr/init.h new file mode 100644 index 000000000..58c89454a --- /dev/null +++ b/wireless/bluetooth/zblue/port/include/zephyr/init.h @@ -0,0 +1,61 @@ +/**************************************************************************** + * apps/wireless/bluetooth/zblue/port/include/zephyr/init.h + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. The + * ASF licenses this file to you 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. + * + ****************************************************************************/ + +/* SYS_INIT() without a linker script: entries record their level and + * priority, port/src/misc.c sorts and runs them before the Bluetooth host + * starts. + */ + +#ifndef __APPS_WIRELESS_BLUETOOTH_ZBLUE_PORT_INCLUDE_ZEPHYR_INIT_H +#define __APPS_WIRELESS_BLUETOOTH_ZBLUE_PORT_INCLUDE_ZEPHYR_INIT_H + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include_next <zephyr/init.h> + +struct z_zblue_init +{ + int (*init_fn)(void); + int level; + int prio; +}; + +#define Z_ZBLUE_INIT_LEVEL_EARLY 0 +#define Z_ZBLUE_INIT_LEVEL_PRE_KERNEL_1 1 +#define Z_ZBLUE_INIT_LEVEL_PRE_KERNEL_2 2 +#define Z_ZBLUE_INIT_LEVEL_POST_KERNEL 3 +#define Z_ZBLUE_INIT_LEVEL_APPLICATION 4 +#define Z_ZBLUE_INIT_LEVEL_SMP 5 + +#undef SYS_INIT_NAMED +#define SYS_INIT_NAMED(name, init_fn_, level_, prio_) \ + static const struct z_zblue_init _CONCAT(z_zblue_init_, name) \ + __attribute__((__section__("zblue_init"))) __used = \ + { \ + .init_fn = (init_fn_), \ + .level = Z_ZBLUE_INIT_LEVEL_##level_, \ + .prio = (prio_), \ + } + +#endif /* __APPS_WIRELESS_BLUETOOTH_ZBLUE_PORT_INCLUDE_ZEPHYR_INIT_H */ diff --git a/wireless/bluetooth/zblue/port/include/zephyr/irq.h b/wireless/bluetooth/zblue/port/include/zephyr/irq.h new file mode 100644 index 000000000..181ec19ba --- /dev/null +++ b/wireless/bluetooth/zblue/port/include/zephyr/irq.h @@ -0,0 +1,32 @@ +/**************************************************************************** + * apps/wireless/bluetooth/zblue/port/include/zephyr/irq.h + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. The + * ASF licenses this file to you 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. + * + ****************************************************************************/ + +#ifndef __APPS_WIRELESS_BLUETOOTH_ZBLUE_PORT_INCLUDE_ZEPHYR_IRQ_H +#define __APPS_WIRELESS_BLUETOOTH_ZBLUE_PORT_INCLUDE_ZEPHYR_IRQ_H + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <zephyr/spinlock.h> + +#endif diff --git a/wireless/bluetooth/zblue/port/include/zephyr/kernel.h b/wireless/bluetooth/zblue/port/include/zephyr/kernel.h new file mode 100644 index 000000000..0fd3da178 --- /dev/null +++ b/wireless/bluetooth/zblue/port/include/zephyr/kernel.h @@ -0,0 +1,502 @@ +/**************************************************************************** + * apps/wireless/bluetooth/zblue/port/include/zephyr/kernel.h + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. The + * ASF licenses this file to you 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. + * + ****************************************************************************/ + +/* The subset of the Zephyr kernel API used by the Bluetooth host, built on + * POSIX threads. Declarations follow include/zephyr/kernel.h of the + * downloaded Zephyr release; only what the host uses is provided. + * + * Scheduling model: Zephyr cooperative threads are never preempted by other + * threads, and parts of the host depend on that. All threads created here + * with a cooperative priority, and the HCI RX thread, run while holding + * one global lock (the "coop lock") and release it only while blocked. + * k_sched_lock() takes the same lock, so a preemptive caller cannot run + * concurrently with a cooperative thread inside a k_sched_lock() section. + */ + +#ifndef __APPS_WIRELESS_BLUETOOTH_ZBLUE_PORT_INCLUDE_ZEPHYR_KERNEL_H +#define __APPS_WIRELESS_BLUETOOTH_ZBLUE_PORT_INCLUDE_ZEPHYR_KERNEL_H + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <errno.h> +#include <limits.h> +#include <pthread.h> +#include <stdbool.h> +#include <stddef.h> +#include <stdint.h> +#include <stdlib.h> + +#include <nuttx/wqueue.h> + +#include <zephyr/toolchain.h> +#include <zephyr/types.h> +#include <zephyr/sys/atomic.h> +#include <zephyr/sys/__assert.h> +#include <zephyr/sys/clock.h> +#include <zephyr/sys/dlist.h> +#include <zephyr/sys/slist.h> +#include <zephyr/sys/sflist.h> +#include <zephyr/sys/time_units.h> +#include <zephyr/sys/util.h> +#include <zephyr/sys/printk.h> +#include <zephyr/sys/iterable_sections.h> +#include <zephyr/spinlock.h> +#include <zephyr/kernel/thread_stack.h> + +#ifdef __cplusplus +extern "C" +{ +#endif + +/* Timeouts */ + +#define K_NO_WAIT Z_TIMEOUT_NO_WAIT +#define K_NSEC(t) Z_TIMEOUT_NS(t) +#define K_USEC(t) Z_TIMEOUT_US(t) +#define K_TICKS(t) Z_TIMEOUT_TICKS(t) +#define K_MSEC(ms) Z_TIMEOUT_MS(ms) +#define K_SECONDS(s) K_MSEC((s) * MSEC_PER_SEC) +#define K_MINUTES(m) K_SECONDS((m) * 60) +#define K_HOURS(h) K_MINUTES((h) * 60) +#define K_FOREVER Z_FOREVER + +/* Priorities */ + +#define K_PRIO_COOP(x) (-(CONFIG_NUM_COOP_PRIORITIES - (x))) +#define K_PRIO_PREEMPT(x) (x) +#define K_HIGHEST_THREAD_PRIO (-CONFIG_NUM_COOP_PRIORITIES) +#define K_LOWEST_THREAD_PRIO CONFIG_NUM_PREEMPT_PRIORITIES + +/* Threads */ + +struct k_thread +{ + pthread_t pthread; + int prio; + const char *name; + void (*entry)(void *, void *, void *); + void *p1; + void *p2; + void *p3; + size_t stack_size; + int coop_depth; + bool coop; +}; + +typedef struct k_thread *k_tid_t; + +k_tid_t k_current_get(void); +void k_yield(void); +int32_t k_sleep(k_timeout_t timeout); +int32_t k_msleep(int32_t ms); +void k_busy_wait(uint32_t usec_to_wait); +int k_thread_name_set(k_tid_t thread, const char *str); +k_tid_t k_thread_create(struct k_thread *new_thread, k_thread_stack_t *stack, + size_t stack_size, + void (*entry)(void *, void *, void *), + void *p1, void *p2, void *p3, + int prio, uint32_t options, k_timeout_t delay); + +static inline bool k_is_in_isr(void) +{ + return false; +} + +static inline bool k_is_pre_kernel(void) +{ + return false; +} + +void k_sched_lock(void); +void k_sched_unlock(void); + +/* Fatal errors of the current thread: there is no thread to abort alone + * in a process, so both end the program. + */ + +#define k_oops() abort() +#define k_panic() abort() + +/* Time */ + +int64_t k_uptime_ticks(void); + +static inline int64_t k_uptime_get(void) +{ + return k_ticks_to_ms_floor64(k_uptime_ticks()); +} + +static inline uint32_t k_uptime_get_32(void) +{ + return (uint32_t)k_uptime_get(); +} + +static inline int64_t k_uptime_delta(int64_t *reftime) +{ + int64_t now = k_uptime_get(); + int64_t delta = now - *reftime; + + *reftime = now; + return delta; +} + +uint32_t k_cycle_get_32(void); +uint64_t k_cycle_get_64(void); + +/* Semaphores */ + +struct k_sem +{ + pthread_mutex_t lock; + pthread_cond_t cond; + unsigned int count; + unsigned int limit; +}; + +#define K_SEM_MAX_LIMIT UINT_MAX + +#define Z_SEM_INITIALIZER(obj, initial_count, count_limit) \ + { \ + .lock = PTHREAD_MUTEX_INITIALIZER, \ + .cond = PTHREAD_COND_INITIALIZER, \ + .count = (initial_count), \ + .limit = (count_limit), \ + } + +#define K_SEM_DEFINE(name, initial_count, count_limit) \ + struct k_sem name = Z_SEM_INITIALIZER(name, initial_count, count_limit) + +int k_sem_init(struct k_sem *sem, unsigned int initial_count, + unsigned int limit); +int k_sem_take(struct k_sem *sem, k_timeout_t timeout); +void k_sem_give(struct k_sem *sem); +void k_sem_reset(struct k_sem *sem); +unsigned int k_sem_count_get(struct k_sem *sem); + +/* Mutexes (recursive, as in Zephyr) */ + +struct k_mutex +{ + pthread_mutex_t lock; + pthread_cond_t cond; + struct k_thread *owner; + uint32_t lock_count; +}; + +#define Z_MUTEX_INITIALIZER(obj) \ + { \ + .lock = PTHREAD_MUTEX_INITIALIZER, \ + .cond = PTHREAD_COND_INITIALIZER, \ + } + +#define K_MUTEX_DEFINE(name) struct k_mutex name = Z_MUTEX_INITIALIZER(name) + +int k_mutex_init(struct k_mutex *mutex); +int k_mutex_lock(struct k_mutex *mutex, k_timeout_t timeout); +int k_mutex_unlock(struct k_mutex *mutex); + +/* Condition variables */ + +struct k_condvar +{ + pthread_cond_t cond; +}; + +#define Z_CONDVAR_INITIALIZER(obj) { .cond = PTHREAD_COND_INITIALIZER } +#define K_CONDVAR_DEFINE(name) \ + struct k_condvar name = Z_CONDVAR_INITIALIZER(name) + +int k_condvar_init(struct k_condvar *condvar); +int k_condvar_signal(struct k_condvar *condvar); +int k_condvar_broadcast(struct k_condvar *condvar); +int k_condvar_wait(struct k_condvar *condvar, struct k_mutex *mutex, + k_timeout_t timeout); + +/* Queues, FIFOs and LIFOs. Items reserve their first word for the link, + * as in Zephyr. + */ + +struct k_queue +{ + sys_sflist_t data_q; + pthread_mutex_t lock; + pthread_cond_t cond; +}; + +#define Z_QUEUE_INITIALIZER(obj) \ + { \ + .data_q = SYS_SFLIST_STATIC_INIT(&obj.data_q), \ + .lock = PTHREAD_MUTEX_INITIALIZER, \ + .cond = PTHREAD_COND_INITIALIZER, \ + } + +void k_queue_init(struct k_queue *queue); +void k_queue_append(struct k_queue *queue, void *data); +void k_queue_prepend(struct k_queue *queue, void *data); +void *k_queue_get(struct k_queue *queue, k_timeout_t timeout); +bool k_queue_remove(struct k_queue *queue, void *data); +void *k_queue_peek_head(struct k_queue *queue); +void *k_queue_peek_tail(struct k_queue *queue); +int k_queue_is_empty(struct k_queue *queue); +void k_queue_cancel_wait(struct k_queue *queue); + +struct k_fifo +{ + struct k_queue _queue; +}; + +#define Z_FIFO_INITIALIZER(obj) { ._queue = Z_QUEUE_INITIALIZER(obj._queue) } +#define K_FIFO_DEFINE(name) struct k_fifo name = Z_FIFO_INITIALIZER(name) + +#define k_fifo_init(fifo) k_queue_init(&(fifo)->_queue) +#define k_fifo_put(fifo, data) k_queue_append(&(fifo)->_queue, data) +#define k_fifo_get(fifo, timeout) k_queue_get(&(fifo)->_queue, timeout) +#define k_fifo_is_empty(fifo) k_queue_is_empty(&(fifo)->_queue) +#define k_fifo_peek_head(fifo) k_queue_peek_head(&(fifo)->_queue) +#define k_fifo_peek_tail(fifo) k_queue_peek_tail(&(fifo)->_queue) +#define k_fifo_cancel_wait(fifo) k_queue_cancel_wait(&(fifo)->_queue) + +struct k_lifo +{ + struct k_queue _queue; +}; + +#define Z_LIFO_INITIALIZER(obj) { ._queue = Z_QUEUE_INITIALIZER(obj._queue) } +#define K_LIFO_DEFINE(name) struct k_lifo name = Z_LIFO_INITIALIZER(name) + +#define k_lifo_init(lifo) k_queue_init(&(lifo)->_queue) +#define k_lifo_put(lifo, data) k_queue_prepend(&(lifo)->_queue, data) +#define k_lifo_get(lifo, timeout) k_queue_get(&(lifo)->_queue, timeout) + +/* Memory slabs */ + +struct k_mem_slab +{ + struct k_lifo free_q; + char *buffer; + size_t block_size; + uint32_t num_blocks; + uint32_t num_used; + bool ready; +}; + +#define Z_MEM_SLAB_INITIALIZER(_slab, _buf, _size, _num) \ + { \ + .free_q = Z_LIFO_INITIALIZER(_slab.free_q), \ + .buffer = (char *)(_buf), \ + .block_size = (_size), \ + .num_blocks = (_num), \ + } + +#define K_MEM_SLAB_DEFINE_STATIC(name, slab_block_size, slab_num_blocks, \ + slab_align) \ + static char __aligned(MAX(slab_align, sizeof(void *))) \ + _k_mem_slab_buf_##name[(slab_num_blocks) * \ + ROUND_UP(slab_block_size, sizeof(void *))]; \ + static struct k_mem_slab name = Z_MEM_SLAB_INITIALIZER(name, \ + _k_mem_slab_buf_##name, ROUND_UP(slab_block_size, sizeof(void *)), \ + slab_num_blocks) + +#define K_MEM_SLAB_DEFINE(name, slab_block_size, slab_num_blocks, slab_align) \ + static char __aligned(MAX(slab_align, sizeof(void *))) \ + _k_mem_slab_buf_##name[(slab_num_blocks) * \ + ROUND_UP(slab_block_size, sizeof(void *))]; \ + struct k_mem_slab name = Z_MEM_SLAB_INITIALIZER(name, \ + _k_mem_slab_buf_##name, ROUND_UP(slab_block_size, sizeof(void *)), \ + slab_num_blocks) + +#define K_MEM_SLAB_DEFINE_STATIC_TYPE(name, type, slab_num_blocks) \ + K_MEM_SLAB_DEFINE_STATIC(name, sizeof(type), slab_num_blocks, \ + __alignof__(type)) + +#define K_MEM_SLAB_DEFINE_TYPE(name, type, slab_num_blocks) \ + K_MEM_SLAB_DEFINE(name, sizeof(type), slab_num_blocks, __alignof__(type)) + +int k_mem_slab_init(struct k_mem_slab *slab, void *buffer, + size_t block_size, uint32_t num_blocks); +int k_mem_slab_alloc(struct k_mem_slab *slab, void **mem, + k_timeout_t timeout); +void k_mem_slab_free(struct k_mem_slab *slab, void *mem); +uint32_t k_mem_slab_num_used_get(struct k_mem_slab *slab); +uint32_t k_mem_slab_num_free_get(struct k_mem_slab *slab); + +/* Heaps: backed by the C library heap */ + +struct k_heap +{ + size_t size; +}; + +#define K_HEAP_DEFINE(name, bytes) struct k_heap name = { .size = (bytes) } +#define K_HEAP_DEFINE_NOCACHE(name, bytes) K_HEAP_DEFINE(name, bytes) + +#ifndef K_HEAP_MEM_POOL_SIZE +# define K_HEAP_MEM_POOL_SIZE 1 +#endif + +void *k_heap_alloc(struct k_heap *h, size_t bytes, k_timeout_t timeout); +void *k_heap_aligned_alloc(struct k_heap *h, size_t align, size_t bytes, + k_timeout_t timeout); +void k_heap_free(struct k_heap *h, void *mem); +void *k_malloc(size_t size); +void *k_calloc(size_t nmemb, size_t size); +void *k_aligned_alloc(size_t align, size_t size); +void k_free(void *ptr); + +/* Work queues */ + +struct k_work; +struct k_work_q; + +typedef void (*k_work_handler_t)(struct k_work *work); + +enum +{ + K_WORK_RUNNING_BIT = 0, + K_WORK_CANCELING_BIT = 1, + K_WORK_QUEUED_BIT = 2, + K_WORK_DELAYED_BIT = 3, + K_WORK_FLUSHING_BIT = 4, + + K_WORK_RUNNING = BIT(K_WORK_RUNNING_BIT), + K_WORK_CANCELING = BIT(K_WORK_CANCELING_BIT), + K_WORK_QUEUED = BIT(K_WORK_QUEUED_BIT), + K_WORK_DELAYED = BIT(K_WORK_DELAYED_BIT), + K_WORK_FLUSHING = BIT(K_WORK_FLUSHING_BIT), + K_WORK_MASK = K_WORK_DELAYED | K_WORK_QUEUED | K_WORK_RUNNING | + K_WORK_CANCELING | K_WORK_FLUSHING, +}; + +/* Run on a NuttX work queue. The flags hold the Zephyr state; the + * NuttX work item only dispatches the handler on the queue thread. + */ + +struct k_work +{ + struct work_s nxwork; + k_work_handler_t handler; + struct k_work_q *queue; + uint32_t flags; +}; + +#define Z_WORK_INITIALIZER(work_handler) { .handler = (work_handler) } +#define K_WORK_DEFINE(work, work_handler) \ + struct k_work work = Z_WORK_INITIALIZER(work_handler) + +struct k_work_delayable +{ + struct k_work work; + int64_t expiry; +}; + +#define Z_WORK_DELAYABLE_INITIALIZER(work_handler) \ + { .work = { .handler = (work_handler), .flags = 0 } } +#define K_WORK_DELAYABLE_DEFINE(work, work_handler) \ + struct k_work_delayable work = Z_WORK_DELAYABLE_INITIALIZER(work_handler) + +struct k_work_sync +{ + int unused; +}; + +struct k_work_queue_config +{ + const char *name; + bool no_yield; + bool essential; + uint32_t work_timeout_ms; +}; + +struct k_work_q +{ + struct k_thread thread; + k_tid_t thread_id; + FAR struct kwork_wqueue_s *wq; + struct work_s start; +}; + +extern struct k_work_q k_sys_work_q; + +void k_work_init(struct k_work *work, k_work_handler_t handler); +int k_work_busy_get(const struct k_work *work); + +static inline bool k_work_is_pending(const struct k_work *work) +{ + return k_work_busy_get(work) != 0; +} + +int k_work_submit_to_queue(struct k_work_q *queue, struct k_work *work); +int k_work_submit(struct k_work *work); +bool k_work_flush(struct k_work *work, struct k_work_sync *sync); +int k_work_cancel(struct k_work *work); +bool k_work_cancel_sync(struct k_work *work, struct k_work_sync *sync); + +void k_work_queue_init(struct k_work_q *queue); +void k_work_queue_start(struct k_work_q *queue, k_thread_stack_t *stack, + size_t stack_size, int prio, + const struct k_work_queue_config *cfg); + +static inline k_tid_t k_work_queue_thread_get(struct k_work_q *queue) +{ + return queue->thread_id; +} + +static inline struct k_work_delayable * +k_work_delayable_from_work(struct k_work *work) +{ + return CONTAINER_OF(work, struct k_work_delayable, work); +} + +void k_work_init_delayable(struct k_work_delayable *dwork, + k_work_handler_t handler); +int k_work_delayable_busy_get(const struct k_work_delayable *dwork); + +static inline bool +k_work_delayable_is_pending(const struct k_work_delayable *dwork) +{ + return k_work_delayable_busy_get(dwork) != 0; +} + +k_ticks_t k_work_delayable_remaining_get( + const struct k_work_delayable *dwork); + +int k_work_schedule_for_queue(struct k_work_q *queue, + struct k_work_delayable *dwork, + k_timeout_t delay); +int k_work_schedule(struct k_work_delayable *dwork, k_timeout_t delay); +int k_work_reschedule_for_queue(struct k_work_q *queue, + struct k_work_delayable *dwork, + k_timeout_t delay); +int k_work_reschedule(struct k_work_delayable *dwork, k_timeout_t delay); +bool k_work_flush_delayable(struct k_work_delayable *dwork, + struct k_work_sync *sync); +int k_work_cancel_delayable(struct k_work_delayable *dwork); +bool k_work_cancel_delayable_sync(struct k_work_delayable *dwork, + struct k_work_sync *sync); + +#ifdef __cplusplus +} +#endif + +#endif /* __APPS_WIRELESS_BLUETOOTH_ZBLUE_PORT_INCLUDE_ZEPHYR_KERNEL_H */ diff --git a/wireless/bluetooth/zblue/port/include/zephyr/kernel/thread.h b/wireless/bluetooth/zblue/port/include/zephyr/kernel/thread.h new file mode 100644 index 000000000..66e6e4cbd --- /dev/null +++ b/wireless/bluetooth/zblue/port/include/zephyr/kernel/thread.h @@ -0,0 +1,32 @@ +/**************************************************************************** + * apps/wireless/bluetooth/zblue/port/include/zephyr/kernel/thread.h + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. The + * ASF licenses this file to you 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. + * + ****************************************************************************/ + +#ifndef __APPS_WIRELESS_BLUETOOTH_ZBLUE_PORT_INCLUDE_ZEPHYR_KERNEL_THREAD_H +#define __APPS_WIRELESS_BLUETOOTH_ZBLUE_PORT_INCLUDE_ZEPHYR_KERNEL_THREAD_H + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <zephyr/kernel.h> + +#endif diff --git a/wireless/bluetooth/zblue/port/include/zephyr/kernel/thread_stack.h b/wireless/bluetooth/zblue/port/include/zephyr/kernel/thread_stack.h new file mode 100644 index 000000000..35eeeb318 --- /dev/null +++ b/wireless/bluetooth/zblue/port/include/zephyr/kernel/thread_stack.h @@ -0,0 +1,50 @@ +/**************************************************************************** + * apps/wireless/bluetooth/zblue/port/include/zephyr/kernel/thread_stack.h + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. The + * ASF licenses this file to you 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. + * + ****************************************************************************/ + +#ifndef __APPS_WIRELESS_BLUETOOTH_ZBLUE_PORT_INCLUDE_ZEPHYR_KERNEL_THREAD_STACK_H +#define __APPS_WIRELESS_BLUETOOTH_ZBLUE_PORT_INCLUDE_ZEPHYR_KERNEL_THREAD_STACK_H + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <stddef.h> +#include <zephyr/toolchain.h> + +/* Stacks are allocated by pthread_create(); the Zephyr stack objects only + * carry their size. + */ + +typedef struct +{ + size_t size; +} k_thread_stack_t; + +#define K_KERNEL_STACK_DEFINE(sym, size) \ + k_thread_stack_t sym[1] = { { (size) } } +#define K_KERNEL_STACK_MEMBER(sym, size) k_thread_stack_t sym[1] +#define K_THREAD_STACK_DEFINE(sym, size) K_KERNEL_STACK_DEFINE(sym, size) +#define K_THREAD_STACK_MEMBER(sym, size) K_KERNEL_STACK_MEMBER(sym, size) +#define K_KERNEL_STACK_SIZEOF(sym) ((sym)[0].size) +#define K_THREAD_STACK_SIZEOF(sym) K_KERNEL_STACK_SIZEOF(sym) + +#endif diff --git a/wireless/bluetooth/zblue/port/include/zephyr/logging/log.h b/wireless/bluetooth/zblue/port/include/zephyr/logging/log.h new file mode 100644 index 000000000..b60c7a7da --- /dev/null +++ b/wireless/bluetooth/zblue/port/include/zephyr/logging/log.h @@ -0,0 +1,130 @@ +/**************************************************************************** + * apps/wireless/bluetooth/zblue/port/include/zephyr/logging/log.h + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. The + * ASF licenses this file to you 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. + * + ****************************************************************************/ + +/* Zephyr logging macros on top of syslog(). The level of each module is + * fixed at build time, from LOG_LEVEL or the second argument of + * LOG_MODULE_REGISTER()/LOG_MODULE_DECLARE(), as in Zephyr. + */ + +#ifndef __APPS_WIRELESS_BLUETOOTH_ZBLUE_PORT_INCLUDE_ZEPHYR_LOGGING_LOG_H +#define __APPS_WIRELESS_BLUETOOTH_ZBLUE_PORT_INCLUDE_ZEPHYR_LOGGING_LOG_H + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <debug.h> +#include <stddef.h> +#include <stdint.h> +#include <syslog.h> + +#include <zephyr/sys/util.h> + +#ifdef __cplusplus +extern "C" +{ +#endif + +#define LOG_LEVEL_NONE 0 +#define LOG_LEVEL_ERR 1 +#define LOG_LEVEL_WRN 2 +#define LOG_LEVEL_INF 3 +#define LOG_LEVEL_DBG 4 + +#ifndef CONFIG_LOG +# define Z_ZBLUE_LOG_MAX 0 +#else +# define Z_ZBLUE_LOG_MAX CONFIG_LOG_MAX_LEVEL +#endif + +#ifdef LOG_LEVEL +# define Z_ZBLUE_LOG_DEFAULT LOG_LEVEL +#else +# define Z_ZBLUE_LOG_DEFAULT CONFIG_LOG_DEFAULT_LEVEL +#endif + +#define Z_ZBLUE_LOG_RESOLVE(...) \ + GET_ARG_N(2, __VA_ARGS__, Z_ZBLUE_LOG_DEFAULT) + +#define LOG_MODULE_REGISTER(...) \ + static const char __unused z_log_name[] = STRINGIFY(GET_ARG_N(1, __VA_ARGS__)); \ + enum { z_log_level = Z_ZBLUE_LOG_RESOLVE(__VA_ARGS__) } + +#define LOG_MODULE_DECLARE(...) LOG_MODULE_REGISTER(__VA_ARGS__) + +/* <syslog.h> uses LOG_ERR for a priority, keep its value before the + * Zephyr macro replaces it. + */ + +enum +{ + Z_ZBLUE_SYSLOG_ERR = LOG_ERR +}; + +#define Z_ZBLUE_PRIO(_level) \ + ((_level) == LOG_LEVEL_ERR ? Z_ZBLUE_SYSLOG_ERR : \ + (_level) == LOG_LEVEL_WRN ? LOG_WARNING : \ + (_level) == LOG_LEVEL_INF ? LOG_INFO : LOG_DEBUG) + +#define Z_ZBLUE_ENABLED(_level) \ + ((_level) <= z_log_level && (_level) <= Z_ZBLUE_LOG_MAX) + +#define Z_ZBLUE_LOG(_level, fmt, ...) \ + do \ + { \ + if (Z_ZBLUE_ENABLED(_level)) \ + { \ + syslog(Z_ZBLUE_PRIO(_level), "%c: %s: " fmt "\n", \ + "?EWID"[_level], z_log_name, ##__VA_ARGS__); \ + } \ + } \ + while (0) + +#define Z_ZBLUE_HEXDUMP(_level, _data, _len, _str) \ + do \ + { \ + if (Z_ZBLUE_ENABLED(_level)) \ + { \ + lib_dumpbuffer(_str, (const uint8_t *)(_data), _len); \ + } \ + } \ + while (0) + +#undef LOG_ERR +#define LOG_ERR(...) Z_ZBLUE_LOG(LOG_LEVEL_ERR, __VA_ARGS__) +#define LOG_WRN(...) Z_ZBLUE_LOG(LOG_LEVEL_WRN, __VA_ARGS__) +#define LOG_INF(...) Z_ZBLUE_LOG(LOG_LEVEL_INF, __VA_ARGS__) +#define LOG_DBG(...) Z_ZBLUE_LOG(LOG_LEVEL_DBG, __VA_ARGS__) + +#define LOG_HEXDUMP_ERR(d, l, s) Z_ZBLUE_HEXDUMP(LOG_LEVEL_ERR, d, l, s) +#define LOG_HEXDUMP_WRN(d, l, s) Z_ZBLUE_HEXDUMP(LOG_LEVEL_WRN, d, l, s) +#define LOG_HEXDUMP_INF(d, l, s) Z_ZBLUE_HEXDUMP(LOG_LEVEL_INF, d, l, s) +#define LOG_HEXDUMP_DBG(d, l, s) Z_ZBLUE_HEXDUMP(LOG_LEVEL_DBG, d, l, s) + +#define LOG_PRINTK(...) syslog(LOG_INFO, __VA_ARGS__) +#define LOG_RAW(...) syslog(LOG_INFO, __VA_ARGS__) + +#ifdef __cplusplus +} +#endif + +#endif /* __APPS_WIRELESS_BLUETOOTH_ZBLUE_PORT_INCLUDE_ZEPHYR_LOGGING_LOG_H */ diff --git a/wireless/bluetooth/zblue/port/include/zephyr/spinlock.h b/wireless/bluetooth/zblue/port/include/zephyr/spinlock.h new file mode 100644 index 000000000..9de4dd78a --- /dev/null +++ b/wireless/bluetooth/zblue/port/include/zephyr/spinlock.h @@ -0,0 +1,104 @@ +/**************************************************************************** + * apps/wireless/bluetooth/zblue/port/include/zephyr/spinlock.h + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. The + * ASF licenses this file to you 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. + * + ****************************************************************************/ + +#ifndef __APPS_WIRELESS_BLUETOOTH_ZBLUE_PORT_INCLUDE_ZEPHYR_SPINLOCK_H +#define __APPS_WIRELESS_BLUETOOTH_ZBLUE_PORT_INCLUDE_ZEPHYR_SPINLOCK_H + +/* Spinlocks protect short sections against other threads. In userspace + * there are no interrupts to mask, so all of them map to one recursive + * lock; nothing blocks while holding it. + */ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <errno.h> +#include <pthread.h> +#include <stdbool.h> + +#ifdef __cplusplus +extern "C" +{ +#endif + +struct k_spinlock +{ + char unused; +}; + +typedef struct +{ + int key; +} k_spinlock_key_t; + +/* The one lock behind all spinlocks and irq_lock(), see kernel.c */ + +extern pthread_mutex_t g_zblue_spin; + +static inline k_spinlock_key_t k_spin_lock(struct k_spinlock *l) +{ + k_spinlock_key_t key = + { + 0 + }; + + (void)l; + pthread_mutex_lock(&g_zblue_spin); + return key; +} + +static inline int k_spin_trylock(struct k_spinlock *l, k_spinlock_key_t *k) +{ + (void)l; + (void)k; + return pthread_mutex_trylock(&g_zblue_spin) == 0 ? 0 : -EBUSY; +} + +static inline void k_spin_unlock(struct k_spinlock *l, k_spinlock_key_t key) +{ + (void)l; + (void)key; + pthread_mutex_unlock(&g_zblue_spin); +} + +#define K_SPINLOCK(lck) \ + for (k_spinlock_key_t __k = k_spin_lock(lck), *__once = &__k; __once; \ + k_spin_unlock(lck, __k), __once = NULL) + +static inline unsigned int irq_lock(void) +{ + pthread_mutex_lock(&g_zblue_spin); + return 0; +} + +static inline void irq_unlock(unsigned int key) +{ + (void)key; + pthread_mutex_unlock(&g_zblue_spin); +} + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/wireless/bluetooth/zblue/port/include/zephyr/sys/iterable_sections.h b/wireless/bluetooth/zblue/port/include/zephyr/sys/iterable_sections.h new file mode 100644 index 000000000..6171bfd97 --- /dev/null +++ b/wireless/bluetooth/zblue/port/include/zephyr/sys/iterable_sections.h @@ -0,0 +1,51 @@ +/**************************************************************************** + * apps/wireless/bluetooth/zblue/port/include/zephyr/sys/iterable_sections.h + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. The + * ASF licenses this file to you 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. + * + ****************************************************************************/ + +/* Iterable sections without a linker script. Every entry of a type goes + * to one section whose name is a C identifier, so the linker provides + * __start_<name> and __stop_<name>, and keeps the section with + * --gc-sections as long as these symbols are referenced. This works for + * entries defined by applications as well. Unlike Zephyr, entries of a + * type are in link order, not sorted by name. + */ + +#ifndef __APPS_WIRELESS_BLUETOOTH_ZBLUE_PORT_INCLUDE_ZEPHYR_SYS_ITERABLE_SECTIONS_H +#define __APPS_WIRELESS_BLUETOOTH_ZBLUE_PORT_INCLUDE_ZEPHYR_SYS_ITERABLE_SECTIONS_H + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include_next <zephyr/sys/iterable_sections.h> + +#undef TYPE_SECTION_ITERABLE +#undef TYPE_SECTION_START +#undef TYPE_SECTION_END + +#define TYPE_SECTION_ITERABLE(type, varname, secname, section_postfix) \ + Z_DECL_ALIGN(type) varname \ + __attribute__((__section__("zblue_" STRINGIFY(secname)))) __used __noasan + +#define TYPE_SECTION_START(secname) _CONCAT(__start_zblue_, secname) +#define TYPE_SECTION_END(secname) _CONCAT(__stop_zblue_, secname) + +#endif /* __APPS_WIRELESS_BLUETOOTH_ZBLUE_PORT_INCLUDE_ZEPHYR_SYS_ITERABLE_SECTIONS_H */ diff --git a/wireless/bluetooth/zblue/port/include/zephyr/sys/printk.h b/wireless/bluetooth/zblue/port/include/zephyr/sys/printk.h new file mode 100644 index 000000000..ddb4cee11 --- /dev/null +++ b/wireless/bluetooth/zblue/port/include/zephyr/sys/printk.h @@ -0,0 +1,45 @@ +/**************************************************************************** + * apps/wireless/bluetooth/zblue/port/include/zephyr/sys/printk.h + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. The + * ASF licenses this file to you 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. + * + ****************************************************************************/ + +/* Zephyr printk() family mapped to syslog() and the C library */ + +#ifndef __APPS_WIRELESS_BLUETOOTH_ZBLUE_PORT_INCLUDE_ZEPHYR_SYS_PRINTK_H +#define __APPS_WIRELESS_BLUETOOTH_ZBLUE_PORT_INCLUDE_ZEPHYR_SYS_PRINTK_H + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <stdarg.h> +#include <stdio.h> +#include <syslog.h> + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +#define printk(...) syslog(LOG_INFO, __VA_ARGS__) +#define vprintk(fmt, ap) vsyslog(LOG_INFO, fmt, ap) +#define snprintk(...) snprintf(__VA_ARGS__) +#define vsnprintk(str, size, fmt, ap) vsnprintf(str, size, fmt, ap) + +#endif /* __APPS_WIRELESS_BLUETOOTH_ZBLUE_PORT_INCLUDE_ZEPHYR_SYS_PRINTK_H */ diff --git a/wireless/bluetooth/zblue/port/src/kernel.c b/wireless/bluetooth/zblue/port/src/kernel.c new file mode 100644 index 000000000..54d9c2a81 --- /dev/null +++ b/wireless/bluetooth/zblue/port/src/kernel.c @@ -0,0 +1,370 @@ +/**************************************************************************** + * apps/wireless/bluetooth/zblue/port/src/kernel.c + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. The + * ASF licenses this file to you 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. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <zephyr/kernel.h> + +#include "port.h" + +/**************************************************************************** + * Public Data + ****************************************************************************/ + +/* Spinlocks and irq_lock() nest, so the lock is recursive */ + +pthread_mutex_t g_zblue_spin = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP; + +/**************************************************************************** + * Private Data + ****************************************************************************/ + +static pthread_mutex_t g_coop = PTHREAD_MUTEX_INITIALIZER; +static pthread_once_t g_once = PTHREAD_ONCE_INIT; +static pthread_key_t g_self; + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +static void kernel_once(void) +{ + int ret; + + ret = pthread_key_create(&g_self, free); + __ASSERT(ret == 0, "pthread_key_create: %d", ret); + ARG_UNUSED(ret); +} + +static void coop_lock(struct k_thread *self) +{ + if (self->coop_depth++ == 0) + { + pthread_mutex_lock(&g_coop); + } +} + +static void coop_unlock(struct k_thread *self) +{ + if (--self->coop_depth == 0) + { + pthread_mutex_unlock(&g_coop); + } +} + +static void *thread_main(void *arg) +{ + struct k_thread *thread = arg; + + z_zblue_set_self(thread); + + if (thread->coop) + { + coop_lock(thread); + } + + thread->entry(thread->p1, thread->p2, thread->p3); + + if (thread->coop) + { + coop_unlock(thread); + } + + /* The record is not heap allocated, keep the key destructor away */ + + pthread_setspecific(g_self, NULL); + return NULL; +} + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +void z_zblue_set_self(struct k_thread *thread) +{ + pthread_once(&g_once, kernel_once); + pthread_setspecific(g_self, thread); +} + +k_tid_t k_current_get(void) +{ + struct k_thread *self; + + pthread_once(&g_once, kernel_once); + self = pthread_getspecific(g_self); + if (self == NULL) + { + /* A thread not created by zblue, e.g. the application calling + * bt_enable(). It is a preemptive thread. The key destructor + * frees the record when the thread exits. + */ + + self = calloc(1, sizeof(*self)); + __ASSERT_NO_MSG(self != NULL); + self->pthread = pthread_self(); + self->name = "app"; + pthread_setspecific(g_self, self); + } + + return self; +} + +int z_zblue_block_begin(void) +{ + struct k_thread *self = k_current_get(); + int depth = self->coop_depth; + + if (depth > 0) + { + self->coop_depth = 0; + pthread_mutex_unlock(&g_coop); + } + + return depth; +} + +void z_zblue_block_end(int depth) +{ + struct k_thread *self; + + if (depth > 0) + { + self = k_current_get(); + pthread_mutex_lock(&g_coop); + self->coop_depth = depth; + } +} + +void k_sched_lock(void) +{ + coop_lock(k_current_get()); +} + +void k_sched_unlock(void) +{ + coop_unlock(k_current_get()); +} + +int z_zblue_priority(int prio) +{ + int nxprio = CONFIG_ZBLUE_THREAD_PRIORITY - prio; + + return CLAMP(nxprio, SCHED_PRIORITY_MIN + 1, SCHED_PRIORITY_MAX - 1); +} + +int z_zblue_thread_start(struct k_thread *thread, size_t stack_size, + int prio) +{ + struct sched_param param; + pthread_attr_t attr; + int ret; + + pthread_once(&g_once, kernel_once); + + thread->prio = prio; + thread->coop = prio < 0; + thread->coop_depth = 0; + + pthread_attr_init(&attr); + pthread_attr_setstacksize(&attr, stack_size + ZBLUE_STACK_EXTRA); + pthread_attr_setschedpolicy(&attr, SCHED_FIFO); + param.sched_priority = z_zblue_priority(prio); + pthread_attr_setschedparam(&attr, ¶m); + pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED); + + ret = pthread_create(&thread->pthread, &attr, thread_main, thread); + pthread_attr_destroy(&attr); + if (ret != 0) + { + return -ret; + } + + if (thread->name != NULL) + { + pthread_setname_np(thread->pthread, thread->name); + } + + return 0; +} + +k_tid_t k_thread_create(struct k_thread *new_thread, k_thread_stack_t *stack, + size_t stack_size, + void (*entry)(void *, void *, void *), + void *p1, void *p2, void *p3, + int prio, uint32_t options, k_timeout_t delay) +{ + UNUSED(stack); + UNUSED(options); + __ASSERT(K_TIMEOUT_EQ(delay, K_NO_WAIT), "delayed start not supported"); + + new_thread->entry = entry; + new_thread->p1 = p1; + new_thread->p2 = p2; + new_thread->p3 = p3; + + if (z_zblue_thread_start(new_thread, stack_size, prio) < 0) + { + return NULL; + } + + return new_thread; +} + +int k_thread_name_set(k_tid_t thread, const char *str) +{ + thread->name = str; + if (thread->pthread != 0) + { + pthread_setname_np(thread->pthread, str); + } + + return 0; +} + +void k_yield(void) +{ + int depth = z_zblue_block_begin(); + + sched_yield(); + z_zblue_block_end(depth); +} + +int32_t k_sleep(k_timeout_t timeout) +{ + struct timespec ts; + int depth; + + if (K_TIMEOUT_EQ(timeout, K_FOREVER)) + { + depth = z_zblue_block_begin(); + for (; ; ) + { + pause(); + } + } + + z_zblue_abstime(timeout, &ts); + depth = z_zblue_block_begin(); + while (clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &ts, NULL) == + EINTR); + z_zblue_block_end(depth); + return 0; +} + +int32_t k_msleep(int32_t ms) +{ + return k_sleep(K_MSEC(ms)); +} + +void k_busy_wait(uint32_t usec_to_wait) +{ + usleep(usec_to_wait); +} + +/* Time: one tick is one millisecond, one cycle one microsecond */ + +int64_t k_uptime_ticks(void) +{ + struct timespec ts; + + clock_gettime(CLOCK_MONOTONIC, &ts); + return (int64_t)ts.tv_sec * 1000 + ts.tv_nsec / 1000000; +} + +uint64_t k_cycle_get_64(void) +{ + struct timespec ts; + + clock_gettime(CLOCK_MONOTONIC, &ts); + return (uint64_t)ts.tv_sec * 1000000 + ts.tv_nsec / 1000; +} + +uint32_t k_cycle_get_32(void) +{ + return (uint32_t)k_cycle_get_64(); +} + +int64_t z_zblue_deadline(k_timeout_t timeout) +{ + if (K_TIMEOUT_EQ(timeout, K_FOREVER)) + { + return INT64_MAX; + } + + if (timeout.ticks < K_TICKS_FOREVER) + { + /* Absolute timeout, see Z_TICK_ABS() */ + + return K_TICKS_FOREVER - 1 - timeout.ticks; + } + + return k_uptime_ticks() + timeout.ticks; +} + +void z_zblue_abstime(k_timeout_t timeout, struct timespec *ts) +{ + int64_t ms = z_zblue_deadline(timeout); + + ts->tv_sec = ms / 1000; + ts->tv_nsec = (ms % 1000) * 1000000; +} + +k_timepoint_t sys_timepoint_calc(k_timeout_t timeout) +{ + k_timepoint_t tp; + + if (K_TIMEOUT_EQ(timeout, K_FOREVER)) + { + tp.tick = UINT64_MAX; + } + else if (K_TIMEOUT_EQ(timeout, K_NO_WAIT)) + { + tp.tick = 0; + } + else + { + tp.tick = z_zblue_deadline(timeout); + } + + return tp; +} + +k_timeout_t sys_timepoint_timeout(k_timepoint_t timepoint) +{ + int64_t now; + + if (timepoint.tick == UINT64_MAX) + { + return K_FOREVER; + } + + if (timepoint.tick == 0) + { + return K_NO_WAIT; + } + + now = k_uptime_ticks(); + return (int64_t)timepoint.tick > now ? + K_TICKS(timepoint.tick - now) : K_NO_WAIT; +} diff --git a/wireless/bluetooth/zblue/port/src/misc.c b/wireless/bluetooth/zblue/port/src/misc.c new file mode 100644 index 000000000..e67a2429e --- /dev/null +++ b/wireless/bluetooth/zblue/port/src/misc.c @@ -0,0 +1,173 @@ +/**************************************************************************** + * apps/wireless/bluetooth/zblue/port/src/misc.c + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. The + * ASF licenses this file to you 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. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <stdarg.h> +#include <stdio.h> +#include <sys/random.h> +#include <syslog.h> + +#include <zephyr/kernel.h> +#include <zephyr/device.h> +#include <zephyr/init.h> +#include <zephyr/random/random.h> +#include <zephyr/logging/log.h> + +#include "port.h" + +/**************************************************************************** + * Private Data + ****************************************************************************/ + +static pthread_once_t g_init_once = PTHREAD_ONCE_INIT; + +K_THREAD_STACK_DEFINE(g_sys_work_q_stack, + CONFIG_SYSTEM_WORKQUEUE_STACK_SIZE); + +/* Provided by the linker for the "zblue_init" section, see <zephyr/init.h> */ + +extern const struct z_zblue_init __start_zblue_init[]; +extern const struct z_zblue_init __stop_zblue_init[]; + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +static int init_cmp(const void *a, const void *b) +{ + const struct z_zblue_init *x = *(const struct z_zblue_init **)a; + const struct z_zblue_init *y = *(const struct z_zblue_init **)b; + + if (x->level != y->level) + { + return x->level - y->level; + } + + if (x->prio != y->prio) + { + return x->prio - y->prio; + } + + /* qsort() is not stable: keep the link order of equal entries */ + + return x < y ? -1 : x > y; +} + +static void kernel_init(void) +{ + const struct k_work_queue_config cfg = + { + .name = "sysworkq", + }; + + const struct z_zblue_init **list; + size_t n = __stop_zblue_init - __start_zblue_init; + size_t i; + int ret; + + k_work_queue_start(&k_sys_work_q, g_sys_work_q_stack, + K_THREAD_STACK_SIZEOF(g_sys_work_q_stack), + CONFIG_SYSTEM_WORKQUEUE_PRIORITY, &cfg); + + /* Run the SYS_INIT() entries in Zephyr order: by level, then priority */ + + list = malloc(n * sizeof(*list)); + __ASSERT_NO_MSG(n == 0 || list != NULL); + for (i = 0; i < n; i++) + { + list[i] = &__start_zblue_init[i]; + } + + qsort(list, n, sizeof(*list), init_cmp); + for (i = 0; i < n; i++) + { + ret = list[i]->init_fn(); + if (ret < 0) + { + syslog(Z_ZBLUE_SYSLOG_ERR, "zblue: init %p failed: %d\n", + list[i]->init_fn, ret); + } + } + + free(list); +} + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +/* Runs what the Zephyr kernel runs at boot: the system work queue and the + * SYS_INIT() functions. bt_enable() checks that the HCI device is ready + * before anything else, which is the first point zblue gets control. + */ + +void z_zblue_kernel_init(void) +{ + pthread_once(&g_init_once, kernel_init); +} + +bool z_impl_device_is_ready(const struct device *dev) +{ + z_zblue_kernel_init(); + return dev != NULL; +} + +/* Assertions: __ASSERT() failures end the program, as in Zephyr */ + +void zassert_vprint(const char *fmt, va_list ap) +{ + vsyslog(Z_ZBLUE_SYSLOG_ERR, fmt, ap); +} + +void zassert_fail(const char *cond, const char *file, unsigned int line, + const char *fmt, ...) +{ + char msg[128]; + va_list ap; + + msg[0] = '\0'; + if (fmt != NULL) + { + va_start(ap, fmt); + vsnprintf(msg, sizeof(msg), fmt, ap); + va_end(ap); + } + + syslog(Z_ZBLUE_SYSLOG_ERR, "zblue: assertion failed: %s at %s:%u %s\n", + cond != NULL ? cond : "?", file != NULL ? file : "?", line, msg); + abort(); +} + +/* Random numbers */ + +void z_impl_sys_rand_get(void *dst, size_t len) +{ + arc4random_buf(dst, len); +} + +int z_impl_sys_csrand_get(void *dst, size_t len) +{ + return getrandom(dst, len, 0) == (ssize_t)len ? 0 : -EIO; +} diff --git a/wireless/bluetooth/zblue/port/src/port.h b/wireless/bluetooth/zblue/port/src/port.h new file mode 100644 index 000000000..0e9beb020 --- /dev/null +++ b/wireless/bluetooth/zblue/port/src/port.h @@ -0,0 +1,75 @@ +/**************************************************************************** + * apps/wireless/bluetooth/zblue/port/src/port.h + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. The + * ASF licenses this file to you 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. + * + ****************************************************************************/ + +#ifndef __APPS_WIRELESS_BLUETOOTH_ZBLUE_PORT_SRC_PORT_H +#define __APPS_WIRELESS_BLUETOOTH_ZBLUE_PORT_SRC_PORT_H + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <time.h> + +#include <zephyr/kernel.h> + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +/* Zephyr stack sizes are tuned for 32-bit MCUs and no C library stdio. + * Give each thread some headroom on top. + */ + +#define ZBLUE_STACK_EXTRA (2048 * sizeof(void *) / 4) + +/**************************************************************************** + * Public Function Prototypes + ****************************************************************************/ + +/* Release the coop lock before blocking, and take it back after. Never + * call z_zblue_block_end() while holding another lock: the coop lock is + * always the outermost one. + */ + +int z_zblue_block_begin(void); +void z_zblue_block_end(int depth); + +void z_zblue_set_self(struct k_thread *thread); +int z_zblue_priority(int prio); +int z_zblue_thread_start(struct k_thread *thread, size_t stack_size, + int prio); + +/* Timeouts: absolute uptime in ticks (ms), INT64_MAX for K_FOREVER */ + +int64_t z_zblue_deadline(k_timeout_t timeout); +void z_zblue_abstime(k_timeout_t timeout, struct timespec *ts); + +/* Wait on cond with mutex held, until woken or the deadline passes. + * Returns ETIMEDOUT on timeout. + */ + +int z_zblue_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex, + int64_t deadline); + +void z_zblue_kernel_init(void); + +#endif /* __APPS_WIRELESS_BLUETOOTH_ZBLUE_PORT_SRC_PORT_H */ diff --git a/wireless/bluetooth/zblue/port/src/sync.c b/wireless/bluetooth/zblue/port/src/sync.c new file mode 100644 index 000000000..1fa1a9b78 --- /dev/null +++ b/wireless/bluetooth/zblue/port/src/sync.c @@ -0,0 +1,486 @@ +/**************************************************************************** + * apps/wireless/bluetooth/zblue/port/src/sync.c + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. The + * ASF licenses this file to you 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. + * + ****************************************************************************/ + +/* All blocking objects follow the same pattern: the object lock is only + * held for short sections, and a thread that has to wait first drops the + * object lock, releases the coop lock, then waits with the object lock + * held again. The coop lock is retaken only after the object lock is + * released, so the coop lock is always taken first. + */ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <malloc.h> +#include <string.h> + +#include <zephyr/kernel.h> + +#include "port.h" + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +int z_zblue_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex, + int64_t deadline) +{ + struct timespec ts; + + if (deadline == INT64_MAX) + { + return pthread_cond_wait(cond, mutex); + } + + ts.tv_sec = deadline / 1000; + ts.tv_nsec = (deadline % 1000) * 1000000; + return pthread_cond_clockwait(cond, mutex, CLOCK_MONOTONIC, &ts); +} + +/* Semaphores */ + +int k_sem_init(struct k_sem *sem, unsigned int initial_count, + unsigned int limit) +{ + if (limit == 0 || initial_count > limit) + { + return -EINVAL; + } + + pthread_mutex_init(&sem->lock, NULL); + pthread_cond_init(&sem->cond, NULL); + sem->count = initial_count; + sem->limit = limit; + return 0; +} + +int k_sem_take(struct k_sem *sem, k_timeout_t timeout) +{ + int64_t deadline; + int depth; + int ret = 0; + + pthread_mutex_lock(&sem->lock); + if (sem->count > 0) + { + sem->count--; + pthread_mutex_unlock(&sem->lock); + return 0; + } + + pthread_mutex_unlock(&sem->lock); + if (K_TIMEOUT_EQ(timeout, K_NO_WAIT)) + { + return -EBUSY; + } + + deadline = z_zblue_deadline(timeout); + depth = z_zblue_block_begin(); + pthread_mutex_lock(&sem->lock); + while (sem->count == 0 && ret != ETIMEDOUT) + { + ret = z_zblue_cond_wait(&sem->cond, &sem->lock, deadline); + } + + if (sem->count > 0) + { + sem->count--; + ret = 0; + } + else + { + ret = -EAGAIN; + } + + pthread_mutex_unlock(&sem->lock); + z_zblue_block_end(depth); + return ret; +} + +void k_sem_give(struct k_sem *sem) +{ + pthread_mutex_lock(&sem->lock); + if (sem->count < sem->limit) + { + sem->count++; + } + + pthread_cond_signal(&sem->cond); + pthread_mutex_unlock(&sem->lock); +} + +void k_sem_reset(struct k_sem *sem) +{ + pthread_mutex_lock(&sem->lock); + sem->count = 0; + pthread_mutex_unlock(&sem->lock); +} + +unsigned int k_sem_count_get(struct k_sem *sem) +{ + unsigned int count; + + pthread_mutex_lock(&sem->lock); + count = sem->count; + pthread_mutex_unlock(&sem->lock); + return count; +} + +/* Mutexes */ + +int k_mutex_init(struct k_mutex *mutex) +{ + pthread_mutex_init(&mutex->lock, NULL); + pthread_cond_init(&mutex->cond, NULL); + mutex->owner = NULL; + mutex->lock_count = 0; + return 0; +} + +int k_mutex_lock(struct k_mutex *mutex, k_timeout_t timeout) +{ + struct k_thread *self = k_current_get(); + int64_t deadline; + int depth; + int ret = 0; + + pthread_mutex_lock(&mutex->lock); + if (mutex->owner == NULL || mutex->owner == self) + { + mutex->owner = self; + mutex->lock_count++; + pthread_mutex_unlock(&mutex->lock); + return 0; + } + + pthread_mutex_unlock(&mutex->lock); + if (K_TIMEOUT_EQ(timeout, K_NO_WAIT)) + { + return -EBUSY; + } + + deadline = z_zblue_deadline(timeout); + depth = z_zblue_block_begin(); + pthread_mutex_lock(&mutex->lock); + while (mutex->owner != NULL && ret != ETIMEDOUT) + { + ret = z_zblue_cond_wait(&mutex->cond, &mutex->lock, deadline); + } + + if (mutex->owner == NULL) + { + mutex->owner = self; + mutex->lock_count = 1; + ret = 0; + } + else + { + ret = -EAGAIN; + } + + pthread_mutex_unlock(&mutex->lock); + z_zblue_block_end(depth); + return ret; +} + +int k_mutex_unlock(struct k_mutex *mutex) +{ + int ret = 0; + + pthread_mutex_lock(&mutex->lock); + if (mutex->owner != k_current_get()) + { + ret = mutex->owner == NULL ? -EINVAL : -EPERM; + } + else if (--mutex->lock_count == 0) + { + mutex->owner = NULL; + pthread_cond_signal(&mutex->cond); + } + + pthread_mutex_unlock(&mutex->lock); + return ret; +} + +/* Condition variables: use the lock of the k_mutex they are paired with */ + +int k_condvar_init(struct k_condvar *condvar) +{ + return -pthread_cond_init(&condvar->cond, NULL); +} + +int k_condvar_signal(struct k_condvar *condvar) +{ + return -pthread_cond_signal(&condvar->cond); +} + +int k_condvar_broadcast(struct k_condvar *condvar) +{ + return -pthread_cond_broadcast(&condvar->cond); +} + +int k_condvar_wait(struct k_condvar *condvar, struct k_mutex *mutex, + k_timeout_t timeout) +{ + struct k_thread *self = k_current_get(); + int64_t deadline = z_zblue_deadline(timeout); + uint32_t count; + int depth; + int ret; + + depth = z_zblue_block_begin(); + pthread_mutex_lock(&mutex->lock); + __ASSERT_NO_MSG(mutex->owner == self); + + count = mutex->lock_count; + mutex->owner = NULL; + mutex->lock_count = 0; + pthread_cond_signal(&mutex->cond); + + ret = K_TIMEOUT_EQ(timeout, K_NO_WAIT) ? ETIMEDOUT : + z_zblue_cond_wait(&condvar->cond, &mutex->lock, deadline); + + while (mutex->owner != NULL) + { + pthread_cond_wait(&mutex->cond, &mutex->lock); + } + + mutex->owner = self; + mutex->lock_count = count; + pthread_mutex_unlock(&mutex->lock); + z_zblue_block_end(depth); + return ret == ETIMEDOUT ? -EAGAIN : 0; +} + +/* Queues */ + +void k_queue_init(struct k_queue *queue) +{ + sys_sflist_init(&queue->data_q); + pthread_mutex_init(&queue->lock, NULL); + pthread_cond_init(&queue->cond, NULL); +} + +void k_queue_append(struct k_queue *queue, void *data) +{ + pthread_mutex_lock(&queue->lock); + sys_sflist_append(&queue->data_q, data); + pthread_cond_signal(&queue->cond); + pthread_mutex_unlock(&queue->lock); +} + +void k_queue_prepend(struct k_queue *queue, void *data) +{ + pthread_mutex_lock(&queue->lock); + sys_sflist_prepend(&queue->data_q, data); + pthread_cond_signal(&queue->cond); + pthread_mutex_unlock(&queue->lock); +} + +void *k_queue_get(struct k_queue *queue, k_timeout_t timeout) +{ + int64_t deadline; + void *data; + int depth; + int ret = 0; + + pthread_mutex_lock(&queue->lock); + data = sys_sflist_get(&queue->data_q); + pthread_mutex_unlock(&queue->lock); + if (data != NULL || K_TIMEOUT_EQ(timeout, K_NO_WAIT)) + { + return data; + } + + deadline = z_zblue_deadline(timeout); + depth = z_zblue_block_begin(); + pthread_mutex_lock(&queue->lock); + while ((data = sys_sflist_get(&queue->data_q)) == NULL && + ret != ETIMEDOUT) + { + ret = z_zblue_cond_wait(&queue->cond, &queue->lock, deadline); + } + + pthread_mutex_unlock(&queue->lock); + z_zblue_block_end(depth); + return data; +} + +bool k_queue_remove(struct k_queue *queue, void *data) +{ + bool ret; + + pthread_mutex_lock(&queue->lock); + ret = sys_sflist_find_and_remove(&queue->data_q, data); + pthread_mutex_unlock(&queue->lock); + return ret; +} + +void *k_queue_peek_head(struct k_queue *queue) +{ + void *data; + + pthread_mutex_lock(&queue->lock); + data = sys_sflist_peek_head(&queue->data_q); + pthread_mutex_unlock(&queue->lock); + return data; +} + +void *k_queue_peek_tail(struct k_queue *queue) +{ + void *data; + + pthread_mutex_lock(&queue->lock); + data = sys_sflist_peek_tail(&queue->data_q); + pthread_mutex_unlock(&queue->lock); + return data; +} + +int k_queue_is_empty(struct k_queue *queue) +{ + int ret; + + pthread_mutex_lock(&queue->lock); + ret = sys_sflist_is_empty(&queue->data_q); + pthread_mutex_unlock(&queue->lock); + return ret; +} + +void k_queue_cancel_wait(struct k_queue *queue) +{ + pthread_mutex_lock(&queue->lock); + pthread_cond_broadcast(&queue->cond); + pthread_mutex_unlock(&queue->lock); +} + +/* Memory slabs: the free blocks are kept in a LIFO, filled on first use + * because K_MEM_SLAB_DEFINE() must be a static initializer. + */ + +static void slab_fill(struct k_mem_slab *slab) +{ + uint32_t i; + + pthread_mutex_lock(&slab->free_q._queue.lock); + if (!slab->ready) + { + for (i = 0; i < slab->num_blocks; i++) + { + sys_sflist_append(&slab->free_q._queue.data_q, + (sys_sfnode_t *)(slab->buffer + + i * slab->block_size)); + } + + slab->ready = true; + } + + pthread_mutex_unlock(&slab->free_q._queue.lock); +} + +int k_mem_slab_init(struct k_mem_slab *slab, void *buffer, + size_t block_size, uint32_t num_blocks) +{ + memset(slab, 0, sizeof(*slab)); + k_lifo_init(&slab->free_q); + slab->buffer = buffer; + slab->block_size = block_size; + slab->num_blocks = num_blocks; + return 0; +} + +int k_mem_slab_alloc(struct k_mem_slab *slab, void **mem, + k_timeout_t timeout) +{ + if (!slab->ready) + { + slab_fill(slab); + } + + *mem = k_lifo_get(&slab->free_q, timeout); + if (*mem == NULL) + { + return K_TIMEOUT_EQ(timeout, K_NO_WAIT) ? -ENOMEM : -EAGAIN; + } + + __atomic_fetch_add(&slab->num_used, 1, __ATOMIC_RELAXED); + return 0; +} + +void k_mem_slab_free(struct k_mem_slab *slab, void *mem) +{ + __atomic_fetch_sub(&slab->num_used, 1, __ATOMIC_RELAXED); + k_lifo_put(&slab->free_q, mem); +} + +uint32_t k_mem_slab_num_used_get(struct k_mem_slab *slab) +{ + return slab->num_used; +} + +uint32_t k_mem_slab_num_free_get(struct k_mem_slab *slab) +{ + return slab->num_blocks - slab->num_used; +} + +/* Heap */ + +void *k_heap_alloc(struct k_heap *h, size_t bytes, k_timeout_t timeout) +{ + UNUSED(h); + UNUSED(timeout); + return malloc(bytes); +} + +void *k_heap_aligned_alloc(struct k_heap *h, size_t align, size_t bytes, + k_timeout_t timeout) +{ + UNUSED(h); + UNUSED(timeout); + return memalign(align, bytes); +} + +void k_heap_free(struct k_heap *h, void *mem) +{ + UNUSED(h); + free(mem); +} + +void *k_malloc(size_t size) +{ + return malloc(size); +} + +void *k_calloc(size_t nmemb, size_t size) +{ + return calloc(nmemb, size); +} + +void *k_aligned_alloc(size_t align, size_t size) +{ + return memalign(align, size); +} + +void k_free(void *ptr) +{ + free(ptr); +} diff --git a/wireless/bluetooth/zblue/port/src/work.c b/wireless/bluetooth/zblue/port/src/work.c new file mode 100644 index 000000000..61155f564 --- /dev/null +++ b/wireless/bluetooth/zblue/port/src/work.c @@ -0,0 +1,535 @@ +/**************************************************************************** + * apps/wireless/bluetooth/zblue/port/src/work.c + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. The + * ASF licenses this file to you 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. + * + ****************************************************************************/ + +/* Zephyr work queues on NuttX work queues (work_queue_create()). + * + * Each k_work_q is a NuttX work queue with one thread. The NuttX work + * item of a k_work only runs work_entry() on that thread when the item is + * due. The Zephyr state (QUEUED, DELAYED, RUNNING, CANCELING) is kept in + * the k_work flags, under one lock, and gives the Zephyr return values; + * work_entry() checks it and does nothing for an item that was cancelled + * or rescheduled after NuttX had already taken it. The waits of flush() + * and cancel_sync() use one shared condition. + */ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <zephyr/kernel.h> + +#include "port.h" + +/**************************************************************************** + * Private Data + ****************************************************************************/ + +static pthread_mutex_t g_work_lock = PTHREAD_MUTEX_INITIALIZER; +static pthread_cond_t g_work_done = PTHREAD_COND_INITIALIZER; + +struct k_work_q k_sys_work_q; + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +static void work_entry(FAR void *arg); + +/* A delayed item that is due counts as queued, as in Zephyr */ + +static uint32_t busy_locked(const struct k_work *work) +{ + uint32_t flags = work->flags; + + if ((flags & K_WORK_DELAYED) && + CONTAINER_OF(work, struct k_work_delayable, work)->expiry <= + k_uptime_ticks()) + { + flags = (flags & ~K_WORK_DELAYED) | K_WORK_QUEUED; + } + + return flags & K_WORK_MASK; +} + +static void expire_locked(struct k_work *work) +{ + work->flags = (work->flags & ~K_WORK_MASK) | busy_locked(work); +} + +/* Queue the NuttX work item for the time the k_work is due */ + +static void arm_locked(struct k_work *work) +{ + struct k_work_q *queue = work->queue; + int64_t delay = 0; + int64_t ticks; + int ret; + + if ((work->flags & (K_WORK_QUEUED | K_WORK_DELAYED)) == 0) + { + return; + } + + if ((work->flags & K_WORK_QUEUED) == 0) + { + delay = k_work_delayable_from_work(work)->expiry; + if (delay == INT64_MAX) + { + /* K_FOREVER: never due */ + + work_cancel_wq(queue->wq, &work->nxwork); + return; + } + + delay = MAX(delay - k_uptime_ticks(), 0); + } + + /* Zephyr ticks are milliseconds. A delay longer than NuttX allows + * fires early; work_entry() then queues the item again. + */ + + ticks = (delay * 1000 + CONFIG_USEC_PER_TICK - 1) / CONFIG_USEC_PER_TICK; + ret = work_queue_wq(queue->wq, &work->nxwork, work_entry, work, + MIN(ticks, WDOG_MAX_DELAY)); + __ASSERT(ret == 0, "work_queue_wq: %d", ret); + ARG_UNUSED(ret); +} + +static int submit_locked(struct k_work *work, struct k_work_q *queue) +{ + int ret; + + expire_locked(work); + if (work->flags & K_WORK_CANCELING) + { + return -EBUSY; + } + + if (work->flags & K_WORK_QUEUED) + { + return 0; + } + + ret = 1; + if (queue == NULL) + { + queue = work->queue; + } + + if (work->flags & K_WORK_RUNNING) + { + queue = work->queue; + ret = 2; + } + + if (queue == NULL) + { + return -EINVAL; + } + + work->queue = queue; + work->flags |= K_WORK_QUEUED; + arm_locked(work); + return ret; +} + +static bool unschedule_locked(struct k_work_delayable *dwork) +{ + struct k_work *work = &dwork->work; + + if ((work->flags & K_WORK_DELAYED) == 0) + { + return false; + } + + work->flags &= ~K_WORK_DELAYED; + if ((work->flags & K_WORK_QUEUED) == 0) + { + work_cancel_wq(work->queue->wq, &work->nxwork); + } + + return true; +} + +static int schedule_locked(struct k_work_q *queue, + struct k_work_delayable *dwork, + k_timeout_t delay) +{ + struct k_work *work = &dwork->work; + + if (K_TIMEOUT_EQ(delay, K_NO_WAIT)) + { + return submit_locked(work, queue); + } + + /* A queued or running item stays on its queue */ + + if ((work->flags & (K_WORK_QUEUED | K_WORK_RUNNING)) == 0) + { + work->queue = queue; + } + + work->flags |= K_WORK_DELAYED; + dwork->expiry = z_zblue_deadline(delay); + arm_locked(work); + return 1; +} + +static int cancel_async_locked(struct k_work *work) +{ + if ((work->flags & K_WORK_CANCELING) == 0 && + (work->flags & K_WORK_QUEUED)) + { + work->flags &= ~K_WORK_QUEUED; + if ((work->flags & K_WORK_DELAYED) == 0) + { + work_cancel_wq(work->queue->wq, &work->nxwork); + } + + pthread_cond_broadcast(&g_work_done); + } + + if (work->flags & K_WORK_MASK) + { + work->flags |= K_WORK_CANCELING; + } + + return work->flags & K_WORK_MASK; +} + +static void wait_locked(struct k_work *work, uint32_t mask) +{ + int depth; + + if ((work->flags & mask) == 0) + { + return; + } + + /* g_work_lock is dropped while the coop lock is released, so the coop + * lock is never taken with g_work_lock held. + */ + + pthread_mutex_unlock(&g_work_lock); + depth = z_zblue_block_begin(); + pthread_mutex_lock(&g_work_lock); + while (work->flags & mask) + { + pthread_cond_wait(&g_work_done, &g_work_lock); + } + + pthread_mutex_unlock(&g_work_lock); + z_zblue_block_end(depth); + pthread_mutex_lock(&g_work_lock); +} + +/* Run by NuttX on the queue thread */ + +static void work_entry(FAR void *arg) +{ + struct k_work *work = arg; + struct k_work_q *queue; + + pthread_mutex_lock(&g_work_lock); + expire_locked(work); + queue = work->queue; + if (k_current_get() != queue->thread_id || + (work->flags & K_WORK_QUEUED) == 0) + { + /* Not due here: cancelled, rescheduled or on another queue */ + + if (work->nxwork.worker == NULL) + { + arm_locked(work); + } + + pthread_mutex_unlock(&g_work_lock); + return; + } + + work->flags &= ~K_WORK_QUEUED; + work->flags |= K_WORK_RUNNING; + pthread_mutex_unlock(&g_work_lock); + + if (queue->thread.coop) + { + k_sched_lock(); + } + + work->handler(work); + + if (queue->thread.coop) + { + k_sched_unlock(); + } + + pthread_mutex_lock(&g_work_lock); + work->flags &= ~(K_WORK_RUNNING | K_WORK_CANCELING); + pthread_cond_broadcast(&g_work_done); + + /* Rescheduled while it ran, behind an item still queued */ + + if (work->nxwork.worker == NULL) + { + arm_locked(work); + } + + pthread_mutex_unlock(&g_work_lock); +} + +/* First item of every queue: makes k_current_get() the queue thread */ + +static void queue_start_entry(FAR void *arg) +{ + struct k_work_q *queue = arg; + + queue->thread.pthread = pthread_self(); + pthread_setname_np(queue->thread.pthread, queue->thread.name); + z_zblue_set_self(&queue->thread); +} + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +void k_work_init(struct k_work *work, k_work_handler_t handler) +{ + memset(work, 0, sizeof(*work)); + work->handler = handler; +} + +int k_work_busy_get(const struct k_work *work) +{ + int ret; + + pthread_mutex_lock(&g_work_lock); + ret = busy_locked(work); + pthread_mutex_unlock(&g_work_lock); + return ret; +} + +int k_work_submit_to_queue(struct k_work_q *queue, struct k_work *work) +{ + int ret; + + pthread_mutex_lock(&g_work_lock); + ret = submit_locked(work, queue); + pthread_mutex_unlock(&g_work_lock); + return ret; +} + +int k_work_submit(struct k_work *work) +{ + return k_work_submit_to_queue(&k_sys_work_q, work); +} + +bool k_work_flush(struct k_work *work, struct k_work_sync *sync) +{ + bool busy; + + UNUSED(sync); + pthread_mutex_lock(&g_work_lock); + busy = (work->flags & (K_WORK_QUEUED | K_WORK_RUNNING)) != 0; + wait_locked(work, K_WORK_QUEUED | K_WORK_RUNNING); + pthread_mutex_unlock(&g_work_lock); + return busy; +} + +int k_work_cancel(struct k_work *work) +{ + int ret; + + pthread_mutex_lock(&g_work_lock); + ret = cancel_async_locked(work); + pthread_mutex_unlock(&g_work_lock); + return ret; +} + +bool k_work_cancel_sync(struct k_work *work, struct k_work_sync *sync) +{ + bool pending; + + UNUSED(sync); + pthread_mutex_lock(&g_work_lock); + pending = (work->flags & K_WORK_MASK) != 0; + if (pending) + { + cancel_async_locked(work); + wait_locked(work, K_WORK_CANCELING); + } + + pthread_mutex_unlock(&g_work_lock); + return pending; +} + +void k_work_queue_init(struct k_work_q *queue) +{ + memset(queue, 0, sizeof(*queue)); +} + +void k_work_queue_start(struct k_work_q *queue, k_thread_stack_t *stack, + size_t stack_size, int prio, + const struct k_work_queue_config *cfg) +{ + UNUSED(stack); + + queue->thread.name = (cfg != NULL && cfg->name != NULL) ? + cfg->name : "zblue_wq"; + queue->thread.prio = prio; + queue->thread.coop = prio < 0; + queue->thread_id = &queue->thread; + + queue->wq = work_queue_create(queue->thread.name, z_zblue_priority(prio), + NULL, stack_size + ZBLUE_STACK_EXTRA, 1); + if (queue->wq == NULL || + work_queue_wq(queue->wq, &queue->start, queue_start_entry, + queue, 0) < 0) + { + __ASSERT(0, "cannot start work queue %s", queue->thread.name); + } +} + +void k_work_init_delayable(struct k_work_delayable *dwork, + k_work_handler_t handler) +{ + memset(dwork, 0, sizeof(*dwork)); + dwork->work.handler = handler; +} + +int k_work_delayable_busy_get(const struct k_work_delayable *dwork) +{ + return k_work_busy_get(&dwork->work); +} + +k_ticks_t k_work_delayable_remaining_get( + const struct k_work_delayable *dwork) +{ + k_ticks_t ret = 0; + int64_t now; + + pthread_mutex_lock(&g_work_lock); + if (dwork->work.flags & K_WORK_DELAYED) + { + now = k_uptime_ticks(); + ret = dwork->expiry > now ? dwork->expiry - now : 0; + } + + pthread_mutex_unlock(&g_work_lock); + return ret; +} + +int k_work_schedule_for_queue(struct k_work_q *queue, + struct k_work_delayable *dwork, + k_timeout_t delay) +{ + int ret = 0; + + pthread_mutex_lock(&g_work_lock); + expire_locked(&dwork->work); + if ((dwork->work.flags & K_WORK_MASK & ~K_WORK_RUNNING) == 0) + { + ret = schedule_locked(queue, dwork, delay); + } + + pthread_mutex_unlock(&g_work_lock); + return ret; +} + +int k_work_schedule(struct k_work_delayable *dwork, k_timeout_t delay) +{ + return k_work_schedule_for_queue(&k_sys_work_q, dwork, delay); +} + +int k_work_reschedule_for_queue(struct k_work_q *queue, + struct k_work_delayable *dwork, + k_timeout_t delay) +{ + int ret; + + pthread_mutex_lock(&g_work_lock); + expire_locked(&dwork->work); + unschedule_locked(dwork); + ret = schedule_locked(queue, dwork, delay); + pthread_mutex_unlock(&g_work_lock); + return ret; +} + +int k_work_reschedule(struct k_work_delayable *dwork, k_timeout_t delay) +{ + return k_work_reschedule_for_queue(&k_sys_work_q, dwork, delay); +} + +bool k_work_flush_delayable(struct k_work_delayable *dwork, + struct k_work_sync *sync) +{ + struct k_work *work = &dwork->work; + + UNUSED(sync); + pthread_mutex_lock(&g_work_lock); + expire_locked(work); + if ((work->flags & K_WORK_MASK) == 0) + { + pthread_mutex_unlock(&g_work_lock); + return false; + } + + if (unschedule_locked(dwork)) + { + submit_locked(work, work->queue); + } + + wait_locked(work, K_WORK_QUEUED | K_WORK_RUNNING); + pthread_mutex_unlock(&g_work_lock); + return true; +} + +int k_work_cancel_delayable(struct k_work_delayable *dwork) +{ + int ret; + + pthread_mutex_lock(&g_work_lock); + expire_locked(&dwork->work); + unschedule_locked(dwork); + ret = cancel_async_locked(&dwork->work); + pthread_mutex_unlock(&g_work_lock); + return ret; +} + +bool k_work_cancel_delayable_sync(struct k_work_delayable *dwork, + struct k_work_sync *sync) +{ + bool pending; + + UNUSED(sync); + pthread_mutex_lock(&g_work_lock); + expire_locked(&dwork->work); + pending = (dwork->work.flags & K_WORK_MASK) != 0; + if (pending) + { + unschedule_locked(dwork); + cancel_async_locked(&dwork->work); + wait_locked(&dwork->work, K_WORK_CANCELING); + } + + pthread_mutex_unlock(&g_work_lock); + return pending; +}
