LCOV - code coverage report
Current view: top level - /home/ubuntu/zephyrproject/zephyr/kernel - thread.c (source / functions) Coverage Total Hit
Test: lcov.info Lines: 59.5 % 227 135
Test Date: 2026-11-06 14:43:19 Functions: 48.4 % 31 15
Legend: Lines: hit not hit | Branches: + taken - not taken # not executed Branches: 25.6 % 78 20

             Branch data     Line data    Source code
       1                 :             : /*
       2                 :             :  * Copyright (c) 2010-2014 Wind River Systems, Inc.
       3                 :             :  *
       4                 :             :  * SPDX-License-Identifier: Apache-2.0
       5                 :             :  */
       6                 :             : 
       7                 :             : /**
       8                 :             :  * @file
       9                 :             :  * @brief Kernel thread support
      10                 :             :  *
      11                 :             :  * This module provides general purpose thread support.
      12                 :             :  */
      13                 :             : 
      14                 :             : #include <zephyr/kernel.h>
      15                 :             : #include <zephyr/spinlock.h>
      16                 :             : #include <zephyr/sys/math_extras.h>
      17                 :             : #include <zephyr/sys/clock.h>
      18                 :             : #include <ksched.h>
      19                 :             : #include <kthread.h>
      20                 :             : #include <wait_q.h>
      21                 :             : #include <timeout_q.h>
      22                 :             : #include <zephyr/internal/syscall_handler.h>
      23                 :             : #include <kernel_internal.h>
      24                 :             : #include <ksmp.h>
      25                 :             : #include <kswap.h>
      26                 :             : #include <zephyr/init.h>
      27                 :             : #include <zephyr/tracing/tracing.h>
      28                 :             : #include <string.h>
      29                 :             : #include <stdbool.h>
      30                 :             : #include <zephyr/sys/check.h>
      31                 :             : #include <zephyr/random/random.h>
      32                 :             : #include <zephyr/sys/atomic.h>
      33                 :             : #include <zephyr/logging/log.h>
      34                 :             : #include <zephyr/llext/symbol.h>
      35                 :             : #include <zephyr/sys/iterable_sections.h>
      36                 :             : #include <zephyr/sys/minmax.h>
      37                 :             : 
      38                 :             : #include <usage.h>
      39                 :             : 
      40                 :             : LOG_MODULE_DECLARE(os, CONFIG_KERNEL_LOG_LEVEL);
      41                 :             : 
      42                 :             : #ifdef CONFIG_OBJ_CORE_THREAD
      43                 :             : #ifdef CONFIG_OBJ_CORE_STATS_THREAD
      44                 :             : static struct k_obj_core_stats_desc  thread_stats_desc = {
      45                 :             :         .raw_size = sizeof(struct k_cycle_stats),
      46                 :             :         .query_size = sizeof(struct k_thread_runtime_stats),
      47                 :             :         .raw   = z_thread_stats_raw,
      48                 :             :         .query = z_thread_stats_query,
      49                 :             :         .reset = z_thread_stats_reset,
      50                 :             :         .disable = z_thread_stats_disable,
      51                 :             :         .enable  = z_thread_stats_enable,
      52                 :             : };
      53                 :             : #endif /* CONFIG_OBJ_CORE_STATS_THREAD */
      54                 :             : 
      55                 :             : /* Threads have no statically defined instances to walk; each thread links its
      56                 :             :  * own object core as it is created (see z_setup_new_thread()). Register the
      57                 :             :  * type only.
      58                 :             :  */
      59                 :             : #ifdef CONFIG_OBJ_CORE_STATS_THREAD
      60                 :             : K_OBJ_TYPE_DEFINE_TYPE_ONLY(obj_type_thread, k_thread, K_OBJ_TYPE_THREAD_ID,
      61                 :             :                             &thread_stats_desc);
      62                 :             : #else
      63                 :             : K_OBJ_TYPE_DEFINE_TYPE_ONLY(obj_type_thread, k_thread, K_OBJ_TYPE_THREAD_ID,
      64                 :             :                             NULL);
      65                 :             : #endif /* CONFIG_OBJ_CORE_STATS_THREAD */
      66                 :             : #endif /* CONFIG_OBJ_CORE_THREAD */
      67                 :             : 
      68                 :             : 
      69                 :             : #define _FOREACH_STATIC_THREAD(thread_data)              \
      70                 :             :         STRUCT_SECTION_FOREACH(_static_thread_data, thread_data)
      71                 :             : 
      72                 :           0 : bool k_is_in_isr(void)
      73                 :             : {
      74                 :           0 :         return arch_is_in_isr();
      75                 :             : }
      76                 :             : EXPORT_SYMBOL(k_is_in_isr);
      77                 :             : 
      78                 :             : #ifdef CONFIG_THREAD_CUSTOM_DATA
      79                 :             : void z_impl_k_thread_custom_data_set(void *value)
      80                 :             : {
      81                 :             :         _current->custom_data = value;
      82                 :             : }
      83                 :             : 
      84                 :             : #ifdef CONFIG_USERSPACE
      85                 :             : static inline void z_vrfy_k_thread_custom_data_set(void *data)
      86                 :             : {
      87                 :             :         z_impl_k_thread_custom_data_set(data);
      88                 :             : }
      89                 :             : #include <zephyr/syscalls/k_thread_custom_data_set_mrsh.c>
      90                 :             : #endif /* CONFIG_USERSPACE */
      91                 :             : 
      92                 :             : void *z_impl_k_thread_custom_data_get(void)
      93                 :             : {
      94                 :             :         return _current->custom_data;
      95                 :             : }
      96                 :             : 
      97                 :             : #ifdef CONFIG_USERSPACE
      98                 :             : static inline void *z_vrfy_k_thread_custom_data_get(void)
      99                 :             : {
     100                 :             :         return z_impl_k_thread_custom_data_get();
     101                 :             : }
     102                 :             : #include <zephyr/syscalls/k_thread_custom_data_get_mrsh.c>
     103                 :             : 
     104                 :             : #endif /* CONFIG_USERSPACE */
     105                 :             : #endif /* CONFIG_THREAD_CUSTOM_DATA */
     106                 :             : 
     107                 :           0 : int z_impl_k_is_preempt_thread(void)
     108                 :             : {
     109   [ #  #  #  # ]:           0 :         return !arch_is_in_isr() && thread_is_preemptible(_current);
     110                 :             : }
     111                 :             : 
     112                 :             : #ifdef CONFIG_USERSPACE
     113                 :             : static inline int z_vrfy_k_is_preempt_thread(void)
     114                 :             : {
     115                 :             :         return z_impl_k_is_preempt_thread();
     116                 :             : }
     117                 :             : #include <zephyr/syscalls/k_is_preempt_thread_mrsh.c>
     118                 :             : #endif /* CONFIG_USERSPACE */
     119                 :             : 
     120                 :           0 : int z_impl_k_thread_priority_get(k_tid_t thread)
     121                 :             : {
     122                 :           0 :         return thread->base.prio;
     123                 :             : }
     124                 :             : 
     125                 :             : #ifdef CONFIG_USERSPACE
     126                 :             : static inline int z_vrfy_k_thread_priority_get(k_tid_t thread)
     127                 :             : {
     128                 :             :         K_OOPS(K_SYSCALL_OBJ(thread, K_OBJ_THREAD));
     129                 :             :         return z_impl_k_thread_priority_get(thread);
     130                 :             : }
     131                 :             : #include <zephyr/syscalls/k_thread_priority_get_mrsh.c>
     132                 :             : #endif /* CONFIG_USERSPACE */
     133                 :             : 
     134                 :             : #ifdef CONFIG_THREAD_NAME
     135                 :         106 : static void set_thread_name(struct k_thread *thread, const char *str)
     136                 :             : {
     137         [ +  + ]:         106 :         if (str != NULL) {
     138                 :          52 :                 strncpy(thread->name, str, CONFIG_THREAD_MAX_NAME_LEN - 1);
     139                 :             :                 /* Ensure NULL termination, truncate if longer */
     140                 :          52 :                 thread->name[CONFIG_THREAD_MAX_NAME_LEN - 1] = '\0';
     141                 :             : #ifdef CONFIG_ARCH_HAS_THREAD_NAME_HOOK
     142                 :          52 :                 arch_thread_name_set(thread, str);
     143                 :             : #endif /* CONFIG_ARCH_HAS_THREAD_NAME_HOOK */
     144                 :             :         } else {
     145                 :          54 :                 thread->name[0] = '\0';
     146                 :             :         }
     147                 :         106 : }
     148                 :             : #endif /* CONFIG_THREAD_NAME */
     149                 :             : 
     150                 :          50 : int z_impl_k_thread_name_set(k_tid_t thread, const char *str)
     151                 :             : {
     152                 :             : #ifdef CONFIG_THREAD_NAME
     153         [ -  + ]:          50 :         if (thread == NULL) {
     154                 :           0 :                 thread = _current;
     155                 :             :         }
     156                 :             : 
     157                 :          50 :         set_thread_name(thread, str);
     158                 :             : 
     159                 :          50 :         SYS_PORT_TRACING_OBJ_FUNC(k_thread, name_set, thread, 0);
     160                 :             : 
     161                 :          50 :         return 0;
     162                 :             : #else
     163                 :             :         ARG_UNUSED(thread);
     164                 :             :         ARG_UNUSED(str);
     165                 :             : 
     166                 :             :         SYS_PORT_TRACING_OBJ_FUNC(k_thread, name_set, thread, -ENOSYS);
     167                 :             : 
     168                 :             :         return -ENOSYS;
     169                 :             : #endif /* CONFIG_THREAD_NAME */
     170                 :             : }
     171                 :             : 
     172                 :             : #ifdef CONFIG_USERSPACE
     173                 :             : static inline int z_vrfy_k_thread_name_set(k_tid_t thread, const char *str)
     174                 :             : {
     175                 :             : #ifdef CONFIG_THREAD_NAME
     176                 :             :         char name[CONFIG_THREAD_MAX_NAME_LEN];
     177                 :             : 
     178                 :             :         if (thread != NULL) {
     179                 :             :                 if (K_SYSCALL_OBJ(thread, K_OBJ_THREAD) != 0) {
     180                 :             :                         return -EINVAL;
     181                 :             :                 }
     182                 :             :         }
     183                 :             : 
     184                 :             :         /* In theory we could copy directly into thread->name, but
     185                 :             :          * the current z_vrfy / z_impl split does not provide a
     186                 :             :          * means of doing so.
     187                 :             :          */
     188                 :             :         if (k_usermode_string_copy(name, str, sizeof(name)) != 0) {
     189                 :             :                 return -EFAULT;
     190                 :             :         }
     191                 :             : 
     192                 :             :         return z_impl_k_thread_name_set(thread, name);
     193                 :             : #else
     194                 :             :         return -ENOSYS;
     195                 :             : #endif /* CONFIG_THREAD_NAME */
     196                 :             : }
     197                 :             : #include <zephyr/syscalls/k_thread_name_set_mrsh.c>
     198                 :             : #endif /* CONFIG_USERSPACE */
     199                 :             : 
     200                 :           0 : const char *k_thread_name_get(k_tid_t thread)
     201                 :             : {
     202                 :             : #ifdef CONFIG_THREAD_NAME
     203                 :           0 :         return (const char *)thread->name;
     204                 :             : #else
     205                 :             :         ARG_UNUSED(thread);
     206                 :             :         return NULL;
     207                 :             : #endif /* CONFIG_THREAD_NAME */
     208                 :             : }
     209                 :             : 
     210                 :           0 : int z_impl_k_thread_name_copy(k_tid_t thread, char *buf, size_t size)
     211                 :             : {
     212                 :             : #ifdef CONFIG_THREAD_NAME
     213                 :           0 :         strncpy(buf, thread->name, size);
     214                 :           0 :         return 0;
     215                 :             : #else
     216                 :             :         ARG_UNUSED(thread);
     217                 :             :         ARG_UNUSED(buf);
     218                 :             :         ARG_UNUSED(size);
     219                 :             :         return -ENOSYS;
     220                 :             : #endif /* CONFIG_THREAD_NAME */
     221                 :             : }
     222                 :             : 
     223                 :           0 : static size_t copy_bytes(char *dest, size_t dest_size, const char *src, size_t src_size)
     224                 :             : {
     225                 :           0 :         size_t  bytes_to_copy;
     226                 :             : 
     227                 :           0 :         bytes_to_copy = min(dest_size, src_size);
     228                 :           0 :         memcpy(dest, src, bytes_to_copy);
     229                 :             : 
     230                 :           0 :         return bytes_to_copy;
     231                 :             : }
     232                 :             : 
     233                 :           0 : const char *k_thread_state_str(k_tid_t thread_id, char *buf, size_t buf_size)
     234                 :             : {
     235                 :           0 :         size_t      off = 0;
     236                 :           0 :         uint8_t     bit;
     237                 :           0 :         uint8_t     thread_state = thread_id->base.thread_state;
     238                 :             : #define SS_ENT(s) { Z_STATE_STR_##s, _THREAD_##s, sizeof(Z_STATE_STR_##s) - 1 }
     239                 :           0 :         static const struct {
     240                 :             :                 const char *str;
     241                 :             :                 uint16_t    bit;
     242                 :             :                 uint16_t    len;
     243                 :             :         } state_string[] = {
     244                 :             :                 SS_ENT(DUMMY),
     245                 :             :                 SS_ENT(PENDING),
     246                 :             :                 SS_ENT(SLEEPING),
     247                 :             :                 SS_ENT(DEAD),
     248                 :             :                 SS_ENT(SUSPENDED),
     249                 :             :                 SS_ENT(ABORTING),
     250                 :             :                 SS_ENT(SUSPENDING),
     251                 :             :                 SS_ENT(QUEUED),
     252                 :             :         };
     253                 :             : #undef SS_ENT
     254                 :             : 
     255         [ #  # ]:           0 :         if ((buf == NULL) || (buf_size == 0)) {
     256                 :             :                 return "";
     257                 :             :         }
     258                 :             : 
     259                 :           0 :         buf_size--;   /* Reserve 1 byte for end-of-string character */
     260                 :             : 
     261                 :             :         /*
     262                 :             :          * Loop through each bit in the thread_state. Stop once all have
     263                 :             :          * been processed. If more than one thread_state bit is set, then
     264                 :             :          * separate the descriptive strings with a '+'.
     265                 :             :          */
     266                 :             : 
     267                 :             : 
     268         [ #  # ]:           0 :         for (unsigned int index = 0; thread_state != 0; index++) {
     269                 :           0 :                 bit = state_string[index].bit;
     270         [ #  # ]:           0 :                 if ((thread_state & bit) == 0) {
     271                 :           0 :                         continue;
     272                 :             :                 }
     273                 :             : 
     274                 :           0 :                 off += copy_bytes(buf + off, buf_size - off,
     275                 :           0 :                                   state_string[index].str,
     276                 :           0 :                                   state_string[index].len);
     277                 :             : 
     278                 :           0 :                 thread_state &= ~bit;
     279                 :             : 
     280         [ #  # ]:           0 :                 if (thread_state != 0) {
     281                 :           0 :                         off += copy_bytes(buf + off, buf_size - off, "+", 1);
     282                 :             :                 }
     283                 :             :         }
     284                 :             : 
     285                 :           0 :         buf[off] = '\0';
     286                 :             : 
     287                 :           0 :         return (const char *)buf;
     288                 :             : }
     289                 :             : 
     290                 :             : #ifdef CONFIG_USERSPACE
     291                 :             : static inline int z_vrfy_k_thread_name_copy(k_tid_t thread,
     292                 :             :                                             char *buf, size_t size)
     293                 :             : {
     294                 :             : #ifdef CONFIG_THREAD_NAME
     295                 :             :         size_t len;
     296                 :             :         struct k_object *ko = k_object_find(thread);
     297                 :             : 
     298                 :             :         /* Special case: we allow reading the names of initialized threads
     299                 :             :          * even if we don't have permission on them
     300                 :             :          */
     301                 :             :         if ((ko == NULL) || (ko->type != K_OBJ_THREAD) ||
     302                 :             :                 ((ko->flags & K_OBJ_FLAG_INITIALIZED) == 0)) {
     303                 :             :                 return -EINVAL;
     304                 :             :         }
     305                 :             :         if (K_SYSCALL_MEMORY_WRITE(buf, size) != 0) {
     306                 :             :                 return -EFAULT;
     307                 :             :         }
     308                 :             :         len = strlen(thread->name);
     309                 :             :         if ((len + 1) > size) {
     310                 :             :                 return -ENOSPC;
     311                 :             :         }
     312                 :             : 
     313                 :             :         return k_usermode_to_copy((void *)buf, thread->name, len + 1);
     314                 :             : #else
     315                 :             :         ARG_UNUSED(thread);
     316                 :             :         ARG_UNUSED(buf);
     317                 :             :         ARG_UNUSED(size);
     318                 :             :         return -ENOSYS;
     319                 :             : #endif /* CONFIG_THREAD_NAME */
     320                 :             : }
     321                 :             : #include <zephyr/syscalls/k_thread_name_copy_mrsh.c>
     322                 :             : #endif /* CONFIG_USERSPACE */
     323                 :             : 
     324                 :             : #ifdef CONFIG_STACK_SENTINEL
     325                 :             : /* Check that the stack sentinel is still present
     326                 :             :  *
     327                 :             :  * The stack sentinel feature writes a magic value to the lowest 4 bytes of
     328                 :             :  * the thread's stack when the thread is initialized. This value gets checked
     329                 :             :  * in a few places:
     330                 :             :  *
     331                 :             :  * 1) In k_yield() if the current thread is not swapped out
     332                 :             :  * 2) After servicing a non-nested interrupt
     333                 :             :  * 3) In z_swap(), check the sentinel in the outgoing thread
     334                 :             :  *
     335                 :             :  * Item 2 requires support in arch/ code.
     336                 :             :  *
     337                 :             :  * If the check fails, the thread will be terminated appropriately through
     338                 :             :  * the system fatal error handler.
     339                 :             :  */
     340                 :             : void z_check_stack_sentinel(void)
     341                 :             : {
     342                 :             :         uint32_t *stack;
     343                 :             : 
     344                 :             :         if ((_current->base.thread_state & _THREAD_DUMMY) != 0) {
     345                 :             :                 return;
     346                 :             :         }
     347                 :             : 
     348                 :             :         stack = (uint32_t *)_current->stack_info.start;
     349                 :             :         if (*stack != STACK_SENTINEL) {
     350                 :             :                 /* Restore it so further checks don't trigger this same error */
     351                 :             :                 *stack = STACK_SENTINEL;
     352                 :             :                 z_except_reason(K_ERR_STACK_CHK_FAIL);
     353                 :             :         }
     354                 :             : }
     355                 :             : #endif /* CONFIG_STACK_SENTINEL */
     356                 :             : 
     357                 :             : #if defined(CONFIG_STACK_POINTER_RANDOM) && (CONFIG_STACK_POINTER_RANDOM != 0)
     358                 :             : int z_stack_adjust_initialized;
     359                 :             : 
     360                 :             : static size_t random_offset(size_t stack_size)
     361                 :             : {
     362                 :             :         size_t random_val;
     363                 :             : 
     364                 :             :         if (!z_stack_adjust_initialized) {
     365                 :             :                 z_early_rand_get((uint8_t *)&random_val, sizeof(random_val));
     366                 :             :         } else {
     367                 :             :                 sys_rand_get((uint8_t *)&random_val, sizeof(random_val));
     368                 :             :         }
     369                 :             : 
     370                 :             :         /* Don't need to worry about alignment of the size here,
     371                 :             :          * arch_new_thread() is required to do it.
     372                 :             :          *
     373                 :             :          * FIXME: Not the best way to get a random number in a range.
     374                 :             :          * See #6493
     375                 :             :          */
     376                 :             :         const size_t fuzz = random_val % CONFIG_STACK_POINTER_RANDOM;
     377                 :             : 
     378                 :             :         if (unlikely(fuzz * 2 > stack_size)) {
     379                 :             :                 return 0;
     380                 :             :         }
     381                 :             : 
     382                 :             :         return fuzz;
     383                 :             : }
     384                 :             : #if defined(CONFIG_STACK_GROWS_UP)
     385                 :             :         /* This is so rare not bothering for now */
     386                 :             : #error "Stack pointer randomization not implemented for upward growing stacks"
     387                 :             : #endif /* CONFIG_STACK_GROWS_UP */
     388                 :             : #endif /* CONFIG_STACK_POINTER_RANDOM */
     389                 :             : 
     390                 :             : /*
     391                 :             :  * Geometry of a thread's stack object, computed once and threaded through the
     392                 :             :  * setup_thread_stack() helpers below.
     393                 :             :  */
     394                 :             : struct stack_geometry {
     395                 :             :         size_t obj_size;        /* size of the whole stack object */
     396                 :             :         char *buf_start;        /* start of the usable stack buffer */
     397                 :             :         size_t buf_size;        /* size of the usable stack buffer */
     398                 :             : };
     399                 :             : 
     400                 :             : /*
     401                 :             :  * Derive the stack object geometry from the caller-supplied stack and size.
     402                 :             :  * User-capable stacks and kernel-only stacks reserve different amounts.
     403                 :             :  */
     404                 :          56 : static struct stack_geometry compute_stack_geometry(k_thread_stack_t *stack,
     405                 :             :                                                     size_t stack_size)
     406                 :             : {
     407                 :          56 :         struct stack_geometry geo;
     408                 :             : 
     409                 :             : #ifdef CONFIG_USERSPACE
     410                 :             :         if (z_stack_is_user_capable(stack)) {
     411                 :             :                 geo.obj_size = K_THREAD_STACK_LEN(stack_size);
     412                 :             :                 geo.buf_start = K_THREAD_STACK_BUFFER(stack);
     413                 :             :                 geo.buf_size = geo.obj_size - K_THREAD_STACK_RESERVED;
     414                 :             :         } else
     415                 :             : #endif /* CONFIG_USERSPACE */
     416                 :             :         {
     417                 :             :                 /* Object cannot host a user mode thread */
     418                 :          56 :                 geo.obj_size = K_KERNEL_STACK_LEN(stack_size);
     419                 :          56 :                 geo.buf_start = K_KERNEL_STACK_BUFFER(stack);
     420                 :          56 :                 geo.buf_size = geo.obj_size - K_KERNEL_STACK_RESERVED;
     421                 :             : 
     422                 :             : #if defined(ARCH_KERNEL_STACK_RESERVED)
     423                 :             :                 /* Zephyr treats stack overflow as an app bug.  But
     424                 :             :                  * this particular overflow can be seen by static
     425                 :             :                  * analysis so needs to be handled somehow.
     426                 :             :                  */
     427                 :             :                 if (K_KERNEL_STACK_RESERVED > geo.obj_size) {
     428                 :             :                         k_panic();
     429                 :             :                 }
     430                 :             : #endif
     431                 :             :         }
     432                 :             : 
     433                 :          56 :         return geo;
     434                 :             : }
     435                 :             : 
     436                 :             : /*
     437                 :             :  * Return the initial (high end) stack pointer. When stacks are memory mapped
     438                 :             :  * this maps the object into virtual memory, records the mapping so it can be
     439                 :             :  * torn down at thread exit, and rebases buf_start onto the mapped address.
     440                 :             :  */
     441                 :          56 : static char *map_thread_stack(struct k_thread *new_thread,
     442                 :             :                               k_thread_stack_t *stack,
     443                 :             :                               struct stack_geometry *geo)
     444                 :             : {
     445                 :          56 :         char *stack_ptr;
     446                 :             : 
     447                 :             : #ifdef CONFIG_THREAD_STACK_MEM_MAPPED
     448                 :             :         /* Map the stack into virtual memory and use that as the base to
     449                 :             :          * calculate the initial stack pointer at the high end of the stack
     450                 :             :          * object. The stack pointer may be reduced later by TLS or random
     451                 :             :          * offset.
     452                 :             :          *
     453                 :             :          * K_MEM_MAP_UNINIT is used to mimic the behavior of non-mapped
     454                 :             :          * stack. If CONFIG_INIT_STACKS is enabled, the stack will be
     455                 :             :          * cleared later.
     456                 :             :          */
     457                 :             :         void *stack_mapped = k_mem_map_phys_guard((uintptr_t)stack, geo->obj_size,
     458                 :             :                                 K_MEM_PERM_RW | K_MEM_CACHE_WB | K_MEM_MAP_UNINIT,
     459                 :             :                                 false);
     460                 :             : 
     461                 :             :         __ASSERT_NO_MSG((uintptr_t)stack_mapped != 0);
     462                 :             : 
     463                 :             : #ifdef CONFIG_USERSPACE
     464                 :             :         if (z_stack_is_user_capable(stack)) {
     465                 :             :                 geo->buf_start = K_THREAD_STACK_BUFFER(stack_mapped);
     466                 :             :         } else
     467                 :             : #endif /* CONFIG_USERSPACE */
     468                 :             :         {
     469                 :             :                 geo->buf_start = K_KERNEL_STACK_BUFFER(stack_mapped);
     470                 :             :         }
     471                 :             : 
     472                 :             :         stack_ptr = (char *)stack_mapped + geo->obj_size;
     473                 :             : 
     474                 :             :         /* Need to store the info on mapped stack so we can remove the mappings
     475                 :             :          * when the thread ends.
     476                 :             :          */
     477                 :             :         new_thread->stack_info.mapped.addr = stack_mapped;
     478                 :             :         new_thread->stack_info.mapped.sz = geo->obj_size;
     479                 :             : #else /* CONFIG_THREAD_STACK_MEM_MAPPED */
     480                 :          56 :         ARG_UNUSED(new_thread);
     481                 :             : 
     482                 :             :         /* Initial stack pointer at the high end of the stack object, may
     483                 :             :          * be reduced later by TLS or random offset
     484                 :             :          */
     485                 :          56 :         stack_ptr = (char *)stack + geo->obj_size;
     486                 :             : #endif /* CONFIG_THREAD_STACK_MEM_MAPPED */
     487                 :             : 
     488                 :          56 :         return stack_ptr;
     489                 :             : }
     490                 :             : 
     491                 :             : /* Pre-fill the stack buffer with a known pattern for usage measurement. */
     492                 :          56 : static inline void fill_init_stack(char *buf_start, size_t buf_size)
     493                 :             : {
     494                 :             : #ifdef CONFIG_INIT_STACKS
     495                 :          56 :         memset(buf_start, 0xaa, buf_size);
     496                 :             : #else
     497                 :             :         ARG_UNUSED(buf_start);
     498                 :             :         ARG_UNUSED(buf_size);
     499                 :             : #endif /* CONFIG_INIT_STACKS */
     500                 :          56 : }
     501                 :             : 
     502                 :             : /* Place the overflow-detection sentinel at the low end of the stack buffer. */
     503                 :             : static inline void set_stack_sentinel(char *buf_start)
     504                 :             : {
     505                 :             : #ifdef CONFIG_STACK_SENTINEL
     506                 :             :         /* Put the stack sentinel at the lowest 4 bytes of the stack area.
     507                 :             :          * We periodically check that it's still present and kill the thread
     508                 :             :          * if it isn't.
     509                 :             :          */
     510                 :             :         *((uint32_t *)buf_start) = STACK_SENTINEL;
     511                 :             : #else
     512                 :             :         ARG_UNUSED(buf_start);
     513                 :             : #endif /* CONFIG_STACK_SENTINEL */
     514                 :             : }
     515                 :             : 
     516                 :             : /*
     517                 :             :  * Compute how much to reserve at the top of the stack buffer for TLS,
     518                 :             :  * userspace-local data and stack-pointer randomization, and return the
     519                 :             :  * aligned amount the initial stack pointer must be lowered by.
     520                 :             :  */
     521                 :          56 : static size_t reserve_stack_headroom(struct k_thread *new_thread,
     522                 :             :                                      char *stack_ptr, size_t buf_size)
     523                 :             : {
     524                 :          56 :         size_t delta = 0;
     525                 :             : 
     526                 :          56 :         ARG_UNUSED(new_thread);
     527                 :          56 :         ARG_UNUSED(stack_ptr);
     528                 :          56 :         ARG_UNUSED(buf_size);
     529                 :             : 
     530                 :             : #ifdef CONFIG_THREAD_LOCAL_STORAGE
     531                 :             :         /* TLS is always last within the stack buffer */
     532                 :             :         delta += arch_tls_stack_setup(new_thread, stack_ptr);
     533                 :             : #endif /* CONFIG_THREAD_LOCAL_STORAGE */
     534                 :             : #ifdef CONFIG_THREAD_USERSPACE_LOCAL_DATA
     535                 :             :         size_t tls_size = sizeof(struct _thread_userspace_local_data);
     536                 :             : 
     537                 :             :         /* reserve space on highest memory of stack buffer for local data */
     538                 :             :         delta += tls_size;
     539                 :             :         new_thread->userspace_local_data =
     540                 :             :                 (struct _thread_userspace_local_data *)(stack_ptr - delta);
     541                 :             : #endif /* CONFIG_THREAD_USERSPACE_LOCAL_DATA */
     542                 :             : #if defined(CONFIG_STACK_POINTER_RANDOM) && (CONFIG_STACK_POINTER_RANDOM != 0)
     543                 :             :         delta += random_offset(buf_size);
     544                 :             : #endif /* CONFIG_STACK_POINTER_RANDOM */
     545                 :             : 
     546                 :          56 :         return ROUND_UP(delta, ARCH_STACK_PTR_ALIGN);
     547                 :             : }
     548                 :             : 
     549                 :             : /* Record the thread-accessible stack bounds (and runtime-safety threshold). */
     550                 :             : static inline void set_stack_info(struct k_thread *new_thread, char *buf_start,
     551                 :             :                                   size_t buf_size, size_t delta)
     552                 :             : {
     553                 :             : #ifdef CONFIG_THREAD_STACK_INFO
     554                 :             :         /* Initial values. Arches which implement MPU guards that "borrow"
     555                 :             :          * memory from the stack buffer (not tracked in K_THREAD_STACK_RESERVED)
     556                 :             :          * will need to appropriately update this.
     557                 :             :          *
     558                 :             :          * The bounds tracked here correspond to the area of the stack object
     559                 :             :          * that the thread can access, which includes TLS.
     560                 :             :          */
     561                 :             :         new_thread->stack_info.start = (uintptr_t)buf_start;
     562                 :             :         new_thread->stack_info.size = buf_size;
     563                 :             :         new_thread->stack_info.delta = delta;
     564                 :             : 
     565                 :             : #ifdef CONFIG_THREAD_RUNTIME_STACK_SAFETY
     566                 :             :         new_thread->stack_info.usage.unused_threshold =
     567                 :             :                 (CONFIG_THREAD_RUNTIME_STACK_SAFETY_DEFAULT_UNUSED_THRESHOLD_PCT *
     568                 :             :                  buf_size) / 100;
     569                 :             : #endif
     570                 :             : #else
     571                 :             :         ARG_UNUSED(new_thread);
     572                 :             :         ARG_UNUSED(buf_start);
     573                 :             :         ARG_UNUSED(buf_size);
     574                 :             :         ARG_UNUSED(delta);
     575                 :             : #endif /* CONFIG_THREAD_STACK_INFO */
     576                 :             : }
     577                 :             : 
     578                 :          56 : static char *setup_thread_stack(struct k_thread *new_thread,
     579                 :             :                                 k_thread_stack_t *stack, size_t stack_size)
     580                 :             : {
     581                 :          56 :         struct stack_geometry geo = compute_stack_geometry(stack, stack_size);
     582                 :          56 :         char *stack_ptr = map_thread_stack(new_thread, stack, &geo);
     583                 :          56 :         size_t delta;
     584                 :             : 
     585                 :          56 :         LOG_DBG("stack %p for thread %p: obj_size=%zu buf_start=%p "
     586                 :             :                 " buf_size %zu stack_ptr=%p",
     587                 :             :                 stack, new_thread, geo.obj_size, (void *)geo.buf_start,
     588                 :             :                 geo.buf_size, (void *)stack_ptr);
     589                 :             : 
     590                 :          56 :         fill_init_stack(geo.buf_start, geo.buf_size);
     591                 :          56 :         set_stack_sentinel(geo.buf_start);
     592                 :          56 :         delta = reserve_stack_headroom(new_thread, stack_ptr, geo.buf_size);
     593                 :          56 :         set_stack_info(new_thread, geo.buf_start, geo.buf_size, delta);
     594                 :             : 
     595                 :          56 :         return stack_ptr - delta;
     596                 :             : }
     597                 :             : 
     598                 :             : #ifdef CONFIG_HW_SHADOW_STACK
     599                 :             : static void setup_shadow_stack(struct k_thread *new_thread,
     600                 :             :                          k_thread_stack_t *stack)
     601                 :             : {
     602                 :             :         int ret = -ENOENT;
     603                 :             : 
     604                 :             :         STRUCT_SECTION_FOREACH(_stack_to_hw_shadow_stack, stk_to_hw_shstk) {
     605                 :             :                 if (stk_to_hw_shstk->stack == stack) {
     606                 :             :                         ret = k_thread_hw_shadow_stack_attach(new_thread,
     607                 :             :                                                               stk_to_hw_shstk->shstk_addr,
     608                 :             :                                                               stk_to_hw_shstk->size);
     609                 :             :                         if (ret != 0) {
     610                 :             :                                 LOG_ERR("Could not set thread %p shadow stack %p, got error %d",
     611                 :             :                                         new_thread, stk_to_hw_shstk->shstk_addr, ret);
     612                 :             :                                 k_panic();
     613                 :             :                         }
     614                 :             :                         break;
     615                 :             :                 }
     616                 :             :         }
     617                 :             : 
     618                 :             :         /* Check if the stack isn't in a stack array, and use the corresponding
     619                 :             :          * shadow stack.
     620                 :             :          */
     621                 :             :         if (ret != -ENOENT) {
     622                 :             :                 return;
     623                 :             :         }
     624                 :             : 
     625                 :             :         STRUCT_SECTION_FOREACH(_stack_to_hw_shadow_stack_arr, stk_to_hw_shstk) {
     626                 :             :                 if ((uintptr_t)stack >= stk_to_hw_shstk->stack_addr &&
     627                 :             :                     (uintptr_t)stack < stk_to_hw_shstk->stack_addr +
     628                 :             :                     stk_to_hw_shstk->stack_size * stk_to_hw_shstk->nmemb) {
     629                 :             :                         /* Now we have to guess which index of the stack array is being used */
     630                 :             :                         uintptr_t stack_offset = (uintptr_t)stack - stk_to_hw_shstk->stack_addr;
     631                 :             :                         uintptr_t stack_index = stack_offset / stk_to_hw_shstk->stack_size;
     632                 :             :                         uintptr_t addr;
     633                 :             : 
     634                 :             :                         if (stack_index >= stk_to_hw_shstk->nmemb) {
     635                 :             :                                 LOG_ERR("Could not find shadow stack for thread %p, stack %p",
     636                 :             :                                         new_thread, stack);
     637                 :             :                                 k_panic();
     638                 :             :                         }
     639                 :             : 
     640                 :             :                         addr = stk_to_hw_shstk->shstk_addr +
     641                 :             :                                 stk_to_hw_shstk->shstk_size * stack_index;
     642                 :             :                         ret = k_thread_hw_shadow_stack_attach(new_thread,
     643                 :             :                                                               (arch_thread_hw_shadow_stack_t *)addr,
     644                 :             :                                                               stk_to_hw_shstk->shstk_size);
     645                 :             :                         if (ret != 0) {
     646                 :             :                                 LOG_ERR("Could not set thread %p shadow stack 0x%lx, got error %d",
     647                 :             :                                         new_thread, stk_to_hw_shstk->shstk_addr, ret);
     648                 :             :                                 k_panic();
     649                 :             :                         }
     650                 :             :                         break;
     651                 :             :                 }
     652                 :             :         }
     653                 :             : 
     654                 :             :         if (ret == -ENOENT) {
     655                 :             :                 LOG_ERR("Could not find shadow stack for thread %p, stack %p",
     656                 :             :                         new_thread, stack);
     657                 :             :                 k_panic();
     658                 :             :         }
     659                 :             : }
     660                 :             : #else
     661                 :             : /* No-op stub used when hardware shadow stacks are not configured. */
     662                 :             : static inline void setup_shadow_stack(struct k_thread *new_thread,
     663                 :             :                                       k_thread_stack_t *stack)
     664                 :             : {
     665                 :             :         ARG_UNUSED(new_thread);
     666                 :             :         ARG_UNUSED(stack);
     667                 :             : }
     668                 :             : #endif
     669                 :             : 
     670                 :             : /*
     671                 :             :  * The following init_thread_*()/assert_*() helpers each own one optional
     672                 :             :  * kernel feature. Building z_setup_new_thread() out of these calls keeps its
     673                 :             :  * body a readable, linear narrative instead of a wall of #ifdefs. Every helper
     674                 :             :  * is static inline and collapses to nothing when its feature is disabled, so
     675                 :             :  * this is purely a readability change with no runtime cost.
     676                 :             :  */
     677                 :             : 
     678                 :             : /* Reset per-thread cleanup bookkeeping before a k_thread object is reused. */
     679                 :             : static inline void thread_abort_cleanup_check_reuse(struct k_thread *thread)
     680                 :             : {
     681                 :             : #ifdef CONFIG_THREAD_ABORT_NEED_CLEANUP
     682                 :             :         k_thread_abort_cleanup_check_reuse(thread);
     683                 :             : #else
     684                 :             :         ARG_UNUSED(thread);
     685                 :             : #endif /* CONFIG_THREAD_ABORT_NEED_CLEANUP */
     686                 :             : }
     687                 :             : 
     688                 :             : /* Register the thread with the object-core framework and its usage stats. */
     689                 :             : static inline void init_thread_obj_core(struct k_thread *thread)
     690                 :             : {
     691                 :             : #ifdef CONFIG_OBJ_CORE_THREAD
     692                 :             :         k_obj_core_init_and_link(K_OBJ_CORE(thread), &obj_type_thread);
     693                 :             : #ifdef CONFIG_OBJ_CORE_STATS_THREAD
     694                 :             :         k_obj_core_stats_register(K_OBJ_CORE(thread), &thread->base.usage,
     695                 :             :                                   sizeof(thread->base.usage));
     696                 :             : #endif /* CONFIG_OBJ_CORE_STATS_THREAD */
     697                 :             : #else
     698                 :             :         ARG_UNUSED(thread);
     699                 :             : #endif /* CONFIG_OBJ_CORE_THREAD */
     700                 :             : }
     701                 :             : 
     702                 :             : /*
     703                 :             :  * Initialize userspace bookkeeping: register the thread and stack kernel
     704                 :             :  * objects, record stack ownership, and grant the thread access to itself.
     705                 :             :  */
     706                 :             : static inline void init_thread_userspace(struct k_thread *thread,
     707                 :             :                                          k_thread_stack_t *stack,
     708                 :             :                                          uint32_t options)
     709                 :             : {
     710                 :             : #ifdef CONFIG_USERSPACE
     711                 :             :         __ASSERT((options & K_USER) == 0U || z_stack_is_user_capable(stack),
     712                 :             :                  "user thread %p with kernel-only stack %p", thread, stack);
     713                 :             :         k_object_init(thread);
     714                 :             :         k_object_init(stack);
     715                 :             :         thread->stack_obj = stack;
     716                 :             :         thread->syscall_frame = NULL;
     717                 :             : 
     718                 :             :         /* Any given thread has access to itself */
     719                 :             :         k_object_access_grant(thread, thread);
     720                 :             : #else
     721                 :             :         ARG_UNUSED(thread);
     722                 :             :         ARG_UNUSED(stack);
     723                 :             :         ARG_UNUSED(options);
     724                 :             : #endif /* CONFIG_USERSPACE */
     725                 :             : }
     726                 :             : 
     727                 :             : /* Assert the thread object is cache-coherent while its stack stays cached. */
     728                 :             : static inline void assert_thread_coherence(struct k_thread *thread,
     729                 :             :                                            k_thread_stack_t *stack)
     730                 :             : {
     731                 :             : #ifdef CONFIG_KERNEL_COHERENCE
     732                 :             :         /* Check that the thread object is safe, but that the stack is
     733                 :             :          * still cached!
     734                 :             :          */
     735                 :             :         __ASSERT_NO_MSG(sys_cache_is_mem_coherent(thread));
     736                 :             : 
     737                 :             :         /* When dynamic thread stack is available, the stack may come from
     738                 :             :          * uncached area.
     739                 :             :          */
     740                 :             : #ifndef CONFIG_DYNAMIC_THREAD
     741                 :             :         __ASSERT_NO_MSG(!sys_cache_is_mem_coherent(stack));
     742                 :             : #endif /* CONFIG_DYNAMIC_THREAD */
     743                 :             : #endif /* CONFIG_KERNEL_COHERENCE */
     744                 :             :         ARG_UNUSED(thread);
     745                 :             :         ARG_UNUSED(stack);
     746                 :             : }
     747                 :             : 
     748                 :             : /* Assert the arch layer populated switch_handle on USE_SWITCH builds. */
     749                 :             : static inline void assert_switch_handle(struct k_thread *thread)
     750                 :             : {
     751                 :             : #ifdef CONFIG_USE_SWITCH
     752                 :             :         /* switch_handle must be non-null except when inside z_swap()
     753                 :             :          * for synchronization reasons.  Historically some notional
     754                 :             :          * USE_SWITCH architectures have actually ignored the field
     755                 :             :          */
     756                 :             :         __ASSERT(thread->switch_handle != NULL,
     757                 :             :                  "arch layer failed to initialize switch_handle");
     758                 :             : #endif /* CONFIG_USE_SWITCH */
     759                 :             :         ARG_UNUSED(thread);
     760                 :             : }
     761                 :             : 
     762                 :             : /* Clear the opaque, kernel-managed per-thread custom data pointer. */
     763                 :             : static inline void init_thread_custom_data(struct k_thread *thread)
     764                 :             : {
     765                 :             : #ifdef CONFIG_THREAD_CUSTOM_DATA
     766                 :             :         /* Initialize custom data field (value is opaque to kernel) */
     767                 :             :         thread->custom_data = NULL;
     768                 :             : #else
     769                 :             :         ARG_UNUSED(thread);
     770                 :             : #endif /* CONFIG_THREAD_CUSTOM_DATA */
     771                 :             : }
     772                 :             : 
     773                 :             : /*
     774                 :             :  * Record the entry point and parameters, then link the thread into the
     775                 :             :  * global thread-monitor list under the monitor spinlock.
     776                 :             :  */
     777                 :             : static inline void add_thread_to_monitor(struct k_thread *thread,
     778                 :             :                                          k_thread_entry_t entry,
     779                 :             :                                          void *p1, void *p2, void *p3)
     780                 :             : {
     781                 :             : #ifdef CONFIG_THREAD_MONITOR
     782                 :             :         thread->entry.pEntry = entry;
     783                 :             :         thread->entry.parameter1 = p1;
     784                 :             :         thread->entry.parameter2 = p2;
     785                 :             :         thread->entry.parameter3 = p3;
     786                 :             : 
     787                 :             :         k_spinlock_key_t key = k_spin_lock(&z_thread_monitor_lock);
     788                 :             : 
     789                 :             :         thread->next_thread = _kernel.threads;
     790                 :             :         _kernel.threads = thread;
     791                 :             :         k_spin_unlock(&z_thread_monitor_lock, key);
     792                 :             : #else
     793                 :             :         ARG_UNUSED(thread);
     794                 :             :         ARG_UNUSED(entry);
     795                 :             :         ARG_UNUSED(p1);
     796                 :             :         ARG_UNUSED(p2);
     797                 :             :         ARG_UNUSED(p3);
     798                 :             : #endif /* CONFIG_THREAD_MONITOR */
     799                 :             : }
     800                 :             : 
     801                 :             : /* Set the thread's name from the caller-supplied string (may be NULL). */
     802                 :          56 : static inline void init_thread_name(struct k_thread *thread, const char *name)
     803                 :             : {
     804                 :             : #ifdef CONFIG_THREAD_NAME
     805                 :          56 :         set_thread_name(thread, name);
     806                 :             : #else
     807                 :             :         ARG_UNUSED(thread);
     808                 :             :         ARG_UNUSED(name);
     809                 :             : #endif /* CONFIG_THREAD_NAME */
     810                 :          56 : }
     811                 :             : 
     812                 :             : /* Set the thread's initial SMP CPU affinity mask. */
     813                 :             : static inline void init_thread_cpu_mask(struct k_thread *thread)
     814                 :             : {
     815                 :             : #ifdef CONFIG_SCHED_CPU_MASK
     816                 :             :         if (IS_ENABLED(CONFIG_SCHED_CPU_MASK_PIN_ONLY)) {
     817                 :             :                 thread->base.cpu_mask = 1; /* must specify only one cpu */
     818                 :             :         } else {
     819                 :             :                 thread->base.cpu_mask = -1; /* allow all cpus */
     820                 :             :         }
     821                 :             : #else
     822                 :             :         ARG_UNUSED(thread);
     823                 :             : #endif /* CONFIG_SCHED_CPU_MASK */
     824                 :             : }
     825                 :             : 
     826                 :             : /* Attach the thread to its memory domain and inherit caller permissions
     827                 :             :  * when K_INHERIT_PERMS is requested.
     828                 :             :  */
     829                 :             : static inline void init_thread_userspace_perms(struct k_thread *thread,
     830                 :             :                                                uint32_t options)
     831                 :             : {
     832                 :             : #ifdef CONFIG_USERSPACE
     833                 :             :         z_mem_domain_init_thread(thread);
     834                 :             : 
     835                 :             :         if ((options & K_INHERIT_PERMS) != 0U) {
     836                 :             :                 k_thread_perms_inherit(_current, thread);
     837                 :             :         }
     838                 :             : #else
     839                 :             :         ARG_UNUSED(thread);
     840                 :             :         ARG_UNUSED(options);
     841                 :             : #endif /* CONFIG_USERSPACE */
     842                 :             : }
     843                 :             : 
     844                 :             : /* Clear the EDF scheduling deadline. */
     845                 :             : static inline void init_thread_deadline(struct k_thread *thread)
     846                 :             : {
     847                 :             : #ifdef CONFIG_SCHED_DEADLINE
     848                 :             :         thread->base.prio_deadline = 0;
     849                 :             : #else
     850                 :             :         ARG_UNUSED(thread);
     851                 :             : #endif /* CONFIG_SCHED_DEADLINE */
     852                 :             : }
     853                 :             : 
     854                 :             : /* Initialize runtime CPU-usage tracking for the thread. */
     855                 :             : static inline void init_thread_usage(struct k_thread *thread)
     856                 :             : {
     857                 :             : #ifdef CONFIG_SCHED_THREAD_USAGE
     858                 :             :         thread->base.usage = (struct k_cycle_stats) {};
     859                 :             :         thread->base.usage.track_usage = CONFIG_SCHED_THREAD_USAGE_AUTO_ENABLE;
     860                 :             : #else
     861                 :             :         ARG_UNUSED(thread);
     862                 :             : #endif /* CONFIG_SCHED_THREAD_USAGE */
     863                 :             : }
     864                 :             : 
     865                 :             : /* Assert the thread wasn't already linked into the monitor list. */
     866                 :             : static inline void assert_thread_not_reused(struct k_thread *new_thread)
     867                 :             : {
     868                 :             : #ifdef CONFIG_THREAD_MONITOR
     869                 :             : #ifdef CONFIG_ASSERT
     870                 :             :         k_spinlock_key_t key = k_spin_lock(&z_thread_monitor_lock);
     871                 :             :         bool reused = false;
     872                 :             : 
     873                 :             :         /* Check if the thread is already in the list */
     874                 :             :         for (struct k_thread *t = _kernel.threads; t; t = t->next_thread) {
     875                 :             :                 if (t == new_thread) {
     876                 :             :                         reused = true;
     877                 :             :                         break;
     878                 :             :                 }
     879                 :             :         }
     880                 :             : 
     881                 :             :         k_spin_unlock(&z_thread_monitor_lock, key);
     882                 :             : 
     883                 :             :         __ASSERT(!reused, "thread %p is already in the running list", new_thread);
     884                 :             : #endif /* CONFIG_ASSERT */
     885                 :             : #endif /* CONFIG_THREAD_MONITOR */
     886                 :             :         ARG_UNUSED(new_thread);
     887                 :             : }
     888                 :             : 
     889                 :             : /*
     890                 :             :  * The provided stack_size value is presumed to be either the result of
     891                 :             :  * K_THREAD_STACK_SIZEOF(stack), or the size value passed to the instance
     892                 :             :  * of K_THREAD_STACK_DEFINE() which defined 'stack'.
     893                 :             :  */
     894                 :          56 : char *z_setup_new_thread(struct k_thread *new_thread,
     895                 :             :                          k_thread_stack_t *stack, size_t stack_size,
     896                 :             :                          k_thread_entry_t entry,
     897                 :             :                          void *p1, void *p2, void *p3,
     898                 :             :                          int prio, uint32_t options, const char *name)
     899                 :             : {
     900                 :          56 :         char *stack_ptr;
     901                 :             : 
     902   [ +  +  -  +  :          56 :         Z_ASSERT_VALID_PRIO(prio, entry);
                   +  - ]
     903                 :             : 
     904                 :          56 :         assert_thread_not_reused(new_thread);
     905                 :             : 
     906                 :          56 :         thread_abort_cleanup_check_reuse(new_thread);
     907                 :          56 :         init_thread_obj_core(new_thread);
     908                 :          56 :         init_thread_userspace(new_thread, stack, options);
     909                 :             : 
     910                 :          56 :         z_waitq_init(&new_thread->join_queue);
     911                 :             : 
     912                 :             :         /* Initialize various struct k_thread members */
     913                 :          56 :         z_init_thread_base(&new_thread->base, prio, _THREAD_SLEEPING, options);
     914                 :          56 :         stack_ptr = setup_thread_stack(new_thread, stack, stack_size);
     915                 :             : 
     916                 :             : #if Z_MUTEX_PI_ENABLED
     917                 :          56 :         sys_slist_init(&new_thread->held_mutexes);
     918                 :          56 :         new_thread->mutex_pended_on = NULL;
     919                 :          56 :         new_thread->orig_prio = new_thread->base.prio;
     920                 :             : #endif /* Z_MUTEX_PI_ENABLED */
     921                 :             : 
     922                 :          56 :         setup_shadow_stack(new_thread, stack);
     923                 :          56 :         assert_thread_coherence(new_thread, stack);
     924                 :             : 
     925                 :          56 :         arch_new_thread(new_thread, stack, stack_ptr, entry, p1, p2, p3);
     926                 :             : 
     927                 :             :         /* static threads overwrite it afterwards with real value */
     928                 :          56 :         new_thread->init_data = NULL;
     929                 :             : 
     930                 :          56 :         assert_switch_handle(new_thread);
     931                 :          56 :         init_thread_custom_data(new_thread);
     932                 :          56 :         add_thread_to_monitor(new_thread, entry, p1, p2, p3);
     933                 :          56 :         init_thread_name(new_thread, name);
     934                 :          56 :         init_thread_cpu_mask(new_thread);
     935                 :             : 
     936                 :             :         /* _current may be NULL if the dummy thread is not used */
     937                 :          56 :         if (IS_ENABLED(CONFIG_ARCH_HAS_CUSTOM_SWAP_TO_MAIN) &&
     938         [ -  + ]:          56 :             (_current == NULL)) {
     939                 :           0 :                 new_thread->resource_pool = NULL;
     940                 :           0 :                 return stack_ptr;
     941                 :             :         }
     942                 :             : 
     943                 :          56 :         init_thread_userspace_perms(new_thread, options);
     944                 :          56 :         init_thread_deadline(new_thread);
     945                 :          56 :         new_thread->resource_pool = _current->resource_pool;
     946                 :          56 :         z_smp_halt_queue_init(new_thread);
     947                 :          56 :         init_thread_usage(new_thread);
     948                 :             : 
     949                 :          56 :         SYS_PORT_TRACING_OBJ_FUNC(k_thread, create, new_thread);
     950                 :             : 
     951                 :          56 :         return stack_ptr;
     952                 :             : }
     953                 :             : 
     954                 :             : #ifdef CONFIG_THREAD_RUNTIME_STACK_SAFETY
     955                 :             : int z_impl_k_thread_runtime_stack_unused_threshold_pct_set(struct k_thread *thread,
     956                 :             :                                                            uint32_t pct)
     957                 :             : {
     958                 :             :         size_t unused_threshold;
     959                 :             : 
     960                 :             :         if (pct > 99) {
     961                 :             :                 return -EINVAL;   /* 100% unused stack and up is invalid */
     962                 :             :         }
     963                 :             : 
     964                 :             :         unused_threshold = (thread->stack_info.size * pct) / 100;
     965                 :             : 
     966                 :             :         thread->stack_info.usage.unused_threshold = unused_threshold;
     967                 :             : 
     968                 :             :         return 0;
     969                 :             : }
     970                 :             : 
     971                 :             : int z_impl_k_thread_runtime_stack_unused_threshold_set(struct k_thread *thread,
     972                 :             :                                                        size_t threshold)
     973                 :             : {
     974                 :             :         if (threshold > thread->stack_info.size) {
     975                 :             :                 return -EINVAL;
     976                 :             :         }
     977                 :             : 
     978                 :             :         thread->stack_info.usage.unused_threshold = threshold;
     979                 :             : 
     980                 :             :         return 0;
     981                 :             : }
     982                 :             : 
     983                 :             : size_t z_impl_k_thread_runtime_stack_unused_threshold_get(struct k_thread *thread)
     984                 :             : {
     985                 :             :         return thread->stack_info.usage.unused_threshold;
     986                 :             : }
     987                 :             : 
     988                 :             : #ifdef CONFIG_USERSPACE
     989                 :             : int z_vrfy_k_thread_runtime_stack_unused_threshold_pct_set(struct k_thread *thread,
     990                 :             :                                                            uint32_t pct)
     991                 :             : {
     992                 :             :         K_OOPS(K_SYSCALL_OBJ(thread, K_OBJ_THREAD));
     993                 :             : 
     994                 :             :         return z_impl_k_thread_runtime_stack_unused_threshold_pct_set(thread, pct);
     995                 :             : }
     996                 :             : #include <zephyr/syscalls/k_thread_runtime_stack_unused_threshold_pct_set_mrsh.c>
     997                 :             : 
     998                 :             : int z_vrfy_k_thread_runtime_stack_unused_threshold_set(struct k_thread *thread,
     999                 :             :                                                        size_t threshold)
    1000                 :             : {
    1001                 :             :         K_OOPS(K_SYSCALL_OBJ(thread, K_OBJ_THREAD));
    1002                 :             : 
    1003                 :             :         return z_impl_k_thread_runtime_stack_unused_threshold_set(thread, threshold);
    1004                 :             : }
    1005                 :             : #include <zephyr/syscalls/k_thread_runtime_stack_unused_threshold_set_mrsh.c>
    1006                 :             : 
    1007                 :             : size_t z_vrfy_k_thread_runtime_stack_unused_threshold_get(struct k_thread *thread)
    1008                 :             : {
    1009                 :             :         K_OOPS(K_SYSCALL_OBJ(thread, K_OBJ_THREAD));
    1010                 :             : 
    1011                 :             :         return z_impl_k_thread_runtime_stack_unused_threshold_get(thread);
    1012                 :             : }
    1013                 :             : #include <zephyr/syscalls/k_thread_runtime_stack_unused_threshold_get_mrsh.c>
    1014                 :             : #endif /* CONFIG_USERSPACE */
    1015                 :             : #endif /* CONFIG_THREAD_RUNTIME_STACK_SAFETY */
    1016                 :             : 
    1017                 :          54 : k_tid_t z_impl_k_thread_create(struct k_thread *new_thread,
    1018                 :             :                               k_thread_stack_t *stack,
    1019                 :             :                               size_t stack_size, k_thread_entry_t entry,
    1020                 :             :                               void *p1, void *p2, void *p3,
    1021                 :             :                               int prio, uint32_t options, k_timeout_t delay)
    1022                 :             : {
    1023         [ -  + ]:          54 :         __ASSERT(!arch_is_in_isr(), "Threads may not be created in ISRs");
    1024                 :             : 
    1025                 :          54 :         z_setup_new_thread(new_thread, stack, stack_size, entry, p1, p2, p3,
    1026                 :             :                           prio, options, NULL);
    1027                 :             : 
    1028                 :          54 :         thread_schedule_new(new_thread, delay);
    1029                 :             : 
    1030                 :          54 :         return new_thread;
    1031                 :             : }
    1032                 :             : 
    1033                 :             : #ifdef CONFIG_USERSPACE
    1034                 :             : bool z_stack_is_user_capable(k_thread_stack_t *stack)
    1035                 :             : {
    1036                 :             :         return k_object_find(stack) != NULL;
    1037                 :             : }
    1038                 :             : 
    1039                 :             : k_tid_t z_vrfy_k_thread_create(struct k_thread *new_thread,
    1040                 :             :                                k_thread_stack_t *stack,
    1041                 :             :                                size_t stack_size, k_thread_entry_t entry,
    1042                 :             :                                void *p1, void *p2, void *p3,
    1043                 :             :                                int prio, uint32_t options, k_timeout_t delay)
    1044                 :             : {
    1045                 :             :         size_t total_size, stack_obj_size;
    1046                 :             :         struct k_object *stack_object;
    1047                 :             : 
    1048                 :             :         /* The thread and stack objects *must* be in an uninitialized state */
    1049                 :             :         K_OOPS(K_SYSCALL_OBJ_NEVER_INIT(new_thread, K_OBJ_THREAD));
    1050                 :             : 
    1051                 :             :         /* No need to check z_stack_is_user_capable(), it won't be in the
    1052                 :             :          * object table if it isn't
    1053                 :             :          */
    1054                 :             :         stack_object = k_object_find(stack);
    1055                 :             :         K_OOPS(K_SYSCALL_VERIFY_MSG(k_object_validation_check(stack_object, stack,
    1056                 :             :                                                 K_OBJ_THREAD_STACK_ELEMENT,
    1057                 :             :                                                 _OBJ_INIT_FALSE) == 0,
    1058                 :             :                                     "bad stack object"));
    1059                 :             : 
    1060                 :             :         /* Verify that the stack size passed in is OK by computing the total
    1061                 :             :          * size and comparing it with the size value in the object metadata
    1062                 :             :          */
    1063                 :             :         K_OOPS(K_SYSCALL_VERIFY_MSG(!size_add_overflow(K_THREAD_STACK_RESERVED,
    1064                 :             :                                                        stack_size, &total_size),
    1065                 :             :                                     "stack size overflow (%zu+%zu)",
    1066                 :             :                                     stack_size,
    1067                 :             :                                     K_THREAD_STACK_RESERVED));
    1068                 :             : 
    1069                 :             :         /* Testing less-than-or-equal since additional room may have been
    1070                 :             :          * allocated for alignment constraints
    1071                 :             :          */
    1072                 :             : #ifdef CONFIG_GEN_PRIV_STACKS
    1073                 :             :         stack_obj_size = stack_object->data.stack_data->size;
    1074                 :             : #else
    1075                 :             :         stack_obj_size = stack_object->data.stack_size;
    1076                 :             : #endif /* CONFIG_GEN_PRIV_STACKS */
    1077                 :             :         K_OOPS(K_SYSCALL_VERIFY_MSG(total_size <= stack_obj_size,
    1078                 :             :                                     "stack size %zu is too big, max is %zu",
    1079                 :             :                                     total_size, stack_obj_size));
    1080                 :             : 
    1081                 :             :         /* User threads may only create other user threads and they can't
    1082                 :             :          * be marked as essential
    1083                 :             :          */
    1084                 :             :         K_OOPS(K_SYSCALL_VERIFY(options & K_USER));
    1085                 :             :         K_OOPS(K_SYSCALL_VERIFY(!(options & K_ESSENTIAL)));
    1086                 :             : 
    1087                 :             :         /* Check validity of prio argument; must be the same or worse priority
    1088                 :             :          * than the caller
    1089                 :             :          */
    1090                 :             :         K_OOPS(K_SYSCALL_VERIFY(_is_valid_prio(prio, NULL)));
    1091                 :             :         K_OOPS(K_SYSCALL_VERIFY(z_is_prio_lower_or_equal(prio,
    1092                 :             :                                                         _current->base.prio)));
    1093                 :             : 
    1094                 :             :         z_setup_new_thread(new_thread, stack, stack_size,
    1095                 :             :                            entry, p1, p2, p3, prio, options, NULL);
    1096                 :             : 
    1097                 :             :         thread_schedule_new(new_thread, delay);
    1098                 :             : 
    1099                 :             :         return new_thread;
    1100                 :             : }
    1101                 :             : #include <zephyr/syscalls/k_thread_create_mrsh.c>
    1102                 :             : #endif /* CONFIG_USERSPACE */
    1103                 :             : 
    1104                 :          56 : void z_init_thread_base(struct _thread_base *thread_base, int priority,
    1105                 :             :                        uint32_t initial_state, unsigned int options)
    1106                 :             : {
    1107                 :             :         /* k_q_node is initialized upon first insertion in a list */
    1108                 :          56 :         thread_base->pended_on = NULL;
    1109                 :          56 :         thread_base->user_options = (uint16_t)options;
    1110                 :          56 :         thread_base->thread_state = (uint8_t)initial_state;
    1111                 :             : 
    1112                 :          56 :         thread_base->prio = priority;
    1113                 :             : 
    1114                 :          56 :         thread_base->sched_locked = 0U;
    1115                 :             : 
    1116                 :          56 :         z_smp_thread_base_init(thread_base);
    1117                 :             : 
    1118                 :             : #ifdef CONFIG_TIMESLICE_PER_THREAD
    1119                 :             :         thread_base->slice_ticks = 0;
    1120                 :             :         thread_base->slice_expired = NULL;
    1121                 :             : #endif /* CONFIG_TIMESLICE_PER_THREAD */
    1122                 :             : 
    1123                 :             : #ifdef CONFIG_SPIN_VALIDATE
    1124                 :             :         thread_base->swap_data = NULL;
    1125                 :             :         /* otherwise swap_data does not need to be initialized */
    1126                 :             : #endif
    1127                 :             : 
    1128                 :          56 :         z_init_thread_timeout(thread_base);
    1129                 :          56 : }
    1130                 :             : 
    1131                 :           0 : FUNC_NORETURN void k_thread_user_mode_enter(k_thread_entry_t entry,
    1132                 :             :                                             void *p1, void *p2, void *p3)
    1133                 :             : {
    1134                 :           0 :         SYS_PORT_TRACING_FUNC(k_thread, user_mode_enter);
    1135                 :             : 
    1136                 :           0 :         _current->base.user_options |= K_USER;
    1137                 :           0 :         z_thread_essential_clear(_current);
    1138                 :             : #ifdef CONFIG_THREAD_MONITOR
    1139                 :             :         _current->entry.pEntry = entry;
    1140                 :             :         _current->entry.parameter1 = p1;
    1141                 :             :         _current->entry.parameter2 = p2;
    1142                 :             :         _current->entry.parameter3 = p3;
    1143                 :             : #endif /* CONFIG_THREAD_MONITOR */
    1144                 :             : #ifdef CONFIG_USERSPACE
    1145                 :             :         __ASSERT(z_stack_is_user_capable(_current->stack_obj),
    1146                 :             :                  "dropping to user mode with kernel-only stack object");
    1147                 :             : #ifdef CONFIG_THREAD_USERSPACE_LOCAL_DATA
    1148                 :             :         memset(_current->userspace_local_data, 0,
    1149                 :             :                sizeof(struct _thread_userspace_local_data));
    1150                 :             : #endif /* CONFIG_THREAD_USERSPACE_LOCAL_DATA */
    1151                 :             : #ifdef CONFIG_THREAD_LOCAL_STORAGE
    1152                 :             :         arch_tls_stack_setup(_current,
    1153                 :             :                              (char *)(_current->stack_info.start +
    1154                 :             :                                       _current->stack_info.size));
    1155                 :             : #endif /* CONFIG_THREAD_LOCAL_STORAGE */
    1156                 :             :         arch_user_mode_enter(entry, p1, p2, p3);
    1157                 :             : #else
    1158                 :             :         /* XXX In this case we do not reset the stack */
    1159                 :           0 :         z_thread_entry(entry, p1, p2, p3);
    1160                 :             : #endif /* CONFIG_USERSPACE */
    1161                 :             : }
    1162                 :             : 
    1163                 :             : #if defined(CONFIG_INIT_STACKS) && defined(CONFIG_THREAD_STACK_INFO)
    1164                 :             : #ifdef CONFIG_STACK_GROWS_UP
    1165                 :             : #error "Unsupported configuration for stack analysis"
    1166                 :             : #endif /* CONFIG_STACK_GROWS_UP */
    1167                 :             : 
    1168                 :             : int z_stack_space_get(const uint8_t *stack_start, size_t size, size_t *unused_ptr)
    1169                 :             : {
    1170                 :             :         size_t unused = 0;
    1171                 :             :         const uint8_t *checked_stack = stack_start;
    1172                 :             :         /* Take the address of any local variable as a shallow bound for the
    1173                 :             :          * stack pointer.  Addresses above it are guaranteed to be
    1174                 :             :          * accessible.
    1175                 :             :          */
    1176                 :             :         const uint8_t *stack_pointer = (const uint8_t *)&stack_start;
    1177                 :             : 
    1178                 :             :         /* If we are currently running on the stack being analyzed, some
    1179                 :             :          * memory management hardware will generate an exception if we
    1180                 :             :          * read unused stack memory.
    1181                 :             :          *
    1182                 :             :          * This never happens when invoked from user mode, as user mode
    1183                 :             :          * will always run this function on the privilege elevation stack.
    1184                 :             :          */
    1185                 :             :         if ((stack_pointer > stack_start) && (stack_pointer <= (stack_start + size)) &&
    1186                 :             :             IS_ENABLED(CONFIG_NO_UNUSED_STACK_INSPECTION)) {
    1187                 :             :                 /* TODO: We could add an arch_ API call to temporarily
    1188                 :             :                  * disable the stack checking in the CPU, but this would
    1189                 :             :                  * need to be properly managed wrt context switches/interrupts
    1190                 :             :                  */
    1191                 :             :                 return -ENOTSUP;
    1192                 :             :         }
    1193                 :             : 
    1194                 :             :         if (IS_ENABLED(CONFIG_STACK_SENTINEL)) {
    1195                 :             :                 /* First 4 bytes of the stack buffer reserved for the
    1196                 :             :                  * sentinel value, it won't be 0xAAAAAAAA for thread
    1197                 :             :                  * stacks.
    1198                 :             :                  *
    1199                 :             :                  * FIXME: thread->stack_info.start ought to reflect
    1200                 :             :                  * this!
    1201                 :             :                  */
    1202                 :             :                 checked_stack += 4;
    1203                 :             :                 size -= 4;
    1204                 :             :         }
    1205                 :             : 
    1206                 :             :         for (size_t i = 0; i < size; i++) {
    1207                 :             :                 if ((checked_stack[i]) == 0xaaU) {
    1208                 :             :                         unused++;
    1209                 :             :                 } else {
    1210                 :             :                         break;
    1211                 :             :                 }
    1212                 :             :         }
    1213                 :             : 
    1214                 :             :         *unused_ptr = unused;
    1215                 :             : 
    1216                 :             :         return 0;
    1217                 :             : }
    1218                 :             : 
    1219                 :             : #ifdef CONFIG_THREAD_RUNTIME_STACK_SAFETY
    1220                 :             : int k_thread_runtime_stack_safety_full_check(const struct k_thread *thread,
    1221                 :             :                                              size_t *unused_ptr,
    1222                 :             :                                              k_thread_stack_safety_handler_t handler,
    1223                 :             :                                              void *arg)
    1224                 :             : {
    1225                 :             :         int    rv;
    1226                 :             :         size_t unused_space;
    1227                 :             : 
    1228                 :             :         __ASSERT_NO_MSG(thread != NULL);
    1229                 :             : 
    1230                 :             :         rv = z_stack_space_get((const uint8_t *)thread->stack_info.start,
    1231                 :             :                                thread->stack_info.size, &unused_space);
    1232                 :             : 
    1233                 :             :         if (rv != 0) {
    1234                 :             :                 return rv;
    1235                 :             :         }
    1236                 :             : 
    1237                 :             :         if (unused_ptr != NULL) {
    1238                 :             :                 *unused_ptr = unused_space;
    1239                 :             :         }
    1240                 :             : 
    1241                 :             :         if ((unused_space < thread->stack_info.usage.unused_threshold) &&
    1242                 :             :             (handler != NULL)) {
    1243                 :             :                 handler(thread, unused_space, arg);
    1244                 :             :         }
    1245                 :             : 
    1246                 :             :         return 0;
    1247                 :             : }
    1248                 :             : 
    1249                 :             : int k_thread_runtime_stack_safety_threshold_check(const struct k_thread *thread,
    1250                 :             :                                                   size_t *unused_ptr,
    1251                 :             :                                                   k_thread_stack_safety_handler_t handler,
    1252                 :             :                                                   void *arg)
    1253                 :             : {
    1254                 :             :         int    rv;
    1255                 :             :         size_t unused_space;
    1256                 :             :         size_t threshold;
    1257                 :             :         size_t scan_size;
    1258                 :             : 
    1259                 :             :         __ASSERT_NO_MSG(thread != NULL);
    1260                 :             : 
    1261                 :             :         threshold = thread->stack_info.usage.unused_threshold;
    1262                 :             :         scan_size = threshold;
    1263                 :             : 
    1264                 :             :         /* z_stack_space_get() reserves the first bytes of the stack buffer for
    1265                 :             :          * the stack sentinel and shrinks its scan window by that amount. Grow
    1266                 :             :          * the requested window by the same reservation so that up to
    1267                 :             :          * 'threshold' bytes of the usable stack are actually examined;
    1268                 :             :          * otherwise a fully unused window would report fewer than 'threshold'
    1269                 :             :          * unused bytes and spuriously trip the threshold.
    1270                 :             :          */
    1271                 :             :         if (IS_ENABLED(CONFIG_STACK_SENTINEL) && (threshold != 0U)) {
    1272                 :             :                 scan_size += sizeof(uint32_t);
    1273                 :             :         }
    1274                 :             : 
    1275                 :             :         rv = z_stack_space_get((const uint8_t *)thread->stack_info.start,
    1276                 :             :                                scan_size, &unused_space);
    1277                 :             : 
    1278                 :             :         if (rv != 0) {
    1279                 :             :                 return rv;
    1280                 :             :         }
    1281                 :             : 
    1282                 :             :         if (unused_ptr != NULL) {
    1283                 :             :                 *unused_ptr = unused_space;
    1284                 :             :         }
    1285                 :             : 
    1286                 :             :         if ((unused_space < threshold) && (handler != NULL)) {
    1287                 :             :                 handler(thread, unused_space, arg);
    1288                 :             :         }
    1289                 :             : 
    1290                 :             :         return 0;
    1291                 :             : }
    1292                 :             : #endif /* CONFIG_THREAD_RUNTIME_STACK_SAFETY */
    1293                 :             : 
    1294                 :             : int z_impl_k_thread_stack_space_get(const struct k_thread *thread,
    1295                 :             :                                     size_t *unused_ptr)
    1296                 :             : {
    1297                 :             : #ifdef CONFIG_THREAD_STACK_MEM_MAPPED
    1298                 :             :         if (thread->stack_info.mapped.addr == NULL) {
    1299                 :             :                 return -EINVAL;
    1300                 :             :         }
    1301                 :             : #endif /* CONFIG_THREAD_STACK_MEM_MAPPED */
    1302                 :             : 
    1303                 :             :         return z_stack_space_get((const uint8_t *)thread->stack_info.start,
    1304                 :             :                                  thread->stack_info.size, unused_ptr);
    1305                 :             : }
    1306                 :             : 
    1307                 :             : #ifdef CONFIG_USERSPACE
    1308                 :             : int z_vrfy_k_thread_stack_space_get(const struct k_thread *thread,
    1309                 :             :                                     size_t *unused_ptr)
    1310                 :             : {
    1311                 :             :         size_t unused;
    1312                 :             :         int ret;
    1313                 :             : 
    1314                 :             :         K_OOPS(K_SYSCALL_OBJ(thread, K_OBJ_THREAD));
    1315                 :             : 
    1316                 :             :         ret = z_impl_k_thread_stack_space_get(thread, &unused);
    1317                 :             :         CHECKIF(ret != 0) {
    1318                 :             :                 return ret;
    1319                 :             :         }
    1320                 :             : 
    1321                 :             :         ret = k_usermode_to_copy(unused_ptr, &unused, sizeof(size_t));
    1322                 :             :         CHECKIF(ret != 0) {
    1323                 :             :                 return ret;
    1324                 :             :         }
    1325                 :             : 
    1326                 :             :         return 0;
    1327                 :             : }
    1328                 :             : #include <zephyr/syscalls/k_thread_stack_space_get_mrsh.c>
    1329                 :             : #endif /* CONFIG_USERSPACE */
    1330                 :             : #endif /* CONFIG_INIT_STACKS && CONFIG_THREAD_STACK_INFO */
    1331                 :             : 
    1332                 :             : #ifdef CONFIG_USERSPACE
    1333                 :             : static inline k_ticks_t z_vrfy_k_thread_timeout_remaining_ticks(
    1334                 :             :                                                     const struct k_thread *thread)
    1335                 :             : {
    1336                 :             :         K_OOPS(K_SYSCALL_OBJ(thread, K_OBJ_THREAD));
    1337                 :             :         return z_impl_k_thread_timeout_remaining_ticks(thread);
    1338                 :             : }
    1339                 :             : #include <zephyr/syscalls/k_thread_timeout_remaining_ticks_mrsh.c>
    1340                 :             : 
    1341                 :             : static inline k_ticks_t z_vrfy_k_thread_timeout_expires_ticks(
    1342                 :             :                                                   const struct k_thread *thread)
    1343                 :             : {
    1344                 :             :         K_OOPS(K_SYSCALL_OBJ(thread, K_OBJ_THREAD));
    1345                 :             :         return z_impl_k_thread_timeout_expires_ticks(thread);
    1346                 :             : }
    1347                 :             : #include <zephyr/syscalls/k_thread_timeout_expires_ticks_mrsh.c>
    1348                 :             : #endif /* CONFIG_USERSPACE */
    1349                 :             : 
    1350                 :             : #ifdef CONFIG_INSTRUMENT_THREAD_SWITCHING
    1351                 :             : void z_thread_mark_switched_in(void)
    1352                 :             : {
    1353                 :             : #if defined(CONFIG_SCHED_THREAD_USAGE) && !defined(CONFIG_USE_SWITCH)
    1354                 :             :         z_sched_usage_start(_current);
    1355                 :             : #endif /* CONFIG_SCHED_THREAD_USAGE && !CONFIG_USE_SWITCH */
    1356                 :             : 
    1357                 :             : #ifdef CONFIG_TRACING
    1358                 :             :         SYS_PORT_TRACING_FUNC(k_thread, switched_in);
    1359                 :             : #endif /* CONFIG_TRACING */
    1360                 :             : }
    1361                 :             : 
    1362                 :             : void z_thread_mark_switched_out(void)
    1363                 :             : {
    1364                 :             : #if defined(CONFIG_SCHED_THREAD_USAGE) && !defined(CONFIG_USE_SWITCH)
    1365                 :             :         z_sched_usage_stop();
    1366                 :             : #endif /*CONFIG_SCHED_THREAD_USAGE && !CONFIG_USE_SWITCH */
    1367                 :             : 
    1368                 :             : #ifdef CONFIG_TRACING
    1369                 :             : #ifdef CONFIG_THREAD_LOCAL_STORAGE
    1370                 :             :         /* Dummy thread won't have TLS set up to run arbitrary code */
    1371                 :             :         if (!_current ||
    1372                 :             :             (_current->base.thread_state & _THREAD_DUMMY) != 0) {
    1373                 :             :                 return;
    1374                 :             :         }
    1375                 :             : #endif /* CONFIG_THREAD_LOCAL_STORAGE */
    1376                 :             :         SYS_PORT_TRACING_FUNC(k_thread, switched_out);
    1377                 :             : #endif /* CONFIG_TRACING */
    1378                 :             : }
    1379                 :             : #endif /* CONFIG_INSTRUMENT_THREAD_SWITCHING */
    1380                 :             : 
    1381                 :           0 : int k_thread_runtime_stats_get(k_tid_t thread,
    1382                 :             :                                k_thread_runtime_stats_t *stats)
    1383                 :             : {
    1384         [ #  # ]:           0 :         if ((thread == NULL) || (stats == NULL)) {
    1385                 :           0 :                 return -EINVAL;
    1386                 :             :         }
    1387                 :             : 
    1388                 :             : #ifdef CONFIG_SCHED_THREAD_USAGE
    1389                 :             :         z_sched_thread_usage(thread, stats);
    1390                 :             : #else
    1391                 :             :         *stats = (k_thread_runtime_stats_t) {};
    1392                 :             : #endif /* CONFIG_SCHED_THREAD_USAGE */
    1393                 :             : 
    1394                 :             :         return 0;
    1395                 :             : }
    1396                 :             : 
    1397                 :           0 : int k_thread_runtime_stats_all_get(k_thread_runtime_stats_t *stats)
    1398                 :             : {
    1399                 :             : #ifdef CONFIG_SCHED_THREAD_USAGE_ALL
    1400                 :             :         k_thread_runtime_stats_t  tmp_stats;
    1401                 :             : #endif /* CONFIG_SCHED_THREAD_USAGE_ALL */
    1402                 :             : 
    1403         [ #  # ]:           0 :         if (stats == NULL) {
    1404                 :           0 :                 return -EINVAL;
    1405                 :             :         }
    1406                 :             : 
    1407                 :             :         *stats = (k_thread_runtime_stats_t) {};
    1408                 :             : 
    1409                 :             : #ifdef CONFIG_SCHED_THREAD_USAGE_ALL
    1410                 :             :         /* Retrieve the usage stats for each core and amalgamate them. */
    1411                 :             : 
    1412                 :             :         unsigned int num_cpus = arch_num_cpus();
    1413                 :             : 
    1414                 :             :         for (unsigned int i = 0; i < num_cpus; i++) {
    1415                 :             :                 z_sched_cpu_usage(i, &tmp_stats);
    1416                 :             : 
    1417                 :             :                 stats->execution_cycles += tmp_stats.execution_cycles;
    1418                 :             :                 stats->total_cycles     += tmp_stats.total_cycles;
    1419                 :             : #ifdef CONFIG_SCHED_THREAD_USAGE_ANALYSIS
    1420                 :             :                 stats->current_cycles   += tmp_stats.current_cycles;
    1421                 :             :                 stats->peak_cycles      += tmp_stats.peak_cycles;
    1422                 :             :                 stats->average_cycles   += tmp_stats.average_cycles;
    1423                 :             : #endif /* CONFIG_SCHED_THREAD_USAGE_ANALYSIS */
    1424                 :             :                 stats->idle_cycles      += tmp_stats.idle_cycles;
    1425                 :             :         }
    1426                 :             : #endif /* CONFIG_SCHED_THREAD_USAGE_ALL */
    1427                 :             : 
    1428                 :             :         return 0;
    1429                 :             : }
    1430                 :             : 
    1431                 :           0 : int k_thread_runtime_stats_cpu_get(int cpu, k_thread_runtime_stats_t *stats)
    1432                 :             : {
    1433         [ #  # ]:           0 :         if (stats == NULL) {
    1434                 :           0 :                 return -EINVAL;
    1435                 :             :         }
    1436                 :             : 
    1437                 :             :         *stats = (k_thread_runtime_stats_t) {};
    1438                 :             : 
    1439                 :             : #ifdef CONFIG_SCHED_THREAD_USAGE_ALL
    1440                 :             :         CHECKIF((cpu < 0) || ((unsigned int)cpu >= arch_num_cpus())) {
    1441                 :             :                 return -EINVAL;
    1442                 :             :         }
    1443                 :             : 
    1444                 :             :         z_sched_cpu_usage(cpu, stats);
    1445                 :             : #else
    1446                 :             :         ARG_UNUSED(cpu);
    1447                 :             : #endif
    1448                 :             : 
    1449                 :             :         return 0;
    1450                 :             : }
    1451                 :             : 
    1452                 :             : #ifdef CONFIG_THREAD_ABORT_NEED_CLEANUP
    1453                 :             : /** Pointer to thread which needs to be cleaned up. */
    1454                 :             : static struct k_thread *thread_to_cleanup;
    1455                 :             : 
    1456                 :             : /** Spinlock for thread abort cleanup. */
    1457                 :             : static struct k_spinlock thread_cleanup_lock;
    1458                 :             : 
    1459                 :             : #ifdef CONFIG_THREAD_STACK_MEM_MAPPED
    1460                 :             : static void *thread_cleanup_stack_addr;
    1461                 :             : static size_t thread_cleanup_stack_sz;
    1462                 :             : 
    1463                 :             : static void unmap_thread_stack(void *addr, size_t sz)
    1464                 :             : {
    1465                 :             :         if (addr != NULL) {
    1466                 :             :                 k_mem_unmap_phys_guard(addr, sz, false);
    1467                 :             :         }
    1468                 :             : }
    1469                 :             : #endif /* CONFIG_THREAD_STACK_MEM_MAPPED */
    1470                 :             : 
    1471                 :             : void defer_thread_cleanup(struct k_thread *thread)
    1472                 :             : {
    1473                 :             :         /* Note when adding new deferred cleanup steps:
    1474                 :             :          * - The thread object may have been overwritten by the time
    1475                 :             :          *   the actual cleanup is being done (e.g. thread object
    1476                 :             :          *   allocated on a stack). So stash any necessary data here
    1477                 :             :          *   that will be used in the actual cleanup steps.
    1478                 :             :          */
    1479                 :             :         thread_to_cleanup = thread;
    1480                 :             : 
    1481                 :             : #ifdef CONFIG_THREAD_STACK_MEM_MAPPED
    1482                 :             :         /* Note that the permission of the stack should have been
    1483                 :             :          * stripped of user thread access due to the thread having
    1484                 :             :          * already exited from a memory domain. That is done via
    1485                 :             :          * k_thread_abort().
    1486                 :             :          */
    1487                 :             : 
    1488                 :             :         /* Stash the address and size so the region can be unmapped
    1489                 :             :          * later.
    1490                 :             :          */
    1491                 :             :         thread_cleanup_stack_addr = thread->stack_info.mapped.addr;
    1492                 :             :         thread_cleanup_stack_sz = thread->stack_info.mapped.sz;
    1493                 :             : 
    1494                 :             :         /* The stack is now considered un-usable. This should prevent any functions
    1495                 :             :          * from looking directly into the mapped stack if they are made to be aware
    1496                 :             :          * of memory mapped stacks, e.g., z_stack_space_get().
    1497                 :             :          */
    1498                 :             :         thread->stack_info.mapped.addr = NULL;
    1499                 :             :         thread->stack_info.mapped.sz = 0;
    1500                 :             : #endif /* CONFIG_THREAD_STACK_MEM_MAPPED */
    1501                 :             : }
    1502                 :             : 
    1503                 :             : void do_deferred_thread_cleanup(void)
    1504                 :             : {
    1505                 :             :         /* Note when adding new actual cleanup steps:
    1506                 :             :          * - The thread object may have been overwritten when this is
    1507                 :             :          *   called. So only data stashed by defer_thread_cleanup() can
    1508                 :             :          *   be used here, never anything from the thread object.
    1509                 :             :          */
    1510                 :             : 
    1511                 :             : #ifdef CONFIG_THREAD_STACK_MEM_MAPPED
    1512                 :             :         unmap_thread_stack(thread_cleanup_stack_addr, thread_cleanup_stack_sz);
    1513                 :             : 
    1514                 :             :         thread_cleanup_stack_addr = NULL;
    1515                 :             :         thread_cleanup_stack_sz = 0;
    1516                 :             : #endif /* CONFIG_THREAD_STACK_MEM_MAPPED */
    1517                 :             : }
    1518                 :             : 
    1519                 :             : void do_thread_cleanup(struct k_thread *thread)
    1520                 :             : {
    1521                 :             :         /* This is only for threads which are no longer running and are not
    1522                 :             :          * the current thread, so the thread object is still valid here and
    1523                 :             :          * the cleanup can be driven from it directly.
    1524                 :             :          */
    1525                 :             : 
    1526                 :             : #ifdef CONFIG_THREAD_STACK_MEM_MAPPED
    1527                 :             :         unmap_thread_stack(thread->stack_info.mapped.addr,
    1528                 :             :                            thread->stack_info.mapped.sz);
    1529                 :             : 
    1530                 :             :         /* The stack is now unmapped and thus un-usable. Clear the mapping
    1531                 :             :          * info so nothing looks into the stack afterwards, and so that
    1532                 :             :          * a repeated cleanup of the same thread object is a no-op,
    1533                 :             :          * e.g., z_stack_space_get().
    1534                 :             :          */
    1535                 :             :         thread->stack_info.mapped.addr = NULL;
    1536                 :             :         thread->stack_info.mapped.sz = 0;
    1537                 :             : #else /* CONFIG_THREAD_STACK_MEM_MAPPED */
    1538                 :             :         ARG_UNUSED(thread);
    1539                 :             : #endif /* CONFIG_THREAD_STACK_MEM_MAPPED */
    1540                 :             : }
    1541                 :             : 
    1542                 :             : void k_thread_abort_cleanup(struct k_thread *thread)
    1543                 :             : {
    1544                 :             :         K_SPINLOCK(&thread_cleanup_lock) {
    1545                 :             :                 if (thread_to_cleanup != NULL) {
    1546                 :             :                         /* Finish the pending one first. */
    1547                 :             :                         do_deferred_thread_cleanup();
    1548                 :             :                         thread_to_cleanup = NULL;
    1549                 :             :                 }
    1550                 :             : 
    1551                 :             :                 if (thread == _current) {
    1552                 :             :                         /* Need to defer for current running thread as the cleanup
    1553                 :             :                          * might result in exception. Actual cleanup will be done
    1554                 :             :                          * at the next time k_thread_abort() is called, or at thread
    1555                 :             :                          * creation if the same thread object is being reused. This
    1556                 :             :                          * is to make sure the cleanup code no longer needs this
    1557                 :             :                          * thread's stack. This is not exactly ideal as the stack
    1558                 :             :                          * may still be memory mapped for a while. However, this is
    1559                 :             :                          * a simple solution without a) the need to workaround
    1560                 :             :                          * the schedule lock during k_thread_abort(), b) creating
    1561                 :             :                          * another thread to perform the cleanup, and c) does not
    1562                 :             :                          * require architecture code support (e.g. via exception).
    1563                 :             :                          */
    1564                 :             :                         defer_thread_cleanup(thread);
    1565                 :             :                 } else {
    1566                 :             :                         /* Not the current running thread, so we are safe to do
    1567                 :             :                          * cleanups.
    1568                 :             :                          */
    1569                 :             :                         do_thread_cleanup(thread);
    1570                 :             :                 }
    1571                 :             :         }
    1572                 :             : }
    1573                 :             : 
    1574                 :             : void k_thread_abort_cleanup_check_reuse(struct k_thread *thread)
    1575                 :             : {
    1576                 :             :         K_SPINLOCK(&thread_cleanup_lock) {
    1577                 :             :                 /* This is to guard reuse of the same thread object and make sure
    1578                 :             :                  * any pending cleanups of it needs to be finished before the thread
    1579                 :             :                  * object can be reused.
    1580                 :             :                  */
    1581                 :             :                 if (thread_to_cleanup == thread) {
    1582                 :             :                         do_deferred_thread_cleanup();
    1583                 :             :                         thread_to_cleanup = NULL;
    1584                 :             :                 }
    1585                 :             :         }
    1586                 :             : }
    1587                 :             : 
    1588                 :             : #endif /* CONFIG_THREAD_ABORT_NEED_CLEANUP */
    1589                 :             : 
    1590                 :           1 : void z_dummy_thread_init(struct k_thread *dummy_thread)
    1591                 :             : {
    1592                 :           1 :         dummy_thread->base.thread_state = _THREAD_DUMMY;
    1593                 :             : #ifdef CONFIG_SCHED_CPU_MASK
    1594                 :             :         dummy_thread->base.cpu_mask = -1;
    1595                 :             : #endif /* CONFIG_SCHED_CPU_MASK */
    1596                 :           1 :         dummy_thread->base.user_options = K_ESSENTIAL;
    1597                 :             : #if Z_MUTEX_PI_ENABLED
    1598                 :           1 :         sys_slist_init(&dummy_thread->held_mutexes);
    1599                 :           1 :         dummy_thread->mutex_pended_on = NULL;
    1600                 :           1 :         dummy_thread->orig_prio = dummy_thread->base.prio;
    1601                 :             : #endif /* Z_MUTEX_PI_ENABLED */
    1602                 :             : #ifdef CONFIG_THREAD_STACK_INFO
    1603                 :             :         dummy_thread->stack_info.start = 0U;
    1604                 :             :         dummy_thread->stack_info.size = 0U;
    1605                 :             : #endif /* CONFIG_THREAD_STACK_INFO */
    1606                 :             : #ifdef CONFIG_USERSPACE
    1607                 :             :         dummy_thread->mem_domain_info.mem_domain = &k_mem_domain_default;
    1608                 :             : #endif /* CONFIG_USERSPACE */
    1609                 :             : #if (K_HEAP_MEM_POOL_SIZE > 0)
    1610                 :             :         k_thread_system_pool_assign(dummy_thread);
    1611                 :             : #else
    1612                 :           1 :         dummy_thread->resource_pool = NULL;
    1613                 :             : #endif /* K_HEAP_MEM_POOL_SIZE */
    1614                 :             : 
    1615                 :             : #ifdef CONFIG_USE_SWITCH
    1616                 :             :         dummy_thread->switch_handle = NULL;
    1617                 :             : #endif /* CONFIG_USE_SWITCH */
    1618                 :             : 
    1619                 :             : #ifdef CONFIG_TIMESLICE_PER_THREAD
    1620                 :             :         dummy_thread->base.slice_ticks = 0;
    1621                 :             : #endif /* CONFIG_TIMESLICE_PER_THREAD */
    1622                 :             : 
    1623                 :           1 :         z_current_thread_set(dummy_thread);
    1624                 :           1 : }
    1625                 :             : 
    1626                 :             : /*
    1627                 :             :  * Thread lifecycle APIs: suspend, resume, priority, wakeup, abort, join.
    1628                 :             :  *
    1629                 :             :  * These APIs operate on thread objects and belong here in thread.c.  They
    1630                 :             :  * depend on a small set of scheduler internals (z_thread_halt,
    1631                 :             :  * z_sched_ready_locked, z_sched_add_to_waitq_locked) exposed via ksched.h.
    1632                 :             :  */
    1633                 :             : 
    1634                 :           0 : void z_impl_k_thread_priority_set(k_tid_t thread, int prio)
    1635                 :             : {
    1636                 :             :         /*
    1637                 :             :          * Use NULL, since we cannot know what the entry point is (we do not
    1638                 :             :          * keep track of it) and idle cannot change its priority.
    1639                 :             :          */
    1640   [ #  #  #  #  :           0 :         Z_ASSERT_VALID_PRIO(prio, NULL);
                   #  # ]
    1641                 :             : 
    1642                 :           0 :         bool need_sched = z_thread_prio_set((struct k_thread *)thread, prio);
    1643                 :             : 
    1644         [ #  # ]:           0 :         if ((need_sched) && (IS_ENABLED(CONFIG_SMP) ||
    1645         [ #  # ]:           0 :                              (_current->base.sched_locked == 0U))) {
    1646                 :           0 :                 z_reschedule_unlocked();
    1647                 :             :         }
    1648                 :           0 : }
    1649                 :             : 
    1650                 :             : #ifdef CONFIG_USERSPACE
    1651                 :             : static inline void z_vrfy_k_thread_priority_set(k_tid_t thread, int prio)
    1652                 :             : {
    1653                 :             :         K_OOPS(K_SYSCALL_OBJ(thread, K_OBJ_THREAD));
    1654                 :             :         K_OOPS(K_SYSCALL_VERIFY_MSG(_is_valid_prio(prio, NULL),
    1655                 :             :                                     "invalid thread priority %d", prio));
    1656                 :             : #ifndef CONFIG_USERSPACE_THREAD_MAY_RAISE_PRIORITY
    1657                 :             :         K_OOPS(K_SYSCALL_VERIFY_MSG((int8_t)prio >= thread->base.prio,
    1658                 :             :                                     "thread priority may only be downgraded (%d < %d)",
    1659                 :             :                                     prio, thread->base.prio));
    1660                 :             : #endif /* CONFIG_USERSPACE_THREAD_MAY_RAISE_PRIORITY */
    1661                 :             :         z_impl_k_thread_priority_set(thread, prio);
    1662                 :             : }
    1663                 :             : #include <zephyr/syscalls/k_thread_priority_set_mrsh.c>
    1664                 :             : #endif /* CONFIG_USERSPACE */
    1665                 :             : 
    1666                 :           0 : void z_impl_k_thread_suspend(k_tid_t thread)
    1667                 :             : {
    1668                 :           0 :         SYS_PORT_TRACING_OBJ_FUNC_ENTER(k_thread, suspend, thread);
    1669                 :             : 
    1670                 :             :         /* Special case "suspend the current thread" as it doesn't
    1671                 :             :          * need the async complexity below.
    1672                 :             :          */
    1673                 :           0 :         if (!IS_ENABLED(CONFIG_SMP) &&
    1674   [ #  #  #  # ]:           0 :             likely((thread == _current) && !arch_is_in_isr())) {
    1675                 :           0 :                 z_thread_suspend_current(thread);
    1676                 :           0 :                 return;
    1677                 :             :         }
    1678                 :             : 
    1679                 :           0 :         k_spinlock_key_t key = z_sched_spinlock_lock();
    1680                 :             : 
    1681         [ #  # ]:           0 :         if (unlikely(z_is_thread_suspended(thread))) {
    1682                 :             : 
    1683                 :             :                 /* The target thread is already suspended. Nothing to do. */
    1684                 :             : 
    1685                 :           0 :                 z_sched_spinlock_unlock(key);
    1686                 :           0 :                 return;
    1687                 :             :         }
    1688                 :             : 
    1689                 :           0 :         z_thread_halt(thread, key, false);
    1690                 :             : 
    1691                 :           0 :         SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_thread, suspend, thread);
    1692                 :             : }
    1693                 :             : 
    1694                 :             : #ifdef CONFIG_USERSPACE
    1695                 :             : static inline void z_vrfy_k_thread_suspend(k_tid_t thread)
    1696                 :             : {
    1697                 :             :         K_OOPS(K_SYSCALL_OBJ(thread, K_OBJ_THREAD));
    1698                 :             :         z_impl_k_thread_suspend(thread);
    1699                 :             : }
    1700                 :             : #include <zephyr/syscalls/k_thread_suspend_mrsh.c>
    1701                 :             : #endif /* CONFIG_USERSPACE */
    1702                 :             : 
    1703                 :           0 : void z_impl_k_thread_resume(k_tid_t thread)
    1704                 :             : {
    1705                 :           0 :         SYS_PORT_TRACING_OBJ_FUNC_ENTER(k_thread, resume, thread);
    1706                 :             : 
    1707                 :           0 :         k_spinlock_key_t key = z_sched_spinlock_lock();
    1708                 :             : 
    1709                 :             :         /* Do not try to resume a thread that was not suspended */
    1710         [ #  # ]:           0 :         if (unlikely(!z_is_thread_suspended(thread))) {
    1711                 :           0 :                 z_sched_spinlock_unlock(key);
    1712                 :           0 :                 return;
    1713                 :             :         }
    1714                 :             : 
    1715                 :           0 :         z_mark_thread_as_not_suspended(thread);
    1716                 :           0 :         z_sched_ready_locked(thread);
    1717                 :             : 
    1718                 :           0 :         z_reschedule_locked(key);
    1719                 :             : 
    1720                 :           0 :         SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_thread, resume, thread);
    1721                 :             : }
    1722                 :             : 
    1723                 :             : #ifdef CONFIG_USERSPACE
    1724                 :             : static inline void z_vrfy_k_thread_resume(k_tid_t thread)
    1725                 :             : {
    1726                 :             :         K_OOPS(K_SYSCALL_OBJ(thread, K_OBJ_THREAD));
    1727                 :             :         z_impl_k_thread_resume(thread);
    1728                 :             : }
    1729                 :             : #include <zephyr/syscalls/k_thread_resume_mrsh.c>
    1730                 :             : #endif /* CONFIG_USERSPACE */
    1731                 :             : 
    1732                 :          58 : void z_impl_k_wakeup(k_tid_t thread)
    1733                 :             : {
    1734                 :          58 :         SYS_PORT_TRACING_OBJ_FUNC(k_thread, wakeup, thread);
    1735                 :             : 
    1736                 :          58 :         k_spinlock_key_t key = z_sched_spinlock_lock();
    1737                 :             : 
    1738         [ +  + ]:          58 :         if (z_is_thread_sleeping(thread)) {
    1739                 :          54 :                 (void)z_try_abort_thread_timeout(thread);
    1740                 :          54 :                 z_mark_thread_as_not_sleeping(thread);
    1741                 :          54 :                 z_sched_ready_locked(thread);
    1742                 :          54 :                 z_reschedule_locked(key);
    1743                 :             :         } else {
    1744                 :           4 :                 z_sched_spinlock_unlock(key);
    1745                 :             :         }
    1746                 :          58 : }
    1747                 :             : 
    1748                 :             : #ifdef CONFIG_USERSPACE
    1749                 :             : static inline void z_vrfy_k_wakeup(k_tid_t thread)
    1750                 :             : {
    1751                 :             :         K_OOPS(K_SYSCALL_OBJ(thread, K_OBJ_THREAD));
    1752                 :             :         z_impl_k_wakeup(thread);
    1753                 :             : }
    1754                 :             : #include <zephyr/syscalls/k_wakeup_mrsh.c>
    1755                 :             : #endif /* CONFIG_USERSPACE */
    1756                 :             : 
    1757                 :         104 : void z_thread_abort(struct k_thread *thread)
    1758                 :             : {
    1759                 :         104 :         bool essential = z_is_thread_essential(thread);
    1760                 :         104 :         k_spinlock_key_t key = z_sched_spinlock_lock();
    1761                 :             : 
    1762         [ +  + ]:         104 :         if (z_is_thread_dead(thread)) {
    1763                 :          50 :                 z_sched_spinlock_unlock(key);
    1764                 :          50 :                 return;
    1765                 :             :         }
    1766                 :             : 
    1767                 :          54 :         z_thread_halt(thread, key, true);
    1768                 :             : 
    1769         [ #  # ]:           0 :         if (essential) {
    1770                 :           0 :                 __ASSERT(!essential, "aborted essential thread %p", thread);
    1771                 :           0 :                 k_panic();
    1772                 :             :         }
    1773                 :             : }
    1774                 :             : 
    1775                 :             : #if !defined(CONFIG_ARCH_HAS_THREAD_ABORT)
    1776                 :             : void z_impl_k_thread_abort(k_tid_t thread)
    1777                 :             : {
    1778                 :             :         SYS_PORT_TRACING_OBJ_FUNC_ENTER(k_thread, abort, thread);
    1779                 :             : 
    1780                 :             :         z_thread_abort(thread);
    1781                 :             : 
    1782                 :             :         __ASSERT_NO_MSG(z_is_thread_dead(thread));
    1783                 :             : 
    1784                 :             :         SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_thread, abort, thread);
    1785                 :             : }
    1786                 :             : #endif /* !CONFIG_ARCH_HAS_THREAD_ABORT */
    1787                 :             : 
    1788                 :          54 : int z_impl_k_thread_join(struct k_thread *thread, k_timeout_t timeout)
    1789                 :             : {
    1790                 :          54 :         k_spinlock_key_t key = z_sched_spinlock_lock();
    1791                 :          54 :         int ret;
    1792                 :             : 
    1793                 :          54 :         SYS_PORT_TRACING_OBJ_FUNC_ENTER(k_thread, join, thread, timeout);
    1794                 :             : 
    1795   [ +  +  -  + ]:          54 :         if (z_is_thread_dead(thread) && !z_is_thread_halting(thread)) {
    1796                 :             :                 z_sched_switch_spin(thread);
    1797                 :          48 :                 ret = 0;
    1798         [ +  - ]:           6 :         } else if (K_TIMEOUT_EQ(timeout, K_NO_WAIT)) {
    1799                 :             :                 ret = -EBUSY;
    1800         [ +  - ]:           6 :         } else if ((thread == _current) ||
    1801         [ +  - ]:           6 :                    (thread->base.pended_on == &_current->join_queue)) {
    1802                 :             :                 ret = -EDEADLK;
    1803                 :             :         } else {
    1804         [ -  + ]:           6 :                 __ASSERT(!arch_is_in_isr(), "cannot join in ISR");
    1805                 :           6 :                 z_sched_add_to_waitq_locked(_current, &thread->join_queue);
    1806                 :           6 :                 z_add_thread_timeout(_current, timeout);
    1807                 :             : 
    1808                 :           6 :                 SYS_PORT_TRACING_OBJ_FUNC_BLOCKING(k_thread, join, thread, timeout);
    1809                 :           6 :                 ret = z_swap_locked(key);
    1810                 :           6 :                 SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_thread, join, thread, timeout, ret);
    1811                 :             : 
    1812                 :           6 :                 return ret;
    1813                 :             :         }
    1814                 :             : 
    1815                 :          48 :         SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_thread, join, thread, timeout, ret);
    1816                 :             : 
    1817                 :          48 :         z_sched_spinlock_unlock(key);
    1818                 :          48 :         return ret;
    1819                 :             : }
    1820                 :             : 
    1821                 :             : #ifdef CONFIG_USERSPACE
    1822                 :             : /* Special case: don't oops if the thread is uninitialized.  This is because
    1823                 :             :  * the initialization bit does double-duty for thread objects; if false, means
    1824                 :             :  * the thread object is truly uninitialized, or the thread ran and exited for
    1825                 :             :  * some reason.
    1826                 :             :  *
    1827                 :             :  * Return true in this case indicating we should just do nothing and return
    1828                 :             :  * success to the caller.
    1829                 :             :  */
    1830                 :             : static bool thread_obj_validate(struct k_thread *thread)
    1831                 :             : {
    1832                 :             :         struct k_object *ko = k_object_find(thread);
    1833                 :             :         int ret = k_object_validate(ko, K_OBJ_THREAD, _OBJ_INIT_TRUE);
    1834                 :             : 
    1835                 :             :         switch (ret) {
    1836                 :             :         case 0:
    1837                 :             :                 return false;
    1838                 :             :         case -EINVAL:
    1839                 :             :                 return true;
    1840                 :             :         default:
    1841                 :             : #ifdef CONFIG_LOG
    1842                 :             :                 k_object_dump_error(ret, thread, ko, K_OBJ_THREAD);
    1843                 :             : #endif /* CONFIG_LOG */
    1844                 :             :                 /* ret is a non-zero error code here (the 0 and -EINVAL cases
    1845                 :             :                  * are handled above), so this branch must always oops. Passing
    1846                 :             :                  * ret as the "verify" expression would treat the failure code as
    1847                 :             :                  * success and fall through to CODE_UNREACHABLE; verify ret == 0
    1848                 :             :                  * so the oops is actually raised.
    1849                 :             :                  */
    1850                 :             :                 K_OOPS(K_SYSCALL_VERIFY_MSG(ret == 0, "access denied"));
    1851                 :             :         }
    1852                 :             :         CODE_UNREACHABLE; /* LCOV_EXCL_LINE */
    1853                 :             : }
    1854                 :             : 
    1855                 :             : static inline int z_vrfy_k_thread_join(struct k_thread *thread,
    1856                 :             :                                        k_timeout_t timeout)
    1857                 :             : {
    1858                 :             :         if (thread_obj_validate(thread)) {
    1859                 :             :                 return 0;
    1860                 :             :         }
    1861                 :             : 
    1862                 :             :         return z_impl_k_thread_join(thread, timeout);
    1863                 :             : }
    1864                 :             : #include <zephyr/syscalls/k_thread_join_mrsh.c>
    1865                 :             : 
    1866                 :             : static inline void z_vrfy_k_thread_abort(k_tid_t thread)
    1867                 :             : {
    1868                 :             :         if (thread_obj_validate(thread)) {
    1869                 :             :                 return;
    1870                 :             :         }
    1871                 :             : 
    1872                 :             :         K_OOPS(K_SYSCALL_VERIFY_MSG(!z_is_thread_essential(thread),
    1873                 :             :                                     "aborting essential thread %p", thread));
    1874                 :             : 
    1875                 :             :         z_impl_k_thread_abort((struct k_thread *)thread);
    1876                 :             : }
    1877                 :             : #include <zephyr/syscalls/k_thread_abort_mrsh.c>
    1878                 :             : #endif /* CONFIG_USERSPACE */
    1879                 :             : 
    1880                 :           0 : bool k_can_yield(void)
    1881                 :             : {
    1882   [ #  #  #  #  :           0 :         return !(k_is_pre_kernel() || k_is_in_isr() || !arch_cpu_irqs_are_enabled() ||
                   #  # ]
    1883         [ #  # ]:           0 :                  z_is_idle_thread_object(_current));
    1884                 :             : }
    1885                 :             : 
    1886                 :           0 : void z_impl_k_yield(void)
    1887                 :             : {
    1888         [ #  # ]:           0 :         __ASSERT(!arch_is_in_isr(), "");
    1889                 :             : 
    1890                 :           0 :         SYS_PORT_TRACING_FUNC(k_thread, yield);
    1891                 :             : 
    1892                 :           0 :         z_sched_yield();
    1893                 :           0 : }
    1894                 :             : 
    1895                 :             : #ifdef CONFIG_USERSPACE
    1896                 :             : static inline void z_vrfy_k_yield(void)
    1897                 :             : {
    1898                 :             :         z_impl_k_yield();
    1899                 :             : }
    1900                 :             : #include <zephyr/syscalls/k_yield_mrsh.c>
    1901                 :             : #endif /* CONFIG_USERSPACE */
        

Generated by: LCOV version 2.0-1