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.
32 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
34 __thread volatile struct rseq __rseq_abi = {
35 .cpu_id = RSEQ_CPU_ID_UNINITIALIZED,
39 * Shared with other libraries. This library may take rseq ownership if it is
40 * still 0 when executing the library constructor. Set to 1 by library
41 * constructor when handling rseq. Set to 0 in destructor if handling rseq.
45 /* Whether this library have ownership of rseq registration. */
46 static int rseq_ownership;
48 static __thread volatile uint32_t __rseq_refcount;
50 static void signal_off_save(sigset_t *oldset)
56 ret = pthread_sigmask(SIG_BLOCK, &set, oldset);
61 static void signal_restore(sigset_t oldset)
65 ret = pthread_sigmask(SIG_SETMASK, &oldset, NULL);
70 static int sys_rseq(volatile struct rseq *rseq_abi, uint32_t rseq_len,
71 int flags, uint32_t sig)
73 return syscall(__NR_rseq, rseq_abi, rseq_len, flags, sig);
76 int rseq_register_current_thread(void)
83 signal_off_save(&oldset);
84 if (__rseq_refcount == UINT_MAX) {
88 if (__rseq_refcount++)
90 rc = sys_rseq(&__rseq_abi, sizeof(struct rseq), 0, RSEQ_SIG);
92 assert(rseq_current_cpu_raw() >= 0);
96 __rseq_abi.cpu_id = RSEQ_CPU_ID_REGISTRATION_FAILED;
100 signal_restore(oldset);
104 int rseq_unregister_current_thread(void)
111 signal_off_save(&oldset);
112 if (!__rseq_refcount) {
116 if (--__rseq_refcount)
118 rc = sys_rseq(&__rseq_abi, sizeof(struct rseq),
119 RSEQ_FLAG_UNREGISTER, RSEQ_SIG);
125 signal_restore(oldset);
129 int32_t rseq_fallback_current_cpu(void)
133 cpu = sched_getcpu();
135 perror("sched_getcpu()");
141 void __attribute__((constructor)) rseq_init(void)
143 /* Check whether rseq is handled by another library. */
150 void __attribute__((destructor)) rseq_fini(void)