1 // SPDX-License-Identifier: LGPL-2.1-only
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.
31 #include <rseq/rseq.h>
33 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
35 __thread
struct rseq __rseq_abi
= {
36 .cpu_id
= RSEQ_CPU_ID_UNINITIALIZED
,
39 static __thread
uint32_t __rseq_refcount
;
41 static int sys_rseq(struct rseq
*rseq_abi
, uint32_t rseq_len
,
42 int flags
, uint32_t sig
)
44 return syscall(__NR_rseq
, rseq_abi
, rseq_len
, flags
, sig
);
47 int rseq_available(void)
51 rc
= sys_rseq(NULL
, 0, 0, 0);
64 static void signal_off_save(sigset_t
*oldset
)
70 ret
= pthread_sigmask(SIG_BLOCK
, &set
, oldset
);
75 static void signal_restore(sigset_t oldset
)
79 ret
= pthread_sigmask(SIG_SETMASK
, &oldset
, NULL
);
84 int rseq_register_current_thread(void)
86 int rc
, ret
= 0, cpu_id
;
89 signal_off_save(&oldset
);
90 cpu_id
= rseq_current_cpu_raw();
91 if (cpu_id
== RSEQ_CPU_ID_REGISTRATION_FAILED
) {
97 * If cpu_id >= 0, rseq is already successfully registered either by
98 * libc (__rseq_refcount == 0) or by another user library
99 * (__rseq_refcount > 0) for this thread.
102 /* Treat libc's ownership as a successful registration. */
103 if (__rseq_refcount
== 0)
105 if (__rseq_refcount
== UINT_MAX
) {
111 assert(__rseq_refcount
== 0);
112 rc
= sys_rseq(&__rseq_abi
, sizeof(struct rseq
), 0, RSEQ_SIG
);
114 assert(errno
!= EBUSY
);
115 __rseq_abi
.cpu_id
= RSEQ_CPU_ID_REGISTRATION_FAILED
;
119 assert(rseq_current_cpu_raw() >= 0);
123 signal_restore(oldset
);
127 int rseq_unregister_current_thread(void)
129 int rc
, ret
= 0, cpu_id
;
132 signal_off_save(&oldset
);
133 cpu_id
= rseq_current_cpu_raw();
134 /* cpu_id < 0 means rseq is either uninitialized or registration failed. */
141 * If cpu_id >= 0, rseq is currently successfully registered either by
142 * libc (__rseq_refcount == 0) or by another user library
143 * (__rseq_refcount > 0) for this thread.
145 * Treat libc's ownership as a successful unregistration.
147 if (__rseq_refcount
== 0) {
150 if (__rseq_refcount
== 1) {
151 rc
= sys_rseq(&__rseq_abi
, sizeof(struct rseq
),
152 RSEQ_FLAG_UNREGISTER
, RSEQ_SIG
);
160 signal_restore(oldset
);
164 int32_t rseq_fallback_current_cpu(void)
168 cpu
= sched_getcpu();
170 perror("sched_getcpu()");