| 1 | /* |
| 2 | * Copyright (C) 2022 EfficiOS Inc. |
| 3 | * |
| 4 | * SPDX-License-Identifier: GPL-2.0-only |
| 5 | * |
| 6 | */ |
| 7 | |
| 8 | #include "lttng-relayd.hpp" |
| 9 | |
| 10 | #include <common/compat/poll.hpp> |
| 11 | #include <common/error.hpp> |
| 12 | #include <common/fd-tracker/utils.hpp> |
| 13 | #include <common/readwrite.hpp> |
| 14 | #include <common/utils.hpp> |
| 15 | |
| 16 | /* |
| 17 | * Quit pipe for all threads. This permits a single cancellation point |
| 18 | * for all threads when receiving an event on the pipe. |
| 19 | */ |
| 20 | static int thread_quit_pipe[2] = { -1, -1 }; |
| 21 | |
| 22 | /* |
| 23 | * Write to writable pipe used to notify a thread. |
| 24 | */ |
| 25 | static int notify_thread_pipe(int wpipe) |
| 26 | { |
| 27 | const auto ret = lttng_write(wpipe, "!", 1); |
| 28 | |
| 29 | if (ret < 1) { |
| 30 | PERROR("Failed to write to thread pipe"); |
| 31 | return -1; |
| 32 | } |
| 33 | |
| 34 | return 0; |
| 35 | } |
| 36 | |
| 37 | /* |
| 38 | * Initialize the thread quit pipe. |
| 39 | * |
| 40 | * Return -1 on error or 0 if all pipes are created. |
| 41 | */ |
| 42 | int relayd_init_thread_quit_pipe() |
| 43 | { |
| 44 | return fd_tracker_util_pipe_open_cloexec( |
| 45 | the_fd_tracker, "Thread quit pipe", thread_quit_pipe); |
| 46 | } |
| 47 | |
| 48 | /* |
| 49 | * Notify the threads to initiate shutdown. |
| 50 | * |
| 51 | * Return 0 on success or -1 on error. |
| 52 | */ |
| 53 | int relayd_notify_thread_quit_pipe() |
| 54 | { |
| 55 | return notify_thread_pipe(thread_quit_pipe[1]); |
| 56 | } |
| 57 | |
| 58 | /* |
| 59 | * Close the thread quit pipe. |
| 60 | */ |
| 61 | void relayd_close_thread_quit_pipe() |
| 62 | { |
| 63 | if (thread_quit_pipe[0] != -1) { |
| 64 | (void) fd_tracker_util_pipe_close(the_fd_tracker, thread_quit_pipe); |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | /* |
| 69 | * Return 1 if 'fd' is the thread quit pipe read fd. |
| 70 | */ |
| 71 | bool relayd_is_thread_quit_pipe(const int fd) |
| 72 | { |
| 73 | return (fd == thread_quit_pipe[0]); |
| 74 | } |
| 75 | |
| 76 | /* |
| 77 | * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set. |
| 78 | */ |
| 79 | int create_named_thread_poll_set(struct lttng_poll_event *events, int size, const char *name) |
| 80 | { |
| 81 | if (events == nullptr || size == 0) { |
| 82 | return -1; |
| 83 | } |
| 84 | |
| 85 | const auto create_ret = |
| 86 | fd_tracker_util_poll_create(the_fd_tracker, name, events, 1, LTTNG_CLOEXEC); |
| 87 | if (create_ret) { |
| 88 | PERROR("Failed to create \"%s\" poll file descriptor", name); |
| 89 | return -1; |
| 90 | } |
| 91 | |
| 92 | /* Add thread quit pipe to monitored events. */ |
| 93 | const auto poll_add_ret = lttng_poll_add(events, thread_quit_pipe[0], LPOLLIN); |
| 94 | if (poll_add_ret < 0) { |
| 95 | return -1; |
| 96 | } |
| 97 | |
| 98 | return 0; |
| 99 | } |