目次: Zephyr
前回はCONFIG_SMPのビルドエラーと実行時エラーに対応しました。以前書いたとおり、SMP対応は下記の手順で進めていますので、再掲します。
前回までで2番目の項目が終わったところです。今回はコア数を増やして先頭以外のコアで実行します。
Zephyrを書き換える前に、変更した効果が確認できる環境を作りましょう。サンプルのsynchronizationを少し改造してHART IDを表示します。
// zephyr/samples/synchronization/src/main.c
void helloLoop(const char *my_name,
struct k_sem *my_sem, struct k_sem *other_sem)
{
const char *tname;
while (1) {
int id = z_riscv_hart_id(); //★HART IDを取得★
/* take my semaphore */
k_sem_take(my_sem, K_FOREVER);
/* say "hello" */
tname = k_thread_name_get(k_current_get());
if (tname != NULL && tname[0] != '\0') {
printk("%d: %s: Hello World from %s!\n",
id, tname, CONFIG_BOARD); //★HART IDを一緒に表示する★
} else {
printk("%d: %s: Hello World from %s!\n",
id, my_name, CONFIG_BOARD); //★HART IDを一緒に表示する★
}
今回は変更してもしなくても構わないですが、カーネルコンフィグを変えるとk_thread_name_get() でスレッド名が取得できるようになります。スレッドを多数作成したときに便利です。
$ ninja menuconfig
General Kernel Options --->
Kernel Debugging and Metrics --->
[*] Thread name [EXPERIMENTAL]
動作させると下記のような表示になるはずです。
$ mkdir build $ cd build $ cmake -G Ninja -DBOARD=qemu_rv32_virt ../samples/synchronization/ ... $ ninja ... $ qemu-system-riscv32 -nographic -machine virt -net none -chardev stdio,id=con,mux=on -serial chardev:con -mon chardev=con,mode=readline -kernel zephyr/zephyr.elf -cpu rv32 -smp cpus=1 -bios none ** Booting Zephyr OS build zephyr-v2.4.0-546-g720718653f92 *** 0: thread_a: Hello World from QEMU RV32 virt board! 0: thread_b: Hello World from QEMU RV32 virt board! 0: thread_a: Hello World from QEMU RV32 virt board! 0: thread_b: Hello World from QEMU RV32 virt board! ...
HART ID = 0で実行されていることがわかります。
続きは次回です。
この記事にコメントする
目次: Zephyr
SMP対応のうち、ビルドエラーの対処が終わったので、実行時エラーに対処します。
CONFIG_SMPを有効にすると、k_spin_lock() 内でatomic_cas() を呼ぶようになります。するとk_spin_lock() -> atomic_cas() -> z_impl_atomic_cas() -> k_spin_lock() という循環呼び出しが発生し、スタックオーバーフローを起こしてクラッシュします。これはZephyrのバグではなくコンフィグの設定間違いが原因です。
// zephyr/include/spinlock.h
static ALWAYS_INLINE k_spinlock_key_t k_spin_lock(struct k_spinlock *l)
{
ARG_UNUSED(l);
k_spinlock_key_t k;
/* Note that we need to use the underlying arch-specific lock
* implementation. The "irq_lock()" API in SMP context is
* actually a wrapper for a global spinlock!
*/
k.key = arch_irq_lock();
#ifdef CONFIG_SPIN_VALIDATE
__ASSERT(z_spin_lock_valid(l), "Recursive spinlock %p", l);
#endif
#ifdef CONFIG_SMP
while (!atomic_cas(&l->locked, 0, 1)) { //★CONFIG_SMPが有効だとatomic_cas() を呼ぶ★
}
#endif
...
// zephyr/include/sys/atomic.h
#ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN
static inline bool atomic_cas(atomic_t *target, atomic_val_t old_value,
atomic_val_t new_value)
{
return __atomic_compare_exchange_n(target, &old_value, new_value,
0, __ATOMIC_SEQ_CST,
__ATOMIC_SEQ_CST);
}
#elif defined(CONFIG_ATOMIC_OPERATIONS_C) //★既存のRISC-Vボードはこちらが有効になっている★
__syscall bool atomic_cas(atomic_t *target, atomic_val_t old_value,
atomic_val_t new_value);
#else
extern bool atomic_cas(atomic_t *target, atomic_val_t old_value,
atomic_val_t new_value);
#endif
...
// build/zephyr/include/generated/syscalls/atomic.h
static inline bool atomic_cas(atomic_t * target, atomic_val_t old_value, atomic_val_t new_value)
{
#ifdef CONFIG_USERSPACE
if (z_syscall_trap()) {
return (bool) arch_syscall_invoke3(*(uintptr_t *)&target, *(uintptr_t *)&old_value, *(uintptr_t *)&new_value, K_SYSCALL_ATOMIC_CAS);
}
#endif
compiler_barrier();
return z_impl_atomic_cas(target, old_value, new_value); //★ここにくる★
}
...
// zephyr/kernel/CMakeLists.txt
target_sources_ifdef(CONFIG_ATOMIC_OPERATIONS_C kernel PRIVATE atomic_c.c) //★CONFIG_ATOMIC_OPERATIONS_C有効のとき実装はatomic_c.c★
...
// zephyr/kernel/atomic_c.c
bool z_impl_atomic_cas(atomic_t *target, atomic_val_t old_value,
atomic_val_t new_value)
{
k_spinlock_key_t key;
int ret = false;
key = k_spin_lock(&lock); //★循環呼び出し★
if (*target == old_value) {
*target = new_value;
ret = true;
}
k_spin_unlock(&lock, key);
return ret;
}
...
RISC-VのSoCのコンフィグでは大抵CONFIG_ATOMIC_OPERATIONS_Cが有効になっていて、atomic_cas() の実装としてスピンロックを使います。これはSMPと相性が悪く、CONFIG_ATOMIC_OPERATIONS_CとCONFIG_SMPを同時に有効にすると先ほど説明した循環呼び出しが発生してしまいます。
循環呼び出しを防ぐには独自にatomic_cas() を実装する必要がありますが、アトミック操作を自分で実装&検証するのは大変ですから、RISC-Vのアトミック命令(Atomic Extension)とコンパイラの機能を頼ります。
以前追加したQEMU RISC-V 32bit virtpc用のコンフィグをSMPのテスト用に改造します。
# zephyr/soc/riscv/riscv-privilege/rv32-virt/Kconfig.soc
config SOC_QEMU_RV32_VIRT
bool "QEMU RV32 virt SOC implementation"
select ATOMIC_OPERATIONS_C if !SMP # 非SMPのときは従来通り
select ATOMIC_OPERATIONS_BUILTIN if SMP # SMPのときはAtomic Extensionに頼る
コンフィグCONFIG_ATOMIC_OPERATIONS_BUILTINを有効にすると、Zephyrはatomic_cas() の実装として __atomic_compare_exchange_n() ビルトイン関数を使います。ビルトイン関数を使うにはコンパイラのサポートが必要で、今のところ、サポートしているのはGCCのみだと思います。LLVMでも使えるかもしれませんが、未調査です。
これでCONFIG_SMPを有効にしても、エラーやハングアップすることなく、今までどおりに動作するようになったはずです。
この記事にコメントする
目次: Zephyr
SMP対応の序盤、ビルドエラー対処の続きです。
ビルドの難所です。CONFIG_SMPを有効にするとisr.Sで大量にエラーが出ます。
zephyr/arch/riscv/core/isr.S:305: Error: illegal operands `lw sp,_kernel_offset_to_irq_stack(t2)'
zephyr/arch/riscv/core/isr.S:316: Error: illegal operands `lw t3,_kernel_offset_to_nested(t2)'
zephyr/arch/riscv/core/isr.S:376: Error: illegal operands `sw t2,_kernel_offset_to_nested(t1)'
zephyr/arch/riscv/core/isr.S:463: Error: illegal operands `lw t1,(0x78+___ready_q_t_cache_OFFSET)(t0)'
zephyr/arch/riscv/core/isr.S:468: Error: illegal operands `sw t1,_kernel_offset_to_current(t0)'
原因は_kernel_offset_* 系のオフセットマクロが未定義になるためです。
// zephyr/kernel/include/offsets_short.h
#ifndef CONFIG_SMP
/* Relies on _kernel.cpu being the first member of _kernel and having 1 element
*/
#define _kernel_offset_to_nested \r (___cpu_t_nested_OFFSET)
#define _kernel_offset_to_irq_stack \r (___cpu_t_irq_stack_OFFSET)
#define _kernel_offset_to_current \r (___cpu_t_current_OFFSET)
#endif /* CONFIG_SMP */
#define _kernel_offset_to_idle \r (___kernel_t_idle_OFFSET)
#define _kernel_offset_to_current_fp \r (___kernel_t_current_fp_OFFSET)
#define _kernel_offset_to_ready_q_cache \r (___kernel_t_ready_q_OFFSET + ___ready_q_t_cache_OFFSET)
...
// zephyr/include/kernel_offsets.h
...
#ifndef CONFIG_SMP
GEN_OFFSET_SYM(_ready_q_t, cache);
#endif
当たり前ですが、この #ifdefを外すだけではSMPは動きません。対策方法を理解するには、Zephyrのカーネル構造体の内部に、少しだけ立ち入る必要があります。
カーネル構造体は_kernelという名前で何度か出ていましたが、見覚えありますか?なくても全然構わないです。下記のような定義の構造体です。細かい定義はさておき、大事なことはcpusが _kernelの先頭にある、という点です。
// zephyr/kernel/sched.c
/* the only struct z_kernel instance */
struct z_kernel _kernel;
// zephyr/include/kernel_structs.h
struct z_kernel {
struct _cpu cpus[CONFIG_MP_NUM_CPUS]; //★_kernelの先頭にcpusがある★
#ifdef CONFIG_SYS_CLOCK_EXISTS
/* queue of timeouts */
sys_dlist_t timeout_q;
#endif
#ifdef CONFIG_SYS_POWER_MANAGEMENT
int32_t idle; /* Number of ticks for kernel idling */
#endif
/*
* ready queue: can be big, keep after small fields, since some
* assembly (e.g. ARC) are limited in the encoding of the offset
*/
struct _ready_q ready_q;
...
// zephyr/include/kernel_structs.h
struct _cpu {
/* nested interrupt count */
uint32_t nested;
/* interrupt stack pointer base */
char *irq_stack;
/* currently scheduled thread */
struct k_thread *current;
/* one assigned idle thread per CPU */
struct k_thread *idle_thread;
...
CPUが1つしか存在しない場合、cpusの要素数は1であり、_kernelの先頭 = cpus[0] の先頭になります。そのため _kernel.cpus[0].currentのオフセット = cpu構造体のcurrentへのオフセット、です。offsets_short.hの定義はこの性質を利用しています。
C言語だとcpus[0] とcpus[i] の違いでしかなく、ありがたみがわかりませんが、アセンブラだと非常に単純かつ高速にオフセットを求めることができます。下記はisr.Sから持ってきた例ですが、_kernel.cpus[0].currentへのアクセスがわずか2命令で実現できます。
la t0, _kernel
RV_OP_LOADREG t0, _kernel_offset_to_current(t0)
残念ながらSMPの場合はcpusが1つではありませんから、上記の最適化は使えません。cpus[n] のオフセット、つまりHART ID * sizeof(struct _cpu) を計算する必要があります。
まずはstruct _cpuのオフセットマクロが未定義なので、追加します。ZephyrではGEN_ABSOLUTE_SYM() というマクロが用意されており、アセンブラ用のマクロを生成してくれます。便利ですね。
// zephyr/arch/riscv/core/offsets/offsets.c
#ifdef CONFIG_SMP
GEN_ABSOLUTE_SYM(__cpu_t_SIZEOF, sizeof(_cpu_t));
#endif
次にisr.Sのビルドエラーが出ている箇所を直します。
// zephyr/arch/riscv/core/isr.S
/*
* xreg0: result &_kernel.cpu[mhartid]
* xreg1: work area
*/
.macro z_riscv_get_cpu xreg0, xreg1
#ifdef CONFIG_SMP
csrr xreg0, mhartid
addi xreg1, x0, __cpu_t_SIZEOF
mul xreg1, xreg0, xreg1
la xreg0, _kernel
add xreg0, xreg0, xreg1
#else
la xreg0, _kernel
#endif
.endm
//(変更前)
/* Get reference to _kernel */
la t1, _kernel
/* Decrement _kernel.cpus[0].nested variable */
lw t2, _kernel_offset_to_nested(t1)
addi t2, t2, -1
sw t2, _kernel_offset_to_nested(t1)
//(変更後)
/* Get reference to _kernel.cpus[n] */
z_riscv_get_cpu t1, t2 //★z_riscv_get_cpuに置き換え★
/* Decrement _kernel.cpus[n].nested variable */
lw t2, ___cpu_t_nested_OFFSET(t1) //★_kernel_offset_to_* から ___cpu_t_*_OFFSETに置き換え★
addi t2, t2, -1
sw t2, ___cpu_t_nested_OFFSET(t1)
修正方針は2つあります。
ここまで直すとビルドが通るはずですが、実はビルドが通るだけでは動きません。次回は実行時のエラーを対策します。
この記事にコメントする
目次: Zephyr
新しい形式のコンテキストスイッチを実装しました。以前書いたとおり、SMP対応は下記の手順で進めています。再掲しておきましょう。
やっと最初の項目が終わったところです。いよいよCONFIG_SMPを有効にします。大量のビルドエラーが発生しますので、1つずつやっつけます。
環境や利用するバージョンによりますが、最初に目にするのはarch_curr_cpu() に関するコンパイルエラーだと思われます。
../include/sys/arch_interface.h:367:28: warning: 'arch_curr_cpu' declared 'static' but never defined [-Wunused-function]
static inline struct _cpu *arch_curr_cpu(void);
^~~~~~~~~~~~~
この関数は、現在のCPU(= 実行中のCPU)の情報を返します。RISC-Vにはmhartidという自身のHART IDを取得できるCSR(Control and Status Registers)が規格で定められており、この手の処理は楽に実装できます。
// zephyr/include/arch/riscv/arch_inlines.h
static inline uint32_t z_riscv_hart_id(void)
{
uint32_t hartid;
__asm__ volatile ("csrr %0, mhartid" : "=r"(hartid));
return hartid;
}
static inline struct _cpu *arch_curr_cpu(void)
{
#ifdef CONFIG_SMP
uint32_t hartid = z_riscv_hart_id();
return &_kernel.cpus[hartid];
#else
return &_kernel.cpus[0];
#endif
}
他のアーキテクチャを見る限りarch_inlines.hに定義するのが良さそうですが、RISC-V向けには存在しません。新たに追加しましょう。ヘッダファイルを追加したら、親玉のarch_inlines.hに #includeを追加します。
// zephyr/include/arch/arch_inlines.h
...
#if defined(CONFIG_X86) || defined(CONFIG_X86_64)
#include <arch/x86/arch_inlines.h>
#elif defined(CONFIG_ARC)
#include <arch/arc/arch_inlines.h>
#elif defined(CONFIG_XTENSA)
#include <arch/xtensa/arch_inlines.h>
#elif defined(CONFIG_RISCV) //★この2行を追加する
#include <arch/riscv/arch_inlines.h> //★
#endif
このヘッダは明示的に #includeしなくても常にインクルードされます。
メインCPU以外のCPU(2つ目以降のCPU)を起動するための関数です。SMPモードの他、非SMPモード(※)でも使います。今はCPU 1つで動かすので、とりあえず空関数を定義します。
関数はどこに定義しても動きますが、他アーキテクチャの実装を見るとSMP関連の関数は1つのCソースファイルにまとめた方が良さそうなので、新たにcpu_smp.cを作成します。
// zephyr/arch/riscv/core/CMakeLists.txt
zephyr_library_sources(
cpu_idle.c
cpu_smp.c ★足す★
fatal.c
irq_manage.c
isr.S
prep_c.c
reset.S
swap.S
thread.c
)
// zephyr/arch/riscv/core/cpu_smp.c
void arch_start_cpu(int cpu_num, k_thread_stack_t *stack, int sz,
arch_cpustart_t fn, void *arg)
{
}
ZephyrというかCMakeのルールですけども、新たにソースコードを追加した場合、CMakeLists.txtにファイル名を追加しコンパイル対象に指定する必要があります。特定のCONFIG_* が定義されたときだけコンパイルすることも可能ですが、今回は不要です。
(※)Zephyrのマルチプロセッサモードには、SMPモードと非SMPモードがあります。SMPモードは、互いのプロセッサ間でIPI(Inter-Processor Interrupt)を用いて制御します。非SMPモードでは、互いのプロセッサのことは何も考慮せず動作します。
これはSMP用のタイマーの初期化関数です。タイマーのハードウェア構成はアーキテクチャによって様々で、一様に「こう実装すべき」という指針はありません。今はCPU 1つで動かすので、とりあえず空関数を定義します。
// zephyr/drivers/timer/riscv_machine_timer.c
...
void smp_timer_init(void)
{
}
今回はRISC-VのPrivilege modeのタイマーが実装対象です。タイマードライバはriscv_machine_timer.cになります。
長くなってきたので、続きは次回。
この記事にコメントする
目次: Zephyr
前回はRISC-Vの2つあるコンテキストスイッチのうち、明示的なコンテキストスイッチを実装しました。今回はもう一方のプリエンプションを実装します。
従来と新形式のコンテキストスイッチで大きく異なるのは、下記の要素です。
| 明示的コンテキストスイッチ | 従来 | 新形式 |
|---|---|---|
| 割り込まれた処理の返り値 | 設定必要(thread->arch.swap_return_value) | 設定不要(do_swap() がやってくれる) |
| 切り替え元スレッド | _kernel.cpu[0].current | a1レジスタ(引数old_thread->switch_handle) |
| 切り替え先スレッド | _kernel.ready_q.cache | a0レジスタ(引数new_thread->switch_handle) |
| プリエンプション | 従来 | 新形式 |
|---|---|---|
| 割り込まれた処理の返り値 | 設定必要(thread->arch.swap_return_value) | 設定不要(do_swap() がやってくれる) |
| 切り替え元スレッド | _kernel.cpu[0].current | _kernel.cpu[n].current(※) |
| 切り替え先スレッド | _kernel.ready_q.cache | z_get_next_switch_handle() の返り値 |
(※)初めは切り替え元スレッドですが、z_get_next_switch_handle() を呼ぶと、切り替え先のスレッドに変わります。
明示的プリエンプションと共通の部分のため、改めて直す必要はないです。
かなり処理が変わるため、#ifdefだとごちゃごちゃしてしまいます。スレッド取得の専用マクロを作ります。
// zephyr/arch/riscv/core/isr.S
/*
* xcpu: pointer of _kernel.cpus[n]
* xold: (result) old thread
* xnew: (result) next thread to schedule
*
* after this function a0 is broken
*/
.macro z_riscv_get_next_switch_handle xcpu, xold, xnew
#ifdef CONFIG_USE_SWITCH
addi sp, sp, -RV_REGSIZE*2 //★新たな処理★
RV_OP_STOREREG ra, RV_REGSIZE(sp)
addi a0, sp, 0 //★スタックの先頭へのポインタを第一引数old_threadとする★
jal ra, z_arch_get_next_switch_handle //★(2) この関数内で _currentがnew_threadに設定される★
addi xnew, a0, 0 //★a0が返り値、切り替え先のスレッドが入っている★
RV_OP_LOADREG xold, 0(sp) //★スタック先頭に切り替え元のスレッドが入っている★
RV_OP_LOADREG ra, RV_REGSIZE(sp)
addi sp, sp, RV_REGSIZE*2
#else
/* Get pointer to _kernel.current */ //★従来処理★
RV_OP_LOADREG xold, _kernel_offset_to_current(xcpu) //★切り替え元スレッド★
RV_OP_LOADREG xnew, _kernel_offset_to_ready_q_cache(xcpu) //★切り替え先スレッド★
#endif
.endm
// zephyr/arch/riscv/core/thread.c
#ifdef CONFIG_USE_SWITCH
void *z_arch_get_next_switch_handle(struct k_thread **old_thread)
{
*old_thread = _current; //★スタックの先頭に現在のスレッド(= 切り替え元のスレッド)を保存★
return z_get_next_switch_handle(*old_thread);
}
#endif
わざわざスタックのポインタを経由して書き込むなんてややこしいことをせず、RV_OP_LOADREG xold, _kernel_offset_to_current(xcpu) で良いのでは?と思うかもしれませんが、z_arch_get_next_switch_handle() の呼び出しでどのレジスタが壊れるかわかりませんから、結局 xoldをスタックに退避する必要があります。
明示的コンテキストスイッチと処理を共有しているため、ちょっとわかりにくいですが、プリエンプションの中心となる処理はこの辺りです。
// zephyr/arch/riscv/core/isr.S
#ifdef CONFIG_PREEMPT_ENABLED
- /*
- * Check if we need to perform a reschedule
- */
-
- /* Get pointer to _kernel.current */
- RV_OP_LOADREG t2, _kernel_offset_to_current(t1)
-
/*
* Check if next thread to schedule is current thread.
* If yes do not perform a reschedule
*/
- RV_OP_LOADREG t3, _kernel_offset_to_ready_q_cache(t1)
+ z_riscv_get_next_switch_handle t1, t2, t3
beq t3, t2, no_reschedule
+
+#ifdef CONFIG_USE_SWITCH
+ /* Set old thread to t1 */
+ addi t1, t2, 0 //★(1) t1レジスタにold_threadを設定する★
+#endif
+
前回決めたとおり、合流地点(reschedule)に辿り着く前に切り替え元(old_thread)、切り替え先スレッド(new_thread)を取得し _currentにnew_threadを設定し, t1レジスタにold_threadを設定します。
処理 (1) でnew_threadを _currentに設定していて、処理 (2) でold_threadをt1レジスタに設定してから、rescheduleに到達します。プリエンプション処理のすぐ後にrescheduleラベルがあるので、ジャンプは不要です。
とても長くなってしまいましたが、新しい形式のコンテキストスイッチを実装できました。苦労の割に動作の見た目は何も変わりませんが、本命のSMP対応に活用するためなので我慢です。
この記事にコメントする
目次: Zephyr
前回はRISC-Vの明示的なコンテキストスイッチの既存実装を調べました。今回は新しいコンテキストスイッチを実装します。
従来と新形式のコンテキストスイッチで大きく異なるのは、下記の要素です。
| 明示的コンテキストスイッチ | 従来 | 新形式 |
|---|---|---|
| 割り込まれた処理の返り値 | 設定必要(thread->arch.swap_return_value) | 設定不要(do_swap() がやってくれる) |
| 切り替え元スレッド | _kernel.cpu[0].current | a1レジスタ(引数old_thread->switch_handle) |
| 切り替え先スレッド | _kernel.ready_q.cache | a0レジスタ(引数new_thread->switch_handle) |
| プリエンプション | 従来 | 新形式 |
|---|---|---|
| 割り込まれた処理の返り値 | 設定必要(thread->arch.swap_return_value) | 設定不要(do_swap() がやってくれる) |
| 切り替え元スレッド | _kernel.cpu[0].current | _kernel.cpu[n].current(※) |
| 切り替え先スレッド | _kernel.ready_q.cache | z_get_next_switch_handle() の返り値 |
(※)初めは切り替え元スレッドですが、z_get_next_switch_handle() を呼ぶと、切り替え先のスレッドに変わります。
割り込まれた処理の返り値を -EINTRに設定するために必要な処理は、do_swap() がやるため実装は必要ありません。従来の処理が間違って発動しないように #ifdefで消しておきます。
// zephyr/arch/riscv/core/isr.Sの差分
+ /* Save stack pointer of current thread. */
+ RV_OP_STOREREG sp, _thread_offset_to_sp(t1) //★スタックポインタ保存は新しい形式でも必要★
+
+#ifndef CONFIG_USE_SWITCH
/*
- * Save stack pointer of current thread and set the default return value
- * of z_swap to _k_neg_eagain for the thread.
+ * Set the default return value of z_swap to _k_neg_eagain for
+ * the thread.
*/
- RV_OP_STOREREG sp, _thread_offset_to_sp(t1)
la t2, _k_neg_eagain
lw t3, 0x00(t2)
sw t3, _thread_offset_to_swap_return_value(t1) //★返り値設定は不要★
+#endif /* !CONFIG_USE_SWITCH */
// zephyr/arch/riscv/core/offsets/offsets.c
//★_thread_offset_to_swap_return_value() マクロを使えるようにする仕掛け★
#ifndef CONFIG_USE_SWITCH
GEN_OFFSET_SYM(_thread_arch_t, swap_return_value); //★いらない★
#endif /* !CONFIG_USE_SWITCH */
// zephyr/include/arch/riscv/thread.h
struct _thread_arch {
#ifndef CONFIG_USE_SWITCH
uint32_t swap_return_value; /* Return value of z_swap() */ //★いらない★
#endif /* !CONFIG_USE_SWITCH */
};
処理を消すだけでも動きますが、swap_return_valueを間違って使うとバグの元なので、変数宣言ごと消します。
従来は常に _kernel変数を見れば良かったので楽でした。新形式では明示的コンテキストスイッチとプリエンプションで切り替え元/切り替え先スレッドの取得方法が異なります。よって、明示的コンテキストスイッチとプリエンプションで、スレッドの扱いを揃える必要があります。
設計する人の自由で決めて構いませんが、今回は合流地点(reschedule)に辿り着く前に切り替え元(old_thread)、切り替え先スレッド(new_thread)を取得し _currentにnew_threadを設定し, t1レジスタにold_threadを設定することとします。
明示的コンテキストスイッチの場合、切り替え元と切り替え先スレッドは引数で渡されます。引数はハンドラの先頭でスタックに保存されますので、スタックからロードできます。
// zephyr/arc/riscv/core/isr.S
#ifdef CONFIG_USE_SWITCH
/*
* Get new_thread and old_thread from stack.
* - a0 = new_thread->switch_handle -> _current
* - a1 = &old_thread->switch_handle -> t1
*/
/* Get reference to _kernel */
la t2, _kernel
/* Get new_thread from stack */
RV_OP_LOADREG t1, __z_arch_esf_t_a0_OFFSET(sp) //★スタックから切り替え先スレッド取得★
/* Set new thread to _current */
RV_OP_STOREREG t1, ___cpu_t_current_OFFSET(t2) //★(2) この関数内でnew_threadを _currentに設定★
/* Get old_thread from stack and set it to t1 */
RV_OP_LOADREG t1, __z_arch_esf_t_a1_OFFSET(sp) //★(1)スタックから切り替え元スレッド取得、t1レジスタにold_threadを設定★
addi t1, t1, -___thread_t_switch_handle_OFFSET //★(A) old_thread->switch_handleの更新★
#endif
/*
* Go to reschedule to handle context-switch
*/
j reschedule
// zephyr/arch/riscv/core/thread.c
void arch_new_thread(struct k_thread *thread, k_thread_stack_t *stack,
char *stack_ptr, k_thread_entry_t entry,
void *p1, void *p2, void *p3)
{
struct __esf *stack_init;
...
#ifdef CONFIG_USE_SWITCH
thread->switch_handle = thread; //★(B) switch_handleの初期値設定★
#endif
}
処理 (1) でnew_threadを _currentに設定していて、処理 (2) でold_threadをt1レジスタに設定してから、rescheduleにジャンプします。
スレッドと直接関係ないもののold_thread->switch_handleを更新する処理も重要です。あとでハマりやすいポイントですので、補足しておきます。
以前、少し言及しましたが(2020年9月30日の日記参照)、switch_handleの更新を実装し忘れるとCONFIG_SMPを有効にしたときにwait_for_switch() で無限ループに陥ってハマります。
Zephyrのドキュメントにてarch_switch() を見ると(Zephyr Project: arch_switch)、スレッドにレジスタを退避後、old_thread->switch_handleをNULL以外の値で書き換える必要があります。これはコンテキストスイッチ処理内で行う (A) の処理に相当します。
実はこれだけではダメです。wait_for_switch() はコンテキストスイッチの「前」に呼ばれるからです。一番最初に発生するコンテキストスイッチのold_thread->switch_handleは誰も書き換えてくれないのでハングします。この問題の対処としてスレッド生成時にswitch_handleを初期化する (B) の処理を実装しています。
次回はプリエンプションの実装をします。
この記事にコメントする
目次: Zephyr
前回は、AArch64の実装を調べました。いよいよ新しい方式のコンテキストスイッチを実装したいところですが、その前にもう一つだけRISC-Vの既存実装を調べます。
RISC-V向け実装において、コンテキストスイッチが行われる条件は2つあります。1つはスリープしたときなどに呼ばれる明示的なコンテキストスイッチです。do_swap() を経由します。もう1つは割り込み発生時に行われるプリエンプションです。
明示的コンテキストスイッチについては、以前(2020年9月29日の日記参照)実装したラッパー関数がスタート地点となります。コードを変更する前に、従来のコンテキストスイッチがどんな経路を通るか確認します。
// zephyr/arch/riscv/include/kernel_arch_func.h
static inline void arch_switch(void *switch_to, void **switched_from)
{
z_riscv_switch(switch_to, switched_from);
}
// zephyr/arch/riscv/core/swap.S
/*
* void z_riscv_switch(void *switch_to, void **switched_from)
*/
SECTION_FUNC(exception.other, z_riscv_switch)
/* Make a system call to perform context switch */
ecall //★例外を発生させる★
jalr x0, ra
// zephyr/arch/riscv/core/isr.S
/*
* Handler called upon each exception/interrupt/fault
* In this architecture, system call (ECALL) is used to perform context
* switching or IRQ offloading (when enabled).
*/
SECTION_FUNC(exception.entry, __irq_wrapper)
/* Allocate space on thread stack to save registers */
addi sp, sp, -__z_arch_esf_t_SIZEOF
...
/*
* Check if exception is the result of an interrupt or not.
* (SOC dependent). Following the RISC-V architecture spec, the MSB
* of the mcause register is used to indicate whether an exception
* is the result of an interrupt or an exception/fault. But for some
* SOCs (like pulpino or riscv-qemu), the MSB is never set to indicate
* interrupt. Hence, check for interrupt/exception via the __soc_is_irq
* function (that needs to be implemented by each SOC). The result is
* returned via register a0 (1: interrupt, 0 exception)
*/
jal ra, __soc_is_irq
/* If a0 != 0, jump to is_interrupt */
addi t1, x0, 0
bnez a0, is_interrupt //★割り込みの場合はこちらにジャンプする★
/*
* If the exception is the result of an ECALL, check whether to
* perform a context-switch or an IRQ offload. Otherwise call _Fault
* to report the exception.
*/
csrr t0, mcause
li t2, SOC_MCAUSE_EXP_MASK
and t0, t0, t2
li t1, SOC_MCAUSE_ECALL_EXP
/*
* If mcause == SOC_MCAUSE_ECALL_EXP, handle system call,
* otherwise handle fault
*/
beq t0, t1, is_syscall //★ecallの場合はこちらにジャンプする★
/*
* Call _Fault to handle exception.
* Stack pointer is pointing to a z_arch_esf_t structure, pass it
* to _Fault (via register a0).
* If _Fault shall return, set return address to no_reschedule
* to restore stack.
*/
addi a0, sp, 0
la ra, no_reschedule
tail _Fault //★いずれでもなければ停止させる★
...
Zephyr RISC-V向け実装では、割り込み・例外ハンドラは1つだけです。割り込みも例外も全て __irq_wrapperに飛んできますから、最初の方で要因をチェックして仕分けしています。RISC-Vの規格としては割り込み要因ごとに別の割り込みハンドラに飛べる形式(ベクタ形式)もありますが、Zephyrは使っていません。
// zephyr/arch/riscv/core/isr.S
is_syscall:
/*
* A syscall is the result of an ecall instruction, in which case the
* MEPC will contain the address of the ecall instruction.
* Increment saved MEPC by 4 to prevent triggering the same ecall
* again upon exiting the ISR.
*
* It's safe to always increment by 4, even with compressed
* instructions, because the ecall instruction is always 4 bytes.
*/
RV_OP_LOADREG t0, __z_arch_esf_t_mepc_OFFSET(sp)
addi t0, t0, 4
RV_OP_STOREREG t0, __z_arch_esf_t_mepc_OFFSET(sp)
...
/*
* Go to reschedule to handle context-switch
*/
j reschedule //★コンテキストスイッチ★
...
reschedule:
...
/* Get reference to _kernel */
la t0, _kernel
/* Get pointer to _kernel.current */
RV_OP_LOADREG t1, _kernel_offset_to_current(t0)
/*
* Save callee-saved registers of current thread
* prior to handle context-switching
*/
RV_OP_STOREREG s0, _thread_offset_to_s0(t1)
RV_OP_STOREREG s1, _thread_offset_to_s1(t1)
...
RV_OP_STOREREG s10, _thread_offset_to_s10(t1)
RV_OP_STOREREG s11, _thread_offset_to_s11(t1)
...
/*
* Save stack pointer of current thread and set the default return value
* of z_swap to _k_neg_eagain for the thread.
*/
RV_OP_STOREREG sp, _thread_offset_to_sp(t1)
la t2, _k_neg_eagain
lw t3, 0x00(t2)
sw t3, _thread_offset_to_swap_return_value(t1)
/* Get next thread to schedule. */
RV_OP_LOADREG t1, _kernel_offset_to_ready_q_cache(t0)
/*
* Set _kernel.current to new thread loaded in t1
*/
RV_OP_STOREREG t1, _kernel_offset_to_current(t0)
/* Switch to new thread stack */
RV_OP_LOADREG sp, _thread_offset_to_sp(t1)
/* Restore callee-saved registers of new thread */
RV_OP_LOADREG s0, _thread_offset_to_s0(t1)
RV_OP_LOADREG s1, _thread_offset_to_s1(t1)
...
RV_OP_LOADREG s10, _thread_offset_to_s10(t1)
RV_OP_LOADREG s11, _thread_offset_to_s11(t1)
...
no_reschedule:
...
/* Restore MEPC register */
RV_OP_LOADREG t0, __z_arch_esf_t_mepc_OFFSET(sp)
csrw mepc, t0
/* Restore SOC-specific MSTATUS register */
RV_OP_LOADREG t0, __z_arch_esf_t_mstatus_OFFSET(sp)
csrw mstatus, t0
...
/* Restore caller-saved registers from thread stack */
RV_OP_LOADREG ra, __z_arch_esf_t_ra_OFFSET(sp)
RV_OP_LOADREG gp, __z_arch_esf_t_gp_OFFSET(sp)
RV_OP_LOADREG tp, __z_arch_esf_t_tp_OFFSET(sp)
RV_OP_LOADREG t0, __z_arch_esf_t_t0_OFFSET(sp)
...
RV_OP_LOADREG a6, __z_arch_esf_t_a6_OFFSET(sp)
RV_OP_LOADREG a7, __z_arch_esf_t_a7_OFFSET(sp)
/* Release stack space */
addi sp, sp, __z_arch_esf_t_SIZEOF
/* Call SOC_ERET to exit ISR */
SOC_ERET
コメントが丁寧に書いてあって素晴らしいですね。コンテキストスイッチの手順はAArch64の実装とほぼ同じですが、AAarch64は明示的なコンテキストスイッチとプリエンプションが独立して実装されており、RISC-Vはrescheduleで両者が合流する点が違います。コンテキストスイッチの説明は先日(2020年10月1日の日記参照)の紙芝居が参考になるかと思います。
明示的なコンテキストスイッチとプリエンプションの部分が大体仕分けできました。いよいよ実装に挑みます。続きはまた。
この記事にコメントする
目次: Zephyr
前回は、新しいコンテキストスイッチ関数に対応しているAArch64の実装のうち、共通部分からアーキテクチャ依存部分に至るまでを調べました。引き続きアーキテクチャ依存部分を調べます。
コンテキストスイッチのアーキテクチャ依存部分(AArch64向けarch_switch())の実装はほぼ全てアセンブラで実装されています。
コンテキストスイッチの本体はz_arm64_context_switchです。x0がnew_thread, x1がold_threadだと思って動きます。コンテキストスイッチの仕事はレジスタの値を切り替え前のスレッド構造体(old_thread)に退避し、切り替え後のスレッド構造体(new_thread)からレジスタの値を復旧させることです。
// zephyr/arch/arm/core/aarch64/switch.S
GTEXT(z_arm64_svc)
SECTION_FUNC(TEXT, z_arm64_svc)
z_arm64_enter_exc x2, x3, x4 /* ★レジスタをスタックに退避(切り替え前のスレッド)★ */
switch_el x1, 3f, 2f, 1f
3:
mrs x0, esr_el3
b 0f
2:
mrs x0, esr_el2
b 0f
1:
mrs x0, esr_el1
0:
lsr x1, x0, #26
cmp x1, #0x15 /* 0x15 = SVC */
bne inv
/* Demux the SVC call */
and x1, x0, #0xff
cmp x1, #_SVC_CALL_CONTEXT_SWITCH
beq context_switch /* ★以下参照★ */
...
context_switch:
/*
* Retrieve x0 and x1 from the stack:
* - x0 = new_thread->switch_handle = switch_to thread
* - x1 = x1 = &old_thread->switch_handle = current thread
*/
ldp x0, x1, [sp, #(16 * 10)] /* ★x1 = 切り替え前、x0 = 切り替え後のスレッド★ */
/* Get old thread from x1 */
sub x1, x1, ___thread_t_switch_handle_OFFSET
/* Switch thread */
bl z_arm64_context_switch /* ★コンテキストスイッチ本体(スタックが切り替わる)★ */
exit:
z_arm64_exit_exc x0, x1, x2 /* ★レジスタをスタックから復旧(切り替え後のスレッド)★ */
...
/**
* @brief Routine to handle context switches
*
* This function is directly called either by _isr_wrapper() in case of
* preemption, or z_arm64_svc() in case of cooperative switching.
*/
GTEXT(z_arm64_context_switch)
SECTION_FUNC(TEXT, z_arm64_context_switch)
/* addr of callee-saved regs in thread in x2 */
ldr x2, =_thread_offset_to_callee_saved
add x2, x2, x1
/* Store rest of process context including x30 */
stp x19, x20, [x2], #16
stp x21, x22, [x2], #16
stp x23, x24, [x2], #16
stp x25, x26, [x2], #16
stp x27, x28, [x2], #16
stp x29, x30, [x2], #16
/* Save the current SP */
mov x1, sp
str x1, [x2]
/* addr of callee-saved regs in thread in x2 */
ldr x2, =_thread_offset_to_callee_saved
add x2, x2, x0
/* Restore x19-x29 plus x30 */
ldp x19, x20, [x2], #16
ldp x21, x22, [x2], #16
ldp x23, x24, [x2], #16
ldp x25, x26, [x2], #16
ldp x27, x28, [x2], #16
ldp x29, x30, [x2], #16
ldr x1, [x2]
mov sp, x1 /* ★ここで切り替え後のスレッドのスタックに変わる★ */
#ifdef CONFIG_TRACING
stp xzr, x30, [sp, #-16]!
bl sys_trace_thread_switched_in
ldp xzr, x30, [sp], #16
#endif
/* We restored x30 from the process stack. There are three possible
* cases:
*
* - We return to z_arm64_svc() when swapping in a thread that was
* swapped out by z_arm64_svc() before jumping into
* z_arm64_exit_exc()
* - We return to _isr_wrapper() when swapping in a thread that was
* swapped out by _isr_wrapper() before jumping into
* z_arm64_exit_exc()
* - We return (jump) into z_thread_entry_wrapper() for new threads
* (see thread.c)
*/
ret
// zephyr/include/arm/aarch64/thread.h
struct _callee_saved {
uint64_t x19;
uint64_t x20;
uint64_t x21;
uint64_t x22;
uint64_t x23;
uint64_t x24;
uint64_t x25;
uint64_t x26;
uint64_t x27;
uint64_t x28;
uint64_t x29; /* FP */
uint64_t x30; /* LR */
uint64_t sp;
};
コードを見て一発で理解するのは厳しいので、処理の概要を書いておきます。
コンテキストスイッチの際にスタックが切り替わります。z_arm64_exit_exc x0, x1, x2はシステムコールを呼んだスレッド(=切り替え前のスレッド)ではなく、コンテキストスイッチ後のスレッドのスタックからレジスタを復旧します。
これも文章だと何だかわからないので、紙芝居を書いておきます。

Zephyr AArch64のコンテキストスイッチ: 例外ハンドラ先頭

Zephyr AArch64のコンテキストスイッチ: 例外ハンドラ入り口、スタックへレジスタ退避

Zephyr AArch64のコンテキストスイッチ: コンテキストスイッチ前半、切り替え前スレッド構造体へレジスタ退避

Zephyr AArch64のコンテキストスイッチ: コンテキストスイッチ前半、切り替え前スレッド構造体へスタックポインタ退避

Zephyr AArch64のコンテキストスイッチ: コンテキストスイッチ後半、切り替え後スレッド構造体からレジスタ復旧

Zephyr AArch64のコンテキストスイッチ: コンテキストスイッチ後半、切り替え後スレッド構造体からスタックポインタ復旧(=スタック切り替え)

Zephyr AArch64のコンテキストスイッチ: 例外ハンドラ入り口、切り替え後のスタックからレジスタ復旧
図には書きませんでしたが、例外からリターンする命令(eret命令)が参照するレジスタ(SPSR, ELRレジスタ)もスタックに退避、復旧しています。従ってeretが戻る先は切り替え後のスレッドのコードです。
この記事にコメントする
目次: Zephyr
前回は、新しい形式のコンテキストスイッチ関数arch_switch() のラッパー関数まで実装しました。RISC-V向け実装をする前に、既に新しいコンテキストスイッチ関数に対応しているAArch64の実装を調べます。
コンテキストスイッチ処理の共通部分(do_swap())から、アーキテクチャ依存部分(AArch64のarch_switch())に至るまでを見ます。
// zephyr/kernel/include/kswap.h
/* New style context switching. arch_switch() is a lower level
* primitive that doesn't know about the scheduler or return value.
* Needed for SMP, where the scheduler requires spinlocking that we
* don't want to have to do in per-architecture assembly.
*
* Note that is_spinlock is a compile-time construct which will be
* optimized out when this function is expanded.
*/
static ALWAYS_INLINE unsigned int do_swap(unsigned int key,
struct k_spinlock *lock,
int is_spinlock)
{
...
if (new_thread != old_thread) {
#ifdef CONFIG_TIMESLICING
z_reset_time_slice();
#endif
old_thread->swap_retval = -EAGAIN;
#ifdef CONFIG_SMP
_current_cpu->swap_ok = 0;
new_thread->base.cpu = arch_curr_cpu()->id;
if (!is_spinlock) {
z_smp_release_global_lock(new_thread);
}
#endif
sys_trace_thread_switched_out();
_current_cpu->current = new_thread;
wait_for_switch(new_thread);
arch_switch(new_thread->switch_handle,
&old_thread->switch_handle); //★コンテキストスイッチ★
}
...
前々回に紹介した新しいコンテキストスイッチの方式(arch_switch())を使っていることがわかります。
// zephyr/arch/arm/include/aarch64/arch_func.h
static inline void arch_switch(void *switch_to, void **switched_from)
{
z_arm64_call_svc(switch_to, switched_from); //★アセンブラ実装へ★
return;
}
// zephyr/arch/arm/core/aarch64/switch.S
GTEXT(z_arm64_call_svc)
SECTION_FUNC(TEXT, z_arm64_call_svc)
svc #_SVC_CALL_CONTEXT_SWITCH //★スーパーバイザーコール命令★
ret
アセンブラ側の実装では、いきなりスーパーバイザーコール命令(svc命令)をぶっ放して、スーパーバイザーコール例外を起こすだけになっています。AArch64は例外ハンドラ内でコンテキストスイッチを行う仕組みのようです。
関数arch_switch() はスレッドを2つ受け取ります。old_threadは切り替え元のスレッド、new_threadは切り替え先のスレッドです。old_thread -> new_threadにコンテキストスイッチするわけです。ただし直接スレッド構造体を受け取るわけではなく、若干クセのある渡し方をします。
第1引数new_thread->switch_handle(void * 型)は切り替え先のスレッド構造体へのポインタ(struct k_thread * 型)new_threadが入っています。このポインタをキャストするとnew_threadが求められます。
実はここには罠があり、何も実装せずにいるとnew_thread->switch_handleにはNULLが入ります。すると、あとでCONFIG_SMPを有効にした段階でwait_for_switch() 関数にてハングアップします。こんなのパッと見ではわかりません……。
// zephyr/kernel/include/kswap.h
/* New style context switching. arch_switch() is a lower level
* primitive that doesn't know about the scheduler or return value.
* Needed for SMP, where the scheduler requires spinlocking that we
* don't want to have to do in per-architecture assembly.
*
* Note that is_spinlock is a compile-time construct which will be
* optimized out when this function is expanded.
*/
static ALWAYS_INLINE unsigned int do_swap(unsigned int key,
struct k_spinlock *lock,
int is_spinlock)
{
...
if (new_thread != old_thread) {
...
sys_trace_thread_switched_out();
_current_cpu->current = new_thread;
wait_for_switch(new_thread); //★これ★
arch_switch(new_thread->switch_handle,
&old_thread->switch_handle);
}
if (is_spinlock) {
arch_irq_unlock(key);
} else {
irq_unlock(key);
}
return _current->swap_retval;
}
/* There is an unavoidable SMP race when threads swap -- their thread
* record is in the queue (and visible to other CPUs) before
* arch_switch() finishes saving state. We must spin for the switch
* handle before entering a new thread. See docs on arch_switch().
*
* Note: future SMP architectures may need a fence/barrier or cache
* invalidation here. Current ones don't, and sadly Zephyr doesn't
* have a framework for that yet.
*/
static inline void wait_for_switch(struct k_thread *thread)
{
#ifdef CONFIG_SMP
volatile void **shp = (void *)&thread->switch_handle;
while (*shp == NULL) { //★CONFIG_SMP有効でnew_thread->switch_handleがNULLだとこのループでハング★
k_busy_wait(1);
}
#endif
}
AArch64向けのスレッド作成する関数を良く見ると、しれっとswitch_handleを初期化しています。この処理はRISC-V向けには存在しないため、追加する必要がありそうです。
// zephyr/arch/arm/core/aarch64/thread.c
/*
* An initial context, to be "restored" by z_arm64_context_switch(), is put at
* the other end of the stack, and thus reusable by the stack when not needed
* anymore.
*/
void arch_new_thread(struct k_thread *thread, k_thread_stack_t *stack,
char *stack_ptr, k_thread_entry_t entry,
void *p1, void *p2, void *p3)
{
...
/*
* We are saving:
*
* - SP: to pop out entry and parameters when going through
* z_thread_entry_wrapper().
* - x30: to be used by ret in z_arm64_context_switch() when the new
* task is first scheduled.
*/
thread->callee_saved.sp = (uint64_t)pInitCtx;
thread->callee_saved.x30 = (uint64_t)z_thread_entry_wrapper;
thread->switch_handle = thread; //★ここで初期化している★
}
関数arch_switch() の第2引数 &old_thread->switch_handle(void ** 型)は切り替え元のスレッド構造体のswitch_handleのポインタです。switch_handleの値(たいていNULL)自体には意味がなくて、このポインタからold_threadが計算できることが大事です。
長くなってきたので続きは次回。
この記事にコメントする
| < | 2020 | > | ||||
| << | < | 10 | > | >> | ||
| 日 | 月 | 火 | 水 | 木 | 金 | 土 |
| - | - | - | - | 1 | 2 | 3 |
| 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| 11 | 12 | 13 | 14 | 15 | 16 | 17 |
| 18 | 19 | 20 | 21 | 22 | 23 | 24 |
| 25 | 26 | 27 | 28 | 29 | 30 | 31 |
25年10月15日
25年10月18日
22年5月5日
25年10月19日
23年4月11日
06年4月22日
25年10月17日
25年10月6日
25年10月13日
20年10月23日
25年10月12日
20年8月29日
19年1月13日
18年10月13日
18年9月3日
18年8月20日
18年7月23日
18年7月22日
18年10月14日
18年11月10日
wiki
Linux JM
Java API
2002年
2003年
2004年
2005年
2006年
2007年
2008年
2009年
2010年
2011年
2012年
2013年
2014年
2015年
2016年
2017年
2018年
2019年
2020年
2021年
2022年
2023年
2024年
2025年
過去日記について
アクセス統計
サーバ一覧
サイトの情報合計:
本日: