xref: /linux/arch/riscv/include/asm/switch_to.h (revision be3382ecdf317f005e7d47356d0a9256cc36dd88)
1 /* SPDX-License-Identifier: GPL-2.0-only */
2 /*
3  * Copyright (C) 2012 Regents of the University of California
4  */
5 
6 #ifndef _ASM_RISCV_SWITCH_TO_H
7 #define _ASM_RISCV_SWITCH_TO_H
8 
9 #include <linux/jump_label.h>
10 #include <linux/sched/task_stack.h>
11 #include <asm/vector.h>
12 #include <asm/cpufeature.h>
13 #include <asm/processor.h>
14 #include <asm/ptrace.h>
15 #include <asm/csr.h>
16 
17 #ifdef CONFIG_FPU
18 extern void __fstate_save(struct task_struct *save_to);
19 extern void __fstate_restore(struct task_struct *restore_from);
20 
21 static inline void __fstate_clean(struct pt_regs *regs)
22 {
23 	regs->status = (regs->status & ~SR_FS) | SR_FS_CLEAN;
24 }
25 
26 static inline void fstate_off(struct task_struct *task,
27 			      struct pt_regs *regs)
28 {
29 	regs->status = (regs->status & ~SR_FS) | SR_FS_OFF;
30 }
31 
32 static inline void fstate_save(struct task_struct *task,
33 			       struct pt_regs *regs)
34 {
35 	if ((regs->status & SR_FS) == SR_FS_DIRTY) {
36 		__fstate_save(task);
37 		__fstate_clean(regs);
38 	}
39 }
40 
41 static inline void fstate_restore(struct task_struct *task,
42 				  struct pt_regs *regs)
43 {
44 	if ((regs->status & SR_FS) != SR_FS_OFF) {
45 		__fstate_restore(task);
46 		__fstate_clean(regs);
47 	}
48 }
49 
50 static inline void __switch_to_fpu(struct task_struct *prev,
51 				   struct task_struct *next)
52 {
53 	struct pt_regs *regs;
54 
55 	regs = task_pt_regs(prev);
56 	fstate_save(prev, regs);
57 	fstate_restore(next, task_pt_regs(next));
58 }
59 
60 static __always_inline bool has_fpu(void)
61 {
62 	return riscv_has_extension_likely(RISCV_ISA_EXT_f) ||
63 		riscv_has_extension_likely(RISCV_ISA_EXT_d);
64 }
65 #else
66 static __always_inline bool has_fpu(void) { return false; }
67 #define fstate_save(task, regs) do { } while (0)
68 #define fstate_restore(task, regs) do { } while (0)
69 #define __switch_to_fpu(__prev, __next) do { } while (0)
70 #endif
71 
72 extern struct task_struct *__switch_to(struct task_struct *,
73 				       struct task_struct *);
74 
75 #define switch_to(prev, next, last)			\
76 do {							\
77 	struct task_struct *__prev = (prev);		\
78 	struct task_struct *__next = (next);		\
79 	if (has_fpu())					\
80 		__switch_to_fpu(__prev, __next);	\
81 	if (has_vector())					\
82 		__switch_to_vector(__prev, __next);	\
83 	((last) = __switch_to(__prev, __next));		\
84 } while (0)
85 
86 #endif /* _ASM_RISCV_SWITCH_TO_H */
87