xref: /linux-6.15/kernel/rseq.c (revision 60af388d)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Restartable sequences system call
4  *
5  * Copyright (C) 2015, Google, Inc.,
6  * Paul Turner <[email protected]> and Andrew Hunter <[email protected]>
7  * Copyright (C) 2015-2018, EfficiOS Inc.,
8  * Mathieu Desnoyers <[email protected]>
9  */
10 
11 #include <linux/sched.h>
12 #include <linux/uaccess.h>
13 #include <linux/syscalls.h>
14 #include <linux/rseq.h>
15 #include <linux/types.h>
16 #include <asm/ptrace.h>
17 
18 #define CREATE_TRACE_POINTS
19 #include <trace/events/rseq.h>
20 
21 #define RSEQ_CS_PREEMPT_MIGRATE_FLAGS (RSEQ_CS_FLAG_NO_RESTART_ON_MIGRATE | \
22 				       RSEQ_CS_FLAG_NO_RESTART_ON_PREEMPT)
23 
24 /*
25  *
26  * Restartable sequences are a lightweight interface that allows
27  * user-level code to be executed atomically relative to scheduler
28  * preemption and signal delivery. Typically used for implementing
29  * per-cpu operations.
30  *
31  * It allows user-space to perform update operations on per-cpu data
32  * without requiring heavy-weight atomic operations.
33  *
34  * Detailed algorithm of rseq user-space assembly sequences:
35  *
36  *                     init(rseq_cs)
37  *                     cpu = TLS->rseq::cpu_id_start
38  *   [1]               TLS->rseq::rseq_cs = rseq_cs
39  *   [start_ip]        ----------------------------
40  *   [2]               if (cpu != TLS->rseq::cpu_id)
41  *                             goto abort_ip;
42  *   [3]               <last_instruction_in_cs>
43  *   [post_commit_ip]  ----------------------------
44  *
45  *   The address of jump target abort_ip must be outside the critical
46  *   region, i.e.:
47  *
48  *     [abort_ip] < [start_ip]  || [abort_ip] >= [post_commit_ip]
49  *
50  *   Steps [2]-[3] (inclusive) need to be a sequence of instructions in
51  *   userspace that can handle being interrupted between any of those
52  *   instructions, and then resumed to the abort_ip.
53  *
54  *   1.  Userspace stores the address of the struct rseq_cs assembly
55  *       block descriptor into the rseq_cs field of the registered
56  *       struct rseq TLS area. This update is performed through a single
57  *       store within the inline assembly instruction sequence.
58  *       [start_ip]
59  *
60  *   2.  Userspace tests to check whether the current cpu_id field match
61  *       the cpu number loaded before start_ip, branching to abort_ip
62  *       in case of a mismatch.
63  *
64  *       If the sequence is preempted or interrupted by a signal
65  *       at or after start_ip and before post_commit_ip, then the kernel
66  *       clears TLS->__rseq_abi::rseq_cs, and sets the user-space return
67  *       ip to abort_ip before returning to user-space, so the preempted
68  *       execution resumes at abort_ip.
69  *
70  *   3.  Userspace critical section final instruction before
71  *       post_commit_ip is the commit. The critical section is
72  *       self-terminating.
73  *       [post_commit_ip]
74  *
75  *   4.  <success>
76  *
77  *   On failure at [2], or if interrupted by preempt or signal delivery
78  *   between [1] and [3]:
79  *
80  *       [abort_ip]
81  *   F1. <failure>
82  */
83 
84 static int rseq_update_cpu_id(struct task_struct *t)
85 {
86 	u32 cpu_id = raw_smp_processor_id();
87 	struct rseq __user *rseq = t->rseq;
88 
89 	if (!user_write_access_begin(rseq, sizeof(*rseq)))
90 		goto efault;
91 	unsafe_put_user(cpu_id, &rseq->cpu_id_start, efault_end);
92 	unsafe_put_user(cpu_id, &rseq->cpu_id, efault_end);
93 	user_write_access_end();
94 	trace_rseq_update(t);
95 	return 0;
96 
97 efault_end:
98 	user_write_access_end();
99 efault:
100 	return -EFAULT;
101 }
102 
103 static int rseq_reset_rseq_cpu_id(struct task_struct *t)
104 {
105 	u32 cpu_id_start = 0, cpu_id = RSEQ_CPU_ID_UNINITIALIZED;
106 
107 	/*
108 	 * Reset cpu_id_start to its initial state (0).
109 	 */
110 	if (put_user(cpu_id_start, &t->rseq->cpu_id_start))
111 		return -EFAULT;
112 	/*
113 	 * Reset cpu_id to RSEQ_CPU_ID_UNINITIALIZED, so any user coming
114 	 * in after unregistration can figure out that rseq needs to be
115 	 * registered again.
116 	 */
117 	if (put_user(cpu_id, &t->rseq->cpu_id))
118 		return -EFAULT;
119 	return 0;
120 }
121 
122 static int rseq_get_rseq_cs(struct task_struct *t, struct rseq_cs *rseq_cs)
123 {
124 	struct rseq_cs __user *urseq_cs;
125 	u64 ptr;
126 	u32 __user *usig;
127 	u32 sig;
128 	int ret;
129 
130 	if (copy_from_user(&ptr, &t->rseq->rseq_cs.ptr64, sizeof(ptr)))
131 		return -EFAULT;
132 	if (!ptr) {
133 		memset(rseq_cs, 0, sizeof(*rseq_cs));
134 		return 0;
135 	}
136 	if (ptr >= TASK_SIZE)
137 		return -EINVAL;
138 	urseq_cs = (struct rseq_cs __user *)(unsigned long)ptr;
139 	if (copy_from_user(rseq_cs, urseq_cs, sizeof(*rseq_cs)))
140 		return -EFAULT;
141 
142 	if (rseq_cs->start_ip >= TASK_SIZE ||
143 	    rseq_cs->start_ip + rseq_cs->post_commit_offset >= TASK_SIZE ||
144 	    rseq_cs->abort_ip >= TASK_SIZE ||
145 	    rseq_cs->version > 0)
146 		return -EINVAL;
147 	/* Check for overflow. */
148 	if (rseq_cs->start_ip + rseq_cs->post_commit_offset < rseq_cs->start_ip)
149 		return -EINVAL;
150 	/* Ensure that abort_ip is not in the critical section. */
151 	if (rseq_cs->abort_ip - rseq_cs->start_ip < rseq_cs->post_commit_offset)
152 		return -EINVAL;
153 
154 	usig = (u32 __user *)(unsigned long)(rseq_cs->abort_ip - sizeof(u32));
155 	ret = get_user(sig, usig);
156 	if (ret)
157 		return ret;
158 
159 	if (current->rseq_sig != sig) {
160 		printk_ratelimited(KERN_WARNING
161 			"Possible attack attempt. Unexpected rseq signature 0x%x, expecting 0x%x (pid=%d, addr=%p).\n",
162 			sig, current->rseq_sig, current->pid, usig);
163 		return -EINVAL;
164 	}
165 	return 0;
166 }
167 
168 static int rseq_need_restart(struct task_struct *t, u32 cs_flags)
169 {
170 	u32 flags, event_mask;
171 	int ret;
172 
173 	/* Get thread flags. */
174 	ret = get_user(flags, &t->rseq->flags);
175 	if (ret)
176 		return ret;
177 
178 	/* Take critical section flags into account. */
179 	flags |= cs_flags;
180 
181 	/*
182 	 * Restart on signal can only be inhibited when restart on
183 	 * preempt and restart on migrate are inhibited too. Otherwise,
184 	 * a preempted signal handler could fail to restart the prior
185 	 * execution context on sigreturn.
186 	 */
187 	if (unlikely((flags & RSEQ_CS_FLAG_NO_RESTART_ON_SIGNAL) &&
188 		     (flags & RSEQ_CS_PREEMPT_MIGRATE_FLAGS) !=
189 		     RSEQ_CS_PREEMPT_MIGRATE_FLAGS))
190 		return -EINVAL;
191 
192 	/*
193 	 * Load and clear event mask atomically with respect to
194 	 * scheduler preemption.
195 	 */
196 	preempt_disable();
197 	event_mask = t->rseq_event_mask;
198 	t->rseq_event_mask = 0;
199 	preempt_enable();
200 
201 	return !!(event_mask & ~flags);
202 }
203 
204 static int clear_rseq_cs(struct task_struct *t)
205 {
206 	/*
207 	 * The rseq_cs field is set to NULL on preemption or signal
208 	 * delivery on top of rseq assembly block, as well as on top
209 	 * of code outside of the rseq assembly block. This performs
210 	 * a lazy clear of the rseq_cs field.
211 	 *
212 	 * Set rseq_cs to NULL.
213 	 */
214 	if (clear_user(&t->rseq->rseq_cs.ptr64, sizeof(t->rseq->rseq_cs.ptr64)))
215 		return -EFAULT;
216 	return 0;
217 }
218 
219 /*
220  * Unsigned comparison will be true when ip >= start_ip, and when
221  * ip < start_ip + post_commit_offset.
222  */
223 static bool in_rseq_cs(unsigned long ip, struct rseq_cs *rseq_cs)
224 {
225 	return ip - rseq_cs->start_ip < rseq_cs->post_commit_offset;
226 }
227 
228 static int rseq_ip_fixup(struct pt_regs *regs)
229 {
230 	unsigned long ip = instruction_pointer(regs);
231 	struct task_struct *t = current;
232 	struct rseq_cs rseq_cs;
233 	int ret;
234 
235 	ret = rseq_get_rseq_cs(t, &rseq_cs);
236 	if (ret)
237 		return ret;
238 
239 	/*
240 	 * Handle potentially not being within a critical section.
241 	 * If not nested over a rseq critical section, restart is useless.
242 	 * Clear the rseq_cs pointer and return.
243 	 */
244 	if (!in_rseq_cs(ip, &rseq_cs))
245 		return clear_rseq_cs(t);
246 	ret = rseq_need_restart(t, rseq_cs.flags);
247 	if (ret <= 0)
248 		return ret;
249 	ret = clear_rseq_cs(t);
250 	if (ret)
251 		return ret;
252 	trace_rseq_ip_fixup(ip, rseq_cs.start_ip, rseq_cs.post_commit_offset,
253 			    rseq_cs.abort_ip);
254 	instruction_pointer_set(regs, (unsigned long)rseq_cs.abort_ip);
255 	return 0;
256 }
257 
258 /*
259  * This resume handler must always be executed between any of:
260  * - preemption,
261  * - signal delivery,
262  * and return to user-space.
263  *
264  * This is how we can ensure that the entire rseq critical section
265  * will issue the commit instruction only if executed atomically with
266  * respect to other threads scheduled on the same CPU, and with respect
267  * to signal handlers.
268  */
269 void __rseq_handle_notify_resume(struct ksignal *ksig, struct pt_regs *regs)
270 {
271 	struct task_struct *t = current;
272 	int ret, sig;
273 
274 	if (unlikely(t->flags & PF_EXITING))
275 		return;
276 	if (unlikely(!access_ok(t->rseq, sizeof(*t->rseq))))
277 		goto error;
278 	ret = rseq_ip_fixup(regs);
279 	if (unlikely(ret < 0))
280 		goto error;
281 	if (unlikely(rseq_update_cpu_id(t)))
282 		goto error;
283 	return;
284 
285 error:
286 	sig = ksig ? ksig->sig : 0;
287 	force_sigsegv(sig);
288 }
289 
290 #ifdef CONFIG_DEBUG_RSEQ
291 
292 /*
293  * Terminate the process if a syscall is issued within a restartable
294  * sequence.
295  */
296 void rseq_syscall(struct pt_regs *regs)
297 {
298 	unsigned long ip = instruction_pointer(regs);
299 	struct task_struct *t = current;
300 	struct rseq_cs rseq_cs;
301 
302 	if (!t->rseq)
303 		return;
304 	if (!access_ok(t->rseq, sizeof(*t->rseq)) ||
305 	    rseq_get_rseq_cs(t, &rseq_cs) || in_rseq_cs(ip, &rseq_cs))
306 		force_sig(SIGSEGV);
307 }
308 
309 #endif
310 
311 /*
312  * sys_rseq - setup restartable sequences for caller thread.
313  */
314 SYSCALL_DEFINE4(rseq, struct rseq __user *, rseq, u32, rseq_len,
315 		int, flags, u32, sig)
316 {
317 	int ret;
318 
319 	if (flags & RSEQ_FLAG_UNREGISTER) {
320 		if (flags & ~RSEQ_FLAG_UNREGISTER)
321 			return -EINVAL;
322 		/* Unregister rseq for current thread. */
323 		if (current->rseq != rseq || !current->rseq)
324 			return -EINVAL;
325 		if (rseq_len != sizeof(*rseq))
326 			return -EINVAL;
327 		if (current->rseq_sig != sig)
328 			return -EPERM;
329 		ret = rseq_reset_rseq_cpu_id(current);
330 		if (ret)
331 			return ret;
332 		current->rseq = NULL;
333 		current->rseq_sig = 0;
334 		return 0;
335 	}
336 
337 	if (unlikely(flags))
338 		return -EINVAL;
339 
340 	if (current->rseq) {
341 		/*
342 		 * If rseq is already registered, check whether
343 		 * the provided address differs from the prior
344 		 * one.
345 		 */
346 		if (current->rseq != rseq || rseq_len != sizeof(*rseq))
347 			return -EINVAL;
348 		if (current->rseq_sig != sig)
349 			return -EPERM;
350 		/* Already registered. */
351 		return -EBUSY;
352 	}
353 
354 	/*
355 	 * If there was no rseq previously registered,
356 	 * ensure the provided rseq is properly aligned and valid.
357 	 */
358 	if (!IS_ALIGNED((unsigned long)rseq, __alignof__(*rseq)) ||
359 	    rseq_len != sizeof(*rseq))
360 		return -EINVAL;
361 	if (!access_ok(rseq, rseq_len))
362 		return -EFAULT;
363 	current->rseq = rseq;
364 	current->rseq_sig = sig;
365 	/*
366 	 * If rseq was previously inactive, and has just been
367 	 * registered, ensure the cpu_id_start and cpu_id fields
368 	 * are updated before returning to user-space.
369 	 */
370 	rseq_set_notify_resume(current);
371 
372 	return 0;
373 }
374