xref: /openbmc/linux/arch/mips/math-emu/dsemul.c (revision 589ee62844e042b0b7d19ef57fb4cff77f3ca294)
1 #include <linux/err.h>
2 #include <linux/slab.h>
3 #include <linux/mm_types.h>
4 
5 #include <asm/branch.h>
6 #include <asm/cacheflush.h>
7 #include <asm/fpu_emulator.h>
8 #include <asm/inst.h>
9 #include <asm/mipsregs.h>
10 #include <linux/uaccess.h>
11 
12 /**
13  * struct emuframe - The 'emulation' frame structure
14  * @emul:	The instruction to 'emulate'.
15  * @badinst:	A break instruction to cause a return to the kernel.
16  *
17  * This structure defines the frames placed within the delay slot emulation
18  * page in response to a call to mips_dsemul(). Each thread may be allocated
19  * only one frame at any given time. The kernel stores within it the
20  * instruction to be 'emulated' followed by a break instruction, then
21  * executes the frame in user mode. The break causes a trap to the kernel
22  * which leads to do_dsemulret() being called unless the instruction in
23  * @emul causes a trap itself, is a branch, or a signal is delivered to
24  * the thread. In these cases the allocated frame will either be reused by
25  * a subsequent delay slot 'emulation', or be freed during signal delivery or
26  * upon thread exit.
27  *
28  * This approach is used because:
29  *
30  * - Actually emulating all instructions isn't feasible. We would need to
31  *   be able to handle instructions from all revisions of the MIPS ISA,
32  *   all ASEs & all vendor instruction set extensions. This would be a
33  *   whole lot of work & continual maintenance burden as new instructions
34  *   are introduced, and in the case of some vendor extensions may not
35  *   even be possible. Thus we need to take the approach of actually
36  *   executing the instruction.
37  *
38  * - We must execute the instruction within user context. If we were to
39  *   execute the instruction in kernel mode then it would have access to
40  *   kernel resources without very careful checks, leaving us with a
41  *   high potential for security or stability issues to arise.
42  *
43  * - We used to place the frame on the users stack, but this requires
44  *   that the stack be executable. This is bad for security so the
45  *   per-process page is now used instead.
46  *
47  * - The instruction in @emul may be something entirely invalid for a
48  *   delay slot. The user may (intentionally or otherwise) place a branch
49  *   in a delay slot, or a kernel mode instruction, or something else
50  *   which generates an exception. Thus we can't rely upon the break in
51  *   @badinst always being hit. For this reason we track the index of the
52  *   frame allocated to each thread, allowing us to clean it up at later
53  *   points such as signal delivery or thread exit.
54  *
55  * - The user may generate a fake struct emuframe if they wish, invoking
56  *   the BRK_MEMU break instruction themselves. We must therefore not
57  *   trust that BRK_MEMU means there's actually a valid frame allocated
58  *   to the thread, and must not allow the user to do anything they
59  *   couldn't already.
60  */
61 struct emuframe {
62 	mips_instruction	emul;
63 	mips_instruction	badinst;
64 };
65 
66 static const int emupage_frame_count = PAGE_SIZE / sizeof(struct emuframe);
67 
68 static inline __user struct emuframe *dsemul_page(void)
69 {
70 	return (__user struct emuframe *)STACK_TOP;
71 }
72 
73 static int alloc_emuframe(void)
74 {
75 	mm_context_t *mm_ctx = &current->mm->context;
76 	int idx;
77 
78 retry:
79 	spin_lock(&mm_ctx->bd_emupage_lock);
80 
81 	/* Ensure we have an allocation bitmap */
82 	if (!mm_ctx->bd_emupage_allocmap) {
83 		mm_ctx->bd_emupage_allocmap =
84 			kcalloc(BITS_TO_LONGS(emupage_frame_count),
85 					      sizeof(unsigned long),
86 				GFP_ATOMIC);
87 
88 		if (!mm_ctx->bd_emupage_allocmap) {
89 			idx = BD_EMUFRAME_NONE;
90 			goto out_unlock;
91 		}
92 	}
93 
94 	/* Attempt to allocate a single bit/frame */
95 	idx = bitmap_find_free_region(mm_ctx->bd_emupage_allocmap,
96 				      emupage_frame_count, 0);
97 	if (idx < 0) {
98 		/*
99 		 * Failed to allocate a frame. We'll wait until one becomes
100 		 * available. We unlock the page so that other threads actually
101 		 * get the opportunity to free their frames, which means
102 		 * technically the result of bitmap_full may be incorrect.
103 		 * However the worst case is that we repeat all this and end up
104 		 * back here again.
105 		 */
106 		spin_unlock(&mm_ctx->bd_emupage_lock);
107 		if (!wait_event_killable(mm_ctx->bd_emupage_queue,
108 			!bitmap_full(mm_ctx->bd_emupage_allocmap,
109 				     emupage_frame_count)))
110 			goto retry;
111 
112 		/* Received a fatal signal - just give in */
113 		return BD_EMUFRAME_NONE;
114 	}
115 
116 	/* Success! */
117 	pr_debug("allocate emuframe %d to %d\n", idx, current->pid);
118 out_unlock:
119 	spin_unlock(&mm_ctx->bd_emupage_lock);
120 	return idx;
121 }
122 
123 static void free_emuframe(int idx, struct mm_struct *mm)
124 {
125 	mm_context_t *mm_ctx = &mm->context;
126 
127 	spin_lock(&mm_ctx->bd_emupage_lock);
128 
129 	pr_debug("free emuframe %d from %d\n", idx, current->pid);
130 	bitmap_clear(mm_ctx->bd_emupage_allocmap, idx, 1);
131 
132 	/* If some thread is waiting for a frame, now's its chance */
133 	wake_up(&mm_ctx->bd_emupage_queue);
134 
135 	spin_unlock(&mm_ctx->bd_emupage_lock);
136 }
137 
138 static bool within_emuframe(struct pt_regs *regs)
139 {
140 	unsigned long base = (unsigned long)dsemul_page();
141 
142 	if (regs->cp0_epc < base)
143 		return false;
144 	if (regs->cp0_epc >= (base + PAGE_SIZE))
145 		return false;
146 
147 	return true;
148 }
149 
150 bool dsemul_thread_cleanup(struct task_struct *tsk)
151 {
152 	int fr_idx;
153 
154 	/* Clear any allocated frame, retrieving its index */
155 	fr_idx = atomic_xchg(&tsk->thread.bd_emu_frame, BD_EMUFRAME_NONE);
156 
157 	/* If no frame was allocated, we're done */
158 	if (fr_idx == BD_EMUFRAME_NONE)
159 		return false;
160 
161 	task_lock(tsk);
162 
163 	/* Free the frame that this thread had allocated */
164 	if (tsk->mm)
165 		free_emuframe(fr_idx, tsk->mm);
166 
167 	task_unlock(tsk);
168 	return true;
169 }
170 
171 bool dsemul_thread_rollback(struct pt_regs *regs)
172 {
173 	struct emuframe __user *fr;
174 	int fr_idx;
175 
176 	/* Do nothing if we're not executing from a frame */
177 	if (!within_emuframe(regs))
178 		return false;
179 
180 	/* Find the frame being executed */
181 	fr_idx = atomic_read(&current->thread.bd_emu_frame);
182 	if (fr_idx == BD_EMUFRAME_NONE)
183 		return false;
184 	fr = &dsemul_page()[fr_idx];
185 
186 	/*
187 	 * If the PC is at the emul instruction, roll back to the branch. If
188 	 * PC is at the badinst (break) instruction, we've already emulated the
189 	 * instruction so progress to the continue PC. If it's anything else
190 	 * then something is amiss & the user has branched into some other area
191 	 * of the emupage - we'll free the allocated frame anyway.
192 	 */
193 	if (msk_isa16_mode(regs->cp0_epc) == (unsigned long)&fr->emul)
194 		regs->cp0_epc = current->thread.bd_emu_branch_pc;
195 	else if (msk_isa16_mode(regs->cp0_epc) == (unsigned long)&fr->badinst)
196 		regs->cp0_epc = current->thread.bd_emu_cont_pc;
197 
198 	atomic_set(&current->thread.bd_emu_frame, BD_EMUFRAME_NONE);
199 	free_emuframe(fr_idx, current->mm);
200 	return true;
201 }
202 
203 void dsemul_mm_cleanup(struct mm_struct *mm)
204 {
205 	mm_context_t *mm_ctx = &mm->context;
206 
207 	kfree(mm_ctx->bd_emupage_allocmap);
208 }
209 
210 int mips_dsemul(struct pt_regs *regs, mips_instruction ir,
211 		unsigned long branch_pc, unsigned long cont_pc)
212 {
213 	int isa16 = get_isa16_mode(regs->cp0_epc);
214 	mips_instruction break_math;
215 	struct emuframe __user *fr;
216 	int err, fr_idx;
217 
218 	/* NOP is easy */
219 	if (ir == 0)
220 		return -1;
221 
222 	/* microMIPS instructions */
223 	if (isa16) {
224 		union mips_instruction insn = { .word = ir };
225 
226 		/* NOP16 aka MOVE16 $0, $0 */
227 		if ((ir >> 16) == MM_NOP16)
228 			return -1;
229 
230 		/* ADDIUPC */
231 		if (insn.mm_a_format.opcode == mm_addiupc_op) {
232 			unsigned int rs;
233 			s32 v;
234 
235 			rs = (((insn.mm_a_format.rs + 0xe) & 0xf) + 2);
236 			v = regs->cp0_epc & ~3;
237 			v += insn.mm_a_format.simmediate << 2;
238 			regs->regs[rs] = (long)v;
239 			return -1;
240 		}
241 	}
242 
243 	pr_debug("dsemul 0x%08lx cont at 0x%08lx\n", regs->cp0_epc, cont_pc);
244 
245 	/* Allocate a frame if we don't already have one */
246 	fr_idx = atomic_read(&current->thread.bd_emu_frame);
247 	if (fr_idx == BD_EMUFRAME_NONE)
248 		fr_idx = alloc_emuframe();
249 	if (fr_idx == BD_EMUFRAME_NONE)
250 		return SIGBUS;
251 	fr = &dsemul_page()[fr_idx];
252 
253 	/* Retrieve the appropriately encoded break instruction */
254 	break_math = BREAK_MATH(isa16);
255 
256 	/* Write the instructions to the frame */
257 	if (isa16) {
258 		err = __put_user(ir >> 16,
259 				 (u16 __user *)(&fr->emul));
260 		err |= __put_user(ir & 0xffff,
261 				  (u16 __user *)((long)(&fr->emul) + 2));
262 		err |= __put_user(break_math >> 16,
263 				  (u16 __user *)(&fr->badinst));
264 		err |= __put_user(break_math & 0xffff,
265 				  (u16 __user *)((long)(&fr->badinst) + 2));
266 	} else {
267 		err = __put_user(ir, &fr->emul);
268 		err |= __put_user(break_math, &fr->badinst);
269 	}
270 
271 	if (unlikely(err)) {
272 		MIPS_FPU_EMU_INC_STATS(errors);
273 		free_emuframe(fr_idx, current->mm);
274 		return SIGBUS;
275 	}
276 
277 	/* Record the PC of the branch, PC to continue from & frame index */
278 	current->thread.bd_emu_branch_pc = branch_pc;
279 	current->thread.bd_emu_cont_pc = cont_pc;
280 	atomic_set(&current->thread.bd_emu_frame, fr_idx);
281 
282 	/* Change user register context to execute the frame */
283 	regs->cp0_epc = (unsigned long)&fr->emul | isa16;
284 
285 	/* Ensure the icache observes our newly written frame */
286 	flush_cache_sigtramp((unsigned long)&fr->emul);
287 
288 	return 0;
289 }
290 
291 bool do_dsemulret(struct pt_regs *xcp)
292 {
293 	/* Cleanup the allocated frame, returning if there wasn't one */
294 	if (!dsemul_thread_cleanup(current)) {
295 		MIPS_FPU_EMU_INC_STATS(errors);
296 		return false;
297 	}
298 
299 	/* Set EPC to return to post-branch instruction */
300 	xcp->cp0_epc = current->thread.bd_emu_cont_pc;
301 	pr_debug("dsemulret to 0x%08lx\n", xcp->cp0_epc);
302 	MIPS_FPU_EMU_INC_STATS(ds_emul);
303 	return true;
304 }
305