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 "../kselftest.h"
33 __thread volatile struct rseq_abi __rseq_abi = {
34 .cpu_id = RSEQ_ABI_CPU_ID_UNINITIALIZED,
38 * Shared with other libraries. This library may take rseq ownership if it is
39 * still 0 when executing the library constructor. Set to 1 by library
40 * constructor when handling rseq. Set to 0 in destructor if handling rseq.
44 /* Whether this library have ownership of rseq registration. */
45 static int rseq_ownership;
47 static __thread volatile uint32_t __rseq_refcount;
49 static void signal_off_save(sigset_t *oldset)
55 ret = pthread_sigmask(SIG_BLOCK, &set, oldset);
60 static void signal_restore(sigset_t oldset)
64 ret = pthread_sigmask(SIG_SETMASK, &oldset, NULL);
69 static int sys_rseq(volatile struct rseq_abi *rseq_abi, uint32_t rseq_len,
70 int flags, uint32_t sig)
72 return syscall(__NR_rseq, rseq_abi, rseq_len, flags, sig);
75 int rseq_register_current_thread(void)
82 signal_off_save(&oldset);
83 if (__rseq_refcount == UINT_MAX) {
87 if (__rseq_refcount++)
89 rc = sys_rseq(&__rseq_abi, sizeof(struct rseq_abi), 0, RSEQ_SIG);
91 assert(rseq_current_cpu_raw() >= 0);
95 __rseq_abi.cpu_id = RSEQ_ABI_CPU_ID_REGISTRATION_FAILED;
99 signal_restore(oldset);
103 int rseq_unregister_current_thread(void)
110 signal_off_save(&oldset);
111 if (!__rseq_refcount) {
115 if (--__rseq_refcount)
117 rc = sys_rseq(&__rseq_abi, sizeof(struct rseq_abi),
118 RSEQ_ABI_FLAG_UNREGISTER, RSEQ_SIG);
124 signal_restore(oldset);
128 int32_t rseq_fallback_current_cpu(void)
132 cpu = sched_getcpu();
134 perror("sched_getcpu()");
140 void __attribute__((constructor)) rseq_init(void)
142 /* Check whether rseq is handled by another library. */
149 void __attribute__((destructor)) rseq_fini(void)