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