Files
unkernel/kernel/patches/linux/0037-wasm-SMP.patch
Pooya Parsa 951bb8e5dd kernel: let kwsnd periods go down to 2 ms, in a buffer of 10 ms or more (#22)
The shortest period and tick drop from 5 ms to 2 ms for programs that
ask for low latency. A buffer is 10 ms or more as before (two 5 ms
periods), and a late tick still hands over up to 15 ms' worth when ticks
are shorter than 5 ms, so a short period tolerates the same host stall.
Programs that leave the period to alsa-lib, plain aplay, OSS without
SETFRAGMENT and requests of 256 frames or more negotiate what they did;
snd_pcm_set_params() with a latency under 20 ms now gets four periods of
2.5 to 3.75 ms (measured on Node, 2026-11-24).

Co-authored-by: Adam Meghji <566793+adammeghji@users.noreply.github.com>
2026-11-24 16:25:03 +00:00

2468 lines
80 KiB
Diff

From f44accde67e0ded2323f21b81091e5e17d0db80b Mon Sep 17 00:00:00 2001
From: kernel-wasm <kernel-wasm@localhost>
Date: Mon, 16 Nov 2026 16:07:10 +0000
Subject: [PATCH] wasm: SMP
A second build of the same arch (kw_smp.config: CONFIG_SMP, NR_CPUS
16), which always links with a shared memory. Each CPU is an instance
of the kernel module in its own host thread on that memory; current,
__stack_pointer, the interrupt flag (kw_irq_flags) and the address of
the CPU's word of pending interrupts (kw_irq_word) are wasm globals of
the instance. The host offers wasm_cpu_count() CPUs, and __cpu_up()
asks it to start one with wasm_cpu_start(): the new instance enters at
kw_secondary_entry with its idle task. The word that guards the data
segments of a shared memory (__wasm_init_memory_flag, past _end) is
memblock-reserved at the address the host reads from the module
(wasm_init_flag()), so later instances skip the initialisation.
A task's stack lives in the thread that started it, so the task is
held on that CPU (ARCH_TASKS_STAY_ON_CPU) from its first run, except
where nothing on the stack is needed again: a user task at the
reschedule on its way to user mode (its state is all in pt_regs), a
kthread at a restart point. Switched in on another CPU it starts there
on a fresh stack (a user task runs the exit to user mode again, a
kthread its restart function), and the CPU that holds the old stack
tells its host to drop it (wasm_stack_drop()) at its next switch or
idle; switched in on its own CPU it resumes its stack. An affinity
change that excludes a held user task's CPU sets TIF_KW_MOVE, so the
task moves on its way to user mode (at once from user mode: the
change kicks it). So does a better CPU the scheduler names for a held
user task (arch_stay_move_to(): exec, a wakeup on its busy CPU), which
the task takes on its way to user mode only if that CPU is idle then
and its own CPU has other work. /proc/kwmove counts the moves.
copy_thread() drops the hold a fork copied.
IPIs are bits in the target's word (CPU 0's is wasm_host_irqs, where
the host's device bits arrive), set atomically and followed by
memory.atomic.notify. A CPU takes them at user slice ends, in idle
(secondaries block in memory.atomic.wait32 with the timer's timeout;
CPU 0 in the host's poll_oneoff), and, on SMP only, when interrupts
are enabled and in cpu_relax(), so a CPU spinning on a lock answers
the holder's TLB shootdown. A CPU spinning with interrupts off still
takes the stop IPI, which a panic sends and which a CPU's host raises
on CPU 0 when the session ends there. The timer is a per-CPU
clockevent on a percpu-devid IRQ 0.
TLB flushes reach the other CPUs in mm_cpumask (kept by switch_mm())
by IPI and wait for them, except a CPU in lazy TLB mode (idle or a
kthread, with the mm still loaded), which is marked stale and flushes
when it switches back to that mm; a PTE that only gained access is
flushed on this CPU alone, since kwemu caches only translations that
allowed the access. riscv_flush_icache flushes every CPU. The software
A/D update is a cmpxchg, so every read-modify-write of a present PTE
is atomic (but for the clear in the teardown of a whole mm, which no
CPU uses any more), and the uaccess walk and copy have no poll point
between them, so pages freed after a shootdown are never copied
into. kwemu gets its own state per CPU (8 MiB from memblock
for the secondaries), the WASI clock and write buffers are per CPU,
and every CPU yields to its own host every 20 ms of user code: CPU 0's
serves the devices, the others' event loops run the engine's
housekeeping (collecting the modules kwemu's JIT freed on that CPU).
Parking (KW_PARK) is off.
kw_emu.h follows kwemu's ABI 7 (several harts on one memory).
---
arch/wasm/Kconfig | 25 +-
arch/wasm/Makefile | 5 +
arch/wasm/configs/kw_smp.config | 4 +
arch/wasm/include/asm/entry-common.h | 27 +++
arch/wasm/include/asm/futex.h | 26 +-
arch/wasm/include/asm/hwcap.h | 2 +
arch/wasm/include/asm/irq.h | 22 ++
arch/wasm/include/asm/irqflags.h | 71 +++++-
arch/wasm/include/asm/kw_emu.h | 11 +-
arch/wasm/include/asm/kwcpu.h | 23 ++
arch/wasm/include/asm/mmu_context.h | 5 +
arch/wasm/include/asm/park.h | 17 ++
arch/wasm/include/asm/pgtable.h | 70 ++++++
arch/wasm/include/asm/processor.h | 29 +++
arch/wasm/include/asm/smp.h | 34 +++
arch/wasm/include/asm/thread_info.h | 3 +
arch/wasm/include/asm/time.h | 10 +
arch/wasm/include/asm/tlbflush.h | 7 +-
arch/wasm/include/asm/wasm.h | 30 +++
arch/wasm/kernel/Makefile | 3 +-
arch/wasm/kernel/cpu.c | 7 +
arch/wasm/kernel/entry.S | 42 ++++
arch/wasm/kernel/head.S | 9 +
arch/wasm/kernel/irq.c | 119 +++++++++-
arch/wasm/kernel/irqflags.c | 4 +-
arch/wasm/kernel/park.c | 3 +-
arch/wasm/kernel/process.c | 340 ++++++++++++++++++++++++++-
arch/wasm/kernel/setup.c | 14 ++
arch/wasm/kernel/signal.c | 3 +-
arch/wasm/kernel/smp.c | 174 ++++++++++++++
arch/wasm/kernel/sys_riscv.c | 6 +-
arch/wasm/kernel/time.c | 54 ++++-
arch/wasm/kernel/traps.c | 26 +-
arch/wasm/kernel/wasi.c | 41 +++-
arch/wasm/mm/fault.c | 60 +++--
arch/wasm/mm/tlb.c | 236 ++++++++++++++++++-
36 files changed, 1490 insertions(+), 72 deletions(-)
create mode 100644 arch/wasm/configs/kw_smp.config
create mode 100644 arch/wasm/include/asm/kwcpu.h
create mode 100644 arch/wasm/include/asm/smp.h
create mode 100644 arch/wasm/kernel/smp.c
diff --git a/arch/wasm/Kconfig b/arch/wasm/Kconfig
index 1ed6743adce..e8846e18f69 100644
--- a/arch/wasm/Kconfig
+++ b/arch/wasm/Kconfig
@@ -36,6 +36,9 @@ config WASM
select VMALLOC_FLAT
select HAVE_ARCH_MMAP_RND_BITS
select LOCK_MM_AND_FIND_VMA
+ select GENERIC_SMP_IDLE_THREAD if SMP
+ select ARCH_USE_QUEUED_RWLOCKS if SMP
+ select ARCH_TASKS_STAY_ON_CPU if SMP
# riscv64 ELF userspace runs on the kwemu software CPU with real page tables
# (fork, mmap, copy-on-write). The original linux-wasm NOMMU mode (programs
@@ -43,12 +46,28 @@ config WASM
config MMU
def_bool y
+# One instance of the kernel module per CPU, each on its own host thread
+# (a worker), all on one shared memory (KW_SHARED_MEMORY in the arch
+# Makefile). A task's wasm stack lives in the thread that started it, so
+# a task stays on that CPU (ARCH_TASKS_STAY_ON_CPU) except where it can
+# start again on a fresh stack: a user task on its way to user mode, a
+# kthread at a restart point. Interrupts and IPIs are bits in a word per CPU,
+# polled at user slice ends, in idle, when interrupts are enabled and in
+# cpu_relax(). Host devices stay on CPU 0.
config SMP
- bool
+ bool "Symmetric multi-processing (experimental)"
+ help
+ Build a kernel that runs on as many CPUs as the host offers
+ (wasm_cpu_count(), at most NR_CPUS). Needs a host that starts one
+ worker per CPU and kwemu built with atomics
+ (zig build -Dkwemu-atomics=true). Parking and snapshots
+ (KW_PARK) are not available on SMP.
# Parking every task on demand (arch/wasm/kernel/park.c, linux/kw_park.h).
+# It assumes one CPU (kernel.md, Parking).
config KW_PARK
def_bool y
+ depends on !SMP
config 64BIT
def_bool y
@@ -58,7 +77,9 @@ config HZ
default 100
config NR_CPUS
- int
+ int "Maximum number of CPUs (2-32)" if SMP
+ range 2 32 if SMP
+ default 16 if SMP
default 1
config GENERIC_CSUM
diff --git a/arch/wasm/Makefile b/arch/wasm/Makefile
index 34e941e06b6..49049055794 100644
--- a/arch/wasm/Makefile
+++ b/arch/wasm/Makefile
@@ -10,6 +10,11 @@ KCFLAGS += -march=wasm64
KAFLAGS += -march=wasm64
KBUILD_LDFLAGS += -mwasm64
+# An SMP kernel (CONFIG_SMP) always links against a shared memory.
+ifeq ($(CONFIG_SMP),y)
+KW_SHARED_MEMORY := 1
+endif
+
# Experimental (SMP groundwork; the kernel stays UP): KW_ATOMICS=1 builds
# with the wasm atomics feature, so the __atomic_* builtins behind
# atomic.h, cmpxchg.h and barrier.h become real atomic instructions.
diff --git a/arch/wasm/configs/kw_smp.config b/arch/wasm/configs/kw_smp.config
new file mode 100644
index 00000000000..749e2d12a01
--- /dev/null
+++ b/arch/wasm/configs/kw_smp.config
@@ -0,0 +1,4 @@
+# unkernel SMP build: merged over kw_defconfig (make kw_defconfig kw_smp.config).
+# One wasm instance per CPU on a shared memory; see arch/wasm/Kconfig, SMP.
+CONFIG_SMP=y
+CONFIG_NR_CPUS=16
diff --git a/arch/wasm/include/asm/entry-common.h b/arch/wasm/include/asm/entry-common.h
index 185b2ff8246..ea8e4a240f7 100644
--- a/arch/wasm/include/asm/entry-common.h
+++ b/arch/wasm/include/asm/entry-common.h
@@ -5,4 +5,31 @@
#include <asm/stacktrace.h>
+#ifdef CONFIG_SMP
+/*
+ * A user task's stack lives in the host thread of its CPU; it may move to
+ * another CPU only at the reschedule on its way to user mode, and starts
+ * there on a fresh stack (process.c).
+ */
+void kw_exit_to_user_schedule(void);
+void kw_exit_to_user_move(void);
+#define arch_exit_to_user_mode_schedule kw_exit_to_user_schedule
+
+/*
+ * An affinity change that excludes the CPU (arch_stay_move()) or a better
+ * CPU named by the scheduler (arch_stay_move_to()) sets TIF_KW_MOVE.
+ */
+#define ARCH_EXIT_TO_USER_MODE_WORK _TIF_KW_MOVE
+
+static inline void arch_exit_to_user_mode_work(struct pt_regs *regs,
+ unsigned long ti_work)
+{
+ if (unlikely(ti_work & _TIF_KW_MOVE)) {
+ clear_thread_flag(TIF_KW_MOVE);
+ kw_exit_to_user_move();
+ }
+}
+#define arch_exit_to_user_mode_work arch_exit_to_user_mode_work
+#endif
+
#endif /* _ASM_WASM_ENTRY_COMMON_H */
diff --git a/arch/wasm/include/asm/futex.h b/arch/wasm/include/asm/futex.h
index 298606ab13a..295105b9d6b 100644
--- a/arch/wasm/include/asm/futex.h
+++ b/arch/wasm/include/asm/futex.h
@@ -8,8 +8,13 @@
#include <asm/errno.h>
/*
- * Single CPU, no preemption, and user mode only runs when the kernel calls
- * kw_run(): plain read-modify-write on the translated address is atomic.
+ * Read-modify-write of a user word through its kernel address
+ * (kw_user_addr(), valid until the next poll point). On SMP user code on
+ * other CPUs updates the same word with AMOs and LR/SC (kwemu's atomics
+ * are wasm atomics on the same memory), so these are wasm atomics too,
+ * fully ordered as riscv's amo*.aqrl and lr/sc.aqrl. Without wasm atomics
+ * (UP) the compiler makes them plain loads and stores, which suffices:
+ * one CPU, no preemption, and user code only runs inside kw_run().
*/
static inline int futex_atomic_cmpxchg_inatomic(u32 *uval, u32 __user *uaddr,
u32 oldval, u32 newval)
@@ -22,9 +27,9 @@ static inline int futex_atomic_cmpxchg_inatomic(u32 *uval, u32 __user *uaddr,
if (!p)
return -EFAULT;
- *uval = *p;
- if (*uval == oldval)
- *p = newval;
+ *uval = oldval;
+ __atomic_compare_exchange_n(p, uval, newval, false, __ATOMIC_SEQ_CST,
+ __ATOMIC_SEQ_CST);
return 0;
}
@@ -39,22 +44,21 @@ static inline int arch_futex_atomic_op_inuser(int op, u32 oparg, int *oval,
if (!p)
return -EFAULT;
- old = *p;
switch (op) {
case FUTEX_OP_SET:
- *p = oparg;
+ old = __atomic_exchange_n(p, oparg, __ATOMIC_SEQ_CST);
break;
case FUTEX_OP_ADD:
- *p = old + oparg;
+ old = __atomic_fetch_add(p, oparg, __ATOMIC_SEQ_CST);
break;
case FUTEX_OP_OR:
- *p = old | oparg;
+ old = __atomic_fetch_or(p, oparg, __ATOMIC_SEQ_CST);
break;
case FUTEX_OP_ANDN:
- *p = old & ~oparg;
+ old = __atomic_fetch_and(p, ~oparg, __ATOMIC_SEQ_CST);
break;
case FUTEX_OP_XOR:
- *p = old ^ oparg;
+ old = __atomic_fetch_xor(p, oparg, __ATOMIC_SEQ_CST);
break;
default:
return -ENOSYS;
diff --git a/arch/wasm/include/asm/hwcap.h b/arch/wasm/include/asm/hwcap.h
index f71640d38f5..e116408e5c1 100644
--- a/arch/wasm/include/asm/hwcap.h
+++ b/arch/wasm/include/asm/hwcap.h
@@ -21,6 +21,8 @@ struct kw_cpu;
* riscv_hwprobe report it.
*/
void kw_isa_init(struct kw_cpu *cpu);
+/* The KW_ISA_* set kw_isa_init() enabled (for the other CPUs' kwemu). */
+u64 kw_isa_enabled(void);
u64 kw_isa_hwprobe_ext0(void);
u64 kw_isa_hwprobe_ext1(void);
#endif
diff --git a/arch/wasm/include/asm/irq.h b/arch/wasm/include/asm/irq.h
index 8614e54fe17..f8fb09f2579 100644
--- a/arch/wasm/include/asm/irq.h
+++ b/arch/wasm/include/asm/irq.h
@@ -17,15 +17,37 @@
#define WASM_IRQ_VIRTIO 10 /* host: kwvirtio used buffers or a config change */
#define WASM_IRQ_DROP_CACHES 11 /* host: with WASM_IRQ_SNAPSHOT, drop the caches first (park.c) */
+/*
+ * SMP: inter-processor interrupts are bits of the target CPU's pending word
+ * (CPU 0's is wasm_host_irqs, where the host sets the device bits above;
+ * the others' are kw_irq_words[]), set atomically by the sender, which then
+ * wakes the target (memory.atomic.notify).
+ */
+#define KW_IPI_RESCHEDULE 24
+#define KW_IPI_CALL_FUNC 25
+#define KW_IPI_STOP 26
+#define KW_IPI_MASK (7U << KW_IPI_RESCHEDULE)
+
#include <asm-generic/irq.h>
#ifndef __ASSEMBLER__
+#include <linux/types.h>
+
struct pt_regs;
/* Run pending timer/host interrupts if irqs are enabled in @regs' context. */
void wasm_poll_irqs(struct pt_regs *regs);
/* Nanoseconds until the next timer expiry, -1 if none. */
long long wasm_timer_timeout(void);
+
+#ifdef CONFIG_SMP
+/* @cpu's word of pending interrupts. */
+u32 *kw_irq_word_of(int cpu);
+/* Set @bits in @cpu's word and wake it (any context, any CPU). */
+void kw_irq_raise(int cpu, u32 bits);
+/* smp.c: run the IPIs in @bits (in interrupt context). */
+void kw_handle_ipis(u32 bits);
+#endif
#endif
#endif /* _ASM_WASM_IRQ_H */
diff --git a/arch/wasm/include/asm/irqflags.h b/arch/wasm/include/asm/irqflags.h
index 93987ef653f..c69c2059a09 100644
--- a/arch/wasm/include/asm/irqflags.h
+++ b/arch/wasm/include/asm/irqflags.h
@@ -4,13 +4,15 @@
#define _ASM_WASM_IRQFLAGS_H
/*
- * Uniprocessor; "interrupts" (timer expiry, host events) are only taken at
+ * "Interrupts" (timer expiry, host events, IPIs) are only taken at
* well-defined poll points, so the irq state is just a flag.
*/
#define ARCH_IRQ_DISABLED 0
#define ARCH_IRQ_ENABLED 1
#ifndef __ASSEMBLER__
+#ifndef CONFIG_SMP
+/* Uniprocessor: the flag is in memory, and nothing polls on enable. */
extern unsigned long wasm_irq_flags;
#define arch_local_save_flags arch_local_save_flags
@@ -24,7 +26,72 @@ static inline void arch_local_irq_restore(unsigned long flags)
{
*(volatile unsigned long *)&wasm_irq_flags = flags;
}
-#endif
+#else
+#include <asm/asm.h>
+
+/*
+ * SMP: the flag is a wasm global of the CPU's instance (entry.S), and so is
+ * the address of the CPU's word of pending interrupts (asm/irq.h). Another
+ * CPU waiting for an IPI to be handled (a TLB shootdown, a function call)
+ * needs this CPU to poll, so enabling interrupts delivers what is pending,
+ * as hardware would (kw_irq_enable_pending(), irq.c).
+ */
+__ASM_DECL(kw_irq_flags, "i32")
+__ASM_DECL(kw_irq_word, iLONG)
+
+#define arch_local_save_flags arch_local_save_flags
+static __always_inline unsigned long arch_local_save_flags(void)
+{
+ unsigned int flags;
+
+ __asm__ volatile("global.get kw_irq_flags\n\t"
+ "local.set %0" : "=r"(flags));
+ return flags;
+}
+
+static __always_inline void kw_irq_flags_set(unsigned long flags)
+{
+ __asm__ volatile("local.get %0\n\t"
+ "global.set kw_irq_flags" : : "r"((unsigned int)flags) : "memory");
+}
+
+/* This CPU's word of pending interrupts and IPIs (non-zero: something to take). */
+static __always_inline unsigned int kw_irq_pending(void)
+{
+ const volatile unsigned int *word;
+
+ __asm__ volatile("global.get kw_irq_word\n\t"
+ "local.set %0" : "=r"(word));
+ return *word;
+}
+
+void kw_irq_enable_pending(void);
+
+#define arch_local_irq_restore arch_local_irq_restore
+static __always_inline void arch_local_irq_restore(unsigned long flags)
+{
+ if (flags == ARCH_IRQ_ENABLED && unlikely(kw_irq_pending()))
+ kw_irq_enable_pending();
+ else
+ kw_irq_flags_set(flags);
+}
+
+#define arch_local_irq_save arch_local_irq_save
+static __always_inline unsigned long arch_local_irq_save(void)
+{
+ unsigned long flags = arch_local_save_flags();
+
+ kw_irq_flags_set(ARCH_IRQ_DISABLED);
+ return flags;
+}
+
+#define arch_local_irq_disable arch_local_irq_disable
+static __always_inline void arch_local_irq_disable(void)
+{
+ kw_irq_flags_set(ARCH_IRQ_DISABLED);
+}
+#endif /* CONFIG_SMP */
+#endif /* __ASSEMBLER__ */
#include <asm-generic/irqflags.h>
diff --git a/arch/wasm/include/asm/kw_emu.h b/arch/wasm/include/asm/kw_emu.h
index dbdb6b5547c..fe4eaee612d 100644
--- a/arch/wasm/include/asm/kw_emu.h
+++ b/arch/wasm/include/asm/kw_emu.h
@@ -35,6 +35,15 @@
* the icache. (Rewriting a currently mapped exec page in place with no
* flush at all may keep running the old code until one of those, as an
* incoherent icache would.)
+ *
+ * Several CPUs (ABI 7): an SMP kernel gives each CPU its own struct
+ * kw_cpu, used only by that CPU's thread, on one shared memory. kwemu
+ * built with wasm atomics (zig build -Dkwemu-atomics) makes guest AMOs
+ * atomic read-modify-writes, SC a compare-and-swap against the value LR
+ * read, and FENCE a full barrier; without atomics they assume one hart.
+ * Guest stores are tracked only by the struct kw_cpu that runs them: code
+ * another CPU rewrites is seen after a flush on this one (riscv's
+ * flush_icache syscall, FENCE.I alone is local), as on hardware.
*/
#ifndef KW_EMU_H
#define KW_EMU_H
@@ -49,7 +58,7 @@
extern "C" {
#endif
-#define KW_ABI_VERSION 6
+#define KW_ABI_VERSION 7
struct kw_regs {
uint64_t x[32]; /* x[0] is ignored and reads as zero */
diff --git a/arch/wasm/include/asm/kwcpu.h b/arch/wasm/include/asm/kwcpu.h
new file mode 100644
index 00000000000..f245df77cb8
--- /dev/null
+++ b/arch/wasm/include/asm/kwcpu.h
@@ -0,0 +1,23 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * The kwemu software CPU of the running CPU (arch/wasm/mm/tlb.c), and the
+ * word of pending interrupts it polls (asm/irq.h).
+ */
+
+#ifndef _ASM_WASM_KWCPU_H
+#define _ASM_WASM_KWCPU_H
+
+#include <linux/smp.h>
+#include <asm/kw_emu.h>
+
+#ifdef CONFIG_SMP
+/* CPU 0's is static (tlb.c); the others' come from memblock (setup.c). */
+extern struct kw_cpu *kw_cpus[NR_CPUS];
+#define wasm_kw_cpu (kw_cpus[raw_smp_processor_id()])
+/* A secondary CPU sets up its kwemu (tlb.c). */
+void kw_cpu_start(void);
+#else
+extern struct kw_cpu *const wasm_kw_cpu;
+#endif
+
+#endif /* _ASM_WASM_KWCPU_H */
diff --git a/arch/wasm/include/asm/mmu_context.h b/arch/wasm/include/asm/mmu_context.h
index 1cc64c5d496..b89ef7b6009 100644
--- a/arch/wasm/include/asm/mmu_context.h
+++ b/arch/wasm/include/asm/mmu_context.h
@@ -15,6 +15,11 @@ static inline void activate_mm(struct mm_struct *prev, struct mm_struct *next)
switch_mm(prev, next, NULL);
}
+#ifdef CONFIG_SMP
+#define enter_lazy_tlb enter_lazy_tlb
+void enter_lazy_tlb(struct mm_struct *mm, struct task_struct *tsk);
+#endif
+
void kw_mm_release(struct mm_struct *mm);
#define destroy_context destroy_context
diff --git a/arch/wasm/include/asm/park.h b/arch/wasm/include/asm/park.h
index 2aa5ffd70d1..55f55c238c3 100644
--- a/arch/wasm/include/asm/park.h
+++ b/arch/wasm/include/asm/park.h
@@ -13,6 +13,7 @@
struct task_struct;
+#ifdef CONFIG_KW_PARK
/* Set while user tasks are asked to park at the top of user_mode_loop(). */
extern int kw_park_users;
/* Set once every task but the idle tasks is parked: arch_cpu_idle() finishes. */
@@ -28,5 +29,21 @@ void __noreturn kw_park_resume(struct task_struct *prev);
void kw_park_idle(void);
/* kw_resume (entry.S): a restored snapshot starts here. */
asmlinkage void __noreturn __kw_resume(void);
+#else
+/* SMP: no parking (kernel.md, Parking). */
+static const int kw_park_users;
+static const int kw_park_final;
+static inline void kw_park_user(void)
+{
+}
+
+static inline void kw_park_resume(struct task_struct *prev)
+{
+}
+
+static inline void kw_park_idle(void)
+{
+}
+#endif
#endif /* _ASM_WASM_PARK_H */
diff --git a/arch/wasm/include/asm/pgtable.h b/arch/wasm/include/asm/pgtable.h
index 78f4b6ab5f4..841c27fd516 100644
--- a/arch/wasm/include/asm/pgtable.h
+++ b/arch/wasm/include/asm/pgtable.h
@@ -348,6 +348,75 @@ void update_mmu_cache_range(struct vm_fault *vmf, struct vm_area_struct *vma,
#define update_mmu_cache(vma, addr, ptep) \
update_mmu_cache_range(NULL, vma, addr, ptep, 1)
+#ifdef CONFIG_SMP
+/*
+ * SMP: another CPU may set A and D in a present PTE at any time, without
+ * the PTE lock (arch/wasm/mm/fault.c, as a hardware walker would), so every
+ * read-modify-write of a present PTE is atomic and none loses a D bit.
+ */
+#define __HAVE_ARCH_PTEP_GET_AND_CLEAR
+static inline pte_t ptep_get_and_clear(struct mm_struct *mm,
+ unsigned long address, pte_t *ptep)
+{
+ return __pte(xchg(&pte_val(*ptep), 0));
+}
+
+/*
+ * The teardown of a whole mm (exit_mmap(), tlb->fullmm): no task uses the
+ * mm any more and none can start to (mm_users is 0), so nothing sets A or D
+ * behind our back and a plain read and clear is enough (as on x86).
+ */
+#define __HAVE_ARCH_PTEP_GET_AND_CLEAR_FULL
+static inline pte_t ptep_get_and_clear_full(struct mm_struct *mm,
+ unsigned long address,
+ pte_t *ptep, int full)
+{
+ pte_t pte;
+
+ if (!full)
+ return ptep_get_and_clear(mm, address, ptep);
+ pte = READ_ONCE(*ptep);
+ WRITE_ONCE(pte_val(*ptep), 0);
+ return pte;
+}
+
+#define __HAVE_ARCH_PTEP_SET_WRPROTECT
+static inline void ptep_set_wrprotect(struct mm_struct *mm,
+ unsigned long address, pte_t *ptep)
+{
+ unsigned long old = pte_val(READ_ONCE(*ptep));
+
+ while (!try_cmpxchg(&pte_val(*ptep), &old, old & ~_PAGE_WRITE))
+ ;
+}
+
+#define __HAVE_ARCH_PTEP_TEST_AND_CLEAR_YOUNG
+static inline int ptep_test_and_clear_young(struct vm_area_struct *vma,
+ unsigned long address, pte_t *ptep)
+{
+ unsigned long old = pte_val(READ_ONCE(*ptep));
+
+ do {
+ if (!(old & _PAGE_ACCESSED))
+ return 0;
+ } while (!try_cmpxchg(&pte_val(*ptep), &old, old & ~_PAGE_ACCESSED));
+ return 1;
+}
+
+/*
+ * The fault path's update (generic: compare, then a plain store of @entry,
+ * which was built from an older read): keep a D bit set since.
+ */
+#define __HAVE_ARCH_PTEP_SET_ACCESS_FLAGS
+int ptep_set_access_flags(struct vm_area_struct *vma, unsigned long address,
+ pte_t *ptep, pte_t entry, int dirty);
+
+/* This CPU only: a wider PTE needs no other CPU's flush (mm/tlb.c). */
+void kw_flush_tlb_fix_spurious_fault(struct vm_area_struct *vma,
+ unsigned long addr);
+#define flush_tlb_fix_spurious_fault(vma, address, ptep) \
+ kw_flush_tlb_fix_spurious_fault(vma, address)
+#else
#define __HAVE_ARCH_PTEP_GET_AND_CLEAR
static inline pte_t ptep_get_and_clear(struct mm_struct *mm,
unsigned long address, pte_t *ptep)
@@ -364,6 +433,7 @@ static inline void ptep_set_wrprotect(struct mm_struct *mm,
{
set_pte(ptep, pte_wrprotect(*ptep));
}
+#endif
/* --- swap entries (riscv layout) --------------------------------------- */
/*
diff --git a/arch/wasm/include/asm/processor.h b/arch/wasm/include/asm/processor.h
index da9befa9706..67d9ec0deed 100644
--- a/arch/wasm/include/asm/processor.h
+++ b/arch/wasm/include/asm/processor.h
@@ -25,7 +25,17 @@
struct task_struct;
struct pt_regs;
+#ifdef CONFIG_SMP
+/*
+ * A CPU spinning with interrupts on (a lock, a csd wait) takes pending
+ * IPIs here: the CPU it waits for may be waiting for this one's answer
+ * (a TLB shootdown from the lock holder). irq.c.
+ */
+void kw_cpu_relax(void);
+#define cpu_relax() kw_cpu_relax()
+#else
#define cpu_relax() barrier()
+#endif
struct thread_struct {
int (*fn)(void *); /* kernel thread entry (until first run) */
@@ -34,6 +44,25 @@ struct thread_struct {
int (*park_fn)(void *); /* kernel thread: re-enters its loop */
void *park_arg;
int park_state; /* KW_PARK_* (asm/park.h) */
+#ifdef CONFIG_SMP
+ /* The CPU whose host thread holds the task's wasm stack (process.c). */
+ int stack_cpu;
+ /*
+ * Switched in on another CPU than stack_cpu, the task starts there on
+ * a fresh stack: a user task switched out at the reschedule on its way
+ * to user mode (movable) goes on to user mode, a kthread asleep at
+ * arch_kthread_restart_point() (linux/kthread.h) runs
+ * kthread_exit(restart_fn(restart_arg)).
+ */
+ int movable;
+ /*
+ * 1 + a CPU the scheduler named as better while the task was held
+ * (arch_stay_move_to(): exec, a wakeup on a busy CPU), 0 for none.
+ */
+ int move_to;
+ int (*restart_fn)(void *);
+ void *restart_arg;
+#endif
};
#define INIT_THREAD { }
diff --git a/arch/wasm/include/asm/smp.h b/arch/wasm/include/asm/smp.h
new file mode 100644
index 00000000000..8bda30c28a9
--- /dev/null
+++ b/arch/wasm/include/asm/smp.h
@@ -0,0 +1,34 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+
+#ifndef _ASM_WASM_SMP_H
+#define _ASM_WASM_SMP_H
+
+#include <linux/cpumask.h>
+#include <linux/thread_info.h>
+
+#ifdef CONFIG_SMP
+/*
+ * Each CPU is an instance of the kernel module on its own host thread;
+ * `current` is a wasm global of the instance, so it is per CPU, and a task
+ * moves to another CPU only while it is switched out where its stack can
+ * be dropped (ARCH_TASKS_STAY_ON_CPU, process.c).
+ */
+#define raw_smp_processor_id() (current_thread_info()->cpu)
+
+void arch_send_call_function_ipi_mask(const struct cpumask *mask);
+void arch_send_call_function_single_ipi(int cpu);
+
+/* process.c: tell this CPU's host which stacks will never run again. */
+void kw_stack_drain(void);
+
+/* setup_arch(): the CPUs the host offers become possible and present. */
+void __init kw_smp_init_cpus(void);
+/* kw_secondary_entry (entry.S): a secondary CPU's idle task starts here. */
+asmlinkage void __noreturn kw_secondary_start(void);
+#else
+static inline void kw_smp_init_cpus(void)
+{
+}
+#endif
+
+#endif /* _ASM_WASM_SMP_H */
diff --git a/arch/wasm/include/asm/thread_info.h b/arch/wasm/include/asm/thread_info.h
index aa4b53abe79..446dae41f88 100644
--- a/arch/wasm/include/asm/thread_info.h
+++ b/arch/wasm/include/asm/thread_info.h
@@ -38,5 +38,8 @@ struct thread_info {
/* Architecture specific bits (16-31): */
#define TIF_NEVER_RUN 16 /* was never run by the scheduler */
#define _TIF_NEVER_RUN (1 << TIF_NEVER_RUN)
+/* SMP: the affinity excludes its CPU; move on the way to user mode */
+#define TIF_KW_MOVE 17
+#define _TIF_KW_MOVE (1 << TIF_KW_MOVE)
#endif /* _ASM_WASM_THREAD_INFO_H */
diff --git a/arch/wasm/include/asm/time.h b/arch/wasm/include/asm/time.h
index 9b5deac5ebd..3845ef11a34 100644
--- a/arch/wasm/include/asm/time.h
+++ b/arch/wasm/include/asm/time.h
@@ -3,7 +3,17 @@
#ifndef _ASM_WASM_TIME_H
#define _ASM_WASM_TIME_H
+#ifdef CONFIG_SMP
+#include <linux/percpu.h>
+
+/* Expiry (monotonic ns) of this CPU's one-shot clockevent, or -1. */
+DECLARE_PER_CPU(long long, kw_timer_expiry);
+#define wasm_timer_expiry (*this_cpu_ptr(&kw_timer_expiry))
+/* A secondary CPU starts its clockevent (smp.c). */
+void kw_timer_start_cpu(void);
+#else
/* Expiry (monotonic ns) of the one-shot clockevent, or -1. */
extern long long wasm_timer_expiry;
+#endif
#endif /* _ASM_WASM_TIME_H */
diff --git a/arch/wasm/include/asm/tlbflush.h b/arch/wasm/include/asm/tlbflush.h
index 4ce1d520697..c6369fd7ff4 100644
--- a/arch/wasm/include/asm/tlbflush.h
+++ b/arch/wasm/include/asm/tlbflush.h
@@ -6,8 +6,8 @@
#include <linux/mm_types.h>
/*
- * The only "TLB" is the kwemu software CPU's translation cache, which
- * belongs to the (single) active user address space.
+ * The only "TLB" is each CPU's kwemu translation cache, which belongs to
+ * the user address space loaded on that CPU (mm/tlb.c).
*/
void flush_tlb_all(void);
void flush_tlb_mm(struct mm_struct *mm);
@@ -15,6 +15,9 @@ void flush_tlb_page(struct vm_area_struct *vma, unsigned long addr);
void flush_tlb_range(struct vm_area_struct *vma, unsigned long start,
unsigned long end);
+/* riscv_flush_icache(): drop decoded code (every CPU's on SMP). */
+void kw_flush_icache_all(void);
+
static inline void flush_tlb_kernel_range(unsigned long start,
unsigned long end)
{
diff --git a/arch/wasm/include/asm/wasm.h b/arch/wasm/include/asm/wasm.h
index f317d3f6710..139f3e96491 100644
--- a/arch/wasm/include/asm/wasm.h
+++ b/arch/wasm/include/asm/wasm.h
@@ -85,6 +85,36 @@ struct task_struct *wasm_switch_to(struct task_struct *prev,
int next_is_new, int prev_dead)
__unkernel_import(wasm_switch_to);
+#ifdef CONFIG_SMP
+/*
+ * Address of the module's __wasm_init_memory_flag (wasm-ld's guard of the
+ * passive data segments of a shared memory; setup.c), or 0.
+ */
+unsigned long wasm_init_flag(void)
+ __unkernel_import(wasm_init_flag);
+
+/* How many CPUs the host offers (at least 1: this one). */
+int wasm_cpu_count(void)
+ __unkernel_import(wasm_cpu_count);
+
+/*
+ * Start CPU @cpu: the host creates another instance of this module on the
+ * same memory, in its own thread (a worker), and calls the export
+ * kw_secondary_entry(@idle) there. Returns 0, or a negative errno if it
+ * cannot. Called from __cpu_up() on CPU 0.
+ */
+int wasm_cpu_start(int cpu, struct task_struct *idle)
+ __unkernel_import(wasm_cpu_start);
+
+/*
+ * @task's suspended stack in this CPU's thread will never run: the task
+ * started on a fresh stack on another CPU (process.c). The host forgets
+ * it, if it still holds one for @task. Called on this CPU only.
+ */
+void wasm_stack_drop(struct task_struct *task)
+ __unkernel_import(wasm_stack_drop);
+#endif
+
/* Bits set by the host in wasm_host_irqs (see irq.h). */
extern u32 wasm_host_irqs;
diff --git a/arch/wasm/kernel/Makefile b/arch/wasm/kernel/Makefile
index 9e24c876077..1f9d572be1b 100644
--- a/arch/wasm/kernel/Makefile
+++ b/arch/wasm/kernel/Makefile
@@ -7,12 +7,13 @@ obj-y += entry.o
obj-y += head.o
obj-y += irq.o
obj-y += irqflags.o
-obj-y += park.o
+obj-$(CONFIG_KW_PARK) += park.o
obj-y += process.o
obj-y += ptrace.o
obj-y += random.o
obj-y += reboot.o
obj-y += setup.o
+obj-$(CONFIG_SMP) += smp.o
obj-y += signal.o
obj-y += sync.o
obj-y += sys_riscv.o
diff --git a/arch/wasm/kernel/cpu.c b/arch/wasm/kernel/cpu.c
index d5bb65ac3fc..f81622e213d 100644
--- a/arch/wasm/kernel/cpu.c
+++ b/arch/wasm/kernel/cpu.c
@@ -93,6 +93,12 @@ static u64 kw_isa_want __initdata = ~0ULL;
static char kw_isa_str[256] __ro_after_init = "rv64imafdc_zicsr_zifencei";
static u64 kw_isa_ext0 __ro_after_init = RISCV_HWPROBE_IMA_FD | RISCV_HWPROBE_IMA_C;
static u64 kw_isa_ext1 __ro_after_init;
+static u64 kw_isa_got __ro_after_init;
+
+u64 kw_isa_enabled(void)
+{
+ return kw_isa_got;
+}
/*
* kw.isa=LIST: a comma-separated list applied from left to right.
@@ -148,6 +154,7 @@ void __init kw_isa_init(struct kw_cpu *cpu)
if (kw_isa_want & BIT_ULL(i))
want |= kw_isa_exts[i].kw;
got = kw_set_isa(cpu, want);
+ kw_isa_got = got;
p += scnprintf(p, end - p, "rv64imafdc");
kw_isa_ext0 = RISCV_HWPROBE_IMA_FD | RISCV_HWPROBE_IMA_C;
diff --git a/arch/wasm/kernel/entry.S b/arch/wasm/kernel/entry.S
index b1f3e265fcb..9d2b7aeb433 100644
--- a/arch/wasm/kernel/entry.S
+++ b/arch/wasm/kernel/entry.S
@@ -12,6 +12,18 @@
.globaltype current, iLONG
current:
+#ifdef CONFIG_SMP
+/* This CPU's interrupt flag (asm/irqflags.h); 0: disabled. */
+.globl kw_irq_flags
+.globaltype kw_irq_flags, i32
+kw_irq_flags:
+
+/* The address of this CPU's word of pending interrupts (asm/irq.h). */
+.globl kw_irq_word
+.globaltype kw_irq_word, iLONG
+kw_irq_word:
+#endif
+
.section .text,"",@
.functype wasm_switch_to(iLONG, iLONG, i32, i32) -> (iLONG)
@@ -52,6 +64,7 @@ wasm_arch_switch:
local.get 5
end_function
+#ifdef CONFIG_KW_PARK
/*
* kw_resume(): entry point of a restored snapshot, called by the host on a
* fresh Wasm stack (JSPI "promising" export) instead of _start, after it
@@ -71,6 +84,35 @@ kw_resume:
call __kw_resume
unreachable
end_function
+#endif
+
+#ifdef CONFIG_SMP
+/*
+ * kw_secondary_entry(idle): entry point of a secondary CPU, called by the
+ * host (JSPI "promising" export) on a fresh Wasm stack of a new instance
+ * of the module, in the CPU's own thread, with the idle task that
+ * __cpu_up() passed to wasm_cpu_start(). Never returns.
+ */
+.functype kw_secondary_start() -> ()
+.globl kw_secondary_entry
+kw_secondary_entry:
+ .functype kw_secondary_entry(iLONG) -> ()
+
+ local.get 0
+ global.set current
+
+ local.get 0
+ iLONG.const zeroptr+TASK_STRUCT_STACK
+ iLONG.add
+ iLONG.load 0
+ iLONG.const zeroptr+THREAD_STACK_START
+ iLONG.add
+ global.set __stack_pointer
+
+ call kw_secondary_start
+ unreachable
+ end_function
+#endif
/*
* ret_from_fork(prev, next): entry point of every new task, called by the
diff --git a/arch/wasm/kernel/head.S b/arch/wasm/kernel/head.S
index 6f84fb37fba..254440d9c0f 100644
--- a/arch/wasm/kernel/head.S
+++ b/arch/wasm/kernel/head.S
@@ -7,6 +7,10 @@
.functype start_kernel() -> ()
+#ifdef CONFIG_SMP
+.globaltype kw_irq_word, iLONG
+#endif
+
/*
* vmlinux entry point, called by the host (as a JSPI "promising" export) once
* linear memory has been sized. The command line and the initrd come from
@@ -22,6 +26,11 @@ _start:
iLONG.const init_stack+THREAD_STACK_START
global.set __stack_pointer
+#ifdef CONFIG_SMP
+ iLONG.const wasm_host_irqs
+ global.set kw_irq_word
+#endif
+
iLONG.const memory_start
iLONG.const CONFIG_KERNEL_START
iLONG.store 0
diff --git a/arch/wasm/kernel/irq.c b/arch/wasm/kernel/irq.c
index fa7551ee9e9..1f2055d28c0 100644
--- a/arch/wasm/kernel/irq.c
+++ b/arch/wasm/kernel/irq.c
@@ -1,8 +1,11 @@
/* SPDX-License-Identifier: GPL-2.0-only */
/*
- * Interrupts. There is one CPU and no asynchronous delivery: pending
- * "interrupts" (the clockevent expiring, host events such as console input)
- * are polled when user mode traps back into the kernel and in the idle loop.
+ * Interrupts. There is no asynchronous delivery: pending "interrupts" (the
+ * clockevent expiring, host events such as console input) are polled when
+ * user mode traps back into the kernel and in the idle loop. On SMP each
+ * CPU has a word of pending bits (CPU 0's is wasm_host_irqs, which also
+ * gets the host's device bits), IPIs among them, and a CPU also polls it
+ * when interrupts are enabled and in cpu_relax().
*/
#include <linux/irq.h>
@@ -11,15 +14,50 @@
#include <linux/hardirq.h>
#include <linux/interrupt.h>
#include <linux/sched.h>
+#include <linux/atomic.h>
+#include <linux/export.h>
#include <asm/irq.h>
#include <asm/irq_regs.h>
#include <asm/park.h>
#include <asm/time.h>
#include <asm/wasm.h>
-/* Written by the host (any time the kernel is suspended). */
+/*
+ * Written by the host (any time the kernel is suspended; on SMP with an
+ * atomic OR, since other CPUs set IPI bits in it too).
+ */
u32 wasm_host_irqs;
+#ifdef CONFIG_SMP
+/* The other CPUs' words (index 0 is unused: CPU 0's is wasm_host_irqs). */
+static struct {
+ u32 pending;
+} ____cacheline_aligned kw_irq_words[NR_CPUS];
+
+u32 *kw_irq_word_of(int cpu)
+{
+ return cpu ? &kw_irq_words[cpu].pending : &wasm_host_irqs;
+}
+
+void kw_irq_raise(int cpu, u32 bits)
+{
+ u32 *word = kw_irq_word_of(cpu);
+
+ atomic_or(bits, (atomic_t *)word);
+ /* Ends an idle wait: memory.atomic.wait32 there, Atomics.waitAsync on CPU 0. */
+ __builtin_wasm_memory_atomic_notify((int *)word, ~0U);
+}
+
+static u32 *kw_this_irq_word(void)
+{
+ u32 *word;
+
+ __asm__ volatile("global.get kw_irq_word\n\t"
+ "local.set %0" : "=r"(word));
+ return word;
+}
+#endif
+
static void wasm_irq_noop(struct irq_data *data)
{
}
@@ -37,6 +75,12 @@ void __init init_IRQ(void)
for (irq = 0; irq < NR_IRQS; ++irq)
irq_set_chip_and_handler(irq, &wasm_irq_chip, handle_simple_irq);
+#ifdef CONFIG_SMP
+ /* Each CPU has its own clockevent (time.c). */
+ irq_set_percpu_devid(WASM_IRQ_TIMER);
+ irq_set_chip_and_handler(WASM_IRQ_TIMER, &wasm_irq_chip,
+ handle_percpu_devid_irq);
+#endif
}
long long wasm_timer_timeout(void)
@@ -52,10 +96,18 @@ long long wasm_timer_timeout(void)
static u32 wasm_pending_irqs(void)
{
+#ifdef CONFIG_SMP
+ u32 *word = kw_this_irq_word();
+ u32 pending = READ_ONCE(*word);
+
+ if (pending)
+ pending = xchg(word, 0);
+#else
u32 pending = READ_ONCE(wasm_host_irqs);
if (pending)
WRITE_ONCE(wasm_host_irqs, 0);
+#endif
if (wasm_timer_timeout() == 0) {
WRITE_ONCE(wasm_timer_expiry, -1);
pending |= 1U << WASM_IRQ_TIMER;
@@ -75,6 +127,11 @@ void wasm_poll_irqs(struct pt_regs *regs)
irq_enter_rcu();
old_regs = set_irq_regs(regs);
+#ifdef CONFIG_SMP
+ if (pending & KW_IPI_MASK)
+ kw_handle_ipis(pending & KW_IPI_MASK);
+ pending &= ~KW_IPI_MASK;
+#endif
for (irq = 0; pending; irq++, pending >>= 1)
if (pending & 1)
generic_handle_irq(irq);
@@ -101,10 +158,64 @@ void arch_cpu_idle(void)
return;
}
+#ifdef CONFIG_SMP
+ /* Stacks of tasks that moved away: dropped before this CPU sleeps. */
+ kw_stack_drain();
+ if (!kw_irq_pending() && timeout != 0) {
+ if (smp_processor_id() == 0)
+ wasm_idle(timeout); /* the host's devices may wake it too */
+ else
+ /* Until an IPI (kw_irq_raise()) or the timer; no JSPI needed. */
+ __builtin_wasm_memory_atomic_wait32((int *)kw_this_irq_word(),
+ 0, timeout);
+ }
+#else
if (!READ_ONCE(wasm_host_irqs) && timeout != 0)
wasm_idle(timeout);
+#endif
state = irqentry_enter(&regs);
wasm_poll_irqs(&regs);
irqentry_exit(&regs, state);
}
+
+#ifdef CONFIG_SMP
+/*
+ * arch_local_irq_restore() is enabling interrupts and something is pending:
+ * take it first, as an interrupt arriving right after the enable, with
+ * interrupts still off while the handlers run.
+ */
+void kw_irq_enable_pending(void)
+{
+ struct pt_regs regs = { .kernel = 1, .irqflags = ARCH_IRQ_ENABLED,
+ .cause = PT_CAUSE_NONE };
+ irqentry_state_t state;
+
+ do {
+ state = irqentry_enter(&regs);
+ wasm_poll_irqs(&regs);
+ irqentry_exit(&regs, state);
+ } while (kw_irq_pending());
+ kw_irq_flags_set(ARCH_IRQ_ENABLED);
+}
+
+void kw_cpu_relax(void)
+{
+ unsigned int pending = kw_irq_pending();
+
+ if (likely(!pending))
+ return;
+ if (arch_local_save_flags() == ARCH_IRQ_ENABLED) {
+ kw_irq_flags_set(ARCH_IRQ_DISABLED);
+ kw_irq_enable_pending();
+ } else if (pending & BIT(KW_IPI_STOP)) {
+ /*
+ * A panic elsewhere, or the session ended on another CPU (its
+ * host raises this on CPU 0): the CPU this one spins for may
+ * never answer. Stop, so that CPU 0's host can take the exit.
+ */
+ kw_handle_ipis(BIT(KW_IPI_STOP));
+ }
+}
+EXPORT_SYMBOL(kw_cpu_relax);
+#endif
diff --git a/arch/wasm/kernel/irqflags.c b/arch/wasm/kernel/irqflags.c
index 0cedd2cd63b..2cce4b92bde 100644
--- a/arch/wasm/kernel/irqflags.c
+++ b/arch/wasm/kernel/irqflags.c
@@ -3,6 +3,8 @@
#include <linux/export.h>
#include <asm/irqflags.h>
-/* Boot with interrupts disabled. */
+#ifndef CONFIG_SMP
+/* Boot with interrupts disabled. (SMP: a wasm global per CPU, entry.S.) */
unsigned long wasm_irq_flags = ARCH_IRQ_DISABLED;
EXPORT_SYMBOL(wasm_irq_flags);
+#endif
diff --git a/arch/wasm/kernel/park.c b/arch/wasm/kernel/park.c
index a3e4b05f3ea..7cbf1adc740 100644
--- a/arch/wasm/kernel/park.c
+++ b/arch/wasm/kernel/park.c
@@ -94,6 +94,7 @@
#include <asm/entry.h>
#include <asm/irq.h>
#include <asm/kw_emu.h>
+#include <asm/kwcpu.h>
#include <asm/park.h>
#include <asm/wasi.h>
#include <asm/wasm.h>
@@ -126,8 +127,6 @@ static unsigned long kw_park_free_bits, kw_park_nr_free;
/* In the kernel image: below 4 GiB, as WASI needs (asm/wasi.h). */
static u8 kw_park_seed[32];
-extern struct kw_cpu *const wasm_kw_cpu;
-
static int kw_parkd_fn(void *unused);
static BLOCKING_NOTIFIER_HEAD(kw_park_restore_chain);
diff --git a/arch/wasm/kernel/process.c b/arch/wasm/kernel/process.c
index 3cad124e5cb..05622e66df2 100644
--- a/arch/wasm/kernel/process.c
+++ b/arch/wasm/kernel/process.c
@@ -10,29 +10,180 @@
*/
#include <linux/entry-common.h>
+#include <linux/kthread.h>
#include <linux/ptrace.h>
#include <linux/sched.h>
#include <linux/sched/debug.h>
+#include <linux/sched/stat.h>
#include <linux/sched/task.h>
#include <linux/sched/task_stack.h>
#include <linux/printk.h>
+#include <linux/proc_fs.h>
+#include <linux/seq_file.h>
#include <linux/slab.h>
#include <asm/entry.h>
#include <asm/kw_emu.h>
+#include <asm/kwcpu.h>
#include <asm/park.h>
#include <asm/wasm.h>
-extern struct kw_cpu *const wasm_kw_cpu;
+#ifdef CONFIG_SMP
+/*
+ * Moving tasks between CPUs. A task's wasm stack lives in the host thread
+ * of the CPU that started it (thread.stack_cpu), and only that thread can
+ * resume it, so the task is held on that CPU (migrate_disable() from its
+ * first run on) except where nothing on its stack is needed again:
+ *
+ * - a user task at the reschedule on its way to user mode
+ * (kw_exit_to_user_schedule(), called by exit_to_user_mode_loop() after
+ * a system call, a fault or an interrupt, the slice end among them): its
+ * state is all in pt_regs and task_struct;
+ * - a kthread at a restart point (arch_kthread_restart_point()).
+ *
+ * There sched_stay_release() lets it go until it runs again. Switched in on
+ * its stack's CPU, it resumes that stack as usual and is held again.
+ * Switched in on another CPU (the load balancer pulled it, an affinity
+ * change sent it there), it starts on a fresh stack (__ret_from_fork()): a
+ * user task finishes the switch and runs the exit to user mode again from
+ * the top (kw_user_resume()), which finds whatever work the interrupted
+ * pass had left in the TIF flags; a kthread calls its restart function.
+ * The old stack never runs again: the CPU that holds it tells its host to
+ * drop it at its next switch or idle (kw_stack_drain()), before it could
+ * switch to that task again.
+ *
+ * An affinity change that excludes a held user task's CPU is recorded
+ * without waiting (kernel/sched/core.c): arch_stay_move() sets TIF_KW_MOVE,
+ * and the exit work (asm/entry-common.h) then releases the task, which the
+ * stopper moves as soon as it is off the CPU.
+ */
+#define KW_STACK_DROPS 32
+
+struct kw_stack_drops {
+ raw_spinlock_t lock;
+ unsigned int n;
+ struct task_struct *task[KW_STACK_DROPS];
+};
+
+static DEFINE_PER_CPU(struct kw_stack_drops, kw_stack_drops) = {
+ .lock = __RAW_SPIN_LOCK_UNLOCKED(kw_stack_drops.lock),
+};
+
+/* /proc/kwmove */
+struct kw_move_stats {
+ unsigned long released; /* user tasks switched out where they may move */
+ unsigned long resumed; /* ... and switched in on their stack's CPU */
+ unsigned long moved; /* ... and started on another CPU */
+ unsigned long restarted; /* kthreads started again on another CPU */
+ unsigned long dropped; /* stacks this CPU's host was told to drop */
+ unsigned long lost; /* drops that found the list full */
+ unsigned long hinted; /* exits that found a better CPU named (exec, wakeup) */
+ unsigned long followed; /* ... and moved there (it was idle, this CPU busy) */
+};
+
+static DEFINE_PER_CPU(struct kw_move_stats, kw_move_stats);
+
+/* @t started on a fresh stack here: @cpu's host must drop its old one. */
+static void kw_stack_drop(int cpu, struct task_struct *t)
+{
+ struct kw_stack_drops *d = per_cpu_ptr(&kw_stack_drops, cpu);
+
+ raw_spin_lock(&d->lock);
+ if (d->n < KW_STACK_DROPS) {
+ d->task[d->n] = t;
+ WRITE_ONCE(d->n, d->n + 1);
+ } else {
+ /* The host keeps that stack until the task's next fresh start there. */
+ this_cpu_inc(kw_move_stats.lost);
+ }
+ raw_spin_unlock(&d->lock);
+}
+
+/*
+ * Tell this CPU's host to drop the stacks that started again elsewhere.
+ * Called before every switch, so before this CPU could hold a newer stack
+ * of one of those tasks (or of a new task at the same address).
+ */
+void kw_stack_drain(void)
+{
+ struct kw_stack_drops *d = this_cpu_ptr(&kw_stack_drops);
+ unsigned long flags;
+ unsigned int i;
+
+ if (likely(!READ_ONCE(d->n)))
+ return;
+ raw_spin_lock_irqsave(&d->lock, flags);
+ for (i = 0; i < d->n; i++)
+ wasm_stack_drop(d->task[i]);
+ this_cpu_add(kw_move_stats.dropped, d->n);
+ WRITE_ONCE(d->n, 0);
+ raw_spin_unlock_irqrestore(&d->lock, flags);
+}
+
+static int kw_move_show(struct seq_file *m, void *v)
+{
+ struct kw_move_stats s = { };
+ int cpu;
+
+ for_each_possible_cpu(cpu) {
+ struct kw_move_stats *c = per_cpu_ptr(&kw_move_stats, cpu);
+
+ s.released += READ_ONCE(c->released);
+ s.resumed += READ_ONCE(c->resumed);
+ s.moved += READ_ONCE(c->moved);
+ s.restarted += READ_ONCE(c->restarted);
+ s.dropped += READ_ONCE(c->dropped);
+ s.lost += READ_ONCE(c->lost);
+ s.hinted += READ_ONCE(c->hinted);
+ s.followed += READ_ONCE(c->followed);
+ }
+ seq_printf(m, "released %lu resumed %lu moved %lu restarted %lu dropped %lu lost %lu hinted %lu followed %lu\n",
+ s.released, s.resumed, s.moved, s.restarted, s.dropped, s.lost, s.hinted, s.followed);
+ return 0;
+}
+
+static int __init kw_move_proc_init(void)
+{
+ proc_create_single("kwmove", 0444, NULL, kw_move_show);
+ return 0;
+}
+fs_initcall(kw_move_proc_init);
+#endif
struct task_struct *__sched
__switch_to(struct task_struct *prev, struct task_struct *next)
{
int is_new = 0;
+#ifdef CONFIG_SMP
+ int cpu = smp_processor_id();
+
+ kw_stack_drain();
+ if (prev->thread.movable)
+ this_cpu_inc(kw_move_stats.released);
+ /* Atomic: other CPUs set flags of these tasks (need_resched). */
+ if (test_ti_thread_flag(task_thread_info(next), TIF_NEVER_RUN)) {
+ clear_ti_thread_flag(task_thread_info(next), TIF_NEVER_RUN);
+ is_new = 1;
+ } else if (unlikely(next->thread.stack_cpu != cpu)) {
+ /* Moved while released: start it here, drop the old stack there. */
+ WARN_ON_ONCE(!next->thread.movable && !next->thread.restart_fn);
+ kw_stack_drop(next->thread.stack_cpu, next);
+ if (next->thread.movable)
+ this_cpu_inc(kw_move_stats.moved);
+ else
+ this_cpu_inc(kw_move_stats.restarted);
+ is_new = 1;
+ } else if (next->thread.movable) {
+ this_cpu_inc(kw_move_stats.resumed);
+ }
+ if (is_new)
+ next->thread.stack_cpu = cpu;
+#else
if (task_thread_info(next)->flags & _TIF_NEVER_RUN) {
task_thread_info(next)->flags &= ~_TIF_NEVER_RUN;
is_new = 1;
}
+#endif
/* Threads sharing an mm must not inherit an LR/SC reservation. */
kw_clear_reservation(wasm_kw_cpu);
@@ -41,14 +192,186 @@ __switch_to(struct task_struct *prev, struct task_struct *next)
READ_ONCE(prev->__state) == TASK_DEAD);
}
+#ifdef CONFIG_SMP
+/*
+ * A kthread is about to sleep with nothing on its stack that it needs
+ * again (a new one waiting for its first wakeup, a park before its
+ * function, an idle workqueue worker), and may be bound to another CPU
+ * meanwhile: let it move until it runs again. Woken here, it returns from
+ * schedule() as usual; woken on another CPU, __switch_to() starts it on a
+ * fresh stack and __ret_from_fork() calls @fn.
+ */
+void arch_kthread_restart_point(int (*fn)(void *), void *arg)
+{
+ current->thread.restart_arg = arg;
+ WRITE_ONCE(current->thread.restart_fn, fn);
+ migrate_enable();
+}
+
+/* It woke without switching out: still on its stack, so it stays here. */
+void arch_kthread_restart_cancel(void)
+{
+ migrate_disable();
+ current->thread.restart_fn = NULL;
+}
+
+/*
+ * Let current go (sched_stay_release(), to @dest if >= 0) and reschedule:
+ * the task may move to another CPU while it is switched out here, and then
+ * never returns from this schedule() (kw_user_resume()).
+ */
+static void kw_stay_schedule(int dest)
+{
+ struct task_struct *p = current;
+
+ if (!sched_stay_release(dest)) {
+ schedule();
+ return;
+ }
+ p->thread.movable = 1;
+ schedule();
+ /* Not switched out, or switched in again on this CPU: held again. */
+ p->thread.movable = 0;
+ migrate_disable();
+}
+
+/* exit_to_user_mode_loop()'s reschedule (asm/entry-common.h). */
+void kw_exit_to_user_schedule(void)
+{
+ kw_stay_schedule(-1);
+}
+
+/*
+ * TIF_KW_MOVE: an affinity change that excludes this CPU (arch_stay_move()),
+ * or a better CPU named while the task was held (arch_stay_move_to()). That
+ * one is taken only if it is idle now and this CPU has other work: a move
+ * costs a fresh stack, and the code the JIT compiled for the task here.
+ */
+void kw_exit_to_user_move(void)
+{
+ struct task_struct *p = current;
+ int dest = p->thread.move_to - 1;
+
+ p->thread.move_to = 0;
+ if (dest >= 0) {
+ this_cpu_inc(kw_move_stats.hinted);
+ if (single_task_running() || !idle_cpu(dest)) {
+ /* Unless an affinity change also wants it elsewhere. */
+ if (cpumask_test_cpu(smp_processor_id(), &p->cpus_mask))
+ return;
+ dest = -1;
+ } else {
+ this_cpu_inc(kw_move_stats.followed);
+ }
+ }
+ kw_stay_schedule(dest);
+}
+
+/*
+ * The scheduler would have moved @p, held, to @cpu (sched_exec(), a wakeup
+ * on a busy CPU while @cpu was idle): let a user task try on its way to
+ * user mode (kw_exit_to_user_move()). Called with p->pi_lock held, for
+ * current or a task being woken, so no kick.
+ */
+void arch_stay_move_to(struct task_struct *p, int cpu)
+{
+ if (p->flags & (PF_KTHREAD | PF_USER_WORKER))
+ return;
+ p->thread.move_to = cpu + 1;
+ set_tsk_thread_flag(p, TIF_KW_MOVE);
+}
+
+/*
+ * A user task switched out in kw_exit_to_user_schedule() starts on this
+ * CPU on a fresh stack: finish that schedule() and run the exit to user
+ * mode again from the top. What the old pass had still to do (a signal,
+ * notify-resume work, another reschedule) is in the TIF flags, which only
+ * the task itself clears; its system call's exit work (tracing, a ptrace
+ * stop, audit) came before the reschedule and is not repeated; pt_regs
+ * (cause, a0 for a restart) are as the old pass left them.
+ */
+static void __noreturn kw_user_resume(struct task_struct *prev)
+{
+ struct pt_regs *regs = current_pt_regs();
+
+ sched_stay_switch_tail(prev);
+ local_irq_disable();
+ irqentry_exit_to_user_mode(regs);
+ user_mode_loop(regs);
+}
+
+/*
+ * An affinity change that excludes a held task's CPU (kernel/sched/core.c):
+ * a user task moves on its way to user mode, a kthread only as
+ * arch_kthread_move() moves itself. Others get EBUSY.
+ */
+bool arch_stay_may_move(struct task_struct *p)
+{
+ if (p->flags & PF_KTHREAD)
+ return p == current && p->thread.restart_fn;
+ return !(p->flags & PF_USER_WORKER);
+}
+
+void arch_stay_move(struct task_struct *p)
+{
+ if (p->flags & PF_KTHREAD)
+ return;
+ set_tsk_thread_flag(p, TIF_KW_MOVE);
+ /* In user mode on another CPU: make it enter the kernel and leave again. */
+ kick_process(p);
+}
+
+void arch_kthread_move(int cpu, int (*fn)(void *), void *arg)
+{
+ struct task_struct *p = current;
+
+ if (WARN_ON_ONCE(!(p->flags & PF_KTHREAD) || p->thread.restart_fn))
+ return;
+ p->thread.restart_arg = arg;
+ p->thread.restart_fn = fn;
+ /*
+ * The affinity is recorded without waiting (arch_stay_may_move()),
+ * and sched_stay_release() has the stopper move this thread once it
+ * is off the CPU; switched in there, it starts on a fresh stack.
+ */
+ if (!set_cpus_allowed_ptr(p, cpumask_of(cpu)) && sched_stay_release(-1)) {
+ schedule();
+ /* Picked again here: it did not move (cpu not active?). */
+ migrate_disable();
+ }
+ p->thread.restart_fn = NULL;
+}
+#endif
+
/*
* Called from ret_from_fork (entry.S) on the new task's fresh Wasm stack:
- * a task's first run, or a parked task resuming (park.c).
+ * a task's first run, a task that moved to this CPU (SMP), or a parked
+ * task resuming (park.c).
*/
asmlinkage void __ret_from_fork(struct task_struct *prev)
{
struct pt_regs *regs = current_pt_regs();
+#ifdef CONFIG_SMP
+ /*
+ * From now on the task's wasm stack lives in this CPU's thread, which
+ * alone can resume it: hold it here (ARCH_TASKS_STAY_ON_CPU). Still
+ * in the switch, with the runqueue locked, so nothing moved it yet.
+ */
+ migrate_disable();
+ if (current->thread.restart_fn) {
+ int (*fn)(void *) = current->thread.restart_fn;
+
+ /* A kthread woken here from arch_kthread_restart_point(). */
+ current->thread.restart_fn = NULL;
+ schedule_tail(prev);
+ kthread_exit(fn(current->thread.restart_arg));
+ }
+ if (current->thread.movable) {
+ current->thread.movable = 0;
+ kw_user_resume(prev);
+ }
+#endif
if (unlikely(READ_ONCE(current->thread.park_state) == KW_PARK_RESUMING))
kw_park_resume(prev);
@@ -94,6 +417,19 @@ int copy_thread(struct task_struct *p, const struct kernel_clone_args *args)
p->thread.park_fn = NULL;
p->thread.park_arg = NULL;
p->thread.park_state = KW_PARK_NONE;
+#ifdef CONFIG_SMP
+ p->thread.restart_fn = NULL;
+ p->thread.movable = 0;
+ p->thread.move_to = 0;
+ clear_ti_thread_flag(task_thread_info(p), TIF_KW_MOVE);
+ /*
+ * Not the parent's hold (fork copies migration_disabled and, for a
+ * migration-disabled parent, cpus_ptr): the child may start on any
+ * CPU its affinity allows, and is held where it first runs.
+ */
+ p->migration_disabled = 0;
+ p->cpus_ptr = &p->cpus_mask;
+#endif
return 0;
}
diff --git a/arch/wasm/kernel/setup.c b/arch/wasm/kernel/setup.c
index bcd73515a90..6b58421e047 100644
--- a/arch/wasm/kernel/setup.c
+++ b/arch/wasm/kernel/setup.c
@@ -9,6 +9,7 @@
#include <asm/processor.h>
#include <asm/random.h>
#include <asm/sections.h>
+#include <asm/smp.h>
#include <asm/wasm.h>
unsigned long memory_start;
@@ -39,6 +40,18 @@ void __init setup_arch(char **cmdline_p)
memblock_add(memory_start, memory_end - memory_start);
memblock_reserve(memory_start, kernel_end - memory_start);
+#ifdef CONFIG_SMP
+ /*
+ * With a shared memory the data segments are passive, and the start
+ * function (__wasm_init_memory) of every instance of the module
+ * initialises them only if a word that wasm-ld places after all the
+ * data, past _end, is 0; it leaves it at 2. The other CPUs' instances
+ * start later, so it must stay 2: keep it from the allocator. Only the
+ * host can see where it is (the module exports its address).
+ */
+ if (wasm_init_flag())
+ memblock_reserve(wasm_init_flag(), sizeof(u32));
+#endif
#ifdef CONFIG_BLK_DEV_INITRD
wasm_load_initrd();
@@ -53,4 +66,5 @@ void __init setup_arch(char **cmdline_p)
paging_init();
setup_boot_rng();
+ kw_smp_init_cpus();
}
diff --git a/arch/wasm/kernel/signal.c b/arch/wasm/kernel/signal.c
index 3eceaadeb6e..5df45d42d6e 100644
--- a/arch/wasm/kernel/signal.c
+++ b/arch/wasm/kernel/signal.c
@@ -18,8 +18,7 @@
#include <asm/ucontext.h>
#include <asm/syscall.h>
#include <asm/kw_emu.h>
-
-extern struct kw_cpu *const wasm_kw_cpu;
+#include <asm/kwcpu.h>
struct rt_sigframe {
struct siginfo info;
diff --git a/arch/wasm/kernel/smp.c b/arch/wasm/kernel/smp.c
new file mode 100644
index 00000000000..ec63ba2d518
--- /dev/null
+++ b/arch/wasm/kernel/smp.c
@@ -0,0 +1,174 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * SMP: one instance of the kernel module per CPU, each in its own host
+ * thread, all on one shared memory. CPU 0 boots as on UP; __cpu_up() asks
+ * the host for another instance (wasm_cpu_start()), which enters at
+ * kw_secondary_entry (entry.S) with the CPU's idle task.
+ *
+ * IPIs are bits in the target's word of pending interrupts (irq.c,
+ * kw_irq_raise()), taken at its next poll point: a user slice end (kwemu
+ * polls the word every block), idle (where the sender's notify wakes it),
+ * an interrupt enable, or cpu_relax().
+ *
+ * A task's wasm stack lives in the thread of the CPU that started it, so
+ * the task is held there (migration-disabled from its first run,
+ * ARCH_TASKS_STAY_ON_CPU) except where the stack can be dropped: a user
+ * task at the reschedule on its way to user mode, a kthread at a restart
+ * point. Moved, it starts on a fresh stack (process.c).
+ */
+
+#include <linux/cpu.h>
+#include <linux/delay.h>
+#include <linux/interrupt.h>
+#include <linux/memblock.h>
+#include <linux/sched/mm.h>
+#include <linux/sched/task_stack.h>
+#include <linux/smp.h>
+#include <asm/irq.h>
+#include <asm/kwcpu.h>
+#include <asm/time.h>
+#include <asm/wasm.h>
+
+static DECLARE_COMPLETION(cpu_running);
+
+void __init kw_smp_init_cpus(void)
+{
+ int n = min_t(int, wasm_cpu_count(), nr_cpu_ids), cpu;
+
+ for (cpu = 1; cpu < n; cpu++) {
+ /* kwemu's state (KW_CPU_SIZE, 9 MiB) for each further CPU. */
+ kw_cpus[cpu] = memblock_alloc_raw(KW_CPU_SIZE, SMP_CACHE_BYTES);
+ if (!kw_cpus[cpu]) {
+ pr_warn("smp: no memory for CPU%d's kwemu state\n", cpu);
+ break;
+ }
+ set_cpu_possible(cpu, true);
+ set_cpu_present(cpu, true);
+ }
+}
+
+void __init smp_prepare_cpus(unsigned int max_cpus)
+{
+}
+
+void __init smp_cpus_done(unsigned int max_cpus)
+{
+}
+
+int __cpu_up(unsigned int cpu, struct task_struct *tidle)
+{
+ int ret;
+
+ tidle->thread_info.cpu = cpu;
+ ret = wasm_cpu_start(cpu, tidle);
+ if (ret) {
+ pr_crit("CPU%u: the host cannot start it (%d)\n", cpu, ret);
+ return ret;
+ }
+ /* The host starts a thread and instantiates the module: give it time. */
+ wait_for_completion_timeout(&cpu_running, secs_to_jiffies(30));
+ if (!cpu_online(cpu)) {
+ pr_crit("CPU%u: failed to come online\n", cpu);
+ return -EIO;
+ }
+ return 0;
+}
+
+static void kw_irq_word_set(u32 *word)
+{
+ __asm__ volatile("local.get %0\n\t"
+ "global.set kw_irq_word" : : "r"(word) : "memory");
+}
+
+asmlinkage void __noreturn kw_secondary_start(void)
+{
+ unsigned int cpu = smp_processor_id();
+ struct mm_struct *mm = &init_mm;
+
+ kw_irq_word_set(kw_irq_word_of(cpu));
+ /* The idle task runs on this, the thread's first stack. */
+ current_thread_info()->flags &= ~_TIF_NEVER_RUN;
+ current->thread.stack_cpu = cpu;
+ kw_cpu_start();
+
+ mmgrab(mm);
+ current->active_mm = mm;
+
+ notify_cpu_starting(cpu);
+ kw_timer_start_cpu();
+ set_cpu_online(cpu, true);
+ complete(&cpu_running);
+
+ local_irq_enable();
+ cpu_startup_entry(CPUHP_AP_ONLINE_IDLE);
+}
+
+void arch_smp_send_reschedule(int cpu)
+{
+ kw_irq_raise(cpu, BIT(KW_IPI_RESCHEDULE));
+}
+
+void arch_send_call_function_single_ipi(int cpu)
+{
+ kw_irq_raise(cpu, BIT(KW_IPI_CALL_FUNC));
+}
+
+void arch_send_call_function_ipi_mask(const struct cpumask *mask)
+{
+ int cpu;
+
+ for_each_cpu(cpu, mask)
+ kw_irq_raise(cpu, BIT(KW_IPI_CALL_FUNC));
+}
+
+static void __noreturn kw_ipi_stop(void)
+{
+ static int never;
+
+ set_cpu_online(smp_processor_id(), false);
+ local_irq_disable();
+ for (;;) {
+ /*
+ * CPU 0 suspends instead of blocking its thread: the host
+ * there still has to take the exit (a panic) from the CPU that
+ * stopped it. Its idle wait ends as soon as its word of pending
+ * interrupts is not 0, so clear the word first: a stop bit left
+ * there (taken in cpu_relax(), or raised again by a CPU whose
+ * session ended) would end every wait at once, and the host,
+ * resuming CPU 0 without end, would never get to that exit.
+ */
+ if (smp_processor_id() == 0) {
+ xchg(kw_irq_word_of(0), 0);
+ wasm_idle(-1);
+ } else
+ __builtin_wasm_memory_atomic_wait32(&never, 0, -1);
+ }
+}
+
+void kw_handle_ipis(u32 bits)
+{
+ if (bits & BIT(KW_IPI_RESCHEDULE))
+ scheduler_ipi();
+ if (bits & BIT(KW_IPI_CALL_FUNC))
+ generic_smp_call_function_interrupt();
+ if (bits & BIT(KW_IPI_STOP))
+ kw_ipi_stop();
+}
+
+void smp_send_stop(void)
+{
+ unsigned long timeout = USEC_PER_SEC;
+ int cpu;
+
+ if (num_online_cpus() > 1) {
+ for_each_online_cpu(cpu)
+ if (cpu != smp_processor_id())
+ kw_irq_raise(cpu, BIT(KW_IPI_STOP));
+ }
+ /* Up to one second for the others to take it. */
+ while (num_online_cpus() > 1 && timeout--)
+ udelay(1);
+ if (num_online_cpus() > 1)
+ pr_warn("smp: failed to stop secondary CPUs %*pbl\n",
+ cpumask_pr_args(cpu_online_mask));
+}
diff --git a/arch/wasm/kernel/sys_riscv.c b/arch/wasm/kernel/sys_riscv.c
index 5ac30437666..775eae39dbe 100644
--- a/arch/wasm/kernel/sys_riscv.c
+++ b/arch/wasm/kernel/sys_riscv.c
@@ -7,9 +7,7 @@
#include <asm/hwprobe.h>
#define SYS_RISCV_FLUSH_ICACHE_ALL 1UL
-#include <asm/kw_emu.h>
-
-extern struct kw_cpu *const wasm_kw_cpu;
+#include <asm/tlbflush.h>
SYSCALL_DEFINE6(mmap, unsigned long, addr, unsigned long, len,
unsigned long, prot, unsigned long, flags,
@@ -27,7 +25,7 @@ SYSCALL_DEFINE3(riscv_flush_icache, uintptr_t, start, uintptr_t, end,
if (flags & ~SYS_RISCV_FLUSH_ICACHE_ALL)
return -EINVAL;
/* Drop translations; the emulator re-decodes from memory. */
- kw_flush_tlb_all(wasm_kw_cpu);
+ kw_flush_icache_all();
return 0;
}
diff --git a/arch/wasm/kernel/time.c b/arch/wasm/kernel/time.c
index 52a4707efc1..dc8e6f8c3e4 100644
--- a/arch/wasm/kernel/time.c
+++ b/arch/wasm/kernel/time.c
@@ -10,7 +10,11 @@
#include <asm/time.h>
#include <asm/wasm.h>
+#ifdef CONFIG_SMP
+DEFINE_PER_CPU(long long, kw_timer_expiry) = -1;
+#else
long long wasm_timer_expiry = -1;
+#endif
static u64 wasm_clocksource_read(struct clocksource *cs)
{
@@ -44,14 +48,14 @@ static int wasm_clockevent_shutdown(struct clock_event_device *dev)
return 0;
}
-static struct clock_event_device wasm_clockevent = {
- .name = "wasm_timer",
- .features = CLOCK_EVT_FEAT_ONESHOT,
- .rating = 300,
- .set_next_event = wasm_clockevent_set_next_event,
- .set_state_shutdown = wasm_clockevent_shutdown,
- .set_state_oneshot_stopped = wasm_clockevent_shutdown,
-};
+#define WASM_CLOCKEVENT_INIT { \
+ .name = "wasm_timer", \
+ .features = CLOCK_EVT_FEAT_ONESHOT, \
+ .rating = 300, \
+ .set_next_event = wasm_clockevent_set_next_event, \
+ .set_state_shutdown = wasm_clockevent_shutdown, \
+ .set_state_oneshot_stopped = wasm_clockevent_shutdown, \
+}
static irqreturn_t wasm_timer_interrupt(int irq, void *dev_id)
{
@@ -69,6 +73,39 @@ void read_persistent_clock64(struct timespec64 *ts)
ts->tv_nsec = ns - ts->tv_sec * NSEC_PER_SEC;
}
+#ifdef CONFIG_SMP
+/*
+ * One clockevent per CPU, each with its own expiry, checked by that CPU
+ * against the host clock (wasm_timer_timeout(), irq.c); IRQ 0 is a per-CPU
+ * interrupt.
+ */
+static DEFINE_PER_CPU(struct clock_event_device, wasm_clockevent) = WASM_CLOCKEVENT_INIT;
+
+/* On the CPU itself: the boot CPU from time_init(), the others from smp.c. */
+void kw_timer_start_cpu(void)
+{
+ struct clock_event_device *ce = this_cpu_ptr(&wasm_clockevent);
+
+ ce->cpumask = cpumask_of(smp_processor_id());
+ ce->irq = WASM_IRQ_TIMER;
+ clockevents_config_and_register(ce, NSEC_PER_SEC, 1000, ULONG_MAX);
+ enable_percpu_irq(WASM_IRQ_TIMER, IRQ_TYPE_NONE);
+}
+
+void __init time_init(void)
+{
+ sched_clock_register(wasm_sched_clock_read, 64, NSEC_PER_SEC);
+ if (clocksource_register_khz(&wasm_clocksource, 1000000))
+ panic("wasm: cannot register clocksource");
+
+ if (request_percpu_irq(WASM_IRQ_TIMER, wasm_timer_interrupt,
+ "wasm-timer", &wasm_clockevent))
+ panic("wasm: cannot request timer irq");
+ kw_timer_start_cpu();
+}
+#else
+static struct clock_event_device wasm_clockevent = WASM_CLOCKEVENT_INIT;
+
void __init time_init(void)
{
sched_clock_register(wasm_sched_clock_read, 64, NSEC_PER_SEC);
@@ -84,3 +121,4 @@ void __init time_init(void)
clockevents_config_and_register(&wasm_clockevent, NSEC_PER_SEC, 1000,
ULONG_MAX);
}
+#endif
diff --git a/arch/wasm/kernel/traps.c b/arch/wasm/kernel/traps.c
index f1deec5f5b3..b439f07ef39 100644
--- a/arch/wasm/kernel/traps.c
+++ b/arch/wasm/kernel/traps.c
@@ -16,12 +16,11 @@
#include <asm/entry.h>
#include <asm/irq.h>
#include <asm/kw_emu.h>
+#include <asm/kwcpu.h>
#include <asm/park.h>
#include <asm/syscall.h>
#include <asm/wasm.h>
-extern struct kw_cpu *const wasm_kw_cpu;
-
/*
* Instructions per slice; timers, host IRQs and the host yield are checked
* between slices. The slice belongs to the CPU, not to one kw_run() call:
@@ -36,7 +35,12 @@ extern struct kw_cpu *const wasm_kw_cpu;
/* Let the host event loop breathe at least this often while user code runs. */
#define KW_YIELD_NS (20 * NSEC_PER_MSEC)
+#ifdef CONFIG_SMP
+static DEFINE_PER_CPU(u64, last_yield_ns_pcpu);
+#define last_yield_ns (*this_cpu_ptr(&last_yield_ns_pcpu))
+#else
static u64 last_yield_ns;
+#endif
int show_unhandled_signals = 1;
@@ -96,6 +100,12 @@ static void do_user_interrupt(struct pt_regs *regs)
{
u64 now = wasm_cpu_clock_get_monotonic();
+ /*
+ * SMP: every CPU yields to its own host. CPU 0's serves the devices;
+ * the others' event loops run the engine's housekeeping, without
+ * which modules the JIT freed are never collected (finalizers and
+ * the collector's last pass run as tasks there).
+ */
if (now - last_yield_ns >= KW_YIELD_NS) {
wasm_yield();
last_yield_ns = wasm_cpu_clock_get_monotonic();
@@ -121,8 +131,18 @@ void __noreturn user_mode_loop(struct pt_regs *regs)
if (unlikely(READ_ONCE(kw_park_users)))
kw_park_user();
- /* "sret": user mode runs with interrupts enabled. */
+ /*
+ * "sret": user mode runs with interrupts enabled. On SMP without
+ * taking what is pending here: kw_run() sees it at once
+ * (KW_EV_INTERRUPT), and do_user_interrupt() then takes it on
+ * the way to user mode, where a reschedule is honoured.
+ */
+#ifdef CONFIG_SMP
+ trace_hardirqs_on();
+ kw_irq_flags_set(ARCH_IRQ_ENABLED);
+#else
local_irq_enable();
+#endif
ev = kw_run(cpu, &regs->user);
local_irq_disable();
diff --git a/arch/wasm/kernel/wasi.c b/arch/wasm/kernel/wasi.c
index f96cf96b2cf..62c43ddb405 100644
--- a/arch/wasm/kernel/wasi.c
+++ b/arch/wasm/kernel/wasi.c
@@ -4,12 +4,13 @@
* and yield (poll_oneoff, sched_yield), exit (proc_exit), the command line
* (the program arguments) and the initrd (a file in a preopened directory).
*
- * The kernel is single-threaded and nothing runs while a host call is in
- * progress (a suspended call only lets the host event loop run), so the
- * static argument buffers below are never used by two calls at once. They
- * are in the kernel image, below 4 GiB, as the wasm32 ABI of preview 1
- * requires; console data that may be anywhere in RAM is copied through
- * wasi_bounce when it is not.
+ * A CPU runs nothing else while a host call is in progress (a suspended
+ * call only lets the host event loop run), so the static argument buffers
+ * below are never used by two calls at once: the clock and write ones are
+ * per CPU, and the rest (console input, idle, yield) is used by CPU 0
+ * alone on SMP. They are in the kernel image, below 4 GiB, as the wasm32
+ * ABI of preview 1 requires; console data that may be anywhere in RAM is
+ * copied through the bounce buffer when it is not.
*/
#include <linux/init.h>
@@ -19,7 +20,9 @@
#include <linux/minmax.h>
#include <linux/printk.h>
#include <linux/sizes.h>
+#include <linux/smp.h>
#include <linux/string.h>
+#include <linux/atomic.h>
#include <linux/time64.h>
#include <asm/irq.h>
#include <asm/page.h>
@@ -33,10 +36,18 @@
#define WASI_POLL_CLOCK BIT(0)
#define WASI_POLL_STDIN BIT(1)
-static u8 wasi_bounce[512];
-static struct wasi_iovec wasi_iov;
-static u32 wasi_nbytes;
-static u64 wasi_time;
+static struct wasi_cpu_buf {
+ u8 bounce[512];
+ struct wasi_iovec iov;
+ u32 nbytes;
+ u64 time;
+} ____cacheline_aligned wasi_cpu_bufs[NR_CPUS];
+
+#define wasi_buf (&wasi_cpu_bufs[raw_smp_processor_id()])
+#define wasi_bounce (wasi_buf->bounce)
+#define wasi_iov (wasi_buf->iov)
+#define wasi_nbytes (wasi_buf->nbytes)
+#define wasi_time (wasi_buf->time)
static struct wasi_subscription wasi_subs[2];
static struct wasi_event wasi_events[2];
static u32 wasi_nevents;
@@ -187,8 +198,13 @@ static bool wasi_stdin_ready(void)
static void wasi_raise_console_irq(void)
{
+#ifdef CONFIG_SMP
+ /* Other CPUs set IPI bits in the same word. */
+ atomic_or(BIT(WASM_IRQ_CONSOLE), (atomic_t *)&wasm_host_irqs);
+#else
WRITE_ONCE(wasm_host_irqs,
READ_ONCE(wasm_host_irqs) | BIT(WASM_IRQ_CONSOLE));
+#endif
}
ssize_t wasm_console_read(u8 *buf, size_t count)
@@ -231,6 +247,11 @@ void wasm_idle(long long timeout_ns)
void wasm_yield(void)
{
wasi_sched_yield();
+#ifdef CONFIG_SMP
+ /* Only CPU 0's host has stdin (and takes the console interrupt). */
+ if (smp_processor_id())
+ return;
+#endif
/* A host that cannot raise WASM_IRQ_CONSOLE by itself (plain WASI). */
if (wasi_stdin_ready())
wasi_raise_console_irq();
diff --git a/arch/wasm/mm/fault.c b/arch/wasm/mm/fault.c
index 553d1c3e541..959f2396685 100644
--- a/arch/wasm/mm/fault.c
+++ b/arch/wasm/mm/fault.c
@@ -16,25 +16,31 @@
#include <linux/hugetlb.h>
#include <asm/entry.h>
#include <asm/kw_emu.h>
+#include <asm/kwcpu.h>
#include <asm/pgtable.h>
#include <asm/tlbflush.h>
-extern struct kw_cpu *const wasm_kw_cpu;
-
-/* Find the PTE for @addr in @mm, or NULL if no page table covers it. */
+/*
+ * Find the PTE for @addr in @mm, or NULL if no page table covers it. Runs
+ * without the mmap lock or the PTE lock, as a hardware walker: another CPU
+ * may clear an entry meanwhile (free_pgtables() after munmap() downgraded
+ * to a read lock), so each level is read once and the next table found
+ * from that value (as gup-fast does); the table itself stays allocated
+ * until that CPU's flush, which waits for this one (kw_user_addr()).
+ */
static pte_t *kw_walk(struct mm_struct *mm, unsigned long addr)
{
pgd_t *pgd = pgd_offset(mm, addr);
p4d_t *p4d = p4d_offset(pgd, addr);
- pud_t *pud = pud_offset(p4d, addr);
- pmd_t *pmd;
+ pud_t pud = __pud(READ_ONCE(pud_val(*pud_offset(p4d, addr))));
+ pmd_t pmd;
- if (pud_none(*pud) || !pud_present(*pud))
+ if (pud_none(pud) || !pud_present(pud))
return NULL;
- pmd = pmd_offset(pud, addr);
- if (pmd_none(*pmd) || !(pmd_val(*pmd) & _PAGE_PRESENT))
+ pmd = __pmd(READ_ONCE(pmd_val(*(pud_pgtable(pud) + pmd_index(addr)))));
+ if (pmd_none(pmd) || !(pmd_val(pmd) & _PAGE_PRESENT))
return NULL;
- return pte_offset_kernel(pmd, addr);
+ return (pte_t *)pmd_page_vaddr(pmd) + pte_index(addr);
}
static bool access_error(unsigned int access, struct vm_area_struct *vma)
@@ -49,6 +55,23 @@ static bool access_error(unsigned int access, struct vm_area_struct *vma)
}
}
+/*
+ * Set A/D (@bits) in the PTE at @ptep, which held @v. On SMP atomically, as
+ * a hardware walker does: the generic code changes PTEs under the PTE lock
+ * but this runs without it, so a plain store could bring back a PTE that
+ * another CPU just cleared or write-protected (pgtable.h makes those
+ * atomic too). False if the PTE changed meanwhile.
+ */
+static bool kw_set_ad(pte_t *ptep, unsigned long v, unsigned long bits)
+{
+#ifdef CONFIG_SMP
+ return try_cmpxchg((unsigned long *)ptep, &v, v | bits);
+#else
+ set_pte(ptep, __pte(v | bits));
+ return true;
+#endif
+}
+
/*
* What a hardware walker with Svadu would do: the mapping allows the access
* but A (or D for a store) is clear. Returns true if fixed.
@@ -61,7 +84,7 @@ static bool kw_fixup_ad(struct mm_struct *mm, unsigned long addr,
if (!ptep)
return false;
- v = pte_val(*ptep);
+ v = pte_val(READ_ONCE(*ptep));
if (!(v & _PAGE_PRESENT) || !(v & _PAGE_USER))
return false;
need = access == KW_ACCESS_WRITE ? _PAGE_WRITE :
@@ -69,8 +92,8 @@ static bool kw_fixup_ad(struct mm_struct *mm, unsigned long addr,
if (!(v & need))
return false;
need = _PAGE_ACCESSED | (access == KW_ACCESS_WRITE ? _PAGE_DIRTY : 0);
- if ((v & need) != need)
- set_pte(ptep, __pte(v | need));
+ if ((v & need) != need && !kw_set_ad(ptep, v, need))
+ return false; /* changed under us: the full fault path decides */
kw_flush_tlb_range(wasm_kw_cpu, addr & PAGE_MASK,
(addr & PAGE_MASK) + PAGE_SIZE);
return true;
@@ -182,6 +205,14 @@ void do_user_page_fault(struct pt_regs *regs, unsigned long addr,
/* ---------------------------------------------------------------------- */
+/*
+ * The kernel address of @len bytes (within one page) at user @uaddr, faulted
+ * in. SMP: valid until the caller's next poll point (an interrupt enable,
+ * cpu_relax(), idle), which the copies below do not reach: a CPU that
+ * unmaps the page or frees the page table waits for this CPU's answer to
+ * its TLB shootdown first (tlb.c), as gup-fast relies on interrupts being
+ * off.
+ */
void *kw_user_addr(const void __user *uaddr, size_t len, bool write)
{
unsigned long addr = (unsigned long)uaddr;
@@ -208,7 +239,7 @@ void *kw_user_addr(const void __user *uaddr, size_t len, bool write)
for (;;) {
pte_t *ptep = kw_walk(mm, addr);
- unsigned long v = ptep ? pte_val(*ptep) : 0;
+ unsigned long v = ptep ? pte_val(READ_ONCE(*ptep)) : 0;
unsigned long need = _PAGE_PRESENT | _PAGE_USER |
(write ? _PAGE_WRITE : _PAGE_READ);
@@ -217,7 +248,8 @@ void *kw_user_addr(const void __user *uaddr, size_t len, bool write)
(write ? _PAGE_DIRTY : 0);
if ((v & ad) != ad) {
- set_pte(ptep, __pte(v | ad));
+ if (!kw_set_ad(ptep, v, ad))
+ continue; /* changed under us: walk again */
kw_flush_tlb_range(wasm_kw_cpu, addr & PAGE_MASK,
(addr & PAGE_MASK) + PAGE_SIZE);
}
diff --git a/arch/wasm/mm/tlb.c b/arch/wasm/mm/tlb.c
index d4509d6b89e..f0d1a12c122 100644
--- a/arch/wasm/mm/tlb.c
+++ b/arch/wasm/mm/tlb.c
@@ -1,23 +1,45 @@
/* SPDX-License-Identifier: GPL-2.0-only */
/*
- * The kwemu software CPU: one per (single) kernel CPU. Its translation cache
- * plays the role of the TLB for the currently loaded user page table.
+ * The kwemu software CPU: one per kernel CPU. Its translation cache plays
+ * the role of the TLB for the currently loaded user page table.
+ *
+ * SMP: each CPU's kwemu belongs to its own thread, so another CPU's TLB is
+ * flushed by an IPI to it (smp_call_function_many(), waiting for the
+ * answer), to the CPUs in the mm's mm_cpumask: those whose kwemu has that
+ * page table loaded (switch_mm() keeps it so), except those in lazy TLB
+ * mode, which flush when they use the mm again (below). Pages and page
+ * tables are freed only after such a flush (mmu_gather), and the software
+ * uaccess walk (fault.c) has no poll point between its walk and the end of
+ * its copy, so a CPU that is copying cannot answer before it is done.
+ * A PTE that only gains access needs no other CPU's flush
+ * (update_mmu_cache_range()).
*/
#include <linux/init.h>
#include <linux/mm.h>
#include <linux/sched.h>
+#include <linux/smp.h>
#include <asm/hwcap.h>
-#include <asm/kw_emu.h>
+#include <asm/irq.h>
+#include <asm/kwcpu.h>
#include <asm/mmu_context.h>
#include <asm/tlbflush.h>
#include <asm/wasm.h>
static u64 kw_cpu_storage[KW_CPU_SIZE / sizeof(u64)] __aligned(64);
+
+#ifdef CONFIG_SMP
+struct kw_cpu *kw_cpus[NR_CPUS] = { (struct kw_cpu *)kw_cpu_storage };
+
+/* The mm whose page table this CPU's kwemu walks. */
+static DEFINE_PER_CPU(struct mm_struct *, kw_loaded_mm_pcpu);
+#define kw_loaded_mm (*this_cpu_ptr(&kw_loaded_mm_pcpu))
+#else
struct kw_cpu *const wasm_kw_cpu = (struct kw_cpu *)kw_cpu_storage;
/* The mm whose page table the emulator currently walks. */
static struct mm_struct *kw_loaded_mm;
+#endif
static int __init kw_cpu_setup(void)
{
@@ -36,15 +58,204 @@ static int __init kw_cpu_setup(void)
}
early_initcall(kw_cpu_setup);
+#ifdef CONFIG_SMP
+/* A secondary CPU sets up its kwemu (smp.c), with the ISA CPU 0 enabled. */
+void kw_cpu_start(void)
+{
+ struct kw_cpu *cpu = wasm_kw_cpu;
+
+ kw_cpu_init(cpu);
+ kw_set_isa(cpu, kw_isa_enabled());
+ cpu->phys_base = 0;
+ cpu->irq_pending = kw_irq_word_of(smp_processor_id());
+ kw_set_pgd(cpu, __pa(swapper_pg_dir));
+ kw_loaded_mm = &init_mm;
+}
+#endif
+
+#ifdef CONFIG_SMP
+/*
+ * Lazy TLB: running a kthread or idle, a CPU keeps the user mm it had
+ * (kw_loaded_mm, still in that mm's mm_cpumask) without using it. A flush
+ * does not wait for such a CPU (an idle one would have to wake its host
+ * thread): it marks the CPU stale instead, and the CPU flushes when it
+ * switches back to that mm (as x86 does). The pairing:
+ * flusher: stale = 1; smp_mb(); lazy? skip : IPI
+ * back to the mm: lazy = 0; smp_mb(); stale? flush
+ * so either the flusher sees the CPU in use and waits for it, or the CPU
+ * sees the mark. A lazy CPU runs no user code and does no uaccess walk
+ * (its task has no mm; kthread_use_mm() goes through switch_mm()), and
+ * kwemu walks the table only when it runs user code and caches no table
+ * entries, so page tables may be freed without its answer as well (x86
+ * still waits then, for its hardware's speculative walks). Switching to
+ * another mm drops everything anyway (kw_set_pgd()).
+ */
+static DEFINE_PER_CPU(int, kw_tlb_lazy);
+static DEFINE_PER_CPU(int, kw_tlb_stale);
+
+void enter_lazy_tlb(struct mm_struct *mm, struct task_struct *tsk)
+{
+ if (mm != &init_mm)
+ this_cpu_write(kw_tlb_lazy, 1);
+}
+#endif
+
void switch_mm(struct mm_struct *prev, struct mm_struct *next,
struct task_struct *task)
{
+#ifdef CONFIG_SMP
+ if (next == kw_loaded_mm) {
+ if (this_cpu_read(kw_tlb_lazy)) {
+ this_cpu_write(kw_tlb_lazy, 0);
+ smp_mb();
+ if (this_cpu_read(kw_tlb_stale)) {
+ this_cpu_write(kw_tlb_stale, 0);
+ kw_flush_tlb_all(wasm_kw_cpu);
+ }
+ }
+ return;
+ }
+ /* In use from here: a flusher that sees the mask bit below waits. */
+ this_cpu_write(kw_tlb_lazy, 0);
+ smp_mb();
+ this_cpu_write(kw_tlb_stale, 0);
+#else
if (next == kw_loaded_mm)
return;
+#endif
+#ifdef CONFIG_SMP
+ /*
+ * In the mask before the page table is loaded: a flush from now on
+ * reaches this CPU, and kw_set_pgd() drops everything older. The
+ * previous mm is still referenced (lazy TLB refcount), and nothing of
+ * it stays cached here.
+ */
+ cpumask_set_cpu(smp_processor_id(), mm_cpumask(next));
kw_set_pgd(wasm_kw_cpu, __pa(next->pgd));
+ cpumask_clear_cpu(smp_processor_id(), mm_cpumask(kw_loaded_mm));
+#else
+ kw_set_pgd(wasm_kw_cpu, __pa(next->pgd));
+#endif
kw_loaded_mm = next;
}
+#ifdef CONFIG_SMP
+struct kw_flush {
+ struct mm_struct *mm; /* NULL: every mm */
+ unsigned long start, end; /* end 0: the whole mm */
+};
+
+static void kw_flush_local(void *info)
+{
+ const struct kw_flush *f = info;
+
+ if (f->mm && f->mm != kw_loaded_mm)
+ return;
+ if (f->end)
+ kw_flush_tlb_range(wasm_kw_cpu, f->start, f->end);
+ else
+ kw_flush_tlb_all(wasm_kw_cpu);
+}
+
+/* Flush here and on every other CPU that has @mm loaded, and wait for them. */
+static void kw_flush_mm(struct mm_struct *mm, unsigned long start,
+ unsigned long end)
+{
+ struct kw_flush f = { .mm = mm, .start = start, .end = end };
+ int self = get_cpu(), cpu;
+ cpumask_t wait;
+
+ kw_flush_local(&f);
+ cpumask_clear(&wait);
+ for_each_cpu(cpu, mm_cpumask(mm)) {
+ if (cpu == self)
+ continue;
+ if (READ_ONCE(per_cpu(kw_tlb_lazy, cpu))) {
+ WRITE_ONCE(per_cpu(kw_tlb_stale, cpu), 1);
+ smp_mb();
+ if (READ_ONCE(per_cpu(kw_tlb_lazy, cpu)))
+ continue;
+ }
+ __cpumask_set_cpu(cpu, &wait);
+ }
+ if (!cpumask_empty(&wait))
+ smp_call_function_many(&wait, kw_flush_local, &f, true);
+ put_cpu();
+}
+
+void flush_tlb_all(void)
+{
+ struct kw_flush f = { };
+
+ on_each_cpu(kw_flush_local, &f, 1);
+}
+
+void flush_tlb_mm(struct mm_struct *mm)
+{
+ kw_flush_mm(mm, 0, 0);
+}
+
+void flush_tlb_page(struct vm_area_struct *vma, unsigned long addr)
+{
+ kw_flush_mm(vma->vm_mm, addr & PAGE_MASK, (addr & PAGE_MASK) + PAGE_SIZE);
+}
+
+void flush_tlb_range(struct vm_area_struct *vma, unsigned long start,
+ unsigned long end)
+{
+ kw_flush_mm(vma->vm_mm, start, end);
+}
+
+/*
+ * A PTE that became present, writable, young or dirty with the same page
+ * (the cases that end here, and the spurious-fault flush) needs no other
+ * CPU's flush: kwemu caches only translations that allowed the access
+ * when they were filled, never a non-present or narrower entry that would
+ * hide the new one (separate read and write TLBs; a miss walks the table),
+ * so another CPU at worst walks again. Every change that removes access or
+ * moves the page flushes first (ptep_clear_flush(), flush_tlb_*()). The
+ * local flush only mirrors riscv's update_mmu_cache_range().
+ */
+void update_mmu_cache_range(struct vm_fault *vmf, struct vm_area_struct *vma,
+ unsigned long addr, pte_t *ptep, unsigned int nr)
+{
+ if (vma->vm_mm == kw_loaded_mm)
+ kw_flush_tlb_range(wasm_kw_cpu, addr,
+ addr + (unsigned long)nr * PAGE_SIZE);
+}
+
+void kw_flush_tlb_fix_spurious_fault(struct vm_area_struct *vma,
+ unsigned long addr)
+{
+ if (vma->vm_mm == kw_loaded_mm)
+ kw_flush_tlb_range(wasm_kw_cpu, addr & PAGE_MASK,
+ (addr & PAGE_MASK) + PAGE_SIZE);
+}
+
+/*
+ * The fault path's update (pgtable.h; generic: compare, then a plain store
+ * of @entry, built from an older read): keep a D bit set since.
+ */
+int ptep_set_access_flags(struct vm_area_struct *vma, unsigned long address,
+ pte_t *ptep, pte_t entry, int dirty)
+{
+ unsigned long old = pte_val(READ_ONCE(*ptep)), new;
+
+ do {
+ new = pte_val(entry) | (old & _PAGE_DIRTY);
+ if (old == new)
+ return 0;
+ } while (!try_cmpxchg(&pte_val(*ptep), &old, new));
+ kw_flush_tlb_fix_spurious_fault(vma, address);
+ return 1;
+}
+
+/* riscv_flush_icache(): every CPU drops its decoded code. */
+void kw_flush_icache_all(void)
+{
+ flush_tlb_all();
+}
+#else
void flush_tlb_all(void)
{
kw_flush_tlb_all(wasm_kw_cpu);
@@ -78,11 +289,30 @@ void update_mmu_cache_range(struct vm_fault *vmf, struct vm_area_struct *vma,
addr + (unsigned long)nr * PAGE_SIZE);
}
+void kw_flush_icache_all(void)
+{
+ kw_flush_tlb_all(wasm_kw_cpu);
+}
+#endif
+
/* mm teardown: never leave the emulator pointing at a freed page table. */
void kw_mm_release(struct mm_struct *mm)
{
+#ifdef CONFIG_SMP
+ int self = get_cpu();
+
+ if (mm == kw_loaded_mm) {
+ kw_set_pgd(wasm_kw_cpu, __pa(swapper_pg_dir));
+ cpumask_clear_cpu(self, mm_cpumask(mm));
+ kw_loaded_mm = &init_mm;
+ }
+ /* Another CPU switches away before its lazy reference goes. */
+ WARN_ON_ONCE(cpumask_any(mm_cpumask(mm)) < nr_cpu_ids);
+ put_cpu();
+#else
if (mm == kw_loaded_mm) {
kw_set_pgd(wasm_kw_cpu, __pa(swapper_pg_dir));
kw_loaded_mm = &init_mm;
}
+#endif
}
--
2.56.0