1 /* 2 * Copyright (C) 2023 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #include "berberis/runtime_primitives/signal_queue.h" 18 19 #include <atomic> 20 21 #include "berberis/base/forever_pool.h" 22 23 namespace berberis { 24 AllocSignal()25siginfo_t* SignalQueue::AllocSignal() { 26 Node* node = ForeverPool<Node>::Alloc(); 27 return &node->info; 28 } 29 EnqueueSignal(siginfo_t * info)30void SignalQueue::EnqueueSignal(siginfo_t* info) { 31 Node* node = reinterpret_cast<Node*>(info); 32 Node* produced = produced_.load(std::memory_order_relaxed); 33 do { 34 node->next = produced; 35 } while (!produced_.compare_exchange_weak(produced, node, std::memory_order_release)); 36 } 37 DequeueSignalUnsafe()38siginfo_t* SignalQueue::DequeueSignalUnsafe() { 39 // Pick everything produced so far. 40 Node* produced = produced_.exchange(nullptr, std::memory_order_acquire); 41 42 // Put in front of consumed. 43 if (produced) { 44 Node* last = produced; 45 while (last->next) { 46 last = last->next; 47 } 48 last->next = consumed_; 49 consumed_ = produced; 50 } 51 52 if (!consumed_) { 53 return nullptr; 54 } 55 56 // Consumed is in reverse order of arrival. 57 Node** best_p = &consumed_; 58 for (Node** curr_p = &consumed_->next; *curr_p; curr_p = &(*curr_p)->next) { 59 // As the list is in reverse order, use '<=' to get last match. 60 if ((*curr_p)->info.si_signo <= (*best_p)->info.si_signo) { 61 best_p = curr_p; 62 } 63 } 64 65 Node* best = *best_p; 66 *best_p = best->next; 67 68 return &best->info; 69 } 70 FreeSignal(siginfo_t * info)71void SignalQueue::FreeSignal(siginfo_t* info) { 72 ForeverPool<Node>::Free(reinterpret_cast<Node*>(info)); 73 } 74 75 } // namespace berberis 76