diff --git a/Documentation/dovetail.rst b/Documentation/dovetail.rst new file mode 100644 index 000000000..5d37b0455 --- /dev/null +++ b/Documentation/dovetail.rst @@ -0,0 +1,30 @@ +======================== +Introduction to Dovetail +======================== + +:Author: Philippe Gerum +:Date: 08.04.2020 + +Using Linux as a host for lightweight software cores specialized in +delivering very short and bounded response times has been a popular +way of supporting real-time applications in the embedded space over +the years. + +In this so-called *dual kernel* design, the time-critical work is +immediately delegated to a small companion core running out-of-band +with respect to the regular, in-band kernel activities. Applications +run in user space, obtaining real-time services from the +core. Alternatively, when there is no real-time requirement, threads +can still use the rich GPOS feature set Linux provides such as +networking, data storage or GUIs. + +*Dovetail* introduces a high-priority execution stage into the main +kernel logic reserved for such a companion core to run on. At any +time, out-of-band activities from this stage can preempt the common, +in-band work. A companion core can be implemented as as a driver, +which connects to the main kernel via the Dovetail interface for +delivering ultra-low latency scheduling capabilities to applications. + +Dovetail is fully described at https://evlproject.org/dovetail/. +The reference implementation of a Dovetail-based companion core is +maintained at https://evlproject.org/core/. diff --git a/arch/Kconfig b/arch/Kconfig index 09603e0bc..91f228190 100644 --- a/arch/Kconfig +++ b/arch/Kconfig @@ -234,6 +234,9 @@ config ARCH_CORRECT_STACKTRACE_ON_KRETPROBE config HAVE_FUNCTION_ERROR_INJECTION bool +config HAVE_PERCPU_PREEMPT_COUNT + bool + config HAVE_NMI bool @@ -993,7 +996,7 @@ config HAVE_SOFTIRQ_ON_OWN_STACK separate stack. config SOFTIRQ_ON_OWN_STACK - def_bool HAVE_SOFTIRQ_ON_OWN_STACK && !PREEMPT_RT + def_bool HAVE_SOFTIRQ_ON_OWN_STACK && !PREEMPT_RT && !IRQ_PIPELINE config ALTERNATE_USER_ADDRESS_SPACE bool diff --git a/arch/arm/Kconfig b/arch/arm/Kconfig index 57c0448d0..e5e52da2d 100644 --- a/arch/arm/Kconfig +++ b/arch/arm/Kconfig @@ -249,6 +249,11 @@ config FIQ config ARCH_MTD_XIP bool +# Limited I-pipe compat (syscall routing only). +config IPIPE_COMPAT + bool + select DOVETAIL_LEGACY_SYSCALL_RANGE + config ARM_PATCH_PHYS_VIRT bool "Patch physical to virtual translations at runtime" if !ARCH_MULTIPLATFORM default y @@ -388,6 +393,12 @@ config ARCH_MULTI_V7 config ARCH_MULTI_V6_V7 bool select MIGHT_HAVE_CACHE_L2X0 + select HAVE_IRQ_PIPELINE + select HAVE_DOVETAIL if CPU_HAS_ASID + select HAVE_ARCH_EVL + select WARN_CPUFREQ_GOVERNOR if CPU_FREQ && \ + !(CPU_FREQ_DEFAULT_GOV_PERFORMANCE || \ + CPU_FREQ_DEFAULT_GOV_POWERSAVE) config ARCH_MULTI_CPU_AUTO def_bool !(ARCH_MULTI_V4 || ARCH_MULTI_V4T || ARCH_MULTI_V6_V7) @@ -1040,6 +1051,9 @@ config SCHED_SMT MultiThreading at a cost of slightly increased overhead in some places. If unsure say N here. +source "kernel/Kconfig.dovetail" +source "kernel/Kconfig.evl" + config HAVE_ARM_SCU bool help diff --git a/arch/arm/common/mcpm_entry.c b/arch/arm/common/mcpm_entry.c index e013ff116..ae289af41 100644 --- a/arch/arm/common/mcpm_entry.c +++ b/arch/arm/common/mcpm_entry.c @@ -206,7 +206,7 @@ int mcpm_cpu_power_up(unsigned int cpu, unsigned int cluster) * Since this is called with IRQs enabled, and no arch_spin_lock_irq * variant exists, we need to disable IRQs manually here. */ - local_irq_disable(); + hard_local_irq_disable(); arch_spin_lock(&mcpm_lock); cpu_is_down = !mcpm_cpu_use_count[cluster][cpu]; @@ -230,7 +230,7 @@ int mcpm_cpu_power_up(unsigned int cpu, unsigned int cluster) ret = platform_ops->cpu_powerup(cpu, cluster); arch_spin_unlock(&mcpm_lock); - local_irq_enable(); + hard_local_irq_enable(); return ret; } @@ -349,7 +349,7 @@ int mcpm_cpu_powered_up(void) mpidr = read_cpuid_mpidr(); cpu = MPIDR_AFFINITY_LEVEL(mpidr, 0); cluster = MPIDR_AFFINITY_LEVEL(mpidr, 1); - local_irq_save(flags); + flags = hard_local_irq_save(); arch_spin_lock(&mcpm_lock); cpu_was_down = !mcpm_cpu_use_count[cluster][cpu]; @@ -363,7 +363,7 @@ int mcpm_cpu_powered_up(void) platform_ops->cpu_is_up(cpu, cluster); arch_spin_unlock(&mcpm_lock); - local_irq_restore(flags); + hard_local_irq_restore(flags); return 0; } @@ -402,7 +402,7 @@ int __init mcpm_loopback(void (*cache_disable)(void)) * infrastructure. Let's play it safe by using cpu_pm_enter() * in case the CPU init code path resets the VFP or similar. */ - local_irq_disable(); + hard_local_irq_disable(); local_fiq_disable(); ret = cpu_pm_enter(); if (!ret) { @@ -410,7 +410,7 @@ int __init mcpm_loopback(void (*cache_disable)(void)) cpu_pm_exit(); } local_fiq_enable(); - local_irq_enable(); + hard_local_irq_enable(); if (ret) pr_err("%s returned %d\n", __func__, ret); return ret; diff --git a/arch/arm/include/asm/assembler.h b/arch/arm/include/asm/assembler.h index aebe2c8f6..31263e0a3 100644 --- a/arch/arm/include/asm/assembler.h +++ b/arch/arm/include/asm/assembler.h @@ -126,7 +126,7 @@ THUMB( fpreg .req r7 ) .if \save stmdb sp!, {r0-r3, ip, lr} .endif - bl trace_hardirqs_off + bl trace_hardirqs_off_pipelined .if \save ldmia sp!, {r0-r3, ip, lr} .endif @@ -142,7 +142,7 @@ THUMB( fpreg .req r7 ) .if \save stmdb sp!, {r0-r3, ip, lr} .endif - bl\cond trace_hardirqs_on + bl\cond trace_hardirqs_on_pipelined .if \save ldmia sp!, {r0-r3, ip, lr} .endif diff --git a/arch/arm/include/asm/atomic.h b/arch/arm/include/asm/atomic.h index f0e3b01af..7749a7e7e 100644 --- a/arch/arm/include/asm/atomic.h +++ b/arch/arm/include/asm/atomic.h @@ -164,9 +164,9 @@ static inline void arch_atomic_##op(int i, atomic_t *v) \ { \ unsigned long flags; \ \ - raw_local_irq_save(flags); \ + flags = hard_local_irq_save(); \ v->counter c_op i; \ - raw_local_irq_restore(flags); \ + hard_local_irq_restore(flags); \ } \ #define ATOMIC_OP_RETURN(op, c_op, asm_op) \ @@ -175,10 +175,10 @@ static inline int arch_atomic_##op##_return(int i, atomic_t *v) \ unsigned long flags; \ int val; \ \ - raw_local_irq_save(flags); \ + flags = hard_local_irq_save(); \ v->counter c_op i; \ val = v->counter; \ - raw_local_irq_restore(flags); \ + hard_local_irq_restore(flags); \ \ return val; \ } @@ -189,10 +189,10 @@ static inline int arch_atomic_fetch_##op(int i, atomic_t *v) \ unsigned long flags; \ int val; \ \ - raw_local_irq_save(flags); \ + flags = hard_local_irq_save(); \ val = v->counter; \ v->counter c_op i; \ - raw_local_irq_restore(flags); \ + hard_local_irq_restore(flags); \ \ return val; \ } @@ -212,11 +212,11 @@ static inline int arch_atomic_cmpxchg(atomic_t *v, int old, int new) int ret; unsigned long flags; - raw_local_irq_save(flags); + flags = hard_local_irq_save(); ret = v->counter; if (likely(ret == old)) v->counter = new; - raw_local_irq_restore(flags); + hard_local_irq_restore(flags); return ret; } diff --git a/arch/arm/include/asm/bitops.h b/arch/arm/include/asm/bitops.h index 714440fa2..5e83e1e21 100644 --- a/arch/arm/include/asm/bitops.h +++ b/arch/arm/include/asm/bitops.h @@ -40,9 +40,9 @@ static inline void ____atomic_set_bit(unsigned int bit, volatile unsigned long * p += BIT_WORD(bit); - raw_local_irq_save(flags); + flags = hard_local_irq_save(); *p |= mask; - raw_local_irq_restore(flags); + hard_local_irq_restore(flags); } static inline void ____atomic_clear_bit(unsigned int bit, volatile unsigned long *p) @@ -52,9 +52,9 @@ static inline void ____atomic_clear_bit(unsigned int bit, volatile unsigned long p += BIT_WORD(bit); - raw_local_irq_save(flags); + flags = hard_local_irq_save(); *p &= ~mask; - raw_local_irq_restore(flags); + hard_local_irq_restore(flags); } static inline void ____atomic_change_bit(unsigned int bit, volatile unsigned long *p) @@ -64,9 +64,9 @@ static inline void ____atomic_change_bit(unsigned int bit, volatile unsigned lon p += BIT_WORD(bit); - raw_local_irq_save(flags); + flags = hard_local_irq_save(); *p ^= mask; - raw_local_irq_restore(flags); + hard_local_irq_restore(flags); } static inline int @@ -78,10 +78,10 @@ ____atomic_test_and_set_bit(unsigned int bit, volatile unsigned long *p) p += BIT_WORD(bit); - raw_local_irq_save(flags); + flags = hard_local_irq_save(); res = *p; *p = res | mask; - raw_local_irq_restore(flags); + hard_local_irq_restore(flags); return (res & mask) != 0; } @@ -95,10 +95,10 @@ ____atomic_test_and_clear_bit(unsigned int bit, volatile unsigned long *p) p += BIT_WORD(bit); - raw_local_irq_save(flags); + flags = hard_local_irq_save(); res = *p; *p = res & ~mask; - raw_local_irq_restore(flags); + hard_local_irq_restore(flags); return (res & mask) != 0; } @@ -112,10 +112,10 @@ ____atomic_test_and_change_bit(unsigned int bit, volatile unsigned long *p) p += BIT_WORD(bit); - raw_local_irq_save(flags); + flags = hard_local_irq_save(); res = *p; *p = res ^ mask; - raw_local_irq_restore(flags); + hard_local_irq_restore(flags); return (res & mask) != 0; } diff --git a/arch/arm/include/asm/cmpxchg.h b/arch/arm/include/asm/cmpxchg.h index 44667bdb4..fa300befb 100644 --- a/arch/arm/include/asm/cmpxchg.h +++ b/arch/arm/include/asm/cmpxchg.h @@ -78,17 +78,17 @@ __arch_xchg(unsigned long x, volatile void *ptr, int size) #error SMP is not supported on this platform #endif case 1: - raw_local_irq_save(flags); + flags = hard_local_irq_save(); ret = *(volatile unsigned char *)ptr; *(volatile unsigned char *)ptr = x; - raw_local_irq_restore(flags); + hard_local_irq_restore(flags); break; case 4: - raw_local_irq_save(flags); + flags = hard_local_irq_save(); ret = *(volatile unsigned long *)ptr; *(volatile unsigned long *)ptr = x; - raw_local_irq_restore(flags); + hard_local_irq_restore(flags); break; #else case 1: diff --git a/arch/arm/include/asm/dovetail.h b/arch/arm/include/asm/dovetail.h new file mode 100644 index 000000000..4ecf7bc45 --- /dev/null +++ b/arch/arm/include/asm/dovetail.h @@ -0,0 +1,65 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2016 Philippe Gerum. + */ +#ifndef _ASM_ARM_DOVETAIL_H +#define _ASM_ARM_DOVETAIL_H + +/* ARM traps */ +#define ARM_TRAP_ACCESS 0 /* Data or instruction access exception */ +#define ARM_TRAP_SECTION 1 /* Section fault */ +#define ARM_TRAP_DABT 2 /* Generic data abort */ +#define ARM_TRAP_PABT 3 /* Prefetch abort */ +#define ARM_TRAP_BREAK 4 /* Instruction breakpoint */ +#define ARM_TRAP_FPU 5 /* Floating point exception */ +#define ARM_TRAP_VFP 6 /* VFP floating point exception */ +#define ARM_TRAP_UNDEFINSTR 7 /* Undefined instruction */ +#define ARM_TRAP_ALIGNMENT 8 /* Unaligned access exception */ + +#if !defined(__ASSEMBLY__) + +#ifdef CONFIG_DOVETAIL + +static inline void arch_dovetail_exec_prepare(void) +{ } + +static inline void arch_dovetail_switch_prepare(bool leave_inband) +{ } + +static inline void arch_dovetail_switch_finish(bool enter_inband) +{ } + +#endif + +/* + * Pass the trap event to the companion core. Return true if running + * in-band afterwards. + */ +#define mark_cond_trap_entry(__trapnr, __regs) \ + ({ \ + bool __ret; \ + oob_trap_notify(__trapnr, __regs); \ + __ret = running_inband(); \ + if (!__ret) \ + oob_trap_unwind(__trapnr, __regs); \ + __ret; \ + }) + +/* + * Pass the trap event to the companion core. We expect the current + * context to be running on the in-band stage upon return so that our + * caller can tread on common kernel code. + */ +#define mark_trap_entry(__trapnr, __regs) \ + do { \ + bool __ret = mark_cond_trap_entry(__trapnr, __regs); \ + BUG_ON(dovetail_debug() && !__ret); \ + } while (0) + +#define mark_trap_exit(__trapnr, __regs) \ + oob_trap_unwind(__trapnr, __regs) + +#endif /* !__ASSEMBLY__ */ + +#endif /* _ASM_ARM_DOVETAIL_H */ diff --git a/arch/arm/include/asm/efi.h b/arch/arm/include/asm/efi.h index 78282ced5..e0c544e52 100644 --- a/arch/arm/include/asm/efi.h +++ b/arch/arm/include/asm/efi.h @@ -31,7 +31,11 @@ int efi_set_mapping_permissions(struct mm_struct *mm, efi_memory_desc_t *md, boo static inline void efi_set_pgd(struct mm_struct *mm) { + unsigned long flags; + + protect_inband_mm(flags); check_and_switch_context(mm, NULL); + unprotect_inband_mm(flags); } void efi_virtmap_load(void); diff --git a/arch/arm/include/asm/evl/calibration.h b/arch/arm/include/asm/evl/calibration.h new file mode 100644 index 000000000..0fe3ef8cf --- /dev/null +++ b/arch/arm/include/asm/evl/calibration.h @@ -0,0 +1,13 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _EVL_ARM_ASM_CALIBRATION_H +#define _EVL_ARM_ASM_CALIBRATION_H + +#include + +static inline unsigned int evl_get_default_clock_gravity(void) +{ + /* Reasonable default for many armv7-based systems. */ + return IS_ENABLED(CONFIG_SMP) ? 6000 : 3000; +} + +#endif /* !_EVL_ARM_ASM_CALIBRATION_H */ diff --git a/arch/arm/include/asm/evl/fptest.h b/arch/arm/include/asm/evl/fptest.h new file mode 100644 index 000000000..e58130472 --- /dev/null +++ b/arch/arm/include/asm/evl/fptest.h @@ -0,0 +1,25 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _EVL_ARM_ASM_FPTEST_H +#define _EVL_ARM_ASM_FPTEST_H + +#include +#include + +static inline bool evl_begin_fpu(void) +{ + return false; +} + +static inline void evl_end_fpu(void) { } + +static inline u32 evl_detect_fpu(void) +{ + u32 features = 0; + + if (elf_hwcap & HWCAP_VFP) + return features |= evl_arm_vfp; + + return features; +} + +#endif /* _EVL_ARM_ASM_FPTEST_H */ diff --git a/arch/arm/include/asm/evl/syscall.h b/arch/arm/include/asm/evl/syscall.h new file mode 100644 index 000000000..753f23d24 --- /dev/null +++ b/arch/arm/include/asm/evl/syscall.h @@ -0,0 +1,25 @@ +/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ +#ifndef _EVL_ARM_ASM_SYSCALL_H +#define _EVL_ARM_ASM_SYSCALL_H + +#include +#include +#include +#include +#include + +#define raw_put_user(src, dst) __put_user(src, dst) +#define raw_get_user(dst, src) __get_user(dst, src) + +static inline bool +is_valid_inband_syscall(unsigned int nr) +{ + return nr < NR_syscalls || nr >= __ARM_NR_BASE; +} + +static inline bool is_compat_oob_call(void) +{ + return false; +} + +#endif /* !_EVL_ARM_ASM_SYSCALL_H */ diff --git a/arch/arm/include/asm/evl/thread.h b/arch/arm/include/asm/evl/thread.h new file mode 100644 index 000000000..393aa65a4 --- /dev/null +++ b/arch/arm/include/asm/evl/thread.h @@ -0,0 +1,13 @@ +/* + * Derived from Xenomai Cobalt, https://xenomai.org/ + * Copyright (C) 2005 Stelian Pop + */ +#ifndef _EVL_ARM_ASM_THREAD_H +#define _EVL_ARM_ASM_THREAD_H + +static inline bool evl_is_breakpoint(int trapnr) +{ + return trapnr == ARM_TRAP_BREAK || trapnr == ARM_TRAP_UNDEFINSTR; +} + +#endif /* !_EVL_ARM_ASM_THREAD_H */ diff --git a/arch/arm/include/asm/irq_pipeline.h b/arch/arm/include/asm/irq_pipeline.h new file mode 100644 index 000000000..da57c8625 --- /dev/null +++ b/arch/arm/include/asm/irq_pipeline.h @@ -0,0 +1,143 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2016 Philippe Gerum . + */ +#ifndef _ASM_ARM_IRQ_PIPELINE_H +#define _ASM_ARM_IRQ_PIPELINE_H + +#include + +#ifdef CONFIG_IRQ_PIPELINE + +/* + * In order to cope with the limited number of SGIs available to us, + * In-band IPI messages are multiplexed over SGI0, whereas out-of-band + * IPIs are directly mapped to SGI1-3. + */ +#define OOB_NR_IPI 3 +#define OOB_IPI_OFFSET 1 /* SGI1 */ +#define TIMER_OOB_IPI (ipi_irq_base + OOB_IPI_OFFSET) +#define RESCHEDULE_OOB_IPI (TIMER_OOB_IPI + 1) +#define CALL_FUNCTION_OOB_IPI (RESCHEDULE_OOB_IPI + 1) + +extern int ipi_irq_base; + +static inline notrace +unsigned long arch_irqs_virtual_to_native_flags(int stalled) +{ + return (!!stalled) << IRQMASK_I_POS; +} + +static inline notrace +unsigned long arch_irqs_native_to_virtual_flags(unsigned long flags) +{ + return (!!hard_irqs_disabled_flags(flags)) << IRQMASK_i_POS; +} + +static inline notrace unsigned long arch_local_irq_save(void) +{ + int stalled = inband_irq_save(); + barrier(); + return arch_irqs_virtual_to_native_flags(stalled); +} + +static inline notrace void arch_local_irq_enable(void) +{ + barrier(); + inband_irq_enable(); +} + +static inline notrace void arch_local_irq_disable(void) +{ + inband_irq_disable(); + barrier(); +} + +static inline notrace unsigned long arch_local_save_flags(void) +{ + int stalled = inband_irqs_disabled(); + barrier(); + return arch_irqs_virtual_to_native_flags(stalled); +} + +static inline int arch_irqs_disabled_flags(unsigned long flags) +{ + return native_irqs_disabled_flags(flags); +} + +static inline notrace void arch_local_irq_restore(unsigned long flags) +{ + inband_irq_restore(arch_irqs_disabled_flags(flags)); + barrier(); +} + +static inline +void arch_save_timer_regs(struct pt_regs *dst, struct pt_regs *src) +{ + dst->ARM_cpsr = src->ARM_cpsr; + dst->ARM_pc = src->ARM_pc; +} + +static inline bool arch_steal_pipelined_tick(struct pt_regs *regs) +{ + return !!(regs->ARM_cpsr & IRQMASK_I_BIT); +} + +static inline int arch_enable_oob_stage(void) +{ + return 0; +} + +extern void (*handle_arch_irq)(struct pt_regs *); + +static inline void arch_handle_irq_pipelined(struct pt_regs *regs) +{ + handle_arch_irq(regs); +} + +#define arch_kentry_get_irqstate(__regs) \ + ({ \ + to_svc_pt_regs(__regs)->irqstate; \ + }) + +#define arch_kentry_set_irqstate(__regs, __irqstate) \ + do { \ + to_svc_pt_regs(__regs)->irqstate = __irqstate; \ + } while (0) + +#else /* !CONFIG_IRQ_PIPELINE */ + +static inline unsigned long arch_local_irq_save(void) +{ + return native_irq_save(); +} + +static inline void arch_local_irq_enable(void) +{ + native_irq_enable(); +} + +static inline void arch_local_irq_disable(void) +{ + native_irq_disable(); +} + +static inline unsigned long arch_local_save_flags(void) +{ + return native_save_flags(); +} + +static inline void arch_local_irq_restore(unsigned long flags) +{ + native_irq_restore(flags); +} + +static inline int arch_irqs_disabled_flags(unsigned long flags) +{ + return native_irqs_disabled_flags(flags); +} + +#endif /* !CONFIG_IRQ_PIPELINE */ + +#endif /* _ASM_ARM_IRQ_PIPELINE_H */ diff --git a/arch/arm/include/asm/irqflags.h b/arch/arm/include/asm/irqflags.h index a3b186608..01efe521a 100644 --- a/arch/arm/include/asm/irqflags.h +++ b/arch/arm/include/asm/irqflags.h @@ -5,6 +5,7 @@ #ifdef __KERNEL__ #include +#include /* * CPU interrupt mask handling. @@ -13,41 +14,44 @@ #define IRQMASK_REG_NAME_R "primask" #define IRQMASK_REG_NAME_W "primask" #define IRQMASK_I_BIT 1 +#define IRQMASK_I_POS 0 #else #define IRQMASK_REG_NAME_R "cpsr" #define IRQMASK_REG_NAME_W "cpsr_c" #define IRQMASK_I_BIT PSR_I_BIT +#define IRQMASK_I_POS 7 #endif +#define IRQMASK_i_POS 31 #if __LINUX_ARM_ARCH__ >= 6 #define arch_local_irq_save arch_local_irq_save -static inline unsigned long arch_local_irq_save(void) +static inline unsigned long native_irq_save(void) { unsigned long flags; asm volatile( - " mrs %0, " IRQMASK_REG_NAME_R " @ arch_local_irq_save\n" + " mrs %0, " IRQMASK_REG_NAME_R " @ native_irq_save\n" " cpsid i" : "=r" (flags) : : "memory", "cc"); return flags; } #define arch_local_irq_enable arch_local_irq_enable -static inline void arch_local_irq_enable(void) +static inline void native_irq_enable(void) { asm volatile( - " cpsie i @ arch_local_irq_enable" + " cpsie i @ native_irq_enable" : : : "memory", "cc"); } #define arch_local_irq_disable arch_local_irq_disable -static inline void arch_local_irq_disable(void) +static inline void native_irq_disable(void) { asm volatile( - " cpsid i @ arch_local_irq_disable" + " cpsid i @ native_irq_disable" : : : "memory", "cc"); @@ -69,12 +73,12 @@ static inline void arch_local_irq_disable(void) * Save the current interrupt enable state & disable IRQs */ #define arch_local_irq_save arch_local_irq_save -static inline unsigned long arch_local_irq_save(void) +static inline unsigned long native_irq_save(void) { unsigned long flags, temp; asm volatile( - " mrs %0, cpsr @ arch_local_irq_save\n" + " mrs %0, cpsr @ native_irq_save\n" " orr %1, %0, #128\n" " msr cpsr_c, %1" : "=r" (flags), "=r" (temp) @@ -87,11 +91,11 @@ static inline unsigned long arch_local_irq_save(void) * Enable IRQs */ #define arch_local_irq_enable arch_local_irq_enable -static inline void arch_local_irq_enable(void) +static inline void native_irq_enable(void) { unsigned long temp; asm volatile( - " mrs %0, cpsr @ arch_local_irq_enable\n" + " mrs %0, cpsr @ native_irq_enable\n" " bic %0, %0, #128\n" " msr cpsr_c, %0" : "=r" (temp) @@ -103,11 +107,11 @@ static inline void arch_local_irq_enable(void) * Disable IRQs */ #define arch_local_irq_disable arch_local_irq_disable -static inline void arch_local_irq_disable(void) +static inline void native_irq_disable(void) { unsigned long temp; asm volatile( - " mrs %0, cpsr @ arch_local_irq_disable\n" + " mrs %0, cpsr @ native_irq_disable\n" " orr %0, %0, #128\n" " msr cpsr_c, %0" : "=r" (temp) @@ -149,15 +153,22 @@ static inline void arch_local_irq_disable(void) #define local_abt_disable() do { } while (0) #endif +static inline void native_irq_sync(void) +{ + native_irq_enable(); + isb(); + native_irq_disable(); +} + /* * Save the current interrupt enable state. */ #define arch_local_save_flags arch_local_save_flags -static inline unsigned long arch_local_save_flags(void) +static inline unsigned long native_save_flags(void) { unsigned long flags; asm volatile( - " mrs %0, " IRQMASK_REG_NAME_R " @ local_save_flags" + " mrs %0, " IRQMASK_REG_NAME_R " @ native_save_flags" : "=r" (flags) : : "memory", "cc"); return flags; } diff --git a/arch/arm/include/asm/mmu_context.h b/arch/arm/include/asm/mmu_context.h index db2cb06aa..228e022d1 100644 --- a/arch/arm/include/asm/mmu_context.h +++ b/arch/arm/include/asm/mmu_context.h @@ -14,6 +14,7 @@ #include #include #include +#include #include #include @@ -83,6 +84,7 @@ static inline void check_and_switch_context(struct mm_struct *mm, static inline void finish_arch_post_lock_switch(void) { struct mm_struct *mm = current->mm; + unsigned long flags; if (mm && mm->context.switch_pending) { /* @@ -94,7 +96,9 @@ static inline void finish_arch_post_lock_switch(void) preempt_disable(); if (mm->context.switch_pending) { mm->context.switch_pending = 0; + protect_inband_mm(flags); cpu_switch_mm(mm->pgd, mm); + unprotect_inband_mm(flags); } preempt_enable_no_resched(); } @@ -105,7 +109,7 @@ static inline void finish_arch_post_lock_switch(void) #endif /* CONFIG_CPU_HAS_ASID */ -#define activate_mm(prev,next) switch_mm(prev, next, NULL) +#define activate_mm(prev,next) __switch_mm(prev, next, NULL) /* * This is the actual mm switch as far as the scheduler @@ -114,8 +118,8 @@ static inline void finish_arch_post_lock_switch(void) * actually changed. */ static inline void -switch_mm(struct mm_struct *prev, struct mm_struct *next, - struct task_struct *tsk) +__switch_mm(struct mm_struct *prev, struct mm_struct *next, + struct task_struct *tsk) { #ifdef CONFIG_MMU unsigned int cpu = smp_processor_id(); @@ -149,4 +153,28 @@ static inline void enter_lazy_tlb(struct mm_struct *mm, struct task_struct *tsk) #include +/* + * This is the actual mm switch as far as the scheduler + * is concerned. No registers are touched. We avoid + * calling the CPU specific function when the mm hasn't + * actually changed. + */ +static inline void +switch_mm(struct mm_struct *prev, struct mm_struct *next, + struct task_struct *tsk) +{ + unsigned long flags; + + protect_inband_mm(flags); + __switch_mm(prev, next, tsk); + unprotect_inband_mm(flags); +} + +static inline void +switch_oob_mm(struct mm_struct *prev, struct mm_struct *next, + struct task_struct *tsk) +{ + __switch_mm(prev, next, tsk); +} + #endif diff --git a/arch/arm/include/asm/outercache.h b/arch/arm/include/asm/outercache.h index 336463775..811978d36 100644 --- a/arch/arm/include/asm/outercache.h +++ b/arch/arm/include/asm/outercache.h @@ -78,8 +78,13 @@ static inline void outer_flush_range(phys_addr_t start, phys_addr_t end) */ static inline void outer_flush_all(void) { - if (outer_cache.flush_all) + unsigned long flags; + + if (outer_cache.flush_all) { + flags = hard_cond_local_irq_save(); outer_cache.flush_all(); + hard_cond_local_irq_restore(flags); + } } /** diff --git a/arch/arm/include/asm/ptrace.h b/arch/arm/include/asm/ptrace.h index 7f44e88d1..8e1a82b26 100644 --- a/arch/arm/include/asm/ptrace.h +++ b/arch/arm/include/asm/ptrace.h @@ -19,6 +19,9 @@ struct pt_regs { struct svc_pt_regs { struct pt_regs regs; u32 dacr; +#ifdef CONFIG_IRQ_PIPELINE + long irqstate; +#endif }; #define to_svc_pt_regs(r) container_of(r, struct svc_pt_regs, regs) diff --git a/arch/arm/include/asm/syscall.h b/arch/arm/include/asm/syscall.h index fe4326d93..5407d2de9 100644 --- a/arch/arm/include/asm/syscall.h +++ b/arch/arm/include/asm/syscall.h @@ -80,6 +80,12 @@ static inline void syscall_get_arguments(struct task_struct *task, memcpy(args, ®s->ARM_r0 + 1, 5 * sizeof(args[0])); } +static inline unsigned long syscall_get_arg0(struct task_struct *task, + struct pt_regs *regs) +{ + return regs->ARM_ORIG_r0; +} + static inline int syscall_get_arch(struct task_struct *task) { /* ARM tasks don't change audit architectures on the fly. */ diff --git a/arch/arm/include/asm/thread_info.h b/arch/arm/include/asm/thread_info.h index 943ffcf06..e399af40a 100644 --- a/arch/arm/include/asm/thread_info.h +++ b/arch/arm/include/asm/thread_info.h @@ -39,6 +39,7 @@ struct task_struct; DECLARE_PER_CPU(struct task_struct *, __entry_task); +#include #include #include @@ -62,6 +63,7 @@ struct cpu_context_save { */ struct thread_info { unsigned long flags; /* low level flags */ + __u32 local_flags; /* local (synchronous) flags */ int preempt_count; /* 0 => preemptable, <0 => bug */ __u32 cpu; /* cpu */ __u32 cpu_domain; /* cpu domain */ @@ -73,11 +75,13 @@ struct thread_info { #ifdef CONFIG_ARM_THUMBEE unsigned long thumbee_state; /* ThumbEE Handler Base register */ #endif + struct oob_thread_state oob_state; /* co-kernel thread state */ }; #define INIT_THREAD_INFO(tsk) \ { \ .flags = 0, \ + .local_flags = 0, \ .preempt_count = INIT_PREEMPT_COUNT, \ } @@ -86,7 +90,9 @@ static inline struct task_struct *thread_task(struct thread_info* ti) return (struct task_struct *)ti; } -#define thread_saved_pc(tsk) \ +#define ti_local_flags(__ti) ((__ti)->local_flags) + +#define thread_saved_pc(tsk) \ ((unsigned long)(task_thread_info(tsk)->cpu_context.pc)) #define thread_saved_sp(tsk) \ ((unsigned long)(task_thread_info(tsk)->cpu_context.sp)) @@ -144,6 +150,7 @@ extern int vfp_restore_user_hwstate(struct user_vfp *, #define TIF_NOTIFY_RESUME 2 /* callback before returning to user */ #define TIF_UPROBE 3 /* breakpointed or singlestepping */ #define TIF_NOTIFY_SIGNAL 4 /* signal notifications exist */ +#define TIF_RETUSER 5 /* INBAND_TASK_RETUSER is pending */ #define TIF_USING_IWMMXT 17 #define TIF_MEMDIE 18 /* is terminating due to OOM killer */ @@ -153,6 +160,7 @@ extern int vfp_restore_user_hwstate(struct user_vfp *, #define TIF_SYSCALL_TRACEPOINT 22 /* syscall tracepoint instrumentation */ #define TIF_SECCOMP 23 /* seccomp syscall filtering active */ +#define TIF_MAYDAY 24 /* emergency trap pending */ #define _TIF_SIGPENDING (1 << TIF_SIGPENDING) #define _TIF_NEED_RESCHED (1 << TIF_NEED_RESCHED) @@ -163,9 +171,14 @@ extern int vfp_restore_user_hwstate(struct user_vfp *, #define _TIF_SYSCALL_TRACEPOINT (1 << TIF_SYSCALL_TRACEPOINT) #define _TIF_SECCOMP (1 << TIF_SECCOMP) #define _TIF_NOTIFY_SIGNAL (1 << TIF_NOTIFY_SIGNAL) +#define _TIF_RETUSER (1 << TIF_RETUSER) #define _TIF_USING_IWMMXT (1 << TIF_USING_IWMMXT) +#define _TIF_MAYDAY (1 << TIF_MAYDAY) -/* Checks for any syscall work in entry-common.S */ +/* + * Checks for any syscall work in entry-common.S. + * CAUTION: Only bit0-bit15 are tested there. + */ #define _TIF_SYSCALL_WORK (_TIF_SYSCALL_TRACE | _TIF_SYSCALL_AUDIT | \ _TIF_SYSCALL_TRACEPOINT | _TIF_SECCOMP) @@ -174,7 +187,15 @@ extern int vfp_restore_user_hwstate(struct user_vfp *, */ #define _TIF_WORK_MASK (_TIF_NEED_RESCHED | _TIF_SIGPENDING | \ _TIF_NOTIFY_RESUME | _TIF_UPROBE | \ - _TIF_NOTIFY_SIGNAL) + _TIF_NOTIFY_SIGNAL | _TIF_RETUSER) + +/* + * Local (synchronous) thread flags. + */ +#define _TLF_OOB 0x0001 +#define _TLF_DOVETAIL 0x0002 +#define _TLF_OFFSTAGE 0x0004 +#define _TLF_OOBTRAP 0x0008 #endif /* __KERNEL__ */ #endif /* __ASM_ARM_THREAD_INFO_H */ diff --git a/arch/arm/include/asm/trace/exceptions.h b/arch/arm/include/asm/trace/exceptions.h new file mode 100644 index 000000000..bdb666b3d --- /dev/null +++ b/arch/arm/include/asm/trace/exceptions.h @@ -0,0 +1,62 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#undef TRACE_SYSTEM +#define TRACE_SYSTEM exceptions + +#if !defined(_TRACE_EXCEPTIONS_H) || defined(TRACE_HEADER_MULTI_READ) +#define _TRACE_EXCEPTIONS_H + +#include +#include +#include + +#define __trace_trap(__sym) { __sym, #__sym } + +#define trace_trap_symbolic(__trapnr) \ + __print_symbolic(__trapnr, \ + __trace_trap(ARM_TRAP_ACCESS), \ + __trace_trap(ARM_TRAP_SECTION), \ + __trace_trap(ARM_TRAP_DABT), \ + __trace_trap(ARM_TRAP_PABT), \ + __trace_trap(ARM_TRAP_BREAK), \ + __trace_trap(ARM_TRAP_FPU), \ + __trace_trap(ARM_TRAP_VFP), \ + __trace_trap(ARM_TRAP_UNDEFINSTR), \ + __trace_trap(ARM_TRAP_ALIGNMENT)) + +DECLARE_EVENT_CLASS(ARM_trap_event, + TP_PROTO(int trapnr, struct pt_regs *regs), + TP_ARGS(trapnr, regs), + + TP_STRUCT__entry( + __field(int, trapnr) + __field(struct pt_regs *, regs) + ), + + TP_fast_assign( + __entry->trapnr = trapnr; + __entry->regs = regs; + ), + + TP_printk("%s mode trap: %s", + user_mode(__entry->regs) ? "user" : "kernel", + trace_trap_symbolic(__entry->trapnr)) +); + +DEFINE_EVENT(ARM_trap_event, ARM_trap_entry, + TP_PROTO(int trapnr, struct pt_regs *regs), + TP_ARGS(trapnr, regs) +); + +DEFINE_EVENT(ARM_trap_event, ARM_trap_exit, + TP_PROTO(int trapnr, struct pt_regs *regs), + TP_ARGS(trapnr, regs) +); + +#undef TRACE_INCLUDE_PATH +#undef TRACE_INCLUDE_FILE +#define TRACE_INCLUDE_PATH asm/trace +#define TRACE_INCLUDE_FILE exceptions +#endif /* _TRACE_EXCEPTIONS_H */ + +/* This part must be outside protection */ +#include diff --git a/arch/arm/include/asm/vdso/gettimeofday.h b/arch/arm/include/asm/vdso/gettimeofday.h index 2134cbd54..faa1b3b21 100644 --- a/arch/arm/include/asm/vdso/gettimeofday.h +++ b/arch/arm/include/asm/vdso/gettimeofday.h @@ -142,6 +142,66 @@ static __always_inline const struct vdso_data *__arch_get_vdso_data(void) return __get_datapage(); } +#ifdef CONFIG_GENERIC_CLOCKSOURCE_VDSO + +extern struct vdso_priv *__get_privpage(void); + +static __always_inline struct vdso_priv *__arch_get_vdso_priv(void) +{ + return __get_privpage(); +} + +static __always_inline long clock_open_device(const char *path, int mode) +{ + register u32 r0 asm("r0") = (u32)path; + register u32 r1 asm("r1") = (u32)mode; + register long ret asm ("r0"); + register long nr asm("r7") = __NR_open; + + asm volatile( + " swi #0\n" + : "=r" (ret) + : "r"(r0), "r"(r1), "r"(nr) + : "memory"); + + return ret; +} + +static __always_inline +long clock_ioctl_device(int fd, unsigned int cmd, long arg) +{ + register u32 r0 asm("r0") = (u32)fd; + register u32 r1 asm("r1") = (u32)cmd; + register u32 r2 asm("r2") = (u32)arg; + register long ret asm ("r0"); + register long nr asm("r7") = __NR_ioctl; + + asm volatile( + " swi #0\n" + : "=r" (ret) + : "r"(r0), "r"(r1), "r"(r2), "r"(nr) + : "memory"); + + return ret; +} + +static __always_inline long clock_close_device(int fd) +{ + register u32 r0 asm("r0") = (u32)fd; + register long ret asm ("r0"); + register long nr asm("r7") = __NR_close; + + asm volatile( + " swi #0\n" + : "=r" (ret) + : "r"(r0), "r"(nr) + : "memory"); + + return ret; +} + +#endif /* CONFIG_GENERIC_CLOCKSOURCE_VDSO */ + #endif /* !__ASSEMBLY__ */ #endif /* __ASM_VDSO_GETTIMEOFDAY_H */ diff --git a/arch/arm/include/dovetail/irq.h b/arch/arm/include/dovetail/irq.h new file mode 100644 index 000000000..f214e2f6e --- /dev/null +++ b/arch/arm/include/dovetail/irq.h @@ -0,0 +1,11 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _EVL_DOVETAIL_IRQ_H +#define _EVL_DOVETAIL_IRQ_H + +#ifdef CONFIG_EVL +#include +#else +#include_next +#endif + +#endif /* !_EVL_DOVETAIL_IRQ_H */ diff --git a/arch/arm/include/dovetail/mm_info.h b/arch/arm/include/dovetail/mm_info.h new file mode 100644 index 000000000..13087687d --- /dev/null +++ b/arch/arm/include/dovetail/mm_info.h @@ -0,0 +1,7 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _EVL_DOVETAIL_MM_INFO_H +#define _EVL_DOVETAIL_MM_INFO_H + +#include + +#endif /* !_EVL_DOVETAIL_MM_INFO_H */ diff --git a/arch/arm/include/dovetail/net.h b/arch/arm/include/dovetail/net.h new file mode 100644 index 000000000..b23cf3c5e --- /dev/null +++ b/arch/arm/include/dovetail/net.h @@ -0,0 +1,7 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _EVL_DOVETAIL_NET_H +#define _EVL_DOVETAIL_NET_H + +#include + +#endif /* !_EVL_DOVETAIL_NET_H */ diff --git a/arch/arm/include/dovetail/netdevice.h b/arch/arm/include/dovetail/netdevice.h new file mode 100644 index 000000000..bc7ac6769 --- /dev/null +++ b/arch/arm/include/dovetail/netdevice.h @@ -0,0 +1,7 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _EVL_DOVETAIL_NETDEVICE_H +#define _EVL_DOVETAIL_NETDEVICE_H + +#include + +#endif /* !_EVL_DOVETAIL_NETDEVICE_H */ diff --git a/arch/arm/include/dovetail/poll.h b/arch/arm/include/dovetail/poll.h new file mode 100644 index 000000000..76e51be38 --- /dev/null +++ b/arch/arm/include/dovetail/poll.h @@ -0,0 +1,7 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _EVL_DOVETAIL_POLL_H +#define _EVL_DOVETAIL_POLL_H + +#include + +#endif /* !_EVL_DOVETAIL_POLL_H */ diff --git a/arch/arm/include/dovetail/thread_info.h b/arch/arm/include/dovetail/thread_info.h new file mode 100644 index 000000000..4253b13fe --- /dev/null +++ b/arch/arm/include/dovetail/thread_info.h @@ -0,0 +1,7 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _EVL_DOVETAIL_THREAD_INFO_H +#define _EVL_DOVETAIL_THREAD_INFO_H + +#include + +#endif /* !_EVL_DOVETAIL_THREAD_INFO_H */ diff --git a/arch/arm/include/uapi/asm/evl/fptest.h b/arch/arm/include/uapi/asm/evl/fptest.h new file mode 100644 index 000000000..1ea355d28 --- /dev/null +++ b/arch/arm/include/uapi/asm/evl/fptest.h @@ -0,0 +1,49 @@ +/* + * SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note + * + * Derived from Xenomai Cobalt, https://xenomai.org/ + * Copyright (C) 2006 Gilles Chanteperdrix . + */ +#ifndef _EVL_ARM_ASM_UAPI_FPTEST_H +#define _EVL_ARM_ASM_UAPI_FPTEST_H + +#include + +#define evl_arm_vfp 0x1 + +#define evl_set_fpregs(__features, __val) \ + do { \ + unsigned int __i; \ + __u64 __e[16]; \ + \ + if (__features & evl_arm_vfp) { \ + for (__i = 0; __i < 16; __i++) \ + __e[__i] = (__val); \ + /* vldm %0!, {d0-d15}, AKA fldmiax %0!, {d0-d15} */ \ + __asm__ __volatile__("ldc p11, cr0, [%0],#32*4": \ + "=r"(__i): \ + "0"(&__e[0]): "memory"); \ + } \ + } while (0) + +#define evl_check_fpregs(__features, __val, __bad) \ + ({ \ + unsigned int __result = (__val), __i; \ + __u64 __e[16]; \ + \ + if (__features & evl_arm_vfp) { \ + /* vstm %0!, {d0-d15}, AKA fstmiax %0!, {d0-d15} */ \ + __asm__ __volatile__("stc p11, cr0, [%0],#32*4": \ + "=r"(__i): \ + "0"(&__e[0]): "memory"); \ + for (__i = 0; __i < 16; __i++) \ + if (__e[__i] != __val) { \ + __result = __e[__i]; \ + (__bad) = __i; \ + break; \ + } \ + } \ + __result; \ + }) + +#endif /* !_EVL_ARM_ASM_UAPI_FPTEST_H */ diff --git a/arch/arm/kernel/Makefile b/arch/arm/kernel/Makefile index ae2f2b2b4..b2578d4f2 100644 --- a/arch/arm/kernel/Makefile +++ b/arch/arm/kernel/Makefile @@ -89,6 +89,11 @@ obj-y += head$(MMUEXT).o obj-$(CONFIG_DEBUG_LL) += debug.o obj-$(CONFIG_EARLY_PRINTK) += early_printk.o obj-$(CONFIG_ARM_PATCH_PHYS_VIRT) += phys2virt.o +ifeq ($(CONFIG_DEBUG_LL),y) +obj-$(CONFIG_RAW_PRINTK) += raw_printk.o +endif + +obj-$(CONFIG_IRQ_PIPELINE) += irq_pipeline.o # This is executed very early using a temporary stack when no memory allocator # nor global data is available. Everything has to be allocated on the stack. diff --git a/arch/arm/kernel/asm-offsets.c b/arch/arm/kernel/asm-offsets.c index 219cbc7e5..8308f9113 100644 --- a/arch/arm/kernel/asm-offsets.c +++ b/arch/arm/kernel/asm-offsets.c @@ -42,6 +42,7 @@ int main(void) #endif BLANK(); DEFINE(TI_FLAGS, offsetof(struct thread_info, flags)); + DEFINE(TI_LOCAL_FLAGS, offsetof(struct thread_info, local_flags)); DEFINE(TI_PREEMPT, offsetof(struct thread_info, preempt_count)); DEFINE(TI_CPU, offsetof(struct thread_info, cpu)); DEFINE(TI_CPU_DOMAIN, offsetof(struct thread_info, cpu_domain)); @@ -49,6 +50,7 @@ int main(void) DEFINE(TI_ABI_SYSCALL, offsetof(struct thread_info, abi_syscall)); DEFINE(TI_TP_VALUE, offsetof(struct thread_info, tp_value)); DEFINE(TI_FPSTATE, offsetof(struct thread_info, fpstate)); + DEFINE(TI_OOB_MASK, STAGE_MASK); #ifdef CONFIG_VFP DEFINE(TI_VFPSTATE, offsetof(struct thread_info, vfpstate)); #ifdef CONFIG_SMP @@ -152,6 +154,7 @@ int main(void) BLANK(); #ifdef CONFIG_VDSO DEFINE(VDSO_DATA_SIZE, sizeof(union vdso_data_store)); + DEFINE(VDSO_PRIV_SIZE, PAGE_SIZE); #endif BLANK(); #ifdef CONFIG_ARM_MPU diff --git a/arch/arm/kernel/entry-armv.S b/arch/arm/kernel/entry-armv.S index 0384fbbdc..100e760b0 100644 --- a/arch/arm/kernel/entry-armv.S +++ b/arch/arm/kernel/entry-armv.S @@ -5,6 +5,7 @@ * Copyright (C) 1996,1997,1998 Russell King. * ARM700 fix by Matthew Godbolt (linux-user@willothewisp.demon.co.uk) * nommu support by Hyok S. Choi (hyok.choi@samsung.com) + * Copyright (C) 2005 Stelian Pop. * * Low-level vector interface routines * @@ -29,11 +30,23 @@ #include "entry-header.S" #include +#include /* * Interrupt handling. */ + +#ifdef CONFIG_IRQ_PIPELINE +#define irq_service_handler handle_arch_irq_pipelined +#else +#define irq_service_handler generic_handle_arch_irq +#endif + .macro irq_handler, from_user:req +#ifdef CONFIG_DOVETAIL + mov r0, sp + bl irq_service_handler +#else mov r1, sp ldr_this_cpu r2, irq_stack_ptr, r2, r3 .if \from_user == 0 @@ -49,14 +62,15 @@ #endif bcc 0f @ If not, switch to the IRQ stack mov r0, r1 - bl generic_handle_arch_irq + bl irq_service_handler b 1f 0: .endif - mov_l r0, generic_handle_arch_irq + mov_l r0, irq_service_handler bl call_with_stack 1: +#endif /* !CONFIG_DOVETAIL */ .endm .macro pabt_helper @@ -200,7 +214,10 @@ ENDPROC(__und_invalid) uaccess_entry tsk, r0, r1, r2, \uaccess .if \trace -#ifdef CONFIG_TRACE_IRQFLAGS +#ifdef CONFIG_IRQ_PIPELINE + mov r0, sp + bl kentry_enter_pipelined +#elif defined(CONFIG_TRACE_IRQFLAGS) bl trace_hardirqs_off #endif .endif @@ -220,6 +237,10 @@ ENDPROC(__dabt_svc) __irq_svc: svc_entry irq_handler from_user=0 +#ifdef CONFIG_IRQ_PIPELINE + tst r0, r0 @ skip epilogue if oob or in-band stalled + beq 1f +#endif #ifdef CONFIG_PREEMPTION ldr r8, [tsk, #TI_PREEMPT] @ get preempt count @@ -230,6 +251,7 @@ __irq_svc: blne svc_preempt #endif +1: svc_exit r5, irq = 1 @ return from exception UNWIND(.fnend ) ENDPROC(__irq_svc) @@ -239,7 +261,7 @@ ENDPROC(__irq_svc) #ifdef CONFIG_PREEMPTION svc_preempt: mov r8, lr -1: bl preempt_schedule_irq @ irq en/disable is done inside +1: bl arm_preempt_schedule_irq @ irq en/disable is done inside ldr r0, [tsk, #TI_FLAGS] @ get new tasks TI_FLAGS tst r0, #_TIF_NEED_RESCHED reteq r8 @ go again @@ -268,6 +290,16 @@ __und_svc: svc_entry MAX_STACK_SIZE #else svc_entry +#endif +#ifdef CONFIG_DOVETAIL + get_thread_info tsk + ldr r0, [tsk, #TI_PREEMPT] @ get preempt count + tst r0, #TI_OOB_MASK @ oob stage? + beq 1f + mov r0, #ARM_TRAP_UNDEFINSTR + mov r1, sp @ r1 = ®s + bl __oob_trap_notify +1: #endif mov r1, #4 @ PC correction to apply @@ -278,6 +310,15 @@ __und_svc: __und_svc_finish: get_thread_info tsk +#ifdef CONFIG_DOVETAIL + ldr r0, [tsk, #TI_PREEMPT] @ get preempt count + tst r0, #TI_OOB_MASK @ oob stage? + beq 1f + mov r0, #ARM_TRAP_UNDEFINSTR + mov r1, sp @ r1 = ®s + bl __oob_trap_unwind +1: +#endif ldr r5, [sp, #S_PSR] @ Get SVC cpsr svc_exit r5 @ return from exception UNWIND(.fnend ) @@ -398,7 +439,7 @@ ENDPROC(__fiq_abt) .if \trace #ifdef CONFIG_TRACE_IRQFLAGS - bl trace_hardirqs_off + bl trace_hardirqs_off_pipelined #endif ct_user_exit save = 0 .endif @@ -437,6 +478,10 @@ __irq_usr: irq_handler from_user=1 get_thread_info tsk mov why, #0 +#ifdef CONFIG_IRQ_PIPELINE + tst r0, r0 + beq fast_ret_to_user @ skip epilogue if oob (in-band cannot be stalled) +#endif b ret_to_user_from_irq UNWIND(.fnend ) ENDPROC(__irq_usr) @@ -482,7 +527,7 @@ ENTRY(ret_from_exception) UNWIND(.cantunwind ) get_thread_info tsk mov why, #0 - b ret_to_user + ret_to_user_pipelined r1 UNWIND(.fnend ) ENDPROC(__pabt_usr) ENDPROC(ret_from_exception) diff --git a/arch/arm/kernel/entry-common.S b/arch/arm/kernel/entry-common.S index 5c31e9de7..31928665c 100644 --- a/arch/arm/kernel/entry-common.S +++ b/arch/arm/kernel/entry-common.S @@ -3,6 +3,7 @@ * linux/arch/arm/kernel/entry-common.S * * Copyright (C) 2000 Russell King + * Copyright (C) 2005 Stelian Pop. */ #include @@ -12,6 +13,7 @@ #include #ifdef CONFIG_AEABI #include +#include #endif .equ NR_syscalls, __NR_syscalls @@ -122,6 +124,10 @@ no_work_pending: restore_user_regs fast = 0, offset = 0 ENDPROC(ret_to_user_from_irq) ENDPROC(ret_to_user) +ENTRY(fast_ret_to_user) + disable_irq_notrace @ disable interrupts + b no_work_pending +ENDPROC(fast_ret_to_user) /* * This is how we return from a fork. @@ -257,6 +263,70 @@ ENTRY(vector_swi) TRACE( ldmia sp, {r0 - r3} ) local_restart: +#ifdef CONFIG_DOVETAIL + ldr r10, [tsk, #TI_LOCAL_FLAGS] @ tsk(r10) is callee-saved +#ifdef CONFIG_IPIPE_COMPAT + ldr r0, =#0xf0042 @ old syscall signature + cmp scno, r0 + bne 1f + add scno, scno, #__OOB_SYSCALL_BIT @ force in oob marker + b fastcall_try +1: +#endif +#ifdef CONFIG_DOVETAIL_LEGACY_SYSCALL_RANGE + ldr r0, =#__OOB_SYSCALL_BIT + ands r0, scno, r0 + bne fastcall_try +#endif + cmp scno, #__NR_prctl + bne slow_path + ldr r0, [sp, #S_OLD_R0] + tst r0, #__OOB_SYSCALL_BIT + beq slow_path +fastcall_try: + tst r10, #_TLF_OOB + beq slow_path + mov r0, sp @ regs + bl handle_oob_syscall + ldr r10, [tsk, #TI_LOCAL_FLAGS] + tst r0, r0 + beq slow_path + tst r10, #_TLF_OOB + bne fastcall_exit_check @ check for MAYDAY + bl sync_inband_irqs + b ret_slow_syscall +fastcall_exit_check: + ldr r10, [tsk, #TI_FLAGS] + tst r10, #_TIF_MAYDAY + beq fast_ret_to_user + mov r0, sp @ regs + bl dovetail_call_mayday + b fast_ret_to_user +slow_path: + tst r10, #_TLF_DOVETAIL + bne pipeline_syscall +#ifdef CONFIG_DOVETAIL_LEGACY_SYSCALL_RANGE + ldr r0, =#__OOB_SYSCALL_BIT + ands r0, scno, r0 + bne pipeline_syscall +#endif + cmp scno, #__NR_prctl + bne root_syscall + ldr r0, [sp, #S_OLD_R0] + tst r0, #__OOB_SYSCALL_BIT + beq root_syscall +pipeline_syscall: + mov r0, sp @ regs + bl __pipeline_syscall + ldr r10, [tsk, #TI_LOCAL_FLAGS] + tst r10, #_TLF_OOB + bne fast_ret_to_user + cmp r0, #0 + bgt ret_slow_syscall +root_syscall: + ldmia sp, { r0 - r3 } +#endif /* CONFIG_DOVETAIL */ + ldr r10, [tsk, #TI_FLAGS] @ check for syscall tracing stmdb sp!, {r4, r5} @ push fifth and sixth args diff --git a/arch/arm/kernel/entry-header.S b/arch/arm/kernel/entry-header.S index 99411fa91..55004682c 100644 --- a/arch/arm/kernel/entry-header.S +++ b/arch/arm/kernel/entry-header.S @@ -202,15 +202,21 @@ .macro svc_exit, rpsr, irq = 0 .if \irq != 0 @ IRQs already off -#ifdef CONFIG_TRACE_IRQFLAGS @ The parent context IRQs must have been enabled to get here in @ the first place, so there's no point checking the PSR I bit. +#ifdef CONFIG_IRQ_PIPELINE + mov r0, sp + bl kentry_exit_pipelined +#elif defined(CONFIG_TRACE_IRQFLAGS) bl trace_hardirqs_on #endif .else @ IRQs off again before pulling preserved data off the stack disable_irq_notrace -#ifdef CONFIG_TRACE_IRQFLAGS +#ifdef CONFIG_IRQ_PIPELINE + mov r0, sp + bl kentry_exit_pipelined +#elif defined(CONFIG_TRACE_IRQFLAGS) tst \rpsr, #PSR_I_BIT bleq trace_hardirqs_on tst \rpsr, #PSR_I_BIT @@ -414,6 +420,19 @@ ALT_UP_B(.L1_\@) #endif .endm +/* + * Branch to the exception epilogue, skipping the in-band work + * if running over the out-of-band interrupt stage. + */ + .macro ret_to_user_pipelined, tmp +#ifdef CONFIG_IRQ_PIPELINE + ldr \tmp, [tsk, #TI_LOCAL_FLAGS] + tst \tmp, #_TLF_OOB + bne fast_ret_to_user +#endif + b ret_to_user + .endm + /* * These are the registers used in the syscall handler, and allow us to * have in theory up to 7 arguments to a function - r0 to r6. diff --git a/arch/arm/kernel/irq.c b/arch/arm/kernel/irq.c index fe28fc1f7..11340e936 100644 --- a/arch/arm/kernel/irq.c +++ b/arch/arm/kernel/irq.c @@ -23,6 +23,7 @@ #include #include #include +#include #include #include #include @@ -147,6 +148,46 @@ void __init init_IRQ(void) uniphier_cache_init(); } +#ifdef CONFIG_IRQ_PIPELINE + +#ifdef CONFIG_DOVETAIL +/* + * When Dovetail is enabled, the companion core may switch contexts + * over the irq stack, therefore subsequent interrupts might be taken + * over sibling stack contexts. So we need a not so subtle way of + * figuring out whether the irq stack is already current, which cannot + * depend on the value of the stack pointer. Instead, we track the + * interrupt nesting depth for a CPU in irq_nesting. + */ +DEFINE_PER_CPU(int, irq_nesting); + +asmlinkage int __exception_irq_entry +handle_arch_irq_pipelined(struct pt_regs *regs) +{ + if (this_cpu_inc_return(irq_nesting) == 1) { + void (*handler)(void *) = + (typeof(handler)) + (void (*)(void))handle_irq_pipelined; + call_with_stack(handler, regs, __this_cpu_read(irq_stack_ptr)); + this_cpu_dec(irq_nesting); + return running_inband() && !irqs_disabled(); + } + + return handle_irq_pipelined(regs); +} + +#else /* !CONFIG_DOVETAIL*/ + +asmlinkage int __exception_irq_entry +handle_arch_irq_pipelined(struct pt_regs *regs) +{ + return handle_irq_pipelined(regs); +} + +#endif /* !CONFIG_DOVETAIL*/ + +#endif /* CONFIG_IRQ_PIPELINE */ + #ifdef CONFIG_SPARSE_IRQ int __init arch_probe_nr_irqs(void) { diff --git a/arch/arm/kernel/irq_pipeline.c b/arch/arm/kernel/irq_pipeline.c new file mode 100644 index 000000000..7d366c959 --- /dev/null +++ b/arch/arm/kernel/irq_pipeline.c @@ -0,0 +1,24 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2016 Philippe Gerum . + */ +#include +#include + +void arch_do_IRQ_pipelined(struct irq_desc *desc) +{ + struct pt_regs *regs = raw_cpu_ptr(&irq_pipeline.tick_regs); + struct pt_regs *old_regs = set_irq_regs(regs); + + irq_enter(); + handle_irq_desc(desc); + irq_exit(); + + set_irq_regs(old_regs); +} + +void __init arch_irq_pipeline_init(void) +{ + /* no per-arch init. */ +} diff --git a/arch/arm/kernel/patch.c b/arch/arm/kernel/patch.c index e9e828b6b..35c7285bf 100644 --- a/arch/arm/kernel/patch.c +++ b/arch/arm/kernel/patch.c @@ -17,7 +17,7 @@ struct patch { }; #ifdef CONFIG_MMU -static DEFINE_RAW_SPINLOCK(patch_lock); +static DEFINE_HARD_SPINLOCK(patch_lock); static void __kprobes *patch_map(void *addr, int fixmap, unsigned long *flags) { diff --git a/arch/arm/kernel/process.c b/arch/arm/kernel/process.c index e16ed1029..45b2a9ca0 100644 --- a/arch/arm/kernel/process.c +++ b/arch/arm/kernel/process.c @@ -440,3 +440,18 @@ int arch_setup_additional_pages(struct linux_binprm *bprm, int uses_interp) return ret; } #endif + +/* + * When pipelining interrupts, we have to reconcile the hardware and + * the virtual states. Hard irqs are off on entry while the current + * stage has to be unstalled: fix this up by stalling the in-band + * stage on entry, unstalling on exit. These bits are compiled out if + * !IRQ_PIPELINE. + */ +asmlinkage void __sched arm_preempt_schedule_irq(void) +{ + WARN_ON_ONCE(irq_pipeline_debug() && test_inband_stall()); + stall_inband_nocheck(); + preempt_schedule_irq(); + unstall_inband_nocheck(); +} diff --git a/arch/arm/kernel/ptrace.c b/arch/arm/kernel/ptrace.c index c421a899f..30b9ba8f6 100644 --- a/arch/arm/kernel/ptrace.c +++ b/arch/arm/kernel/ptrace.c @@ -205,7 +205,9 @@ void ptrace_break(struct pt_regs *regs) static int break_trap(struct pt_regs *regs, unsigned int instr) { + mark_trap_entry(ARM_TRAP_BREAK, regs); ptrace_break(regs); + mark_trap_exit(ARM_TRAP_BREAK, regs); return 0; } diff --git a/arch/arm/kernel/raw_printk.c b/arch/arm/kernel/raw_printk.c new file mode 100644 index 000000000..9024b772f --- /dev/null +++ b/arch/arm/kernel/raw_printk.c @@ -0,0 +1,30 @@ +#include +#include +#include + +/* + * If both CONFIG_DEBUG_LL and CONFIG_RAW_PRINTK are set, create a + * console device sending the raw output to printascii(). + */ +void printascii(const char *s); + +static void raw_console_write(struct console *co, + const char *s, unsigned count) +{ + printascii(s); +} + +static struct console raw_console = { + .name = "rawcon", + .write_raw = raw_console_write, + .flags = CON_PRINTBUFFER | CON_ENABLED, + .index = -1, +}; + +static int __init raw_console_init(void) +{ + register_console(&raw_console); + + return 0; +} +console_initcall(raw_console_init); diff --git a/arch/arm/kernel/signal.c b/arch/arm/kernel/signal.c index 79a6730fa..263163209 100644 --- a/arch/arm/kernel/signal.c +++ b/arch/arm/kernel/signal.c @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -598,16 +599,36 @@ static int do_signal(struct pt_regs *regs, int syscall) return 0; } +static inline void do_retuser(void) +{ + unsigned int thread_flags; + + if (dovetailing()) { + thread_flags = current_thread_info()->flags; + if (thread_flags & _TIF_RETUSER) + inband_retuser_notify(); + } +} + asmlinkage int do_work_pending(struct pt_regs *regs, unsigned int thread_flags, int syscall) { + WARN_ON_ONCE(irq_pipeline_debug() && + (irqs_disabled() || running_oob())); + /* * The assembly code enters us with IRQs off, but it hasn't * informed the tracing code of that for efficiency reasons. * Update the trace code with the current status. */ - trace_hardirqs_off(); + if (!irqs_pipelined()) + trace_hardirqs_off(); do { + if (irqs_pipelined()) { + local_irq_disable(); + hard_cond_local_irq_enable(); + } + if (likely(thread_flags & _TIF_NEED_RESCHED)) { schedule(); } else { @@ -617,6 +638,7 @@ do_work_pending(struct pt_regs *regs, unsigned int thread_flags, int syscall) if (thread_flags & (_TIF_SIGPENDING | _TIF_NOTIFY_SIGNAL)) { int restart = do_signal(regs, syscall); if (unlikely(restart)) { + do_retuser(); /* * Restart without handlers. * Deal with it without leaving @@ -630,10 +652,16 @@ do_work_pending(struct pt_regs *regs, unsigned int thread_flags, int syscall) } else { resume_user_mode_work(regs); } + do_retuser(); } - local_irq_disable(); + hard_local_irq_disable(); + + /* RETUSER might have switched oob */ + if (!running_inband()) + break; + thread_flags = read_thread_flags(); - } while (thread_flags & _TIF_WORK_MASK); + } while (inband_irq_pending() || (thread_flags & _TIF_WORK_MASK)); return 0; } diff --git a/arch/arm/kernel/smp.c b/arch/arm/kernel/smp.c index 3431c0553..1ebb9a540 100644 --- a/arch/arm/kernel/smp.c +++ b/arch/arm/kernel/smp.c @@ -79,7 +79,7 @@ enum ipi_msg_type { MAX_IPI }; -static int ipi_irq_base __read_mostly; +int ipi_irq_base __read_mostly; static int nr_ipi __read_mostly = NR_IPI; static struct irq_desc *ipi_desc[MAX_IPI] __read_mostly; @@ -321,7 +321,7 @@ void __noreturn arch_cpu_idle_dead(void) idle_task_exit(); - local_irq_disable(); + local_irq_disable_full(); /* * Flush the data out of the L1 cache for this CPU. This must be @@ -425,6 +425,13 @@ asmlinkage void secondary_start_kernel(struct task_struct *task) enter_lazy_tlb(mm, current); local_flush_tlb_all(); + /* + * irq_pipeline: debug_smp_processor_id() accesses percpu + * data. + */ + if (irqs_pipelined()) + set_my_cpu_offset(per_cpu_offset(raw_smp_processor_id())); + /* * All kernel threads share the same mm context; grab a * reference and switch to it. @@ -468,7 +475,7 @@ asmlinkage void secondary_start_kernel(struct task_struct *task) complete(&cpu_running); - local_irq_enable(); + local_irq_enable_full(); local_fiq_enable(); local_abt_enable(); @@ -543,6 +550,8 @@ static const char *ipi_types[NR_IPI] __tracepoint_string = { static void smp_cross_call(const struct cpumask *target, unsigned int ipinr); +static unsigned int get_ipi_count(struct irq_desc *desc, unsigned int cpu); + void show_ipi_list(struct seq_file *p, int prec) { unsigned int cpu, i; @@ -554,7 +563,7 @@ void show_ipi_list(struct seq_file *p, int prec) seq_printf(p, "%*s%u: ", prec - 1, "IPI", i); for_each_online_cpu(cpu) - seq_printf(p, "%10u ", irq_desc_kstat_cpu(ipi_desc[i], cpu)); + seq_printf(p, "%10u ", get_ipi_count(ipi_desc[i], cpu)); seq_printf(p, " %s\n", ipi_types[i]); } @@ -598,6 +607,7 @@ static DEFINE_RAW_SPINLOCK(stop_lock); static void ipi_cpu_stop(unsigned int cpu) { local_fiq_disable(); + local_irq_disable_full(); if (system_state <= SYSTEM_RUNNING) { raw_spin_lock(&stop_lock); @@ -690,6 +700,12 @@ void handle_IPI(int ipinr, struct pt_regs *regs) { struct pt_regs *old_regs = set_irq_regs(regs); + /* + * We don't support legacy IPI delivery when pipelining + * interrupts. + */ + WARN_ON_ONCE(irqs_pipelined()); + irq_enter(); do_handle_IPI(ipinr); irq_exit(); @@ -697,6 +713,74 @@ void handle_IPI(int ipinr, struct pt_regs *regs) set_irq_regs(old_regs); } +static void __smp_cross_call(const struct cpumask *target, unsigned int ipinr) +{ + trace_ipi_raise(target, ipi_types[ipinr]); + __ipi_send_mask(ipi_desc[ipinr], target); +} + +#ifdef CONFIG_IRQ_PIPELINE + +static DEFINE_PER_CPU(unsigned long, ipi_messages); + +static DEFINE_PER_CPU(unsigned int [MAX_IPI], ipi_counts); + +static irqreturn_t ipi_handler(int irq, void *data) +{ + unsigned long *pmsg; + unsigned int ipinr; + + /* + * Decode in-band IPIs (0..MAX_IPI - 1) multiplexed over + * SGI0. Out-of-band IPIs (SGI1, SGI2) have their own + * individual handler. + */ + pmsg = raw_cpu_ptr(&ipi_messages); + while (*pmsg) { + ipinr = ffs(*pmsg) - 1; + clear_bit(ipinr, pmsg); + __this_cpu_inc(ipi_counts[ipinr]); + do_handle_IPI(ipinr); + } + + return IRQ_HANDLED; +} + +static void smp_cross_call(const struct cpumask *target, unsigned int ipinr) +{ + unsigned int cpu; + + /* regular in-band IPI (multiplexed over SGI0). */ + for_each_cpu(cpu, target) + set_bit(ipinr, &per_cpu(ipi_messages, cpu)); + + wmb(); + __smp_cross_call(target, 0); +} + +static unsigned int get_ipi_count(struct irq_desc *desc, unsigned int cpu) +{ + unsigned int irq = irq_desc_get_irq(desc); + return per_cpu(ipi_counts[irq - ipi_irq_base], cpu); +} + +void irq_send_oob_ipi(unsigned int irq, + const struct cpumask *cpumask) +{ + unsigned int sgi = irq - ipi_irq_base; + + if (WARN_ON(irq_pipeline_debug() && + (sgi < OOB_IPI_OFFSET || + sgi >= OOB_IPI_OFFSET + OOB_NR_IPI))) + return; + + /* Out-of-band IPI (SGI1-2). */ + __smp_cross_call(cpumask, sgi); +} +EXPORT_SYMBOL_GPL(irq_send_oob_ipi); + +#else + static irqreturn_t ipi_handler(int irq, void *data) { do_handle_IPI(irq - ipi_irq_base); @@ -705,10 +789,16 @@ static irqreturn_t ipi_handler(int irq, void *data) static void smp_cross_call(const struct cpumask *target, unsigned int ipinr) { - trace_ipi_raise(target, ipi_types[ipinr]); - __ipi_send_mask(ipi_desc[ipinr], target); + __smp_cross_call(target, ipinr); +} + +static unsigned int get_ipi_count(struct irq_desc *desc, unsigned int cpu) +{ + return irq_desc_kstat_cpu(desc, cpu); } +#endif /* CONFIG_IRQ_PIPELINE */ + static void ipi_setup(int cpu) { int i; @@ -722,18 +812,25 @@ static void ipi_setup(int cpu) void __init set_smp_ipi_range(int ipi_base, int n) { - int i; + int i, inband_nr_ipi; WARN_ON(n < MAX_IPI); nr_ipi = min(n, MAX_IPI); + /* + * irq_pipeline: the in-band stage traps SGI0 only, + * over which IPI messages are mutiplexed. Other SGIs + * are available for delivering out-of-band IPIs. + */ + inband_nr_ipi = irqs_pipelined() ? 1 : nr_ipi; for (i = 0; i < nr_ipi; i++) { - int err; - - err = request_percpu_irq(ipi_base + i, ipi_handler, - "IPI", &irq_stat); - WARN_ON(err); + if (i < inband_nr_ipi) { + int err; + err = request_percpu_irq(ipi_base + i, ipi_handler, + "IPI", &irq_stat); + WARN_ON(err); + } ipi_desc[i] = irq_to_desc(ipi_base + i); irq_set_status_flags(ipi_base + i, IRQ_HIDDEN); } diff --git a/arch/arm/kernel/smp_twd.c b/arch/arm/kernel/smp_twd.c index 9a14f721a..194d3cc7c 100644 --- a/arch/arm/kernel/smp_twd.c +++ b/arch/arm/kernel/smp_twd.c @@ -31,7 +31,7 @@ static DEFINE_PER_CPU(bool, percpu_setup_called); static struct clock_event_device __percpu *twd_evt; static unsigned int twd_features = - CLOCK_EVT_FEAT_PERIODIC | CLOCK_EVT_FEAT_ONESHOT; + CLOCK_EVT_FEAT_PERIODIC | CLOCK_EVT_FEAT_ONESHOT | CLOCK_EVT_FEAT_PIPELINE; static int twd_ppi; static int twd_shutdown(struct clock_event_device *clk) @@ -181,8 +181,8 @@ static irqreturn_t twd_handler(int irq, void *dev_id) { struct clock_event_device *evt = dev_id; - if (twd_timer_ack()) { - evt->event_handler(evt); + if ((running_inband() && clockevent_is_oob(evt)) || twd_timer_ack()) { + clockevents_handle_event(evt); return IRQ_HANDLED; } @@ -279,7 +279,8 @@ static int __init twd_local_timer_common_register(struct device_node *np) goto out_free; } - err = request_percpu_irq(twd_ppi, twd_handler, "twd", twd_evt); + err = __request_percpu_irq(twd_ppi, twd_handler, + IRQF_TIMER, "twd", twd_evt); if (err) { pr_err("twd: can't register interrupt %d (%d)\n", twd_ppi, err); goto out_free; diff --git a/arch/arm/kernel/traps.c b/arch/arm/kernel/traps.c index 3bad79db5..dba723f85 100644 --- a/arch/arm/kernel/traps.c +++ b/arch/arm/kernel/traps.c @@ -411,7 +411,7 @@ int is_valid_bugaddr(unsigned long pc) #endif static LIST_HEAD(undef_hook); -static DEFINE_RAW_SPINLOCK(undef_lock); +static DEFINE_HARD_SPINLOCK(undef_lock); void register_undef_hook(struct undef_hook *hook) { diff --git a/arch/arm/kernel/vdso.c b/arch/arm/kernel/vdso.c index f297d66a8..94a7f943c 100644 --- a/arch/arm/kernel/vdso.c +++ b/arch/arm/kernel/vdso.c @@ -32,7 +32,10 @@ static struct page **vdso_text_pagelist; extern char vdso_start[], vdso_end[]; -/* Total number of pages needed for the data and text portions of the VDSO. */ +/* + * Total number of pages needed for the data, private and text + * portions of the VDSO. + */ unsigned int vdso_total_pages __ro_after_init; /* @@ -171,8 +174,10 @@ static void __init patch_vdso(void *ehdr) /* If the virtual counter is absent or non-functional we don't * want programs to incur the slight additional overhead of * dispatching through the VDSO only to fall back to syscalls. + * However, if clocksources supporting generic MMIO access can + * be reached via the vDSO, keep this fast path enabled. */ - if (!cntvct_ok) { + if (!cntvct_ok && !IS_ENABLED(CONFIG_GENERIC_CLOCKSOURCE_VDSO)) { vdso_nullpatch_one(&einfo, "__vdso_gettimeofday"); vdso_nullpatch_one(&einfo, "__vdso_clock_gettime"); vdso_nullpatch_one(&einfo, "__vdso_clock_gettime64"); @@ -210,17 +215,28 @@ static int __init vdso_init(void) vdso_text_mapping.pages = vdso_text_pagelist; - vdso_total_pages = 1; /* for the data/vvar page */ + vdso_total_pages = 2; /* for the data/vvar and vpriv pages */ vdso_total_pages += text_pages; cntvct_ok = cntvct_functional(); patch_vdso(vdso_start); +#ifdef CONFIG_GENERIC_CLOCKSOURCE_VDSO + vdso_data->cs_type_seq = CLOCKSOURCE_VDSO_NONE << 16 | 1; +#endif return 0; } arch_initcall(vdso_init); +static int install_vpriv(struct mm_struct *mm, unsigned long addr) +{ + /* Try mapping a page of anonymous memory at 'addr'. */ + return mmap_region(NULL, addr, PAGE_SIZE, + VM_READ | VM_WRITE | VM_MAYREAD | VM_MAYWRITE, + 0, NULL) != addr ? -EINVAL : 0; +} + static int install_vvar(struct mm_struct *mm, unsigned long addr) { struct vm_area_struct *vma; @@ -228,8 +244,13 @@ static int install_vvar(struct mm_struct *mm, unsigned long addr) vma = _install_special_mapping(mm, addr, PAGE_SIZE, VM_READ | VM_MAYREAD, &vdso_data_mapping); + if (IS_ERR(vma)) + return PTR_ERR(vma); + + if (cache_is_vivt()) + vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot); - return PTR_ERR_OR_ZERO(vma); + return vma->vm_start != addr ? -EINVAL : 0; } /* assumes mmap_lock is write-locked */ @@ -243,18 +264,41 @@ void arm_install_vdso(struct mm_struct *mm, unsigned long addr) if (vdso_text_pagelist == NULL) return; - if (install_vvar(mm, addr)) + /* + * Install the vDSO mappings we need: + * + * +----------------+ + * | vpriv | PAGE_SIZE (private anon memory) + * |----------------| + * | vvar | PAGE_SIZE (shared) + * |----------------| + * | text | text_pages * PAGE_SIZE (shared) + * | ... | + * +----------------+ + */ + + if (install_vpriv(mm, addr)) { + pr_err("cannot map VPRIV at expected address!\n"); + return; + } + + addr += PAGE_SIZE; + if (install_vvar(mm, addr)) { + WARN(1, "cannot map VVAR at expected address!\n"); return; + } - /* Account for vvar page. */ + /* Account for vvar and vpriv pages. */ addr += PAGE_SIZE; - len = (vdso_total_pages - 1) << PAGE_SHIFT; + len = (vdso_total_pages - 2) << PAGE_SHIFT; vma = _install_special_mapping(mm, addr, len, VM_READ | VM_EXEC | VM_MAYREAD | VM_MAYWRITE | VM_MAYEXEC, &vdso_text_mapping); - if (!IS_ERR(vma)) + if (IS_ERR(vma) || vma->vm_start != addr) + WARN(1, "cannot map VDSO at expected address!\n"); + else mm->context.vdso = addr; } diff --git a/arch/arm/mach-imx/gpc.c b/arch/arm/mach-imx/gpc.c index 5909088d5..8255eab95 100644 --- a/arch/arm/mach-imx/gpc.c +++ b/arch/arm/mach-imx/gpc.c @@ -62,28 +62,38 @@ void imx_gpc_set_l2_mem_power_in_lpm(bool power_off) void imx_gpc_pre_suspend(bool arm_power_off) { void __iomem *reg_imr1 = gpc_base + GPC_IMR1; + unsigned long flags; int i; /* Tell GPC to power off ARM core when suspend */ if (arm_power_off) imx_gpc_set_arm_power_in_lpm(arm_power_off); + flags = hard_cond_local_irq_save(); + for (i = 0; i < IMR_NUM; i++) { gpc_saved_imrs[i] = readl_relaxed(reg_imr1 + i * 4); writel_relaxed(~gpc_wake_irqs[i], reg_imr1 + i * 4); } + + hard_cond_local_irq_restore(flags); } void imx_gpc_post_resume(void) { void __iomem *reg_imr1 = gpc_base + GPC_IMR1; + unsigned long flags; int i; /* Keep ARM core powered on for other low-power modes */ imx_gpc_set_arm_power_in_lpm(false); + flags = hard_cond_local_irq_save(); + for (i = 0; i < IMR_NUM; i++) writel_relaxed(gpc_saved_imrs[i], reg_imr1 + i * 4); + + hard_cond_local_irq_restore(flags); } static int imx_gpc_irq_set_wake(struct irq_data *d, unsigned int on) @@ -105,21 +115,31 @@ static int imx_gpc_irq_set_wake(struct irq_data *d, unsigned int on) void imx_gpc_mask_all(void) { void __iomem *reg_imr1 = gpc_base + GPC_IMR1; + unsigned long flags; int i; + flags = hard_cond_local_irq_save(); + for (i = 0; i < IMR_NUM; i++) { gpc_saved_imrs[i] = readl_relaxed(reg_imr1 + i * 4); writel_relaxed(~0, reg_imr1 + i * 4); } + + hard_cond_local_irq_restore(flags); } void imx_gpc_restore_all(void) { void __iomem *reg_imr1 = gpc_base + GPC_IMR1; + unsigned long flags; int i; + flags = hard_cond_local_irq_save(); + for (i = 0; i < IMR_NUM; i++) writel_relaxed(gpc_saved_imrs[i], reg_imr1 + i * 4); + + hard_cond_local_irq_restore(flags); } void imx_gpc_hwirq_unmask(unsigned int hwirq) @@ -167,6 +187,7 @@ static struct irq_chip imx_gpc_chip = { #ifdef CONFIG_SMP .irq_set_affinity = irq_chip_set_affinity_parent, #endif + .flags = IRQCHIP_PIPELINE_SAFE, }; static int imx_gpc_domain_translate(struct irq_domain *d, diff --git a/arch/arm/mm/alignment.c b/arch/arm/mm/alignment.c index f8dd0b3cc..b03ce1ded 100644 --- a/arch/arm/mm/alignment.c +++ b/arch/arm/mm/alignment.c @@ -19,6 +19,7 @@ #include #include #include +#include #include #include @@ -807,10 +808,12 @@ do_alignment(unsigned long addr, unsigned int fsr, struct pt_regs *regs) u16 tinstr = 0; int isize = 4; int thumb2_32b = 0; - int fault; + int fault, ret = 0; if (interrupts_enabled(regs)) - local_irq_enable(); + hard_local_irq_enable(); + + mark_trap_entry(ARM_TRAP_ALIGNMENT, regs); instrptr = instruction_pointer(regs); @@ -938,7 +941,7 @@ do_alignment(unsigned long addr, unsigned int fsr, struct pt_regs *regs) if (thumb_mode(regs)) regs->ARM_cpsr = it_advance(regs->ARM_cpsr); - return 0; + goto out; bad_or_fault: if (type == TYPE_ERROR) @@ -947,7 +950,7 @@ do_alignment(unsigned long addr, unsigned int fsr, struct pt_regs *regs) * We got a fault - fix it up, or die. */ do_bad_area(addr, fsr, regs); - return 0; + goto out; swp: pr_err("Alignment trap: not handling swp instruction\n"); @@ -961,7 +964,8 @@ do_alignment(unsigned long addr, unsigned int fsr, struct pt_regs *regs) isize << 1, isize == 2 ? tinstr : instr, instrptr); ai_skipped += 1; - return 1; + ret = 1; + goto out; user: ai_user += 1; @@ -992,12 +996,15 @@ do_alignment(unsigned long addr, unsigned int fsr, struct pt_regs *regs) * entry-common.S) and disable the alignment trap only if * there is no work pending for this thread. */ - raw_local_irq_disable(); + hard_local_irq_disable(); if (!(read_thread_flags() & _TIF_WORK_MASK)) set_cr(cr_no_alignment); } - return 0; +out: + mark_trap_exit(ARM_TRAP_ALIGNMENT, regs); + + return ret; } static int __init noalign_setup(char *__unused) diff --git a/arch/arm/mm/cache-l2x0.c b/arch/arm/mm/cache-l2x0.c index 43d91bfd2..b2af3e0da 100644 --- a/arch/arm/mm/cache-l2x0.c +++ b/arch/arm/mm/cache-l2x0.c @@ -38,7 +38,7 @@ struct l2c_init_data { static void __iomem *l2x0_base; static const struct l2c_init_data *l2x0_data; -static DEFINE_RAW_SPINLOCK(l2x0_lock); +static DEFINE_HARD_SPINLOCK(l2x0_lock); static u32 l2x0_way_mask; /* Bitmask of active ways */ static u32 l2x0_size; static unsigned long sync_reg_offset = L2X0_CACHE_SYNC; @@ -48,6 +48,19 @@ struct l2x0_regs l2x0_saved_regs; static bool l2x0_bresp_disable; static bool l2x0_flz_disable; +#ifdef CONFIG_IRQ_PIPELINE +#define CACHE_RANGE_ATOMIC_MAX 512UL +static int l2x0_wa = -1; +static int __init l2x0_setup_wa(char *str) +{ + l2x0_wa = !!simple_strtol(str, NULL, 0); + return 0; +} +early_param("l2x0_write_allocate", l2x0_setup_wa); +#else +#define CACHE_RANGE_ATOMIC_MAX 4096UL +#endif + /* * Common code for all cache controllers. */ @@ -120,11 +133,11 @@ static void l2c_enable(void __iomem *base, unsigned num_lock) l2x0_data->unlock(base, num_lock); - local_irq_save(flags); + flags = hard_local_irq_save(); __l2c_op_way(base + L2X0_INV_WAY); writel_relaxed(0, base + sync_reg_offset); l2c_wait_mask(base + sync_reg_offset, 1); - local_irq_restore(flags); + hard_local_irq_restore(flags); l2c_write_sec(L2X0_CTRL_EN, base, L2X0_CTRL); } @@ -225,7 +238,7 @@ static void l2c210_flush_all(void) { void __iomem *base = l2x0_base; - BUG_ON(!irqs_disabled()); + BUG_ON(!hard_irqs_disabled()); __l2c_op_way(base + L2X0_CLEAN_INV_WAY); __l2c210_cache_sync(base); @@ -284,10 +297,10 @@ static void l2c220_op_way(void __iomem *base, unsigned reg) static unsigned long l2c220_op_pa_range(void __iomem *reg, unsigned long start, unsigned long end, unsigned long flags) { - raw_spinlock_t *lock = &l2x0_lock; + typeof(l2x0_lock) *lock = &l2x0_lock; while (start < end) { - unsigned long blk_end = start + min(end - start, 4096UL); + unsigned long blk_end = start + min(end - start, CACHE_RANGE_ATOMIC_MAX); while (start < blk_end) { l2c_wait_mask(reg, 1); @@ -498,13 +511,13 @@ static void l2c310_inv_range_erratum(unsigned long start, unsigned long end) static void l2c310_flush_range_erratum(unsigned long start, unsigned long end) { - raw_spinlock_t *lock = &l2x0_lock; + typeof(l2x0_lock) *lock = &l2x0_lock; unsigned long flags; void __iomem *base = l2x0_base; raw_spin_lock_irqsave(lock, flags); while (start < end) { - unsigned long blk_end = start + min(end - start, 4096UL); + unsigned long blk_end = start + min(end - start, CACHE_RANGE_ATOMIC_MAX); l2c_set_debug(base, 0x03); while (start < blk_end) { @@ -800,6 +813,24 @@ static int __init __l2c_init(const struct l2c_init_data *data, if (aux_val & aux_mask) pr_alert("L2C: platform provided aux values permit register corruption.\n"); +#ifdef CONFIG_IRQ_PIPELINE + if (!l2x0_wa) { + /* + * Disable WA by setting bit 23 in the auxiliary + * control register. + */ + aux_mask &= ~L220_AUX_CTRL_FWA_MASK; + aux_val &= ~L220_AUX_CTRL_FWA_MASK; + aux_val |= 1 << L220_AUX_CTRL_FWA_SHIFT; + pr_warn("%s: irq_pipeline: write-allocate disabled via command line\n", + data->type); + } else if ((cache_id & L2X0_CACHE_ID_PART_MASK) == L2X0_CACHE_ID_PART_L220 || + ((cache_id & L2X0_CACHE_ID_PART_MASK) == L2X0_CACHE_ID_PART_L310 && + (cache_id & L2X0_CACHE_ID_RTL_MASK) < L310_CACHE_ID_RTL_R3P2)) + pr_alert("%s: irq_pipeline: write-allocate enabled, may induce high latency\n", + data->type); +#endif + old_aux = aux = readl_relaxed(l2x0_base + L2X0_AUX_CTRL); aux &= aux_mask; aux |= aux_val; diff --git a/arch/arm/mm/context.c b/arch/arm/mm/context.c index 4204ffa2d..3bac4d2f4 100644 --- a/arch/arm/mm/context.c +++ b/arch/arm/mm/context.c @@ -39,7 +39,7 @@ #define ASID_FIRST_VERSION (1ULL << ASID_BITS) #define NUM_USER_ASIDS ASID_FIRST_VERSION -static DEFINE_RAW_SPINLOCK(cpu_asid_lock); +static DEFINE_HARD_SPINLOCK(cpu_asid_lock); static atomic64_t asid_generation = ATOMIC64_INIT(ASID_FIRST_VERSION); static DECLARE_BITMAP(asid_map, NUM_USER_ASIDS); @@ -237,10 +237,12 @@ static u64 new_context(struct mm_struct *mm, unsigned int cpu) void check_and_switch_context(struct mm_struct *mm, struct task_struct *tsk) { unsigned long flags; - unsigned int cpu = smp_processor_id(); + unsigned int cpu = raw_smp_processor_id(); + bool need_flush; u64 asid; check_vmalloc_seq(mm); + WARN_ON_ONCE(dovetail_debug() && !hard_irqs_disabled()); /* * We cannot update the pgd and the ASID atomicly with classic @@ -262,15 +264,16 @@ void check_and_switch_context(struct mm_struct *mm, struct task_struct *tsk) atomic64_set(&mm->context.id, asid); } - if (cpumask_test_and_clear_cpu(cpu, &tlb_flush_pending)) { - local_flush_bp_all(); - local_flush_tlb_all(); - } - + need_flush = cpumask_test_and_clear_cpu(cpu, &tlb_flush_pending); atomic64_set(&per_cpu(active_asids, cpu), asid); cpumask_set_cpu(cpu, mm_cpumask(mm)); raw_spin_unlock_irqrestore(&cpu_asid_lock, flags); + if (need_flush) { + local_flush_bp_all(); + local_flush_tlb_all(); + } + switch_mm_fastpath: cpu_switch_mm(mm->pgd, mm); } diff --git a/arch/arm/mm/fault.c b/arch/arm/mm/fault.c index fef62e4a9..fd628acec 100644 --- a/arch/arm/mm/fault.c +++ b/arch/arm/mm/fault.c @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -22,11 +23,69 @@ #include #include #include +#include +#define CREATE_TRACE_POINTS +#include #include "fault.h" #ifdef CONFIG_MMU +#ifdef CONFIG_IRQ_PIPELINE +/* + * We need to synchronize the virtual interrupt state with the hard + * interrupt state we received on entry, then turn hardirqs back on to + * allow code which does not require strict serialization to be + * preempted by an out-of-band activity. + */ +static inline +unsigned long fault_entry(int exception, struct pt_regs *regs) +{ + unsigned long flags; + + trace_ARM_trap_entry(exception, regs); + + flags = hard_local_save_flags(); + + /* + * The companion core must demote the current context to + * in-band stage if running oob on entry. + */ + mark_trap_entry(exception, regs); + + if (raw_irqs_disabled_flags(flags)) { + stall_inband(); + trace_hardirqs_off(); + } + + hard_local_irq_enable(); + + return flags; +} + +static inline +void fault_exit(int exception, struct pt_regs *regs, + unsigned long flags) +{ + WARN_ON_ONCE(irq_pipeline_debug() && hard_irqs_disabled()); + + /* + * We expect kentry_exit_pipelined() to clear the stall bit if + * kentry_enter_pipelined() observed it that way. + */ + mark_trap_exit(exception, regs); + trace_ARM_trap_exit(exception, regs); + hard_local_irq_restore(flags); +} + +#else /* !CONFIG_IRQ_PIPELINE */ + +#define fault_entry(__exception, __regs) ({ 0; }) +#define fault_exit(__exception, __regs, __flags) \ + do { (void)(__flags); } while (0) + +#endif /* !CONFIG_IRQ_PIPELINE */ + /* * This is useful to dump out the page tables associated with * 'addr' in mm 'mm'. @@ -99,6 +158,15 @@ void show_pte(const char *lvl, struct mm_struct *mm, unsigned long addr) pr_cont("\n"); } #else /* CONFIG_MMU */ +unsigned long fault_entry(int exception, struct pt_regs *regs) +{ + return 0; +} + +static inline void fault_exit(int exception, struct pt_regs *regs, + unsigned long combo) +{ } + void show_pte(const char *lvl, struct mm_struct *mm, unsigned long addr) { } #endif /* CONFIG_MMU */ @@ -125,6 +193,7 @@ static void die_kernel_fault(const char *msg, struct mm_struct *mm, unsigned long addr, unsigned int fsr, struct pt_regs *regs) { + irq_pipeline_oops(); bust_spinlocks(1); pr_alert("8<--- cut here ---\n"); pr_alert("Unable to handle kernel %s at virtual address %08lx when %s\n", @@ -207,14 +276,22 @@ void do_bad_area(unsigned long addr, unsigned int fsr, struct pt_regs *regs) { struct task_struct *tsk = current; struct mm_struct *mm = tsk->active_mm; + unsigned long irqflags; /* * If we are in kernel mode at this point, we * have no context to handle this fault with. */ - if (user_mode(regs)) + if (user_mode(regs)) { + irqflags = fault_entry(ARM_TRAP_ACCESS, regs); __do_user_fault(addr, fsr, SIGSEGV, SEGV_MAPERR, regs); - else + fault_exit(ARM_TRAP_ACCESS, regs, irqflags); + } else + /* + * irq_pipeline: kernel faults are either quickly + * recoverable via fixup, or lethal. In both cases, we + * can skip the interrupt state synchronization. + */ __do_kernel_fault(mm, addr, fsr, regs); } @@ -244,9 +321,12 @@ do_page_fault(unsigned long addr, unsigned int fsr, struct pt_regs *regs) vm_fault_t fault; unsigned int flags = FAULT_FLAG_DEFAULT; unsigned long vm_flags = VM_ACCESS_FLAGS; + unsigned long irqflags; + + irqflags = fault_entry(ARM_TRAP_ACCESS, regs); if (kprobe_page_fault(regs, fsr)) - return 0; + goto out; /* Enable interrupts if they were enabled in the parent context. */ @@ -301,7 +381,7 @@ do_page_fault(unsigned long addr, unsigned int fsr, struct pt_regs *regs) if (fault_signal_pending(fault, regs)) { if (!user_mode(regs)) goto no_context; - return 0; + goto out; } /* The fault is fully completed (including releasing mmap lock) */ @@ -321,7 +401,7 @@ do_page_fault(unsigned long addr, unsigned int fsr, struct pt_regs *regs) * Handle the "normal" case first - VM_FAULT_MAJOR */ if (likely(!(fault & (VM_FAULT_ERROR | VM_FAULT_BADMAP | VM_FAULT_BADACCESS)))) - return 0; + goto out; bad_area: /* @@ -338,7 +418,7 @@ do_page_fault(unsigned long addr, unsigned int fsr, struct pt_regs *regs) * got oom-killed) */ pagefault_out_of_memory(); - return 0; + goto out; } if (fault & VM_FAULT_SIGBUS) { @@ -359,10 +439,13 @@ do_page_fault(unsigned long addr, unsigned int fsr, struct pt_regs *regs) } __do_user_fault(addr, fsr, sig, code, regs); - return 0; + goto out; no_context: __do_kernel_fault(mm, addr, fsr, regs); +out: + fault_exit(ARM_TRAP_ACCESS, regs, irqflags); + return 0; } #else /* CONFIG_MMU */ @@ -401,6 +484,8 @@ do_translation_fault(unsigned long addr, unsigned int fsr, pud_t *pud, *pud_k; pmd_t *pmd, *pmd_k; + WARN_ON_ONCE(irqs_pipelined() && !hard_irqs_disabled()); + if (addr < TASK_SIZE) return do_page_fault(addr, fsr, regs); @@ -474,7 +559,11 @@ do_translation_fault(unsigned long addr, unsigned int fsr, static int do_sect_fault(unsigned long addr, unsigned int fsr, struct pt_regs *regs) { + unsigned long irqflags; + + irqflags = fault_entry(ARM_TRAP_SECTION, regs); do_bad_area(addr, fsr, regs); + fault_exit(ARM_TRAP_SECTION, regs, irqflags); return 0; } #endif /* CONFIG_ARM_LPAE */ @@ -522,10 +611,12 @@ asmlinkage void do_DataAbort(unsigned long addr, unsigned int fsr, struct pt_regs *regs) { const struct fsr_info *inf = fsr_info + fsr_fs(fsr); + unsigned long irqflags; if (!inf->fn(addr, fsr & ~FSR_LNX_PF, regs)) return; + irqflags = fault_entry(ARM_TRAP_DABT, regs); pr_alert("8<--- cut here ---\n"); pr_alert("Unhandled fault: %s (0x%03x) at 0x%08lx\n", inf->name, fsr, addr); @@ -533,6 +624,7 @@ do_DataAbort(unsigned long addr, unsigned int fsr, struct pt_regs *regs) arm_notify_die("", regs, inf->sig, inf->code, (void __user *)addr, fsr, 0); + fault_exit(ARM_TRAP_DABT, regs, irqflags); } void __init @@ -552,15 +644,18 @@ asmlinkage void do_PrefetchAbort(unsigned long addr, unsigned int ifsr, struct pt_regs *regs) { const struct fsr_info *inf = ifsr_info + fsr_fs(ifsr); + unsigned long irqflags; if (!inf->fn(addr, ifsr | FSR_LNX_PF, regs)) return; + irqflags = fault_entry(ARM_TRAP_PABT, regs); pr_alert("Unhandled prefetch abort: %s (0x%03x) at 0x%08lx\n", inf->name, ifsr, addr); arm_notify_die("", regs, inf->sig, inf->code, (void __user *)addr, ifsr, 0); + fault_exit(ARM_TRAP_PABT, regs, irqflags); } /* diff --git a/arch/arm/vdso/datapage.S b/arch/arm/vdso/datapage.S index 9cd73b725..9beb76db2 100644 --- a/arch/arm/vdso/datapage.S +++ b/arch/arm/vdso/datapage.S @@ -5,6 +5,8 @@ .align 2 .L_vdso_data_ptr: .long _start - . - VDSO_DATA_SIZE +.L_vdso_priv_ptr: + .long _start - . - VDSO_DATA_SIZE - VDSO_PRIV_SIZE ENTRY(__get_datapage) .fnstart @@ -14,3 +16,12 @@ ENTRY(__get_datapage) bx lr .fnend ENDPROC(__get_datapage) + +ENTRY(__get_privpage) + .fnstart + adr r0, .L_vdso_priv_ptr + ldr r1, [r0] + add r0, r0, r1 + bx lr + .fnend +ENDPROC(__get_privpage) diff --git a/arch/arm/vfp/vfpmodule.c b/arch/arm/vfp/vfpmodule.c index a1ff693e4..5224e2a7e 100644 --- a/arch/arm/vfp/vfpmodule.c +++ b/arch/arm/vfp/vfpmodule.c @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -90,6 +91,7 @@ static void vfp_force_reload(unsigned int cpu, struct thread_info *thread) static void vfp_thread_flush(struct thread_info *thread) { union vfp_state *vfp = &thread->vfpstate; + unsigned long flags; unsigned int cpu; /* @@ -100,11 +102,11 @@ static void vfp_thread_flush(struct thread_info *thread) * Do this first to ensure that preemption won't overwrite our * state saving should access to the VFP be enabled at this point. */ - cpu = get_cpu(); + cpu = hard_get_cpu(flags); if (vfp_current_hw_state[cpu] == vfp) vfp_current_hw_state[cpu] = NULL; fmxr(FPEXC, fmrx(FPEXC) & ~FPEXC_EN); - put_cpu(); + hard_put_cpu(flags); memset(vfp, 0, sizeof(union vfp_state)); @@ -119,11 +121,14 @@ static void vfp_thread_exit(struct thread_info *thread) { /* release case: Per-thread VFP cleanup. */ union vfp_state *vfp = &thread->vfpstate; - unsigned int cpu = get_cpu(); + unsigned long flags; + unsigned int cpu; + + cpu = hard_get_cpu(flags); if (vfp_current_hw_state[cpu] == vfp) vfp_current_hw_state[cpu] = NULL; - put_cpu(); + hard_put_cpu(flags); } static void vfp_thread_copy(struct thread_info *thread) @@ -160,12 +165,14 @@ static int vfp_notifier(struct notifier_block *self, unsigned long cmd, void *v) { struct thread_info *thread = v; u32 fpexc; + unsigned long flags; #ifdef CONFIG_SMP unsigned int cpu; #endif switch (cmd) { case THREAD_NOTIFY_SWITCH: + flags = hard_cond_local_irq_save(); fpexc = fmrx(FPEXC); #ifdef CONFIG_SMP @@ -188,6 +195,7 @@ static int vfp_notifier(struct notifier_block *self, unsigned long cmd, void *v) * old state. */ fmxr(FPEXC, fpexc & ~FPEXC_EN); + hard_cond_local_irq_restore(flags); break; case THREAD_NOTIFY_FLUSH: @@ -251,7 +259,10 @@ static void vfp_raise_exceptions(u32 exceptions, u32 inst, u32 fpscr, struct pt_ if (exceptions == VFP_EXCEPTION_ERROR) { vfp_panic("unhandled bounce", inst); - vfp_raise_sigfpe(FPE_FLTINV, regs); + if (mark_cond_trap_entry(ARM_TRAP_VFP, regs)) { + vfp_raise_sigfpe(FPE_FLTINV, regs); + mark_trap_exit(ARM_TRAP_VFP, regs); + } return; } @@ -323,10 +334,15 @@ static u32 vfp_emulate_instruction(u32 inst, u32 fpscr, struct pt_regs *regs) /* * Package up a bounce condition. + * + * Dovetail: always enters with hard irqs off, bh disabled if running + * inband. We make sure to read the fpregs we need before re-enabling + * hard irqs, at which point an oob task might preempt. Returns with + * hard irqs ON, which matches the converse toggle in vfp_support_entry(). */ static void VFP_bounce(u32 trigger, u32 fpexc, struct pt_regs *regs) { - u32 fpscr, orig_fpscr, fpsid, exceptions; + u32 fpscr, orig_fpscr, fpsid, exceptions, next_trigger = 0; pr_debug("VFP: bounce: trigger %08x fpexc %08x\n", trigger, fpexc); @@ -356,6 +372,7 @@ static void VFP_bounce(u32 trigger, u32 fpexc, struct pt_regs *regs) /* * Synchronous exception, emulate the trigger instruction */ + hard_cond_local_irq_enable(); goto emulate; } @@ -366,13 +383,28 @@ static void VFP_bounce(u32 trigger, u32 fpexc, struct pt_regs *regs) */ trigger = fmrx(FPINST); regs->ARM_pc -= 4; - } else if (!(fpexc & FPEXC_DEX)) { + if (fpexc & FPEXC_FP2V) { + /* + * The barrier() here prevents fpinst2 being read + * before the condition above. + * + * Dovetail: we read fpinst2 early before + * re-enabling hard irqs. + */ + barrier(); + next_trigger = fmrx(FPINST2); + } + } + + hard_cond_local_irq_enable(); /* Matches converse in vfp_support_entry(). */ + + if (!(fpexc & (FPEXC_EX | FPEXC_DEX))) { /* * Illegal combination of bits. It can be caused by an * unallocated VFP instruction but with FPSCR.IXE set and not * on VFP subarch 1. */ - vfp_raise_exceptions(VFP_EXCEPTION_ERROR, trigger, fpscr, regs); + vfp_raise_exceptions(VFP_EXCEPTION_ERROR, trigger, fpscr, regs); return; } @@ -406,12 +438,7 @@ static void VFP_bounce(u32 trigger, u32 fpexc, struct pt_regs *regs) if ((fpexc & (FPEXC_EX | FPEXC_FP2V)) != (FPEXC_EX | FPEXC_FP2V)) return; - /* - * The barrier() here prevents fpinst2 being read - * before the condition above. - */ - barrier(); - trigger = fmrx(FPINST2); + trigger = next_trigger; emulate: exceptions = vfp_emulate_instruction(trigger, orig_fpscr, regs); @@ -518,9 +545,8 @@ static inline void vfp_pm_init(void) { } */ void vfp_sync_hwstate(struct thread_info *thread) { - unsigned int cpu = get_cpu(); - - local_bh_disable(); + unsigned long flags; + unsigned int cpu = hard_get_cpu(flags); if (vfp_state_in_hw(cpu, thread)) { u32 fpexc = fmrx(FPEXC); @@ -534,18 +560,18 @@ void vfp_sync_hwstate(struct thread_info *thread) fmxr(FPEXC, fpexc); } - local_bh_enable(); - put_cpu(); + hard_put_cpu(flags); } /* Ensure that the thread reloads the hardware VFP state on the next use. */ void vfp_flush_hwstate(struct thread_info *thread) { - unsigned int cpu = get_cpu(); + unsigned long flags; + unsigned int cpu = hard_get_cpu(flags); vfp_force_reload(cpu, thread); - put_cpu(); + hard_put_cpu(flags); } /* @@ -687,6 +713,7 @@ static int vfp_kmode_exception(struct pt_regs *regs, unsigned int instr) static int vfp_support_entry(struct pt_regs *regs, u32 trigger) { struct thread_info *ti = current_thread_info(); + int ret = 0; u32 fpexc; if (unlikely(!have_vfp)) @@ -695,7 +722,12 @@ static int vfp_support_entry(struct pt_regs *regs, u32 trigger) if (!user_mode(regs)) return vfp_kmode_exception(regs, trigger); - local_bh_disable(); + if (running_inband()) + local_bh_disable(); + + /* Dovetail: guard against preemption from oob task. */ + hard_cond_local_irq_disable(); + fpexc = fmrx(FPEXC); /* @@ -760,6 +792,8 @@ static int vfp_support_entry(struct pt_regs *regs, u32 trigger) * replay the instruction that trapped. */ fmxr(FPEXC, fpexc); + + hard_cond_local_irq_enable(); } else { /* Check for synchronous or asynchronous exceptions */ if (!(fpexc & (FPEXC_EX | FPEXC_DEX))) { @@ -774,18 +808,26 @@ static int vfp_support_entry(struct pt_regs *regs, u32 trigger) if (!(fpscr & FPSCR_IXE)) { if (!(fpscr & FPSCR_LENGTH_MASK)) { pr_debug("not VFP\n"); - local_bh_enable(); - return -ENOEXEC; + ret = -ENOEXEC; + goto out; } fpexc |= FPEXC_DEX; } } bounce: regs->ARM_pc += 4; - VFP_bounce(trigger, fpexc, regs); + VFP_bounce(trigger, fpexc, regs); /* Returns with hard irqs on. */ } - local_bh_enable(); - return 0; +out: + /* + * Dovetail: we might have switched from oob to inband context + * in vfp_raise_exceptions(), in which case we did not disable + * bh on entry, so make sure not to spuriously restore it. + */ + if (running_inband() && softirq_count() == SOFTIRQ_DISABLE_OFFSET) + local_bh_enable(); + + return ret; } static struct undef_hook neon_support_hook[] = {{ diff --git a/arch/arm64/Kconfig b/arch/arm64/Kconfig index 401ffd960..fa5879e09 100644 --- a/arch/arm64/Kconfig +++ b/arch/arm64/Kconfig @@ -181,6 +181,7 @@ config ARM64 select HAVE_ARCH_TRACEHOOK select HAVE_ARCH_TRANSPARENT_HUGEPAGE select HAVE_ARCH_VMAP_STACK + select HAVE_ARCH_EVL select HAVE_ARM_SMCCC select HAVE_ASM_MODVERSIONS select HAVE_EBPF_JIT @@ -215,6 +216,8 @@ config ARM64 HW_PERF_EVENTS && HAVE_PERF_EVENTS_NMI select HAVE_HW_BREAKPOINT if PERF_EVENTS select HAVE_IOREMAP_PROT + select HAVE_IRQ_PIPELINE + select HAVE_DOVETAIL select HAVE_IRQ_TIME_ACCOUNTING select HAVE_KVM select HAVE_MOD_ARCH_SPECIFIC @@ -1525,6 +1528,9 @@ config HW_PERF_EVENTS config CC_HAVE_SHADOW_CALL_STACK def_bool $(cc-option, -fsanitize=shadow-call-stack -ffixed-x18) +source "kernel/Kconfig.dovetail" +source "kernel/Kconfig.evl" + config PARAVIRT bool "Enable paravirtualization code" help diff --git a/arch/arm64/Makefile b/arch/arm64/Makefile index 117828607..dc9a29eec 100644 --- a/arch/arm64/Makefile +++ b/arch/arm64/Makefile @@ -140,6 +140,10 @@ else ifeq ($(CONFIG_KASAN_GENERIC), y) KASAN_SHADOW_SCALE_SHIFT := 3 endif +ifeq ($(CONFIG_EVENLESS),y) +KBUILD_CFLAGS += -Iarch/$(SRCARCH)/evenless/include -Iinclude/evenless +endif + KBUILD_CFLAGS += -DKASAN_SHADOW_SCALE_SHIFT=$(KASAN_SHADOW_SCALE_SHIFT) KBUILD_CPPFLAGS += -DKASAN_SHADOW_SCALE_SHIFT=$(KASAN_SHADOW_SCALE_SHIFT) KBUILD_AFLAGS += -DKASAN_SHADOW_SCALE_SHIFT=$(KASAN_SHADOW_SCALE_SHIFT) diff --git a/arch/arm64/include/asm/daifflags.h b/arch/arm64/include/asm/daifflags.h index 55f57dfa8..9f863ce0a 100644 --- a/arch/arm64/include/asm/daifflags.h +++ b/arch/arm64/include/asm/daifflags.h @@ -12,6 +12,12 @@ #include #include +/* + * irq_pipeline: DAIF masking is only used in contexts where hard + * interrupt masking applies, so no need to virtualize for the inband + * stage here (the pipeline core does assume this). + */ + #define DAIF_PROCCTX 0 #define DAIF_PROCCTX_NOIRQ (PSR_I_BIT | PSR_F_BIT) #define DAIF_ERRCTX (PSR_A_BIT | PSR_I_BIT | PSR_F_BIT) @@ -35,7 +41,7 @@ static inline void local_daif_mask(void) if (system_uses_irq_prio_masking()) gic_write_pmr(GIC_PRIO_IRQON | GIC_PRIO_PSR_I_SET); - trace_hardirqs_off(); + trace_hardirqs_off_pipelined(); } static inline unsigned long local_daif_save_flags(void) @@ -72,7 +78,7 @@ static inline void local_daif_restore(unsigned long flags) (read_sysreg(daif) & (PSR_I_BIT | PSR_F_BIT)) != (PSR_I_BIT | PSR_F_BIT)); if (!irq_disabled) { - trace_hardirqs_on(); + trace_hardirqs_on_pipelined(); if (system_uses_irq_prio_masking()) { gic_write_pmr(GIC_PRIO_IRQON); @@ -117,7 +123,7 @@ static inline void local_daif_restore(unsigned long flags) write_sysreg(flags, daif); if (irq_disabled) - trace_hardirqs_off(); + trace_hardirqs_off_pipelined(); } /* @@ -129,7 +135,7 @@ static inline void local_daif_inherit(struct pt_regs *regs) unsigned long flags = regs->pstate & DAIF_MASK; if (interrupts_enabled(regs)) - trace_hardirqs_on(); + trace_hardirqs_on_pipelined(); if (system_uses_irq_prio_masking()) gic_write_pmr(regs->pmr_save); diff --git a/arch/arm64/include/asm/dovetail.h b/arch/arm64/include/asm/dovetail.h new file mode 100644 index 000000000..b6d29ab24 --- /dev/null +++ b/arch/arm64/include/asm/dovetail.h @@ -0,0 +1,74 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2018 Philippe Gerum . + */ +#ifndef _ASM_ARM64_DOVETAIL_H +#define _ASM_ARM64_DOVETAIL_H + +#include + +/* ARM64 traps */ +#define ARM64_TRAP_ACCESS 0 /* Data or instruction access exception */ +#define ARM64_TRAP_ALIGN 1 /* SP/PC alignment abort */ +#define ARM64_TRAP_SEA 2 /* Synchronous external abort */ +#define ARM64_TRAP_DEBUG 3 /* Debug trap */ +#define ARM64_TRAP_UNDI 4 /* Undefined instruction */ +#define ARM64_TRAP_UNDSE 5 /* Undefined synchronous exception */ +#define ARM64_TRAP_FPE 6 /* FPSIMD exception */ +#define ARM64_TRAP_SVE 7 /* SVE access trap */ +#define ARM64_TRAP_BTI 8 /* Branch target identification */ +#define ARM64_TRAP_SME 9 /* SME access trap */ + +#ifdef CONFIG_DOVETAIL + +static inline void arch_dovetail_exec_prepare(void) +{ } + +static inline void arch_dovetail_switch_prepare(bool leave_inband) +{ } + +static inline void arch_dovetail_switch_finish(bool enter_inband) +{ + fpsimd_restore_current_oob(); +} + +/* + * 172 is __NR_prctl from unistd32 in ARM32 mode, without #inclusion + * hell. At the end of the day, this number is written in stone to + * honor the ABI stability promise anyway. + */ +#define arch_dovetail_is_prctl(__nr) \ + (is_compat_task() ? (__nr) == 172 : (__nr) == __NR_prctl) + +#endif + +/* + * Pass the trap event to the companion core. Return true if running + * in-band afterwards. + */ +#define mark_cond_trap_entry(__trapnr, __regs) \ + ({ \ + bool __ret; \ + oob_trap_notify(__trapnr, __regs); \ + __ret = running_inband(); \ + if (!__ret) \ + oob_trap_unwind(__trapnr, __regs); \ + __ret; \ + }) + +/* + * Pass the trap event to the companion core. We expect the current + * context to be running on the in-band stage upon return so that our + * caller can tread on common kernel code. + */ +#define mark_trap_entry(__trapnr, __regs) \ + do { \ + bool __ret = mark_cond_trap_entry(__trapnr, __regs); \ + BUG_ON(dovetail_debug() && !__ret); \ + } while (0) + +#define mark_trap_exit(__trapnr, __regs) \ + oob_trap_unwind(__trapnr, __regs) + +#endif /* _ASM_ARM64_DOVETAIL_H */ diff --git a/arch/arm64/include/asm/efi.h b/arch/arm64/include/asm/efi.h index bcd5622aa..34aaa6443 100644 --- a/arch/arm64/include/asm/efi.h +++ b/arch/arm64/include/asm/efi.h @@ -120,6 +120,10 @@ extern unsigned long primary_entry_offset(void); static inline void efi_set_pgd(struct mm_struct *mm) { + unsigned long flags; + + protect_inband_mm(flags); + __switch_mm(mm); if (system_uses_ttbr0_pan()) { @@ -144,6 +148,8 @@ static inline void efi_set_pgd(struct mm_struct *mm) update_saved_ttbr0(current, current->active_mm); } } + + unprotect_inband_mm(flags); } void efi_virtmap_load(void); diff --git a/arch/arm64/include/asm/evl/calibration.h b/arch/arm64/include/asm/evl/calibration.h new file mode 100644 index 000000000..297f131b1 --- /dev/null +++ b/arch/arm64/include/asm/evl/calibration.h @@ -0,0 +1,12 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _EVL_ARM64_ASM_CALIBRATION_H +#define _EVL_ARM64_ASM_CALIBRATION_H + +#include + +static inline unsigned int evl_get_default_clock_gravity(void) +{ + return 3000; +} + +#endif /* !_EVL_ARM64_ASM_CALIBRATION_H */ diff --git a/arch/arm64/include/asm/evl/fptest.h b/arch/arm64/include/asm/evl/fptest.h new file mode 100644 index 000000000..a853b1206 --- /dev/null +++ b/arch/arm64/include/asm/evl/fptest.h @@ -0,0 +1,28 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _EVL_ARM64_ASM_FPTEST_H +#define _EVL_ARM64_ASM_FPTEST_H + +#include +#include + +static inline bool evl_begin_fpu(void) +{ + return false; +} + +static inline void evl_end_fpu(void) { } + +static inline u32 evl_detect_fpu(void) +{ + u32 features = 0; + + if (system_supports_fpsimd()) + return features |= evl_arm64_fpsimd; + + if (system_supports_sve()) + return features |= evl_arm64_sve; + + return features; +} + +#endif /* _EVL_ARM64_ASM_FPTEST_H */ diff --git a/arch/arm64/include/asm/evl/syscall.h b/arch/arm64/include/asm/evl/syscall.h new file mode 100644 index 000000000..7459d82c3 --- /dev/null +++ b/arch/arm64/include/asm/evl/syscall.h @@ -0,0 +1,33 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _EVL_ARM64_ASM_SYSCALL_H +#define _EVL_ARM64_ASM_SYSCALL_H + +#include +#include +#include +#include + +#define raw_put_user(src, dst) __put_user(src, dst) +#define raw_get_user(dst, src) __get_user(dst, src) + +#define __ARM_NR_BASE_compat 0xf0000 + +static inline bool +is_valid_inband_syscall(unsigned int nr) +{ + return nr < NR_syscalls; +} + +#ifdef CONFIG_COMPAT +static inline bool is_compat_oob_call(void) +{ + return is_compat_task(); +} +#else +static inline bool is_compat_oob_call(void) +{ + return false; +} +#endif + +#endif /* !_EVL_ARM64_ASM_SYSCALL_H */ diff --git a/arch/arm64/include/asm/evl/thread.h b/arch/arm64/include/asm/evl/thread.h new file mode 100644 index 000000000..3939cdbd1 --- /dev/null +++ b/arch/arm64/include/asm/evl/thread.h @@ -0,0 +1,10 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _EVL_ARM64_ASM_THREAD_H +#define _EVL_ARM64_ASM_THREAD_H + +static inline bool evl_is_breakpoint(int trapnr) +{ + return trapnr == ARM64_TRAP_DEBUG || trapnr == ARM64_TRAP_UNDI; +} + +#endif /* !_EVL_ARM64_ASM_THREAD_H */ diff --git a/arch/arm64/include/asm/fpsimd.h b/arch/arm64/include/asm/fpsimd.h index 7415c63b4..26a433a02 100644 --- a/arch/arm64/include/asm/fpsimd.h +++ b/arch/arm64/include/asm/fpsimd.h @@ -55,6 +55,7 @@ extern void fpsimd_flush_thread(void); extern void fpsimd_signal_preserve_current_state(void); extern void fpsimd_preserve_current_state(void); extern void fpsimd_restore_current_state(void); +extern void fpsimd_restore_current_oob(void); extern void fpsimd_update_current_state(struct user_fpsimd_state const *state); extern void fpsimd_kvm_prepare(void); diff --git a/arch/arm64/include/asm/irq_pipeline.h b/arch/arm64/include/asm/irq_pipeline.h new file mode 100644 index 000000000..09cb33b82 --- /dev/null +++ b/arch/arm64/include/asm/irq_pipeline.h @@ -0,0 +1,149 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2018 Philippe Gerum . + */ +#ifndef _ASM_ARM64_IRQ_PIPELINE_H +#define _ASM_ARM64_IRQ_PIPELINE_H + +#include + +#ifdef CONFIG_IRQ_PIPELINE + +/* + * In order to cope with the limited number of SGIs available to us, + * In-band IPI messages are multiplexed over SGI0, whereas out-of-band + * IPIs are directly mapped to SGI1-3. + */ +#define OOB_NR_IPI 3 +#define OOB_IPI_OFFSET 1 /* SGI1 */ +#define TIMER_OOB_IPI (ipi_irq_base + OOB_IPI_OFFSET) +#define RESCHEDULE_OOB_IPI (TIMER_OOB_IPI + 1) +#define CALL_FUNCTION_OOB_IPI (RESCHEDULE_OOB_IPI + 1) + +extern int ipi_irq_base; + +static inline notrace +unsigned long arch_irqs_virtual_to_native_flags(int stalled) +{ + return (!!stalled) << IRQMASK_I_POS; +} + +static inline notrace +unsigned long arch_irqs_native_to_virtual_flags(unsigned long flags) +{ + return (!!hard_irqs_disabled_flags(flags)) << IRQMASK_i_POS; +} + +static inline notrace unsigned long arch_local_irq_save(void) +{ + int stalled = inband_irq_save(); + barrier(); + return arch_irqs_virtual_to_native_flags(stalled); +} + +static inline notrace void arch_local_irq_enable(void) +{ + barrier(); + inband_irq_enable(); +} + +static inline notrace void arch_local_irq_disable(void) +{ + inband_irq_disable(); + barrier(); +} + +static inline notrace unsigned long arch_local_save_flags(void) +{ + int stalled = inband_irqs_disabled(); + barrier(); + return arch_irqs_virtual_to_native_flags(stalled); +} + +static inline int arch_irqs_disabled_flags(unsigned long flags) +{ + return native_irqs_disabled_flags(flags); +} + +static inline notrace void arch_local_irq_restore(unsigned long flags) +{ + inband_irq_restore(arch_irqs_disabled_flags(flags)); + barrier(); +} + +static inline +void arch_save_timer_regs(struct pt_regs *dst, struct pt_regs *src) +{ + dst->pstate = src->pstate; + dst->pc = src->pc; +} + +static inline bool arch_steal_pipelined_tick(struct pt_regs *regs) +{ + return !!(regs->pstate & IRQMASK_I_BIT); +} + +static inline int arch_enable_oob_stage(void) +{ + return 0; +} + +extern void (*handle_arch_irq)(struct pt_regs *); + +static inline void arch_handle_irq_pipelined(struct pt_regs *regs) +{ + handle_arch_irq(regs); +} + +/* + * We use neither the generic entry code nor + * kentry_enter/exit_pipelined yet. We still build a no-op version of + * the latter for now, until we enventually switch to using whichever + * of them is available first. + */ +#define arch_kentry_get_irqstate(__regs) 0 + +#define arch_kentry_set_irqstate(__regs, __irqstate) \ + do { (void)__irqstate; } while (0) + +#else /* !CONFIG_IRQ_PIPELINE */ + +static inline unsigned long arch_local_irq_save(void) +{ + return native_irq_save(); +} + +static inline void arch_local_irq_enable(void) +{ + native_irq_enable(); +} + +static inline void arch_local_irq_disable(void) +{ + native_irq_disable(); +} + +static inline unsigned long arch_local_save_flags(void) +{ + return native_save_flags(); +} + +static inline void arch_local_irq_restore(unsigned long flags) +{ + native_irq_restore(flags); +} + +static inline int arch_irqs_disabled_flags(unsigned long flags) +{ + return native_irqs_disabled_flags(flags); +} + +#endif /* !CONFIG_IRQ_PIPELINE */ + +static inline int arch_irqs_disabled(void) +{ + return arch_irqs_disabled_flags(arch_local_save_flags()); +} + +#endif /* _ASM_ARM64_IRQ_PIPELINE_H */ diff --git a/arch/arm64/include/asm/irqflags.h b/arch/arm64/include/asm/irqflags.h index 1f31ec146..c53d8c5f5 100644 --- a/arch/arm64/include/asm/irqflags.h +++ b/arch/arm64/include/asm/irqflags.h @@ -10,6 +10,10 @@ #include #include +#define IRQMASK_I_BIT PSR_I_BIT +#define IRQMASK_I_POS 7 +#define IRQMASK_i_POS 31 + /* * Aarch64 has flags for masking: Debug, Asynchronous (serror), Interrupts and * FIQ exceptions, in the 'daif' register. We mask and unmask them in 'daif' @@ -47,7 +51,7 @@ static __always_inline void __pmr_local_irq_enable(void) barrier(); } -static inline void arch_local_irq_enable(void) +static inline void native_irq_enable(void) { if (__irqflags_uses_pmr()) { __pmr_local_irq_enable(); @@ -75,7 +79,7 @@ static __always_inline void __pmr_local_irq_disable(void) barrier(); } -static inline void arch_local_irq_disable(void) +static inline void native_irq_disable(void) { if (__irqflags_uses_pmr()) { __pmr_local_irq_disable(); @@ -94,10 +98,17 @@ static __always_inline unsigned long __pmr_local_save_flags(void) return read_sysreg_s(SYS_ICC_PMR_EL1); } +static inline void native_irq_sync(void) +{ + native_irq_enable(); + isb(); + native_irq_disable(); +} + /* * Save the current interrupt enable state. */ -static inline unsigned long arch_local_save_flags(void) +static inline unsigned long native_save_flags(void) { if (__irqflags_uses_pmr()) { return __pmr_local_save_flags(); @@ -116,7 +127,7 @@ static __always_inline bool __pmr_irqs_disabled_flags(unsigned long flags) return flags != GIC_PRIO_IRQON; } -static inline bool arch_irqs_disabled_flags(unsigned long flags) +static inline bool native_irqs_disabled_flags(unsigned long flags) { if (__irqflags_uses_pmr()) { return __pmr_irqs_disabled_flags(flags); @@ -135,7 +146,7 @@ static __always_inline bool __pmr_irqs_disabled(void) return __pmr_irqs_disabled_flags(__pmr_local_save_flags()); } -static inline bool arch_irqs_disabled(void) +static inline bool native_irqs_disabled(void) { if (__irqflags_uses_pmr()) { return __pmr_irqs_disabled(); @@ -167,7 +178,7 @@ static __always_inline unsigned long __pmr_local_irq_save(void) return flags; } -static inline unsigned long arch_local_irq_save(void) +static inline unsigned long native_irq_save(void) { if (__irqflags_uses_pmr()) { return __pmr_local_irq_save(); @@ -194,7 +205,7 @@ static __always_inline void __pmr_local_irq_restore(unsigned long flags) /* * restore saved IRQ state */ -static inline void arch_local_irq_restore(unsigned long flags) +static inline void native_irq_restore(unsigned long flags) { if (__irqflags_uses_pmr()) { __pmr_local_irq_restore(flags); @@ -203,4 +214,6 @@ static inline void arch_local_irq_restore(unsigned long flags) } } +#include + #endif /* __ASM_IRQFLAGS_H */ diff --git a/arch/arm64/include/asm/mmu_context.h b/arch/arm64/include/asm/mmu_context.h index a6fb32542..629a7b4ac 100644 --- a/arch/arm64/include/asm/mmu_context.h +++ b/arch/arm64/include/asm/mmu_context.h @@ -15,6 +15,7 @@ #include #include #include +#include #include #include @@ -101,6 +102,9 @@ static inline void __cpu_set_tcr_t0sz(unsigned long t0sz) static inline void cpu_uninstall_idmap(void) { struct mm_struct *mm = current->active_mm; + unsigned long flags; + + flags = hard_cond_local_irq_save(); cpu_set_reserved_ttbr0(); local_flush_tlb_all(); @@ -108,15 +112,23 @@ static inline void cpu_uninstall_idmap(void) if (mm != &init_mm && !system_uses_ttbr0_pan()) cpu_switch_mm(mm->pgd, mm); + + hard_cond_local_irq_restore(flags); } static inline void __cpu_install_idmap(pgd_t *idmap) { + unsigned long flags; + + flags = hard_cond_local_irq_save(); + cpu_set_reserved_ttbr0(); local_flush_tlb_all(); cpu_set_idmap_tcr_t0sz(); cpu_switch_mm(lm_alias(idmap), &init_mm); + + hard_cond_local_irq_restore(flags); } static inline void cpu_install_idmap(void) @@ -258,7 +270,7 @@ static inline void __switch_mm(struct mm_struct *next) } static inline void -switch_mm(struct mm_struct *prev, struct mm_struct *next, +do_switch_mm(struct mm_struct *prev, struct mm_struct *next, struct task_struct *tsk) { if (prev != next) @@ -273,6 +285,24 @@ switch_mm(struct mm_struct *prev, struct mm_struct *next, update_saved_ttbr0(tsk, next); } +static inline void +switch_mm(struct mm_struct *prev, struct mm_struct *next, + struct task_struct *tsk) +{ + unsigned long flags; + + protect_inband_mm(flags); + do_switch_mm(prev, next, tsk); + unprotect_inband_mm(flags); +} + +static inline void +switch_oob_mm(struct mm_struct *prev, struct mm_struct *next, + struct task_struct *tsk) /* hard irqs off */ +{ + do_switch_mm(prev, next, tsk); +} + static inline const struct cpumask * task_cpu_possible_mask(struct task_struct *p) { diff --git a/arch/arm64/include/asm/ptrace.h b/arch/arm64/include/asm/ptrace.h index 47ec58031..729044c87 100644 --- a/arch/arm64/include/asm/ptrace.h +++ b/arch/arm64/include/asm/ptrace.h @@ -200,7 +200,13 @@ struct pt_regs { /* Only valid for some EL1 exceptions. */ u64 lockdep_hardirqs; +#ifdef CONFIG_IRQ_PIPELINE + u64 exit_rcu : 1, + oob_on_entry : 1, + stalled_on_entry : 1; +#else u64 exit_rcu; +#endif }; static inline bool in_syscall(struct pt_regs const *regs) diff --git a/arch/arm64/include/asm/syscall.h b/arch/arm64/include/asm/syscall.h index ab8e14b96..3cf564634 100644 --- a/arch/arm64/include/asm/syscall.h +++ b/arch/arm64/include/asm/syscall.h @@ -73,6 +73,12 @@ static inline void syscall_get_arguments(struct task_struct *task, memcpy(args, ®s->regs[1], 5 * sizeof(args[0])); } +static inline unsigned long syscall_get_arg0(struct task_struct *task, + struct pt_regs *regs) +{ + return regs->orig_x0; +} + /* * We don't care about endianness (__AUDIT_ARCH_LE bit) here because * AArch64 has the same system calls both on little- and big- endian. diff --git a/arch/arm64/include/asm/thread_info.h b/arch/arm64/include/asm/thread_info.h index 553d1bc55..901e2a378 100644 --- a/arch/arm64/include/asm/thread_info.h +++ b/arch/arm64/include/asm/thread_info.h @@ -14,6 +14,7 @@ struct task_struct; +#include #include #include #include @@ -23,6 +24,7 @@ struct task_struct; */ struct thread_info { unsigned long flags; /* low level flags */ + unsigned long local_flags; /* local (synchronous) flags */ #ifdef CONFIG_ARM64_SW_TTBR0_PAN u64 ttbr0; /* saved TTBR0_EL1 */ #endif @@ -43,6 +45,7 @@ struct thread_info { void *scs_sp; #endif u32 cpu; + struct oob_thread_state oob_state; }; #define thread_saved_pc(tsk) \ @@ -55,6 +58,8 @@ struct thread_info { void arch_setup_new_exec(void); #define arch_setup_new_exec arch_setup_new_exec +#define ti_local_flags(__ti) ((__ti)->local_flags) + #endif #define TIF_SIGPENDING 0 /* signal pending */ @@ -64,6 +69,7 @@ void arch_setup_new_exec(void); #define TIF_UPROBE 4 /* uprobe breakpoint or singlestep */ #define TIF_MTE_ASYNC_FAULT 5 /* MTE Asynchronous Tag Check Fault */ #define TIF_NOTIFY_SIGNAL 6 /* signal notifications exist */ +#define TIF_RETUSER 7 /* INBAND_TASK_RETUSER is pending */ #define TIF_SYSCALL_TRACE 8 /* syscall trace active */ #define TIF_SYSCALL_AUDIT 9 /* syscall auditing */ #define TIF_SYSCALL_TRACEPOINT 10 /* syscall tracepoint for ftrace */ @@ -80,6 +86,7 @@ void arch_setup_new_exec(void); #define TIF_TAGGED_ADDR 26 /* Allow tagged user addresses */ #define TIF_SME 27 /* SME in use */ #define TIF_SME_VL_INHERIT 28 /* Inherit SME vl_onexec across exec */ +#define TIF_MAYDAY 29 /* Emergency trap pending */ #define _TIF_SIGPENDING (1 << TIF_SIGPENDING) #define _TIF_NEED_RESCHED (1 << TIF_NEED_RESCHED) @@ -96,11 +103,13 @@ void arch_setup_new_exec(void); #define _TIF_SVE (1 << TIF_SVE) #define _TIF_MTE_ASYNC_FAULT (1 << TIF_MTE_ASYNC_FAULT) #define _TIF_NOTIFY_SIGNAL (1 << TIF_NOTIFY_SIGNAL) +#define _TIF_RETUSER (1 << TIF_RETUSER) +#define _TIF_MAYDAY (1 << TIF_MAYDAY) #define _TIF_WORK_MASK (_TIF_NEED_RESCHED | _TIF_SIGPENDING | \ _TIF_NOTIFY_RESUME | _TIF_FOREIGN_FPSTATE | \ _TIF_UPROBE | _TIF_MTE_ASYNC_FAULT | \ - _TIF_NOTIFY_SIGNAL) + _TIF_NOTIFY_SIGNAL | _TIF_RETUSER) #define _TIF_SYSCALL_WORK (_TIF_SYSCALL_TRACE | _TIF_SYSCALL_AUDIT | \ _TIF_SYSCALL_TRACEPOINT | _TIF_SECCOMP | \ @@ -121,4 +130,12 @@ void arch_setup_new_exec(void); INIT_SCS \ } +/* + * Local (synchronous) thread flags. + */ +#define _TLF_OOB 0x0001 +#define _TLF_DOVETAIL 0x0002 +#define _TLF_OFFSTAGE 0x0004 +#define _TLF_OOBTRAP 0x0008 + #endif /* __ASM_THREAD_INFO_H */ diff --git a/arch/arm64/include/asm/uaccess.h b/arch/arm64/include/asm/uaccess.h index 14be5000c..93f4b82a4 100644 --- a/arch/arm64/include/asm/uaccess.h +++ b/arch/arm64/include/asm/uaccess.h @@ -60,7 +60,7 @@ static inline void __uaccess_ttbr0_disable(void) { unsigned long flags, ttbr; - local_irq_save(flags); + flags = hard_local_irq_save(); ttbr = read_sysreg(ttbr1_el1); ttbr &= ~TTBR_ASID_MASK; /* reserved_pg_dir placed before swapper_pg_dir */ @@ -68,7 +68,7 @@ static inline void __uaccess_ttbr0_disable(void) /* Set reserved ASID */ write_sysreg(ttbr, ttbr1_el1); isb(); - local_irq_restore(flags); + hard_local_irq_restore(flags); } static inline void __uaccess_ttbr0_enable(void) @@ -80,7 +80,7 @@ static inline void __uaccess_ttbr0_enable(void) * variable and the MSR. A context switch could trigger an ASID * roll-over and an update of 'ttbr0'. */ - local_irq_save(flags); + flags = hard_local_irq_save(); ttbr0 = READ_ONCE(current_thread_info()->ttbr0); /* Restore active ASID */ @@ -92,7 +92,7 @@ static inline void __uaccess_ttbr0_enable(void) /* Restore user page table */ write_sysreg(ttbr0, ttbr0_el1); isb(); - local_irq_restore(flags); + hard_local_irq_restore(flags); } static inline bool uaccess_ttbr0_disable(void) diff --git a/arch/arm64/include/asm/vdso.h b/arch/arm64/include/asm/vdso.h index b4ae32109..30de8c8a2 100644 --- a/arch/arm64/include/asm/vdso.h +++ b/arch/arm64/include/asm/vdso.h @@ -13,6 +13,11 @@ #define VDSO_LBASE 0x0 #define __VVAR_PAGES 2 +#ifdef CONFIG_GENERIC_CLOCKSOURCE_VDSO +#define __VPRIV_PAGES 1 +#else +#define __VPRIV_PAGES 0 +#endif #ifndef __ASSEMBLY__ diff --git a/arch/arm64/include/asm/vdso/gettimeofday.h b/arch/arm64/include/asm/vdso/gettimeofday.h index 764d13e29..b3be784dd 100644 --- a/arch/arm64/include/asm/vdso/gettimeofday.h +++ b/arch/arm64/include/asm/vdso/gettimeofday.h @@ -113,6 +113,71 @@ const struct vdso_data *__arch_get_timens_vdso_data(const struct vdso_data *vd) } #endif +#ifdef CONFIG_GENERIC_CLOCKSOURCE_VDSO + +#include + +extern struct vdso_priv _vdso_priv __attribute__((visibility("hidden"))); /* vdso.lds.S */ + +static __always_inline struct vdso_priv *__arch_get_vdso_priv(void) +{ + return &_vdso_priv; +} + +static __always_inline int clock_open_device(const char *path, int mode) +{ + register int sc asm("w8") = __NR_openat; + register long ret asm("x0"); + register long x0 asm("x0") = AT_FDCWD; + register long x1 asm("x1") = (long)path; + register long x2 asm("x2") = mode; + + asm volatile( + "svc #0\n" + : "=r" (ret) + : "r" (sc), + "r" (x0), "r" (x1), "r" (x2) + : "cc", "memory"); + + return ret; +} + +static __always_inline int clock_ioctl_device(int fd, unsigned int cmd, long arg) +{ + register int sc asm("w8") = __NR_ioctl; + register long ret asm("x0"); + register long x0 asm("x0") = fd; + register long x1 asm("x1") = cmd; + register long x2 asm("x2") = arg; + + asm volatile( + "svc #0\n" + : "=r" (ret) + : "r" (sc), + "r" (x0), "r" (x1), "r" (x2) + : "cc", "memory"); + + return ret; +} + +static __always_inline int clock_close_device(int fd) +{ + register int sc asm("w8") = __NR_close; + register long ret asm("x0"); + register long x0 asm("x0") = fd; + + asm volatile( + "svc #0\n" + : "=r" (ret) + : "r" (sc), + "r" (x0) + : "cc", "memory"); + + return ret; +} + +#endif /* CONFIG_GENERIC_CLOCKSOURCE_VDSO */ + #endif /* !__ASSEMBLY__ */ #endif /* __ASM_VDSO_GETTIMEOFDAY_H */ diff --git a/arch/arm64/include/dovetail/irq.h b/arch/arm64/include/dovetail/irq.h new file mode 100644 index 000000000..f214e2f6e --- /dev/null +++ b/arch/arm64/include/dovetail/irq.h @@ -0,0 +1,11 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _EVL_DOVETAIL_IRQ_H +#define _EVL_DOVETAIL_IRQ_H + +#ifdef CONFIG_EVL +#include +#else +#include_next +#endif + +#endif /* !_EVL_DOVETAIL_IRQ_H */ diff --git a/arch/arm64/include/dovetail/mm_info.h b/arch/arm64/include/dovetail/mm_info.h new file mode 100644 index 000000000..13087687d --- /dev/null +++ b/arch/arm64/include/dovetail/mm_info.h @@ -0,0 +1,7 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _EVL_DOVETAIL_MM_INFO_H +#define _EVL_DOVETAIL_MM_INFO_H + +#include + +#endif /* !_EVL_DOVETAIL_MM_INFO_H */ diff --git a/arch/arm64/include/dovetail/net.h b/arch/arm64/include/dovetail/net.h new file mode 100644 index 000000000..b23cf3c5e --- /dev/null +++ b/arch/arm64/include/dovetail/net.h @@ -0,0 +1,7 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _EVL_DOVETAIL_NET_H +#define _EVL_DOVETAIL_NET_H + +#include + +#endif /* !_EVL_DOVETAIL_NET_H */ diff --git a/arch/arm64/include/dovetail/netdevice.h b/arch/arm64/include/dovetail/netdevice.h new file mode 100644 index 000000000..bc7ac6769 --- /dev/null +++ b/arch/arm64/include/dovetail/netdevice.h @@ -0,0 +1,7 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _EVL_DOVETAIL_NETDEVICE_H +#define _EVL_DOVETAIL_NETDEVICE_H + +#include + +#endif /* !_EVL_DOVETAIL_NETDEVICE_H */ diff --git a/arch/arm64/include/dovetail/poll.h b/arch/arm64/include/dovetail/poll.h new file mode 100644 index 000000000..76e51be38 --- /dev/null +++ b/arch/arm64/include/dovetail/poll.h @@ -0,0 +1,7 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _EVL_DOVETAIL_POLL_H +#define _EVL_DOVETAIL_POLL_H + +#include + +#endif /* !_EVL_DOVETAIL_POLL_H */ diff --git a/arch/arm64/include/dovetail/thread_info.h b/arch/arm64/include/dovetail/thread_info.h new file mode 100644 index 000000000..4253b13fe --- /dev/null +++ b/arch/arm64/include/dovetail/thread_info.h @@ -0,0 +1,7 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _EVL_DOVETAIL_THREAD_INFO_H +#define _EVL_DOVETAIL_THREAD_INFO_H + +#include + +#endif /* !_EVL_DOVETAIL_THREAD_INFO_H */ diff --git a/arch/arm64/include/uapi/asm/evl/fptest.h b/arch/arm64/include/uapi/asm/evl/fptest.h new file mode 100644 index 000000000..e083e952c --- /dev/null +++ b/arch/arm64/include/uapi/asm/evl/fptest.h @@ -0,0 +1,94 @@ +/* + * SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note + * + * Derived from Xenomai Cobalt, https://xenomai.org/ + * Copyright (C) 2006 Gilles Chanteperdrix . + */ +#ifndef _EVL_ARM64_ASM_UAPI_FPTEST_H +#define _EVL_ARM64_ASM_UAPI_FPTEST_H + +#include + +#define evl_arm64_fpsimd 0x1 +#define evl_arm64_sve 0x2 + +/* + * CAUTION: keep this code strictly inlined in macros: we don't want + * GCC to apply any callee-saved logic to fpsimd registers in + * evl_set_fpregs() before evl_check_fpregs() can verify their + * contents, but we still want GCC to know about the registers we have + * clobbered. + */ + +#define evl_set_fpregs(__features, __val) \ + do { \ + unsigned int __i; \ + __u64 __e[32]; \ + \ + if (__features & evl_arm64_fpsimd) { \ + for (__i = 0; __i < 32; __i++) \ + __e[__i] = (__val); \ + __asm__ __volatile__("ldp d0, d1, [%0, #8 * 0] \n" \ + "ldp d2, d3, [%0, #8 * 2] \n" \ + "ldp d4, d5, [%0, #8 * 4]\n" \ + "ldp d6, d7, [%0, #8 * 6]\n" \ + "ldp d8, d9, [%0, #8 * 8]\n" \ + "ldp d10, d11, [%0, #8 * 10]\n" \ + "ldp d12, d13, [%0, #8 * 12]\n" \ + "ldp d14, d15, [%0, #8 * 14]\n" \ + "ldp d16, d17, [%0, #8 * 16]\n" \ + "ldp d18, d19, [%0, #8 * 18]\n" \ + "ldp d20, d21, [%0, #8 * 20]\n" \ + "ldp d22, d23, [%0, #8 * 22]\n" \ + "ldp d24, d25, [%0, #8 * 24]\n" \ + "ldp d26, d27, [%0, #8 * 26]\n" \ + "ldp d28, d29, [%0, #8 * 28]\n" \ + "ldp d30, d31, [%0, #8 * 30]\n" \ + : /* No outputs. */ \ + : "r"(&__e[0]) \ + : "d0", "d1", "d2", "d3", "d4", "d5", "d6", \ + "d7", "d8", "d9", "d10", "d11", "d12", "d13", \ + "d14", "d15", "d16", "d17", "d18", "d19", \ + "d20", "d21", "d22", "d23", "d24", "d25", \ + "d26", "d27", "d28", "d29", "d30", "d31", \ + "memory"); \ + } \ + } while (0) + +#define evl_check_fpregs(__features, __val, __bad) \ + ({ \ + unsigned int __result = (__val), __i; \ + __u64 __e[32]; \ + \ + if (__features & evl_arm64_fpsimd) { \ + __asm__ __volatile__("stp d0, d1, [%0, #8 * 0] \n" \ + "stp d2, d3, [%0, #8 * 2] \n" \ + "stp d4, d5, [%0, #8 * 4]\n" \ + "stp d6, d7, [%0, #8 * 6]\n" \ + "stp d8, d9, [%0, #8 * 8]\n" \ + "stp d10, d11, [%0, #8 * 10]\n" \ + "stp d12, d13, [%0, #8 * 12]\n" \ + "stp d14, d15, [%0, #8 * 14]\n" \ + "stp d16, d17, [%0, #8 * 16]\n" \ + "stp d18, d19, [%0, #8 * 18]\n" \ + "stp d20, d21, [%0, #8 * 20]\n" \ + "stp d22, d23, [%0, #8 * 22]\n" \ + "stp d24, d25, [%0, #8 * 24]\n" \ + "stp d26, d27, [%0, #8 * 26]\n" \ + "stp d28, d29, [%0, #8 * 28]\n" \ + "stp d30, d31, [%0, #8 * 30]\n" \ + : /* No outputs. */ \ + : "r"(&__e[0]) \ + : "memory"); \ + \ + for (__i = 0; __i < 32; __i++) \ + if (__e[__i] != __val) { \ + __result = __e[__i]; \ + (__bad) = __i; \ + break; \ + } \ + } \ + __result; \ + }) + +#endif /* !_EVL_ARM64_ASM_UAPI_FPTEST_H */ diff --git a/arch/arm64/kernel/Makefile b/arch/arm64/kernel/Makefile index d95b3d6b4..04eeddc90 100644 --- a/arch/arm64/kernel/Makefile +++ b/arch/arm64/kernel/Makefile @@ -58,6 +58,7 @@ obj-$(CONFIG_ACPI_NUMA) += acpi_numa.o obj-$(CONFIG_ARM64_ACPI_PARKING_PROTOCOL) += acpi_parking_protocol.o obj-$(CONFIG_PARAVIRT) += paravirt.o obj-$(CONFIG_RANDOMIZE_BASE) += kaslr.o pi/ +obj-$(CONFIG_IRQ_PIPELINE) += irq_pipeline.o obj-$(CONFIG_HIBERNATION) += hibernate.o hibernate-asm.o obj-$(CONFIG_ELF_CORE) += elfcore.o obj-$(CONFIG_KEXEC_CORE) += machine_kexec.o relocate_kernel.o \ diff --git a/arch/arm64/kernel/asm-offsets.c b/arch/arm64/kernel/asm-offsets.c index 5ff1942b0..a203f3492 100644 --- a/arch/arm64/kernel/asm-offsets.c +++ b/arch/arm64/kernel/asm-offsets.c @@ -32,6 +32,7 @@ int main(void) BLANK(); DEFINE(TSK_TI_CPU, offsetof(struct task_struct, thread_info.cpu)); DEFINE(TSK_TI_FLAGS, offsetof(struct task_struct, thread_info.flags)); + DEFINE(TSK_TI_LOCAL_FLAGS, offsetof(struct task_struct, thread_info.local_flags)); DEFINE(TSK_TI_PREEMPT, offsetof(struct task_struct, thread_info.preempt_count)); #ifdef CONFIG_ARM64_SW_TTBR0_PAN DEFINE(TSK_TI_TTBR0, offsetof(struct task_struct, thread_info.ttbr0)); diff --git a/arch/arm64/kernel/debug-monitors.c b/arch/arm64/kernel/debug-monitors.c index 64f2ecbdf..32271ed24 100644 --- a/arch/arm64/kernel/debug-monitors.c +++ b/arch/arm64/kernel/debug-monitors.c @@ -232,7 +232,7 @@ static void send_user_sigtrap(int si_code) return; if (interrupts_enabled(regs)) - local_irq_enable(); + local_irq_enable_full(); arm64_force_sig_fault(SIGTRAP, si_code, instruction_pointer(regs), "User debug trap"); diff --git a/arch/arm64/kernel/entry-common.c b/arch/arm64/kernel/entry-common.c index 0fc94207e..b35b7e866 100644 --- a/arch/arm64/kernel/entry-common.c +++ b/arch/arm64/kernel/entry-common.c @@ -13,12 +13,12 @@ #include #include #include +#include #include #include #include #include -#include #include #include #include @@ -53,13 +53,61 @@ static __always_inline void __enter_from_kernel_mode(struct pt_regs *regs) trace_hardirqs_off_finish(); } -static void noinstr enter_from_kernel_mode(struct pt_regs *regs) +static void noinstr _enter_from_kernel_mode(struct pt_regs *regs) { __enter_from_kernel_mode(regs); mte_check_tfsr_entry(); mte_disable_tco_entry(current); } +#ifdef CONFIG_IRQ_PIPELINE + +static void noinstr enter_from_kernel_mode(struct pt_regs *regs) +{ + /* + * CAUTION: we may switch in-band as a result of handling a + * trap, so if we are running out-of-band, we must make sure + * not to perform the RCU exit since we did not enter it in + * the first place. + */ + regs->oob_on_entry = running_oob(); + if (regs->oob_on_entry) { + regs->exit_rcu = false; + goto out; + } + + /* + * We trapped from kernel space running in-band, we need to + * record the virtual interrupt state into the current + * register frame (regs->stalled_on_entry) in order to + * reinstate it from exit_to_kernel_mode(). Next we stall the + * in-band stage in order to mirror the current hardware state + * (i.e. hardirqs are off). + */ + regs->stalled_on_entry = test_and_stall_inband_nocheck(); + + __enter_from_kernel_mode(regs); + + /* + * Our caller is going to inherit the hardware interrupt state + * from the trapped context once we have returned: if running + * in-band, align the stall bit on the upcoming state. + */ + if (running_inband() && interrupts_enabled(regs)) + unstall_inband_nocheck(); +out: + mte_check_tfsr_entry(); +} + +#else + +static void noinstr enter_from_kernel_mode(struct pt_regs *regs) +{ + _enter_from_kernel_mode(regs); +} + +#endif /* !CONFIG_IRQ_PIPELINE */ + /* * Handle IRQ/context state management when exiting to kernel mode. * After this function returns it is not safe to call regular kernel code, @@ -91,7 +139,24 @@ static __always_inline void __exit_to_kernel_mode(struct pt_regs *regs) static void noinstr exit_to_kernel_mode(struct pt_regs *regs) { mte_check_tfsr_exit(); + + if (running_oob()) + return; + __exit_to_kernel_mode(regs); + +#ifdef CONFIG_IRQ_PIPELINE + /* + * Reinstate the virtual interrupt state which was in effect + * on entry to the trap. + */ + if (!regs->oob_on_entry) { + if (regs->stalled_on_entry) + stall_inband_nocheck(); + else + unstall_inband_nocheck(); + } +#endif } /* @@ -101,11 +166,16 @@ static void noinstr exit_to_kernel_mode(struct pt_regs *regs) */ static __always_inline void __enter_from_user_mode(void) { - lockdep_hardirqs_off(CALLER_ADDR0); - CT_WARN_ON(ct_state() != CONTEXT_USER); - user_exit_irqoff(); - trace_hardirqs_off_finish(); - mte_disable_tco_entry(current); + if (running_inband()) { + lockdep_hardirqs_off(CALLER_ADDR0); + WARN_ON_ONCE(irq_pipeline_debug() && test_inband_stall()); + CT_WARN_ON(ct_state() != CONTEXT_USER); + stall_inband_nocheck(); + user_exit_irqoff(); + unstall_inband_nocheck(); + trace_hardirqs_off_finish(); + mte_disable_tco_entry(current); + } } static __always_inline void enter_from_user_mode(struct pt_regs *regs) @@ -117,33 +187,52 @@ static __always_inline void enter_from_user_mode(struct pt_regs *regs) * Handle IRQ/context state management when exiting to user mode. * After this function returns it is not safe to call regular kernel code, * instrumentable code, or any code which may trigger an exception. + * + * irq_pipeline: prepare_exit_to_user_mode() tells the caller whether + * it is safe to return via the common in-band exit path, i.e. the + * in-band stage was unstalled on entry, and we are (still) running on + * it. */ static __always_inline void __exit_to_user_mode(void) { + stall_inband_nocheck(); trace_hardirqs_on_prepare(); lockdep_hardirqs_on_prepare(); user_enter_irqoff(); lockdep_hardirqs_on(CALLER_ADDR0); + unstall_inband_nocheck(); } -static __always_inline void exit_to_user_mode_prepare(struct pt_regs *regs) +static __always_inline bool exit_to_user_mode_prepare(struct pt_regs *regs) { unsigned long flags; local_daif_mask(); - flags = read_thread_flags(); - if (unlikely(flags & _TIF_WORK_MASK)) - do_notify_resume(regs, flags); + if (running_inband() && !test_inband_stall()) { + flags = read_thread_flags(); + if (unlikely(flags & _TIF_WORK_MASK)) + do_notify_resume(regs, flags); + + lockdep_sys_exit(); + /* + * Caution: do_notify_resume() might have switched us + * to the out-of-band stage. + */ + return running_inband(); + } - lockdep_sys_exit(); + return false; } static __always_inline void exit_to_user_mode(struct pt_regs *regs) { - exit_to_user_mode_prepare(regs); + bool ret; + + ret = exit_to_user_mode_prepare(regs); mte_check_tfsr_exit(); - __exit_to_user_mode(); + if (ret) + __exit_to_user_mode(); } asmlinkage void noinstr asm_exit_to_user_mode(struct pt_regs *regs) @@ -158,6 +247,7 @@ asmlinkage void noinstr asm_exit_to_user_mode(struct pt_regs *regs) */ static void noinstr arm64_enter_nmi(struct pt_regs *regs) { + /* irq_pipeline: running this code oob is ok. */ regs->lockdep_hardirqs = lockdep_hardirqs_enabled(); __nmi_enter(); @@ -233,6 +323,37 @@ DEFINE_STATIC_KEY_TRUE(sk_dynamic_irqentry_exit_cond_resched); #define need_irq_preemption() (IS_ENABLED(CONFIG_PREEMPTION)) #endif +#ifdef CONFIG_IRQ_PIPELINE + +/* + * When pipelining interrupts, we have to reconcile the hardware and + * the virtual states. Hard irqs are off on entry while the current + * stage has to be unstalled: fix this up by stalling the in-band + * stage on entry, unstalling on exit. + */ +static inline void arm64_preempt_irq_enter(void) +{ + WARN_ON_ONCE(irq_pipeline_debug() && test_inband_stall()); + stall_inband_nocheck(); + trace_hardirqs_off(); +} + +static inline void arm64_preempt_irq_exit(void) +{ + trace_hardirqs_on(); + unstall_inband_nocheck(); +} + +#else /* !CONFIG_IRQ_PIPELINE */ + +static inline void arm64_preempt_irq_enter(void) +{ } + +static inline void arm64_preempt_irq_exit(void) +{ } + +#endif /* !CONFIG_IRQ_PIPELINE */ + static void __sched arm64_preempt_schedule_irq(void) { if (!need_irq_preemption()) @@ -246,6 +367,8 @@ static void __sched arm64_preempt_schedule_irq(void) if (READ_ONCE(current_thread_info()->preempt_count) != 0) return; + arm64_preempt_irq_enter(); + /* * DAIF.DA are cleared at the start of IRQ/FIQ handling, and when GIC * priority masking is used the GIC irqchip driver will clear DAIF.IF @@ -253,7 +376,7 @@ static void __sched arm64_preempt_schedule_irq(void) * DAIF we must have handled an NMI, so skip preemption. */ if (system_uses_irq_prio_masking() && read_sysreg(daif)) - return; + goto out; /* * Preempting a task from an IRQ means we leave copies of PSTATE @@ -265,20 +388,73 @@ static void __sched arm64_preempt_schedule_irq(void) */ if (system_capabilities_finalized()) preempt_schedule_irq(); +out: + arm64_preempt_irq_exit(); } -static void do_interrupt_handler(struct pt_regs *regs, - void (*handler)(struct pt_regs *)) +#ifdef CONFIG_DOVETAIL +/* + * When Dovetail is enabled, the companion core may switch contexts + * over the irq stack, therefore subsequent interrupts might be taken + * over sibling stack contexts. So we need a not so subtle way of + * figuring out whether the irq stack was actually exited, which + * cannot depend on the current task pointer. Instead, we track the + * interrupt nesting depth for a CPU in irq_nesting. + */ +DEFINE_PER_CPU(int, irq_nesting); + +static void __do_interrupt_handler(struct pt_regs *regs, + void (*handler)(struct pt_regs *)) { - struct pt_regs *old_regs = set_irq_regs(regs); + if (this_cpu_inc_return(irq_nesting) == 1) + call_on_irq_stack(regs, handler); + else + handler(regs); + this_cpu_dec(irq_nesting); +} + +#else +static void __do_interrupt_handler(struct pt_regs *regs, + void (*handler)(struct pt_regs *)) +{ if (on_thread_stack()) call_on_irq_stack(regs, handler); else handler(regs); +} +#endif /* !CONFIG_DOVETAIL */ + +#ifdef CONFIG_IRQ_PIPELINE +static bool do_interrupt_handler(struct pt_regs *regs, + void (*handler)(struct pt_regs *)) +{ + struct pt_regs *old_regs = set_irq_regs(regs); /* need this for FIQs */ + + if (handler == handle_arch_irq) + handler = (typeof(handler))(void (*)(void))handle_irq_pipelined; + + __do_interrupt_handler(regs, handler); + + set_irq_regs(old_regs); + + return running_inband() && !irqs_disabled(); +} +#else +static bool do_interrupt_handler(struct pt_regs *regs, + void (*handler)(struct pt_regs *)) +{ + struct pt_regs *old_regs = set_irq_regs(regs); + + irq_enter_rcu(); + __do_interrupt_handler(regs, handler); + irq_exit_rcu(); set_irq_regs(old_regs); + + return true; } +#endif /* !CONFIG_IRQ_PIPELINE */ extern void (*handle_arch_irq)(struct pt_regs *); extern void (*handle_arch_fiq)(struct pt_regs *); @@ -286,6 +462,11 @@ extern void (*handle_arch_fiq)(struct pt_regs *); static void noinstr __panic_unhandled(struct pt_regs *regs, const char *vector, unsigned long esr) { + /* + * Dovetail: Same as __do_kernel_fault(), don't bother + * restoring the in-band stage, this trap is fatal and we are + * already walking on thin ice. + */ arm64_enter_nmi(regs); console_verbose(); @@ -492,19 +673,54 @@ static __always_inline void __el1_pnmi(struct pt_regs *regs, do_interrupt_handler(regs, handler); arm64_exit_nmi(regs); } - static __always_inline void __el1_irq(struct pt_regs *regs, void (*handler)(struct pt_regs *)) { - enter_from_kernel_mode(regs); + bool ret; - irq_enter_rcu(); - do_interrupt_handler(regs, handler); - irq_exit_rcu(); - - arm64_preempt_schedule_irq(); + /* + * IRQ pipeline: the interrupt entry is special in that we may + * run the regular kernel entry prologue/epilogue only if the + * IRQ is going to be dispatched to its handler on behalf of + * the current context, i.e. only if running in-band and + * unstalled. If so, we also have to reconcile the hardware + * and virtual interrupt states temporarily in order to run + * such prologue. + */ +#ifdef CONFIG_IRQ_PIPELINE + if (running_inband()) { + regs->stalled_on_entry = test_inband_stall(); + if (!regs->stalled_on_entry) { + stall_inband_nocheck(); + _enter_from_kernel_mode(regs); + unstall_inband_nocheck(); + } + } +#else + enter_from_kernel_mode(regs); +#endif - exit_to_kernel_mode(regs); + ret = do_interrupt_handler(regs, handler); + if (ret) + arm64_preempt_schedule_irq(); + +#ifdef CONFIG_IRQ_PIPELINE + /* + * UGLY: we also have to tell the tracer that irqs are + * off, since sync_current_irq_stage() did the + * opposite on exit. Hopefully, at some point arm64 + * will convert to the generic entry code which + * exhibits a less convoluted logic. + */ + if (running_inband() && !regs->stalled_on_entry) { + stall_inband_nocheck(); + trace_hardirqs_off(); + exit_to_kernel_mode(regs); + unstall_inband_nocheck(); + } +#else + exit_to_kernel_mode(regs); +#endif } static void noinstr el1_interrupt(struct pt_regs *regs, void (*handler)(struct pt_regs *)) @@ -749,16 +965,16 @@ asmlinkage void noinstr el0t_64_sync_handler(struct pt_regs *regs) static void noinstr el0_interrupt(struct pt_regs *regs, void (*handler)(struct pt_regs *)) { - enter_from_user_mode(regs); + if (handler == handle_arch_fiq || + (running_inband() && !test_inband_stall())) + enter_from_user_mode(regs); write_sysreg(DAIF_PROCCTX_NOIRQ, daif); if (regs->pc & BIT(55)) arm64_apply_bp_hardening(); - irq_enter_rcu(); do_interrupt_handler(regs, handler); - irq_exit_rcu(); exit_to_user_mode(regs); } diff --git a/arch/arm64/kernel/fpsimd.c b/arch/arm64/kernel/fpsimd.c index 0137d9876..6c3074ca3 100644 --- a/arch/arm64/kernel/fpsimd.c +++ b/arch/arm64/kernel/fpsimd.c @@ -221,6 +221,42 @@ static void __get_cpu_fpsimd_context(void) WARN_ON(busy); } +static void __put_cpu_fpsimd_context(void) +{ + bool busy = __this_cpu_xchg(fpsimd_context_busy, false); + + WARN_ON(!busy); /* No matching get_cpu_fpsimd_context()? */ +} + +#ifdef CONFIG_DOVETAIL + +#define get_cpu_fpsimd_context(__flags) \ + do { \ + (__flags) = hard_preempt_disable(); \ + __get_cpu_fpsimd_context(); \ + } while (0) + +#define put_cpu_fpsimd_context(__flags) \ + do { \ + __put_cpu_fpsimd_context(); \ + hard_preempt_enable(__flags); \ + } while (0) + +void fpsimd_restore_current_oob(void) +{ + /* + * Restore the fpsimd context for the current task as it + * resumes from dovetail_context_switch(), which always happen + * on the out-of-band stage. Skip this for kernel threads + * which have no such context but always bear + * TIF_FOREIGN_FPSTATE. + */ + if (current->mm) + fpsimd_restore_current_state(); +} + +#else + /* * Claim ownership of the CPU FPSIMD context for use by the calling context. * @@ -236,21 +272,15 @@ static void __get_cpu_fpsimd_context(void) * half processing is always in thread context on RT kernels so it * implicitly prevents bottom half processing as well. */ -static void get_cpu_fpsimd_context(void) -{ - if (!IS_ENABLED(CONFIG_PREEMPT_RT)) - local_bh_disable(); - else - preempt_disable(); - __get_cpu_fpsimd_context(); -} - -static void __put_cpu_fpsimd_context(void) -{ - bool busy = __this_cpu_xchg(fpsimd_context_busy, false); - - WARN_ON(!busy); /* No matching get_cpu_fpsimd_context()? */ -} +#define get_cpu_fpsimd_context(__flags) \ + do { \ + if (!IS_ENABLED(CONFIG_PREEMPT_RT)) \ + local_bh_disable(); \ + else \ + preempt_disable(); \ + __get_cpu_fpsimd_context(); \ + (void)(__flags); \ + } while (0) /* * Release the CPU FPSIMD context. @@ -259,14 +289,17 @@ static void __put_cpu_fpsimd_context(void) * previously called, with no call to put_cpu_fpsimd_context() in the * meantime. */ -static void put_cpu_fpsimd_context(void) -{ - __put_cpu_fpsimd_context(); - if (!IS_ENABLED(CONFIG_PREEMPT_RT)) - local_bh_enable(); - else - preempt_enable(); -} +#define put_cpu_fpsimd_context(__flags) \ + do { \ + __put_cpu_fpsimd_context(); \ + if (!IS_ENABLED(CONFIG_PREEMPT_RT)) \ + local_bh_enable(); \ + else \ + preempt_enable(); \ + (void)(__flags); \ + } while (0) + +#endif /* !CONFIG_DOVETAIL */ static bool have_cpu_fpsimd_context(void) { @@ -383,7 +416,7 @@ static void task_fpsimd_load(void) bool restore_ffr; WARN_ON(!system_supports_fpsimd()); - WARN_ON(!have_cpu_fpsimd_context()); + WARN_ON(!hard_irqs_disabled() && !have_cpu_fpsimd_context()); if (system_supports_sve() || system_supports_sme()) { switch (current->thread.fp_type) { @@ -457,7 +490,7 @@ static void task_fpsimd_load(void) * than via current, if we are saving KVM state then it will have * ensured that the type of registers to save is set in last->to_save. */ -static void fpsimd_save(void) +static void __fpsimd_save(void) { struct cpu_fp_state const *last = this_cpu_ptr(&fpsimd_last_state); @@ -467,7 +500,7 @@ static void fpsimd_save(void) unsigned int vl; WARN_ON(!system_supports_fpsimd()); - WARN_ON(!have_cpu_fpsimd_context()); + WARN_ON(!hard_irqs_disabled() && !have_cpu_fpsimd_context()); if (test_thread_flag(TIF_FOREIGN_FPSTATE)) return; @@ -524,6 +557,15 @@ static void fpsimd_save(void) } } +void fpsimd_save(void) +{ + unsigned long flags; + + flags = hard_cond_local_irq_save(); + __fpsimd_save(); + hard_cond_local_irq_restore(flags); +} + /* * All vector length selection from userspace comes through here. * We're on a slow path, so some sanity-checks are included. @@ -673,7 +715,7 @@ static void __fpsimd_to_sve(void *sst, struct user_fpsimd_state const *fst, * task->thread.uw.fpsimd_state must be up to date before calling this * function. */ -static void fpsimd_to_sve(struct task_struct *task) +static void _fpsimd_to_sve(struct task_struct *task) { unsigned int vq; void *sst = task->thread.sve_state; @@ -686,6 +728,15 @@ static void fpsimd_to_sve(struct task_struct *task) __fpsimd_to_sve(sst, fst, vq); } +static void fpsimd_to_sve(struct task_struct *task) +{ + unsigned long flags; + + flags = hard_cond_local_irq_save(); + _fpsimd_to_sve(task); + hard_cond_local_irq_restore(flags); +} + /* * Transfer the SVE state in task->thread.sve_state to * task->thread.uw.fpsimd_state. @@ -704,16 +755,21 @@ static void sve_to_fpsimd(struct task_struct *task) struct user_fpsimd_state *fst = &task->thread.uw.fpsimd_state; unsigned int i; __uint128_t const *p; + unsigned long flags; if (!system_supports_sve() && !system_supports_sme()) return; + flags = hard_cond_local_irq_save(); + vl = thread_get_cur_vl(&task->thread); vq = sve_vq_from_vl(vl); for (i = 0; i < SVE_NUM_ZREGS; ++i) { p = (__uint128_t const *)ZREG(sst, vq, i); fst->vregs[i] = arm64_le128_to_cpu(*p); } + + hard_cond_local_irq_restore(flags); } #ifdef CONFIG_ARM64_SVE @@ -849,6 +905,7 @@ int vec_set_vector_length(struct task_struct *task, enum vec_type type, unsigned long vl, unsigned long flags) { bool free_sme = false; + unsigned long irqflags = 0; if (flags & ~(unsigned long)(PR_SVE_VL_INHERIT | PR_SVE_SET_VL_ONEXEC)) @@ -888,9 +945,9 @@ int vec_set_vector_length(struct task_struct *task, enum vec_type type, * regular FPSIMD thread. */ if (task == current) { - get_cpu_fpsimd_context(); + get_cpu_fpsimd_context(irqflags); - fpsimd_save(); + __fpsimd_save(); } fpsimd_flush_task_state(task); @@ -916,7 +973,7 @@ int vec_set_vector_length(struct task_struct *task, enum vec_type type, } if (task == current) - put_cpu_fpsimd_context(); + put_cpu_fpsimd_context(irqflags); task_set_vl(task, type, vl); @@ -1462,19 +1519,23 @@ static void sve_init_regs(void) */ void do_sve_acc(unsigned long esr, struct pt_regs *regs) { + unsigned long flags; + + mark_trap_entry(ARM64_TRAP_SVE, regs); + /* Even if we chose not to use SVE, the hardware could still trap: */ if (unlikely(!system_supports_sve()) || WARN_ON(is_compat_task())) { force_signal_inject(SIGILL, ILL_ILLOPC, regs->pc, 0); - return; + goto out; } sve_alloc(current, true); if (!current->thread.sve_state) { force_sig(SIGKILL); - return; + goto out; } - get_cpu_fpsimd_context(); + get_cpu_fpsimd_context(flags); if (test_and_set_thread_flag(TIF_SVE)) WARN_ON(1); /* SVE access shouldn't have trapped */ @@ -1488,7 +1549,9 @@ void do_sve_acc(unsigned long esr, struct pt_regs *regs) */ sve_init_regs(); - put_cpu_fpsimd_context(); + put_cpu_fpsimd_context(flags); +out: + mark_trap_exit(ARM64_TRAP_SVE, regs); } /* @@ -1504,10 +1567,14 @@ void do_sve_acc(unsigned long esr, struct pt_regs *regs) */ void do_sme_acc(unsigned long esr, struct pt_regs *regs) { + unsigned long flags; + + oob_trap_notify(ARM64_TRAP_SME, regs); + /* Even if we chose not to use SME, the hardware could still trap: */ if (unlikely(!system_supports_sme()) || WARN_ON(is_compat_task())) { force_signal_inject(SIGILL, ILL_ILLOPC, regs->pc, 0); - return; + goto out; } /* @@ -1516,17 +1583,17 @@ void do_sme_acc(unsigned long esr, struct pt_regs *regs) */ if (ESR_ELx_ISS(esr) != ESR_ELx_SME_ISS_SME_DISABLED) { force_signal_inject(SIGILL, ILL_ILLOPC, regs->pc, 0); - return; + goto out; } sve_alloc(current, false); sme_alloc(current, true); if (!current->thread.sve_state || !current->thread.sme_state) { force_sig(SIGKILL); - return; + goto out; } - get_cpu_fpsimd_context(); + get_cpu_fpsimd_context(flags); /* With TIF_SME userspace shouldn't generate any traps */ if (test_and_set_thread_flag(TIF_SME)) @@ -1540,7 +1607,9 @@ void do_sme_acc(unsigned long esr, struct pt_regs *regs) fpsimd_bind_task_to_cpu(); } - put_cpu_fpsimd_context(); + put_cpu_fpsimd_context(flags); +out: + oob_trap_unwind(ARM64_TRAP_SME, regs); } /* @@ -1559,6 +1628,9 @@ void do_fpsimd_exc(unsigned long esr, struct pt_regs *regs) { unsigned int si_code = FPE_FLTUNK; + if (!mark_cond_trap_entry(ARM64_TRAP_FPE, regs)) + return; + if (esr & ESR_ELx_FP_EXC_TFV) { if (esr & FPEXC_IOF) si_code = FPE_FLTINV; @@ -1575,19 +1647,24 @@ void do_fpsimd_exc(unsigned long esr, struct pt_regs *regs) send_sig_fault(SIGFPE, si_code, (void __user *)instruction_pointer(regs), current); + + mark_trap_exit(ARM64_TRAP_FPE, regs); } void fpsimd_thread_switch(struct task_struct *next) { bool wrong_task, wrong_cpu; + unsigned long flags; if (!system_supports_fpsimd()) return; + flags = hard_cond_local_irq_save(); + __get_cpu_fpsimd_context(); /* Save unsaved fpsimd state, if any: */ - fpsimd_save(); + __fpsimd_save(); /* * Fix up TIF_FOREIGN_FPSTATE to correctly describe next's @@ -1602,6 +1679,8 @@ void fpsimd_thread_switch(struct task_struct *next) wrong_task || wrong_cpu); __put_cpu_fpsimd_context(); + + hard_cond_local_irq_restore(flags); } static void fpsimd_flush_thread_vl(enum vec_type type) @@ -1643,11 +1722,12 @@ void fpsimd_flush_thread(void) { void *sve_state = NULL; void *sme_state = NULL; + unsigned long flags; if (!system_supports_fpsimd()) return; - get_cpu_fpsimd_context(); + get_cpu_fpsimd_context(flags); fpsimd_flush_task_state(current); memset(¤t->thread.uw.fpsimd_state, 0, @@ -1676,7 +1756,7 @@ void fpsimd_flush_thread(void) current->thread.fp_type = FP_STATE_FPSIMD; - put_cpu_fpsimd_context(); + put_cpu_fpsimd_context(flags); kfree(sve_state); kfree(sme_state); } @@ -1687,12 +1767,14 @@ void fpsimd_flush_thread(void) */ void fpsimd_preserve_current_state(void) { + unsigned long flags; + if (!system_supports_fpsimd()) return; - get_cpu_fpsimd_context(); - fpsimd_save(); - put_cpu_fpsimd_context(); + get_cpu_fpsimd_context(flags); + __fpsimd_save(); + put_cpu_fpsimd_context(flags); } /* @@ -1712,6 +1794,8 @@ void fpsimd_signal_preserve_current_state(void) */ void fpsimd_kvm_prepare(void) { + unsigned long flags; + if (!system_supports_sve()) return; @@ -1722,14 +1806,14 @@ void fpsimd_kvm_prepare(void) * SVE enabled for performance reasons then update the task * state to be FPSIMD only. */ - get_cpu_fpsimd_context(); + get_cpu_fpsimd_context(flags); if (test_and_clear_thread_flag(TIF_SVE)) { sve_to_fpsimd(current); current->thread.fp_type = FP_STATE_FPSIMD; } - put_cpu_fpsimd_context(); + put_cpu_fpsimd_context(flags); } /* @@ -1774,11 +1858,14 @@ static void fpsimd_bind_task_to_cpu(void) void fpsimd_bind_state_to_cpu(struct cpu_fp_state *state) { struct cpu_fp_state *last = this_cpu_ptr(&fpsimd_last_state); + unsigned long flags; WARN_ON(!system_supports_fpsimd()); WARN_ON(!in_softirq() && !irqs_disabled()); + flags = hard_cond_local_irq_save(); *last = *state; + hard_cond_local_irq_restore(flags); } /* @@ -1789,6 +1876,8 @@ void fpsimd_bind_state_to_cpu(struct cpu_fp_state *state) */ void fpsimd_restore_current_state(void) { + unsigned long flags; + /* * For the tasks that were created before we detected the absence of * FP/SIMD, the TIF_FOREIGN_FPSTATE could be set via fpsimd_thread_switch(), @@ -1803,14 +1892,14 @@ void fpsimd_restore_current_state(void) return; } - get_cpu_fpsimd_context(); + get_cpu_fpsimd_context(flags); if (test_and_clear_thread_flag(TIF_FOREIGN_FPSTATE)) { task_fpsimd_load(); fpsimd_bind_task_to_cpu(); } - put_cpu_fpsimd_context(); + put_cpu_fpsimd_context(flags); } /* @@ -1822,21 +1911,23 @@ void fpsimd_restore_current_state(void) */ void fpsimd_update_current_state(struct user_fpsimd_state const *state) { + unsigned long flags; + if (WARN_ON(!system_supports_fpsimd())) return; - get_cpu_fpsimd_context(); + get_cpu_fpsimd_context(flags); current->thread.uw.fpsimd_state = *state; if (test_thread_flag(TIF_SVE)) - fpsimd_to_sve(current); + _fpsimd_to_sve(current); task_fpsimd_load(); fpsimd_bind_task_to_cpu(); clear_thread_flag(TIF_FOREIGN_FPSTATE); - put_cpu_fpsimd_context(); + put_cpu_fpsimd_context(flags); } /* @@ -1895,9 +1986,9 @@ void fpsimd_save_and_flush_cpu_state(void) { if (!system_supports_fpsimd()) return; - WARN_ON(preemptible()); + WARN_ON(!hard_irqs_disabled() && preemptible()); __get_cpu_fpsimd_context(); - fpsimd_save(); + __fpsimd_save(); fpsimd_flush_cpu_state(); __put_cpu_fpsimd_context(); } @@ -1923,18 +2014,23 @@ void fpsimd_save_and_flush_cpu_state(void) */ void kernel_neon_begin(void) { + unsigned long flags; + if (WARN_ON(!system_supports_fpsimd())) return; BUG_ON(!may_use_simd()); - get_cpu_fpsimd_context(); + get_cpu_fpsimd_context(flags); /* Save unsaved fpsimd state, if any: */ - fpsimd_save(); + __fpsimd_save(); /* Invalidate any task state remaining in the fpsimd regs: */ fpsimd_flush_cpu_state(); + + if (dovetailing()) + hard_cond_local_irq_restore(flags); } EXPORT_SYMBOL_GPL(kernel_neon_begin); @@ -1949,10 +2045,12 @@ EXPORT_SYMBOL_GPL(kernel_neon_begin); */ void kernel_neon_end(void) { + unsigned long flags = hard_local_save_flags(); + if (!system_supports_fpsimd()) return; - put_cpu_fpsimd_context(); + put_cpu_fpsimd_context(flags); } EXPORT_SYMBOL_GPL(kernel_neon_end); @@ -2086,9 +2184,13 @@ void __efi_fpsimd_end(void) static int fpsimd_cpu_pm_notifier(struct notifier_block *self, unsigned long cmd, void *v) { + unsigned long flags; + switch (cmd) { case CPU_PM_ENTER: + flags = hard_cond_local_irq_save(); fpsimd_save_and_flush_cpu_state(); + hard_cond_local_irq_restore(flags); break; case CPU_PM_EXIT: break; diff --git a/arch/arm64/kernel/irq.c b/arch/arm64/kernel/irq.c index 85087e2df..ac77081fb 100644 --- a/arch/arm64/kernel/irq.c +++ b/arch/arm64/kernel/irq.c @@ -11,6 +11,7 @@ */ #include +#include #include #include #include @@ -32,7 +33,6 @@ DEFINE_PER_CPU(struct nmi_ctx, nmi_contexts); DEFINE_PER_CPU(unsigned long *, irq_stack_ptr); - DECLARE_PER_CPU(unsigned long *, irq_shadow_call_stack_ptr); #ifdef CONFIG_SHADOW_CALL_STACK @@ -75,7 +75,7 @@ static void init_irq_stacks(void) } #endif -#ifndef CONFIG_PREEMPT_RT +#ifdef CONFIG_SOFTIRQ_ON_OWN_STACK static void ____do_softirq(struct pt_regs *regs) { __do_softirq(); diff --git a/arch/arm64/kernel/irq_pipeline.c b/arch/arm64/kernel/irq_pipeline.c new file mode 100644 index 000000000..74c4746fb --- /dev/null +++ b/arch/arm64/kernel/irq_pipeline.c @@ -0,0 +1,24 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2018 Philippe Gerum . + */ +#include +#include + +void arch_do_IRQ_pipelined(struct irq_desc *desc) +{ + struct pt_regs *regs = raw_cpu_ptr(&irq_pipeline.tick_regs); + struct pt_regs *old_regs = set_irq_regs(regs); + + irq_enter(); + handle_irq_desc(desc); + irq_exit(); + + set_irq_regs(old_regs); +} + +void __init arch_irq_pipeline_init(void) +{ + /* no per-arch init. */ +} diff --git a/arch/arm64/kernel/process.c b/arch/arm64/kernel/process.c index 37a70d59e..32a8c244b 100644 --- a/arch/arm64/kernel/process.c +++ b/arch/arm64/kernel/process.c @@ -491,6 +491,10 @@ static void erratum_1418040_thread_switch(struct task_struct *next) static void erratum_1418040_new_exec(void) { + /* + * Dovetail: we do not compete with oob on updating this + * register, so inband disable is enough. + */ preempt_disable(); erratum_1418040_thread_switch(current); preempt_enable(); diff --git a/arch/arm64/kernel/signal.c b/arch/arm64/kernel/signal.c index 425b1bc17..6dacaeb84 100644 --- a/arch/arm64/kernel/signal.c +++ b/arch/arm64/kernel/signal.c @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -1278,15 +1279,33 @@ static void do_signal(struct pt_regs *regs) restore_saved_sigmask(); } +static inline void do_retuser(void) +{ + unsigned long thread_flags; + + if (dovetailing()) { + thread_flags = current_thread_info()->flags; + if (thread_flags & _TIF_RETUSER) + inband_retuser_notify(); + } +} + void do_notify_resume(struct pt_regs *regs, unsigned long thread_flags) { + WARN_ON_ONCE(irq_pipeline_debug() && running_oob()); + WARN_ON_ONCE(irq_pipeline_debug() && test_inband_stall()); + do { + stall_inband_nocheck(); + if (thread_flags & _TIF_NEED_RESCHED) { /* Unmask Debug and SError for the next task */ - local_daif_restore(DAIF_PROCCTX_NOIRQ); + local_daif_restore(irqs_pipelined() ? DAIF_PROCCTX : + DAIF_PROCCTX_NOIRQ); schedule(); } else { + unstall_inband_nocheck(); local_daif_restore(DAIF_PROCCTX); if (thread_flags & _TIF_UPROBE) @@ -1306,11 +1325,34 @@ void do_notify_resume(struct pt_regs *regs, unsigned long thread_flags) if (thread_flags & _TIF_FOREIGN_FPSTATE) fpsimd_restore_current_state(); + + do_retuser(); + /* RETUSER might have switched oob */ + if (running_oob()) { + local_daif_mask(); + return; + } } + /* + * Dovetail: we may have restored the fpsimd state for + * current with no other opportunity to check for + * _TIF_FOREIGN_FPSTATE until we are back running on + * el0, so we must not take any interrupt until then, + * otherwise we may end up resuming with some OOB + * thread's fpsimd state. + */ local_daif_mask(); thread_flags = read_thread_flags(); } while (thread_flags & _TIF_WORK_MASK); + + /* + * irq_pipeline: trace_hardirqs_off was in effect on entry, we + * leave it this way by virtue of calling local_daif_mask() + * before exiting the loop. However, we did enter unstalled + * and we must restore such state on exit. + */ + unstall_inband_nocheck(); } unsigned long __ro_after_init signal_minsigstksz; diff --git a/arch/arm64/kernel/smp.c b/arch/arm64/kernel/smp.c index 14365ef84..19a367c0b 100644 --- a/arch/arm64/kernel/smp.c +++ b/arch/arm64/kernel/smp.c @@ -76,7 +76,7 @@ enum ipi_msg_type { NR_IPI }; -static int ipi_irq_base __read_mostly; +int ipi_irq_base __read_mostly; static int nr_ipi __read_mostly = NR_IPI; static struct irq_desc *ipi_desc[NR_IPI] __read_mostly; @@ -257,6 +257,7 @@ asmlinkage notrace void secondary_start_kernel(void) complete(&cpu_running); local_daif_restore(DAIF_PROCCTX); + local_irq_enable_full(); /* * OK, it's off to the idle thread for us @@ -771,6 +772,8 @@ static const char *ipi_types[NR_IPI] __tracepoint_string = { static void smp_cross_call(const struct cpumask *target, unsigned int ipinr); +static unsigned int get_ipi_count(struct irq_desc *desc, unsigned int cpu); + unsigned long irq_err_count; int arch_show_interrupts(struct seq_file *p, int prec) @@ -781,7 +784,7 @@ int arch_show_interrupts(struct seq_file *p, int prec) seq_printf(p, "%*s%u:%s", prec - 1, "IPI", i, prec >= 4 ? " " : ""); for_each_online_cpu(cpu) - seq_printf(p, "%10u ", irq_desc_kstat_cpu(ipi_desc[i], cpu)); + seq_printf(p, "%10u ", get_ipi_count(ipi_desc[i], cpu)); seq_printf(p, " %s\n", ipi_types[i]); } @@ -843,7 +846,7 @@ static void __noreturn ipi_cpu_crash_stop(unsigned int cpu, struct pt_regs *regs atomic_dec(&waiting_for_crash_ipi); - local_irq_disable(); + local_irq_disable_full(); sdei_mask_local_cpu(); if (IS_ENABLED(CONFIG_HOTPLUG_CPU)) @@ -857,7 +860,7 @@ static void __noreturn ipi_cpu_crash_stop(unsigned int cpu, struct pt_regs *regs } /* - * Main handler for inter-processor interrupts + * Main handler for inter-processor interrupts on the in-band stage. */ static void do_handle_IPI(int ipinr) { @@ -916,6 +919,74 @@ static void do_handle_IPI(int ipinr) trace_ipi_exit(ipi_types[ipinr]); } +static void __smp_cross_call(const struct cpumask *target, unsigned int ipinr) +{ + trace_ipi_raise(target, ipi_types[ipinr]); + __ipi_send_mask(ipi_desc[ipinr], target); +} + +#ifdef CONFIG_IRQ_PIPELINE + +static DEFINE_PER_CPU(unsigned long, ipi_messages); + +static DEFINE_PER_CPU(unsigned int [NR_IPI], ipi_counts); + +static irqreturn_t ipi_handler(int irq, void *data) +{ + unsigned long *pmsg; + unsigned int ipinr; + + /* + * Decode in-band IPIs (0..NR_IPI - 1) multiplexed over + * SGI0. Out-of-band IPIs (SGI1, SGI2) have their own + * individual handler. + */ + pmsg = raw_cpu_ptr(&ipi_messages); + while (*pmsg) { + ipinr = ffs(*pmsg) - 1; + clear_bit(ipinr, pmsg); + __this_cpu_inc(ipi_counts[ipinr]); + do_handle_IPI(ipinr); + } + + return IRQ_HANDLED; +} + +static void smp_cross_call(const struct cpumask *target, unsigned int ipinr) +{ + unsigned int cpu; + + /* regular in-band IPI (multiplexed over SGI0). */ + for_each_cpu(cpu, target) + set_bit(ipinr, &per_cpu(ipi_messages, cpu)); + + wmb(); + __smp_cross_call(target, 0); +} + +static unsigned int get_ipi_count(struct irq_desc *desc, unsigned int cpu) +{ + unsigned int irq = irq_desc_get_irq(desc); + return per_cpu(ipi_counts[irq - ipi_irq_base], cpu); +} + +void irq_send_oob_ipi(unsigned int irq, + const struct cpumask *cpumask) +{ + unsigned int sgi = irq - ipi_irq_base; + + if (WARN_ON(irq_pipeline_debug() && + (sgi < OOB_IPI_OFFSET || + sgi >= OOB_IPI_OFFSET + OOB_NR_IPI))) + return; + + /* Out-of-band IPI (SGI1-2). */ + __smp_cross_call(cpumask, sgi); +} +EXPORT_SYMBOL_GPL(irq_send_oob_ipi); + +#else + static irqreturn_t ipi_handler(int irq, void *data) { do_handle_IPI(irq - ipi_irq_base); @@ -924,10 +995,16 @@ static irqreturn_t ipi_handler(int irq, void *data) static void smp_cross_call(const struct cpumask *target, unsigned int ipinr) { - trace_ipi_raise(target, ipi_types[ipinr]); - __ipi_send_mask(ipi_desc[ipinr], target); + __smp_cross_call(target, ipinr); +} + +static unsigned int get_ipi_count(struct irq_desc *desc, unsigned int cpu) +{ + return irq_desc_kstat_cpu(desc, cpu); } +#endif /* CONFIG_IRQ_PIPELINE */ + static void ipi_setup(int cpu) { int i; @@ -954,18 +1031,25 @@ static void ipi_teardown(int cpu) void __init set_smp_ipi_range(int ipi_base, int n) { - int i; + int i, inband_nr_ipi; WARN_ON(n < NR_IPI); nr_ipi = min(n, NR_IPI); + /* + * irq_pipeline: the in-band stage traps SGI0 only, + * over which IPI messages are mutiplexed. Other SGIs + * are available for delivering out-of-band IPIs. + */ + inband_nr_ipi = irqs_pipelined() ? 1 : nr_ipi; for (i = 0; i < nr_ipi; i++) { - int err; - - err = request_percpu_irq(ipi_base + i, ipi_handler, - "IPI", &cpu_number); - WARN_ON(err); + if (i < inband_nr_ipi) { + int err; + err = request_percpu_irq(ipi_base + i, ipi_handler, + "IPI", &cpu_number); + WARN_ON(err); + } ipi_desc[i] = irq_to_desc(ipi_base + i); irq_set_status_flags(ipi_base + i, IRQ_HIDDEN); } diff --git a/arch/arm64/kernel/syscall.c b/arch/arm64/kernel/syscall.c index f090e39f6..332ec9faf 100644 --- a/arch/arm64/kernel/syscall.c +++ b/arch/arm64/kernel/syscall.c @@ -2,6 +2,7 @@ #include #include +#include #include #include #include @@ -76,6 +77,7 @@ static void el0_svc_common(struct pt_regs *regs, int scno, int sc_nr, const syscall_fn_t syscall_table[]) { unsigned long flags = read_thread_flags(); + int ret; regs->orig_x0 = regs->regs[0]; regs->syscallno = scno; @@ -98,6 +100,18 @@ static void el0_svc_common(struct pt_regs *regs, int scno, int sc_nr, * (Similarly for HVC and SMC elsewhere.) */ + if (dovetail_debug()) { + WARN_ON_ONCE(hard_irqs_disabled()); + WARN_ON_ONCE(running_inband() && test_inband_stall()); + } + + ret = pipeline_syscall(scno, regs); + if (ret > 0) + return; + + if (ret < 0) + goto tail_work; + if (flags & _TIF_MTE_ASYNC_FAULT) { /* * Process the asynchronous tag check fault before the actual @@ -138,6 +152,7 @@ static void el0_svc_common(struct pt_regs *regs, int scno, int sc_nr, * check again. However, if we were tracing entry, then we always trace * exit regardless, as the old entry assembly did. */ +tail_work: if (!has_syscall_work(flags) && !IS_ENABLED(CONFIG_DEBUG_RSEQ)) { flags = read_thread_flags(); if (!has_syscall_work(flags) && !(flags & _TIF_SINGLESTEP)) diff --git a/arch/arm64/kernel/traps.c b/arch/arm64/kernel/traps.c index 8b70759cd..0811aa219 100644 --- a/arch/arm64/kernel/traps.c +++ b/arch/arm64/kernel/traps.c @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -203,7 +204,7 @@ static int __die(const char *str, long err, struct pt_regs *regs) return ret; } -static DEFINE_RAW_SPINLOCK(die_lock); +static DEFINE_HARD_SPINLOCK(die_lock); /* * This function is protected against re-entrancy. @@ -455,21 +456,33 @@ void do_el0_undef(struct pt_regs *regs, unsigned long esr) { u32 insn; + mark_trap_entry(ARM64_TRAP_UNDI, regs); + + /* + * If the companion core did not switched us to in-band + * context, we may assume that it has handled the trap. + */ + if (running_oob()) + goto out_exit; + /* check for AArch32 breakpoint instructions */ if (!aarch32_break_handler(regs)) - return; + goto out_exit; if (user_insn_read(regs, &insn)) goto out_err; if (try_emulate_mrs(regs, insn)) - return; + goto out_exit; if (try_emulate_armv8_deprecated(regs, insn)) - return; + goto out_exit; out_err: force_signal_inject(SIGILL, ILL_ILLOPC, regs->pc, 0); + +out_exit: + mark_trap_exit(ARM64_TRAP_UNDI, regs); } void do_el1_undef(struct pt_regs *regs, unsigned long esr) @@ -488,7 +501,9 @@ void do_el1_undef(struct pt_regs *regs, unsigned long esr) void do_el0_bti(struct pt_regs *regs) { + mark_trap_entry(ARM64_TRAP_BTI, regs); force_signal_inject(SIGILL, ILL_ILLOPC, regs->pc, 0); + mark_trap_exit(ARM64_TRAP_BTI, regs); } void do_el1_bti(struct pt_regs *regs, unsigned long esr) @@ -620,10 +635,13 @@ static void user_cache_maint_handler(unsigned long esr, struct pt_regs *regs) return; } - if (ret) + if (ret) { + mark_trap_entry(ARM64_TRAP_ACCESS, regs); arm64_notify_segfault(tagged_address); - else + mark_trap_exit(ARM64_TRAP_ACCESS, regs); + } else { arm64_skip_faulting_instruction(regs, AARCH64_INSN_SIZE); + } } static void ctr_read_handler(unsigned long esr, struct pt_regs *regs) @@ -668,8 +686,11 @@ static void mrs_handler(unsigned long esr, struct pt_regs *regs) rt = ESR_ELx_SYS64_ISS_RT(esr); sysreg = esr_sys64_to_sysreg(esr); - if (do_emulate_mrs(regs, sysreg, rt) != 0) + if (do_emulate_mrs(regs, sysreg, rt) != 0) { + mark_trap_entry(ARM64_TRAP_ACCESS, regs); force_signal_inject(SIGILL, ILL_ILLOPC, regs->pc, 0); + mark_trap_exit(ARM64_TRAP_ACCESS, regs); + } } static void wfi_handler(unsigned long esr, struct pt_regs *regs) @@ -909,11 +930,13 @@ void bad_el0_sync(struct pt_regs *regs, int reason, unsigned long esr) { unsigned long pc = instruction_pointer(regs); + mark_trap_entry(ARM64_TRAP_ACCESS, regs); current->thread.fault_address = 0; current->thread.fault_code = esr; arm64_force_sig_fault(SIGILL, ILL_ILLOPC, pc, "Bad EL0 synchronous exception"); + mark_trap_exit(ARM64_TRAP_ACCESS, regs); } #ifdef CONFIG_VMAP_STACK diff --git a/arch/arm64/kernel/vdso.c b/arch/arm64/kernel/vdso.c index d9e135573..e9ea3fef8 100644 --- a/arch/arm64/kernel/vdso.c +++ b/arch/arm64/kernel/vdso.c @@ -40,6 +40,8 @@ enum vvar_pages { VVAR_NR_PAGES, }; +#define VPRIV_NR_PAGES __VPRIV_PAGES + struct vdso_abi_info { const char *name; const char *vdso_code_start; @@ -112,6 +114,9 @@ static int __init __vdso_init(enum vdso_abi abi) vdso_pagelist[i] = pfn_to_page(pfn + i); vdso_info[abi].cm->pages = vdso_pagelist; +#ifdef CONFIG_GENERIC_CLOCKSOURCE_VDSO + vdso_data->cs_type_seq = CLOCKSOURCE_VDSO_NONE << 16 | 1; +#endif return 0; } @@ -198,7 +203,8 @@ static int __setup_additional_pages(enum vdso_abi abi, vdso_text_len = vdso_info[abi].vdso_pages << PAGE_SHIFT; /* Be sure to map the data page */ - vdso_mapping_len = vdso_text_len + VVAR_NR_PAGES * PAGE_SIZE; + vdso_mapping_len = vdso_text_len + VVAR_NR_PAGES * PAGE_SIZE + + VPRIV_NR_PAGES * PAGE_SIZE; vdso_base = get_unmapped_area(NULL, 0, vdso_mapping_len, 0, 0); if (IS_ERR_VALUE(vdso_base)) { @@ -206,6 +212,26 @@ static int __setup_additional_pages(enum vdso_abi abi, goto up_fail; } + /* + * Install the vDSO mappings we need: + * + * +----------------+ + * | vpriv | PAGE_SIZE (private anon page if GENERIC_CLOCKSOURCE_VDSO) + * |----------------| + * | vvar | PAGE_SIZE (shared) + * |----------------| + * | text | text_pages * PAGE_SIZE (shared) + * | ... | + * +----------------+ + */ + if (VPRIV_NR_PAGES > 0 && mmap_region(NULL, vdso_base, PAGE_SIZE, + VM_READ | VM_WRITE | VM_MAYREAD | VM_MAYWRITE, + 0, NULL) != vdso_base) { + ret = ERR_PTR(-EINVAL); + goto up_fail; + } + + vdso_base += VPRIV_NR_PAGES * PAGE_SIZE; /* Skip private area. */ ret = _install_special_mapping(mm, vdso_base, VVAR_NR_PAGES * PAGE_SIZE, VM_READ|VM_MAYREAD|VM_PFNMAP, vdso_info[abi].dm); diff --git a/arch/arm64/kernel/vdso/vdso.lds.S b/arch/arm64/kernel/vdso/vdso.lds.S index 45354f2dd..7e76b6780 100644 --- a/arch/arm64/kernel/vdso/vdso.lds.S +++ b/arch/arm64/kernel/vdso/vdso.lds.S @@ -21,6 +21,9 @@ SECTIONS PROVIDE(_vdso_data = . - __VVAR_PAGES * PAGE_SIZE); #ifdef CONFIG_TIME_NS PROVIDE(_timens_data = _vdso_data + PAGE_SIZE); +#endif +#ifdef CONFIG_GENERIC_CLOCKSOURCE_VDSO + PROVIDE(_vdso_priv = _vdso_data - __VPRIV_PAGES * PAGE_SIZE); #endif . = VDSO_LBASE + SIZEOF_HEADERS; diff --git a/arch/arm64/kernel/vdso32/vdso.lds.S b/arch/arm64/kernel/vdso32/vdso.lds.S index 8d95d7d35..529cd8167 100644 --- a/arch/arm64/kernel/vdso32/vdso.lds.S +++ b/arch/arm64/kernel/vdso32/vdso.lds.S @@ -21,6 +21,9 @@ SECTIONS PROVIDE_HIDDEN(_vdso_data = . - __VVAR_PAGES * PAGE_SIZE); #ifdef CONFIG_TIME_NS PROVIDE_HIDDEN(_timens_data = _vdso_data + PAGE_SIZE); +#endif +#ifdef CONFIG_GENERIC_CLOCKSOURCE_VDSO + PROVIDE_HIDDEN(_vdso_priv = _vdso_data - __VPRIV_PAGES * PAGE_SIZE); #endif . = VDSO_LBASE + SIZEOF_HEADERS; diff --git a/arch/arm64/mm/context.c b/arch/arm64/mm/context.c index b2ac06246..5fd97df8b 100644 --- a/arch/arm64/mm/context.c +++ b/arch/arm64/mm/context.c @@ -18,7 +18,7 @@ #include static u32 asid_bits; -static DEFINE_RAW_SPINLOCK(cpu_asid_lock); +static DEFINE_HARD_SPINLOCK(cpu_asid_lock); static atomic64_t asid_generation; static unsigned long *asid_map; @@ -217,6 +217,9 @@ void check_and_switch_context(struct mm_struct *mm) unsigned long flags; unsigned int cpu; u64 asid, old_active_asid; + bool need_flush; + + WARN_ON_ONCE(dovetail_debug() && !hard_irqs_disabled()); if (system_supports_cnp()) cpu_set_reserved_ttbr0(); @@ -252,12 +255,14 @@ void check_and_switch_context(struct mm_struct *mm) } cpu = smp_processor_id(); - if (cpumask_test_and_clear_cpu(cpu, &tlb_flush_pending)) - local_flush_tlb_all(); + need_flush = cpumask_test_and_clear_cpu(cpu, &tlb_flush_pending); atomic64_set(this_cpu_ptr(&active_asids), asid); raw_spin_unlock_irqrestore(&cpu_asid_lock, flags); + if (need_flush) + local_flush_tlb_all(); + switch_mm_fastpath: arm64_apply_bp_hardening(); diff --git a/arch/arm64/mm/fault.c b/arch/arm64/mm/fault.c index 2e5d1e238..4ef52458d 100644 --- a/arch/arm64/mm/fault.c +++ b/arch/arm64/mm/fault.c @@ -283,11 +283,11 @@ static bool __kprobes is_spurious_el1_translation_fault(unsigned long addr, (esr & ESR_ELx_FSC_TYPE) != ESR_ELx_FSC_FAULT) return false; - local_irq_save(flags); + flags = hard_local_irq_save(); asm volatile("at s1e1r, %0" :: "r" (addr)); isb(); par = read_sysreg_par(); - local_irq_restore(flags); + hard_local_irq_restore(flags); /* * If we now have a valid translation, treat the translation fault as @@ -415,6 +415,12 @@ static void __do_kernel_fault(unsigned long addr, unsigned long esr, if (efi_runtime_fixup_exception(regs, msg)) return; + /* + * Dovetail: Don't bother restoring the in-band stage in the + * non-recoverable fault case, we got busted and a full stage + * switch is likely to make things even worse. Try at least to + * get some debug output before panicking. + */ die_kernel_fault(msg, addr, esr, regs); } @@ -487,8 +493,10 @@ static void do_bad_area(unsigned long far, unsigned long esr, if (user_mode(regs)) { const struct fault_info *inf = esr_to_fault_info(esr); + mark_trap_entry(ARM64_TRAP_ACCESS, regs); set_thread_esr(addr, esr); arm64_force_sig_fault(inf->sig, inf->code, far, inf->name); + mark_trap_exit(ARM64_TRAP_ACCESS, regs); } else { __do_kernel_fault(addr, esr, regs); } @@ -541,6 +549,8 @@ static int __kprobes do_page_fault(unsigned long far, unsigned long esr, if (kprobe_page_fault(regs, esr)) return 0; + mark_trap_entry(ARM64_TRAP_ACCESS, regs); + /* * If we're in an interrupt or have no user context, we must not take * the fault. @@ -629,7 +639,7 @@ static int __kprobes do_page_fault(unsigned long far, unsigned long esr, if (fault_signal_pending(fault, regs)) { if (!user_mode(regs)) goto no_context; - return 0; + goto out; } /* The fault is fully completed (including releasing mmap lock) */ @@ -648,7 +658,7 @@ static int __kprobes do_page_fault(unsigned long far, unsigned long esr, */ if (likely(!(fault & (VM_FAULT_ERROR | VM_FAULT_BADMAP | VM_FAULT_BADACCESS)))) - return 0; + goto out; /* * If we are in kernel mode at this point, we have no context to @@ -664,7 +674,7 @@ static int __kprobes do_page_fault(unsigned long far, unsigned long esr, * oom-killed). */ pagefault_out_of_memory(); - return 0; + goto out; } inf = esr_to_fault_info(esr); @@ -693,10 +703,12 @@ static int __kprobes do_page_fault(unsigned long far, unsigned long esr, far, inf->name); } - return 0; + goto out; no_context: __do_kernel_fault(addr, esr, regs); +out: + mark_trap_exit(ARM64_TRAP_ACCESS, regs); return 0; } @@ -733,6 +745,8 @@ static int do_sea(unsigned long far, unsigned long esr, struct pt_regs *regs) const struct fault_info *inf; unsigned long siaddr; + mark_trap_entry(ARM64_TRAP_SEA, regs); + inf = esr_to_fault_info(esr); if (user_mode(regs) && apei_claim_sea(regs) == 0) { @@ -740,7 +754,7 @@ static int do_sea(unsigned long far, unsigned long esr, struct pt_regs *regs) * APEI claimed this as a firmware-first notification. * Some processing deferred to task_work before ret_to_user(). */ - return 0; + goto out; } if (esr & ESR_ELx_FnV) { @@ -754,6 +768,8 @@ static int do_sea(unsigned long far, unsigned long esr, struct pt_regs *regs) siaddr = untagged_addr(far); } arm64_notify_die(inf->name, regs, inf->sig, inf->code, siaddr, esr); +out: + mark_trap_exit(ARM64_TRAP_SEA, regs); return 0; } @@ -846,6 +862,8 @@ void do_mem_abort(unsigned long far, unsigned long esr, struct pt_regs *regs) if (!inf->fn(far, esr, regs)) return; + mark_trap_entry(ARM64_TRAP_ACCESS, regs); + if (!user_mode(regs)) die_kernel_fault(inf->name, addr, esr, regs); @@ -855,13 +873,19 @@ void do_mem_abort(unsigned long far, unsigned long esr, struct pt_regs *regs) * address to the signal handler. */ arm64_notify_die(inf->name, regs, inf->sig, inf->code, addr, esr); + + mark_trap_exit(ARM64_TRAP_ACCESS, regs); } NOKPROBE_SYMBOL(do_mem_abort); void do_sp_pc_abort(unsigned long addr, unsigned long esr, struct pt_regs *regs) { + mark_trap_entry(ARM64_TRAP_ALIGN, regs); + arm64_notify_die("SP/PC alignment exception", regs, SIGBUS, BUS_ADRALN, addr, esr); + + mark_trap_exit(ARM64_TRAP_ALIGN, regs); } NOKPROBE_SYMBOL(do_sp_pc_abort); @@ -921,6 +945,8 @@ void do_debug_exception(unsigned long addr_if_watchpoint, unsigned long esr, const struct fault_info *inf = esr_to_debug_fault_info(esr); unsigned long pc = instruction_pointer(regs); + mark_trap_entry(ARM64_TRAP_DEBUG, regs); + debug_exception_enter(regs); if (user_mode(regs) && !is_ttbr0_addr(pc)) @@ -931,6 +957,8 @@ void do_debug_exception(unsigned long addr_if_watchpoint, unsigned long esr, } debug_exception_exit(regs); + + mark_trap_exit(ARM64_TRAP_DEBUG, regs); } NOKPROBE_SYMBOL(do_debug_exception); diff --git a/arch/x86/Kconfig b/arch/x86/Kconfig index 05c82fd5d..8171f80d0 100644 --- a/arch/x86/Kconfig +++ b/arch/x86/Kconfig @@ -30,6 +30,9 @@ config X86_64 select ARCH_SUPPORTS_PER_VMA_LOCK select ARCH_USE_CMPXCHG_LOCKREF select HAVE_ARCH_SOFT_DIRTY + select HAVE_IRQ_PIPELINE + select HAVE_DOVETAIL + select HAVE_ARCH_EVL select MODULES_USE_ELF_RELA select NEED_DMA_MAP_STATE select SWIOTLB @@ -251,6 +254,7 @@ config X86 select HAVE_NMI select HAVE_NOINSTR_VALIDATION if HAVE_OBJTOOL select HAVE_OBJTOOL if X86_64 + select HAVE_PERCPU_PREEMPT_COUNT select HAVE_OPTPROBES select HAVE_PCSPKR_PLATFORM select HAVE_PERF_EVENTS @@ -895,6 +899,8 @@ config INTEL_TDX_GUEST endif # HYPERVISOR_GUEST +source "kernel/Kconfig.evl" +source "kernel/Kconfig.dovetail" source "arch/x86/Kconfig.cpu" config HPET_TIMER diff --git a/arch/x86/entry/common.c b/arch/x86/entry/common.c index e72dac092..259aba616 100644 --- a/arch/x86/entry/common.c +++ b/arch/x86/entry/common.c @@ -76,6 +76,15 @@ __visible noinstr void do_syscall_64(struct pt_regs *regs, int nr) add_random_kstack_offset(); nr = syscall_enter_from_user_mode(regs, nr); + if (dovetailing()) { + if (nr == EXIT_SYSCALL_OOB) { + hard_local_irq_disable(); + return; + } + if (nr == EXIT_SYSCALL_TAIL) + goto done; + } + instrumentation_begin(); if (!do_syscall_x64(regs, nr) && !do_syscall_x32(regs, nr) && nr != -1) { @@ -84,6 +93,7 @@ __visible noinstr void do_syscall_64(struct pt_regs *regs, int nr) } instrumentation_end(); +done: syscall_exit_to_user_mode(regs); } #endif @@ -200,11 +210,23 @@ __visible noinstr void do_int80_emulation(struct pt_regs *regs) nr = syscall_32_enter(regs); - local_irq_enable(); + local_irq_enable_full(); nr = syscall_enter_from_user_mode_work(regs, nr); + + if (dovetailing()) { + if (nr == EXIT_SYSCALL_OOB) { + hard_local_irq_disable(); + return; + } + if (nr == EXIT_SYSCALL_TAIL) + goto done; + } + do_syscall_32_irqs_on(regs, nr); +done: instrumentation_end(); + syscall_exit_to_user_mode(regs); } #else /* CONFIG_IA32_EMULATION */ @@ -221,11 +243,22 @@ __visible noinstr void do_int80_syscall_32(struct pt_regs *regs) * the semantics of syscall_get_nr(). */ nr = syscall_enter_from_user_mode(regs, nr); + + if (dovetailing()) { + if (nr == EXIT_SYSCALL_OOB) { + hard_local_irq_disable(); + return; + } + if (nr == EXIT_SYSCALL_TAIL) + goto done; + } + instrumentation_begin(); do_syscall_32_irqs_on(regs, nr); instrumentation_end(); +done: syscall_exit_to_user_mode(regs); } #endif /* !CONFIG_IA32_EMULATION */ @@ -269,9 +302,20 @@ static noinstr bool __do_fast_syscall_32(struct pt_regs *regs) nr = syscall_enter_from_user_mode_work(regs, nr); + if (dovetailing()) { + if (nr == EXIT_SYSCALL_OOB) { + instrumentation_end(); + hard_local_irq_disable(); + return true; + } + if (nr == EXIT_SYSCALL_TAIL) + goto done; + } + /* Now this is just like a normal syscall. */ do_syscall_32_irqs_on(regs, nr); +done: instrumentation_end(); syscall_exit_to_user_mode(regs); return true; diff --git a/arch/x86/entry/entry_64.S b/arch/x86/entry/entry_64.S index 2192b6c33..e48043814 100644 --- a/arch/x86/entry/entry_64.S +++ b/arch/x86/entry/entry_64.S @@ -444,6 +444,11 @@ SYM_CODE_END(\asmsym) * If hits in kernel mode then it needs to go through the paranoid * entry as the exception can hit any random state. No preemption * check on exit to keep the paranoid path simple. + * + * irq_pipeline: since those events are non-maskable in essence, + * we may assume NMI-type restrictions for their handlers, which + * means the latter may - and actually have to - run immediately + * regardless of the current stage. */ .macro idtentry_mce_db vector asmsym cfunc SYM_CODE_START(\asmsym) diff --git a/arch/x86/hyperv/hv_init.c b/arch/x86/hyperv/hv_init.c index d1e2d1227..98fe6d426 100644 --- a/arch/x86/hyperv/hv_init.c +++ b/arch/x86/hyperv/hv_init.c @@ -177,7 +177,8 @@ static inline bool hv_reenlightenment_available(void) ms_hyperv.features & HV_ACCESS_REENLIGHTENMENT; } -DEFINE_IDTENTRY_SYSVEC(sysvec_hyperv_reenlightenment) +DEFINE_IDTENTRY_SYSVEC_PIPELINED(HYPERV_REENLIGHTENMENT_VECTOR, + sysvec_hyperv_reenlightenment) { apic_eoi(); inc_irq_stat(irq_hv_reenlightenment_count); diff --git a/arch/x86/include/asm/apic.h b/arch/x86/include/asm/apic.h index 33aa0c31c..71c25a3a0 100644 --- a/arch/x86/include/asm/apic.h +++ b/arch/x86/include/asm/apic.h @@ -403,11 +403,17 @@ static __always_inline void apic_write(u32 reg, u32 val) static_call(apic_call_write)(reg, val); } -static __always_inline void apic_eoi(void) +static __always_inline void __apic_eoi(void) { static_call(apic_call_eoi)(); } +static __always_inline void apic_eoi(void) +{ + if (!irqs_pipelined()) + __apic_eoi(); +} + static __always_inline void apic_native_eoi(void) { static_call(apic_call_native_eoi)(); diff --git a/arch/x86/include/asm/dovetail.h b/arch/x86/include/asm/dovetail.h new file mode 100644 index 000000000..a78959af6 --- /dev/null +++ b/arch/x86/include/asm/dovetail.h @@ -0,0 +1,49 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2019 Philippe Gerum. + */ +#ifndef _ASM_X86_DOVETAIL_H +#define _ASM_X86_DOVETAIL_H + +#if !defined(__ASSEMBLY__) && defined(CONFIG_DOVETAIL) + +#include +#include +#include + +static inline void arch_dovetail_exec_prepare(void) +{ + clear_thread_flag(TIF_NEED_FPU_LOAD); +} + +static inline +void arch_dovetail_switch_prepare(bool leave_inband) +{ + if (leave_inband) + fpu__suspend_inband(); +} + +static inline +void arch_dovetail_switch_finish(bool enter_inband) +{ + unsigned int ti_work = READ_ONCE(current_thread_info()->flags); + + if (unlikely(ti_work & _TIF_IO_BITMAP)) + tss_update_io_bitmap(); + + if (enter_inband) { + fpu__resume_inband(); + } else { + if (unlikely(ti_work & _TIF_NEED_FPU_LOAD && + !(current->flags & PF_KTHREAD))) + switch_fpu_return(); + } +} + +#define arch_dovetail_is_prctl(__nr) \ + (in_compat_syscall() ? (__nr) == __NR_ia32_prctl : (__nr) == __NR_prctl) + +#endif /* !__ASSEMBLY__ && CONFIG_DOVETAIL */ + +#endif /* _ASM_X86_DOVETAIL_H */ diff --git a/arch/x86/include/asm/evl/calibration.h b/arch/x86/include/asm/evl/calibration.h new file mode 100644 index 000000000..d3dcfdb86 --- /dev/null +++ b/arch/x86/include/asm/evl/calibration.h @@ -0,0 +1,12 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _EVL_X86_ASM_CALIBRATION_H +#define _EVL_X86_ASM_CALIBRATION_H + +#include + +static inline unsigned int evl_get_default_clock_gravity(void) +{ + return 3000; +} + +#endif /* !_EVL_X86_ASM_CALIBRATION_H */ diff --git a/arch/x86/include/asm/evl/fptest.h b/arch/x86/include/asm/evl/fptest.h new file mode 100644 index 000000000..ba9504980 --- /dev/null +++ b/arch/x86/include/asm/evl/fptest.h @@ -0,0 +1,42 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _EVL_X86_ASM_FPTEST_H +#define _EVL_X86_ASM_FPTEST_H + +#include +#include + +static inline bool evl_begin_fpu(void) +{ + kernel_fpu_begin(); + /* + * We need a clean context for testing the sanity of the FPU + * register stack across switches in evl_check_fpregs() + * (fildl->fistpl), which kernel_fpu_begin() does not + * guarantee us. Force this manually. + */ + asm volatile("fninit"); + + return true; +} + +static inline void evl_end_fpu(void) +{ + kernel_fpu_end(); +} + +static inline u32 evl_detect_fpu(void) +{ + u32 features = 0; + + /* We only test XMM2 and AVX switching when present. */ + + if (boot_cpu_has(X86_FEATURE_XMM2)) + features |= evl_x86_xmm2; + + if (boot_cpu_has(X86_FEATURE_AVX)) + features |= evl_x86_avx; + + return features; +} + +#endif /* _EVL_X86_ASM_FPTEST_H */ diff --git a/arch/x86/include/asm/evl/syscall.h b/arch/x86/include/asm/evl/syscall.h new file mode 100644 index 000000000..30f7feb6b --- /dev/null +++ b/arch/x86/include/asm/evl/syscall.h @@ -0,0 +1,24 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _EVL_X86_ASM_SYSCALL_H +#define _EVL_X86_ASM_SYSCALL_H + +#include +#include +#include +#include + +#define raw_put_user(src, dst) __put_user(src, dst) +#define raw_get_user(dst, src) __get_user(dst, src) + +static inline bool +is_valid_inband_syscall(unsigned int nr) +{ + return nr < NR_syscalls; +} + +static inline bool is_compat_oob_call(void) +{ + return in_ia32_syscall(); +} + +#endif /* !_EVL_X86_ASM_SYSCALL_H */ diff --git a/arch/x86/include/asm/evl/thread.h b/arch/x86/include/asm/evl/thread.h new file mode 100644 index 000000000..50c07d74f --- /dev/null +++ b/arch/x86/include/asm/evl/thread.h @@ -0,0 +1,12 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _EVL_X86_ASM_THREAD_H +#define _EVL_X86_ASM_THREAD_H + +#include + +static inline bool evl_is_breakpoint(int trapnr) +{ + return trapnr == X86_TRAP_DB || trapnr == X86_TRAP_BP; +} + +#endif /* !_EVL_X86_ASM_THREAD_H */ diff --git a/arch/x86/include/asm/fpu/api.h b/arch/x86/include/asm/fpu/api.h index a2be3aeff..2c7e3a0bb 100644 --- a/arch/x86/include/asm/fpu/api.h +++ b/arch/x86/include/asm/fpu/api.h @@ -66,20 +66,29 @@ static inline void kernel_fpu_begin(void) * * Disabling preemption also serializes against kernel_fpu_begin(). */ -static inline void fpregs_lock(void) +static inline unsigned long fpregs_lock(void) { + if (IS_ENABLED(CONFIG_IRQ_PIPELINE)) + return hard_preempt_disable(); + if (!IS_ENABLED(CONFIG_PREEMPT_RT)) local_bh_disable(); else preempt_disable(); + + return 0; } -static inline void fpregs_unlock(void) +static inline void fpregs_unlock(unsigned long flags) { - if (!IS_ENABLED(CONFIG_PREEMPT_RT)) - local_bh_enable(); - else - preempt_enable(); + if (IS_ENABLED(CONFIG_IRQ_PIPELINE)) { + hard_preempt_enable(flags); + } else { + if (!IS_ENABLED(CONFIG_PREEMPT_RT)) + local_bh_enable(); + else + preempt_enable(); + } } /* @@ -89,7 +98,7 @@ static inline void fpregs_unlock(void) * being automatically saved/restored. Then FPU state can be modified safely in the * registers, before unlocking with fpregs_unlock(). */ -void fpregs_lock_and_load(void); +unsigned long fpregs_lock_and_load(void); #ifdef CONFIG_X86_DEBUG_FPU extern void fpregs_assert_state_consistent(void); @@ -102,6 +111,10 @@ static inline void fpregs_assert_state_consistent(void) { } */ extern void switch_fpu_return(void); +/* For Dovetail context switching. */ +void fpu__suspend_inband(void); +void fpu__resume_inband(void); + /* * Query the presence of one or more xfeatures. Works on any legacy CPU as well. * diff --git a/arch/x86/include/asm/fpu/sched.h b/arch/x86/include/asm/fpu/sched.h index ca6e5e5f1..031eba1ae 100644 --- a/arch/x86/include/asm/fpu/sched.h +++ b/arch/x86/include/asm/fpu/sched.h @@ -3,6 +3,7 @@ #define _ASM_X86_FPU_SCHED_H #include +#include #include #include @@ -15,6 +16,32 @@ extern int fpu_clone(struct task_struct *dst, unsigned long clone_flags, bool m unsigned long shstk_addr); extern void fpu_flush_thread(void); +#ifdef CONFIG_DOVETAIL + +static inline void oob_fpu_set_preempt(struct fpu *fpu) +{ + fpu->preempted = true; +} + +static inline void oob_fpu_clear_preempt(struct fpu *fpu) +{ + fpu->preempted = false; +} + +static inline bool oob_fpu_preempted(struct fpu *old_fpu) +{ + return old_fpu->preempted; +} + +#else + +static inline bool oob_fpu_preempted(struct fpu *old_fpu) +{ + return false; +} + +#endif /* !CONFIG_DOVETAIL */ + /* * FPU state switching for scheduling. * @@ -40,7 +67,8 @@ extern void fpu_flush_thread(void); static inline void switch_fpu_prepare(struct fpu *old_fpu, int cpu) { if (cpu_feature_enabled(X86_FEATURE_FPU) && - !(current->flags & (PF_KTHREAD | PF_USER_WORKER))) { + !(current->flags & (PF_KTHREAD | PF_USER_WORKER)) && + !oob_fpu_preempted(old_fpu)) { save_fpregs_to_fpstate(old_fpu); /* * The save operation preserved register state, so the diff --git a/arch/x86/include/asm/fpu/types.h b/arch/x86/include/asm/fpu/types.h index fd5fb43d9..fb6321320 100644 --- a/arch/x86/include/asm/fpu/types.h +++ b/arch/x86/include/asm/fpu/types.h @@ -460,6 +460,18 @@ struct fpu { */ unsigned int last_cpu; +#ifdef CONFIG_DOVETAIL + /* + * @preempted: + * + * When Dovetail is enabled, this flag is set for the inband + * task context saved when entering a kernel_fpu_begin/end() + * section before the latter got preempted by an out-of-band + * task. + */ + bool preempted : 1; +#endif + /* * @avx512_timestamp: * diff --git a/arch/x86/include/asm/gsseg.h b/arch/x86/include/asm/gsseg.h index ab6a595ce..d523d23fe 100644 --- a/arch/x86/include/asm/gsseg.h +++ b/arch/x86/include/asm/gsseg.h @@ -32,9 +32,9 @@ static inline void native_load_gs_index(unsigned int selector) } else { unsigned long flags; - local_irq_save(flags); + flags = hard_local_irq_save(); asm_load_gs_index(selector); - local_irq_restore(flags); + hard_local_irq_restore(flags); } } diff --git a/arch/x86/include/asm/i8259.h b/arch/x86/include/asm/i8259.h index c715097e9..1dd2adc83 100644 --- a/arch/x86/include/asm/i8259.h +++ b/arch/x86/include/asm/i8259.h @@ -28,7 +28,7 @@ extern unsigned int cached_irq_mask; #define SLAVE_ICW4_DEFAULT 0x01 #define PIC_ICW4_AEOI 2 -extern raw_spinlock_t i8259A_lock; +extern hard_spinlock_t i8259A_lock; /* the PIC may need a careful delay on some platforms, hence specific calls */ static inline unsigned char inb_pic(unsigned int port) diff --git a/arch/x86/include/asm/idtentry.h b/arch/x86/include/asm/idtentry.h index 10603e185..d3548f43c 100644 --- a/arch/x86/include/asm/idtentry.h +++ b/arch/x86/include/asm/idtentry.h @@ -191,6 +191,66 @@ __visible noinstr void func(struct pt_regs *regs, unsigned long error_code) #define DECLARE_IDTENTRY_IRQ(vector, func) \ DECLARE_IDTENTRY_ERRORCODE(vector, func) +#ifdef CONFIG_IRQ_PIPELINE + +struct irq_stage_data; + +void arch_pipeline_entry(struct pt_regs *regs, u8 vector); + +#define DECLARE_IDTENTRY_SYSVEC_PIPELINED(vector, func) \ + DECLARE_IDTENTRY_SYSVEC(vector, func); \ + __visible void __##func(struct pt_regs *regs) + +#define DEFINE_IDTENTRY_IRQ_PIPELINED(func) \ +__visible noinstr void func(struct pt_regs *regs, \ + unsigned long error_code) \ +{ \ + arch_pipeline_entry(regs, (u8)error_code); \ +} \ +static __always_inline void __##func(struct pt_regs *regs, u8 vector) + +/* + * In a pipelined model, the actual sysvec __handler() is directly + * instrumentable, just like it is in fact in the non-pipelined + * model. The indirect call via run_on_irqstack_cond() in + * DEFINE_IDTENTRY_SYSVEC() happens to hide the noinstr dependency + * from objtool in the latter case. + */ +#define DEFINE_IDTENTRY_SYSVEC_PIPELINED(vector, func) \ +__visible noinstr void func(struct pt_regs *regs) \ +{ \ + arch_pipeline_entry(regs, vector); \ +} \ + \ +__visible void __##func(struct pt_regs *regs) + +#define DEFINE_IDTENTRY_SYSVEC_PIPELINED_NORETURN(vector, func) \ +__visible noinstr void func(struct pt_regs *regs) \ +{ \ + arch_pipeline_entry(regs, vector); \ +} \ + \ +__visible __noreturn void __##func(struct pt_regs *regs) + +#define DEFINE_IDTENTRY_SYSVEC_SIMPLE_PIPELINED(vector, func) \ + DEFINE_IDTENTRY_SYSVEC_PIPELINED(vector, func) + +extern void (*pipeline_hv_callback_fn)(struct pt_regs *regs); +static inline void pipeline_install_sysvec(int vector, const void *function) +{ + if (vector == HYPERVISOR_CALLBACK_VECTOR) + pipeline_hv_callback_fn = function; +} + +#else /* !CONFIG_IRQ_PIPELINE */ + +#define DECLARE_IDTENTRY_SYSVEC_PIPELINED(vector, func) DECLARE_IDTENTRY_SYSVEC(vector, func) + +#define DEFINE_IDTENTRY_IRQ_PIPELINED(func) DEFINE_IDTENTRY_IRQ(func) +#define DEFINE_IDTENTRY_SYSVEC_PIPELINED(vector, func) DEFINE_IDTENTRY_SYSVEC(func) +#define DEFINE_IDTENTRY_SYSVEC_SIMPLE_PIPELINED(vector, func) DEFINE_IDTENTRY_SYSVEC_SIMPLE(func) +#define DEFINE_IDTENTRY_SYSVEC_PIPELINED_NORETURN(vector, func) DEFINE_IDTENTRY_SYSVEC(func) + /** * DEFINE_IDTENTRY_IRQ - Emit code for device interrupt IDT entry points * @func: Function name of the entry point @@ -221,6 +281,11 @@ __visible noinstr void func(struct pt_regs *regs, \ \ static noinline void __##func(struct pt_regs *regs, u32 vector) +#define pipeline_install_sysvec(__vector, __function) \ + do { (void)__vector; (void)__function; } while (0) + +#endif /* !CONFIG_IRQ_PIPELINE */ + /** * DECLARE_IDTENTRY_SYSVEC - Declare functions for system vector entry points * @vector: Vector number (ignored for C) @@ -459,6 +524,12 @@ __visible noinstr void func(struct pt_regs *regs, \ #define DEFINE_FREDENTRY_DEBUG DEFINE_FREDENTRY_RAW #endif +#define sysvec_install(vector, function) \ + { \ + pipeline_install_sysvec(vector, __##function); \ + alloc_intr_gate(vector, asm_##function); \ + } + #else /* !__ASSEMBLY__ */ /* @@ -487,6 +558,9 @@ __visible noinstr void func(struct pt_regs *regs, \ #define DECLARE_IDTENTRY_SYSVEC(vector, func) \ idtentry_sysvec vector func +#define DECLARE_IDTENTRY_SYSVEC_PIPELINED(vector, func) \ + DECLARE_IDTENTRY_SYSVEC(vector, func) + #ifdef CONFIG_X86_64 # define DECLARE_IDTENTRY_MCE(vector, func) \ idtentry_mce_db vector asm_##func func diff --git a/arch/x86/include/asm/irq_pipeline.h b/arch/x86/include/asm/irq_pipeline.h new file mode 100644 index 000000000..a2e1bc865 --- /dev/null +++ b/arch/x86/include/asm/irq_pipeline.h @@ -0,0 +1,131 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2019 Philippe Gerum . + */ +#ifndef _ASM_X86_IRQ_PIPELINE_H +#define _ASM_X86_IRQ_PIPELINE_H + +#include + +#ifdef CONFIG_IRQ_PIPELINE + +#include + +#define FIRST_SYSTEM_IRQ NR_IRQS +#define TIMER_OOB_IPI apicm_vector_irq(TIMER_OOB_VECTOR) +#define RESCHEDULE_OOB_IPI apicm_vector_irq(RESCHEDULE_OOB_VECTOR) +#define CALL_FUNCTION_OOB_IPI apicm_vector_irq(CALL_FUNCTION_OOB_VECTOR) +#define apicm_irq_vector(__irq) ((__irq) - FIRST_SYSTEM_IRQ + FIRST_SYSTEM_VECTOR) +#define apicm_vector_irq(__vec) ((__vec) - FIRST_SYSTEM_VECTOR + FIRST_SYSTEM_IRQ) + +#define X86_EFLAGS_SS_BIT 31 + +static inline notrace +unsigned long arch_irqs_virtual_to_native_flags(int stalled) +{ + return (!stalled) << X86_EFLAGS_IF_BIT; +} + +static inline notrace +unsigned long arch_irqs_native_to_virtual_flags(unsigned long flags) +{ + return hard_irqs_disabled_flags(flags) << X86_EFLAGS_SS_BIT; +} + +#ifndef CONFIG_PARAVIRT_XXL + +static inline notrace unsigned long arch_local_irq_save(void) +{ + int stalled = inband_irq_save(); + barrier(); + return arch_irqs_virtual_to_native_flags(stalled); +} + +static inline notrace void arch_local_irq_enable(void) +{ + barrier(); + inband_irq_enable(); +} + +static inline notrace void arch_local_irq_disable(void) +{ + inband_irq_disable(); + barrier(); +} + +static inline notrace unsigned long arch_local_save_flags(void) +{ + int stalled = inband_irqs_disabled(); + barrier(); + return arch_irqs_virtual_to_native_flags(stalled); +} + +#endif /* !CONFIG_PARAVIRT_XXL */ + +static inline notrace void arch_local_irq_restore(unsigned long flags) +{ + inband_irq_restore(native_irqs_disabled_flags(flags)); + barrier(); +} + +static inline +void arch_save_timer_regs(struct pt_regs *dst, struct pt_regs *src) +{ + dst->flags = src->flags; + dst->cs = src->cs; + dst->ip = src->ip; + dst->bp = src->bp; + dst->ss = src->ss; + dst->sp = src->sp; +} + +static inline bool arch_steal_pipelined_tick(struct pt_regs *regs) +{ + return !(regs->flags & X86_EFLAGS_IF); +} + +static inline int arch_enable_oob_stage(void) +{ + return 0; +} + +static inline void arch_handle_irq_pipelined(struct pt_regs *regs) +{ } + +#else /* !CONFIG_IRQ_PIPELINE */ + +struct pt_regs; + +#ifndef CONFIG_PARAVIRT_XXL + +static inline notrace unsigned long arch_local_save_flags(void) +{ + return native_save_fl(); +} + +static inline notrace void arch_local_irq_disable(void) +{ + native_irq_disable(); +} + +static inline notrace void arch_local_irq_enable(void) +{ + native_irq_enable(); +} + +/* + * For spinlocks, etc: + */ +static inline notrace unsigned long arch_local_irq_save(void) +{ + unsigned long flags = arch_local_save_flags(); + arch_local_irq_disable(); + return flags; +} + +#endif /* !CONFIG_PARAVIRT_XXL */ + +#endif /* !CONFIG_IRQ_PIPELINE */ + +#endif /* _ASM_X86_IRQ_PIPELINE_H */ diff --git a/arch/x86/include/asm/irq_stack.h b/arch/x86/include/asm/irq_stack.h index b71ad173f..879fa241c 100644 --- a/arch/x86/include/asm/irq_stack.h +++ b/arch/x86/include/asm/irq_stack.h @@ -134,8 +134,13 @@ /* \ * User mode entry and interrupt on the irq stack do not \ * switch stacks. If from user mode the task stack is empty. \ + * \ + * irq_pipeline: we always start from a kernel context when \ + * replaying interrupts, so the user check is not relevant \ + * in this case. \ */ \ - if (user_mode(regs) || __this_cpu_read(pcpu_hot.hardirq_stack_inuse)) { \ + if ((!irqs_pipelined() && user_mode(regs)) || \ + __this_cpu_read(pcpu_hot.hardirq_stack_inuse)) { \ irq_enter_rcu(); \ func(c_args); \ irq_exit_rcu(); \ @@ -145,6 +150,11 @@ * switching stacks. Interrupts are disabled in both \ * places. Invoke the stack switch macro with the call \ * sequence which matches the above direct invocation. \ + * \ + * IRQ pipeline: only in-band (soft-)irq handlers have \ + * to run on the irqstack. Out-of-band irq handlers \ + * run directly over the preempted context, therefore \ + * they never land there. \ */ \ __this_cpu_write(pcpu_hot.hardirq_stack_inuse, true); \ call_on_irqstack(func, asm_call, constr); \ @@ -217,6 +227,8 @@ __this_cpu_write(pcpu_hot.hardirq_stack_inuse, false); \ } +#else /* needed by CONFIG_IRQ_PIPELINE */ +#include #endif #else /* CONFIG_X86_64 */ diff --git a/arch/x86/include/asm/irq_vectors.h b/arch/x86/include/asm/irq_vectors.h index 3a19904c2..13288f177 100644 --- a/arch/x86/include/asm/irq_vectors.h +++ b/arch/x86/include/asm/irq_vectors.h @@ -99,10 +99,20 @@ #define LOCAL_TIMER_VECTOR 0xec +#ifdef CONFIG_IRQ_PIPELINE +#define TIMER_OOB_VECTOR 0xeb +#define RESCHEDULE_OOB_VECTOR 0xea +#define CALL_FUNCTION_OOB_VECTOR 0xe9 +#define FIRST_SYSTEM_APIC_VECTOR CALL_FUNCTION_OOB_VECTOR +#define NR_APIC_VECTORS (NR_VECTORS - FIRST_SYSTEM_VECTOR) +#else +#define FIRST_SYSTEM_APIC_VECTOR LOCAL_TIMER_VECTOR +#endif + #define NR_VECTORS 256 #ifdef CONFIG_X86_LOCAL_APIC -#define FIRST_SYSTEM_VECTOR LOCAL_TIMER_VECTOR +#define FIRST_SYSTEM_VECTOR FIRST_SYSTEM_APIC_VECTOR #else #define FIRST_SYSTEM_VECTOR NR_VECTORS #endif diff --git a/arch/x86/include/asm/irqflags.h b/arch/x86/include/asm/irqflags.h index 8c5ae649d..b7d7419f6 100644 --- a/arch/x86/include/asm/irqflags.h +++ b/arch/x86/include/asm/irqflags.h @@ -23,7 +23,7 @@ extern __always_inline unsigned long native_save_fl(void) * it evaluates its effective address -- this is part of the * documented behavior of the "pop" instruction. */ - asm volatile("# __raw_save_flags\n\t" + asm volatile("# __native_save_flags\n\t" "pushf ; pop %0" : "=rm" (flags) : /* no input */ @@ -32,6 +32,15 @@ extern __always_inline unsigned long native_save_fl(void) return flags; } +extern inline void native_restore_fl(unsigned long flags); +extern __always_inline void native_restore_fl(unsigned long flags) +{ + asm volatile("push %0 ; popf" + : /* no output */ + :"g" (flags) + :"memory", "cc"); +} + static __always_inline void native_irq_disable(void) { asm volatile("cli": : :"memory"); @@ -48,35 +57,64 @@ static __always_inline void native_safe_halt(void) asm volatile("sti; hlt": : :"memory"); } -static __always_inline void native_halt(void) +static inline unsigned long native_save_flags(void) { - mds_idle_clear_cpu_buffers(); - asm volatile("hlt": : :"memory"); + return native_save_fl(); } -#endif +static __always_inline void native_irq_sync(void) +{ + asm volatile("sti ; nop ; cli": : :"memory"); +} -#ifdef CONFIG_PARAVIRT_XXL -#include -#else -#ifndef __ASSEMBLY__ -#include +static __always_inline unsigned long native_irq_save(void) +{ + unsigned long flags; + + flags = native_save_flags(); + + native_irq_disable(); + + return flags; +} -static __always_inline unsigned long arch_local_save_flags(void) +static __always_inline int native_irqs_disabled_flags(unsigned long flags) { - return native_save_fl(); + return !(flags & X86_EFLAGS_IF); } -static __always_inline void arch_local_irq_disable(void) +static __always_inline void native_irq_restore(unsigned long flags) { - native_irq_disable(); + /* + * CAUTION: the hard_irq_* API may be used to bracket code + * which re-enables interrupts inside save/restore pairs, so + * do not try to be (too) smart: do restore the original flags + * unconditionally. + */ + native_restore_fl(flags); +} + +static __always_inline bool native_irqs_disabled(void) +{ + unsigned long flags = native_save_flags(); + return native_irqs_disabled_flags(flags); } -static __always_inline void arch_local_irq_enable(void) +static __always_inline void native_halt(void) { - native_irq_enable(); + mds_idle_clear_cpu_buffers(); + asm volatile("hlt": : :"memory"); } +#endif + +#ifdef CONFIG_PARAVIRT_XXL +#include +#else +#ifndef __ASSEMBLY__ +#include +#include + /* * Used in the idle loop; sti takes one instruction cycle * to complete: @@ -95,15 +133,6 @@ static __always_inline void halt(void) native_halt(); } -/* - * For spinlocks, etc: - */ -static __always_inline unsigned long arch_local_irq_save(void) -{ - unsigned long flags = arch_local_save_flags(); - arch_local_irq_disable(); - return flags; -} #else #ifdef CONFIG_X86_64 @@ -119,7 +148,7 @@ static __always_inline unsigned long arch_local_irq_save(void) #ifndef __ASSEMBLY__ static __always_inline int arch_irqs_disabled_flags(unsigned long flags) { - return !(flags & X86_EFLAGS_IF); + return native_irqs_disabled_flags(flags); } static __always_inline int arch_irqs_disabled(void) @@ -129,11 +158,13 @@ static __always_inline int arch_irqs_disabled(void) return arch_irqs_disabled_flags(flags); } -static __always_inline void arch_local_irq_restore(unsigned long flags) +#ifndef CONFIG_IRQ_PIPELINE +static inline notrace void arch_local_irq_restore(unsigned long flags) { if (!arch_irqs_disabled_flags(flags)) arch_local_irq_enable(); } +#endif /* !CONFIG_IRQ_PIPELINE */ #endif /* !__ASSEMBLY__ */ #endif diff --git a/arch/x86/include/asm/mmu_context.h b/arch/x86/include/asm/mmu_context.h index 8dac45a2c..40c3be33d 100644 --- a/arch/x86/include/asm/mmu_context.h +++ b/arch/x86/include/asm/mmu_context.h @@ -172,6 +172,13 @@ extern void switch_mm_irqs_off(struct mm_struct *prev, struct mm_struct *next, struct task_struct *tsk); #define switch_mm_irqs_off switch_mm_irqs_off +static inline void +switch_oob_mm(struct mm_struct *prev, struct mm_struct *next, + struct task_struct *tsk) +{ + switch_mm_irqs_off(prev, next, tsk); +} + #define activate_mm(prev, next) \ do { \ paravirt_enter_mmap(next); \ diff --git a/arch/x86/include/asm/syscall.h b/arch/x86/include/asm/syscall.h index 228a42585..22c93762d 100644 --- a/arch/x86/include/asm/syscall.h +++ b/arch/x86/include/asm/syscall.h @@ -121,6 +121,16 @@ static inline void syscall_get_arguments(struct task_struct *task, } } +static inline unsigned long syscall_get_arg0(struct task_struct *task, + struct pt_regs *regs) +{ + if (IS_ENABLED(CONFIG_IA32_EMULATION) && + task->thread_info.status & TS_COMPAT) + return regs->bx; + + return regs->di; +} + static inline int syscall_get_arch(struct task_struct *task) { /* x32 tasks should be considered AUDIT_ARCH_X86_64. */ diff --git a/arch/x86/include/asm/thread_info.h b/arch/x86/include/asm/thread_info.h index d63b02940..ee3c4845f 100644 --- a/arch/x86/include/asm/thread_info.h +++ b/arch/x86/include/asm/thread_info.h @@ -52,6 +52,7 @@ struct task_struct; #include #include +#include struct thread_info { unsigned long flags; /* low level flags */ @@ -60,6 +61,7 @@ struct thread_info { #ifdef CONFIG_SMP u32 cpu; /* current CPU */ #endif + struct oob_thread_state oob_state; /* co-kernel thread state */ }; #define INIT_THREAD_INFO(tsk) \ @@ -67,6 +69,8 @@ struct thread_info { .flags = 0, \ } +#define ti_local_flags(__ti) ((__ti)->status) + #else /* !__ASSEMBLY__ */ #include @@ -92,12 +96,14 @@ struct thread_info { #define TIF_NOCPUID 15 /* CPUID is not accessible in userland */ #define TIF_NOTSC 16 /* TSC is not accessible in userland */ #define TIF_NOTIFY_SIGNAL 17 /* signal notifications exist */ +#define TIF_RETUSER 19 /* INBAND_TASK_RETUSER is pending */ #define TIF_MEMDIE 20 /* is terminating due to OOM killer */ #define TIF_POLLING_NRFLAG 21 /* idle is polling for TIF_NEED_RESCHED */ #define TIF_IO_BITMAP 22 /* uses I/O bitmap */ #define TIF_SPEC_FORCE_UPDATE 23 /* Force speculation MSR update in context switch */ #define TIF_FORCED_TF 24 /* true if TF in eflags artificially */ #define TIF_BLOCKSTEP 25 /* set when we want DEBUGCTLMSR_BTF */ +#define TIF_MAYDAY 26 /* emergency trap pending */ #define TIF_LAZY_MMU_UPDATES 27 /* task is updating the mmu lazily */ #define TIF_ADDR32 29 /* 32-bit address space on 64 bits */ @@ -115,10 +121,12 @@ struct thread_info { #define _TIF_NOCPUID (1 << TIF_NOCPUID) #define _TIF_NOTSC (1 << TIF_NOTSC) #define _TIF_NOTIFY_SIGNAL (1 << TIF_NOTIFY_SIGNAL) +#define _TIF_RETUSER (1 << TIF_RETUSER) #define _TIF_POLLING_NRFLAG (1 << TIF_POLLING_NRFLAG) #define _TIF_IO_BITMAP (1 << TIF_IO_BITMAP) #define _TIF_SPEC_FORCE_UPDATE (1 << TIF_SPEC_FORCE_UPDATE) #define _TIF_FORCED_TF (1 << TIF_FORCED_TF) +#define _TIF_MAYDAY (1 << TIF_MAYDAY) #define _TIF_BLOCKSTEP (1 << TIF_BLOCKSTEP) #define _TIF_LAZY_MMU_UPDATES (1 << TIF_LAZY_MMU_UPDATES) #define _TIF_ADDR32 (1 << TIF_ADDR32) @@ -215,6 +223,16 @@ static inline int arch_within_stack_frames(const void * const stack, * have to worry about atomic accesses. */ #define TS_COMPAT 0x0002 /* 32bit syscall active (64BIT)*/ +/* bits 2 and 3 reserved for compat */ +#define TS_OOB 0x0010 /* Thread is running out-of-band */ +#define TS_DOVETAIL 0x0020 /* Dovetail notifier enabled */ +#define TS_OFFSTAGE 0x0040 /* Thread is in-flight to OOB context */ +#define TS_OOBTRAP 0x0080 /* Handling a trap from OOB context */ + +#define _TLF_OOB TS_OOB +#define _TLF_DOVETAIL TS_DOVETAIL +#define _TLF_OFFSTAGE TS_OFFSTAGE +#define _TLF_OOBTRAP TS_OOBTRAP #ifndef __ASSEMBLY__ #ifdef CONFIG_COMPAT diff --git a/arch/x86/include/asm/tlbflush.h b/arch/x86/include/asm/tlbflush.h index 25726893c..dec5322ce 100644 --- a/arch/x86/include/asm/tlbflush.h +++ b/arch/x86/include/asm/tlbflush.h @@ -42,9 +42,9 @@ static inline void cr4_set_bits(unsigned long mask) { unsigned long flags; - local_irq_save(flags); + flags = hard_local_irq_save(); cr4_set_bits_irqsoff(mask); - local_irq_restore(flags); + hard_local_irq_restore(flags); } /* Clear in this cpu's CR4. */ @@ -52,9 +52,9 @@ static inline void cr4_clear_bits(unsigned long mask) { unsigned long flags; - local_irq_save(flags); + flags = hard_local_irq_save(); cr4_clear_bits_irqsoff(mask); - local_irq_restore(flags); + hard_local_irq_restore(flags); } #ifndef MODULE diff --git a/arch/x86/include/asm/traps.h b/arch/x86/include/asm/traps.h index b1c9cea6b..413cd1d52 100644 --- a/arch/x86/include/asm/traps.h +++ b/arch/x86/include/asm/traps.h @@ -50,14 +50,22 @@ void __noreturn handle_stack_overflow(struct pt_regs *regs, static inline void cond_local_irq_enable(struct pt_regs *regs) { - if (regs->flags & X86_EFLAGS_IF) - local_irq_enable(); + if (regs->flags & X86_EFLAGS_IF) { + if (running_inband()) + local_irq_enable_full(); + else + hard_local_irq_enable(); + } } static inline void cond_local_irq_disable(struct pt_regs *regs) { - if (regs->flags & X86_EFLAGS_IF) - local_irq_disable(); + if (regs->flags & X86_EFLAGS_IF) { + if (running_inband()) + local_irq_disable_full(); + else + hard_local_irq_disable(); + } } #endif /* _ASM_X86_TRAPS_H */ diff --git a/arch/x86/include/dovetail/irq.h b/arch/x86/include/dovetail/irq.h new file mode 100644 index 000000000..f214e2f6e --- /dev/null +++ b/arch/x86/include/dovetail/irq.h @@ -0,0 +1,11 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _EVL_DOVETAIL_IRQ_H +#define _EVL_DOVETAIL_IRQ_H + +#ifdef CONFIG_EVL +#include +#else +#include_next +#endif + +#endif /* !_EVL_DOVETAIL_IRQ_H */ diff --git a/arch/x86/include/dovetail/mm_info.h b/arch/x86/include/dovetail/mm_info.h new file mode 100644 index 000000000..13087687d --- /dev/null +++ b/arch/x86/include/dovetail/mm_info.h @@ -0,0 +1,7 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _EVL_DOVETAIL_MM_INFO_H +#define _EVL_DOVETAIL_MM_INFO_H + +#include + +#endif /* !_EVL_DOVETAIL_MM_INFO_H */ diff --git a/arch/x86/include/dovetail/net.h b/arch/x86/include/dovetail/net.h new file mode 100644 index 000000000..b23cf3c5e --- /dev/null +++ b/arch/x86/include/dovetail/net.h @@ -0,0 +1,7 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _EVL_DOVETAIL_NET_H +#define _EVL_DOVETAIL_NET_H + +#include + +#endif /* !_EVL_DOVETAIL_NET_H */ diff --git a/arch/x86/include/dovetail/netdevice.h b/arch/x86/include/dovetail/netdevice.h new file mode 100644 index 000000000..bc7ac6769 --- /dev/null +++ b/arch/x86/include/dovetail/netdevice.h @@ -0,0 +1,7 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _EVL_DOVETAIL_NETDEVICE_H +#define _EVL_DOVETAIL_NETDEVICE_H + +#include + +#endif /* !_EVL_DOVETAIL_NETDEVICE_H */ diff --git a/arch/x86/include/dovetail/poll.h b/arch/x86/include/dovetail/poll.h new file mode 100644 index 000000000..76e51be38 --- /dev/null +++ b/arch/x86/include/dovetail/poll.h @@ -0,0 +1,7 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _EVL_DOVETAIL_POLL_H +#define _EVL_DOVETAIL_POLL_H + +#include + +#endif /* !_EVL_DOVETAIL_POLL_H */ diff --git a/arch/x86/include/dovetail/thread_info.h b/arch/x86/include/dovetail/thread_info.h new file mode 100644 index 000000000..4253b13fe --- /dev/null +++ b/arch/x86/include/dovetail/thread_info.h @@ -0,0 +1,7 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _EVL_DOVETAIL_THREAD_INFO_H +#define _EVL_DOVETAIL_THREAD_INFO_H + +#include + +#endif /* !_EVL_DOVETAIL_THREAD_INFO_H */ diff --git a/arch/x86/include/uapi/asm/evl/fptest.h b/arch/x86/include/uapi/asm/evl/fptest.h new file mode 100644 index 000000000..0c9ceb694 --- /dev/null +++ b/arch/x86/include/uapi/asm/evl/fptest.h @@ -0,0 +1,122 @@ +/* + * SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note + * + * Derived from Xenomai Cobalt, https://xenomai.org/ + * Copyright (C) 2006 Gilles Chanteperdrix . + */ +#ifndef _EVL_X86_ASM_UAPI_FPTEST_H +#define _EVL_X86_ASM_UAPI_FPTEST_H + +#include + +#define evl_x86_xmm2 0x1 +#define evl_x86_avx 0x2 + +#define evl_set_fpregs(__features, __val) \ + do { \ + __u64 __vec[4] = { __val, 0, __val, 0 }; \ + __u32 __ival = (__val); \ + unsigned int __i; \ + \ + for (__i = 0; __i < 8; __i++) \ + __asm__ __volatile__("fildl %0": \ + /* no output */ :"m"(__ival)); \ + if (__features & evl_x86_avx) { \ + __asm__ __volatile__( \ + "vmovupd %0,%%ymm0;" \ + "vmovupd %0,%%ymm1;" \ + "vmovupd %0,%%ymm2;" \ + "vmovupd %0,%%ymm3;" \ + "vmovupd %0,%%ymm4;" \ + "vmovupd %0,%%ymm5;" \ + "vmovupd %0,%%ymm6;" \ + "vmovupd %0,%%ymm7;" \ + : : "m"(__vec[0]), "m"(__vec[1]), \ + "m"(__vec[2]), "m"(__vec[3])); \ + } else if (__features & evl_x86_xmm2) { \ + __asm__ __volatile__( \ + "movupd %0,%%xmm0;" \ + "movupd %0,%%xmm1;" \ + "movupd %0,%%xmm2;" \ + "movupd %0,%%xmm3;" \ + "movupd %0,%%xmm4;" \ + "movupd %0,%%xmm5;" \ + "movupd %0,%%xmm6;" \ + "movupd %0,%%xmm7;" \ + : : "m"(__vec[0]), "m"(__vec[1]), \ + "m"(__vec[2]), "m"(__vec[3])); \ + } \ + } while (0) + +#define evl_check_fpregs(__features, __val, __bad) \ + ({ \ + unsigned int __i, __result = __val; \ + __u64 __vec[8][4]; \ + __u32 __e[8]; \ + \ + for (__i = 0; __i < 8; __i++) \ + __asm__ __volatile__("fistpl %0": \ + "=m" (__e[7 - __i])); \ + if (__features & evl_x86_avx) { \ + __asm__ __volatile__( \ + "vmovupd %%ymm0,%0;" \ + "vmovupd %%ymm1,%1;" \ + "vmovupd %%ymm2,%2;" \ + "vmovupd %%ymm3,%3;" \ + "vmovupd %%ymm4,%4;" \ + "vmovupd %%ymm5,%5;" \ + "vmovupd %%ymm6,%6;" \ + "vmovupd %%ymm7,%7;" \ + : "=m" (__vec[0][0]), "=m" (__vec[1][0]), \ + "=m" (__vec[2][0]), "=m" (__vec[3][0]), \ + "=m" (__vec[4][0]), "=m" (__vec[5][0]), \ + "=m" (__vec[6][0]), "=m" (__vec[7][0])); \ + } else if (__features & evl_x86_xmm2) { \ + __asm__ __volatile__( \ + "movupd %%xmm0,%0;" \ + "movupd %%xmm1,%1;" \ + "movupd %%xmm2,%2;" \ + "movupd %%xmm3,%3;" \ + "movupd %%xmm4,%4;" \ + "movupd %%xmm5,%5;" \ + "movupd %%xmm6,%6;" \ + "movupd %%xmm7,%7;" \ + : "=m" (__vec[0][0]), "=m" (__vec[1][0]), \ + "=m" (__vec[2][0]), "=m" (__vec[3][0]), \ + "=m" (__vec[4][0]), "=m" (__vec[5][0]), \ + "=m" (__vec[6][0]), "=m" (__vec[7][0])); \ + } \ + for (__i = 0, __bad = -1; __i < 8; __i++) { \ + if (__e[__i] != __val) { \ + __result = __e[__i]; \ + __bad = __i; \ + break; \ + } \ + } \ + if (__bad >= 0) \ + ; \ + else if (__features & evl_x86_avx) { \ + for (__i = 0; __i < 8; __i++) { \ + if (__vec[__i][0] != __val) { \ + __result = __vec[__i][0]; \ + __bad = __i + 8; \ + break; \ + } \ + if (__vec[__i][2] != __val) { \ + __result = __vec[__i][2]; \ + __bad = __i + 8; \ + break; \ + } \ + } \ + } else if (__features & evl_x86_xmm2) { \ + for (__i = 0; __i < 8; __i++) \ + if (__vec[__i][0] != __val) { \ + __result = __vec[__i][0]; \ + __bad = __i + 8; \ + break; \ + } \ + } \ + __result; \ + }) + +#endif /* !_EVL_X86_ASM_UAPI_FPTEST_H */ diff --git a/arch/x86/kernel/Makefile b/arch/x86/kernel/Makefile index 3269a0e23..d12e55518 100644 --- a/arch/x86/kernel/Makefile +++ b/arch/x86/kernel/Makefile @@ -121,6 +121,7 @@ obj-$(CONFIG_PARAVIRT_CLOCK) += pvclock.o obj-$(CONFIG_X86_PMEM_LEGACY_DEVICE) += pmem.o obj-$(CONFIG_JAILHOUSE_GUEST) += jailhouse.o +obj-$(CONFIG_IRQ_PIPELINE) += irq_pipeline.o obj-$(CONFIG_EISA) += eisa.o obj-$(CONFIG_PCSPKR_PLATFORM) += pcspeaker.o diff --git a/arch/x86/kernel/alternative.c b/arch/x86/kernel/alternative.c index aae7456ec..4196267c9 100644 --- a/arch/x86/kernel/alternative.c +++ b/arch/x86/kernel/alternative.c @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -220,13 +221,16 @@ __optimize_nops(u8 *instr, size_t len, struct insn *insn, int *next, int *prev, } if (insn_is_nop(insn)) { + unsigned long flags; int nop = i; *next = skip_nops(instr, *next, len); if (*target && *next == *target) nop = *prev; + flags = hard_local_irq_save(); add_nop(instr + nop, *next - nop); + hard_local_irq_restore(flags); DUMP_BYTES(ALT, instr, len, "%px: [%d:%d) optimized NOPs: ", instr, nop, *next); return true; } @@ -1426,6 +1430,10 @@ int alternatives_text_reserved(void *start, void *end) /* Use this to add nops to a buffer, then text_poke the whole buffer. */ static void __init_or_module add_nops(void *insns, unsigned int len) { + unsigned long flags; + + flags = hard_local_irq_save(); + while (len > 0) { unsigned int noplen = len; if (noplen > ASM_NOP_MAX) @@ -1434,6 +1442,8 @@ static void __init_or_module add_nops(void *insns, unsigned int len) insns += noplen; len -= noplen; } + + hard_local_irq_restore(flags); } void __init_or_module apply_paravirt(struct paravirt_patch_site *start, @@ -1441,6 +1451,9 @@ void __init_or_module apply_paravirt(struct paravirt_patch_site *start, { struct paravirt_patch_site *p; char insn_buff[MAX_PATCH_LEN]; + unsigned long flags; + + flags = hard_local_irq_save(); for (p = start; p < end; p++) { unsigned int used; @@ -1456,6 +1469,8 @@ void __init_or_module apply_paravirt(struct paravirt_patch_site *start, add_nops(insn_buff + used, p->len - used); text_poke_early(p->instr, insn_buff, p->len); } + + hard_local_irq_restore(flags); } extern struct paravirt_patch_site __start_parainstructions[], __stop_parainstructions[]; @@ -1691,12 +1706,14 @@ void __init_or_module text_poke_early(void *addr, const void *opcode, * code cannot be running and speculative code-fetches are * prevented. Just change the code. */ + flags = hard_local_irq_save(); memcpy(addr, opcode, len); + hard_local_irq_restore(flags); } else { - local_irq_save(flags); + flags = hard_local_irq_save(); memcpy(addr, opcode, len); sync_core(); - local_irq_restore(flags); + hard_local_irq_restore(flags); /* * Could also do a CLFLUSH here to speed up CPU recovery; but @@ -1727,6 +1744,7 @@ static inline temp_mm_state_t use_temporary_mm(struct mm_struct *mm) temp_mm_state_t temp_state; lockdep_assert_irqs_disabled(); + WARN_ON_ONCE(irq_pipeline_debug() && !hard_irqs_disabled()); /* * Make sure not to be in TLB lazy mode, as otherwise we'll end up @@ -1834,7 +1852,7 @@ static void *__text_poke(text_poke_f func, void *addr, const void *src, size_t l */ VM_BUG_ON(!ptep); - local_irq_save(flags); + local_irq_save_full(flags); pte = mk_pte(pages[0], pgprot); set_pte_at(poking_mm, poking_addr, ptep, pte); @@ -1887,7 +1905,7 @@ static void *__text_poke(text_poke_f func, void *addr, const void *src, size_t l BUG_ON(memcmp(addr, src, len)); } - local_irq_restore(flags); + local_irq_restore_full(flags); pte_unmap_unlock(ptep, ptl); return addr; } diff --git a/arch/x86/kernel/apic/apic.c b/arch/x86/kernel/apic/apic.c index 00ca9c3c1..398726db4 100644 --- a/arch/x86/kernel/apic/apic.c +++ b/arch/x86/kernel/apic/apic.c @@ -31,6 +31,7 @@ #include #include #include +#include #include #include #include @@ -245,10 +246,10 @@ void native_apic_icr_write(u32 low, u32 id) { unsigned long flags; - local_irq_save(flags); + flags = hard_local_irq_save(); apic_write(APIC_ICR2, SET_XAPIC_DEST_FIELD(id)); apic_write(APIC_ICR, low); - local_irq_restore(flags); + hard_local_irq_restore(flags); } u64 native_apic_icr_read(void) @@ -307,6 +308,9 @@ int lapic_get_maxlvt(void) static void __setup_APIC_LVTT(unsigned int clocks, int oneshot, int irqen) { unsigned int lvtt_value, tmp_value; + unsigned long flags; + + flags = hard_cond_local_irq_save(); lvtt_value = LOCAL_TIMER_VECTOR; if (!oneshot) @@ -335,6 +339,8 @@ static void __setup_APIC_LVTT(unsigned int clocks, int oneshot, int irqen) * According to Intel, MFENCE can do the serialization here. */ asm volatile("mfence" : : : "memory"); + hard_cond_local_irq_restore(flags); + printk_once(KERN_DEBUG "TSC deadline timer enabled\n"); return; } @@ -348,6 +354,8 @@ static void __setup_APIC_LVTT(unsigned int clocks, int oneshot, int irqen) if (!oneshot) apic_write(APIC_TMICT, clocks / APIC_DIVISOR); + + hard_cond_local_irq_restore(flags); } /* @@ -452,24 +460,29 @@ static int lapic_next_event(unsigned long delta, static int lapic_next_deadline(unsigned long delta, struct clock_event_device *evt) { + unsigned long flags; u64 tsc; /* This MSR is special and need a special fence: */ weak_wrmsr_fence(); + flags = hard_local_irq_save(); tsc = rdtsc(); wrmsrl(MSR_IA32_TSC_DEADLINE, tsc + (((u64) delta) * TSC_DIVISOR)); + hard_local_irq_restore(flags); return 0; } static int lapic_timer_shutdown(struct clock_event_device *evt) { + unsigned long flags; unsigned int v; /* Lapic used as dummy for broadcast ? */ if (evt->features & CLOCK_EVT_FEAT_DUMMY) return 0; + flags = hard_local_irq_save(); v = apic_read(APIC_LVTT); v |= (APIC_LVT_MASKED | LOCAL_TIMER_VECTOR); apic_write(APIC_LVTT, v); @@ -758,6 +771,7 @@ calibrate_by_pmtimer(long deltapm, long *delta, long *deltatsc) *deltatsc = (long)res; } + hard_local_irq_restore(flags); return 0; } @@ -1245,6 +1259,32 @@ void lapic_shutdown(void) #endif disable_local_APIC(); +static DEFINE_PER_CPU(struct clock_event_device, lapic_events); + +#ifdef CONFIG_IRQ_PIPELINE + +#define LAPIC_TIMER_IRQ apicm_vector_irq(LOCAL_TIMER_VECTOR) + +static irqreturn_t lapic_oob_handler(int irq, void *dev_id) +{ + struct clock_event_device *evt = this_cpu_ptr(&lapic_events); + + trace_local_timer_entry(LOCAL_TIMER_VECTOR); + clockevents_handle_event(evt); + trace_local_timer_exit(LOCAL_TIMER_VECTOR); + + return IRQ_HANDLED; +} + +static struct irqaction lapic_oob_action = { + .handler = lapic_oob_handler, + .name = "Out-of-band LAPIC timer interrupt", + .flags = IRQF_TIMER | IRQF_PERCPU, +}; + +#else +#define LAPIC_TIMER_IRQ -1 +#endif local_irq_restore(flags); } @@ -1493,7 +1533,7 @@ static bool apic_check_and_ack(union apic_ir *irr, union apic_ir *isr) * per set bit. */ for_each_set_bit(bit, isr->map, APIC_IR_BITS) - apic_eoi(); + __apic_eoi(); return true; } @@ -2167,7 +2207,7 @@ static noinline void handle_spurious_interrupt(u8 vector) if (v & (1 << (vector & 0x1f))) { pr_info("Spurious interrupt (vector 0x%02x) on CPU#%d. Acked\n", vector, smp_processor_id()); - apic_eoi(); + __apic_eoi(); } else { pr_info("Spurious interrupt (vector 0x%02x) on CPU#%d. Not pending!\n", vector, smp_processor_id()); @@ -2185,18 +2225,23 @@ static noinline void handle_spurious_interrupt(u8 vector) * trigger on an entry which is routed to the common_spurious idtentry * point. */ -DEFINE_IDTENTRY_IRQ(spurious_interrupt) +DEFINE_IDTENTRY_IRQ_PIPELINED(spurious_interrupt) { handle_spurious_interrupt(vector); } -DEFINE_IDTENTRY_SYSVEC(sysvec_spurious_apic_interrupt) +DEFINE_IDTENTRY_SYSVEC_PIPELINED(SPURIOUS_APIC_VECTOR, + sysvec_spurious_apic_interrupt) { handle_spurious_interrupt(SPURIOUS_APIC_VECTOR); } /* * This interrupt should never happen with our APIC/SMP architecture + * + * irq_pipeline: same as spurious_interrupt, would run directly out of + * the IDT, no deferral via the interrupt log which means that only + * the hardware IRQ state is considered for masking. */ DEFINE_IDTENTRY_SYSVEC(sysvec_error_interrupt) { diff --git a/arch/x86/kernel/apic/apic_flat_64.c b/arch/x86/kernel/apic/apic_flat_64.c index 032a84e2c..b5f44fe67 100644 --- a/arch/x86/kernel/apic/apic_flat_64.c +++ b/arch/x86/kernel/apic/apic_flat_64.c @@ -32,9 +32,9 @@ static void _flat_send_IPI_mask(unsigned long mask, int vector) { unsigned long flags; - local_irq_save(flags); + flags = hard_local_irq_save(); __default_send_IPI_dest_field(mask, vector, APIC_DEST_LOGICAL); - local_irq_restore(flags); + hard_local_irq_restore(flags); } static void flat_send_IPI_mask(const struct cpumask *cpumask, int vector) diff --git a/arch/x86/kernel/apic/apic_numachip.c b/arch/x86/kernel/apic/apic_numachip.c index 63f3d7be9..f3c5fac35 100644 --- a/arch/x86/kernel/apic/apic_numachip.c +++ b/arch/x86/kernel/apic/apic_numachip.c @@ -92,10 +92,10 @@ static void numachip_send_IPI_one(int cpu, int vector) if (!((apicid ^ local_apicid) >> NUMACHIP_LAPIC_BITS)) { unsigned long flags; - local_irq_save(flags); + flags = hard_local_irq_save(); __default_send_IPI_dest_field(apicid, vector, APIC_DEST_PHYSICAL); - local_irq_restore(flags); + hard_local_irq_restore(flags); preempt_enable(); return; } diff --git a/arch/x86/kernel/apic/io_apic.c b/arch/x86/kernel/apic/io_apic.c index d0c5325d1..4a004276a 100644 --- a/arch/x86/kernel/apic/io_apic.c +++ b/arch/x86/kernel/apic/io_apic.c @@ -80,7 +80,7 @@ #define for_each_irq_pin(entry, head) \ list_for_each_entry(entry, &head, list) -static DEFINE_RAW_SPINLOCK(ioapic_lock); +static DEFINE_HARD_SPINLOCK(ioapic_lock); static DEFINE_MUTEX(ioapic_mutex); static unsigned int ioapic_dynirq_base; static int ioapic_initialized; @@ -1623,7 +1623,7 @@ static int __init timer_irq_works(void) if (no_timer_check) return 1; - local_irq_enable(); + local_irq_enable_full(); if (boot_cpu_has(X86_FEATURE_TSC)) delay_with_tsc(); else @@ -1637,7 +1637,7 @@ static int __init timer_irq_works(void) * least one tick may be lost due to delays. */ - local_irq_disable(); + local_irq_disable_full(); /* Did jiffies advance? */ return time_after(jiffies, t1 + 4); @@ -1708,14 +1708,56 @@ static bool io_apic_level_ack_pending(struct mp_chip_data *data) return false; } +static inline void do_prepare_move(struct irq_data *data) +{ + if (!irqd_irq_masked(data)) + mask_ioapic_irq(data); +} + +#ifdef CONFIG_IRQ_PIPELINE + +static inline void ioapic_finish_move(struct irq_data *data, bool moveit); + +static void ioapic_deferred_irq_move(struct irq_work *work) +{ + struct irq_data *data; + struct irq_desc *desc; + unsigned long flags; + + data = container_of(work, struct irq_data, move_work); + desc = irq_data_to_desc(data); + raw_spin_lock_irqsave(&desc->lock, flags); + do_prepare_move(data); + ioapic_finish_move(data, true); + raw_spin_unlock_irqrestore(&desc->lock, flags); +} + +static inline bool __ioapic_prepare_move(struct irq_data *data) +{ + init_irq_work(&data->move_work, ioapic_deferred_irq_move); + irq_work_queue(&data->move_work); + + return false; /* Postpone ioapic_finish_move(). */ +} + +#else /* !CONFIG_IRQ_PIPELINE */ + +static inline bool __ioapic_prepare_move(struct irq_data *data) +{ + do_prepare_move(data); + + return true; +} + +#endif + static inline bool ioapic_prepare_move(struct irq_data *data) { /* If we are moving the IRQ we need to mask it */ - if (unlikely(irqd_is_setaffinity_pending(data))) { - if (!irqd_irq_masked(data)) - mask_ioapic_irq(data); - return true; - } + if (irqd_is_setaffinity_pending(data) && + !irqd_is_setaffinity_blocked(data)) + return __ioapic_prepare_move(data); + return false; } @@ -1814,7 +1856,7 @@ static void ioapic_ack_level(struct irq_data *irq_data) * We must acknowledge the irq before we move it or the acknowledge will * not propagate properly. */ - apic_eoi(); + __apic_eoi(); /* * Tail end of clearing remote IRR bit (either by delivering the EOI @@ -1976,7 +2018,8 @@ static struct irq_chip ioapic_chip __read_mostly = { .irq_retrigger = irq_chip_retrigger_hierarchy, .irq_get_irqchip_state = ioapic_irq_get_chip_state, .flags = IRQCHIP_SKIP_SET_WAKE | - IRQCHIP_AFFINITY_PRE_STARTUP, + IRQCHIP_AFFINITY_PRE_STARTUP | + IRQCHIP_PIPELINE_SAFE, }; static struct irq_chip ioapic_ir_chip __read_mostly = { @@ -1990,7 +2033,8 @@ static struct irq_chip ioapic_ir_chip __read_mostly = { .irq_retrigger = irq_chip_retrigger_hierarchy, .irq_get_irqchip_state = ioapic_irq_get_chip_state, .flags = IRQCHIP_SKIP_SET_WAKE | - IRQCHIP_AFFINITY_PRE_STARTUP, + IRQCHIP_AFFINITY_PRE_STARTUP | + IRQCHIP_PIPELINE_SAFE, }; static inline void init_IO_APIC_traps(void) @@ -2037,7 +2081,7 @@ static void unmask_lapic_irq(struct irq_data *data) static void ack_lapic_irq(struct irq_data *data) { - apic_eoi(); + __apic_eoi(); } static struct irq_chip lapic_chip __read_mostly = { @@ -2045,6 +2089,7 @@ static struct irq_chip lapic_chip __read_mostly = { .irq_mask = mask_lapic_irq, .irq_unmask = unmask_lapic_irq, .irq_ack = ack_lapic_irq, + .flags = IRQCHIP_PIPELINE_SAFE, }; static void lapic_register_intr(int irq) @@ -2164,7 +2209,7 @@ static inline void __init check_timer(void) if (!global_clock_event) return; - local_irq_disable(); + local_irq_disable_full(); /* * get/set the timer IRQ vector: @@ -2297,7 +2342,7 @@ static inline void __init check_timer(void) panic("IO-APIC + timer doesn't work! Boot with apic=debug and send a " "report. Then try booting with the 'noapic' option.\n"); out: - local_irq_enable(); + local_irq_enable_full(); } /* @@ -3046,10 +3091,10 @@ int mp_irqdomain_alloc(struct irq_domain *domain, unsigned int virq, mp_preconfigure_entry(data); mp_register_handler(virq, data->is_level); - local_irq_save(flags); + local_irq_save_full(flags); if (virq < nr_legacy_irqs()) legacy_pic->mask(virq); - local_irq_restore(flags); + local_irq_restore_full(flags); apic_printk(APIC_VERBOSE, KERN_DEBUG "IOAPIC[%d]: Preconfigured routing entry (%d-%d -> IRQ %d Level:%i ActiveLow:%i)\n", diff --git a/arch/x86/kernel/apic/ipi.c b/arch/x86/kernel/apic/ipi.c index a44ba7209..05d5bcaf0 100644 --- a/arch/x86/kernel/apic/ipi.c +++ b/arch/x86/kernel/apic/ipi.c @@ -143,12 +143,15 @@ void apic_mem_wait_icr_idle(void) */ static void __default_send_IPI_shortcut(unsigned int shortcut, int vector) { + unsigned long flags; + /* * Wait for the previous ICR command to complete. Use * safe_apic_wait_icr_idle() for the NMI vector as there have been * issues where otherwise the system hangs when the panic CPU tries * to stop the others before launching the kdump kernel. */ + flags = hard_cond_local_irq_save(); if (unlikely(vector == NMI_VECTOR)) apic_mem_wait_icr_idle_timeout(); else @@ -156,6 +159,7 @@ static void __default_send_IPI_shortcut(unsigned int shortcut, int vector) /* Destination field (ICR2) and the destination mode are ignored */ native_apic_mem_write(APIC_ICR, __prepare_ICR(shortcut, vector, 0)); + hard_cond_local_irq_restore(flags); } /* @@ -165,7 +169,10 @@ static void __default_send_IPI_shortcut(unsigned int shortcut, int vector) void __default_send_IPI_dest_field(unsigned int dest_mask, int vector, unsigned int dest_mode) { + unsigned long flags; + /* See comment in __default_send_IPI_shortcut() */ + flags = hard_cond_local_irq_save(); if (unlikely(vector == NMI_VECTOR)) apic_mem_wait_icr_idle_timeout(); else @@ -175,16 +182,17 @@ void __default_send_IPI_dest_field(unsigned int dest_mask, int vector, native_apic_mem_write(APIC_ICR2, __prepare_ICR2(dest_mask)); /* Send it with the proper destination mode */ native_apic_mem_write(APIC_ICR, __prepare_ICR(0, vector, dest_mode)); + hard_cond_local_irq_restore(flags); } void default_send_IPI_single_phys(int cpu, int vector) { unsigned long flags; - local_irq_save(flags); + flags = hard_local_irq_save(); __default_send_IPI_dest_field(per_cpu(x86_cpu_to_apicid, cpu), vector, APIC_DEST_PHYSICAL); - local_irq_restore(flags); + hard_local_irq_restore(flags); } void default_send_IPI_mask_sequence_phys(const struct cpumask *mask, int vector) @@ -192,12 +200,12 @@ void default_send_IPI_mask_sequence_phys(const struct cpumask *mask, int vector) unsigned long flags; unsigned long cpu; - local_irq_save(flags); + flags = hard_local_irq_save(); for_each_cpu(cpu, mask) { __default_send_IPI_dest_field(per_cpu(x86_cpu_to_apicid, cpu), vector, APIC_DEST_PHYSICAL); } - local_irq_restore(flags); + hard_local_irq_restore(flags); } void default_send_IPI_mask_allbutself_phys(const struct cpumask *mask, @@ -206,14 +214,14 @@ void default_send_IPI_mask_allbutself_phys(const struct cpumask *mask, unsigned int cpu, this_cpu = smp_processor_id(); unsigned long flags; - local_irq_save(flags); + flags = hard_local_irq_save(); for_each_cpu(cpu, mask) { if (cpu == this_cpu) continue; __default_send_IPI_dest_field(per_cpu(x86_cpu_to_apicid, cpu), vector, APIC_DEST_PHYSICAL); } - local_irq_restore(flags); + hard_local_irq_restore(flags); } /* @@ -245,10 +253,10 @@ void default_send_IPI_mask_sequence_logical(const struct cpumask *mask, int vect unsigned long flags; unsigned int cpu; - local_irq_save(flags); + flags = hard_local_irq_save(); for_each_cpu(cpu, mask) __default_send_IPI_dest_field(1U << cpu, vector, APIC_DEST_LOGICAL); - local_irq_restore(flags); + hard_local_irq_restore(flags); } void default_send_IPI_mask_allbutself_logical(const struct cpumask *mask, @@ -257,13 +265,13 @@ void default_send_IPI_mask_allbutself_logical(const struct cpumask *mask, unsigned int cpu, this_cpu = smp_processor_id(); unsigned long flags; - local_irq_save(flags); + flags = hard_local_irq_save(); for_each_cpu(cpu, mask) { if (cpu == this_cpu) continue; __default_send_IPI_dest_field(1U << cpu, vector, APIC_DEST_LOGICAL); } - local_irq_restore(flags); + hard_local_irq_restore(flags); } void default_send_IPI_mask_logical(const struct cpumask *cpumask, int vector) @@ -274,10 +282,10 @@ void default_send_IPI_mask_logical(const struct cpumask *cpumask, int vector) if (!mask) return; - local_irq_save(flags); + flags = hard_local_irq_save(); WARN_ON(mask & ~cpumask_bits(cpu_online_mask)[0]); __default_send_IPI_dest_field(mask, vector, APIC_DEST_LOGICAL); - local_irq_restore(flags); + hard_local_irq_restore(flags); } #ifdef CONFIG_SMP diff --git a/arch/x86/kernel/apic/msi.c b/arch/x86/kernel/apic/msi.c index d9651f15a..1ff8df151 100644 --- a/arch/x86/kernel/apic/msi.c +++ b/arch/x86/kernel/apic/msi.c @@ -252,7 +252,8 @@ static bool x86_init_dev_msi_info(struct device *dev, struct irq_domain *domain, info->chip->irq_ack = irq_chip_ack_parent; info->chip->irq_retrigger = irq_chip_retrigger_hierarchy; info->chip->flags |= IRQCHIP_SKIP_SET_WAKE | - IRQCHIP_AFFINITY_PRE_STARTUP; + IRQCHIP_AFFINITY_PRE_STARTUP | + IRQCHIP_PIPELINE_SAFE; info->handler = handle_edge_irq; info->handler_name = "edge"; @@ -321,7 +322,8 @@ static struct irq_chip dmar_msi_controller = { .irq_compose_msi_msg = dmar_msi_compose_msg, .irq_write_msi_msg = dmar_msi_write_msg, .flags = IRQCHIP_SKIP_SET_WAKE | - IRQCHIP_AFFINITY_PRE_STARTUP, + IRQCHIP_AFFINITY_PRE_STARTUP | + IRQCHIP_PIPELINE_SAFE, }; static int dmar_msi_init(struct irq_domain *domain, diff --git a/arch/x86/kernel/apic/vector.c b/arch/x86/kernel/apic/vector.c index 218ef9072..659b79113 100644 --- a/arch/x86/kernel/apic/vector.c +++ b/arch/x86/kernel/apic/vector.c @@ -9,6 +9,7 @@ */ #include #include +#include #include #include #include @@ -39,27 +40,110 @@ struct apic_chip_data { struct irq_domain *x86_vector_domain; EXPORT_SYMBOL_GPL(x86_vector_domain); -static DEFINE_RAW_SPINLOCK(vector_lock); +static DEFINE_HARD_SPINLOCK(vector_lock); static cpumask_var_t vector_searchmask; static struct irq_chip lapic_controller; static struct irq_matrix *vector_matrix; #ifdef CONFIG_SMP +#ifdef CONFIG_IRQ_PIPELINE + +static void vector_cleanup_work(struct irq_work *work); + +#define DECLARE_X86_CLEANUP_WORKER struct irq_work work +#define INIT_X86_CLEANUP_WORKER \ + .work = IRQ_WORK_INIT(vector_cleanup_work) + +#define queue_cleanup_work(__cl, __cpu) \ + irq_work_queue_on(&(__cl)->work, __cpu) + +/* + * Dequeuing from the current CPU always, so we don't expect any + * pending work. + */ +#define dequeue_cleanup_work(__cl) \ + ({ irq_work_is_busy(&(__cl)->work) ? -1 : 0; }) + +#define requeue_cleanup_work(__cl) \ + irq_work_queue(&(__cl)->work) + +#else /* !CONFIG_IRQ_PIPELINE */ + static void vector_cleanup_callback(struct timer_list *tmr); +#define DECLARE_X86_CLEANUP_WORKER struct timer_list timer +#define INIT_X86_CLEANUP_WORKER \ + .timer = __TIMER_INITIALIZER(vector_cleanup_callback, TIMER_PINNED) + +/* + * The lockless timer_pending() check is safe here. If it returns + * true, then the callback will observe this new apic data in the + * hlist as everything is serialized by vector lock. + * + * If it returns false then the timer is either not armed or the other + * CPU executes the callback, which again would be blocked on vector + * lock. Rearming it in the latter case makes it fire for nothing. + * + * This is also safe against the callback rearming the timer because + * that's serialized via vector lock too. + */ +#define queue_cleanup_work(__cl, __cpu) \ + do { \ + if (!timer_pending(&(__cl)->timer)) { \ + (__cl)->timer.expires = jiffies + 1; \ + add_timer_on(&(__cl)->timer, __cpu); \ + } \ + } while (0) + +#define dequeue_cleanup_work(__cl) \ + try_to_del_timer_sync(&(__cl)->timer) + +#define requeue_cleanup_work(__cl) \ + mod_timer(&(__cl)->timer, jiffies + 1) + +#endif /* !CONFIG_IRQ_PIPELINE */ + struct vector_cleanup { struct hlist_head head; - struct timer_list timer; + DECLARE_X86_CLEANUP_WORKER; }; static DEFINE_PER_CPU(struct vector_cleanup, vector_cleanup) = { .head = HLIST_HEAD_INIT, - .timer = __TIMER_INITIALIZER(vector_cleanup_callback, TIMER_PINNED), + INIT_X86_CLEANUP_WORKER, }; + +static void __vector_cleanup_callback(struct vector_cleanup *cl); + +#ifdef CONFIG_IRQ_PIPELINE + +static void vector_cleanup_work(struct irq_work *work) +{ + struct vector_cleanup *cl = container_of(work, typeof(*cl), work); + __vector_cleanup_callback(cl); +} + +#else + +static void vector_cleanup_callback(struct timer_list *tmr) +{ + struct vector_cleanup *cl = container_of(tmr, typeof(*cl), timer); + __vector_cleanup_callback(cl); +} + #endif +#endif /* !CONFIG_SMP */ + void lock_vector_lock(void) { + /* + * irq_pipeline: vanilla assumes that inband is stalled on + * entry. In addition, we assume that hard irqs are on as well + * (which is the regular case). + */ + WARN_ON_ONCE(irq_pipeline_debug() && !hard_irqs_disabled()); + hard_cond_local_irq_disable(); /* Used to the online set of cpus does not change * during assign_irq_vector. */ @@ -69,6 +153,7 @@ void lock_vector_lock(void) void unlock_vector_lock(void) { raw_spin_unlock(&vector_lock); + hard_cond_local_irq_enable(); } void init_irq_alloc_info(struct irq_alloc_info *info, @@ -860,11 +945,11 @@ void lapic_offline(void) lock_vector_lock(); - /* In case the vector cleanup timer has not expired */ + /* In case some cleanup work is pending */ __vector_cleanup(cl, false); irq_matrix_offline(vector_matrix); - WARN_ON_ONCE(try_to_del_timer_sync(&cl->timer) < 0); + WARN_ON_ONCE(dequeue_cleanup_work(cl) < 0); WARN_ON_ONCE(!hlist_empty(&cl->head)); unlock_vector_lock(); @@ -873,18 +958,21 @@ void lapic_offline(void) static int apic_set_affinity(struct irq_data *irqd, const struct cpumask *dest, bool force) { + unsigned long flags; int err; + WARN_ON_ONCE(irq_pipeline_debug() && !hard_irqs_disabled()); + if (WARN_ON_ONCE(!irqd_is_activated(irqd))) return -EIO; - raw_spin_lock(&vector_lock); + raw_spin_lock_irqsave(&vector_lock, flags); cpumask_and(vector_searchmask, dest, cpu_online_mask); if (irqd_affinity_is_managed(irqd)) err = assign_managed_vector(irqd, vector_searchmask); else err = assign_vector_locked(irqd, vector_searchmask); - raw_spin_unlock(&vector_lock); + raw_spin_unlock_irqrestore(&vector_lock, flags); return err ? err : IRQ_SET_MASK_OK; } @@ -904,12 +992,46 @@ static int apic_retrigger_irq(struct irq_data *irqd) return 1; } +#if defined(CONFIG_IRQ_PIPELINE) && defined(CONFIG_GENERIC_PENDING_IRQ) +/* + * Moving an irq means updating its affinity settings (see + * irq_move_masked_irq()). We cannot do such operation directly from a + * pipeline entry context. Defer it to a regular inband IRQ context on + * the current CPU via an irq_work callback. + */ +static void apic_deferred_irq_move(struct irq_work *work) +{ + struct irq_data *irqd; + struct irq_desc *desc; + unsigned long flags; + + irqd = container_of(work, struct irq_data, move_work); + desc = irq_data_to_desc(irqd); + raw_spin_lock_irqsave(&desc->lock, flags); + __irq_move_irq(irqd); + raw_spin_unlock_irqrestore(&desc->lock, flags); +} + +void apic_ack_irq(struct irq_data *irqd) +{ + if (irqd_is_setaffinity_pending(irqd) && + !irqd_is_setaffinity_blocked(irqd)) { + init_irq_work(&irqd->move_work, apic_deferred_irq_move); + irq_work_queue(&irqd->move_work); + } + __apic_eoi(); +} + +#else + void apic_ack_irq(struct irq_data *irqd) { irq_move_irq(irqd); apic_eoi(); } +#endif /* !CONFIG_IRQ_PIPELINE || !CONFIG_GENERIC_PENDING_IRQ */ + void apic_ack_edge(struct irq_data *irqd) { irq_complete_move(irqd_cfg(irqd)); @@ -963,6 +1085,7 @@ static void __vector_cleanup(struct vector_cleanup *cl, bool check_irr) bool rearm = false; lockdep_assert_held(&vector_lock); + WARN_ON_ONCE(irq_pipeline_debug() && !hard_irqs_disabled()); hlist_for_each_entry_safe(apicd, tmp, &cl->head, clist) { unsigned int irr, vector = apicd->prev_vector; @@ -991,15 +1114,17 @@ static void __vector_cleanup(struct vector_cleanup *cl, bool check_irr) /* * Must happen under vector_lock to make the timer_pending() check * in __vector_schedule_cleanup() race free against the rearm here. + * + * irq_pipeline: irq_work functions run in-band with hard irqs + * on, so we will take the pending interrupt prior to cleaning + * up again. */ if (rearm) - mod_timer(&cl->timer, jiffies + 1); + requeue_cleanup_work(cl); } -static void vector_cleanup_callback(struct timer_list *tmr) +static void __vector_cleanup_callback(struct vector_cleanup *cl) { - struct vector_cleanup *cl = container_of(tmr, typeof(*cl), timer); - /* Prevent vectors vanishing under us */ raw_spin_lock_irq(&vector_lock); __vector_cleanup(cl, true); @@ -1009,37 +1134,19 @@ static void vector_cleanup_callback(struct timer_list *tmr) static void __vector_schedule_cleanup(struct apic_chip_data *apicd) { unsigned int cpu = apicd->prev_cpu; + unsigned long flags; - raw_spin_lock(&vector_lock); + raw_spin_lock_irqsave(&vector_lock, flags); apicd->move_in_progress = 0; if (cpu_online(cpu)) { struct vector_cleanup *cl = per_cpu_ptr(&vector_cleanup, cpu); - hlist_add_head(&apicd->clist, &cl->head); - - /* - * The lockless timer_pending() check is safe here. If it - * returns true, then the callback will observe this new - * apic data in the hlist as everything is serialized by - * vector lock. - * - * If it returns false then the timer is either not armed - * or the other CPU executes the callback, which again - * would be blocked on vector lock. Rearming it in the - * latter case makes it fire for nothing. - * - * This is also safe against the callback rearming the timer - * because that's serialized via vector lock too. - */ - if (!timer_pending(&cl->timer)) { - cl->timer.expires = jiffies + 1; - add_timer_on(&cl->timer, cpu); - } + queue_cleanup_work(cl, cpu); } else { pr_warn("IRQ %u schedule cleanup for offline CPU %u\n", apicd->irq, cpu); free_moved_vector(apicd); } - raw_spin_unlock(&vector_lock); + raw_spin_unlock_irqrestore(&vector_lock, flags); } void vector_schedule_cleanup(struct irq_cfg *cfg) @@ -1079,6 +1186,8 @@ void irq_force_complete_move(struct irq_desc *desc) struct irq_data *irqd; unsigned int vector; + WARN_ON_ONCE(irq_pipeline_debug() && !hard_irqs_disabled()); + /* * The function is called for all descriptors regardless of which * irqdomain they belong to. For example if an IRQ is provided by @@ -1170,9 +1279,10 @@ void irq_force_complete_move(struct irq_desc *desc) int lapic_can_unplug_cpu(void) { unsigned int rsvd, avl, tomove, cpu = smp_processor_id(); + unsigned long flags; int ret = 0; - raw_spin_lock(&vector_lock); + raw_spin_lock_irqsave(&vector_lock, flags); tomove = irq_matrix_allocated(vector_matrix); avl = irq_matrix_available(vector_matrix, true); if (avl < tomove) { @@ -1187,7 +1297,7 @@ int lapic_can_unplug_cpu(void) rsvd, avl); } out: - raw_spin_unlock(&vector_lock); + raw_spin_unlock_irqrestore(&vector_lock, flags); return ret; } #endif /* HOTPLUG_CPU */ diff --git a/arch/x86/kernel/apic/x2apic_cluster.c b/arch/x86/kernel/apic/x2apic_cluster.c index affbff65e..d6e64d8af 100644 --- a/arch/x86/kernel/apic/x2apic_cluster.c +++ b/arch/x86/kernel/apic/x2apic_cluster.c @@ -45,7 +45,7 @@ __x2apic_send_IPI_mask(const struct cpumask *mask, int vector, int apic_dest) /* x2apic MSRs are special and need a special fence: */ weak_wrmsr_fence(); - local_irq_save(flags); + flags = hard_local_irq_save(); tmpmsk = this_cpu_cpumask_var_ptr(ipi_mask); cpumask_copy(tmpmsk, mask); @@ -69,7 +69,7 @@ __x2apic_send_IPI_mask(const struct cpumask *mask, int vector, int apic_dest) cpumask_andnot(tmpmsk, tmpmsk, cmsk); } - local_irq_restore(flags); + hard_local_irq_restore(flags); } static void x2apic_send_IPI_mask(const struct cpumask *mask, int vector) diff --git a/arch/x86/kernel/apic/x2apic_phys.c b/arch/x86/kernel/apic/x2apic_phys.c index 788cdb4ee..1189b19fd 100644 --- a/arch/x86/kernel/apic/x2apic_phys.c +++ b/arch/x86/kernel/apic/x2apic_phys.c @@ -60,7 +60,7 @@ __x2apic_send_IPI_mask(const struct cpumask *mask, int vector, int apic_dest) /* x2apic MSRs are special and need a special fence: */ weak_wrmsr_fence(); - local_irq_save(flags); + flags = hard_local_irq_save(); this_cpu = smp_processor_id(); for_each_cpu(query_cpu, mask) { @@ -69,7 +69,7 @@ __x2apic_send_IPI_mask(const struct cpumask *mask, int vector, int apic_dest) __x2apic_send_IPI_dest(per_cpu(x86_cpu_to_apicid, query_cpu), vector, APIC_DEST_PHYSICAL); } - local_irq_restore(flags); + hard_local_irq_restore(flags); } static void x2apic_send_IPI_mask(const struct cpumask *mask, int vector) diff --git a/arch/x86/kernel/asm-offsets.c b/arch/x86/kernel/asm-offsets.c index 50383bc46..484c919ee 100644 --- a/arch/x86/kernel/asm-offsets.c +++ b/arch/x86/kernel/asm-offsets.c @@ -38,6 +38,9 @@ static void __used common(void) #ifdef CONFIG_STACKPROTECTOR OFFSET(TASK_stack_canary, task_struct, stack_canary); #endif +#ifdef CONFIG_IRQ_PIPELINE + DEFINE(OOB_stage_mask, STAGE_MASK); +#endif BLANK(); OFFSET(pbe_address, pbe, address); diff --git a/arch/x86/kernel/cpu/acrn.c b/arch/x86/kernel/cpu/acrn.c index bfeb18fad..54128c997 100644 --- a/arch/x86/kernel/cpu/acrn.c +++ b/arch/x86/kernel/cpu/acrn.c @@ -27,7 +27,7 @@ static u32 __init acrn_detect(void) static void __init acrn_init_platform(void) { /* Setup the IDT for ACRN hypervisor callback */ - alloc_intr_gate(HYPERVISOR_CALLBACK_VECTOR, asm_sysvec_acrn_hv_callback); + sysvec_install(HYPERVISOR_CALLBACK_VECTOR, sysvec_acrn_hv_callback); x86_platform.calibrate_tsc = acrn_get_tsc_khz; x86_platform.calibrate_cpu = acrn_get_tsc_khz; @@ -40,7 +40,8 @@ static bool acrn_x2apic_available(void) static void (*acrn_intr_handler)(void); -DEFINE_IDTENTRY_SYSVEC(sysvec_acrn_hv_callback) +DEFINE_IDTENTRY_SYSVEC_PIPELINED(HYPERVISOR_CALLBACK_VECTOR, + sysvec_acrn_hv_callback) { struct pt_regs *old_regs = set_irq_regs(regs); diff --git a/arch/x86/kernel/cpu/mce/amd.c b/arch/x86/kernel/cpu/mce/amd.c index c267f43de..2b180c0c9 100644 --- a/arch/x86/kernel/cpu/mce/amd.c +++ b/arch/x86/kernel/cpu/mce/amd.c @@ -753,13 +753,18 @@ static void __log_error(unsigned int bank, u64 status, u64 addr, u64 misc) mce_log(&m); } +/* + * irq_pipeline: Deferred error events have NMI semantics wrt to + * pipelining, they can and should be handled immediately out of the + * IDT. + */ DEFINE_IDTENTRY_SYSVEC(sysvec_deferred_error) { trace_deferred_error_apic_entry(DEFERRED_ERROR_VECTOR); inc_irq_stat(irq_deferred_error_count); deferred_error_int_vector(); trace_deferred_error_apic_exit(DEFERRED_ERROR_VECTOR); - apic_eoi(); + __apic_eoi(); } /* diff --git a/arch/x86/kernel/cpu/mce/core.c b/arch/x86/kernel/cpu/mce/core.c index e103c227a..f5c22f432 100644 --- a/arch/x86/kernel/cpu/mce/core.c +++ b/arch/x86/kernel/cpu/mce/core.c @@ -1572,10 +1572,12 @@ noinstr void do_machine_check(struct pt_regs *regs) /* If this triggers there is no way to recover. Die hard. */ BUG_ON(!on_thread_stack() || !user_mode(regs)); + hard_local_irq_enable(); if (!mce_usable_address(&m)) queue_task_work(&m, msg, kill_me_now); else queue_task_work(&m, msg, kill_me_maybe); + hard_local_irq_disable(); } else { /* diff --git a/arch/x86/kernel/cpu/mce/threshold.c b/arch/x86/kernel/cpu/mce/threshold.c index ef4e7bb5f..ef522dce5 100644 --- a/arch/x86/kernel/cpu/mce/threshold.c +++ b/arch/x86/kernel/cpu/mce/threshold.c @@ -27,5 +27,5 @@ DEFINE_IDTENTRY_SYSVEC(sysvec_threshold) inc_irq_stat(irq_threshold_count); mce_threshold_vector(); trace_threshold_apic_exit(THRESHOLD_APIC_VECTOR); - apic_eoi(); + __apic_eoi(); } diff --git a/arch/x86/kernel/cpu/mshyperv.c b/arch/x86/kernel/cpu/mshyperv.c index 5ae77d966..4c885d0ef 100644 --- a/arch/x86/kernel/cpu/mshyperv.c +++ b/arch/x86/kernel/cpu/mshyperv.c @@ -115,7 +115,8 @@ static void (*hv_stimer0_handler)(void); static void (*hv_kexec_handler)(void); static void (*hv_crash_handler)(struct pt_regs *regs); -DEFINE_IDTENTRY_SYSVEC(sysvec_hyperv_callback) +DEFINE_IDTENTRY_SYSVEC_PIPELINED(HYPERVISOR_CALLBACK_VECTOR, + sysvec_hyperv_callback) { struct pt_regs *old_regs = set_irq_regs(regs); @@ -144,7 +145,8 @@ void hv_remove_vmbus_handler(void) * Routines to do per-architecture handling of stimer0 * interrupts when in Direct Mode */ -DEFINE_IDTENTRY_SYSVEC(sysvec_hyperv_stimer0) +DEFINE_IDTENTRY_SYSVEC_PIPELINED(HYPERV_STIMER0_VECTOR, + sysvec_hyperv_stimer0) { struct pt_regs *old_regs = set_irq_regs(regs); @@ -595,7 +597,7 @@ static void __init ms_hyperv_init_platform(void) x86_platform.apic_post_init = hyperv_init; hyperv_setup_mmu_ops(); /* Setup the IDT for hypervisor callback */ - alloc_intr_gate(HYPERVISOR_CALLBACK_VECTOR, asm_sysvec_hyperv_callback); + sysvec_install(HYPERVISOR_CALLBACK_VECTOR, sysvec_hyperv_callback); /* Setup the IDT for reenlightenment notifications */ if (ms_hyperv.features & HV_ACCESS_REENLIGHTENMENT) { diff --git a/arch/x86/kernel/cpu/mtrr/generic.c b/arch/x86/kernel/cpu/mtrr/generic.c index 2d6aa5d2e..6c866799a 100644 --- a/arch/x86/kernel/cpu/mtrr/generic.c +++ b/arch/x86/kernel/cpu/mtrr/generic.c @@ -953,10 +953,15 @@ void mtrr_enable(void) void mtrr_generic_set_state(void) { unsigned long mask, count; + unsigned long flags; + + flags = hard_local_irq_save(); /* Actually set the state */ mask = set_mtrr_state(); + hard_local_irq_restore(flags); + /* Use the atomic bitops to update the global mask */ for (count = 0; count < sizeof(mask) * 8; ++count) { if (mask & 0x01) @@ -983,7 +988,7 @@ static void generic_set_mtrr(unsigned int reg, unsigned long base, vr = &mtrr_state.var_ranges[reg]; - local_irq_save(flags); + flags = hard_local_irq_save(); cache_disable(); if (size == 0) { @@ -1004,7 +1009,7 @@ static void generic_set_mtrr(unsigned int reg, unsigned long base, } cache_enable(); - local_irq_restore(flags); + hard_local_irq_restore(flags); } int generic_validate_add_page(unsigned long base, unsigned long size, diff --git a/arch/x86/kernel/dumpstack.c b/arch/x86/kernel/dumpstack.c index f18ca44c9..1f9d0abf7 100644 --- a/arch/x86/kernel/dumpstack.c +++ b/arch/x86/kernel/dumpstack.c @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -338,7 +339,7 @@ unsigned long oops_begin(void) oops_enter(); /* racy, but better than risking deadlock. */ - raw_local_irq_save(flags); + flags = hard_local_irq_save(); cpu = smp_processor_id(); if (!arch_spin_trylock(&die_lock)) { if (cpu == die_owner) @@ -368,7 +369,7 @@ void oops_end(unsigned long flags, struct pt_regs *regs, int signr) if (!die_nest_count) /* Nest count reaches zero, release the lock. */ arch_spin_unlock(&die_lock); - raw_local_irq_restore(flags); + hard_local_irq_restore(flags); oops_exit(); /* Executive summary in case the oops scrolled away */ @@ -397,6 +398,8 @@ static void __die_header(const char *str, struct pt_regs *regs, long err) { const char *pr = ""; + irq_pipeline_oops(); + /* Save the regs of the first oops for the executive summary later. */ if (!die_counter) exec_summary_regs = *regs; @@ -405,13 +408,14 @@ static void __die_header(const char *str, struct pt_regs *regs, long err) pr = IS_ENABLED(CONFIG_PREEMPT_RT) ? " PREEMPT_RT" : " PREEMPT"; printk(KERN_DEFAULT - "%s: %04lx [#%d]%s%s%s%s%s\n", str, err & 0xffff, ++die_counter, + "%s: %04lx [#%d]%s%s%s%s%s%s\n", str, err & 0xffff, ++die_counter, pr, IS_ENABLED(CONFIG_SMP) ? " SMP" : "", debug_pagealloc_enabled() ? " DEBUG_PAGEALLOC" : "", IS_ENABLED(CONFIG_KASAN) ? " KASAN" : "", IS_ENABLED(CONFIG_PAGE_TABLE_ISOLATION) ? - (boot_cpu_has(X86_FEATURE_PTI) ? " PTI" : " NOPTI") : ""); + (boot_cpu_has(X86_FEATURE_PTI) ? " PTI" : " NOPTI") : "", + irqs_pipelined() ? " IRQ_PIPELINE" : ""); } NOKPROBE_SYMBOL(__die_header); diff --git a/arch/x86/kernel/fpu/core.c b/arch/x86/kernel/fpu/core.c index 4b414b0ab..553ae3358 100644 --- a/arch/x86/kernel/fpu/core.c +++ b/arch/x86/kernel/fpu/core.c @@ -19,6 +19,7 @@ #include #include #include +#include #include "context.h" #include "internal.h" @@ -57,6 +58,9 @@ DEFINE_PER_CPU(struct fpu *, fpu_fpregs_owner_ctx); */ bool irq_fpu_usable(void) { + if (running_oob()) + return false; + if (WARN_ON_ONCE(in_nmi())) return false; @@ -294,11 +298,13 @@ EXPORT_SYMBOL_GPL(fpu_enable_guest_xfd_features); #ifdef CONFIG_X86_64 void fpu_update_guest_xfd(struct fpu_guest *guest_fpu, u64 xfd) { - fpregs_lock(); + unsigned long flags; + + flags = fpregs_lock(); guest_fpu->fpstate->xfd = xfd; if (guest_fpu->fpstate->in_use) xfd_update_state(guest_fpu->fpstate); - fpregs_unlock(); + fpregs_unlock(flags); } EXPORT_SYMBOL_GPL(fpu_update_guest_xfd); @@ -332,8 +338,9 @@ int fpu_swap_kvm_fpstate(struct fpu_guest *guest_fpu, bool enter_guest) struct fpstate *guest_fps = guest_fpu->fpstate; struct fpu *fpu = ¤t->thread.fpu; struct fpstate *cur_fps = fpu->fpstate; + unsigned long flags; - fpregs_lock(); + flags = fpregs_lock(); if (!cur_fps->is_confidential && !test_thread_flag(TIF_NEED_FPU_LOAD)) save_fpregs_to_fpstate(fpu); @@ -363,7 +370,7 @@ int fpu_swap_kvm_fpstate(struct fpu_guest *guest_fpu, bool enter_guest) } fpregs_mark_activate(); - fpregs_unlock(); + fpregs_unlock(flags); return 0; } EXPORT_SYMBOL_GPL(fpu_swap_kvm_fpstate); @@ -420,11 +427,15 @@ EXPORT_SYMBOL_GPL(fpu_copy_uabi_to_guest_fpstate); void kernel_fpu_begin_mask(unsigned int kfpu_mask) { + unsigned long flags; + preempt_disable(); WARN_ON_FPU(!irq_fpu_usable()); WARN_ON_FPU(this_cpu_read(in_kernel_fpu)); + flags = hard_cond_local_irq_save(); + this_cpu_write(in_kernel_fpu, true); if (!(current->flags & (PF_KTHREAD | PF_USER_WORKER)) && @@ -440,6 +451,8 @@ void kernel_fpu_begin_mask(unsigned int kfpu_mask) if (unlikely(kfpu_mask & KFPU_387) && boot_cpu_has(X86_FEATURE_FPU)) asm volatile ("fninit"); + + hard_cond_local_irq_restore(flags); } EXPORT_SYMBOL_GPL(kernel_fpu_begin_mask); @@ -458,16 +471,18 @@ EXPORT_SYMBOL_GPL(kernel_fpu_end); */ void fpu_sync_fpstate(struct fpu *fpu) { + unsigned long flags; + WARN_ON_FPU(fpu != ¤t->thread.fpu); - fpregs_lock(); + flags = fpregs_lock(); trace_x86_fpu_before_save(fpu); if (!test_thread_flag(TIF_NEED_FPU_LOAD)) save_fpregs_to_fpstate(fpu); trace_x86_fpu_after_save(fpu); - fpregs_unlock(); + fpregs_unlock(flags); } static inline unsigned int init_fpstate_copy_size(void) @@ -586,6 +601,7 @@ int fpu_clone(struct task_struct *dst, unsigned long clone_flags, bool minimal, { struct fpu *src_fpu = ¤t->thread.fpu; struct fpu *dst_fpu = &dst->thread.fpu; + unsigned long flags; /* The new task's FPU state cannot be valid in the hardware. */ dst_fpu->last_cpu = -1; @@ -627,11 +643,16 @@ int fpu_clone(struct task_struct *dst, unsigned long clone_flags, bool minimal, * Do not use memcpy() when TIF_NEED_FPU_LOAD is set because * copying is not valid when current uses non-default states. */ - fpregs_lock(); + flags = fpregs_lock(); if (test_thread_flag(TIF_NEED_FPU_LOAD)) fpregs_restore_userregs(); save_fpregs_to_fpstate(dst_fpu); - fpregs_unlock(); + fpregs_unlock(flags); + /* + * Dovetail: this is ok to access the current fpu perm bits of + * current for reading only, even in case of preemption by an + * oob thread. + */ if (!(clone_flags & CLONE_THREAD)) fpu_inherit_perms(dst_fpu); @@ -675,7 +696,9 @@ void fpu_thread_struct_whitelist(unsigned long *offset, unsigned long *size) */ void fpu__drop(struct fpu *fpu) { - preempt_disable(); + unsigned long flags; + + flags = hard_preempt_disable(); if (fpu == ¤t->thread.fpu) { /* Ignore delayed exceptions from user space */ @@ -687,7 +710,7 @@ void fpu__drop(struct fpu *fpu) trace_x86_fpu_dropped(fpu); - preempt_enable(); + hard_preempt_enable(flags); } /* @@ -712,8 +735,9 @@ static inline void restore_fpregs_from_init_fpstate(u64 features_mask) static void fpu_reset_fpregs(void) { struct fpu *fpu = ¤t->thread.fpu; + unsigned long flags; - fpregs_lock(); + flags = fpregs_lock(); __fpu_invalidate_fpregs_state(fpu); /* * This does not change the actual hardware registers. It just @@ -730,7 +754,7 @@ static void fpu_reset_fpregs(void) */ memcpy(&fpu->fpstate->regs, &init_fpstate.regs, init_fpstate_copy_size()); set_thread_flag(TIF_NEED_FPU_LOAD); - fpregs_unlock(); + fpregs_unlock(flags); } /* @@ -740,12 +764,14 @@ static void fpu_reset_fpregs(void) */ void fpu__clear_user_states(struct fpu *fpu) { + unsigned long flags; + WARN_ON_FPU(fpu != ¤t->thread.fpu); - fpregs_lock(); + flags = fpregs_lock(); if (!cpu_feature_enabled(X86_FEATURE_FPU)) { fpu_reset_fpregs(); - fpregs_unlock(); + fpregs_unlock(flags); return; } @@ -768,7 +794,7 @@ void fpu__clear_user_states(struct fpu *fpu) * current's FPU is marked active. */ fpregs_mark_activate(); - fpregs_unlock(); + fpregs_unlock(flags); } void fpu_flush_thread(void) @@ -781,15 +807,21 @@ void fpu_flush_thread(void) */ void switch_fpu_return(void) { + unsigned long flags; + if (!static_cpu_has(X86_FEATURE_FPU)) return; + flags = hard_cond_local_irq_save(); fpregs_restore_userregs(); + hard_cond_local_irq_restore(flags); } EXPORT_SYMBOL_GPL(switch_fpu_return); -void fpregs_lock_and_load(void) +unsigned long fpregs_lock_and_load(void) { + unsigned long flags; + /* * fpregs_lock() only disables preemption (mostly). So modifying state * in an interrupt could screw up some in progress fpregs operation. @@ -798,12 +830,14 @@ void fpregs_lock_and_load(void) WARN_ON_ONCE(!irq_fpu_usable()); WARN_ON_ONCE(current->flags & PF_KTHREAD); - fpregs_lock(); + flags = fpregs_lock(); fpregs_assert_state_consistent(); if (test_thread_flag(TIF_NEED_FPU_LOAD)) fpregs_restore_userregs(); + + return flags; } #ifdef CONFIG_X86_DEBUG_FPU @@ -915,3 +949,88 @@ noinstr void fpu_idle_fpregs(void) __this_cpu_write(fpu_fpregs_owner_ctx, NULL); } } + +#ifdef CONFIG_DOVETAIL + +/* + * Holds the in-kernel fpu state when preempted by a task running on + * the out-of-band stage. + */ +static DEFINE_PER_CPU(struct fpu *, in_kernel_fpstate); + +static int fpu__init_kernel_fpstate(unsigned int cpu) +{ + struct fpu *fpu; + int fpu_size; + + fpu_size = sizeof(current->thread.fpu); + fpu_size -= sizeof(current->thread.fpu.__fpstate.regs); + fpu_size += fpu_kernel_cfg.default_size; + + /* + * We need to save kernel fpu states exclusively (statically + * sized). See fpu__suspend_inband(). + */ + fpu = kzalloc(fpu_size, GFP_KERNEL); + if (fpu == NULL) + return -ENOMEM; + + fpu->last_cpu = -1; + fpstate_reset(fpu); + this_cpu_write(in_kernel_fpstate, fpu); + memcpy(&fpu->fpstate->regs, &init_fpstate.regs, + init_fpstate_copy_size()); + + return 0; +} + +static int fpu__drop_kernel_fpstate(unsigned int cpu) +{ + struct fpu *fpu = this_cpu_read(in_kernel_fpstate); + + kfree(fpu); + + return 0; +} + +void fpu__suspend_inband(void) +{ + struct fpu *kfpu = this_cpu_read(in_kernel_fpstate); + struct task_struct *tsk = current; + + /* + * If in_kernel_fpu is set, we are dealing with the preemption + * of an inband kernel context currently using the fpu by a + * thread which resumes on the oob stage. + */ + if (this_cpu_read(in_kernel_fpu)) { + save_fpregs_to_fpstate(kfpu); + __cpu_invalidate_fpregs_state(); + oob_fpu_set_preempt(&tsk->thread.fpu); + } +} + +void fpu__resume_inband(void) +{ + struct fpu *kfpu = this_cpu_read(in_kernel_fpstate); + struct task_struct *tsk = current; + + if (oob_fpu_preempted(&tsk->thread.fpu)) { + restore_fpregs_from_fpstate(kfpu->fpstate, XFEATURE_MASK_FPSTATE); + __cpu_invalidate_fpregs_state(); + oob_fpu_clear_preempt(&tsk->thread.fpu); + } else if (!(tsk->flags & PF_KTHREAD) && + test_thread_flag(TIF_NEED_FPU_LOAD)) + switch_fpu_return(); +} + +static int __init fpu__init_dovetail(void) +{ + cpuhp_setup_state(CPUHP_AP_ONLINE_DYN, + "platform/x86/dovetail:online", + fpu__init_kernel_fpstate, fpu__drop_kernel_fpstate); + return 0; +} +core_initcall(fpu__init_dovetail); + +#endif diff --git a/arch/x86/kernel/fpu/signal.c b/arch/x86/kernel/fpu/signal.c index 2b3b9e140..e3c29f747 100644 --- a/arch/x86/kernel/fpu/signal.c +++ b/arch/x86/kernel/fpu/signal.c @@ -68,15 +68,17 @@ static inline bool check_xstate_in_sigframe(struct fxregs_state __user *fxbuf, */ static inline bool save_fsave_header(struct task_struct *tsk, void __user *buf) { + unsigned long flags; + if (use_fxsr()) { struct xregs_state *xsave = &tsk->thread.fpu.fpstate->regs.xsave; struct user_i387_ia32_struct env; struct _fpstate_32 __user *fp = buf; - fpregs_lock(); + flags = fpregs_lock(); if (!test_thread_flag(TIF_NEED_FPU_LOAD)) fxsave(&tsk->thread.fpu.fpstate->regs.fxsave); - fpregs_unlock(); + fpregs_unlock(flags); convert_from_fxsr(&env, tsk); @@ -190,6 +192,7 @@ bool copy_fpstate_to_sigframe(void __user *buf, void __user *buf_fx, int size, u struct task_struct *tsk = current; struct fpstate *fpstate = tsk->thread.fpu.fpstate; bool ia32_fxstate = (buf != buf_fx); + unsigned long flags; int ret; ia32_fxstate &= (IS_ENABLED(CONFIG_X86_32) || @@ -277,12 +280,13 @@ static int __restore_fpregs_from_user(void __user *buf, u64 ufeatures, static bool restore_fpregs_from_user(void __user *buf, u64 xrestore, bool fx_only) { struct fpu *fpu = ¤t->thread.fpu; + unsigned long flags; int ret; /* Restore enabled features only. */ xrestore &= fpu->fpstate->user_xfeatures; retry: - fpregs_lock(); + flags = fpregs_lock(); /* Ensure that XFD is up to date */ xfd_update_state(fpu->fpstate); pagefault_disable(); @@ -304,7 +308,7 @@ static bool restore_fpregs_from_user(void __user *buf, u64 xrestore, bool fx_onl */ if (test_thread_flag(TIF_NEED_FPU_LOAD)) __cpu_invalidate_fpregs_state(); - fpregs_unlock(); + fpregs_unlock(flags); /* Try to handle #PF, but anything else is fatal. */ if (ret != X86_TRAP_PF) @@ -328,7 +332,7 @@ static bool restore_fpregs_from_user(void __user *buf, u64 xrestore, bool fx_onl os_xrstor_supervisor(fpu->fpstate); fpregs_mark_activate(); - fpregs_unlock(); + fpregs_unlock(flags); return true; } @@ -341,6 +345,7 @@ static bool __fpu_restore_sig(void __user *buf, void __user *buf_fx, bool success, fx_only = false; union fpregs_state *fpregs; u64 user_xfeatures = 0; + unsigned long flags; if (use_xsave()) { struct _fpx_sw_bytes fx_sw_user; @@ -373,7 +378,7 @@ static bool __fpu_restore_sig(void __user *buf, void __user *buf_fx, * to be loaded again on return to userland (overriding last_cpu avoids * the optimisation). */ - fpregs_lock(); + flags = fpregs_lock(); if (!test_thread_flag(TIF_NEED_FPU_LOAD)) { /* * If supervisor states are available then save the @@ -389,7 +394,7 @@ static bool __fpu_restore_sig(void __user *buf, void __user *buf_fx, } __fpu_invalidate_fpregs_state(fpu); __cpu_invalidate_fpregs_state(); - fpregs_unlock(); + fpregs_unlock(flags); fpregs = &fpu->fpstate->regs; if (use_xsave() && !fx_only) { @@ -417,7 +422,7 @@ static bool __fpu_restore_sig(void __user *buf, void __user *buf_fx, /* Fold the legacy FP storage */ convert_to_fxsr(&fpregs->fxsave, &env); - fpregs_lock(); + flags = fpregs_lock(); if (use_xsave()) { /* * Remove all UABI feature bits not set in user_xfeatures @@ -440,7 +445,7 @@ static bool __fpu_restore_sig(void __user *buf, void __user *buf_fx, if (likely(success)) fpregs_mark_activate(); - fpregs_unlock(); + fpregs_unlock(flags); return success; } diff --git a/arch/x86/kernel/fpu/xstate.c b/arch/x86/kernel/fpu/xstate.c index 255ff8f6c..366ca6138 100644 --- a/arch/x86/kernel/fpu/xstate.c +++ b/arch/x86/kernel/fpu/xstate.c @@ -1005,6 +1005,7 @@ int arch_set_user_pkey_access(struct task_struct *tsk, int pkey, unsigned long init_val) { u32 old_pkru, new_pkru_bits = 0; + unsigned long flags; int pkey_shift; /* @@ -1032,6 +1033,8 @@ int arch_set_user_pkey_access(struct task_struct *tsk, int pkey, pkey_shift = pkey * PKRU_BITS_PER_PKEY; new_pkru_bits <<= pkey_shift; + flags = hard_cond_local_irq_save(); + /* Get old PKRU and mask off any old bits in place: */ old_pkru = read_pkru(); old_pkru &= ~((PKRU_AD_BIT|PKRU_WD_BIT) << pkey_shift); @@ -1039,6 +1042,8 @@ int arch_set_user_pkey_access(struct task_struct *tsk, int pkey, /* Write old part along with new part: */ write_pkru(old_pkru | new_pkru_bits); + hard_cond_local_irq_restore(flags); + return 0; } #endif /* ! CONFIG_ARCH_HAS_PKEYS */ @@ -1506,6 +1511,7 @@ static int fpstate_realloc(u64 xfeatures, unsigned int ksize, struct fpstate *curfps, *newfps = NULL; unsigned int fpsize; bool in_use; + unsigned long flags; fpsize = ksize + ALIGN(offsetof(struct fpstate, regs), 64); @@ -1533,7 +1539,7 @@ static int fpstate_realloc(u64 xfeatures, unsigned int ksize, guest_fpu->uabi_size = usize; } - fpregs_lock(); + flags = fpregs_lock(); /* * If @curfps is in use, ensure that the current state is in the * registers before swapping fpstate as that might invalidate it @@ -1560,7 +1566,7 @@ static int fpstate_realloc(u64 xfeatures, unsigned int ksize, if (in_use) xfd_update_state(fpu->fpstate); - fpregs_unlock(); + fpregs_unlock(flags); /* Only free valloc'ed state */ if (curfps && curfps->is_valloc) diff --git a/arch/x86/kernel/hpet.c b/arch/x86/kernel/hpet.c index 046bc9d57..1572b1a06 100644 --- a/arch/x86/kernel/hpet.c +++ b/arch/x86/kernel/hpet.c @@ -407,7 +407,7 @@ static void hpet_init_clockevent(struct hpet_channel *hc, unsigned int rating) evt->set_next_event = hpet_clkevt_set_next_event; evt->set_state_shutdown = hpet_clkevt_set_state_shutdown; - evt->features = CLOCK_EVT_FEAT_ONESHOT; + evt->features = CLOCK_EVT_FEAT_ONESHOT|CLOCK_EVT_FEAT_PIPELINE; if (hc->boot_cfg & HPET_TN_PERIODIC) { evt->features |= CLOCK_EVT_FEAT_PERIODIC; evt->set_state_periodic = hpet_clkevt_set_state_periodic; @@ -509,7 +509,9 @@ static struct irq_chip hpet_msi_controller __ro_after_init = { .irq_set_affinity = msi_domain_set_affinity, .irq_retrigger = irq_chip_retrigger_hierarchy, .irq_write_msi_msg = hpet_msi_write_msg, - .flags = IRQCHIP_SKIP_SET_WAKE | IRQCHIP_AFFINITY_PRE_STARTUP, + .flags = IRQCHIP_SKIP_SET_WAKE | + IRQCHIP_AFFINITY_PRE_STARTUP | + IRQCHIP_PIPELINE_SAFE, }; static int hpet_msi_init(struct irq_domain *domain, @@ -629,7 +631,7 @@ static irqreturn_t hpet_msi_interrupt_handler(int irq, void *data) return IRQ_HANDLED; } - evt->event_handler(evt); + clockevents_handle_event(evt); return IRQ_HANDLED; } @@ -812,7 +814,7 @@ static u64 read_hpet(struct clocksource *cs) if (arch_spin_is_locked(&old.lock)) goto contended; - local_irq_save(flags); + flags = hard_local_irq_save(); if (arch_spin_trylock(&hpet.lock)) { new.value = hpet_readl(HPET_COUNTER); /* @@ -820,10 +822,10 @@ static u64 read_hpet(struct clocksource *cs) */ WRITE_ONCE(hpet.value, new.value); arch_spin_unlock(&hpet.lock); - local_irq_restore(flags); + hard_local_irq_restore(flags); return (u64)new.value; } - local_irq_restore(flags); + hard_local_irq_restore(flags); contended: /* diff --git a/arch/x86/kernel/i8259.c b/arch/x86/kernel/i8259.c index c20d1832c..890ede954 100644 --- a/arch/x86/kernel/i8259.c +++ b/arch/x86/kernel/i8259.c @@ -34,7 +34,7 @@ static void init_8259A(int auto_eoi); static bool pcat_compat __ro_after_init; static int i8259A_auto_eoi; -DEFINE_RAW_SPINLOCK(i8259A_lock); +DEFINE_HARD_SPINLOCK(i8259A_lock); /* * 8259A PIC functions to handle ISA devices: @@ -229,6 +229,7 @@ struct irq_chip i8259A_chip = { .irq_disable = disable_8259A_irq, .irq_unmask = enable_8259A_irq, .irq_mask_ack = mask_and_ack_8259A, + .flags = IRQCHIP_PIPELINE_SAFE, }; static char irq_trigger[2]; diff --git a/arch/x86/kernel/idt.c b/arch/x86/kernel/idt.c index fc77a9604..6ae90fb10 100644 --- a/arch/x86/kernel/idt.c +++ b/arch/x86/kernel/idt.c @@ -132,6 +132,11 @@ static const __initconst struct idt_data apic_idts[] = { INTG(CALL_FUNCTION_VECTOR, asm_sysvec_call_function), INTG(CALL_FUNCTION_SINGLE_VECTOR, asm_sysvec_call_function_single), INTG(REBOOT_VECTOR, asm_sysvec_reboot), +#ifdef CONFIG_IRQ_PIPELINE + INTG(TIMER_OOB_VECTOR, asm_sysvec_timer_oob_ipi), + INTG(RESCHEDULE_OOB_VECTOR, asm_sysvec_reschedule_oob_ipi), + INTG(CALL_FUNCTION_OOB_VECTOR, asm_sysvec_call_function_oob_ipi), +#endif #endif #ifdef CONFIG_X86_THERMAL_VECTOR diff --git a/arch/x86/kernel/irq.c b/arch/x86/kernel/irq.c index 11761c124..8849279d2 100644 --- a/arch/x86/kernel/irq.c +++ b/arch/x86/kernel/irq.c @@ -4,6 +4,7 @@ */ #include #include +#include #include #include #include @@ -49,7 +50,7 @@ void ack_bad_irq(unsigned int irq) * completely. * But only ack when the APIC is enabled -AK */ - apic_eoi(); + __apic_eoi(); } #define irq_stats(x) (&per_cpu(irq_stat, x)) @@ -243,8 +244,11 @@ static __always_inline void handle_irq(struct irq_desc *desc, /* * common_interrupt() handles all normal device IRQ's (the special SMP * cross-CPU interrupts have their own entry points). + * + * Compiled out if CONFIG_IRQ_PIPELINE is enabled, replaced by + * arch_handle_irq(). */ -DEFINE_IDTENTRY_IRQ(common_interrupt) +DEFINE_IDTENTRY_IRQ_PIPELINED(common_interrupt) { struct pt_regs *old_regs = set_irq_regs(regs); struct irq_desc *desc; @@ -276,7 +280,8 @@ void (*x86_platform_ipi_callback)(void) = NULL; /* * Handler for X86_PLATFORM_IPI_VECTOR. */ -DEFINE_IDTENTRY_SYSVEC(sysvec_x86_platform_ipi) +DEFINE_IDTENTRY_SYSVEC_PIPELINED(X86_PLATFORM_IPI_VECTOR, + sysvec_x86_platform_ipi) { struct pt_regs *old_regs = set_irq_regs(regs); @@ -308,7 +313,8 @@ EXPORT_SYMBOL_GPL(kvm_set_posted_intr_wakeup_handler); /* * Handler for POSTED_INTERRUPT_VECTOR. */ -DEFINE_IDTENTRY_SYSVEC_SIMPLE(sysvec_kvm_posted_intr_ipi) +DEFINE_IDTENTRY_SYSVEC_SIMPLE_PIPELINED(POSTED_INTR_VECTOR, + sysvec_kvm_posted_intr_ipi) { apic_eoi(); inc_irq_stat(kvm_posted_intr_ipis); @@ -317,7 +323,8 @@ DEFINE_IDTENTRY_SYSVEC_SIMPLE(sysvec_kvm_posted_intr_ipi) /* * Handler for POSTED_INTERRUPT_WAKEUP_VECTOR. */ -DEFINE_IDTENTRY_SYSVEC(sysvec_kvm_posted_intr_wakeup_ipi) +DEFINE_IDTENTRY_SYSVEC_PIPELINED(POSTED_INTR_WAKEUP_VECTOR, + sysvec_kvm_posted_intr_wakeup_ipi) { apic_eoi(); inc_irq_stat(kvm_posted_intr_wakeup_ipis); @@ -327,7 +334,8 @@ DEFINE_IDTENTRY_SYSVEC(sysvec_kvm_posted_intr_wakeup_ipi) /* * Handler for POSTED_INTERRUPT_NESTED_VECTOR. */ -DEFINE_IDTENTRY_SYSVEC_SIMPLE(sysvec_kvm_posted_intr_nested_ipi) +DEFINE_IDTENTRY_SYSVEC_SIMPLE_PIPELINED(POSTED_INTR_NESTED_VECTOR, + sysvec_kvm_posted_intr_nested_ipi) { apic_eoi(); inc_irq_stat(kvm_posted_intr_nested_ipis); @@ -401,6 +409,6 @@ DEFINE_IDTENTRY_SYSVEC(sysvec_thermal) inc_irq_stat(irq_thermal_count); smp_thermal_vector(); trace_thermal_apic_exit(THERMAL_APIC_VECTOR); - apic_eoi(); + __apic_eoi(); } #endif diff --git a/arch/x86/kernel/irq_pipeline.c b/arch/x86/kernel/irq_pipeline.c new file mode 100644 index 000000000..095fd2e15 --- /dev/null +++ b/arch/x86/kernel/irq_pipeline.c @@ -0,0 +1,362 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2019 Philippe Gerum . + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +void (*pipeline_hv_callback_fn)(struct pt_regs *regs) = NULL; + +static struct irq_domain *sipic_domain; + +static void sipic_irq_noop(struct irq_data *data) { } + +static unsigned int sipic_irq_noop_ret(struct irq_data *data) +{ + return 0; +} + +static struct irq_chip sipic_chip = { + .name = "SIPIC", + .irq_startup = sipic_irq_noop_ret, + .irq_shutdown = sipic_irq_noop, + .irq_enable = sipic_irq_noop, + .irq_disable = sipic_irq_noop, + .flags = IRQCHIP_PIPELINE_SAFE | IRQCHIP_SKIP_SET_WAKE, +}; + +void handle_apic_irq(struct irq_desc *desc) +{ + if (WARN_ON_ONCE(irq_pipeline_debug() && !on_pipeline_entry())) + return; + + /* + * MCE events are non-maskable therefore their in-band + * handlers have to be oob-compatible by construction. Those + * handlers run immediately out of the IDT for this reason as + * well. We won't see them here since they are not routed via + * arch_handle_irq() -> generic_pipeline_irq_desc(). + * + * All we need to do at this stage is to acknowledge other + * APIC events, then pipeline the corresponding interrupt from + * our synthetic controller chip (SIPIC). + */ + __apic_eoi(); + + handle_oob_irq(desc); +} + +static irqentry_state_t pipeline_enter_rcu(void) +{ + irqentry_state_t state = { + .exit_rcu = false, + .stage_info = IRQENTRY_INBAND_UNSTALLED, + }; + + if (!IS_ENABLED(CONFIG_TINY_RCU) && is_idle_task(current)) { + ct_irq_enter(); + state.exit_rcu = true; + } else { + rcu_irq_enter_check_tick(); + } + + return state; +} + +static void pipeline_exit_rcu(irqentry_state_t state) +{ + if (state.exit_rcu) + ct_irq_exit(); +} + +static void pipeline_hv_callback(struct pt_regs *regs) +{ + pipeline_hv_callback_fn(regs); +} + +static void do_sysvec_inband(struct irq_desc *desc, struct pt_regs *regs) +{ + unsigned int irq = irq_desc_get_irq(desc); + int vector = apicm_irq_vector(irq); + + /* + * This code only sees pipelined sysvec events tagged with + * DEFINE_IDTENTRY_SYSVEC_PIPELINED: + * + * arch_handle_irq(irq) + * generic_pipeline_irq_desc(desc) + * handle_apic_irq(irq) + * handle_oob_irq(irq) + * [...irq_post_inband...] + * + * arch_do_IRQ_pipelined(desc) + * do_sysvec_inband(desc) + * + * | + * v + * sysvec_handler(regs) + * + * System vectors which are still tagged as + * DEFINE_IDTENTRY_SYSVEC/DEFINE_IDTENTRY_SYSVEC_SIMPLE are + * directly dispatched out of the IDT, assuming their handler + * is oob-safe (like NMI handlers) therefore never reach this + * in-band stage handler. + * + * NOTE: we expand run_sysvec_on_irqstack_cond() each time, + * which is ugly. But the irqstack code makes assumptions we + * don't want to break. + */ + + irq_clear_deferral(desc); + + switch (vector) { +#ifdef CONFIG_SMP + case RESCHEDULE_VECTOR: + run_sysvec_on_irqstack_cond(__sysvec_reschedule_ipi, + regs); + break; + case CALL_FUNCTION_VECTOR: + run_sysvec_on_irqstack_cond(__sysvec_call_function, + regs); + break; + case CALL_FUNCTION_SINGLE_VECTOR: + run_sysvec_on_irqstack_cond(__sysvec_call_function_single, + regs); + break; + case REBOOT_VECTOR: + run_sysvec_on_irqstack_cond(__sysvec_reboot, regs); + break; +#endif + case X86_PLATFORM_IPI_VECTOR: + run_sysvec_on_irqstack_cond(__sysvec_x86_platform_ipi, + regs); + break; + case IRQ_WORK_VECTOR: + run_sysvec_on_irqstack_cond(__sysvec_irq_work, regs); + break; +#ifdef CONFIG_HAVE_KVM + case POSTED_INTR_VECTOR: + run_sysvec_on_irqstack_cond(__sysvec_kvm_posted_intr_ipi, + regs); + break; + case POSTED_INTR_WAKEUP_VECTOR: + run_sysvec_on_irqstack_cond(__sysvec_kvm_posted_intr_wakeup_ipi, + regs); + break; + case POSTED_INTR_NESTED_VECTOR: + run_sysvec_on_irqstack_cond(__sysvec_kvm_posted_intr_nested_ipi, + regs); + break; +#endif + case HYPERVISOR_CALLBACK_VECTOR: + run_sysvec_on_irqstack_cond(pipeline_hv_callback, regs); + break; + case LOCAL_TIMER_VECTOR: + run_sysvec_on_irqstack_cond(__sysvec_apic_timer_interrupt, + regs); + break; + default: + printk_once(KERN_ERR "irq_pipeline: unexpected event" + " on vector #%.2x (irq=%u)", vector, irq); + return; + } +} + +static void do_irq_inband(struct pt_regs *regs, u32 irq) +{ + struct irq_desc *desc = irq_to_desc(irq); + + desc->handle_irq(desc); +} + +void arch_do_IRQ_pipelined(struct irq_desc *desc) +{ + struct pt_regs *regs = raw_cpu_ptr(&irq_pipeline.tick_regs), *old_regs; + irqentry_state_t state; + + /* Emulate a kernel entry. */ + state = pipeline_enter_rcu(); + + if (desc->irq_data.domain == sipic_domain) { + do_sysvec_inband(desc, regs); + } else { + /* + * XXX: the following is ugly, but the irqstack + * switching code is not that flexible. However, we + * don't want to provide a separate implementation of + * the latter in the pipelined case, so let's get + * along with it. + */ + u32 vector = irq_desc_get_irq(desc); /* irq carried as 'vector' */ + old_regs = set_irq_regs(regs); + run_irq_on_irqstack_cond(do_irq_inband, regs, vector); + set_irq_regs(old_regs); + } + + pipeline_exit_rcu(state); +} + +void arch_handle_irq(struct pt_regs *regs, u8 vector, bool irq_movable) +{ + struct pt_regs *old_regs = set_irq_regs(regs); + struct irq_desc *desc; + unsigned int irq; + + if (vector >= FIRST_SYSTEM_VECTOR) { + irq = apicm_vector_irq(vector); + desc = irq_to_desc(irq); + } else { + desc = __this_cpu_read(vector_irq[vector]); + if (unlikely(IS_ERR_OR_NULL(desc))) { + __apic_eoi(); + + if (desc == VECTOR_UNUSED) { + pr_emerg_ratelimited("%s: %d.%u No irq handler for vector\n", + __func__, smp_processor_id(), + vector); + } else { + __this_cpu_write(vector_irq[vector], VECTOR_UNUSED); + } + return; + } + if (irqd_is_setaffinity_pending(&desc->irq_data)) { + raw_spin_lock(&desc->lock); + if (irq_movable) + irqd_clr_move_blocked(&desc->irq_data); + else + irqd_set_move_blocked(&desc->irq_data); + raw_spin_unlock(&desc->lock); + } + } + + generic_pipeline_irq_desc(desc); + + set_irq_regs(old_regs); +} + +noinstr void arch_pipeline_entry(struct pt_regs *regs, u8 vector) +{ + struct irq_stage_data *prevd; + irqentry_state_t state; + + /* + * The tricky one: we distinguish the following cases: + * + * [1] entry from oob context, either kernel or user code was + * preempted by the IRQ, the in-band (virtual) interrupt state + * is 'undefined' (could be either stalled/unstalled, it is + * not relevant). + * + * [2] entry from in-band context while the stage is stalled, + * which means that some kernel code was preempted by the IRQ + * since in-band user code cannot run with interrupts + * (virtually) disabled. + * + * [3] entry from in-band context while the stage is + * unstalled: the common case for IRQ entry. Kernel or user + * code may have been preempted, we handle the event + * identically. + * + * [1] and [2] are processed almost the same way, except for + * one key aspect: the potential stage demotion of the + * preempted task which originally entered [1] on the oob + * stage, then left it for the in-band stage as a result of + * handling the IRQ (such demotion normally happens during + * handle_irq_pipelined_finish() if required). In this + * particular case, we want to run the common IRQ epilogue + * code before returning to user mode, so that all pending + * in-band work (_TIF_WORK_*) is carried out for the task + * which is about to exit kernel mode. + * + * If the task runs in-band at the exit point and a user mode + * context was preempted, then case [2] is excluded by + * definition so we know for sure that we just observed a + * stage demotion, therefore we have to run the work loop by + * calling irqentry_exit_to_user_mode(). + */ + if (unlikely(running_oob() || irqs_disabled())) { + instrumentation_begin(); + prevd = handle_irq_pipelined_prepare(regs); + arch_handle_irq(regs, vector, false); + kvm_set_cpu_l1tf_flush_l1d(); + handle_irq_pipelined_finish(prevd, regs); + if (running_inband() && user_mode(regs)) { + stall_inband_nocheck(); + irqentry_exit_to_user_mode(regs); + } + instrumentation_end(); + return; + } + + /* In-band on entry, accepting interrupts. */ + state = irqentry_enter(regs); + instrumentation_begin(); + /* Prep for handling, switching oob. */ + prevd = handle_irq_pipelined_prepare(regs); + arch_handle_irq(regs, vector, true); + kvm_set_cpu_l1tf_flush_l1d(); + /* irqentry_enter() stalled the in-band stage. */ + trace_hardirqs_on(); + unstall_inband_nocheck(); + handle_irq_pipelined_finish(prevd, regs); + stall_inband_nocheck(); + trace_hardirqs_off(); + instrumentation_end(); + irqentry_exit(regs, state); +} + +static int sipic_irq_map(struct irq_domain *d, unsigned int irq, + irq_hw_number_t hwirq) +{ + irq_set_percpu_devid(irq); + irq_set_chip_and_handler(irq, &sipic_chip, handle_apic_irq); + + return 0; +} + +static struct irq_domain_ops sipic_domain_ops = { + .map = sipic_irq_map, +}; + +static void create_x86_apic_domain(void) +{ + sipic_domain = irq_domain_add_simple(NULL, NR_APIC_VECTORS, + FIRST_SYSTEM_IRQ, + &sipic_domain_ops, NULL); +} + +#ifdef CONFIG_SMP + +DEFINE_IDTENTRY_SYSVEC_PIPELINED(TIMER_OOB_VECTOR, + sysvec_timer_oob_ipi) +{ /* In-band handler is unused. */ } + +DEFINE_IDTENTRY_SYSVEC_PIPELINED(RESCHEDULE_OOB_VECTOR, + sysvec_reschedule_oob_ipi) +{ /* In-band handler is unused. */ } + +DEFINE_IDTENTRY_SYSVEC_PIPELINED(CALL_FUNCTION_OOB_VECTOR, + sysvec_call_function_oob_ipi) +{ /* In-band handler is unused. */ } + +#endif /* !CONFIG_SMP */ + +void __init arch_irq_pipeline_init(void) +{ + /* + * Create an IRQ domain for mapping APIC system interrupts + * (in-band and out-of-band), with fixed sirq numbers starting + * from FIRST_SYSTEM_IRQ. Upon receipt of a system interrupt, + * the corresponding sirq is injected into the pipeline. + */ + create_x86_apic_domain(); +} diff --git a/arch/x86/kernel/irq_work.c b/arch/x86/kernel/irq_work.c index b0a24deab..48e022204 100644 --- a/arch/x86/kernel/irq_work.c +++ b/arch/x86/kernel/irq_work.c @@ -14,7 +14,8 @@ #include #ifdef CONFIG_X86_LOCAL_APIC -DEFINE_IDTENTRY_SYSVEC(sysvec_irq_work) +DEFINE_IDTENTRY_SYSVEC_PIPELINED(IRQ_WORK_VECTOR, + sysvec_irq_work) { apic_eoi(); trace_irq_work_entry(IRQ_WORK_VECTOR); diff --git a/arch/x86/kernel/kvm.c b/arch/x86/kernel/kvm.c index b8ab9ee58..16255ecb4 100644 --- a/arch/x86/kernel/kvm.c +++ b/arch/x86/kernel/kvm.c @@ -257,12 +257,15 @@ noinstr bool __kvm_handle_async_pf(struct pt_regs *regs, u32 token) { u32 flags = kvm_read_and_reset_apf_flags(); irqentry_state_t state; + unsigned long irqflags; if (!flags) return false; state = irqentry_enter(regs); + oob_trap_notify(X86_TRAP_PF, regs); instrumentation_begin(); + irqflags = hard_cond_local_irq_save(); /* * If the host managed to inject an async #PF into an interrupt @@ -281,12 +284,15 @@ noinstr bool __kvm_handle_async_pf(struct pt_regs *regs, u32 token) WARN_ONCE(1, "Unexpected async PF flags: %x\n", flags); } + hard_cond_local_irq_restore(irqflags); instrumentation_end(); + oob_trap_unwind(X86_TRAP_PF, regs); irqentry_exit(regs, state); return true; } -DEFINE_IDTENTRY_SYSVEC(sysvec_kvm_asyncpf_interrupt) +DEFINE_IDTENTRY_SYSVEC_PIPELINED(HYPERVISOR_CALLBACK_VECTOR, + sysvec_kvm_asyncpf_interrupt) { struct pt_regs *old_regs = set_irq_regs(regs); u32 token; @@ -446,6 +452,9 @@ static void __init sev_map_percpu_data(void) static void kvm_guest_cpu_offline(bool shutdown) { + unsigned long flags; + + flags = hard_cond_local_irq_save(); kvm_disable_steal_time(); if (kvm_para_has_feature(KVM_FEATURE_PV_EOI)) wrmsrl(MSR_KVM_PV_EOI_EN, 0); @@ -455,15 +464,16 @@ static void kvm_guest_cpu_offline(bool shutdown) if (!shutdown) apf_task_wake_all(); kvmclock_disable(); + hard_cond_local_irq_restore(flags); } static int kvm_cpu_online(unsigned int cpu) { unsigned long flags; - local_irq_save(flags); + local_irq_save_full(flags); kvm_guest_cpu_init(); - local_irq_restore(flags); + local_irq_restore_full(flags); return 0; } @@ -829,7 +839,7 @@ static void __init kvm_guest_init(void) if (kvm_para_has_feature(KVM_FEATURE_ASYNC_PF_INT) && kvmapf) { static_branch_enable(&kvm_async_pf_enabled); - alloc_intr_gate(HYPERVISOR_CALLBACK_VECTOR, asm_sysvec_kvm_asyncpf_interrupt); + sysvec_install(HYPERVISOR_CALLBACK_VECTOR, sysvec_kvm_asyncpf_interrupt); } #ifdef CONFIG_SMP @@ -1047,6 +1057,23 @@ static void kvm_wait(u8 *ptr, u8 val) * for irq enabled case to avoid hang when lock info is overwritten * in irq spinlock slowpath and no spurious interrupt occur to save us. */ + +#ifdef CONFIG_IRQ_PIPELINE + + if (hard_irqs_disabled()) { + if (READ_ONCE(*ptr) == val) + halt(); + } else { + hard_local_irq_disable(); + + if (READ_ONCE(*ptr) == val) + native_safe_halt(); /* enables hard IRQs */ + else + hard_local_irq_enable(); + } + +#else /* !CONFIG_IRQ_PIPELINE */ + if (irqs_disabled()) { if (READ_ONCE(*ptr) == val) halt(); @@ -1059,6 +1086,7 @@ static void kvm_wait(u8 *ptr, u8 val) else local_irq_enable(); } +#endif } /* diff --git a/arch/x86/kernel/nmi.c b/arch/x86/kernel/nmi.c index 87aee638e..7bdf645d0 100644 --- a/arch/x86/kernel/nmi.c +++ b/arch/x86/kernel/nmi.c @@ -485,6 +485,10 @@ static DEFINE_PER_CPU(enum nmi_states, nmi_state); static DEFINE_PER_CPU(unsigned long, nmi_cr2); static DEFINE_PER_CPU(unsigned long, nmi_dr7); +/* + * IRQ pipeline: fixing up the virtual IRQ state makes no sense on + * NMI. + */ DEFINE_IDTENTRY_RAW(exc_nmi) { irqentry_state_t irq_state; diff --git a/arch/x86/kernel/process.c b/arch/x86/kernel/process.c index 5351f293f..ad17dc1d5 100644 --- a/arch/x86/kernel/process.c +++ b/arch/x86/kernel/process.c @@ -665,9 +665,9 @@ void speculation_ctrl_update(unsigned long tif) unsigned long flags; /* Forced update. Make sure all relevant TIF flags are different */ - local_irq_save(flags); + flags = hard_local_irq_save(); __speculation_ctrl_update(~tif, tif); - local_irq_restore(flags); + hard_local_irq_restore(flags); } /* Called from seccomp/prctl update */ @@ -740,6 +740,7 @@ EXPORT_SYMBOL(boot_option_idle_override); void __cpuidle default_idle(void) { raw_safe_halt(); + hard_cond_local_irq_disable(); raw_local_irq_disable(); } #if defined(CONFIG_APM_MODULE) || defined(CONFIG_HALTPOLL_CPUIDLE_MODULE) @@ -796,9 +797,10 @@ struct cpumask cpus_stop_mask; void __noreturn stop_this_cpu(void *dummy) { struct cpuinfo_x86 *c = this_cpu_ptr(&cpu_info); - unsigned int cpu = smp_processor_id(); + unsigned int cpu; - local_irq_disable(); + hard_local_irq_disable(); + cpu = smp_processor_id(); /* * Remove this CPU from the online mask and disable it @@ -927,6 +929,7 @@ static __cpuidle void mwait_idle(void) __monitor((void *)¤t_thread_info()->flags, 0, 0); if (!need_resched()) { __sti_mwait(0, 0); + hard_cond_local_irq_disable(); raw_local_irq_disable(); } } diff --git a/arch/x86/kernel/process_64.c b/arch/x86/kernel/process_64.c index dd19a4db7..f96a51d4c 100644 --- a/arch/x86/kernel/process_64.c +++ b/arch/x86/kernel/process_64.c @@ -274,9 +274,9 @@ void current_save_fsgs(void) unsigned long flags; /* Interrupts need to be off for FSGSBASE */ - local_irq_save(flags); + local_irq_save_full(flags); save_fsgs(current); - local_irq_restore(flags); + local_irq_restore_full(flags); } #if IS_ENABLED(CONFIG_KVM) EXPORT_SYMBOL_GPL(current_save_fsgs); @@ -435,9 +435,9 @@ unsigned long x86_gsbase_read_cpu_inactive(void) if (boot_cpu_has(X86_FEATURE_FSGSBASE)) { unsigned long flags; - local_irq_save(flags); + local_irq_save_full(flags); gsbase = __rdgsbase_inactive(); - local_irq_restore(flags); + local_irq_restore_full(flags); } else { rdmsrl(MSR_KERNEL_GS_BASE, gsbase); } @@ -450,9 +450,9 @@ void x86_gsbase_write_cpu_inactive(unsigned long gsbase) if (boot_cpu_has(X86_FEATURE_FSGSBASE)) { unsigned long flags; - local_irq_save(flags); + local_irq_save_full(flags); __wrgsbase_inactive(gsbase); - local_irq_restore(flags); + local_irq_restore_full(flags); } else { wrmsrl(MSR_KERNEL_GS_BASE, gsbase); } @@ -565,8 +565,17 @@ __switch_to(struct task_struct *prev_p, struct task_struct *next_p) struct fpu *prev_fpu = &prev->fpu; int cpu = smp_processor_id(); + /* + * Dovetail: Switching context on the out-of-band stage is + * legit, and we may have preempted an in-band (soft)irq + * handler earlier. Since oob handlers never switch stack, + * make sure to restrict the following test to in-band + * callers. + */ WARN_ON_ONCE(IS_ENABLED(CONFIG_DEBUG_ENTRY) && - this_cpu_read(pcpu_hot.hardirq_stack_inuse)); + running_inband() && this_cpu_read(pcpu_hot.hardirq_stack_inuse)); + + WARN_ON_ONCE(dovetail_debug() && !hard_irqs_disabled()); if (!test_thread_flag(TIF_NEED_FPU_LOAD)) switch_fpu_prepare(prev_fpu, cpu); @@ -817,6 +826,7 @@ static int prctl_enable_tagged_addr(struct mm_struct *mm, unsigned long nr_bits) long do_arch_prctl_64(struct task_struct *task, int option, unsigned long arg2) { + unsigned long flags; int ret = 0; switch (option) { @@ -824,7 +834,7 @@ long do_arch_prctl_64(struct task_struct *task, int option, unsigned long arg2) if (unlikely(arg2 >= TASK_SIZE_MAX)) return -EPERM; - preempt_disable(); + flags = hard_preempt_disable(); /* * ARCH_SET_GS has always overwritten the index * and the base. Zero is the most sensible value @@ -845,7 +855,7 @@ long do_arch_prctl_64(struct task_struct *task, int option, unsigned long arg2) task->thread.gsindex = 0; x86_gsbase_write_task(task, arg2); } - preempt_enable(); + hard_preempt_enable(flags); break; } case ARCH_SET_FS: { @@ -856,7 +866,7 @@ long do_arch_prctl_64(struct task_struct *task, int option, unsigned long arg2) if (unlikely(arg2 >= TASK_SIZE_MAX)) return -EPERM; - preempt_disable(); + flags = hard_preempt_disable(); /* * Set the selector to 0 for the same reason * as %gs above. @@ -874,7 +884,7 @@ long do_arch_prctl_64(struct task_struct *task, int option, unsigned long arg2) task->thread.fsindex = 0; x86_fsbase_write_task(task, arg2); } - preempt_enable(); + hard_preempt_enable(flags); break; } case ARCH_GET_FS: { diff --git a/arch/x86/kernel/shstk.c b/arch/x86/kernel/shstk.c index 19e4db582..835dfc713 100644 --- a/arch/x86/kernel/shstk.c +++ b/arch/x86/kernel/shstk.c @@ -158,6 +158,7 @@ static int shstk_setup(void) { struct thread_shstk *shstk = ¤t->thread.shstk; unsigned long addr, size; + unsigned long flags; /* Already enabled */ if (features_enabled(ARCH_SHSTK_SHSTK)) @@ -172,10 +173,10 @@ static int shstk_setup(void) if (IS_ERR_VALUE(addr)) return PTR_ERR((void *)addr); - fpregs_lock_and_load(); + flags = fpregs_lock_and_load(); wrmsrl(MSR_IA32_PL3_SSP, addr + size); wrmsrl(MSR_IA32_U_CET, CET_SHSTK_EN); - fpregs_unlock(); + fpregs_unlock(flags); shstk->base = addr; shstk->size = size; @@ -236,12 +237,13 @@ unsigned long shstk_alloc_thread_stack(struct task_struct *tsk, unsigned long cl static unsigned long get_user_shstk_addr(void) { unsigned long long ssp; + unsigned long flags; - fpregs_lock_and_load(); + flags = fpregs_lock_and_load(); rdmsrl(MSR_IA32_PL3_SSP, ssp); - fpregs_unlock(); + fpregs_unlock(flags); return ssp; } @@ -347,6 +349,7 @@ static int shstk_pop_sigframe(unsigned long *ssp) int setup_signal_shadow_stack(struct ksignal *ksig) { void __user *restorer = ksig->ka.sa.sa_restorer; + unsigned long flags; unsigned long ssp; int err; @@ -371,15 +374,16 @@ int setup_signal_shadow_stack(struct ksignal *ksig) if (unlikely(err)) return -EFAULT; - fpregs_lock_and_load(); + flags = fpregs_lock_and_load(); wrmsrl(MSR_IA32_PL3_SSP, ssp); - fpregs_unlock(); + fpregs_unlock(flags); return 0; } int restore_signal_shadow_stack(void) { + unsigned long flags; unsigned long ssp; int err; @@ -395,9 +399,9 @@ int restore_signal_shadow_stack(void) if (unlikely(err)) return err; - fpregs_lock_and_load(); + flags = fpregs_lock_and_load(); wrmsrl(MSR_IA32_PL3_SSP, ssp); - fpregs_unlock(); + fpregs_unlock(flags); return 0; } @@ -442,6 +446,7 @@ void shstk_free(struct task_struct *tsk) static int wrss_control(bool enable) { + unsigned long flags; u64 msrval; if (!cpu_feature_enabled(X86_FEATURE_USER_SHSTK)) @@ -459,7 +464,7 @@ static int wrss_control(bool enable) if (features_enabled(ARCH_SHSTK_WRSS) == enable) return 0; - fpregs_lock_and_load(); + flags = fpregs_lock_and_load(); rdmsrl(MSR_IA32_U_CET, msrval); if (enable) { @@ -476,13 +481,15 @@ static int wrss_control(bool enable) wrmsrl(MSR_IA32_U_CET, msrval); unlock: - fpregs_unlock(); + fpregs_unlock(flags); return 0; } static int shstk_disable(void) { + unsigned long flags; + if (!cpu_feature_enabled(X86_FEATURE_USER_SHSTK)) return -EOPNOTSUPP; @@ -490,11 +497,11 @@ static int shstk_disable(void) if (!features_enabled(ARCH_SHSTK_SHSTK)) return 0; - fpregs_lock_and_load(); + flags = fpregs_lock_and_load(); /* Disable WRSS too when disabling shadow stack */ wrmsrl(MSR_IA32_U_CET, 0); wrmsrl(MSR_IA32_PL3_SSP, 0); - fpregs_unlock(); + fpregs_unlock(flags); shstk_free(current); features_clr(ARCH_SHSTK_SHSTK | ARCH_SHSTK_WRSS); diff --git a/arch/x86/kernel/smp.c b/arch/x86/kernel/smp.c index 96a771f9f..a9336e729 100644 --- a/arch/x86/kernel/smp.c +++ b/arch/x86/kernel/smp.c @@ -133,7 +133,7 @@ static int smp_stop_nmi_callback(unsigned int val, struct pt_regs *regs) /* * this function calls the 'stop' function on all other CPUs in the system. */ -DEFINE_IDTENTRY_SYSVEC(sysvec_reboot) +DEFINE_IDTENTRY_SYSVEC_PIPELINED_NORETURN(REBOOT_VECTOR, sysvec_reboot) { apic_eoi(); cpu_emergency_disable_virtualization(); @@ -225,10 +225,10 @@ static void native_stop_other_cpus(int wait) udelay(1); } - local_irq_save(flags); + flags = hard_local_irq_save(); disable_local_APIC(); mcheck_cpu_clear(this_cpu_ptr(&cpu_info)); - local_irq_restore(flags); + hard_local_irq_restore(flags); /* * Ensure that the cpus_stop_mask cache lines are invalidated on @@ -241,7 +241,8 @@ static void native_stop_other_cpus(int wait) * Reschedule call back. KVM uses this interrupt to force a cpu out of * guest mode. */ -DEFINE_IDTENTRY_SYSVEC_SIMPLE(sysvec_reschedule_ipi) +DEFINE_IDTENTRY_SYSVEC_SIMPLE_PIPELINED(RESCHEDULE_VECTOR, + sysvec_reschedule_ipi) { apic_eoi(); trace_reschedule_entry(RESCHEDULE_VECTOR); @@ -250,7 +251,8 @@ DEFINE_IDTENTRY_SYSVEC_SIMPLE(sysvec_reschedule_ipi) trace_reschedule_exit(RESCHEDULE_VECTOR); } -DEFINE_IDTENTRY_SYSVEC(sysvec_call_function) +DEFINE_IDTENTRY_SYSVEC_PIPELINED(CALL_FUNCTION_VECTOR, + sysvec_call_function) { apic_eoi(); trace_call_function_entry(CALL_FUNCTION_VECTOR); @@ -259,7 +261,8 @@ DEFINE_IDTENTRY_SYSVEC(sysvec_call_function) trace_call_function_exit(CALL_FUNCTION_VECTOR); } -DEFINE_IDTENTRY_SYSVEC(sysvec_call_function_single) +DEFINE_IDTENTRY_SYSVEC_PIPELINED(CALL_FUNCTION_SINGLE_VECTOR, + sysvec_call_function_single) { apic_eoi(); trace_call_function_single_entry(CALL_FUNCTION_SINGLE_VECTOR); @@ -268,6 +271,17 @@ DEFINE_IDTENTRY_SYSVEC(sysvec_call_function_single) trace_call_function_single_exit(CALL_FUNCTION_SINGLE_VECTOR); } +#ifdef CONFIG_IRQ_PIPELINE + +void irq_send_oob_ipi(unsigned int ipi, + const struct cpumask *cpumask) +{ + apic_send_IPI_allbutself(apicm_irq_vector(ipi)); +} +EXPORT_SYMBOL_GPL(irq_send_oob_ipi); + +#endif + static int __init nonmi_ipi_setup(char *str) { smp_no_nmi_ipi = true; diff --git a/arch/x86/kernel/smpboot.c b/arch/x86/kernel/smpboot.c index ce77dac9a..ae4e9c868 100644 --- a/arch/x86/kernel/smpboot.c +++ b/arch/x86/kernel/smpboot.c @@ -319,7 +319,7 @@ static void notrace start_secondary(void *unused) x86_platform.nmi_init(); /* enable local interrupts */ - local_irq_enable(); + local_irq_enable_full(); x86_cpuinit.setup_percpu_clockev(); @@ -1471,7 +1471,7 @@ void play_dead_common(void) cpuhp_ap_report_dead(); - local_irq_disable(); + local_irq_disable_full(); } /* diff --git a/arch/x86/kernel/time.c b/arch/x86/kernel/time.c index 52e1f3f0b..f9355478f 100644 --- a/arch/x86/kernel/time.c +++ b/arch/x86/kernel/time.c @@ -36,7 +36,7 @@ EXPORT_SYMBOL(profile_pc); */ static irqreturn_t timer_interrupt(int irq, void *dev_id) { - global_clock_event->event_handler(global_clock_event); + clockevents_handle_event(global_clock_event); return IRQ_HANDLED; } diff --git a/arch/x86/kernel/traps.c b/arch/x86/kernel/traps.c index 37b8e20c0..f8b47f05a 100644 --- a/arch/x86/kernel/traps.c +++ b/arch/x86/kernel/traps.c @@ -186,6 +186,52 @@ static void show_signal(struct task_struct *tsk, int signr, } } +static __always_inline +bool mark_trap_entry(int trapnr, struct pt_regs *regs) +{ + oob_trap_notify(trapnr, regs); + + if (likely(running_inband())) { + hard_cond_local_irq_enable(); + return true; + } + + /* + * If the oob core did not switch us inband, our caller is + * expected to leave the trap handler immediately, so we may + * notify the core about this right now. + */ + oob_trap_unwind(trapnr, regs); + + return false; +} + +static __always_inline +void mark_trap_exit(int trapnr, struct pt_regs *regs) +{ + oob_trap_unwind(trapnr, regs); + hard_cond_local_irq_disable(); +} + +static __always_inline +bool mark_trap_entry_raw(int trapnr, struct pt_regs *regs) +{ + oob_trap_notify(trapnr, regs); + + if (running_oob()) { + oob_trap_unwind(trapnr, regs); + return false; + } + + return true; +} + +static __always_inline +void mark_trap_exit_raw(int trapnr, struct pt_regs *regs) +{ + oob_trap_unwind(trapnr, regs); +} + static void do_trap(int trapnr, int signr, char *str, struct pt_regs *regs, long error_code, int sicode, void __user *addr) @@ -209,12 +255,17 @@ static void do_error_trap(struct pt_regs *regs, long error_code, char *str, { RCU_LOCKDEP_WARN(!rcu_is_watching(), "entry code didn't wake RCU"); + if (!mark_trap_entry(trapnr, regs)) + return; + if (notify_die(DIE_TRAP, str, regs, error_code, trapnr, signr) != NOTIFY_STOP) { cond_local_irq_enable(regs); do_trap(trapnr, signr, str, regs, error_code, sicode, addr); cond_local_irq_disable(regs); } + + mark_trap_exit(trapnr, regs); } /* @@ -303,15 +354,26 @@ DEFINE_IDTENTRY_RAW(exc_invalid_op) * We use UD2 as a short encoding for 'CALL __WARN', as such * handle it before exception entry to avoid recursive WARN * in case exception entry is the one triggering WARNs. + * + * dovetail: handle_bug() may run oob, so we do not downgrade + * in-band upon a failed __WARN assertion since it might have + * tripped in a section of code which would not be happy to + * switch stage. However, anything else should be notified to + * the core, because the kernel execution might be about to + * stop, so we'd need to switch in-band to get any output + * before this happens. */ if (!user_mode(regs) && handle_bug(regs)) return; - state = irqentry_enter(regs); - instrumentation_begin(); - handle_invalid_op(regs); - instrumentation_end(); - irqentry_exit(regs, state); + if (mark_trap_entry_raw(X86_TRAP_UD, regs)) { + state = irqentry_enter(regs); + instrumentation_begin(); + handle_invalid_op(regs); + instrumentation_end(); + irqentry_exit(regs, state); + mark_trap_exit_raw(X86_TRAP_UD, regs); + } } DEFINE_IDTENTRY(exc_coproc_segment_overrun) @@ -342,9 +404,12 @@ DEFINE_IDTENTRY_ERRORCODE(exc_alignment_check) { char *str = "alignment check"; - if (notify_die(DIE_TRAP, str, regs, error_code, X86_TRAP_AC, SIGBUS) == NOTIFY_STOP) + if (!mark_trap_entry(X86_TRAP_AC, regs)) return; + if (notify_die(DIE_TRAP, str, regs, error_code, X86_TRAP_AC, SIGBUS) == NOTIFY_STOP) + goto mark_exit; + if (!user_mode(regs)) die("Split lock detected\n", regs, error_code); @@ -358,6 +423,9 @@ DEFINE_IDTENTRY_ERRORCODE(exc_alignment_check) out: local_irq_disable(); + +mark_exit: + mark_trap_exit(X86_TRAP_AC, regs); } #ifdef CONFIG_VMAP_STACK @@ -395,6 +463,9 @@ __visible void __noreturn handle_stack_overflow(struct pt_regs *regs, * * The 32bit #DF shim provides CR2 already as an argument. On 64bit it needs * to be read before doing anything else. + * + * Dovetail: do not even ask the companion core to try restoring the + * in-band stage on double-fault, this would be a lost cause. */ DEFINE_IDTENTRY_DF(exc_double_fault) { @@ -518,9 +589,12 @@ DEFINE_IDTENTRY_DF(exc_double_fault) DEFINE_IDTENTRY(exc_bounds) { + if (!mark_trap_entry(X86_TRAP_BR, regs)) + return; + if (notify_die(DIE_TRAP, "bounds", regs, 0, X86_TRAP_BR, SIGSEGV) == NOTIFY_STOP) - return; + goto out; cond_local_irq_enable(regs); if (!user_mode(regs)) @@ -529,6 +603,8 @@ DEFINE_IDTENTRY(exc_bounds) do_trap(X86_TRAP_BR, SIGSEGV, "bounds", regs, 0, 0, NULL); cond_local_irq_disable(regs); +out: + mark_trap_exit(X86_TRAP_BR, regs); } enum kernel_gp_hint { @@ -662,9 +738,13 @@ static bool gp_try_fixup_and_notify(struct pt_regs *regs, int trapnr, unsigned long error_code, const char *str, unsigned long address) { + bool ret; + if (fixup_exception(regs, trapnr, error_code, address)) return true; + mark_trap_entry(trapnr, regs); + current->thread.error_code = error_code; current->thread.trap_nr = trapnr; @@ -673,10 +753,14 @@ static bool gp_try_fixup_and_notify(struct pt_regs *regs, int trapnr, * from kprobe_running(), we have to be non-preemptible. */ if (!preemptible() && kprobe_running() && - kprobe_fault_handler(regs, trapnr)) - return true; + kprobe_fault_handler(regs, trapnr)) + ret = true; + else + ret = notify_die(DIE_GPF, str, regs, error_code, trapnr, SIGSEGV) == NOTIFY_STOP; + + mark_trap_exit(trapnr, regs); - return notify_die(DIE_GPF, str, regs, error_code, trapnr, SIGSEGV) == NOTIFY_STOP; + return ret; } static void gp_user_force_sig_segv(struct pt_regs *regs, int trapnr, @@ -705,9 +789,9 @@ DEFINE_IDTENTRY_ERRORCODE(exc_general_protection) } if (v8086_mode(regs)) { - local_irq_enable(); + local_irq_enable_full(); handle_vm86_fault((struct kernel_vm86_regs *) regs, error_code); - local_irq_disable(); + local_irq_disable_full(); return; } @@ -718,8 +802,11 @@ DEFINE_IDTENTRY_ERRORCODE(exc_general_protection) if (fixup_vdso_exception(regs, X86_TRAP_GP, error_code, 0)) goto exit; + if (!mark_trap_entry(X86_TRAP_GP, regs)) + goto exit; + gp_user_force_sig_segv(regs, X86_TRAP_GP, error_code, desc); - goto exit; + goto mark_exit; } if (gp_try_fixup_and_notify(regs, X86_TRAP_GP, error_code, desc, 0)) @@ -745,6 +832,8 @@ DEFINE_IDTENTRY_ERRORCODE(exc_general_protection) die_addr(desc, regs, error_code, gp_addr); +mark_exit: + mark_trap_exit(X86_TRAP_GP, regs); exit: cond_local_irq_disable(regs); } @@ -789,6 +878,9 @@ DEFINE_IDTENTRY_RAW(exc_int3) if (poke_int3_handler(regs)) return; + if (!mark_trap_entry_raw(X86_TRAP_BP, regs)) + return; + /* * irqentry_enter_from_user_mode() uses static_branch_{,un}likely() * and therefore can trigger INT3, hence poke_int3_handler() must @@ -811,6 +903,8 @@ DEFINE_IDTENTRY_RAW(exc_int3) instrumentation_end(); irqentry_nmi_exit(regs, irq_state); } + + mark_trap_exit_raw(X86_TRAP_BP, regs); } #ifdef CONFIG_X86_64 @@ -1107,7 +1201,7 @@ static __always_inline void exc_debug_user(struct pt_regs *regs, goto out; /* It's safe to allow irq's after DR6 has been saved */ - local_irq_enable(); + local_irq_enable_full(); if (v8086_mode(regs)) { handle_vm86_trap((struct kernel_vm86_regs *)regs, 0, X86_TRAP_DB); @@ -1124,7 +1218,7 @@ static __always_inline void exc_debug_user(struct pt_regs *regs, send_sigtrap(regs, 0, get_si_code(dr6)); out_irq: - local_irq_disable(); + local_irq_disable_full(); out: instrumentation_end(); irqentry_exit_to_user_mode(regs); @@ -1134,13 +1228,19 @@ static __always_inline void exc_debug_user(struct pt_regs *regs, /* IST stack entry */ DEFINE_IDTENTRY_DEBUG(exc_debug) { - exc_debug_kernel(regs, debug_read_clear_dr6()); + if (mark_trap_entry_raw(X86_TRAP_DB, regs)) { + exc_debug_kernel(regs, debug_read_clear_dr6()); + mark_trap_exit_raw(X86_TRAP_DB, regs); + } } /* User entry, runs on regular task stack */ DEFINE_IDTENTRY_DEBUG_USER(exc_debug) { - exc_debug_user(regs, debug_read_clear_dr6()); + if (mark_trap_entry_raw(X86_TRAP_DB, regs)) { + exc_debug_user(regs, debug_read_clear_dr6()); + mark_trap_exit_raw(X86_TRAP_DB, regs); + } } #else /* 32 bit does not have separate entry points. */ @@ -1174,13 +1274,16 @@ static void math_error(struct pt_regs *regs, int trapnr) if (fixup_exception(regs, trapnr, 0, 0)) goto exit; + if (!mark_trap_entry(trapnr, regs)) + goto exit; + task->thread.error_code = 0; task->thread.trap_nr = trapnr; if (notify_die(DIE_TRAP, str, regs, 0, trapnr, SIGFPE) != NOTIFY_STOP) die(str, regs, 0); - goto exit; + goto mark_exit; } /* @@ -1200,8 +1303,13 @@ static void math_error(struct pt_regs *regs, int trapnr) if (fixup_vdso_exception(regs, trapnr, 0, 0)) goto exit; + if (!mark_trap_entry(trapnr, regs)) + goto exit; + force_sig_fault(SIGFPE, si_code, (void __user *)uprobe_get_trap_addr(regs)); +mark_exit: + mark_trap_exit(trapnr, regs); exit: cond_local_irq_disable(regs); } @@ -1264,6 +1372,8 @@ static bool handle_xfd_event(struct pt_regs *regs) if (WARN_ON(!user_mode(regs))) return false; + mark_trap_entry(X86_TRAP_NM, regs); + local_irq_enable(); err = xfd_enable_feature(xfd_err); @@ -1278,6 +1388,9 @@ static bool handle_xfd_event(struct pt_regs *regs) } local_irq_disable(); + + mark_trap_exit(X86_TRAP_NM, regs); + return true; } @@ -1312,7 +1425,10 @@ DEFINE_IDTENTRY(exc_device_not_available) * to kill the task than getting stuck in a never-ending * loop of #NM faults. */ - die("unexpected #NM exception", regs, 0); + if (mark_trap_entry(X86_TRAP_NM, regs)) { + die("unexpected #NM exception", regs, 0); + mark_trap_exit(X86_TRAP_NM, regs); + } } } diff --git a/arch/x86/kernel/tsc.c b/arch/x86/kernel/tsc.c index 15f97c0ab..bd6ecee91 100644 --- a/arch/x86/kernel/tsc.c +++ b/arch/x86/kernel/tsc.c @@ -145,8 +145,11 @@ static void __set_cyc2ns_scale(unsigned long khz, int cpu, unsigned long long ts { unsigned long long ns_now; struct cyc2ns_data data; + unsigned long flags; struct cyc2ns *c2n; + flags = hard_cond_local_irq_save(); + ns_now = cycles_2_ns(tsc_now); /* @@ -177,6 +180,8 @@ static void __set_cyc2ns_scale(unsigned long khz, int cpu, unsigned long long ts c2n->data[0] = data; raw_write_seqcount_latch(&c2n->seq); c2n->data[1] = data; + + hard_cond_local_irq_restore(flags); } static void set_cyc2ns_scale(unsigned long khz, int cpu, unsigned long long tsc_now) @@ -796,11 +801,11 @@ static unsigned long pit_hpet_ptimer_calibrate_cpu(void) * calibration, which will take at least 50ms, and * read the end value. */ - local_irq_save(flags); + flags = hard_local_irq_save(); tsc1 = tsc_read_refs(&ref1, hpet); tsc_pit_khz = pit_calibrate_tsc(latch, ms, loopmin); tsc2 = tsc_read_refs(&ref2, hpet); - local_irq_restore(flags); + hard_local_irq_restore(flags); /* Pick the lowest PIT TSC calibration so far */ tsc_pit_min = min(tsc_pit_min, tsc_pit_khz); @@ -909,9 +914,9 @@ unsigned long native_calibrate_cpu_early(void) if (!fast_calibrate) fast_calibrate = cpu_khz_from_msr(); if (!fast_calibrate) { - local_irq_save(flags); + flags = hard_local_irq_save(); fast_calibrate = quick_pit_calibrate(); - local_irq_restore(flags); + hard_local_irq_restore(flags); } return fast_calibrate; } @@ -978,7 +983,7 @@ void tsc_restore_sched_clock_state(void) if (!sched_clock_stable()) return; - local_irq_save(flags); + flags = hard_local_irq_save(); /* * We're coming out of suspend, there's no concurrency yet; don't @@ -996,7 +1001,7 @@ void tsc_restore_sched_clock_state(void) per_cpu(cyc2ns.data[1].cyc2ns_offset, cpu) = offset; } - local_irq_restore(flags); + hard_local_irq_restore(flags); } #ifdef CONFIG_CPU_FREQ @@ -1475,6 +1480,8 @@ static int __init init_tsc_clocksource(void) if (boot_cpu_has(X86_FEATURE_NONSTOP_TSC_S3)) clocksource_tsc.flags |= CLOCK_SOURCE_SUSPEND_NONSTOP; + clocksource_tsc.vdso_type = CLOCKSOURCE_VDSO_ARCHITECTED; + /* * When TSC frequency is known (retrieved via MSR or CPUID), we skip * the refined calibration and directly register it as a clocksource. diff --git a/arch/x86/kernel/tsc_sync.c b/arch/x86/kernel/tsc_sync.c index 433403365..96f2d385e 100644 --- a/arch/x86/kernel/tsc_sync.c +++ b/arch/x86/kernel/tsc_sync.c @@ -365,6 +365,8 @@ static void check_tsc_sync_source(void *__cpu) atomic_set(&test_runs, 1); else atomic_set(&test_runs, 3); + + hard_cond_local_irq_disable(); retry: /* Wait for the target to start. */ while (atomic_read(&start_count) != cpus - 1) @@ -439,6 +441,8 @@ void check_tsc_sync_target(void) if (unsynchronized_tsc()) return; + hard_cond_local_irq_disable(); + /* * Store, verify and sanitize the TSC adjust register. If * successful skip the test. diff --git a/arch/x86/kvm/emulate.c b/arch/x86/kvm/emulate.c index 2673cd5c4..2b55adf7b 100644 --- a/arch/x86/kvm/emulate.c +++ b/arch/x86/kvm/emulate.c @@ -1092,25 +1092,28 @@ static void fetch_register_operand(struct operand *op) static int em_fninit(struct x86_emulate_ctxt *ctxt) { + unsigned long flags; + if (ctxt->ops->get_cr(ctxt, 0) & (X86_CR0_TS | X86_CR0_EM)) return emulate_nm(ctxt); - kvm_fpu_get(); + flags = kvm_fpu_get(); asm volatile("fninit"); - kvm_fpu_put(); + kvm_fpu_put(flags); return X86EMUL_CONTINUE; } static int em_fnstcw(struct x86_emulate_ctxt *ctxt) { + unsigned long flags; u16 fcw; if (ctxt->ops->get_cr(ctxt, 0) & (X86_CR0_TS | X86_CR0_EM)) return emulate_nm(ctxt); - kvm_fpu_get(); + flags = kvm_fpu_get(); asm volatile("fnstcw %0": "+m"(fcw)); - kvm_fpu_put(); + kvm_fpu_put(flags); ctxt->dst.val = fcw; @@ -1119,14 +1122,15 @@ static int em_fnstcw(struct x86_emulate_ctxt *ctxt) static int em_fnstsw(struct x86_emulate_ctxt *ctxt) { + unsigned long flags; u16 fsw; if (ctxt->ops->get_cr(ctxt, 0) & (X86_CR0_TS | X86_CR0_EM)) return emulate_nm(ctxt); - kvm_fpu_get(); + flags = kvm_fpu_get(); asm volatile("fnstsw %0": "+m"(fsw)); - kvm_fpu_put(); + kvm_fpu_put(flags); ctxt->dst.val = fsw; @@ -3750,17 +3754,18 @@ static inline size_t fxstate_size(struct x86_emulate_ctxt *ctxt) static int em_fxsave(struct x86_emulate_ctxt *ctxt) { struct fxregs_state fx_state; + unsigned long flags; int rc; rc = check_fxsr(ctxt); if (rc != X86EMUL_CONTINUE) return rc; - kvm_fpu_get(); + flags = kvm_fpu_get(); rc = asm_safe("fxsave %[fx]", , [fx] "+m"(fx_state)); - kvm_fpu_put(); + kvm_fpu_put(flags); if (rc != X86EMUL_CONTINUE) return rc; @@ -3794,6 +3799,7 @@ static int em_fxrstor(struct x86_emulate_ctxt *ctxt) struct fxregs_state fx_state; int rc; size_t size; + unsigned long flags; rc = check_fxsr(ctxt); if (rc != X86EMUL_CONTINUE) @@ -3804,7 +3810,7 @@ static int em_fxrstor(struct x86_emulate_ctxt *ctxt) if (rc != X86EMUL_CONTINUE) return rc; - kvm_fpu_get(); + flags = kvm_fpu_get(); if (size < __fxstate_size(16)) { rc = fxregs_fixup(&fx_state, size); @@ -3821,7 +3827,7 @@ static int em_fxrstor(struct x86_emulate_ctxt *ctxt) rc = asm_safe("fxrstor %[fx]", : [fx] "m"(fx_state)); out: - kvm_fpu_put(); + kvm_fpu_put(flags); return rc; } @@ -5083,11 +5089,12 @@ static bool string_insn_completed(struct x86_emulate_ctxt *ctxt) static int flush_pending_x87_faults(struct x86_emulate_ctxt *ctxt) { + unsigned long flags; int rc; - kvm_fpu_get(); + flags = kvm_fpu_get(); rc = asm_safe("fwait"); - kvm_fpu_put(); + kvm_fpu_put(flags); if (unlikely(rc != X86EMUL_CONTINUE)) return emulate_exception(ctxt, MF_VECTOR, 0, false); diff --git a/arch/x86/kvm/fpu.h b/arch/x86/kvm/fpu.h index 3ba12888b..19c831336 100644 --- a/arch/x86/kvm/fpu.h +++ b/arch/x86/kvm/fpu.h @@ -95,46 +95,48 @@ static inline void _kvm_write_mmx_reg(int reg, const u64 *data) } } -static inline void kvm_fpu_get(void) +static inline unsigned long kvm_fpu_get(void) { - fpregs_lock(); + unsigned long flags = fpregs_lock(); fpregs_assert_state_consistent(); if (test_thread_flag(TIF_NEED_FPU_LOAD)) switch_fpu_return(); + + return flags; } -static inline void kvm_fpu_put(void) +static inline void kvm_fpu_put(unsigned long flags) { - fpregs_unlock(); + fpregs_unlock(flags); } static inline void kvm_read_sse_reg(int reg, sse128_t *data) { - kvm_fpu_get(); + unsigned long flags = kvm_fpu_get(); _kvm_read_sse_reg(reg, data); - kvm_fpu_put(); + kvm_fpu_put(flags); } static inline void kvm_write_sse_reg(int reg, const sse128_t *data) { - kvm_fpu_get(); + unsigned long flags = kvm_fpu_get(); _kvm_write_sse_reg(reg, data); - kvm_fpu_put(); + kvm_fpu_put(flags); } static inline void kvm_read_mmx_reg(int reg, u64 *data) { - kvm_fpu_get(); + unsigned long flags = kvm_fpu_get(); _kvm_read_mmx_reg(reg, data); - kvm_fpu_put(); + kvm_fpu_put(flags); } static inline void kvm_write_mmx_reg(int reg, const u64 *data) { - kvm_fpu_get(); + unsigned long flags = kvm_fpu_get(); _kvm_write_mmx_reg(reg, data); - kvm_fpu_put(); + kvm_fpu_put(flags); } #endif diff --git a/arch/x86/kvm/hyperv.c b/arch/x86/kvm/hyperv.c index 238afd733..9184bdd54 100644 --- a/arch/x86/kvm/hyperv.c +++ b/arch/x86/kvm/hyperv.c @@ -2408,12 +2408,13 @@ static bool is_xmm_fast_hypercall(struct kvm_hv_hcall *hc) static void kvm_hv_hypercall_read_xmm(struct kvm_hv_hcall *hc) { + unsigned long flags; int reg; - kvm_fpu_get(); + flags = kvm_fpu_get(); for (reg = 0; reg < HV_HYPERCALL_MAX_XMM_REGISTERS; reg++) _kvm_read_sse_reg(reg, &hc->xmm[reg]); - kvm_fpu_put(); + kvm_fpu_put(flags); } static bool hv_check_hypercall_access(struct kvm_vcpu_hv *hv_vcpu, u16 code) diff --git a/arch/x86/kvm/vmx/vmx.c b/arch/x86/kvm/vmx/vmx.c index 479ef2662..3145a719a 100644 --- a/arch/x86/kvm/vmx/vmx.c +++ b/arch/x86/kvm/vmx/vmx.c @@ -735,12 +735,13 @@ static int vmx_set_guest_uret_msr(struct vcpu_vmx *vmx, struct vmx_uret_msr *msr, u64 data) { unsigned int slot = msr - vmx->guest_uret_msrs; + unsigned long flags; int ret = 0; if (msr->load_into_hardware) { - preempt_disable(); + flags = hard_preempt_disable(); ret = kvm_set_user_return_msr(slot, data, msr->mask); - preempt_enable(); + hard_preempt_enable(flags); } if (!ret) msr->data = data; @@ -1406,19 +1407,23 @@ static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx) #ifdef CONFIG_X86_64 static u64 vmx_read_guest_kernel_gs_base(struct vcpu_vmx *vmx) { - preempt_disable(); + unsigned long flags; + + flags = hard_preempt_disable(); if (vmx->guest_state_loaded) rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base); - preempt_enable(); + hard_preempt_enable(flags); return vmx->msr_guest_kernel_gs_base; } static void vmx_write_guest_kernel_gs_base(struct vcpu_vmx *vmx, u64 data) { - preempt_disable(); + unsigned long flags; + + flags = hard_preempt_disable(); if (vmx->guest_state_loaded) wrmsrl(MSR_KERNEL_GS_BASE, data); - preempt_enable(); + hard_preempt_enable(flags); vmx->msr_guest_kernel_gs_base = data; } #endif @@ -1877,6 +1882,7 @@ static void vmx_setup_uret_msrs(struct vcpu_vmx *vmx) * The SYSCALL MSRs are only needed on long mode guests, and only * when EFER.SCE is set. */ + hard_cond_local_irq_disable(); load_syscall_msrs = is_long_mode(&vmx->vcpu) && (vmx->vcpu.arch.efer & EFER_SCE); @@ -1898,6 +1904,8 @@ static void vmx_setup_uret_msrs(struct vcpu_vmx *vmx) */ vmx_setup_uret_msr(vmx, MSR_IA32_TSX_CTRL, boot_cpu_has(X86_FEATURE_RTM)); + hard_cond_local_irq_enable(); + /* * The set of MSRs to load may have changed, reload MSRs before the * next VM-Enter. @@ -2178,6 +2186,7 @@ static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info) u32 msr_index = msr_info->index; u64 data = msr_info->data; u32 index; + unsigned long flags; switch (msr_index) { case MSR_EFER: @@ -2459,11 +2468,22 @@ static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info) default: find_uret_msr: + /* + * Dovetail: guest MSRs may be activated independently + * from vcpu_run(): rely on the notifier for restoring + * them upon preemption by the companion core, right + * before the current CPU switches to out-of-band + * scheduling (see dovetail_context_switch()). + */ msr = vmx_find_uret_msr(vmx, msr_index); - if (msr) + if (msr) { + flags = hard_cond_local_irq_save(); + inband_enter_guest(vcpu); ret = vmx_set_guest_uret_msr(vmx, msr, data); - else + hard_cond_local_irq_restore(flags); + } else { ret = kvm_set_msr_common(vcpu, msr_info); + } } /* FB_CLEAR may have changed, also update the FB_CLEAR_DIS behavior */ diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c index dcd0c12c3..b94ce2457 100644 --- a/arch/x86/kvm/x86.c +++ b/arch/x86/kvm/x86.c @@ -210,6 +210,7 @@ module_param(mitigate_smt_rsb, bool, 0444); struct kvm_user_return_msrs { struct user_return_notifier urn; bool registered; + bool dirty; struct kvm_user_return_msr_values { u64 host; u64 curr; @@ -359,12 +360,29 @@ static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu) vcpu->arch.apf.gfns[i] = ~0; } -static void kvm_on_user_return(struct user_return_notifier *urn) +static void __kvm_on_user_return(struct kvm_user_return_msrs *msrs) { + struct kvm_user_return_msr_values *values; unsigned slot; + + if (!msrs->dirty) + return; + + for (slot = 0; slot < kvm_nr_uret_msrs; ++slot) { + values = &msrs->values[slot]; + if (values->host != values->curr) { + wrmsrl(kvm_uret_msrs_list[slot], values->host); + values->curr = values->host; + } + } + + msrs->dirty = false; +} + +static void kvm_on_user_return(struct user_return_notifier *urn) +{ struct kvm_user_return_msrs *msrs = container_of(urn, struct kvm_user_return_msrs, urn); - struct kvm_user_return_msr_values *values; unsigned long flags; /* @@ -377,27 +395,25 @@ static void kvm_on_user_return(struct user_return_notifier *urn) user_return_notifier_unregister(urn); } local_irq_restore(flags); - for (slot = 0; slot < kvm_nr_uret_msrs; ++slot) { - values = &msrs->values[slot]; - if (values->host != values->curr) { - wrmsrl(kvm_uret_msrs_list[slot], values->host); - values->curr = values->host; - } - } + flags = hard_cond_local_irq_save(); + __kvm_on_user_return(msrs); + hard_cond_local_irq_restore(flags); + inband_exit_guest(); } static int kvm_probe_user_return_msr(u32 msr) { + unsigned long flags; u64 val; int ret; - preempt_disable(); + flags = hard_preempt_disable(); ret = rdmsrl_safe(msr, &val); if (ret) goto out; ret = wrmsrl_safe(msr, val); out: - preempt_enable(); + hard_preempt_enable(flags); return ret; } @@ -452,6 +468,7 @@ int kvm_set_user_return_msr(unsigned slot, u64 value, u64 mask) if (err) return 1; + msrs->dirty = true; msrs->values[slot].curr = value; if (!msrs->registered) { msrs->urn.on_user_return = kvm_on_user_return; @@ -4908,12 +4925,23 @@ static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu) void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu) { + struct kvm_user_return_msrs *msrs = this_cpu_ptr(user_return_msrs); + unsigned long flags; int idx; + flags = hard_cond_local_irq_save(); + if (vcpu->preempted) { if (!vcpu->arch.guest_state_protected) vcpu->arch.preempted_in_kernel = !static_call(kvm_x86_get_cpl)(vcpu); + /* + * Skip steal time accounting from the out-of-band stage since + * this is oob-unsafe. We leave it to the next call from the + * inband stage. + */ + if (running_oob()) + goto skip_steal_time_update; /* * Take the srcu lock as memslots will be accessed to check the gfn * cache generation against the memslots generation. @@ -4926,10 +4954,44 @@ void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu) srcu_read_unlock(&vcpu->kvm->srcu, idx); } +skip_steal_time_update: static_call(kvm_x86_vcpu_put)(vcpu); vcpu->arch.last_host_tsc = rdtsc(); + + inband_set_vcpu_release_state(vcpu, false); + if (!msrs->dirty) + inband_exit_guest(); + + hard_cond_local_irq_restore(flags); } +#ifdef CONFIG_DOVETAIL +/* hard irqs off. */ +void kvm_handle_oob_switch(struct kvm_oob_notifier *nfy) +{ + struct kvm_user_return_msrs *msrs = this_cpu_ptr(user_return_msrs); + struct kvm_vcpu *vcpu; + + vcpu = container_of(nfy, struct kvm_vcpu, oob_notifier); + /* + * If user_return MSRs were still active when leaving + * kvm_arch_vcpu_put(), inband_exit_guest() was not invoked, + * so we might get called later on before kvm_on_user_return() + * had a chance to run, if a switch to out-of-band scheduling + * sneaks in in the meantime. Prevent kvm_arch_vcpu_put() + * from running twice in such a case by checking ->put_vcpu + * from the notifier block. + */ + if (nfy->put_vcpu) + kvm_arch_vcpu_put(vcpu); + + __kvm_on_user_return(msrs); + inband_exit_guest(); +} +#else +#define kvm_handle_oob_switch NULL +#endif + static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu, struct kvm_lapic_state *s) { @@ -10705,6 +10767,10 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu) } preempt_disable(); + local_irq_disable_full(); + + inband_enter_guest(vcpu); + inband_set_vcpu_release_state(vcpu, true); static_call(kvm_x86_prepare_switch_to_guest)(vcpu); @@ -10713,7 +10779,7 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu) * IPI are then delayed after guest entry, which ensures that they * result in virtual interrupt delivery. */ - local_irq_disable(); + local_irq_disable_full(); /* Store vcpu->apicv_active before vcpu->mode. */ smp_store_release(&vcpu->mode, IN_GUEST_MODE); @@ -10747,7 +10813,7 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu) if (kvm_vcpu_exit_request(vcpu)) { vcpu->mode = OUTSIDE_GUEST_MODE; smp_wmb(); - local_irq_enable(); + local_irq_enable_full(); preempt_enable(); kvm_vcpu_srcu_read_lock(vcpu); r = 1; @@ -10854,9 +10920,9 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu) * stat.exits increment will do nicely. */ kvm_before_interrupt(vcpu, KVM_HANDLING_IRQ); - local_irq_enable(); + local_irq_enable_full(); ++vcpu->stat.exits; - local_irq_disable(); + local_irq_disable_full(); kvm_after_interrupt(vcpu); /* @@ -10868,7 +10934,7 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu) */ guest_timing_exit_irqoff(); - local_irq_enable(); + local_irq_enable_full(); preempt_enable(); kvm_vcpu_srcu_read_lock(vcpu); @@ -11952,6 +12018,7 @@ int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu) if (r) goto free_guest_fpu; + inband_init_vcpu(vcpu, kvm_handle_oob_switch); vcpu->arch.arch_capabilities = kvm_get_arch_capabilities(); vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT; kvm_xen_init_vcpu(vcpu); diff --git a/arch/x86/lib/usercopy.c b/arch/x86/lib/usercopy.c index 24b48af27..c3b3df116 100644 --- a/arch/x86/lib/usercopy.c +++ b/arch/x86/lib/usercopy.c @@ -33,7 +33,7 @@ copy_from_user_nmi(void *to, const void __user *from, unsigned long n) { unsigned long ret; - if (!__access_ok(from, n)) + if (running_oob() || !__access_ok(from, n)) return n; if (!nmi_uaccess_okay()) diff --git a/arch/x86/mm/fault.c b/arch/x86/mm/fault.c index 6529b3e2c..9187aebc4 100644 --- a/arch/x86/mm/fault.c +++ b/arch/x86/mm/fault.c @@ -647,6 +647,12 @@ page_fault_oops(struct pt_regs *regs, unsigned long error_code, goto oops; } + /* + * Do not bother unwinding the notification context on + * CPU/firmware/kernel bug. + */ + oob_trap_notify(X86_TRAP_PF, regs); + #ifdef CONFIG_VMAP_STACK /* * Stack overflow? During boot, we can fault near the initial @@ -767,6 +773,55 @@ show_signal_msg(struct pt_regs *regs, unsigned long error_code, show_opcodes(regs, loglvl); } +#ifdef CONFIG_IRQ_PIPELINE + +static inline void cond_reenable_irqs_user(void) +{ + hard_local_irq_enable(); + + if (running_inband()) + local_irq_enable(); +} + +static inline void cond_reenable_irqs_kernel(irqentry_state_t state, + struct pt_regs *regs) +{ + if (regs->flags & X86_EFLAGS_IF) { + hard_local_irq_enable(); + if (state.stage_info == IRQENTRY_INBAND_UNSTALLED) + local_irq_enable(); + } +} + +static inline void cond_disable_irqs(void) +{ + hard_local_irq_disable(); + + if (running_inband()) + local_irq_disable(); +} + +#else /* !CONFIG_IRQ_PIPELINE */ + +static inline void cond_reenable_irqs_user(void) +{ + local_irq_enable(); +} + +static inline void cond_reenable_irqs_kernel(irqentry_state_t state, + struct pt_regs *regs) +{ + if (regs->flags & X86_EFLAGS_IF) + local_irq_enable(); +} + +static inline void cond_disable_irqs(void) +{ + local_irq_disable(); +} + +#endif /* !CONFIG_IRQ_PIPELINE */ + static void __bad_area_nosemaphore(struct pt_regs *regs, unsigned long error_code, unsigned long address, u32 pkey, int si_code) @@ -789,7 +844,7 @@ __bad_area_nosemaphore(struct pt_regs *regs, unsigned long error_code, * User mode accesses just cause a SIGSEGV. * It's possible to have interrupts off here: */ - local_irq_enable(); + cond_reenable_irqs_user(); /* * Valid to do another page fault here because this one came @@ -806,6 +861,10 @@ __bad_area_nosemaphore(struct pt_regs *regs, unsigned long error_code, if (fixup_vdso_exception(regs, X86_TRAP_PF, error_code, address)) return; + oob_trap_notify(X86_TRAP_PF, regs); + if (!running_inband()) + goto out; + if (likely(show_unhandled_signals)) show_signal_msg(regs, error_code, address, tsk); @@ -816,7 +875,9 @@ __bad_area_nosemaphore(struct pt_regs *regs, unsigned long error_code, else force_sig_fault(SIGSEGV, si_code, (void __user *)address); - local_irq_disable(); + local_irq_disable_full(); +out: + oob_trap_unwind(X86_TRAP_PF, regs); } static noinline void @@ -1198,7 +1259,8 @@ NOKPROBE_SYMBOL(do_kern_addr_fault); static inline void do_user_addr_fault(struct pt_regs *regs, unsigned long error_code, - unsigned long address) + unsigned long address, + irqentry_state_t state) { struct vm_area_struct *vma; struct task_struct *tsk; @@ -1257,7 +1319,7 @@ void do_user_addr_fault(struct pt_regs *regs, * If we're in an interrupt, have no user context or are running * in a region with pagefaults disabled then we must not take the fault */ - if (unlikely(faulthandler_disabled() || !mm)) { + if (unlikely(running_inband() && (faulthandler_disabled() || !mm))) { bad_area_nosemaphore(regs, error_code, address); return; } @@ -1270,13 +1332,24 @@ void do_user_addr_fault(struct pt_regs *regs, * potential system fault or CPU buglet: */ if (user_mode(regs)) { - local_irq_enable(); + cond_reenable_irqs_user(); flags |= FAULT_FLAG_USER; } else { if (regs->flags & X86_EFLAGS_IF) - local_irq_enable(); + cond_reenable_irqs_kernel(state, regs); } + /* + * At this point, we would have to stop running + * out-of-band. Tell the companion core about the page fault + * event, so that it might switch current to in-band mode if + * need be. If it does not, then we may assume that it would + * also handle the fixups. + */ + oob_trap_notify(X86_TRAP_PF, regs); + if (!running_inband()) + goto out; + perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, regs, address); /* @@ -1306,7 +1379,7 @@ void do_user_addr_fault(struct pt_regs *regs, */ if (is_vsyscall_vaddr(address)) { if (emulate_vsyscall(error_code, regs, address)) - return; + goto out; } #endif @@ -1337,7 +1410,7 @@ void do_user_addr_fault(struct pt_regs *regs, kernelmode_fixup_or_oops(regs, error_code, address, SIGBUS, BUS_ADRERR, ARCH_DEFAULT_PKEY); - return; + goto out; } lock_mmap: @@ -1345,7 +1418,7 @@ void do_user_addr_fault(struct pt_regs *regs, vma = lock_mm_and_find_vma(mm, address, regs); if (unlikely(!vma)) { bad_area_nosemaphore(regs, error_code, address); - return; + goto out; } /* @@ -1354,7 +1427,7 @@ void do_user_addr_fault(struct pt_regs *regs, */ if (unlikely(access_error(error_code, vma))) { bad_area_access_error(regs, error_code, address, vma); - return; + goto out; } /* @@ -1381,12 +1454,12 @@ void do_user_addr_fault(struct pt_regs *regs, kernelmode_fixup_or_oops(regs, error_code, address, SIGBUS, BUS_ADRERR, ARCH_DEFAULT_PKEY); - return; + goto out; } /* The fault is fully completed (including releasing mmap lock) */ if (fault & VM_FAULT_COMPLETED) - return; + goto out; /* * If we need to retry the mmap_lock has already been released, @@ -1401,12 +1474,12 @@ void do_user_addr_fault(struct pt_regs *regs, mmap_read_unlock(mm); done: if (likely(!(fault & VM_FAULT_ERROR))) - return; + goto out; if (fatal_signal_pending(current) && !user_mode(regs)) { kernelmode_fixup_or_oops(regs, error_code, address, 0, 0, ARCH_DEFAULT_PKEY); - return; + goto out; } if (fault & VM_FAULT_OOM) { @@ -1415,7 +1488,7 @@ void do_user_addr_fault(struct pt_regs *regs, kernelmode_fixup_or_oops(regs, error_code, address, SIGSEGV, SEGV_MAPERR, ARCH_DEFAULT_PKEY); - return; + goto out; } /* @@ -1433,6 +1506,8 @@ void do_user_addr_fault(struct pt_regs *regs, else BUG(); } +out: + oob_trap_unwind(X86_TRAP_PF, regs); } NOKPROBE_SYMBOL(do_user_addr_fault); @@ -1451,7 +1526,8 @@ trace_page_fault_entries(struct pt_regs *regs, unsigned long error_code, static __always_inline void handle_page_fault(struct pt_regs *regs, unsigned long error_code, - unsigned long address) + unsigned long address, + irqentry_state_t state) { trace_page_fault_entries(regs, error_code, address); @@ -1462,7 +1538,7 @@ handle_page_fault(struct pt_regs *regs, unsigned long error_code, if (unlikely(fault_in_kernel_space(address))) { do_kern_addr_fault(regs, error_code, address); } else { - do_user_addr_fault(regs, error_code, address); + do_user_addr_fault(regs, error_code, address, state); /* * User address page fault handling might have reenabled * interrupts. Fixing up all potential exit points of @@ -1470,7 +1546,7 @@ handle_page_fault(struct pt_regs *regs, unsigned long error_code, * doable w/o creating an unholy mess or turning the code * upside down. */ - local_irq_disable(); + cond_disable_irqs(); } } @@ -1518,8 +1594,46 @@ DEFINE_IDTENTRY_RAW_ERRORCODE(exc_page_fault) state = irqentry_enter(regs); instrumentation_begin(); - handle_page_fault(regs, error_code, address); + handle_page_fault(regs, error_code, address, state); instrumentation_end(); irqentry_exit(regs, state); } + +#ifdef CONFIG_DOVETAIL + +void arch_advertise_page_mapping(unsigned long start, unsigned long end) +{ + unsigned long next, addr = start; + pgd_t *pgd, *pgd_ref; + struct page *page; + + /* + * APEI may create temporary mappings in interrupt context - + * nothing we can and need to propagate globally. + */ + if (in_interrupt()) + return; + + if (!(start >= VMALLOC_START && start < VMALLOC_END)) + return; + + do { + next = pgd_addr_end(addr, end); + pgd_ref = pgd_offset_k(addr); + if (pgd_none(*pgd_ref)) + continue; + spin_lock(&pgd_lock); + list_for_each_entry(page, &pgd_list, lru) { + pgd = page_address(page) + pgd_index(addr); + if (pgd_none(*pgd)) + set_pgd(pgd, *pgd_ref); + } + spin_unlock(&pgd_lock); + addr = next; + } while (addr != end); + + arch_flush_lazy_mmu_mode(); +} + +#endif diff --git a/arch/x86/mm/tlb.c b/arch/x86/mm/tlb.c index 64f594826..0676d1604 100644 --- a/arch/x86/mm/tlb.c +++ b/arch/x86/mm/tlb.c @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -325,10 +326,12 @@ EXPORT_SYMBOL_GPL(leave_mm); void switch_mm(struct mm_struct *prev, struct mm_struct *next, struct task_struct *tsk) { - unsigned long flags; + unsigned long flags, _flags; local_irq_save(flags); + protect_inband_mm(_flags); switch_mm_irqs_off(prev, next, tsk); + unprotect_inband_mm(_flags); local_irq_restore(flags); } @@ -515,7 +518,9 @@ void switch_mm_irqs_off(struct mm_struct *prev, struct mm_struct *next, */ /* We don't want flush_tlb_func() to run concurrently with us. */ - if (IS_ENABLED(CONFIG_PROVE_LOCKING)) + if (IS_ENABLED(CONFIG_DOVETAIL)) + WARN_ON_ONCE(!hard_irqs_disabled()); + else if (IS_ENABLED(CONFIG_PROVE_LOCKING)) WARN_ON_ONCE(!irqs_disabled()); /* @@ -753,11 +758,11 @@ static void flush_tlb_func(void *info) */ const struct flush_tlb_info *f = info; struct mm_struct *loaded_mm = this_cpu_read(cpu_tlbstate.loaded_mm); - u32 loaded_mm_asid = this_cpu_read(cpu_tlbstate.loaded_mm_asid); - u64 local_tlb_gen = this_cpu_read(cpu_tlbstate.ctxs[loaded_mm_asid].tlb_gen); - bool local = smp_processor_id() == f->initiating_cpu; - unsigned long nr_invalidate = 0; + u32 loaded_mm_asid; u64 mm_tlb_gen; + u64 local_tlb_gen; + bool local = smp_processor_id() == f->initiating_cpu; + unsigned long nr_invalidate = 0, flags; /* This code cannot presently handle being reentered. */ VM_WARN_ON(!irqs_disabled()); @@ -771,8 +776,16 @@ static void flush_tlb_func(void *info) return; } - if (unlikely(loaded_mm == &init_mm)) + protect_inband_mm(flags); + + loaded_mm_asid = this_cpu_read(cpu_tlbstate.loaded_mm_asid); + mm_tlb_gen = atomic64_read(&loaded_mm->context.tlb_gen); + local_tlb_gen = this_cpu_read(cpu_tlbstate.ctxs[loaded_mm_asid].tlb_gen); + + if (unlikely(loaded_mm == &init_mm)) { + unprotect_inband_mm(flags); return; + } VM_WARN_ON(this_cpu_read(cpu_tlbstate.ctxs[loaded_mm_asid].ctx_id) != loaded_mm->context.ctx_id); @@ -788,6 +801,7 @@ static void flush_tlb_func(void *info) * IPIs to lazy TLB mode CPUs. */ switch_mm_irqs_off(NULL, &init_mm, NULL); + unprotect_inband_mm(flags); return; } @@ -799,6 +813,7 @@ static void flush_tlb_func(void *info) * mm_tlb_gen unnecessarily would have negative caching effects * so avoid it. */ + unprotect_inband_mm(flags); return; } @@ -815,12 +830,15 @@ static void flush_tlb_func(void *info) * be handled can catch us all the way up, leaving no work for * the second flush. */ + unprotect_inband_mm(flags); goto done; } WARN_ON_ONCE(local_tlb_gen > mm_tlb_gen); WARN_ON_ONCE(f->new_tlb_gen > mm_tlb_gen); + unprotect_inband_mm(flags); + /* * If we get to this point, we know that our TLB is out of date. * This does not strictly imply that we need to flush (it's @@ -1194,11 +1212,11 @@ STATIC_NOPV void native_flush_tlb_global(void) * from interrupts. (Use the raw variant because this code can * be called from deep inside debugging code.) */ - raw_local_irq_save(flags); + flags = hard_local_irq_save(); __native_tlb_flush_global(this_cpu_read(cpu_tlbstate.cr4)); - raw_local_irq_restore(flags); + hard_local_irq_restore(flags); } /* @@ -1206,6 +1224,8 @@ STATIC_NOPV void native_flush_tlb_global(void) */ STATIC_NOPV void native_flush_tlb_local(void) { + unsigned long flags; + /* * Preemption or interrupts must be disabled to protect the access * to the per CPU variable and to prevent being preempted between @@ -1213,10 +1233,14 @@ STATIC_NOPV void native_flush_tlb_local(void) */ WARN_ON_ONCE(preemptible()); + flags = hard_cond_local_irq_save(); + invalidate_user_asid(this_cpu_read(cpu_tlbstate.loaded_mm_asid)); /* If current->mm == NULL then the read_cr3() "borrows" an mm */ native_write_cr3(__native_read_cr3()); + + hard_cond_local_irq_restore(flags); } void flush_tlb_local(void) @@ -1288,6 +1312,16 @@ bool nmi_uaccess_okay(void) VM_WARN_ON_ONCE(!loaded_mm); + /* + * There would be no way for the companion core to switch an + * out-of-band task back in-band in order to handle an access + * fault over NMI safely. Tell the caller that uaccess from + * NMI is NOT ok if the preempted task was running + * out-of-band. + */ + if (running_oob()) + return false; + /* * The condition we want to check is * current_mm->pgd == __va(read_cr3_pa()). This may be slow, though, diff --git a/arch/x86/platform/efi/efi_64.c b/arch/x86/platform/efi/efi_64.c index 91d31ac42..634fcb660 100644 --- a/arch/x86/platform/efi/efi_64.c +++ b/arch/x86/platform/efi/efi_64.c @@ -476,15 +476,23 @@ void __init efi_dump_pagetable(void) */ static void efi_enter_mm(void) { + unsigned long flags; + + protect_inband_mm(flags); efi_prev_mm = current->active_mm; current->active_mm = &efi_mm; switch_mm(efi_prev_mm, &efi_mm, NULL); + unprotect_inband_mm(flags); } static void efi_leave_mm(void) { + unsigned long flags; + + protect_inband_mm(flags); current->active_mm = efi_prev_mm; switch_mm(&efi_mm, efi_prev_mm, NULL); + unprotect_inband_mm(flags); } void arch_efi_call_virt_setup(void) diff --git a/arch/x86/xen/Kconfig b/arch/x86/xen/Kconfig index a65fc2ae1..0d27871b2 100644 --- a/arch/x86/xen/Kconfig +++ b/arch/x86/xen/Kconfig @@ -5,7 +5,7 @@ config XEN bool "Xen guest support" - depends on PARAVIRT + depends on PARAVIRT && !IRQ_PIPELINE select PARAVIRT_CLOCK select X86_HV_CALLBACK_VECTOR depends on X86_64 || (X86_32 && X86_PAE) diff --git a/arch/x86/xen/enlighten_hvm.c b/arch/x86/xen/enlighten_hvm.c index 70be57e8f..65721f918 100644 --- a/arch/x86/xen/enlighten_hvm.c +++ b/arch/x86/xen/enlighten_hvm.c @@ -120,7 +120,8 @@ static void __init init_hvm_pv_info(void) this_cpu_write(xen_vcpu_id, smp_processor_id()); } -DEFINE_IDTENTRY_SYSVEC(sysvec_xen_hvm_callback) +DEFINE_IDTENTRY_SYSVEC_PIPELINED(HYPERVISOR_CALLBACK_VECTOR, + sysvec_xen_hvm_callback) { struct pt_regs *old_regs = set_irq_regs(regs); diff --git a/drivers/Kconfig b/drivers/Kconfig index efb66e25f..7250a60bd 100644 --- a/drivers/Kconfig +++ b/drivers/Kconfig @@ -35,6 +35,8 @@ source "drivers/block/Kconfig" source "drivers/nvme/Kconfig" +source "drivers/evl/Kconfig" + source "drivers/misc/Kconfig" source "drivers/scsi/Kconfig" diff --git a/drivers/Makefile b/drivers/Makefile index 1bec7819a..735642f52 100644 --- a/drivers/Makefile +++ b/drivers/Makefile @@ -163,6 +163,8 @@ obj-$(CONFIG_REMOTEPROC) += remoteproc/ obj-$(CONFIG_RPMSG) += rpmsg/ obj-$(CONFIG_SOUNDWIRE) += soundwire/ +obj-$(CONFIG_EVL) += evl/ + # Virtualization drivers obj-$(CONFIG_VIRT_DRIVERS) += virt/ obj-$(subst m,y,$(CONFIG_HYPERV)) += hv/ diff --git a/drivers/base/regmap/internal.h b/drivers/base/regmap/internal.h index a29f24b15..5c1903a0d 100644 --- a/drivers/base/regmap/internal.h +++ b/drivers/base/regmap/internal.h @@ -51,7 +51,10 @@ struct regmap { union { struct mutex mutex; struct { - spinlock_t spinlock; + union { + spinlock_t spinlock; + hard_spinlock_t oob_lock; + }; unsigned long spinlock_flags; }; struct { diff --git a/drivers/base/regmap/regmap-irq.c b/drivers/base/regmap/regmap-irq.c index dceab5d01..5a65d6366 100644 --- a/drivers/base/regmap/regmap-irq.c +++ b/drivers/base/regmap/regmap-irq.c @@ -299,6 +299,7 @@ static const struct irq_chip regmap_irq_chip = { .irq_enable = regmap_irq_enable, .irq_set_type = regmap_irq_set_type, .irq_set_wake = regmap_irq_set_wake, + .flags = IRQCHIP_PIPELINE_SAFE, }; static inline int read_sub_irq_data(struct regmap_irq_chip_data *data, diff --git a/drivers/base/regmap/regmap.c b/drivers/base/regmap/regmap.c index 3011f7f93..4ff5f35f4 100644 --- a/drivers/base/regmap/regmap.c +++ b/drivers/base/regmap/regmap.c @@ -17,6 +17,7 @@ #include #include #include +#include #include #define CREATE_TRACE_POINTS @@ -485,6 +486,23 @@ __releases(&map->raw_spinlock) raw_spin_unlock_irqrestore(&map->raw_spinlock, map->raw_spinlock_flags); } +static void regmap_lock_oob(void *__map) +__acquires(&map->oob_lock) +{ + struct regmap *map = __map; + unsigned long flags; + + raw_spin_lock_irqsave(&map->oob_lock, flags); + map->spinlock_flags = flags; +} + +static void regmap_unlock_oob(void *__map) +__releases(&map->oob_lock) +{ + struct regmap *map = __map; + raw_spin_unlock_irqrestore(&map->oob_lock, map->spinlock_flags); +} + static void dev_get_regmap_release(struct device *dev, void *res) { /* @@ -734,7 +752,13 @@ struct regmap *__regmap_init(struct device *dev, } else { if ((bus && bus->fast_io) || config->fast_io) { - if (config->use_raw_spinlock) { + if (dovetailing() && config->oob_io) { + raw_spin_lock_init(&map->oob_lock); + map->lock = regmap_lock_oob; + map->unlock = regmap_unlock_oob; + lockdep_set_class_and_name(&map->oob_lock, + lock_key, lock_name); + } else if (config->use_raw_spinlock) { raw_spin_lock_init(&map->raw_spinlock); map->lock = regmap_lock_raw_spinlock; map->unlock = regmap_unlock_raw_spinlock; @@ -747,13 +771,16 @@ struct regmap *__regmap_init(struct device *dev, lockdep_set_class_and_name(&map->spinlock, lock_key, lock_name); } - } else { + } else if (!config->oob_io) { /* Catch configuration issue: oob && !fast_io */ mutex_init(&map->mutex); map->lock = regmap_lock_mutex; map->unlock = regmap_unlock_mutex; map->can_sleep = true; lockdep_set_class_and_name(&map->mutex, lock_key, lock_name); + } else { + ret = -ENXIO; + goto err_name; } map->lock_arg = map; map->lock_key = lock_key; diff --git a/drivers/clocksource/Kconfig b/drivers/clocksource/Kconfig index 8208a3d89..235c68189 100644 --- a/drivers/clocksource/Kconfig +++ b/drivers/clocksource/Kconfig @@ -25,6 +25,7 @@ config I8253_LOCK config OMAP_DM_SYSTIMER bool select TIMER_OF + imply GENERIC_CLOCKSOURCE_VDSO config CLKBLD_I8253 def_bool y if CLKSRC_I8253 || CLKEVT_I8253 || I8253_LOCK @@ -65,6 +66,8 @@ config OMAP_DM_TIMER config DW_APB_TIMER bool "DW APB timer driver" if COMPILE_TEST + select CLKSRC_MMIO + imply GENERIC_CLOCKSOURCE_VDSO help Enables the support for the dw_apb timer. @@ -371,6 +374,7 @@ config SUN50I_ERRATUM_UNKNOWN1 config ARM_GLOBAL_TIMER bool "Support for the ARM global timer" if COMPILE_TEST select TIMER_OF if OF + imply GENERIC_CLOCKSOURCE_VDSO depends on ARM help This option enables support for the ARM global timer unit. @@ -436,6 +440,7 @@ config CLKSRC_EXYNOS_MCT bool "Exynos multi core timer driver" if COMPILE_TEST depends on ARM || ARM64 depends on ARCH_ARTPEC || ARCH_EXYNOS || COMPILE_TEST + imply GENERIC_CLOCKSOURCE_VDSO help Support for Multi Core Timer controller on Exynos SoCs. @@ -588,7 +593,7 @@ config CLKSRC_PXA config CLKSRC_IMX_GPT bool "Clocksource using i.MX GPT" if COMPILE_TEST depends on (ARM || ARM64) && HAVE_CLK - select CLKSRC_MMIO + imply GENERIC_CLOCKSOURCE_VDSO config CLKSRC_IMX_TPM bool "Clocksource using i.MX TPM" if COMPILE_TEST @@ -619,7 +624,7 @@ config CLKSRC_ST_LPC bool "Low power clocksource found in the LPC" if COMPILE_TEST select TIMER_OF if OF depends on HAS_IOMEM - select CLKSRC_MMIO + imply GENERIC_CLOCKSOURCE_VDSO help Enable this option to use the Low Power controller timer as clocksource. diff --git a/drivers/clocksource/arm_arch_timer.c b/drivers/clocksource/arm_arch_timer.c index 071b04f1e..1570a96ee 100644 --- a/drivers/clocksource/arm_arch_timer.c +++ b/drivers/clocksource/arm_arch_timer.c @@ -23,6 +23,7 @@ #include #include #include +#include #include #include #include @@ -671,7 +672,7 @@ static __always_inline irqreturn_t timer_handler(const int access, if (ctrl & ARCH_TIMER_CTRL_IT_STAT) { ctrl |= ARCH_TIMER_CTRL_IT_MASK; arch_timer_reg_write(access, ARCH_TIMER_REG_CTRL, ctrl, evt); - evt->event_handler(evt); + clockevents_handle_event(evt); return IRQ_HANDLED; } @@ -855,7 +856,7 @@ static void __arch_timer_setup(unsigned type, { u64 max_delta; - clk->features = CLOCK_EVT_FEAT_ONESHOT; + clk->features = CLOCK_EVT_FEAT_ONESHOT | CLOCK_EVT_FEAT_PIPELINE; if (type == ARCH_TIMER_TYPE_CP15) { typeof(clk->set_next_event) sne; @@ -978,6 +979,9 @@ static void arch_counter_set_user_access(void) else cntkctl |= ARCH_TIMER_USR_VCT_ACCESS_EN; + if (IS_ENABLED(CONFIG_GENERIC_CLOCKSOURCE_VDSO)) + cntkctl |= ARCH_TIMER_USR_PT_ACCESS_EN; + arch_timer_set_cntkctl(cntkctl); } @@ -1011,6 +1015,7 @@ static int arch_timer_starting_cpu(unsigned int cpu) enable_percpu_irq(arch_timer_ppi[arch_timer_uses_ppi], flags); if (arch_timer_has_nonsecure_ppi()) { + clk->irq = arch_timer_ppi[ARCH_TIMER_PHYS_NONSECURE_PPI]; flags = check_ppi_trigger(arch_timer_ppi[ARCH_TIMER_PHYS_NONSECURE_PPI]); enable_percpu_irq(arch_timer_ppi[ARCH_TIMER_PHYS_NONSECURE_PPI], flags); @@ -1129,6 +1134,8 @@ static void __init arch_counter_register(unsigned type) arch_timer_read_counter = rd; clocksource_counter.vdso_clock_mode = vdso_default; + if (vdso_default != VDSO_CLOCKMODE_NONE) + clocksource_counter.vdso_type = CLOCKSOURCE_VDSO_ARCHITECTED; } else { arch_timer_read_counter = arch_counter_get_cntvct_mem; scr = arch_counter_get_cntvct_mem; diff --git a/drivers/clocksource/arm_global_timer.c b/drivers/clocksource/arm_global_timer.c index 22a58d35a..86a8d729e 100644 --- a/drivers/clocksource/arm_global_timer.c +++ b/drivers/clocksource/arm_global_timer.c @@ -162,11 +162,11 @@ static irqreturn_t gt_clockevent_interrupt(int irq, void *dev_id) * the Global Timer flag _after_ having incremented * the Comparator register value to a higher value. */ - if (clockevent_state_oneshot(evt)) + if (clockevent_is_oob(evt) || clockevent_state_oneshot(evt)) gt_compare_set(ULONG_MAX, 0); writel_relaxed(GT_INT_STATUS_EVENT_FLAG, gt_base + GT_INT_STATUS); - evt->event_handler(evt); + clockevents_handle_event(evt); return IRQ_HANDLED; } @@ -177,7 +177,7 @@ static int gt_starting_cpu(unsigned int cpu) clk->name = "arm_global_timer"; clk->features = CLOCK_EVT_FEAT_PERIODIC | CLOCK_EVT_FEAT_ONESHOT | - CLOCK_EVT_FEAT_PERCPU; + CLOCK_EVT_FEAT_PERCPU | CLOCK_EVT_FEAT_PIPELINE; clk->set_state_shutdown = gt_clockevent_shutdown; clk->set_state_periodic = gt_clockevent_set_periodic; clk->set_state_oneshot = gt_clockevent_shutdown; @@ -201,11 +201,6 @@ static int gt_dying_cpu(unsigned int cpu) return 0; } -static u64 gt_clocksource_read(struct clocksource *cs) -{ - return gt_counter_read(); -} - static void gt_resume(struct clocksource *cs) { unsigned long ctrl; @@ -216,13 +211,15 @@ static void gt_resume(struct clocksource *cs) writel(GT_CONTROL_TIMER_ENABLE, gt_base + GT_CONTROL); } -static struct clocksource gt_clocksource = { - .name = "arm_global_timer", - .rating = 300, - .read = gt_clocksource_read, - .mask = CLOCKSOURCE_MASK(64), - .flags = CLOCK_SOURCE_IS_CONTINUOUS, - .resume = gt_resume, +static struct clocksource_user_mmio gt_clocksource = { + .mmio.clksrc = { + .name = "arm_global_timer", + .rating = 300, + .read = clocksource_dual_mmio_readl_up, + .mask = CLOCKSOURCE_MASK(64), + .flags = CLOCK_SOURCE_IS_CONTINUOUS, + .resume = gt_resume, + }, }; #ifdef CONFIG_CLKSRC_ARM_GLOBAL_TIMER_SCHED_CLOCK @@ -268,6 +265,8 @@ static void __init gt_delay_timer_init(void) static int __init gt_clocksource_init(void) { + struct clocksource_mmio_regs mmr; + writel(0, gt_base + GT_CONTROL); writel(0, gt_base + GT_COUNTER0); writel(0, gt_base + GT_COUNTER1); @@ -279,7 +278,13 @@ static int __init gt_clocksource_init(void) #ifdef CONFIG_CLKSRC_ARM_GLOBAL_TIMER_SCHED_CLOCK sched_clock_register(gt_sched_clock_read, 64, gt_target_rate); #endif - return clocksource_register_hz(>_clocksource, gt_target_rate); + mmr.reg_upper = gt_base + GT_COUNTER1; + mmr.reg_lower = gt_base + GT_COUNTER0; + mmr.bits_upper = 32; + mmr.bits_lower = 32; + mmr.revmap = NULL; + + return clocksource_user_mmio_init(>_clocksource, &mmr, gt_target_rate); } static int gt_clk_rate_change_cb(struct notifier_block *nb, @@ -398,8 +403,8 @@ static int __init global_timer_of_register(struct device_node *np) goto out_clk_nb; } - err = request_percpu_irq(gt_ppi, gt_clockevent_interrupt, - "gt", gt_evt); + err = __request_percpu_irq(gt_ppi, gt_clockevent_interrupt, + IRQF_TIMER, "gt", gt_evt); if (err) { pr_warn("global-timer: can't register interrupt %d (%d)\n", gt_ppi, err); diff --git a/drivers/clocksource/bcm2835_timer.c b/drivers/clocksource/bcm2835_timer.c index 319c0c780..4228f11f1 100644 --- a/drivers/clocksource/bcm2835_timer.c +++ b/drivers/clocksource/bcm2835_timer.c @@ -53,25 +53,33 @@ static int bcm2835_time_set_next_event(unsigned long event, static irqreturn_t bcm2835_time_interrupt(int irq, void *dev_id) { struct bcm2835_timer *timer = dev_id; - void (*event_handler)(struct clock_event_device *); + if (readl_relaxed(timer->control) & timer->match_mask) { writel_relaxed(timer->match_mask, timer->control); - event_handler = READ_ONCE(timer->evt.event_handler); - if (event_handler) - event_handler(&timer->evt); + clockevents_handle_event(&timer->evt); return IRQ_HANDLED; } else { return IRQ_NONE; } } +static struct clocksource_user_mmio clocksource_bcm2835 = { + .mmio.clksrc = { + .rating = 300, + .read = clocksource_mmio_readl_up, + .mask = CLOCKSOURCE_MASK(32), + .flags = CLOCK_SOURCE_IS_CONTINUOUS, + }, +}; + static int __init bcm2835_timer_init(struct device_node *node) { void __iomem *base; u32 freq; int irq, ret; struct bcm2835_timer *timer; + struct clocksource_mmio_regs mmr; base = of_iomap(node, 0); if (!base) { @@ -88,8 +96,13 @@ static int __init bcm2835_timer_init(struct device_node *node) system_clock = base + REG_COUNTER_LO; sched_clock_register(bcm2835_sched_read, 32, freq); - clocksource_mmio_init(base + REG_COUNTER_LO, node->name, - freq, 300, 32, clocksource_mmio_readl_up); + mmr.reg_lower = base + REG_COUNTER_LO; + mmr.bits_lower = 32; + mmr.reg_upper = 0; + mmr.bits_upper = 0; + mmr.revmap = NULL; + clocksource_bcm2835.mmio.clksrc.name = node->name; + clocksource_user_mmio_init(&clocksource_bcm2835, &mmr, freq); irq = irq_of_parse_and_map(node, DEFAULT_TIMER); if (irq <= 0) { @@ -109,7 +122,7 @@ static int __init bcm2835_timer_init(struct device_node *node) timer->match_mask = BIT(DEFAULT_TIMER); timer->evt.name = node->name; timer->evt.rating = 300; - timer->evt.features = CLOCK_EVT_FEAT_ONESHOT; + timer->evt.features = CLOCK_EVT_FEAT_ONESHOT | CLOCK_EVT_FEAT_PIPELINE; timer->evt.set_next_event = bcm2835_time_set_next_event; timer->evt.cpumask = cpumask_of(0); diff --git a/drivers/clocksource/clksrc_st_lpc.c b/drivers/clocksource/clksrc_st_lpc.c index 419a88687..b30b814d2 100644 --- a/drivers/clocksource/clksrc_st_lpc.c +++ b/drivers/clocksource/clksrc_st_lpc.c @@ -51,7 +51,7 @@ static int __init st_clksrc_init(void) sched_clock_register(st_clksrc_sched_clock_read, 32, rate); - ret = clocksource_mmio_init(ddata.base + LPC_LPT_LSB_OFF, + ret = clocksource_user_single_mmio_init(ddata.base + LPC_LPT_LSB_OFF, "clksrc-st-lpc", rate, 300, 32, clocksource_mmio_readl_up); if (ret) { diff --git a/drivers/clocksource/dw_apb_timer.c b/drivers/clocksource/dw_apb_timer.c index f5f24a95e..a974b9df4 100644 --- a/drivers/clocksource/dw_apb_timer.c +++ b/drivers/clocksource/dw_apb_timer.c @@ -43,7 +43,7 @@ ced_to_dw_apb_ced(struct clock_event_device *evt) static inline struct dw_apb_clocksource * clocksource_to_dw_apb_clocksource(struct clocksource *cs) { - return container_of(cs, struct dw_apb_clocksource, cs); + return container_of(cs, struct dw_apb_clocksource, ummio.mmio.clksrc); } static inline u32 apbt_readl(struct dw_apb_timer *timer, unsigned long offs) @@ -343,18 +343,6 @@ void dw_apb_clocksource_start(struct dw_apb_clocksource *dw_cs) dw_apb_clocksource_read(dw_cs); } -static u64 __apbt_read_clocksource(struct clocksource *cs) -{ - u32 current_count; - struct dw_apb_clocksource *dw_cs = - clocksource_to_dw_apb_clocksource(cs); - - current_count = apbt_readl_relaxed(&dw_cs->timer, - APBTMR_N_CURRENT_VALUE); - - return (u64)~current_count; -} - static void apbt_restart_clocksource(struct clocksource *cs) { struct dw_apb_clocksource *dw_cs = @@ -376,7 +364,7 @@ static void apbt_restart_clocksource(struct clocksource *cs) * dw_apb_clocksource_register() as the next step. */ struct dw_apb_clocksource * -dw_apb_clocksource_init(unsigned rating, const char *name, void __iomem *base, +__init dw_apb_clocksource_init(unsigned rating, const char *name, void __iomem *base, unsigned long freq) { struct dw_apb_clocksource *dw_cs = kzalloc(sizeof(*dw_cs), GFP_KERNEL); @@ -386,12 +374,12 @@ dw_apb_clocksource_init(unsigned rating, const char *name, void __iomem *base, dw_cs->timer.base = base; dw_cs->timer.freq = freq; - dw_cs->cs.name = name; - dw_cs->cs.rating = rating; - dw_cs->cs.read = __apbt_read_clocksource; - dw_cs->cs.mask = CLOCKSOURCE_MASK(32); - dw_cs->cs.flags = CLOCK_SOURCE_IS_CONTINUOUS; - dw_cs->cs.resume = apbt_restart_clocksource; + dw_cs->ummio.mmio.clksrc.name = name; + dw_cs->ummio.mmio.clksrc.rating = rating; + dw_cs->ummio.mmio.clksrc.read = clocksource_mmio_readl_down; + dw_cs->ummio.mmio.clksrc.mask = CLOCKSOURCE_MASK(32); + dw_cs->ummio.mmio.clksrc.flags = CLOCK_SOURCE_IS_CONTINUOUS; + dw_cs->ummio.mmio.clksrc.resume = apbt_restart_clocksource; return dw_cs; } @@ -401,9 +389,17 @@ dw_apb_clocksource_init(unsigned rating, const char *name, void __iomem *base, * * @dw_cs: The clocksource to register. */ -void dw_apb_clocksource_register(struct dw_apb_clocksource *dw_cs) +void __init dw_apb_clocksource_register(struct dw_apb_clocksource *dw_cs) { - clocksource_register_hz(&dw_cs->cs, dw_cs->timer.freq); + struct clocksource_mmio_regs mmr; + + mmr.reg_lower = dw_cs->timer.base + APBTMR_N_CURRENT_VALUE; + mmr.bits_lower = 32; + mmr.reg_upper = 0; + mmr.bits_upper = 0; + mmr.revmap = NULL; + + clocksource_user_mmio_init(&dw_cs->ummio, &mmr, dw_cs->timer.freq); } /** diff --git a/drivers/clocksource/exynos_mct.c b/drivers/clocksource/exynos_mct.c index ef8cb1b71..37e30fdee 100644 --- a/drivers/clocksource/exynos_mct.c +++ b/drivers/clocksource/exynos_mct.c @@ -200,23 +200,20 @@ static u32 notrace exynos4_read_count_32(void) return readl_relaxed(reg_base + EXYNOS4_MCT_G_CNT_L); } -static u64 exynos4_frc_read(struct clocksource *cs) -{ - return exynos4_read_count_32(); -} - static void exynos4_frc_resume(struct clocksource *cs) { exynos4_mct_frc_start(); } -static struct clocksource mct_frc = { - .name = "mct-frc", - .rating = MCT_CLKSOURCE_RATING, - .read = exynos4_frc_read, - .mask = CLOCKSOURCE_MASK(32), - .flags = CLOCK_SOURCE_IS_CONTINUOUS, - .resume = exynos4_frc_resume, +static struct clocksource_user_mmio mct_frc = { + .mmio.clksrc = { + .name = "mct-frc", + .rating = MCT_CLKSOURCE_RATING, + .read = clocksource_mmio_readl_up, + .mask = CLOCKSOURCE_MASK(32), + .flags = CLOCK_SOURCE_IS_CONTINUOUS, + .resume = exynos4_frc_resume, + }, }; static u64 notrace exynos4_read_sched_clock(void) @@ -237,12 +234,14 @@ static cycles_t exynos4_read_current_timer(void) static int __init exynos4_clocksource_init(bool frc_shared) { + struct clocksource_mmio_regs mmr; + /* * When the frc is shared, the main processer should have already * turned it on and we shouldn't be writing to TCON. */ if (frc_shared) - mct_frc.resume = NULL; + mct_frc.mmio.clksrc.resume = NULL; else exynos4_mct_frc_start(); @@ -252,8 +251,13 @@ static int __init exynos4_clocksource_init(bool frc_shared) register_current_timer_delay(&exynos4_delay_timer); #endif - if (clocksource_register_hz(&mct_frc, clk_rate)) - panic("%s: can't register clocksource\n", mct_frc.name); + mmr.reg_upper = NULL; + mmr.reg_lower = reg_base + EXYNOS4_MCT_G_CNT_L; + mmr.bits_upper = 0; + mmr.bits_lower = 32; + mmr.revmap = NULL; + if (clocksource_user_mmio_init(&mct_frc, &mmr, clk_rate)) + panic("%s: can't register clocksource\n", mct_frc.mmio.clksrc.name); sched_clock_register(exynos4_read_sched_clock, 32, clk_rate); @@ -321,7 +325,8 @@ static int mct_set_state_periodic(struct clock_event_device *evt) static struct clock_event_device mct_comp_device = { .name = "mct-comp", .features = CLOCK_EVT_FEAT_PERIODIC | - CLOCK_EVT_FEAT_ONESHOT, + CLOCK_EVT_FEAT_ONESHOT | + CLOCK_EVT_FEAT_PIPELINE, .rating = 250, .set_next_event = exynos4_comp_set_next_event, .set_state_periodic = mct_set_state_periodic, @@ -337,7 +342,7 @@ static irqreturn_t exynos4_mct_comp_isr(int irq, void *dev_id) exynos4_mct_write(0x1, EXYNOS4_MCT_G_INT_CSTAT); - evt->event_handler(evt); + clockevents_handle_event(evt); return IRQ_HANDLED; } @@ -348,7 +353,7 @@ static int exynos4_clockevent_init(void) clockevents_config_and_register(&mct_comp_device, clk_rate, 0xf, 0xffffffff); if (request_irq(mct_irqs[MCT_G0_IRQ], exynos4_mct_comp_isr, - IRQF_TIMER | IRQF_IRQPOLL, "mct_comp_irq", + IRQF_TIMER | IRQF_IRQPOLL | IRQF_OOB, "mct_comp_irq", &mct_comp_device)) pr_err("%s: request_irq() failed\n", "mct_comp_irq"); @@ -447,7 +452,7 @@ static irqreturn_t exynos4_mct_tick_isr(int irq, void *dev_id) exynos4_mct_tick_clear(mevt); - evt->event_handler(evt); + clockevents_handle_event(evt); return IRQ_HANDLED; } @@ -469,7 +474,7 @@ static int exynos4_mct_starting_cpu(unsigned int cpu) evt->set_state_oneshot_stopped = set_state_shutdown; evt->tick_resume = set_state_shutdown; evt->features = CLOCK_EVT_FEAT_PERIODIC | CLOCK_EVT_FEAT_ONESHOT | - CLOCK_EVT_FEAT_PERCPU; + CLOCK_EVT_FEAT_PERCPU | CLOCK_EVT_FEAT_PIPELINE; evt->rating = MCT_CLKEVENTS_RATING; exynos4_mct_write(TICK_BASE_CNT, mevt->base + MCT_L_TCNTB_OFFSET); @@ -563,9 +568,9 @@ static int __init exynos4_timer_interrupts(struct device_node *np, if (mct_int_type == MCT_INT_PPI) { - err = request_percpu_irq(mct_irqs[MCT_L0_IRQ], - exynos4_mct_tick_isr, "MCT", - &percpu_mct_tick); + err = __request_percpu_irq(mct_irqs[MCT_L0_IRQ], + exynos4_mct_tick_isr, IRQF_TIMER, + "MCT", &percpu_mct_tick); WARN(err, "MCT: can't request IRQ %d (%d)\n", mct_irqs[MCT_L0_IRQ], err); } else { diff --git a/drivers/clocksource/mmio.c b/drivers/clocksource/mmio.c index 9de751531..11cd38692 100644 --- a/drivers/clocksource/mmio.c +++ b/drivers/clocksource/mmio.c @@ -6,12 +6,31 @@ #include #include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include -struct clocksource_mmio { - void __iomem *reg; - struct clocksource clksrc; +struct clocksource_user_mapping { + struct mm_struct *mm; + struct clocksource_user_mmio *ucs; + void *regs; + struct hlist_node link; + atomic_t refs; }; +static struct class *user_mmio_class; +static dev_t user_mmio_devt; + +static DEFINE_SPINLOCK(user_clksrcs_lock); +static unsigned int user_clksrcs_count; +static LIST_HEAD(user_clksrcs); + static inline struct clocksource_mmio *to_mmio_clksrc(struct clocksource *c) { return container_of(c, struct clocksource_mmio, clksrc); @@ -37,6 +56,53 @@ u64 clocksource_mmio_readw_down(struct clocksource *c) return ~(u64)readw_relaxed(to_mmio_clksrc(c)->reg) & c->mask; } +static inline struct clocksource_user_mmio * +to_mmio_ucs(struct clocksource *c) +{ + return container_of(c, struct clocksource_user_mmio, mmio.clksrc); +} + +u64 clocksource_dual_mmio_readl_up(struct clocksource *c) +{ + struct clocksource_user_mmio *ucs = to_mmio_ucs(c); + u32 upper, old_upper, lower; + + upper = readl_relaxed(ucs->reg_upper); + do { + old_upper = upper; + lower = readl_relaxed(ucs->mmio.reg); + upper = readl_relaxed(ucs->reg_upper); + } while (upper != old_upper); + + return (((u64)upper) << ucs->bits_lower) | lower; +} + +u64 clocksource_dual_mmio_readw_up(struct clocksource *c) +{ + struct clocksource_user_mmio *ucs = to_mmio_ucs(c); + u16 upper, old_upper, lower; + + upper = readw_relaxed(ucs->reg_upper); + do { + old_upper = upper; + lower = readw_relaxed(ucs->mmio.reg); + upper = readw_relaxed(ucs->reg_upper); + } while (upper != old_upper); + + return (((u64)upper) << ucs->bits_lower) | lower; +} + +static void mmio_base_init(const char *name,int rating, unsigned int bits, + u64 (*read)(struct clocksource *), + struct clocksource *cs) +{ + cs->name = name; + cs->rating = rating; + cs->read = read; + cs->mask = CLOCKSOURCE_MASK(bits); + cs->flags = CLOCK_SOURCE_IS_CONTINUOUS; +} + /** * clocksource_mmio_init - Initialize a simple mmio based clocksource * @base: Virtual address of the clock readout register @@ -51,6 +117,7 @@ int __init clocksource_mmio_init(void __iomem *base, const char *name, u64 (*read)(struct clocksource *)) { struct clocksource_mmio *cs; + int err; if (bits > 64 || bits < 16) return -EINVAL; @@ -60,11 +127,428 @@ int __init clocksource_mmio_init(void __iomem *base, const char *name, return -ENOMEM; cs->reg = base; - cs->clksrc.name = name; - cs->clksrc.rating = rating; - cs->clksrc.read = read; - cs->clksrc.mask = CLOCKSOURCE_MASK(bits); - cs->clksrc.flags = CLOCK_SOURCE_IS_CONTINUOUS; + mmio_base_init(name, rating, bits, read, &cs->clksrc); + + err = clocksource_register_hz(&cs->clksrc, hz); + if (err < 0) { + kfree(cs); + return err; + } + + return err; +} + +static void mmio_ucs_vmopen(struct vm_area_struct *vma) +{ + struct clocksource_user_mapping *mapping, *clone; + struct clocksource_user_mmio *ucs; + unsigned long h_key; + + mapping = vma->vm_private_data; + + if (mapping->mm == vma->vm_mm) { + atomic_inc(&mapping->refs); + } else if (mapping->mm) { + /* + * We must be duplicating the original mm upon fork(), + * clone the parent ucs mapping struct then rehash it + * on the child mm key. If we cannot get memory for + * this, mitigate the issue for users by preventing a + * stale parent mm from being matched later on by a + * process which reused its mm_struct (h_key is based + * on this struct address). + */ + clone = kmalloc(sizeof(*mapping), GFP_KERNEL); + if (clone == NULL) { + pr_alert("out-of-memory for UCS mapping!\n"); + atomic_inc(&mapping->refs); + mapping->mm = NULL; + return; + } + ucs = mapping->ucs; + clone->mm = vma->vm_mm; + clone->ucs = ucs; + clone->regs = mapping->regs; + atomic_set(&clone->refs, 1); + vma->vm_private_data = clone; + h_key = (unsigned long)vma->vm_mm / sizeof(*vma->vm_mm); + spin_lock(&ucs->lock); + hash_add(ucs->mappings, &clone->link, h_key); + spin_unlock(&ucs->lock); + } +} + +static void mmio_ucs_vmclose(struct vm_area_struct *vma) +{ + struct clocksource_user_mapping *mapping; + + mapping = vma->vm_private_data; + + if (atomic_dec_and_test(&mapping->refs)) { + spin_lock(&mapping->ucs->lock); + hash_del(&mapping->link); + spin_unlock(&mapping->ucs->lock); + kfree(mapping); + } +} + +static const struct vm_operations_struct mmio_ucs_vmops = { + .open = mmio_ucs_vmopen, + .close = mmio_ucs_vmclose, +}; + +static int mmio_ucs_mmap(struct file *file, struct vm_area_struct *vma) +{ + unsigned long addr, upper_pfn, lower_pfn; + struct clocksource_user_mapping *mapping, *tmp; + struct clocksource_user_mmio *ucs; + unsigned int bits_upper; + unsigned long h_key; + pgprot_t prot; + size_t pages; + int err; + + pages = (vma->vm_end - vma->vm_start) >> PAGE_SHIFT; + if (pages > 2) + return -EINVAL; + + vma->vm_private_data = NULL; + + ucs = file->private_data; + upper_pfn = ucs->phys_upper >> PAGE_SHIFT; + lower_pfn = ucs->phys_lower >> PAGE_SHIFT; + bits_upper = fls(ucs->mmio.clksrc.mask) - ucs->bits_lower; + if (pages == 2 && (!bits_upper || upper_pfn == lower_pfn)) + return -EINVAL; + + mapping = kmalloc(sizeof(*mapping), GFP_KERNEL); + if (!mapping) + return -ENOSPC; + + mapping->mm = vma->vm_mm; + mapping->ucs = ucs; + mapping->regs = (void *)vma->vm_start; + atomic_set(&mapping->refs, 1); + + vma->vm_private_data = mapping; + vma->vm_ops = &mmio_ucs_vmops; + prot = pgprot_noncached(vma->vm_page_prot); + addr = vma->vm_start; + + err = remap_pfn_range(vma, addr, lower_pfn, PAGE_SIZE, prot); + if (err < 0) + goto fail; + + if (pages > 1) { + addr += PAGE_SIZE; + err = remap_pfn_range(vma, addr, upper_pfn, PAGE_SIZE, prot); + if (err < 0) + goto fail; + } + + h_key = (unsigned long)vma->vm_mm / sizeof(*vma->vm_mm); + + spin_lock(&ucs->lock); + hash_for_each_possible(ucs->mappings, tmp, link, h_key) { + if (tmp->mm == vma->vm_mm) { + spin_unlock(&ucs->lock); + err = -EBUSY; + goto fail; + } + } + hash_add(ucs->mappings, &mapping->link, h_key); + spin_unlock(&ucs->lock); + + return 0; +fail: + kfree(mapping); + + return err; +} + +static long +mmio_ucs_ioctl(struct file *file, unsigned int cmd, unsigned long arg) +{ + struct clocksource_user_mapping *mapping; + struct clksrc_user_mmio_info __user *u; + unsigned long upper_pfn, lower_pfn; + struct clksrc_user_mmio_info info; + struct clocksource_user_mmio *ucs; + unsigned int bits_upper; + void __user *map_base; + unsigned long h_key; + size_t size; + + u = (struct clksrc_user_mmio_info __user *)arg; + + switch (cmd) { + case CLKSRC_USER_MMIO_MAP: + break; + default: + return -ENOTTY; + } + + h_key = (unsigned long)current->mm / sizeof(*current->mm); + + ucs = file->private_data; + upper_pfn = ucs->phys_upper >> PAGE_SHIFT; + lower_pfn = ucs->phys_lower >> PAGE_SHIFT; + bits_upper = fls(ucs->mmio.clksrc.mask) - ucs->bits_lower; + size = PAGE_SIZE; + if (bits_upper && upper_pfn != lower_pfn) + size += PAGE_SIZE; + + do { + spin_lock(&ucs->lock); + hash_for_each_possible(ucs->mappings, mapping, link, h_key) { + if (mapping->mm == current->mm) { + spin_unlock(&ucs->lock); + map_base = mapping->regs; + goto found; + } + } + spin_unlock(&ucs->lock); + + map_base = (void *) + vm_mmap(file, 0, size, PROT_READ, MAP_SHARED, 0); + } while (IS_ERR(map_base) && PTR_ERR(map_base) == -EBUSY); + + if (IS_ERR(map_base)) + return PTR_ERR(map_base); + +found: + info.type = ucs->type; + info.reg_lower = map_base + offset_in_page(ucs->phys_lower); + info.mask_lower = ucs->mmio.clksrc.mask; + info.bits_lower = ucs->bits_lower; + info.reg_upper = NULL; + if (ucs->phys_upper) + info.reg_upper = map_base + (size - PAGE_SIZE) + + offset_in_page(ucs->phys_upper); + info.mask_upper = ucs->mask_upper; + + return copy_to_user(u, &info, sizeof(*u)); +} + +static int mmio_ucs_open(struct inode *inode, struct file *file) +{ + struct clocksource_user_mmio *ucs; + + if (file->f_mode & FMODE_WRITE) + return -EINVAL; + + ucs = container_of(inode->i_cdev, typeof(*ucs), cdev); + file->private_data = ucs; + + return 0; +} + +static const struct file_operations mmio_ucs_fops = { + .owner = THIS_MODULE, + .unlocked_ioctl = mmio_ucs_ioctl, + .open = mmio_ucs_open, + .mmap = mmio_ucs_mmap, +}; + +static int __init +ucs_create_cdev(struct class *class, struct clocksource_user_mmio *ucs) +{ + int err; + + ucs->dev = device_create(class, NULL, + MKDEV(MAJOR(user_mmio_devt), ucs->id), + ucs, "ucs/%d", ucs->id); + if (IS_ERR(ucs->dev)) + return PTR_ERR(ucs->dev); + + spin_lock_init(&ucs->lock); + hash_init(ucs->mappings); + + cdev_init(&ucs->cdev, &mmio_ucs_fops); + ucs->cdev.kobj.parent = &ucs->dev->kobj; + + err = cdev_add(&ucs->cdev, ucs->dev->devt, 1); + if (err < 0) + goto err_device_destroy; + + return 0; + +err_device_destroy: + device_destroy(class, MKDEV(MAJOR(user_mmio_devt), ucs->id)); + return err; +} + +static unsigned long default_revmap(void *virt) +{ + struct vm_struct *vm; + + vm = find_vm_area(virt); + if (!vm) + return 0; + + return vm->phys_addr + (virt - vm->addr); +} + +int __init clocksource_user_mmio_init(struct clocksource_user_mmio *ucs, + const struct clocksource_mmio_regs *regs, + unsigned long hz) +{ + static u64 (*user_types[CLKSRC_MMIO_TYPE_NR])(struct clocksource *) = { + [CLKSRC_MMIO_L_UP] = clocksource_mmio_readl_up, + [CLKSRC_MMIO_L_DOWN] = clocksource_mmio_readl_down, + [CLKSRC_DMMIO_L_UP] = clocksource_dual_mmio_readl_up, + [CLKSRC_MMIO_W_UP] = clocksource_mmio_readw_up, + [CLKSRC_MMIO_W_DOWN] = clocksource_mmio_readw_down, + [CLKSRC_DMMIO_W_UP] = clocksource_dual_mmio_readw_up, + }; + const char *name = ucs->mmio.clksrc.name; + unsigned long phys_upper = 0, phys_lower; + enum clksrc_user_mmio_type type; + unsigned long (*revmap)(void *); + int err; + + if (regs->bits_lower > 32 || regs->bits_lower < 16 || + regs->bits_upper > 32) + return -EINVAL; + + for (type = 0; type < ARRAY_SIZE(user_types); type++) + if (ucs->mmio.clksrc.read == user_types[type]) + break; + + if (type == ARRAY_SIZE(user_types)) + return -EINVAL; + + if (!(ucs->mmio.clksrc.flags & CLOCK_SOURCE_IS_CONTINUOUS)) + return -EINVAL; + + revmap = regs->revmap; + if (!revmap) + revmap = default_revmap; + + phys_lower = revmap(regs->reg_lower); + if (!phys_lower) + return -EINVAL; + + if (regs->bits_upper) { + phys_upper = revmap(regs->reg_upper); + if (!phys_upper) + return -EINVAL; + } + + ucs->mmio.reg = regs->reg_lower; + ucs->type = type; + ucs->bits_lower = regs->bits_lower; + ucs->reg_upper = regs->reg_upper; + ucs->mask_lower = CLOCKSOURCE_MASK(regs->bits_lower); + ucs->mask_upper = CLOCKSOURCE_MASK(regs->bits_upper); + ucs->phys_lower = phys_lower; + ucs->phys_upper = phys_upper; + spin_lock_init(&ucs->lock); + + err = clocksource_register_hz(&ucs->mmio.clksrc, hz); + if (err < 0) + return err; + + spin_lock(&user_clksrcs_lock); + + ucs->id = user_clksrcs_count++; + if (ucs->id < CLKSRC_USER_MMIO_MAX) + list_add_tail(&ucs->link, &user_clksrcs); + + spin_unlock(&user_clksrcs_lock); + + if (ucs->id >= CLKSRC_USER_MMIO_MAX) { + pr_warn("%s: Too many clocksources\n", name); + err = -EAGAIN; + goto fail; + } + + ucs->mmio.clksrc.vdso_type = CLOCKSOURCE_VDSO_MMIO + ucs->id; + + if (user_mmio_class) { + err = ucs_create_cdev(user_mmio_class, ucs); + if (err < 0) { + pr_warn("%s: Failed to add character device\n", name); + goto fail; + } + } + + return 0; + +fail: + clocksource_unregister(&ucs->mmio.clksrc); + + return err; +} + +int __init clocksource_user_single_mmio_init( + void __iomem *base, const char *name, + unsigned long hz, int rating, unsigned int bits, + u64 (*read)(struct clocksource *)) +{ + struct clocksource_user_mmio *ucs; + struct clocksource_mmio_regs regs; + int ret; + + ucs = kzalloc(sizeof(*ucs), GFP_KERNEL); + if (!ucs) + return -ENOMEM; + + mmio_base_init(name, rating, bits, read, &ucs->mmio.clksrc); + regs.reg_lower = base; + regs.reg_upper = NULL; + regs.bits_lower = bits; + regs.bits_upper = 0; + regs.revmap = NULL; + + ret = clocksource_user_mmio_init(ucs, ®s, hz); + if (ret) + kfree(ucs); + + return ret; +} + +static int __init mmio_clksrc_chr_dev_init(void) +{ + struct clocksource_user_mmio *ucs; + struct class *class; + int err; + + class = class_create("mmio_ucs"); + if (IS_ERR(class)) { + pr_err("couldn't create user mmio clocksources class\n"); + return PTR_ERR(class); + } + + err = alloc_chrdev_region(&user_mmio_devt, 0, CLKSRC_USER_MMIO_MAX, + "mmio_ucs"); + if (err < 0) { + pr_err("failed to allocate user mmio clocksources character devivces region\n"); + goto err_class_destroy; + } + + /* + * Calling list_for_each_entry is safe here: clocksources are always + * added to the list tail, never removed. + */ + spin_lock(&user_clksrcs_lock); + list_for_each_entry(ucs, &user_clksrcs, link) { + spin_unlock(&user_clksrcs_lock); + + err = ucs_create_cdev(class, ucs); + if (err < 0) + pr_err("%s: Failed to add character device\n", + ucs->mmio.clksrc.name); + + spin_lock(&user_clksrcs_lock); + } + user_mmio_class = class; + spin_unlock(&user_clksrcs_lock); + + return 0; - return clocksource_register_hz(&cs->clksrc, hz); +err_class_destroy: + class_destroy(class); + return err; } +device_initcall(mmio_clksrc_chr_dev_init); diff --git a/drivers/clocksource/timer-imx-gpt.c b/drivers/clocksource/timer-imx-gpt.c index 6a878d227..bb5aef1ee 100644 --- a/drivers/clocksource/timer-imx-gpt.c +++ b/drivers/clocksource/timer-imx-gpt.c @@ -163,8 +163,8 @@ static int __init mxc_clocksource_init(struct imx_timer *imxtm) sched_clock_reg = reg; sched_clock_register(mxc_read_sched_clock, 32, c); - return clocksource_mmio_init(reg, "mxc_timer1", c, 200, 32, - clocksource_mmio_readl_up); + return clocksource_user_single_mmio_init(reg, "mxc_timer1", c, 200, 32, + clocksource_mmio_readl_up); } /* clock event */ @@ -264,7 +264,7 @@ static irqreturn_t mxc_timer_interrupt(int irq, void *dev_id) imxtm->gpt->gpt_irq_acknowledge(imxtm); - ced->event_handler(ced); + clockevents_handle_event(ced); return IRQ_HANDLED; } @@ -274,7 +274,7 @@ static int __init mxc_clockevent_init(struct imx_timer *imxtm) struct clock_event_device *ced = &imxtm->ced; ced->name = "mxc_timer1"; - ced->features = CLOCK_EVT_FEAT_ONESHOT | CLOCK_EVT_FEAT_DYNIRQ; + ced->features = CLOCK_EVT_FEAT_ONESHOT | CLOCK_EVT_FEAT_DYNIRQ | CLOCK_EVT_FEAT_PIPELINE; ced->set_state_shutdown = mxc_shutdown; ced->set_state_oneshot = mxc_set_oneshot; ced->tick_resume = mxc_shutdown; diff --git a/drivers/clocksource/timer-sun4i.c b/drivers/clocksource/timer-sun4i.c index 7bdcc60ad..5aaa25161 100644 --- a/drivers/clocksource/timer-sun4i.c +++ b/drivers/clocksource/timer-sun4i.c @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -133,7 +134,7 @@ static irqreturn_t sun4i_timer_interrupt(int irq, void *dev_id) struct timer_of *to = to_timer_of(evt); sun4i_timer_clear_interrupt(timer_of_base(to)); - evt->event_handler(evt); + clockevents_handle_event(evt); return IRQ_HANDLED; } @@ -145,7 +146,7 @@ static struct timer_of to = { .name = "sun4i_tick", .rating = 350, .features = CLOCK_EVT_FEAT_PERIODIC | CLOCK_EVT_FEAT_ONESHOT | - CLOCK_EVT_FEAT_DYNIRQ, + CLOCK_EVT_FEAT_DYNIRQ | CLOCK_EVT_FEAT_PIPELINE, .set_state_shutdown = sun4i_clkevt_shutdown, .set_state_periodic = sun4i_clkevt_set_periodic, .set_state_oneshot = sun4i_clkevt_set_oneshot, diff --git a/drivers/clocksource/timer-ti-dm-systimer.c b/drivers/clocksource/timer-ti-dm-systimer.c index d1c144d6f..875c5038f 100644 --- a/drivers/clocksource/timer-ti-dm-systimer.c +++ b/drivers/clocksource/timer-ti-dm-systimer.c @@ -57,7 +57,7 @@ struct dmtimer_clockevent { }; struct dmtimer_clocksource { - struct clocksource dev; + struct clocksource_user_mmio mmio; struct dmtimer_systimer t; unsigned int loadval; }; @@ -437,7 +437,7 @@ static irqreturn_t dmtimer_clockevent_interrupt(int irq, void *data) struct dmtimer_systimer *t = &clkevt->t; writel_relaxed(OMAP_TIMER_INT_OVERFLOW, t->base + t->irq_stat); - clkevt->dev.event_handler(&clkevt->dev); + clockevents_handle_event(&clkevt->dev); return IRQ_HANDLED; } @@ -548,7 +548,7 @@ static int __init dmtimer_clkevt_init_common(struct dmtimer_clockevent *clkevt, * We mostly use cpuidle_coupled with ARM local timers for runtime, * so there's probably no use for CLOCK_EVT_FEAT_DYNIRQ here. */ - dev->features = features; + dev->features = features | CLOCK_EVT_FEAT_PIPELINE; dev->rating = rating; dev->set_next_event = dmtimer_set_next_event; dev->set_state_shutdown = dmtimer_clockevent_shutdown; @@ -706,15 +706,7 @@ static int __init dmtimer_percpu_quirk_init(struct device_node *np, u32 pa) static struct dmtimer_clocksource * to_dmtimer_clocksource(struct clocksource *cs) { - return container_of(cs, struct dmtimer_clocksource, dev); -} - -static u64 dmtimer_clocksource_read_cycles(struct clocksource *cs) -{ - struct dmtimer_clocksource *clksrc = to_dmtimer_clocksource(cs); - struct dmtimer_systimer *t = &clksrc->t; - - return (u64)readl_relaxed(t->base + t->counter); + return container_of(cs, struct dmtimer_clocksource, mmio.mmio.clksrc); } static void __iomem *dmtimer_sched_clock_counter; @@ -753,6 +745,7 @@ static void dmtimer_clocksource_resume(struct clocksource *cs) static int __init dmtimer_clocksource_init(struct device_node *np) { struct dmtimer_clocksource *clksrc; + struct clocksource_mmio_regs mmr; struct dmtimer_systimer *t; struct clocksource *dev; int error; @@ -761,7 +754,7 @@ static int __init dmtimer_clocksource_init(struct device_node *np) if (!clksrc) return -ENOMEM; - dev = &clksrc->dev; + dev = &clksrc->mmio.mmio.clksrc; t = &clksrc->t; error = dmtimer_systimer_setup(np, t); @@ -770,7 +763,7 @@ static int __init dmtimer_clocksource_init(struct device_node *np) dev->name = "dmtimer"; dev->rating = 300; - dev->read = dmtimer_clocksource_read_cycles; + dev->read = clocksource_mmio_readl_up, dev->mask = CLOCKSOURCE_MASK(32); dev->flags = CLOCK_SOURCE_IS_CONTINUOUS; @@ -793,7 +786,13 @@ static int __init dmtimer_clocksource_init(struct device_node *np) sched_clock_register(dmtimer_read_sched_clock, 32, t->rate); } - if (clocksource_register_hz(dev, t->rate)) + mmr.reg_lower = t->base + t->counter; + mmr.bits_lower = 32; + mmr.reg_upper = 0; + mmr.bits_upper = 0; + mmr.revmap = NULL; + + if (clocksource_user_mmio_init(&clksrc->mmio, &mmr, t->rate)) pr_err("Could not register clocksource %pOF\n", np); return 0; diff --git a/drivers/cpuidle/cpuidle.c b/drivers/cpuidle/cpuidle.c index 737a026ef..c936b17bf 100644 --- a/drivers/cpuidle/cpuidle.c +++ b/drivers/cpuidle/cpuidle.c @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -220,6 +221,23 @@ noinstr int cpuidle_enter_state(struct cpuidle_device *dev, instrumentation_begin(); + /* + * A companion core running on the oob stage of the IRQ + * pipeline may deny switching to a deeper C-state. If so, + * call the default idle routine instead. If the core cannot + * bear with the latency induced by the default idling + * operation, then CPUIDLE is not usable and should be + * disabled at build time. The in-band stage is currently + * stalled, hard irqs are on. irq_cpuidle_enter() turns off + * hard irqs before synchronizing the in-band stage, making + * sure we have no event lingering in the interrupt log as we + * may go for a nap. + */ + if (!irq_cpuidle_enter(dev, target_state)) { + default_idle_call(); + return -EBUSY; + } + /* * Tell the time framework to switch to a broadcast timer because our * local timer will be shut down. If a local timer is used from another @@ -269,6 +287,7 @@ noinstr int cpuidle_enter_state(struct cpuidle_device *dev, if (WARN_ONCE(!irqs_disabled(), "%ps leaked IRQ state", target_state->enter)) raw_local_irq_disable(); + hard_cond_local_irq_enable(); if (!(target_state->flags & CPUIDLE_FLAG_RCU_IDLE)) { instrumentation_end(); ct_cpuidle_exit(); diff --git a/drivers/cpuidle/poll_state.c b/drivers/cpuidle/poll_state.c index 9b6d90a72..d86fe8983 100644 --- a/drivers/cpuidle/poll_state.c +++ b/drivers/cpuidle/poll_state.c @@ -20,6 +20,7 @@ static int __cpuidle poll_idle(struct cpuidle_device *dev, dev->poll_time_limit = false; raw_local_irq_enable(); + hard_cond_local_irq_enable(); if (!current_set_polling_and_test()) { unsigned int loop_count = 0; u64 limit; diff --git a/drivers/dma/Kconfig b/drivers/dma/Kconfig index e8e029bab..57c8d5156 100644 --- a/drivers/dma/Kconfig +++ b/drivers/dma/Kconfig @@ -47,6 +47,10 @@ config DMA_ENGINE config DMA_VIRTUAL_CHANNELS tristate +config DMA_VIRTUAL_CHANNELS_OOB + def_bool n + depends on DMA_VIRTUAL_CHANNELS && DOVETAIL + config DMA_ACPI def_bool y depends on ACPI @@ -140,6 +144,13 @@ config DMA_BCM2835 select DMA_ENGINE select DMA_VIRTUAL_CHANNELS +config DMA_BCM2835_OOB + bool "Out-of-band support for BCM2835 DMA" + depends on DMA_BCM2835 && DOVETAIL + select DMA_VIRTUAL_CHANNELS_OOB + help + Enable out-of-band requests to BCM2835 DMA. + config DMA_JZ4780 tristate "JZ4780 DMA support" depends on MIPS || COMPILE_TEST @@ -279,6 +290,13 @@ config IMX_SDMA Support the i.MX SDMA engine. This engine is integrated into Freescale i.MX25/31/35/51/53/6 chips. +config IMX_SDMA_OOB + bool "Out-of-band support for i.MX SDMA" + depends on IMX_SDMA && DOVETAIL + select DMA_VIRTUAL_CHANNELS_OOB + help + Enable out-of-band requests to i.MX SDMA. + config INTEL_IDMA64 tristate "Intel integrated DMA 64-bit support" depends on HAS_IOMEM diff --git a/drivers/dma/bcm2835-dma.c b/drivers/dma/bcm2835-dma.c index e159f976a..0f15a1116 100644 --- a/drivers/dma/bcm2835-dma.c +++ b/drivers/dma/bcm2835-dma.c @@ -31,6 +31,7 @@ #include #include #include +#include #include #include @@ -746,6 +747,17 @@ static void bcm2835_dma_abort(struct bcm2835_chan *c) } } +static inline void bcm2835_dma_enable_channel(struct bcm2835_chan *c) +{ + writel(c->desc->cb_list[0].paddr, c->chan_base + BCM2835_DMA_ADDR); + writel(BCM2835_DMA_ACTIVE, c->chan_base + BCM2835_DMA_CS); +} + +static inline bool bcm2835_dma_oob_capable(void) +{ + return IS_ENABLED(CONFIG_DMA_BCM2835_OOB); +} + static void bcm2835_dma_start_desc(struct bcm2835_chan *c) { struct virt_dma_desc *vd = vchan_next_desc(&c->vc); @@ -768,8 +780,8 @@ static void bcm2835_dma_start_desc(struct bcm2835_chan *c) } else { writel(BIT(31), c->chan_base + BCM2835_DMA_CS); - writel(c->is_2712 ? to_40bit_cbaddr(d->cb_list[0].paddr) : d->cb_list[0].paddr, - c->chan_base + BCM2835_DMA_ADDR); + writel(c->is_2712 ? to_40bit_cbaddr(d->cb_list[0].paddr) : (d->cb_list[0].paddr), + (c->chan_base + BCM2835_DMA_ADDR)); writel(BCM2835_DMA_ACTIVE | BCM2835_DMA_CS_FLAGS(c->dreq), c->chan_base + BCM2835_DMA_CS); } @@ -790,7 +802,12 @@ static irqreturn_t bcm2835_dma_callback(int irq, void *data) return IRQ_NONE; } - spin_lock_irqsave(&c->vc.lock, flags); + /* + * Hybrid locking of oob-enabled vchans ensures that hard IRQ + * are disabled across the locked section, including from the + * in-band stage. + */ + vchan_lock(&c->vc); /* * Clear the INT flag to receive further interrupts. Keep the channel @@ -917,7 +934,7 @@ static enum dma_status bcm2835_dma_tx_status(struct dma_chan *chan, if (ret == DMA_COMPLETE || !txstate) return ret; - spin_lock_irqsave(&c->vc.lock, flags); + vchan_lock_irqsave(&c->vc, flags); vd = vchan_find_desc(&c->vc, cookie); if (vd) { txstate->residue = @@ -951,7 +968,7 @@ static enum dma_status bcm2835_dma_tx_status(struct dma_chan *chan, txstate->residue = 0; } - spin_unlock_irqrestore(&c->vc.lock, flags); + vchan_unlock_irqrestore(&c->vc, flags); return ret; } @@ -961,13 +978,36 @@ static void bcm2835_dma_issue_pending(struct dma_chan *chan) struct bcm2835_chan *c = to_bcm2835_dma_chan(chan); unsigned long flags; - spin_lock_irqsave(&c->vc.lock, flags); + vchan_lock_irqsave(&c->vc, flags); if (vchan_issue_pending(&c->vc) && !c->desc) bcm2835_dma_start_desc(c); - spin_unlock_irqrestore(&c->vc.lock, flags); + vchan_unlock_irqrestore(&c->vc, flags); } +#ifdef CONFIG_DMA_BCM2835_OOB +static int bcm2835_dma_pulse_oob(struct dma_chan *chan) +{ + struct bcm2835_chan *c = to_bcm2835_dma_chan(chan); + unsigned long flags; + int ret = -EIO; + + vchan_lock_irqsave(&c->vc, flags); + if (c->desc && vchan_oob_pulsed(&c->desc->vd)) { + bcm2835_dma_enable_channel(c); + ret = 0; + } + vchan_unlock_irqrestore(&c->vc, flags); + + return ret; +} +#else +static int bcm2835_dma_pulse_oob(struct dma_chan *chan) +{ + return -ENOTSUPP; +} +#endif + static struct dma_async_tx_descriptor *bcm2835_dma_prep_dma_memcpy( struct dma_chan *chan, dma_addr_t dst, dma_addr_t src, size_t len, unsigned long flags) @@ -1012,6 +1052,15 @@ static struct dma_async_tx_descriptor *bcm2835_dma_prep_slave_sg( u32 extra = BCM2835_DMA_INT_EN; size_t frames; + if (!bcm2835_dma_oob_capable()) { + if (flags & (DMA_OOB_INTERRUPT|DMA_OOB_PULSE)) { + dev_err(chan->device->dev, + "%s: out-of-band slave transfers disabled\n", + __func__); + return NULL; + } + } + if (!is_slave_direction(direction)) { dev_err(chan->device->dev, "%s: bad direction?\n", __func__); @@ -1078,7 +1127,21 @@ static struct dma_async_tx_descriptor *bcm2835_dma_prep_dma_cyclic( return NULL; } - if (flags & DMA_PREP_INTERRUPT) + if (!bcm2835_dma_oob_capable()) { + if (flags & DMA_OOB_INTERRUPT) { + dev_err(chan->device->dev, + "%s: out-of-band cyclic transfers disabled\n", + __func__); + return NULL; + } + } else if (flags & DMA_OOB_PULSE) { + dev_err(chan->device->dev, + "%s: no pulse mode with out-of-band cyclic transfers\n", + __func__); + return NULL; + } + + if (flags & (DMA_PREP_INTERRUPT|DMA_OOB_INTERRUPT)) extra |= BCM2835_DMA_INT_EN; else period_len = buf_len; @@ -1160,7 +1223,7 @@ static int bcm2835_dma_terminate_all(struct dma_chan *chan) unsigned long flags; LIST_HEAD(head); - spin_lock_irqsave(&c->vc.lock, flags); + vchan_lock_irqsave(&c->vc, flags); /* stop DMA activity */ if (c->desc) { @@ -1170,7 +1233,7 @@ static int bcm2835_dma_terminate_all(struct dma_chan *chan) } vchan_get_all_descriptors(&c->vc, &head); - spin_unlock_irqrestore(&c->vc.lock, flags); + vchan_unlock_irqrestore(&c->vc, flags); vchan_dma_desc_free_list(&c->vc, &head); return 0; @@ -1353,11 +1416,13 @@ static int bcm2835_dma_probe(struct platform_device *pdev) dma_cap_set(DMA_SLAVE, od->ddev.cap_mask); dma_cap_set(DMA_PRIVATE, od->ddev.cap_mask); dma_cap_set(DMA_CYCLIC, od->ddev.cap_mask); + dma_cap_set(DMA_OOB, od->ddev.cap_mask); dma_cap_set(DMA_MEMCPY, od->ddev.cap_mask); od->ddev.device_alloc_chan_resources = bcm2835_dma_alloc_chan_resources; od->ddev.device_free_chan_resources = bcm2835_dma_free_chan_resources; od->ddev.device_tx_status = bcm2835_dma_tx_status; od->ddev.device_issue_pending = bcm2835_dma_issue_pending; + od->ddev.device_pulse_oob = bcm2835_dma_pulse_oob; od->ddev.device_prep_dma_cyclic = bcm2835_dma_prep_dma_cyclic; od->ddev.device_prep_slave_sg = bcm2835_dma_prep_slave_sg; od->ddev.device_prep_dma_memcpy = bcm2835_dma_prep_dma_memcpy; diff --git a/drivers/dma/dmaengine.c b/drivers/dma/dmaengine.c index 491b22240..261439414 100644 --- a/drivers/dma/dmaengine.c +++ b/drivers/dma/dmaengine.c @@ -579,7 +579,8 @@ int dma_get_slave_caps(struct dma_chan *chan, struct dma_slave_caps *caps) /* check if the channel supports slave transactions */ if (!(test_bit(DMA_SLAVE, device->cap_mask.bits) || - test_bit(DMA_CYCLIC, device->cap_mask.bits))) + test_bit(DMA_CYCLIC, device->cap_mask.bits) || + test_bit(DMA_OOB, device->cap_mask.bits))) return -ENXIO; /* @@ -1183,6 +1184,12 @@ int dma_async_device_register(struct dma_device *device) return -EIO; } + if (dma_has_cap(DMA_OOB, device->cap_mask) && !device->device_pulse_oob) { + dev_err(device->dev, + "Device claims capability DMA_OOB, but pulse handler is not defined\n"); + return -EIO; + } + if (!device->device_release) dev_dbg(device->dev, "WARN: Device release is not defined so it is not safe to unbind this driver while in use\n"); diff --git a/drivers/dma/imx-sdma.c b/drivers/dma/imx-sdma.c index 51012bd39..758c8db45 100644 --- a/drivers/dma/imx-sdma.c +++ b/drivers/dma/imx-sdma.c @@ -535,6 +535,10 @@ struct sdma_engine { /* clock ratio for AHB:SDMA core. 1:1 is 1, 2:1 is 0*/ bool clk_ratio; bool fw_loaded; +#ifdef CONFIG_IMX_SDMA_OOB + hard_spinlock_t oob_lock; + u32 pending_stat; +#endif }; static int sdma_config_write(struct dma_chan *chan, @@ -828,6 +832,11 @@ static struct sdma_desc *to_sdma_desc(struct dma_async_tx_descriptor *t) return container_of(t, struct sdma_desc, vd.tx); } +static inline bool sdma_oob_capable(void) +{ + return IS_ENABLED(CONFIG_IMX_SDMA_OOB); +} + static void sdma_start_desc(struct sdma_channel *sdmac) { struct virt_dma_desc *vd = vchan_next_desc(&sdmac->vc); @@ -845,7 +854,8 @@ static void sdma_start_desc(struct sdma_channel *sdmac) sdma->channel_control[channel].base_bd_ptr = desc->bd_phys; sdma->channel_control[channel].current_bd_ptr = desc->bd_phys; - sdma_enable_channel(sdma, sdmac->channel); + if (!sdma_oob_capable() || !vchan_oob_pulsed(vd)) + sdma_enable_channel(sdma, sdmac->channel); } static void sdma_update_channel_loop(struct sdma_channel *sdmac) @@ -888,9 +898,9 @@ static void sdma_update_channel_loop(struct sdma_channel *sdmac) * SDMA transaction status by the time the client tasklet is * executed. */ - spin_unlock(&sdmac->vc.lock); + vchan_unlock(&sdmac->vc); dmaengine_desc_get_callback_invoke(&desc->vd.tx, NULL); - spin_lock(&sdmac->vc.lock); + vchan_lock(&sdmac->vc); /* Assign buffer ownership to SDMA */ bd->mode.status |= BD_DONE; @@ -912,20 +922,21 @@ static void sdma_update_channel_loop(struct sdma_channel *sdmac) static void mxc_sdma_handle_channel_normal(struct sdma_channel *data) { struct sdma_channel *sdmac = (struct sdma_channel *) data; + struct sdma_desc *desc = sdmac->desc; struct sdma_buffer_descriptor *bd; int i, error = 0; - sdmac->desc->chn_real_count = 0; + desc->chn_real_count = 0; /* * non loop mode. Iterate over all descriptors, collect * errors and call callback function */ - for (i = 0; i < sdmac->desc->num_bd; i++) { - bd = &sdmac->desc->bd[i]; + for (i = 0; i < desc->num_bd; i++) { + bd = &desc->bd[i]; if (bd->mode.status & (BD_DONE | BD_RROR)) error = -EIO; - sdmac->desc->chn_real_count += bd->mode.count; + desc->chn_real_count += bd->mode.count; } if (error) @@ -934,24 +945,21 @@ static void mxc_sdma_handle_channel_normal(struct sdma_channel *data) sdmac->status = DMA_COMPLETE; } -static irqreturn_t sdma_int_handler(int irq, void *dev_id) +static unsigned long sdma_do_channels(struct sdma_engine *sdma, + unsigned long stat) { - struct sdma_engine *sdma = dev_id; - unsigned long stat; + unsigned long mask = stat; - stat = readl_relaxed(sdma->regs + SDMA_H_INTR); - writel_relaxed(stat, sdma->regs + SDMA_H_INTR); - /* channel 0 is special and not handled here, see run_channel0() */ - stat &= ~1; - - while (stat) { - int channel = fls(stat) - 1; + while (mask) { + int channel = fls(mask) - 1; struct sdma_channel *sdmac = &sdma->channel[channel]; struct sdma_desc *desc; - spin_lock(&sdmac->vc.lock); + vchan_lock(&sdmac->vc); desc = sdmac->desc; if (desc) { + if (running_oob() && !vchan_oob_handled(&desc->vd)) + goto next; if (sdmac->flags & IMX_DMA_SG_LOOP) { if (sdmac->peripheral_type != IMX_DMATYPE_HDMI) sdma_update_channel_loop(sdmac); @@ -959,15 +967,69 @@ static irqreturn_t sdma_int_handler(int irq, void *dev_id) vchan_cyclic_callback(&desc->vd); } else { mxc_sdma_handle_channel_normal(sdmac); + if (running_oob()) { + vchan_unlock(&sdmac->vc); + dmaengine_desc_get_callback_invoke(&desc->vd.tx, NULL); + __clear_bit(channel, &stat); + goto next_unlocked; + } vchan_cookie_complete(&desc->vd); sdma_start_desc(sdmac); } } - - spin_unlock(&sdmac->vc.lock); __clear_bit(channel, &stat); + next: + vchan_unlock(&sdmac->vc); + next_unlocked: + __clear_bit(channel, &mask); } + return stat; /* => channels pending in-band handling. */ +} + +static irqreturn_t sdma_int_handler(int irq, void *dev_id) +{ + struct sdma_engine *sdma = dev_id; + unsigned long stat, flags __maybe_unused; + +#ifdef CONFIG_IMX_SDMA_OOB + if (running_oob()) { + stat = readl_relaxed(sdma->regs + SDMA_H_INTR); + writel_relaxed(stat, sdma->regs + SDMA_H_INTR); + /* + * Locking is only to guard against IRQ migration with + * a delayed in-band event running from a remote CPU + * after some IRQ routing changed the affinity of the + * out-of-band handler in the meantime. + */ + stat = sdma_do_channels(sdma, stat & ~1); + if (stat) { + raw_spin_lock(&sdma->oob_lock); + sdma->pending_stat |= stat; + raw_spin_unlock(&sdma->oob_lock); + /* Call us back from in-band context. */ + return IRQ_FORWARD; + } + } else { + /* In-band IRQ context: stalled, but hard irqs are on. */ + raw_spin_lock_irqsave(&sdma->oob_lock, flags); + stat = sdma->pending_stat; + sdma->pending_stat = 0; + raw_spin_unlock_irqrestore(&sdma->oob_lock, flags); + /* + * Hybrid locking of oob-enabled vchans ensures that + * hard IRQ are disabled across the locked section, + * including from the in-band stage. + */ + sdma_do_channels(sdma, stat); + } +#else + stat = readl_relaxed(sdma->regs + SDMA_H_INTR); + writel_relaxed(stat, sdma->regs + SDMA_H_INTR); + /* channel 0 is special and not handled here, see run_channel0() */ + sdma_do_channels(sdma, stat & ~1); +#endif + return IRQ_HANDLED; } @@ -1190,7 +1252,7 @@ static int sdma_terminate_all(struct dma_chan *chan) struct sdma_channel *sdmac = to_sdma_chan(chan); unsigned long flags; - spin_lock_irqsave(&sdmac->vc.lock, flags); + vchan_lock_irqsave(&sdmac->vc, flags); sdma_disable_channel(chan); @@ -1204,11 +1266,12 @@ static int sdma_terminate_all(struct dma_chan *chan) */ vchan_get_all_descriptors(&sdmac->vc, &sdmac->terminated); sdmac->desc = NULL; + vchan_unlock_irqrestore(&sdmac->vc, flags); schedule_work(&sdmac->terminate_worker); + } else { + vchan_unlock_irqrestore(&sdmac->vc, flags); } - spin_unlock_irqrestore(&sdmac->vc.lock, flags); - return 0; } @@ -1612,6 +1675,15 @@ static struct dma_async_tx_descriptor *sdma_prep_slave_sg( struct scatterlist *sg; struct sdma_desc *desc; + if (!sdma_oob_capable()) { + if (flags & (DMA_OOB_INTERRUPT|DMA_OOB_PULSE)) { + dev_err(sdma->dev, + "%s: out-of-band slave transfers disabled\n", + __func__); + return NULL; + } + } + sdma_config_write(chan, &sdmac->slave_config, direction); desc = sdma_transfer_init(sdmac, direction, sg_len); @@ -1663,7 +1735,8 @@ static struct dma_async_tx_descriptor *sdma_prep_slave_sg( if (i + 1 == sg_len) { param |= BD_INTR; - param |= BD_LAST; + if (!sdma_oob_capable() || !(flags & DMA_OOB_PULSE)) + param |= BD_LAST; param &= ~BD_CONT; } @@ -1701,6 +1774,20 @@ static struct dma_async_tx_descriptor *sdma_prep_dma_cyclic( if (sdmac->peripheral_type != IMX_DMATYPE_HDMI) num_periods = buf_len / period_len; + if (!sdma_oob_capable()) { + if (flags & (DMA_OOB_INTERRUPT|DMA_OOB_PULSE)) { + dev_err(sdma->dev, + "%s: out-of-band cyclic transfers disabled\n", + __func__); + return NULL; + } + } else if (flags & DMA_OOB_PULSE) { + dev_err(chan->device->dev, + "%s: no pulse mode with out-of-band cyclic transfers\n", + __func__); + return NULL; + } + sdma_config_write(chan, &sdmac->slave_config, direction); desc = sdma_transfer_init(sdmac, direction, num_periods); @@ -1847,7 +1934,7 @@ static enum dma_status sdma_tx_status(struct dma_chan *chan, if (ret == DMA_COMPLETE || !txstate) return ret; - spin_lock_irqsave(&sdmac->vc.lock, flags); + vchan_lock_irqsave(&sdmac->vc, flags); vd = vchan_find_desc(&sdmac->vc, cookie); if (vd) @@ -1865,7 +1952,7 @@ static enum dma_status sdma_tx_status(struct dma_chan *chan, residue = 0; } - spin_unlock_irqrestore(&sdmac->vc.lock, flags); + vchan_unlock_irqrestore(&sdmac->vc, flags); dma_set_tx_state(txstate, chan->completed_cookie, chan->cookie, residue); @@ -1878,11 +1965,38 @@ static void sdma_issue_pending(struct dma_chan *chan) struct sdma_channel *sdmac = to_sdma_chan(chan); unsigned long flags; - spin_lock_irqsave(&sdmac->vc.lock, flags); + vchan_lock_irqsave(&sdmac->vc, flags); if (vchan_issue_pending(&sdmac->vc) && !sdmac->desc) sdma_start_desc(sdmac); - spin_unlock_irqrestore(&sdmac->vc.lock, flags); + vchan_unlock_irqrestore(&sdmac->vc, flags); +} + +#ifdef CONFIG_IMX_SDMA_OOB +static int sdma_pulse_oob(struct dma_chan *chan) +{ + struct sdma_channel *sdmac = to_sdma_chan(chan); + struct sdma_desc *desc = sdmac->desc; + unsigned long flags; + int n, ret = -EIO; + + vchan_lock_irqsave(&sdmac->vc, flags); + if (desc && vchan_oob_pulsed(&desc->vd)) { + for (n = 0; n < desc->num_bd - 1; n++) + desc->bd[n].mode.status |= BD_DONE; + desc->bd[n].mode.status |= BD_DONE|BD_WRAP; + sdma_enable_channel(sdmac->sdma, sdmac->channel); + ret = 0; + } + vchan_unlock_irqrestore(&sdmac->vc, flags); + + return ret; +} +#else +static int sdma_pulse_oob(struct dma_chan *chan) +{ + return -ENOTSUPP; } +#endif #define SDMA_SCRIPT_ADDRS_ARRAY_SIZE_V1 34 #define SDMA_SCRIPT_ADDRS_ARRAY_SIZE_V2 38 @@ -2133,6 +2247,9 @@ static int sdma_init(struct sdma_engine *sdma) clk_disable(sdma->clk_ipg); clk_disable(sdma->clk_ahb); +#ifdef CONFIG_IMX_SDMA_OOB + raw_spin_lock_init(&sdma->oob_lock); +#endif return 0; err_dma_alloc: @@ -2232,7 +2349,8 @@ static int sdma_probe(struct platform_device *pdev) if (ret) goto err_clk; - ret = devm_request_irq(&pdev->dev, irq, sdma_int_handler, 0, + ret = devm_request_irq(&pdev->dev, irq, sdma_int_handler, + IS_ENABLED(CONFIG_IMX_SDMA_OOB) ? IRQF_OOB : 0, dev_name(&pdev->dev), sdma); if (ret) goto err_irq; @@ -2252,6 +2370,7 @@ static int sdma_probe(struct platform_device *pdev) dma_cap_set(DMA_SLAVE, sdma->dma_device.cap_mask); dma_cap_set(DMA_CYCLIC, sdma->dma_device.cap_mask); + dma_cap_set(DMA_OOB, sdma->dma_device.cap_mask); dma_cap_set(DMA_MEMCPY, sdma->dma_device.cap_mask); dma_cap_set(DMA_PRIVATE, sdma->dma_device.cap_mask); @@ -2303,6 +2422,7 @@ static int sdma_probe(struct platform_device *pdev) sdma->dma_device.residue_granularity = DMA_RESIDUE_GRANULARITY_SEGMENT; sdma->dma_device.device_prep_dma_memcpy = sdma_prep_memcpy; sdma->dma_device.device_issue_pending = sdma_issue_pending; + sdma->dma_device.device_pulse_oob = sdma_pulse_oob; sdma->dma_device.copy_align = 2; dma_set_max_seg_size(sdma->dma_device.dev, SDMA_BD_MAX_CNT); @@ -2345,6 +2465,16 @@ static int sdma_probe(struct platform_device *pdev) dev_warn(&pdev->dev, "failed to get firmware from device tree\n"); } + /* + * Keep the clocks enabled at any time if we plan to use the + * DMA from out-of-band context, bumping their refcount to + * keep them on until sdma_remove() is called eventually. + */ + if (IS_ENABLED(CONFIG_IMX_SDMA_OOB)) { + clk_enable(sdma->clk_ipg); + clk_enable(sdma->clk_ahb); + } + return 0; err_register: @@ -2363,6 +2493,11 @@ static int sdma_remove(struct platform_device *pdev) struct sdma_engine *sdma = platform_get_drvdata(pdev); int i; + if (IS_ENABLED(CONFIG_IMX_SDMA_OOB)) { + clk_disable(sdma->clk_ahb); + clk_disable(sdma->clk_ipg); + } + devm_free_irq(&pdev->dev, sdma->irq, sdma); dma_async_device_unregister(&sdma->dma_device); kfree(sdma->script_addrs); diff --git a/drivers/dma/virt-dma.c b/drivers/dma/virt-dma.c index a6f4265be..89e011699 100644 --- a/drivers/dma/virt-dma.c +++ b/drivers/dma/virt-dma.c @@ -23,11 +23,11 @@ dma_cookie_t vchan_tx_submit(struct dma_async_tx_descriptor *tx) unsigned long flags; dma_cookie_t cookie; - spin_lock_irqsave(&vc->lock, flags); + vchan_lock_irqsave(vc, flags); cookie = dma_cookie_assign(tx); list_move_tail(&vd->node, &vc->desc_submitted); - spin_unlock_irqrestore(&vc->lock, flags); + vchan_unlock_irqrestore(vc, flags); dev_dbg(vc->chan.device->dev, "vchan %p: txd %p[%x]: submitted\n", vc, vd, cookie); @@ -52,9 +52,9 @@ int vchan_tx_desc_free(struct dma_async_tx_descriptor *tx) struct virt_dma_desc *vd = to_virt_desc(tx); unsigned long flags; - spin_lock_irqsave(&vc->lock, flags); + vchan_lock_irqsave(vc, flags); list_del(&vd->node); - spin_unlock_irqrestore(&vc->lock, flags); + vchan_unlock_irqrestore(vc, flags); dev_dbg(vc->chan.device->dev, "vchan %p: txd %p[%x]: freeing\n", vc, vd, vd->tx.cookie); @@ -87,7 +87,7 @@ static void vchan_complete(struct tasklet_struct *t) struct dmaengine_desc_callback cb; LIST_HEAD(head); - spin_lock_irq(&vc->lock); + vchan_lock_irq(vc); list_splice_tail_init(&vc->desc_completed, &head); vd = vc->cyclic; if (vd) { @@ -96,7 +96,7 @@ static void vchan_complete(struct tasklet_struct *t) } else { memset(&cb, 0, sizeof(cb)); } - spin_unlock_irq(&vc->lock); + vchan_unlock_irq(vc); dmaengine_desc_callback_invoke(&cb, &vd->tx_result); @@ -120,11 +120,119 @@ void vchan_dma_desc_free_list(struct virt_dma_chan *vc, struct list_head *head) } EXPORT_SYMBOL_GPL(vchan_dma_desc_free_list); +#ifdef CONFIG_DMA_VIRTUAL_CHANNELS_OOB + +static void inband_init_chan_lock(struct virt_dma_chan *vc) +{ + spin_lock_init(&vc->lock); +} + +static void inband_lock_chan(struct virt_dma_chan *vc) +{ + spin_lock(&vc->lock); +} + +static void inband_unlock_chan(struct virt_dma_chan *vc) +{ + spin_unlock(&vc->lock); +} + +static void inband_lock_irq_chan(struct virt_dma_chan *vc) +{ + spin_lock_irq(&vc->lock); +} + +static void inband_unlock_irq_chan(struct virt_dma_chan *vc) +{ + spin_unlock_irq(&vc->lock); +} + +static unsigned long inband_lock_irqsave_chan(struct virt_dma_chan *vc) +{ + unsigned long flags; + + spin_lock_irqsave(&vc->lock, flags); + + return flags; +} + +static void inband_unlock_irqrestore_chan(struct virt_dma_chan *vc, + unsigned long flags) +{ + spin_unlock_irqrestore(&vc->lock, flags); +} + +static struct virt_dma_lockops inband_lock_ops = { + .init = inband_init_chan_lock, + .lock = inband_lock_chan, + .unlock = inband_unlock_chan, + .lock_irq = inband_lock_irq_chan, + .unlock_irq = inband_unlock_irq_chan, + .lock_irqsave = inband_lock_irqsave_chan, + .unlock_irqrestore = inband_unlock_irqrestore_chan, +}; + +static void oob_init_chan_lock(struct virt_dma_chan *vc) +{ + raw_spin_lock_init(&vc->oob_lock); +} + +static void oob_lock_chan(struct virt_dma_chan *vc) +{ + raw_spin_lock(&vc->oob_lock); +} + +static void oob_unlock_chan(struct virt_dma_chan *vc) +{ + raw_spin_unlock(&vc->oob_lock); +} + +static void oob_lock_irq_chan(struct virt_dma_chan *vc) +{ + raw_spin_lock_irq(&vc->oob_lock); +} + +static void oob_unlock_irq_chan(struct virt_dma_chan *vc) +{ + raw_spin_unlock_irq(&vc->oob_lock); +} + +static unsigned long oob_lock_irqsave_chan(struct virt_dma_chan *vc) +{ + unsigned long flags; + + raw_spin_lock_irqsave(&vc->oob_lock, flags); + + return flags; +} + +static void oob_unlock_irqrestore_chan(struct virt_dma_chan *vc, + unsigned long flags) +{ + raw_spin_unlock_irqrestore(&vc->oob_lock, flags); +} + +static struct virt_dma_lockops oob_lock_ops = { + .init = oob_init_chan_lock, + .lock = oob_lock_chan, + .unlock = oob_unlock_chan, + .lock_irq = oob_lock_irq_chan, + .unlock_irq = oob_unlock_irq_chan, + .lock_irqsave = oob_lock_irqsave_chan, + .unlock_irqrestore = oob_unlock_irqrestore_chan, +}; + +#endif + void vchan_init(struct virt_dma_chan *vc, struct dma_device *dmadev) { dma_cookie_init(&vc->chan); - spin_lock_init(&vc->lock); +#ifdef CONFIG_DMA_VIRTUAL_CHANNELS_OOB + vc->lock_ops = test_bit(DMA_OOB, dmadev->cap_mask.bits) ? + &oob_lock_ops : &inband_lock_ops; +#endif + vchan_lock_init(vc); INIT_LIST_HEAD(&vc->desc_allocated); INIT_LIST_HEAD(&vc->desc_submitted); INIT_LIST_HEAD(&vc->desc_issued); diff --git a/drivers/dma/virt-dma.h b/drivers/dma/virt-dma.h index e9f5250fb..698bce541 100644 --- a/drivers/dma/virt-dma.h +++ b/drivers/dma/virt-dma.h @@ -19,12 +19,22 @@ struct virt_dma_desc { struct list_head node; }; +struct virt_dma_lockops; + struct virt_dma_chan { struct dma_chan chan; struct tasklet_struct task; void (*desc_free)(struct virt_dma_desc *); +#ifdef CONFIG_DMA_VIRTUAL_CHANNELS_OOB + struct virt_dma_lockops *lock_ops; + union { + spinlock_t lock; + hybrid_spinlock_t oob_lock; + }; +#else spinlock_t lock; +#endif /* protected by vc.lock */ struct list_head desc_allocated; @@ -41,6 +51,107 @@ static inline struct virt_dma_chan *to_virt_chan(struct dma_chan *chan) return container_of(chan, struct virt_dma_chan, chan); } +#ifdef CONFIG_DMA_VIRTUAL_CHANNELS_OOB + +struct virt_dma_lockops { + void (*init)(struct virt_dma_chan *vc); + void (*lock)(struct virt_dma_chan *vc); + void (*unlock)(struct virt_dma_chan *vc); + void (*lock_irq)(struct virt_dma_chan *vc); + void (*unlock_irq)(struct virt_dma_chan *vc); + unsigned long (*lock_irqsave)(struct virt_dma_chan *vc); + void (*unlock_irqrestore)(struct virt_dma_chan *vc, + unsigned long flags); +}; + +static inline void vchan_lock_init(struct virt_dma_chan *vc) +{ + vc->lock_ops->init(vc); +} + +static inline void vchan_lock(struct virt_dma_chan *vc) +{ + vc->lock_ops->lock(vc); +} + +static inline void vchan_unlock(struct virt_dma_chan *vc) +{ + vc->lock_ops->unlock(vc); +} + +static inline void vchan_lock_irq(struct virt_dma_chan *vc) +{ + vc->lock_ops->lock_irq(vc); +} + +static inline void vchan_unlock_irq(struct virt_dma_chan *vc) +{ + vc->lock_ops->unlock_irq(vc); +} + +static inline +unsigned long __vchan_lock_irqsave(struct virt_dma_chan *vc) +{ + return vc->lock_ops->lock_irqsave(vc); +} + +#define vchan_lock_irqsave(__vc, __flags) \ + do { \ + (__flags) = __vchan_lock_irqsave(__vc); \ + } while (0) + +static inline +void vchan_unlock_irqrestore(struct virt_dma_chan *vc, + unsigned long flags) +{ + vc->lock_ops->unlock_irqrestore(vc, flags); +} + +static inline bool vchan_oob_handled(struct virt_dma_desc *vd) +{ + return !!(vd->tx.flags & DMA_OOB_INTERRUPT); +} + +static inline bool vchan_oob_pulsed(struct virt_dma_desc *vd) +{ + return !!(vd->tx.flags & DMA_OOB_PULSE); +} + +#else + +#define vchan_lock_init(__vc) \ + spin_lock_init(&(__vc)->lock) + +#define vchan_lock(__vc) \ + spin_lock(&(__vc)->lock) + +#define vchan_unlock(__vc) \ + spin_unlock(&(__vc)->lock) + +#define vchan_lock_irq(__vc) \ + spin_lock_irq(&(__vc)->lock) + +#define vchan_unlock_irq(__vc) \ + spin_unlock_irq(&(__vc)->lock) + +#define vchan_lock_irqsave(__vc, __flags) \ + spin_lock_irqsave(&(__vc)->lock, __flags) + +#define vchan_unlock_irqrestore(__vc, __flags) \ + spin_unlock_irqrestore(&(__vc)->lock, __flags) + +static inline bool vchan_oob_handled(struct virt_dma_desc *vd) +{ + return false; +} + +static inline bool vchan_oob_pulsed(struct virt_dma_desc *vd) +{ + return false; +} + +#endif /* !CONFIG_DMA_VIRTUAL_CHANNELS_OOB */ + void vchan_dma_desc_free_list(struct virt_dma_chan *vc, struct list_head *head); void vchan_init(struct virt_dma_chan *vc, struct dma_device *dmadev); struct virt_dma_desc *vchan_find_desc(struct virt_dma_chan *, dma_cookie_t); @@ -66,9 +177,9 @@ static inline struct dma_async_tx_descriptor *vchan_tx_prep(struct virt_dma_chan vd->tx_result.result = DMA_TRANS_NOERROR; vd->tx_result.residue = 0; - spin_lock_irqsave(&vc->lock, flags); + vchan_lock_irqsave(vc, flags); list_add_tail(&vd->node, &vc->desc_allocated); - spin_unlock_irqrestore(&vc->lock, flags); + vchan_unlock_irqrestore(vc, flags); return &vd->tx; } @@ -90,6 +201,11 @@ static inline bool vchan_issue_pending(struct virt_dma_chan *vc) * @vd: virtual descriptor to update * * vc.lock must be held by caller + * + * irq_pipeline: calling with hard irqs off is ok as long as we are + * running in-band from an interrupt context (i.e. in_interrupt() + * yields true), so that there is no attempt to wake up softirqd until + * the interrupt frame unwinds. */ static inline void vchan_cookie_complete(struct virt_dma_desc *vd) { @@ -116,9 +232,9 @@ static inline void vchan_vdesc_fini(struct virt_dma_desc *vd) if (dmaengine_desc_test_reuse(&vd->tx)) { unsigned long flags; - spin_lock_irqsave(&vc->lock, flags); + vchan_lock_irqsave(vc, flags); list_add(&vd->node, &vc->desc_allocated); - spin_unlock_irqrestore(&vc->lock, flags); + vchan_unlock_irqrestore(vc, flags); } else { vc->desc_free(vd); } @@ -190,11 +306,11 @@ static inline void vchan_free_chan_resources(struct virt_dma_chan *vc) unsigned long flags; LIST_HEAD(head); - spin_lock_irqsave(&vc->lock, flags); + vchan_lock_irqsave(vc, flags); vchan_get_all_descriptors(vc, &head); list_for_each_entry(vd, &head, node) dmaengine_desc_clear_reuse(&vd->tx); - spin_unlock_irqrestore(&vc->lock, flags); + vchan_unlock_irqrestore(vc, flags); vchan_dma_desc_free_list(vc, &head); } @@ -215,11 +331,11 @@ static inline void vchan_synchronize(struct virt_dma_chan *vc) tasklet_kill(&vc->task); - spin_lock_irqsave(&vc->lock, flags); + vchan_lock_irqsave(vc, flags); list_splice_tail_init(&vc->desc_terminated, &head); - spin_unlock_irqrestore(&vc->lock, flags); + vchan_unlock_irqrestore(vc, flags); vchan_dma_desc_free_list(vc, &head); } diff --git a/drivers/evl/Kconfig b/drivers/evl/Kconfig new file mode 100644 index 000000000..792404d29 --- /dev/null +++ b/drivers/evl/Kconfig @@ -0,0 +1,24 @@ +menu "Out-of-band device drivers" + +config EVL_LATMUS + bool "Timer latency calibration and measurement" + depends on EVL + default y + help + This driver supports the latmus application for + determining the best gravity values for the EVL core + clock, and measuring the response time to timer events. + If in doubt, say 'Y'. + +config EVL_HECTIC + bool "OOB context switching validator" + depends on EVL + default y + help + This driver provides kernel support mainly to the + hectic application, which validates the out-of-band + context switching machinery. It is also required + for running some tests from the EVL test suite. + If in doubt, say 'Y'. + +endmenu diff --git a/drivers/evl/Makefile b/drivers/evl/Makefile new file mode 100644 index 000000000..06d35e90e --- /dev/null +++ b/drivers/evl/Makefile @@ -0,0 +1,2 @@ +obj-$(CONFIG_EVL_LATMUS) += latmus.o +obj-$(CONFIG_EVL_HECTIC) += hectic.o diff --git a/drivers/evl/hectic.c b/drivers/evl/hectic.c new file mode 100644 index 000000000..4cff66cb1 --- /dev/null +++ b/drivers/evl/hectic.c @@ -0,0 +1,717 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Derived from Xenomai Cobalt's switchtest driver, https://xenomai.org/ + * Copyright (C) 2010 Gilles Chanteperdrix . + * Copyright (C) 2018 Philippe Gerum + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define HECTIC_KTHREAD 0x20000 + +struct rtswitch_context; + +struct rtswitch_task { + struct hectic_task_index base; + struct evl_flag rt_synch; + struct semaphore nrt_synch; + struct evl_kthread kthread; /* For kernel-space real-time tasks. */ + unsigned int last_switch; + struct rtswitch_context *ctx; +}; + +struct rtswitch_context { + struct rtswitch_task *tasks; + unsigned int tasks_count; + unsigned int next_index; + struct semaphore lock; + unsigned int cpu; + unsigned int switches_count; + + unsigned long pause_us; + unsigned int next_task; + struct evl_timer wake_up_delay; + + bool failed; + struct hectic_error error; + + struct rtswitch_task *utask; + struct irq_work wake_utask; + struct evl_stax stax; + struct evl_file efile; +}; + +static u32 fp_features; + +#define trace_fpu_breakage(__ctx) \ + do { \ + trace_evl_fpu_corrupt((__ctx)->error.fp_val); \ + trace_evl_trigger("hectic"); \ + } while (0) + +static void handle_fpu_error(struct rtswitch_context *ctx, + unsigned int fp_in, unsigned int fp_out, + int bad_reg) +{ + struct rtswitch_task *cur = &ctx->tasks[ctx->error.last_switch.to]; + unsigned int i; + + printk(EVL_ERR "fpreg%d trashed: in=%u, out=%u\n", + bad_reg, fp_in, fp_out); + + ctx->failed = true; + ctx->error.fp_val = fp_out; + trace_fpu_breakage(ctx); + + if ((cur->base.flags & HECTIC_OOB_WAIT) == HECTIC_OOB_WAIT) + for (i = 0; i < ctx->tasks_count; i++) { + struct rtswitch_task *task = &ctx->tasks[i]; + + /* Find the first non kernel-space task. */ + if ((task->base.flags & HECTIC_KTHREAD)) + continue; + + /* Unblock it. */ + switch(task->base.flags & HECTIC_OOB_WAIT) { + case HECTIC_INBAND_WAIT: + ctx->utask = task; + irq_work_queue(&ctx->wake_utask); + break; + + case HECTIC_OOB_WAIT: + evl_raise_flag(&task->rt_synch); + break; + } + + evl_hold_thread(&cur->kthread.thread, EVL_T_SUSP); + } +} + +static int rtswitch_pend_rt(struct rtswitch_context *ctx, + unsigned int idx) +{ + struct rtswitch_task *task; + int rc; + + if (idx > ctx->tasks_count) + return -EINVAL; + + task = &ctx->tasks[idx]; + task->base.flags |= HECTIC_OOB_WAIT; + + rc = evl_wait_flag(&task->rt_synch); + if (rc < 0) + return rc; + + if (ctx->failed) + return 1; + + return 0; +} + +static void timed_wake_up(struct evl_timer *timer) /* hard irqs off */ +{ + struct rtswitch_context *ctx; + struct rtswitch_task *task; + + ctx = container_of(timer, struct rtswitch_context, wake_up_delay); + task = &ctx->tasks[ctx->next_task]; + + switch (task->base.flags & HECTIC_OOB_WAIT) { + case HECTIC_INBAND_WAIT: + ctx->utask = task; + irq_work_queue(&ctx->wake_utask); + break; + + case HECTIC_OOB_WAIT: + evl_raise_flag(&task->rt_synch); + } +} + +static int rtswitch_to_rt(struct rtswitch_context *ctx, + unsigned int from_idx, + unsigned int to_idx) +{ + struct rtswitch_task *from, *to; + int rc; + + if (from_idx > ctx->tasks_count || to_idx > ctx->tasks_count) + return -EINVAL; + + /* to == from is a special case which means + "return to the previous task". */ + if (to_idx == from_idx) + to_idx = ctx->error.last_switch.from; + + from = &ctx->tasks[from_idx]; + to = &ctx->tasks[to_idx]; + + from->base.flags |= HECTIC_OOB_WAIT; + from->last_switch = ++ctx->switches_count; + ctx->error.last_switch.from = from_idx; + ctx->error.last_switch.to = to_idx; + barrier(); + + if (ctx->pause_us) { + ctx->next_task = to_idx; + barrier(); + evl_start_timer(&ctx->wake_up_delay, + evl_abs_timeout(&ctx->wake_up_delay, + ctx->pause_us * 1000), + EVL_INFINITE); + } else + switch (to->base.flags & HECTIC_OOB_WAIT) { + case HECTIC_INBAND_WAIT: + ctx->utask = to; + barrier(); + irq_work_queue(&ctx->wake_utask); + break; + + case HECTIC_OOB_WAIT: + evl_raise_flag(&to->rt_synch); + break; + + default: + return -EINVAL; + } + + rc = evl_wait_flag(&from->rt_synch); + if (rc < 0) + return rc; + + if (ctx->failed) + return 1; + + return 0; +} + +static int rtswitch_pend_nrt(struct rtswitch_context *ctx, + unsigned int idx) +{ + struct rtswitch_task *task; + + if (idx > ctx->tasks_count) + return -EINVAL; + + task = &ctx->tasks[idx]; + + task->base.flags &= ~HECTIC_OOB_WAIT; + + if (down_interruptible(&task->nrt_synch)) + return -EINTR; + + if (ctx->failed) + return 1; + + return 0; +} + +static int rtswitch_to_nrt(struct rtswitch_context *ctx, + unsigned int from_idx, + unsigned int to_idx) +{ + struct rtswitch_task *from, *to; + unsigned int expected, fp_val; + bool fp_check; + int bad_reg; + + if (from_idx > ctx->tasks_count || to_idx > ctx->tasks_count) + return -EINVAL; + + /* to == from is a special case which means + "return to the previous task". */ + if (to_idx == from_idx) + to_idx = ctx->error.last_switch.from; + + from = &ctx->tasks[from_idx]; + to = &ctx->tasks[to_idx]; + + fp_check = ctx->switches_count == from->last_switch + 1 + && ctx->error.last_switch.from == to_idx + && ctx->error.last_switch.to == from_idx; + + from->base.flags &= ~HECTIC_OOB_WAIT; + from->last_switch = ++ctx->switches_count; + ctx->error.last_switch.from = from_idx; + ctx->error.last_switch.to = to_idx; + barrier(); + + if (ctx->pause_us) { + ctx->next_task = to_idx; + barrier(); + evl_start_timer(&ctx->wake_up_delay, + evl_abs_timeout(&ctx->wake_up_delay, + ctx->pause_us * 1000), + EVL_INFINITE); + } else + switch (to->base.flags & HECTIC_OOB_WAIT) { + case HECTIC_INBAND_WAIT: + switch_to_nrt: + up(&to->nrt_synch); + break; + + case HECTIC_OOB_WAIT: + + if (!fp_check || !evl_begin_fpu()) + goto signal_nofp; + + expected = from_idx + 500 + + (ctx->switches_count % 4000000) * 1000; + + evl_set_fpregs(fp_features, expected); + evl_raise_flag(&to->rt_synch); + fp_val = evl_check_fpregs(fp_features, expected, bad_reg); + evl_end_fpu(); + + if (down_interruptible(&from->nrt_synch)) + return -EINTR; + if (ctx->failed) + return 1; + if (fp_val != expected) { + handle_fpu_error(ctx, expected, fp_val, bad_reg); + return 1; + } + + from->base.flags &= ~HECTIC_OOB_WAIT; + from->last_switch = ++ctx->switches_count; + ctx->error.last_switch.from = from_idx; + ctx->error.last_switch.to = to_idx; + if ((to->base.flags & HECTIC_OOB_WAIT) == HECTIC_INBAND_WAIT) + goto switch_to_nrt; + expected = from_idx + 500 + + (ctx->switches_count % 4000000) * 1000; + barrier(); + + evl_begin_fpu(); + evl_set_fpregs(fp_features, expected); + evl_raise_flag(&to->rt_synch); + fp_val = evl_check_fpregs(fp_features, expected, bad_reg); + evl_end_fpu(); + + if (down_interruptible(&from->nrt_synch)) + return -EINTR; + if (ctx->failed) + return 1; + if (fp_val != expected) { + handle_fpu_error(ctx, expected, fp_val, bad_reg); + return 1; + } + + from->base.flags &= ~HECTIC_OOB_WAIT; + from->last_switch = ++ctx->switches_count; + ctx->error.last_switch.from = from_idx; + ctx->error.last_switch.to = to_idx; + barrier(); + if ((to->base.flags & HECTIC_OOB_WAIT) == HECTIC_INBAND_WAIT) + goto switch_to_nrt; + + signal_nofp: + evl_raise_flag(&to->rt_synch); + break; + + default: + return -EINVAL; + } + + if (down_interruptible(&from->nrt_synch)) + return -EINTR; + + if (ctx->failed) + return 1; + + return 0; +} + +static int rtswitch_set_tasks_count(struct rtswitch_context *ctx, unsigned int count) +{ + struct rtswitch_task *tasks; + + if (ctx->tasks_count == count) + return 0; + + tasks = vmalloc(count * sizeof(*tasks)); + + if (!tasks) + return -ENOMEM; + + down(&ctx->lock); + + if (ctx->tasks) + vfree(ctx->tasks); + + ctx->tasks = tasks; + ctx->tasks_count = count; + ctx->next_index = 0; + + up(&ctx->lock); + + return 0; +} + +static int rtswitch_register_task(struct rtswitch_context *ctx, + struct hectic_task_index *arg, + int flags) +{ + struct rtswitch_task *t; + + down(&ctx->lock); + + if (ctx->next_index == ctx->tasks_count) { + up(&ctx->lock); + return -EBUSY; + } + + arg->index = ctx->next_index; + t = &ctx->tasks[arg->index]; + ctx->next_index++; + t->base.index = arg->index; + t->base.flags = (arg->flags & HECTIC_OOB_WAIT)|flags; + t->last_switch = 0; + sema_init(&t->nrt_synch, 0); + evl_init_flag(&t->rt_synch); + + up(&ctx->lock); + + return 0; +} + +static void rtswitch_kthread(void *arg) +{ + struct rtswitch_task *task = arg; + struct rtswitch_context *ctx; + unsigned int to, i = 0; + + ctx = task->ctx; + + to = task->base.index; + + rtswitch_pend_rt(ctx, task->base.index); + + while (!evl_kthread_should_stop()) { + switch(i % 3) { + case 0: + /* to == from means "return to last task" */ + rtswitch_to_rt(ctx, task->base.index, task->base.index); + break; + case 1: + if (++to == task->base.index) + ++to; + if (to > ctx->tasks_count - 1) + to = 0; + if (to == task->base.index) + ++to; + + fallthrough; + case 2: + rtswitch_to_rt(ctx, task->base.index, to); + } + if (++i == 4000000) + i = 0; + } +} + +static int rtswitch_create_kthread(struct rtswitch_context *ctx, + struct hectic_task_index *ptask) +{ + struct rtswitch_task *task; + int err; + + err = rtswitch_register_task(ctx, ptask, HECTIC_KTHREAD); + if (err) + return err; + + task = &ctx->tasks[ptask->index]; + task->ctx = ctx; + err = evl_run_kthread_on_cpu(&task->kthread, ctx->cpu, + rtswitch_kthread, task, 1, + EVL_CLONE_PUBLIC, + "rtk%d@%u:%d", + ptask->index, ctx->cpu, + task_pid_nr(current)); + /* + * On error, clear the flag bits in order to avoid calling + * evl_stop_kthread() for an invalid thread in + * hectic_release(). + */ + if (err) + task->base.flags = 0; + + return err; +} + +static void rtswitch_utask_waker(struct irq_work *work) +{ + struct rtswitch_context *ctx; + ctx = container_of(work, struct rtswitch_context, wake_utask); + up(&ctx->utask->nrt_synch); +} + +static long hectic_ioctl(struct file *filp, unsigned int cmd, + unsigned long arg) +{ + struct rtswitch_context *ctx = filp->private_data; + struct hectic_switch_req fromto, __user *u_fromto; + struct hectic_task_index task, __user *u_task; + struct hectic_error __user *u_lerr; + __u32 count; + int err; + + switch (cmd) { + case EVL_HECIOC_SET_TASKS_COUNT: + return rtswitch_set_tasks_count(ctx, arg); + + case EVL_HECIOC_SET_CPU: + if (arg > num_online_cpus() - 1) + return -EINVAL; + + ctx->cpu = arg; + return 0; + + case EVL_HECIOC_SET_PAUSE: + ctx->pause_us = arg; + return 0; + + case EVL_HECIOC_REGISTER_UTASK: + u_task = (typeof(u_task))arg; + err = copy_from_user(&task, u_task, sizeof(task)); + if (err) + return -EFAULT; + + err = rtswitch_register_task(ctx, &task, 0); + if (!err && copy_to_user(u_task, &task, sizeof(task))) + err = -EFAULT; + + return err; + + case EVL_HECIOC_CREATE_KTASK: + u_task = (typeof(u_task))arg; + err = copy_from_user(&task, u_task, sizeof(task)); + if (err) + return -EFAULT; + + err = rtswitch_create_kthread(ctx, &task); + if (!err && copy_to_user(u_task, &task, sizeof(task))) + err = -EFAULT; + + return err; + + case EVL_HECIOC_PEND: + u_task = (typeof(u_task))arg; + err = copy_from_user(&task, u_task, sizeof(task)); + if (err) + return -EFAULT; + + return rtswitch_pend_nrt(ctx, task.index); + + case EVL_HECIOC_SWITCH_TO: + u_fromto = (typeof(u_fromto))arg; + err = copy_from_user(&fromto, u_fromto, sizeof(fromto)); + if (err) + return -EFAULT; + + return rtswitch_to_nrt(ctx, fromto.from, fromto.to); + + case EVL_HECIOC_GET_SWITCHES_COUNT: + count = ctx->switches_count; + return copy_to_user((__u32 *)arg, &count, sizeof(count)) ? + -EFAULT : 0; + + case EVL_HECIOC_GET_LAST_ERROR: + trace_fpu_breakage(ctx); + u_lerr = (typeof(u_lerr))arg; + return copy_to_user(u_lerr, &ctx->error, sizeof(ctx->error)) ? + -EFAULT : 0; + + case EVL_HECIOC_LOCK_STAX: + return evl_lock_stax(&ctx->stax); + + case EVL_HECIOC_UNLOCK_STAX: + evl_unlock_stax(&ctx->stax); + return 0; + + default: + return -ENOTTY; + } +} + +static long hectic_oob_ioctl(struct file *filp, unsigned int cmd, + unsigned long arg) +{ + struct rtswitch_context *ctx = filp->private_data; + struct hectic_switch_req fromto, __user *u_fromto; + struct hectic_task_index task, __user *u_task; + struct hectic_error __user *u_lerr; + int err; + + switch (cmd) { + case EVL_HECIOC_PEND: + u_task = (typeof(u_task))arg; + err = raw_copy_from_user(&task, u_task, sizeof(task)); + return err ? -EFAULT : + rtswitch_pend_rt(ctx, task.index); + + case EVL_HECIOC_SWITCH_TO: + u_fromto = (typeof(u_fromto))arg; + err = raw_copy_from_user(&fromto, u_fromto, sizeof(fromto)); + return err ? -EFAULT : + rtswitch_to_rt(ctx, fromto.from, fromto.to); + + case EVL_HECIOC_GET_LAST_ERROR: + trace_fpu_breakage(ctx); + u_lerr = (typeof(u_lerr))arg; + return raw_copy_to_user(u_lerr, &ctx->error, sizeof(ctx->error)) ? + -EFAULT : 0; + + case EVL_HECIOC_LOCK_STAX: + return evl_lock_stax(&ctx->stax); + + case EVL_HECIOC_UNLOCK_STAX: + evl_unlock_stax(&ctx->stax); + return 0; + + default: + return -ENOTTY; + } +} + +static int hectic_open(struct inode *inode, struct file *filp) +{ + struct rtswitch_context *ctx; + int ret; + + ctx = kmalloc(sizeof(*ctx), GFP_KERNEL); + if (ctx == NULL) + return -ENOMEM; + + ret = evl_open_file(&ctx->efile, filp); + if (ret) { + kfree(ctx); + return ret; + } + + ctx->tasks = NULL; + ctx->tasks_count = ctx->next_index = ctx->cpu = ctx->switches_count = 0; + sema_init(&ctx->lock, 1); + ctx->failed = false; + ctx->error.last_switch.from = ctx->error.last_switch.to = -1; + ctx->pause_us = 0; + + init_irq_work(&ctx->wake_utask, rtswitch_utask_waker); + evl_init_timer(&ctx->wake_up_delay, timed_wake_up); + evl_init_stax(&ctx->stax, 0); + + filp->private_data = ctx; + stream_open(inode, filp); + + return 0; +} + +static int hectic_release(struct inode *inode, struct file *filp) +{ + struct rtswitch_context *ctx = filp->private_data; + unsigned int i; + + evl_destroy_stax(&ctx->stax); + evl_destroy_timer(&ctx->wake_up_delay); + + if (ctx->tasks) { + set_cpus_allowed_ptr(current, cpumask_of(ctx->cpu)); + + for (i = 0; i < ctx->next_index; i++) { + struct rtswitch_task *task = &ctx->tasks[i]; + + if (task->base.flags & HECTIC_KTHREAD) + evl_stop_kthread(&task->kthread); + + evl_destroy_flag(&task->rt_synch); + } + vfree(ctx->tasks); + } + + evl_release_file(&ctx->efile); + kfree(ctx); + + return 0; +} + +static struct class hectic_class = { + .name = "hectic", +}; + +static const struct file_operations hectic_fops = { + .open = hectic_open, + .release = hectic_release, + .unlocked_ioctl = hectic_ioctl, + .oob_ioctl = hectic_oob_ioctl, +#ifdef CONFIG_COMPAT + .compat_ioctl = compat_ptr_ioctl, + .compat_oob_ioctl = compat_ptr_oob_ioctl, +#endif +}; + +static dev_t hectic_devt; + +static struct cdev hectic_cdev; + +static int __init hectic_init(void) +{ + struct device *dev; + int ret; + + fp_features = evl_detect_fpu(); + + ret = class_register(&hectic_class); + if (ret) + return ret; + + ret = alloc_chrdev_region(&hectic_devt, 0, 1, "hectic"); + if (ret) + goto fail_region; + + cdev_init(&hectic_cdev, &hectic_fops); + ret = cdev_add(&hectic_cdev, hectic_devt, 1); + if (ret) + goto fail_add; + + dev = device_create(&hectic_class, NULL, hectic_devt, NULL, "hectic"); + if (IS_ERR(dev)) { + ret = PTR_ERR(dev); + goto fail_dev; + } + + return 0; + +fail_dev: + cdev_del(&hectic_cdev); +fail_add: + unregister_chrdev_region(hectic_devt, 1); +fail_region: + class_unregister(&hectic_class); + + return ret; +} +module_init(hectic_init); + +static void __exit hectic_exit(void) +{ + device_destroy(&hectic_class, MKDEV(MAJOR(hectic_devt), 0)); + cdev_del(&hectic_cdev); + class_unregister(&hectic_class); +} +module_exit(hectic_exit); + +MODULE_LICENSE("GPL"); diff --git a/drivers/evl/latmus.c b/drivers/evl/latmus.c new file mode 100644 index 000000000..447ebd9d0 --- /dev/null +++ b/drivers/evl/latmus.c @@ -0,0 +1,1237 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Derived from Xenomai Cobalt's autotune driver, https://xenomai.org/ + * Copyright (C) 2014, 2018 Philippe Gerum + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define TUNER_SAMPLING_TIME 500000000UL +#define TUNER_WARMUP_STEPS 10 +#define TUNER_RESULT_STEPS 40 + +#define progress(__runner, __fmt, __args...) \ + do { \ + if ((__runner)->verbosity > 1) \ + printk(EVL_INFO "latmus(%s) " __fmt "\n", \ + (__runner)->name, ##__args); \ + } while (0) + +struct tuning_score { + int pmean; + int stddev; + int minlat; + unsigned int step; + unsigned int gravity; +}; + +struct runner_state { + ktime_t ideal; + int offset; + int min_lat; + int max_lat; + int allmax_lat; + int prev_mean; + int prev_sqs; + int cur_sqs; + int sum; + unsigned int overruns; + unsigned int cur_samples; + unsigned int max_samples; +}; + +struct latmus_runner { + const char *name; + unsigned int (*get_gravity)(struct latmus_runner *runner); + void (*set_gravity)(struct latmus_runner *runner, unsigned int gravity); + unsigned int (*adjust_gravity)(struct latmus_runner *runner, int adjust); + int (*start)(struct latmus_runner *runner, ktime_t start_time); + void (*stop)(struct latmus_runner *runner); + void (*destroy)(struct latmus_runner *runner); + int (*add_sample)(struct latmus_runner *runner, ktime_t timestamp); + int (*run)(struct latmus_runner *runner, struct latmus_result *result); + void (*cleanup)(struct latmus_runner *runner); + struct runner_state state; + struct evl_flag done; + int status; + int verbosity; + ktime_t period; + union { + struct { + struct tuning_score scores[TUNER_RESULT_STEPS]; + int nscores; + }; + struct { + unsigned int warmup_samples; + unsigned int warmup_limit; + int xfd; + struct evl_xbuf *xbuf; + u32 hcells; + s32 *histogram; + }; + }; +}; + +struct irq_runner { + struct evl_timer timer; + struct latmus_runner runner; +}; + +struct kthread_runner { + struct evl_kthread kthread; + struct evl_flag barrier; + ktime_t start_time; + struct latmus_runner runner; +}; + +struct uthread_runner { + struct evl_timer timer; + struct evl_flag pulse; + struct latmus_runner runner; +}; + +struct sirq_runner { + int sirq; + struct sirq_runner * __percpu *sirq_percpu; + struct evl_timer timer; + struct latmus_runner runner; +}; + +struct latmus_state { + struct evl_file efile; + struct latmus_runner *runner; +}; + +static inline void init_runner_base(struct latmus_runner *runner) +{ + evl_init_flag(&runner->done); + runner->status = 0; +} + +static inline void destroy_runner_base(struct latmus_runner *runner) +{ + evl_destroy_flag(&runner->done); + if (runner->cleanup) + runner->cleanup(runner); +} + +static inline void done_sampling(struct latmus_runner *runner, + int status) +{ + runner->status = status; + evl_raise_flag(&runner->done); +} + +static void send_measurement(struct latmus_runner *runner) +{ + struct runner_state *state = &runner->state; + struct latmus_measurement meas; + + meas.min_lat = state->min_lat; + meas.max_lat = state->max_lat; + meas.sum_lat = state->sum; + meas.overruns = state->overruns; + meas.samples = state->cur_samples; + evl_write_xbuf(runner->xbuf, &meas, sizeof(meas), O_NONBLOCK); + + /* Reset counters for next round. */ + state->min_lat = INT_MAX; + state->max_lat = INT_MIN; + state->sum = 0; + state->overruns = 0; + state->cur_samples = 0; +} + +static int add_measurement_sample(struct latmus_runner *runner, + ktime_t timestamp) +{ + struct runner_state *state = &runner->state; + ktime_t period = runner->period; + int delta, cell, offset_delta; + + /* Skip samples in warmup time. */ + if (runner->warmup_samples < runner->warmup_limit) { + runner->warmup_samples++; + state->ideal = ktime_add(state->ideal, period); + return 0; + } + + delta = (int)ktime_to_ns(ktime_sub(timestamp, state->ideal)); + offset_delta = delta - state->offset; + if (offset_delta < state->min_lat) + state->min_lat = offset_delta; + if (offset_delta > state->max_lat) + state->max_lat = offset_delta; + if (offset_delta > state->allmax_lat) { + state->allmax_lat = offset_delta; + trace_evl_latspot(offset_delta); + trace_evl_trigger("latmus"); + } + + if (runner->histogram) { + cell = (offset_delta < 0 ? -offset_delta : offset_delta) / 1000; /* us */ + if (cell >= runner->hcells) + cell = runner->hcells - 1; + runner->histogram[cell]++; + } + + state->sum += offset_delta; + state->ideal = ktime_add(state->ideal, period); + + while (delta > 0 && + (unsigned int)delta > ktime_to_ns(period)) { /* period > 0 */ + state->overruns++; + state->ideal = ktime_add(state->ideal, period); + delta -= ktime_to_ns(period); + } + + if (++state->cur_samples >= state->max_samples) + send_measurement(runner); + + return 0; /* Always keep going. */ +} + +static int add_tuning_sample(struct latmus_runner *runner, + ktime_t timestamp) +{ + struct runner_state *state = &runner->state; + int n, delta, cur_mean; + + delta = (int)ktime_to_ns(ktime_sub(timestamp, state->ideal)); + if (delta < state->min_lat) + state->min_lat = delta; + if (delta > state->max_lat) + state->max_lat = delta; + if (delta < 0) + delta = 0; + + state->sum += delta; + state->ideal = ktime_add(state->ideal, runner->period); + n = ++state->cur_samples; + + /* TAOCP (Vol 2), single-pass computation of variance. */ + if (n == 1) + state->prev_mean = delta; + else { + cur_mean = state->prev_mean + (delta - state->prev_mean) / n; + state->cur_sqs = state->prev_sqs + (delta - state->prev_mean) + * (delta - cur_mean); + state->prev_mean = cur_mean; + state->prev_sqs = state->cur_sqs; + } + + if (n >= state->max_samples) { + done_sampling(runner, 0); + return 1; /* Finished. */ + } + + return 0; /* Keep going. */ +} + +static void latmus_irq_handler(struct evl_timer *timer) /* hard irqs off */ +{ + struct irq_runner *irq_runner; + ktime_t now; + + irq_runner = container_of(timer, struct irq_runner, timer); + now = evl_read_clock(&evl_mono_clock); + if (irq_runner->runner.add_sample(&irq_runner->runner, now)) + evl_stop_timer(timer); +} + +static void destroy_irq_runner(struct latmus_runner *runner) +{ + struct irq_runner *irq_runner; + + irq_runner = container_of(runner, struct irq_runner, runner); + evl_destroy_timer(&irq_runner->timer); + destroy_runner_base(runner); + kfree(irq_runner); +} + +static unsigned int get_irq_gravity(struct latmus_runner *runner) +{ + return evl_mono_clock.gravity.irq; +} + +static void set_irq_gravity(struct latmus_runner *runner, unsigned int gravity) +{ + evl_mono_clock.gravity.irq = gravity; +} + +static unsigned int adjust_irq_gravity(struct latmus_runner *runner, int adjust) +{ + return evl_mono_clock.gravity.irq += adjust; +} + +static int start_irq_runner(struct latmus_runner *runner, + ktime_t start_time) +{ + struct irq_runner *irq_runner; + + irq_runner = container_of(runner, struct irq_runner, runner); + + evl_start_timer(&irq_runner->timer, start_time, runner->period); + + return 0; +} + +static void stop_irq_runner(struct latmus_runner *runner) +{ + struct irq_runner *irq_runner; + + irq_runner = container_of(runner, struct irq_runner, runner); + + evl_stop_timer(&irq_runner->timer); +} + +static struct latmus_runner *create_irq_runner(int cpu) +{ + struct irq_runner *irq_runner; + + irq_runner = kzalloc(sizeof(*irq_runner), GFP_KERNEL); + if (irq_runner == NULL) + return NULL; + + irq_runner->runner = (struct latmus_runner){ + .name = "irqhand", + .destroy = destroy_irq_runner, + .get_gravity = get_irq_gravity, + .set_gravity = set_irq_gravity, + .adjust_gravity = adjust_irq_gravity, + .start = start_irq_runner, + .stop = stop_irq_runner, + }; + + init_runner_base(&irq_runner->runner); + evl_init_timer_on_cpu(&irq_runner->timer, cpu, latmus_irq_handler); + + return &irq_runner->runner; +} + +static irqreturn_t latmus_sirq_handler(int sirq, void *dev_id) +{ + struct sirq_runner * __percpu *self_percpu = dev_id; + struct sirq_runner *sirq_runner = *self_percpu; + ktime_t now; + + now = evl_read_clock(&evl_mono_clock); + if (sirq_runner->runner.add_sample(&sirq_runner->runner, now)) + evl_stop_timer(&sirq_runner->timer); + + return IRQ_HANDLED; +} + +static void latmus_sirq_timer_handler(struct evl_timer *timer) /* hard irqs off */ +{ + struct sirq_runner *sirq_runner; + struct runner_state *state; + ktime_t now; + + now = evl_read_clock(&evl_mono_clock); + sirq_runner = container_of(timer, struct sirq_runner, timer); + state = &sirq_runner->runner.state; + state->offset = (int)ktime_to_ns(ktime_sub(now, state->ideal)); + irq_post_inband(sirq_runner->sirq); +} + +static void destroy_sirq_runner(struct latmus_runner *runner) +{ + struct sirq_runner *sirq_runner; + + sirq_runner = container_of(runner, struct sirq_runner, runner); + evl_destroy_timer(&sirq_runner->timer); + free_percpu_irq(sirq_runner->sirq, sirq_runner->sirq_percpu); + free_percpu(sirq_runner->sirq_percpu); + irq_dispose_mapping(sirq_runner->sirq); + destroy_runner_base(runner); + kfree(sirq_runner); +} + +static int start_sirq_runner(struct latmus_runner *runner, + ktime_t start_time) +{ + struct sirq_runner *sirq_runner; + + sirq_runner = container_of(runner, struct sirq_runner, runner); + + evl_start_timer(&sirq_runner->timer, start_time, runner->period); + + return 0; +} + +static void stop_sirq_runner(struct latmus_runner *runner) +{ + struct sirq_runner *sirq_runner; + + sirq_runner = container_of(runner, struct sirq_runner, runner); + + evl_stop_timer(&sirq_runner->timer); +} + +static struct latmus_runner *create_sirq_runner(int cpu) +{ + struct sirq_runner * __percpu *sirq_percpu; + struct sirq_runner *sirq_runner; + int sirq, ret, _cpu; + + sirq_percpu = alloc_percpu(struct sirq_runner *); + if (sirq_percpu == NULL) + return ERR_PTR(-ENOMEM); + + sirq_runner = kzalloc(sizeof(*sirq_runner), GFP_KERNEL); + if (sirq_runner == NULL) { + free_percpu(sirq_percpu); + return NULL; + } + + sirq = irq_create_direct_mapping(synthetic_irq_domain); + if (sirq == 0) { + free_percpu(sirq_percpu); + kfree(sirq_runner); + return ERR_PTR(-EAGAIN); + } + + sirq_runner->runner = (struct latmus_runner){ + .name = "sirqhand", + .destroy = destroy_sirq_runner, + .start = start_sirq_runner, + .stop = stop_sirq_runner, + }; + sirq_runner->sirq = sirq; + sirq_runner->sirq_percpu = sirq_percpu; + init_runner_base(&sirq_runner->runner); + evl_init_timer_on_cpu(&sirq_runner->timer, cpu, + latmus_sirq_timer_handler); + + for_each_possible_cpu(_cpu) + *per_cpu_ptr(sirq_percpu, _cpu) = sirq_runner; + + ret = __request_percpu_irq(sirq, latmus_sirq_handler, + IRQF_NO_THREAD, + "latmus sirq", + sirq_percpu); + if (ret) { + evl_destroy_timer(&sirq_runner->timer); + irq_dispose_mapping(sirq); + free_percpu(sirq_percpu); + kfree(sirq_runner); + return ERR_PTR(ret); + } + + return &sirq_runner->runner; +} + +static void kthread_handler(void *arg) +{ + struct kthread_runner *k_runner = arg; + ktime_t now; + int ret = 0; + + for (;;) { + if (evl_kthread_should_stop()) + break; + + ret = evl_wait_flag(&k_runner->barrier); + if (ret) + break; + + ret = evl_set_period(&evl_mono_clock, + k_runner->start_time, + k_runner->runner.period); + if (ret) + break; + + for (;;) { + ret = evl_wait_period(NULL); + if (ret && ret != -ETIMEDOUT) + goto out; + + now = evl_read_clock(&evl_mono_clock); + if (k_runner->runner.add_sample(&k_runner->runner, now)) { + evl_set_period(NULL, 0, 0); + break; + } + } + } +out: + done_sampling(&k_runner->runner, ret); + evl_stop_kthread(&k_runner->kthread); +} + +static void destroy_kthread_runner(struct latmus_runner *runner) +{ + struct kthread_runner *k_runner; + + k_runner = container_of(runner, struct kthread_runner, runner); + evl_stop_kthread(&k_runner->kthread); + evl_destroy_flag(&k_runner->barrier); + destroy_runner_base(runner); + kfree(k_runner); +} + +static unsigned int get_kthread_gravity(struct latmus_runner *runner) +{ + return evl_mono_clock.gravity.kernel; +} + +static void +set_kthread_gravity(struct latmus_runner *runner, unsigned int gravity) +{ + evl_mono_clock.gravity.kernel = gravity; +} + +static unsigned int +adjust_kthread_gravity(struct latmus_runner *runner, int adjust) +{ + return evl_mono_clock.gravity.kernel += adjust; +} + +static int start_kthread_runner(struct latmus_runner *runner, + ktime_t start_time) +{ + struct kthread_runner *k_runner; + + k_runner = container_of(runner, struct kthread_runner, runner); + + k_runner->start_time = start_time; + evl_raise_flag(&k_runner->barrier); + + return 0; +} + +static struct latmus_runner * +create_kthread_runner(int priority, int cpu) +{ + struct kthread_runner *k_runner; + int ret; + + k_runner = kzalloc(sizeof(*k_runner), GFP_KERNEL); + if (k_runner == NULL) + return NULL; + + k_runner->runner = (struct latmus_runner){ + .name = "kthread", + .destroy = destroy_kthread_runner, + .get_gravity = get_kthread_gravity, + .set_gravity = set_kthread_gravity, + .adjust_gravity = adjust_kthread_gravity, + .start = start_kthread_runner, + }; + + init_runner_base(&k_runner->runner); + evl_init_flag(&k_runner->barrier); + + ret = evl_run_kthread_on_cpu(&k_runner->kthread, cpu, + kthread_handler, k_runner, + priority, + EVL_CLONE_PUBLIC, + "latmus-klat:%d", + task_pid_nr(current)); + if (ret) { + kfree(k_runner); + return ERR_PTR(ret); + } + + return &k_runner->runner; +} + +static void latmus_pulse_handler(struct evl_timer *timer) +{ + struct uthread_runner *u_runner; + + u_runner = container_of(timer, struct uthread_runner, timer); + evl_raise_flag(&u_runner->pulse); +} + +static void destroy_uthread_runner(struct latmus_runner *runner) +{ + struct uthread_runner *u_runner; + + u_runner = container_of(runner, struct uthread_runner, runner); + evl_destroy_timer(&u_runner->timer); + evl_destroy_flag(&u_runner->pulse); + destroy_runner_base(runner); + kfree(u_runner); +} + +static unsigned int get_uthread_gravity(struct latmus_runner *runner) +{ + return evl_mono_clock.gravity.user; +} + +static void set_uthread_gravity(struct latmus_runner *runner, + unsigned int gravity) +{ + evl_mono_clock.gravity.user = gravity; +} + +static unsigned int +adjust_uthread_gravity(struct latmus_runner *runner, int adjust) +{ + return evl_mono_clock.gravity.user += adjust; +} + +static int start_uthread_runner(struct latmus_runner *runner, + ktime_t start_time) +{ + struct uthread_runner *u_runner; + + u_runner = container_of(runner, struct uthread_runner, runner); + + evl_start_timer(&u_runner->timer, start_time, runner->period); + + return 0; +} + +static void stop_uthread_runner(struct latmus_runner *runner) +{ + struct uthread_runner *u_runner; + + u_runner = container_of(runner, struct uthread_runner, runner); + + evl_stop_timer(&u_runner->timer); +} + +static int add_uthread_sample(struct latmus_runner *runner, + ktime_t user_timestamp) +{ + struct uthread_runner *u_runner; + int ret; + + u_runner = container_of(runner, struct uthread_runner, runner); + + if (user_timestamp && + u_runner->runner.add_sample(runner, user_timestamp)) { + evl_stop_timer(&u_runner->timer); + /* Tell the caller to park until next round. */ + ret = -EPIPE; + } else { + ret = evl_wait_flag(&u_runner->pulse); + } + + return ret; +} + +static struct latmus_runner *create_uthread_runner(int cpu) +{ + struct uthread_runner *u_runner; + + u_runner = kzalloc(sizeof(*u_runner), GFP_KERNEL); + if (u_runner == NULL) + return NULL; + + u_runner->runner = (struct latmus_runner){ + .name = "uthread", + .destroy = destroy_uthread_runner, + .get_gravity = get_uthread_gravity, + .set_gravity = set_uthread_gravity, + .adjust_gravity = adjust_uthread_gravity, + .start = start_uthread_runner, + .stop = stop_uthread_runner, + }; + + init_runner_base(&u_runner->runner); + evl_init_timer_on_cpu(&u_runner->timer, cpu, latmus_pulse_handler); + evl_set_timer_gravity(&u_runner->timer, EVL_TIMER_UGRAVITY); + evl_init_flag(&u_runner->pulse); + + return &u_runner->runner; +} + +static inline void build_score(struct latmus_runner *runner, int step) +{ + struct runner_state *state = &runner->state; + unsigned int variance, n; + + n = state->cur_samples; + runner->scores[step].pmean = state->sum / n; + variance = n > 1 ? state->cur_sqs / (n - 1) : 0; + runner->scores[step].stddev = int_sqrt(variance); + runner->scores[step].minlat = state->min_lat; + runner->scores[step].gravity = runner->get_gravity(runner); + runner->scores[step].step = step; + runner->nscores++; +} + +static int cmp_score_mean(const void *c, const void *r) +{ + const struct tuning_score *sc = c, *sr = r; + return sc->pmean - sr->pmean; +} + +static int cmp_score_stddev(const void *c, const void *r) +{ + const struct tuning_score *sc = c, *sr = r; + return sc->stddev - sr->stddev; +} + +static int cmp_score_minlat(const void *c, const void *r) +{ + const struct tuning_score *sc = c, *sr = r; + return sc->minlat - sr->minlat; +} + +static int cmp_score_gravity(const void *c, const void *r) +{ + const struct tuning_score *sc = c, *sr = r; + return sc->gravity - sr->gravity; +} + +static int filter_mean(struct latmus_runner *runner) +{ + sort(runner->scores, runner->nscores, + sizeof(struct tuning_score), + cmp_score_mean, NULL); + + /* Top half of the best pondered means. */ + + return (runner->nscores + 1) / 2; +} + +static int filter_stddev(struct latmus_runner *runner) +{ + sort(runner->scores, runner->nscores, + sizeof(struct tuning_score), + cmp_score_stddev, NULL); + + /* Top half of the best standard deviations. */ + + return (runner->nscores + 1) / 2; +} + +static int filter_minlat(struct latmus_runner *runner) +{ + sort(runner->scores, runner->nscores, + sizeof(struct tuning_score), + cmp_score_minlat, NULL); + + /* Top half of the minimum latencies. */ + + return (runner->nscores + 1) / 2; +} + +static int filter_gravity(struct latmus_runner *runner) +{ + sort(runner->scores, runner->nscores, + sizeof(struct tuning_score), + cmp_score_gravity, NULL); + + /* Smallest gravity required among the shortest latencies. */ + + return runner->nscores; +} + +static void dump_scores(struct latmus_runner *runner) +{ + int n; + + if (runner->verbosity < 2) + return; + + for (n = 0; n < runner->nscores; n++) + printk(EVL_INFO + ".. S%.2d pmean=%d stddev=%d minlat=%d gravity=%u\n", + runner->scores[n].step, + runner->scores[n].pmean, + runner->scores[n].stddev, + runner->scores[n].minlat, + runner->scores[n].gravity); +} + +static inline void filter_score(struct latmus_runner *runner, + int (*filter)(struct latmus_runner *runner)) +{ + runner->nscores = filter(runner); + dump_scores(runner); +} + +static int measure_continously(struct latmus_runner *runner) +{ + struct runner_state *state = &runner->state; + ktime_t period = runner->period; + struct evl_file *sfilp; + struct evl_xbuf *xbuf; + int ret; + + /* + * Get a reference on the cross-buffer we should use to send + * interval results to userland. This may delay the disposal + * of such element when the last in-band file reference is + * dropped until we are done with OOB operations + * (evl_put_xbuf). + */ + xbuf = evl_get_xbuf(runner->xfd, &sfilp); + if (xbuf == NULL) + return -EBADF; /* muhh? */ + + state->max_samples = ONE_BILLION / (int)ktime_to_ns(period); + runner->add_sample = add_measurement_sample; + runner->xbuf = xbuf; + state->min_lat = INT_MAX; + state->max_lat = INT_MIN; + state->allmax_lat = INT_MIN; + state->sum = 0; + state->overruns = 0; + state->cur_samples = 0; + state->offset = 0; /* for SIRQ latency only. */ + state->ideal = ktime_add(evl_read_clock(&evl_mono_clock), period); + + ret = runner->start(runner, state->ideal); + if (ret) + goto out; + + ret = evl_wait_flag(&runner->done) ?: runner->status; + + if (runner->stop) + runner->stop(runner); +out: + evl_put_xbuf(sfilp); + + return ret; +} + +static int tune_gravity(struct latmus_runner *runner) +{ + struct runner_state *state = &runner->state; + int ret, step, gravity_limit, adjust; + ktime_t period = runner->period; + unsigned int orig_gravity; + + state->max_samples = TUNER_SAMPLING_TIME / (int)ktime_to_ns(period); + orig_gravity = runner->get_gravity(runner); + runner->add_sample = add_tuning_sample; + runner->set_gravity(runner, 0); + runner->nscores = 0; + adjust = 500; /* Gravity adjustment step */ + gravity_limit = 0; + progress(runner, "warming up..."); + + for (step = 0; step < TUNER_WARMUP_STEPS + TUNER_RESULT_STEPS; step++) { + state->ideal = ktime_add_ns(evl_read_clock(&evl_mono_clock), + ktime_to_ns(period) * TUNER_WARMUP_STEPS); + state->min_lat = INT_MAX; + state->max_lat = INT_MIN; + state->prev_mean = 0; + state->prev_sqs = 0; + state->cur_sqs = 0; + state->sum = 0; + state->cur_samples = 0; + + ret = runner->start(runner, state->ideal); + if (ret) + goto fail; + + /* Runner stops when posting. */ + ret = evl_wait_flag(&runner->done); + if (ret) + goto fail; + + ret = runner->status; + if (ret) + goto fail; + + if (step < TUNER_WARMUP_STEPS) { + if (state->min_lat > gravity_limit) { + gravity_limit = state->min_lat; + progress(runner, "gravity limit set to %u ns (%d)", + gravity_limit, state->min_lat); + } + continue; + } + + if (state->min_lat < 0) { + if (runner->get_gravity(runner) < -state->min_lat) { + printk(EVL_WARNING + "latmus(%s) failed with early shot (%d ns)\n", + runner->name, + -(runner->get_gravity(runner) + state->min_lat)); + ret = -EAGAIN; + goto fail; + } + break; + } + + if (((step - TUNER_WARMUP_STEPS) % 5) == 0) + progress(runner, "calibrating... (slice %d)", + (step - TUNER_WARMUP_STEPS) / 5 + 1); + + build_score(runner, step - TUNER_WARMUP_STEPS); + + /* + * Anticipating by more than the minimum latency + * detected at warmup would make no sense: cap the + * gravity we may try. + */ + if (runner->adjust_gravity(runner, adjust) > gravity_limit) { + progress(runner, "beyond gravity limit at %u ns", + runner->get_gravity(runner)); + break; + } + } + + progress(runner, "calibration scores"); + dump_scores(runner); + progress(runner, "pondered mean filter"); + filter_score(runner, filter_mean); + progress(runner, "standard deviation filter"); + filter_score(runner, filter_stddev); + progress(runner, "minimum latency filter"); + filter_score(runner, filter_minlat); + progress(runner, "gravity filter"); + filter_score(runner, filter_gravity); + runner->set_gravity(runner, runner->scores[0].gravity); + + return 0; +fail: + runner->set_gravity(runner, orig_gravity); + + return ret; +} + +static int setup_tuning(struct latmus_runner *runner, + struct latmus_setup *setup) +{ + runner->verbosity = setup->u.tune.verbosity; + runner->period = setup->period; + + return 0; +} + +static int run_tuning(struct latmus_runner *runner, + struct latmus_result *result) +{ + __u32 gravity; + int ret; + + ret = tune_gravity(runner); + if (ret) + return ret; + + gravity = runner->get_gravity(runner); + + if (raw_copy_to_user_ptr64(result->data_ptr, &gravity, sizeof(gravity))) + return -EFAULT; + + return 0; +} + +static int setup_measurement(struct latmus_runner *runner, + struct latmus_setup *setup) +{ + runner->period = setup->period; + runner->warmup_limit = ONE_BILLION / (int)ktime_to_ns(setup->period); /* 1s warmup */ + runner->xfd = setup->u.measure.xfd; + runner->histogram = NULL; + runner->hcells = setup->u.measure.hcells; + if (runner->hcells == 0) + return 0; + + if (runner->hcells > 1000) /* LART */ + return -EINVAL; + + runner->histogram = kzalloc(runner->hcells * sizeof(s32), + GFP_KERNEL); + + return runner->histogram ? 0 : -ENOMEM; +} + +static int run_measurement(struct latmus_runner *runner, + struct latmus_result *result) +{ + struct runner_state *state = &runner->state; + struct latmus_measurement_result mr; + struct latmus_measurement last; + size_t len; + int ret; + + if (result->len != sizeof(mr)) + return -EINVAL; + + if (raw_copy_from_user_ptr64(&mr, result->data_ptr, sizeof(mr))) + return -EFAULT; + + ret = measure_continously(runner); + if (ret != -EINTR) + return ret; + + /* + * Copy the last bulk of consolidated measurements and the + * histogram distribution data back to userland. + */ + last.min_lat = state->min_lat; + last.max_lat = state->max_lat; + last.sum_lat = state->sum; + last.overruns = state->overruns; + last.samples = state->cur_samples; + if (raw_copy_to_user_ptr64(mr.last_ptr, &last, sizeof(last))) + return -EFAULT; + + if (runner->histogram) { + len = runner->hcells * sizeof(s32); + if (len > mr.len) + len = result->len; + if (len > 0 && + raw_copy_to_user_ptr64(mr.histogram_ptr, + runner->histogram, len)) + return -EFAULT; + } + + return 0; +} + +static void cleanup_measurement(struct latmus_runner *runner) +{ + if (runner->histogram) + kfree(runner->histogram); +} + +static long latmus_ioctl(struct file *filp, unsigned int cmd, + unsigned long arg) +{ + struct latmus_state *ls = filp->private_data; + int (*setup)(struct latmus_runner *runner, + struct latmus_setup *setup_data); + int (*run)(struct latmus_runner *runner, + struct latmus_result *result); + void (*cleanup)(struct latmus_runner *runner); + struct latmus_setup setup_data; + struct latmus_runner *runner; + int ret; + + if (cmd == EVL_LATIOC_RESET) { + evl_reset_clock_gravity(&evl_mono_clock); + return 0; + } + + /* All other cmds require a setup struct to be passed. */ + + if (copy_from_user(&setup_data, (struct latmus_setup __user *)arg, + sizeof(setup_data))) + return -EFAULT; + + if (setup_data.type == EVL_LAT_SIRQ && cmd != EVL_LATIOC_MEASURE) + return -EINVAL; + + switch (cmd) { + case EVL_LATIOC_TUNE: + setup = setup_tuning; + run = run_tuning; + cleanup = NULL; + break; + case EVL_LATIOC_MEASURE: + setup = setup_measurement; + run = run_measurement; + cleanup = cleanup_measurement; + break; + default: + return -ENOTTY; + } + + if (setup_data.period <= 0 || + setup_data.period > ONE_BILLION) + return -EINVAL; + + if (setup_data.priority < 1 || + setup_data.priority > EVL_FIFO_MAX_PRIO) + return -EINVAL; + + if (setup_data.cpu >= num_possible_cpus() || + !is_evl_cpu(setup_data.cpu)) + return -EINVAL; + + /* Clear previous runner. */ + runner = ls->runner; + if (runner) { + runner->destroy(runner); + ls->runner = NULL; + } + + switch (setup_data.type) { + case EVL_LAT_IRQ: + runner = create_irq_runner(setup_data.cpu); + break; + case EVL_LAT_KERN: + runner = create_kthread_runner(setup_data.priority, + setup_data.cpu); + break; + case EVL_LAT_USER: + runner = create_uthread_runner(setup_data.cpu); + break; + case EVL_LAT_SIRQ: + runner = create_sirq_runner(setup_data.cpu); + break; + default: + return -EINVAL; + } + + if (IS_ERR(runner)) + return PTR_ERR(runner); + + ret = setup(runner, &setup_data); + if (ret) { + runner->destroy(runner); + return ret; + } + + runner->run = run; + runner->cleanup = cleanup; + ls->runner = runner; + + return 0; +} + +static long latmus_oob_ioctl(struct file *filp, unsigned int cmd, + unsigned long arg) +{ + struct latmus_state *ls = filp->private_data; + struct latmus_runner *runner; + struct latmus_result result; + __u64 timestamp; + int ret; + + runner = ls->runner; + if (runner == NULL) + return -EAGAIN; + + switch (cmd) { + case EVL_LATIOC_RUN: + ret = raw_copy_from_user(&result, + (struct latmus_result __user *)arg, + sizeof(result)); + if (ret) + return -EFAULT; + ret = runner->run(runner, &result); + break; + case EVL_LATIOC_PULSE: + if (runner->start != start_uthread_runner) + return -EINVAL; + ret = raw_copy_from_user(×tamp, (__u64 __user *)arg, + sizeof(timestamp)); + if (ret) + return -EFAULT; + ret = add_uthread_sample(runner, ns_to_ktime(timestamp)); + break; + default: + ret = -ENOTTY; + } + + return ret; +} + +static int latmus_open(struct inode *inode, struct file *filp) +{ + struct latmus_state *ls; + int ret; + + ls = kzalloc(sizeof(*ls), GFP_KERNEL); + if (ls == NULL) + return -ENOMEM; + + ret = evl_open_file(&ls->efile, filp); + if (ret) + kfree(ls); + + filp->private_data = ls; + stream_open(inode, filp); + + return ret; +} + +static int latmus_release(struct inode *inode, struct file *filp) +{ + struct latmus_state *ls = filp->private_data; + struct latmus_runner *runner; + + runner = ls->runner; + if (runner) + runner->destroy(runner); + + evl_release_file(&ls->efile); + kfree(ls); + + return 0; +} + +static struct class latmus_class = { + .name = "latmus", +}; + +static const struct file_operations latmus_fops = { + .open = latmus_open, + .release = latmus_release, + .unlocked_ioctl = latmus_ioctl, + .oob_ioctl = latmus_oob_ioctl, +#ifdef CONFIG_COMPAT + .compat_ioctl = compat_ptr_ioctl, + .compat_oob_ioctl = compat_ptr_oob_ioctl, +#endif +}; + +static dev_t latmus_devt; + +static struct cdev latmus_cdev; + +static int __init latmus_init(void) +{ + struct device *dev; + int ret; + + ret = class_register(&latmus_class); + if (ret) + return ret; + + ret = alloc_chrdev_region(&latmus_devt, 0, 1, "latmus"); + if (ret) + goto fail_region; + + cdev_init(&latmus_cdev, &latmus_fops); + ret = cdev_add(&latmus_cdev, latmus_devt, 1); + if (ret) + goto fail_add; + + dev = device_create(&latmus_class, NULL, latmus_devt, NULL, "latmus"); + if (IS_ERR(dev)) { + ret = PTR_ERR(dev); + goto fail_dev; + } + + return 0; + +fail_dev: + cdev_del(&latmus_cdev); +fail_add: + unregister_chrdev_region(latmus_devt, 1); +fail_region: + class_unregister(&latmus_class); + + return ret; +} +module_init(latmus_init); + +static void __exit latmus_exit(void) +{ + device_destroy(&latmus_class, MKDEV(MAJOR(latmus_devt), 0)); + cdev_del(&latmus_cdev); + class_unregister(&latmus_class); +} +module_exit(latmus_exit); + +MODULE_LICENSE("GPL"); diff --git a/drivers/gpio/Kconfig b/drivers/gpio/Kconfig index d0c38993b..7daf953db 100644 --- a/drivers/gpio/Kconfig +++ b/drivers/gpio/Kconfig @@ -47,6 +47,16 @@ config OF_GPIO_MM_GPIOCHIP this symbol, but new drivers should use the generic gpio-regmap infrastructure instead. +config GPIOLIB_OOB + bool "Out-of-band GPIO calls" + depends on EVL + select GPIO_CDEV + select GPIO_CDEV_V1 + help + Enable support for out-of-band GPIO line handling requests via + the user-space interface, which are served by the EVL real-time + core. + config DEBUG_GPIO bool "Debug GPIO calls" depends on DEBUG_KERNEL diff --git a/drivers/gpio/gpio-brcmstb.c b/drivers/gpio/gpio-brcmstb.c index 5f7e93335..901057fb0 100644 --- a/drivers/gpio/gpio-brcmstb.c +++ b/drivers/gpio/gpio-brcmstb.c @@ -478,6 +478,9 @@ static int brcmstb_gpio_irq_setup(struct platform_device *pdev, priv->irq_chip.irq_unmask = brcmstb_gpio_irq_unmask; priv->irq_chip.irq_ack = brcmstb_gpio_irq_ack; priv->irq_chip.irq_set_type = brcmstb_gpio_irq_set_type; + // test 2024-11-15 set flag (BB) + priv->irq_chip.flags = IRQCHIP_PIPELINE_SAFE; + if (priv->parent_wake_irq) priv->irq_chip.irq_set_wake = brcmstb_gpio_irq_set_wake; diff --git a/drivers/gpio/gpio-davinci.c b/drivers/gpio/gpio-davinci.c index 75107ede3..f59195ad1 100644 --- a/drivers/gpio/gpio-davinci.c +++ b/drivers/gpio/gpio-davinci.c @@ -327,7 +327,8 @@ static struct irq_chip gpio_irqchip = { .irq_unmask = gpio_irq_unmask, .irq_mask = gpio_irq_mask, .irq_set_type = gpio_irq_type, - .flags = IRQCHIP_SET_TYPE_MASKED | IRQCHIP_SKIP_SET_WAKE, + .flags = IRQCHIP_SET_TYPE_MASKED | IRQCHIP_SKIP_SET_WAKE | + IRQCHIP_PIPELINE_SAFE, }; static void gpio_irq_handler(struct irq_desc *desc) diff --git a/drivers/gpio/gpio-mxc.c b/drivers/gpio/gpio-mxc.c index 4cb455b2b..0e3f9bbb1 100644 --- a/drivers/gpio/gpio-mxc.c +++ b/drivers/gpio/gpio-mxc.c @@ -365,7 +365,8 @@ static int mxc_gpio_init_gc(struct mxc_gpio_port *port, int irq_base) ct->chip.irq_unmask = irq_gc_mask_set_bit; ct->chip.irq_set_type = gpio_set_irq_type; ct->chip.irq_set_wake = gpio_set_wake_irq; - ct->chip.flags = IRQCHIP_MASK_ON_SUSPEND | IRQCHIP_ENABLE_WAKEUP_ON_SUSPEND; + ct->chip.flags = IRQCHIP_MASK_ON_SUSPEND | + IRQCHIP_ENABLE_WAKEUP_ON_SUSPEND | IRQCHIP_PIPELINE_SAFE; ct->regs.ack = GPIO_ISR; ct->regs.mask = GPIO_IMR; diff --git a/drivers/gpio/gpio-omap.c b/drivers/gpio/gpio-omap.c index a927680c6..7f42b4e40 100644 --- a/drivers/gpio/gpio-omap.c +++ b/drivers/gpio/gpio-omap.c @@ -56,8 +56,8 @@ struct gpio_bank { u32 saved_datain; u32 level_mask; u32 toggle_mask; - raw_spinlock_t lock; - raw_spinlock_t wa_lock; + hard_spinlock_t lock; + hard_spinlock_t wa_lock; struct gpio_chip chip; struct clk *dbck; struct notifier_block nb; @@ -728,7 +728,7 @@ static const struct irq_chip omap_gpio_irq_chip = { .irq_bus_lock = omap_gpio_irq_bus_lock, .irq_bus_sync_unlock = gpio_irq_bus_sync_unlock, .irq_print_chip = omap_gpio_irq_print_chip, - .flags = IRQCHIP_MASK_ON_SUSPEND | IRQCHIP_IMMUTABLE, + .flags = IRQCHIP_MASK_ON_SUSPEND | IRQCHIP_IMMUTABLE | IRQCHIP_PIPELINE_SAFE, GPIOCHIP_IRQ_RESOURCE_HELPERS, }; @@ -741,7 +741,7 @@ static const struct irq_chip omap_gpio_irq_chip_nowake = { .irq_bus_lock = omap_gpio_irq_bus_lock, .irq_bus_sync_unlock = gpio_irq_bus_sync_unlock, .irq_print_chip = omap_gpio_irq_print_chip, - .flags = IRQCHIP_MASK_ON_SUSPEND | IRQCHIP_IMMUTABLE, + .flags = IRQCHIP_MASK_ON_SUSPEND | IRQCHIP_IMMUTABLE | IRQCHIP_PIPELINE_SAFE, GPIOCHIP_IRQ_RESOURCE_HELPERS, }; @@ -1077,7 +1077,7 @@ static int omap_gpio_chip_init(struct gpio_bank *bank, struct device *pm_dev) irq_domain_set_pm_device(bank->chip.irq.domain, pm_dev); ret = devm_request_irq(bank->chip.parent, bank->irq, omap_gpio_irq_handler, - 0, dev_name(bank->chip.parent), bank); + IRQF_OOB, dev_name(bank->chip.parent), bank); if (ret) gpiochip_remove(&bank->chip); diff --git a/drivers/gpio/gpio-pca953x.c b/drivers/gpio/gpio-pca953x.c index 11bdd6782..824821211 100644 --- a/drivers/gpio/gpio-pca953x.c +++ b/drivers/gpio/gpio-pca953x.c @@ -835,7 +835,7 @@ static const struct irq_chip pca953x_irq_chip = { .irq_set_type = pca953x_irq_set_type, .irq_shutdown = pca953x_irq_shutdown, .irq_print_chip = pca953x_irq_print_chip, - .flags = IRQCHIP_IMMUTABLE, + .flags = IRQCHIP_IMMUTABLE | IRQCHIP_PIPELINE_SAFE, GPIOCHIP_IRQ_RESOURCE_HELPERS, }; diff --git a/drivers/gpio/gpio-pl061.c b/drivers/gpio/gpio-pl061.c index 9fc1f3dd4..d5870aca4 100644 --- a/drivers/gpio/gpio-pl061.c +++ b/drivers/gpio/gpio-pl061.c @@ -49,7 +49,7 @@ struct pl061_context_save_regs { #endif struct pl061 { - raw_spinlock_t lock; + hard_spinlock_t lock; void __iomem *base; struct gpio_chip gc; @@ -301,7 +301,7 @@ static const struct irq_chip pl061_irq_chip = { .irq_set_type = pl061_irq_type, .irq_set_wake = pl061_irq_set_wake, .irq_print_chip = pl061_irq_print_chip, - .flags = IRQCHIP_IMMUTABLE, + .flags = IRQCHIP_IMMUTABLE|IRQCHIP_PIPELINE_SAFE, GPIOCHIP_IRQ_RESOURCE_HELPERS, }; diff --git a/drivers/gpio/gpio-xilinx.c b/drivers/gpio/gpio-xilinx.c old mode 100644 new mode 100755 index 956ea2957..356541268 --- a/drivers/gpio/gpio-xilinx.c +++ b/drivers/gpio/gpio-xilinx.c @@ -66,7 +66,7 @@ struct xgpio_instance { DECLARE_BITMAP(state, 64); DECLARE_BITMAP(last_irq_read, 64); DECLARE_BITMAP(dir, 64); - raw_spinlock_t gpio_lock; /* For serializing operations */ + hard_spinlock_t gpio_lock; /* For serializing operations */ int irq; DECLARE_BITMAP(enable, 64); DECLARE_BITMAP(rising_edge, 64); diff --git a/drivers/gpio/gpio-zynq.c b/drivers/gpio/gpio-zynq.c index 324e942c0..f73abe7d7 100644 --- a/drivers/gpio/gpio-zynq.c +++ b/drivers/gpio/gpio-zynq.c @@ -607,7 +607,7 @@ static const struct irq_chip zynq_gpio_level_irqchip = { .irq_request_resources = zynq_gpio_irq_reqres, .irq_release_resources = zynq_gpio_irq_relres, .flags = IRQCHIP_EOI_THREADED | IRQCHIP_EOI_IF_HANDLED | - IRQCHIP_MASK_ON_SUSPEND | IRQCHIP_IMMUTABLE, + IRQCHIP_MASK_ON_SUSPEND | IRQCHIP_IMMUTABLE | IRQCHIP_PIPELINE_SAFE, }; static const struct irq_chip zynq_gpio_edge_irqchip = { @@ -620,7 +620,7 @@ static const struct irq_chip zynq_gpio_edge_irqchip = { .irq_set_wake = zynq_gpio_set_wake, .irq_request_resources = zynq_gpio_irq_reqres, .irq_release_resources = zynq_gpio_irq_relres, - .flags = IRQCHIP_MASK_ON_SUSPEND | IRQCHIP_IMMUTABLE, + .flags = IRQCHIP_MASK_ON_SUSPEND | IRQCHIP_IMMUTABLE | IRQCHIP_PIPELINE_SAFE, }; static void zynq_gpio_handle_bank_irq(struct zynq_gpio *gpio, diff --git a/drivers/gpio/gpiolib-cdev.c b/drivers/gpio/gpiolib-cdev.c index 545998e9f..7021337ea 100644 --- a/drivers/gpio/gpiolib-cdev.c +++ b/drivers/gpio/gpiolib-cdev.c @@ -30,6 +30,7 @@ #include #include +#include #include "gpiolib.h" #include "gpiolib-cdev.h" @@ -120,6 +121,8 @@ struct linehandle_state { const char *label; struct gpio_desc *descs[GPIOHANDLES_MAX]; u32 num_descs; + u32 lflags; + struct linehandle_oob_state oob_state; }; #define GPIOHANDLE_REQUEST_VALID_FLAGS \ @@ -130,7 +133,13 @@ struct linehandle_state { GPIOHANDLE_REQUEST_BIAS_PULL_DOWN | \ GPIOHANDLE_REQUEST_BIAS_DISABLE | \ GPIOHANDLE_REQUEST_OPEN_DRAIN | \ - GPIOHANDLE_REQUEST_OPEN_SOURCE) + GPIOHANDLE_REQUEST_OPEN_SOURCE | \ + (IS_ENABLED(CONFIG_GPIOLIB_OOB) ? GPIOHANDLE_REQUEST_OOB : 0)) + +static inline bool oob_handling_requested(u32 lflags) +{ + return IS_ENABLED(CONFIG_GPIOLIB_OOB) && lflags & GPIOHANDLE_REQUEST_OOB; +} #define GPIOHANDLE_REQUEST_DIRECTION_FLAGS \ (GPIOHANDLE_REQUEST_INPUT | \ @@ -317,6 +326,54 @@ static long linehandle_ioctl_compat(struct file *file, unsigned int cmd, } #endif +#ifdef CONFIG_GPIOLIB_OOB + +static long linehandle_oob_ioctl(struct file *file, unsigned int cmd, + unsigned long arg) +{ + struct linehandle_state *lh = file->private_data; + DECLARE_BITMAP(valmap, GPIOHANDLES_MAX); + struct gpio_chip *gc = lh->gdev->chip; + void __user *ip = (void __user *)arg; + struct gpiohandle_data ghd; + int i, ret; + + if (!oob_handling_requested(lh->lflags)) + return -EPERM; + + if (cmd == GPIOHANDLE_GET_LINE_VALUES_IOCTL) { + ret = gpiod_get_array_value_oob(gc, valmap, + lh->num_descs, lh->descs); + if (ret) + return ret; + + memset(&ghd, 0, sizeof(ghd)); + for (i = 0; i < lh->num_descs; i++) + ghd.values[i] = test_bit(i, valmap); + + if (raw_copy_to_user(ip, &ghd, sizeof(ghd))) + return -EFAULT; + + return 0; + } else if (cmd == GPIOHANDLE_SET_LINE_VALUES_IOCTL) { + if (!test_bit(FLAG_IS_OUT, &lh->descs[0]->flags)) + return -EPERM; + + if (raw_copy_from_user(&ghd, ip, sizeof(ghd))) + return -EFAULT; + + for (i = 0; i < lh->num_descs; i++) + __assign_bit(i, valmap, ghd.values[i]); + + return gpiod_set_array_value_oob(gc, valmap, + lh->num_descs, lh->descs); + } + + return -EINVAL; +} + +#endif /* CONFIG_GPIOLIB_OOB */ + static void linehandle_free(struct linehandle_state *lh) { int i; @@ -331,7 +388,12 @@ static void linehandle_free(struct linehandle_state *lh) static int linehandle_release(struct inode *inode, struct file *file) { - linehandle_free(file->private_data); + struct linehandle_state *lh = file->private_data; + + if (oob_handling_requested(lh->lflags)) + evl_release_file(&lh->oob_state.efile); + + linehandle_free(lh); return 0; } @@ -340,9 +402,15 @@ static const struct file_operations linehandle_fileops = { .owner = THIS_MODULE, .llseek = noop_llseek, .unlocked_ioctl = linehandle_ioctl, +#ifdef CONFIG_GPIOLIB_OOB + .oob_ioctl = linehandle_oob_ioctl, +#endif #ifdef CONFIG_COMPAT .compat_ioctl = linehandle_ioctl_compat, #endif +#ifdef CONFIG_GPIOLIB_OOB + .compat_oob_ioctl = compat_ptr_oob_ioctl, +#endif }; static int linehandle_create(struct gpio_device *gdev, void __user *ip) @@ -360,6 +428,18 @@ static int linehandle_create(struct gpio_device *gdev, void __user *ip) lflags = handlereq.flags; + if (oob_handling_requested(lflags)) { + if (gdev->chip->ngpio > CONFIG_GPIOLIB_FASTPATH_LIMIT) { + chip_warn(gdev->chip, + "too many lines for out-of-band handling" + " (%u > %u fastpath)\n", + gdev->chip->ngpio, CONFIG_GPIOLIB_FASTPATH_LIMIT); + return -EOPNOTSUPP; + } + if (gdev->chip->can_sleep) + return -EOPNOTSUPP; + } + ret = linehandle_validate_flags(lflags); if (ret) return ret; @@ -368,6 +448,7 @@ static int linehandle_create(struct gpio_device *gdev, void __user *ip) if (!lh) return -ENOMEM; lh->gdev = gpio_device_get(gdev); + lh->lflags = lflags; if (handlereq.consumer_label[0] != '\0') { /* label is only initialized if consumer_label is set */ @@ -439,6 +520,14 @@ static int linehandle_create(struct gpio_device *gdev, void __user *ip) goto out_put_unused_fd; } + if (oob_handling_requested(lflags)) { + ret = evl_open_file(&lh->oob_state.efile, file); + if (ret) { + fput(file); + goto out_put_unused_fd; + } + } + handlereq.fd = fd; if (copy_to_user(ip, &handlereq, sizeof(handlereq))) { /* @@ -1986,12 +2075,14 @@ struct lineevent_state { struct gpio_device *gdev; const char *label; struct gpio_desc *desc; + u32 lflags; u32 eflags; int irq; wait_queue_head_t wait; struct notifier_block device_unregistered_nb; DECLARE_KFIFO(events, struct gpioevent_data, 16); u64 timestamp; + struct lineevent_oob_state oob_state; }; #define GPIOEVENT_REQUEST_VALID_FLAGS \ @@ -2051,6 +2142,9 @@ static ssize_t lineevent_read_unlocked(struct file *file, char __user *buf, if (!le->gdev->chip) return -ENODEV; + if (oob_handling_requested(le->lflags)) + return -EPERM; + /* * When compatible system call is being used the struct gpioevent_data, * in case of at least ia32, has different size due to the alignment @@ -2117,6 +2211,142 @@ static ssize_t lineevent_read(struct file *file, char __user *buf, lineevent_read_unlocked); } +static irqreturn_t lineevent_read_pin(struct lineevent_state *le, + struct gpioevent_data *ge, + bool maysleep) +{ + if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE + && le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE) { + int level; + if (maysleep) + level = gpiod_get_value_cansleep(le->desc); + else + level = gpiod_get_value(le->desc); + if (level) + /* Emit low-to-high event */ + ge->id = GPIOEVENT_EVENT_RISING_EDGE; + else + /* Emit high-to-low event */ + ge->id = GPIOEVENT_EVENT_FALLING_EDGE; + } else if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE) { + /* Emit low-to-high event */ + ge->id = GPIOEVENT_EVENT_RISING_EDGE; + } else if (le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE) { + /* Emit high-to-low event */ + ge->id = GPIOEVENT_EVENT_FALLING_EDGE; + } else { + return IRQ_NONE; + } + + return IRQ_HANDLED; +} + +#ifdef CONFIG_GPIOLIB_OOB + +static irqreturn_t lineevent_oob_irq_handler(int irq, void *p) +{ + struct lineevent_state *le = p; + struct gpioevent_data ge; + + ge.timestamp = evl_ktime_monotonic(); + + if (lineevent_read_pin(le, &ge, false) == IRQ_NONE) + return IRQ_NONE; + + raw_spin_lock(&le->oob_state.wait.wchan.lock); + kfifo_put(&le->events, ge); + evl_wake_up_head(&le->oob_state.wait); + evl_signal_poll_events(&le->oob_state.poll_head, POLLIN|POLLRDNORM); + raw_spin_unlock(&le->oob_state.wait.wchan.lock); + + return IRQ_HANDLED; +} + +static __poll_t lineevent_oob_poll(struct file *file, + struct oob_poll_wait *wait) +{ + struct lineevent_state *le = file->private_data; + unsigned long flags; + __poll_t ready = 0; + + evl_poll_watch(&le->oob_state.poll_head, wait, NULL); + + raw_spin_lock_irqsave(&le->oob_state.wait.wchan.lock, flags); + + if (!kfifo_is_empty(&le->events)) + ready |= POLLIN|POLLRDNORM; + + raw_spin_unlock_irqrestore(&le->oob_state.wait.wchan.lock, flags); + + return ready; +} + +static ssize_t lineevent_oob_read(struct file *file, + char __user *buf, + size_t count) +{ + struct lineevent_state *le = file->private_data; + struct gpioevent_data ge = { 0 }; + unsigned long flags; + int ret; + + if (count < sizeof(struct gpioevent_data)) + return -EINVAL; + + if (!oob_handling_requested(le->lflags)) + return -EPERM; + + do { + raw_spin_lock_irqsave(&le->oob_state.wait.wchan.lock, flags); + + ret = kfifo_get(&le->events, &ge); + /* + * Silly work around to address a false positive + * enabling -Wmaybe-uninitialized w/ gcc 8.3.1. + */ + if (!ret) + ret = 0; + + raw_spin_unlock_irqrestore(&le->oob_state.wait.wchan.lock, flags); + + if (ret) { + ret = raw_copy_to_user(buf, &ge, sizeof(ge)); + return ret ? -EFAULT : sizeof(ge); + } + + if (file->f_flags & O_NONBLOCK) + return -EAGAIN; + + ret = evl_wait_event(&le->oob_state.wait, + !kfifo_is_empty(&le->events)); + } while (!ret); + + return ret; +} + +static int lineevent_init_oob_state(struct lineevent_state *le, + int irq, const char *label, int irqflags) +{ + evl_init_wait(&le->oob_state.wait, &evl_mono_clock, EVL_WAIT_PRIO); + evl_init_poll_head(&le->oob_state.poll_head); + + return request_irq(irq, + lineevent_oob_irq_handler, + irqflags | IRQF_OOB, + label, + le); +} + +#else + +static inline int lineevent_init_oob_state(struct lineevent_state *le, + int irq, const char *label, int irqflags) +{ + return -EINVAL; +} + +#endif /* !CONFIG_GPIOLIB_OOB */ + static void lineevent_free(struct lineevent_state *le) { if (le->device_unregistered_nb.notifier_call) @@ -2133,7 +2363,12 @@ static void lineevent_free(struct lineevent_state *le) static int lineevent_release(struct inode *inode, struct file *file) { - lineevent_free(file->private_data); + struct lineevent_state *le = file->private_data; + + if (oob_handling_requested(le->lflags)) + evl_release_file(&le->oob_state.efile); + + lineevent_free(le); return 0; } @@ -2189,6 +2424,10 @@ static long lineevent_ioctl_compat(struct file *file, unsigned int cmd, static const struct file_operations lineevent_fileops = { .release = lineevent_release, .read = lineevent_read, +#ifdef CONFIG_GPIOLIB_OOB + .oob_read = lineevent_oob_read, + .oob_poll = lineevent_oob_poll, +#endif .poll = lineevent_poll, .owner = THIS_MODULE, .llseek = noop_llseek, @@ -2216,25 +2455,8 @@ static irqreturn_t lineevent_irq_thread(int irq, void *p) else ge.timestamp = le->timestamp; - if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE - && le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE) { - int level = gpiod_get_value_cansleep(le->desc); - - if (level) - /* Emit low-to-high event */ - ge.id = GPIOEVENT_EVENT_RISING_EDGE; - else - /* Emit high-to-low event */ - ge.id = GPIOEVENT_EVENT_FALLING_EDGE; - } else if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE) { - /* Emit low-to-high event */ - ge.id = GPIOEVENT_EVENT_RISING_EDGE; - } else if (le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE) { - /* Emit high-to-low event */ - ge.id = GPIOEVENT_EVENT_FALLING_EDGE; - } else { + if (lineevent_read_pin(le, &ge, true) == IRQ_NONE) return IRQ_NONE; - } ret = kfifo_in_spinlocked_noirqsave(&le->events, &ge, 1, &le->wait.lock); @@ -2324,6 +2546,7 @@ static int lineevent_create(struct gpio_device *gdev, void __user *ip) goto out_free_le; le->desc = desc; le->eflags = eflags; + le->lflags = lflags; linehandle_flags_to_desc_flags(lflags, &desc->flags); @@ -2362,13 +2585,20 @@ static int lineevent_create(struct gpio_device *gdev, void __user *ip) goto out_free_le; } - /* Request a thread to read the events */ - ret = request_threaded_irq(irq, - lineevent_irq_handler, - lineevent_irq_thread, - irqflags, - label, - le); + if (oob_handling_requested(lflags)) { + if (desc->gdev->chip->can_sleep) + ret = -EOPNOTSUPP; + else + ret = lineevent_init_oob_state(le, irq, label, irqflags); + } else { + /* Request a thread to read the events */ + ret = request_threaded_irq(irq, + lineevent_irq_handler, + lineevent_irq_thread, + irqflags, + label, + le); + } if (ret) { free_irq_label(label); goto out_free_le; @@ -2391,21 +2621,31 @@ static int lineevent_create(struct gpio_device *gdev, void __user *ip) goto out_put_unused_fd; } + if (oob_handling_requested(lflags)) { + ret = evl_open_file(&le->oob_state.efile, file); + if (ret) + goto out_put_file; + } + eventreq.fd = fd; if (copy_to_user(ip, &eventreq, sizeof(eventreq))) { /* * fput() will trigger the release() callback, so do not go onto * the regular error cleanup path here. */ - fput(file); - put_unused_fd(fd); - return -EFAULT; + if (oob_handling_requested(lflags)) + evl_release_file(&le->oob_state.efile); + + ret = -EFAULT; + goto out_put_file; } fd_install(fd, file); return 0; +out_put_file: + fput(file); out_put_unused_fd: put_unused_fd(fd); out_free_le: diff --git a/drivers/gpio/gpiolib.c b/drivers/gpio/gpiolib.c index 3710585e7..bf3a96127 100644 --- a/drivers/gpio/gpiolib.c +++ b/drivers/gpio/gpiolib.c @@ -3263,6 +3263,78 @@ int gpiod_set_array_value_complex(bool raw, bool can_sleep, return 0; } +#ifdef CONFIG_GPIOLIB_OOB + +int gpiod_get_array_value_oob(struct gpio_chip *gc, + unsigned long *value_bitmap, + u32 num_descs, + struct gpio_desc **desc_array) +{ + unsigned long mask[2 * BITS_TO_LONGS(CONFIG_GPIOLIB_FASTPATH_LIMIT)]; + unsigned long *bits = mask + BITS_TO_LONGS(gc->ngpio); + const struct gpio_desc *desc; + int ret, n, hwgpio, value; + + bitmap_zero(mask, gc->ngpio); + + for (n = 0; n < num_descs; n++) { + desc = desc_array[n]; + hwgpio = gpio_chip_hwgpio(desc); + __set_bit(hwgpio, mask); + } + + ret = gpio_chip_get_multiple(gc, mask, bits); + if (ret) + return ret; + + for (n = 0; n < num_descs; n++) { + desc = desc_array[n]; + hwgpio = gpio_chip_hwgpio(desc); + value = test_bit(hwgpio, bits); + /* We assume non-raw mode. */ + if (test_bit(FLAG_ACTIVE_LOW, &desc->flags)) + value = !value; + __assign_bit(n, value_bitmap, value); + trace_gpio_value(desc_to_gpio(desc), 1, value); + } + + return 0; +} + +int gpiod_set_array_value_oob(struct gpio_chip *gc, + const unsigned long *value_bitmap, + u32 num_descs, + struct gpio_desc **desc_array) +{ + unsigned long mask[2 * BITS_TO_LONGS(CONFIG_GPIOLIB_FASTPATH_LIMIT)]; + unsigned long *bits = mask + BITS_TO_LONGS(gc->ngpio); + const struct gpio_desc *desc; + int n, hwgpio, value; + + bitmap_zero(mask, gc->ngpio); + + for (n = 0; n < num_descs; n++) { + desc = desc_array[n]; + hwgpio = gpio_chip_hwgpio(desc); + __set_bit(hwgpio, mask); + /* We assume non-raw mode. */ + value = test_bit(n, value_bitmap); + if (test_bit(FLAG_ACTIVE_LOW, &desc->flags)) + value = !value; + if (value) + __set_bit(hwgpio, bits); + else + __clear_bit(hwgpio, bits); + trace_gpio_value(desc_to_gpio(desc), 0, value); + } + + gpio_chip_set_multiple(gc, mask, bits); + + return 0; +} + +#endif /* CONFIG_GPIOLIB_OOB */ + /** * gpiod_set_raw_value() - assign a gpio's raw value * @desc: gpio whose value will be assigned diff --git a/drivers/gpio/gpiolib.h b/drivers/gpio/gpiolib.h index 9bbde3823..22c735e0c 100644 --- a/drivers/gpio/gpiolib.h +++ b/drivers/gpio/gpiolib.h @@ -134,6 +134,17 @@ int gpiod_set_array_value_complex(bool raw, bool can_sleep, struct gpio_array *array_info, unsigned long *value_bitmap); +#ifdef CONFIG_GPIOLIB_OOB +int gpiod_get_array_value_oob(struct gpio_chip *gc, + unsigned long *value_bitmap, + u32 num_descs, + struct gpio_desc **desc_array); +int gpiod_set_array_value_oob(struct gpio_chip *gc, + const unsigned long *value_bitmap, + u32 num_descs, + struct gpio_desc **desc_array); +#endif + extern spinlock_t gpio_lock; extern struct list_head gpio_devices; diff --git a/drivers/gpu/drm/msm/msm_mdss.c b/drivers/gpu/drm/msm/msm_mdss.c index 83b49d489..ce80fc0ff 100644 --- a/drivers/gpu/drm/msm/msm_mdss.c +++ b/drivers/gpu/drm/msm/msm_mdss.c @@ -136,6 +136,7 @@ static struct irq_chip msm_mdss_irq_chip = { .name = "msm_mdss", .irq_mask = msm_mdss_irq_mask, .irq_unmask = msm_mdss_irq_unmask, + .flags = IRQCHIP_PIPELINE_SAFE, }; static struct lock_class_key msm_mdss_lock_key, msm_mdss_request_key; @@ -428,6 +429,7 @@ static struct msm_mdss *msm_mdss_init(struct platform_device *pdev, bool is_mdp5 irq_set_chained_handler_and_data(irq, msm_mdss_irq, msm_mdss); + irq_switch_oob(irq, true); pm_runtime_enable(&pdev->dev); diff --git a/drivers/gpu/ipu-v3/ipu-common.c b/drivers/gpu/ipu-v3/ipu-common.c index 71ec1e7f6..be50b97a2 100644 --- a/drivers/gpu/ipu-v3/ipu-common.c +++ b/drivers/gpu/ipu-v3/ipu-common.c @@ -1236,6 +1236,7 @@ static int ipu_irq_init(struct ipu_soc *ipu) ct->chip.irq_ack = irq_gc_ack_set_bit; ct->chip.irq_mask = irq_gc_mask_clr_bit; ct->chip.irq_unmask = irq_gc_mask_set_bit; + ct->chip.flags = IRQCHIP_PIPELINE_SAFE; ct->regs.ack = IPU_INT_STAT(i / 32); ct->regs.mask = IPU_INT_CTRL(i / 32); } diff --git a/drivers/hv/Kconfig b/drivers/hv/Kconfig index 862c47b19..52b1840d8 100644 --- a/drivers/hv/Kconfig +++ b/drivers/hv/Kconfig @@ -4,8 +4,8 @@ menu "Microsoft Hyper-V guest support" config HYPERV tristate "Microsoft Hyper-V client drivers" - depends on (X86 && X86_LOCAL_APIC && HYPERVISOR_GUEST) \ - || (ACPI && ARM64 && !CPU_BIG_ENDIAN) + depends on ((X86 && X86_LOCAL_APIC && HYPERVISOR_GUEST) \ + || (ACPI && ARM64 && !CPU_BIG_ENDIAN)) && !IRQ_PIPELINE select PARAVIRT select X86_HV_CALLBACK_VECTOR if X86 select OF_EARLY_FLATTREE if OF diff --git a/drivers/iio/industrialio-trigger.c b/drivers/iio/industrialio-trigger.c index b5fed8a00..581bb58a4 100644 --- a/drivers/iio/industrialio-trigger.c +++ b/drivers/iio/industrialio-trigger.c @@ -595,6 +595,7 @@ struct iio_trigger *viio_trigger_alloc(struct device *parent, trig->subirq_chip.name = trig->name; trig->subirq_chip.irq_mask = &iio_trig_subirqmask; trig->subirq_chip.irq_unmask = &iio_trig_subirqunmask; + trig->subirq_chip.flags = IRQCHIP_PIPELINE_SAFE; for (i = 0; i < CONFIG_IIO_CONSUMERS_PER_TRIGGER; i++) { irq_set_chip(trig->subirq_base + i, &trig->subirq_chip); irq_set_handler(trig->subirq_base + i, &handle_simple_irq); diff --git a/drivers/iommu/intel/iommu.h b/drivers/iommu/intel/iommu.h index e6a3e7065..b40047c5c 100644 --- a/drivers/iommu/intel/iommu.h +++ b/drivers/iommu/intel/iommu.h @@ -659,7 +659,7 @@ struct intel_iommu { u64 vccap; u64 ecmdcap[DMA_MAX_NUM_ECMDCAP]; u32 gcmd; /* Holds TE, EAFL. Don't need SRTP, SFL, WBF */ - raw_spinlock_t register_lock; /* protect register handling */ + hard_spinlock_t register_lock; /* protect register handling */ int seq_id; /* sequence id of the iommu */ int agaw; /* agaw of this iommu */ int msagaw; /* max sagaw of this iommu */ diff --git a/drivers/irqchip/exynos-combiner.c b/drivers/irqchip/exynos-combiner.c index 552aa04ff..4ae8e5895 100644 --- a/drivers/irqchip/exynos-combiner.c +++ b/drivers/irqchip/exynos-combiner.c @@ -24,7 +24,7 @@ #define IRQ_IN_COMBINER 8 -static DEFINE_SPINLOCK(irq_controller_lock); +static DEFINE_HARD_SPINLOCK(irq_controller_lock); struct combiner_chip_data { unsigned int hwirq_offset; @@ -72,9 +72,9 @@ static void combiner_handle_cascade_irq(struct irq_desc *desc) chained_irq_enter(chip, desc); - spin_lock(&irq_controller_lock); + raw_spin_lock(&irq_controller_lock); status = readl_relaxed(chip_data->base + COMBINER_INT_STATUS); - spin_unlock(&irq_controller_lock); + raw_spin_unlock(&irq_controller_lock); status &= chip_data->irq_mask; if (status == 0) @@ -111,6 +111,7 @@ static struct irq_chip combiner_chip = { #ifdef CONFIG_SMP .irq_set_affinity = combiner_set_affinity, #endif + .flags = IRQCHIP_PIPELINE_SAFE, }; static void __init combiner_cascade_irq(struct combiner_chip_data *combiner_data, diff --git a/drivers/irqchip/irq-bcm2712-mip.c b/drivers/irqchip/irq-bcm2712-mip.c index 2eaa3ac10..5bc6a52b7 100644 --- a/drivers/irqchip/irq-bcm2712-mip.c +++ b/drivers/irqchip/irq-bcm2712-mip.c @@ -65,6 +65,7 @@ static struct irq_chip mip_msi_irq_chip = { .irq_mask = mip_mask_msi_irq, .irq_eoi = irq_chip_eoi_parent, .irq_set_affinity = irq_chip_set_affinity_parent, + .flags = IRQCHIP_PIPELINE_SAFE, }; static struct msi_domain_info mip_msi_domain_info = { diff --git a/drivers/irqchip/irq-bcm2835.c b/drivers/irqchip/irq-bcm2835.c index 8e995ade7..ace9da0a6 100644 --- a/drivers/irqchip/irq-bcm2835.c +++ b/drivers/irqchip/irq-bcm2835.c @@ -166,6 +166,7 @@ static struct irq_chip armctrl_chip = { .name = "ARMCTRL-level", .irq_mask = armctrl_mask_irq, .irq_unmask = armctrl_unmask_irq, + .flags = IRQCHIP_PIPELINE_SAFE, #ifdef CONFIG_ARM64 .irq_ack = armctrl_ack_irq #endif diff --git a/drivers/irqchip/irq-bcm2836.c b/drivers/irqchip/irq-bcm2836.c index 42660f14a..b2526b821 100644 --- a/drivers/irqchip/irq-bcm2836.c +++ b/drivers/irqchip/irq-bcm2836.c @@ -61,6 +61,7 @@ static struct irq_chip bcm2836_arm_irqchip_timer = { .name = "bcm2836-timer", .irq_mask = bcm2836_arm_irqchip_mask_timer_irq, .irq_unmask = bcm2836_arm_irqchip_unmask_timer_irq, + .flags = IRQCHIP_PIPELINE_SAFE, }; static void bcm2836_arm_irqchip_mask_pmu_irq(struct irq_data *d) @@ -77,6 +78,7 @@ static struct irq_chip bcm2836_arm_irqchip_pmu = { .name = "bcm2836-pmu", .irq_mask = bcm2836_arm_irqchip_mask_pmu_irq, .irq_unmask = bcm2836_arm_irqchip_unmask_pmu_irq, + .flags = IRQCHIP_PIPELINE_SAFE, }; static void bcm2836_arm_irqchip_mask_gpu_irq(struct irq_data *d) @@ -107,11 +109,11 @@ void bcm2836_arm_irqchip_spin_gpu_irq(void) EXPORT_SYMBOL(bcm2836_arm_irqchip_spin_gpu_irq); #endif - static struct irq_chip bcm2836_arm_irqchip_gpu = { .name = "bcm2836-gpu", .irq_mask = bcm2836_arm_irqchip_mask_gpu_irq, .irq_unmask = bcm2836_arm_irqchip_unmask_gpu_irq, + .flags = IRQCHIP_PIPELINE_SAFE, }; static void bcm2836_arm_irqchip_dummy_op(struct irq_data *d) diff --git a/drivers/irqchip/irq-gic-v2m.c b/drivers/irqchip/irq-gic-v2m.c index d83c2c859..223447729 100644 --- a/drivers/irqchip/irq-gic-v2m.c +++ b/drivers/irqchip/irq-gic-v2m.c @@ -89,6 +89,7 @@ static struct irq_chip gicv2m_msi_irq_chip = { .irq_mask = gicv2m_mask_msi_irq, .irq_unmask = gicv2m_unmask_msi_irq, .irq_eoi = irq_chip_eoi_parent, + .flags = IRQCHIP_PIPELINE_SAFE, }; static struct msi_domain_info gicv2m_msi_domain_info = { @@ -130,6 +131,7 @@ static struct irq_chip gicv2m_irq_chip = { .irq_eoi = irq_chip_eoi_parent, .irq_set_affinity = irq_chip_set_affinity_parent, .irq_compose_msi_msg = gicv2m_compose_msi_msg, + .flags = IRQCHIP_PIPELINE_SAFE, }; static int gicv2m_irq_gic_domain_alloc(struct irq_domain *domain, @@ -252,6 +254,7 @@ static bool is_msi_spi_valid(u32 base, u32 num) static struct irq_chip gicv2m_pmsi_irq_chip = { .name = "pMSI", + .flags = IRQCHIP_PIPELINE_SAFE, }; static struct msi_domain_ops gicv2m_pmsi_ops = { diff --git a/drivers/irqchip/irq-gic-v3-its-fsl-mc-msi.c b/drivers/irqchip/irq-gic-v3-its-fsl-mc-msi.c index 8e87fc35f..3bf0d0fee 100644 --- a/drivers/irqchip/irq-gic-v3-its-fsl-mc-msi.c +++ b/drivers/irqchip/irq-gic-v3-its-fsl-mc-msi.c @@ -20,7 +20,8 @@ static struct irq_chip its_msi_irq_chip = { .irq_mask = irq_chip_mask_parent, .irq_unmask = irq_chip_unmask_parent, .irq_eoi = irq_chip_eoi_parent, - .irq_set_affinity = msi_domain_set_affinity + .irq_set_affinity = msi_domain_set_affinity, + .flags = IRQCHIP_PIPELINE_SAFE, }; static u32 fsl_mc_msi_domain_get_msi_id(struct irq_domain *domain, diff --git a/drivers/irqchip/irq-gic-v3-its-pci-msi.c b/drivers/irqchip/irq-gic-v3-its-pci-msi.c index 93f77a819..64b9b9df4 100644 --- a/drivers/irqchip/irq-gic-v3-its-pci-msi.c +++ b/drivers/irqchip/irq-gic-v3-its-pci-msi.c @@ -28,6 +28,7 @@ static struct irq_chip its_msi_irq_chip = { .irq_unmask = its_unmask_msi_irq, .irq_mask = its_mask_msi_irq, .irq_eoi = irq_chip_eoi_parent, + .flags = IRQCHIP_PIPELINE_SAFE, }; static int its_pci_msi_vec_count(struct pci_dev *pdev, void *data) diff --git a/drivers/irqchip/irq-gic-v3-its-platform-msi.c b/drivers/irqchip/irq-gic-v3-its-platform-msi.c index daa6d5053..ae29443e9 100644 --- a/drivers/irqchip/irq-gic-v3-its-platform-msi.c +++ b/drivers/irqchip/irq-gic-v3-its-platform-msi.c @@ -12,6 +12,7 @@ static struct irq_chip its_pmsi_irq_chip = { .name = "ITS-pMSI", + .flags = IRQCHIP_PIPELINE_SAFE, }; static int of_pmsi_get_dev_id(struct irq_domain *domain, struct device *dev, diff --git a/drivers/irqchip/irq-gic-v3-mbi.c b/drivers/irqchip/irq-gic-v3-mbi.c index dbb8b1efd..881162dfd 100644 --- a/drivers/irqchip/irq-gic-v3-mbi.c +++ b/drivers/irqchip/irq-gic-v3-mbi.c @@ -215,7 +215,7 @@ static struct irq_chip mbi_pmsi_irq_chip = { .name = "pMSI", .irq_set_type = irq_chip_set_type_parent, .irq_compose_msi_msg = mbi_compose_mbi_msg, - .flags = IRQCHIP_SUPPORTS_LEVEL_MSI, + .flags = IRQCHIP_SUPPORTS_LEVEL_MSI | IRQCHIP_PIPELINE_SAFE, }; static struct msi_domain_ops mbi_pmsi_ops = { diff --git a/drivers/irqchip/irq-gic-v3.c b/drivers/irqchip/irq-gic-v3.c index 6c7943c51..410e92ada 100644 --- a/drivers/irqchip/irq-gic-v3.c +++ b/drivers/irqchip/irq-gic-v3.c @@ -1499,7 +1499,8 @@ static struct irq_chip gic_chip = { .ipi_send_mask = gic_ipi_send_mask, .flags = IRQCHIP_SET_TYPE_MASKED | IRQCHIP_SKIP_SET_WAKE | - IRQCHIP_MASK_ON_SUSPEND, + IRQCHIP_MASK_ON_SUSPEND | + IRQCHIP_PIPELINE_SAFE, }; static struct irq_chip gic_eoimode1_chip = { @@ -1518,7 +1519,8 @@ static struct irq_chip gic_eoimode1_chip = { .ipi_send_mask = gic_ipi_send_mask, .flags = IRQCHIP_SET_TYPE_MASKED | IRQCHIP_SKIP_SET_WAKE | - IRQCHIP_MASK_ON_SUSPEND, + IRQCHIP_MASK_ON_SUSPEND | + IRQCHIP_PIPELINE_SAFE, }; static int gic_irq_domain_map(struct irq_domain *d, unsigned int irq, diff --git a/drivers/irqchip/irq-gic.c b/drivers/irqchip/irq-gic.c index 2c6c50348..0e3a8951b 100644 --- a/drivers/irqchip/irq-gic.c +++ b/drivers/irqchip/irq-gic.c @@ -88,7 +88,7 @@ struct gic_chip_data { #ifdef CONFIG_BL_SWITCHER -static DEFINE_RAW_SPINLOCK(cpu_map_lock); +static DEFINE_HARD_SPINLOCK(cpu_map_lock); #define gic_lock_irqsave(f) \ raw_spin_lock_irqsave(&cpu_map_lock, (f)) @@ -893,7 +893,8 @@ static const struct irq_chip gic_chip = { .irq_print_chip = gic_irq_print_chip, .flags = IRQCHIP_SET_TYPE_MASKED | IRQCHIP_SKIP_SET_WAKE | - IRQCHIP_MASK_ON_SUSPEND, + IRQCHIP_MASK_ON_SUSPEND | + IRQCHIP_PIPELINE_SAFE, }; static const struct irq_chip gic_chip_mode1 = { @@ -910,7 +911,8 @@ static const struct irq_chip gic_chip_mode1 = { .irq_set_vcpu_affinity = gic_irq_set_vcpu_affinity, .flags = IRQCHIP_SET_TYPE_MASKED | IRQCHIP_SKIP_SET_WAKE | - IRQCHIP_MASK_ON_SUSPEND, + IRQCHIP_MASK_ON_SUSPEND | + IRQCHIP_PIPELINE_SAFE, }; #ifdef CONFIG_BL_SWITCHER diff --git a/drivers/irqchip/irq-imx-irqsteer.c b/drivers/irqchip/irq-imx-irqsteer.c index 7df53b453..0d9180a4a 100644 --- a/drivers/irqchip/irq-imx-irqsteer.c +++ b/drivers/irqchip/irq-imx-irqsteer.c @@ -31,7 +31,7 @@ struct irqsteer_data { struct clk *ipg_clk; int irq[CHAN_MAX_OUTPUT_INT]; int irq_count; - raw_spinlock_t lock; + hard_spinlock_t lock; int reg_num; int channel; struct irq_domain *domain; @@ -93,6 +93,7 @@ static const struct irq_chip imx_irqsteer_irq_chip = { .irq_unmask = imx_irqsteer_irq_unmask, .irq_bus_lock = imx_irqsteer_irq_bus_lock, .irq_bus_sync_unlock = imx_irqsteer_irq_bus_sync_unlock, + .flags = IRQCHIP_PIPELINE_SAFE, }; static int imx_irqsteer_irq_map(struct irq_domain *h, unsigned int irq, diff --git a/drivers/irqchip/irq-omap-intc.c b/drivers/irqchip/irq-omap-intc.c index dc82162ba..50ddc703f 100644 --- a/drivers/irqchip/irq-omap-intc.c +++ b/drivers/irqchip/irq-omap-intc.c @@ -211,7 +211,7 @@ static int __init omap_alloc_gc_of(struct irq_domain *d, void __iomem *base) ct->chip.irq_mask = irq_gc_mask_disable_reg; ct->chip.irq_unmask = irq_gc_unmask_enable_reg; - ct->chip.flags |= IRQCHIP_SKIP_SET_WAKE; + ct->chip.flags |= IRQCHIP_SKIP_SET_WAKE | IRQCHIP_PIPELINE_SAFE; ct->regs.enable = INTC_MIR_CLEAR0 + 32 * i; ct->regs.disable = INTC_MIR_SET0 + 32 * i; diff --git a/drivers/irqchip/irq-sun4i.c b/drivers/irqchip/irq-sun4i.c index dd506ebfd..f268c8bc2 100644 --- a/drivers/irqchip/irq-sun4i.c +++ b/drivers/irqchip/irq-sun4i.c @@ -87,7 +87,7 @@ static struct irq_chip sun4i_irq_chip = { .irq_eoi = sun4i_irq_ack, .irq_mask = sun4i_irq_mask, .irq_unmask = sun4i_irq_unmask, - .flags = IRQCHIP_EOI_THREADED | IRQCHIP_EOI_IF_HANDLED, + .flags = IRQCHIP_EOI_THREADED | IRQCHIP_EOI_IF_HANDLED | IRQCHIP_PIPELINE_SAFE, }; static int sun4i_irq_map(struct irq_domain *d, unsigned int virq, diff --git a/drivers/irqchip/irq-sunxi-nmi.c b/drivers/irqchip/irq-sunxi-nmi.c index e760b1278..324cd0967 100644 --- a/drivers/irqchip/irq-sunxi-nmi.c +++ b/drivers/irqchip/irq-sunxi-nmi.c @@ -186,7 +186,9 @@ static int __init sunxi_sc_nmi_irq_init(struct device_node *node, gc->chip_types[0].chip.irq_unmask = irq_gc_mask_set_bit; gc->chip_types[0].chip.irq_eoi = irq_gc_ack_set_bit; gc->chip_types[0].chip.irq_set_type = sunxi_sc_nmi_set_type; - gc->chip_types[0].chip.flags = IRQCHIP_EOI_THREADED | IRQCHIP_EOI_IF_HANDLED; + gc->chip_types[0].chip.flags = IRQCHIP_EOI_THREADED | + IRQCHIP_EOI_IF_HANDLED | + IRQCHIP_PIPELINE_SAFE; gc->chip_types[0].regs.ack = reg_offs->pend; gc->chip_types[0].regs.mask = reg_offs->enable; gc->chip_types[0].regs.type = reg_offs->ctrl; diff --git a/drivers/irqchip/irq-ti-sci-inta.c b/drivers/irqchip/irq-ti-sci-inta.c index b83f5cbab..24d3ff905 100644 --- a/drivers/irqchip/irq-ti-sci-inta.c +++ b/drivers/irqchip/irq-ti-sci-inta.c @@ -259,6 +259,7 @@ static struct ti_sci_inta_vint_desc *ti_sci_inta_alloc_parent_irq(struct irq_dom list_add_tail(&vint_desc->list, &inta->vint_list); irq_set_chained_handler_and_data(vint_desc->parent_virq, ti_sci_inta_irq_handler, vint_desc); + irq_switch_oob(vint_desc->parent_virq, true); return vint_desc; free_vint_desc: @@ -540,6 +541,7 @@ static struct irq_chip ti_sci_inta_irq_chip = { .irq_set_affinity = ti_sci_inta_set_affinity, .irq_request_resources = ti_sci_inta_request_resources, .irq_release_resources = ti_sci_inta_release_resources, + .flags = IRQCHIP_PIPELINE_SAFE, }; /** diff --git a/drivers/memory/omap-gpmc.c b/drivers/memory/omap-gpmc.c index d78f73db3..fbeaab399 100644 --- a/drivers/memory/omap-gpmc.c +++ b/drivers/memory/omap-gpmc.c @@ -1475,6 +1475,7 @@ static int gpmc_setup_irq(struct gpmc_device *gpmc) gpmc->irq_chip.irq_mask = gpmc_irq_mask; gpmc->irq_chip.irq_unmask = gpmc_irq_unmask; gpmc->irq_chip.irq_set_type = gpmc_irq_set_type; + gpmc->irq_chip.flags = IRQCHIP_PIPELINE_SAFE; gpmc_irq_domain = irq_domain_add_linear(gpmc->dev->of_node, gpmc->nirqs, @@ -1485,7 +1486,7 @@ static int gpmc_setup_irq(struct gpmc_device *gpmc) return -ENODEV; } - rc = request_irq(gpmc->irq, gpmc_handle_irq, 0, "gpmc", gpmc); + rc = request_irq(gpmc->irq, gpmc_handle_irq, IRQF_OOB, "gpmc", gpmc); if (rc) { dev_err(gpmc->dev, "failed to request irq %d: %d\n", gpmc->irq, rc); diff --git a/drivers/mfd/rp1.c b/drivers/mfd/rp1.c index 0a498a670..41aa28be8 100644 --- a/drivers/mfd/rp1.c +++ b/drivers/mfd/rp1.c @@ -155,6 +155,7 @@ static struct irq_chip rp1_irq_chip = { .irq_unmask = rp1_unmask_irq, .irq_set_type = rp1_irq_set_type, .irq_set_affinity = rp1_irq_set_affinity, + .flags = IRQCHIP_PIPELINE_SAFE, }; static void rp1_chained_handle_irq(struct irq_desc *desc) diff --git a/drivers/mfd/tps65217.c b/drivers/mfd/tps65217.c index 029ecc32f..60db576ce 100644 --- a/drivers/mfd/tps65217.c +++ b/drivers/mfd/tps65217.c @@ -75,6 +75,7 @@ static struct irq_chip tps65217_irq_chip = { .irq_bus_sync_unlock = tps65217_irq_sync_unlock, .irq_enable = tps65217_irq_enable, .irq_disable = tps65217_irq_disable, + .flags = IRQCHIP_PIPELINE_SAFE, }; static struct mfd_cell tps65217s[] = { diff --git a/drivers/net/ethernet/freescale/Kconfig b/drivers/net/ethernet/freescale/Kconfig index 75401d2a5..8b6285133 100644 --- a/drivers/net/ethernet/freescale/Kconfig +++ b/drivers/net/ethernet/freescale/Kconfig @@ -35,6 +35,15 @@ config FEC Say Y here if you want to use the built-in 10/100 Fast ethernet controller on some Motorola ColdFire and Freescale i.MX/S32 processors. +config FEC_OOB + bool "Out-of-band support for FEC" + depends on NET_OOB + help + Enable out-of-band I/O. Say Y if a companion kernel may divert + the network traffic going through FEC devices for real-time delivery. + Enabling this option makes sense only in a dual kernel configuration. + If unsure, disable it. + config FEC_MPC52xx tristate "FEC MPC52xx driver" depends on PPC_MPC52xx && PPC_BESTCOMM diff --git a/drivers/net/ethernet/freescale/fec.h b/drivers/net/ethernet/freescale/fec.h index 733af928c..6b796fa3f 100644 --- a/drivers/net/ethernet/freescale/fec.h +++ b/drivers/net/ethernet/freescale/fec.h @@ -701,6 +701,126 @@ struct fec_enet_private { u64 ethtool_stats[]; }; +/* + * Check whether oob support is compiled in for the FEC driver. This + * tells nothing about the current execution stage, or whether oob + * diversion is ongoing for any FEC device. + */ +static inline bool fec_net_oob(void) +{ + return IS_ENABLED(CONFIG_FEC_OOB); +} + +/* + * Check whether the caller is running on the out-of-band stage, with + * the precondition that oob support is compiled in for the FEC driver. + */ +static inline bool fec_running_oob(void) +{ + return fec_net_oob() && running_oob(); +} + +/* + * Check whether a FEC device is currently diverting packet to the + * out-of-band netstack. The compiler is given the opportunity to + * compile the whole thing out if either NET_OOB or FEC_OOB which + * depends on it are disabled. + */ +static inline bool fec_oob_enabled(struct fec_enet_private *fep) +{ + return IS_ENABLED(CONFIG_FEC_OOB) && netif_oob_diversion(fep->netdev); +} + +/* + * Check whether oob support is compiled in for the FEC driver. This + * tells nothing about the current execution stage, or whether oob + * diversion is ongoing for any FEC device. + */ +static inline bool fec_net_oob(void) +{ + return IS_ENABLED(CONFIG_FEC_OOB); +} + +/* + * Check whether the caller is running on the out-of-band stage, with + * the precondition that oob support is compiled in for the FEC driver. + */ +static inline bool fec_running_oob(void) +{ + return fec_net_oob() && running_oob(); +} + +/* + * Check whether a FEC device is currently diverting packet to the + * out-of-band netstack. The compiler is given the opportunity to + * compile the whole thing out if either NET_OOB or FEC_OOB which + * depends on it are disabled. + */ +static inline bool fec_oob_enabled(struct fec_enet_private *fep) +{ + return IS_ENABLED(CONFIG_FEC_OOB) && netif_oob_diversion(fep->netdev); +} + +/* + * Check whether oob support is compiled in for the FEC driver. This + * tells nothing about the current execution stage, or whether oob + * diversion is ongoing for any FEC device. + */ +static inline bool fec_net_oob(void) +{ + return IS_ENABLED(CONFIG_FEC_OOB); +} + +/* + * Check whether the caller is running on the out-of-band stage, with + * the precondition that oob support is compiled in for the FEC driver. + */ +static inline bool fec_running_oob(void) +{ + return fec_net_oob() && running_oob(); +} + +/* + * Check whether a FEC device is currently diverting packet to the + * out-of-band netstack. The compiler is given the opportunity to + * compile the whole thing out if either NET_OOB or FEC_OOB which + * depends on it are disabled. + */ +static inline bool fec_oob_enabled(struct fec_enet_private *fep) +{ + return IS_ENABLED(CONFIG_FEC_OOB) && netif_oob_diversion(fep->netdev); +} + +/* + * Check whether oob support is compiled in for the FEC driver. This + * tells nothing about the current execution stage, or whether oob + * diversion is ongoing for any FEC device. + */ +static inline bool fec_net_oob(void) +{ + return IS_ENABLED(CONFIG_FEC_OOB); +} + +/* + * Check whether the caller is running on the out-of-band stage, with + * the precondition that oob support is compiled in for the FEC driver. + */ +static inline bool fec_running_oob(void) +{ + return fec_net_oob() && running_oob(); +} + +/* + * Check whether a FEC device is currently diverting packet to the + * out-of-band netstack. The compiler is given the opportunity to + * compile the whole thing out if either NET_OOB or FEC_OOB which + * depends on it are disabled. + */ +static inline bool fec_oob_enabled(struct fec_enet_private *fep) +{ + return IS_ENABLED(CONFIG_FEC_OOB) && netif_oob_diversion(fep->netdev); +} + void fec_ptp_init(struct platform_device *pdev, int irq_idx); void fec_ptp_restore_state(struct fec_enet_private *fep); void fec_ptp_save_state(struct fec_enet_private *fep); diff --git a/drivers/net/ethernet/freescale/fec_main.c b/drivers/net/ethernet/freescale/fec_main.c index 8f5cc1f23..7af0e9477 100644 --- a/drivers/net/ethernet/freescale/fec_main.c +++ b/drivers/net/ethernet/freescale/fec_main.c @@ -355,6 +355,50 @@ MODULE_PARM_DESC(macaddr, "FEC Ethernet MAC address"); static int mii_cnt; +#ifdef CONFIG_FEC_OOB + +static int fec_enet_get_irq_cnt(struct platform_device *pdev); + +static int fec_enable_oob(struct net_device *ndev) +{ + struct fec_enet_private *fep = netdev_priv(ndev); + int nr_irqs = fec_enet_get_irq_cnt(fep->pdev), n, ret = 0; + + napi_disable(&fep->napi); + netif_tx_lock_bh(ndev); + + for (n = 0; n < nr_irqs; n++) { + ret = irq_switch_oob(fep->irq[n], true); + if (ret) { + while (--n > 0) + irq_switch_oob(fep->irq[n], false); + break; + } + } + + netif_tx_unlock_bh(ndev); + napi_enable(&fep->napi); + + return ret; +} + +static void fec_disable_oob(struct net_device *ndev) +{ + struct fec_enet_private *fep = netdev_priv(ndev); + int nr_irqs = fec_enet_get_irq_cnt(fep->pdev), n; + + napi_disable(&fep->napi); + netif_tx_lock_bh(ndev); + + for (n = 0; n < nr_irqs; n++) + irq_switch_oob(fep->irq[n], false); + + netif_tx_unlock_bh(ndev); + napi_enable(&fep->napi); +} + +#endif /* !CONFIG_FEC_OOB */ + static struct bufdesc *fec_enet_get_nextdesc(struct bufdesc *bdp, struct bufdesc_prop *bd) { @@ -460,6 +504,12 @@ fec_enet_create_page_pool(struct fec_enet_private *fep, }; int err; + if (fec_net_oob()) { + pp_params.flags |= PP_FLAG_PAGE_OOB; + /* An oob pool can't grow, so plan for extra space. */ + pp_params.pool_size *= 2; + } + rxq->page_pool = page_pool_create(&pp_params); if (IS_ERR(rxq->page_pool)) { err = PTR_ERR(rxq->page_pool); @@ -486,6 +536,43 @@ fec_enet_create_page_pool(struct fec_enet_private *fep, return err; } +static dma_addr_t get_dma_mapping(struct sk_buff *skb, + struct device *dev, void *ptr, + size_t size, enum dma_data_direction dir) +{ + dma_addr_t addr; + + if (!fec_net_oob() || !skb_has_oob_storage(skb)) + return dma_map_single(dev, ptr, size, dir); + + /* + * An oob-managed storage is already mapped by the page pool + * it belongs to. We only need to to let the device get at the + * pre-mapped DMA area for the specified I/O direction. + */ + addr = skb_oob_storage_addr(skb); + dma_sync_single_for_device(dev, addr, size, dir); + + return addr; +} + +static void release_dma_mapping(struct sk_buff *skb, + struct device *dev, dma_addr_t addr, size_t size, + enum dma_data_direction dir) +{ + if (!fec_net_oob() || !skb || !skb_has_oob_storage(skb)) { + dma_unmap_single(dev, addr, size, dir); + } else { + /* + * An oob-managed storage should not be unmapped, this + * operation is handled when required by the page pool + * it belongs to. We only need to synchronize the CPU + * caches for the specified I/O direction. + */ + dma_sync_single_for_cpu(dev, addr, size, dir); + } +} + static struct bufdesc * fec_enet_txq_submit_frag_skb(struct fec_enet_priv_tx_q *txq, struct sk_buff *skb, @@ -547,8 +634,8 @@ fec_enet_txq_submit_frag_skb(struct fec_enet_priv_tx_q *txq, swap_buffer(bufaddr, frag_len); } - addr = dma_map_single(&fep->pdev->dev, bufaddr, frag_len, - DMA_TO_DEVICE); + addr = get_dma_mapping(skb, &fep->pdev->dev, bufaddr, frag_len, + DMA_TO_DEVICE); if (dma_mapping_error(&fep->pdev->dev, addr)) { if (net_ratelimit()) netdev_err(ndev, "Tx DMA memory map failed\n"); @@ -569,8 +656,8 @@ fec_enet_txq_submit_frag_skb(struct fec_enet_priv_tx_q *txq, bdp = txq->bd.cur; for (i = 0; i < frag; i++) { bdp = fec_enet_get_nextdesc(bdp, &txq->bd); - dma_unmap_single(&fep->pdev->dev, fec32_to_cpu(bdp->cbd_bufaddr), - fec16_to_cpu(bdp->cbd_datlen), DMA_TO_DEVICE); + release_dma_mapping(NULL, &fep->pdev->dev, fec32_to_cpu(bdp->cbd_bufaddr), + fec16_to_cpu(bdp->cbd_datlen), DMA_TO_DEVICE); } return ERR_PTR(-ENOMEM); } @@ -624,7 +711,7 @@ static int fec_enet_txq_submit_skb(struct fec_enet_priv_tx_q *txq, } /* Push the data cache so the CPM does not get stale memory data. */ - addr = dma_map_single(&fep->pdev->dev, bufaddr, buflen, DMA_TO_DEVICE); + addr = get_dma_mapping(skb, &fep->pdev->dev, bufaddr, buflen, DMA_TO_DEVICE); if (dma_mapping_error(&fep->pdev->dev, addr)) { dev_kfree_skb_any(skb); if (net_ratelimit()) @@ -635,8 +722,8 @@ static int fec_enet_txq_submit_skb(struct fec_enet_priv_tx_q *txq, if (nr_frags) { last_bdp = fec_enet_txq_submit_frag_skb(txq, skb, ndev); if (IS_ERR(last_bdp)) { - dma_unmap_single(&fep->pdev->dev, addr, - buflen, DMA_TO_DEVICE); + release_dma_mapping(skb, &fep->pdev->dev, addr, + buflen, DMA_TO_DEVICE); dev_kfree_skb_any(skb); return NETDEV_TX_OK; } @@ -726,7 +813,7 @@ fec_enet_txq_put_data_tso(struct fec_enet_priv_tx_q *txq, struct sk_buff *skb, swap_buffer(data, size); } - addr = dma_map_single(&fep->pdev->dev, data, size, DMA_TO_DEVICE); + addr = get_dma_mapping(skb, &fep->pdev->dev, data, size, DMA_TO_DEVICE); if (dma_mapping_error(&fep->pdev->dev, addr)) { dev_kfree_skb_any(skb); if (net_ratelimit()) @@ -787,7 +874,7 @@ fec_enet_txq_put_hdr_tso(struct fec_enet_priv_tx_q *txq, if (fep->quirks & FEC_QUIRK_SWAP_FRAME) swap_buffer(bufaddr, hdr_len); - dmabuf = dma_map_single(&fep->pdev->dev, bufaddr, + dmabuf = get_dma_mapping(skb, &fep->pdev->dev, bufaddr, hdr_len, DMA_TO_DEVICE); if (dma_mapping_error(&fep->pdev->dev, dmabuf)) { dev_kfree_skb_any(skb); @@ -906,12 +993,23 @@ fec_enet_start_xmit(struct sk_buff *skb, struct net_device *ndev) unsigned short queue; struct fec_enet_priv_tx_q *txq; struct netdev_queue *nq; - int ret; + int ret = 0; queue = skb_get_queue_mapping(skb); txq = fep->tx_queue[queue]; nq = netdev_get_tx_queue(ndev, queue); + /* + * Lock out any sender running from the alternate execution + * stage from other CPUs (i.e. oob vs in-band). Clearly, + * in-band tasks should refrain from sending output through an + * oob-enabled device when aiming at the lowest possible + * latency for the oob players, but we still allow shared use + * for flexibility though, which comes in handy when a single + * NIC only is available to convey both kinds of traffic. + */ + netif_tx_lock_oob(nq); + if (skb_is_gso(skb)) ret = fec_enet_txq_submit_tso(txq, skb, ndev); else @@ -919,9 +1017,13 @@ fec_enet_start_xmit(struct sk_buff *skb, struct net_device *ndev) if (ret) return ret; - entries_free = fec_enet_get_free_txdesc_num(txq); - if (entries_free <= txq->tx_stop_threshold) - netif_tx_stop_queue(nq); + if (running_inband()) { + entries_free = fec_enet_get_free_txdesc_num(txq); + if (entries_free <= txq->tx_stop_threshold) + netif_tx_stop_queue(nq); + } + + netif_tx_unlock_oob(nq); return NETDEV_TX_OK; } @@ -971,7 +1073,8 @@ static void fec_enet_bd_init(struct net_device *dev) if (txq->tx_buf[i].type == FEC_TXBUF_T_SKB) { if (bdp->cbd_bufaddr && !IS_TSO_HEADER(txq, fec32_to_cpu(bdp->cbd_bufaddr))) - dma_unmap_single(&fep->pdev->dev, + release_dma_mapping(txq->tx_buf[i].buf_p, + &fep->pdev->dev, fec32_to_cpu(bdp->cbd_bufaddr), fec16_to_cpu(bdp->cbd_datlen), DMA_TO_DEVICE); @@ -979,7 +1082,8 @@ static void fec_enet_bd_init(struct net_device *dev) dev_kfree_skb_any(txq->tx_buf[i].buf_p); } else if (txq->tx_buf[i].type == FEC_TXBUF_T_XDP_NDO) { if (bdp->cbd_bufaddr) - dma_unmap_single(&fep->pdev->dev, + release_dma_mapping(txq->tx_buf[i].buf_p, + &fep->pdev->dev, fec32_to_cpu(bdp->cbd_bufaddr), fec16_to_cpu(bdp->cbd_datlen), DMA_TO_DEVICE); @@ -1439,12 +1543,13 @@ fec_enet_tx_queue(struct net_device *ndev, u16 queue_id, int budget) break; index = fec_enet_get_bd_index(bdp, &txq->bd); + skb = txq->tx_buf[index].buf_p; if (txq->tx_buf[index].type == FEC_TXBUF_T_SKB) { - skb = txq->tx_buf[index].buf_p; if (bdp->cbd_bufaddr && !IS_TSO_HEADER(txq, fec32_to_cpu(bdp->cbd_bufaddr))) - dma_unmap_single(&fep->pdev->dev, + release_dma_mapping(skb, + &fep->pdev->dev, fec32_to_cpu(bdp->cbd_bufaddr), fec16_to_cpu(bdp->cbd_datlen), DMA_TO_DEVICE); @@ -1463,7 +1568,8 @@ fec_enet_tx_queue(struct net_device *ndev, u16 queue_id, int budget) if (txq->tx_buf[index].type == FEC_TXBUF_T_XDP_NDO) { xdpf = txq->tx_buf[index].buf_p; if (bdp->cbd_bufaddr) - dma_unmap_single(&fep->pdev->dev, + release_dma_mapping(skb, + &fep->pdev->dev, fec32_to_cpu(bdp->cbd_bufaddr), fec16_to_cpu(bdp->cbd_datlen), DMA_TO_DEVICE); @@ -4003,6 +4109,10 @@ static const struct net_device_ops fec_netdev_ops = { .ndo_tx_timeout = fec_timeout, .ndo_set_mac_address = fec_set_mac_address, .ndo_eth_ioctl = phy_do_ioctl_running, +#ifdef CONFIG_FEC_OOB + .ndo_enable_oob = fec_enable_oob, + .ndo_disable_oob = fec_disable_oob, +#endif .ndo_set_features = fec_set_features, .ndo_bpf = fec_enet_bpf, .ndo_xdp_xmit = fec_enet_xdp_xmit, @@ -4548,6 +4658,11 @@ fec_probe(struct platform_device *pdev) INIT_WORK(&fep->tx_timeout_work, fec_enet_timeout_work); + if (IS_ENABLED(CONFIG_FEC_OOB)) { + ndev->priv_flags |= IFF_OOB_CAPABLE; + netdev_info(ndev, "FEC device is oob-capable\n"); + } + pm_runtime_mark_last_busy(&pdev->dev); pm_runtime_put_autosuspend(&pdev->dev); diff --git a/drivers/pci/controller/dwc/pcie-designware-host.c b/drivers/pci/controller/dwc/pcie-designware-host.c index a7170fd0e..ebcf1563f 100644 --- a/drivers/pci/controller/dwc/pcie-designware-host.c +++ b/drivers/pci/controller/dwc/pcie-designware-host.c @@ -45,6 +45,7 @@ static struct irq_chip dw_pcie_msi_irq_chip = { .irq_ack = dw_msi_ack_irq, .irq_mask = dw_msi_mask_irq, .irq_unmask = dw_msi_unmask_irq, + .flags = IRQCHIP_PIPELINE_SAFE, }; static struct msi_domain_info dw_pcie_msi_domain_info = { diff --git a/drivers/pci/controller/pcie-brcmstb.c b/drivers/pci/controller/pcie-brcmstb.c index 457a8d29f..463404ab2 100644 --- a/drivers/pci/controller/pcie-brcmstb.c +++ b/drivers/pci/controller/pcie-brcmstb.c @@ -663,6 +663,7 @@ static struct irq_chip brcm_msi_irq_chip = { .irq_ack = irq_chip_ack_parent, .irq_mask = pci_msi_mask_irq, .irq_unmask = pci_msi_unmask_irq, + .flags = IRQCHIP_PIPELINE_SAFE, }; static struct msi_domain_info brcm_msi_domain_info = { @@ -737,6 +738,7 @@ static struct irq_chip brcm_msi_bottom_irq_chip = { .irq_compose_msi_msg = brcm_msi_compose_msi_msg, .irq_set_affinity = brcm_msi_set_affinity, .irq_ack = brcm_msi_ack_irq, + .flags = IRQCHIP_PIPELINE_SAFE, }; static int brcm_msi_alloc(struct brcm_msi *msi, unsigned int nr_irqs) diff --git a/drivers/pinctrl/bcm/pinctrl-bcm2835.c b/drivers/pinctrl/bcm/pinctrl-bcm2835.c index cfb51cf2f..24e79c3e5 100644 --- a/drivers/pinctrl/bcm/pinctrl-bcm2835.c +++ b/drivers/pinctrl/bcm/pinctrl-bcm2835.c @@ -89,7 +89,7 @@ struct bcm2835_pinctrl { struct pinctrl_desc pctl_desc; struct pinctrl_gpio_range gpio_range; - raw_spinlock_t irq_lock[BCM2835_NUM_BANKS]; + hard_spinlock_t irq_lock[BCM2835_NUM_BANKS]; /* Protect FSEL registers */ spinlock_t fsel_lock; }; @@ -727,7 +727,7 @@ static const struct irq_chip bcm2835_gpio_irq_chip = { .irq_mask = bcm2835_gpio_irq_mask, .irq_unmask = bcm2835_gpio_irq_unmask, .irq_set_wake = bcm2835_gpio_irq_set_wake, - .flags = (IRQCHIP_MASK_ON_SUSPEND | IRQCHIP_IMMUTABLE), + .flags = (IRQCHIP_MASK_ON_SUSPEND | IRQCHIP_IMMUTABLE | IRQCHIP_PIPELINE_SAFE), GPIOCHIP_IRQ_RESOURCE_HELPERS, }; diff --git a/drivers/pinctrl/intel/pinctrl-cherryview.c b/drivers/pinctrl/intel/pinctrl-cherryview.c index 81ee949b9..f59092486 100644 --- a/drivers/pinctrl/intel/pinctrl-cherryview.c +++ b/drivers/pinctrl/intel/pinctrl-cherryview.c @@ -566,7 +566,7 @@ static const struct intel_pinctrl_soc_data *chv_soc_data[] = { * See Intel Atom Z8000 Processor Series Specification Update (Rev. 005), * errata #CHT34, for further information. */ -static DEFINE_RAW_SPINLOCK(chv_lock); +static DEFINE_HARD_SPINLOCK(chv_lock); static u32 chv_pctrl_readl(struct intel_pinctrl *pctrl, unsigned int offset) { @@ -1417,7 +1417,7 @@ static const struct irq_chip chv_gpio_irq_chip = { .irq_mask = chv_gpio_irq_mask, .irq_unmask = chv_gpio_irq_unmask, .irq_set_type = chv_gpio_irq_type, - .flags = IRQCHIP_SKIP_SET_WAKE | IRQCHIP_IMMUTABLE, + .flags = IRQCHIP_SKIP_SET_WAKE | IRQCHIP_IMMUTABLE | IRQCHIP_PIPELINE_SAFE, GPIOCHIP_IRQ_RESOURCE_HELPERS, }; diff --git a/drivers/pinctrl/qcom/pinctrl-msm.c b/drivers/pinctrl/qcom/pinctrl-msm.c index 115b83e2d..718d80982 100644 --- a/drivers/pinctrl/qcom/pinctrl-msm.c +++ b/drivers/pinctrl/qcom/pinctrl-msm.c @@ -69,7 +69,7 @@ struct msm_pinctrl { bool intr_target_use_scm; - raw_spinlock_t lock; + hard_spinlock_t lock; DECLARE_BITMAP(dual_edge_irqs, MAX_NR_GPIO); DECLARE_BITMAP(enabled_irqs, MAX_NR_GPIO); @@ -1339,7 +1339,8 @@ static const struct irq_chip msm_gpio_irq_chip = { .flags = (IRQCHIP_MASK_ON_SUSPEND | IRQCHIP_SET_TYPE_MASKED | IRQCHIP_ENABLE_WAKEUP_ON_SUSPEND | - IRQCHIP_IMMUTABLE), + IRQCHIP_IMMUTABLE | + IRQCHIP_PIPELINE_SAFE), }; static int msm_gpio_init(struct msm_pinctrl *pctrl) diff --git a/drivers/pinctrl/samsung/pinctrl-exynos.c b/drivers/pinctrl/samsung/pinctrl-exynos.c index a8212fc12..a080c14d1 100644 --- a/drivers/pinctrl/samsung/pinctrl-exynos.c +++ b/drivers/pinctrl/samsung/pinctrl-exynos.c @@ -214,6 +214,7 @@ static const struct exynos_irq_chip exynos_gpio_irq_chip __initconst = { .irq_set_type = exynos_irq_set_type, .irq_request_resources = exynos_irq_request_resources, .irq_release_resources = exynos_irq_release_resources, + .flags = IRQCHIP_PIPELINE_SAFE, }, .eint_con = EXYNOS_GPIO_ECON_OFFSET, .eint_mask = EXYNOS_GPIO_EMASK_OFFSET, @@ -286,7 +287,7 @@ __init int exynos_eint_gpio_init(struct samsung_pinctrl_drv_data *d) } ret = devm_request_irq(dev, d->irq, exynos_eint_gpio_irq, - 0, dev_name(dev), d); + IRQF_OOB, dev_name(dev), d); if (ret) { dev_err(dev, "irq request failed\n"); return -ENXIO; @@ -304,6 +305,7 @@ __init int exynos_eint_gpio_init(struct samsung_pinctrl_drv_data *d) goto err_domains; } bank->irq_chip->chip.name = bank->name; + bank->irq_chip->chip.flags |= IRQCHIP_PIPELINE_SAFE; bank->irq_domain = irq_domain_create_linear(bank->fwnode, bank->nr_pins, &exynos_eint_irqd_ops, bank); @@ -408,6 +410,7 @@ static const struct exynos_irq_chip s5pv210_wkup_irq_chip __initconst = { .irq_set_wake = exynos_wkup_irq_set_wake, .irq_request_resources = exynos_irq_request_resources, .irq_release_resources = exynos_irq_release_resources, + .flags = IRQCHIP_PIPELINE_SAFE, }, .eint_con = EXYNOS_WKUP_ECON_OFFSET, .eint_mask = EXYNOS_WKUP_EMASK_OFFSET, @@ -428,6 +431,7 @@ static const struct exynos_irq_chip exynos4210_wkup_irq_chip __initconst = { .irq_set_wake = exynos_wkup_irq_set_wake, .irq_request_resources = exynos_irq_request_resources, .irq_release_resources = exynos_irq_release_resources, + .flags = IRQCHIP_PIPELINE_SAFE, }, .eint_con = EXYNOS_WKUP_ECON_OFFSET, .eint_mask = EXYNOS_WKUP_EMASK_OFFSET, @@ -447,6 +451,7 @@ static const struct exynos_irq_chip exynos7_wkup_irq_chip __initconst = { .irq_set_wake = exynos_wkup_irq_set_wake, .irq_request_resources = exynos_irq_request_resources, .irq_release_resources = exynos_irq_release_resources, + .flags = IRQCHIP_PIPELINE_SAFE, }, .eint_con = EXYNOS7_WKUP_ECON_OFFSET, .eint_mask = EXYNOS7_WKUP_EMASK_OFFSET, diff --git a/drivers/pinctrl/samsung/pinctrl-samsung.h b/drivers/pinctrl/samsung/pinctrl-samsung.h index 9af93e3d8..5c7ba36f6 100644 --- a/drivers/pinctrl/samsung/pinctrl-samsung.h +++ b/drivers/pinctrl/samsung/pinctrl-samsung.h @@ -179,7 +179,7 @@ struct samsung_pin_bank { struct gpio_chip gpio_chip; struct pinctrl_gpio_range grange; struct exynos_irq_chip *irq_chip; - raw_spinlock_t slock; + hard_spinlock_t slock; u32 pm_save[PINCFG_TYPE_NUM + 1]; /* +1 to handle double CON registers*/ }; diff --git a/drivers/pinctrl/sunxi/pinctrl-sunxi.c b/drivers/pinctrl/sunxi/pinctrl-sunxi.c index 73bcf806a..d0bd5e43d 100644 --- a/drivers/pinctrl/sunxi/pinctrl-sunxi.c +++ b/drivers/pinctrl/sunxi/pinctrl-sunxi.c @@ -1159,7 +1159,7 @@ static struct irq_chip sunxi_pinctrl_edge_irq_chip = { .irq_release_resources = sunxi_pinctrl_irq_release_resources, .irq_set_type = sunxi_pinctrl_irq_set_type, .irq_set_wake = sunxi_pinctrl_irq_set_wake, - .flags = IRQCHIP_MASK_ON_SUSPEND, + .flags = IRQCHIP_SKIP_SET_WAKE | IRQCHIP_PIPELINE_SAFE, }; static struct irq_chip sunxi_pinctrl_level_irq_chip = { @@ -1177,7 +1177,8 @@ static struct irq_chip sunxi_pinctrl_level_irq_chip = { .irq_set_wake = sunxi_pinctrl_irq_set_wake, .flags = IRQCHIP_EOI_THREADED | IRQCHIP_MASK_ON_SUSPEND | - IRQCHIP_EOI_IF_HANDLED, + IRQCHIP_EOI_IF_HANDLED | + IRQCHIP_PIPELINE_SAFE, }; static int sunxi_pinctrl_irq_of_xlate(struct irq_domain *d, diff --git a/drivers/pinctrl/sunxi/pinctrl-sunxi.h b/drivers/pinctrl/sunxi/pinctrl-sunxi.h index a87a2f944..54f18a970 100644 --- a/drivers/pinctrl/sunxi/pinctrl-sunxi.h +++ b/drivers/pinctrl/sunxi/pinctrl-sunxi.h @@ -172,7 +172,7 @@ struct sunxi_pinctrl { unsigned ngroups; int *irq; unsigned *irq_array; - raw_spinlock_t lock; + hard_spinlock_t lock; struct pinctrl_dev *pctl_dev; unsigned long variant; u32 bank_mem_size; diff --git a/drivers/soc/qcom/smp2p.c b/drivers/soc/qcom/smp2p.c index e9c8030d5..942308476 100644 --- a/drivers/soc/qcom/smp2p.c +++ b/drivers/soc/qcom/smp2p.c @@ -356,6 +356,7 @@ static struct irq_chip smp2p_irq_chip = { .irq_mask = smp2p_mask_irq, .irq_unmask = smp2p_unmask_irq, .irq_set_type = smp2p_set_irq_type, + .flags = IRQCHIP_PIPELINE_SAFE, }; static int smp2p_irq_map(struct irq_domain *d, diff --git a/drivers/soc/ti/ti_sci_inta_msi.c b/drivers/soc/ti/ti_sci_inta_msi.c index c36364522..e6b598a07 100644 --- a/drivers/soc/ti/ti_sci_inta_msi.c +++ b/drivers/soc/ti/ti_sci_inta_msi.c @@ -43,6 +43,7 @@ static void ti_sci_inta_msi_update_chip_ops(struct msi_domain_info *info) chip->irq_unmask = irq_chip_unmask_parent; chip->irq_mask = irq_chip_mask_parent; chip->irq_ack = irq_chip_ack_parent; + chip->flags |= IRQCHIP_PIPELINE_SAFE; } struct irq_domain *ti_sci_inta_msi_create_irq_domain(struct fwnode_handle *fwnode, diff --git a/drivers/spi/Kconfig b/drivers/spi/Kconfig index b09c2c38e..082170ebb 100644 --- a/drivers/spi/Kconfig +++ b/drivers/spi/Kconfig @@ -32,6 +32,10 @@ config SPI_DEBUG Say "yes" to enable debug messaging (like dev_dbg and pr_debug), sysfs, and debugfs support in SPI controller and protocol drivers. +config SPI_OOB + def_bool n + depends on HAS_DMA && DOVETAIL + # # MASTER side ... talking to discrete SPI slave chips including microcontrollers # @@ -172,6 +176,13 @@ config SPI_BCM2835 is for the regular SPI controller. Slave mode operation is not also not supported. +config SPI_BCM2835_OOB + bool "Out-of-band support for BCM2835 SPI controller" + depends on SPI_BCM2835 && DOVETAIL + select SPI_OOB + help + Enable out-of-band cyclic transfers. + config SPI_BCM2835AUX tristate "BCM2835 SPI auxiliary controller" depends on ((ARCH_BCM2835 || ARCH_BRCMSTB) && GPIOLIB) || COMPILE_TEST @@ -1214,6 +1225,10 @@ config SPI_SPIDEV help This supports user mode SPI protocol drivers. +config SPI_SPIDEV_OOB + bool "Enable out-of-band SPI transactions" + depends on SPI_SPIDEV && EVL + config SPI_LOOPBACK_TEST tristate "spi loopback test framework support" depends on m diff --git a/drivers/spi/spi-bcm2835.c b/drivers/spi/spi-bcm2835.c index d3ad0f08d..899e61e2b 100644 --- a/drivers/spi/spi-bcm2835.c +++ b/drivers/spi/spi-bcm2835.c @@ -1035,6 +1035,31 @@ static int bcm2835_spi_transfer_one_poll(struct spi_controller *ctlr, return 0; } + +static unsigned long bcm2835_get_clkdiv(struct bcm2835_spi *bs, u32 spi_hz, + u32 *effective_speed_hz) +{ + unsigned long cdiv; + + if (spi_hz >= bs->clk_hz / 2) { + cdiv = 2; /* clk_hz/2 is the fastest we can go */ + } else if (spi_hz) { + /* CDIV must be a multiple of two */ + cdiv = DIV_ROUND_UP(bs->clk_hz, spi_hz); + cdiv += (cdiv % 2); + + if (cdiv >= 65536) + cdiv = 0; /* 0 is the slowest we can go */ + } else { + cdiv = 0; /* 0 is the slowest we can go */ + } + + *effective_speed_hz = cdiv ? (bs->clk_hz / cdiv) : (bs->clk_hz / 65536); + + return cdiv; +} + + static int bcm2835_spi_transfer_one(struct spi_controller *ctlr, struct spi_device *spi, struct spi_transfer *tfr) @@ -1070,43 +1095,12 @@ static int bcm2835_spi_transfer_one(struct spi_controller *ctlr, } else { cdiv = 0; /* 0 is the slowest we can go */ } - tfr->effective_speed_hz = cdiv ? (bs->clk_hz / cdiv) : (bs->clk_hz / 65536); - bcm2835_wr(bs, BCM2835_SPI_CLK, cdiv); - - /* handle all the 3-wire mode */ - if (spi->mode & SPI_3WIRE && tfr->rx_buf) - cs |= BCM2835_SPI_CS_REN; - - /* set transmit buffers and length */ - bs->tx_buf = tfr->tx_buf; - bs->rx_buf = tfr->rx_buf; - bs->tx_len = tfr->len; - bs->rx_len = tfr->len; - - /* Calculate the estimated time in us the transfer runs. Note that - * there is 1 idle clocks cycles after each byte getting transferred - * so we have 9 cycles/byte. This is used to find the number of Hz - * per byte per polling limit. E.g., we can transfer 1 byte in 30 us - * per 300,000 Hz of bus clock. - */ - hz_per_byte = polling_limit_us ? (9 * 1000000) / polling_limit_us : 0; - byte_limit = hz_per_byte ? tfr->effective_speed_hz / hz_per_byte : 1; - - /* run in polling mode for short transfers */ - if (tfr->len < byte_limit) - return bcm2835_spi_transfer_one_poll(ctlr, spi, tfr, cs); - /* run in dma mode if conditions are right - * Note that unlike poll or interrupt mode DMA mode does not have - * this 1 idle clock cycle pattern but runs the spi clock without gaps - */ - if (ctlr->can_dma && bcm2835_spi_can_dma(ctlr, spi, tfr)) - return bcm2835_spi_transfer_one_dma(ctlr, tfr, target, cs); - - /* run in interrupt-mode */ - return bcm2835_spi_transfer_one_irq(ctlr, spi, tfr, cs, true); + tfr->effective_speed_hz = cdiv ? (bs->clk_hz / cdiv) : (bs->clk_hz / 65536); + return cdiv; } + static int bcm2835_spi_prepare_message(struct spi_controller *ctlr, struct spi_message *msg) { @@ -1234,6 +1228,12 @@ static int bcm2835_spi_setup(struct spi_device *spi) spi_set_ctldata(spi, target); + /* Dovetail: we need this to start oob xfers. */ + bs->target = target; + + /* Dovetail: we need this to start oob xfers. */ + bs->target = target; + ret = bcm2835_spi_setup_dma(ctlr, spi, bs, target); if (ret) goto err_cleanup; @@ -1327,6 +1327,69 @@ static int bcm2835_spi_setup(struct spi_device *spi) return ret; } +#ifdef CONFIG_SPI_BCM2835_OOB + +static int bcm2835_spi_prepare_oob_transfer(struct spi_controller *ctlr, + struct spi_oob_transfer *xfer) +{ + /* + * The size of a transfer is limited by DLEN which is 16-bit + * wide, and we don't want to scatter transfers in out-of-band + * mode, so cap the frame size accordingly. + */ + if (xfer->setup.frame_len > 65532) + return -EINVAL; + + return 0; +} + +static void bcm2835_spi_start_oob_transfer(struct spi_controller *ctlr, + struct spi_oob_transfer *xfer) +{ + struct bcm2835_spi *bs = spi_controller_get_devdata(ctlr); + u32 cs = bs->target->prepare_cs, effective_speed_hz; + struct spi_device *spi = xfer->spi; + unsigned long cdiv; + + /* See bcm2835_spi_prepare_message(). */ + bcm2835_wr(bs, BCM2835_SPI_CS, cs); + + cdiv = bcm2835_get_clkdiv(bs, xfer->setup.speed_hz, &effective_speed_hz); + xfer->effective_speed_hz = effective_speed_hz; + bcm2835_wr(bs, BCM2835_SPI_CLK, cdiv); + bcm2835_wr(bs, BCM2835_SPI_DLEN, xfer->setup.frame_len); + + if (spi->mode & SPI_3WIRE) + cs |= BCM2835_SPI_CS_REN; + bcm2835_wr(bs, BCM2835_SPI_CS, + cs | BCM2835_SPI_CS_TA | BCM2835_SPI_CS_DMAEN); +} + +static void bcm2835_spi_pulse_oob_transfer(struct spi_controller *ctlr, + struct spi_oob_transfer *xfer) +{ + struct bcm2835_spi *bs = spi_controller_get_devdata(ctlr); + + /* Reload DLEN for the next pulse. */ + bcm2835_wr(bs, BCM2835_SPI_DLEN, xfer->setup.frame_len); +} + +static void bcm2835_spi_terminate_oob_transfer(struct spi_controller *ctlr, + struct spi_oob_transfer *xfer) +{ + struct bcm2835_spi *bs = spi_controller_get_devdata(ctlr); + + bcm2835_spi_reset_hw(bs); +} + +#else +#define bcm2835_spi_prepare_oob_transfer NULL +#define bcm2835_spi_start_oob_transfer NULL +#define bcm2835_spi_pulse_oob_transfer NULL +#define bcm2835_spi_terminate_oob_transfer NULL +#endif + + static int bcm2835_spi_probe(struct platform_device *pdev) { struct spi_controller *ctlr; @@ -1349,6 +1412,10 @@ static int bcm2835_spi_probe(struct platform_device *pdev) ctlr->transfer_one = bcm2835_spi_transfer_one; ctlr->handle_err = bcm2835_spi_handle_err; ctlr->prepare_message = bcm2835_spi_prepare_message; + ctlr->prepare_oob_transfer = bcm2835_spi_prepare_oob_transfer; + ctlr->start_oob_transfer = bcm2835_spi_start_oob_transfer; + ctlr->pulse_oob_transfer = bcm2835_spi_pulse_oob_transfer; + ctlr->terminate_oob_transfer = bcm2835_spi_terminate_oob_transfer; ctlr->dev.of_node = pdev->dev.of_node; bs = spi_controller_get_devdata(ctlr); diff --git a/drivers/spi/spi.c b/drivers/spi/spi.c index 93fdee285..c3178a3e0 100644 --- a/drivers/spi/spi.c +++ b/drivers/spi/spi.c @@ -2925,6 +2925,9 @@ struct spi_controller *__spi_alloc_controller(struct device *dev, mutex_init(&ctlr->bus_lock_mutex); mutex_init(&ctlr->io_mutex); mutex_init(&ctlr->add_lock); +#ifdef CONFIG_SPI_OOB + sema_init(&ctlr->bus_oob_lock_sem, 1); +#endif ctlr->bus_num = -1; ctlr->num_chipselect = 1; ctlr->slave = slave; @@ -4225,6 +4228,22 @@ static void __spi_transfer_message_noqueue(struct spi_controller *ctlr, struct s * inline functions. */ +static void get_spi_bus(struct spi_controller *ctlr) +{ + mutex_lock(&ctlr->bus_lock_mutex); +#ifdef CONFIG_SPI_OOB + down(&ctlr->bus_oob_lock_sem); +#endif +} + +static void put_spi_bus(struct spi_controller *ctlr) +{ +#ifdef CONFIG_SPI_OOB + up(&ctlr->bus_oob_lock_sem); +#endif + mutex_unlock(&ctlr->bus_lock_mutex); +} + static void spi_complete(void *arg) { complete(arg); @@ -4314,9 +4333,9 @@ int spi_sync(struct spi_device *spi, struct spi_message *message) { int ret; - mutex_lock(&spi->controller->bus_lock_mutex); + get_spi_bus(spi->controller); ret = __spi_sync(spi, message); - mutex_unlock(&spi->controller->bus_lock_mutex); + put_spi_bus(spi->controller); return ret; } @@ -4363,7 +4382,7 @@ int spi_bus_lock(struct spi_controller *ctlr) { unsigned long flags; - mutex_lock(&ctlr->bus_lock_mutex); + get_spi_bus(ctlr); spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags); ctlr->bus_lock_flag = 1; @@ -4392,7 +4411,7 @@ int spi_bus_unlock(struct spi_controller *ctlr) { ctlr->bus_lock_flag = 0; - mutex_unlock(&ctlr->bus_lock_mutex); + put_spi_bus(ctlr); return 0; } @@ -4478,6 +4497,274 @@ int spi_write_then_read(struct spi_device *spi, } EXPORT_SYMBOL_GPL(spi_write_then_read); +#ifdef CONFIG_SPI_OOB + +static int bus_lock_oob(struct spi_controller *ctlr) +{ + unsigned long flags; + int ret = -EBUSY; + + mutex_lock(&ctlr->bus_lock_mutex); + + spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags); + + if (!ctlr->bus_lock_flag && !down_trylock(&ctlr->bus_oob_lock_sem)) { + ctlr->bus_lock_flag = 1; + ret = 0; + } + + spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags); + + mutex_unlock(&ctlr->bus_lock_mutex); + + return ret; +} + +static int bus_unlock_oob(struct spi_controller *ctlr) +{ + ctlr->bus_lock_flag = 0; + up(&ctlr->bus_oob_lock_sem); + + return 0; +} + +static int prepare_oob_dma(struct spi_controller *ctlr, + struct spi_oob_transfer *xfer) +{ + struct dma_async_tx_descriptor *desc; + size_t len = xfer->setup.frame_len; + dma_cookie_t cookie; + dma_addr_t addr; + int ret; + + /* TX to second half of I/O buffer. */ + addr = xfer->dma_addr + xfer->aligned_frame_len; + desc = dmaengine_prep_slave_single(ctlr->dma_tx, addr, len, + DMA_MEM_TO_DEV, + DMA_OOB_INTERRUPT|DMA_OOB_PULSE); + if (!desc) + return -EIO; + + xfer->txd = desc; + cookie = dmaengine_submit(desc); + ret = dma_submit_error(cookie); + if (ret) + return ret; + + dma_async_issue_pending(ctlr->dma_tx); + + /* RX to first half of I/O buffer. */ + addr = xfer->dma_addr; + desc = dmaengine_prep_slave_single(ctlr->dma_rx, addr, len, + DMA_DEV_TO_MEM, + DMA_OOB_INTERRUPT|DMA_OOB_PULSE); + if (!desc) { + ret = -EIO; + goto fail_rx; + } + + desc->callback = xfer->setup.xfer_done; + desc->callback_param = xfer; + + xfer->rxd = desc; + cookie = dmaengine_submit(desc); + ret = dma_submit_error(cookie); + if (ret) + goto fail_rx; + + dma_async_issue_pending(ctlr->dma_rx); + + return 0; + +fail_rx: + dmaengine_terminate_sync(ctlr->dma_tx); + + return ret; +} + +static void unprepare_oob_dma(struct spi_controller *ctlr) +{ + dmaengine_terminate_sync(ctlr->dma_rx); + dmaengine_terminate_sync(ctlr->dma_tx); +} + +/* + * A simpler version of __spi_validate() for oob transfers. + */ +static int validate_oob_xfer(struct spi_device *spi, + struct spi_oob_transfer *xfer) +{ + struct spi_controller *ctlr = spi->controller; + struct spi_oob_setup *p = &xfer->setup; + int w_size; + + if (p->frame_len == 0) + return -EINVAL; + + if (!p->bits_per_word) + p->bits_per_word = spi->bits_per_word; + + if (!p->speed_hz) + p->speed_hz = spi->max_speed_hz; + + if (ctlr->max_speed_hz && p->speed_hz > ctlr->max_speed_hz) + p->speed_hz = ctlr->max_speed_hz; + + if (__spi_validate_bits_per_word(ctlr, p->bits_per_word)) + return -EINVAL; + + if (p->bits_per_word <= 8) + w_size = 1; + else if (p->bits_per_word <= 16) + w_size = 2; + else + w_size = 4; + + if (p->frame_len % w_size) + return -EINVAL; + + if (p->speed_hz && ctlr->min_speed_hz && + p->speed_hz < ctlr->min_speed_hz) + return -EINVAL; + + return 0; +} + +int spi_prepare_oob_transfer(struct spi_device *spi, + struct spi_oob_transfer *xfer) +{ + struct spi_controller *ctlr; + dma_addr_t dma_addr; + size_t alen, iolen; + void *iobuf; + int ret; + + /* Controller must support oob transactions. */ + ctlr = spi->controller; + if (!ctlr->prepare_oob_transfer) + return -ENOTSUPP; + + /* Out-of-band transfers require DMA support. */ + if (!ctlr->can_dma) + return -ENODEV; + + ret = validate_oob_xfer(spi, xfer); + if (ret) + return ret; + + alen = L1_CACHE_ALIGN(xfer->setup.frame_len); + /* + * Allocate a single coherent I/O buffer which is twice as + * large as the user specified transfer length, TX data goes + * to the upper half, RX data to the lower half. + */ + iolen = alen * 2; + iobuf = dma_alloc_coherent(ctlr->dev.parent, iolen, + &dma_addr, GFP_KERNEL); + if (iobuf == NULL) + return -ENOMEM; + + xfer->spi = spi; + xfer->dma_addr = dma_addr; + xfer->io_buffer = iobuf; + xfer->aligned_frame_len = alen; + xfer->effective_speed_hz = 0; + + ret = prepare_oob_dma(ctlr, xfer); + if (ret) + goto fail_prep_dma; + + ret = bus_lock_oob(ctlr); + if (ret) + goto fail_bus_lock; + + ret = ctlr->prepare_oob_transfer(ctlr, xfer); + if (ret) + goto fail_prep_xfer; + + return 0; + +fail_prep_xfer: + bus_unlock_oob(ctlr); +fail_bus_lock: + unprepare_oob_dma(ctlr); +fail_prep_dma: + dma_free_coherent(ctlr->dev.parent, iolen, iobuf, dma_addr); + + return ret; +} +EXPORT_SYMBOL_GPL(spi_prepare_oob_transfer); + +void spi_start_oob_transfer(struct spi_oob_transfer *xfer) +{ + struct spi_device *spi = xfer->spi; + struct spi_controller *ctlr = spi->controller; + + ctlr->start_oob_transfer(ctlr, xfer); +} +EXPORT_SYMBOL_GPL(spi_start_oob_transfer); + +int spi_pulse_oob_transfer(struct spi_oob_transfer *xfer) /* oob stage */ +{ + struct spi_device *spi = xfer->spi; + struct spi_controller *ctlr = spi->controller; + int ret; + + if (ctlr->pulse_oob_transfer) + ctlr->pulse_oob_transfer(ctlr, xfer); + + ret = dma_pulse_oob(ctlr->dma_rx); + if (likely(!ret)) + ret = dma_pulse_oob(ctlr->dma_tx); + + return ret; +} +EXPORT_SYMBOL_GPL(spi_pulse_oob_transfer); + +void spi_terminate_oob_transfer(struct spi_oob_transfer *xfer) +{ + struct spi_device *spi = xfer->spi; + struct spi_controller *ctlr = spi->controller; + + if (ctlr->terminate_oob_transfer) + ctlr->terminate_oob_transfer(ctlr, xfer); + + unprepare_oob_dma(ctlr); + bus_unlock_oob(ctlr); + dma_free_coherent(ctlr->dev.parent, xfer->aligned_frame_len * 2, + xfer->io_buffer, xfer->dma_addr); +} +EXPORT_SYMBOL_GPL(spi_terminate_oob_transfer); + +int spi_mmap_oob_transfer(struct vm_area_struct *vma, + struct spi_oob_transfer *xfer) +{ + struct spi_device *spi = xfer->spi; + struct spi_controller *ctlr = spi->controller; + size_t len; + int ret; + + /* + * We may have an IOMMU, rely on dma_mmap_coherent() for + * dealing with the nitty-gritty details of mapping a coherent + * buffer. + */ + len = vma->vm_end - vma->vm_start; + if (spi_get_oob_iolen(xfer) <= len) + ret = dma_mmap_coherent(ctlr->dev.parent, + vma, + xfer->io_buffer, + xfer->dma_addr, + len); + else + ret = -EINVAL; + + return ret; +} +EXPORT_SYMBOL_GPL(spi_mmap_oob_transfer); + +#endif /* SPI_OOB */ + /*-------------------------------------------------------------------------*/ #if IS_ENABLED(CONFIG_OF_DYNAMIC) diff --git a/drivers/spi/spidev.c b/drivers/spi/spidev.c index 0daf6e5e9..d972f97d9 100644 --- a/drivers/spi/spidev.c +++ b/drivers/spi/spidev.c @@ -25,7 +25,8 @@ #include #include - +#include +#include /* * This supports access to SPI devices using normal userspace I/O calls. @@ -79,6 +80,15 @@ struct spidev_data { u8 *tx_buffer; u8 *rx_buffer; u32 speed_hz; +#ifdef CONFIG_SPI_SPIDEV_OOB + struct { + struct evl_file efile; + struct spi_oob_transfer xfer; + struct evl_flag flag; + struct evl_ksem sem; + bool enabled; + } oob; +#endif }; static LIST_HEAD(device_list); @@ -351,6 +361,138 @@ spidev_get_ioc_message(unsigned int cmd, struct spi_ioc_transfer __user *u_ioc, return memdup_user(u_ioc, tmp); } +#ifdef CONFIG_SPI_SPIDEV_OOB + +static void oob_transfer_done(void *arg) /* oob stage, hardirqs off */ +{ + struct spidev_data *spidev; + + spidev = container_of(arg, struct spidev_data, oob.xfer); + evl_pulse_flag(&spidev->oob.flag); +} + +static int enable_oob_mode(struct spidev_data *spidev, + struct spi_ioc_oob_setup __user *u_ioc) +{ + struct spi_oob_transfer *xfer = &spidev->oob.xfer; + __u32 tx_offset, rx_offset, iobuf_len; + struct spi_ioc_oob_setup oob_setup; + int ret; + + ret = evl_trydown(&spidev->oob.sem); + if (ret) + return ret; + + if (spidev->oob.enabled) { + ret = -EBUSY; + goto out; + } + + ret = copy_from_user(&oob_setup, u_ioc, sizeof(oob_setup)); + if (ret) + goto out; + + xfer->setup.frame_len = oob_setup.frame_len; + xfer->setup.speed_hz = oob_setup.speed_hz; + xfer->setup.bits_per_word = oob_setup.bits_per_word; + xfer->setup.xfer_done = oob_transfer_done; + ret = spi_prepare_oob_transfer(spidev->spi, xfer); + if (ret) + goto out; + + tx_offset = (__u32)spi_get_oob_txoff(xfer); + put_user(tx_offset, &u_ioc->tx_offset); + rx_offset = (__u32)spi_get_oob_rxoff(xfer); + put_user(rx_offset, &u_ioc->rx_offset); + iobuf_len = (__u32)spi_get_oob_iolen(xfer); + put_user(iobuf_len, &u_ioc->iobuf_len); + + evl_clear_flag(&spidev->oob.flag); + spi_start_oob_transfer(xfer); + spidev->oob.enabled = true; +out: + evl_up(&spidev->oob.sem); + + return ret == -ENOTSUPP ? -EOPNOTSUPP : ret; +} + +static int disable_oob_mode(struct spidev_data *spidev) +{ + int ret; + + ret = evl_trydown(&spidev->oob.sem); + if (ret) + return ret; + + if (spidev->oob.enabled) { + spi_terminate_oob_transfer(&spidev->oob.xfer); + spidev->oob.enabled = false; + } + + evl_up(&spidev->oob.sem); + + return 0; +} + +static int run_oob_transfer(struct spidev_data *spidev) /* oob stage */ +{ + int ret; + + ret = evl_down(&spidev->oob.sem); + if (ret) + return ret; + + if (!spidev->oob.enabled) { + ret = -ENXIO; + goto out; + } + + ret = spi_pulse_oob_transfer(&spidev->oob.xfer); + if (ret) + goto out; + + ret = evl_wait_flag(&spidev->oob.flag); +out: + evl_up(&spidev->oob.sem); + + return ret; +} + +static long +spidev_oob_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) +{ + struct spidev_data *spidev = filp->private_data; + long ret; + + switch (cmd) { + case SPI_IOC_RUN_OOB_XFER: + ret = run_oob_transfer(spidev); + break; + default: + ret = -ENOTTY; + } + + return ret; +} + +static int spidev_mmap(struct file *filp, struct vm_area_struct *vma) +{ + struct spidev_data *spidev = filp->private_data; + int ret; + + mutex_lock(&spidev->buf_lock); + + if (!spidev->oob.enabled) + ret = -ENXIO; + else + ret = spi_mmap_oob_transfer(vma, &spidev->oob.xfer); + + mutex_unlock(&spidev->buf_lock); + + return ret; +} +#endif + static long spidev_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { @@ -493,6 +635,18 @@ spidev_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) spi->max_speed_hz = save; break; } + +#ifdef CONFIG_SPI_SPIDEV_OOB + case SPI_IOC_ENABLE_OOB_MODE: + retval = enable_oob_mode(spidev, + (struct spi_ioc_oob_setup __user *)arg); + break; + + case SPI_IOC_DISABLE_OOB_MODE: + retval = disable_oob_mode(spidev); + break; +#endif + default: /* segmented and/or full-duplex I/O request */ /* Check message and copy into scratch area */ @@ -585,6 +739,42 @@ spidev_compat_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) #define spidev_compat_ioctl NULL #endif /* CONFIG_COMPAT */ +#ifdef CONFIG_SPI_SPIDEV_OOB +static int init_oob_state(struct spidev_data *spidev, + struct file *filp) +{ + evl_init_flag(&spidev->oob.flag); + evl_init_ksem(&spidev->oob.sem, 1); + + return evl_open_file(&spidev->oob.efile, filp); +} + +static void release_oob_state(struct spidev_data *spidev) +{ + /* + * First, delete wait objects to unblocks waiters + * if any. + */ + evl_destroy_flag(&spidev->oob.flag); + evl_destroy_ksem(&spidev->oob.sem); + /* + * Releasing the EVL file waits for any unblocked waiter to + * leave the oob call before returning. + */ + evl_release_file(&spidev->oob.efile); + disable_oob_mode(spidev); +} +#else +static inline int init_oob_state(struct spidev_data*spidev, + struct file *filp) +{ + return 0; +} + +static void release_oob_state(struct spidev_data *spidev) +{ } +#endif + static int spidev_open(struct inode *inode, struct file *filp) { struct spidev_data *spidev = NULL, *iter; @@ -621,6 +811,10 @@ static int spidev_open(struct inode *inode, struct file *filp) } } + status = init_oob_state(spidev, filp); + if (status) + goto err_init_oob; + spidev->users++; filp->private_data = spidev; stream_open(inode, filp); @@ -628,6 +822,9 @@ static int spidev_open(struct inode *inode, struct file *filp) mutex_unlock(&device_list_lock); return 0; +err_init_oob: + kfree(spidev->rx_buffer); + spidev->rx_buffer = NULL; err_alloc_rx_buf: kfree(spidev->tx_buffer); spidev->tx_buffer = NULL; @@ -641,8 +838,9 @@ static int spidev_release(struct inode *inode, struct file *filp) struct spidev_data *spidev; int dofree; - mutex_lock(&device_list_lock); spidev = filp->private_data; + release_oob_state(spidev); + mutex_lock(&device_list_lock); filp->private_data = NULL; mutex_lock(&spidev->spi_lock); @@ -687,6 +885,11 @@ static const struct file_operations spidev_fops = { .open = spidev_open, .release = spidev_release, .llseek = no_llseek, +#ifdef CONFIG_SPI_SPIDEV_OOB + .mmap = spidev_mmap, + .oob_ioctl = spidev_oob_ioctl, + .compat_oob_ioctl = compat_ptr_oob_ioctl, +#endif }; /*-------------------------------------------------------------------------*/ diff --git a/drivers/spmi/spmi-pmic-arb.c b/drivers/spmi/spmi-pmic-arb.c index dcb675d98..eca473b9e 100644 --- a/drivers/spmi/spmi-pmic-arb.c +++ b/drivers/spmi/spmi-pmic-arb.c @@ -159,7 +159,7 @@ struct spmi_pmic_arb { void __iomem *cnfg; void __iomem *core; resource_size_t core_size; - raw_spinlock_t lock; + hard_spinlock_t lock; u8 channel; int irq; u8 ee; @@ -852,7 +852,7 @@ static struct irq_chip pmic_arb_irqchip = { .irq_set_type = qpnpint_irq_set_type, .irq_set_wake = qpnpint_irq_set_wake, .irq_get_irqchip_state = qpnpint_get_irqchip_state, - .flags = IRQCHIP_MASK_ON_SUSPEND, + .flags = IRQCHIP_MASK_ON_SUSPEND|IRQCHIP_PIPELINE_SAFE, }; static int qpnpint_irq_domain_translate(struct irq_domain *d, diff --git a/drivers/tty/serial/8250/8250_core.c b/drivers/tty/serial/8250/8250_core.c index 679a74d9f..2bf76cac1 100644 --- a/drivers/tty/serial/8250/8250_core.c +++ b/drivers/tty/serial/8250/8250_core.c @@ -711,6 +711,48 @@ static int univ8250_console_match(struct console *co, char *name, int idx, return -ENODEV; } +#ifdef CONFIG_RAW_PRINTK + +static void raw_write_char(struct uart_8250_port *up, int c) +{ + unsigned int status, tmout = 10000; + + for (;;) { + status = serial_in(up, UART_LSR); + up->lsr_saved_flags |= status & LSR_SAVE_FLAGS; + if ((status & UART_LSR_THRE) == UART_LSR_THRE) + break; + if (--tmout == 0) + break; + cpu_relax(); + } + serial_port_out(&up->port, UART_TX, c); +} + +static void univ8250_console_write_raw(struct console *co, const char *s, + unsigned int count) +{ + struct uart_8250_port *up = &serial8250_ports[co->index]; + unsigned int ier; + + ier = serial_in(up, UART_IER); + + if (up->capabilities & UART_CAP_UUE) + serial_out(up, UART_IER, UART_IER_UUE); + else + serial_out(up, UART_IER, 0); + + while (count-- > 0) { + if (*s == '\n') + raw_write_char(up, '\r'); + raw_write_char(up, *s++); + } + + serial_out(up, UART_IER, ier); +} + +#endif + static struct console univ8250_console = { .name = "ttyS", .write = univ8250_console_write, @@ -718,6 +760,9 @@ static struct console univ8250_console = { .setup = univ8250_console_setup, .exit = univ8250_console_exit, .match = univ8250_console_match, +#ifdef CONFIG_RAW_PRINTK + .write_raw = univ8250_console_write_raw, +#endif .flags = CON_PRINTBUFFER | CON_ANYTIME, .index = -1, .data = &serial8250_reg, diff --git a/drivers/tty/serial/amba-pl011.c b/drivers/tty/serial/amba-pl011.c index 778bac198..7a97588e8 100644 --- a/drivers/tty/serial/amba-pl011.c +++ b/drivers/tty/serial/amba-pl011.c @@ -2005,6 +2005,8 @@ static void pl011_shutdown(struct uart_port *port) pl011_disable_uart(uap); + if (IS_ENABLED(CONFIG_RAW_PRINTK)) + clk_disable(uap->clk); /* * Shut down the clock producer */ @@ -2351,6 +2353,37 @@ static void pl011_console_putchar(struct uart_port *port, unsigned char ch) pl011_write(ch, uap, REG_DR); } +#ifdef CONFIG_RAW_PRINTK + +static void +pl011_console_write_raw(struct console *co, const char *s, unsigned int count) +{ + struct uart_amba_port *uap = amba_ports[co->index]; + unsigned int old_cr = 0, new_cr; + + if (!uap->vendor->always_enabled) { + old_cr = pl011_read(uap, REG_CR); + new_cr = old_cr & ~UART011_CR_CTSEN; + new_cr |= UART01x_CR_UARTEN | UART011_CR_TXE; + pl011_write(new_cr, uap, REG_CR); + } + + while (count-- > 0) { + if (*s == '\n') + pl011_console_putchar(&uap->port, '\r'); + pl011_console_putchar(&uap->port, *s++); + } + + while ((pl011_read(uap, REG_FR) ^ uap->vendor->inv_fr) + & uap->vendor->fr_busy) + cpu_relax(); + + if (!uap->vendor->always_enabled) + pl011_write(old_cr, uap, REG_CR); +} + +#endif /* !CONFIG_RAW_PRINTK */ + static void pl011_console_write(struct console *co, const char *s, unsigned int count) { @@ -2480,6 +2513,9 @@ static int pl011_console_setup(struct console *co, char *options) pl011_console_get_options(uap, &baud, &parity, &bits); } + if (IS_ENABLED(CONFIG_RAW_PRINTK)) + clk_enable(uap->clk); + return uart_set_options(&uap->port, co, baud, parity, bits, flow); } @@ -2550,6 +2586,9 @@ static struct console amba_console = { .device = uart_console_device, .setup = pl011_console_setup, .match = pl011_console_match, +#ifdef CONFIG_RAW_PRINTK + .write_raw = pl011_console_write_raw, +#endif .flags = CON_PRINTBUFFER | CON_ANYTIME, .index = -1, .data = &amba_reg, diff --git a/drivers/tty/serial/imx.c b/drivers/tty/serial/imx.c index 349d4849b..d2543ba9e 100644 --- a/drivers/tty/serial/imx.c +++ b/drivers/tty/serial/imx.c @@ -2022,24 +2022,11 @@ static void imx_uart_console_putchar(struct uart_port *port, unsigned char ch) imx_uart_writel(sport, ch, URTX0); } -/* - * Interrupts are disabled on entering - */ static void -imx_uart_console_write(struct console *co, const char *s, unsigned int count) +__imx_uart_console_write(struct imx_port *sport, const char *s, unsigned int count) { - struct imx_port *sport = imx_uart_ports[co->index]; struct imx_port_ucrs old_ucr; - unsigned long flags; unsigned int ucr1, usr2; - int locked = 1; - - if (sport->port.sysrq) - locked = 0; - else if (oops_in_progress) - locked = spin_trylock_irqsave(&sport->port.lock, flags); - else - spin_lock_irqsave(&sport->port.lock, flags); /* * First, save UCR1/2/3 and then disable interrupts @@ -2065,11 +2052,41 @@ imx_uart_console_write(struct console *co, const char *s, unsigned int count) read_poll_timeout_atomic(imx_uart_readl, usr2, usr2 & USR2_TXDC, 0, USEC_PER_SEC, false, sport, USR2); imx_uart_ucrs_restore(sport, &old_ucr); +} + +/* + * Interrupts are disabled on entering + */ +static void +imx_uart_console_write(struct console *co, const char *s, unsigned int count) +{ + struct imx_port *sport = imx_uart_ports[co->index]; + unsigned long flags; + int locked = 1; + + if (sport->port.sysrq) + locked = 0; + else if (oops_in_progress) + locked = spin_trylock_irqsave(&sport->port.lock, flags); + else + spin_lock_irqsave(&sport->port.lock, flags); + + __imx_uart_console_write(sport, s, count); if (locked) spin_unlock_irqrestore(&sport->port.lock, flags); } +#ifdef CONFIG_RAW_PRINTK +static void +imx_uart_console_write_raw(struct console *co, const char *s, unsigned int count) +{ + struct imx_port *sport = imx_uart_ports[co->index]; + + return __imx_uart_console_write(sport, s, count); +} +#endif + /* * If the port was already initialised (eg, by a boot loader), * try to determine the current setup. @@ -2196,6 +2213,9 @@ static struct uart_driver imx_uart_uart_driver; static struct console imx_uart_console = { .name = DEV_NAME, .write = imx_uart_console_write, +#ifdef CONFIG_RAW_PRINTK + .write_raw = imx_uart_console_write_raw, +#endif .device = uart_console_device, .setup = imx_uart_console_setup, .exit = imx_uart_console_exit, diff --git a/drivers/tty/serial/samsung_tty.c b/drivers/tty/serial/samsung_tty.c index 5a4d88e13..0a2a88339 100644 --- a/drivers/tty/serial/samsung_tty.c +++ b/drivers/tty/serial/samsung_tty.c @@ -2494,6 +2494,10 @@ static struct console s3c24xx_serial_console = { .flags = CON_PRINTBUFFER, .index = -1, .write = s3c24xx_serial_console_write, +#ifdef CONFIG_RAW_PRINTK + /* The common write handler can run from atomic context. */ + .write_raw = s3c24xx_serial_console_write, +#endif .setup = s3c24xx_serial_console_setup, .data = &s3c24xx_uart_drv, }; diff --git a/drivers/tty/serial/st-asc.c b/drivers/tty/serial/st-asc.c index 92b9f6894..11cacd689 100644 --- a/drivers/tty/serial/st-asc.c +++ b/drivers/tty/serial/st-asc.c @@ -872,6 +872,29 @@ static void asc_console_write(struct console *co, const char *s, unsigned count) spin_unlock_irqrestore(&port->lock, flags); } +#ifdef CONFIG_RAW_PRINTK + +static void asc_console_write_raw(struct console *co, + const char *s, unsigned int count) +{ + struct uart_port *port = &asc_ports[co->index].port; + unsigned long timeout = 1000000; + u32 intenable; + + intenable = asc_in(port, ASC_INTEN); + asc_out(port, ASC_INTEN, 0); + (void)asc_in(port, ASC_INTEN); /* Defeat bus write posting */ + + uart_console_write(port, s, count, asc_console_putchar); + + while (timeout-- && !asc_txfifo_is_empty(port)) + cpu_relax(); /* wait shorter */ + + asc_out(port, ASC_INTEN, intenable); +} + +#endif + static int asc_console_setup(struct console *co, char *options) { struct asc_port *ascport; @@ -904,6 +927,9 @@ static struct console asc_console = { .name = ASC_SERIAL_NAME, .device = uart_console_device, .write = asc_console_write, +#ifdef CONFIG_RAW_PRINTK + .write_raw = asc_console_write_raw, +#endif .setup = asc_console_setup, .flags = CON_PRINTBUFFER, .index = -1, diff --git a/drivers/xen/events/events_base.c b/drivers/xen/events/events_base.c index 9e3b5d21d..75733eefe 100644 --- a/drivers/xen/events/events_base.c +++ b/drivers/xen/events/events_base.c @@ -2235,7 +2235,7 @@ static __init void xen_alloc_callback_vector(void) return; pr_info("Xen HVM callback vector for event delivery is enabled\n"); - alloc_intr_gate(HYPERVISOR_CALLBACK_VECTOR, asm_sysvec_xen_hvm_callback); + sysvec_install(HYPERVISOR_CALLBACK_VECTOR, sysvec_xen_hvm_callback); } #else void xen_setup_callback_vector(void) {} diff --git a/fs/eventfd.c b/fs/eventfd.c index 33a918f95..41efead33 100644 --- a/fs/eventfd.c +++ b/fs/eventfd.c @@ -256,16 +256,16 @@ static ssize_t eventfd_read(struct kiocb *iocb, struct iov_iter *to) return sizeof(ucnt); } -static ssize_t eventfd_write(struct file *file, const char __user *buf, size_t count, - loff_t *ppos) +static ssize_t eventfd_write(struct kiocb *iocb, struct iov_iter *from) { + struct file *file = iocb->ki_filp; struct eventfd_ctx *ctx = file->private_data; ssize_t res; __u64 ucnt; - if (count < sizeof(ucnt)) + if (iov_iter_count(from) < sizeof(ucnt)) return -EINVAL; - if (copy_from_user(&ucnt, buf, sizeof(ucnt))) + if (copy_from_iter(&ucnt, sizeof(ucnt), from) != sizeof(ucnt)) return -EFAULT; if (ucnt == ULLONG_MAX) return -EINVAL; @@ -313,7 +313,7 @@ static const struct file_operations eventfd_fops = { .release = eventfd_release, .poll = eventfd_poll, .read_iter = eventfd_read, - .write = eventfd_write, + .write_iter = eventfd_write, .llseek = noop_llseek, }; diff --git a/fs/exec.c b/fs/exec.c index 7776209d9..b76ec4d41 100644 --- a/fs/exec.c +++ b/fs/exec.c @@ -33,6 +33,7 @@ #include #include #include +#include #include #include #include @@ -980,6 +981,7 @@ static int exec_mmap(struct mm_struct *mm) struct task_struct *tsk; struct mm_struct *old_mm, *active_mm; int ret; + unsigned long flags; /* Notify parent that we're no longer interested in the old VM */ tsk = current; @@ -1010,6 +1012,7 @@ static int exec_mmap(struct mm_struct *mm) local_irq_disable(); active_mm = tsk->active_mm; + protect_inband_mm(flags); tsk->active_mm = mm; tsk->mm = mm; mm_init_cid(mm); @@ -1019,10 +1022,17 @@ static int exec_mmap(struct mm_struct *mm) * lazy tlb mm refcounting when these are updated by context * switches. Not all architectures can handle irqs off over * activate_mm yet. + * + * irq_pipeline: activate_mm() allowing irqs off context is a + * requirement. e.g. TLB shootdown must not involve IPIs. We + * make sure protect_inband_mm() is in effect while switching + * in and activating the new mm by forcing + * CONFIG_ARCH_WANT_IRQS_OFF_ACTIVATE_MM on. */ if (!IS_ENABLED(CONFIG_ARCH_WANT_IRQS_OFF_ACTIVATE_MM)) local_irq_enable(); activate_mm(active_mm, mm); + unprotect_inband_mm(flags); if (IS_ENABLED(CONFIG_ARCH_WANT_IRQS_OFF_ACTIVATE_MM)) local_irq_enable(); lru_gen_add_mm(mm); @@ -1319,6 +1329,10 @@ int begin_new_exec(struct linux_binprm * bprm) me->flags &= ~(PF_RANDOMIZE | PF_FORKNOEXEC | PF_NOFREEZE | PF_NO_SETAFFINITY); + + /* Tell Dovetail about the ongoing exec(). */ + arch_dovetail_exec_prepare(); + flush_thread(); me->personality &= ~bprm->per_clear; diff --git a/fs/fcntl.c b/fs/fcntl.c index 1484f062e..e1bd3f36d 100644 --- a/fs/fcntl.c +++ b/fs/fcntl.c @@ -1021,7 +1021,7 @@ static int __init fcntl_init(void) * Exceptions: O_NONBLOCK is a two bit define on parisc; O_NDELAY * is defined as O_NONBLOCK on some platforms and not on others. */ - BUILD_BUG_ON(21 - 1 /* for O_RDONLY being 0 */ != + BUILD_BUG_ON(22 - 1 /* for O_RDONLY being 0 */ != HWEIGHT32( (VALID_OPEN_FLAGS & ~(O_NONBLOCK | O_NDELAY)) | __FMODE_EXEC | __FMODE_NONOTIFY)); diff --git a/fs/file.c b/fs/file.c index a178efc8c..a592ea487 100644 --- a/fs/file.c +++ b/fs/file.c @@ -411,6 +411,7 @@ static struct fdtable *close_files(struct files_struct * files) if (set & 1) { struct file * file = xchg(&fdt->fd[i], NULL); if (file) { + uninstall_inband_fd(i, file, files); filp_close(file, files); cond_resched(); } @@ -594,6 +595,7 @@ void fd_install(unsigned int fd, struct file *file) fdt = files_fdtable(files); BUG_ON(fdt->fd[fd] != NULL); rcu_assign_pointer(fdt->fd[fd], file); + install_inband_fd(fd, file, files); spin_unlock(&files->file_lock); return; } @@ -602,6 +604,7 @@ void fd_install(unsigned int fd, struct file *file) fdt = rcu_dereference_sched(files->fdt); BUG_ON(fdt->fd[fd] != NULL); rcu_assign_pointer(fdt->fd[fd], file); + install_inband_fd(fd, file, files); rcu_read_unlock_sched(); } @@ -629,6 +632,7 @@ static struct file *pick_file(struct files_struct *files, unsigned fd) if (file) { rcu_assign_pointer(fdt->fd[fd], NULL); __put_unused_fd(files, fd); + uninstall_inband_fd(fd, file, files); } return file; } @@ -813,6 +817,7 @@ void do_close_on_exec(struct files_struct *files) continue; rcu_assign_pointer(fdt->fd[fd], NULL); __put_unused_fd(files, fd); + uninstall_inband_fd(fd, file, files); spin_unlock(&files->file_lock); filp_close(file, files); cond_resched(); @@ -1105,6 +1110,7 @@ __releases(&files->file_lock) __set_close_on_exec(fd, fdt); else __clear_close_on_exec(fd, fdt); + replace_inband_fd(fd, file, files); spin_unlock(&files->file_lock); if (tofree) diff --git a/fs/ioctl.c b/fs/ioctl.c index 76cf22ac9..36c340ffc 100644 --- a/fs/ioctl.c +++ b/fs/ioctl.c @@ -911,6 +911,22 @@ long compat_ptr_ioctl(struct file *file, unsigned int cmd, unsigned long arg) } EXPORT_SYMBOL(compat_ptr_ioctl); +/** + * compat_ptr_oob_ioctl - generic implementation of .compat_oob_ioctl file operation + * + * The equivalent of compat_ptr_ioctl, dealing with out-of-band ioctl + * calls. Management of this handler is delegated to the code + * implementing the out-of-band ioctl() syscall in the companion core. + */ +long compat_ptr_oob_ioctl(struct file *file, unsigned int cmd, unsigned long arg) +{ + if (!file->f_op->oob_ioctl) + return -ENOIOCTLCMD; + + return file->f_op->oob_ioctl(file, cmd, (unsigned long)compat_ptr(arg)); +} +EXPORT_SYMBOL(compat_ptr_oob_ioctl); + COMPAT_SYSCALL_DEFINE3(ioctl, unsigned int, fd, unsigned int, cmd, compat_ulong_t, arg) { diff --git a/include/asm-generic/atomic.h b/include/asm-generic/atomic.h index 22142c71d..6a4c96132 100644 --- a/include/asm-generic/atomic.h +++ b/include/asm-generic/atomic.h @@ -59,9 +59,9 @@ static inline void generic_atomic_##op(int i, atomic_t *v) \ { \ unsigned long flags; \ \ - raw_local_irq_save(flags); \ + flags = hard_local_irq_save(); \ v->counter = v->counter c_op i; \ - raw_local_irq_restore(flags); \ + hard_local_irq_restore(flags); \ } #define ATOMIC_OP_RETURN(op, c_op) \ @@ -70,9 +70,9 @@ static inline int generic_atomic_##op##_return(int i, atomic_t *v) \ unsigned long flags; \ int ret; \ \ - raw_local_irq_save(flags); \ + flags = hard_local_irq_save(); \ ret = (v->counter = v->counter c_op i); \ - raw_local_irq_restore(flags); \ + hard_local_irq_restore(flags); \ \ return ret; \ } @@ -83,10 +83,10 @@ static inline int generic_atomic_fetch_##op(int i, atomic_t *v) \ unsigned long flags; \ int ret; \ \ - raw_local_irq_save(flags); \ + flags = hard_local_irq_save(); \ ret = v->counter; \ v->counter = v->counter c_op i; \ - raw_local_irq_restore(flags); \ + hard_local_irq_restore(flags); \ \ return ret; \ } diff --git a/include/asm-generic/cmpxchg-local.h b/include/asm-generic/cmpxchg-local.h index f27d66fdc..8e762f137 100644 --- a/include/asm-generic/cmpxchg-local.h +++ b/include/asm-generic/cmpxchg-local.h @@ -23,7 +23,7 @@ static inline unsigned long __generic_cmpxchg_local(volatile void *ptr, if (size == 8 && sizeof(unsigned long) != 8) wrong_size_cmpxchg(ptr); - raw_local_irq_save(flags); + flags = hard_local_irq_save(); switch (size) { case 1: prev = *(u8 *)ptr; if (prev == (old & 0xffu)) @@ -44,7 +44,7 @@ static inline unsigned long __generic_cmpxchg_local(volatile void *ptr, default: wrong_size_cmpxchg(ptr); } - raw_local_irq_restore(flags); + hard_local_irq_restore(flags); return prev; } @@ -57,11 +57,11 @@ static inline u64 __generic_cmpxchg64_local(volatile void *ptr, u64 prev; unsigned long flags; - raw_local_irq_save(flags); + flags = hard_local_irq_save(); prev = *(u64 *)ptr; if (prev == old) *(u64 *)ptr = new; - raw_local_irq_restore(flags); + hard_local_irq_restore(flags); return prev; } diff --git a/include/asm-generic/cmpxchg.h b/include/asm-generic/cmpxchg.h index 848de25fc..4deb5dcd3 100644 --- a/include/asm-generic/cmpxchg.h +++ b/include/asm-generic/cmpxchg.h @@ -30,10 +30,10 @@ unsigned long __generic_xchg(unsigned long x, volatile void *ptr, int size) #ifdef __xchg_u8 return __xchg_u8(x, ptr); #else - local_irq_save(flags); + flags = hard_local_irq_save(); ret = *(volatile u8 *)ptr; *(volatile u8 *)ptr = (x & 0xffu); - local_irq_restore(flags); + hard_local_irq_restore(flags); return ret; #endif /* __xchg_u8 */ @@ -41,10 +41,10 @@ unsigned long __generic_xchg(unsigned long x, volatile void *ptr, int size) #ifdef __xchg_u16 return __xchg_u16(x, ptr); #else - local_irq_save(flags); + flags = hard_local_irq_save(); ret = *(volatile u16 *)ptr; *(volatile u16 *)ptr = (x & 0xffffu); - local_irq_restore(flags); + hard_local_irq_restore(flags); return ret; #endif /* __xchg_u16 */ @@ -52,10 +52,10 @@ unsigned long __generic_xchg(unsigned long x, volatile void *ptr, int size) #ifdef __xchg_u32 return __xchg_u32(x, ptr); #else - local_irq_save(flags); + flags = hard_local_irq_save(); ret = *(volatile u32 *)ptr; *(volatile u32 *)ptr = (x & 0xffffffffu); - local_irq_restore(flags); + hard_local_irq_restore(flags); return ret; #endif /* __xchg_u32 */ @@ -64,10 +64,10 @@ unsigned long __generic_xchg(unsigned long x, volatile void *ptr, int size) #ifdef __xchg_u64 return __xchg_u64(x, ptr); #else - local_irq_save(flags); + flags = hard_local_irq_save(); ret = *(volatile u64 *)ptr; *(volatile u64 *)ptr = x; - local_irq_restore(flags); + hard_local_irq_restore(flags); return ret; #endif /* __xchg_u64 */ #endif /* CONFIG_64BIT */ diff --git a/include/asm-generic/evl/irq.h b/include/asm-generic/evl/irq.h new file mode 100644 index 000000000..ea3d047c3 --- /dev/null +++ b/include/asm-generic/evl/irq.h @@ -0,0 +1,21 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _ASM_GENERIC_EVL_IRQ_H +#define _ASM_GENERIC_EVL_IRQ_H + +#include + +static inline void irq_enter_pipeline(void) +{ +#ifdef CONFIG_EVL + evl_enter_irq(); +#endif +} + +static inline void irq_exit_pipeline(void) +{ +#ifdef CONFIG_EVL + evl_exit_irq(); +#endif +} + +#endif /* !_ASM_GENERIC_EVL_IRQ_H */ diff --git a/include/asm-generic/evl/mm_info.h b/include/asm-generic/evl/mm_info.h new file mode 100644 index 000000000..092b3aab8 --- /dev/null +++ b/include/asm-generic/evl/mm_info.h @@ -0,0 +1,28 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _ASM_GENERIC_EVL_MM_INFO_H +#define _ASM_GENERIC_EVL_MM_INFO_H + +#ifdef CONFIG_EVL + +#include +#include + +#define EVL_MM_PTSYNC_BIT 0 +#define EVL_MM_ACTIVE_BIT 30 +#define EVL_MM_INIT_BIT 31 + +struct evl_wait_queue; + +struct oob_mm_state { + unsigned long flags; /* Guaranteed zero initially. */ + struct list_head ptrace_sync; + struct evl_wait_queue ptsync_barrier; +}; + +#else + +struct oob_mm_state { }; + +#endif /* !CONFIG_EVL */ + +#endif /* !_ASM_GENERIC_EVL_MM_INFO_H */ diff --git a/include/asm-generic/evl/net.h b/include/asm-generic/evl/net.h new file mode 100644 index 000000000..845639c1b --- /dev/null +++ b/include/asm-generic/evl/net.h @@ -0,0 +1,99 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _ASM_GENERIC_EVL_NET_H +#define _ASM_GENERIC_EVL_NET_H + +#ifdef CONFIG_EVL_NET + +#include +#include +#include +#include +#include +#include +#include + +#define EVL_NET_FRAGS_HASHBITS 7 + +struct evl_net_frag_tdir; +struct net_device; + +struct evl_net_frag_tree { + /* End offset (bytes). */ + size_t end; + /* Cumulated length (bytes). */ + size_t len; + /* Status flags. */ + int flags; + /* Root of fragment tree. */ + struct rb_root frags; + /* Hash collision link. */ + struct hlist_node hash; + /* Backlink to parent tree directory. */ + struct evl_net_frag_tdir *tdir; + /* The device performing garbage collection. */ + struct net_device *gc_dev; + /* Garbage collection link (pending). */ + struct hlist_node gc; + /* Expiration timer (set to IP_FRAG_TIME). */ + struct evl_timer timer; + /* + * Serializes access to the frags tree. This is lightweight, + * and may be initialized from the out-of-band stage. + */ + evl_spinlock_t lock; + /* Hash key (ipv4 so far). */ + union { + struct frag_v4_compare_key ipv4; + } key; +}; + +struct evl_net_frag_gc { + /* Garbage collection queue for fragment trees. */ + struct hlist_head queue; + /* + * Serializes access to the garbage collection queue between + * an oob interrupt handler and a kthread. + */ + hard_spinlock_t lock; +}; + +struct evl_net_frag_tdir { + /* Hash map of fragment trees. */ + DECLARE_HASHTABLE(ht, EVL_NET_FRAGS_HASHBITS); + /* Serializes updates to the hash table. */ + struct evl_kmutex lock; + /* Garbage collector. */ + struct evl_net_frag_gc gc; + /* Fragment lifetime (ns). */ + ktime_t timeout; +}; + +struct oob_net_state { + struct { + /* Fragment tree directory. */ + struct evl_net_frag_tdir ftdir; + /* ARP resolution cache. */ + struct evl_cache arp; + /* Route cache of IPv4 destinations. */ + struct evl_cache routes; + /* Cache of active UDP4 receivers. */ + struct evl_cache udp; + } ipv4; +}; + +void net_init_oob_state(struct net *net); +void net_cleanup_oob_state(struct net *net); + +#else + +struct oob_net_state { +}; + +struct net; + +static inline void net_init_oob_state(struct net *net) { } +static inline void net_cleanup_oob_state(struct net *net) { } + +#endif + +#endif /* !_ASM_GENERIC_EVL_NET_H */ diff --git a/include/asm-generic/evl/netdevice.h b/include/asm-generic/evl/netdevice.h new file mode 100644 index 000000000..45f32cf90 --- /dev/null +++ b/include/asm-generic/evl/netdevice.h @@ -0,0 +1,97 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _ASM_GENERIC_EVL_NETDEVICE_H +#define _ASM_GENERIC_EVL_NETDEVICE_H + +#ifdef CONFIG_EVL_NET + +#include +#include +#include +#include +#include +#include +#include +#include + +struct evl_net_qdisc; +struct evl_kthread; +struct bpf_prog; + +struct evl_net_skb_queue { + struct list_head queue; + hard_spinlock_t lock; +}; + +struct evl_net_ebpf_filter { + struct rcu_head rcu; + struct bpf_prog *prog; +}; + +#define EVL_NETDEV_POLL_SCHED 0 +#define EVL_NETDEV_RXFILTER_BIT 1 + +struct evl_netdev_state { + /* TX page pool (premapped if device is oob-capable). */ + struct page_pool *tx_pages; + struct evl_wait_queue tx_wait; + size_t pool_max; + size_t buf_size; + struct evl_poll_head poll_head; + /* RX handling */ + struct evl_kthread *rx_handler; + struct evl_flag rx_flag; + struct list_head rx_poll; /* NAPI instances to poll (oob) */ + hard_spinlock_t rx_lock; /* Serializes accesses to rx_poll */ + struct evl_net_skb_queue rx_packets; /* Ingress packets to process (oob) */ + /* TX handling */ + struct evl_net_qdisc *qdisc; + struct evl_kthread *tx_handler; + struct evl_flag tx_flag; + /* RX filter/redirector */ + spinlock_t filter_lock; + struct evl_net_ebpf_filter __rcu *rx_filter; + /* Runtime state flags. */ + unsigned long flags; + /* Count of oob ports referring to this device. */ + int refs; +}; + +struct oob_netdev_state { + struct evl_netdev_state *estate; + struct evl_crossing crossing; + struct list_head next; +}; + +struct oob_netqueue_state { + struct evl_stax tx_lock; /* inband vs oob exclusion lock */ +}; + +static inline void netqueue_init_oob(struct oob_netqueue_state *qs) +{ + evl_init_stax(&qs->tx_lock, EVL_STAX_INBAND_SPIN); +} + +static inline void netqueue_destroy_oob(struct oob_netqueue_state *qs) +{ + evl_destroy_stax(&qs->tx_lock); +} + +#else /* !CONFIG_EVL_NET */ + +struct oob_netdev_state { +}; + +struct oob_netqueue_state { +}; + +static inline void netqueue_init_oob(struct oob_netqueue_state *qs) +{ +} + +static inline void netqueue_destroy_oob(struct oob_netqueue_state *qs) +{ +} + +#endif /* !CONFIG_EVL_NET */ + +#endif /* !_ASM_GENERIC_EVL_NETDEVICE_H */ diff --git a/include/asm-generic/evl/poll.h b/include/asm-generic/evl/poll.h new file mode 100644 index 000000000..972698553 --- /dev/null +++ b/include/asm-generic/evl/poll.h @@ -0,0 +1,59 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _ASM_GENERIC_EVL_POLL_H +#define _ASM_GENERIC_EVL_POLL_H + +#ifdef CONFIG_EVL + +#include + +/* + * Poll operation descriptor for f_op->oob_poll. Can be attached + * concurrently to at most EVL_POLL_NR_CONNECTORS poll heads. + */ +#define EVL_POLL_NR_CONNECTORS 4 + +struct oob_poll_wait { + struct evl_poll_connector { + struct evl_poll_head *head; + struct list_head next; + void (*unwatch)(struct evl_poll_head *head); + int events_received; + int index; + } connectors[EVL_POLL_NR_CONNECTORS]; +}; + +struct oob_poll_queue { + struct evl_poll_head head; +}; + +static inline +void init_oob_poll_queue(struct oob_poll_queue *pwq) +{ + evl_init_poll_head(&pwq->head); +} + +#define poll_signal_oob(__pwq, __mask) \ + evl_signal_poll_events(&(__pwq)->head, __mask) + +#define poll_wait_oob(__pwq, __wait) \ + evl_poll_watch(&(__pwq)->head, __wait, NULL) + +#else + +struct oob_poll_wait { +}; + +struct oob_poll_queue { +}; + +static inline void init_oob_poll_queue(struct oob_poll_queue *pwq) { } + +#define poll_signal_oob(__pwq, __mask) \ + do { (void)(__pwq), (void)(__mask); } while (0) + +#define poll_wait_oob(__pwq, __wait) \ + do { (void)(__pwq), (void)(__wait); } while (0) + +#endif /* !CONFIG_EVL */ + +#endif /* !_ASM_GENERIC_EVL_POLL_H */ diff --git a/include/asm-generic/evl/thread_info.h b/include/asm-generic/evl/thread_info.h new file mode 100644 index 000000000..2aa2a697a --- /dev/null +++ b/include/asm-generic/evl/thread_info.h @@ -0,0 +1,30 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _ASM_GENERIC_EVL_THREAD_INFO_H +#define _ASM_GENERIC_EVL_THREAD_INFO_H + +#ifdef CONFIG_EVL + +struct evl_thread; +struct evl_subscriber; + +struct oob_thread_state { + struct evl_thread *thread; + struct evl_subscriber *subscriber; + int preempt_count; +}; + +static inline +void evl_init_thread_state(struct oob_thread_state *p) +{ + p->thread = NULL; + p->subscriber = NULL; + p->preempt_count = 0; +} + +#else + +struct oob_thread_state { }; + +#endif /* !CONFIG_EVL */ + +#endif /* !_ASM_GENERIC_EVL_THREAD_INFO_H */ diff --git a/include/asm-generic/irq_pipeline.h b/include/asm-generic/irq_pipeline.h new file mode 100644 index 000000000..096b4f6fd --- /dev/null +++ b/include/asm-generic/irq_pipeline.h @@ -0,0 +1,144 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2016 Philippe Gerum . + */ +#ifndef __ASM_GENERIC_IRQ_PIPELINE_H +#define __ASM_GENERIC_IRQ_PIPELINE_H + +#include +#include + +#ifdef CONFIG_IRQ_PIPELINE + +unsigned long inband_irq_save(void); +void inband_irq_restore(unsigned long flags); +void inband_irq_enable(void); +void inband_irq_disable(void); +int inband_irqs_disabled(void); + +#define hard_cond_local_irq_enable() hard_local_irq_enable() +#define hard_cond_local_irq_disable() hard_local_irq_disable() +#define hard_cond_local_irq_save() hard_local_irq_save() +#define hard_cond_local_irq_restore(__flags) hard_local_irq_restore(__flags) + +#define hard_local_irq_save() native_irq_save() +#define hard_local_irq_restore(__flags) native_irq_restore(__flags) +#define hard_local_irq_enable() native_irq_enable() +#define hard_local_irq_disable() native_irq_disable() +#define hard_local_save_flags() native_save_flags() + +#define hard_irqs_disabled() native_irqs_disabled() +#define hard_irqs_disabled_flags(__flags) native_irqs_disabled_flags(__flags) + +void irq_pipeline_nmi_enter(void); +void irq_pipeline_nmi_exit(void); + +/* Swap then merge virtual and hardware interrupt states. */ +#define irqs_merge_flags(__flags, __stalled) \ + ({ \ + unsigned long __combo = \ + arch_irqs_virtual_to_native_flags(__stalled) | \ + arch_irqs_native_to_virtual_flags(__flags); \ + __combo; \ + }) + +/* Extract swap virtual and hardware interrupt states. */ +#define irqs_split_flags(__combo, __stall_r) \ + ({ \ + unsigned long __virt = (__combo); \ + *(__stall_r) = hard_irqs_disabled_flags(__combo); \ + __virt &= ~arch_irqs_virtual_to_native_flags(*(__stall_r)); \ + arch_irqs_virtual_to_native_flags(__virt); \ + }) + +#define hard_local_irq_sync() native_irq_sync() + +bool stage_disabled(void); + +bool stage_disabled_flags(unsigned long irqstate, bool *stalled); + +unsigned long test_and_lock_stage(int *irqsoff); + +void unlock_stage(unsigned long irqstate); + +#define stage_save_flags(__irqstate) \ + do { \ + unsigned long __flags = hard_local_save_flags(); \ + (__irqstate) = irqs_merge_flags(__flags, \ + irqs_disabled()); \ + } while (0) + +#else /* !CONFIG_IRQ_PIPELINE */ + +#define hard_local_save_flags() ({ unsigned long __flags; \ + raw_local_save_flags(__flags); __flags; }) +#define hard_local_irq_enable() raw_local_irq_enable() +#define hard_local_irq_disable() raw_local_irq_disable() +#define hard_local_irq_save() ({ unsigned long __flags; \ + raw_local_irq_save(__flags); __flags; }) +#define hard_local_irq_restore(__flags) raw_local_irq_restore(__flags) + +#define hard_cond_local_irq_enable() do { } while(0) +#define hard_cond_local_irq_disable() do { } while(0) +#define hard_cond_local_irq_save() 0 +#define hard_cond_local_irq_restore(__flags) do { (void)(__flags); } while(0) + +#define hard_irqs_disabled() irqs_disabled() +#define hard_irqs_disabled_flags(__flags) raw_irqs_disabled_flags(__flags) + +static inline void irq_pipeline_nmi_enter(void) { } +static inline void irq_pipeline_nmi_exit(void) { } + +#define hard_local_irq_sync() do { } while (0) + +#define stage_disabled() irqs_disabled() + +#define stage_disabled_flags(__flags, __stalled) \ + ({ \ + (*__stalled) = irqs_disabled_flags(__flags); \ + (*__stalled); \ + }) + +#define test_and_lock_stage(__irqsoff) \ + ({ \ + unsigned long __flags; \ + raw_local_irq_save(__flags); \ + *(__irqsoff) = irqs_disabled_flags(__flags); \ + __flags; \ + }) + +#define unlock_stage(__flags) raw_local_irq_restore(__flags) + +#define stage_save_flags(__flags) raw_local_save_flags(__flags) + +#endif /* !CONFIG_IRQ_PIPELINE */ + +#ifdef CONFIG_DEBUG_IRQ_PIPELINE +void check_inband_stage(void); +#define check_hard_irqs_disabled() \ + WARN_ON_ONCE(!hard_irqs_disabled()) +#else +static inline void check_inband_stage(void) { } +static inline int check_hard_irqs_disabled(void) { return 0; } +#endif + +extern bool irq_pipeline_oopsing; + +static __always_inline bool irqs_pipelined(void) +{ + return IS_ENABLED(CONFIG_IRQ_PIPELINE); +} + +static __always_inline bool irq_pipeline_debug(void) +{ + return IS_ENABLED(CONFIG_DEBUG_IRQ_PIPELINE) && + !irq_pipeline_oopsing; +} + +static __always_inline bool irq_pipeline_debug_locking(void) +{ + return IS_ENABLED(CONFIG_DEBUG_HARD_LOCKS); +} + +#endif /* __ASM_GENERIC_IRQ_PIPELINE_H */ diff --git a/include/asm-generic/percpu.h b/include/asm-generic/percpu.h index 94cbd50cc..a6c5a6f45 100644 --- a/include/asm-generic/percpu.h +++ b/include/asm-generic/percpu.h @@ -133,9 +133,9 @@ do { \ ({ \ typeof(pcp) ___ret; \ unsigned long ___flags; \ - raw_local_irq_save(___flags); \ + ___flags = hard_local_irq_save(); \ ___ret = raw_cpu_generic_read(pcp); \ - raw_local_irq_restore(___flags); \ + hard_local_irq_restore(___flags); \ ___ret; \ }) @@ -152,9 +152,9 @@ do { \ #define this_cpu_generic_to_op(pcp, val, op) \ do { \ unsigned long __flags; \ - raw_local_irq_save(__flags); \ + __flags = hard_local_irq_save(); \ raw_cpu_generic_to_op(pcp, val, op); \ - raw_local_irq_restore(__flags); \ + hard_local_irq_restore(__flags); \ } while (0) @@ -162,9 +162,9 @@ do { \ ({ \ typeof(pcp) __ret; \ unsigned long __flags; \ - raw_local_irq_save(__flags); \ + __flags = hard_local_irq_save(); \ __ret = raw_cpu_generic_add_return(pcp, val); \ - raw_local_irq_restore(__flags); \ + hard_local_irq_restore(__flags); \ __ret; \ }) @@ -172,9 +172,9 @@ do { \ ({ \ typeof(pcp) __ret; \ unsigned long __flags; \ - raw_local_irq_save(__flags); \ + __flags = hard_local_irq_save(); \ __ret = raw_cpu_generic_xchg(pcp, nval); \ - raw_local_irq_restore(__flags); \ + hard_local_irq_restore(__flags); \ __ret; \ }) @@ -192,9 +192,9 @@ do { \ ({ \ typeof(pcp) __ret; \ unsigned long __flags; \ - raw_local_irq_save(__flags); \ + __flags = hard_local_irq_save(); \ __ret = raw_cpu_generic_cmpxchg(pcp, oval, nval); \ - raw_local_irq_restore(__flags); \ + hard_local_irq_restore(__flags); \ __ret; \ }) diff --git a/include/dovetail/irq.h b/include/dovetail/irq.h new file mode 100644 index 000000000..ac8b5310e --- /dev/null +++ b/include/dovetail/irq.h @@ -0,0 +1,11 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _DOVETAIL_IRQ_H +#define _DOVETAIL_IRQ_H + +/* Placeholders for pre- and post-IRQ handling. */ + +static inline void irq_enter_pipeline(void) { } + +static inline void irq_exit_pipeline(void) { } + +#endif /* !_DOVETAIL_IRQ_H */ diff --git a/include/dovetail/mm_info.h b/include/dovetail/mm_info.h new file mode 100644 index 000000000..504bd1d87 --- /dev/null +++ b/include/dovetail/mm_info.h @@ -0,0 +1,12 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _DOVETAIL_MM_INFO_H +#define _DOVETAIL_MM_INFO_H + +/* + * Placeholder for per-mm state information defined by the co-kernel. + */ + +struct oob_mm_state { +}; + +#endif /* !_DOVETAIL_MM_INFO_H */ diff --git a/include/dovetail/net.h b/include/dovetail/net.h new file mode 100644 index 000000000..c7ef00fb9 --- /dev/null +++ b/include/dovetail/net.h @@ -0,0 +1,17 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _DOVETAIL_NET_H +#define _DOVETAIL_NET_H + +/* + * Placeholder for a network descriptor extension otherwise defined by + * the out-of-band network stack. + */ +struct oob_net_state { +}; + +struct net; + +static inline void net_init_oob_state(struct net *net) { } +static inline void net_cleanup_oob_state(struct net *net) { } + +#endif /* !_DOVETAIL_NET_H */ diff --git a/include/dovetail/netdevice.h b/include/dovetail/netdevice.h new file mode 100644 index 000000000..2939e017b --- /dev/null +++ b/include/dovetail/netdevice.h @@ -0,0 +1,23 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _DOVETAIL_NETDEVICE_H +#define _DOVETAIL_NETDEVICE_H + +/* + * Placeholder for per-device state information otherwise defined by + * the out-of-band network stack. + */ +struct oob_netdev_state { +}; + +struct oob_netqueue_state { +}; + +static inline void netqueue_init_oob(struct oob_netqueue_state *qs) +{ +} + +static inline void netqueue_destroy_oob(struct oob_netqueue_state *qs) +{ +} + +#endif /* !_DOVETAIL_NETDEVICE_H */ diff --git a/include/dovetail/poll.h b/include/dovetail/poll.h new file mode 100644 index 000000000..d15b14f88 --- /dev/null +++ b/include/dovetail/poll.h @@ -0,0 +1,12 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _DOVETAIL_POLL_H +#define _DOVETAIL_POLL_H + +/* + * Placeholder for the out-of-band poll operation descriptor. + */ + +struct oob_poll_wait { +}; + +#endif /* !_DOVETAIL_POLL_H */ diff --git a/include/dovetail/spinlock.h b/include/dovetail/spinlock.h new file mode 100644 index 000000000..381031afd --- /dev/null +++ b/include/dovetail/spinlock.h @@ -0,0 +1,21 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _DOVETAIL_SPINLOCK_H +#define _DOVETAIL_SPINLOCK_H + +/* Placeholders for hard/hybrid spinlock modifiers. */ + +struct raw_spinlock; + +static inline void hard_spin_lock_prepare(struct raw_spinlock *lock) +{ } + +static inline void hard_spin_unlock_finish(struct raw_spinlock *lock) +{ } + +static inline void hard_spin_trylock_prepare(struct raw_spinlock *lock) +{ } + +static inline void hard_spin_trylock_fail(struct raw_spinlock *lock) +{ } + +#endif /* !_DOVETAIL_SPINLOCK_H */ diff --git a/include/dovetail/thread_info.h b/include/dovetail/thread_info.h new file mode 100644 index 000000000..4dea8bf1e --- /dev/null +++ b/include/dovetail/thread_info.h @@ -0,0 +1,13 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _DOVETAIL_THREAD_INFO_H +#define _DOVETAIL_THREAD_INFO_H + +/* + * Placeholder for per-thread state information defined by the + * co-kernel. + */ + +struct oob_thread_state { +}; + +#endif /* !_DOVETAIL_THREAD_INFO_H */ diff --git a/include/evl/assert.h b/include/evl/assert.h new file mode 100644 index 000000000..d20d09b01 --- /dev/null +++ b/include/evl/assert.h @@ -0,0 +1,52 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Derived from Xenomai Cobalt, https://xenomai.org/ + * Copyright (C) 2006, 2018 Philippe Gerum + */ + +#ifndef _EVL_ASSERT_H +#define _EVL_ASSERT_H + +#include +#include + +#define EVL_INFO KERN_INFO "EVL: " +#define EVL_WARNING KERN_WARNING "EVL: " +#define EVL_ERR KERN_ERR "EVL: " + +#define EVL_DEBUG(__subsys) \ + IS_ENABLED(CONFIG_EVL_DEBUG_##__subsys) +#define EVL_ASSERT(__subsys, __cond) \ + (!WARN_ON(EVL_DEBUG(__subsys) && !(__cond))) +#define EVL_WARN(__subsys, __cond, __fmt...) \ + WARN(EVL_DEBUG(__subsys) && (__cond), __fmt) +#define EVL_WARN_ON(__subsys, __cond) \ + WARN_ON(EVL_DEBUG(__subsys) && (__cond)) +#define EVL_WARN_ON_ONCE(__subsys, __cond) \ + WARN_ON_ONCE(EVL_DEBUG(__subsys) && (__cond)) +#ifdef CONFIG_SMP +#define EVL_WARN_ON_SMP(__subsys, __cond) \ + EVL_WARN_ON(__subsys, __cond) +#else +#define EVL_WARN_ON_SMP(__subsys, __cond) 0 +#endif + +#define oob_context_only() EVL_WARN_ON_ONCE(CORE, running_inband()) +#define inband_context_only() EVL_WARN_ON_ONCE(CORE, !running_inband()) +#ifdef CONFIG_SMP +#define assert_hard_lock(__lock) EVL_WARN_ON_ONCE(CORE, \ + !(raw_spin_is_locked(__lock) && hard_irqs_disabled())) +#define assert_evl_lock(__lock) assert_hard_lock(&(__lock)->_lock) +#else +#define assert_hard_lock(__lock) EVL_WARN_ON_ONCE(CORE, !hard_irqs_disabled()) +#define assert_evl_lock(__lock) assert_hard_lock(&(__lock)->_lock) +#endif + +#define assert_thread_pinned(__thread) \ + do { \ + assert_hard_lock(&(__thread)->lock); \ + assert_hard_lock(&(__thread)->rq->lock);\ + } while (0) + +#endif /* !_EVL_ASSERT_H */ diff --git a/include/evl/cache.h b/include/evl/cache.h new file mode 100644 index 000000000..846503eb6 --- /dev/null +++ b/include/evl/cache.h @@ -0,0 +1,111 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2023 Philippe Gerum + * + * A dynamically-growable cache with support for in-band update and + * out-of-band lookup. + */ + +#ifndef _EVL_CACHE_H +#define _EVL_CACHE_H + +#include +#include +#include +#include + +struct evl_cache; + +/* Cacheable entry. */ +struct evl_cache_entry { + /* Out-of-band reference count. */ + refcount_t refcnt; + /* Link in hash table. */ + struct evl_cache_entry __rcu *next; + /* Holder for work trampoline to RCU. */ + struct evl_work work; + /* Owner cache. */ + struct evl_cache *cache; + /* RCU holder for release. */ + struct rcu_head rcu; +}; + +/* Client-specific operations. */ +struct evl_cache_ops { + u32 (*hash)(const void *key); + bool (*eq)(const struct evl_cache_entry *entry, const void *key); + void (*drop)(struct evl_cache_entry *entry); + const void *(*get_key)(const struct evl_cache_entry *entry); + char *(*format_key)(const struct evl_cache_entry *entry); +}; + +/* Dynamic hash table indexing entries. */ +struct evl_hash_table { + /* RCU-managed bucket array. */ + struct evl_cache_entry __rcu **buckets; + /* Size order for bucket array. */ + unsigned int shift; + /* Number of busy entries. */ + int nr_entries; + /* RCU holder for release. */ + struct rcu_head rcu; +}; + +/* Generic cache. */ +struct evl_cache { + /* Client-specific operation descriptor. */ + struct evl_cache_ops *ops; + /* For serializing updates (in-band only). */ + spinlock_t lock; + /* Hash table of entries. */ + struct evl_hash_table __rcu *hash_table; + /* Initial cache shift. */ + size_t init_shift; + /* Name of cache. */ + const char *name; +}; + +int evl_init_cache(struct evl_cache *cache); + +void evl_cleanup_cache(struct evl_cache *cache); + +int evl_add_cache_entry(struct evl_cache *cache, + struct evl_cache_entry *entry); + +int evl_add_cache_entry_locked(struct evl_cache *cache, + struct evl_cache_entry *entry); + +void evl_del_cache_entry(struct evl_cache *cache, + const void *key); + +void evl_del_cache_entry_locked(struct evl_cache *cache, + const void *key); + +struct evl_cache_entry *evl_lookup_cache(struct evl_cache *cache, + const void *key); + +static inline void evl_get_cache_entry(struct evl_cache_entry *entry) +{ + refcount_inc(&entry->refcnt); +} + +void evl_put_cache_entry(struct evl_cache_entry *entry); + +void evl_clean_cache(struct evl_cache *cache, + bool (*testfn)(struct evl_cache_entry *e, void *arg), + void *arg); + +void evl_flush_cache(struct evl_cache *cache); + +static inline void evl_lock_cache(struct evl_cache *cache) +{ + spin_lock_bh(&cache->lock); +} + +static inline void evl_unlock_cache(struct evl_cache *cache) +{ + spin_unlock_bh(&cache->lock); +} + +#endif /* !_EVL_CACHE_H */ diff --git a/include/evl/clock.h b/include/evl/clock.h new file mode 100644 index 000000000..cb1bbf2cc --- /dev/null +++ b/include/evl/clock.h @@ -0,0 +1,218 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Derived from Xenomai Cobalt, https://xenomai.org/ + * Copyright (C) 2006, 2018 Philippe Gerum + */ + +#ifndef _EVL_CLOCK_H +#define _EVL_CLOCK_H + +#include +#include +#include +#include +#include +#include +#include +#include + +#define ONE_BILLION 1000000000 + +struct evl_rq; +struct evl_timerbase; +struct clock_event_device; +struct __kernel_timex; + +struct evl_clock_gravity { + ktime_t irq; + ktime_t kernel; + ktime_t user; +}; + +struct evl_clock { + ktime_t resolution; + struct evl_clock_gravity gravity; + const char *name; + int flags; + struct { + ktime_t (*read)(struct evl_clock *clock); + u64 (*read_cycles)(struct evl_clock *clock); + int (*set)(struct evl_clock *clock, ktime_t date); + void (*program_local_shot)(struct evl_clock *clock); + void (*program_remote_shot)(struct evl_clock *clock, + struct evl_rq *rq); + int (*set_gravity)(struct evl_clock *clock, + const struct evl_clock_gravity *p); + void (*reset_gravity)(struct evl_clock *clock); + void (*adjust)(struct evl_clock *clock); + } ops; + struct evl_timerbase *timerdata; + struct evl_clock *master; + ktime_t offset; /* from master clock. */ +#ifdef CONFIG_SMP + struct cpumask affinity; /* which CPU this clock beats on. */ +#endif + struct list_head next; + struct evl_element element; + void (*dispose)(struct evl_clock *clock); +} ____cacheline_aligned; + +extern struct evl_clock evl_mono_clock; + +extern struct evl_clock evl_realtime_clock; + +int evl_init_clock(struct evl_clock *clock, + const struct cpumask *affinity); + +int evl_init_slave_clock(struct evl_clock *clock, + struct evl_clock *master); + +void evl_core_tick(struct clock_event_device *dummy); + +void evl_announce_tick(struct evl_clock *clock); + +void evl_adjust_timers(struct evl_clock *clock, + ktime_t delta); + +void evl_stop_timers(struct evl_clock *clock); + +static inline u64 evl_read_clock_cycles(struct evl_clock *clock) +{ + return clock->ops.read_cycles(clock); +} + +static ktime_t evl_ktime_monotonic(void) +{ + return ktime_get_mono_fast_ns(); +} + +static inline ktime_t evl_read_clock(struct evl_clock *clock) +{ + /* + * In many occasions on the fast path, evl_read_clock() is + * explicitly called with &evl_mono_clock which resolves as + * a constant. Skip the clock trampoline handler, branching + * immediately to the final code for such clock. + */ + if (clock == &evl_mono_clock) + return evl_ktime_monotonic(); + + return clock->ops.read(clock); +} + +static inline int +evl_set_clock_time(struct evl_clock *clock, ktime_t date) +{ + if (clock->ops.set) + return clock->ops.set(clock, date); + + return -EOPNOTSUPP; +} + +static inline +ktime_t evl_get_clock_resolution(struct evl_clock *clock) +{ + return clock->resolution; +} + +static inline +void evl_set_clock_resolution(struct evl_clock *clock, + ktime_t resolution) +{ + clock->resolution = resolution; +} + +static inline +int evl_set_clock_gravity(struct evl_clock *clock, + const struct evl_clock_gravity *gravity) +{ + if (clock->ops.set_gravity) + return clock->ops.set_gravity(clock, gravity); + + return -EOPNOTSUPP; +} + +static inline void evl_reset_clock_gravity(struct evl_clock *clock) +{ + if (clock->ops.reset_gravity) + clock->ops.reset_gravity(clock); +} + +#define evl_get_clock_gravity(__clock, __type) ((__clock)->gravity.__type) + +int evl_clock_init(void); + +void evl_clock_cleanup(void); + +int evl_register_clock(struct evl_clock *clock, + const struct cpumask *affinity); + +void evl_unregister_clock(struct evl_clock *clock); + +struct evl_clock *evl_get_clock_by_fd(int efd); + +static inline void evl_put_clock(struct evl_clock *clock) +{ + evl_put_element(&clock->element); +} + +static inline ktime_t +u_timespec_to_ktime(const struct __evl_timespec u_ts) +{ + struct timespec64 ts64 = (struct timespec64){ + .tv_sec = u_ts.tv_sec, + .tv_nsec = u_ts.tv_nsec, + }; + + return timespec64_to_ktime(ts64); +} + +static inline struct __evl_timespec +ktime_to_u_timespec(ktime_t t) +{ + struct timespec64 ts64 = ktime_to_timespec64(t); + + return (struct __evl_timespec){ + .tv_sec = ts64.tv_sec, + .tv_nsec = ts64.tv_nsec, + }; +} + +static inline struct timespec64 +u_timespec_to_timespec64(const struct __evl_timespec u_ts) +{ + return (struct timespec64){ + .tv_sec = u_ts.tv_sec, + .tv_nsec = u_ts.tv_nsec, + }; +} + +static inline struct __evl_timespec +timespec64_to_u_timespec(const struct timespec64 ts64) +{ + return (struct __evl_timespec){ + .tv_sec = ts64.tv_sec, + .tv_nsec = ts64.tv_nsec, + }; +} + +static inline struct itimerspec64 +u_itimerspec_to_itimerspec64(const struct __evl_itimerspec u_its) +{ + return (struct itimerspec64){ + .it_value = u_timespec_to_timespec64(u_its.it_value), + .it_interval = u_timespec_to_timespec64(u_its.it_interval), + }; +} + +static inline struct __evl_itimerspec +itimerspec64_to_u_itimerspec(const struct itimerspec64 its64) +{ + return (struct __evl_itimerspec){ + .it_value = timespec64_to_u_timespec(its64.it_value), + .it_interval = timespec64_to_u_timespec(its64.it_interval), + }; +} + +#endif /* !_EVL_CLOCK_H */ diff --git a/include/evl/control.h b/include/evl/control.h new file mode 100644 index 000000000..dcc90775f --- /dev/null +++ b/include/evl/control.h @@ -0,0 +1,60 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2018 Philippe Gerum + */ + +#ifndef _EVL_CONTROL_H +#define _EVL_CONTROL_H + +#include +#include +#include +#include +#include + +enum evl_run_states { + EVL_STATE_DISABLED, + EVL_STATE_RUNNING, + EVL_STATE_STOPPED, + EVL_STATE_TEARDOWN, + EVL_STATE_WARMUP, +}; + +extern atomic_t evl_runstate; + +static inline enum evl_run_states get_evl_state(void) +{ + return atomic_read(&evl_runstate); +} + +static inline int evl_is_warming(void) +{ + return get_evl_state() == EVL_STATE_WARMUP; +} + +static inline int evl_is_running(void) +{ + return get_evl_state() == EVL_STATE_RUNNING; +} + +static inline int evl_is_enabled(void) +{ + return get_evl_state() != EVL_STATE_DISABLED; +} + +static inline int evl_is_stopped(void) +{ + return get_evl_state() == EVL_STATE_STOPPED; +} + +static inline void set_evl_state(enum evl_run_states state) +{ + atomic_set(&evl_runstate, state); +} + +void evl_add_state_chain(struct notifier_block *nb); + +void evl_remove_state_chain(struct notifier_block *nb); + +#endif /* !_EVL_CONTROL_H */ diff --git a/include/evl/crossing.h b/include/evl/crossing.h new file mode 100644 index 000000000..12dce869c --- /dev/null +++ b/include/evl/crossing.h @@ -0,0 +1,74 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2020 Philippe Gerum + */ + +#ifndef _EVL_CROSSING_H +#define _EVL_CROSSING_H + +#include +#include +#include + +/* + * This is a simple synchronization mechanism allowing an in-band + * caller to pass a point in the code making sure that no out-of-band + * operations which might traverse the same crossing are in + * flight. The protection works once, after which the crossing must be + * reinitialized. + * + * Out-of-band callers delimit the danger zone by down-ing and up-ing + * the barrier at the crossing, the in-band code should ask for + * passing the crossing. + * + * CAUTION: the caller must guarantee that evl_down_crossing() cannot + * be invoked _after_ evl_pass_crossing() is entered for a given + * crossing. + */ + +struct evl_crossing { + atomic_t oob_refs; + struct completion oob_done; + struct irq_work oob_work; +}; + +static inline void evl_open_crossing(struct irq_work *work) +{ + struct evl_crossing *c = container_of(work, struct evl_crossing, oob_work); + complete(&c->oob_done); +} + +static inline void evl_init_crossing(struct evl_crossing *c) +{ + atomic_set(&c->oob_refs, 1); + init_completion(&c->oob_done); + init_irq_work(&c->oob_work, evl_open_crossing); +} + +static inline void evl_reinit_crossing(struct evl_crossing *c) +{ + atomic_set(&c->oob_refs, 1); + reinit_completion(&c->oob_done); +} + +static inline void evl_down_crossing(struct evl_crossing *c) +{ + atomic_inc(&c->oob_refs); +} + +static inline void evl_up_crossing(struct evl_crossing *c) +{ + /* CAUTION: See word of caution in the initial comment. */ + + if (atomic_dec_return(&c->oob_refs) == 0) + irq_work_queue(&c->oob_work); +} + +static inline void evl_pass_crossing(struct evl_crossing *c) +{ + if (atomic_dec_return(&c->oob_refs) > 0) + wait_for_completion(&c->oob_done); +} + +#endif /* !_EVL_CROSSING_H */ diff --git a/include/evl/device.h b/include/evl/device.h new file mode 100644 index 000000000..6c0478293 --- /dev/null +++ b/include/evl/device.h @@ -0,0 +1,34 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2019 Philippe Gerum + */ + +#ifndef _EVL_DEVICE_H +#define _EVL_DEVICE_H + +#ifdef CONFIG_EVL + +#include +#include +#include +#include +#include +#include +#include + +#else /* !CONFIG_EVL */ + +struct evl_file { }; + +#define evl_open_file(__efilp, __filp) ({ 0; }) +#define evl_release_file(__efilp) do { } while (0) + +#endif /* !CONFIG_EVL */ + +static inline bool evl_enabled(void) +{ + return IS_ENABLED(CONFIG_EVL); +} + +#endif /* !_EVL_DEVICE_H */ diff --git a/include/evl/devices/gpio.h b/include/evl/devices/gpio.h new file mode 100644 index 000000000..06d03464f --- /dev/null +++ b/include/evl/devices/gpio.h @@ -0,0 +1,38 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2019 Philippe Gerum + */ + +#ifndef _EVL_DEVICES_GPIO_H +#define _EVL_DEVICES_GPIO_H + +#include +#include + +#ifdef CONFIG_EVL + +#include +#include +#include + +struct lineevent_oob_state { + struct evl_file efile; + struct evl_poll_head poll_head; + struct evl_wait_queue wait; + hard_spinlock_t lock; +}; + +#else + +struct lineevent_oob_state { + struct evl_file efile; +}; + +#endif + +struct linehandle_oob_state { + struct evl_file efile; +}; + +#endif /* !_EVL_DEVICES_GPIO_H */ diff --git a/include/evl/factory.h b/include/evl/factory.h new file mode 100644 index 000000000..14ace1510 --- /dev/null +++ b/include/evl/factory.h @@ -0,0 +1,239 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2018 Philippe Gerum + */ + +#ifndef _EVL_FACTORY_H +#define _EVL_FACTORY_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define element_of(__filp, __type) \ + ({ \ + struct evl_file_binding *__fbind = (__filp)->private_data; \ + container_of(__fbind->element, __type, element); \ + }) + +#define fundle_of(__obj) ((__obj)->element.fundle) + +struct evl_element; + +#define EVL_FACTORY_CLONE BIT(0) +#define EVL_FACTORY_SINGLE BIT(1) + +#define EVL_DEVHASH_BITS 8 + +struct evl_index { + struct rb_root root; + hard_spinlock_t lock; + fundle_t generator; +}; + +struct evl_factory { + const char *name; + const struct file_operations *fops; + unsigned int nrdev; + struct evl_element *(*build)(struct evl_factory *fac, + const char __user *u_name, + void __user *u_attrs, + int clone_flags, + u32 *state_offp); + void (*dispose)(struct evl_element *e); + const struct attribute_group **attrs; + int flags; + struct { + struct device_type type; + struct class *class; + struct cdev cdev; + struct device *dev; + dev_t sub_rdev; + kuid_t kuid; + kgid_t kgid; + unsigned long *minor_map; + struct evl_index index; + DECLARE_HASHTABLE(name_hash, EVL_DEVHASH_BITS); + struct mutex hash_lock; + }; /* Internal. */ +}; + +struct evl_element { + struct rcu_head rcu; + struct evl_factory *factory; + struct cdev cdev; + struct device *dev; + struct filename *devname; + unsigned int minor; + refcount_t refs; + fundle_t fundle; + int clone_flags; + struct rb_node index_node; + struct irq_work irq_work; + struct list_head flush; + struct hlist_node hash; + struct { + struct file *filp; + int efd; + } fpriv; +}; + +static inline const char * +evl_element_name(struct evl_element *e) +{ + if (e->devname) + return e->devname->name; + + return NULL; +} + +int evl_init_element(struct evl_element *e, + struct evl_factory *fac, + int clone_flags); + +int evl_init_user_element(struct evl_element *e, + struct evl_factory *fac, + const char __user *u_name, + int clone_flags); + +void evl_destroy_element(struct evl_element *e); + +static inline bool __evl_get_element(struct evl_element *e) +{ + return refcount_inc_not_zero(&e->refs); +} + +static inline void evl_get_element(struct evl_element *e) +{ + bool ret = !__evl_get_element(e); + EVL_WARN_ON(CORE, ret); +} + +struct evl_element * +__evl_get_element_by_fundle(struct evl_index *map, + fundle_t fundle); + +#define evl_get_element_by_fundle(__map, __fundle, __type) \ + ({ \ + struct evl_element *__e; \ + __e = __evl_get_element_by_fundle(__map, __fundle); \ + __e ? container_of(__e, __type, element) : NULL; \ + }) + +#define evl_get_factory_element_by_fundle(__fac, __fundle, __type) \ + ({ \ + struct evl_index *__map = &(__fac)->index; \ + evl_get_element_by_fundle(__map, __fundle, __type); \ + }) + +/* + * An element can be disposed of only after the device backing it is + * removed. If @dev is valid, so is @e at the time of the call. + */ +#define evl_get_element_by_dev(__dev, __type) \ + ({ \ + struct evl_element *__e = dev_get_drvdata(__dev); \ + __e ? ({ evl_get_element(__e); \ + container_of(__e, __type, element); }) : NULL; \ + }) + +/* Hide the element from sysfs operations. */ +static inline void evl_hide_element(struct evl_element *e) +{ + struct device *dev = e->dev; + if (dev) + dev_set_drvdata(dev, NULL); +} + +static inline bool evl_element_is_public(struct evl_element *e) +{ + return !!(e->clone_flags & EVL_CLONE_PUBLIC); +} + +static inline bool evl_element_has_coredev(struct evl_element *e) +{ + return !!(e->clone_flags & EVL_CLONE_COREDEV); +} + +static inline bool evl_element_is_observable(struct evl_element *e) +{ + return !!(e->clone_flags & EVL_CLONE_OBSERVABLE); +} + +void __evl_put_element(struct evl_element *e); + +static inline void evl_put_element(struct evl_element *e) /* in-band or OOB */ +{ + if (refcount_dec_and_test(&e->refs)) + __evl_put_element(e); +} + +int evl_open_element(struct inode *inode, + struct file *filp); + +int evl_release_element(struct inode *inode, + struct file *filp); + +int evl_create_core_element_device(struct evl_element *e, + struct evl_factory *fac, + const char *name); + +void evl_remove_element_device(struct evl_element *e); + +void evl_index_element(struct evl_index *map, + struct evl_element *e); + +static inline void evl_index_factory_element(struct evl_element *e) +{ + evl_index_element(&e->factory->index, e); +} + +void evl_unindex_element(struct evl_index *map, + struct evl_element *e); + +static inline void evl_unindex_factory_element(struct evl_element *e) +{ + evl_unindex_element(&e->factory->index, e); +} + +int evl_create_factory(struct evl_factory *fac, dev_t rdev); + +void evl_delete_factory(struct evl_factory *fac); + +bool evl_may_access_factory(struct evl_factory *fac); + +int evl_early_init_factories(void); + +void evl_early_cleanup_factories(void); + +int evl_late_init_factories(void); + +void evl_late_cleanup_factories(void); + +extern struct evl_factory evl_clock_factory; +extern struct evl_factory evl_control_factory; +extern struct evl_factory evl_monitor_factory; +extern struct evl_factory evl_poll_factory; +extern struct evl_factory evl_thread_factory; +extern struct evl_factory evl_trace_factory; +extern struct evl_factory evl_xbuf_factory; +extern struct evl_factory evl_proxy_factory; +extern struct evl_factory evl_observable_factory; +extern struct evl_factory evl_rng_factory; +extern struct evl_factory evl_net_factory; + +#endif /* !_EVL_FACTORY_H */ diff --git a/include/evl/file.h b/include/evl/file.h new file mode 100644 index 000000000..630a20182 --- /dev/null +++ b/include/evl/file.h @@ -0,0 +1,65 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2018 Philippe Gerum + */ + +#ifndef _EVL_FILE_H +#define _EVL_FILE_H + +#include +#include +#include + +struct file; +struct files_struct; +struct evl_element; +struct evl_poll_node; + +struct evl_file { + struct file *filp; + struct evl_crossing crossing; +}; + +struct evl_fd { + unsigned int fd; + struct evl_file *efilp; + struct files_struct *files; + struct rb_node rb; + struct list_head poll_nodes; /* poll_item->node */ +}; + +struct evl_file_binding { + struct evl_file efile; + struct evl_element *element; +}; + +int evl_open_file(struct evl_file *efilp, + struct file *filp); + +void evl_release_file(struct evl_file *efilp); + +static inline +void evl_get_fileref(struct evl_file *efilp) +{ + evl_down_crossing(&efilp->crossing); +} + +struct evl_file *evl_get_file(unsigned int fd); + +static inline +void evl_put_file(struct evl_file *efilp) /* oob */ +{ + evl_up_crossing(&efilp->crossing); +} + +struct evl_file *evl_watch_fd(unsigned int fd, + struct evl_poll_node *node); + +void evl_ignore_fd(struct evl_poll_node *node); + +int evl_init_files(void); + +void evl_cleanup_files(void); + +#endif /* !_EVL_FILE_H */ diff --git a/include/evl/flag.h b/include/evl/flag.h new file mode 100644 index 000000000..a652b4681 --- /dev/null +++ b/include/evl/flag.h @@ -0,0 +1,148 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2017 Philippe Gerum + */ + +#ifndef _EVL_FLAG_H +#define _EVL_FLAG_H + +#include +#include + +struct evl_flag { + struct evl_wait_queue wait; + bool raised; +}; + +#define EVL_FLAG_INITIALIZER(__name) { \ + .wait = EVL_WAIT_INITIALIZER((__name).wait), \ + .raised = false, \ + } + +#define DEFINE_EVL_FLAG(__name) \ + struct evl_flag __name = EVL_FLAG_INITIALIZER(__name) + +static inline void evl_init_flag(struct evl_flag *wf) +{ + evl_init_wait(&wf->wait, &evl_mono_clock, EVL_WAIT_PRIO); + wf->raised = false; +} + +static inline void evl_init_flag_on_stack(struct evl_flag *wf) +{ + evl_init_wait_on_stack(&wf->wait, &evl_mono_clock, EVL_WAIT_PRIO); + wf->raised = false; +} + +static inline void evl_destroy_flag(struct evl_flag *wf) +{ + evl_destroy_wait(&wf->wait); +} + +static inline bool evl_peek_flag(struct evl_flag *wf) +{ + smp_wmb(); + return wf->raised; +} + +static inline bool evl_read_flag(struct evl_flag *wf) +{ + if (wf->raised) { + wf->raised = false; + return true; + } + + return false; +} + +#define evl_lock_flag(__wf, __flags) \ + raw_spin_lock_irqsave(&(__wf)->wait.wchan.lock, __flags) + +#define evl_unlock_flag(__wf, __flags) \ + raw_spin_unlock_irqrestore(&(__wf)->wait.wchan.lock, __flags) + +static inline +int evl_wait_flag_timeout(struct evl_flag *wf, + ktime_t timeout, enum evl_tmode timeout_mode) +{ + return evl_wait_event_timeout(&wf->wait, timeout, + timeout_mode, evl_read_flag(wf)); +} + +static inline int evl_wait_flag(struct evl_flag *wf) +{ + return evl_wait_flag_timeout(wf, EVL_INFINITE, EVL_REL); +} + +/* wf->wait.wchan.lock held, irqs off */ +static inline struct evl_thread *evl_wait_flag_head(struct evl_flag *wf) +{ + return evl_wait_head(&wf->wait); +} + +/* wf->wait.wchan.lock held, irqs off */ +static inline void evl_raise_flag_locked(struct evl_flag *wf) +{ + wf->raised = true; + evl_flush_wait_locked(&wf->wait, 0); +} + +static inline void evl_raise_flag_nosched(struct evl_flag *wf) +{ + unsigned long flags; + + evl_lock_flag(wf, flags); + evl_raise_flag_locked(wf); + evl_unlock_flag(wf, flags); +} + +static inline void evl_raise_flag(struct evl_flag *wf) +{ + evl_raise_flag_nosched(wf); + evl_schedule(); +} + +/* wf->wait.wchan.lock held, irqs off */ +static inline void evl_flush_flag_locked(struct evl_flag *wf, int reason) +{ + evl_flush_wait_locked(&wf->wait, reason); +} + +static inline void evl_flush_flag_nosched(struct evl_flag *wf, int reason) +{ + unsigned long flags; + + evl_lock_flag(wf, flags); + evl_flush_flag_locked(wf, reason); + evl_unlock_flag(wf, flags); +} + +static inline void evl_flush_flag(struct evl_flag *wf, int reason) +{ + evl_flush_flag_nosched(wf, reason); + evl_schedule(); +} + +/* wf->wait.wchan.lock held, irqs off */ +static inline void evl_pulse_flag_locked(struct evl_flag *wf) +{ + evl_flush_flag_locked(wf, EVL_T_BCAST); +} + +static inline void evl_pulse_flag_nosched(struct evl_flag *wf) +{ + evl_flush_flag_nosched(wf, EVL_T_BCAST); +} + +static inline void evl_pulse_flag(struct evl_flag *wf) +{ + evl_flush_flag(wf, EVL_T_BCAST); +} + +static inline void evl_clear_flag(struct evl_flag *wf) +{ + wf->raised = false; +} + +#endif /* _EVL_FLAG_H */ diff --git a/include/evl/init.h b/include/evl/init.h new file mode 100644 index 000000000..b588c58b8 --- /dev/null +++ b/include/evl/init.h @@ -0,0 +1,34 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2018 Philippe Gerum + */ + +#ifndef _EVL_INIT_H +#define _EVL_INIT_H + +#include + +struct evl_machine_cpudata { +}; + +DECLARE_PER_CPU(struct evl_machine_cpudata, evl_machine_cpudata); + +extern struct cpumask evl_oob_cpus; + +#ifdef CONFIG_EVL_DEBUG +void evl_warn_init(const char *fn, int level, int status); +#else +static inline void evl_warn_init(const char *fn, int level, int status) +{ } +#endif + +#define EVL_INIT_CALL(__level, __call) \ + ({ \ + int __ret = __call; \ + if (__ret) \ + evl_warn_init(#__call, __level, __ret); \ + __ret; \ + }) + +#endif /* !_EVL_INIT_H_ */ diff --git a/include/evl/irq.h b/include/evl/irq.h new file mode 100644 index 000000000..babee3738 --- /dev/null +++ b/include/evl/irq.h @@ -0,0 +1,38 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2017 Philippe Gerum + */ + +#ifndef _EVL_IRQ_H +#define _EVL_IRQ_H + +#include + +/* hard irqs off. */ +static inline void evl_enter_irq(void) +{ + struct evl_rq *rq = this_evl_rq(); + + rq->local_flags |= RQ_IRQ; +} + +/* hard irqs off. */ +static inline void evl_exit_irq(void) +{ + struct evl_rq *this_rq = this_evl_rq(); + + this_rq->local_flags &= ~RQ_IRQ; + + /* + * CAUTION: Switching stages as a result of rescheduling may + * re-enable irqs, shut them off before returning if so. + */ + if ((this_rq->flags|this_rq->local_flags) & RQ_SCHED) { + evl_schedule(); + if (!hard_irqs_disabled()) + hard_local_irq_disable(); + } +} + +#endif /* !_EVL_IRQ_H */ diff --git a/include/evl/list.h b/include/evl/list.h new file mode 100644 index 000000000..85fa2f79b --- /dev/null +++ b/include/evl/list.h @@ -0,0 +1,49 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Derived from Xenomai Cobalt, https://xenomai.org/ + * Copyright (C) 2013, 2018 Philippe Gerum + */ + +#ifndef _EVL_LIST_H +#define _EVL_LIST_H + +#include + +#define __list_add_pri(__new, __head, __member_pri, __member_next, __relop) \ +do { \ + typeof(*__new) *__pos; \ + if (list_empty(__head)) \ + list_add(&(__new)->__member_next, __head); \ + else { \ + list_for_each_entry_reverse(__pos, __head, __member_next) { \ + if ((__new)->__member_pri __relop __pos->__member_pri) \ + break; \ + } \ + list_add(&(__new)->__member_next, &__pos->__member_next); \ + } \ +} while (0) + +#define list_add_priff(__new, __head, __member_pri, __member_next) \ + __list_add_pri(__new, __head, __member_pri, __member_next, <=) + +#define list_add_prilf(__new, __head, __member_pri, __member_next) \ + __list_add_pri(__new, __head, __member_pri, __member_next, <) + +#define list_get_entry(__head, __type, __member) \ + ({ \ + __type *__item; \ + __item = list_first_entry(__head, __type, __member); \ + list_del(&__item->__member); \ + __item; \ + }) + +#define list_get_entry_init(__head, __type, __member) \ + ({ \ + __type *__item; \ + __item = list_first_entry(__head, __type, __member); \ + list_del_init(&__item->__member); \ + __item; \ + }) + +#endif /* !_EVL_LIST_H_ */ diff --git a/include/evl/lock.h b/include/evl/lock.h new file mode 100644 index 000000000..8aef7ea7f --- /dev/null +++ b/include/evl/lock.h @@ -0,0 +1,173 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2019 Philippe Gerum + */ +#ifndef _EVL_LOCK_H +#define _EVL_LOCK_H + +#include + +#ifdef CONFIG_LOCKDEP +/* + * might_hard_lock() forces immediate lock class registration from the + * current stage. Keep the lock->unlock sequence safe from preemption + * from any stage by disabling hard irqs, so that lockdep cannot + * observe invalid chains. + */ +#define might_hard_lock(__lock) \ + do { \ + unsigned long __flags; \ + local_irq_save_full(__flags); \ + rcu_read_lock(); \ + might_lock(__lock); \ + rcu_read_unlock(); \ + local_irq_restore_full(__flags); \ + } while (0) +#else +#define might_hard_lock(__lock) \ + do { } while (0) +#endif + +/* + * A (hard) spinlock API which also deals with thread preemption + * disabling in the EVL core. Such spinlock may be useful when only + * EVL threads running out-of-band can contend for the lock, to the + * exclusion of out-of-band IRQ handlers. In this case, disabling + * preemption before attempting to grab the lock may be substituted to + * disabling hard irqs. + * + * In other words, if you can guarantee that lock X can only be taken + * from out-of-band EVL thread contexts, then the two locking forms + * below would guard the section safely, without the extra cost of + * masking out-of-band IRQs in the second form: + * + * hard_spinlock_t X; + * ... + * unsigned long flags; + * raw_spin_lock_irqsave(&X, flags); + * (guarded section) + * raw_spin_unlock_irqrestore(&X, flags); + * + * ------------------------------------------------ + * + * evl_spinlock_t X; + * ... + * evl_spin_lock(&X); -- disables preemption + * (guarded section) + * evl_spin_unlock(&X); -- enables preemption, may resched + * + * In this case, picking the right type of lock is a matter of + * trade-off between interrupt latency and scheduling latency, + * depending on how time-critical it is for some IRQ handler to + * execute despite any request for rescheduling the latter might issue + * would have to wait until the lock is dropped by the interrupted + * thread eventually. + * + * Since an EVL spinlock is a hard lock at its core, you may also use + * it to serialize access to data from the in-band context. However, + * because such code would also be subject to preemption by the + * in-band scheduler which might impose a severe priority inversion on + * out-of-band threads spinning on the same lock from other CPU(s), + * any attempt to grab an EVL lock from the in-band stage without + * stalling such stage or disabling hard irqs is considered a bug. + * + * Just like the in-band preempt_count(), the EVL preemption count + * which guards against unwanted rescheduling from the core allows + * evl_spinlock_t locks to be nested safely. + */ + +typedef struct evl_spinlock { + hard_spinlock_t _lock; +} evl_spinlock_t; + +#define __EVL_SPIN_LOCK_INITIALIZER(__lock) { \ + ._lock = __HARD_SPIN_LOCK_INITIALIZER((__lock)._lock), \ + } + +#define DEFINE_EVL_SPINLOCK(__lock) \ + evl_spinlock_t __lock = __EVL_SPIN_LOCK_INITIALIZER(__lock) + +#define evl_spin_lock_init(__lock) \ + raw_spin_lock_init(&(__lock)->_lock) + +#define __evl_spin_lock(__lock) \ + do { \ + evl_disable_preempt(); \ + raw_spin_lock(&(__lock)->_lock); \ + } while (0) + +#define __evl_spin_lock_nested(__lock, __subclass) \ + do { \ + evl_disable_preempt(); \ + raw_spin_lock_nested(&(__lock)->_lock, __subclass); \ + } while (0) + +#define __evl_spin_trylock(__lock) \ + ({ \ + evl_disable_preempt(); \ + raw_spin_trylock(&(__lock)->_lock); \ + }) + +#ifdef CONFIG_EVL_DEBUG_CORE +#define _evl_spin_lock_check() \ + WARN_ON_ONCE(!(running_oob() || \ + irqs_disabled() || \ + hard_irqs_disabled())) +#define _evl_spin_lock(__lock) \ + do { \ + _evl_spin_lock_check(); \ + __evl_spin_lock(__lock); \ + } while (0) + +#define _evl_spin_lock_nested(__lock, __subclass) \ + do { \ + _evl_spin_lock_check(); \ + __evl_spin_lock_nested(__lock, __subclass); \ + } while (0) + +#define _evl_spin_trylock(__lock) \ + ({ \ + _evl_spin_lock_check(); \ + __evl_spin_trylock(__lock); \ + }) +#define evl_spin_lock(__lock) _evl_spin_lock(__lock) +#define evl_spin_lock_nested(__lock, __subclass) _evl_spin_lock_nested(__lock, __subclass) +#define evl_spin_trylock(__lock) _evl_spin_trylock(__lock) +#else +#define evl_spin_lock(__lock) __evl_spin_lock(__lock) +#define evl_spin_lock_nested(__lock, __subclass) __evl_spin_lock_nested(__lock, __subclass) +#define evl_spin_trylock(__lock) __evl_spin_trylock(__lock) +#endif /* !CONFIG_EVL_DEBUG_CORE */ + +#define evl_spin_lock_irq(__lock) \ + do { \ + evl_disable_preempt(); \ + raw_spin_lock_irq(&(__lock)->_lock); \ + } while (0) + +#define evl_spin_unlock_irq(__lock) \ + do { \ + raw_spin_unlock_irq(&(__lock)->_lock); \ + evl_enable_preempt(); \ + } while (0) + +#define evl_spin_lock_irqsave(__lock, __flags) \ + do { \ + evl_disable_preempt(); \ + raw_spin_lock_irqsave(&(__lock)->_lock, __flags); \ + } while (0) + +#define evl_spin_unlock(__lock) \ + do { \ + raw_spin_unlock(&(__lock)->_lock); \ + evl_enable_preempt(); \ + } while (0) + +#define evl_spin_unlock_irqrestore(__lock, __flags) \ + do { \ + raw_spin_unlock_irqrestore(&(__lock)->_lock, __flags); \ + evl_enable_preempt(); \ + } while (0) + +#endif /* !_EVL_LOCK_H */ diff --git a/include/evl/memory.h b/include/evl/memory.h new file mode 100644 index 000000000..3219ee4bd --- /dev/null +++ b/include/evl/memory.h @@ -0,0 +1,141 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Derived from Xenomai Cobalt, https://xenomai.org/ + * Copyright (C) 2018 Philippe Gerum + */ + +#ifndef _EVL_MEMORY_H +#define _EVL_MEMORY_H + +#include +#include +#include +#include +#include +#include +#include + +#define EVL_HEAP_PAGE_SHIFT 9 /* 2^9 => 512 bytes */ +#define EVL_HEAP_PAGE_SIZE (1UL << EVL_HEAP_PAGE_SHIFT) +#define EVL_HEAP_PAGE_MASK (~(EVL_HEAP_PAGE_SIZE - 1)) +#define EVL_HEAP_MIN_LOG2 4 /* 16 bytes */ +/* + * Use bucketed memory for sizes between 2^EVL_HEAP_MIN_LOG2 and + * 2^(EVL_HEAP_PAGE_SHIFT-1). + */ +#define EVL_HEAP_MAX_BUCKETS (EVL_HEAP_PAGE_SHIFT - EVL_HEAP_MIN_LOG2) +#define EVL_HEAP_MIN_ALIGN (1U << EVL_HEAP_MIN_LOG2) +/* Maximum size of a heap (4Gb - PAGE_SIZE). */ +#define EVL_HEAP_MAX_HEAPSZ (4294967295U - PAGE_SIZE + 1) +/* Bits we need for encoding a page # */ +#define EVL_HEAP_PGENT_BITS (32 - EVL_HEAP_PAGE_SHIFT) +/* Each page is represented by a page map entry. */ +#define EVL_HEAP_PGMAP_BYTES sizeof(struct evl_heap_pgentry) + +struct evl_heap_pgentry { + /* Linkage in bucket list. */ + unsigned int prev : EVL_HEAP_PGENT_BITS; + unsigned int next : EVL_HEAP_PGENT_BITS; + /* page_list or log2. */ + unsigned int type : 6; + /* + * We hold either a spatial map of busy blocks within the page + * for bucketed memory (up to 32 blocks per page), or the + * overall size of the multi-page block if entry.type == + * page_list. + */ + union { + u32 map; + u32 bsize; + }; +}; + +/* + * A range descriptor is stored at the beginning of the first page of + * a range of free pages. evl_heap_range.size is nrpages * + * EVL_HEAP_PAGE_SIZE. Ranges are indexed by address and size in + * rbtrees. + */ +struct evl_heap_range { + struct rb_node addr_node; + struct rb_node size_node; + size_t size; +}; + +struct evl_heap { + void *membase; + struct rb_root addr_tree; + struct rb_root size_tree; + struct evl_heap_pgentry *pagemap; + size_t usable_size; + size_t used_size; + u32 buckets[EVL_HEAP_MAX_BUCKETS]; + hard_spinlock_t lock; + struct list_head next; +}; + +extern struct evl_heap evl_system_heap; + +extern struct evl_heap evl_shared_heap; + +static inline size_t evl_get_heap_size(const struct evl_heap *heap) +{ + return heap->usable_size; +} + +static inline size_t evl_get_heap_free(const struct evl_heap *heap) +{ + return heap->usable_size - heap->used_size; +} + +static inline void *evl_get_heap_base(const struct evl_heap *heap) +{ + return heap->membase; +} + +int evl_init_heap(struct evl_heap *heap, void *membase, + size_t size); + +void evl_destroy_heap(struct evl_heap *heap); + +void *evl_alloc_chunk(struct evl_heap *heap, size_t size); + +void evl_free_chunk(struct evl_heap *heap, void *block); + +ssize_t evl_check_chunk(struct evl_heap *heap, void *block); + +static inline void *evl_zalloc_chunk(struct evl_heap *heap, u32 size) +{ + void *p; + + p = evl_alloc_chunk(heap, size); + if (p) + memset(p, 0, size); + + return p; +} + +static inline +int evl_shared_offset(void *p) +{ + return p - evl_get_heap_base(&evl_shared_heap); +} + +static inline void *evl_alloc(size_t size) +{ + return evl_alloc_chunk(&evl_system_heap, size); +} + +static inline void evl_free(void *ptr) +{ + evl_free_chunk(&evl_system_heap, ptr); +} + +int evl_init_memory(void); + +void evl_cleanup_memory(void); + +extern size_t evl_shm_size; + +#endif /* !_EVL_MEMORY_H */ diff --git a/include/evl/monitor.h b/include/evl/monitor.h new file mode 100644 index 000000000..632f95d48 --- /dev/null +++ b/include/evl/monitor.h @@ -0,0 +1,26 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2018 Philippe Gerum + */ + +#ifndef _EVL_MONITOR_H +#define _EVL_MONITOR_H + +#include +#include + +int evl_signal_monitor_targeted(struct evl_thread *target, + int monfd); + +void __evl_commit_monitor_ceiling(void); + +static inline void evl_commit_monitor_ceiling(void) +{ + struct evl_thread *curr = evl_current(); + + if (curr->u_window->pp_pending != EVL_NO_HANDLE) + __evl_commit_monitor_ceiling(); +} + +#endif /* !_EVL_MONITOR_H */ diff --git a/include/evl/mutex.h b/include/evl/mutex.h new file mode 100644 index 000000000..0313768cd --- /dev/null +++ b/include/evl/mutex.h @@ -0,0 +1,168 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2019 Philippe Gerum + */ + +#ifndef _EVL_MUTEX_H +#define _EVL_MUTEX_H + +#include +#include +#include +#include +#include +#include +#include +#include + +struct evl_clock; +struct evl_thread; + +/* Priority inheritance protocol enforced. */ +#define EVL_MUTEX_PI BIT(0) +/* Priority protection protocol enforced. */ +#define EVL_MUTEX_PP BIT(1) +/* Causes a priority boost for its owner. */ +#define EVL_MUTEX_PIBOOST BIT(2) +/* Causes a priority ceiling for its owner. */ +#define EVL_MUTEX_CEILING BIT(3) +/* Counted in thread->held_mutex_count. */ +#define EVL_MUTEX_COUNTED BIT(4) + +struct evl_mutex { + atomic_t *fastlock; + int flags; + u32 *ceiling_addr; + struct evl_wait_channel wchan; + struct list_head next_booster; /* thread->boosters */ + struct list_head next_owned; /* thread->owned_mutexes */ + struct { + struct evl_sched_class *sched_class; + union evl_sched_param param; + int wprio; + } boost; + struct evl_clock *clock; +}; + +void __evl_init_mutex(struct evl_mutex *mutex, + struct evl_clock *clock, + atomic_t *fastlock, + u32 *ceiling, + const char *name, + struct lock_class_key *lock_key); + +#define evl_init_mutex(__mutex, __clock, __fastlock, __ceiling) \ + do { \ + static struct lock_class_key key; \ + __evl_init_mutex(__mutex, __clock, __fastlock, __ceiling, #__mutex, &key); \ + } while (0) + +#define evl_init_mutex_pi(__mutex, __clock, __fastlock) \ + evl_init_mutex(__mutex, __clock, __fastlock, NULL) + +#define evl_init_mutex_pp(__mutex, __clock, __fastlock, __ceiling) \ + evl_init_mutex(__mutex, __clock, __fastlock, __ceiling) + +void evl_destroy_mutex(struct evl_mutex *mutex); + +int evl_trylock_mutex(struct evl_mutex *mutex); + +int evl_lock_mutex_timeout(struct evl_mutex *mutex, ktime_t timeout, + enum evl_tmode timeout_mode); + +static inline int evl_lock_mutex(struct evl_mutex *mutex) +{ + return evl_lock_mutex_timeout(mutex, EVL_INFINITE, EVL_REL); +} + +void __evl_unlock_mutex(struct evl_mutex *mutex); + +void evl_unlock_mutex(struct evl_mutex *mutex); + +void evl_flush_mutex(struct evl_mutex *mutex, + int reason); + +void evl_commit_mutex_ceiling(struct evl_mutex *mutex); + +void evl_check_no_mutex(void); + +bool evl_requeue_mutex_wait(struct evl_wait_channel *wchan, + struct evl_thread *waiter); + +void evl_drop_current_ownership(void); + +static inline bool +evl_is_mutex_owner(atomic_t *fastlock, fundle_t ownerh) +{ + return evl_get_index(atomic_read(fastlock)) == ownerh; +} + +struct evl_kmutex { + struct evl_mutex mutex; + atomic_t fastlock; +}; + +#define EVL_KMUTEX_INITIALIZER(__name) { \ + .mutex = { \ + .fastlock = &(__name).fastlock, \ + .flags = EVL_MUTEX_PI, \ + .wprio = -1, \ + .ceiling_addr = NULL, \ + .clock = &evl_mono_clock, \ + .wchan = { \ + .lock = __HARD_SPIN_LOCK_INITIALIZER((__name).wchan.lock), \ + .owner = NULL, \ + .requeue_wait = evl_requeue_mutex_wait, \ + .wait_list = LIST_HEAD_INIT((__name).mutex.wchan.wait_list), \ + .name = #__name, \ + }, \ + }, \ + .fastlock = ATOMIC_INIT(0), \ + } + +#define DEFINE_EVL_KMUTEX(__name) \ + struct evl_kmutex __name = EVL_KMUTEX_INITIALIZER(__name) + +static inline +void evl_init_kmutex(struct evl_kmutex *kmutex) +{ + atomic_set(&kmutex->fastlock, 0); + evl_init_mutex_pi(&kmutex->mutex, &evl_mono_clock, &kmutex->fastlock); +} + +static inline +void evl_destroy_kmutex(struct evl_kmutex *kmutex) +{ + evl_destroy_mutex(&kmutex->mutex); +} + +static inline +int evl_trylock_kmutex(struct evl_kmutex *kmutex) +{ + return evl_trylock_mutex(&kmutex->mutex); +} + +static inline +int evl_lock_kmutex(struct evl_kmutex *kmutex) +{ + return evl_lock_mutex(&kmutex->mutex); +} + +static inline +void evl_unlock_kmutex(struct evl_kmutex *kmutex) +{ + return evl_unlock_mutex(&kmutex->mutex); +} + +static inline int evl_ceiling_priority(struct evl_mutex *mutex) +{ + /* + * The ceiling priority value is stored in user-writable + * memory, make sure to constrain it within valid bounds for + * evl_sched_fifo before using it. + */ + return clamp(*mutex->ceiling_addr, 1U, (u32)EVL_FIFO_MAX_PRIO); +} + +#endif /* !_EVL_MUTEX_H */ diff --git a/include/evl/net.h b/include/evl/net.h new file mode 100644 index 000000000..9b194d69b --- /dev/null +++ b/include/evl/net.h @@ -0,0 +1,38 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2020 Philippe Gerum + */ + +#ifndef _EVL_NET_H +#define _EVL_NET_H + +#ifdef CONFIG_EVL_NET + +#include +#include +#include +#include +#include + +int evl_net_init(void); + +void evl_net_cleanup(void); + +extern const struct net_proto_family evl_family_ops; + +extern struct proto evl_af_oob_proto; + +#else + +static inline int evl_net_init(void) +{ + return 0; +} + +static inline void evl_net_cleanup(void) +{ } + +#endif + +#endif /* !_EVL_NET_H */ diff --git a/include/evl/net/device.h b/include/evl/net/device.h new file mode 100644 index 000000000..b4abecd32 --- /dev/null +++ b/include/evl/net/device.h @@ -0,0 +1,65 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2020 Philippe Gerum + */ + +#ifndef _EVL_NET_DEVICE_H +#define _EVL_NET_DEVICE_H + +#ifdef CONFIG_EVL_NET + +#include +#include +#include + +struct evl_socket; +struct evl_netdev_activation; +struct notifier_block; +struct sk_buff; + +int evl_net_switch_oob_port(struct evl_socket *esk, + struct evl_netdev_activation *act); + +int evl_netdev_event(struct notifier_block *ev_block, + unsigned long event, void *ptr); + +struct net_device * +evl_net_get_dev_by_index(struct net *net, int ifindex); + +struct net_device * +evl_net_get_dev_by_name(struct net *net, const char *name); + +void evl_net_get_dev(struct net_device *dev); + +void evl_net_put_dev(struct net_device *dev); + +void evl_net_wake_rx(struct net_device *dev); + +int evl_net_dev_allocfd(struct net *net, const char *devname); + +enum evl_net_rx_action +__evl_net_filter_rx(struct evl_netdev_state *est, struct sk_buff *skb); + +static inline enum evl_net_rx_action +evl_net_filter_rx(struct net_device *dev, struct sk_buff *skb) +{ + struct evl_netdev_state *est = dev->oob_state.estate; + + if (test_bit(EVL_NETDEV_RXFILTER_BIT, &est->flags)) + return __evl_net_filter_rx(est, skb); + + return EVL_RX_VLAN; +} + +static inline struct net_device *evl_net_real_dev(struct net_device *dev) +{ + if (is_vlan_dev(dev)) + return vlan_dev_real_dev(dev); + + return dev; +} + +#endif + +#endif /* !_EVL_NET_DEVICE_H */ diff --git a/include/evl/net/ether/output.h b/include/evl/net/ether/output.h new file mode 100644 index 000000000..2c919f489 --- /dev/null +++ b/include/evl/net/ether/output.h @@ -0,0 +1,19 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2023 Philippe Gerum + */ + +#ifndef _EVL_NET_ETHER_OUTPUT_H +#define _EVL_NET_ETHER_OUTPUT_H + +struct sk_buff; +struct net_device; + +int evl_net_ether_transmit_raw(struct net_device *dev, + struct sk_buff *skb); + +int evl_net_ether_transmit(struct net_device *dev, struct sk_buff *skb, + const void *hw_dst); + +#endif /* !_EVL_NET_ETHER_OUTPUT_H */ diff --git a/include/evl/net/input.h b/include/evl/net/input.h new file mode 100644 index 000000000..2838cb04a --- /dev/null +++ b/include/evl/net/input.h @@ -0,0 +1,49 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2020 Philippe Gerum + */ + +#ifndef _EVL_NET_INPUT_H +#define _EVL_NET_INPUT_H + +#include +#include + +struct sk_buff; + +struct evl_net_handler { + void (*ingress)(struct sk_buff *skb); +}; + +struct evl_net_rxqueue { + u32 hkey; + struct hlist_node hash; + struct list_head subscribers; + evl_spinlock_t lock; + struct list_head next; +}; + +void evl_net_do_rx(void *arg); + +void evl_net_receive(struct sk_buff *skb, + struct evl_net_handler *handler); + +struct evl_net_rxqueue *evl_net_alloc_rxqueue(u32 hkey); + +void evl_net_free_rxqueue(struct evl_net_rxqueue *rxq); + +bool evl_net_ether_accept(struct sk_buff *skb); + +bool evl_net_ether_accept_vlan(struct sk_buff *skb); + +static inline bool evl_net_rxqueue_active(struct evl_net_rxqueue *rxq) +{ + return list_empty(&rxq->subscribers); +} + +ssize_t evl_net_store_vlans(const char *buf, size_t len); + +ssize_t evl_net_show_vlans(char *buf, size_t len); + +#endif /* !_EVL_NET_INPUT_H */ diff --git a/include/evl/net/ip.h b/include/evl/net/ip.h new file mode 100644 index 000000000..77e486598 --- /dev/null +++ b/include/evl/net/ip.h @@ -0,0 +1,17 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2023 Philippe Gerum + */ + +#ifndef _EVL_NET_IP_H +#define _EVL_NET_IP_H + +#include + +static inline void evl_net_init_ip_socket(struct evl_socket *esk) +{ + INIT_LIST_HEAD(&esk->u.ip.pending_output); +} + +#endif /* !_EVL_NET_IP_H */ diff --git a/include/evl/net/ipv4.h b/include/evl/net/ipv4.h new file mode 100644 index 000000000..b2930539b --- /dev/null +++ b/include/evl/net/ipv4.h @@ -0,0 +1,42 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2023 Philippe Gerum + */ + +#ifndef _EVL_NET_IPV4_H +#define _EVL_NET_IPV4_H + +#include +#include +#include +#include + +struct sk_buff; + +struct evl_net_ipv4_cookie { + __be32 saddr; /* Source IP */ + __be32 daddr; /* Destination IP */ + __u8 protocol; /* Internet protocol identifier */ + int transhdrlen; /* Transport header length */ +}; + +int evl_net_ipv4_deliver(struct sk_buff *skb); + +void __evl_net_ipv4_gc(struct evl_net_frag_tdir *ftdir); + +static inline void evl_net_ipv4_gc(struct net *net) +{ + struct evl_net_frag_tdir *ftdir = &net->oob.ipv4.ftdir; + + if (!hlist_empty(&ftdir->gc.queue)) + __evl_net_ipv4_gc(ftdir); +} + +int evl_net_init_ipv4(struct net *net); + +void evl_net_cleanup_ipv4(struct net *net); + +extern struct evl_socket_domain evl_net_ipv4; + +#endif /* !_EVL_NET_IPV4_H */ diff --git a/include/evl/net/ipv4/arp.h b/include/evl/net/ipv4/arp.h new file mode 100644 index 000000000..7c074d49e --- /dev/null +++ b/include/evl/net/ipv4/arp.h @@ -0,0 +1,44 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2021 Philippe Gerum + */ + +#ifndef _EVL_NET_IPV4_ARP_H +#define _EVL_NET_IPV4_ARP_H + +#include +#include + +/* ARP entry. */ +struct evl_net_arp_entry { + /* Generic cache entry. */ + struct evl_cache_entry entry; + /* Device reference tracker. */ + netdevice_tracker dev_tracker; + /* Cached hardware address. */ + unsigned char ha[ALIGN(MAX_ADDR_LEN, sizeof(unsigned long))] __aligned(8); + /* Index key. */ + struct evl_net_arp_key { + /* Associated netdev (in-band refcounted). */ + struct net_device *dev; + /* IPv4 address of neighbour. */ + __be32 addr; + } key; +}; + +int evl_net_init_arp(struct net *net); + +void evl_net_cleanup_arp(struct net *net); + +void evl_net_flush_arp(struct net *net); + +struct evl_net_arp_entry * +evl_net_get_arp_entry(struct net_device *dev, __be32 addr); + +static inline void evl_net_put_arp_entry(struct evl_net_arp_entry *earp) +{ + evl_put_cache_entry(&earp->entry); +} + +#endif /* !_EVL_NET_IPV4_ARP_H */ diff --git a/include/evl/net/ipv4/fragment.h b/include/evl/net/ipv4/fragment.h new file mode 100644 index 000000000..1c2ff4ba9 --- /dev/null +++ b/include/evl/net/ipv4/fragment.h @@ -0,0 +1,14 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2023 Philippe Gerum + */ + +#ifndef _EVL_NET_IPV4_FRAGMENT_H +#define _EVL_NET_IPV4_FRAGMENT_H + +struct sk_buff; + +struct sk_buff *evl_ipv4_defrag(struct sk_buff *skb); + +#endif /* !_EVL_NET_IPV4_FRAGMENT_H */ diff --git a/include/evl/net/ipv4/output.h b/include/evl/net/ipv4/output.h new file mode 100644 index 000000000..e42846198 --- /dev/null +++ b/include/evl/net/ipv4/output.h @@ -0,0 +1,26 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2023 Philippe Gerum + */ + +#ifndef _EVL_NET_IPV4_OUTPUT_H +#define _EVL_NET_IPV4_OUTPUT_H + +#include +#include +#include + +struct evl_socket; +struct evl_net_route; +struct sk_buff_head; +struct iovec; + +struct sk_buff *evl_net_ipv4_build_datagram(struct evl_socket *esk, + struct iovec *iov, size_t iovlen, + struct evl_net_route *ert, + size_t datalen, + ktime_t timeout, + struct evl_net_ipv4_cookie *ipc); + +#endif /* !_EVL_NET_IPV4_OUTPUT_H */ diff --git a/include/evl/net/ipv4/route.h b/include/evl/net/ipv4/route.h new file mode 100644 index 000000000..cf40ef21d --- /dev/null +++ b/include/evl/net/ipv4/route.h @@ -0,0 +1,29 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2023 Philippe Gerum + */ + +#ifndef _EVL_NET_IPV4_ROUTE_H +#define _EVL_NET_IPV4_ROUTE_H + +#include + +struct sk_buff; +struct net; +struct net_device; +struct flowi4; +struct rtable; + +int evl_net_init_ipv4_routing(struct net *net); + +void evl_net_cleanup_ipv4_routing(struct net *net); + +void evl_net_learn_ipv4_route(struct net *net, + struct flowi4 *fl4, struct rtable *rt); + +void evl_net_flush_ipv4_routes(struct net *net, struct net_device *dev); + +struct evl_net_route *evl_net_get_ipv4_route(struct net *net, __be32 daddr); + +#endif /* !_EVL_NET_IPV4_ROUTE_H */ diff --git a/include/evl/net/ipv4/udp.h b/include/evl/net/ipv4/udp.h new file mode 100644 index 000000000..a4837c493 --- /dev/null +++ b/include/evl/net/ipv4/udp.h @@ -0,0 +1,41 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2021 Philippe Gerum + */ + +#ifndef _EVL_NET_IPV4_UDP_H +#define _EVL_NET_IPV4_UDP_H + +#include +#include +#include +#include +#include + +/* Cached UDP receiver. */ +struct evl_net_udp_receiver { + /* Generic cache entry. */ + struct evl_cache_entry entry; + /* Queue of pending datagrams. */ + struct list_head queue; + /* Wait queue receivers sleep on. */ + struct evl_wait_queue wait; + /* Users (SO_REUSEPORT) */ + refcount_t refs; + /* The hash key must be aliasable to u32[]. */ + struct __evl_net_udp_key { + u32 dport; + u32 daddr; + } key __packed; +}; + +int evl_net_deliver_udp(struct sk_buff *skb); + +int evl_net_init_udp(struct net *net); + +void evl_net_cleanup_udp(struct net *net); + +extern struct evl_net_proto evl_net_udp_proto; + +#endif /* !_EVL_NET_IPV4_UDP_H */ diff --git a/include/evl/net/offload.h b/include/evl/net/offload.h new file mode 100644 index 000000000..e032b9f07 --- /dev/null +++ b/include/evl/net/offload.h @@ -0,0 +1,24 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2023 Philippe Gerum + */ + +#ifndef _EVL_NET_OFFLOAD_H +#define _EVL_NET_OFFLOAD_H + +#include +#include +#include + +struct evl_net_offload { + struct kvec kvec; + size_t count; + union { + struct sockaddr_in in; + } dest; + int destlen; + struct list_head next; +}; + +#endif /* !_EVL_NET_OFFLOAD_H */ diff --git a/include/evl/net/output.h b/include/evl/net/output.h new file mode 100644 index 000000000..ef54154ac --- /dev/null +++ b/include/evl/net/output.h @@ -0,0 +1,20 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2020 Philippe Gerum + */ + +#ifndef _EVL_NET_OUTPUT_H +#define _EVL_NET_OUTPUT_H + +#include + +struct sk_buff; + +void evl_net_do_tx(void *arg); + +int evl_net_transmit(struct sk_buff *skb); + +void evl_net_init_tx(void); + +#endif /* !_EVL_NET_OUTPUT_H */ diff --git a/include/evl/net/packet.h b/include/evl/net/packet.h new file mode 100644 index 000000000..bea66141f --- /dev/null +++ b/include/evl/net/packet.h @@ -0,0 +1,16 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2020 Philippe Gerum + */ + +#ifndef _EVL_NET_PACKET_H +#define _EVL_NET_PACKET_H + +#include + +bool evl_net_packet_deliver(struct sk_buff *skb); + +extern struct evl_socket_domain evl_net_packet; + +#endif /* !_EVL_NET_PACKET_H */ diff --git a/include/evl/net/qdisc.h b/include/evl/net/qdisc.h new file mode 100644 index 000000000..ebcc9061d --- /dev/null +++ b/include/evl/net/qdisc.h @@ -0,0 +1,54 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2020 Philippe Gerum + */ + +#ifndef _EVL_NET_QDISC_H +#define _EVL_NET_QDISC_H + +#include +#include +#include + +struct evl_net_qdisc; + +struct evl_net_qdisc_ops { + const char *name; + size_t priv_size; + int (*init)(struct evl_net_qdisc *qdisc); + void (*destroy)(struct evl_net_qdisc *qdisc); + int (*enqueue)(struct evl_net_qdisc *qdisc, struct sk_buff *skb); + struct sk_buff *(*dequeue)(struct evl_net_qdisc *qdisc); + struct list_head next; +}; + +struct evl_net_qdisc { + const struct evl_net_qdisc_ops *oob_ops; + unsigned long packet_dropped; +}; + +static inline void *evl_qdisc_priv(struct evl_net_qdisc *qdisc) +{ + return qdisc + 1; +} + +void evl_net_register_qdisc(struct evl_net_qdisc_ops *ops); + +void evl_net_unregister_qdisc(struct evl_net_qdisc_ops *ops); + +struct evl_net_qdisc * +evl_net_alloc_qdisc(struct evl_net_qdisc_ops *ops); + +void evl_net_free_qdisc(struct evl_net_qdisc *qdisc); + +int evl_net_sched_packet(struct net_device *dev, + struct sk_buff *skb); + +void evl_net_init_qdisc(void); + +void evl_net_cleanup_qdisc(void); + +extern struct evl_net_qdisc_ops evl_net_qdisc_fifo; + +#endif /* !_EVL_NET_QDISC_H */ diff --git a/include/evl/net/route.h b/include/evl/net/route.h new file mode 100644 index 000000000..27a4955f3 --- /dev/null +++ b/include/evl/net/route.h @@ -0,0 +1,50 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2023 Philippe Gerum + */ + +#ifndef _EVL_NET_ROUTE_H +#define _EVL_NET_ROUTE_H + +#include +#include + +struct net; +struct evl_work; + +/* Cached route for IP datagrams. */ +struct evl_net_route { + /* Generic cache entry. */ + struct evl_cache_entry entry; + /* Destination as resolved in-band (in-band refcounted). */ + struct rtable *rt; + /* Index key (destination IP). */ + u8 key[0] __aligned(4); +}; + +int evl_net_cache_route(struct evl_cache *cache, + struct rtable *rt, + const void *key, + size_t key_len); + +void evl_net_free_route(struct evl_cache_entry *entry); + +static inline void evl_net_put_route(struct evl_net_route *ert) +{ + evl_put_cache_entry(&ert->entry); +} + +void evl_net_flush_routes(struct net *net, struct net_device *dev); + +static inline struct dst_entry *evl_net_route_dst(const struct evl_net_route *ert) +{ + return &ert->rt->dst; +} + +static inline struct net_device *evl_net_route_dev(const struct evl_net_route *ert) +{ + return evl_net_route_dst(ert)->dev; +} + +#endif /* !_EVL_NET_ROUTE_H */ diff --git a/include/evl/net/skb.h b/include/evl/net/skb.h new file mode 100644 index 000000000..a44c3a682 --- /dev/null +++ b/include/evl/net/skb.h @@ -0,0 +1,81 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2020 Philippe Gerum + */ + +#ifndef _EVL_NET_SKB_H +#define _EVL_NET_SKB_H + +#include +#include +#include +#include + +struct sk_buff; +struct net_device; +struct evl_net_handler; +struct evl_net_skb_queue; +struct evl_socket; +struct iovec; + +struct evl_net_cb { + struct evl_net_handler *handler; + struct evl_socket *tracker; + union { + /* protocol-specific stuff should live here. */ + }; +}; +#define EVL_NET_CB(__skb) ((struct evl_net_cb *)&((__skb)->cb[0])) + +void evl_net_init_skb_queue(struct evl_net_skb_queue *txq); + +void evl_net_destroy_skb_queue(struct evl_net_skb_queue *txq); + +void evl_net_add_skb_queue(struct evl_net_skb_queue *skbq, + struct sk_buff *skb); + +struct sk_buff * +evl_net_get_skb_queue(struct evl_net_skb_queue *skbq); + +bool evl_net_move_skb_queue(struct evl_net_skb_queue *skbq, + struct list_head *list); + +int evl_net_dev_build_pool(struct net_device *dev); + +void evl_net_dev_purge_pool(struct net_device *dev); + +struct sk_buff *evl_net_wget_skb(struct evl_socket *esk, + struct net_device *dev, + ktime_t timeout); + +void evl_net_wput_skb(struct sk_buff *skb); + +void evl_net_rput_skb(struct sk_buff *skb); + +struct sk_buff *evl_net_dev_alloc_skb(struct net_device *dev, + ktime_t timeout, + enum evl_tmode tmode); + +void evl_net_free_skb(struct sk_buff *skb); + +void evl_net_free_skb_list(struct list_head *list); + +struct sk_buff *evl_net_clone_skb(struct sk_buff *skb); + +bool evl_net_charge_skb_rmem(struct evl_socket *esk, + struct sk_buff *skb); + +void evl_net_uncharge_skb_rmem(struct sk_buff *skb); + +int evl_net_charge_skb_wmem(struct evl_socket *esk, + struct sk_buff *skb, + ktime_t timeout, enum evl_tmode tmode); + +void evl_net_uncharge_skb_wmem(struct sk_buff *skb); + +ssize_t evl_net_skb_to_uio(const struct iovec *iov, size_t iovlen, + struct sk_buff *skb, size_t skip, + bool *short_write); + +#endif /* !_EVL_NET_SKB_H */ diff --git a/include/evl/net/socket.h b/include/evl/net/socket.h new file mode 100644 index 000000000..fbe6c73fe --- /dev/null +++ b/include/evl/net/socket.h @@ -0,0 +1,145 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2020 Philippe Gerum + */ + +#ifndef _EVL_NET_SOCKET_H +#define _EVL_NET_SOCKET_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct evl_socket; +struct net; +struct net_device; +struct evl_net_offload; +struct evl_net_udp_receiver; + +struct evl_net_proto { + int (*attach)(struct evl_socket *esk, + struct evl_net_proto *proto, int protocol); + void (*release)(struct evl_socket *esk); + void (*destroy)(struct evl_socket *esk); + int (*bind)(struct evl_socket *esk, + struct sockaddr *addr, int len); + int (*connect)(struct evl_socket *esk, + struct sockaddr *addr, int len, int flags); + int (*shutdown)(struct evl_socket *esk, int how); + int (*ioctl)(struct evl_socket *esk, unsigned int cmd, + unsigned long arg); + ssize_t (*oob_send)(struct evl_socket *esk, + const struct user_oob_msghdr __user *u_msghdr, + struct iovec *iov, + size_t iovlen); + ssize_t (*oob_receive)(struct evl_socket *esk, + struct user_oob_msghdr __user *u_msghdr, + struct iovec *iov, + size_t iovlen); + __poll_t (*oob_poll)(struct evl_socket *esk, + struct oob_poll_wait *wait); + struct net_device *(*get_netif)(struct evl_socket *esk); + void (*handle_offload)(struct evl_socket *esk); +}; + +struct evl_socket_domain { + int af_domain; + struct evl_net_proto *(*match)(int type, int protocol); + struct list_head next; +}; + +struct evl_socket { + struct evl_net_proto *proto; + struct evl_file efile; + struct mutex lock; + struct net *net; + struct hlist_node hash; + struct list_head input; + struct evl_wait_queue input_wait; + struct evl_poll_head poll_head; /* On input queue. */ + struct list_head next_sub; /* evl_net_rxqueue.subscribers */ + struct sock *sk; + atomic_t rmem_count; + int rmem_max; + atomic_t wmem_count; + int wmem_max; + struct evl_wait_queue wmem_wait; + struct evl_crossing wmem_drain; + int protocol; + refcount_t refs; /* release vs destroy */ + struct evl_work inband_offload; + union { + /* Packet interface data. */ + struct { + int real_ifindex; + int ifindex; /* Same as real_ifindex or vlan ifindex */ + u16 vlan_id; /* non-zero if vlan device, zero otherwise */ + u32 proto_hash; + } packet; + /* Used by all IP protocols we support. */ + struct { + /* Offload descriptors. */ + struct list_head pending_output; + /* UDP bindings. */ + union { + struct { + u32 rcv_addr; + u16 rcv_port; + struct evl_net_udp_receiver *receiver; + } udp; + }; + } ip; + } u; + hard_spinlock_t oob_lock; +}; + +static inline unsigned int evl_socket_f_flags(struct evl_socket *esk) +{ + return esk->efile.filp->f_flags; +} + +static inline bool evl_charge_socket_rmem(struct evl_socket *esk, + size_t size) +{ + /* An overflow of skb->truesize - 1 is allowed, not more. */ + if (atomic_read(&esk->rmem_count) >= esk->rmem_max) + return false; + + /* We don't have to saturate, atomic_t is fine. */ + atomic_add(size, &esk->rmem_count); + + return true; +} + +static inline void evl_uncharge_socket_rmem(struct evl_socket *esk, + size_t size) +{ + int count = atomic_sub_return(size, &esk->rmem_count); + EVL_WARN_ON(NET, count < 0); +} + +int evl_charge_socket_wmem(struct evl_socket *esk, size_t size, + ktime_t timeout, enum evl_tmode tmode); + +void evl_uncharge_socket_wmem(struct evl_socket *esk, size_t size); + +int evl_register_socket_domain(struct evl_socket_domain *domain); + +void evl_unregister_socket_domain(struct evl_socket_domain *domain); + +void evl_net_offload_inband(struct evl_socket *esk, + struct evl_net_offload *ofld, + struct list_head *q); + +#endif /* !_EVL_NET_SOCKET_H */ diff --git a/include/evl/observable.h b/include/evl/observable.h new file mode 100644 index 000000000..8a53cd9d8 --- /dev/null +++ b/include/evl/observable.h @@ -0,0 +1,63 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2020 Philippe Gerum + */ + +#ifndef _EVL_OBSERVABLE_H +#define _EVL_OBSERVABLE_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct file; + +struct evl_observable { + struct evl_element element; + struct list_head observers; /* struct evl_observer */ + struct list_head flush_list; /* struct evl_observer */ + struct evl_wait_queue oob_wait; + wait_queue_head_t inband_wait_r; + wait_queue_head_t inband_wait_w; + struct evl_poll_head poll_head; + struct irq_work wake_r_irqwork; + struct irq_work wake_w_irqwork; + struct irq_work flush_irqwork; + hard_spinlock_t lock; /* guards observers and flush_list */ + u32 serial_counter; + int writable_observers; +}; + +void evl_drop_subscriptions(struct evl_subscriber *subscriber); + +struct evl_observable *evl_alloc_observable(const char __user *u_name, + int clone_flags); + +void evl_flush_observable(struct evl_observable *observable); + +bool evl_send_observable(struct evl_observable *observable, int tag, + union evl_value details); + +ssize_t evl_read_observable(struct evl_observable *observable, + char __user *u_buf, size_t count, bool wait); + +ssize_t evl_write_observable(struct evl_observable *observable, + const char __user *u_buf, size_t count); + +__poll_t evl_oob_poll_observable(struct evl_observable *observable, + struct oob_poll_wait *wait); + +__poll_t evl_poll_observable(struct evl_observable *observable, + struct file *filp, poll_table *pt); + +long evl_ioctl_observable(struct evl_observable *observable, + unsigned int cmd, unsigned long arg); + +#endif /* !_EVL_OBSERVABLE_H */ diff --git a/include/evl/poll.h b/include/evl/poll.h new file mode 100644 index 000000000..c16ed26bb --- /dev/null +++ b/include/evl/poll.h @@ -0,0 +1,45 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2018 Philippe Gerum + */ + +#ifndef _EVL_POLL_H +#define _EVL_POLL_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct file; + +struct evl_poll_node { + struct list_head next; /* in watchpoint->poll_nodes */ +}; + +/* + * The watchpoint struct linked to poll heads by drivers. This watches + * files not elements, so that we can monitor any type of EVL files. + */ +struct evl_poll_watchpoint { + unsigned int fd; + int events_polled; + union evl_value pollval; + struct oob_poll_wait wait; + struct evl_flag *flag; + struct file *filp; + struct evl_poll_node node; +}; + +void evl_drop_poll_table(struct evl_thread *thread); + +void evl_drop_watchpoints(struct list_head *drop_list); + +#endif /* !_EVL_POLL_H */ diff --git a/include/evl/poll_head.h b/include/evl/poll_head.h new file mode 100644 index 000000000..253571f30 --- /dev/null +++ b/include/evl/poll_head.h @@ -0,0 +1,48 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2018 Philippe Gerum + */ + +#ifndef _EVL_POLL_HEAD_H +#define _EVL_POLL_HEAD_H + +#include +#include + +struct oob_poll_wait; + +#define EVL_POLLHEAD_INITIALIZER(__name) { \ + .watchpoints = LIST_HEAD_INIT((__name).watchpoints), \ + .lock = __HARD_SPIN_LOCK_INITIALIZER((__name).lock), \ + } + +struct evl_poll_head { + struct list_head watchpoints; /* struct evl_poll_watchpoint */ + hard_spinlock_t lock; +}; + +static inline +void evl_init_poll_head(struct evl_poll_head *head) +{ + INIT_LIST_HEAD(&head->watchpoints); + raw_spin_lock_init(&head->lock); +} + +void evl_poll_watch(struct evl_poll_head *head, + struct oob_poll_wait *wait, + void (*unwatch)(struct evl_poll_head *head)); + +void __evl_signal_poll_events(struct evl_poll_head *head, + int events); + +static inline void +evl_signal_poll_events(struct evl_poll_head *head, + int events) +{ + /* Quick check. We'll redo under lock */ + if (!list_empty(&head->watchpoints)) + __evl_signal_poll_events(head, events); +} + +#endif /* !_EVL_POLL_HEAD_H */ diff --git a/include/evl/random.h b/include/evl/random.h new file mode 100644 index 000000000..ec852cb3a --- /dev/null +++ b/include/evl/random.h @@ -0,0 +1,24 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2023 Lionel Minne + * Copyright (C) 2023 Philippe Gerum + * + * A fast and efficient random number generator usable from the + * out-of-band stage. + */ + +#ifndef _EVL_RANDOM_H +#define _EVL_RANDOM_H + +#include + +void evl_init_rng(void); + +u8 evl_read_rng_u8(void); + +u16 evl_read_rng_u16(void); + +u32 evl_read_rng_u32(void); + +#endif /* !_EVL_RANDOM_H */ diff --git a/include/evl/sched.h b/include/evl/sched.h new file mode 100644 index 000000000..f915da411 --- /dev/null +++ b/include/evl/sched.h @@ -0,0 +1,651 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Derived from Xenomai Cobalt, https://xenomai.org/ + * Copyright (C) 2008, 2018 Philippe Gerum + */ + +#ifndef _EVL_SCHED_H +#define _EVL_SCHED_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* + * Shared rq flags bits. + * + * A rescheduling operation is pending. May also be present in the + * private flags. + */ +#define RQ_SCHED 0x10000000 + +/** + * Private rq flags (combined in test operation with shared bits by + * evl_schedule(), care for any conflict). + * + * Currently running in tick handler context. + */ +#define RQ_TIMER 0x00010000 +/* + * A proxy tick is being processed, i.e. matching an earlier timing + * request from inband via set_next_event(). + */ +#define RQ_TPROXY 0x00008000 +/* + * Currently running in IRQ handling context. + */ +#define RQ_IRQ 0x00004000 +/* + * Proxy tick is deferred, because we have more urgent out-of-band + * work to carry out first. + */ +#define RQ_TDEFER 0x00002000 +/* + * Idle state: there is no outstanding timer. We check this flag to + * know whether we may allow inband to enter the CPU idle state. + */ +#define RQ_IDLE 0x00001000 +/* + * Hardware timer is stopped. + */ +#define RQ_TSTOPPED 0x00000800 + +struct evl_sched_fifo { + struct evl_sched_queue runnable; +}; + +struct evl_rq { + hard_spinlock_t lock; + + /* + * Shared data, covered by ->lock. + */ + unsigned long flags; + struct evl_thread *curr; + struct evl_sched_fifo fifo; + struct evl_sched_weak weak; +#ifdef CONFIG_EVL_SCHED_QUOTA + struct evl_sched_quota quota; +#endif +#ifdef CONFIG_EVL_SCHED_TP + struct evl_sched_tp tp; +#endif + struct evl_thread root_thread; + struct lock_class_key root_lock_key; +#ifdef CONFIG_EVL_RUNSTATS + ktime_t last_account_switch; + struct evl_account *current_account; +#endif + + /* + * runqueue-local data the owner may modify locklessly. + */ + unsigned long local_flags; +#ifdef CONFIG_SMP + int cpu; + struct cpumask resched_cpus; +#endif + struct evl_timer inband_timer; + struct evl_timer rrbtimer; +#ifdef CONFIG_EVL_WATCHDOG + struct evl_timer wdtimer; +#endif + /* Misc stuff. */ + char *proxy_timer_name; + char *rrb_timer_name; +}; + +DECLARE_PER_CPU(struct evl_rq, evl_runqueues); + +extern struct cpumask evl_cpu_affinity; + +extern struct list_head evl_thread_list; + +extern int evl_nrthreads; + +union evl_sched_param; +struct evl_sched_config; + +struct evl_sched_class { + void (*sched_init)(struct evl_rq *rq); + void (*sched_enqueue)(struct evl_thread *thread); + void (*sched_dequeue)(struct evl_thread *thread); + void (*sched_requeue)(struct evl_thread *thread); + struct evl_thread *(*sched_pick)(struct evl_rq *rq); + void (*sched_yield)(struct evl_thread *thread); + void (*sched_migrate)(struct evl_thread *thread, + struct evl_rq *rq); + /* + * Set base scheduling parameters. This routine is indirectly + * called upon a change of base scheduling settings through + * evl_set_thread_schedparam_locked() -> + * evl_set_thread_policy_locked(), exclusively. + * + * The scheduling class implementation should do the necessary + * housekeeping to comply with the new settings. + * thread->base_class is up to date before the call is made, + * and should be considered for the new weighted priority + * calculation. On the contrary, thread->sched_class should + * NOT be referred to by this handler. + * + * sched_setparam() is NEVER involved in PI or PP + * management. However it must deny a priority update if it + * contradicts an ongoing boost for @a thread. This is + * typically what the evl_set_effective_thread_priority() helper + * does for such handler. + * + * Returns true if the effective priority was updated + * (thread->cprio). + */ + bool (*sched_setparam)(struct evl_thread *thread, + const union evl_sched_param *p); + void (*sched_getparam)(struct evl_thread *thread, + union evl_sched_param *p); + int (*sched_chkparam)(struct evl_thread *thread, + const union evl_sched_param *p); + void (*sched_trackprio)(struct evl_thread *thread, + const union evl_sched_param *p); + void (*sched_ceilprio)(struct evl_thread *thread, int prio); + /* Prep work for assigning a policy to a thread. */ + int (*sched_declare)(struct evl_thread *thread, + const union evl_sched_param *p); + void (*sched_forget)(struct evl_thread *thread); + void (*sched_kick)(struct evl_thread *thread); + const char *(*sched_name)(struct evl_thread *thread); + ssize_t (*sched_show)(struct evl_thread *thread, + char *buf, ssize_t count); + ssize_t (*sched_control)(int cpu, union evl_sched_ctlparam *ctlp, + union evl_sched_ctlinfo *infp); + int nthreads; + struct evl_sched_class *next; + int weight; + int policy; + const char *name; +}; + +#define EVL_CLASS_WEIGHT(n) (n * EVL_CLASS_WEIGHT_FACTOR) + +#define for_each_evl_thread(__thread) \ + list_for_each_entry(__thread, &evl_thread_list, next) + +static inline struct evl_rq *evl_cpu_rq(int cpu) +{ + return &per_cpu(evl_runqueues, cpu); +} + +static inline struct evl_rq *this_evl_rq(void) +{ + /* IRQs off */ + return raw_cpu_ptr(&evl_runqueues); +} + +static inline struct evl_thread *this_evl_rq_thread(void) +{ + return this_evl_rq()->curr; +} + +/* Test resched flag of given rq. */ +static inline int evl_need_resched(struct evl_rq *rq) +{ + return rq->flags & RQ_SCHED; +} + +/* Set resched flag for the current rq. */ +static inline void evl_set_self_resched(struct evl_rq *rq) +{ + assert_hard_lock(&rq->lock); + rq->flags |= RQ_SCHED; +} + +/* Set resched flag for the given rq. */ +#ifdef CONFIG_SMP + +static inline bool is_evl_cpu(int cpu) +{ + return !!cpumask_test_cpu(cpu, &evl_oob_cpus); +} + +static inline int evl_rq_cpu(struct evl_rq *rq) +{ + return rq->cpu; +} + +static inline void evl_set_resched(struct evl_rq *rq) +{ + struct evl_rq *this_rq = this_evl_rq(); + + assert_hard_lock(&rq->lock); /* Implies hard irqs are off. */ + + if (this_rq == rq) { + this_rq->flags |= RQ_SCHED; + } else if (!evl_need_resched(rq)) { + rq->flags |= RQ_SCHED; + /* + * The following updates change CPU-local data and + * hard irqs are off on the current CPU, so this is + * safe despite that we don't hold this_rq->lock. + * + * NOTE: raising RQ_SCHED in the local_flags too + * ensures that the current CPU will pass through + * evl_schedule() to __evl_schedule() at the next + * opportunity for sending the resched IPIs (see + * test_resched()). + */ + this_rq->local_flags |= RQ_SCHED; + cpumask_set_cpu(evl_rq_cpu(rq), &this_rq->resched_cpus); + } +} + +static inline bool is_threading_cpu(int cpu) +{ + return !!cpumask_test_cpu(cpu, &evl_cpu_affinity); +} + +void evl_migrate_thread(struct evl_thread *thread, + struct evl_rq *dst_rq); + +#else /* !CONFIG_SMP */ + +static inline bool is_evl_cpu(int cpu) +{ + return true; +} + +static inline int evl_rq_cpu(struct evl_rq *rq) +{ + return 0; +} + +static inline void evl_set_resched(struct evl_rq *rq) +{ + evl_set_self_resched(rq); +} + +static inline bool is_threading_cpu(int cpu) +{ + return true; +} + +static inline +void evl_migrate_thread(struct evl_thread *thread, + struct evl_rq *dst_rq) +{ } + +#endif /* !CONFIG_SMP */ + +void evl_start_ptsync(struct evl_thread *stopper); + +#define for_each_evl_cpu(cpu) \ + for_each_online_cpu(cpu) \ + if (is_evl_cpu(cpu)) + +void __evl_schedule(void); + +static inline void evl_schedule(void) +{ + struct evl_rq *this_rq = this_evl_rq(); + + /* + * If we race here reading the rq state locklessly because of + * a CPU migration, we must be running over the in-band stage, + * in which case the call to __evl_schedule() will be + * escalated to the oob stage where migration cannot happen, + * ensuring safe access to the runqueue state. + * + * Remote RQ_SCHED requests are paired with out-of-band IPIs + * running on the oob stage by definition, so we can't miss + * them here. + * + * Finally, RQ_IRQ is always tested from the CPU which handled + * an out-of-band interrupt, there is no coherence issue. + */ + if (((this_rq->flags|this_rq->local_flags) & (RQ_IRQ|RQ_SCHED)) != RQ_SCHED) + return; + + if (likely(running_oob())) { + __evl_schedule(); + return; + } + + run_oob_call((int (*)(void *))__evl_schedule, NULL); +} + +int evl_switch_oob(void); + +void evl_switch_inband(int cause); + +void evl_switch_inband_details(int cause, union evl_value details); + +static inline int evl_preempt_count(void) +{ + return dovetail_current_state()->preempt_count; +} + +static inline void __evl_disable_preempt(void) +{ + dovetail_current_state()->preempt_count++; +} + +static inline void __evl_enable_preempt(void) +{ + if (--dovetail_current_state()->preempt_count == 0) + evl_schedule(); +} + +#ifdef CONFIG_EVL_DEBUG_CORE + +void evl_disable_preempt(void); +void evl_enable_preempt(void); + +#else + +static inline void evl_disable_preempt(void) +{ + __evl_disable_preempt(); +} + +static inline void evl_enable_preempt(void) +{ + __evl_enable_preempt(); +} + +#endif + +static inline bool evl_in_irq(void) +{ + return !!(this_evl_rq()->local_flags & RQ_IRQ); +} + +static inline bool evl_is_inband(void) +{ + return !!(this_evl_rq_thread()->state & EVL_T_ROOT); +} + +static inline bool evl_cannot_block(void) +{ + return evl_in_irq() || evl_is_inband(); +} + +#define evl_get_thread_rq(__thread, __flags) \ + ({ \ + struct evl_rq *__rq; \ + raw_spin_lock_irqsave(&(__thread)->lock, __flags); \ + __rq = (__thread)->rq; \ + raw_spin_lock(&__rq->lock); \ + __rq; \ + }) + +#define evl_put_thread_rq(__thread, __rq, __flags) \ + do { \ + raw_spin_unlock(&(__rq)->lock); \ + raw_spin_unlock_irqrestore(&(__thread)->lock, __flags); \ + } while (0) + +#define evl_put_thread_rq_check(__thread, __rq, __flags) \ + do { \ + evl_put_thread_rq_check_noirq(__thread, __rq); \ + hard_local_irq_restore(__flags); \ + } while (0) + +#define evl_get_thread_rq_noirq(__thread) \ + ({ \ + struct evl_rq *__rq; \ + raw_spin_lock(&(__thread)->lock); \ + __rq = (__thread)->rq; \ + raw_spin_lock(&__rq->lock); \ + __rq; \ + }) + +#define evl_put_thread_rq_noirq(__thread, __rq) \ + do { \ + raw_spin_unlock(&(__rq)->lock); \ + raw_spin_unlock(&(__thread)->lock); \ + } while (0) + +/* + * Unpin the thread, checking for a pending requeue operation in a + * wait channel. See comment in drop_boosters() for details about the + * requirements to achieve correctness in this case. + * + * CAUTION: we should hold NO lock on entry to this macro, at the very + * least we must not hold any wchan or thread lock, otherwise an ABBA + * issue is certain. + */ +#define evl_put_thread_rq_check_noirq(__thread, __rq) \ + do { \ + bool __need_requeue = (__thread)->info & EVL_T_WCHAN; \ + if (__need_requeue) \ + (__thread)->info &= ~EVL_T_WCHAN; \ + evl_put_thread_rq_noirq(__thread, __rq); \ + if (__need_requeue) \ + evl_adjust_wait_priority(__thread); \ + } while (0) + +bool evl_set_effective_thread_priority(struct evl_thread *thread, + int prio); + +#include +#include + +void evl_putback_thread(struct evl_thread *thread); + +int evl_set_thread_policy_locked(struct evl_thread *thread, + struct evl_sched_class *sched_class, + const union evl_sched_param *p); + +int evl_set_thread_policy(struct evl_thread *thread, + struct evl_sched_class *sched_class, + const union evl_sched_param *p); + +bool evl_adjust_thread_boost(struct evl_thread *thread); + +static inline int evl_init_rq_thread(struct evl_thread *thread) +{ + int ret = 0; + + evl_init_idle_thread(thread); + evl_init_fifo_thread(thread); +#ifdef CONFIG_EVL_SCHED_QUOTA + ret = evl_quota_init_thread(thread); + if (ret) + return ret; +#endif +#ifdef CONFIG_EVL_SCHED_TP + ret = evl_tp_init_thread(thread); + if (ret) + return ret; +#endif + + return ret; +} + +/* rq->lock held, hard irqs off */ +static inline void evl_sched_yield(struct evl_rq *rq) +{ + struct evl_thread *curr = rq->curr; + struct evl_sched_class *sched_class = curr->sched_class; + + assert_hard_lock(&rq->lock); + + /* + * A thread may yield the CPU manually only when 1) it is + * currently unblocked, 2) it runs within its own scheduling + * class which excludes temporary PI boosts, 3) preemption is + * enabled. + */ + if (sched_class->sched_yield && + !(curr->state & EVL_THREAD_BLOCK_BITS) && + sched_class == curr->base_class && + evl_preempt_count() == 0) + sched_class->sched_yield(curr); +} + +static inline +int evl_check_schedparams(struct evl_sched_class *sched_class, + struct evl_thread *thread, + const union evl_sched_param *p) +{ + int ret = 0; + + assert_thread_pinned(thread); + + if (sched_class->sched_chkparam) + ret = sched_class->sched_chkparam(thread, p); + + return ret; +} + +static inline +int evl_declare_thread(struct evl_sched_class *sched_class, + struct evl_thread *thread, + const union evl_sched_param *p) +{ + int ret; + + assert_thread_pinned(thread); + + if (sched_class->sched_declare) { + ret = sched_class->sched_declare(thread, p); + if (ret) + return ret; + } + if (sched_class != thread->base_class) + sched_class->nthreads++; + + return 0; +} + +static inline int evl_calc_weighted_prio(struct evl_sched_class *sched_class, + int prio) +{ + return prio + sched_class->weight; +} + +static __always_inline void evl_enqueue_thread(struct evl_thread *thread) +{ + struct evl_sched_class *sched_class = thread->sched_class; + + assert_thread_pinned(thread); + + /* + * Enqueue for next pick: i.e. move to end of current priority + * group (i.e. FIFO). + */ + if (likely(sched_class == &evl_sched_fifo)) + __evl_enqueue_fifo_thread(thread); + else if (sched_class != &evl_sched_idle) + sched_class->sched_enqueue(thread); +} + +static __always_inline void evl_dequeue_thread(struct evl_thread *thread) +{ + struct evl_sched_class *sched_class = thread->sched_class; + + assert_thread_pinned(thread); + + /* + * Pull from the runnable thread queue. + */ + if (likely(sched_class == &evl_sched_fifo)) + __evl_dequeue_fifo_thread(thread); + else if (sched_class != &evl_sched_idle) + sched_class->sched_dequeue(thread); +} + +static __always_inline void evl_requeue_thread(struct evl_thread *thread) +{ + struct evl_sched_class *sched_class = thread->sched_class; + + assert_thread_pinned(thread); + + /* + * Put back at same place: i.e. requeue to head of current + * priority group (i.e. LIFO, used for preemption handling). + */ + if (likely(sched_class == &evl_sched_fifo)) + __evl_requeue_fifo_thread(thread); + else if (sched_class != &evl_sched_idle) + sched_class->sched_requeue(thread); +} + +static inline +bool evl_set_schedparam(struct evl_thread *thread, + const union evl_sched_param *p) +{ + assert_thread_pinned(thread); + + return thread->base_class->sched_setparam(thread, p); +} + +static inline void evl_get_schedparam(struct evl_thread *thread, + union evl_sched_param *p) +{ + assert_thread_pinned(thread); + + thread->sched_class->sched_getparam(thread, p); +} + +static inline void evl_track_priority(struct evl_thread *thread, + const union evl_sched_param *p) +{ + assert_thread_pinned(thread); + + thread->sched_class->sched_trackprio(thread, p); + thread->wprio = evl_calc_weighted_prio(thread->sched_class, thread->cprio); +} + +static inline void evl_ceil_priority(struct evl_thread *thread, int prio) +{ + assert_thread_pinned(thread); + + thread->sched_class->sched_ceilprio(thread, prio); + thread->wprio = evl_calc_weighted_prio(thread->sched_class, thread->cprio); +} + +static inline void evl_forget_thread(struct evl_thread *thread) +{ + struct evl_sched_class *sched_class = thread->base_class; + + assert_thread_pinned(thread); + + --sched_class->nthreads; + + if (sched_class->sched_forget) + sched_class->sched_forget(thread); +} + +static inline void evl_force_thread(struct evl_thread *thread) +{ + struct evl_sched_class *sched_class = thread->base_class; + + assert_thread_pinned(thread); + + if (sched_class->sched_kick) + sched_class->sched_kick(thread); +} + +struct evl_sched_group { +#ifdef CONFIG_EVL_SCHED_QUOTA + struct evl_quota_group quota; +#endif + struct list_head next; +}; + +struct evl_sched_class * +evl_find_sched_class(union evl_sched_param *param, + const struct evl_sched_attrs *attrs, + ktime_t *tslice_r); + +int __init evl_init_sched(void); + +void __init evl_cleanup_sched(void); + +#endif /* !_EVL_SCHED_H */ diff --git a/include/evl/sched/fifo.h b/include/evl/sched/fifo.h new file mode 100644 index 000000000..daa90c097 --- /dev/null +++ b/include/evl/sched/fifo.h @@ -0,0 +1,112 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Derived from Xenomai Cobalt, https://xenomai.org/ + * Copyright (C) 2008, 2018 Philippe Gerum + */ + +#ifndef _EVL_SCHED_FIFO_H +#define _EVL_SCHED_FIFO_H + +#ifndef _EVL_SCHED_H +#error "please don't include evl/sched/fifo.h directly" +#endif + +/* + * EVL's SCHED_FIFO class is meant to map onto the inband SCHED_FIFO + * priority scale when applied to user threads. EVL kthreads may use a + * couple of levels more, from EVL_CORE_MIN_PRIO to EVL_CORE_MAX_PRIO. + */ +#define EVL_FIFO_MIN_PRIO 1 +#define EVL_FIFO_MAX_PRIO (MAX_RT_PRIO - 1) + +extern struct evl_sched_class evl_sched_fifo; + +static inline void __evl_requeue_fifo_thread(struct evl_thread *thread) +{ + evl_add_schedq(&thread->rq->fifo.runnable, thread); +} + +static inline void __evl_enqueue_fifo_thread(struct evl_thread *thread) +{ + evl_add_schedq_tail(&thread->rq->fifo.runnable, thread); +} + +static inline void __evl_dequeue_fifo_thread(struct evl_thread *thread) +{ + evl_del_schedq(&thread->rq->fifo.runnable, thread); +} + +static inline +int __evl_chk_fifo_schedparam(struct evl_thread *thread, + const union evl_sched_param *p) +{ + int min = EVL_FIFO_MIN_PRIO, max = EVL_FIFO_MAX_PRIO; + + if (!(thread->state & EVL_T_USER)) { + min = EVL_CORE_MIN_PRIO; + max = EVL_CORE_MAX_PRIO; + } + + if (p->fifo.prio < min || p->fifo.prio > max) + return -EINVAL; + + return 0; +} + +static inline +bool __evl_set_fifo_schedparam(struct evl_thread *thread, + const union evl_sched_param *p) +{ + bool ret = evl_set_effective_thread_priority(thread, p->fifo.prio); + + if (!(thread->state & EVL_T_BOOST)) + thread->state &= ~EVL_T_WEAK; + + return ret; +} + +static inline +void __evl_get_fifo_schedparam(struct evl_thread *thread, + union evl_sched_param *p) +{ + p->fifo.prio = thread->cprio; +} + +static inline +void __evl_track_fifo_priority(struct evl_thread *thread, + const union evl_sched_param *p) +{ + if (p) + thread->cprio = p->fifo.prio; /* Force update. */ + else { + thread->cprio = thread->bprio; + /* Leaving PI/PP, so neither boosted nor weak. */ + thread->state &= ~EVL_T_WEAK; + } +} + +static inline +void __evl_ceil_fifo_priority(struct evl_thread *thread, int prio) +{ + /* + * The FIFO class supports the widest priority range from + * EVL_CORE_MIN_PRIO to EVL_CORE_MAX_PRIO inclusive, no need + * to cap the priority argument which is guaranteed to be in + * this range. + */ + thread->cprio = prio; +} + +static inline +void __evl_forget_fifo_thread(struct evl_thread *thread) +{ +} + +static inline +int evl_init_fifo_thread(struct evl_thread *thread) +{ + return 0; +} + +#endif /* !_EVL_SCHED_FIFO_H */ diff --git a/include/evl/sched/idle.h b/include/evl/sched/idle.h new file mode 100644 index 000000000..3f3c55a1a --- /dev/null +++ b/include/evl/sched/idle.h @@ -0,0 +1,53 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Derived from Xenomai Cobalt, https://xenomai.org/ + * Copyright (C) 2008, 2018 Philippe Gerum + */ + +#ifndef _EVL_SCHED_IDLE_H +#define _EVL_SCHED_IDLE_H + +#ifndef _EVL_SCHED_H +#error "please don't include evl/sched/idle.h directly" +#endif + +/* Idle priority level - actually never used for indexing. */ +#define EVL_IDLE_PRIO -1 + +extern struct evl_sched_class evl_sched_idle; + +static inline bool __evl_set_idle_schedparam(struct evl_thread *thread, + const union evl_sched_param *p) +{ + thread->state &= ~EVL_T_WEAK; + return evl_set_effective_thread_priority(thread, p->idle.prio); +} + +static inline void __evl_get_idle_schedparam(struct evl_thread *thread, + union evl_sched_param *p) +{ + p->idle.prio = thread->cprio; +} + +static inline void __evl_track_idle_priority(struct evl_thread *thread, + const union evl_sched_param *p) +{ + if (p) + /* Inheriting a priority-less class makes no sense. */ + EVL_WARN_ON_ONCE(CORE, 1); + else + thread->cprio = EVL_IDLE_PRIO; +} + +static inline void __evl_ceil_idle_priority(struct evl_thread *thread, int prio) +{ + EVL_WARN_ON_ONCE(CORE, 1); +} + +static inline int evl_init_idle_thread(struct evl_thread *thread) +{ + return 0; +} + +#endif /* !_EVL_SCHED_IDLE_H */ diff --git a/include/evl/sched/param.h b/include/evl/sched/param.h new file mode 100644 index 000000000..342c3affe --- /dev/null +++ b/include/evl/sched/param.h @@ -0,0 +1,45 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Derived from Xenomai Cobalt, https://xenomai.org/ + * Copyright (C) 2008, 2018 Philippe Gerum + */ + +#ifndef _EVL_SCHED_PARAM_H +#define _EVL_SCHED_PARAM_H + +struct evl_idle_param { + int prio; +}; + +struct evl_weak_param { + int prio; +}; + +struct evl_fifo_param { + int prio; +}; + +struct evl_quota_param { + int prio; + int tgid; /* thread group id. */ +}; + +struct evl_tp_param { + int prio; + int ptid; /* partition id. */ +}; + +union evl_sched_param { + struct evl_idle_param idle; + struct evl_fifo_param fifo; + struct evl_weak_param weak; +#ifdef CONFIG_EVL_SCHED_QUOTA + struct evl_quota_param quota; +#endif +#ifdef CONFIG_EVL_SCHED_TP + struct evl_tp_param tp; +#endif +}; + +#endif /* !_EVL_SCHED_PARAM_H */ diff --git a/include/evl/sched/queue.h b/include/evl/sched/queue.h new file mode 100644 index 000000000..93c874d24 --- /dev/null +++ b/include/evl/sched/queue.h @@ -0,0 +1,170 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Derived from Xenomai Cobalt, https://xenomai.org/ + * Copyright (C) 2008, 2018 Philippe Gerum + */ + +#ifndef _EVL_SCHED_QUEUE_H +#define _EVL_SCHED_QUEUE_H + +#include +#include + +/* + * EVL core priority scale. We reserve a couple of additional priority + * levels above the highest inband kthread priority (MAX_RT_PRIO-1), + * which is guaranteed not to be less than the highest EVL user task + * priority (MAX_RT_PRIO-1) we use for SCHED_FIFO. Those extra levels + * can be used for EVL kthreads which must top the priority of any + * userland thread. + */ +#define EVL_CORE_MIN_PRIO 0 +#define EVL_CORE_MAX_PRIO (MAX_RT_PRIO + 1) +#define EVL_CORE_NR_PRIO (EVL_CORE_MAX_PRIO - EVL_CORE_MIN_PRIO + 1) + +#define EVL_CLASS_WEIGHT_FACTOR 1024 + +#ifdef CONFIG_EVL_SCHED_SCALABLE + +#define EVL_MLQ_LEVELS EVL_CORE_NR_PRIO + +#if EVL_CORE_NR_PRIO > EVL_CLASS_WEIGHT_FACTOR || \ + EVL_CORE_NR_PRIO > EVL_MLQ_LEVELS +#error "EVL_MLQ_LEVELS is too low" +#endif + +struct evl_sched_queue { + int elems; + DECLARE_BITMAP(prio_map, EVL_MLQ_LEVELS); + struct list_head heads[EVL_MLQ_LEVELS]; +}; + +void evl_init_schedq(struct evl_sched_queue *q); + +struct evl_thread *__evl_get_schedq(struct evl_sched_queue *q); + +static __always_inline +struct evl_thread *evl_get_schedq(struct evl_sched_queue *q) +{ + if (!q->elems) + return NULL; + + return __evl_get_schedq(q); +} + +static __always_inline +int evl_get_schedq_weight(struct evl_sched_queue *q) +{ + /* Highest priorities are mapped to lowest array elements. */ + return find_first_bit(q->prio_map, EVL_MLQ_LEVELS); +} + +static __always_inline +int get_qindex(struct evl_sched_queue *q, int prio) +{ + /* + * find_first_bit() is used to scan the bitmap, so the lower + * the index value, the higher the priority. + */ + return EVL_MLQ_LEVELS - prio - 1; +} + +static __always_inline +struct list_head *add_q(struct evl_sched_queue *q, int prio) +{ + struct list_head *head; + int idx; + + idx = get_qindex(q, prio); + head = q->heads + idx; + q->elems++; + + /* New item is not linked yet. */ + if (list_empty(head)) + __set_bit(idx, q->prio_map); + + return head; +} + +static __always_inline +void evl_add_schedq(struct evl_sched_queue *q, + struct evl_thread *thread) +{ + struct list_head *head = add_q(q, thread->cprio); + list_add(&thread->rq_next, head); +} + +static __always_inline +void evl_add_schedq_tail(struct evl_sched_queue *q, + struct evl_thread *thread) +{ + struct list_head *head = add_q(q, thread->cprio); + list_add_tail(&thread->rq_next, head); +} + +static __always_inline +void __evl_del_schedq(struct evl_sched_queue *q, + struct list_head *entry, int idx) +{ + struct list_head *head = q->heads + idx; + + list_del(entry); + q->elems--; + + if (list_empty(head)) + __clear_bit(idx, q->prio_map); +} + +static __always_inline +void evl_del_schedq(struct evl_sched_queue *q, + struct evl_thread *thread) +{ + __evl_del_schedq(q, &thread->rq_next, get_qindex(q, thread->cprio)); +} + +#else /* !CONFIG_EVL_SCHED_SCALABLE */ + +struct evl_sched_queue { + struct list_head head; +}; + +static __always_inline +void evl_init_schedq(struct evl_sched_queue *q) +{ + INIT_LIST_HEAD(&q->head); +} + +static __always_inline +struct evl_thread *evl_get_schedq(struct evl_sched_queue *q) +{ + if (list_empty(&q->head)) + return NULL; + + return list_get_entry(&q->head, struct evl_thread, rq_next); +} + +static __always_inline +void evl_add_schedq(struct evl_sched_queue *q, + struct evl_thread *thread) +{ + list_add_prilf(thread, &q->head, cprio, rq_next); +} + +static __always_inline +void evl_add_schedq_tail(struct evl_sched_queue *q, + struct evl_thread *thread) +{ + list_add_priff(thread, &q->head, cprio, rq_next); +} + +static __always_inline +void evl_del_schedq(struct evl_sched_queue *q, + struct evl_thread *thread) +{ + list_del(&thread->rq_next); +} + +#endif /* CONFIG_EVL_SCHED_SCALABLE */ + +#endif /* !_EVL_SCHED_QUEUE_H */ diff --git a/include/evl/sched/quota.h b/include/evl/sched/quota.h new file mode 100644 index 000000000..dfe3b7390 --- /dev/null +++ b/include/evl/sched/quota.h @@ -0,0 +1,76 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Derived from Xenomai Cobalt, https://xenomai.org/ + * Copyright (C) 2013, 2018 Philippe Gerum + */ + +#ifndef _EVL_SCHED_QUOTA_H +#define _EVL_SCHED_QUOTA_H + +#ifndef _EVL_SCHED_H +#error "please don't include evl/sched/quota.h directly" +#endif + +#ifdef CONFIG_EVL_SCHED_QUOTA + +#define EVL_QUOTA_MIN_PRIO EVL_FIFO_MIN_PRIO +#define EVL_QUOTA_MAX_PRIO EVL_FIFO_MAX_PRIO +#define EVL_QUOTA_NR_PRIO \ + (EVL_QUOTA_MAX_PRIO - EVL_QUOTA_MIN_PRIO + 1) + +extern struct evl_sched_class evl_sched_quota; + +struct evl_quota_group { + struct evl_rq *rq; + ktime_t quota; + ktime_t quota_peak; + ktime_t run_start; + ktime_t run_budget; + ktime_t run_credit; + struct list_head members; + struct list_head expired; + struct list_head next; + int nr_active; + int nr_threads; + int tgid; + int quota_percent; + int quota_peak_percent; +}; + +struct evl_sched_quota { + ktime_t period; + struct evl_timer refill_timer; + struct evl_timer limit_timer; + struct list_head groups; +}; + +static inline int evl_quota_init_thread(struct evl_thread *thread) +{ + thread->quota = NULL; + INIT_LIST_HEAD(&thread->quota_expired); + + return 0; +} + +int evl_quota_create_group(struct evl_quota_group *tg, + struct evl_rq *rq, + int *quota_sum_r); + +int evl_quota_destroy_group(struct evl_quota_group *tg, + int force, + int *quota_sum_r); + +void evl_quota_set_limit(struct evl_quota_group *tg, + int quota_percent, int quota_peak_percent, + int *quota_sum_r); + +int evl_quota_sum_all(struct evl_rq *rq); + +void evl_set_quota_period(ktime_t period); + +ktime_t evl_get_quota_period(void); + +#endif /* !CONFIG_EVL_SCHED_QUOTA */ + +#endif /* !_EVL_SCHED_QUOTA_H */ diff --git a/include/evl/sched/tp.h b/include/evl/sched/tp.h new file mode 100644 index 000000000..00db7845e --- /dev/null +++ b/include/evl/sched/tp.h @@ -0,0 +1,57 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Derived from Xenomai Cobalt, https://xenomai.org/ + * Copyright (C) 2008, 2019 Philippe Gerum + */ + +#ifndef _EVL_SCHED_TP_H +#define _EVL_SCHED_TP_H + +#ifndef _EVL_SCHED_H +#error "please don't include evl/sched/tp.h directly" +#endif + +#ifdef CONFIG_EVL_SCHED_TP + +#define EVL_TP_MIN_PRIO EVL_FIFO_MIN_PRIO +#define EVL_TP_MAX_PRIO EVL_FIFO_MAX_PRIO +#define EVL_TP_NR_PRIO (EVL_TP_MAX_PRIO - EVL_TP_MIN_PRIO + 1) + +extern struct evl_sched_class evl_sched_tp; + +struct evl_tp_window { + ktime_t w_offset; + int w_part; +}; + +struct evl_tp_schedule { + int pwin_nr; + ktime_t tf_duration; + atomic_t refcount; + struct evl_tp_window pwins[0]; +}; + +struct evl_sched_tp { + struct evl_tp_rq { + struct evl_sched_queue runnable; + } partitions[CONFIG_EVL_SCHED_TP_NR_PART]; + struct evl_tp_rq idle; + struct evl_tp_rq *tps; + struct evl_timer tf_timer; + struct evl_tp_schedule *gps; + int wnext; + ktime_t tf_start; + struct list_head threads; +}; + +static inline int evl_tp_init_thread(struct evl_thread *thread) +{ + thread->tps = NULL; + + return 0; +} + +#endif /* !CONFIG_EVL_SCHED_TP */ + +#endif /* !_EVL_SCHED_TP_H */ diff --git a/include/evl/sched/weak.h b/include/evl/sched/weak.h new file mode 100644 index 000000000..60cc4ef96 --- /dev/null +++ b/include/evl/sched/weak.h @@ -0,0 +1,30 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Derived from Xenomai Cobalt, https://xenomai.org/ + * Copyright (C) 2013, 2018 Philippe Gerum + */ + +#ifndef _EVL_SCHED_WEAK_H +#define _EVL_SCHED_WEAK_H + +#ifndef _EVL_SCHED_H +#error "please don't include evl/sched/weak.h directly" +#endif + +#define EVL_WEAK_MIN_PRIO 0 +#define EVL_WEAK_MAX_PRIO 99 +#define EVL_WEAK_NR_PRIO (EVL_WEAK_MAX_PRIO - EVL_WEAK_MIN_PRIO + 1) + +extern struct evl_sched_class evl_sched_weak; + +struct evl_sched_weak { + struct evl_sched_queue runnable; +}; + +static inline int evl_weak_init_thread(struct evl_thread *thread) +{ + return 0; +} + +#endif /* !_EVL_SCHED_WEAK_H */ diff --git a/include/evl/sem.h b/include/evl/sem.h new file mode 100644 index 000000000..43d2b9e77 --- /dev/null +++ b/include/evl/sem.h @@ -0,0 +1,48 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2019 Philippe Gerum + */ + +#ifndef _EVL_SEM_H +#define _EVL_SEM_H + +#include +#include + +struct evl_ksem { + struct evl_wait_queue wait; + unsigned int value; +}; + +#define EVL_KSEM_INITIALIZER(__name, __value) { \ + .wait = EVL_WAIT_INITIALIZER((__name).wait), \ + .value = (__value), \ + } + +#define DEFINE_EVL_KSEM(__name, __value) \ + struct evl_ksem __name = EVL_KSEM_INITIALIZER(__name, __value) + +static inline void evl_init_ksem(struct evl_ksem *ksem, unsigned int value) +{ + ksem->value = value; + evl_init_wait(&ksem->wait, &evl_mono_clock, EVL_WAIT_PRIO); +} + +static inline void evl_destroy_ksem(struct evl_ksem *ksem) +{ + evl_destroy_wait(&ksem->wait); +} + +int evl_down_timeout(struct evl_ksem *ksem, + ktime_t timeout); + +int evl_down(struct evl_ksem *ksem); + +int evl_trydown(struct evl_ksem *ksem); + +void evl_up(struct evl_ksem *ksem); + +void evl_broadcast(struct evl_ksem *ksem); + +#endif /* !_EVL_SEM_H */ diff --git a/include/evl/stat.h b/include/evl/stat.h new file mode 100644 index 000000000..a94aa709c --- /dev/null +++ b/include/evl/stat.h @@ -0,0 +1,141 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Derived from Xenomai Cobalt, https://xenomai.org/ + * Copyright (C) 2006 Jan Kiszka . + * Copyright (C) 2006 Dmitry Adamushko + * Copyright (C) 2008, 2018 Philippe Gerum + */ + +#ifndef _EVL_STAT_H +#define _EVL_STAT_H + +#include + +struct evl_rq; + +#ifdef CONFIG_EVL_RUNSTATS + +struct evl_account { + ktime_t start; /* Start of execution time accumulation */ + ktime_t total; /* Accumulated execution time */ +}; + +/* + * Return current date which can be passed to other accounting + * services for immediate accounting. We do not use sched_clock() on + * purpose: its worst case execution time may be really bad under some + * combination of clock data updates and high cache pressure. + */ +static inline ktime_t evl_get_timestamp(void) +{ + return evl_read_clock(&evl_mono_clock); +} + +static inline ktime_t evl_get_account_total(struct evl_account *account) +{ + return account->total; +} + +/* + * Reset statistics from inside the accounted entity (e.g. after CPU + * migration). + */ +static inline void evl_reset_account(struct evl_account *account) +{ + account->total = 0; + account->start = evl_get_timestamp(); +} + +/* + * Accumulate the time spent for the current account until now. + * CAUTION: all changes must be committed before changing the + * current_account reference in rq. + */ +#define evl_update_account(__rq) \ + do { \ + ktime_t __now = evl_get_timestamp(); \ + (__rq)->current_account->total += \ + __now - (__rq)->last_account_switch; \ + (__rq)->last_account_switch = __now; \ + smp_wmb(); \ + } while (0) + +/* Obtain last account switch date of considered runqueue */ +#define evl_get_last_account_switch(__rq) ((__rq)->last_account_switch) + +/* + * Update the current account reference, returning the previous one. + */ +#define evl_set_current_account(__rq, __new_account) \ + ({ \ + struct evl_account *__prev; \ + __prev = (struct evl_account *) \ + xchg(&(__rq)->current_account, (__new_account)); \ + __prev; \ + }) + +/* + * Finalize an account (no need to accumulate the exectime, just mark + * the switch date and set the new account). + */ +#define evl_close_account(__rq, __new_account) \ + do { \ + (__rq)->last_account_switch = \ + evl_get_timestamp(); \ + (__rq)->current_account = (__new_account); \ + } while (0) + +struct evl_counter { + unsigned long counter; +}; + +static inline unsigned long evl_inc_counter(struct evl_counter *c) +{ + return c->counter++; +} + +static inline unsigned long evl_get_counter(struct evl_counter *c) +{ + return c->counter; +} + +static inline +void evl_set_counter(struct evl_counter *c, unsigned long value) +{ + c->counter = value; +} + +#else /* !CONFIG_EVL_RUNSTATS */ + +struct evl_account { +}; + +#define evl_get_timestamp() ({ 0; }) +#define evl_get_account_total(__account) ({ 0; }) +#define evl_reset_account(__account) do { } while (0) +#define evl_update_account(__rq) do { } while (0) +#define evl_set_current_account(__rq, __new_account) ({ (void)__rq; NULL; }) +#define evl_close_account(__rq, __new_account) do { } while (0) +#define evl_get_last_account_switch(__rq) ({ 0; }) + +struct evl_counter { +}; + +#define evl_inc_counter(__c) ({ do { } while(0); 0; }) +#define evl_get_counter(__c) ({ 0; }) +#define evl_set_counter(_c, __value) do { } while (0) + +#endif /* CONFIG_EVL_RUNSTATS */ + +/* + * Account the exectime of the current account until now, switch to + * new_account, return the previous one. + */ +#define evl_switch_account(__rq, __new_account) \ + ({ \ + evl_update_account(__rq); \ + evl_set_current_account(__rq, __new_account); \ + }) + +#endif /* !_EVL_STAT_H */ diff --git a/include/evl/stax.h b/include/evl/stax.h new file mode 100644 index 000000000..e82f3628d --- /dev/null +++ b/include/evl/stax.h @@ -0,0 +1,35 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2020 Philippe Gerum + */ + +#ifndef _EVL_STAX_H +#define _EVL_STAX_H + +#include +#include +#include +#include + +#define EVL_STAX_INBAND_SPIN BIT(0) + +struct evl_stax { + atomic_t gate; + int flags; + struct evl_wait_queue oob_wait; + wait_queue_head_t inband_wait; + struct irq_work irq_work; +}; + +void evl_init_stax(struct evl_stax *stax, int flags); + +void evl_destroy_stax(struct evl_stax *stax); + +int evl_lock_stax(struct evl_stax *stax); + +int evl_trylock_stax(struct evl_stax *stax); + +void evl_unlock_stax(struct evl_stax *stax); + +#endif /* !_EVL_STAX_H */ diff --git a/include/evl/thread.h b/include/evl/thread.h new file mode 100644 index 000000000..1164962cd --- /dev/null +++ b/include/evl/thread.h @@ -0,0 +1,434 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Derived from Xenomai Cobalt, https://xenomai.org/ + * Copyright (C) 2001, 2018 Philippe Gerum + * Copyright Gilles Chanteperdrix . + */ + +#ifndef _EVL_THREAD_H +#define _EVL_THREAD_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* All bits which may cause an EVL thread to block in oob context. */ +#define EVL_THREAD_BLOCK_BITS (EVL_T_SUSP|EVL_T_PEND|EVL_T_DELAY| \ + EVL_T_WAIT|EVL_T_DORMANT| \ + EVL_T_INBAND|EVL_T_HALT|EVL_T_PTSYNC) +/* Information bits an EVL thread may receive from a blocking op. */ +#define EVL_THREAD_INFO_MASK (EVL_T_RMID|EVL_T_TIMEO|EVL_T_BREAK| \ + EVL_T_KICKED|EVL_T_BCAST|EVL_T_NOMEM) +/* Mode bits configurable via EVL_THRIOC_SET/CLEAR_MODE. */ +#define EVL_THREAD_MODE_BITS (EVL_T_WOSS|EVL_T_WOLI|EVL_T_WOSX| \ + EVL_T_WOSO|EVL_T_HMSIG|EVL_T_HMOBS) + +/* + * These are special internal values of HM diags which are never sent + * to user-space, but specifically handled by evl_switch_inband(). + */ +#define EVL_HMDIAG_NONE 0 +#define EVL_HMDIAG_TRAP -1 + +struct evl_thread; +struct evl_rq; +struct evl_sched_class; +struct evl_poll_watchpoint; +struct evl_wait_channel; +struct evl_observable; +struct file; + +struct evl_init_thread_attr { + const struct cpumask *affinity; + struct evl_observable *observable; + int flags; + struct evl_sched_class *sched_class; + union evl_sched_param sched_param; +}; + +struct evl_thread { + hard_spinlock_t lock; + struct lock_class_key lock_key; /* lockdep disambiguation */ + + /* + * Shared thread-specific data, covered by ->lock. + */ + struct evl_rq *rq; + struct evl_sched_class *base_class; + struct evl_sched_class *sched_class; /* PI/PP sensitive. */ + + int bprio; + int cprio; /* PI/PP sensitive. */ + int wprio; /* cprio + scheduling class weight */ + + /* + * List of mutexes owned by this thread which specifically + * cause a priority boost due to one of the following + * reasons: + * + * - they are currently claimed by other thread(s) when + * enforcing the priority inheritance protocol (EVL_MUTEX_PI). + * + * - they require immediate priority ceiling (EVL_MUTEX_PP). + * + * This list is ordered by decreasing (weighted) priorities of + * waiters. + */ + struct list_head boosters; + struct evl_wait_channel *wchan; /* Wait channel @thread pends on */ + struct list_head wait_next; /* in wchan->wait_list */ + + struct evl_timer rtimer; /* Resource timer */ + struct evl_timer ptimer; /* Periodic timer */ + ktime_t rrperiod; /* Round-robin period (ns) */ + + /* + * Shared scheduler-specific data covered by both thread->lock + * AND thread->rq->lock. For such data, the first lock + * protects against the thread moving to a different rq, it + * may be omitted if the target cannot be subject to such + * migration (i.e. @thread == evl_this_rq()->curr, which + * implies that we are out-of-band and thus cannot trigger + * evl_migrate_thread()). The second one serializes with the + * scheduler core and must ALWAYS be taken for accessing this + * data. + */ + __u32 state; + __u32 info; +#ifdef CONFIG_EVL_SCHED_QUOTA + struct evl_quota_group *quota; + struct list_head quota_expired; /* evl_rq->quota.expired */ + struct list_head quota_next; /* evl_rq->quota.members */ +#endif +#ifdef CONFIG_EVL_SCHED_TP + struct evl_tp_rq *tps; + struct list_head tp_link; /* evl_rq->tp.threads */ +#endif + struct list_head rq_next; /* evl_rq->policy.runqueue */ + struct list_head next; /* in evl_thread_list */ + + /* + * Thread-local data only the owner may modify, therefore it + * may do so locklessly. + */ + struct dovetail_altsched_context altsched; + __u32 local_info; + void *wait_data; + struct { + struct evl_poll_watchpoint *table; + unsigned int generation; + int nr; + int active; + } poll_context; + atomic_t held_mutex_count; + struct irq_work inband_work; + struct { + struct evl_counter isw; /* in-band switches */ + struct evl_counter csw; /* context switches */ + struct evl_counter sc; /* OOB syscalls */ + struct evl_counter rwa; /* remote wakeups */ + struct evl_account account; /* exec time accounting */ + struct evl_account lastperiod; + } stat; + struct evl_user_window *u_window; + + /* Misc stuff. */ + + struct list_head owned_mutexes; /* Mutex(es) this thread currently owns */ + struct evl_element element; + struct cpumask affinity; + struct completion exited; + kernel_cap_t raised_cap; + struct list_head kill_next; + struct oob_mm_state *oob_mm; /* Mostly RO. */ + struct list_head ptsync_next; /* covered by oob_mm->lock. */ + struct evl_observable *observable; + char *name; +}; + +static inline void evl_sync_uwindow(struct evl_thread *curr) +{ + if (curr->u_window) { + curr->u_window->state = curr->state; + curr->u_window->info = curr->info; + } +} + +static inline +void evl_clear_sync_uwindow(struct evl_thread *curr, int state_bits) +{ + if (curr->u_window) { + curr->u_window->state = curr->state & ~state_bits; + curr->u_window->info = curr->info; + } +} + +static inline +void evl_set_sync_uwindow(struct evl_thread *curr, int state_bits) +{ + if (curr->u_window) { + curr->u_window->state = curr->state | state_bits; + curr->u_window->info = curr->info; + } +} + +static inline +void evl_double_thread_lock(struct evl_thread *t1, struct evl_thread *t2) +{ + EVL_WARN_ON_ONCE(CORE, t1 == t2); + EVL_WARN_ON_ONCE(CORE, !hard_irqs_disabled()); + + /* + * Prevent ABBA deadlock, always lock threads in address + * order. The caller guarantees t1 and t2 are distinct. + */ + if (t1 < t2) { + raw_spin_lock(&t1->lock); + raw_spin_lock(&t2->lock); + } else { + raw_spin_lock(&t2->lock); + raw_spin_lock(&t1->lock); + } +} + +void __evl_test_cancel(struct evl_thread *curr); + +void evl_discard_thread(struct evl_thread *thread); + +/* + * Might differ from this_evl_rq() if @current is running inband, and + * evl_migrate_thread() is pending until it switches back to oob. + */ +static inline struct evl_thread *evl_current(void) +{ + return dovetail_current_state()->thread; +} + +static inline +struct evl_rq *evl_thread_rq(struct evl_thread *thread) +{ + return thread->rq; +} + +static inline struct evl_rq *evl_current_rq(void) +{ + return evl_thread_rq(evl_current()); +} + +static inline +struct evl_thread *evl_thread_from_task(struct task_struct *p) +{ + return dovetail_task_state(p)->thread; +} + +static inline void evl_test_cancel(void) +{ + struct evl_thread *curr = evl_current(); + + if (curr && (curr->info & EVL_T_CANCELD)) + __evl_test_cancel(curr); +} + +static inline struct evl_subscriber *evl_get_subscriber(void) +{ + return dovetail_current_state()->subscriber; +} + +static inline void evl_set_subscriber(struct evl_subscriber *sbr) +{ + dovetail_current_state()->subscriber = sbr; +} + +ktime_t evl_get_thread_timeout(struct evl_thread *thread); + +ktime_t evl_get_thread_period(struct evl_thread *thread); + +int evl_init_thread(struct evl_thread *thread, + const struct evl_init_thread_attr *attr, + struct evl_rq *rq, + const char *fmt, ...); + +void evl_sleep_on_locked(ktime_t timeout, enum evl_tmode timeout_mode, + struct evl_clock *clock, + struct evl_wait_channel *wchan); + +void evl_sleep_on(ktime_t timeout, enum evl_tmode timeout_mode, + struct evl_clock *clock, + struct evl_wait_channel *wchan); + +void evl_wakeup_thread(struct evl_thread *thread, + int mask, int info); + +void evl_hold_thread(struct evl_thread *thread, + int mask); + +void evl_release_thread(struct evl_thread *thread, + int mask, int info); + +void evl_unblock_thread(struct evl_thread *thread, + int reason); + +ktime_t evl_delay(ktime_t timeout, + enum evl_tmode timeout_mode, + struct evl_clock *clock); + +int evl_sleep_until(ktime_t timeout); + +int evl_sleep(ktime_t delay); + +int evl_set_period(struct evl_clock *clock, + ktime_t idate, + ktime_t period); + +int evl_wait_period(unsigned long *overruns_r); + +void evl_cancel_thread(struct evl_thread *thread); + +int evl_join_thread(struct evl_thread *thread, + bool uninterruptible); + +void evl_notify_thread(struct evl_thread *thread, + int tag, union evl_value details); + +void evl_get_thread_state(struct evl_thread *thread, + struct evl_thread_state *statebuf); + +int evl_detach_self(void); + +void evl_kick_thread(struct evl_thread *thread, + int info); + +void evl_demote_thread(struct evl_thread *thread); + +void evl_signal_thread(struct evl_thread *thread, + int sig, int arg); + +int evl_set_thread_schedparam_locked(struct evl_thread *thread, + struct evl_sched_class *sched_class, + const union evl_sched_param *sched_param); + +int evl_set_thread_schedparam(struct evl_thread *thread, + struct evl_sched_class *sched_class, + const union evl_sched_param *sched_param); + +int evl_killall(int mask); + +bool evl_is_thread_file(struct file *filp); + +void __evl_propagate_schedparam_change(struct evl_thread *curr); + +static inline void evl_propagate_schedparam_change(struct evl_thread *curr) +{ + if (curr->info & EVL_T_SCHEDP) + __evl_propagate_schedparam_change(curr); +} + +pid_t evl_get_inband_pid(struct evl_thread *thread); + +int activate_oob_mm_state(struct oob_mm_state *p); + +struct evl_kthread { + struct evl_thread thread; + struct completion done; + void (*threadfn)(void *arg); + int status; + void *arg; + struct irq_work irq_work; +}; + +int __evl_run_kthread(struct evl_kthread *kthread, int clone_flags); + +#define _evl_run_kthread(__kthread, __affinity, __fn, __arg, \ + __priority, __clone_flags, __fmt, __args...) \ + ({ \ + int __ret; \ + struct evl_init_thread_attr __iattr = { \ + .flags = 0, \ + .affinity = __affinity, \ + .observable = NULL, \ + .sched_class = &evl_sched_fifo, \ + .sched_param.fifo.prio = __priority, \ + }; \ + (__kthread)->threadfn = __fn; \ + (__kthread)->arg = __arg; \ + (__kthread)->status = 0; \ + init_completion(&(__kthread)->done); \ + __ret = evl_init_thread(&(__kthread)->thread, &__iattr, \ + NULL, __fmt, ##__args); \ + if (!__ret) \ + __ret = __evl_run_kthread(__kthread, __clone_flags); \ + __ret; \ + }) + +#define evl_run_kthread(__kthread, __fn, __arg, __priority, \ + __clone_flags, __fmt, __args...) \ + _evl_run_kthread(__kthread, &evl_oob_cpus, __fn, __arg, \ + __priority, __clone_flags, __fmt, ##__args) + +#define evl_run_kthread_on_cpu(__kthread, __cpu, __fn, __arg, \ + __priority, __clone_flags, __fmt, __args...) \ + _evl_run_kthread(__kthread, cpumask_of(__cpu), __fn, __arg, \ + __priority, __clone_flags, __fmt, ##__args) + +void evl_set_kthread_priority(struct evl_kthread *kthread, + int priority); + +static inline void evl_stop_kthread(struct evl_kthread *kthread) +{ + evl_cancel_thread(&kthread->thread); + evl_join_thread(&kthread->thread, true); +} + +static inline bool evl_kthread_should_stop(void) +{ + return !!(evl_current()->info & EVL_T_CANCELD); +} + +static inline +void evl_unblock_kthread(struct evl_kthread *kthread, + int reason) +{ + evl_unblock_thread(&kthread->thread, reason); +} + +static inline +int evl_join_kthread(struct evl_kthread *kthread, + bool uninterruptible) +{ + return evl_join_thread(&kthread->thread, uninterruptible); +} + +static inline struct evl_kthread * +evl_current_kthread(void) +{ + struct evl_thread *t = evl_current(); + + return !t || t->state & EVL_T_USER ? NULL : + container_of(t, struct evl_kthread, thread); +} + +struct evl_wait_channel * +evl_get_thread_wchan(struct evl_thread *thread); + +static inline void evl_put_thread_wchan(struct evl_wait_channel *wchan) +{ + assert_hard_lock(&wchan->lock); + raw_spin_unlock(&wchan->lock); +} + +#endif /* !_EVL_THREAD_H */ diff --git a/include/evl/tick.h b/include/evl/tick.h new file mode 100644 index 000000000..581bb106b --- /dev/null +++ b/include/evl/tick.h @@ -0,0 +1,63 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Derived from Xenomai Cobalt, https://xenomai.org/ + * Copyright (C) 2016 Philippe Gerum + */ + +#ifndef _EVL_TICK_H +#define _EVL_TICK_H + +#include +#include +#include +#include +#include +#include + +struct evl_rq; + +static inline void evl_program_local_tick(struct evl_clock *clock) +{ + struct evl_clock *master = clock->master; + + if (master->ops.program_local_shot) + master->ops.program_local_shot(master); +} + +static inline void evl_program_remote_tick(struct evl_clock *clock, + struct evl_rq *rq) +{ +#ifdef CONFIG_SMP + struct evl_clock *master = clock->master; + + if (master->ops.program_remote_shot) + master->ops.program_remote_shot(master, rq); +#endif +} + +/* hard IRQs off. */ +static inline void evl_notify_proxy_tick(struct evl_rq *this_rq) +{ + /* + * A proxy clock event device is active on this CPU, make it + * tick asap when the in-band code resumes; this will honour a + * previous set_next_ktime() request received from the kernel + * we have carried out using our core timing services. + */ + this_rq->local_flags &= ~RQ_TPROXY; + tick_notify_proxy(); +} + +int evl_enable_tick(void); + +void evl_disable_tick(void); + +void evl_notify_proxy_tick(struct evl_rq *this_rq); + +void evl_program_proxy_tick(struct evl_clock *clock); + +void evl_send_timer_ipi(struct evl_clock *clock, + struct evl_rq *rq); + +#endif /* !_EVL_TICK_H */ diff --git a/include/evl/timeout.h b/include/evl/timeout.h new file mode 100644 index 000000000..f41ff1045 --- /dev/null +++ b/include/evl/timeout.h @@ -0,0 +1,48 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2020 Philippe Gerum + */ + +#ifndef _EVL_TIMEOUT_H +#define _EVL_TIMEOUT_H + +#include + +/* + * Basic assumption throughout the code: ktime_t is a 64bit signed + * scalar type holding an internal time unit, which means that: + * + * - we may compare two ktime_t values using basic relational operators + * - we may check for nullness by comparing to 0 directly + * - we must use ktime_to_ns()/ns_to_ktime() helpers for converting + * to/from nanoseconds. + */ +#define EVL_INFINITE 0 +#define EVL_NONBLOCK KTIME_MAX + +static inline bool timeout_infinite(ktime_t kt) +{ + return kt == EVL_INFINITE; +} + +static inline bool timeout_nonblock(ktime_t kt) +{ + return kt == EVL_NONBLOCK; +} + +/* Timer modes */ +enum evl_tmode { + EVL_REL, + EVL_ABS, +}; + +/* + * So that readers do not need to pull evl/clock.h for defining timed + * object initializers which only refer to the built-in clock + * addresses in the common case. + */ +extern struct evl_clock evl_mono_clock, + evl_realtime_clock; + +#endif /* !_EVL_TIMEOUT_H */ diff --git a/include/evl/timer.h b/include/evl/timer.h new file mode 100644 index 000000000..c5ce4a0ff --- /dev/null +++ b/include/evl/timer.h @@ -0,0 +1,440 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Derived from Xenomai Cobalt, https://xenomai.org/ + * Copyright (C) 2001, 2018 Philippe Gerum + */ + +#ifndef _EVL_TIMER_H +#define _EVL_TIMER_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* Timer status */ +#define EVL_TIMER_DEQUEUED 0x00000001 +#define EVL_TIMER_KILLED 0x00000002 +#define EVL_TIMER_PERIODIC 0x00000004 +#define EVL_TIMER_FIRED 0x00000010 +#define EVL_TIMER_RUNNING 0x00000020 +#define EVL_TIMER_KGRAVITY 0x00000040 +#define EVL_TIMER_UGRAVITY 0x00000080 +#define EVL_TIMER_IGRAVITY 0 /* most conservative */ + +#define EVL_TIMER_GRAVITY_MASK (EVL_TIMER_KGRAVITY|EVL_TIMER_UGRAVITY) +#define EVL_TIMER_INIT_MASK EVL_TIMER_GRAVITY_MASK + +#ifdef CONFIG_EVL_TIMER_SCALABLE + +struct evl_tnode { + struct rb_node rb; + ktime_t date; +}; + +struct evl_tqueue { + struct rb_root root; + struct evl_tnode *head; +}; + +static inline void evl_init_tqueue(struct evl_tqueue *tq) +{ + tq->root = RB_ROOT; + tq->head = NULL; +} + +#define evl_destroy_tqueue(__tq) do { } while (0) + +static inline bool evl_tqueue_is_empty(struct evl_tqueue *tq) +{ + return tq->head == NULL; +} + +static inline +struct evl_tnode *evl_get_tqueue_head(struct evl_tqueue *tq) +{ + return tq->head; +} + +static inline +struct evl_tnode *evl_get_tqueue_next(struct evl_tqueue *tq, + struct evl_tnode *node) +{ + struct rb_node *_node = rb_next(&node->rb); + return _node ? container_of(_node, struct evl_tnode, rb) : NULL; +} + +static inline +void evl_remove_tnode(struct evl_tqueue *tq, struct evl_tnode *node) +{ + if (node == tq->head) + tq->head = evl_get_tqueue_next(tq, node); + + rb_erase(&node->rb, &tq->root); +} + +#define for_each_evl_tnode(__node, __tq) \ + for ((__node) = evl_get_tqueue_head(__tq); (__node); \ + (__node) = evl_get_tqueue_next(__tq, __node)) + +#else /* !CONFIG_EVL_TIMER_SCALABLE */ + +struct evl_tnode { + ktime_t date; + struct list_head next; +}; + +struct evl_tqueue { + struct list_head q; +}; + +static inline void evl_init_tqueue(struct evl_tqueue *tq) +{ + INIT_LIST_HEAD(&tq->q); +} + +#define evl_destroy_tqueue(__tq) do { } while (0) + +static inline bool evl_tqueue_is_empty(struct evl_tqueue *tq) +{ + return list_empty(&tq->q); +} + +static inline +struct evl_tnode *evl_get_tqueue_head(struct evl_tqueue *tq) +{ + if (list_empty(&tq->q)) + return NULL; + + return list_first_entry(&tq->q, struct evl_tnode, next); +} + +static inline +struct evl_tnode *evl_get_tqueue_next(struct evl_tqueue *tq, + struct evl_tnode *node) +{ + if (list_is_last(&node->next, &tq->q)) + return NULL; + + return list_entry(node->next.next, struct evl_tnode, next); +} + +static inline +void evl_insert_tnode(struct evl_tqueue *tq, + struct evl_tnode *node) +{ + struct evl_tnode *n; + + if (list_empty(&tq->q)) { + list_add(&node->next, &tq->q); + } else { + list_for_each_entry_reverse(n, &tq->q, next) { + if (n->date <= node->date) + break; + } + list_add(&node->next, &n->next); + } +} + +static inline +void evl_remove_tnode(struct evl_tqueue *tq, struct evl_tnode *node) +{ + list_del(&node->next); +} + +#define for_each_evl_tnode(__node, __tq) \ + list_for_each_entry(__node, &(__tq)->q, next) + +#endif /* CONFIG_EVL_TIMER_SCALABLE */ + +struct evl_rq; + +struct evl_timerbase { + hard_spinlock_t lock; + struct evl_tqueue q; +}; + +static inline struct evl_timerbase * +evl_percpu_timers(struct evl_clock *clock, int cpu) +{ + return per_cpu_ptr(clock->timerdata, cpu); +} + +static inline struct evl_timerbase * +evl_this_cpu_timers(struct evl_clock *clock) +{ + return raw_cpu_ptr(clock->timerdata); +} + +struct evl_timer { + struct evl_clock *clock; + struct evl_tnode node; + struct list_head adjlink; + int status; + ktime_t interval; /* 0 == oneshot */ + ktime_t start_date; + u64 consumed_ticks; /* advanced by evl_get_timer_overruns() */ + u64 periodic_ticks; +#ifdef CONFIG_SMP + struct evl_rq *rq; +#endif + struct evl_timerbase *base; + void (*handler)(struct evl_timer *timer); + const char *name; +#ifdef CONFIG_EVL_RUNSTATS + struct evl_counter scheduled; + struct evl_counter fired; +#endif /* CONFIG_EVL_RUNSTATS */ +}; + +#define evl_tdate(__timer) ((__timer)->node.date) + +void evl_start_timer(struct evl_timer *timer, + ktime_t value, + ktime_t interval); + +void __evl_stop_timer(struct evl_timer *timer); + +static inline int evl_timer_is_running(struct evl_timer *timer) +{ + return (timer->status & EVL_TIMER_RUNNING) != 0; +} + +static inline int evl_timer_is_periodic(struct evl_timer *timer) +{ + return (timer->status & EVL_TIMER_PERIODIC) != 0; +} + +static inline void evl_stop_timer(struct evl_timer *timer) +{ + if (evl_timer_is_running(timer)) + __evl_stop_timer(timer); +} + +void evl_destroy_timer(struct evl_timer *timer); + +static inline ktime_t evl_abs_timeout(struct evl_timer *timer, + ktime_t delta) +{ + return ktime_add(evl_read_clock(timer->clock), delta); +} + +#ifdef CONFIG_SMP +static inline struct evl_rq *evl_get_timer_rq(struct evl_timer *timer) +{ + return timer->rq; +} +#else /* !CONFIG_SMP */ +#define evl_get_timer_rq(t) this_evl_rq() +#endif /* !CONFIG_SMP */ + +/* + * timer base locked so that ->clock does not change under our + * feet. + */ +static inline unsigned long evl_get_timer_gravity(struct evl_timer *timer) +{ + struct evl_clock *clock = timer->clock; + + if (timer->status & EVL_TIMER_KGRAVITY) + return clock->gravity.kernel; + + if (timer->status & EVL_TIMER_UGRAVITY) + return clock->gravity.user; + + return clock->gravity.irq; +} + +/* timer base locked. */ +static inline void evl_update_timer_date(struct evl_timer *timer) +{ + evl_tdate(timer) = ktime_add_ns(timer->start_date, + (timer->periodic_ticks * ktime_to_ns(timer->interval)) + - evl_get_timer_gravity(timer)); +} + +static inline +ktime_t evl_get_timer_next_date(struct evl_timer *timer) +{ + return ktime_add_ns(timer->start_date, + timer->consumed_ticks * ktime_to_ns(timer->interval)); +} + +void __evl_init_timer(struct evl_timer *timer, + struct evl_clock *clock, + void (*handler)(struct evl_timer *timer), + struct evl_rq *rq, + const char *name, + int flags); + +void evl_set_timer_gravity(struct evl_timer *timer, + int gravity); + +#define evl_init_timer_on_rq(__timer, __clock, __handler, __rq, __flags) \ + __evl_init_timer(__timer, __clock, __handler, \ + __rq, #__handler, __flags) + +#define evl_init_timer_on_cpu(__timer, __cpu, __handler) \ + do { \ + struct evl_rq *__rq = evl_cpu_rq(__cpu); \ + evl_init_timer_on_rq(__timer, &evl_mono_clock, __handler, \ + __rq, EVL_TIMER_IGRAVITY); \ + } while (0) + +#define evl_init_timer(__timer, __handler) \ + evl_init_timer_on_rq(__timer, &evl_mono_clock, __handler, NULL, \ + EVL_TIMER_IGRAVITY) + +#ifdef CONFIG_EVL_RUNSTATS + +static inline +void evl_reset_timer_stats(struct evl_timer *timer) +{ + evl_set_counter(&timer->scheduled, 0); + evl_set_counter(&timer->fired, 0); +} + +static inline +void evl_account_timer_scheduled(struct evl_timer *timer) +{ + evl_inc_counter(&timer->scheduled); +} + +static inline +void evl_account_timer_fired(struct evl_timer *timer) +{ + evl_inc_counter(&timer->fired); +} + +#else /* !CONFIG_EVL_RUNSTATS */ + +static inline +void evl_reset_timer_stats(struct evl_timer *timer) { } + +static inline +void evl_account_timer_scheduled(struct evl_timer *timer) { } + +static inline +void evl_account_timer_fired(struct evl_timer *timer) { } + +#endif /* !CONFIG_EVL_RUNSTATS */ + +static inline +void evl_set_timer_name(struct evl_timer *timer, const char *name) +{ + timer->name = name; +} + +static inline +const char *evl_get_timer_name(struct evl_timer *timer) +{ + return timer->name; +} + +bool evl_timer_deactivate(struct evl_timer *timer); + +/* timer base locked. */ +static inline ktime_t evl_get_timer_expiry(struct evl_timer *timer) +{ + /* Ideal expiry date without anticipation (no gravity) */ + return ktime_add(evl_tdate(timer), + evl_get_timer_gravity(timer)); +} + +ktime_t evl_get_timer_date(struct evl_timer *timer); + +ktime_t __evl_get_timer_delta(struct evl_timer *timer); + +static inline ktime_t evl_get_timer_delta(struct evl_timer *timer) +{ + if (!evl_timer_is_running(timer)) + return EVL_INFINITE; + + return __evl_get_timer_delta(timer); +} + +static inline +ktime_t __evl_get_stopped_timer_delta(struct evl_timer *timer) +{ + return __evl_get_timer_delta(timer); +} + +static inline +ktime_t evl_get_stopped_timer_delta(struct evl_timer *timer) +{ + ktime_t t = __evl_get_stopped_timer_delta(timer); + + if (ktime_to_ns(t) <= 1) + return EVL_INFINITE; + + return t; +} + +static __always_inline +void evl_dequeue_timer(struct evl_timer *timer, + struct evl_tqueue *tq) +{ + evl_remove_tnode(tq, &timer->node); + timer->status |= EVL_TIMER_DEQUEUED; +} + +void evl_insert_tnode(struct evl_tqueue *tq, struct evl_tnode *node); + +/* timer base locked. */ +static __always_inline +void evl_enqueue_timer(struct evl_timer *timer, + struct evl_tqueue *tq) +{ + evl_insert_tnode(tq, &timer->node); + timer->status &= ~EVL_TIMER_DEQUEUED; + evl_account_timer_scheduled(timer); +} + +unsigned long evl_get_timer_overruns(struct evl_timer *timer); + +void evl_move_timer(struct evl_timer *timer, + struct evl_clock *clock, + struct evl_rq *rq); + +#ifdef CONFIG_SMP + +static inline void evl_prepare_timed_wait(struct evl_timer *timer, + struct evl_clock *clock, + struct evl_rq *rq) +{ + /* We may change the reference clock before waiting. */ + if (rq != timer->rq || clock != timer->clock) + evl_move_timer(timer, clock, rq); +} + +static inline bool evl_timer_on_rq(struct evl_timer *timer, + struct evl_rq *rq) +{ + return timer->rq == rq; +} + +#else /* ! CONFIG_SMP */ + +static inline void evl_prepare_timed_wait(struct evl_timer *timer, + struct evl_clock *clock, + struct evl_rq *rq) +{ + if (clock != timer->clock) + evl_move_timer(timer, clock, rq); +} + +static inline bool evl_timer_on_rq(struct evl_timer *timer, + struct evl_rq *rq) +{ + return true; +} + +#endif /* CONFIG_SMP */ + +#endif /* !_EVL_TIMER_H */ diff --git a/include/evl/uaccess.h b/include/evl/uaccess.h new file mode 100644 index 000000000..349e6ec7f --- /dev/null +++ b/include/evl/uaccess.h @@ -0,0 +1,28 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2020 Philippe Gerum + */ + +#ifndef _EVL_UACCESS_H +#define _EVL_UACCESS_H + +#include +#include + +static inline unsigned long __must_check +raw_copy_from_user_ptr64(void *to, u64 from_ptr, unsigned long n) +{ + return raw_copy_from_user(to, (void *)(long)from_ptr, n); +} + +static inline unsigned long __must_check +raw_copy_to_user_ptr64(u64 to, const void *from, unsigned long n) +{ + return raw_copy_to_user((void *)(long)to, from, n); +} + +#define evl_ptrval64(__ptr) ((u64)(long)(__ptr)) +#define evl_valptr64(__ptrval, __type) ((__type *)(long)(__ptrval)) + +#endif /* !_EVL_UACCESS_H */ diff --git a/include/evl/uio.h b/include/evl/uio.h new file mode 100644 index 000000000..00026af6c --- /dev/null +++ b/include/evl/uio.h @@ -0,0 +1,40 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2023 Philippe Gerum + */ + +#ifndef _EVL_UIO_H +#define _EVL_UIO_H + +#include + +struct iovec; +struct kvec; + +ssize_t evl_copy_to_uio(const struct iovec *iov, size_t iovlen, + const void *data, size_t len); + +ssize_t evl_copy_from_uio(const struct iovec *iov, size_t iovlen, + void *data, size_t len, size_t *remainder); + +struct iovec *evl_load_uio(const struct iovec __user *u_iov, + size_t iovlen, struct iovec *fast_iov); + +ssize_t evl_copy_from_uio_to_kvec(const struct iovec *iov, + size_t iovlen, size_t count, + struct kvec *kvec); + +static inline +size_t evl_iov_flat_length(const struct iovec *iov, int iovlen) +{ + size_t count; + int n; + + for (n = 0, count = 0; n < iovlen; n++) + count += iov[n].iov_len; + + return count; +} + +#endif /* !_EVL_UIO_H */ diff --git a/include/evl/wait.h b/include/evl/wait.h new file mode 100644 index 000000000..fd363331c --- /dev/null +++ b/include/evl/wait.h @@ -0,0 +1,151 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Derived from Xenomai Cobalt, https://xenomai.org/ + * Copyright (C) 2001, 2018 Philippe Gerum + */ + +#ifndef _EVL_WAIT_H +#define _EVL_WAIT_H + +#include +#include +#include +#include + +#define EVL_WAIT_FIFO 0 +#define EVL_WAIT_PRIO BIT(0) + +struct evl_thread; + +struct evl_wait_channel { + hard_spinlock_t lock; + struct evl_thread *owner; + bool (*requeue_wait)(struct evl_wait_channel *wchan, + struct evl_thread *waiter); + struct list_head wait_list; + const char *name; +}; + +struct evl_wait_queue { + int flags; + struct evl_clock *clock; + struct evl_wait_channel wchan; +}; + +#define EVL_WAIT_INITIALIZER(__name) { \ + .flags = EVL_WAIT_PRIO, \ + .clock = &evl_mono_clock, \ + .wchan = { \ + .lock = __HARD_SPIN_LOCK_INITIALIZER((__name).wchan.lock), \ + .owner = NULL, \ + .requeue_wait = evl_requeue_wait, \ + .wait_list = LIST_HEAD_INIT((__name).wchan.wait_list), \ + .name = #__name, \ + }, \ + } + +#define evl_head_waiter(__wq) \ + list_first_entry_or_null(&(__wq)->wchan.wait_list, \ + struct evl_thread, wait_next) + +#define evl_for_each_waiter(__pos, __wq) \ + list_for_each_entry(__pos, &(__wq)->wchan.wait_list, wait_next) + +#define evl_for_each_waiter_safe(__pos, __tmp, __wq) \ + list_for_each_entry_safe(__pos, __tmp, \ + &(__wq)->wchan.wait_list, wait_next) + +#define evl_wait_event_timeout(__wq, __timeout, __timeout_mode, __cond) \ +({ \ + int __ret = 0, __bcast; \ + unsigned long __flags; \ + \ + raw_spin_lock_irqsave(&(__wq)->wchan.lock, __flags); \ + if (!(__cond)) { \ + if (timeout_nonblock(__timeout)) { \ + __ret = -EAGAIN; \ + } else { \ + do { \ + evl_add_wait_queue(__wq, __timeout, \ + __timeout_mode); \ + raw_spin_unlock_irqrestore(&(__wq)->wchan.lock, __flags); \ + __ret = evl_wait_schedule(__wq); \ + __bcast = evl_current()->info & EVL_T_BCAST; \ + raw_spin_lock_irqsave(&(__wq)->wchan.lock, __flags); \ + } while (!__ret && !__bcast && !(__cond)); \ + } \ + } \ + raw_spin_unlock_irqrestore(&(__wq)->wchan.lock, __flags); \ + __ret; \ +}) + +#define evl_wait_event(__wq, __cond) \ + evl_wait_event_timeout(__wq, EVL_INFINITE, EVL_REL, __cond) + +void evl_add_wait_queue(struct evl_wait_queue *wq, + ktime_t timeout, + enum evl_tmode timeout_mode); + +void evl_add_wait_queue_unchecked(struct evl_wait_queue *wq, + ktime_t timeout, + enum evl_tmode timeout_mode); + +int __evl_wait_schedule(struct evl_wait_channel *wchan); + +static inline int evl_wait_schedule(struct evl_wait_queue *wq) +{ + return __evl_wait_schedule(&wq->wchan); +} + +static inline bool evl_wait_active(struct evl_wait_queue *wq) +{ + assert_hard_lock(&wq->wchan.lock); + return !list_empty(&wq->wchan.wait_list); +} + +void __evl_init_wait(struct evl_wait_queue *wq, + struct evl_clock *clock, + int flags, + const char *name, + struct lock_class_key *key); + +#define evl_init_wait(__wq, __clock, __flags) \ + do { \ + static struct lock_class_key __key; \ + __evl_init_wait(__wq, __clock, __flags, #__wq, &__key); \ + } while (0) + +#define evl_init_wait_on_stack(__wq, __clock, __flags) \ + evl_init_wait(__wq, __clock, __flags) + +void evl_destroy_wait(struct evl_wait_queue *wq); + +struct evl_thread *evl_wait_head(struct evl_wait_queue *wq); + +int evl_flush_wait_locked(struct evl_wait_queue *wq, + int reason); + +int evl_flush_wait(struct evl_wait_queue *wq, + int reason); + +struct evl_thread *evl_wake_up(struct evl_wait_queue *wq, + struct evl_thread *waiter, + int reason); + +static inline +struct evl_thread *evl_wake_up_head(struct evl_wait_queue *wq) +{ + return evl_wake_up(wq, NULL, 0); +} + +bool evl_requeue_wait(struct evl_wait_channel *wchan, + struct evl_thread *waiter); + +void evl_adjust_wait_priority(struct evl_thread *thread); + +int evl_walk_lock_chain(struct evl_wait_channel *orig_wchan, + struct evl_thread *orig_waiter, + bool check_only); + +#endif /* !_EVL_WAIT_H_ */ diff --git a/include/evl/work.h b/include/evl/work.h new file mode 100644 index 000000000..c67d7f303 --- /dev/null +++ b/include/evl/work.h @@ -0,0 +1,108 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2020 Philippe Gerum + */ + +#ifndef _EVL_WORK_H +#define _EVL_WORK_H + +#include +#include +#include + +struct evl_element; + +struct evl_work { + struct irq_work irq_work; + struct work_struct wq_work; + struct workqueue_struct *wq; + union { + int (*handler)(void *arg); + void (*handler_noreturn)(void *arg); + }; + struct evl_element *element; +}; + +#define EVL_DEFINE_WORK(__work, __handler) \ + struct evl_work __work = { \ + .irq_work = IRQ_WORK_INIT(__evl_do_irq_work), \ + .wq_work = __WORK_INITIALIZER((__work).wq_work, \ + __evl_do_work), \ + .wq = NULL, \ + .handler_noreturn = (void (*)(void *))__handler, \ + .element = NULL, \ + } + +struct evl_sync_work { + struct evl_work work; + struct evl_flag done; + int result; +}; + +#define EVL_DEFINE_SYNC_WORK(__work, __handler) \ + struct evl_sync_work __work = { \ + .work = { \ + .irq_work = IRQ_WORK_INIT(__evl_do_irq_work), \ + .wq_work = __WORK_INITIALIZER((__work).work.wq_work, \ + __evl_do_sync_work), \ + .wq = NULL, \ + .handler = (int (*)(void *))__handler, \ + .element = NULL, \ + }, \ + .done = EVL_FLAG_INITIALIZER((__work).done), \ + .result = 0, \ + } + +void evl_init_work(struct evl_work *work, + void (*handler)(struct evl_work *work)); + +void evl_init_work_safe(struct evl_work *work, + void (*handler)(struct evl_work *work), + struct evl_element *element); + +void evl_init_sync_work(struct evl_sync_work *sync_work, + int (*handler)(struct evl_sync_work *sync_work)); + +bool evl_call_inband_from(struct evl_work *work, + struct workqueue_struct *wq); + +static inline bool evl_call_inband(struct evl_work *work) +{ + return evl_call_inband_from(work, system_wq); +} + +static inline +void evl_flush_work(struct evl_work *work) +{ + irq_work_sync(&work->irq_work); + flush_work(&work->wq_work); +} + +static inline +void evl_cancel_work(struct evl_work *work) +{ + irq_work_sync(&work->irq_work); + cancel_work_sync(&work->wq_work); +} + +int evl_call_inband_sync_from(struct evl_sync_work *sync_work, + struct workqueue_struct *wq); + +static inline +int evl_call_inband_sync(struct evl_sync_work *sync_work) +{ + return evl_call_inband_sync_from(sync_work, system_wq); +} + +static inline +void evl_flush_sync_work(struct evl_sync_work *sync_work) +{ + evl_flush_work(&sync_work->work); +} + +void __evl_do_irq_work(struct irq_work *irq_work); +void __evl_do_work(struct work_struct *wq_work); +void __evl_do_sync_work(struct work_struct *wq_work); + +#endif /* !_EVL_WORK_H */ diff --git a/include/evl/xbuf.h b/include/evl/xbuf.h new file mode 100644 index 000000000..ff7013675 --- /dev/null +++ b/include/evl/xbuf.h @@ -0,0 +1,28 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2018 Philippe Gerum + */ + +#ifndef _EVL_XBUF_H +#define _EVL_XBUF_H + +#include + +struct evl_file; +struct evl_xbuf; + +struct evl_xbuf *evl_get_xbuf(int efd, + struct evl_file **efilpp); + +void evl_put_xbuf(struct evl_file *efilp); + +ssize_t evl_read_xbuf(struct evl_xbuf *xbuf, + void *buf, size_t count, + int f_flags); + +ssize_t evl_write_xbuf(struct evl_xbuf *xbuf, + const void *buf, size_t count, + int f_flags); + +#endif /* !_EVL_XBUF_H */ diff --git a/include/linux/clockchips.h b/include/linux/clockchips.h index 9aac31d85..9338b9ec6 100644 --- a/include/linux/clockchips.h +++ b/include/linux/clockchips.h @@ -15,6 +15,7 @@ # include # include # include +# include struct clock_event_device; struct module; @@ -31,6 +32,7 @@ struct module; * from DETACHED or SHUTDOWN. * ONESHOT_STOPPED: Device was programmed in ONESHOT mode and is temporarily * stopped. + * RESERVED: Device is controlled by an out-of-band core via a proxy. */ enum clock_event_state { CLOCK_EVT_STATE_DETACHED, @@ -38,6 +40,7 @@ enum clock_event_state { CLOCK_EVT_STATE_PERIODIC, CLOCK_EVT_STATE_ONESHOT, CLOCK_EVT_STATE_ONESHOT_STOPPED, + CLOCK_EVT_STATE_RESERVED, }; /* @@ -67,6 +70,17 @@ enum clock_event_state { */ # define CLOCK_EVT_FEAT_HRTIMER 0x000080 +/* + * Interrupt pipeline support: + * + * - Clockevent device can work with pipelined timer events (i.e. proxied). + * - Device currently delivers high-precision events via out-of-band interrupts. + * - Device acts as a proxy for timer interrupt pipelining. + */ +# define CLOCK_EVT_FEAT_PIPELINE 0x000100 +# define CLOCK_EVT_FEAT_OOB 0x000200 +# define CLOCK_EVT_FEAT_PROXY 0x000400 + /** * struct clock_event_device - clock event device descriptor * @event_handler: Assigned by the framework to be called by the low @@ -91,7 +105,7 @@ enum clock_event_state { * @max_delta_ticks: maximum delta value in ticks stored for reconfiguration * @name: ptr to clock event name * @rating: variable to rate clock event devices - * @irq: IRQ number (only for non CPU local devices) + * @irq: IRQ number (only for non CPU local devices, or pipelined timers) * @bound_on: Bound on CPU * @cpumask: cpumask to indicate for which CPUs this device works * @list: list head for the management code @@ -137,6 +151,11 @@ static inline bool clockevent_state_detached(struct clock_event_device *dev) return dev->state_use_accessors == CLOCK_EVT_STATE_DETACHED; } +static inline bool clockevent_state_reserved(struct clock_event_device *dev) +{ + return dev->state_use_accessors == CLOCK_EVT_STATE_RESERVED; +} + static inline bool clockevent_state_shutdown(struct clock_event_device *dev) { return dev->state_use_accessors == CLOCK_EVT_STATE_SHUTDOWN; @@ -157,6 +176,11 @@ static inline bool clockevent_state_oneshot_stopped(struct clock_event_device *d return dev->state_use_accessors == CLOCK_EVT_STATE_ONESHOT_STOPPED; } +static inline bool clockevent_is_oob(struct clock_event_device *dev) +{ + return !!(dev->features & CLOCK_EVT_FEAT_OOB); +} + /* * Calculate a multiplication factor for scaled math, which is used to convert * nanoseconds based values to clock ticks: @@ -186,6 +210,8 @@ extern int clockevents_unbind_device(struct clock_event_device *ced, int cpu); extern void clockevents_config_and_register(struct clock_event_device *dev, u32 freq, unsigned long min_delta, unsigned long max_delta); +extern void clockevents_switch_state(struct clock_event_device *dev, + enum clock_event_state state); extern int clockevents_update_freq(struct clock_event_device *ce, u32 freq); @@ -215,6 +241,49 @@ static __always_inline int tick_check_broadcast_expired(void) { return 0; } static inline void tick_setup_hrtimer_broadcast(void) { } # endif +#ifdef CONFIG_IRQ_PIPELINE + +struct clock_proxy_device { + struct clock_event_device proxy_device; + struct clock_event_device *real_device; + void (*handle_oob_event)(struct clock_event_device *dev); + void (*__setup_handler)(struct clock_proxy_device *dev); + void (*__original_handler)(struct clock_event_device *dev); +}; + +void tick_notify_proxy(void); + +static inline +void clockevents_handle_event(struct clock_event_device *ced) +{ + /* + * If called from the in-band stage, or for delivering a + * high-precision timer event to the out-of-band stage, call + * the event handler immediately. + * + * Otherwise, ced is still the in-band tick device for the + * current CPU, so just relay the incoming tick to the in-band + * stage via tick_notify_proxy(). This situation can happen + * when all CPUs receive the same out-of-band IRQ from a given + * clock event device, but only a subset of the online CPUs has + * enabled a proxy. + */ + if (clockevent_is_oob(ced) || running_inband()) + ced->event_handler(ced); + else + tick_notify_proxy(); +} + +#else + +static inline +void clockevents_handle_event(struct clock_event_device *ced) +{ + ced->event_handler(ced); +} + +#endif /* !CONFIG_IRQ_PIPELINE */ + #else /* !CONFIG_GENERIC_CLOCKEVENTS: */ static inline void clockevents_suspend(void) { } diff --git a/include/linux/clocksource.h b/include/linux/clocksource.h index 0ad8b550b..b0bdc5136 100644 --- a/include/linux/clocksource.h +++ b/include/linux/clocksource.h @@ -13,13 +13,16 @@ #include #include #include +#include #include #include +#include #include #include #include #include #include +#include struct clocksource; struct module; @@ -29,6 +32,7 @@ struct module; #include #endif + #include /** @@ -110,6 +114,7 @@ struct clocksource { int rating; enum clocksource_ids id; enum vdso_clock_mode vdso_clock_mode; + enum clocksource_vdso_type vdso_type; unsigned long flags; int (*enable)(struct clocksource *cs); @@ -129,6 +134,36 @@ struct clocksource { struct module *owner; }; +struct clocksource_mmio { + void __iomem *reg; + struct clocksource clksrc; +}; + +struct clocksource_user_mmio { + struct clocksource_mmio mmio; + void __iomem *reg_upper; + unsigned int bits_lower; + unsigned int mask_lower; + unsigned int mask_upper; + enum clksrc_user_mmio_type type; + unsigned long phys_lower; + unsigned long phys_upper; + unsigned int id; + struct device *dev; + struct cdev cdev; + DECLARE_HASHTABLE(mappings, 10); + struct spinlock lock; + struct list_head link; +}; + +struct clocksource_mmio_regs { + void __iomem *reg_upper; + void __iomem *reg_lower; + unsigned int bits_upper; + unsigned int bits_lower; + unsigned long (*revmap)(void *); +}; + /* * Clock source flags bits:: */ @@ -273,10 +308,21 @@ extern u64 clocksource_mmio_readl_up(struct clocksource *); extern u64 clocksource_mmio_readl_down(struct clocksource *); extern u64 clocksource_mmio_readw_up(struct clocksource *); extern u64 clocksource_mmio_readw_down(struct clocksource *); +extern u64 clocksource_dual_mmio_readw_up(struct clocksource *); +extern u64 clocksource_dual_mmio_readl_up(struct clocksource *); extern int clocksource_mmio_init(void __iomem *, const char *, unsigned long, int, unsigned, u64 (*)(struct clocksource *)); +extern int clocksource_user_mmio_init(struct clocksource_user_mmio *ucs, + const struct clocksource_mmio_regs *regs, + unsigned long hz); + +extern int clocksource_user_single_mmio_init( + void __iomem *base, const char *name, + unsigned long hz, int rating, unsigned int bits, + u64 (*read)(struct clocksource *)); + extern int clocksource_i8253_init(void); #define TIMER_OF_DECLARE(name, compat, fn) \ diff --git a/include/linux/console.h b/include/linux/console.h index 7de11c763..a182e11ab 100644 --- a/include/linux/console.h +++ b/include/linux/console.h @@ -191,6 +191,7 @@ enum cons_flags { struct console { char name[16]; void (*write)(struct console *co, const char *s, unsigned int count); + void (*write_raw)(struct console *co, const char *, unsigned int count); int (*read)(struct console *co, char *s, unsigned int count); struct tty_driver *(*device)(struct console *co, int *index); void (*unblank)(void); diff --git a/include/linux/context_tracking_state.h b/include/linux/context_tracking_state.h index bbff5f7f8..4ab32af0b 100644 --- a/include/linux/context_tracking_state.h +++ b/include/linux/context_tracking_state.h @@ -105,7 +105,7 @@ extern struct static_key_false context_tracking_key; static __always_inline bool context_tracking_enabled(void) { - return static_branch_unlikely(&context_tracking_key); + return static_branch_unlikely(&context_tracking_key) && running_inband(); } static __always_inline bool context_tracking_enabled_cpu(int cpu) diff --git a/include/linux/dmaengine.h b/include/linux/dmaengine.h index cff3dba65..bc4d7819b 100644 --- a/include/linux/dmaengine.h +++ b/include/linux/dmaengine.h @@ -61,6 +61,7 @@ enum dma_transaction_type { DMA_ASYNC_TX, DMA_SLAVE, DMA_CYCLIC, + DMA_OOB, DMA_INTERLEAVE, DMA_COMPLETION_NO_ORDER, DMA_REPEAT, @@ -190,6 +191,13 @@ struct dma_interleaved_template { * transaction is marked with DMA_PREP_REPEAT will cause the new transaction * to never be processed and stay in the issued queue forever. The flag is * ignored if the previous transaction is not a repeated transaction. + * @DMA_OOB_INTERRUPT - if DMA_OOB is supported, handle the completion + * interrupt for this transaction from the out-of-band stage (implies + * DMA_PREP_INTERRUPT). This includes calling the completion callback routine + * from such context if defined for the transaction. + * @DMA_OOB_PULSE - if DMA_OOB is supported, (slave) transactions on the + * out-of-band channel should be triggered manually by a call to + * dma_pulse_oob() (implies DMA_OOB_INTERRUPT). */ enum dma_ctrl_flags { DMA_PREP_INTERRUPT = (1 << 0), @@ -202,6 +210,8 @@ enum dma_ctrl_flags { DMA_PREP_CMD = (1 << 7), DMA_PREP_REPEAT = (1 << 8), DMA_PREP_LOAD_EOT = (1 << 9), + DMA_OOB_INTERRUPT = (1 << 10), + DMA_OOB_PULSE = (1 << 11), }; /** @@ -938,6 +948,7 @@ struct dma_device { dma_cookie_t cookie, struct dma_tx_state *txstate); void (*device_issue_pending)(struct dma_chan *chan); + int (*device_pulse_oob)(struct dma_chan *chan); void (*device_release)(struct dma_device *dev); /* debugfs support */ void (*dbg_summary_show)(struct seq_file *s, struct dma_device *dev); @@ -975,6 +986,14 @@ static inline struct dma_async_tx_descriptor *dmaengine_prep_slave_single( dir, flags, NULL); } +static inline bool dmaengine_oob_valid(struct dma_chan *chan, + unsigned long flags) +{ + return !(dovetailing() && + flags & (DMA_OOB_INTERRUPT|DMA_OOB_PULSE) && + !test_bit(DMA_OOB, chan->device->cap_mask.bits)); +} + static inline struct dma_async_tx_descriptor *dmaengine_prep_slave_sg( struct dma_chan *chan, struct scatterlist *sgl, unsigned int sg_len, enum dma_transfer_direction dir, unsigned long flags) @@ -982,6 +1001,9 @@ static inline struct dma_async_tx_descriptor *dmaengine_prep_slave_sg( if (!chan || !chan->device || !chan->device->device_prep_slave_sg) return NULL; + if (!dmaengine_oob_valid(chan, flags)) + return NULL; + return chan->device->device_prep_slave_sg(chan, sgl, sg_len, dir, flags, NULL); } @@ -1009,6 +1031,9 @@ static inline struct dma_async_tx_descriptor *dmaengine_prep_dma_cyclic( if (!chan || !chan->device || !chan->device->device_prep_dma_cyclic) return NULL; + if (!dmaengine_oob_valid(chan, flags)) + return NULL; + return chan->device->device_prep_dma_cyclic(chan, buf_addr, buf_len, period_len, dir, flags); } @@ -1421,6 +1446,22 @@ static inline void dma_async_issue_pending(struct dma_chan *chan) chan->device->device_issue_pending(chan); } +/** + * dma_pulse_oob - manual trigger of an out-of-band transaction + * @chan: target DMA channel + * + * Trigger the next out-of-band transaction immediately. + */ +static inline int dma_pulse_oob(struct dma_chan *chan) +{ + int ret = -ENOTSUPP; + + if (chan->device->device_pulse_oob) + ret = chan->device->device_pulse_oob(chan); + + return ret; +} + /** * dma_async_is_tx_complete - poll for transaction completion * @chan: DMA channel diff --git a/include/linux/dovetail.h b/include/linux/dovetail.h new file mode 100644 index 000000000..0ae33a3c5 --- /dev/null +++ b/include/linux/dovetail.h @@ -0,0 +1,343 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2016 Philippe Gerum . + */ +#ifndef _LINUX_DOVETAIL_H +#define _LINUX_DOVETAIL_H + +struct pt_regs; +struct mm_struct; +struct task_struct; +struct file; +struct files_struct; + +#ifdef CONFIG_DOVETAIL + +#include +#include +#include +#include +#include +#include + +enum inband_event_type { + INBAND_TASK_SIGNAL, + INBAND_TASK_MIGRATION, + INBAND_TASK_EXIT, + INBAND_TASK_RETUSER, + INBAND_TASK_PTSTEP, + INBAND_TASK_PTSTOP, + INBAND_TASK_PTCONT, + INBAND_PROCESS_CLEANUP, +}; + +struct dovetail_migration_data { + struct task_struct *task; + int dest_cpu; +}; + +struct dovetail_altsched_context { + struct task_struct *task; + struct mm_struct *active_mm; + bool borrowed_mm; +}; + +#define protect_inband_mm(__flags) \ + do { \ + (__flags) = hard_cond_local_irq_save(); \ + barrier(); \ + } while (0) \ + +#define unprotect_inband_mm(__flags) \ + do { \ + barrier(); \ + hard_cond_local_irq_restore(__flags); \ + } while (0) \ + +void inband_task_init(struct task_struct *p); + +int pipeline_syscall(unsigned int nr, struct pt_regs *regs); + +void __oob_trap_notify(unsigned int exception, + struct pt_regs *regs); + +static __always_inline void oob_trap_notify(unsigned int exception, + struct pt_regs *regs) +{ + if (running_oob() && !test_thread_local_flags(_TLF_OOBTRAP)) + __oob_trap_notify(exception, regs); +} + +void __oob_trap_unwind(unsigned int exception, + struct pt_regs *regs); + +static __always_inline void oob_trap_unwind(unsigned int exception, + struct pt_regs *regs) +{ + if (test_thread_local_flags(_TLF_OOBTRAP)) + __oob_trap_unwind(exception, regs); +} + +void inband_event_notify(enum inband_event_type, + void *data); + +void inband_clock_was_set(void); + +static inline void inband_signal_notify(struct task_struct *p) +{ + if (test_ti_local_flags(task_thread_info(p), _TLF_DOVETAIL)) + inband_event_notify(INBAND_TASK_SIGNAL, p); +} + +static inline void inband_migration_notify(struct task_struct *p, int cpu) +{ + if (test_ti_local_flags(task_thread_info(p), _TLF_DOVETAIL)) { + struct dovetail_migration_data d = { + .task = p, + .dest_cpu = cpu, + }; + inband_event_notify(INBAND_TASK_MIGRATION, &d); + } +} + +static inline void inband_exit_notify(void) +{ + inband_event_notify(INBAND_TASK_EXIT, NULL); +} + +static inline void inband_cleanup_notify(struct mm_struct *mm) +{ + /* + * Notify regardless of _TLF_DOVETAIL: current may have + * resources to clean up although it might not be interested + * in other kernel events. + */ + inband_event_notify(INBAND_PROCESS_CLEANUP, mm); +} + +static inline void inband_ptstop_notify(void) +{ + if (test_thread_local_flags(_TLF_DOVETAIL)) + inband_event_notify(INBAND_TASK_PTSTOP, current); +} + +static inline void inband_ptcont_notify(void) +{ + if (test_thread_local_flags(_TLF_DOVETAIL)) + inband_event_notify(INBAND_TASK_PTCONT, current); +} + +static inline void inband_ptstep_notify(struct task_struct *tracee) +{ + if (test_ti_local_flags(task_thread_info(tracee), _TLF_DOVETAIL)) + inband_event_notify(INBAND_TASK_PTSTEP, tracee); +} + +static inline +void prepare_inband_switch(struct task_struct *next) +{ + struct task_struct *prev = current; + + if (test_ti_local_flags(task_thread_info(next), _TLF_DOVETAIL)) + __this_cpu_write(irq_pipeline.rqlock_owner, prev); +} + +void inband_retuser_notify(void); + +bool inband_switch_tail(void); + +void oob_trampoline(void); + +void arch_inband_task_init(struct task_struct *p); + +int dovetail_start(void); + +void dovetail_stop(void); + +void dovetail_init_altsched(struct dovetail_altsched_context *p); + +void dovetail_start_altsched(void); + +void dovetail_stop_altsched(void); + +__must_check int dovetail_leave_inband(void); + +static inline void dovetail_leave_oob(void) +{ + clear_thread_local_flags(_TLF_OOB|_TLF_OFFSTAGE); + clear_thread_flag(TIF_MAYDAY); +} + +void dovetail_resume_inband(void); + +bool dovetail_context_switch(struct dovetail_altsched_context *out, + struct dovetail_altsched_context *in, + bool leave_inband); + +static inline +struct oob_thread_state *dovetail_current_state(void) +{ + return ¤t_thread_info()->oob_state; +} + +static inline +struct oob_thread_state *dovetail_task_state(struct task_struct *p) +{ + return &task_thread_info(p)->oob_state; +} + +static inline +struct oob_mm_state *dovetail_mm_state(void) +{ + if (current->flags & PF_KTHREAD) + return NULL; + + return ¤t->mm->oob_state; +} + +void dovetail_call_mayday(struct pt_regs *regs); + +static inline void dovetail_send_mayday(struct task_struct *castaway) +{ + struct thread_info *ti = task_thread_info(castaway); + + if (test_ti_local_flags(ti, _TLF_DOVETAIL)) + set_ti_thread_flag(ti, TIF_MAYDAY); +} + +static inline void dovetail_request_ucall(struct task_struct *task) +{ + struct thread_info *ti = task_thread_info(task); + + if (test_ti_local_flags(ti, _TLF_DOVETAIL)) + set_ti_thread_flag(ti, TIF_RETUSER); +} + +static inline void dovetail_clear_ucall(void) +{ + if (test_thread_flag(TIF_RETUSER)) + clear_thread_flag(TIF_RETUSER); +} + +void install_inband_fd(unsigned int fd, struct file *file, + struct files_struct *files); + +void uninstall_inband_fd(unsigned int fd, struct file *file, + struct files_struct *files); + +void replace_inband_fd(unsigned int fd, struct file *file, + struct files_struct *files); + +#ifndef arch_dovetail_is_prctl +#define arch_dovetail_is_prctl(__nr) ((__nr) == __NR_prctl) +#endif + +#ifndef arch_dovetail_is_syscall +#define arch_dovetail_is_syscall(__tsk, __nr, __regs) \ + ({ \ + bool __is_prctl = arch_dovetail_is_prctl(__nr); \ + __is_prctl && syscall_get_arg0(__tsk, __regs) == PR_OOB_SYSCALL; \ + }) +#endif + +bool in_oob_syscall(struct pt_regs *regs); + +#else /* !CONFIG_DOVETAIL */ + +#include + +#ifdef CONFIG_HAVE_DOVETAIL +/* We may have arch-specific placeholders. */ +#include +#endif + +#define protect_inband_mm(__flags) \ + do { (void)(__flags); } while (0) + +#define unprotect_inband_mm(__flags) \ + do { (void)(__flags); } while (0) + +static inline +void inband_task_init(struct task_struct *p) { } + +static inline void arch_dovetail_exec_prepare(void) +{ } + +/* + * Keep the trap helpers as macros, we might not be able to resolve + * trap numbers if CONFIG_DOVETAIL is off. + */ +#define oob_trap_notify(__exception, __regs) do { } while (0) +#define oob_trap_unwind(__exception, __regs) do { } while (0) + +static inline +int pipeline_syscall(unsigned int nr, struct pt_regs *regs) +{ + return 0; +} + +static inline void inband_signal_notify(struct task_struct *p) { } + +static inline +void inband_migration_notify(struct task_struct *p, int cpu) { } + +static inline void inband_exit_notify(void) { } + +static inline void inband_cleanup_notify(struct mm_struct *mm) { } + +static inline void inband_retuser_notify(void) { } + +static inline void inband_ptstop_notify(void) { } + +static inline void inband_ptcont_notify(void) { } + +static inline void inband_ptstep_notify(struct task_struct *tracee) { } + +static inline void oob_trampoline(void) { } + +static inline void prepare_inband_switch(struct task_struct *next) { } + +static inline bool inband_switch_tail(void) +{ + /* Matches converse disabling in prepare_task_switch(). */ + hard_cond_local_irq_enable(); + return false; +} + +static inline void dovetail_request_ucall(struct task_struct *task) { } + +static inline void dovetail_clear_ucall(void) { } + +static inline void inband_clock_was_set(void) { } + +static inline +void install_inband_fd(unsigned int fd, struct file *file, + struct files_struct *files) { } + +static inline +void uninstall_inband_fd(unsigned int fd, struct file *file, + struct files_struct *files) { } + +static inline +void replace_inband_fd(unsigned int fd, struct file *file, + struct files_struct *files) { } + +static inline bool in_oob_syscall(struct pt_regs *regs) +{ + return false; +} + +#endif /* !CONFIG_DOVETAIL */ + +static __always_inline bool dovetailing(void) +{ + return IS_ENABLED(CONFIG_DOVETAIL); +} + +static __always_inline bool dovetail_debug(void) +{ + return IS_ENABLED(CONFIG_DEBUG_DOVETAIL); +} + +#endif /* _LINUX_DOVETAIL_H */ diff --git a/include/linux/dw_apb_timer.h b/include/linux/dw_apb_timer.h index 82ebf9223..d69dbd096 100644 --- a/include/linux/dw_apb_timer.h +++ b/include/linux/dw_apb_timer.h @@ -30,7 +30,7 @@ struct dw_apb_clock_event_device { struct dw_apb_clocksource { struct dw_apb_timer timer; - struct clocksource cs; + struct clocksource_user_mmio ummio; }; void dw_apb_clockevent_register(struct dw_apb_clock_event_device *dw_ced); diff --git a/include/linux/entry-common.h b/include/linux/entry-common.h index d95ab85f9..84e633be9 100644 --- a/include/linux/entry-common.h +++ b/include/linux/entry-common.h @@ -62,6 +62,14 @@ _TIF_NEED_RESCHED | _TIF_PATCH_PENDING | _TIF_NOTIFY_SIGNAL | \ ARCH_EXIT_TO_USER_MODE_WORK) +/* + * Status codes of syscall entry when Dovetail is enabled. Must not + * conflict with valid syscall numbers. And with -1 which seccomp uses + * to skip an syscall. + */ +#define EXIT_SYSCALL_OOB (-2) +#define EXIT_SYSCALL_TAIL (-3) + /** * arch_enter_from_user_mode - Architecture specific sanity check for user mode regs * @regs: Pointer to currents pt_regs @@ -142,6 +150,29 @@ void syscall_enter_from_user_mode_prepare(struct pt_regs *regs); */ long syscall_enter_from_user_mode_work(struct pt_regs *regs, long syscall); +static __always_inline void syscall_enter_from_user_enable_irqs(void) +{ + if (running_inband()) { + /* + * If pipelining interrupts, prepare for emulating a + * stall -> unstall transition (we are currently + * unstalled), fixing up the IRQ trace state in order + * to keep lockdep happy (and silent). + */ + stall_inband_nocheck(); + hard_cond_local_irq_enable(); + local_irq_enable(); + } else { + /* + * We are running on the out-of-band stage, don't mess + * with the in-band interrupt state. This is none of + * our business. We may manipulate the hardware state + * only. + */ + hard_local_irq_enable(); + } +} + /** * syscall_enter_from_user_mode - Establish state and check and handle work * before invoking a syscall @@ -173,7 +204,7 @@ static inline void local_irq_enable_exit_to_user(unsigned long ti_work); #ifndef local_irq_enable_exit_to_user static inline void local_irq_enable_exit_to_user(unsigned long ti_work) { - local_irq_enable(); + local_irq_enable_full(); } #endif @@ -188,7 +219,7 @@ static inline void local_irq_disable_exit_to_user(void); #ifndef local_irq_disable_exit_to_user static inline void local_irq_disable_exit_to_user(void) { - local_irq_disable(); + local_irq_disable_full(); } #endif @@ -352,6 +383,12 @@ void irqentry_enter_from_user_mode(struct pt_regs *regs); */ void irqentry_exit_to_user_mode(struct pt_regs *regs); +enum irqentry_info { + IRQENTRY_INBAND_UNSTALLED = 0, + IRQENTRY_INBAND_STALLED, + IRQENTRY_OOB, +}; + #ifndef irqentry_state /** * struct irqentry_state - Opaque object for exception state storage @@ -359,6 +396,7 @@ void irqentry_exit_to_user_mode(struct pt_regs *regs); * exit path has to invoke ct_irq_exit(). * @lockdep: Used exclusively in the irqentry_nmi_*() calls; ensures that * lockdep state is restored correctly on exit from nmi. + * @stage_info: Information about pipeline state and current stage on IRQ entry. * * This opaque object is filled in by the irqentry_*_enter() functions and * must be passed back into the corresponding irqentry_*_exit() functions @@ -373,6 +411,9 @@ typedef struct irqentry_state { bool exit_rcu; bool lockdep; }; +#ifdef CONFIG_IRQ_PIPELINE + enum irqentry_info stage_info; +#endif } irqentry_state_t; #endif diff --git a/include/linux/fcntl.h b/include/linux/fcntl.h index a332e79b3..31d552753 100644 --- a/include/linux/fcntl.h +++ b/include/linux/fcntl.h @@ -10,7 +10,7 @@ (O_RDONLY | O_WRONLY | O_RDWR | O_CREAT | O_EXCL | O_NOCTTY | O_TRUNC | \ O_APPEND | O_NDELAY | O_NONBLOCK | __O_SYNC | O_DSYNC | \ FASYNC | O_DIRECT | O_LARGEFILE | O_DIRECTORY | O_NOFOLLOW | \ - O_NOATIME | O_CLOEXEC | O_PATH | __O_TMPFILE) + O_NOATIME | O_CLOEXEC | O_PATH | __O_TMPFILE | O_OOB) /* List of all valid flags for the how->resolve argument: */ #define VALID_RESOLVE_FLAGS \ diff --git a/include/linux/filter.h b/include/linux/filter.h index 5090e940b..d68668bd7 100644 --- a/include/linux/filter.h +++ b/include/linux/filter.h @@ -604,10 +604,16 @@ static __always_inline u32 __bpf_prog_run(const struct bpf_prog *prog, ret = dfunc(ctx, prog->insnsi, prog->bpf_func); stats = this_cpu_ptr(prog->stats); - flags = u64_stats_update_begin_irqsave(&stats->syncp); + if (IS_ENABLED(CONFIG_BPF_OOB)) + flags = u64_stats_update_begin_hard_irqsave(&stats->syncp); + else + flags = u64_stats_update_begin_irqsave(&stats->syncp); u64_stats_inc(&stats->cnt); u64_stats_add(&stats->nsecs, sched_clock() - start); - u64_stats_update_end_irqrestore(&stats->syncp, flags); + if (IS_ENABLED(CONFIG_BPF_OOB)) + u64_stats_update_end_hard_irqrestore(&stats->syncp, flags); + else + u64_stats_update_end_irqrestore(&stats->syncp, flags); } else { ret = dfunc(ctx, prog->insnsi, prog->bpf_func); } diff --git a/include/linux/fs.h b/include/linux/fs.h index 6c3d86532..f404a33ce 100644 --- a/include/linux/fs.h +++ b/include/linux/fs.h @@ -59,6 +59,7 @@ struct kiocb; struct kobject; struct pipe_inode_info; struct poll_table_struct; +struct oob_poll_wait; struct kstatfs; struct vm_area_struct; struct vfsmount; @@ -1029,6 +1030,9 @@ struct file { struct address_space *f_mapping; errseq_t f_wb_err; errseq_t f_sb_err; /* for syncfs */ +#ifdef CONFIG_DOVETAIL + void *f_oob_ctx; +#endif } __randomize_layout __attribute__((aligned(4))); /* lest something weird decides that 2 is OK */ @@ -1831,8 +1835,11 @@ extern long vfs_ioctl(struct file *file, unsigned int cmd, unsigned long arg); #ifdef CONFIG_COMPAT extern long compat_ptr_ioctl(struct file *file, unsigned int cmd, unsigned long arg); +extern long compat_ptr_oob_ioctl(struct file *file, unsigned int cmd, + unsigned long arg); #else #define compat_ptr_ioctl NULL +#define compat_ptr_oob_ioctl NULL #endif /* @@ -1924,6 +1931,11 @@ struct file_operations { __poll_t (*poll) (struct file *, struct poll_table_struct *); long (*unlocked_ioctl) (struct file *, unsigned int, unsigned long); long (*compat_ioctl) (struct file *, unsigned int, unsigned long); + ssize_t (*oob_read) (struct file *, char __user *, size_t); + ssize_t (*oob_write) (struct file *, const char __user *, size_t); + long (*oob_ioctl) (struct file *, unsigned int, unsigned long); + long (*compat_oob_ioctl) (struct file *, unsigned int, unsigned long); + __poll_t (*oob_poll) (struct file *, struct oob_poll_wait *); int (*mmap) (struct file *, struct vm_area_struct *); unsigned long mmap_supported_flags; int (*open) (struct inode *, struct file *); diff --git a/include/linux/hardirq.h b/include/linux/hardirq.h index d57cab4d4..2ba79d080 100644 --- a/include/linux/hardirq.h +++ b/include/linux/hardirq.h @@ -8,6 +8,7 @@ #include #include #include +#include #include extern void synchronize_irq(unsigned int irq); @@ -114,6 +115,7 @@ void irq_exit_rcu(void); #define nmi_enter() \ do { \ + irq_pipeline_nmi_enter(); \ __nmi_enter(); \ lockdep_hardirq_enter(); \ ct_nmi_enter(); \ @@ -138,6 +140,22 @@ void irq_exit_rcu(void); ct_nmi_exit(); \ lockdep_hardirq_exit(); \ __nmi_exit(); \ + irq_pipeline_nmi_exit(); \ } while (0) +static inline bool on_pipeline_entry(void) +{ + return irqs_pipelined() && in_pipeline(); +} + +static inline bool in_nonmaskable(void) +{ + /* + * From the standpoint of tne in-band stage, any oob activity + * stands for a non-maskable event being handled (including + * the pipeline entry context). + */ + return running_oob() || in_nmi(); +} + #endif /* LINUX_HARDIRQ_H */ diff --git a/include/linux/interrupt.h b/include/linux/interrupt.h index 4a1dc88dd..022f6a633 100644 --- a/include/linux/interrupt.h +++ b/include/linux/interrupt.h @@ -67,6 +67,12 @@ * later. * IRQF_NO_DEBUG - Exclude from runnaway detection for IPI and similar handlers, * depends on IRQF_PERCPU. + * IRQF_OOB - Interrupt is attached to an out-of-band handler living + * on the heading stage of the interrupt pipeline + * (CONFIG_IRQ_PIPELINE). It may be delivered to the + * handler any time interrupts are enabled in the CPU, + * regardless of the (virtualized) interrupt state + * maintained by local_irq_save/disable(). */ #define IRQF_SHARED 0x00000080 #define IRQF_PROBE_SHARED 0x00000100 @@ -82,6 +88,7 @@ #define IRQF_COND_SUSPEND 0x00040000 #define IRQF_NO_AUTOEN 0x00080000 #define IRQF_NO_DEBUG 0x00100000 +#define IRQF_OOB 0x00200000 #define IRQF_TIMER (__IRQF_TIMER | IRQF_NO_SUSPEND | IRQF_NO_THREAD) @@ -534,9 +541,29 @@ DECLARE_STATIC_KEY_FALSE(force_irqthreads_key); * to ensure that after a local_irq_disable(), interrupts have * really been disabled in hardware. Such architectures need to * implement the following hook. + * + * Those cases also apply when interrupt pipelining is in effect, + * since we are virtualizing the interrupt disable state here too. */ #ifndef hard_irq_disable -#define hard_irq_disable() do { } while(0) +#define hard_irq_disable() hard_cond_local_irq_disable() +#endif + +/* + * Unlike other virtualized interrupt disabling schemes may assume, we + * can't expect local_irq_restore() to turn hard interrupts on when + * pipelining. hard_irq_enable() is introduced to be paired with + * hard_irq_disable(), for unconditionally turning them on. The only + * sane sequence mixing virtual and real disable state manipulation + * is: + * + * 1. local_irq_save/disable + * 2. hard_irq_disable + * 3. hard_irq_enable + * 4. local_irq_restore/enable + */ +#ifndef hard_irq_enable +#define hard_irq_enable() hard_cond_local_irq_enable() #endif /* PLEASE, avoid to allocate new softirqs, if you need not _really_ high diff --git a/include/linux/irq.h b/include/linux/irq.h index 90081afa1..ec24e81e0 100644 --- a/include/linux/irq.h +++ b/include/linux/irq.h @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -73,6 +74,11 @@ enum irqchip_irq_state; * IRQ_DISABLE_UNLAZY - Disable lazy irq disable * IRQ_HIDDEN - Don't show up in /proc/interrupts * IRQ_NO_DEBUG - Exclude from note_interrupt() debugging + * IRQ_OOB - Interrupt can be delivered to the out-of-band handler + * when pipelining is enabled (CONFIG_IRQ_PIPELINE), + * regardless of the (virtualized) interrupt state + * maintained by local_irq_save/disable(). + * IRQ_CHAINED - Interrupt is chained. */ enum { IRQ_TYPE_NONE = 0x00000000, @@ -101,13 +107,15 @@ enum { IRQ_DISABLE_UNLAZY = (1 << 19), IRQ_HIDDEN = (1 << 20), IRQ_NO_DEBUG = (1 << 21), + IRQ_OOB = (1 << 22), + IRQ_CHAINED = (1 << 23), }; #define IRQF_MODIFY_MASK \ (IRQ_TYPE_SENSE_MASK | IRQ_NOPROBE | IRQ_NOREQUEST | \ IRQ_NOAUTOEN | IRQ_MOVE_PCNTXT | IRQ_LEVEL | IRQ_NO_BALANCING | \ IRQ_PER_CPU | IRQ_NESTED_THREAD | IRQ_NOTHREAD | IRQ_PER_CPU_DEVID | \ - IRQ_IS_POLLED | IRQ_DISABLE_UNLAZY | IRQ_HIDDEN) + IRQ_IS_POLLED | IRQ_DISABLE_UNLAZY | IRQ_HIDDEN | IRQ_OOB) #define IRQ_NO_BALANCING_MASK (IRQ_PER_CPU | IRQ_NO_BALANCING) @@ -175,6 +183,7 @@ struct irq_common_data { * irq_domain * @chip_data: platform-specific per-chip private data for the chip * methods, to allow shared chip implementations + * @move_work: irq_work for setaffinity deferral when pipelining irqs */ struct irq_data { u32 mask; @@ -185,6 +194,9 @@ struct irq_data { struct irq_domain *domain; #ifdef CONFIG_IRQ_DOMAIN_HIERARCHY struct irq_data *parent_data; +#endif +#if defined(CONFIG_IRQ_PIPELINE) && defined(CONFIG_GENERIC_PENDING_IRQ) + struct irq_work move_work; #endif void *chip_data; }; @@ -193,6 +205,7 @@ struct irq_data { * Bit masks for irq_common_data.state_use_accessors * * IRQD_TRIGGER_MASK - Mask for the trigger type bits + * IRQD_SETAFFINITY_BLOCKED - Pending affinity setting on hold (IRQ_PIPELINE) * IRQD_SETAFFINITY_PENDING - Affinity setting is pending * IRQD_ACTIVATED - Interrupt has already been activated * IRQD_NO_BALANCING - Balancing disabled for this IRQ @@ -226,6 +239,7 @@ struct irq_data { */ enum { IRQD_TRIGGER_MASK = 0xf, + IRQD_SETAFFINITY_BLOCKED = BIT(7), IRQD_SETAFFINITY_PENDING = BIT(8), IRQD_ACTIVATED = BIT(9), IRQD_NO_BALANCING = BIT(10), @@ -258,6 +272,21 @@ static inline bool irqd_is_setaffinity_pending(struct irq_data *d) return __irqd_to_state(d) & IRQD_SETAFFINITY_PENDING; } +static inline void irqd_set_move_blocked(struct irq_data *d) +{ + __irqd_to_state(d) |= IRQD_SETAFFINITY_BLOCKED; +} + +static inline void irqd_clr_move_blocked(struct irq_data *d) +{ + __irqd_to_state(d) &= ~IRQD_SETAFFINITY_BLOCKED; +} + +static inline bool irqd_is_setaffinity_blocked(struct irq_data *d) +{ + return irqs_pipelined() && __irqd_to_state(d) & IRQD_SETAFFINITY_BLOCKED; +} + static inline bool irqd_is_per_cpu(struct irq_data *d) { return __irqd_to_state(d) & IRQD_PER_CPU; @@ -567,6 +596,7 @@ struct irq_chip { * in the suspend path if they are in disabled state * IRQCHIP_AFFINITY_PRE_STARTUP: Default affinity update before startup * IRQCHIP_IMMUTABLE: Don't ever change anything in this chip + * IRQCHIP_PIPELINE_SAFE: Chip can work in pipelined mode */ enum { IRQCHIP_SET_TYPE_MASKED = (1 << 0), @@ -581,6 +611,7 @@ enum { IRQCHIP_ENABLE_WAKEUP_ON_SUSPEND = (1 << 9), IRQCHIP_AFFINITY_PRE_STARTUP = (1 << 10), IRQCHIP_IMMUTABLE = (1 << 11), + IRQCHIP_PIPELINE_SAFE = (1 << 12), }; #include @@ -659,6 +690,7 @@ extern void handle_percpu_irq(struct irq_desc *desc); extern void handle_percpu_devid_irq(struct irq_desc *desc); extern void handle_bad_irq(struct irq_desc *desc); extern void handle_nested_irq(unsigned int irq); +extern void handle_synthetic_irq(struct irq_desc *desc); extern void handle_fasteoi_nmi(struct irq_desc *desc); extern void handle_percpu_devid_fasteoi_nmi(struct irq_desc *desc); @@ -1059,7 +1091,7 @@ struct irq_chip_type { * different flow mechanisms (level/edge) for it. */ struct irq_chip_generic { - raw_spinlock_t lock; + hard_spinlock_t lock; void __iomem *reg_base; u32 (*reg_readl)(void __iomem *addr); void (*reg_writel)(u32 val, void __iomem *addr); @@ -1187,6 +1219,20 @@ static inline struct irq_chip_type *irq_data_get_chip_type(struct irq_data *d) #define IRQ_MSK(n) (u32)((n) < 32 ? ((1 << (n)) - 1) : UINT_MAX) +#ifdef CONFIG_IRQ_PIPELINE +int irq_switch_oob(unsigned int irq, bool on); +void irq_clear_deferral(struct irq_desc *desc); +void irq_clear_forward(struct irq_desc *desc); +#else +static inline int irq_switch_oob(unsigned int irq, bool on) +{ + return 0; +} + +static inline void irq_clear_deferral(struct irq_desc *desc) { } +static inline void irq_clear_forward(struct irq_desc *desc) { } +#endif /* !CONFIG_IRQ_PIPELINE */ + #ifdef CONFIG_SMP static inline void irq_gc_lock(struct irq_chip_generic *gc) { diff --git a/include/linux/irq_pipeline.h b/include/linux/irq_pipeline.h new file mode 100644 index 000000000..353f0b4de --- /dev/null +++ b/include/linux/irq_pipeline.h @@ -0,0 +1,142 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2002 Philippe Gerum . + * 2006 Gilles Chanteperdrix. + * 2007 Jan Kiszka. + */ +#ifndef _LINUX_IRQ_PIPELINE_H +#define _LINUX_IRQ_PIPELINE_H + +struct cpuidle_device; +struct cpuidle_state; +struct irq_desc; + +#ifdef CONFIG_IRQ_PIPELINE + +#include +#include +#include +#include +#include +#include +#include + +void irq_pipeline_init_early(void); + +void irq_pipeline_init(void); + +void arch_irq_pipeline_init(void); + +int generic_pipeline_irq_desc(struct irq_desc *desc); + +int irq_inject_pipeline(unsigned int irq); + +void synchronize_pipeline(void); + +static __always_inline void synchronize_pipeline_on_irq(void) +{ + /* + * Optimize if we preempted the high priority oob stage: we + * don't need to synchronize the pipeline unless there is a + * pending interrupt for it. + */ + if (running_inband() || + stage_irqs_pending(this_oob_staged())) + synchronize_pipeline(); +} + +bool handle_oob_irq(struct irq_desc *desc); + +void arch_do_IRQ_pipelined(struct irq_desc *desc); + +#ifdef CONFIG_SMP +void irq_send_oob_ipi(unsigned int ipi, + const struct cpumask *cpumask); +#endif /* CONFIG_SMP */ + +void irq_pipeline_oops(void); + +bool irq_pipeline_can_idle(void); + +bool irq_cpuidle_enter(struct cpuidle_device *dev, + struct cpuidle_state *state); + +int run_oob_call(int (*fn)(void *arg), void *arg); + +static inline bool inband_irq_pending(void) +{ + check_hard_irqs_disabled(); + + return stage_irqs_pending(this_inband_staged()); +} + +struct irq_stage_data * +handle_irq_pipelined_prepare(struct pt_regs *regs); + +int handle_irq_pipelined_finish(struct irq_stage_data *prevd, + struct pt_regs *regs); + +int handle_irq_pipelined(struct pt_regs *regs); + +void sync_inband_irqs(void); + +static inline void irq_pipeline_idling_checks(void) +{ + if (irq_pipeline_debug()) { + WARN_ON_ONCE(!raw_irqs_disabled()); + WARN_ON_ONCE(!hard_irqs_disabled()); + WARN_ON_ONCE(stage_irqs_pending(this_inband_staged())); + } +} + +extern struct irq_domain *synthetic_irq_domain; + +#else /* !CONFIG_IRQ_PIPELINE */ + +#include +#include + +static inline +void irq_pipeline_init_early(void) { } + +static inline +void irq_pipeline_init(void) { } + +static inline +void irq_pipeline_oops(void) { } + +static inline int +generic_pipeline_irq_desc(struct irq_desc *desc) +{ + return 0; +} + +static inline bool handle_oob_irq(struct irq_desc *desc) +{ + return false; +} + +static inline bool irq_cpuidle_enter(struct cpuidle_device *dev, + struct cpuidle_state *state) +{ + return true; +} + +static inline bool inband_irq_pending(void) +{ + return false; +} + +static inline void sync_inband_irqs(void) { } + +static inline bool irq_pipeline_can_idle(void) +{ + return true; +} + +static inline void irq_pipeline_idling_checks(void) { } + +#endif /* !CONFIG_IRQ_PIPELINE */ + +#endif /* _LINUX_IRQ_PIPELINE_H */ diff --git a/include/linux/irqdesc.h b/include/linux/irqdesc.h index d9451d456..84f32f736 100644 --- a/include/linux/irqdesc.h +++ b/include/linux/irqdesc.h @@ -68,7 +68,7 @@ struct irq_desc { unsigned int irqs_unhandled; atomic_t threads_handled; int threads_handled_last; - raw_spinlock_t lock; + hybrid_spinlock_t lock; struct cpumask *percpu_enabled; const struct cpumask *percpu_affinity; #ifdef CONFIG_SMP @@ -241,6 +241,11 @@ static inline bool irq_is_percpu_devid(unsigned int irq) return irq_check_status_bit(irq, IRQ_PER_CPU_DEVID); } +static inline int irq_is_oob(unsigned int irq) +{ + return irq_check_status_bit(irq, IRQ_OOB); +} + void __irq_set_lockdep_class(unsigned int irq, struct lock_class_key *lock_class, struct lock_class_key *request_class); static inline void diff --git a/include/linux/irqflags.h b/include/linux/irqflags.h index 2e09c269b..5b138a6b3 100644 --- a/include/linux/irqflags.h +++ b/include/linux/irqflags.h @@ -14,6 +14,7 @@ #include #include +#include #include #include @@ -53,7 +54,9 @@ DECLARE_PER_CPU(int, hardirq_context); extern void trace_hardirqs_on_prepare(void); extern void trace_hardirqs_off_finish(void); extern void trace_hardirqs_on(void); +extern void trace_hardirqs_on_pipelined(void); extern void trace_hardirqs_off(void); +extern void trace_hardirqs_off_pipelined(void); # define lockdep_hardirq_context() (raw_cpu_read(hardirq_context)) # define lockdep_softirq_context(p) ((p)->softirq_context) @@ -115,7 +118,9 @@ do { \ # define trace_hardirqs_on_prepare() do { } while (0) # define trace_hardirqs_off_finish() do { } while (0) # define trace_hardirqs_on() do { } while (0) +# define trace_hardirqs_on_pipelined() do { } while (0) # define trace_hardirqs_off() do { } while (0) +# define trace_hardirqs_off_pipelined() do { } while (0) # define lockdep_hardirq_context() 0 # define lockdep_softirq_context(p) 0 # define lockdep_hardirqs_enabled() 0 @@ -248,6 +253,45 @@ extern void warn_bogus_irq_restore(void); #endif /* CONFIG_TRACE_IRQFLAGS */ +#ifdef CONFIG_IRQ_PIPELINE +#define local_irq_enable_full() \ + do { \ + hard_local_irq_enable(); \ + local_irq_enable(); \ + } while (0) + +#define local_irq_disable_full() \ + do { \ + hard_local_irq_disable(); \ + local_irq_disable(); \ + } while (0) + +#define local_irq_save_full(__flags) \ + do { \ + bool __was_unstalled = running_inband() && !raw_irqs_disabled(); \ + (__flags) = test_and_lock_stage(NULL); \ + if (__was_unstalled) \ + trace_hardirqs_off(); \ + } while (0) + +#define local_irq_restore_full(__flags) \ + do { \ + if (running_inband()) { \ + bool __stalled; \ + stage_disabled_flags(__flags, &__stalled); \ + if (!__stalled) \ + trace_hardirqs_on(); \ + } \ + unlock_stage(__flags); \ + } while (0) + +#else +#define local_irq_enable_full() local_irq_enable() +#define local_irq_disable_full() local_irq_disable() +#define local_irq_save_full(__flags) local_irq_save(__flags) +#define local_irq_restore_full(__flags) local_irq_restore(__flags) +#endif + #define local_save_flags(flags) raw_local_save_flags(flags) /* diff --git a/include/linux/irqreturn.h b/include/linux/irqreturn.h index d426c7ad9..e47cb12af 100644 --- a/include/linux/irqreturn.h +++ b/include/linux/irqreturn.h @@ -7,11 +7,17 @@ * @IRQ_NONE: interrupt was not from this device or was not handled * @IRQ_HANDLED: interrupt was handled by this device * @IRQ_WAKE_THREAD: handler requests to wake the handler thread + * @IRQ_FORWARD interrupt was handled oob _and_ forwarded to in-band (irq_pipeline) */ enum irqreturn { IRQ_NONE = (0 << 0), IRQ_HANDLED = (1 << 0), IRQ_WAKE_THREAD = (1 << 1), +#ifdef CONFIG_IRQ_PIPELINE + IRQ_FORWARD = (1 << 2), +#else + IRQ_FORWARD = IRQ_HANDLED, +#endif }; typedef enum irqreturn irqreturn_t; diff --git a/include/linux/irqstage.h b/include/linux/irqstage.h new file mode 100644 index 000000000..84773e6eb --- /dev/null +++ b/include/linux/irqstage.h @@ -0,0 +1,368 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2016, 2019 Philippe Gerum . + */ +#ifndef _LINUX_IRQSTAGE_H +#define _LINUX_IRQSTAGE_H + +#ifdef CONFIG_IRQ_PIPELINE + +#include +#include +#include +#include +#include + +struct kvm_oob_notifier; + +struct irq_stage { + int index; + const char *name; +}; + +extern struct irq_stage inband_stage; + +extern struct irq_stage oob_stage; + +struct irq_event_map; + +struct irq_log { + unsigned long index_0; + struct irq_event_map *map; +}; + +/* Per-CPU, per-stage data. */ +struct irq_stage_data { + struct irq_log log; + struct irq_stage *stage; +#ifdef CONFIG_DEBUG_IRQ_PIPELINE + int cpu; +#endif +}; + +/* Per-CPU pipeline descriptor. */ +struct irq_pipeline_data { + struct irq_stage_data stages[2]; + struct pt_regs tick_regs; +#ifdef CONFIG_DOVETAIL + struct task_struct *task_inflight; + struct task_struct *rqlock_owner; +#ifdef CONFIG_KVM + struct kvm_oob_notifier *vcpu_notify; +#endif +#endif +}; + +DECLARE_PER_CPU(struct irq_pipeline_data, irq_pipeline); + +/* + * The low-level stall bit accessors. Should be used by the Dovetail + * core implementation exclusively, inband_irq_*() and oob_irq_*() + * accessors are available to common code. + */ + +#define INBAND_STALL_BIT 0 +#define OOB_STALL_BIT 1 + +static __always_inline void init_task_stall_bits(struct task_struct *p) +{ + __set_bit(INBAND_STALL_BIT, &p->stall_bits); + __clear_bit(OOB_STALL_BIT, &p->stall_bits); +} + +static __always_inline void stall_inband_nocheck(void) +{ + __set_bit(INBAND_STALL_BIT, ¤t->stall_bits); + barrier(); +} + +static __always_inline void stall_inband(void) +{ + WARN_ON_ONCE(irq_pipeline_debug() && running_oob()); + stall_inband_nocheck(); +} + +static __always_inline void unstall_inband_nocheck(void) +{ + barrier(); + __clear_bit(INBAND_STALL_BIT, ¤t->stall_bits); +} + +static __always_inline void unstall_inband(void) +{ + WARN_ON_ONCE(irq_pipeline_debug() && running_oob()); + unstall_inband_nocheck(); +} + +static __always_inline int test_and_stall_inband_nocheck(void) +{ + return __test_and_set_bit(INBAND_STALL_BIT, ¤t->stall_bits); +} + +static __always_inline int test_and_stall_inband(void) +{ + WARN_ON_ONCE(irq_pipeline_debug() && running_oob()); + return test_and_stall_inband_nocheck(); +} + +static __always_inline int test_inband_stall(void) +{ + return test_bit(INBAND_STALL_BIT, ¤t->stall_bits); +} + +static __always_inline void stall_oob(void) +{ + __set_bit(OOB_STALL_BIT, ¤t->stall_bits); + barrier(); +} + +static __always_inline void unstall_oob(void) +{ + barrier(); + __clear_bit(OOB_STALL_BIT, ¤t->stall_bits); +} + +static __always_inline int test_and_stall_oob(void) +{ + return __test_and_set_bit(OOB_STALL_BIT, ¤t->stall_bits); +} + +static __always_inline int test_oob_stall(void) +{ + return test_bit(OOB_STALL_BIT, ¤t->stall_bits); +} + +/** + * this_staged - IRQ stage data on the current CPU + * + * Return the address of @stage's data on the current CPU. IRQs must + * be hard disabled to prevent CPU migration. + */ +static __always_inline +struct irq_stage_data *this_staged(struct irq_stage *stage) +{ + return &raw_cpu_ptr(irq_pipeline.stages)[stage->index]; +} + +/** + * percpu_inband_staged - IRQ stage data on specified CPU + * + * Return the address of @stage's data on @cpu. + * + * This is the slowest accessor, use it carefully. Prefer + * this_staged() for requests referring to the current + * CPU. Additionally, if the target stage is known at build time, + * consider using this_{inband, oob}_staged() instead. + */ +static __always_inline +struct irq_stage_data *percpu_inband_staged(struct irq_stage *stage, int cpu) +{ + return &per_cpu(irq_pipeline.stages, cpu)[stage->index]; +} + +/** + * this_inband_staged - return the address of the pipeline context + * data for the inband stage on the current CPU. CPU migration must be + * disabled. + * + * This accessor is recommended when the stage we refer to is known at + * build time to be the inband one. + */ +static __always_inline struct irq_stage_data *this_inband_staged(void) +{ + return raw_cpu_ptr(&irq_pipeline.stages[0]); +} + +/** + * this_oob_staged - return the address of the pipeline context data + * for the registered oob stage on the current CPU. CPU migration must + * be disabled. + * + * This accessor is recommended when the stage we refer to is known at + * build time to be the registered oob stage. This address is always + * different from the context data of the inband stage, even in + * absence of registered oob stage. + */ +static __always_inline struct irq_stage_data *this_oob_staged(void) +{ + return raw_cpu_ptr(&irq_pipeline.stages[1]); +} + +static __always_inline struct irq_stage_data *__current_irq_staged(void) +{ + return &raw_cpu_ptr(irq_pipeline.stages)[stage_level()]; +} + +/** + * current_irq_staged - return the address of the pipeline context + * data for the current stage. CPU migration must be disabled. + */ +#define current_irq_staged __current_irq_staged() + +static __always_inline +void check_staged_locality(struct irq_stage_data *pd) +{ +#ifdef CONFIG_DEBUG_IRQ_PIPELINE + /* + * Setting our context with another processor's is a really + * bad idea, our caller definitely went loopy. + */ + WARN_ON_ONCE(raw_smp_processor_id() != pd->cpu); +#endif +} + +/** + * switch_oob(), switch_inband() - switch the current CPU to the + * specified stage context. CPU migration must be disabled. + * + * Calling these routines is the only sane and safe way to change the + * interrupt stage for the current CPU. Don't bypass them, ever. + * Really. + */ +static __always_inline +void switch_oob(struct irq_stage_data *pd) +{ + check_staged_locality(pd); + if (!(preempt_count() & STAGE_MASK)) + preempt_count_add(STAGE_OFFSET); +} + +static __always_inline +void switch_inband(struct irq_stage_data *pd) +{ + check_staged_locality(pd); + if (preempt_count() & STAGE_MASK) + preempt_count_sub(STAGE_OFFSET); +} + +static __always_inline +void set_current_irq_staged(struct irq_stage_data *pd) +{ + if (pd->stage == &inband_stage) + switch_inband(pd); + else + switch_oob(pd); +} + +static __always_inline struct irq_stage *__current_irq_stage(void) +{ + /* + * We don't have to hard disable irqs while accessing the + * per-CPU stage data here, because there is no way we could + * switch stage and CPU at the same time. + */ + return __current_irq_staged()->stage; +} + +#define current_irq_stage __current_irq_stage() + +static __always_inline bool oob_stage_present(void) +{ + return oob_stage.index != 0; +} + +/** + * stage_irqs_pending() - Whether we have interrupts pending + * (i.e. logged) on the current CPU for the given stage. Hard IRQs + * must be disabled. + */ +static __always_inline int stage_irqs_pending(struct irq_stage_data *pd) +{ + return pd->log.index_0 != 0; +} + +void sync_current_irq_stage(void); + +void sync_irq_stage(struct irq_stage *top); + +void irq_post_stage(struct irq_stage *stage, + unsigned int irq); + +static __always_inline void irq_post_oob(unsigned int irq) +{ + irq_post_stage(&oob_stage, irq); +} + +static __always_inline void irq_post_inband(unsigned int irq) +{ + irq_post_stage(&inband_stage, irq); +} + +static __always_inline void oob_irq_disable(void) +{ + hard_local_irq_disable(); + stall_oob(); +} + +static __always_inline unsigned long oob_irq_save(void) +{ + hard_local_irq_disable(); + return test_and_stall_oob(); +} + +static __always_inline int oob_irqs_disabled(void) +{ + return test_oob_stall(); +} + +void oob_irq_enable(void); + +void __oob_irq_restore(unsigned long x); + +static __always_inline void oob_irq_restore(unsigned long x) +{ + if ((x ^ test_oob_stall()) & 1) + __oob_irq_restore(x); +} + +int enable_oob_stage(const char *name); + +int arch_enable_oob_stage(void); + +void disable_oob_stage(void); + +#else /* !CONFIG_IRQ_PIPELINE */ + +#include + +void call_is_nop_without_pipelining(void); + +static __always_inline void stall_inband(void) { } + +static __always_inline void unstall_inband(void) { } + +static __always_inline int test_and_stall_inband(void) +{ + return false; +} + +static __always_inline int test_inband_stall(void) +{ + return false; +} + +static __always_inline bool oob_stage_present(void) +{ + return false; +} + +static __always_inline void irq_post_inband(unsigned int irq) +{ + call_is_nop_without_pipelining(); +} + +static __always_inline void stall_inband_nocheck(void) +{ } + +static __always_inline void unstall_inband_nocheck(void) +{ } + +static __always_inline int test_and_stall_inband_nocheck(void) +{ + return irqs_disabled(); +} + +#endif /* !CONFIG_IRQ_PIPELINE */ + +#endif /* !_LINUX_IRQSTAGE_H */ diff --git a/include/linux/kernel.h b/include/linux/kernel.h index cee8fe87e..c6bef691a 100644 --- a/include/linux/kernel.h +++ b/include/linux/kernel.h @@ -33,6 +33,7 @@ #include #include #include +#include #include @@ -119,7 +120,7 @@ extern int dynamic_might_resched(void); #else -# define might_resched() do { } while (0) +# define might_resched() check_inband_stage() #endif /* CONFIG_PREEMPT_* */ diff --git a/include/linux/kvm_host.h b/include/linux/kvm_host.h index fb6c6109f..5743346a9 100644 --- a/include/linux/kvm_host.h +++ b/include/linux/kvm_host.h @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -319,10 +320,23 @@ struct kvm_mmio_fragment { unsigned len; }; +/* + * Called when the host is about to leave the inband stage. Typically + * used for switching the current vcpu out of guest mode before a + * companion core reinstates an oob task context. + */ +struct kvm_oob_notifier { + void (*handler)(struct kvm_oob_notifier *nfy); + bool put_vcpu; +}; + struct kvm_vcpu { struct kvm *kvm; #ifdef CONFIG_PREEMPT_NOTIFIERS struct preempt_notifier preempt_notifier; +#endif +#ifdef CONFIG_DOVETAIL + struct kvm_oob_notifier oob_notifier; #endif int cpu; int vcpu_id; /* id given by userspace at creation */ @@ -2281,6 +2295,47 @@ static inline int kvm_arch_vcpu_run_pid_change(struct kvm_vcpu *vcpu) } #endif /* CONFIG_HAVE_KVM_VCPU_RUN_PID_CHANGE */ +#if defined(CONFIG_DOVETAIL) && defined(CONFIG_KVM) +static inline void inband_init_vcpu(struct kvm_vcpu *vcpu, + void (*preempt_handler)(struct kvm_oob_notifier *nfy)) +{ + vcpu->oob_notifier.handler = preempt_handler; + vcpu->oob_notifier.put_vcpu = false; +} + +static inline void inband_enter_guest(struct kvm_vcpu *vcpu) +{ + struct irq_pipeline_data *p = raw_cpu_ptr(&irq_pipeline); + WRITE_ONCE(p->vcpu_notify, &vcpu->oob_notifier); +} + +static inline void inband_exit_guest(void) +{ + struct irq_pipeline_data *p = raw_cpu_ptr(&irq_pipeline); + WRITE_ONCE(p->vcpu_notify, NULL); +} + +static inline void inband_set_vcpu_release_state(struct kvm_vcpu *vcpu, + bool pending) +{ + vcpu->oob_notifier.put_vcpu = pending; +} +#else +static inline void inband_init_vcpu(struct kvm_vcpu *vcpu, + void (*preempt_handler)(struct kvm_oob_notifier *nfy)) +{ } + +static inline void inband_enter_guest(struct kvm_vcpu *vcpu) +{ } + +static inline void inband_exit_guest(void) +{ } + +static inline void inband_set_vcpu_release_state(struct kvm_vcpu *vcpu, + bool pending) +{ } +#endif + typedef int (*kvm_vm_thread_fn_t)(struct kvm *kvm, uintptr_t data); int kvm_vm_create_worker_thread(struct kvm *kvm, kvm_vm_thread_fn_t thread_fn, diff --git a/include/linux/lockdep.h b/include/linux/lockdep.h index 919a5cb63..5374b5763 100644 --- a/include/linux/lockdep.h +++ b/include/linux/lockdep.h @@ -211,29 +211,31 @@ static inline void lockdep_init_map(struct lockdep_map *lock, const char *name, * of dependencies wrong: they are either too broad (they need a class-split) * or they are too narrow (they suffer from a false class-split): */ -#define lockdep_set_class(lock, key) \ - lockdep_init_map_type(&(lock)->dep_map, #key, key, 0, \ - (lock)->dep_map.wait_type_inner, \ - (lock)->dep_map.wait_type_outer, \ - (lock)->dep_map.lock_type) - -#define lockdep_set_class_and_name(lock, key, name) \ - lockdep_init_map_type(&(lock)->dep_map, name, key, 0, \ - (lock)->dep_map.wait_type_inner, \ - (lock)->dep_map.wait_type_outer, \ - (lock)->dep_map.lock_type) - -#define lockdep_set_class_and_subclass(lock, key, sub) \ - lockdep_init_map_type(&(lock)->dep_map, #key, key, sub, \ - (lock)->dep_map.wait_type_inner, \ - (lock)->dep_map.wait_type_outer, \ - (lock)->dep_map.lock_type) +#define lockdep_set_class(lock, key) \ + lockdep_init_map_type(LOCKDEP_ALT_DEPMAP(lock), #key, key, 0, \ + LOCKDEP_ALT_DEPMAP(lock)->wait_type_inner, \ + LOCKDEP_ALT_DEPMAP(lock)->wait_type_outer, \ + LOCKDEP_ALT_DEPMAP(lock)->lock_type) + +#define lockdep_set_class_and_name(lock, key, name) \ + lockdep_init_map_type(LOCKDEP_ALT_DEPMAP(lock), name, key, 0, \ + LOCKDEP_ALT_DEPMAP(lock)->wait_type_inner, \ + LOCKDEP_ALT_DEPMAP(lock)->wait_type_outer, \ + LOCKDEP_ALT_DEPMAP(lock)->lock_type) + +#define lockdep_set_class_and_subclass(lock, key, sub) \ + lockdep_init_map_type(LOCKDEP_ALT_DEPMAP(lock), #key, key, sub, \ + LOCKDEP_ALT_DEPMAP(lock)->wait_type_inner, \ + LOCKDEP_ALT_DEPMAP(lock)->wait_type_outer, \ + LOCKDEP_ALT_DEPMAP(lock)->lock_type) #define lockdep_set_subclass(lock, sub) \ - lockdep_init_map_type(&(lock)->dep_map, (lock)->dep_map.name, (lock)->dep_map.key, sub,\ - (lock)->dep_map.wait_type_inner, \ - (lock)->dep_map.wait_type_outer, \ - (lock)->dep_map.lock_type) + lockdep_init_map_type(LOCKDEP_ALT_DEPMAP(lock), \ + LOCKDEP_ALT_DEPMAP(lock)->name, \ + LOCKDEP_ALT_DEPMAP(lock)->key, sub, \ + LOCKDEP_ALT_DEPMAP(lock)->wait_type_inner, \ + LOCKDEP_ALT_DEPMAP(lock)->wait_type_outer, \ + LOCKDEP_ALT_DEPMAP(lock)->lock_type) #define lockdep_set_novalidate_class(lock) \ lockdep_set_class_and_name(lock, &__lockdep_no_validate__, #lock) @@ -241,7 +243,8 @@ static inline void lockdep_init_map(struct lockdep_map *lock, const char *name, /* * Compare locking classes */ -#define lockdep_match_class(lock, key) lockdep_match_key(&(lock)->dep_map, key) +#define lockdep_match_class(lock, key) \ + lockdep_match_key(LOCKDEP_ALT_DEPMAP(lock), key) static inline int lockdep_match_key(struct lockdep_map *lock, struct lock_class_key *key) @@ -288,8 +291,8 @@ static inline int lock_is_held(const struct lockdep_map *lock) return lock_is_held_type(lock, -1); } -#define lockdep_is_held(lock) lock_is_held(&(lock)->dep_map) -#define lockdep_is_held_type(lock, r) lock_is_held_type(&(lock)->dep_map, (r)) +#define lockdep_is_held(lock) lock_is_held(LOCKDEP_ALT_DEPMAP(lock)) +#define lockdep_is_held_type(lock, r) lock_is_held_type(LOCKDEP_ALT_DEPMAP(lock), (r)) extern void lock_set_class(struct lockdep_map *lock, const char *name, struct lock_class_key *key, unsigned int subclass, @@ -321,28 +324,34 @@ extern void lock_unpin_lock(struct lockdep_map *lock, struct pin_cookie); do { WARN_ON_ONCE(debug_locks && !(cond)); } while (0) #define lockdep_assert_held(l) \ - lockdep_assert(lockdep_is_held(l) != LOCK_STATE_NOT_HELD) + lockdep_assert(LOCKDEP_HARD_DEBUG_RET(l, 1, \ + lockdep_is_held(l) != LOCK_STATE_NOT_HELD)) #define lockdep_assert_not_held(l) \ - lockdep_assert(lockdep_is_held(l) != LOCK_STATE_HELD) + lockdep_assert(LOCKDEP_HARD_DEBUG_RET(l, 1, \ + lockdep_is_held(l) != LOCK_STATE_HELD)) #define lockdep_assert_held_write(l) \ - lockdep_assert(lockdep_is_held_type(l, 0)) + lockdep_assert(LOCKDEP_HARD_DEBUG_RET(l, 1, \ + lockdep_is_held_type(l, 0))) #define lockdep_assert_held_read(l) \ - lockdep_assert(lockdep_is_held_type(l, 1)) + lockdep_assert(LOCKDEP_HARD_DEBUG_RET(l, 1, \ + lockdep_is_held_type(l, 1))) #define lockdep_assert_held_once(l) \ - lockdep_assert_once(lockdep_is_held(l) != LOCK_STATE_NOT_HELD) + lockdep_assert_once(LOCKDEP_HARD_DEBUG_RET(l, 1, \ + lockdep_is_held(l) != LOCK_STATE_NOT_HELD)) #define lockdep_assert_none_held_once() \ lockdep_assert_once(!current->lockdep_depth) #define lockdep_recursing(tsk) ((tsk)->lockdep_recursion) -#define lockdep_pin_lock(l) lock_pin_lock(&(l)->dep_map) -#define lockdep_repin_lock(l,c) lock_repin_lock(&(l)->dep_map, (c)) -#define lockdep_unpin_lock(l,c) lock_unpin_lock(&(l)->dep_map, (c)) +#define lockdep_pin_lock(l) LOCKDEP_HARD_DEBUG_RET(l, ({ struct pin_cookie cookie; cookie;} ), \ + lock_pin_lock(LOCKDEP_ALT_DEPMAP(l))) +#define lockdep_repin_lock(l,c) LOCKDEP_HARD_DEBUG(l,, lock_repin_lock(LOCKDEP_ALT_DEPMAP(l), (c))) +#define lockdep_unpin_lock(l,c) LOCKDEP_HARD_DEBUG(l,, lock_unpin_lock(LOCKDEP_ALT_DEPMAP(l), (c))) /* * Must use lock_map_aquire_try() with override maps to avoid @@ -586,22 +595,22 @@ do { \ #ifdef CONFIG_PROVE_LOCKING # define might_lock(lock) \ do { \ - typecheck(struct lockdep_map *, &(lock)->dep_map); \ - lock_acquire(&(lock)->dep_map, 0, 0, 0, 1, NULL, _THIS_IP_); \ - lock_release(&(lock)->dep_map, _THIS_IP_); \ + typecheck(struct lockdep_map *, LOCKDEP_ALT_DEPMAP(lock)); \ + lock_acquire(LOCKDEP_ALT_DEPMAP(lock), 0, 0, 0, 1, NULL, _THIS_IP_); \ + lock_release(LOCKDEP_ALT_DEPMAP(lock), _THIS_IP_); \ } while (0) # define might_lock_read(lock) \ do { \ - typecheck(struct lockdep_map *, &(lock)->dep_map); \ - lock_acquire(&(lock)->dep_map, 0, 0, 1, 1, NULL, _THIS_IP_); \ - lock_release(&(lock)->dep_map, _THIS_IP_); \ + typecheck(struct lockdep_map *, LOCKDEP_ALT_DEPMAP(lock)); \ + lock_acquire(LOCKDEP_ALT_DEPMAP(lock), 0, 0, 1, 1, NULL, _THIS_IP_); \ + lock_release(LOCKDEP_ALT_DEPMAP(lock), _THIS_IP_); \ } while (0) # define might_lock_nested(lock, subclass) \ do { \ - typecheck(struct lockdep_map *, &(lock)->dep_map); \ - lock_acquire(&(lock)->dep_map, subclass, 0, 1, 1, NULL, \ + typecheck(struct lockdep_map *, LOCKDEP_ALT_DEPMAP(lock)); \ + lock_acquire(LOCKDEP_ALT_DEPMAP(lock), subclass, 0, 1, 1, NULL, \ _THIS_IP_); \ - lock_release(&(lock)->dep_map, _THIS_IP_); \ + lock_release(LOCKDEP_ALT_DEPMAP(lock), _THIS_IP_); \ } while (0) DECLARE_PER_CPU(int, hardirqs_enabled); @@ -610,14 +619,32 @@ DECLARE_PER_CPU(unsigned int, lockdep_recursion); #define __lockdep_enabled (debug_locks && !this_cpu_read(lockdep_recursion)) +#define __lockdep_check_irqs_enabled() \ + ({ !hard_irqs_disabled() && \ + (running_oob() || this_cpu_read(hardirqs_enabled)); }) + #define lockdep_assert_irqs_enabled() \ -do { \ - WARN_ON_ONCE(__lockdep_enabled && !this_cpu_read(hardirqs_enabled)); \ -} while (0) + do { \ + WARN_ON_ONCE(__lockdep_enabled && \ + !__lockdep_check_irqs_enabled()); \ + } while (0) + +#define __lockdep_check_irqs_disabled() \ + ({ hard_irqs_disabled() || \ + (running_inband() && !this_cpu_read(hardirqs_enabled)); }) #define lockdep_assert_irqs_disabled() \ + do { \ + WARN_ON_ONCE(__lockdep_enabled && \ + !__lockdep_check_irqs_disabled()); \ + } while (0) + +#define lockdep_read_irqs_state() \ + ({ this_cpu_read(hardirqs_enabled); }) + +#define lockdep_write_irqs_state(__state) \ do { \ - WARN_ON_ONCE(__lockdep_enabled && this_cpu_read(hardirqs_enabled)); \ + this_cpu_write(hardirqs_enabled, __state); \ } while (0) #define lockdep_assert_in_irq() \ @@ -636,7 +663,7 @@ do { \ WARN_ON_ONCE(IS_ENABLED(CONFIG_PREEMPT_COUNT) && \ __lockdep_enabled && \ (preempt_count() != 0 || \ - !this_cpu_read(hardirqs_enabled))); \ + __lockdep_check_irqs_disabled())); \ } while (0) #define lockdep_assert_preemption_disabled() \ @@ -644,7 +671,7 @@ do { \ WARN_ON_ONCE(IS_ENABLED(CONFIG_PREEMPT_COUNT) && \ __lockdep_enabled && \ (preempt_count() == 0 && \ - this_cpu_read(hardirqs_enabled))); \ + __lockdep_check_irqs_enabled())); \ } while (0) /* @@ -664,6 +691,8 @@ do { \ # define lockdep_assert_irqs_enabled() do { } while (0) # define lockdep_assert_irqs_disabled() do { } while (0) +# define lockdep_read_irqs_state() 0 +# define lockdep_write_irqs_state(__state) do { (void)(__state); } while (0) # define lockdep_assert_in_irq() do { } while (0) # define lockdep_assert_no_hardirq() do { } while (0) diff --git a/include/linux/mm.h b/include/linux/mm.h index 209370f64..b6b67aa43 100644 --- a/include/linux/mm.h +++ b/include/linux/mm.h @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -1950,11 +1951,20 @@ static inline bool page_maybe_dma_pinned(struct page *page) * * The caller has to hold the PT lock and the vma->vm_mm->->write_protect_seq. */ -static inline bool page_needs_cow_for_dma(struct vm_area_struct *vma, - struct page *page) +static inline bool page_needs_cow(struct vm_area_struct *vma, + struct page *page) { VM_BUG_ON(!(raw_read_seqcount(&vma->vm_mm->write_protect_seq) & 1)); + /* + * Dovetail: If the source mm belongs to a dovetailed process, + * we don't want to impose the COW-induced latency on it: make + * sure the child gets its own copy of the page. + */ + if (IS_ENABLED(CONFIG_DOVETAIL) && + test_bit(MMF_DOVETAILED, &vma->vm_mm->flags)) + return true; + if (!test_bit(MMF_HAS_PINNED, &vma->vm_mm->flags)) return false; diff --git a/include/linux/mm_types.h b/include/linux/mm_types.h index e77d4a5c0..c0d40bf04 100644 --- a/include/linux/mm_types.h +++ b/include/linux/mm_types.h @@ -22,6 +22,8 @@ #include +#include + #ifndef AT_VECTOR_SIZE_ARCH #define AT_VECTOR_SIZE_ARCH 0 #endif @@ -938,6 +940,9 @@ struct mm_struct { #endif #ifdef CONFIG_HUGETLB_PAGE atomic_long_t hugetlb_usage; +#endif +#ifdef CONFIG_DOVETAIL + struct oob_mm_state oob_state; #endif struct work_struct async_put_work; diff --git a/include/linux/net.h b/include/linux/net.h index c9b4a6379..5607d77db 100644 --- a/include/linux/net.h +++ b/include/linux/net.h @@ -81,6 +81,7 @@ enum sock_type { #ifndef SOCK_NONBLOCK #define SOCK_NONBLOCK O_NONBLOCK #endif +#define SOCK_OOB O_OOB #endif /* ARCH_HAS_SOCKET_TYPES */ @@ -323,6 +324,16 @@ static inline bool sendpage_ok(struct page *page) return !PageSlab(page) && page_count(page) >= 1; } +static inline bool net_running_oob(void) +{ + /* + * Ensure depending code blocks are compiled out if + * CONFIG_NET_OOB is disabled even if CONFIG_DOVETAIL is + * enabled. + */ + return IS_ENABLED(CONFIG_NET_OOB) && running_oob(); +} + int kernel_sendmsg(struct socket *sock, struct msghdr *msg, struct kvec *vec, size_t num, size_t len); int kernel_sendmsg_locked(struct sock *sk, struct msghdr *msg, diff --git a/include/linux/netdevice.h b/include/linux/netdevice.h index 1576e7443..7880fb84f 100644 --- a/include/linux/netdevice.h +++ b/include/linux/netdevice.h @@ -49,6 +49,7 @@ #include #include #include +#include #include #include #include @@ -333,6 +334,8 @@ enum netdev_state_t { __LINK_STATE_LINKWATCH_PENDING, __LINK_STATE_DORMANT, __LINK_STATE_TESTING, + __LINK_STATE_OOB_PORT, + __LINK_STATE_OOB, }; struct gro_list { @@ -481,6 +484,7 @@ static inline bool napi_prefer_busy_poll(struct napi_struct *n) } bool napi_schedule_prep(struct napi_struct *n); +bool napi_schedule_unprep(struct napi_struct *n); /** * napi_schedule - schedule NAPI poll @@ -655,6 +659,8 @@ struct netdev_queue { unsigned long state; + struct oob_netqueue_state oob; + #ifdef CONFIG_BQL struct dql dql; #endif @@ -1406,6 +1412,13 @@ struct netdev_net_notifier { * struct kernel_hwtstamp_config *kernel_config, * struct netlink_ext_ack *extack); * Change the hardware timestamping parameters for NIC device. + * void (*ndo_enable_oob)(struct net_device *dev); + * Turn on out-of-band I/O handling. On return from this handler, the device + * must be prepared to handle RX/TX packets from the out-of-band stage. This + * handler is optional. + * void (*ndo_disable_oob)(struct net_device *dev); + * Turn off out-of-band I/O handling, reverting the effect of ndo_enable_oob(). + * This handler is optional. */ struct net_device_ops { int (*ndo_init)(struct net_device *dev); @@ -1645,6 +1658,10 @@ struct net_device_ops { int (*ndo_hwtstamp_set)(struct net_device *dev, struct kernel_hwtstamp_config *kernel_config, struct netlink_ext_ack *extack); +#ifdef CONFIG_NET_OOB + int (*ndo_enable_oob)(struct net_device *dev); + void (*ndo_disable_oob)(struct net_device *dev); +#endif }; /** @@ -1698,6 +1715,7 @@ struct net_device_ops { * @IFF_SEE_ALL_HWTSTAMP_REQUESTS: device wants to see calls to * ndo_hwtstamp_set() for all timestamp requests regardless of source, * even if those aren't HWTSTAMP_SOURCE_NETDEV. + * @IFF_OOB_CAPABLE: device supports direct out-of-band I/O operations. */ enum netdev_priv_flags { IFF_802_1Q_VLAN = 1<<0, @@ -1734,6 +1752,8 @@ enum netdev_priv_flags { IFF_TX_SKB_NO_LINEAR = BIT_ULL(31), IFF_CHANGE_PROTO_DOWN = BIT_ULL(32), IFF_SEE_ALL_HWTSTAMP_REQUESTS = BIT_ULL(33), + IFF_OOB_CAPABLE = BIT_ULL(34), + IFF_OOB_PORT = BIT_ULL(35), }; #define IFF_802_1Q_VLAN IFF_802_1Q_VLAN @@ -1767,6 +1787,7 @@ enum netdev_priv_flags { #define IFF_FAILOVER_SLAVE IFF_FAILOVER_SLAVE #define IFF_L3MDEV_RX_HANDLER IFF_L3MDEV_RX_HANDLER #define IFF_TX_SKB_NO_LINEAR IFF_TX_SKB_NO_LINEAR +#define IFF_OOB_CAPABLE IFF_OOB_CAPABLE /* Specifies the type of the struct net_device::ml_priv pointer */ enum netdev_ml_priv_type { @@ -1850,6 +1871,7 @@ enum netdev_stat_type { * @tlsdev_ops: Transport Layer Security offload operations * @header_ops: Includes callbacks for creating,parsing,caching,etc * of Layer 2 headers. + * @oob_state: Out-of-band networking state (oob stage diversion) * * @flags: Interface flags (a la BSD) * @xdp_features: XDP capability supported by the device @@ -2159,6 +2181,10 @@ struct net_device { const struct tlsdev_ops *tlsdev_ops; #endif +#ifdef CONFIG_NET_OOB + struct oob_netdev_state oob_state; +#endif + const struct header_ops *header_ops; unsigned char operstate; @@ -3221,6 +3247,11 @@ struct softnet_data { #ifdef CONFIG_NET_FLOW_LIMIT struct sd_flow_limit __rcu *flow_limit; +#endif +#ifdef CONFIG_NET_OOB + struct list_head inband_rx_list; /* Inband skbs received oob */ + hard_spinlock_t inband_rx_lock; + struct irq_work inband_rx_work; #endif struct Qdisc *output_queue; struct Qdisc **output_queue_tailp; @@ -4306,6 +4337,120 @@ void netif_device_detach(struct net_device *dev); void netif_device_attach(struct net_device *dev); +#ifdef CONFIG_NET_OOB + +static inline void netdev_set_oob_capable(struct net_device *dev) +{ + dev->priv_flags |= IFF_OOB_CAPABLE; +} + +static inline bool netdev_is_oob_capable(struct net_device *dev) +{ + return !!(dev->priv_flags & IFF_OOB_CAPABLE); +} + +bool netif_receive_oob(struct sk_buff *skb); + +/** + * netif_oob_diversion - is the ingress traffic diverted for out-of-band handling? + * @dev: network device + * + * Check if the RX packets are currently diverted to a companion + * kernel for out-of-band handling. + */ +static inline bool netif_oob_diversion(const struct net_device *dev) +{ + return test_bit(__LINK_STATE_OOB, &dev->state); +} + +static inline void netif_enable_oob_diversion(struct net_device *dev) +{ + const struct net_device_ops *ops = dev->netdev_ops; + + if (ops->ndo_enable_oob) + ops->ndo_enable_oob(dev); + + set_bit(__LINK_STATE_OOB, &dev->state); +} + +static inline void netif_disable_oob_diversion(struct net_device *dev) +{ + const struct net_device_ops *ops = dev->netdev_ops; + + clear_bit(__LINK_STATE_OOB, &dev->state); + smp_mb__after_atomic(); + + if (ops->ndo_disable_oob) + ops->ndo_disable_oob(dev); +} + +/** + * netif_oob_port - is the interface an active oob port? + * @dev: network device + * + * Check whether the interface acts as a virtual port for handling oob + * traffic. + */ +static inline bool netif_oob_port(struct net_device *dev) +{ + return test_bit(__LINK_STATE_OOB_PORT, &dev->state); +} + +static inline void netif_enable_oob_port(struct net_device *dev) +{ + set_bit(__LINK_STATE_OOB_PORT, &dev->state); +} + +static inline void netif_disable_oob_port(struct net_device *dev) +{ + clear_bit(__LINK_STATE_OOB_PORT, &dev->state); + smp_mb__after_atomic(); +} + +/* Out-of-band hooks implemented by the companion core. */ +void napi_schedule_oob(struct napi_struct *n); +void napi_complete_oob(struct napi_struct *n); +bool netif_deliver_oob(struct sk_buff *skb); +void netif_tx_lock_oob(struct netdev_queue *txq); +void netif_tx_unlock_oob(struct netdev_queue *txq); +void process_inband_tx_backlog(struct softnet_data *sd); + +#else /* !CONFIG_NET_OOB */ + +static inline void netdev_set_oob_capable(struct net_device *dev) +{ +} + +static inline bool netif_receive_oob(struct sk_buff *skb) +{ + return false; +} + +static inline bool netif_oob_diversion(const struct net_device *dev) +{ + return false; +} + +static inline bool netif_oob_port(struct net_device *dev) +{ + return false; +} + +static inline bool netdev_is_oob_capable(struct net_device *dev) +{ + return false; +} + +static inline void netif_tx_lock_oob(struct netdev_queue *txq) +{ +} + +static inline void netif_tx_unlock_oob(struct netdev_queue *txq) +{ +} + +#endif /* !CONFIG_NET_OOB */ + /* * Network interface message level settings */ diff --git a/include/linux/poll.h b/include/linux/poll.h index fc641b50f..74c7881c4 100644 --- a/include/linux/poll.h +++ b/include/linux/poll.h @@ -9,6 +9,7 @@ #include #include #include +#include #include #include diff --git a/include/linux/preempt.h b/include/linux/preempt.h index 9aa6358a1..6382c16a9 100644 --- a/include/linux/preempt.h +++ b/include/linux/preempt.h @@ -28,17 +28,23 @@ * SOFTIRQ_MASK: 0x0000ff00 * HARDIRQ_MASK: 0x000f0000 * NMI_MASK: 0x00f00000 + * PIPELINE_MASK: 0x01000000 + * STAGE_MASK: 0x02000000 * PREEMPT_NEED_RESCHED: 0x80000000 */ #define PREEMPT_BITS 8 #define SOFTIRQ_BITS 8 #define HARDIRQ_BITS 4 #define NMI_BITS 4 +#define PIPELINE_BITS 1 +#define STAGE_BITS 1 #define PREEMPT_SHIFT 0 #define SOFTIRQ_SHIFT (PREEMPT_SHIFT + PREEMPT_BITS) #define HARDIRQ_SHIFT (SOFTIRQ_SHIFT + SOFTIRQ_BITS) #define NMI_SHIFT (HARDIRQ_SHIFT + HARDIRQ_BITS) +#define PIPELINE_SHIFT (NMI_SHIFT + NMI_BITS) +#define STAGE_SHIFT (PIPELINE_SHIFT + PIPELINE_BITS) #define __IRQ_MASK(x) ((1UL << (x))-1) @@ -46,11 +52,15 @@ #define SOFTIRQ_MASK (__IRQ_MASK(SOFTIRQ_BITS) << SOFTIRQ_SHIFT) #define HARDIRQ_MASK (__IRQ_MASK(HARDIRQ_BITS) << HARDIRQ_SHIFT) #define NMI_MASK (__IRQ_MASK(NMI_BITS) << NMI_SHIFT) +#define PIPELINE_MASK (__IRQ_MASK(PIPELINE_BITS) << PIPELINE_SHIFT) +#define STAGE_MASK (__IRQ_MASK(STAGE_BITS) << STAGE_SHIFT) #define PREEMPT_OFFSET (1UL << PREEMPT_SHIFT) #define SOFTIRQ_OFFSET (1UL << SOFTIRQ_SHIFT) #define HARDIRQ_OFFSET (1UL << HARDIRQ_SHIFT) #define NMI_OFFSET (1UL << NMI_SHIFT) +#define PIPELINE_OFFSET (1UL << PIPELINE_SHIFT) +#define STAGE_OFFSET (1UL << STAGE_SHIFT) #define SOFTIRQ_DISABLE_OFFSET (2 * SOFTIRQ_OFFSET) @@ -115,6 +125,9 @@ static __always_inline unsigned char interrupt_context_level(void) # define irq_count() (preempt_count() & (NMI_MASK | HARDIRQ_MASK | SOFTIRQ_MASK)) #endif +/* The current IRQ stage level: 0=inband, 1=oob */ +#define stage_level() ((preempt_count() & STAGE_MASK) >> STAGE_SHIFT) + /* * Macros to retrieve the current execution context: * @@ -137,10 +150,12 @@ static __always_inline unsigned char interrupt_context_level(void) * in_irq() - Obsolete version of in_hardirq() * in_softirq() - We have BH disabled, or are processing softirqs * in_interrupt() - We're in NMI,IRQ,SoftIRQ context or have BH disabled + * in_pipeline() - We're on pipeline entry */ #define in_irq() (hardirq_count()) #define in_softirq() (softirq_count()) #define in_interrupt() (irq_count()) +#define in_pipeline() (preempt_count() & PIPELINE_MASK) /* * The preempt_count offset after preempt_disable(); @@ -224,7 +239,8 @@ do { \ #define preempt_enable_no_resched() sched_preempt_enable_no_resched() -#define preemptible() (preempt_count() == 0 && !irqs_disabled()) +#define preemptible() (preempt_count() == 0 && \ + !hard_irqs_disabled() && !irqs_disabled()) #ifdef CONFIG_PREEMPTION #define preempt_enable() \ @@ -296,6 +312,21 @@ do { \ #endif /* CONFIG_PREEMPT_COUNT */ +#ifdef CONFIG_IRQ_PIPELINE +/* + * We legitimately need unlimited access to + * preempt_enable_no_resched_notrace() when pipelining interrupts, + * including from code which may be compiled in modules. Create an + * internal alias before this macro gets undefined below. + */ +static __always_inline void __preempt_enable_no_resched_notrace(void) +{ + preempt_enable_no_resched_notrace(); +} +#else +#define __preempt_enable_no_resched_notrace() do { } while(0) +#endif + #ifdef MODULE /* * Modules have no business playing preemption tricks. @@ -479,4 +510,59 @@ DEFINE_LOCK_GUARD_0(preempt, preempt_disable(), preempt_enable()) DEFINE_LOCK_GUARD_0(preempt_notrace, preempt_disable_notrace(), preempt_enable_notrace()) DEFINE_LOCK_GUARD_0(migrate, migrate_disable(), migrate_enable()) +#ifdef CONFIG_IRQ_PIPELINE + +static __always_inline bool running_inband(void) +{ + return stage_level() == 0; +} + +static __always_inline bool running_oob(void) +{ + return !running_inband(); +} + +unsigned long hard_preempt_disable(void); +void hard_preempt_enable(unsigned long flags); +unsigned long hard_bh_disable(void); +void hard_bh_enable(unsigned long flags); + +#else /* !CONFIG_IRQ_PIPELINE */ + +static __always_inline bool running_inband(void) +{ + return true; +} + +static __always_inline bool running_oob(void) +{ + return false; +} + +#define hard_preempt_disable() \ +({ \ + preempt_disable(); \ + 0; \ +}) + +#define hard_preempt_enable(__flags) \ + do { \ + preempt_enable(); \ + (void)(__flags); \ + } while (0) + +#define hard_bh_disable() \ +({ \ + local_bh_disable(); \ + 0; \ +}) + +#define hard_bh_enable(__flags) \ + do { \ + local_bh_enable(); \ + (void)(__flags); \ + } while (0) + +#endif /* !CONFIG_IRQ_PIPELINE */ + #endif /* __LINUX_PREEMPT_H */ diff --git a/include/linux/printk.h b/include/linux/printk.h index e4878bb58..3f04357b4 100644 --- a/include/linux/printk.h +++ b/include/linux/printk.h @@ -140,6 +140,20 @@ void early_printk(const char *s, ...) { } struct dev_printk_info; +#ifdef CONFIG_RAW_PRINTK +void raw_puts(const char *s, size_t len); +void raw_vprintk(const char *fmt, va_list ap); +asmlinkage __printf(1, 2) +void raw_printk(const char *fmt, ...); +#else +static inline __cold +void raw_puts(const char *s, size_t len) { } +static inline __cold +void raw_vprintk(const char *s, va_list ap) { } +static inline __printf(1, 2) __cold +void raw_printk(const char *s, ...) { } +#endif + #ifdef CONFIG_PRINTK asmlinkage __printf(4, 0) int vprintk_emit(int facility, int level, @@ -305,14 +319,22 @@ extern void __printk_cpu_sync_put(void); * unsafe to perform any type of locking or spinning to wait for other * CPUs after calling this function from any context. This includes * using spinlocks or any other busy-waiting synchronization methods. + * + * irq_pipeline: we neither need nor want to disable in-band IRQs over + * the oob stage or pipeline entry contexts, where CPU migration can't + * happen. Conversely, we neither need nor want to disable hard IRQs + * from the oob stage, so that latency won't skyrocket as a result of + * holding the print lock. */ -#define printk_cpu_sync_get_irqsave(flags) \ - for (;;) { \ - local_irq_save(flags); \ - if (__printk_cpu_sync_try_get()) \ - break; \ - local_irq_restore(flags); \ - __printk_cpu_sync_wait(); \ +#define printk_cpu_sync_get_irqsave(flags) \ + for (;;) { \ + if (running_inband() && !on_pipeline_entry()) \ + local_irq_save(flags); \ + if (__printk_cpu_sync_try_get()) \ + break; \ + if (running_inband() && !on_pipeline_entry()) \ + local_irq_restore(flags); \ + __printk_cpu_sync_wait(); \ } /** @@ -320,10 +342,11 @@ extern void __printk_cpu_sync_put(void); * lock and restore interrupts. * @flags: Caller's saved interrupt state, from printk_cpu_sync_get_irqsave(). */ -#define printk_cpu_sync_put_irqrestore(flags) \ - do { \ - __printk_cpu_sync_put(); \ - local_irq_restore(flags); \ +#define printk_cpu_sync_put_irqrestore(flags) \ + do { \ + __printk_cpu_sync_put(); \ + if (running_inband() && !on_pipeline_entry()) \ + local_irq_restore(flags); \ } while (0) extern int kptr_restrict; @@ -645,7 +668,7 @@ struct pi_entry { DEFAULT_RATELIMIT_INTERVAL, \ DEFAULT_RATELIMIT_BURST); \ \ - if (__ratelimit(&_rs)) \ + if (running_oob() || __ratelimit(&_rs)) \ printk(fmt, ##__VA_ARGS__); \ }) #else diff --git a/include/linux/rcupdate.h b/include/linux/rcupdate.h index 7602d1f8a..a265b3ac1 100644 --- a/include/linux/rcupdate.h +++ b/include/linux/rcupdate.h @@ -157,6 +157,14 @@ static inline int rcu_nocb_cpu_deoffload(int cpu) { return 0; } static inline void rcu_nocb_flush_deferred_wakeup(void) { } #endif /* #else #ifdef CONFIG_RCU_NOCB_CPU */ +#ifdef CONFIG_IRQ_PIPELINE +void rcu_oob_prepare_lock(void); +void rcu_oob_finish_lock(void); +#else +#define rcu_oob_prepare_lock() do { } while (0) +#define rcu_oob_finish_lock() do { } while (0) +#endif + /* * Note a quasi-voluntary context switch for RCU-tasks's benefit. * This is a macro rather than an inline function to avoid #include hell. @@ -368,7 +376,7 @@ static inline int rcu_read_lock_bh_held(void) static inline int rcu_read_lock_sched_held(void) { - return !preemptible(); + return !running_inband() || !preemptible(); } static inline int rcu_read_lock_any_held(void) @@ -781,6 +789,7 @@ do { \ */ static __always_inline void rcu_read_lock(void) { + rcu_oob_prepare_lock(); __rcu_read_lock(); __acquire(RCU); rcu_lock_acquire(&rcu_lock_map); @@ -816,6 +825,7 @@ static inline void rcu_read_unlock(void) "rcu_read_unlock() used illegally while idle"); __release(RCU); __rcu_read_unlock(); + rcu_oob_finish_lock(); rcu_lock_release(&rcu_lock_map); /* Keep acq info for rls diags. */ } @@ -874,6 +884,7 @@ static inline void rcu_read_unlock_bh(void) static inline void rcu_read_lock_sched(void) { preempt_disable(); + rcu_oob_prepare_lock(); __acquire(RCU_SCHED); rcu_lock_acquire(&rcu_sched_lock_map); RCU_LOCKDEP_WARN(!rcu_is_watching(), @@ -898,6 +909,7 @@ static inline void rcu_read_unlock_sched(void) "rcu_read_unlock_sched() used illegally while idle"); rcu_lock_release(&rcu_sched_lock_map); __release(RCU_SCHED); + rcu_oob_finish_lock(); preempt_enable(); } diff --git a/include/linux/regmap.h b/include/linux/regmap.h index 113261287..6a411c192 100644 --- a/include/linux/regmap.h +++ b/include/linux/regmap.h @@ -420,6 +420,7 @@ struct regmap_config { bool fast_io; bool io_port; + bool oob_io; unsigned int max_register; const struct regmap_access_table *wr_table; diff --git a/include/linux/rmap.h b/include/linux/rmap.h index b1fb58b43..3b28f72bb 100644 --- a/include/linux/rmap.h +++ b/include/linux/rmap.h @@ -262,7 +262,7 @@ static inline int page_try_dup_anon_rmap(struct page *page, bool compound, * future on write faults. */ if (likely(!is_device_private_page(page)) && - unlikely(page_needs_cow_for_dma(vma, page))) + unlikely(page_needs_cow(vma, page))) return -EBUSY; ClearPageAnonExclusive(page); diff --git a/include/linux/sched.h b/include/linux/sched.h index d4f9d82c6..c84c9844b 100644 --- a/include/linux/sched.h +++ b/include/linux/sched.h @@ -133,6 +133,12 @@ struct user_event_mm; #define task_is_stopped(task) ((READ_ONCE(task->jobctl) & JOBCTL_STOPPED) != 0) #define task_is_stopped_or_traced(task) ((READ_ONCE(task->jobctl) & (JOBCTL_STOPPED | JOBCTL_TRACED)) != 0) +#ifdef CONFIG_DOVETAIL +#define task_is_off_stage(task) test_ti_local_flags(task_thread_info(task), _TLF_OFFSTAGE) +#else +#define task_is_off_stage(task) 0 +#endif + /* * Special states are those that do not use the normal wait-loop pattern. See * the comment with set_special_state(). @@ -1171,6 +1177,10 @@ struct task_struct { int softirq_disable_cnt; #endif +#ifdef CONFIG_IRQ_PIPELINE + unsigned long stall_bits; +#endif + #ifdef CONFIG_LOCKDEP # define MAX_LOCK_DEPTH 48UL u64 curr_chain_key; diff --git a/include/linux/sched/coredump.h b/include/linux/sched/coredump.h index 1b37fa8fc..b7ade822c 100644 --- a/include/linux/sched/coredump.h +++ b/include/linux/sched/coredump.h @@ -86,6 +86,7 @@ static inline int get_dumpable(struct mm_struct *mm) #define MMF_HAS_MDWE_MASK (1 << MMF_HAS_MDWE) #define MMF_DISABLE_THP_MASK (1 << MMF_DISABLE_THP) +#define MMF_DOVETAILED 31 /* mm belongs to a dovetailed process */ #define MMF_INIT_MASK (MMF_DUMPABLE_MASK | MMF_DUMP_FILTER_MASK |\ MMF_DISABLE_THP_MASK | MMF_HAS_MDWE_MASK) diff --git a/include/linux/skbuff.h b/include/linux/skbuff.h index 5f11f9873..38a3f9e7b 100644 --- a/include/linux/skbuff.h +++ b/include/linux/skbuff.h @@ -516,6 +516,9 @@ enum { * use frags only up until ubuf_info is released */ SKBFL_MANAGED_FRAG_REFS = BIT(4), + + /* data lives into an oob-enabled storage. */ + SKBFL_OOB_STORAGE = BIT(5), }; #define SKBFL_ZEROCOPY_FRAG (SKBFL_ZEROCOPY_ENABLE | SKBFL_SHARED_FRAG) @@ -914,6 +917,9 @@ struct sk_buff { head_frag:1, pfmemalloc:1, pp_recycle:1; /* page_pool recycle indicator */ +#ifdef CONFIG_NET_OOB + __u8 oob_head:1; +#endif #ifdef CONFIG_SKB_EXTENSIONS __u8 active_extensions; #endif @@ -1263,6 +1269,7 @@ struct sk_buff *__build_skb(void *data, unsigned int frag_size); struct sk_buff *build_skb(void *data, unsigned int frag_size); struct sk_buff *build_skb_around(struct sk_buff *skb, void *data, unsigned int frag_size); + void skb_attempt_defer_free(struct sk_buff *skb); struct sk_buff *napi_build_skb(void *data, unsigned int frag_size); @@ -5094,5 +5101,129 @@ static inline void skb_mark_for_recycle(struct sk_buff *skb) ssize_t skb_splice_from_iter(struct sk_buff *skb, struct iov_iter *iter, ssize_t maxsize, gfp_t gfp); +#ifdef CONFIG_NET_OOB + +#include + +extern unsigned int sysctl_max_oob_skb; + +struct skbuff_oob_pool { + struct list_head pool; + hard_spinlock_t lock; +}; + +struct sk_buff *get_oob_skb(void); + +void put_oob_skb(struct sk_buff *skb); + +/** + * skb_is_oob - Whether the buffer was allocated from the oob + * pool. Caution: this is distinct from the skb conveying oob storage, + * see skb_has_oob_storage(). + */ +static inline bool skb_is_oob(const struct sk_buff *skb) +{ + return skb->oob_head; +} + +static inline void skb_mark_oob(struct sk_buff *skb) +{ + skb->oob_head = 1; +} + +/** + * skb_has_oob_storage - Whether the skb data lives in an oob-enabled + * page pool. + */ +static inline bool skb_has_oob_storage(const struct sk_buff *skb) +{ + return skb_shinfo(skb)->flags & SKBFL_OOB_STORAGE; +} + +static inline void skb_mark_oob_storage(struct sk_buff *skb) +{ + skb_shinfo(skb)->flags |= SKBFL_OOB_STORAGE; +} + +static inline dma_addr_t skb_oob_storage_addr(const struct sk_buff *skb) +{ + if (!skb->head || !skb_has_oob_storage(skb) || !skb->pp_recycle) + return DMA_MAPPING_ERROR; + + return page_pool_get_dma_addr(virt_to_page(skb->head)); +} + +bool recycle_skb_oob(struct sk_buff *skb); +void free_skb_oob(struct sk_buff *skb); +void finalize_skb_inband(struct sk_buff *skb); + +/** + * __skb_inband_clone - In-band specific setup for skbs for a + * newly allocated clone head. Other allocation places don't need + * that because they are memset-zeroed from skb to &skb->end + * before building the buffer around a data storage area. + */ +static inline void __skb_inband_clone(struct sk_buff *skb) +{ + skb->oob_head = 0; +} + +/** + * __skb_oob_free_head - Called from the in-band net core after + * the last reference to the buffer (->users) was dropped, and + * any (shared) data was unref'ed (and possibly freed). By + * construction, this is only called for buffers which refer(red) + * to non-oob storage. Out-of-band allocated buffers which also + * convey out-of-band acessible storage must flow through + * free_skb_oob() instead. + */ +static inline bool __skb_oob_free_head(struct sk_buff *skb) +{ + if (skb_is_oob(skb)) { + put_oob_skb(skb); + return true; + } + + return false; +} + +#else /* !CONFIG_NET_OOB */ + +static inline bool skb_is_oob(const struct sk_buff *skb) +{ + return false; +} + +static inline void __skb_inband_clone(struct sk_buff *skb) +{ +} + +static inline bool __skb_oob_free_head(struct sk_buff *skb) +{ + return false; +} + +static inline bool skb_has_oob_storage(const struct sk_buff *skb) +{ + return false; +} + +static inline dma_addr_t skb_oob_storage_addr(const struct sk_buff *skb) +{ + return DMA_MAPPING_ERROR; +} + +static inline bool recycle_skb_oob(struct sk_buff *skb) +{ + return false; +} + +static inline struct sk_buff *get_oob_skb(void) +{ + return NULL; +} + +#endif /* !CONFIG_NET_OOB */ + #endif /* __KERNEL__ */ #endif /* _LINUX_SKBUFF_H */ diff --git a/include/linux/smp.h b/include/linux/smp.h index 2e3f605c3..2723db1e1 100644 --- a/include/linux/smp.h +++ b/include/linux/smp.h @@ -276,6 +276,58 @@ static inline int get_boot_cpu_id(void) #define get_cpu() ({ preempt_disable(); __smp_processor_id(); }) #define put_cpu() preempt_enable() +#ifdef CONFIG_IRQ_PIPELINE +#define hard_get_cpu(flags) ({ \ + (flags) = hard_preempt_disable(); \ + raw_smp_processor_id(); \ + }) +#define hard_put_cpu(flags) hard_preempt_enable(flags) +#define hard_get_cpu_bh(flags) ({ \ + (flags) = hard_bh_disable(); \ + raw_smp_processor_id(); \ + }) +#define hard_put_cpu_bh(flags) hard_bh_enable(flags) + +int up_oob_call(smp_call_func_t func, void *info); + +#ifdef CONFIG_SMP +int smp_call_function_oob(int cpu, smp_call_func_t func, void *info, bool wait); +void smp_flush_oob_call_function_queue(void); +#else +static inline int smp_call_function_oob(int cpu, smp_call_func_t func, + void *info, bool wait) +{ + return up_oob_call(func, info); +} +#endif /* !CONFIG_SMP */ +#else +#define hard_get_cpu(flags) ({ (void)(flags); get_cpu(); }) +#define hard_put_cpu(flags) \ + do { \ + put_cpu(); \ + (void)(flags); \ + } while (0) +#define hard_get_cpu_bh(flags) \ + ({ \ + int __cpu = get_cpu(); \ + local_bh_disable(); \ + (void)(flags); \ + __cpu; \ + }) +#define hard_put_cpu_bh(flags) \ + do { \ + local_bh_enable(); \ + put_cpu(); \ + (void)(flags); \ + } while (0) + +static inline int smp_call_function_oob(int cpu, smp_call_func_t func, + void *info, bool wait) +{ + return -ENOTSUPP; +} +#endif + /* * Callback to arch code if there's nosmp or maxcpus=0 on the * boot command line: diff --git a/include/linux/socket.h b/include/linux/socket.h index cfcb7e2c3..6f05e42e5 100644 --- a/include/linux/socket.h +++ b/include/linux/socket.h @@ -239,8 +239,9 @@ struct ucred { #define AF_MCTP 45 /* Management component * transport protocol */ +#define AF_OOB 46 /* Out-of-band domain sockets */ -#define AF_MAX 46 /* For now.. */ +#define AF_MAX 47 /* For now.. */ /* Protocol families, same as address families. */ #define PF_UNSPEC AF_UNSPEC @@ -291,6 +292,7 @@ struct ucred { #define PF_SMC AF_SMC #define PF_XDP AF_XDP #define PF_MCTP AF_MCTP +#define PF_OOB AF_OOB #define PF_MAX AF_MAX /* Maximum queue length specifiable by listen. */ diff --git a/include/linux/spi/spi.h b/include/linux/spi/spi.h index e5baf43bc..c84c312cb 100644 --- a/include/linux/spi/spi.h +++ b/include/linux/spi/spi.h @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -25,6 +26,7 @@ struct software_node; struct ptp_system_timestamp; struct spi_controller; struct spi_transfer; +struct spi_oob_transfer; struct spi_controller_mem_ops; struct spi_controller_mem_caps; struct spi_message; @@ -398,6 +400,7 @@ extern struct spi_device *spi_new_ancillary_device(struct spi_device *spi, u8 ch * @add_lock: mutex to avoid adding devices to the same chipselect * @bus_lock_spinlock: spinlock for SPI bus locking * @bus_lock_mutex: mutex for exclusion of multiple callers + * @bus_oob_lock_sem: semaphore for exclusion during oob operations * @bus_lock_flag: indicates that the SPI bus is locked for exclusive use * @setup: updates the device mode and clocking records used by a * device's SPI controller; protocol code may call this. This @@ -595,6 +598,10 @@ struct spi_controller { spinlock_t bus_lock_spinlock; struct mutex bus_lock_mutex; +#ifdef CONFIG_SPI_OOB + struct semaphore bus_oob_lock_sem; +#endif + /* Flag indicating that the SPI bus is locked for exclusive use */ bool bus_lock_flag; @@ -695,6 +702,14 @@ struct spi_controller { int (*slave_abort)(struct spi_controller *ctlr); int (*target_abort)(struct spi_controller *ctlr); }; + int (*prepare_oob_transfer)(struct spi_controller *ctlr, + struct spi_oob_transfer *xfer); + void (*start_oob_transfer)(struct spi_controller *ctlr, + struct spi_oob_transfer *xfer); + void (*pulse_oob_transfer)(struct spi_controller *ctlr, + struct spi_oob_transfer *xfer); + void (*terminate_oob_transfer)(struct spi_controller *ctlr, + struct spi_oob_transfer *xfer); /* * These hooks are for drivers that use a generic implementation @@ -1223,6 +1238,90 @@ static inline void spi_message_free(struct spi_message *m) kfree(m); } +struct spi_oob_transfer { + struct spi_device *spi; + dma_addr_t dma_addr; + size_t aligned_frame_len; + void *io_buffer; /* 2 x aligned_frame_len */ + struct dma_async_tx_descriptor *txd; + struct dma_async_tx_descriptor *rxd; + u32 effective_speed_hz; + /* + * Caller-defined settings for the transfer. + */ + struct spi_oob_setup { + u32 frame_len; + u32 speed_hz; + u8 bits_per_word; + dma_async_tx_callback xfer_done; + } setup; +}; + +static inline off_t spi_get_oob_rxoff(struct spi_oob_transfer *xfer) +{ + /* RX area is in first half of the I/O buffer. */ + return 0; +} + +static inline off_t spi_get_oob_txoff(struct spi_oob_transfer *xfer) +{ + /* TX area is in second half of the I/O buffer. */ + return xfer->aligned_frame_len; +} + +static inline size_t spi_get_oob_iolen(struct spi_oob_transfer *xfer) +{ + return xfer->aligned_frame_len * 2; +} + +#ifdef CONFIG_SPI_OOB + +struct vm_area_struct; + +int spi_prepare_oob_transfer(struct spi_device *spi, + struct spi_oob_transfer *xfer); + +void spi_start_oob_transfer(struct spi_oob_transfer *xfer); + +int spi_pulse_oob_transfer(struct spi_oob_transfer *xfer); + +void spi_terminate_oob_transfer(struct spi_oob_transfer *xfer); + +int spi_mmap_oob_transfer(struct vm_area_struct *vma, + struct spi_oob_transfer *xfer); + +#else + +static inline +int spi_prepare_oob_transfer(struct spi_device *spi, + struct spi_oob_transfer *xfer) +{ + return -ENOTSUPP; +} + +static inline +void spi_start_oob_transfer(struct spi_oob_transfer *xfer) +{ } + +static inline +int spi_pulse_oob_transfer(struct spi_oob_transfer *xfer) +{ + return -EIO; +} + +static inline +void spi_terminate_oob_transfer(struct spi_oob_transfer *xfer) +{ } + +static inline +int spi_mmap_oob_transfer(struct vm_area_struct *vma, + struct spi_oob_transfer *xfer) +{ + return -ENXIO; +} + +#endif + extern int spi_setup(struct spi_device *spi); extern int spi_async(struct spi_device *spi, struct spi_message *message); extern int spi_slave_abort(struct spi_device *spi); diff --git a/include/linux/spinlock.h b/include/linux/spinlock.h index ceb56b39c..1e5c4d3ae 100644 --- a/include/linux/spinlock.h +++ b/include/linux/spinlock.h @@ -102,21 +102,27 @@ struct lock_class_key *key, short inner); # define raw_spin_lock_init(lock) \ + LOCK_ALTERNATIVES(lock, spin_lock_init, \ do { \ static struct lock_class_key __key; \ \ - __raw_spin_lock_init((lock), #lock, &__key, LD_WAIT_SPIN); \ -} while (0) + __raw_spin_lock_init(__RAWLOCK(lock), #lock, &__key, LD_WAIT_SPIN); \ +} while (0)) #else # define raw_spin_lock_init(lock) \ - do { *(lock) = __RAW_SPIN_LOCK_UNLOCKED(lock); } while (0) + LOCK_ALTERNATIVES(lock, spin_lock_init, \ + do { *(__RAWLOCK(lock)) = __RAW_SPIN_LOCK_UNLOCKED(__RAWLOCK(lock)); } while (0)) #endif -#define raw_spin_is_locked(lock) arch_spin_is_locked(&(lock)->raw_lock) +#define raw_spin_is_locked(lock) \ + LOCK_ALTERNATIVES_RET(lock, spin_is_locked, \ + arch_spin_is_locked(&(__RAWLOCK(lock))->raw_lock)) #ifdef arch_spin_is_contended -#define raw_spin_is_contended(lock) arch_spin_is_contended(&(lock)->raw_lock) +#define raw_spin_is_contended(lock) \ + LOCK_ALTERNATIVES_RET(lock, spin_is_contended, \ + arch_spin_is_contended(&(__RAWLOCK(lock))->raw_lock)) #else #define raw_spin_is_contended(lock) (((void)(lock), 0)) #endif /*arch_spin_is_contended*/ @@ -212,13 +218,19 @@ static inline void do_raw_spin_unlock(raw_spinlock_t *lock) __releases(lock) * various methods are defined as nops in the case they are not * required. */ -#define raw_spin_trylock(lock) __cond_lock(lock, _raw_spin_trylock(lock)) +#define raw_spin_trylock(lock) \ + __cond_lock(lock, \ + LOCK_ALTERNATIVES_RET(lock, \ + spin_trylock, _raw_spin_trylock(__RAWLOCK(lock)))) -#define raw_spin_lock(lock) _raw_spin_lock(lock) +#define raw_spin_lock(lock) \ + LOCK_ALTERNATIVES(lock, spin_lock, _raw_spin_lock(__RAWLOCK(lock))) #ifdef CONFIG_DEBUG_LOCK_ALLOC + # define raw_spin_lock_nested(lock, subclass) \ - _raw_spin_lock_nested(lock, subclass) + LOCK_ALTERNATIVES(lock, spin_lock_nested, \ + _raw_spin_lock_nested(__RAWLOCK(lock), subclass), subclass) # define raw_spin_lock_nest_lock(lock, nest_lock) \ do { \ @@ -231,18 +243,20 @@ static inline void do_raw_spin_unlock(raw_spinlock_t *lock) __releases(lock) * warns about set-but-not-used variables when building with * CONFIG_DEBUG_LOCK_ALLOC=n and with W=1. */ -# define raw_spin_lock_nested(lock, subclass) \ - _raw_spin_lock(((void)(subclass), (lock))) +# define raw_spin_lock_nested(lock, subclass) \ + LOCK_ALTERNATIVES(lock, spin_lock_nested, \ + _raw_spin_lock(((void)(subclass), __RAWLOCK(lock))), subclass) # define raw_spin_lock_nest_lock(lock, nest_lock) _raw_spin_lock(lock) #endif #if defined(CONFIG_SMP) || defined(CONFIG_DEBUG_SPINLOCK) -#define raw_spin_lock_irqsave(lock, flags) \ - do { \ - typecheck(unsigned long, flags); \ - flags = _raw_spin_lock_irqsave(lock); \ - } while (0) +#define raw_spin_lock_irqsave(lock, flags) \ + LOCK_ALTERNATIVES(lock, spin_lock_irqsave, \ + do { \ + typecheck(unsigned long, flags); \ + flags = _raw_spin_lock_irqsave(__RAWLOCK(lock)); \ + } while (0), flags) #ifdef CONFIG_DEBUG_LOCK_ALLOC #define raw_spin_lock_irqsave_nested(lock, flags, subclass) \ @@ -260,45 +274,55 @@ static inline void do_raw_spin_unlock(raw_spinlock_t *lock) __releases(lock) #else -#define raw_spin_lock_irqsave(lock, flags) \ - do { \ - typecheck(unsigned long, flags); \ - _raw_spin_lock_irqsave(lock, flags); \ - } while (0) +#define raw_spin_lock_irqsave(lock, flags) \ + LOCK_ALTERNATIVES(lock, spin_lock_irqsave, \ + do { \ + typecheck(unsigned long, flags); \ + _raw_spin_lock_irqsave(__RAWLOCK(lock), flags); \ + } while (0), flags) #define raw_spin_lock_irqsave_nested(lock, flags, subclass) \ raw_spin_lock_irqsave(lock, flags) #endif -#define raw_spin_lock_irq(lock) _raw_spin_lock_irq(lock) +#define raw_spin_lock_irq(lock) \ + LOCK_ALTERNATIVES(lock, spin_lock_irq, \ + _raw_spin_lock_irq(__RAWLOCK(lock))) #define raw_spin_lock_bh(lock) _raw_spin_lock_bh(lock) -#define raw_spin_unlock(lock) _raw_spin_unlock(lock) -#define raw_spin_unlock_irq(lock) _raw_spin_unlock_irq(lock) - -#define raw_spin_unlock_irqrestore(lock, flags) \ - do { \ - typecheck(unsigned long, flags); \ - _raw_spin_unlock_irqrestore(lock, flags); \ - } while (0) +#define raw_spin_unlock(lock) \ + LOCK_ALTERNATIVES(lock, spin_unlock, \ + _raw_spin_unlock(__RAWLOCK(lock))) +#define raw_spin_unlock_irq(lock) \ + LOCK_ALTERNATIVES(lock, spin_unlock_irq, \ + _raw_spin_unlock_irq(__RAWLOCK(lock))) + +#define raw_spin_unlock_irqrestore(lock, flags) \ + LOCK_ALTERNATIVES(lock, spin_unlock_irqrestore, \ + do { \ + typecheck(unsigned long, flags); \ + _raw_spin_unlock_irqrestore(__RAWLOCK(lock), flags); \ + } while (0), flags) #define raw_spin_unlock_bh(lock) _raw_spin_unlock_bh(lock) #define raw_spin_trylock_bh(lock) \ __cond_lock(lock, _raw_spin_trylock_bh(lock)) #define raw_spin_trylock_irq(lock) \ + LOCK_ALTERNATIVES_RET(lock, spin_trylock_irq, \ ({ \ local_irq_disable(); \ - raw_spin_trylock(lock) ? \ + raw_spin_trylock(__RAWLOCK(lock)) ? \ 1 : ({ local_irq_enable(); 0; }); \ -}) +})) #define raw_spin_trylock_irqsave(lock, flags) \ + LOCK_ALTERNATIVES_RET(lock, spin_trylock_irqsave, \ ({ \ local_irq_save(flags); \ - raw_spin_trylock(lock) ? \ + raw_spin_trylock(__RAWLOCK(lock)) ? \ 1 : ({ local_irq_restore(flags); 0; }); \ -}) +}), flags) #ifndef CONFIG_PREEMPT_RT /* Include rwlock functions for !RT */ @@ -314,15 +338,25 @@ static inline void do_raw_spin_unlock(raw_spinlock_t *lock) __releases(lock) # include #endif +/* Pull the lock types specific to the IRQ pipeline. */ +#ifdef CONFIG_IRQ_PIPELINE +#include +#endif + /* Non PREEMPT_RT kernel, map to raw spinlocks: */ #ifndef CONFIG_PREEMPT_RT +#ifndef CONFIG_IRQ_PIPELINE +static inline void check_spinlock_context(void) { } +#endif + /* * Map the spin_lock functions to the raw variants for PREEMPT_RT=n */ static __always_inline raw_spinlock_t *spinlock_check(spinlock_t *lock) { + check_spinlock_context(); return &lock->rlock; } diff --git a/include/linux/spinlock_api_up.h b/include/linux/spinlock_api_up.h index 819aeba1c..938b8568b 100644 --- a/include/linux/spinlock_api_up.h +++ b/include/linux/spinlock_api_up.h @@ -30,21 +30,33 @@ #define __LOCK(lock) \ do { preempt_disable(); ___LOCK(lock); } while (0) +#define __HARD_LOCK(lock) \ + do { ___LOCK(lock); } while (0) + #define __LOCK_BH(lock) \ do { __local_bh_disable_ip(_THIS_IP_, SOFTIRQ_LOCK_OFFSET); ___LOCK(lock); } while (0) #define __LOCK_IRQ(lock) \ do { local_irq_disable(); __LOCK(lock); } while (0) +#define __HARD_LOCK_IRQ(lock) \ + do { hard_local_irq_disable(); __HARD_LOCK(lock); } while (0) + #define __LOCK_IRQSAVE(lock, flags) \ do { local_irq_save(flags); __LOCK(lock); } while (0) +#define __HARD_LOCK_IRQSAVE(lock, flags) \ + do { flags = hard_local_irq_save(); __HARD_LOCK(lock); } while (0) + #define ___UNLOCK(lock) \ do { __release(lock); (void)(lock); } while (0) #define __UNLOCK(lock) \ do { preempt_enable(); ___UNLOCK(lock); } while (0) +#define __HARD_UNLOCK(lock) \ + do { ___UNLOCK(lock); } while (0) + #define __UNLOCK_BH(lock) \ do { __local_bh_enable_ip(_THIS_IP_, SOFTIRQ_LOCK_OFFSET); \ ___UNLOCK(lock); } while (0) @@ -52,9 +64,15 @@ #define __UNLOCK_IRQ(lock) \ do { local_irq_enable(); __UNLOCK(lock); } while (0) +#define __HARD_UNLOCK_IRQ(lock) \ + do { hard_local_irq_enable(); __HARD_UNLOCK(lock); } while (0) + #define __UNLOCK_IRQRESTORE(lock, flags) \ do { local_irq_restore(flags); __UNLOCK(lock); } while (0) +#define __HARD_UNLOCK_IRQRESTORE(lock, flags) \ + do { hard_local_irq_restore(flags); __HARD_UNLOCK(lock); } while (0) + #define _raw_spin_lock(lock) __LOCK(lock) #define _raw_spin_lock_nested(lock, subclass) __LOCK(lock) #define _raw_read_lock(lock) __LOCK(lock) diff --git a/include/linux/spinlock_pipeline.h b/include/linux/spinlock_pipeline.h new file mode 100644 index 000000000..1652735f1 --- /dev/null +++ b/include/linux/spinlock_pipeline.h @@ -0,0 +1,387 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2016 Philippe Gerum . + */ +#ifndef __LINUX_SPINLOCK_PIPELINE_H +#define __LINUX_SPINLOCK_PIPELINE_H + +#ifndef __LINUX_SPINLOCK_H +# error "Please don't include this file directly. Use spinlock.h." +#endif + +#include + +#define hard_spin_lock_irqsave(__rlock, __flags) \ + do { \ + (__flags) = __hard_spin_lock_irqsave(__rlock); \ + } while (0) + +#define hard_spin_trylock_irqsave(__rlock, __flags) \ + ({ \ + int __locked; \ + (__flags) = __hard_spin_trylock_irqsave(__rlock, &__locked); \ + __locked; \ + }) + +#define hybrid_spin_lock_init(__rlock) hard_spin_lock_init(__rlock) + +/* + * CAUTION: We don't want the hand-coded irq-enable of + * do_raw_spin_lock_flags(), hard locked sections assume that + * interrupts are not re-enabled during lock-acquire. + */ +#define hard_lock_acquire(__rlock, __try, __ip) \ + do { \ + hard_spin_lock_prepare(__rlock); \ + if (irq_pipeline_debug_locking()) { \ + spin_acquire(&(__rlock)->dep_map, 0, __try, __ip); \ + LOCK_CONTENDED(__rlock, do_raw_spin_trylock, do_raw_spin_lock); \ + } else { \ + do_raw_spin_lock(__rlock); \ + } \ + } while (0) + +#define hard_lock_acquire_nested(__rlock, __subclass, __ip) \ + do { \ + hard_spin_lock_prepare(__rlock); \ + if (irq_pipeline_debug_locking()) { \ + spin_acquire(&(__rlock)->dep_map, __subclass, 0, __ip); \ + LOCK_CONTENDED(__rlock, do_raw_spin_trylock, do_raw_spin_lock); \ + } else { \ + do_raw_spin_lock(__rlock); \ + } \ + } while (0) + +#define hard_trylock_acquire(__rlock, __try, __ip) \ + do { \ + if (irq_pipeline_debug_locking()) \ + spin_acquire(&(__rlock)->dep_map, 0, __try, __ip); \ + } while (0) + +#define hard_lock_release(__rlock, __ip) \ + do { \ + if (irq_pipeline_debug_locking()) \ + spin_release(&(__rlock)->dep_map, __ip); \ + do_raw_spin_unlock(__rlock); \ + hard_spin_unlock_finish(__rlock); \ + } while (0) + +#if defined(CONFIG_SMP) || defined(CONFIG_DEBUG_SPINLOCK) + +#ifdef CONFIG_DEBUG_SPINLOCK +/* + * Hard spinlocks are not checked for invalid wait context in-band + * wise (LD_WAIT_INV). We could be smarter with handling a specific + * wait type for them, so that we could detect hard_spin_lock -> + * {raw_}spin_lock for instance, but we already have + * check_inband_stage() calls all over the place in the latter API, so + * that kind of misusage would be detected regardless. + */ +#define hard_spin_lock_init(__lock) \ + do { \ + static struct lock_class_key __key; \ + __raw_spin_lock_init((raw_spinlock_t *)__lock, #__lock, &__key, LD_WAIT_INV); \ + } while (0) +#else +#define hard_spin_lock_init(__rlock) \ + do { *(__rlock) = __RAW_SPIN_LOCK_UNLOCKED(__rlock); } while (0) +#endif + +/* + * XXX: no preempt_enable/disable when hard locking. + */ + +static inline +void hard_spin_lock(struct raw_spinlock *rlock) +{ + hard_lock_acquire(rlock, 0, _THIS_IP_); +} + +#ifdef CONFIG_DEBUG_LOCK_ALLOC +static inline +void hard_spin_lock_nested(struct raw_spinlock *rlock, int subclass) +{ + hard_lock_acquire_nested(rlock, subclass, _THIS_IP_); +} +#else +static inline +void hard_spin_lock_nested(struct raw_spinlock *rlock, int subclass) +{ + hard_spin_lock(rlock); +} +#endif + +static inline +void hard_spin_unlock(struct raw_spinlock *rlock) +{ + hard_lock_release(rlock, _THIS_IP_); +} + +static inline +void hard_spin_lock_irq(struct raw_spinlock *rlock) +{ + hard_local_irq_disable(); + hard_lock_acquire(rlock, 0, _THIS_IP_); +} + +static inline +void hard_spin_unlock_irq(struct raw_spinlock *rlock) +{ + hard_lock_release(rlock, _THIS_IP_); + hard_local_irq_enable(); +} + +static inline +void hard_spin_unlock_irqrestore(struct raw_spinlock *rlock, + unsigned long flags) +{ + hard_lock_release(rlock, _THIS_IP_); + hard_local_irq_restore(flags); +} + +static inline +unsigned long __hard_spin_lock_irqsave(struct raw_spinlock *rlock) +{ + unsigned long flags = hard_local_irq_save(); + + hard_lock_acquire(rlock, 0, _THIS_IP_); + + return flags; +} + +static inline +int hard_spin_trylock(struct raw_spinlock *rlock) +{ + hard_spin_trylock_prepare(rlock); + + if (do_raw_spin_trylock(rlock)) { + hard_trylock_acquire(rlock, 1, _THIS_IP_); + return 1; + } + + hard_spin_trylock_fail(rlock); + + return 0; +} + +static inline +unsigned long __hard_spin_trylock_irqsave(struct raw_spinlock *rlock, + int *locked) +{ + unsigned long flags = hard_local_irq_save(); + *locked = hard_spin_trylock(rlock); + return *locked ? flags : ({ hard_local_irq_restore(flags); flags; }); +} + +static inline +int hard_spin_trylock_irq(struct raw_spinlock *rlock) +{ + hard_local_irq_disable(); + return hard_spin_trylock(rlock) ? : ({ hard_local_irq_enable(); 0; }); +} + +static inline +int hard_spin_is_locked(struct raw_spinlock *rlock) +{ + return arch_spin_is_locked(&rlock->raw_lock); +} + +static inline +int hard_spin_is_contended(struct raw_spinlock *rlock) +{ +#ifdef CONFIG_GENERIC_LOCKBREAK + return rlock->break_lock; +#elif defined(arch_spin_is_contended) + return arch_spin_is_contended(&rlock->raw_lock); +#else + return 0; +#endif +} + +#else /* !SMP && !DEBUG_SPINLOCK */ + +#define hard_spin_lock_init(__rlock) do { (void)(__rlock); } while (0) +#define hard_spin_lock(__rlock) __HARD_LOCK(__rlock) +#define hard_spin_lock_nested(__rlock, __subclass) \ + do { __HARD_LOCK(__rlock); (void)(__subclass); } while (0) +#define hard_spin_unlock(__rlock) __HARD_UNLOCK(__rlock) +#define hard_spin_lock_irq(__rlock) __HARD_LOCK_IRQ(__rlock) +#define hard_spin_unlock_irq(__rlock) __HARD_UNLOCK_IRQ(__rlock) +#define hard_spin_unlock_irqrestore(__rlock, __flags) \ + __HARD_UNLOCK_IRQRESTORE(__rlock, __flags) +#define __hard_spin_lock_irqsave(__rlock) \ + ({ \ + unsigned long __flags; \ + __HARD_LOCK_IRQSAVE(__rlock, __flags); \ + __flags; \ + }) +#define __hard_spin_trylock_irqsave(__rlock, __locked) \ + ({ \ + unsigned long __flags; \ + __HARD_LOCK_IRQSAVE(__rlock, __flags); \ + *(__locked) = 1; \ + __flags; \ + }) +#define hard_spin_trylock(__rlock) ({ __HARD_LOCK(__rlock); 1; }) +#define hard_spin_trylock_irq(__rlock) ({ __HARD_LOCK_IRQ(__rlock); 1; }) +#define hard_spin_is_locked(__rlock) ((void)(__rlock), 0) +#define hard_spin_is_contended(__rlock) ((void)(__rlock), 0) +#endif /* !SMP && !DEBUG_SPINLOCK */ + +/* + * In the pipeline entry context, the regular preemption and root + * stall logic do not apply since we may actually have preempted any + * critical section of the kernel which is protected by regular + * locking (spin or stall), or we may even have preempted the + * out-of-band stage. Therefore, we just need to grab the raw spinlock + * underlying a hybrid spinlock to exclude other CPUs. + * + * NOTE: When entering the pipeline, IRQs are already hard disabled. + */ + +void __hybrid_spin_lock(struct raw_spinlock *rlock); +void __hybrid_spin_lock_nested(struct raw_spinlock *rlock, int subclass); + +static inline void hybrid_spin_lock(struct raw_spinlock *rlock) +{ + if (in_pipeline()) + hard_lock_acquire(rlock, 0, _THIS_IP_); + else + __hybrid_spin_lock(rlock); +} + +#ifdef CONFIG_DEBUG_LOCK_ALLOC +static inline +void hybrid_spin_lock_nested(struct raw_spinlock *rlock, int subclass) +{ + if (in_pipeline()) + hard_lock_acquire_nested(rlock, subclass, _THIS_IP_); + else + __hybrid_spin_lock_nested(rlock, subclass); +} +#else +static inline +void hybrid_spin_lock_nested(struct raw_spinlock *rlock, int subclass) +{ + hybrid_spin_lock(rlock); +} +#endif + +void __hybrid_spin_unlock(struct raw_spinlock *rlock); + +static inline void hybrid_spin_unlock(struct raw_spinlock *rlock) +{ + if (in_pipeline()) + hard_lock_release(rlock, _THIS_IP_); + else + __hybrid_spin_unlock(rlock); +} + +void __hybrid_spin_lock_irq(struct raw_spinlock *rlock); + +static inline void hybrid_spin_lock_irq(struct raw_spinlock *rlock) +{ + if (in_pipeline()) + hard_lock_acquire(rlock, 0, _THIS_IP_); + else + __hybrid_spin_lock_irq(rlock); +} + +void __hybrid_spin_unlock_irq(struct raw_spinlock *rlock); + +static inline void hybrid_spin_unlock_irq(struct raw_spinlock *rlock) +{ + if (in_pipeline()) + hard_lock_release(rlock, _THIS_IP_); + else + __hybrid_spin_unlock_irq(rlock); +} + +unsigned long __hybrid_spin_lock_irqsave(struct raw_spinlock *rlock); + +#define hybrid_spin_lock_irqsave(__rlock, __flags) \ + do { \ + if (in_pipeline()) { \ + hard_lock_acquire(__rlock, 0, _THIS_IP_); \ + (__flags) = hard_local_save_flags(); \ + } else \ + (__flags) = __hybrid_spin_lock_irqsave(__rlock); \ + } while (0) + +void __hybrid_spin_unlock_irqrestore(struct raw_spinlock *rlock, + unsigned long flags); + +static inline void hybrid_spin_unlock_irqrestore(struct raw_spinlock *rlock, + unsigned long flags) +{ + + if (in_pipeline()) + hard_lock_release(rlock, _THIS_IP_); + else + __hybrid_spin_unlock_irqrestore(rlock, flags); +} + +int __hybrid_spin_trylock(struct raw_spinlock *rlock); + +static inline int hybrid_spin_trylock(struct raw_spinlock *rlock) +{ + if (in_pipeline()) { + hard_spin_trylock_prepare(rlock); + if (do_raw_spin_trylock(rlock)) { + hard_trylock_acquire(rlock, 1, _THIS_IP_); + return 1; + } + hard_spin_trylock_fail(rlock); + return 0; + } + + return __hybrid_spin_trylock(rlock); +} + +int __hybrid_spin_trylock_irqsave(struct raw_spinlock *rlock, + unsigned long *flags); + +#define hybrid_spin_trylock_irqsave(__rlock, __flags) \ + ({ \ + int __ret = 1; \ + if (in_pipeline()) { \ + hard_spin_trylock_prepare(__rlock); \ + if (do_raw_spin_trylock(__rlock)) { \ + hard_trylock_acquire(__rlock, 1, _THIS_IP_); \ + (__flags) = hard_local_save_flags(); \ + } else { \ + hard_spin_trylock_fail(__rlock); \ + __ret = 0; \ + } \ + } else { \ + __ret = __hybrid_spin_trylock_irqsave(__rlock, &(__flags)); \ + } \ + __ret; \ + }) + +static inline int hybrid_spin_trylock_irq(struct raw_spinlock *rlock) +{ + unsigned long flags; + return hybrid_spin_trylock_irqsave(rlock, flags); +} + +static inline +int hybrid_spin_is_locked(struct raw_spinlock *rlock) +{ + return hard_spin_is_locked(rlock); +} + +static inline +int hybrid_spin_is_contended(struct raw_spinlock *rlock) +{ + return hard_spin_is_contended(rlock); +} + +#ifdef CONFIG_DEBUG_IRQ_PIPELINE +void check_spinlock_context(void); +#else +static inline void check_spinlock_context(void) { } +#endif + +#endif /* __LINUX_SPINLOCK_PIPELINE_H */ diff --git a/include/linux/spinlock_types.h b/include/linux/spinlock_types.h index 2dfa35ffe..8c77fd344 100644 --- a/include/linux/spinlock_types.h +++ b/include/linux/spinlock_types.h @@ -71,6 +71,154 @@ typedef struct spinlock { #endif /* CONFIG_PREEMPT_RT */ +#ifdef CONFIG_IRQ_PIPELINE + +void __bad_spinlock_type(void); + +#define __RAWLOCK(x) ((struct raw_spinlock *)(x)) + +#define LOCK_ALTERNATIVES(__lock, __base_op, __raw_form, __args...) \ + do { \ + if (__builtin_types_compatible_p(typeof(__lock), \ + raw_spinlock_t *)) \ + __raw_form; \ + else if (__builtin_types_compatible_p(typeof(__lock), \ + hard_spinlock_t *)) \ + hard_ ## __base_op(__RAWLOCK(__lock), ##__args); \ + else if (__builtin_types_compatible_p(typeof(__lock), \ + hybrid_spinlock_t *)) \ + hybrid_ ## __base_op(__RAWLOCK(__lock), ##__args); \ + else \ + __bad_spinlock_type(); \ + } while (0) + +#define LOCK_ALTERNATIVES_RET(__lock, __base_op, __raw_form, __args...) \ + ({ \ + long __ret = 0; \ + if (__builtin_types_compatible_p(typeof(__lock), \ + raw_spinlock_t *)) \ + __ret = __raw_form; \ + else if (__builtin_types_compatible_p(typeof(__lock), \ + hard_spinlock_t *)) \ + __ret = hard_ ## __base_op(__RAWLOCK(__lock), ##__args); \ + else if (__builtin_types_compatible_p(typeof(__lock), \ + hybrid_spinlock_t *)) \ + __ret = hybrid_ ## __base_op(__RAWLOCK(__lock), ##__args); \ + else \ + __bad_spinlock_type(); \ + __ret; \ + }) + +#define LOCKDEP_ALT_DEPMAP(__lock) \ + ({ \ + struct lockdep_map *__ret; \ + if (__builtin_types_compatible_p(typeof(&(__lock)->dep_map), \ + struct phony_lockdep_map *)) \ + __ret = &__RAWLOCK(__lock)->dep_map; \ + else \ + __ret = (struct lockdep_map *)(&(__lock)->dep_map); \ + __ret; \ + }) + +#define LOCKDEP_HARD_DEBUG(__lock, __nodebug, __debug) \ + do { \ + if (__builtin_types_compatible_p(typeof(__lock), \ + raw_spinlock_t *) || \ + irq_pipeline_debug_locking()) { \ + __debug; \ + } else { \ + __nodebug; \ + } \ + } while (0) + +#define LOCKDEP_HARD_DEBUG_RET(__lock, __nodebug, __debug) \ + ({ \ + typeof(__nodebug) __ret; \ + if (__builtin_types_compatible_p(typeof(__lock), \ + raw_spinlock_t *) || \ + irq_pipeline_debug_locking()) { \ + __ret = (__debug); \ + } else { \ + __ret = (__nodebug); \ + } \ + __ret; \ + }) + +#define __HARD_SPIN_LOCK_INITIALIZER(x) { \ + .rlock = { \ + .raw_lock = __ARCH_SPIN_LOCK_UNLOCKED, \ + SPIN_DEBUG_INIT(x) \ + HARD_SPIN_DEP_MAP_INIT(x) \ + } \ + } + +#define __HARD_SPIN_LOCK_UNLOCKED(x) \ + (hard_spinlock_t) __HARD_SPIN_LOCK_INITIALIZER(x) + +#define DEFINE_HARD_SPINLOCK(x) hard_spinlock_t x = __HARD_SPIN_LOCK_UNLOCKED(x) + +#define DECLARE_HARD_SPINLOCK(x) hard_spinlock_t x + +/* + * The presence of a phony depmap is tested by LOCKDEP_ALT_DEPMAP() to + * locate the real depmap without enumerating every spinlock type + * which may contain one. + */ +struct phony_lockdep_map { }; + +typedef struct hard_spinlock { + /* XXX: offset_of(struct hard_spinlock, rlock) == 0 */ + struct raw_spinlock rlock; + struct phony_lockdep_map dep_map; +} hard_spinlock_t; + +#define DEFINE_MUTABLE_SPINLOCK(x) hybrid_spinlock_t x = { \ + .rlock = __RAW_SPIN_LOCK_UNLOCKED(x), \ + } + +#define DECLARE_MUTABLE_SPINLOCK(x) hybrid_spinlock_t x + +typedef struct hybrid_spinlock { + /* XXX: offset_of(struct hybrid_spinlock, rlock) == 0 */ + struct raw_spinlock rlock; + unsigned long hwflags; + struct phony_lockdep_map dep_map; +} hybrid_spinlock_t; + +#else + +typedef raw_spinlock_t hard_spinlock_t; + +typedef raw_spinlock_t hybrid_spinlock_t; + +#define LOCK_ALTERNATIVES(__lock, __base_op, __raw_form, __args...) \ + __raw_form + +#define LOCK_ALTERNATIVES_RET(__lock, __base_op, __raw_form, __args...) \ + __raw_form + +#define LOCKDEP_ALT_DEPMAP(__lock) (&(__lock)->dep_map) + +#define LOCKDEP_HARD_DEBUG(__lock, __nondebug, __debug) do { __debug; } while (0) + +#define LOCKDEP_HARD_DEBUG_RET(__lock, __nondebug, __debug) ({ __debug; }) + +#define DEFINE_HARD_SPINLOCK(x) DEFINE_RAW_SPINLOCK(x) + +#define DECLARE_HARD_SPINLOCK(x) raw_spinlock_t x + +#define DEFINE_MUTABLE_SPINLOCK(x) DEFINE_RAW_SPINLOCK(x) + +#define DECLARE_MUTABLE_SPINLOCK(x) raw_spinlock_t x + +#define __RAWLOCK(x) (x) + +#define __HARD_SPIN_LOCK_UNLOCKED(__lock) __RAW_SPIN_LOCK_UNLOCKED(__lock) + +#define __HARD_SPIN_LOCK_INITIALIZER(__lock) __RAW_SPIN_LOCK_UNLOCKED(__lock) + +#endif /* CONFIG_IRQ_PIPELINE */ + #include #endif /* __LINUX_SPINLOCK_TYPES_H */ diff --git a/include/linux/spinlock_types_raw.h b/include/linux/spinlock_types_raw.h index 91cb36b65..ada89a26b 100644 --- a/include/linux/spinlock_types_raw.h +++ b/include/linux/spinlock_types_raw.h @@ -44,10 +44,16 @@ typedef struct raw_spinlock { .wait_type_inner = LD_WAIT_CONFIG, \ .lock_type = LD_LOCK_PERCPU, \ } +# define HARD_SPIN_DEP_MAP_INIT(lockname) \ + .dep_map = { \ + .name = #lockname, \ + .wait_type_inner = LD_WAIT_INV, \ + } #else # define RAW_SPIN_DEP_MAP_INIT(lockname) # define SPIN_DEP_MAP_INIT(lockname) # define LOCAL_SPIN_DEP_MAP_INIT(lockname) +# define HARD_SPIN_DEP_MAP_INIT(lockname) #endif #ifdef CONFIG_DEBUG_SPINLOCK diff --git a/include/linux/stop_machine.h b/include/linux/stop_machine.h index ea7a74ea7..37d5495cb 100644 --- a/include/linux/stop_machine.h +++ b/include/linux/stop_machine.h @@ -6,6 +6,7 @@ #include #include #include +#include /* * stop_cpu[s]() is simplistic per-cpu maximum priority cpu @@ -150,7 +151,9 @@ static __always_inline int stop_machine_cpuslocked(cpu_stop_fn_t fn, void *data, unsigned long flags; int ret; local_irq_save(flags); + hard_irq_disable(); ret = fn(data); + hard_irq_enable(); local_irq_restore(flags); return ret; } diff --git a/include/linux/thread_info.h b/include/linux/thread_info.h index 9ea0b2806..ace9feee3 100644 --- a/include/linux/thread_info.h +++ b/include/linux/thread_info.h @@ -260,6 +260,71 @@ void arch_task_cache_init(void); /* for CONFIG_SH */ void arch_release_task_struct(struct task_struct *tsk); int arch_dup_task_struct(struct task_struct *dst, struct task_struct *src); +#ifdef ti_local_flags +/* + * If the arch defines a set of per-thread synchronous flags, provide + * generic accessors to them. + */ +static __always_inline +void set_ti_local_flags(struct thread_info *ti, unsigned int mask) +{ + ti_local_flags(ti) |= mask; +} + +static __always_inline void set_thread_local_flags(unsigned int mask) +{ + set_ti_local_flags(current_thread_info(), mask); +} + +static __always_inline +int test_and_set_ti_local_flags(struct thread_info *ti, unsigned int mask) +{ + int old = ti_local_flags(ti) & mask; + ti_local_flags(ti) |= mask; + return old != 0; +} + +static __always_inline int test_and_set_thread_local_flags(unsigned int mask) +{ + return test_and_set_ti_local_flags(current_thread_info(), mask); +} + +static __always_inline +void clear_ti_local_flags(struct thread_info *ti, unsigned int mask) +{ + ti_local_flags(ti) &= ~mask; +} + +static __always_inline +int test_and_clear_ti_local_flags(struct thread_info *ti, unsigned int mask) +{ + int old = ti_local_flags(ti) & mask; + ti_local_flags(ti) &= ~mask; + return old != 0; +} + +static __always_inline int test_and_clear_thread_local_flags(unsigned int mask) +{ + return test_and_clear_ti_local_flags(current_thread_info(), mask); +} + +static __always_inline void clear_thread_local_flags(unsigned int mask) +{ + clear_ti_local_flags(current_thread_info(), mask); +} + +static __always_inline +bool test_ti_local_flags(struct thread_info *ti, unsigned int mask) +{ + return (ti_local_flags(ti) & mask) != 0; +} + +static __always_inline bool test_thread_local_flags(unsigned int mask) +{ + return test_ti_local_flags(current_thread_info(), mask); +} + +#endif /* ti_local_flags */ #endif /* __KERNEL__ */ diff --git a/include/linux/tick.h b/include/linux/tick.h index 9701c571a..58861257a 100644 --- a/include/linux/tick.h +++ b/include/linux/tick.h @@ -21,6 +21,14 @@ extern void tick_suspend_local(void); extern void tick_resume_local(void); extern void tick_handover_do_timer(void); extern void tick_cleanup_dead_cpu(int cpu); + +#ifdef CONFIG_IRQ_PIPELINE +int tick_install_proxy(void (*setup_proxy)(struct clock_proxy_device *dev), + const struct cpumask *cpumask); +void tick_uninstall_proxy(const struct cpumask *cpumask); +void tick_notify_proxy(void); +#endif + #else /* CONFIG_GENERIC_CLOCKEVENTS */ static inline void tick_init(void) { } static inline void tick_suspend_local(void) { } diff --git a/include/linux/trace_events.h b/include/linux/trace_events.h index aa1bc4172..053956e2d 100644 --- a/include/linux/trace_events.h +++ b/include/linux/trace_events.h @@ -7,6 +7,7 @@ #include #include #include +#include #include #include @@ -183,8 +184,9 @@ enum trace_flag_type { TRACE_FLAG_HARDIRQ = 0x08, TRACE_FLAG_SOFTIRQ = 0x10, TRACE_FLAG_PREEMPT_RESCHED = 0x20, - TRACE_FLAG_NMI = 0x40, + TRACE_FLAG_NMI = 0x40, /* Dovetail: hw NMI or oob */ TRACE_FLAG_BH_OFF = 0x80, + TRACE_FLAG_IRQS_HARDOFF = TRACE_FLAG_IRQS_NOSUPPORT, }; #ifdef CONFIG_TRACE_IRQFLAGS_SUPPORT @@ -198,7 +200,7 @@ static inline unsigned int tracing_gen_ctx(void) { unsigned long irqflags; - local_save_flags(irqflags); + stage_save_flags(irqflags); return tracing_gen_ctx_flags(irqflags); } #else diff --git a/include/linux/tracepoint.h b/include/linux/tracepoint.h index 88c0ba623..7364e84e8 100644 --- a/include/linux/tracepoint.h +++ b/include/linux/tracepoint.h @@ -180,12 +180,16 @@ static inline struct tracepoint *tracepoint_ptr_deref(tracepoint_ptr_t *p) /* * ARCH_WANTS_NO_INSTR archs are expected to have sanitized entry and idle * code that disallow any/all tracing/instrumentation when RCU isn't watching. + * + * IRQ pipeline: we may not depend on RCU for data which may be + * manipulated from the out-of-band stage, so rcuidle is meaningless + * in this case. */ #ifdef CONFIG_ARCH_WANTS_NO_INSTR -#define RCUIDLE_COND(rcuidle) (rcuidle) +#define RCUIDLE_COND(rcuidle) (running_inband() && rcuidle) #else /* srcu can't be used from NMI */ -#define RCUIDLE_COND(rcuidle) (rcuidle && in_nmi()) +#define RCUIDLE_COND(rcuidle) (running_inband() && rcuidle && in_nmi()) #endif /* @@ -258,7 +262,8 @@ static inline struct tracepoint *tracepoint_ptr_deref(tracepoint_ptr_t *p) __DO_TRACE(name, \ TP_ARGS(args), \ TP_CONDITION(cond), 0); \ - if (IS_ENABLED(CONFIG_LOCKDEP) && (cond)) { \ + if (IS_ENABLED(CONFIG_LOCKDEP) && \ + running_inband() && (cond)) { \ WARN_ON_ONCE(!rcu_is_watching()); \ } \ } \ diff --git a/include/linux/u64_stats_sync.h b/include/linux/u64_stats_sync.h index 457879938..4eaaf6496 100644 --- a/include/linux/u64_stats_sync.h +++ b/include/linux/u64_stats_sync.h @@ -99,6 +99,8 @@ static inline void __u64_stats_update_begin(struct u64_stats_sync *syncp) { } static inline void __u64_stats_update_end(struct u64_stats_sync *syncp) { } static inline unsigned long __u64_stats_irqsave(void) { return 0; } static inline void __u64_stats_irqrestore(unsigned long flags) { } +static inline unsigned long __u64_stats_hard_irqsave(void) { return 0; } +static inline void __u64_stats_hard_irqrestore(unsigned long flags) { } static inline unsigned int __u64_stats_fetch_begin(const struct u64_stats_sync *syncp) { return 0; @@ -166,6 +168,32 @@ static inline void __u64_stats_irqrestore(unsigned long flags) local_irq_restore(flags); } +#ifdef CONFIG_IRQ_PIPELINE + +static inline unsigned long __u64_stats_hard_irqsave(void) +{ + return hard_local_irq_save(); +} + +static inline void __u64_stats_hard_irqrestore(unsigned long flags) +{ + hard_local_irq_restore(flags); +} + +#else /* !CONFIG_IRQ_PIPELINE */ + +static inline unsigned long __u64_stats_hard_irqsave(void) +{ + return __u64_stats_irqsave(); +} + +static inline void __u64_stats_hard_irqrestore(unsigned long flags) +{ + __u64_stats_irqrestore(flags); +} + +#endif /* !CONFIG_IRQ_PIPELINE */ + static inline unsigned int __u64_stats_fetch_begin(const struct u64_stats_sync *syncp) { return read_seqcount_begin(&syncp->seq); @@ -203,6 +231,38 @@ static inline void u64_stats_update_end_irqrestore(struct u64_stats_sync *syncp, __u64_stats_irqrestore(flags); } +#ifdef CONFIG_IRQ_PIPELINE + +static inline unsigned long u64_stats_update_begin_hard_irqsave(struct u64_stats_sync *syncp) +{ + unsigned long flags = __u64_stats_hard_irqsave(); + + __u64_stats_update_begin(syncp); + return flags; +} + +static inline void u64_stats_update_end_hard_irqrestore(struct u64_stats_sync *syncp, + unsigned long flags) +{ + __u64_stats_update_end(syncp); + __u64_stats_hard_irqrestore(flags); +} + +#else /* !CONFIG_IRQ_PIPELINE */ + +static inline unsigned long u64_stats_update_begin_hard_irqsave(struct u64_stats_sync *syncp) +{ + return u64_stats_update_begin_irqsave(syncp); +} + +static inline void u64_stats_update_end_hard_irqrestore(struct u64_stats_sync *syncp, + unsigned long flags) +{ + u64_stats_update_end_irqrestore(syncp, flags); +} + +#endif /* !CONFIG_IRQ_PIPELINE */ + static inline unsigned int u64_stats_fetch_begin(const struct u64_stats_sync *syncp) { return __u64_stats_fetch_begin(syncp); diff --git a/include/linux/vmalloc.h b/include/linux/vmalloc.h index c720be70c..ef10f20aa 100644 --- a/include/linux/vmalloc.h +++ b/include/linux/vmalloc.h @@ -288,6 +288,7 @@ pcpu_free_vm_areas(struct vm_struct **vms, int nr_vms) int register_vmap_purge_notifier(struct notifier_block *nb); int unregister_vmap_purge_notifier(struct notifier_block *nb); +void arch_advertise_page_mapping(unsigned long start, unsigned long end); #if defined(CONFIG_MMU) && defined(CONFIG_PRINTK) bool vmalloc_dump_obj(void *object); diff --git a/include/net/net_namespace.h b/include/net/net_namespace.h index 1befad79a..1a9857c76 100644 --- a/include/net/net_namespace.h +++ b/include/net/net_namespace.h @@ -38,6 +38,7 @@ #include #include #include +#include #include #include #include @@ -169,6 +170,8 @@ struct net { u64 net_cookie; /* written once */ + struct oob_net_state oob; + #if IS_ENABLED(CONFIG_IP_VS) struct netns_ipvs *ipvs; #endif diff --git a/include/net/page_pool/types.h b/include/net/page_pool/types.h index 887e7946a..6f64a89c1 100644 --- a/include/net/page_pool/types.h +++ b/include/net/page_pool/types.h @@ -18,9 +18,11 @@ * device driver responsibility */ #define PP_FLAG_PAGE_FRAG BIT(2) /* for page frag feature */ +#define PP_FLAG_PAGE_OOB BIT(3) /* Enable access from the oob stage (Dovetail) */ #define PP_FLAG_ALL (PP_FLAG_DMA_MAP |\ PP_FLAG_DMA_SYNC_DEV |\ - PP_FLAG_PAGE_FRAG) + PP_FLAG_PAGE_FRAG |\ + PP_FLAG_PAGE_OOB) /* * Fast allocation side cache array/stack @@ -40,7 +42,12 @@ #define PP_ALLOC_CACHE_REFILL 64 struct pp_alloc_cache { u32 count; +#ifdef CONFIG_PAGE_POOL_OOB + struct page **cache; + hard_spinlock_t oob_lock; +#else /* !CONFIG_PAGE_POOL_OOB */ struct page *cache[PP_ALLOC_CACHE_SIZE]; +#endif /* !CONFIG_PAGE_POOL_OOB */ }; /** @@ -196,6 +203,24 @@ void page_pool_use_xdp_mem(struct page_pool *pool, void (*disconnect)(void *), struct xdp_mem_info *mem); void page_pool_put_page_bulk(struct page_pool *pool, void **data, int count); + +static inline bool page_pool_is_oob(struct page_pool *pool) +{ + return IS_ENABLED(CONFIG_PAGE_POOL_OOB) && + pool->p.flags & PP_FLAG_PAGE_OOB; +} + +static inline unsigned int page_pool_cache_size(struct page_pool *pool) +{ + return IS_ENABLED(CONFIG_PAGE_POOL_OOB) && + pool->p.flags & PP_FLAG_PAGE_OOB ? pool->p.pool_size : PP_ALLOC_CACHE_SIZE; +} + +static inline unsigned int page_pool_cache_refill(struct page_pool *pool) +{ + return IS_ENABLED(CONFIG_PAGE_POOL_OOB) && + pool->p.flags & PP_FLAG_PAGE_OOB ? pool->p.pool_size : PP_ALLOC_CACHE_REFILL; +} #else static inline void page_pool_unlink_napi(struct page_pool *pool) { diff --git a/include/net/sock.h b/include/net/sock.h index dc625f94e..e5f17caaa 100644 --- a/include/net/sock.h +++ b/include/net/sock.h @@ -539,6 +539,9 @@ struct sock { #endif void (*sk_destruct)(struct sock *sk); struct sock_reuseport __rcu *sk_reuseport_cb; +#ifdef CONFIG_NET_OOB + void *oob_data; +#endif #ifdef CONFIG_BPF_SYSCALL struct bpf_local_storage __rcu *sk_bpf_storage; #endif @@ -1879,6 +1882,47 @@ void sock_pfree(struct sk_buff *skb); #define sock_edemux sock_efree #endif +#ifdef CONFIG_NET_OOB + +static inline bool sock_oob_capable(struct socket *sock) +{ + return sock && sock->sk && sock->file && sock->file->oob_data; +} + +int sock_oob_bind(struct sock *sk, + struct sockaddr *addr, int len); + +int sock_oob_shutdown(struct sock *sk, int how); + +static inline void sock_oob_destruct(struct sock *sk) +{ + void sock_oob_destroy(struct sock *sk); + if (sk->oob_data) + sock_oob_destroy(sk); +} + +#else + +static inline bool sock_oob_capable(struct socket *sock) +{ + return false; +} + +static inline int sock_oob_bind(struct sock *sk, + struct sockaddr *addr, int len) +{ + return 0; +} + +static inline int sock_oob_shutdown(struct sock *sk, int how) +{ + return 0; +} + +static inline void sock_oob_destruct(struct sock *sk) { } + +#endif + int sk_setsockopt(struct sock *sk, int level, int optname, sockptr_t optval, unsigned int optlen); int sock_setsockopt(struct socket *sock, int level, int op, diff --git a/include/trace/events/evl.h b/include/trace/events/evl.h new file mode 100644 index 000000000..1fb2ba92b --- /dev/null +++ b/include/trace/events/evl.h @@ -0,0 +1,953 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Derived from Xenomai Cobalt, https://xenomai.org/ + * Copyright (C) 2014 Jan Kiszka . + * Copyright (C) 2014, 2018 Philippe Gerum + */ + +#if !defined(_TRACE_EVL_H) || defined(TRACE_HEADER_MULTI_READ) +#define _TRACE_EVL_H + +#undef TRACE_SYSTEM +#define TRACE_SYSTEM evl + +#include +#include +#include +#include +#include +#include +#include + +struct evl_rq; +struct evl_thread; +struct evl_sched_attrs; +struct evl_init_thread_attr; +struct evl_mutex; +struct evl_clock; + +DECLARE_EVENT_CLASS(thread_event, + TP_PROTO(struct evl_thread *thread), + TP_ARGS(thread), + + TP_STRUCT__entry( + __field(pid_t, pid) + __field(u32, state) + __field(u32, info) + ), + + TP_fast_assign( + __entry->state = thread->state; + __entry->info = thread->info; + __entry->pid = evl_get_inband_pid(thread); + ), + + TP_printk("pid=%d state=%#x info=%#x", + __entry->pid, __entry->state, __entry->info) +); + +DECLARE_EVENT_CLASS(curr_thread_event, + TP_PROTO(struct evl_thread *thread), + TP_ARGS(thread), + + TP_STRUCT__entry( + __field(struct evl_thread *, thread) + __field(u32, state) + __field(u32, info) + ), + + TP_fast_assign( + __entry->state = thread->state; + __entry->info = thread->info; + ), + + TP_printk("state=%#x info=%#x", + __entry->state, __entry->info) +); + +DECLARE_EVENT_CLASS(wchan_event, + TP_PROTO(struct evl_wait_channel *wchan), + TP_ARGS(wchan), + + TP_STRUCT__entry( + __string(name, wchan->name) + ), + + TP_fast_assign( + __assign_str(name, wchan->name); + ), + + TP_printk("wchan=%s", __get_str(name)) +); + +DECLARE_EVENT_CLASS(mutex_event, + TP_PROTO(struct evl_mutex *mutex), + TP_ARGS(mutex), + + TP_STRUCT__entry( + __field(struct evl_mutex *, mutex) + ), + + TP_fast_assign( + __entry->mutex = mutex; + ), + + TP_printk("mutex=%p", __entry->mutex) +); + +DECLARE_EVENT_CLASS(timer_event, + TP_PROTO(struct evl_timer *timer), + TP_ARGS(timer), + + TP_STRUCT__entry( + __field(struct evl_timer *, timer) + ), + + TP_fast_assign( + __entry->timer = timer; + ), + + TP_printk("timer=%s", evl_get_timer_name(__entry->timer)) +); + +#define evl_print_syscall(__nr) \ + __print_symbolic(__nr, \ + { 0, "oob_read" }, \ + { 1, "oob_write" }, \ + { 2, "oob_ioctl" }) + +DECLARE_EVENT_CLASS(evl_syscall_entry, + TP_PROTO(unsigned int nr), + TP_ARGS(nr), + + TP_STRUCT__entry( + __field(unsigned int, nr) + ), + + TP_fast_assign( + __entry->nr = nr; + ), + + TP_printk("syscall=%s", evl_print_syscall(__entry->nr)) +); + +DECLARE_EVENT_CLASS(evl_syscall_exit, + TP_PROTO(long result), + TP_ARGS(result), + + TP_STRUCT__entry( + __field(long, result) + ), + + TP_fast_assign( + __entry->result = result; + ), + + TP_printk("result=%ld", __entry->result) +); + +#define evl_print_sched_policy(__policy) \ + __print_symbolic(__policy, \ + {SCHED_NORMAL, "normal"}, \ + {SCHED_FIFO, "fifo"}, \ + {SCHED_RR, "rr"}, \ + {SCHED_QUOTA, "quota"}, \ + {SCHED_WEAK, "weak"}) + +const char *evl_trace_sched_attrs(struct trace_seq *seq, + struct evl_sched_attrs *attrs); + +DECLARE_EVENT_CLASS(evl_sched_attrs, + TP_PROTO(struct evl_thread *thread, + const struct evl_sched_attrs *attrs), + TP_ARGS(thread, attrs), + + TP_STRUCT__entry( + __field(struct evl_thread *, thread) + __field(int, policy) + __dynamic_array(char, attrs, sizeof(struct evl_sched_attrs)) + ), + + TP_fast_assign( + __entry->thread = thread; + __entry->policy = attrs->sched_policy; + memcpy(__get_dynamic_array(attrs), attrs, sizeof(*attrs)); + ), + + TP_printk("thread=%s policy=%s param={ %s }", + evl_element_name(&__entry->thread->element)? + evl_element_name(&__entry->thread->element):"{ }", + evl_print_sched_policy(__entry->policy), + evl_trace_sched_attrs(p, + (struct evl_sched_attrs *) + __get_dynamic_array(attrs)) + ) +); + +DECLARE_EVENT_CLASS(evl_clock_timespec, + TP_PROTO(struct evl_clock *clock, const struct timespec64 *val), + TP_ARGS(clock, val), + + TP_STRUCT__entry( + __timespec_fields(val) + __string(name, clock->name) + ), + + TP_fast_assign( + __assign_timespec(val, val); + __assign_str(name, clock->name); + ), + + TP_printk("clock=%s timeval=(%lld.%09lld)", + __get_str(name), + __timespec_args(val) + ) +); + +DECLARE_EVENT_CLASS(evl_clock_ident, + TP_PROTO(const char *name), + TP_ARGS(name), + TP_STRUCT__entry( + __string(name, name) + ), + TP_fast_assign( + __assign_str(name, name); + ), + TP_printk("name=%s", __get_str(name)) +); + +DECLARE_EVENT_CLASS(evl_schedule_event, + TP_PROTO(struct evl_rq *rq), + TP_ARGS(rq), + + TP_STRUCT__entry( + __field(unsigned long, flags) + __field(unsigned long, local_flags) + ), + + TP_fast_assign( + __entry->flags = rq->flags; + __entry->local_flags = rq->local_flags; + ), + + TP_printk("flags=%#lx, local_flags=%#lx", + __entry->flags, __entry->local_flags) +); + +DEFINE_EVENT(evl_schedule_event, evl_schedule, + TP_PROTO(struct evl_rq *rq), + TP_ARGS(rq) +); + +DEFINE_EVENT(evl_schedule_event, evl_reschedule_ipi, + TP_PROTO(struct evl_rq *rq), + TP_ARGS(rq) +); + +TRACE_EVENT(evl_pick_thread, + TP_PROTO(struct evl_thread *next), + TP_ARGS(next), + + TP_STRUCT__entry( + __string(next_name, next->name) + __field(pid_t, next_pid) + ), + + TP_fast_assign( + __assign_str(next_name, next->name); + __entry->next_pid = evl_get_inband_pid(next); + ), + + TP_printk("{ next=%s[%d] }", + __get_str(next_name), __entry->next_pid) +); + +TRACE_EVENT(evl_switch_context, + TP_PROTO(struct evl_thread *prev, struct evl_thread *next), + TP_ARGS(prev, next), + + TP_STRUCT__entry( + __string(prev_name, prev->name) + __string(next_name, next->name) + __field(pid_t, prev_pid) + __field(int, prev_prio) + __field(u32, prev_state) + __field(pid_t, next_pid) + __field(int, next_prio) + ), + + TP_fast_assign( + __entry->prev_pid = evl_get_inband_pid(prev); + __entry->prev_prio = prev->cprio; + __entry->prev_state = prev->state; + __entry->next_pid = evl_get_inband_pid(next); + __entry->next_prio = next->cprio; + __assign_str(prev_name, prev->name); + __assign_str(next_name, next->name); + ), + + TP_printk("{ %s[%d] prio=%d, state=%#x } => { %s[%d] prio=%d }", + __get_str(prev_name), __entry->prev_pid, + __entry->prev_prio, __entry->prev_state, + __get_str(next_name), __entry->next_pid, __entry->next_prio) +); + +TRACE_EVENT(evl_switch_tail, + TP_PROTO(struct evl_thread *curr), + TP_ARGS(curr), + + TP_STRUCT__entry( + __string(curr_name, curr->name) + __field(pid_t, curr_pid) + ), + + TP_fast_assign( + __assign_str(curr_name, curr->name); + __entry->curr_pid = evl_get_inband_pid(curr); + ), + + TP_printk("{ current=%s[%d] }", + __get_str(curr_name), __entry->curr_pid) +); + +TRACE_EVENT(evl_init_thread, + TP_PROTO(struct evl_thread *thread, + const struct evl_init_thread_attr *iattr, + int status), + TP_ARGS(thread, iattr, status), + + TP_STRUCT__entry( + __field(struct evl_thread *, thread) + __string(thread_name, thread->name) + __string(class_name, iattr->sched_class->name) + __field(unsigned long, flags) + __field(int, cprio) + __field(int, status) + ), + + TP_fast_assign( + __entry->thread = thread; + __assign_str(thread_name, thread->name); + __entry->flags = iattr->flags | (iattr->observable ? EVL_T_OBSERV : 0); + __assign_str(class_name, iattr->sched_class->name); + __entry->cprio = thread->cprio; + __entry->status = status; + ), + + TP_printk("thread=%p name=%s flags=%#lx class=%s prio=%d status=%#x", + __entry->thread, __get_str(thread_name), __entry->flags, + __get_str(class_name), __entry->cprio, __entry->status) +); + +TRACE_EVENT(evl_sleep_on, + TP_PROTO(ktime_t timeout, + enum evl_tmode timeout_mode, struct evl_clock *clock, + struct evl_wait_channel *wchan), + TP_ARGS(timeout, timeout_mode, clock, wchan), + + TP_STRUCT__entry( + __field(pid_t, pid) + __field(ktime_t, timeout) + __field(enum evl_tmode, timeout_mode) + __field(struct evl_wait_channel *, wchan) + __string(wchan_name, wchan ? wchan->name : "none") + __string(clock_name, clock ? clock->name : "none") + ), + + TP_fast_assign( + __entry->pid = evl_get_inband_pid(evl_current()); + __entry->timeout = timeout; + __entry->timeout_mode = timeout_mode; + __entry->wchan = wchan; + __assign_str(clock_name, clock ? clock->name : "none"); + __assign_str(wchan_name, wchan ? wchan->name : "none"); + ), + + TP_printk("pid=%d timeout=%Lu timeout_mode=%d clock=%s wchan=%s(%p)", + __entry->pid, + ktime_to_ns(__entry->timeout), __entry->timeout_mode, + __get_str(clock_name), + __get_str(wchan_name), + __entry->wchan) +); + +TRACE_EVENT(evl_wakeup_thread, + TP_PROTO(struct evl_thread *thread, int mask, int info), + TP_ARGS(thread, mask, info), + + TP_STRUCT__entry( + __string(name, thread->name) + __field(pid_t, pid) + __field(int, mask) + __field(int, info) + ), + + TP_fast_assign( + __assign_str(name, thread->name); + __entry->pid = evl_get_inband_pid(thread); + __entry->mask = mask; + __entry->info = info; + ), + + TP_printk("name=%s pid=%d mask=%#x info=%#x", + __get_str(name), __entry->pid, + __entry->mask, __entry->info) +); + +TRACE_EVENT(evl_hold_thread, + TP_PROTO(struct evl_thread *thread, unsigned long mask), + TP_ARGS(thread, mask), + + TP_STRUCT__entry( + __string(name, thread->name) + __field(pid_t, pid) + __field(unsigned long, mask) + ), + + TP_fast_assign( + __assign_str(name, thread->name); + __entry->pid = evl_get_inband_pid(thread); + __entry->mask = mask; + ), + + TP_printk("name=%s pid=%d mask=%#lx", + __get_str(name), __entry->pid, __entry->mask) +); + +TRACE_EVENT(evl_release_thread, + TP_PROTO(struct evl_thread *thread, int mask, int info), + TP_ARGS(thread, mask, info), + + TP_STRUCT__entry( + __string(name, thread->name) + __field(pid_t, pid) + __field(int, mask) + __field(int, info) + ), + + TP_fast_assign( + __assign_str(name, thread->name); + __entry->pid = evl_get_inband_pid(thread); + __entry->mask = mask; + __entry->info = info; + ), + + TP_printk("name=%s pid=%d mask=%#x info=%#x", + __get_str(name), __entry->pid, + __entry->mask, __entry->info) +); + +TRACE_EVENT(evl_thread_fault, + TP_PROTO(int trapnr, struct pt_regs *regs), + TP_ARGS(trapnr, regs), + + TP_STRUCT__entry( + __field(long, ip) + __field(unsigned int, trapnr) + ), + + TP_fast_assign( + __entry->ip = instruction_pointer(regs); + __entry->trapnr = trapnr; + ), + + TP_printk("ip=%#lx trapnr=%#x", + __entry->ip, __entry->trapnr) +); + +TRACE_EVENT(evl_thread_set_current_prio, + TP_PROTO(struct evl_thread *thread), + TP_ARGS(thread), + + TP_STRUCT__entry( + __field(struct evl_thread *, thread) + __field(pid_t, pid) + __field(int, cprio) + ), + + TP_fast_assign( + __entry->thread = thread; + __entry->pid = evl_get_inband_pid(thread); + __entry->cprio = thread->cprio; + ), + + TP_printk("thread=%p pid=%d prio=%d", + __entry->thread, __entry->pid, __entry->cprio) +); + +DEFINE_EVENT(thread_event, evl_thread_cancel, + TP_PROTO(struct evl_thread *thread), + TP_ARGS(thread) +); + +DEFINE_EVENT(thread_event, evl_thread_join, + TP_PROTO(struct evl_thread *thread), + TP_ARGS(thread) +); + +DEFINE_EVENT(thread_event, evl_unblock_thread, + TP_PROTO(struct evl_thread *thread), + TP_ARGS(thread) +); + +DEFINE_EVENT(curr_thread_event, evl_thread_wait_period, + TP_PROTO(struct evl_thread *thread), + TP_ARGS(thread) +); + +DEFINE_EVENT(curr_thread_event, evl_thread_missed_period, + TP_PROTO(struct evl_thread *thread), + TP_ARGS(thread) +); + +TRACE_EVENT(evl_thread_migrate, + TP_PROTO(struct evl_thread *thread, unsigned int cpu), + TP_ARGS(thread, cpu), + + TP_STRUCT__entry( + __field(struct evl_thread *, thread) + __field(pid_t, pid) + __field(unsigned int, cpu) + ), + + TP_fast_assign( + __entry->thread = thread; + __entry->pid = evl_get_inband_pid(thread); + __entry->cpu = cpu; + ), + + TP_printk("thread=%p pid=%d cpu=%u", + __entry->thread, __entry->pid, __entry->cpu) +); + +DEFINE_EVENT(curr_thread_event, evl_watchdog_signal, + TP_PROTO(struct evl_thread *curr), + TP_ARGS(curr) +); + +DEFINE_EVENT(curr_thread_event, evl_switch_oob, + TP_PROTO(struct evl_thread *curr), + TP_ARGS(curr) +); + +DEFINE_EVENT(curr_thread_event, evl_switched_oob, + TP_PROTO(struct evl_thread *curr), + TP_ARGS(curr) +); + +#define evl_print_switch_cause(cause) \ + __print_symbolic(cause, \ + { EVL_HMDIAG_TRAP, "breakpoint trap" }, \ + { EVL_HMDIAG_NONE, "undefined" }, \ + { EVL_HMDIAG_SIGDEMOTE, "in-band signal" }, \ + { EVL_HMDIAG_SYSDEMOTE, "in-band syscall" }, \ + { EVL_HMDIAG_EXDEMOTE, "processor exception" },\ + { EVL_HMDIAG_WATCHDOG, "watchdog" }, \ + { EVL_HMDIAG_LKDEPEND, "lock dependency" }, \ + { EVL_HMDIAG_LKIMBALANCE, "lock imbalance" }, \ + { EVL_HMDIAG_LKSLEEP, "sleep holding lock" }, \ + { EVL_HMDIAG_STAGEX, "stage exclusion" } ) + +TRACE_EVENT(evl_switch_inband, + TP_PROTO(int cause), + TP_ARGS(cause), + + TP_STRUCT__entry( + __field(int, cause) + ), + + TP_fast_assign( + __entry->cause = cause; + ), + + TP_printk("cause=%s", evl_print_switch_cause(__entry->cause)) +); + +DEFINE_EVENT(curr_thread_event, evl_switched_inband, + TP_PROTO(struct evl_thread *curr), + TP_ARGS(curr) +); + +DEFINE_EVENT(curr_thread_event, evl_kthread_entry, + TP_PROTO(struct evl_thread *thread), + TP_ARGS(thread) +); + +TRACE_EVENT(evl_thread_map, + TP_PROTO(struct evl_thread *thread), + TP_ARGS(thread), + + TP_STRUCT__entry( + __field(struct evl_thread *, thread) + __field(pid_t, pid) + __field(int, prio) + ), + + TP_fast_assign( + __entry->thread = thread; + __entry->pid = evl_get_inband_pid(thread); + __entry->prio = thread->bprio; + ), + + TP_printk("thread=%p pid=%d prio=%d", + __entry->thread, __entry->pid, __entry->prio) +); + +DEFINE_EVENT(curr_thread_event, evl_thread_unmap, + TP_PROTO(struct evl_thread *thread), + TP_ARGS(thread) +); + +TRACE_EVENT(evl_inband_wakeup, + TP_PROTO(struct task_struct *task), + TP_ARGS(task), + + TP_STRUCT__entry( + __field(pid_t, pid) + __array(char, comm, TASK_COMM_LEN) + ), + + TP_fast_assign( + __entry->pid = task_pid_nr(task); + memcpy(__entry->comm, task->comm, TASK_COMM_LEN); + ), + + TP_printk("pid=%d comm=%s", + __entry->pid, __entry->comm) +); + +TRACE_EVENT(evl_inband_signal, + TP_PROTO(struct evl_thread *thread, int sig, int sigval), + TP_ARGS(thread, sig, sigval), + + TP_STRUCT__entry( + __field(struct evl_thread *, thread) + __field(int, sig) + __field(int, sigval) + ), + + TP_fast_assign( + __entry->thread = thread; + __entry->sig = sig; + __entry->sigval = sigval; + ), + + /* Caller holds a reference on @thread, memory cannot be stale. */ + TP_printk("thread=%s pid=%d sig=%d sigval=%d", + evl_element_name(&__entry->thread->element), + evl_get_inband_pid(__entry->thread), + __entry->sig, __entry->sigval) +); + +DEFINE_EVENT(timer_event, evl_timer_stop, + TP_PROTO(struct evl_timer *timer), + TP_ARGS(timer) +); + +DEFINE_EVENT(timer_event, evl_timer_expire, + TP_PROTO(struct evl_timer *timer), + TP_ARGS(timer) +); + +#define evl_print_timer_mode(mode) \ + __print_symbolic(mode, \ + { EVL_REL, "rel" }, \ + { EVL_ABS, "abs" }) + +TRACE_EVENT(evl_timer_start, + TP_PROTO(struct evl_timer *timer, ktime_t value, ktime_t interval), + TP_ARGS(timer, value, interval), + + TP_STRUCT__entry( + __field(struct evl_timer *, timer) + __field(ktime_t, value) + __field(ktime_t, interval) + ), + + TP_fast_assign( + __entry->timer = timer; + __entry->value = value; + __entry->interval = interval; + ), + + TP_printk("timer=%s value=%Lu interval=%Lu", + evl_get_timer_name(__entry->timer), + ktime_to_ns(__entry->value), + ktime_to_ns(__entry->interval)) +); + +TRACE_EVENT(evl_timer_move, + TP_PROTO(struct evl_timer *timer, + struct evl_clock *clock, + unsigned int cpu), + TP_ARGS(timer, clock, cpu), + + TP_STRUCT__entry( + __field(unsigned int, cpu) + __string(timer_name, timer->name) + __string(clock_name, clock->name) + ), + + TP_fast_assign( + __entry->cpu = cpu; + __assign_str(timer_name, timer->name); + __assign_str(clock_name, clock->name); + ), + + TP_printk("timer=%s clock=%s cpu=%u", + __get_str(timer_name), + __get_str(clock_name), + __entry->cpu) +); + +TRACE_EVENT(evl_timer_shot, + TP_PROTO(struct evl_timer *timer, s64 delta, u64 cycles), + TP_ARGS(timer, delta, cycles), + + TP_STRUCT__entry( + __field(u64, secs) + __field(u32, nsecs) + __field(s64, delta) + __field(u64, cycles) + __string(name, timer->name) + ), + + TP_fast_assign( + __entry->cycles = cycles; + __entry->delta = delta; + __entry->secs = div_u64_rem(trace_clock_local() + delta, + NSEC_PER_SEC, &__entry->nsecs); + __assign_str(name, timer->name); + ), + + TP_printk("%s at %Lu.%06u (delay: %Ld us, %Lu cycles)", + __get_str(name), + (unsigned long long)__entry->secs, + __entry->nsecs / 1000, div_s64(__entry->delta, 1000), + __entry->cycles) +); + +DEFINE_EVENT(wchan_event, evl_wait, + TP_PROTO(struct evl_wait_channel *wchan), + TP_ARGS(wchan) +); + +DEFINE_EVENT(wchan_event, evl_wake_up, + TP_PROTO(struct evl_wait_channel *wchan), + TP_ARGS(wchan) +); + +DEFINE_EVENT(wchan_event, evl_flush_wait, + TP_PROTO(struct evl_wait_channel *wchan), + TP_ARGS(wchan) +); + +DEFINE_EVENT(wchan_event, evl_finish_wait, + TP_PROTO(struct evl_wait_channel *wchan), + TP_ARGS(wchan) +); + +DEFINE_EVENT(mutex_event, evl_mutex_trylock, + TP_PROTO(struct evl_mutex *mutex), + TP_ARGS(mutex) +); + +DEFINE_EVENT(mutex_event, evl_mutex_lock, + TP_PROTO(struct evl_mutex *mutex), + TP_ARGS(mutex) +); + +DEFINE_EVENT(mutex_event, evl_mutex_unlock, + TP_PROTO(struct evl_mutex *mutex), + TP_ARGS(mutex) +); + +DEFINE_EVENT(mutex_event, evl_mutex_destroy, + TP_PROTO(struct evl_mutex *mutex), + TP_ARGS(mutex) +); + +DEFINE_EVENT(mutex_event, evl_mutex_flush, + TP_PROTO(struct evl_mutex *mutex), + TP_ARGS(mutex) +); + +#define __timespec_fields(__name) \ + __field(__kernel_time64_t, tv_sec_##__name) \ + __field(long long, tv_nsec_##__name) + +#define __assign_timespec(__to, __from) \ + do { \ + __entry->tv_sec_##__to = (__from)->tv_sec; \ + __entry->tv_nsec_##__to = (__from)->tv_nsec; \ + } while (0) + +#define __timespec_args(__name) \ + __entry->tv_sec_##__name, __entry->tv_nsec_##__name + +DEFINE_EVENT(evl_syscall_entry, evl_oob_sysentry, + TP_PROTO(unsigned int nr), + TP_ARGS(nr) +); + +DEFINE_EVENT(evl_syscall_exit, evl_oob_sysexit, + TP_PROTO(long result), + TP_ARGS(result) +); + +DEFINE_EVENT(evl_syscall_entry, evl_inband_sysentry, + TP_PROTO(unsigned int nr), + TP_ARGS(nr) +); + +DEFINE_EVENT(evl_syscall_exit, evl_inband_sysexit, + TP_PROTO(long result), + TP_ARGS(result) +); + +DEFINE_EVENT(evl_sched_attrs, evl_thread_setsched, + TP_PROTO(struct evl_thread *thread, + const struct evl_sched_attrs *attrs), + TP_ARGS(thread, attrs) +); + +DEFINE_EVENT(evl_sched_attrs, evl_thread_getsched, + TP_PROTO(struct evl_thread *thread, + const struct evl_sched_attrs *attrs), + TP_ARGS(thread, attrs) +); + +#define evl_print_thread_mode(__mode) \ + __print_flags(__mode, "|", \ + {EVL_T_HMOBS, "hmobs"}, \ + {EVL_T_HMSIG, "hmsig"}, \ + {EVL_T_WOSX, "wosx"}, \ + {EVL_T_WOSS, "woss"}, \ + {EVL_T_WOLI, "woli"}, \ + {EVL_T_WOSO, "woso"}) + +TRACE_EVENT(evl_thread_update_mode, + TP_PROTO(struct evl_thread *thread, int mode, bool set), + TP_ARGS(thread, mode, set), + TP_STRUCT__entry( + __field(struct evl_thread *, thread) + __field(int, mode) + __field(bool, set) + ), + TP_fast_assign( + __entry->thread = thread; + __entry->mode = mode; + __entry->set = set; + ), + TP_printk("thread=%s %s %#x(%s)", + evl_element_name(&__entry->thread->element), + __entry->set ? "set" : "clear", + __entry->mode, evl_print_thread_mode(__entry->mode)) +); + +DEFINE_EVENT(evl_clock_timespec, evl_clock_getres, + TP_PROTO(struct evl_clock *clock, const struct timespec64 *res), + TP_ARGS(clock, res) +); + +DEFINE_EVENT(evl_clock_timespec, evl_clock_gettime, + TP_PROTO(struct evl_clock *clock, const struct timespec64 *time), + TP_ARGS(clock, time) +); + +DEFINE_EVENT(evl_clock_timespec, evl_clock_settime, + TP_PROTO(struct evl_clock *clock, const struct timespec64 *time), + TP_ARGS(clock, time) +); + +TRACE_EVENT(evl_clock_adjtime, + TP_PROTO(struct evl_clock *clock, struct __kernel_timex *tx), + TP_ARGS(clock, tx), + + TP_STRUCT__entry( + __field(struct __kernel_timex *, tx) + __string(name, clock->name) + ), + + TP_fast_assign( + __entry->tx = tx; + __assign_str(name, clock->name); + ), + + TP_printk("clock=%s timex=%p", + __get_str(name), + __entry->tx + ) +); + +#define evl_print_timer_flags(__flags) \ + __print_flags(__flags, "|", \ + {TIMER_ABSTIME, "TIMER_ABSTIME"}) + +DEFINE_EVENT(evl_clock_ident, evl_register_clock, + TP_PROTO(const char *name), + TP_ARGS(name) +); + +DEFINE_EVENT(evl_clock_ident, evl_unregister_clock, + TP_PROTO(const char *name), + TP_ARGS(name) +); + +TRACE_EVENT(evl_trace, + TP_PROTO(const char *msg), + TP_ARGS(msg), + TP_STRUCT__entry( + __string(msg, msg) + ), + TP_fast_assign( + __assign_str(msg, msg); + ), + TP_printk("%s", __get_str(msg)) +); + +TRACE_EVENT(evl_latspot, + TP_PROTO(int latmax_ns), + TP_ARGS(latmax_ns), + TP_STRUCT__entry( + __field(int, latmax_ns) + ), + TP_fast_assign( + __entry->latmax_ns = latmax_ns; + ), + TP_printk("** latency peak: %d.%.3d us **", + __entry->latmax_ns / 1000, + __entry->latmax_ns % 1000) +); + +TRACE_EVENT(evl_fpu_corrupt, + TP_PROTO(unsigned int fp_val), + TP_ARGS(fp_val), + TP_STRUCT__entry( + __field(unsigned int, fp_val) + ), + TP_fast_assign( + __entry->fp_val = fp_val; + ), + TP_printk("** bad FPU context: fp_val = %u **", + __entry->fp_val) +); + +/* Basically evl_trace() + trigger point */ +TRACE_EVENT(evl_trigger, + TP_PROTO(const char *issuer), + TP_ARGS(issuer), + TP_STRUCT__entry( + __string(issuer, issuer) + ), + TP_fast_assign( + __assign_str(issuer, issuer); + ), + TP_printk("%s", __get_str(issuer)) +); + +#endif /* _TRACE_EVL_H */ + +/* This part must be outside protection */ +#include diff --git a/include/trace/events/irq.h b/include/trace/events/irq.h index a07b4607b..239203ce5 100644 --- a/include/trace/events/irq.h +++ b/include/trace/events/irq.h @@ -100,6 +100,48 @@ TRACE_EVENT(irq_handler_exit, __entry->irq, __entry->ret ? "handled" : "unhandled") ); +/** + * irq_pipeline_entry - called when an external irq enters the pipeline + * @irq: irq number + */ +TRACE_EVENT(irq_pipeline_entry, + + TP_PROTO(int irq), + + TP_ARGS(irq), + + TP_STRUCT__entry( + __field( int, irq ) + ), + + TP_fast_assign( + __entry->irq = irq; + ), + + TP_printk("irq=%d", __entry->irq) +); + +/** + * irq_pipeline_exit - called when an external irq leaves the pipeline + * @irq: irq number + */ +TRACE_EVENT(irq_pipeline_exit, + + TP_PROTO(int irq), + + TP_ARGS(irq), + + TP_STRUCT__entry( + __field( int, irq ) + ), + + TP_fast_assign( + __entry->irq = irq; + ), + + TP_printk("irq=%d", __entry->irq) +); + DECLARE_EVENT_CLASS(softirq, TP_PROTO(unsigned int vec_nr), diff --git a/include/uapi/asm-generic/dovetail.h b/include/uapi/asm-generic/dovetail.h new file mode 100644 index 000000000..d5ff0044d --- /dev/null +++ b/include/uapi/asm-generic/dovetail.h @@ -0,0 +1,13 @@ +/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ +#ifndef __ASM_GENERIC_DOVETAIL_H +#define __ASM_GENERIC_DOVETAIL_H + +/* + * Legacy out-of-band syscall marker. Will be dropped at some point. + */ +#define __OOB_SYSCALL_BIT 0x10000000 + +/* Dovetail out-of-band syscall via prctl(2) */ +#define PR_OOB_SYSCALL 0x4f4f4243 + +#endif /* !__ASM_GENERIC_DOVETAIL_H */ diff --git a/include/uapi/asm-generic/fcntl.h b/include/uapi/asm-generic/fcntl.h index 80f37a0d4..6f0d33c5a 100644 --- a/include/uapi/asm-generic/fcntl.h +++ b/include/uapi/asm-generic/fcntl.h @@ -89,6 +89,15 @@ #define __O_TMPFILE 020000000 #endif +/* + * Tells the open call that out-of-band operations should be enabled + * for the file (if supported). Can also be passed along to socket(2) + * via the type argument as SOCK_OOB. + */ +#ifndef O_OOB +#define O_OOB 010000000000 +#endif + /* a horrid kludge trying to make sure that this will fail on old kernels */ #define O_TMPFILE (__O_TMPFILE | O_DIRECTORY) diff --git a/include/uapi/evl/clock-abi.h b/include/uapi/evl/clock-abi.h new file mode 100644 index 000000000..1d678d966 --- /dev/null +++ b/include/uapi/evl/clock-abi.h @@ -0,0 +1,37 @@ +/* + * SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note + * + * Copyright (C) 2018 Philippe Gerum + */ + +#ifndef _EVL_UAPI_CLOCK_ABI_H +#define _EVL_UAPI_CLOCK_ABI_H + +#include + +#define EVL_CLOCK_MONOTONIC_DEV "monotonic" +#define EVL_CLOCK_REALTIME_DEV "realtime" +#define EVL_CLOCK_DEV "clock" + +#define EVL_CLOCK_MONOTONIC (-CLOCK_MONOTONIC) +#define EVL_CLOCK_REALTIME (-CLOCK_REALTIME) + +#define EVL_CLOCK_IOCBASE 'c' + +#define EVL_CLKIOC_SLEEP _IOW(EVL_CLOCK_IOCBASE, 0, struct __evl_timespec) +#define EVL_CLKIOC_GET_RES _IOR(EVL_CLOCK_IOCBASE, 1, struct __evl_timespec) +#define EVL_CLKIOC_GET_TIME _IOR(EVL_CLOCK_IOCBASE, 2, struct __evl_timespec) +#define EVL_CLKIOC_SET_TIME _IOW(EVL_CLOCK_IOCBASE, 3, struct __evl_timespec) +#define EVL_CLKIOC_NEW_TIMER _IO(EVL_CLOCK_IOCBASE, 5) + +struct evl_timerfd_setreq { + __u64 value_ptr; /* (struct __evl_itimerspec __user *value) */ + __u64 ovalue_ptr; /* (struct __evl_itimerspec __user *ovalue) */ +}; + +#define EVL_TIMERFD_IOCBASE 't' + +#define EVL_TFDIOC_SET _IOWR(EVL_TIMERFD_IOCBASE, 0, struct evl_timerfd_setreq) +#define EVL_TFDIOC_GET _IOR(EVL_TIMERFD_IOCBASE, 1, struct __evl_itimerspec) + +#endif /* !_EVL_UAPI_CLOCK_ABI_H */ diff --git a/include/uapi/evl/control-abi.h b/include/uapi/evl/control-abi.h new file mode 100644 index 000000000..39e005195 --- /dev/null +++ b/include/uapi/evl/control-abi.h @@ -0,0 +1,42 @@ +/* + * SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note + * + * Copyright (C) 2018 Philippe Gerum + */ + +#ifndef _EVL_UAPI_CONTROL_ABI_H +#define _EVL_UAPI_CONTROL_ABI_H + +#include + +/* Earliest ABI level we support. */ +#define EVL_ABI_BASE 36 +/* + * Current/latest ABI level we support. We may decouple the base and + * current ABI levels by providing backward compatibility from the + * latter to the former. CAUTION: a litteral value is required for the + * current ABI definition (scripts reading this may be naive). + */ +#define EVL_ABI_LEVEL 37 + +#define EVL_CONTROL_DEV "/dev/evl/control" + +struct evl_core_info { + __u32 abi_base; + __u32 abi_current; + __u32 fpu_features; + __u64 shm_size; +}; + +struct evl_cpu_state { + __u32 cpu; + __u64 state_ptr; /* (__u32 __user *state) */ +}; + +#define EVL_CONTROL_IOCBASE 'C' + +#define EVL_CTLIOC_GET_COREINFO _IOR(EVL_CONTROL_IOCBASE, 0, struct evl_core_info) +#define EVL_CTLIOC_SCHEDCTL _IOWR(EVL_CONTROL_IOCBASE, 1, struct evl_sched_ctlreq) +#define EVL_CTLIOC_GET_CPUSTATE _IOR(EVL_CONTROL_IOCBASE, 2, struct evl_cpu_state) + +#endif /* !_EVL_UAPI_CONTROL_ABI_H */ diff --git a/include/uapi/evl/devices/gpio.h b/include/uapi/evl/devices/gpio.h new file mode 100644 index 000000000..06e43fbe8 --- /dev/null +++ b/include/uapi/evl/devices/gpio.h @@ -0,0 +1,10 @@ +/* + * SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note + */ + +#ifndef _EVL_UAPI_DEVICES_GPIO_H +#define _EVL_UAPI_DEVICES_GPIO_H + +#define GPIOHANDLE_REQUEST_OOB (1UL << 5) + +#endif /* !_EVL_UAPI_DEVICES_GPIO_H */ diff --git a/include/uapi/evl/devices/hectic.h b/include/uapi/evl/devices/hectic.h new file mode 100644 index 000000000..6426901d0 --- /dev/null +++ b/include/uapi/evl/devices/hectic.h @@ -0,0 +1,47 @@ +/* + * SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note + * + * Derived from Xenomai Cobalt's switchtest driver, https://xenomai.org/ + * Copyright (C) 2010 Gilles Chanteperdrix + * Copyright (C) 2018 Philippe Gerum + */ + +#ifndef _EVL_UAPI_DEVICES_HECTIC_H +#define _EVL_UAPI_DEVICES_HECTIC_H + +#include + +/* hectic_task_index.flags */ +#define HECTIC_OOB_WAIT 0x10000 +#define HECTIC_INBAND_WAIT 0 + +struct hectic_task_index { + unsigned int index; + unsigned int flags; +}; + +struct hectic_switch_req { + unsigned int from; + unsigned int to; +}; + +struct hectic_error { + struct hectic_switch_req last_switch; + unsigned int fp_val; +}; + +#define EVL_HECTIC_IOCBASE 'H' + +#define EVL_HECIOC_SET_TASKS_COUNT _IOW(EVL_HECTIC_IOCBASE, 0, __u32) +#define EVL_HECIOC_SET_CPU _IOW(EVL_HECTIC_IOCBASE, 1, __u32) +#define EVL_HECIOC_REGISTER_UTASK _IOW(EVL_HECTIC_IOCBASE, 2, struct hectic_task_index) +#define EVL_HECIOC_CREATE_KTASK _IOWR(EVL_HECTIC_IOCBASE, 3, struct hectic_task_index) +#define EVL_HECIOC_PEND _IOR(EVL_HECTIC_IOCBASE, 4, struct hectic_task_index) +#define EVL_HECIOC_SWITCH_TO _IOR(EVL_HECTIC_IOCBASE, 5, struct hectic_switch_req) +#define EVL_HECIOC_GET_SWITCHES_COUNT _IOR(EVL_HECTIC_IOCBASE, 6, __u32) +#define EVL_HECIOC_GET_LAST_ERROR _IOR(EVL_HECTIC_IOCBASE, 7, struct hectic_error) +#define EVL_HECIOC_SET_PAUSE _IOW(EVL_HECTIC_IOCBASE, 8, __u32) +#define EVL_HECIOC_LOCK_STAX _IO(EVL_HECTIC_IOCBASE, 9) +#define EVL_HECIOC_UNLOCK_STAX _IO(EVL_HECTIC_IOCBASE, 10) + +#endif /* !_EVL_UAPI_DEVICES_HECTIC_H */ diff --git a/include/uapi/evl/devices/latmus.h b/include/uapi/evl/devices/latmus.h new file mode 100644 index 000000000..b9cfd2897 --- /dev/null +++ b/include/uapi/evl/devices/latmus.h @@ -0,0 +1,67 @@ +/* + * SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note + * + * Derived from Xenomai Cobalt's autotune driver, https://xenomai.org/ + * Copyright (C) 2018 Philippe Gerum + */ + +#ifndef _EVL_UAPI_DEVICES_LATMUS_H +#define _EVL_UAPI_DEVICES_LATMUS_H + +#include + +/* Latmus context types. */ +#define EVL_LAT_IRQ 0 +#define EVL_LAT_KERN 1 +#define EVL_LAT_USER 2 +#define EVL_LAT_SIRQ 3 +#define EVL_LAT_LAST EVL_LAT_SIRQ + +struct latmus_setup { + __u32 type; + __u64 period; + __s32 priority; + __u32 cpu; + union { + struct { + __u32 verbosity; + } tune; + struct { + __u32 xfd; + __u32 hcells; + } measure; + } u; +}; + +/* + * The measurement record which the driver sends to userland each + * second through an xbuf channel. + */ +struct latmus_measurement { + __s64 sum_lat; + __s32 min_lat; + __s32 max_lat; + __u32 overruns; + __u32 samples; +}; + +struct latmus_measurement_result { + __u64 last_ptr; /* (struct latmus_measurement __user *last) */ + __u64 histogram_ptr; /* (__s32 __user *histogram) */ + __u32 len; +}; + +struct latmus_result { + __u64 data_ptr; /* (void __user *data) */ + __u32 len; +}; + +#define EVL_LATMUS_IOCBASE 'L' + +#define EVL_LATIOC_TUNE _IOWR(EVL_LATMUS_IOCBASE, 0, struct latmus_setup) +#define EVL_LATIOC_MEASURE _IOWR(EVL_LATMUS_IOCBASE, 1, struct latmus_setup) +#define EVL_LATIOC_RUN _IOR(EVL_LATMUS_IOCBASE, 2, struct latmus_result) +#define EVL_LATIOC_PULSE _IOW(EVL_LATMUS_IOCBASE, 3, __u64) +#define EVL_LATIOC_RESET _IO(EVL_LATMUS_IOCBASE, 4) + +#endif /* !_EVL_UAPI_DEVICES_LATMUS_H */ diff --git a/include/uapi/evl/devices/spidev.h b/include/uapi/evl/devices/spidev.h new file mode 100644 index 000000000..78ab4e709 --- /dev/null +++ b/include/uapi/evl/devices/spidev.h @@ -0,0 +1,26 @@ +/* + * SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note + */ + +#ifndef _EVL_UAPI_DEVICES_SPIDEV_H +#define _EVL_UAPI_DEVICES_SPIDEV_H + +#include + +/* Manage out-of-band mode (master only) */ +struct spi_ioc_oob_setup { + /* Input */ + __u32 frame_len; + __u32 speed_hz; + __u8 bits_per_word; + /* Output */ + __u32 iobuf_len; + __u32 tx_offset; + __u32 rx_offset; +}; + +#define SPI_IOC_ENABLE_OOB_MODE _IOWR(SPI_IOC_MAGIC, 50, struct spi_ioc_oob_setup) +#define SPI_IOC_DISABLE_OOB_MODE _IO(SPI_IOC_MAGIC, 51) +#define SPI_IOC_RUN_OOB_XFER _IO(SPI_IOC_MAGIC, 52) + +#endif /* _EVL_UAPI_DEVICES_SPIDEV_H */ diff --git a/include/uapi/evl/factory-abi.h b/include/uapi/evl/factory-abi.h new file mode 100644 index 000000000..84e495910 --- /dev/null +++ b/include/uapi/evl/factory-abi.h @@ -0,0 +1,48 @@ +/* + * SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note + * + * Copyright (C) 2018 Philippe Gerum + */ + +#ifndef _EVL_UAPI_FACTORY_ABI_H +#define _EVL_UAPI_FACTORY_ABI_H + +#include + +#define EVL_FACTORY_IOCBASE 'f' + +struct evl_element_ids { + __u32 minor; + __u32 fundle; + __u32 state_offset; +}; + +/* The core only uses bits 16-31, rest is available to libevl. */ +#define EVL_CLONE_PUBLIC (1 << 16) +#define EVL_CLONE_PRIVATE (0 << 16) +#define EVL_CLONE_OBSERVABLE (1 << 17) +#define EVL_CLONE_NONBLOCK (1 << 18) +#define EVL_CLONE_UNICAST (1 << 19) +#define EVL_CLONE_INPUT (1 << 20) +#define EVL_CLONE_OUTPUT (1 << 21) +#define EVL_CLONE_COREDEV (1 << 31) +#define EVL_CLONE_MASK (((__u32)-1 << 16) & ~EVL_CLONE_COREDEV) +/* + * Deprecated: this is a longstanding misnomer. This flag is really + * about sending unicast notifications as opposed to broadcasting + * events to all observers. + */ +#define EVL_CLONE_MASTER EVL_CLONE_UNICAST + +struct evl_clone_req { + __u64 name_ptr; /* (const char __user *name) */ + __u64 attrs_ptr; /* (void __user *attrs) */ + __u32 clone_flags; + /* Output on success: */ + struct evl_element_ids eids; + __u32 efd; +}; + +#define EVL_IOC_CLONE _IOWR(EVL_FACTORY_IOCBASE, 0, struct evl_clone_req) + +#endif /* !_EVL_UAPI_FACTORY_ABI_H */ diff --git a/include/uapi/evl/fcntl.h b/include/uapi/evl/fcntl.h new file mode 100644 index 000000000..8f0b92570 --- /dev/null +++ b/include/uapi/evl/fcntl.h @@ -0,0 +1,16 @@ +/* + * SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note + * + * Copyright (C) 2021 Philippe Gerum + */ + +#ifndef _EVL_UAPI_FCNTL_H +#define _EVL_UAPI_FCNTL_H + +/* + * EVL-specific open mode. Must match kernel UAPI in + * include/uapi/asm-generic/fcntl.h. + */ +#define O_OOB 010000000000 /* Request out-of-band capabilities */ + +#endif /* !_EVL_UAPI_FCNTL_H */ diff --git a/include/uapi/evl/monitor-abi.h b/include/uapi/evl/monitor-abi.h new file mode 100644 index 000000000..d77da9038 --- /dev/null +++ b/include/uapi/evl/monitor-abi.h @@ -0,0 +1,88 @@ +/* + * SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note + * + * Copyright (C) 2018 Philippe Gerum + */ + +#ifndef _EVL_UAPI_MONITOR_ABI_H +#define _EVL_UAPI_MONITOR_ABI_H + +#include + +#define EVL_MONITOR_DEV "monitor" + +#define EVL_MONITOR_EVENT 0 /* Event monitor. */ +# define EVL_EVENT_GATED 0 /* Gate protected. */ +# define EVL_EVENT_COUNT 1 /* Semaphore. */ +# define EVL_EVENT_MASK 2 /* Event (bit)mask. */ +#define EVL_MONITOR_GATE 1 /* Gate monitor. */ +# define EVL_GATE_PI 0 /* Gate with priority inheritance. */ +# define EVL_GATE_PP 1 /* Gate with priority protection (ceiling). */ + +struct evl_monitor_attrs { + __u32 clockfd; + __u32 type : 2, + protocol : 4; + __u32 initval; +}; + +/* State flags. */ +#define EVL_MONITOR_SIGNALED 0x1 /* Gate/Event */ +#define EVL_MONITOR_BROADCAST 0x2 /* Event */ +#define EVL_MONITOR_TARGETED 0x4 /* Event */ + +#define EVL_MONITOR_NOGATE -1U + +struct evl_monitor_state { + __u32 flags; + union { + struct { + __u32 owner; /* atomic_t */ + __u32 ceiling; + __u32 recursive: 1, + nesting : 31; + } gate; + struct { + __u32 value; /* atomic_t */ + __u32 pollrefs; /* atomic_t */ + __u32 gate_offset; + } event; + } u; +}; + +struct evl_monitor_waitreq { + __u64 timeout_ptr; /* (struct __evl_timespec __user *timeout) */ + __s32 gatefd; + __s32 status; + __s32 value; +}; + +struct evl_monitor_unwaitreq { + __s32 gatefd; +}; + +struct evl_monitor_trywaitreq { + __s32 value; +}; + +struct evl_monitor_binding { + __u32 type : 2, + protocol : 4; + struct evl_element_ids eids; +}; + +#define EVL_MONITOR_IOCBASE 'm' + +#define EVL_MONIOC_ENTER _IOW(EVL_MONITOR_IOCBASE, 0, struct __evl_timespec) +#define EVL_MONIOC_TRYENTER _IO(EVL_MONITOR_IOCBASE, 1) +#define EVL_MONIOC_EXIT _IO(EVL_MONITOR_IOCBASE, 2) +#define EVL_MONIOC_WAIT _IOWR(EVL_MONITOR_IOCBASE, 3, struct evl_monitor_waitreq) +#define EVL_MONIOC_UNWAIT _IOWR(EVL_MONITOR_IOCBASE, 4, struct evl_monitor_unwaitreq) +#define EVL_MONIOC_BIND _IOR(EVL_MONITOR_IOCBASE, 5, struct evl_monitor_binding) +#define EVL_MONIOC_SIGNAL _IOW(EVL_MONITOR_IOCBASE, 6, __s32) +#define EVL_MONIOC_BROADCAST _IOW(EVL_MONITOR_IOCBASE, 7, __s32) +#define EVL_MONIOC_WAIT_EXACT _IOWR(EVL_MONITOR_IOCBASE, 8, struct evl_monitor_waitreq) +#define EVL_MONIOC_TRYWAIT _IOWR(EVL_MONITOR_IOCBASE, 9, struct evl_monitor_trywaitreq) +#define EVL_MONIOC_TRYWAIT_EXACT _IOWR(EVL_MONITOR_IOCBASE, 10, struct evl_monitor_trywaitreq) + +#endif /* !_EVL_UAPI_MONITOR_ABI_H */ diff --git a/include/uapi/evl/net/bpf-abi.h b/include/uapi/evl/net/bpf-abi.h new file mode 100644 index 000000000..08757fedb --- /dev/null +++ b/include/uapi/evl/net/bpf-abi.h @@ -0,0 +1,17 @@ +/* + * SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note + * + * Copyright (C) 2024 Philippe Gerum + */ + +#ifndef _EVL_UAPI_NET_BPF_ABI_H +#define _EVL_UAPI_NET_BPF_ABI_H + +enum evl_net_rx_action { + EVL_RX_DROP = 0, /* Discard */ + EVL_RX_ACCEPT, /* Pass to oob stack */ + EVL_RX_SKIP, /* Leave to inband stack */ + EVL_RX_VLAN, /* Apply VLAN-based rules */ +}; + +#endif /* !_EVL_UAPI_NET_BPF_ABI_H */ diff --git a/include/uapi/evl/net/device-abi.h b/include/uapi/evl/net/device-abi.h new file mode 100644 index 000000000..7c2a2a206 --- /dev/null +++ b/include/uapi/evl/net/device-abi.h @@ -0,0 +1,16 @@ +/* + * SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note + * + * Copyright (C) 2024 Philippe Gerum + */ + +#ifndef _EVL_UAPI_NET_DEVICE_ABI_H +#define _EVL_UAPI_NET_DEVICE_ABI_H + +#include + +#define EVL_NETDEV_IOCBASE 0xef + +#define EVL_NDEVIOC_SETRXEBPF _IOW(EVL_NETDEV_IOCBASE, 0, __s32 /* fd */) + +#endif /* !_EVL_UAPI_NET_DEVICE_ABI_H */ diff --git a/include/uapi/evl/net/net-abi.h b/include/uapi/evl/net/net-abi.h new file mode 100644 index 000000000..c75e571a8 --- /dev/null +++ b/include/uapi/evl/net/net-abi.h @@ -0,0 +1,23 @@ +/* + * SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note + * + * Copyright (C) 2024 Philippe Gerum + */ + +#ifndef _EVL_UAPI_NET_NET_ABI_H +#define _EVL_UAPI_NET_NET_ABI_H + +#include + +#define EVL_NET_DEV "net" + +#define EVL_NET_IOCBASE 0xf0 + +struct evl_net_devfd { + __u64 name_ptr; /* (const char __user *name) */ + __u32 fd; +}; + +#define EVL_NET_GETDEVFD _IOWR(EVL_NETDEV_IOCBASE, 0, struct evl_net_devfd) + +#endif /* !_EVL_UAPI_NET_NET_ABI_H */ diff --git a/include/uapi/evl/net/socket-abi.h b/include/uapi/evl/net/socket-abi.h new file mode 100644 index 000000000..4973e7d0d --- /dev/null +++ b/include/uapi/evl/net/socket-abi.h @@ -0,0 +1,44 @@ +/* + * SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note + * + * Copyright (C) 2020 Philippe Gerum + */ + +#ifndef _EVL_UAPI_NET_SOCKET_ABI_H +#define _EVL_UAPI_NET_SOCKET_ABI_H + +#include + +#define AF_OOB 46 /* Out-of-band domain sockets */ + +#define SOCK_OOB O_OOB /* Request out-of-band capabilities */ + +/* Keep this distinct from SOCK_IOC_TYPE (0x89) */ +#define EVL_SOCKET_IOCBASE 0xee + +struct user_oob_msghdr { + __u64 name_ptr; /* (struct sockaddr __user *name) */ + __u64 iov_ptr; /* (struct iovec __user *iov) */ + __u64 ctl_ptr; /* (void __user *control) */ + __u32 namelen; + __u32 iovlen; + __u32 ctllen; + __s32 count; /* Receive only (actual byte count). */ + __u32 flags; + struct __evl_timespec timeout; + struct __evl_timespec timestamp; /* Stats / TSN trigger */ +}; + +struct evl_netdev_activation { + __u64 poolsz; + __u64 bufsz; +}; + +#define EVL_SOCKIOC_ACTIVATE _IOW(EVL_SOCKET_IOCBASE, 2, struct evl_netdev_activation) +#define EVL_SOCKIOC_DEACTIVATE _IO(EVL_SOCKET_IOCBASE, 3) +#define EVL_SOCKIOC_SENDMSG _IOW(EVL_SOCKET_IOCBASE, 4, struct user_oob_msghdr) +#define EVL_SOCKIOC_RECVMSG _IOWR(EVL_SOCKET_IOCBASE, 5, struct user_oob_msghdr) +#define EVL_SOCKIOC_SETRECVSZ _IOW(EVL_SOCKET_IOCBASE, 6, int) +#define EVL_SOCKIOC_SETSENDSZ _IOW(EVL_SOCKET_IOCBASE, 7, int) + +#endif /* !_EVL_UAPI_NET_SOCKET_ABI_H */ diff --git a/include/uapi/evl/observable-abi.h b/include/uapi/evl/observable-abi.h new file mode 100644 index 000000000..3da0a47ae --- /dev/null +++ b/include/uapi/evl/observable-abi.h @@ -0,0 +1,45 @@ +/* + * SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note + * + * Copyright (C) 2020 Philippe Gerum + */ + +#ifndef _EVL_UAPI_OBSERVABLE_ABI_H +#define _EVL_UAPI_OBSERVABLE_ABI_H + +#include + +#define EVL_OBSERVABLE_DEV "observable" + +/* __evl_notification.flags */ +#define EVL_NOTIFY_ALWAYS (0 << 0) +#define EVL_NOTIFY_ONCHANGE (1 << 0) +#define EVL_NOTIFY_MASK EVL_NOTIFY_ONCHANGE + +struct evl_notice { + __u32 tag; + union evl_value event; +}; + +/* Notice tags below this value are reserved to the core. */ +#define EVL_NOTICE_USER 64 + +struct evl_subscription { + __u32 backlog_count; + __u32 flags; +}; + +struct __evl_notification { + __u32 tag; + __u32 serial; + __s32 issuer; + union evl_value event; + struct __evl_timespec date; +}; + +#define EVL_OBSERVABLE_IOCBASE 'o' + +#define EVL_OBSIOC_SUBSCRIBE _IOW(EVL_OBSERVABLE_IOCBASE, 0, struct evl_subscription) +#define EVL_OBSIOC_UNSUBSCRIBE _IO(EVL_OBSERVABLE_IOCBASE, 1) + +#endif /* !_EVL_UAPI_OBSERVABLE_ABI_H */ diff --git a/include/uapi/evl/poll-abi.h b/include/uapi/evl/poll-abi.h new file mode 100644 index 000000000..ba2816e62 --- /dev/null +++ b/include/uapi/evl/poll-abi.h @@ -0,0 +1,42 @@ +/* + * SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note + * + * Copyright (C) 2018 Philippe Gerum + */ + +#ifndef _EVL_UAPI_POLL_ABI_H +#define _EVL_UAPI_POLL_ABI_H + +#include + +#define EVL_POLL_DEV "poll" + +#define EVL_POLL_IOCBASE 'p' + +#define EVL_POLL_CTLADD 0 +#define EVL_POLL_CTLDEL 1 +#define EVL_POLL_CTLMOD 2 + +struct evl_poll_ctlreq { + __u32 action; + __u32 fd; + __u32 events; + union evl_value pollval; +}; + +struct evl_poll_event { + __u32 fd; + __u32 events; + union evl_value pollval; +}; + +struct evl_poll_waitreq { + __u64 timeout_ptr; /* (struct __evl_timespec __user *timeout) */ + __u64 pollset_ptr; /* (struct evl_poll_event __user *pollset) */ + int nrset; +}; + +#define EVL_POLIOC_CTL _IOW(EVL_POLL_IOCBASE, 0, struct evl_poll_ctlreq) +#define EVL_POLIOC_WAIT _IOWR(EVL_POLL_IOCBASE, 1, struct evl_poll_waitreq) + +#endif /* !_EVL_UAPI_POLL_ABI_H */ diff --git a/include/uapi/evl/proxy-abi.h b/include/uapi/evl/proxy-abi.h new file mode 100644 index 000000000..6425e282b --- /dev/null +++ b/include/uapi/evl/proxy-abi.h @@ -0,0 +1,20 @@ +/* + * SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note + * + * Copyright (C) 2019 Philippe Gerum + */ + +#ifndef _EVL_UAPI_PROXY_ABI_H +#define _EVL_UAPI_PROXY_ABI_H + +#include + +#define EVL_PROXY_DEV "proxy" + +struct evl_proxy_attrs { + __u32 fd; + __u32 bufsz; + __u32 granularity; +}; + +#endif /* !_EVL_UAPI_PROXY_ABI_H */ diff --git a/include/uapi/evl/random-abi.h b/include/uapi/evl/random-abi.h new file mode 100644 index 000000000..5a2afe981 --- /dev/null +++ b/include/uapi/evl/random-abi.h @@ -0,0 +1,20 @@ +/* + * SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note + * + * Copyright (C) 2023 Philippe Gerum + */ + +#ifndef _EVL_UAPI_RANDOM_ABI_H +#define _EVL_UAPI_RANDOM_ABI_H + +#include + +#define EVL_RANDOM_DEV "random" + +#define EVL_RANDOM_IOCBASE 'r' + +#define EVL_RNGIOC_U8 _IOR(EVL_RANDOM_IOCBASE, 0, __u8) +#define EVL_RNGIOC_U16 _IOR(EVL_RANDOM_IOCBASE, 1, __u16) +#define EVL_RNGIOC_U32 _IOR(EVL_RANDOM_IOCBASE, 2, __u32) + +#endif /* !_EVL_UAPI_RANDOM_ABI_H */ diff --git a/include/uapi/evl/sched-abi.h b/include/uapi/evl/sched-abi.h new file mode 100644 index 000000000..8c453c86c --- /dev/null +++ b/include/uapi/evl/sched-abi.h @@ -0,0 +1,133 @@ +/* + * SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note + * + * Derived from Xenomai Cobalt, https://xenomai.org/ + * Copyright (C) 2005, 2018 Philippe Gerum + */ + +#ifndef _EVL_UAPI_SCHED_ABI_H +#define _EVL_UAPI_SCHED_ABI_H + +#include + +#define EVL_CPU_OOB (1 << 0) +#define EVL_CPU_ISOL (1 << 1) +#define EVL_CPU_OFFLINE (1 << 2) + +#define SCHED_WEAK 43 + +#define sched_rr_quantum sched_u.rr.__sched_rr_quantum + +struct __evl_rr_param { + struct __evl_timespec __sched_rr_quantum; +}; + +#define SCHED_QUOTA 44 +#define sched_quota_group sched_u.quota.__sched_group + +struct __evl_quota_param { + int __sched_group; +}; + +enum evl_quota_ctlop { + evl_quota_add, + evl_quota_remove, + evl_quota_force_remove, + evl_quota_set, + evl_quota_get, +}; + +struct evl_quota_ctlparam { + enum evl_quota_ctlop op; + union { + struct { + int tgid; + } remove; + struct { + int tgid; + int quota; + int quota_peak; + } set; + struct { + int tgid; + } get; + } u; +}; + +struct evl_quota_ctlinfo { + int tgid; + int quota; + int quota_peak; + int quota_sum; +}; + +#define SCHED_TP 45 +#define sched_tp_partition sched_u.tp.__sched_partition + +struct __evl_tp_param { + int __sched_partition; +}; + +#define EVL_TP_IDLE -1 /* Idle pseudo-partition */ + +struct __evl_tp_window { + struct __evl_timespec offset; + struct __evl_timespec duration; + int ptid; +}; + +enum evl_tp_ctlop { + evl_tp_install, + evl_tp_uninstall, + evl_tp_start, + evl_tp_stop, + evl_tp_get, +}; + +struct evl_tp_ctlparam { + enum evl_tp_ctlop op; + int nr_windows; + struct __evl_tp_window windows[0]; +}; + +#define evl_tp_paramlen(__nr_windows) \ + (sizeof(struct evl_tp_ctlparam) + \ + __nr_windows * sizeof(struct __evl_tp_window)) + +struct evl_tp_ctlinfo { + int nr_windows; + struct __evl_tp_window windows[0]; +}; + +#define evl_tp_infolen(__nr_windows) \ + (sizeof(struct evl_tp_ctlinfo) + \ + __nr_windows * sizeof(struct __evl_tp_window)) + +struct evl_sched_attrs { + int sched_policy; + int sched_priority; + union { + struct __evl_rr_param rr; + struct __evl_quota_param quota; + struct __evl_tp_param tp; + } sched_u; +}; + +union evl_sched_ctlparam { + struct evl_quota_ctlparam quota; + struct evl_tp_ctlparam tp; +}; + +union evl_sched_ctlinfo { + struct evl_quota_ctlinfo quota; + struct evl_tp_ctlinfo tp; +}; + +struct evl_sched_ctlreq { + int policy; + int cpu; + __u64 param_ptr; /* (const union evl_sched_ctlparam __user *param) */ + __u64 info_ptr; /* (union evl_sched_ctlinfo __user *info) */ +}; + +#endif /* !_EVL_UAPI_SCHED_ABI_H */ diff --git a/include/uapi/evl/signal.h b/include/uapi/evl/signal.h new file mode 100644 index 000000000..3d4a869e1 --- /dev/null +++ b/include/uapi/evl/signal.h @@ -0,0 +1,22 @@ +/* + * SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note + * + * Derived from Xenomai Cobalt, https://xenomai.org/ + * Copyright (C) 2006 Gilles Chanteperdrix + * Copyright (C) 2013, 2018 Philippe Gerum + */ + +#ifndef _EVL_UAPI_SIGNAL_H +#define _EVL_UAPI_SIGNAL_H + +/* + * EVL_HMDIAG_xxx codes are possible values of sigdebug_cause(). + */ +#define SIGDEBUG SIGXCPU +#define sigdebug_code(si) ((si)->si_value.sival_int) +#define sigdebug_cause(si) (sigdebug_code(si) & 0xff) +#define sigdebug_marker 0xfccf0000 +#define sigdebug_marked(si) \ + ((sigdebug_code(si) & 0xffff0000) == sigdebug_marker) + +#endif /* !_EVL_UAPI_SIGNAL_H */ diff --git a/include/uapi/evl/syscall-abi.h b/include/uapi/evl/syscall-abi.h new file mode 100644 index 000000000..ecc2412f3 --- /dev/null +++ b/include/uapi/evl/syscall-abi.h @@ -0,0 +1,16 @@ +/* + * SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note + * + * Copyright (C) 2018 Philippe Gerum + */ + +#ifndef _EVL_UAPI_SYSCALL_ABI_H +#define _EVL_UAPI_SYSCALL_ABI_H + +#define sys_evl_read 0 /* oob_read() */ +#define sys_evl_write 1 /* oob_write() */ +#define sys_evl_ioctl 2 /* oob_ioctl() */ + +#define NR_EVL_SYSCALLS 3 + +#endif /* !_EVL_UAPI_SYSCALL_ABI_H */ diff --git a/include/uapi/evl/thread-abi.h b/include/uapi/evl/thread-abi.h new file mode 100644 index 000000000..8b3c76aa2 --- /dev/null +++ b/include/uapi/evl/thread-abi.h @@ -0,0 +1,133 @@ +/* + * SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note + * + * Derived from Xenomai Cobalt, https://xenomai.org/ + * Copyright (C) 2005, 2018 Philippe Gerum + */ + +#ifndef _EVL_UAPI_THREAD_ABI_H +#define _EVL_UAPI_THREAD_ABI_H + +#include + +#define EVL_THREAD_DEV "thread" + +/* State flags (shared) */ + +#define EVL_T_SUSP 0x00000001 /* Suspended */ +#define EVL_T_PEND 0x00000002 /* Blocked on a wait_queue/mutex */ +#define EVL_T_DELAY 0x00000004 /* Delayed/timed */ +#define EVL_T_WAIT 0x00000008 /* Periodic wait */ +#define EVL_T_READY 0x00000010 /* Ready to run (in rq) */ +#define EVL_T_DORMANT 0x00000020 /* Not started yet */ +#define EVL_T_ZOMBIE 0x00000040 /* Dead, waiting for disposal */ +#define EVL_T_INBAND 0x00000080 /* Running in-band */ +#define EVL_T_HALT 0x00000100 /* Halted */ +#define EVL_T_BOOST 0x00000200 /* PI/PP boost undergoing */ +#define EVL_T_PTSYNC 0x00000400 /* Synchronizing on ptrace event */ +#define EVL_T_RRB 0x00000800 /* Undergoes round-robin scheduling */ +#define EVL_T_ROOT 0x00001000 /* Root thread (in-band kernel placeholder) */ +#define EVL_T_WEAK 0x00002000 /* Weak scheduling (in-band) */ +#define EVL_T_USER 0x00004000 /* Userland thread */ +#define EVL_T_WOSS 0x00008000 /* Warn on stage switch (HM) */ +#define EVL_T_WOLI 0x00010000 /* Warn on locking inconsistency (HM) */ +#define EVL_T_WOSX 0x00020000 /* Warn on stage exclusion (HM) */ +#define EVL_T_PTRACE 0x00040000 /* Stopped on ptrace event */ +#define EVL_T_OBSERV 0x00080000 /* Observable (only for export to userland) */ +#define EVL_T_HMSIG 0x00100000 /* Notify HM events via SIGDEBUG */ +#define EVL_T_HMOBS 0x00200000 /* Notify HM events via observable */ +#define EVL_T_WOSO 0x00400000 /* Schedule overrun */ + +/* Information flags (shared) */ + +#define EVL_T_TIMEO 0x00000001 /* Woken up due to a timeout condition */ +#define EVL_T_RMID 0x00000002 /* Pending on a removed resource */ +#define EVL_T_BREAK 0x00000004 /* Forcibly awaken from a wait state */ +#define EVL_T_KICKED 0x00000008 /* Forced out of OOB context */ +#define EVL_T_WCHAN 0x00000010 /* Need to requeue in wait channel */ +/* free: 0x00000020 */ +#define EVL_T_CANCELD 0x00000040 /* Cancellation request is pending */ +#define EVL_T_PIALERT 0x00000080 /* Priority inversion alert (HM notified) */ +#define EVL_T_SCHEDP 0x00000100 /* Schedparam propagation is pending */ +#define EVL_T_BCAST 0x00000200 /* Woken up upon resource broadcast */ +#define EVL_T_SIGNAL 0x00000400 /* Event monitor signaled */ +#define EVL_T_SXALERT 0x00000800 /* Stage exclusion alert (HM notified) */ +#define EVL_T_PTSIG 0x00001000 /* Ptrace signal is pending */ +#define EVL_T_PTSTOP 0x00002000 /* Ptrace stop is ongoing */ +#define EVL_T_PTJOIN 0x00004000 /* Ptracee should join ptsync barrier */ +#define EVL_T_NOMEM 0x00008000 /* No memory to complete the operation */ + +/* Local information flags (private to current thread) */ + +#define EVL_T_SYSRST 0x00000001 /* Thread awaiting syscall restart after signal */ +#define EVL_T_IGNOVR 0x00000002 /* Overrun detection temporarily disabled */ +#define EVL_T_INFAULT 0x00000004 /* In fault handling */ +#define EVL_T_NORST 0x00000008 /* Disable syscall restart */ + +/* + * Must follow strictly the declaration order of the state flags + * defined above. Status symbols are defined as follows: + * + * 'S' -> Forcibly suspended + * 'w'/'W' -> Blocked with/without timeout + * 'D' -> Delayed + * 'p' -> Periodic timeline + * 'R' -> Ready to run + * 'U' -> Dormant + * 'Z' -> Zombie + * 'X' -> Running in-band + * 'H' -> Halted + * 'b' -> Priority boost undergoing + * '#' -> Ptrace sync ongoing + * 'r' -> Undergoes round-robin + * 't' -> Warned on stage switch (EVL_T_WOSS) + * 'T' -> Stopped on ptrace event + * 'o' -> Observable + */ +#define EVL_THREAD_STATE_LABELS "SWDpRUZXHb#r...t..To.." + +/* Health monitoring diag codes (via observable or SIGDEBUG). */ +#define EVL_HMDIAG_SIGDEMOTE 1 +#define EVL_HMDIAG_SYSDEMOTE 2 +#define EVL_HMDIAG_EXDEMOTE 3 +#define EVL_HMDIAG_WATCHDOG 4 +#define EVL_HMDIAG_LKDEPEND 5 +#define EVL_HMDIAG_LKIMBALANCE 6 +#define EVL_HMDIAG_LKSLEEP 7 +#define EVL_HMDIAG_STAGEX 8 +#define EVL_HMDIAG_OVERRUN 9 + +struct evl_user_window { + __u32 state; + __u32 info; + __u32 pp_pending; +}; + +struct evl_thread_state { + struct evl_sched_attrs eattrs; + __u32 cpu; + __u32 state; + __u32 isw; + __u32 csw; + __u32 sc; + __u32 rwa; + __u64 xtime; +}; + +#define EVL_THREAD_IOCBASE 'T' + +#define EVL_THRIOC_SIGNAL _IOW(EVL_THREAD_IOCBASE, 0, __u32) +#define EVL_THRIOC_SET_SCHEDPARAM _IOW(EVL_THREAD_IOCBASE, 1, struct evl_sched_attrs) +#define EVL_THRIOC_GET_SCHEDPARAM _IOR(EVL_THREAD_IOCBASE, 2, struct evl_sched_attrs) +#define EVL_THRIOC_JOIN _IO(EVL_THREAD_IOCBASE, 3) +#define EVL_THRIOC_GET_STATE _IOR(EVL_THREAD_IOCBASE, 4, struct evl_thread_state) +#define EVL_THRIOC_SWITCH_OOB _IO(EVL_THREAD_IOCBASE, 5) +#define EVL_THRIOC_SWITCH_INBAND _IO(EVL_THREAD_IOCBASE, 6) +#define EVL_THRIOC_DETACH_SELF _IO(EVL_THREAD_IOCBASE, 7) +#define EVL_THRIOC_SET_MODE _IOWR(EVL_THREAD_IOCBASE, 8, __u32) +#define EVL_THRIOC_CLEAR_MODE _IOWR(EVL_THREAD_IOCBASE, 9, __u32) +#define EVL_THRIOC_UNBLOCK _IO(EVL_THREAD_IOCBASE, 10) +#define EVL_THRIOC_DEMOTE _IO(EVL_THREAD_IOCBASE, 11) +#define EVL_THRIOC_YIELD _IO(EVL_THREAD_IOCBASE, 12) + +#endif /* !_EVL_UAPI_THREAD_ABI_H */ diff --git a/include/uapi/evl/trace.h b/include/uapi/evl/trace.h new file mode 100644 index 000000000..b0e4e8c26 --- /dev/null +++ b/include/uapi/evl/trace.h @@ -0,0 +1,14 @@ +/* + * SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note + * + * Copyright (C) 2018 Philippe Gerum + */ + +#ifndef _EVL_UAPI_TRACE_H +#define _EVL_UAPI_TRACE_H + +#define EVL_TRACE_IOCBASE 'O' + +#define EVL_TRCIOC_SNAPSHOT _IO(EVL_TRACE_IOCBASE, 0) + +#endif /* !_EVL_UAPI_TRACE_H */ diff --git a/include/uapi/evl/types.h b/include/uapi/evl/types.h new file mode 100644 index 000000000..975b25db6 --- /dev/null +++ b/include/uapi/evl/types.h @@ -0,0 +1,57 @@ +/* + * SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note + * + * Derived from Xenomai Cobalt, https://xenomai.org/ + * Copyright (C) 2013, 2018 Philippe Gerum + */ + +#ifndef _EVL_UAPI_TYPES_H +#define _EVL_UAPI_TYPES_H + +#include + +typedef __u32 fundle_t; + +#define EVL_NO_HANDLE ((fundle_t)0x00000000) + +/* Reserved status bits */ +#define EVL_MUTEX_FLCLAIM ((fundle_t)0x80000000) /* Contended. */ +#define EVL_MUTEX_FLCEIL ((fundle_t)0x40000000) /* Ceiling active. */ +#define EVL_HANDLE_INDEX_MASK (EVL_MUTEX_FLCLAIM|EVL_MUTEX_FLCEIL) + +/* + * Strip all reserved bits from the handle, only retaining the fast + * index value. + */ +static inline fundle_t evl_get_index(fundle_t handle) +{ + return handle & ~EVL_HANDLE_INDEX_MASK; +} + +/* + * Y2038 safety. Match the kernel ABI definitions of __kernel_timespec + * and __kernel_itimerspec. + */ +typedef long long __evl_time64_t; + +struct __evl_timespec { + __evl_time64_t tv_sec; + long long tv_nsec; +}; + +struct __evl_itimerspec { + struct __evl_timespec it_interval; + struct __evl_timespec it_value; +}; + +union evl_value { + __s32 val; + __s64 lval; + void *ptr; +}; + +#define evl_intval(__val) ((union evl_value){ .lval = (__val) }) +#define evl_ptrval(__ptr) ((union evl_value){ .ptr = (__ptr) }) +#define evl_nil evl_intval(0) + +#endif /* !_EVL_UAPI_TYPES_H */ diff --git a/include/uapi/evl/xbuf-abi.h b/include/uapi/evl/xbuf-abi.h new file mode 100644 index 000000000..816496cf2 --- /dev/null +++ b/include/uapi/evl/xbuf-abi.h @@ -0,0 +1,19 @@ +/* + * SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note + * + * Copyright (C) 2018 Philippe Gerum + */ + +#ifndef _EVL_UAPI_XBUF_ABI_H +#define _EVL_UAPI_XBUF_ABI_H + +#include + +#define EVL_XBUF_DEV "xbuf" + +struct evl_xbuf_attrs { + __u32 i_bufsz; + __u32 o_bufsz; +}; + +#endif /* !_EVL_UAPI_XBUF_ABI_H */ diff --git a/include/uapi/linux/clocksource.h b/include/uapi/linux/clocksource.h new file mode 100644 index 000000000..966f92230 --- /dev/null +++ b/include/uapi/linux/clocksource.h @@ -0,0 +1,39 @@ +/* + * Definitions for user-mappable clock sources. + * + * Gilles Chanteperdrix + */ +#ifndef _UAPI_LINUX_CLOCKSOURCE_H +#define _UAPI_LINUX_CLOCKSOURCE_H + +enum clksrc_user_mmio_type { + CLKSRC_MMIO_L_UP, + CLKSRC_MMIO_L_DOWN, + CLKSRC_MMIO_W_UP, + CLKSRC_MMIO_W_DOWN, + CLKSRC_DMMIO_L_UP, + CLKSRC_DMMIO_W_UP, + + CLKSRC_MMIO_TYPE_NR, +}; + +struct clksrc_user_mmio_info { + enum clksrc_user_mmio_type type; + void *reg_lower; + unsigned int mask_lower; + unsigned int bits_lower; + void *reg_upper; + unsigned int mask_upper; +}; + +#define CLKSRC_USER_MMIO_MAX 16 + +#define CLKSRC_USER_MMIO_MAP _IOWR(0xC1, 0, struct clksrc_user_mmio_info) + +enum clocksource_vdso_type { + CLOCKSOURCE_VDSO_NONE = 0, + CLOCKSOURCE_VDSO_ARCHITECTED, + CLOCKSOURCE_VDSO_MMIO, /* <= Must be last. */ +}; + +#endif /* _UAPI_LINUX_CLOCKSOURCE_H */ diff --git a/include/vdso/datapage.h b/include/vdso/datapage.h index 73eb622e7..3432f9b8a 100644 --- a/include/vdso/datapage.h +++ b/include/vdso/datapage.h @@ -106,9 +106,34 @@ struct vdso_data { u32 hrtimer_res; u32 __unused; +#ifdef CONFIG_GENERIC_CLOCKSOURCE_VDSO + u32 cs_type_seq; + char cs_mmdev[16]; +#endif + struct arch_vdso_data arch_data; }; +#if defined(CONFIG_GENERIC_CLOCKSOURCE_VDSO) && !defined(ENABLE_COMPAT_VDSO) + +#include + +struct clksrc_info; + +typedef u64 vdso_read_cycles_t(const struct clksrc_info *info); + +struct clksrc_info { + vdso_read_cycles_t *read_cycles; + struct clksrc_user_mmio_info mmio; +}; + +struct vdso_priv { + u32 current_cs_type_seq; + struct clksrc_info clksrc_info[CLOCKSOURCE_VDSO_MMIO + CLKSRC_USER_MMIO_MAX]; +}; + +#endif /* !CONFIG_GENERIC_CLOCKSOURCE_VDSO */ + /* * We use the hidden visibility to prevent the compiler from generating a GOT * relocation. Not only is going through a GOT useless (the entry couldn't and diff --git a/init/Kconfig b/init/Kconfig index 60ed7713b..d7870cc17 100644 --- a/init/Kconfig +++ b/init/Kconfig @@ -1560,6 +1560,18 @@ config PRINTK very difficult to diagnose system problems, saying N here is strongly discouraged. +config RAW_PRINTK + bool "Enable support for raw printk" + default n + help + This option enables a printk variant called raw_printk() for + writing all output unmodified to a raw console channel + immediately, without any header or preparation whatsoever, + usable from any context. + + Unlike early_printk() console devices, raw_printk() devices + can live past the boot sequence. + config BUG bool "BUG() support" if EXPERT default y diff --git a/init/Makefile b/init/Makefile index cbac576c5..302798aa3 100644 --- a/init/Makefile +++ b/init/Makefile @@ -27,13 +27,14 @@ smp-flag-$(CONFIG_SMP) := SMP preempt-flag-$(CONFIG_PREEMPT_BUILD) := PREEMPT preempt-flag-$(CONFIG_PREEMPT_DYNAMIC) := PREEMPT_DYNAMIC preempt-flag-$(CONFIG_PREEMPT_RT) := PREEMPT_RT +dovetail-flag-$(CONFIG_IRQ_PIPELINE) := $(or $(CONFIG_DOVETAIL_GUEST),IRQ_PIPELINE) build-version = $(or $(KBUILD_BUILD_VERSION), $(build-version-auto)) build-timestamp = $(or $(KBUILD_BUILD_TIMESTAMP), $(build-timestamp-auto)) # Maximum length of UTS_VERSION is 64 chars filechk_uts_version = \ - utsver=$$(echo '$(pound)'"$(build-version)" $(smp-flag-y) $(preempt-flag-y) "$(build-timestamp)" | cut -b -64); \ + utsver=$$(echo '$(pound)'"$(build-version)" $(smp-flag-y) $(preempt-flag-y) $(dovetail-flag-y) "$(build-timestamp)" | cut -b -64); \ echo '$(pound)'define UTS_VERSION \""$${utsver}"\" # diff --git a/init/main.c b/init/main.c index c787e94cc..7815a5cc8 100644 --- a/init/main.c +++ b/init/main.c @@ -55,6 +55,7 @@ #include #include #include +#include #include #include #include @@ -878,6 +879,7 @@ void start_kernel(void) char *command_line; char *after_dashes; + stall_inband_nocheck(); set_task_stack_end_magic(&init_task); smp_setup_processor_id(); debug_objects_early_init(); @@ -885,7 +887,7 @@ void start_kernel(void) cgroup_init_early(); - local_irq_disable(); + local_irq_disable_full(); early_boot_irqs_disabled = true; /* @@ -930,6 +932,7 @@ void start_kernel(void) setup_log_buf(0); vfs_caches_init_early(); sort_main_extable(); + irq_pipeline_init_early(); trap_init(); mm_core_init(); poking_init(); @@ -976,6 +979,7 @@ void start_kernel(void) /* init some links before init_ISA_irqs() */ early_irq_init(); init_IRQ(); + irq_pipeline_init(); tick_init(); rcu_init_nohz(); init_timers(); @@ -998,7 +1002,7 @@ void start_kernel(void) WARN(!irqs_disabled(), "Interrupts were enabled early\n"); early_boot_irqs_disabled = false; - local_irq_enable(); + local_irq_enable_full(); kmem_cache_init_late(); diff --git a/kernel/Kconfig.dovetail b/kernel/Kconfig.dovetail new file mode 100644 index 000000000..29c46e06e --- /dev/null +++ b/kernel/Kconfig.dovetail @@ -0,0 +1,30 @@ + +# DOVETAIL dual-kernel interface +config HAVE_DOVETAIL + bool + +# Selecting ARCH_WANT_IRQS_OFF_ACTIVATE_MM in this generic Kconfig +# portion is ugly, but the whole ARCH_WANT_IRQS_OFF_ACTIVATE_MM logic +# is a temporary kludge which is meant to disappear anyway. See +# the related comments in exec_mmap() for details. +config DOVETAIL + bool "Dovetail interface" + depends on HAVE_DOVETAIL + select IRQ_PIPELINE + select ARCH_WANT_IRQS_OFF_ACTIVATE_MM + default n + help + Activate this option if you want to enable the interface for + running a high-priority software core on the out-of-band + pipeline stage (aka "dual kernel" configuration). + +config DOVETAIL_LEGACY_SYSCALL_RANGE + depends on DOVETAIL + def_bool y + +# The nickname of the guest companion core using Dovetail to attach to +# the main kernel. Advertise mere dovetailing only if none. +config DOVETAIL_GUEST + string + depends on DOVETAIL + default "$(shell,$(srctree)/scripts/dovetail-guest.sh 2>/dev/null || echo DOVETAIL)" diff --git a/kernel/Kconfig.evl b/kernel/Kconfig.evl new file mode 100644 index 000000000..668e5d56f --- /dev/null +++ b/kernel/Kconfig.evl @@ -0,0 +1,32 @@ + +# EVL real-time core +config HAVE_ARCH_EVL + bool + +menuconfig EVL + bool "EVL real-time core" + depends on HAVE_ARCH_EVL + select DOVETAIL + select DEVTMPFS + help + + The EVL core is a real-time component of the Linux kernel, + which delivers very short and bounded response time to + interrupt and task events. EVL runs asynchronously to the + common kernel services, on the high-priority, out-of-band + stage managed by the Dovetail layer. + +if EVL + +source "kernel/evl/Kconfig" + +if WARN_CPUFREQ_GOVERNOR +comment "WARNING! CPU_FREQ governors other than 'performance'" +comment "or 'powersave' may significantly increase latency" +comment "on this platform during the frequency transitions." +endif + +endif + +config WARN_CPUFREQ_GOVERNOR + def_bool n diff --git a/kernel/Makefile b/kernel/Makefile index ce105a555..6112c83f8 100644 --- a/kernel/Makefile +++ b/kernel/Makefile @@ -107,6 +107,8 @@ obj-$(CONFIG_RING_BUFFER) += trace/ obj-$(CONFIG_TRACEPOINTS) += trace/ obj-$(CONFIG_RETHOOK) += trace/ obj-$(CONFIG_IRQ_WORK) += irq_work.o +obj-$(CONFIG_DOVETAIL) += dovetail.o +obj-$(CONFIG_EVL) += evl/ obj-$(CONFIG_CPU_PM) += cpu_pm.o obj-$(CONFIG_BPF) += bpf/ obj-$(CONFIG_KCSAN) += kcsan/ diff --git a/kernel/bpf/Kconfig b/kernel/bpf/Kconfig index 6a906ff93..1fa27929b 100644 --- a/kernel/bpf/Kconfig +++ b/kernel/bpf/Kconfig @@ -100,4 +100,7 @@ config BPF_LSM If you are unsure how to answer this question, answer N. +config BPF_OOB + bool + endmenu # "BPF subsystem" diff --git a/kernel/context_tracking.c b/kernel/context_tracking.c index 6ef0b35fc..b37462986 100644 --- a/kernel/context_tracking.c +++ b/kernel/context_tracking.c @@ -239,7 +239,7 @@ void noinstr ct_nmi_exit(void) ct_kernel_exit_state(RCU_DYNTICKS_IDX); // ... but is no longer watching here. - if (!in_nmi()) + if (!in_nonmaskable()) rcu_dynticks_task_enter(); } @@ -273,7 +273,7 @@ void noinstr ct_nmi_enter(void) */ if (rcu_dynticks_curr_cpu_in_eqs()) { - if (!in_nmi()) + if (!in_nonmaskable()) rcu_dynticks_task_exit(); // RCU is not watching here ... @@ -287,7 +287,7 @@ void noinstr ct_nmi_enter(void) instrument_atomic_write(&ct->state, sizeof(ct->state)); incby = 1; - } else if (!in_nmi()) { + } else if (!in_nonmaskable()) { instrumentation_begin(); rcu_irq_enter_check_tick(); } else { diff --git a/kernel/debug/debug_core.c b/kernel/debug/debug_core.c index ce1bb2301..12d6dfb34 100644 --- a/kernel/debug/debug_core.c +++ b/kernel/debug/debug_core.c @@ -107,8 +107,8 @@ static struct kgdb_bkpt kgdb_break[KGDB_MAX_BREAKPOINTS] = { */ atomic_t kgdb_active = ATOMIC_INIT(-1); EXPORT_SYMBOL_GPL(kgdb_active); -static DEFINE_RAW_SPINLOCK(dbg_master_lock); -static DEFINE_RAW_SPINLOCK(dbg_slave_lock); +static DEFINE_HARD_SPINLOCK(dbg_master_lock); +static DEFINE_HARD_SPINLOCK(dbg_slave_lock); /* * We use NR_CPUs not PERCPU, in case kgdb is used to debug early @@ -596,7 +596,7 @@ static int kgdb_cpu_enter(struct kgdb_state *ks, struct pt_regs *regs, * Interrupts will be restored by the 'trap return' code, except when * single stepping. */ - local_irq_save(flags); + flags = hard_local_irq_save(); cpu = ks->cpu; kgdb_info[cpu].debuggerinfo = regs; @@ -650,7 +650,7 @@ static int kgdb_cpu_enter(struct kgdb_state *ks, struct pt_regs *regs, smp_mb__before_atomic(); atomic_dec(&slaves_in_kgdb); dbg_touch_watchdogs(); - local_irq_restore(flags); + hard_local_irq_restore(flags); rcu_read_unlock(); return 0; } @@ -669,7 +669,7 @@ static int kgdb_cpu_enter(struct kgdb_state *ks, struct pt_regs *regs, atomic_set(&kgdb_active, -1); raw_spin_unlock(&dbg_master_lock); dbg_touch_watchdogs(); - local_irq_restore(flags); + hard_local_irq_restore(flags); rcu_read_unlock(); goto acquirelock; @@ -705,8 +705,11 @@ static int kgdb_cpu_enter(struct kgdb_state *ks, struct pt_regs *regs, atomic_set(ks->send_ready, 1); /* Signal the other CPUs to enter kgdb_wait() */ - else if ((!kgdb_single_step) && kgdb_do_roundup) + else if ((!kgdb_single_step) && kgdb_do_roundup && running_inband()) { + hard_cond_local_irq_enable(); kgdb_roundup_cpus(); + hard_cond_local_irq_disable(); + } #endif /* @@ -818,7 +821,7 @@ static int kgdb_cpu_enter(struct kgdb_state *ks, struct pt_regs *regs, atomic_set(&kgdb_active, -1); raw_spin_unlock(&dbg_master_lock); dbg_touch_watchdogs(); - local_irq_restore(flags); + hard_local_irq_restore(flags); rcu_read_unlock(); return kgdb_info[cpu].ret_state; @@ -941,7 +944,7 @@ static void kgdb_console_write(struct console *co, const char *s, if (!kgdb_connected || atomic_read(&kgdb_active) != -1 || dbg_kdb_mode) return; - local_irq_save(flags); + flags = hard_local_irq_save(); gdbstub_msg_write(s, count); local_irq_restore(flags); } diff --git a/kernel/dovetail.c b/kernel/dovetail.c new file mode 100644 index 000000000..bcd49183f --- /dev/null +++ b/kernel/dovetail.c @@ -0,0 +1,463 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2016 Philippe Gerum . + */ +#include +#include +#include +#include +#include +#include +#include +#include + +static bool dovetail_enabled; + +void __weak arch_inband_task_init(struct task_struct *p) +{ +} + +void inband_task_init(struct task_struct *p) +{ + struct thread_info *ti = task_thread_info(p); + + clear_ti_local_flags(ti, _TLF_DOVETAIL|_TLF_OOB|_TLF_OFFSTAGE); + arch_inband_task_init(p); +} + +void dovetail_init_altsched(struct dovetail_altsched_context *p) +{ + struct task_struct *tsk = current; + struct mm_struct *mm = tsk->mm; + + check_inband_stage(); + p->task = tsk; + p->active_mm = mm; + p->borrowed_mm = false; + + /* + * Make sure the current process will not share any private + * page with its child upon fork(), sparing it the random + * latency induced by COW. MMF_DOVETAILED is never cleared + * once set. We serialize with dup_mmap() which holds the mm + * write lock. CAUTION: the boot context has no mm and does + * not bear the PF_KTHREAD bit either. + */ + if (mm && !(tsk->flags & PF_KTHREAD) && + !test_bit(MMF_DOVETAILED, &mm->flags)) { + mmap_write_lock(mm); + __set_bit(MMF_DOVETAILED, &mm->flags); + mmap_write_unlock(mm); + } +} +EXPORT_SYMBOL_GPL(dovetail_init_altsched); + +void dovetail_start_altsched(void) +{ + check_inband_stage(); + set_thread_local_flags(_TLF_DOVETAIL); +} +EXPORT_SYMBOL_GPL(dovetail_start_altsched); + +void dovetail_stop_altsched(void) +{ + clear_thread_local_flags(_TLF_DOVETAIL); + clear_thread_flag(TIF_MAYDAY); +} +EXPORT_SYMBOL_GPL(dovetail_stop_altsched); + +int __weak handle_oob_syscall(struct pt_regs *regs) +{ + return 0; +} + +int __weak handle_pipelined_syscall(struct irq_stage *stage, + struct pt_regs *regs) +{ + return 0; /* i.e. propagate to in-band handler. */ +} + +void __weak handle_oob_mayday(struct pt_regs *regs) +{ +} + +static inline +void call_mayday(struct thread_info *ti, struct pt_regs *regs) +{ + clear_ti_thread_flag(ti, TIF_MAYDAY); + handle_oob_mayday(regs); +} + +void dovetail_call_mayday(struct pt_regs *regs) +{ + struct thread_info *ti = current_thread_info(); + unsigned long flags; + + flags = hard_local_irq_save(); + call_mayday(ti, regs); + hard_local_irq_restore(flags); +} + +void inband_retuser_notify(void) +{ + clear_thread_flag(TIF_RETUSER); + inband_event_notify(INBAND_TASK_RETUSER, current); + /* CAUTION: we might have switched out-of-band here. */ +} + +static bool __in_oob_syscall(struct task_struct *tsk, + unsigned int nr, struct pt_regs *regs) +{ + /* + * Given a syscall number and a register file encoding a + * system call issued by a task, check whether the companion + * core might be interested in the request. If the old syscall + * form is handled, pass the syscall to the core if + * __OOB_SYSCALL_BIT is set in @nr. Otherwise, only check + * whether an oob syscall is folded into a prctl() request as + * a PR_OOB_SYSCALL command (new/current call form). + */ + if (IS_ENABLED(CONFIG_DOVETAIL_LEGACY_SYSCALL_RANGE)) { + if (nr != -1 && nr & __OOB_SYSCALL_BIT) + return true; + } + + return arch_dovetail_is_syscall(tsk, nr, regs); +} + +/* Whether an oob syscall is to be handled for the current task. */ +bool in_oob_syscall(struct pt_regs *regs) +{ + struct task_struct *tsk = current; + unsigned int nr = syscall_get_nr(tsk, regs); + + return __in_oob_syscall(tsk, nr, regs); +} + +int __pipeline_syscall(struct pt_regs *regs) +{ + struct thread_info *ti = current_thread_info(); + struct irq_stage *caller_stage, *target_stage; + struct irq_stage_data *p, *this_context; + unsigned long flags; + int ret = 0; + + /* + * We should definitely not pipeline a syscall through the + * slow path with IRQs off. + */ + WARN_ON_ONCE(dovetail_debug() && hard_irqs_disabled()); + + if (!dovetail_enabled) + return 0; + + flags = hard_local_irq_save(); + caller_stage = current_irq_stage; + this_context = current_irq_staged; + target_stage = &oob_stage; +next: + p = this_staged(target_stage); + set_current_irq_staged(p); + hard_local_irq_restore(flags); + ret = handle_pipelined_syscall(caller_stage, regs); + flags = hard_local_irq_save(); + /* + * Be careful about stage switching _and_ CPU migration that + * might have happened as a result of handing over the syscall + * to the out-of-band handler. + * + * - if a stage migration is detected, fetch the new + * per-stage, per-CPU context pointer. + * + * - if no stage migration happened, switch back to the + * initial call stage, on a possibly different CPU though. + */ + if (current_irq_stage != target_stage) { + this_context = current_irq_staged; + } else { + p = this_staged(this_context->stage); + set_current_irq_staged(p); + } + + if (this_context->stage == &inband_stage) { + if (target_stage != &inband_stage && ret == 0) { + target_stage = &inband_stage; + goto next; + } + p = this_inband_staged(); + if (stage_irqs_pending(p)) + sync_current_irq_stage(); + } else { + if (test_ti_thread_flag(ti, TIF_MAYDAY)) + call_mayday(ti, regs); + } + + hard_local_irq_restore(flags); + + return ret; +} + +int pipeline_syscall(unsigned int nr, struct pt_regs *regs) +{ + struct thread_info *ti = current_thread_info(); + unsigned long local_flags = READ_ONCE(ti_local_flags(ti)); + struct task_struct *tsk = current; + int ret; + + WARN_ON_ONCE(dovetail_debug() && hard_irqs_disabled()); + + /* + * If the syscall signature belongs to the out-of-band syscall + * set and we are running out-of-band, pass the request + * directly to the companion core by calling the oob syscall + * handler. + * + * Otherwise, if this is an out-of-band syscall or alternate + * scheduling is enabled for the caller, propagate the syscall + * through the pipeline stages, so that: + * + * - the core can manipulate the current execution stage for + * handling the request, which includes switching the current + * thread back to the in-band context if the syscall is a + * native one, or promoting it to the oob stage if handling an + * oob syscall requires this. + * + * - the core can receive the initial oob syscall a thread + * might have to emit for enabling dovetailing from the + * in-band stage. + * + * Native syscalls from common (non-dovetailed) threads are + * not subject to pipelining, but flow down to the in-band + * system call handler directly. + * + * Sanity check: we bark on returning from a syscall on a + * stalled in-band stage, which combined with running with + * hard irqs on might cause interrupts to linger in the log + * after exiting to user. + */ + + if ((local_flags & _TLF_OOB) && __in_oob_syscall(tsk, nr, regs)) { + ret = handle_oob_syscall(regs); + if (!IS_ENABLED(CONFIG_DOVETAIL_LEGACY_SYSCALL_RANGE)) + WARN_ON_ONCE(dovetail_debug() && !ret); + local_flags = READ_ONCE(ti_local_flags(ti)); + if (likely(ret)) { + if (local_flags & _TLF_OOB) { + if (test_ti_thread_flag(ti, TIF_MAYDAY)) + dovetail_call_mayday(regs); + return 1; /* don't pass down, no tail work. */ + } else { + WARN_ON_ONCE(dovetail_debug() && irqs_disabled()); + return -1; /* don't pass down, do tail work. */ + } + } + } + + if ((local_flags & _TLF_DOVETAIL) || __in_oob_syscall(tsk, nr, regs)) { + ret = __pipeline_syscall(regs); + local_flags = READ_ONCE(ti_local_flags(ti)); + if (local_flags & _TLF_OOB) + return 1; /* don't pass down, no tail work. */ + if (ret) { + WARN_ON_ONCE(dovetail_debug() && irqs_disabled()); + return -1; /* don't pass down, do tail work. */ + } + } + + return 0; /* pass syscall down to the in-band dispatcher. */ +} + +void __weak handle_oob_trap_entry(unsigned int trapnr, struct pt_regs *regs) +{ +} + +noinstr void __oob_trap_notify(unsigned int exception, + struct pt_regs *regs) +{ + unsigned long flags; + + /* + * We send a notification about exceptions raised over a + * registered oob stage only. The trap_entry handler expects + * hard irqs off on entry. It may demote the current context + * to the in-band stage, may return with hard irqs on. + */ + if (dovetail_enabled) { + set_thread_local_flags(_TLF_OOBTRAP); + flags = hard_local_irq_save(); + instrumentation_begin(); + handle_oob_trap_entry(exception, regs); + instrumentation_end(); + hard_local_irq_restore(flags); + } +} + +void __weak handle_oob_trap_exit(unsigned int trapnr, struct pt_regs *regs) +{ +} + +noinstr void __oob_trap_unwind(unsigned int exception, struct pt_regs *regs) +{ + /* + * The trap_exit handler runs only if trap_entry was called + * for the same trap occurrence. It expects hard irqs off on + * entry, may switch the current context back to the oob + * stage. Must return with hard irqs off. + */ + hard_local_irq_disable(); + clear_thread_local_flags(_TLF_OOBTRAP); + instrumentation_begin(); + handle_oob_trap_exit(exception, regs); + instrumentation_end(); +} + +void __weak handle_inband_event(enum inband_event_type event, void *data) +{ +} + +void inband_event_notify(enum inband_event_type event, void *data) +{ + check_inband_stage(); + + if (dovetail_enabled) + handle_inband_event(event, data); +} + +void __weak resume_oob_task(struct task_struct *p) +{ +} + +static void finalize_oob_transition(void) /* hard IRQs off */ +{ + struct irq_pipeline_data *pd; + struct irq_stage_data *p; + struct task_struct *t; + + pd = raw_cpu_ptr(&irq_pipeline); + t = pd->task_inflight; + if (t == NULL) + return; + + /* + * @t which is in flight to the oob stage might have received + * a signal while waiting in off-stage state to be actually + * scheduled out. We can't act upon that signal safely from + * here, we simply let the task complete the migration process + * to the oob stage. The pending signal will be handled when + * the task eventually exits the out-of-band context by the + * converse migration. + */ + pd->task_inflight = NULL; + + /* + * The transition handler in the companion core assumes the + * oob stage is stalled, fix this up. + */ + stall_oob(); + resume_oob_task(t); + unstall_oob(); + p = this_oob_staged(); + if (stage_irqs_pending(p)) + /* Current stage (in-band) != p->stage (oob). */ + sync_irq_stage(p->stage); +} + +void oob_trampoline(void) +{ + unsigned long flags; + + check_inband_stage(); + flags = hard_local_irq_save(); + finalize_oob_transition(); + hard_local_irq_restore(flags); +} + +bool inband_switch_tail(void) +{ + bool oob; + + check_hard_irqs_disabled(); + + /* + * We may run this code either over the inband or oob + * contexts. If inband, we may have a thread blocked in + * dovetail_leave_inband(), waiting for the companion core to + * schedule it back in over the oob context, in which case + * finalize_oob_transition() should take care of it. If oob, + * the core just switched us back, and we may update the + * context markers before returning to context_switch(). + * + * Since the preemption count does not reflect the active + * stage yet upon inband -> oob transition, we figure out + * which one we are on by testing _TLF_OFFSTAGE. Having this + * bit set when running the inband switch tail code means that + * we are completing such transition for the current task, + * switched in by dovetail_context_switch() over the oob + * stage. If so, update the context markers appropriately. + */ + oob = test_thread_local_flags(_TLF_OFFSTAGE); + if (oob) { + /* + * The companion core assumes a stalled stage on exit + * from dovetail_leave_inband(). + */ + stall_oob(); + set_thread_local_flags(_TLF_OOB); + if (!IS_ENABLED(CONFIG_HAVE_PERCPU_PREEMPT_COUNT)) { + WARN_ON_ONCE(dovetail_debug() && + (preempt_count() & STAGE_MASK)); + preempt_count_add(STAGE_OFFSET); + } + } else { + finalize_oob_transition(); + hard_local_irq_enable(); + } + + return oob; +} + +void __weak inband_clock_was_set(void) +{ +} + +void __weak install_inband_fd(unsigned int fd, struct file *file, + struct files_struct *files) +{ +} + +void __weak uninstall_inband_fd(unsigned int fd, struct file *file, + struct files_struct *files) +{ +} + +void __weak replace_inband_fd(unsigned int fd, struct file *file, + struct files_struct *files) +{ +} + +int dovetail_start(void) +{ + check_inband_stage(); + + if (dovetail_enabled) + return -EBUSY; + + if (!oob_stage_present()) + return -EAGAIN; + + dovetail_enabled = true; + smp_wmb(); + + return 0; +} +EXPORT_SYMBOL_GPL(dovetail_start); + +void dovetail_stop(void) +{ + check_inband_stage(); + + dovetail_enabled = false; + smp_wmb(); +} +EXPORT_SYMBOL_GPL(dovetail_stop); diff --git a/kernel/entry/common.c b/kernel/entry/common.c index 5ff4f1cd3..7067dfef9 100644 --- a/kernel/entry/common.c +++ b/kernel/entry/common.c @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -91,10 +92,45 @@ static long syscall_trace_enter(struct pt_regs *regs, long syscall, return ret ? : syscall; } +static __always_inline void +syscall_enter_from_user_enable_irqs(void) +{ + if (running_inband()) { + /* + * If pipelining interrupts, prepare for emulating a + * stall -> unstall transition (we are currently + * unstalled), fixing up the IRQ trace state in order + * to keep lockdep happy (and silent). + */ + stall_inband_nocheck(); + hard_cond_local_irq_enable(); + local_irq_enable(); + } else { + /* + * We are running on the out-of-band stage, don't mess + * with the in-band interrupt state. This is none of + * our business. We may manipulate the hardware state + * only. + */ + hard_local_irq_enable(); + } +} + static __always_inline long __syscall_enter_from_user_work(struct pt_regs *regs, long syscall) { unsigned long work = READ_ONCE(current_thread_info()->syscall_work); + int ret; + + /* + * Pipeline the syscall to the companion core if the current + * task wants this. Compiled out if not dovetailing. + */ + ret = pipeline_syscall(syscall, regs); + if (ret > 0) /* out-of-band, bail out. */ + return EXIT_SYSCALL_OOB; + if (ret < 0) /* in-band, tail work only. */ + return EXIT_SYSCALL_TAIL; if (work & SYSCALL_WORK_ENTER) syscall = syscall_trace_enter(regs, syscall, work); @@ -114,7 +150,7 @@ noinstr long syscall_enter_from_user_mode(struct pt_regs *regs, long syscall) __enter_from_user_mode(regs); instrumentation_begin(); - local_irq_enable(); + syscall_enter_from_user_enable_irqs(); ret = __syscall_enter_from_user_work(regs, syscall); instrumentation_end(); @@ -125,7 +161,7 @@ noinstr void syscall_enter_from_user_mode_prepare(struct pt_regs *regs) { __enter_from_user_mode(regs); instrumentation_begin(); - local_irq_enable(); + syscall_enter_from_user_enable_irqs(); instrumentation_end(); } @@ -140,6 +176,8 @@ static __always_inline void __exit_to_user_mode(void) user_enter_irqoff(); arch_exit_to_user_mode(); lockdep_hardirqs_on(CALLER_ADDR0); + if (running_inband()) + unstall_inband(); } void noinstr exit_to_user_mode(void) @@ -161,6 +199,12 @@ static unsigned long exit_to_user_mode_loop(struct pt_regs *regs, local_irq_enable_exit_to_user(ti_work); + /* + * Check that local_irq_enable_exit_to_user() does the + * right thing when pipelining. + */ + WARN_ON_ONCE(irq_pipeline_debug() && hard_irqs_disabled()); + if (ti_work & _TIF_NEED_RESCHED) schedule(); @@ -189,6 +233,7 @@ static unsigned long exit_to_user_mode_loop(struct pt_regs *regs, /* Check if any of the above work has queued a deferred wakeup */ tick_nohz_user_enter_prepare(); + WARN_ON_ONCE(irq_pipeline_debug() && !hard_irqs_disabled()); ti_work = read_thread_flags(); } @@ -196,11 +241,28 @@ static unsigned long exit_to_user_mode_loop(struct pt_regs *regs, return ti_work; } +static inline bool do_retuser(unsigned long ti_work) +{ + if (dovetailing() && (ti_work & _TIF_RETUSER)) { + hard_local_irq_enable(); + inband_retuser_notify(); + hard_local_irq_disable(); + /* RETUSER might have switched oob */ + return running_inband(); + } + + return false; +} + static void exit_to_user_mode_prepare(struct pt_regs *regs) { unsigned long ti_work; + check_hard_irqs_disabled(); + lockdep_assert_irqs_disabled(); +again: + ti_work = read_thread_flags(); /* Flush pending rcuog wakeup before the last need_resched() check */ tick_nohz_user_enter_prepare(); @@ -211,6 +273,10 @@ static void exit_to_user_mode_prepare(struct pt_regs *regs) arch_exit_to_user_mode_prepare(regs, ti_work); + /* Dovetail: Fire pending RETUSER request. */ + if (do_retuser(ti_work)) + goto again; + /* Ensure that kernel state is sane for a return to userspace */ kmap_assert_nomap(); lockdep_assert_irqs_disabled(); @@ -257,6 +323,23 @@ static void syscall_exit_work(struct pt_regs *regs, unsigned long work) ptrace_report_syscall_exit(regs, step); } +static inline bool syscall_has_exit_work(struct pt_regs *regs, + unsigned long work) +{ + /* + * Dovetail: if this does not look like an in-band syscall, it + * has to belong to the companion core. Skip the work for + * those syscalls. + */ + if (unlikely(work & SYSCALL_WORK_EXIT)) { + if (!irqs_pipelined()) + return true; + return !in_oob_syscall(regs); + } + + return false; +} + /* * Syscall specific exit to user mode preparation. Runs with interrupts * enabled. @@ -270,7 +353,7 @@ static void syscall_exit_to_user_mode_prepare(struct pt_regs *regs) if (IS_ENABLED(CONFIG_PROVE_LOCKING)) { if (WARN(irqs_disabled(), "syscall %lu left IRQs disabled", nr)) - local_irq_enable(); + local_irq_enable_full(); } rseq_syscall(regs); @@ -280,7 +363,7 @@ static void syscall_exit_to_user_mode_prepare(struct pt_regs *regs) * enabled, we want to run them exactly once per syscall exit with * interrupts enabled. */ - if (unlikely(work & SYSCALL_WORK_EXIT)) + if (syscall_has_exit_work(regs, work)) syscall_exit_work(regs, work); } @@ -306,6 +389,8 @@ __visible noinstr void syscall_exit_to_user_mode(struct pt_regs *regs) noinstr void irqentry_enter_from_user_mode(struct pt_regs *regs) { + WARN_ON_ONCE(irq_pipeline_debug() && irqs_disabled()); + stall_inband_nocheck(); __enter_from_user_mode(regs); } @@ -321,13 +406,37 @@ noinstr irqentry_state_t irqentry_enter(struct pt_regs *regs) { irqentry_state_t ret = { .exit_rcu = false, +#ifdef CONFIG_IRQ_PIPELINE + .stage_info = IRQENTRY_INBAND_STALLED, +#endif }; +#ifdef CONFIG_IRQ_PIPELINE + if (running_oob()) { + WARN_ON_ONCE(irq_pipeline_debug() && oob_irqs_disabled()); + ret.stage_info = IRQENTRY_OOB; + return ret; + } +#endif + if (user_mode(regs)) { +#ifdef CONFIG_IRQ_PIPELINE + ret.stage_info = IRQENTRY_INBAND_UNSTALLED; +#endif irqentry_enter_from_user_mode(regs); return ret; } +#ifdef CONFIG_IRQ_PIPELINE + /* + * IRQ pipeline: If we trapped from kernel space, the virtual + * state may or may not match the hardware state. Since hard + * irqs are off on entry, we have to stall the in-band stage. + */ + if (!test_and_stall_inband_nocheck()) + ret.stage_info = IRQENTRY_INBAND_UNSTALLED; +#endif + /* * If this entry hit the idle task invoke ct_irq_enter() whether * RCU is watching or not. @@ -409,14 +518,91 @@ void dynamic_irqentry_exit_cond_resched(void) #endif #endif +#ifdef CONFIG_IRQ_PIPELINE + +static inline +bool irqexit_may_preempt_schedule(irqentry_state_t state, + struct pt_regs *regs) +{ + return state.stage_info == IRQENTRY_INBAND_UNSTALLED; +} + +#else + +static inline +bool irqexit_may_preempt_schedule(irqentry_state_t state, + struct pt_regs *regs) +{ + return !regs_irqs_disabled(regs); +} + +#endif + +#ifdef CONFIG_IRQ_PIPELINE + +static bool irqentry_syncstage(irqentry_state_t state) /* hard irqs off */ +{ + /* + * If pipelining interrupts, enable in-band IRQs then + * synchronize the interrupt log on exit if: + * + * - irqentry_enter() stalled the stage in order to mirror the + * hardware state. + * + * - we where coming from oob, thus went through a stage migration + * that was caused by taking a CPU exception, e.g., a fault. + * + * We run before preempt_schedule_irq() may be called later on + * by preemptible kernels, so that any rescheduling request + * triggered by in-band IRQ handlers is considered. + */ + if (state.stage_info == IRQENTRY_INBAND_UNSTALLED || + state.stage_info == IRQENTRY_OOB) { + unstall_inband_nocheck(); + synchronize_pipeline_on_irq(); + stall_inband_nocheck(); + return true; + } + + return false; +} + +static void irqentry_unstall(void) +{ + unstall_inband_nocheck(); +} + +#else + +static bool irqentry_syncstage(irqentry_state_t state) +{ + return false; +} + +static void irqentry_unstall(void) +{ +} + +#endif + noinstr void irqentry_exit(struct pt_regs *regs, irqentry_state_t state) { + bool synchronized = false; + + if (running_oob()) + return; + lockdep_assert_irqs_disabled(); /* Check whether this returns to user mode */ if (user_mode(regs)) { irqentry_exit_to_user_mode(regs); - } else if (!regs_irqs_disabled(regs)) { + return; + } + + synchronized = irqentry_syncstage(state); + + if (irqexit_may_preempt_schedule(state, regs)) { /* * If RCU was not watching on entry this needs to be done * carefully and needs the same ordering of lockdep/tracing @@ -430,7 +616,7 @@ noinstr void irqentry_exit(struct pt_regs *regs, irqentry_state_t state) instrumentation_end(); ct_irq_exit(); lockdep_hardirqs_on(CALLER_ADDR0); - return; + goto out; } instrumentation_begin(); @@ -448,6 +634,12 @@ noinstr void irqentry_exit(struct pt_regs *regs, irqentry_state_t state) if (state.exit_rcu) ct_irq_exit(); } + +out: + if (synchronized) + irqentry_unstall(); + + return; } irqentry_state_t noinstr irqentry_nmi_enter(struct pt_regs *regs) diff --git a/kernel/evl/.gitignore b/kernel/evl/.gitignore new file mode 100755 index 000000000..beea4d8a9 --- /dev/null +++ b/kernel/evl/.gitignore @@ -0,0 +1 @@ +syscall_entries.h diff --git a/kernel/evl/Kconfig b/kernel/evl/Kconfig new file mode 100644 index 000000000..83e5c97c2 --- /dev/null +++ b/kernel/evl/Kconfig @@ -0,0 +1,302 @@ + +config EVL_SCHED_QUOTA + bool "Enable quota-based scheduling" + default n + help + This option enables the SCHED_QUOTA scheduling policy in the + EVL core. + + This policy enforces a limitation on the CPU consumption of + threads over a globally defined period, known as the quota + interval. This is done by pooling threads with common + requirements in groups, and giving each group a share of the + global period. + + If in doubt, say N. + +config EVL_SCHED_TP + bool "Enable temporal partitioning policy" + default n + help + This option enables the SCHED_TP scheduling policy in the + EVL core. + + This policy runs threads which execution is confined to + dedicated time windows defined within a recurring time frame + or global period. The ARINC653 standard describes such + scheduling policy. + + If in doubt, say N. + +config EVL_SCHED_TP_NR_PART + int "Number of partitions" + default 4 + range 1 1024 + depends on EVL_SCHED_TP + help + + Define the maximum number of temporal partitions the TP + scheduler may have to handle. + +config EVL_TIMER_SCALABLE + bool + +config EVL_SCHED_SCALABLE + bool + +config EVL_HIGH_PERCPU_CONCURRENCY + bool "Optimize for intra-core concurrency" + select EVL_TIMER_SCALABLE + select EVL_SCHED_SCALABLE + default n + help + + This option optimizes the implementation for applications with + many real-time threads running concurrently on any given CPU + core (typically when eight or more threads may be sharing a + single CPU core). Currently, this option controls the + following aspects of the implementation: + + - when enabled, a per-CPU multi-level priority queue is used + for ordering threads, which operates in constant-time + regardless of the number of concurrently runnable threads on + a CPU (which is normally significantly lower than the total + number of threads existing in the system). Otherwise, a + basic per-CPU linear list is used, which performs better + latency-wise for a small number of runnable threads per CPU. + + - when enabled, a per-CPU red-black tree is used for indexing + the software timers, which has good scalability when many + timers may be outstanding concurrently on any given + CPU. Otherwise, a basic per-CPU linear list is used, which + performs better latency-wise for a small number of running + threads per CPU. + + In short, if your application system runs only a few EVL + threads per CPU core, then your best shot is at leaving this + option turned off, in order to minimize the cache footprint of + the queuing operations performed by the scheduler and timer + subsystems. Otherwise, you may benefit from turning it on in + order to have constant-time queuing operations for a large + number of runnable threads and outstanding timers. + +config EVL_RUNSTATS + bool "Collect runtime statistics" + default y + help + This option causes the EVL core to collect various + per-thread runtime statistics, which are accessible via + the /sys interface. + +config EVL_NET + bool "Out-of-band networking (EXPERIMENTAL)" + default n + select NET_OOB + select NET_SCHED + select BPF_OOB + select INET + select VLAN_8021Q + help + This option enables preliminary networking support for EVL. + + CAUTION! This is WIP, experimental code with limited support + at the moment, which is still subject to significant UAPI and + kernel API changes all over the map. + +menu "Fixed sizes and limits" + +config EVL_COREMEM_SIZE + int "Size of core memory heap (Kb)" + default 2048 + help + The core heap is used for various internal allocations by + the EVL core. The size is expressed in Kilobytes. + +config EVL_NR_THREADS + int "Maximum number of threads" + range 1 4096 + default 256 + help + + The maximum number of user-space threads attached to the + EVL core which can run concurrently in the system. + +config EVL_NR_MONITORS + int "Maximum number of monitors" + range 1 16384 + default 512 + help + + The monitor is the fundamental synchronization element + implemented by the EVL core, which can underpin any other + synchronization mechanism. This value gives the maximum number + of monitors which can be alive concurrently in the system. + +config EVL_NR_CLOCKS + int "Maximum number of clocks" + range 1 16384 + default 8 + help + + This value gives the maximum number of semaphores which can be + alive concurrently in the system for user-space applications. + +config EVL_NR_XBUFS + int "Maximum number of x-buffers" + range 1 16384 + default 128 + help + + This value gives the maximum number of x-buffers which can be + alive concurrently in the system for user-space applications. + +config EVL_NR_PROXIES + int "Maximum number of proxies" + range 1 16384 + default 64 + help + + This value gives the maximum number of file proxies which can + be alive concurrently in the system for user-space + applications. + +config EVL_NR_OBSERVABLES + int "Maximum number of observables" + range 1 16384 + default 64 + help + + This value gives the maximum number of observable elements + which can live concurrently in the EVL core. Observables enable + the observer design pattern, in which any number of observer + threads can be notified of updates to any number of observable + subjects, in a loosely coupled fashion. An EVL thread is in and + of itself an observable which can be monitored for events; + observables attached to threads are not accounted for in this + value. + +config EVL_NR_NETDEV + depends on EVL_NET + int "Maximum number of netdevices" + range 1 256 + default 8 + help + + This value gives the maximum number of network devices which + can deal with out-of-band traffic. + +endmenu + +menu "Pre-calibrated latency" + +config EVL_LATENCY_USER + int "User scheduling latency (ns)" + default 0 + help + The user scheduling latency is the time between the + termination of an interrupt handler and the execution of the + first instruction of the application thread this + handler resumes. A default value of 0 (recommended) will cause + a pre-calibrated value to be used. + + If the latmus driver is enabled, this value will be used as the + factory default when running "latmus --reset". + +config EVL_LATENCY_KERNEL + int "Intra-kernel scheduling latency (ns)" + default 0 + help + The intra-kernel scheduling latency is the time between the + termination of an interrupt handler and the execution of the + first instruction of the EVL kthread this handler + resumes. A default value of 0 (recommended) will cause a + pre-calibrated value to be used. + + Intra-kernel latency is usually significantly lower than user + scheduling latency on MMU-enabled platforms, due to CPU cache + latency. + + If the auto-tuner is enabled, this value will be used as the + factory default when running "autotune --reset". + +config EVL_LATENCY_IRQ + int "Interrupt latency (ns)" + default 0 + help + The interrupt latency is the time between the occurrence of an + IRQ and the first instruction of the interrupt handler which + will service it. A default value of 0 (recommended) will cause + a pre-calibrated value to be used. + + If the auto-tuner is enabled, this value will be used as the + factory default when running "autotune --reset". + +endmenu + +menuconfig EVL_DEBUG + bool "Debug support" + help + When enabled, various debugging features can be switched + on. They can help to find problems in applications, drivers, + and the EVL core. EVL_DEBUG by itself does not have + any impact on the generated code. + +if EVL_DEBUG + +config EVL_DEBUG_CORE + bool "Core runtime assertions" + select DOVETAIL_DEBUG + help + This option activates various assertions inside the EVL + core. This option has moderate overhead. + +config EVL_DEBUG_MEMORY + bool "Memory checks" + help + This option enables memory debug checks inside the EVL + core. This option may induce significant overhead with large + heaps. + +config EVL_DEBUG_WOLI + bool "Default enable locking consistency checks" + help + This option enables a set of consistency checks by default + for every new EVL thread for detecting wrong mutex-based + locking patterns (aka EVL_T_WOLI flag), which are otherwise + opted-in programmatically on a per-thread basis when this + option is off. This feature may induce overhead in some + cases, so you should enable it for debugging purposes only. + +config EVL_DEBUG_NET + bool "Network stack debugging" + depends on EVL_NET + select DOVETAIL_DEBUG + help + This option activates various assertions inside the EVL + network stack. This option has moderate overhead. + +config EVL_WATCHDOG + bool "Watchdog support" + default y + help + This option activates a watchdog aimed at detecting runaway + EVL threads. If enabled, the watchdog triggers after a given + period of uninterrupted out-of-band activity has elapsed + without in-band interaction in the meantime. + + In such an event, the thread preempted by the watchdog timer + is kicked out the out-of-band context, and immediately + receives a SIGDEBUG signal from the kernel. + + The timeout value of the watchdog can be set using the + EVL_WATCHDOG_TIMEOUT parameter. + +config EVL_WATCHDOG_TIMEOUT + depends on EVL_WATCHDOG + int "Watchdog timeout" + default 4 + range 1 60 + help + Watchdog timeout value (in seconds). + +endif # EVL_DEBUG diff --git a/kernel/evl/Makefile b/kernel/evl/Makefile new file mode 100644 index 000000000..013cd9547 --- /dev/null +++ b/kernel/evl/Makefile @@ -0,0 +1,26 @@ +obj-$(CONFIG_EVL) += evl.o sched/ lib/ net/ + +evl-y := \ + clock.o \ + control.o \ + factory.o \ + file.o \ + init.o \ + memory.o \ + monitor.o \ + mutex.o \ + observable.o \ + poll.o \ + proxy.o \ + random.o \ + sem.o \ + stax.o \ + syscall.o \ + thread.o \ + tick.o \ + timer.o \ + wait.o \ + work.o \ + xbuf.o + +evl-$(CONFIG_FTRACE) += trace.o diff --git a/kernel/evl/clock.c b/kernel/evl/clock.c new file mode 100644 index 000000000..3e8dd473f --- /dev/null +++ b/kernel/evl/clock.c @@ -0,0 +1,1137 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Derived from Xenomai Cobalt, https://xenomai.org/ + * Copyright (C) 2006, 2018 Philippe Gerum + * Copyright Gilles Chanteperdrix + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static const struct file_operations clock_fops; + +static LIST_HEAD(clock_list); + +static DEFINE_MUTEX(clocklist_lock); + +/* timer base locked */ +static void adjust_timer(struct evl_clock *clock, + struct evl_timer *timer, struct evl_tqueue *q, + ktime_t delta) +{ + ktime_t period, diff; + s64 div; + + /* Apply the new offset from the master base. */ + evl_tdate(timer) = ktime_sub(evl_tdate(timer), delta); + + if (!evl_timer_is_periodic(timer)) + goto enqueue; + + timer->start_date = ktime_sub(timer->start_date, delta); + period = timer->interval; + diff = ktime_sub(evl_read_clock(clock), evl_get_timer_expiry(timer)); + + if (diff >= period) { + /* + * Timer should tick several times before now, instead + * of calling timer->handler several times, we change + * the timer date without changing its pexpect, so + * that timer will tick only once and the lost ticks + * will be counted as overruns. + */ + div = ktime_divns(diff, ktime_to_ns(period)); + timer->periodic_ticks += div; + evl_update_timer_date(timer); + } else if (ktime_to_ns(delta) < 0 + && (timer->status & EVL_TIMER_FIRED) + && ktime_to_ns(ktime_add(diff, period)) <= 0) { + /* + * Timer is periodic and NOT waiting for its first + * shot, so we make it tick sooner than its original + * date in order to avoid the case where by adjusting + * time to a sooner date, real-time periodic timers do + * not tick until the original date has passed. + */ + div = ktime_divns(-diff, ktime_to_ns(period)); + timer->periodic_ticks -= div; + timer->consumed_ticks -= div; + evl_update_timer_date(timer); + } + +enqueue: + evl_enqueue_timer(timer, q); +} + +void evl_adjust_timers(struct evl_clock *clock, ktime_t delta) +{ + struct evl_timer *timer, *tmp; + struct evl_timerbase *tmb; + struct evl_tqueue *tq; + struct evl_tnode *tn; + struct list_head adjq; + struct evl_rq *rq; + unsigned long flags; + int cpu; + + INIT_LIST_HEAD(&adjq); + + for_each_online_cpu(cpu) { + rq = evl_cpu_rq(cpu); + tmb = evl_percpu_timers(clock, cpu); + tq = &tmb->q; + raw_spin_lock_irqsave(&tmb->lock, flags); + + for_each_evl_tnode(tn, tq) { + timer = container_of(tn, struct evl_timer, node); + if (timer->clock == clock) + list_add_tail(&timer->adjlink, &adjq); + } + + if (list_empty(&adjq)) + goto next; + + list_for_each_entry_safe(timer, tmp, &adjq, adjlink) { + list_del(&timer->adjlink); + evl_dequeue_timer(timer, tq); + adjust_timer(clock, timer, tq, delta); + } + + if (rq != this_evl_rq()) + evl_program_remote_tick(clock, rq); + else + evl_program_local_tick(clock); + next: + raw_spin_unlock_irqrestore(&tmb->lock, flags); + } +} +EXPORT_SYMBOL_GPL(evl_adjust_timers); + +void inband_clock_was_set(void) +{ + struct evl_clock *clock; + + if (!evl_is_enabled()) + return; + + mutex_lock(&clocklist_lock); + + list_for_each_entry(clock, &clock_list, next) { + if (clock->ops.adjust) + clock->ops.adjust(clock); + } + + mutex_unlock(&clocklist_lock); +} + +static int init_clock(struct evl_clock *clock, struct evl_clock *master) +{ + int ret; + + ret = evl_init_element(&clock->element, &evl_clock_factory, + clock->flags & EVL_CLONE_PUBLIC); + if (ret) + return ret; + + clock->master = master; + + /* + * Once the device appears in the filesystem, it has to be + * usable. Make sure all inits have been completed before this + * point. + */ + ret = evl_create_core_element_device(&clock->element, + &evl_clock_factory, + clock->name); + if (ret) { + evl_destroy_element(&clock->element); + return ret; + } + + mutex_lock(&clocklist_lock); + list_add(&clock->next, &clock_list); + mutex_unlock(&clocklist_lock); + + return 0; +} + +int evl_init_clock(struct evl_clock *clock, + const struct cpumask *affinity) +{ + struct evl_timerbase *tmb; + int cpu, ret; + + inband_context_only(); + + /* + * A CPU affinity set may be defined for each clock, + * enumerating the CPUs which can receive ticks from the + * backing clock device. When given, this set must be a + * subset of the out-of-band CPU set. Otherwise, this is a + * global device for which we pick a constant affinity based + * on a known-to-be-always-valid CPU, i.e. the first OOB CPU + * available. + */ +#ifdef CONFIG_SMP + if (!affinity) { + cpumask_clear(&clock->affinity); + cpumask_set_cpu(cpumask_first(&evl_oob_cpus), + &clock->affinity); + } else { + cpumask_and(&clock->affinity, affinity, &evl_oob_cpus); + if (cpumask_empty(&clock->affinity)) + return -EINVAL; + } +#endif + + clock->timerdata = alloc_percpu(struct evl_timerbase); + if (clock->timerdata == NULL) + return -ENOMEM; + + /* + * POLA: init all timer slots for the new clock, although some + * of them might remain unused depending on the CPU affinity + * of the event source(s). If the clock device is global + * without any particular IRQ affinity, all timers will be + * queued to the first OOB CPU. + */ + for_each_online_cpu(cpu) { + tmb = evl_percpu_timers(clock, cpu); + evl_init_tqueue(&tmb->q); + raw_spin_lock_init(&tmb->lock); + } + + clock->offset = 0; + + ret = init_clock(clock, clock); + if (ret) + goto fail; + + return 0; + +fail: + for_each_online_cpu(cpu) { + tmb = evl_percpu_timers(clock, cpu); + evl_destroy_tqueue(&tmb->q); + } + + free_percpu(clock->timerdata); + + return ret; +} +EXPORT_SYMBOL_GPL(evl_init_clock); + +int evl_init_slave_clock(struct evl_clock *clock, + struct evl_clock *master) +{ + inband_context_only(); + + /* A slave clock shares its master's device. */ +#ifdef CONFIG_SMP + clock->affinity = master->affinity; +#endif + clock->timerdata = master->timerdata; + clock->offset = evl_read_clock(clock) - + evl_read_clock(master); + init_clock(clock, master); + + return 0; +} +EXPORT_SYMBOL_GPL(evl_init_slave_clock); + +static inline bool timer_needs_enqueuing(struct evl_timer *timer) +{ + /* + * True for periodic timers which have not been requeued, + * stopped or killed, false otherwise. + */ + return (timer->status & + (EVL_TIMER_PERIODIC|EVL_TIMER_DEQUEUED| + EVL_TIMER_RUNNING|EVL_TIMER_KILLED)) + == (EVL_TIMER_PERIODIC|EVL_TIMER_DEQUEUED| + EVL_TIMER_RUNNING); +} + +/* hard irqs off */ +static void do_clock_tick(struct evl_clock *clock, struct evl_timerbase *tmb) +{ + struct evl_rq *rq = this_evl_rq(); + struct evl_timer *timer; + struct evl_tqueue *tq; + struct evl_tnode *tn; + ktime_t now; + + if (EVL_WARN_ON_ONCE(CORE, !hard_irqs_disabled())) + hard_local_irq_disable(); + + tq = &tmb->q; + raw_spin_lock(&tmb->lock); + + /* + * Optimisation: any local timer reprogramming triggered by + * invoked timer handlers can wait until we leave this tick + * handler. This is a hint for the program_local_shot() + * handler of the ticking clock. + */ + rq->local_flags |= RQ_TIMER; + + now = evl_read_clock(clock); + while ((tn = evl_get_tqueue_head(tq)) != NULL) { + timer = container_of(tn, struct evl_timer, node); + if (now < evl_tdate(timer)) + break; + + trace_evl_timer_expire(timer); + evl_dequeue_timer(timer, tq); + evl_account_timer_fired(timer); + timer->status |= EVL_TIMER_FIRED; + + /* + * Propagating the proxy tick to the inband stage is a + * low priority task: postpone this until the very end + * of the core tick interrupt. + */ + if (unlikely(timer == &rq->inband_timer)) { + rq->local_flags |= RQ_TPROXY; + rq->local_flags &= ~RQ_TDEFER; + continue; + } + + raw_spin_unlock(&tmb->lock); + timer->handler(timer); + now = evl_read_clock(clock); + raw_spin_lock(&tmb->lock); + + if (timer_needs_enqueuing(timer)) { + do { + timer->periodic_ticks++; + evl_update_timer_date(timer); + } while (evl_tdate(timer) < now); + if (likely(evl_timer_on_rq(timer, rq))) + evl_enqueue_timer(timer, tq); + } + } + + rq->local_flags &= ~RQ_TIMER; + + evl_program_local_tick(clock); + + raw_spin_unlock(&tmb->lock); +} + +void evl_core_tick(struct clock_event_device *dummy) /* hard irqs off */ +{ + struct evl_rq *this_rq = this_evl_rq(); + struct evl_timerbase *tmb; + + if (EVL_WARN_ON_ONCE(CORE, !is_evl_cpu(evl_rq_cpu(this_rq)))) + return; + + tmb = evl_this_cpu_timers(&evl_mono_clock); + do_clock_tick(&evl_mono_clock, tmb); + + /* + * If an EVL thread was preempted by this clock event, any + * transition to the in-band context will cause a pending + * in-band tick to be propagated by evl_schedule() called from + * evl_exit_irq(), so we may have to propagate the in-band + * tick immediately only if the in-band context was preempted. + */ + if ((this_rq->local_flags & RQ_TPROXY) && (this_rq->curr->state & EVL_T_ROOT)) + evl_notify_proxy_tick(this_rq); +} + +void evl_announce_tick(struct evl_clock *clock) /* hard irqs off */ +{ + struct evl_timerbase *tmb; + +#ifdef CONFIG_SMP + /* + * Some external clock devices may tick on any CPU, expect the + * timers to be be queued to the first legit CPU for them + * (i.e. global devices with no affinity). + */ + if (!cpumask_test_cpu(evl_rq_cpu(this_evl_rq()), &clock->affinity)) + tmb = evl_percpu_timers(clock, cpumask_first(&clock->affinity)); + else +#endif + tmb = evl_this_cpu_timers(clock); + + do_clock_tick(clock, tmb); +} +EXPORT_SYMBOL_GPL(evl_announce_tick); + +void evl_stop_timers(struct evl_clock *clock) +{ + struct evl_timerbase *tmb; + struct evl_timer *timer; + struct evl_tqueue *tq; + struct evl_tnode *tn; + unsigned long flags; + int cpu; + + /* Deactivate all outstanding timers on the clock. */ + + for_each_evl_cpu(cpu) { + tmb = evl_percpu_timers(clock, cpu); + raw_spin_lock_irqsave(&tmb->lock, flags); + tq = &tmb->q; + while (!evl_tqueue_is_empty(tq)) { + tn = evl_get_tqueue_head(tq); + timer = container_of(tn, struct evl_timer, node); + if (EVL_WARN_ON(CORE, timer->status & EVL_TIMER_DEQUEUED)) + continue; + evl_timer_deactivate(timer); + } + raw_spin_unlock_irqrestore(&tmb->lock, flags); + } +} + +int evl_register_clock(struct evl_clock *clock, + const struct cpumask *affinity) +{ + int ret; + + inband_context_only(); + + ret = evl_init_clock(clock, affinity); + if (ret) + return ret; + + trace_evl_register_clock(clock->name); + + return 0; +} +EXPORT_SYMBOL_GPL(evl_register_clock); + +void evl_unregister_clock(struct evl_clock *clock) +{ + inband_context_only(); + + trace_evl_unregister_clock(clock->name); + evl_put_element(&clock->element); +} +EXPORT_SYMBOL_GPL(evl_unregister_clock); + +struct evl_clock *evl_get_clock_by_fd(int efd) +{ + struct evl_clock *clock = NULL; + struct evl_file *efilp; + + switch (efd) { + case EVL_CLOCK_MONOTONIC: + clock = &evl_mono_clock; + evl_get_element(&clock->element); + break; + case EVL_CLOCK_REALTIME: + clock = &evl_realtime_clock; + evl_get_element(&clock->element); + break; + default: + efilp = evl_get_file(efd); + if (efilp && efilp->filp->f_op == &clock_fops) { + clock = element_of(efilp->filp, struct evl_clock); + evl_get_element(&clock->element); + evl_put_file(efilp); + } + } + + return clock; +} +EXPORT_SYMBOL_GPL(evl_get_clock_by_fd); + +static long restart_clock_sleep(struct restart_block *param) +{ + return -EINVAL; +} + +static int clock_sleep(struct evl_clock *clock, + struct timespec64 ts64) +{ + struct evl_thread *curr = evl_current(); + struct restart_block *restart; + ktime_t timeout, rem; + + if (curr->local_info & EVL_T_SYSRST) { + curr->local_info &= ~EVL_T_SYSRST; + restart = ¤t->restart_block; + if (restart->fn != restart_clock_sleep) + return -EINTR; + timeout = restart->nanosleep.expires; + } else + timeout = timespec64_to_ktime(ts64); + + rem = evl_delay(timeout, EVL_ABS, clock); + if (!rem) + return 0; + + if (signal_pending(current)) { + restart = ¤t->restart_block; + restart->nanosleep.expires = timeout; + restart->fn = restart_clock_sleep; + curr->local_info |= EVL_T_SYSRST; + return -ERESTARTSYS; + } + + return -EINTR; +} + +static void get_clock_resolution(struct evl_clock *clock, + struct timespec64 *res) +{ + *res = ktime_to_timespec64(evl_get_clock_resolution(clock)); + + trace_evl_clock_getres(clock, res); +} + +static void get_clock_time(struct evl_clock *clock, + struct timespec64 *ts) +{ + *ts = ktime_to_timespec64(evl_read_clock(clock)); + + trace_evl_clock_gettime(clock, ts); +} + +static int set_clock_time(struct evl_clock *clock, + struct timespec64 ts) +{ + trace_evl_clock_settime(clock, &ts); + + return evl_set_clock_time(clock, timespec64_to_ktime(ts)); +} + +static void get_timer_value(struct evl_timer *__restrict__ timer, + struct itimerspec64 *__restrict__ value) +{ + value->it_interval = ktime_to_timespec64(timer->interval); + + if (!evl_timer_is_running(timer)) { + value->it_value.tv_sec = 0; + value->it_value.tv_nsec = 0; + } else + value->it_value = + ktime_to_timespec64(evl_get_timer_delta(timer)); +} + +static int set_timer_value(struct evl_timer *__restrict__ timer, + const struct itimerspec64 *__restrict__ value) +{ + ktime_t start, period; + + if (value->it_value.tv_nsec == 0 && value->it_value.tv_sec == 0) { + evl_stop_timer(timer); + return 0; + } + + period = timespec64_to_ktime(value->it_interval); + start = timespec64_to_ktime(value->it_value); + evl_start_timer(timer, start, period); + + return 0; +} + +struct evl_timerfd { + struct evl_timer timer; + struct evl_wait_queue readers; + struct evl_poll_head poll_head; + struct evl_file efile; + bool ticked; +}; + +#ifdef CONFIG_SMP + +/* Pin @timer to the current thread rq. */ +static void pin_timer(struct evl_timer *timer) +{ + unsigned long flags = hard_local_irq_save(); + struct evl_rq *this_rq = evl_current_rq(); + + if (this_rq != timer->rq) + evl_move_timer(timer, timer->clock, this_rq); + + hard_local_irq_restore(flags); +} + +#else + +static inline void pin_timer(struct evl_timer *timer) +{ } + +#endif + +static int set_timerfd(struct evl_timerfd *timerfd, + const struct itimerspec64 *__restrict__ value, + struct itimerspec64 *__restrict__ ovalue) +{ + get_timer_value(&timerfd->timer, ovalue); + + if (evl_current()) + pin_timer(&timerfd->timer); + + return set_timer_value(&timerfd->timer, value); +} + +static void timerfd_handler(struct evl_timer *timer) /* hard IRQs off */ +{ + struct evl_timerfd *timerfd; + + timerfd = container_of(timer, struct evl_timerfd, timer); + timerfd->ticked = true; + evl_signal_poll_events(&timerfd->poll_head, POLLIN|POLLRDNORM); + evl_flush_wait(&timerfd->readers, 0); +} + +static bool read_timerfd_event(struct evl_timerfd *timerfd) +{ + if (timerfd->ticked) { + timerfd->ticked = false; + return true; + } + + return false; +} + +static long timerfd_common_ioctl(struct file *filp, + unsigned int cmd, unsigned long arg) +{ + struct evl_timerfd *timerfd = filp->private_data; + struct __evl_itimerspec uits, uoits, __user *u_uits; + struct evl_timerfd_setreq sreq, __user *u_sreq; + struct itimerspec64 its, oits; + long ret = 0; + + switch (cmd) { + case EVL_TFDIOC_SET: + u_sreq = (typeof(u_sreq))arg; + sreq.ovalue_ptr = 0; + ret = raw_copy_from_user(&sreq, u_sreq, sizeof(sreq)); + if (ret) + return -EFAULT; + ret = raw_copy_from_user_ptr64(&uits, sreq.value_ptr, sizeof(uits)); + if (ret) + return -EFAULT; + if ((unsigned long)uits.it_value.tv_nsec >= ONE_BILLION || + ((unsigned long)uits.it_interval.tv_nsec >= ONE_BILLION && + (uits.it_value.tv_sec != 0 || + uits.it_value.tv_nsec != 0))) + return -EINVAL; + its = u_itimerspec_to_itimerspec64(uits); + ret = set_timerfd(timerfd, &its, &oits); + if (ret) + return ret; + if (sreq.ovalue_ptr) { + uoits = itimerspec64_to_u_itimerspec(oits); + u_uits = evl_valptr64(sreq.ovalue_ptr, + struct __evl_itimerspec); + if (raw_copy_to_user(u_uits, &uoits, sizeof(uoits))) + return -EFAULT; + } + break; + case EVL_TFDIOC_GET: + get_timer_value(&timerfd->timer, &its); + uits = itimerspec64_to_u_itimerspec(its); + u_uits = (typeof(u_uits))arg; + if (raw_copy_to_user(u_uits, &uits, sizeof(uits))) + return -EFAULT; + break; + default: + ret = -ENOTTY; + } + + return ret; +} + +static ssize_t timerfd_oob_read(struct file *filp, + char __user *u_buf, size_t count) +{ + __u64 __user *u_ticks = (__u64 __user *)u_buf, ticks = 0; + struct evl_timerfd *timerfd = filp->private_data; + ktime_t timeout = EVL_INFINITE; + int ret; + + if (count < sizeof(ticks)) + return -EINVAL; + + if (filp->f_flags & O_NONBLOCK) + timeout = EVL_NONBLOCK; + + ret = evl_wait_event_timeout(&timerfd->readers, timeout, + EVL_REL, read_timerfd_event(timerfd)); + if (ret) + return ret; + + ticks = 1; + if (evl_timer_is_periodic(&timerfd->timer)) + ticks += evl_get_timer_overruns(&timerfd->timer); + + if (raw_put_user(ticks, u_ticks)) + return -EFAULT; + + return sizeof(ticks); +} + +static __poll_t timerfd_oob_poll(struct file *filp, + struct oob_poll_wait *wait) +{ + struct evl_timerfd *timerfd = filp->private_data; + + evl_poll_watch(&timerfd->poll_head, wait, NULL); + + return timerfd->ticked ? POLLIN|POLLRDNORM : 0; +} + +static int timerfd_release(struct inode *inode, struct file *filp) +{ + struct evl_timerfd *timerfd = filp->private_data; + + evl_stop_timer(&timerfd->timer); + evl_destroy_wait(&timerfd->readers); + evl_release_file(&timerfd->efile); + evl_put_element(&timerfd->timer.clock->element); + kfree(timerfd); + + return 0; +} + +static const struct file_operations timerfd_fops = { + .open = stream_open, + .release = timerfd_release, + .oob_ioctl = timerfd_common_ioctl, + .oob_read = timerfd_oob_read, + .oob_poll = timerfd_oob_poll, + .unlocked_ioctl = timerfd_common_ioctl, +#ifdef CONFIG_COMPAT + .compat_ioctl = compat_ptr_ioctl, + .compat_oob_ioctl = compat_ptr_oob_ioctl, +#endif +}; + +static int new_timerfd(struct evl_clock *clock) +{ + struct evl_timerfd *timerfd; + struct file *filp; + int ret, fd; + + timerfd = kzalloc(sizeof(*timerfd), GFP_KERNEL); + if (timerfd == NULL) + return -ENOMEM; + + filp = anon_inode_getfile("[evl-timerfd]", &timerfd_fops, + timerfd, O_RDWR|O_CLOEXEC); + if (IS_ERR(filp)) { + kfree(timerfd); + return PTR_ERR(filp); + } + + /* + * From that point, timerfd_release() might be called for + * cleaning up on error via filp_close(). So initialize + * everything we need for a graceful cleanup. + */ + evl_get_element(&clock->element); + evl_init_timer_on_rq(&timerfd->timer, clock, timerfd_handler, + NULL, EVL_TIMER_UGRAVITY); + evl_init_wait(&timerfd->readers, clock, EVL_WAIT_PRIO); + evl_init_poll_head(&timerfd->poll_head); + + ret = evl_open_file(&timerfd->efile, filp); + if (ret) + goto fail_open; + + fd = get_unused_fd_flags(O_RDWR|O_CLOEXEC); + if (fd < 0) { + ret = fd; + goto fail_getfd; + } + + fd_install(fd, filp); + + return fd; + +fail_getfd: + evl_release_file(&timerfd->efile); +fail_open: + filp_close(filp, current->files); + + return ret; +} + +static long clock_common_ioctl(struct evl_clock *clock, + unsigned int cmd, unsigned long arg) +{ + struct __evl_timespec uts, __user *u_uts; + struct timespec64 ts64; + int ret; + + switch (cmd) { + case EVL_CLKIOC_GET_RES: + get_clock_resolution(clock, &ts64); + uts = timespec64_to_u_timespec(ts64); + u_uts = (typeof(u_uts))arg; + ret = raw_copy_to_user(u_uts, &uts, + sizeof(*u_uts)) ? -EFAULT : 0; + break; + case EVL_CLKIOC_GET_TIME: + get_clock_time(clock, &ts64); + uts = timespec64_to_u_timespec(ts64); + u_uts = (typeof(u_uts))arg; + ret = raw_copy_to_user(u_uts, &uts, + sizeof(uts)) ? -EFAULT : 0; + break; + case EVL_CLKIOC_SET_TIME: + u_uts = (typeof(u_uts))arg; + ret = raw_copy_from_user(&uts, u_uts, sizeof(uts)); + if (ret) + return -EFAULT; + if ((unsigned long)uts.tv_nsec >= ONE_BILLION) + return -EINVAL; + ts64 = u_timespec_to_timespec64(uts); + ret = set_clock_time(clock, ts64); + break; + default: + ret = -ENOTTY; + } + + return ret; +} + +static long clock_oob_ioctl(struct file *filp, unsigned int cmd, + unsigned long arg) +{ + struct evl_clock *clock = element_of(filp, struct evl_clock); + struct __evl_timespec __user *u_uts; + struct __evl_timespec uts = { + .tv_sec = 0, + .tv_nsec = 0, + }; + int ret; + + switch (cmd) { + case EVL_CLKIOC_SLEEP: + u_uts = (typeof(u_uts))arg; + ret = raw_copy_from_user(&uts, u_uts, sizeof(uts)); + if (ret) + return -EFAULT; + if (uts.tv_sec < 0) + return -EINVAL; + /* + * CAUTION: the user-provided type is wider than our + * internal type, we need to check ranges prior to + * converting to timespec64. + */ + if ((unsigned long)uts.tv_nsec >= ONE_BILLION) + return -EINVAL; + ret = clock_sleep(clock, u_timespec_to_timespec64(uts)); + break; + default: + ret = clock_common_ioctl(clock, cmd, arg); + } + + return ret; +} + +static long clock_ioctl(struct file *filp, unsigned int cmd, + unsigned long arg) +{ + struct evl_clock *clock = element_of(filp, struct evl_clock); + int __user *u_fd; + int ret; + + switch (cmd) { + case EVL_CLKIOC_NEW_TIMER: + ret = new_timerfd(clock); + if (ret >= 0) { + u_fd = (typeof(u_fd))arg; + ret = put_user(ret, u_fd); + } + break; + default: + ret = clock_common_ioctl(clock, cmd, arg); + } + + return ret; +} + +static const struct file_operations clock_fops = { + .open = evl_open_element, + .release = evl_release_element, + .unlocked_ioctl = clock_ioctl, + .oob_ioctl = clock_oob_ioctl, +#ifdef CONFIG_COMPAT + .compat_ioctl = compat_ptr_ioctl, + .compat_oob_ioctl = compat_ptr_oob_ioctl, +#endif +}; + +/* + * Once created, a clock must be deleted by dropping the last + * reference to it via a call to evl_put_element(), so that we + * remove the factory device and properly synchronize. No direct call + * to destroy_clock() except from the element disposal routine, + * please. + */ +static void destroy_clock(struct evl_clock *clock) +{ + struct evl_timerbase *tmb; + int cpu; + + inband_context_only(); + + /* + * Slave clocks use the timer queues from their master. + */ + if (clock->master != clock) + return; + + for_each_online_cpu(cpu) { + tmb = evl_percpu_timers(clock, cpu); + EVL_WARN_ON(CORE, !evl_tqueue_is_empty(&tmb->q)); + evl_destroy_tqueue(&tmb->q); + } + + free_percpu(clock->timerdata); + mutex_lock(&clocklist_lock); + list_del(&clock->next); + mutex_unlock(&clocklist_lock); + + evl_destroy_element(&clock->element); + + if (clock->dispose) + clock->dispose(clock); +} + +static void clock_factory_dispose(struct evl_element *e) +{ + struct evl_clock *clock; + + clock = container_of(e, struct evl_clock, element); + destroy_clock(clock); +} + +static ssize_t gravity_show(struct device *dev, + struct device_attribute *attr, + char *buf) +{ + struct evl_clock *clock; + ssize_t ret; + + clock = evl_get_element_by_dev(dev, struct evl_clock); + ret = snprintf(buf, PAGE_SIZE, "%Ldi %Ldk %Ldu\n", + ktime_to_ns(evl_get_clock_gravity(clock, irq)), + ktime_to_ns(evl_get_clock_gravity(clock, kernel)), + ktime_to_ns(evl_get_clock_gravity(clock, user))); + evl_put_element(&clock->element); + + return ret; +} + +static ssize_t gravity_store(struct device *dev, + struct device_attribute *attr, + const char *buf, size_t count) +{ + struct evl_clock_gravity gravity; + struct evl_clock *clock; + char *dups, *args, *p; + ssize_t ret; + long ns; + + if (!*buf) + return 0; + + dups = args = kstrdup(buf, GFP_KERNEL); + + clock = evl_get_element_by_dev(dev, struct evl_clock); + + gravity = clock->gravity; + + while ((p = strsep(&args, " \t:/,")) != NULL) { + if (*p == '\0') + continue; + ns = simple_strtol(p, &p, 10); + switch (*p) { + case 'i': + gravity.irq = ns; + break; + case 'k': + gravity.kernel = ns; + break; + case 'u': + case '\0': + gravity.user = ns; + break; + default: + ret = -EINVAL; + goto out; + } + } + + ret = evl_set_clock_gravity(clock, &gravity) ?: count; +out: + evl_put_element(&clock->element); + + kfree(dups); + + return ret; +} + +static DEVICE_ATTR_RW(gravity); + +static struct attribute *clock_attrs[] = { + &dev_attr_gravity.attr, + NULL, +}; +ATTRIBUTE_GROUPS(clock); + +struct evl_factory evl_clock_factory = { + .name = EVL_CLOCK_DEV, + .fops = &clock_fops, + .nrdev = CONFIG_EVL_NR_CLOCKS, + .attrs = clock_groups, + .dispose = clock_factory_dispose, +}; + +static int set_coreclk_gravity(struct evl_clock *clock, + const struct evl_clock_gravity *p) +{ + clock->gravity = *p; + + return 0; +} + +static void get_default_gravity(struct evl_clock_gravity *p) +{ + unsigned int ulat = CONFIG_EVL_LATENCY_USER; /* ns */ + + if (!ulat) + /* If not specified, pick a reasonable default. */ + ulat = evl_get_default_clock_gravity(); + + p->user = ulat; + p->kernel = CONFIG_EVL_LATENCY_KERNEL; + p->irq = CONFIG_EVL_LATENCY_IRQ; +} + +static void reset_coreclk_gravity(struct evl_clock *clock) +{ + struct evl_clock_gravity gravity; + + get_default_gravity(&gravity); + + if (gravity.kernel == 0) + gravity.kernel = gravity.user; + + set_coreclk_gravity(clock, &gravity); +} + +static ktime_t read_mono_clock(struct evl_clock *clock) +{ + return evl_ktime_monotonic(); +} + +static u64 read_mono_clock_cycles(struct evl_clock *clock) +{ + return read_mono_clock(clock); +} + +static ktime_t read_realtime_clock(struct evl_clock *clock) +{ + return ns_to_ktime(ktime_get_real_fast_ns()); +} + +static u64 read_realtime_clock_cycles(struct evl_clock *clock) +{ + return read_realtime_clock(clock); +} + +static void adjust_realtime_clock(struct evl_clock *clock) +{ + ktime_t old_offset = clock->offset; + + clock->offset = evl_read_clock(clock) - + evl_read_clock(&evl_mono_clock); + + evl_adjust_timers(clock, clock->offset - old_offset); +} + +struct evl_clock evl_mono_clock = { + .name = EVL_CLOCK_MONOTONIC_DEV, + .resolution = 1, /* nanosecond. */ + .flags = EVL_CLONE_PUBLIC, + .ops = { + .read = read_mono_clock, + .read_cycles = read_mono_clock_cycles, + .program_local_shot = evl_program_proxy_tick, +#ifdef CONFIG_SMP + .program_remote_shot = evl_send_timer_ipi, +#endif + .set_gravity = set_coreclk_gravity, + .reset_gravity = reset_coreclk_gravity, + }, +}; +EXPORT_SYMBOL_GPL(evl_mono_clock); + +struct evl_clock evl_realtime_clock = { + .name = EVL_CLOCK_REALTIME_DEV, + .resolution = 1, /* nanosecond. */ + .flags = EVL_CLONE_PUBLIC, + .ops = { + .read = read_realtime_clock, + .read_cycles = read_realtime_clock_cycles, + .set_gravity = set_coreclk_gravity, + .reset_gravity = reset_coreclk_gravity, + .adjust = adjust_realtime_clock, + }, +}; +EXPORT_SYMBOL_GPL(evl_realtime_clock); + +int __init evl_clock_init(void) +{ + int ret; + + evl_reset_clock_gravity(&evl_mono_clock); + evl_reset_clock_gravity(&evl_realtime_clock); + + ret = evl_init_clock(&evl_mono_clock, &evl_oob_cpus); + if (ret) + return ret; + + ret = evl_init_slave_clock(&evl_realtime_clock, &evl_mono_clock); + if (ret) + evl_put_element(&evl_mono_clock.element); + + return ret; +} + +void __init evl_clock_cleanup(void) +{ + evl_put_element(&evl_realtime_clock.element); + evl_put_element(&evl_mono_clock.element); +} diff --git a/kernel/evl/control.c b/kernel/evl/control.c new file mode 100644 index 000000000..ebbb38a02 --- /dev/null +++ b/kernel/evl/control.c @@ -0,0 +1,492 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2018 Philippe Gerum + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static BLOCKING_NOTIFIER_HEAD(state_notifier_list); + +atomic_t evl_runstate = ATOMIC_INIT(EVL_STATE_WARMUP); +EXPORT_SYMBOL_GPL(evl_runstate); + +void evl_add_state_chain(struct notifier_block *nb) +{ + blocking_notifier_chain_register(&state_notifier_list, nb); +} +EXPORT_SYMBOL_GPL(evl_add_state_chain); + +void evl_remove_state_chain(struct notifier_block *nb) +{ + blocking_notifier_chain_unregister(&state_notifier_list, nb); +} +EXPORT_SYMBOL_GPL(evl_remove_state_chain); + +static inline void call_state_chain(enum evl_run_states newstate) +{ + blocking_notifier_call_chain(&state_notifier_list, newstate, NULL); +} + +static int start_services(void) +{ + enum evl_run_states state; + int ret = 0; + + state = atomic_cmpxchg(&evl_runstate, + EVL_STATE_STOPPED, + EVL_STATE_WARMUP); + switch (state) { + case EVL_STATE_RUNNING: + break; + case EVL_STATE_STOPPED: + ret = evl_enable_tick(); + if (ret) { + atomic_set(&evl_runstate, EVL_STATE_STOPPED); + return ret; + } + call_state_chain(EVL_STATE_WARMUP); + set_evl_state(EVL_STATE_RUNNING); + printk(EVL_INFO "core started\n"); + break; + default: + ret = -EINPROGRESS; + } + + return ret; +} + +static int stop_services(void) +{ + enum evl_run_states state; + int ret = 0; + + state = atomic_cmpxchg(&evl_runstate, + EVL_STATE_RUNNING, + EVL_STATE_TEARDOWN); + switch (state) { + case EVL_STATE_STOPPED: + break; + case EVL_STATE_RUNNING: + ret = evl_killall(EVL_T_USER); + if (ret) { + set_evl_state(state); + return ret; + } + call_state_chain(EVL_STATE_TEARDOWN); + ret = evl_killall(0); + evl_disable_tick(); + set_evl_state(EVL_STATE_STOPPED); + printk(EVL_INFO "core stopped\n"); + break; + default: + ret = -EINPROGRESS; + } + + return ret; +} + +#ifdef CONFIG_EVL_SCHED_QUOTA + +static int do_quota_control(const struct evl_sched_ctlreq *ctl) +{ + union evl_sched_ctlparam param, __user *u_ctlp; + union evl_sched_ctlinfo info, __user *u_infp; + int ret; + + u_ctlp = evl_valptr64(ctl->param_ptr, union evl_sched_ctlparam); + ret = raw_copy_from_user(¶m.quota, &u_ctlp->quota, + sizeof(param.quota)); + if (ret) + return -EFAULT; + + ret = evl_sched_quota.sched_control(ctl->cpu, ¶m, &info); + if (ret < 0) + return ret; + + if (!ctl->info_ptr) + return 0; + + u_infp = evl_valptr64(ctl->info_ptr, union evl_sched_ctlinfo); + ret = raw_copy_to_user(&u_infp->quota, &info.quota, + sizeof(info.quota)); + if (ret) + return -EFAULT; + + return 0; +} + +#else + +static int do_quota_control(const struct evl_sched_ctlreq *ctl) +{ + return -EOPNOTSUPP; +} + +#endif + +#ifdef CONFIG_EVL_SCHED_TP + +static int do_tp_control(const struct evl_sched_ctlreq *ctl) +{ + union evl_sched_ctlparam _param, *param = &_param, __user *u_ctlp; + union evl_sched_ctlinfo *info = NULL, __user *u_infp; + ssize_t ret; + ssize_t len; + + u_ctlp = evl_valptr64(ctl->param_ptr, union evl_sched_ctlparam); + ret = raw_copy_from_user(&_param.tp, &u_ctlp->tp, sizeof(_param.tp)); + if (ret) + return -EFAULT; + + /* Check now to prevent creepy memalloc down the road. */ + if ((_param.tp.op == evl_tp_install || _param.tp.op == evl_tp_get) && + (_param.tp.nr_windows <= 0 || + _param.tp.nr_windows > CONFIG_EVL_SCHED_TP_NR_PART)) + return -EINVAL; + + if (_param.tp.op == evl_tp_install) { + len = evl_tp_paramlen(_param.tp.nr_windows); + param = evl_alloc(len); + if (param == NULL) + return -ENOMEM; + ret = raw_copy_from_user(¶m->tp, &u_ctlp->tp, len); + if (ret) + goto out; + } + + if (ctl->info_ptr) { + len = evl_tp_infolen(param->tp.nr_windows); + /* + * No need to zalloc, only the updated portion of the + * info buffer is going to be returned. + */ + info = evl_alloc(len); + if (info == NULL) { + ret = -ENOMEM; + goto out; + } + } + + len = evl_sched_tp.sched_control(ctl->cpu, param, info); + if (len < 0) { + ret = len; + goto out; + } + + if (info && len > 0) { + u_infp = evl_valptr64(ctl->info_ptr, + union evl_sched_ctlinfo); + ret = raw_copy_to_user(&u_infp->tp, &info->tp, len); + if (ret) + ret = -EFAULT; + } +out: + if (info) + evl_free(info); + + if (param != &_param) + evl_free(param); + + return ret; +} + +#else + +static int do_tp_control(const struct evl_sched_ctlreq *ctl) +{ + return -EOPNOTSUPP; +} + +#endif + +static int do_sched_control(const struct evl_sched_ctlreq *ctl) +{ + int ret; + + switch (ctl->policy) { + case SCHED_QUOTA: + ret = do_quota_control(ctl); + break; + case SCHED_TP: + ret = do_tp_control(ctl); + break; + default: + return -EINVAL; + } + + return ret; +} + +static int do_cpu_state(struct evl_cpu_state *cpst) +{ + int cpu = cpst->cpu; + __u32 state = 0; + + if (cpst->cpu >= num_possible_cpus() || !cpu_present(cpu)) + return -EINVAL; + + if (!cpu_online(cpu)) + state |= EVL_CPU_OFFLINE; + + if (is_evl_cpu(cpu)) + state |= EVL_CPU_OOB; + + if (!housekeeping_cpu(cpu, HK_TYPE_DOMAIN)) + state |= EVL_CPU_ISOL; + + return raw_copy_to_user_ptr64(cpst->state_ptr, &state, + sizeof(state)) ? -EFAULT : 0; +} + +static long control_common_ioctl(struct file *filp, unsigned int cmd, + unsigned long arg) +{ + struct evl_cpu_state cpst = { .state_ptr = 0 }, __user *u_cpst; + struct evl_sched_ctlreq ctl, __user *u_ctl; + long ret; + + switch (cmd) { + case EVL_CTLIOC_SCHEDCTL: + u_ctl = (typeof(u_ctl))arg; + ret = raw_copy_from_user(&ctl, u_ctl, sizeof(ctl)); + if (ret) + return -EFAULT; + ret = do_sched_control(&ctl); + break; + case EVL_CTLIOC_GET_CPUSTATE: + u_cpst = (typeof(u_cpst))arg; + ret = raw_copy_from_user(&cpst, u_cpst, sizeof(cpst)); + if (ret) + return -EFAULT; + ret = do_cpu_state(&cpst); + break; + default: + ret = -ENOTTY; + } + + return ret; +} + +static int control_open(struct inode *inode, struct file *filp) +{ + struct oob_mm_state *oob_mm = dovetail_mm_state(); + int ret = 0; + + /* + * Opening the control device is a strong hint that we are + * about to host EVL threads in the current process, so this + * makes sense to allocate the resources we'll need to + * maintain them here. The in-band kernel has no way to figure + * out when initializing the oob context for a new mm might be + * relevant, so this has to be done on demand based on some + * information only EVL has. This is the reason why there is + * no initialization call for the oob_mm state defined in the + * Dovetail interface, the in-band kernel would not know when + * to call it. + */ + + if (!oob_mm) /* Userland only. */ + return -EPERM; + + /* The control device might be opened multiple times. */ + if (!test_and_set_bit(EVL_MM_INIT_BIT, &oob_mm->flags)) + ret = activate_oob_mm_state(oob_mm); + + stream_open(inode, filp); + + return ret; +} + +static long control_oob_ioctl(struct file *filp, unsigned int cmd, + unsigned long arg) +{ + return control_common_ioctl(filp, cmd, arg); +} + +static long control_ioctl(struct file *filp, unsigned int cmd, + unsigned long arg) +{ + struct evl_core_info info; + long ret; + + switch (cmd) { + case EVL_CTLIOC_GET_COREINFO: + info.abi_base = EVL_ABI_BASE; + info.abi_current = EVL_ABI_LEVEL; + info.fpu_features = evl_detect_fpu(); + info.shm_size = evl_shm_size; + ret = copy_to_user((struct evl_core_info __user *)arg, + &info, sizeof(info)) ? -EFAULT : 0; + break; + default: + ret = control_common_ioctl(filp, cmd, arg); + } + + return ret; +} + +static int control_mmap(struct file *filp, struct vm_area_struct *vma) +{ + void *p = evl_get_heap_base(&evl_shared_heap); + size_t len = vma->vm_end - vma->vm_start; + unsigned long addr = vma->vm_start; + int err; + struct page *page; + + if (len != evl_shm_size) + return -EINVAL; + + while (addr < vma->vm_end) { + page = vmalloc_to_page(p); + err = vm_insert_page(vma, addr, page); + if (err < 0) + return err; + addr += PAGE_SIZE; + p += PAGE_SIZE; + } + + return 0; +} + +static const struct file_operations control_fops = { + .open = control_open, + .oob_ioctl = control_oob_ioctl, + .unlocked_ioctl = control_ioctl, + .mmap = control_mmap, +#ifdef CONFIG_COMPAT + .compat_ioctl = compat_ptr_ioctl, + .compat_oob_ioctl = compat_ptr_oob_ioctl, +#endif +}; + +static const char *state_labels[] = { + [EVL_STATE_DISABLED] = "disabled", + [EVL_STATE_RUNNING] = "running", + [EVL_STATE_STOPPED] = "stopped", + [EVL_STATE_TEARDOWN] = "teardown", + [EVL_STATE_WARMUP] = "warmup", +}; + +static ssize_t state_show(struct device *dev, + struct device_attribute *attr, + char *buf) +{ + int st = atomic_read(&evl_runstate); + + return snprintf(buf, PAGE_SIZE, "%s\n", state_labels[st]); +} + +static ssize_t state_store(struct device *dev, + struct device_attribute *attr, + const char *buf, size_t count) +{ + size_t len = count; + + if (len && buf[len - 1] == '\n') + len--; + + if (!strncmp(buf, "start", len)) + return start_services() ?: count; + + if (!strncmp(buf, "stop", len)) + return stop_services() ?: count; + + return -EINVAL; +} +static DEVICE_ATTR_RW(state); + +static ssize_t abi_show(struct device *dev, + struct device_attribute *attr, + char *buf) +{ + return snprintf(buf, PAGE_SIZE, "%d\n", EVL_ABI_LEVEL); +} +static DEVICE_ATTR_RO(abi); + +static ssize_t cpus_show(struct device *dev, + struct device_attribute *attr, + char *buf) +{ + return scnprintf(buf, PAGE_SIZE, "%*pbl\n", + cpumask_pr_args(&evl_oob_cpus)); +} +static DEVICE_ATTR_RO(cpus); + +#ifdef CONFIG_EVL_SCHED_QUOTA + +static ssize_t quota_show(struct device *dev, + struct device_attribute *attr, + char *buf) +{ + return snprintf(buf, PAGE_SIZE, "%Lu\n", + ktime_to_ns(evl_get_quota_period())); +} + +static ssize_t quota_store(struct device *dev, + struct device_attribute *attr, + const char *buf, size_t count) +{ + unsigned long long period; + int ret; + + ret = kstrtoull(buf, 10, &period); + if (ret < 0) + return -EINVAL; + + /* + * If the quota period is shorter than the monotonic clock + * gravity for user-targeted timers, assume PEBKAC. + */ + if (period < evl_get_clock_gravity(&evl_mono_clock, user)) + return -EINVAL; + + evl_set_quota_period(ns_to_ktime(period)); + + return count; +} +static DEVICE_ATTR_RW(quota); + +#endif + +#ifdef CONFIG_EVL_SCHED_TP + +static ssize_t tp_show(struct device *dev, + struct device_attribute *attr, + char *buf) +{ + return snprintf(buf, PAGE_SIZE, "%d\n", CONFIG_EVL_SCHED_TP_NR_PART); +} +static DEVICE_ATTR_RO(tp); + +#endif + +static struct attribute *control_attrs[] = { + &dev_attr_state.attr, + &dev_attr_abi.attr, + &dev_attr_cpus.attr, +#ifdef CONFIG_EVL_SCHED_QUOTA + &dev_attr_quota.attr, +#endif +#ifdef CONFIG_EVL_SCHED_TP + &dev_attr_tp.attr, +#endif + NULL, +}; +ATTRIBUTE_GROUPS(control); + +struct evl_factory evl_control_factory = { + .name = "control", + .fops = &control_fops, + .attrs = control_groups, + .flags = EVL_FACTORY_SINGLE, +}; diff --git a/kernel/evl/factory.c b/kernel/evl/factory.c new file mode 100644 index 000000000..a2f87b89f --- /dev/null +++ b/kernel/evl/factory.c @@ -0,0 +1,986 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2018 Philippe Gerum + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static struct class *evl_class; + +static struct evl_factory *early_factories[] = { + &evl_clock_factory, +}; + +static struct evl_factory *factories[] = { + &evl_control_factory, + &evl_thread_factory, + &evl_monitor_factory, + &evl_poll_factory, + &evl_xbuf_factory, + &evl_proxy_factory, + &evl_observable_factory, + &evl_rng_factory, +#ifdef CONFIG_EVL_NET + &evl_net_factory, +#endif +#ifdef CONFIG_FTRACE + &evl_trace_factory, +#endif +}; + +#define NR_FACTORIES \ + (ARRAY_SIZE(early_factories) + ARRAY_SIZE(factories)) + +static dev_t factory_rdev; + +static struct task_struct flusher_kthread; + +static wait_queue_head_t flusher_wait; + +static LIST_HEAD(flusher_queue); + +int evl_init_element(struct evl_element *e, + struct evl_factory *fac, int clone_flags) +{ + int minor; + + do { + minor = find_first_zero_bit(fac->minor_map, fac->nrdev); + if (minor >= fac->nrdev) { + printk_ratelimited(EVL_WARNING "out of %ss", + fac->name); + return -EAGAIN; + } + } while (test_and_set_bit(minor, fac->minor_map)); + + e->factory = fac; + e->minor = minor; + refcount_set(&e->refs, 1); + e->dev = NULL; + e->fpriv.filp = NULL; + e->fpriv.efd = -1; + e->fundle = EVL_NO_HANDLE; + e->devname = NULL; + e->clone_flags = clone_flags; + + return 0; +} + +int evl_init_user_element(struct evl_element *e, + struct evl_factory *fac, + const char __user *u_name, + int clone_flags) +{ + struct filename *devname; + char tmpbuf[32]; + int ret; + + ret = evl_init_element(e, fac, clone_flags); + if (ret) + return ret; + + if (u_name) { + devname = getname(u_name); + } else { + snprintf(tmpbuf, sizeof(tmpbuf), "%s%%%d", + fac->name, e->minor); + devname = getname_kernel(tmpbuf); + } + + if (IS_ERR(devname)) { + evl_destroy_element(e); + return PTR_ERR(devname); + } + + e->devname = devname; + + return 0; +} + +void evl_destroy_element(struct evl_element *e) +{ + clear_bit(e->minor, e->factory->minor_map); + if (e->devname) + putname(e->devname); +} + +static int bind_file_to_element(struct file *filp, struct evl_element *e) +{ + struct evl_file_binding *fbind; + int ret; + + fbind = kmalloc(sizeof(*fbind), GFP_KERNEL); + if (fbind == NULL) + return -ENOMEM; + + ret = evl_open_file(&fbind->efile, filp); + if (ret) { + kfree(fbind); + return ret; + } + + fbind->element = e; + filp->private_data = fbind; + + return 0; +} + +static struct evl_element *unbind_file_from_element(struct file *filp) +{ + struct evl_file_binding *fbind = filp->private_data; + struct evl_element *e = fbind->element; + + evl_release_file(&fbind->efile); + kfree(fbind); + + return e; +} + +/* + * evl_open_element() might race with __do_put_element() for the same + * element before the backing device is removed. If the refcount is + * zero on entry, evl_open_element() knows that __evl_put_element() is + * about to delete @e, returns -ESTALE if so. + */ +int evl_open_element(struct inode *inode, struct file *filp) +{ + struct evl_element *e; + int ret = 0; + + e = container_of(inode->i_cdev, struct evl_element, cdev); + if (!__evl_get_element(e)) + return -ESTALE; + + ret = bind_file_to_element(filp, e); + if (ret) { + evl_put_element(e); + return ret; + } + + stream_open(inode, filp); + + return 0; +} + +static void __do_put_element(struct evl_element *e) +{ + struct evl_factory *fac = e->factory; + + /* + * We might get there device-less if create_element_device() + * failed installing a file descriptor for a private + * element. Go to disposal immediately if so. + * + * CAUTION: the disposal handler should delay the release of + * @e's container at the next rcu idle period via kfree_rcu(), + * because the embedded e->cdev is still needed ahead for + * completing the file release process of public elements (see + * __fput()). + */ + if (likely(e->dev)) + evl_remove_element_device(e); + + /* + * e->minor is not reusable until evl_destroy_element() is + * called from the disposal handler, so there is no risk of + * reusing it too early. + */ + fac->dispose(e); +} + +static void do_put_element_irq(struct irq_work *work) +{ + struct evl_element *e; + unsigned long flags; + + e = container_of(work, struct evl_element, irq_work); + + /* + * Queue the flushable element then wake the flusher up if + * need be. + */ + spin_lock_irqsave(&flusher_wait.lock, flags); + + list_add(&e->flush, &flusher_queue); + if (list_is_singular(&flusher_queue)) + wake_up_locked(&flusher_wait); + + spin_unlock_irqrestore(&flusher_wait.lock, flags); +} + +void __evl_put_element(struct evl_element *e) +{ + /* + * Element disposal is a bit tricky: + * + * 1. this must happen from an inband task context which is + * NOT a work queue callback since dispose() handlers might + * want to call flush_work(), which might in turn lead to a + * deadlock in the workqueue synchronization code if so. Our + * flusher kthread provides such workqueue-independent task + * context when the disposal routine runs from a work handler. + * + * 2. however, we want dependent create->delete->create + * sequences to be preserved when issued from the same context + * on any given CPU, e.g. the following must work: + * + * struct evl_clone_req req = { .name_ptr = __evl_ptr64("foo") }; + * CPU0: ioctl(..., EVL_IOC_CLONE, &req); + * CPU0: close(req.efd); + * CPU0: efd = ioctl(..., EVL_IOC_CLONE, &req); + * + * In this case, the disposal request never runs from a worker + * context, so we can and must call dispose() immediately from + * the calling context to provide the guarantee above + * (i.e. fully synchronous path). + * + * 3. the last reference to an element might be dropped either + * from oob context or inband while hard irqs are off. To + * address this we need an irq work trampoline for queuing the + * element to the flush queue. Note that irq_work_queue() does + * not synchronize the interrupt log when called with hard + * irqs off. + */ + if (unlikely(running_oob() || hard_irqs_disabled())) { + init_irq_work(&e->irq_work, do_put_element_irq); + irq_work_queue(&e->irq_work); + } else { + /* + * If the calling context is a workqueue worker, we + * must go through the flusher kthread to prevent any + * workqueue synchronization woes. Otherwise, we may + * (and must) run the disposal code directly. + */ + if (current_work()) + do_put_element_irq(&e->irq_work); + else + __do_put_element(e); + } +} +EXPORT_SYMBOL_GPL(__evl_put_element); + +int evl_release_element(struct inode *inode, struct file *filp) +{ + struct evl_element *e; + + e = unbind_file_from_element(filp); + evl_put_element(e); + + return 0; +} + +static void release_sys_device(struct device *dev) +{ + kfree(dev); +} + +static struct device *create_sys_device(dev_t rdev, struct evl_factory *fac, + void *drvdata, const char *name) +{ + struct device *dev; + int ret; + + dev = kzalloc(sizeof(*dev), GFP_KERNEL); + if (dev == NULL) + return ERR_PTR(-ENOMEM); + + dev->devt = rdev; + dev->class = fac->class; + dev->type = &fac->type; + dev->groups = fac->attrs; + dev->release = release_sys_device; + dev_set_drvdata(dev, drvdata); + + ret = dev_set_name(dev, "%s", name); + if (ret) + goto fail; + + ret = device_register(dev); + if (ret) + goto fail; + + return dev; + +fail: + put_device(dev); /* ->release_sys_device() */ + + return ERR_PTR(ret); +} + +static struct file_operations dummy_fops = { + .owner = THIS_MODULE, +}; + +static int do_element_visibility(struct evl_element *e, + struct evl_factory *fac, + dev_t *rdev) +{ + struct file *filp; + int ret, efd; + + if (EVL_WARN_ON(CORE, !evl_element_has_coredev(e) && !current->mm)) + e->clone_flags |= EVL_CLONE_COREDEV; + + /* + * Unlike a private one, a publicly visible element exports a + * cdev in the /dev/evl hierarchy so that any process can see + * it. Both types are backed by a kernel device object so + * that we can export their state to userland via /sysfs. + */ + + if (evl_element_is_public(e)) { + *rdev = MKDEV(MAJOR(fac->sub_rdev), e->minor); + cdev_init(&e->cdev, fac->fops); + return cdev_add(&e->cdev, *rdev, 1); + } + + *rdev = MKDEV(0, e->minor); + + if (evl_element_has_coredev(e)) + return 0; + + /* + * Create a private user element, passing the real fops so + * that FMODE_CAN_READ/WRITE are set accordingly by the vfs. + */ + filp = anon_inode_getfile(evl_element_name(e), fac->fops, + NULL, O_RDWR); + if (IS_ERR(filp)) { + ret = PTR_ERR(filp); + return ret; + } + + /* + * Now switch to dummy fops temporarily, until calling + * evl_release_element() is safe for filp, meaning once + * bind_file_to_element() has returned successfully. + */ + replace_fops(filp, &dummy_fops); + + /* + * There will be no open() call for this new private element + * since we have no associated cdev, bind it to the anon file + * immediately. + */ + ret = bind_file_to_element(filp, e); + if (ret) { + filp_close(filp, current->files); + /* + * evl_release_element() was not called: do a manual + * disposal. + */ + fac->dispose(e); + return ret; + } + + /* Back to the real fops for this element class. */ + replace_fops(filp, fac->fops); + + efd = get_unused_fd_flags(O_RDWR|O_CLOEXEC); + if (efd < 0) { + filp_close(filp, current->files); + ret = efd; + return ret; + } + + e->fpriv.filp = filp; + e->fpriv.efd = efd; + + return 0; +} + +static int create_element_device(struct evl_element *e, + struct evl_factory *fac) +{ + struct evl_element *n; + struct device *dev; + dev_t rdev; + u64 hlen; + int ret; + + /* + * Do a quick hash check on the new element name, to make sure + * device_register() won't trigger a kernel log splash because + * of a naming conflict. + */ + hlen = hashlen_string("EVL", e->devname->name); + + mutex_lock(&fac->hash_lock); + + hash_for_each_possible(fac->name_hash, n, hash, hlen) + if (!strcmp(n->devname->name, e->devname->name)) { + mutex_unlock(&fac->hash_lock); + goto fail_hash; + } + + hash_add(fac->name_hash, &e->hash, hlen); + + mutex_unlock(&fac->hash_lock); + + ret = do_element_visibility(e, fac, &rdev); + if (ret) + goto fail_visibility; + + dev = create_sys_device(rdev, fac, e, evl_element_name(e)); + if (IS_ERR(dev)) { + ret = PTR_ERR(dev); + goto fail_device; + } + + /* + * Install fd on a private user element file only when we + * cannot fail creating the device anymore. First take a + * reference then install fd (which is a membar). + */ + if (!evl_element_is_public(e) && !evl_element_has_coredev(e)) { + refcount_inc(&e->refs); + fd_install(e->fpriv.efd, e->fpriv.filp); + } + + e->dev = dev; + + return 0; + + /* + * On error, public and/or core-owned elements should be + * discarded by the caller. Private user elements must be + * disposed of in this routine if we cannot give them a + * device. + */ +fail_hash: + if (!evl_element_is_public(e) && !evl_element_has_coredev(e)) + fac->dispose(e); + + return -EEXIST; + +fail_device: + if (evl_element_is_public(e)) { + cdev_del(&e->cdev); + } else if (!evl_element_has_coredev(e)) { + put_unused_fd(e->fpriv.efd); + filp_close(e->fpriv.filp, current->files); + } + +fail_visibility: + mutex_lock(&fac->hash_lock); + hash_del(&e->hash); + mutex_unlock(&fac->hash_lock); + + return ret; +} + +int evl_create_core_element_device(struct evl_element *e, + struct evl_factory *fac, + const char *name) +{ + struct filename *devname; + + if (name) { + devname = getname_kernel(name); + if (devname == NULL) + return PTR_ERR(devname); + e->devname = devname; + } + + e->clone_flags |= EVL_CLONE_COREDEV; + + return create_element_device(e, fac); +} + +void evl_remove_element_device(struct evl_element *e) +{ + struct evl_factory *fac = e->factory; + struct device *dev = e->dev; + + device_unregister(dev); + + if (evl_element_is_public(e)) + cdev_del(&e->cdev); + + mutex_lock(&fac->hash_lock); + hash_del(&e->hash); + mutex_unlock(&fac->hash_lock); +} + +static long ioctl_clone_device(struct file *filp, unsigned int cmd, + unsigned long arg) +{ + struct evl_element *e = filp->private_data; + struct evl_clone_req req, __user *u_req; + __u32 val, state_offset = -1U; + const char __user *u_name; + struct evl_factory *fac; + void __user *u_attrs; + int ret; + + if (cmd != EVL_IOC_CLONE) + return -ENOTTY; + + if (!evl_is_running()) + return -ENXIO; + + if (e) + return -EBUSY; + + u_req = (typeof(u_req))arg; + ret = copy_from_user(&req, u_req, sizeof(req)); + if (ret) + return -EFAULT; + + u_name = evl_valptr64(req.name_ptr, const char); + if (u_name == NULL && req.clone_flags & EVL_CLONE_PUBLIC) + return -EINVAL; + + u_attrs = evl_valptr64(req.attrs_ptr, void); + fac = container_of(filp->f_inode->i_cdev, struct evl_factory, cdev); + e = fac->build(fac, u_name, u_attrs, req.clone_flags, &state_offset); + if (IS_ERR(e)) + return PTR_ERR(e); + + /* This must be set before the device appears. */ + filp->private_data = e; + barrier(); + + ret = create_element_device(e, fac); + if (ret) { + /* release_clone_device() must skip cleanup. */ + filp->private_data = NULL; + /* + * If we failed to create a private element, + * evl_release_element() did run via filp_close(), so + * the disposal has taken place already. + * + * NOTE: this code should never directly handle core + * devices, since we are running the user interface to + * cloning a new element. Although a thread may be + * associated with a coredev observable, the latter + * does not export any direct interface to user. + */ + EVL_WARN_ON(CORE, evl_element_has_coredev(e)); + /* + * @e might be stale if it was private, test the + * visibility flag from the request block instead. + */ + if (req.clone_flags & EVL_CLONE_PUBLIC) + fac->dispose(e); + return ret; + } + + val = e->minor; + ret |= put_user(val, &u_req->eids.minor); + val = e->fundle; + ret |= put_user(val, &u_req->eids.fundle); + ret |= put_user(state_offset, &u_req->eids.state_offset); + val = e->fpriv.efd; + ret |= put_user(val, &u_req->efd); + + return ret ? -EFAULT : 0; +} + +static int release_clone_device(struct inode *inode, struct file *filp) +{ + struct evl_element *e = filp->private_data; + + if (e) + evl_put_element(e); + + return 0; +} + +static int open_clone_device(struct inode *inode, struct file *filp) +{ + struct evl_factory *fac; + + fac = container_of(filp->f_inode->i_cdev, struct evl_factory, cdev); + fac->kuid = inode->i_uid; + fac->kgid = inode->i_gid; + stream_open(inode, filp); + + return 0; +} + +static const struct file_operations clone_fops = { + .open = open_clone_device, + .release = release_clone_device, + .unlocked_ioctl = ioctl_clone_device, +#ifdef CONFIG_COMPAT + .compat_ioctl = compat_ptr_ioctl, +#endif +}; + +static int index_element_at(struct evl_index *map, + struct evl_element *e, fundle_t fundle) +{ + struct rb_node **rbp, *parent; + struct evl_element *tmp; + + parent = NULL; + rbp = &map->root.rb_node; + while (*rbp) { + tmp = rb_entry(*rbp, struct evl_element, index_node); + parent = *rbp; + if (fundle < tmp->fundle) + rbp = &(*rbp)->rb_left; + else if (fundle > tmp->fundle) + rbp = &(*rbp)->rb_right; + else + return -EEXIST; + } + + e->fundle = fundle; + rb_link_node(&e->index_node, parent, rbp); + rb_insert_color(&e->index_node, &map->root); + + return 0; +} + +void evl_index_element(struct evl_index *map, struct evl_element *e) +{ + fundle_t fundle, guard = 0; + unsigned long flags; + int ret; + + do { + if (evl_get_index(++guard) == 0) { /* Paranoid. */ + e->fundle = EVL_NO_HANDLE; + WARN_ON_ONCE("out of fundle index space"); + return; + } + + raw_spin_lock_irqsave(&map->lock, flags); + + fundle = evl_get_index(++map->generator); + if (!fundle) /* Exclude EVL_NO_HANDLE */ + fundle = map->generator = 1; + + ret = index_element_at(map, e, fundle); + + raw_spin_unlock_irqrestore(&map->lock, flags); + } while (ret); +} + +void evl_unindex_element(struct evl_index *map, struct evl_element *e) +{ + unsigned long flags; + + raw_spin_lock_irqsave(&map->lock, flags); + rb_erase(&e->index_node, &map->root); + raw_spin_unlock_irqrestore(&map->lock, flags); +} + +struct evl_element * +__evl_get_element_by_fundle(struct evl_index *map, fundle_t fundle) +{ + struct evl_element *e; + unsigned long flags; + struct rb_node *rb; + + raw_spin_lock_irqsave(&map->lock, flags); + + rb = map->root.rb_node; + while (rb) { + e = rb_entry(rb, struct evl_element, index_node); + if (fundle < e->fundle) { + rb = rb->rb_left; + } else if (fundle > e->fundle) { + rb = rb->rb_right; + } else { + if (unlikely(!refcount_inc_not_zero(&e->refs))) + e = NULL; + break; + } + } + + raw_spin_unlock_irqrestore(&map->lock, flags); + + return rb ? e : NULL; +} + +static char *factory_type_devnode(const struct device *dev, umode_t *mode, + kuid_t *uid, kgid_t *gid) +{ + struct evl_element *e; + + /* + * Inherit the ownership of a new element device from the + * clone device which has instantiated it. + */ + e = dev_get_drvdata(dev); + if (e) { + if (uid) + *uid = e->factory->kuid; + if (gid) + *gid = e->factory->kgid; + } + + return kasprintf(GFP_KERNEL, "evl/%s/%s", + dev->type->name, dev_name(dev)); +} + +static int create_element_class(struct evl_factory *fac) +{ + struct class *class; + int ret = -ENOMEM; + + fac->minor_map = bitmap_zalloc(fac->nrdev, GFP_KERNEL); + if (fac->minor_map == NULL) + return ret; + + class = class_create(fac->name); + if (IS_ERR(class)) { + ret = PTR_ERR(class); + goto cleanup_minor; + } + + fac->class = class; + fac->type.name = fac->name; + fac->type.devnode = factory_type_devnode; + fac->kuid = GLOBAL_ROOT_UID; + fac->kgid = GLOBAL_ROOT_GID; + + ret = alloc_chrdev_region(&fac->sub_rdev, 0, fac->nrdev, fac->name); + if (ret) + goto cleanup_class; + + return 0; + +cleanup_class: + class_destroy(class); +cleanup_minor: + bitmap_free(fac->minor_map); + + return ret; +} + +static void delete_element_class(struct evl_factory *fac) +{ + unregister_chrdev_region(fac->sub_rdev, fac->nrdev); + class_destroy(fac->class); + bitmap_free(fac->minor_map); +} + +int evl_create_factory(struct evl_factory *fac, dev_t rdev) +{ + const char *idevname = "clone"; /* Initial device in factory. */ + struct device *dev = NULL; + int ret; + + if (fac->flags & EVL_FACTORY_SINGLE) { + idevname = fac->name; + fac->class = evl_class; + fac->minor_map = NULL; + fac->sub_rdev = MKDEV(0, 0); + cdev_init(&fac->cdev, fac->fops); + } else { + ret = create_element_class(fac); + if (ret) + return ret; + if (fac->flags & EVL_FACTORY_CLONE) + cdev_init(&fac->cdev, &clone_fops); + } + + if (fac->flags & (EVL_FACTORY_CLONE|EVL_FACTORY_SINGLE)) { + ret = cdev_add(&fac->cdev, rdev, 1); + if (ret) + goto fail_cdev; + + dev = create_sys_device(rdev, fac, NULL, idevname); + if (IS_ERR(dev)) + goto fail_dev; + } + + fac->dev = dev; + raw_spin_lock_init(&fac->index.lock); + fac->index.root = RB_ROOT; + fac->index.generator = EVL_NO_HANDLE; + hash_init(fac->name_hash); + mutex_init(&fac->hash_lock); + + return 0; + +fail_dev: + cdev_del(&fac->cdev); +fail_cdev: + if (!(fac->flags & EVL_FACTORY_SINGLE)) + delete_element_class(fac); + + return ret; +} +EXPORT_SYMBOL_GPL(evl_create_factory); + +void evl_delete_factory(struct evl_factory *fac) +{ + struct device *dev = fac->dev; + + if (dev) { + device_unregister(dev); + cdev_del(&fac->cdev); + } + + if (!(fac->flags & EVL_FACTORY_SINGLE)) + delete_element_class(fac); +} +EXPORT_SYMBOL_GPL(evl_delete_factory); + +bool evl_may_access_factory(struct evl_factory *fac) +{ + const struct cred *cred = current_cred(); + + return capable(CAP_SYS_ADMIN) || uid_eq(cred->euid, fac->kuid); +} +EXPORT_SYMBOL_GPL(evl_may_access_factory); + +static char *evl_devnode(const struct device *dev, umode_t *mode) +{ + return kasprintf(GFP_KERNEL, "evl/%s", dev_name(dev)); +} + +static int factory_flusher(void *arg) +{ + struct wait_queue_entry wq_entry; + struct evl_element *e, *tmp; + unsigned long flags; + LIST_HEAD(list); + + init_wait_entry(&wq_entry, 0); + + for (;;) { + if (kthread_should_stop()) + break; + + spin_lock_irqsave(&flusher_wait.lock, flags); + + if (!list_empty(&flusher_queue)) { + list_splice_init(&flusher_queue, &list); + spin_unlock_irqrestore(&flusher_wait.lock, flags); + list_for_each_entry_safe(e, tmp, &list, flush) { + list_del(&e->flush); + __do_put_element(e); + } + } else { + if (list_empty(&wq_entry.entry)) + __add_wait_queue(&flusher_wait, &wq_entry); + set_current_state(TASK_INTERRUPTIBLE); + spin_unlock_irqrestore(&flusher_wait.lock, flags); + schedule(); + } + } + + return 0; +} + +static int __init +create_core_factories(struct evl_factory **factories, int nr) +{ + int ret, n; + + for (n = 0; n < nr; n++) { + ret = evl_create_factory(factories[n], + MKDEV(MAJOR(factory_rdev), n)); + if (ret) + goto fail; + } + + return 0; +fail: + while (n-- > 0) + evl_delete_factory(factories[n]); + + return ret; +} + +static void __init +delete_core_factories(struct evl_factory **factories, int nr) +{ + int n; + + for (n = 0; n < nr; n++) + evl_delete_factory(factories[n]); +} + +int __init evl_early_init_factories(void) +{ + struct task_struct *p; + int ret; + + evl_class = class_create("evl"); + if (IS_ERR(evl_class)) + return PTR_ERR(evl_class); + + evl_class->devnode = evl_devnode; + + ret = alloc_chrdev_region(&factory_rdev, 0, NR_FACTORIES, + "evl_factory"); + if (ret) + goto fail_region; + + init_waitqueue_head(&flusher_wait); + p = kthread_run(factory_flusher, &flusher_kthread, "evl_flusher"); + if (IS_ERR(p)) { + ret = PTR_ERR(p); + goto fail_kthread; + } + + ret = create_core_factories(early_factories, + ARRAY_SIZE(early_factories)); + if (ret) + goto fail_factories; + + return 0; + +fail_factories: + kthread_stop(&flusher_kthread); +fail_kthread: + unregister_chrdev_region(factory_rdev, NR_FACTORIES); +fail_region: + class_destroy(evl_class); + + return ret; +} + +void __init evl_early_cleanup_factories(void) +{ + delete_core_factories(early_factories, ARRAY_SIZE(early_factories)); + unregister_chrdev_region(factory_rdev, NR_FACTORIES); + kthread_stop(&flusher_kthread); + wake_up(&flusher_wait); + class_destroy(evl_class); +} + +int __init evl_late_init_factories(void) +{ + return create_core_factories(factories, ARRAY_SIZE(factories)); +} + +void __init evl_late_cleanup_factories(void) +{ + delete_core_factories(factories, ARRAY_SIZE(factories)); +} diff --git a/kernel/evl/file.c b/kernel/evl/file.c new file mode 100644 index 000000000..dcb369e21 --- /dev/null +++ b/kernel/evl/file.c @@ -0,0 +1,273 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2018 Philippe Gerum + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static struct rb_root fd_tree = RB_ROOT; + +static DEFINE_HARD_SPINLOCK(fdt_lock); + +/* + * We could have a per-files_struct table of fds managed out-of-band, + * but this looks overkill at the moment. So we only have a single + * rb-tree for now, indexing our file descriptors on a composite key + * which pairs the the in-band fd and the originating files struct + * pointer. + */ + +static inline bool lean_left(struct evl_fd *lh, struct evl_fd *rh) +{ + if (lh->files == rh->files) + return lh->fd < rh->fd; + + return lh->files < rh->files; +} + +static inline bool lean_right(struct evl_fd *lh, struct evl_fd *rh) +{ + if (lh->files == rh->files) + return lh->fd > rh->fd; + + return lh->files > rh->files; +} + +static inline int index_efd(struct evl_fd *efd, struct file *filp) +{ + struct rb_node **rbp, *parent = NULL; + struct evl_fd *tmp; + + rbp = &fd_tree.rb_node; + while (*rbp) { + tmp = rb_entry(*rbp, struct evl_fd, rb); + parent = *rbp; + if (lean_left(efd, tmp)) + rbp = &(*rbp)->rb_left; + else if (lean_right(efd, tmp)) + rbp = &(*rbp)->rb_right; + else + return -EEXIST; + } + + rb_link_node(&efd->rb, parent, rbp); + rb_insert_color(&efd->rb, &fd_tree); + + return 0; +} + +static inline +struct evl_fd *lookup_efd(unsigned int fd, + struct files_struct *files) +{ + struct evl_fd *efd, tmp; + struct rb_node *rb; + + tmp.fd = fd; + tmp.files = files; + rb = fd_tree.rb_node; + while (rb) { + efd = rb_entry(rb, struct evl_fd, rb); + if (lean_left(&tmp, efd)) + rb = rb->rb_left; + else if (lean_right(&tmp, efd)) + rb = rb->rb_right; + else + return efd; + } + + return NULL; +} + +static inline +struct evl_fd *unindex_efd(unsigned int fd, + struct files_struct *files) +{ + struct evl_fd *efd = lookup_efd(fd, files); + + if (efd) + rb_erase(&efd->rb, &fd_tree); + + return efd; +} + +/* in-band, caller may hold files->file_lock */ +void install_inband_fd(unsigned int fd, struct file *filp, + struct files_struct *files) +{ + unsigned long flags; + struct evl_fd *efd; + int ret = -ENOMEM; + + if (filp->f_oob_ctx == NULL) + return; + + efd = evl_alloc(sizeof(struct evl_fd)); + if (efd) { + efd->fd = fd; + efd->files = files; + efd->efilp = filp->f_oob_ctx; + INIT_LIST_HEAD(&efd->poll_nodes); + raw_spin_lock_irqsave(&fdt_lock, flags); + ret = index_efd(efd, filp); + raw_spin_unlock_irqrestore(&fdt_lock, flags); + } + + EVL_WARN_ON(CORE, ret); +} + +/* fdt_lock held, irqs off. CAUTION: resched required on exit. */ +static void drop_watchpoints(struct evl_fd *efd) +{ + if (!list_empty(&efd->poll_nodes)) + evl_drop_watchpoints(&efd->poll_nodes); +} + +/* in-band, caller holds files->file_lock */ +void uninstall_inband_fd(unsigned int fd, struct file *filp, + struct files_struct *files) +{ + unsigned long flags; + struct evl_fd *efd; + + if (filp->f_oob_ctx == NULL) + return; + + raw_spin_lock_irqsave(&fdt_lock, flags); + efd = unindex_efd(fd, files); + if (efd) + drop_watchpoints(efd); + raw_spin_unlock_irqrestore(&fdt_lock, flags); + evl_schedule(); + + if (efd) + evl_free(efd); +} + +/* in-band, caller holds files->file_lock */ +void replace_inband_fd(unsigned int fd, struct file *filp, + struct files_struct *files) +{ + unsigned long flags; + struct evl_fd *efd; + + if (filp->f_oob_ctx == NULL) + return; + + raw_spin_lock_irqsave(&fdt_lock, flags); + + efd = lookup_efd(fd, files); + if (efd) { + drop_watchpoints(efd); + efd->efilp = filp->f_oob_ctx; + raw_spin_unlock_irqrestore(&fdt_lock, flags); + evl_schedule(); + return; + } + + raw_spin_unlock_irqrestore(&fdt_lock, flags); + + install_inband_fd(fd, filp, files); +} + +struct evl_file *evl_get_file(unsigned int fd) +{ + struct evl_file *efilp = NULL; + unsigned long flags; + struct evl_fd *efd; + + raw_spin_lock_irqsave(&fdt_lock, flags); + efd = lookup_efd(fd, current->files); + if (efd) { + efilp = efd->efilp; + evl_get_fileref(efilp); + } + raw_spin_unlock_irqrestore(&fdt_lock, flags); + + return efilp; +} +EXPORT_SYMBOL_GPL(evl_get_file); + +struct evl_file *evl_watch_fd(unsigned int fd, + struct evl_poll_node *node) +{ + struct evl_file *efilp = NULL; + unsigned long flags; + struct evl_fd *efd; + + raw_spin_lock_irqsave(&fdt_lock, flags); + efd = lookup_efd(fd, current->files); + if (efd) { + efilp = efd->efilp; + evl_get_fileref(efilp); + list_add(&node->next, &efd->poll_nodes); + } + raw_spin_unlock_irqrestore(&fdt_lock, flags); + + return efilp; +} + +void evl_ignore_fd(struct evl_poll_node *node) +{ + unsigned long flags; + + raw_spin_lock_irqsave(&fdt_lock, flags); + list_del(&node->next); + raw_spin_unlock_irqrestore(&fdt_lock, flags); +} + +/** + * evl_open_file - Open new file with oob capabilities + * + * Called by chrdev with oob capabilities when a new @efilp is + * opened. @efilp is paired with the in-band file struct at @filp. + */ +int evl_open_file(struct evl_file *efilp, struct file *filp) +{ + efilp->filp = filp; + filp->f_oob_ctx = efilp; /* mark filp as oob-capable. */ + evl_init_crossing(&efilp->crossing); + + return 0; +} +EXPORT_SYMBOL_GPL(evl_open_file); + +/** + * evl_release_file - Drop an oob-capable file + * + * Called by chrdev with oob capabilities when @efilp is about to be + * released. Must be called from a fops->release() handler, and paired + * with a previous call to evl_open_file() from the fops->open() + * handler. + */ +void evl_release_file(struct evl_file *efilp) +{ + /* + * Release the original reference on @efilp. If oob references + * are still pending (e.g. some thread is still blocked in + * fops->oob_read()), we must wait for them to be dropped + * before allowing the in-band code to dismantle @efilp->filp. + * + * NOTE: In-band and out-of-band fds are working together in + * lockstep mode via dovetail_install/uninstall_fd() calls. + * Therefore, we can't livelock with evl_get_file() as @efilp + * was removed from the fd tree before fops->release() called + * us. + */ + evl_pass_crossing(&efilp->crossing); +} +EXPORT_SYMBOL_GPL(evl_release_file); diff --git a/kernel/evl/init.c b/kernel/evl/init.c new file mode 100644 index 000000000..03e677523 --- /dev/null +++ b/kernel/evl/init.c @@ -0,0 +1,210 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2018 Philippe Gerum + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#define CREATE_TRACE_POINTS +#include + +static char *oobcpus_arg; +module_param_named(oobcpus, oobcpus_arg, charp, 0444); + +static char init_state_arg[16] = "enabled"; +module_param_string(state, init_state_arg, sizeof(init_state_arg), 0444); + +struct cpumask evl_oob_cpus; +EXPORT_SYMBOL_GPL(evl_oob_cpus); + +DEFINE_PER_CPU(struct evl_machine_cpudata, evl_machine_cpudata); +EXPORT_PER_CPU_SYMBOL_GPL(evl_machine_cpudata); + +#ifdef CONFIG_EVL_DEBUG +#define boot_debug_notice "[DEBUG]" +#else +#define boot_debug_notice "" +#endif + +#ifdef CONFIG_ENABLE_DEFAULT_TRACERS +#define boot_trace_notice "[TRACE]" +#else +#define boot_trace_notice "" +#endif + +#define boot_state_notice \ + ({ \ + evl_is_stopped() ? "[STOPPED]" : ""; \ + }) + +static struct { + const char *label; + enum evl_run_states state; +} init_states[] __initdata = { + { "disabled", EVL_STATE_DISABLED }, + { "stopped", EVL_STATE_STOPPED }, + { "enabled", EVL_STATE_WARMUP }, +}; + +static void __init setup_init_state(void) +{ + static char warn_bad_state[] __initdata = + EVL_WARNING "invalid init state '%s'\n"; + int n; + + for (n = 0; n < ARRAY_SIZE(init_states); n++) + if (strcmp(init_states[n].label, init_state_arg) == 0) { + set_evl_state(init_states[n].state); + return; + } + + printk(warn_bad_state, init_state_arg); +} + +#ifdef CONFIG_EVL_DEBUG + +void __init evl_warn_init(const char *fn, int level, int status) +{ + printk(EVL_ERR "FAILED: %s => [%d]\n", fn, status); +} + +#endif + +static __init int init_core(void) +{ + int ret; + + enable_oob_stage("EVL"); + + ret = evl_init_memory(); + if (ret) + goto cleanup_stage; + + ret = evl_early_init_factories(); + if (ret) + goto cleanup_memory; + + ret = evl_clock_init(); + if (ret) + goto cleanup_early_factories; + + ret = evl_init_sched(); + if (ret) + goto cleanup_clock; + + /* + * If starting in stopped mode, do all initializations, but do + * not enable the core timer. + */ + if (evl_is_warming()) { + ret = evl_enable_tick(); + if (ret) + goto cleanup_sched; + set_evl_state(EVL_STATE_RUNNING); + } + + ret = dovetail_start(); + if (ret) + goto cleanup_tick; + + /* + * Other factories can clone elements, which would allow users + * to issue Dovetail requests afterwards, so let's expose them + * once Dovetail is mindful. + */ + ret = evl_late_init_factories(); + if (ret) + goto cleanup_dovetail; + + /* + * Eventually, bootstrap anything which may require factory + * services. + */ + ret = evl_net_init(); + if (ret) + goto cleanup_late_factories; + + return 0; + +cleanup_late_factories: + evl_late_cleanup_factories(); +cleanup_dovetail: + dovetail_stop(); +cleanup_tick: + if (evl_is_running()) + evl_disable_tick(); +cleanup_sched: + evl_cleanup_sched(); +cleanup_clock: + evl_clock_cleanup(); +cleanup_early_factories: + evl_early_cleanup_factories(); +cleanup_memory: + evl_cleanup_memory(); +cleanup_stage: + disable_oob_stage(); + set_evl_state(EVL_STATE_STOPPED); + + return ret; +} + +static int __init evl_init(void) +{ + int ret; + + setup_init_state(); + + if (!evl_is_enabled()) { + printk(EVL_WARNING "disabled on kernel command line\n"); + return 0; + } + + /* + * Set of CPUs the core knows about and which should run an + * in-band proxy timer. This set includes the subset of CPUs + * which may run EVL threads, aka evl_cpu_affinity. + */ + if (oobcpus_arg && *oobcpus_arg) { + if (cpulist_parse(oobcpus_arg, &evl_oob_cpus)) { + printk(EVL_WARNING "invalid set of OOB cpus\n"); + cpumask_copy(&evl_oob_cpus, cpu_online_mask); + } + } else + cpumask_copy(&evl_oob_cpus, cpu_online_mask); + + /* Threads may run on any out-of-band CPU by default. */ + evl_cpu_affinity = evl_oob_cpus; + + ret = EVL_INIT_CALL(0, init_core()); + if (ret) + goto fail; + + /* Set up the random generators. */ + evl_init_rng(); + + printk(EVL_INFO "core started %s%s%s\n", + boot_debug_notice, + boot_trace_notice, + boot_state_notice); + + return 0; +fail: + set_evl_state(EVL_STATE_DISABLED); + + printk(EVL_ERR "disabling.\n"); + + return ret; +} +device_initcall(evl_init); diff --git a/kernel/evl/lib/Makefile b/kernel/evl/lib/Makefile new file mode 100644 index 000000000..d6bdc3111 --- /dev/null +++ b/kernel/evl/lib/Makefile @@ -0,0 +1,3 @@ +obj-y += lib.o + +lib-y := cache.o uio.o diff --git a/kernel/evl/lib/cache.c b/kernel/evl/lib/cache.c new file mode 100644 index 000000000..82c6faf13 --- /dev/null +++ b/kernel/evl/lib/cache.c @@ -0,0 +1,400 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2023 Philippe Gerum + * + * This file implements a generic dynamically-growable cache with + * support for in-band update and out-of-band lookup. + */ + +#include +#include + +static int realloc_hash_table(struct evl_cache *cache); + +static void hash_free_rcu(struct rcu_head *rcu); + +static void entry_free_rcu(struct rcu_head *rcu); + +static void entry_free_work(struct evl_work *work); + +int evl_init_cache(struct evl_cache *cache) /* in-band */ +{ + spin_lock_init(&cache->lock); + cache->hash_table = NULL; + + return realloc_hash_table(cache); +} +EXPORT_SYMBOL_GPL(evl_init_cache); + +void evl_cleanup_cache(struct evl_cache *cache) /* in-band */ +{ + evl_flush_cache(cache); +} +EXPORT_SYMBOL_GPL(evl_cleanup_cache); + +/* + * Cache a new entry. The cache must have been locked prior to calling + * this routine. This call must be issued from the in-band stage. + * + * @entry entry to add to the cache. + */ +int evl_add_cache_entry_locked(struct evl_cache *cache, /* in-band */ + struct evl_cache_entry *entry) +{ + const void *key = cache->ops->get_key(entry); + struct evl_cache_entry *e, **ep; + struct evl_hash_table *ht; + u32 hashval; + int ret; + + hashval = cache->ops->hash(key); +retry: + ht = rcu_dereference_protected(cache->hash_table, + lockdep_is_held(&cache->lock)); + if (!ht || ht->nr_entries >= (1 << ht->shift)) { + spin_unlock_bh(&cache->lock); + ret = realloc_hash_table(cache); + spin_lock_bh(&cache->lock); + if (ret) + return ret; + goto retry; + } + + /* + * Find the place to attach the new entry, dropping a previous + * match on the fly if any. + */ + hashval >>= (32 - ht->shift); /* Modulo table size. */ + for (ep = &ht->buckets[hashval], + e = rcu_dereference_protected(ht->buckets[hashval], + lockdep_is_held(&cache->lock)); + e; e = rcu_dereference_protected(e->next, + lockdep_is_held(&cache->lock))) { + if (cache->ops->eq(e, key)) { + rcu_assign_pointer(*ep, e->next); + if (refcount_dec_and_test(&e->refcnt)) + call_rcu(&e->rcu, entry_free_rcu); + } else { + ep = &e->next; + } + } + + ht->nr_entries++; + entry->cache = cache; + refcount_set(&entry->refcnt, 1); + evl_init_work(&entry->work, entry_free_work); + rcu_assign_pointer(*ep, entry); + + return 0; +} +EXPORT_SYMBOL_GPL(evl_add_cache_entry_locked); + +/* + * Cache a new entry. This call must be issued from the in-band + * stage. + * + * @entry entry to add to the cache. + */ +int evl_add_cache_entry(struct evl_cache *cache, /* in-band */ + struct evl_cache_entry *entry) +{ + int ret; + + spin_lock_bh(&cache->lock); + ret = evl_add_cache_entry_locked(cache, entry); + spin_unlock_bh(&cache->lock); + + return 0; +} +EXPORT_SYMBOL_GPL(evl_add_cache_entry); + +/* + * Remove an entry from the cache. The cache must have been locked + * prior to calling this routine. This call must be issued from the + * in-band stage. + * + * @entry entry to remove from the cache. + */ +void evl_del_cache_entry_locked(struct evl_cache *cache, const void *key) /* in-band */ +{ + struct evl_cache_entry *e, **ep; + struct evl_hash_table *ht; + u32 hashval; + + ht = rcu_dereference_protected(cache->hash_table, + lockdep_is_held(&cache->lock)); + if (!ht) + return; + + hashval = cache->ops->hash(key); + hashval >>= (32 - ht->shift); /* Modulo table size. */ + + /* Don't bark on invalid removal request, just ignore it. */ + for (ep = &ht->buckets[hashval], + e = rcu_dereference_protected( + ht->buckets[hashval], + lockdep_is_held(&cache->lock)); + e; e = rcu_dereference_protected( + e->next, + lockdep_is_held(&cache->lock))) { + if (cache->ops->eq(e, key)) { + rcu_assign_pointer(*ep, e->next); + if (refcount_dec_and_test(&e->refcnt)) + call_rcu(&e->rcu, entry_free_rcu); + break; + } + ep = &e->next; + } +} +EXPORT_SYMBOL_GPL(evl_del_cache_entry_locked); + +/* + * Remove an entry from the cache. This call must be issued from the + * in-band stage. + * + * @entry entry to remove from the cache. + */ +void evl_del_cache_entry(struct evl_cache *cache, const void *key) /* in-band */ +{ + spin_lock_bh(&cache->lock); + evl_del_cache_entry_locked(cache, key); + spin_unlock_bh(&cache->lock); +} +EXPORT_SYMBOL_GPL(evl_del_cache_entry); + +void evl_flush_cache(struct evl_cache *cache) /* in-band */ +{ + struct evl_cache_entry __rcu **buckets, *e, *next; + struct evl_hash_table *ht; + size_t size; + int n; + + spin_lock_bh(&cache->lock); + + ht = rcu_dereference_protected(cache->hash_table, + lockdep_is_held(&cache->lock)); + if (likely(ht)) { + rcu_assign_pointer(cache->hash_table, NULL); + size = (1 << ht->shift) * sizeof(struct evl_cache_entry *); + buckets = rcu_dereference_protected(ht->buckets, + lockdep_is_held(&cache->lock)); + + for (n = 0; n < (1 << ht->shift); n++) { + for (e = rcu_dereference_protected(buckets[n], + lockdep_is_held(&cache->lock)); e; e = next) { + next = rcu_dereference_protected(e->next, + lockdep_is_held(&cache->lock)); + if (refcount_dec_and_test(&e->refcnt)) + call_rcu(&e->rcu, entry_free_rcu); + } + } + + call_rcu(&ht->rcu, hash_free_rcu); + } + + spin_unlock_bh(&cache->lock); +} +EXPORT_SYMBOL_GPL(evl_flush_cache); + +void evl_clean_cache(struct evl_cache *cache, + bool (*testfn)(struct evl_cache_entry *e, void *arg), + void *arg) /* in-band */ +{ + struct evl_cache_entry __rcu **buckets, *e, **ep, *next; + struct evl_hash_table *ht; + size_t size; + int n; + + spin_lock_bh(&cache->lock); + + ht = rcu_dereference_protected(cache->hash_table, + lockdep_is_held(&cache->lock)); + if (likely(ht)) { + size = (1 << ht->shift) * sizeof(struct evl_cache_entry *); + buckets = rcu_dereference_protected(ht->buckets, + lockdep_is_held(&cache->lock)); + + for (n = 0; n < (1 << ht->shift); n++) { + for (ep = &ht->buckets[n], + e = rcu_dereference_protected(buckets[n], + lockdep_is_held(&cache->lock)); e; e = next) { + next = rcu_dereference_protected(e->next, + lockdep_is_held(&cache->lock)); + if (testfn(e, arg)) { + rcu_assign_pointer(*ep, e->next); + if (refcount_dec_and_test(&e->refcnt)) + call_rcu(&e->rcu, entry_free_rcu); + } else { + ep = &e->next; + } + } + } + } + + spin_unlock_bh(&cache->lock); +} +EXPORT_SYMBOL_GPL(evl_clean_cache); + +/* in-band / oob */ +struct evl_cache_entry *evl_lookup_cache(struct evl_cache *cache, + const void *key) +{ + struct evl_cache_entry *e = NULL; + struct evl_hash_table *ht; + u32 hashval; + + rcu_read_lock(); + + ht = rcu_dereference(cache->hash_table); + if (likely(ht)) { + hashval = cache->ops->hash(key); + hashval >>= (32 - ht->shift); /* Modulo table size. */ + for (e = rcu_dereference(ht->buckets[hashval]); + e; e = rcu_dereference(e->next)) { + if (cache->ops->eq(e, key)) { + refcount_inc(&e->refcnt); + break; + } + } + } + + rcu_read_unlock(); + + return e; +} +EXPORT_SYMBOL_GPL(evl_lookup_cache); + +/* in-band / oob */ +void evl_put_cache_entry(struct evl_cache_entry *entry) +{ + if (refcount_dec_and_test(&entry->refcnt)) { + if (running_inband()) + call_rcu(&entry->rcu, entry_free_rcu); + else + evl_call_inband(&entry->work); + } +} +EXPORT_SYMBOL_GPL(evl_put_cache_entry); + +static void entry_free_rcu(struct rcu_head *rcu) /* in-band */ +{ + struct evl_cache_entry *e = container_of(rcu, struct evl_cache_entry, rcu); + e->cache->ops->drop(e); +} + +/* + * Trampoline to schedule our RCU callback. We could not do this + * directly from oob, since call_rcu() would not support this, _and_ + * RCU does neither watch nor even know about the oob context in the + * first place. + */ +static void entry_free_work(struct evl_work *work) /* in-band */ +{ + struct evl_cache_entry *e = container_of(work, struct evl_cache_entry, work); + call_rcu(&e->rcu, entry_free_rcu); +} + +static void hash_free_rcu(struct rcu_head *head) +{ + struct evl_hash_table *ht = + container_of(head, struct evl_hash_table, rcu); + size_t size = (1 << ht->shift) * sizeof(struct evl_cache_entry *); + struct evl_cache_entry __rcu **buckets = ht->buckets; + + if (size <= PAGE_SIZE) { + kfree(buckets); + } else { + kmemleak_free(buckets); + free_pages((unsigned long)buckets, get_order(size)); + } + + kfree(ht); +} + +/* + * Grow the hash table of a cache. We may look up into a table from + * oob inside a read-side RCU section (Dovetail may emulate an NMI + * entry in this case). + */ +static int realloc_hash_table(struct evl_cache *cache) +{ + struct evl_hash_table *old_ht, *new_ht; + struct evl_cache_entry __rcu **buckets; + unsigned int shift; + size_t size; + u32 hash; + int n; + + rcu_read_lock(); + old_ht = rcu_dereference(cache->hash_table); + shift = old_ht ? old_ht->shift + 1 : cache->init_shift; + rcu_read_unlock(); + size = (1 << shift) * sizeof(struct evl_cache_entry *); + + new_ht = kmalloc(sizeof(*new_ht), GFP_ATOMIC); + if (!new_ht) + return -ENOMEM; + + if (size <= PAGE_SIZE) { + buckets = kzalloc(size, GFP_ATOMIC); + } else { + buckets = (struct evl_cache_entry __rcu **) + __get_free_pages(GFP_ATOMIC | __GFP_ZERO, + get_order(size)); + kmemleak_alloc(buckets, size, 1, GFP_ATOMIC); + } + + if (!buckets) { + kfree(new_ht); + return -ENOMEM; + } + + /* The table must be valid before aborting. */ + new_ht->buckets = buckets; + new_ht->shift = shift; + new_ht->nr_entries = 0; + + spin_lock_bh(&cache->lock); + + old_ht = rcu_dereference_protected(cache->hash_table, lockdep_is_held(&cache->lock)); + if (!old_ht) + goto finish; + + /* Somebody slipped in and grew the table already, abort. */ + if (old_ht->shift >= shift) { + spin_unlock_bh(&cache->lock); + hash_free_rcu(&new_ht->rcu); + return 0; + } + + /* Copy the old table content to the new (larger) one. */ + for (n = 0; n < (1 << old_ht->shift); n++) { + struct evl_cache_entry *e, *next; + + for (e = rcu_dereference_protected(old_ht->buckets[n], + lockdep_is_held(&cache->lock)); + e; e = next) { + hash = cache->ops->hash(e); + hash >>= (32 - shift); + next = rcu_dereference_protected(e->next, + lockdep_is_held(&cache->lock)); + rcu_assign_pointer(e->next, + rcu_dereference_protected( + new_ht->buckets[hash], + lockdep_is_held(&cache->lock))); + rcu_assign_pointer(new_ht->buckets[hash], e); + } + } + + new_ht->nr_entries = old_ht->nr_entries; + +finish: + rcu_assign_pointer(cache->hash_table, new_ht); + spin_unlock_bh(&cache->lock); + + if (old_ht) + call_rcu(&old_ht->rcu, hash_free_rcu); + + return 0; +} diff --git a/kernel/evl/lib/uio.c b/kernel/evl/lib/uio.c new file mode 100644 index 000000000..cf015cb20 --- /dev/null +++ b/kernel/evl/lib/uio.c @@ -0,0 +1,194 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2020-2023 Philippe Gerum + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +static int load_iov_native(struct iovec *iov, + const struct iovec __user *u_iov, + size_t iovlen) +{ + return raw_copy_from_user(iov, u_iov, iovlen * sizeof(*u_iov)) ? + -EFAULT : 0; +} + +#ifdef CONFIG_COMPAT + +static int do_load_iov(struct iovec *iov, + const struct iovec __user *u_iov, + size_t iovlen) +{ + struct compat_iovec c_iov[UIO_FASTIOV], __user *uc_iov; + size_t nvec = 0; + int ret, n, i; + + if (likely(!is_compat_oob_call())) + return load_iov_native(iov, u_iov, iovlen); + + uc_iov = (struct compat_iovec *)u_iov; + + /* + * Slurp compat_iovector in by chunks of UIO_FASTIOV + * cells. This is faster in the most likely case compared to + * allocating yet another in-kernel vector dynamically for + * such purpose. + */ + while (nvec < iovlen) { + n = iovlen - nvec; + if (n > UIO_FASTIOV) + n = UIO_FASTIOV; + ret = raw_copy_from_user(c_iov, uc_iov, sizeof(*uc_iov) * n); + if (ret) + return -EFAULT; + for (i = 0; i < n; i++, iov++) { + iov->iov_base = compat_ptr(c_iov[i].iov_base); + iov->iov_len = c_iov[i].iov_len; + } + uc_iov += n; + nvec += n; + } + + return 0; +} + +#else + +static inline int do_load_iov(struct iovec *iov, + const struct iovec __user *u_iov, + size_t iovlen) +{ + return load_iov_native(iov, u_iov, iovlen); +} + +#endif + +struct iovec *evl_load_uio(const struct iovec __user *u_iov, + size_t iovlen, struct iovec *fast_iov) +{ + struct iovec *slow_iov; + int ret; + + if (iovlen > UIO_MAXIOV) + return ERR_PTR(-EINVAL); + + if (likely(iovlen <= UIO_FASTIOV)) { + ret = do_load_iov(fast_iov, u_iov, iovlen); + return ret ? ERR_PTR(ret) : fast_iov; + } + + slow_iov = evl_alloc(iovlen * sizeof(*u_iov)); + if (slow_iov == NULL) + return ERR_PTR(-ENOMEM); + + ret = do_load_iov(slow_iov, u_iov, iovlen); + if (ret) { + evl_free(slow_iov); + return ERR_PTR(ret); + } + + return slow_iov; +} +EXPORT_SYMBOL_GPL(evl_load_uio); + +ssize_t evl_copy_to_uio(const struct iovec *iov, size_t iovlen, + const void *data, size_t len) +{ + ssize_t written = 0; + size_t nbytes; + int n, ret; + + for (n = 0; len > 0 && n < iovlen; n++, iov++) { + if (iov->iov_len == 0) + continue; + + nbytes = iov->iov_len; + if (nbytes > len) + nbytes = len; + + ret = raw_copy_to_user(iov->iov_base, data, nbytes); + if (ret) + return -EFAULT; + + len -= nbytes; + data += nbytes; + written += nbytes; + if (written < 0) + return -EINVAL; + } + + return written; +} +EXPORT_SYMBOL_GPL(evl_copy_to_uio); + +ssize_t evl_copy_from_uio(const struct iovec *iov, size_t iovlen, + void *data, size_t len, size_t *remainder) +{ + size_t nbytes, avail = 0; + ssize_t read = 0; + int n, ret; + + for (n = 0; len > 0 && n < iovlen; n++, iov++) { + if (iov->iov_len == 0) + continue; + + nbytes = iov->iov_len; + avail += nbytes; + if (nbytes > len) + nbytes = len; + + ret = raw_copy_from_user(data, iov->iov_base, nbytes); + if (ret) + return -EFAULT; + + len -= nbytes; + data += nbytes; + read += nbytes; + if (read < 0) + return -EINVAL; + } + + if (remainder) { + for (; n < iovlen; n++, iov++) + avail += iov->iov_len; + *remainder = avail - read; + } + + return read; +} +EXPORT_SYMBOL_GPL(evl_copy_from_uio); + +/* + * Copy the content referred to by a user I/O vector to a linear area, + * returning a kernel I/O vector composed of a single cell covering + * the loaded data. + */ +ssize_t evl_copy_from_uio_to_kvec(const struct iovec *iov, size_t iovlen, + size_t count, struct kvec *kvec) +{ + ssize_t ret; + void *data; + + data = evl_alloc(count); + if (!data) + return -ENOMEM; + + ret = evl_copy_from_uio(iov, iovlen, data, count, NULL); + if (ret <= 0) { + evl_free(data); + } else { + kvec->iov_base = data; + kvec->iov_len = ret; + } + + return ret; +} +EXPORT_SYMBOL_GPL(evl_copy_from_uio_to_kvec); diff --git a/kernel/evl/memory.c b/kernel/evl/memory.c new file mode 100644 index 000000000..acd5d6e26 --- /dev/null +++ b/kernel/evl/memory.c @@ -0,0 +1,707 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Derived from Xenomai Cobalt, https://xenomai.org/ + * Copyright (C) 2018 Philippe Gerum + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static unsigned long sysheap_size_arg; +module_param_named(sysheap_size, sysheap_size_arg, ulong, 0444); + +struct evl_heap evl_system_heap; +EXPORT_SYMBOL_GPL(evl_system_heap); + +struct evl_heap evl_shared_heap; + +size_t evl_shm_size; + +enum evl_heap_pgtype { + page_free =0, + page_cont =1, + page_list =2 +}; + +__always_inline static u32 gen_block_mask(int log2size) +{ + return -1U >> (32 - (EVL_HEAP_PAGE_SIZE >> log2size)); +} + +static inline __always_inline +int addr_to_pagenr(struct evl_heap *heap, void *p) +{ + return ((void *)p - heap->membase) >> EVL_HEAP_PAGE_SHIFT; +} + +static inline __always_inline +void *pagenr_to_addr(struct evl_heap *heap, int pg) +{ + return heap->membase + (pg << EVL_HEAP_PAGE_SHIFT); +} + +#ifdef CONFIG_EVL_DEBUG_MEMORY +/* + * Setting page_cont/page_free in the page map is only required for + * enabling full checking of the block address in free requests, which + * may be extremely time-consuming when deallocating huge blocks + * spanning thousands of pages. We only do such marking when running + * in memory debug mode. + */ +static inline bool +page_is_valid(struct evl_heap *heap, int pg) +{ + switch (heap->pagemap[pg].type) { + case page_free: + case page_cont: + return false; + case page_list: + default: + return true; + } +} + +static void mark_pages(struct evl_heap *heap, + int pg, int nrpages, + enum evl_heap_pgtype type) +{ + while (nrpages-- > 0) + heap->pagemap[pg].type = type; +} + +#else + +static inline bool +page_is_valid(struct evl_heap *heap, int pg) +{ + return true; +} + +static void mark_pages(struct evl_heap *heap, + int pg, int nrpages, + enum evl_heap_pgtype type) +{ } + +#endif + +static struct evl_heap_range * +search_size_ge(struct rb_root *t, size_t size) +{ + struct rb_node *rb, *deepest = NULL; + struct evl_heap_range *r; + + /* + * We first try to find an exact match. If that fails, we walk + * the tree in logical order by increasing size value from the + * deepest node traversed until we find the first successor to + * that node, or nothing beyond it, whichever comes first. + */ + rb = t->rb_node; + while (rb) { + deepest = rb; + r = rb_entry(rb, struct evl_heap_range, size_node); + if (size < r->size) { + rb = rb->rb_left; + continue; + } + if (size > r->size) { + rb = rb->rb_right; + continue; + } + return r; + } + + rb = deepest; + while (rb) { + r = rb_entry(rb, struct evl_heap_range, size_node); + if (size <= r->size) + return r; + rb = rb_next(rb); + } + + return NULL; +} + +static struct evl_heap_range * +search_left_mergeable(struct evl_heap *heap, struct evl_heap_range *r) +{ + struct rb_node *node = heap->addr_tree.rb_node; + struct evl_heap_range *p; + + while (node) { + p = rb_entry(node, struct evl_heap_range, addr_node); + if ((void *)p + p->size == (void *)r) + return p; + if (&r->addr_node < node) + node = node->rb_left; + else + node = node->rb_right; + } + + return NULL; +} + +static struct evl_heap_range * +search_right_mergeable(struct evl_heap *heap, struct evl_heap_range *r) +{ + struct rb_node *node = heap->addr_tree.rb_node; + struct evl_heap_range *p; + + while (node) { + p = rb_entry(node, struct evl_heap_range, addr_node); + if ((void *)r + r->size == (void *)p) + return p; + if (&r->addr_node < node) + node = node->rb_left; + else + node = node->rb_right; + } + + return NULL; +} + +static void insert_range_bysize(struct evl_heap *heap, struct evl_heap_range *r) +{ + struct rb_node **new = &heap->size_tree.rb_node, *parent = NULL; + struct evl_heap_range *p; + + while (*new) { + p = container_of(*new, struct evl_heap_range, size_node); + parent = *new; + if (r->size <= p->size) + new = &((*new)->rb_left); + else + new = &((*new)->rb_right); + } + + rb_link_node(&r->size_node, parent, new); + rb_insert_color(&r->size_node, &heap->size_tree); +} + +static void insert_range_byaddr(struct evl_heap *heap, struct evl_heap_range *r) +{ + struct rb_node **new = &heap->addr_tree.rb_node, *parent = NULL; + struct evl_heap_range *p; + + while (*new) { + p = container_of(*new, struct evl_heap_range, addr_node); + parent = *new; + if (r < p) + new = &((*new)->rb_left); + else + new = &((*new)->rb_right); + } + + rb_link_node(&r->addr_node, parent, new); + rb_insert_color(&r->addr_node, &heap->addr_tree); +} + +static int reserve_page_range(struct evl_heap *heap, size_t size) +{ + struct evl_heap_range *new, *splitr; + + /* Find a suitable range of pages covering 'size'. */ + new = search_size_ge(&heap->size_tree, size); + if (new == NULL) + return -1; + + rb_erase(&new->size_node, &heap->size_tree); + if (new->size == size) { + rb_erase(&new->addr_node, &heap->addr_tree); + return addr_to_pagenr(heap, new); + } + + /* + * The free range fetched is larger than what we need: split + * it in two, the upper part is returned to the caller, the + * lower part is sent back to the free list, which makes + * reindexing by address pointless. + */ + splitr = new; + splitr->size -= size; + new = (struct evl_heap_range *)((void *)new + splitr->size); + insert_range_bysize(heap, splitr); + + return addr_to_pagenr(heap, new); +} + +static void release_page_range(struct evl_heap *heap, + void *page, size_t size) +{ + struct evl_heap_range *freed = page, *left, *right; + bool addr_linked = false; + + freed->size = size; + + left = search_left_mergeable(heap, freed); + if (left) { + rb_erase(&left->size_node, &heap->size_tree); + left->size += freed->size; + freed = left; + addr_linked = true; + } + + right = search_right_mergeable(heap, freed); + if (right) { + rb_erase(&right->size_node, &heap->size_tree); + freed->size += right->size; + if (addr_linked) + rb_erase(&right->addr_node, &heap->addr_tree); + else + rb_replace_node(&right->addr_node, &freed->addr_node, + &heap->addr_tree); + } else if (!addr_linked) + insert_range_byaddr(heap, freed); + + insert_range_bysize(heap, freed); + mark_pages(heap, addr_to_pagenr(heap, page), + size >> EVL_HEAP_PAGE_SHIFT, page_free); +} + +static void add_page_front(struct evl_heap *heap, + int pg, int log2size) +{ + struct evl_heap_pgentry *new, *head, *next; + int ilog; + + /* Insert page at front of the per-bucket page list. */ + + ilog = log2size - EVL_HEAP_MIN_LOG2; + new = &heap->pagemap[pg]; + if (heap->buckets[ilog] == -1U) { + heap->buckets[ilog] = pg; + new->prev = new->next = pg; + } else { + head = &heap->pagemap[heap->buckets[ilog]]; + new->prev = heap->buckets[ilog]; + new->next = head->next; + next = &heap->pagemap[new->next]; + next->prev = pg; + head->next = pg; + heap->buckets[ilog] = pg; + } +} + +static void remove_page(struct evl_heap *heap, + int pg, int log2size) +{ + struct evl_heap_pgentry *old, *prev, *next; + int ilog = log2size - EVL_HEAP_MIN_LOG2; + + /* Remove page from the per-bucket page list. */ + + old = &heap->pagemap[pg]; + if (pg == old->next) + heap->buckets[ilog] = -1U; + else { + if (pg == heap->buckets[ilog]) + heap->buckets[ilog] = old->next; + prev = &heap->pagemap[old->prev]; + prev->next = old->next; + next = &heap->pagemap[old->next]; + next->prev = old->prev; + } +} + +static void move_page_front(struct evl_heap *heap, + int pg, int log2size) +{ + int ilog = log2size - EVL_HEAP_MIN_LOG2; + + /* Move page at front of the per-bucket page list. */ + + if (heap->buckets[ilog] == pg) + return; /* Already at front, no move. */ + + remove_page(heap, pg, log2size); + add_page_front(heap, pg, log2size); +} + +static void move_page_back(struct evl_heap *heap, + int pg, int log2size) +{ + struct evl_heap_pgentry *old, *last, *head, *next; + int ilog; + + /* Move page at end of the per-bucket page list. */ + + old = &heap->pagemap[pg]; + if (pg == old->next) /* Singleton, no move. */ + return; + + remove_page(heap, pg, log2size); + + ilog = log2size - EVL_HEAP_MIN_LOG2; + head = &heap->pagemap[heap->buckets[ilog]]; + last = &heap->pagemap[head->prev]; + old->prev = head->prev; + old->next = last->next; + next = &heap->pagemap[old->next]; + next->prev = pg; + last->next = pg; +} + +static void *add_free_range(struct evl_heap *heap, + size_t bsize, int log2size) +{ + int pg; + + pg = reserve_page_range(heap, ALIGN(bsize, EVL_HEAP_PAGE_SIZE)); + if (pg < 0) + return NULL; + + /* + * Update the page entry. If @log2size is non-zero + * (i.e. bsize < EVL_HEAP_PAGE_SIZE), bsize is (1 << log2Size) + * between 2^EVL_HEAP_MIN_LOG2 and 2^(EVL_HEAP_PAGE_SHIFT - + * 1). Save the log2 power into entry.type, then update the + * per-page allocation bitmap to reserve the first block. + * + * Otherwise, we have a larger block which may span multiple + * pages: set entry.type to page_list, indicating the start of + * the page range, and entry.bsize to the overall block size. + */ + if (log2size) { + heap->pagemap[pg].type = log2size; + /* + * Mark the first object slot (#0) as busy, along with + * the leftmost bits we won't use for this log2 size. + */ + heap->pagemap[pg].map = ~gen_block_mask(log2size) | 1; + /* + * Insert the new page at front of the per-bucket page + * list, enforcing the assumption that pages with free + * space live close to the head of this list. + */ + add_page_front(heap, pg, log2size); + } else { + heap->pagemap[pg].type = page_list; + heap->pagemap[pg].bsize = (u32)bsize; + mark_pages(heap, pg + 1, + (bsize >> EVL_HEAP_PAGE_SHIFT) - 1, page_cont); + } + + heap->used_size += bsize; + + return pagenr_to_addr(heap, pg); +} + +int evl_init_heap(struct evl_heap *heap, void *membase, size_t size) +{ + int n, nrpages; + + inband_context_only(); + + if (size > EVL_HEAP_MAX_HEAPSZ || !PAGE_ALIGNED(size)) + return -EINVAL; + + /* Reset bucket page lists, all empty. */ + for (n = 0; n < EVL_HEAP_MAX_BUCKETS; n++) + heap->buckets[n] = -1U; + + raw_spin_lock_init(&heap->lock); + + nrpages = size >> EVL_HEAP_PAGE_SHIFT; + heap->pagemap = kzalloc(sizeof(struct evl_heap_pgentry) * nrpages, + GFP_KERNEL); + if (heap->pagemap == NULL) + return -ENOMEM; + + heap->membase = membase; + heap->usable_size = size; + heap->used_size = 0; + + /* + * The free page pool is maintained as a set of ranges of + * contiguous pages indexed by address and size in rbtrees. + * Initially, we have a single range in those trees covering + * the whole memory we have been given for the heap. Over + * time, that range will be split then possibly re-merged back + * as allocations and deallocations take place. + */ + heap->size_tree = RB_ROOT; + heap->addr_tree = RB_ROOT; + release_page_range(heap, membase, size); + + return 0; +} +EXPORT_SYMBOL_GPL(evl_init_heap); + +void evl_destroy_heap(struct evl_heap *heap) +{ + inband_context_only(); + + kfree(heap->pagemap); +} +EXPORT_SYMBOL_GPL(evl_destroy_heap); + +void *evl_alloc_chunk(struct evl_heap *heap, size_t size) +{ + int log2size, ilog, pg, b = -1; + unsigned long flags; + size_t bsize; + void *block; + + if (size == 0) + return NULL; + + if (size < EVL_HEAP_MIN_ALIGN) { + bsize = size = EVL_HEAP_MIN_ALIGN; + log2size = EVL_HEAP_MIN_LOG2; + } else { + log2size = ilog2(size); + if (log2size < EVL_HEAP_PAGE_SHIFT) { + if (size & (size - 1)) + log2size++; + bsize = 1 << log2size; + } else + bsize = ALIGN(size, EVL_HEAP_PAGE_SIZE); + } + + /* + * Allocate entire pages directly from the pool whenever the + * block is larger or equal to EVL_HEAP_PAGE_SIZE. Otherwise, + * use bucketed memory. + * + * NOTE: Fully busy pages from bucketed memory are moved back + * at the end of the per-bucket page list, so that we may + * always assume that either the heading page has some room + * available, or no room is available from any page linked to + * this list, in which case we should immediately add a fresh + * page. + */ + raw_spin_lock_irqsave(&heap->lock, flags); + + if (bsize >= EVL_HEAP_PAGE_SIZE) + /* Add a range of contiguous free pages. */ + block = add_free_range(heap, bsize, 0); + else { + ilog = log2size - EVL_HEAP_MIN_LOG2; + EVL_WARN_ON(MEMORY, ilog < 0 || ilog >= EVL_HEAP_MAX_BUCKETS); + pg = heap->buckets[ilog]; + /* + * Find a block in the heading page if any. If there + * is none, there won't be any down the list: add a + * new page right away. + */ + if (pg < 0 || heap->pagemap[pg].map == -1U) + block = add_free_range(heap, bsize, log2size); + else { + b = ffs(~heap->pagemap[pg].map) - 1; + /* + * Got one block from the heading per-bucket + * page, tag it as busy in the per-page + * allocation map. + */ + heap->pagemap[pg].map |= (1U << b); + heap->used_size += bsize; + block = heap->membase + + (pg << EVL_HEAP_PAGE_SHIFT) + + (b << log2size); + if (heap->pagemap[pg].map == -1U) + move_page_back(heap, pg, log2size); + } + } + + raw_spin_unlock_irqrestore(&heap->lock, flags); + + return block; +} +EXPORT_SYMBOL_GPL(evl_alloc_chunk); + +void evl_free_chunk(struct evl_heap *heap, void *block) +{ + unsigned long pgoff, boff; + int log2size, pg, n; + unsigned long flags; + size_t bsize; + u32 oldmap; + + raw_spin_lock_irqsave(&heap->lock, flags); + + /* Compute the heading page number in the page map. */ + pgoff = block - heap->membase; + pg = pgoff >> EVL_HEAP_PAGE_SHIFT; + + if (!page_is_valid(heap, pg)) + goto bad; + + switch (heap->pagemap[pg].type) { + case page_list: + bsize = heap->pagemap[pg].bsize; + EVL_WARN_ON(MEMORY, (bsize & (EVL_HEAP_PAGE_SIZE - 1)) != 0); + release_page_range(heap, pagenr_to_addr(heap, pg), bsize); + break; + + default: + log2size = heap->pagemap[pg].type; + bsize = (1 << log2size); + EVL_WARN_ON(MEMORY, bsize >= EVL_HEAP_PAGE_SIZE); + boff = pgoff & ~EVL_HEAP_PAGE_MASK; + if ((boff & (bsize - 1)) != 0) /* Not at block start? */ + goto bad; + + n = boff >> log2size; /* Block position in page. */ + oldmap = heap->pagemap[pg].map; + heap->pagemap[pg].map &= ~(1U << n); + + /* + * If the page the block was sitting on is fully idle, + * return it to the pool. Otherwise, check whether + * that page is transitioning from fully busy to + * partially busy state, in which case it should move + * toward the front of the per-bucket page list. + */ + if (heap->pagemap[pg].map == ~gen_block_mask(log2size)) { + remove_page(heap, pg, log2size); + release_page_range(heap, pagenr_to_addr(heap, pg), + EVL_HEAP_PAGE_SIZE); + } else if (oldmap == -1U) + move_page_front(heap, pg, log2size); + } + + heap->used_size -= bsize; + + raw_spin_unlock_irqrestore(&heap->lock, flags); + + return; +bad: + raw_spin_unlock_irqrestore(&heap->lock, flags); + + EVL_WARN(MEMORY, 1, "invalid block %p in heap %s", + block, heap == &evl_shared_heap ? + "shared" : "system"); +} +EXPORT_SYMBOL_GPL(evl_free_chunk); + +ssize_t evl_check_chunk(struct evl_heap *heap, void *block) +{ + unsigned long pg, pgoff, boff; + ssize_t ret = -EINVAL; + unsigned long flags; + size_t bsize; + + raw_spin_lock_irqsave(&heap->lock, flags); + + /* Calculate the page number from the block address. */ + pgoff = block - heap->membase; + pg = pgoff >> EVL_HEAP_PAGE_SHIFT; + if (page_is_valid(heap, pg)) { + if (heap->pagemap[pg].type == page_list) + bsize = heap->pagemap[pg].bsize; + else { + bsize = (1 << heap->pagemap[pg].type); + boff = pgoff & ~EVL_HEAP_PAGE_MASK; + if ((boff & (bsize - 1)) != 0) /* Not at block start? */ + goto out; + } + ret = (ssize_t)bsize; + } +out: + raw_spin_unlock_irqrestore(&heap->lock, flags); + + return ret; +} +EXPORT_SYMBOL_GPL(evl_check_chunk); + +static int init_shared_heap(void) +{ + size_t size; + void *mem; + int ret; + + size = CONFIG_EVL_NR_THREADS * + sizeof(struct evl_user_window) + + CONFIG_EVL_NR_MONITORS * + sizeof(struct evl_monitor_state); + size = PAGE_ALIGN(size); + mem = vzalloc(size); + if (mem == NULL) + return -ENOMEM; + + ret = evl_init_heap(&evl_shared_heap, mem, size); + if (ret) { + vfree(mem); + return ret; + } + + evl_shm_size = size; + + return 0; +} + +static void cleanup_shared_heap(void) +{ + void *membase = evl_get_heap_base(&evl_shared_heap); + + evl_destroy_heap(&evl_shared_heap); + vfree(membase); +} + +static int init_system_heap(void) +{ + size_t size = sysheap_size_arg; + void *sysmem; + int ret; + + if (size == 0) + size = CONFIG_EVL_COREMEM_SIZE * 1024; + + sysmem = vmalloc(size); + if (sysmem == NULL) + return -ENOMEM; + + ret = evl_init_heap(&evl_system_heap, sysmem, size); + if (ret) { + vfree(sysmem); + return -ENOMEM; + } + + return 0; +} + +static void cleanup_system_heap(void) +{ + void *membase = evl_get_heap_base(&evl_system_heap); + + evl_destroy_heap(&evl_system_heap); + vfree(membase); +} + +int __init evl_init_memory(void) +{ + int ret; + + ret = EVL_INIT_CALL(1, init_system_heap()); + if (ret) + return ret; + + ret = EVL_INIT_CALL(1, init_shared_heap()); + if (ret) { + cleanup_system_heap(); + return ret; + } + + return 0; +} + +void evl_cleanup_memory(void) +{ + cleanup_shared_heap(); + cleanup_system_heap(); +} diff --git a/kernel/evl/monitor.c b/kernel/evl/monitor.c new file mode 100644 index 000000000..e41d26d65 --- /dev/null +++ b/kernel/evl/monitor.c @@ -0,0 +1,1390 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2018 Philippe Gerum + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static __always_inline atomic_t *__ATOMIC32(__u32 *ptr) +{ + return (atomic_t *)ptr; +} + +struct evl_monitor { + struct evl_element element; + struct evl_monitor_state *state; + int type : 2, + protocol : 4; + union { + struct { + struct evl_mutex mutex; + struct list_head events; + hard_spinlock_t lock; + }; + struct { + /* Out-of-band wait queue. */ + struct evl_wait_queue wait_queue; + /* In-band wait queue (read side). */ + wait_queue_head_t inband_wait_r; + /* In-band wait queue (write side). */ + wait_queue_head_t inband_wait_w; + /* In-band wake up work (read side). */ + struct irq_work inband_wake_r; + /* In-band wake up work (write side). */ + struct irq_work inband_wake_w; + /* Gate (valid during active wait only). */ + struct evl_monitor *gate; + /* Out-of-band poll head. */ + struct evl_poll_head poll_head; + /* in ->events */ + struct list_head next; + }; + }; +}; + +static const struct file_operations monitor_fops; + +static struct evl_monitor *get_monitor_by_fd(int efd, struct evl_file **efilpp) +{ + struct evl_file *efilp = evl_get_file(efd); + + if (efilp && efilp->filp->f_op == &monitor_fops) { + *efilpp = efilp; + return element_of(efilp->filp, struct evl_monitor); + } + + return NULL; +} + +int evl_signal_monitor_targeted(struct evl_thread *target, int monfd) +{ + struct evl_wait_channel *wchan; + struct evl_monitor *event; + struct evl_file *efilp; + unsigned long flags; + int ret = 0; + + event = get_monitor_by_fd(monfd, &efilp); + if (event == NULL) + return -EINVAL; + + if (event->type != EVL_MONITOR_EVENT) { + ret = -EINVAL; + goto out; + } + + /* + * Current must hold the gate lock before calling us; if not, + * we might race updating state->flags, possibly loosing + * events. Too bad. + */ + raw_spin_lock_irqsave(&target->lock, flags); + + wchan = evl_get_thread_wchan(target); + if (wchan == &event->wait_queue.wchan) { + event->state->flags |= (EVL_MONITOR_TARGETED| + EVL_MONITOR_SIGNALED); + raw_spin_lock(&target->rq->lock); + target->info |= EVL_T_SIGNAL; + raw_spin_unlock(&target->rq->lock); + } + + if (wchan) + evl_put_thread_wchan(wchan); + + raw_spin_unlock_irqrestore(&target->lock, flags); +out: + evl_put_file(efilp); + + return ret; +} + +void __evl_commit_monitor_ceiling(void) +{ + struct evl_thread *curr = evl_current(); + struct evl_monitor *gate; + + /* + * curr->u_window has to be valid since curr bears EVL_T_USER. If + * pp_pending is a bad handle, just skip ceiling. + */ + gate = evl_get_factory_element_by_fundle(&evl_monitor_factory, + curr->u_window->pp_pending, + struct evl_monitor); + if (gate == NULL) + goto out; + + if (gate->protocol == EVL_GATE_PP) + evl_commit_mutex_ceiling(&gate->mutex); + + evl_put_element(&gate->element); +out: + curr->u_window->pp_pending = EVL_NO_HANDLE; +} + +/* gate->lock + event->wait_queue.wchan.lock held, irqs off */ +static void untrack_event(struct evl_monitor *event, struct evl_monitor *gate) +{ + assert_hard_lock(&gate->lock); + assert_hard_lock(&event->wait_queue.wchan.lock); + + /* + * If no more waiter is pending on this event, have the gate + * stop tracking it. + */ + if (event->gate == gate && !evl_wait_active(&event->wait_queue)) { + list_del(&event->next); + event->gate = NULL; + event->state->u.event.gate_offset = EVL_MONITOR_NOGATE; + } +} + +/* gate->lock + event->wait_queue.wchan.lock held, irqs off */ +static void wakeup_waiters(struct evl_monitor *event, struct evl_monitor *gate) +{ + struct evl_monitor_state *state = event->state; + struct evl_thread *waiter, *n; + bool bcast; + + bcast = !!(state->flags & EVL_MONITOR_BROADCAST); + + /* + * We are called upon exiting a gate which serializes access + * to a signaled event. Unblock the thread(s) satisfied by the + * signal, either all of them, a designated set or the first + * waiter in line, depending on whether this is due to a + * broadcast, targeted or regular notification. + * + * Precedence order for event delivery is as follows: + * broadcast > targeted > regular. This means that a + * broadcast notification is considered first and applied if + * detected. Otherwise, and in presence of a targeted wake up + * request, only target threads are resumed. Otherwise, the + * thread heading the wait queue is readied. + */ + if (evl_wait_active(&event->wait_queue)) { + if (bcast) { + evl_flush_wait_locked(&event->wait_queue, 0); + } else if (state->flags & EVL_MONITOR_TARGETED) { + evl_for_each_waiter_safe(waiter, n, + &event->wait_queue) { + if (waiter->info & EVL_T_SIGNAL) + evl_wake_up(&event->wait_queue, + waiter, 0); + } + } else { + evl_wake_up_head(&event->wait_queue); + } + untrack_event(event, gate); + } /* Otherwise, spurious wakeup (fine, might happen). */ + + state->flags &= ~(EVL_MONITOR_SIGNALED| + EVL_MONITOR_BROADCAST| + EVL_MONITOR_TARGETED); +} + +static int __enter_monitor(struct evl_monitor *gate, + struct timespec64 *ts64) +{ + ktime_t timeout = EVL_INFINITE; + enum evl_tmode tmode; + + if (ts64) + timeout = timespec64_to_ktime(*ts64); + + tmode = timeout ? EVL_ABS : EVL_REL; + + return evl_lock_mutex_timeout(&gate->mutex, timeout, tmode); +} + +static int enter_monitor(struct evl_monitor *gate, + struct timespec64 *ts64) +{ + struct evl_thread *curr = evl_current(); + + if (gate->type != EVL_MONITOR_GATE) + return -EINVAL; + + if (evl_is_mutex_owner(gate->mutex.fastlock, fundle_of(curr))) + return -EDEADLK; /* Deny recursive locking. */ + + evl_commit_monitor_ceiling(); + + return __enter_monitor(gate, ts64); +} + +static int tryenter_monitor(struct evl_monitor *gate) +{ + if (gate->type != EVL_MONITOR_GATE) + return -EINVAL; + + evl_commit_monitor_ceiling(); + + return evl_trylock_mutex(&gate->mutex); +} + +static void __exit_monitor(struct evl_monitor *gate, + struct evl_thread *curr) +{ + /* + * If we are about to release the lock which is still pending + * PP (i.e. we never got scheduled out while holding it), + * clear the lazy handle. + */ + if (fundle_of(gate) == curr->u_window->pp_pending) + curr->u_window->pp_pending = EVL_NO_HANDLE; + + __evl_unlock_mutex(&gate->mutex); +} + +static int exit_monitor(struct evl_monitor *gate) +{ + struct evl_monitor_state *state = gate->state; + struct evl_thread *curr = evl_current(); + struct evl_monitor *event, *n; + unsigned long flags; + + if (gate->type != EVL_MONITOR_GATE) + return -EINVAL; + + if (!evl_is_mutex_owner(gate->mutex.fastlock, fundle_of(curr))) + return -EPERM; + + /* + * Locking order is gate lock first, depending event lock(s) + * next. + */ + raw_spin_lock_irqsave(&gate->lock, flags); + + /* + * While gate.mutex is still held by current, we can + * manipulate the state flags racelessly. + */ + if (state->flags & EVL_MONITOR_SIGNALED) { + state->flags &= ~EVL_MONITOR_SIGNALED; + list_for_each_entry_safe(event, n, &gate->events, next) { + raw_spin_lock(&event->wait_queue.wchan.lock); + if (event->state->flags & EVL_MONITOR_SIGNALED) + wakeup_waiters(event, gate); + raw_spin_unlock(&event->wait_queue.wchan.lock); + } + } + + /* + * The whole wakeup+exit sequence must appear as atomic, drop + * the gate lock last so that we are fully covered until the + * monitor is released. + */ + __exit_monitor(gate, curr); + + raw_spin_unlock_irqrestore(&gate->lock, flags); + + evl_schedule(); + + return 0; +} + +static int trywait_count(struct evl_monitor *event) +{ + struct evl_monitor_state *state = event->state; + int ret = 0, val; + + /* atomic_dec_unless_zero_or_negative */ + val = atomic_read(__ATOMIC32(&state->u.event.value)); + do { + if (unlikely(val <= 0)) { + ret = -EAGAIN; + break; + } + } while (!atomic_try_cmpxchg(__ATOMIC32(&state->u.event.value), &val, val - 1)); + + return ret; +} + +static int wait_count(struct file *filp, + ktime_t timeout, + enum evl_tmode tmode) +{ + struct evl_monitor *event = element_of(filp, struct evl_monitor); + struct evl_monitor_state *state = event->state; + unsigned long flags; + int ret = 0; + + if (filp->f_flags & O_NONBLOCK) { + ret = trywait_count(event); + } else { + /* + * CAUTION: we must fully serialize with + * post_count(). Since user-space is expected to + * trywait first before branching here, we are most + * likely going to wait anyway. + */ + raw_spin_lock_irqsave(&event->wait_queue.wchan.lock, flags); + if (atomic_dec_return(__ATOMIC32(&state->u.event.value)) < 0) { + evl_add_wait_queue(&event->wait_queue, + timeout, tmode); + raw_spin_unlock_irqrestore(&event->wait_queue.wchan.lock, + flags); + ret = evl_wait_schedule(&event->wait_queue); + if (ret) { /* Rollback decrement if failed. */ + atomic_inc(__ATOMIC32(&state->u.event.value)); + } else { + /* + * If waking up on a broadcast, we did + * not actually receive a free pass, + * make the caller notice by returning + * -EAGAIN. + */ + if (evl_current()->info & EVL_T_BCAST) + ret = -EAGAIN; + } + } else { + raw_spin_unlock_irqrestore(&event->wait_queue.wchan.lock, + flags); + } + } + + return ret; +} + +static int post_count(struct evl_monitor *event, s32 sigval, + bool bcast) +{ + struct evl_monitor_state *state = event->state; + bool pollable = true; + unsigned long flags; + int ret = 0, val; + + /* + * We may receive a null sigval for the purpose of triggering + * a poll notification without updating the count. + * + * Otherwise, we can either post a single waiter or broadcast + * the semaphore which unblocks all waiters at once, making + * them know they were not granted anything in the process + * though. Broadcasting here is equivalent to a flush + * operation. + */ + if (sigval) { + raw_spin_lock_irqsave(&event->wait_queue.wchan.lock, flags); + + if (bcast) { + val = evl_flush_wait_locked(&event->wait_queue, EVL_T_BCAST); + /* + * Each waiter found sleeping on the wait + * queue counts for 1 semaphore unit to be + * added back to the count. + */ + if (val > 0) + atomic_add(val, __ATOMIC32(&state->u.event.value)); + /* Userland might have slipped in, re-check. */ + pollable = atomic_read(__ATOMIC32(&state->u.event.value)) > 0; + } else { + if (atomic_inc_return(__ATOMIC32(&state->u.event.value)) <= 0) { + evl_wake_up_head(&event->wait_queue); + pollable = false; + } + } + + raw_spin_unlock_irqrestore(&event->wait_queue.wchan.lock, flags); + } + + if (pollable) + evl_signal_poll_events(&event->poll_head, POLLIN|POLLRDNORM); + + evl_schedule(); + + return ret; +} + +static void inband_wake_r_irqwork(struct irq_work *work) /* in-band */ +{ + struct evl_monitor *event; + + event = container_of(work, struct evl_monitor, inband_wake_r); + wake_up(&event->inband_wait_r); + evl_put_element(&event->element); +} + +static void inband_wake_w_irqwork(struct irq_work *work) /* in-band */ +{ + struct evl_monitor *event; + + event = container_of(work, struct evl_monitor, inband_wake_w); + wake_up(&event->inband_wait_w); + evl_put_element(&event->element); +} + +/* event->wait_queue.wchan.lock held, dropped on success, irqs off. */ +static bool __trywait_mask(struct evl_monitor *event, + s32 match_value, + bool exact_match, + s32 *r_value, + unsigned long flags) +{ + struct evl_monitor_state *state = event->state; + int testval; + + *r_value = atomic_read(__ATOMIC32(&state->u.event.value)) & match_value; + testval = exact_match ? match_value : *r_value; + if (*r_value && *r_value == testval) { + atomic_andnot(*r_value, __ATOMIC32(&state->u.event.value)); + testval = atomic_read(__ATOMIC32(&state->u.event.value)); + raw_spin_unlock_irqrestore(&event->wait_queue.wchan.lock, flags); + if (!testval) { + evl_signal_poll_events(&event->poll_head, POLLOUT|POLLWRNORM); + evl_schedule(); + } + return true; + } + + return false; +} + +static int trywait_mask_oob(struct evl_monitor *event, + s32 match_value, + bool exact_match, + s32 *r_value) +{ + unsigned long flags; + + /* + * Waiting for no bit is interpreted as waiting for any/all of + * them (depending on exact_match). + */ + if (match_value == 0) + match_value = -1; + + raw_spin_lock_irqsave(&event->wait_queue.wchan.lock, flags); + if (!__trywait_mask(event, match_value, exact_match, r_value, flags)) { + raw_spin_unlock_irqrestore(&event->wait_queue.wchan.lock, flags); + return -EAGAIN; + } + + return 0; +} + +struct evl_mask_wait { + /* Value to wait for. */ + int value; + /* i.e. Conjunctive/AND/ALL match */ + bool exact_match; +}; + +static int wait_mask_oob(struct file *filp, + ktime_t timeout, + enum evl_tmode tmode, + s32 match_value, + bool exact_match, + s32 *r_value) +{ + struct evl_monitor *event = element_of(filp, struct evl_monitor); + struct evl_thread *curr = evl_current(); + struct evl_mask_wait w; + unsigned long flags; + int ret; + + if (match_value == 0) /* See trywait_mask(). */ + match_value = -1; + + raw_spin_lock_irqsave(&event->wait_queue.wchan.lock, flags); + + if (__trywait_mask(event, match_value, exact_match, r_value, flags)) + return 0; /* oob lock already dropped on success. */ + + if (filp->f_flags & O_NONBLOCK) { + raw_spin_unlock_irqrestore(&event->wait_queue.wchan.lock, flags); + return -EAGAIN; + } + + w.exact_match = exact_match; + w.value = match_value; + curr->wait_data = &w; + evl_add_wait_queue(&event->wait_queue, timeout, tmode); + + raw_spin_unlock_irqrestore(&event->wait_queue.wchan.lock, flags); + + ret = evl_wait_schedule(&event->wait_queue); + if (!ret) + *r_value = w.value; + + return ret; +} + +static int post_mask(struct evl_monitor *event, int bits, bool bcast) +{ + struct evl_monitor_state *state = event->state; + int waitval, testval, consumed = 0, val; + struct evl_thread *waiter, *tmp; + struct evl_mask_wait *w; + unsigned long flags; + + raw_spin_lock_irqsave(&event->wait_queue.wchan.lock, flags); + + /* + * NOTE: the only reasons we still have state->u.event.value + * as an atomic value ATM is strictly for ABI preservation, + * and allow for peeking at the mask value directly from + * userland (which is hardly a common operation and could be + * done differently anyway). We may turn this into a plain + * word when an ABI jump is required from applications for + * some compelling reason. + */ + atomic_or(bits, __ATOMIC32(&state->u.event.value)); + + evl_for_each_waiter_safe(waiter, tmp, &event->wait_queue) { + w = waiter->wait_data; + waitval = w->value & atomic_read(__ATOMIC32(&state->u.event.value)); + testval = w->exact_match ? w->value : waitval; + if (waitval && waitval == testval) { + w->value = waitval; + consumed |= waitval; + evl_wake_up(&event->wait_queue, waiter, 0); + if (!bcast) + break; + } + } + + if (consumed) + atomic_andnot(consumed, __ATOMIC32(&state->u.event.value)); + + val = atomic_read(__ATOMIC32(&state->u.event.value)); + + raw_spin_unlock_irqrestore(&event->wait_queue.wchan.lock, flags); + + evl_signal_poll_events(&event->poll_head, + val ? POLLIN|POLLRDNORM : POLLOUT|POLLWRNORM); + + evl_schedule(); + + /* + * Now wake up any in-band waiter if we still have events to + * consume. + */ + smp_mb(); + if (val && waitqueue_active(&event->inband_wait_r)) { + if (running_inband()) { + wake_up(&event->inband_wait_r); + } else { + evl_get_element(&event->element); + if (!irq_work_queue(&event->inband_wake_r)) + evl_put_element(&event->element); + } + } + + return 0; +} + +static int wait_gated_event(struct evl_monitor *event, + struct evl_monitor_waitreq *req, + ktime_t timeout, + enum evl_tmode tmode, + s32 *r_op_ret) +{ + struct evl_thread *curr = evl_current(); + struct evl_monitor *gate; + int ret = 0, op_ret = 0; + struct evl_file *efilp; + unsigned long flags; + struct evl_rq *rq; + + if (event->protocol != EVL_EVENT_GATED) { + op_ret = -EINVAL; + goto out; + } + + /* Find the gate monitor protecting us. */ + gate = get_monitor_by_fd(req->gatefd, &efilp); + if (gate == NULL) { + op_ret = -EINVAL; + goto out; + } + + if (gate->type != EVL_MONITOR_GATE) { + op_ret = -EINVAL; + goto put; + } + + /* Make sure we actually passed the gate. */ + if (!evl_is_mutex_owner(gate->mutex.fastlock, fundle_of(curr))) { + op_ret = -EPERM; + goto put; + } + + raw_spin_lock_irqsave(&gate->lock, flags); + + /* + * Track event monitors the gate protects. When multiple + * threads issue concurrent wait requests on the same event + * monitor, they must use the same gate to serialize. Don't + * trust userland for maintaining sane tracking info in + * gate_offset, keep event->gate on the kernel side for this. + */ + if (event->gate == NULL) { + list_add_tail(&event->next, &gate->events); + event->gate = gate; + event->state->u.event.gate_offset = evl_shared_offset(gate->state); + } else if (event->gate != gate) { + raw_spin_unlock_irqrestore(&gate->lock, flags); + op_ret = -EBADFD; + goto put; + } + + /* + * Since we still hold the mutex until __exit_monitor() is + * called later on, do not perform the WOLI checks when + * enqueuing. + */ + raw_spin_lock(&event->wait_queue.wchan.lock); + evl_add_wait_queue_unchecked(&event->wait_queue, timeout, tmode); + raw_spin_unlock(&event->wait_queue.wchan.lock); + + rq = evl_get_thread_rq_noirq(curr); + curr->info &= ~EVL_T_SIGNAL; + evl_put_thread_rq_noirq(curr, rq); + + __exit_monitor(gate, curr); /* See comment in exit_monitor(). */ + + raw_spin_unlock_irqrestore(&gate->lock, flags); + + /* + * Actually wait on the event. If a break condition is raised + * such as an inband signal pending, do not attempt to + * reacquire the gate lock just yet as this might block + * indefinitely (in theory) and we want the inband signal to + * be handled asap. So exit to user mode, allowing any pending + * signal to be handled during the transition, then expect + * userland to issue UNWAIT to recover (or exit, whichever + * comes first). + * + * Consequently, disable syscall restart from kernel upon + * interrupted wait, because the caller does not hold the + * mutex until UNWAIT happens. + */ + ret = evl_wait_schedule(&event->wait_queue); + if (ret) { + raw_spin_lock_irqsave(&gate->lock, flags); + raw_spin_lock(&event->wait_queue.wchan.lock); + untrack_event(event, gate); + raw_spin_unlock(&event->wait_queue.wchan.lock); + raw_spin_unlock_irqrestore(&gate->lock, flags); + + /* + * Disable syscall restart upon signal (only), user + * receives -EINTR and a zero status in this case. If + * the caller was forcibly unblocked for any other + * reason, both the return value and the status word + * are set to -EINTR. + */ + if (ret == -EINTR && signal_pending(current)) { + curr->local_info |= EVL_T_NORST; + goto put; + } + op_ret = ret; + if (ret == -EIDRM) + goto put; + } + + ret = __enter_monitor(gate, NULL); + if (ret == -EINTR) { + if (signal_pending(current)) + curr->local_info |= EVL_T_NORST; + op_ret = -EAGAIN; + } +put: + evl_put_file(efilp); +out: + *r_op_ret = op_ret; + + return ret; +} + +static int wait_monitor(struct file *filp, + struct evl_monitor_waitreq *req, + struct timespec64 *ts64, + s32 *r_op_ret, + s32 *r_value, + bool exact_match) +{ + struct evl_monitor *event = element_of(filp, struct evl_monitor); + enum evl_tmode tmode; + ktime_t timeout; + + if (event->type != EVL_MONITOR_EVENT) { + *r_op_ret = -EINVAL; + return 0; + } + + timeout = timespec64_to_ktime(*ts64); + tmode = timeout ? EVL_ABS : EVL_REL; + + if (req->gatefd < 0) { + switch (event->protocol) { + case EVL_EVENT_COUNT: + *r_op_ret = wait_count(filp, timeout, tmode); + break; + case EVL_EVENT_MASK: + *r_op_ret = wait_mask_oob(filp, timeout, tmode, req->value, + exact_match, r_value); + break; + default: + *r_op_ret = -EINVAL; + } + return *r_op_ret; + } + + return wait_gated_event(event, req, timeout, tmode, r_op_ret); +} + +static int unwait_monitor(struct evl_monitor *event, + struct evl_monitor_unwaitreq *req) +{ + struct evl_monitor *gate; + struct evl_file *efilp; + int ret; + + if (event->type != EVL_MONITOR_EVENT) + return -EINVAL; + + /* Find the gate monitor we need to re-acquire. */ + gate = get_monitor_by_fd(req->gatefd, &efilp); + if (gate == NULL) + return -EINVAL; + + ret = enter_monitor(gate, NULL); + + evl_put_file(efilp); + + return ret; +} + +static long monitor_common_ioctl(struct file *filp, unsigned int cmd, + unsigned long arg) +{ + struct evl_monitor *event = element_of(filp, struct evl_monitor); + struct evl_monitor_trywaitreq twreq, __user *u_twreq; + bool bcast = false, exact_match = false; + __s32 value; + int ret; + + if (event->type != EVL_MONITOR_EVENT) + return -EINVAL; + + switch (cmd) { + case EVL_MONIOC_BROADCAST: + bcast = true; + fallthrough; + case EVL_MONIOC_SIGNAL: + if (raw_get_user(value, (__s32 __user *)arg)) + return -EFAULT; + switch (event->protocol) { + case EVL_EVENT_COUNT: + ret = post_count(event, value, bcast); + break; + case EVL_EVENT_MASK: + ret = post_mask(event, value, bcast); + break; + default: + ret = -EINVAL; + } + break; + case EVL_MONIOC_TRYWAIT_EXACT: + exact_match = true; + fallthrough; + case EVL_MONIOC_TRYWAIT: + u_twreq = (typeof(u_twreq))arg; + ret = raw_copy_from_user(&twreq, u_twreq, sizeof(twreq)); + if (ret) + return -EFAULT; + switch (event->protocol) { + case EVL_EVENT_COUNT: + ret = trywait_count(event); + break; + case EVL_EVENT_MASK: + ret = trywait_mask_oob(event, twreq.value, exact_match, &value); + if (!ret) + raw_put_user(value, &u_twreq->value); + break; + default: + ret = -EINVAL; + } + break; + default: + ret = -ENOTTY; + } + + return ret; +} + +static long monitor_ioctl(struct file *filp, unsigned int cmd, + unsigned long arg) +{ + struct evl_monitor *mon = element_of(filp, struct evl_monitor); + struct evl_monitor_binding bind, __user *u_bind; + + if (cmd != EVL_MONIOC_BIND) + return monitor_common_ioctl(filp, cmd, arg); + + bind.type = mon->type; + bind.protocol = mon->protocol; + bind.eids.minor = mon->element.minor; + bind.eids.state_offset = evl_shared_offset(mon->state); + bind.eids.fundle = fundle_of(mon); + u_bind = (typeof(u_bind))arg; + + return copy_to_user(u_bind, &bind, sizeof(bind)) ? -EFAULT : 0; +} + +static long monitor_oob_ioctl(struct file *filp, unsigned int cmd, + unsigned long arg) +{ + struct evl_monitor *mon = element_of(filp, struct evl_monitor); + struct evl_monitor_unwaitreq uwreq, __user *u_uwreq; + struct evl_monitor_waitreq wreq, __user *u_wreq; + struct __evl_timespec __user *u_uts; + struct __evl_timespec uts = { + .tv_sec = 0, + .tv_nsec = 0, + }; + bool exact_match = false; + struct timespec64 ts64; + s32 op_ret, value = 0; + long ret; + + switch (cmd) { + case EVL_MONIOC_WAIT_EXACT: + exact_match = true; + fallthrough; + case EVL_MONIOC_WAIT: + u_wreq = (typeof(u_wreq))arg; + ret = raw_copy_from_user(&wreq, u_wreq, sizeof(wreq)); + if (ret) + return -EFAULT; + u_uts = evl_valptr64(wreq.timeout_ptr, struct __evl_timespec); + ret = raw_copy_from_user(&uts, u_uts, sizeof(uts)); + if (ret) + return -EFAULT; + if ((unsigned long)uts.tv_nsec >= ONE_BILLION) + return -EINVAL; + ts64 = u_timespec_to_timespec64(uts); + ret = wait_monitor(filp, &wreq, &ts64, &op_ret, &value, exact_match); + raw_put_user(op_ret, &u_wreq->status); + if (!ret && !op_ret) + raw_put_user(value, &u_wreq->value); + break; + case EVL_MONIOC_UNWAIT: + u_uwreq = (typeof(u_uwreq))arg; + ret = raw_copy_from_user(&uwreq, u_uwreq, sizeof(uwreq)); + if (ret) + return -EFAULT; + ret = unwait_monitor(mon, &uwreq); + break; + case EVL_MONIOC_ENTER: + u_uts = (typeof(u_uts))arg; + ret = raw_copy_from_user(&uts, u_uts, sizeof(uts)); + if (ret) + return -EFAULT; + if ((unsigned long)uts.tv_nsec >= ONE_BILLION) + return -EINVAL; + ts64 = u_timespec_to_timespec64(uts); + ret = enter_monitor(mon, &ts64); + break; + case EVL_MONIOC_TRYENTER: + ret = tryenter_monitor(mon); + break; + case EVL_MONIOC_EXIT: + ret = exit_monitor(mon); + break; + default: + ret = monitor_common_ioctl(filp, cmd, arg); + } + + return ret; +} + +static void monitor_unwatch(struct evl_poll_head *head) +{ + struct evl_monitor *mon; + + mon = container_of(head, struct evl_monitor, poll_head); + atomic_dec(__ATOMIC32(&mon->state->u.event.pollrefs)); +} + +static __poll_t monitor_oob_poll(struct file *filp, + struct oob_poll_wait *wait) +{ + struct evl_monitor *mon = element_of(filp, struct evl_monitor); + struct evl_monitor_state *state = mon->state; + __poll_t ret = 0; + int val; + + /* + * NOTE: for ungated events, we close a race window by queuing + * the caller into the poll queue _before_ incrementing the + * pollrefs count which userland checks. + */ + switch (mon->type) { + case EVL_MONITOR_EVENT: + switch (mon->protocol) { + case EVL_EVENT_COUNT: + evl_poll_watch(&mon->poll_head, wait, monitor_unwatch); + atomic_inc(__ATOMIC32(&state->u.event.pollrefs)); + if (atomic_read(__ATOMIC32(&state->u.event.value)) > 0) + ret = POLLIN|POLLRDNORM; + break; + case EVL_EVENT_MASK: + evl_poll_watch(&mon->poll_head, wait, monitor_unwatch); + /* + * We need to keep the pollrefs count up to + * date as long as we support legacy ABIs + * (pre-32). + */ + atomic_inc(__ATOMIC32(&state->u.event.pollrefs)); + val = atomic_read(__ATOMIC32(&state->u.event.value)); + /* + * Return POLLIN when some bits are present, + * ready for consumption, or POLLOUT when the + * mask is entirely clear, i.e. no bit to + * consume. + */ + if (val) + ret = POLLIN|POLLRDNORM; + else + ret = POLLOUT|POLLWRNORM; + break; + case EVL_EVENT_GATED: + /* + * The poll interface does not cope with the + * gated event semantics, since we could not + * release the gate protecting the event and + * enter a poll wait atomically to prevent + * missed wakeups. Therefore, polling a gated + * event leads to an error. + */ + ret = POLLERR; + break; + } + break; + case EVL_MONITOR_GATE: + /* + * A mutex should be held only for a short period of + * time, with the locked state appearing as a discrete + * event to users. Assume a gate lock is always + * readable (as "unlocked") then. If this is about + * probing for a mutex state from userland then + * trylock() should be used instead of poll(). + */ + ret = POLLIN|POLLRDNORM; + break; + } + + return ret; +} + +static int monitor_release(struct inode *inode, struct file *filp) +{ + struct evl_monitor *mon = element_of(filp, struct evl_monitor); + + if (mon->type == EVL_MONITOR_EVENT) + evl_flush_wait(&mon->wait_queue, EVL_T_RMID); + else + evl_flush_mutex(&mon->mutex, EVL_T_RMID); + + return evl_release_element(inode, filp); +} + +static ssize_t monitor_read(struct file *filp, char __user *u_buf, + size_t count, loff_t *ppos) +{ + struct evl_monitor *event = element_of(filp, struct evl_monitor); + struct wait_queue_entry wq_entry; + unsigned long flags, ib_flags; + int ret = 0; + s32 val; + + if (event->type != EVL_MONITOR_EVENT || event->protocol != EVL_EVENT_MASK) + return -EINVAL; + + if (count != sizeof(s32)) + return -EINVAL; + + init_wait_entry(&wq_entry, 0); + + for (;;) { + spin_lock_irqsave(&event->inband_wait_r.lock, ib_flags); + raw_spin_lock_irqsave(&event->wait_queue.wchan.lock, flags); + + if (signal_pending(current)) { + ret = -ERESTARTSYS; + break; + } + + if (list_empty(&wq_entry.entry)) + __add_wait_queue(&event->inband_wait_r, &wq_entry); + + /* Disjunctive operation. */ + if (__trywait_mask(event, -1, false, &val, flags)) + goto unlocked; + + if (filp->f_flags & O_NONBLOCK) { + ret = -EAGAIN; + break; + } + + set_current_state(TASK_INTERRUPTIBLE); + raw_spin_unlock_irqrestore(&event->wait_queue.wchan.lock, flags); + spin_unlock_irqrestore(&event->inband_wait_r.lock, ib_flags); + schedule(); + } + + raw_spin_unlock_irqrestore(&event->wait_queue.wchan.lock, flags); +unlocked: + list_del(&wq_entry.entry); + + spin_unlock_irqrestore(&event->inband_wait_r.lock, ib_flags); + + /* + * If we have successfully collected all the bits, send a + * POLLOUT wakeup. + */ + smp_mb(); /* Matches mb in set_current_state() */ + if (!ret && waitqueue_active(&event->inband_wait_w)) + wake_up(&event->inband_wait_w); + + return copy_to_user(u_buf, &val, sizeof(val)) ? -EFAULT : sizeof(val); +} + +static ssize_t monitor_write(struct file *filp, const char __user *u_buf, + size_t count, loff_t *ppos) +{ + struct evl_monitor *event = element_of(filp, struct evl_monitor); + s32 val; + int ret; + + if (event->type != EVL_MONITOR_EVENT || event->protocol != EVL_EVENT_MASK) + return -EINVAL; + + if (count != sizeof(s32)) + return -EINVAL; + + ret = copy_from_user(&val, u_buf, sizeof(val)); + if (ret) + return -EFAULT; + + /* Unicast operation. */ + return post_mask(event, val, false) ?: sizeof(val); +} + +static ssize_t monitor_oob_read(struct file *filp, + char __user *u_buf, size_t count) +{ + struct evl_monitor *event = element_of(filp, struct evl_monitor); + s32 val; + int ret; + + if (event->type != EVL_MONITOR_EVENT || event->protocol != EVL_EVENT_MASK) + return -EINVAL; + + if (count != sizeof(s32)) + return -EINVAL; + + /* Disjunctive operation. */ + ret = wait_mask_oob(filp, EVL_INFINITE, EVL_REL, -1, false, &val); + if (ret) + return ret; + + return copy_to_user(u_buf, &val, sizeof(val)) ? -EFAULT : sizeof(val); +} + +static ssize_t monitor_oob_write(struct file *filp, + const char __user *u_buf, size_t count) +{ + struct evl_monitor *event = element_of(filp, struct evl_monitor); + s32 val; + int ret; + + if (event->type != EVL_MONITOR_EVENT || event->protocol != EVL_EVENT_MASK) + return -EINVAL; + + if (count != sizeof(s32)) + return -EINVAL; + + ret = copy_from_user(&val, u_buf, sizeof(val)); + if (ret) + return -EFAULT; + + /* Unicast operation. */ + return post_mask(event, val, false) ?: sizeof(val); +} + +static __poll_t monitor_poll(struct file *filp, poll_table *wait) +{ + struct evl_monitor *event = element_of(filp, struct evl_monitor); + __poll_t ret = 0; + int val; + + if (event->type != EVL_MONITOR_EVENT || event->protocol != EVL_EVENT_MASK) + return -EINVAL; + + poll_wait(filp, &event->inband_wait_r, wait); + poll_wait(filp, &event->inband_wait_w, wait); + + val = atomic_read(__ATOMIC32(&event->state->u.event.value)); + if (val) + ret |= POLLIN|POLLRDNORM; + else + ret |= POLLOUT|POLLWRNORM; + + return ret; +} + +static const struct file_operations monitor_fops = { + .open = evl_open_element, + .release = monitor_release, + .read = monitor_read, + .write = monitor_write, + .poll = monitor_poll, + .unlocked_ioctl = monitor_ioctl, + .oob_read = monitor_oob_read, + .oob_write = monitor_oob_write, + .oob_ioctl = monitor_oob_ioctl, + .oob_poll = monitor_oob_poll, +#ifdef CONFIG_COMPAT + .compat_ioctl = compat_ptr_ioctl, + .compat_oob_ioctl = compat_ptr_oob_ioctl, +#endif +}; + +static struct evl_element * +monitor_factory_build(struct evl_factory *fac, const char __user *u_name, + void __user *u_attrs, int clone_flags, u32 *state_offp) +{ + struct evl_monitor_state *state; + struct evl_monitor_attrs attrs; + struct evl_monitor *mon; + struct evl_clock *clock; + int ret; + + if (clone_flags & ~EVL_CLONE_PUBLIC) + return ERR_PTR(-EINVAL); + + ret = copy_from_user(&attrs, u_attrs, sizeof(attrs)); + if (ret) + return ERR_PTR(-EFAULT); + + switch (attrs.type) { + case EVL_MONITOR_GATE: + switch (attrs.protocol) { + case EVL_GATE_PP: + if (attrs.initval == 0 || + attrs.initval > EVL_FIFO_MAX_PRIO) + return ERR_PTR(-EINVAL); + break; + case EVL_GATE_PI: + if (attrs.initval) + return ERR_PTR(-EINVAL); + break; + default: + return ERR_PTR(-EINVAL); + } + break; + case EVL_MONITOR_EVENT: + switch (attrs.protocol) { + case EVL_EVENT_GATED: + case EVL_EVENT_COUNT: + case EVL_EVENT_MASK: + break; + default: + return ERR_PTR(-EINVAL); + } + break; + default: + return ERR_PTR(-EINVAL); + } + + clock = evl_get_clock_by_fd(attrs.clockfd); + if (clock == NULL) + return ERR_PTR(-EINVAL); + + mon = kzalloc(sizeof(*mon), GFP_KERNEL); + if (mon == NULL) { + ret = -ENOMEM; + goto fail_alloc; + } + + ret = evl_init_user_element(&mon->element, &evl_monitor_factory, + u_name, clone_flags); + if (ret) + goto fail_element; + + state = evl_zalloc_chunk(&evl_shared_heap, sizeof(*state)); + if (state == NULL) { + ret = -ENOMEM; + goto fail_heap; + } + + switch (attrs.type) { + case EVL_MONITOR_GATE: + switch (attrs.protocol) { + case EVL_GATE_PP: + state->u.gate.ceiling = attrs.initval; + evl_init_mutex_pp(&mon->mutex, clock, + __ATOMIC32(&state->u.gate.owner), + &state->u.gate.ceiling); + break; + case EVL_GATE_PI: + evl_init_mutex_pi(&mon->mutex, clock, + __ATOMIC32(&state->u.gate.owner)); + break; + } + raw_spin_lock_init(&mon->lock); + INIT_LIST_HEAD(&mon->events); + break; + case EVL_MONITOR_EVENT: + evl_init_wait(&mon->wait_queue, clock, EVL_WAIT_PRIO); + state->u.event.gate_offset = EVL_MONITOR_NOGATE; + atomic_set(__ATOMIC32(&state->u.event.value), attrs.initval); + evl_init_poll_head(&mon->poll_head); + init_waitqueue_head(&mon->inband_wait_r); + init_waitqueue_head(&mon->inband_wait_w); + init_irq_work(&mon->inband_wake_r, inband_wake_r_irqwork); + init_irq_work(&mon->inband_wake_w, inband_wake_w_irqwork); + } + + /* + * The type information is critical for the kernel sanity, + * don't allow userland to mess with it, so don't trust the + * shared state for this. + */ + mon->type = attrs.type; + mon->protocol = attrs.protocol; + mon->state = state; + *state_offp = evl_shared_offset(state); + evl_index_factory_element(&mon->element); + + return &mon->element; + +fail_heap: + evl_destroy_element(&mon->element); +fail_element: + kfree(mon); +fail_alloc: + evl_put_clock(clock); + + return ERR_PTR(ret); +} + +static void monitor_factory_dispose(struct evl_element *e) +{ + struct evl_monitor *mon; + unsigned long flags; + + mon = container_of(e, struct evl_monitor, element); + + evl_unindex_factory_element(&mon->element); + + if (mon->type == EVL_MONITOR_EVENT) { + evl_put_clock(mon->wait_queue.clock); + evl_destroy_wait(&mon->wait_queue); + if (mon->gate) { + raw_spin_lock_irqsave(&mon->gate->lock, flags); + list_del(&mon->next); + raw_spin_unlock_irqrestore(&mon->gate->lock, flags); + } + } else { + evl_put_clock(mon->mutex.clock); + evl_destroy_mutex(&mon->mutex); + } + + evl_free_chunk(&evl_shared_heap, mon->state); + evl_destroy_element(&mon->element); + kfree_rcu(mon, element.rcu); +} + +static ssize_t state_show(struct device *dev, + struct device_attribute *attr, + char *buf) +{ + struct evl_monitor_state *state; + struct evl_thread *owner = NULL; + struct evl_monitor *mon; + ssize_t ret = 0; + fundle_t fun; + + mon = evl_get_element_by_dev(dev, struct evl_monitor); + if (mon == NULL) + return -EIO; + + state = mon->state; + + if (mon->type == EVL_MONITOR_EVENT) { + switch (mon->protocol) { + case EVL_EVENT_MASK: + ret = snprintf(buf, PAGE_SIZE, "%#x\n", + atomic_read(__ATOMIC32(&state->u.event.value))); + break; + case EVL_EVENT_COUNT: + ret = snprintf(buf, PAGE_SIZE, "%d\n", + atomic_read(__ATOMIC32(&state->u.event.value))); + break; + case EVL_EVENT_GATED: + ret = snprintf(buf, PAGE_SIZE, "%#x\n", + state->flags); + break; + } + } else { + fun = atomic_read(__ATOMIC32(&state->u.gate.owner)); + if (fun != EVL_NO_HANDLE) { + owner = evl_get_factory_element_by_fundle(&evl_thread_factory, + evl_get_index(fun), + struct evl_thread); + if (!owner) + goto no_owner; + ret = snprintf(buf, PAGE_SIZE, "%s(%d) %u %u\n", + evl_element_name(&owner->element), + evl_get_inband_pid(owner), + state->u.gate.ceiling, + state->u.gate.recursive ? state->u.gate.nesting : 1); + evl_put_element(&owner->element); + } else { + no_owner: + ret = snprintf(buf, PAGE_SIZE, "-1 %u 0\n", + state->u.gate.ceiling); + } + } + + evl_put_element(&mon->element); + + return ret; +} +static DEVICE_ATTR_RO(state); + +static struct attribute *monitor_attrs[] = { + &dev_attr_state.attr, + NULL, +}; +ATTRIBUTE_GROUPS(monitor); + +struct evl_factory evl_monitor_factory = { + .name = EVL_MONITOR_DEV, + .fops = &monitor_fops, + .build = monitor_factory_build, + .dispose = monitor_factory_dispose, + .nrdev = CONFIG_EVL_NR_MONITORS, + .attrs = monitor_groups, + .flags = EVL_FACTORY_CLONE, +}; diff --git a/kernel/evl/mutex.c b/kernel/evl/mutex.c new file mode 100644 index 000000000..aa3205905 --- /dev/null +++ b/kernel/evl/mutex.c @@ -0,0 +1,842 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Derived from Xenomai Cobalt, https://xenomai.org/ + * Copyright (C) 2001, 2019, 2022 Philippe Gerum + * Copyright (C) 2008, 2009 Jan Kiszka . + */ + +#include +#include +#include +#include +#include +#include +#include + +#define for_each_evl_mutex_waiter(__pos, __mutex) \ + list_for_each_entry(__pos, &(__mutex)->wchan.wait_list, wait_next) + +void __evl_init_mutex(struct evl_mutex *mutex, + struct evl_clock *clock, + atomic_t *fastlock, u32 *ceiling, + const char *name, + struct lock_class_key *lock_key) +{ + int type = ceiling ? EVL_MUTEX_PP : EVL_MUTEX_PI; + + mutex->fastlock = fastlock; + atomic_set(fastlock, EVL_NO_HANDLE); + mutex->flags = type; + mutex->boost.wprio = -1; + mutex->boost.sched_class = NULL; + mutex->ceiling_addr = ceiling; + mutex->clock = clock; + mutex->wchan.owner = NULL; + mutex->wchan.requeue_wait = evl_requeue_mutex_wait; + mutex->wchan.name = name; + INIT_LIST_HEAD(&mutex->wchan.wait_list); + raw_spin_lock_init(&mutex->wchan.lock); + lockdep_set_class_and_name(&mutex->wchan.lock, lock_key, name); + might_hard_lock(&mutex->wchan.lock); +} +EXPORT_SYMBOL_GPL(__evl_init_mutex); + +/* mutex->wchan.lock held, irqs off. */ +static inline +void disable_inband_switch(struct evl_thread *curr, struct evl_mutex *mutex) +{ + /* + * Track mutex locking depth: 1) to prevent weak threads from + * being switched back to in-band context on return from OOB + * syscalls, 2) when locking consistency is being checked. + */ + if (unlikely(curr->state & (EVL_T_WEAK|EVL_T_WOLI))) { + atomic_inc(&curr->held_mutex_count); + mutex->flags |= EVL_MUTEX_COUNTED; + } +} + +/* mutex->wchan.lock held, irqs off. */ +static inline +void enable_inband_switch(struct evl_thread *curr, struct evl_mutex *mutex) +{ + if (unlikely(mutex->flags & EVL_MUTEX_COUNTED)) { + mutex->flags &= ~EVL_MUTEX_COUNTED; + if (atomic_dec_return(&curr->held_mutex_count) < 0) { + atomic_set(&curr->held_mutex_count, 0); + EVL_WARN_ON(CORE, 1); + } + } +} + +static inline int fast_mutex_is_claimed(fundle_t handle) +{ + return (handle & EVL_MUTEX_FLCLAIM) != 0; +} + +static inline fundle_t mutex_fast_claim(fundle_t handle) +{ + return handle | EVL_MUTEX_FLCLAIM; +} + +static inline fundle_t mutex_fast_ceil(fundle_t handle) +{ + return handle | EVL_MUTEX_FLCEIL; +} + +/* mutex->wchan.lock + owner->lock held, irqs off. */ +static void track_mutex_owner(struct evl_mutex *mutex, struct evl_thread *owner) +{ + struct evl_thread *prev = mutex->wchan.owner; + + assert_hard_lock(&mutex->wchan.lock); + assert_hard_lock(&owner->lock); + + if (prev) { + if (EVL_WARN_ON(CORE, prev == owner)) + return; + list_del(&mutex->next_owned); + evl_put_element(&prev->element); + } + + list_add(&mutex->next_owned, &owner->owned_mutexes); + mutex->wchan.owner = owner; +} + +/* mutex->wchan.lock held, irqs off */ +static void untrack_mutex_owner(struct evl_mutex *mutex) +{ + struct evl_thread *owner = mutex->wchan.owner; + + assert_hard_lock(&mutex->wchan.lock); + + if (owner) { + raw_spin_lock(&owner->lock); + list_del(&mutex->next_owned); + mutex->wchan.owner = NULL; + raw_spin_unlock(&owner->lock); + evl_put_element(&owner->element); + } +} + +/* + * mutex.wchan->lock, irqs off. + * + * Make the owner field of a mutex refer to the current thread, + * applying the PP boost to the latter if need be. + */ +static void set_mutex_owner(struct evl_mutex *mutex) +{ + struct evl_thread *curr = evl_current(); + + assert_hard_lock(&mutex->wchan.lock); + + raw_spin_lock(&curr->lock); + + if (mutex->wchan.owner != curr) { + track_mutex_owner(mutex, curr); + evl_get_element(&curr->element); + } + + /* + * In case of a PP mutex, adjustment takes place only upon + * priority increase. BEWARE: not only this restriction is + * required to keep the PP logic right, but this is also a + * basic assumption made by all callers of + * evl_commit_monitor_ceiling() which won't check for any + * rescheduling opportunity upon return. However, we still do + * want the mutex to be linked to the new owner's booster + * list. + * + * Since the owner is current, there is no way it could be + * pending on a wait channel, so don't bother branching to + * evl_adjust_wait_priority(). + */ + if (mutex->flags & EVL_MUTEX_PP) { + int wprio = evl_calc_weighted_prio(&evl_sched_fifo, + evl_ceiling_priority(mutex)); + mutex->boost.wprio = wprio; + mutex->boost.sched_class = NULL; /* Unused for PP. */ + list_add_priff(mutex, &curr->boosters, boost.wprio, next_booster); + mutex->flags |= EVL_MUTEX_CEILING; + if (wprio > curr->wprio) + evl_adjust_thread_boost(curr); + } + + raw_spin_unlock(&curr->lock); +} + +static inline +fundle_t get_owner_handle(fundle_t ownerh, struct evl_mutex *mutex) +{ + /* + * On acquisition from kernel space, the fast lock handle + * should bear the FLCEIL bit for PP mutexes, so that userland + * takes the slow path on release, jumping to the kernel for + * dropping the ceiling priority boost. + */ + if (mutex->flags & EVL_MUTEX_PP) + ownerh = mutex_fast_ceil(ownerh); + + return ownerh; +} + +/* + * Fast path: try to give mutex to the current thread. We hold no lock + * on entry, irqs are on. + */ +static int fast_grab_mutex(struct evl_mutex *mutex, fundle_t *oldh) +{ + struct evl_thread *curr = evl_current(); + fundle_t currh = fundle_of(curr), newh; + unsigned long flags; + + /* + * Try grabbing the mutex via CAS. Upon success, we will be + * tracking it, and other threads might be waiting for us to + * release it as well. So we have to raise FLCLAIM in the + * atomic handle, so that user-space does not succeed in fast + * unlocking but jumps back to the kernel instead, allowing us + * to do the required housekeeping chores upon unlock. + */ + newh = mutex_fast_claim(get_owner_handle(currh, mutex)); + *oldh = atomic_cmpxchg(mutex->fastlock, EVL_NO_HANDLE, newh); + if (*oldh != EVL_NO_HANDLE) + return evl_get_index(*oldh) == currh ? -EDEADLK : -EBUSY; + + /* Success, we have ownership now. */ + raw_spin_lock_irqsave(&mutex->wchan.lock, flags); + + /* + * Update the owner information for mutex so that it belongs + * to the current thread, applying any PP boost if applicable. + */ + set_mutex_owner(mutex); + + disable_inband_switch(curr, mutex); + + raw_spin_unlock_irqrestore(&mutex->wchan.lock, flags); + + return 0; +} + +/* mutex->wchan.lock held (temporarily dropped), irqs off */ +static void drop_booster(struct evl_mutex *mutex, bool release) +{ + struct evl_thread *owner; + bool adjusted; + + assert_hard_lock(&mutex->wchan.lock); + owner = mutex->wchan.owner; + + if (EVL_WARN_ON(CORE, !owner)) + return; + + /* + * Unlink the mutex from the list of boosters held by @owner, + * adjusting its priority according to the boosters it still + * holds. + */ + evl_get_element(&owner->element); + + if (release) /* Drop upon release sequence? */ + untrack_mutex_owner(mutex); + + raw_spin_lock(&owner->lock); + list_del(&mutex->next_booster); /* owner->boosters */ + mutex->boost.sched_class = NULL; + raw_spin_unlock(&mutex->wchan.lock); + adjusted = evl_adjust_thread_boost(owner); + raw_spin_unlock(&owner->lock); + + if (adjusted) + evl_adjust_wait_priority(owner); + + evl_put_element(&owner->element); + raw_spin_lock(&mutex->wchan.lock); +} + +/* + * Detect when current is about to switch in-band while owning a + * mutex, which is plain wrong since this would create a priority + * inversion. EVL_T_WOLI is set for current. + */ +void evl_check_no_mutex(void) +{ + struct evl_thread *curr = evl_current(); + unsigned long flags; + bool notify; + + raw_spin_lock_irqsave(&curr->lock, flags); + if (!(curr->info & EVL_T_PIALERT)) { + notify = !list_empty(&curr->owned_mutexes); + if (notify) { + raw_spin_lock(&curr->rq->lock); + curr->info |= EVL_T_PIALERT; + raw_spin_unlock(&curr->rq->lock); + } + } + raw_spin_unlock_irqrestore(&curr->lock, flags); + + if (notify) + evl_notify_thread(curr, EVL_HMDIAG_LKDEPEND, evl_nil); +} + +/* mutex->wchan.lock held, irqs off */ +static void flush_mutex_locked(struct evl_mutex *mutex, int reason) +{ + struct evl_thread *waiter, *tmp; + + assert_hard_lock(&mutex->wchan.lock); + + if (list_empty(&mutex->wchan.wait_list)) { + EVL_WARN_ON(CORE, mutex->flags & EVL_MUTEX_PIBOOST); + } else { + list_for_each_entry_safe(waiter, tmp, + &mutex->wchan.wait_list, wait_next) { + list_del_init(&waiter->wait_next); + evl_wakeup_thread(waiter, EVL_T_PEND, reason); + } + + if (mutex->flags & EVL_MUTEX_PIBOOST) { + mutex->flags &= ~EVL_MUTEX_PIBOOST; + drop_booster(mutex, false); + } + } +} + +void evl_flush_mutex(struct evl_mutex *mutex, int reason) +{ + unsigned long flags; + + trace_evl_mutex_flush(mutex); + raw_spin_lock_irqsave(&mutex->wchan.lock, flags); + flush_mutex_locked(mutex, reason); + raw_spin_unlock_irqrestore(&mutex->wchan.lock, flags); + evl_schedule(); +} + +void evl_destroy_mutex(struct evl_mutex *mutex) +{ + unsigned long flags; + + trace_evl_mutex_destroy(mutex); + raw_spin_lock_irqsave(&mutex->wchan.lock, flags); + flush_mutex_locked(mutex, EVL_T_RMID); + untrack_mutex_owner(mutex); + raw_spin_unlock_irqrestore(&mutex->wchan.lock, flags); + evl_schedule(); +} +EXPORT_SYMBOL_GPL(evl_destroy_mutex); + +int evl_trylock_mutex(struct evl_mutex *mutex) +{ + fundle_t oldh; + + oob_context_only(); + + trace_evl_mutex_trylock(mutex); + + return fast_grab_mutex(mutex, &oldh); +} +EXPORT_SYMBOL_GPL(evl_trylock_mutex); + +/* + * Undo the effect of a previous lock chain walk due to an aborted + * wait. The mutex state might have changed under us since we dropped + * mutex->wchan.lock during the walk. If we still have an owner at + * this point, and the mutex is still part of its booster list, then + * we need to consider two cases: + * + * - the mutex still has waiters, in which case we need to adjust the + * boost value to the top waiter priority. + * + * - nobody waits for this mutex anymore, so we may drop it from the + * owner's booster list, adjusting the boost value accordingly too. + * + * mutex->wchan.lock held (dropped at exit), irqs off + * + * NOTE: the caller MUST reschedule. + */ +static void undo_pi_walk(struct evl_mutex *mutex) +{ + struct evl_thread *owner = mutex->wchan.owner; + + if (owner && mutex->flags & EVL_MUTEX_PIBOOST) { + if (list_empty(&mutex->wchan.wait_list)) { + mutex->flags &= ~EVL_MUTEX_PIBOOST; + drop_booster(mutex, false); + } else { + raw_spin_lock(&owner->lock); + raw_spin_unlock(&mutex->wchan.lock); + evl_adjust_thread_boost(owner); + raw_spin_unlock(&owner->lock); + return; + } + } + + raw_spin_unlock(&mutex->wchan.lock); +} + +/* mutex->wchan.lock + mutex->wchan.owner->lock + waiter->lock held, irqs off. */ +static void enqueue_booster(struct evl_mutex *mutex, struct evl_thread *waiter) +{ + struct evl_thread *owner = mutex->wchan.owner; + + assert_hard_lock(&mutex->wchan.lock); + assert_hard_lock(&owner->lock); + assert_hard_lock(&waiter->lock); + + mutex->boost.wprio = waiter->wprio; + mutex->boost.sched_class = waiter->sched_class; + raw_spin_lock(&waiter->rq->lock); + evl_get_schedparam(waiter, &mutex->boost.param); + raw_spin_unlock(&waiter->rq->lock); + list_add_priff(mutex, &owner->boosters, boost.wprio, next_booster); +} + +int evl_lock_mutex_timeout(struct evl_mutex *mutex, ktime_t timeout, + enum evl_tmode timeout_mode) +{ + struct evl_thread *curr = evl_current(), *owner; + atomic_t *lockp = mutex->fastlock; + fundle_t currh, h, oldh; + unsigned long flags; + bool check_dep_only; + int ret; + + oob_context_only(); + + currh = fundle_of(curr); + trace_evl_mutex_lock(mutex); +retry: + ret = fast_grab_mutex(mutex, &h); /* This detects recursion. */ + if (likely(ret != -EBUSY)) + return ret; + + /* + * Well, no luck, mutex is locked and/or claimed already. This + * is the start of the slow path. + */ + ret = 0; + + /* + * As long as mutex->wchan.lock is held and FLCLAIM is set in + * the atomic handle, the thread who might currently own the + * mutex cannot release it directly via the fast release logic + * from user-space, and will therefore have to serialize with + * the current thread in kernel space for doing so. + */ + raw_spin_lock_irqsave(&mutex->wchan.lock, flags); + + /* + * Set claimed bit. In case it appears to be set already, + * re-read its state under mutex->wchan.lock so that we don't + * miss any change between the fast grab attempt and this + * point. But also try to avoid cmpxchg where possible. Only + * if it appears not to be set, start with cmpxchg directly. + */ + if (fast_mutex_is_claimed(h)) { + oldh = atomic_read(lockp); + goto check_if_free; + } + + do { + oldh = atomic_cmpxchg(lockp, h, mutex_fast_claim(h)); + if (likely(oldh == h)) + break; + check_if_free: + if (oldh == EVL_NO_HANDLE) { + /* Lock released from another CPU. */ + raw_spin_unlock_irqrestore(&mutex->wchan.lock, flags); + goto retry; + } + h = oldh; + } while (!fast_mutex_is_claimed(h)); + + /* Fetch the owner as userland sees it. */ + owner = evl_get_factory_element_by_fundle(&evl_thread_factory, + evl_get_index(h), + struct evl_thread); + /* + * The tracked owner disappeared, clear the stale tracking + * data, then fail with -EOWNERDEAD. There is no point in + * trying to clean up that mess any further for userland, the + * logic protected by that lock is dead in the water anyway. + */ + if (owner == NULL) { + untrack_mutex_owner(mutex); + raw_spin_unlock_irqrestore(&mutex->wchan.lock, flags); + return -EOWNERDEAD; + } + + /* + * If the owner information present in the mutex descriptor + * does not match the one available from the atomic handle, it + * means that such mutex was acquired using a fast locking + * operation from userland without involving the kernel, + * therefore we need to reconcile the in-kernel descriptor + * with the shared handle which has the accurate value. If + * both match though, evl_get_factory_element_by_fundle() got + * us another reference on @owner like set_mutex_owner() + * already obtained earlier for that thread, so we need to + * drop it to rebalance the refcount. + * + * The consistency of this information is guaranteed, because + * we just raised the claim bit atomically for this contended + * lock, therefore userland would have to jump to the kernel + * for releasing it, instead of doing a fast unlock. Since we + * currently hold mutex->wchan.lock, consistency wrt + * __evl_unlock_mutex() is guaranteed through explicit + * serialization. + * + * CAUTION: in this particular case, the only assumption we + * may safely make is that *owner is valid and not current on + * this CPU. + */ + if (mutex->wchan.owner != owner) { + raw_spin_lock(&owner->lock); + track_mutex_owner(mutex, owner); + raw_spin_unlock(&owner->lock); + } else { + evl_put_element(&owner->element); + } + + evl_double_thread_lock(curr, owner); + + check_dep_only = true; /* Only check for cyclic dependency. */ + if (mutex->flags & EVL_MUTEX_PI && curr->wprio > owner->wprio) { + if (mutex->flags & EVL_MUTEX_PIBOOST) + list_del(&mutex->next_booster); /* owner->boosters */ + else + mutex->flags |= EVL_MUTEX_PIBOOST; + + enqueue_booster(mutex, curr); + check_dep_only = false; /* Adjust priorities too. */ + } + + /* Walking the chain drops owner->lock. */ + ret = evl_walk_lock_chain(&mutex->wchan, curr, check_dep_only); + assert_hard_lock(&mutex->wchan.lock); + assert_hard_lock(&curr->lock); + if (ret) { + raw_spin_unlock(&curr->lock); + goto fail; + } + + /* + * If the latest owner of this mutex dropped it while we were + * busy walking the lock chain, we should not wait but retry + * acquiring it from the beginning instead. Otherwise, let's + * wait for __evl_unlock_mutex() to notify us of the release. + */ + owner = mutex->wchan.owner; + if (unlikely(!owner)) { + /* + * Since the mutex has no owner, there is no way that + * it could be part of anyone's booster list anymore. + */ + raw_spin_unlock(&curr->lock); + raw_spin_unlock_irqrestore(&mutex->wchan.lock, flags); + goto retry; + } + + raw_spin_unlock(&curr->lock); + list_add_priff(curr, &mutex->wchan.wait_list, wprio, wait_next); + evl_sleep_on(timeout, timeout_mode, mutex->clock, &mutex->wchan); + raw_spin_unlock_irqrestore(&mutex->wchan.lock, flags); + ret = __evl_wait_schedule(&mutex->wchan); + /* If something went wrong while sleeping, bail out. */ + if (ret) { + raw_spin_lock_irqsave(&mutex->wchan.lock, flags); + goto fail; + } + + /* + * Otherwise, this means __evl_unlock_mutex() unblocked us, so + * we just need to retry grabbing the mutex. Keep in mind that + * __evl_unlock_mutex() dropped the mutex from the previous + * owner's booster list before unblocking us, so we do not + * have to revert the effects of our lock chain walk. + */ + evl_schedule(); + goto retry; +fail: + /* + * On error, we may have done a partial boost of the lock + * chain, so we need to carefully revert this, then reschedule + * to apply any priority change. + */ + undo_pi_walk(mutex); + hard_local_irq_enable(); + evl_schedule(); + + return ret; +} +EXPORT_SYMBOL_GPL(evl_lock_mutex_timeout); + +/* wchan->lock held, irqs off. */ +static void wakeup_and_release(struct evl_mutex *mutex) +{ + struct evl_thread *top_waiter; + + /* + * Allow the top waiter in line to retry acquiring the mutex. + */ + if (!list_empty(&mutex->wchan.wait_list)) { + top_waiter = list_get_entry_init(&mutex->wchan.wait_list, + struct evl_thread, wait_next); + evl_wakeup_thread(top_waiter, EVL_T_PEND, 0); + } + + /* + * Make the change visible to everyone including user-space + * once the kernel state is in sync. + */ + atomic_set(mutex->fastlock, EVL_NO_HANDLE); +} + +void __evl_unlock_mutex(struct evl_mutex *mutex) +{ + struct evl_thread *curr = evl_current(); + unsigned long flags; + + trace_evl_mutex_unlock(mutex); + + raw_spin_lock_irqsave(&mutex->wchan.lock, flags); + + /* + * We might have acquired the lock earlier from user-space via + * the fast procedure, releasing it now from kernel space - + * this pattern typically happens with the event monitor, + * e.g. fast_lock(x) -> signal(event) -> slow_unlock(x). In + * this case, the owner field into the wait channel might be + * unset if the lock was uncontended, although our caller has + * checked that the atomic handle does match current's + * fundle. If so, skip the PI/PP deboosting, no boost can be + * in effect for such lock. + */ + if (mutex->wchan.owner == NULL) { + wakeup_and_release(mutex); + goto out; + } + + if (EVL_WARN_ON(CORE, mutex->wchan.owner != curr)) + goto out; + + enable_inband_switch(curr, mutex); + + /* + * The released mutex can no longer be a booster for the + * current thread, remove it from its booster list if queued + * there. + */ + if (mutex->flags & EVL_MUTEX_CEILING) { + EVL_WARN_ON(CORE, mutex->flags & EVL_MUTEX_PIBOOST); + mutex->flags &= ~EVL_MUTEX_CEILING; + wakeup_and_release(mutex); + drop_booster(mutex, true); + } else if (mutex->flags & EVL_MUTEX_PIBOOST) { + EVL_WARN_ON(CORE, mutex->flags & EVL_MUTEX_CEILING); + mutex->flags &= ~EVL_MUTEX_PIBOOST; + wakeup_and_release(mutex); + drop_booster(mutex, true); + } else { + /* Clear the owner information only. */ + untrack_mutex_owner(mutex); + wakeup_and_release(mutex); + } + +out: + raw_spin_unlock_irqrestore(&mutex->wchan.lock, flags); + + /* + * Check for spuriously lingering PI/PP boosts. This check + * happens here and in the rescheduling procedure too in order + * to cover cases which would -wrongly- skip the in-kernel + * unlock path. + */ + if (IS_ENABLED(CONFIG_EVL_DEBUG_CORE)) { + bool bad; + raw_spin_lock_irqsave(&curr->lock, flags); + bad = curr->state & EVL_T_BOOST && list_empty(&curr->boosters); + raw_spin_unlock_irqrestore(&curr->lock, flags); + EVL_WARN_ON_ONCE(CORE, bad); + } +} + +void evl_unlock_mutex(struct evl_mutex *mutex) +{ + struct evl_thread *curr = evl_current(); + fundle_t currh = fundle_of(curr), h; + + oob_context_only(); + + h = evl_get_index(atomic_read(mutex->fastlock)); + if (h != currh) { + if (curr->state & EVL_T_USER) { + if (curr->state & EVL_T_WOLI) + evl_notify_thread(curr, EVL_HMDIAG_LKIMBALANCE, evl_nil); + } else { + EVL_WARN_ON(CORE, 1); + } + return; + } + + __evl_unlock_mutex(mutex); + evl_schedule(); +} +EXPORT_SYMBOL_GPL(evl_unlock_mutex); + +/* + * Release all mutexes the current (exiting) thread owns. + * + * No lock held, irqs on. + */ +void evl_drop_current_ownership(void) +{ + struct evl_thread *curr = evl_current(); + struct evl_mutex *mutex; + unsigned long flags; + + raw_spin_lock_irqsave(&curr->lock, flags); + + while (!list_empty(&curr->owned_mutexes)) { + mutex = list_first_entry(&curr->owned_mutexes, + struct evl_mutex, next_owned); + raw_spin_unlock_irqrestore(&curr->lock, flags); + /* This removes @mutex from curr->owned_mutexes. */ + __evl_unlock_mutex(mutex); + raw_spin_lock_irqsave(&curr->lock, flags); + } + + raw_spin_unlock_irqrestore(&curr->lock, flags); + + evl_schedule(); +} + +static inline struct evl_mutex * +wchan_to_mutex(struct evl_wait_channel *wchan) +{ + return container_of(wchan, struct evl_mutex, wchan); +} + +/* wchan->lock + waiter->lock held, irqs off. */ +bool evl_requeue_mutex_wait(struct evl_wait_channel *wchan, + struct evl_thread *waiter) +{ + struct evl_thread *owner = wchan->owner, *top_waiter; + struct evl_mutex *mutex = wchan_to_mutex(wchan); + bool ret = true; + + assert_hard_lock(&wchan->lock); + assert_hard_lock(&waiter->lock); + + /* + * Make sure the waiter did not abort wait on wchan while + * unlocked; this might happen since evl_wakeup_thread() would + * be allowed to run, clearing waiter->wchan when called upon + * a timeout/break/rmid condition, before such thread resumes + * and dequeues itself from wchan eventually (in + * __evl_wait_schedule()). + * + * We have been holding wchan->lock across the unlocked + * section, so we know that wchan did not go stale though. + */ + if (waiter->wchan != wchan) + return false; + + /* + * __evl_unlock_mutex() may run concurrently to us, dropping + * ownership. Make sure we still have an owner. + */ + if (owner == NULL) { + list_del(&waiter->wait_next); + list_add_priff(waiter, &wchan->wait_list, wprio, wait_next); + return false; + } + + /* + * To prevent ABBA, we may drop the waiter lock prior to + * reacquiring it in a double locking sequence along with + * wchan->owner->lock which we need to requeue the booster. + */ + raw_spin_unlock(&waiter->lock); + evl_double_thread_lock(waiter, owner); + + /* + * Reorder the wait list according to the (updated) priority + * of the waiter, then requeue the booster accordingly. + */ + list_del(&waiter->wait_next); + list_add_priff(waiter, &wchan->wait_list, wprio, wait_next); + if (mutex->flags & EVL_MUTEX_PIBOOST) { + top_waiter = list_first_entry(&mutex->wchan.wait_list, + struct evl_thread, wait_next); + if (mutex->boost.wprio != top_waiter->wprio) { + /* Requeue booster at the right place. */ + list_del(&mutex->next_booster); + enqueue_booster(mutex, top_waiter); + } + } + + raw_spin_unlock(&owner->lock); + + return ret; +} +EXPORT_SYMBOL_GPL(evl_requeue_mutex_wait); + +void evl_commit_mutex_ceiling(struct evl_mutex *mutex) +{ + struct evl_thread *curr = evl_current(); + atomic_t *lockp = mutex->fastlock; + unsigned long flags; + fundle_t oldh, h; + + raw_spin_lock_irqsave(&mutex->wchan.lock, flags); + + /* + * For PP locks, userland does, in that order: + * + * -- LOCK + * 1. curr->u_window->pp_pending = fundle_of(mutex) + * barrier(); + * 2. atomic_cmpxchg(lockp, EVL_NO_HANDLE, fundle_of(curr)); + * + * -- UNLOCK + * 1. atomic_cmpxchg(lockp, fundle_of(curr), EVL_NO_HANDLE); [unclaimed] + * barrier(); + * 2. curr->u_window->pp_pending = EVL_NO_HANDLE + * + * Make sure we have not been caught in a rescheduling in + * between those steps. If we did, then we won't be holding + * the lock as we schedule away, therefore no priority update + * must take place. + * + * We might be called multiple times for committing a lazy + * ceiling for the same mutex, e.g. if userland is preempted + * in the middle of a recursive locking sequence. + * + * This would stem from the fact that userland has to update + * ->pp_pending prior to trying to grab the lock atomically, + * at which point it can figure out whether a recursive + * locking happened. We get out of this trap by testing the + * EVL_MUTEX_CEILING flag. + */ + if (!evl_is_mutex_owner(lockp, fundle_of(curr)) || + (mutex->flags & EVL_MUTEX_CEILING)) + goto out; + + set_mutex_owner(mutex); + /* + * Raise FLCEIL, which indicates a kernel entry will be + * required for releasing this resource. + */ + do { + h = atomic_read(lockp); + oldh = atomic_cmpxchg(lockp, h, mutex_fast_ceil(h)); + } while (oldh != h); +out: + raw_spin_unlock_irqrestore(&mutex->wchan.lock, flags); +} diff --git a/kernel/evl/net/Makefile b/kernel/evl/net/Makefile new file mode 100644 index 000000000..b5fd52780 --- /dev/null +++ b/kernel/evl/net/Makefile @@ -0,0 +1,5 @@ +obj-$(CONFIG_EVL_NET) += ethernet/ packet/ ipv4/ qdisc/ + +obj-$(CONFIG_EVL_NET) += networking.o + +networking-y := net.o socket.o dev.o input.o output.o skb.o route.o diff --git a/kernel/evl/net/dev.c b/kernel/evl/net/dev.c new file mode 100644 index 000000000..079520b7f --- /dev/null +++ b/kernel/evl/net/dev.c @@ -0,0 +1,627 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2020 Philippe Gerum + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* + * Since we need an EVL kthread to handle traffic from the out-of-band + * stage without borrowing CPU time unwisely from random contexts, + * let's have separate, per-device threads for RX and TX. This gives + * the best flexibility for leveraging multi-core capabilities on + * high-bandwidth systems. Kthread priority defaults to 1, chrt is our + * friend for fine-grained tuning. Unlike the RX kthread which is + * always created for a device underlying an oob port, the TX one is + * optional, present only if the NIC driver for that device is + * oob-capable. + */ +#define KTHREAD_RX_PRIO 1 +#define KTHREAD_TX_PRIO 1 + +/* + * The default number of I/O pages which should be available on a + * per-device basis for conveying out-of-band traffic if not specified + * by an EVL_SOCKIOC_ACTIVATE request. + */ +#define EVL_DEFAULT_NETDEV_POOLSZ 1024 +/* + * The default fixed payload size available in I/O pages for conveying + * out-of-band traffic through the device if not specified by an + * EVL_SOCKIOC_ACTIVATE request. + */ +#define EVL_DEFAULT_NETDEV_BUFSZ PAGE_SIZE +/* + * Max. values for the settings above. + */ +#define EVL_MAX_NETDEV_POOLSZ 32768 +#define EVL_MAX_NETDEV_BUFSZ (PAGE_SIZE * 4) + +/* + * The list of network interfaces (real and virtual devices) which are + * usable for sending/receiving oob traffic. + */ +static LIST_HEAD(oob_port_list); + +static DEFINE_HARD_SPINLOCK(oob_port_lock); + +static struct evl_net_ebpf_filter * +__set_rx_filter(struct evl_netdev_state *est, + struct evl_net_ebpf_filter *filter); + +static struct evl_kthread * +start_handler_thread(struct net_device *dev, + void (*fn)(void *arg), + int prio, const char *type) +{ + struct evl_kthread *kt; + int ret; + + kt = kzalloc(sizeof(*kt), GFP_KERNEL); + if (kt == NULL) + return ERR_PTR(-ENOMEM); + + ret = evl_run_kthread(kt, fn, dev, prio, 0, "%s.%s", + netdev_name(dev), type); + if (ret) { + kfree(kt); + return ERR_PTR(ret); + } + + return kt; +} + +/* + * enable_oob_port - @dev is a device which we want to enable as a + * port for channeling out-of-band traffic. This may be a real device, + * or a VLAN interface. + */ +static int enable_oob_port(struct net_device *dev, + struct evl_netdev_activation *act) /* inband, rtnl_lock held */ +{ + struct oob_netdev_state *rnds, *nds; + struct evl_netdev_state *pest, *est; + struct net_device *real_dev; + struct evl_kthread *kt; + unsigned long flags; + unsigned int mtu; + int ret; + + if (netif_oob_port(dev)) + return 0; /* Already enabled. */ + + /* + * If @dev is a VLAN device, diversion is turned on for the + * real device it sits on top of, so that the EVL stack is + * given a chance to pick the ingress traffic to be routed to + * the oob stage. The resources we need are allocated only for + * the real device. + * + * NOTE: the diversion flag is set for a real device only, + * _never_ for a VLAN device. + */ + real_dev = evl_net_real_dev(dev); + rnds = &real_dev->oob_state; + est = pest = rnds->estate; + if (pest == NULL) { + est = kzalloc(sizeof(*est), GFP_KERNEL); + if (est == NULL) + return -ENOMEM; + rnds->estate = est; + } + + nds = &dev->oob_state; + evl_init_crossing(&nds->crossing); + + if (est->refs++ > 0) /* Guarded by rtnl_lock. */ + goto queue; + + if (!act->poolsz) + act->poolsz = EVL_DEFAULT_NETDEV_POOLSZ; + + if (!act->bufsz) + act->bufsz = EVL_DEFAULT_NETDEV_BUFSZ; + + /* Silently align on the current mtu if need be. */ + mtu = READ_ONCE(real_dev->mtu); + if (act->bufsz < mtu) + act->bufsz = mtu; + + est->pool_max = act->poolsz; + est->buf_size = act->bufsz; + spin_lock_init(&est->filter_lock); + est->qdisc = evl_net_alloc_qdisc(&evl_net_qdisc_fifo); + if (IS_ERR(est->qdisc)) { + ret = PTR_ERR(est->qdisc); + goto fail_alloc_qdisc; + } + + ret = evl_net_dev_build_pool(real_dev); + if (ret) + goto fail_build_pool; + + evl_net_init_skb_queue(&est->rx_packets); + INIT_LIST_HEAD(&est->rx_poll); + raw_spin_lock_init(&est->rx_lock); + evl_init_flag(&est->rx_flag); + + kt = start_handler_thread(real_dev, evl_net_do_rx, + KTHREAD_RX_PRIO, "rx"); + if (IS_ERR(kt)) + goto fail_start_rx; + + est->rx_handler = kt; + + /* + * We need a TX handler only for oob-capable + * devices. Otherwise, the traffic would go through an in-band + * Qdisc, like the sched_oob in-band queues. + */ + if (netdev_is_oob_capable(real_dev)) { + evl_init_flag(&est->tx_flag); + kt = start_handler_thread(real_dev, evl_net_do_tx, + KTHREAD_TX_PRIO, "tx"); + if (IS_ERR(kt)) + goto fail_start_tx; + + est->tx_handler = kt; + } + + if (nds != rnds) /* i.e. dev is a VLAN interface. */ + evl_init_crossing(&rnds->crossing); + + /* Divert traffic from the real device. */ + netif_enable_oob_diversion(real_dev); +queue: + netif_enable_oob_port(dev); + + raw_spin_lock_irqsave(&oob_port_lock, flags); + list_add(&nds->next, &oob_port_list); + raw_spin_unlock_irqrestore(&oob_port_lock, flags); + + return 0; + +fail_start_tx: + /* + * No skb has flowed yet, no pending recycling op. Likewise, + * we cannot have any rxq in the cache or dump lists. + */ + if (netdev_is_oob_capable(real_dev)) { + evl_stop_kthread(est->rx_handler); + evl_destroy_flag(&est->tx_flag); + } +fail_start_rx: + evl_net_dev_purge_pool(real_dev); + evl_destroy_flag(&est->rx_flag); +fail_build_pool: + evl_net_free_qdisc(est->qdisc); +fail_alloc_qdisc: + if (!pest) { + kfree(est); + rnds->estate = NULL; + } + + return ret; +} + +/* + * disable_oob_port - @dev is a device for which we want to disable + * the oob port capability (see enable_oob_port()). This may be a real + * device, or a VLAN interface. + */ +static void disable_oob_port(struct net_device *dev) /* inband, rtnl_lock held */ +{ + struct oob_netdev_state *nds, *rnds; + struct evl_netdev_state *est; + struct net_device *real_dev; + unsigned long flags; + + if (!netif_oob_port(dev)) + return; + + /* + * Make sure that no evl_down_crossing() can be issued after + * we attempt to pass the crossing. Since the former can only + * happen as a result of finding the device in the active + * list, first unlink the latter _then_ pass the crossing + * next. + */ + real_dev = evl_net_real_dev(dev); + nds = &dev->oob_state; + raw_spin_lock_irqsave(&oob_port_lock, flags); + list_del(&nds->next); + raw_spin_unlock_irqrestore(&oob_port_lock, flags); + + /* + * Ok, now we may attempt to pass the crossing, waiting until + * all in-flight oob operations holding a reference on the + * network device acting as an oob port have completed. + */ + evl_pass_crossing(&nds->crossing); + + netif_disable_oob_port(dev); + + rnds = &real_dev->oob_state; + est = rnds->estate; + + if (EVL_WARN_ON(NET, est->refs <= 0)) + return; + + if (--est->refs > 0) /* Guarded by rtnl_lock. */ + return; + + /* + * Last ref. from a port to a real device dropped. Dismantle + * the extension for the latter. Start with unblocking all the + * waiters. + */ + evl_signal_poll_events(&est->poll_head, POLLERR); + evl_flush_wait(&est->tx_wait, EVL_T_RMID); + evl_schedule(); + + netif_disable_oob_diversion(real_dev); + + evl_stop_kthread(est->rx_handler); + if (est->tx_handler) + evl_stop_kthread(est->tx_handler); + + __set_rx_filter(est, NULL); + evl_net_dev_purge_pool(real_dev); + evl_destroy_flag(&est->rx_flag); + evl_net_free_qdisc(est->qdisc); + kfree(est); + rnds->estate = NULL; +} + +static int switch_oob_port(struct net_device *dev, + struct evl_netdev_activation *act) /* rtnl_lock held, in-band */ +{ + int ret = 0; + + /* + * Turn on/off oob port for the device. When set, packets + * received by the device flowing through the in-band net core + * are diverted to netif_deliver_oob(). + */ + if (act) + ret = enable_oob_port(dev, act); + else + disable_oob_port(dev); + + return ret; +} + +/* + * in-band, switches the oob port state of the device bound to the + * socket. + */ +int evl_net_switch_oob_port(struct evl_socket *esk, + struct evl_netdev_activation *act) +{ + struct net_device *dev; + int ret; + + dev = esk->proto->get_netif(esk); + if (dev == NULL) + return -ENXIO; + + if (act && + (act->poolsz > EVL_MAX_NETDEV_POOLSZ || + act->bufsz > EVL_MAX_NETDEV_BUFSZ)) { + ret = -EINVAL; + } else { + rtnl_lock(); + ret = switch_oob_port(dev, act); + rtnl_unlock(); + } + + evl_net_put_dev(dev); + + return ret; +} +EXPORT_SYMBOL_GPL(evl_net_switch_oob_port); + +struct net_device *evl_net_get_dev_by_index(struct net *net, int ifindex) +{ + struct net_device *dev, *ret = NULL; + struct oob_netdev_state *nds; + unsigned long flags; + + if (!ifindex) + return NULL; + + raw_spin_lock_irqsave(&oob_port_lock, flags); + + list_for_each_entry(nds, &oob_port_list, next) { + dev = container_of(nds, struct net_device, + oob_state); + if (dev_net(dev) == net && dev->ifindex == ifindex) { + evl_down_crossing(&nds->crossing); + ret = dev; + break; + } + } + + raw_spin_unlock_irqrestore(&oob_port_lock, flags); + + return ret; +} + +struct net_device *evl_net_get_dev_by_name(struct net *net, const char *name) +{ + struct net_device *dev, *ret = NULL; + struct oob_netdev_state *nds; + unsigned long flags; + + raw_spin_lock_irqsave(&oob_port_lock, flags); + + list_for_each_entry(nds, &oob_port_list, next) { + dev = container_of(nds, struct net_device, + oob_state); + if (dev_net(dev) == net && !strcmp(netdev_name(dev), name)) { + evl_down_crossing(&nds->crossing); + ret = dev; + break; + } + } + + raw_spin_unlock_irqrestore(&oob_port_lock, flags); + + return ret; +} + +void evl_net_get_dev(struct net_device *dev) +{ + struct oob_netdev_state *nds = &dev->oob_state; + + evl_down_crossing(&nds->crossing); +} + +void evl_net_put_dev(struct net_device *dev) +{ + struct oob_netdev_state *nds = &dev->oob_state; + + EVL_WARN_ON(NET, hard_irqs_disabled()); + + evl_up_crossing(&nds->crossing); +} + +/** + * netif_oob_switch_port - turn on oob capability for a network + * device. + * + * This call is invoked from the net-sysfs interface in order to + * change the state of the oob port of a network device. The + * default pool and buffer size are used when enabling. + * + * @dev The network device for which the oob port should be + * switched on/off. This may be a real device or a VLAN + * interface. + * + * @enabled The new oob port state. + * + * Returns zero on success, an error code otherwise. + */ +int netif_oob_switch_port(struct net_device *dev, bool enabled) +{ + struct evl_netdev_activation act = { + .poolsz = 0, + .bufsz = 0, + }; + + return switch_oob_port(dev, enabled ? &act : NULL); +} + +/** + * netif_oob_get_port - get the oob diversion state + * + * Returns true if the device is an EVL port for conveying + * networking traffic from the out-of-band execution stage. + */ +bool netif_oob_get_port(struct net_device *dev) +{ + return netif_oob_port(dev); +} + +ssize_t netif_oob_query_pool(struct net_device *dev, char *buf) +{ + struct evl_netdev_state *est; + struct net_device *real_dev; + + real_dev = evl_net_real_dev(dev); + est = real_dev->oob_state.estate; + if (est == NULL) + return -ENXIO; + + return sprintf(buf, "%zu %zu\n", est->pool_max, est->buf_size); +} + +int evl_netdev_event(struct notifier_block *ev_block, + unsigned long event, void *ptr) +{ + struct net_device *dev = netdev_notifier_info_to_dev(ptr); + + /* + * Disable the oob port enabled on a network device before the + * latter goes down. rtnl_lock is held. + */ + if (event == NETDEV_GOING_DOWN && netif_oob_port(dev)) { + disable_oob_port(dev); + evl_net_flush_routes(dev_net(dev), dev); + } + + return NOTIFY_DONE; +} + +enum evl_net_rx_action +__evl_net_filter_rx(struct evl_netdev_state *est, struct sk_buff *skb) +{ + struct evl_net_ebpf_filter *filter = READ_ONCE(est->rx_filter); + enum evl_net_rx_action ret = EVL_RX_VLAN; + + if (filter) { + rcu_read_lock(); /* Recheck under lock. */ + + filter = rcu_dereference(est->rx_filter); + if (filter) + ret = bpf_prog_run_clear_cb(filter->prog, skb); + + rcu_read_unlock(); + } + + return ret; +} + +static void drop_rx_filter(struct rcu_head *rcu) +{ + struct evl_net_ebpf_filter *filter = container_of(rcu, struct evl_net_ebpf_filter, rcu); + + bpf_prog_destroy(filter->prog); + kfree(filter); +} + +static struct evl_net_ebpf_filter * +__set_rx_filter(struct evl_netdev_state *est, + struct evl_net_ebpf_filter *filter) +{ + struct evl_net_ebpf_filter *old; + + spin_lock_bh(&est->filter_lock); + old = rcu_dereference_protected(est->rx_filter, + lockdep_is_held(&est->filter_lock)); + rcu_assign_pointer(est->rx_filter, filter); + if (filter) + set_bit(EVL_NETDEV_RXFILTER_BIT, &est->flags); + else + clear_bit(EVL_NETDEV_RXFILTER_BIT, &est->flags); + spin_unlock_bh(&est->filter_lock); + + if (old) + call_rcu(&old->rcu, drop_rx_filter); + + return old; +} + +/* + * set_rx_filter - install an eBPF program module to redirect ingress + * traffic to the proper network stack, inband or oob. @dev is a + * physical interface. + */ +static int set_rx_filter(struct net_device *dev, unsigned long arg) +{ + struct oob_netdev_state *nds = &dev->oob_state; + struct evl_net_ebpf_filter *old, *new = NULL; + struct bpf_prog *prog; + int ret, fd; + + ret = raw_get_user(fd, (__s32 *)arg); + if (ret) + return -EFAULT; + + if (fd != -1) { + prog = bpf_prog_get_type(fd, BPF_PROG_TYPE_SOCKET_FILTER); + if (IS_ERR(prog)) { + netdev_warn(dev, "invalid out-of-band eBPF program\n"); + return PTR_ERR(prog); + } + new = kmalloc(sizeof(*new), GFP_KERNEL); + if (!new) + return -ENOMEM; + new->prog = prog; + netdev_notice(dev, "out-of-band eBPF program installed\n"); + } + + old = __set_rx_filter(nds->estate, new); + if (old && !new) + netdev_notice(dev, "out-of-band eBPF program removed\n"); + + return 0; +} + +static long netdev_ioctl(struct file *filp, unsigned int cmd, + unsigned long arg) +{ + struct net_device *dev = filp->private_data; + int ret = -ENOTTY; + + switch (cmd) { + case EVL_NDEVIOC_SETRXEBPF: + ret = set_rx_filter(evl_net_real_dev(dev), arg); + break; + } + + return ret; +} + +static int netdev_release(struct inode *inode, struct file *filp) +{ + struct net_device *dev = filp->private_data; + + evl_net_put_dev(dev); + + return 0; +} + +static const struct file_operations netdev_fops = { + .open = stream_open, + .release = netdev_release, + .unlocked_ioctl = netdev_ioctl, +#ifdef CONFIG_COMPAT + .compat_ioctl = compat_ptr_ioctl, +#endif +}; + +int evl_net_dev_allocfd(struct net *net, const char *devname) +{ + struct net_device *dev; + struct file *filp; + int ret, fd; + + dev = evl_net_get_dev_by_name(net, devname); + if (!dev) + return -EINVAL; + + filp = anon_inode_getfile("[evl-netdev]", &netdev_fops, + dev, O_RDWR|O_CLOEXEC); + if (IS_ERR(filp)) + return PTR_ERR(filp); + + fd = get_unused_fd_flags(O_RDWR|O_CLOEXEC); + if (fd < 0) { + ret = fd; + goto fail; + } + + filp->private_data = dev; + + fd_install(fd, filp); + + return fd; +fail: + filp_close(filp, current->files); + + return ret; +} diff --git a/kernel/evl/net/ethernet/Makefile b/kernel/evl/net/ethernet/Makefile new file mode 100644 index 000000000..a5bebe5c8 --- /dev/null +++ b/kernel/evl/net/ethernet/Makefile @@ -0,0 +1,3 @@ +obj-$(CONFIG_EVL_NET) += ethernet.o + +ethernet-y := input.o output.o diff --git a/kernel/evl/net/ethernet/input.c b/kernel/evl/net/ethernet/input.c new file mode 100644 index 000000000..de470dafa --- /dev/null +++ b/kernel/evl/net/ethernet/input.c @@ -0,0 +1,196 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2020 Philippe Gerum + */ + +#include +#include +#include +#include +#include +#include +#include + +static DECLARE_BITMAP(vlan_map, VLAN_N_VID); + +static struct evl_net_handler evl_net_ether; + +static void untag_packet(struct sk_buff *skb, + unsigned char *mac_hdr, struct vlan_ethhdr *ehdr) +{ + int mac_len; + + /* + * We run very early in the RX path, eth_type_trans() already + * pulled the MAC header at this point though. We accept + * ETH_P_IP encapsulation only so that ARP and friends still + * flow through the regular network stack. Fix up the protocol + * tag in the skb manually, cache the VLAN information in the + * skb, then reorder the MAC header eventually. + */ + skb->protocol = ehdr->h_vlan_encapsulated_proto; + __vlan_hwaccel_put_tag(skb, ehdr->h_vlan_proto, + ntohs(ehdr->h_vlan_TCI)); + skb_pull_inline(skb, VLAN_HLEN); + mac_len = skb->data - mac_hdr; + if (likely(mac_len > VLAN_HLEN + ETH_TLEN)) { + memmove(mac_hdr + VLAN_HLEN, mac_hdr, + mac_len - VLAN_HLEN - ETH_TLEN); + } + skb->mac_header += VLAN_HLEN; +} + +/** + * evl_net_ether_accept - Unconditionally accept an ethernet packet + * for the out-of-band stack, stripping out the VLAN information if + * present. + * + * @skb the packet to deliver. May be linked to some upstream queue. + */ +bool evl_net_ether_accept(struct sk_buff *skb) +{ + struct vlan_ethhdr *ehdr; + unsigned char *mac_hdr; + u16 vlan_tci; + + /* If accelerated, the VLAN header is already out. */ + if (!__vlan_hwaccel_get_tag(skb, &vlan_tci)) + goto pick; + + /* + * Deal manually with input from adapters without hw + * accelerated VLAN processing, in this case we need to pull + * the VLAN header from the packet. See comment in + * evl_net_ether_accept_vlan(). + */ + if (skb_vlan_tag_present(skb) || !eth_type_vlan(skb->protocol)) + goto pick; + + mac_hdr = skb_mac_header(skb); + ehdr = (struct vlan_ethhdr *)mac_hdr; + if (ehdr->h_vlan_encapsulated_proto != htons(ETH_P_IP)) + return false; + + untag_packet(skb, mac_hdr, ehdr); +pick: + evl_net_receive(skb, &evl_net_ether); + + return true; +} + +/** + * evl_net_ether_accept_vlan - Accept an ethernet packet if tagged for + * an out-of-band VLAN. + * + * Decide whether an incoming ethernet packet should be handled by the + * out-of-band networking stack instead of the in-band one. This + * routine checks whether some VLAN information stored into the packet + * matches one of the VIDs reserved for out-of-band traffic. + * + * @skb the packet to deliver. May be linked to some upstream queue. + * + * Returns true if the out-of-band stack should handle the packet. + */ +bool evl_net_ether_accept_vlan(struct sk_buff *skb) +{ + struct vlan_ethhdr *ehdr; + unsigned char *mac_hdr; + u16 vlan_tci; + + /* Try the accelerated way first. */ + if (!__vlan_hwaccel_get_tag(skb, &vlan_tci) && + test_bit(vlan_tci & VLAN_VID_MASK, vlan_map)) + goto pick; + + /* + * Deal manually with input from adapters without hw + * accelerated VLAN processing. Only if we should handle this + * packet, pull the VLAN header from it. + */ + if (!skb_vlan_tag_present(skb) && + eth_type_vlan(skb->protocol)) { + mac_hdr = skb_mac_header(skb); + ehdr = (struct vlan_ethhdr *)mac_hdr; + if (ehdr->h_vlan_encapsulated_proto == htons(ETH_P_IP)) { + vlan_tci = ntohs(ehdr->h_vlan_TCI); + if (test_bit(vlan_tci & VLAN_VID_MASK, vlan_map)) + goto untag; + } + } + + return false; +untag: + untag_packet(skb, mac_hdr, ehdr); +pick: + evl_net_receive(skb, &evl_net_ether); + + return true; +} + +/** + * net_ether_ingress - pass an ethernet packet upward to the + * stack. + * + * We are called from the RX kthread from oob context, hard irqs + * on. skb is not linked to any queue. + */ +static void net_ether_ingress(struct sk_buff *skb) /* oob */ +{ + /* Try to deliver to a raw packet socket first. */ + if (evl_net_packet_deliver(skb)) + return; + + switch (ntohs(skb->protocol)) { + case ETH_P_IP: + if (!evl_net_ipv4_deliver(skb)) + return; + } + + evl_net_free_skb(skb); /* Dropped. */ +} + +static struct evl_net_handler evl_net_ether = { + .ingress = net_ether_ingress, +}; + +static inline bool contains_reserved_vid(unsigned long *map) +{ + /* VID 0, 1 and 4095 are reserved. */ + return test_bit(0, map) || test_bit(1, map) || test_bit(VLAN_VID_MASK, map); +} + +ssize_t evl_net_store_vlans(const char *buf, size_t len) +{ + unsigned long *new_map; + ssize_t ret; + + new_map = bitmap_zalloc(VLAN_N_VID, GFP_KERNEL); + if (new_map == NULL) + return -ENOMEM; + + ret = bitmap_parselist(buf, new_map, VLAN_N_VID); + if (!ret && contains_reserved_vid(new_map)) + ret = -EINVAL; + if (ret) { + bitmap_free(new_map); + return ret; + } + + /* + * We don't have to provide for atomic update wrt our net + * stack when updating the vlan map. We use the VID as a + * shortlived information early for filtering + * input. Serializing writes/stores which the vfs does for us + * is enough. + */ + bitmap_copy(vlan_map, new_map, VLAN_N_VID); + bitmap_free(new_map); + + return len; +} + +ssize_t evl_net_show_vlans(char *buf, size_t len) +{ + return scnprintf(buf, len, "%*pbl\n", VLAN_N_VID, vlan_map); +} diff --git a/kernel/evl/net/ethernet/output.c b/kernel/evl/net/ethernet/output.c new file mode 100644 index 000000000..c05076691 --- /dev/null +++ b/kernel/evl/net/ethernet/output.c @@ -0,0 +1,86 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2021 Philippe Gerum + */ + +#include +#include +#include +#include +#include +#include + +/** + * evl_net_ether_transmit_raw - pass an ethernet packet down to + * the hardware as is. If @dev is a VLAN device, this routine + * tags the outgoing packet accordingly for the device. + * + * We are called from a protocol handler running in oob context, + * hard irqs on. @skb is not linked to any queue. + */ +int evl_net_ether_transmit_raw(struct net_device *dev, struct sk_buff *skb) +{ + __be16 vlan_proto; + u16 vlan_tci; + + if (is_vlan_dev(dev)) { + vlan_proto = vlan_dev_vlan_proto(dev); + vlan_tci = vlan_dev_vlan_id(dev); + vlan_tci |= vlan_dev_get_egress_qos_mask(dev, skb->priority); + __vlan_insert_tag(skb, vlan_proto, vlan_tci); + } + + netdev_dbg(dev, "transmitting %px\n", skb); + + return evl_net_transmit(skb); +} + +static int ether_transmit_one(struct net_device *dev, struct sk_buff *skb, + const void *hw_dst) +{ + struct ethhdr *eth; + + eth = skb_push(skb, ETH_HLEN); + skb_reset_mac_header(skb); + eth->h_proto = skb->protocol; + ether_addr_copy(eth->h_source, evl_net_real_dev(dev)->dev_addr); + ether_addr_copy(eth->h_dest, hw_dst); + + return evl_net_ether_transmit_raw(dev, skb); +} + +/** + * evl_net_ether_transmit - set the l2 header of an ethernet packet + * before passing it down to the hardware. + * + * This routine can deal with fragmented output. + */ +int evl_net_ether_transmit(struct net_device *dev, struct sk_buff *skb, + const void *hw_dst) +{ + struct sk_buff *fskb, *nskb; + int ret; + + ret = ether_transmit_one(dev, skb, hw_dst); + if (ret) + return ret; + + fskb = skb_shinfo(skb)->frag_list; + if (fskb) { + do { + nskb = fskb->next; + fskb->next = NULL; + ret = ether_transmit_one(dev, fskb, hw_dst); + if (ret) { + fskb->next = nskb; + skb_shinfo(skb)->frag_list = fskb; + return ret; + } + fskb = nskb; + } while (fskb); + skb_shinfo(skb)->frag_list = NULL; + } + + return 0; +} diff --git a/kernel/evl/net/input.c b/kernel/evl/net/input.c new file mode 100644 index 000000000..9ea9469f0 --- /dev/null +++ b/kernel/evl/net/input.c @@ -0,0 +1,313 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2020 Philippe Gerum + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static void napi_poll_oob(struct evl_netdev_state *est) /* oob */ +{ + struct napi_struct *napi, *tmp; + LIST_HEAD(requeuing); + unsigned long flags; + + /* + * We cannot conflict with the in-band stack on queuing via + * napi->poll_list by design, since we own the NAPI instances + * queued to est->rx_poll until we release them in this + * routine by a call to napi_schedule_unprep(). + */ + raw_spin_lock_irqsave(&est->rx_lock, flags); + + /* + * We are about to drop the RX lock, clear this flag early to + * close a race. We might compete with __set_rx_filter(), so + * use atomic bitops. + */ + clear_bit(EVL_NETDEV_POLL_SCHED, &est->flags); + + list_for_each_entry_safe(napi, tmp, &est->rx_poll, poll_list) { + int budget = napi->weight; + list_del_init(&napi->poll_list); + raw_spin_unlock_irqrestore(&est->rx_lock, flags); + budget -= napi->poll(napi, budget); + /* + * If the budget was not fully consumed (> 0), then we + * have no more work for this instance and we may + * release it, unless a scheduling request was missed, + * in which case napi_schedule_unprep() would take + * care of calling napi_schedule_oob() for + * it. Otherwise, we need to requeue the instance for + * another polling round. + */ + if (budget > 0) + napi_schedule_unprep(napi); + else + list_add(&napi->poll_list, &requeuing); + raw_spin_lock_irqsave(&est->rx_lock, flags); + } + + if (!list_empty(&requeuing)) { + list_splice(&requeuing, &est->rx_poll); + set_bit(EVL_NETDEV_POLL_SCHED, &est->flags); + } + + raw_spin_unlock_irqrestore(&est->rx_lock, flags); +} + +/* + * RX thread dealing with ingress traffic and garbage collection for + * stale input fragments. Specifically, this thread handles: + * + * - the outstanding requests for polling the device for new packets + * (napi_schedule_oob()) + * + * - the polled ingress packets queued by netif_deliver_oob(), passing + * them over to the proper protocol layer. + * + * - the garbage collection to flush the IP fragments which have not + * been collected in time. + * + * Each net device is served by a dedicated RX thread. + */ +void evl_net_do_rx(void *arg) +{ + struct net_device *dev = arg; + struct evl_netdev_state *est; + struct sk_buff *skb, *next; + LIST_HEAD(list); + int ret; + + est = dev->oob_state.estate; + + while (!evl_kthread_should_stop()) { + ret = evl_wait_flag(&est->rx_flag); + if (ret) + break; + + if (test_bit(EVL_NETDEV_POLL_SCHED, &est->flags)) + napi_poll_oob(est); + + if (evl_net_move_skb_queue(&est->rx_packets, &list)) { + list_for_each_entry_safe(skb, next, &list, list) { + list_del(&skb->list); + EVL_NET_CB(skb)->handler->ingress(skb); + } + } + + evl_net_ipv4_gc(dev_net(dev)); + } +} + +void evl_net_wake_rx(struct net_device *dev) +{ + struct evl_netdev_state *est = dev->oob_state.estate; + + evl_raise_flag(&est->rx_flag); +} + +/** + * evl_net_receive - schedule an ingress packet for oob handling + * + * Schedule an incoming packet for delivery to a listening EVL socket + * This call is either invoked: + * + * - in-band by a protocol-specific out-of-band packet filter + * (e.g. evl_net_ether_accept(), evl_net_ether_accept_vlan()) + * diverting packets from the regular networking stack, in order to + * queue work for its .ingress() handler. + * + * - out-of-band on behalf of a fully oob capable NIC driver, + * typically from an out-of-band (RX) IRQ context. + * + * @skb the packet to queue. May be linked to some upstream + * queue. skb->dev must be valid. + * + * @handler the network protocol descriptor which should eventually + * handle the packet. + */ +void evl_net_receive(struct sk_buff *skb, + struct evl_net_handler *handler) /* in-band or oob */ +{ + struct evl_netdev_state *est = skb->dev->oob_state.estate; + + if (skb->next) + skb_list_del_init(skb); + + EVL_NET_CB(skb)->handler = handler; + + /* + * Enqueue then kick our kthread handling the ingress path + * immediately if called from oob context. Otherwise, wait for + * the NIC driver to invoke napi_complete_done() when the RX + * side goes quiescent. + */ + evl_net_add_skb_queue(&est->rx_packets, skb); + + if (running_oob()) + evl_net_wake_rx(skb->dev); +} + +struct evl_net_rxqueue *evl_net_alloc_rxqueue(u32 hkey) /* in-band */ +{ + struct evl_net_rxqueue *rxq; + + rxq = kzalloc(sizeof(*rxq), GFP_KERNEL); + if (rxq == NULL) + return NULL; + + rxq->hkey = hkey; + INIT_LIST_HEAD(&rxq->subscribers); + evl_spin_lock_init(&rxq->lock); + + return rxq; +} + +/* in-band */ +void evl_net_free_rxqueue(struct evl_net_rxqueue *rxq) +{ + EVL_WARN_ON(NET, !list_empty(&rxq->subscribers)); + + kfree(rxq); +} + +/** + * napi_schedule_oob - plan for polling a NAPI instance. + * + * The RX kthread is resumed so that it polls the associated device + * for ingress packets directly from the oob stage. + * + * @n is the NAPI instance associated to a device for which oob packet + * diversion is enabled. An earlier call to napi_schedule_prep() is + * expected to have been issued for @n. + */ +void napi_schedule_oob(struct napi_struct *n) /* oob */ +{ + struct net_device *dev = n->dev; + struct evl_netdev_state *est = dev->oob_state.estate; + unsigned long flags; + + if (EVL_WARN_ON(NET, !(n->state & NAPIF_STATE_SCHED))) + return; + + /* + * We might have multiple NAPI instances per device, so + * serialization is required despite a single NAPI instance + * may be active at any point in time. Oh, well. See + * napi_poll_oob() for an explanation about the requirement + * for atomic bitops (EVL_NETDEV_POLL_SCHED). + */ + raw_spin_lock_irqsave(&est->rx_lock, flags); + list_add(&n->poll_list, &est->rx_poll); + set_bit(EVL_NETDEV_POLL_SCHED, &est->flags); + raw_spin_unlock_irqrestore(&est->rx_lock, flags); + evl_net_wake_rx(dev); +} + +/** + * napi_complete_oob - release a NAPI instance. + * + * May be called in-band or out-of-band indifferently. Eventually, the + * RX kthread is resumed so that it passes the pending ingress packets + * to the proper protocol handlers. + * + * @n is the NAPI instance associated to a device for which oob packet + * diversion is enabled. + */ +void napi_complete_oob(struct napi_struct *n) /* inband / oob */ +{ + evl_net_wake_rx(n->dev); +} + +/** + * netif_deliver_oob - receive a network packet from the hardware. + * + * Decide whether we should channel a freshly incoming packet to our + * out-of-band stack. May be called from any stage. + * + * Delivery is trivially simple at the moment: the set of protocols we + * handle is statically defined, currently ETH_P_IP. The point is to + * provide an expedited data path via the oob stage for the protocols + * which most users need, without reinventing the whole networking + * infrastructure. + * + * @skb the packet to inspect for oob delivery. May be linked to some + * upstream queue. + * + * Returns true if the oob stack wants to handle @skb, in which case + * the caller must assume that it does not own the packet anymore. + */ +bool netif_deliver_oob(struct sk_buff *skb) /* oob or in-band */ +{ + skb_reset_network_header(skb); + if (!skb_transport_header_was_set(skb)) + skb_reset_transport_header(skb); + skb_reset_mac_len(skb); + + /* + * Filter the incoming packet through the eBPF RX program + * attached to the input device (if any), passing it down to + * the regular in-band stack if the filter code says that we + * are not interested in it. + */ + switch (evl_net_filter_rx(skb->dev, skb)) { + case EVL_RX_VLAN: + /* + * Apply our VLAN rules to decide whether this is an + * oob packet. + */ + break; + case EVL_RX_ACCEPT: + /* Direct the packet to the oob stack unconditionally. */ + switch (skb->protocol) { + case htons(ETH_P_IP): + return evl_net_ether_accept(skb); + default: + /* + * We don't deal with non-IP protocols, and + * the filter mistakenly told us to handle the + * packet. Leave it to inband. + */ + return false; + } + case EVL_RX_SKIP: + /* Leave the packet to inband. */ + return false; + case EVL_RX_DROP: + /* Blackhole. */ + evl_net_free_skb(skb); + return true; + } + + /* + * Fallback to VLAN-based filtering to figure out whether the + * packet should be handled by the oob stack. + */ + switch (skb->protocol) { + case htons(ETH_P_IP): + return evl_net_ether_accept_vlan(skb); + default: + /* + * For those adapters without hw-accelerated VLAN + * capabilities, check the ethertype directly. + */ + if (eth_type_vlan(skb->protocol)) + return evl_net_ether_accept_vlan(skb); + + return false; + } +} diff --git a/kernel/evl/net/ipv4/Makefile b/kernel/evl/net/ipv4/Makefile new file mode 100644 index 000000000..7136dea58 --- /dev/null +++ b/kernel/evl/net/ipv4/Makefile @@ -0,0 +1,3 @@ +obj-$(CONFIG_EVL_NET) += ip.o + +ip-y := arp.o ipv4.o fragment.o route.o output.o udp.o diff --git a/kernel/evl/net/ipv4/arp.c b/kernel/evl/net/ipv4/arp.c new file mode 100644 index 000000000..abfaf5715 --- /dev/null +++ b/kernel/evl/net/ipv4/arp.c @@ -0,0 +1,225 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2021-2023 Philippe Gerum + * + * This file implements a simple out-of-band front cache to the ARP + * table maintained by the in-band network stack. Basically, we listen + * to update events from the later, caching new complete entries + * observed on oob-enabled devices, uncaching invalidated/dead + * entries. The front cache may be used safely from oob context for + * address lookup. + */ + +#include +#include +#include +#include +#include +#include + +#define EVL_NET_ARP_CACHE_SHIFT 8 + +static u32 hash_arp_entry(const void *key) +{ + const struct evl_net_arp_key *arp_k = key; + return arp_k->addr ^ hash32_ptr(arp_k->dev); +} + +static bool eq_arp_entry(const struct evl_cache_entry *entry, + const void *key) +{ + const struct evl_net_arp_entry *e = + container_of(entry, struct evl_net_arp_entry, entry); + const struct evl_net_arp_key *arp_k = key; + + return e->key.addr == arp_k->addr && e->key.dev == arp_k->dev; +} + +static char *format_arp_key(const struct evl_cache_entry *entry) +{ + const struct evl_net_arp_entry *e = + container_of(entry, struct evl_net_arp_entry, entry); + + return kasprintf(GFP_ATOMIC, "%pI4", &e->key.addr); +} + +static const void *get_arp_key(const struct evl_cache_entry *entry) +{ + const struct evl_net_arp_entry *e = + container_of(entry, struct evl_net_arp_entry, entry); + + return &e->key; +} + +static void free_arp_entry(struct evl_cache_entry *entry) /* in-band */ +{ + struct evl_net_arp_entry *e = + container_of(entry, struct evl_net_arp_entry, entry); + + netdev_put(e->key.dev, &e->dev_tracker); + kfree(e); +} + +static struct evl_cache_ops arp_cache_ops = { + .hash = hash_arp_entry, + .eq = eq_arp_entry, + .get_key = get_arp_key, + .format_key = format_arp_key, + .drop = free_arp_entry, +}; + +/* + * Cache a new ARP entry. + */ +static int cache_arp_entry(struct evl_cache *cache, struct neighbour *neigh) /* in-band */ +{ + struct net_device *dev = neigh->dev; + struct evl_net_arp_entry *e; + int ret; + + e = kzalloc(sizeof(*e), GFP_ATOMIC); + if (!e) + return -ENOMEM; + + e->key.dev = dev; + e->key.addr = *(const __be32 *)neigh->primary_key; + memcpy(e->ha, neigh->ha, sizeof(e->ha)); + netdev_hold(dev, &e->dev_tracker, GFP_ATOMIC); + + ret = evl_add_cache_entry(cache, &e->entry); + if (ret) { + netdev_put(dev, &e->dev_tracker); + kfree(e); + } + + return ret; +} + +/* + * Uncache an ARP entry. + */ +static void uncache_arp_entry(struct evl_cache *cache, struct neighbour *neigh) /* in-band */ +{ + const struct evl_net_arp_key key = { + .addr = *(const __be32 *)neigh->primary_key, + .dev = neigh->dev, + }; + + evl_del_cache_entry(cache, &key); +} + +/* + * Handle an update notification from the in-band ARP cache. + */ +static void update_arp_cache(struct neighbour *neigh) /* in-band */ +{ + struct net_device *dev = neigh->dev; + struct oob_net_state *nets = &dev_net(dev)->oob; + struct evl_cache *cache = &nets->ipv4.arp; + int ret; + + read_lock_bh(&neigh->lock); /* Protect against races on nud_state */ + + if (netif_oob_port(dev)) + netdev_dbg(dev, "proto=%#x, state=%#x, dead=%d, " + "iface=%s, ip=%pI4, mac=%pM\n", + ntohs(neigh->tbl->protocol), neigh->nud_state, + neigh->dead, netdev_name(neigh->dev), + neigh->primary_key, neigh->ha); + + if (neigh->nud_state & NUD_REACHABLE && netif_oob_port(dev)) { + /* Cache complete entries from oob-enabled devices. */ + ret = cache_arp_entry(cache, neigh); + if (ret) { + /* + * Yeah, well. Nothing useful we can do. Now + * the oob cache is out of sync and since the + * in-band one is up to date, nothing would + * justify to redo the resolution so that we + * might catch its output - except flushing + * the in-band cache entirely. This said, this + * would likely be the gentlest effect of + * receiving OOM here anyway. + */ + printk(EVL_WARNING "out of memory for ARP cache\n"); + } + } else { + /* + * Try uncaching any invalidated, stale or dead entry. + * Out-of-band caps might have just been turned off + * for the device although we still keep entries + * referring to it, so do not filter out on + * netif_oob_port(). + */ + if (neigh->dead || neigh->nud_state & (NUD_FAILED|NUD_STALE)) + uncache_arp_entry(cache, neigh); + } + + read_unlock_bh(&neigh->lock); +} + +static int netevent_handler(struct notifier_block *nb, + unsigned long event, void *arg) +{ + struct neighbour *neigh = arg; + + if (event == NETEVENT_NEIGH_UPDATE && neigh->tbl == &arp_tbl) + update_arp_cache(neigh); + + return NOTIFY_DONE; +} + +struct evl_net_arp_entry *evl_net_get_arp_entry(struct net_device *dev, __be32 addr) +{ + const struct evl_net_arp_key key = { + .addr = addr, + .dev = dev, + }; + struct oob_net_state *nets = &dev_net(dev)->oob; + struct evl_cache_entry *entry; + + entry = evl_lookup_cache(&nets->ipv4.arp, &key); + if (likely(entry)) + return container_of(entry, struct evl_net_arp_entry, entry); + + return NULL; +} + +static struct notifier_block netevent_notifier __read_mostly = { + .notifier_call = netevent_handler, +}; + +void evl_net_flush_arp(struct net *net) +{ + struct oob_net_state *nets = &net->oob; + + evl_flush_cache(&nets->ipv4.arp); +} + +int evl_net_init_arp(struct net *net) +{ + struct oob_net_state *nets = &net->oob; + struct evl_cache *cache; + int ret; + + /* ARP resolution cache. */ + cache = &nets->ipv4.arp; + cache->ops = &arp_cache_ops; + cache->init_shift = EVL_NET_ARP_CACHE_SHIFT; + cache->name = "ARP"; + + ret = evl_init_cache(cache); + if (ret) + return ret; + + register_netevent_notifier(&netevent_notifier); + + return 0; +} + +void evl_net_cleanup_arp(struct net *net) +{ + unregister_netevent_notifier(&netevent_notifier); + evl_net_flush_arp(net); +} diff --git a/kernel/evl/net/ipv4/fragment.c b/kernel/evl/net/ipv4/fragment.c new file mode 100644 index 000000000..005b5dbbf --- /dev/null +++ b/kernel/evl/net/ipv4/fragment.c @@ -0,0 +1,321 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2023 Philippe Gerum + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* + * Fragment expiration handler. Triggers when a fragmented datagram + * could not be reassembled within the allotted time (IP_FRAG_TIME). + */ +static void frag_expired(struct evl_timer *timer) +{ + struct evl_net_frag_tdir *ftdir; + struct evl_net_frag_tree *ft; + + ft = container_of(timer, struct evl_net_frag_tree, timer); + ftdir = ft->tdir; + raw_spin_lock(&ftdir->gc.lock); + hlist_add_head(&ft->gc, &ftdir->gc.queue); + raw_spin_unlock(&ftdir->gc.lock); + /* Tell the RX thread to run the garbage collection. */ + evl_net_wake_rx(ft->gc_dev); + netdev_warn(ft->gc_dev, "reassembly timed out, frag tree %px\n", ft); +} + +static u32 hash_frag_key(const void *data, u32 len) +{ + return jhash2(data, len / sizeof(u32), 0); +} + +static bool compare_frag_key(struct evl_net_frag_tree *ft, + const struct frag_v4_compare_key *key) +{ + return !memcmp(&ft->key.ipv4, key, sizeof(*key)); +} + +static struct evl_net_frag_tree * +alloc_frag_tree(struct evl_net_frag_tdir *ftdir, + const struct frag_v4_compare_key *key, + struct net_device *dev) +{ + struct evl_net_frag_tree *ft; + + ft = evl_alloc(sizeof(*ft)); + if (!ft) + return NULL; + + ft->end = 0; + ft->len = 0; + ft->flags = 0; + ft->frags = RB_ROOT; + ft->tdir = ftdir; + ft->gc_dev = dev; + INIT_HLIST_NODE(&ft->gc); + ft->key.ipv4 = *key; + evl_init_timer(&ft->timer, frag_expired); + evl_spin_lock_init(&ft->lock); + netdev_dbg(dev, "allocated frag tree %px\n", ft); + + return ft; +} + +/* ftdir->lock held. */ +static struct evl_net_frag_tree * +get_frag_tree(struct evl_net_frag_tdir *ftdir, + const struct frag_v4_compare_key *key, + struct net_device *dev) +{ + u32 hashval = hash_frag_key(key, sizeof(*key)); + struct evl_net_frag_tree *ft; + + hash_for_each_possible(ftdir->ht, ft, hash, hashval) { + if (compare_frag_key(ft, key)) + return ft; + } + + ft = alloc_frag_tree(ftdir, key, dev); + if (!ft) + return ERR_PTR(-ENOMEM); + + hash_add(ftdir->ht, &ft->hash, hashval); + netdev_dbg(dev, "hashed frag tree %px\n", ft); + + /* Starts aging only once hashed. */ + evl_start_timer(&ft->timer, + evl_abs_timeout(&ft->timer, ftdir->timeout), + 0); + return ft; +} + +/* + * Index the new fragment into the frag tree on the fragment offset + * found into the IP header. + * + * CAUTION: since ->rbnode and ->dev are unionized in sk_buff, the + * device the indexed skbs came from can only be found in the heading + * skb holding them (which is not indexed). + * + * @offset is a count of 8-byte chunks. + * + * ftdir->lock and ft->lock held, irqs off. + */ +static int index_frag(struct evl_net_frag_tree *ft, int offset, struct sk_buff *skb) +{ + struct rb_node **rbp, *parent; + int ret = 0; + + parent = NULL; + rbp = &ft->frags.rb_node; + + while (*rbp) { + struct sk_buff *e = rb_entry(*rbp, struct sk_buff, rbnode); + struct iphdr *iph = ip_hdr(e); + int _offset = ntohs(iph->frag_off) & IP_OFFSET; + parent = *rbp; + if (offset < _offset) + rbp = &(*rbp)->rb_left; + else if (offset > _offset) + rbp = &(*rbp)->rb_right; + else + return -EEXIST; /* Duplicate - drop it. */ + } + + rb_link_node(&skb->rbnode, parent, rbp); + rb_insert_color(&skb->rbnode, &ft->frags); + + return ret; +} + +/* + * Reassemble the datagram, connecting all skbs indexed in the frag + * tree as a single-linked list in logical offset order. The tree is + * guaranteed non-empty on entry. + * + * @ft the frag tree to reassemble from. + * + * No lock held, the frag tree is not hashed, only known to the + * caller. + */ +static struct sk_buff *reasm_frag(struct net *net, + struct evl_net_frag_tree *ft, + struct net_device *dev) +{ + struct rb_node *rb = rb_first(&ft->frags); + struct sk_buff *head, **skbp, *fskb; + + /* This has to be the heading packet at offset 0. */ + head = rb_entry(rb, struct sk_buff, rbnode); + head->dev = dev; + skbp = &skb_shinfo(head)->frag_list; + rb = rb_next(rb); + + while (rb) { + fskb = rb_entry(rb, struct sk_buff, rbnode); + fskb->dev = dev; + *skbp = fskb; + skbp = &fskb->next; + rb = rb_next(rb); + } + + *skbp = NULL; + + return head; +} + +/* + * Push an incoming fragment to the corresponding frag tree. The main + * logic was shamelessly lifted from ip_frag_queue(). + */ +static struct sk_buff *push_frag(struct sk_buff *skb, struct net_device *dev) +{ + struct net *net = dev_net(dev); + struct evl_net_frag_tdir *ftdir = &net->oob.ipv4.ftdir; + struct iphdr *iph = ip_hdr(skb); + struct frag_v4_compare_key key = { + .saddr = iph->saddr, + .daddr = iph->daddr, + .user = IP_DEFRAG_LOCAL_DELIVER, + .id = iph->id, + .protocol = iph->protocol, + }; + int offset, floff, end, len, ret; + struct evl_net_frag_tree *ft; + struct sk_buff *head; + unsigned long flags; + + rcu_read_lock(); + key.vif = l3mdev_master_ifindex_rcu(dev); + rcu_read_unlock(); + + evl_lock_kmutex(&ftdir->lock); + + ft = get_frag_tree(ftdir, &key, dev); + if (IS_ERR(ft)) { + ret = PTR_ERR(ft); + goto out_notree; + } + + evl_spin_lock(&ft->lock); + + floff = ntohs(iph->frag_off); + offset = (floff & IP_OFFSET) << 3; /* 8-byte chunks */ + /* + * The logical end offset of the packet, stripping out the + * l2+IP headers. + */ + end = offset + skb->len - skb_network_offset(skb) - ip_hdrlen(skb); + + netdev_dbg(dev, "pushing id=%d to frag tree %px, frag_off=%#x, ipfl=%#x, ihl=%d, %pI4 -> %pI4\n", + iph->id, ft, ntohs(iph->frag_off), floff & ~IP_OFFSET, + ip_hdrlen(skb), &iph->saddr, &iph->daddr); + + ret = -EINVAL; + if (!(floff & IP_MF)) { /* Last fragment in the series? */ + /* + * If we were already past the incoming fragment, or + * received a different end, this fragment is + * corrupted, so we reject it. + */ + if (end < ft->end || + ((ft->flags & INET_FRAG_LAST_IN) && end != ft->end)) + goto out; + + ft->flags |= INET_FRAG_LAST_IN; + ft->end = end; + netdev_dbg(dev, "final frag id=%d\n", iph->id); + } else { + netdev_dbg(dev, "more frag(s) id=%d\n", iph->id); + /* + * Inner frag length should be a multiple of 8 + * bytes. + */ + if (end & 7) { + end &= ~7; + if (skb->ip_summed != CHECKSUM_UNNECESSARY) + skb->ip_summed = CHECKSUM_NONE; + } + if (end > ft->end) { + /* + * If receiving data beyond the final packet, + * the incoming packet is corrupt. + */ + if (ft->flags & INET_FRAG_LAST_IN) + goto out; + + ft->end = end; + } + } + + if (end == offset) /* Zero-sized? Ignore then. */ + goto out; + + if (offset == 0) { + ft->flags |= INET_FRAG_FIRST_IN; + netdev_dbg(dev, "first frag id=%d\n", iph->id); + } + + /* Update the logical length received (headers stripped). */ + ft->len += end - offset; + + netdev_dbg(dev, "indexing frag id=%d\n", iph->id); + ret = index_frag(ft, offset >> 3, skb); + if (ret) + goto out; + + /* If complete, reassemble the datagram. */ + if (ft->flags == (INET_FRAG_FIRST_IN | INET_FRAG_LAST_IN) && + ft->len == ft->end) { + netdev_dbg(dev, "completed frag id=%d, len=%zu\n", iph->id, ft->len); + evl_spin_unlock(&ft->lock); + /* + * Stop the timer, then move the frag tree out of the + * gc queue if it's linked there. + */ + evl_stop_timer(&ft->timer); + raw_spin_lock_irqsave(&ftdir->gc.lock, flags); + if (!hlist_unhashed(&ft->gc)) + hlist_del(&ft->gc); + raw_spin_unlock_irqrestore(&ftdir->gc.lock, flags); + /* Covered by ftdir->lock. */ + hlist_del(&ft->hash); + evl_unlock_kmutex(&ftdir->lock); + head = reasm_frag(net, ft, dev); + len = ip_hdrlen(skb) + ft->len; + evl_free(ft); + if (len > 65535) { /* RFC 791 */ + evl_net_free_skb(head); /* Timer is off, so we have to cleanup manually. */ + return ERR_PTR(-E2BIG); + } + return head; + } + + /* Tell the caller to wait for more. */ + ret = -EINPROGRESS; +out: + evl_spin_unlock(&ft->lock); +out_notree: + evl_unlock_kmutex(&ftdir->lock); + + return ERR_PTR(ret); +} + +struct sk_buff *evl_ipv4_defrag(struct sk_buff *skb) +{ + struct net_device *dev = skb->dev ?: skb_dst(skb)->dev; + + return push_frag(skb, dev); +} diff --git a/kernel/evl/net/ipv4/ipv4.c b/kernel/evl/net/ipv4/ipv4.c new file mode 100644 index 000000000..3f02f7605 --- /dev/null +++ b/kernel/evl/net/ipv4/ipv4.c @@ -0,0 +1,247 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2023 Philippe Gerum + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* + * Setup the IPv4 portion of the EVL state into an in-band network + * namespace (struct net { ... struct oob_net_state oob; ... }). + */ +int evl_net_init_ipv4(struct net *net) +{ + struct oob_net_state *nets = &net->oob; + struct evl_net_frag_tdir *ftdir; + struct evl_net_frag_gc *gc; + int ret; + + ret = evl_net_init_ipv4_routing(net); + if (ret) + return ret; + + ret = evl_net_init_arp(net); + if (ret) + goto fail_arp; + + ret = evl_net_init_udp(net); + if (ret) + goto fail_udp; + + /* Fragment directory and friends. */ + ftdir = &nets->ipv4.ftdir; + hash_init(ftdir->ht); + evl_init_kmutex(&ftdir->lock); + ftdir->timeout = (ktime_t)IP_FRAG_TIME / HZ * NANOHZ_PER_HZ; + gc = &ftdir->gc; + INIT_HLIST_HEAD(&gc->queue); + raw_spin_lock_init(&gc->lock); + might_hard_lock(&gc->lock); + + return 0; + +fail_udp: + evl_net_cleanup_arp(net); +fail_arp: + evl_net_cleanup_ipv4_routing(net); + + return ret; +} + +void evl_net_cleanup_ipv4(struct net *net) +{ + struct oob_net_state *nets = &net->oob; + struct evl_net_frag_gc *gc = &nets->ipv4.ftdir.gc; + + evl_net_cleanup_udp(net); + evl_net_cleanup_arp(net); + evl_net_cleanup_ipv4_routing(net); + EVL_WARN_ON(NET, !hlist_empty(&gc->queue)); +} + +/* + * evl_net_ipv4_deliver - deliver an IPv4 packet to its final handler + * (typically the UDP layer). + * + * @skb the packet to deliver to the IPv4 stack. + * + * On error from this routine, the caller should care of dropping + * @skb. + * + * The logic of this code borrows a lot from ip_rcv_core(), with + * EVL-specific tweaks. + */ +int evl_net_ipv4_deliver(struct sk_buff *skb) +{ + struct iphdr *iph; + u32 len; + int ret; + + /* + * Out-of-band packets are never shared on entry and always + * linear. Part of this routine relies on these requirements. + */ + if (EVL_WARN_ON(NET, skb_shared(skb))) + return -EINVAL; + + if (EVL_WARN_ON(NET, skb_is_nonlinear(skb))) + return -EINVAL; + + /* + * Do not handle packets which were not directly targeted + * towards the network interface. If so, eth_type_trans() has + * set the packet type to PACKET_OTHERHOST. + */ + if (skb->pkt_type == PACKET_OTHERHOST) + return -ENOMSG; + + /* + * Make sure that we have enough data in there to hold an IP + * header (Since out-of-band packets are always linear, + * skb->data_len is zero, therefore skb_headlen() is actually + * skb->len). + */ + if (skb_headlen(skb) < sizeof(*iph)) + return -EINVAL; + + iph = ip_hdr(skb); + + /* + * Check minimum size of an IP header in 32bit words, and IPv4 + * signature as well. + */ + if (iph->ihl < 5 || iph->version != 4) + return -EINVAL; + + if (skb_headlen(skb) < iph->ihl * sizeof(u32)) + return -EINVAL; + + /* RFC 1122: silently drop packets failing the checksum. */ + if (unlikely(ip_fast_csum(iph, iph->ihl))) + return -EINVAL; + + /* Check for truncated packet. */ + len = ntohs(iph->tot_len); + if (skb->len < len) + return -EINVAL; + + if (len < iph->ihl * sizeof(u32)) + return -EINVAL; + + if (pskb_trim_rcsum(skb, len)) + return -EINVAL; + + /* + * The IP header should not have moved because of trimming + * since the skb is linear and not cloned. + */ + if (EVL_WARN_ON(NET, iph != ip_hdr(skb))) + return -EINVAL; + + skb->transport_header = skb->network_header + iph->ihl * sizeof(u32); + + /* + * If this is an IP fragment, push it to the defragmenter for + * reassembly. A successful return from evl_ipv4_defrag() + * passing back a valid heading skb means that the datagram is + * now complete. + */ + if (ip_is_fragment(iph)) { + skb = evl_ipv4_defrag(skb); + if (IS_ERR(skb)) { + ret = PTR_ERR(skb); + switch (ret) { + case -EINPROGRESS: + case -E2BIG: + /* + * We don't want the caller to drop + * the skb, either because we are + * waiting for more data to reassemble + * the datagram, or we did the cleanup + * already. + */ + return 0; + default: + return ret; + } + } + } + + /* Pass complete datagram to the next layer. */ + + switch (iph->protocol) { + case IPPROTO_UDP: + ret = evl_net_deliver_udp(skb); + /* + * Our caller does not know about fragmentation. On + * error, care for releasing the heading buffer by + * ourselves. + */ + if (ret) + evl_net_free_skb(skb); + return 0; + default: + return -ENOTSUPP; + } + + return 0; +} + +/* + * Run the garbage collection for a given net, like dropping outdated + * IPv4 frags. + */ +void __evl_net_ipv4_gc(struct evl_net_frag_tdir *ftdir) +{ + struct evl_net_frag_tree *ft; + struct hlist_head tmp; + struct hlist_node *n; + unsigned long flags; + + raw_spin_lock_irqsave(&ftdir->gc.lock, flags); + hlist_move_list(&ftdir->gc.queue, &tmp); + raw_spin_unlock_irqrestore(&ftdir->gc.lock, flags); + + evl_lock_kmutex(&ftdir->lock); + + hlist_for_each_entry_safe(ft, n, &tmp, gc) { + netdev_dbg(ft->gc_dev, "free frag tree %px\n", ft); + hlist_del(&ft->hash); + evl_free(ft); + } + + evl_unlock_kmutex(&ftdir->lock); +} + +static struct evl_net_proto *match_ipv4_domain(int type, int protocol) +{ + switch (protocol) { + case IPPROTO_UDP: + if (type != SOCK_DGRAM) + return ERR_PTR(-ESOCKTNOSUPPORT); + + return &evl_net_udp_proto; + default: + return NULL; + } +} + +struct evl_socket_domain evl_net_ipv4 = { + .af_domain = AF_INET, + .match = match_ipv4_domain, +}; diff --git a/kernel/evl/net/ipv4/output.c b/kernel/evl/net/ipv4/output.c new file mode 100644 index 000000000..0fb5a8810 --- /dev/null +++ b/kernel/evl/net/ipv4/output.c @@ -0,0 +1,196 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2023 Philippe Gerum + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static inline int select_ttl(struct inet_sock *inet, struct dst_entry *dst) +{ + int ttl = inet->uc_ttl; + + return ttl < 0 ? ip4_dst_hoplimit(dst) : ttl; +} + +static void fill_ipv4_header(struct iphdr *iph, + struct inet_sock *inet, + struct dst_entry *dst, + struct evl_net_ipv4_cookie *ipc) +{ + iph->version = 4; + iph->ihl = 5; + iph->tos = RT_TOS(inet->tos); + iph->ttl = select_ttl(inet, dst); + iph->daddr = ipc->daddr; + iph->saddr = ipc->saddr; + iph->protocol = ipc->protocol; +} + +/* + * Create an IPv4 datagram from the contents referred to by a + * user-provided I/O vector. + * + * @esk emitting socket + * @iov source I/O vector + * @iovlen number of cells in vector + * @ert EVL route cache entry + * @datalen length of payload data in @iov (excluding the transport header) + * @timeout time limit for sleeping on congestion + * @ipc IPv4 cookie with misc transmit information + * + * We make the following assumptions: + * + * - no GSO for out-of-band traffic. + * - always output frags when required (IP_DF never ignored). + * - scatter-gather capability of the device is ignored (NETIF_F_SG). + * + * This routine reserves the space for a transport header in the + * leading skb if ipc->transhdrlen > 0. The caller is expected to + * update it eventually. + * + * Returns the heading socket buffer (which may have fragments) loaded + * with the user data to transmit. + */ +struct sk_buff *evl_net_ipv4_build_datagram(struct evl_socket *esk, + struct iovec *iov, size_t iovlen, + struct evl_net_route *ert, + size_t datalen, + ktime_t timeout, + struct evl_net_ipv4_cookie *ipc) +{ + struct net_device *dev = evl_net_route_dev(ert), + *real_dev = evl_net_real_dev(dev); + size_t maxfraglen, chunksz, i_offset = 0, + offset = 0, thdrlen = 0; + struct sk_buff *head = NULL, *skb, **skbp = NULL; + struct dst_entry *dst = evl_net_route_dst(ert); + struct sock *sk = esk->sk; + struct inet_sock *inet = inet_sk(sk); + int mtu, n = 0, ret = 0; + __be16 id = 0, df = 0; + struct iphdr *iph; + __u16 frag_off; + void *data; + + /* + * It's ok for us to receive packets with no payload, but not + * to send them. + */ + if (EVL_WARN_ON(NET, datalen == 0)) + return ERR_PTR(-EINVAL); + + mtu = ip_sk_use_pmtu(sk) ? dst_mtu(dst) : READ_ONCE(real_dev->mtu); + if (!inetdev_valid_mtu(mtu)) + return ERR_PTR(-ENETUNREACH); /* Smaller than min ipv4 MTU? */ + + /* Room for payload in an IP frag aligned on 8-byte boundary. */ + maxfraglen = (mtu - sizeof(*iph)) & ~7; + if (datalen > maxfraglen) { + id = evl_read_rng_u16(); + } else if (datalen <= IPV4_MIN_MTU || ip_dont_fragment(sk, evl_net_route_dst(ert))) { + df = htons(IP_DF); + } + + netdev_dbg(dev, "build dgram: src=%pI4, dst=%pI4, mtu=%d, " + " transhdrlen=%d, maxfraglen=%zd\n", + &ipc->saddr, &ipc->daddr, mtu, ipc->transhdrlen, maxfraglen); + + for (;;) { + skb = evl_net_wget_skb(esk, real_dev, timeout); + if (IS_ERR(skb)) { + ret = PTR_ERR(skb); + goto fail; + } + + skb_reserve(skb, real_dev->hard_header_len + sizeof(*iph)); + + if (skbp) { + skb->next = NULL; + *skbp = skb; + skbp = &skb->next; + } else { + head = skb; + skb_shinfo(skb)->frag_list = NULL; + skbp = &skb_shinfo(skb)->frag_list; + /* + * Reserve the required space to store the + * transport header in the first skb. As far + * as we are concerned, this is part of the + * payload. + */ + if (ipc->transhdrlen > 0) { + skb_reserve(skb, ipc->transhdrlen); + skb_push(skb, ipc->transhdrlen); + skb_reset_transport_header(skb); + } + } + + skb->ip_summed = CHECKSUM_NONE; + skb->csum = 0; + /* To be used as the VLAN priority by the hw layer. */ + skb->priority = READ_ONCE(sk->sk_priority); + /* Assume IP over ethernet ATM. */ + skb->protocol = htons(ETH_P_IP); + /* We want the payload offset at head of packet. */ + frag_off = htons((offset + thdrlen) >> 3); + + do { + if (iov->iov_len == 0) { + if (++n >= iovlen) + break; + iov++; + i_offset = 0; + continue; + } + + chunksz = iov->iov_len; + if (chunksz > maxfraglen - skb->len) + chunksz = maxfraglen - skb->len; + + data = skb_put(skb, chunksz); + ret = raw_copy_from_user(data, iov->iov_base + i_offset, chunksz); + if (ret) + goto fail; + + iov->iov_len -= chunksz; + i_offset += chunksz; /* input offset (in current vector cell) */ + offset += chunksz; /* virtual packet offset (frag-insensitive) */ + } while (skb->len < maxfraglen); + + /* Account for the transport header past the heading packet. */ + thdrlen = ipc->transhdrlen; + iph = skb_push(skb, sizeof(*iph)); + skb_reset_network_header(skb); + fill_ipv4_header(iph, inet, dst, ipc); + iph->tot_len = htons(skb->len); + iph->id = id; + if (offset < datalen) { + iph->frag_off = frag_off | htons(IP_MF); + ip_send_check(iph); + } else { + iph->frag_off = frag_off | df; + ip_send_check(iph); + break; + } + } + + return head; +fail: + if (head) + evl_net_wput_skb(head); + + return ERR_PTR(ret); +} diff --git a/kernel/evl/net/ipv4/route.c b/kernel/evl/net/ipv4/route.c new file mode 100644 index 000000000..8d0e8839a --- /dev/null +++ b/kernel/evl/net/ipv4/route.c @@ -0,0 +1,153 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2023 Philippe Gerum + */ + +#include +#include +#include +#include + +/* Start an IPv4 route cache with 256 entries. */ +#define EVL_NET_IPV4_ROUTE_SHIFT 8 + +static u32 hash_ipv4_route(const void *key) +{ + return ipv4_addr_hash(*(const u32 *)key); +} + +static bool eq_ipv4_route(const struct evl_cache_entry *entry, + const void *key) +{ + const struct evl_net_route *e = + container_of(entry, struct evl_net_route, entry); + + return *(const __be32 *)e->key == *(const __be32 *)key; +} + +static char *format_ipv4_key(const struct evl_cache_entry *entry) +{ + const struct evl_net_route *e = + container_of(entry, struct evl_net_route, entry); + + return kasprintf(GFP_ATOMIC, "%pI4", e->key); +} + +static const void *get_ipv4_key(const struct evl_cache_entry *entry) +{ + const struct evl_net_route *e = + container_of(entry, struct evl_net_route, entry); + + return e->key; +} + +static struct evl_cache_ops ipv4_route_cache_ops = { + .hash = hash_ipv4_route, + .eq = eq_ipv4_route, + .get_key = get_ipv4_key, + .format_key = format_ipv4_key, + .drop = evl_net_free_route, +}; + +int evl_net_init_ipv4_routing(struct net *net) +{ + struct oob_net_state *nets = &net->oob; + struct evl_cache *cache; + + /* Route cache for IPv4 destinations. */ + cache = &nets->ipv4.routes; + cache->ops = &ipv4_route_cache_ops; + cache->init_shift = EVL_NET_IPV4_ROUTE_SHIFT; + cache->name = "ipv4_routes"; + + return evl_init_cache(cache); +} + +static bool compare_route_dev(struct evl_cache_entry *entry, void *arg) +{ + const struct evl_net_route *ert = + container_of(entry, struct evl_net_route, entry); + struct net_device *dev = arg; + + return dev == evl_net_route_dev(ert); +} + +static inline void flush_route_cache(struct net *net, struct net_device *dev) +{ + if (dev) + evl_clean_cache(&net->oob.ipv4.routes, compare_route_dev, dev); + else + evl_flush_cache(&net->oob.ipv4.routes); +} + +void evl_net_cleanup_ipv4_routing(struct net *net) +{ + flush_route_cache(net, NULL); +} + +/* + * Update the out-of-band front-cache on the fly with the routing + * information we received for the outgoing IPv4 traffic on an + * oob-enabled device. We may be running in softirq context, don't + * wait. + */ +void evl_net_learn_ipv4_route(struct net *net, + struct flowi4 *fl4, struct rtable *rt) /* in-band */ +{ + struct oob_net_state *nets = &net->oob; + struct net_device *dev = rt->dst.dev; + struct evl_net_route *e; + int ret; + + netdev_dbg(dev, "learning ipv4 route: %pI4 -> %pI4 via %s\n", + &fl4->saddr, &fl4->daddr, netdev_name(dev)); + + e = evl_net_get_ipv4_route(net, fl4->daddr); + if (e && e->rt->dst.dev == dev) { + evl_net_put_route(e); + return; + } + + e = kzalloc(sizeof(*e) + sizeof(fl4->daddr), GFP_ATOMIC); + if (!e) + goto warn; + + e->rt = rt_dst_clone(dev, rt); + *(__be32 *)e->key = fl4->daddr; + netdev_dbg(dev, "caching route to %pI4\n", &fl4->daddr); + ret = evl_add_cache_entry(&nets->ipv4.routes, &e->entry); + if (ret) { + ip_rt_put(e->rt); + kfree(e); + goto warn; + } + + return; +warn: + printk(EVL_WARNING "out of memory for IPv4 route cache\n"); +} + +/* + * Find a route to a destination IPv4 peer in the front cache. + * + * On success, the caller needs to release the route by a call to + * evl_net_put_route(). + */ +struct evl_net_route * +evl_net_get_ipv4_route(struct net *net, __be32 daddr) +{ + struct oob_net_state *nets = &net->oob; + struct evl_cache_entry *entry; + + entry = evl_lookup_cache(&nets->ipv4.routes, &daddr); + if (likely(entry)) + return container_of(entry, struct evl_net_route, entry); + + return NULL; +} + +void evl_net_flush_ipv4_routes(struct net *net, struct net_device *dev) +{ + flush_route_cache(net, dev); +} diff --git a/kernel/evl/net/ipv4/udp.c b/kernel/evl/net/ipv4/udp.c new file mode 100644 index 000000000..f08e54175 --- /dev/null +++ b/kernel/evl/net/ipv4/udp.c @@ -0,0 +1,852 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2021 Philippe Gerum + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define EVL_NET_UDP_CACHE_SHIFT 8 + +/* in-band. */ +static int attach_udp_socket(struct evl_socket *esk, + struct evl_net_proto *proto, int protocol) +{ + esk->proto = proto; + esk->protocol = protocol; + evl_net_init_ip_socket(esk); + + return 0; +} + +/* + * set_receive_slot - install/update a receive slot for the socket to + * wait on later. We are called whenever bind() is issued on an UDP + * socket from the inband stack: this enables our generic cache + * mechanism to deal with this information since it supports + * inband-only updates, inband/oob lookups. + * + * @esk->sk is locked on entry. + */ +static int add_receive_slot(struct evl_socket *esk) /* inband */ +{ + struct evl_cache *cache = &esk->net->oob.ipv4.udp; + struct inet_sock *inet = inet_sk(esk->sk); + struct evl_net_udp_receiver *new, *old; + struct evl_cache_entry *entry; + struct __evl_net_udp_key key; + int ret; + + /* + * Allocate without holding any lock to eliminate any risk of + * lock order inversion. In most cases (i.e. without + * SO_REUSEPORT), we won't find a pre-existing slot for the + * [addr, port] pair, so this new slot will be used. + */ + new = kzalloc(sizeof(*new), GFP_KERNEL); + if (!new) + return -ENOMEM; + + /* + * Binding for oob[-extended] protocols always and only + * happens after the inband-side binding operation was + * successful, so we may use the port and receive address the + * inband stack already parsed and checked, dealing with the + * hairy reuseport logic as well. Yummie. + */ + key.dport = inet->inet_num; + key.daddr = inet->inet_rcv_saddr; + + new->key = key; + INIT_LIST_HEAD(&new->queue); + evl_init_wait(&new->wait, &evl_mono_clock, 0); + refcount_set(&new->refs, 1); + + /* Lookup and insertion must be seen as atomic. */ + evl_lock_cache(cache); + entry = evl_lookup_cache(cache, &key); + if (entry) { + /* Unlock prior to freeing the slot (see above). */ + evl_unlock_cache(cache); + old = container_of(entry, struct evl_net_udp_receiver, entry); + /* One user more via reuseport, account for it. */ + refcount_inc(&old->refs); + evl_put_cache_entry(entry); + kfree(new); + new = old; + } else { + ret = evl_add_cache_entry_locked(cache, &new->entry); + evl_unlock_cache(cache); + if (ret) { + kfree(new); + return ret; + } + } + + WRITE_ONCE(esk->u.ip.udp.receiver, new); + + return 0; +} + +/* + * drop_receive_slot - remove a receive slot previously installed by + * add_receive_slot(). Slots a refcounted, so that SO_REUSEPORT is + * dealt with. + * + * @esk->sk is either locked on entry, or not known from anyone else + * (i.e. zombie state). + */ +static void drop_receive_slot(struct evl_socket *esk) /* inband */ +{ + struct evl_cache *cache = &esk->net->oob.ipv4.udp; + struct evl_net_udp_receiver *e; + struct __evl_net_udp_key key; + + e = READ_ONCE(esk->u.ip.udp.receiver); + if (e && refcount_dec_and_test(&e->refs)) { + key.dport = e->key.dport; + key.daddr = e->key.daddr; + evl_del_cache_entry(cache, &key); + WRITE_ONCE(esk->u.ip.udp.receiver, NULL); + } +} + +/* + * destroy_udp_socket - perform cleanup on UDP socket + * closure. This routine runs as an RCU callback. + * + * NOTE: sk_common_release() already ran for esk->sk, which means the + * socket is not hashed on any inband receive port anymore. We only + * have to release the receive slot @esk might be referring to. + */ +static void destroy_udp_socket(struct evl_socket *esk) /* inband */ +{ + drop_receive_slot(esk); +} + +/* + * @esk->sk is locked by the inband stack on entry. In addition, the + * latter denies double bindings for AF_INET sockets, so we know for + * sure that @esk does not reference any receive slot yet. Likewise, + * multiple bindings to the same destination is denied by the inband + * stack as well, so we may assume that we are always going to create + * a new cache entry on a unique key. Unbinding happens when the + * socket is either shut down or destroyed on the inband side, which + * is paired with our shutdown() and destroy() handlers. + */ +static int bind_udp_socket(struct evl_socket *esk, + struct sockaddr *addr, + int len) +{ + return add_receive_slot(esk); +} + +/* + * @esk->sk is locked by the inband stack on entry. + */ +static int shutdown_udp_socket(struct evl_socket *esk, int how) +{ + drop_receive_slot(esk); + return 0; +} + +static ssize_t offload_send_udp(struct evl_socket *esk, + struct kvec *kvec, size_t count, + struct sockaddr_in *in_dest) +{ + struct evl_net_offload *ofld; + + ofld = evl_alloc(sizeof(*ofld)); + if (!ofld) + return -ENOMEM; + + ofld->kvec = *kvec; + ofld->count = count; + ofld->dest.in = in_dest ? *in_dest : (struct sockaddr_in){}; + ofld->destlen = in_dest ? sizeof(*in_dest) : 0; + evl_net_offload_inband(esk, ofld, &esk->u.ip.pending_output); + + return count; +} + +/* + * Given an IPv4 address, look into our oob route and ARP front caches + * to find an egress path. If we cannot find a route to the next hop + * through an oob-enabled device, or we don't know the hardware + * address of this peer, then the caller will have to pass on the + * datagram to the in-band stack. + */ +static bool find_egress_path(struct evl_socket *esk, __be32 daddr, + struct evl_net_route **ertp, struct evl_net_arp_entry **earpp) +{ + struct evl_net_arp_entry *_earp; + struct evl_net_route *_ert; + struct net_device *dev; + + _ert = evl_net_get_ipv4_route(sock_net(esk->sk), daddr); + if (likely(_ert)) { + dev = _ert->rt->dst.dev; + if (netif_oob_port(dev)) { + _earp = evl_net_get_arp_entry(dev, daddr); + if (likely(_earp)) { + *ertp = _ert; + *earpp = _earp; + return true; + } + } + evl_net_put_route(_ert); + } + + return false; +} + +/* + * Calculate the UDP checksum, starting from the IP header up to the + * full payload, including the UDP header. @skb contains the IP frame + * heading a valid UDP datagram, which might be fragmented over + * additional IP frames. + */ +static inline __wsum checksum_datagram(struct sk_buff *skb) +{ + __wsum csum = csum_partial(skb->data, skb->len, 0); + struct sk_buff *fskb; + + skb_walk_frags(skb, fskb) { + csum = csum_partial(fskb->data, fskb->len, csum); + } + + return csum; +} + +/* + * Send a datagram - which might be fragmented - to the peer we have + * an ARP entry for. + */ +static int send_datagram(struct sk_buff *skb, struct net_device *dev, + struct evl_net_arp_entry *earp, + struct evl_net_ipv4_cookie *ipc, + __be16 dport, __be16 sport, + size_t datalen) +{ + size_t ulen = datalen + sizeof(struct udphdr); + struct udphdr *uh; + int ret; + + /* + * Set up our transport header. evl_net_ipv4_build_datagram() + * reserved the required space in the heading skb for us. + */ + uh = udp_hdr(skb); + uh->source = sport; + uh->dest = dport; + uh->len = htons(ulen); + uh->check = 0; /* Caution: checksum_datagram() reads this too. */ + uh->check = csum_tcpudp_magic(ipc->saddr, ipc->daddr, + ulen, IPPROTO_UDP, checksum_datagram(skb)); + if (uh->check == 0) + uh->check = CSUM_MANGLED_0; + + skb->ip_summed = CHECKSUM_NONE; + + ret = evl_net_ether_transmit(dev, skb, earp->ha); + if (ret) + evl_net_wput_skb(skb); + + return ret; +} + +/* oob */ +static ssize_t send_udp(struct evl_socket *esk, + const struct user_oob_msghdr __user *u_msghdr, + struct iovec *iov, + size_t iovlen) +{ + struct sockaddr_in in_addr, *u_in_addr; + struct sock *sk = esk->sk; + struct inet_sock *inet = inet_sk(sk); + struct evl_net_ipv4_cookie ipc; + struct evl_net_arp_entry *earp; + struct evl_net_route *ert; + struct msghdr msg = { 0 }; + struct __evl_timespec uts; + ssize_t datalen, ret; + enum evl_tmode tmode; + __u32 msg_flags = 0; + struct sk_buff *skb; + __be32 daddr, saddr; + __u32 namelen = 0; + struct kvec kvec; + ktime_t timeout; + __u64 name_ptr; + __be16 dport; + + ret = raw_get_user(msg_flags, &u_msghdr->flags); + if (ret) + return -EFAULT; + + /* + * Unlike BSD, we accept MSG_DONTWAIT to decline waiting on + * skb contention, or offloading to the in-band stage. + */ + if (msg_flags & ~MSG_DONTWAIT) + return -EINVAL; + + if (evl_socket_f_flags(esk) & O_NONBLOCK) + msg_flags |= MSG_DONTWAIT; + + ret = raw_copy_from_user(&uts, &u_msghdr->timeout, sizeof(uts)); + if (ret) + return -EFAULT; + + timeout = msg_flags & MSG_DONTWAIT ? EVL_NONBLOCK : + u_timespec_to_ktime(uts); + tmode = timeout ? EVL_ABS : EVL_REL; + + ret = raw_get_user(name_ptr, &u_msghdr->name_ptr); + if (ret) + return -EFAULT; + + if (name_ptr) { + ret = raw_get_user(namelen, &u_msghdr->namelen); + if (ret) + return -EFAULT; + if (namelen < sizeof(in_addr)) + return -EINVAL; + u_in_addr = evl_valptr64(name_ptr, struct sockaddr_in); + ret = raw_copy_from_user(&in_addr, u_in_addr, sizeof(in_addr)); + if (ret) + return -EFAULT; + daddr = in_addr.sin_addr.s_addr; + dport = in_addr.sin_port; + if (!daddr || !dport) + return -EINVAL; + msg.msg_name = (struct sockaddr *)&in_addr; + msg.msg_namelen = namelen; + } else { + if (sk->sk_state != TCP_ESTABLISHED) + return -EDESTADDRREQ; + daddr = inet->inet_daddr; + dport = inet->inet_dport; + } + + datalen = evl_iov_flat_length(iov, iovlen); + if (datalen == 0) + return 0; + + /* UDP datagram cannot exceed 64k. */ + if (datalen > 65535) + return -EMSGSIZE; + + /* + * Try finding an oob path for the datagram based on the + * routing information collected into our front caches. If + * none, then offload the packet to the inband stack (as a + * result, we may receive the missing information eventually). + */ + if (!find_egress_path(esk, daddr, &ert, &earp)) { + /* + * We charge the socket for the offloaded data + * although we won't consume any oob skb for + * transmit. This allows for contention management. + */ + ret = evl_charge_socket_wmem(esk, datalen, timeout, tmode); + if (ret) + return ret; + + ret = evl_copy_from_uio_to_kvec(iov, iovlen, datalen, &kvec); + if (ret < 0) { + evl_uncharge_socket_wmem(esk, datalen); + return ret; + } + + ret = offload_send_udp(esk, &kvec, ret, namelen ? &in_addr : NULL); + if (ret < 0) + return ret; + /* + * EVL-specific: we had to pass on the request to the + * in-band stage for routing and/or MAC address + * resolution. So the datagram is indeed in-flight, + * but we cannot guarantee a bounded delay before it + * is written to the wire. In such a case, provided + * the caller asked for non-blocking I/O, return + * -EINPROGRESS. This is a way for the caller to + * detect a missing peer solicitation before the + * latter is sent oob data. + */ + return unlikely(msg_flags & MSG_DONTWAIT) ? -EINPROGRESS : 0; + } + + /* Ok, we have an oob path for that datagram. */ + + saddr = inet->inet_saddr; + if (!saddr) { + if (ipv4_is_multicast(daddr)) { + saddr = inet->mc_addr; + } else { + rcu_read_lock(); + saddr = inet_select_addr(ert->rt->dst.dev, daddr, RT_SCOPE_LINK); + rcu_read_unlock(); + } + } + + ipc.saddr = saddr; + ipc.daddr = daddr; + ipc.protocol = IPPROTO_UDP; + ipc.transhdrlen = sizeof(struct udphdr); + skb = evl_net_ipv4_build_datagram(esk, iov, iovlen, ert, + datalen, timeout, &ipc); + if (IS_ERR_OR_NULL(skb)) { + ret = PTR_ERR(skb); + goto out; + } + + ret = send_datagram(skb, ert->rt->dst.dev, earp, &ipc, + dport, inet->inet_sport, datalen); +out: + evl_net_put_arp_entry(earp); + evl_net_put_route(ert); + + return ret ?: datalen; +} + +static ssize_t copy_datagram_to_user(struct user_oob_msghdr __user *u_msghdr, + const struct iovec *iov, + size_t iovlen, + struct sk_buff *skb) +{ + struct sockaddr_in addr, __user *u_addr; + __u64 name_ptr, namelen; + __u32 msg_flags = 0; + ssize_t ret, count; + bool short_write; + + ret = raw_get_user(name_ptr, &u_msghdr->name_ptr); + if (ret) + return -EFAULT; + + ret = raw_get_user(namelen, &u_msghdr->namelen); + if (ret) + return -EFAULT; + + if (name_ptr) { + if (namelen != sizeof(addr)) { + if (namelen < sizeof(addr)) + return -EINVAL; + ret = raw_put_user(sizeof(addr), &u_msghdr->namelen); + if (ret) + return -EFAULT; + } + addr.sin_family = AF_INET; + addr.sin_port = udp_hdr(skb)->source; + addr.sin_addr.s_addr = ip_hdr(skb)->saddr; + memset(addr.sin_zero, 0, sizeof(addr.sin_zero)); + u_addr = evl_valptr64(name_ptr, struct sockaddr_in); + ret = raw_copy_to_user(u_addr, &addr, sizeof(addr)); + if (ret) + return -EFAULT; + } else { + if (namelen) + return -EINVAL; + } + + skb_pull_inline(skb, sizeof(struct udphdr)); + + count = evl_net_skb_to_uio(iov, iovlen, skb, sizeof(struct iphdr), &short_write); + if (short_write) + msg_flags |= MSG_TRUNC; + + ret = raw_put_user(msg_flags, &u_msghdr->flags); + + return ret ? -EFAULT : count; +} + +/* oob */ +static ssize_t receive_udp(struct evl_socket *esk, + struct user_oob_msghdr __user *u_msghdr, + struct iovec *iov, + size_t iovlen) +{ + struct evl_net_udp_receiver *e; + struct __evl_timespec uts; + enum evl_tmode tmode; + struct sk_buff *skb; + unsigned long flags; + __u32 msg_flags = 0; + ktime_t timeout; + ssize_t ret; + + /* + * The cache entry may be freed only from a RCU callback, get + * a safe reference on it from a RCU read side to prevent + * stale access. + */ +again: + rcu_read_lock(); + + e = READ_ONCE(esk->u.ip.udp.receiver); + if (!e) { + /* + * If not bound prior to calling oob_recvmsg(), force + * a binding to 0.0.0.0:0, which means that no receipt + * will ever happen for this socket, causing this call + * to hang indefinitely until interrupted. + */ + rcu_read_unlock(); + lock_sock(esk->sk); + /* Recheck binding under lock. */ + e = READ_ONCE(esk->u.ip.udp.receiver); + ret = e ? 0 : add_receive_slot(esk); + release_sock(esk->sk); + if (!ret) + goto again; + return ret; + } + + evl_get_cache_entry(&e->entry); + + rcu_read_unlock(); + + if (u_msghdr) { + ret = raw_get_user(msg_flags, &u_msghdr->flags); + if (ret) { + ret = -EFAULT; + goto out; + } + + /* We only support MSG_DONTWAIT at the moment. */ + if (msg_flags & ~MSG_DONTWAIT) { + ret = -EINVAL; + goto out; + } + + ret = raw_copy_from_user(&uts, &u_msghdr->timeout, + sizeof(uts)); + if (ret) { + ret = -EFAULT; + goto out; + } + + timeout = u_timespec_to_ktime(uts); + tmode = timeout ? EVL_ABS : EVL_REL; + } else { + timeout = EVL_INFINITE; + tmode = EVL_REL; + } + + if (evl_socket_f_flags(esk) & O_NONBLOCK) + msg_flags |= MSG_DONTWAIT; + + do { + raw_spin_lock_irqsave(&e->wait.wchan.lock, flags); + + if (!list_empty(&e->queue)) { + skb = list_get_entry(&e->queue, struct sk_buff, list); + raw_spin_unlock_irqrestore(&e->wait.wchan.lock, flags); + ret = copy_datagram_to_user(u_msghdr, iov, iovlen, skb); + evl_net_rput_skb(skb); /* Uncharge rmem and free. */ + goto out; + } + + if (msg_flags & MSG_DONTWAIT) { + raw_spin_unlock_irqrestore(&e->wait.wchan.lock, flags); + ret = -EWOULDBLOCK; + goto out; + } + + evl_add_wait_queue(&e->wait, timeout, tmode); + raw_spin_unlock_irqrestore(&e->wait.wchan.lock, flags); + ret = evl_wait_schedule(&e->wait); + } while (!ret); +out: + evl_put_cache_entry(&e->entry); + + return ret; +} + +/* oob */ +static __poll_t poll_udp(struct evl_socket *esk, + struct oob_poll_wait *wait) +{ + return 0; +} + +/* in-band */ +static struct net_device *get_netif_udp(struct evl_socket *esk) +{ + int ifindex; + + ifindex = READ_ONCE(esk->sk->sk_bound_dev_if); + if (ifindex) + return evl_net_get_dev_by_index(esk->net, ifindex); + + return NULL; +} + +/* in-band */ +static void handle_udp_inband(struct evl_socket *esk) +{ + struct evl_net_offload *ofld, *n; + struct sock *sk = esk->sk; + unsigned long flags; + LIST_HEAD(tmp); + int ret; + + /* Process pending output. */ + + raw_spin_lock_irqsave(&esk->oob_lock, flags); + list_splice_init(&esk->u.ip.pending_output, &tmp); + raw_spin_unlock_irqrestore(&esk->oob_lock, flags); + + list_for_each_entry_safe(ofld, n, &tmp, next) { + struct msghdr msg = { 0 }; + list_del(&ofld->next); + msg.msg_namelen = ofld->destlen; + if (msg.msg_namelen) + msg.msg_name = (struct sockaddr *)&ofld->dest.in; + ret = kernel_sendmsg(sk->sk_socket, &msg, + &ofld->kvec, 1, ofld->count); + evl_free(ofld->kvec.iov_base); + evl_uncharge_socket_wmem(esk, ofld->count); + evl_free(ofld); + } +} + +static inline bool __validate_checksum(struct sk_buff *skb, u16 ulen, __sum16 check) +{ + __sum16 sum; + + /* + * If the hw computed the checksum, combine and check with the + * pseudo-header. + */ + if (skb->ip_summed == CHECKSUM_COMPLETE) { + if (!csum_tcpudp_magic(ip_hdr(skb)->saddr, ip_hdr(skb)->daddr, + ulen, IPPROTO_UDP, skb->csum)) { + skb->csum_valid = 1; + return true; + } + /* If the hw produced a bad checksum, check by ourselves. */ + } + + sum = csum_tcpudp_magic(ip_hdr(skb)->saddr, ip_hdr(skb)->daddr, + ulen, IPPROTO_UDP, checksum_datagram(skb)); + if (!sum) + sum = CSUM_MANGLED_0; + /* + * Tricky: checksumming here although CHECKSUM_COMPLETE was + * set means that we've just found out that the hardware + * checksum was invalid. If our software-computed checksum is + * valid instead, then we disagree with the hardware. This + * means either the original hardware checksum is incorrect or + * we screwed up skb->csum when moving skb->data around, which + * is quite bad news either way. + */ + sum -= check; + if (!sum && skb->ip_summed == CHECKSUM_COMPLETE) + netdev_rx_csum_fault(skb->dev, skb); + + skb->csum = sum; + skb->ip_summed = CHECKSUM_COMPLETE; + skb->csum_complete_sw = 1; + skb->csum_valid = !sum; + + return skb->csum_valid; +} + +static inline bool validate_checksum(struct sk_buff *skb, u16 ulen, __sum16 check) +{ + skb->csum_valid = 0; + + if (__skb_checksum_validate_needed(skb, true, check)) + return __validate_checksum(skb, ulen, check); + + return true; +} + +static inline bool verify_checksum(struct sk_buff *skb) +{ + struct udphdr *uh = udp_hdr(skb); + unsigned short ulen; + __sum16 check; + + ulen = ntohs(uh->len); + + if (ulen < sizeof(*uh)) + return false; /* Short packet, drop it. */ + + check = uh->check; + uh->check = 0; + + return validate_checksum(skb, ulen, check); +} + +static bool __queue_for_receiver(struct evl_cache *cache, + struct sk_buff *skb, + const struct __evl_net_udp_key *key) +{ + struct evl_cache_entry *entry = evl_lookup_cache(cache, key); + struct evl_net_udp_receiver *e; + unsigned long flags; + + /* + * If an entry is found, queue the incoming skb then wake up + * the receiver. + */ + if (entry) { + e = container_of(entry, struct evl_net_udp_receiver, entry); + raw_spin_lock_irqsave(&e->wait.wchan.lock, flags); + list_add(&skb->list, &e->queue); + if (evl_wait_active(&e->wait)) + evl_wake_up_head(&e->wait); + raw_spin_unlock_irqrestore(&e->wait.wchan.lock, flags); + evl_schedule(); + return true; + } + + return false; +} + +/* + * queue_for_receiver - push an incoming datagram to the proper + * receive slot. @skb is not part of any queue, however it might have + * a frag list. We may reuse skb->list only for the heading @skb, but + * not for its frags, this is ok. + */ +static bool queue_for_receiver(struct sk_buff *skb) +{ + const struct iphdr *iph = ip_hdr(skb); + struct net *net = dev_net(skb->dev); + struct udphdr *uh = udp_hdr(skb); + struct __evl_net_udp_key key; + struct evl_cache *cache = &net->oob.ipv4.udp; + + /* + * First try a direct hit to the destination address and port + * number. + */ + key.dport = ntohs(uh->dest); + key.daddr = iph->daddr; + if (__queue_for_receiver(cache, skb, &key)) + return true; + + /* Nope, try a waiter on the wildcard address then. */ + key.daddr = htonl(INADDR_ANY); + return __queue_for_receiver(cache, skb, &key); +} + +int evl_net_deliver_udp(struct sk_buff *skb) +{ + if (unlikely(sizeof(struct udphdr) > skb->len)) + return -EINVAL; /* Obviously garbled, drop that. */ + + if (!verify_checksum(skb)) + return -EINVAL; + + return queue_for_receiver(skb) ? 0 : -ESRCH; +} + +static u32 hash_udp_slot(const void *key) +{ + const struct __evl_net_udp_key *k = key; + + return jhash2((const u32 *)k, sizeof(*k) / sizeof(u32), 0); +} + +static bool eq_udp_slot(const struct evl_cache_entry *entry, + const void *key) +{ + const struct __evl_net_udp_key *k = key; + const struct evl_net_udp_receiver *e = + container_of(entry, struct evl_net_udp_receiver, entry); + + return e->key.dport == k->dport && e->key.daddr == k->daddr; +} + +static char *format_udp_key(const struct evl_cache_entry *entry) +{ + const struct evl_net_udp_receiver *e = + container_of(entry, struct evl_net_udp_receiver, entry); + + return kasprintf(GFP_ATOMIC, "%pI4:%u", &e->key.daddr, e->key.dport); +} + +static const void *get_udp_key(const struct evl_cache_entry *entry) +{ + const struct evl_net_udp_receiver *e = + container_of(entry, struct evl_net_udp_receiver, entry); + + return &e->key; +} + +static void drop_udp_slot(struct evl_cache_entry *entry) /* in-band */ +{ + struct evl_net_udp_receiver *e = + container_of(entry, struct evl_net_udp_receiver, entry); + struct sk_buff *skb, *tmp; + + list_for_each_entry_safe(skb, tmp, &e->queue, list) { + list_del(&skb->list); + evl_net_free_skb(skb); + } + + kfree(e); +} + +static struct evl_cache_ops udp_cache_ops = { + .hash = hash_udp_slot, + .eq = eq_udp_slot, + .get_key = get_udp_key, + .format_key = format_udp_key, + .drop = drop_udp_slot, +}; + +int evl_net_init_udp(struct net *net) +{ + struct oob_net_state *nets = &net->oob; + struct evl_cache *cache; + + /* Cache of active UDP4 receivers. */ + cache = &nets->ipv4.udp; + cache->ops = &udp_cache_ops; + cache->init_shift = EVL_NET_UDP_CACHE_SHIFT; + cache->name = "udp_receivers"; + + return evl_init_cache(cache); +} + +void evl_net_cleanup_udp(struct net *net) +{ + struct oob_net_state *nets = &net->oob; + + evl_flush_cache(&nets->ipv4.udp); +} + +struct evl_net_proto evl_net_udp_proto = { + .attach = attach_udp_socket, + .destroy = destroy_udp_socket, + .bind = bind_udp_socket, + .shutdown = shutdown_udp_socket, + .oob_send = send_udp, + .oob_poll = poll_udp, + .oob_receive = receive_udp, + .get_netif = get_netif_udp, + .handle_offload = handle_udp_inband, +}; diff --git a/kernel/evl/net/net.c b/kernel/evl/net/net.c new file mode 100644 index 000000000..46e454cee --- /dev/null +++ b/kernel/evl/net/net.c @@ -0,0 +1,192 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2021 Philippe Gerum + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* + * Called by the in-band stack to setup the oob state which is going + * to be maintained by EVL in a network namespace. + */ +void net_init_oob_state(struct net *net) +{ + evl_net_init_ipv4(net); +} + +/* + * Converse to net_init_oob_state(), called to cleanup the oob state + * which is being dismanted by the in-band stack. + */ +void net_cleanup_oob_state(struct net *net) +{ + evl_net_cleanup_ipv4(net); +} + +static struct notifier_block netdev_notifier = { + .notifier_call = evl_netdev_event +}; + +int __init evl_net_init(void) +{ + int ret; + + evl_net_init_tx(); + + evl_net_init_qdisc(); + + ret = register_netdevice_notifier(&netdev_notifier); + if (ret) + goto fail_notifier; + + ret = evl_register_socket_domain(&evl_net_packet); + if (ret) + goto fail_packet; + + ret = evl_register_socket_domain(&evl_net_ipv4); + if (ret) + goto fail_ipv4; + + /* AF_OOB is given no dedicated socket cache. */ + ret = proto_register(&evl_af_oob_proto, 0); + if (ret) + goto fail_proto; + + sock_register(&evl_family_ops); + + return 0; + +fail_proto: + evl_unregister_socket_domain(&evl_net_ipv4); +fail_ipv4: + evl_unregister_socket_domain(&evl_net_packet); +fail_packet: + unregister_netdevice_notifier(&netdev_notifier); +fail_notifier: + evl_net_cleanup_qdisc(); + + return ret; +} + +void __init evl_net_cleanup(void) +{ + sock_unregister(PF_OOB); + proto_unregister(&evl_af_oob_proto); + evl_unregister_socket_domain(&evl_net_packet); + unregister_netdevice_notifier(&netdev_notifier); + evl_net_cleanup_qdisc(); +} + +static long net_ioctl(struct file *filp, unsigned int cmd, + unsigned long arg) +{ + struct evl_net_devfd req, __user *u_req; + const char __user *u_name; + struct filename *devname; + long ret; + int ufd; + + switch (cmd) { + case EVL_NET_GETDEVFD: + u_req = (typeof(u_req))arg; + ret = copy_from_user(&req, u_req, sizeof(req)); + if (ret) + return -EFAULT; + u_name = evl_valptr64(req.name_ptr, const char); + devname = getname(u_name); + if (IS_ERR(devname)) + return PTR_ERR(devname); + ufd = evl_net_dev_allocfd(current->nsproxy->net_ns, devname->name); + putname(devname); + if (ufd < 0) + return ufd; + ret = put_user((__u32)ufd, &u_req->fd); + if (ret) + return -EFAULT; + break; + default: + ret = -ENOTTY; + } + + return ret; +} + +static const struct file_operations net_fops = { + .unlocked_ioctl = net_ioctl, +#ifdef CONFIG_COMPAT + .compat_ioctl = compat_ptr_ioctl, +#endif +}; + +static ssize_t vlans_show(struct device *dev, + struct device_attribute *attr, + char *buf) +{ + return evl_net_show_vlans(buf, PAGE_SIZE); +} + +static ssize_t vlans_store(struct device *dev, + struct device_attribute *attr, + const char *buf, size_t count) +{ + return evl_net_store_vlans(buf, count); +} +static DEVICE_ATTR_RW(vlans); + +static ssize_t ipv4_routes_store(struct device *dev, + struct device_attribute *attr, + const char *buf, size_t count) +{ + struct net *net = current->nsproxy->net_ns; + + evl_net_flush_ipv4_routes(net, NULL); + + return count; +} +static DEVICE_ATTR_WO(ipv4_routes); + +static ssize_t arp_store(struct device *dev, + struct device_attribute *attr, + const char *buf, size_t count) +{ + struct net *net = current->nsproxy->net_ns; + + evl_net_flush_arp(net); + + return count; +} +static DEVICE_ATTR_WO(arp); + +static struct attribute *net_attrs[] = { + &dev_attr_vlans.attr, + &dev_attr_ipv4_routes.attr, + &dev_attr_arp.attr, + NULL, +}; +ATTRIBUTE_GROUPS(net); + +struct evl_factory evl_net_factory = { + .name = "net", + .fops = &net_fops, + .attrs = net_groups, + .flags = EVL_FACTORY_SINGLE, +}; diff --git a/kernel/evl/net/output.c b/kernel/evl/net/output.c new file mode 100644 index 000000000..279aaedd0 --- /dev/null +++ b/kernel/evl/net/output.c @@ -0,0 +1,220 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2020 Philippe Gerum + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static void xmit_inband(struct irq_work *work); + +DEFINE_IRQ_WORK(oob_xmit_work, xmit_inband); + +static DEFINE_PER_CPU(struct evl_net_skb_queue, oob_tx_relay); + +static inline netdev_tx_t +oob_start_xmit(struct net_device *dev, struct sk_buff *skb) +{ + /* + * If we got there, @dev is deemed oob-capable + * (IFF_OOB_CAPABLE, see evl_net_transmit()). The driver should + * check the current execution stage for handling the + * out-of-band packet properly. + */ + return dev->netdev_ops->ndo_start_xmit(skb, dev); +} + +static inline void do_tx(struct evl_net_qdisc *qdisc, + struct net_device *dev, struct sk_buff *skb) +{ + evl_net_uncharge_skb_wmem(skb); + + switch (oob_start_xmit(dev, skb)) { + case NETDEV_TX_OK: + break; + default: /* busy, or whatever */ + qdisc->packet_dropped++; + /* FIXME: we need to do better wrt error handling. */ + evl_net_free_skb(skb); + break; + } +} + +void evl_net_do_tx(void *arg) +{ + struct net_device *dev = arg; + struct evl_netdev_state *est; + struct evl_net_qdisc *qdisc; + struct sk_buff *skb; + LIST_HEAD(list); + int ret; + + est = dev->oob_state.estate; + + while (!evl_kthread_should_stop()) { + ret = evl_wait_flag(&est->tx_flag); + if (ret) + break; + + /* + * Reread queueing discipline descriptor to allow + * dynamic updates. FIXME: protect this against + * swap/deletion while pulling packets (stax?). + */ + qdisc = est->qdisc; + + /* + * First we transmit the traffic as prioritized by the + * out-of-band queueing discipline attached to our + * device. + */ + for (;;) { + skb = qdisc->oob_ops->dequeue(qdisc); + if (skb == NULL) + break; + do_tx(qdisc, dev, skb); + } + } +} + +static void skb_xmit_inband(struct sk_buff *skb) +{ + evl_net_uncharge_skb_wmem(skb); + skb->prev = NULL; + skb->next = NULL; + dev_queue_xmit(skb); +} + +/* in-band hook, called upon NET_TX_SOFTIRQ. */ +void process_inband_tx_backlog(struct softnet_data *sd) +{ + struct sk_buff *skb, *n; + LIST_HEAD(list); + + if (evl_net_move_skb_queue(this_cpu_ptr(&oob_tx_relay), &list)) { + list_for_each_entry_safe(skb, n, &list, list) { + list_del(&skb->list); + skb_xmit_inband(skb); + } + } +} + +static void xmit_inband(struct irq_work *work) /* in-band, stalled */ +{ + /* + * process_inband_tx_backlog() should run soon, kicked by tx_action. + */ + __raise_softirq_irqoff(NET_TX_SOFTIRQ); +} + +/* oob or in-band */ +static int xmit_oob(struct net_device *dev, struct sk_buff *skb) +{ + struct evl_netdev_state *est = dev->oob_state.estate; + int ret; + + ret = evl_net_sched_packet(dev, skb); + if (ret) + return ret; + + evl_raise_flag(&est->tx_flag); + + return 0; +} + +/** + * evl_net_transmit - queue an egress packet for out-of-band + * transmission to the device. + * + * Add an outgoing packet to the out-of-band transmit queue, so + * that it will be handed over to the device referred to by + * @skb->dev. The packet is complete (e.g. the VLAN tag is set if + * @skb->dev is a VLAN device). + * + * @skb the packet to queue. Must not be linked to any upstream + * queue. + * + * Prerequisites: + * - skb->dev is a valid (real) device. The caller must prevent from + * the interface going down. + * - skb->sk == NULL. + */ +int evl_net_transmit(struct sk_buff *skb) /* oob or in-band */ +{ + struct evl_net_skb_queue *rl = this_cpu_ptr(&oob_tx_relay); + struct net_device *dev = skb->dev; + unsigned long flags; + bool kick; + + if (EVL_WARN_ON(NET, !dev)) + return -EINVAL; + + if (EVL_WARN_ON(NET, skb->sk)) + return -EINVAL; + + if (netdev_is_oob_capable(dev)) + return xmit_oob(dev, skb); + + /* + * If running in-band, just push the skb for transmission + * immediately to the in-band stack. Otherwise relay it via + * xmit_inband(). + */ + if (running_inband()) { + skb_xmit_inband(skb); + return 0; + } + + /* + * Running oob but net device is not oob-capable, resort to + * relaying the traffic to the in-band stage for enqueuing. + * Dovetail does ensure that __raise_softirq_irqoff() is safe + * to call from the oob stage provided hard irqs are off, but + * we want the softirq to be raised as soon as in-band resumes + * with interrupts enabled, so we go through the irq_work + * indirection first. + */ + raw_spin_lock_irqsave(&rl->lock, flags); + kick = list_empty(&rl->queue); + list_add_tail(&skb->list, &rl->queue); + raw_spin_unlock_irqrestore(&rl->lock, flags); + + if (kick) /* Rare false positives are ok. */ + irq_work_queue(&oob_xmit_work); + + return 0; +} + +void netif_tx_lock_oob(struct netdev_queue *txq) /* oob or in-band */ +{ + evl_lock_stax(&txq->oob.tx_lock); +} + +void netif_tx_unlock_oob(struct netdev_queue *txq) /* oob or in-band */ +{ + evl_unlock_stax(&txq->oob.tx_lock); +} + +void __init evl_net_init_tx(void) +{ + struct evl_net_skb_queue *txq; + int cpu; + + for_each_online_cpu(cpu) { + txq = &per_cpu(oob_tx_relay, cpu); + evl_net_init_skb_queue(txq); + } +} diff --git a/kernel/evl/net/packet/Makefile b/kernel/evl/net/packet/Makefile new file mode 100644 index 000000000..582beb792 --- /dev/null +++ b/kernel/evl/net/packet/Makefile @@ -0,0 +1,3 @@ +obj-$(CONFIG_EVL_NET) += af_packet.o + +af_packet-y := packet.o diff --git a/kernel/evl/net/packet/packet.c b/kernel/evl/net/packet/packet.c new file mode 100644 index 000000000..7a134101b --- /dev/null +++ b/kernel/evl/net/packet/packet.c @@ -0,0 +1,692 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2020 Philippe Gerum + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static struct evl_net_proto * +find_packet_proto(int protocol, struct evl_net_proto *default_proto); + +/* + * Lock nesting: protocol_lock -> rxq->lock -> esk->input_wait.wchan.lock + * We use linear skbs only (no paged data). + */ + +#define EVL_PROTO_HASH_BITS 8 + +static DEFINE_HASHTABLE(protocol_hash, EVL_PROTO_HASH_BITS); + +/* + * Protects protocol_hash, shared between in-band and oob contexts, + * never accessed from oob IRQ handlers. + */ +static DEFINE_EVL_SPINLOCK(protocol_lock); + +/* oob, hard irqs off */ +static bool __packet_deliver(struct evl_net_rxqueue *rxq, + struct sk_buff *skb, int protocol) +{ + struct net_device *dev = skb->dev; + bool delivered = false; + struct evl_socket *esk; + struct sk_buff *qskb; + u16 vlan_id; + int ifindex; + + evl_spin_lock(&rxq->lock); + + /* + * Subscribers are searched sequentially for a matching net + * device if specified, otherwise we accept traffic from any + * interface. The net_device lookup could be hashed too, but + * [lame excuse coming] we are not supposed to have a + * truckload of NICs to listen to, so keep it plain dumb which + * is going to be faster in the normal case. + */ + list_for_each_entry(esk, &rxq->subscribers, next_sub) { + /* + * Revisit: we could filter on some "activation tag" + * value calculated at activation time + * (enable_oob_port) to eliminate spurious matches on + * a newly registered device reusing an old ifindex we + * initially captured at binding time. + */ + ifindex = READ_ONCE(esk->u.packet.real_ifindex); + if (ifindex) { + if (ifindex != dev->ifindex) + continue; + vlan_id = READ_ONCE(esk->u.packet.vlan_id); + if (vlan_id && skb_vlan_tag_get_id(skb) != vlan_id) + continue; + } + + /* + * This packet may be delivered to esk, attempt to + * charge it to its rmem counter. If the socket may + * not consume more memory, skip delivery and try with + * the next subscriber. + */ + if (!evl_net_charge_skb_rmem(esk, skb)) + continue; + + /* + * All sockets bound to ETH_P_ALL receive a clone of + * each incoming buffer, leaving the latter unconsumed + * yet. A single one among the other listeners + * consumes the incoming buffer. + */ + qskb = skb; + if (protocol == ETH_P_ALL) { + qskb = evl_net_clone_skb(skb); + if (qskb == NULL) { + evl_flush_wait(&esk->input_wait, EVL_T_NOMEM); + evl_net_uncharge_skb_rmem(skb); + break; + } + } + + raw_spin_lock(&esk->input_wait.wchan.lock); + + list_add_tail(&qskb->list, &esk->input); + if (evl_wait_active(&esk->input_wait)) + evl_wake_up_head(&esk->input_wait); + + raw_spin_unlock(&esk->input_wait.wchan.lock); + + evl_signal_poll_events(&esk->poll_head, POLLIN|POLLRDNORM); + delivered = true; + if (protocol != ETH_P_ALL) + break; + } + + evl_spin_unlock(&rxq->lock); + + return delivered; +} + +/* protocol_lock held, hard irqs off */ +static struct evl_net_rxqueue *find_rxqueue(u32 hkey) +{ + struct evl_net_rxqueue *rxq; + + hash_for_each_possible(protocol_hash, rxq, hash, hkey) + if (rxq->hkey == hkey) + return rxq; + + return NULL; +} + +static inline u32 get_protocol_hash(int protocol) +{ + u32 hsrc = protocol; + + return jhash2(&hsrc, 1, 0); +} + +static bool packet_deliver(struct sk_buff *skb, int protocol) /* oob */ +{ + struct evl_net_rxqueue *rxq; + unsigned long flags; + bool ret = false; + u32 hkey; + + hkey = get_protocol_hash(protocol); + /* + * Find the rx queue linking sockets attached to the protocol. + */ + evl_spin_lock_irqsave(&protocol_lock, flags); /* FIXME: this is utterly inefficient. */ + + rxq = find_rxqueue(hkey); + if (rxq) + ret = __packet_deliver(rxq, skb, protocol); + + evl_spin_unlock_irqrestore(&protocol_lock, flags); + + return ret; +} + +/** + * evl_net_packet_deliver - deliver an ethernet packet to the raw + * interface tap + * + * Deliver a copy of @skb to every socket accepting all ethernet + * protocols (ETH_P_ALL) if any, and/or @skb to the heading + * socket waiting for skb->protocol. + * + * @skb the packet to deliver, not linked to any upstream + * queue. + * + * Returns true if @skb was queued. + * + * Caller must call evl_schedule(). + */ +bool evl_net_packet_deliver(struct sk_buff *skb) /* oob */ +{ + packet_deliver(skb, ETH_P_ALL); + + return packet_deliver(skb, ntohs(skb->protocol)); +} + +/* in-band. */ +static int attach_packet_socket(struct evl_socket *esk, + struct evl_net_proto *proto, int protocol) +{ + struct evl_net_rxqueue *rxq, *_rxq; + unsigned long flags; + u32 hkey; + + hkey = get_protocol_hash(protocol); + + /* + * We pre-allocate an rx queue then drop it if one is already + * hashed for the same protocol. Not pretty but we are running + * in-band, and this keeps the hard locked section short. + */ + rxq = evl_net_alloc_rxqueue(hkey); + if (rxq == NULL) + return -ENOMEM; + + /* + * From this point we cannot fail, packets might come in as + * soon as we queue. + */ + + evl_spin_lock_irqsave(&protocol_lock, flags); + + esk->proto = proto; + esk->u.packet.proto_hash = hkey; + esk->protocol = protocol; + + _rxq = find_rxqueue(hkey); + if (_rxq) { + evl_spin_lock(&_rxq->lock); + list_add(&esk->next_sub, &_rxq->subscribers); + evl_spin_unlock(&_rxq->lock); + } else { + hash_add(protocol_hash, &rxq->hash, hkey); + list_add(&esk->next_sub, &rxq->subscribers); + } + + evl_spin_unlock_irqrestore(&protocol_lock, flags); + + if (_rxq) + evl_net_free_rxqueue(rxq); + + return 0; +} + +/* in-band, esk->lock held or __sk_destruct() */ +static void destroy_packet_socket(struct evl_socket *esk) +{ + struct evl_net_rxqueue *rxq, *n; + unsigned long flags; + LIST_HEAD(tmp); + + if (list_empty(&esk->next_sub)) + return; + + evl_spin_lock_irqsave(&protocol_lock, flags); + + rxq = find_rxqueue(esk->u.packet.proto_hash); + + list_del_init(&esk->next_sub); /* Remove from rxq->subscribers */ + if (list_empty(&rxq->subscribers)) { + hash_del(&rxq->hash); + list_add(&rxq->next, &tmp); + } + + evl_spin_unlock_irqrestore(&protocol_lock, flags); + + list_for_each_entry_safe(rxq, n, &tmp, next) + evl_net_free_rxqueue(rxq); +} + +/* in-band */ +static int bind_packet_socket(struct evl_socket *esk, + struct sockaddr *addr, + int len) +{ + int ret, new_ifindex, real_ifindex, old_ifindex; + static struct evl_net_proto *proto; + struct net_device *dev = NULL; + struct sockaddr_ll *sll; + unsigned long flags; + u16 vlan_id; + + if (len != sizeof(*sll)) + return -EINVAL; + + sll = (struct sockaddr_ll *)addr; + if (sll->sll_family != AF_PACKET) + return -EINVAL; + + proto = find_packet_proto(ntohs(sll->sll_protocol), esk->proto); + if (proto == NULL) + return -EINVAL; + + new_ifindex = sll->sll_ifindex; + + mutex_lock(&esk->lock); + + old_ifindex = esk->u.packet.ifindex; + if (new_ifindex != old_ifindex) { + if (new_ifindex) { + dev = evl_net_get_dev_by_index(esk->net, new_ifindex); + if (dev == NULL) + goto out; + if (is_vlan_dev(dev)) { + vlan_id = vlan_dev_vlan_id(dev); + real_ifindex = vlan_dev_real_dev(dev)->ifindex; + } else { + vlan_id = 0; + real_ifindex = dev->ifindex; + } + } else { + vlan_id = 0; + real_ifindex = 0; + } + } + + if (esk->protocol != ntohs(sll->sll_protocol)) { + destroy_packet_socket(esk); + /* + * Since the old binding was dropped, we would not + * receive anything if the new binding fails. This + * said, -ENOMEM is the only possible failure, so the + * root issue would be way more problematic than a + * dead socket. + */ + ret = attach_packet_socket(esk, proto, ntohs(sll->sll_protocol)); + if (ret) + goto out; + } + + /* + * Ensure that all binding-related changes happen atomically + * from the standpoint of oob observers. + * + * Revisit: cannot race with IRQs, use preemption-disabling + * spinlock instead. + */ + raw_spin_lock_irqsave(&esk->oob_lock, flags); + if (new_ifindex != old_ifindex) { + /* First change the real interface, next the vid. */ + WRITE_ONCE(esk->u.packet.real_ifindex, real_ifindex); + esk->u.packet.vlan_id = vlan_id; + WRITE_ONCE(esk->u.packet.ifindex, new_ifindex); + } + raw_spin_unlock_irqrestore(&esk->oob_lock, flags); + + out: + mutex_unlock(&esk->lock); + + if (dev) + evl_net_put_dev(dev); + + return ret; +} + +static struct net_device *get_netif_packet(struct evl_socket *esk) +{ + return evl_net_get_dev_by_index(esk->net, + esk->u.packet.ifindex); +} + +static struct net_device *find_xmit_device(struct evl_socket *esk, + const struct user_oob_msghdr __user *u_msghdr) +{ + struct sockaddr_ll __user *u_addr; + __u64 name_ptr = 0, namelen = 0; + struct sockaddr_ll addr; + struct net_device *dev; + int ret; + + ret = raw_get_user(name_ptr, &u_msghdr->name_ptr); + if (ret) + return ERR_PTR(-EFAULT); + + ret = raw_get_user(namelen, &u_msghdr->namelen); + if (ret) + return ERR_PTR(-EFAULT); + + if (!name_ptr) { + if (namelen) + return ERR_PTR(-EINVAL); + + dev = esk->proto->get_netif(esk); + } else { + if (namelen < sizeof(addr)) + return ERR_PTR(-EINVAL); + + u_addr = evl_valptr64(name_ptr, struct sockaddr_ll); + ret = raw_copy_from_user(&addr, u_addr, sizeof(addr)); + if (ret) + return ERR_PTR(-EFAULT); + + if (addr.sll_family != AF_PACKET && + addr.sll_family != AF_UNSPEC) + return ERR_PTR(-EINVAL); + + dev = evl_net_get_dev_by_index(esk->net, addr.sll_ifindex); + } + + if (dev == NULL) + return ERR_PTR(-ENXIO); + + return dev; +} + +/* oob */ +static ssize_t send_packet(struct evl_socket *esk, + const struct user_oob_msghdr __user *u_msghdr, + struct iovec *iov, + size_t iovlen) +{ + struct net_device *dev, *real_dev; + struct __evl_timespec uts; + enum evl_tmode tmode; + struct sk_buff *skb; + __u32 msg_flags = 0; + ssize_t ret, count; + ktime_t timeout; + size_t rem; + + ret = raw_get_user(msg_flags, &u_msghdr->flags); + if (ret) + return -EFAULT; + + if (msg_flags & ~MSG_DONTWAIT) + return -EINVAL; + + if (evl_socket_f_flags(esk) & O_NONBLOCK) + msg_flags |= MSG_DONTWAIT; + + /* Fetch the timeout on obtaining a buffer from the TX pool. */ + ret = raw_copy_from_user(&uts, &u_msghdr->timeout, sizeof(uts)); + if (ret) + return -EFAULT; + + timeout = msg_flags & MSG_DONTWAIT ? EVL_NONBLOCK : + u_timespec_to_ktime(uts); + tmode = timeout ? EVL_ABS : EVL_REL; + + /* Determine the xmit interface. */ + dev = find_xmit_device(esk, u_msghdr); + if (IS_ERR(dev)) + return PTR_ERR(dev); + + /* + * If @dev is a VLAN device, then @real_dev cannot be stale + * until @dev goes down per the in-band refcounting + * guarantee. Since we hold a crossing reference on @real_dev, + * it cannot go down as it would need to pass the crossing + * first, so @real_dev cannot go stale until we are done. + */ + real_dev = evl_net_real_dev(dev); + + skb = evl_net_dev_alloc_skb(real_dev, timeout, tmode); + if (IS_ERR(skb)) { + ret = PTR_ERR(skb); + goto out; + } + + skb_reset_mac_header(skb); + skb->protocol = htons(esk->protocol); + skb->dev = real_dev; + skb->priority = READ_ONCE(esk->sk->sk_priority); + + count = evl_copy_from_uio(iov, iovlen, skb->data, skb_tailroom(skb), &rem); + if (rem || count + dev->hard_header_len + VLAN_HLEN > READ_ONCE(dev->mtu)) + ret = -EMSGSIZE; + else if (!dev_validate_header(dev, skb->data, count)) + ret = -EINVAL; + + if (ret < 0) + goto cleanup; + + skb_put(skb, count); + + if (!skb->protocol || skb->protocol == htons(ETH_P_ALL)) + skb->protocol = dev_parse_header_protocol(skb); + + skb_set_network_header(skb, real_dev->hard_header_len); + + /* + * Charge the socket with the memory consumption of skb, + * waiting for the output to drain if needed. The latter might + * fail if we got forcibly unblocked while waiting for the + * output contention to end, or the caller asked for a + * non-blocking operation while such contention was ongoing. + */ + ret = evl_net_charge_skb_wmem(esk, skb, timeout, tmode); + if (ret) + goto cleanup; + + ret = evl_net_ether_transmit_raw(dev, skb); + if (ret) { + evl_net_uncharge_skb_wmem(skb); + goto cleanup; + } + + ret = count; +out: + evl_net_put_dev(dev); + + return ret; +cleanup: + evl_net_free_skb(skb); + goto out; +} + +static ssize_t copy_packet_to_user(struct user_oob_msghdr __user *u_msghdr, + const struct iovec *iov, + size_t iovlen, + struct sk_buff *skb) +{ + struct sockaddr_ll addr, __user *u_addr; + __u64 name_ptr, namelen; + __u32 msg_flags = 0; + ssize_t ret, count; + + ret = raw_get_user(name_ptr, &u_msghdr->name_ptr); + if (ret) + return -EFAULT; + + ret = raw_get_user(namelen, &u_msghdr->namelen); + if (ret) + return -EFAULT; + + if (name_ptr) { + if (namelen != sizeof(addr)) { + if (namelen < sizeof(addr)) + return -EINVAL; + ret = raw_put_user(sizeof(addr), &u_msghdr->namelen); + if (ret) + return -EFAULT; + } + addr.sll_family = AF_PACKET; + addr.sll_protocol = skb->protocol; + addr.sll_ifindex = skb->dev->ifindex; + addr.sll_hatype = skb->dev->type; + addr.sll_pkttype = skb->pkt_type; + addr.sll_halen = dev_parse_header(skb, addr.sll_addr); + u_addr = evl_valptr64(name_ptr, struct sockaddr_ll); + ret = raw_copy_to_user(u_addr, &addr, sizeof(addr)); + if (ret) + return -EFAULT; + } else { + if (namelen) + return -EINVAL; + } + + count = evl_copy_to_uio(iov, iovlen, skb->data, skb->len); + if (count < skb->len) + msg_flags |= MSG_TRUNC; + + ret = raw_put_user(msg_flags, &u_msghdr->flags); + if (ret) + return -EFAULT; + + return count; +} + +/* oob */ +static ssize_t receive_packet(struct evl_socket *esk, + struct user_oob_msghdr __user *u_msghdr, + struct iovec *iov, + size_t iovlen) +{ + struct __evl_timespec uts; + enum evl_tmode tmode; + struct sk_buff *skb; + unsigned long flags; + __u32 msg_flags = 0; + ktime_t timeout; + ssize_t ret; + + if (u_msghdr) { + ret = raw_get_user(msg_flags, &u_msghdr->flags); + if (ret) + return -EFAULT; + + /* No MSG_TRUNC on recv, too much of a kludge. */ + if (msg_flags & ~MSG_DONTWAIT) + return -EINVAL; + + /* + * Fetch the timeout on receiving a buffer from + * esk->input. + */ + ret = raw_copy_from_user(&uts, &u_msghdr->timeout, + sizeof(uts)); + if (ret) + return -EFAULT; + + timeout = u_timespec_to_ktime(uts); + tmode = timeout ? EVL_ABS : EVL_REL; + } else { + timeout = EVL_INFINITE; + tmode = EVL_REL; + } + + if (evl_socket_f_flags(esk) & O_NONBLOCK) + msg_flags |= MSG_DONTWAIT; + + do { + raw_spin_lock_irqsave(&esk->input_wait.wchan.lock, flags); + + if (!list_empty(&esk->input)) { + skb = list_get_entry(&esk->input, struct sk_buff, list); + raw_spin_unlock_irqrestore(&esk->input_wait.wchan.lock, flags); + /* Restore the MAC header. */ + skb_push(skb, skb->data - skb_mac_header(skb)); + ret = copy_packet_to_user(u_msghdr, iov, iovlen, skb); + evl_net_uncharge_skb_rmem(skb); + evl_net_free_skb(skb); + return ret; + } + + if (msg_flags & MSG_DONTWAIT) { + raw_spin_unlock_irqrestore(&esk->input_wait.wchan.lock, flags); + return -EWOULDBLOCK; + } + + evl_add_wait_queue(&esk->input_wait, timeout, tmode); + raw_spin_unlock_irqrestore(&esk->input_wait.wchan.lock, flags); + ret = evl_wait_schedule(&esk->input_wait); + } while (!ret); + + return ret; +} + +/* oob */ +static __poll_t poll_packet(struct evl_socket *esk, + struct oob_poll_wait *wait) +{ + struct evl_netdev_state *est; + struct net_device *dev; + __poll_t ret = 0; + + /* Enqueue, then test. */ + evl_poll_watch(&esk->poll_head, wait, NULL); + if (!list_empty(&esk->input)) + ret = POLLIN|POLLRDNORM; + + dev = esk->proto->get_netif(esk); + if (dev) { + est = dev->oob_state.estate; + evl_poll_watch(&est->poll_head, wait, NULL); + /* FIXME: Assume we can always TX, which is too optimistic. */ + ret |= POLLOUT|POLLWRNORM; + evl_net_put_dev(dev); + } + + return ret; +} + +static struct evl_net_proto ether_packet_proto = { + .attach = attach_packet_socket, + .destroy = destroy_packet_socket, + .bind = bind_packet_socket, + .oob_send = send_packet, + .oob_poll = poll_packet, + .oob_receive = receive_packet, + .get_netif = get_netif_packet, +}; + +static struct evl_net_proto * +find_packet_proto(int protocol, struct evl_net_proto *default_proto) +{ + switch (protocol) { + case ETH_P_ALL: + case ETH_P_IP: + return ðer_packet_proto; + case 0: + return default_proto; + default: + return NULL; + } +} + +static struct evl_net_proto *match_packet_domain(int type, int protocol) +{ + static struct evl_net_proto *proto; + + proto = find_packet_proto(protocol, ðer_packet_proto); + if (proto == NULL) + return NULL; + + if (type != SOCK_RAW) + return ERR_PTR(-ESOCKTNOSUPPORT); + + return proto; +} + +struct evl_socket_domain evl_net_packet = { + .af_domain = AF_PACKET, + .match = match_packet_domain, +}; diff --git a/kernel/evl/net/qdisc/Makefile b/kernel/evl/net/qdisc/Makefile new file mode 100644 index 000000000..ad48ae703 --- /dev/null +++ b/kernel/evl/net/qdisc/Makefile @@ -0,0 +1,3 @@ +obj-$(CONFIG_EVL_NET) += qdisc.o + +qdisc-y := core.o fifo.o diff --git a/kernel/evl/net/qdisc/core.c b/kernel/evl/net/qdisc/core.c new file mode 100644 index 000000000..6bfd3c144 --- /dev/null +++ b/kernel/evl/net/qdisc/core.c @@ -0,0 +1,86 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2020 Philippe Gerum + */ + +#include +#include +#include +#include +#include +#include + +static LIST_HEAD(all_net_qdisc); + +static DEFINE_MUTEX(qdisc_list_lock); + +void evl_net_register_qdisc(struct evl_net_qdisc_ops *ops) /* in-band */ +{ + mutex_lock(&qdisc_list_lock); + list_add(&ops->next, &all_net_qdisc); + mutex_unlock(&qdisc_list_lock); +} +EXPORT_SYMBOL_GPL(evl_net_register_qdisc); + +void evl_net_unregister_qdisc(struct evl_net_qdisc_ops *ops) /* in-band */ +{ + mutex_lock(&qdisc_list_lock); + list_del(&ops->next); + mutex_unlock(&qdisc_list_lock); +} +EXPORT_SYMBOL_GPL(evl_net_unregister_qdisc); + +struct evl_net_qdisc *evl_net_alloc_qdisc(struct evl_net_qdisc_ops *ops) /* in-band */ +{ + struct evl_net_qdisc *qdisc; + int ret; + + qdisc = kzalloc(sizeof(*qdisc) + ops->priv_size, GFP_KERNEL); + if (qdisc == NULL) + return ERR_PTR(-ENOMEM); + + qdisc->oob_ops = ops; + + ret = ops->init(qdisc); + if (ret) { + kfree(qdisc); + return ERR_PTR(ret); + } + + return qdisc; +} +EXPORT_SYMBOL_GPL(evl_net_alloc_qdisc); + +void evl_net_free_qdisc(struct evl_net_qdisc *qdisc) /* in-band */ +{ + qdisc->oob_ops->destroy(qdisc); + kfree(qdisc); +} +EXPORT_SYMBOL_GPL(evl_net_free_qdisc); + +/** + * evl_net_sched_packet - pass an outgoing buffer to the packet + * scheduler. + * + * @skb the oob packet to schedule for transmission. Must not be + * linked to any upstream queue. + * + * @dev the device to pass the packet to. + */ +int evl_net_sched_packet(struct net_device *dev, struct sk_buff *skb) /* oob/in-band */ +{ + struct evl_net_qdisc *qdisc = dev->oob_state.estate->qdisc; + + return qdisc->oob_ops->enqueue(qdisc, skb); +} + +void __init evl_net_init_qdisc(void) +{ + evl_net_register_qdisc(&evl_net_qdisc_fifo); +} + +void __init evl_net_cleanup_qdisc(void) +{ + evl_net_unregister_qdisc(&evl_net_qdisc_fifo); +} diff --git a/kernel/evl/net/qdisc/fifo.c b/kernel/evl/net/qdisc/fifo.c new file mode 100644 index 000000000..0d4d2448d --- /dev/null +++ b/kernel/evl/net/qdisc/fifo.c @@ -0,0 +1,57 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2020 Philippe Gerum + */ + +#include +#include +#include +#include +#include + +struct qdisc_fifo_priv { + struct evl_net_skb_queue q; +}; + +static int init_qdisc_fifo(struct evl_net_qdisc *qdisc) +{ + struct qdisc_fifo_priv *p = evl_qdisc_priv(qdisc); + + evl_net_init_skb_queue(&p->q); + + return 0; +} + +static void destroy_qdisc_fifo(struct evl_net_qdisc *qdisc) +{ + struct qdisc_fifo_priv *p = evl_qdisc_priv(qdisc); + + evl_net_destroy_skb_queue(&p->q); +} + +static int enqueue_qdisc_fifo(struct evl_net_qdisc *qdisc, + struct sk_buff *skb) +{ + struct qdisc_fifo_priv *p = evl_qdisc_priv(qdisc); + + evl_net_add_skb_queue(&p->q, skb); + + return 0; +} + +static struct sk_buff *dequeue_qdisc_fifo(struct evl_net_qdisc *qdisc) +{ + struct qdisc_fifo_priv *p = evl_qdisc_priv(qdisc); + + return evl_net_get_skb_queue(&p->q); +} + +struct evl_net_qdisc_ops evl_net_qdisc_fifo = { + .name = "oob_fifo", + .priv_size = sizeof(struct qdisc_fifo_priv), + .init = init_qdisc_fifo, + .destroy = destroy_qdisc_fifo, + .enqueue = enqueue_qdisc_fifo, + .dequeue = dequeue_qdisc_fifo, +}; diff --git a/kernel/evl/net/route.c b/kernel/evl/net/route.c new file mode 100644 index 000000000..46ad54b9b --- /dev/null +++ b/kernel/evl/net/route.c @@ -0,0 +1,74 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2023 Philippe Gerum + */ + +#include +#include +#include +#include + +/* + * Cache a new IP route. + * + * @rt route to cache. The caller got a reference on the inner dst + * entry. + */ +int evl_net_cache_route(struct evl_cache *cache, /* in-band */ + struct rtable *rt, + const void *key, size_t key_len) +{ + struct evl_net_route *e; + int ret; + + e = kzalloc(sizeof(*e) + key_len, GFP_ATOMIC); + if (!e) + return -ENOMEM; + + e->rt = rt; + memcpy(e->key, key, key_len); + + ret = evl_add_cache_entry(cache, &e->entry); + if (ret) + kfree(e); + + return ret; +} + +/* + * Release a route. This is a common helper which may be called by the + * drop() handler from the generic cache layer for any cached IP route + * entry. + */ +void evl_net_free_route(struct evl_cache_entry *entry) /* in-band */ +{ + struct evl_net_route *e = + container_of(entry, struct evl_net_route, entry); + + netdev_dbg(evl_net_route_dev(e), "dropping IPv4 route %pI4\n", e->key); + + /* Drop the ref. we received in evl_net_cache_route(). */ + ip_rt_put(e->rt); + + kfree(e); +} + +/* + * in-band hook which receives IPv4 routing decisions which go through + * an oob-enabled device. + */ +void ip_learn_oob_route(struct net *net, struct flowi4 *fl4, struct rtable *rt) +{ + evl_net_learn_ipv4_route(net, fl4, rt); +} + +/* + * Flush the routes maintained in the out-of-band front cache. If @dev + * is non-NULL, only the routes going via the device are + * dropped. Otherwise, NULL is a wildcard for dropping all routes. + */ +void evl_net_flush_routes(struct net *net, struct net_device *dev) +{ + evl_net_flush_ipv4_routes(net, dev); +} diff --git a/kernel/evl/net/skb.c b/kernel/evl/net/skb.c new file mode 100644 index 000000000..4bcb0db9d --- /dev/null +++ b/kernel/evl/net/skb.c @@ -0,0 +1,699 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2020 Philippe Gerum + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* + * skb lifecycle: + * + * [RX path]: netif_deliver_oob(skb) + * * false: pass down, freed through in-band stack + * * true: process -> receive -> evl_net_free_skb(skb) + * skb_has_oob_storage(skb) ? immediately released to oob pool + * : pushed to in-band recycling queue + * + * [TX path]: skb = evl_net_dev_alloc_skb() + * ... + * netdev_start_xmit(skb) + * ... + * [IRQ or NAPI context] + * napi_consume_skb(skb) + * -> __napi_kfree_skb(skb) [3] + * | + * [1] consume_skb(skb) + * [2] -> __kfree_skb(skb) + * -> free_skb_oob(skb) + * | + * __dev_kfree_skb_any(skb) + * -> __dev_kfree_skb_irq_reason(skb) + * [SOFTIRQ NET_TX] + * -> net_tx_action + * | -> __kfree_skb(skb) [2] + * | | + * [3] | -> __napi_kfree_skb(skb) + * -> free_skb_oob(skb) + * -> dev_kfree_skb(skb) + * -> consume_skb(skb) [1] + */ + +#define SKB_RECYCLING_THRESHOLD 32 + +static LIST_HEAD(recycling_queue); + +static int recycling_count; + +static DEFINE_HARD_SPINLOCK(recycling_lock); + +static void skb_recycler(struct evl_work *work) +{ + struct sk_buff *skb, *next; + unsigned long flags; + LIST_HEAD(list); + + raw_spin_lock_irqsave(&recycling_lock, flags); + list_splice_init(&recycling_queue, &list); + recycling_count = 0; + raw_spin_unlock_irqrestore(&recycling_lock, flags); + + local_bh_disable(); + + list_for_each_entry_safe(skb, next, &list, list) { + skb_list_del_init(skb); + finalize_skb_inband(skb); + } + + local_bh_enable(); +} + +static EVL_DEFINE_WORK(recycler_work, skb_recycler); + +static inline void maybe_kick_recycler(void) +{ + if (READ_ONCE(recycling_count) >= SKB_RECYCLING_THRESHOLD) + evl_call_inband(&recycler_work); +} + +static struct page *alloc_bufpage(struct net_device *dev, + ktime_t timeout, enum evl_tmode tmode) +{ + struct evl_netdev_state *est = dev->oob_state.estate; + unsigned long flags; + struct page *page; + int ret; + + for (;;) { + raw_spin_lock_irqsave(&est->tx_wait.wchan.lock, flags); + + page = page_pool_dev_alloc_pages(est->tx_pages); + if (likely(page)) + break; + + if (timeout == EVL_NONBLOCK) { + page = ERR_PTR(-EWOULDBLOCK); + break; + } + + evl_add_wait_queue(&est->tx_wait, timeout, tmode); + + raw_spin_unlock_irqrestore(&est->tx_wait.wchan.lock, flags); + + ret = evl_wait_schedule(&est->tx_wait); + if (ret) + return ERR_PTR(ret); + } + + raw_spin_unlock_irqrestore(&est->tx_wait.wchan.lock, flags); + + return page; +} + +struct sk_buff *evl_net_dev_alloc_skb(struct net_device *dev, + ktime_t timeout, enum evl_tmode tmode) +{ + struct evl_netdev_state *est; + struct net_device *real_dev; + struct sk_buff *skb; + struct page *page; + + /* + * Statically check the sanity of our basic assumptions: + * + * - the size of our control block fits into the space + * reserved for this purpose in the generic socket buffer. + * + * - the list head we use for queuing buffers does not overlap + * the device pointer in the unionized layout (this is + * definitely ugly, for sure). + */ + BUILD_BUG_ON(sizeof(struct evl_net_cb) > sizeof(skb->cb)); + BUILD_BUG_ON(sizeof(skb->list) > sizeof(struct sk_buff_list)); + + /* + * Build a free skb (for TX) from a page pulled from a + * per-device pool, enforcing congestion control according to + * the specified timeout rule. + */ + real_dev = evl_net_real_dev(dev); + page = alloc_bufpage(real_dev, timeout, tmode); + if (IS_ERR(page)) + return ERR_PTR(PTR_ERR(page)); + + est = real_dev->oob_state.estate; + skb = build_skb(page_address(page), est->buf_size); + if (!skb) { + maybe_kick_recycler(); /* Hope for the best. */ + return ERR_PTR(-ENOMEM); + } + + skb_mark_oob_storage(skb); + skb_mark_for_recycle(skb); + /* + * The current assumption is that we are going to deal with + * ethernet devices, for which we may need some extra header + * space for adding the 802.1q encapsulation. Reserve enough + * headroom, so that we won't have to reallocate for such + * purpose. + */ + skb_reserve(skb, VLAN_HLEN); + skb->dev = real_dev; + + return skb; +} + +/* + * Plan for a skb to be released by the in-band stack. + * + * CAUTION: the caller must call evl_schedule() and call the in-band + * recycler. + */ +static void free_inband_skb(struct sk_buff *skb) +{ + unsigned long flags; + + if (running_inband()) { + finalize_skb_inband(skb); + } else { + raw_spin_lock_irqsave(&recycling_lock, flags); + list_add(&skb->list, &recycling_queue); + recycling_count++; + raw_spin_unlock_irqrestore(&recycling_lock, flags); + } +} + +static void __free_evl_skb(struct sk_buff *skb) +{ + struct skb_shared_info *shinfo = skb_shinfo(skb); + struct net_device *dev = skb->dev; + struct evl_netdev_state *est = dev->oob_state.estate; + unsigned long flags; + + /* If the data storage is still shared, don't release it. */ + if (skb->cloned && + atomic_sub_return(skb->nohdr ? (1 << SKB_DATAREF_SHIFT) + 1 : 1, + &shinfo->dataref)) + goto release_head; + + /* + * Release the data. This is the gist of skb_pp_recycle(), + * since we already know for sure that an oob-managed skb is + * built around a page from a per-device pool (in + * evl_netdev_state). + */ + napi_pp_put_page(virt_to_page(skb->head), false); + + /* + * Wake up any thread waiting for buffer space to send to the + * device we are releasing the page to. + */ + raw_spin_lock_irqsave(&est->tx_wait.wchan.lock, flags); + + if (evl_wait_active(&est->tx_wait)) + evl_wake_up_head(&est->tx_wait); + + raw_spin_unlock_irqrestore(&est->tx_wait.wchan.lock, flags); + + evl_signal_poll_events(&est->poll_head, POLLOUT|POLLWRNORM); + +release_head: + EVL_WARN_ON(NET, atomic_read(&shinfo->dataref) < 0); + /* Now release the buffer head. */ + put_oob_skb(skb); +} + +/* + * Free an skb we originally allocated from our pool. The caller has + * exclusive ownership on this (i.e. no other reference is pending). + */ +static void free_evl_skb(struct sk_buff *skb) +{ + struct net_device *dev = skb->dev; + struct sk_buff *fskb, *nskb; + + if (EVL_WARN_ON(NET, dev == NULL)) + return; + + /* + * All skbs on a given fragment list are guaranteed to belong + * to the same device. + */ + for (fskb = skb_shinfo(skb)->frag_list; fskb; fskb = nskb) { + netdev_dbg(dev, "releasing frag %px from %px\n", fskb, skb); + nskb = fskb->next; + __free_evl_skb(fskb); + } + + netdev_dbg(dev, "releasing skb %px (has_frags=%d)\n", + skb, skb_has_frag_list(skb)); + + __free_evl_skb(skb); +} + +static void __free_skb(struct sk_buff *skb) +{ + /* + * If the skb data does not live in an oob pool, hand over the + * release to the in-band stack. Otherwise we may immediately + * attempt to free the data if no other skb refers to it, and + * the buffer head too. + */ + if (!skb_has_oob_storage(skb)) + free_inband_skb(skb); + else + free_evl_skb(skb); +} + +static void free_skb(struct sk_buff *skb) +{ + if (skb_unref(skb)) + __free_skb(skb); +} + +/** + * evl_net_free_skb - releases a socket buffer. + * + * Packets which were conveying out-of-band data are moved back + * to the originating per-device pool (if that device is still + * active). Otherwise, the packet is scheduled for release to the + * in-band pool. + * + * @skb the packet to release. Not linked to any upstream + * queue. The routine also accepts regular in-band buffers. + */ +void evl_net_free_skb(struct sk_buff *skb) /* in-band/oob */ +{ + EVL_WARN_ON(NET, hard_irqs_disabled()); + + free_skb(skb); + evl_schedule(); + maybe_kick_recycler(); +} + +/** + * evl_net_free_skb_list - releases a list of socket buffers. + * + * Releases a list of buffers linked to a private list. Buffers + * may belong to different devices. + + * @list the list head queuing packets to release. + */ +void evl_net_free_skb_list(struct list_head *list) +{ + struct sk_buff *skb, *n; + + EVL_WARN_ON(NET, hard_irqs_disabled()); + + if (list_empty(list)) + return; + + list_for_each_entry_safe(skb, n, list, list) + free_skb(skb); + + evl_schedule(); + maybe_kick_recycler(); +} + +/** + * free_skb_oob - attempt to free a buffer head along with its + * data storage. + * + * Called from the in-band net core right after the last + * reference to the buffer was dropped. We get a chance to + * release the buffer immediately to our bufheads pool. However, + * if the buffer data was allocated in-band, send the skb back to + * the in-band core for disposal from there. + */ +void free_skb_oob(struct sk_buff *skb) /* inband/oob */ +{ + EVL_WARN_ON(NET, hard_irqs_disabled()); + + /* + * The in-band stack should give us only fully released + * buffers via this hook. skb_unref() might have skipped + * decrementation down to zero if skb->users == 1 on entry + * (i.e. exclusive ownership), account for this. + */ + if (EVL_WARN_ON(NET, refcount_read(&skb->users) > 1)) + return; + + __free_skb(skb); + evl_schedule(); + maybe_kick_recycler(); +} + +/** + * evl_net_clone_skb - clone a socket buffer. + * + * Allocate and build a clone of @skb, referring to the same + * data. + * + * @skb the packet to clone. + * + * CAUTION: fragments are not cloned. + */ +struct sk_buff *evl_net_clone_skb(struct sk_buff *skb) +{ + struct sk_buff *clone; + + clone = get_oob_skb(); + if (!clone) + return NULL; + + clone->head = NULL; /* So we can morph safely. */ + skb_morph(clone, skb); + + return clone; +} + +void evl_net_init_skb_queue(struct evl_net_skb_queue *skbq) +{ + INIT_LIST_HEAD(&skbq->queue); + raw_spin_lock_init(&skbq->lock); +} + +void evl_net_destroy_skb_queue(struct evl_net_skb_queue *skbq) +{ + evl_net_free_skb_list(&skbq->queue); +} + +void evl_net_add_skb_queue(struct evl_net_skb_queue *skbq, + struct sk_buff *skb) +{ + unsigned long flags; + + raw_spin_lock_irqsave(&skbq->lock, flags); + list_add_tail(&skb->list, &skbq->queue); + raw_spin_unlock_irqrestore(&skbq->lock, flags); +} + +struct sk_buff *evl_net_get_skb_queue(struct evl_net_skb_queue *skbq) +{ + struct sk_buff *skb = NULL; + unsigned long flags; + + raw_spin_lock_irqsave(&skbq->lock, flags); + + if (!list_empty(&skbq->queue)) + skb = list_get_entry(&skbq->queue, struct sk_buff, list); + + raw_spin_unlock_irqrestore(&skbq->lock, flags); + + return skb; +} + +bool evl_net_move_skb_queue(struct evl_net_skb_queue *skbq, + struct list_head *list) +{ + unsigned long flags; + bool ret; + + raw_spin_lock_irqsave(&skbq->lock, flags); + list_splice_init(&skbq->queue, list); + ret = !list_empty(list); + raw_spin_unlock_irqrestore(&skbq->lock, flags); + + return ret; +} + +bool evl_net_charge_skb_rmem(struct evl_socket *esk, struct sk_buff *skb) +{ + bool ret; + + EVL_NET_CB(skb)->tracker = NULL; + ret = evl_charge_socket_rmem(esk, skb->truesize); + if (likely(ret)) + EVL_NET_CB(skb)->tracker = esk; + + return ret; +} + +void evl_net_uncharge_skb_rmem(struct sk_buff *skb) +{ + struct evl_socket *esk = EVL_NET_CB(skb)->tracker; + + if (esk) { + EVL_NET_CB(skb)->tracker = NULL; + evl_uncharge_socket_rmem(esk, skb->truesize); + } +} + +int evl_net_charge_skb_wmem(struct evl_socket *esk, + struct sk_buff *skb, + ktime_t timeout, enum evl_tmode tmode) +{ + int ret; + + EVL_NET_CB(skb)->tracker = NULL; + ret = evl_charge_socket_wmem(esk, skb->truesize, timeout, tmode); + if (likely(!ret)) + EVL_NET_CB(skb)->tracker = esk; + + return ret; +} + +void evl_net_uncharge_skb_wmem(struct sk_buff *skb) +{ + struct evl_socket *esk = EVL_NET_CB(skb)->tracker; + + /* + * If set, the tracking socket cannot be stale as it has to + * pass the wmem_crossing first before unwinding in + * sock_oob_destroy(). + */ + if (esk) { + EVL_NET_CB(skb)->tracker = NULL; + evl_uncharge_socket_wmem(esk, skb->truesize); + } +} + +/* in-band */ +int evl_net_dev_build_pool(struct net_device *dev) +{ + struct page_pool_params pp_params; + struct evl_netdev_state *est; + + if (EVL_WARN_ON(NET, is_vlan_dev(dev))) + return -EINVAL; + + if (EVL_WARN_ON(NET, netif_oob_diversion(dev))) + return -EBUSY; + + est = dev->oob_state.estate; + + /* + * Set up a page pool for TX from the EVL netstack through the + * device. + */ + est->buf_size = ALIGN(est->buf_size, PAGE_SIZE); + pp_params = (struct page_pool_params){ + .order = ilog2(est->buf_size / PAGE_SIZE), + .flags = PP_FLAG_PAGE_OOB, + .pool_size = est->pool_max, + .nid = dev_to_node(dev->dev.parent), + .dev = dev->dev.parent, + .dma_dir = DMA_NONE, + .offset = 0, + .max_len = est->buf_size, + }; + + /* + * If the device is oob-capable, the page pool must perform + * DMA pre-mapping so that the NIC driver only has to deal + * with cache synchronization on the out-of-band TX path. We + * are piggybacked by the XDP/TX support which enables + * DMA_BIDIRECTIONAL (DMA_TO_DEVICE is not supported). + */ + if (netdev_is_oob_capable(dev)) { + pp_params.flags |= PP_FLAG_DMA_MAP | PP_FLAG_DMA_SYNC_DEV; + pp_params.dma_dir = DMA_BIDIRECTIONAL; + } + + est->tx_pages = page_pool_create(&pp_params); + if (IS_ERR(est->tx_pages)) + return PTR_ERR(est->tx_pages); + + evl_init_wait(&est->tx_wait, &evl_mono_clock, EVL_WAIT_PRIO); + evl_init_poll_head(&est->poll_head); + + return 0; +} + +/* in-band, only when diversion is disabled! */ +void evl_net_dev_purge_pool(struct net_device *dev) +{ + struct evl_netdev_state *est; + + if (EVL_WARN_ON(NET, netif_oob_diversion(dev))) + return; + + est = dev->oob_state.estate; + evl_destroy_wait(&est->tx_wait); + page_pool_destroy(est->tx_pages); +} + +/* + * evl_net_wget_skb - allocate a buffer with contention management for + * output. + * + * If the allocation causes the per-socket write contention threshold + * to be crossed, the caller may sleep according to the timeout + * specification. + */ +struct sk_buff *evl_net_wget_skb(struct evl_socket *esk, + struct net_device *dev, ktime_t timeout) +{ + enum evl_tmode tmode = timeout ? EVL_ABS : EVL_REL; + struct sk_buff *skb; + int ret; + + skb = evl_net_dev_alloc_skb(dev, timeout, tmode); + if (IS_ERR(skb)) + return skb; + + ret = evl_net_charge_skb_wmem(esk, skb, timeout, tmode); + + return ret ? ERR_PTR(ret) : skb; +} + +/* + * evl_net_wput_skb - deallocate a buffer obtained from + * evl_net_wget_skb() for output. + * + * Fragments are deallocated if present. + */ +void evl_net_wput_skb(struct sk_buff *skb) +{ + struct sk_buff *fskb; + + skb_walk_frags(skb, fskb) { + evl_net_uncharge_skb_wmem(fskb); + } + evl_net_uncharge_skb_wmem(skb); + evl_net_free_skb(skb); +} + +/* + * evl_net_rput_skb - deallocate a buffer obtained from the ingress + * path. + * + * Fragments are deallocated if present. + */ +void evl_net_rput_skb(struct sk_buff *skb) +{ + struct sk_buff *fskb; + + skb_walk_frags(skb, fskb) { + evl_net_uncharge_skb_rmem(fskb); + } + evl_net_uncharge_skb_rmem(skb); + evl_net_free_skb(skb); +} + +static ssize_t __skb_to_uio(const struct iovec *iov, size_t iovlen, + size_t *vpos, size_t *bpos, + const void *data, size_t len) +{ + size_t rem = len; + ssize_t ret = 0; + + while (rem > 0) { + size_t avail = iov[*vpos].iov_len - *bpos, copy = rem; + if (avail == 0) { + if (++(*vpos) >= iovlen) + break; + *bpos = 0; + continue; + } + if (copy > avail) + copy = avail; + if (raw_copy_to_user(iov[*vpos].iov_base + *bpos, data + ret, copy)) + return -EFAULT; + *bpos += copy; + ret += copy; + rem -= copy; + } + + return ret; +} + +static ssize_t skb_to_uio(const struct iovec *iov, size_t iovlen, + size_t *vpos, size_t *bpos, + const void *data, size_t len) +{ + size_t rem = len; + ssize_t ret = 0; + + while (rem > 0) { + ssize_t partial = __skb_to_uio(iov, iovlen, vpos, bpos, + data + ret, rem); + if (partial <= 0) + return partial; + ret += partial; + rem -= partial; + } + + return ret; +} + +/* + * evl_net_skb_to_uio - copy the content of a socket buffer to a user + * I/O vector. @skb may contain fragments. + * + * Returns the count of bytes written to @iov, or -EFAULT on uaccess + * error. @short_write is set on return if not enough space is + * available from @iov for storing the entire content. + */ +ssize_t evl_net_skb_to_uio(const struct iovec *iov, size_t iovlen, + struct sk_buff *skb, + size_t skip, + bool *short_write) +{ + size_t vpos = 0, bpos = 0; + struct sk_buff *fskb; + ssize_t ret, out; + + if (skip) + skb_pull_inline(skb, skip); + + ret = skb_to_uio(iov, iovlen, &vpos, &bpos, skb->data, skb->len); + if (ret < skb->len) { + *short_write = true; + return ret; + } + + skb_walk_frags(skb, fskb) { + if (skip) + skb_pull_inline(fskb, skip); + out = skb_to_uio(iov, iovlen, &vpos, &bpos, fskb->data, fskb->len); + if (out < 0) + return out; + ret += out; + if (out < fskb->len) { + *short_write = true; + break; + } + } + + *short_write = false; + + return ret; +} diff --git a/kernel/evl/net/socket.c b/kernel/evl/net/socket.c new file mode 100644 index 000000000..83dea0bae --- /dev/null +++ b/kernel/evl/net/socket.c @@ -0,0 +1,762 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2020 Philippe Gerum + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* + * EVL sockets are (almost) regular sockets, extended with out-of-band + * capabilities. In theory, this would allow us to provide out-of-band + * services on top of any common protocol already handled by the + * in-band network stack. EVL-specific protocols belong to the generic + * PF_OOB family, which we use as a protocol mutiplexor. + */ + +#define EVL_DOMAIN_HASH_BITS 8 + +static DEFINE_HASHTABLE(domain_hash, EVL_DOMAIN_HASH_BITS); + +static DEFINE_MUTEX(domain_lock); + +struct domain_list_head { + int af_domain; + u32 hkey; + struct hlist_node hash; + struct list_head list; +}; + +/* + * EVL sockets are always bound to an EVL file (see + * sock_oob_attach()). We may access our extended socket context via + * filp->f_oob_ctx or sock->sk->sk_oob_ctx, which works for all socket + * families. + */ +static inline struct evl_socket *evl_sk_from_file(struct file *filp) +{ + return filp->f_oob_ctx ? + container_of(filp->f_oob_ctx, struct evl_socket, efile) : + NULL; +} + +static inline struct evl_socket *evl_sk(struct sock *sk) +{ + return sk->sk_oob_ctx; +} + +static inline u32 get_domain_hash(int af_domain) +{ + u32 hsrc = af_domain; + + return jhash2(&hsrc, 1, 0); +} + +/* domain_lock held */ +static struct domain_list_head *fetch_domain_list(u32 hkey) +{ + struct domain_list_head *head; + + hash_for_each_possible(domain_hash, head, hash, hkey) + if (head->hkey == hkey) + return head; + + return NULL; +} + +int evl_register_socket_domain(struct evl_socket_domain *domain) +{ + struct domain_list_head *head; + u32 hkey; + + inband_context_only(); + + hkey = get_domain_hash(domain->af_domain); + + mutex_lock(&domain_lock); + + head = fetch_domain_list(hkey); + if (head == NULL) { + head = kzalloc(sizeof(*head), GFP_KERNEL); + if (head) { + head->af_domain = domain->af_domain; + head->hkey = hkey; + INIT_LIST_HEAD(&head->list); + hash_add(domain_hash, &head->hash, hkey); + } + } + + if (head) /* Add LIFO to allow for override. */ + list_add(&domain->next, &head->list); + + mutex_unlock(&domain_lock); + + return head ? 0 : -ENOMEM; +} + +void evl_unregister_socket_domain(struct evl_socket_domain *domain) +{ + struct domain_list_head *head; + u32 hkey; + + inband_context_only(); + + hkey = get_domain_hash(domain->af_domain); + + mutex_lock(&domain_lock); + + head = fetch_domain_list(hkey); + if (head) { + list_del(&domain->next); + if (list_empty(&head->list)) { + hash_del(&head->hash); + kfree(head); + } + } else { + EVL_WARN_ON(NET, 1); + } + + mutex_unlock(&domain_lock); +} + +static inline bool charge_socket_wmem(struct evl_socket *esk, size_t size) +{ /* esk->wmem_wait.wchan.lock held */ + if (atomic_read(&esk->wmem_count) >= esk->wmem_max) + return false; + + atomic_add(size, &esk->wmem_count); + evl_down_crossing(&esk->wmem_drain); + + return true; +} + +int evl_charge_socket_wmem(struct evl_socket *esk, size_t size, + ktime_t timeout, enum evl_tmode tmode) +{ + if (!esk->wmem_max) /* Unlimited. */ + return 0; + + return evl_wait_event_timeout(&esk->wmem_wait, timeout, tmode, + charge_socket_wmem(esk, size)); +} + +void evl_uncharge_socket_wmem(struct evl_socket *esk, size_t size) +{ + unsigned long flags; + int count; + + /* + * The tracking socket cannot be stale as it has to pass the + * wmem_crossing first before unwinding in sock_oob_destroy(). + */ + raw_spin_lock_irqsave(&esk->wmem_wait.wchan.lock, flags); + + count = atomic_sub_return(size, &esk->wmem_count); + if (count < esk->wmem_max && evl_wait_active(&esk->wmem_wait)) + evl_flush_wait_locked(&esk->wmem_wait, 0); + + evl_up_crossing(&esk->wmem_drain); + + raw_spin_unlock_irqrestore(&esk->wmem_wait.wchan.lock, flags); + + EVL_WARN_ON(NET, count < 0); +} + +/* in-band */ +static struct evl_net_proto *find_oob_proto(int domain, int type, int protocol) +{ + struct evl_net_proto *proto = NULL; + struct domain_list_head *head; + struct evl_socket_domain *d; + u32 hkey; + + hkey = get_domain_hash(domain); + + mutex_lock(&domain_lock); + + head = fetch_domain_list(hkey); + if (head) { + list_for_each_entry(d, &head->list, next) { + if (d->af_domain != domain) + continue; + proto = d->match(type, protocol); + if (proto) + break; + } + } + + mutex_unlock(&domain_lock); + + return proto; +} + +/* + * The inband offload handler. Handles packets for which we cannot + * handle from the oob stage directly (e.g. because we don't have the + * routing information available in our oob front-cache). + */ +static void inband_offload_handler(struct evl_work *work) +{ + struct evl_socket *esk = + container_of(work, struct evl_socket, inband_offload); + + if (EVL_WARN_ON(NET, !esk->proto->handle_offload)) + return; + + esk->proto->handle_offload(esk); + + /* Release the ref. obtained by evl_net_offload_inband(). */ + evl_put_file(&esk->efile); +} + +/* + * Offload a protocol-specific operation to the in-band stage. + */ +void evl_net_offload_inband(struct evl_socket *esk, + struct evl_net_offload *ofld, + struct list_head *q) +{ + unsigned long flags; + + /* + * Make sure esk won't vanish until the offload handler has + * run. + */ + evl_get_fileref(&esk->efile); + + raw_spin_lock_irqsave(&esk->oob_lock, flags); + list_add_tail(&ofld->next, q); + raw_spin_unlock_irqrestore(&esk->oob_lock, flags); + + if (!evl_call_inband(&esk->inband_offload)) + evl_put_file(&esk->efile); +} + +/* + * In-band call from the common network stack creating a new BSD + * socket, @sock is already bound to a file. We know the following: + * + * - the caller wants us either to attach an out-of-band extension to + * a common protocol (e.g. AF_PACKET over ethernet), or to set up an + * mere AF_OOB socket for EVL-specific protocols. + * + * - we have no oob extension context for @sock yet + * (sock->sk->sk_oob_ctx is NULL) + */ +int sock_oob_attach(struct socket *sock) +{ + struct evl_net_proto *proto; + struct sock *sk = sock->sk; + struct evl_socket *esk; + int ret; + + /* + * Try finding a suitable out-of-band protocol among those + * registered in EVL. + */ + proto = find_oob_proto(sk->sk_family, sk->sk_type, sk->sk_protocol); + if (proto == NULL) + return -EPROTONOSUPPORT; + + /* + * We might support a protocol, but we might not be happy with + * the socket type (e.g. AF_PACKET mandates SOCK_RAW). + */ + if (IS_ERR(proto)) + return PTR_ERR(proto); + + /* + * If sk->sk_family is not PF_OOB, we have no extended oob + * context yet, allocate one to piggyback on a common socket. + */ + if (sk->sk_family != PF_OOB) { + esk = kzalloc(sizeof(*esk), GFP_KERNEL); + if (esk == NULL) + return -ENOMEM; + refcount_set(&esk->refs, 2); /* release + destroy */ + } else { + esk = (struct evl_socket *)sk; + refcount_set(&esk->refs, 1); /* release only */ + } + + esk->sk = sk; + + /* + * Bind the underlying socket file to an EVL file, which + * enables out-of-band I/O requests for that socket. + */ + ret = evl_open_file(&esk->efile, sock->file); + if (ret) + goto fail_open; + + /* + * In-band wise, the host socket is fully initialized, so the + * in-band network stack already holds a ref. on the net + * struct for that socket. + */ + esk->net = sock_net(sk); + mutex_init(&esk->lock); + INIT_LIST_HEAD(&esk->input); + INIT_LIST_HEAD(&esk->next_sub); + evl_init_wait(&esk->input_wait, &evl_mono_clock, 0); + evl_init_wait(&esk->wmem_wait, &evl_mono_clock, 0); + evl_init_poll_head(&esk->poll_head); + raw_spin_lock_init(&esk->oob_lock); + evl_init_work(&esk->inband_offload, inband_offload_handler); + /* Inherit the {rw}mem limits from the base socket. */ + esk->rmem_max = sk->sk_rcvbuf; + esk->wmem_max = sk->sk_sndbuf; + evl_init_crossing(&esk->wmem_drain); + + ret = proto->attach(esk, proto, ntohs(sk->sk_protocol)); + if (ret) + goto fail_attach; + + sk->sk_oob_ctx = esk; + + return 0; + +fail_attach: + evl_release_file(&esk->efile); +fail_open: + if (sk->sk_family != PF_OOB) + kfree(esk); + + return ret; +} + +/* + * In-band call from the common network stack releasing a BSD socket, + * @sock is still bound to a file, but the network representation + * sock->sk might be stale. + */ +void sock_oob_release(struct socket *sock) +{ + struct evl_socket *esk = evl_sk_from_file(sock->file); + + if (esk->proto->release) + esk->proto->release(esk); + + evl_release_file(&esk->efile); + /* Wait for the stack to drain in-flight outgoing buffers. */ + evl_pass_crossing(&esk->wmem_drain); + + if (refcount_dec_and_test(&esk->refs)) + kfree(esk); +} + +/* + * In-band call from the common network stack which is about to + * destruct a socket, releasing all resources attached (@sock is + * out-of-band capable). + */ +void sock_oob_destroy(struct sock *sk) +{ + struct evl_socket *esk = evl_sk(sk); + + /* We are detaching, so rmem_count can be left out of sync. */ + evl_net_free_skb_list(&esk->input); + + evl_destroy_wait(&esk->input_wait); + evl_destroy_wait(&esk->wmem_wait); + + if (esk->proto->destroy) + esk->proto->destroy(esk); + + if (sk->sk_family != PF_OOB && refcount_dec_and_test(&esk->refs)) + kfree(esk); /* meaning sk != esk. */ + + sk->sk_oob_ctx = NULL; +} + +/* + * In-band call from the common network stack to complete a binding + * (@sock is out-of-band capable). We end up here _after_ a successful + * binding of the network socket to the given address by the in-band + * stack. + */ +int sock_oob_bind(struct sock *sk, struct sockaddr *addr, int len) +{ + struct evl_socket *esk = evl_sk(sk); + + /* + * If @sk belongs to PF_OOB, then evl_sock_bind() already + * handled the binding. We only care about common protocols + * for which we have an out-of-band extension + * (e.g. AF_PACKET). + */ + if (sk->sk_family == PF_OOB || !esk->proto->bind) + return 0; + + return esk->proto->bind(esk, addr, len); +} + +/* + * In-band call from the common network stack to shutdown the + * socket. We end up here _after_ the socket was successfully shut + * down by the in-band network stack. + */ +int sock_oob_shutdown(struct sock *sk, int how) +{ + struct evl_socket *esk = evl_sk(sk); + + /* + * If @sk belongs to PF_OOB, then evl_sock_shutdown() already + * handled the connection. We only care about common protocols + * for which we have an out-of-band extension + * (e.g. AF_INET/IPPROTO_UDP). + */ + if (sk->sk_family == PF_OOB || !esk->proto->shutdown) + return 0; + + return esk->proto->shutdown(esk, how); +} + +/* + * In-band call from the common network stack to connect the socket. + * We end up here _after_ a successful connection of the network + * socket to the given address by the in-band stack. + */ +int sock_oob_connect(struct sock *sk, + struct sockaddr *addr, int len, int flags) +{ + struct evl_socket *esk = evl_sk(sk); + + /* + * If @sk belongs to PF_OOB, then evl_sock_connect() already + * handled the connection. We only care about common protocols + * for which we have an out-of-band extension + * (e.g. AF_INET/IPPROTO_UDP). + */ + if (sk->sk_family == PF_OOB || !esk->proto->connect) + return 0; + + return esk->proto->connect(esk, addr, len, flags); +} + +static int socket_send_recv(struct evl_socket *esk, + struct user_oob_msghdr __user *u_msghdr, + unsigned int cmd) +{ + struct iovec fast_iov[UIO_FASTIOV], *iov, __user *u_iov; + __u64 iov_ptr; + __u32 iovlen; + __s32 count; + int ret; + + ret = raw_get_user(iov_ptr, &u_msghdr->iov_ptr); + if (ret) + return -EFAULT; + + ret = raw_get_user(iovlen, &u_msghdr->iovlen); + if (ret) + return -EFAULT; + + u_iov = evl_valptr64(iov_ptr, struct iovec); + iov = evl_load_uio(u_iov, iovlen, fast_iov); + if (IS_ERR(iov)) + return PTR_ERR(iov); + + if (cmd == EVL_SOCKIOC_SENDMSG) + count = esk->proto->oob_send(esk, u_msghdr, iov, iovlen); + else + count = esk->proto->oob_receive(esk, u_msghdr, iov, iovlen); + + if (iov != fast_iov) + evl_free(iov); + + if (count < 0) + return count; + + ret = raw_put_user(count, &u_msghdr->count); + if (ret) + return -EFAULT; + + return 0; +} + +long sock_oob_ioctl(struct file *filp, unsigned int cmd, + unsigned long arg) +{ + struct evl_socket *esk = evl_sk_from_file(filp); + struct user_oob_msghdr __user *u_msghdr; + long ret; + + if (esk == NULL) + return -EBADFD; + + switch (cmd) { + case EVL_SOCKIOC_SENDMSG: + case EVL_SOCKIOC_RECVMSG: + u_msghdr = (typeof(u_msghdr))arg; + ret = socket_send_recv(esk, u_msghdr, cmd); + break; + default: + ret = -ENOTTY; + } + + return ret; +} + +ssize_t sock_oob_write(struct file *filp, + const char __user *u_buf, size_t count) +{ + struct evl_socket *esk = evl_sk_from_file(filp); + struct iovec iov; + + if (esk == NULL) + return -EBADFD; + + if (!count) + return 0; + + iov.iov_base = (void *)u_buf; + iov.iov_len = count; + + return esk->proto->oob_send(esk, NULL, &iov, 1); +} + +ssize_t sock_oob_read(struct file *filp, + char __user *u_buf, size_t count) +{ + struct evl_socket *esk = evl_sk_from_file(filp); + struct iovec iov; + + if (esk == NULL) + return -EBADFD; + + if (!count) + return 0; + + iov.iov_base = u_buf; + iov.iov_len = count; + + return esk->proto->oob_receive(esk, NULL, &iov, 1); +} + +__poll_t sock_oob_poll(struct file *filp, + struct oob_poll_wait *wait) +{ + struct evl_socket *esk = evl_sk_from_file(filp); + + if (esk == NULL) + return -EBADFD; + + return esk->proto->oob_poll(esk, wait); +} + +static int socket_set_rmem(struct evl_socket *esk, int __user *u_val) +{ + int ret, val; + + ret = raw_get_user(val, u_val); + if (ret) + return -EFAULT; + + /* Same logic as __sock_set_rcvbuf(). */ + val = min_t(int, val, INT_MAX / 2); + WRITE_ONCE(esk->rmem_max, max_t(int, val * 2, SOCK_MIN_RCVBUF)); + + return 0; +} + +static int socket_set_wmem(struct evl_socket *esk, int __user *u_val) +{ + int ret, val; + + ret = raw_get_user(val, u_val); + if (ret) + return -EFAULT; + + val = min_t(int, val, INT_MAX / 2); + WRITE_ONCE(esk->wmem_max, max_t(int, val * 2, SOCK_MIN_SNDBUF)); + + return 0; +} + +static int sock_inband_ioctl(struct sock *sk, unsigned int cmd, + unsigned long arg) +{ + struct evl_socket *esk = evl_sk(sk); + struct evl_netdev_activation act, __user *u_act; + int __user *u_val; + int ret; + + switch (cmd) { + case EVL_SOCKIOC_ACTIVATE: /* Turn oob port on. */ + u_act = (typeof(u_act))arg; + ret = raw_copy_from_user(&act, u_act, sizeof(act)); + if (ret) + return -EFAULT; + ret = evl_net_switch_oob_port(esk, &act); + break; + case EVL_SOCKIOC_DEACTIVATE: /* Turn oob port off. */ + ret = evl_net_switch_oob_port(esk, NULL); + break; + case EVL_SOCKIOC_SETRECVSZ: + u_val = (typeof(u_val))arg; + ret = socket_set_rmem(esk, u_val); + break; + case EVL_SOCKIOC_SETSENDSZ: + u_val = (typeof(u_val))arg; + ret = socket_set_wmem(esk, u_val); + break; + default: + ret = -ENOTTY; + if (esk->proto->ioctl) + ret = esk->proto->ioctl(esk, cmd, arg); + } + + return ret; +} + +/* + * Ioctl redirector for common protocols with oob extension. AF_OOB + * jumps directly to sock_ioctl() via the netproto ops instead. If the + * out-of-band protocol implementation was not able to handle the + * EVL-specific command, we should return -ENOIOCTLCMD to the caller, + * so that it tries harder to find a suitable handler. + */ +long sock_inband_ioctl_redirect(struct sock *sk, /* in-band hook */ + unsigned int cmd, unsigned long arg) +{ + long ret = sock_inband_ioctl(sk, cmd, arg); + + return ret == -ENOTTY ? -ENOIOCTLCMD : ret; +} + +static int evl_sock_ioctl(struct socket *sock, unsigned int cmd, + unsigned long arg) +{ + return sock_inband_ioctl(sock->sk, cmd, arg); +} + +static int evl_sock_bind(struct socket *sock, struct sockaddr *u_addr, int len) +{ + struct evl_socket *esk = evl_sk(sock->sk); + + return esk->proto->bind(esk, u_addr, len); +} + +static int evl_sock_connect(struct socket *sock, + struct sockaddr *u_addr, int len, int flags) +{ + struct evl_socket *esk = evl_sk(sock->sk); + + return esk->proto->connect(esk, u_addr, len, flags); +} + +static int evl_sock_shutdown(struct socket *sock, int how) +{ + struct evl_socket *esk = evl_sk(sock->sk); + + return esk->proto->shutdown(esk, how); +} + +static int evl_sock_release(struct socket *sock) +{ + /* + * Cleanup happens from sock_oob_destroy(), so that PF_OOB and + * common protocols sockets we piggybacked on are released. + */ + return 0; +} + +static const struct proto_ops netproto_ops = { + .family = PF_OOB, + .owner = THIS_MODULE, + .release = evl_sock_release, + .bind = evl_sock_bind, + .connect = evl_sock_connect, + .shutdown = evl_sock_shutdown, + .ioctl = evl_sock_ioctl, + .socketpair = sock_no_socketpair, + .accept = sock_no_accept, + .getname = sock_no_getname, + .listen = sock_no_listen, + .sendmsg = sock_no_sendmsg, + .recvmsg = sock_no_recvmsg, + .mmap = sock_no_mmap, +}; + +/* + * A generic family for protocols implemented by the companion + * core. user<->evl interaction is possible only through the + * oob_read/oob_write/oob_ioctl/ioctl calls. + */ +struct proto evl_af_oob_proto = { + .name = "EVL", + .owner = THIS_MODULE, + .obj_size = sizeof(struct evl_socket), +}; + +static void destroy_evl_socket(struct sock *sk) +{ + local_bh_disable(); + sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1); + local_bh_enable(); +} + +static int create_evl_socket(struct net *net, struct socket *sock, + int protocol, int kern) +{ + struct sock *sk; + + if (kern) + return -EOPNOTSUPP; + + sock->state = SS_UNCONNECTED; + + sk = sk_alloc(net, PF_OOB, GFP_KERNEL, &evl_af_oob_proto, 0); + if (!sk) + return -ENOBUFS; + + sock->ops = &netproto_ops; + sock_init_data(sock, sk); + + /* + * Protocol is checked for validity when the socket is + * attached to the out-of-band core in sock_oob_attach(). + */ + sk->sk_protocol = htons(protocol); + sk->sk_destruct = destroy_evl_socket; + + local_bh_disable(); + sock_prot_inuse_add(net, &evl_af_oob_proto, 1); + local_bh_enable(); + + return 0; +} + +const struct net_proto_family evl_family_ops = { + .family = PF_OOB, + .create = create_evl_socket, + .owner = THIS_MODULE, +}; diff --git a/kernel/evl/observable.c b/kernel/evl/observable.c new file mode 100644 index 000000000..3f65c8a68 --- /dev/null +++ b/kernel/evl/observable.c @@ -0,0 +1,1171 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2020 Philippe Gerum + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* Co-exists with EVL_NOTIFY_MASK bits. */ +#define EVL_NOTIFY_INITIAL (1 << 31) + +#define EVL_OBSERVABLE_CLONE_FLAGS \ + (EVL_CLONE_PUBLIC|EVL_CLONE_OBSERVABLE|EVL_CLONE_UNICAST) + +/* + * We want any kind of threads to be able to subscribe to an + * observable including non-EVL ones, evl_subscriber holds the + * information we need for this. This descriptor is accessed directly + * from the task_struct via the oob thread state. + */ +struct evl_subscriber { + struct rb_root subscriptions; /* struct evl_observer */ + hard_spinlock_t lock; +}; + +struct evl_notification_record { + u32 tag; + u32 serial; + pid_t issuer; + union evl_value event; + ktime_t date; + struct list_head next; /* in evl_observers.(free|pending)_list */ +}; + +struct evl_observer { + size_t backlog_size; + struct list_head free_list; /* evl_notification_record */ + struct list_head pending_list; /* evl_notification_record */ + struct list_head next; /* in evl_observable.observers */ + fundle_t fundle; /* fundle of observable */ + struct rb_node rb; /* in evl_subscriber.subscriptions */ + int flags; /* EVL_NOTIFY_xx */ + int refs; /* notification vs unsubscription */ + struct evl_notice last_notice; + struct evl_notification_record backlog[0]; +}; + +static const struct file_operations observable_fops; + +static inline +int index_observer(struct rb_root *root, struct evl_observer *observer) +{ + struct rb_node **rbp, *parent = NULL; + struct evl_observer *tmp; + + rbp = &root->rb_node; + while (*rbp) { + tmp = rb_entry(*rbp, struct evl_observer, rb); + parent = *rbp; + if (observer->fundle < tmp->fundle) + rbp = &(*rbp)->rb_left; + else if (observer->fundle > tmp->fundle) + rbp = &(*rbp)->rb_right; + else + return -EEXIST; + } + + rb_link_node(&observer->rb, parent, rbp); + rb_insert_color(&observer->rb, root); + + return 0; +} + +static struct evl_observer * +find_observer(struct rb_root *root, fundle_t fundle) +{ + struct evl_observer *observer; + struct rb_node *rb; + + rb = root->rb_node; + while (rb) { + observer = rb_entry(rb, struct evl_observer, rb); + if (fundle < observer->fundle) + rb = rb->rb_left; + else if (fundle > observer->fundle) + rb = rb->rb_right; + else + return observer; + } + + return NULL; +} + +/* + * Threads can only subscribe/unsubscribe to/from observables for + * themselves, which guarantees that no observer can go away while a + * thread is accessing it from [oob_]read()/write() operations. An + * observer only knows about the observable's fundle, it does not + * maintain any memory reference to the former: we want lose coupling + * in this direction so that observables can go away while subscribers + * still target them. + */ +static int add_subscription(struct evl_observable *observable, + unsigned int backlog_count, int op_flags) /* in-band */ +{ + struct evl_subscriber *sbr = evl_get_subscriber(); + struct evl_notification_record *nf; + struct evl_observer *observer; + size_t backlog_size; + unsigned long flags; + unsigned int n; + int ret; + + inband_context_only(); + + if (backlog_count == 0) + return -EINVAL; + + if (op_flags & ~EVL_NOTIFY_MASK) + return -EINVAL; + + if (sbr == NULL) { + sbr = kzalloc(sizeof(*sbr), GFP_KERNEL); + if (sbr == NULL) + return -ENOMEM; + raw_spin_lock_init(&sbr->lock); + sbr->subscriptions = RB_ROOT; + evl_set_subscriber(sbr); + } + + /* + * We don't need to guard against racing with in-band file + * release since the caller must be running in-band, so the + * VFS already ensures consistency between release vs other + * in-band I/O ops. We do need a reference on the underlying + * element though. + */ + evl_get_element(&observable->element); + + /* + * The observer descriptor and its backlog are adjacent in + * memory. The backlog contains notification records, align on + * this element size. + */ + backlog_size = backlog_count * sizeof(*nf); + observer = kzalloc(sizeof(*observer) + backlog_size, GFP_KERNEL); + if (observer == NULL) { + ret = -ENOMEM; + goto fail_alloc; + } + + observer->fundle = fundle_of(observable); + observer->backlog_size = backlog_size; + observer->flags = op_flags; + observer->refs = 1; + INIT_LIST_HEAD(&observer->free_list); + INIT_LIST_HEAD(&observer->pending_list); + + if (op_flags & EVL_NOTIFY_ONCHANGE) + observer->flags |= EVL_NOTIFY_INITIAL; + + raw_spin_lock_irqsave(&sbr->lock, flags); + ret = index_observer(&sbr->subscriptions, observer); + raw_spin_unlock_irqrestore(&sbr->lock, flags); + if (ret) + goto dup_subscription; + + /* Build the free list of notification records. */ + for (nf = observer->backlog, n = 0; n < backlog_count; n++, nf++) + list_add(&nf->next, &observer->free_list); + + /* + * Make the new observer visible to the observable. We need + * the observer and writability tracking to be atomically + * updated, so nested locking is required. Observers are + * linked to the observable's list by order of subscription + * (FIFO) in case users make such assumption for unicast mode + * (which undergoes round-robin). + */ + raw_spin_lock_irqsave(&observable->lock, flags); + list_add_tail(&observer->next, &observable->observers); + raw_spin_lock(&observable->oob_wait.wchan.lock); + observable->writable_observers++; + raw_spin_unlock(&observable->oob_wait.wchan.lock); + raw_spin_unlock_irqrestore(&observable->lock, flags); + evl_signal_poll_events(&observable->poll_head, POLLOUT|POLLWRNORM); + evl_schedule(); + smp_mb(); + if (waitqueue_active(&observable->inband_wait_w)) + wake_up(&observable->inband_wait_w); + + evl_put_element(&observable->element); + + return 0; + +dup_subscription: + kfree(observer); +fail_alloc: + evl_put_element(&observable->element); + + return ret; +} + +/* observable->oob_wait.wchan.lock held, irqs off */ +static void decrease_writability(struct evl_observable *observable) +{ + observable->writable_observers--; + EVL_WARN_ON(CORE, observable->writable_observers < 0); +} + +/* observable->lock held, irqs off */ +static void detach_observer_locked(struct evl_observer *observer, + struct evl_observable *observable) /* irqs off */ +{ + list_del(&observer->next); + + raw_spin_lock(&observable->oob_wait.wchan.lock); + + if (!list_empty(&observer->free_list)) + decrease_writability(observable); + + raw_spin_unlock(&observable->oob_wait.wchan.lock); +} + +static inline void get_observer(struct evl_observer *observer) +{ + observer->refs++; +} + +static inline bool put_observer(struct evl_observer *observer) +{ + int new_refs = --observer->refs; + + EVL_WARN_ON(CORE, new_refs < 0); + + return new_refs == 0; +} + +static bool detach_observer(struct evl_observer *observer, + struct evl_observable *observable) +{ + bool dropped = false; + unsigned long flags; + + raw_spin_lock_irqsave(&observable->lock, flags); + + /* + * If the refcount does not drop to zero, push_notification() + * will flush the observer later on when it is safe. + */ + if (likely(put_observer(observer))) { + detach_observer_locked(observer, observable); + dropped = true; + } + + raw_spin_unlock_irqrestore(&observable->lock, flags); + + return dropped; +} + +static int cancel_subscription(struct evl_observable *observable) /* in-band */ +{ + struct evl_subscriber *sbr = evl_get_subscriber(); + struct evl_observer *observer; + unsigned long flags; + bool dropped; + + inband_context_only(); + + if (sbr == NULL) + return -ENOENT; + + evl_get_element(&observable->element); + + observer = find_observer(&sbr->subscriptions, + fundle_of(observable)); + if (observer == NULL) { + evl_put_element(&observable->element); + return -ENOENT; + } + + /* + * Remove observer from the subscription index. Once done, + * this observer escapes evl_drop_subscriptions() in case the + * caller exits afterwards. + */ + raw_spin_lock_irqsave(&sbr->lock, flags); + rb_erase(&observer->rb, &sbr->subscriptions); + raw_spin_unlock_irqrestore(&sbr->lock, flags); + + /* + * Remove observer from observable->observers. Subscription + * cannot be stale since observable is still around (meaning + * observable_release() did not run). + */ + dropped = detach_observer(observer, observable); + + evl_put_element(&observable->element); + + if (dropped) + kfree(observer); + + return 0; +} + +/* + * Current is wrapping up, drop the associated subscriber information + * if any, no need to lock subscriptions. + */ +void evl_drop_subscriptions(struct evl_subscriber *sbr) +{ + struct evl_observable *observable; + struct evl_observer *observer; + bool dropped = true; + struct rb_node *rb; + + if (sbr == NULL) + return; + + while ((rb = sbr->subscriptions.rb_node) != NULL) { + observer = rb_entry(rb, struct evl_observer, rb); + rb_erase(rb, &sbr->subscriptions); + /* Some subscriptions might be stale, check this. */ + if (likely(!list_empty(&observer->next))) { + observable = evl_get_factory_element_by_fundle( + &evl_observable_factory, + observer->fundle, + struct evl_observable); + if (!EVL_WARN_ON(CORE, observable == NULL)) { + dropped = detach_observer(observer, observable); + evl_put_element(&observable->element); + } else { + /* Something is going seriously wrong. */ + dropped = false; + } + } + if (dropped) + kfree(observer); + } + + kfree(sbr); +} + +static void inband_wake_r_irqwork(struct irq_work *work) +{ + struct evl_observable *observable; + + observable = container_of(work, struct evl_observable, wake_r_irqwork); + wake_up(&observable->inband_wait_r); + evl_put_element(&observable->element); +} + +static void inband_wake_w_irqwork(struct irq_work *work) +{ + struct evl_observable *observable; + + observable = container_of(work, struct evl_observable, wake_w_irqwork); + wake_up(&observable->inband_wait_w); + evl_put_element(&observable->element); +} + +void evl_flush_observable(struct evl_observable *observable) +{ + struct evl_observer *observer, *tmp; + unsigned long flags; + + /* + * We may be called from do_cleanup_current() in which case + * some events might still being pushed to the observable via + * the thread file descriptor, so locking is required. + */ + raw_spin_lock_irqsave(&observable->oob_wait.wchan.lock, flags); + + list_for_each_entry_safe(observer, tmp, &observable->observers, next) { + list_del_init(&observer->next); + if (!list_empty(&observer->free_list)) + decrease_writability(observable); + } + + if (evl_wait_active(&observable->oob_wait)) + evl_flush_wait_locked(&observable->oob_wait, 0); + + raw_spin_unlock_irqrestore(&observable->oob_wait.wchan.lock, flags); + + evl_schedule(); +} + +static int observable_release(struct inode *inode, struct file *filp) +{ + struct evl_observable *observable = element_of(filp, struct evl_observable); + + /* + * Unbind observers, then wake up so that oob waiters can + * figure out that we forced unsubscribed them. Those + * subscriptions are now stale. There is no point in + * attempting to wake up in-band waiters, there cannot be any + * since no regular read()/write() request could be ongoing on + * this file since the VFS wants us to release it. + */ + evl_flush_observable(observable); + + /* + * Wait for any ongoing oob request to have completed before + * allowing the VFS to fully dismantle filp. + */ + return evl_release_element(inode, filp); +} + +static void do_flush_work(struct evl_observable *observable) +{ + struct evl_observer *observer; + unsigned long flags; + + /* + * Flush the observers pending deletion. This should happen + * only rarely, in case push_notification() raced with + * cancel_subscription() or evl_drop_subscriptions(). + */ + raw_spin_lock_irqsave(&observable->lock, flags); + + while (!list_empty(&observable->flush_list)) { + observer = list_get_entry(&observable->flush_list, + struct evl_observer, next); + raw_spin_unlock_irqrestore(&observable->lock, flags); + kfree(observer); + raw_spin_lock_irqsave(&observable->lock, flags); + } + + raw_spin_unlock_irqrestore(&observable->lock, flags); +} + +static void inband_flush_irqwork(struct irq_work *work) +{ + struct evl_observable *observable; + + observable = container_of(work, struct evl_observable, flush_irqwork); + do_flush_work(observable); + evl_put_element(&observable->element); +} + +static bool notify_one_observer(struct evl_observable *observable, + struct evl_observer *observer, + const struct evl_notification_record *tmpl_nfr) +{ + struct evl_notification_record *nfr; + struct evl_notice last_notice; + unsigned long flags; + + raw_spin_lock_irqsave(&observable->oob_wait.wchan.lock, flags); + + if (observer->flags & EVL_NOTIFY_ONCHANGE) { + last_notice = observer->last_notice; + observer->last_notice.tag = tmpl_nfr->tag; + observer->last_notice.event = tmpl_nfr->event; + if (unlikely(observer->flags & EVL_NOTIFY_INITIAL)) + observer->flags &= ~EVL_NOTIFY_INITIAL; + else if (tmpl_nfr->tag == last_notice.tag && + tmpl_nfr->event.lval == last_notice.event.lval) + goto done; + } + + if (list_empty(&observer->free_list)) { + raw_spin_unlock_irqrestore(&observable->oob_wait.wchan.lock, flags); + return false; + } + + nfr = list_get_entry(&observer->free_list, + struct evl_notification_record, next); + + *nfr = *tmpl_nfr; + list_add_tail(&nfr->next, &observer->pending_list); + + if (list_empty(&observer->free_list)) + decrease_writability(observable); +done: + raw_spin_unlock_irqrestore(&observable->oob_wait.wchan.lock, flags); + + return true; +} + +static bool notify_single(struct evl_observable *observable, + struct evl_notification_record *nfr, + ssize_t *len_r) +{ + struct evl_observer *observer; + bool do_flush = false; + unsigned long flags; + + raw_spin_lock_irqsave(&observable->lock, flags); + + if (list_empty(&observable->observers)) + goto out; + + nfr->serial = observable->serial_counter++; + + observer = list_first_entry(&observable->observers, + struct evl_observer, next); + get_observer(observer); + + /* + * Use round-robin as a naive load-balancing strategy among + * multiple observers forming a pool of worker threads. + */ + if (!list_is_singular(&observable->observers)) { + list_del(&observer->next); + list_add_tail(&observer->next, &observable->observers); + } + + raw_spin_unlock_irqrestore(&observable->lock, flags); + + if (notify_one_observer(observable, observer, nfr)) + *len_r += sizeof(struct evl_notice); + + raw_spin_lock_irqsave(&observable->lock, flags); + + if (unlikely(put_observer(observer))) { + detach_observer_locked(observer, observable); + list_add(&observer->next, &observable->flush_list); + do_flush = true; + } +out: + raw_spin_unlock_irqrestore(&observable->lock, flags); + + return do_flush; +} + +static bool notify_all(struct evl_observable *observable, + struct evl_notification_record *nfr, + ssize_t *len_r) +{ + struct list_head *pos, *nextpos; + struct evl_observer *observer; + unsigned long flags; + bool do_flush; + + raw_spin_lock_irqsave(&observable->lock, flags); + + if (list_empty(&observable->observers)) { + do_flush = false; + goto out; + } + + nfr->serial = observable->serial_counter++; + + observer = list_first_entry(&observable->observers, + struct evl_observer, next); + get_observer(observer); + + /* + * Prevent cancel_subscription() and evl_drop_subscriptions() + * from dropping the observers we are about to push the + * notification to, without locking the observable all over + * the list walk. The trick is to hold a reference both on the + * current and next items during the traversal. Observers + * which might be added to the list concurrently by + * add_subscription() would not be picked during the + * traversal, which is still logically correct. + */ + list_for_each_safe(pos, nextpos, &observable->observers) { + + if (likely(nextpos != &observable->observers)) { + observer = list_entry(nextpos, struct evl_observer, next); + get_observer(observer); + } + + observer = list_entry(pos, struct evl_observer, next); + + raw_spin_unlock_irqrestore(&observable->lock, flags); + + if (notify_one_observer(observable, observer, nfr)) + *len_r += sizeof(struct evl_notice); + + raw_spin_lock_irqsave(&observable->lock, flags); + + if (unlikely(put_observer(observer))) { + detach_observer_locked(observer, observable); + list_add(&observer->next, &observable->flush_list); + } + } + + do_flush = !list_empty(&observable->flush_list); +out: + raw_spin_unlock_irqrestore(&observable->lock, flags); + + return do_flush; +} + +static bool is_pool_unicast(struct evl_observable *observable) +{ + return !!(observable->element.clone_flags & EVL_CLONE_UNICAST); +} + +static bool push_notification(struct evl_observable *observable, + const struct evl_notice *ntc, + ktime_t date) +{ + struct evl_notification_record nfr; + ssize_t len = 0; + bool do_flush; + + /* + * Prep a template notification record so that multiple + * observers receive exactly the same notification data for + * any single change, timestamp included. + */ + nfr.tag = ntc->tag; + nfr.event = ntc->event; + nfr.issuer = ntc->tag >= EVL_NOTICE_USER ? task_pid_nr(current) : 0; + nfr.date = date; + + /* + * Feed one observer/worker if unicast, or broadcast to all + * observers. + */ + if (is_pool_unicast(observable)) + do_flush = notify_single(observable, &nfr, &len); + else + do_flush = notify_all(observable, &nfr, &len); + + if (unlikely(do_flush)) { + if (running_inband()) { + do_flush_work(observable); + } else { + evl_get_element(&observable->element); + if (!irq_work_queue(&observable->flush_irqwork)) + evl_put_element(&observable->element); + } + } + + return len > 0; /* True if some subscribers could receive. */ +} + +static void wake_up_observers(struct evl_observable *observable) +{ + unsigned long flags; + + raw_spin_lock_irqsave(&observable->oob_wait.wchan.lock, flags); + + if (evl_wait_active(&observable->oob_wait)) + evl_flush_wait_locked(&observable->oob_wait, 0); + + raw_spin_unlock_irqrestore(&observable->oob_wait.wchan.lock, flags); + + evl_signal_poll_events(&observable->poll_head, POLLIN|POLLRDNORM); + evl_schedule(); + + smp_mb(); + if (waitqueue_active(&observable->inband_wait_r)) { + /* + * If running oob, we need to go through the + * wake_irqwork trampoline for waking up in-band + * waiters. + */ + if (running_inband()) { + wake_up(&observable->inband_wait_r); + } else { + evl_get_element(&observable->element); + if (!irq_work_queue(&observable->wake_r_irqwork)) + evl_put_element(&observable->element); + } + } +} + +bool evl_send_observable(struct evl_observable *observable, int tag, + union evl_value details) +{ + struct evl_notice ntc; + ktime_t now; + + ntc.tag = tag; + ntc.event = details; + now = evl_ktime_monotonic(); + + if (push_notification(observable, &ntc, now)) { + wake_up_observers(observable); + return true; + } + + return false; +} +EXPORT_SYMBOL_GPL(evl_send_observable); + +ssize_t evl_write_observable(struct evl_observable *observable, + const char __user *u_buf, size_t count) +{ + ssize_t len = 0, xlen = 0; + struct evl_notice ntc; + ktime_t now; + int ret = 0; + + if (!evl_element_is_observable(&observable->element)) + return -ENXIO; + + if (count == 0) + return 0; + + if (count % sizeof(struct evl_notice)) + return -EINVAL; /* No partial write. */ + + now = evl_ktime_monotonic(); + + while (xlen < count) { + if (raw_copy_from_user(&ntc, u_buf, sizeof(ntc))) { + ret = -EFAULT; + break; + } + + if (ntc.tag < EVL_NOTICE_USER) { + ret = -EINVAL; + break; + } + + if (push_notification(observable, &ntc, now)) + len += sizeof(ntc); + + xlen += sizeof(ntc); + u_buf += sizeof(ntc); + } + + /* If some notification was delivered, wake observers up. */ + if (len > 0) + wake_up_observers(observable); + + return ret ?: len; +} + +static struct evl_notification_record * +pull_from_oob(struct evl_observable *observable, + struct evl_observer *observer, + bool wait) +{ + struct evl_notification_record *nfr; + unsigned long flags; + int ret; + + raw_spin_lock_irqsave(&observable->oob_wait.wchan.lock, flags); + + /* + * observable->wait.lock guards the pending and free + * notification lists of all observers subscribed to it. + */ + for (;;) { + if (list_empty(&observer->next)) { + /* Unsubscribed by observable_release(). */ + nfr = ERR_PTR(-EBADF); + goto out; + } + if (!list_empty(&observer->pending_list)) + break; + if (!wait) { + nfr = ERR_PTR(-EWOULDBLOCK); + goto out; + } + evl_add_wait_queue(&observable->oob_wait, EVL_INFINITE, EVL_REL); + raw_spin_unlock_irqrestore(&observable->oob_wait.wchan.lock, flags); + ret = evl_wait_schedule(&observable->oob_wait); + if (ret) + return ERR_PTR(ret); + raw_spin_lock_irqsave(&observable->oob_wait.wchan.lock, flags); + } + + nfr = list_get_entry(&observer->pending_list, + struct evl_notification_record, next); +out: + raw_spin_unlock_irqrestore(&observable->oob_wait.wchan.lock, flags); + + return nfr; +} + +static struct evl_notification_record * +pull_from_inband(struct evl_observable *observable, + struct evl_observer *observer, + bool wait) +{ + struct evl_notification_record *nfr = NULL; + unsigned long ib_flags, oob_flags; + struct wait_queue_entry wq_entry; + int ret = 0; + + init_wait_entry(&wq_entry, 0); + + /* + * In-band lock first, oob next. See stax implementation for + * an explanation. + */ + spin_lock_irqsave(&observable->inband_wait_r.lock, ib_flags); + raw_spin_lock_irqsave(&observable->oob_wait.wchan.lock, oob_flags); + + for (;;) { + /* + * No need to check for observer->next linkage when + * handling read(): observable_release() did not run + * for the underlying file, obviously. + */ + if (list_empty(&wq_entry.entry)) + __add_wait_queue(&observable->inband_wait_r, &wq_entry); + + if (!list_empty(&observer->pending_list)) { + nfr = list_get_entry(&observer->pending_list, + struct evl_notification_record, next); + break; + } + if (!wait) { + ret = -EWOULDBLOCK; + break; + } + set_current_state(TASK_INTERRUPTIBLE); + raw_spin_unlock_irqrestore(&observable->oob_wait.wchan.lock, oob_flags); + spin_unlock_irqrestore(&observable->inband_wait_r.lock, ib_flags); + schedule(); + spin_lock_irqsave(&observable->inband_wait_r.lock, ib_flags); + raw_spin_lock_irqsave(&observable->oob_wait.wchan.lock, oob_flags); + + if (signal_pending(current)) { + ret = -ERESTARTSYS; + break; + } + } + + list_del(&wq_entry.entry); + + raw_spin_unlock_irqrestore(&observable->oob_wait.wchan.lock, oob_flags); + spin_unlock_irqrestore(&observable->inband_wait_r.lock, ib_flags); + + return ret ? ERR_PTR(ret) : nfr; +} + +static int pull_notification(struct evl_observable *observable, + struct evl_observer *observer, + char __user *u_buf, + bool wait) +{ + struct evl_notification_record *nfr; + struct __evl_notification nf; + bool sigpoll = false; + unsigned long flags; + int ret; + + if (running_inband()) + nfr = pull_from_inband(observable, observer, wait); + else + nfr = pull_from_oob(observable, observer, wait); + + if (IS_ERR(nfr)) + return PTR_ERR(nfr); + + nf.tag = nfr->tag; + nf.event = nfr->event; + nf.issuer = nfr->issuer; + nf.serial = nfr->serial; + nf.date = ktime_to_u_timespec(nfr->date); + + /* + * Do not risk losing notifications because of a broken + * userland; re-post them at front in case we fail copying the + * information back. A more recent record might have slipped + * in since we dropped the lock, but monotonic timestamps can + * still be used to sort out order of arrival. + */ + ret = raw_copy_to_user(u_buf, &nf, sizeof(nf)); + + raw_spin_lock_irqsave(&observable->oob_wait.wchan.lock, flags); + + if (ret) { + list_add(&nfr->next, &observer->pending_list); + ret = -EFAULT; + } else { + if (list_empty(&observer->free_list)) { + observable->writable_observers++; + sigpoll = true; + } + list_add(&nfr->next, &observer->free_list); + } + + raw_spin_unlock_irqrestore(&observable->oob_wait.wchan.lock, flags); + + if (unlikely(sigpoll)) { + evl_signal_poll_events(&observable->poll_head, + POLLOUT|POLLWRNORM); + evl_schedule(); + smp_mb(); + if (waitqueue_active(&observable->inband_wait_w)) { + if (running_inband()) { + wake_up(&observable->inband_wait_w); + } else { + evl_get_element(&observable->element); + if (!irq_work_queue(&observable->wake_w_irqwork)) + evl_put_element(&observable->element); + } + } + } + + return ret; +} + +ssize_t evl_read_observable(struct evl_observable *observable, + char __user *u_buf, size_t count, bool wait) +{ + struct evl_subscriber *sbr = evl_get_subscriber(); + struct evl_observer *observer; + ssize_t len = 0; + int ret = 0; + + /* + * The caller must have a valid subscription for reading an + * observable. + */ + if (sbr == NULL) + return -ENXIO; + + if (!evl_element_is_observable(&observable->element)) + return -ENXIO; + + /* + * Invariant: the caller owns observer (if found), nobody else + * may free it. This is _not_ true for push_notification() + * walking the list of observers which may belong to different + * threads. + */ + observer = find_observer(&sbr->subscriptions, fundle_of(observable)); + if (observer == NULL) + return -ENXIO; /* Not subscribed. */ + + if (count == 0) + return 0; + + if (count % sizeof(struct __evl_notification)) + return -EINVAL; /* No partial read. */ + /* + * Return as many available notifications we can, waiting for + * the first one if necessary. + */ + while (len < count) { + ret = pull_notification(observable, observer, u_buf, wait); + if (ret) + break; + wait = false; + u_buf += sizeof(struct __evl_notification); + len += sizeof(struct __evl_notification); + } + + return len ?: ret; +} + +static __poll_t poll_observable(struct evl_observable *observable) +{ + struct evl_subscriber *sbr = evl_get_subscriber(); + struct evl_observer *observer; + unsigned long flags; + __poll_t ret = 0; + + if (sbr == NULL) + return POLLERR; + + observer = find_observer(&sbr->subscriptions, fundle_of(observable)); + if (observer == NULL) + return POLLERR; + + raw_spin_lock_irqsave(&observable->oob_wait.wchan.lock, flags); + + /* Only subscribers can inquire about readability. */ + if (observer && !list_empty(&observer->pending_list)) + ret = POLLIN|POLLRDNORM; + + if (observable->writable_observers > 0) + ret |= POLLOUT|POLLWRNORM; + + raw_spin_unlock_irqrestore(&observable->oob_wait.wchan.lock, flags); + + return ret; +} + +__poll_t evl_oob_poll_observable(struct evl_observable *observable, + struct oob_poll_wait *wait) +{ + evl_poll_watch(&observable->poll_head, wait, NULL); + + return poll_observable(observable); +} + +__poll_t evl_poll_observable(struct evl_observable *observable, + struct file *filp, poll_table *pt) +{ + poll_wait(filp, &observable->inband_wait_r, pt); + poll_wait(filp, &observable->inband_wait_w, pt); + + return poll_observable(observable); +} + +long evl_ioctl_observable(struct evl_observable *observable, unsigned int cmd, + unsigned long arg) +{ + struct evl_subscription sub, *u_sub; + int ret; + + switch (cmd) { + case EVL_OBSIOC_SUBSCRIBE: + /* + * Add a subscription to @observable for the current + * thread, which may not be attached. + */ + u_sub = (typeof(u_sub))arg; + ret = raw_copy_from_user(&sub, u_sub, sizeof(sub)); + if (ret) + return -EFAULT; + ret = add_subscription(observable, + sub.backlog_count, sub.flags); + break; + case EVL_OBSIOC_UNSUBSCRIBE: + /* Likewise for unsubscribing from @observable. */ + ret = cancel_subscription(observable); + break; + default: + ret = -ENOTTY; + } + + evl_schedule(); + + return ret; +} + +static ssize_t observable_oob_write(struct file *filp, + const char __user *u_buf, size_t count) +{ + struct evl_observable *observable = element_of(filp, struct evl_observable); + + return evl_write_observable(observable, u_buf, count); +} + +static ssize_t observable_oob_read(struct file *filp, + char __user *u_buf, size_t count) +{ + struct evl_observable *observable = element_of(filp, struct evl_observable); + + return evl_read_observable(observable, u_buf, count, + !(filp->f_flags & O_NONBLOCK)); +} + +static __poll_t observable_oob_poll(struct file *filp, + struct oob_poll_wait *wait) +{ + struct evl_observable *observable = element_of(filp, struct evl_observable); + + return evl_oob_poll_observable(observable, wait); +} + +static ssize_t observable_write(struct file *filp, const char __user *u_buf, + size_t count, loff_t *ppos) +{ + struct evl_observable *observable = element_of(filp, struct evl_observable); + + return evl_write_observable(observable, u_buf, count); +} + +static ssize_t observable_read(struct file *filp, char __user *u_buf, + size_t count, loff_t *ppos) +{ + struct evl_observable *observable = element_of(filp, struct evl_observable); + + return evl_read_observable(observable, u_buf, count, + !(filp->f_flags & O_NONBLOCK)); +} + +static __poll_t observable_poll(struct file *filp, poll_table *pt) +{ + struct evl_observable *observable = element_of(filp, struct evl_observable); + + return evl_poll_observable(observable, filp, pt); +} + +static long observable_ioctl(struct file *filp, unsigned int cmd, + unsigned long arg) +{ + struct evl_observable *observable = element_of(filp, struct evl_observable); + + return evl_ioctl_observable(observable, cmd, arg); +} + +static const struct file_operations observable_fops = { + .open = evl_open_element, + .release = observable_release, + .oob_write = observable_oob_write, + .oob_read = observable_oob_read, + .oob_poll = observable_oob_poll, + .write = observable_write, + .read = observable_read, + .poll = observable_poll, + .unlocked_ioctl = observable_ioctl, +#ifdef CONFIG_COMPAT + .compat_ioctl = compat_ptr_ioctl, +#endif +}; + +struct evl_observable *evl_alloc_observable(const char __user *u_name, + int clone_flags) +{ + struct evl_observable *observable; + int ret; + + observable = kzalloc(sizeof(*observable), GFP_KERNEL); + if (observable == NULL) + return ERR_PTR(-ENOMEM); + + ret = evl_init_user_element(&observable->element, + &evl_observable_factory, u_name, + clone_flags | EVL_CLONE_OBSERVABLE); + if (ret) { + kfree(observable); + return ERR_PTR(ret); + } + + INIT_LIST_HEAD(&observable->observers); + INIT_LIST_HEAD(&observable->flush_list); + evl_init_wait(&observable->oob_wait, &evl_mono_clock, EVL_WAIT_PRIO); + init_waitqueue_head(&observable->inband_wait_r); + init_waitqueue_head(&observable->inband_wait_w); + init_irq_work(&observable->wake_r_irqwork, inband_wake_r_irqwork); + init_irq_work(&observable->wake_w_irqwork, inband_wake_w_irqwork); + init_irq_work(&observable->flush_irqwork, inband_flush_irqwork); + evl_init_poll_head(&observable->poll_head); + raw_spin_lock_init(&observable->lock); + evl_index_factory_element(&observable->element); + + return observable; +} + +static struct evl_element * +observable_factory_build(struct evl_factory *fac, const char __user *u_name, + void __user *u_attrs, int clone_flags, u32 *state_offp) +{ + struct evl_observable *observable; + + if (clone_flags & ~EVL_OBSERVABLE_CLONE_FLAGS) + return ERR_PTR(-EINVAL); + + observable = evl_alloc_observable(u_name, clone_flags); + if (IS_ERR(observable)) + return ERR_PTR(PTR_ERR(observable)); + + return &observable->element; +} + +static void observable_factory_dispose(struct evl_element *e) +{ + struct evl_observable *observable; + + observable = container_of(e, struct evl_observable, element); + evl_destroy_wait(&observable->oob_wait); + evl_unindex_factory_element(&observable->element); + evl_destroy_element(&observable->element); + kfree_rcu(observable, element.rcu); +} + +struct evl_factory evl_observable_factory = { + .name = EVL_OBSERVABLE_DEV, + .fops = &observable_fops, + .build = observable_factory_build, + .dispose = observable_factory_dispose, + /* Threads are observables in essence. */ + .nrdev = CONFIG_EVL_NR_OBSERVABLES + CONFIG_EVL_NR_THREADS, + .flags = EVL_FACTORY_CLONE, +}; diff --git a/kernel/evl/poll.c b/kernel/evl/poll.c new file mode 100644 index 000000000..b7c4d0caa --- /dev/null +++ b/kernel/evl/poll.c @@ -0,0 +1,734 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2018 Philippe Gerum + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct poll_group { + struct rb_root item_index; /* struct poll_item */ + struct list_head item_list; /* struct poll_item */ + struct list_head waiter_list; /* struct poll_waiter */ + hard_spinlock_t wait_lock; + struct evl_file efile; + struct evl_kmutex item_lock; + int nr_items; + unsigned int generation; +}; + +struct poll_item { + unsigned int fd; + int events_polled; + union evl_value pollval; + struct rb_node rb; /* in group->item_index */ + struct list_head next; /* in group->item_list */ +}; + +struct poll_waiter { + struct evl_flag flag; + struct list_head next; +}; + +/* Maximum nesting depth (poll group watching other group(s)) */ +#define POLLER_NEST_MAX 4 + +static const struct file_operations poll_fops; + +#define for_each_poll_connector(__poco, __wpt) \ + for (__poco = (__wpt)->wait.connectors; \ + __poco < (__wpt)->wait.connectors + EVL_POLL_NR_CONNECTORS; \ + __poco++) \ + if ((__poco)->head) + +/* head->lock held, irqs off */ +static void connect_watchpoint(struct oob_poll_wait *wait, + struct evl_poll_head *head, + void (*unwatch)(struct evl_poll_head *head)) +{ + struct evl_poll_connector *poco; + int i; + + for (i = 0; i < EVL_POLL_NR_CONNECTORS; i++) { + poco = wait->connectors + i; + if (poco->head == NULL) { + poco->head = head; + poco->unwatch = unwatch; + poco->events_received = 0; + list_add(&poco->next, &head->watchpoints); + poco->index = i; + return; + } + /* Duplicate connection to a poll head - fix driver. */ + if (EVL_WARN_ON(CORE, poco->head == head)) + return; + } + + /* All connectors are busy - fix driver. */ + EVL_WARN_ON(CORE, 1); +} + +void evl_poll_watch(struct evl_poll_head *head, + struct oob_poll_wait *wait, + void (*unwatch)(struct evl_poll_head *head)) +{ + struct evl_poll_watchpoint *wpt; + unsigned long flags; + + wpt = container_of(wait, struct evl_poll_watchpoint, wait); + /* Connect to a driver's poll head. */ + raw_spin_lock_irqsave(&head->lock, flags); + connect_watchpoint(wait, head, unwatch); + raw_spin_unlock_irqrestore(&head->lock, flags); +} +EXPORT_SYMBOL_GPL(evl_poll_watch); + +/* + * __evl_signal_poll_events - wake up threads polling for events. + * + * @head poll head waiters sleep on + * @events incoming events to signal + * + * A single waiter is unblocked for any distinct event signaled on + * entry. + */ +void __evl_signal_poll_events(struct evl_poll_head *head, + int events) +{ + struct evl_poll_watchpoint *wpt; + struct evl_poll_connector *poco; + unsigned long flags; + int ready; + + raw_spin_lock_irqsave(&head->lock, flags); + + list_for_each_entry(poco, &head->watchpoints, next) { + wpt = container_of(poco, struct evl_poll_watchpoint, + wait.connectors[poco->index]); + ready = events & wpt->events_polled; + if (ready) { + poco->events_received |= ready; + evl_raise_flag_nosched(wpt->flag); + events &= ~ready; + if (!events) + break; + } + } + + raw_spin_unlock_irqrestore(&head->lock, flags); +} +EXPORT_SYMBOL_GPL(__evl_signal_poll_events); + +void evl_drop_poll_table(struct evl_thread *curr) +{ + struct evl_poll_watchpoint *table; + + table = curr->poll_context.table; + if (table) + evl_free(table); +} + +static inline +int index_item(struct rb_root *root, struct poll_item *item) +{ + struct rb_node **rbp, *parent = NULL; + struct poll_item *tmp; + + rbp = &root->rb_node; + while (*rbp) { + tmp = rb_entry(*rbp, struct poll_item, rb); + parent = *rbp; + if (item->fd < tmp->fd) + rbp = &(*rbp)->rb_left; + else if (item->fd > tmp->fd) + rbp = &(*rbp)->rb_right; + else + return -EEXIST; + } + + rb_link_node(&item->rb, parent, rbp); + rb_insert_color(&item->rb, root); + + return 0; +} + +static inline void new_generation(struct poll_group *group) +{ + if (++group->generation == 0) /* Keep zero for init state. */ + group->generation = 1; +} + +static int check_no_loop_deeper(struct poll_group *origin, + struct poll_item *item, + int depth) +{ + struct poll_group *group; + struct poll_item *_item; + struct evl_file *efilp; + struct file *filp; + int ret = 0; + + if (depth >= POLLER_NEST_MAX) + return -ELOOP; + + efilp = evl_get_file(item->fd); + if (efilp == NULL) + return 0; + + filp = efilp->filp; + if (filp->f_op != &poll_fops) + goto out; + + group = filp->private_data; + if (group == origin) { + ret = -ELOOP; + goto out; + } + + evl_lock_kmutex(&group->item_lock); + + list_for_each_entry(_item, &group->item_list, next) { + ret = check_no_loop_deeper(origin, _item, depth + 1); + if (ret) + break; + } + + evl_unlock_kmutex(&group->item_lock); +out: + evl_put_file(efilp); + + return ret; +} + +static int check_no_loop(struct poll_group *group, + struct poll_item *item) +{ + return check_no_loop_deeper(group, item, 0); +} + +static int add_item(struct file *filp, struct poll_group *group, + struct evl_poll_ctlreq *creq) +{ + struct poll_item *item; + struct evl_file *efilp; + int ret, events; + + item = evl_alloc(sizeof(*item)); + if (item == NULL) + return -ENOMEM; + + item->fd = creq->fd; + events = creq->events & ~POLLNVAL; + item->events_polled = events | POLLERR | POLLHUP; + item->pollval = creq->pollval; + + efilp = evl_get_file(creq->fd); + if (efilp == NULL) { + ret = -EBADF; + goto fail_get; + } + + evl_lock_kmutex(&group->item_lock); + + /* Check for cyclic deps. */ + ret = check_no_loop(group, item); + if (ret) + goto fail_add; + + ret = index_item(&group->item_index, item); + if (ret) + goto fail_add; + + list_add(&item->next, &group->item_list); + group->nr_items++; + new_generation(group); + + evl_unlock_kmutex(&group->item_lock); + evl_put_file(efilp); + + return 0; + +fail_add: + evl_unlock_kmutex(&group->item_lock); + evl_put_file(efilp); +fail_get: + evl_free(item); + + return ret; +} + +static struct poll_item * +lookup_item(struct rb_root *root, unsigned int fd) +{ + struct poll_item *item; + struct rb_node *rb; + + rb = root->rb_node; + while (rb) { + item = rb_entry(rb, struct poll_item, rb); + if (fd < item->fd) + rb = rb->rb_left; + else if (fd > item->fd) + rb = rb->rb_right; + else + return item; + } + + return NULL; +} + +static int del_item(struct poll_group *group, + struct evl_poll_ctlreq *creq) +{ + struct poll_item *item; + + evl_lock_kmutex(&group->item_lock); + + item = lookup_item(&group->item_index, creq->fd); + if (item == NULL) { + evl_unlock_kmutex(&group->item_lock); + return -ENOENT; + } + + rb_erase(&item->rb, &group->item_index); + list_del(&item->next); + group->nr_items--; + new_generation(group); + + evl_unlock_kmutex(&group->item_lock); + + evl_free(item); + + return 0; +} + +/* fdt_lock held, irqs off. */ +void evl_drop_watchpoints(struct list_head *drop_list) +{ + struct evl_poll_watchpoint *wpt; + struct evl_poll_connector *poco; + struct evl_poll_node *node; + + /* + * Drop the watchpoints attached to a file descriptor which is + * being closed. Watchpoints found in @drop_list were + * registered via a call to evl_watch_fd() from wait_events() + * but not unregistered by calling evl_ignore_fd() from + * clear_wait() yet, so they are still valid. wpt->filp is + * valid as well, although it may become stale later on if the + * last fd referencing it is being closed. + * + * NOTE: poco->next is kept untouched, only the thread which + * is sleeping on a watchpoint is allowed to alter such + * information for any of the related connectors. + */ + list_for_each_entry(node, drop_list, next) { + wpt = container_of(node, struct evl_poll_watchpoint, node); + for_each_poll_connector(poco, wpt) { + raw_spin_lock(&poco->head->lock); + poco->events_received |= POLLNVAL; + if (poco->unwatch) /* handler must NOT reschedule. */ + poco->unwatch(poco->head); + raw_spin_unlock(&poco->head->lock); + } + evl_raise_flag_nosched(wpt->flag); + wpt->filp = NULL; + } +} + +static inline +int mod_item(struct poll_group *group, + struct evl_poll_ctlreq *creq) +{ + struct poll_item *item; + int events; + + events = creq->events & ~POLLNVAL; + + evl_lock_kmutex(&group->item_lock); + + item = lookup_item(&group->item_index, creq->fd); + if (item == NULL) { + evl_unlock_kmutex(&group->item_lock); + return -ENOENT; + } + + item->events_polled = events | POLLERR | POLLHUP; + item->pollval = creq->pollval; + new_generation(group); + + evl_unlock_kmutex(&group->item_lock); + + return 0; +} + +static inline +int setup_item(struct file *filp, struct poll_group *group, + struct evl_poll_ctlreq *creq) +{ + int ret; + + switch (creq->action) { + case EVL_POLL_CTLADD: + ret = add_item(filp, group, creq); + break; + case EVL_POLL_CTLDEL: + ret = del_item(group, creq); + break; + case EVL_POLL_CTLMOD: + ret = mod_item(group, creq); + break; + default: + ret = -EINVAL; + } + + return ret; +} + +static int collect_events(struct poll_group *group, + struct evl_poll_event __user *u_set, + int maxevents, struct evl_flag *flag) +{ + struct evl_thread *curr = evl_current(); + struct evl_poll_watchpoint *wpt, *table; + int ret, n, nr, count = 0, ready; + struct evl_poll_connector *poco; + struct evl_poll_event ev; + unsigned int generation; + struct poll_item *item; + struct evl_file *efilp; + struct file *filp; + + evl_lock_kmutex(&group->item_lock); + + nr = group->nr_items; + if (nr == 0) { + evl_unlock_kmutex(&group->item_lock); + return -EINVAL; + } + + /* + * Check whether the registered items are in sync with the + * caller's registered watchpoints (if any). Go polling + * directly using those watchpoints if so, otherwise resync. + */ + table = curr->poll_context.table; + if (flag == NULL) + goto collect; + + generation = group->generation; + if (likely(generation == curr->poll_context.generation)) + goto collect; + + /* Need to resync. */ + do { + generation = group->generation; + evl_unlock_kmutex(&group->item_lock); + evl_drop_poll_table(curr); + table = evl_alloc(sizeof(*wpt) * nr); + if (table == NULL) { + curr->poll_context.nr = 0; + curr->poll_context.active = 0; + curr->poll_context.table = NULL; + curr->poll_context.generation = 0; + return -ENOMEM; + } + evl_lock_kmutex(&group->item_lock); + } while (generation != group->generation); + + curr->poll_context.table = table; + curr->poll_context.nr = nr; + curr->poll_context.generation = generation; + + /* Build the poll table. */ + wpt = table; + list_for_each_entry(item, &group->item_list, next) { + wpt->fd = item->fd; + wpt->events_polled = item->events_polled; + wpt->pollval = item->pollval; + wpt++; + } + +collect: + evl_unlock_kmutex(&group->item_lock); + + if (flag) + curr->poll_context.active = 0; + + for (n = 0, wpt = table; n < nr; n++, wpt++) { + if (flag) { + wpt->flag = flag; + for_each_poll_connector(poco, wpt) { + poco->head = NULL; + INIT_LIST_HEAD(&poco->next); + } + /* If oob_poll() is absent, default to all events ready. */ + ready = POLLIN|POLLOUT|POLLRDNORM|POLLWRNORM; + efilp = evl_watch_fd(wpt->fd, &wpt->node); + if (efilp == NULL) + goto stale; + curr->poll_context.active++; + filp = efilp->filp; + wpt->filp = filp; + if (filp->f_op->oob_poll) + ready = filp->f_op->oob_poll(filp, &wpt->wait); + evl_put_file(efilp); + } else { + ready = 0; + for_each_poll_connector(poco, wpt) + ready |= poco->events_received; + } + + ready &= wpt->events_polled | POLLNVAL; + if (ready) { + ev.fd = wpt->fd; + ev.pollval = wpt->pollval; + ev.events = ready; + ret = raw_copy_to_user(u_set, &ev, sizeof(ev)); + if (ret) { + count = -EFAULT; + break; + } + u_set++; + if (++count >= maxevents) { + count = maxevents; + break; + } + } + } + + return count; +stale: + /* + * We have a stale fd in the table, force regeneration next + * time we collect events then bail out on error. + */ + evl_lock_kmutex(&group->item_lock); + new_generation(group); + evl_unlock_kmutex(&group->item_lock); + + return -EBADF; +} + +static inline void clear_wait(void) +{ + struct evl_thread *curr = evl_current(); + struct evl_poll_watchpoint *wpt; + struct evl_poll_connector *poco; + unsigned long flags; + int n; + + /* + * Current stopped waiting for events, remove the watchpoints + * we have been monitoring so far from their poll heads. + * wpt->head->lock serializes with __evl_signal_poll_events(). + * Any watchpoint which does not bear the POLLNVAL bit is + * monitoring a valid file by construction. + * + * A watchpoint might no be attached to any poll head in case + * oob_poll() is undefined for the device, or the related fd + * is stale. Since only the caller may update the linkage of + * its watchpoints, using list_empty() locklessly is safe + * here. + */ + for (n = 0, wpt = curr->poll_context.table; + n < curr->poll_context.active; n++, wpt++) { + evl_ignore_fd(&wpt->node); + /* Remove from driver's poll head(s). */ + for_each_poll_connector(poco, wpt) { + raw_spin_lock_irqsave(&poco->head->lock, flags); + list_del(&poco->next); + if (!(poco->events_received & POLLNVAL) && poco->unwatch) + poco->unwatch(poco->head); + raw_spin_unlock_irqrestore(&poco->head->lock, flags); + } + } +} + +static inline +int wait_events(struct file *filp, + struct poll_group *group, + struct evl_poll_waitreq *wreq, + struct timespec64 *ts64) +{ + struct evl_poll_event __user *u_set; + struct poll_waiter waiter; + enum evl_tmode tmode; + unsigned long flags; + ktime_t timeout; + int ret, count; + + if (wreq->nrset < 0) + return -EINVAL; + + if (wreq->nrset == 0) + return 0; + + u_set = evl_valptr64(wreq->pollset_ptr, struct evl_poll_event); + evl_init_flag_on_stack(&waiter.flag); + + count = collect_events(group, u_set, wreq->nrset, &waiter.flag); + if (count > 0 || (count == -EFAULT || count == -EBADF)) + goto unwait; + if (count < 0) + goto out; + + if (filp->f_flags & O_NONBLOCK) { + count = -EAGAIN; + goto unwait; + } + + timeout = timespec64_to_ktime(*ts64); + tmode = timeout ? EVL_ABS : EVL_REL; + + raw_spin_lock_irqsave(&group->wait_lock, flags); + list_add(&waiter.next, &group->waiter_list); + raw_spin_unlock_irqrestore(&group->wait_lock, flags); + ret = evl_wait_flag_timeout(&waiter.flag, timeout, tmode); + raw_spin_lock_irqsave(&group->wait_lock, flags); + list_del(&waiter.next); + raw_spin_unlock_irqrestore(&group->wait_lock, flags); + + count = ret; + if (count == 0) /* Re-collect events after successful wait. */ + count = collect_events(group, u_set, wreq->nrset, NULL); +unwait: + clear_wait(); +out: + evl_destroy_flag(&waiter.flag); + + return count; +} + +static int poll_open(struct inode *inode, struct file *filp) +{ + struct poll_group *group; + int ret; + + group = kzalloc(sizeof(*group), GFP_KERNEL); + if (group == NULL) + return -ENOMEM; + + ret = evl_open_file(&group->efile, filp); + if (ret) { + kfree(group); + return ret; + } + + group->item_index = RB_ROOT; + INIT_LIST_HEAD(&group->item_list); + INIT_LIST_HEAD(&group->waiter_list); + evl_init_kmutex(&group->item_lock); + raw_spin_lock_init(&group->wait_lock); + might_hard_lock(&group->wait_lock); /* see __evl_init_wait(). */ + filp->private_data = group; + stream_open(inode, filp); + + return ret; +} + +static inline void flush_items(struct poll_group *group) +{ + struct poll_item *item, *n; + + list_for_each_entry_safe(item, n, &group->item_list, next) + evl_free(item); +} + +static int poll_release(struct inode *inode, struct file *filp) +{ + struct poll_group *group = filp->private_data; + struct poll_waiter *waiter; + unsigned long flags; + + raw_spin_lock_irqsave(&group->wait_lock, flags); + list_for_each_entry(waiter, &group->waiter_list, next) + evl_flush_flag_nosched(&waiter->flag, EVL_T_RMID); + raw_spin_unlock_irqrestore(&group->wait_lock, flags); + evl_schedule(); + + flush_items(group); + evl_destroy_kmutex(&group->item_lock); + evl_release_file(&group->efile); + kfree(group); + + return 0; +} + +static long poll_oob_ioctl(struct file *filp, unsigned int cmd, + unsigned long arg) +{ + struct poll_group *group = filp->private_data; + struct evl_poll_waitreq wreq, __user *u_wreq; + struct evl_poll_ctlreq creq, __user *u_creq; + struct __evl_timespec __user *u_uts; + struct __evl_timespec uts = { + .tv_sec = 0, + .tv_nsec = 0, + }; + struct timespec64 ts64; + int ret; + + switch (cmd) { + case EVL_POLIOC_CTL: + u_creq = (typeof(u_creq))arg; + ret = raw_copy_from_user(&creq, u_creq, sizeof(creq)); + if (ret) + return -EFAULT; + ret = setup_item(filp, group, &creq); + break; + case EVL_POLIOC_WAIT: + u_wreq = (typeof(u_wreq))arg; + ret = raw_copy_from_user(&wreq, u_wreq, sizeof(wreq)); + if (ret) + return -EFAULT; + u_uts = evl_valptr64(wreq.timeout_ptr, struct __evl_timespec); + ret = raw_copy_from_user(&uts, u_uts, sizeof(uts)); + if (ret) + return -EFAULT; + if ((unsigned long)uts.tv_nsec >= ONE_BILLION) + return -EINVAL; + ts64 = u_timespec_to_timespec64(uts); + ret = wait_events(filp, group, &wreq, &ts64); + if (ret < 0) + return ret; + if (raw_put_user(ret, &u_wreq->nrset)) + return -EFAULT; + ret = 0; + break; + default: + ret = -ENOTTY; + } + + return ret; +} + +static const struct file_operations poll_fops = { + .open = poll_open, + .release = poll_release, + .oob_ioctl = poll_oob_ioctl, +#ifdef CONFIG_COMPAT + .compat_oob_ioctl = compat_ptr_oob_ioctl, +#endif +}; + +struct evl_factory evl_poll_factory = { + .name = EVL_POLL_DEV, + .fops = &poll_fops, + .flags = EVL_FACTORY_SINGLE, +}; diff --git a/kernel/evl/proxy.c b/kernel/evl/proxy.c new file mode 100644 index 000000000..bc30a840f --- /dev/null +++ b/kernel/evl/proxy.c @@ -0,0 +1,789 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2019 Philippe Gerum + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define EVL_PROXY_CLONE_FLAGS \ + (EVL_CLONE_PUBLIC|EVL_CLONE_OUTPUT|EVL_CLONE_INPUT) + +struct proxy_ring { + void *bufmem; + atomic_t fillsz; + int nesting; + unsigned int bufsz; + unsigned int rdoff; + unsigned int wroff; + unsigned int reserved; + unsigned int granularity; + struct evl_flag oob_wait; + wait_queue_head_t inband_wait_r; + wait_queue_head_t inband_wait_w; + struct evl_work relay_work; + hard_spinlock_t lock; + struct workqueue_struct *wq; + struct mutex worker_lock; +}; + +struct proxy_out { /* oob_write->write */ + struct proxy_ring ring; +}; + +struct proxy_in { /* read->oob_read */ + struct proxy_ring ring; + atomic_t reqsz; + atomic_t on_eof; + int on_error; +}; + +struct evl_proxy { + struct file *filp; + struct proxy_out output; + struct proxy_in input; + struct evl_element element; + struct evl_poll_head poll_head; +}; + +static inline bool proxy_may_read(struct evl_proxy *proxy) +{ + return !!(proxy->element.clone_flags & EVL_CLONE_INPUT); +} + +static inline bool proxy_may_write(struct evl_proxy *proxy) +{ + return !!(proxy->element.clone_flags & EVL_CLONE_OUTPUT); +} + +static void relay_output(struct evl_proxy *proxy) +{ + struct proxy_ring *ring = &proxy->output.ring; + unsigned int rdoff, count, len, n; + struct file *filp = proxy->filp; + loff_t pos, *ppos; + ssize_t ret = 0; + + mutex_lock(&ring->worker_lock); + + count = atomic_read(&ring->fillsz); + rdoff = ring->rdoff; + + ppos = NULL; + if (filp->f_mode & FMODE_ATOMIC_POS) { + mutex_lock(&filp->f_pos_lock); + ppos = &pos; + pos = filp->f_pos; + } + + while (count > 0 && ret >= 0) { + len = count; + do { + if (rdoff + len > ring->bufsz) + n = ring->bufsz - rdoff; + else + n = len; + + if (ring->granularity > 0) + n = min(n, ring->granularity); + + ret = kernel_write(filp, ring->bufmem + rdoff, n, ppos); + if (ret >= 0 && ppos) + filp->f_pos = *ppos; + len -= n; + rdoff = (rdoff + n) % ring->bufsz; + } while (len > 0 && ret > 0); + /* + * On error, the portion we failed writing is + * lost. Fair enough. + */ + count = atomic_sub_return(count, &ring->fillsz); + } + + if (ppos) + mutex_unlock(&filp->f_pos_lock); + + ring->rdoff = rdoff; + + mutex_unlock(&ring->worker_lock); + + /* + * For proxies, writability means that all pending data was + * sent out without error. + */ + if (count == 0) + evl_signal_poll_events(&proxy->poll_head, POLLOUT|POLLWRNORM); + + /* + * Since we are running in-band, make sure to give precedence + * to oob waiters for wakeups. + */ + if (count < ring->bufsz) { + evl_raise_flag(&ring->oob_wait); /* Reschedules. */ + wake_up(&ring->inband_wait_w); + } else { + evl_schedule(); /* Covers evl_signal_poll_events() */ + } +} + +static void relay_output_work(struct evl_work *work) +{ + struct evl_proxy *proxy = + container_of(work, struct evl_proxy, output.ring.relay_work); + + relay_output(proxy); +} + +static bool can_write_buffer(struct proxy_ring *ring, size_t size) +{ + return atomic_read(&ring->fillsz) + + ring->reserved + size <= ring->bufsz; +} + +static ssize_t do_proxy_write(struct file *filp, + const char __user *u_buf, size_t count) +{ + struct evl_proxy *proxy = element_of(filp, struct evl_proxy); + struct proxy_ring *ring = &proxy->output.ring; + unsigned int wroff, wbytes, n, rsvd; + unsigned long flags; + ssize_t ret; + int xret; + + if (count == 0) + return 0; + + if (count > ring->bufsz) + return -EFBIG; + + if (ring->granularity > 1 && count % ring->granularity > 0) + return -EINVAL; + + raw_spin_lock_irqsave(&ring->lock, flags); + + /* No short or scattered writes. */ + if (!can_write_buffer(ring, count)) { + ret = -EAGAIN; + goto out; + } + + /* Reserve a write slot into the circular buffer. */ + wroff = ring->wroff; + ring->wroff = (wroff + count) % ring->bufsz; + ring->nesting++; + ring->reserved += count; + wbytes = ret = count; + + do { + if (wroff + wbytes > ring->bufsz) + n = ring->bufsz - wroff; + else + n = wbytes; + + raw_spin_unlock_irqrestore(&ring->lock, flags); + xret = raw_copy_from_user(ring->bufmem + wroff, u_buf, n); + raw_spin_lock_irqsave(&ring->lock, flags); + if (xret) { + memset(ring->bufmem + wroff + n - xret, 0, xret); + ret = -EFAULT; + break; + } + + u_buf += n; + wbytes -= n; + wroff = (wroff + n) % ring->bufsz; + } while (wbytes > 0); + + if (--ring->nesting == 0) { + n = atomic_add_return(ring->reserved, &ring->fillsz); + rsvd = ring->reserved; + ring->reserved = 0; + if (n == rsvd) { /* empty -> non-empty transition */ + if (running_inband()) { + raw_spin_unlock_irqrestore(&ring->lock, flags); + relay_output(proxy); + return ret; + } + evl_call_inband_from(&ring->relay_work, ring->wq); + } + } +out: + raw_spin_unlock_irqrestore(&ring->lock, flags); + + return ret; +} + +static void relay_input(struct evl_proxy *proxy) +{ + struct proxy_in *in = &proxy->input; + struct proxy_ring *ring = &in->ring; + unsigned int wroff, count, len, n; + struct file *filp = proxy->filp; + bool exception = false; + loff_t pos, *ppos; + ssize_t ret = 0; + + mutex_lock(&ring->worker_lock); + + count = atomic_read(&in->reqsz); + wroff = ring->wroff; + + ppos = NULL; + if (filp->f_mode & FMODE_ATOMIC_POS) { + mutex_lock(&filp->f_pos_lock); + ppos = &pos; + pos = filp->f_pos; + } + + while (count > 0) { + len = count; + do { + if (wroff + len > ring->bufsz) + n = ring->bufsz - wroff; + else + n = len; + + if (ring->granularity > 0) + n = min(n, ring->granularity); + + ret = kernel_read(filp, ring->bufmem + wroff, n, ppos); + if (ret <= 0) { + atomic_sub(count - len, &in->reqsz); + if (ret) + in->on_error = ret; + else + atomic_set(&in->on_eof, true); + exception = true; + goto done; + } + + if (ppos) + filp->f_pos = *ppos; + + atomic_add(ret, &ring->fillsz); + len -= ret; + wroff = (wroff + n) % ring->bufsz; + } while (len > 0); + count = atomic_sub_return(count, &in->reqsz); + } +done: + if (ppos) + mutex_unlock(&filp->f_pos_lock); + + ring->wroff = wroff; + + mutex_unlock(&ring->worker_lock); + + if (atomic_read(&ring->fillsz) > 0 || exception) { + evl_signal_poll_events(&proxy->poll_head, POLLIN|POLLRDNORM); + evl_raise_flag(&ring->oob_wait); /* Reschedules. */ + wake_up(&ring->inband_wait_r); + } +} + +static void relay_input_work(struct evl_work *work) +{ + struct evl_proxy *proxy = + container_of(work, struct evl_proxy, input.ring.relay_work); + + relay_input(proxy); +} + +static ssize_t do_proxy_read(struct file *filp, + char __user *u_buf, size_t count) +{ + struct evl_proxy *proxy = element_of(filp, struct evl_proxy); + struct proxy_in *in = &proxy->input; + struct proxy_ring *ring = &in->ring; + ssize_t len, ret, rbytes, n; + unsigned int rdoff, avail; + unsigned long flags; + char __user *u_ptr; + int xret; + + /* count may not be zero. */ + + if (count > ring->bufsz) + return -EFBIG; + + if (ring->granularity > 1 && count % ring->granularity > 0) + return -EINVAL; + + len = count; +retry: + u_ptr = u_buf; + + for (;;) { + raw_spin_lock_irqsave(&ring->lock, flags); + + avail = atomic_read(&ring->fillsz) - ring->reserved; + + if (avail < len) { + raw_spin_unlock_irqrestore(&ring->lock, flags); + + if (avail > 0 && filp->f_flags & O_NONBLOCK) { + /* granularity may not be ^2. */ + len = rounddown(avail, ring->granularity ?: 1); + if (len) + goto retry; + } + + if (in->on_error) + return in->on_error; + + /* + * Zero return means 'wait then try again' to + * the caller. Should the worker get -EAGAIN + * as non-blocking mode was set for the target + * file, on_error would reflect this. + */ + return 0; + } + + rdoff = ring->rdoff; + ring->rdoff = (rdoff + len) % ring->bufsz; + ring->nesting++; + ring->reserved += len; + rbytes = ret = len; + + do { + if (rdoff + rbytes > ring->bufsz) + n = ring->bufsz - rdoff; + else + n = rbytes; + + raw_spin_unlock_irqrestore(&ring->lock, flags); + xret = raw_copy_to_user(u_ptr, ring->bufmem + rdoff, n); + raw_spin_lock_irqsave(&ring->lock, flags); + if (xret) { + ret = -EFAULT; + break; + } + + u_ptr += n; + rbytes -= n; + rdoff = (rdoff + n) % ring->bufsz; + } while (rbytes > 0); + + if (--ring->nesting == 0) { + atomic_sub(ring->reserved, &ring->fillsz); + ring->reserved = 0; + } + break; + } + + raw_spin_unlock_irqrestore(&ring->lock, flags); + + evl_schedule(); + + return ret; +} + +static ssize_t proxy_oob_write(struct file *filp, + const char __user *u_buf, size_t count) +{ + struct evl_proxy *proxy = element_of(filp, struct evl_proxy); + struct proxy_ring *ring = &proxy->output.ring; + ssize_t ret; + + if (!proxy_may_write(proxy)) + return -ENXIO; + + do { + ret = do_proxy_write(filp, u_buf, count); + if (ret != -EAGAIN || filp->f_flags & O_NONBLOCK) + break; + ret = evl_wait_flag(&ring->oob_wait); + } while (!ret); + + return ret == -EIDRM ? -EBADF : ret; +} + +static ssize_t proxy_oob_read(struct file *filp, + char __user *u_buf, size_t count) +{ + struct evl_proxy *proxy = element_of(filp, struct evl_proxy); + struct proxy_in *in = &proxy->input; + struct proxy_ring *ring = &in->ring; + bool request_done = false; + ssize_t ret; + + if (!proxy_may_read(proxy)) + return -ENXIO; + + if (count == 0) + return 0; + + for (;;) { + ret = do_proxy_read(filp, u_buf, count); + if (ret || filp->f_flags & O_NONBLOCK) + break; + if (!request_done) { + atomic_add(count, &in->reqsz); + request_done = true; + } + evl_call_inband_from(&ring->relay_work, ring->wq); + ret = evl_wait_flag(&ring->oob_wait); + if (ret) + break; + if (atomic_cmpxchg(&in->on_eof, true, false)) { + ret = 0; + break; + } + } + + return ret == -EIDRM ? -EBADF : ret; +} + +static __poll_t proxy_oob_poll(struct file *filp, + struct oob_poll_wait *wait) +{ + struct evl_proxy *proxy = element_of(filp, struct evl_proxy); + struct proxy_ring *oring = &proxy->output.ring; + struct proxy_ring *iring = &proxy->input.ring; + __poll_t ret = 0; + int peek; + + evl_poll_watch(&proxy->poll_head, wait, NULL); + + if (proxy_may_write(proxy) && + atomic_read(&oring->fillsz) < oring->bufsz) + ret |= POLLOUT|POLLWRNORM; + + /* + * If the input ring is empty, kick the worker to perform a + * readahead. + */ + if (proxy_may_read(proxy)) { + if (atomic_read(&iring->fillsz) > 0) + ret |= POLLIN|POLLRDNORM; + else if (atomic_read(&proxy->input.reqsz) == 0) { + peek = iring->granularity ?: 1; + atomic_add(peek, &proxy->input.reqsz); + evl_call_inband_from(&iring->relay_work, iring->wq); + } + } + + /* + * If the proxied file implements an oob poll handler, collect + * the events pending there as well. + */ + if (proxy->filp->f_op->oob_poll) + ret |= proxy->filp->f_op->oob_poll(filp, wait); + + return ret; +} + +static ssize_t proxy_write(struct file *filp, const char __user *u_buf, + size_t count, loff_t *ppos) +{ + struct evl_proxy *proxy = element_of(filp, struct evl_proxy); + struct proxy_ring *ring = &proxy->output.ring; + ssize_t ret; + + if (!proxy_may_write(proxy)) + return -ENXIO; + + do { + ret = do_proxy_write(filp, u_buf, count); + if (ret != -EAGAIN || filp->f_flags & O_NONBLOCK) + break; + ret = wait_event_interruptible(ring->inband_wait_w, + can_write_buffer(ring, count)); + } while (!ret); + + return ret; +} + +static ssize_t proxy_read(struct file *filp, + char __user *u_buf, size_t count, loff_t *ppos) +{ + struct evl_proxy *proxy = element_of(filp, struct evl_proxy); + struct proxy_in *in = &proxy->input; + bool request_done = false; + ssize_t ret; + + if (!proxy_may_read(proxy)) + return -ENXIO; + + if (count == 0) + return 0; + + for (;;) { + ret = do_proxy_read(filp, u_buf, count); + if (ret || filp->f_flags & O_NONBLOCK) + break; + if (!request_done) { + atomic_add(count, &in->reqsz); + request_done = true; + } + relay_input(proxy); + if (atomic_cmpxchg(&in->on_eof, true, false)) { + ret = 0; + break; + } + } + + return ret; +} + +static __poll_t proxy_poll(struct file *filp, poll_table *wait) +{ + struct evl_proxy *proxy = element_of(filp, struct evl_proxy); + struct proxy_ring *oring = &proxy->output.ring; + struct proxy_ring *iring = &proxy->input.ring; + __poll_t ret = 0; + + if (proxy_may_write(proxy)) { + poll_wait(filp, &oring->inband_wait_w, wait); + if (atomic_read(&oring->fillsz) < oring->bufsz) + ret = POLLOUT|POLLWRNORM; + } + + if (proxy_may_read(proxy)) { + poll_wait(filp, &iring->inband_wait_r, wait); + if (atomic_read(&iring->fillsz) > 0) + ret |= POLLIN|POLLRDNORM; + } + + if (proxy->filp->f_op->poll) + ret |= proxy->filp->f_op->poll(proxy->filp, wait); + + return ret; +} + +static int proxy_mmap(struct file *filp, struct vm_area_struct *vma) +{ + struct evl_proxy *proxy = element_of(filp, struct evl_proxy); + struct file *mapfilp = proxy->filp; + int ret; + + if (mapfilp->f_op->mmap == NULL) + return -ENODEV; + + vma->vm_file = get_file(mapfilp); + + /* + * Since the mapper element impersonates a different file, we + * need to swap references: if the mapping call fails, we have + * to drop the reference on the target file we just took on + * entry; if it succeeds, then we have to drop the reference + * on the mapper file do_mmap_pgoff() acquired before calling + * us. + */ + ret = call_mmap(mapfilp, vma); + if (ret) + fput(mapfilp); + else + fput(filp); + + return ret; +} + +static int proxy_release(struct inode *inode, struct file *filp) +{ + struct evl_proxy *proxy = element_of(filp, struct evl_proxy); + + if (proxy_may_write(proxy)) + evl_flush_flag(&proxy->output.ring.oob_wait, EVL_T_RMID); + + if (proxy_may_read(proxy)) + evl_flush_flag(&proxy->input.ring.oob_wait, EVL_T_RMID); + + return evl_release_element(inode, filp); +} + +static const struct file_operations proxy_fops = { + .open = evl_open_element, + .release = proxy_release, + .oob_write = proxy_oob_write, + .oob_read = proxy_oob_read, + .oob_poll = proxy_oob_poll, + .write = proxy_write, + .read = proxy_read, + .poll = proxy_poll, + .mmap = proxy_mmap, +}; + +static int init_ring(struct proxy_ring *ring, + struct evl_proxy *proxy, + size_t bufsz, + unsigned int granularity, + bool is_output) +{ + struct workqueue_struct *wq; + void *bufmem; + + bufmem = kzalloc(bufsz, GFP_KERNEL); + if (bufmem == NULL) + return -ENOMEM; + + wq = alloc_ordered_workqueue("%s.%c", 0, + evl_element_name(&proxy->element), + is_output ? 'O' : 'I'); + if (wq == NULL) { + kfree(bufmem); + return -ENOMEM; + } + + ring->wq = wq; + ring->bufmem = bufmem; + ring->bufsz = bufsz; + ring->granularity = granularity; + raw_spin_lock_init(&ring->lock); + evl_init_work_safe(&ring->relay_work, + is_output ? relay_output_work : relay_input_work, + &proxy->element); + evl_init_flag(&ring->oob_wait); + init_waitqueue_head(&ring->inband_wait_r); + init_waitqueue_head(&ring->inband_wait_w); + mutex_init(&ring->worker_lock); + + return 0; +} + +static void destroy_ring(struct proxy_ring *ring) +{ + evl_destroy_flag(&ring->oob_wait); + /* + * We cannot flush_work() since we may be called from a + * kworker, so we bluntly cancel any pending work instead. If + * output sync has to be guaranteed on closure, polling for + * POLLOUT before closing the target file is your friend. + */ + evl_cancel_work(&ring->relay_work); + destroy_workqueue(ring->wq); + kfree(ring->bufmem); +} + +static struct evl_element * +proxy_factory_build(struct evl_factory *fac, const char __user *u_name, + void __user *u_attrs, int clone_flags, u32 *state_offp) +{ + struct evl_proxy_attrs attrs; + struct evl_proxy *proxy; + struct file *filp; + size_t bufsz; + int ret; + + if (clone_flags & ~EVL_PROXY_CLONE_FLAGS) + return ERR_PTR(-EINVAL); + + ret = copy_from_user(&attrs, u_attrs, sizeof(attrs)); + if (ret) + return ERR_PTR(-EFAULT); + + bufsz = attrs.bufsz; + if (order_base_2(bufsz) > 30) /* LART */ + return ERR_PTR(-EINVAL); + + if (bufsz == 0 && (clone_flags & (EVL_CLONE_INPUT|EVL_CLONE_OUTPUT))) + return ERR_PTR(-EINVAL); + + /* + * If a granularity is set, the buffer size must be a multiple + * of the granule size. + */ + if (attrs.granularity > 1 && bufsz % attrs.granularity > 0) + return ERR_PTR(-EINVAL); + + filp = fget(attrs.fd); + if (filp == NULL) + return ERR_PTR(-EBADF); + + proxy = kzalloc(sizeof(*proxy), GFP_KERNEL); + if (proxy == NULL) { + ret = -ENOMEM; + goto fail_proxy; + } + + /* + * No direction specified but a valid buffer size implies + * EVL_CLONE_OUTPUT. + */ + if (bufsz > 0 && !(clone_flags & (EVL_CLONE_INPUT|EVL_CLONE_OUTPUT))) + clone_flags |= EVL_CLONE_OUTPUT; + + ret = evl_init_user_element(&proxy->element, + &evl_proxy_factory, u_name, clone_flags); + if (ret) + goto fail_element; + + proxy->filp = filp; + evl_init_poll_head(&proxy->poll_head); + + if (clone_flags & EVL_CLONE_OUTPUT) { + ret = init_ring(&proxy->output.ring, proxy, bufsz, + attrs.granularity, true); + if (ret) + goto fail_output_init; + } + + if (clone_flags & EVL_CLONE_INPUT) { + ret = init_ring(&proxy->input.ring, proxy, bufsz, + attrs.granularity, false); + if (ret) + goto fail_input_init; + } + + evl_index_factory_element(&proxy->element); + + return &proxy->element; + +fail_input_init: + if (clone_flags & EVL_CLONE_OUTPUT) + destroy_ring(&proxy->output.ring); +fail_output_init: + evl_destroy_element(&proxy->element); +fail_element: + kfree(proxy); +fail_proxy: + fput(filp); + + return ERR_PTR(ret); +} + +static void proxy_factory_dispose(struct evl_element *e) +{ + struct evl_proxy *proxy; + + proxy = container_of(e, struct evl_proxy, element); + + if (proxy_may_write(proxy)) + destroy_ring(&proxy->output.ring); + + if (proxy_may_read(proxy)) + destroy_ring(&proxy->input.ring); + + fput(proxy->filp); + + evl_unindex_factory_element(&proxy->element); + evl_destroy_element(&proxy->element); + + kfree_rcu(proxy, element.rcu); +} + +struct evl_factory evl_proxy_factory = { + .name = EVL_PROXY_DEV, + .fops = &proxy_fops, + .build = proxy_factory_build, + .dispose = proxy_factory_dispose, + .nrdev = CONFIG_EVL_NR_PROXIES, + .flags = EVL_FACTORY_CLONE, +}; diff --git a/kernel/evl/random.c b/kernel/evl/random.c new file mode 100644 index 000000000..da2a1edd5 --- /dev/null +++ b/kernel/evl/random.c @@ -0,0 +1,163 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2023 Lionel Minne + * Copyright (C) 2023 Philippe Gerum + */ + +#include +#include +#include +#include +#include + +static const u64 EVL_RNG_PRIME_u8 = 409; + +static const u64 EVL_RNG_PRIME_u16 = 106013; + +static const u64 EVL_RNG_PRIME_u32 = 949402981; + +#define EVL_RNG_SIZE 55 +#define EVL_RNG_J 24 +#define EVL_RNG_K EVL_RNG_SIZE + +#define EVL_DEFINE_RNG(__type) \ + static struct evl_rng_ ## __type { \ + __type array[EVL_RNG_SIZE]; \ + size_t index; \ + } evl_rng_ ## __type; \ + \ + static void init_rng_ ## __type(struct evl_rng_ ## __type *rng, __type seed) \ + { \ + u64 val; \ + size_t n; \ + \ + rng->array[0] = seed; \ + for (n = 0, val = seed; n < ARRAY_SIZE(rng->array); n++) { \ + val += EVL_RNG_PRIME_ ## __type; \ + rng->array[n] = (__type)val; \ + } \ + } \ + \ + static __type read_rng_ ## __type(struct evl_rng_ ## __type *rng) \ + { \ + size_t n_j, n_k; \ + __type res; \ + \ + n_j = rng->index - EVL_RNG_J; \ + if (EVL_RNG_J > rng->index) \ + n_j += ARRAY_SIZE(rng->array); \ + \ + n_k = rng->index - EVL_RNG_K; \ + if (EVL_RNG_K > rng->index) \ + n_k += ARRAY_SIZE(rng->array); \ + \ + res = (__type)((u64)rng->array[n_j] + (u64)rng->array[n_k]); \ + rng->array[rng->index] = res; \ + rng->index = (rng->index + 1) % ARRAY_SIZE(rng->array); \ + \ + return res; \ + } \ + \ + __type evl_read_rng_ ## __type(void) \ + { \ + return read_rng_ ## __type(&evl_rng_ ## __type); \ + } + +EVL_DEFINE_RNG(u8); +EVL_DEFINE_RNG(u16); +EVL_DEFINE_RNG(u32); + +static ssize_t rng_common_read(struct file *filp, + char __user *u_buf, size_t count) +{ + u32 val32; + + if (count != sizeof(val32)) + return -EINVAL; + + val32 = evl_read_rng_u32(); + + if (raw_put_user(val32, (u32 __user *)u_buf)) + return -EFAULT; + + return count; +} + +static ssize_t rng_oob_read(struct file *filp, + char __user *u_buf, size_t count) +{ + return rng_common_read(filp, u_buf, count); +} + +static ssize_t rng_read(struct file *filp, char __user *u_buf, + size_t count, loff_t *ppos) +{ + return rng_common_read(filp, u_buf, count); +} + +static long rng_common_ioctl(struct file *filp, unsigned int cmd, + unsigned long arg) +{ + __u32 val32; + __u16 val16; + __u8 val8; + int ret; + + switch (cmd) { + case EVL_RNGIOC_U8: + val8 = evl_read_rng_u8(); + ret = raw_put_user(val8, (u8 __user *)arg); + break; + case EVL_RNGIOC_U16: + val16 = evl_read_rng_u16(); + ret = raw_put_user(val16, (u16 __user *)arg); + break; + case EVL_RNGIOC_U32: + val32 = evl_read_rng_u32(); + ret = raw_put_user(val32, (u32 __user *)arg); + break; + default: + ret = -ENOTTY; + } + + return ret > 0 ? -EFAULT : ret; +} + +static long rng_oob_ioctl(struct file *filp, unsigned int cmd, + unsigned long arg) +{ + return rng_common_ioctl(filp, cmd, arg); +} + +static long rng_ioctl(struct file *filp, unsigned int cmd, + unsigned long arg) +{ + return rng_common_ioctl(filp, cmd, arg); +} + +void evl_init_rng(void) +{ + u64 now = ktime_get(); + + init_rng_u8(&evl_rng_u8, (u8)now); + init_rng_u16(&evl_rng_u16, (u16)now); + init_rng_u32(&evl_rng_u32, (u32)now); +} + +static const struct file_operations rng_fops = { + .oob_ioctl = rng_oob_ioctl, + .oob_read = rng_oob_read, + .unlocked_ioctl = rng_ioctl, + .read = rng_read, +#ifdef CONFIG_COMPAT + .compat_ioctl = compat_ptr_ioctl, + .compat_oob_ioctl = compat_ptr_oob_ioctl, +#endif +}; + +struct evl_factory evl_rng_factory = { + .name = "random", + .fops = &rng_fops, + .flags = EVL_FACTORY_SINGLE, +}; diff --git a/kernel/evl/sched/Makefile b/kernel/evl/sched/Makefile new file mode 100644 index 000000000..5d9245823 --- /dev/null +++ b/kernel/evl/sched/Makefile @@ -0,0 +1,12 @@ +obj-$(CONFIG_EVL) += evl.o + +ccflags-y += -Ikernel + +evl-y := \ + core.o \ + fifo.o \ + idle.o \ + weak.o + +evl-$(CONFIG_EVL_SCHED_QUOTA) += quota.o +evl-$(CONFIG_EVL_SCHED_TP) += tp.o diff --git a/kernel/evl/sched/core.c b/kernel/evl/sched/core.c new file mode 100644 index 000000000..7154481b7 --- /dev/null +++ b/kernel/evl/sched/core.c @@ -0,0 +1,1445 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Derived from Xenomai Cobalt, https://xenomai.org/ + * Copyright (C) 2001, 2008, 2018 Philippe Gerum + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +DEFINE_PER_CPU(struct evl_rq, evl_runqueues); +EXPORT_PER_CPU_SYMBOL_GPL(evl_runqueues); + +struct cpumask evl_cpu_affinity = CPU_MASK_ALL; +EXPORT_SYMBOL_GPL(evl_cpu_affinity); + +static struct evl_sched_class *evl_sched_topmost; + +#define for_each_evl_sched_class(p) \ + for (p = evl_sched_topmost; p; p = p->next) + +static struct evl_sched_class *evl_sched_lower; + +#define for_each_evl_lower_sched_class(p) \ + for (p = evl_sched_lower; p; p = p->next) + +static void register_one_class(struct evl_sched_class *sched_class) +{ + sched_class->next = evl_sched_topmost; + evl_sched_topmost = sched_class; + if (sched_class != &evl_sched_fifo) + evl_sched_lower = sched_class; + + /* + * Classes shall be registered by increasing priority order, + * idle first and up until fifo last. + */ + EVL_WARN_ON(CORE, sched_class->next && + sched_class->next->weight > sched_class->weight); +} + +static void register_classes(void) +{ + register_one_class(&evl_sched_idle); + register_one_class(&evl_sched_weak); +#ifdef CONFIG_EVL_SCHED_QUOTA + register_one_class(&evl_sched_quota); +#endif +#ifdef CONFIG_EVL_SCHED_TP + register_one_class(&evl_sched_tp); +#endif + register_one_class(&evl_sched_fifo); + + /* The FIFO class must be on top (see __pick_next_thread()). */ + EVL_WARN_ON_ONCE(CORE, evl_sched_topmost != &evl_sched_fifo); +} + +#ifdef CONFIG_EVL_WATCHDOG + +static unsigned long wd_timeout_arg = CONFIG_EVL_WATCHDOG_TIMEOUT; +module_param_named(watchdog_timeout, wd_timeout_arg, ulong, 0644); + +static inline ktime_t get_watchdog_timeout(void) +{ + return ns_to_ktime(wd_timeout_arg * 1000000000ULL); +} + +static void watchdog_handler(struct evl_timer *timer) /* oob stage stalled */ +{ + struct evl_rq *this_rq = this_evl_rq(); + struct evl_thread *curr = this_rq->curr; + + trace_evl_watchdog_signal(curr); + + /* + * CAUTION: The watchdog tick might have been delayed while we + * were busy switching the CPU to in-band context at the + * trigger date eventually. Make sure that we are not about to + * kick the incoming root thread. + */ + if (curr->state & EVL_T_ROOT) + return; + + if (curr->state & EVL_T_USER) { + raw_spin_lock(&curr->lock); + raw_spin_lock(&this_rq->lock); + curr->info |= EVL_T_KICKED; + raw_spin_unlock(&this_rq->lock); + raw_spin_unlock(&curr->lock); + evl_notify_thread(curr, EVL_HMDIAG_WATCHDOG, evl_nil); + dovetail_send_mayday(current); + printk(EVL_WARNING "watchdog triggered on CPU #%d -- runaway thread " + "'%s' signaled\n", evl_rq_cpu(this_rq), curr->name); + } else { + printk(EVL_WARNING "watchdog triggered on CPU #%d -- runaway thread " + "'%s' canceled\n", evl_rq_cpu(this_rq), curr->name); + /* + * On behalf on an IRQ handler, evl_cancel_thread() + * would go half way cancelling the preempted + * thread. Therefore we manually raise EVL_T_KICKED to + * cause the next blocking call to return early in + * EVL_T_BREAK condition, and EVL_T_CANCELD so that @curr + * exits next time it invokes evl_test_cancel(). + */ + raw_spin_lock(&curr->lock); + raw_spin_lock(&this_rq->lock); + curr->info |= (EVL_T_KICKED|EVL_T_CANCELD); + raw_spin_unlock(&this_rq->lock); + raw_spin_unlock(&curr->lock); + } +} + +#endif /* CONFIG_EVL_WATCHDOG */ + +static void roundrobin_handler(struct evl_timer *timer) /* hard irqs off */ +{ + struct evl_rq *this_rq = container_of(timer, struct evl_rq, rrbtimer); + + raw_spin_lock(&this_rq->lock); + + if (this_rq->curr->state & EVL_T_RRB) + evl_sched_yield(this_rq); + + raw_spin_unlock(&this_rq->lock); +} + +static void init_rq(struct evl_rq *rq, int cpu) +{ + struct evl_sched_class *sched_class; + struct evl_init_thread_attr iattr; + const char *name_fmt; + +#ifdef CONFIG_SMP + rq->cpu = cpu; + name_fmt = "ROOT/%u"; + rq->proxy_timer_name = kasprintf(GFP_KERNEL, "[proxy-timer/%u]", cpu); + rq->rrb_timer_name = kasprintf(GFP_KERNEL, "[rrb-timer/%u]", cpu); + cpumask_clear(&rq->resched_cpus); +#else + name_fmt = "ROOT"; + rq->proxy_timer_name = kstrdup("[proxy-timer]", GFP_KERNEL); + rq->rrb_timer_name = kstrdup("[rrb-timer]", GFP_KERNEL); +#endif + raw_spin_lock_init(&rq->lock); + + for_each_evl_sched_class(sched_class) { + if (sched_class->sched_init) + sched_class->sched_init(rq); + } + + rq->flags = 0; + rq->local_flags = RQ_IDLE; + rq->curr = &rq->root_thread; + + /* + * No handler needed for the inband timer since proxy timer + * events are handled specifically by the generic timer code + * (do_clock_tick()). + */ + evl_init_timer_on_rq(&rq->inband_timer, &evl_mono_clock, NULL, + rq, EVL_TIMER_IGRAVITY); + evl_set_timer_name(&rq->inband_timer, rq->proxy_timer_name); + evl_init_timer_on_rq(&rq->rrbtimer, &evl_mono_clock, roundrobin_handler, + rq, EVL_TIMER_IGRAVITY); + evl_set_timer_name(&rq->rrbtimer, rq->rrb_timer_name); +#ifdef CONFIG_EVL_WATCHDOG + evl_init_timer_on_rq(&rq->wdtimer, &evl_mono_clock, watchdog_handler, + rq, EVL_TIMER_IGRAVITY); + evl_set_timer_name(&rq->wdtimer, "[watchdog]"); +#endif /* CONFIG_EVL_WATCHDOG */ + + evl_set_current_account(rq, &rq->root_thread.stat.account); + + /* + * Postpone evl_init_thread() - which sets RQ_SCHED upon + * setting the schedparams for the root thread - until we have + * enough of the runqueue initialized, so that attempting to + * reschedule from evl_exit_irq() later on is harmless. + */ + iattr.flags = EVL_T_ROOT; + iattr.affinity = cpumask_of(cpu); + iattr.observable = NULL; + iattr.sched_class = &evl_sched_idle; + iattr.sched_param.idle.prio = EVL_IDLE_PRIO; + evl_init_thread(&rq->root_thread, &iattr, rq, name_fmt, cpu); + + dovetail_init_altsched(&rq->root_thread.altsched); + + list_add_tail(&rq->root_thread.next, &evl_thread_list); + evl_nrthreads++; +} + +static void destroy_rq(struct evl_rq *rq) +{ + evl_destroy_timer(&rq->inband_timer); + evl_destroy_timer(&rq->rrbtimer); + kfree(rq->proxy_timer_name); + kfree(rq->rrb_timer_name); + evl_destroy_timer(&rq->root_thread.ptimer); + evl_destroy_timer(&rq->root_thread.rtimer); +#ifdef CONFIG_EVL_WATCHDOG + evl_destroy_timer(&rq->wdtimer); +#endif /* CONFIG_EVL_WATCHDOG */ +} + +#ifdef CONFIG_EVL_DEBUG_CORE + +void evl_disable_preempt(void) +{ + __evl_disable_preempt(); +} +EXPORT_SYMBOL(evl_disable_preempt); + +void evl_enable_preempt(void) +{ + __evl_enable_preempt(); +} +EXPORT_SYMBOL(evl_enable_preempt); + +#endif /* CONFIG_EVL_DEBUG_CORE */ + +#ifdef CONFIG_SMP + +static inline +void evl_double_rq_lock(struct evl_rq *rq1, struct evl_rq *rq2) +{ + EVL_WARN_ON_ONCE(CORE, !hard_irqs_disabled()); + + /* Prevent ABBA deadlock, always lock rqs in address order. */ + + if (rq1 == rq2) { + raw_spin_lock(&rq1->lock); + } else if (rq1 < rq2) { + raw_spin_lock(&rq1->lock); + raw_spin_lock_nested(&rq2->lock, SINGLE_DEPTH_NESTING); + } else { + raw_spin_lock(&rq2->lock); + raw_spin_lock_nested(&rq1->lock, SINGLE_DEPTH_NESTING); + } +} + +static inline +void evl_double_rq_unlock(struct evl_rq *rq1, struct evl_rq *rq2) +{ + raw_spin_unlock(&rq1->lock); + if (rq1 != rq2) + raw_spin_unlock(&rq2->lock); +} + +/* irqs off. */ +static void migrate_rq(struct evl_thread *thread, struct evl_rq *dst_rq) +{ + struct evl_sched_class *sched_class = thread->sched_class; + struct evl_rq *src_rq = thread->rq; + + /* + * check_cpu_affinity() might ask us to move @thread to a CPU + * which is not part of the oob set due to a spurious + * migration, this is ok. The offending thread would exit + * shortly after resuming. + */ + evl_double_rq_lock(src_rq, dst_rq); + + if (thread->state & EVL_T_READY) { + evl_dequeue_thread(thread); + thread->state &= ~EVL_T_READY; + } + + if (sched_class->sched_migrate) + sched_class->sched_migrate(thread, dst_rq); + /* + * WARNING: the scheduling class may have just changed as a + * result of calling the per-class migration hook. + */ + thread->rq = dst_rq; + + if (!(thread->state & EVL_THREAD_BLOCK_BITS)) { + evl_requeue_thread(thread); + thread->state |= EVL_T_READY; + evl_set_resched(dst_rq); + evl_set_resched(src_rq); + } + + evl_double_rq_unlock(src_rq, dst_rq); +} + +/* + * Move a thread to a different runqueue. Some sched_migrate() policy + * handlers might change the scheduling class and/or priority of the + * target thread, our callers MAY HAVE TO check for EVL_T_WCHAN to + * determine whether the wait channel it might pend on should be + * adjusted accordingly. + * + * thread->lock held, hard irqs off. @thread must be running in-band. + */ +void evl_migrate_thread(struct evl_thread *thread, struct evl_rq *dst_rq) +{ + assert_hard_lock(&thread->lock); + + if (thread->rq == dst_rq) + return; + + trace_evl_thread_migrate(thread, evl_rq_cpu(dst_rq)); + + /* + * Timer migration is postponed until the next timeout happens + * for the periodic and rrb timers. The resource/periodic + * timer will be moved to the right CPU next time + * evl_prepare_timed_wait() is called for it (via + * evl_sleep_on()). + */ + migrate_rq(thread, dst_rq); + + evl_reset_account(&thread->stat.lastperiod); +} + +static void check_cpu_affinity(struct task_struct *p) /* inband, hard irqs off */ +{ + struct evl_thread *thread = evl_thread_from_task(p); + int cpu = task_cpu(p); + struct evl_rq *rq = evl_cpu_rq(cpu); + bool need_requeue = false; + + raw_spin_lock(&thread->lock); + + if (likely(rq == thread->rq)) { + raw_spin_unlock(&thread->lock); + return; + } + + /* + * Resync the EVL and in-band schedulers upon migration from + * an EVL thread, which can only happen from the in-band stage + * (no CPU migration from the oob stage is possible). In such + * an event, the CPU information kept by the EVL scheduler for + * that thread has become obsolete. + * + * check_cpu_affinity() detects this when the EVL thread is in + * flight to the oob stage. If the new CPU is not part of the + * oob set, mark the thread for pending cancellation but + * update the scheduler information nevertheless. Although + * some CPUs might be excluded from the oob set, all of them + * are capable of scheduling threads nevertheless (i.e. all + * runqueues are up and running). + */ + if (unlikely(!is_threading_cpu(cpu))) { + printk(EVL_WARNING "thread %s[%d] switched to non-rt CPU%d, aborted.\n", + thread->name, evl_get_inband_pid(thread), cpu); + /* + * Can't call evl_cancel_thread() from a CPU migration + * point, that would break. Since we are on the wakeup + * path to oob context, just raise EVL_T_CANCELD to catch + * it in evl_switch_oob(). + */ + raw_spin_lock(&thread->rq->lock); + thread->info |= EVL_T_CANCELD; + raw_spin_unlock(&thread->rq->lock); + } else { + /* + * If the current thread moved to a supported + * out-of-band CPU, which is not part of its original + * affinity mask, assume user wants to extend this + * mask. + */ + if (!cpumask_test_cpu(cpu, &thread->affinity)) + cpumask_set_cpu(cpu, &thread->affinity); + } + + evl_migrate_thread(thread, rq); + + /* + * Check for a wait channel requeuing. Open code the portion + * of the evl_put_thread_rq_check_noirq() logic we need. + */ + if (thread->info & EVL_T_WCHAN) { + raw_spin_lock(&thread->rq->lock); + thread->info &= ~EVL_T_WCHAN; + raw_spin_unlock(&thread->rq->lock); + need_requeue = true; + } + + raw_spin_unlock(&thread->lock); + + if (need_requeue) + evl_adjust_wait_priority(thread); +} + +#else + +#define evl_double_rq_lock(__rq1, __rq2) \ + EVL_WARN_ON_ONCE(CORE, !hard_irqs_disabled()); + +#define evl_double_rq_unlock(__rq1, __rq2) do { } while (0) + +static inline void check_cpu_affinity(struct task_struct *p) +{ } + +#endif /* CONFIG_SMP */ + +/* thread->lock + thread->rq->lock held, hard irqs off. */ +void evl_putback_thread(struct evl_thread *thread) +{ + assert_thread_pinned(thread); + + if (thread->state & EVL_T_READY) + evl_dequeue_thread(thread); + else + thread->state |= EVL_T_READY; + + evl_enqueue_thread(thread); + evl_set_resched(thread->rq); +} + +/* thread->lock + thread->rq->lock held, hard irqs off. */ +int evl_set_thread_policy_locked(struct evl_thread *thread, + struct evl_sched_class *sched_class, + const union evl_sched_param *p) +{ + struct evl_sched_class *orig_effective_class __maybe_unused; + bool effective; + int ret; + + assert_thread_pinned(thread); + + /* Check parameters early on. */ + ret = evl_check_schedparams(sched_class, thread, p); + if (ret) + return ret; + + /* + * Declaring a thread to a new scheduling class may fail, so + * we do that early, while the thread is still a member of the + * previous class. However, this also means that the + * declaration callback shall not do anything that might + * affect the previous class (such as touching thread->rq_next + * for instance). + */ + if (sched_class != thread->base_class) { + ret = evl_declare_thread(sched_class, thread, p); + if (ret) + return ret; + } + + /* + * As a special case, we may be called from evl_init_thread() + * with no previous scheduling class at all. + */ + if (likely(thread->base_class != NULL)) { + if (thread->state & EVL_T_READY) + evl_dequeue_thread(thread); + + if (sched_class != thread->base_class) + evl_forget_thread(thread); + } + + /* + * Set the base and effective scheduling parameters. However, + * evl_set_schedparam() will deny lowering the effective + * priority if a boost is undergoing, only recording the + * change into the base priority field in such case. + */ + thread->base_class = sched_class; + /* + * Referring to the effective class from a setparam() handler + * is wrong: make sure to break if so. + */ + if (EVL_DEBUG(CORE)) { + orig_effective_class = thread->sched_class; + thread->sched_class = NULL; + } + + /* + * This is the ONLY place where calling + * evl_set_schedparam() is legit, sane and safe. + */ + effective = evl_set_schedparam(thread, p); + if (effective) { + thread->sched_class = sched_class; + thread->wprio = evl_calc_weighted_prio(sched_class, thread->cprio); + } else if (EVL_DEBUG(CORE)) + thread->sched_class = orig_effective_class; + + if (thread->state & EVL_T_READY) + evl_enqueue_thread(thread); + + /* + * Make sure not to raise RQ_SCHED when setting up the root + * thread, so that we can't start rescheduling from + * evl_exit_irq() before all CPUs have their runqueue fully + * built. Filtering on EVL_T_ROOT here is correct because the root + * thread enters the idle class once as part of the runqueue + * setup process and never leaves it afterwards. + */ + if (!(thread->state & (EVL_T_DORMANT|EVL_T_ROOT))) + evl_set_resched(thread->rq); + else + EVL_WARN_ON(CORE, (thread->state & EVL_T_ROOT) && + sched_class != &evl_sched_idle); + return 0; +} + +int evl_set_thread_policy(struct evl_thread *thread, + struct evl_sched_class *sched_class, + const union evl_sched_param *p) +{ + unsigned long flags; + struct evl_rq *rq; + int ret; + + rq = evl_get_thread_rq(thread, flags); + ret = evl_set_thread_policy_locked(thread, sched_class, p); + evl_put_thread_rq(thread, rq, flags); + + return ret; +} + +/* thread->lock + thread->rq->lock held, hard irqs off. */ +bool evl_set_effective_thread_priority(struct evl_thread *thread, int prio) +{ + int wprio = evl_calc_weighted_prio(thread->base_class, prio); + + assert_thread_pinned(thread); + + thread->bprio = prio; + if (wprio == thread->wprio) + return true; + + /* + * We may not lower the effective/current priority of a thread + * undergoing a priority boost when changing the base + * scheduling parameters. Only evl_adjust_thread_boost() may + * do so. + */ + if (wprio < thread->wprio && (thread->state & EVL_T_BOOST)) + return false; + + thread->cprio = prio; + + trace_evl_thread_set_current_prio(thread); + + return true; +} + +/* + * thread->lock held, irqs off. + * + * Returns true if the operation resulted in a priority/policy update + * for @thread. + */ +bool evl_adjust_thread_boost(struct evl_thread *thread) +{ + struct evl_mutex *top_booster; + bool ret = false; + + assert_hard_lock(&thread->lock); + + raw_spin_lock(&thread->rq->lock); + + /* Check for the deboosting case first. */ + if (list_empty(&thread->boosters)) { + if (!(thread->state & EVL_T_BOOST)) + goto out; + + /* Dequeue first, _then_ update the schedparams. */ + if (thread->state & EVL_T_READY) + evl_dequeue_thread(thread); + + thread->state &= ~EVL_T_BOOST; + thread->sched_class = thread->base_class; + /* Tell the sched policy module about the update. */ + evl_track_priority(thread, NULL); + + /* + * Per SuSv2, resetting the base scheduling parameters + * should not move the thread to the tail of its + * priority group, which makes sense. + */ + if (thread->state & EVL_T_READY) + evl_requeue_thread(thread); + } else { + /* + * Fetch the top booster, which is the mutex queuing + * the waiter with the highest priority among all + * PI/PP mutexes currently held by @thread. This + * booster might have no waiter yet, if current is + * about to wait on it. + */ + top_booster = list_first_entry(&thread->boosters, + struct evl_mutex, next_booster); + + /* + * top_booster->boost.wprio stores the policy-weighted + * priority of the top waiter sleeping on + * top_booster. IOW, the priority the owner should + * have when boosted. + */ + if (top_booster->boost.wprio == thread->wprio) + goto out; + + /* Save the base priority at initial boost (only). */ + if (!(thread->state & EVL_T_BOOST)) { + thread->bprio = thread->cprio; + thread->state |= EVL_T_BOOST; + } + + if (thread->state & EVL_T_READY) + evl_dequeue_thread(thread); + + if (top_booster->flags & EVL_MUTEX_PP) { + thread->sched_class = &evl_sched_fifo; + evl_ceil_priority(thread, + evl_ceiling_priority(top_booster)); + } else { + thread->sched_class = top_booster->boost.sched_class; + evl_track_priority(thread, &top_booster->boost.param); + } + + if (thread->state & EVL_T_READY) + evl_enqueue_thread(thread); + } + + trace_evl_thread_set_current_prio(thread); + evl_set_resched(thread->rq); + ret = true; +out: + raw_spin_unlock(&thread->rq->lock); + + return ret; +} + +#ifdef CONFIG_EVL_SCHED_SCALABLE + +void evl_init_schedq(struct evl_sched_queue *q) +{ + int prio; + + q->elems = 0; + bitmap_zero(q->prio_map, EVL_MLQ_LEVELS); + + for (prio = 0; prio < EVL_MLQ_LEVELS; prio++) + INIT_LIST_HEAD(q->heads + prio); +} + +struct evl_thread *__evl_get_schedq(struct evl_sched_queue *q) +{ + struct evl_thread *thread; + struct list_head *head; + int idx; + + idx = evl_get_schedq_weight(q); + head = q->heads + idx; + thread = list_first_entry(head, struct evl_thread, rq_next); + __evl_del_schedq(q, &thread->rq_next, idx); + + return thread; +} + +static struct evl_thread *lookup_fifo_class(struct evl_rq *rq) +{ + struct evl_sched_queue *q = &rq->fifo.runnable; + struct evl_thread *thread; + struct list_head *head; + int idx; + + if (!q->elems) + return NULL; + + /* + * Some scheduling policies may be implemented as variants of + * the core SCHED_FIFO class, sharing its runqueue + * (e.g. SCHED_QUOTA). This means that we have to do some + * cascading to call the right pick handler eventually. + */ + idx = evl_get_schedq_weight(q); + head = q->heads + idx; + + /* + * The active class (i.e. ->sched_class) is the one currently + * queuing the thread, reflecting any priority boost due to + * PI. + */ + thread = list_first_entry(head, struct evl_thread, rq_next); + if (unlikely(thread->sched_class != &evl_sched_fifo)) + return thread->sched_class->sched_pick(rq); + + __evl_del_schedq(q, &thread->rq_next, idx); + + return thread; +} + +#else /* !CONFIG_EVL_SCHED_SCALABLE */ + +static __always_inline +struct evl_thread *lookup_fifo_class(struct evl_rq *rq) +{ + struct evl_sched_queue *q = &rq->fifo.runnable; + struct evl_thread *thread = NULL; + + if (list_empty(&q->head)) + return NULL; + + thread = list_first_entry(&q->head, struct evl_thread, rq_next); + if (unlikely(thread->sched_class != &evl_sched_fifo)) + return thread->sched_class->sched_pick(rq); + + evl_del_schedq(q, thread); + + return thread; +} + +#endif /* CONFIG_EVL_SCHED_SCALABLE */ + +static inline void enter_inband(struct evl_thread *root) +{ +#ifdef CONFIG_EVL_WATCHDOG + evl_stop_timer(&evl_thread_rq(root)->wdtimer); +#endif +} + +static inline void leave_inband(struct evl_thread *root) +{ +#ifdef CONFIG_EVL_WATCHDOG + evl_start_timer(&evl_thread_rq(root)->wdtimer, + evl_abs_timeout(&evl_thread_rq(root)->wdtimer, + get_watchdog_timeout()), + EVL_INFINITE); +#endif +} + +#ifdef CONFIG_SMP +/* oob stalled. */ +static irqreturn_t oob_reschedule_interrupt(int irq, void *dev_id) +{ + trace_evl_reschedule_ipi(this_evl_rq()); + + /* Will reschedule from evl_exit_irq(). */ + + return IRQ_HANDLED; +} +#else +#define oob_reschedule_interrupt NULL +#endif + +static inline void set_next_running(struct evl_rq *rq, + struct evl_thread *next) +{ + next->state &= ~EVL_T_READY; + if (next->state & EVL_T_RRB) + evl_start_timer(&rq->rrbtimer, + evl_abs_timeout(&rq->rrbtimer, next->rrperiod), + EVL_INFINITE); + else + evl_stop_timer(&rq->rrbtimer); +} + +static struct evl_thread *__pick_next_thread(struct evl_rq *rq) +{ + struct evl_sched_class *sched_class; + struct evl_thread *curr = rq->curr; + struct evl_thread *next; + + /* + * We have to switch the current thread out if a blocking + * condition is raised for it. Otherwise, check whether + * preemption is allowed. + */ + if (!(curr->state & (EVL_THREAD_BLOCK_BITS | EVL_T_ZOMBIE))) { + if (evl_preempt_count() > 0) { + evl_set_self_resched(rq); + return curr; + } + /* + * Push the current thread back to the run queue of + * the scheduling class it belongs to, if not yet + * linked to it (EVL_T_READY tells us if it is). + */ + if (!(curr->state & EVL_T_READY)) { + evl_requeue_thread(curr); + curr->state |= EVL_T_READY; + } + } + + /* + * Find the next runnable thread with the highest priority + * amongst all scheduling classes, scanned by decreasing + * weight. We start from the FIFO class which is always on top + * without going through any indirection; if no thread is + * runnable there, poll the lower classes. + */ + next = lookup_fifo_class(rq); + if (likely(next)) + return next; + + for_each_evl_lower_sched_class(sched_class) { + next = sched_class->sched_pick(rq); + if (next) + return next; + } + + return NULL; /* NOT REACHED (idle class). */ +} + +/* rq->curr->lock + rq->lock held, hard irqs off. */ +static struct evl_thread *pick_next_thread(struct evl_rq *rq) +{ + struct oob_mm_state *oob_mm; + struct evl_thread *next; + + for (;;) { + next = __pick_next_thread(rq); + oob_mm = next->oob_mm; + if (unlikely(!oob_mm)) /* Includes the root thread. */ + break; + /* + * Obey any pending request for a ptsync freeze. + * Either we freeze @next before a sigwake event lifts + * EVL_T_PTSYNC, setting EVL_T_PTSTOP, or after in which case + * we already have EVL_T_PTSTOP set so we don't have to + * raise EVL_T_PTSYNC. The basic assumption is that we + * should get SIGSTOP/SIGTRAP for any thread involved. + */ + if (likely(!test_bit(EVL_MM_PTSYNC_BIT, &oob_mm->flags))) + break; /* Fast and most likely path. */ + if (next->info & (EVL_T_PTSTOP|EVL_T_PTSIG|EVL_T_KICKED)) + break; + /* + * NOTE: We hold next->rq->lock by construction, so + * changing next->state is ok despite that we don't + * hold next->lock. This properly serializes with + * evl_kick_thread() which might raise EVL_T_PTSTOP. + */ + next->state |= EVL_T_PTSYNC; + next->state &= ~EVL_T_READY; + } + + set_next_running(rq, next); + + return next; +} + +static __always_inline +void prepare_rq_switch(struct evl_rq *this_rq, + struct evl_thread *prev, struct evl_thread *next) +{ + if (irq_pipeline_debug_locking()) + spin_release(&this_rq->lock.rlock.dep_map, + _THIS_IP_); +#ifdef CONFIG_DEBUG_SPINLOCK + this_rq->lock.rlock.owner = next->altsched.task; +#endif + + trace_evl_switch_context(prev, next); +} + +static __always_inline +void finish_rq_switch(bool inband_tail, unsigned long flags) +{ + struct evl_rq *this_rq = this_evl_rq(); + + trace_evl_switch_tail(this_rq->curr); + + EVL_WARN_ON(CORE, this_rq->curr->state & EVL_THREAD_BLOCK_BITS); + + /* + * Check whether we are completing a transition to the inband + * stage for the current task, i.e.: + * + * irq_work_queue() -> + * IRQ:wake_up_process() -> + * schedule() -> + * back from dovetail_context_switch() + */ + if (likely(!inband_tail)) { + if (irq_pipeline_debug_locking()) + spin_acquire(&this_rq->lock.rlock.dep_map, + 0, 0, _THIS_IP_); + raw_spin_unlock_irqrestore(&this_rq->lock, flags); + } +} + +static __always_inline void finish_rq_switch_from_inband(void) +{ + struct evl_rq *this_rq = this_evl_rq(); + + assert_hard_lock(&this_rq->lock); + + if (irq_pipeline_debug_locking()) + spin_acquire(&this_rq->lock.rlock.dep_map, + 0, 0, _THIS_IP_); + + raw_spin_unlock_irq(&this_rq->lock); +} + +/* hard irqs off. */ +static __always_inline bool test_resched(struct evl_rq *this_rq) +{ + bool need_resched = evl_need_resched(this_rq); + +#ifdef CONFIG_SMP + /* Send resched IPI to remote CPU(s). */ + if (unlikely(!cpumask_empty(&this_rq->resched_cpus))) { + irq_send_oob_ipi(RESCHEDULE_OOB_IPI, &this_rq->resched_cpus); + cpumask_clear(&this_rq->resched_cpus); + this_rq->local_flags &= ~RQ_SCHED; + } +#endif + if (need_resched) + this_rq->flags &= ~RQ_SCHED; + + return need_resched; +} + +/* + * CAUTION: curr->altsched.task may be unsynced and even stale if + * (this_rq->curr == &this_rq->root_thread), since the task logged by + * dovetail_context_switch() may not still be the current one. Always + * use "current" for disambiguating if you intend to refer to the + * running inband task. + */ +void __evl_schedule(void) /* oob or/and hard irqs off (CPU migration-safe) */ +{ + struct evl_rq *this_rq = this_evl_rq(); + struct evl_thread *prev, *next, *curr; + bool leaving_inband, inband_tail; + unsigned long flags; + + if (EVL_WARN_ON_ONCE(CORE, running_inband() && !hard_irqs_disabled())) + return; + + trace_evl_schedule(this_rq); + + flags = hard_local_irq_save(); + + /* + * Check whether we have a pending priority ceiling request to + * commit before putting the current thread to sleep. + * evl_current() may differ from rq->curr only if rq->curr == + * &rq->root_thread. Testing EVL_T_USER eliminates this case since + * a root thread never bears this bit. + */ + curr = this_rq->curr; + /* + * Deferred WCHAN requeuing must be handled prior to + * rescheduling. + */ + EVL_WARN_ON(CORE, curr->info & EVL_T_WCHAN); + + /* + * Priority protection for mutexes is only available to + * applications. Kernel users stick with the priority + * inheritance protocol (see evl_init_kmutex()). + */ + if (curr->state & EVL_T_USER) + evl_commit_monitor_ceiling(); + + /* + * Only holding this_rq->lock is required for test_resched(), + * but we grab curr->lock in advance in order to keep the + * locking order safe from ABBA deadlocking. + */ + raw_spin_lock(&curr->lock); + + /* + * Detect any lingering priority boost which should not be in + * effect anymore. Since this situation is likely to stick, + * warn only once. If that message ever appears, something + * would be really wrong in the PI/PP implementation anyway. + */ + if (IS_ENABLED(CONFIG_EVL_DEBUG_CORE) && + curr->state & EVL_T_BOOST && list_empty(&curr->boosters)) { + raw_spin_unlock(&curr->lock); + EVL_WARN_ON_ONCE(CORE, 1); + raw_spin_lock(&curr->lock); + } + + raw_spin_lock(&this_rq->lock); + + if (unlikely(!test_resched(this_rq))) { + raw_spin_unlock(&this_rq->lock); + raw_spin_unlock_irqrestore(&curr->lock, flags); + return; + } + + next = pick_next_thread(this_rq); + trace_evl_pick_thread(next); + if (next == curr) { + if (unlikely(next->state & EVL_T_ROOT)) { + if (this_rq->local_flags & RQ_TPROXY) + evl_notify_proxy_tick(this_rq); + if (this_rq->local_flags & RQ_TDEFER) + evl_program_local_tick(&evl_mono_clock); + } + raw_spin_unlock(&this_rq->lock); + raw_spin_unlock_irqrestore(&curr->lock, flags); + return; + } + + prev = curr; + this_rq->curr = next; + leaving_inband = false; + + if (prev->state & EVL_T_ROOT) { + leave_inband(prev); + leaving_inband = true; + } else if (next->state & EVL_T_ROOT) { + if (this_rq->local_flags & RQ_TPROXY) + evl_notify_proxy_tick(this_rq); + if (this_rq->local_flags & RQ_TDEFER) + evl_program_local_tick(&evl_mono_clock); + enter_inband(next); + } + + evl_switch_account(this_rq, &next->stat.account); + evl_inc_counter(&next->stat.csw); + raw_spin_unlock(&prev->lock); + + prepare_rq_switch(this_rq, prev, next); + inband_tail = dovetail_context_switch(&prev->altsched, + &next->altsched, leaving_inband); + finish_rq_switch(inband_tail, flags); +} +EXPORT_SYMBOL_GPL(__evl_schedule); + +/* this_rq->lock held, hard irqs off. */ +static void start_ptsync_locked(struct evl_thread *stopper, + struct evl_rq *this_rq) +{ + struct oob_mm_state *oob_mm = stopper->oob_mm; + + if (!test_and_set_bit(EVL_MM_PTSYNC_BIT, &oob_mm->flags)) { +#ifdef CONFIG_SMP + cpumask_copy(&this_rq->resched_cpus, &evl_oob_cpus); + cpumask_clear_cpu(raw_smp_processor_id(), &this_rq->resched_cpus); +#endif + evl_set_self_resched(this_rq); + } +} + +void evl_start_ptsync(struct evl_thread *stopper) +{ + struct evl_rq *this_rq; + unsigned long flags; + + if (EVL_WARN_ON(CORE, !(stopper->state & EVL_T_USER))) + return; + + flags = hard_local_irq_save(); + this_rq = this_evl_rq(); + raw_spin_lock(&this_rq->lock); + start_ptsync_locked(stopper, this_rq); + raw_spin_unlock_irqrestore(&this_rq->lock, flags); +} + +void resume_oob_task(struct task_struct *p) /* inband, oob stage stalled */ +{ + struct evl_thread *thread = evl_thread_from_task(p); + + /* + * Dovetail calls us with hard irqs off, oob stage + * stalled. Clear the stall bit which we don't use for + * protection but keep hard irqs off. + */ + unstall_oob(); + check_cpu_affinity(p); + evl_release_thread(thread, EVL_T_INBAND, 0); + /* + * If EVL_T_PTSTOP is set, pick_next_thread() is not allowed to + * freeze @thread while in flight to the out-of-band stage. + */ + evl_schedule(); + stall_oob(); +} + +int evl_switch_oob(void) +{ + struct evl_thread *curr = evl_current(); + struct task_struct *p = current; + unsigned long flags; + int ret; + + inband_context_only(); + + if (curr == NULL) + return -EPERM; + + if (signal_pending(p)) + return -ERESTARTSYS; + + trace_evl_switch_oob(curr); + + evl_clear_sync_uwindow(curr, EVL_T_INBAND); + + ret = dovetail_leave_inband(); + if (ret) { + evl_test_cancel(); + evl_set_sync_uwindow(curr, EVL_T_INBAND); + return ret; + } + + /* + * On success, dovetail_leave_inband() stalls the oob stage + * before returning to us: clear this stall bit since we don't + * use it for protection but keep hard irqs off. + */ + unstall_oob(); + + /* + * The current task is now running on the out-of-band + * execution stage, scheduled in by the latest call to + * __evl_schedule() on this CPU: we must be holding the + * runqueue lock and hard irqs must be off. + */ + oob_context_only(); + + finish_rq_switch_from_inband(); + + trace_evl_switched_oob(curr); + + /* + * In case check_cpu_affinity() caught us resuming oob from a + * wrong CPU (i.e. outside of the oob set), we have EVL_T_CANCELD + * set. Check and bail out if so. + */ + if (curr->info & EVL_T_CANCELD) + evl_test_cancel(); + + /* + * Since handle_sigwake_event()->evl_kick_thread() won't set + * EVL_T_KICKED unless EVL_T_INBAND is cleared, a signal received + * during the stage transition process might have gone + * unnoticed. Recheck for signals here and raise EVL_T_KICKED if + * some are pending, so that we switch back in-band asap for + * handling them. + */ + if (signal_pending(p)) { + raw_spin_lock_irqsave(&curr->rq->lock, flags); + curr->info |= EVL_T_KICKED; + raw_spin_unlock_irqrestore(&curr->rq->lock, flags); + } + + return 0; +} +EXPORT_SYMBOL_GPL(evl_switch_oob); + +void evl_switch_inband_details(int cause, union evl_value details) +{ + struct evl_thread *curr = evl_current(); + struct evl_rq *this_rq; + bool notify; + + oob_context_only(); + + trace_evl_switch_inband(cause); + + /* + * This is the only location where we may assert EVL_T_INBAND for + * a thread. Basic assumption: switching to the inband stage + * only applies to the current thread running out-of-band on + * this CPU. See caveat about dovetail_leave_oob() below. + */ + hard_local_irq_disable(); + irq_work_queue(&curr->inband_work); + + raw_spin_lock(&curr->lock); + this_rq = curr->rq; + raw_spin_lock(&this_rq->lock); + + if (curr->state & EVL_T_READY) { + evl_dequeue_thread(curr); + curr->state &= ~EVL_T_READY; + } + + curr->state |= EVL_T_INBAND; + curr->local_info &= ~EVL_T_SYSRST; + notify = curr->state & EVL_T_USER && cause > EVL_HMDIAG_NONE; + + /* + * If we are initiating the ptsync sequence on breakpoint or + * SIGSTOP/SIGINT is pending, do not send any HM notification + * since switching in-band is ok. + */ + if (cause == EVL_HMDIAG_TRAP) { + curr->info |= EVL_T_PTSTOP; + curr->info &= ~EVL_T_PTJOIN; + start_ptsync_locked(curr, this_rq); + } else if (curr->info & EVL_T_PTSIG) { + curr->info &= ~EVL_T_PTSIG; + notify = false; + } + + curr->info &= ~EVL_THREAD_INFO_MASK; + + evl_set_resched(this_rq); + + raw_spin_unlock(&this_rq->lock); + raw_spin_unlock(&curr->lock); + + /* + * CAVEAT: dovetail_leave_oob() must run _before_ the in-band + * kernel is allowed to take interrupts again, so that + * try_to_wake_up() does not block the wake up request for the + * switching thread as a result of testing + * task_is_off_stage(). + */ + dovetail_leave_oob(); + + __evl_schedule(); + /* + * this_rq()->lock was released when the root thread resumed + * from __evl_schedule() (i.e. inband_tail path). + */ + hard_local_irq_enable(); + dovetail_resume_inband(); + + /* + * Basic sanity check after an expected transition to in-band + * context. + */ + EVL_WARN(CORE, !running_inband(), + "evl_switch_inband() failed for thread %s[%d]", + curr->name, evl_get_inband_pid(curr)); + + /* Account for switch to in-band context. */ + evl_inc_counter(&curr->stat.isw); + + trace_evl_switched_inband(curr); + + /* + * When switching to in-band context, we check for propagating + * the current EVL schedparams that might have been set for + * current while running in OOB context. + * + * CAUTION: This obviously won't update the schedparams cached + * by the glibc for the caller in user-space, but this is the + * deal: we don't switch threads which issue + * EVL_THRIOC_SET_SCHEDPARAM to in-band mode, but then only + * the kernel side will be aware of the change, and glibc + * might cache obsolete information. + */ + evl_propagate_schedparam_change(curr); + + if (notify) { + /* + * Help debugging spurious stage switches by sending + * an HM event. + */ + if (curr->state & EVL_T_WOSS) + evl_notify_thread(curr, cause, details); + + /* May check for locking inconsistency too. */ + if (curr->state & EVL_T_WOLI) + evl_check_no_mutex(); + } + + /* @curr is now running inband. */ + evl_sync_uwindow(curr); +} +EXPORT_SYMBOL_GPL(evl_switch_inband_details); + +void evl_switch_inband(int cause) +{ + evl_switch_inband_details(cause, evl_nil); +} +EXPORT_SYMBOL_GPL(evl_switch_inband); + +struct evl_sched_class * +evl_find_sched_class(union evl_sched_param *param, + const struct evl_sched_attrs *attrs, + ktime_t *tslice_r) +{ + struct evl_sched_class *sched_class; + int prio, policy; + ktime_t tslice; + + policy = attrs->sched_policy; + prio = attrs->sched_priority; + tslice = EVL_INFINITE; + sched_class = &evl_sched_fifo; + param->fifo.prio = prio; + + switch (policy) { + case SCHED_NORMAL: + if (prio) + return ERR_PTR(-EINVAL); + fallthrough; + case SCHED_WEAK: + if (prio < EVL_WEAK_MIN_PRIO || prio > EVL_WEAK_MAX_PRIO) + return ERR_PTR(-EINVAL); + param->weak.prio = prio; + sched_class = &evl_sched_weak; + break; + case SCHED_RR: + /* if unspecified, use current one. */ + tslice = u_timespec_to_ktime(attrs->sched_rr_quantum); + if (timeout_infinite(tslice) && tslice_r) + tslice = *tslice_r; + fallthrough; + case SCHED_FIFO: + /* + * This routine handles requests submitted from + * user-space exclusively, so a SCHED_FIFO priority + * must be in the [FIFO_MIN..FIFO_MAX] range. + */ + if (prio < EVL_FIFO_MIN_PRIO || prio > EVL_FIFO_MAX_PRIO) + return ERR_PTR(-EINVAL); + break; + case SCHED_QUOTA: +#ifdef CONFIG_EVL_SCHED_QUOTA + param->quota.prio = attrs->sched_priority; + param->quota.tgid = attrs->sched_quota_group; + sched_class = &evl_sched_quota; + break; +#else + return ERR_PTR(-EOPNOTSUPP); +#endif + case SCHED_TP: +#ifdef CONFIG_EVL_SCHED_TP + param->tp.prio = attrs->sched_priority; + param->tp.ptid = attrs->sched_tp_partition; + sched_class = &evl_sched_tp; + break; +#else + return ERR_PTR(-EOPNOTSUPP); +#endif + default: + return ERR_PTR(-EINVAL); + } + + *tslice_r = tslice; + + return sched_class; +} + +#ifdef CONFIG_TRACING + +notrace const char *evl_trace_sched_attrs(struct trace_seq *p, + struct evl_sched_attrs *attrs) +{ + const char *ret = trace_seq_buffer_ptr(p); + + switch (attrs->sched_policy) { + case SCHED_QUOTA: + trace_seq_printf(p, "priority=%d, group=%d", + attrs->sched_priority, + attrs->sched_quota_group); + break; + case SCHED_TP: + trace_seq_printf(p, "priority=%d, partition=%d", + attrs->sched_priority, + attrs->sched_tp_partition); + case SCHED_NORMAL: + break; + case SCHED_RR: + case SCHED_FIFO: + case SCHED_WEAK: + default: + trace_seq_printf(p, "priority=%d", attrs->sched_priority); + break; + } + trace_seq_putc(p, '\0'); + + return ret; +} + +#endif /* CONFIG_TRACING */ + +/* in-band stage, hard_irqs_disabled() */ +bool irq_cpuidle_control(struct cpuidle_device *dev, + struct cpuidle_state *state) +{ + /* + * Deny entering sleep state if this entails stopping the + * timer (i.e. C3STOP misfeature). + */ + if (state && (state->flags & CPUIDLE_FLAG_TIMER_STOP)) + return false; + + return true; +} + +int __init evl_init_sched(void) +{ + struct evl_rq *rq; + int ret, cpu; + + register_classes(); + + for_each_online_cpu(cpu) { + rq = &per_cpu(evl_runqueues, cpu); + init_rq(rq, cpu); + } + + /* See comment about hooking TIMER_OOB_IPI. */ + if (IS_ENABLED(CONFIG_SMP) && num_possible_cpus() > 1) { + ret = __request_percpu_irq(RESCHEDULE_OOB_IPI, + oob_reschedule_interrupt, + IRQF_OOB, + "EVL reschedule", + &evl_machine_cpudata); + if (ret) + goto cleanup_rq; + } + + return 0; + +cleanup_rq: + for_each_online_cpu(cpu) { + rq = evl_cpu_rq(cpu); + destroy_rq(rq); + } + + return ret; +} + +void __init evl_cleanup_sched(void) +{ + struct evl_rq *rq; + int cpu; + + if (IS_ENABLED(CONFIG_SMP) && num_possible_cpus() > 1) + free_percpu_irq(RESCHEDULE_OOB_IPI, &evl_machine_cpudata); + + for_each_online_cpu(cpu) { + rq = evl_cpu_rq(cpu); + destroy_rq(rq); + } +} diff --git a/kernel/evl/sched/fifo.c b/kernel/evl/sched/fifo.c new file mode 100644 index 000000000..57e0a0797 --- /dev/null +++ b/kernel/evl/sched/fifo.c @@ -0,0 +1,81 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Derived from Xenomai Cobalt, https://xenomai.org/ + * Copyright (C) 2008, 2018 Philippe Gerum + */ + +#include + +static void evl_fifo_init(struct evl_rq *rq) +{ + evl_init_schedq(&rq->fifo.runnable); +} + +static void evl_fifo_yield(struct evl_thread *thread) +{ + evl_putback_thread(thread); +} + +static int evl_fifo_chkparam(struct evl_thread *thread, + const union evl_sched_param *p) +{ + return __evl_chk_fifo_schedparam(thread, p); +} + +static bool evl_fifo_setparam(struct evl_thread *thread, + const union evl_sched_param *p) +{ + return __evl_set_fifo_schedparam(thread, p); +} + +static void evl_fifo_getparam(struct evl_thread *thread, + union evl_sched_param *p) +{ + __evl_get_fifo_schedparam(thread, p); +} + +static void evl_fifo_trackprio(struct evl_thread *thread, + const union evl_sched_param *p) +{ + __evl_track_fifo_priority(thread, p); +} + +static void evl_fifo_ceilprio(struct evl_thread *thread, int prio) +{ + __evl_ceil_fifo_priority(thread, prio); +} + +static const char *evl_fifo_name(struct evl_thread *thread) +{ + if (thread->state & EVL_T_RRB) + return "rr"; + + return "fifo"; +} + +static ssize_t evl_fifo_show(struct evl_thread *thread, + char *buf, ssize_t count) +{ + if (thread->state & EVL_T_RRB) + return snprintf(buf, count, "%Ld\n", + ktime_to_ns(thread->rrperiod)); + return 0; +} + +struct evl_sched_class evl_sched_fifo = { + .sched_init = evl_fifo_init, + .sched_pick = NULL, /* not used (see __pick_next_thread()) */ + .sched_yield = evl_fifo_yield, + .sched_chkparam = evl_fifo_chkparam, + .sched_setparam = evl_fifo_setparam, + .sched_trackprio = evl_fifo_trackprio, + .sched_ceilprio = evl_fifo_ceilprio, + .sched_getparam = evl_fifo_getparam, + .sched_name = evl_fifo_name, + .sched_show = evl_fifo_show, + .weight = EVL_CLASS_WEIGHT(4), + .policy = SCHED_FIFO, + .name = "fifo" +}; +EXPORT_SYMBOL_GPL(evl_sched_fifo); diff --git a/kernel/evl/sched/idle.c b/kernel/evl/sched/idle.c new file mode 100644 index 000000000..11b156a7f --- /dev/null +++ b/kernel/evl/sched/idle.c @@ -0,0 +1,53 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Derived from Xenomai Cobalt, https://xenomai.org/ + * Copyright (C) 2008, 2018 Philippe Gerum + */ + +#include + +static struct evl_thread *evl_idle_pick(struct evl_rq *rq) +{ + return &rq->root_thread; +} + +static bool evl_idle_setparam(struct evl_thread *thread, + const union evl_sched_param *p) +{ + return __evl_set_idle_schedparam(thread, p); +} + +static void evl_idle_getparam(struct evl_thread *thread, + union evl_sched_param *p) +{ + __evl_get_idle_schedparam(thread, p); +} + +static void evl_idle_trackprio(struct evl_thread *thread, + const union evl_sched_param *p) +{ + __evl_track_idle_priority(thread, p); +} + +static void evl_idle_ceilprio(struct evl_thread *thread, int prio) +{ + __evl_ceil_idle_priority(thread, prio); +} + +static const char *evl_idle_name(struct evl_thread *thread) +{ + return "idle"; +} + +struct evl_sched_class evl_sched_idle = { + .sched_pick = evl_idle_pick, + .sched_setparam = evl_idle_setparam, + .sched_getparam = evl_idle_getparam, + .sched_trackprio = evl_idle_trackprio, + .sched_ceilprio = evl_idle_ceilprio, + .sched_name = evl_idle_name, + .weight = EVL_CLASS_WEIGHT(0), + .policy = SCHED_IDLE, + .name = "idle" +}; diff --git a/kernel/evl/sched/quota.c b/kernel/evl/sched/quota.c new file mode 100644 index 000000000..70b64cb4e --- /dev/null +++ b/kernel/evl/sched/quota.c @@ -0,0 +1,804 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Derived from Xenomai Cobalt, https://xenomai.org/ + * Copyright (C) 2013, 2018 Philippe Gerum + */ + +#include +#include +#include +#include +#include + +/* + * With this policy, each per-CPU runqueue maintains a list of active + * thread groups for the sched_fifo class. + * + * Each time a thread is picked from the runqueue, we check whether we + * still have budget for running it, looking at the group it belongs + * to. If so, a timer is armed to elapse when that group has no more + * budget, would the incoming thread run unpreempted until then + * (i.e. evl_quota->limit_timer). + * + * Otherwise, if no budget remains in the group for running the + * candidate thread, we move the latter to a local expiry queue + * maintained by the group. This process is done on the fly as we pull + * from the runqueue. + * + * Updating the remaining budget is done each time the EVL core asks + * for replacing the current thread with the next runnable one, + * i.e. evl_quota_pick(). There we charge the elapsed run time of the + * outgoing thread to the relevant group, and conversely, we check + * whether the incoming thread has budget. + * + * Finally, a per-CPU timer (evl_quota->refill_timer) periodically + * ticks in the background, in accordance to the defined quota + * interval. Thread group budgets get replenished by its handler in + * accordance to their respective share, pushing all expired threads + * back to the run queue in the same move. + * + * NOTE: since the core logic enforcing the budget entirely happens in + * evl_quota_pick(), applying a budget change can be done as simply as + * forcing the rescheduling procedure to be invoked asap. As a result + * of this, the EVL core will ask for the next thread to run, which + * means calling evl_quota_pick() eventually. + * + * CAUTION: evl_quota_group->nr_active does count both the threads + * from that group linked to the sched_fifo runqueue, _and_ the + * threads moved to the local expiry queue. As a matter of fact, the + * expired threads - those for which we consumed all the per-group + * budget - are still seen as runnable (i.e. not blocked/suspended) by + * the EVL core. This only means that the SCHED_QUOTA policy won't + * pick them until the corresponding budget is replenished. + */ + +#define MAX_QUOTA_GROUPS 1024 + +static ktime_t quota_period = 1000000000UL; /* 1s */ + +static DECLARE_BITMAP(group_map, MAX_QUOTA_GROUPS); + +static LIST_HEAD(group_list); + +static inline bool thread_on_quota(struct evl_thread *thread, + struct evl_quota_group *tg) +{ + /* + * Check whether @thread is running on some CPU, and belongs + * to quota group @tg. + */ + return thread->quota == tg && + !(thread->state & (EVL_T_READY|EVL_THREAD_BLOCK_BITS)); +} + +static inline bool group_is_active(struct evl_quota_group *tg) +{ + if (tg->nr_active) + return true; + + /* + * EVL_T_READY set for @thread would mean that it is linked to the + * runqueue, in which case tg->nr_active already accounted for + * it. + */ + return thread_on_quota(tg->rq->curr, tg); +} + +static inline void replenish_budget(struct evl_sched_quota *qs, + struct evl_quota_group *tg) +{ + ktime_t budget, credit; + + if (tg->quota == tg->quota_peak) { + /* + * Fast path: we don't accumulate runtime credit. + * This includes groups with no runtime limit + * (i.e. quota off: quota >= period && quota == peak). + */ + tg->run_budget = tg->quota; + return; + } + + /* + * We have to deal with runtime credit accumulation, as the + * group may consume more than its base quota during a single + * interval, up to a peak duration though (not to monopolize + * the CPU). + * + * - In the simplest case, a group is allotted a new full + * budget plus the unconsumed portion of the previous budget, + * provided the sum does not exceed the peak quota. + * + * - When there is too much budget for a single interval + * (i.e. above peak quota), we spread the extra time over + * multiple intervals through a credit accumulation mechanism. + * + * - The accumulated credit is dropped whenever a group has no + * runnable threads. + */ + if (!group_is_active(tg)) { + /* Drop accumulated credit. */ + tg->run_credit = 0; + tg->run_budget = tg->quota; + return; + } + + budget = ktime_add(tg->run_budget, tg->quota); + if (budget > tg->quota_peak) { + /* Too much budget, spread it over intervals. */ + tg->run_credit = + ktime_add(tg->run_credit, + ktime_sub(budget, tg->quota_peak)); + tg->run_budget = tg->quota_peak; + } else if (tg->run_credit) { + credit = ktime_sub(tg->quota_peak, budget); + /* Consume the accumulated credit. */ + if (tg->run_credit >= credit) + tg->run_credit = + ktime_sub(tg->run_credit, credit); + else { + credit = tg->run_credit; + tg->run_credit = 0; + } + /* Allot extended budget, limited to peak quota. */ + tg->run_budget = ktime_add(budget, credit); + } else + /* No credit, budget was below peak quota. */ + tg->run_budget = budget; +} + +static void quota_refill_handler(struct evl_timer *timer) /* oob stage stalled */ +{ + struct evl_quota_group *tg; + struct evl_thread *thread, *tmp; + struct evl_sched_quota *qs; + struct evl_rq *rq; + + qs = container_of(timer, struct evl_sched_quota, refill_timer); + rq = container_of(qs, struct evl_rq, quota); + + raw_spin_lock(&rq->lock); + + list_for_each_entry(tg, &qs->groups, next) { + /* Allot a new runtime budget for the group. */ + replenish_budget(qs, tg); + + if (tg->run_budget == 0 || list_empty(&tg->expired)) + continue; + /* + * For each group living on this CPU, move all expired + * threads back to the runqueue. Since those threads + * were moved out of the runqueue as we were + * considering them for execution, we push them back + * in LIFO order to their respective priority group. + * The expiry queue is FIFO to keep ordering right + * among expired threads. + */ + list_for_each_entry_safe_reverse(thread, tmp, + &tg->expired, quota_expired) { + list_del_init(&thread->quota_expired); + evl_add_schedq(&rq->fifo.runnable, thread); + } + } + + evl_set_self_resched(evl_get_timer_rq(timer)); + + raw_spin_unlock(&rq->lock); +} + +static void quota_limit_handler(struct evl_timer *timer) /* oob stage stalled */ +{ + struct evl_rq *rq; + + rq = container_of(timer, struct evl_rq, quota.limit_timer); + /* + * Force a rescheduling on the return path of the current + * interrupt, so that the budget is re-evaluated for the + * current group in evl_quota_pick(). + */ + raw_spin_lock(&rq->lock); + evl_set_self_resched(rq); + raw_spin_unlock(&rq->lock); +} + +static int quota_sum_all(struct evl_sched_quota *qs) +{ + struct evl_quota_group *tg; + int sum; + + if (list_empty(&qs->groups)) + return 0; + + sum = 0; + list_for_each_entry(tg, &qs->groups, next) + sum += tg->quota_percent; + + return sum; +} + +static void quota_init(struct evl_rq *rq) +{ + struct evl_sched_quota *qs = &rq->quota; + + qs->period = quota_period; + INIT_LIST_HEAD(&qs->groups); + + evl_init_timer_on_rq(&qs->refill_timer, + &evl_mono_clock, quota_refill_handler, rq, + EVL_TIMER_IGRAVITY); + evl_set_timer_name(&qs->refill_timer, "[quota-refill]"); + + evl_init_timer_on_rq(&qs->limit_timer, + &evl_mono_clock, quota_limit_handler, rq, + EVL_TIMER_IGRAVITY); + evl_set_timer_name(&qs->limit_timer, "[quota-limit]"); +} + +static bool quota_setparam(struct evl_thread *thread, + const union evl_sched_param *p) +{ + struct evl_quota_group *tg; + struct evl_sched_quota *qs; + bool effective; + + thread->state &= ~EVL_T_WEAK; + effective = evl_set_effective_thread_priority(thread, p->quota.prio); + + qs = &thread->rq->quota; + list_for_each_entry(tg, &qs->groups, next) { + if (tg->tgid != p->quota.tgid) + continue; + if (thread->quota) { + /* Dequeued earlier by our caller. */ + list_del(&thread->quota_next); + thread->quota->nr_threads--; + } + thread->quota = tg; + list_add(&thread->quota_next, &tg->members); + tg->nr_threads++; + return effective; + } + + return false; /* not reached. */ +} + +static void quota_getparam(struct evl_thread *thread, + union evl_sched_param *p) +{ + p->quota.prio = thread->cprio; + p->quota.tgid = thread->quota->tgid; +} + +static void quota_trackprio(struct evl_thread *thread, + const union evl_sched_param *p) +{ + if (p) { + /* We should not cross groups during PI boost. */ + EVL_WARN_ON(CORE, + thread->base_class == &evl_sched_quota && + thread->quota->tgid != p->quota.tgid); + thread->cprio = p->quota.prio; + } else { + thread->cprio = thread->bprio; + } +} + +static void quota_ceilprio(struct evl_thread *thread, int prio) +{ + if (prio > EVL_QUOTA_MAX_PRIO) + prio = EVL_QUOTA_MAX_PRIO; + + thread->cprio = prio; +} + +static int quota_chkparam(struct evl_thread *thread, + const union evl_sched_param *p) +{ + struct evl_quota_group *tg; + struct evl_sched_quota *qs; + int tgid; + + if (p->quota.prio < EVL_QUOTA_MIN_PRIO || + p->quota.prio > EVL_QUOTA_MAX_PRIO) + return -EINVAL; + + tgid = p->quota.tgid; + if (tgid < 0 || tgid >= MAX_QUOTA_GROUPS) + return -EINVAL; + + /* + * The group must be managed on the same CPU the thread + * currently runs on. + */ + qs = &thread->rq->quota; + list_for_each_entry(tg, &qs->groups, next) { + if (tg->tgid == tgid) + return 0; + } + + /* + * If that group exists nevertheless, we give userland a + * specific error code. + */ + if (test_bit(tgid, group_map)) + return -EPERM; + + return -EINVAL; +} + +static void quota_forget(struct evl_thread *thread) +{ + thread->quota->nr_threads--; + EVL_WARN_ON_ONCE(CORE, thread->quota->nr_threads < 0); + list_del(&thread->quota_next); + thread->quota = NULL; +} + +static void quota_kick(struct evl_thread *thread) +{ + struct evl_quota_group *tg = thread->quota; + struct evl_rq *rq = thread->rq; + + /* + * Allow a kicked thread to be elected for running until it + * switches to in-band context, even if the group it belongs + * to lacks runtime budget. + */ + if (tg->run_budget == 0 && !list_empty(&thread->quota_expired)) { + list_del_init(&thread->quota_expired); + evl_add_schedq_tail(&rq->fifo.runnable, thread); + } +} + +static inline int thread_is_runnable(struct evl_thread *thread) +{ + return thread->quota->run_budget > 0 || (thread->info & EVL_T_KICKED); +} + +static void quota_enqueue(struct evl_thread *thread) +{ + struct evl_quota_group *tg = thread->quota; + struct evl_rq *rq = thread->rq; + + if (!thread_is_runnable(thread)) + list_add_tail(&thread->quota_expired, &tg->expired); + else + evl_add_schedq_tail(&rq->fifo.runnable, thread); + + tg->nr_active++; +} + +static void quota_dequeue(struct evl_thread *thread) +{ + struct evl_quota_group *tg = thread->quota; + struct evl_rq *rq = thread->rq; + + if (!list_empty(&thread->quota_expired)) + list_del_init(&thread->quota_expired); + else + evl_del_schedq(&rq->fifo.runnable, thread); + + tg->nr_active--; +} + +static void quota_requeue(struct evl_thread *thread) +{ + struct evl_quota_group *tg = thread->quota; + struct evl_rq *rq = thread->rq; + + if (!thread_is_runnable(thread)) + list_add(&thread->quota_expired, &tg->expired); + else + evl_add_schedq(&rq->fifo.runnable, thread); + + tg->nr_active++; +} + +static struct evl_thread *quota_pick(struct evl_rq *rq) +{ + struct evl_thread *next, *curr = rq->curr; + struct evl_sched_quota *qs = &rq->quota; + struct evl_quota_group *otg, *tg; + ktime_t now, elapsed; + + now = evl_read_clock(&evl_mono_clock); + otg = curr->quota; + if (otg == NULL) + goto pick; + /* + * Charge the time consumed by the outgoing thread to the + * group it belongs to. + */ + elapsed = ktime_sub(now, otg->run_start); + if (elapsed < otg->run_budget) + otg->run_budget = ktime_sub(otg->run_budget, elapsed); + else + otg->run_budget = 0; +pick: + next = evl_get_schedq(&rq->fifo.runnable); + if (next == NULL) { + evl_stop_timer(&qs->limit_timer); + return NULL; + } + + /* + * As we basically piggyback on the SCHED_FIFO runqueue, make + * sure to detect non-quota threads. + */ + tg = next->quota; + if (tg == NULL) + return next; + + tg->run_start = now; + + /* + * Don't consider budget if kicked, we have to allow this + * thread to run until it eventually switches to in-band + * context. + */ + if (next->info & EVL_T_KICKED) { + evl_stop_timer(&qs->limit_timer); + goto out; + } + + if (ktime_to_ns(tg->run_budget) == 0) { + /* Flush expired group members as we go. */ + list_add_tail(&next->quota_expired, &tg->expired); + goto pick; + } + + if (otg == tg && evl_timer_is_running(&qs->limit_timer)) + /* Same group, leave the running timer untouched. */ + goto out; + + /* Arm limit timer for the new running group. */ + evl_start_timer(&qs->limit_timer, + ktime_add(now, tg->run_budget), + EVL_INFINITE); +out: + tg->nr_active--; + + return next; +} + +static void quota_migrate(struct evl_thread *thread, struct evl_rq *rq) +{ + union evl_sched_param param; + /* + * Runtime quota groups are defined per-CPU, so leaving the + * current CPU means exiting the group. We do this by moving + * the target thread to the FIFO class. + */ + param.fifo.prio = thread->cprio; + evl_set_thread_schedparam_locked(thread, &evl_sched_fifo, ¶m); +} + +static const char *quota_name(struct evl_thread *thread) +{ + return "quota"; +} + +static ssize_t quota_show(struct evl_thread *thread, + char *buf, ssize_t count) +{ + return snprintf(buf, count, "%d\n", + thread->quota->tgid); +} + +static int quota_create_group(struct evl_quota_group *tg, + struct evl_rq *rq, + int *quota_sum_r) +{ + int tgid, nr_groups = MAX_QUOTA_GROUPS; + struct evl_sched_quota *qs = &rq->quota; + + assert_hard_lock(&rq->lock); + + tgid = find_first_zero_bit(group_map, nr_groups); + if (tgid >= nr_groups) + return -EAGAIN; + + __set_bit(tgid, group_map); + tg->tgid = tgid; + tg->rq = rq; + tg->run_budget = qs->period; + tg->run_credit = 0; + tg->quota_percent = 100; + tg->quota_peak_percent = 100; + tg->quota = qs->period; + tg->quota_peak = qs->period; + tg->nr_active = 0; + tg->nr_threads = 0; + INIT_LIST_HEAD(&tg->members); + INIT_LIST_HEAD(&tg->expired); + + if (list_empty(&qs->groups)) + evl_start_timer(&qs->refill_timer, + evl_abs_timeout(&qs->refill_timer, qs->period), + qs->period); + + list_add(&tg->next, &qs->groups); + *quota_sum_r = quota_sum_all(qs); + + return 0; +} + +static int quota_destroy_group(struct evl_quota_group *tg, + bool force, unsigned long flags, + int *quota_sum_r) +{ + struct evl_rq *rq = tg->rq; + struct evl_sched_quota *qs = &rq->quota; + union evl_sched_param param; + struct evl_thread *thread; + + assert_hard_lock(&rq->lock); + + if (!list_empty(&tg->members) && !force) + return -EBUSY; + + /* + * Unregister the group before we drop rq->lock. As a result, + * it won't accept threads anymore while we are busy moving + * the current members to the fifo class, and concurrent + * evl_quota_remove requests would receive -EINVAL. + */ + __clear_bit(tg->tgid, group_map); + list_del(&tg->next); + + if (list_empty(&qs->groups)) + evl_stop_timer(&qs->refill_timer); + + /* + * Move group members to the fifo class. Since the correct + * locking order is thread->lock => rq->lock but we already + * hold rq->lock on entry, we do a trylock dance to prevent an + * ABBA issue. No livelock is possible since we unregistered + * that group already, so &tg->members can only be depleted + * (by this loop specifically). + */ + + while (!list_empty(&tg->members)) { + thread = list_first_entry(&tg->members, struct evl_thread, + quota_next); + param.fifo.prio = thread->cprio; + if (raw_spin_trylock(&thread->lock)) { + evl_set_thread_schedparam_locked(thread, + &evl_sched_fifo, ¶m); + raw_spin_unlock(&thread->lock); + } + raw_spin_unlock_irqrestore(&rq->lock, flags); + cpu_relax(); + raw_spin_lock_irqsave(&rq->lock, flags); + } + + *quota_sum_r = quota_sum_all(qs); + + return 0; +} + +static void quota_set_limit(struct evl_quota_group *tg, + int quota_percent, int quota_peak_percent, + int *quota_sum_r) +{ + struct evl_rq *rq = tg->rq; + struct evl_thread *thread, *tmp, *curr = rq->curr; + struct evl_sched_quota *qs = &rq->quota; + ktime_t now, elapsed, consumed; + ktime_t old_quota = tg->quota; + u64 n; + + assert_hard_lock(&rq->lock); + + if (quota_percent < 0 || quota_percent > 100) { /* Quota off. */ + quota_percent = 100; + tg->quota = qs->period; + } else { + n = qs->period * quota_percent; + do_div(n, 100); + tg->quota = n; + } + + if (quota_peak_percent < quota_percent) + quota_peak_percent = quota_percent; + + if (quota_peak_percent < 0 || quota_peak_percent > 100) { + quota_peak_percent = 100; + tg->quota_peak = qs->period; + } else { + n = qs->period * quota_peak_percent; + do_div(n, 100); + tg->quota_peak = n; + } + + tg->quota_percent = quota_percent; + tg->quota_peak_percent = quota_peak_percent; + + if (thread_on_quota(curr, tg)) { + now = evl_read_clock(&evl_mono_clock); + + elapsed = now - tg->run_start; + if (elapsed < tg->run_budget) + tg->run_budget -= elapsed; + else + tg->run_budget = 0; + + tg->run_start = now; + evl_stop_timer(&qs->limit_timer); + } + + if (tg->run_budget <= old_quota) + consumed = old_quota - tg->run_budget; + else + consumed = 0; + + if (tg->quota >= consumed) + tg->run_budget = tg->quota - consumed; + else + tg->run_budget = 0; + + tg->run_credit = 0; /* Drop accumulated credit. */ + + *quota_sum_r = quota_sum_all(qs); + + if (tg->run_budget > 0) { + list_for_each_entry_safe_reverse(thread, tmp, &tg->expired, + quota_expired) { + list_del_init(&thread->quota_expired); + evl_add_schedq(&rq->fifo.runnable, thread); + } + } + + /* + * Apply the new budget immediately, in case a member of this + * group is currently running. + */ + evl_set_resched(rq); +} + +static struct evl_quota_group * +find_quota_group(struct evl_rq *rq, int tgid) +{ + struct evl_quota_group *tg; + + assert_hard_lock(&rq->lock); + + /* Quick check using the global id. map first. */ + if (!test_bit(tgid, group_map)) + return NULL; + + /* + * The group does exist, we need to check whether it is + * attached to the given runqueue. + */ + if (list_empty(&rq->quota.groups)) + return NULL; + + list_for_each_entry(tg, &rq->quota.groups, next) { + if (tg->tgid == tgid) + return tg; + } + + return NULL; +} + +static ssize_t quota_control(int cpu, union evl_sched_ctlparam *ctlp, + union evl_sched_ctlinfo *infp) +{ + struct evl_quota_ctlparam *pq = &ctlp->quota; + struct evl_quota_ctlinfo *iq = &infp->quota; + struct evl_sched_group *group; + struct evl_quota_group *tg; + unsigned long flags; + int ret, quota_sum; + struct evl_rq *rq; + + if (cpu < 0 || !cpu_present(cpu) || !is_threading_cpu(cpu)) + return -EINVAL; + + switch (pq->op) { + case evl_quota_add: + group = evl_alloc(sizeof(*group)); + if (group == NULL) + return -ENOMEM; + tg = &group->quota; + rq = evl_cpu_rq(cpu); + raw_spin_lock_irqsave(&rq->lock, flags); + ret = quota_create_group(tg, rq, "a_sum); + if (ret) { + raw_spin_unlock_irqrestore(&rq->lock, flags); + evl_free(group); + return ret; + } + list_add(&group->next, &group_list); + break; + case evl_quota_remove: + case evl_quota_force_remove: + rq = evl_cpu_rq(cpu); + raw_spin_lock_irqsave(&rq->lock, flags); + tg = find_quota_group(rq, pq->u.remove.tgid); + if (tg == NULL) + goto bad_tgid; + group = container_of(tg, struct evl_sched_group, quota); + ret = quota_destroy_group(tg, + pq->op == evl_quota_force_remove, + flags, + "a_sum); + if (ret) { + raw_spin_unlock_irqrestore(&rq->lock, flags); + return ret; + } + list_del(&group->next); + raw_spin_unlock_irqrestore(&rq->lock, flags); + evl_free(group); + goto done; + case evl_quota_set: + rq = evl_cpu_rq(cpu); + raw_spin_lock_irqsave(&rq->lock, flags); + tg = find_quota_group(rq, pq->u.set.tgid); + if (tg == NULL) + goto bad_tgid; + group = container_of(tg, struct evl_sched_group, quota); + quota_set_limit(tg, pq->u.set.quota, pq->u.set.quota_peak, + "a_sum); + break; + case evl_quota_get: + rq = evl_cpu_rq(cpu); + raw_spin_lock_irqsave(&rq->lock, flags); + tg = find_quota_group(rq, pq->u.get.tgid); + if (tg == NULL) + goto bad_tgid; + quota_sum = quota_sum_all(&rq->quota); + break; + default: + return -EINVAL; + } + + iq->tgid = tg->tgid; + iq->quota = tg->quota_percent; + iq->quota_peak = tg->quota_peak_percent; + raw_spin_unlock_irqrestore(&rq->lock, flags); + iq->quota_sum = quota_sum; +done: + evl_schedule(); + + return sizeof(*iq); +bad_tgid: + raw_spin_unlock_irqrestore(&rq->lock, flags); + + return -EINVAL; +} + +void evl_set_quota_period(ktime_t period) +{ + quota_period = period; +} + +ktime_t evl_get_quota_period(void) +{ + return quota_period; +} + +struct evl_sched_class evl_sched_quota = { + .sched_init = quota_init, + .sched_enqueue = quota_enqueue, + .sched_dequeue = quota_dequeue, + .sched_requeue = quota_requeue, + .sched_pick = quota_pick, + .sched_migrate = quota_migrate, + .sched_chkparam = quota_chkparam, + .sched_setparam = quota_setparam, + .sched_getparam = quota_getparam, + .sched_trackprio = quota_trackprio, + .sched_ceilprio = quota_ceilprio, + .sched_forget = quota_forget, + .sched_kick = quota_kick, + .sched_name = quota_name, + .sched_show = quota_show, + .sched_control = quota_control, + .weight = EVL_CLASS_WEIGHT(2), + .policy = SCHED_QUOTA, + .name = "quota" +}; +EXPORT_SYMBOL_GPL(evl_sched_quota); diff --git a/kernel/evl/sched/tp.c b/kernel/evl/sched/tp.c new file mode 100644 index 000000000..a4054266e --- /dev/null +++ b/kernel/evl/sched/tp.c @@ -0,0 +1,487 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Derived from Xenomai Cobalt, https://xenomai.org/ + * Copyright (C) 2008, 2018 Philippe Gerum + */ + +#include +#include +#include +#include + +static void tp_schedule_next(struct evl_sched_tp *tp) +{ + struct evl_tp_window *w; + struct evl_rq *rq; + ktime_t t, now; + int p_next; + + rq = container_of(tp, struct evl_rq, tp); + assert_hard_lock(&rq->lock); + + /* + * Switch to the next partition. Time holes in a global time + * frame are defined as partition windows assigned to part# + * -1, in which case the (always empty) idle queue will be + * polled for runnable threads. Therefore, we may assume that + * a window begins immediately after the previous one ends, + * which simplifies the implementation a lot. + */ + w = &tp->gps->pwins[tp->wnext]; + p_next = w->w_part; + tp->tps = p_next < 0 ? &tp->idle : &tp->partitions[p_next]; + + /* Schedule tick to advance to the next window. */ + tp->wnext = (tp->wnext + 1) % tp->gps->pwin_nr; + w = &tp->gps->pwins[tp->wnext]; + t = ktime_add(tp->tf_start, w->w_offset); + + /* + * If we are late, make sure to remain within the bounds of a + * valid time frame before advancing to the next + * window. Otherwise, fix up by advancing to the next time + * frame immediately. + */ + for (;;) { + now = evl_read_clock(&evl_mono_clock); + if (ktime_compare(now, t) <= 0) + break; + t = ktime_add(tp->tf_start, tp->gps->tf_duration); + tp->tf_start = t; + tp->wnext = 0; + } + + evl_start_timer(&tp->tf_timer, t, EVL_INFINITE); + evl_set_resched(rq); +} + +static void tp_tick_handler(struct evl_timer *timer) +{ + struct evl_rq *rq = container_of(timer, struct evl_rq, tp.tf_timer); + struct evl_thread *curr = rq->curr; + struct evl_sched_tp *tp = &rq->tp; + int overrun_frame = -1; + + raw_spin_lock(&rq->lock); + + /* + * If the current thread on this CPU was still active at the + * end of its time frame, we may have to notify an overrun. + */ + if ((curr->state & (EVL_T_WOSO|EVL_THREAD_BLOCK_BITS)) == EVL_T_WOSO) { + /* + * tp->wnext is pointing at the next window already, + * move back to one which is being overrun. + */ + overrun_frame = tp->wnext - 1; + if (overrun_frame < 0) + overrun_frame = tp->gps->pwin_nr - 1; + } + + /* + * Advance the start date for the next time frame by a full + * period if we are processing the last window. + */ + if (tp->wnext + 1 == tp->gps->pwin_nr) + tp->tf_start = ktime_add(tp->tf_start, tp->gps->tf_duration); + + tp_schedule_next(tp); + + raw_spin_unlock(&rq->lock); + + if (overrun_frame >= 0) + evl_notify_thread(curr, EVL_HMDIAG_OVERRUN, + evl_intval(overrun_frame)); +} + +static void tp_init(struct evl_rq *rq) +{ + struct evl_sched_tp *tp = &rq->tp; + int n; + + for (n = 0; n < CONFIG_EVL_SCHED_TP_NR_PART; n++) + evl_init_schedq(&tp->partitions[n].runnable); + + tp->tps = NULL; + tp->gps = NULL; + INIT_LIST_HEAD(&tp->threads); + evl_init_schedq(&tp->idle.runnable); + evl_init_timer_on_rq(&tp->tf_timer, &evl_mono_clock, tp_tick_handler, + rq, EVL_TIMER_IGRAVITY); + evl_set_timer_name(&tp->tf_timer, "[tp-tick]"); +} + +static bool tp_setparam(struct evl_thread *thread, + const union evl_sched_param *p) +{ + struct evl_rq *rq = evl_thread_rq(thread); + + thread->tps = &rq->tp.partitions[p->tp.ptid]; + thread->state &= ~EVL_T_WEAK; + + return evl_set_effective_thread_priority(thread, p->tp.prio); +} + +static void tp_getparam(struct evl_thread *thread, + union evl_sched_param *p) +{ + p->tp.prio = thread->cprio; + p->tp.ptid = thread->tps - evl_thread_rq(thread)->tp.partitions; +} + +static void tp_trackprio(struct evl_thread *thread, + const union evl_sched_param *p) +{ + /* + * The assigned partition never changes as a result of a PI/PP + * boost, since this would be pretty wrong with respect to TP + * scheduling: i.e. we may not allow a thread from another + * partition to consume CPU time from the current one, despite + * this would help enforcing PI (see note). In any case, + * introducing resource contention between threads that belong + * to different partitions is utterly wrong in the first + * place. Only an explicit call to evl_set_thread_policy() + * may change the partition assigned to a thread. For that + * reason, a policy reset action only boils down to + * reinstating the base priority. + * + * NOTE: we do allow threads from lower scheduling classes to + * consume CPU time from the current window as a result of a + * PI boost, since this is aimed at speeding up the release of + * a synchronization object a TP thread needs. + */ + if (p) { + /* We should never cross partition boundaries. */ + EVL_WARN_ON(CORE, + thread->base_class == &evl_sched_tp && + thread->tps - evl_thread_rq(thread)->tp.partitions + != p->tp.ptid); + thread->cprio = p->tp.prio; + } else + thread->cprio = thread->bprio; +} + +static void tp_ceilprio(struct evl_thread *thread, int prio) +{ + if (prio > EVL_TP_MAX_PRIO) + prio = EVL_TP_MAX_PRIO; + + thread->cprio = prio; +} + +static int tp_chkparam(struct evl_thread *thread, + const union evl_sched_param *p) +{ + struct evl_sched_tp *tp = &evl_thread_rq(thread)->tp; + + if (tp->gps == NULL || + p->tp.prio < EVL_TP_MIN_PRIO || + p->tp.prio > EVL_TP_MAX_PRIO || + p->tp.ptid < 0 || + p->tp.ptid >= CONFIG_EVL_SCHED_TP_NR_PART) + return -EINVAL; + + return 0; +} + +static int tp_declare(struct evl_thread *thread, + const union evl_sched_param *p) +{ + struct evl_rq *rq = evl_thread_rq(thread); + + list_add_tail(&thread->tp_link, &rq->tp.threads); + + return 0; +} + +static void tp_forget(struct evl_thread *thread) +{ + list_del(&thread->tp_link); + thread->tps = NULL; +} + +static void tp_enqueue(struct evl_thread *thread) +{ + evl_add_schedq_tail(&thread->tps->runnable, thread); +} + +static void tp_dequeue(struct evl_thread *thread) +{ + evl_del_schedq(&thread->tps->runnable, thread); +} + +static void tp_requeue(struct evl_thread *thread) +{ + evl_add_schedq(&thread->tps->runnable, thread); +} + +static struct evl_thread *tp_pick(struct evl_rq *rq) +{ + /* Never pick a thread if we don't schedule partitions. */ + if (!evl_timer_is_running(&rq->tp.tf_timer)) + return NULL; + + return evl_get_schedq(&rq->tp.tps->runnable); +} + +static void tp_migrate(struct evl_thread *thread, struct evl_rq *rq) +{ + union evl_sched_param param; + /* + * Since our partition schedule is a per-rq property, it + * cannot apply to a thread that moves to another CPU + * anymore. So we upgrade that thread to the FIFO class when a + * CPU migration occurs. A subsequent call to + * evl_set_thread_schedparam_locked() may move it back to TP + * scheduling, with a partition assignment that fits the + * remote CPU's partition schedule. + */ + param.fifo.prio = thread->cprio; + evl_set_thread_schedparam_locked(thread, &evl_sched_fifo, ¶m); +} + +static const char *tp_name(struct evl_thread *thread) +{ + return "tp"; +} + +static ssize_t tp_show(struct evl_thread *thread, + char *buf, ssize_t count) +{ + int ptid = thread->tps - evl_thread_rq(thread)->tp.partitions; + + return snprintf(buf, count, "%d\n", ptid); +} + +static void start_tp_schedule(struct evl_rq *rq) +{ + struct evl_sched_tp *tp = &rq->tp; + + assert_hard_lock(&rq->lock); + + if (tp->gps == NULL) + return; + + tp->wnext = 0; + tp->tf_start = evl_read_clock(&evl_mono_clock); + tp_schedule_next(tp); +} + +static void stop_tp_schedule(struct evl_rq *rq) +{ + struct evl_sched_tp *tp = &rq->tp; + + assert_hard_lock(&rq->lock); + + if (tp->gps) + evl_stop_timer(&tp->tf_timer); +} + +static struct evl_tp_schedule * +set_tp_schedule(struct evl_rq *rq, struct evl_tp_schedule *gps) +{ + struct evl_sched_tp *tp = &rq->tp; + struct evl_tp_schedule *old_gps; + unsigned long flags; + + if (EVL_WARN_ON(CORE, gps != NULL && + (gps->pwin_nr <= 0 || gps->pwins[0].w_offset != 0))) + return tp->gps; + + /* + * Changing the TP schedule on a runqueue is a twofold + * operation which happens atomically: first we stop the + * per-CPU timer driving the time slicing, next the new + * scheduling table is swapped with the old one. + */ + raw_spin_lock_irqsave(&rq->lock, flags); + + /* + * We deny the change if some thread undergoing the TP policy + * is currently attached to the target runqueue. + */ + if (!list_empty(&tp->threads)) { + raw_spin_unlock_irqrestore(&rq->lock, flags); + return ERR_PTR(-EBUSY); + } + + stop_tp_schedule(rq); + old_gps = tp->gps; + tp->gps = gps; + + raw_spin_unlock_irqrestore(&rq->lock, flags); + + return old_gps; +} + +static struct evl_tp_schedule * +get_tp_schedule(struct evl_rq *rq) +{ + struct evl_tp_schedule *gps = rq->tp.gps; + + assert_hard_lock(&rq->lock); + + if (gps == NULL) + return NULL; + + atomic_inc(&gps->refcount); + + return gps; +} + +static void put_tp_schedule(struct evl_tp_schedule *gps) +{ + if (atomic_dec_and_test(&gps->refcount)) + evl_free(gps); +} + +static ssize_t tp_control(int cpu, union evl_sched_ctlparam *ctlp, + union evl_sched_ctlinfo *infp) +{ + struct evl_tp_ctlparam *pt = &ctlp->tp; + ktime_t offset, duration, next_offset; + struct evl_tp_schedule *gps, *ogps; + int n, nr_windows, ret = -EINVAL; + struct __evl_tp_window *p, *pp; + struct evl_tp_window *w, *pw; + struct evl_tp_ctlinfo *it; + unsigned long flags; + struct evl_rq *rq; + + if (cpu < 0 || !cpu_present(cpu) || !is_threading_cpu(cpu)) + return -EINVAL; + + rq = evl_cpu_rq(cpu); + + switch (pt->op) { + case evl_tp_install: + if (pt->nr_windows > 0) + goto install_schedule; + fallthrough; + case evl_tp_uninstall: + gps = NULL; + goto switch_schedule; + case evl_tp_start: + raw_spin_lock_irqsave(&rq->lock, flags); + start_tp_schedule(rq); + raw_spin_unlock_irqrestore(&rq->lock, flags); + goto done; + case evl_tp_stop: + raw_spin_lock_irqsave(&rq->lock, flags); + stop_tp_schedule(rq); + raw_spin_unlock_irqrestore(&rq->lock, flags); + goto done; + case evl_tp_get: + raw_spin_lock_irqsave(&rq->lock, flags); + gps = get_tp_schedule(rq); + raw_spin_unlock_irqrestore(&rq->lock, flags); + if (gps == NULL) + goto done; + break; + default: + return -EINVAL; + } + + /* evl_tp_get */ + + if (infp == NULL) { + put_tp_schedule(gps); + return -EINVAL; + } + + it = &infp->tp; + nr_windows = min(pt->nr_windows, gps->pwin_nr); + it->nr_windows = gps->pwin_nr; /* Actual count is returned. */ + + for (n = 0, pp = p = it->windows, pw = w = gps->pwins; + n < nr_windows; pp = p, p++, pw = w, w++, n++) { + p->offset = ktime_to_u_timespec(w->w_offset); + pp->duration = ktime_to_u_timespec( + ktime_sub(w->w_offset, pw->w_offset)); + p->ptid = w->w_part; + } + + pp->duration = ktime_to_u_timespec( + ktime_sub(gps->tf_duration, pw->w_offset)); + + put_tp_schedule(gps); + + return evl_tp_infolen(nr_windows); + +install_schedule: /* evl_tp_install */ + + gps = evl_alloc(sizeof(*gps) + pt->nr_windows * sizeof(*w)); + if (gps == NULL) + return -ENOMEM; + + for (n = 0, p = pt->windows, w = gps->pwins, next_offset = 0; + n < pt->nr_windows; n++, p++, w++) { + /* + * Time windows must be strictly contiguous. Holes may + * be defined using windows assigned to the pseudo + * partition #-1. + */ + offset = u_timespec_to_ktime(p->offset); + if (offset != next_offset) + goto fail; + + duration = u_timespec_to_ktime(p->duration); + if (duration <= 0) + goto fail; + + if (p->ptid < -1 || + p->ptid >= CONFIG_EVL_SCHED_TP_NR_PART) { + goto fail; + } + + w->w_offset = next_offset; + w->w_part = p->ptid; + next_offset = ktime_add(next_offset, duration); + } + + atomic_set(&gps->refcount, 1); + gps->pwin_nr = n; + gps->tf_duration = next_offset; + +switch_schedule: /* evl_tp_{un}install */ + + ogps = set_tp_schedule(rq, gps); + if (IS_ERR(ogps)) { + ret = PTR_ERR(ogps); + goto fail; + } + if (ogps) + put_tp_schedule(ogps); +done: + evl_schedule(); + + return 0; +fail: + evl_free(gps); + + return ret; +} + +struct evl_sched_class evl_sched_tp = { + .sched_init = tp_init, + .sched_enqueue = tp_enqueue, + .sched_dequeue = tp_dequeue, + .sched_requeue = tp_requeue, + .sched_pick = tp_pick, + .sched_migrate = tp_migrate, + .sched_chkparam = tp_chkparam, + .sched_setparam = tp_setparam, + .sched_getparam = tp_getparam, + .sched_trackprio = tp_trackprio, + .sched_ceilprio = tp_ceilprio, + .sched_declare = tp_declare, + .sched_forget = tp_forget, + .sched_name = tp_name, + .sched_show = tp_show, + .sched_control = tp_control, + .weight = EVL_CLASS_WEIGHT(3), + .policy = SCHED_TP, + .name = "tp" +}; +EXPORT_SYMBOL_GPL(evl_sched_tp); diff --git a/kernel/evl/sched/weak.c b/kernel/evl/sched/weak.c new file mode 100644 index 000000000..b3d25186c --- /dev/null +++ b/kernel/evl/sched/weak.c @@ -0,0 +1,110 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Derived from Xenomai Cobalt, https://xenomai.org/ + * Copyright (C) 2013, 2018 Philippe Gerum + */ + +#include +#include + +static void weak_init(struct evl_rq *rq) +{ + evl_init_schedq(&rq->weak.runnable); +} + +static void weak_requeue(struct evl_thread *thread) +{ + evl_add_schedq(&thread->rq->weak.runnable, thread); +} + +static void weak_enqueue(struct evl_thread *thread) +{ + evl_add_schedq_tail(&thread->rq->weak.runnable, thread); +} + +static void weak_dequeue(struct evl_thread *thread) +{ + evl_del_schedq(&thread->rq->weak.runnable, thread); +} + +static struct evl_thread *weak_pick(struct evl_rq *rq) +{ + return evl_get_schedq(&rq->weak.runnable); +} + +static int weak_chkparam(struct evl_thread *thread, + const union evl_sched_param *p) +{ + if (p->weak.prio < EVL_WEAK_MIN_PRIO || + p->weak.prio > EVL_WEAK_MAX_PRIO) + return -EINVAL; + + return 0; +} + +static bool weak_setparam(struct evl_thread *thread, + const union evl_sched_param *p) +{ + if (!(thread->state & EVL_T_BOOST)) + thread->state |= EVL_T_WEAK; + + return evl_set_effective_thread_priority(thread, p->weak.prio); +} + +static void weak_getparam(struct evl_thread *thread, + union evl_sched_param *p) +{ + p->weak.prio = thread->cprio; +} + +static void weak_trackprio(struct evl_thread *thread, + const union evl_sched_param *p) +{ + if (p) + thread->cprio = p->weak.prio; + else + thread->cprio = thread->bprio; +} + +static void weak_ceilprio(struct evl_thread *thread, int prio) +{ + if (prio > EVL_WEAK_MAX_PRIO) + prio = EVL_WEAK_MAX_PRIO; + + thread->cprio = prio; +} + +static int weak_declare(struct evl_thread *thread, + const union evl_sched_param *p) +{ + if (p->weak.prio < EVL_WEAK_MIN_PRIO || + p->weak.prio > EVL_WEAK_MAX_PRIO) + return -EINVAL; + + return 0; +} + +static const char *weak_name(struct evl_thread *thread) +{ + return "weak"; +} + +struct evl_sched_class evl_sched_weak = { + .sched_init = weak_init, + .sched_enqueue = weak_enqueue, + .sched_dequeue = weak_dequeue, + .sched_requeue = weak_requeue, + .sched_pick = weak_pick, + .sched_declare = weak_declare, + .sched_chkparam = weak_chkparam, + .sched_setparam = weak_setparam, + .sched_trackprio = weak_trackprio, + .sched_ceilprio = weak_ceilprio, + .sched_getparam = weak_getparam, + .sched_name = weak_name, + .weight = EVL_CLASS_WEIGHT(1), + .policy = SCHED_WEAK, + .name = "weak" +}; +EXPORT_SYMBOL_GPL(evl_sched_weak); diff --git a/kernel/evl/sem.c b/kernel/evl/sem.c new file mode 100644 index 000000000..7609e35d4 --- /dev/null +++ b/kernel/evl/sem.c @@ -0,0 +1,68 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2019 Philippe Gerum + */ + +#include +#include + +static bool down_ksem(struct evl_ksem *ksem) +{ + if (ksem->value > 0) { + --ksem->value; + return true; + } + + return false; +} + +int evl_down_timeout(struct evl_ksem *ksem, ktime_t timeout) +{ + return evl_wait_event_timeout(&ksem->wait, timeout, + EVL_ABS, down_ksem(ksem)); +} +EXPORT_SYMBOL_GPL(evl_down_timeout); + +int evl_down(struct evl_ksem *ksem) +{ + return evl_wait_event(&ksem->wait, down_ksem(ksem)); +} +EXPORT_SYMBOL_GPL(evl_down); + +int evl_trydown(struct evl_ksem *ksem) +{ + unsigned long flags; + bool ret; + + raw_spin_lock_irqsave(&ksem->wait.wchan.lock, flags); + ret = down_ksem(ksem); + raw_spin_unlock_irqrestore(&ksem->wait.wchan.lock, flags); + + return ret ? 0 : -EAGAIN; +} +EXPORT_SYMBOL_GPL(evl_trydown); + +void evl_up(struct evl_ksem *ksem) +{ + unsigned long flags; + + raw_spin_lock_irqsave(&ksem->wait.wchan.lock, flags); + ksem->value++; + evl_wake_up_head(&ksem->wait); + raw_spin_unlock_irqrestore(&ksem->wait.wchan.lock, flags); + evl_schedule(); +} +EXPORT_SYMBOL_GPL(evl_up); + +void evl_broadcast(struct evl_ksem *ksem) +{ + unsigned long flags; + + raw_spin_lock_irqsave(&ksem->wait.wchan.lock, flags); + ksem->value = 0; + evl_flush_wait_locked(&ksem->wait, EVL_T_BCAST); + raw_spin_unlock_irqrestore(&ksem->wait.wchan.lock, flags); + evl_schedule(); +} +EXPORT_SYMBOL_GPL(evl_broadcast); diff --git a/kernel/evl/stax.c b/kernel/evl/stax.c new file mode 100644 index 000000000..fdba95bd5 --- /dev/null +++ b/kernel/evl/stax.c @@ -0,0 +1,410 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2020 Philippe Gerum + * + * Stage exclusion lock implementation (aka STAX). + */ + +#include +#include + +/* Gate marker for in-band activity. */ +#define STAX_INBAND_BIT BIT(31) +/* + * The stax is being claimed by the converse stage. This bit is + * manipulated exclusively while holding oob_wait.wchan.lock. When set + * from inband, this bit also implicitly means that the waiter is not + * spinning but sleeping on the stax (i.e. EVL_STAX_INBAND_SPIN is + * clear at init). + */ +#define STAX_CLAIMED_BIT BIT(30) + +/* The number of threads currently traversing the section. */ +#define STAX_CONCURRENCY_MASK (~(STAX_INBAND_BIT|STAX_CLAIMED_BIT)) + +static void wakeup_inband_waiters(struct irq_work *work); + +void evl_init_stax(struct evl_stax *stax, int flags) +{ + atomic_set(&stax->gate, 0); + stax->flags = flags; + evl_init_wait(&stax->oob_wait, &evl_mono_clock, EVL_WAIT_FIFO); + if (!(flags & EVL_STAX_INBAND_SPIN)) { + init_waitqueue_head(&stax->inband_wait); + init_irq_work(&stax->irq_work, wakeup_inband_waiters); + } +} +EXPORT_SYMBOL_GPL(evl_init_stax); + +void evl_destroy_stax(struct evl_stax *stax) +{ + evl_destroy_wait(&stax->oob_wait); +} +EXPORT_SYMBOL_GPL(evl_destroy_stax); + +static inline bool oob_may_access(int gateval) +{ + /* + * Out-of-band threads may access as long as no in-band thread + * holds the stax. + */ + return !(gateval & STAX_INBAND_BIT); +} + +static int claim_stax_from_oob(struct evl_stax *stax, int gateval) +{ + struct evl_thread *curr = evl_current(); + int old, new, prev, ret = 0; + unsigned long flags; + bool notify = false; + + raw_spin_lock_irqsave(&stax->oob_wait.wchan.lock, flags); + + if (gateval & STAX_CLAIMED_BIT) { + prev = atomic_read(&stax->gate); + goto check_access; + } + + prev = gateval; + do { + old = prev; + new = old | STAX_CLAIMED_BIT; + prev = atomic_cmpxchg(&stax->gate, old, new); + if (likely(prev == old)) + break; + check_access: + if (!(prev & STAX_INBAND_BIT)) + goto out; + } while (!(prev & STAX_CLAIMED_BIT)); + + if (curr->state & EVL_T_WOSX) + notify = true; + + do { + if (oob_may_access(atomic_read(&stax->gate))) + break; + evl_add_wait_queue(&stax->oob_wait, EVL_INFINITE, EVL_REL); + raw_spin_unlock_irqrestore(&stax->oob_wait.wchan.lock, flags); + ret = evl_wait_schedule(&stax->oob_wait); + raw_spin_lock_irqsave(&stax->oob_wait.wchan.lock, flags); + } while (!ret); + + /* Clear the claim bit if nobody contends anymore. */ + if (!evl_wait_active(&stax->oob_wait)) { + prev = atomic_read(&stax->gate); + do { + old = prev; + prev = atomic_cmpxchg(&stax->gate, old, + old & ~STAX_CLAIMED_BIT); + } while (prev != old); + } +out: + raw_spin_unlock_irqrestore(&stax->oob_wait.wchan.lock, flags); + + if (notify) { + evl_notify_thread(curr, EVL_HMDIAG_STAGEX, evl_nil); + evl_kick_thread(curr, 0); + } + + return ret; +} + +static int lock_from_oob(struct evl_stax *stax, bool wait) +{ + int old, prev, ret = 0; + + for (;;) { + /* + * The inband flag is the sign bit, mask it out in + * arithmetics. In addition, this ensures cmpxchg() + * fails if inband currently owns the section. + */ + old = atomic_read(&stax->gate) & ~STAX_INBAND_BIT; + prev = atomic_cmpxchg(&stax->gate, old, old + 1); + if (prev == old) + break; + /* + * Retry if the section is still clear for entry from + * oob. + */ + if (oob_may_access(prev)) + continue; + if (!wait) { + ret = -EAGAIN; + break; + } + ret = claim_stax_from_oob(stax, prev); + if (ret) + break; + } + + return ret; +} + +static inline bool inband_may_access(int gateval) +{ + /* + * The section is clear for entry by inband if the concurrency + * value is either zero, or STAX_INBAND_BIT is set in the gate + * mask. + */ + return !(gateval & STAX_CONCURRENCY_MASK) || + !!(gateval & STAX_INBAND_BIT); +} + +static int claim_stax_from_inband(struct evl_stax *stax, int gateval) +{ + unsigned long ib_flags, oob_flags; + struct wait_queue_entry wq_entry; + int old, new, prev, ret = 0; + + init_wait_entry(&wq_entry, 0); + + /* + * In-band lock first, oob next. First one disables irqs for + * the in-band stage only, second one disables hard irqs. Only + * this sequence is legit. + */ + spin_lock_irqsave(&stax->inband_wait.lock, ib_flags); + raw_spin_lock_irqsave(&stax->oob_wait.wchan.lock, oob_flags); + + if (gateval & STAX_CLAIMED_BIT) { + prev = atomic_read(&stax->gate); + goto check_access; + } + + prev = gateval; + do { + old = prev; + new = old | STAX_CLAIMED_BIT; + prev = atomic_cmpxchg(&stax->gate, old, new); + if (likely(prev == old)) + break; + check_access: + if (prev & STAX_INBAND_BIT) + goto out; + } while (!(prev & STAX_CLAIMED_BIT)); + + for (;;) { + if (list_empty(&wq_entry.entry)) + __add_wait_queue(&stax->inband_wait, &wq_entry); + + if (inband_may_access(atomic_read(&stax->gate))) + break; + + set_current_state(TASK_INTERRUPTIBLE); + raw_spin_unlock_irqrestore(&stax->oob_wait.wchan.lock, oob_flags); + spin_unlock_irqrestore(&stax->inband_wait.lock, ib_flags); + schedule(); + spin_lock_irqsave(&stax->inband_wait.lock, ib_flags); + raw_spin_lock_irqsave(&stax->oob_wait.wchan.lock, oob_flags); + + if (signal_pending(current)) { + ret = -ERESTARTSYS; + break; + } + } + + list_del(&wq_entry.entry); + + if (!waitqueue_active(&stax->inband_wait)) { + prev = atomic_read(&stax->gate); + do { + old = prev; + prev = atomic_cmpxchg(&stax->gate, old, + old & ~STAX_CLAIMED_BIT); + } while (prev != old); + } +out: + raw_spin_unlock_irqrestore(&stax->oob_wait.wchan.lock, oob_flags); + spin_unlock_irqrestore(&stax->inband_wait.lock, ib_flags); + + return ret; +} + +static int lock_from_inband(struct evl_stax *stax, bool wait) +{ + int old, prev, new, ret = 0; + + for (;;) { + old = atomic_read(&stax->gate); + /* + * If oob currently owns the stax, we have + * STAX_INBAND_BIT clear and at least one thread is + * counted in the concurrency value. Adding + * STAX_INBAND_BIT to the non-zero concurrency value + * ensures cmpxchg() fails if oob currently owns the + * section. + */ + if (old & STAX_CONCURRENCY_MASK) + old |= STAX_INBAND_BIT; + + /* Keep the claim bit in arithmetics. */ + new = ((old & ~STAX_INBAND_BIT) + 1) | STAX_INBAND_BIT; + prev = atomic_cmpxchg(&stax->gate, old, new); + if (prev == old) + break; /* Acquired. */ + + /* + * Cannot acquire for inband yet. Retry if spinning + * wait is requested, or if the section is clear from + * any oob activity. + */ + if (stax->flags & EVL_STAX_INBAND_SPIN || inband_may_access(prev)) { + cpu_relax(); + continue; + } + + if (!wait) { + ret = -EAGAIN; + break; + } + ret = claim_stax_from_inband(stax, prev); + if (ret) + break; + } + + return ret; +} + +int evl_lock_stax(struct evl_stax *stax) +{ + EVL_WARN_ON(CORE, evl_in_irq()); + + if (running_inband()) + return lock_from_inband(stax, true); + + return lock_from_oob(stax, true); +} +EXPORT_SYMBOL_GPL(evl_lock_stax); + +int evl_trylock_stax(struct evl_stax *stax) +{ + if (running_inband()) + return lock_from_inband(stax, false); + + return lock_from_oob(stax, false); +} +EXPORT_SYMBOL_GPL(evl_trylock_stax); + +static void wakeup_inband_waiters(struct irq_work *work) +{ + struct evl_stax *stax = container_of(work, struct evl_stax, irq_work); + + wake_up_all(&stax->inband_wait); +} + +static bool oob_unlock_sane(int gateval) +{ + return !EVL_WARN_ON(CORE, + !(gateval & STAX_CONCURRENCY_MASK) || + gateval & STAX_INBAND_BIT); +} + +static void unlock_from_oob(struct evl_stax *stax) +{ + unsigned long flags; + int old, prev, new; + + /* + * Try the fast path: non-contended (unclaimed by inband, + * maybe spinning). + */ + prev = atomic_read(&stax->gate); + + while (!(prev & STAX_CLAIMED_BIT)) { + old = prev; + if (unlikely(!oob_unlock_sane(old))) + return; + /* Force slow path if claimed. */ + old &= ~STAX_CLAIMED_BIT; + new = old - 1; + prev = atomic_cmpxchg(&stax->gate, old, new); + if (prev == old) + return; + } + + /* + * stax is claimed by inband (which is therefore NOT + * spinning), we have to take the slow path under lock. + */ + raw_spin_lock_irqsave(&stax->oob_wait.wchan.lock, flags); + + do { + old = prev; + new = old - 1; + if (unlikely(!oob_unlock_sane(old))) + break; + prev = atomic_cmpxchg(&stax->gate, old, new); + } while (prev != old); + + raw_spin_unlock_irqrestore(&stax->oob_wait.wchan.lock, flags); + + if (!(new & STAX_CONCURRENCY_MASK)) + irq_work_queue(&stax->irq_work); +} + +static inline bool inband_unlock_sane(int gateval) +{ + return !EVL_WARN_ON(CORE, + !(gateval & STAX_CONCURRENCY_MASK) || + !(gateval & STAX_INBAND_BIT)); +} + +static void unlock_from_inband(struct evl_stax *stax) +{ + unsigned long flags; + int old, prev, new; + + /* Try the fast path: non-contended (unclaimed by oob). */ + prev = atomic_read(&stax->gate); + + while (!(prev & STAX_CLAIMED_BIT)) { + old = prev; + if (unlikely(!inband_unlock_sane(old))) + return; + /* Force slow path if claimed. */ + old &= ~STAX_CLAIMED_BIT; + new = (old & ~STAX_INBAND_BIT) - 1; + if (new & STAX_CONCURRENCY_MASK) + new |= STAX_INBAND_BIT; + prev = atomic_cmpxchg(&stax->gate, old, new); + if (prev == old) + return; + } + + /* + * Converse to unlock_from_oob(): stax is claimed by oob, we + * have to take the slow path under lock. + */ + raw_spin_lock_irqsave(&stax->oob_wait.wchan.lock, flags); + + do { + old = prev; + if (!inband_unlock_sane(old)) + goto out; + new = (old & ~STAX_INBAND_BIT) - 1; + if (new & STAX_CONCURRENCY_MASK) + new |= STAX_INBAND_BIT; + prev = atomic_cmpxchg(&stax->gate, old, new); + } while (prev != old); + + if (!(new & STAX_CONCURRENCY_MASK)) + evl_flush_wait_locked(&stax->oob_wait, 0); +out: + raw_spin_unlock_irqrestore(&stax->oob_wait.wchan.lock, flags); + + evl_schedule(); +} + +void evl_unlock_stax(struct evl_stax *stax) +{ + EVL_WARN_ON(CORE, evl_in_irq()); + + if (running_inband()) + unlock_from_inband(stax); + else + unlock_from_oob(stax); +} +EXPORT_SYMBOL_GPL(evl_unlock_stax); diff --git a/kernel/evl/syscall.c b/kernel/evl/syscall.c new file mode 100644 index 000000000..63c4d8625 --- /dev/null +++ b/kernel/evl/syscall.c @@ -0,0 +1,473 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Derived from Xenomai Cobalt, https://xenomai.org/ + * Copyright (C) 2005-2020 Philippe Gerum + * Copyright (C) 2005 Gilles Chanteperdrix + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define EVL_SYSCALL(__name, __args) \ + long EVL_ ## __name __args + +static EVL_SYSCALL(read, (int fd, char __user *u_buf, size_t size)) +{ + struct evl_file *efilp = evl_get_file(fd); + struct file *filp; + ssize_t ret; + + if (efilp == NULL) + return -EBADF; + + filp = efilp->filp; + if (!(filp->f_mode & FMODE_READ)) { + ret = -EBADF; + goto out; + } + + if (filp->f_op->oob_read == NULL) { + ret = -EINVAL; + goto out; + } + + ret = filp->f_op->oob_read(filp, u_buf, size); +out: + evl_put_file(efilp); + + return ret; +} + +static EVL_SYSCALL(write, (int fd, const char __user *u_buf, size_t size)) +{ + struct evl_file *efilp = evl_get_file(fd); + struct file *filp; + ssize_t ret; + + if (efilp == NULL) + return -EBADF; + + filp = efilp->filp; + if (!(filp->f_mode & FMODE_WRITE)) { + ret = -EBADF; + goto out; + } + + if (filp->f_op->oob_write == NULL) { + ret = -EINVAL; + goto out; + } + + ret = filp->f_op->oob_write(filp, u_buf, size); +out: + evl_put_file(efilp); + + return ret; +} + +static EVL_SYSCALL(ioctl, (int fd, unsigned int request, unsigned long arg)) +{ + struct evl_file *efilp = evl_get_file(fd); + long ret = -ENOTTY; + struct file *filp; + + if (efilp == NULL) + return -EBADF; + + filp = efilp->filp; + + if (unlikely(is_compat_oob_call())) { + if (filp->f_op->compat_oob_ioctl) + ret = filp->f_op->compat_oob_ioctl(filp, request, arg); + } else if (filp->f_op->oob_ioctl) { + ret = filp->f_op->oob_ioctl(filp, request, arg); + } + + if (ret == -ENOIOCTLCMD) + ret = -ENOTTY; + + evl_put_file(efilp); + + return ret; +} + +#define __EVL_CALL_NAME(__name) \ + [sys_evl_ ## __name] = #__name + +static const char *evl_sysnames[] = { + __EVL_CALL_NAME(read), + __EVL_CALL_NAME(write), + __EVL_CALL_NAME(ioctl), +}; + +#define SYSCALL_PROPAGATE 0 +#define SYSCALL_STOP 1 + +static __always_inline +void invoke_syscall(unsigned int nr, struct pt_regs *regs, + unsigned long *args) +{ + int error; + long ret; + + /* + * We have only very few syscalls, prefer a plain switch to a + * pointer indirection which ends up being fairly costly due + * to exploit mitigations. + */ + switch (nr) { + case sys_evl_read: + ret = EVL_read((int)args[0], + (char __user *)args[1], + (size_t)args[2]); + break; + case sys_evl_write: + ret = EVL_write((int)args[0], + (const char __user *)args[1], + (size_t)args[2]); + break; + case sys_evl_ioctl: + ret = EVL_ioctl((int)args[0], + (unsigned int)args[1], + args[2]); + break; + } + + error = IS_ERR_VALUE(ret) ? ret : 0; + syscall_set_return_value(current, regs, error, ret); +} + +static void prepare_for_signal(struct task_struct *p, + struct evl_thread *curr, + struct pt_regs *regs) +{ + unsigned long flags; + + /* + * @curr == this_evl_rq()->curr over oob so no need to grab + * @curr->lock (i.e. @curr cannot go away under out feet). + */ + raw_spin_lock_irqsave(&curr->rq->lock, flags); + + /* + * We are called from out-of-band mode only to act upon a + * pending signal receipt. We may observe signal_pending(p) + * which implies that EVL_T_KICKED was set too + * (handle_sigwake_event()), or EVL_T_KICKED alone which means + * that we have been unblocked from a wait for some other + * reason. + */ + if (curr->info & EVL_T_KICKED) { + if (signal_pending(p)) { + int retval = -ERESTARTSYS; + if (curr->local_info & EVL_T_NORST) { + retval = -EINTR; + curr->local_info &= ~EVL_T_NORST; + } + syscall_set_return_value(current, regs, retval, 0); + curr->info &= ~EVL_T_BREAK; + } + curr->info &= ~EVL_T_KICKED; + } + + raw_spin_unlock_irqrestore(&curr->rq->lock, flags); + + evl_test_cancel(); + + evl_switch_inband(EVL_HMDIAG_SIGDEMOTE); +} + +/* + * Intercepting __NR_clock_gettime (or __NR_clock_gettime64 on 32bit + * archs) here means that we are handling a fallback syscall for + * clock_gettime*() from the vDSO, which failed performing a direct + * access to the clocksource. Such fallback would involve a switch to + * in-band mode unless we provide the service directly from here, + * which is not optimal but still correct. + */ +static bool handle_vdso_fallback(struct pt_regs *regs, unsigned int nr, + unsigned long *args) +{ + struct __kernel_old_timespec __user *u_old_ts; + struct __kernel_timespec uts, __user *u_uts; + struct __kernel_old_timespec old_ts; + int clock_id, ret = 0, error; + struct evl_clock *clock; + struct timespec64 ts64; + +#define is_clock_gettime(__nr) ((__nr) == __NR_clock_gettime) +#ifndef __NR_clock_gettime64 +#define is_clock_gettime64(__nr) 0 +#else +#define is_clock_gettime64(__nr) ((__nr) == __NR_clock_gettime64) +#endif + + if (!is_clock_gettime(nr) && !is_clock_gettime64(nr)) + return false; + + clock_id = (int)args[0]; + switch (clock_id) { + case CLOCK_MONOTONIC: + clock = &evl_mono_clock; + break; + case CLOCK_REALTIME: + clock = &evl_realtime_clock; + break; + default: + return false; + } + + ts64 = ktime_to_timespec64(evl_read_clock(clock)); + + if (is_clock_gettime(nr)) { + old_ts.tv_sec = (__kernel_old_time_t)ts64.tv_sec; + old_ts.tv_nsec = ts64.tv_nsec; + u_old_ts = (struct __kernel_old_timespec __user *)args[1]; + if (raw_copy_to_user(u_old_ts, &old_ts, sizeof(old_ts))) + ret = -EFAULT; + } else if (is_clock_gettime64(nr)) { + uts.tv_sec = ts64.tv_sec; + uts.tv_nsec = ts64.tv_nsec; + u_uts = (struct __kernel_timespec __user *)args[1]; + if (raw_copy_to_user(u_uts, &uts, sizeof(uts))) + ret = -EFAULT; + } + + error = IS_ERR_VALUE((long)ret) ? ret : 0; + syscall_set_return_value(current, regs, error, ret); + +#undef is_clock_gettime +#undef is_clock_gettime64 + + return true; +} + +static int do_oob_syscall(struct irq_stage *stage, struct pt_regs *regs, + unsigned int scno, unsigned long *args, bool is_evlsc) +{ + struct task_struct *tsk = current; + struct evl_thread *curr; + + if (!is_evlsc) + goto do_inband; + + if (scno >= NR_EVL_SYSCALLS) { + printk(EVL_WARNING "invalid out-of-band syscall <%#x>\n", scno); + goto bad_syscall; + } + + curr = evl_current(); + if (curr == NULL || !cap_raised(current_cap(), CAP_SYS_NICE)) { + if (EVL_DEBUG(CORE)) + printk(EVL_WARNING + "syscall denied to %s[%d]\n", + evl_sysnames[scno], tsk->comm, task_pid_nr(tsk)); + syscall_set_return_value(tsk, regs, -EPERM, 0); + return SYSCALL_STOP; + } + + /* + * If the syscall originates from in-band context, hand it + * over to handle_inband_syscall() where the caller would be + * switched to OOB context prior to handling the request. + */ + if (stage != &oob_stage) + return SYSCALL_PROPAGATE; + + trace_evl_oob_sysentry(scno); + + invoke_syscall(scno, regs, args); + + /* Syscall might have switched in-band, recheck. */ + if (!evl_is_inband()) { + if (signal_pending(tsk) || (curr->info & EVL_T_KICKED)) + prepare_for_signal(tsk, curr, regs); + else if ((curr->state & EVL_T_WEAK) && + !atomic_read(&curr->held_mutex_count)) + evl_switch_inband(EVL_HMDIAG_NONE); + } + + /* Update the stats and user visible info. */ + evl_inc_counter(&curr->stat.sc); + evl_sync_uwindow(curr); + + trace_evl_oob_sysexit(syscall_get_return_value(tsk, regs)); + + return SYSCALL_STOP; + +do_inband: + if (evl_is_inband()) + return SYSCALL_PROPAGATE; + + /* + * We don't want to trigger a stage switch whenever the + * current request issued from the out-of-band stage is not a + * valid in-band syscall, but rather deliver -ENOSYS directly + * instead. Otherwise, switch to in-band mode before + * propagating the syscall down the pipeline. + */ + if (is_valid_inband_syscall(scno)) { + if (handle_vdso_fallback(regs, scno, args)) + return SYSCALL_STOP; + evl_switch_inband(EVL_HMDIAG_SYSDEMOTE); + return SYSCALL_PROPAGATE; + } + + printk(EVL_WARNING "invalid in-band syscall <%u>\n", scno); + +bad_syscall: + syscall_set_return_value(tsk, regs, -ENOSYS, 0); + + return SYSCALL_STOP; +} + +static int do_inband_syscall(struct pt_regs *regs, unsigned int scno, + unsigned long *args, + bool is_evlsc) +{ + struct evl_thread *curr = evl_current(); /* Always valid. */ + struct task_struct *tsk = current; + int ret; + + /* + * Some architectures may use special out-of-bound syscall + * numbers which escape Dovetail's range check, e.g. when + * handling aarch32 syscalls over an aarch64 kernel. When so, + * assume this is an in-band syscall which we need to + * propagate downstream to the common handler. + */ + if (curr == NULL) + return SYSCALL_PROPAGATE; + + /* + * Catch cancellation requests pending for threads undergoing + * the weak scheduling policy, which won't cross + * prepare_for_signal() frequently as they run mostly in-band. + */ + evl_test_cancel(); + + /* Handle lazy schedparam updates before switching. */ + evl_propagate_schedparam_change(curr); + + /* Propagate in-band syscalls. */ + if (!is_evlsc) + return SYSCALL_PROPAGATE; + + /* + * Process an OOB syscall after switching current to the + * out-of-band stage. do_oob_syscall() already checked the + * syscall number. + */ + trace_evl_inband_sysentry(scno); + + ret = evl_switch_oob(); + /* + * -ERESTARTSYS might be received if switching oob was blocked + * by a pending signal, otherwise -EINTR might be received + * upon signal detection after the transition to oob context, + * in which case the common logic applies (i.e. based on + * EVL_T_KICKED and/or signal_pending()). + */ + if (ret == -ERESTARTSYS) { + syscall_set_return_value(tsk, regs, ret, 0); + goto done; + } + + invoke_syscall(scno, regs, args); + + if (!evl_is_inband()) { + if (signal_pending(tsk) || (curr->info & EVL_T_KICKED)) + prepare_for_signal(tsk, curr, regs); + else if ((curr->state & EVL_T_WEAK) && + !atomic_read(&curr->held_mutex_count)) + evl_switch_inband(EVL_HMDIAG_NONE); + } +done: + if (curr->local_info & EVL_T_IGNOVR) + curr->local_info &= ~EVL_T_IGNOVR; + + evl_inc_counter(&curr->stat.sc); + evl_sync_uwindow(curr); + + trace_evl_inband_sysexit(syscall_get_return_value(tsk, regs)); + + return SYSCALL_STOP; +} + +static bool collect_syscall_args(struct pt_regs *regs, + unsigned long *args, + unsigned int *scno) +{ + struct task_struct *tsk = current; + + /* + * We'll need the arguments later on for handling either of + * inband or evl syscalls. + */ + syscall_get_arguments(tsk, regs, args); + + if (!in_oob_syscall(regs)) { + *scno = syscall_get_nr(tsk, regs); + return false; + } + + /* + * Since ABI 36, we recognize EVL requests only when folded + * into a prctl() call, such as prctl(PR_OOB_SYSCALL, @nr, + * args...). If so, fetch the EVL syscall number then shift + * the arguments left to skip it (3 arguments max). + * Otherwise, assume this is an in-band syscall, so leave the + * argument vector unchanged. + */ + *scno = args[1]; + args[0] = args[2]; + args[1] = args[3]; + args[2] = args[4]; + + return true; +} + +int handle_pipelined_syscall(struct irq_stage *stage, struct pt_regs *regs) +{ + unsigned long args[6] = { 0 }; + unsigned int scno; + bool is_evlsc; + + is_evlsc = collect_syscall_args(regs, args, &scno); + + if (unlikely(running_inband())) + return do_inband_syscall(regs, scno, args, is_evlsc); + + return do_oob_syscall(stage, regs, scno, args, is_evlsc); +} + +int handle_oob_syscall(struct pt_regs *regs) +{ + unsigned long args[6] = { 0 }; + unsigned int scno; + bool is_evlsc; + int ret; + + is_evlsc = collect_syscall_args(regs, args, &scno); + ret = do_oob_syscall(&oob_stage, regs, scno, args, is_evlsc); + EVL_WARN_ON(CORE, ret == SYSCALL_PROPAGATE); /* Keep me there! */ + + return ret; +} diff --git a/kernel/evl/thread.c b/kernel/evl/thread.c new file mode 100644 index 000000000..0191394bc --- /dev/null +++ b/kernel/evl/thread.c @@ -0,0 +1,2859 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Derived from Xenomai Cobalt, https://xenomai.org/ + * Copyright (C) 2006, 2016 Gilles Chanteperdrix + * Copyright (C) 2001, 2018 Philippe Gerum + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define EVL_THREAD_CLONE_FLAGS \ + (EVL_CLONE_PUBLIC|EVL_CLONE_OBSERVABLE|EVL_CLONE_UNICAST) + +int evl_nrthreads; + +LIST_HEAD(evl_thread_list); + +static DEFINE_HARD_SPINLOCK(thread_list_lock); + +static DECLARE_WAIT_QUEUE_HEAD(join_all); + +static const struct file_operations thread_fops; + +static void inband_task_wakeup(struct irq_work *work); + +static void skip_ptsync(struct evl_thread *thread); + +static void timeout_handler(struct evl_timer *timer) /* oob stage stalled */ +{ + struct evl_thread *thread = container_of(timer, struct evl_thread, rtimer); + + evl_wakeup_thread(thread, EVL_T_DELAY|EVL_T_PEND, EVL_T_TIMEO); +} + +static void periodic_handler(struct evl_timer *timer) /* oob stage stalled */ +{ + struct evl_thread *thread = + container_of(timer, struct evl_thread, ptimer); + + evl_wakeup_thread(thread, EVL_T_WAIT, EVL_T_TIMEO); +} + +static inline void enqueue_new_thread(struct evl_thread *thread) +{ + unsigned long flags; + + raw_spin_lock_irqsave(&thread_list_lock, flags); + list_add_tail(&thread->next, &evl_thread_list); + evl_nrthreads++; + raw_spin_unlock_irqrestore(&thread_list_lock, flags); +} + +static inline void dequeue_old_thread(struct evl_thread *thread) +{ + unsigned long flags; + + raw_spin_lock_irqsave(&thread_list_lock, flags); + if (!list_empty(&thread->next)) { + list_del(&thread->next); + evl_nrthreads--; + } + raw_spin_unlock_irqrestore(&thread_list_lock, flags); +} + +static inline void set_oob_threadinfo(struct evl_thread *thread) +{ + struct oob_thread_state *p; + + p = dovetail_current_state(); + p->thread = thread; +} + +static inline void set_oob_mminfo(struct evl_thread *thread) +{ + thread->oob_mm = dovetail_mm_state(); +} + +static inline void add_u_cap(struct evl_thread *thread, + struct cred *newcap, + int cap) +{ + if (!capable(cap)) { + cap_raise(newcap->cap_effective, cap); + cap_raise(thread->raised_cap, cap); + } +} + +static inline void drop_u_cap(struct evl_thread *thread, + struct cred *newcap, + int cap) +{ + if (cap_raised(thread->raised_cap, cap)) { + cap_lower(newcap->cap_effective, cap); + cap_lower(thread->raised_cap, cap); + } +} + +static void pin_to_initial_cpu(struct evl_thread *thread) +{ + struct task_struct *p = current; + unsigned long flags; + struct evl_rq *rq; + int cpu; + + /* + * @thread is the EVL extension of the current in-band + * task. If the current CPU is part of the affinity mask of + * this thread, pin the latter on this CPU. Otherwise pin it + * to the first CPU of that mask. + */ + cpu = task_cpu(p); + if (!cpumask_test_cpu(cpu, &thread->affinity)) + cpu = cpumask_first(&thread->affinity); + + set_cpus_allowed_ptr(p, cpumask_of(cpu)); + /* + * @thread is still unstarted EVL-wise, we are in the process + * of mapping the current in-band task to it. Therefore + * evl_migrate_thread() can be called for pinning it on an + * out-of-band CPU. + * + * NOTE: we do not need to check for EVL_T_WCHAN on return from + * evl_migrate_thread(), there is no way the emerging thread + * could be sleeping on a wait channel. + */ + rq = evl_cpu_rq(cpu); + raw_spin_lock_irqsave(&thread->lock, flags); + evl_migrate_thread(thread, rq); + raw_spin_unlock_irqrestore(&thread->lock, flags); +} + +int evl_init_thread(struct evl_thread *thread, + const struct evl_init_thread_attr *iattr, + struct evl_rq *rq, + const char *fmt, ...) +{ + int state = iattr->flags & ~EVL_T_SUSP, ret, gravity; + cpumask_var_t affinity; + va_list args; + + inband_context_only(); + + if (!(state & EVL_T_ROOT)) + state |= EVL_T_DORMANT | EVL_T_INBAND; + + if ((state & EVL_T_USER) && IS_ENABLED(CONFIG_EVL_DEBUG_WOLI)) + state |= EVL_T_WOLI; + + if (iattr->observable) + state |= EVL_T_OBSERV; + + /* + * If no rq was given, pick an initial CPU for the new thread + * which is part of its affinity mask, and therefore also part + * of the supported CPUs. This CPU may change in + * pin_to_initial_cpu(). + */ + if (!rq) { + if (!alloc_cpumask_var(&affinity, GFP_KERNEL)) + return -ENOMEM; + cpumask_and(affinity, iattr->affinity, &evl_cpu_affinity); + if (!cpumask_empty(affinity)) + rq = evl_cpu_rq(cpumask_first(affinity)); + free_cpumask_var(affinity); + if (!rq) + return -EINVAL; + } + + va_start(args, fmt); + thread->name = kvasprintf(GFP_KERNEL, fmt, args); + va_end(args); + if (thread->name == NULL) + return -ENOMEM; + + cpumask_and(&thread->affinity, iattr->affinity, &evl_cpu_affinity); + thread->rq = rq; + thread->state = state; + thread->info = 0; + thread->local_info = 0; + thread->wprio = EVL_IDLE_PRIO; + thread->cprio = EVL_IDLE_PRIO; + thread->bprio = EVL_IDLE_PRIO; + thread->rrperiod = EVL_INFINITE; + thread->wchan = NULL; + thread->wait_data = NULL; + thread->u_window = NULL; + thread->observable = iattr->observable; + atomic_set(&thread->held_mutex_count, 0); + memset(&thread->poll_context, 0, sizeof(thread->poll_context)); + memset(&thread->stat, 0, sizeof(thread->stat)); + memset(&thread->altsched, 0, sizeof(thread->altsched)); + init_irq_work(&thread->inband_work, inband_task_wakeup); + + INIT_LIST_HEAD(&thread->next); + INIT_LIST_HEAD(&thread->boosters); + INIT_LIST_HEAD(&thread->owned_mutexes); + raw_spin_lock_init(&thread->lock); + init_completion(&thread->exited); + INIT_LIST_HEAD(&thread->ptsync_next); + thread->oob_mm = NULL; + + gravity = state & EVL_T_USER ? EVL_TIMER_UGRAVITY : EVL_TIMER_KGRAVITY; + evl_init_timer_on_rq(&thread->rtimer, &evl_mono_clock, timeout_handler, + rq, gravity); + evl_set_timer_name(&thread->rtimer, thread->name); + evl_init_timer_on_rq(&thread->ptimer, &evl_mono_clock, periodic_handler, + rq, gravity); + evl_set_timer_name(&thread->ptimer, thread->name); + + thread->base_class = NULL; /* evl_set_thread_policy() sets it. */ + ret = evl_init_rq_thread(thread); + if (ret) + goto err_out; + + ret = evl_set_thread_policy(thread, iattr->sched_class, + &iattr->sched_param); + if (ret) + goto err_out; + +#ifdef CONFIG_LOCKDEP + if (state & EVL_T_ROOT) { + lockdep_set_class_and_name(&thread->lock, &rq->root_lock_key, + thread->name); + } else { + lockdep_register_key(&thread->lock_key); + lockdep_set_class_and_name(&thread->lock, &thread->lock_key, + thread->name); + } + might_hard_lock(&thread->lock); +#endif + + trace_evl_init_thread(thread, iattr, ret); + + return 0; + +err_out: + evl_destroy_timer(&thread->rtimer); + evl_destroy_timer(&thread->ptimer); + trace_evl_init_thread(thread, iattr, ret); + kfree(thread->name); + + return ret; +} +EXPORT_SYMBOL_GPL(evl_init_thread); + +/* Undoes evl_init_thread(), and only that. */ +static void uninit_thread(struct evl_thread *thread) +{ + unsigned long flags; + struct evl_rq *rq; + + /* + * Threads are special elements in that they may exit + * independently from the existence of their respective + * backing cdev. Make sure to hide exiting threads from sysfs + * handlers before we dismantle things. + */ + evl_hide_element(&thread->element); + + evl_destroy_timer(&thread->rtimer); + evl_destroy_timer(&thread->ptimer); + + rq = evl_get_thread_rq(thread, flags); + evl_forget_thread(thread); + evl_put_thread_rq(thread, rq, flags); + + if (!(thread->state & EVL_T_ROOT)) + lockdep_unregister_key(&thread->lock_key); + + kfree(thread->name); +} + +static void do_cleanup_current(struct evl_thread *curr) +{ + struct cred *newcap; + unsigned long flags; + struct evl_rq *rq; + + /* Kick out all subscribers. */ + if (curr->observable) + evl_flush_observable(curr->observable); + + /* + * Drop all mutexes first since this may alter the rq state + * for current. + */ + evl_drop_current_ownership(); + + evl_unindex_factory_element(&curr->element); + + if (curr->state & EVL_T_USER) { + evl_free_chunk(&evl_shared_heap, curr->u_window); + curr->u_window = NULL; + evl_drop_poll_table(curr); + newcap = prepare_creds(); + if (newcap) { + drop_u_cap(curr, newcap, CAP_SYS_NICE); + drop_u_cap(curr, newcap, CAP_IPC_LOCK); + drop_u_cap(curr, newcap, CAP_SYS_RAWIO); + commit_creds(newcap); + } + } + + dequeue_old_thread(curr); + + rq = evl_get_thread_rq(curr, flags); + + if (curr->state & EVL_T_READY) { + EVL_WARN_ON(CORE, (curr->state & EVL_THREAD_BLOCK_BITS)); + evl_dequeue_thread(curr); + curr->state &= ~EVL_T_READY; + } + + curr->state |= EVL_T_ZOMBIE; + + evl_put_thread_rq(curr, rq, flags); + uninit_thread(curr); +} + +static void cleanup_current_thread(void) +{ + struct oob_thread_state *p = dovetail_current_state(); + struct evl_thread *curr = evl_current(); + + /* + * We are called for exiting kernel and user threads over the + * in-band context. + */ + trace_evl_thread_unmap(curr); + dovetail_stop_altsched(); + do_cleanup_current(curr); + + p->thread = NULL; /* evl_current() <- NULL */ +} + +static void put_current_thread(void) +{ + struct evl_thread *curr = evl_current(); + + if (curr->state & EVL_T_USER) + skip_ptsync(curr); + + cleanup_current_thread(); + evl_put_element(&curr->element); +} + +static void wakeup_kthread_parent(struct irq_work *irq_work) +{ + struct evl_kthread *kthread; + kthread = container_of(irq_work, struct evl_kthread, irq_work); + complete(&kthread->done); +} + +static int map_kthread_self(struct evl_kthread *kthread) +{ + struct evl_thread *curr = &kthread->thread; + + pin_to_initial_cpu(curr); + + dovetail_init_altsched(&curr->altsched); + set_oob_threadinfo(curr); + dovetail_start_altsched(); + evl_release_thread(curr, EVL_T_DORMANT, 0); + + trace_evl_thread_map(curr); + + /* + * Upon -weird- error from evl_switch_oob() for an emerging + * kernel thread, we still finalize the registration but the + * caller should self-cancel eventually. + */ + kthread->status = evl_switch_oob(); + + /* + * We are now running OOB, therefore __evl_run_kthread() can't + * start us before we enter the dormant state because + * irq_work_queue() schedules the in-band wakeup request on + * the current CPU. If we fail switching to OOB context, + * kthread->status tells __evl_run_kthread() not to start but + * cancel us instead. + */ + init_irq_work(&kthread->irq_work, wakeup_kthread_parent); + irq_work_queue(&kthread->irq_work); + + enqueue_new_thread(curr); + evl_hold_thread(curr, EVL_T_DORMANT); + + return kthread->status; +} + +static int kthread_trampoline(void *arg) +{ + struct evl_kthread *kthread = arg; + struct evl_thread *curr = &kthread->thread; + struct sched_param param; + int policy, prio, ret; + + /* + * It makes sense to schedule EVL kthreads either in the + * SCHED_FIFO or SCHED_NORMAL policy only. So anything that is + * not based on EVL's FIFO class is assumed to belong to the + * in-band SCHED_NORMAL class. + */ + if (curr->sched_class != &evl_sched_fifo) { + policy = SCHED_NORMAL; + prio = 0; + } else { + policy = SCHED_FIFO; + prio = curr->cprio; + /* Normalize priority linux-wise. */ + if (prio >= MAX_RT_PRIO) + prio = MAX_RT_PRIO - 1; + } + + param.sched_priority = prio; + sched_setscheduler(current, policy, ¶m); + + ret = map_kthread_self(kthread); + if (!ret) { + trace_evl_kthread_entry(curr); + kthread->threadfn(kthread->arg); + } + + /* Handles nitty-gritty details like in-band switch. */ + evl_cancel_thread(curr); + + return 0; +} + +int __evl_run_kthread(struct evl_kthread *kthread, int clone_flags) +{ + struct evl_thread *thread = &kthread->thread; + struct task_struct *p; + int ret; + + ret = evl_init_element(&thread->element, + &evl_thread_factory, clone_flags); + if (ret) + goto fail_element; + + ret = evl_create_core_element_device(&thread->element, + &evl_thread_factory, + thread->name); + if (ret) + goto fail_device; + + p = kthread_run(kthread_trampoline, kthread, "%s", thread->name); + if (IS_ERR(p)) { + ret = PTR_ERR(p); + goto fail_spawn; + } + + evl_index_factory_element(&thread->element); + wait_for_completion(&kthread->done); + if (kthread->status) + return kthread->status; + + evl_release_thread(thread, EVL_T_DORMANT, 0); + evl_schedule(); + + return 0; + +fail_spawn: + evl_remove_element_device(&thread->element); +fail_device: + evl_destroy_element(&thread->element); +fail_element: + uninit_thread(thread); + + return ret; +} +EXPORT_SYMBOL_GPL(__evl_run_kthread); + +/* evl_current()->lock + evl_current()->rq->lock held, hard irqs off. */ +void evl_sleep_on_locked(ktime_t timeout, enum evl_tmode timeout_mode, + struct evl_clock *clock, + struct evl_wait_channel *wchan) +{ + struct evl_thread *curr = evl_current(); + struct evl_rq *rq = curr->rq; + unsigned long oldstate; + + /* Sleeping while preemption is disabled is a bug. */ + EVL_WARN_ON(CORE, evl_preempt_count() != 0); + + assert_thread_pinned(curr); + + trace_evl_sleep_on(timeout, timeout_mode, clock, wchan); + + oldstate = curr->state; + + /* + * If a request to switch to in-band context is pending + * (EVL_T_KICKED), raise EVL_T_BREAK then return immediately. + */ + if (likely(!(oldstate & EVL_THREAD_BLOCK_BITS))) { + if (curr->info & EVL_T_KICKED) { + curr->info &= ~(EVL_T_RMID|EVL_T_TIMEO); + curr->info |= EVL_T_BREAK; + return; + } + curr->info &= ~EVL_THREAD_INFO_MASK; + } + + /* + * wchan + timeout: timed wait for a resource (EVL_T_PEND|EVL_T_DELAY) + * wchan + !timeout: unbounded sleep on resource (EVL_T_PEND) + * !wchan + timeout: timed sleep (EVL_T_DELAY) + * !wchan + !timeout: periodic wait (EVL_T_WAIT) + */ + if (timeout_mode != EVL_REL || !timeout_infinite(timeout)) { + evl_prepare_timed_wait(&curr->rtimer, clock, + evl_thread_rq(curr)); + if (timeout_mode == EVL_REL) + timeout = evl_abs_timeout(&curr->rtimer, timeout); + else if (timeout <= evl_read_clock(clock)) { + curr->info |= EVL_T_TIMEO; + return; + } + evl_start_timer(&curr->rtimer, timeout, EVL_INFINITE); + curr->state |= EVL_T_DELAY; + } else if (!wchan) { + evl_prepare_timed_wait(&curr->ptimer, clock, + evl_thread_rq(curr)); + curr->state |= EVL_T_WAIT; + } + + if (oldstate & EVL_T_READY) { + evl_dequeue_thread(curr); + curr->state &= ~EVL_T_READY; + } + + if (wchan) { + curr->wchan = wchan; + curr->state |= EVL_T_PEND; + } + + evl_set_resched(rq); +} + +void evl_sleep_on(ktime_t timeout, enum evl_tmode timeout_mode, + struct evl_clock *clock, + struct evl_wait_channel *wchan) +{ + struct evl_thread *curr = evl_current(); + unsigned long flags; + struct evl_rq *rq; + + oob_context_only(); + + rq = evl_get_thread_rq(curr, flags); + evl_sleep_on_locked(timeout, timeout_mode, clock, wchan); + evl_put_thread_rq(curr, rq, flags); +} + +/* thread->lock + thread->rq->lock held, irqs off */ +static void evl_wakeup_thread_locked(struct evl_thread *thread, + int mask, int info) +{ + struct evl_rq *rq = thread->rq; + unsigned long oldstate; + + assert_thread_pinned(thread); + + if (EVL_WARN_ON(CORE, mask & ~(EVL_T_DELAY|EVL_T_PEND|EVL_T_WAIT))) + return; + + trace_evl_wakeup_thread(thread, mask, info); + + oldstate = thread->state; + if (likely(oldstate & mask)) { + /* Clear EVL_T_DELAY along w/ EVL_T_PEND in state. */ + if (mask & EVL_T_PEND) + mask |= EVL_T_DELAY; + + thread->state &= ~mask; + + if (mask & (EVL_T_DELAY|EVL_T_PEND)) + evl_stop_timer(&thread->rtimer); + + if (mask & EVL_T_PEND & oldstate) + thread->wchan = NULL; + + thread->info |= info; + + if (!(thread->state & EVL_THREAD_BLOCK_BITS)) { + evl_enqueue_thread(thread); + thread->state |= EVL_T_READY; + evl_set_resched(rq); + if (rq != this_evl_rq()) + evl_inc_counter(&thread->stat.rwa); + } + } +} + +void evl_wakeup_thread(struct evl_thread *thread, int mask, int info) +{ + unsigned long flags; + struct evl_rq *rq; + + rq = evl_get_thread_rq(thread, flags); + evl_wakeup_thread_locked(thread, mask, info); + evl_put_thread_rq(thread, rq, flags); +} + +void evl_hold_thread(struct evl_thread *thread, int mask) +{ + unsigned long oldstate, flags; + struct evl_rq *rq; + + if (EVL_WARN_ON(CORE, mask & ~(EVL_T_SUSP|EVL_T_HALT|EVL_T_DORMANT))) + return; + + trace_evl_hold_thread(thread, mask); + + rq = evl_get_thread_rq(thread, flags); + + oldstate = thread->state; + + /* + * If a request to switch to in-band context is pending for + * the target thread (EVL_T_KICKED), raise EVL_T_BREAK for it then + * return immediately. + */ + if (likely(!(oldstate & EVL_THREAD_BLOCK_BITS))) { + if (thread->info & EVL_T_KICKED) { + thread->info &= ~(EVL_T_RMID|EVL_T_TIMEO); + thread->info |= EVL_T_BREAK; + goto out; + } + if (thread == rq->curr) + thread->info &= ~EVL_THREAD_INFO_MASK; + } + + if (oldstate & EVL_T_READY) { + evl_dequeue_thread(thread); + thread->state &= ~EVL_T_READY; + } + + thread->state |= mask; + + /* + * If the thread is current on its CPU, we need to raise + * RQ_SCHED on the target runqueue. + * + * If the target thread runs in-band in userland on a remote + * CPU, request it to call us back next time it transitions + * from kernel to user mode. + */ + if (likely(thread == rq->curr)) + evl_set_resched(rq); + else if (((oldstate & (EVL_THREAD_BLOCK_BITS|EVL_T_USER)) == (EVL_T_INBAND|EVL_T_USER))) + dovetail_request_ucall(thread->altsched.task); + out: + evl_put_thread_rq(thread, rq, flags); +} + +/* thread->lock + thread->rq->lock held, irqs off */ +static void evl_release_thread_locked(struct evl_thread *thread, + int mask, int info) +{ + struct evl_rq *rq = thread->rq; + unsigned long oldstate; + + assert_thread_pinned(thread); + + if (EVL_WARN_ON(CORE, mask & ~(EVL_T_SUSP|EVL_T_HALT|EVL_T_INBAND|EVL_T_DORMANT|EVL_T_PTSYNC))) + return; + + trace_evl_release_thread(thread, mask, info); + + oldstate = thread->state; + if (oldstate & mask) { + thread->state &= ~mask; + thread->info |= info; + + if (thread->state & EVL_THREAD_BLOCK_BITS) + return; + + if (unlikely((oldstate & mask) & (EVL_T_HALT|EVL_T_PTSYNC))) { + /* Requeue at head of priority group. */ + evl_requeue_thread(thread); + goto ready; + } + } else if (oldstate & EVL_T_READY) + /* Ends up in round-robin (group rotation). */ + evl_dequeue_thread(thread); + + /* Enqueue at the tail of priority group. */ + evl_enqueue_thread(thread); +ready: + thread->state |= EVL_T_READY; + evl_set_resched(rq); + if (rq != this_evl_rq()) + evl_inc_counter(&thread->stat.rwa); +} + +void evl_release_thread(struct evl_thread *thread, int mask, int info) +{ + unsigned long flags; + struct evl_rq *rq; + + rq = evl_get_thread_rq(thread, flags); + evl_release_thread_locked(thread, mask, info); + evl_put_thread_rq(thread, rq, flags); +} + +static void inband_task_wakeup(struct irq_work *work) +{ + struct evl_thread *thread; + struct task_struct *p; + + thread = container_of(work, struct evl_thread, inband_work); + p = thread->altsched.task; + trace_evl_inband_wakeup(p); + wake_up_process(p); +} + +void evl_set_kthread_priority(struct evl_kthread *kthread, int priority) +{ + union evl_sched_param param = { .fifo = { .prio = priority } }; + + evl_set_thread_schedparam(&kthread->thread, &evl_sched_fifo, ¶m); + evl_schedule(); +} +EXPORT_SYMBOL_GPL(evl_set_kthread_priority); + +ktime_t evl_get_thread_timeout(struct evl_thread *thread) +{ + struct evl_timer *timer; + ktime_t timeout, now; + + if (!(thread->state & EVL_T_DELAY)) + return 0LL; + + if (evl_timer_is_running(&thread->rtimer)) + timer = &thread->rtimer; + else if (evl_timer_is_running(&thread->ptimer)) + timer = &thread->ptimer; + else + return 0; + + now = evl_ktime_monotonic(); + timeout = evl_get_timer_date(timer); + if (timeout <= now) + return ktime_set(0, 1); + + return ktime_sub(timeout, now); +} +EXPORT_SYMBOL_GPL(evl_get_thread_timeout); + +ktime_t evl_get_thread_period(struct evl_thread *thread) +{ + ktime_t period = 0; + /* + * The current thread period might be: + * - the value of the timer interval for periodic threads (ns/ticks) + * - or, the value of the alloted round-robin quantum (ticks) + * - or zero, meaning "no periodic activity". + */ + if (evl_timer_is_running(&thread->ptimer)) + period = thread->ptimer.interval; + else if (thread->state & EVL_T_RRB) + period = thread->rrperiod; + + return period; +} +EXPORT_SYMBOL_GPL(evl_get_thread_period); + +ktime_t evl_delay(ktime_t timeout, enum evl_tmode timeout_mode, + struct evl_clock *clock) +{ + struct evl_thread *curr = evl_current(); + ktime_t rem = 0; + + evl_sleep_on(timeout, timeout_mode, clock, NULL); + evl_schedule(); + + if (curr->info & EVL_T_BREAK) + rem = __evl_get_stopped_timer_delta(&curr->rtimer); + + return rem; +} +EXPORT_SYMBOL_GPL(evl_delay); + +int evl_sleep_until(ktime_t timeout) +{ + ktime_t rem; + + if (!EVL_ASSERT(CORE, !evl_cannot_block())) + return -EPERM; + + rem = evl_delay(timeout, EVL_ABS, &evl_mono_clock); + + return rem ? -EINTR : 0; +} +EXPORT_SYMBOL_GPL(evl_sleep_until); + +int evl_sleep(ktime_t delay) +{ + ktime_t end = ktime_add(evl_read_clock(&evl_mono_clock), delay); + return evl_sleep_until(end); +} +EXPORT_SYMBOL_GPL(evl_sleep); + +int evl_set_period(struct evl_clock *clock, + ktime_t idate, ktime_t period) +{ + struct evl_thread *curr = evl_current(); + unsigned long flags; + + if (curr == NULL) + return -EPERM; + + if (clock == NULL || period == EVL_INFINITE) { + evl_stop_timer(&curr->ptimer); + return 0; + } + + /* + * LART: detect periods which are shorter than the target + * clock gravity for kernel thread timers. This can't work, + * caller must have messed up arguments. + */ + if (period < evl_get_clock_gravity(clock, kernel)) + return -EINVAL; + + raw_spin_lock_irqsave(&curr->lock, flags); + + evl_prepare_timed_wait(&curr->ptimer, clock, evl_thread_rq(curr)); + + if (timeout_infinite(idate)) + idate = evl_abs_timeout(&curr->ptimer, period); + + evl_start_timer(&curr->ptimer, idate, period); + + raw_spin_unlock_irqrestore(&curr->lock, flags); + + return 0; +} +EXPORT_SYMBOL_GPL(evl_set_period); + +int evl_wait_period(unsigned long *overruns_r) +{ + unsigned long overruns, flags; + struct evl_thread *curr; + struct evl_clock *clock; + ktime_t now; + + curr = evl_current(); + if (unlikely(!evl_timer_is_running(&curr->ptimer))) + return -EAGAIN; + + trace_evl_thread_wait_period(curr); + + flags = hard_local_irq_save(); + clock = curr->ptimer.clock; + now = evl_read_clock(clock); + if (likely(now < evl_get_timer_next_date(&curr->ptimer))) { + evl_sleep_on(EVL_INFINITE, EVL_REL, clock, NULL); /* EVL_T_WAIT */ + hard_local_irq_restore(flags); + evl_schedule(); + if (unlikely(curr->info & EVL_T_BREAK)) + return -EINTR; + } else + hard_local_irq_restore(flags); + + overruns = evl_get_timer_overruns(&curr->ptimer); + if (overruns) { + if (likely(overruns_r != NULL)) + *overruns_r = overruns; + trace_evl_thread_missed_period(curr); + return -ETIMEDOUT; + } + + return 0; +} +EXPORT_SYMBOL_GPL(evl_wait_period); + +void evl_cancel_thread(struct evl_thread *thread) +{ + unsigned long flags; + struct evl_rq *rq; + + if (EVL_WARN_ON(CORE, thread->state & EVL_T_ROOT)) + return; + + rq = evl_get_thread_rq(thread, flags); + + if (thread->state & EVL_T_ZOMBIE) { + evl_put_thread_rq(thread, rq, flags); + return; + } + + if (thread->info & EVL_T_CANCELD) + goto check_self_cancel; + + trace_evl_thread_cancel(thread); + + thread->info |= EVL_T_CANCELD; + + /* + * If @thread is not started yet, fake a start request, + * raising the kicked condition bit to make sure it reaches + * evl_test_cancel() on its wakeup path. + * + * NOTE: if EVL_T_DORMANT and !EVL_T_INBAND, then some not-yet-mapped + * emerging thread is self-cancelling due to an early error in + * the prep work. + */ + if ((thread->state & (EVL_T_DORMANT|EVL_T_INBAND)) == (EVL_T_DORMANT|EVL_T_INBAND)) { + evl_release_thread_locked(thread, EVL_T_DORMANT, EVL_T_KICKED); + evl_put_thread_rq(thread, rq, flags); + goto out; + } + +check_self_cancel: + evl_put_thread_rq(thread, rq, flags); + + if (evl_current() == thread) { + evl_test_cancel(); + /* + * May return if on behalf of some IRQ handler which + * interrupted @thread. + */ + return; + } + + /* + * Force the non-current thread to exit: + * + * - unblock a user thread, switch it to weak scheduling, + * then send it SIGTERM. + * + * - just unblock a kernel thread, it is expected to reach a + * cancellation point soon after (i.e. evl_test_cancel()). + */ + if (thread->state & EVL_T_USER) { + evl_demote_thread(thread); + evl_signal_thread(thread, SIGTERM, 0); + } else + evl_kick_thread(thread, 0); +out: + evl_schedule(); +} +EXPORT_SYMBOL_GPL(evl_cancel_thread); + +int evl_detach_self(void) +{ + if (evl_current() == NULL) + return -EPERM; + + put_current_thread(); + + return 0; +} + +int evl_join_thread(struct evl_thread *thread, bool uninterruptible) +{ + struct evl_thread *curr = evl_current(); + bool switched = false; + unsigned long flags; + struct evl_rq *rq; + int ret = 0; + + if (EVL_WARN_ON(CORE, thread->state & EVL_T_ROOT)) + return -EINVAL; + + if (thread == curr) + return -EDEADLK; + + rq = evl_get_thread_rq(thread, flags); + + /* + * We allow multiple callers to join @thread, this is purely a + * synchronization mechanism with no resource collection. + */ + if (thread->info & EVL_T_DORMANT) { + evl_put_thread_rq(thread, rq, flags); + return 0; + } + + trace_evl_thread_join(thread); + + if (curr && !(curr->state & EVL_T_INBAND)) { + evl_put_thread_rq(thread, rq, flags); + evl_switch_inband(EVL_HMDIAG_NONE); + switched = true; + } else { + evl_put_thread_rq(thread, rq, flags); + } + + /* + * Wait until the joinee is fully dismantled in + * thread_factory_dispose(), which guarantees safe module + * removal afterwards if applicable. After this point, @thread + * is invalid. + */ + if (uninterruptible) + wait_for_completion(&thread->exited); + else { + ret = wait_for_completion_interruptible(&thread->exited); + if (ret < 0) + return -EINTR; + } + + if (switched) + ret = evl_switch_oob(); + + return ret; +} +EXPORT_SYMBOL_GPL(evl_join_thread); + +int evl_set_thread_schedparam(struct evl_thread *thread, + struct evl_sched_class *sched_class, + const union evl_sched_param *sched_param) +{ + unsigned long flags; + struct evl_rq *rq; + int ret; + + rq = evl_get_thread_rq(thread, flags); + ret = evl_set_thread_schedparam_locked(thread, sched_class, sched_param); + evl_put_thread_rq_check(thread, rq, flags); + + return ret; +} +EXPORT_SYMBOL_GPL(evl_set_thread_schedparam); + +/* + * Update the priority and/or scheduling policy of @thread. This + * routine is NOT involved in PI/PP management for mutexes in any way, + * a specific calls exists for this instead, see + * evl_adjust_thread_boost(). + * + * On entry: thread->lock + thread->rq->lock held, irqs off. + */ +int evl_set_thread_schedparam_locked(struct evl_thread *thread, + struct evl_sched_class *sched_class, + const union evl_sched_param *sched_param) +{ + int old_wprio, new_wprio, ret; + + assert_thread_pinned(thread); + + old_wprio = thread->wprio; + + ret = evl_set_thread_policy_locked(thread, sched_class, sched_param); + if (ret) + return ret; + + new_wprio = thread->wprio; + + /* + * Only if the (weighted) priority actually changed - so that + * we do not cause any spurious RR side effect - and the + * thread is sleeping on a wait channel, tell the caller to + * reorder the wait list at the first opportunity. We cannot + * do that here since this would trigger ABBA locking issues + * with wchan->lock and/or thread->lock. + * + * CAVEAT: This must be done prior to rescheduling or + * re-enabling irqs in order to prevent priority inversion. + */ + if (old_wprio != new_wprio && thread->wchan) + thread->info |= EVL_T_WCHAN; + + thread->info |= EVL_T_SCHEDP; + /* Ask the target thread to call back if in-band. */ + if ((thread->state & (EVL_T_INBAND|EVL_T_USER)) == (EVL_T_INBAND|EVL_T_USER)) + dovetail_request_ucall(thread->altsched.task); + + return ret; +} + +void __evl_test_cancel(struct evl_thread *curr) +{ + /* + * Just in case evl_test_cancel() is called from an IRQ + * handler, in which case we may not take the exit path. + * + * NOTE: curr->rq is stable from our POV and can't change + * under our feet. + */ + if (curr->rq->local_flags & RQ_IRQ) + return; + + if (!(curr->state & EVL_T_INBAND)) + evl_switch_inband(EVL_HMDIAG_NONE); + + do_exit(0); + /* ... won't return ... */ + EVL_WARN_ON(CORE, 1); +} +EXPORT_SYMBOL_GPL(__evl_test_cancel); + +void __evl_propagate_schedparam_change(struct evl_thread *curr) +{ + int kpolicy = SCHED_FIFO, kprio, ret; + struct task_struct *p = current; + struct sched_param param; + unsigned long flags; + struct evl_rq *rq; + + /* + * Test-set race for EVL_T_SCHEDP is ok, the propagation is meant + * to be done asap but not guaranteed to be carried out + * immediately, and the request will remain pending until it + * is eventually handled. We just have to protect against a + * set-clear race. + */ + rq = evl_get_thread_rq(curr, flags); + kprio = curr->bprio; + curr->info &= ~EVL_T_SCHEDP; + + /* + * Map our policies/priorities to the regular kernel's + * (approximated). + */ + if ((curr->state & EVL_T_WEAK) && kprio == 0) + kpolicy = SCHED_NORMAL; + else if (kprio > EVL_FIFO_MAX_PRIO) + kprio = EVL_FIFO_MAX_PRIO; + + evl_put_thread_rq(curr, rq, flags); + + if (p->policy != kpolicy || (kprio > 0 && p->rt_priority != kprio)) { + param.sched_priority = kprio; + ret = sched_setscheduler_nocheck(p, kpolicy, ¶m); + EVL_WARN_ON(CORE, ret != 0); + } +} + +void evl_unblock_thread(struct evl_thread *thread, int reason) +{ + trace_evl_unblock_thread(thread); + + /* + * We must not raise the EVL_T_BREAK bit if the target thread was + * already runnable at the time of this call, so that + * downstream code does not get confused by some "successful + * but interrupted syscall" condition. IOW, a break state + * raised here must always trigger an error code downstream, + * and a wait which went to completion should not be marked as + * interrupted. + * + * evl_wakeup_thread() guarantees this by updating the info + * bits only if any of the mask bits is set. + */ + evl_wakeup_thread(thread, EVL_T_DELAY|EVL_T_PEND|EVL_T_WAIT, reason|EVL_T_BREAK); +} +EXPORT_SYMBOL_GPL(evl_unblock_thread); + +void evl_kick_thread(struct evl_thread *thread, int info) +{ + struct task_struct *p = thread->altsched.task; + unsigned long flags; + struct evl_rq *rq; + + rq = evl_get_thread_rq(thread, flags); + + if (thread->state & EVL_T_INBAND) + goto out; + + /* + * We might get EVL_T_PTSIG on top of EVL_T_KICKED, never filter out + * the former. + */ + if (!(info & EVL_T_PTSIG) && thread->info & EVL_T_KICKED) + goto out; + + /* See comment in evl_unblock_thread(). */ + evl_wakeup_thread_locked(thread, EVL_T_DELAY|EVL_T_PEND|EVL_T_WAIT, + EVL_T_KICKED|EVL_T_BREAK); + + /* + * If @thread receives multiple ptrace-stop requests, ensure + * that disabling EVL_T_PTJOIN has precedence over enabling for + * the whole set. + */ + if (thread->info & EVL_T_PTSTOP) { + if (thread->info & EVL_T_PTJOIN) + thread->info &= ~EVL_T_PTJOIN; + else + info &= ~EVL_T_PTJOIN; + } + + /* + * CAUTION: we must NOT raise EVL_T_BREAK when clearing a forcible + * block state, such as EVL_T_SUSP, EVL_T_HALT. The caller of + * evl_sleep_on() we unblock shall proceed as for a normal + * return, until it traverses a cancellation point if + * EVL_T_CANCELD was raised earlier, or calls evl_sleep_on() again + * which will detect EVL_T_KICKED and act accordingly. + * + * Rationale: callers of evl_sleep_on() may assume that + * receiving EVL_T_BREAK implicitly means that the awaited event + * was NOT received in the meantime. Therefore, in case only + * EVL_T_SUSP remains set for the thread on entry to + * evl_kick_thread(), after EVL_T_PEND was lifted earlier when the + * wait went to successful completion (i.e. no timeout), then + * we want the kicked thread to know that it did receive the + * requested resource, not finding EVL_T_BREAK in its state word. + * + * Callers of evl_sleep_on() may inquire for EVL_T_KICKED locally + * to detect forcible unblocks from EVL_T_SUSP, EVL_T_HALT, if they + * should act upon this case specifically. + * + * If @thread was frozen by an ongoing ptrace sync sequence + * (EVL_T_PTSYNC), release it so that it can reach the next + * in-band switch point (either from the EVL syscall return + * path, or from the mayday trap). + */ + evl_release_thread_locked(thread, EVL_T_SUSP|EVL_T_HALT|EVL_T_PTSYNC, EVL_T_KICKED); + + /* + * We may send mayday signals to userland threads only. + * However, no need to run a mayday trap if the current thread + * kicks itself out of OOB context: it will switch to in-band + * context on its way back to userland via the current syscall + * epilogue. Otherwise, we want that thread to enter the + * mayday trap asap. + */ + if ((thread->state & EVL_T_USER) && thread != this_evl_rq_thread()) + dovetail_send_mayday(p); + + /* + * Tricky cases: + * + * - a thread which was ready on entry wasn't actually + * running, but nevertheless waits for the CPU in OOB context, + * so we have to make sure that it will be notified of the + * pending break condition as soon as it enters a blocking EVL + * call. + * + * - a ready/readied thread on exit may be prevented from + * running by the scheduling policy module it belongs + * to. Typically, policies enforcing a runtime budget do not + * block threads with no budget, but rather keep them out of + * their run queue, so that ->sched_pick() won't elect + * them. We tell the policy handler about the fact that we do + * want such thread to run until it switches to in-band + * context, whatever this entails internally for the + * implementation. + * + * - if the thread is running on the CPU, raising EVL_T_KICKED is + * enough to force a switch to in-band context on the next + * return to user. + */ + thread->info |= EVL_T_KICKED; + + if (thread->state & EVL_T_READY) { + evl_force_thread(thread); + evl_set_resched(thread->rq); + } + + if (info) + thread->info |= info; +out: + evl_put_thread_rq(thread, rq, flags); +} +EXPORT_SYMBOL_GPL(evl_kick_thread); + +void evl_demote_thread(struct evl_thread *thread) +{ + struct evl_sched_class *sched_class; + union evl_sched_param param; + unsigned long flags; + struct evl_rq *rq; + + rq = evl_get_thread_rq(thread, flags); + + /* + * First demote @thread to the weak class, which still has + * access to EVL resources, but won't compete for real-time + * scheduling anymore. This will prevent @thread from keeping + * the CPU busy in out-of-band context once kicked out from + * wait. + */ + param.weak.prio = 0; + sched_class = &evl_sched_weak; + evl_set_thread_schedparam_locked(thread, sched_class, ¶m); + + evl_put_thread_rq_check(thread, rq, flags); + + /* Then unblock it from any wait state. */ + evl_kick_thread(thread, 0); +} +EXPORT_SYMBOL_GPL(evl_demote_thread); + +struct sig_irqwork_data { + struct evl_thread *thread; + int signo, sigval; + struct irq_work work; +}; + +static void do_inband_signal(struct evl_thread *thread, int signo, int sigval) +{ + struct task_struct *p = thread->altsched.task; + struct kernel_siginfo si; + + trace_evl_inband_signal(thread, signo, sigval); + + if (signo == SIGDEBUG) { + memset(&si, '\0', sizeof(si)); + si.si_signo = signo; + si.si_code = SI_QUEUE; + si.si_int = sigval | sigdebug_marker; + send_sig_info(signo, &si, p); + } else { + send_sig(signo, p, 1); + } +} + +static void sig_irqwork(struct irq_work *work) +{ + struct sig_irqwork_data *sigd; + + sigd = container_of(work, struct sig_irqwork_data, work); + do_inband_signal(sigd->thread, sigd->signo, sigd->sigval); + evl_put_element(&sigd->thread->element); + evl_free(sigd); +} + +void evl_signal_thread(struct evl_thread *thread, int sig, int arg) +{ + struct sig_irqwork_data *sigd; + + if (EVL_WARN_ON(CORE, !(thread->state & EVL_T_USER))) + return; + + if (running_inband()) { + do_inband_signal(thread, sig, arg); + return; + } + + sigd = evl_alloc(sizeof(*sigd)); + init_irq_work(&sigd->work, sig_irqwork); + sigd->thread = thread; + sigd->signo = sig; + sigd->sigval = arg; + + evl_get_element(&thread->element); + /* Cannot fail, irq_work is local to this call. */ + irq_work_queue(&sigd->work); +} +EXPORT_SYMBOL_GPL(evl_signal_thread); + +void evl_notify_thread(struct evl_thread *thread, + int tag, union evl_value details) +{ + if (thread->state & EVL_T_HMSIG) + evl_signal_thread(thread, SIGDEBUG, tag); + + if (thread->state & EVL_T_HMOBS) { + if (!evl_send_observable(thread->observable, tag, details)) + printk_ratelimited(EVL_WARNING + "%s[%d] could not receive HM event #%d", + evl_element_name(&thread->element), + evl_get_inband_pid(thread), + tag); + } +} +EXPORT_SYMBOL_GPL(evl_notify_thread); + +int evl_killall(int mask) +{ + int nrkilled = 0, nrthreads, count; + struct evl_thread *t, *n; + LIST_HEAD(kill_list); + unsigned long flags; + long ret; + + inband_context_only(); + + if (evl_current()) + return -EPERM; + + raw_spin_lock_irqsave(&thread_list_lock, flags); + + nrthreads = evl_nrthreads; + + for_each_evl_thread(t) { + if ((t->state & EVL_T_ROOT) || (t->state & mask) != mask) + continue; + + if (EVL_DEBUG(CORE)) + printk(EVL_INFO "terminating %s[%d]\n", + t->name, evl_get_inband_pid(t)); + + evl_get_element(&t->element); + list_add(&t->kill_next, &kill_list); + } + + raw_spin_unlock_irqrestore(&thread_list_lock, flags); + + list_for_each_entry_safe(t, n, &kill_list, kill_next) { + list_del(&t->kill_next); + nrkilled++; + evl_cancel_thread(t); + evl_put_element(&t->element); + } + + count = nrthreads - nrkilled; + if (EVL_DEBUG(CORE)) + printk(EVL_INFO "waiting for %d %s threads to exit\n", + nrkilled, mask & EVL_T_USER ? "user" : "kernel"); + + ret = wait_event_interruptible(join_all, + evl_nrthreads == count); + + if (EVL_DEBUG(CORE)) + printk(EVL_INFO "joined %d %s threads\n", + count + nrkilled - evl_nrthreads, + mask & EVL_T_USER ? "user" : "kernel"); + + return ret < 0 ? -EINTR : 0; +} +EXPORT_SYMBOL_GPL(evl_killall); + +/* thread->lock held (temporarily dropped), irqs off. */ +struct evl_wait_channel *evl_get_thread_wchan(struct evl_thread *thread) +{ + struct evl_wait_channel *wchan = NULL; + + assert_hard_lock(&thread->lock); + + /* + * Chicken-and-egg: the safe locking order imposed on us by PI + * management is, + * + * lock(wchan->lock) + * lock(thread->lock) + * + * But to safely retrieve the wait channel a thread pends on, + * we need to hold thread->lock. + * + * Escape this ABBA issue between these locks by resorting to + * a trylock pattern until it eventually succeeds. + */ + for (;;) { + wchan = thread->wchan; + if (!wchan || raw_spin_trylock(&wchan->lock)) + break; + + /* + * We need to drop thread->lock temporarily in order + * to allow progress for a concurrent thread + * attempting the opposite locking sequence. Hold a + * reference to prevent @thread from going stale in + * the meantime. + */ + evl_get_element(&thread->element); + raw_spin_unlock(&thread->lock); + cpu_relax(); + raw_spin_lock(&thread->lock); + evl_put_element(&thread->element); + } + + return wchan; +} + +notrace pid_t evl_get_inband_pid(struct evl_thread *thread) +{ + if (thread->state & (EVL_T_ROOT|EVL_T_DORMANT|EVL_T_ZOMBIE)) + return 0; + + if (thread->altsched.task == NULL) + return -1; /* weird */ + + return task_pid_nr(thread->altsched.task); +} + +int activate_oob_mm_state(struct oob_mm_state *p) +{ + evl_init_wait(&p->ptsync_barrier, &evl_mono_clock, EVL_WAIT_PRIO); + INIT_LIST_HEAD(&p->ptrace_sync); + smp_mb__before_atomic(); + set_bit(EVL_MM_ACTIVE_BIT, &p->flags); + + return 0; +} + +static void flush_oob_mm_state(struct oob_mm_state *p) +{ + /* + * We are called for every mm dropped. Since every oob state + * is zeroed before use by the in-band kernel, processes with + * no active out-of-band state will escape this cleanup work + * on test_and_clear_bit(). + */ + if (test_and_clear_bit(EVL_MM_ACTIVE_BIT, &p->flags)) { + EVL_WARN_ON(CORE, !list_empty(&p->ptrace_sync)); + evl_destroy_wait(&p->ptsync_barrier); + } +} + +void arch_inband_task_init(struct task_struct *tsk) +{ + struct oob_thread_state *p = dovetail_task_state(tsk); + + evl_init_thread_state(p); +} + +static inline void note_trap(struct evl_thread *curr, + unsigned int trapnr, struct pt_regs *regs, + const char *msg) +{ + if (user_mode(regs)) + printk(EVL_WARNING + "%s %s [pid=%d, excpt=%d, user_pc=%#lx]\n", + curr->name, msg, + evl_get_inband_pid(curr), + trapnr, + instruction_pointer(regs)); + else + printk(EVL_WARNING + "%s %s [pid=%d, excpt=%d, %pS]\n", + curr->name, msg, + evl_get_inband_pid(curr), + trapnr, + (void *)instruction_pointer(regs)); +} + +/* hard irqs off. */ +void handle_oob_trap_entry(unsigned int trapnr, struct pt_regs *regs) +{ + struct evl_thread *curr; + bool is_bp = false; + int diag; + + trace_evl_thread_fault(trapnr, regs); + + /* + * We may not demote the current task if running in NMI + * context. Just bail out if so. + */ + if (in_nmi()) + return; + + /* + * We might be running oob over a non-dovetailed task context + * (e.g. taking a trap on top of evl_schedule() -> + * run_oob_call()). In this case, there is nothing we + * can/should do, just bail out. + */ + curr = evl_current(); + if (curr == NULL) + return; + + if (curr->local_info & EVL_T_INFAULT) { + note_trap(curr, trapnr, regs, "recursive fault"); + return; + } + + oob_context_only(); + + curr->local_info |= EVL_T_INFAULT; + + if (current->ptrace & PT_PTRACED) + is_bp = evl_is_breakpoint(trapnr); + + if ((EVL_DEBUG(CORE) || (curr->state & EVL_T_WOSS)) && !is_bp) + note_trap(curr, trapnr, regs, "switching in-band"); + + /* + * We received a trap on the oob stage, switch to in-band + * before handling the exception. + */ + diag = is_bp ? EVL_HMDIAG_TRAP : EVL_HMDIAG_EXDEMOTE; + if (user_mode(regs)) + evl_switch_inband_details(diag, evl_intval(instruction_pointer(regs))); + else + evl_switch_inband(diag); +} + +/* hard irqs off */ +void handle_oob_trap_exit(unsigned int trapnr, struct pt_regs *regs) +{ + struct evl_thread *curr = evl_current(); + bool is_bp = false; + int ret; + + if (in_nmi()) + return; + + hard_local_irq_enable(); + + if (curr == NULL) + return; + + curr->local_info &= ~EVL_T_INFAULT; + + if (current->ptrace & PT_PTRACED) + is_bp = evl_is_breakpoint(trapnr); + + /* + * Switch back to the oob stage only after recovering from a + * trap in kernel space, which ensures a consistent execution + * state, e.g. if the current task is holding an EVL mutex or + * stax. If the trap occurred in user space, we can leave it + * to the common lazy stage switching strategy since the + * syscall barrier is there to reinstate the proper stage if + * need be. + */ + if (!user_mode(regs)) { + ret = evl_switch_oob(); + if ((EVL_DEBUG(CORE) || (curr->state & EVL_T_WOSS)) && !is_bp) + note_trap(curr, trapnr, regs, + ret ? "failed to resume out-of-band" : + "resuming out-of-band"); + } + + hard_local_irq_disable(); +} + +void handle_oob_mayday(struct pt_regs *regs) +{ + struct evl_thread *curr = evl_current(); + + if (EVL_WARN_ON(CORE, !(curr->state & EVL_T_USER))) + return; + + /* + * It might happen that a thread gets a mayday trap right + * after it switched to in-band mode while returning from a + * syscall. Filter this case out. + */ + if (!(curr->state & EVL_T_INBAND)) + evl_switch_inband(EVL_HMDIAG_NONE); +} + +static void handle_migration_event(struct dovetail_migration_data *d) +{ +#ifdef CONFIG_SMP + struct task_struct *p = d->task; + struct evl_thread *thread; + + thread = evl_thread_from_task(p); + if (thread == NULL) + return; + + /* + * Detect an EVL thread sleeping in OOB context which is + * required to migrate to another CPU by the in-band kernel. + * + * We may NOT fix up thread->sched immediately using the + * migration call, because the latter always has to take place + * on behalf of the target thread itself while running + * in-band. Therefore, that thread needs to switch to in-band + * context first, so that check_cpu_affinity() may do the + * fixup at the next transition to OOB. We expedite such + * transition for user threads by requesting them to call back + * asap via the RETUSER event. + */ + if (thread->state & (EVL_THREAD_BLOCK_BITS & ~EVL_T_INBAND)) { + evl_kick_thread(thread, 0); + evl_schedule(); + if (thread->state & EVL_T_USER) + dovetail_request_ucall(thread->altsched.task); + } +#endif +} + +static void handle_sigwake_event(struct task_struct *p) +{ + struct evl_thread *thread; + sigset_t sigpending; + bool ptsync = false; + int info = 0; + + thread = evl_thread_from_task(p); + if (thread == NULL) + return; + + if (thread->state & EVL_T_USER && p->ptrace & PT_PTRACED) { + /* We already own p->sighand->siglock. */ + sigorsets(&sigpending, + &p->pending.signal, + &p->signal->shared_pending.signal); + + if (sigismember(&sigpending, SIGINT) || + sigismember(&sigpending, SIGTRAP)) { + info = EVL_T_PTSIG|EVL_T_PTSTOP; + ptsync = true; + } + /* + * CAUTION: we want T_JOIN to appear whenever SIGSTOP + * is present, regardless of other signals which might + * be pending. + */ + if (sigismember(&sigpending, SIGSTOP)) + info |= EVL_T_PTSIG|EVL_T_PTSTOP|EVL_T_PTJOIN; + } + + /* + * A thread running on the oob stage may not be picked by the + * in-band scheduler as it bears the _TLF_OFFSTAGE flag. We + * need to force that thread to switch to in-band context, + * which will clear that flag. If we got there due to a ptrace + * signal, then setting EVL_T_PTSTOP ensures that @thread will be + * released from EVL_T_PTSYNC and will not receive any WOSS alert + * next time it switches in-band. + */ + evl_kick_thread(thread, info); + + /* + * Start a ptrace sync sequence if @thread is the initial stop + * target and runs oob. It is important to do this asap, so + * that sibling threads from the same process which also run + * oob cannot delay the in-band ptrace chores on this CPU, + * moving too far away from the stop point. + */ + if (ptsync) + evl_start_ptsync(thread); + + evl_schedule(); +} + +/* curr locked, curr->rq locked. */ +static void join_ptsync(struct evl_thread *curr) +{ + struct oob_mm_state *oob_mm = curr->oob_mm; + + raw_spin_lock(&oob_mm->ptsync_barrier.wchan.lock); + + /* In non-stop mode, no ptsync sequence is started. */ + if (test_bit(EVL_MM_PTSYNC_BIT, &oob_mm->flags) && + list_empty(&curr->ptsync_next)) + list_add_tail(&curr->ptsync_next, &oob_mm->ptrace_sync); + + raw_spin_unlock(&oob_mm->ptsync_barrier.wchan.lock); +} + +static int leave_ptsync(struct evl_thread *leaver) +{ + struct oob_mm_state *oob_mm = leaver->oob_mm; + unsigned long flags; + int ret = 0; + + raw_spin_lock_irqsave(&oob_mm->ptsync_barrier.wchan.lock, flags); + + if (!test_bit(EVL_MM_PTSYNC_BIT, &oob_mm->flags)) + goto out; + + ret = -1; + if (!list_empty(&leaver->ptsync_next)) + list_del_init(&leaver->ptsync_next); + + if (list_empty(&oob_mm->ptrace_sync)) { + clear_bit(EVL_MM_PTSYNC_BIT, &oob_mm->flags); + ret = 1; + } +out: + raw_spin_unlock_irqrestore(&oob_mm->ptsync_barrier.wchan.lock, flags); + + return ret; +} + +static void skip_ptsync(struct evl_thread *thread) +{ + struct oob_mm_state *oob_mm = thread->oob_mm; + + if (test_bit(EVL_MM_ACTIVE_BIT, &oob_mm->flags) && + leave_ptsync(thread) > 0) { + evl_flush_wait(&oob_mm->ptsync_barrier, 0); + evl_schedule(); + } +} + +static void handle_ptstop_event(void) +{ + struct evl_thread *curr = evl_current(); + unsigned long flags; + struct evl_rq *rq; + + /* + * EVL_T_PTRACE denotes a stopped state as defined by ptrace() + * which means blocked in ptrace_stop(). Our EVL_T_PTSTOP bit has + * a broader scope which starts from the in-band request to + * stop (handle_sigwake_event()), then ends after the tracee + * switched back to oob context via RETUSER handler. + */ + rq = evl_get_thread_rq(curr, flags); + + curr->state |= EVL_T_PTRACE; + + /* + * If we were running out-of-band when SIGSTOP reached us, we + * have to join the ptsync queue. + */ + if (curr->info & EVL_T_PTJOIN) { + join_ptsync(curr); + curr->info &= ~EVL_T_PTJOIN; + } + + evl_put_thread_rq(curr, rq, flags); +} + +static void handle_ptstep_event(struct task_struct *task) +{ + struct evl_thread *tracee = evl_thread_from_task(task); + + /* + * The ptracer might have switched focus, (single-)stepping a + * thread which did not hit the latest breakpoint + * (i.e. bearing EVL_T_PTJOIN). For this reason, we do need to + * listen to PTSTEP events to remove that thread from the + * ptsync queue. + */ + skip_ptsync(tracee); +} + +static void handle_ptcont_event(void) +{ + struct evl_thread *curr = evl_current(); + + if (curr->state & EVL_T_PTRACE) { + /* + * Since we stopped executing due to ptracing, any + * ongoing periodic timeline is now lost: disable + * overrun detection for the next round. + */ + curr->local_info |= EVL_T_IGNOVR; + + /* + * Request to receive INBAND_TASK_RETUSER on the + * return path to user mode so that we can switch back + * to out-of-band mode for synchronizing on the ptsync + * barrier. + */ + dovetail_request_ucall(current); + } +} + +/* oob stage, hard irqs on. */ +static int ptrace_sync(void) +{ + struct evl_thread *curr = evl_current(); + struct oob_mm_state *oob_mm = curr->oob_mm; + struct evl_rq *this_rq = curr->rq; + unsigned long flags; + bool sigpending; + int ret; + + /* + * The last thread resuming from a ptsync to switch back to + * out-of-band mode has to release the others which have been + * waiting for this event on the ptrace sync barrier. + */ + sigpending = signal_pending(current); + ret = leave_ptsync(curr); + if (ret > 0) { + evl_flush_wait(&oob_mm->ptsync_barrier, 0); + ret = 0; + } else if (ret < 0) + ret = sigpending ? -ERESTARTSYS : + evl_wait_event(&oob_mm->ptsync_barrier, + list_empty(&oob_mm->ptrace_sync)); + + raw_spin_lock_irqsave(&this_rq->lock, flags); + + /* + * If we got interrupted while waiting on the ptsync barrier, + * make sure pick_next_thread() will let us slip through again + * by keeping EVL_T_PTSTOP set. + */ + if (!ret && !(curr->info & EVL_T_PTSIG)) { + curr->info &= ~EVL_T_PTSTOP; + curr->state &= ~EVL_T_PTRACE; + } + + raw_spin_unlock_irqrestore(&this_rq->lock, flags); + + return ret ? -ERESTARTSYS : 0; +} + +static void handle_retuser_event(void) +{ + struct evl_thread *curr = evl_current(); + int ret; + + ret = evl_switch_oob(); + if (ret) { + /* Ask for retry until we succeed. */ + dovetail_request_ucall(current); + return; + } + + if (!(curr->state & EVL_T_PTRACE)) + return; + + ret = ptrace_sync(); + if (ret) + dovetail_request_ucall(current); + + evl_schedule(); + + if ((curr->state & EVL_T_WEAK) && + atomic_read(&curr->held_mutex_count) == 0) + evl_switch_inband(EVL_HMDIAG_NONE); +} + +static void handle_cleanup_event(struct mm_struct *mm) +{ + struct evl_thread *curr = evl_current(); + + /* + * This event is fired whenever a user task is dropping its + * mm. + * + * Detect an EVL thread running exec(), i.e. still attached to + * the current in-band task but not bearing PF_EXITING, which + * indicates that it did not call do_exit(). In this case, we + * emulate a task exit, since the EVL binding shall not + * survive the exec() syscall. We may get there after + * cleanup_current_thread() already ran, so check @curr for + * NULL. + * + * Alwausrelease the oob state for the dropped mm if any, + * EVL_MM_ACTIVE_BIT tells us if we have one. + */ + if (curr && !(current->flags & PF_EXITING)) + put_current_thread(); + + flush_oob_mm_state(&mm->oob_state); +} + +void handle_inband_event(enum inband_event_type event, void *data) +{ + switch (event) { + case INBAND_TASK_SIGNAL: + handle_sigwake_event(data); + break; + case INBAND_TASK_EXIT: + evl_drop_subscriptions(evl_get_subscriber()); + if (evl_current()) + put_current_thread(); + break; + case INBAND_TASK_MIGRATION: + handle_migration_event(data); + break; + case INBAND_TASK_RETUSER: + handle_retuser_event(); + break; + case INBAND_TASK_PTSTOP: + handle_ptstop_event(); + break; + case INBAND_TASK_PTCONT: + handle_ptcont_event(); + break; + case INBAND_TASK_PTSTEP: + handle_ptstep_event(data); + break; + case INBAND_PROCESS_CLEANUP: + handle_cleanup_event(data); + break; + } +} + +/* thread->lock + thread->rq->lock held, irqs off */ +static int set_time_slice(struct evl_thread *thread, ktime_t quantum) +{ + struct evl_rq *rq = thread->rq; + + assert_thread_pinned(thread); + + thread->rrperiod = quantum; + + if (!timeout_infinite(quantum)) { + if (quantum <= evl_get_clock_gravity(&evl_mono_clock, user)) + return -EINVAL; + + if (thread->base_class->sched_yield == NULL) + return -EINVAL; + + thread->state |= EVL_T_RRB; + if (rq->curr == thread) + evl_start_timer(&rq->rrbtimer, + evl_abs_timeout(&rq->rrbtimer, quantum), + EVL_INFINITE); + } else { + thread->state &= ~EVL_T_RRB; + if (rq->curr == thread) + evl_stop_timer(&rq->rrbtimer); + } + + return 0; +} + +static int set_sched_attrs(struct evl_thread *thread, + const struct evl_sched_attrs *attrs) +{ + struct evl_sched_class *sched_class; + union evl_sched_param param; + unsigned long flags; + struct evl_rq *rq; + ktime_t tslice; + int ret; + + trace_evl_thread_setsched(thread, attrs); + + rq = evl_get_thread_rq(thread, flags); + + tslice = thread->rrperiod; + sched_class = evl_find_sched_class(¶m, attrs, &tslice); + if (IS_ERR(sched_class)) { + evl_put_thread_rq(thread, rq, flags); + return PTR_ERR(sched_class); + } + + ret = set_time_slice(thread, tslice); + if (ret) { + evl_put_thread_rq(thread, rq, flags); + return ret; + } + + ret = evl_set_thread_schedparam_locked(thread, sched_class, ¶m); + + evl_put_thread_rq_check(thread, rq, flags); + + return ret; +} + +static void __get_sched_attrs(struct evl_sched_class *sched_class, + struct evl_thread *thread, + struct evl_sched_attrs *attrs) +{ + union evl_sched_param param; + + assert_thread_pinned(thread); + + attrs->sched_policy = sched_class->policy; + + sched_class->sched_getparam(thread, ¶m); + + if (sched_class == &evl_sched_fifo) { + if (thread->state & EVL_T_RRB) { + attrs->sched_rr_quantum = + ktime_to_u_timespec(thread->rrperiod); + attrs->sched_policy = SCHED_RR; + } + goto out; + } + +#ifdef CONFIG_EVL_SCHED_QUOTA + if (sched_class == &evl_sched_quota) { + attrs->sched_quota_group = param.quota.tgid; + goto out; + } +#endif + +#ifdef CONFIG_EVL_SCHED_TP + if (sched_class == &evl_sched_tp) { + attrs->sched_tp_partition = param.tp.ptid; + goto out; + } +#endif + +out: + trace_evl_thread_getsched(thread, attrs); +} + +static void get_sched_attrs(struct evl_thread *thread, + struct evl_sched_attrs *attrs) +{ + unsigned long flags; + struct evl_rq *rq; + + rq = evl_get_thread_rq(thread, flags); + /* Get the base scheduling attributes. */ + attrs->sched_priority = thread->bprio; + __get_sched_attrs(thread->base_class, thread, attrs); + evl_put_thread_rq(thread, rq, flags); +} + +void evl_get_thread_state(struct evl_thread *thread, + struct evl_thread_state *statebuf) +{ + unsigned long flags; + struct evl_rq *rq; + + rq = evl_get_thread_rq(thread, flags); + /* Get the effective scheduling attributes. */ + statebuf->eattrs.sched_priority = thread->cprio; + __get_sched_attrs(thread->sched_class, thread, &statebuf->eattrs); + statebuf->cpu = evl_rq_cpu(thread->rq); + statebuf->state = evl_rq_cpu(thread->rq); + statebuf->isw = evl_get_counter(&thread->stat.isw); + statebuf->csw = evl_get_counter(&thread->stat.csw); + statebuf->sc = evl_get_counter(&thread->stat.sc); + statebuf->rwa = evl_get_counter(&thread->stat.rwa); + statebuf->xtime = ktime_to_ns(evl_get_account_total( + &thread->stat.account)); + evl_put_thread_rq(thread, rq, flags); +} +EXPORT_SYMBOL_GPL(evl_get_thread_state); + +static int update_mode(struct evl_thread *thread, __u32 mask, + __u32 *oldmask, bool set) +{ + unsigned long flags; + struct evl_rq *rq; + + trace_evl_thread_update_mode(thread, mask, set); + + if (mask & ~EVL_THREAD_MODE_BITS) + return -EINVAL; + + if (set) { + /* EVL_T_HMOBS requires observability of @thread. */ + if (mask & EVL_T_HMOBS && thread->observable == NULL) + return -EINVAL; + /* Default to EVL_T_HMSIG if not specified. */ + if (!(mask & (EVL_T_HMSIG|EVL_T_HMOBS))) + mask |= EVL_T_HMSIG; + } + + rq = evl_get_thread_rq(thread, flags); + + *oldmask = thread->state & EVL_THREAD_MODE_BITS; + + if (likely(mask)) { + if (set) { + thread->state |= mask; + } else { + thread->state &= ~mask; + if (!(thread->state & (EVL_T_WOSS|EVL_T_WOLI|EVL_T_WOSX|EVL_T_WOSO))) + thread->state &= ~(EVL_T_HMSIG|EVL_T_HMOBS); + else if (!(thread->state & (EVL_T_HMSIG|EVL_T_HMOBS))) + thread->state &= ~(EVL_T_WOSS|EVL_T_WOLI|EVL_T_WOSX|EVL_T_WOSO); + } + } + + evl_put_thread_rq(thread, rq, flags); + + return 0; +} + +static long thread_common_ioctl(struct evl_thread *thread, + unsigned int cmd, unsigned long arg) +{ + struct evl_thread_state statebuf; + struct evl_sched_attrs attrs; + __u32 mask, oldmask; + long ret = 0; + + switch (cmd) { + case EVL_THRIOC_SET_SCHEDPARAM: + ret = raw_copy_from_user(&attrs, + (struct evl_sched_attrs *)arg, sizeof(attrs)); + if (ret) + return -EFAULT; + ret = set_sched_attrs(thread, &attrs); + break; + case EVL_THRIOC_GET_SCHEDPARAM: + get_sched_attrs(thread, &attrs); + ret = raw_copy_to_user((struct evl_sched_attrs *)arg, + &attrs, sizeof(attrs)); + if (ret) + return -EFAULT; + break; + case EVL_THRIOC_GET_STATE: + evl_get_thread_state(thread, &statebuf); + ret = raw_copy_to_user((struct evl_thread_state *)arg, + &statebuf, sizeof(statebuf)); + if (ret) + return -EFAULT; + break; + case EVL_THRIOC_SET_MODE: + case EVL_THRIOC_CLEAR_MODE: + ret = raw_get_user(mask, (__u32 *)arg); + if (ret) + return -EFAULT; + ret = update_mode(thread, mask, &oldmask, + cmd == EVL_THRIOC_SET_MODE); + if (ret) + return ret; + ret = raw_put_user(oldmask, (__u32 *)arg); + if (ret) + return -EFAULT; + break; + case EVL_THRIOC_UNBLOCK: + evl_unblock_thread(thread, 0); + break; + case EVL_THRIOC_DEMOTE: + evl_demote_thread(thread); + break; + default: + ret = -ENOTTY; + } + + evl_schedule(); + + return ret; +} + +static long thread_oob_ioctl(struct file *filp, unsigned int cmd, + unsigned long arg) +{ + struct evl_thread *thread = element_of(filp, struct evl_thread); + struct evl_thread *curr = evl_current(); + long ret = -EPERM; + __u32 monfd; + + if (thread->state & EVL_T_ZOMBIE) + return -ESTALE; + + switch (cmd) { + case EVL_THRIOC_SWITCH_OOB: + if (thread == curr) + ret = 0; /* Already there. */ + break; + case EVL_THRIOC_SWITCH_INBAND: + if (thread == curr) { + evl_switch_inband(EVL_HMDIAG_NONE); + ret = 0; + } + break; + case EVL_THRIOC_SIGNAL: + ret = raw_get_user(monfd, (__u32 *)arg); + if (ret) + return -EFAULT; + ret = evl_signal_monitor_targeted(thread, monfd); + break; + case EVL_THRIOC_YIELD: + evl_release_thread(curr, 0, 0); + evl_schedule(); + ret = 0; + break; + default: + ret = thread_common_ioctl(thread, cmd, arg); + } + + return ret; +} + +static long thread_ioctl(struct file *filp, unsigned int cmd, + unsigned long arg) +{ + struct evl_thread *thread = element_of(filp, struct evl_thread); + struct evl_thread *curr = evl_current(); + long ret = -EPERM; + + if (thread->state & EVL_T_ZOMBIE) + return -ESTALE; + + switch (cmd) { + case EVL_THRIOC_SWITCH_INBAND: + if (thread == curr) + ret = 0; + break; + case EVL_THRIOC_DETACH_SELF: + ret = evl_detach_self(); + break; + case EVL_THRIOC_JOIN: + ret = evl_join_thread(thread, false); + break; + case EVL_OBSIOC_SUBSCRIBE: + case EVL_OBSIOC_UNSUBSCRIBE: + if (thread->observable) + ret = evl_ioctl_observable(thread->observable, + cmd, arg); + break; + default: + ret = thread_common_ioctl(thread, cmd, arg); + } + + return ret; +} + +static ssize_t thread_oob_read(struct file *filp, + char __user *u_buf, size_t count) +{ + struct evl_thread *thread = element_of(filp, struct evl_thread); + + if (thread->observable == NULL) + return -EPERM; + + return evl_read_observable(thread->observable, u_buf, count, + !(filp->f_flags & O_NONBLOCK)); +} + +static ssize_t thread_oob_write(struct file *filp, + const char __user *u_buf, size_t count) +{ + struct evl_thread *thread = element_of(filp, struct evl_thread); + + if (thread->observable == NULL) + return -EPERM; + + return evl_write_observable(thread->observable, u_buf, count); +} + +static __poll_t thread_oob_poll(struct file *filp, + struct oob_poll_wait *wait) +{ + struct evl_thread *thread = element_of(filp, struct evl_thread); + + if (thread->observable == NULL) + return POLLERR; + + return evl_oob_poll_observable(thread->observable, wait); +} + +static ssize_t thread_write(struct file *filp, const char __user *u_buf, + size_t count, loff_t *ppos) +{ + struct evl_thread *thread = element_of(filp, struct evl_thread); + + if (thread->observable == NULL) + return -EPERM; + + return evl_write_observable(thread->observable, u_buf, count); +} + +static ssize_t thread_read(struct file *filp, char __user *u_buf, + size_t count, loff_t *ppos) +{ + struct evl_thread *thread = element_of(filp, struct evl_thread); + + if (thread->observable == NULL) + return -EPERM; + + return evl_read_observable(thread->observable, u_buf, count, + !(filp->f_flags & O_NONBLOCK)); +} + +static __poll_t thread_poll(struct file *filp, poll_table *pt) +{ + struct evl_thread *thread = element_of(filp, struct evl_thread); + + if (thread->observable == NULL) + return POLLERR; + + return evl_poll_observable(thread->observable, filp, pt); +} + +bool evl_is_thread_file(struct file *filp) +{ + return filp->f_op == &thread_fops; +} + +static const struct file_operations thread_fops = { + .open = evl_open_element, + .release = evl_release_element, + .unlocked_ioctl = thread_ioctl, + .oob_ioctl = thread_oob_ioctl, +#ifdef CONFIG_COMPAT + .compat_ioctl = compat_ptr_ioctl, + .compat_oob_ioctl = compat_ptr_oob_ioctl, +#endif + /* For observability. */ + .oob_read = thread_oob_read, + .oob_write = thread_oob_write, + .oob_poll = thread_oob_poll, + .read = thread_read, + .write = thread_write, + .poll = thread_poll, +}; + +static int map_uthread_self(struct evl_thread *thread) +{ + struct mm_struct *mm = current->mm; + struct evl_user_window *u_window; + struct cred *newcap; + + /* mlockall(MCL_FUTURE) required. */ + if (!(mm->def_flags & VM_LOCKED)) + return -EINVAL; + + u_window = evl_zalloc_chunk(&evl_shared_heap, sizeof(*u_window)); + if (u_window == NULL) + return -ENOMEM; + + /* + * Raise capababilities of user threads when attached to the + * core. Filtering access to /dev/evl/control can be used to + * restrict attachment. + */ + thread->raised_cap = CAP_EMPTY_SET; + newcap = prepare_creds(); + if (newcap == NULL) + return -ENOMEM; + + add_u_cap(thread, newcap, CAP_SYS_NICE); + add_u_cap(thread, newcap, CAP_IPC_LOCK); + add_u_cap(thread, newcap, CAP_SYS_RAWIO); + commit_creds(newcap); + + /* + * CAUTION: From that point, we assume the mapping won't fail, + * therefore there is no added capability to drop in + * discard_unmapped_uthread(). + */ + thread->u_window = u_window; + pin_to_initial_cpu(thread); + trace_evl_thread_map(thread); + + dovetail_init_altsched(&thread->altsched); + set_oob_threadinfo(thread); + set_oob_mminfo(thread); + + /* + * CAUTION: we enable dovetailing only when *thread is + * consistent, so that we won't trigger false positive in + * debug code from handle_schedule_event() and friends. + */ + dovetail_start_altsched(); + + /* + * A user-space thread is already started EVL-wise since we + * have an underlying in-band context for it, so we can + * enqueue it now. + */ + enqueue_new_thread(thread); + evl_release_thread(thread, EVL_T_DORMANT, 0); + evl_sync_uwindow(thread); + + return 0; +} + +/* + * Deconstruct a thread we just failed to map over a userland task. + * Since the former must be dormant, it can't be part of any runqueue. + * The caller is in charge of freeing @thread. + */ +static void discard_unmapped_uthread(struct evl_thread *thread) +{ + evl_destroy_timer(&thread->rtimer); + evl_destroy_timer(&thread->ptimer); + dequeue_old_thread(thread); + + if (thread->u_window) + evl_free_chunk(&evl_shared_heap, thread->u_window); +} + +static struct evl_element * +thread_factory_build(struct evl_factory *fac, const char __user *u_name, + void __user *u_attrs, int clone_flags, u32 *state_offp) +{ + struct evl_observable *observable = NULL; + struct task_struct *tsk = current; + struct evl_init_thread_attr iattr; + unsigned char comm[sizeof(tsk->comm)]; + struct evl_thread *curr; + int ret; + + if (evl_current()) + return ERR_PTR(-EBUSY); + + if (clone_flags & ~EVL_THREAD_CLONE_FLAGS) + return ERR_PTR(-EINVAL); + + /* @current must open the control device first. */ + if (!test_bit(EVL_MM_ACTIVE_BIT, &dovetail_mm_state()->flags)) + return ERR_PTR(-EPERM); + + curr = kzalloc(sizeof(*curr), GFP_KERNEL); + if (curr == NULL) + return ERR_PTR(-ENOMEM); + + ret = evl_init_user_element(&curr->element, &evl_thread_factory, + u_name, clone_flags); + if (ret) + goto fail_element; + + iattr.flags = EVL_T_USER; + + if (clone_flags & EVL_CLONE_OBSERVABLE) { + /* + * Accessing the observable is done via the thread + * element (if public), so clear the public flag for + * the observable itself. + */ + observable = evl_alloc_observable( + u_name, clone_flags & ~EVL_CLONE_PUBLIC); + if (IS_ERR(observable)) { + ret = PTR_ERR(observable); + goto fail_observable; + } + /* + * Element name was already set from user input by + * evl_alloc_observable(). evl_create_core_element_device() + * is told to skip name assignment (NULL name). + */ + ret = evl_create_core_element_device( + &observable->element, + &evl_observable_factory, NULL); + if (ret) + goto fail_observable_dev; + observable = observable; + } else if (clone_flags & EVL_CLONE_UNICAST) { + ret = -EINVAL; + goto fail_observable; + } + + iattr.affinity = cpu_possible_mask; + iattr.observable = observable; + iattr.sched_class = &evl_sched_weak; + iattr.sched_param.weak.prio = 0; + ret = evl_init_thread(curr, &iattr, NULL, "%s", + evl_element_name(&curr->element)); + if (ret) + goto fail_thread; + + ret = map_uthread_self(curr); + if (ret) + goto fail_map; + + *state_offp = evl_shared_offset(curr->u_window); + evl_index_factory_element(&curr->element); + + /* + * Unlike most elements, a thread may exist in absence of any + * file reference, so we get a reference on the emerging + * thread here to block automatic disposal on last file + * release. put_current_thread() drops this reference when the + * thread exits, or voluntarily detaches by sending the + * EVL_THRIOC_DETACH_SELF control request. + */ + evl_get_element(&curr->element); + + strncpy(comm, evl_element_name(&curr->element), sizeof(comm)); + comm[sizeof(comm) - 1] = '\0'; + set_task_comm(tsk, comm); + proc_comm_connector(tsk); + + return &curr->element; + +fail_map: + discard_unmapped_uthread(curr); +fail_thread: + if (observable) +fail_observable_dev: + evl_put_element(&observable->element); /* ->dispose() */ +fail_observable: + evl_destroy_element(&curr->element); +fail_element: + kfree(curr); + + return ERR_PTR(ret); +} + +static void thread_factory_dispose(struct evl_element *e) +{ + struct evl_thread *thread; + int state; + + thread = container_of(e, struct evl_thread, element); + state = thread->state; + + /* + * Two ways to get into the disposal handler: either + * open_factory_node() failed creating a device for @thread + * which is current, or after the last file reference to + * @thread was dropped after exit. EVL_T_ZOMBIE cleared denotes + * the first case, otherwise @thread has existed, is now dead + * and no more reachable, so we can wakeup joiners if any. + */ + if (likely(state & EVL_T_ZOMBIE)) { + if (thread->observable) + evl_put_element(&thread->observable->element); + evl_destroy_element(&thread->element); + complete_all(&thread->exited); /* evl_join_thread() */ + if (waitqueue_active(&join_all)) /* evl_killall() */ + wake_up(&join_all); + } else { + if (EVL_WARN_ON(CORE, evl_current() != thread)) + return; + if (thread->observable) + evl_put_element(&thread->observable->element); + cleanup_current_thread(); + evl_destroy_element(&thread->element); + } + + if (state & EVL_T_USER) + kfree_rcu(thread, element.rcu); +} + +static ssize_t state_show(struct device *dev, + struct device_attribute *attr, + char *buf) +{ + struct evl_thread *thread; + ssize_t ret; + + thread = evl_get_element_by_dev(dev, struct evl_thread); + if (thread == NULL) + return -EIO; + + ret = snprintf(buf, PAGE_SIZE, "%#x\n", thread->state); + + evl_put_element(&thread->element); + + return ret; +} +static DEVICE_ATTR_RO(state); + +static ssize_t sched_show(struct device *dev, + struct device_attribute *attr, + char *buf) +{ + struct evl_sched_class *sched_class; + struct evl_thread *thread; + int bprio, cprio, cpu; + unsigned long flags; + ssize_t ret, _ret; + + thread = evl_get_element_by_dev(dev, struct evl_thread); + if (thread == NULL) + return -EIO; + + raw_spin_lock_irqsave(&thread->lock, flags); + + sched_class = thread->sched_class; + bprio = thread->bprio; + cprio = thread->cprio; + cpu = evl_rq_cpu(thread->rq); + + ret = snprintf(buf, PAGE_SIZE, "%d %d %d %s ", + cpu, bprio, cprio, sched_class->sched_name(thread)); + + if (sched_class->sched_show) { + _ret = sched_class->sched_show(thread, buf + ret, + PAGE_SIZE - ret); + if (_ret > 0) { + ret += _ret; + goto out; + } + } + + /* overwrites trailing whitespace */ + buf[ret - 1] = '\n'; +out: + raw_spin_unlock_irqrestore(&thread->lock, flags); + evl_put_element(&thread->element); + + return ret; +} +static DEVICE_ATTR_RO(sched); + +#ifdef CONFIG_EVL_RUNSTATS + +static ssize_t stats_show(struct device *dev, + struct device_attribute *attr, + char *buf) +{ + ktime_t period, exectime, account, total; + struct evl_thread *thread; + unsigned long flags; + struct evl_rq *rq; + ssize_t ret; + int usage; + + thread = evl_get_element_by_dev(dev, struct evl_thread); + if (thread == NULL) + return -EIO; + + raw_spin_lock_irqsave(&thread->lock, flags); + + rq = evl_thread_rq(thread); + + period = rq->last_account_switch - thread->stat.lastperiod.start; + if (period == 0 && thread == rq->curr) { + exectime = ktime_set(0, 1); + account = ktime_set(0, 1); + } else { + exectime = thread->stat.account.total - + thread->stat.lastperiod.total; + account = period; + } + + total = thread->stat.account.total; + thread->stat.lastperiod.total = total; + thread->stat.lastperiod.start = rq->last_account_switch; + + raw_spin_unlock_irqrestore(&thread->lock, flags); + + if (account) { + while (account > 0xffffffffUL) { + exectime >>= 16; + account >>= 16; + } + + exectime = ns_to_ktime(ktime_to_ns(exectime) * 1000LL + + ktime_to_ns(account) / 2); + usage = ktime_divns(exectime, ktime_to_ns(account)); + } else + usage = 0; + + ret = snprintf(buf, PAGE_SIZE, "%lu %lu %lu %lu %Lu %d\n", + thread->stat.isw.counter, + thread->stat.csw.counter, + thread->stat.sc.counter, + thread->stat.rwa.counter, + total, + usage); + + evl_put_element(&thread->element); + + return ret; +} + +#else + +static ssize_t stats_show(struct device *dev, + struct device_attribute *attr, + char *buf) +{ + return snprintf(buf, PAGE_SIZE, "0 0 0 0 0\n"); +} + +#endif /* !CONFIG_EVL_RUNSTATS */ + +static DEVICE_ATTR_RO(stats); + +static ssize_t timeout_show(struct device *dev, + struct device_attribute *attr, + char *buf) +{ + struct evl_thread *thread; + ssize_t ret; + + thread = evl_get_element_by_dev(dev, struct evl_thread); + if (thread == NULL) + return -EIO; + + ret = snprintf(buf, PAGE_SIZE, "%Lu\n", + ktime_to_ns(evl_get_thread_timeout(thread))); + + evl_put_element(&thread->element); + + return ret; +} +static DEVICE_ATTR_RO(timeout); + +static ssize_t pid_show(struct device *dev, + struct device_attribute *attr, + char *buf) +{ + struct evl_thread *thread; + ssize_t ret; + + thread = evl_get_element_by_dev(dev, struct evl_thread); + if (thread == NULL) + return -EIO; + + ret = snprintf(buf, PAGE_SIZE, "%d\n", evl_get_inband_pid(thread)); + + evl_put_element(&thread->element); + + return ret; +} +static DEVICE_ATTR_RO(pid); + +static ssize_t observable_show(struct device *dev, + struct device_attribute *attr, + char *buf) +{ + struct evl_thread *thread; + ssize_t ret; + + thread = evl_get_element_by_dev(dev, struct evl_thread); + if (thread == NULL) + return -EIO; + + ret = snprintf(buf, PAGE_SIZE, "%d\n", + evl_element_is_observable(&thread->element)); + + evl_put_element(&thread->element); + + return ret; +} +static DEVICE_ATTR_RO(observable); + +static ssize_t wchan_show(struct device *dev, + struct device_attribute *attr, + char *buf) +{ + struct evl_wait_channel *wchan; + struct evl_thread *thread; + unsigned long flags; + ssize_t ret; + + /* + * Reading the wait channel is a sensitive operation: + * safety-wise, and performance-wise since this locks the + * thread scheduling state and disables interrupts in the + * process. Reserve this to authorized users. + */ + if (!evl_may_access_factory(&evl_thread_factory)) + return -EPERM; + + thread = evl_get_element_by_dev(dev, struct evl_thread); + if (thread == NULL) + return -EIO; + + raw_spin_lock_irqsave(&thread->lock, flags); + wchan = thread->wchan; + ret = snprintf(buf, PAGE_SIZE, "%s\n", wchan ? wchan->name : "-"); + raw_spin_unlock_irqrestore(&thread->lock, flags); + + evl_put_element(&thread->element); + + return ret; +} +static DEVICE_ATTR_RO(wchan); + +static struct attribute *thread_attrs[] = { + &dev_attr_state.attr, + &dev_attr_sched.attr, + &dev_attr_timeout.attr, + &dev_attr_stats.attr, + &dev_attr_pid.attr, + &dev_attr_observable.attr, + &dev_attr_wchan.attr, + NULL, +}; +ATTRIBUTE_GROUPS(thread); + +struct evl_factory evl_thread_factory = { + .name = EVL_THREAD_DEV, + .fops = &thread_fops, + .build = thread_factory_build, + .dispose = thread_factory_dispose, + .nrdev = CONFIG_EVL_NR_THREADS, + .attrs = thread_groups, + .flags = EVL_FACTORY_CLONE, +}; diff --git a/kernel/evl/tick.c b/kernel/evl/tick.c new file mode 100644 index 000000000..3d9c43363 --- /dev/null +++ b/kernel/evl/tick.c @@ -0,0 +1,284 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2016, 2018 Philippe Gerum + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static DEFINE_PER_CPU(struct clock_proxy_device *, proxy_device); + +static int proxy_set_next_ktime(ktime_t expires, + struct clock_event_device *proxy_dev) +{ + struct evl_rq *rq; + unsigned long flags; + ktime_t delta; + + /* + * Negative delta have been observed. evl_start_timer() + * will trigger an immediate shot in such an event. + */ + delta = ktime_sub(expires, ktime_get()); + + flags = hard_local_irq_save(); /* Prevent CPU migration. */ + rq = this_evl_rq(); + evl_start_timer(&rq->inband_timer, + evl_abs_timeout(&rq->inband_timer, delta), + EVL_INFINITE); + hard_local_irq_restore(flags); + + return 0; +} + +static int proxy_set_oneshot_stopped(struct clock_event_device *proxy_dev) +{ + struct clock_event_device *real_dev; + struct clock_proxy_device *dev; + unsigned long flags; + struct evl_rq *rq; + + dev = container_of(proxy_dev, struct clock_proxy_device, proxy_device); + + /* + * In-band wants to disable the clock hardware on entering a + * tickless state, so we have to stop our in-band tick + * emulation. Propagate the request for shutting down the + * hardware to the real device only if we have no outstanding + * OOB timers. CAUTION: the in-band timer is counted when + * assessing the RQ_IDLE condition, so we need to stop it + * prior to testing the latter. + */ + flags = hard_local_irq_save(); + + rq = this_evl_rq(); + evl_stop_timer(&rq->inband_timer); + rq->local_flags |= RQ_TSTOPPED; + + if (rq->local_flags & RQ_IDLE) { + real_dev = dev->real_device; + real_dev->set_state_oneshot_stopped(real_dev); + } + + hard_local_irq_restore(flags); + + return 0; +} + +#ifdef CONFIG_SMP +static irqreturn_t clock_ipi_handler(int irq, void *dev_id) +{ + evl_core_tick(NULL); + + return IRQ_HANDLED; +} +#else +#define clock_ipi_handler NULL +#endif + +static void setup_proxy(struct clock_proxy_device *dev) +{ + struct clock_event_device *proxy_dev = &dev->proxy_device; + + dev->handle_oob_event = evl_core_tick; + proxy_dev->features |= CLOCK_EVT_FEAT_KTIME; + proxy_dev->set_next_ktime = proxy_set_next_ktime; + if (proxy_dev->set_state_oneshot_stopped) + proxy_dev->set_state_oneshot_stopped = proxy_set_oneshot_stopped; + + __this_cpu_write(proxy_device, dev); +} + +#ifdef CONFIG_SMP +static int request_timer_ipi(void) +{ + int ret = 0; + + /* + * We may be running a SMP kernel on a uniprocessor machine + * whose interrupt controller provides no IPI: attempt to hook + * the timer IPI only if the hardware can support multiple + * CPUs. + */ + if (num_possible_cpus() > 1) + ret = __request_percpu_irq(TIMER_OOB_IPI, + clock_ipi_handler, + IRQF_OOB, "EVL timer IPI", + &evl_machine_cpudata); + return ret; +} + +static void __free_timer_ipi(void *arg) +{ + disable_percpu_irq(TIMER_OOB_IPI); +} + +static void free_timer_ipi(void) +{ + if (num_possible_cpus() > 1) { + on_each_cpu_mask(&evl_oob_cpus, + __free_timer_ipi, NULL, true); + free_percpu_irq(TIMER_OOB_IPI, &evl_machine_cpudata); + } +} +#else +static inline int request_timer_ipi(void) +{ + return 0; +} + +static inline void free_timer_ipi(void) +{ +} +#endif /* !CONFIG_SMP */ + +int evl_enable_tick(void) +{ + int ret; + + ret = request_timer_ipi(); + if (ret) + return ret; + + /* + * CAUTION: + * + * - EVL timers may be started only _after_ the proxy clock + * device has been set up for the target CPU. + * + * - do not hold any lock across calls to evl_enable_tick(). + * + * - tick_install_proxy() guarantees that the real clock + * device supports oneshot mode, or fails. + */ + ret = tick_install_proxy(setup_proxy, &evl_oob_cpus); + if (ret) + goto fail_proxy; + + return 0; + +fail_proxy: + + free_timer_ipi(); + + return ret; +} + +void evl_disable_tick(void) +{ + tick_uninstall_proxy(&evl_oob_cpus); + free_timer_ipi(); + + /* + * When the kernel is swapping clock event devices on behalf + * of enable_clock_devices(), it may end up calling + * program_timer() via the synthetic device's + * ->set_next_event() handler for resuming the in-band timer. + * Therefore, no timer should remain queued before + * enable_clock_devices() is called, or unpleasant hangs may + * happen if the in-band timer is not at front of the + * queue. You have been warned. + */ + evl_stop_timers(&evl_mono_clock); +} + +/* per-cpu timer queue locked. */ +void evl_program_proxy_tick(struct evl_clock *clock) +{ + struct clock_proxy_device *dev = __this_cpu_read(proxy_device); + struct clock_event_device *real_dev = dev->real_device; + struct evl_rq *this_rq = this_evl_rq(); + struct evl_timerbase *tmb; + struct evl_timer *timer; + struct evl_tnode *tn; + int64_t delta; + u64 cycles; + ktime_t t; + int ret; + + /* + * Do not reprogram locally when inside the tick handler - + * will be done on exit anyway. Also exit if there is no + * pending timer. + */ + if (this_rq->local_flags & RQ_TIMER) + return; + + tmb = evl_this_cpu_timers(clock); + tn = evl_get_tqueue_head(&tmb->q); + if (tn == NULL) { + this_rq->local_flags |= RQ_IDLE; + return; + } + + /* + * Try to defer the next in-band tick, so that it does not + * preempt an OOB activity uselessly, in two cases: + * + * 1) a rescheduling is pending for the current CPU. We may + * assume that an EVL thread is about to resume, so we want to + * move the in-band tick out of the way until in-band activity + * resumes, unless there is no other outstanding timers. + * + * 2) the current EVL thread is running OOB, in which case we + * may defer the in-band tick until the in-band activity + * resumes. + * + * The in-band tick deferral is cleared whenever EVL is about + * to yield control to the in-band code (see + * __evl_schedule()), or a timer with an earlier timeout date + * is scheduled, whichever comes first. + */ + this_rq->local_flags &= ~(RQ_TDEFER|RQ_IDLE|RQ_TSTOPPED); + timer = container_of(tn, struct evl_timer, node); + if (timer == &this_rq->inband_timer) { + if (evl_need_resched(this_rq) || + !(this_rq->curr->state & EVL_T_ROOT)) { + tn = evl_get_tqueue_next(&tmb->q, tn); + if (tn) { + this_rq->local_flags |= RQ_TDEFER; + timer = container_of(tn, struct evl_timer, node); + } + } + } + + t = evl_tdate(timer); + delta = ktime_to_ns(ktime_sub(t, evl_read_clock(clock))); + + if (real_dev->features & CLOCK_EVT_FEAT_KTIME) { + real_dev->set_next_ktime(t, real_dev); + trace_evl_timer_shot(timer, delta, t); + } else { + if (delta <= 0) + delta = real_dev->min_delta_ns; + else { + delta = min(delta, (int64_t)real_dev->max_delta_ns); + delta = max(delta, (int64_t)real_dev->min_delta_ns); + } + cycles = ((u64)delta * real_dev->mult) >> real_dev->shift; + ret = real_dev->set_next_event(cycles, real_dev); + trace_evl_timer_shot(timer, delta, cycles); + if (ret) { + real_dev->set_next_event(real_dev->min_delta_ticks, + real_dev); + trace_evl_timer_shot(timer, real_dev->min_delta_ns, + real_dev->min_delta_ticks); + } + } +} + +#ifdef CONFIG_SMP +void evl_send_timer_ipi(struct evl_clock *clock, struct evl_rq *rq) +{ + irq_send_oob_ipi(TIMER_OOB_IPI, cpumask_of(evl_rq_cpu(rq))); +} +#endif diff --git a/kernel/evl/timer.c b/kernel/evl/timer.c new file mode 100644 index 000000000..ec372f9cd --- /dev/null +++ b/kernel/evl/timer.c @@ -0,0 +1,524 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Derived from Xenomai Cobalt, https://xenomai.org/ + * Copyright (C) 2004 Gilles Chanteperdrix + * Copyright (C) 2001, 2018 Philippe Gerum + */ + +#include +#include +#include +#include +#include + +#ifdef CONFIG_SMP + +static struct evl_timerbase * +lock_timer_base(struct evl_timer *timer, unsigned long *flags) +{ + struct evl_timerbase *base; + + for (;;) { + base = READ_ONCE(timer->base); + raw_spin_lock_irqsave(&base->lock, *flags); + /* + * Careful about evl_move_timer() running concurrently + * on a different CPU. + */ + if (base == timer->base) + break; + raw_spin_unlock_irqrestore(&base->lock, *flags); + } + + return base; +} + +static inline void unlock_timer_base(struct evl_timerbase *base, + unsigned long flags) +{ + raw_spin_unlock_irqrestore(&base->lock, flags); +} + +#else + +static inline struct evl_timerbase * +lock_timer_base(struct evl_timer *timer, unsigned long *flags) +{ + *flags = hard_local_irq_save(); + + return timer->base; +} + +static inline void unlock_timer_base(struct evl_timerbase *base, + unsigned long flags) +{ + hard_local_irq_restore(flags); +} + +#endif + +/* hard irqs off */ +static inline void double_timer_base_lock(struct evl_timerbase *tb1, + struct evl_timerbase *tb2) +{ + if (tb1 == tb2) + raw_spin_lock(&tb1->lock); + else if (tb1 < tb2) { + raw_spin_lock(&tb1->lock); + raw_spin_lock_nested(&tb2->lock, SINGLE_DEPTH_NESTING); + } else { + raw_spin_lock(&tb2->lock); + raw_spin_lock_nested(&tb1->lock, SINGLE_DEPTH_NESTING); + } +} + +static inline void double_timer_base_unlock(struct evl_timerbase *tb1, + struct evl_timerbase *tb2) +{ + raw_spin_unlock(&tb1->lock); + if (tb1 != tb2) + raw_spin_unlock(&tb2->lock); +} + +/* timer base locked. */ +static bool timer_at_front(struct evl_timer *timer) +{ + struct evl_rq *rq = evl_get_timer_rq(timer); + struct evl_tqueue *tq; + struct evl_tnode *tn; + + tq = &timer->base->q; + tn = evl_get_tqueue_head(tq); + if (tn == &timer->node) + return true; + + if (rq->local_flags & RQ_TDEFER) { + tn = evl_get_tqueue_next(tq, tn); + if (tn == &timer->node) + return true; + } + + return false; +} + +/* timer base locked. */ +static void program_timer(struct evl_timer *timer, + struct evl_tqueue *tq) +{ + struct evl_rq *rq; + + evl_enqueue_timer(timer, tq); + + rq = evl_get_timer_rq(timer); + if (!(rq->local_flags & RQ_TSTOPPED) && !timer_at_front(timer)) + return; + + if (rq != this_evl_rq()) + evl_program_remote_tick(timer->clock, rq); + else + evl_program_local_tick(timer->clock); +} + +void evl_start_timer(struct evl_timer *timer, + ktime_t value, ktime_t interval) +{ + struct evl_timerbase *base; + struct evl_tqueue *tq; + ktime_t date, gravity; + unsigned long flags; + + trace_evl_timer_start(timer, value, interval); + + base = lock_timer_base(timer, &flags); + tq = &base->q; + + if ((timer->status & EVL_TIMER_DEQUEUED) == 0) + evl_dequeue_timer(timer, tq); + + timer->status &= ~(EVL_TIMER_FIRED | EVL_TIMER_PERIODIC); + + date = ktime_sub(value, timer->clock->offset); + + /* + * To cope with the basic system latency, we apply a clock + * gravity value, which is the amount of time expressed in + * nanoseconds by which we should anticipate the shot for the + * timer. The gravity value varies with the type of context + * the timer wakes up, i.e. irq handler, kernel or user + * thread. + */ + gravity = evl_get_timer_gravity(timer); + evl_tdate(timer) = ktime_sub(date, gravity); + + timer->interval = EVL_INFINITE; + if (!timeout_infinite(interval)) { + timer->interval = interval; + timer->start_date = value; + timer->consumed_ticks = 0; + timer->periodic_ticks = 0; + timer->status |= EVL_TIMER_PERIODIC; + } + + timer->status |= EVL_TIMER_RUNNING; + program_timer(timer, tq); + + unlock_timer_base(base, flags); +} +EXPORT_SYMBOL_GPL(evl_start_timer); + +/* timer base locked. */ +bool evl_timer_deactivate(struct evl_timer *timer) +{ + struct evl_tqueue *tq = &timer->base->q; + bool heading = true; + + if (!(timer->status & EVL_TIMER_DEQUEUED)) { + heading = timer_at_front(timer); + evl_dequeue_timer(timer, tq); + } + + timer->status &= ~(EVL_TIMER_FIRED|EVL_TIMER_RUNNING); + + return heading; +} + +/* timerbase locked, hard irqs off */ +static void stop_timer_locked(struct evl_timer *timer) +{ + bool heading; + + /* + * If we removed the heading timer, reprogram the next shot if + * any. If the timer was running on another CPU, let it tick. + */ + if (evl_timer_is_running(timer)) { + heading = evl_timer_deactivate(timer); + if (heading && evl_timer_on_rq(timer, this_evl_rq())) + evl_program_local_tick(timer->clock); + } +} + +void __evl_stop_timer(struct evl_timer *timer) +{ + struct evl_timerbase *base; + unsigned long flags; + + trace_evl_timer_stop(timer); + base = lock_timer_base(timer, &flags); + stop_timer_locked(timer); + unlock_timer_base(base, flags); +} +EXPORT_SYMBOL_GPL(__evl_stop_timer); + +ktime_t evl_get_timer_date(struct evl_timer *timer) +{ + struct evl_timerbase *base; + unsigned long flags; + ktime_t expiry; + + base = lock_timer_base(timer, &flags); + + if (!evl_timer_is_running(timer)) + expiry = EVL_INFINITE; + else + expiry = evl_get_timer_expiry(timer); + + unlock_timer_base(base, flags); + + return expiry; +} +EXPORT_SYMBOL_GPL(evl_get_timer_date); + +ktime_t __evl_get_timer_delta(struct evl_timer *timer) +{ + struct evl_timerbase *base; + ktime_t expiry, now; + unsigned long flags; + + base = lock_timer_base(timer, &flags); + expiry = evl_get_timer_expiry(timer); + unlock_timer_base(base, flags); + now = evl_read_clock(timer->clock); + if (expiry <= now) + return ktime_set(0, 1); /* Will elapse shortly. */ + + return ktime_sub(expiry, now); +} +EXPORT_SYMBOL_GPL(__evl_get_timer_delta); + +#ifdef CONFIG_SMP + +static inline int get_clock_cpu(struct evl_clock *clock, int cpu) +{ + /* + * Check a CPU number against the possible set of CPUs + * receiving events from the underlying clock device. If the + * suggested CPU does not receive events from this device, + * return the first one which does instead. + * + * NOTE: we have run queues initialized for all online CPUs, + * we can program and receive clock ticks on any of them. So + * there is no point in restricting the valid CPU set to + * evl_cpu_affinity, which specifically refers to the set of + * CPUs which may run EVL threads. Although receiving a clock + * tick for waking up a thread living on a remote CPU is not + * optimal since this involves IPI-signaled rescheds, this is + * still acceptable. + */ + if (cpumask_test_cpu(cpu, &clock->affinity)) + return cpu; + + return cpumask_first(&clock->affinity); +} + +#else + +static inline int get_clock_cpu(struct evl_clock *clock, int cpu) +{ + return 0; +} + +#endif /* CONFIG_SMP */ + +void __evl_init_timer(struct evl_timer *timer, + struct evl_clock *clock, + void (*handler)(struct evl_timer *timer), + struct evl_rq *rq, + const char *name, + int flags) +{ + int cpu; + + timer->clock = clock; + evl_tdate(timer) = EVL_INFINITE; + timer->status = EVL_TIMER_DEQUEUED|(flags & EVL_TIMER_INIT_MASK); + timer->handler = handler; + timer->interval = EVL_INFINITE; + + /* + * Set the timer affinity to the CPU rq is on if given, or the + * first CPU which may run EVL threads otherwise. + */ + cpu = rq ? + get_clock_cpu(clock->master, evl_rq_cpu(rq)) : + cpumask_first(&evl_cpu_affinity); +#ifdef CONFIG_SMP + timer->rq = evl_cpu_rq(cpu); +#endif + timer->base = evl_percpu_timers(clock, cpu); + timer->clock = clock; + timer->name = name ?: ""; + evl_reset_timer_stats(timer); +} +EXPORT_SYMBOL_GPL(__evl_init_timer); + +void evl_set_timer_gravity(struct evl_timer *timer, int gravity) +{ + struct evl_timerbase *base; + unsigned long flags; + + base = lock_timer_base(timer, &flags); + timer->status &= ~EVL_TIMER_GRAVITY_MASK; + timer->status |= gravity; + unlock_timer_base(base, flags); + +} +EXPORT_SYMBOL_GPL(evl_set_timer_gravity); + +void evl_destroy_timer(struct evl_timer *timer) +{ + evl_stop_timer(timer); + timer->status |= EVL_TIMER_KILLED; +#ifdef CONFIG_SMP + WRITE_ONCE(timer->rq, NULL); +#endif + WRITE_ONCE(timer->base, NULL); +} +EXPORT_SYMBOL_GPL(evl_destroy_timer); + +/* + * evl_move_timer - change the reference clock and/or the CPU + * affinity of a timer + * @timer: timer to modify + * @clock: reference clock + * @rq: runqueue to assign the timer to + * + * hard irqs off on entry. + */ +void evl_move_timer(struct evl_timer *timer, + struct evl_clock *clock, struct evl_rq *rq) +{ + struct evl_timerbase *old_base, *new_base; + struct evl_clock *master = clock->master; + unsigned long flags; + int cpu; + + EVL_WARN_ON_ONCE(CORE, !hard_irqs_disabled()); + + trace_evl_timer_move(timer, clock, evl_rq_cpu(rq)); + + /* + * Find out which CPU is best suited for managing this timer, + * preferably picking evl_rq_cpu(rq) if the ticking device + * moving the timer clock beats on that CPU. Otherwise, pick + * the first CPU from the clock affinity mask if set. + */ + cpu = get_clock_cpu(clock->master, evl_rq_cpu(rq)); + rq = evl_cpu_rq(cpu); + + old_base = lock_timer_base(timer, &flags); + + if (evl_timer_on_rq(timer, rq) && clock == timer->clock) { + unlock_timer_base(old_base, flags); + return; + } + + new_base = evl_percpu_timers(master, cpu); + + if (timer->status & EVL_TIMER_RUNNING) { + stop_timer_locked(timer); + unlock_timer_base(old_base, flags); + flags = hard_local_irq_save(); + double_timer_base_lock(old_base, new_base); +#ifdef CONFIG_SMP + timer->rq = rq; +#endif + timer->base = new_base; + timer->clock = clock; + evl_enqueue_timer(timer, &new_base->q); + if (timer_at_front(timer)) + evl_program_remote_tick(clock, rq); + double_timer_base_unlock(old_base, new_base); + hard_local_irq_restore(flags); + } else { +#ifdef CONFIG_SMP + timer->rq = rq; +#endif + timer->base = new_base; + timer->clock = clock; + unlock_timer_base(old_base, flags); + } +} +EXPORT_SYMBOL_GPL(evl_move_timer); + +unsigned long evl_get_timer_overruns(struct evl_timer *timer) +{ + unsigned long overruns = 0, flags; + struct evl_timerbase *base; + struct evl_thread *thread; + struct evl_tqueue *tq; + ktime_t now, delta; + + if (EVL_WARN_ON_ONCE(CORE, !evl_timer_is_periodic(timer))) + return 0; + + base = lock_timer_base(timer, &flags); + now = evl_read_clock(timer->clock); + + /* + * Measure the lateness with respect to the expected expiry + * date in the timeline for this timer. This ideal expiry date + * would be the start date of the timer, plus the interval + * duration times the number of ticks which were consumed so + * far. Any delay longer than the periodic interval denotes an + * overrun condition since we missed at least one tick. + */ + delta = ktime_sub(now, evl_get_timer_next_date(timer)); + if (likely(delta < timer->interval)) + goto done; + + overruns = ktime_divns(delta, ktime_to_ns(timer->interval)); + + /* + * Compensate for the current lateness as the timer progresses + * in the timeline, consuming all missed ticks in one gulp to + * catch up. + */ + timer->consumed_ticks += overruns; + + /* + * We are about to re-enqueue the timer for its next expiry + * date. However, we refrain from doing so if either: + * + * - the timer was deactivated, in which case there is no + * point in planning for further expiry. + * + * - the timer is still running but not queued, which means + * that do_clock_tick() dequeued it then released the base + * lock on a remote CPU for running its handler. Since the + * timer is running and we hold that lock at the moment, + * do_clock_tick() is certainly going to either advance the + * expiry as required or shut the timer down after we drop the + * base lock. IOW, we may leave reprogramming to the core tick + * handler. + */ + if (!evl_timer_is_running(timer)) + goto done; + + if (timer->status & EVL_TIMER_DEQUEUED) + goto done; + + /* + * Re-enqueue the periodic timer so that it ticks at the next + * interval boundary. + */ + tq = &base->q; + evl_dequeue_timer(timer, tq); + while (evl_tdate(timer) < now) { + timer->periodic_ticks++; + evl_update_timer_date(timer); + } + + program_timer(timer, tq); +done: + timer->consumed_ticks++; + + unlock_timer_base(base, flags); + + /* + * Hide overruns due to the most recent ptracing session from + * the caller. + */ + thread = evl_current(); + if (thread->local_info & EVL_T_IGNOVR) + return 0; + + return overruns; +} +EXPORT_SYMBOL_GPL(evl_get_timer_overruns); + +#ifdef CONFIG_EVL_TIMER_SCALABLE + +static __always_inline +bool date_is_earlier(struct evl_tnode *left, + struct evl_tnode *right) +{ + return left->date < right->date; +} + +void evl_insert_tnode(struct evl_tqueue *tq, struct evl_tnode *node) +{ + struct rb_node **new = &tq->root.rb_node, *parent = NULL; + struct evl_tnode *i; + + if (!tq->head) + tq->head = node; + else if (date_is_earlier(node, tq->head)) { + parent = &tq->head->rb; + new = &parent->rb_left; + tq->head = node; + } else while (*new) { + i = container_of(*new, struct evl_tnode, rb); + parent = *new; + if (date_is_earlier(node, i)) + new = &((*new)->rb_left); + else + new = &((*new)->rb_right); + } + + rb_link_node(&node->rb, parent, new); + rb_insert_color(&node->rb, &tq->root); +} + +#endif diff --git a/kernel/evl/trace.c b/kernel/evl/trace.c new file mode 100644 index 000000000..aaf3d3f3d --- /dev/null +++ b/kernel/evl/trace.c @@ -0,0 +1,94 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2018 Philippe Gerum + */ + +#include +#include +#include +#include +#include + +static long trace_common_ioctl(struct file *filp, unsigned int cmd, + unsigned long arg) +{ + long ret = 0; + + switch (cmd) { + case EVL_TRCIOC_SNAPSHOT: +#ifdef CONFIG_TRACER_SNAPSHOT + tracing_snapshot(); +#endif + break; + default: + ret = -ENOTTY; + } + + return ret; +} + +static long trace_oob_ioctl(struct file *filp, unsigned int cmd, + unsigned long arg) +{ + return trace_common_ioctl(filp, cmd, arg); +} + +static notrace ssize_t +trace_oob_write(struct file *filp, + const char __user *u_buf, size_t count) +{ + char buf[128]; + int ret; + + if (count >= sizeof(buf)) + count = sizeof(buf) - 1; + + /* May be called from in-band context too. */ + ret = raw_copy_from_user(buf, u_buf, count); + if (ret) + return -EFAULT; + + buf[count] = '\0'; + + /* + * trace_printk() is slow and triggers a scary and noisy + * warning at boot. Prefer a common tracepoint for issuing the + * message to the log. + */ + trace_evl_trace(buf); + + return count; +} + +static long trace_ioctl(struct file *filp, unsigned int cmd, + unsigned long arg) +{ + return trace_common_ioctl(filp, cmd, arg); +} + +static notrace +ssize_t trace_write(struct file *filp, + const char __user *u_buf, size_t count, + loff_t *ppos) +{ + return trace_oob_write(filp, u_buf, count); +} + +static const struct file_operations trace_fops = { + .open = stream_open, + .unlocked_ioctl = trace_ioctl, + .write = trace_write, + .oob_ioctl = trace_oob_ioctl, + .oob_write = trace_oob_write, +#ifdef CONFIG_COMPAT + .compat_ioctl = compat_ptr_ioctl, + .compat_oob_ioctl = compat_ptr_oob_ioctl, +#endif +}; + +struct evl_factory evl_trace_factory = { + .name = "trace", + .fops = &trace_fops, + .flags = EVL_FACTORY_SINGLE, +}; diff --git a/kernel/evl/wait.c b/kernel/evl/wait.c new file mode 100644 index 000000000..69f24e735 --- /dev/null +++ b/kernel/evl/wait.c @@ -0,0 +1,401 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Derived from Xenomai Cobalt, https://xenomai.org/ + * Copyright (C) 2001, 2019 Philippe Gerum + */ + +#include +#include +#include +#include +#include + +void __evl_init_wait(struct evl_wait_queue *wq, + struct evl_clock *clock, int wq_flags, + const char *name, + struct lock_class_key *lock_key) +{ + wq->flags = wq_flags; + wq->clock = clock; + wq->wchan.owner = NULL; + wq->wchan.requeue_wait = evl_requeue_wait; + wq->wchan.name = name; + INIT_LIST_HEAD(&wq->wchan.wait_list); + raw_spin_lock_init(&wq->wchan.lock); + lockdep_set_class_and_name(&wq->wchan.lock, lock_key, name); + might_hard_lock(&wq->wchan.lock); +} +EXPORT_SYMBOL_GPL(__evl_init_wait); + +void evl_destroy_wait(struct evl_wait_queue *wq) +{ + evl_flush_wait(wq, EVL_T_RMID); + evl_schedule(); +} +EXPORT_SYMBOL_GPL(evl_destroy_wait); + +/* wq->wchan.lock held, hard irqs off */ +static void __evl_add_wait_queue(struct evl_thread *curr, + struct evl_wait_queue *wq, + ktime_t timeout, enum evl_tmode timeout_mode) +{ + assert_hard_lock(&wq->wchan.lock); + + trace_evl_wait(&wq->wchan); + + if (!(wq->flags & EVL_WAIT_PRIO)) + list_add_tail(&curr->wait_next, &wq->wchan.wait_list); + else + list_add_priff(curr, &wq->wchan.wait_list, wprio, wait_next); + + evl_sleep_on(timeout, timeout_mode, wq->clock, &wq->wchan); +} + +void evl_add_wait_queue(struct evl_wait_queue *wq, ktime_t timeout, + enum evl_tmode timeout_mode) +{ + struct evl_thread *curr = evl_current(); + + if ((curr->state & EVL_T_WOLI) && + atomic_read(&curr->held_mutex_count) > 0) + evl_notify_thread(curr, EVL_HMDIAG_LKSLEEP, evl_nil); + + __evl_add_wait_queue(curr, wq, timeout, timeout_mode); + +} +EXPORT_SYMBOL_GPL(evl_add_wait_queue); + +void evl_add_wait_queue_unchecked(struct evl_wait_queue *wq, ktime_t timeout, + enum evl_tmode timeout_mode) +{ + struct evl_thread *curr = evl_current(); + + __evl_add_wait_queue(curr, wq, timeout, timeout_mode); +} + +/* wq->wchan.lock held, hard irqs off */ +struct evl_thread *evl_wake_up(struct evl_wait_queue *wq, + struct evl_thread *waiter, + int reason) +{ + assert_hard_lock(&wq->wchan.lock); + + trace_evl_wake_up(&wq->wchan); + + if (list_empty(&wq->wchan.wait_list)) { + waiter = NULL; + } else { + if (waiter == NULL) + waiter = list_first_entry(&wq->wchan.wait_list, + struct evl_thread, wait_next); + list_del_init(&waiter->wait_next); + evl_wakeup_thread(waiter, EVL_T_PEND, reason); + } + + return waiter; +} +EXPORT_SYMBOL_GPL(evl_wake_up); + +/* wq->wchan.lock held, hard irqs off */ +int evl_flush_wait_locked(struct evl_wait_queue *wq, int reason) +{ + struct evl_thread *waiter, *tmp; + int ret = 0; + + assert_hard_lock(&wq->wchan.lock); + + trace_evl_flush_wait(&wq->wchan); + + list_for_each_entry_safe(waiter, tmp, &wq->wchan.wait_list, wait_next) { + list_del_init(&waiter->wait_next); + evl_wakeup_thread(waiter, EVL_T_PEND, reason); + ret++; + } + + return ret; +} +EXPORT_SYMBOL_GPL(evl_flush_wait_locked); + +int evl_flush_wait(struct evl_wait_queue *wq, int reason) +{ + unsigned long flags; + int ret; + + raw_spin_lock_irqsave(&wq->wchan.lock, flags); + ret = evl_flush_wait_locked(wq, reason); + raw_spin_unlock_irqrestore(&wq->wchan.lock, flags); + + return ret; +} +EXPORT_SYMBOL_GPL(evl_flush_wait); + +static inline struct evl_wait_queue * +wchan_to_wait_queue(struct evl_wait_channel *wchan) +{ + return container_of(wchan, struct evl_wait_queue, wchan); +} + +/* wchan->lock + waiter->lock held, irqs off. */ +bool evl_requeue_wait(struct evl_wait_channel *wchan, struct evl_thread *waiter) +{ + struct evl_wait_queue *wq = wchan_to_wait_queue(wchan); + + assert_hard_lock(&wchan->lock); + assert_hard_lock(&waiter->lock); + + if (wq->flags & EVL_WAIT_PRIO) { + list_del(&waiter->wait_next); + list_add_priff(waiter, &wq->wchan.wait_list, wprio, wait_next); + } + + return true; +} +EXPORT_SYMBOL_GPL(evl_requeue_wait); + +int __evl_wait_schedule(struct evl_wait_channel *wchan) +{ + struct evl_thread *curr = evl_current(); + unsigned long flags; + int info; + + evl_schedule(); + + trace_evl_finish_wait(wchan); + + /* + * Upon return from a wait state, the following logic applies + * depending on the information flags: + * + * - if none of EVL_T_RMID, EVL_T_NOMEM, EVL_T_TIMEO or EVL_T_BREAK is set, we + * got a wakeup upon a successful operation. In this case, we + * should not be linked to the waitqueue anymore. NOTE: the + * caller may need to check for EVL_T_BCAST if the signal is not + * paired with a condition but works as a pulse instead. + * + * - if EVL_T_RMID is set, evl_flush_wait() removed us from the + * waitqueue before the wait channel got destroyed, and + * therefore cannot be referred to anymore since it may be + * stale: -EIDRM is returned. + * + * - otherwise, we may still be linked to the waitqueue if the + * wait was aborted prior to receiving any wakeup, in which + * case we have to drop out from there. Timeout or break + * condition might be followed by a normal wakeup, in which + * case the former prevails wrt the status returned to the + * caller. + * + * INVARIANT: only the sleep-and-retry scheme to grab a + * resource is safe and assumed throughout the + * implementation. On the contrary, passing a resource from + * the thread which releases it directly to the one it is + * being granted to would be UNSAFE, since we could have a + * stale resource left over upon a timeout or break condition + * returned to the caller. + */ + info = evl_current()->info; + if (likely(!(info & (EVL_T_RMID|EVL_T_NOMEM|EVL_T_TIMEO|EVL_T_BREAK)))) { /* Fast path. */ + if (IS_ENABLED(CONFIG_EVL_DEBUG_CORE)) { + bool empty; + raw_spin_lock_irqsave(&wchan->lock, flags); + empty = list_empty(&curr->wait_next); + raw_spin_unlock_irqrestore(&wchan->lock, flags); + EVL_WARN_ON_ONCE(CORE, !empty); + } + return 0; + } + + if (info & EVL_T_RMID) + return -EIDRM; + + raw_spin_lock_irqsave(&wchan->lock, flags); + + if (!list_empty(&curr->wait_next)) + list_del_init(&curr->wait_next); + + raw_spin_unlock_irqrestore(&wchan->lock, flags); + + if (info & EVL_T_NOMEM) + return -ENOMEM; + + return info & EVL_T_TIMEO ? -ETIMEDOUT : -EINTR; +} +EXPORT_SYMBOL_GPL(__evl_wait_schedule); + +struct evl_thread *evl_wait_head(struct evl_wait_queue *wq) +{ + assert_hard_lock(&wq->wchan.lock); + return list_first_entry_or_null(&wq->wchan.wait_list, + struct evl_thread, wait_next); +} +EXPORT_SYMBOL_GPL(evl_wait_head); + +/* + * Requeue a thread which changed priority in the wait channel it + * pends on, then propagate the change down the lock chain. + * + * On entry: irqs off. + */ +void evl_adjust_wait_priority(struct evl_thread *thread) +{ + struct evl_wait_channel *wchan; + struct evl_thread *owner; + + EVL_WARN_ON_ONCE(CORE, !hard_irqs_disabled()); + + raw_spin_lock(&thread->lock); + wchan = evl_get_thread_wchan(thread); + if (!wchan) { + raw_spin_unlock(&thread->lock); + return; + } + + /* + * Careful: mere waitqueues have no owner, only mutexes may + * be owned. + */ + owner = wchan->owner; + if (owner) { + wchan->requeue_wait(wchan, thread); + raw_spin_unlock(&thread->lock); + evl_double_thread_lock(thread, owner); + /* Walking the chain drops owner->lock. */ + evl_walk_lock_chain(wchan, thread, false); + } else { + wchan->requeue_wait(wchan, thread); + } + + raw_spin_unlock(&thread->lock); + evl_put_thread_wchan(wchan); +} + +/* + * Walking the lock chain deals with the following items: + * + * waiter := the thread which waits on wchan + * wchan := the wait channel being processed + * owner := the current owner of wchan + * + * In order to go fine-grained and escape ABBA situations, we hold + * three locks at most while walking the lock chain, keeping a + * consistent locking sequence among them as follows: + * + * lock(wchan) + * lock(waiter, owner) + * + * Rules: + * + * 1. holding wchan->lock guarantees that wchan->owner is stable. + * + * 2. holding thread->lock guarantees that thread->wchan is stable. + * + * 3. there is no rule #3. + * + * On entry: + * + * (orig_wchan->lock + orig_wchan->owner->lock + orig_waiter->lock) + * held, irqs off. All these locks may be dropped temporarily during + * the walk. orig_wchan->owner->lock is NOT reacquired at exit. + */ +int evl_walk_lock_chain(struct evl_wait_channel *orig_wchan, + struct evl_thread *orig_waiter, + bool check_only) +{ + struct evl_thread *waiter = orig_waiter, *owner = orig_wchan->owner; + struct evl_wait_channel *wchan = orig_wchan, *next_wchan; + int ret = 0; + + assert_hard_lock(&wchan->lock); + assert_hard_lock(&waiter->lock); + + /* We must have a valid owner for the origin wchan. */ + if (EVL_WARN_ON_ONCE(CORE, !owner)) + return -EIO; + + assert_hard_lock(&owner->lock); + + /* The chain must be sane on entry. */ + if (EVL_WARN_ON_ONCE(CORE, owner == orig_waiter)) { + raw_spin_unlock(&owner->lock); + return -EDEADLK; + } + + evl_get_element(&orig_waiter->element); + raw_spin_unlock(&orig_waiter->lock); + + /* + * Since we drop locks inside the loop, we might have + * concurrent walks on the same chain from different CPUs, + * contradicting each other when it comes to the priority to + * set for a thread. This issue is solved by + * evl_adjust_thread_boost() which solely considers the + * current state of a thread's booster list in order to give + * it the proper priority at any point in time. + */ + for (;;) { + /* + * We already hold wchan->owner->lock, so dropping + * wchan->lock is safe. + */ + raw_spin_unlock(&wchan->lock); + + /* + * If no adjustment was deemed necessary, we may stop + * the walk right here, since there would be no + * priority change to propagate further down the + * chain. + */ + if (!check_only && !evl_adjust_thread_boost(owner)) { + raw_spin_unlock(&owner->lock); + break; + } + + next_wchan = evl_get_thread_wchan(owner); + if (!next_wchan) { + raw_spin_unlock(&owner->lock); + break; + } + + /* + * Progress down the lock chain, at this point we hold + * owner->lock and next_wchan->lock. + */ + waiter = owner; + wchan = next_wchan; + + /* + * If the priority of the last owner we visited has + * changed, update its position into the wait channel + * it sleeps on. + */ + if (!check_only && !wchan->requeue_wait(wchan, waiter)) + goto unlock_out; + + owner = wchan->owner; + if (!owner) /* End of lock chain, we are done. */ + goto unlock_out; + + if (owner == orig_waiter) { + ret = -EDEADLK; + goto unlock_out; + } + + raw_spin_unlock(&waiter->lock); + /* + * We must grab this lock before we drop wchan->lock + * at the next iteration. + */ + raw_spin_lock(&owner->lock); + } +out: + raw_spin_lock(&orig_wchan->lock); + raw_spin_lock(&orig_waiter->lock); + evl_put_element(&orig_waiter->element); + + return ret; + +unlock_out: + raw_spin_unlock(&waiter->lock); + raw_spin_unlock(&wchan->lock); + goto out; +} diff --git a/kernel/evl/work.c b/kernel/evl/work.c new file mode 100644 index 000000000..b6c4a3fd0 --- /dev/null +++ b/kernel/evl/work.c @@ -0,0 +1,118 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2020 Philippe Gerum + */ + +#include + +void __evl_do_work(struct work_struct *wq_work) +{ + struct evl_work *work; + + work = container_of(wq_work, struct evl_work, wq_work); + work->handler_noreturn(work); + if (work->element) + evl_put_element(work->element); +} +EXPORT_SYMBOL_GPL(__evl_do_work); + +void __evl_do_sync_work(struct work_struct *wq_work) +{ + struct evl_sync_work *sync_work; + + sync_work = container_of(wq_work, struct evl_sync_work, work.wq_work); + sync_work->result = sync_work->work.handler(sync_work); + evl_raise_flag(&sync_work->done); +} +EXPORT_SYMBOL_GPL(__evl_do_sync_work); + +void __evl_do_irq_work(struct irq_work *irq_work) +{ + struct evl_work *work; + + work = container_of(irq_work, struct evl_work, irq_work); + + if (!queue_work(work->wq, &work->wq_work) && work->element) + evl_put_element(work->element); +} +EXPORT_SYMBOL_GPL(__evl_do_irq_work); + +void evl_init_work(struct evl_work *work, + void (*handler)(struct evl_work *work)) +{ + init_irq_work(&work->irq_work, __evl_do_irq_work); + INIT_WORK(&work->wq_work, __evl_do_work); + work->handler_noreturn = (typeof(work->handler_noreturn))handler; + work->element = NULL; +} +EXPORT_SYMBOL_GPL(evl_init_work); + +void evl_init_work_safe(struct evl_work *work, + void (*handler)(struct evl_work *work), + struct evl_element *element) +{ + evl_init_work(work, handler); + work->element = element; +} +EXPORT_SYMBOL_GPL(evl_init_work_safe); + +void evl_init_sync_work(struct evl_sync_work *sync_work, + int (*handler)(struct evl_sync_work *sync_work)) +{ + struct evl_work *work = &sync_work->work; + + init_irq_work(&work->irq_work, __evl_do_irq_work); + INIT_WORK(&work->wq_work, __evl_do_sync_work); + work->handler = (typeof(work->handler))handler; + /* + * No point in holding a safety reference since the caller + * waits for the handler to have returned. + */ + work->element = NULL; + evl_init_flag(&sync_work->done); +} +EXPORT_SYMBOL_GPL(evl_init_sync_work); + +bool evl_call_inband_from(struct evl_work *work, + struct workqueue_struct *wq) +{ + work->wq = wq; + + /* + * Async call: get a reference on the protected element if + * specified so that the handler may access such element + * safely after our caller has unwound. + */ + if (work->element) + evl_get_element(work->element); + + if (!irq_work_queue(&work->irq_work)) { + if (work->element) + evl_put_element(work->element); + return false; + } + + return true; +} +EXPORT_SYMBOL_GPL(evl_call_inband_from); + +int evl_call_inband_sync_from(struct evl_sync_work *sync_work, + struct workqueue_struct *wq) +{ + struct evl_work *work = &sync_work->work; + + sync_work->result = -EINVAL; + + if (unlikely(running_inband())) { + EVL_WARN_ON(CORE, irqs_disabled()); + evl_call_inband_from(work, wq); + flush_work(&work->wq_work); + return sync_work->result; + } + + evl_call_inband_from(work, wq); + + return evl_wait_flag(&sync_work->done) ?: sync_work->result; +} +EXPORT_SYMBOL_GPL(evl_call_inband_sync_from); diff --git a/kernel/evl/xbuf.c b/kernel/evl/xbuf.c new file mode 100644 index 000000000..fca6d2a83 --- /dev/null +++ b/kernel/evl/xbuf.c @@ -0,0 +1,770 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2018 Philippe Gerum + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct xbuf_ring { + void *bufmem; + size_t bufsz; + size_t fillsz; + unsigned int rdoff; + unsigned int rdrsvd; + int rdpending; + unsigned int wroff; + unsigned int wrrsvd; + int wrpending; + unsigned long (*lock)(struct xbuf_ring *ring); + void (*unlock)(struct xbuf_ring *ring, unsigned long flags); + int (*wait_input)(struct xbuf_ring *ring, size_t len, size_t avail); + void (*signal_input)(struct xbuf_ring *ring, bool sigpoll); + int (*wait_output)(struct xbuf_ring *ring, size_t len); + void (*signal_output)(struct xbuf_ring *ring, bool sigpoll); +}; + +struct xbuf_inbound { /* oob_write->read */ + struct wait_queue_head i_event; + struct evl_flag o_event; + struct irq_work irq_work; + struct xbuf_ring ring; + hard_spinlock_t lock; +}; + +struct xbuf_outbound { /* write->oob_read */ + struct evl_wait_queue i_event; + struct wait_queue_head o_event; + struct irq_work irq_work; + struct xbuf_ring ring; +}; + +struct evl_xbuf { + struct evl_element element; + struct xbuf_inbound ibnd; + struct xbuf_outbound obnd; + struct evl_poll_head poll_head; +}; + +struct xbuf_rdesc { + char *buf; + char *buf_ptr; + size_t count; + int (*xfer)(struct xbuf_rdesc *dst, char *src, size_t len); +}; + +static int write_to_user(struct xbuf_rdesc *dst, char *src, size_t len) +{ + return raw_copy_to_user(dst->buf_ptr, src, len); +} + +static int write_to_kernel(struct xbuf_rdesc *dst, char *src, size_t len) +{ + memcpy(dst->buf_ptr, src, len); + + return 0; +} + +struct xbuf_wdesc { + const char *buf; + const char *buf_ptr; + size_t count; + int (*xfer)(char *dst, struct xbuf_wdesc *src, size_t len); +}; + +static int read_from_user(char *dst, struct xbuf_wdesc *src, size_t len) +{ + return raw_copy_from_user(dst, src->buf_ptr, len); +} + +static int read_from_kernel(char *dst, struct xbuf_wdesc *src, size_t len) +{ + memcpy(dst, src->buf_ptr, len); + + return 0; +} + +static ssize_t do_xbuf_read(struct xbuf_ring *ring, + struct xbuf_rdesc *rd, int f_flags) +{ + ssize_t len, ret, rbytes, n; + unsigned int rdoff, avail; + unsigned long flags; + bool sigpoll; + int xret; + + len = rd->count; + if (len == 0) + return 0; + + if (ring->bufsz == 0) + return -ENOBUFS; +retry: + rd->buf_ptr = rd->buf; + + for (;;) { + flags = ring->lock(ring); + /* + * We should be able to read a complete message of the + * requested length if O_NONBLOCK is clear. If set and + * some bytes are available, return them. Otherwise, + * send -EAGAIN. The actual count of bytes available + * for reading excludes the data which might be in + * flight to userland as we drop the lock during copy. + */ + avail = ring->fillsz - ring->rdrsvd; + if (avail < len) { + if (f_flags & O_NONBLOCK) { + if (avail == 0) { + ret = -EAGAIN; + break; + } + len = avail; + } else { + if (len > ring->bufsz) { + ret = -EINVAL; + break; + } + ring->unlock(ring, flags); + ret = ring->wait_input(ring, len, avail); + if (unlikely(ret)) { + if (ret == -EAGAIN) { + len = avail; + goto retry; + } + return ret; + } + continue; + } + } + + /* Reserve a read slot into the circular buffer. */ + rdoff = ring->rdoff; + ring->rdoff = (rdoff + len) % ring->bufsz; + ring->rdpending++; + ring->rdrsvd += len; + rbytes = ret = len; + + do { + if (rdoff + rbytes > ring->bufsz) + n = ring->bufsz - rdoff; + else + n = rbytes; + + /* + * Drop the lock before copying data to + * user. The read slot is consumed in any + * case: the non-copied portion of the message + * is lost on bad write. + */ + ring->unlock(ring, flags); + + xret = rd->xfer(rd, ring->bufmem + rdoff, n); + flags = ring->lock(ring); + if (xret) { + ret = -EFAULT; + break; + } + + rd->buf_ptr += n; + rbytes -= n; + rdoff = (rdoff + n) % ring->bufsz; + } while (rbytes > 0); + + if (--ring->rdpending == 0) { + /* sigpoll := full -> non-full transition. */ + sigpoll = ring->fillsz == ring->bufsz; + ring->fillsz -= ring->rdrsvd; + ring->rdrsvd = 0; + ring->signal_output(ring, sigpoll); + } + break; + } + + ring->unlock(ring, flags); + + evl_schedule(); + + return ret; +} + +static ssize_t do_xbuf_write(struct xbuf_ring *ring, + struct xbuf_wdesc *wd, int f_flags) +{ + ssize_t len, ret, wbytes, n; + unsigned int wroff, avail; + unsigned long flags; + bool sigpoll; + int xret; + + len = wd->count; + if (len == 0) + return 0; + + if (ring->bufsz == 0) + return -ENOBUFS; + + wd->buf_ptr = wd->buf; + + for (;;) { + flags = ring->lock(ring); + /* + * No short or scattered writes: we should write the + * entire message atomically or block. + */ + avail = ring->fillsz + ring->wrrsvd; + if (avail + len > ring->bufsz) { + ring->unlock(ring, flags); + + if (f_flags & O_NONBLOCK) + return -EAGAIN; + + ret = ring->wait_output(ring, len); + if (unlikely(ret)) + return ret; + + continue; + } + + /* Reserve a write slot into the circular buffer. */ + wroff = ring->wroff; + ring->wroff = (wroff + len) % ring->bufsz; + ring->wrpending++; + ring->wrrsvd += len; + wbytes = ret = len; + + do { + if (wroff + wbytes > ring->bufsz) + n = ring->bufsz - wroff; + else + n = wbytes; + + /* + * We have to drop the lock while reading in + * data, but we can't rollback on bad read + * from user because some other thread might + * have populated the memory ahead of our + * write slot already: bluntly clear the + * unavailable bytes on copy error. + */ + ring->unlock(ring, flags); + xret = wd->xfer(ring->bufmem + wroff, wd, n); + flags = ring->lock(ring); + if (xret) { + memset(ring->bufmem + wroff + n - xret, 0, xret); + ret = -EFAULT; + break; + } + + wd->buf_ptr += n; + wbytes -= n; + wroff = (wroff + n) % ring->bufsz; + } while (wbytes > 0); + + if (--ring->wrpending == 0) { + sigpoll = ring->fillsz == 0; + ring->fillsz += ring->wrrsvd; + ring->wrrsvd = 0; + ring->signal_input(ring, sigpoll); + } + + ring->unlock(ring, flags); + break; + } + + evl_schedule(); + + return ret; +} + +static unsigned long inbound_lock(struct xbuf_ring *ring) +{ + struct evl_xbuf *xbuf = container_of(ring, struct evl_xbuf, ibnd.ring); + unsigned long flags; + + raw_spin_lock_irqsave(&xbuf->ibnd.lock, flags); + + return flags; +} + +static void inbound_unlock(struct xbuf_ring *ring, unsigned long flags) +{ + struct evl_xbuf *xbuf = container_of(ring, struct evl_xbuf, ibnd.ring); + + raw_spin_unlock_irqrestore(&xbuf->ibnd.lock, flags); +} + +static int inbound_wait_input(struct xbuf_ring *ring, size_t len, size_t avail) +{ + struct evl_xbuf *xbuf = container_of(ring, struct evl_xbuf, ibnd.ring); + struct xbuf_inbound *ibnd = &xbuf->ibnd; + unsigned long flags; + bool o_blocked; + + /* + * Check whether writers are already waiting for sending data, + * while we are about to wait for receiving some. In such a + * case, we have a pathological use of the buffer due to a + * miscalculated size. We must allow for a short read to + * prevent a deadlock. + */ + if (avail > 0) { + evl_lock_flag(&ibnd->o_event, flags); + o_blocked = !!evl_wait_flag_head(&ibnd->o_event); + evl_unlock_flag(&ibnd->o_event, flags); + if (o_blocked) + return -EAGAIN; + } + + return wait_event_interruptible(ibnd->i_event, ring->fillsz >= len); +} + +static void resume_inband_reader(struct irq_work *work) +{ + struct evl_xbuf *xbuf = container_of(work, struct evl_xbuf, ibnd.irq_work); + + wake_up(&xbuf->ibnd.i_event); +} + +/* ring locked, irqsoff */ +static void inbound_signal_input(struct xbuf_ring *ring, bool sigpoll) +{ + struct evl_xbuf *xbuf = container_of(ring, struct evl_xbuf, ibnd.ring); + + irq_work_queue(&xbuf->ibnd.irq_work); +} + +static int inbound_wait_output(struct xbuf_ring *ring, size_t len) +{ + struct evl_xbuf *xbuf = container_of(ring, struct evl_xbuf, ibnd.ring); + + return evl_wait_flag(&xbuf->ibnd.o_event); +} + +static void inbound_signal_output(struct xbuf_ring *ring, bool sigpoll) +{ + struct evl_xbuf *xbuf = container_of(ring, struct evl_xbuf, ibnd.ring); + + if (sigpoll) + evl_signal_poll_events(&xbuf->poll_head, POLLOUT|POLLWRNORM); + + evl_raise_flag_nosched(&xbuf->ibnd.o_event); +} + +static ssize_t xbuf_read(struct file *filp, char __user *u_buf, + size_t count, loff_t *ppos) +{ + struct evl_xbuf *xbuf = element_of(filp, struct evl_xbuf); + struct xbuf_rdesc rd = { + .buf = u_buf, + .count = count, + .xfer = write_to_user, + }; + + return do_xbuf_read(&xbuf->ibnd.ring, &rd, filp->f_flags); +} + +static ssize_t xbuf_write(struct file *filp, const char __user *u_buf, + size_t count, loff_t *ppos) +{ + struct evl_xbuf *xbuf = element_of(filp, struct evl_xbuf); + struct xbuf_wdesc wd = { + .buf = u_buf, + .count = count, + .xfer = read_from_user, + }; + + return do_xbuf_write(&xbuf->obnd.ring, &wd, filp->f_flags); +} + +static long xbuf_ioctl(struct file *filp, + unsigned int cmd, unsigned long arg) +{ + return -ENOTTY; +} + +static __poll_t xbuf_poll(struct file *filp, poll_table *wait) +{ + struct evl_xbuf *xbuf = element_of(filp, struct evl_xbuf); + struct xbuf_outbound *obnd = &xbuf->obnd; + struct xbuf_inbound *ibnd = &xbuf->ibnd; + unsigned long flags; + __poll_t ready = 0; + + poll_wait(filp, &ibnd->i_event, wait); + poll_wait(filp, &obnd->o_event, wait); + + flags = ibnd->ring.lock(&ibnd->ring); + + if (ibnd->ring.fillsz > 0) + ready |= POLLIN|POLLRDNORM; + + ibnd->ring.unlock(&ibnd->ring, flags); + + flags = obnd->ring.lock(&obnd->ring); + + if (obnd->ring.fillsz < obnd->ring.bufsz) + ready |= POLLOUT|POLLWRNORM; + + obnd->ring.unlock(&obnd->ring, flags); + + return ready; +} + +static long xbuf_oob_ioctl(struct file *filp, + unsigned int cmd, unsigned long arg) +{ + return -ENOTTY; +} + +static unsigned long outbound_lock(struct xbuf_ring *ring) +{ + struct evl_xbuf *xbuf = container_of(ring, struct evl_xbuf, obnd.ring); + unsigned long flags; + + raw_spin_lock_irqsave(&xbuf->obnd.i_event.wchan.lock, flags); + + return flags; +} + +static void outbound_unlock(struct xbuf_ring *ring, unsigned long flags) +{ + struct evl_xbuf *xbuf = container_of(ring, struct evl_xbuf, obnd.ring); + + raw_spin_unlock_irqrestore(&xbuf->obnd.i_event.wchan.lock, flags); +} + +static int outbound_wait_input(struct xbuf_ring *ring, size_t len, size_t avail) +{ + struct evl_xbuf *xbuf = container_of(ring, struct evl_xbuf, obnd.ring); + struct xbuf_outbound *obnd = &xbuf->obnd; + + if (avail > 0 && wq_has_sleeper(&obnd->o_event)) + return -EAGAIN; + + return evl_wait_event(&obnd->i_event, ring->fillsz >= len); +} + +/* obnd.i_event locked, hard irqs off */ +static void outbound_signal_input(struct xbuf_ring *ring, bool sigpoll) +{ + struct evl_xbuf *xbuf = container_of(ring, struct evl_xbuf, obnd.ring); + + if (sigpoll) + evl_signal_poll_events(&xbuf->poll_head, POLLIN|POLLRDNORM); + + evl_flush_wait_locked(&xbuf->obnd.i_event, 0); +} + +static int outbound_wait_output(struct xbuf_ring *ring, size_t len) +{ + struct evl_xbuf *xbuf = container_of(ring, struct evl_xbuf, obnd.ring); + + return wait_event_interruptible(xbuf->obnd.o_event, + ring->fillsz + len <= ring->bufsz); +} + +static void resume_inband_writer(struct irq_work *work) +{ + struct evl_xbuf *xbuf = container_of(work, struct evl_xbuf, obnd.irq_work); + + wake_up(&xbuf->obnd.o_event); +} + +static void outbound_signal_output(struct xbuf_ring *ring, bool sigpoll) +{ + struct evl_xbuf *xbuf = container_of(ring, struct evl_xbuf, obnd.ring); + + irq_work_queue(&xbuf->obnd.irq_work); +} + +static ssize_t xbuf_oob_read(struct file *filp, + char __user *u_buf, size_t count) +{ + struct evl_xbuf *xbuf = element_of(filp, struct evl_xbuf); + struct xbuf_rdesc rd = { + .buf = u_buf, + .count = count, + .xfer = write_to_user, + }; + + return do_xbuf_read(&xbuf->obnd.ring, &rd, filp->f_flags); +} + +static ssize_t xbuf_oob_write(struct file *filp, + const char __user *u_buf, size_t count) +{ + struct evl_xbuf *xbuf = element_of(filp, struct evl_xbuf); + struct xbuf_wdesc wd = { + .buf = u_buf, + .count = count, + .xfer = read_from_user, + }; + + return do_xbuf_write(&xbuf->ibnd.ring, &wd, filp->f_flags); +} + +static __poll_t xbuf_oob_poll(struct file *filp, + struct oob_poll_wait *wait) +{ + struct evl_xbuf *xbuf = element_of(filp, struct evl_xbuf); + struct xbuf_outbound *obnd = &xbuf->obnd; + struct xbuf_inbound *ibnd = &xbuf->ibnd; + unsigned long flags; + __poll_t ready = 0; + + evl_poll_watch(&xbuf->poll_head, wait, NULL); + + flags = obnd->ring.lock(&obnd->ring); + + if (obnd->ring.fillsz > 0) + ready |= POLLIN|POLLRDNORM; + + obnd->ring.unlock(&obnd->ring, flags); + + flags = ibnd->ring.lock(&ibnd->ring); + + if (ibnd->ring.fillsz < ibnd->ring.bufsz) + ready |= POLLOUT|POLLWRNORM; + + ibnd->ring.unlock(&ibnd->ring, flags); + + return ready; +} + +static int xbuf_release(struct inode *inode, struct file *filp) +{ + struct evl_xbuf *xbuf = element_of(filp, struct evl_xbuf); + + evl_flush_wait(&xbuf->obnd.i_event, EVL_T_RMID); + evl_flush_flag(&xbuf->ibnd.o_event, EVL_T_RMID); + + return evl_release_element(inode, filp); +} + +static const struct file_operations xbuf_fops = { + .open = evl_open_element, + .release = xbuf_release, + .unlocked_ioctl = xbuf_ioctl, + .read = xbuf_read, + .write = xbuf_write, + .poll = xbuf_poll, + .oob_ioctl = xbuf_oob_ioctl, + .oob_read = xbuf_oob_read, + .oob_write = xbuf_oob_write, + .oob_poll = xbuf_oob_poll, +#ifdef CONFIG_COMPAT + .compat_ioctl = compat_ptr_ioctl, + .compat_oob_ioctl = compat_ptr_oob_ioctl, +#endif +}; + +struct evl_xbuf *evl_get_xbuf(int efd, struct evl_file **efilpp) +{ + struct evl_file *efilp = evl_get_file(efd); + + if (efilp && efilp->filp->f_op == &xbuf_fops) { + *efilpp = efilp; + return element_of(efilp->filp, struct evl_xbuf); + } + + return NULL; +} +EXPORT_SYMBOL_GPL(evl_get_xbuf); + +void evl_put_xbuf(struct evl_file *efilp) +{ + evl_put_file(efilp); +} +EXPORT_SYMBOL_GPL(evl_put_xbuf); + +ssize_t evl_read_xbuf(struct evl_xbuf *xbuf, void *buf, + size_t count, int f_flags) +{ + struct xbuf_rdesc rd = { + .buf = buf, + .count = count, + .xfer = write_to_kernel, + }; + + if (!(f_flags & O_NONBLOCK) && evl_cannot_block()) + return -EPERM; + + return do_xbuf_read(&xbuf->obnd.ring, &rd, f_flags); +} +EXPORT_SYMBOL_GPL(evl_read_xbuf); + +ssize_t evl_write_xbuf(struct evl_xbuf *xbuf, const void *buf, + size_t count, int f_flags) +{ + struct xbuf_wdesc wd = { + .buf = buf, + .count = count, + .xfer = read_from_kernel, + }; + + if (!(f_flags & O_NONBLOCK) && evl_cannot_block()) + return -EPERM; + + return do_xbuf_write(&xbuf->ibnd.ring, &wd, f_flags); +} +EXPORT_SYMBOL_GPL(evl_write_xbuf); + +static struct evl_element * +xbuf_factory_build(struct evl_factory *fac, const char __user *u_name, + void __user *u_attrs, int clone_flags, u32 *state_offp) +{ + void *i_bufmem = NULL, *o_bufmem = NULL; + struct evl_xbuf_attrs attrs; + struct evl_xbuf *xbuf; + int ret; + + ret = copy_from_user(&attrs, u_attrs, sizeof(attrs)); + if (ret) + return ERR_PTR(-EFAULT); + + if (clone_flags & ~EVL_CLONE_PUBLIC) + return ERR_PTR(-EINVAL); + + /* LART */ + if ((attrs.i_bufsz == 0 && attrs.o_bufsz == 0) || + order_base_2(attrs.i_bufsz) > 30 || + order_base_2(attrs.o_bufsz) > 30) + return ERR_PTR(-EINVAL); + + xbuf = kzalloc(sizeof(*xbuf), GFP_KERNEL); + if (xbuf == NULL) + return ERR_PTR(-ENOMEM); + + if (attrs.i_bufsz > 0) { + i_bufmem = kzalloc(attrs.i_bufsz, GFP_KERNEL); + if (i_bufmem == NULL) { + ret = -ENOMEM; + goto fail_ibufmem; + } + } + + if (attrs.o_bufsz > 0) { + o_bufmem = kzalloc(attrs.o_bufsz, GFP_KERNEL); + if (o_bufmem == NULL) { + ret = -ENOMEM; + goto fail_obufmem; + } + } + + ret = evl_init_user_element(&xbuf->element, &evl_xbuf_factory, + u_name, clone_flags); + if (ret) + goto fail_element; + + /* Inbound traffic: oob_write() -> read(). */ + init_waitqueue_head(&xbuf->ibnd.i_event); + evl_init_flag(&xbuf->ibnd.o_event); + raw_spin_lock_init(&xbuf->ibnd.lock); + init_irq_work(&xbuf->ibnd.irq_work, resume_inband_reader); + xbuf->ibnd.ring.bufmem = i_bufmem; + xbuf->ibnd.ring.bufsz = attrs.i_bufsz; + xbuf->ibnd.ring.lock = inbound_lock; + xbuf->ibnd.ring.unlock = inbound_unlock; + xbuf->ibnd.ring.wait_input = inbound_wait_input; + xbuf->ibnd.ring.signal_input = inbound_signal_input; + xbuf->ibnd.ring.wait_output = inbound_wait_output; + xbuf->ibnd.ring.signal_output = inbound_signal_output; + + /* Outbound traffic: write() -> oob_read(). */ + evl_init_wait(&xbuf->obnd.i_event, &evl_mono_clock, EVL_WAIT_PRIO); + init_waitqueue_head(&xbuf->obnd.o_event); + init_irq_work(&xbuf->obnd.irq_work, resume_inband_writer); + xbuf->obnd.ring.bufmem = o_bufmem; + xbuf->obnd.ring.bufsz = attrs.o_bufsz; + xbuf->obnd.ring.lock = outbound_lock; + xbuf->obnd.ring.unlock = outbound_unlock; + xbuf->obnd.ring.wait_input = outbound_wait_input; + xbuf->obnd.ring.signal_input = outbound_signal_input; + xbuf->obnd.ring.wait_output = outbound_wait_output; + xbuf->obnd.ring.signal_output = outbound_signal_output; + + evl_init_poll_head(&xbuf->poll_head); + + return &xbuf->element; + +fail_element: + if (o_bufmem) + kfree(o_bufmem); +fail_obufmem: + if (i_bufmem) + kfree(i_bufmem); +fail_ibufmem: + kfree(xbuf); + + return ERR_PTR(ret); +} + +static void xbuf_factory_dispose(struct evl_element *e) +{ + struct evl_xbuf *xbuf; + + xbuf = container_of(e, struct evl_xbuf, element); + + evl_destroy_wait(&xbuf->obnd.i_event); + evl_destroy_flag(&xbuf->ibnd.o_event); + evl_destroy_element(&xbuf->element); + if (xbuf->ibnd.ring.bufmem) + kfree(xbuf->ibnd.ring.bufmem); + if (xbuf->obnd.ring.bufmem) + kfree(xbuf->obnd.ring.bufmem); + kfree_rcu(xbuf, element.rcu); +} + +static ssize_t rings_show(struct device *dev, + struct device_attribute *attr, + char *buf) +{ + struct evl_xbuf *xbuf; + ssize_t ret; + + xbuf = evl_get_element_by_dev(dev, struct evl_xbuf); + if (xbuf == NULL) + return -EIO; + + ret = snprintf(buf, PAGE_SIZE, "%zu %zu %zu %zu\n", + xbuf->ibnd.ring.fillsz, + xbuf->ibnd.ring.bufsz, + xbuf->obnd.ring.fillsz, + xbuf->obnd.ring.bufsz); + + evl_put_element(&xbuf->element); + + return ret; +} +static DEVICE_ATTR_RO(rings); + +static struct attribute *xbuf_attrs[] = { + &dev_attr_rings.attr, + NULL, +}; +ATTRIBUTE_GROUPS(xbuf); + +struct evl_factory evl_xbuf_factory = { + .name = EVL_XBUF_DEV, + .fops = &xbuf_fops, + .build = xbuf_factory_build, + .dispose = xbuf_factory_dispose, + .nrdev = CONFIG_EVL_NR_XBUFS, + .attrs = xbuf_groups, + .flags = EVL_FACTORY_CLONE, +}; diff --git a/kernel/exit.c b/kernel/exit.c index 3540b2c9b..49574bf8d 100644 --- a/kernel/exit.c +++ b/kernel/exit.c @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -828,6 +829,7 @@ void __noreturn do_exit(long code) io_uring_files_cancel(); exit_signals(tsk); /* sets PF_EXITING */ + inband_exit_notify(); /* sync mm's RSS info before statistics gathering */ if (tsk->mm) diff --git a/kernel/fork.c b/kernel/fork.c index 23efaa2c4..6b51aa48f 100644 --- a/kernel/fork.c +++ b/kernel/fork.c @@ -49,6 +49,7 @@ #include #include #include +#include #include #include #include @@ -1140,6 +1141,7 @@ static struct task_struct *dup_task_struct(struct task_struct *orig, int node) #endif setup_thread_stack(tsk, orig); + inband_task_init(tsk); clear_user_return_notifier(tsk); clear_tsk_need_resched(tsk); set_task_stack_end_magic(tsk); @@ -1287,6 +1289,9 @@ static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p, #endif mm_init_uprobes_state(mm); hugetlb_count_init(mm); +#ifdef CONFIG_DOVETAIL + memset(&mm->oob_state, 0, sizeof(mm->oob_state)); +#endif if (current->mm) { mm->flags = mmf_init_flags(current->mm->flags); @@ -1347,6 +1352,7 @@ static inline void __mmput(struct mm_struct *mm) exit_aio(mm); ksm_exit(mm); khugepaged_exit(mm); /* must run before exit_mmap */ + inband_cleanup_notify(mm); /* ditto. */ exit_mmap(mm); mm_put_huge_zero_page(mm); set_mm_exe_file(mm, NULL); diff --git a/kernel/irq/Kconfig b/kernel/irq/Kconfig index 2531f3496..7ea943d55 100644 --- a/kernel/irq/Kconfig +++ b/kernel/irq/Kconfig @@ -137,6 +137,20 @@ config GENERIC_IRQ_DEBUGFS If you don't know what to do here, say N. +# Interrupt pipeline +config HAVE_IRQ_PIPELINE + bool + +config IRQ_PIPELINE + bool "Interrupt pipeline" + depends on HAVE_IRQ_PIPELINE + select IRQ_DOMAIN + select IRQ_DOMAIN_NOMAP + default n + help + Activate this option if you want the interrupt pipeline to be + compiled in. + endmenu config GENERIC_IRQ_MULTI_HANDLER diff --git a/kernel/irq/Makefile b/kernel/irq/Makefile index f19d3080b..b94043306 100644 --- a/kernel/irq/Makefile +++ b/kernel/irq/Makefile @@ -9,6 +9,8 @@ obj-$(CONFIG_GENERIC_IRQ_CHIP) += generic-chip.o obj-$(CONFIG_GENERIC_IRQ_PROBE) += autoprobe.o obj-$(CONFIG_IRQ_DOMAIN) += irqdomain.o obj-$(CONFIG_IRQ_SIM) += irq_sim.o +obj-$(CONFIG_IRQ_PIPELINE) += pipeline.o +obj-$(CONFIG_IRQ_PIPELINE_TORTURE_TEST) += irqptorture.o obj-$(CONFIG_PROC_FS) += proc.o obj-$(CONFIG_GENERIC_PENDING_IRQ) += migration.o obj-$(CONFIG_GENERIC_IRQ_MIGRATION) += cpuhotplug.o diff --git a/kernel/irq/chip.c b/kernel/irq/chip.c index dc94e0bf2..2fe9aa5f8 100644 --- a/kernel/irq/chip.c +++ b/kernel/irq/chip.c @@ -14,6 +14,7 @@ #include #include #include +#include #include @@ -47,6 +48,11 @@ int irq_set_chip(unsigned int irq, const struct irq_chip *chip) return -EINVAL; desc->irq_data.chip = (struct irq_chip *)(chip ?: &no_irq_chip); + + WARN_ONCE(irqs_pipelined() && chip && + (chip->flags & IRQCHIP_PIPELINE_SAFE) == 0, + "irqchip %s is not pipeline-safe!", chip->name); + irq_put_desc_unlock(desc, flags); /* * For !CONFIG_SPARSE_IRQ make the irq show up in @@ -385,7 +391,8 @@ static void __irq_disable(struct irq_desc *desc, bool mask) */ void irq_disable(struct irq_desc *desc) { - __irq_disable(desc, irq_settings_disable_unlazy(desc)); + __irq_disable(desc, + irq_settings_disable_unlazy(desc) || irqs_pipelined()); } void irq_percpu_enable(struct irq_desc *desc, unsigned int cpu) @@ -499,6 +506,158 @@ static bool irq_check_poll(struct irq_desc *desc) return irq_wait_for_poll(desc); } +enum { + IRQ_FLOW_START, + IRQ_FLOW_PILEUP, + IRQ_FLOW_REPLAY, + IRQ_FLOW_FORWARD, +}; + +#ifdef CONFIG_IRQ_PIPELINE + +static inline bool may_start_flow(int flow) +{ + return flow != IRQ_FLOW_REPLAY && flow != IRQ_FLOW_FORWARD; +} + +void irq_clear_deferral(struct irq_desc *desc) +{ + desc->istate &= ~IRQS_DEFERRED; +} + +void irq_clear_forward(struct irq_desc *desc) +{ + desc->istate &= ~IRQS_FORWARDED; +} + +static irqreturn_t forward_irq_event(struct irq_desc *desc) +{ + irqreturn_t ret = IRQ_HANDLED; + + if (likely(running_inband())) { + raw_spin_unlock(&desc->lock); + ret = handle_irq_event_percpu(desc); + raw_spin_lock(&desc->lock); + } + + return ret; +} + +#else + +static inline bool may_start_flow(int flow) +{ + return true; +} + +irqreturn_t forward_irq_event(struct irq_desc *desc) +{ + return IRQ_NONE; +} + +#endif + +/* + * get_flow_step - Determine which step of the interrupt flow handling + * we are in. + * + * When interrupt pipelining is enabled, interrupt flow handlers may + * be called twice for each event, following either of these patterns: + * + * - initially from the pipeline entry context in a attempt to handle + * the hardware event from the oob stage, next if the event was + * deferred to the in-band stage in absence of any oob handler. In + * the first case, we have to ack the hardware before feeding the + * pipeline. Otherwise, we should simply run the action associated + * to the event from the in-band stage. In this case, the IRQ action + * handler is called only once from the in-band stage. + * + * OR, + * + * - initially from the pipeline entry context for handling the + * hardware event from the oob stage. The action handler may then + * issue a forwarding request of the incoming event to the in-band + * stage once done. In this case, the same IRQ action handler is + * called twice, first from the oob stage then from the in-band + * stage. + * + * When IRQ forwarding is requested by an oob action handler + * (IRQS_FORWARDED is set in the per-descriptor state), acknowledge + * was already sent to the hardware, therefore we want to skip this + * part when running the in-band call. + * + * With stacked irqchips, handlers of parent irqs not delivered to the + * oob stage would decode and post the cascaded events to the in-band + * stage as well. The internal per-descriptor IRQS_DEFERRED flag + * disambiguates between the latter context and events being replayed + * after deferral to the in-band stage, so that we do ack the hardware + * for cascaded events as expected. + * + * We might also receive a subsequent unmasked edge event on the same + * line while a deferred one is still pending replay from the in-band + * stage (hard irqs are on for replay). The flow state enumeration + * disambiguates all cases as follows: + * + * - IRQ_FLOW_START: we are running oob on behalf of the low-level irq + * entry code, no deferred event is pending replay for the same + * line, we need to send ack to the hardware. + * + * - IRQ_FLOW_PILEUP: we are running in-band for synchronizing the irq + * log, one or more deferred events are already pending replay for + * the same line, we need to ack the subsequent event to the + * hardware too. + * + * - IRQ_FLOW_REPLAY: we are (re)playing a deferred event from the + * in-band stage, as a result of synchronizing the irq log. A + * deferred event was NOT handled from the oob stage by definition. + * + * - IRQ_FLOW_FORWARD: we are running in-band for passing a forwarded + * event already handled from the oob stage to the action + * handler. This mode allows for two-step subsequent handling of an + * IRQ event over both stages by the same action + * handler. IRQ_FLOW_FORWARD is mutually exclusive with + * IRQ_FLOW_REPLAY since only the oob handler may request + * forwarding. + */ +static inline unsigned int get_flow_step(struct irq_desc *desc) +{ + if (!irqs_pipelined()) + return IRQ_FLOW_START; + + if (!(desc->istate & IRQS_DEFERRED)) + return desc->istate & IRQS_FORWARDED ? + IRQ_FLOW_FORWARD : IRQ_FLOW_START; + + return in_pipeline() ? IRQ_FLOW_PILEUP : IRQ_FLOW_REPLAY; +} + +/* + * should_feed_pipeline - Determine whether we should be feeding the + * interrupt pipeline with the incoming event. + * + * Depending on the flow state determined by get_flow_step(), the + * event is passed to the oob handler or directly replayed from the + * current in-band stage. + */ +static inline bool should_feed_pipeline(struct irq_desc *desc, int state) +{ + if (!irqs_pipelined()) + return false; + + switch (state) { + case IRQ_FLOW_REPLAY: /* Deferred to in-band. */ + irq_clear_deferral(desc); + break; + case IRQ_FLOW_FORWARD: /* Handled oob, forwarded in-band. */ + irq_clear_forward(desc); + break; + default: + return true; + } + + return false; +} + static bool irq_may_run(struct irq_desc *desc) { unsigned int mask = IRQD_IRQ_INPROGRESS | IRQD_WAKEUP_ARMED; @@ -514,8 +673,22 @@ static bool irq_may_run(struct irq_desc *desc) * If the interrupt is an armed wakeup source, mark it pending * and suspended, disable it and notify the pm core about the * event. + * + * When pipelining, the logic is as follows: + * + * - from a pipeline entry context, we might have preempted + * the oob stage, or irqs might be [virtually] off, so we may + * not run the in-band PM code. Just make sure any wakeup + * interrupt is detected later on when the flow handler + * re-runs from the in-band stage. + * + * - from the in-band context, run the PM wakeup check. */ - if (irq_pm_check_wakeup(desc)) + if (irqs_pipelined()) { + WARN_ON_ONCE(irq_pipeline_debug() && !in_pipeline()); + if (irqd_is_wakeup_armed(&desc->irq_data)) + return true; + } else if (irq_pm_check_wakeup(desc)) return false; /* @@ -537,20 +710,32 @@ static bool irq_may_run(struct irq_desc *desc) */ void handle_simple_irq(struct irq_desc *desc) { + int flow; + raw_spin_lock(&desc->lock); - if (!irq_may_run(desc)) + flow = get_flow_step(desc); + if (may_start_flow(flow) && !irq_may_run(desc)) goto out_unlock; - desc->istate &= ~(IRQS_REPLAY | IRQS_WAITING); - - if (unlikely(!desc->action || irqd_irq_disabled(&desc->irq_data))) { - desc->istate |= IRQS_PENDING; + if (should_feed_pipeline(desc, flow)) { + handle_oob_irq(desc); goto out_unlock; } - kstat_incr_irqs_this_cpu(desc); - handle_irq_event(desc); + if (flow == IRQ_FLOW_FORWARD) { + forward_irq_event(desc); + } else { + desc->istate &= ~(IRQS_REPLAY | IRQS_WAITING); + + if (unlikely(!desc->action || irqd_irq_disabled(&desc->irq_data))) { + desc->istate |= IRQS_PENDING; + goto out_unlock; + } + + kstat_incr_irqs_this_cpu(desc); + handle_irq_event(desc); + } out_unlock: raw_spin_unlock(&desc->lock); @@ -572,10 +757,23 @@ EXPORT_SYMBOL_GPL(handle_simple_irq); */ void handle_untracked_irq(struct irq_desc *desc) { + int flow; + raw_spin_lock(&desc->lock); - if (!irq_may_run(desc)) + flow = get_flow_step(desc); + if (may_start_flow(flow) && !irq_may_run(desc)) + goto out_unlock; + + if (should_feed_pipeline(desc, flow)) { + handle_oob_irq(desc); + goto out_unlock; + } + + if (flow == IRQ_FLOW_FORWARD) { + forward_irq_event(desc); goto out_unlock; + } desc->istate &= ~(IRQS_REPLAY | IRQS_WAITING); @@ -598,6 +796,20 @@ void handle_untracked_irq(struct irq_desc *desc) } EXPORT_SYMBOL_GPL(handle_untracked_irq); +static inline void cond_eoi_irq(struct irq_desc *desc) +{ + struct irq_chip *chip = desc->irq_data.chip; + + if (!(chip->flags & IRQCHIP_EOI_THREADED)) + chip->irq_eoi(&desc->irq_data); +} + +static inline void mask_cond_eoi_irq(struct irq_desc *desc) +{ + mask_irq(desc); + cond_eoi_irq(desc); +} + /* * Called unconditionally from handle_level_irq() and only for oneshot * interrupts from handle_fasteoi_irq() @@ -627,11 +839,28 @@ static void cond_unmask_irq(struct irq_desc *desc) */ void handle_level_irq(struct irq_desc *desc) { + int flow; + raw_spin_lock(&desc->lock); - mask_ack_irq(desc); - if (!irq_may_run(desc)) + flow = get_flow_step(desc); + if (may_start_flow(flow)) { + mask_ack_irq(desc); + + if (!irq_may_run(desc)) + goto out_unlock; + } + + if (should_feed_pipeline(desc, flow)) { + if (handle_oob_irq(desc)) + goto out_unmask; goto out_unlock; + } + + if (flow == IRQ_FLOW_FORWARD) { + forward_irq_event(desc); + goto out_unlock; + } desc->istate &= ~(IRQS_REPLAY | IRQS_WAITING); @@ -646,7 +875,7 @@ void handle_level_irq(struct irq_desc *desc) kstat_incr_irqs_this_cpu(desc); handle_irq_event(desc); - +out_unmask: cond_unmask_irq(desc); out_unlock: @@ -657,7 +886,10 @@ EXPORT_SYMBOL_GPL(handle_level_irq); static void cond_unmask_eoi_irq(struct irq_desc *desc, struct irq_chip *chip) { if (!(desc->istate & IRQS_ONESHOT)) { - chip->irq_eoi(&desc->irq_data); + if (!irqs_pipelined()) + chip->irq_eoi(&desc->irq_data); + else if (!irqd_irq_disabled(&desc->irq_data)) + unmask_irq(desc); return; } /* @@ -668,9 +900,11 @@ static void cond_unmask_eoi_irq(struct irq_desc *desc, struct irq_chip *chip) */ if (!irqd_irq_disabled(&desc->irq_data) && irqd_irq_masked(&desc->irq_data) && !desc->threads_oneshot) { - chip->irq_eoi(&desc->irq_data); + if (!irqs_pipelined()) + chip->irq_eoi(&desc->irq_data); unmask_irq(desc); - } else if (!(chip->flags & IRQCHIP_EOI_THREADED)) { + } else if (!irqs_pipelined() && + !(chip->flags & IRQCHIP_EOI_THREADED)) { chip->irq_eoi(&desc->irq_data); } } @@ -687,6 +921,7 @@ static void cond_unmask_eoi_irq(struct irq_desc *desc, struct irq_chip *chip) void handle_fasteoi_irq(struct irq_desc *desc) { struct irq_chip *chip = desc->irq_data.chip; + int flow; raw_spin_lock(&desc->lock); @@ -695,12 +930,26 @@ void handle_fasteoi_irq(struct irq_desc *desc) * can arrive on the new CPU before the original CPU has completed * handling the previous one - it may need to be resent. */ - if (!irq_may_run(desc)) { + flow = get_flow_step(desc); + if (may_start_flow(flow) && !irq_may_run(desc)) { if (irqd_needs_resend_when_in_progress(&desc->irq_data)) desc->istate |= IRQS_PENDING; goto out; } + if (should_feed_pipeline(desc, flow)) { + if (handle_oob_irq(desc)) + chip->irq_eoi(&desc->irq_data); + else + mask_cond_eoi_irq(desc); + goto out_unlock; + } + + if (flow == IRQ_FLOW_FORWARD) { + forward_irq_event(desc); + goto out_unlock; + } + desc->istate &= ~(IRQS_REPLAY | IRQS_WAITING); /* @@ -714,7 +963,7 @@ void handle_fasteoi_irq(struct irq_desc *desc) } kstat_incr_irqs_this_cpu(desc); - if (desc->istate & IRQS_ONESHOT) + if (!irqs_pipelined() && (desc->istate & IRQS_ONESHOT)) mask_irq(desc); handle_irq_event(desc); @@ -727,6 +976,7 @@ void handle_fasteoi_irq(struct irq_desc *desc) if (unlikely(desc->istate & IRQS_PENDING)) check_irq_resend(desc, false); +out_unlock: raw_spin_unlock(&desc->lock); return; out: @@ -786,35 +1036,54 @@ EXPORT_SYMBOL_GPL(handle_fasteoi_nmi); */ void handle_edge_irq(struct irq_desc *desc) { + struct irq_chip *chip = irq_desc_get_chip(desc); + int flow; + raw_spin_lock(&desc->lock); - desc->istate &= ~(IRQS_REPLAY | IRQS_WAITING); + flow = get_flow_step(desc); + if (may_start_flow(flow)) { + desc->istate &= ~(IRQS_REPLAY | IRQS_WAITING); - if (!irq_may_run(desc)) { - desc->istate |= IRQS_PENDING; - mask_ack_irq(desc); - goto out_unlock; + if (!irq_may_run(desc)) { + desc->istate |= IRQS_PENDING; + mask_ack_irq(desc); + goto out; + } + + /* + * If its disabled or no action available then mask it + * and get out of here. + */ + if (irqd_irq_disabled(&desc->irq_data) || !desc->action) { + desc->istate |= IRQS_PENDING; + mask_ack_irq(desc); + goto out; + } } - /* - * If its disabled or no action available then mask it and get - * out of here. - */ - if (irqd_irq_disabled(&desc->irq_data) || !desc->action) { - desc->istate |= IRQS_PENDING; - mask_ack_irq(desc); + if (should_feed_pipeline(desc, flow)) { + chip->irq_ack(&desc->irq_data); + desc->istate |= IRQS_EDGE; + handle_oob_irq(desc); + goto out; + } + + if (flow == IRQ_FLOW_FORWARD) { + forward_irq_event(desc); goto out_unlock; } kstat_incr_irqs_this_cpu(desc); /* Start handling the irq */ - desc->irq_data.chip->irq_ack(&desc->irq_data); + if (!irqs_pipelined()) + chip->irq_ack(&desc->irq_data); do { if (unlikely(!desc->action)) { mask_irq(desc); - goto out_unlock; + goto out; } /* @@ -833,6 +1102,9 @@ void handle_edge_irq(struct irq_desc *desc) } while ((desc->istate & IRQS_PENDING) && !irqd_irq_disabled(&desc->irq_data)); +out: + if (on_pipeline_entry()) + desc->istate &= ~IRQS_EDGE; out_unlock: raw_spin_unlock(&desc->lock); } @@ -849,14 +1121,30 @@ EXPORT_SYMBOL(handle_edge_irq); void handle_edge_eoi_irq(struct irq_desc *desc) { struct irq_chip *chip = irq_desc_get_chip(desc); + int flow; raw_spin_lock(&desc->lock); - desc->istate &= ~(IRQS_REPLAY | IRQS_WAITING); + flow = get_flow_step(desc); + if (may_start_flow(flow)) { + desc->istate &= ~(IRQS_REPLAY | IRQS_WAITING); - if (!irq_may_run(desc)) { - desc->istate |= IRQS_PENDING; - goto out_eoi; + if (!irq_may_run(desc)) { + desc->istate |= IRQS_PENDING; + goto out_eoi; + } + } + + if (should_feed_pipeline(desc, flow)) { + desc->istate |= IRQS_EDGE; + if (handle_oob_irq(desc)) + goto out_eoi; + goto out; + } + + if (flow == IRQ_FLOW_FORWARD) { + forward_irq_event(desc); + goto out_unlock; } /* @@ -881,6 +1169,10 @@ void handle_edge_eoi_irq(struct irq_desc *desc) out_eoi: chip->irq_eoi(&desc->irq_data); +out: + if (on_pipeline_entry()) + desc->istate &= ~IRQS_EDGE; +out_unlock: raw_spin_unlock(&desc->lock); } #endif @@ -894,20 +1186,49 @@ void handle_edge_eoi_irq(struct irq_desc *desc) void handle_percpu_irq(struct irq_desc *desc) { struct irq_chip *chip = irq_desc_get_chip(desc); + unsigned long flags; + bool handled; + int flow; + + if (irqs_pipelined()) { + flow = get_flow_step(desc); + if (may_start_flow(flow)) { + if (chip->irq_ack) + chip->irq_ack(&desc->irq_data); + handled = handle_oob_irq(desc); + if (chip->irq_eoi) + chip->irq_eoi(&desc->irq_data); + if (!handled && chip->irq_mask) + chip->irq_mask(&desc->irq_data); + } else if (flow == IRQ_FLOW_FORWARD) { + handle_irq_event_percpu(desc); + } else { + __kstat_incr_irqs_this_cpu(desc); + handle_irq_event_percpu(desc); + /* + * irqchip handlers assume that hard irqs are + * off, which is not the case on replay of + * unserialized percpu irqs: fix this up. + */ + if (chip->irq_unmask) { + flags = hard_cond_local_irq_save(); + chip->irq_unmask(&desc->irq_data); + hard_cond_local_irq_restore(flags); + } + } + } else { + /* + * PER CPU interrupts are not serialized. Do not touch + * desc->tot_count. + */ + __kstat_incr_irqs_this_cpu(desc); - /* - * PER CPU interrupts are not serialized. Do not touch - * desc->tot_count. - */ - __kstat_incr_irqs_this_cpu(desc); - - if (chip->irq_ack) - chip->irq_ack(&desc->irq_data); - - handle_irq_event_percpu(desc); - - if (chip->irq_eoi) - chip->irq_eoi(&desc->irq_data); + if (chip->irq_ack) + chip->irq_ack(&desc->irq_data); + handle_irq_event_percpu(desc); + if (chip->irq_eoi) + chip->irq_eoi(&desc->irq_data); + } } /** @@ -926,7 +1247,29 @@ void handle_percpu_devid_irq(struct irq_desc *desc) struct irq_chip *chip = irq_desc_get_chip(desc); struct irqaction *action = desc->action; unsigned int irq = irq_desc_get_irq(desc); + unsigned long flags; irqreturn_t res; + bool handled; + int flow; + + flow = get_flow_step(desc); + if (irqs_pipelined()) { + if (may_start_flow(flow)) { + if (chip->irq_ack) + chip->irq_ack(&desc->irq_data); + handled = handle_oob_irq(desc); + if (chip->irq_eoi) + chip->irq_eoi(&desc->irq_data); + if (!handled && chip->irq_mask) + chip->irq_mask(&desc->irq_data); + return; + } else if (flow == IRQ_FLOW_FORWARD) { + handle_irq_event_percpu(desc); + return; + } + } else if (chip->irq_ack) { + chip->irq_ack(&desc->irq_data); + } /* * PER CPU interrupts are not serialized. Do not touch @@ -934,9 +1277,6 @@ void handle_percpu_devid_irq(struct irq_desc *desc) */ __kstat_incr_irqs_this_cpu(desc); - if (chip->irq_ack) - chip->irq_ack(&desc->irq_data); - if (likely(action)) { trace_irq_handler_entry(irq, action); res = action->handler(irq, raw_cpu_ptr(action->percpu_dev_id)); @@ -952,8 +1292,19 @@ void handle_percpu_devid_irq(struct irq_desc *desc) enabled ? " and unmasked" : "", irq, cpu); } - if (chip->irq_eoi) + if (irqs_pipelined()) { + /* + * irqchip handlers assume that hard irqs are off, + * which is not the case on replay of unserialized + * percpu irqs: fix this up. + */ + flags = hard_cond_local_irq_save(); + if (chip->irq_unmask) + chip->irq_unmask(&desc->irq_data); + hard_cond_local_irq_restore(flags); + } else if (chip->irq_eoi) { chip->irq_eoi(&desc->irq_data); + } } /** @@ -963,6 +1314,8 @@ void handle_percpu_devid_irq(struct irq_desc *desc) * * Similar to handle_fasteoi_nmi, but handling the dev_id cookie * as a percpu pointer. + * + * irq_pipeline: we never log & replay NMIs. */ void handle_percpu_devid_fasteoi_nmi(struct irq_desc *desc) { @@ -1045,6 +1398,7 @@ __irq_do_set_handler(struct irq_desc *desc, irq_flow_handler_t handle, desc->handle_irq = handle; } + irq_settings_set_chained(desc); irq_settings_set_noprobe(desc); irq_settings_set_norequest(desc); irq_settings_set_nothread(desc); @@ -1212,12 +1566,28 @@ void irq_cpu_offline(void) void handle_fasteoi_ack_irq(struct irq_desc *desc) { struct irq_chip *chip = desc->irq_data.chip; + int flow; raw_spin_lock(&desc->lock); - if (!irq_may_run(desc)) + flow = get_flow_step(desc); + if (may_start_flow(flow) && !irq_may_run(desc)) goto out; + if (should_feed_pipeline(desc, flow)) { + chip->irq_ack(&desc->irq_data); + if (handle_oob_irq(desc)) + chip->irq_eoi(&desc->irq_data); + else + mask_cond_eoi_irq(desc); + goto out_unlock; + } + + if (flow == IRQ_FLOW_FORWARD) { + forward_irq_event(desc); + goto out_unlock; + } + desc->istate &= ~(IRQS_REPLAY | IRQS_WAITING); /* @@ -1231,11 +1601,13 @@ void handle_fasteoi_ack_irq(struct irq_desc *desc) } kstat_incr_irqs_this_cpu(desc); - if (desc->istate & IRQS_ONESHOT) - mask_irq(desc); + if (!irqs_pipelined()) { + if (desc->istate & IRQS_ONESHOT) + mask_irq(desc); - /* Start handling the irq */ - desc->irq_data.chip->irq_ack(&desc->irq_data); + /* Start handling the irq */ + chip->irq_ack(&desc->irq_data); + } handle_irq_event(desc); @@ -1246,6 +1618,7 @@ void handle_fasteoi_ack_irq(struct irq_desc *desc) out: if (!(chip->flags & IRQCHIP_EOI_IF_HANDLED)) chip->irq_eoi(&desc->irq_data); +out_unlock: raw_spin_unlock(&desc->lock); } EXPORT_SYMBOL_GPL(handle_fasteoi_ack_irq); @@ -1263,12 +1636,30 @@ EXPORT_SYMBOL_GPL(handle_fasteoi_ack_irq); void handle_fasteoi_mask_irq(struct irq_desc *desc) { struct irq_chip *chip = desc->irq_data.chip; + int flow; raw_spin_lock(&desc->lock); - mask_ack_irq(desc); - if (!irq_may_run(desc)) - goto out; + flow = get_flow_step(desc); + if (may_start_flow(flow)) { + mask_ack_irq(desc); + + if (!irq_may_run(desc)) + goto out; + } + + if (should_feed_pipeline(desc, flow)) { + if (handle_oob_irq(desc)) + chip->irq_eoi(&desc->irq_data); + else + cond_eoi_irq(desc); + goto out_unlock; + } + + if (flow == IRQ_FLOW_FORWARD) { + forward_irq_event(desc); + goto out_unlock; + } desc->istate &= ~(IRQS_REPLAY | IRQS_WAITING); @@ -1283,7 +1674,7 @@ void handle_fasteoi_mask_irq(struct irq_desc *desc) } kstat_incr_irqs_this_cpu(desc); - if (desc->istate & IRQS_ONESHOT) + if (!irqs_pipelined() && (desc->istate & IRQS_ONESHOT)) mask_irq(desc); handle_irq_event(desc); @@ -1295,6 +1686,7 @@ void handle_fasteoi_mask_irq(struct irq_desc *desc) out: if (!(chip->flags & IRQCHIP_EOI_IF_HANDLED)) chip->irq_eoi(&desc->irq_data); +out_unlock: raw_spin_unlock(&desc->lock); } EXPORT_SYMBOL_GPL(handle_fasteoi_mask_irq); diff --git a/kernel/irq/cpuhotplug.c b/kernel/irq/cpuhotplug.c index eb8628390..46f2f2633 100644 --- a/kernel/irq/cpuhotplug.c +++ b/kernel/irq/cpuhotplug.c @@ -172,6 +172,9 @@ void irq_migrate_all_off_this_cpu(void) { struct irq_desc *desc; unsigned int irq; + unsigned long flags; + + flags = hard_local_irq_save(); for_each_active_irq(irq) { bool affinity_broken; @@ -186,6 +189,8 @@ void irq_migrate_all_off_this_cpu(void) irq, smp_processor_id()); } } + + hard_local_irq_restore(flags); } static bool hk_should_isolate(struct irq_data *data, unsigned int cpu) diff --git a/kernel/irq/debug.h b/kernel/irq/debug.h index 8ccb326d2..40f726845 100644 --- a/kernel/irq/debug.h +++ b/kernel/irq/debug.h @@ -33,6 +33,8 @@ static inline void print_irq_desc(unsigned int irq, struct irq_desc *desc) ___P(IRQ_NOREQUEST); ___P(IRQ_NOTHREAD); ___P(IRQ_NOAUTOEN); + ___P(IRQ_OOB); + ___P(IRQ_CHAINED); ___PS(IRQS_AUTODETECT); ___PS(IRQS_REPLAY); diff --git a/kernel/irq/dummychip.c b/kernel/irq/dummychip.c index 7fe6cffe7..d25a1a23d 100644 --- a/kernel/irq/dummychip.c +++ b/kernel/irq/dummychip.c @@ -43,7 +43,7 @@ struct irq_chip no_irq_chip = { .irq_enable = noop, .irq_disable = noop, .irq_ack = ack_bad, - .flags = IRQCHIP_SKIP_SET_WAKE, + .flags = IRQCHIP_SKIP_SET_WAKE | IRQCHIP_PIPELINE_SAFE, }; /* @@ -59,6 +59,6 @@ struct irq_chip dummy_irq_chip = { .irq_ack = noop, .irq_mask = noop, .irq_unmask = noop, - .flags = IRQCHIP_SKIP_SET_WAKE, + .flags = IRQCHIP_SKIP_SET_WAKE | IRQCHIP_PIPELINE_SAFE, }; EXPORT_SYMBOL_GPL(dummy_irq_chip); diff --git a/kernel/irq/generic-chip.c b/kernel/irq/generic-chip.c index 5a452b94b..5a2c69dec 100644 --- a/kernel/irq/generic-chip.c +++ b/kernel/irq/generic-chip.c @@ -16,7 +16,7 @@ #include "internals.h" static LIST_HEAD(gc_list); -static DEFINE_RAW_SPINLOCK(gc_lock); +static DEFINE_HARD_SPINLOCK(gc_lock); /** * irq_gc_noop - NOOP function diff --git a/kernel/irq/handle.c b/kernel/irq/handle.c index 9489f93b3..a6c90482d 100644 --- a/kernel/irq/handle.c +++ b/kernel/irq/handle.c @@ -34,9 +34,16 @@ void handle_bad_irq(struct irq_desc *desc) { unsigned int irq = irq_desc_get_irq(desc); + /* Let the in-band stage report the issue. */ + if (on_pipeline_entry()) { + ack_bad_irq(irq); + return; + } + print_irq_desc(irq, desc); kstat_incr_irqs_this_cpu(desc); - ack_bad_irq(irq); + if (!irqs_pipelined()) + ack_bad_irq(irq); } EXPORT_SYMBOL_GPL(handle_bad_irq); diff --git a/kernel/irq/internals.h b/kernel/irq/internals.h index bcc7f21db..7baaf7603 100644 --- a/kernel/irq/internals.h +++ b/kernel/irq/internals.h @@ -56,6 +56,9 @@ enum { * IRQS_SUSPENDED - irq is suspended * IRQS_NMI - irq line is used to deliver NMIs * IRQS_SYSFS - descriptor has been added to sysfs + * IRQS_EDGE - irq line received an edge event (irq_pipeline) + * IRQS_DEFERRED - irq event deferred to inband (irq_pipeline) + * IRQS_FORWARDED - irq event handled and forwarded to inband (irq_pipeline) */ enum { IRQS_AUTODETECT = 0x00000001, @@ -69,6 +72,9 @@ enum { IRQS_TIMINGS = 0x00001000, IRQS_NMI = 0x00002000, IRQS_SYSFS = 0x00004000, + IRQS_EDGE = 0x00008000, + IRQS_DEFERRED = 0x00010000, + IRQS_FORWARDED = 0x00020000, }; #include "debug.h" diff --git a/kernel/irq/irqdesc.c b/kernel/irq/irqdesc.c index 46094f0c9..285f1246d 100644 --- a/kernel/irq/irqdesc.c +++ b/kernel/irq/irqdesc.c @@ -15,6 +15,7 @@ #include #include #include +#include #include "internals.h" @@ -662,6 +663,17 @@ void irq_init_desc(unsigned int irq) #endif /* !CONFIG_SPARSE_IRQ */ +static inline bool is_hardirq(struct irq_desc *desc) +{ + if (!irqs_pipelined()) + return in_hardirq(); + + if (in_pipeline() || !(desc->istate & IRQS_DEFERRED)) + return true; + + return false; +} + int handle_irq_desc(struct irq_desc *desc) { struct irq_data *data; @@ -670,7 +682,7 @@ int handle_irq_desc(struct irq_desc *desc) return -EINVAL; data = irq_desc_get_irq_data(desc); - if (WARN_ON_ONCE(!in_hardirq() && handle_enforce_irqctx(data))) + if (WARN_ON_ONCE(!is_hardirq(desc) && handle_enforce_irqctx(data))) return -EPERM; generic_handle_irq_desc(desc); @@ -678,14 +690,18 @@ int handle_irq_desc(struct irq_desc *desc) } /** - * generic_handle_irq - Invoke the handler for a particular irq + * generic_handle_irq - Handle a particular irq * @irq: The irq number to handle * * Returns: 0 on success, or -EINVAL if conversion has failed * * This function must be called from an IRQ context with irq regs * initialized. - */ + * + * The handler is invoked, unless we are entering the interrupt + * pipeline, in which case the incoming IRQ is only scheduled for + * deferred delivery. + */ int generic_handle_irq(unsigned int irq) { return handle_irq_desc(irq_to_desc(irq)); @@ -729,7 +745,10 @@ EXPORT_SYMBOL_GPL(generic_handle_irq_safe); */ int generic_handle_domain_irq(struct irq_domain *domain, unsigned int hwirq) { - return handle_irq_desc(irq_resolve_mapping(domain, hwirq)); + struct irq_desc *desc = irq_resolve_mapping(domain, hwirq); + + return irqs_pipelined() ? generic_pipeline_irq_desc(desc) + : handle_irq_desc(desc); } EXPORT_SYMBOL_GPL(generic_handle_domain_irq); diff --git a/kernel/irq/irqptorture.c b/kernel/irq/irqptorture.c new file mode 100644 index 000000000..ddd4a9c2b --- /dev/null +++ b/kernel/irq/irqptorture.c @@ -0,0 +1,326 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2017 Philippe Gerum . + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "settings.h" + +static void torture_event_handler(struct clock_event_device *dev) +{ + /* + * We are running on the oob stage, in NMI-like mode. Schedule + * a tick on the proxy device to satisfy the corresponding + * timing request asap. + */ + tick_notify_proxy(); +} + +static void setup_proxy(struct clock_proxy_device *dev) +{ + dev->handle_oob_event = torture_event_handler; +} + +static int start_tick_takeover_test(void) +{ + return tick_install_proxy(setup_proxy, cpu_online_mask); +} + +static void stop_tick_takeover_test(void) +{ + tick_uninstall_proxy(cpu_online_mask); +} + +struct stop_machine_p_data { + int origin_cpu; + cpumask_var_t disable_mask; +}; + +static int stop_machine_handler(void *arg) +{ + struct stop_machine_p_data *p = arg; + int cpu = raw_smp_processor_id(); + + /* + * The stop_machine() handler must run with hard + * IRQs off, note the current state in the result mask. + */ + if (hard_irqs_disabled()) + cpumask_set_cpu(cpu, p->disable_mask); + + if (cpu != p->origin_cpu) + pr_alert("irq_pipeline" TORTURE_FLAG + " CPU%d responds to stop_machine()\n", cpu); + return 0; +} + +/* + * We test stop_machine() as a way to validate IPI broadcast when irqs + * are pipelined. + */ +static int test_stop_machine(void) +{ + struct stop_machine_p_data d; + cpumask_var_t tmp_mask; + int ret = -ENOMEM, cpu; + + if (!zalloc_cpumask_var(&d.disable_mask, GFP_KERNEL)) { + WARN_ON(1); + return ret; + } + + if (!alloc_cpumask_var(&tmp_mask, GFP_KERNEL)) { + WARN_ON(1); + goto fail; + } + + ret = -EINVAL; + d.origin_cpu = raw_smp_processor_id(); + pr_alert("irq_pipeline" TORTURE_FLAG + " CPU%d initiates stop_machine()\n", + d.origin_cpu); + + ret = stop_machine(stop_machine_handler, &d, cpu_online_mask); + WARN_ON(ret); + if (ret) + goto fail; + + /* + * Check whether all handlers did run with hard IRQs off. If + * some of them did not, then we have a problem with the stop + * IRQ delivery. + */ + cpumask_xor(tmp_mask, cpu_online_mask, d.disable_mask); + if (!cpumask_empty(tmp_mask)) { + for_each_cpu(cpu, tmp_mask) + pr_alert("irq_pipeline" TORTURE_FLAG + " CPU%d: hard IRQs ON in stop_machine()" + " handler!\n", cpu); + } + + free_cpumask_var(tmp_mask); +fail: + free_cpumask_var(d.disable_mask); + + return ret; +} + +struct call_function_p_data { + int origin_cpu; + cpumask_var_t oob_mask; +}; + +static void remote_function_handler(void *arg) +{ + struct call_function_p_data *p = arg; + int cpu = raw_smp_processor_id(); + + if (running_oob()) + cpumask_set_cpu(cpu, p->oob_mask); + + if (cpu != p->origin_cpu) + pr_alert("irq_pipeline" TORTURE_FLAG + " CPU%d handles remote function call\n", cpu); +} + +static int test_call_function_oob(void) +{ + struct call_function_p_data d; + cpumask_var_t tmp_mask; + int ret = -ENOMEM, cpu; + + if (!zalloc_cpumask_var(&d.oob_mask, GFP_KERNEL)) { + WARN_ON(1); + return ret; + } + + if (!alloc_cpumask_var(&tmp_mask, GFP_KERNEL)) { + WARN_ON(1); + goto fail; + } + + ret = -EINVAL; + d.origin_cpu = raw_smp_processor_id(); + pr_alert("irq_pipeline" TORTURE_FLAG + " CPU%d calls function on remote(s)\n", + d.origin_cpu); + + for_each_cpu(cpu, cpu_online_mask) { + /* Issue a synchronous call to each online CPU. */ + ret = smp_call_function_oob(cpu, remote_function_handler, &d, true); + WARN_ON(ret); + if (ret) + goto fail; + } + + /* + * Check whether all callback functions did run as expected on + * the oob stage. + */ + cpumask_xor(tmp_mask, cpu_online_mask, d.oob_mask); + if (!cpumask_empty(tmp_mask)) { + for_each_cpu(cpu, tmp_mask) + pr_alert("irq_pipeline" TORTURE_FLAG + " CPU%d: remote function call did not run out-of-band!\n", + cpu); + } + + free_cpumask_var(tmp_mask); +fail: + free_cpumask_var(d.oob_mask); + + return ret; +} + +static struct irq_work_tester { + struct irq_work work; + struct completion done; +} irq_work_tester; + +static void irq_work_handler(struct irq_work *work) +{ + int cpu = raw_smp_processor_id(); + + if (!running_inband()) { + pr_alert("irq_pipeline" TORTURE_FLAG + " CPU%d: irq_work handler not running on" + " in-band stage?!\n", cpu); + return; + } + + if (work != &irq_work_tester.work) + pr_alert("irq_pipeline" TORTURE_FLAG + " CPU%d: irq_work handler received broken" + " arg?!\n", cpu); + else { + pr_alert("irq_pipeline" TORTURE_FLAG + " CPU%d: irq_work handled\n", cpu); + complete(&irq_work_tester.done); + } +} + +static int trigger_oob_work(void *arg) +{ + int cpu = raw_smp_processor_id(); + + if (!running_oob()) { + pr_alert("irq_pipeline" TORTURE_FLAG + " CPU%d: escalated request not running on" + " oob stage?!\n", cpu); + return -EINVAL; + } + + if ((struct irq_work_tester *)arg != &irq_work_tester) { + pr_alert("irq_pipeline" TORTURE_FLAG + " CPU%d: escalation handler received broken" + " arg?!\n", cpu); + return -EINVAL; + } + + irq_work_queue(&irq_work_tester.work); + pr_alert("irq_pipeline" TORTURE_FLAG + " CPU%d: stage escalation request works\n", + cpu); + + return 0; +} + +static int test_interstage_work_injection(void) +{ + struct irq_work_tester *p = &irq_work_tester; + int ret, cpu = raw_smp_processor_id(); + unsigned long rem; + + init_completion(&p->done); + init_irq_work(&p->work, irq_work_handler); + + /* Trigger over the in-band stage. */ + irq_work_queue(&p->work); + rem = wait_for_completion_timeout(&p->done, HZ / 10); + if (!rem) { + pr_alert("irq_pipeline" TORTURE_FLAG + " CPU%d: irq_work trigger from in-band stage not handled!\n", + cpu); + return -EINVAL; + } + + pr_alert("irq_pipeline" TORTURE_FLAG + " CPU%d: in-band->in-band irq_work trigger works\n", cpu); + + reinit_completion(&p->done); + + /* Now try over the oob stage. */ + ret = run_oob_call(trigger_oob_work, p); + if (ret) + return ret; + + ret = wait_for_completion_timeout(&p->done, HZ / 10); + if (!rem) { + pr_alert("irq_pipeline" TORTURE_FLAG + " CPU%d: irq_work trigger from oob" + " stage not handled!\n", cpu); + return -EINVAL; + } + + pr_alert("irq_pipeline" TORTURE_FLAG + " CPU%d: oob->in-band irq_work trigger works\n", + cpu); + + return 0; +} + +static int __init irqp_torture_init(void) +{ + int ret; + + pr_info("Starting IRQ pipeline tests..."); + + ret = enable_oob_stage("torture"); + if (ret) { + if (ret == -EBUSY) + pr_alert("irq_pipeline" TORTURE_FLAG + " won't run, oob stage '%s' is already installed", + oob_stage.name); + + return ret; + } + + ret = test_stop_machine(); + if (ret) + goto out; + + ret = test_call_function_oob(); + if (ret) + goto out; + + ret = start_tick_takeover_test(); + if (ret) + goto out; + + ret = test_interstage_work_injection(); + if (!ret) + msleep(1000); + + stop_tick_takeover_test(); +out: + disable_oob_stage(); + pr_info("IRQ pipeline tests %s.", ret ? "FAILED" : "OK"); + + return 0; +} +late_initcall(irqp_torture_init); diff --git a/kernel/irq/manage.c b/kernel/irq/manage.c index 8a936c1ff..1cf1c93e0 100644 --- a/kernel/irq/manage.c +++ b/kernel/irq/manage.c @@ -10,6 +10,7 @@ #include #include +#include #include #include #include @@ -932,6 +933,50 @@ int irq_set_irq_wake(unsigned int irq, unsigned int on) } EXPORT_SYMBOL(irq_set_irq_wake); +#ifdef CONFIG_IRQ_PIPELINE + +/** + * irq_switch_oob - Control out-of-band setting for a registered IRQ descriptor + * @irq: interrupt to control + * @on: enable/disable pipelining + * + * Enable/disable out-of-band handling for an IRQ. At least one + * action must have been previously registered for such + * interrupt. + * + * The previously registered action(s) need(s) not bearing the + * IRQF_OOB flag for the IRQ to be switched to out-of-band + * handling. This call enables switching pre-installed IRQs from + * in-band to out-of-band handling. + * + * NOTE: This routine affects all action handlers sharing the + * IRQ. + */ +int irq_switch_oob(unsigned int irq, bool on) +{ + struct irq_desc *desc; + unsigned long flags; + int ret = 0; + + desc = irq_get_desc_lock(irq, &flags, 0); + if (!desc) + return -EINVAL; + + if (!desc->action) + ret = -EINVAL; + else if (on) + irq_settings_set_oob(desc); + else + irq_settings_clr_oob(desc); + + irq_put_desc_unlock(desc, flags); + + return ret; +} +EXPORT_SYMBOL_GPL(irq_switch_oob); + +#endif /* CONFIG_IRQ_PIPELINE */ + /* * Internal function that tells the architecture code whether a * particular irq has been exclusively allocated or is available @@ -948,7 +993,8 @@ int can_request_irq(unsigned int irq, unsigned long irqflags) if (irq_settings_can_request(desc)) { if (!desc->action || - irqflags & desc->action->flags & IRQF_SHARED) + ((irqflags & desc->action->flags & IRQF_SHARED) && + !((irqflags ^ desc->action->flags) & IRQF_OOB))) canrequest = 1; } irq_put_desc_unlock(desc, flags); @@ -1522,6 +1568,21 @@ __setup_irq(unsigned int irq, struct irq_desc *desc, struct irqaction *new) new->irq = irq; + ret = -EINVAL; + /* + * Out-of-band interrupts can be shared but not threaded. We + * silently ignore the OOB setting if interrupt pipelining is + * disabled. + */ + if (!irqs_pipelined()) + new->flags &= ~IRQF_OOB; + else if (new->flags & IRQF_OOB) { + if (new->thread_fn) + goto out_mput; + new->flags |= IRQF_NO_THREAD; + new->flags &= ~IRQF_ONESHOT; + } + /* * If the trigger type is not specified by the caller, * then use the default for this interrupt. @@ -1535,10 +1596,8 @@ __setup_irq(unsigned int irq, struct irq_desc *desc, struct irqaction *new) */ nested = irq_settings_is_nested_thread(desc); if (nested) { - if (!new->thread_fn) { - ret = -EINVAL; + if (!new->thread_fn) goto out_mput; - } /* * Replace the primary handler which was provided from * the driver for non nested interrupt handling by the @@ -1622,7 +1681,7 @@ __setup_irq(unsigned int irq, struct irq_desc *desc, struct irqaction *new) * the same type (level, edge, polarity). So both flag * fields must have IRQF_SHARED set and the bits which * set the trigger type must match. Also all must - * agree on ONESHOT. + * agree on ONESHOT and OOB. * Interrupt lines used for NMIs cannot be shared. */ unsigned int oldtype; @@ -1647,7 +1706,7 @@ __setup_irq(unsigned int irq, struct irq_desc *desc, struct irqaction *new) if (!((old->flags & new->flags) & IRQF_SHARED) || (oldtype != (new->flags & IRQF_TRIGGER_MASK)) || - ((old->flags ^ new->flags) & IRQF_ONESHOT)) + ((old->flags ^ new->flags) & (IRQF_OOB|IRQF_ONESHOT))) goto mismatch; /* All handlers must agree on per-cpuness */ @@ -1770,6 +1829,9 @@ __setup_irq(unsigned int irq, struct irq_desc *desc, struct irqaction *new) if (new->flags & IRQF_ONESHOT) desc->istate |= IRQS_ONESHOT; + if (new->flags & IRQF_OOB) + irq_settings_set_oob(desc); + /* Exclude IRQ from balancing if requested */ if (new->flags & IRQF_NOBALANCING) { irq_settings_set_no_balancing(desc); @@ -1916,6 +1978,8 @@ static struct irqaction *__free_irq(struct irq_desc *desc, void *dev_id) irq_settings_clr_disable_unlazy(desc); /* Only shutdown. Deactivate after synchronize_hardirq() */ irq_shutdown(desc); + /* Turn off OOB handling (after shutdown). */ + irq_settings_clr_oob(desc); } #ifdef CONFIG_SMP @@ -1952,14 +2016,15 @@ static struct irqaction *__free_irq(struct irq_desc *desc, void *dev_id) #ifdef CONFIG_DEBUG_SHIRQ /* - * It's a shared IRQ -- the driver ought to be prepared for an IRQ - * event to happen even now it's being freed, so let's make sure that - * is so by doing an extra call to the handler .... + * It's a shared IRQ (with in-band handler) -- the driver + * ought to be prepared for an IRQ event to happen even now + * it's being freed, so let's make sure that is so by doing an + * extra call to the handler .... * * ( We do this after actually deregistering it, to make sure that a * 'real' IRQ doesn't run in parallel with our fake. ) */ - if (action->flags & IRQF_SHARED) { + if ((action->flags & (IRQF_SHARED|IRQF_OOB)) == IRQF_SHARED) { local_irq_save(flags); action->handler(irq, dev_id); local_irq_restore(flags); @@ -2583,7 +2648,7 @@ int setup_percpu_irq(unsigned int irq, struct irqaction *act) * __request_percpu_irq - allocate a percpu interrupt line * @irq: Interrupt line to allocate * @handler: Function to be called when the IRQ occurs. - * @flags: Interrupt type flags (IRQF_TIMER only) + * @flags: Interrupt type flags (IRQF_TIMER and/or IRQF_OOB only) * @devname: An ascii name for the claiming device * @dev_id: A percpu cookie passed back to the handler function * @@ -2612,7 +2677,7 @@ int __request_percpu_irq(unsigned int irq, irq_handler_t handler, !irq_settings_is_per_cpu_devid(desc)) return -EINVAL; - if (flags && flags != IRQF_TIMER) + if (flags & ~(IRQF_TIMER|IRQF_OOB)) return -EINVAL; action = kzalloc(sizeof(struct irqaction), GFP_KERNEL); diff --git a/kernel/irq/msi.c b/kernel/irq/msi.c index 79b4a58ba..0c147ad7c 100644 --- a/kernel/irq/msi.c +++ b/kernel/irq/msi.c @@ -801,6 +801,9 @@ static void msi_domain_update_chip_ops(struct msi_domain_info *info) struct irq_chip *chip = info->chip; BUG_ON(!chip || !chip->irq_mask || !chip->irq_unmask); + WARN_ONCE(IS_ENABLED(CONFIG_IRQ_PIPELINE) && + (chip->flags & IRQCHIP_PIPELINE_SAFE) == 0, + "MSI domain irqchip %s is not pipeline-safe!", chip->name); if (!chip->irq_set_affinity) chip->irq_set_affinity = msi_domain_set_affinity; } diff --git a/kernel/irq/pipeline.c b/kernel/irq/pipeline.c new file mode 100644 index 000000000..64fcf4b39 --- /dev/null +++ b/kernel/irq/pipeline.c @@ -0,0 +1,1909 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2016 Philippe Gerum . + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "internals.h" + +#ifdef CONFIG_DEBUG_IRQ_PIPELINE +#define trace_on_debug +#else +#define trace_on_debug notrace +#endif + +struct irq_stage inband_stage = { + .name = "Linux", +}; +EXPORT_SYMBOL_GPL(inband_stage); + +struct irq_stage oob_stage; +EXPORT_SYMBOL_GPL(oob_stage); + +struct irq_domain *synthetic_irq_domain; +EXPORT_SYMBOL_GPL(synthetic_irq_domain); + +bool irq_pipeline_oopsing; +EXPORT_SYMBOL_GPL(irq_pipeline_oopsing); + +bool irq_pipeline_active; +EXPORT_SYMBOL_GPL(irq_pipeline_active); + +#define IRQ_L1_MAPSZ BITS_PER_LONG +#define IRQ_L2_MAPSZ (BITS_PER_LONG * BITS_PER_LONG) +#ifdef CONFIG_SPARSE_IRQ +/* + * CAUTION: In sparse mode, we provision for up to 16k distinct + * interrupts in addition to NR_IRQS as we currently need a static + * bitmap to mark pending events. + */ +#define MAX_PIPELINED_IRQS (NR_IRQS + 16384) +#else +#define MAX_PIPELINED_IRQS NR_IRQS +#endif +#define IRQ_FLAT_MAPSZ DIV_ROUND_UP(MAX_PIPELINED_IRQS, BITS_PER_LONG) + +#if IRQ_FLAT_MAPSZ > IRQ_L2_MAPSZ +#define __IRQ_STAGE_MAP_LEVELS 4 /* up to 4/16M vectors on 32/64bit arch */ +#elif IRQ_FLAT_MAPSZ > IRQ_L1_MAPSZ +#define __IRQ_STAGE_MAP_LEVELS 3 /* up to 64/256M vectors */ +#else +#define __IRQ_STAGE_MAP_LEVELS 2 /* up to 1024/4096 vectors */ +#endif + +struct irq_event_map { +#if __IRQ_STAGE_MAP_LEVELS >= 3 + unsigned long index_1[IRQ_L1_MAPSZ]; +#if __IRQ_STAGE_MAP_LEVELS >= 4 + unsigned long index_2[IRQ_L2_MAPSZ]; +#endif +#endif + unsigned long flat[IRQ_FLAT_MAPSZ]; +}; + +#ifdef CONFIG_SMP + +static struct irq_event_map bootup_irq_map __initdata; + +static DEFINE_PER_CPU(struct irq_event_map, irq_map_array[2]); + +DEFINE_PER_CPU(struct irq_pipeline_data, irq_pipeline) = { + .stages = { + [0] = { + .log = { + .map = &bootup_irq_map, + }, + .stage = &inband_stage, + }, + }, +}; + +struct pipeline_percpu_data { }; +static DEFINE_PER_CPU(struct pipeline_percpu_data, pipeline_percpu_data); + +static irqreturn_t smp_call_function_ipi_handler(int irq, void *dev_id) +{ + smp_flush_oob_call_function_queue(); + + return IRQ_HANDLED; +} + +#else /* !CONFIG_SMP */ + +static struct irq_event_map inband_irq_map; + +static struct irq_event_map oob_irq_map; + +DEFINE_PER_CPU(struct irq_pipeline_data, irq_pipeline) = { + .stages = { + [0] = { + .log = { + .map = &inband_irq_map, + }, + .stage = &inband_stage, + }, + [1] = { + .log = { + .map = &oob_irq_map, + }, + }, + }, +}; + +#endif /* !CONFIG_SMP */ + +EXPORT_PER_CPU_SYMBOL(irq_pipeline); + +static void sirq_noop(struct irq_data *data) { } + +/* Virtual interrupt controller for synthetic IRQs. */ +static struct irq_chip sirq_chip = { + .name = "SIRQC", + .irq_enable = sirq_noop, + .irq_disable = sirq_noop, + .flags = IRQCHIP_PIPELINE_SAFE | IRQCHIP_SKIP_SET_WAKE, +}; + +static int sirq_map(struct irq_domain *d, unsigned int irq, + irq_hw_number_t hwirq) +{ + irq_set_percpu_devid(irq); + irq_set_chip_and_handler(irq, &sirq_chip, handle_synthetic_irq); + + return 0; +} + +static struct irq_domain_ops sirq_domain_ops = { + .map = sirq_map, +}; + +/** + * handle_synthetic_irq - synthetic irq handler + * @desc: the interrupt description structure for this irq + * + * Handles synthetic interrupts flowing down the IRQ pipeline + * with per-CPU semantics (accessing desc needs no locking). + * + * Since the SIPIC cannot be stacked on top of a parent irqchip, + * we can bypass most of the IRQS_DEFERRED logic, testing + * on_pipeline_entry() directly - although we should still clear + * IRQS_DEFERRED when in-band since handle_oob_irq() raises it. + * + * CAUTION: synthetic IRQs may be used to map hardware-generated + * events (e.g. IPIs or traps), we must start handling them as + * common interrupts. + */ +void handle_synthetic_irq(struct irq_desc *desc) +{ + unsigned int irq = irq_desc_get_irq(desc); + struct irqaction *action; + irqreturn_t ret; + void *dev_id; + + if (on_pipeline_entry()) { + handle_oob_irq(desc); + return; + } + + if (desc->istate & IRQS_DEFERRED) + irq_clear_deferral(desc); + + if (desc->istate & IRQS_FORWARDED) + irq_clear_forward(desc); + + action = desc->action; + if (action == NULL) { + if (printk_ratelimit()) + printk(KERN_WARNING + "CPU%d: WARNING: synthetic IRQ%d has no action.\n", + smp_processor_id(), irq); + return; + } + + __kstat_incr_irqs_this_cpu(desc); + trace_irq_handler_entry(irq, action); + dev_id = raw_cpu_ptr(action->percpu_dev_id); + ret = action->handler(irq, dev_id); + trace_irq_handler_exit(irq, action, ret); +} + +void sync_irq_stage(struct irq_stage *top) +{ + struct irq_stage_data *p; + struct irq_stage *stage; + + /* We must enter over the inband stage with hardirqs off. */ + if (irq_pipeline_debug()) { + WARN_ON_ONCE(!hard_irqs_disabled()); + WARN_ON_ONCE(current_irq_stage != &inband_stage); + } + + stage = top; + + for (;;) { + if (stage == &inband_stage) { + if (test_inband_stall()) + break; + } else { + if (test_oob_stall()) + break; + } + + p = this_staged(stage); + if (stage_irqs_pending(p)) { + if (stage == &inband_stage) + sync_current_irq_stage(); + else { + /* Switch to oob before synchronizing. */ + switch_oob(p); + sync_current_irq_stage(); + /* Then back to the inband stage. */ + switch_inband(this_inband_staged()); + } + } + + if (stage == &inband_stage) + break; + + stage = &inband_stage; + } +} + +void synchronize_pipeline(void) /* hardirqs off */ +{ + struct irq_stage *top = &oob_stage; + int stalled = test_oob_stall(); + + if (unlikely(!oob_stage_present())) { + top = &inband_stage; + stalled = test_inband_stall(); + } + + if (current_irq_stage != top) + sync_irq_stage(top); + else if (!stalled) + sync_current_irq_stage(); +} + +static void __inband_irq_enable(void) +{ + struct irq_stage_data *p; + unsigned long flags; + + check_inband_stage(); + + flags = hard_local_irq_save(); + + unstall_inband_nocheck(); + + p = this_inband_staged(); + if (unlikely(stage_irqs_pending(p) && !in_pipeline())) { + sync_current_irq_stage(); + hard_local_irq_restore(flags); + preempt_check_resched(); + } else { + hard_local_irq_restore(flags); + } +} + +/** + * inband_irq_enable - enable interrupts for the inband stage + * + * Enable interrupts for the inband stage, allowing interrupts to + * preempt the in-band code. If in-band IRQs are pending for the + * inband stage in the per-CPU log at the time of this call, they + * are played back. + * + * The caller is expected to tell the tracer about the change, by + * calling trace_hardirqs_on(). + */ +notrace void inband_irq_enable(void) +{ + /* + * We are NOT supposed to enter this code with hard IRQs off. + * If we do, then the caller might be wrongly assuming that + * invoking local_irq_enable() implies enabling hard + * interrupts like the legacy I-pipe did, which is not the + * case anymore. Relax this requirement when oopsing, since + * the kernel may be in a weird state. + */ + WARN_ON_ONCE(irq_pipeline_debug() && hard_irqs_disabled()); + __inband_irq_enable(); +} +EXPORT_SYMBOL(inband_irq_enable); + +/** + * inband_irq_disable - disable interrupts for the inband stage + * + * Disable interrupts for the inband stage, disabling in-band + * interrupts. Out-of-band interrupts can still be taken and + * delivered to their respective handlers though. + */ +notrace void inband_irq_disable(void) +{ + check_inband_stage(); + stall_inband_nocheck(); +} +EXPORT_SYMBOL(inband_irq_disable); + +/** + * inband_irqs_disabled - test the virtual interrupt state + * + * Returns non-zero if interrupts are currently disabled for the + * inband stage, zero otherwise. + * + * May be used from the oob stage too (e.g. for tracing + * purpose). + */ +noinstr int inband_irqs_disabled(void) +{ + return test_inband_stall(); +} +EXPORT_SYMBOL(inband_irqs_disabled); + +/** + * inband_irq_save - test and disable (virtual) interrupts + * + * Save the virtual interrupt state then disables interrupts for + * the inband stage. + * + * Returns the original interrupt state. + */ +trace_on_debug unsigned long inband_irq_save(void) +{ + check_inband_stage(); + return test_and_stall_inband_nocheck(); +} +EXPORT_SYMBOL(inband_irq_save); + +/** + * inband_irq_restore - restore the (virtual) interrupt state + * @x: Interrupt state to restore + * + * Restore the virtual interrupt state from x. If the inband + * stage is unstalled as a consequence of this operation, any + * interrupt pending for the inband stage in the per-CPU log is + * played back. + */ +trace_on_debug void inband_irq_restore(unsigned long flags) +{ + if (flags) + inband_irq_disable(); + else + __inband_irq_enable(); +} +EXPORT_SYMBOL(inband_irq_restore); + +/** + * oob_irq_enable - enable interrupts in the CPU + * + * Enable interrupts in the CPU, allowing out-of-band interrupts + * to preempt any code. If out-of-band IRQs are pending in the + * per-CPU log for the oob stage at the time of this call, they + * are played back. + */ +trace_on_debug void oob_irq_enable(void) +{ + struct irq_stage_data *p; + + hard_local_irq_disable(); + + unstall_oob(); + + p = this_oob_staged(); + if (unlikely(stage_irqs_pending(p))) + synchronize_pipeline(); + + hard_local_irq_enable(); +} +EXPORT_SYMBOL(oob_irq_enable); + +/** + * oob_irq_restore - restore the hardware interrupt state + * @x: Interrupt state to restore + * + * Restore the harware interrupt state from x. If the oob stage + * is unstalled as a consequence of this operation, any interrupt + * pending for the oob stage in the per-CPU log is played back + * prior to turning IRQs on. + * + * NOTE: Stalling the oob stage must always be paired with + * disabling hard irqs and conversely when calling + * oob_irq_restore(), otherwise the latter would badly misbehave + * in unbalanced conditions. + */ +trace_on_debug void __oob_irq_restore(unsigned long flags) /* hw interrupt off */ +{ + struct irq_stage_data *p = this_oob_staged(); + + check_hard_irqs_disabled(); + + if (!flags) { + unstall_oob(); + if (unlikely(stage_irqs_pending(p))) + synchronize_pipeline(); + hard_local_irq_enable(); + } +} +EXPORT_SYMBOL(__oob_irq_restore); + +/** + * stage_disabled - test the interrupt state of the current stage + * + * Returns non-zero if interrupts are currently disabled for the + * current interrupt stage, zero otherwise. + * In other words, returns non-zero either if: + * - interrupts are disabled for the OOB context (i.e. hard disabled), + * - the inband stage is current and inband interrupts are disabled. + */ +noinstr bool stage_disabled(void) +{ + bool ret = true; + + if (!hard_irqs_disabled()) { + ret = false; + if (running_inband()) + ret = test_inband_stall(); + } + + return ret; +} +EXPORT_SYMBOL_GPL(stage_disabled); + +/** + * stage_disabled_flags - test a particular interrupt state + * + * Returns non-zero if interrupts are marked as disabled in the + * interrupt state, zero otherwise. + * In other words, returns non-zero either if: + * - interrupts are disabled for the OOB context (i.e. hard disabled), + * - inband interrupts are stalled (meaning that we were running in-band + * when building that interrupt state). + * + * CAUTION: in general, you cannot infer from an interrupt state + * value which stage was active at the time such state was + * snapshot. However, as mentioned earlier, you may assume that + * the in-band stage can be reported as stalled only when current + * though, since this is guaranteed by the implementation of + * test_and_lock_stage(). + */ +noinstr bool stage_disabled_flags(unsigned long irqstate, bool *stalled) +{ + unsigned long flags; + int _stalled; + + flags = irqs_split_flags(irqstate, &_stalled); + *stalled = _stalled; + return hard_irqs_disabled_flags(flags) || stalled; +} +EXPORT_SYMBOL_GPL(stage_disabled_flags); + +/** + * test_and_lock_stage - test and disable interrupts for the current stage + * @irqsoff: Pointer to boolean denoting stage_disabled() + * on entry + * + * Fully disables interrupts for the current stage. When the + * inband stage is current, the stall bit is raised and hardware + * IRQs are masked as well. Only the latter operation is + * performed when the oob stage is current. + * + * Returns the combined interrupt state on entry including the + * real/hardware (in CPU) and virtual (inband stage) states. For + * this reason, [test_and_]lock_stage() must be paired with + * unlock_stage() exclusively. The combined irq state returned by + * the former may NOT be passed to hard_local_irq_restore(). + * + * The interrupt state of the current stage in the return value + * (i.e. stall bit for the inband stage, hardware interrupt bit + * for the oob stage) must be testable using + * arch_irqs_disabled_flags(). + * + * Notice that test_and_lock_stage(), unlock_stage() are raw + * level ops, which substitute to raw_local_irq_save(), + * raw_local_irq_restore() in lockdep code. Therefore, changes to + * the in-band stall bit must not be propagated to the tracing + * core (i.e. no trace_hardirqs_*() annotations). + */ +noinstr unsigned long test_and_lock_stage(int *irqsoff) +{ + unsigned long flags; + int stalled, dummy; + + if (irqsoff == NULL) + irqsoff = &dummy; + + /* + * Combine the hard irq flag and the stall bit into a single + * state word. We need to fill in the stall bit only if the + * inband stage is current, otherwise it is not relevant. + */ + flags = hard_local_irq_save(); + *irqsoff = hard_irqs_disabled_flags(flags); + if (running_inband()) { + stalled = test_and_stall_inband_nocheck(); + flags = irqs_merge_flags(flags, stalled); + if (stalled) + *irqsoff = 1; + } + + /* + * CAUTION: don't ever pass this verbatim to + * hard_local_irq_restore(). Only unlock_stage() knows how to + * decode and use a combined state word. + */ + return flags; +} +EXPORT_SYMBOL_GPL(test_and_lock_stage); + +/** + * unlock_stage - restore interrupts for the current stage + * @flags: Combined interrupt state to restore as received from + * test_and_lock_stage() + * + * Restore the virtual interrupt state if the inband stage is + * current, and the hardware interrupt state unconditionally. + * The per-CPU log is not played for any stage. + */ +noinstr void unlock_stage(unsigned long irqstate) +{ + unsigned long flags = irqstate; + int stalled; + + WARN_ON_ONCE(irq_pipeline_debug_locking() && !hard_irqs_disabled()); + + if (running_inband()) { + flags = irqs_split_flags(irqstate, &stalled); + if (!stalled) + unstall_inband_nocheck(); + } + + /* + * The hardware interrupt bit is the only flag which may be + * present in the combined state at this point, all other + * status bits have been cleared by irqs_merge_flags(), so + * don't ever try to reload the hardware status register with + * such value directly! + */ + if (!hard_irqs_disabled_flags(flags)) + hard_local_irq_enable(); +} +EXPORT_SYMBOL_GPL(unlock_stage); + +/** + * sync_inband_irqs - Synchronize the inband log + * + * Play any deferred interrupt which might have been logged for the + * in-band stage while running with hard irqs on but stalled. + * + * Called from the unstalled in-band stage. Returns with hard irqs off. + */ +void sync_inband_irqs(void) +{ + struct irq_stage_data *p; + + check_inband_stage(); + WARN_ON_ONCE(irq_pipeline_debug() && irqs_disabled()); + + if (!hard_irqs_disabled()) + hard_local_irq_disable(); + + p = this_inband_staged(); + if (unlikely(stage_irqs_pending(p))) { + /* Do not pile up preemption frames. */ + preempt_disable_notrace(); + sync_current_irq_stage(); + preempt_enable_no_resched_notrace(); + } +} + +static inline bool irq_post_check(struct irq_stage *stage, unsigned int irq) +{ + if (irq_pipeline_debug()) { + if (WARN_ONCE(!hard_irqs_disabled(), + "hard irqs on posting IRQ%u to %s\n", + irq, stage->name)) + return true; + if (WARN_ONCE(irq >= MAX_PIPELINED_IRQS, + "cannot post invalid IRQ%u to %s\n", + irq, stage->name)) + return true; + } + + return false; +} + +#if __IRQ_STAGE_MAP_LEVELS == 4 + +/* Must be called hard irqs off. */ +void irq_post_stage(struct irq_stage *stage, unsigned int irq) +{ + struct irq_stage_data *p = this_staged(stage); + int l0b, l1b, l2b; + + if (irq_post_check(stage, irq)) + return; + + l0b = irq / (BITS_PER_LONG * BITS_PER_LONG * BITS_PER_LONG); + l1b = irq / (BITS_PER_LONG * BITS_PER_LONG); + l2b = irq / BITS_PER_LONG; + + __set_bit(irq, p->log.map->flat); + __set_bit(l2b, p->log.map->index_2); + __set_bit(l1b, p->log.map->index_1); + __set_bit(l0b, &p->log.index_0); +} +EXPORT_SYMBOL_GPL(irq_post_stage); + +#define ltob_1(__n) ((__n) * BITS_PER_LONG) +#define ltob_2(__n) (ltob_1(__n) * BITS_PER_LONG) +#define ltob_3(__n) (ltob_2(__n) * BITS_PER_LONG) + +static inline int pull_next_irq(struct irq_stage_data *p) +{ + unsigned long l0m, l1m, l2m, l3m; + int l0b, l1b, l2b, l3b; + unsigned int irq; + + l0m = p->log.index_0; + if (l0m == 0) + return -1; + l0b = __ffs(l0m); + irq = ltob_3(l0b); + + l1m = p->log.map->index_1[l0b]; + if (unlikely(l1m == 0)) { + WARN_ON_ONCE(1); + return -1; + } + l1b = __ffs(l1m); + irq += ltob_2(l1b); + + l2m = p->log.map->index_2[ltob_1(l0b) + l1b]; + if (unlikely(l2m == 0)) { + WARN_ON_ONCE(1); + return -1; + } + l2b = __ffs(l2m); + irq += ltob_1(l2b); + + l3m = p->log.map->flat[ltob_2(l0b) + ltob_1(l1b) + l2b]; + if (unlikely(l3m == 0)) + return -1; + l3b = __ffs(l3m); + irq += l3b; + + __clear_bit(irq, p->log.map->flat); + if (p->log.map->flat[irq / BITS_PER_LONG] == 0) { + __clear_bit(l2b, &p->log.map->index_2[ltob_1(l0b) + l1b]); + if (p->log.map->index_2[ltob_1(l0b) + l1b] == 0) { + __clear_bit(l1b, &p->log.map->index_1[l0b]); + if (p->log.map->index_1[l0b] == 0) + __clear_bit(l0b, &p->log.index_0); + } + } + + return irq; +} + +#elif __IRQ_STAGE_MAP_LEVELS == 3 + +/* Must be called hard irqs off. */ +void irq_post_stage(struct irq_stage *stage, unsigned int irq) +{ + struct irq_stage_data *p = this_staged(stage); + int l0b, l1b; + + if (irq_post_check(stage, irq)) + return; + + l0b = irq / (BITS_PER_LONG * BITS_PER_LONG); + l1b = irq / BITS_PER_LONG; + + __set_bit(irq, p->log.map->flat); + __set_bit(l1b, p->log.map->index_1); + __set_bit(l0b, &p->log.index_0); +} +EXPORT_SYMBOL_GPL(irq_post_stage); + +static inline int pull_next_irq(struct irq_stage_data *p) +{ + unsigned long l0m, l1m, l2m; + int l0b, l1b, l2b, irq; + + l0m = p->log.index_0; + if (unlikely(l0m == 0)) + return -1; + + l0b = __ffs(l0m); + l1m = p->log.map->index_1[l0b]; + if (l1m == 0) + return -1; + + l1b = __ffs(l1m) + l0b * BITS_PER_LONG; + l2m = p->log.map->flat[l1b]; + if (unlikely(l2m == 0)) { + WARN_ON_ONCE(1); + return -1; + } + + l2b = __ffs(l2m); + irq = l1b * BITS_PER_LONG + l2b; + + __clear_bit(irq, p->log.map->flat); + if (p->log.map->flat[l1b] == 0) { + __clear_bit(l1b, p->log.map->index_1); + if (p->log.map->index_1[l0b] == 0) + __clear_bit(l0b, &p->log.index_0); + } + + return irq; +} + +#else /* __IRQ_STAGE_MAP_LEVELS == 2 */ + +/* Must be called hard irqs off. */ +void irq_post_stage(struct irq_stage *stage, unsigned int irq) +{ + struct irq_stage_data *p = this_staged(stage); + int l0b = irq / BITS_PER_LONG; + + if (irq_post_check(stage, irq)) + return; + + __set_bit(irq, p->log.map->flat); + __set_bit(l0b, &p->log.index_0); +} +EXPORT_SYMBOL_GPL(irq_post_stage); + +static inline int pull_next_irq(struct irq_stage_data *p) +{ + unsigned long l0m, l1m; + int l0b, l1b; + + l0m = p->log.index_0; + if (l0m == 0) + return -1; + + l0b = __ffs(l0m); + l1m = p->log.map->flat[l0b]; + if (unlikely(l1m == 0)) { + WARN_ON_ONCE(1); + return -1; + } + + l1b = __ffs(l1m); + __clear_bit(l1b, &p->log.map->flat[l0b]); + if (p->log.map->flat[l0b] == 0) + __clear_bit(l0b, &p->log.index_0); + + return l0b * BITS_PER_LONG + l1b; +} + +#endif /* __IRQ_STAGE_MAP_LEVELS == 2 */ + +/** + * hard_preempt_disable - Disable preemption the hard way + * + * Disable hardware interrupts in the CPU, and disable preemption + * as well if currently running on the inband stage. + * + * Return the hardware interrupt state on entry. + */ +unsigned long hard_preempt_disable(void) +{ + unsigned long flags = hard_local_irq_save(); + + if (running_inband()) + preempt_disable(); + + return flags; +} +EXPORT_SYMBOL_GPL(hard_preempt_disable); + +/** + * hard_preempt_enable - Enable preemption the hard way + * + * Enable preemption if currently running on the inband stage, + * restoring the hardware interrupt state in the CPU as well. + * The per-CPU log is not played for the oob stage. + */ +void hard_preempt_enable(unsigned long flags) +{ + if (running_inband()) { + preempt_enable_no_resched(); + hard_local_irq_restore(flags); + if (!hard_irqs_disabled_flags(flags)) + preempt_check_resched(); + } else { + hard_local_irq_restore(flags); + } +} +EXPORT_SYMBOL_GPL(hard_preempt_enable); + +/** + * hard_bh_disable - Disable bottom-halves and hard irqs + * + * Disable BH if currently running on the inband stage, then hard + * irqs. + * + * Return the hardware interrupt state on entry. + */ +unsigned long hard_bh_disable(void) +{ + if (running_inband()) + local_bh_disable(); + + return hard_local_irq_save(); +} +EXPORT_SYMBOL_GPL(hard_bh_disable); + +/** + * hard_bh_enable - Restore hard irqs then enable bottom-halves + * + * Restore the hardware interrupt state in the CPU, then enable + * BH if currently running on the inband stage. The per-CPU log + * is not played for the oob stage. + */ +void hard_bh_enable(unsigned long flags) +{ + hard_local_irq_restore(flags); + + if (running_inband()) + local_bh_enable(); +} +EXPORT_SYMBOL_GPL(hard_bh_enable); + +static void handle_unexpected_irq(struct irq_desc *desc, irqreturn_t ret) +{ + unsigned int irq = irq_desc_get_irq(desc); + struct irqaction *action; + + /* + * Since IRQ_HANDLED was not received from any handler, we may + * have a problem dealing with an OOB interrupt. The error + * detection logic is as follows: + * + * - check and complain about any bogus return value from a + * out-of-band IRQ handler: we only allow IRQ_HANDLED, + * IRQ_FORWARD or IRQ_NONE from those routines. + * + * - filter out spurious IRQs which may have been due to bus + * asynchronicity, those tend to happen infrequently and + * should not cause us to pull the break (see + * note_interrupt()). + * + * - otherwise, stop pipelining the IRQ line after a thousand + * consecutive unhandled events. + * + * NOTE: we should already be holding desc->lock for non + * per-cpu IRQs, since we should only get there from the + * pipeline entry context. + */ + + WARN_ON_ONCE(irq_pipeline_debug() && + !irq_settings_is_per_cpu(desc) && + !raw_spin_is_locked(&desc->lock)); + + if (ret != IRQ_NONE) { + printk(KERN_ERR "out-of-band irq event %d: bogus return value %x\n", + irq, ret); + for_each_action_of_desc(desc, action) + printk(KERN_ERR "[<%p>] %pf", + action->handler, action->handler); + printk(KERN_CONT "\n"); + return; + } + + if (time_after(jiffies, desc->last_unhandled + HZ/10)) + desc->irqs_unhandled = 0; + else + desc->irqs_unhandled++; + + desc->last_unhandled = jiffies; + + if (unlikely(desc->irqs_unhandled > 1000)) { + printk(KERN_ERR "out-of-band irq %d: stuck or unexpected\n", irq); + irq_settings_clr_oob(desc); + desc->istate |= IRQS_SPURIOUS_DISABLED; + irq_disable(desc); + } +} + +static inline void incr_irq_kstat(struct irq_desc *desc) +{ + if (irq_settings_is_per_cpu_devid(desc)) + __kstat_incr_irqs_this_cpu(desc); + else + kstat_incr_irqs_this_cpu(desc); +} + +/* + * do_oob_irq() - Handles interrupts over the oob stage. Hard irqs + * off. + */ +static void do_oob_irq(struct irq_desc *desc) +{ + bool percpu_devid = irq_settings_is_per_cpu_devid(desc); + unsigned int irq = irq_desc_get_irq(desc); + irqreturn_t ret = IRQ_NONE, res; + struct irqaction *action; + void *dev_id; + + action = desc->action; + if (unlikely(action == NULL)) + goto done; + + if (percpu_devid) { + trace_irq_handler_entry(irq, action); + dev_id = raw_cpu_ptr(action->percpu_dev_id); + ret = action->handler(irq, dev_id); + trace_irq_handler_exit(irq, action, ret); + } else { + desc->istate &= ~IRQS_PENDING; + if (unlikely(irqd_irq_disabled(&desc->irq_data))) + return; + irqd_set(&desc->irq_data, IRQD_IRQ_INPROGRESS); + raw_spin_unlock(&desc->lock); + for_each_action_of_desc(desc, action) { + trace_irq_handler_entry(irq, action); + dev_id = action->dev_id; + res = action->handler(irq, dev_id); + trace_irq_handler_exit(irq, action, res); + ret |= res; + } + raw_spin_lock(&desc->lock); + irqd_clear(&desc->irq_data, IRQD_IRQ_INPROGRESS); + } + /* + * The oob handler might request to forward the event + * downstream to the in-band stage. Post the event to the + * in-band log, marking the descriptor accordingly if so. + */ + if (ret & IRQ_FORWARD) { + irq_post_stage(&inband_stage, irq); + desc->istate |= IRQS_FORWARDED; + } +done: + incr_irq_kstat(desc); + + if (likely(ret & (IRQ_HANDLED|IRQ_FORWARD))) { + desc->irqs_unhandled = 0; + return; + } + + handle_unexpected_irq(desc, ret); +} + +/* + * Over the inband stage, IRQs must be dispatched by the arch-specific + * arch_do_IRQ_pipelined() routine. + * + * Entered with hardirqs on, inband stalled. + */ +static inline +void do_inband_irq(struct irq_desc *desc) +{ + arch_do_IRQ_pipelined(desc); + WARN_ON_ONCE(irq_pipeline_debug() && !irqs_disabled()); +} + +static inline bool is_active_edge_event(struct irq_desc *desc) +{ + return (desc->istate & IRQS_PENDING) && + !irqd_irq_disabled(&desc->irq_data); +} + +/* desc->lock held unless per-CPU, hardirqs off. */ +bool handle_oob_irq(struct irq_desc *desc) +{ + struct irq_stage_data *oobd = this_oob_staged(); + unsigned int irq = irq_desc_get_irq(desc); + int stalled; + + /* + * Flow handlers of chained interrupts have no business + * running here: they should decode the event, invoking + * generic_handle_irq() for each cascaded IRQ. + */ + if (WARN_ON_ONCE(irq_pipeline_debug() && + irq_settings_is_chained(desc))) + return false; + + /* + * If no oob stage is present, all interrupts must go to the + * inband stage through the interrupt log. Otherwise, + * out-of-band IRQs are immediately delivered to the oob + * stage, while in-band IRQs still go through the inband stage + * log. + * + * This routine returns a boolean status telling the caller + * whether an out-of-band interrupt was delivered. + */ + if (!oob_stage_present() || !irq_settings_is_oob(desc)) { + desc->istate |= IRQS_DEFERRED; + irq_post_stage(&inband_stage, irq); + return false; + } + + if (WARN_ON_ONCE(irq_pipeline_debug() && running_inband())) + return false; + + stalled = test_and_stall_oob(); + + if (unlikely(desc->istate & IRQS_EDGE)) { + do { + if (is_active_edge_event(desc)) { + if (irqd_irq_masked(&desc->irq_data)) + unmask_irq(desc); + } + do_oob_irq(desc); + } while (is_active_edge_event(desc)); + } else { + do_oob_irq(desc); + } + + /* + * Cascaded interrupts enter handle_oob_irq() on the stalled + * out-of-band stage during the parent invocation. Make sure + * to restore the stall bit accordingly. + */ + if (likely(!stalled)) + unstall_oob(); + + /* + * CPU migration and/or stage switching over the handler are + * NOT allowed. These should take place over + * irq_exit_pipeline(). + */ + if (irq_pipeline_debug()) { + /* No CPU migration allowed. */ + WARN_ON_ONCE(this_oob_staged() != oobd); + /* No stage migration allowed. */ + WARN_ON_ONCE(current_irq_staged != oobd); + } + + return true; +} + +static inline +void copy_timer_regs(struct irq_desc *desc, struct pt_regs *regs) +{ + struct irq_pipeline_data *p; + + if (desc->action == NULL || !(desc->action->flags & __IRQF_TIMER)) + return; + /* + * Given our deferred dispatching model for regular IRQs, we + * record the preempted context registers only for the latest + * timer interrupt, so that the regular tick handler charges + * CPU times properly. It is assumed that no other interrupt + * handler cares for such information. + */ + p = raw_cpu_ptr(&irq_pipeline); + arch_save_timer_regs(&p->tick_regs, regs); +} + +static __always_inline +struct irq_stage_data *switch_stage_on_irq(void) +{ + struct irq_stage_data *prevd = current_irq_staged, *nextd; + + if (oob_stage_present()) { + nextd = this_oob_staged(); + if (prevd != nextd) + switch_oob(nextd); + } + + return prevd; +} + +static __always_inline +void restore_stage_on_irq(struct irq_stage_data *prevd) +{ + /* + * CPU migration and/or stage switching over + * irq_exit_pipeline() are allowed. Our exit logic is as + * follows: + * + * ENTRY EXIT EPILOGUE + * + * oob oob nop + * inband oob switch inband + * oob inband nop + * inband inband nop + */ + if (prevd->stage == &inband_stage && + current_irq_staged == this_oob_staged()) + switch_inband(this_inband_staged()); +} + +/** + * generic_pipeline_irq_desc - Pass an IRQ to the pipeline + * @desc: Descriptor of the IRQ to pass + * + * Inject an IRQ into the pipeline from a CPU interrupt or trap + * context. A flow handler runs next for this IRQ. + * + * Hard irqs must be off on entry. Caller should have pushed the + * IRQ regs using set_irq_regs(). + */ +int generic_pipeline_irq_desc(struct irq_desc *desc) +{ + struct pt_regs *regs = get_irq_regs(); + int irq; + + if (!desc) + return -EINVAL; + + irq = irq_desc_get_irq(desc); + + if (irq_pipeline_debug() && !hard_irqs_disabled()) { + hard_local_irq_disable(); + pr_err("IRQ pipeline: interrupts enabled on entry (IRQ%u)\n", irq); + } + + trace_irq_pipeline_entry(irq); + copy_timer_regs(desc, regs); + generic_handle_irq_desc(desc); + trace_irq_pipeline_exit(irq); + + return 0; +} + +struct irq_stage_data *handle_irq_pipelined_prepare(struct pt_regs *regs) +{ + struct irq_stage_data *prevd; + + /* + * Running with the oob stage stalled implies hardirqs off. + * For this reason, if the oob stage is stalled when we + * receive an interrupt from the hardware, something is badly + * broken in our interrupt state. Try fixing up, but without + * great hopes. + */ + if (irq_pipeline_debug()) { + if (test_oob_stall()) { + pr_err("IRQ pipeline: out-of-band stage stalled on IRQ entry\n"); + unstall_oob(); + } + WARN_ON(on_pipeline_entry()); + } + + /* + * Switch early on to the out-of-band stage if present, + * anticipating a companion kernel is going to handle the + * incoming event. If not, never mind, we will switch back + * in-band before synchronizing interrupts. + */ + prevd = switch_stage_on_irq(); + + /* Tell the companion core about the entry. */ + irq_enter_pipeline(); + + /* + * Invariant: IRQs may not pile up in the section covered by + * the PIPELINE_OFFSET marker, because: + * + * - out-of-band handlers called from handle_oob_irq() may NOT + * re-enable hard interrupts. Ever. + * + * - synchronizing the in-band log with hard interrupts + * enabled is done outside of this section. + */ + preempt_count_add(PIPELINE_OFFSET); + + /* + * From the standpoint of the in-band context when pipelining + * is in effect, an interrupt entry is unsafe in a similar way + * a NMI is, since it may preempt almost anywhere as IRQs are + * only virtually masked most of the time, including inside + * (virtually) interrupt-free sections. Declare a NMI entry so + * that the low handling code is allowed to enter RCU read + * sides (e.g. generic_handle_domain_irq() needs this to + * resolve IRQ mappings). + */ + ct_nmi_enter(); + + return prevd; +} + +int handle_irq_pipelined_finish(struct irq_stage_data *prevd, + struct pt_regs *regs) +{ + /* + * Leave the (pseudo-)NMI entry for RCU before the out-of-band + * core might reschedule in irq_exit_pipeline(), and + * interrupts are hard enabled again on this CPU as a result + * of switching context. + */ + ct_nmi_exit(); + + /* + * Make sure to leave the pipeline entry context before + * allowing the companion core to reschedule, and eventually + * synchronizing interrupts. + */ + preempt_count_sub(PIPELINE_OFFSET); + + /* Allow the companion core to reschedule. */ + irq_exit_pipeline(); + + /* Back to the preempted stage. */ + restore_stage_on_irq(prevd); + + /* + * We have to synchronize interrupts because some might have + * been logged while we were busy handling an out-of-band + * event coming from the hardware: + * + * - as a result of calling an out-of-band handler which in + * turn posted them. + * + * - because we posted them directly for scheduling the + * interrupt to happen from the in-band stage. + */ + synchronize_pipeline_on_irq(); + +#ifdef CONFIG_DOVETAIL + /* + * Sending MAYDAY is in essence a rare case, so prefer test + * then maybe clear over test_and_clear. + */ + if (user_mode(regs) && test_thread_flag(TIF_MAYDAY)) + dovetail_call_mayday(regs); +#endif + + return running_inband() && !irqs_disabled(); +} + +int handle_irq_pipelined(struct pt_regs *regs) +{ + struct irq_stage_data *prevd; + struct pt_regs *old_regs; + + prevd = handle_irq_pipelined_prepare(regs); + old_regs = set_irq_regs(regs); + arch_handle_irq_pipelined(regs); + set_irq_regs(old_regs); + return handle_irq_pipelined_finish(prevd, regs); +} + +/** + * irq_inject_pipeline - Inject a software-generated IRQ into the + * pipeline @irq: IRQ to inject + * + * Inject an IRQ into the pipeline by software as if such + * hardware event had happened on the current CPU. + */ +int irq_inject_pipeline(unsigned int irq) +{ + struct irq_stage_data *oobd, *prevd; + struct irq_desc *desc; + unsigned long flags; + + desc = irq_to_desc(irq); + if (desc == NULL) + return -EINVAL; + + flags = hard_local_irq_save(); + + /* + * Handle the case of an IRQ sent to a stalled oob stage here, + * which allows to trap the same condition in handle_oob_irq() + * in a debug check (see comment there). + */ + oobd = this_oob_staged(); + if (oob_stage_present() && + irq_settings_is_oob(desc) && + test_oob_stall()) { + irq_post_stage(&oob_stage, irq); + } else { + prevd = switch_stage_on_irq(); + irq_enter_pipeline(); + handle_oob_irq(desc); + irq_exit_pipeline(); + restore_stage_on_irq(prevd); + synchronize_pipeline_on_irq(); + } + + hard_local_irq_restore(flags); + + return 0; + +} +EXPORT_SYMBOL_GPL(irq_inject_pipeline); + +/* + * sync_current_irq_stage() -- Flush the pending IRQs for the current + * stage (and processor). This routine flushes the interrupt log (see + * "Optimistic interrupt protection" from D. Stodolsky et al. for more + * on the deferred interrupt scheme). Every interrupt which has + * occurred while the pipeline was stalled gets played. + * + * CAUTION: CPU migration may occur over this routine if running over + * the inband stage. + */ +void sync_current_irq_stage(void) /* hard irqs off */ +{ + struct irq_stage_data *p; + struct irq_stage *stage; + struct irq_desc *desc; + int irq; + + WARN_ON_ONCE(irq_pipeline_debug() && on_pipeline_entry()); + check_hard_irqs_disabled(); + + p = current_irq_staged; +respin: + stage = p->stage; + if (stage == &inband_stage) { + /* + * Since we manipulate the stall bit directly, we have + * to open code the IRQ state tracing. + */ + stall_inband_nocheck(); + trace_hardirqs_off(); + } else { + stall_oob(); + } + + for (;;) { + irq = pull_next_irq(p); + if (irq < 0) + break; + /* + * Make sure the compiler does not reorder wrongly, so + * that all updates to maps are done before the + * handler gets called. + */ + barrier(); + + desc = irq_to_desc(irq); + + if (stage == &inband_stage) { + hard_local_irq_enable(); + do_inband_irq(desc); + hard_local_irq_disable(); + } else { + do_oob_irq(desc); + } + + /* + * We might have switched from the oob stage to the + * in-band one on return from the handler, in which + * case we might also have migrated to a different CPU + * (the converse in-band -> oob switch is NOT allowed + * though). Reload the current per-cpu context + * pointer, so that we further pull pending interrupts + * from the proper in-band log. + */ + p = current_irq_staged; + if (p->stage != stage) { + if (WARN_ON_ONCE(irq_pipeline_debug() && + stage == &inband_stage)) + break; + goto respin; + } + } + + if (stage == &inband_stage) { + trace_hardirqs_on(); + unstall_inband_nocheck(); + } else { + unstall_oob(); + } +} + +#ifndef CONFIG_GENERIC_ENTRY + +/* + * These helpers are normally called from the kernel entry/exit code + * in the asm section by architectures which do not use the generic + * kernel entry code, in order to save the interrupt and lockdep + * states for the in-band stage on entry, restoring them when leaving + * the kernel. The per-architecture arch_kentry_set/get_irqstate() + * calls determine where this information should be kept while running + * in kernel context, indexed on the current register frame. + */ + +#define KENTRY_STALL_BIT BIT(0) /* Tracks INBAND_STALL_BIT */ +#define KENTRY_LOCKDEP_BIT BIT(1) /* Tracks hardirqs_enabled */ + +asmlinkage __visible noinstr void kentry_enter_pipelined(struct pt_regs *regs) +{ + long irqstate = 0; + + WARN_ON(irq_pipeline_debug() && !hard_irqs_disabled()); + + if (!running_inband()) + return; + + if (lockdep_read_irqs_state()) + irqstate |= KENTRY_LOCKDEP_BIT; + + if (irqs_disabled()) + irqstate |= KENTRY_STALL_BIT; + else + trace_hardirqs_off(); + + arch_kentry_set_irqstate(regs, irqstate); +} + +asmlinkage void __visible noinstr kentry_exit_pipelined(struct pt_regs *regs) +{ + long irqstate; + + WARN_ON(irq_pipeline_debug() && !hard_irqs_disabled()); + + if (!running_inband()) + return; + + /* + * If the in-band stage of the kernel is current but the IRQ + * is not going to be delivered because the latter is stalled, + * keep the tracing logic unaware of the receipt, so that no + * false positive is triggered in lockdep (e.g. IN-HARDIRQ-W + * -> HARDIRQ-ON-W). In this case, we still have to restore + * the lockdep irq state independently, since it might not be + * in sync with the stall bit (e.g. raw_local_irq_disable/save + * do flip the stall bit, but are not tracked by lockdep). + */ + + irqstate = arch_kentry_get_irqstate(regs); + if (!(irqstate & KENTRY_STALL_BIT)) { + stall_inband_nocheck(); + trace_hardirqs_on(); + unstall_inband_nocheck(); + } else { + lockdep_write_irqs_state(!!(irqstate & KENTRY_LOCKDEP_BIT)); + } +} + +#endif /* !CONFIG_GENERIC_ENTRY */ + +/** + * run_oob_call - escalate function call to the oob stage + * @fn: address of routine + * @arg: routine argument + * + * Make the specified function run on the oob stage, switching + * the current stage accordingly if needed. The escalated call is + * allowed to perform a stage migration in the process. + */ +int notrace run_oob_call(int (*fn)(void *arg), void *arg) +{ + struct irq_stage_data *p, *old; + struct irq_stage *oob; + unsigned long flags; + int ret, s; + + flags = hard_local_irq_save(); + + /* Switch to the oob stage if not current. */ + p = this_oob_staged(); + oob = p->stage; + old = current_irq_staged; + if (old != p) + switch_oob(p); + + s = test_and_stall_oob(); + barrier(); + ret = fn(arg); + hard_local_irq_disable(); + if (!s) + unstall_oob(); + + /* + * The exit logic is as follows: + * + * ON-ENTRY AFTER-CALL EPILOGUE + * + * oob oob sync current stage if !stalled + * inband oob switch to inband + sync all stages + * oob inband sync all stages + * inband inband sync all stages + * + * Each path which has stalled the oob stage while running on + * the inband stage at some point during the escalation + * process must synchronize all stages of the pipeline on + * exit. Otherwise, we may restrict the synchronization scope + * to the current stage when the whole sequence ran on the oob + * stage. + */ + p = this_oob_staged(); + if (likely(current_irq_staged == p)) { + if (old->stage == oob) { + if (!s && stage_irqs_pending(p)) + sync_current_irq_stage(); + goto out; + } + switch_inband(this_inband_staged()); + } + + sync_irq_stage(oob); +out: + hard_local_irq_restore(flags); + + return ret; +} +EXPORT_SYMBOL_GPL(run_oob_call); + +struct up_oob_call_tramp { + smp_call_func_t func; + void *info; +}; + +static int __up_oob_call(void *arg) +{ + struct up_oob_call_tramp *tramp = arg; + + tramp->func(tramp->info); + + return 0; +} + +/* + * up_oob_call_tramp - run_oob_call() trampoline to smp function calls + * for uniprocessor configuration. + */ +int up_oob_call(smp_call_func_t func, void *info) +{ + struct up_oob_call_tramp tramp = { .func = func, .info = info }; + return run_oob_call(__up_oob_call, &tramp); +} + +int enable_oob_stage(const char *name) +{ + struct irq_event_map *map; + struct irq_stage_data *p; + int cpu, ret; + + if (oob_stage_present()) + return -EBUSY; + + /* Set up the out-of-band interrupt stage on all CPUs. */ + + for_each_possible_cpu(cpu) { + p = &per_cpu(irq_pipeline.stages, cpu)[1]; + map = p->log.map; /* save/restore after memset(). */ + memset(p, 0, sizeof(*p)); + p->stage = &oob_stage; + memset(map, 0, sizeof(struct irq_event_map)); + p->log.map = map; +#ifdef CONFIG_DEBUG_IRQ_PIPELINE + p->cpu = cpu; +#endif + } + + ret = arch_enable_oob_stage(); + if (ret) + return ret; + + oob_stage.name = name; + smp_wmb(); + oob_stage.index = 1; + + pr_info("IRQ pipeline: high-priority %s stage added.\n", name); + + return 0; +} +EXPORT_SYMBOL_GPL(enable_oob_stage); + +void disable_oob_stage(void) +{ + const char *name = oob_stage.name; + + WARN_ON(!running_inband() || !oob_stage_present()); + + oob_stage.index = 0; + smp_wmb(); + + pr_info("IRQ pipeline: %s stage removed.\n", name); +} +EXPORT_SYMBOL_GPL(disable_oob_stage); + +void irq_pipeline_oops(void) +{ + irq_pipeline_oopsing = true; + local_irq_disable_full(); +} + +/* + * Used to save/restore the status bits of the inband stage across runs + * of NMI-triggered code, so that we can restore the original pipeline + * state before leaving NMI context. + */ +static DEFINE_PER_CPU(unsigned long, nmi_saved_stall_bits); + +noinstr void irq_pipeline_nmi_enter(void) +{ + raw_cpu_write(nmi_saved_stall_bits, current->stall_bits); + +} +EXPORT_SYMBOL(irq_pipeline_nmi_enter); + +noinstr void irq_pipeline_nmi_exit(void) +{ + current->stall_bits = raw_cpu_read(nmi_saved_stall_bits); +} +EXPORT_SYMBOL(irq_pipeline_nmi_exit); + +/** + * irq_pipeline_can_idle - Prepare for idling the CPU. + * + * Flush the in-band interrupt log before the caller idles, so + * that no event lingers before we actually wait for the next + * IRQ. If some IRQ events were pending, ask the caller to + * abort the idling process since we might have to reschedule. + * On entry: + * + * - we must be running on the in-band stage + * - hard irqs must be enabled + * - the in-band stage must be stalled + * + * Returns @true if the caller may proceed with idling, @false + * otherwise. If @true, hard irqs are left disabled so that no + * event might sneak in until the caller actually + * idles. Otherwise, the interrupt log is synchronized before + * leaving this routine with hard irqs on. + */ +bool irq_pipeline_can_idle(void) +{ + if (irq_pipeline_debug()) { + WARN_ON_ONCE(running_oob()); + WARN_ON_ONCE(hard_irqs_disabled()); + WARN_ON_ONCE(!irqs_disabled()); + } + + hard_local_irq_disable(); + + if (stage_irqs_pending(this_inband_staged())) { + unstall_inband_nocheck(); + synchronize_pipeline(); + stall_inband_nocheck(); + trace_hardirqs_off(); + return false; + } + + return true; +} + +bool __weak irq_cpuidle_control(struct cpuidle_device *dev, + struct cpuidle_state *state) +{ + /* + * Allow entering the idle state by default, matching the + * original behavior when CPU_IDLE is turned + * on. irq_cpuidle_control() may be overriden by an + * out-of-band code for determining whether the CPU may + * actually enter the idle state. + */ + return true; +} + +/** + * irq_cpuidle_enter - Prepare for entering the next idle state + * @dev: CPUIDLE device + * @state: CPUIDLE state to be entered + * + * This routine first checks for pending interrupts in the + * in-band log, then allow the companion core to block the idling + * request if it sees fit with respect to its own requirements. + * + * Returns @true if the caller may proceed with idling, @false + * otherwise. Either way, hard irqs are left disabled. + */ +bool irq_cpuidle_enter(struct cpuidle_device *dev, + struct cpuidle_state *state) +{ + bool ret; + + ret = irq_pipeline_can_idle(); + irq_pipeline_idling_checks(); + if (!ret) + return false; + + ret = irq_cpuidle_control(dev, state); + irq_pipeline_idling_checks(); + + return ret; +} + +static unsigned int inband_work_sirq; + +static irqreturn_t inband_work_interrupt(int sirq, void *dev_id) +{ + irq_work_run(); + + return IRQ_HANDLED; +} + +static struct irqaction inband_work = { + .handler = inband_work_interrupt, + .name = "in-band work", + .flags = IRQF_NO_THREAD, +}; + +void irq_local_work_raise(void) +{ + unsigned long flags; + + /* + * irq_work_queue() may be called from the in-band stage too + * in case we want to delay a work until the hard irqs are on + * again, so we may only sync the in-band log when unstalled, + * with hard irqs on. + */ + flags = hard_local_irq_save(); + irq_post_inband(inband_work_sirq); + if (running_inband() && + !hard_irqs_disabled_flags(flags) && !irqs_disabled()) + sync_current_irq_stage(); + hard_local_irq_restore(flags); +} + +#ifdef CONFIG_DEBUG_IRQ_PIPELINE + +#ifdef CONFIG_LOCKDEP +static inline bool lockdep_on_error(void) +{ + return !debug_locks; +} +#else +static inline bool lockdep_on_error(void) +{ + return false; +} +#endif + +notrace void check_inband_stage(void) +{ + struct irq_stage *this_stage; + unsigned long flags; + + flags = hard_local_irq_save(); + + this_stage = current_irq_stage; + if (likely(this_stage == &inband_stage && !test_oob_stall())) { + hard_local_irq_restore(flags); + return; + } + + if (in_nmi() || irq_pipeline_oopsing || lockdep_on_error()) { + hard_local_irq_restore(flags); + return; + } + + /* + * This will disable all further pipeline debug checks, since + * a wrecked interrupt state is likely to trigger many of + * them, ending up in a terrible mess. IOW, the current + * situation must be fixed prior to investigating any + * subsequent issue that might still exist. + */ + irq_pipeline_oopsing = true; + + hard_local_irq_restore(flags); + + if (this_stage != &inband_stage) + pr_err("IRQ pipeline: some code running in oob context '%s'\n" + " called an in-band only routine\n", + this_stage->name); + else + pr_err("IRQ pipeline: oob stage found stalled while modifying in-band\n" + " interrupt state and/or running sleeping code\n"); + + dump_stack(); +} +EXPORT_SYMBOL(check_inband_stage); + +void check_spinlock_context(void) +{ + WARN_ON_ONCE(in_pipeline() || running_oob()); + +} +EXPORT_SYMBOL(check_spinlock_context); + +#endif /* CONFIG_DEBUG_IRQ_PIPELINE */ + +static inline void fixup_percpu_data(void) +{ +#ifdef CONFIG_SMP + struct irq_pipeline_data *p; + int cpu; + + /* + * A temporary event log is used by the inband stage during the + * early boot up (bootup_irq_map), until the per-cpu areas + * have been set up. + * + * Obviously, this code must run over the boot CPU, before SMP + * operations start, with hard IRQs off so that nothing can + * change under our feet. + */ + WARN_ON(!hard_irqs_disabled()); + + memcpy(&per_cpu(irq_map_array, 0)[0], &bootup_irq_map, + sizeof(struct irq_event_map)); + + for_each_possible_cpu(cpu) { + p = &per_cpu(irq_pipeline, cpu); + p->stages[0].stage = &inband_stage; + p->stages[0].log.map = &per_cpu(irq_map_array, cpu)[0]; + p->stages[1].log.map = &per_cpu(irq_map_array, cpu)[1]; +#ifdef CONFIG_DEBUG_IRQ_PIPELINE + p->stages[0].cpu = cpu; + p->stages[1].cpu = cpu; +#endif + } +#endif +} + +void __init irq_pipeline_init_early(void) +{ + /* + * This is called early from start_kernel(), even before the + * actual number of IRQs is known. We are running on the boot + * CPU, hw interrupts are off, and secondary CPUs are still + * lost in space. Careful. + */ + fixup_percpu_data(); +} + +/** + * irq_pipeline_init - Main pipeline core inits + * + * This is step #2 of the 3-step pipeline initialization, which + * should happen right after init_IRQ() has run. The internal + * service interrupts are created along with the synthetic IRQ + * domain, and the arch-specific init chores are performed too. + * + * Interrupt pipelining should be fully functional when this + * routine returns. + */ +void __init irq_pipeline_init(void) +{ + WARN_ON(!hard_irqs_disabled()); + + /* + * So far, internally we need one sirq for the tick proxy and + * another one to relay the inband work. The companion core + * may need a few of them as well. Assume 1024 is (more than) + * enough system-wide. + * + * CAVEAT: __irq_domain_add() is a bit fragile, max_irq must + * not translate to a negative value when coerced to a signed + * int, otherwise the domain creation would fail. + */ + synthetic_irq_domain = irq_domain_add_nomap(NULL, 1024, + &sirq_domain_ops, + NULL); + inband_work_sirq = irq_create_direct_mapping(synthetic_irq_domain); + setup_percpu_irq(inband_work_sirq, &inband_work); + + /* + * We are running on the boot CPU, hw interrupts are off, and + * secondary CPUs are still lost in space. Now we may run + * arch-specific code for enabling the pipeline. + */ + arch_irq_pipeline_init(); + +#ifdef CONFIG_SMP + /* + * Hook the remote call IPI which smp_call_function_oob() + * sends to notify remote CPUs of pending work. + * + * CAUTION: the base interrupt controller of a uniprocessor + * machine provides no IPI: skip the operation if the hardware + * cannot support multiple CPUs. + */ + if (num_possible_cpus() > 1 && + __request_percpu_irq(CALL_FUNCTION_OOB_IPI, + smp_call_function_ipi_handler, + IRQF_OOB, "out-of-band function call IPI", + &pipeline_percpu_data)) + WARN_ON(1); +#endif + + irq_pipeline_active = true; + + pr_info("IRQ pipeline enabled\n"); +} + +#ifndef CONFIG_SPARSE_IRQ +EXPORT_SYMBOL_GPL(irq_desc); +#endif diff --git a/kernel/irq/proc.c b/kernel/irq/proc.c index 623b8136e..0d226cd8d 100644 --- a/kernel/irq/proc.c +++ b/kernel/irq/proc.c @@ -518,6 +518,9 @@ int show_interrupts(struct seq_file *p, void *v) seq_printf(p, " %*s", prec, ""); #ifdef CONFIG_GENERIC_IRQ_SHOW_LEVEL seq_printf(p, " %-8s", irqd_is_level_type(&desc->irq_data) ? "Level" : "Edge"); +#endif +#ifdef CONFIG_IRQ_PIPELINE + seq_printf(p, " %-3s", irq_settings_is_oob(desc) ? "oob" : ""); #endif if (desc->name) seq_printf(p, "-%-8s", desc->name); diff --git a/kernel/irq/resend.c b/kernel/irq/resend.c index 5f2c66860..d609b3a47 100644 --- a/kernel/irq/resend.c +++ b/kernel/irq/resend.c @@ -16,10 +16,11 @@ #include #include #include +#include #include "internals.h" -#ifdef CONFIG_HARDIRQS_SW_RESEND +#if defined(CONFIG_HARDIRQS_SW_RESEND) && !defined(CONFIG_IRQ_PIPELINE) /* hlist_head to handle software resend of interrupts: */ static HLIST_HEAD(irq_resend_list); @@ -100,7 +101,12 @@ void irq_resend_init(struct irq_desc *desc) {} static int irq_sw_resend(struct irq_desc *desc) { +#if defined(CONFIG_HARDIRQS_SW_RESEND) && defined(CONFIG_IRQ_PIPELINE) + irq_inject_pipeline(irq_desc_get_irq(desc)); + return 0; +#else return -EINVAL; +#endif } #endif diff --git a/kernel/irq/settings.h b/kernel/irq/settings.h index 7b7efb1a1..47d9896e7 100644 --- a/kernel/irq/settings.h +++ b/kernel/irq/settings.h @@ -19,6 +19,8 @@ enum { _IRQ_DISABLE_UNLAZY = IRQ_DISABLE_UNLAZY, _IRQ_HIDDEN = IRQ_HIDDEN, _IRQ_NO_DEBUG = IRQ_NO_DEBUG, + _IRQ_OOB = IRQ_OOB, + _IRQ_CHAINED = IRQ_CHAINED, _IRQF_MODIFY_MASK = IRQF_MODIFY_MASK, }; @@ -35,6 +37,8 @@ enum { #define IRQ_DISABLE_UNLAZY GOT_YOU_MORON #define IRQ_HIDDEN GOT_YOU_MORON #define IRQ_NO_DEBUG GOT_YOU_MORON +#define IRQ_OOB GOT_YOU_MORON +#define IRQ_CHAINED GOT_YOU_MORON #undef IRQF_MODIFY_MASK #define IRQF_MODIFY_MASK GOT_YOU_MORON @@ -186,3 +190,33 @@ static inline bool irq_settings_no_debug(struct irq_desc *desc) { return desc->status_use_accessors & _IRQ_NO_DEBUG; } + +static inline bool irq_settings_is_oob(struct irq_desc *desc) +{ + return desc->status_use_accessors & _IRQ_OOB; +} + +static inline void irq_settings_clr_oob(struct irq_desc *desc) +{ + desc->status_use_accessors &= ~_IRQ_OOB; +} + +static inline void irq_settings_set_oob(struct irq_desc *desc) +{ + desc->status_use_accessors |= _IRQ_OOB; +} + +static inline bool irq_settings_is_chained(struct irq_desc *desc) +{ + return desc->status_use_accessors & _IRQ_CHAINED; +} + +static inline void irq_settings_set_chained(struct irq_desc *desc) +{ + desc->status_use_accessors |= _IRQ_CHAINED; +} + +static inline void irq_settings_clr_chained(struct irq_desc *desc) +{ + desc->status_use_accessors &= ~_IRQ_CHAINED; +} diff --git a/kernel/irq/spurious.c b/kernel/irq/spurious.c index 02b2daf07..74de27f7d 100644 --- a/kernel/irq/spurious.c +++ b/kernel/irq/spurious.c @@ -176,7 +176,7 @@ static inline int bad_action_ret(irqreturn_t action_ret) { unsigned int r = action_ret; - if (likely(r <= (IRQ_HANDLED | IRQ_WAKE_THREAD))) + if (likely(r <= (IRQ_HANDLED | IRQ_WAKE_THREAD | (running_oob() ? IRQ_FORWARD : 0)))) return 0; return 1; } diff --git a/kernel/irq_work.c b/kernel/irq_work.c index 2f4fb336d..360a23d0e 100644 --- a/kernel/irq_work.c +++ b/kernel/irq_work.c @@ -76,11 +76,8 @@ void __weak arch_irq_work_raise(void) */ } -static __always_inline void irq_work_raise(struct irq_work *work) +void __weak irq_local_work_raise(void) { - if (trace_ipi_send_cpu_enabled() && arch_irq_work_has_interrupt()) - trace_ipi_send_cpu(smp_processor_id(), _RET_IP_, work->func); - arch_irq_work_raise(); } @@ -108,8 +105,11 @@ static void __irq_work_queue_local(struct irq_work *work) return; /* If the work is "lazy", handle it from next tick if any */ - if (!lazy_work || tick_nohz_tick_stopped()) - irq_work_raise(work); + if (!lazy_work || tick_nohz_tick_stopped()) { + if (trace_ipi_send_cpu_enabled() && arch_irq_work_has_interrupt()) + trace_ipi_send_cpu(smp_processor_id(), _RET_IP_, work->func); + irq_local_work_raise(); + } } /* Enqueue the irq work @work on the current CPU */ diff --git a/kernel/kthread.c b/kernel/kthread.c index 980e6b325..97a9703e0 100644 --- a/kernel/kthread.c +++ b/kernel/kthread.c @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -1439,6 +1440,7 @@ void kthread_use_mm(struct mm_struct *mm) { struct mm_struct *active_mm; struct task_struct *tsk = current; + unsigned long flags; WARN_ON_ONCE(!(tsk->flags & PF_KTHREAD)); WARN_ON_ONCE(tsk->mm); @@ -1454,10 +1456,12 @@ void kthread_use_mm(struct mm_struct *mm) /* Hold off tlb flush IPIs while switching mm's */ local_irq_disable(); active_mm = tsk->active_mm; + protect_inband_mm(flags); tsk->active_mm = mm; tsk->mm = mm; membarrier_update_current_mm(mm); switch_mm_irqs_off(active_mm, mm, tsk); + unprotect_inband_mm(flags); local_irq_enable(); task_unlock(tsk); #ifdef finish_arch_post_lock_switch diff --git a/kernel/locking/Makefile b/kernel/locking/Makefile index 0db4093d1..ea72e5917 100644 --- a/kernel/locking/Makefile +++ b/kernel/locking/Makefile @@ -28,6 +28,7 @@ obj-$(CONFIG_RT_MUTEXES) += rtmutex_api.o obj-$(CONFIG_PREEMPT_RT) += spinlock_rt.o ww_rt_mutex.o obj-$(CONFIG_DEBUG_SPINLOCK) += spinlock.o obj-$(CONFIG_DEBUG_SPINLOCK) += spinlock_debug.o +obj-$(CONFIG_IRQ_PIPELINE) += pipeline.o obj-$(CONFIG_QUEUED_RWLOCKS) += qrwlock.o obj-$(CONFIG_LOCK_TORTURE_TEST) += locktorture.o obj-$(CONFIG_WW_MUTEX_SELFTEST) += test-ww_mutex.o diff --git a/kernel/locking/lockdep.c b/kernel/locking/lockdep.c index 3468d8230..9cdfab1d8 100644 --- a/kernel/locking/lockdep.c +++ b/kernel/locking/lockdep.c @@ -42,6 +42,7 @@ #include #include #include +#include #include #include #include @@ -136,9 +137,56 @@ static __always_inline bool lockdep_enabled(void) static arch_spinlock_t __lock = (arch_spinlock_t)__ARCH_SPIN_LOCK_UNLOCKED; static struct task_struct *__owner; +static __always_inline bool lockdep_stage_disabled(void) +{ + return stage_disabled(); +} + +#ifdef CONFIG_IRQ_PIPELINE +/* + * If LOCKDEP is enabled, we want irqs to be disabled for both stages + * when traversing the lockdep code for hard and hybrid locks (at the + * expense of massive latency overhead though). + */ +static __always_inline unsigned long lockdep_stage_test_and_disable(int *irqsoff) +{ + return test_and_lock_stage(irqsoff); +} + +static __always_inline unsigned long lockdep_stage_disable(void) +{ + return lockdep_stage_test_and_disable(NULL); +} + +static __always_inline void lockdep_stage_restore(unsigned long flags) +{ + unlock_stage(flags); +} + +#else + +#define lockdep_stage_test_and_disable(__irqsoff) \ + ({ \ + unsigned long __flags; \ + raw_local_irq_save(__flags); \ + *(__irqsoff) = irqs_disabled_flags(__flags); \ + __flags; \ + }) + +#define lockdep_stage_disable() \ + ({ \ + unsigned long __flags; \ + raw_local_irq_save(__flags); \ + __flags; \ + }) + +#define lockdep_stage_restore(__flags) raw_local_irq_restore(__flags) + +#endif /* !CONFIG_IRQ_PIPELINE */ + static inline void lockdep_lock(void) { - DEBUG_LOCKS_WARN_ON(!irqs_disabled()); + DEBUG_LOCKS_WARN_ON(!hard_irqs_disabled()); __this_cpu_inc(lockdep_recursion); arch_spin_lock(&__lock); @@ -147,7 +195,7 @@ static inline void lockdep_lock(void) static inline void lockdep_unlock(void) { - DEBUG_LOCKS_WARN_ON(!irqs_disabled()); + DEBUG_LOCKS_WARN_ON(!hard_irqs_disabled()); if (debug_locks && DEBUG_LOCKS_WARN_ON(__owner != current)) return; @@ -920,7 +968,7 @@ look_up_lock_class(const struct lockdep_map *lock, unsigned int subclass) /* * We do an RCU walk of the hash, see lockdep_free_key_range(). */ - if (DEBUG_LOCKS_WARN_ON(!irqs_disabled())) + if (DEBUG_LOCKS_WARN_ON(!lockdep_stage_disabled())) return NULL; hlist_for_each_entry_rcu_notrace(class, hash_head, hash_entry) { @@ -1219,7 +1267,7 @@ void lockdep_register_key(struct lock_class_key *key) return; hash_head = keyhashentry(key); - raw_local_irq_save(flags); + flags = lockdep_stage_disable(); if (!graph_lock()) goto restore_irqs; hlist_for_each_entry_rcu(k, hash_head, hash_entry) { @@ -1230,7 +1278,7 @@ void lockdep_register_key(struct lock_class_key *key) out_unlock: graph_unlock(); restore_irqs: - raw_local_irq_restore(flags); + lockdep_stage_restore(flags); } EXPORT_SYMBOL_GPL(lockdep_register_key); @@ -1279,7 +1327,7 @@ register_lock_class(struct lockdep_map *lock, unsigned int subclass, int force) struct lock_class *class; int idx; - DEBUG_LOCKS_WARN_ON(!irqs_disabled()); + DEBUG_LOCKS_WARN_ON(!lockdep_stage_disabled()); class = look_up_lock_class(lock, subclass); if (likely(class)) @@ -2093,11 +2141,11 @@ unsigned long lockdep_count_forward_deps(struct lock_class *class) __bfs_init_root(&this, class); - raw_local_irq_save(flags); + flags = lockdep_stage_disable(); lockdep_lock(); ret = __lockdep_count_forward_deps(&this); lockdep_unlock(); - raw_local_irq_restore(flags); + lockdep_stage_restore(flags); return ret; } @@ -2119,11 +2167,11 @@ unsigned long lockdep_count_backward_deps(struct lock_class *class) __bfs_init_root(&this, class); - raw_local_irq_save(flags); + flags = lockdep_stage_disable(); lockdep_lock(); ret = __lockdep_count_backward_deps(&this); lockdep_unlock(); - raw_local_irq_restore(flags); + lockdep_stage_restore(flags); return ret; } @@ -4310,6 +4358,8 @@ static void __trace_hardirqs_on_caller(void) */ void lockdep_hardirqs_on_prepare(void) { + unsigned long flags; + if (unlikely(!debug_locks)) return; @@ -4332,38 +4382,43 @@ void lockdep_hardirqs_on_prepare(void) return; } + flags = hard_cond_local_irq_save(); + /* * We're enabling irqs and according to our state above irqs weren't * already enabled, yet we find the hardware thinks they are in fact * enabled.. someone messed up their IRQ state tracing. */ - if (DEBUG_LOCKS_WARN_ON(!irqs_disabled())) - return; + if (DEBUG_LOCKS_WARN_ON(!lockdep_stage_disabled())) + goto out; /* * See the fine text that goes along with this variable definition. */ if (DEBUG_LOCKS_WARN_ON(early_boot_irqs_disabled)) - return; + goto out; /* * Can't allow enabling interrupts while in an interrupt handler, * that's general bad form and such. Recursion, limited stack etc.. */ - if (DEBUG_LOCKS_WARN_ON(lockdep_hardirq_context())) - return; + if (DEBUG_LOCKS_WARN_ON(running_inband() && lockdep_hardirq_context())) + goto out; current->hardirq_chain_key = current->curr_chain_key; lockdep_recursion_inc(); __trace_hardirqs_on_caller(); lockdep_recursion_finish(); +out: + hard_cond_local_irq_restore(flags); } EXPORT_SYMBOL_GPL(lockdep_hardirqs_on_prepare); void noinstr lockdep_hardirqs_on(unsigned long ip) { struct irqtrace_events *trace = ¤t->irqtrace; + unsigned long flags; if (unlikely(!debug_locks)) return; @@ -4401,13 +4456,15 @@ void noinstr lockdep_hardirqs_on(unsigned long ip) return; } + flags = hard_cond_local_irq_save(); + /* * We're enabling irqs and according to our state above irqs weren't * already enabled, yet we find the hardware thinks they are in fact * enabled.. someone messed up their IRQ state tracing. */ - if (DEBUG_LOCKS_WARN_ON(!irqs_disabled())) - return; + if (DEBUG_LOCKS_WARN_ON(!lockdep_stage_disabled())) + goto out; /* * Ensure the lock stack remained unchanged between @@ -4422,6 +4479,8 @@ void noinstr lockdep_hardirqs_on(unsigned long ip) trace->hardirq_enable_ip = ip; trace->hardirq_enable_event = ++trace->irq_events; debug_atomic_inc(hardirqs_on_events); +out: + hard_cond_local_irq_restore(flags); } EXPORT_SYMBOL_GPL(lockdep_hardirqs_on); @@ -4430,6 +4489,8 @@ EXPORT_SYMBOL_GPL(lockdep_hardirqs_on); */ void noinstr lockdep_hardirqs_off(unsigned long ip) { + unsigned long flags; + if (unlikely(!debug_locks)) return; @@ -4444,12 +4505,14 @@ void noinstr lockdep_hardirqs_off(unsigned long ip) } else if (__this_cpu_read(lockdep_recursion)) return; + flags = hard_cond_local_irq_save(); + /* * So we're supposed to get called after you mask local IRQs, but for * some reason the hardware doesn't quite think you did a proper job. */ - if (DEBUG_LOCKS_WARN_ON(!irqs_disabled())) - return; + if (DEBUG_LOCKS_WARN_ON(!lockdep_stage_disabled())) + goto out; if (lockdep_hardirqs_enabled()) { struct irqtrace_events *trace = ¤t->irqtrace; @@ -4464,6 +4527,8 @@ void noinstr lockdep_hardirqs_off(unsigned long ip) } else { debug_atomic_inc(redundant_hardirqs_off); } +out: + hard_cond_local_irq_restore(flags); } EXPORT_SYMBOL_GPL(lockdep_hardirqs_off); @@ -4473,20 +4538,23 @@ EXPORT_SYMBOL_GPL(lockdep_hardirqs_off); void lockdep_softirqs_on(unsigned long ip) { struct irqtrace_events *trace = ¤t->irqtrace; + unsigned long flags; if (unlikely(!lockdep_enabled())) return; + flags = hard_cond_local_irq_save(); + /* * We fancy IRQs being disabled here, see softirq.c, avoids * funny state and nesting things. */ - if (DEBUG_LOCKS_WARN_ON(!irqs_disabled())) - return; + if (DEBUG_LOCKS_WARN_ON(!lockdep_stage_disabled())) + goto out; if (current->softirqs_enabled) { debug_atomic_inc(redundant_softirqs_on); - return; + goto out; } lockdep_recursion_inc(); @@ -4505,6 +4573,8 @@ void lockdep_softirqs_on(unsigned long ip) if (lockdep_hardirqs_enabled()) mark_held_locks(current, LOCK_ENABLED_SOFTIRQ); lockdep_recursion_finish(); +out: + hard_cond_local_irq_restore(flags); } /* @@ -4512,14 +4582,18 @@ void lockdep_softirqs_on(unsigned long ip) */ void lockdep_softirqs_off(unsigned long ip) { + unsigned long flags; + if (unlikely(!lockdep_enabled())) return; + flags = hard_cond_local_irq_save(); + /* * We fancy IRQs being disabled here, see softirq.c */ - if (DEBUG_LOCKS_WARN_ON(!irqs_disabled())) - return; + if (DEBUG_LOCKS_WARN_ON(!lockdep_stage_disabled())) + goto out; if (current->softirqs_enabled) { struct irqtrace_events *trace = ¤t->irqtrace; @@ -4537,6 +4611,8 @@ void lockdep_softirqs_off(unsigned long ip) DEBUG_LOCKS_WARN_ON(!softirq_count()); } else debug_atomic_inc(redundant_softirqs_off); +out: + hard_cond_local_irq_restore(flags); } static int @@ -4906,11 +4982,11 @@ void lockdep_init_map_type(struct lockdep_map *lock, const char *name, if (DEBUG_LOCKS_WARN_ON(!lockdep_enabled())) return; - raw_local_irq_save(flags); + flags = lockdep_stage_disable(); lockdep_recursion_inc(); register_lock_class(lock, subclass, 1); lockdep_recursion_finish(); - raw_local_irq_restore(flags); + lockdep_stage_restore(flags); } } EXPORT_SYMBOL_GPL(lockdep_init_map_type); @@ -5272,7 +5348,7 @@ static int reacquire_held_locks(struct task_struct *curr, unsigned int depth, struct held_lock *hlock; int first_idx = idx; - if (DEBUG_LOCKS_WARN_ON(!irqs_disabled())) + if (DEBUG_LOCKS_WARN_ON(!lockdep_stage_disabled())) return 0; for (hlock = curr->held_locks + idx; idx < depth; idx++, hlock++) { @@ -5584,14 +5660,22 @@ static void __lock_unpin_lock(struct lockdep_map *lock, struct pin_cookie cookie static noinstr void check_flags(unsigned long flags) { #if defined(CONFIG_PROVE_LOCKING) && defined(CONFIG_DEBUG_LOCKDEP) - if (!debug_locks) + bool stalled; + + /* + * irq_pipeline: we can't and don't want to check the + * consistency of the irq tracer when running the interrupt + * entry prologue or oob stage code, since the inband stall + * bit does not reflect the current irq state in these cases. + */ + if (on_pipeline_entry() || running_oob() || !debug_locks) return; /* Get the warning out.. */ instrumentation_begin(); - if (irqs_disabled_flags(flags)) { - if (DEBUG_LOCKS_WARN_ON(lockdep_hardirqs_enabled())) { + if (stage_disabled_flags(flags, &stalled)) { + if (DEBUG_LOCKS_WARN_ON(lockdep_hardirqs_enabled() && stalled)) { printk("possible reason: unannotated irqs-off.\n"); } } else { @@ -5633,13 +5717,13 @@ void lock_set_class(struct lockdep_map *lock, const char *name, if (unlikely(!lockdep_enabled())) return; - raw_local_irq_save(flags); + flags = lockdep_stage_disable(); lockdep_recursion_inc(); check_flags(flags); if (__lock_set_class(lock, name, key, subclass, ip)) check_chain_key(current); lockdep_recursion_finish(); - raw_local_irq_restore(flags); + lockdep_stage_restore(flags); } EXPORT_SYMBOL_GPL(lock_set_class); @@ -5650,13 +5734,13 @@ void lock_downgrade(struct lockdep_map *lock, unsigned long ip) if (unlikely(!lockdep_enabled())) return; - raw_local_irq_save(flags); + flags = lockdep_stage_disable(); lockdep_recursion_inc(); check_flags(flags); if (__lock_downgrade(lock, ip)) check_chain_key(current); lockdep_recursion_finish(); - raw_local_irq_restore(flags); + lockdep_stage_restore(flags); } EXPORT_SYMBOL_GPL(lock_downgrade); @@ -5721,6 +5805,7 @@ void lock_acquire(struct lockdep_map *lock, unsigned int subclass, struct lockdep_map *nest_lock, unsigned long ip) { unsigned long flags; + int irqsoff; trace_lock_acquire(lock, subclass, trylock, read, check, nest_lock, ip); @@ -5747,14 +5832,14 @@ void lock_acquire(struct lockdep_map *lock, unsigned int subclass, return; } - raw_local_irq_save(flags); + flags = lockdep_stage_test_and_disable(&irqsoff); check_flags(flags); lockdep_recursion_inc(); __lock_acquire(lock, subclass, trylock, read, check, - irqs_disabled_flags(flags), nest_lock, ip, 0, 0, 0); + irqsoff, nest_lock, ip, 0, 0, 0); lockdep_recursion_finish(); - raw_local_irq_restore(flags); + lockdep_stage_restore(flags); } EXPORT_SYMBOL_GPL(lock_acquire); @@ -5767,14 +5852,14 @@ void lock_release(struct lockdep_map *lock, unsigned long ip) if (unlikely(!lockdep_enabled())) return; - raw_local_irq_save(flags); + flags = lockdep_stage_disable(); check_flags(flags); lockdep_recursion_inc(); if (__lock_release(lock, ip)) check_chain_key(current); lockdep_recursion_finish(); - raw_local_irq_restore(flags); + lockdep_stage_restore(flags); } EXPORT_SYMBOL_GPL(lock_release); @@ -5794,7 +5879,7 @@ void lock_sync(struct lockdep_map *lock, unsigned subclass, int read, if (unlikely(!lockdep_enabled())) return; - raw_local_irq_save(flags); + flags = lockdep_stage_disable(); check_flags(flags); lockdep_recursion_inc(); @@ -5802,7 +5887,7 @@ void lock_sync(struct lockdep_map *lock, unsigned subclass, int read, irqs_disabled_flags(flags), nest_lock, ip, 0, 0, 1); check_chain_key(current); lockdep_recursion_finish(); - raw_local_irq_restore(flags); + lockdep_stage_restore(flags); } EXPORT_SYMBOL_GPL(lock_sync); @@ -5818,13 +5903,13 @@ noinstr int lock_is_held_type(const struct lockdep_map *lock, int read) if (unlikely(!lockdep_enabled())) return LOCK_STATE_UNKNOWN; - raw_local_irq_save(flags); + flags = lockdep_stage_disable(); check_flags(flags); lockdep_recursion_inc(); ret = __lock_is_held(lock, read); lockdep_recursion_finish(); - raw_local_irq_restore(flags); + lockdep_stage_restore(flags); return ret; } @@ -5839,13 +5924,13 @@ struct pin_cookie lock_pin_lock(struct lockdep_map *lock) if (unlikely(!lockdep_enabled())) return cookie; - raw_local_irq_save(flags); + flags = lockdep_stage_disable(); check_flags(flags); lockdep_recursion_inc(); cookie = __lock_pin_lock(lock); lockdep_recursion_finish(); - raw_local_irq_restore(flags); + lockdep_stage_restore(flags); return cookie; } @@ -5858,13 +5943,13 @@ void lock_repin_lock(struct lockdep_map *lock, struct pin_cookie cookie) if (unlikely(!lockdep_enabled())) return; - raw_local_irq_save(flags); + flags = lockdep_stage_disable(); check_flags(flags); lockdep_recursion_inc(); __lock_repin_lock(lock, cookie); lockdep_recursion_finish(); - raw_local_irq_restore(flags); + lockdep_stage_restore(flags); } EXPORT_SYMBOL_GPL(lock_repin_lock); @@ -5875,13 +5960,13 @@ void lock_unpin_lock(struct lockdep_map *lock, struct pin_cookie cookie) if (unlikely(!lockdep_enabled())) return; - raw_local_irq_save(flags); + flags = lockdep_stage_disable(); check_flags(flags); lockdep_recursion_inc(); __lock_unpin_lock(lock, cookie); lockdep_recursion_finish(); - raw_local_irq_restore(flags); + lockdep_stage_restore(flags); } EXPORT_SYMBOL_GPL(lock_unpin_lock); @@ -6011,12 +6096,12 @@ void lock_contended(struct lockdep_map *lock, unsigned long ip) if (unlikely(!lock_stat || !lockdep_enabled())) return; - raw_local_irq_save(flags); + flags = lockdep_stage_disable(); check_flags(flags); lockdep_recursion_inc(); __lock_contended(lock, ip); lockdep_recursion_finish(); - raw_local_irq_restore(flags); + lockdep_stage_restore(flags); } EXPORT_SYMBOL_GPL(lock_contended); @@ -6029,12 +6114,12 @@ void lock_acquired(struct lockdep_map *lock, unsigned long ip) if (unlikely(!lock_stat || !lockdep_enabled())) return; - raw_local_irq_save(flags); + flags = lockdep_stage_disable(); check_flags(flags); lockdep_recursion_inc(); __lock_acquired(lock, ip); lockdep_recursion_finish(); - raw_local_irq_restore(flags); + lockdep_stage_restore(flags); } EXPORT_SYMBOL_GPL(lock_acquired); #endif @@ -6049,7 +6134,7 @@ void lockdep_reset(void) unsigned long flags; int i; - raw_local_irq_save(flags); + flags = lockdep_stage_disable(); lockdep_init_task(current); memset(current->held_locks, 0, MAX_LOCK_DEPTH*sizeof(struct held_lock)); nr_hardirq_chains = 0; @@ -6058,7 +6143,7 @@ void lockdep_reset(void) debug_locks = 1; for (i = 0; i < CHAINHASH_SIZE; i++) INIT_HLIST_HEAD(chainhash_table + i); - raw_local_irq_restore(flags); + lockdep_stage_restore(flags); } /* Remove a class from a lock chain. Must be called with the graph lock held. */ @@ -6235,7 +6320,7 @@ static void free_zapped_rcu(struct rcu_head *ch) if (WARN_ON_ONCE(ch != &delayed_free.rcu_head)) return; - raw_local_irq_save(flags); + flags = lockdep_stage_disable(); lockdep_lock(); /* closed head */ @@ -6245,7 +6330,7 @@ static void free_zapped_rcu(struct rcu_head *ch) need_callback = prepare_call_rcu_zapped(delayed_free.pf + delayed_free.index); lockdep_unlock(); - raw_local_irq_restore(flags); + lockdep_stage_restore(flags); /* * If there's pending free and its callback has not been scheduled, @@ -6324,12 +6409,12 @@ static void lockdep_free_key_range_imm(void *start, unsigned long size) init_data_structures_once(); - raw_local_irq_save(flags); + flags = lockdep_stage_disable(); lockdep_lock(); __lockdep_free_key_range(pf, start, size); __free_zapped_classes(pf); lockdep_unlock(); - raw_local_irq_restore(flags); + lockdep_stage_restore(flags); } void lockdep_free_key_range(void *start, unsigned long size) @@ -6401,7 +6486,7 @@ static void lockdep_reset_lock_reg(struct lockdep_map *lock) int locked; bool need_callback = false; - raw_local_irq_save(flags); + flags = lockdep_stage_disable(); locked = graph_lock(); if (!locked) goto out_irq; @@ -6426,12 +6511,12 @@ static void lockdep_reset_lock_imm(struct lockdep_map *lock) struct pending_free *pf = delayed_free.pf; unsigned long flags; - raw_local_irq_save(flags); + flags = lockdep_stage_disable(); lockdep_lock(); __lockdep_reset_lock(pf, lock); __free_zapped_classes(pf); lockdep_unlock(); - raw_local_irq_restore(flags); + lockdep_stage_restore(flags); } void lockdep_reset_lock(struct lockdep_map *lock) @@ -6465,7 +6550,7 @@ void lockdep_unregister_key(struct lock_class_key *key) if (WARN_ON_ONCE(static_obj(key))) return; - raw_local_irq_save(flags); + flags = lockdep_stage_disable(); lockdep_lock(); hlist_for_each_entry_rcu(k, hash_head, hash_entry) { @@ -6482,7 +6567,7 @@ void lockdep_unregister_key(struct lock_class_key *key) need_callback = prepare_call_rcu_zapped(pf); } lockdep_unlock(); - raw_local_irq_restore(flags); + lockdep_stage_restore(flags); if (need_callback) call_rcu(&delayed_free.rcu_head, free_zapped_rcu); @@ -6576,7 +6661,7 @@ void debug_check_no_locks_freed(const void *mem_from, unsigned long mem_len) if (unlikely(!debug_locks)) return; - raw_local_irq_save(flags); + flags = lockdep_stage_disable(); for (i = 0; i < curr->lockdep_depth; i++) { hlock = curr->held_locks + i; @@ -6587,7 +6672,7 @@ void debug_check_no_locks_freed(const void *mem_from, unsigned long mem_len) print_freed_lock_bug(curr, mem_from, mem_from + mem_len, hlock); break; } - raw_local_irq_restore(flags); + lockdep_stage_restore(flags); } EXPORT_SYMBOL_GPL(debug_check_no_locks_freed); diff --git a/kernel/locking/lockdep_internals.h b/kernel/locking/lockdep_internals.h index bbe900026..6f78acc29 100644 --- a/kernel/locking/lockdep_internals.h +++ b/kernel/locking/lockdep_internals.h @@ -213,12 +213,12 @@ DECLARE_PER_CPU(struct lockdep_stats, lockdep_stats); this_cpu_inc(lockdep_stats.ptr); #define debug_atomic_inc(ptr) { \ - WARN_ON_ONCE(!irqs_disabled()); \ + WARN_ON_ONCE(!hard_irqs_disabled() && !irqs_disabled());\ __this_cpu_inc(lockdep_stats.ptr); \ } #define debug_atomic_dec(ptr) { \ - WARN_ON_ONCE(!irqs_disabled()); \ + WARN_ON_ONCE(!hard_irqs_disabled() && !irqs_disabled());\ __this_cpu_dec(lockdep_stats.ptr); \ } diff --git a/kernel/locking/pipeline.c b/kernel/locking/pipeline.c new file mode 100644 index 000000000..fde458e82 --- /dev/null +++ b/kernel/locking/pipeline.c @@ -0,0 +1,231 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2016 Philippe Gerum . + */ +#include +#include +#include +#include +#include +#include + +/* + * A hybrid spinlock behaves in different ways depending on the + * current interrupt stage on entry. + * + * Such spinlock always leaves hard IRQs disabled once locked. In + * addition, it stalls the in-band stage when protecting a critical + * section there, disabling preemption like regular spinlocks do as + * well. This combination preserves the regular locking logic when + * called from the in-band stage, while fully disabling preemption by + * other interrupt stages. + * + * When taken from the pipeline entry context, a hybrid lock behaves + * like a hard spinlock, assuming that hard IRQs are already disabled. + * + * The irq descriptor lock (struct irq_desc) is a typical example of + * such lock, which properly serializes accesses regardless of the + * calling context. + */ +void __hybrid_spin_lock(struct raw_spinlock *rlock) +{ + struct hybrid_spinlock *lock; + unsigned long __flags; + + if (running_inband()) + preempt_disable(); + + __flags = hard_local_irq_save(); + hard_lock_acquire(rlock, 0, _RET_IP_); + lock = container_of(rlock, struct hybrid_spinlock, rlock); + lock->hwflags = __flags; +} +EXPORT_SYMBOL(__hybrid_spin_lock); + +void __hybrid_spin_lock_nested(struct raw_spinlock *rlock, int subclass) +{ + struct hybrid_spinlock *lock; + unsigned long __flags; + + if (running_inband()) + preempt_disable(); + + __flags = hard_local_irq_save(); + hard_lock_acquire_nested(rlock, subclass, _RET_IP_); + lock = container_of(rlock, struct hybrid_spinlock, rlock); + lock->hwflags = __flags; +} +EXPORT_SYMBOL(__hybrid_spin_lock_nested); + +void __hybrid_spin_unlock(struct raw_spinlock *rlock) +{ + struct hybrid_spinlock *lock; + unsigned long __flags; + + /* Pick the flags before releasing the lock. */ + lock = container_of(rlock, struct hybrid_spinlock, rlock); + __flags = lock->hwflags; + hard_lock_release(rlock, _RET_IP_); + hard_local_irq_restore(__flags); + + if (running_inband()) + preempt_enable(); +} +EXPORT_SYMBOL(__hybrid_spin_unlock); + +void __hybrid_spin_lock_irq(struct raw_spinlock *rlock) +{ + struct hybrid_spinlock *lock; + unsigned long __flags; + + __flags = hard_local_irq_save(); + + if (running_inband()) { + stall_inband(); + trace_hardirqs_off(); + preempt_disable(); + } + + hard_lock_acquire(rlock, 0, _RET_IP_); + lock = container_of(rlock, struct hybrid_spinlock, rlock); + lock->hwflags = __flags; +} +EXPORT_SYMBOL(__hybrid_spin_lock_irq); + +void __hybrid_spin_unlock_irq(struct raw_spinlock *rlock) +{ + struct hybrid_spinlock *lock; + unsigned long __flags; + + /* Pick the flags before releasing the lock. */ + lock = container_of(rlock, struct hybrid_spinlock, rlock); + __flags = lock->hwflags; + hard_lock_release(rlock, _RET_IP_); + + if (running_inband()) { + trace_hardirqs_on(); + unstall_inband_nocheck(); + hard_local_irq_restore(__flags); + preempt_enable(); + return; + } + + hard_local_irq_restore(__flags); +} +EXPORT_SYMBOL(__hybrid_spin_unlock_irq); + +unsigned long __hybrid_spin_lock_irqsave(struct raw_spinlock *rlock) +{ + struct hybrid_spinlock *lock; + unsigned long __flags, flags; + + __flags = flags = hard_local_irq_save(); + + if (running_inband()) { + flags = test_and_stall_inband(); + trace_hardirqs_off(); + preempt_disable(); + } + + hard_lock_acquire(rlock, 0, _RET_IP_); + lock = container_of(rlock, struct hybrid_spinlock, rlock); + lock->hwflags = __flags; + + return flags; +} +EXPORT_SYMBOL(__hybrid_spin_lock_irqsave); + +void __hybrid_spin_unlock_irqrestore(struct raw_spinlock *rlock, + unsigned long flags) +{ + struct hybrid_spinlock *lock; + unsigned long __flags; + + /* Pick the flags before releasing the lock. */ + lock = container_of(rlock, struct hybrid_spinlock, rlock); + __flags = lock->hwflags; + hard_lock_release(rlock, _RET_IP_); + + if (running_inband()) { + if (!flags) { + trace_hardirqs_on(); + unstall_inband_nocheck(); + } + hard_local_irq_restore(__flags); + preempt_enable(); + return; + } + + hard_local_irq_restore(__flags); +} +EXPORT_SYMBOL(__hybrid_spin_unlock_irqrestore); + +int __hybrid_spin_trylock(struct raw_spinlock *rlock) +{ + struct hybrid_spinlock *lock; + unsigned long __flags; + + if (running_inband()) + preempt_disable(); + + lock = container_of(rlock, struct hybrid_spinlock, rlock); + __flags = hard_local_irq_save(); + + hard_spin_trylock_prepare(rlock); + if (do_raw_spin_trylock(rlock)) { + lock->hwflags = __flags; + hard_trylock_acquire(rlock, 1, _RET_IP_); + return 1; + } + + hard_spin_trylock_fail(rlock); + hard_local_irq_restore(__flags); + + if (running_inband()) + preempt_enable(); + + return 0; +} +EXPORT_SYMBOL(__hybrid_spin_trylock); + +int __hybrid_spin_trylock_irqsave(struct raw_spinlock *rlock, + unsigned long *flags) +{ + struct hybrid_spinlock *lock; + unsigned long __flags; + bool inband; + + inband = running_inband(); + + __flags = *flags = hard_local_irq_save(); + + lock = container_of(rlock, struct hybrid_spinlock, rlock); + if (inband) { + *flags = test_and_stall_inband(); + trace_hardirqs_off(); + preempt_disable(); + } + + hard_spin_trylock_prepare(rlock); + if (do_raw_spin_trylock(rlock)) { + hard_trylock_acquire(rlock, 1, _RET_IP_); + lock->hwflags = __flags; + return 1; + } + + hard_spin_trylock_fail(rlock); + + if (inband && !*flags) { + trace_hardirqs_on(); + unstall_inband_nocheck(); + } + + hard_local_irq_restore(__flags); + + if (inband) + preempt_enable(); + + return 0; +} +EXPORT_SYMBOL(__hybrid_spin_trylock_irqsave); diff --git a/kernel/locking/spinlock_debug.c b/kernel/locking/spinlock_debug.c index 14235671a..8c86d6567 100644 --- a/kernel/locking/spinlock_debug.c +++ b/kernel/locking/spinlock_debug.c @@ -116,6 +116,7 @@ void do_raw_spin_lock(raw_spinlock_t *lock) mmiowb_spin_lock(); debug_spin_lock_after(lock); } +EXPORT_SYMBOL_GPL(do_raw_spin_lock); int do_raw_spin_trylock(raw_spinlock_t *lock) { @@ -133,6 +134,7 @@ int do_raw_spin_trylock(raw_spinlock_t *lock) #endif return ret; } +EXPORT_SYMBOL_GPL(do_raw_spin_trylock); void do_raw_spin_unlock(raw_spinlock_t *lock) { @@ -140,6 +142,7 @@ void do_raw_spin_unlock(raw_spinlock_t *lock) debug_spin_unlock(lock); arch_spin_unlock(&lock->raw_lock); } +EXPORT_SYMBOL_GPL(do_raw_spin_unlock); #ifndef CONFIG_PREEMPT_RT static void rwlock_bug(rwlock_t *lock, const char *msg) diff --git a/kernel/notifier.c b/kernel/notifier.c index b3ce28f39..d468a86c6 100644 --- a/kernel/notifier.c +++ b/kernel/notifier.c @@ -227,6 +227,9 @@ int atomic_notifier_call_chain(struct atomic_notifier_head *nh, { int ret; + if (!running_inband()) + return notifier_call_chain(&nh->head, val, v, -1, NULL); + rcu_read_lock(); ret = notifier_call_chain(&nh->head, val, v, -1, NULL); rcu_read_unlock(); diff --git a/kernel/panic.c b/kernel/panic.c index ef9f9a4e9..ca815c29f 100644 --- a/kernel/panic.c +++ b/kernel/panic.c @@ -29,6 +29,7 @@ #include #include #include +#include #include #include #include @@ -56,7 +57,7 @@ static unsigned long tainted_mask = IS_ENABLED(CONFIG_RANDSTRUCT) ? (1 << TAINT_RANDSTRUCT) : 0; static int pause_on_oops; static int pause_on_oops_flag; -static DEFINE_SPINLOCK(pause_on_oops_lock); +static DEFINE_HARD_SPINLOCK(pause_on_oops_lock); bool crash_kexec_post_notifiers; int panic_on_warn __read_mostly; unsigned long panic_on_taint; @@ -298,8 +299,9 @@ void panic(const char *fmt, ...) * there is nothing to prevent an interrupt handler (that runs * after setting panic_cpu) from invoking panic() again. */ - local_irq_disable(); + hard_local_irq_disable(); preempt_disable_notrace(); + irq_pipeline_oops(); /* * It's possible to come here directly from a panic-assertion and @@ -362,9 +364,12 @@ void panic(const char *fmt, ...) /* * Run any panic handlers, including those that might need to - * add information to the kmsg dump output. + * add information to the kmsg dump output. Skip panic + * handlers if running over the oob stage, as they would most + * likely break. */ - atomic_notifier_call_chain(&panic_notifier_list, 0, buf); + if (running_inband()) + atomic_notifier_call_chain(&panic_notifier_list, 0, buf); panic_print_sys_info(false); @@ -575,7 +580,7 @@ static void do_oops_enter_exit(void) if (!pause_on_oops) return; - spin_lock_irqsave(&pause_on_oops_lock, flags); + raw_spin_lock_irqsave(&pause_on_oops_lock, flags); if (pause_on_oops_flag == 0) { /* This CPU may now print the oops message */ pause_on_oops_flag = 1; @@ -585,21 +590,21 @@ static void do_oops_enter_exit(void) /* This CPU gets to do the counting */ spin_counter = pause_on_oops; do { - spin_unlock(&pause_on_oops_lock); + raw_spin_unlock(&pause_on_oops_lock); spin_msec(MSEC_PER_SEC); - spin_lock(&pause_on_oops_lock); + raw_spin_lock(&pause_on_oops_lock); } while (--spin_counter); pause_on_oops_flag = 0; } else { /* This CPU waits for a different one */ while (spin_counter) { - spin_unlock(&pause_on_oops_lock); + raw_spin_unlock(&pause_on_oops_lock); spin_msec(1); - spin_lock(&pause_on_oops_lock); + raw_spin_lock(&pause_on_oops_lock); } } } - spin_unlock_irqrestore(&pause_on_oops_lock, flags); + raw_spin_unlock_irqrestore(&pause_on_oops_lock, flags); } /* @@ -629,6 +634,7 @@ void oops_enter(void) { tracing_off(); /* can't trust the integrity of the kernel anymore: */ + irq_pipeline_oops(); debug_locks_off(); do_oops_enter_exit(); diff --git a/kernel/power/hibernate.c b/kernel/power/hibernate.c index 8d35b9f9a..3a707ddb7 100644 --- a/kernel/power/hibernate.c +++ b/kernel/power/hibernate.c @@ -309,6 +309,7 @@ static int create_image(int platform_mode) goto Enable_cpus; local_irq_disable(); + hard_cond_local_irq_disable(); system_state = SYSTEM_SUSPEND; @@ -478,6 +479,7 @@ static int resume_target_kernel(bool platform_mode) local_irq_disable(); system_state = SYSTEM_SUSPEND; + hard_cond_local_irq_disable(); error = syscore_suspend(); if (error) @@ -599,6 +601,7 @@ int hibernation_platform_enter(void) local_irq_disable(); system_state = SYSTEM_SUSPEND; + hard_cond_local_irq_disable(); syscore_suspend(); if (pm_wakeup_pending()) { error = -EAGAIN; diff --git a/kernel/printk/internal.h b/kernel/printk/internal.h index 7d4979d5c..91675cbd7 100644 --- a/kernel/printk/internal.h +++ b/kernel/printk/internal.h @@ -61,6 +61,26 @@ void defer_console_output(void); u16 printk_parse_prefix(const char *text, int *level, enum printk_info_flags *flags); + +#ifdef CONFIG_IRQ_PIPELINE + +extern bool irq_pipeline_active; + +static inline bool printk_stage_safe(void) +{ + return running_inband() && + (!hard_irqs_disabled() || !irq_pipeline_active); +} + +#else + +static inline bool printk_stage_safe(void) +{ + return true; +} + +#endif + #else #define PRINTK_PREFIX_MAX 0 diff --git a/kernel/printk/printk.c b/kernel/printk/printk.c index 0fca282c0..c601298fd 100644 --- a/kernel/printk/printk.c +++ b/kernel/printk/printk.c @@ -2067,10 +2067,10 @@ static u8 *__printk_recursion_counter(void) bool success = true; \ \ typecheck(u8 *, recursion_ptr); \ - local_irq_save(flags); \ + prb_irq_save(flags); \ (recursion_ptr) = __printk_recursion_counter(); \ if (*(recursion_ptr) > PRINTK_MAX_RECURSION) { \ - local_irq_restore(flags); \ + prb_irq_restore(flags); \ success = false; \ } else { \ (*(recursion_ptr))++; \ @@ -2083,7 +2083,7 @@ static u8 *__printk_recursion_counter(void) do { \ typecheck(u8 *, recursion_ptr); \ (*(recursion_ptr))--; \ - local_irq_restore(flags); \ + prb_irq_restore(flags); \ } while (0) int printk_delay_msec __read_mostly; @@ -2203,9 +2203,6 @@ int vprintk_store(int facility, int level, int ret = 0; u64 ts_nsec; - if (!printk_enter_irqsave(recursion_ptr, irqflags)) - return 0; - /* * Since the duration of printk() can vary depending on the message * and state of the ringbuffer, grab the timestamp now so that it is @@ -2214,8 +2211,6 @@ int vprintk_store(int facility, int level, */ ts_nsec = local_clock(); - caller_id = printk_caller_id(); - /* * The sprintf needs to come first since the syslog prefix might be * passed in as a parameter. An extra byte must be reserved so that @@ -2239,6 +2234,12 @@ int vprintk_store(int facility, int level, if (dev_info) flags |= LOG_NEWLINE; + /* Disable interrupts as late as possible. */ + if (!printk_enter_irqsave(recursion_ptr, irqflags)) + return 0; + + caller_id = printk_caller_id(); + if (flags & LOG_CONT) { prb_rec_init_wr(&r, reserve_size); if (prb_reserve_in_last(&e, prb, &r, caller_id, PRINTKRB_RECORD_MAX)) { @@ -2312,6 +2313,12 @@ asmlinkage int vprintk_emit(int facility, int level, if (unlikely(suppress_panic_printk) && other_cpu_in_panic()) return 0; + if (unlikely(!printk_stage_safe())) { + printed_len = vprintk_store(facility, level, dev_info, fmt, args); + defer_console_output(); + return printed_len; + } + if (level == LOGLEVEL_SCHED) { level = LOGLEVEL_DEFAULT; in_sched = true; @@ -2438,6 +2445,75 @@ static void set_user_specified(struct console_cmdline *c, bool user_specified) console_set_on_cmdline = 1; } +#ifdef CONFIG_RAW_PRINTK +static struct console *raw_console; +static DEFINE_HARD_SPINLOCK(raw_console_lock); + +static inline bool console_is_usable(struct console *con); + +void raw_puts(const char *s, size_t len) +{ + unsigned long flags; + + raw_spin_lock_irqsave(&raw_console_lock, flags); + if (raw_console) + raw_console->write_raw(raw_console, s, len); + raw_spin_unlock_irqrestore(&raw_console_lock, flags); +} +EXPORT_SYMBOL(raw_puts); + +void raw_vprintk(const char *fmt, va_list ap) +{ + char buf[256]; + size_t n; + + if (raw_console == NULL || !console_is_usable(raw_console)) + return; + + touch_nmi_watchdog(); + n = vscnprintf(buf, sizeof(buf), fmt, ap); + raw_puts(buf, n); +} +EXPORT_SYMBOL(raw_vprintk); + +asmlinkage __visible void raw_printk(const char *fmt, ...) +{ + va_list ap; + + va_start(ap, fmt); + raw_vprintk(fmt, ap); + va_end(ap); +} +EXPORT_SYMBOL(raw_printk); + +static inline void register_raw_console(struct console *newcon) +{ + unsigned long flags; + + raw_spin_lock_irqsave(&raw_console_lock, flags); + if (newcon->write_raw) + raw_console = newcon; + raw_spin_unlock_irqrestore(&raw_console_lock, flags); +} + +static inline void unregister_raw_console(struct console *oldcon) +{ + unsigned long flags; + + raw_spin_lock_irqsave(&raw_console_lock, flags); + if (oldcon == raw_console) + raw_console = NULL; + raw_spin_unlock_irqrestore(&raw_console_lock, flags); +} + +#else + +static inline void register_raw_console(struct console *newcon) { } + +static inline void unregister_raw_console(struct console *oldcon) { } + +#endif + static int __add_preferred_console(char *name, int idx, char *options, char *brl_options, bool user_specified) { @@ -3523,6 +3599,9 @@ void register_console(struct console *newcon) if (err || newcon->flags & CON_BRL) goto unlock; + /* The latest raw console to register is current. */ + register_raw_console(newcon); + /* * If we have a bootconsole, and are switching to a real console, * don't print everything out again, since when the boot console, and @@ -3595,6 +3674,8 @@ static int unregister_console_locked(struct console *console) con_printk(KERN_INFO, console, "disabled\n"); + unregister_raw_console(console); + res = _braille_unregister_console(console); if (res < 0) return res; diff --git a/kernel/printk/printk_ringbuffer.c b/kernel/printk/printk_ringbuffer.c index fde338606..980105c6e 100644 --- a/kernel/printk/printk_ringbuffer.c +++ b/kernel/printk/printk_ringbuffer.c @@ -1356,12 +1356,12 @@ bool prb_reserve_in_last(struct prb_reserved_entry *e, struct printk_ringbuffer struct prb_desc *d; unsigned long id; - local_irq_save(e->irqflags); + prb_irq_save(e->irqflags); /* Transition the newest descriptor back to the reserved state. */ d = desc_reopen_last(desc_ring, caller_id, &id); if (!d) { - local_irq_restore(e->irqflags); + prb_irq_restore(e->irqflags); goto fail_reopen; } @@ -1500,12 +1500,12 @@ bool prb_reserve(struct prb_reserved_entry *e, struct printk_ringbuffer *rb, * interrupts during the reserve/commit window in order to minimize * the likelihood of this happening. */ - local_irq_save(e->irqflags); + prb_irq_save(e->irqflags); if (!desc_reserve(rb, &id)) { /* Descriptor reservation failures are tracked. */ atomic_long_inc(&rb->fail); - local_irq_restore(e->irqflags); + prb_irq_restore(e->irqflags); goto fail; } @@ -1610,7 +1610,7 @@ static void _prb_commit(struct prb_reserved_entry *e, unsigned long state_val) } /* Restore interrupts, the reserve/commit window is finished. */ - local_irq_restore(e->irqflags); + prb_irq_restore(e->irqflags); } /** diff --git a/kernel/printk/printk_ringbuffer.h b/kernel/printk/printk_ringbuffer.h index 18cd25e48..636631769 100644 --- a/kernel/printk/printk_ringbuffer.h +++ b/kernel/printk/printk_ringbuffer.h @@ -222,6 +222,18 @@ enum desc_state { #define DESC0_ID(ct_bits) DESC_ID(-(_DESCS_COUNT(ct_bits) + 1)) #define DESC0_SV(ct_bits) DESC_SV(DESC0_ID(ct_bits), desc_reusable) +/* + * When interrupt pipelining is enabled, we want the critical sections + * to be protected against preemption by out-of-band code. + */ +#ifdef CONFIG_IRQ_PIPELINE +#define prb_irq_save(__flags) do { (__flags) = hard_local_irq_save(); } while (0) +#define prb_irq_restore(__flags) hard_local_irq_restore(__flags) +#else +#define prb_irq_save(__flags) local_irq_save(__flags) +#define prb_irq_restore(__flags) local_irq_restore(__flags) +#endif + /* * Define a ringbuffer with an external text data buffer. The same as * DEFINE_PRINTKRB() but requires specifying an external buffer for the diff --git a/kernel/printk/printk_safe.c b/kernel/printk/printk_safe.c index 6d10927a0..bae54c76b 100644 --- a/kernel/printk/printk_safe.c +++ b/kernel/printk/printk_safe.c @@ -9,6 +9,7 @@ #include #include #include +#include #include "internal.h" @@ -38,7 +39,7 @@ asmlinkage int vprintk(const char *fmt, va_list args) * Use the main logbuf even in NMI. But avoid calling console * drivers that might have their own locks. */ - if (this_cpu_read(printk_context) || in_nmi()) + if (this_cpu_read(printk_context) || !printk_stage_safe() || in_nmi()) return vprintk_deferred(fmt, args); /* No obstacles. */ diff --git a/kernel/ptrace.c b/kernel/ptrace.c index 443057bee..4d9dce884 100644 --- a/kernel/ptrace.c +++ b/kernel/ptrace.c @@ -862,10 +862,12 @@ static int ptrace_resume(struct task_struct *child, long request, if (unlikely(!arch_has_block_step())) return -EIO; user_enable_block_step(child); + inband_ptstep_notify(child); } else if (is_singlestep(request) || is_sysemu_singlestep(request)) { if (unlikely(!arch_has_single_step())) return -EIO; user_enable_single_step(child); + inband_ptstep_notify(child); } else { user_disable_single_step(child); } diff --git a/kernel/rcu/tree.c b/kernel/rcu/tree.c index fda08520c..cafb3774b 100644 --- a/kernel/rcu/tree.c +++ b/kernel/rcu/tree.c @@ -612,7 +612,7 @@ void __rcu_irq_enter_check_tick(void) struct rcu_data *rdp = this_cpu_ptr(&rcu_data); // If we're here from NMI there's nothing to do. - if (in_nmi()) + if (in_nonmaskable()) return; RCU_LOCKDEP_WARN(rcu_dynticks_curr_cpu_in_eqs(), @@ -696,6 +696,9 @@ notrace bool rcu_is_watching(void) { bool ret; + if (on_pipeline_entry()) + return true; + preempt_disable_notrace(); ret = !rcu_dynticks_curr_cpu_in_eqs(); preempt_enable_notrace(); @@ -4211,7 +4214,7 @@ bool rcu_lockdep_current_cpu_online(void) struct rcu_data *rdp; bool ret = false; - if (in_nmi() || !rcu_scheduler_fully_active) + if (in_nonmaskable() || !rcu_scheduler_fully_active) return true; preempt_disable_notrace(); rdp = this_cpu_ptr(&rcu_data); diff --git a/kernel/rcu/tree_plugin.h b/kernel/rcu/tree_plugin.h index 41021080a..58f2ae592 100644 --- a/kernel/rcu/tree_plugin.h +++ b/kernel/rcu/tree_plugin.h @@ -630,8 +630,9 @@ static void rcu_read_unlock_special(struct task_struct *t) bool preempt_bh_were_disabled = !!(preempt_count() & (PREEMPT_MASK | SOFTIRQ_MASK)); - /* NMI handlers cannot block and cannot safely manipulate state. */ - if (in_nmi()) + /* Neither NMI handlers nor pipeline entry code can either + block or safely manipulate state. */ + if (in_nonmaskable()) return; local_irq_save(flags); @@ -821,7 +822,7 @@ void rcu_read_unlock_strict(void) { struct rcu_data *rdp; - if (irqs_disabled() || preempt_count() || !rcu_state.gp_kthread) + if (on_pipeline_entry() || running_oob() || irqs_disabled() || preempt_count() || !rcu_state.gp_kthread) return; rdp = this_cpu_ptr(&rcu_data); rdp->cpu_no_qs.b.norm = false; diff --git a/kernel/rcu/update.c b/kernel/rcu/update.c index 19bf6fa3e..449758e9b 100644 --- a/kernel/rcu/update.c +++ b/kernel/rcu/update.c @@ -101,6 +101,11 @@ module_param(rcu_normal_after_boot, int, 0444); */ static bool rcu_read_lock_held_common(bool *ret) { + if (irqs_pipelined() && + (hard_irqs_disabled() || running_oob())) { + *ret = true; + return true; + } if (!debug_lockdep_rcu_enabled()) { *ret = true; return true; @@ -249,6 +254,32 @@ EXPORT_SYMBOL_GPL(rcu_inkernel_boot_has_ended); #endif /* #ifndef CONFIG_TINY_RCU */ +#ifdef CONFIG_IRQ_PIPELINE + +/* + * Prepare for taking the RCU read lock when running out-of-band. Nop + * otherwise. + */ +void rcu_oob_prepare_lock(void) +{ + if (!on_pipeline_entry() && running_oob()) + ct_nmi_enter(); +} +EXPORT_SYMBOL_GPL(rcu_oob_prepare_lock); + +/* + * Converse to rcu_oob_prepare_lock(), after dropping the RCU read + * lock. + */ +void rcu_oob_finish_lock(void) +{ + if (!on_pipeline_entry() && running_oob()) + ct_nmi_exit(); +} +EXPORT_SYMBOL_GPL(rcu_oob_finish_lock); + +#endif /* CONFIG_IRQ_PIPELINE */ + /* * Test each non-SRCU synchronous grace-period wait API. This is * useful just after a change in mode for these primitives, and diff --git a/kernel/sched/core.c b/kernel/sched/core.c index 86606fb9e..3828b480e 100644 --- a/kernel/sched/core.c +++ b/kernel/sched/core.c @@ -3174,6 +3174,8 @@ static int __set_cpus_allowed_ptr_locked(struct task_struct *p, __do_set_cpus_allowed(p, ctx); + inband_migration_notify(p, dest_cpu); + return affine_move_task(rq, p, rf, dest_cpu, ctx->flags); out: @@ -4213,7 +4215,7 @@ int try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags) * - we're serialized against set_special_state() by virtue of * it disabling IRQs (this allows not taking ->pi_lock). */ - if (!ttwu_state_match(p, state, &success)) + if (!ttwu_state_match(p, state, &success) || task_is_off_stage(p)) goto out; trace_sched_waking(p); @@ -4229,7 +4231,7 @@ int try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags) */ scoped_guard (raw_spinlock_irqsave, &p->pi_lock) { smp_mb__after_spinlock(); - if (!ttwu_state_match(p, state, &success)) + if (!ttwu_state_match(p, state, &success) || task_is_off_stage(p)) break; trace_sched_waking(p); @@ -4534,7 +4536,9 @@ static void __sched_fork(unsigned long clone_flags, struct task_struct *p) p->wake_entry.u_flags = CSD_TYPE_TTWU; p->migration_pending = NULL; #endif - init_sched_mm_cid(p); +#ifdef CONFIG_IRQ_PIPELINE + init_task_stall_bits(p); +#endif } DEFINE_STATIC_KEY_FALSE(sched_numa_balancing); @@ -5184,6 +5188,13 @@ prepare_task_switch(struct rq *rq, struct task_struct *prev, fire_sched_out_preempt_notifiers(prev, next); kmap_local_sched_out(); prepare_task(next); + prepare_inband_switch(next); + /* + * Do not fold the following hard irqs disabling into + * prepare_inband_switch(), this is required when pipelining + * interrupts, not only by alternate scheduling. + */ + hard_cond_local_irq_disable(); prepare_arch_switch(next); } @@ -5304,8 +5315,19 @@ asmlinkage __visible void schedule_tail(struct task_struct *prev) * finish_task_switch() will drop rq->lock() and lower preempt_count * and the preempt_enable() will end up enabling preemption (on * PREEMPT_COUNT kernels). - */ - + * + * If interrupts are pipelined, we may enable hard irqs since + * the in-band stage is stalled. If dovetailing is enabled + * too, schedule_tail() is the place where transitions of + * tasks from the in-band to the oob stage completes. The + * companion core is notified that 'prev' is now suspended in + * the in-band stage, and can be safely resumed in the oob + * stage. + */ + + WARN_ON_ONCE(irq_pipeline_debug() && !irqs_disabled()); + hard_cond_local_irq_enable(); + oob_trampoline(); finish_task_switch(prev); preempt_enable(); @@ -5362,6 +5384,20 @@ context_switch(struct rq *rq, struct task_struct *prev, switch_mm_irqs_off(prev->active_mm, next->mm, next); lru_gen_use_mm(next->mm); + /* + * If dovetail is enabled, insert a short window of + * opportunity for preemption by out-of-band IRQs + * before finalizing the context switch. + * dovetail_context_switch() can deal with preempting + * partially switched in-band contexts. + */ + if (dovetailing()) { + struct mm_struct *oldmm = prev->active_mm; + prev->active_mm = next->mm; + hard_local_irq_sync(); + prev->active_mm = oldmm; + } + if (!prev->mm) { // from kernel /* will mmdrop_lazy_tlb() in finish_task_switch(). */ rq->prev_mm = prev->active_mm; @@ -5378,6 +5414,15 @@ context_switch(struct rq *rq, struct task_struct *prev, switch_to(prev, next, prev); barrier(); + /* + * If 'next' is on its way to the oob stage, don't run the + * context switch epilogue just yet. We will do that at some + * point later, when the task switches back to the in-band + * stage. + */ + if (unlikely(inband_switch_tail())) + return NULL; + return finish_task_switch(prev); } @@ -5939,6 +5984,8 @@ static inline void schedule_debug(struct task_struct *prev, bool preempt) panic("corrupted shadow stack detected inside scheduler\n"); #endif + check_inband_stage(); + #ifdef CONFIG_DEBUG_ATOMIC_SLEEP if (!preempt && READ_ONCE(prev->__state) && prev->non_block_count) { printk(KERN_ERR "BUG: scheduling in a non-blocking section: %s/%d/%i\n", @@ -6572,7 +6619,7 @@ pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf) * * WARNING: must be called with preemption disabled! */ -static void __sched notrace __schedule(unsigned int sched_mode) +static int __sched notrace __schedule(unsigned int sched_mode) { struct task_struct *prev, *next; unsigned long *switch_count; @@ -6695,11 +6742,16 @@ static void __sched notrace __schedule(unsigned int sched_mode) /* Also unlocks the rq: */ rq = context_switch(rq, prev, next, &rf); + if (dovetailing() && rq == NULL) + /* Task moved to the oob stage. */ + return 1; } else { rq_unpin_lock(rq, &rf); __balance_callbacks(rq); raw_spin_rq_unlock_irq(rq); } + + return 0; } void __noreturn do_task_dead(void) @@ -6768,7 +6820,8 @@ asmlinkage __visible void __sched schedule(void) sched_submit_work(tsk); do { preempt_disable(); - __schedule(SM_NONE); + if (__schedule(SM_NONE)) + return; sched_preempt_enable_no_resched(); } while (need_resched()); sched_update_worker(tsk); @@ -6861,7 +6914,8 @@ static void __sched notrace preempt_schedule_common(void) */ preempt_disable_notrace(); preempt_latency_start(1); - __schedule(SM_PREEMPT); + if (__schedule(SM_PREEMPT)) + return; preempt_latency_stop(1); preempt_enable_no_resched_notrace(); @@ -6883,7 +6937,7 @@ asmlinkage __visible void __sched notrace preempt_schedule(void) * If there is a non-zero preempt_count or interrupts are disabled, * we do not want to preempt the current task. Just return.. */ - if (likely(!preemptible())) + if (likely(!running_inband() || !preemptible())) return; preempt_schedule_common(); } @@ -6929,7 +6983,7 @@ asmlinkage __visible void __sched notrace preempt_schedule_notrace(void) { enum ctx_state prev_ctx; - if (likely(!preemptible())) + if (likely(!running_inband() || !preemptible())) return; do { @@ -6991,23 +7045,41 @@ EXPORT_SYMBOL(dynamic_preempt_schedule_notrace); * off of irq context. * Note, that this is called and return with irqs disabled. This will * protect us against recursive calling from irq. + * + * IRQ pipeline: we are called with hard irqs off, synchronize the + * pipeline then return the same way, so that the in-band log is + * guaranteed empty and further interrupt delivery is postponed by the + * hardware until have exited the kernel. */ asmlinkage __visible void __sched preempt_schedule_irq(void) { enum ctx_state prev_state; + if (irq_pipeline_debug()) { + /* Catch any weirdness in pipelined entry code. */ + if (WARN_ON_ONCE(!running_inband())) + return; + WARN_ON_ONCE(!hard_irqs_disabled()); + } + + hard_cond_local_irq_enable(); + /* Catch callers which need to be fixed */ BUG_ON(preempt_count() || !irqs_disabled()); prev_state = exception_enter(); - do { + for (;;) { preempt_disable(); local_irq_enable(); __schedule(SM_PREEMPT); + sync_inband_irqs(); local_irq_disable(); sched_preempt_enable_no_resched(); - } while (need_resched()); + if (!need_resched()) + break; + hard_cond_local_irq_enable(); + } exception_exit(prev_state); } @@ -8559,6 +8631,8 @@ SYSCALL_DEFINE0(sched_yield) #if !defined(CONFIG_PREEMPTION) || defined(CONFIG_PREEMPT_DYNAMIC) int __sched __cond_resched(void) { + check_inband_stage(); + if (should_resched(0)) { preempt_schedule_common(); return 1; @@ -10247,6 +10321,9 @@ void __cant_migrate(const char *file, int line) { static unsigned long prev_jiffy; + if (irqs_pipelined() && (running_oob() || hard_irqs_disabled())) + return; + if (irqs_disabled()) return; @@ -11533,6 +11610,231 @@ struct cgroup_subsys cpu_cgrp_subsys = { #endif /* CONFIG_CGROUP_SCHED */ +#ifdef CONFIG_DOVETAIL + +int dovetail_leave_inband(void) +{ + struct task_struct *p = current; + struct irq_pipeline_data *pd; + unsigned long flags; + + preempt_disable(); + + pd = raw_cpu_ptr(&irq_pipeline); + + if (WARN_ON_ONCE(dovetail_debug() && pd->task_inflight)) + goto out; /* Paranoid. */ + + raw_spin_lock_irqsave(&p->pi_lock, flags); + pd->task_inflight = p; + /* + * The scope of the off-stage state is broader than _TLF_OOB, + * in that it includes the transition path from the in-band + * context to the oob stage. + */ + set_thread_local_flags(_TLF_OFFSTAGE); + set_current_state(TASK_INTERRUPTIBLE); + raw_spin_unlock_irqrestore(&p->pi_lock, flags); + sched_submit_work(p); + /* + * The current task is scheduled out from the inband stage, + * before resuming on the oob stage. Since this code stands + * for the scheduling tail of the oob scheduler, + * arch_dovetail_switch_finish() is called to perform + * architecture-specific fixups (e.g. fpu context reload). + */ + if (likely(__schedule(SM_NONE))) { + arch_dovetail_switch_finish(false); + return 0; + } + + clear_thread_local_flags(_TLF_OFFSTAGE); + pd->task_inflight = NULL; +out: + preempt_enable(); + + return -ERESTARTSYS; +} +EXPORT_SYMBOL_GPL(dovetail_leave_inband); + +void dovetail_resume_inband(void) +{ + struct task_struct *p; + + p = __this_cpu_read(irq_pipeline.rqlock_owner); + if (WARN_ON_ONCE(dovetail_debug() && p == NULL)) + return; + + if (WARN_ON_ONCE(dovetail_debug() && (preempt_count() & STAGE_MASK))) + return; + + finish_task_switch(p); + preempt_enable(); + oob_trampoline(); +} +EXPORT_SYMBOL_GPL(dovetail_resume_inband); + +#ifdef CONFIG_KVM + +#include + +static inline void notify_guest_preempt(void) +{ + struct kvm_oob_notifier *nfy; + struct irq_pipeline_data *p; + + p = raw_cpu_ptr(&irq_pipeline); + nfy = p->vcpu_notify; + if (unlikely(nfy)) + nfy->handler(nfy); +} +#else +static inline void notify_guest_preempt(void) +{ } +#endif + +bool dovetail_context_switch(struct dovetail_altsched_context *out, + struct dovetail_altsched_context *in, + bool leave_inband) +{ + unsigned long pc __maybe_unused, lockdep_irqs; + struct task_struct *next, *prev, *last; + struct mm_struct *prev_mm, *next_mm; + bool inband_tail = false; + + WARN_ON_ONCE(dovetail_debug() && on_pipeline_entry()); + + if (leave_inband) { + struct task_struct *tsk = current; + /* + * We are about to leave the current inband context + * for switching to an out-of-band task, save the + * preempted context information. + */ + out->task = tsk; + out->active_mm = tsk->active_mm; + /* + * Switching out-of-band may require some housekeeping + * from a kernel VM which might currently run guest + * code, notify it about the upcoming preemption. + */ + notify_guest_preempt(); + } + + arch_dovetail_switch_prepare(leave_inband); + + next = in->task; + prev = out->task; + prev_mm = out->active_mm; + next_mm = in->active_mm; + + if (next_mm == NULL) { + in->active_mm = prev_mm; + in->borrowed_mm = true; + enter_lazy_tlb(prev_mm, next); + } else { + switch_oob_mm(prev_mm, next_mm, next); + /* + * We might be switching back to the inband context + * which we preempted earlier, shortly after "current" + * dropped its mm context in the do_exit() path + * (next->mm == NULL). In such a case, a lazy TLB + * state is expected when leaving the mm. + */ + if (next->mm == NULL) + enter_lazy_tlb(prev_mm, next); + } + + if (out->borrowed_mm) { + out->borrowed_mm = false; + out->active_mm = NULL; + } + + /* + * Tasks running out-of-band may alter the (in-band) + * preemption count as long as they don't trigger an in-band + * rescheduling, which Dovetail properly blocks. + * + * If the preemption count is not stack-based but a global + * per-cpu variable instead, changing it has a globally + * visible side-effect though, which is a problem if the + * out-of-band task is preempted and schedules away before the + * change is rolled back: this may cause the in-band context + * to later resume with a broken preemption count. + * + * For this reason, the preemption count of any context which + * blocks from the out-of-band stage is carried over and + * restored across switches, emulating a stack-based + * storage. + * + * Eventually, the count is reset to FORK_PREEMPT_COUNT upon + * transition from out-of-band to in-band stage, reinstating + * the value in effect when the converse transition happened + * at some point before. + */ + if (IS_ENABLED(CONFIG_HAVE_PERCPU_PREEMPT_COUNT)) + pc = preempt_count(); + + /* + * Like the preemption count and for the same reason, the irq + * state maintained by lockdep must be preserved across + * switches. + */ + lockdep_irqs = lockdep_read_irqs_state(); + + switch_to(prev, next, last); + barrier(); + + if (check_hard_irqs_disabled()) + hard_local_irq_disable(); + + /* + * If we entered this routine for switching to an out-of-band + * task but don't have _TLF_OOB set for the current context + * when resuming, this portion of code is the switch tail of + * the inband schedule() routine, finalizing a transition to + * the inband stage for the current task. Update the stage + * level as/if required. + */ + if (unlikely(!leave_inband && !test_thread_local_flags(_TLF_OOB))) { + if (IS_ENABLED(CONFIG_HAVE_PERCPU_PREEMPT_COUNT)) + preempt_count_set(FORK_PREEMPT_COUNT); + else if (unlikely(dovetail_debug() && + !(preempt_count() & STAGE_MASK))) + WARN_ON_ONCE(1); + else + preempt_count_sub(STAGE_OFFSET); + + lockdep_write_irqs_state(lockdep_irqs); + + /* + * Fixup the interrupt state conversely to what + * inband_switch_tail() does for the opposite stage + * switching direction. + */ + stall_inband(); + trace_hardirqs_off(); + inband_tail = true; + } else { + if (IS_ENABLED(CONFIG_HAVE_PERCPU_PREEMPT_COUNT)) + preempt_count_set(pc); + + lockdep_write_irqs_state(lockdep_irqs); + } + + arch_dovetail_switch_finish(leave_inband); + + /* + * inband_tail is true whenever we are finalizing a transition + * to the inband stage from the oob context for current. See + * above. + */ + return inband_tail; +} +EXPORT_SYMBOL_GPL(dovetail_context_switch); + +#endif /* CONFIG_DOVETAIL */ + void dump_cpu_task(int cpu) { if (cpu == smp_processor_id() && in_hardirq()) { diff --git a/kernel/sched/idle.c b/kernel/sched/idle.c index 565f8374d..6d05de285 100644 --- a/kernel/sched/idle.c +++ b/kernel/sched/idle.c @@ -85,9 +85,14 @@ void __weak arch_cpu_idle(void) * default_idle_call - Default CPU idle routine. * * To use when the cpuidle framework cannot be used. + * + * IRQ pipeline: this call is entered with hard irqs off, in-band + * stage is stalled and its log is empty. Returns unstalled with hard + * irqs on. */ void __cpuidle default_idle_call(void) { + irq_pipeline_idling_checks(); instrumentation_begin(); if (!current_clr_polling_and_test()) { trace_cpu_idle(1, smp_processor_id()); @@ -100,7 +105,7 @@ void __cpuidle default_idle_call(void) start_critical_timings(); trace_cpu_idle(PWR_EVENT_EXIT, smp_processor_id()); } - local_irq_enable(); + local_irq_enable_full(); instrumentation_end(); } @@ -142,6 +147,8 @@ static int call_cpuidle(struct cpuidle_driver *drv, struct cpuidle_device *dev, * On architectures that support TIF_POLLING_NRFLAG, is called with polling * set, and it returns with polling set. If it ever stops polling, it * must clear the polling bit. + * + * IRQ pipeline: we enter this code stalled with hard irqs on. */ static void cpuidle_idle_call(void) { @@ -166,8 +173,10 @@ static void cpuidle_idle_call(void) if (cpuidle_not_available(drv, dev)) { tick_nohz_idle_stop_tick(); - - default_idle_call(); + if (irq_pipeline_can_idle()) + default_idle_call(); + else + local_irq_enable_full(); goto exit_idle; } @@ -222,6 +231,13 @@ static void cpuidle_idle_call(void) exit_idle: __current_set_polling(); + /* + * Catch mishandling of the CPU's interrupt disable flag when + * pipelining IRQs. + */ + if (WARN_ON_ONCE(irq_pipeline_debug() && hard_irqs_disabled())) + hard_local_irq_enable(); + /* * It is up to the idle functions to reenable local interrupts */ @@ -280,6 +296,7 @@ static void do_idle(void) cpu_idle_poll(); } else { cpuidle_idle_call(); + WARN_ON_ONCE(irq_pipeline_debug() && hard_irqs_disabled()); } arch_cpu_idle_exit(); } diff --git a/kernel/sched/sched.h b/kernel/sched/sched.h index d48c6a292..6dda3d7fb 100644 --- a/kernel/sched/sched.h +++ b/kernel/sched/sched.h @@ -48,6 +48,8 @@ #include #include #include +#include +#include #include #include #include diff --git a/kernel/sched/wait.c b/kernel/sched/wait.c index 802d98cf2..90a708cd4 100644 --- a/kernel/sched/wait.c +++ b/kernel/sched/wait.c @@ -84,6 +84,8 @@ static int __wake_up_common(struct wait_queue_head *wq_head, unsigned int mode, wait_queue_entry_t *curr, *next; int cnt = 0; + check_inband_stage(); + lockdep_assert_held(&wq_head->lock); if (bookmark && (bookmark->flags & WQ_FLAG_BOOKMARK)) { diff --git a/kernel/signal.c b/kernel/signal.c index 49c8c24b4..64e287beb 100644 --- a/kernel/signal.c +++ b/kernel/signal.c @@ -773,6 +773,9 @@ void signal_wake_up_state(struct task_struct *t, unsigned int state) set_tsk_thread_flag(t, TIF_SIGPENDING); + /* TIF_SIGPENDING must be set prior to notifying. */ + inband_signal_notify(t); + /* * TASK_WAKEKILL also means wake it up in the stopped/traced/killable * case. We don't check t->state here because there is a race with it @@ -996,8 +999,11 @@ static inline bool wants_signal(int sig, struct task_struct *p) if (sig == SIGKILL) return true; - if (task_is_stopped_or_traced(p)) + if (task_is_stopped_or_traced(p)) { + if (!signal_pending(p)) + inband_signal_notify(p); return false; + } return task_curr(p) || !task_sigpending(p); } @@ -2259,6 +2265,8 @@ static int ptrace_stop(int exit_code, int why, unsigned long message, spin_lock_irq(¤t->sighand->siglock); } + inband_ptstop_notify(); + /* * After this point ptrace_signal_wake_up or signal_wake_up * will clear TASK_TRACED if ptrace_unlink happens or a fatal @@ -2343,6 +2351,8 @@ static int ptrace_stop(int exit_code, int why, unsigned long message, schedule(); cgroup_leave_frozen(true); + inband_ptcont_notify(); + /* * We are back. Now reacquire the siglock before touching * last_siginfo, so that we are sure to have synchronized with diff --git a/kernel/smp.c b/kernel/smp.c index 3eeffeaf5..dcfda3d96 100644 --- a/kernel/smp.c +++ b/kernel/smp.c @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -50,6 +51,8 @@ static DEFINE_PER_CPU(atomic_t, trigger_backtrace) = ATOMIC_INIT(1); static void __flush_smp_call_function_queue(bool warn_cpu_offline); +static void call_function_oob_init(void); + int smpcfd_prepare_cpu(unsigned int cpu) { struct call_function_data *cfd = &per_cpu(cfd_data, cpu); @@ -105,6 +108,8 @@ void __init call_function_init(void) for_each_possible_cpu(i) init_llist_head(&per_cpu(call_single_queue, i)); + call_function_oob_init(); + smpcfd_prepare_cpu(smp_processor_id()); } @@ -1124,3 +1129,142 @@ int smp_call_on_cpu(unsigned int cpu, int (*func)(void *), void *par, bool phys) return sscs.ret; } EXPORT_SYMBOL_GPL(smp_call_on_cpu); + +#ifdef CONFIG_IRQ_PIPELINE + +static DEFINE_PER_CPU_SHARED_ALIGNED(struct llist_head, call_oob_queue); +static DEFINE_PER_CPU_SHARED_ALIGNED(call_single_data_t, csd_oob_data); + +static void __init call_function_oob_init(void) +{ + int n; + + for_each_possible_cpu(n) + init_llist_head(&per_cpu(call_oob_queue, n)); +} + +/* + * Runs the oob callbacks queued by remote CPUs. Hard irqs off, oob + * stage on entry. The implementation was shamelessly lifted from + * __flush_smp_call_function_queue(). + */ +void smp_flush_oob_call_function_queue(void) +{ + call_single_data_t *csd, *csd_next; + struct llist_node *entry, *prev; + struct llist_head *head; + + WARN_ON(irq_pipeline_debug() && (!hard_irqs_disabled() || running_inband())); + + head = raw_cpu_ptr(&call_oob_queue); + if (llist_empty(head)) + return; + + entry = llist_del_all(head); + + /* + * Run all SYNC callbacks first since senders are waiting for + * us. Callbacks are pushed at head, so walk the list in + * reverse order to preserve the enqueuing sequence. + */ + entry = llist_reverse_order(entry); + prev = NULL; + llist_for_each_entry_safe(csd, csd_next, entry, node.llist) { + if (CSD_TYPE(csd) == CSD_TYPE_SYNC) { + smp_call_func_t func = csd->func; + void *info = csd->info; + + if (prev) + prev->next = &csd_next->node.llist; + else + entry = &csd_next->node.llist; + + csd_do_func(func, info, csd); + csd_unlock(csd); + } else { + prev = &csd->node.llist; + } + } + + if (!entry) + return; + + /* Finish with ASYNC calls. */ + prev = NULL; + llist_for_each_entry_safe(csd, csd_next, entry, node.llist) { + if (prev) + prev->next = &csd_next->node.llist; + else + entry = &csd_next->node.llist; + if (CSD_TYPE(csd) == CSD_TYPE_ASYNC) { + smp_call_func_t func = csd->func; + void *info = csd->info; + + csd_unlock(csd); + csd_do_func(func, info, csd); + } + } +} + +/* + * smp_call_function_oob - Run a function on a specific CPU, on the + * out-of-band stage. + * + * @func: The function to run. This must be fast and non-blocking. + * @info: An arbitrary pointer to pass to the function. + * @wait: If true, wait until function has completed on the target CPU. + * + * Hard irqs must be enabled on entry. + * + * Returns 0 on success, else a negative status code. + */ +int smp_call_function_oob(int cpu, smp_call_func_t func, void *info, bool wait) +{ + call_single_data_t csd_stack = { + .node = { .u_flags = CSD_FLAG_LOCK | CSD_TYPE_SYNC }, + }, *csd; + unsigned long flags; + int this_cpu; + + /* + * If hard irqs are off, this call might deadlock if two CPUs + * are waiting for each other to unlock the csd. Make sure to + * detect this. + */ + WARN_ON_ONCE(hard_irqs_disabled()); + + if ((unsigned)cpu >= nr_cpu_ids || !cpu_online(cpu)) + return -ENXIO; + + this_cpu = hard_get_cpu(flags); + if (this_cpu == cpu) { + trace_csd_function_entry(func, NULL); + up_oob_call(func, info); + trace_csd_function_exit(func, NULL); + goto out; + } + + csd = &csd_stack; + if (!wait) { + csd = raw_cpu_ptr(&csd_oob_data); + csd_lock(csd); + } + + csd->func = func; + csd->info = info; + + if (llist_add(&csd->node.llist, &per_cpu(call_oob_queue, cpu))) + irq_send_oob_ipi(CALL_FUNCTION_OOB_IPI, cpumask_of(cpu)); + + if (wait) + csd_lock_wait(csd); +out: + hard_put_cpu(flags); + + return 0; +} +EXPORT_SYMBOL_GPL(smp_call_function_oob); + +#else +static inline void call_function_oob_init(void) { } +#endif diff --git a/kernel/stop_machine.c b/kernel/stop_machine.c index cedb17ba1..e8aee285d 100644 --- a/kernel/stop_machine.c +++ b/kernel/stop_machine.c @@ -232,8 +232,8 @@ static int multi_cpu_stop(void *data) curstate = newstate; switch (curstate) { case MULTI_STOP_DISABLE_IRQ: - local_irq_disable(); hard_irq_disable(); + local_irq_disable(); break; case MULTI_STOP_RUN: if (is_active) @@ -254,6 +254,7 @@ static int multi_cpu_stop(void *data) rcu_momentary_dyntick_idle(); } while (curstate != MULTI_STOP_EXIT); + hard_irq_enable(); local_irq_restore(flags); return err; } @@ -609,6 +610,7 @@ int stop_machine_cpuslocked(cpu_stop_fn_t fn, void *data, local_irq_save(flags); hard_irq_disable(); ret = (*fn)(data); + hard_irq_enable(); local_irq_restore(flags); return ret; diff --git a/kernel/time/Makefile b/kernel/time/Makefile index 7e875e63f..333cf9447 100644 --- a/kernel/time/Makefile +++ b/kernel/time/Makefile @@ -16,6 +16,7 @@ ifeq ($(CONFIG_GENERIC_CLOCKEVENTS_BROADCAST),y) endif obj-$(CONFIG_GENERIC_SCHED_CLOCK) += sched_clock.o obj-$(CONFIG_TICK_ONESHOT) += tick-oneshot.o tick-sched.o +obj-$(CONFIG_IRQ_PIPELINE) += tick-proxy.o obj-$(CONFIG_LEGACY_TIMER_TICK) += tick-legacy.o obj-$(CONFIG_HAVE_GENERIC_VDSO) += vsyscall.o obj-$(CONFIG_DEBUG_FS) += timekeeping_debug.o diff --git a/kernel/time/clockevents.c b/kernel/time/clockevents.c index 960143b18..072f32795 100644 --- a/kernel/time/clockevents.c +++ b/kernel/time/clockevents.c @@ -97,6 +97,7 @@ static int __clockevents_switch_state(struct clock_event_device *dev, /* Transition with new state-specific callbacks */ switch (state) { case CLOCK_EVT_STATE_DETACHED: + case CLOCK_EVT_STATE_RESERVED: /* The clockevent device is getting replaced. Shut it down. */ case CLOCK_EVT_STATE_SHUTDOWN: @@ -436,6 +437,69 @@ int clockevents_unbind_device(struct clock_event_device *ced, int cpu) } EXPORT_SYMBOL_GPL(clockevents_unbind_device); +#ifdef CONFIG_IRQ_PIPELINE + +/** + * clockevents_register_proxy - register a proxy device on the current CPU + * @dev: proxy to register + */ +int clockevents_register_proxy(struct clock_proxy_device *dev) +{ + struct clock_event_device *proxy_dev, *real_dev; + unsigned long flags; + u32 freq; + int ret; + + raw_spin_lock_irqsave(&clockevents_lock, flags); + + ret = tick_setup_proxy(dev); + if (ret) { + raw_spin_unlock_irqrestore(&clockevents_lock, flags); + return ret; + } + + proxy_dev = &dev->proxy_device; + clockevent_set_state(proxy_dev, CLOCK_EVT_STATE_DETACHED); + + list_add(&proxy_dev->list, &clockevent_devices); + tick_check_new_device(proxy_dev); + clockevents_notify_released(); + + raw_spin_unlock_irqrestore(&clockevents_lock, flags); + + real_dev = dev->real_device; + freq = (1000000000ULL * real_dev->mult) >> real_dev->shift; + printk(KERN_INFO "CPU%d: proxy tick device registered (%u.%02uMHz)\n", + smp_processor_id(), freq / 1000000, (freq / 10000) % 100); + + return ret; +} + +void clockevents_unregister_proxy(struct clock_proxy_device *dev) +{ + unsigned long flags; + int ret; + + clockevents_register_device(dev->real_device); + clockevents_switch_state(dev->real_device, CLOCK_EVT_STATE_DETACHED); + + /* + * Pop the proxy device, do not give it back to the + * framework. + */ + raw_spin_lock_irqsave(&clockevents_lock, flags); + ret = clockevents_replace(&dev->proxy_device); + raw_spin_unlock_irqrestore(&clockevents_lock, flags); + + if (WARN_ON(ret)) + return; + + printk(KERN_INFO "CPU%d: proxy tick device unregistered\n", + smp_processor_id()); +} + +#endif + /** * clockevents_register_device - register a clock event device * @dev: device to register @@ -574,8 +638,18 @@ void clockevents_exchange_device(struct clock_event_device *old, */ if (old) { module_put(old->owner); - clockevents_switch_state(old, CLOCK_EVT_STATE_DETACHED); - list_move(&old->list, &clockevents_released); + /* + * Do not move the device backing a proxy tick device + * to the release list, keep it around but mark it as + * reserved. + */ + if (tick_check_is_proxy(new)) { + list_del(&old->list); + clockevents_switch_state(old, CLOCK_EVT_STATE_RESERVED); + } else { + clockevents_switch_state(old, CLOCK_EVT_STATE_DETACHED); + list_move(&old->list, &clockevents_released); + } } if (new) { diff --git a/kernel/time/clocksource.c b/kernel/time/clocksource.c index aa864999d..c4cc7afb3 100644 --- a/kernel/time/clocksource.c +++ b/kernel/time/clocksource.c @@ -1186,8 +1186,8 @@ void __clocksource_update_freq_scale(struct clocksource *cs, u32 scale, u32 freq clocksource_update_max_deferment(cs); - pr_info("%s: mask: 0x%llx max_cycles: 0x%llx, max_idle_ns: %lld ns\n", - cs->name, cs->mask, cs->max_cycles, cs->max_idle_ns); + pr_info("%s: freq: %Lu Hz, mask: 0x%llx max_cycles: 0x%llx, max_idle_ns: %lld ns\n", + cs->name, (u64)freq * scale, cs->mask, cs->max_cycles, cs->max_idle_ns); } EXPORT_SYMBOL_GPL(__clocksource_update_freq_scale); @@ -1456,10 +1456,36 @@ static ssize_t available_clocksource_show(struct device *dev, } static DEVICE_ATTR_RO(available_clocksource); +/** + * vdso_clocksource_show - sysfs interface for vDSO type of + * current clocksource + * @dev: unused + * @attr: unused + * @buf: char buffer to be filled with vDSO type + */ +static ssize_t vdso_clocksource_show(struct device *dev, + struct device_attribute *attr, + char *buf) +{ + ssize_t count = 0, type; + + mutex_lock(&clocksource_mutex); + type = curr_clocksource->vdso_type; + count = snprintf(buf, PAGE_SIZE, "%s\n", + type == CLOCKSOURCE_VDSO_NONE ? "none" : + type == CLOCKSOURCE_VDSO_ARCHITECTED ? "architected" : + "mmio"); + mutex_unlock(&clocksource_mutex); + + return count; +} +static DEVICE_ATTR_RO(vdso_clocksource); + static struct attribute *clocksource_attrs[] = { &dev_attr_current_clocksource.attr, &dev_attr_unbind_clocksource.attr, &dev_attr_available_clocksource.attr, + &dev_attr_vdso_clocksource.attr, NULL }; ATTRIBUTE_GROUPS(clocksource); diff --git a/kernel/time/hrtimer.c b/kernel/time/hrtimer.c index e99b1305e..fff170ab6 100644 --- a/kernel/time/hrtimer.c +++ b/kernel/time/hrtimer.c @@ -981,6 +981,7 @@ void clock_was_set(unsigned int bases) out_timerfd: timerfd_clock_was_set(); + inband_clock_was_set(); } static void clock_was_set_work(struct work_struct *work) diff --git a/kernel/time/tick-broadcast.c b/kernel/time/tick-broadcast.c index ed58eebb4..1d6bc4c73 100644 --- a/kernel/time/tick-broadcast.c +++ b/kernel/time/tick-broadcast.c @@ -801,6 +801,14 @@ static int ___tick_broadcast_oneshot_control(enum tick_broadcast_state state, int ret = 0; ktime_t now; + /* + * If proxying the hardware timer for high-precision tick + * delivery to the out-of-band stage, the whole broadcast + * dance is a no-go. Deny entering deep idle. + */ + if (dev->features & CLOCK_EVT_FEAT_PROXY) + return -EBUSY; + raw_spin_lock(&tick_broadcast_lock); bc = tick_broadcast_device.evtdev; diff --git a/kernel/time/tick-common.c b/kernel/time/tick-common.c index 7f2b17fc8..4928e5963 100644 --- a/kernel/time/tick-common.c +++ b/kernel/time/tick-common.c @@ -231,7 +231,8 @@ static void tick_setup_device(struct tick_device *td, } else { handler = td->evtdev->event_handler; next_event = td->evtdev->next_event; - td->evtdev->event_handler = clockevents_handle_noop; + if (!clockevent_state_reserved(td->evtdev)) + td->evtdev->event_handler = clockevents_handle_noop; } td->evtdev = newdev; @@ -313,6 +314,12 @@ static bool tick_check_preferred(struct clock_event_device *curdev, bool tick_check_replacement(struct clock_event_device *curdev, struct clock_event_device *newdev) { + /* + * Never replace an active proxy except when unregistering it. + */ + if (tick_check_is_proxy(curdev)) + return false; + if (!tick_check_percpu(curdev, newdev, smp_processor_id())) return false; @@ -333,6 +340,9 @@ void tick_check_new_device(struct clock_event_device *newdev) td = &per_cpu(tick_cpu_device, cpu); curdev = td->evtdev; + if (tick_check_is_proxy(curdev)) + goto out_bc; + if (!tick_check_replacement(curdev, newdev)) goto out_bc; @@ -345,7 +355,12 @@ void tick_check_new_device(struct clock_event_device *newdev) * not give it back to the clockevents layer ! */ if (tick_is_broadcast_device(curdev)) { - clockevents_shutdown(curdev); + if (tick_check_is_proxy(newdev)) { + list_del(&curdev->list); + clockevents_switch_state(curdev, CLOCK_EVT_STATE_RESERVED); + } else { + clockevents_shutdown(curdev); + } curdev = NULL; } clockevents_exchange_device(curdev, newdev); diff --git a/kernel/time/tick-internal.h b/kernel/time/tick-internal.h index 649f2b48e..85d8451df 100644 --- a/kernel/time/tick-internal.h +++ b/kernel/time/tick-internal.h @@ -47,15 +47,26 @@ static inline void clockevent_set_state(struct clock_event_device *dev, dev->state_use_accessors = state; } +static inline bool tick_check_is_proxy(struct clock_event_device *dev) +{ + if (!irqs_pipelined()) + return false; + + return dev && dev->features & CLOCK_EVT_FEAT_PROXY; +} + extern void clockevents_shutdown(struct clock_event_device *dev); extern void clockevents_exchange_device(struct clock_event_device *old, struct clock_event_device *new); -extern void clockevents_switch_state(struct clock_event_device *dev, - enum clock_event_state state); extern int clockevents_program_event(struct clock_event_device *dev, ktime_t expires, bool force); extern void clockevents_handle_noop(struct clock_event_device *dev); extern int __clockevents_update_freq(struct clock_event_device *dev, u32 freq); +#ifdef CONFIG_IRQ_PIPELINE +int clockevents_register_proxy(struct clock_proxy_device *dev); +extern void clockevents_unregister_proxy(struct clock_proxy_device *dev); +int tick_setup_proxy(struct clock_proxy_device *dev); +#endif extern ssize_t sysfs_get_uname(const char *buf, char *dst, size_t cnt); /* Broadcasting support */ diff --git a/kernel/time/tick-proxy.c b/kernel/time/tick-proxy.c new file mode 100644 index 000000000..5fc50cdb2 --- /dev/null +++ b/kernel/time/tick-proxy.c @@ -0,0 +1,466 @@ +/* + * SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2017 Philippe Gerum . + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "tick-internal.h" + +static unsigned int proxy_tick_irq; + +static DEFINE_MUTEX(proxy_mutex); + +static DEFINE_PER_CPU(struct clock_proxy_device, proxy_tick_device); + +static inline struct clock_event_device * +get_real_tick_device(struct clock_event_device *proxy_dev) +{ + return container_of(proxy_dev, struct clock_proxy_device, proxy_device)->real_device; +} + +static void proxy_event_handler(struct clock_event_device *real_dev) +{ + struct clock_proxy_device *dev = raw_cpu_ptr(&proxy_tick_device); + struct clock_event_device *proxy_dev = &dev->proxy_device; + + proxy_dev->event_handler(proxy_dev); +} + +static int proxy_set_state_oneshot(struct clock_event_device *dev) +{ + struct clock_event_device *real_dev = get_real_tick_device(dev); + unsigned long flags; + int ret; + + flags = hard_local_irq_save(); + ret = real_dev->set_state_oneshot(real_dev); + hard_local_irq_restore(flags); + + return ret; +} + +static int proxy_set_state_periodic(struct clock_event_device *dev) +{ + struct clock_event_device *real_dev = get_real_tick_device(dev); + unsigned long flags; + int ret; + + flags = hard_local_irq_save(); + ret = real_dev->set_state_periodic(real_dev); + hard_local_irq_restore(flags); + + return ret; +} + +static int proxy_set_state_oneshot_stopped(struct clock_event_device *dev) +{ + struct clock_event_device *real_dev = get_real_tick_device(dev); + unsigned long flags; + int ret; + + flags = hard_local_irq_save(); + ret = real_dev->set_state_oneshot_stopped(real_dev); + hard_local_irq_restore(flags); + + return ret; +} + +static int proxy_set_state_shutdown(struct clock_event_device *dev) +{ + struct clock_event_device *real_dev = get_real_tick_device(dev); + unsigned long flags; + int ret; + + flags = hard_local_irq_save(); + ret = real_dev->set_state_shutdown(real_dev); + hard_local_irq_restore(flags); + + return ret; +} + +static void proxy_suspend(struct clock_event_device *dev) +{ + struct clock_event_device *real_dev = get_real_tick_device(dev); + unsigned long flags; + + flags = hard_local_irq_save(); + real_dev->suspend(real_dev); + hard_local_irq_restore(flags); +} + +static void proxy_resume(struct clock_event_device *dev) +{ + struct clock_event_device *real_dev = get_real_tick_device(dev); + unsigned long flags; + + flags = hard_local_irq_save(); + real_dev->resume(real_dev); + hard_local_irq_restore(flags); +} + +static int proxy_tick_resume(struct clock_event_device *dev) +{ + struct clock_event_device *real_dev = get_real_tick_device(dev); + unsigned long flags; + int ret; + + flags = hard_local_irq_save(); + ret = real_dev->tick_resume(real_dev); + hard_local_irq_restore(flags); + + return ret; +} + +static void proxy_broadcast(const struct cpumask *mask) +{ + struct clock_proxy_device *dev = raw_cpu_ptr(&proxy_tick_device); + struct clock_event_device *real_dev = dev->real_device; + unsigned long flags; + + flags = hard_local_irq_save(); + real_dev->broadcast(mask); + hard_local_irq_restore(flags); +} + +static int proxy_set_next_event(unsigned long delay, + struct clock_event_device *dev) +{ + struct clock_event_device *real_dev = get_real_tick_device(dev); + unsigned long flags; + int ret; + + flags = hard_local_irq_save(); + ret = real_dev->set_next_event(delay, real_dev); + hard_local_irq_restore(flags); + + return ret; +} + +static int proxy_set_next_ktime(ktime_t expires, + struct clock_event_device *dev) +{ + struct clock_event_device *real_dev = get_real_tick_device(dev); + unsigned long flags; + int ret; + + flags = hard_local_irq_save(); + ret = real_dev->set_next_ktime(expires, real_dev); + hard_local_irq_restore(flags); + + return ret; +} + +static irqreturn_t proxy_irq_handler(int sirq, void *dev_id) +{ + struct clock_event_device *evt; + + /* + * Tricky: we may end up running this in-band IRQ handler + * because tick_notify_proxy() was posted either: + * + * - from the out-of-band stage via ->handle_oob_event() for + * emulating an in-band tick. In this case, the active tick + * device for the in-band timing core is the proxy device, + * whose event handler is still the same than the real tick + * device's. + * + * - directly by the clock chip driver on the local CPU via + * clockevents_handle_event(), for propagating a tick to the + * in-band stage nobody from the out-of-band stage is + * interested on i.e. no proxy device was registered on the + * receiving CPU, which was excluded from @cpumask in the call + * to tick_install_proxy(). In this case, the active tick + * device for the in-band timing core is a real clock event + * device. + * + * In both cases, we are running on the in-band stage, and we + * should fire the event handler of the currently active tick + * device for the in-band timing core. + */ + evt = raw_cpu_ptr(&tick_cpu_device)->evtdev; + evt->event_handler(evt); + + return IRQ_HANDLED; +} + +#define interpose_proxy_handler(__proxy, __real, __h) \ + do { \ + if ((__real)->__h) \ + (__proxy)->__h = proxy_ ## __h; \ + } while (0) + +/* + * Setup a proxy which is about to override the tick device on the + * current CPU. Called with clockevents_lock held and irqs off so that + * the tick device does not change under our feet. + */ +int tick_setup_proxy(struct clock_proxy_device *dev) +{ + struct clock_event_device *proxy_dev, *real_dev; + + real_dev = raw_cpu_ptr(&tick_cpu_device)->evtdev; + if ((real_dev->features & + (CLOCK_EVT_FEAT_PIPELINE|CLOCK_EVT_FEAT_ONESHOT)) + != (CLOCK_EVT_FEAT_PIPELINE|CLOCK_EVT_FEAT_ONESHOT)) { + WARN(1, "cannot use clockevent device %s in proxy mode!", + real_dev->name); + return -ENODEV; + } + + /* + * The assumption is that neither us nor clockevents_register_proxy() + * can fail afterwards, so this is ok to advertise the new proxy as + * built by setting dev->real_device early. + */ + dev->real_device = real_dev; + dev->__original_handler = real_dev->event_handler; + + /* + * Inherit the feature bits since the proxy device has the + * same capabilities than the real one we are overriding + * (including CLOCK_EVT_FEAT_C3STOP if present). + */ + proxy_dev = &dev->proxy_device; + memset(proxy_dev, 0, sizeof(*proxy_dev)); + proxy_dev->features = real_dev->features | + CLOCK_EVT_FEAT_PERCPU | CLOCK_EVT_FEAT_PROXY; + proxy_dev->name = "proxy"; + proxy_dev->irq = real_dev->irq; + proxy_dev->bound_on = -1; + proxy_dev->cpumask = cpumask_of(smp_processor_id()); + proxy_dev->rating = real_dev->rating + 1; + proxy_dev->mult = real_dev->mult; + proxy_dev->shift = real_dev->shift; + proxy_dev->max_delta_ticks = real_dev->max_delta_ticks; + proxy_dev->min_delta_ticks = real_dev->min_delta_ticks; + proxy_dev->max_delta_ns = real_dev->max_delta_ns; + proxy_dev->min_delta_ns = real_dev->min_delta_ns; + /* + * Interpose default handlers which are safe wrt preemption by + * the out-of-band stage. + */ + interpose_proxy_handler(proxy_dev, real_dev, set_state_oneshot); + interpose_proxy_handler(proxy_dev, real_dev, set_state_oneshot_stopped); + interpose_proxy_handler(proxy_dev, real_dev, set_state_periodic); + interpose_proxy_handler(proxy_dev, real_dev, set_state_shutdown); + interpose_proxy_handler(proxy_dev, real_dev, suspend); + interpose_proxy_handler(proxy_dev, real_dev, resume); + interpose_proxy_handler(proxy_dev, real_dev, tick_resume); + interpose_proxy_handler(proxy_dev, real_dev, broadcast); + interpose_proxy_handler(proxy_dev, real_dev, set_next_event); + interpose_proxy_handler(proxy_dev, real_dev, set_next_ktime); + + dev->__setup_handler(dev); + + return 0; +} + +static int enable_oob_timer(void *arg) /* hard_irqs_disabled() */ +{ + struct clock_proxy_device *dev = raw_cpu_ptr(&proxy_tick_device); + struct clock_event_device *real_dev; + + /* + * Install the out-of-band handler on this CPU's real clock + * device, then turn on out-of-band mode for the associated + * IRQ (duplicates are silently ignored if the IRQ is common + * to multiple CPUs). + */ + real_dev = dev->real_device; + real_dev->event_handler = dev->handle_oob_event; + real_dev->features |= CLOCK_EVT_FEAT_OOB; + barrier(); + + /* + * irq_switch_oob() grabs the IRQ descriptor lock which is + * hybrid, so that is fine to invoke this routine with hard + * IRQs off. + */ + irq_switch_oob(real_dev->irq, true); + + return 0; +} + +struct proxy_install_arg { + void (*setup_proxy)(struct clock_proxy_device *dev); + int result; +}; + +static void register_proxy_device(void *arg) /* irqs_disabled() */ +{ + struct clock_proxy_device *dev = raw_cpu_ptr(&proxy_tick_device); + struct proxy_install_arg *req = arg; + int ret; + + dev->__setup_handler = req->setup_proxy; + ret = clockevents_register_proxy(dev); + if (ret) { + if (!req->result) + req->result = ret; + } else { + dev->real_device->event_handler = proxy_event_handler; + } +} + +int tick_install_proxy(void (*setup_proxy)(struct clock_proxy_device *dev), + const struct cpumask *cpumask) +{ + struct proxy_install_arg arg; + int ret, sirq; + + mutex_lock(&proxy_mutex); + + ret = -EAGAIN; + if (proxy_tick_irq) + goto out; + + sirq = irq_create_direct_mapping(synthetic_irq_domain); + if (WARN_ON(sirq == 0)) + goto out; + + ret = __request_percpu_irq(sirq, proxy_irq_handler, + IRQF_NO_THREAD, /* no IRQF_TIMER here. */ + "proxy tick", + &proxy_tick_device); + if (WARN_ON(ret)) { + irq_dispose_mapping(sirq); + goto out; + } + + proxy_tick_irq = sirq; + barrier(); + + /* + * Install a proxy tick device on each CPU. As the proxy + * device is picked, the previous (real) tick device is + * switched to reserved state by the clockevent core. + * Immediately after, the proxy device starts controlling the + * real device under the hood to carry out the timing requests + * it receives. + * + * For a short period of time, after the proxy device is + * installed, and until the real device IRQ is switched to + * out-of-band mode, the flow is as follows: + * + * [inband timing request] + * proxy_dev->set_next_event(proxy_dev) + * oob_program_event(proxy_dev) + * real_dev->set_next_event(real_dev) + * ... + * + * original_timer_handler() [in-band stage] + * clockevents_handle_event(real_dev) + * proxy_event_handler(real_dev) + * inband_event_handler(proxy_dev) + * + * Eventually, we substitute the original (in-band) clock + * event handler with the out-of-band handler for the real + * clock event device, then turn on out-of-band mode for the + * timer IRQ associated to the latter. These two steps are + * performed over a stop_machine() context, so that no tick + * can race with this code while we swap handlers. + * + * Once the hand over is complete, the flow is as follows: + * + * [inband timing request] + * proxy_dev->set_next_event(proxy_dev) + * oob_program_event(proxy_dev) + * real_dev->set_next_event(real_dev) + * ... + * + * inband_event_handler() [out-of-band stage] + * clockevents_handle_event(real_dev) + * handle_oob_event(proxy_dev) + * ...(inband tick emulation)... + * tick_notify_proxy() + * ... + * proxy_irq_handler(proxy_dev) [in-band stage] + * clockevents_handle_event(proxy_dev) + * inband_event_handler(proxy_dev) + */ + arg.setup_proxy = setup_proxy; + arg.result = 0; + on_each_cpu_mask(cpumask, register_proxy_device, &arg, true); + if (arg.result) { + tick_uninstall_proxy(cpumask); + return arg.result; + } + + /* + * Start ticking from the out-of-band interrupt stage upon + * receipt of out-of-band timer events. + */ + stop_machine(enable_oob_timer, NULL, cpumask); +out: + mutex_unlock(&proxy_mutex); + + return ret; +} +EXPORT_SYMBOL_GPL(tick_install_proxy); + +static int disable_oob_timer(void *arg) /* hard_irqs_disabled() */ +{ + struct clock_proxy_device *dev = raw_cpu_ptr(&proxy_tick_device); + struct clock_event_device *real_dev; + + dev = raw_cpu_ptr(&proxy_tick_device); + real_dev = dev->real_device; + real_dev->event_handler = dev->__original_handler; + real_dev->features &= ~CLOCK_EVT_FEAT_OOB; + barrier(); + + irq_switch_oob(real_dev->irq, false); + + return 0; +} + +static void unregister_proxy_device(void *arg) /* irqs_disabled() */ +{ + struct clock_proxy_device *dev = raw_cpu_ptr(&proxy_tick_device); + + if (dev->real_device) { + clockevents_unregister_proxy(dev); + dev->real_device = NULL; + } +} + +void tick_uninstall_proxy(const struct cpumask *cpumask) +{ + /* + * Undo all we did in tick_install_proxy(), handing over + * control of the tick device back to the inband code. + */ + mutex_lock(&proxy_mutex); + stop_machine(disable_oob_timer, NULL, cpu_online_mask); + on_each_cpu_mask(cpumask, unregister_proxy_device, NULL, true); + free_percpu_irq(proxy_tick_irq, &proxy_tick_device); + irq_dispose_mapping(proxy_tick_irq); + proxy_tick_irq = 0; + mutex_unlock(&proxy_mutex); +} +EXPORT_SYMBOL_GPL(tick_uninstall_proxy); + +void tick_notify_proxy(void) +{ + /* + * Schedule a tick on the proxy device to occur from the + * in-band stage, which will trigger proxy_irq_handler() at + * some point (i.e. when the in-band stage is back in control + * and not stalled). Note that we might be called from the + * in-band stage in some cases (see proxy_irq_handler()). + */ + irq_post_inband(proxy_tick_irq); +} +EXPORT_SYMBOL_GPL(tick_notify_proxy); diff --git a/kernel/time/vsyscall.c b/kernel/time/vsyscall.c index f0d5062d9..dc366fdf4 100644 --- a/kernel/time/vsyscall.c +++ b/kernel/time/vsyscall.c @@ -69,16 +69,42 @@ static inline void update_vdso_data(struct vdso_data *vdata, vdso_ts->nsec = tk->tkr_mono.xtime_nsec; } +static void update_generic_mmio(struct vdso_data *vdata, struct timekeeper *tk) +{ +#ifdef CONFIG_GENERIC_CLOCKSOURCE_VDSO + const struct clocksource *cs = tk->tkr_mono.clock; + u16 seq; + + if (cs->vdso_type == (vdata->cs_type_seq >> 16)) + return; + + seq = vdata->cs_type_seq; + if (++seq == 0) + seq = 1; + + vdata->cs_type_seq = cs->vdso_type << 16 | seq; + + if (cs->vdso_type >= CLOCKSOURCE_VDSO_MMIO) + snprintf(vdata->cs_mmdev, sizeof(vdata->cs_mmdev), + "/dev/ucs/%u", cs->vdso_type - CLOCKSOURCE_VDSO_MMIO); +#endif +} + void update_vsyscall(struct timekeeper *tk) { struct vdso_data *vdata = __arch_get_k_vdso_data(); struct vdso_timestamp *vdso_ts; + unsigned long flags; s32 clock_mode; u64 nsec; + flags = hard_cond_local_irq_save(); + /* copy vsyscall data */ vdso_write_begin(vdata); + update_generic_mmio(vdata, tk); + clock_mode = tk->tkr_mono.clock->vdso_clock_mode; vdata[CS_HRES_COARSE].clock_mode = clock_mode; vdata[CS_RAW].clock_mode = clock_mode; @@ -110,13 +136,16 @@ void update_vsyscall(struct timekeeper *tk) * If the current clocksource is not VDSO capable, then spare the * update of the high resolution parts. */ - if (clock_mode != VDSO_CLOCKMODE_NONE) + if (IS_ENABLED(CONFIG_GENERIC_CLOCKSOURCE_VDSO) || + clock_mode != VDSO_CLOCKMODE_NONE) update_vdso_data(vdata, tk); __arch_update_vsyscall(vdata, tk); vdso_write_end(vdata); + hard_cond_local_irq_restore(flags); + __arch_sync_vdso_data(vdata); } diff --git a/kernel/trace/ftrace.c b/kernel/trace/ftrace.c index 1043936b3..4d2417d12 100644 --- a/kernel/trace/ftrace.c +++ b/kernel/trace/ftrace.c @@ -6585,10 +6585,10 @@ static int ftrace_process_locs(struct module *mod, * reason to cause large interrupt latencies while we do it. */ if (!mod) - local_irq_save(flags); + flags = hard_local_irq_save(); ftrace_update_code(mod, start_pg); if (!mod) - local_irq_restore(flags); + hard_local_irq_restore(flags); ret = 0; out: mutex_unlock(&ftrace_lock); @@ -7236,9 +7236,9 @@ void __init ftrace_init(void) unsigned long count, flags; int ret; - local_irq_save(flags); + flags = hard_local_irq_save(); ret = ftrace_dyn_arch_init(); - local_irq_restore(flags); + hard_local_irq_restore(flags); if (ret) goto failed; diff --git a/kernel/trace/ring_buffer.c b/kernel/trace/ring_buffer.c index 61caff3d4..3ed4a14c6 100644 --- a/kernel/trace/ring_buffer.c +++ b/kernel/trace/ring_buffer.c @@ -3291,9 +3291,14 @@ trace_recursive_lock(struct ring_buffer_per_cpu *cpu_buffer) { unsigned int val = cpu_buffer->current_context; int bit = interrupt_context_level(); + unsigned long flags; bit = RB_CTX_NORMAL - bit; + flags = hard_cond_local_irq_save(); + + val = cpu_buffer->current_context; + if (unlikely(val & (1 << (bit + cpu_buffer->nest)))) { /* * It is possible that this was called by transitioning @@ -3303,6 +3308,7 @@ trace_recursive_lock(struct ring_buffer_per_cpu *cpu_buffer) bit = RB_CTX_TRANSITION; if (val & (1 << (bit + cpu_buffer->nest))) { do_ring_buffer_record_recursion(); + hard_cond_local_irq_restore(flags); return true; } } @@ -3310,14 +3316,20 @@ trace_recursive_lock(struct ring_buffer_per_cpu *cpu_buffer) val |= (1 << (bit + cpu_buffer->nest)); cpu_buffer->current_context = val; + hard_cond_local_irq_restore(flags); + return false; } static __always_inline void trace_recursive_unlock(struct ring_buffer_per_cpu *cpu_buffer) { + unsigned long flags; + + flags = hard_cond_local_irq_save(); cpu_buffer->current_context &= cpu_buffer->current_context - (1 << cpu_buffer->nest); + hard_cond_local_irq_restore(flags); } /* The recursive locking above uses 5 bits */ diff --git a/kernel/trace/trace.c b/kernel/trace/trace.c index 9d9af60b2..e93ec0c2b 100644 --- a/kernel/trace/trace.c +++ b/kernel/trace/trace.c @@ -1175,9 +1175,9 @@ static void tracing_snapshot_instance_cond(struct trace_array *tr, return; } - local_irq_save(flags); + flags = hard_local_irq_save(); update_max_tr(tr, current, smp_processor_id(), cond_data); - local_irq_restore(flags); + hard_local_irq_restore(flags); } void tracing_snapshot_instance(struct trace_array *tr) @@ -1867,7 +1867,7 @@ update_max_tr(struct trace_array *tr, struct task_struct *tsk, int cpu, if (tr->stop_count) return; - WARN_ON_ONCE(!irqs_disabled()); + WARN_ON_ONCE(!hard_irqs_disabled()); if (!tr->allocated_snapshot) { /* Only the nop tracer should hit this when disabling */ @@ -1915,7 +1915,7 @@ update_max_tr_single(struct trace_array *tr, struct task_struct *tsk, int cpu) if (tr->stop_count) return; - WARN_ON_ONCE(!irqs_disabled()); + WARN_ON_ONCE(!hard_irqs_disabled()); if (!tr->allocated_snapshot) { /* Only the nop tracer should hit this when disabling */ WARN_ON_ONCE(tr->current_trace != &nop_trace); @@ -2695,7 +2695,7 @@ unsigned int tracing_gen_ctx_irq_test(unsigned int irqs_status) pc = preempt_count(); - if (pc & NMI_MASK) + if (pc & (NMI_MASK|STAGE_MASK)) trace_flags |= TRACE_FLAG_NMI; if (pc & HARDIRQ_MASK) trace_flags |= TRACE_FLAG_HARDIRQ; @@ -2703,6 +2703,8 @@ unsigned int tracing_gen_ctx_irq_test(unsigned int irqs_status) trace_flags |= TRACE_FLAG_SOFTIRQ; if (softirq_count() >> (SOFTIRQ_SHIFT + 1)) trace_flags |= TRACE_FLAG_BH_OFF; + if (irqs_pipelined() && hard_irqs_disabled()) + trace_flags |= TRACE_FLAG_IRQS_HARDOFF; if (tif_need_resched()) trace_flags |= TRACE_FLAG_NEED_RESCHED; @@ -7529,7 +7531,9 @@ static int tracing_snapshot_open(struct inode *inode, struct file *file) static void tracing_swap_cpu_buffer(void *tr) { + hard_local_irq_disable(); update_max_tr_single((struct trace_array *)tr, current, smp_processor_id()); + hard_local_irq_enable(); } static ssize_t @@ -7592,12 +7596,12 @@ tracing_snapshot_write(struct file *filp, const char __user *ubuf, size_t cnt, break; /* Now, we're going to swap */ if (iter->cpu_file == RING_BUFFER_ALL_CPUS) { - local_irq_disable(); + hard_local_irq_disable(); update_max_tr(tr, current, smp_processor_id(), NULL); - local_irq_enable(); + hard_local_irq_enable(); } else { smp_call_function_single(iter->cpu_file, tracing_swap_cpu_buffer, - (void *)tr, 1); + (void *)tr, 1); } break; default: diff --git a/kernel/trace/trace_branch.c b/kernel/trace/trace_branch.c index e47fdb4c9..9cbf973c1 100644 --- a/kernel/trace/trace_branch.c +++ b/kernel/trace/trace_branch.c @@ -53,7 +53,7 @@ probe_likely_condition(struct ftrace_likely_data *f, int val, int expect) if (unlikely(!tr)) return; - raw_local_irq_save(flags); + flags = hard_local_irq_save(); current->trace_recursion |= TRACE_BRANCH_BIT; data = this_cpu_ptr(tr->array_buffer.data); if (atomic_read(&data->disabled)) @@ -87,7 +87,7 @@ probe_likely_condition(struct ftrace_likely_data *f, int val, int expect) out: current->trace_recursion &= ~TRACE_BRANCH_BIT; - raw_local_irq_restore(flags); + hard_local_irq_restore(flags); } static inline diff --git a/kernel/trace/trace_clock.c b/kernel/trace/trace_clock.c index 4cb2ebc43..c39f60fa8 100644 --- a/kernel/trace/trace_clock.c +++ b/kernel/trace/trace_clock.c @@ -97,7 +97,7 @@ u64 notrace trace_clock_global(void) int this_cpu; u64 now, prev_time; - raw_local_irq_save(flags); + flags = hard_local_irq_save(); this_cpu = raw_smp_processor_id(); @@ -139,7 +139,7 @@ u64 notrace trace_clock_global(void) arch_spin_unlock(&trace_clock_struct.lock); } out: - raw_local_irq_restore(flags); + hard_local_irq_restore(flags); return now; } diff --git a/kernel/trace/trace_functions.c b/kernel/trace/trace_functions.c index 9f1bfbe10..030c751f4 100644 --- a/kernel/trace/trace_functions.c +++ b/kernel/trace/trace_functions.c @@ -231,7 +231,7 @@ function_stack_trace_call(unsigned long ip, unsigned long parent_ip, * Need to use raw, since this must be called before the * recursive protection is performed. */ - local_irq_save(flags); + flags = hard_local_irq_save(); cpu = raw_smp_processor_id(); data = per_cpu_ptr(tr->array_buffer.data, cpu); disabled = atomic_inc_return(&data->disabled); @@ -243,7 +243,7 @@ function_stack_trace_call(unsigned long ip, unsigned long parent_ip, } atomic_dec(&data->disabled); - local_irq_restore(flags); + hard_local_irq_restore(flags); } static inline bool is_repeat_check(struct trace_array *tr, @@ -342,7 +342,7 @@ function_stack_no_repeats_trace_call(unsigned long ip, unsigned long parent_ip, * Need to use raw, since this must be called before the * recursive protection is performed. */ - local_irq_save(flags); + flags = hard_local_irq_save(); cpu = raw_smp_processor_id(); data = per_cpu_ptr(tr->array_buffer.data, cpu); disabled = atomic_inc_return(&data->disabled); @@ -361,7 +361,7 @@ function_stack_no_repeats_trace_call(unsigned long ip, unsigned long parent_ip, out: atomic_dec(&data->disabled); - local_irq_restore(flags); + hard_local_irq_restore(flags); } static struct tracer_opt func_opts[] = { diff --git a/kernel/trace/trace_functions_graph.c b/kernel/trace/trace_functions_graph.c index c35fbaab2..58ac8fce6 100644 --- a/kernel/trace/trace_functions_graph.c +++ b/kernel/trace/trace_functions_graph.c @@ -174,7 +174,7 @@ int trace_graph_entry(struct ftrace_graph_ent *trace) if (tracing_thresh) return 1; - local_irq_save(flags); + flags = hard_local_irq_save(); cpu = raw_smp_processor_id(); data = per_cpu_ptr(tr->array_buffer.data, cpu); disabled = atomic_inc_return(&data->disabled); @@ -186,7 +186,7 @@ int trace_graph_entry(struct ftrace_graph_ent *trace) } atomic_dec(&data->disabled); - local_irq_restore(flags); + hard_local_irq_restore(flags); return ret; } @@ -254,7 +254,7 @@ void trace_graph_return(struct ftrace_graph_ret *trace) return; } - local_irq_save(flags); + flags = hard_local_irq_save(); cpu = raw_smp_processor_id(); data = per_cpu_ptr(tr->array_buffer.data, cpu); disabled = atomic_inc_return(&data->disabled); @@ -263,7 +263,7 @@ void trace_graph_return(struct ftrace_graph_ret *trace) __trace_graph_return(tr, trace, trace_ctx); } atomic_dec(&data->disabled); - local_irq_restore(flags); + hard_local_irq_restore(flags); } void set_graph_array(struct trace_array *tr) diff --git a/kernel/trace/trace_irqsoff.c b/kernel/trace/trace_irqsoff.c index ba37f768e..cfe745786 100644 --- a/kernel/trace/trace_irqsoff.c +++ b/kernel/trace/trace_irqsoff.c @@ -14,6 +14,7 @@ #include #include #include +#include #include #include "trace.h" @@ -26,7 +27,7 @@ static int tracer_enabled __read_mostly; static DEFINE_PER_CPU(int, tracing_cpu); -static DEFINE_RAW_SPINLOCK(max_trace_lock); +static DEFINE_HARD_SPINLOCK(max_trace_lock); enum { TRACER_IRQS_OFF = (1 << 1), @@ -44,7 +45,7 @@ static int start_irqsoff_tracer(struct trace_array *tr, int graph); static inline int preempt_trace(int pc) { - return ((trace_type & TRACER_PREEMPT_OFF) && pc); + return (running_inband() && (trace_type & TRACER_PREEMPT_OFF) && pc); } #else # define preempt_trace(pc) (0) @@ -55,7 +56,7 @@ static inline int irq_trace(void) { return ((trace_type & TRACER_IRQS_OFF) && - irqs_disabled()); + (hard_irqs_disabled() || (running_inband() && irqs_disabled()))); } #else # define irq_trace() (0) diff --git a/kernel/trace/trace_output.c b/kernel/trace/trace_output.c index 2b948d35f..0cb22f118 100644 --- a/kernel/trace/trace_output.c +++ b/kernel/trace/trace_output.c @@ -454,18 +454,22 @@ int trace_print_lat_fmt(struct trace_seq *s, struct trace_entry *entry) int softirq; int bh_off; int nmi; + int none; nmi = entry->flags & TRACE_FLAG_NMI; hardirq = entry->flags & TRACE_FLAG_HARDIRQ; softirq = entry->flags & TRACE_FLAG_SOFTIRQ; bh_off = entry->flags & TRACE_FLAG_BH_OFF; + none = !irqs_pipelined() && (entry->flags & TRACE_FLAG_IRQS_NOSUPPORT) ? 'X' : '.'; irqs_off = + (entry->flags & (TRACE_FLAG_IRQS_OFF|TRACE_FLAG_IRQS_HARDOFF)) == + (TRACE_FLAG_IRQS_OFF|TRACE_FLAG_IRQS_HARDOFF) ? '*' : + (entry->flags & TRACE_FLAG_IRQS_HARDOFF) ? '#' : (entry->flags & TRACE_FLAG_IRQS_OFF && bh_off) ? 'D' : (entry->flags & TRACE_FLAG_IRQS_OFF) ? 'd' : bh_off ? 'b' : - (entry->flags & TRACE_FLAG_IRQS_NOSUPPORT) ? 'X' : - '.'; + none; switch (entry->flags & (TRACE_FLAG_NEED_RESCHED | TRACE_FLAG_PREEMPT_RESCHED)) { @@ -484,6 +488,7 @@ int trace_print_lat_fmt(struct trace_seq *s, struct trace_entry *entry) } hardsoft_irq = + irqs_pipelined() && nmi ? '~' : (nmi && hardirq) ? 'Z' : nmi ? 'z' : (hardirq && softirq) ? 'H' : diff --git a/kernel/trace/trace_preemptirq.c b/kernel/trace/trace_preemptirq.c index e37446f79..bfb4baa74 100644 --- a/kernel/trace/trace_preemptirq.c +++ b/kernel/trace/trace_preemptirq.c @@ -10,6 +10,7 @@ #include #include #include +#include #include "trace.h" #define CREATE_TRACE_POINTS @@ -94,6 +95,57 @@ void trace_hardirqs_off(void) } EXPORT_SYMBOL(trace_hardirqs_off); NOKPROBE_SYMBOL(trace_hardirqs_off); + +#ifdef CONFIG_IRQ_PIPELINE + +void trace_hardirqs_off_pipelined(void) +{ + WARN_ON(irq_pipeline_debug() && !hard_irqs_disabled()); + + if (running_inband()) + trace_hardirqs_off(); +} +EXPORT_SYMBOL(trace_hardirqs_off_pipelined); +NOKPROBE_SYMBOL(trace_hardirqs_off_pipelined); + +void trace_hardirqs_on_pipelined(void) +{ + WARN_ON(irq_pipeline_debug() && !hard_irqs_disabled()); + + /* + * If the in-band stage of the kernel is current but the IRQ + * was not delivered because the latter is stalled, keep the + * tracing logic unaware of the receipt, so that no false + * positive is triggered in lockdep (e.g. IN-HARDIRQ-W -> + * HARDIRQ-ON-W). + */ + if (running_inband() && !irqs_disabled()) { + stall_inband(); + trace_hardirqs_on(); + unstall_inband_nocheck(); + } +} +EXPORT_SYMBOL(trace_hardirqs_on_pipelined); +NOKPROBE_SYMBOL(trace_hardirqs_on_pipelined); + +#else + +void trace_hardirqs_off_pipelined(void) +{ + trace_hardirqs_off(); +} +EXPORT_SYMBOL(trace_hardirqs_off_pipelined); +NOKPROBE_SYMBOL(trace_hardirqs_off_pipelined); + +void trace_hardirqs_on_pipelined(void) +{ + trace_hardirqs_on(); +} +EXPORT_SYMBOL(trace_hardirqs_on_pipelined); +NOKPROBE_SYMBOL(trace_hardirqs_on_pipelined); + +#endif + #endif /* CONFIG_TRACE_IRQFLAGS */ #ifdef CONFIG_TRACE_PREEMPT_TOGGLE diff --git a/kernel/trace/trace_sched_wakeup.c b/kernel/trace/trace_sched_wakeup.c index 0469a04a3..70766e1d6 100644 --- a/kernel/trace/trace_sched_wakeup.c +++ b/kernel/trace/trace_sched_wakeup.c @@ -486,7 +486,9 @@ probe_wakeup_sched_switch(void *ignore, bool preempt, if (likely(!is_tracing_stopped())) { wakeup_trace->max_latency = delta; + hard_local_irq_disable(); update_max_tr(wakeup_trace, wakeup_task, wakeup_cpu, NULL); + hard_local_irq_enable(); } out_unlock: diff --git a/kernel/trace/trace_stack.c b/kernel/trace/trace_stack.c index 5a48dba91..fe6399cb4 100644 --- a/kernel/trace/trace_stack.c +++ b/kernel/trace/trace_stack.c @@ -171,8 +171,9 @@ static void check_stack(unsigned long ip, unsigned long *stack) if (!object_is_on_stack(stack)) return; - /* Can't do this from NMI context (can cause deadlocks) */ - if (in_nmi()) + /* Can't do this from NMI or oob stage contexts (can cause + deadlocks) */ + if (in_nmi() || !running_inband()) return; local_irq_save(flags); diff --git a/lib/Kconfig.debug b/lib/Kconfig.debug index f94c3e957..8e46504fa 100644 --- a/lib/Kconfig.debug +++ b/lib/Kconfig.debug @@ -978,6 +978,38 @@ config DEBUG_SHIRQ is currently disabled). Drivers need to handle this correctly. Some don't and need to be caught. +config DEBUG_IRQ_PIPELINE + bool "Debug IRQ pipeline" + depends on IRQ_PIPELINE && DEBUG_KERNEL + help + Turn on this option for enabling debug checks related to + interrupt pipelining, like interrupt state consistency and + proper context isolation between the in-band and oob stages. + + If unsure, say N. + +config IRQ_PIPELINE_TORTURE_TEST + bool "Torture tests for IRQ pipeline" + depends on DEBUG_IRQ_PIPELINE + select TORTURE_TEST + default n + help + This option provides a kernel module that runs torture tests + on the IRQ pipeline mechanism. + + Say Y here if you want the IRQ pipeline torture tests to run + when the kernel starts. Say N if you are unsure. + +config DEBUG_DOVETAIL + bool "Debug Dovetail interface" + depends on DOVETAIL && DEBUG_KERNEL + select DEBUG_IRQ_PIPELINE + help + Turn on this option for enabling debug checks related to + running a dual kernel configuration, aka dovetailing. This + option implicitly enables the interrupt pipeline debugging + features. + menu "Debug Oops, Lockups and Hangs" config PANIC_ON_OOPS @@ -1441,6 +1473,27 @@ config DEBUG_LOCK_ALLOC spin_lock_init()/mutex_init()/etc., or whether there is any lock held during task exit. +config DEBUG_HARD_LOCKS + bool "Debug hard spinlocks" + depends on DEBUG_IRQ_PIPELINE && LOCKDEP && EXPERT + help + Turn on this option for enabling LOCKDEP for hard spinlock + types used in interrupt pipelining. + + Keep in mind that enabling such feature will ruin the + latency figures for any out-of-band code, this is merely + useful for proving the correctness of the locking scheme of + such code without any consideration for real-time + guarantees. You have been warned. + + If unsure, say N. + +if DEBUG_HARD_LOCKS +comment "WARNING! DEBUG_HARD_LOCKS induces **massive** latency" +comment "overhead for the code running on the out-of-band" +comment "interrupt stage." +endif + config LOCKDEP bool depends on DEBUG_KERNEL && LOCK_DEBUGGING_SUPPORT diff --git a/lib/atomic64.c b/lib/atomic64.c index caf895789..4e303112d 100644 --- a/lib/atomic64.c +++ b/lib/atomic64.c @@ -25,15 +25,15 @@ * Ensure each lock is in a separate cacheline. */ static union { - raw_spinlock_t lock; + hard_spinlock_t lock; char pad[L1_CACHE_BYTES]; } atomic64_lock[NR_LOCKS] __cacheline_aligned_in_smp = { [0 ... (NR_LOCKS - 1)] = { - .lock = __RAW_SPIN_LOCK_UNLOCKED(atomic64_lock.lock), + .lock = __HARD_SPIN_LOCK_INITIALIZER(atomic64_lock.lock), }, }; -static inline raw_spinlock_t *lock_addr(const atomic64_t *v) +static inline hard_spinlock_t *lock_addr(const atomic64_t *v) { unsigned long addr = (unsigned long) v; @@ -45,7 +45,7 @@ static inline raw_spinlock_t *lock_addr(const atomic64_t *v) s64 generic_atomic64_read(const atomic64_t *v) { unsigned long flags; - raw_spinlock_t *lock = lock_addr(v); + hard_spinlock_t *lock = lock_addr(v); s64 val; raw_spin_lock_irqsave(lock, flags); @@ -58,7 +58,7 @@ EXPORT_SYMBOL(generic_atomic64_read); void generic_atomic64_set(atomic64_t *v, s64 i) { unsigned long flags; - raw_spinlock_t *lock = lock_addr(v); + hard_spinlock_t *lock = lock_addr(v); raw_spin_lock_irqsave(lock, flags); v->counter = i; @@ -70,7 +70,7 @@ EXPORT_SYMBOL(generic_atomic64_set); void generic_atomic64_##op(s64 a, atomic64_t *v) \ { \ unsigned long flags; \ - raw_spinlock_t *lock = lock_addr(v); \ + hard_spinlock_t *lock = lock_addr(v); \ \ raw_spin_lock_irqsave(lock, flags); \ v->counter c_op a; \ @@ -82,7 +82,7 @@ EXPORT_SYMBOL(generic_atomic64_##op); s64 generic_atomic64_##op##_return(s64 a, atomic64_t *v) \ { \ unsigned long flags; \ - raw_spinlock_t *lock = lock_addr(v); \ + hard_spinlock_t *lock = lock_addr(v); \ s64 val; \ \ raw_spin_lock_irqsave(lock, flags); \ @@ -96,7 +96,7 @@ EXPORT_SYMBOL(generic_atomic64_##op##_return); s64 generic_atomic64_fetch_##op(s64 a, atomic64_t *v) \ { \ unsigned long flags; \ - raw_spinlock_t *lock = lock_addr(v); \ + hard_spinlock_t *lock = lock_addr(v); \ s64 val; \ \ raw_spin_lock_irqsave(lock, flags); \ @@ -131,7 +131,7 @@ ATOMIC64_OPS(xor, ^=) s64 generic_atomic64_dec_if_positive(atomic64_t *v) { unsigned long flags; - raw_spinlock_t *lock = lock_addr(v); + hard_spinlock_t *lock = lock_addr(v); s64 val; raw_spin_lock_irqsave(lock, flags); @@ -146,7 +146,7 @@ EXPORT_SYMBOL(generic_atomic64_dec_if_positive); s64 generic_atomic64_cmpxchg(atomic64_t *v, s64 o, s64 n) { unsigned long flags; - raw_spinlock_t *lock = lock_addr(v); + hard_spinlock_t *lock = lock_addr(v); s64 val; raw_spin_lock_irqsave(lock, flags); @@ -161,7 +161,7 @@ EXPORT_SYMBOL(generic_atomic64_cmpxchg); s64 generic_atomic64_xchg(atomic64_t *v, s64 new) { unsigned long flags; - raw_spinlock_t *lock = lock_addr(v); + hard_spinlock_t *lock = lock_addr(v); s64 val; raw_spin_lock_irqsave(lock, flags); @@ -175,7 +175,7 @@ EXPORT_SYMBOL(generic_atomic64_xchg); s64 generic_atomic64_fetch_add_unless(atomic64_t *v, s64 a, s64 u) { unsigned long flags; - raw_spinlock_t *lock = lock_addr(v); + hard_spinlock_t *lock = lock_addr(v); s64 val; raw_spin_lock_irqsave(lock, flags); diff --git a/lib/dump_stack.c b/lib/dump_stack.c index 83471e815..c77840713 100644 --- a/lib/dump_stack.c +++ b/lib/dump_stack.c @@ -10,7 +10,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -66,6 +68,11 @@ void dump_stack_print_info(const char *log_lvl) printk("%sHardware name: %s\n", log_lvl, dump_stack_arch_desc_str); +#ifdef CONFIG_IRQ_PIPELINE + printk("%sIRQ stage: %s\n", + log_lvl, current_irq_stage->name); +#endif + print_worker_info(log_lvl, current); print_stop_info(log_lvl, current); } diff --git a/lib/smp_processor_id.c b/lib/smp_processor_id.c index a2bb7738c..26930c12a 100644 --- a/lib/smp_processor_id.c +++ b/lib/smp_processor_id.c @@ -7,12 +7,16 @@ #include #include #include +#include noinstr static unsigned int check_preemption_disabled(const char *what1, const char *what2) { int this_cpu = raw_smp_processor_id(); + if (hard_irqs_disabled() || !running_inband()) + goto out; + if (likely(preempt_count())) goto out; diff --git a/lib/vdso/Kconfig b/lib/vdso/Kconfig index d883ac299..97e344234 100644 --- a/lib/vdso/Kconfig +++ b/lib/vdso/Kconfig @@ -30,4 +30,12 @@ config GENERIC_VDSO_TIME_NS Selected by architectures which support time namespaces in the VDSO +config GENERIC_CLOCKSOURCE_VDSO + select CLKSRC_MMIO + depends on ARM || ARM64 + bool + help + Enables access to clocksources via the vDSO based on + generic MMIO operations. + endif diff --git a/lib/vdso/gettimeofday.c b/lib/vdso/gettimeofday.c index ce2f69552..1504aa722 100644 --- a/lib/vdso/gettimeofday.c +++ b/lib/vdso/gettimeofday.c @@ -5,6 +5,245 @@ #include #include +static int do_hres_timens(const struct vdso_data *vdns, clockid_t clk, + struct __kernel_timespec *ts); + +#ifndef vdso_clocksource_ok +static inline bool vdso_clocksource_ok(const struct vdso_data *vd) +{ + return vd->clock_mode != VDSO_CLOCKMODE_NONE; +} +#endif + +#ifndef vdso_cycles_ok +static inline bool vdso_cycles_ok(u64 cycles) +{ + return true; +} +#endif + +#if defined(CONFIG_GENERIC_CLOCKSOURCE_VDSO) && !defined(BUILD_VDSO32) + +#include +#include +#include +#include + +static __always_inline notrace u64 readl_mmio_up(const struct clksrc_info *vinfo) +{ + const struct clksrc_user_mmio_info *info = &vinfo->mmio; + return readl_relaxed(info->reg_lower); +} + +static __always_inline notrace u64 readl_mmio_down(const struct clksrc_info *vinfo) +{ + const struct clksrc_user_mmio_info *info = &vinfo->mmio; + return ~(u64)readl_relaxed(info->reg_lower) & info->mask_lower; +} + +static __always_inline notrace u64 readw_mmio_up(const struct clksrc_info *vinfo) +{ + const struct clksrc_user_mmio_info *info = &vinfo->mmio; + return readw_relaxed(info->reg_lower); +} + +static __always_inline notrace u64 readw_mmio_down(const struct clksrc_info *vinfo) +{ + const struct clksrc_user_mmio_info *info = &vinfo->mmio; + return ~(u64)readl_relaxed(info->reg_lower) & info->mask_lower; +} + +static __always_inline notrace u64 readl_dmmio_up(const struct clksrc_info *vinfo) +{ + const struct clksrc_user_mmio_info *info = &vinfo->mmio; + void __iomem *reg_lower, *reg_upper; + u32 upper, old_upper, lower; + + reg_lower = info->reg_lower; + reg_upper = info->reg_upper; + + upper = readl_relaxed(reg_upper); + do { + old_upper = upper; + lower = readl_relaxed(reg_lower); + upper = readl_relaxed(reg_upper); + } while (upper != old_upper); + + return (((u64)upper) << info->bits_lower) | lower; +} + +static __always_inline notrace u64 readw_dmmio_up(const struct clksrc_info *vinfo) +{ + const struct clksrc_user_mmio_info *info = &vinfo->mmio; + void __iomem *reg_lower, *reg_upper; + u16 upper, old_upper, lower; + + reg_lower = info->reg_lower; + reg_upper = info->reg_upper; + + upper = readw_relaxed(reg_upper); + do { + old_upper = upper; + lower = readw_relaxed(reg_lower); + upper = readw_relaxed(reg_upper); + } while (upper != old_upper); + + return (((u64)upper) << info->bits_lower) | lower; +} + +static __always_inline u16 to_cs_type(u32 cs_type_seq) +{ + return cs_type_seq >> 16; +} + +static __always_inline u16 to_seq(u32 cs_type_seq) +{ + return cs_type_seq; +} + +static __always_inline u32 to_cs_type_seq(u16 type, u16 seq) +{ + return (u32)type << 16U | seq; +} + +static notrace noinline __cold +void map_clocksource(const struct vdso_data *vd, struct vdso_priv *vp, + u32 seq, u32 new_cs_type_seq) +{ + vdso_read_cycles_t *read_cycles = NULL; + u32 new_cs_seq, new_cs_type; + struct clksrc_info *info; + int fd, ret; + + new_cs_seq = to_seq(new_cs_type_seq); + new_cs_type = to_cs_type(new_cs_type_seq); + info = &vp->clksrc_info[new_cs_type]; + + if (new_cs_type < CLOCKSOURCE_VDSO_MMIO) + goto done; + + fd = clock_open_device(vd->cs_mmdev, O_RDONLY); + if (fd < 0) + goto fallback_to_syscall; + + if (vdso_read_retry(vd, seq)) { + vdso_read_begin(vd); + if (to_seq(vd->cs_type_seq) != new_cs_seq) { + /* + * cs_mmdev no longer corresponds to + * vd->cs_type_seq. + */ + clock_close_device(fd); + return; + } + } + + ret = clock_ioctl_device(fd, CLKSRC_USER_MMIO_MAP, (long)&info->mmio); + clock_close_device(fd); + if (ret < 0) + goto fallback_to_syscall; + + switch (info->mmio.type) { + case CLKSRC_MMIO_L_UP: + read_cycles = &readl_mmio_up; + break; + case CLKSRC_MMIO_L_DOWN: + read_cycles = &readl_mmio_down; + break; + case CLKSRC_MMIO_W_UP: + read_cycles = &readw_mmio_up; + break; + case CLKSRC_MMIO_W_DOWN: + read_cycles = &readw_mmio_down; + break; + case CLKSRC_DMMIO_L_UP: + read_cycles = &readl_dmmio_up; + break; + case CLKSRC_DMMIO_W_UP: + read_cycles = &readw_dmmio_up; + break; + default: + /* Mmhf, misconfigured. */ + goto fallback_to_syscall; + } +done: + info->read_cycles = read_cycles; + smp_wmb(); + new_cs_type_seq = to_cs_type_seq(new_cs_type, new_cs_seq); + WRITE_ONCE(vp->current_cs_type_seq, new_cs_type_seq); + + return; + +fallback_to_syscall: + new_cs_type = CLOCKSOURCE_VDSO_NONE; + info = &vp->clksrc_info[new_cs_type]; + goto done; +} + +static inline notrace +bool get_hw_counter(const struct vdso_data *vd, u32 *r_seq, u64 *cycles) +{ + const struct clksrc_info *info; + struct vdso_priv *vp; + u32 seq, cs_type_seq; + unsigned int cs; + + vp = __arch_get_vdso_priv(); + + for (;;) { + seq = vdso_read_begin(vd); + cs_type_seq = READ_ONCE(vp->current_cs_type_seq); + if (likely(to_seq(cs_type_seq) == to_seq(vd->cs_type_seq))) + break; + + map_clocksource(vd, vp, seq, vd->cs_type_seq); + } + + switch (to_cs_type(cs_type_seq)) { + case CLOCKSOURCE_VDSO_NONE: + return false; /* Use fallback. */ + case CLOCKSOURCE_VDSO_ARCHITECTED: + if (unlikely(!vdso_clocksource_ok(vd))) + return false; + *cycles = __arch_get_hw_counter(vd->clock_mode, vd); + if (unlikely(!vdso_cycles_ok(*cycles))) + return false; + break; + default: + cs = to_cs_type(READ_ONCE(cs_type_seq)); + info = &vp->clksrc_info[cs]; + *cycles = info->read_cycles(info); + break; + } + + *r_seq = seq; + + return true; +} + +#else + +static inline notrace +bool get_hw_counter(const struct vdso_data *vd, u32 *r_seq, u64 *cycles) +{ + *r_seq = vdso_read_begin(vd); + + /* + * CAUTION: checking the clocksource mode must happen inside + * the seqlocked section. + */ + if (unlikely(!vdso_clocksource_ok(vd))) + return false; + + *cycles = __arch_get_hw_counter(vd->clock_mode, vd); + if (unlikely(!vdso_cycles_ok(*cycles))) + return false; + + return true; +} + +#endif /* CONFIG_GENERIC_CLOCKSOURCE_VDSO */ + #ifndef vdso_calc_delta /* * Default implementation which works for all sane clocksources. That @@ -31,20 +270,6 @@ static inline bool __arch_vdso_hres_capable(void) } #endif -#ifndef vdso_clocksource_ok -static inline bool vdso_clocksource_ok(const struct vdso_data *vd) -{ - return vd->clock_mode != VDSO_CLOCKMODE_NONE; -} -#endif - -#ifndef vdso_cycles_ok -static inline bool vdso_cycles_ok(u64 cycles) -{ - return true; -} -#endif - #ifdef CONFIG_TIME_NS static __always_inline int do_hres_timens(const struct vdso_data *vdns, clockid_t clk, struct __kernel_timespec *ts) @@ -65,13 +290,7 @@ static __always_inline int do_hres_timens(const struct vdso_data *vdns, clockid_ vdso_ts = &vd->basetime[clk]; do { - seq = vdso_read_begin(vd); - - if (unlikely(!vdso_clocksource_ok(vd))) - return -1; - - cycles = __arch_get_hw_counter(vd->clock_mode, vd); - if (unlikely(!vdso_cycles_ok(cycles))) + if (!get_hw_counter(vd, &seq, &cycles)) return -1; ns = vdso_ts->nsec; last = vd->cycle_last; @@ -120,30 +339,29 @@ static __always_inline int do_hres(const struct vdso_data *vd, clockid_t clk, do { /* - * Open coded to handle VDSO_CLOCKMODE_TIMENS. Time namespace - * enabled tasks have a special VVAR page installed which - * has vd->seq set to 1 and vd->clock_mode set to - * VDSO_CLOCKMODE_TIMENS. For non time namespace affected tasks - * this does not affect performance because if vd->seq is - * odd, i.e. a concurrent update is in progress the extra + * Open coded to handle VDSO_CLOCKMODE_TIMENS. Time + * namespace enabled tasks have a special VVAR page + * installed which has vd->seq set to 1 and + * vd->clock_mode set to VDSO_CLOCKMODE_TIMENS. For + * non time namespace affected tasks this does not + * affect performance because if vd->seq is odd, + * i.e. a concurrent update is in progress the extra * check for vd->clock_mode is just a few extra - * instructions while spin waiting for vd->seq to become - * even again. + * instructions while spin waiting for vd->seq to + * become even again. */ while (unlikely((seq = READ_ONCE(vd->seq)) & 1)) { if (IS_ENABLED(CONFIG_TIME_NS) && - vd->clock_mode == VDSO_CLOCKMODE_TIMENS) + vd->clock_mode == VDSO_CLOCKMODE_TIMENS) return do_hres_timens(vd, clk, ts); cpu_relax(); } + smp_rmb(); - if (unlikely(!vdso_clocksource_ok(vd))) + if (!get_hw_counter(vd, &seq, &cycles)) return -1; - cycles = __arch_get_hw_counter(vd->clock_mode, vd); - if (unlikely(!vdso_cycles_ok(cycles))) - return -1; ns = vdso_ts->nsec; last = vd->cycle_last; ns += vdso_calc_delta(cycles, last, vd->mask, vd->mult); diff --git a/mm/huge_memory.c b/mm/huge_memory.c index 635f0f0f6..864eeb334 100644 --- a/mm/huge_memory.c +++ b/mm/huge_memory.c @@ -1239,6 +1239,7 @@ int copy_huge_pud(struct mm_struct *dst_mm, struct mm_struct *src_mm, /* * TODO: once we support anonymous pages, use page_try_dup_anon_rmap() * and split if duplicating fails. + * irq_pipeline: update as required as well. */ pudp_set_wrprotect(src_mm, addr, src_pud); pud = pud_mkold(pud_wrprotect(pud)); diff --git a/mm/kasan/report.c b/mm/kasan/report.c old mode 100644 new mode 100755 index ecced40e5..a66413f49 --- a/mm/kasan/report.c +++ b/mm/kasan/report.c @@ -199,7 +199,7 @@ static inline void fail_non_kasan_kunit_test(void) { } #endif /* CONFIG_KUNIT */ -static DEFINE_RAW_SPINLOCK(report_lock); +static DEFINE_HARD_SPINLOCK(report_lock); static void start_report(unsigned long *flags, bool sync) { diff --git a/mm/memory.c b/mm/memory.c index 742c2f65c..bcb0c225b 100644 --- a/mm/memory.c +++ b/mm/memory.c @@ -5940,6 +5940,15 @@ void print_vma_addr(char *prefix, unsigned long ip) #if defined(CONFIG_PROVE_LOCKING) || defined(CONFIG_DEBUG_ATOMIC_SLEEP) void __might_fault(const char *file, int line) { + /* + * When running over the oob stage (e.g. some co-kernel's own + * thread), we should only make sure to run with hw IRQs + * enabled before accessing the memory. + */ + if (running_oob()) { + WARN_ON_ONCE(hard_irqs_disabled()); + return; + } if (pagefault_disabled()) return; __might_sleep(file, line); diff --git a/mm/mprotect.c b/mm/mprotect.c index 7e870a8c9..1d57d0b9d 100644 --- a/mm/mprotect.c +++ b/mm/mprotect.c @@ -87,6 +87,7 @@ static long change_pte_range(struct mmu_gather *tlb, pte_t *pte, oldpte; spinlock_t *ptl; long pages = 0; + unsigned long flags; int target_node = NUMA_NO_NODE; bool prot_numa = cp_flags & MM_CP_PROT_NUMA; bool uffd_wp = cp_flags & MM_CP_UFFD_WP; @@ -161,6 +162,7 @@ static long change_pte_range(struct mmu_gather *tlb, jiffies_to_msecs(jiffies)); } + flags = hard_local_irq_save(); oldpte = ptep_modify_prot_start(vma, addr, pte); ptent = pte_modify(oldpte, newprot); @@ -190,6 +192,7 @@ static long change_pte_range(struct mmu_gather *tlb, ptep_modify_prot_commit(vma, addr, pte, oldpte, ptent); if (pte_needs_flush(oldpte, ptent)) tlb_flush_pte_range(tlb, addr, PAGE_SIZE); + hard_local_irq_restore(flags); pages++; } else if (is_swap_pte(oldpte)) { swp_entry_t entry = pte_to_swp_entry(oldpte); diff --git a/mm/vmalloc.c b/mm/vmalloc.c index 5c2b5f93c..f4cd00d18 100644 --- a/mm/vmalloc.c +++ b/mm/vmalloc.c @@ -298,6 +298,8 @@ static int vmap_range_noflush(unsigned long addr, unsigned long end, break; } while (pgd++, phys_addr += (next - addr), addr = next, addr != end); + arch_advertise_page_mapping(start, end); + if (mask & ARCH_PAGE_TABLE_SYNC_MASK) arch_sync_kernel_mappings(start, end); @@ -540,6 +542,10 @@ static int vmap_pages_p4d_range(pgd_t *pgd, unsigned long addr, return 0; } +void __weak arch_advertise_page_mapping(unsigned long start, unsigned long end) +{ +} + static int vmap_small_pages_range_noflush(unsigned long addr, unsigned long end, pgprot_t prot, struct page **pages) { @@ -561,6 +567,8 @@ static int vmap_small_pages_range_noflush(unsigned long addr, unsigned long end, return err; } while (pgd++, addr = next, addr != end); + arch_advertise_page_mapping(start, end); + if (mask & ARCH_PAGE_TABLE_SYNC_MASK) arch_sync_kernel_mappings(start, end); diff --git a/net/Kconfig b/net/Kconfig index d532ec33f..7e9eb8a78 100644 --- a/net/Kconfig +++ b/net/Kconfig @@ -63,6 +63,11 @@ config NET_REDIRECT config SKB_EXTENSIONS bool +config NET_OOB + bool + depends on DOVETAIL + select PAGE_POOL_OOB + menu "Networking options" source "net/packet/Kconfig" @@ -469,6 +474,10 @@ config NET_DEVLINK config PAGE_POOL bool +config PAGE_POOL_OOB + def_bool n + select PAGE_POOL + config PAGE_POOL_STATS default n bool "Page pool stats" diff --git a/net/core/dev.c b/net/core/dev.c index 69da7b009..1c8e5f4a1 100644 --- a/net/core/dev.c +++ b/net/core/dev.c @@ -3181,6 +3181,10 @@ void dev_kfree_skb_irq_reason(struct sk_buff *skb, enum skb_drop_reason reason) return; } get_kfree_skb_cb(skb)->reason = reason; + + if (recycle_skb_oob(skb)) + return; + local_irq_save(flags); skb->next = __this_cpu_read(softnet_data.completion_queue); __this_cpu_write(softnet_data.completion_queue, skb); @@ -3191,7 +3195,7 @@ EXPORT_SYMBOL(dev_kfree_skb_irq_reason); void dev_kfree_skb_any_reason(struct sk_buff *skb, enum skb_drop_reason reason) { - if (in_hardirq() || irqs_disabled()) + if (running_oob() || in_hardirq() || irqs_disabled()) dev_kfree_skb_irq_reason(skb, reason); else kfree_skb_reason(skb, reason); @@ -5065,6 +5069,103 @@ int do_xdp_generic(struct bpf_prog *xdp_prog, struct sk_buff *skb) } EXPORT_SYMBOL_GPL(do_xdp_generic); +#ifdef CONFIG_NET_OOB + +static void _netif_receive_skb_list(struct list_head *head); + +__weak bool netif_deliver_oob(struct sk_buff *skb) +{ + return false; +} + +bool netif_receive_oob(struct sk_buff *skb) +{ + struct softnet_data *sd = this_cpu_ptr(&softnet_data); + struct net_device *dev = skb->dev; + unsigned long flags; + bool kick_softirq; + + /* + * If the interface has oob diversion enabled, attempt to + * deliver the incoming packet to the oob netstack. If the + * packet is not picked, then decide whether we should leave + * it to the in-band caller, or defer it to the RX softirq if + * currently running oob. + */ + if (dev && netif_oob_diversion(dev)) { + if (netif_deliver_oob(skb)) + return true; + if (net_running_oob()) { + raw_spin_lock_irqsave(&sd->inband_rx_lock, flags); + kick_softirq = list_empty(&sd->inband_rx_list); + list_add(&skb->list, &sd->inband_rx_list); + raw_spin_unlock_irqrestore(&sd->inband_rx_lock, flags); + if (kick_softirq) + irq_work_queue(&sd->inband_rx_work); + return true; + } + } + + return false; /* Not handled, caller should pick it. */ +} + +static bool netif_receive_oob_list(struct list_head *head) +{ + struct sk_buff *skb, *next; + + list_for_each_entry_safe(skb, next, head, list) + netif_receive_oob(skb); + + return list_empty(head); +} + +static void process_inband_rx_backlog(struct softnet_data *sd) +{ + unsigned long flags; + LIST_HEAD(list); + + raw_spin_lock_irqsave(&sd->inband_rx_lock, flags); + list_splice_init(&sd->inband_rx_list, &list); + raw_spin_unlock_irqrestore(&sd->inband_rx_lock, flags); + if (!list_empty(&list)) + _netif_receive_skb_list(&list); +} + +__weak void napi_schedule_oob(struct napi_struct *n) +{ } + +__weak void napi_complete_oob(struct napi_struct *n) +{ } + +__weak void process_inband_tx_backlog(struct softnet_data *sd) +{ } + +static void kick_rx_inband(struct irq_work *irq_work) +{ + __raise_softirq_irqoff(NET_RX_SOFTIRQ); +} + +#else + +static inline bool netif_receive_oob_list(struct list_head *head) +{ + return false; +} + +static inline void napi_schedule_oob(struct napi_struct *n) +{ } + +static inline void napi_complete_oob(struct napi_struct *n) +{ } + +static inline void process_inband_tx_backlog(struct softnet_data *sd) +{ } + +static void process_inband_rx_backlog(struct softnet_data *sd) +{ } + +#endif + static int netif_rx_internal(struct sk_buff *skb) { int ret; @@ -5157,6 +5258,8 @@ static __latent_entropy void net_tx_action(struct softirq_action *h) { struct softnet_data *sd = this_cpu_ptr(&softnet_data); + process_inband_tx_backlog(sd); + if (sd->completion_queue) { struct sk_buff *clist; @@ -5819,6 +5922,9 @@ int netif_receive_skb(struct sk_buff *skb) { int ret; + if (netif_receive_oob(skb)) + return NET_RX_SUCCESS; + trace_netif_receive_skb_entry(skb); ret = netif_receive_skb_internal(skb); @@ -5828,6 +5934,18 @@ int netif_receive_skb(struct sk_buff *skb) } EXPORT_SYMBOL(netif_receive_skb); +static void _netif_receive_skb_list(struct list_head *head) +{ + struct sk_buff *skb; + + if (trace_netif_receive_skb_list_entry_enabled()) { + list_for_each_entry(skb, head, list) + trace_netif_receive_skb_list_entry(skb); + } + netif_receive_skb_list_internal(head); + trace_netif_receive_skb_list_exit(0); +} + /** * netif_receive_skb_list - process many receive buffers from network * @head: list of skbs to process. @@ -5840,16 +5958,11 @@ EXPORT_SYMBOL(netif_receive_skb); */ void netif_receive_skb_list(struct list_head *head) { - struct sk_buff *skb; - if (list_empty(head)) return; - if (trace_netif_receive_skb_list_entry_enabled()) { - list_for_each_entry(skb, head, list) - trace_netif_receive_skb_list_entry(skb); - } - netif_receive_skb_list_internal(head); - trace_netif_receive_skb_list_exit(0); + if (netif_receive_oob_list(head)) + return; + _netif_receive_skb_list(head); } EXPORT_SYMBOL(netif_receive_skb_list); @@ -6040,14 +6153,20 @@ static int process_backlog(struct napi_struct *napi, int quota) * * The entry's receive function will be scheduled to run. * Consider using __napi_schedule_irqoff() if hard irqs are masked. + * + * Dovetail: may be called from the out-of-band stage. */ void __napi_schedule(struct napi_struct *n) { unsigned long flags; - local_irq_save(flags); - ____napi_schedule(this_cpu_ptr(&softnet_data), n); - local_irq_restore(flags); + if (net_running_oob()) { + napi_schedule_oob(n); + } else { + local_irq_save(flags); + ____napi_schedule(this_cpu_ptr(&softnet_data), n); + local_irq_restore(flags); + } } EXPORT_SYMBOL(__napi_schedule); @@ -6059,6 +6178,8 @@ EXPORT_SYMBOL(__napi_schedule); * it as running. This is used as a condition variable to * insure only one NAPI poll instance runs. We also make * sure there is no pending NAPI disable. + * + * Dovetail: may be called from the out-of-band stage. */ bool napi_schedule_prep(struct napi_struct *n) { @@ -6095,18 +6216,54 @@ EXPORT_SYMBOL(napi_schedule_prep); */ void __napi_schedule_irqoff(struct napi_struct *n) { - if (!IS_ENABLED(CONFIG_PREEMPT_RT)) + if (net_running_oob()) + napi_schedule_oob(n); + else if (!IS_ENABLED(CONFIG_PREEMPT_RT)) ____napi_schedule(this_cpu_ptr(&softnet_data), n); else __napi_schedule(n); } EXPORT_SYMBOL(__napi_schedule_irqoff); +bool napi_schedule_unprep(struct napi_struct *n) +{ + unsigned long val, new; + + val = READ_ONCE(n->state); + do { + WARN_ON_ONCE(!(val & NAPIF_STATE_SCHED)); + + new = val & ~(NAPIF_STATE_MISSED | NAPIF_STATE_SCHED | + NAPIF_STATE_SCHED_THREADED | + NAPIF_STATE_PREFER_BUSY_POLL); + + /* If STATE_MISSED was set, leave STATE_SCHED set, + * because we will call napi->poll() one more time. + * This C code was suggested by Alexander Duyck to help gcc. + */ + new |= (val & NAPIF_STATE_MISSED) / NAPIF_STATE_MISSED * + NAPIF_STATE_SCHED; + } while (!try_cmpxchg(&n->state, &val, new)); + + if (unlikely(val & NAPIF_STATE_MISSED)) { + __napi_schedule(n); + return false; + } + + return true; +} + bool napi_complete_done(struct napi_struct *n, int work_done) { - unsigned long flags, val, new, timeout = 0; + unsigned long flags, timeout = 0; bool ret = true; + if (netif_oob_diversion(n->dev)) { + napi_complete_oob(n); + if (net_running_oob()) + return true; + } + /* * 1) Don't let napi dequeue from the cpu poll list * just in case its running on a different cpu. @@ -6146,26 +6303,8 @@ bool napi_complete_done(struct napi_struct *n, int work_done) } WRITE_ONCE(n->list_owner, -1); - val = READ_ONCE(n->state); - do { - WARN_ON_ONCE(!(val & NAPIF_STATE_SCHED)); - - new = val & ~(NAPIF_STATE_MISSED | NAPIF_STATE_SCHED | - NAPIF_STATE_SCHED_THREADED | - NAPIF_STATE_PREFER_BUSY_POLL); - - /* If STATE_MISSED was set, leave STATE_SCHED set, - * because we will call napi->poll() one more time. - * This C code was suggested by Alexander Duyck to help gcc. - */ - new |= (val & NAPIF_STATE_MISSED) / NAPIF_STATE_MISSED * - NAPIF_STATE_SCHED; - } while (!try_cmpxchg(&n->state, &val, new)); - - if (unlikely(val & NAPIF_STATE_MISSED)) { - __napi_schedule(n); + if (!napi_schedule_unprep(n)) return false; - } if (timeout) hrtimer_start(&n->timer, ns_to_ktime(timeout), @@ -6743,6 +6882,8 @@ static __latent_entropy void net_rx_action(struct softirq_action *h) start: sd->in_net_rx_action = true; + process_inband_rx_backlog(sd); + local_irq_disable(); list_splice_init(&sd->poll_list, &list); local_irq_enable(); @@ -10023,13 +10164,21 @@ static void netdev_init_one_queue(struct net_device *dev, queue->xmit_lock_owner = -1; netdev_queue_numa_node_write(queue, NUMA_NO_NODE); queue->dev = dev; + netqueue_init_oob(&queue->oob); #ifdef CONFIG_BQL dql_init(&queue->dql, HZ); #endif } +static inline void destroy_oob_queue(struct net_device *dev, + struct netdev_queue *nq, void *arg) +{ + netqueue_destroy_oob(&nq->oob); +} + static void netif_free_tx_queues(struct net_device *dev) { + netdev_for_each_tx_queue(dev, destroy_oob_queue, NULL); kvfree(dev->_tx); } @@ -11628,6 +11777,11 @@ static int __init net_dev_init(void) #ifdef CONFIG_RPS INIT_CSD(&sd->csd, rps_trigger_softirq, sd); sd->cpu = i; +#endif +#ifdef CONFIG_NET_OOB + INIT_LIST_HEAD(&sd->inband_rx_list); + raw_spin_lock_init(&sd->inband_rx_lock); + init_irq_work(&sd->inband_rx_work, kick_rx_inband); #endif INIT_CSD(&sd->defer_csd, trigger_rx_softirq, sd); spin_lock_init(&sd->defer_lock); diff --git a/net/core/gro.c b/net/core/gro.c index 85d3f686b..39224aff4 100644 --- a/net/core/gro.c +++ b/net/core/gro.c @@ -598,6 +598,16 @@ gro_result_t napi_gro_receive(struct napi_struct *napi, struct sk_buff *skb) { gro_result_t ret; + /* + * Note: GRO is bypassed for devices enabling out-of-band RX, + * including for in-band traffic not picked by the companion + * core. In this case, the traffic flows through + * process_inband_rx_backlog() -> _netif_receive_skb_list() + * via NET_RX_SOFTIRQ. + */ + if (netif_receive_oob(skb)) + return GRO_NORMAL; + skb_mark_napi_id(skb, napi); trace_napi_gro_receive_entry(skb); diff --git a/net/core/net-sysfs.c b/net/core/net-sysfs.c index f7404bc67..3dfde2ad6 100644 --- a/net/core/net-sysfs.c +++ b/net/core/net-sysfs.c @@ -387,6 +387,54 @@ static ssize_t tx_queue_len_store(struct device *dev, } NETDEVICE_SHOW_RW(tx_queue_len, fmt_dec); +#ifdef CONFIG_NET_OOB + +__weak int netif_oob_switch_port(struct net_device *dev, bool enabled) +{ + return 0; +} + +__weak bool netif_oob_get_port(struct net_device *dev) +{ + return false; +} + +__weak ssize_t netif_oob_query_pool(struct net_device *dev, char *buf) +{ + return -EIO; +} + +static int switch_oob_port(struct net_device *dev, unsigned long enable) +{ + return netif_oob_switch_port(dev, (bool)enable); +} + +static ssize_t oob_port_store(struct device *dev, struct device_attribute *attr, + const char *buf, size_t len) +{ + return netdev_store(dev, attr, buf, len, switch_oob_port); +} + +static ssize_t oob_port_show(struct device *dev, + struct device_attribute *attr, char *buf) +{ + struct net_device *netdev = to_net_dev(dev); + + return sprintf(buf, fmt_dec, netif_oob_get_port(netdev)); +} +static DEVICE_ATTR_RW(oob_port); + +static ssize_t oob_pool_show(struct device *dev, + struct device_attribute *attr, char *buf) +{ + struct net_device *netdev = to_net_dev(dev); + + return netif_oob_query_pool(netdev, buf); +} +static DEVICE_ATTR_RO(oob_pool); + +#endif + static int change_gro_flush_timeout(struct net_device *dev, unsigned long val) { WRITE_ONCE(dev->gro_flush_timeout, val); @@ -652,6 +700,10 @@ static struct attribute *net_class_attrs[] __ro_after_init = { &dev_attr_carrier_up_count.attr, &dev_attr_carrier_down_count.attr, &dev_attr_threaded.attr, +#ifdef CONFIG_NET_OOB + &dev_attr_oob_port.attr, + &dev_attr_oob_pool.attr, +#endif NULL, }; ATTRIBUTE_GROUPS(net_class); diff --git a/net/core/net_namespace.c b/net/core/net_namespace.c index 70ac9d9bc..a56219dad 100644 --- a/net/core/net_namespace.c +++ b/net/core/net_namespace.c @@ -338,6 +338,8 @@ static __net_init int setup_net(struct net *net, struct user_namespace *user_ns) idr_init(&net->netns_ids); spin_lock_init(&net->nsid_lock); mutex_init(&net->ipv4.ra_mutex); + /* Dovetail: set up the oob-specific state. */ + net_init_oob_state(net); list_for_each_entry(ops, &pernet_list, list) { error = ops_init(ops, net); @@ -625,6 +627,8 @@ static void cleanup_net(struct work_struct *work) llist_for_each_entry(net, net_kill_list, cleanup_list) { unhash_nsid(net, last); list_add_tail(&net->exit_list, &net_exit_list); + /* Dovetail: drop the oob-specific state. */ + net_cleanup_oob_state(net); } /* Run all of the network namespace pre_exit methods */ diff --git a/net/core/page_pool.c b/net/core/page_pool.c index 31f923e7b..b50a16f08 100644 --- a/net/core/page_pool.c +++ b/net/core/page_pool.c @@ -168,6 +168,10 @@ static void page_pool_producer_unlock(struct page_pool *pool, spin_unlock_bh(&pool->ring.producer_lock); } +noinline +static struct page *__page_pool_alloc_pages_slow(struct page_pool *pool, + gfp_t gfp); + static int page_pool_init(struct page_pool *pool, const struct page_pool_params *params) { @@ -181,6 +185,9 @@ static int page_pool_init(struct page_pool *pool, if (pool->p.pool_size) ring_qsize = pool->p.pool_size; + /* Size of oob-accessed pools must be specified. */ + else if (page_pool_is_oob(pool)) + return -EINVAL; /* Sanity limit mem that can be pinned down */ if (ring_qsize > 32768) @@ -215,6 +222,11 @@ static int page_pool_init(struct page_pool *pool, pool->p.flags & PP_FLAG_PAGE_FRAG) return -EINVAL; + /* Cannot manage page frags in oob-accessed pools. */ + if (page_pool_is_oob(pool) && + pool->p.flags & PP_FLAG_PAGE_FRAG) + return -EINVAL; + #ifdef CONFIG_PAGE_POOL_STATS pool->recycle_stats = alloc_percpu(struct page_pool_recycle_stats); if (!pool->recycle_stats) @@ -236,6 +248,23 @@ static int page_pool_init(struct page_pool *pool, if (pool->p.flags & PP_FLAG_DMA_MAP) get_device(pool->p.dev); +#ifdef CONFIG_PAGE_POOL_OOB + pool->alloc.cache = kzalloc_node( + sizeof(struct page *) * params->pool_size, + GFP_KERNEL, params->nid); + if (pool->alloc.cache == NULL) { +#ifdef CONFIG_PAGE_POOL_STATS + free_percpu(pool->recycle_stats); +#endif + ptr_ring_cleanup(&pool->ring, NULL); + return -ENOMEM; + } + raw_spin_lock_init(&pool->alloc.oob_lock); + /* Populate the fast cache of oob-accessed pools at init. */ + if (page_pool_is_oob(pool)) + __page_pool_alloc_pages_slow(pool, GFP_KERNEL); +#endif + return 0; } @@ -307,7 +336,7 @@ static struct page *page_pool_refill_alloc_cache(struct page_pool *pool) page = NULL; break; } - } while (pool->alloc.count < PP_ALLOC_CACHE_REFILL); + } while (pool->alloc.count < page_pool_cache_refill(pool)); /* Return last page */ if (likely(pool->alloc.count > 0)) { @@ -329,6 +358,9 @@ static struct page *__page_pool_get_cached(struct page_pool *pool) page = pool->alloc.cache[--pool->alloc.count]; alloc_stat_inc(pool, fast); } else { + /* Cache refilling is disabled for oob-accessed pools. */ + if (unlikely(page_pool_is_oob(pool))) + return NULL; page = page_pool_refill_alloc_cache(pool); } @@ -416,7 +448,7 @@ noinline static struct page *__page_pool_alloc_pages_slow(struct page_pool *pool, gfp_t gfp) { - const int bulk = PP_ALLOC_CACHE_REFILL; + const int bulk = page_pool_cache_refill(pool); unsigned int pp_flags = pool->p.flags; unsigned int pp_order = pool->p.order; struct page *page; @@ -431,7 +463,7 @@ static struct page *__page_pool_alloc_pages_slow(struct page_pool *pool, return pool->alloc.cache[--pool->alloc.count]; /* Mark empty alloc.cache slots "empty" for alloc_pages_bulk_array */ - memset(&pool->alloc.cache, 0, sizeof(void *) * bulk); + memset(pool->alloc.cache, 0, sizeof(void *) * bulk); nr_pages = alloc_pages_bulk_array_node(gfp, pool->p.nid, bulk, pool->alloc.cache); @@ -477,6 +509,27 @@ struct page *page_pool_alloc_pages(struct page_pool *pool, gfp_t gfp) struct page *page; /* Fast-path: Get a page from cache */ + +#ifdef CONFIG_PAGE_POOL_OOB + if (page_pool_is_oob(pool)) { + unsigned long flags; + /* + * Fast, but still serialized. Out-of-band NAPI + * context would not protect us from races since we + * might have in-band vs oob races too. + */ + raw_spin_lock_irqsave(&pool->alloc.oob_lock, flags); + page = __page_pool_get_cached(pool); + raw_spin_unlock_irqrestore(&pool->alloc.oob_lock, flags); + /* + * Slow path is disabled for oob-accessed pools, + * either we did find a free page in the cache, or + * things are about to get ugly. + */ + return page; + } +#endif + page = __page_pool_get_cached(pool); if (page) return page; @@ -570,7 +623,7 @@ static bool page_pool_recycle_in_ring(struct page_pool *pool, struct page *page) static bool page_pool_recycle_in_cache(struct page *page, struct page_pool *pool) { - if (unlikely(pool->alloc.count == PP_ALLOC_CACHE_SIZE)) { + if (unlikely(pool->alloc.count == page_pool_cache_size(pool))) { recycle_stat_inc(pool, cache_full); return false; } @@ -591,6 +644,35 @@ static __always_inline struct page * __page_pool_put_page(struct page_pool *pool, struct page *page, unsigned int dma_sync_size, bool allow_direct) { +#ifdef CONFIG_PAGE_POOL_OOB + /* + * Pages from oob-accessed pools always live in the fast + * cache, never in the ring. They are released to the global + * page allocator only when the pool is destroyed. + */ + if (page_pool_is_oob(pool)) { + unsigned long flags; + bool ret; + /* + * If a page from an oob-accessed pool is still + * referenced when released or the fast cache would + * overflow, we bark at the console then bluntly leak + * it. This situation should never occur, or would + * denote a serious API usage issue anyway. + */ + if (WARN_ON(dovetail_debug() && page_ref_count(page) != 1)) + return NULL; + if (pool->p.flags & PP_FLAG_DMA_SYNC_DEV) + page_pool_dma_sync_for_device(pool, page, + dma_sync_size); + raw_spin_lock_irqsave(&pool->alloc.oob_lock, flags); + ret = page_pool_recycle_in_cache(page, pool); + raw_spin_unlock_irqrestore(&pool->alloc.oob_lock, flags); + WARN_ON(!ret); + return NULL; + } +#endif + lockdep_assert_no_hardirq(); /* This allocator is optimized for the XDP mode that uses @@ -814,6 +896,9 @@ static void page_pool_free(struct page_pool *pool) #ifdef CONFIG_PAGE_POOL_STATS free_percpu(pool->recycle_stats); +#endif +#ifdef CONFIG_PAGE_POOL_OOB + kfree(pool->alloc.cache); #endif kfree(pool); } diff --git a/net/core/skbuff.c b/net/core/skbuff.c index f0a9ef1ae..d8421e23e 100644 --- a/net/core/skbuff.c +++ b/net/core/skbuff.c @@ -440,16 +440,25 @@ static void __build_skb_around(struct sk_buff *skb, void *data, * After IO, driver calls build_skb(), to allocate sk_buff and populate it * before giving packet to stack. * RX rings only contains data buffers, not full skbs. + * + * Dovetail: allocation requests issued from the oob execution stage + * are served by the oob buffer cache. */ struct sk_buff *__build_skb(void *data, unsigned int frag_size) { struct sk_buff *skb; - skb = kmem_cache_alloc(skbuff_cache, GFP_ATOMIC); - if (unlikely(!skb)) - return NULL; + if (running_oob()) { + skb = get_oob_skb(); + if (unlikely(!skb)) + return NULL; + } else { + skb = kmem_cache_alloc(skbuff_cache, GFP_ATOMIC); + if (unlikely(!skb)) + return NULL; + memset(skb, 0, offsetof(struct sk_buff, tail)); + } - memset(skb, 0, offsetof(struct sk_buff, tail)); __build_skb_around(skb, data, frag_size); return skb; @@ -539,6 +548,109 @@ struct sk_buff *napi_build_skb(void *data, unsigned int frag_size) } EXPORT_SYMBOL(napi_build_skb); +#ifdef CONFIG_NET_OOB + +unsigned int sysctl_max_oob_skb __read_mostly = 1024; +EXPORT_SYMBOL(sysctl_max_oob_skb); + +__weak void free_skb_oob(struct sk_buff *skb) +{ } + +__weak void free_skb_head_oob(struct sk_buff *skb) +{ } + +bool recycle_skb_oob(struct sk_buff *skb) +{ + /* + * Hand the buffer release over the out-of-band core either if + * the latter owns the skb data or we are currently running + * oob. + */ + if (running_oob() || skb_has_oob_storage(skb)) { + free_skb_oob(skb); + return true; + } + + return false; +} + +void finalize_skb_inband(struct sk_buff *skb) +{ + if (skb->fclone != SKB_FCLONE_UNAVAILABLE) + __kfree_skb(skb); + else + __napi_kfree_skb(skb, SKB_CONSUMED); +} + +/* + * Pool for out-of-band allocation of buffers. The implementation is + * trivial ATM, we may improve this with per-CPU caches in the future. + */ +static struct skbuff_oob_pool skbuff_oob_pool; + +void init_oob_cache(void) +{ + struct skbuff_oob_pool *c = &skbuff_oob_pool; + unsigned int n, max_skbs; + struct sk_buff *skb; + + /* + * Populate the oob pool with buffers pulled from the regular + * cache. Note: there is no point in using a llist for + * maintaining the entries, our MPMC model requires locking, + * so adding more atomic ops in the picture in addition to + * spinlocking would make no sense. + */ + INIT_LIST_HEAD(&c->pool); + raw_spin_lock_init(&c->lock); + + max_skbs = READ_ONCE(sysctl_max_oob_skb); + for (n = 0; n < max_skbs; n++) { + skb = kmem_cache_alloc(skbuff_cache, GFP_KERNEL); + BUG_ON(!skb); + list_add(&skb->list, &c->pool); + } +} + +struct sk_buff *get_oob_skb(void) +{ + struct skbuff_oob_pool *c = &skbuff_oob_pool; + struct sk_buff *skb = NULL; + unsigned long flags; + + raw_spin_lock_irqsave(&c->lock, flags); + if (!list_empty(&c->pool)) { + skb = list_first_entry(&c->pool, struct sk_buff, list); + list_del(&skb->list); + raw_spin_unlock_irqrestore(&c->lock, flags); + memset(skb, 0, offsetof(struct sk_buff, tail)); + skb_mark_oob(skb); + } else { + raw_spin_unlock_irqrestore(&c->lock, flags); + } + + return skb; +} +EXPORT_SYMBOL(get_oob_skb); + +void put_oob_skb(struct sk_buff *skb) +{ + struct skbuff_oob_pool *c = &skbuff_oob_pool; + unsigned long flags; + + raw_spin_lock_irqsave(&c->lock, flags); + list_add(&skb->list, &c->pool); + raw_spin_unlock_irqrestore(&c->lock, flags); +} +EXPORT_SYMBOL(put_oob_skb); + +#else /* !CONFIG_NET_OOB */ + +static inline void init_oob_cache(void) +{ } + +#endif /* !CONFIG_NET_OOB */ + /* * kmalloc_reserve is a wrapper around kmalloc_node_track_caller that tells * the caller if emergency pfmemalloc reserves are being used. If it is and @@ -1064,8 +1176,12 @@ static void skb_release_all(struct sk_buff *skb, enum skb_drop_reason reason, void __kfree_skb(struct sk_buff *skb) { + if (recycle_skb_oob(skb)) + return; + skb_release_all(skb, SKB_DROP_REASON_NOT_SPECIFIED, false); - kfree_skbmem(skb); + if (!__skb_oob_free_head(skb)) + kfree_skbmem(skb); } EXPORT_SYMBOL(__kfree_skb); @@ -1320,8 +1436,12 @@ static void napi_skb_cache_put(struct sk_buff *skb) void __napi_kfree_skb(struct sk_buff *skb, enum skb_drop_reason reason) { + if (recycle_skb_oob(skb)) + return; + skb_release_all(skb, reason, true); - napi_skb_cache_put(skb); + if (!__skb_oob_free_head(skb)) + napi_skb_cache_put(skb); } void napi_skb_free_stolen_head(struct sk_buff *skb) @@ -1344,7 +1464,7 @@ void napi_consume_skb(struct sk_buff *skb, int budget) return; } - DEBUG_NET_WARN_ON_ONCE(!in_softirq()); + DEBUG_NET_WARN_ON_ONCE(running_inband() && !in_softirq()); if (!skb_unref(skb)) return; @@ -1358,8 +1478,12 @@ void napi_consume_skb(struct sk_buff *skb, int budget) return; } + if (recycle_skb_oob(skb)) + return; + skb_release_all(skb, SKB_CONSUMED, !!budget); - napi_skb_cache_put(skb); + if (!__skb_oob_free_head(skb)) + napi_skb_cache_put(skb); } EXPORT_SYMBOL(napi_consume_skb); @@ -1915,6 +2039,8 @@ struct sk_buff *skb_clone(struct sk_buff *skb, gfp_t gfp_mask) n->fclone = SKB_FCLONE_UNAVAILABLE; } + __skb_inband_clone(n); + return __skb_clone(n, skb); } EXPORT_SYMBOL(skb_clone); @@ -2091,6 +2217,10 @@ int pskb_expand_head(struct sk_buff *skb, int nhead, int ntail, BUG_ON(skb_shared(skb)); + /* skb_reserve() is your friend for out-of-band operations. */ + if (skb_is_oob(skb)) + return -ENOMEM; + skb_zcopy_downgrade_managed(skb); if (skb_pfmemalloc(skb)) @@ -4872,6 +5002,8 @@ void __init skb_init(void) 0, SKB_SMALL_HEAD_HEADROOM, NULL); + init_oob_cache(); + skb_extensions_init(); } @@ -5734,8 +5866,11 @@ EXPORT_SYMBOL(__skb_warn_lro_forwarding); void kfree_skb_partial(struct sk_buff *skb, bool head_stolen) { if (head_stolen) { - skb_release_head_state(skb); - kmem_cache_free(skbuff_cache, skb); + if (!recycle_skb_oob(skb)) { + skb_release_head_state(skb); + if (!__skb_oob_free_head(skb)) + kmem_cache_free(skbuff_cache, skb); + } } else { __kfree_skb(skb); } @@ -6553,6 +6688,7 @@ static int pskb_carve_inside_nonlinear(struct sk_buff *skb, const u32 off, skb->len -= off; skb->data_len = skb->len; atomic_set(&skb_shinfo(skb)->dataref, 1); + return 0; } diff --git a/net/core/sock.c b/net/core/sock.c index 84ba3f67b..506f8df7e 100644 --- a/net/core/sock.c +++ b/net/core/sock.c @@ -2185,6 +2185,8 @@ static void __sk_destruct(struct rcu_head *head) struct sock *sk = container_of(head, struct sock, sk_rcu); struct sk_filter *filter; + sock_oob_destruct(sk); + if (sk->sk_destruct) sk->sk_destruct(sk); diff --git a/net/core/sysctl_net_core.c b/net/core/sysctl_net_core.c index 373b5b223..e6ab69517 100644 --- a/net/core/sysctl_net_core.c +++ b/net/core/sysctl_net_core.c @@ -662,6 +662,17 @@ static struct ctl_table net_core_table[] = { .proc_handler = proc_dointvec_minmax, .extra1 = SYSCTL_ZERO, }, +#ifdef CONFIG_NET_OOB + { + .procname = "max_oob_skb", + .data = &sysctl_max_oob_skb, + .maxlen = sizeof(unsigned int), + .mode = 0444, + .proc_handler = proc_dointvec_minmax, + .extra1 = SYSCTL_ONE_HUNDRED, + .extra2 = SYSCTL_INT_MAX, + }, +#endif { } }; diff --git a/net/ipv4/af_inet.c b/net/ipv4/af_inet.c index f336b2ddf..51975090d 100644 --- a/net/ipv4/af_inet.c +++ b/net/ipv4/af_inet.c @@ -557,6 +557,8 @@ int __inet_bind(struct sock *sk, struct sockaddr *uaddr, int addr_len, inet->inet_dport = 0; sk_dst_reset(sk); err = 0; + if (sock_oob_capable(sk->sk_socket)) + err = sock_oob_bind(sk, uaddr, addr_len); out_release_sock: if (flags & BIND_WITH_LOCK) release_sock(sk); @@ -936,6 +938,9 @@ int inet_shutdown(struct socket *sock, int how) break; } + if (!err && sock_oob_capable(sock)) + err = sock_oob_shutdown(sk, how); + /* Wake up anyone sleeping in poll. */ sk->sk_state_change(sk); release_sock(sk); diff --git a/net/ipv4/route.c b/net/ipv4/route.c index 285482060..504862f59 100644 --- a/net/ipv4/route.c +++ b/net/ipv4/route.c @@ -2861,6 +2861,14 @@ struct dst_entry *ipv4_blackhole_route(struct net *net, struct dst_entry *dst_or return rt ? &rt->dst : ERR_PTR(-ENOMEM); } +#ifdef CONFIG_NET_OOB +__weak +#else +static inline +#endif +void ip_learn_oob_route(struct net *net, struct flowi4 *flp4, struct rtable *rt) +{ } + struct rtable *ip_route_output_flow(struct net *net, struct flowi4 *flp4, const struct sock *sk) { @@ -2876,6 +2884,14 @@ struct rtable *ip_route_output_flow(struct net *net, struct flowi4 *flp4, sk, 0); } + /* + * If the route goes through an oob-enabled device, the oob + * core might want to learn about the routing decision, pass + * it on. + */ + if (!IS_ERR(rt) && netif_oob_port(rt->dst.dev)) + ip_learn_oob_route(net, flp4, rt); + return rt; } EXPORT_SYMBOL_GPL(ip_route_output_flow); diff --git a/net/packet/af_packet.c b/net/packet/af_packet.c index 4abf7e9ac..3faa9948c 100644 --- a/net/packet/af_packet.c +++ b/net/packet/af_packet.c @@ -3366,6 +3366,7 @@ static int packet_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len { struct sockaddr_ll *sll = (struct sockaddr_ll *)uaddr; struct sock *sk = sock->sk; + int ret; /* * Check legality @@ -3376,7 +3377,11 @@ static int packet_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len if (sll->sll_family != AF_PACKET) return -EINVAL; - return packet_do_bind(sk, NULL, sll->sll_ifindex, sll->sll_protocol); + ret = packet_do_bind(sk, NULL, sll->sll_ifindex, sll->sll_protocol); + if (sock_oob_capable(sk->sk_socket)) + ret = sock_oob_bind(sk, uaddr, addr_len); + + return ret; } static struct proto packet_proto = { @@ -3423,6 +3428,7 @@ static int packet_create(struct net *net, struct socket *sock, int protocol, init_completion(&po->skb_completion); sk->sk_family = PF_PACKET; + sk->sk_protocol = protocol; po->num = proto; packet_cached_dev_reset(po); diff --git a/net/socket.c b/net/socket.c index bad58f23f..066d7733b 100644 --- a/net/socket.c +++ b/net/socket.c @@ -146,6 +146,100 @@ static void sock_show_fdinfo(struct seq_file *m, struct file *f) #define sock_show_fdinfo NULL #endif +#ifdef CONFIG_NET_OOB + +int __weak sock_oob_attach(struct socket *sock) +{ + return 0; +} + +void __weak sock_oob_release(struct socket *sock) +{ +} + +void __weak sock_oob_destroy(struct sock *sk) +{ +} + +int __weak sock_oob_bind(struct sock *sk, struct sockaddr *addr, int len) +{ + return 0; +} + +int __weak sock_oob_shutdown(struct sock *sk, int how) +{ + return 0; +} + +int __weak sock_oob_connect(struct sock *sk, + struct sockaddr *addr, int len, int flags) +{ + return 0; +} + +long __weak sock_inband_ioctl_redirect(struct sock *sk, + unsigned int cmd, unsigned long arg) +{ + return -ENOTTY; +} + +long __weak sock_oob_ioctl(struct file *file, + unsigned int cmd, unsigned long arg) +{ + return -ENOTTY; +} + +ssize_t __weak sock_oob_write(struct file *filp, + const char __user *u_buf, size_t count) +{ + return -EOPNOTSUPP; +} + +ssize_t __weak sock_oob_read(struct file *filp, + char __user *u_buf, size_t count) +{ + return -EOPNOTSUPP; +} + +__poll_t __weak sock_oob_poll(struct file *filp, + struct oob_poll_wait *wait) +{ + return -EOPNOTSUPP; +} + +#define compat_sock_oob_ioctl compat_ptr_oob_ioctl + +#else /* !CONFIG_NET_OOB */ + +static inline int sock_oob_attach(struct socket *sock) +{ + return 0; +} + +static inline void sock_oob_release(struct socket *sock) +{ +} + +static inline int sock_oob_connect(struct sock *sk, + struct sockaddr *addr, int len, int flags) +{ + return 0; +} + +static inline long sock_inband_ioctl_redirect(struct sock *sk, + unsigned int cmd, unsigned long arg) +{ + return -ENOTTY; +} + +#define sock_oob_ioctl NULL +#define sock_oob_write NULL +#define sock_oob_read NULL +#define sock_oob_poll NULL +#define compat_sock_oob_ioctl NULL + +#endif /* !CONFIG_NET_OOB */ + /* * Socket files have a set of 'special' operations as well as the generic file ones. These don't appear * in the operation structures but are done directly via the socketcall() multiplexor. @@ -158,8 +252,13 @@ static const struct file_operations socket_file_ops = { .write_iter = sock_write_iter, .poll = sock_poll, .unlocked_ioctl = sock_ioctl, + .oob_ioctl = sock_oob_ioctl, + .oob_write = sock_oob_write, + .oob_read = sock_oob_read, + .oob_poll = sock_oob_poll, #ifdef CONFIG_COMPAT .compat_ioctl = compat_sock_ioctl, + .compat_oob_ioctl = compat_sock_oob_ioctl, #endif .uring_cmd = io_uring_cmd_sock, .mmap = sock_mmap, @@ -218,6 +317,7 @@ static const char * const pf_family_names[] = { [PF_SMC] = "PF_SMC", [PF_XDP] = "PF_XDP", [PF_MCTP] = "PF_MCTP", + [PF_OOB] = "PF_OOB", }; /* @@ -485,7 +585,7 @@ EXPORT_SYMBOL(sock_alloc_file); static int sock_map_fd(struct socket *sock, int flags) { struct file *newfile; - int fd = get_unused_fd_flags(flags); + int fd = get_unused_fd_flags(flags), ret; if (unlikely(fd < 0)) { sock_release(sock); return fd; @@ -493,6 +593,14 @@ static int sock_map_fd(struct socket *sock, int flags) newfile = sock_alloc_file(sock, flags, NULL); if (!IS_ERR(newfile)) { + if (IS_ENABLED(CONFIG_NET_OOB) && (flags & SOCK_OOB)) { + ret = sock_oob_attach(sock); + if (ret < 0) { + put_unused_fd(fd); + sock_release(sock); + return ret; + } + } fd_install(fd, newfile); return fd; } @@ -651,6 +759,9 @@ static void __sock_release(struct socket *sock, struct inode *inode) { const struct proto_ops *ops = READ_ONCE(sock->ops); + if (sock_oob_capable(sock)) + sock_oob_release(sock); + if (ops) { struct module *owner = ops->owner; @@ -1338,6 +1449,11 @@ static long sock_ioctl(struct file *file, unsigned cmd, unsigned long arg) break; default: + if (sock_oob_capable(sock)) { + err = sock_inband_ioctl_redirect(sock->sk, cmd, arg); + if (!err || err != -ENOIOCTLCMD) + break; + } err = sock_do_ioctl(net, sock, cmd, arg); break; } @@ -1656,8 +1772,9 @@ static struct socket *__sys_socket_create(int family, int type, int protocol) BUILD_BUG_ON((SOCK_MAX | SOCK_TYPE_MASK) != SOCK_TYPE_MASK); BUILD_BUG_ON(SOCK_CLOEXEC & SOCK_TYPE_MASK); BUILD_BUG_ON(SOCK_NONBLOCK & SOCK_TYPE_MASK); + BUILD_BUG_ON(SOCK_OOB & SOCK_TYPE_MASK); - if ((type & ~SOCK_TYPE_MASK) & ~(SOCK_CLOEXEC | SOCK_NONBLOCK)) + if ((type & ~SOCK_TYPE_MASK) & ~(SOCK_CLOEXEC | SOCK_NONBLOCK | SOCK_OOB)) return ERR_PTR(-EINVAL); type &= SOCK_TYPE_MASK; @@ -1721,7 +1838,7 @@ int __sys_socket(int family, int type, int protocol) if (SOCK_NONBLOCK != O_NONBLOCK && (flags & SOCK_NONBLOCK)) flags = (flags & ~SOCK_NONBLOCK) | O_NONBLOCK; - return sock_map_fd(sock, flags & (O_CLOEXEC | O_NONBLOCK)); + return sock_map_fd(sock, flags & (O_CLOEXEC | O_NONBLOCK | O_OOB)); } SYSCALL_DEFINE3(socket, int, family, int, type, int, protocol) @@ -2056,6 +2173,12 @@ int __sys_connect_file(struct file *file, struct sockaddr_storage *address, err = READ_ONCE(sock->ops)->connect(sock, (struct sockaddr *)address, addrlen, sock->file->f_flags | file_flags); + if (!err && sock_oob_capable(sock)) { + err = sock_oob_connect(sock->sk, (struct sockaddr *)address, + addrlen, sock->file->f_flags | file_flags); + if (err) + goto out; + } out: return err; } diff --git a/scripts/dovetail-guest.sh b/scripts/dovetail-guest.sh new file mode 100755 index 000000000..175d9de69 --- /dev/null +++ b/scripts/dovetail-guest.sh @@ -0,0 +1 @@ +echo EVL diff --git a/scripts/git-evlabi b/scripts/git-evlabi new file mode 100644 index 000000000..7df080b6e --- /dev/null +++ b/scripts/git-evlabi @@ -0,0 +1,128 @@ +#! /bin/sh +# SPDX-License-Identifier: MIT + +usage() { + echo >&2 "usage: $(basename $1) [-r ][--git-dir ][-s][-h] []" +} + +args=$(getopt -n $(basename $0) -l 'git-dir:' -o 'r:sh' -- "$@") +if [ $? -ne 0 ]; then + usage $0 + exit 1 +fi + +object=HEAD +help=false +abi=rev +addlog= +git_dir=.git + +set -- $args +for opt in "$@" +do +case "$opt" in + --git-dir) git_dir=$(eval echo $2); + shift + shift;; + -r) s=$(eval echo $2); + abirev=$(expr "$s" : '\([0-9]\+\)') + if test ! "$s" = "$abirev"; then + echo >&2 "$0: invalid ABI revision number ($s)" + exit 2 + fi + shift + shift;; + -s) addlog=y + shift;; + -h) help=true; + shift;; + --) shift; break;; + esac +done + +if test x$help = xtrue; then + usage $0 + echo >&2 + echo >&2 "Look for ABI definition/prereq in either linux-evl/libevl trees:" + echo >&2 " - at position if is a commit SHA-1 hash" + echo >&2 " - in the commit history if matches a refname" + echo >&2 + echo >&2 "The output is of the form:" + echo >&2 " []" + echo >&2 + echo >&2 "where is the predecessor to the earliest commit" + echo >&2 " implementing/requesting the ABI revision" + echo >&2 " is the span of the ABI revision" + echo >&2 " is the ABI revision number" + echo >&2 " is the subject line describing " + echo >&2 + echo >&2 "Use -r to look for a particular ABI revision" + echo >&2 " -s to add the shortlog to the output" + echo >&2 " --git-dir sets the path to the repository" + echo >&2 + echo >&2 "# Retrieve all ABI definitions from linux-evl evl/master:" + echo >&2 "\$ git evlabi evl/master" + echo >&2 + echo >&2 "# Retrieve start of ABI 12 into linux-evl evl/next:" + echo >&2 "\$ git evlabi -r 12 evl/next" + echo >&2 + echo >&2 "# Look up for ABI prereq at HEAD of libevl master:" + echo >&2 "\$ git evlabi" + echo >&2 + exit 0 +fi + +if test "$1" = "--"; then + shift +fi + +if test $# -gt 0; then + if test $# -gt 1; then + usage $0 + exit 1 + fi + object=$(eval echo $1) +fi + +GIT="git --git-dir=$git_dir" + +scan_history() { + sym=$1 + file=$2 + end=$($GIT rev-parse --abbrev-ref $object) + depth= + if test -z "$end"; then + end=$object + depth=-1 + fi + end=$($GIT rev-parse --short $end) + reflist=$($GIT log $depth -G $sym --pretty=tformat:'%h %s' $object -- $file | \ + while read hash shortlog + do + rev=$($GIT show -1 -p --pretty=tformat: $hash -- $file|\ + grep "^+#define $sym"|\ + sed -e "s,^\+#define $sym[ ]*\([0-9]\+\).*$,\1,") + test -z "$rev" && continue + start=$($GIT rev-parse --short $hash^) + echo $hash $start..$end "$(printf "%3d " $rev)${addlog:+$shortlog}" + end=$($GIT rev-parse --short $start) + done) + if test -n "$abirev"; then + echo "$reflist" | grep -w "[a-f0-9]+ [a-f0-9]+\.\.[a-f0-9]+[ ]+$abirev[^ ]*" + else + echo "$reflist" + fi +} + +if $GIT rev-parse -q --no-revs --verify $object:include/uapi/evl/control-abi.h; then + result=$(scan_history EVL_ABI_LEVEL include/uapi/evl/control-abi.h) + test -n "$result" && echo "$result" +elif $GIT rev-parse -q --no-revs --verify $object:include/evl/evl.h; then + result=$(scan_history EVL_ABI_PREREQ include/evl/evl.h) + test -n "$result" && echo "$result" +else + echo "cannot parse - either tree or $object is wrong" + exit 1 +fi + +exit 0 diff --git a/scripts/setlocalversion b/scripts/setlocalversion index 5818465ab..b7cef30e8 100755 --- a/scripts/setlocalversion +++ b/scripts/setlocalversion @@ -113,7 +113,7 @@ scm_version() # If only the short version is requested, don't bother # running further git commands if $short; then - echo "+" + # echo "+" return fi diff --git a/security/selinux/hooks.c b/security/selinux/hooks.c index d4a99d98e..ff061041c 100644 --- a/security/selinux/hooks.c +++ b/security/selinux/hooks.c @@ -1295,7 +1295,9 @@ static inline u16 socket_type_to_security_class(int family, int type, int protoc return SECCLASS_XDP_SOCKET; case PF_MCTP: return SECCLASS_MCTP_SOCKET; -#if PF_MAX > 46 + case PF_OOB: + return SECCLASS_OOB_SOCKET; +#if PF_MAX > 47 #error New address family defined, please update this function. #endif } diff --git a/security/selinux/include/classmap.h b/security/selinux/include/classmap.h index a3c380775..bc2c7b50c 100644 --- a/security/selinux/include/classmap.h +++ b/security/selinux/include/classmap.h @@ -248,6 +248,8 @@ const struct security_class_mapping secclass_map[] = { { COMMON_SOCK_PERMS, NULL } }, { "mctp_socket", { COMMON_SOCK_PERMS, NULL } }, + { "oob_socket", + { COMMON_SOCK_PERMS, NULL } }, { "perf_event", { "open", "cpu", "kernel", "tracepoint", "read", "write", NULL } }, { "anon_inode", @@ -259,6 +261,6 @@ const struct security_class_mapping secclass_map[] = { { NULL } }; -#if PF_MAX > 46 +#if PF_MAX > 47 #error New address family defined, please update secclass_map. #endif diff --git a/tools/perf/trace/beauty/include/linux/socket.h b/tools/perf/trace/beauty/include/linux/socket.h index 39b74d83c..47a96afe5 100644 --- a/tools/perf/trace/beauty/include/linux/socket.h +++ b/tools/perf/trace/beauty/include/linux/socket.h @@ -239,8 +239,9 @@ struct ucred { #define AF_MCTP 45 /* Management component * transport protocol */ +#define AF_OOB 46 /* Out-of-band domain sockets */ -#define AF_MAX 46 /* For now.. */ +#define AF_MAX 47 /* For now.. */ /* Protocol families, same as address families. */ #define PF_UNSPEC AF_UNSPEC