[patch 14/15] x86/entry: Provide return_from exception()

From: Thomas Gleixner
Date: Tue Feb 25 2020 - 18:27:32 EST


Now that all exceptions, interrupts and system vectors are using the
IDTENTRY machinery, the return from exception handling in ASM can be lifted
to C.

Provide a C function which:

- Invokes prepare_exit_to_user_mode() when the exception hit user mode
- Checks for preemption when the exception hit kernel mode
- Has the interrupt tracing in C

Signed-off-by: Thomas Gleixner <tglx@xxxxxxxxxxxxx>
---
arch/x86/entry/common.c | 43 ++++++++++++++++++++++++++++++++++++++++
arch/x86/include/asm/idtentry.h | 2 +
2 files changed, 45 insertions(+)

--- a/arch/x86/entry/common.c
+++ b/arch/x86/entry/common.c
@@ -480,3 +480,46 @@ static __always_inline long do_fast_sysc
NOKPROBE_SYMBOL(do_fast_syscall_32);

#endif /* CONFIG_X86_32 || CONFIG_IA32_EMULATION */
+
+/**
+ * return_from_exception - Common code to handle return from exceptions
+ * @regs - Pointer to pt_regs (exception entry regs)
+ *
+ * Depending on the return target (kernel/user) this runs the necessary
+ * preemption and work checks if possible and reguired and returns to
+ * the caller with interrupts disabled and no further work pending.
+ *
+ * This is the last action before returning to the low level ASM code which
+ * just needs to return to the appropriate context.
+ *
+ * Invoked by all exception/interrupt IDTENTRY handlers which are not
+ * returning through the paranoid exit path (all except NMI, MCE, DF).
+ */
+void notrace return_from_exception(struct pt_regs *regs)
+{
+ /*
+ * Unconditionally disable interrupts as some handlers like
+ * the fault handler are not guaranteeing to return with
+ * interrupts disabled.
+ */
+ local_irq_disable();
+
+ /* Check whether this returns to user mode */
+ if (user_mode(regs)) {
+ prepare_exit_to_usermode(regs);
+ } else {
+ /* Interrupts stay disabled on return? */
+ if (!(regs->flags & X86_EFLAGS_IF))
+ return;
+
+ /* Check kernel preemption, if enabled */
+ if (IS_ENABLED(CONFIG_PREEMPTION)) {
+ /* Check for preemption */
+ if (!preempt_count() && need_resched())
+ preempt_schedule_irq();
+ }
+ }
+ /* Make sure the tracer knows that IRET will enable interrupts */
+ trace_hardirqs_on();
+}
+NOKPROBE_SYMBOL(return_from_exception);
--- a/arch/x86/include/asm/idtentry.h
+++ b/arch/x86/include/asm/idtentry.h
@@ -19,6 +19,8 @@ static __always_inline void enter_from_u
static __always_inline void enter_from_user_context(void) { }
#endif

+void return_from_exception(struct pt_regs *regs);
+
/**
* idtentry_enter - Handle state tracking on idtentry
* @regs: Pointer to pt_regs of interrupted context