xref: /linux-6.15/kernel/rseq.c (revision cbae6bac)
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_node_id(struct task_struct *t)
89 {
90 	struct rseq __user *rseq = t->rseq;
91 	u32 cpu_id = raw_smp_processor_id();
92 	u32 node_id = cpu_to_node(cpu_id);
93 
94 	if (!user_write_access_begin(rseq, t->rseq_len))
95 		goto efault;
96 	unsafe_put_user(cpu_id, &rseq->cpu_id_start, efault_end);
97 	unsafe_put_user(cpu_id, &rseq->cpu_id, efault_end);
98 	unsafe_put_user(node_id, &rseq->node_id, efault_end);
99 	/*
100 	 * Additional feature fields added after ORIG_RSEQ_SIZE
101 	 * need to be conditionally updated only if
102 	 * t->rseq_len != ORIG_RSEQ_SIZE.
103 	 */
104 	user_write_access_end();
105 	trace_rseq_update(t);
106 	return 0;
107 
108 efault_end:
109 	user_write_access_end();
110 efault:
111 	return -EFAULT;
112 }
113 
114 static int rseq_reset_rseq_cpu_node_id(struct task_struct *t)
115 {
116 	u32 cpu_id_start = 0, cpu_id = RSEQ_CPU_ID_UNINITIALIZED, node_id = 0;
117 
118 	/*
119 	 * Reset cpu_id_start to its initial state (0).
120 	 */
121 	if (put_user(cpu_id_start, &t->rseq->cpu_id_start))
122 		return -EFAULT;
123 	/*
124 	 * Reset cpu_id to RSEQ_CPU_ID_UNINITIALIZED, so any user coming
125 	 * in after unregistration can figure out that rseq needs to be
126 	 * registered again.
127 	 */
128 	if (put_user(cpu_id, &t->rseq->cpu_id))
129 		return -EFAULT;
130 	/*
131 	 * Reset node_id to its initial state (0).
132 	 */
133 	if (put_user(node_id, &t->rseq->node_id))
134 		return -EFAULT;
135 	/*
136 	 * Additional feature fields added after ORIG_RSEQ_SIZE
137 	 * need to be conditionally reset only if
138 	 * t->rseq_len != ORIG_RSEQ_SIZE.
139 	 */
140 	return 0;
141 }
142 
143 static int rseq_get_rseq_cs(struct task_struct *t, struct rseq_cs *rseq_cs)
144 {
145 	struct rseq_cs __user *urseq_cs;
146 	u64 ptr;
147 	u32 __user *usig;
148 	u32 sig;
149 	int ret;
150 
151 #ifdef CONFIG_64BIT
152 	if (get_user(ptr, &t->rseq->rseq_cs))
153 		return -EFAULT;
154 #else
155 	if (copy_from_user(&ptr, &t->rseq->rseq_cs, sizeof(ptr)))
156 		return -EFAULT;
157 #endif
158 	if (!ptr) {
159 		memset(rseq_cs, 0, sizeof(*rseq_cs));
160 		return 0;
161 	}
162 	if (ptr >= TASK_SIZE)
163 		return -EINVAL;
164 	urseq_cs = (struct rseq_cs __user *)(unsigned long)ptr;
165 	if (copy_from_user(rseq_cs, urseq_cs, sizeof(*rseq_cs)))
166 		return -EFAULT;
167 
168 	if (rseq_cs->start_ip >= TASK_SIZE ||
169 	    rseq_cs->start_ip + rseq_cs->post_commit_offset >= TASK_SIZE ||
170 	    rseq_cs->abort_ip >= TASK_SIZE ||
171 	    rseq_cs->version > 0)
172 		return -EINVAL;
173 	/* Check for overflow. */
174 	if (rseq_cs->start_ip + rseq_cs->post_commit_offset < rseq_cs->start_ip)
175 		return -EINVAL;
176 	/* Ensure that abort_ip is not in the critical section. */
177 	if (rseq_cs->abort_ip - rseq_cs->start_ip < rseq_cs->post_commit_offset)
178 		return -EINVAL;
179 
180 	usig = (u32 __user *)(unsigned long)(rseq_cs->abort_ip - sizeof(u32));
181 	ret = get_user(sig, usig);
182 	if (ret)
183 		return ret;
184 
185 	if (current->rseq_sig != sig) {
186 		printk_ratelimited(KERN_WARNING
187 			"Possible attack attempt. Unexpected rseq signature 0x%x, expecting 0x%x (pid=%d, addr=%p).\n",
188 			sig, current->rseq_sig, current->pid, usig);
189 		return -EINVAL;
190 	}
191 	return 0;
192 }
193 
194 static bool rseq_warn_flags(const char *str, u32 flags)
195 {
196 	u32 test_flags;
197 
198 	if (!flags)
199 		return false;
200 	test_flags = flags & RSEQ_CS_NO_RESTART_FLAGS;
201 	if (test_flags)
202 		pr_warn_once("Deprecated flags (%u) in %s ABI structure", test_flags, str);
203 	test_flags = flags & ~RSEQ_CS_NO_RESTART_FLAGS;
204 	if (test_flags)
205 		pr_warn_once("Unknown flags (%u) in %s ABI structure", test_flags, str);
206 	return true;
207 }
208 
209 static int rseq_need_restart(struct task_struct *t, u32 cs_flags)
210 {
211 	u32 flags, event_mask;
212 	int ret;
213 
214 	if (rseq_warn_flags("rseq_cs", cs_flags))
215 		return -EINVAL;
216 
217 	/* Get thread flags. */
218 	ret = get_user(flags, &t->rseq->flags);
219 	if (ret)
220 		return ret;
221 
222 	if (rseq_warn_flags("rseq", flags))
223 		return -EINVAL;
224 
225 	/*
226 	 * Load and clear event mask atomically with respect to
227 	 * scheduler preemption.
228 	 */
229 	preempt_disable();
230 	event_mask = t->rseq_event_mask;
231 	t->rseq_event_mask = 0;
232 	preempt_enable();
233 
234 	return !!event_mask;
235 }
236 
237 static int clear_rseq_cs(struct task_struct *t)
238 {
239 	/*
240 	 * The rseq_cs field is set to NULL on preemption or signal
241 	 * delivery on top of rseq assembly block, as well as on top
242 	 * of code outside of the rseq assembly block. This performs
243 	 * a lazy clear of the rseq_cs field.
244 	 *
245 	 * Set rseq_cs to NULL.
246 	 */
247 #ifdef CONFIG_64BIT
248 	return put_user(0UL, &t->rseq->rseq_cs);
249 #else
250 	if (clear_user(&t->rseq->rseq_cs, sizeof(t->rseq->rseq_cs)))
251 		return -EFAULT;
252 	return 0;
253 #endif
254 }
255 
256 /*
257  * Unsigned comparison will be true when ip >= start_ip, and when
258  * ip < start_ip + post_commit_offset.
259  */
260 static bool in_rseq_cs(unsigned long ip, struct rseq_cs *rseq_cs)
261 {
262 	return ip - rseq_cs->start_ip < rseq_cs->post_commit_offset;
263 }
264 
265 static int rseq_ip_fixup(struct pt_regs *regs)
266 {
267 	unsigned long ip = instruction_pointer(regs);
268 	struct task_struct *t = current;
269 	struct rseq_cs rseq_cs;
270 	int ret;
271 
272 	ret = rseq_get_rseq_cs(t, &rseq_cs);
273 	if (ret)
274 		return ret;
275 
276 	/*
277 	 * Handle potentially not being within a critical section.
278 	 * If not nested over a rseq critical section, restart is useless.
279 	 * Clear the rseq_cs pointer and return.
280 	 */
281 	if (!in_rseq_cs(ip, &rseq_cs))
282 		return clear_rseq_cs(t);
283 	ret = rseq_need_restart(t, rseq_cs.flags);
284 	if (ret <= 0)
285 		return ret;
286 	ret = clear_rseq_cs(t);
287 	if (ret)
288 		return ret;
289 	trace_rseq_ip_fixup(ip, rseq_cs.start_ip, rseq_cs.post_commit_offset,
290 			    rseq_cs.abort_ip);
291 	instruction_pointer_set(regs, (unsigned long)rseq_cs.abort_ip);
292 	return 0;
293 }
294 
295 /*
296  * This resume handler must always be executed between any of:
297  * - preemption,
298  * - signal delivery,
299  * and return to user-space.
300  *
301  * This is how we can ensure that the entire rseq critical section
302  * will issue the commit instruction only if executed atomically with
303  * respect to other threads scheduled on the same CPU, and with respect
304  * to signal handlers.
305  */
306 void __rseq_handle_notify_resume(struct ksignal *ksig, struct pt_regs *regs)
307 {
308 	struct task_struct *t = current;
309 	int ret, sig;
310 
311 	if (unlikely(t->flags & PF_EXITING))
312 		return;
313 
314 	/*
315 	 * regs is NULL if and only if the caller is in a syscall path.  Skip
316 	 * fixup and leave rseq_cs as is so that rseq_sycall() will detect and
317 	 * kill a misbehaving userspace on debug kernels.
318 	 */
319 	if (regs) {
320 		ret = rseq_ip_fixup(regs);
321 		if (unlikely(ret < 0))
322 			goto error;
323 	}
324 	if (unlikely(rseq_update_cpu_node_id(t)))
325 		goto error;
326 	return;
327 
328 error:
329 	sig = ksig ? ksig->sig : 0;
330 	force_sigsegv(sig);
331 }
332 
333 #ifdef CONFIG_DEBUG_RSEQ
334 
335 /*
336  * Terminate the process if a syscall is issued within a restartable
337  * sequence.
338  */
339 void rseq_syscall(struct pt_regs *regs)
340 {
341 	unsigned long ip = instruction_pointer(regs);
342 	struct task_struct *t = current;
343 	struct rseq_cs rseq_cs;
344 
345 	if (!t->rseq)
346 		return;
347 	if (rseq_get_rseq_cs(t, &rseq_cs) || in_rseq_cs(ip, &rseq_cs))
348 		force_sig(SIGSEGV);
349 }
350 
351 #endif
352 
353 /*
354  * sys_rseq - setup restartable sequences for caller thread.
355  */
356 SYSCALL_DEFINE4(rseq, struct rseq __user *, rseq, u32, rseq_len,
357 		int, flags, u32, sig)
358 {
359 	int ret;
360 
361 	if (flags & RSEQ_FLAG_UNREGISTER) {
362 		if (flags & ~RSEQ_FLAG_UNREGISTER)
363 			return -EINVAL;
364 		/* Unregister rseq for current thread. */
365 		if (current->rseq != rseq || !current->rseq)
366 			return -EINVAL;
367 		if (rseq_len != current->rseq_len)
368 			return -EINVAL;
369 		if (current->rseq_sig != sig)
370 			return -EPERM;
371 		ret = rseq_reset_rseq_cpu_node_id(current);
372 		if (ret)
373 			return ret;
374 		current->rseq = NULL;
375 		current->rseq_sig = 0;
376 		current->rseq_len = 0;
377 		return 0;
378 	}
379 
380 	if (unlikely(flags))
381 		return -EINVAL;
382 
383 	if (current->rseq) {
384 		/*
385 		 * If rseq is already registered, check whether
386 		 * the provided address differs from the prior
387 		 * one.
388 		 */
389 		if (current->rseq != rseq || rseq_len != current->rseq_len)
390 			return -EINVAL;
391 		if (current->rseq_sig != sig)
392 			return -EPERM;
393 		/* Already registered. */
394 		return -EBUSY;
395 	}
396 
397 	/*
398 	 * If there was no rseq previously registered, ensure the provided rseq
399 	 * is properly aligned, as communcated to user-space through the ELF
400 	 * auxiliary vector AT_RSEQ_ALIGN. If rseq_len is the original rseq
401 	 * size, the required alignment is the original struct rseq alignment.
402 	 *
403 	 * In order to be valid, rseq_len is either the original rseq size, or
404 	 * large enough to contain all supported fields, as communicated to
405 	 * user-space through the ELF auxiliary vector AT_RSEQ_FEATURE_SIZE.
406 	 */
407 	if (rseq_len < ORIG_RSEQ_SIZE ||
408 	    (rseq_len == ORIG_RSEQ_SIZE && !IS_ALIGNED((unsigned long)rseq, ORIG_RSEQ_SIZE)) ||
409 	    (rseq_len != ORIG_RSEQ_SIZE && (!IS_ALIGNED((unsigned long)rseq, __alignof__(*rseq)) ||
410 					    rseq_len < offsetof(struct rseq, end))))
411 		return -EINVAL;
412 	if (!access_ok(rseq, rseq_len))
413 		return -EFAULT;
414 	current->rseq = rseq;
415 	current->rseq_len = rseq_len;
416 	current->rseq_sig = sig;
417 	/*
418 	 * If rseq was previously inactive, and has just been
419 	 * registered, ensure the cpu_id_start and cpu_id fields
420 	 * are updated before returning to user-space.
421 	 */
422 	rseq_set_notify_resume(current);
423 
424 	return 0;
425 }
426