1 // SPDX-License-Identifier: LGPL-2.1
5 * Copyright (C) 2016 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; only
10 * version 2.1 of the License.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
30 #include <rseq/rseq.h>
32 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
35 * linux/rseq.h defines struct rseq as aligned on 32 bytes. The kernel ABI
36 * size is 20 bytes. For support of multiple rseq users within a process,
37 * user-space defines an extra 4 bytes field as a reference count, for a
41 /* kernel-userspace ABI. */
48 } __attribute__((aligned(4 * sizeof(__u64
))));
50 __attribute__((visibility("hidden"))) __thread
51 volatile struct libc_rseq __lib_rseq_abi
= {
52 .cpu_id
= RSEQ_CPU_ID_UNINITIALIZED
,
55 extern __attribute__((weak
, alias("__lib_rseq_abi"))) __thread
56 volatile struct rseq __rseq_abi
;
58 static int sys_rseq(volatile struct rseq
*rseq_abi
, uint32_t rseq_len
,
59 int flags
, uint32_t sig
)
61 return syscall(__NR_rseq
, rseq_abi
, rseq_len
, flags
, sig
);
64 int rseq_available(void)
68 rc
= sys_rseq(NULL
, 0, 0, 0);
81 static void signal_off_save(sigset_t
*oldset
)
87 ret
= pthread_sigmask(SIG_BLOCK
, &set
, oldset
);
92 static void signal_restore(sigset_t oldset
)
96 ret
= pthread_sigmask(SIG_SETMASK
, &oldset
, NULL
);
101 int rseq_register_current_thread(void)
106 signal_off_save(&oldset
);
107 if (__lib_rseq_abi
.refcount
== INT_MAX
) {
111 if (__lib_rseq_abi
.refcount
++)
113 rc
= sys_rseq(&__rseq_abi
, sizeof(struct rseq
), 0, RSEQ_SIG
);
115 assert(rseq_current_cpu_raw() >= 0);
119 __rseq_abi
.cpu_id
= RSEQ_CPU_ID_REGISTRATION_FAILED
;
121 __lib_rseq_abi
.refcount
--;
123 signal_restore(oldset
);
127 int rseq_unregister_current_thread(void)
132 signal_off_save(&oldset
);
133 if (!__lib_rseq_abi
.refcount
) {
137 if (--__lib_rseq_abi
.refcount
)
139 rc
= sys_rseq(&__rseq_abi
, sizeof(struct rseq
),
140 RSEQ_FLAG_UNREGISTER
, RSEQ_SIG
);
145 signal_restore(oldset
);
149 int32_t rseq_fallback_current_cpu(void)
153 cpu
= sched_getcpu();
155 perror("sched_getcpu()");