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 __attribute__((weak
)) __thread
36 volatile struct rseq __rseq_abi
= {
37 .cpu_id
= RSEQ_CPU_ID_UNINITIALIZED
,
40 __attribute__((weak
)) __thread
41 volatile uint32_t __rseq_refcount
;
43 static int sys_rseq(volatile struct rseq
*rseq_abi
, uint32_t rseq_len
,
44 int flags
, uint32_t sig
)
46 return syscall(__NR_rseq
, rseq_abi
, rseq_len
, flags
, sig
);
49 int rseq_available(void)
53 rc
= sys_rseq(NULL
, 0, 0, 0);
66 static void signal_off_save(sigset_t
*oldset
)
72 ret
= pthread_sigmask(SIG_BLOCK
, &set
, oldset
);
77 static void signal_restore(sigset_t oldset
)
81 ret
= pthread_sigmask(SIG_SETMASK
, &oldset
, NULL
);
86 int rseq_register_current_thread(void)
91 signal_off_save(&oldset
);
92 if (__rseq_refcount
== UINT_MAX
) {
96 if (__rseq_refcount
++)
98 rc
= sys_rseq(&__rseq_abi
, sizeof(struct rseq
), 0, RSEQ_SIG
);
100 assert(rseq_current_cpu_raw() >= 0);
104 __rseq_abi
.cpu_id
= RSEQ_CPU_ID_REGISTRATION_FAILED
;
108 signal_restore(oldset
);
112 int rseq_unregister_current_thread(void)
117 signal_off_save(&oldset
);
118 if (!__rseq_refcount
) {
122 if (--__rseq_refcount
)
124 rc
= sys_rseq(&__rseq_abi
, sizeof(struct rseq
),
125 RSEQ_FLAG_UNREGISTER
, RSEQ_SIG
);
130 signal_restore(oldset
);
134 int32_t rseq_fallback_current_cpu(void)
138 cpu
= sched_getcpu();
140 perror("sched_getcpu()");