xref: /linux/kernel/rseq.c (revision 02b44d943b3adddc3a15c1da97045e205b7d14c1)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Restartable sequences system call
4  *
5  * Copyright (C) 2015, Google, Inc.,
6  * Paul Turner <pjt@google.com> and Andrew Hunter <ahh@google.com>
7  * Copyright (C) 2015-2018, EfficiOS Inc.,
8  * Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
9  */
10 
11 /*
12  * Restartable sequences are a lightweight interface that allows
13  * user-level code to be executed atomically relative to scheduler
14  * preemption and signal delivery. Typically used for implementing
15  * per-cpu operations.
16  *
17  * It allows user-space to perform update operations on per-cpu data
18  * without requiring heavy-weight atomic operations.
19  *
20  * Detailed algorithm of rseq user-space assembly sequences:
21  *
22  *                     init(rseq_cs)
23  *                     cpu = TLS->rseq::cpu_id_start
24  *   [1]               TLS->rseq::rseq_cs = rseq_cs
25  *   [start_ip]        ----------------------------
26  *   [2]               if (cpu != TLS->rseq::cpu_id)
27  *                             goto abort_ip;
28  *   [3]               <last_instruction_in_cs>
29  *   [post_commit_ip]  ----------------------------
30  *
31  *   The address of jump target abort_ip must be outside the critical
32  *   region, i.e.:
33  *
34  *     [abort_ip] < [start_ip]  || [abort_ip] >= [post_commit_ip]
35  *
36  *   Steps [2]-[3] (inclusive) need to be a sequence of instructions in
37  *   userspace that can handle being interrupted between any of those
38  *   instructions, and then resumed to the abort_ip.
39  *
40  *   1.  Userspace stores the address of the struct rseq_cs assembly
41  *       block descriptor into the rseq_cs field of the registered
42  *       struct rseq TLS area. This update is performed through a single
43  *       store within the inline assembly instruction sequence.
44  *       [start_ip]
45  *
46  *   2.  Userspace tests to check whether the current cpu_id field match
47  *       the cpu number loaded before start_ip, branching to abort_ip
48  *       in case of a mismatch.
49  *
50  *       If the sequence is preempted or interrupted by a signal
51  *       at or after start_ip and before post_commit_ip, then the kernel
52  *       clears TLS->__rseq_abi::rseq_cs, and sets the user-space return
53  *       ip to abort_ip before returning to user-space, so the preempted
54  *       execution resumes at abort_ip.
55  *
56  *   3.  Userspace critical section final instruction before
57  *       post_commit_ip is the commit. The critical section is
58  *       self-terminating.
59  *       [post_commit_ip]
60  *
61  *   4.  <success>
62  *
63  *   On failure at [2], or if interrupted by preempt or signal delivery
64  *   between [1] and [3]:
65  *
66  *       [abort_ip]
67  *   F1. <failure>
68  */
69 
70 /* Required to select the proper per_cpu ops for rseq_stats_inc() */
71 #define RSEQ_BUILD_SLOW_PATH
72 
73 #include <linux/debugfs.h>
74 #include <linux/hrtimer.h>
75 #include <linux/percpu.h>
76 #include <linux/prctl.h>
77 #include <linux/ratelimit.h>
78 #include <linux/rseq_entry.h>
79 #include <linux/sched.h>
80 #include <linux/syscalls.h>
81 #include <linux/uaccess.h>
82 #include <linux/types.h>
83 #include <linux/rseq.h>
84 #include <asm/ptrace.h>
85 
86 #define CREATE_TRACE_POINTS
87 #include <trace/events/rseq.h>
88 
89 DEFINE_STATIC_KEY_MAYBE(CONFIG_RSEQ_DEBUG_DEFAULT_ENABLE, rseq_debug_enabled);
90 
91 static inline void rseq_control_debug(bool on)
92 {
93 	if (on)
94 		static_branch_enable(&rseq_debug_enabled);
95 	else
96 		static_branch_disable(&rseq_debug_enabled);
97 }
98 
99 static int __init rseq_setup_debug(char *str)
100 {
101 	bool on;
102 
103 	if (kstrtobool(str, &on))
104 		return -EINVAL;
105 	rseq_control_debug(on);
106 	return 1;
107 }
108 __setup("rseq_debug=", rseq_setup_debug);
109 
110 #ifdef CONFIG_TRACEPOINTS
111 /*
112  * Out of line, so the actual update functions can be in a header to be
113  * inlined into the exit to user code.
114  */
115 void __rseq_trace_update(struct task_struct *t)
116 {
117 	trace_rseq_update(t);
118 }
119 
120 void __rseq_trace_ip_fixup(unsigned long ip, unsigned long start_ip,
121 			   unsigned long offset, unsigned long abort_ip)
122 {
123 	trace_rseq_ip_fixup(ip, start_ip, offset, abort_ip);
124 }
125 #endif /* CONFIG_TRACEPOINTS */
126 
127 #ifdef CONFIG_RSEQ_STATS
128 DEFINE_PER_CPU(struct rseq_stats, rseq_stats);
129 
130 static int rseq_stats_show(struct seq_file *m, void *p)
131 {
132 	struct rseq_stats stats = { };
133 	unsigned int cpu;
134 
135 	for_each_possible_cpu(cpu) {
136 		stats.exit	+= data_race(per_cpu(rseq_stats.exit, cpu));
137 		stats.signal	+= data_race(per_cpu(rseq_stats.signal, cpu));
138 		stats.slowpath	+= data_race(per_cpu(rseq_stats.slowpath, cpu));
139 		stats.fastpath	+= data_race(per_cpu(rseq_stats.fastpath, cpu));
140 		stats.ids	+= data_race(per_cpu(rseq_stats.ids, cpu));
141 		stats.cs	+= data_race(per_cpu(rseq_stats.cs, cpu));
142 		stats.clear	+= data_race(per_cpu(rseq_stats.clear, cpu));
143 		stats.fixup	+= data_race(per_cpu(rseq_stats.fixup, cpu));
144 		if (IS_ENABLED(CONFIG_RSEQ_SLICE_EXTENSION)) {
145 			stats.s_granted	+= data_race(per_cpu(rseq_stats.s_granted, cpu));
146 			stats.s_expired	+= data_race(per_cpu(rseq_stats.s_expired, cpu));
147 			stats.s_revoked	+= data_race(per_cpu(rseq_stats.s_revoked, cpu));
148 			stats.s_yielded	+= data_race(per_cpu(rseq_stats.s_yielded, cpu));
149 			stats.s_aborted	+= data_race(per_cpu(rseq_stats.s_aborted, cpu));
150 		}
151 	}
152 
153 	seq_printf(m, "exit:   %16lu\n", stats.exit);
154 	seq_printf(m, "signal: %16lu\n", stats.signal);
155 	seq_printf(m, "slowp:  %16lu\n", stats.slowpath);
156 	seq_printf(m, "fastp:  %16lu\n", stats.fastpath);
157 	seq_printf(m, "ids:    %16lu\n", stats.ids);
158 	seq_printf(m, "cs:     %16lu\n", stats.cs);
159 	seq_printf(m, "clear:  %16lu\n", stats.clear);
160 	seq_printf(m, "fixup:  %16lu\n", stats.fixup);
161 	if (IS_ENABLED(CONFIG_RSEQ_SLICE_EXTENSION)) {
162 		seq_printf(m, "sgrant: %16lu\n", stats.s_granted);
163 		seq_printf(m, "sexpir: %16lu\n", stats.s_expired);
164 		seq_printf(m, "srevok: %16lu\n", stats.s_revoked);
165 		seq_printf(m, "syield: %16lu\n", stats.s_yielded);
166 		seq_printf(m, "sabort: %16lu\n", stats.s_aborted);
167 	}
168 	return 0;
169 }
170 
171 static int rseq_stats_open(struct inode *inode, struct file *file)
172 {
173 	return single_open(file, rseq_stats_show, inode->i_private);
174 }
175 
176 static const struct file_operations stat_ops = {
177 	.open		= rseq_stats_open,
178 	.read		= seq_read,
179 	.llseek		= seq_lseek,
180 	.release	= single_release,
181 };
182 
183 static int __init rseq_stats_init(struct dentry *root_dir)
184 {
185 	debugfs_create_file("stats", 0444, root_dir, NULL, &stat_ops);
186 	return 0;
187 }
188 #else
189 static inline void rseq_stats_init(struct dentry *root_dir) { }
190 #endif /* CONFIG_RSEQ_STATS */
191 
192 static int rseq_debug_show(struct seq_file *m, void *p)
193 {
194 	bool on = static_branch_unlikely(&rseq_debug_enabled);
195 
196 	seq_printf(m, "%d\n", on);
197 	return 0;
198 }
199 
200 static ssize_t rseq_debug_write(struct file *file, const char __user *ubuf,
201 			    size_t count, loff_t *ppos)
202 {
203 	bool on;
204 
205 	if (kstrtobool_from_user(ubuf, count, &on))
206 		return -EINVAL;
207 
208 	rseq_control_debug(on);
209 	return count;
210 }
211 
212 static int rseq_debug_open(struct inode *inode, struct file *file)
213 {
214 	return single_open(file, rseq_debug_show, inode->i_private);
215 }
216 
217 static const struct file_operations debug_ops = {
218 	.open		= rseq_debug_open,
219 	.read		= seq_read,
220 	.write		= rseq_debug_write,
221 	.llseek		= seq_lseek,
222 	.release	= single_release,
223 };
224 
225 static void rseq_slice_ext_init(struct dentry *root_dir);
226 
227 static int __init rseq_debugfs_init(void)
228 {
229 	struct dentry *root_dir = debugfs_create_dir("rseq", NULL);
230 
231 	debugfs_create_file("debug", 0644, root_dir, NULL, &debug_ops);
232 	rseq_stats_init(root_dir);
233 	if (IS_ENABLED(CONFIG_RSEQ_SLICE_EXTENSION))
234 		rseq_slice_ext_init(root_dir);
235 	return 0;
236 }
237 __initcall(rseq_debugfs_init);
238 
239 static bool rseq_handle_cs(struct task_struct *t, struct pt_regs *regs)
240 {
241 	struct rseq __user *urseq = t->rseq.usrptr;
242 	u64 csaddr;
243 
244 	scoped_user_read_access(urseq, efault)
245 		unsafe_get_user(csaddr, &urseq->rseq_cs, efault);
246 	if (likely(!csaddr))
247 		return true;
248 	return rseq_update_user_cs(t, regs, csaddr);
249 efault:
250 	return false;
251 }
252 
253 static void rseq_slowpath_update_usr(struct pt_regs *regs)
254 {
255 	/*
256 	 * Preserve has_rseq and user_irq state. The generic entry code clears
257 	 * user_irq on the way out, the non-generic entry architectures are not
258 	 * setting user_irq.
259 	 */
260 	const struct rseq_event evt_mask = {
261 		.has_rseq	= RSEQ_HAS_RSEQ_VERSION_MASK,
262 		.user_irq	= true,
263 	};
264 	struct task_struct *t = current;
265 	struct rseq_ids ids;
266 	u32 node_id;
267 	bool event;
268 
269 	if (unlikely(t->flags & PF_EXITING))
270 		return;
271 
272 	rseq_stat_inc(rseq_stats.slowpath);
273 
274 	/*
275 	 * Read and clear the event pending bit first. If the task
276 	 * was not preempted or migrated or a signal is on the way,
277 	 * there is no point in doing any of the heavy lifting here
278 	 * on production kernels. In that case TIF_NOTIFY_RESUME
279 	 * was raised by some other functionality.
280 	 *
281 	 * This is correct because the read/clear operation is
282 	 * guarded against scheduler preemption, which makes it CPU
283 	 * local atomic. If the task is preempted right after
284 	 * re-enabling preemption then TIF_NOTIFY_RESUME is set
285 	 * again and this function is invoked another time _before_
286 	 * the task is able to return to user mode.
287 	 *
288 	 * On a debug kernel, invoke the fixup code unconditionally
289 	 * with the result handed in to allow the detection of
290 	 * inconsistencies.
291 	 */
292 	scoped_guard(irq) {
293 		event = t->rseq.event.sched_switch;
294 		t->rseq.event.all &= evt_mask.all;
295 		ids.cpu_id = task_cpu(t);
296 		ids.mm_cid = task_mm_cid(t);
297 	}
298 
299 	if (!event)
300 		return;
301 
302 	node_id = cpu_to_node(ids.cpu_id);
303 
304 	if (unlikely(!rseq_update_usr(t, regs, &ids, node_id))) {
305 		/*
306 		 * Clear the errors just in case this might survive magically, but
307 		 * leave the rest intact.
308 		 */
309 		t->rseq.event.error = 0;
310 		force_sig(SIGSEGV);
311 	}
312 }
313 
314 void __rseq_handle_slowpath(struct pt_regs *regs)
315 {
316 	/*
317 	 * If invoked from hypervisors before entering the guest via
318 	 * resume_user_mode_work(), then @regs is a NULL pointer.
319 	 *
320 	 * resume_user_mode_work() clears TIF_NOTIFY_RESUME and re-raises
321 	 * it before returning from the ioctl() to user space when
322 	 * rseq_event.sched_switch is set.
323 	 *
324 	 * So it's safe to ignore here instead of pointlessly updating it
325 	 * in the vcpu_run() loop.
326 	 */
327 	if (!regs)
328 		return;
329 
330 	rseq_slowpath_update_usr(regs);
331 }
332 
333 void __rseq_signal_deliver(int sig, struct pt_regs *regs)
334 {
335 	rseq_stat_inc(rseq_stats.signal);
336 
337 	/*
338 	 * Don't update IDs yet, they are handled on exit to user if
339 	 * necessary. The important thing is to abort a critical section of
340 	 * the interrupted context as after this point the instruction
341 	 * pointer in @regs points to the signal handler.
342 	 */
343 	if (unlikely(!rseq_handle_cs(current, regs))) {
344 		/*
345 		 * Clear the errors just in case this might survive
346 		 * magically, but leave the rest intact.
347 		 */
348 		current->rseq.event.error = 0;
349 		force_sigsegv(sig);
350 	}
351 
352 	/*
353 	 * In legacy mode, force the update of IDs before returning to user
354 	 * space to stay compatible.
355 	 */
356 	if (!rseq_v2(current))
357 		rseq_force_update();
358 }
359 
360 /*
361  * Terminate the process if a syscall is issued within a restartable
362  * sequence.
363  */
364 void __rseq_debug_syscall_return(struct pt_regs *regs)
365 {
366 	struct task_struct *t = current;
367 	u64 csaddr;
368 
369 	if (!t->rseq.event.has_rseq)
370 		return;
371 	if (get_user(csaddr, &t->rseq.usrptr->rseq_cs))
372 		goto fail;
373 	if (likely(!csaddr))
374 		return;
375 	if (unlikely(csaddr >= TASK_SIZE))
376 		goto fail;
377 	if (rseq_debug_update_user_cs(t, regs, csaddr))
378 		return;
379 fail:
380 	force_sig(SIGSEGV);
381 }
382 
383 #ifdef CONFIG_DEBUG_RSEQ
384 /* Kept around to keep GENERIC_ENTRY=n architectures supported. */
385 void rseq_syscall(struct pt_regs *regs)
386 {
387 	__rseq_debug_syscall_return(regs);
388 }
389 #endif
390 
391 static bool rseq_reset_ids(void)
392 {
393 	struct rseq __user *rseq = current->rseq.usrptr;
394 
395 	/*
396 	 * If this fails, terminate it because this leaves the kernel in
397 	 * stupid state as exit to user space will try to fixup the ids
398 	 * again.
399 	 */
400 	scoped_user_rw_access(rseq, efault) {
401 		unsafe_put_user(0, &rseq->cpu_id_start, efault);
402 		unsafe_put_user(RSEQ_CPU_ID_UNINITIALIZED, &rseq->cpu_id, efault);
403 		unsafe_put_user(0, &rseq->node_id, efault);
404 		unsafe_put_user(0, &rseq->mm_cid, efault);
405 	}
406 	return true;
407 
408 efault:
409 	force_sig(SIGSEGV);
410 	return false;
411 }
412 
413 /* The original rseq structure size (including padding) is 32 bytes. */
414 #define ORIG_RSEQ_SIZE		32
415 
416 /*
417  * sys_rseq - setup restartable sequences for caller thread.
418  */
419 SYSCALL_DEFINE4(rseq, struct rseq __user *, rseq, u32, rseq_len, int, flags, u32, sig)
420 {
421 	u32 rseqfl = 0;
422 	u8 version = 1;
423 
424 	if (flags & RSEQ_FLAG_UNREGISTER) {
425 		if (flags & ~RSEQ_FLAG_UNREGISTER)
426 			return -EINVAL;
427 		/* Unregister rseq for current thread. */
428 		if (current->rseq.usrptr != rseq || !current->rseq.usrptr)
429 			return -EINVAL;
430 		if (rseq_len != current->rseq.len)
431 			return -EINVAL;
432 		if (current->rseq.sig != sig)
433 			return -EPERM;
434 		if (!rseq_reset_ids())
435 			return -EFAULT;
436 		rseq_reset(current);
437 		return 0;
438 	}
439 
440 	if (unlikely(flags & ~(RSEQ_FLAG_SLICE_EXT_DEFAULT_ON)))
441 		return -EINVAL;
442 
443 	if (current->rseq.usrptr) {
444 		/*
445 		 * If rseq is already registered, check whether
446 		 * the provided address differs from the prior
447 		 * one.
448 		 */
449 		if (current->rseq.usrptr != rseq || rseq_len != current->rseq.len)
450 			return -EINVAL;
451 		if (current->rseq.sig != sig)
452 			return -EPERM;
453 		/* Already registered. */
454 		return -EBUSY;
455 	}
456 
457 	/*
458 	 * If there was no rseq previously registered, ensure the provided rseq
459 	 * is properly aligned, as communcated to user-space through the ELF
460 	 * auxiliary vector AT_RSEQ_ALIGN. If rseq_len is the original rseq
461 	 * size, the required alignment is the original struct rseq alignment.
462 	 *
463 	 * The rseq_len is required to be greater or equal to the original rseq
464 	 * size. In order to be valid, rseq_len is either the original rseq size,
465 	 * or large enough to contain all supported fields, as communicated to
466 	 * user-space through the ELF auxiliary vector AT_RSEQ_FEATURE_SIZE.
467 	 */
468 	if (rseq_len < ORIG_RSEQ_SIZE ||
469 	    (rseq_len == ORIG_RSEQ_SIZE && !IS_ALIGNED((unsigned long)rseq, ORIG_RSEQ_SIZE)) ||
470 	    (rseq_len != ORIG_RSEQ_SIZE && (!IS_ALIGNED((unsigned long)rseq, rseq_alloc_align()) ||
471 					    rseq_len < offsetof(struct rseq, end))))
472 		return -EINVAL;
473 	if (!access_ok(rseq, rseq_len))
474 		return -EFAULT;
475 
476 	/*
477 	 * The version check effectivly disables time slice extensions until the
478 	 * RSEQ ABI V2 registration are implemented.
479 	 */
480 	if (IS_ENABLED(CONFIG_RSEQ_SLICE_EXTENSION) && version > 1) {
481 		if (rseq_slice_extension_enabled()) {
482 			rseqfl |= RSEQ_CS_FLAG_SLICE_EXT_AVAILABLE;
483 			if (flags & RSEQ_FLAG_SLICE_EXT_DEFAULT_ON)
484 				rseqfl |= RSEQ_CS_FLAG_SLICE_EXT_ENABLED;
485 		}
486 	}
487 
488 	scoped_user_write_access(rseq, efault) {
489 		/*
490 		 * If the rseq_cs pointer is non-NULL on registration, clear it to
491 		 * avoid a potential segfault on return to user-space. The proper thing
492 		 * to do would have been to fail the registration but this would break
493 		 * older libcs that reuse the rseq area for new threads without
494 		 * clearing the fields. Don't bother reading it, just reset it.
495 		 */
496 		unsafe_put_user(0UL, &rseq->rseq_cs, efault);
497 		unsafe_put_user(rseqfl, &rseq->flags, efault);
498 		/* Initialize IDs in user space */
499 		unsafe_put_user(RSEQ_CPU_ID_UNINITIALIZED, &rseq->cpu_id_start, efault);
500 		unsafe_put_user(RSEQ_CPU_ID_UNINITIALIZED, &rseq->cpu_id, efault);
501 		unsafe_put_user(0U, &rseq->node_id, efault);
502 		unsafe_put_user(0U, &rseq->mm_cid, efault);
503 
504 		/*
505 		 * All fields past mm_cid are only valid for non-legacy v2
506 		 * registrations.
507 		 */
508 		if (version > 1) {
509 			if (IS_ENABLED(CONFIG_RSEQ_SLICE_EXTENSION))
510 				unsafe_put_user(0U, &rseq->slice_ctrl.all, efault);
511 		}
512 	}
513 
514 	/*
515 	 * Activate the registration by setting the rseq area address, length
516 	 * and signature in the task struct.
517 	 */
518 	current->rseq.usrptr = rseq;
519 	current->rseq.len = rseq_len;
520 	current->rseq.sig = sig;
521 
522 #ifdef CONFIG_RSEQ_SLICE_EXTENSION
523 	current->rseq.slice.state.enabled = !!(rseqfl & RSEQ_CS_FLAG_SLICE_EXT_ENABLED);
524 #endif
525 
526 	/*
527 	 * If rseq was previously inactive, and has just been
528 	 * registered, ensure the cpu_id_start and cpu_id fields
529 	 * are updated before returning to user-space.
530 	 */
531 	current->rseq.event.has_rseq = true;
532 	rseq_force_update();
533 	return 0;
534 
535 efault:
536 	return -EFAULT;
537 }
538 
539 #ifdef CONFIG_RSEQ_SLICE_EXTENSION
540 struct slice_timer {
541 	struct hrtimer	timer;
542 	void		*cookie;
543 };
544 
545 static const unsigned int rseq_slice_ext_nsecs_min =  5 * NSEC_PER_USEC;
546 static const unsigned int rseq_slice_ext_nsecs_max = 50 * NSEC_PER_USEC;
547 unsigned int rseq_slice_ext_nsecs __read_mostly = rseq_slice_ext_nsecs_min;
548 static DEFINE_PER_CPU(struct slice_timer, slice_timer);
549 DEFINE_STATIC_KEY_TRUE(rseq_slice_extension_key);
550 
551 /*
552  * When the timer expires and the task is still in user space, the return
553  * from interrupt will revoke the grant and schedule. If the task already
554  * entered the kernel via a syscall and the timer fires before the syscall
555  * work was able to cancel it, then depending on the preemption model this
556  * will either reschedule on return from interrupt or in the syscall work
557  * below.
558  */
559 static enum hrtimer_restart rseq_slice_expired(struct hrtimer *tmr)
560 {
561 	struct slice_timer *st = container_of(tmr, struct slice_timer, timer);
562 
563 	/*
564 	 * Validate that the task which armed the timer is still on the
565 	 * CPU. It could have been scheduled out without canceling the
566 	 * timer.
567 	 */
568 	if (st->cookie == current && current->rseq.slice.state.granted) {
569 		rseq_stat_inc(rseq_stats.s_expired);
570 		set_need_resched_current();
571 	}
572 	return HRTIMER_NORESTART;
573 }
574 
575 bool __rseq_arm_slice_extension_timer(void)
576 {
577 	struct slice_timer *st = this_cpu_ptr(&slice_timer);
578 	struct task_struct *curr = current;
579 
580 	lockdep_assert_irqs_disabled();
581 
582 	/*
583 	 * This check prevents a task, which got a time slice extension
584 	 * granted, from exceeding the maximum scheduling latency when the
585 	 * grant expired before going out to user space. Don't bother to
586 	 * clear the grant here, it will be cleaned up automatically before
587 	 * going out to user space after being scheduled back in.
588 	 */
589 	if ((unlikely(curr->rseq.slice.expires < ktime_get_mono_fast_ns()))) {
590 		set_need_resched_current();
591 		return true;
592 	}
593 
594 	/*
595 	 * Store the task pointer as a cookie for comparison in the timer
596 	 * function. This is safe as the timer is CPU local and cannot be
597 	 * in the expiry function at this point.
598 	 */
599 	st->cookie = curr;
600 	hrtimer_start(&st->timer, curr->rseq.slice.expires, HRTIMER_MODE_ABS_PINNED_HARD);
601 	/* Arm the syscall entry work */
602 	set_task_syscall_work(curr, SYSCALL_RSEQ_SLICE);
603 	return false;
604 }
605 
606 static void rseq_cancel_slice_extension_timer(void)
607 {
608 	struct slice_timer *st = this_cpu_ptr(&slice_timer);
609 
610 	/*
611 	 * st->cookie can be safely read as preemption is disabled and the
612 	 * timer is CPU local.
613 	 *
614 	 * As this is most probably the first expiring timer, the cancel is
615 	 * expensive as it has to reprogram the hardware, but that's less
616 	 * expensive than going through a full hrtimer_interrupt() cycle
617 	 * for nothing.
618 	 *
619 	 * hrtimer_try_to_cancel() is sufficient here as the timer is CPU
620 	 * local and once the hrtimer code disabled interrupts the timer
621 	 * callback cannot be running.
622 	 */
623 	if (st->cookie == current)
624 		hrtimer_try_to_cancel(&st->timer);
625 }
626 
627 static inline void rseq_slice_set_need_resched(struct task_struct *curr)
628 {
629 	/*
630 	 * The interrupt guard is required to prevent inconsistent state in
631 	 * this case:
632 	 *
633 	 * set_tsk_need_resched()
634 	 * --> Interrupt
635 	 *       wakeup()
636 	 *        set_tsk_need_resched()
637 	 *	  set_preempt_need_resched()
638 	 *     schedule_on_return()
639 	 *        clear_tsk_need_resched()
640 	 *	  clear_preempt_need_resched()
641 	 * set_preempt_need_resched()		<- Inconsistent state
642 	 *
643 	 * This is safe vs. a remote set of TIF_NEED_RESCHED because that
644 	 * only sets the already set bit and does not create inconsistent
645 	 * state.
646 	 */
647 	scoped_guard(irq)
648 		set_need_resched_current();
649 }
650 
651 static void rseq_slice_validate_ctrl(u32 expected)
652 {
653 	u32 __user *sctrl = &current->rseq.usrptr->slice_ctrl.all;
654 	u32 uval;
655 
656 	if (get_user(uval, sctrl) || uval != expected)
657 		force_sig(SIGSEGV);
658 }
659 
660 /*
661  * Invoked from syscall entry if a time slice extension was granted and the
662  * kernel did not clear it before user space left the critical section.
663  *
664  * While the recommended way to relinquish the CPU side effect free is
665  * rseq_slice_yield(2), any syscall within a granted slice terminates the
666  * grant and immediately reschedules if required. This supports onion layer
667  * applications, where the code requesting the grant cannot control the
668  * code within the critical section.
669  */
670 void rseq_syscall_enter_work(long syscall)
671 {
672 	struct task_struct *curr = current;
673 	struct rseq_slice_ctrl ctrl = { .granted = curr->rseq.slice.state.granted };
674 
675 	clear_task_syscall_work(curr, SYSCALL_RSEQ_SLICE);
676 
677 	if (static_branch_unlikely(&rseq_debug_enabled))
678 		rseq_slice_validate_ctrl(ctrl.all);
679 
680 	/*
681 	 * The kernel might have raced, revoked the grant and updated
682 	 * userspace, but kept the SLICE work set.
683 	 */
684 	if (!ctrl.granted)
685 		return;
686 
687 	/*
688 	 * Required to stabilize the per CPU timer pointer and to make
689 	 * set_tsk_need_resched() correct on PREEMPT[RT] kernels.
690 	 *
691 	 * Leaving the scope will reschedule on preemption models FULL,
692 	 * LAZY and RT if necessary.
693 	 */
694 	scoped_guard(preempt) {
695 		rseq_cancel_slice_extension_timer();
696 		/*
697 		 * Now that preemption is disabled, quickly check whether
698 		 * the task was already rescheduled before arriving here.
699 		 */
700 		if (!curr->rseq.event.sched_switch) {
701 			rseq_slice_set_need_resched(curr);
702 
703 			if (syscall == __NR_rseq_slice_yield) {
704 				rseq_stat_inc(rseq_stats.s_yielded);
705 				/* Update the yielded state for syscall return */
706 				curr->rseq.slice.yielded = 1;
707 			} else {
708 				rseq_stat_inc(rseq_stats.s_aborted);
709 			}
710 		}
711 	}
712 	/* Reschedule on NONE/VOLUNTARY preemption models */
713 	cond_resched();
714 
715 	/* Clear the grant in kernel state and user space */
716 	curr->rseq.slice.state.granted = false;
717 	if (put_user(0U, &curr->rseq.usrptr->slice_ctrl.all))
718 		force_sig(SIGSEGV);
719 }
720 
721 int rseq_slice_extension_prctl(unsigned long arg2, unsigned long arg3)
722 {
723 	switch (arg2) {
724 	case PR_RSEQ_SLICE_EXTENSION_GET:
725 		if (arg3)
726 			return -EINVAL;
727 		return current->rseq.slice.state.enabled ? PR_RSEQ_SLICE_EXT_ENABLE : 0;
728 
729 	case PR_RSEQ_SLICE_EXTENSION_SET: {
730 		u32 rflags, valid = RSEQ_CS_FLAG_SLICE_EXT_AVAILABLE;
731 		bool enable = !!(arg3 & PR_RSEQ_SLICE_EXT_ENABLE);
732 
733 		if (arg3 & ~PR_RSEQ_SLICE_EXT_ENABLE)
734 			return -EINVAL;
735 		if (!rseq_slice_extension_enabled())
736 			return -ENOTSUPP;
737 		if (!current->rseq.usrptr)
738 			return -ENXIO;
739 		if (!rseq_v2(current))
740 			return -ENOTSUPP;
741 
742 		/* No change? */
743 		if (enable == !!current->rseq.slice.state.enabled)
744 			return 0;
745 
746 		if (get_user(rflags, &current->rseq.usrptr->flags))
747 			goto die;
748 
749 		if (current->rseq.slice.state.enabled)
750 			valid |= RSEQ_CS_FLAG_SLICE_EXT_ENABLED;
751 
752 		if ((rflags & valid) != valid)
753 			goto die;
754 
755 		rflags &= ~RSEQ_CS_FLAG_SLICE_EXT_ENABLED;
756 		rflags |= RSEQ_CS_FLAG_SLICE_EXT_AVAILABLE;
757 		if (enable)
758 			rflags |= RSEQ_CS_FLAG_SLICE_EXT_ENABLED;
759 
760 		if (put_user(rflags, &current->rseq.usrptr->flags))
761 			goto die;
762 
763 		current->rseq.slice.state.enabled = enable;
764 		return 0;
765 	}
766 	default:
767 		return -EINVAL;
768 	}
769 die:
770 	force_sig(SIGSEGV);
771 	return -EFAULT;
772 }
773 
774 /**
775  * sys_rseq_slice_yield - yield the current processor side effect free if a
776  *			  task granted with a time slice extension is done with
777  *			  the critical work before being forced out.
778  *
779  * Return: 1 if the task successfully yielded the CPU within the granted slice.
780  *         0 if the slice extension was either never granted or was revoked by
781  *	     going over the granted extension, using a syscall other than this one
782  *	     or being scheduled out earlier due to a subsequent interrupt.
783  *
784  * The syscall does not schedule because the syscall entry work immediately
785  * relinquishes the CPU and schedules if required.
786  */
787 SYSCALL_DEFINE0(rseq_slice_yield)
788 {
789 	int yielded = !!current->rseq.slice.yielded;
790 
791 	current->rseq.slice.yielded = 0;
792 	return yielded;
793 }
794 
795 static int rseq_slice_ext_show(struct seq_file *m, void *p)
796 {
797 	seq_printf(m, "%d\n", rseq_slice_ext_nsecs);
798 	return 0;
799 }
800 
801 static ssize_t rseq_slice_ext_write(struct file *file, const char __user *ubuf,
802 				    size_t count, loff_t *ppos)
803 {
804 	unsigned int nsecs;
805 
806 	if (kstrtouint_from_user(ubuf, count, 10, &nsecs))
807 		return -EINVAL;
808 
809 	if (nsecs < rseq_slice_ext_nsecs_min)
810 		return -ERANGE;
811 
812 	if (nsecs > rseq_slice_ext_nsecs_max)
813 		return -ERANGE;
814 
815 	rseq_slice_ext_nsecs = nsecs;
816 
817 	return count;
818 }
819 
820 static int rseq_slice_ext_open(struct inode *inode, struct file *file)
821 {
822 	return single_open(file, rseq_slice_ext_show, inode->i_private);
823 }
824 
825 static const struct file_operations slice_ext_ops = {
826 	.open		= rseq_slice_ext_open,
827 	.read		= seq_read,
828 	.write		= rseq_slice_ext_write,
829 	.llseek		= seq_lseek,
830 	.release	= single_release,
831 };
832 
833 static void rseq_slice_ext_init(struct dentry *root_dir)
834 {
835 	debugfs_create_file("slice_ext_nsec", 0644, root_dir, NULL, &slice_ext_ops);
836 }
837 
838 static int __init rseq_slice_cmdline(char *str)
839 {
840 	bool on;
841 
842 	if (kstrtobool(str, &on))
843 		return 0;
844 
845 	if (!on)
846 		static_branch_disable(&rseq_slice_extension_key);
847 	return 1;
848 }
849 __setup("rseq_slice_ext=", rseq_slice_cmdline);
850 
851 static int __init rseq_slice_init(void)
852 {
853 	unsigned int cpu;
854 
855 	for_each_possible_cpu(cpu) {
856 		hrtimer_setup(per_cpu_ptr(&slice_timer.timer, cpu), rseq_slice_expired,
857 			      CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED_HARD);
858 	}
859 	return 0;
860 }
861 device_initcall(rseq_slice_init);
862 #else
863 static void rseq_slice_ext_init(struct dentry *root_dir) { }
864 #endif /* CONFIG_RSEQ_SLICE_EXTENSION */
865