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 <zephyr/internal/syscall_handler.h>
22 #include <kernel_internal.h>
23 #include <kswap.h>
24 #include <zephyr/init.h>
25 #include <zephyr/tracing/tracing.h>
26 #include <string.h>
27 #include <stdbool.h>
28 #include <zephyr/sys/check.h>
29 #include <zephyr/random/random.h>
30 #include <zephyr/sys/atomic.h>
31 #include <zephyr/logging/log.h>
32 #include <zephyr/llext/symbol.h>
33 #include <zephyr/sys/iterable_sections.h>
34
35 LOG_MODULE_DECLARE(os, CONFIG_KERNEL_LOG_LEVEL);
36
37 #ifdef CONFIG_OBJ_CORE_THREAD
38 static struct k_obj_type obj_type_thread;
39
40 #ifdef CONFIG_OBJ_CORE_STATS_THREAD
41 static struct k_obj_core_stats_desc thread_stats_desc = {
42 .raw_size = sizeof(struct k_cycle_stats),
43 .query_size = sizeof(struct k_thread_runtime_stats),
44 .raw = z_thread_stats_raw,
45 .query = z_thread_stats_query,
46 .reset = z_thread_stats_reset,
47 .disable = z_thread_stats_disable,
48 .enable = z_thread_stats_enable,
49 };
50 #endif /* CONFIG_OBJ_CORE_STATS_THREAD */
51
init_thread_obj_core_list(void)52 static int init_thread_obj_core_list(void)
53 {
54 /* Initialize mem_slab object type */
55
56 #ifdef CONFIG_OBJ_CORE_THREAD
57 z_obj_type_init(&obj_type_thread, K_OBJ_TYPE_THREAD_ID,
58 offsetof(struct k_thread, obj_core));
59 #endif /* CONFIG_OBJ_CORE_THREAD */
60
61 #ifdef CONFIG_OBJ_CORE_STATS_THREAD
62 k_obj_type_stats_init(&obj_type_thread, &thread_stats_desc);
63 #endif /* CONFIG_OBJ_CORE_STATS_THREAD */
64
65 return 0;
66 }
67
68 SYS_INIT(init_thread_obj_core_list, PRE_KERNEL_1,
69 CONFIG_KERNEL_INIT_PRIORITY_OBJECTS);
70 #endif /* CONFIG_OBJ_CORE_THREAD */
71
72
73 #define _FOREACH_STATIC_THREAD(thread_data) \
74 STRUCT_SECTION_FOREACH(_static_thread_data, thread_data)
75
k_is_in_isr(void)76 bool k_is_in_isr(void)
77 {
78 return arch_is_in_isr();
79 }
80 EXPORT_SYMBOL(k_is_in_isr);
81
82 #ifdef CONFIG_THREAD_CUSTOM_DATA
z_impl_k_thread_custom_data_set(void * value)83 void z_impl_k_thread_custom_data_set(void *value)
84 {
85 arch_current_thread()->custom_data = value;
86 }
87
88 #ifdef CONFIG_USERSPACE
z_vrfy_k_thread_custom_data_set(void * data)89 static inline void z_vrfy_k_thread_custom_data_set(void *data)
90 {
91 z_impl_k_thread_custom_data_set(data);
92 }
93 #include <zephyr/syscalls/k_thread_custom_data_set_mrsh.c>
94 #endif /* CONFIG_USERSPACE */
95
z_impl_k_thread_custom_data_get(void)96 void *z_impl_k_thread_custom_data_get(void)
97 {
98 return arch_current_thread()->custom_data;
99 }
100
101 #ifdef CONFIG_USERSPACE
z_vrfy_k_thread_custom_data_get(void)102 static inline void *z_vrfy_k_thread_custom_data_get(void)
103 {
104 return z_impl_k_thread_custom_data_get();
105 }
106 #include <zephyr/syscalls/k_thread_custom_data_get_mrsh.c>
107
108 #endif /* CONFIG_USERSPACE */
109 #endif /* CONFIG_THREAD_CUSTOM_DATA */
110
z_impl_k_is_preempt_thread(void)111 int z_impl_k_is_preempt_thread(void)
112 {
113 return !arch_is_in_isr() && thread_is_preemptible(arch_current_thread());
114 }
115
116 #ifdef CONFIG_USERSPACE
z_vrfy_k_is_preempt_thread(void)117 static inline int z_vrfy_k_is_preempt_thread(void)
118 {
119 return z_impl_k_is_preempt_thread();
120 }
121 #include <zephyr/syscalls/k_is_preempt_thread_mrsh.c>
122 #endif /* CONFIG_USERSPACE */
123
z_impl_k_thread_priority_get(k_tid_t thread)124 int z_impl_k_thread_priority_get(k_tid_t thread)
125 {
126 return thread->base.prio;
127 }
128
129 #ifdef CONFIG_USERSPACE
z_vrfy_k_thread_priority_get(k_tid_t thread)130 static inline int z_vrfy_k_thread_priority_get(k_tid_t thread)
131 {
132 K_OOPS(K_SYSCALL_OBJ(thread, K_OBJ_THREAD));
133 return z_impl_k_thread_priority_get(thread);
134 }
135 #include <zephyr/syscalls/k_thread_priority_get_mrsh.c>
136 #endif /* CONFIG_USERSPACE */
137
z_impl_k_thread_name_set(k_tid_t thread,const char * str)138 int z_impl_k_thread_name_set(k_tid_t thread, const char *str)
139 {
140 #ifdef CONFIG_THREAD_NAME
141 if (thread == NULL) {
142 thread = arch_current_thread();
143 }
144
145 strncpy(thread->name, str, CONFIG_THREAD_MAX_NAME_LEN - 1);
146 thread->name[CONFIG_THREAD_MAX_NAME_LEN - 1] = '\0';
147
148 #ifdef CONFIG_ARCH_HAS_THREAD_NAME_HOOK
149 arch_thread_name_set(thread, str);
150 #endif /* CONFIG_ARCH_HAS_THREAD_NAME_HOOK */
151
152 SYS_PORT_TRACING_OBJ_FUNC(k_thread, name_set, thread, 0);
153
154 return 0;
155 #else
156 ARG_UNUSED(thread);
157 ARG_UNUSED(str);
158
159 SYS_PORT_TRACING_OBJ_FUNC(k_thread, name_set, thread, -ENOSYS);
160
161 return -ENOSYS;
162 #endif /* CONFIG_THREAD_NAME */
163 }
164
165 #ifdef CONFIG_USERSPACE
z_vrfy_k_thread_name_set(k_tid_t thread,const char * str)166 static inline int z_vrfy_k_thread_name_set(k_tid_t thread, const char *str)
167 {
168 #ifdef CONFIG_THREAD_NAME
169 char name[CONFIG_THREAD_MAX_NAME_LEN];
170
171 if (thread != NULL) {
172 if (K_SYSCALL_OBJ(thread, K_OBJ_THREAD) != 0) {
173 return -EINVAL;
174 }
175 }
176
177 /* In theory we could copy directly into thread->name, but
178 * the current z_vrfy / z_impl split does not provide a
179 * means of doing so.
180 */
181 if (k_usermode_string_copy(name, str, sizeof(name)) != 0) {
182 return -EFAULT;
183 }
184
185 return z_impl_k_thread_name_set(thread, name);
186 #else
187 return -ENOSYS;
188 #endif /* CONFIG_THREAD_NAME */
189 }
190 #include <zephyr/syscalls/k_thread_name_set_mrsh.c>
191 #endif /* CONFIG_USERSPACE */
192
k_thread_name_get(k_tid_t thread)193 const char *k_thread_name_get(k_tid_t thread)
194 {
195 #ifdef CONFIG_THREAD_NAME
196 return (const char *)thread->name;
197 #else
198 ARG_UNUSED(thread);
199 return NULL;
200 #endif /* CONFIG_THREAD_NAME */
201 }
202
z_impl_k_thread_name_copy(k_tid_t thread,char * buf,size_t size)203 int z_impl_k_thread_name_copy(k_tid_t thread, char *buf, size_t size)
204 {
205 #ifdef CONFIG_THREAD_NAME
206 strncpy(buf, thread->name, size);
207 return 0;
208 #else
209 ARG_UNUSED(thread);
210 ARG_UNUSED(buf);
211 ARG_UNUSED(size);
212 return -ENOSYS;
213 #endif /* CONFIG_THREAD_NAME */
214 }
215
copy_bytes(char * dest,size_t dest_size,const char * src,size_t src_size)216 static size_t copy_bytes(char *dest, size_t dest_size, const char *src, size_t src_size)
217 {
218 size_t bytes_to_copy;
219
220 bytes_to_copy = MIN(dest_size, src_size);
221 memcpy(dest, src, bytes_to_copy);
222
223 return bytes_to_copy;
224 }
225
k_thread_state_str(k_tid_t thread_id,char * buf,size_t buf_size)226 const char *k_thread_state_str(k_tid_t thread_id, char *buf, size_t buf_size)
227 {
228 size_t off = 0;
229 uint8_t bit;
230 uint8_t thread_state = thread_id->base.thread_state;
231 #define SS_ENT(s) { Z_STATE_STR_##s, _THREAD_##s, sizeof(Z_STATE_STR_##s) - 1 }
232 static const struct {
233 const char *str;
234 uint16_t bit;
235 uint16_t len;
236 } state_string[] = {
237 SS_ENT(DUMMY),
238 SS_ENT(PENDING),
239 SS_ENT(SLEEPING),
240 SS_ENT(DEAD),
241 SS_ENT(SUSPENDED),
242 SS_ENT(ABORTING),
243 SS_ENT(SUSPENDING),
244 SS_ENT(QUEUED),
245 };
246 #undef SS_ENT
247
248 if ((buf == NULL) || (buf_size == 0)) {
249 return "";
250 }
251
252 buf_size--; /* Reserve 1 byte for end-of-string character */
253
254 /*
255 * Loop through each bit in the thread_state. Stop once all have
256 * been processed. If more than one thread_state bit is set, then
257 * separate the descriptive strings with a '+'.
258 */
259
260
261 for (unsigned int index = 0; thread_state != 0; index++) {
262 bit = state_string[index].bit;
263 if ((thread_state & bit) == 0) {
264 continue;
265 }
266
267 off += copy_bytes(buf + off, buf_size - off,
268 state_string[index].str,
269 state_string[index].len);
270
271 thread_state &= ~bit;
272
273 if (thread_state != 0) {
274 off += copy_bytes(buf + off, buf_size - off, "+", 1);
275 }
276 }
277
278 buf[off] = '\0';
279
280 return (const char *)buf;
281 }
282
283 #ifdef CONFIG_USERSPACE
z_vrfy_k_thread_name_copy(k_tid_t thread,char * buf,size_t size)284 static inline int z_vrfy_k_thread_name_copy(k_tid_t thread,
285 char *buf, size_t size)
286 {
287 #ifdef CONFIG_THREAD_NAME
288 size_t len;
289 struct k_object *ko = k_object_find(thread);
290
291 /* Special case: we allow reading the names of initialized threads
292 * even if we don't have permission on them
293 */
294 if ((thread == NULL) || (ko->type != K_OBJ_THREAD) ||
295 ((ko->flags & K_OBJ_FLAG_INITIALIZED) == 0)) {
296 return -EINVAL;
297 }
298 if (K_SYSCALL_MEMORY_WRITE(buf, size) != 0) {
299 return -EFAULT;
300 }
301 len = strlen(thread->name);
302 if ((len + 1) > size) {
303 return -ENOSPC;
304 }
305
306 return k_usermode_to_copy((void *)buf, thread->name, len + 1);
307 #else
308 ARG_UNUSED(thread);
309 ARG_UNUSED(buf);
310 ARG_UNUSED(size);
311 return -ENOSYS;
312 #endif /* CONFIG_THREAD_NAME */
313 }
314 #include <zephyr/syscalls/k_thread_name_copy_mrsh.c>
315 #endif /* CONFIG_USERSPACE */
316
317 #ifdef CONFIG_STACK_SENTINEL
318 /* Check that the stack sentinel is still present
319 *
320 * The stack sentinel feature writes a magic value to the lowest 4 bytes of
321 * the thread's stack when the thread is initialized. This value gets checked
322 * in a few places:
323 *
324 * 1) In k_yield() if the current thread is not swapped out
325 * 2) After servicing a non-nested interrupt
326 * 3) In z_swap(), check the sentinel in the outgoing thread
327 *
328 * Item 2 requires support in arch/ code.
329 *
330 * If the check fails, the thread will be terminated appropriately through
331 * the system fatal error handler.
332 */
z_check_stack_sentinel(void)333 void z_check_stack_sentinel(void)
334 {
335 uint32_t *stack;
336
337 if ((arch_current_thread()->base.thread_state & _THREAD_DUMMY) != 0) {
338 return;
339 }
340
341 stack = (uint32_t *)arch_current_thread()->stack_info.start;
342 if (*stack != STACK_SENTINEL) {
343 /* Restore it so further checks don't trigger this same error */
344 *stack = STACK_SENTINEL;
345 z_except_reason(K_ERR_STACK_CHK_FAIL);
346 }
347 }
348 #endif /* CONFIG_STACK_SENTINEL */
349
350 #if defined(CONFIG_STACK_POINTER_RANDOM) && (CONFIG_STACK_POINTER_RANDOM != 0)
351 int z_stack_adjust_initialized;
352
random_offset(size_t stack_size)353 static size_t random_offset(size_t stack_size)
354 {
355 size_t random_val;
356
357 if (!z_stack_adjust_initialized) {
358 z_early_rand_get((uint8_t *)&random_val, sizeof(random_val));
359 } else {
360 sys_rand_get((uint8_t *)&random_val, sizeof(random_val));
361 }
362
363 /* Don't need to worry about alignment of the size here,
364 * arch_new_thread() is required to do it.
365 *
366 * FIXME: Not the best way to get a random number in a range.
367 * See #6493
368 */
369 const size_t fuzz = random_val % CONFIG_STACK_POINTER_RANDOM;
370
371 if (unlikely(fuzz * 2 > stack_size)) {
372 return 0;
373 }
374
375 return fuzz;
376 }
377 #if defined(CONFIG_STACK_GROWS_UP)
378 /* This is so rare not bothering for now */
379 #error "Stack pointer randomization not implemented for upward growing stacks"
380 #endif /* CONFIG_STACK_GROWS_UP */
381 #endif /* CONFIG_STACK_POINTER_RANDOM */
382
setup_thread_stack(struct k_thread * new_thread,k_thread_stack_t * stack,size_t stack_size)383 static char *setup_thread_stack(struct k_thread *new_thread,
384 k_thread_stack_t *stack, size_t stack_size)
385 {
386 size_t stack_obj_size, stack_buf_size;
387 char *stack_ptr, *stack_buf_start;
388 size_t delta = 0;
389
390 #ifdef CONFIG_USERSPACE
391 if (z_stack_is_user_capable(stack)) {
392 stack_obj_size = K_THREAD_STACK_LEN(stack_size);
393 stack_buf_start = K_THREAD_STACK_BUFFER(stack);
394 stack_buf_size = stack_obj_size - K_THREAD_STACK_RESERVED;
395 } else
396 #endif /* CONFIG_USERSPACE */
397 {
398 /* Object cannot host a user mode thread */
399 stack_obj_size = K_KERNEL_STACK_LEN(stack_size);
400 stack_buf_start = K_KERNEL_STACK_BUFFER(stack);
401 stack_buf_size = stack_obj_size - K_KERNEL_STACK_RESERVED;
402
403 /* Zephyr treats stack overflow as an app bug. But
404 * this particular overflow can be seen by static
405 * analysis so needs to be handled somehow.
406 */
407 if (K_KERNEL_STACK_RESERVED > stack_obj_size) {
408 k_panic();
409 }
410
411 }
412
413 #ifdef CONFIG_THREAD_STACK_MEM_MAPPED
414 /* Map the stack into virtual memory and use that as the base to
415 * calculate the initial stack pointer at the high end of the stack
416 * object. The stack pointer may be reduced later in this function
417 * by TLS or random offset.
418 *
419 * K_MEM_MAP_UNINIT is used to mimic the behavior of non-mapped
420 * stack. If CONFIG_INIT_STACKS is enabled, the stack will be
421 * cleared below.
422 */
423 void *stack_mapped = k_mem_map_phys_guard((uintptr_t)stack, stack_obj_size,
424 K_MEM_PERM_RW | K_MEM_CACHE_WB | K_MEM_MAP_UNINIT,
425 false);
426
427 __ASSERT_NO_MSG((uintptr_t)stack_mapped != 0);
428
429 #ifdef CONFIG_USERSPACE
430 if (z_stack_is_user_capable(stack)) {
431 stack_buf_start = K_THREAD_STACK_BUFFER(stack_mapped);
432 } else
433 #endif /* CONFIG_USERSPACE */
434 {
435 stack_buf_start = K_KERNEL_STACK_BUFFER(stack_mapped);
436 }
437
438 stack_ptr = (char *)stack_mapped + stack_obj_size;
439
440 /* Need to store the info on mapped stack so we can remove the mappings
441 * when the thread ends.
442 */
443 new_thread->stack_info.mapped.addr = stack_mapped;
444 new_thread->stack_info.mapped.sz = stack_obj_size;
445
446 #else /* CONFIG_THREAD_STACK_MEM_MAPPED */
447
448 /* Initial stack pointer at the high end of the stack object, may
449 * be reduced later in this function by TLS or random offset
450 */
451 stack_ptr = (char *)stack + stack_obj_size;
452
453 #endif /* CONFIG_THREAD_STACK_MEM_MAPPED */
454
455 LOG_DBG("stack %p for thread %p: obj_size=%zu buf_start=%p "
456 " buf_size %zu stack_ptr=%p",
457 stack, new_thread, stack_obj_size, (void *)stack_buf_start,
458 stack_buf_size, (void *)stack_ptr);
459
460 #ifdef CONFIG_INIT_STACKS
461 memset(stack_buf_start, 0xaa, stack_buf_size);
462 #endif /* CONFIG_INIT_STACKS */
463 #ifdef CONFIG_STACK_SENTINEL
464 /* Put the stack sentinel at the lowest 4 bytes of the stack area.
465 * We periodically check that it's still present and kill the thread
466 * if it isn't.
467 */
468 *((uint32_t *)stack_buf_start) = STACK_SENTINEL;
469 #endif /* CONFIG_STACK_SENTINEL */
470 #ifdef CONFIG_THREAD_LOCAL_STORAGE
471 /* TLS is always last within the stack buffer */
472 delta += arch_tls_stack_setup(new_thread, stack_ptr);
473 #endif /* CONFIG_THREAD_LOCAL_STORAGE */
474 #ifdef CONFIG_THREAD_USERSPACE_LOCAL_DATA
475 size_t tls_size = sizeof(struct _thread_userspace_local_data);
476
477 /* reserve space on highest memory of stack buffer for local data */
478 delta += tls_size;
479 new_thread->userspace_local_data =
480 (struct _thread_userspace_local_data *)(stack_ptr - delta);
481 #endif /* CONFIG_THREAD_USERSPACE_LOCAL_DATA */
482 #if defined(CONFIG_STACK_POINTER_RANDOM) && (CONFIG_STACK_POINTER_RANDOM != 0)
483 delta += random_offset(stack_buf_size);
484 #endif /* CONFIG_STACK_POINTER_RANDOM */
485 delta = ROUND_UP(delta, ARCH_STACK_PTR_ALIGN);
486 #ifdef CONFIG_THREAD_STACK_INFO
487 /* Initial values. Arches which implement MPU guards that "borrow"
488 * memory from the stack buffer (not tracked in K_THREAD_STACK_RESERVED)
489 * will need to appropriately update this.
490 *
491 * The bounds tracked here correspond to the area of the stack object
492 * that the thread can access, which includes TLS.
493 */
494 new_thread->stack_info.start = (uintptr_t)stack_buf_start;
495 new_thread->stack_info.size = stack_buf_size;
496 new_thread->stack_info.delta = delta;
497 #endif /* CONFIG_THREAD_STACK_INFO */
498 stack_ptr -= delta;
499
500 return stack_ptr;
501 }
502
503 /*
504 * The provided stack_size value is presumed to be either the result of
505 * K_THREAD_STACK_SIZEOF(stack), or the size value passed to the instance
506 * of K_THREAD_STACK_DEFINE() which defined 'stack'.
507 */
z_setup_new_thread(struct k_thread * new_thread,k_thread_stack_t * stack,size_t stack_size,k_thread_entry_t entry,void * p1,void * p2,void * p3,int prio,uint32_t options,const char * name)508 char *z_setup_new_thread(struct k_thread *new_thread,
509 k_thread_stack_t *stack, size_t stack_size,
510 k_thread_entry_t entry,
511 void *p1, void *p2, void *p3,
512 int prio, uint32_t options, const char *name)
513 {
514 char *stack_ptr;
515
516 Z_ASSERT_VALID_PRIO(prio, entry);
517
518 #ifdef CONFIG_THREAD_ABORT_NEED_CLEANUP
519 k_thread_abort_cleanup_check_reuse(new_thread);
520 #endif /* CONFIG_THREAD_ABORT_NEED_CLEANUP */
521
522 #ifdef CONFIG_OBJ_CORE_THREAD
523 k_obj_core_init_and_link(K_OBJ_CORE(new_thread), &obj_type_thread);
524 #ifdef CONFIG_OBJ_CORE_STATS_THREAD
525 k_obj_core_stats_register(K_OBJ_CORE(new_thread),
526 &new_thread->base.usage,
527 sizeof(new_thread->base.usage));
528 #endif /* CONFIG_OBJ_CORE_STATS_THREAD */
529 #endif /* CONFIG_OBJ_CORE_THREAD */
530
531 #ifdef CONFIG_USERSPACE
532 __ASSERT((options & K_USER) == 0U || z_stack_is_user_capable(stack),
533 "user thread %p with kernel-only stack %p",
534 new_thread, stack);
535 k_object_init(new_thread);
536 k_object_init(stack);
537 new_thread->stack_obj = stack;
538 new_thread->syscall_frame = NULL;
539
540 /* Any given thread has access to itself */
541 k_object_access_grant(new_thread, new_thread);
542 #endif /* CONFIG_USERSPACE */
543 z_waitq_init(&new_thread->join_queue);
544
545 /* Initialize various struct k_thread members */
546 z_init_thread_base(&new_thread->base, prio, _THREAD_SLEEPING, options);
547 stack_ptr = setup_thread_stack(new_thread, stack, stack_size);
548
549 #ifdef CONFIG_KERNEL_COHERENCE
550 /* Check that the thread object is safe, but that the stack is
551 * still cached!
552 */
553 __ASSERT_NO_MSG(arch_mem_coherent(new_thread));
554
555 /* When dynamic thread stack is available, the stack may come from
556 * uncached area.
557 */
558 #ifndef CONFIG_DYNAMIC_THREAD
559 __ASSERT_NO_MSG(!arch_mem_coherent(stack));
560 #endif /* CONFIG_DYNAMIC_THREAD */
561
562 #endif /* CONFIG_KERNEL_COHERENCE */
563
564 arch_new_thread(new_thread, stack, stack_ptr, entry, p1, p2, p3);
565
566 /* static threads overwrite it afterwards with real value */
567 new_thread->init_data = NULL;
568
569 #ifdef CONFIG_USE_SWITCH
570 /* switch_handle must be non-null except when inside z_swap()
571 * for synchronization reasons. Historically some notional
572 * USE_SWITCH architectures have actually ignored the field
573 */
574 __ASSERT(new_thread->switch_handle != NULL,
575 "arch layer failed to initialize switch_handle");
576 #endif /* CONFIG_USE_SWITCH */
577 #ifdef CONFIG_THREAD_CUSTOM_DATA
578 /* Initialize custom data field (value is opaque to kernel) */
579 new_thread->custom_data = NULL;
580 #endif /* CONFIG_THREAD_CUSTOM_DATA */
581 #ifdef CONFIG_EVENTS
582 new_thread->no_wake_on_timeout = false;
583 #endif /* CONFIG_EVENTS */
584 #ifdef CONFIG_THREAD_MONITOR
585 new_thread->entry.pEntry = entry;
586 new_thread->entry.parameter1 = p1;
587 new_thread->entry.parameter2 = p2;
588 new_thread->entry.parameter3 = p3;
589
590 k_spinlock_key_t key = k_spin_lock(&z_thread_monitor_lock);
591
592 new_thread->next_thread = _kernel.threads;
593 _kernel.threads = new_thread;
594 k_spin_unlock(&z_thread_monitor_lock, key);
595 #endif /* CONFIG_THREAD_MONITOR */
596 #ifdef CONFIG_THREAD_NAME
597 if (name != NULL) {
598 strncpy(new_thread->name, name,
599 CONFIG_THREAD_MAX_NAME_LEN - 1);
600 /* Ensure NULL termination, truncate if longer */
601 new_thread->name[CONFIG_THREAD_MAX_NAME_LEN - 1] = '\0';
602 #ifdef CONFIG_ARCH_HAS_THREAD_NAME_HOOK
603 arch_thread_name_set(new_thread, name);
604 #endif /* CONFIG_ARCH_HAS_THREAD_NAME_HOOK */
605 } else {
606 new_thread->name[0] = '\0';
607 }
608 #endif /* CONFIG_THREAD_NAME */
609 #ifdef CONFIG_SCHED_CPU_MASK
610 if (IS_ENABLED(CONFIG_SCHED_CPU_MASK_PIN_ONLY)) {
611 new_thread->base.cpu_mask = 1; /* must specify only one cpu */
612 } else {
613 new_thread->base.cpu_mask = -1; /* allow all cpus */
614 }
615 #endif /* CONFIG_SCHED_CPU_MASK */
616 #ifdef CONFIG_ARCH_HAS_CUSTOM_SWAP_TO_MAIN
617 /* arch_current_thread() may be null if the dummy thread is not used */
618 if (!arch_current_thread()) {
619 new_thread->resource_pool = NULL;
620 return stack_ptr;
621 }
622 #endif /* CONFIG_ARCH_HAS_CUSTOM_SWAP_TO_MAIN */
623 #ifdef CONFIG_USERSPACE
624 z_mem_domain_init_thread(new_thread);
625
626 if ((options & K_INHERIT_PERMS) != 0U) {
627 k_thread_perms_inherit(arch_current_thread(), new_thread);
628 }
629 #endif /* CONFIG_USERSPACE */
630 #ifdef CONFIG_SCHED_DEADLINE
631 new_thread->base.prio_deadline = 0;
632 #endif /* CONFIG_SCHED_DEADLINE */
633 new_thread->resource_pool = arch_current_thread()->resource_pool;
634
635 #ifdef CONFIG_SMP
636 z_waitq_init(&new_thread->halt_queue);
637 #endif /* CONFIG_SMP */
638
639 #ifdef CONFIG_SCHED_THREAD_USAGE
640 new_thread->base.usage = (struct k_cycle_stats) {};
641 new_thread->base.usage.track_usage =
642 CONFIG_SCHED_THREAD_USAGE_AUTO_ENABLE;
643 #endif /* CONFIG_SCHED_THREAD_USAGE */
644
645 SYS_PORT_TRACING_OBJ_FUNC(k_thread, create, new_thread);
646
647 return stack_ptr;
648 }
649
650
z_impl_k_thread_create(struct k_thread * new_thread,k_thread_stack_t * stack,size_t stack_size,k_thread_entry_t entry,void * p1,void * p2,void * p3,int prio,uint32_t options,k_timeout_t delay)651 k_tid_t z_impl_k_thread_create(struct k_thread *new_thread,
652 k_thread_stack_t *stack,
653 size_t stack_size, k_thread_entry_t entry,
654 void *p1, void *p2, void *p3,
655 int prio, uint32_t options, k_timeout_t delay)
656 {
657 __ASSERT(!arch_is_in_isr(), "Threads may not be created in ISRs");
658
659 z_setup_new_thread(new_thread, stack, stack_size, entry, p1, p2, p3,
660 prio, options, NULL);
661
662 if (!K_TIMEOUT_EQ(delay, K_FOREVER)) {
663 thread_schedule_new(new_thread, delay);
664 }
665
666 return new_thread;
667 }
668
669 #ifdef CONFIG_USERSPACE
z_stack_is_user_capable(k_thread_stack_t * stack)670 bool z_stack_is_user_capable(k_thread_stack_t *stack)
671 {
672 return k_object_find(stack) != NULL;
673 }
674
z_vrfy_k_thread_create(struct k_thread * new_thread,k_thread_stack_t * stack,size_t stack_size,k_thread_entry_t entry,void * p1,void * p2,void * p3,int prio,uint32_t options,k_timeout_t delay)675 k_tid_t z_vrfy_k_thread_create(struct k_thread *new_thread,
676 k_thread_stack_t *stack,
677 size_t stack_size, k_thread_entry_t entry,
678 void *p1, void *p2, void *p3,
679 int prio, uint32_t options, k_timeout_t delay)
680 {
681 size_t total_size, stack_obj_size;
682 struct k_object *stack_object;
683
684 /* The thread and stack objects *must* be in an uninitialized state */
685 K_OOPS(K_SYSCALL_OBJ_NEVER_INIT(new_thread, K_OBJ_THREAD));
686
687 /* No need to check z_stack_is_user_capable(), it won't be in the
688 * object table if it isn't
689 */
690 stack_object = k_object_find(stack);
691 K_OOPS(K_SYSCALL_VERIFY_MSG(k_object_validation_check(stack_object, stack,
692 K_OBJ_THREAD_STACK_ELEMENT,
693 _OBJ_INIT_FALSE) == 0,
694 "bad stack object"));
695
696 /* Verify that the stack size passed in is OK by computing the total
697 * size and comparing it with the size value in the object metadata
698 */
699 K_OOPS(K_SYSCALL_VERIFY_MSG(!size_add_overflow(K_THREAD_STACK_RESERVED,
700 stack_size, &total_size),
701 "stack size overflow (%zu+%zu)",
702 stack_size,
703 K_THREAD_STACK_RESERVED));
704
705 /* Testing less-than-or-equal since additional room may have been
706 * allocated for alignment constraints
707 */
708 #ifdef CONFIG_GEN_PRIV_STACKS
709 stack_obj_size = stack_object->data.stack_data->size;
710 #else
711 stack_obj_size = stack_object->data.stack_size;
712 #endif /* CONFIG_GEN_PRIV_STACKS */
713 K_OOPS(K_SYSCALL_VERIFY_MSG(total_size <= stack_obj_size,
714 "stack size %zu is too big, max is %zu",
715 total_size, stack_obj_size));
716
717 /* User threads may only create other user threads and they can't
718 * be marked as essential
719 */
720 K_OOPS(K_SYSCALL_VERIFY(options & K_USER));
721 K_OOPS(K_SYSCALL_VERIFY(!(options & K_ESSENTIAL)));
722
723 /* Check validity of prio argument; must be the same or worse priority
724 * than the caller
725 */
726 K_OOPS(K_SYSCALL_VERIFY(_is_valid_prio(prio, NULL)));
727 K_OOPS(K_SYSCALL_VERIFY(z_is_prio_lower_or_equal(prio,
728 arch_current_thread()->base.prio)));
729
730 z_setup_new_thread(new_thread, stack, stack_size,
731 entry, p1, p2, p3, prio, options, NULL);
732
733 if (!K_TIMEOUT_EQ(delay, K_FOREVER)) {
734 thread_schedule_new(new_thread, delay);
735 }
736
737 return new_thread;
738 }
739 #include <zephyr/syscalls/k_thread_create_mrsh.c>
740 #endif /* CONFIG_USERSPACE */
741
z_init_thread_base(struct _thread_base * thread_base,int priority,uint32_t initial_state,unsigned int options)742 void z_init_thread_base(struct _thread_base *thread_base, int priority,
743 uint32_t initial_state, unsigned int options)
744 {
745 /* k_q_node is initialized upon first insertion in a list */
746 thread_base->pended_on = NULL;
747 thread_base->user_options = (uint8_t)options;
748 thread_base->thread_state = (uint8_t)initial_state;
749
750 thread_base->prio = priority;
751
752 thread_base->sched_locked = 0U;
753
754 #ifdef CONFIG_SMP
755 thread_base->is_idle = 0;
756 #endif /* CONFIG_SMP */
757
758 #ifdef CONFIG_TIMESLICE_PER_THREAD
759 thread_base->slice_ticks = 0;
760 thread_base->slice_expired = NULL;
761 #endif /* CONFIG_TIMESLICE_PER_THREAD */
762
763 /* swap_data does not need to be initialized */
764
765 z_init_thread_timeout(thread_base);
766 }
767
k_thread_user_mode_enter(k_thread_entry_t entry,void * p1,void * p2,void * p3)768 FUNC_NORETURN void k_thread_user_mode_enter(k_thread_entry_t entry,
769 void *p1, void *p2, void *p3)
770 {
771 SYS_PORT_TRACING_FUNC(k_thread, user_mode_enter);
772
773 arch_current_thread()->base.user_options |= K_USER;
774 z_thread_essential_clear(arch_current_thread());
775 #ifdef CONFIG_THREAD_MONITOR
776 arch_current_thread()->entry.pEntry = entry;
777 arch_current_thread()->entry.parameter1 = p1;
778 arch_current_thread()->entry.parameter2 = p2;
779 arch_current_thread()->entry.parameter3 = p3;
780 #endif /* CONFIG_THREAD_MONITOR */
781 #ifdef CONFIG_USERSPACE
782 __ASSERT(z_stack_is_user_capable(arch_current_thread()->stack_obj),
783 "dropping to user mode with kernel-only stack object");
784 #ifdef CONFIG_THREAD_USERSPACE_LOCAL_DATA
785 memset(arch_current_thread()->userspace_local_data, 0,
786 sizeof(struct _thread_userspace_local_data));
787 #endif /* CONFIG_THREAD_USERSPACE_LOCAL_DATA */
788 #ifdef CONFIG_THREAD_LOCAL_STORAGE
789 arch_tls_stack_setup(arch_current_thread(),
790 (char *)(arch_current_thread()->stack_info.start +
791 arch_current_thread()->stack_info.size));
792 #endif /* CONFIG_THREAD_LOCAL_STORAGE */
793 arch_user_mode_enter(entry, p1, p2, p3);
794 #else
795 /* XXX In this case we do not reset the stack */
796 z_thread_entry(entry, p1, p2, p3);
797 #endif /* CONFIG_USERSPACE */
798 }
799
800 #if defined(CONFIG_INIT_STACKS) && defined(CONFIG_THREAD_STACK_INFO)
801 #ifdef CONFIG_STACK_GROWS_UP
802 #error "Unsupported configuration for stack analysis"
803 #endif /* CONFIG_STACK_GROWS_UP */
804
z_stack_space_get(const uint8_t * stack_start,size_t size,size_t * unused_ptr)805 int z_stack_space_get(const uint8_t *stack_start, size_t size, size_t *unused_ptr)
806 {
807 size_t unused = 0;
808 const uint8_t *checked_stack = stack_start;
809 /* Take the address of any local variable as a shallow bound for the
810 * stack pointer. Addresses above it are guaranteed to be
811 * accessible.
812 */
813 const uint8_t *stack_pointer = (const uint8_t *)&stack_start;
814
815 /* If we are currently running on the stack being analyzed, some
816 * memory management hardware will generate an exception if we
817 * read unused stack memory.
818 *
819 * This never happens when invoked from user mode, as user mode
820 * will always run this function on the privilege elevation stack.
821 */
822 if ((stack_pointer > stack_start) && (stack_pointer <= (stack_start + size)) &&
823 IS_ENABLED(CONFIG_NO_UNUSED_STACK_INSPECTION)) {
824 /* TODO: We could add an arch_ API call to temporarily
825 * disable the stack checking in the CPU, but this would
826 * need to be properly managed wrt context switches/interrupts
827 */
828 return -ENOTSUP;
829 }
830
831 if (IS_ENABLED(CONFIG_STACK_SENTINEL)) {
832 /* First 4 bytes of the stack buffer reserved for the
833 * sentinel value, it won't be 0xAAAAAAAA for thread
834 * stacks.
835 *
836 * FIXME: thread->stack_info.start ought to reflect
837 * this!
838 */
839 checked_stack += 4;
840 size -= 4;
841 }
842
843 for (size_t i = 0; i < size; i++) {
844 if ((checked_stack[i]) == 0xaaU) {
845 unused++;
846 } else {
847 break;
848 }
849 }
850
851 *unused_ptr = unused;
852
853 return 0;
854 }
855
z_impl_k_thread_stack_space_get(const struct k_thread * thread,size_t * unused_ptr)856 int z_impl_k_thread_stack_space_get(const struct k_thread *thread,
857 size_t *unused_ptr)
858 {
859 #ifdef CONFIG_THREAD_STACK_MEM_MAPPED
860 if (thread->stack_info.mapped.addr == NULL) {
861 return -EINVAL;
862 }
863 #endif /* CONFIG_THREAD_STACK_MEM_MAPPED */
864
865 return z_stack_space_get((const uint8_t *)thread->stack_info.start,
866 thread->stack_info.size, unused_ptr);
867 }
868
869 #ifdef CONFIG_USERSPACE
z_vrfy_k_thread_stack_space_get(const struct k_thread * thread,size_t * unused_ptr)870 int z_vrfy_k_thread_stack_space_get(const struct k_thread *thread,
871 size_t *unused_ptr)
872 {
873 size_t unused;
874 int ret;
875
876 ret = K_SYSCALL_OBJ(thread, K_OBJ_THREAD);
877 CHECKIF(ret != 0) {
878 return ret;
879 }
880
881 ret = z_impl_k_thread_stack_space_get(thread, &unused);
882 CHECKIF(ret != 0) {
883 return ret;
884 }
885
886 ret = k_usermode_to_copy(unused_ptr, &unused, sizeof(size_t));
887 CHECKIF(ret != 0) {
888 return ret;
889 }
890
891 return 0;
892 }
893 #include <zephyr/syscalls/k_thread_stack_space_get_mrsh.c>
894 #endif /* CONFIG_USERSPACE */
895 #endif /* CONFIG_INIT_STACKS && CONFIG_THREAD_STACK_INFO */
896
897 #ifdef CONFIG_USERSPACE
z_vrfy_k_thread_timeout_remaining_ticks(const struct k_thread * thread)898 static inline k_ticks_t z_vrfy_k_thread_timeout_remaining_ticks(
899 const struct k_thread *thread)
900 {
901 K_OOPS(K_SYSCALL_OBJ(thread, K_OBJ_THREAD));
902 return z_impl_k_thread_timeout_remaining_ticks(thread);
903 }
904 #include <zephyr/syscalls/k_thread_timeout_remaining_ticks_mrsh.c>
905
z_vrfy_k_thread_timeout_expires_ticks(const struct k_thread * thread)906 static inline k_ticks_t z_vrfy_k_thread_timeout_expires_ticks(
907 const struct k_thread *thread)
908 {
909 K_OOPS(K_SYSCALL_OBJ(thread, K_OBJ_THREAD));
910 return z_impl_k_thread_timeout_expires_ticks(thread);
911 }
912 #include <zephyr/syscalls/k_thread_timeout_expires_ticks_mrsh.c>
913 #endif /* CONFIG_USERSPACE */
914
915 #ifdef CONFIG_INSTRUMENT_THREAD_SWITCHING
z_thread_mark_switched_in(void)916 void z_thread_mark_switched_in(void)
917 {
918 #if defined(CONFIG_SCHED_THREAD_USAGE) && !defined(CONFIG_USE_SWITCH)
919 z_sched_usage_start(arch_current_thread());
920 #endif /* CONFIG_SCHED_THREAD_USAGE && !CONFIG_USE_SWITCH */
921
922 #ifdef CONFIG_TRACING
923 SYS_PORT_TRACING_FUNC(k_thread, switched_in);
924 #endif /* CONFIG_TRACING */
925 }
926
z_thread_mark_switched_out(void)927 void z_thread_mark_switched_out(void)
928 {
929 #if defined(CONFIG_SCHED_THREAD_USAGE) && !defined(CONFIG_USE_SWITCH)
930 z_sched_usage_stop();
931 #endif /*CONFIG_SCHED_THREAD_USAGE && !CONFIG_USE_SWITCH */
932
933 #ifdef CONFIG_TRACING
934 #ifdef CONFIG_THREAD_LOCAL_STORAGE
935 /* Dummy thread won't have TLS set up to run arbitrary code */
936 if (!arch_current_thread() ||
937 (arch_current_thread()->base.thread_state & _THREAD_DUMMY) != 0)
938 return;
939 #endif /* CONFIG_THREAD_LOCAL_STORAGE */
940 SYS_PORT_TRACING_FUNC(k_thread, switched_out);
941 #endif /* CONFIG_TRACING */
942 }
943 #endif /* CONFIG_INSTRUMENT_THREAD_SWITCHING */
944
k_thread_runtime_stats_get(k_tid_t thread,k_thread_runtime_stats_t * stats)945 int k_thread_runtime_stats_get(k_tid_t thread,
946 k_thread_runtime_stats_t *stats)
947 {
948 if ((thread == NULL) || (stats == NULL)) {
949 return -EINVAL;
950 }
951
952 #ifdef CONFIG_SCHED_THREAD_USAGE
953 z_sched_thread_usage(thread, stats);
954 #else
955 *stats = (k_thread_runtime_stats_t) {};
956 #endif /* CONFIG_SCHED_THREAD_USAGE */
957
958 return 0;
959 }
960
k_thread_runtime_stats_all_get(k_thread_runtime_stats_t * stats)961 int k_thread_runtime_stats_all_get(k_thread_runtime_stats_t *stats)
962 {
963 #ifdef CONFIG_SCHED_THREAD_USAGE_ALL
964 k_thread_runtime_stats_t tmp_stats;
965 #endif /* CONFIG_SCHED_THREAD_USAGE_ALL */
966
967 if (stats == NULL) {
968 return -EINVAL;
969 }
970
971 *stats = (k_thread_runtime_stats_t) {};
972
973 #ifdef CONFIG_SCHED_THREAD_USAGE_ALL
974 /* Retrieve the usage stats for each core and amalgamate them. */
975
976 unsigned int num_cpus = arch_num_cpus();
977
978 for (uint8_t i = 0; i < num_cpus; i++) {
979 z_sched_cpu_usage(i, &tmp_stats);
980
981 stats->execution_cycles += tmp_stats.execution_cycles;
982 stats->total_cycles += tmp_stats.total_cycles;
983 #ifdef CONFIG_SCHED_THREAD_USAGE_ANALYSIS
984 stats->current_cycles += tmp_stats.current_cycles;
985 stats->peak_cycles += tmp_stats.peak_cycles;
986 stats->average_cycles += tmp_stats.average_cycles;
987 #endif /* CONFIG_SCHED_THREAD_USAGE_ANALYSIS */
988 stats->idle_cycles += tmp_stats.idle_cycles;
989 }
990 #endif /* CONFIG_SCHED_THREAD_USAGE_ALL */
991
992 return 0;
993 }
994
k_thread_runtime_stats_cpu_get(int cpu,k_thread_runtime_stats_t * stats)995 int k_thread_runtime_stats_cpu_get(int cpu, k_thread_runtime_stats_t *stats)
996 {
997 if (stats == NULL) {
998 return -EINVAL;
999 }
1000
1001 *stats = (k_thread_runtime_stats_t) {};
1002
1003 #ifdef CONFIG_SCHED_THREAD_USAGE_ALL
1004 #ifdef CONFIG_SMP
1005 z_sched_cpu_usage(cpu, stats);
1006 #else
1007 __ASSERT(cpu == 0, "cpu filter out of bounds");
1008 ARG_UNUSED(cpu);
1009 z_sched_cpu_usage(0, stats);
1010 #endif
1011 #endif
1012
1013 return 0;
1014 }
1015
1016 #ifdef CONFIG_THREAD_ABORT_NEED_CLEANUP
1017 /** Pointer to thread which needs to be cleaned up. */
1018 static struct k_thread *thread_to_cleanup;
1019
1020 /** Spinlock for thread abort cleanup. */
1021 static struct k_spinlock thread_cleanup_lock;
1022
1023 #ifdef CONFIG_THREAD_STACK_MEM_MAPPED
1024 static void *thread_cleanup_stack_addr;
1025 static size_t thread_cleanup_stack_sz;
1026 #endif /* CONFIG_THREAD_STACK_MEM_MAPPED */
1027
defer_thread_cleanup(struct k_thread * thread)1028 void defer_thread_cleanup(struct k_thread *thread)
1029 {
1030 /* Note when adding new deferred cleanup steps:
1031 * - The thread object may have been overwritten by the time
1032 * the actual cleanup is being done (e.g. thread object
1033 * allocated on a stack). So stash any necessary data here
1034 * that will be used in the actual cleanup steps.
1035 */
1036 thread_to_cleanup = thread;
1037
1038 #ifdef CONFIG_THREAD_STACK_MEM_MAPPED
1039 /* Note that the permission of the stack should have been
1040 * stripped of user thread access due to the thread having
1041 * already exited from a memory domain. That is done via
1042 * k_thread_abort().
1043 */
1044
1045 /* Stash the address and size so the region can be unmapped
1046 * later.
1047 */
1048 thread_cleanup_stack_addr = thread->stack_info.mapped.addr;
1049 thread_cleanup_stack_sz = thread->stack_info.mapped.sz;
1050
1051 /* The stack is now considered un-usable. This should prevent any functions
1052 * from looking directly into the mapped stack if they are made to be aware
1053 * of memory mapped stacks, e.g., z_stack_space_get().
1054 */
1055 thread->stack_info.mapped.addr = NULL;
1056 thread->stack_info.mapped.sz = 0;
1057 #endif /* CONFIG_THREAD_STACK_MEM_MAPPED */
1058 }
1059
do_thread_cleanup(struct k_thread * thread)1060 void do_thread_cleanup(struct k_thread *thread)
1061 {
1062 /* Note when adding new actual cleanup steps:
1063 * - The thread object may have been overwritten when this is
1064 * called. So avoid using any data from the thread object.
1065 */
1066 ARG_UNUSED(thread);
1067
1068 #ifdef CONFIG_THREAD_STACK_MEM_MAPPED
1069 if (thread_cleanup_stack_addr != NULL) {
1070 k_mem_unmap_phys_guard(thread_cleanup_stack_addr,
1071 thread_cleanup_stack_sz, false);
1072
1073 thread_cleanup_stack_addr = NULL;
1074 }
1075 #endif /* CONFIG_THREAD_STACK_MEM_MAPPED */
1076 }
1077
k_thread_abort_cleanup(struct k_thread * thread)1078 void k_thread_abort_cleanup(struct k_thread *thread)
1079 {
1080 K_SPINLOCK(&thread_cleanup_lock) {
1081 if (thread_to_cleanup != NULL) {
1082 /* Finish the pending one first. */
1083 do_thread_cleanup(thread_to_cleanup);
1084 thread_to_cleanup = NULL;
1085 }
1086
1087 if (thread == arch_current_thread()) {
1088 /* Need to defer for current running thread as the cleanup
1089 * might result in exception. Actual cleanup will be done
1090 * at the next time k_thread_abort() is called, or at thread
1091 * creation if the same thread object is being reused. This
1092 * is to make sure the cleanup code no longer needs this
1093 * thread's stack. This is not exactly ideal as the stack
1094 * may still be memory mapped for a while. However, this is
1095 * a simple solution without a) the need to workaround
1096 * the schedule lock during k_thread_abort(), b) creating
1097 * another thread to perform the cleanup, and c) does not
1098 * require architecture code support (e.g. via exception).
1099 */
1100 defer_thread_cleanup(thread);
1101 } else {
1102 /* Not the current running thread, so we are safe to do
1103 * cleanups.
1104 */
1105 do_thread_cleanup(thread);
1106 }
1107 }
1108 }
1109
k_thread_abort_cleanup_check_reuse(struct k_thread * thread)1110 void k_thread_abort_cleanup_check_reuse(struct k_thread *thread)
1111 {
1112 K_SPINLOCK(&thread_cleanup_lock) {
1113 /* This is to guard reuse of the same thread object and make sure
1114 * any pending cleanups of it needs to be finished before the thread
1115 * object can be reused.
1116 */
1117 if (thread_to_cleanup == thread) {
1118 do_thread_cleanup(thread_to_cleanup);
1119 thread_to_cleanup = NULL;
1120 }
1121 }
1122 }
1123
1124 #endif /* CONFIG_THREAD_ABORT_NEED_CLEANUP */
1125