1 /*
2  * Copyright (c) 2016 Wind River Systems, Inc.
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 /**
8  * @file
9  * @brief ARM Cortex-M k_thread_abort() routine
10  *
11  * The ARM Cortex-M architecture provides its own k_thread_abort() to deal
12  * with different CPU modes (handler vs thread) when a thread aborts. When its
13  * entry point returns or when it aborts itself, the CPU is in thread mode and
14  * must call z_swap() (which triggers a service call), but when in handler
15  * mode, the CPU must exit handler mode to cause the context switch, and thus
16  * must queue the PendSV exception.
17  */
18 
19 #include <zephyr/kernel.h>
20 #include <zephyr/toolchain.h>
21 #include <zephyr/linker/sections.h>
22 #include <ksched.h>
23 #include <kswap.h>
24 #include <zephyr/sys/__assert.h>
25 
z_impl_k_thread_abort(k_tid_t thread)26 void z_impl_k_thread_abort(k_tid_t thread)
27 {
28 	SYS_PORT_TRACING_OBJ_FUNC_ENTER(k_thread, abort, thread);
29 
30 	if (_current == thread) {
31 		if (arch_is_in_isr()) {
32 			/* ARM is unlike most arches in that this is true
33 			 * even for non-peripheral interrupts, even though
34 			 * for these types of faults there is not an implicit
35 			 * reschedule on the way out. See #21923.
36 			 *
37 			 * We have to reschedule since the current thread
38 			 * should no longer run after we return, so
39 			 * Trigger PendSV, in case we are in one of the
40 			 * situations where the isr check is true but there
41 			 * is not an implicit scheduler invocation.
42 			 */
43 			SCB->ICSR |= SCB_ICSR_PENDSVSET_Msk;
44 			/* Clear any system calls that may be pending
45 			 * as they have a higher priority than the PendSV
46 			 * handler and will check the stack of the thread
47 			 * being aborted.
48 			 */
49 			SCB->SHCSR &= ~SCB_SHCSR_SVCALLPENDED_Msk;
50 		}
51 	}
52 
53 	z_thread_abort(thread);
54 
55 	SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_thread, abort, thread);
56 }
57