clang-tidy: add Chrome-inspired checks
[lttng-tools.git] / src / common / consumer / consumer.cpp
CommitLineData
3bd1e081 1/*
21cf9b6b 2 * Copyright (C) 2011 EfficiOS Inc.
ab5be9fa
MJ
3 * Copyright (C) 2011 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
4 * Copyright (C) 2012 David Goulet <dgoulet@efficios.com>
3bd1e081 5 *
ab5be9fa 6 * SPDX-License-Identifier: GPL-2.0-only
3bd1e081 7 *
3bd1e081
MD
8 */
9
6c1c0768 10#define _LGPL_SOURCE
c9e313bc
SM
11#include <common/align.hpp>
12#include <common/common.hpp>
13#include <common/compat/endian.hpp>
14#include <common/compat/poll.hpp>
15#include <common/consumer/consumer-metadata-cache.hpp>
16#include <common/consumer/consumer-stream.hpp>
17#include <common/consumer/consumer-testpoint.hpp>
18#include <common/consumer/consumer-timer.hpp>
19#include <common/consumer/consumer.hpp>
20#include <common/dynamic-array.hpp>
21#include <common/index/ctf-index.hpp>
22#include <common/index/index.hpp>
23#include <common/kernel-consumer/kernel-consumer.hpp>
24#include <common/kernel-ctl/kernel-ctl.hpp>
25#include <common/relayd/relayd.hpp>
26#include <common/sessiond-comm/relayd.hpp>
27#include <common/sessiond-comm/sessiond-comm.hpp>
28#include <common/string-utils/format.hpp>
29#include <common/time.hpp>
30#include <common/trace-chunk-registry.hpp>
31#include <common/trace-chunk.hpp>
32#include <common/ust-consumer/ust-consumer.hpp>
33#include <common/utils.hpp>
3bd1e081 34
28ab034a
JG
35#include <bin/lttng-consumerd/health-consumerd.hpp>
36#include <inttypes.h>
37#include <poll.h>
38#include <pthread.h>
39#include <signal.h>
40#include <stdlib.h>
41#include <string.h>
42#include <sys/mman.h>
43#include <sys/socket.h>
44#include <sys/types.h>
45#include <unistd.h>
46
97535efa 47lttng_consumer_global_data the_consumer_data;
3bd1e081 48
d8ef542d
MD
49enum consumer_channel_action {
50 CONSUMER_CHANNEL_ADD,
a0cbdd2e 51 CONSUMER_CHANNEL_DEL,
d8ef542d
MD
52 CONSUMER_CHANNEL_QUIT,
53};
54
f1494934 55namespace {
d8ef542d
MD
56struct consumer_channel_msg {
57 enum consumer_channel_action action;
28ab034a
JG
58 struct lttng_consumer_channel *chan; /* add */
59 uint64_t key; /* del */
d8ef542d
MD
60};
61
f1494934
JG
62/*
63 * Global hash table containing respectively metadata and data streams. The
64 * stream element in this ht should only be updated by the metadata poll thread
65 * for the metadata and the data poll thread for the data.
66 */
67struct lttng_ht *metadata_ht;
68struct lttng_ht *data_ht;
69} /* namespace */
70
80957876 71/* Flag used to temporarily pause data consumption from testpoints. */
cf0bcb51
JG
72int data_consumption_paused;
73
3bd1e081
MD
74/*
75 * Flag to inform the polling thread to quit when all fd hung up. Updated by
76 * the consumer_thread_receive_fds when it notices that all fds has hung up.
77 * Also updated by the signal handler (consumer_should_exit()). Read by the
78 * polling threads.
79 */
10211f5c 80int consumer_quit;
3bd1e081 81
cd9adb8b 82static const char *get_consumer_domain()
5da88b0f 83{
fa29bfbf 84 switch (the_consumer_data.type) {
5da88b0f
MD
85 case LTTNG_CONSUMER_KERNEL:
86 return DEFAULT_KERNEL_TRACE_DIR;
87 case LTTNG_CONSUMER64_UST:
88 /* Fall-through. */
89 case LTTNG_CONSUMER32_UST:
90 return DEFAULT_UST_TRACE_DIR;
91 default:
92 abort();
93 }
94}
95
acdb9057
DG
96/*
97 * Notify a thread lttng pipe to poll back again. This usually means that some
98 * global state has changed so we just send back the thread in a poll wait
99 * call.
100 */
101static void notify_thread_lttng_pipe(struct lttng_pipe *pipe)
102{
cd9adb8b 103 struct lttng_consumer_stream *null_stream = nullptr;
acdb9057 104
a0377dfe 105 LTTNG_ASSERT(pipe);
acdb9057
DG
106
107 (void) lttng_pipe_write(pipe, &null_stream, sizeof(null_stream));
108}
109
5c635c72
MD
110static void notify_health_quit_pipe(int *pipe)
111{
6cd525e8 112 ssize_t ret;
5c635c72 113
6cd525e8
MD
114 ret = lttng_write(pipe[1], "4", 1);
115 if (ret < 1) {
5c635c72
MD
116 PERROR("write consumer health quit");
117 }
118}
119
d8ef542d 120static void notify_channel_pipe(struct lttng_consumer_local_data *ctx,
28ab034a
JG
121 struct lttng_consumer_channel *chan,
122 uint64_t key,
123 enum consumer_channel_action action)
d8ef542d
MD
124{
125 struct consumer_channel_msg msg;
6cd525e8 126 ssize_t ret;
d8ef542d 127
e56251fc
DG
128 memset(&msg, 0, sizeof(msg));
129
d8ef542d
MD
130 msg.action = action;
131 msg.chan = chan;
f21dae48 132 msg.key = key;
6cd525e8
MD
133 ret = lttng_write(ctx->consumer_channel_pipe[1], &msg, sizeof(msg));
134 if (ret < sizeof(msg)) {
135 PERROR("notify_channel_pipe write error");
136 }
d8ef542d
MD
137}
138
28ab034a 139void notify_thread_del_channel(struct lttng_consumer_local_data *ctx, uint64_t key)
a0cbdd2e 140{
cd9adb8b 141 notify_channel_pipe(ctx, nullptr, key, CONSUMER_CHANNEL_DEL);
a0cbdd2e
MD
142}
143
d8ef542d 144static int read_channel_pipe(struct lttng_consumer_local_data *ctx,
28ab034a
JG
145 struct lttng_consumer_channel **chan,
146 uint64_t *key,
147 enum consumer_channel_action *action)
d8ef542d
MD
148{
149 struct consumer_channel_msg msg;
6cd525e8 150 ssize_t ret;
d8ef542d 151
6cd525e8
MD
152 ret = lttng_read(ctx->consumer_channel_pipe[0], &msg, sizeof(msg));
153 if (ret < sizeof(msg)) {
154 ret = -1;
155 goto error;
d8ef542d 156 }
6cd525e8
MD
157 *action = msg.action;
158 *chan = msg.chan;
159 *key = msg.key;
160error:
161 return (int) ret;
d8ef542d
MD
162}
163
212d67a2
DG
164/*
165 * Cleanup the stream list of a channel. Those streams are not yet globally
166 * visible
167 */
168static void clean_channel_stream_list(struct lttng_consumer_channel *channel)
169{
170 struct lttng_consumer_stream *stream, *stmp;
171
a0377dfe 172 LTTNG_ASSERT(channel);
212d67a2
DG
173
174 /* Delete streams that might have been left in the stream list. */
28ab034a 175 cds_list_for_each_entry_safe (stream, stmp, &channel->streams.head, send_node) {
212d67a2
DG
176 /*
177 * Once a stream is added to this list, the buffers were created so we
178 * have a guarantee that this call will succeed. Setting the monitor
179 * mode to 0 so we don't lock nor try to delete the stream from the
180 * global hash table.
181 */
182 stream->monitor = 0;
cd9adb8b 183 consumer_stream_destroy(stream, nullptr);
212d67a2
DG
184 }
185}
186
3bd1e081
MD
187/*
188 * Find a stream. The consumer_data.lock must be locked during this
189 * call.
190 */
28ab034a 191static struct lttng_consumer_stream *find_stream(uint64_t key, struct lttng_ht *ht)
3bd1e081 192{
e4421fec 193 struct lttng_ht_iter iter;
d88aee68 194 struct lttng_ht_node_u64 *node;
cd9adb8b 195 struct lttng_consumer_stream *stream = nullptr;
3bd1e081 196
a0377dfe 197 LTTNG_ASSERT(ht);
8389e4f8 198
d88aee68
DG
199 /* -1ULL keys are lookup failures */
200 if (key == (uint64_t) -1ULL) {
cd9adb8b 201 return nullptr;
7a57cf92 202 }
e4421fec 203
6065ceec
DG
204 rcu_read_lock();
205
d88aee68
DG
206 lttng_ht_lookup(ht, &key, &iter);
207 node = lttng_ht_iter_get_node_u64(&iter);
cd9adb8b 208 if (node != nullptr) {
0114db0e 209 stream = lttng::utils::container_of(node, &lttng_consumer_stream::node);
3bd1e081 210 }
e4421fec 211
6065ceec
DG
212 rcu_read_unlock();
213
e4421fec 214 return stream;
3bd1e081
MD
215}
216
da009f2c 217static void steal_stream_key(uint64_t key, struct lttng_ht *ht)
7ad0a0cb
MD
218{
219 struct lttng_consumer_stream *stream;
220
04253271 221 rcu_read_lock();
ffe60014 222 stream = find_stream(key, ht);
04253271 223 if (stream) {
da009f2c 224 stream->key = (uint64_t) -1ULL;
04253271
MD
225 /*
226 * We don't want the lookup to match, but we still need
227 * to iterate on this stream when iterating over the hash table. Just
228 * change the node key.
229 */
da009f2c 230 stream->node.key = (uint64_t) -1ULL;
04253271
MD
231 }
232 rcu_read_unlock();
7ad0a0cb
MD
233}
234
d56db448
DG
235/*
236 * Return a channel object for the given key.
237 *
238 * RCU read side lock MUST be acquired before calling this function and
239 * protects the channel ptr.
240 */
d88aee68 241struct lttng_consumer_channel *consumer_find_channel(uint64_t key)
3bd1e081 242{
e4421fec 243 struct lttng_ht_iter iter;
d88aee68 244 struct lttng_ht_node_u64 *node;
cd9adb8b 245 struct lttng_consumer_channel *channel = nullptr;
3bd1e081 246
48b7cdc2
FD
247 ASSERT_RCU_READ_LOCKED();
248
d88aee68
DG
249 /* -1ULL keys are lookup failures */
250 if (key == (uint64_t) -1ULL) {
cd9adb8b 251 return nullptr;
7a57cf92 252 }
e4421fec 253
fa29bfbf 254 lttng_ht_lookup(the_consumer_data.channel_ht, &key, &iter);
d88aee68 255 node = lttng_ht_iter_get_node_u64(&iter);
cd9adb8b 256 if (node != nullptr) {
0114db0e 257 channel = lttng::utils::container_of(node, &lttng_consumer_channel::node);
3bd1e081 258 }
e4421fec
DG
259
260 return channel;
3bd1e081
MD
261}
262
b5a6470f
DG
263/*
264 * There is a possibility that the consumer does not have enough time between
265 * the close of the channel on the session daemon and the cleanup in here thus
266 * once we have a channel add with an existing key, we know for sure that this
267 * channel will eventually get cleaned up by all streams being closed.
268 *
269 * This function just nullifies the already existing channel key.
270 */
271static void steal_channel_key(uint64_t key)
272{
273 struct lttng_consumer_channel *channel;
274
275 rcu_read_lock();
276 channel = consumer_find_channel(key);
277 if (channel) {
278 channel->key = (uint64_t) -1ULL;
279 /*
280 * We don't want the lookup to match, but we still need to iterate on
281 * this channel when iterating over the hash table. Just change the
282 * node key.
283 */
284 channel->node.key = (uint64_t) -1ULL;
285 }
286 rcu_read_unlock();
287}
288
ffe60014 289static void free_channel_rcu(struct rcu_head *head)
702b1ea4 290{
28ab034a 291 struct lttng_ht_node_u64 *node = lttng::utils::container_of(head, &lttng_ht_node_u64::head);
ffe60014 292 struct lttng_consumer_channel *channel =
0114db0e 293 lttng::utils::container_of(node, &lttng_consumer_channel::node);
702b1ea4 294
fa29bfbf 295 switch (the_consumer_data.type) {
b83e03c4
MD
296 case LTTNG_CONSUMER_KERNEL:
297 break;
298 case LTTNG_CONSUMER32_UST:
299 case LTTNG_CONSUMER64_UST:
300 lttng_ustconsumer_free_channel(channel);
301 break;
302 default:
303 ERR("Unknown consumer_data type");
304 abort();
305 }
ffe60014 306 free(channel);
702b1ea4
MD
307}
308
00e2e675
DG
309/*
310 * RCU protected relayd socket pair free.
311 */
ffe60014 312static void free_relayd_rcu(struct rcu_head *head)
00e2e675 313{
28ab034a 314 struct lttng_ht_node_u64 *node = lttng::utils::container_of(head, &lttng_ht_node_u64::head);
00e2e675 315 struct consumer_relayd_sock_pair *relayd =
0114db0e 316 lttng::utils::container_of(node, &consumer_relayd_sock_pair::node);
00e2e675 317
8994307f
DG
318 /*
319 * Close all sockets. This is done in the call RCU since we don't want the
320 * socket fds to be reassigned thus potentially creating bad state of the
321 * relayd object.
322 *
323 * We do not have to lock the control socket mutex here since at this stage
324 * there is no one referencing to this relayd object.
325 */
326 (void) relayd_close(&relayd->control_sock);
327 (void) relayd_close(&relayd->data_sock);
328
3a84e2f3 329 pthread_mutex_destroy(&relayd->ctrl_sock_mutex);
00e2e675
DG
330 free(relayd);
331}
332
333/*
334 * Destroy and free relayd socket pair object.
00e2e675 335 */
51230d70 336void consumer_destroy_relayd(struct consumer_relayd_sock_pair *relayd)
00e2e675
DG
337{
338 int ret;
339 struct lttng_ht_iter iter;
340
cd9adb8b 341 if (relayd == nullptr) {
173af62f
DG
342 return;
343 }
344
00e2e675
DG
345 DBG("Consumer destroy and close relayd socket pair");
346
347 iter.iter.node = &relayd->node.node;
fa29bfbf 348 ret = lttng_ht_del(the_consumer_data.relayd_ht, &iter);
173af62f 349 if (ret != 0) {
8994307f 350 /* We assume the relayd is being or is destroyed */
173af62f
DG
351 return;
352 }
00e2e675 353
00e2e675 354 /* RCU free() call */
ffe60014
DG
355 call_rcu(&relayd->node.head, free_relayd_rcu);
356}
357
358/*
359 * Remove a channel from the global list protected by a mutex. This function is
360 * also responsible for freeing its data structures.
361 */
362void consumer_del_channel(struct lttng_consumer_channel *channel)
363{
ffe60014
DG
364 struct lttng_ht_iter iter;
365
d88aee68 366 DBG("Consumer delete channel key %" PRIu64, channel->key);
ffe60014 367
fa29bfbf 368 pthread_mutex_lock(&the_consumer_data.lock);
a9838785 369 pthread_mutex_lock(&channel->lock);
ffe60014 370
212d67a2
DG
371 /* Destroy streams that might have been left in the stream list. */
372 clean_channel_stream_list(channel);
51e762e5 373
d3e2ba59
JD
374 if (channel->live_timer_enabled == 1) {
375 consumer_timer_live_stop(channel);
376 }
e9404c27
JG
377 if (channel->monitor_timer_enabled == 1) {
378 consumer_timer_monitor_stop(channel);
379 }
d3e2ba59 380
319dcddc
JG
381 /*
382 * Send a last buffer statistics sample to the session daemon
383 * to ensure it tracks the amount of data consumed by this channel.
384 */
385 sample_and_send_channel_buffer_stats(channel);
386
fa29bfbf 387 switch (the_consumer_data.type) {
ffe60014
DG
388 case LTTNG_CONSUMER_KERNEL:
389 break;
390 case LTTNG_CONSUMER32_UST:
391 case LTTNG_CONSUMER64_UST:
392 lttng_ustconsumer_del_channel(channel);
393 break;
394 default:
395 ERR("Unknown consumer_data type");
a0377dfe 396 abort();
ffe60014
DG
397 goto end;
398 }
399
d2956687 400 lttng_trace_chunk_put(channel->trace_chunk);
cd9adb8b 401 channel->trace_chunk = nullptr;
5c3892a6 402
d2956687
JG
403 if (channel->is_published) {
404 int ret;
405
406 rcu_read_lock();
407 iter.iter.node = &channel->node.node;
fa29bfbf 408 ret = lttng_ht_del(the_consumer_data.channel_ht, &iter);
a0377dfe 409 LTTNG_ASSERT(!ret);
ffe60014 410
d2956687 411 iter.iter.node = &channel->channels_by_session_id_ht_node.node;
28ab034a 412 ret = lttng_ht_del(the_consumer_data.channels_by_session_id_ht, &iter);
a0377dfe 413 LTTNG_ASSERT(!ret);
d2956687
JG
414 rcu_read_unlock();
415 }
416
b6921a17
JG
417 channel->is_deleted = true;
418 call_rcu(&channel->node.head, free_channel_rcu);
ffe60014 419end:
a9838785 420 pthread_mutex_unlock(&channel->lock);
fa29bfbf 421 pthread_mutex_unlock(&the_consumer_data.lock);
00e2e675
DG
422}
423
228b5bf7
DG
424/*
425 * Iterate over the relayd hash table and destroy each element. Finally,
426 * destroy the whole hash table.
427 */
cd9adb8b 428static void cleanup_relayd_ht()
228b5bf7
DG
429{
430 struct lttng_ht_iter iter;
431 struct consumer_relayd_sock_pair *relayd;
432
433 rcu_read_lock();
434
28ab034a 435 cds_lfht_for_each_entry (the_consumer_data.relayd_ht->ht, &iter.iter, relayd, node.node) {
51230d70 436 consumer_destroy_relayd(relayd);
228b5bf7
DG
437 }
438
228b5bf7 439 rcu_read_unlock();
36b588ed 440
fa29bfbf 441 lttng_ht_destroy(the_consumer_data.relayd_ht);
228b5bf7
DG
442}
443
8994307f
DG
444/*
445 * Update the end point status of all streams having the given network sequence
446 * index (relayd index).
447 *
448 * It's atomically set without having the stream mutex locked which is fine
449 * because we handle the write/read race with a pipe wakeup for each thread.
450 */
da009f2c 451static void update_endpoint_status_by_netidx(uint64_t net_seq_idx,
28ab034a 452 enum consumer_endpoint_status status)
8994307f
DG
453{
454 struct lttng_ht_iter iter;
455 struct lttng_consumer_stream *stream;
456
da009f2c 457 DBG("Consumer set delete flag on stream by idx %" PRIu64, net_seq_idx);
8994307f
DG
458
459 rcu_read_lock();
460
461 /* Let's begin with metadata */
28ab034a 462 cds_lfht_for_each_entry (metadata_ht->ht, &iter.iter, stream, node.node) {
8994307f
DG
463 if (stream->net_seq_idx == net_seq_idx) {
464 uatomic_set(&stream->endpoint_status, status);
465 DBG("Delete flag set to metadata stream %d", stream->wait_fd);
466 }
467 }
468
469 /* Follow up by the data streams */
28ab034a 470 cds_lfht_for_each_entry (data_ht->ht, &iter.iter, stream, node.node) {
8994307f
DG
471 if (stream->net_seq_idx == net_seq_idx) {
472 uatomic_set(&stream->endpoint_status, status);
473 DBG("Delete flag set to data stream %d", stream->wait_fd);
474 }
475 }
476 rcu_read_unlock();
477}
478
479/*
480 * Cleanup a relayd object by flagging every associated streams for deletion,
481 * destroying the object meaning removing it from the relayd hash table,
482 * closing the sockets and freeing the memory in a RCU call.
483 *
484 * If a local data context is available, notify the threads that the streams'
485 * state have changed.
486 */
9276e5c8 487void lttng_consumer_cleanup_relayd(struct consumer_relayd_sock_pair *relayd)
8994307f 488{
da009f2c 489 uint64_t netidx;
8994307f 490
a0377dfe 491 LTTNG_ASSERT(relayd);
8994307f 492
97535efa 493 DBG("Cleaning up relayd object ID %" PRIu64, relayd->net_seq_idx);
9617607b 494
8994307f
DG
495 /* Save the net sequence index before destroying the object */
496 netidx = relayd->net_seq_idx;
497
498 /*
499 * Delete the relayd from the relayd hash table, close the sockets and free
500 * the object in a RCU call.
501 */
51230d70 502 consumer_destroy_relayd(relayd);
8994307f
DG
503
504 /* Set inactive endpoint to all streams */
505 update_endpoint_status_by_netidx(netidx, CONSUMER_ENDPOINT_INACTIVE);
506
507 /*
508 * With a local data context, notify the threads that the streams' state
509 * have changed. The write() action on the pipe acts as an "implicit"
510 * memory barrier ordering the updates of the end point status from the
511 * read of this status which happens AFTER receiving this notify.
512 */
9276e5c8
JR
513 notify_thread_lttng_pipe(relayd->ctx->consumer_data_pipe);
514 notify_thread_lttng_pipe(relayd->ctx->consumer_metadata_pipe);
8994307f
DG
515}
516
a6ba4fe1
DG
517/*
518 * Flag a relayd socket pair for destruction. Destroy it if the refcount
519 * reaches zero.
520 *
521 * RCU read side lock MUST be aquired before calling this function.
522 */
523void consumer_flag_relayd_for_destroy(struct consumer_relayd_sock_pair *relayd)
524{
a0377dfe 525 LTTNG_ASSERT(relayd);
48b7cdc2 526 ASSERT_RCU_READ_LOCKED();
a6ba4fe1
DG
527
528 /* Set destroy flag for this object */
529 uatomic_set(&relayd->destroy_flag, 1);
530
531 /* Destroy the relayd if refcount is 0 */
532 if (uatomic_read(&relayd->refcount) == 0) {
51230d70 533 consumer_destroy_relayd(relayd);
a6ba4fe1
DG
534 }
535}
536
3bd1e081 537/*
1d1a276c
DG
538 * Completly destroy stream from every visiable data structure and the given
539 * hash table if one.
540 *
541 * One this call returns, the stream object is not longer usable nor visible.
3bd1e081 542 */
28ab034a 543void consumer_del_stream(struct lttng_consumer_stream *stream, struct lttng_ht *ht)
3bd1e081 544{
1d1a276c 545 consumer_stream_destroy(stream, ht);
3bd1e081
MD
546}
547
5ab66908
MD
548/*
549 * XXX naming of del vs destroy is all mixed up.
550 */
551void consumer_del_stream_for_data(struct lttng_consumer_stream *stream)
552{
553 consumer_stream_destroy(stream, data_ht);
554}
555
556void consumer_del_stream_for_metadata(struct lttng_consumer_stream *stream)
557{
558 consumer_stream_destroy(stream, metadata_ht);
559}
560
28ab034a
JG
561void consumer_stream_update_channel_attributes(struct lttng_consumer_stream *stream,
562 struct lttng_consumer_channel *channel)
d9a2e16e 563{
28ab034a 564 stream->channel_read_only_attributes.tracefile_size = channel->tracefile_size;
d9a2e16e
JD
565}
566
3bd1e081
MD
567/*
568 * Add a stream to the global list protected by a mutex.
569 */
66d583dc 570void consumer_add_data_stream(struct lttng_consumer_stream *stream)
3bd1e081 571{
5ab66908 572 struct lttng_ht *ht = data_ht;
3bd1e081 573
a0377dfe
FD
574 LTTNG_ASSERT(stream);
575 LTTNG_ASSERT(ht);
c77fc10a 576
d88aee68 577 DBG3("Adding consumer stream %" PRIu64, stream->key);
e316aad5 578
fa29bfbf 579 pthread_mutex_lock(&the_consumer_data.lock);
a9838785 580 pthread_mutex_lock(&stream->chan->lock);
ec6ea7d0 581 pthread_mutex_lock(&stream->chan->timer_lock);
2e818a6a 582 pthread_mutex_lock(&stream->lock);
b0b335c8 583 rcu_read_lock();
e316aad5 584
43c34bc3 585 /* Steal stream identifier to avoid having streams with the same key */
ffe60014 586 steal_stream_key(stream->key, ht);
43c34bc3 587
d88aee68 588 lttng_ht_add_unique_u64(ht, &stream->node);
00e2e675 589
28ab034a 590 lttng_ht_add_u64(the_consumer_data.stream_per_chan_id_ht, &stream->node_channel_id);
d8ef542d 591
ca22feea
DG
592 /*
593 * Add stream to the stream_list_ht of the consumer data. No need to steal
594 * the key since the HT does not use it and we allow to add redundant keys
595 * into this table.
596 */
28ab034a 597 lttng_ht_add_u64(the_consumer_data.stream_list_ht, &stream->node_session_id);
ca22feea 598
e316aad5 599 /*
ffe60014
DG
600 * When nb_init_stream_left reaches 0, we don't need to trigger any action
601 * in terms of destroying the associated channel, because the action that
e316aad5
DG
602 * causes the count to become 0 also causes a stream to be added. The
603 * channel deletion will thus be triggered by the following removal of this
604 * stream.
605 */
ffe60014 606 if (uatomic_read(&stream->chan->nb_init_stream_left) > 0) {
f2ad556d
MD
607 /* Increment refcount before decrementing nb_init_stream_left */
608 cmm_smp_wmb();
ffe60014 609 uatomic_dec(&stream->chan->nb_init_stream_left);
e316aad5
DG
610 }
611
612 /* Update consumer data once the node is inserted. */
fa29bfbf
SM
613 the_consumer_data.stream_count++;
614 the_consumer_data.need_update = 1;
3bd1e081 615
e316aad5 616 rcu_read_unlock();
2e818a6a 617 pthread_mutex_unlock(&stream->lock);
ec6ea7d0 618 pthread_mutex_unlock(&stream->chan->timer_lock);
a9838785 619 pthread_mutex_unlock(&stream->chan->lock);
fa29bfbf 620 pthread_mutex_unlock(&the_consumer_data.lock);
3bd1e081
MD
621}
622
00e2e675 623/*
3f8e211f
DG
624 * Add relayd socket to global consumer data hashtable. RCU read side lock MUST
625 * be acquired before calling this.
00e2e675 626 */
d09e1200 627static int add_relayd(struct consumer_relayd_sock_pair *relayd)
00e2e675
DG
628{
629 int ret = 0;
d88aee68 630 struct lttng_ht_node_u64 *node;
00e2e675
DG
631 struct lttng_ht_iter iter;
632
a0377dfe 633 LTTNG_ASSERT(relayd);
48b7cdc2 634 ASSERT_RCU_READ_LOCKED();
00e2e675 635
28ab034a 636 lttng_ht_lookup(the_consumer_data.relayd_ht, &relayd->net_seq_idx, &iter);
d88aee68 637 node = lttng_ht_iter_get_node_u64(&iter);
cd9adb8b 638 if (node != nullptr) {
00e2e675
DG
639 goto end;
640 }
fa29bfbf 641 lttng_ht_add_unique_u64(the_consumer_data.relayd_ht, &relayd->node);
00e2e675 642
00e2e675
DG
643end:
644 return ret;
645}
646
647/*
648 * Allocate and return a consumer relayd socket.
649 */
28ab034a 650static struct consumer_relayd_sock_pair *consumer_allocate_relayd_sock_pair(uint64_t net_seq_idx)
00e2e675 651{
cd9adb8b 652 struct consumer_relayd_sock_pair *obj = nullptr;
00e2e675 653
da009f2c
MD
654 /* net sequence index of -1 is a failure */
655 if (net_seq_idx == (uint64_t) -1ULL) {
00e2e675
DG
656 goto error;
657 }
658
64803277 659 obj = zmalloc<consumer_relayd_sock_pair>();
cd9adb8b 660 if (obj == nullptr) {
00e2e675
DG
661 PERROR("zmalloc relayd sock");
662 goto error;
663 }
664
665 obj->net_seq_idx = net_seq_idx;
666 obj->refcount = 0;
173af62f 667 obj->destroy_flag = 0;
f96e4545
MD
668 obj->control_sock.sock.fd = -1;
669 obj->data_sock.sock.fd = -1;
d88aee68 670 lttng_ht_node_init_u64(&obj->node, obj->net_seq_idx);
cd9adb8b 671 pthread_mutex_init(&obj->ctrl_sock_mutex, nullptr);
00e2e675
DG
672
673error:
674 return obj;
675}
676
677/*
678 * Find a relayd socket pair in the global consumer data.
679 *
680 * Return the object if found else NULL.
b0b335c8
MD
681 * RCU read-side lock must be held across this call and while using the
682 * returned object.
00e2e675 683 */
d88aee68 684struct consumer_relayd_sock_pair *consumer_find_relayd(uint64_t key)
00e2e675
DG
685{
686 struct lttng_ht_iter iter;
d88aee68 687 struct lttng_ht_node_u64 *node;
cd9adb8b 688 struct consumer_relayd_sock_pair *relayd = nullptr;
00e2e675 689
48b7cdc2
FD
690 ASSERT_RCU_READ_LOCKED();
691
00e2e675 692 /* Negative keys are lookup failures */
d88aee68 693 if (key == (uint64_t) -1ULL) {
00e2e675
DG
694 goto error;
695 }
696
fa29bfbf 697 lttng_ht_lookup(the_consumer_data.relayd_ht, &key, &iter);
d88aee68 698 node = lttng_ht_iter_get_node_u64(&iter);
cd9adb8b 699 if (node != nullptr) {
0114db0e 700 relayd = lttng::utils::container_of(node, &consumer_relayd_sock_pair::node);
00e2e675
DG
701 }
702
00e2e675
DG
703error:
704 return relayd;
705}
706
10a50311
JD
707/*
708 * Find a relayd and send the stream
709 *
710 * Returns 0 on success, < 0 on error
711 */
28ab034a 712int consumer_send_relayd_stream(struct lttng_consumer_stream *stream, char *path)
10a50311
JD
713{
714 int ret = 0;
715 struct consumer_relayd_sock_pair *relayd;
716
a0377dfe
FD
717 LTTNG_ASSERT(stream);
718 LTTNG_ASSERT(stream->net_seq_idx != -1ULL);
719 LTTNG_ASSERT(path);
10a50311
JD
720
721 /* The stream is not metadata. Get relayd reference if exists. */
722 rcu_read_lock();
723 relayd = consumer_find_relayd(stream->net_seq_idx);
cd9adb8b 724 if (relayd != nullptr) {
10a50311
JD
725 /* Add stream on the relayd */
726 pthread_mutex_lock(&relayd->ctrl_sock_mutex);
28ab034a
JG
727 ret = relayd_add_stream(&relayd->control_sock,
728 stream->name,
729 get_consumer_domain(),
730 path,
731 &stream->relayd_stream_id,
732 stream->chan->tracefile_size,
733 stream->chan->tracefile_count,
734 stream->trace_chunk);
10a50311
JD
735 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
736 if (ret < 0) {
28ab034a
JG
737 ERR("Relayd add stream failed. Cleaning up relayd %" PRIu64 ".",
738 relayd->net_seq_idx);
9276e5c8 739 lttng_consumer_cleanup_relayd(relayd);
10a50311
JD
740 goto end;
741 }
1c20f0e2 742
10a50311 743 uatomic_inc(&relayd->refcount);
d01178b6 744 stream->sent_to_relayd = 1;
10a50311
JD
745 } else {
746 ERR("Stream %" PRIu64 " relayd ID %" PRIu64 " unknown. Can't send it.",
28ab034a
JG
747 stream->key,
748 stream->net_seq_idx);
10a50311
JD
749 ret = -1;
750 goto end;
751 }
752
753 DBG("Stream %s with key %" PRIu64 " sent to relayd id %" PRIu64,
28ab034a
JG
754 stream->name,
755 stream->key,
756 stream->net_seq_idx);
10a50311
JD
757
758end:
759 rcu_read_unlock();
760 return ret;
761}
762
a4baae1b
JD
763/*
764 * Find a relayd and send the streams sent message
765 *
766 * Returns 0 on success, < 0 on error
767 */
768int consumer_send_relayd_streams_sent(uint64_t net_seq_idx)
769{
770 int ret = 0;
771 struct consumer_relayd_sock_pair *relayd;
772
a0377dfe 773 LTTNG_ASSERT(net_seq_idx != -1ULL);
a4baae1b
JD
774
775 /* The stream is not metadata. Get relayd reference if exists. */
776 rcu_read_lock();
777 relayd = consumer_find_relayd(net_seq_idx);
cd9adb8b 778 if (relayd != nullptr) {
a4baae1b
JD
779 /* Add stream on the relayd */
780 pthread_mutex_lock(&relayd->ctrl_sock_mutex);
781 ret = relayd_streams_sent(&relayd->control_sock);
782 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
783 if (ret < 0) {
28ab034a
JG
784 ERR("Relayd streams sent failed. Cleaning up relayd %" PRIu64 ".",
785 relayd->net_seq_idx);
9276e5c8 786 lttng_consumer_cleanup_relayd(relayd);
a4baae1b
JD
787 goto end;
788 }
789 } else {
28ab034a 790 ERR("Relayd ID %" PRIu64 " unknown. Can't send streams_sent.", net_seq_idx);
a4baae1b
JD
791 ret = -1;
792 goto end;
793 }
794
795 ret = 0;
796 DBG("All streams sent relayd id %" PRIu64, net_seq_idx);
797
798end:
799 rcu_read_unlock();
800 return ret;
801}
802
10a50311
JD
803/*
804 * Find a relayd and close the stream
805 */
806void close_relayd_stream(struct lttng_consumer_stream *stream)
807{
808 struct consumer_relayd_sock_pair *relayd;
809
810 /* The stream is not metadata. Get relayd reference if exists. */
811 rcu_read_lock();
812 relayd = consumer_find_relayd(stream->net_seq_idx);
813 if (relayd) {
814 consumer_stream_relayd_close(stream, relayd);
815 }
816 rcu_read_unlock();
817}
818
00e2e675
DG
819/*
820 * Handle stream for relayd transmission if the stream applies for network
821 * streaming where the net sequence index is set.
822 *
823 * Return destination file descriptor or negative value on error.
824 */
6197aea7 825static int write_relayd_stream_header(struct lttng_consumer_stream *stream,
28ab034a
JG
826 size_t data_size,
827 unsigned long padding,
828 struct consumer_relayd_sock_pair *relayd)
00e2e675
DG
829{
830 int outfd = -1, ret;
00e2e675
DG
831 struct lttcomm_relayd_data_hdr data_hdr;
832
833 /* Safety net */
a0377dfe
FD
834 LTTNG_ASSERT(stream);
835 LTTNG_ASSERT(relayd);
00e2e675
DG
836
837 /* Reset data header */
838 memset(&data_hdr, 0, sizeof(data_hdr));
839
00e2e675
DG
840 if (stream->metadata_flag) {
841 /* Caller MUST acquire the relayd control socket lock */
842 ret = relayd_send_metadata(&relayd->control_sock, data_size);
843 if (ret < 0) {
844 goto error;
845 }
846
847 /* Metadata are always sent on the control socket. */
6151a90f 848 outfd = relayd->control_sock.sock.fd;
00e2e675
DG
849 } else {
850 /* Set header with stream information */
851 data_hdr.stream_id = htobe64(stream->relayd_stream_id);
852 data_hdr.data_size = htobe32(data_size);
1d4dfdef 853 data_hdr.padding_size = htobe32(padding);
c35f9726 854
39df6d9f
DG
855 /*
856 * Note that net_seq_num below is assigned with the *current* value of
857 * next_net_seq_num and only after that the next_net_seq_num will be
858 * increment. This is why when issuing a command on the relayd using
859 * this next value, 1 should always be substracted in order to compare
860 * the last seen sequence number on the relayd side to the last sent.
861 */
3604f373 862 data_hdr.net_seq_num = htobe64(stream->next_net_seq_num);
00e2e675
DG
863 /* Other fields are zeroed previously */
864
28ab034a 865 ret = relayd_send_data_hdr(&relayd->data_sock, &data_hdr, sizeof(data_hdr));
00e2e675
DG
866 if (ret < 0) {
867 goto error;
868 }
869
3604f373
DG
870 ++stream->next_net_seq_num;
871
00e2e675 872 /* Set to go on data socket */
6151a90f 873 outfd = relayd->data_sock.sock.fd;
00e2e675
DG
874 }
875
876error:
877 return outfd;
878}
879
b1316da1
JG
880/*
881 * Write a character on the metadata poll pipe to wake the metadata thread.
882 * Returns 0 on success, -1 on error.
883 */
884int consumer_metadata_wakeup_pipe(const struct lttng_consumer_channel *channel)
885{
886 int ret = 0;
887
28ab034a 888 DBG("Waking up metadata poll thread (writing to pipe): channel name = '%s'", channel->name);
b1316da1
JG
889 if (channel->monitor && channel->metadata_stream) {
890 const char dummy = 'c';
28ab034a
JG
891 const ssize_t write_ret =
892 lttng_write(channel->metadata_stream->ust_metadata_poll_pipe[1], &dummy, 1);
b1316da1
JG
893
894 if (write_ret < 1) {
895 if (errno == EWOULDBLOCK) {
896 /*
897 * This is fine, the metadata poll thread
898 * is having a hard time keeping-up, but
899 * it will eventually wake-up and consume
900 * the available data.
901 */
902 ret = 0;
903 } else {
904 PERROR("Failed to write to UST metadata pipe while attempting to wake-up the metadata poll thread");
905 ret = -1;
906 goto end;
907 }
908 }
909 }
910
911end:
912 return ret;
913}
914
d2956687
JG
915/*
916 * Trigger a dump of the metadata content. Following/during the succesful
917 * completion of this call, the metadata poll thread will start receiving
918 * metadata packets to consume.
919 *
920 * The caller must hold the channel and stream locks.
921 */
28ab034a 922static int consumer_metadata_stream_dump(struct lttng_consumer_stream *stream)
d2956687
JG
923{
924 int ret;
925
926 ASSERT_LOCKED(stream->chan->lock);
927 ASSERT_LOCKED(stream->lock);
a0377dfe
FD
928 LTTNG_ASSERT(stream->metadata_flag);
929 LTTNG_ASSERT(stream->chan->trace_chunk);
d2956687 930
fa29bfbf 931 switch (the_consumer_data.type) {
d2956687
JG
932 case LTTNG_CONSUMER_KERNEL:
933 /*
934 * Reset the position of what has been read from the
935 * metadata cache to 0 so we can dump it again.
936 */
937 ret = kernctl_metadata_cache_dump(stream->wait_fd);
938 break;
939 case LTTNG_CONSUMER32_UST:
940 case LTTNG_CONSUMER64_UST:
941 /*
942 * Reset the position pushed from the metadata cache so it
943 * will write from the beginning on the next push.
944 */
945 stream->ust_metadata_pushed = 0;
946 ret = consumer_metadata_wakeup_pipe(stream->chan);
947 break;
948 default:
949 ERR("Unknown consumer_data type");
950 abort();
951 }
952 if (ret < 0) {
953 ERR("Failed to dump the metadata cache");
954 }
955 return ret;
956}
957
28ab034a
JG
958static int lttng_consumer_channel_set_trace_chunk(struct lttng_consumer_channel *channel,
959 struct lttng_trace_chunk *new_trace_chunk)
d2956687 960{
d2956687 961 pthread_mutex_lock(&channel->lock);
b6921a17
JG
962 if (channel->is_deleted) {
963 /*
964 * The channel has been logically deleted and should no longer
965 * be used. It has released its reference to its current trace
966 * chunk and should not acquire a new one.
967 *
968 * Return success as there is nothing for the caller to do.
969 */
970 goto end;
971 }
d2956687
JG
972
973 /*
974 * The acquisition of the reference cannot fail (barring
975 * a severe internal error) since a reference to the published
976 * chunk is already held by the caller.
977 */
978 if (new_trace_chunk) {
28ab034a 979 const bool acquired_reference = lttng_trace_chunk_get(new_trace_chunk);
d2956687 980
a0377dfe 981 LTTNG_ASSERT(acquired_reference);
d2956687
JG
982 }
983
984 lttng_trace_chunk_put(channel->trace_chunk);
985 channel->trace_chunk = new_trace_chunk;
d2956687
JG
986end:
987 pthread_mutex_unlock(&channel->lock);
ce1aa6fe 988 return 0;
d2956687
JG
989}
990
3bd1e081 991/*
ffe60014
DG
992 * Allocate and return a new lttng_consumer_channel object using the given key
993 * to initialize the hash table node.
994 *
995 * On error, return NULL.
3bd1e081 996 */
886224ff 997struct lttng_consumer_channel *consumer_allocate_channel(uint64_t key,
28ab034a
JG
998 uint64_t session_id,
999 const uint64_t *chunk_id,
1000 const char *pathname,
1001 const char *name,
1002 uint64_t relayd_id,
1003 enum lttng_event_output output,
1004 uint64_t tracefile_size,
1005 uint64_t tracefile_count,
1006 uint64_t session_id_per_pid,
1007 unsigned int monitor,
1008 unsigned int live_timer_interval,
1009 bool is_in_live_session,
1010 const char *root_shm_path,
1011 const char *shm_path)
3bd1e081 1012{
cd9adb8b
JG
1013 struct lttng_consumer_channel *channel = nullptr;
1014 struct lttng_trace_chunk *trace_chunk = nullptr;
d2956687
JG
1015
1016 if (chunk_id) {
1017 trace_chunk = lttng_trace_chunk_registry_find_chunk(
28ab034a 1018 the_consumer_data.chunk_registry, session_id, *chunk_id);
d2956687
JG
1019 if (!trace_chunk) {
1020 ERR("Failed to find trace chunk reference during creation of channel");
1021 goto end;
1022 }
1023 }
3bd1e081 1024
64803277 1025 channel = zmalloc<lttng_consumer_channel>();
cd9adb8b 1026 if (channel == nullptr) {
7a57cf92 1027 PERROR("malloc struct lttng_consumer_channel");
3bd1e081
MD
1028 goto end;
1029 }
ffe60014
DG
1030
1031 channel->key = key;
3bd1e081 1032 channel->refcount = 0;
ffe60014 1033 channel->session_id = session_id;
1950109e 1034 channel->session_id_per_pid = session_id_per_pid;
ffe60014 1035 channel->relayd_id = relayd_id;
1624d5b7
JD
1036 channel->tracefile_size = tracefile_size;
1037 channel->tracefile_count = tracefile_count;
2bba9e53 1038 channel->monitor = monitor;
ecc48a90 1039 channel->live_timer_interval = live_timer_interval;
a2814ea7 1040 channel->is_live = is_in_live_session;
cd9adb8b
JG
1041 pthread_mutex_init(&channel->lock, nullptr);
1042 pthread_mutex_init(&channel->timer_lock, nullptr);
ffe60014 1043
0c759fc9
DG
1044 switch (output) {
1045 case LTTNG_EVENT_SPLICE:
1046 channel->output = CONSUMER_CHANNEL_SPLICE;
1047 break;
1048 case LTTNG_EVENT_MMAP:
1049 channel->output = CONSUMER_CHANNEL_MMAP;
1050 break;
1051 default:
a0377dfe 1052 abort();
0c759fc9 1053 free(channel);
cd9adb8b 1054 channel = nullptr;
0c759fc9
DG
1055 goto end;
1056 }
1057
07b86b52
JD
1058 /*
1059 * In monitor mode, the streams associated with the channel will be put in
1060 * a special list ONLY owned by this channel. So, the refcount is set to 1
1061 * here meaning that the channel itself has streams that are referenced.
1062 *
1063 * On a channel deletion, once the channel is no longer visible, the
1064 * refcount is decremented and checked for a zero value to delete it. With
1065 * streams in no monitor mode, it will now be safe to destroy the channel.
1066 */
1067 if (!channel->monitor) {
1068 channel->refcount = 1;
1069 }
1070
ffe60014
DG
1071 strncpy(channel->pathname, pathname, sizeof(channel->pathname));
1072 channel->pathname[sizeof(channel->pathname) - 1] = '\0';
1073
1074 strncpy(channel->name, name, sizeof(channel->name));
1075 channel->name[sizeof(channel->name) - 1] = '\0';
1076
3d071855
MD
1077 if (root_shm_path) {
1078 strncpy(channel->root_shm_path, root_shm_path, sizeof(channel->root_shm_path));
1079 channel->root_shm_path[sizeof(channel->root_shm_path) - 1] = '\0';
1080 }
d7ba1388
MD
1081 if (shm_path) {
1082 strncpy(channel->shm_path, shm_path, sizeof(channel->shm_path));
1083 channel->shm_path[sizeof(channel->shm_path) - 1] = '\0';
1084 }
1085
d88aee68 1086 lttng_ht_node_init_u64(&channel->node, channel->key);
28ab034a 1087 lttng_ht_node_init_u64(&channel->channels_by_session_id_ht_node, channel->session_id);
d8ef542d
MD
1088
1089 channel->wait_fd = -1;
ffe60014
DG
1090 CDS_INIT_LIST_HEAD(&channel->streams.head);
1091
d2956687 1092 if (trace_chunk) {
28ab034a 1093 int ret = lttng_consumer_channel_set_trace_chunk(channel, trace_chunk);
d2956687
JG
1094 if (ret) {
1095 goto error;
1096 }
1097 }
1098
62a7b8ed 1099 DBG("Allocated channel (key %" PRIu64 ")", channel->key);
3bd1e081 1100
3bd1e081 1101end:
d2956687 1102 lttng_trace_chunk_put(trace_chunk);
3bd1e081 1103 return channel;
d2956687
JG
1104error:
1105 consumer_del_channel(channel);
cd9adb8b 1106 channel = nullptr;
d2956687 1107 goto end;
3bd1e081
MD
1108}
1109
1110/*
1111 * Add a channel to the global list protected by a mutex.
821fffb2 1112 *
b5a6470f 1113 * Always return 0 indicating success.
3bd1e081 1114 */
d8ef542d 1115int consumer_add_channel(struct lttng_consumer_channel *channel,
28ab034a 1116 struct lttng_consumer_local_data *ctx)
3bd1e081 1117{
fa29bfbf 1118 pthread_mutex_lock(&the_consumer_data.lock);
a9838785 1119 pthread_mutex_lock(&channel->lock);
ec6ea7d0 1120 pthread_mutex_lock(&channel->timer_lock);
c77fc10a 1121
b5a6470f
DG
1122 /*
1123 * This gives us a guarantee that the channel we are about to add to the
1124 * channel hash table will be unique. See this function comment on the why
1125 * we need to steel the channel key at this stage.
1126 */
1127 steal_channel_key(channel->key);
c77fc10a 1128
b5a6470f 1129 rcu_read_lock();
fa29bfbf
SM
1130 lttng_ht_add_unique_u64(the_consumer_data.channel_ht, &channel->node);
1131 lttng_ht_add_u64(the_consumer_data.channels_by_session_id_ht,
28ab034a 1132 &channel->channels_by_session_id_ht_node);
6065ceec 1133 rcu_read_unlock();
d2956687 1134 channel->is_published = true;
b5a6470f 1135
ec6ea7d0 1136 pthread_mutex_unlock(&channel->timer_lock);
a9838785 1137 pthread_mutex_unlock(&channel->lock);
fa29bfbf 1138 pthread_mutex_unlock(&the_consumer_data.lock);
702b1ea4 1139
b5a6470f 1140 if (channel->wait_fd != -1 && channel->type == CONSUMER_CHANNEL_TYPE_DATA) {
a0cbdd2e 1141 notify_channel_pipe(ctx, channel, -1, CONSUMER_CHANNEL_ADD);
d8ef542d 1142 }
b5a6470f
DG
1143
1144 return 0;
3bd1e081
MD
1145}
1146
1147/*
1148 * Allocate the pollfd structure and the local view of the out fds to avoid
1149 * doing a lookup in the linked list and concurrency issues when writing is
1150 * needed. Called with consumer_data.lock held.
1151 *
1152 * Returns the number of fds in the structures.
1153 */
ffe60014 1154static int update_poll_array(struct lttng_consumer_local_data *ctx,
28ab034a
JG
1155 struct pollfd **pollfd,
1156 struct lttng_consumer_stream **local_stream,
1157 struct lttng_ht *ht,
1158 int *nb_inactive_fd)
3bd1e081 1159{
3bd1e081 1160 int i = 0;
e4421fec
DG
1161 struct lttng_ht_iter iter;
1162 struct lttng_consumer_stream *stream;
3bd1e081 1163
a0377dfe
FD
1164 LTTNG_ASSERT(ctx);
1165 LTTNG_ASSERT(ht);
1166 LTTNG_ASSERT(pollfd);
1167 LTTNG_ASSERT(local_stream);
ffe60014 1168
3bd1e081 1169 DBG("Updating poll fd array");
9a2fcf78 1170 *nb_inactive_fd = 0;
481d6c57 1171 rcu_read_lock();
28ab034a 1172 cds_lfht_for_each_entry (ht->ht, &iter.iter, stream, node.node) {
8994307f
DG
1173 /*
1174 * Only active streams with an active end point can be added to the
1175 * poll set and local stream storage of the thread.
1176 *
1177 * There is a potential race here for endpoint_status to be updated
1178 * just after the check. However, this is OK since the stream(s) will
1179 * be deleted once the thread is notified that the end point state has
1180 * changed where this function will be called back again.
9a2fcf78
JD
1181 *
1182 * We track the number of inactive FDs because they still need to be
1183 * closed by the polling thread after a wakeup on the data_pipe or
1184 * metadata_pipe.
8994307f 1185 */
d2956687 1186 if (stream->endpoint_status == CONSUMER_ENDPOINT_INACTIVE) {
9a2fcf78 1187 (*nb_inactive_fd)++;
3bd1e081
MD
1188 continue;
1189 }
7972aab2
DG
1190 /*
1191 * This clobbers way too much the debug output. Uncomment that if you
1192 * need it for debugging purposes.
7972aab2 1193 */
e4421fec 1194 (*pollfd)[i].fd = stream->wait_fd;
3bd1e081 1195 (*pollfd)[i].events = POLLIN | POLLPRI;
e4421fec 1196 local_stream[i] = stream;
3bd1e081
MD
1197 i++;
1198 }
481d6c57 1199 rcu_read_unlock();
3bd1e081
MD
1200
1201 /*
50f8ae69 1202 * Insert the consumer_data_pipe at the end of the array and don't
3bd1e081
MD
1203 * increment i so nb_fd is the number of real FD.
1204 */
acdb9057 1205 (*pollfd)[i].fd = lttng_pipe_get_readfd(ctx->consumer_data_pipe);
509bb1cf 1206 (*pollfd)[i].events = POLLIN | POLLPRI;
02b3d176
DG
1207
1208 (*pollfd)[i + 1].fd = lttng_pipe_get_readfd(ctx->consumer_wakeup_pipe);
1209 (*pollfd)[i + 1].events = POLLIN | POLLPRI;
3bd1e081
MD
1210 return i;
1211}
1212
1213/*
84382d49
MD
1214 * Poll on the should_quit pipe and the command socket return -1 on
1215 * error, 1 if should exit, 0 if data is available on the command socket
3bd1e081
MD
1216 */
1217int lttng_consumer_poll_socket(struct pollfd *consumer_sockpoll)
1218{
1219 int num_rdy;
1220
88f2b785 1221restart:
3bd1e081
MD
1222 num_rdy = poll(consumer_sockpoll, 2, -1);
1223 if (num_rdy == -1) {
88f2b785
MD
1224 /*
1225 * Restart interrupted system call.
1226 */
1227 if (errno == EINTR) {
1228 goto restart;
1229 }
7a57cf92 1230 PERROR("Poll error");
84382d49 1231 return -1;
3bd1e081 1232 }
509bb1cf 1233 if (consumer_sockpoll[0].revents & (POLLIN | POLLPRI)) {
3bd1e081 1234 DBG("consumer_should_quit wake up");
84382d49 1235 return 1;
3bd1e081
MD
1236 }
1237 return 0;
3bd1e081
MD
1238}
1239
1240/*
1241 * Set the error socket.
1242 */
28ab034a 1243void lttng_consumer_set_error_sock(struct lttng_consumer_local_data *ctx, int sock)
3bd1e081
MD
1244{
1245 ctx->consumer_error_socket = sock;
1246}
1247
1248/*
1249 * Set the command socket path.
1250 */
28ab034a 1251void lttng_consumer_set_command_sock_path(struct lttng_consumer_local_data *ctx, char *sock)
3bd1e081
MD
1252{
1253 ctx->consumer_command_sock_path = sock;
1254}
1255
1256/*
1257 * Send return code to the session daemon.
1258 * If the socket is not defined, we return 0, it is not a fatal error
1259 */
ffe60014 1260int lttng_consumer_send_error(struct lttng_consumer_local_data *ctx, int cmd)
3bd1e081
MD
1261{
1262 if (ctx->consumer_error_socket > 0) {
28ab034a
JG
1263 return lttcomm_send_unix_sock(
1264 ctx->consumer_error_socket, &cmd, sizeof(enum lttcomm_sessiond_command));
3bd1e081
MD
1265 }
1266
1267 return 0;
1268}
1269
1270/*
228b5bf7
DG
1271 * Close all the tracefiles and stream fds and MUST be called when all
1272 * instances are destroyed i.e. when all threads were joined and are ended.
3bd1e081 1273 */
cd9adb8b 1274void lttng_consumer_cleanup()
3bd1e081 1275{
e4421fec 1276 struct lttng_ht_iter iter;
ffe60014 1277 struct lttng_consumer_channel *channel;
e10aec8f 1278 unsigned int trace_chunks_left;
6065ceec
DG
1279
1280 rcu_read_lock();
3bd1e081 1281
28ab034a 1282 cds_lfht_for_each_entry (the_consumer_data.channel_ht->ht, &iter.iter, channel, node.node) {
702b1ea4 1283 consumer_del_channel(channel);
3bd1e081 1284 }
6065ceec
DG
1285
1286 rcu_read_unlock();
d6ce1df2 1287
fa29bfbf
SM
1288 lttng_ht_destroy(the_consumer_data.channel_ht);
1289 lttng_ht_destroy(the_consumer_data.channels_by_session_id_ht);
228b5bf7
DG
1290
1291 cleanup_relayd_ht();
1292
fa29bfbf 1293 lttng_ht_destroy(the_consumer_data.stream_per_chan_id_ht);
d8ef542d 1294
228b5bf7
DG
1295 /*
1296 * This HT contains streams that are freed by either the metadata thread or
1297 * the data thread so we do *nothing* on the hash table and simply destroy
1298 * it.
1299 */
fa29bfbf 1300 lttng_ht_destroy(the_consumer_data.stream_list_ht);
28cc88f3 1301
e10aec8f
MD
1302 /*
1303 * Trace chunks in the registry may still exist if the session
1304 * daemon has encountered an internal error and could not
1305 * tear down its sessions and/or trace chunks properly.
1306 *
1307 * Release the session daemon's implicit reference to any remaining
1308 * trace chunk and print an error if any trace chunk was found. Note
1309 * that there are _no_ legitimate cases for trace chunks to be left,
1310 * it is a leak. However, it can happen following a crash of the
1311 * session daemon and not emptying the registry would cause an assertion
1312 * to hit.
1313 */
28ab034a
JG
1314 trace_chunks_left =
1315 lttng_trace_chunk_registry_put_each_chunk(the_consumer_data.chunk_registry);
e10aec8f
MD
1316 if (trace_chunks_left) {
1317 ERR("%u trace chunks are leaked by lttng-consumerd. "
28ab034a
JG
1318 "This can be caused by an internal error of the session daemon.",
1319 trace_chunks_left);
e10aec8f
MD
1320 }
1321 /* Run all callbacks freeing each chunk. */
1322 rcu_barrier();
fa29bfbf 1323 lttng_trace_chunk_registry_destroy(the_consumer_data.chunk_registry);
3bd1e081
MD
1324}
1325
1326/*
1327 * Called from signal handler.
1328 */
1329void lttng_consumer_should_exit(struct lttng_consumer_local_data *ctx)
1330{
6cd525e8
MD
1331 ssize_t ret;
1332
10211f5c 1333 CMM_STORE_SHARED(consumer_quit, 1);
6cd525e8
MD
1334 ret = lttng_write(ctx->consumer_should_quit[1], "4", 1);
1335 if (ret < 1) {
7a57cf92 1336 PERROR("write consumer quit");
3bd1e081 1337 }
ab1027f4
DG
1338
1339 DBG("Consumer flag that it should quit");
3bd1e081
MD
1340}
1341
5199ffc4
JG
1342/*
1343 * Flush pending writes to trace output disk file.
1344 */
28ab034a 1345static void lttng_consumer_sync_trace_file(struct lttng_consumer_stream *stream, off_t orig_offset)
3bd1e081 1346{
c7a78aab 1347 int ret;
3bd1e081
MD
1348 int outfd = stream->out_fd;
1349
1350 /*
1351 * This does a blocking write-and-wait on any page that belongs to the
1352 * subbuffer prior to the one we just wrote.
1353 * Don't care about error values, as these are just hints and ways to
1354 * limit the amount of page cache used.
1355 */
ffe60014 1356 if (orig_offset < stream->max_sb_size) {
3bd1e081
MD
1357 return;
1358 }
28ab034a
JG
1359 lttng_sync_file_range(outfd,
1360 orig_offset - stream->max_sb_size,
1361 stream->max_sb_size,
1362 SYNC_FILE_RANGE_WAIT_BEFORE | SYNC_FILE_RANGE_WRITE |
1363 SYNC_FILE_RANGE_WAIT_AFTER);
3bd1e081
MD
1364 /*
1365 * Give hints to the kernel about how we access the file:
1366 * POSIX_FADV_DONTNEED : we won't re-access data in a near future after
1367 * we write it.
1368 *
1369 * We need to call fadvise again after the file grows because the
1370 * kernel does not seem to apply fadvise to non-existing parts of the
1371 * file.
1372 *
1373 * Call fadvise _after_ having waited for the page writeback to
1374 * complete because the dirty page writeback semantic is not well
1375 * defined. So it can be expected to lead to lower throughput in
1376 * streaming.
1377 */
28ab034a
JG
1378 ret = posix_fadvise(
1379 outfd, orig_offset - stream->max_sb_size, stream->max_sb_size, POSIX_FADV_DONTNEED);
a0d0e127 1380 if (ret && ret != -ENOSYS) {
a74a5f4a
JG
1381 errno = ret;
1382 PERROR("posix_fadvise on fd %i", outfd);
c7a78aab 1383 }
3bd1e081
MD
1384}
1385
1386/*
1387 * Initialise the necessary environnement :
1388 * - create a new context
1389 * - create the poll_pipe
1390 * - create the should_quit pipe (for signal handler)
1391 * - create the thread pipe (for splice)
1392 *
1393 * Takes a function pointer as argument, this function is called when data is
1394 * available on a buffer. This function is responsible to do the
1395 * kernctl_get_next_subbuf, read the data with mmap or splice depending on the
1396 * buffer configuration and then kernctl_put_next_subbuf at the end.
1397 *
1398 * Returns a pointer to the new context or NULL on error.
1399 */
28ab034a
JG
1400struct lttng_consumer_local_data *
1401lttng_consumer_create(enum lttng_consumer_type type,
1402 ssize_t (*buffer_ready)(struct lttng_consumer_stream *stream,
1403 struct lttng_consumer_local_data *ctx,
1404 bool locked_by_caller),
1405 int (*recv_channel)(struct lttng_consumer_channel *channel),
1406 int (*recv_stream)(struct lttng_consumer_stream *stream),
1407 int (*update_stream)(uint64_t stream_key, uint32_t state))
3bd1e081 1408{
d8ef542d 1409 int ret;
3bd1e081
MD
1410 struct lttng_consumer_local_data *ctx;
1411
a0377dfe 1412 LTTNG_ASSERT(the_consumer_data.type == LTTNG_CONSUMER_UNKNOWN ||
28ab034a 1413 the_consumer_data.type == type);
fa29bfbf 1414 the_consumer_data.type = type;
3bd1e081 1415
64803277 1416 ctx = zmalloc<lttng_consumer_local_data>();
cd9adb8b 1417 if (ctx == nullptr) {
7a57cf92 1418 PERROR("allocating context");
3bd1e081
MD
1419 goto error;
1420 }
1421
1422 ctx->consumer_error_socket = -1;
331744e3 1423 ctx->consumer_metadata_socket = -1;
cd9adb8b 1424 pthread_mutex_init(&ctx->metadata_socket_lock, nullptr);
3bd1e081
MD
1425 /* assign the callbacks */
1426 ctx->on_buffer_ready = buffer_ready;
1427 ctx->on_recv_channel = recv_channel;
1428 ctx->on_recv_stream = recv_stream;
1429 ctx->on_update_stream = update_stream;
1430
acdb9057
DG
1431 ctx->consumer_data_pipe = lttng_pipe_open(0);
1432 if (!ctx->consumer_data_pipe) {
3bd1e081
MD
1433 goto error_poll_pipe;
1434 }
1435
02b3d176
DG
1436 ctx->consumer_wakeup_pipe = lttng_pipe_open(0);
1437 if (!ctx->consumer_wakeup_pipe) {
1438 goto error_wakeup_pipe;
1439 }
1440
3bd1e081
MD
1441 ret = pipe(ctx->consumer_should_quit);
1442 if (ret < 0) {
7a57cf92 1443 PERROR("Error creating recv pipe");
3bd1e081
MD
1444 goto error_quit_pipe;
1445 }
1446
d8ef542d
MD
1447 ret = pipe(ctx->consumer_channel_pipe);
1448 if (ret < 0) {
1449 PERROR("Error creating channel pipe");
1450 goto error_channel_pipe;
1451 }
1452
13886d2d
DG
1453 ctx->consumer_metadata_pipe = lttng_pipe_open(0);
1454 if (!ctx->consumer_metadata_pipe) {
fb3a43a9
DG
1455 goto error_metadata_pipe;
1456 }
3bd1e081 1457
e9404c27
JG
1458 ctx->channel_monitor_pipe = -1;
1459
fb3a43a9 1460 return ctx;
3bd1e081 1461
fb3a43a9 1462error_metadata_pipe:
d8ef542d
MD
1463 utils_close_pipe(ctx->consumer_channel_pipe);
1464error_channel_pipe:
d8ef542d 1465 utils_close_pipe(ctx->consumer_should_quit);
3bd1e081 1466error_quit_pipe:
02b3d176
DG
1467 lttng_pipe_destroy(ctx->consumer_wakeup_pipe);
1468error_wakeup_pipe:
acdb9057 1469 lttng_pipe_destroy(ctx->consumer_data_pipe);
3bd1e081
MD
1470error_poll_pipe:
1471 free(ctx);
1472error:
cd9adb8b 1473 return nullptr;
3bd1e081
MD
1474}
1475
282dadbc
MD
1476/*
1477 * Iterate over all streams of the hashtable and free them properly.
1478 */
1479static void destroy_data_stream_ht(struct lttng_ht *ht)
1480{
1481 struct lttng_ht_iter iter;
1482 struct lttng_consumer_stream *stream;
1483
cd9adb8b 1484 if (ht == nullptr) {
282dadbc
MD
1485 return;
1486 }
1487
1488 rcu_read_lock();
28ab034a 1489 cds_lfht_for_each_entry (ht->ht, &iter.iter, stream, node.node) {
282dadbc
MD
1490 /*
1491 * Ignore return value since we are currently cleaning up so any error
1492 * can't be handled.
1493 */
1494 (void) consumer_del_stream(stream, ht);
1495 }
1496 rcu_read_unlock();
1497
1498 lttng_ht_destroy(ht);
1499}
1500
1501/*
1502 * Iterate over all streams of the metadata hashtable and free them
1503 * properly.
1504 */
1505static void destroy_metadata_stream_ht(struct lttng_ht *ht)
1506{
1507 struct lttng_ht_iter iter;
1508 struct lttng_consumer_stream *stream;
1509
cd9adb8b 1510 if (ht == nullptr) {
282dadbc
MD
1511 return;
1512 }
1513
1514 rcu_read_lock();
28ab034a 1515 cds_lfht_for_each_entry (ht->ht, &iter.iter, stream, node.node) {
282dadbc
MD
1516 /*
1517 * Ignore return value since we are currently cleaning up so any error
1518 * can't be handled.
1519 */
1520 (void) consumer_del_metadata_stream(stream, ht);
1521 }
1522 rcu_read_unlock();
1523
1524 lttng_ht_destroy(ht);
1525}
1526
3bd1e081
MD
1527/*
1528 * Close all fds associated with the instance and free the context.
1529 */
1530void lttng_consumer_destroy(struct lttng_consumer_local_data *ctx)
1531{
4c462e79
MD
1532 int ret;
1533
ab1027f4
DG
1534 DBG("Consumer destroying it. Closing everything.");
1535
4f2e75b9
DG
1536 if (!ctx) {
1537 return;
1538 }
1539
282dadbc
MD
1540 destroy_data_stream_ht(data_ht);
1541 destroy_metadata_stream_ht(metadata_ht);
1542
4c462e79
MD
1543 ret = close(ctx->consumer_error_socket);
1544 if (ret) {
1545 PERROR("close");
1546 }
331744e3
JD
1547 ret = close(ctx->consumer_metadata_socket);
1548 if (ret) {
1549 PERROR("close");
1550 }
d8ef542d 1551 utils_close_pipe(ctx->consumer_channel_pipe);
acdb9057 1552 lttng_pipe_destroy(ctx->consumer_data_pipe);
13886d2d 1553 lttng_pipe_destroy(ctx->consumer_metadata_pipe);
02b3d176 1554 lttng_pipe_destroy(ctx->consumer_wakeup_pipe);
d8ef542d 1555 utils_close_pipe(ctx->consumer_should_quit);
fb3a43a9 1556
3bd1e081
MD
1557 unlink(ctx->consumer_command_sock_path);
1558 free(ctx);
1559}
1560
6197aea7
DG
1561/*
1562 * Write the metadata stream id on the specified file descriptor.
1563 */
28ab034a
JG
1564static int
1565write_relayd_metadata_id(int fd, struct lttng_consumer_stream *stream, unsigned long padding)
6197aea7 1566{
6cd525e8 1567 ssize_t ret;
1d4dfdef 1568 struct lttcomm_relayd_metadata_payload hdr;
6197aea7 1569
1d4dfdef
DG
1570 hdr.stream_id = htobe64(stream->relayd_stream_id);
1571 hdr.padding_size = htobe32(padding);
6cd525e8
MD
1572 ret = lttng_write(fd, (void *) &hdr, sizeof(hdr));
1573 if (ret < sizeof(hdr)) {
d7b75ec8 1574 /*
6f04ed72 1575 * This error means that the fd's end is closed so ignore the PERROR
d7b75ec8
DG
1576 * not to clubber the error output since this can happen in a normal
1577 * code path.
1578 */
1579 if (errno != EPIPE) {
1580 PERROR("write metadata stream id");
1581 }
1582 DBG3("Consumer failed to write relayd metadata id (errno: %d)", errno);
534d2592
DG
1583 /*
1584 * Set ret to a negative value because if ret != sizeof(hdr), we don't
1585 * handle writting the missing part so report that as an error and
1586 * don't lie to the caller.
1587 */
1588 ret = -1;
6197aea7
DG
1589 goto end;
1590 }
1d4dfdef 1591 DBG("Metadata stream id %" PRIu64 " with padding %lu written before data",
28ab034a
JG
1592 stream->relayd_stream_id,
1593 padding);
6197aea7
DG
1594
1595end:
6cd525e8 1596 return (int) ret;
6197aea7
DG
1597}
1598
3bd1e081 1599/*
09e26845
DG
1600 * Mmap the ring buffer, read it and write the data to the tracefile. This is a
1601 * core function for writing trace buffers to either the local filesystem or
1602 * the network.
1603 *
d2956687 1604 * It must be called with the stream and the channel lock held.
79d4ffb7 1605 *
09e26845 1606 * Careful review MUST be put if any changes occur!
3bd1e081
MD
1607 *
1608 * Returns the number of bytes written
1609 */
28ab034a
JG
1610ssize_t lttng_consumer_on_read_subbuffer_mmap(struct lttng_consumer_stream *stream,
1611 const struct lttng_buffer_view *buffer,
1612 unsigned long padding)
3bd1e081 1613{
994ab360 1614 ssize_t ret = 0;
f02e1e8a
DG
1615 off_t orig_offset = stream->out_fd_offset;
1616 /* Default is on the disk */
1617 int outfd = stream->out_fd;
cd9adb8b 1618 struct consumer_relayd_sock_pair *relayd = nullptr;
8994307f 1619 unsigned int relayd_hang_up = 0;
fd424d99
JG
1620 const size_t subbuf_content_size = buffer->size - padding;
1621 size_t write_len;
f02e1e8a
DG
1622
1623 /* RCU lock for the relayd pointer */
1624 rcu_read_lock();
28ab034a 1625 LTTNG_ASSERT(stream->net_seq_idx != (uint64_t) -1ULL || stream->trace_chunk);
d2956687 1626
f02e1e8a 1627 /* Flag that the current stream if set for network streaming. */
da009f2c 1628 if (stream->net_seq_idx != (uint64_t) -1ULL) {
f02e1e8a 1629 relayd = consumer_find_relayd(stream->net_seq_idx);
cd9adb8b 1630 if (relayd == nullptr) {
56591bac 1631 ret = -EPIPE;
f02e1e8a
DG
1632 goto end;
1633 }
1634 }
1635
f02e1e8a
DG
1636 /* Handle stream on the relayd if the output is on the network */
1637 if (relayd) {
fd424d99 1638 unsigned long netlen = subbuf_content_size;
f02e1e8a
DG
1639
1640 /*
1641 * Lock the control socket for the complete duration of the function
1642 * since from this point on we will use the socket.
1643 */
1644 if (stream->metadata_flag) {
1645 /* Metadata requires the control socket. */
1646 pthread_mutex_lock(&relayd->ctrl_sock_mutex);
93ec662e
JD
1647 if (stream->reset_metadata_flag) {
1648 ret = relayd_reset_metadata(&relayd->control_sock,
28ab034a
JG
1649 stream->relayd_stream_id,
1650 stream->metadata_version);
93ec662e
JD
1651 if (ret < 0) {
1652 relayd_hang_up = 1;
1653 goto write_error;
1654 }
1655 stream->reset_metadata_flag = 0;
1656 }
1d4dfdef 1657 netlen += sizeof(struct lttcomm_relayd_metadata_payload);
f02e1e8a
DG
1658 }
1659
1d4dfdef 1660 ret = write_relayd_stream_header(stream, netlen, padding, relayd);
994ab360
DG
1661 if (ret < 0) {
1662 relayd_hang_up = 1;
1663 goto write_error;
1664 }
1665 /* Use the returned socket. */
1666 outfd = ret;
f02e1e8a 1667
994ab360
DG
1668 /* Write metadata stream id before payload */
1669 if (stream->metadata_flag) {
239f61af 1670 ret = write_relayd_metadata_id(outfd, stream, padding);
994ab360 1671 if (ret < 0) {
8994307f
DG
1672 relayd_hang_up = 1;
1673 goto write_error;
1674 }
f02e1e8a 1675 }
1624d5b7 1676
fd424d99
JG
1677 write_len = subbuf_content_size;
1678 } else {
1679 /* No streaming; we have to write the full padding. */
93ec662e
JD
1680 if (stream->metadata_flag && stream->reset_metadata_flag) {
1681 ret = utils_truncate_stream_file(stream->out_fd, 0);
1682 if (ret < 0) {
1683 ERR("Reset metadata file");
1684 goto end;
1685 }
1686 stream->reset_metadata_flag = 0;
1687 }
1688
1624d5b7
JD
1689 /*
1690 * Check if we need to change the tracefile before writing the packet.
1691 */
1692 if (stream->chan->tracefile_size > 0 &&
28ab034a
JG
1693 (stream->tracefile_size_current + buffer->size) >
1694 stream->chan->tracefile_size) {
d2956687
JG
1695 ret = consumer_stream_rotate_output_files(stream);
1696 if (ret) {
1624d5b7
JD
1697 goto end;
1698 }
309167d2 1699 outfd = stream->out_fd;
a1ae300f 1700 orig_offset = 0;
1624d5b7 1701 }
fd424d99 1702 stream->tracefile_size_current += buffer->size;
fd424d99 1703 write_len = buffer->size;
f02e1e8a
DG
1704 }
1705
d02b8372
DG
1706 /*
1707 * This call guarantee that len or less is returned. It's impossible to
1708 * receive a ret value that is bigger than len.
1709 */
fd424d99 1710 ret = lttng_write(outfd, buffer->data, write_len);
e2d1190b 1711 DBG("Consumer mmap write() ret %zd (len %zu)", ret, write_len);
fd424d99 1712 if (ret < 0 || ((size_t) ret != write_len)) {
d02b8372
DG
1713 /*
1714 * Report error to caller if nothing was written else at least send the
1715 * amount written.
1716 */
1717 if (ret < 0) {
994ab360 1718 ret = -errno;
f02e1e8a 1719 }
994ab360 1720 relayd_hang_up = 1;
f02e1e8a 1721
d02b8372 1722 /* Socket operation failed. We consider the relayd dead */
fcf0f774 1723 if (errno == EPIPE) {
d02b8372
DG
1724 /*
1725 * This is possible if the fd is closed on the other side
1726 * (outfd) or any write problem. It can be verbose a bit for a
1727 * normal execution if for instance the relayd is stopped
1728 * abruptly. This can happen so set this to a DBG statement.
1729 */
1730 DBG("Consumer mmap write detected relayd hang up");
994ab360
DG
1731 } else {
1732 /* Unhandled error, print it and stop function right now. */
28ab034a 1733 PERROR("Error in write mmap (ret %zd != write_len %zu)", ret, write_len);
f02e1e8a 1734 }
994ab360 1735 goto write_error;
d02b8372
DG
1736 }
1737 stream->output_written += ret;
d02b8372
DG
1738
1739 /* This call is useless on a socket so better save a syscall. */
1740 if (!relayd) {
1741 /* This won't block, but will start writeout asynchronously */
28ab034a
JG
1742 lttng_sync_file_range(
1743 outfd, stream->out_fd_offset, write_len, SYNC_FILE_RANGE_WRITE);
fd424d99 1744 stream->out_fd_offset += write_len;
f5dbe415 1745 lttng_consumer_sync_trace_file(stream, orig_offset);
f02e1e8a 1746 }
f02e1e8a 1747
8994307f
DG
1748write_error:
1749 /*
1750 * This is a special case that the relayd has closed its socket. Let's
1751 * cleanup the relayd object and all associated streams.
1752 */
1753 if (relayd && relayd_hang_up) {
28ab034a 1754 ERR("Relayd hangup. Cleaning up relayd %" PRIu64 ".", relayd->net_seq_idx);
9276e5c8 1755 lttng_consumer_cleanup_relayd(relayd);
8994307f
DG
1756 }
1757
f02e1e8a
DG
1758end:
1759 /* Unlock only if ctrl socket used */
1760 if (relayd && stream->metadata_flag) {
1761 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
1762 }
1763
1764 rcu_read_unlock();
994ab360 1765 return ret;
3bd1e081
MD
1766}
1767
1768/*
1769 * Splice the data from the ring buffer to the tracefile.
1770 *
79d4ffb7
DG
1771 * It must be called with the stream lock held.
1772 *
3bd1e081
MD
1773 * Returns the number of bytes spliced.
1774 */
28ab034a
JG
1775ssize_t lttng_consumer_on_read_subbuffer_splice(struct lttng_consumer_local_data *ctx,
1776 struct lttng_consumer_stream *stream,
1777 unsigned long len,
1778 unsigned long padding)
3bd1e081 1779{
f02e1e8a
DG
1780 ssize_t ret = 0, written = 0, ret_splice = 0;
1781 loff_t offset = 0;
1782 off_t orig_offset = stream->out_fd_offset;
1783 int fd = stream->wait_fd;
1784 /* Default is on the disk */
1785 int outfd = stream->out_fd;
cd9adb8b 1786 struct consumer_relayd_sock_pair *relayd = nullptr;
fb3a43a9 1787 int *splice_pipe;
8994307f 1788 unsigned int relayd_hang_up = 0;
f02e1e8a 1789
fa29bfbf 1790 switch (the_consumer_data.type) {
3bd1e081 1791 case LTTNG_CONSUMER_KERNEL:
f02e1e8a 1792 break;
7753dea8
MD
1793 case LTTNG_CONSUMER32_UST:
1794 case LTTNG_CONSUMER64_UST:
f02e1e8a 1795 /* Not supported for user space tracing */
3bd1e081
MD
1796 return -ENOSYS;
1797 default:
1798 ERR("Unknown consumer_data type");
a0377dfe 1799 abort();
3bd1e081
MD
1800 }
1801
f02e1e8a
DG
1802 /* RCU lock for the relayd pointer */
1803 rcu_read_lock();
1804
1805 /* Flag that the current stream if set for network streaming. */
da009f2c 1806 if (stream->net_seq_idx != (uint64_t) -1ULL) {
f02e1e8a 1807 relayd = consumer_find_relayd(stream->net_seq_idx);
cd9adb8b 1808 if (relayd == nullptr) {
ad0b0d23 1809 written = -ret;
f02e1e8a
DG
1810 goto end;
1811 }
1812 }
a2361a61 1813 splice_pipe = stream->splice_pipe;
fb3a43a9 1814
f02e1e8a 1815 /* Write metadata stream id before payload */
1d4dfdef 1816 if (relayd) {
ad0b0d23 1817 unsigned long total_len = len;
f02e1e8a 1818
1d4dfdef
DG
1819 if (stream->metadata_flag) {
1820 /*
1821 * Lock the control socket for the complete duration of the function
1822 * since from this point on we will use the socket.
1823 */
1824 pthread_mutex_lock(&relayd->ctrl_sock_mutex);
1825
93ec662e
JD
1826 if (stream->reset_metadata_flag) {
1827 ret = relayd_reset_metadata(&relayd->control_sock,
28ab034a
JG
1828 stream->relayd_stream_id,
1829 stream->metadata_version);
93ec662e
JD
1830 if (ret < 0) {
1831 relayd_hang_up = 1;
1832 goto write_error;
1833 }
1834 stream->reset_metadata_flag = 0;
1835 }
28ab034a 1836 ret = write_relayd_metadata_id(splice_pipe[1], stream, padding);
1d4dfdef
DG
1837 if (ret < 0) {
1838 written = ret;
ad0b0d23
DG
1839 relayd_hang_up = 1;
1840 goto write_error;
1d4dfdef
DG
1841 }
1842
1843 total_len += sizeof(struct lttcomm_relayd_metadata_payload);
1844 }
1845
1846 ret = write_relayd_stream_header(stream, total_len, padding, relayd);
ad0b0d23
DG
1847 if (ret < 0) {
1848 written = ret;
1849 relayd_hang_up = 1;
1850 goto write_error;
f02e1e8a 1851 }
ad0b0d23
DG
1852 /* Use the returned socket. */
1853 outfd = ret;
1d4dfdef
DG
1854 } else {
1855 /* No streaming, we have to set the len with the full padding */
1856 len += padding;
1624d5b7 1857
93ec662e
JD
1858 if (stream->metadata_flag && stream->reset_metadata_flag) {
1859 ret = utils_truncate_stream_file(stream->out_fd, 0);
1860 if (ret < 0) {
1861 ERR("Reset metadata file");
1862 goto end;
1863 }
1864 stream->reset_metadata_flag = 0;
1865 }
1624d5b7
JD
1866 /*
1867 * Check if we need to change the tracefile before writing the packet.
1868 */
1869 if (stream->chan->tracefile_size > 0 &&
28ab034a 1870 (stream->tracefile_size_current + len) > stream->chan->tracefile_size) {
d2956687 1871 ret = consumer_stream_rotate_output_files(stream);
1624d5b7 1872 if (ret < 0) {
ad0b0d23 1873 written = ret;
1624d5b7
JD
1874 goto end;
1875 }
309167d2 1876 outfd = stream->out_fd;
a1ae300f 1877 orig_offset = 0;
1624d5b7
JD
1878 }
1879 stream->tracefile_size_current += len;
f02e1e8a
DG
1880 }
1881
1882 while (len > 0) {
1d4dfdef 1883 DBG("splice chan to pipe offset %lu of len %lu (fd : %d, pipe: %d)",
28ab034a
JG
1884 (unsigned long) offset,
1885 len,
1886 fd,
1887 splice_pipe[1]);
1888 ret_splice = splice(
cd9adb8b 1889 fd, &offset, splice_pipe[1], nullptr, len, SPLICE_F_MOVE | SPLICE_F_MORE);
f02e1e8a
DG
1890 DBG("splice chan to pipe, ret %zd", ret_splice);
1891 if (ret_splice < 0) {
d02b8372 1892 ret = errno;
ad0b0d23 1893 written = -ret;
d02b8372 1894 PERROR("Error in relay splice");
f02e1e8a
DG
1895 goto splice_error;
1896 }
1897
1898 /* Handle stream on the relayd if the output is on the network */
ad0b0d23
DG
1899 if (relayd && stream->metadata_flag) {
1900 size_t metadata_payload_size =
1901 sizeof(struct lttcomm_relayd_metadata_payload);
1902
1903 /* Update counter to fit the spliced data */
1904 ret_splice += metadata_payload_size;
1905 len += metadata_payload_size;
1906 /*
1907 * We do this so the return value can match the len passed as
1908 * argument to this function.
1909 */
1910 written -= metadata_payload_size;
f02e1e8a
DG
1911 }
1912
1913 /* Splice data out */
28ab034a 1914 ret_splice = splice(splice_pipe[0],
cd9adb8b 1915 nullptr,
28ab034a 1916 outfd,
cd9adb8b 1917 nullptr,
28ab034a
JG
1918 ret_splice,
1919 SPLICE_F_MOVE | SPLICE_F_MORE);
1920 DBG("Consumer splice pipe to file (out_fd: %d), ret %zd", outfd, ret_splice);
f02e1e8a 1921 if (ret_splice < 0) {
d02b8372 1922 ret = errno;
ad0b0d23
DG
1923 written = -ret;
1924 relayd_hang_up = 1;
1925 goto write_error;
f02e1e8a 1926 } else if (ret_splice > len) {
d02b8372
DG
1927 /*
1928 * We don't expect this code path to be executed but you never know
1929 * so this is an extra protection agains a buggy splice().
1930 */
f02e1e8a 1931 ret = errno;
ad0b0d23 1932 written += ret_splice;
28ab034a 1933 PERROR("Wrote more data than requested %zd (len: %lu)", ret_splice, len);
f02e1e8a 1934 goto splice_error;
d02b8372
DG
1935 } else {
1936 /* All good, update current len and continue. */
1937 len -= ret_splice;
f02e1e8a 1938 }
f02e1e8a
DG
1939
1940 /* This call is useless on a socket so better save a syscall. */
1941 if (!relayd) {
1942 /* This won't block, but will start writeout asynchronously */
28ab034a
JG
1943 lttng_sync_file_range(
1944 outfd, stream->out_fd_offset, ret_splice, SYNC_FILE_RANGE_WRITE);
f02e1e8a
DG
1945 stream->out_fd_offset += ret_splice;
1946 }
e5d1a9b3 1947 stream->output_written += ret_splice;
f02e1e8a
DG
1948 written += ret_splice;
1949 }
f5dbe415
JG
1950 if (!relayd) {
1951 lttng_consumer_sync_trace_file(stream, orig_offset);
1952 }
f02e1e8a
DG
1953 goto end;
1954
8994307f
DG
1955write_error:
1956 /*
1957 * This is a special case that the relayd has closed its socket. Let's
1958 * cleanup the relayd object and all associated streams.
1959 */
1960 if (relayd && relayd_hang_up) {
28ab034a 1961 ERR("Relayd hangup. Cleaning up relayd %" PRIu64 ".", relayd->net_seq_idx);
9276e5c8 1962 lttng_consumer_cleanup_relayd(relayd);
8994307f
DG
1963 /* Skip splice error so the consumer does not fail */
1964 goto end;
1965 }
1966
f02e1e8a
DG
1967splice_error:
1968 /* send the appropriate error description to sessiond */
1969 switch (ret) {
f02e1e8a 1970 case EINVAL:
f73fabfd 1971 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_SPLICE_EINVAL);
f02e1e8a
DG
1972 break;
1973 case ENOMEM:
f73fabfd 1974 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_SPLICE_ENOMEM);
f02e1e8a
DG
1975 break;
1976 case ESPIPE:
f73fabfd 1977 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_SPLICE_ESPIPE);
f02e1e8a
DG
1978 break;
1979 }
1980
1981end:
1982 if (relayd && stream->metadata_flag) {
1983 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
1984 }
1985
1986 rcu_read_unlock();
1987 return written;
3bd1e081
MD
1988}
1989
15055ce5
JD
1990/*
1991 * Sample the snapshot positions for a specific fd
1992 *
1993 * Returns 0 on success, < 0 on error
1994 */
1995int lttng_consumer_sample_snapshot_positions(struct lttng_consumer_stream *stream)
1996{
fa29bfbf 1997 switch (the_consumer_data.type) {
15055ce5
JD
1998 case LTTNG_CONSUMER_KERNEL:
1999 return lttng_kconsumer_sample_snapshot_positions(stream);
2000 case LTTNG_CONSUMER32_UST:
2001 case LTTNG_CONSUMER64_UST:
2002 return lttng_ustconsumer_sample_snapshot_positions(stream);
2003 default:
2004 ERR("Unknown consumer_data type");
a0377dfe 2005 abort();
15055ce5
JD
2006 return -ENOSYS;
2007 }
2008}
3bd1e081
MD
2009/*
2010 * Take a snapshot for a specific fd
2011 *
2012 * Returns 0 on success, < 0 on error
2013 */
ffe60014 2014int lttng_consumer_take_snapshot(struct lttng_consumer_stream *stream)
3bd1e081 2015{
fa29bfbf 2016 switch (the_consumer_data.type) {
3bd1e081 2017 case LTTNG_CONSUMER_KERNEL:
ffe60014 2018 return lttng_kconsumer_take_snapshot(stream);
7753dea8
MD
2019 case LTTNG_CONSUMER32_UST:
2020 case LTTNG_CONSUMER64_UST:
ffe60014 2021 return lttng_ustconsumer_take_snapshot(stream);
3bd1e081
MD
2022 default:
2023 ERR("Unknown consumer_data type");
a0377dfe 2024 abort();
3bd1e081
MD
2025 return -ENOSYS;
2026 }
3bd1e081
MD
2027}
2028
2029/*
2030 * Get the produced position
2031 *
2032 * Returns 0 on success, < 0 on error
2033 */
28ab034a 2034int lttng_consumer_get_produced_snapshot(struct lttng_consumer_stream *stream, unsigned long *pos)
3bd1e081 2035{
fa29bfbf 2036 switch (the_consumer_data.type) {
3bd1e081 2037 case LTTNG_CONSUMER_KERNEL:
ffe60014 2038 return lttng_kconsumer_get_produced_snapshot(stream, pos);
7753dea8
MD
2039 case LTTNG_CONSUMER32_UST:
2040 case LTTNG_CONSUMER64_UST:
ffe60014 2041 return lttng_ustconsumer_get_produced_snapshot(stream, pos);
3bd1e081
MD
2042 default:
2043 ERR("Unknown consumer_data type");
a0377dfe 2044 abort();
3bd1e081
MD
2045 return -ENOSYS;
2046 }
2047}
2048
15055ce5
JD
2049/*
2050 * Get the consumed position (free-running counter position in bytes).
2051 *
2052 * Returns 0 on success, < 0 on error
2053 */
28ab034a 2054int lttng_consumer_get_consumed_snapshot(struct lttng_consumer_stream *stream, unsigned long *pos)
15055ce5 2055{
fa29bfbf 2056 switch (the_consumer_data.type) {
15055ce5
JD
2057 case LTTNG_CONSUMER_KERNEL:
2058 return lttng_kconsumer_get_consumed_snapshot(stream, pos);
2059 case LTTNG_CONSUMER32_UST:
2060 case LTTNG_CONSUMER64_UST:
2061 return lttng_ustconsumer_get_consumed_snapshot(stream, pos);
2062 default:
2063 ERR("Unknown consumer_data type");
a0377dfe 2064 abort();
15055ce5
JD
2065 return -ENOSYS;
2066 }
2067}
2068
3bd1e081 2069int lttng_consumer_recv_cmd(struct lttng_consumer_local_data *ctx,
28ab034a
JG
2070 int sock,
2071 struct pollfd *consumer_sockpoll)
3bd1e081 2072{
fa29bfbf 2073 switch (the_consumer_data.type) {
3bd1e081
MD
2074 case LTTNG_CONSUMER_KERNEL:
2075 return lttng_kconsumer_recv_cmd(ctx, sock, consumer_sockpoll);
7753dea8
MD
2076 case LTTNG_CONSUMER32_UST:
2077 case LTTNG_CONSUMER64_UST:
3bd1e081
MD
2078 return lttng_ustconsumer_recv_cmd(ctx, sock, consumer_sockpoll);
2079 default:
2080 ERR("Unknown consumer_data type");
a0377dfe 2081 abort();
3bd1e081
MD
2082 return -ENOSYS;
2083 }
2084}
2085
cd9adb8b 2086static void lttng_consumer_close_all_metadata()
d88aee68 2087{
fa29bfbf 2088 switch (the_consumer_data.type) {
d88aee68
DG
2089 case LTTNG_CONSUMER_KERNEL:
2090 /*
2091 * The Kernel consumer has a different metadata scheme so we don't
2092 * close anything because the stream will be closed by the session
2093 * daemon.
2094 */
2095 break;
2096 case LTTNG_CONSUMER32_UST:
2097 case LTTNG_CONSUMER64_UST:
2098 /*
2099 * Close all metadata streams. The metadata hash table is passed and
2100 * this call iterates over it by closing all wakeup fd. This is safe
2101 * because at this point we are sure that the metadata producer is
2102 * either dead or blocked.
2103 */
6d574024 2104 lttng_ustconsumer_close_all_metadata(metadata_ht);
d88aee68
DG
2105 break;
2106 default:
2107 ERR("Unknown consumer_data type");
a0377dfe 2108 abort();
d88aee68
DG
2109 }
2110}
2111
fb3a43a9
DG
2112/*
2113 * Clean up a metadata stream and free its memory.
2114 */
28ab034a 2115void consumer_del_metadata_stream(struct lttng_consumer_stream *stream, struct lttng_ht *ht)
fb3a43a9 2116{
cd9adb8b 2117 struct lttng_consumer_channel *channel = nullptr;
a6ef8ee6 2118 bool free_channel = false;
fb3a43a9 2119
a0377dfe 2120 LTTNG_ASSERT(stream);
fb3a43a9
DG
2121 /*
2122 * This call should NEVER receive regular stream. It must always be
2123 * metadata stream and this is crucial for data structure synchronization.
2124 */
a0377dfe 2125 LTTNG_ASSERT(stream->metadata_flag);
fb3a43a9 2126
e316aad5
DG
2127 DBG3("Consumer delete metadata stream %d", stream->wait_fd);
2128
fa29bfbf 2129 pthread_mutex_lock(&the_consumer_data.lock);
a6ef8ee6
JG
2130 /*
2131 * Note that this assumes that a stream's channel is never changed and
2132 * that the stream's lock doesn't need to be taken to sample its
2133 * channel.
2134 */
2135 channel = stream->chan;
2136 pthread_mutex_lock(&channel->lock);
3dad2c0f 2137 pthread_mutex_lock(&stream->lock);
a6ef8ee6 2138 if (channel->metadata_cache) {
081424af 2139 /* Only applicable to userspace consumers. */
a6ef8ee6 2140 pthread_mutex_lock(&channel->metadata_cache->lock);
081424af 2141 }
8994307f 2142
6d574024
DG
2143 /* Remove any reference to that stream. */
2144 consumer_stream_delete(stream, ht);
ca22feea 2145
6d574024 2146 /* Close down everything including the relayd if one. */
d119bd01 2147 consumer_stream_close_output(stream);
6d574024
DG
2148 /* Destroy tracer buffers of the stream. */
2149 consumer_stream_destroy_buffers(stream);
fb3a43a9
DG
2150
2151 /* Atomically decrement channel refcount since other threads can use it. */
28ab034a
JG
2152 if (!uatomic_sub_return(&channel->refcount, 1) &&
2153 !uatomic_read(&channel->nb_init_stream_left)) {
c30aaa51 2154 /* Go for channel deletion! */
a6ef8ee6 2155 free_channel = true;
fb3a43a9 2156 }
cd9adb8b 2157 stream->chan = nullptr;
fb3a43a9 2158
73811ecc
DG
2159 /*
2160 * Nullify the stream reference so it is not used after deletion. The
6d574024
DG
2161 * channel lock MUST be acquired before being able to check for a NULL
2162 * pointer value.
73811ecc 2163 */
cd9adb8b 2164 channel->metadata_stream = nullptr;
73811ecc 2165
a6ef8ee6
JG
2166 if (channel->metadata_cache) {
2167 pthread_mutex_unlock(&channel->metadata_cache->lock);
081424af 2168 }
3dad2c0f 2169 pthread_mutex_unlock(&stream->lock);
a6ef8ee6 2170 pthread_mutex_unlock(&channel->lock);
fa29bfbf 2171 pthread_mutex_unlock(&the_consumer_data.lock);
e316aad5 2172
a6ef8ee6
JG
2173 if (free_channel) {
2174 consumer_del_channel(channel);
e316aad5
DG
2175 }
2176
d2956687 2177 lttng_trace_chunk_put(stream->trace_chunk);
cd9adb8b 2178 stream->trace_chunk = nullptr;
6d574024 2179 consumer_stream_free(stream);
fb3a43a9
DG
2180}
2181
2182/*
2183 * Action done with the metadata stream when adding it to the consumer internal
2184 * data structures to handle it.
2185 */
66d583dc 2186void consumer_add_metadata_stream(struct lttng_consumer_stream *stream)
fb3a43a9 2187{
5ab66908 2188 struct lttng_ht *ht = metadata_ht;
76082088 2189 struct lttng_ht_iter iter;
d88aee68 2190 struct lttng_ht_node_u64 *node;
fb3a43a9 2191
a0377dfe
FD
2192 LTTNG_ASSERT(stream);
2193 LTTNG_ASSERT(ht);
e316aad5 2194
d88aee68 2195 DBG3("Adding metadata stream %" PRIu64 " to hash table", stream->key);
e316aad5 2196
fa29bfbf 2197 pthread_mutex_lock(&the_consumer_data.lock);
a9838785 2198 pthread_mutex_lock(&stream->chan->lock);
ec6ea7d0 2199 pthread_mutex_lock(&stream->chan->timer_lock);
2e818a6a 2200 pthread_mutex_lock(&stream->lock);
e316aad5 2201
e316aad5
DG
2202 /*
2203 * From here, refcounts are updated so be _careful_ when returning an error
2204 * after this point.
2205 */
2206
fb3a43a9 2207 rcu_read_lock();
76082088
DG
2208
2209 /*
2210 * Lookup the stream just to make sure it does not exist in our internal
2211 * state. This should NEVER happen.
2212 */
d88aee68
DG
2213 lttng_ht_lookup(ht, &stream->key, &iter);
2214 node = lttng_ht_iter_get_node_u64(&iter);
a0377dfe 2215 LTTNG_ASSERT(!node);
76082088 2216
e316aad5 2217 /*
ffe60014
DG
2218 * When nb_init_stream_left reaches 0, we don't need to trigger any action
2219 * in terms of destroying the associated channel, because the action that
e316aad5
DG
2220 * causes the count to become 0 also causes a stream to be added. The
2221 * channel deletion will thus be triggered by the following removal of this
2222 * stream.
2223 */
ffe60014 2224 if (uatomic_read(&stream->chan->nb_init_stream_left) > 0) {
f2ad556d
MD
2225 /* Increment refcount before decrementing nb_init_stream_left */
2226 cmm_smp_wmb();
ffe60014 2227 uatomic_dec(&stream->chan->nb_init_stream_left);
e316aad5
DG
2228 }
2229
d88aee68 2230 lttng_ht_add_unique_u64(ht, &stream->node);
ca22feea 2231
28ab034a 2232 lttng_ht_add_u64(the_consumer_data.stream_per_chan_id_ht, &stream->node_channel_id);
d8ef542d 2233
ca22feea
DG
2234 /*
2235 * Add stream to the stream_list_ht of the consumer data. No need to steal
2236 * the key since the HT does not use it and we allow to add redundant keys
2237 * into this table.
2238 */
28ab034a 2239 lttng_ht_add_u64(the_consumer_data.stream_list_ht, &stream->node_session_id);
ca22feea 2240
fb3a43a9 2241 rcu_read_unlock();
e316aad5 2242
2e818a6a 2243 pthread_mutex_unlock(&stream->lock);
a9838785 2244 pthread_mutex_unlock(&stream->chan->lock);
ec6ea7d0 2245 pthread_mutex_unlock(&stream->chan->timer_lock);
fa29bfbf 2246 pthread_mutex_unlock(&the_consumer_data.lock);
fb3a43a9
DG
2247}
2248
8994307f
DG
2249/*
2250 * Delete data stream that are flagged for deletion (endpoint_status).
2251 */
cd9adb8b 2252static void validate_endpoint_status_data_stream()
8994307f
DG
2253{
2254 struct lttng_ht_iter iter;
2255 struct lttng_consumer_stream *stream;
2256
2257 DBG("Consumer delete flagged data stream");
2258
2259 rcu_read_lock();
28ab034a 2260 cds_lfht_for_each_entry (data_ht->ht, &iter.iter, stream, node.node) {
8994307f 2261 /* Validate delete flag of the stream */
79d4ffb7 2262 if (stream->endpoint_status == CONSUMER_ENDPOINT_ACTIVE) {
8994307f
DG
2263 continue;
2264 }
2265 /* Delete it right now */
2266 consumer_del_stream(stream, data_ht);
2267 }
2268 rcu_read_unlock();
2269}
2270
2271/*
2272 * Delete metadata stream that are flagged for deletion (endpoint_status).
2273 */
28ab034a 2274static void validate_endpoint_status_metadata_stream(struct lttng_poll_event *pollset)
8994307f
DG
2275{
2276 struct lttng_ht_iter iter;
2277 struct lttng_consumer_stream *stream;
2278
2279 DBG("Consumer delete flagged metadata stream");
2280
a0377dfe 2281 LTTNG_ASSERT(pollset);
8994307f
DG
2282
2283 rcu_read_lock();
28ab034a 2284 cds_lfht_for_each_entry (metadata_ht->ht, &iter.iter, stream, node.node) {
8994307f 2285 /* Validate delete flag of the stream */
79d4ffb7 2286 if (stream->endpoint_status == CONSUMER_ENDPOINT_ACTIVE) {
8994307f
DG
2287 continue;
2288 }
2289 /*
2290 * Remove from pollset so the metadata thread can continue without
2291 * blocking on a deleted stream.
2292 */
2293 lttng_poll_del(pollset, stream->wait_fd);
2294
2295 /* Delete it right now */
2296 consumer_del_metadata_stream(stream, metadata_ht);
2297 }
2298 rcu_read_unlock();
2299}
2300
fb3a43a9
DG
2301/*
2302 * Thread polls on metadata file descriptor and write them on disk or on the
2303 * network.
2304 */
7d980def 2305void *consumer_thread_metadata_poll(void *data)
fb3a43a9 2306{
1fc79fb4 2307 int ret, i, pollfd, err = -1;
fb3a43a9 2308 uint32_t revents, nb_fd;
cd9adb8b 2309 struct lttng_consumer_stream *stream = nullptr;
fb3a43a9 2310 struct lttng_ht_iter iter;
d88aee68 2311 struct lttng_ht_node_u64 *node;
fb3a43a9 2312 struct lttng_poll_event events;
97535efa 2313 struct lttng_consumer_local_data *ctx = (lttng_consumer_local_data *) data;
fb3a43a9
DG
2314 ssize_t len;
2315
2316 rcu_register_thread();
2317
1fc79fb4
MD
2318 health_register(health_consumerd, HEALTH_CONSUMERD_TYPE_METADATA);
2319
2d57de81
MD
2320 if (testpoint(consumerd_thread_metadata)) {
2321 goto error_testpoint;
2322 }
2323
9ce5646a
MD
2324 health_code_update();
2325
fb3a43a9
DG
2326 DBG("Thread metadata poll started");
2327
fb3a43a9
DG
2328 /* Size is set to 1 for the consumer_metadata pipe */
2329 ret = lttng_poll_create(&events, 2, LTTNG_CLOEXEC);
2330 if (ret < 0) {
2331 ERR("Poll set creation failed");
d8ef542d 2332 goto end_poll;
fb3a43a9
DG
2333 }
2334
28ab034a 2335 ret = lttng_poll_add(&events, lttng_pipe_get_readfd(ctx->consumer_metadata_pipe), LPOLLIN);
fb3a43a9
DG
2336 if (ret < 0) {
2337 goto end;
2338 }
2339
2340 /* Main loop */
2341 DBG("Metadata main loop started");
2342
cd9adb8b 2343 while (true) {
28ab034a 2344 restart:
7fa2082e 2345 health_code_update();
9ce5646a 2346 health_poll_entry();
7fa2082e 2347 DBG("Metadata poll wait");
fb3a43a9 2348 ret = lttng_poll_wait(&events, -1);
28ab034a 2349 DBG("Metadata poll return from wait with %d fd(s)", LTTNG_POLL_GETNB(&events));
9ce5646a 2350 health_poll_exit();
40063ead 2351 DBG("Metadata event caught in thread");
fb3a43a9
DG
2352 if (ret < 0) {
2353 if (errno == EINTR) {
40063ead 2354 ERR("Poll EINTR caught");
fb3a43a9
DG
2355 goto restart;
2356 }
d9607cd7 2357 if (LTTNG_POLL_GETNB(&events) == 0) {
28ab034a 2358 err = 0; /* All is OK */
d9607cd7
MD
2359 }
2360 goto end;
fb3a43a9
DG
2361 }
2362
0d9c5d77
DG
2363 nb_fd = ret;
2364
e316aad5 2365 /* From here, the event is a metadata wait fd */
fb3a43a9 2366 for (i = 0; i < nb_fd; i++) {
9ce5646a
MD
2367 health_code_update();
2368
fb3a43a9
DG
2369 revents = LTTNG_POLL_GETEV(&events, i);
2370 pollfd = LTTNG_POLL_GETFD(&events, i);
2371
13886d2d 2372 if (pollfd == lttng_pipe_get_readfd(ctx->consumer_metadata_pipe)) {
03e43155 2373 if (revents & LPOLLIN) {
13886d2d
DG
2374 ssize_t pipe_len;
2375
2376 pipe_len = lttng_pipe_read(ctx->consumer_metadata_pipe,
28ab034a
JG
2377 &stream,
2378 sizeof(stream));
6cd525e8 2379 if (pipe_len < sizeof(stream)) {
03e43155
MD
2380 if (pipe_len < 0) {
2381 PERROR("read metadata stream");
2382 }
fb3a43a9 2383 /*
28ab034a
JG
2384 * Remove the pipe from the poll set and continue
2385 * the loop since their might be data to consume.
fb3a43a9 2386 */
28ab034a
JG
2387 lttng_poll_del(
2388 &events,
2389 lttng_pipe_get_readfd(
2390 ctx->consumer_metadata_pipe));
03e43155 2391 lttng_pipe_read_close(ctx->consumer_metadata_pipe);
fb3a43a9
DG
2392 continue;
2393 }
2394
8994307f 2395 /* A NULL stream means that the state has changed. */
cd9adb8b 2396 if (stream == nullptr) {
8994307f
DG
2397 /* Check for deleted streams. */
2398 validate_endpoint_status_metadata_stream(&events);
3714380f 2399 goto restart;
8994307f
DG
2400 }
2401
fb3a43a9 2402 DBG("Adding metadata stream %d to poll set",
28ab034a 2403 stream->wait_fd);
fb3a43a9 2404
fb3a43a9 2405 /* Add metadata stream to the global poll events list */
28ab034a
JG
2406 lttng_poll_add(
2407 &events, stream->wait_fd, LPOLLIN | LPOLLPRI);
2408 } else if (revents & (LPOLLERR | LPOLLHUP)) {
03e43155
MD
2409 DBG("Metadata thread pipe hung up");
2410 /*
2411 * Remove the pipe from the poll set and continue the loop
2412 * since their might be data to consume.
2413 */
28ab034a
JG
2414 lttng_poll_del(
2415 &events,
2416 lttng_pipe_get_readfd(ctx->consumer_metadata_pipe));
03e43155
MD
2417 lttng_pipe_read_close(ctx->consumer_metadata_pipe);
2418 continue;
2419 } else {
28ab034a
JG
2420 ERR("Unexpected poll events %u for sock %d",
2421 revents,
2422 pollfd);
03e43155 2423 goto end;
fb3a43a9
DG
2424 }
2425
e316aad5 2426 /* Handle other stream */
fb3a43a9
DG
2427 continue;
2428 }
2429
d09e1200 2430 rcu_read_lock();
d88aee68
DG
2431 {
2432 uint64_t tmp_id = (uint64_t) pollfd;
2433
2434 lttng_ht_lookup(metadata_ht, &tmp_id, &iter);
2435 }
2436 node = lttng_ht_iter_get_node_u64(&iter);
a0377dfe 2437 LTTNG_ASSERT(node);
fb3a43a9 2438
28ab034a 2439 stream = caa_container_of(node, struct lttng_consumer_stream, node);
fb3a43a9 2440
03e43155
MD
2441 if (revents & (LPOLLIN | LPOLLPRI)) {
2442 /* Get the data out of the metadata file descriptor */
2443 DBG("Metadata available on fd %d", pollfd);
a0377dfe 2444 LTTNG_ASSERT(stream->wait_fd == pollfd);
03e43155
MD
2445
2446 do {
2447 health_code_update();
2448
6f9449c2 2449 len = ctx->on_buffer_ready(stream, ctx, false);
03e43155
MD
2450 /*
2451 * We don't check the return value here since if we get
83f4233d 2452 * a negative len, it means an error occurred thus we
03e43155
MD
2453 * simply remove it from the poll set and free the
2454 * stream.
2455 */
2456 } while (len > 0);
2457
2458 /* It's ok to have an unavailable sub-buffer */
2459 if (len < 0 && len != -EAGAIN && len != -ENODATA) {
2460 /* Clean up stream from consumer and free it. */
2461 lttng_poll_del(&events, stream->wait_fd);
2462 consumer_del_metadata_stream(stream, metadata_ht);
2463 }
2464 } else if (revents & (LPOLLERR | LPOLLHUP)) {
e316aad5 2465 DBG("Metadata fd %d is hup|err.", pollfd);
fa29bfbf 2466 if (!stream->hangup_flush_done &&
28ab034a
JG
2467 (the_consumer_data.type == LTTNG_CONSUMER32_UST ||
2468 the_consumer_data.type == LTTNG_CONSUMER64_UST)) {
fb3a43a9
DG
2469 DBG("Attempting to flush and consume the UST buffers");
2470 lttng_ustconsumer_on_stream_hangup(stream);
2471
2472 /* We just flushed the stream now read it. */
4bb94b75 2473 do {
9ce5646a
MD
2474 health_code_update();
2475
6f9449c2 2476 len = ctx->on_buffer_ready(stream, ctx, false);
4bb94b75 2477 /*
28ab034a
JG
2478 * We don't check the return value here since if we
2479 * get a negative len, it means an error occurred
2480 * thus we simply remove it from the poll set and
2481 * free the stream.
4bb94b75
DG
2482 */
2483 } while (len > 0);
fb3a43a9
DG
2484 }
2485
fb3a43a9 2486 lttng_poll_del(&events, stream->wait_fd);
e316aad5
DG
2487 /*
2488 * This call update the channel states, closes file descriptors
2489 * and securely free the stream.
2490 */
2491 consumer_del_metadata_stream(stream, metadata_ht);
03e43155
MD
2492 } else {
2493 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
6f2f1a70 2494 rcu_read_unlock();
03e43155 2495 goto end;
fb3a43a9 2496 }
e316aad5 2497 /* Release RCU lock for the stream looked up */
d09e1200 2498 rcu_read_unlock();
fb3a43a9
DG
2499 }
2500 }
2501
1fc79fb4
MD
2502 /* All is OK */
2503 err = 0;
fb3a43a9
DG
2504end:
2505 DBG("Metadata poll thread exiting");
fb3a43a9 2506
d8ef542d
MD
2507 lttng_poll_clean(&events);
2508end_poll:
2d57de81 2509error_testpoint:
1fc79fb4
MD
2510 if (err) {
2511 health_error();
2512 ERR("Health error occurred in %s", __func__);
2513 }
2514 health_unregister(health_consumerd);
fb3a43a9 2515 rcu_unregister_thread();
cd9adb8b 2516 return nullptr;
fb3a43a9
DG
2517}
2518
3bd1e081 2519/*
e4421fec 2520 * This thread polls the fds in the set to consume the data and write
3bd1e081
MD
2521 * it to tracefile if necessary.
2522 */
7d980def 2523void *consumer_thread_data_poll(void *data)
3bd1e081 2524{
1fc79fb4 2525 int num_rdy, num_hup, high_prio, ret, i, err = -1;
cd9adb8b 2526 struct pollfd *pollfd = nullptr;
3bd1e081 2527 /* local view of the streams */
cd9adb8b 2528 struct lttng_consumer_stream **local_stream = nullptr, *new_stream = nullptr;
3bd1e081 2529 /* local view of consumer_data.fds_count */
8bdcc002
JG
2530 int nb_fd = 0;
2531 /* 2 for the consumer_data_pipe and wake up pipe */
2532 const int nb_pipes_fd = 2;
9a2fcf78
JD
2533 /* Number of FDs with CONSUMER_ENDPOINT_INACTIVE but still open. */
2534 int nb_inactive_fd = 0;
97535efa 2535 struct lttng_consumer_local_data *ctx = (lttng_consumer_local_data *) data;
00e2e675 2536 ssize_t len;
3bd1e081 2537
e7b994a3
DG
2538 rcu_register_thread();
2539
1fc79fb4
MD
2540 health_register(health_consumerd, HEALTH_CONSUMERD_TYPE_DATA);
2541
2d57de81
MD
2542 if (testpoint(consumerd_thread_data)) {
2543 goto error_testpoint;
2544 }
2545
9ce5646a
MD
2546 health_code_update();
2547
64803277 2548 local_stream = zmalloc<lttng_consumer_stream *>();
cd9adb8b 2549 if (local_stream == nullptr) {
4df6c8cb
MD
2550 PERROR("local_stream malloc");
2551 goto end;
2552 }
3bd1e081 2553
cd9adb8b 2554 while (true) {
9ce5646a
MD
2555 health_code_update();
2556
3bd1e081
MD
2557 high_prio = 0;
2558 num_hup = 0;
2559
2560 /*
e4421fec 2561 * the fds set has been updated, we need to update our
3bd1e081
MD
2562 * local array as well
2563 */
fa29bfbf
SM
2564 pthread_mutex_lock(&the_consumer_data.lock);
2565 if (the_consumer_data.need_update) {
0e428499 2566 free(pollfd);
cd9adb8b 2567 pollfd = nullptr;
0e428499
DG
2568
2569 free(local_stream);
cd9adb8b 2570 local_stream = nullptr;
3bd1e081 2571
8bdcc002 2572 /* Allocate for all fds */
28ab034a
JG
2573 pollfd =
2574 calloc<struct pollfd>(the_consumer_data.stream_count + nb_pipes_fd);
cd9adb8b 2575 if (pollfd == nullptr) {
7a57cf92 2576 PERROR("pollfd malloc");
fa29bfbf 2577 pthread_mutex_unlock(&the_consumer_data.lock);
3bd1e081
MD
2578 goto end;
2579 }
2580
28ab034a
JG
2581 local_stream = calloc<lttng_consumer_stream *>(
2582 the_consumer_data.stream_count + nb_pipes_fd);
cd9adb8b 2583 if (local_stream == nullptr) {
7a57cf92 2584 PERROR("local_stream malloc");
fa29bfbf 2585 pthread_mutex_unlock(&the_consumer_data.lock);
3bd1e081
MD
2586 goto end;
2587 }
28ab034a
JG
2588 ret = update_poll_array(
2589 ctx, &pollfd, local_stream, data_ht, &nb_inactive_fd);
3bd1e081
MD
2590 if (ret < 0) {
2591 ERR("Error in allocating pollfd or local_outfds");
f73fabfd 2592 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_POLL_ERROR);
fa29bfbf 2593 pthread_mutex_unlock(&the_consumer_data.lock);
3bd1e081
MD
2594 goto end;
2595 }
2596 nb_fd = ret;
fa29bfbf 2597 the_consumer_data.need_update = 0;
3bd1e081 2598 }
fa29bfbf 2599 pthread_mutex_unlock(&the_consumer_data.lock);
3bd1e081 2600
4078b776 2601 /* No FDs and consumer_quit, consumer_cleanup the thread */
28ab034a
JG
2602 if (nb_fd == 0 && nb_inactive_fd == 0 && CMM_LOAD_SHARED(consumer_quit) == 1) {
2603 err = 0; /* All is OK */
4078b776
MD
2604 goto end;
2605 }
3bd1e081 2606 /* poll on the array of fds */
88f2b785 2607 restart:
261de637 2608 DBG("polling on %d fd", nb_fd + nb_pipes_fd);
cf0bcb51
JG
2609 if (testpoint(consumerd_thread_data_poll)) {
2610 goto end;
2611 }
9ce5646a 2612 health_poll_entry();
261de637 2613 num_rdy = poll(pollfd, nb_fd + nb_pipes_fd, -1);
9ce5646a 2614 health_poll_exit();
3bd1e081
MD
2615 DBG("poll num_rdy : %d", num_rdy);
2616 if (num_rdy == -1) {
88f2b785
MD
2617 /*
2618 * Restart interrupted system call.
2619 */
2620 if (errno == EINTR) {
2621 goto restart;
2622 }
7a57cf92 2623 PERROR("Poll error");
f73fabfd 2624 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_POLL_ERROR);
3bd1e081
MD
2625 goto end;
2626 } else if (num_rdy == 0) {
2627 DBG("Polling thread timed out");
2628 goto end;
2629 }
2630
80957876
JG
2631 if (caa_unlikely(data_consumption_paused)) {
2632 DBG("Data consumption paused, sleeping...");
2633 sleep(1);
2634 goto restart;
2635 }
2636
3bd1e081 2637 /*
50f8ae69 2638 * If the consumer_data_pipe triggered poll go directly to the
00e2e675
DG
2639 * beginning of the loop to update the array. We want to prioritize
2640 * array update over low-priority reads.
3bd1e081 2641 */
509bb1cf 2642 if (pollfd[nb_fd].revents & (POLLIN | POLLPRI)) {
ab30f567 2643 ssize_t pipe_readlen;
04fdd819 2644
50f8ae69 2645 DBG("consumer_data_pipe wake up");
28ab034a
JG
2646 pipe_readlen = lttng_pipe_read(
2647 ctx->consumer_data_pipe, &new_stream, sizeof(new_stream));
6cd525e8
MD
2648 if (pipe_readlen < sizeof(new_stream)) {
2649 PERROR("Consumer data pipe");
23f5f35d
DG
2650 /* Continue so we can at least handle the current stream(s). */
2651 continue;
2652 }
c869f647
DG
2653
2654 /*
2655 * If the stream is NULL, just ignore it. It's also possible that
2656 * the sessiond poll thread changed the consumer_quit state and is
2657 * waking us up to test it.
2658 */
cd9adb8b 2659 if (new_stream == nullptr) {
8994307f 2660 validate_endpoint_status_data_stream();
c869f647
DG
2661 continue;
2662 }
2663
c869f647 2664 /* Continue to update the local streams and handle prio ones */
3bd1e081
MD
2665 continue;
2666 }
2667
02b3d176
DG
2668 /* Handle wakeup pipe. */
2669 if (pollfd[nb_fd + 1].revents & (POLLIN | POLLPRI)) {
2670 char dummy;
2671 ssize_t pipe_readlen;
2672
28ab034a
JG
2673 pipe_readlen =
2674 lttng_pipe_read(ctx->consumer_wakeup_pipe, &dummy, sizeof(dummy));
02b3d176
DG
2675 if (pipe_readlen < 0) {
2676 PERROR("Consumer data wakeup pipe");
2677 }
2678 /* We've been awakened to handle stream(s). */
2679 ctx->has_wakeup = 0;
2680 }
2681
3bd1e081
MD
2682 /* Take care of high priority channels first. */
2683 for (i = 0; i < nb_fd; i++) {
9ce5646a
MD
2684 health_code_update();
2685
cd9adb8b 2686 if (local_stream[i] == nullptr) {
9617607b
DG
2687 continue;
2688 }
fb3a43a9 2689 if (pollfd[i].revents & POLLPRI) {
d41f73b7
MD
2690 DBG("Urgent read on fd %d", pollfd[i].fd);
2691 high_prio = 1;
6f9449c2 2692 len = ctx->on_buffer_ready(local_stream[i], ctx, false);
d41f73b7 2693 /* it's ok to have an unavailable sub-buffer */
b64403e3 2694 if (len < 0 && len != -EAGAIN && len != -ENODATA) {
ab1027f4
DG
2695 /* Clean the stream and free it. */
2696 consumer_del_stream(local_stream[i], data_ht);
cd9adb8b 2697 local_stream[i] = nullptr;
4078b776 2698 } else if (len > 0) {
28ab034a
JG
2699 local_stream[i]->has_data_left_to_be_read_before_teardown =
2700 1;
d41f73b7 2701 }
3bd1e081
MD
2702 }
2703 }
2704
4078b776
MD
2705 /*
2706 * If we read high prio channel in this loop, try again
2707 * for more high prio data.
2708 */
2709 if (high_prio) {
3bd1e081
MD
2710 continue;
2711 }
2712
2713 /* Take care of low priority channels. */
4078b776 2714 for (i = 0; i < nb_fd; i++) {
9ce5646a
MD
2715 health_code_update();
2716
cd9adb8b 2717 if (local_stream[i] == nullptr) {
9617607b
DG
2718 continue;
2719 }
28ab034a
JG
2720 if ((pollfd[i].revents & POLLIN) || local_stream[i]->hangup_flush_done ||
2721 local_stream[i]->has_data) {
4078b776 2722 DBG("Normal read on fd %d", pollfd[i].fd);
6f9449c2 2723 len = ctx->on_buffer_ready(local_stream[i], ctx, false);
4078b776 2724 /* it's ok to have an unavailable sub-buffer */
b64403e3 2725 if (len < 0 && len != -EAGAIN && len != -ENODATA) {
ab1027f4
DG
2726 /* Clean the stream and free it. */
2727 consumer_del_stream(local_stream[i], data_ht);
cd9adb8b 2728 local_stream[i] = nullptr;
4078b776 2729 } else if (len > 0) {
28ab034a
JG
2730 local_stream[i]->has_data_left_to_be_read_before_teardown =
2731 1;
4078b776
MD
2732 }
2733 }
2734 }
2735
2736 /* Handle hangup and errors */
2737 for (i = 0; i < nb_fd; i++) {
9ce5646a
MD
2738 health_code_update();
2739
cd9adb8b 2740 if (local_stream[i] == nullptr) {
9617607b
DG
2741 continue;
2742 }
28ab034a
JG
2743 if (!local_stream[i]->hangup_flush_done &&
2744 (pollfd[i].revents & (POLLHUP | POLLERR | POLLNVAL)) &&
2745 (the_consumer_data.type == LTTNG_CONSUMER32_UST ||
2746 the_consumer_data.type == LTTNG_CONSUMER64_UST)) {
4078b776 2747 DBG("fd %d is hup|err|nval. Attempting flush and read.",
28ab034a 2748 pollfd[i].fd);
4078b776
MD
2749 lttng_ustconsumer_on_stream_hangup(local_stream[i]);
2750 /* Attempt read again, for the data we just flushed. */
c715ddc9 2751 local_stream[i]->has_data_left_to_be_read_before_teardown = 1;
4078b776
MD
2752 }
2753 /*
c715ddc9
JG
2754 * When a stream's pipe dies (hup/err/nval), an "inactive producer" flush is
2755 * performed. This type of flush ensures that a new packet is produced no
2756 * matter the consumed/produced positions are.
2757 *
2758 * This, in turn, causes the next pass to see that data available for the
2759 * stream. When we come back here, we can be assured that all available
2760 * data has been consumed and we can finally destroy the stream.
2761 *
4078b776
MD
2762 * If the poll flag is HUP/ERR/NVAL and we have
2763 * read no data in this pass, we can remove the
2764 * stream from its hash table.
2765 */
2766 if ((pollfd[i].revents & POLLHUP)) {
2767 DBG("Polling fd %d tells it has hung up.", pollfd[i].fd);
c715ddc9 2768 if (!local_stream[i]->has_data_left_to_be_read_before_teardown) {
43c34bc3 2769 consumer_del_stream(local_stream[i], data_ht);
cd9adb8b 2770 local_stream[i] = nullptr;
4078b776
MD
2771 num_hup++;
2772 }
2773 } else if (pollfd[i].revents & POLLERR) {
2774 ERR("Error returned in polling fd %d.", pollfd[i].fd);
c715ddc9 2775 if (!local_stream[i]->has_data_left_to_be_read_before_teardown) {
43c34bc3 2776 consumer_del_stream(local_stream[i], data_ht);
cd9adb8b 2777 local_stream[i] = nullptr;
4078b776
MD
2778 num_hup++;
2779 }
2780 } else if (pollfd[i].revents & POLLNVAL) {
2781 ERR("Polling fd %d tells fd is not open.", pollfd[i].fd);
c715ddc9 2782 if (!local_stream[i]->has_data_left_to_be_read_before_teardown) {
43c34bc3 2783 consumer_del_stream(local_stream[i], data_ht);
cd9adb8b 2784 local_stream[i] = nullptr;
4078b776 2785 num_hup++;
3bd1e081
MD
2786 }
2787 }
cd9adb8b 2788 if (local_stream[i] != nullptr) {
c715ddc9 2789 local_stream[i]->has_data_left_to_be_read_before_teardown = 0;
9617607b 2790 }
3bd1e081
MD
2791 }
2792 }
1fc79fb4
MD
2793 /* All is OK */
2794 err = 0;
3bd1e081
MD
2795end:
2796 DBG("polling thread exiting");
0e428499
DG
2797 free(pollfd);
2798 free(local_stream);
fb3a43a9
DG
2799
2800 /*
2801 * Close the write side of the pipe so epoll_wait() in
7d980def
DG
2802 * consumer_thread_metadata_poll can catch it. The thread is monitoring the
2803 * read side of the pipe. If we close them both, epoll_wait strangely does
2804 * not return and could create a endless wait period if the pipe is the
2805 * only tracked fd in the poll set. The thread will take care of closing
2806 * the read side.
fb3a43a9 2807 */
13886d2d 2808 (void) lttng_pipe_write_close(ctx->consumer_metadata_pipe);
fb3a43a9 2809
2d57de81 2810error_testpoint:
1fc79fb4
MD
2811 if (err) {
2812 health_error();
2813 ERR("Health error occurred in %s", __func__);
2814 }
2815 health_unregister(health_consumerd);
2816
e7b994a3 2817 rcu_unregister_thread();
cd9adb8b 2818 return nullptr;
3bd1e081
MD
2819}
2820
d8ef542d
MD
2821/*
2822 * Close wake-up end of each stream belonging to the channel. This will
2823 * allow the poll() on the stream read-side to detect when the
2824 * write-side (application) finally closes them.
2825 */
28ab034a 2826static void consumer_close_channel_streams(struct lttng_consumer_channel *channel)
d8ef542d
MD
2827{
2828 struct lttng_ht *ht;
2829 struct lttng_consumer_stream *stream;
2830 struct lttng_ht_iter iter;
2831
fa29bfbf 2832 ht = the_consumer_data.stream_per_chan_id_ht;
d8ef542d
MD
2833
2834 rcu_read_lock();
2835 cds_lfht_for_each_entry_duplicate(ht->ht,
28ab034a
JG
2836 ht->hash_fct(&channel->key, lttng_ht_seed),
2837 ht->match_fct,
2838 &channel->key,
2839 &iter.iter,
2840 stream,
2841 node_channel_id.node)
2842 {
f2ad556d
MD
2843 /*
2844 * Protect against teardown with mutex.
2845 */
2846 pthread_mutex_lock(&stream->lock);
2847 if (cds_lfht_is_node_deleted(&stream->node.node)) {
2848 goto next;
2849 }
fa29bfbf 2850 switch (the_consumer_data.type) {
d8ef542d
MD
2851 case LTTNG_CONSUMER_KERNEL:
2852 break;
2853 case LTTNG_CONSUMER32_UST:
2854 case LTTNG_CONSUMER64_UST:
b4a650f3
DG
2855 if (stream->metadata_flag) {
2856 /* Safe and protected by the stream lock. */
2857 lttng_ustconsumer_close_metadata(stream->chan);
2858 } else {
2859 /*
2860 * Note: a mutex is taken internally within
2861 * liblttng-ust-ctl to protect timer wakeup_fd
2862 * use from concurrent close.
2863 */
2864 lttng_ustconsumer_close_stream_wakeup(stream);
2865 }
d8ef542d
MD
2866 break;
2867 default:
2868 ERR("Unknown consumer_data type");
a0377dfe 2869 abort();
d8ef542d 2870 }
f2ad556d
MD
2871 next:
2872 pthread_mutex_unlock(&stream->lock);
d8ef542d
MD
2873 }
2874 rcu_read_unlock();
2875}
2876
2877static void destroy_channel_ht(struct lttng_ht *ht)
2878{
2879 struct lttng_ht_iter iter;
2880 struct lttng_consumer_channel *channel;
2881 int ret;
2882
cd9adb8b 2883 if (ht == nullptr) {
d8ef542d
MD
2884 return;
2885 }
2886
2887 rcu_read_lock();
28ab034a 2888 cds_lfht_for_each_entry (ht->ht, &iter.iter, channel, wait_fd_node.node) {
d8ef542d 2889 ret = lttng_ht_del(ht, &iter);
a0377dfe 2890 LTTNG_ASSERT(ret != 0);
d8ef542d
MD
2891 }
2892 rcu_read_unlock();
2893
2894 lttng_ht_destroy(ht);
2895}
2896
2897/*
2898 * This thread polls the channel fds to detect when they are being
2899 * closed. It closes all related streams if the channel is detected as
2900 * closed. It is currently only used as a shim layer for UST because the
2901 * consumerd needs to keep the per-stream wakeup end of pipes open for
2902 * periodical flush.
2903 */
2904void *consumer_thread_channel_poll(void *data)
2905{
1fc79fb4 2906 int ret, i, pollfd, err = -1;
d8ef542d 2907 uint32_t revents, nb_fd;
cd9adb8b 2908 struct lttng_consumer_channel *chan = nullptr;
d8ef542d
MD
2909 struct lttng_ht_iter iter;
2910 struct lttng_ht_node_u64 *node;
2911 struct lttng_poll_event events;
97535efa 2912 struct lttng_consumer_local_data *ctx = (lttng_consumer_local_data *) data;
d8ef542d
MD
2913 struct lttng_ht *channel_ht;
2914
2915 rcu_register_thread();
2916
1fc79fb4
MD
2917 health_register(health_consumerd, HEALTH_CONSUMERD_TYPE_CHANNEL);
2918
2d57de81
MD
2919 if (testpoint(consumerd_thread_channel)) {
2920 goto error_testpoint;
2921 }
2922
9ce5646a
MD
2923 health_code_update();
2924
d8ef542d
MD
2925 channel_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
2926 if (!channel_ht) {
2927 /* ENOMEM at this point. Better to bail out. */
2928 goto end_ht;
2929 }
2930
2931 DBG("Thread channel poll started");
2932
2933 /* Size is set to 1 for the consumer_channel pipe */
2934 ret = lttng_poll_create(&events, 2, LTTNG_CLOEXEC);
2935 if (ret < 0) {
2936 ERR("Poll set creation failed");
2937 goto end_poll;
2938 }
2939
2940 ret = lttng_poll_add(&events, ctx->consumer_channel_pipe[0], LPOLLIN);
2941 if (ret < 0) {
2942 goto end;
2943 }
2944
2945 /* Main loop */
2946 DBG("Channel main loop started");
2947
cd9adb8b 2948 while (true) {
28ab034a 2949 restart:
7fa2082e
MD
2950 health_code_update();
2951 DBG("Channel poll wait");
9ce5646a 2952 health_poll_entry();
d8ef542d 2953 ret = lttng_poll_wait(&events, -1);
28ab034a 2954 DBG("Channel poll return from wait with %d fd(s)", LTTNG_POLL_GETNB(&events));
9ce5646a 2955 health_poll_exit();
40063ead 2956 DBG("Channel event caught in thread");
d8ef542d
MD
2957 if (ret < 0) {
2958 if (errno == EINTR) {
40063ead 2959 ERR("Poll EINTR caught");
d8ef542d
MD
2960 goto restart;
2961 }
d9607cd7 2962 if (LTTNG_POLL_GETNB(&events) == 0) {
28ab034a 2963 err = 0; /* All is OK */
d9607cd7 2964 }
d8ef542d
MD
2965 goto end;
2966 }
2967
2968 nb_fd = ret;
2969
2970 /* From here, the event is a channel wait fd */
2971 for (i = 0; i < nb_fd; i++) {
9ce5646a
MD
2972 health_code_update();
2973
d8ef542d
MD
2974 revents = LTTNG_POLL_GETEV(&events, i);
2975 pollfd = LTTNG_POLL_GETFD(&events, i);
2976
d8ef542d 2977 if (pollfd == ctx->consumer_channel_pipe[0]) {
03e43155 2978 if (revents & LPOLLIN) {
d8ef542d 2979 enum consumer_channel_action action;
a0cbdd2e 2980 uint64_t key;
d8ef542d 2981
a0cbdd2e 2982 ret = read_channel_pipe(ctx, &chan, &key, &action);
d8ef542d 2983 if (ret <= 0) {
03e43155
MD
2984 if (ret < 0) {
2985 ERR("Error reading channel pipe");
2986 }
28ab034a
JG
2987 lttng_poll_del(&events,
2988 ctx->consumer_channel_pipe[0]);
d8ef542d
MD
2989 continue;
2990 }
2991
2992 switch (action) {
2993 case CONSUMER_CHANNEL_ADD:
28ab034a 2994 DBG("Adding channel %d to poll set", chan->wait_fd);
d8ef542d
MD
2995
2996 lttng_ht_node_init_u64(&chan->wait_fd_node,
28ab034a 2997 chan->wait_fd);
c7260a81 2998 rcu_read_lock();
d8ef542d 2999 lttng_ht_add_unique_u64(channel_ht,
28ab034a 3000 &chan->wait_fd_node);
c7260a81 3001 rcu_read_unlock();
d8ef542d 3002 /* Add channel to the global poll events list */
28ab034a
JG
3003 // FIXME: Empty flag on a pipe pollset, this might
3004 // hang on FreeBSD.
1524f98c 3005 lttng_poll_add(&events, chan->wait_fd, 0);
d8ef542d 3006 break;
a0cbdd2e
MD
3007 case CONSUMER_CHANNEL_DEL:
3008 {
b4a650f3 3009 /*
28ab034a
JG
3010 * This command should never be called if the
3011 * channel has streams monitored by either the data
3012 * or metadata thread. The consumer only notify this
3013 * thread with a channel del. command if it receives
3014 * a destroy channel command from the session daemon
3015 * that send it if a command prior to the
3016 * GET_CHANNEL failed.
b4a650f3
DG
3017 */
3018
c7260a81 3019 rcu_read_lock();
a0cbdd2e
MD
3020 chan = consumer_find_channel(key);
3021 if (!chan) {
c7260a81 3022 rcu_read_unlock();
28ab034a
JG
3023 ERR("UST consumer get channel key %" PRIu64
3024 " not found for del channel",
3025 key);
a0cbdd2e
MD
3026 break;
3027 }
3028 lttng_poll_del(&events, chan->wait_fd);
f623cc0b 3029 iter.iter.node = &chan->wait_fd_node.node;
a0cbdd2e 3030 ret = lttng_ht_del(channel_ht, &iter);
a0377dfe 3031 LTTNG_ASSERT(ret == 0);
a0cbdd2e 3032
fa29bfbf 3033 switch (the_consumer_data.type) {
f2a444f1
DG
3034 case LTTNG_CONSUMER_KERNEL:
3035 break;
3036 case LTTNG_CONSUMER32_UST:
3037 case LTTNG_CONSUMER64_UST:
212d67a2 3038 health_code_update();
28ab034a
JG
3039 /* Destroy streams that might have been left
3040 * in the stream list. */
212d67a2 3041 clean_channel_stream_list(chan);
f2a444f1
DG
3042 break;
3043 default:
3044 ERR("Unknown consumer_data type");
a0377dfe 3045 abort();
f2a444f1
DG
3046 }
3047
a0cbdd2e 3048 /*
28ab034a
JG
3049 * Release our own refcount. Force channel deletion
3050 * even if streams were not initialized.
a0cbdd2e
MD
3051 */
3052 if (!uatomic_sub_return(&chan->refcount, 1)) {
3053 consumer_del_channel(chan);
3054 }
c7260a81 3055 rcu_read_unlock();
a0cbdd2e
MD
3056 goto restart;
3057 }
d8ef542d
MD
3058 case CONSUMER_CHANNEL_QUIT:
3059 /*
28ab034a
JG
3060 * Remove the pipe from the poll set and continue
3061 * the loop since their might be data to consume.
d8ef542d 3062 */
28ab034a
JG
3063 lttng_poll_del(&events,
3064 ctx->consumer_channel_pipe[0]);
d8ef542d
MD
3065 continue;
3066 default:
3067 ERR("Unknown action");
3068 break;
3069 }
03e43155
MD
3070 } else if (revents & (LPOLLERR | LPOLLHUP)) {
3071 DBG("Channel thread pipe hung up");
3072 /*
3073 * Remove the pipe from the poll set and continue the loop
3074 * since their might be data to consume.
3075 */
3076 lttng_poll_del(&events, ctx->consumer_channel_pipe[0]);
3077 continue;
3078 } else {
28ab034a
JG
3079 ERR("Unexpected poll events %u for sock %d",
3080 revents,
3081 pollfd);
03e43155 3082 goto end;
d8ef542d
MD
3083 }
3084
3085 /* Handle other stream */
3086 continue;
3087 }
3088
3089 rcu_read_lock();
3090 {
3091 uint64_t tmp_id = (uint64_t) pollfd;
3092
3093 lttng_ht_lookup(channel_ht, &tmp_id, &iter);
3094 }
3095 node = lttng_ht_iter_get_node_u64(&iter);
a0377dfe 3096 LTTNG_ASSERT(node);
d8ef542d 3097
28ab034a 3098 chan = caa_container_of(node, struct lttng_consumer_channel, wait_fd_node);
d8ef542d
MD
3099
3100 /* Check for error event */
3101 if (revents & (LPOLLERR | LPOLLHUP)) {
3102 DBG("Channel fd %d is hup|err.", pollfd);
3103
3104 lttng_poll_del(&events, chan->wait_fd);
3105 ret = lttng_ht_del(channel_ht, &iter);
a0377dfe 3106 LTTNG_ASSERT(ret == 0);
b4a650f3
DG
3107
3108 /*
3109 * This will close the wait fd for each stream associated to
3110 * this channel AND monitored by the data/metadata thread thus
3111 * will be clean by the right thread.
3112 */
d8ef542d 3113 consumer_close_channel_streams(chan);
f2ad556d
MD
3114
3115 /* Release our own refcount */
28ab034a
JG
3116 if (!uatomic_sub_return(&chan->refcount, 1) &&
3117 !uatomic_read(&chan->nb_init_stream_left)) {
f2ad556d
MD
3118 consumer_del_channel(chan);
3119 }
03e43155
MD
3120 } else {
3121 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
3122 rcu_read_unlock();
3123 goto end;
d8ef542d
MD
3124 }
3125
3126 /* Release RCU lock for the channel looked up */
3127 rcu_read_unlock();
3128 }
3129 }
3130
1fc79fb4
MD
3131 /* All is OK */
3132 err = 0;
d8ef542d
MD
3133end:
3134 lttng_poll_clean(&events);
3135end_poll:
3136 destroy_channel_ht(channel_ht);
3137end_ht:
2d57de81 3138error_testpoint:
d8ef542d 3139 DBG("Channel poll thread exiting");
1fc79fb4
MD
3140 if (err) {
3141 health_error();
3142 ERR("Health error occurred in %s", __func__);
3143 }
3144 health_unregister(health_consumerd);
d8ef542d 3145 rcu_unregister_thread();
cd9adb8b 3146 return nullptr;
d8ef542d
MD
3147}
3148
331744e3 3149static int set_metadata_socket(struct lttng_consumer_local_data *ctx,
28ab034a
JG
3150 struct pollfd *sockpoll,
3151 int client_socket)
331744e3
JD
3152{
3153 int ret;
3154
a0377dfe
FD
3155 LTTNG_ASSERT(ctx);
3156 LTTNG_ASSERT(sockpoll);
331744e3 3157
84382d49
MD
3158 ret = lttng_consumer_poll_socket(sockpoll);
3159 if (ret) {
331744e3
JD
3160 goto error;
3161 }
3162 DBG("Metadata connection on client_socket");
3163
3164 /* Blocking call, waiting for transmission */
3165 ctx->consumer_metadata_socket = lttcomm_accept_unix_sock(client_socket);
3166 if (ctx->consumer_metadata_socket < 0) {
3167 WARN("On accept metadata");
3168 ret = -1;
3169 goto error;
3170 }
3171 ret = 0;
3172
3173error:
3174 return ret;
3175}
3176
3bd1e081
MD
3177/*
3178 * This thread listens on the consumerd socket and receives the file
3179 * descriptors from the session daemon.
3180 */
7d980def 3181void *consumer_thread_sessiond_poll(void *data)
3bd1e081 3182{
1fc79fb4 3183 int sock = -1, client_socket, ret, err = -1;
3bd1e081
MD
3184 /*
3185 * structure to poll for incoming data on communication socket avoids
3186 * making blocking sockets.
3187 */
3188 struct pollfd consumer_sockpoll[2];
97535efa 3189 struct lttng_consumer_local_data *ctx = (lttng_consumer_local_data *) data;
3bd1e081 3190
e7b994a3
DG
3191 rcu_register_thread();
3192
1fc79fb4
MD
3193 health_register(health_consumerd, HEALTH_CONSUMERD_TYPE_SESSIOND);
3194
2d57de81
MD
3195 if (testpoint(consumerd_thread_sessiond)) {
3196 goto error_testpoint;
3197 }
3198
9ce5646a
MD
3199 health_code_update();
3200
3bd1e081
MD
3201 DBG("Creating command socket %s", ctx->consumer_command_sock_path);
3202 unlink(ctx->consumer_command_sock_path);
3203 client_socket = lttcomm_create_unix_sock(ctx->consumer_command_sock_path);
3204 if (client_socket < 0) {
3205 ERR("Cannot create command socket");
3206 goto end;
3207 }
3208
3209 ret = lttcomm_listen_unix_sock(client_socket);
3210 if (ret < 0) {
3211 goto end;
3212 }
3213
32258573 3214 DBG("Sending ready command to lttng-sessiond");
f73fabfd 3215 ret = lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_COMMAND_SOCK_READY);
3bd1e081
MD
3216 /* return < 0 on error, but == 0 is not fatal */
3217 if (ret < 0) {
32258573 3218 ERR("Error sending ready command to lttng-sessiond");
3bd1e081
MD
3219 goto end;
3220 }
3221
3bd1e081
MD
3222 /* prepare the FDs to poll : to client socket and the should_quit pipe */
3223 consumer_sockpoll[0].fd = ctx->consumer_should_quit[0];
3224 consumer_sockpoll[0].events = POLLIN | POLLPRI;
3225 consumer_sockpoll[1].fd = client_socket;
3226 consumer_sockpoll[1].events = POLLIN | POLLPRI;
3227
84382d49
MD
3228 ret = lttng_consumer_poll_socket(consumer_sockpoll);
3229 if (ret) {
3230 if (ret > 0) {
3231 /* should exit */
3232 err = 0;
3233 }
3bd1e081
MD
3234 goto end;
3235 }
3236 DBG("Connection on client_socket");
3237
3238 /* Blocking call, waiting for transmission */
3239 sock = lttcomm_accept_unix_sock(client_socket);
534d2592 3240 if (sock < 0) {
3bd1e081
MD
3241 WARN("On accept");
3242 goto end;
3243 }
3bd1e081 3244
331744e3
JD
3245 /*
3246 * Setup metadata socket which is the second socket connection on the
3247 * command unix socket.
3248 */
3249 ret = set_metadata_socket(ctx, consumer_sockpoll, client_socket);
84382d49
MD
3250 if (ret) {
3251 if (ret > 0) {
3252 /* should exit */
3253 err = 0;
3254 }
331744e3
JD
3255 goto end;
3256 }
3257
d96f09c6
DG
3258 /* This socket is not useful anymore. */
3259 ret = close(client_socket);
3260 if (ret < 0) {
3261 PERROR("close client_socket");
3262 }
3263 client_socket = -1;
3264
3bd1e081
MD
3265 /* update the polling structure to poll on the established socket */
3266 consumer_sockpoll[1].fd = sock;
3267 consumer_sockpoll[1].events = POLLIN | POLLPRI;
3268
cd9adb8b 3269 while (true) {
9ce5646a
MD
3270 health_code_update();
3271
3272 health_poll_entry();
3273 ret = lttng_consumer_poll_socket(consumer_sockpoll);
3274 health_poll_exit();
84382d49
MD
3275 if (ret) {
3276 if (ret > 0) {
3277 /* should exit */
3278 err = 0;
3279 }
3bd1e081
MD
3280 goto end;
3281 }
3282 DBG("Incoming command on sock");
3283 ret = lttng_consumer_recv_cmd(ctx, sock, consumer_sockpoll);
4cbc1a04
DG
3284 if (ret <= 0) {
3285 /*
3286 * This could simply be a session daemon quitting. Don't output
3287 * ERR() here.
3288 */
3289 DBG("Communication interrupted on command socket");
41ba6035 3290 err = 0;
3bd1e081
MD
3291 goto end;
3292 }
10211f5c 3293 if (CMM_LOAD_SHARED(consumer_quit)) {
3bd1e081 3294 DBG("consumer_thread_receive_fds received quit from signal");
28ab034a 3295 err = 0; /* All is OK */
3bd1e081
MD
3296 goto end;
3297 }
a1ed855a 3298 DBG("Received command on sock");
3bd1e081 3299 }
1fc79fb4
MD
3300 /* All is OK */
3301 err = 0;
3302
3bd1e081 3303end:
ffe60014 3304 DBG("Consumer thread sessiond poll exiting");
3bd1e081 3305
d88aee68
DG
3306 /*
3307 * Close metadata streams since the producer is the session daemon which
3308 * just died.
3309 *
3310 * NOTE: for now, this only applies to the UST tracer.
3311 */
6d574024 3312 lttng_consumer_close_all_metadata();
d88aee68 3313
3bd1e081
MD
3314 /*
3315 * when all fds have hung up, the polling thread
3316 * can exit cleanly
3317 */
10211f5c 3318 CMM_STORE_SHARED(consumer_quit, 1);
3bd1e081 3319
04fdd819 3320 /*
c869f647 3321 * Notify the data poll thread to poll back again and test the
8994307f 3322 * consumer_quit state that we just set so to quit gracefully.
04fdd819 3323 */
acdb9057 3324 notify_thread_lttng_pipe(ctx->consumer_data_pipe);
c869f647 3325
cd9adb8b 3326 notify_channel_pipe(ctx, nullptr, -1, CONSUMER_CHANNEL_QUIT);
d8ef542d 3327
5c635c72
MD
3328 notify_health_quit_pipe(health_quit_pipe);
3329
d96f09c6
DG
3330 /* Cleaning up possibly open sockets. */
3331 if (sock >= 0) {
3332 ret = close(sock);
3333 if (ret < 0) {
3334 PERROR("close sock sessiond poll");
3335 }
3336 }
3337 if (client_socket >= 0) {
38476d24 3338 ret = close(client_socket);
d96f09c6
DG
3339 if (ret < 0) {
3340 PERROR("close client_socket sessiond poll");
3341 }
3342 }
3343
2d57de81 3344error_testpoint:
1fc79fb4
MD
3345 if (err) {
3346 health_error();
3347 ERR("Health error occurred in %s", __func__);
3348 }
3349 health_unregister(health_consumerd);
3350
e7b994a3 3351 rcu_unregister_thread();
cd9adb8b 3352 return nullptr;
3bd1e081 3353}
d41f73b7 3354
503fefca 3355static int post_consume(struct lttng_consumer_stream *stream,
28ab034a
JG
3356 const struct stream_subbuffer *subbuffer,
3357 struct lttng_consumer_local_data *ctx)
f96af312 3358{
503fefca 3359 size_t i;
f96af312 3360 int ret = 0;
28ab034a
JG
3361 const size_t count =
3362 lttng_dynamic_array_get_count(&stream->read_subbuffer_ops.post_consume_cbs);
f96af312 3363
503fefca
JG
3364 for (i = 0; i < count; i++) {
3365 const post_consume_cb op = *(post_consume_cb *) lttng_dynamic_array_get_element(
28ab034a 3366 &stream->read_subbuffer_ops.post_consume_cbs, i);
503fefca
JG
3367
3368 ret = op(stream, subbuffer, ctx);
3369 if (ret) {
3370 goto end;
f96af312 3371 }
f96af312 3372 }
f96af312
JG
3373end:
3374 return ret;
3375}
3376
4078b776 3377ssize_t lttng_consumer_read_subbuffer(struct lttng_consumer_stream *stream,
28ab034a
JG
3378 struct lttng_consumer_local_data *ctx,
3379 bool locked_by_caller)
d41f73b7 3380{
12bddd1d 3381 ssize_t ret, written_bytes = 0;
23d56598 3382 int rotation_ret;
6f9449c2 3383 struct stream_subbuffer subbuffer = {};
b6797c8e 3384 enum get_next_subbuffer_status get_next_status;
74251bb8 3385
6f9449c2
JG
3386 if (!locked_by_caller) {
3387 stream->read_subbuffer_ops.lock(stream);
947bd097
JR
3388 } else {
3389 stream->read_subbuffer_ops.assert_locked(stream);
6f9449c2
JG
3390 }
3391
3392 if (stream->read_subbuffer_ops.on_wake_up) {
3393 ret = stream->read_subbuffer_ops.on_wake_up(stream);
3394 if (ret) {
3395 goto end;
3396 }
94d49140 3397 }
74251bb8 3398
23d56598
JG
3399 /*
3400 * If the stream was flagged to be ready for rotation before we extract
3401 * the next packet, rotate it now.
3402 */
3403 if (stream->rotate_ready) {
3404 DBG("Rotate stream before consuming data");
f46376a1 3405 ret = lttng_consumer_rotate_stream(stream);
23d56598
JG
3406 if (ret < 0) {
3407 ERR("Stream rotation error before consuming data");
3408 goto end;
3409 }
3410 }
3411
28ab034a 3412 get_next_status = stream->read_subbuffer_ops.get_next_subbuffer(stream, &subbuffer);
b6797c8e
JG
3413 switch (get_next_status) {
3414 case GET_NEXT_SUBBUFFER_STATUS_OK:
3415 break;
3416 case GET_NEXT_SUBBUFFER_STATUS_NO_DATA:
3417 /* Not an error. */
3418 ret = 0;
3419 goto sleep_stream;
3420 case GET_NEXT_SUBBUFFER_STATUS_ERROR:
3421 ret = -1;
6f9449c2 3422 goto end;
b6797c8e
JG
3423 default:
3424 abort();
d41f73b7 3425 }
74251bb8 3426
28ab034a 3427 ret = stream->read_subbuffer_ops.pre_consume_subbuffer(stream, &subbuffer);
6f9449c2
JG
3428 if (ret) {
3429 goto error_put_subbuf;
3430 }
3431
28ab034a 3432 written_bytes = stream->read_subbuffer_ops.consume_subbuffer(ctx, stream, &subbuffer);
514775d9
FD
3433 if (written_bytes <= 0) {
3434 ERR("Error consuming subbuffer: (%zd)", written_bytes);
3435 ret = (int) written_bytes;
3436 goto error_put_subbuf;
6f9449c2
JG
3437 }
3438
3439 ret = stream->read_subbuffer_ops.put_next_subbuffer(stream, &subbuffer);
3440 if (ret) {
23d56598
JG
3441 goto end;
3442 }
3443
503fefca
JG
3444 ret = post_consume(stream, &subbuffer, ctx);
3445 if (ret) {
3446 goto end;
6f9449c2
JG
3447 }
3448
23d56598
JG
3449 /*
3450 * After extracting the packet, we check if the stream is now ready to
3451 * be rotated and perform the action immediately.
3452 *
3453 * Don't overwrite `ret` as callers expect the number of bytes
3454 * consumed to be returned on success.
3455 */
3456 rotation_ret = lttng_consumer_stream_is_rotate_ready(stream);
3457 if (rotation_ret == 1) {
f46376a1 3458 rotation_ret = lttng_consumer_rotate_stream(stream);
23d56598
JG
3459 if (rotation_ret < 0) {
3460 ret = rotation_ret;
3461 ERR("Stream rotation error after consuming data");
3462 goto end;
3463 }
503fefca 3464
23d56598
JG
3465 } else if (rotation_ret < 0) {
3466 ret = rotation_ret;
3467 ERR("Failed to check if stream was ready to rotate after consuming data");
3468 goto end;
3469 }
3470
82e72193 3471sleep_stream:
6f9449c2
JG
3472 if (stream->read_subbuffer_ops.on_sleep) {
3473 stream->read_subbuffer_ops.on_sleep(stream, ctx);
3474 }
3475
3476 ret = written_bytes;
23d56598 3477end:
6f9449c2
JG
3478 if (!locked_by_caller) {
3479 stream->read_subbuffer_ops.unlock(stream);
94d49140 3480 }
6f9449c2 3481
74251bb8 3482 return ret;
6f9449c2
JG
3483error_put_subbuf:
3484 (void) stream->read_subbuffer_ops.put_next_subbuffer(stream, &subbuffer);
3485 goto end;
d41f73b7
MD
3486}
3487
3488int lttng_consumer_on_recv_stream(struct lttng_consumer_stream *stream)
3489{
fa29bfbf 3490 switch (the_consumer_data.type) {
d41f73b7
MD
3491 case LTTNG_CONSUMER_KERNEL:
3492 return lttng_kconsumer_on_recv_stream(stream);
7753dea8
MD
3493 case LTTNG_CONSUMER32_UST:
3494 case LTTNG_CONSUMER64_UST:
d41f73b7
MD
3495 return lttng_ustconsumer_on_recv_stream(stream);
3496 default:
3497 ERR("Unknown consumer_data type");
a0377dfe 3498 abort();
d41f73b7
MD
3499 return -ENOSYS;
3500 }
3501}
e4421fec
DG
3502
3503/*
3504 * Allocate and set consumer data hash tables.
3505 */
cd9adb8b 3506int lttng_consumer_init()
e4421fec 3507{
fa29bfbf
SM
3508 the_consumer_data.channel_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
3509 if (!the_consumer_data.channel_ht) {
282dadbc
MD
3510 goto error;
3511 }
3512
28ab034a 3513 the_consumer_data.channels_by_session_id_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
fa29bfbf 3514 if (!the_consumer_data.channels_by_session_id_ht) {
5c3892a6
JG
3515 goto error;
3516 }
3517
fa29bfbf
SM
3518 the_consumer_data.relayd_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
3519 if (!the_consumer_data.relayd_ht) {
282dadbc
MD
3520 goto error;
3521 }
3522
fa29bfbf
SM
3523 the_consumer_data.stream_list_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
3524 if (!the_consumer_data.stream_list_ht) {
282dadbc
MD
3525 goto error;
3526 }
3527
28ab034a 3528 the_consumer_data.stream_per_chan_id_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
fa29bfbf 3529 if (!the_consumer_data.stream_per_chan_id_ht) {
282dadbc
MD
3530 goto error;
3531 }
3532
3533 data_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
3534 if (!data_ht) {
3535 goto error;
3536 }
3537
3538 metadata_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
3539 if (!metadata_ht) {
3540 goto error;
3541 }
3542
fa29bfbf
SM
3543 the_consumer_data.chunk_registry = lttng_trace_chunk_registry_create();
3544 if (!the_consumer_data.chunk_registry) {
28cc88f3
JG
3545 goto error;
3546 }
3547
282dadbc
MD
3548 return 0;
3549
3550error:
3551 return -1;
e4421fec 3552}
7735ef9e
DG
3553
3554/*
3555 * Process the ADD_RELAYD command receive by a consumer.
3556 *
3557 * This will create a relayd socket pair and add it to the relayd hash table.
3558 * The caller MUST acquire a RCU read side lock before calling it.
3559 */
4222116f 3560void consumer_add_relayd_socket(uint64_t net_seq_idx,
28ab034a
JG
3561 int sock_type,
3562 struct lttng_consumer_local_data *ctx,
3563 int sock,
3564 struct pollfd *consumer_sockpoll,
3565 uint64_t sessiond_id,
3566 uint64_t relayd_session_id,
3567 uint32_t relayd_version_major,
3568 uint32_t relayd_version_minor,
3569 enum lttcomm_sock_proto relayd_socket_protocol)
7735ef9e 3570{
cd2b09ed 3571 int fd = -1, ret = -1, relayd_created = 0;
0c759fc9 3572 enum lttcomm_return_code ret_code = LTTCOMM_CONSUMERD_SUCCESS;
cd9adb8b 3573 struct consumer_relayd_sock_pair *relayd = nullptr;
7735ef9e 3574
a0377dfe 3575 LTTNG_ASSERT(ctx);
4222116f 3576 LTTNG_ASSERT(sock >= 0);
48b7cdc2 3577 ASSERT_RCU_READ_LOCKED();
6151a90f 3578
da009f2c 3579 DBG("Consumer adding relayd socket (idx: %" PRIu64 ")", net_seq_idx);
7735ef9e
DG
3580
3581 /* Get relayd reference if exists. */
3582 relayd = consumer_find_relayd(net_seq_idx);
cd9adb8b 3583 if (relayd == nullptr) {
a0377dfe 3584 LTTNG_ASSERT(sock_type == LTTNG_STREAM_CONTROL);
7735ef9e
DG
3585 /* Not found. Allocate one. */
3586 relayd = consumer_allocate_relayd_sock_pair(net_seq_idx);
cd9adb8b 3587 if (relayd == nullptr) {
618a6a28
MD
3588 ret_code = LTTCOMM_CONSUMERD_ENOMEM;
3589 goto error;
0d08d75e 3590 } else {
30319bcb 3591 relayd->sessiond_session_id = sessiond_id;
0d08d75e 3592 relayd_created = 1;
7735ef9e 3593 }
0d08d75e
DG
3594
3595 /*
3596 * This code path MUST continue to the consumer send status message to
3597 * we can notify the session daemon and continue our work without
3598 * killing everything.
3599 */
da009f2c
MD
3600 } else {
3601 /*
3602 * relayd key should never be found for control socket.
3603 */
a0377dfe 3604 LTTNG_ASSERT(sock_type != LTTNG_STREAM_CONTROL);
0d08d75e
DG
3605 }
3606
3607 /* First send a status message before receiving the fds. */
0c759fc9 3608 ret = consumer_send_status_msg(sock, LTTCOMM_CONSUMERD_SUCCESS);
618a6a28 3609 if (ret < 0) {
0d08d75e 3610 /* Somehow, the session daemon is not responding anymore. */
618a6a28
MD
3611 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_FATAL);
3612 goto error_nosignal;
7735ef9e
DG
3613 }
3614
3615 /* Poll on consumer socket. */
84382d49
MD
3616 ret = lttng_consumer_poll_socket(consumer_sockpoll);
3617 if (ret) {
3618 /* Needing to exit in the middle of a command: error. */
0d08d75e 3619 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_POLL_ERROR);
618a6a28 3620 goto error_nosignal;
7735ef9e
DG
3621 }
3622
3623 /* Get relayd socket from session daemon */
3624 ret = lttcomm_recv_fds_unix_sock(sock, &fd, 1);
3625 if (ret != sizeof(fd)) {
28ab034a 3626 fd = -1; /* Just in case it gets set with an invalid value. */
0d08d75e
DG
3627
3628 /*
3629 * Failing to receive FDs might indicate a major problem such as
3630 * reaching a fd limit during the receive where the kernel returns a
3631 * MSG_CTRUNC and fails to cleanup the fd in the queue. Any case, we
3632 * don't take any chances and stop everything.
3633 *
3634 * XXX: Feature request #558 will fix that and avoid this possible
3635 * issue when reaching the fd limit.
3636 */
3637 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_ERROR_RECV_FD);
618a6a28 3638 ret_code = LTTCOMM_CONSUMERD_ERROR_RECV_FD;
f50f23d9
DG
3639 goto error;
3640 }
3641
7735ef9e
DG
3642 /* Copy socket information and received FD */
3643 switch (sock_type) {
3644 case LTTNG_STREAM_CONTROL:
3645 /* Copy received lttcomm socket */
4222116f 3646 ret = lttcomm_populate_sock_from_open_socket(
28ab034a 3647 &relayd->control_sock.sock, fd, relayd_socket_protocol);
7735ef9e 3648
6151a90f 3649 /* Assign version values. */
4222116f
JR
3650 relayd->control_sock.major = relayd_version_major;
3651 relayd->control_sock.minor = relayd_version_minor;
c5b6f4f0 3652
d3e2ba59 3653 relayd->relayd_session_id = relayd_session_id;
c5b6f4f0 3654
7735ef9e
DG
3655 break;
3656 case LTTNG_STREAM_DATA:
3657 /* Copy received lttcomm socket */
4222116f 3658 ret = lttcomm_populate_sock_from_open_socket(
28ab034a 3659 &relayd->data_sock.sock, fd, relayd_socket_protocol);
6151a90f 3660 /* Assign version values. */
4222116f
JR
3661 relayd->data_sock.major = relayd_version_major;
3662 relayd->data_sock.minor = relayd_version_minor;
7735ef9e
DG
3663 break;
3664 default:
3665 ERR("Unknown relayd socket type (%d)", sock_type);
618a6a28 3666 ret_code = LTTCOMM_CONSUMERD_FATAL;
7735ef9e
DG
3667 goto error;
3668 }
3669
4222116f
JR
3670 if (ret < 0) {
3671 ret_code = LTTCOMM_CONSUMERD_FATAL;
3672 goto error;
3673 }
3674
d88aee68 3675 DBG("Consumer %s socket created successfully with net idx %" PRIu64 " (fd: %d)",
28ab034a
JG
3676 sock_type == LTTNG_STREAM_CONTROL ? "control" : "data",
3677 relayd->net_seq_idx,
3678 fd);
39d9954c
FD
3679 /*
3680 * We gave the ownership of the fd to the relayd structure. Set the
3681 * fd to -1 so we don't call close() on it in the error path below.
3682 */
3683 fd = -1;
7735ef9e 3684
618a6a28
MD
3685 /* We successfully added the socket. Send status back. */
3686 ret = consumer_send_status_msg(sock, ret_code);
3687 if (ret < 0) {
3688 /* Somehow, the session daemon is not responding anymore. */
3689 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_FATAL);
3690 goto error_nosignal;
3691 }
3692
7735ef9e
DG
3693 /*
3694 * Add relayd socket pair to consumer data hashtable. If object already
3695 * exists or on error, the function gracefully returns.
3696 */
9276e5c8 3697 relayd->ctx = ctx;
d09e1200 3698 add_relayd(relayd);
7735ef9e
DG
3699
3700 /* All good! */
2527bf85 3701 return;
7735ef9e
DG
3702
3703error:
618a6a28
MD
3704 if (consumer_send_status_msg(sock, ret_code) < 0) {
3705 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_FATAL);
3706 }
3707
3708error_nosignal:
4028eeb9
DG
3709 /* Close received socket if valid. */
3710 if (fd >= 0) {
3711 if (close(fd)) {
3712 PERROR("close received socket");
3713 }
3714 }
cd2b09ed
DG
3715
3716 if (relayd_created) {
cd2b09ed
DG
3717 free(relayd);
3718 }
7735ef9e 3719}
ca22feea 3720
f7079f67
DG
3721/*
3722 * Search for a relayd associated to the session id and return the reference.
3723 *
3724 * A rcu read side lock MUST be acquire before calling this function and locked
3725 * until the relayd object is no longer necessary.
3726 */
3727static struct consumer_relayd_sock_pair *find_relayd_by_session_id(uint64_t id)
3728{
3729 struct lttng_ht_iter iter;
cd9adb8b 3730 struct consumer_relayd_sock_pair *relayd = nullptr;
f7079f67 3731
48b7cdc2
FD
3732 ASSERT_RCU_READ_LOCKED();
3733
f7079f67 3734 /* Iterate over all relayd since they are indexed by net_seq_idx. */
28ab034a 3735 cds_lfht_for_each_entry (the_consumer_data.relayd_ht->ht, &iter.iter, relayd, node.node) {
18261bd1
DG
3736 /*
3737 * Check by sessiond id which is unique here where the relayd session
3738 * id might not be when having multiple relayd.
3739 */
3740 if (relayd->sessiond_session_id == id) {
f7079f67 3741 /* Found the relayd. There can be only one per id. */
18261bd1 3742 goto found;
f7079f67
DG
3743 }
3744 }
3745
cd9adb8b 3746 return nullptr;
18261bd1
DG
3747
3748found:
f7079f67
DG
3749 return relayd;
3750}
3751
ca22feea
DG
3752/*
3753 * Check if for a given session id there is still data needed to be extract
3754 * from the buffers.
3755 *
6d805429 3756 * Return 1 if data is pending or else 0 meaning ready to be read.
ca22feea 3757 */
6d805429 3758int consumer_data_pending(uint64_t id)
ca22feea
DG
3759{
3760 int ret;
3761 struct lttng_ht_iter iter;
3762 struct lttng_ht *ht;
3763 struct lttng_consumer_stream *stream;
cd9adb8b 3764 struct consumer_relayd_sock_pair *relayd = nullptr;
6d805429 3765 int (*data_pending)(struct lttng_consumer_stream *);
ca22feea 3766
6d805429 3767 DBG("Consumer data pending command on session id %" PRIu64, id);
ca22feea 3768
6f6eda74 3769 rcu_read_lock();
fa29bfbf 3770 pthread_mutex_lock(&the_consumer_data.lock);
ca22feea 3771
fa29bfbf 3772 switch (the_consumer_data.type) {
ca22feea 3773 case LTTNG_CONSUMER_KERNEL:
6d805429 3774 data_pending = lttng_kconsumer_data_pending;
ca22feea
DG
3775 break;
3776 case LTTNG_CONSUMER32_UST:
3777 case LTTNG_CONSUMER64_UST:
6d805429 3778 data_pending = lttng_ustconsumer_data_pending;
ca22feea
DG
3779 break;
3780 default:
3781 ERR("Unknown consumer data type");
a0377dfe 3782 abort();
ca22feea
DG
3783 }
3784
3785 /* Ease our life a bit */
fa29bfbf 3786 ht = the_consumer_data.stream_list_ht;
ca22feea 3787
c8f59ee5 3788 cds_lfht_for_each_entry_duplicate(ht->ht,
28ab034a
JG
3789 ht->hash_fct(&id, lttng_ht_seed),
3790 ht->match_fct,
3791 &id,
3792 &iter.iter,
3793 stream,
3794 node_session_id.node)
3795 {
bb586a6e 3796 pthread_mutex_lock(&stream->lock);
ca22feea 3797
4e9a4686
DG
3798 /*
3799 * A removed node from the hash table indicates that the stream has
3800 * been deleted thus having a guarantee that the buffers are closed
3801 * on the consumer side. However, data can still be transmitted
3802 * over the network so don't skip the relayd check.
3803 */
3804 ret = cds_lfht_is_node_deleted(&stream->node.node);
3805 if (!ret) {
3806 /* Check the stream if there is data in the buffers. */
6d805429
DG
3807 ret = data_pending(stream);
3808 if (ret == 1) {
4e9a4686 3809 pthread_mutex_unlock(&stream->lock);
f7079f67 3810 goto data_pending;
4e9a4686
DG
3811 }
3812 }
3813
d9f0c7c7
JR
3814 pthread_mutex_unlock(&stream->lock);
3815 }
3816
3817 relayd = find_relayd_by_session_id(id);
3818 if (relayd) {
3819 unsigned int is_data_inflight = 0;
3820
3821 /* Send init command for data pending. */
3822 pthread_mutex_lock(&relayd->ctrl_sock_mutex);
28ab034a 3823 ret = relayd_begin_data_pending(&relayd->control_sock, relayd->relayd_session_id);
d9f0c7c7
JR
3824 if (ret < 0) {
3825 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
3826 /* Communication error thus the relayd so no data pending. */
3827 goto data_not_pending;
3828 }
3829
3830 cds_lfht_for_each_entry_duplicate(ht->ht,
28ab034a
JG
3831 ht->hash_fct(&id, lttng_ht_seed),
3832 ht->match_fct,
3833 &id,
3834 &iter.iter,
3835 stream,
3836 node_session_id.node)
3837 {
c8f59ee5 3838 if (stream->metadata_flag) {
ad7051c0 3839 ret = relayd_quiescent_control(&relayd->control_sock,
28ab034a 3840 stream->relayd_stream_id);
c8f59ee5 3841 } else {
6d805429 3842 ret = relayd_data_pending(&relayd->control_sock,
28ab034a
JG
3843 stream->relayd_stream_id,
3844 stream->next_net_seq_num - 1);
c8f59ee5 3845 }
d9f0c7c7
JR
3846
3847 if (ret == 1) {
3848 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
3849 goto data_pending;
3850 } else if (ret < 0) {
28ab034a
JG
3851 ERR("Relayd data pending failed. Cleaning up relayd %" PRIu64 ".",
3852 relayd->net_seq_idx);
9276e5c8
JR
3853 lttng_consumer_cleanup_relayd(relayd);
3854 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
9276e5c8
JR
3855 goto data_not_pending;
3856 }
c8f59ee5 3857 }
f7079f67 3858
d9f0c7c7 3859 /* Send end command for data pending. */
28ab034a
JG
3860 ret = relayd_end_data_pending(
3861 &relayd->control_sock, relayd->relayd_session_id, &is_data_inflight);
f7079f67 3862 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
bdd88757 3863 if (ret < 0) {
28ab034a
JG
3864 ERR("Relayd end data pending failed. Cleaning up relayd %" PRIu64 ".",
3865 relayd->net_seq_idx);
9276e5c8 3866 lttng_consumer_cleanup_relayd(relayd);
f7079f67
DG
3867 goto data_not_pending;
3868 }
bdd88757
DG
3869 if (is_data_inflight) {
3870 goto data_pending;
3871 }
f7079f67
DG
3872 }
3873
ca22feea 3874 /*
f7079f67
DG
3875 * Finding _no_ node in the hash table and no inflight data means that the
3876 * stream(s) have been removed thus data is guaranteed to be available for
3877 * analysis from the trace files.
ca22feea
DG
3878 */
3879
f7079f67 3880data_not_pending:
ca22feea 3881 /* Data is available to be read by a viewer. */
fa29bfbf 3882 pthread_mutex_unlock(&the_consumer_data.lock);
c8f59ee5 3883 rcu_read_unlock();
6d805429 3884 return 0;
ca22feea 3885
f7079f67 3886data_pending:
ca22feea 3887 /* Data is still being extracted from buffers. */
fa29bfbf 3888 pthread_mutex_unlock(&the_consumer_data.lock);
c8f59ee5 3889 rcu_read_unlock();
6d805429 3890 return 1;
ca22feea 3891}
f50f23d9
DG
3892
3893/*
3894 * Send a ret code status message to the sessiond daemon.
3895 *
3896 * Return the sendmsg() return value.
3897 */
3898int consumer_send_status_msg(int sock, int ret_code)
3899{
3900 struct lttcomm_consumer_status_msg msg;
3901
53efb85a 3902 memset(&msg, 0, sizeof(msg));
97535efa 3903 msg.ret_code = (lttcomm_return_code) ret_code;
f50f23d9
DG
3904
3905 return lttcomm_send_unix_sock(sock, &msg, sizeof(msg));
3906}
ffe60014
DG
3907
3908/*
3909 * Send a channel status message to the sessiond daemon.
3910 *
3911 * Return the sendmsg() return value.
3912 */
28ab034a 3913int consumer_send_status_channel(int sock, struct lttng_consumer_channel *channel)
ffe60014
DG
3914{
3915 struct lttcomm_consumer_status_channel msg;
3916
a0377dfe 3917 LTTNG_ASSERT(sock >= 0);
ffe60014 3918
53efb85a 3919 memset(&msg, 0, sizeof(msg));
ffe60014 3920 if (!channel) {
0c759fc9 3921 msg.ret_code = LTTCOMM_CONSUMERD_CHANNEL_FAIL;
ffe60014 3922 } else {
0c759fc9 3923 msg.ret_code = LTTCOMM_CONSUMERD_SUCCESS;
ffe60014
DG
3924 msg.key = channel->key;
3925 msg.stream_count = channel->streams.count;
3926 }
3927
3928 return lttcomm_send_unix_sock(sock, &msg, sizeof(msg));
3929}
5c786ded 3930
d07ceecd 3931unsigned long consumer_get_consume_start_pos(unsigned long consumed_pos,
28ab034a
JG
3932 unsigned long produced_pos,
3933 uint64_t nb_packets_per_stream,
3934 uint64_t max_sb_size)
5c786ded 3935{
d07ceecd 3936 unsigned long start_pos;
5c786ded 3937
d07ceecd 3938 if (!nb_packets_per_stream) {
28ab034a 3939 return consumed_pos; /* Grab everything */
d07ceecd 3940 }
1cbd136b 3941 start_pos = produced_pos - lttng_offset_align_floor(produced_pos, max_sb_size);
d07ceecd
MD
3942 start_pos -= max_sb_size * nb_packets_per_stream;
3943 if ((long) (start_pos - consumed_pos) < 0) {
28ab034a 3944 return consumed_pos; /* Grab everything */
d07ceecd
MD
3945 }
3946 return start_pos;
5c786ded 3947}
a1ae2ea5 3948
c1dcb8bb
JG
3949/* Stream lock must be held by the caller. */
3950static int sample_stream_positions(struct lttng_consumer_stream *stream,
28ab034a
JG
3951 unsigned long *produced,
3952 unsigned long *consumed)
c1dcb8bb
JG
3953{
3954 int ret;
3955
3956 ASSERT_LOCKED(stream->lock);
3957
3958 ret = lttng_consumer_sample_snapshot_positions(stream);
3959 if (ret < 0) {
3960 ERR("Failed to sample snapshot positions");
3961 goto end;
3962 }
3963
3964 ret = lttng_consumer_get_produced_snapshot(stream, produced);
3965 if (ret < 0) {
3966 ERR("Failed to sample produced position");
3967 goto end;
3968 }
3969
3970 ret = lttng_consumer_get_consumed_snapshot(stream, consumed);
3971 if (ret < 0) {
3972 ERR("Failed to sample consumed position");
3973 goto end;
3974 }
3975
3976end:
3977 return ret;
3978}
3979
b99a8d42
JD
3980/*
3981 * Sample the rotate position for all the streams of a channel. If a stream
3982 * is already at the rotate position (produced == consumed), we flag it as
3983 * ready for rotation. The rotation of ready streams occurs after we have
3984 * replied to the session daemon that we have finished sampling the positions.
92b7a7f8 3985 * Must be called with RCU read-side lock held to ensure existence of channel.
b99a8d42
JD
3986 *
3987 * Returns 0 on success, < 0 on error
3988 */
92b7a7f8 3989int lttng_consumer_rotate_channel(struct lttng_consumer_channel *channel,
28ab034a
JG
3990 uint64_t key,
3991 uint64_t relayd_id)
b99a8d42
JD
3992{
3993 int ret;
b99a8d42
JD
3994 struct lttng_consumer_stream *stream;
3995 struct lttng_ht_iter iter;
fa29bfbf 3996 struct lttng_ht *ht = the_consumer_data.stream_per_chan_id_ht;
c35f9726
JG
3997 struct lttng_dynamic_array stream_rotation_positions;
3998 uint64_t next_chunk_id, stream_count = 0;
3999 enum lttng_trace_chunk_status chunk_status;
4000 const bool is_local_trace = relayd_id == -1ULL;
cd9adb8b 4001 struct consumer_relayd_sock_pair *relayd = nullptr;
c35f9726 4002 bool rotating_to_new_chunk = true;
b32703d6
JG
4003 /* Array of `struct lttng_consumer_stream *` */
4004 struct lttng_dynamic_pointer_array streams_packet_to_open;
4005 size_t stream_idx;
b99a8d42 4006
48b7cdc2
FD
4007 ASSERT_RCU_READ_LOCKED();
4008
b99a8d42
JD
4009 DBG("Consumer sample rotate position for channel %" PRIu64, key);
4010
cd9adb8b
JG
4011 lttng_dynamic_array_init(&stream_rotation_positions,
4012 sizeof(struct relayd_stream_rotation_position),
4013 nullptr);
4014 lttng_dynamic_pointer_array_init(&streams_packet_to_open, nullptr);
c35f9726 4015
b99a8d42
JD
4016 rcu_read_lock();
4017
b99a8d42 4018 pthread_mutex_lock(&channel->lock);
a0377dfe 4019 LTTNG_ASSERT(channel->trace_chunk);
28ab034a 4020 chunk_status = lttng_trace_chunk_get_id(channel->trace_chunk, &next_chunk_id);
c35f9726
JG
4021 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
4022 ret = -1;
4023 goto end_unlock_channel;
4024 }
b99a8d42
JD
4025
4026 cds_lfht_for_each_entry_duplicate(ht->ht,
28ab034a
JG
4027 ht->hash_fct(&channel->key, lttng_ht_seed),
4028 ht->match_fct,
4029 &channel->key,
4030 &iter.iter,
4031 stream,
4032 node_channel_id.node)
4033 {
a40a503f 4034 unsigned long produced_pos = 0, consumed_pos = 0;
b99a8d42
JD
4035
4036 health_code_update();
4037
4038 /*
4039 * Lock stream because we are about to change its state.
4040 */
4041 pthread_mutex_lock(&stream->lock);
4042
c35f9726
JG
4043 if (stream->trace_chunk == stream->chan->trace_chunk) {
4044 rotating_to_new_chunk = false;
4045 }
4046
a40a503f 4047 /*
c1dcb8bb 4048 * Do not flush a packet when rotating from a NULL trace
a9dde553 4049 * chunk. The stream has no means to output data, and the prior
c1dcb8bb
JG
4050 * rotation which rotated to NULL performed that side-effect
4051 * already. No new data can be produced when a stream has no
4052 * associated trace chunk (e.g. a stop followed by a rotate).
a40a503f 4053 */
a9dde553 4054 if (stream->trace_chunk) {
c1dcb8bb
JG
4055 bool flush_active;
4056
4057 if (stream->metadata_flag) {
4058 /*
4059 * Don't produce an empty metadata packet,
4060 * simply close the current one.
4061 *
4062 * Metadata is regenerated on every trace chunk
4063 * switch; there is no concern that no data was
4064 * produced.
4065 */
4066 flush_active = true;
4067 } else {
4068 /*
4069 * Only flush an empty packet if the "packet
4070 * open" could not be performed on transition
4071 * to a new trace chunk and no packets were
4072 * consumed within the chunk's lifetime.
4073 */
4074 if (stream->opened_packet_in_current_trace_chunk) {
4075 flush_active = true;
4076 } else {
4077 /*
4078 * Stream could have been full at the
4079 * time of rotation, but then have had
4080 * no activity at all.
4081 *
4082 * It is important to flush a packet
4083 * to prevent 0-length files from being
4084 * produced as most viewers choke on
4085 * them.
4086 *
4087 * Unfortunately viewers will not be
4088 * able to know that tracing was active
4089 * for this stream during this trace
4090 * chunk's lifetime.
4091 */
28ab034a
JG
4092 ret = sample_stream_positions(
4093 stream, &produced_pos, &consumed_pos);
c1dcb8bb
JG
4094 if (ret) {
4095 goto end_unlock_stream;
4096 }
4097
4098 /*
4099 * Don't flush an empty packet if data
4100 * was produced; it will be consumed
4101 * before the rotation completes.
4102 */
4103 flush_active = produced_pos != consumed_pos;
4104 if (!flush_active) {
c1dcb8bb
JG
4105 const char *trace_chunk_name;
4106 uint64_t trace_chunk_id;
4107
4108 chunk_status = lttng_trace_chunk_get_name(
28ab034a
JG
4109 stream->trace_chunk,
4110 &trace_chunk_name,
cd9adb8b 4111 nullptr);
c1dcb8bb
JG
4112 if (chunk_status == LTTNG_TRACE_CHUNK_STATUS_NONE) {
4113 trace_chunk_name = "none";
4114 }
4115
4116 /*
4117 * Consumer trace chunks are
4118 * never anonymous.
4119 */
4120 chunk_status = lttng_trace_chunk_get_id(
28ab034a 4121 stream->trace_chunk, &trace_chunk_id);
a0377dfe 4122 LTTNG_ASSERT(chunk_status ==
28ab034a 4123 LTTNG_TRACE_CHUNK_STATUS_OK);
c1dcb8bb
JG
4124
4125 DBG("Unable to open packet for stream during trace chunk's lifetime. "
28ab034a
JG
4126 "Flushing an empty packet to prevent an empty file from being created: "
4127 "stream id = %" PRIu64
4128 ", trace chunk name = `%s`, trace chunk id = %" PRIu64,
4129 stream->key,
4130 trace_chunk_name,
4131 trace_chunk_id);
c1dcb8bb
JG
4132 }
4133 }
4134 }
4135
a9dde553 4136 /*
c1dcb8bb
JG
4137 * Close the current packet before sampling the
4138 * ring buffer positions.
a9dde553 4139 */
c1dcb8bb 4140 ret = consumer_stream_flush_buffer(stream, flush_active);
a9dde553
MD
4141 if (ret < 0) {
4142 ERR("Failed to flush stream %" PRIu64 " during channel rotation",
28ab034a 4143 stream->key);
a9dde553
MD
4144 goto end_unlock_stream;
4145 }
b99a8d42
JD
4146 }
4147
a40a503f
MD
4148 ret = lttng_consumer_take_snapshot(stream);
4149 if (ret < 0 && ret != -ENODATA && ret != -EAGAIN) {
4150 ERR("Failed to sample snapshot position during channel rotation");
b99a8d42
JD
4151 goto end_unlock_stream;
4152 }
a40a503f 4153 if (!ret) {
28ab034a 4154 ret = lttng_consumer_get_produced_snapshot(stream, &produced_pos);
a40a503f
MD
4155 if (ret < 0) {
4156 ERR("Failed to sample produced position during channel rotation");
4157 goto end_unlock_stream;
4158 }
b99a8d42 4159
28ab034a 4160 ret = lttng_consumer_get_consumed_snapshot(stream, &consumed_pos);
a40a503f
MD
4161 if (ret < 0) {
4162 ERR("Failed to sample consumed position during channel rotation");
4163 goto end_unlock_stream;
4164 }
4165 }
4166 /*
4167 * Align produced position on the start-of-packet boundary of the first
4168 * packet going into the next trace chunk.
4169 */
1cbd136b 4170 produced_pos = lttng_align_floor(produced_pos, stream->max_sb_size);
a40a503f 4171 if (consumed_pos == produced_pos) {
f8528c7a 4172 DBG("Set rotate ready for stream %" PRIu64 " produced = %lu consumed = %lu",
28ab034a
JG
4173 stream->key,
4174 produced_pos,
4175 consumed_pos);
b99a8d42 4176 stream->rotate_ready = true;
f8528c7a
MD
4177 } else {
4178 DBG("Different consumed and produced positions "
28ab034a
JG
4179 "for stream %" PRIu64 " produced = %lu consumed = %lu",
4180 stream->key,
4181 produced_pos,
4182 consumed_pos);
b99a8d42 4183 }
633d0182 4184 /*
a40a503f
MD
4185 * The rotation position is based on the packet_seq_num of the
4186 * packet following the last packet that was consumed for this
4187 * stream, incremented by the offset between produced and
4188 * consumed positions. This rotation position is a lower bound
4189 * (inclusive) at which the next trace chunk starts. Since it
4190 * is a lower bound, it is OK if the packet_seq_num does not
4191 * correspond exactly to the same packet identified by the
4192 * consumed_pos, which can happen in overwrite mode.
633d0182 4193 */
a40a503f
MD
4194 if (stream->sequence_number_unavailable) {
4195 /*
4196 * Rotation should never be performed on a session which
4197 * interacts with a pre-2.8 lttng-modules, which does
4198 * not implement packet sequence number.
4199 */
4200 ERR("Failure to rotate stream %" PRIu64 ": sequence number unavailable",
28ab034a 4201 stream->key);
a40a503f 4202 ret = -1;
b99a8d42
JD
4203 goto end_unlock_stream;
4204 }
a40a503f 4205 stream->rotate_position = stream->last_sequence_number + 1 +
28ab034a 4206 ((produced_pos - consumed_pos) / stream->max_sb_size);
f8528c7a 4207 DBG("Set rotation position for stream %" PRIu64 " at position %" PRIu64,
28ab034a
JG
4208 stream->key,
4209 stream->rotate_position);
b99a8d42 4210
c35f9726 4211 if (!is_local_trace) {
633d0182
JG
4212 /*
4213 * The relay daemon control protocol expects a rotation
4214 * position as "the sequence number of the first packet
a40a503f 4215 * _after_ the current trace chunk".
633d0182 4216 */
c35f9726
JG
4217 const struct relayd_stream_rotation_position position = {
4218 .stream_id = stream->relayd_stream_id,
a40a503f 4219 .rotate_at_seq_num = stream->rotate_position,
c35f9726
JG
4220 };
4221
28ab034a
JG
4222 ret = lttng_dynamic_array_add_element(&stream_rotation_positions,
4223 &position);
c35f9726
JG
4224 if (ret) {
4225 ERR("Failed to allocate stream rotation position");
4226 goto end_unlock_stream;
4227 }
4228 stream_count++;
4229 }
f96af312
JG
4230
4231 stream->opened_packet_in_current_trace_chunk = false;
4232
4233 if (rotating_to_new_chunk && !stream->metadata_flag) {
4234 /*
4235 * Attempt to flush an empty packet as close to the
4236 * rotation point as possible. In the event where a
4237 * stream remains inactive after the rotation point,
4238 * this ensures that the new trace chunk has a
4239 * beginning timestamp set at the begining of the
4240 * trace chunk instead of only creating an empty
4241 * packet when the trace chunk is stopped.
4242 *
4243 * This indicates to the viewers that the stream
4244 * was being recorded, but more importantly it
4245 * allows viewers to determine a useable trace
4246 * intersection.
4247 *
4248 * This presents a problem in the case where the
4249 * ring-buffer is completely full.
4250 *
4251 * Consider the following scenario:
4252 * - The consumption of data is slow (slow network,
4253 * for instance),
4254 * - The ring buffer is full,
4255 * - A rotation is initiated,
4256 * - The flush below does nothing (no space left to
4257 * open a new packet),
4258 * - The other streams rotate very soon, and new
4259 * data is produced in the new chunk,
4260 * - This stream completes its rotation long after the
4261 * rotation was initiated
4262 * - The session is stopped before any event can be
4263 * produced in this stream's buffers.
4264 *
4265 * The resulting trace chunk will have a single packet
4266 * temporaly at the end of the trace chunk for this
4267 * stream making the stream intersection more narrow
4268 * than it should be.
4269 *
4270 * To work-around this, an empty flush is performed
4271 * after the first consumption of a packet during a
4272 * rotation if open_packet fails. The idea is that
4273 * consuming a packet frees enough space to switch
4274 * packets in this scenario and allows the tracer to
4275 * "stamp" the beginning of the new trace chunk at the
4276 * earliest possible point.
b32703d6
JG
4277 *
4278 * The packet open is performed after the channel
4279 * rotation to ensure that no attempt to open a packet
4280 * is performed in a stream that has no active trace
4281 * chunk.
f96af312 4282 */
28ab034a
JG
4283 ret = lttng_dynamic_pointer_array_add_pointer(&streams_packet_to_open,
4284 stream);
b32703d6
JG
4285 if (ret) {
4286 PERROR("Failed to add a stream pointer to array of streams in which to open a packet");
f96af312
JG
4287 ret = -1;
4288 goto end_unlock_stream;
f96af312
JG
4289 }
4290 }
4291
b99a8d42
JD
4292 pthread_mutex_unlock(&stream->lock);
4293 }
cd9adb8b 4294 stream = nullptr;
b99a8d42 4295
b32703d6
JG
4296 if (!is_local_trace) {
4297 relayd = consumer_find_relayd(relayd_id);
4298 if (!relayd) {
4299 ERR("Failed to find relayd %" PRIu64, relayd_id);
4300 ret = -1;
4301 goto end_unlock_channel;
4302 }
c35f9726 4303
b32703d6 4304 pthread_mutex_lock(&relayd->ctrl_sock_mutex);
28ab034a
JG
4305 ret = relayd_rotate_streams(&relayd->control_sock,
4306 stream_count,
cd9adb8b 4307 rotating_to_new_chunk ? &next_chunk_id : nullptr,
28ab034a
JG
4308 (const struct relayd_stream_rotation_position *)
4309 stream_rotation_positions.buffer.data);
b32703d6
JG
4310 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
4311 if (ret < 0) {
4312 ERR("Relayd rotate stream failed. Cleaning up relayd %" PRIu64,
28ab034a 4313 relayd->net_seq_idx);
b32703d6
JG
4314 lttng_consumer_cleanup_relayd(relayd);
4315 goto end_unlock_channel;
4316 }
c35f9726
JG
4317 }
4318
b32703d6 4319 for (stream_idx = 0;
28ab034a
JG
4320 stream_idx < lttng_dynamic_pointer_array_get_count(&streams_packet_to_open);
4321 stream_idx++) {
b32703d6
JG
4322 enum consumer_stream_open_packet_status status;
4323
97535efa 4324 stream = (lttng_consumer_stream *) lttng_dynamic_pointer_array_get_pointer(
28ab034a 4325 &streams_packet_to_open, stream_idx);
b32703d6
JG
4326
4327 pthread_mutex_lock(&stream->lock);
4328 status = consumer_stream_open_packet(stream);
4329 pthread_mutex_unlock(&stream->lock);
4330 switch (status) {
4331 case CONSUMER_STREAM_OPEN_PACKET_STATUS_OPENED:
4332 DBG("Opened a packet after a rotation: stream id = %" PRIu64
4333 ", channel name = %s, session id = %" PRIu64,
28ab034a
JG
4334 stream->key,
4335 stream->chan->name,
4336 stream->chan->session_id);
b32703d6
JG
4337 break;
4338 case CONSUMER_STREAM_OPEN_PACKET_STATUS_NO_SPACE:
4339 /*
4340 * Can't open a packet as there is no space left
4341 * in the buffer. A new packet will be opened
4342 * once one has been consumed.
4343 */
4344 DBG("No space left to open a packet after a rotation: stream id = %" PRIu64
4345 ", channel name = %s, session id = %" PRIu64,
28ab034a
JG
4346 stream->key,
4347 stream->chan->name,
4348 stream->chan->session_id);
b32703d6
JG
4349 break;
4350 case CONSUMER_STREAM_OPEN_PACKET_STATUS_ERROR:
4351 /* Logged by callee. */
4352 ret = -1;
7a86c13d 4353 goto end_unlock_channel;
b32703d6
JG
4354 default:
4355 abort();
4356 }
c35f9726
JG
4357 }
4358
b32703d6 4359 pthread_mutex_unlock(&channel->lock);
b99a8d42
JD
4360 ret = 0;
4361 goto end;
4362
4363end_unlock_stream:
4364 pthread_mutex_unlock(&stream->lock);
c35f9726 4365end_unlock_channel:
b99a8d42
JD
4366 pthread_mutex_unlock(&channel->lock);
4367end:
4368 rcu_read_unlock();
c35f9726 4369 lttng_dynamic_array_reset(&stream_rotation_positions);
b32703d6 4370 lttng_dynamic_pointer_array_reset(&streams_packet_to_open);
b99a8d42
JD
4371 return ret;
4372}
4373
28ab034a 4374static int consumer_clear_buffer(struct lttng_consumer_stream *stream)
5f3aff8b
MD
4375{
4376 int ret = 0;
4377 unsigned long consumed_pos_before, consumed_pos_after;
4378
4379 ret = lttng_consumer_sample_snapshot_positions(stream);
4380 if (ret < 0) {
4381 ERR("Taking snapshot positions");
4382 goto end;
4383 }
4384
4385 ret = lttng_consumer_get_consumed_snapshot(stream, &consumed_pos_before);
4386 if (ret < 0) {
4387 ERR("Consumed snapshot position");
4388 goto end;
4389 }
4390
fa29bfbf 4391 switch (the_consumer_data.type) {
5f3aff8b
MD
4392 case LTTNG_CONSUMER_KERNEL:
4393 ret = kernctl_buffer_clear(stream->wait_fd);
4394 if (ret < 0) {
96393977 4395 ERR("Failed to clear kernel stream (ret = %d)", ret);
5f3aff8b
MD
4396 goto end;
4397 }
4398 break;
4399 case LTTNG_CONSUMER32_UST:
4400 case LTTNG_CONSUMER64_UST:
881fc67f
MD
4401 ret = lttng_ustconsumer_clear_buffer(stream);
4402 if (ret < 0) {
4403 ERR("Failed to clear ust stream (ret = %d)", ret);
4404 goto end;
4405 }
5f3aff8b
MD
4406 break;
4407 default:
4408 ERR("Unknown consumer_data type");
4409 abort();
4410 }
4411
4412 ret = lttng_consumer_sample_snapshot_positions(stream);
4413 if (ret < 0) {
4414 ERR("Taking snapshot positions");
4415 goto end;
4416 }
4417 ret = lttng_consumer_get_consumed_snapshot(stream, &consumed_pos_after);
4418 if (ret < 0) {
4419 ERR("Consumed snapshot position");
4420 goto end;
4421 }
4422 DBG("clear: before: %lu after: %lu", consumed_pos_before, consumed_pos_after);
4423end:
4424 return ret;
4425}
4426
28ab034a 4427static int consumer_clear_stream(struct lttng_consumer_stream *stream)
5f3aff8b
MD
4428{
4429 int ret;
4430
cd9adb8b 4431 ret = consumer_stream_flush_buffer(stream, true);
5f3aff8b 4432 if (ret < 0) {
28ab034a 4433 ERR("Failed to flush stream %" PRIu64 " during channel clear", stream->key);
5f3aff8b
MD
4434 ret = LTTCOMM_CONSUMERD_FATAL;
4435 goto error;
4436 }
4437
4438 ret = consumer_clear_buffer(stream);
4439 if (ret < 0) {
28ab034a 4440 ERR("Failed to clear stream %" PRIu64 " during channel clear", stream->key);
5f3aff8b
MD
4441 ret = LTTCOMM_CONSUMERD_FATAL;
4442 goto error;
4443 }
4444
4445 ret = LTTCOMM_CONSUMERD_SUCCESS;
4446error:
4447 return ret;
4448}
4449
28ab034a 4450static int consumer_clear_unmonitored_channel(struct lttng_consumer_channel *channel)
5f3aff8b
MD
4451{
4452 int ret;
4453 struct lttng_consumer_stream *stream;
4454
4455 rcu_read_lock();
4456 pthread_mutex_lock(&channel->lock);
28ab034a 4457 cds_list_for_each_entry (stream, &channel->streams.head, send_node) {
5f3aff8b
MD
4458 health_code_update();
4459 pthread_mutex_lock(&stream->lock);
4460 ret = consumer_clear_stream(stream);
4461 if (ret) {
4462 goto error_unlock;
4463 }
4464 pthread_mutex_unlock(&stream->lock);
4465 }
4466 pthread_mutex_unlock(&channel->lock);
4467 rcu_read_unlock();
4468 return 0;
4469
4470error_unlock:
4471 pthread_mutex_unlock(&stream->lock);
4472 pthread_mutex_unlock(&channel->lock);
4473 rcu_read_unlock();
5f3aff8b
MD
4474 return ret;
4475}
4476
02d02e31
JD
4477/*
4478 * Check if a stream is ready to be rotated after extracting it.
4479 *
4480 * Return 1 if it is ready for rotation, 0 if it is not, a negative value on
4481 * error. Stream lock must be held.
4482 */
4483int lttng_consumer_stream_is_rotate_ready(struct lttng_consumer_stream *stream)
4484{
28ab034a
JG
4485 DBG("Check is rotate ready for stream %" PRIu64 " ready %u rotate_position %" PRIu64
4486 " last_sequence_number %" PRIu64,
4487 stream->key,
4488 stream->rotate_ready,
4489 stream->rotate_position,
4490 stream->last_sequence_number);
02d02e31 4491 if (stream->rotate_ready) {
a40a503f 4492 return 1;
02d02e31
JD
4493 }
4494
4495 /*
a40a503f
MD
4496 * If packet seq num is unavailable, it means we are interacting
4497 * with a pre-2.8 lttng-modules which does not implement the
4498 * sequence number. Rotation should never be used by sessiond in this
4499 * scenario.
02d02e31 4500 */
a40a503f
MD
4501 if (stream->sequence_number_unavailable) {
4502 ERR("Internal error: rotation used on stream %" PRIu64
28ab034a
JG
4503 " with unavailable sequence number",
4504 stream->key);
a40a503f 4505 return -1;
02d02e31
JD
4506 }
4507
28ab034a 4508 if (stream->rotate_position == -1ULL || stream->last_sequence_number == -1ULL) {
a40a503f 4509 return 0;
02d02e31
JD
4510 }
4511
a40a503f
MD
4512 /*
4513 * Rotate position not reached yet. The stream rotate position is
4514 * the position of the next packet belonging to the next trace chunk,
4515 * but consumerd considers rotation ready when reaching the last
4516 * packet of the current chunk, hence the "rotate_position - 1".
4517 */
f8528c7a 4518
28ab034a
JG
4519 DBG("Check is rotate ready for stream %" PRIu64 " last_sequence_number %" PRIu64
4520 " rotate_position %" PRIu64,
4521 stream->key,
4522 stream->last_sequence_number,
4523 stream->rotate_position);
a40a503f
MD
4524 if (stream->last_sequence_number >= stream->rotate_position - 1) {
4525 return 1;
02d02e31 4526 }
02d02e31 4527
a40a503f 4528 return 0;
02d02e31
JD
4529}
4530
d73bf3d7
JD
4531/*
4532 * Reset the state for a stream after a rotation occurred.
4533 */
4534void lttng_consumer_reset_stream_rotate_state(struct lttng_consumer_stream *stream)
4535{
28ab034a 4536 DBG("lttng_consumer_reset_stream_rotate_state for stream %" PRIu64, stream->key);
a40a503f 4537 stream->rotate_position = -1ULL;
d73bf3d7
JD
4538 stream->rotate_ready = false;
4539}
4540
4541/*
4542 * Perform the rotation a local stream file.
4543 */
28ab034a 4544static int rotate_local_stream(struct lttng_consumer_stream *stream)
d73bf3d7 4545{
d2956687 4546 int ret = 0;
d73bf3d7 4547
d2956687 4548 DBG("Rotate local stream: stream key %" PRIu64 ", channel key %" PRIu64,
28ab034a
JG
4549 stream->key,
4550 stream->chan->key);
d73bf3d7 4551 stream->tracefile_size_current = 0;
d2956687 4552 stream->tracefile_count_current = 0;
d73bf3d7 4553
d2956687
JG
4554 if (stream->out_fd >= 0) {
4555 ret = close(stream->out_fd);
4556 if (ret) {
4557 PERROR("Failed to close stream out_fd of channel \"%s\"",
28ab034a 4558 stream->chan->name);
d2956687
JG
4559 }
4560 stream->out_fd = -1;
4561 }
d73bf3d7 4562
d2956687 4563 if (stream->index_file) {
d73bf3d7 4564 lttng_index_file_put(stream->index_file);
cd9adb8b 4565 stream->index_file = nullptr;
d73bf3d7
JD
4566 }
4567
d2956687
JG
4568 if (!stream->trace_chunk) {
4569 goto end;
4570 }
d73bf3d7 4571
d2956687 4572 ret = consumer_stream_create_output_files(stream, true);
d73bf3d7
JD
4573end:
4574 return ret;
d73bf3d7
JD
4575}
4576
d73bf3d7
JD
4577/*
4578 * Performs the stream rotation for the rotate session feature if needed.
d2956687 4579 * It must be called with the channel and stream locks held.
d73bf3d7
JD
4580 *
4581 * Return 0 on success, a negative number of error.
4582 */
f46376a1 4583int lttng_consumer_rotate_stream(struct lttng_consumer_stream *stream)
d73bf3d7
JD
4584{
4585 int ret;
4586
4587 DBG("Consumer rotate stream %" PRIu64, stream->key);
4588
d2956687
JG
4589 /*
4590 * Update the stream's 'current' chunk to the session's (channel)
4591 * now-current chunk.
4592 */
4593 lttng_trace_chunk_put(stream->trace_chunk);
4594 if (stream->chan->trace_chunk == stream->trace_chunk) {
4595 /*
4596 * A channel can be rotated and not have a "next" chunk
4597 * to transition to. In that case, the channel's "current chunk"
4598 * has not been closed yet, but it has not been updated to
4599 * a "next" trace chunk either. Hence, the stream, like its
4600 * parent channel, becomes part of no chunk and can't output
4601 * anything until a new trace chunk is created.
4602 */
cd9adb8b 4603 stream->trace_chunk = nullptr;
28ab034a 4604 } else if (stream->chan->trace_chunk && !lttng_trace_chunk_get(stream->chan->trace_chunk)) {
d2956687
JG
4605 ERR("Failed to acquire a reference to channel's trace chunk during stream rotation");
4606 ret = -1;
4607 goto error;
4608 } else {
4609 /*
4610 * Update the stream's trace chunk to its parent channel's
4611 * current trace chunk.
4612 */
4613 stream->trace_chunk = stream->chan->trace_chunk;
4614 }
4615
c35f9726 4616 if (stream->net_seq_idx == (uint64_t) -1ULL) {
f46376a1 4617 ret = rotate_local_stream(stream);
c35f9726
JG
4618 if (ret < 0) {
4619 ERR("Failed to rotate stream, ret = %i", ret);
4620 goto error;
4621 }
d73bf3d7
JD
4622 }
4623
d2956687
JG
4624 if (stream->metadata_flag && stream->trace_chunk) {
4625 /*
4626 * If the stream has transitioned to a new trace
4627 * chunk, the metadata should be re-dumped to the
4628 * newest chunk.
4629 *
4630 * However, it is possible for a stream to transition to
4631 * a "no-chunk" state. This can happen if a rotation
4632 * occurs on an inactive session. In such cases, the metadata
4633 * regeneration will happen when the next trace chunk is
4634 * created.
4635 */
4636 ret = consumer_metadata_stream_dump(stream);
4637 if (ret) {
4638 goto error;
d73bf3d7
JD
4639 }
4640 }
4641 lttng_consumer_reset_stream_rotate_state(stream);
4642
4643 ret = 0;
4644
4645error:
4646 return ret;
4647}
4648
b99a8d42
JD
4649/*
4650 * Rotate all the ready streams now.
4651 *
4652 * This is especially important for low throughput streams that have already
4653 * been consumed, we cannot wait for their next packet to perform the
4654 * rotation.
92b7a7f8
MD
4655 * Need to be called with RCU read-side lock held to ensure existence of
4656 * channel.
b99a8d42
JD
4657 *
4658 * Returns 0 on success, < 0 on error
4659 */
28ab034a 4660int lttng_consumer_rotate_ready_streams(struct lttng_consumer_channel *channel, uint64_t key)
b99a8d42
JD
4661{
4662 int ret;
b99a8d42
JD
4663 struct lttng_consumer_stream *stream;
4664 struct lttng_ht_iter iter;
fa29bfbf 4665 struct lttng_ht *ht = the_consumer_data.stream_per_chan_id_ht;
b99a8d42 4666
48b7cdc2
FD
4667 ASSERT_RCU_READ_LOCKED();
4668
b99a8d42
JD
4669 rcu_read_lock();
4670
4671 DBG("Consumer rotate ready streams in channel %" PRIu64, key);
4672
b99a8d42 4673 cds_lfht_for_each_entry_duplicate(ht->ht,
28ab034a
JG
4674 ht->hash_fct(&channel->key, lttng_ht_seed),
4675 ht->match_fct,
4676 &channel->key,
4677 &iter.iter,
4678 stream,
4679 node_channel_id.node)
4680 {
b99a8d42
JD
4681 health_code_update();
4682
d2956687 4683 pthread_mutex_lock(&stream->chan->lock);
b99a8d42
JD
4684 pthread_mutex_lock(&stream->lock);
4685
4686 if (!stream->rotate_ready) {
4687 pthread_mutex_unlock(&stream->lock);
d2956687 4688 pthread_mutex_unlock(&stream->chan->lock);
b99a8d42
JD
4689 continue;
4690 }
4691 DBG("Consumer rotate ready stream %" PRIu64, stream->key);
4692
f46376a1 4693 ret = lttng_consumer_rotate_stream(stream);
b99a8d42 4694 pthread_mutex_unlock(&stream->lock);
d2956687 4695 pthread_mutex_unlock(&stream->chan->lock);
b99a8d42
JD
4696 if (ret) {
4697 goto end;
4698 }
4699 }
4700
4701 ret = 0;
4702
4703end:
4704 rcu_read_unlock();
4705 return ret;
4706}
4707
28ab034a
JG
4708enum lttcomm_return_code lttng_consumer_init_command(struct lttng_consumer_local_data *ctx,
4709 const lttng_uuid& sessiond_uuid)
00fb02ac 4710{
d2956687 4711 enum lttcomm_return_code ret;
c70636a7 4712 char uuid_str[LTTNG_UUID_STR_LEN];
00fb02ac 4713
d2956687
JG
4714 if (ctx->sessiond_uuid.is_set) {
4715 ret = LTTCOMM_CONSUMERD_ALREADY_SET;
00fb02ac
JD
4716 goto end;
4717 }
4718
d2956687 4719 ctx->sessiond_uuid.is_set = true;
328c2fe7 4720 ctx->sessiond_uuid.value = sessiond_uuid;
d2956687
JG
4721 ret = LTTCOMM_CONSUMERD_SUCCESS;
4722 lttng_uuid_to_str(sessiond_uuid, uuid_str);
4723 DBG("Received session daemon UUID: %s", uuid_str);
00fb02ac
JD
4724end:
4725 return ret;
4726}
4727
28ab034a
JG
4728enum lttcomm_return_code
4729lttng_consumer_create_trace_chunk(const uint64_t *relayd_id,
4730 uint64_t session_id,
4731 uint64_t chunk_id,
4732 time_t chunk_creation_timestamp,
4733 const char *chunk_override_name,
4734 const struct lttng_credentials *credentials,
4735 struct lttng_directory_handle *chunk_directory_handle)
00fb02ac
JD
4736{
4737 int ret;
d2956687 4738 enum lttcomm_return_code ret_code = LTTCOMM_CONSUMERD_SUCCESS;
cd9adb8b 4739 struct lttng_trace_chunk *created_chunk = nullptr, *published_chunk = nullptr;
d2956687
JG
4740 enum lttng_trace_chunk_status chunk_status;
4741 char relayd_id_buffer[MAX_INT_DEC_LEN(*relayd_id)];
4742 char creation_timestamp_buffer[ISO8601_STR_LEN];
4743 const char *relayd_id_str = "(none)";
4744 const char *creation_timestamp_str;
4745 struct lttng_ht_iter iter;
4746 struct lttng_consumer_channel *channel;
92816cc3 4747
d2956687
JG
4748 if (relayd_id) {
4749 /* Only used for logging purposes. */
28ab034a 4750 ret = snprintf(relayd_id_buffer, sizeof(relayd_id_buffer), "%" PRIu64, *relayd_id);
d2956687
JG
4751 if (ret > 0 && ret < sizeof(relayd_id_buffer)) {
4752 relayd_id_str = relayd_id_buffer;
4753 } else {
4754 relayd_id_str = "(formatting error)";
4755 }
d01ef216 4756 }
d2956687 4757
d01ef216 4758 /* Local protocol error. */
a0377dfe 4759 LTTNG_ASSERT(chunk_creation_timestamp);
d2956687 4760 ret = time_to_iso8601_str(chunk_creation_timestamp,
28ab034a
JG
4761 creation_timestamp_buffer,
4762 sizeof(creation_timestamp_buffer));
4763 creation_timestamp_str = !ret ? creation_timestamp_buffer : "(formatting error)";
d2956687
JG
4764
4765 DBG("Consumer create trace chunk command: relay_id = %s"
28ab034a
JG
4766 ", session_id = %" PRIu64 ", chunk_id = %" PRIu64 ", chunk_override_name = %s"
4767 ", chunk_creation_timestamp = %s",
4768 relayd_id_str,
4769 session_id,
4770 chunk_id,
4771 chunk_override_name ?: "(none)",
4772 creation_timestamp_str);
92816cc3
JG
4773
4774 /*
d2956687
JG
4775 * The trace chunk registry, as used by the consumer daemon, implicitly
4776 * owns the trace chunks. This is only needed in the consumer since
4777 * the consumer has no notion of a session beyond session IDs being
4778 * used to identify other objects.
4779 *
4780 * The lttng_trace_chunk_registry_publish() call below provides a
4781 * reference which is not released; it implicitly becomes the session
4782 * daemon's reference to the chunk in the consumer daemon.
4783 *
4784 * The lifetime of trace chunks in the consumer daemon is managed by
4785 * the session daemon through the LTTNG_CONSUMER_CREATE_TRACE_CHUNK
4786 * and LTTNG_CONSUMER_DESTROY_TRACE_CHUNK commands.
92816cc3 4787 */
cd9adb8b 4788 created_chunk = lttng_trace_chunk_create(chunk_id, chunk_creation_timestamp, nullptr);
d2956687
JG
4789 if (!created_chunk) {
4790 ERR("Failed to create trace chunk");
4791 ret_code = LTTCOMM_CONSUMERD_CREATE_TRACE_CHUNK_FAILED;
7ea24db3 4792 goto error;
d2956687 4793 }
92816cc3 4794
d2956687 4795 if (chunk_override_name) {
28ab034a 4796 chunk_status = lttng_trace_chunk_override_name(created_chunk, chunk_override_name);
d2956687
JG
4797 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
4798 ret_code = LTTCOMM_CONSUMERD_CREATE_TRACE_CHUNK_FAILED;
7ea24db3 4799 goto error;
92816cc3
JG
4800 }
4801 }
4802
d2956687 4803 if (chunk_directory_handle) {
28ab034a 4804 chunk_status = lttng_trace_chunk_set_credentials(created_chunk, credentials);
d2956687
JG
4805 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
4806 ERR("Failed to set trace chunk credentials");
4807 ret_code = LTTCOMM_CONSUMERD_CREATE_TRACE_CHUNK_FAILED;
7ea24db3 4808 goto error;
d2956687
JG
4809 }
4810 /*
4811 * The consumer daemon has no ownership of the chunk output
4812 * directory.
4813 */
28ab034a 4814 chunk_status = lttng_trace_chunk_set_as_user(created_chunk, chunk_directory_handle);
cd9adb8b 4815 chunk_directory_handle = nullptr;
d2956687
JG
4816 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
4817 ERR("Failed to set trace chunk's directory handle");
4818 ret_code = LTTCOMM_CONSUMERD_CREATE_TRACE_CHUNK_FAILED;
7ea24db3 4819 goto error;
92816cc3
JG
4820 }
4821 }
4822
d2956687 4823 published_chunk = lttng_trace_chunk_registry_publish_chunk(
28ab034a 4824 the_consumer_data.chunk_registry, session_id, created_chunk);
d2956687 4825 lttng_trace_chunk_put(created_chunk);
cd9adb8b 4826 created_chunk = nullptr;
d2956687
JG
4827 if (!published_chunk) {
4828 ERR("Failed to publish trace chunk");
4829 ret_code = LTTCOMM_CONSUMERD_CREATE_TRACE_CHUNK_FAILED;
7ea24db3 4830 goto error;
d88744a4
JD
4831 }
4832
d2956687 4833 rcu_read_lock();
fa29bfbf 4834 cds_lfht_for_each_entry_duplicate(
28ab034a
JG
4835 the_consumer_data.channels_by_session_id_ht->ht,
4836 the_consumer_data.channels_by_session_id_ht->hash_fct(&session_id, lttng_ht_seed),
4837 the_consumer_data.channels_by_session_id_ht->match_fct,
4838 &session_id,
4839 &iter.iter,
4840 channel,
4841 channels_by_session_id_ht_node.node)
4842 {
4843 ret = lttng_consumer_channel_set_trace_chunk(channel, published_chunk);
d2956687
JG
4844 if (ret) {
4845 /*
4846 * Roll-back the creation of this chunk.
4847 *
4848 * This is important since the session daemon will
4849 * assume that the creation of this chunk failed and
4850 * will never ask for it to be closed, resulting
4851 * in a leak and an inconsistent state for some
4852 * channels.
4853 */
4854 enum lttcomm_return_code close_ret;
ecd1a12f 4855 char path[LTTNG_PATH_MAX];
d2956687
JG
4856
4857 DBG("Failed to set new trace chunk on existing channels, rolling back");
4858 close_ret = lttng_consumer_close_trace_chunk(relayd_id,
28ab034a
JG
4859 session_id,
4860 chunk_id,
4861 chunk_creation_timestamp,
cd9adb8b 4862 nullptr,
28ab034a 4863 path);
d2956687 4864 if (close_ret != LTTCOMM_CONSUMERD_SUCCESS) {
28ab034a
JG
4865 ERR("Failed to roll-back the creation of new chunk: session_id = %" PRIu64
4866 ", chunk_id = %" PRIu64,
4867 session_id,
4868 chunk_id);
d2956687 4869 }
a1ae2ea5 4870
d2956687
JG
4871 ret_code = LTTCOMM_CONSUMERD_CREATE_TRACE_CHUNK_FAILED;
4872 break;
4873 }
a1ae2ea5
JD
4874 }
4875
e5add6d0
JG
4876 if (relayd_id) {
4877 struct consumer_relayd_sock_pair *relayd;
4878
4879 relayd = consumer_find_relayd(*relayd_id);
4880 if (relayd) {
4881 pthread_mutex_lock(&relayd->ctrl_sock_mutex);
28ab034a 4882 ret = relayd_create_trace_chunk(&relayd->control_sock, published_chunk);
e5add6d0
JG
4883 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
4884 } else {
4885 ERR("Failed to find relay daemon socket: relayd_id = %" PRIu64, *relayd_id);
4886 }
4887
4888 if (!relayd || ret) {
4889 enum lttcomm_return_code close_ret;
ecd1a12f 4890 char path[LTTNG_PATH_MAX];
e5add6d0
JG
4891
4892 close_ret = lttng_consumer_close_trace_chunk(relayd_id,
28ab034a
JG
4893 session_id,
4894 chunk_id,
4895 chunk_creation_timestamp,
cd9adb8b 4896 nullptr,
28ab034a 4897 path);
e5add6d0 4898 if (close_ret != LTTCOMM_CONSUMERD_SUCCESS) {
28ab034a
JG
4899 ERR("Failed to roll-back the creation of new chunk: session_id = %" PRIu64
4900 ", chunk_id = %" PRIu64,
4901 session_id,
4902 chunk_id);
e5add6d0
JG
4903 }
4904
4905 ret_code = LTTCOMM_CONSUMERD_CREATE_TRACE_CHUNK_FAILED;
7ea24db3 4906 goto error_unlock;
e5add6d0
JG
4907 }
4908 }
7ea24db3 4909error_unlock:
e5add6d0 4910 rcu_read_unlock();
7ea24db3 4911error:
d2956687
JG
4912 /* Release the reference returned by the "publish" operation. */
4913 lttng_trace_chunk_put(published_chunk);
9bb5f1f8 4914 lttng_trace_chunk_put(created_chunk);
d2956687 4915 return ret_code;
a1ae2ea5
JD
4916}
4917
28ab034a
JG
4918enum lttcomm_return_code
4919lttng_consumer_close_trace_chunk(const uint64_t *relayd_id,
4920 uint64_t session_id,
4921 uint64_t chunk_id,
4922 time_t chunk_close_timestamp,
4923 const enum lttng_trace_chunk_command_type *close_command,
4924 char *path)
a1ae2ea5 4925{
d2956687
JG
4926 enum lttcomm_return_code ret_code = LTTCOMM_CONSUMERD_SUCCESS;
4927 struct lttng_trace_chunk *chunk;
4928 char relayd_id_buffer[MAX_INT_DEC_LEN(*relayd_id)];
4929 const char *relayd_id_str = "(none)";
bbc4768c 4930 const char *close_command_name = "none";
d2956687
JG
4931 struct lttng_ht_iter iter;
4932 struct lttng_consumer_channel *channel;
4933 enum lttng_trace_chunk_status chunk_status;
a1ae2ea5 4934
d2956687
JG
4935 if (relayd_id) {
4936 int ret;
4937
4938 /* Only used for logging purposes. */
28ab034a 4939 ret = snprintf(relayd_id_buffer, sizeof(relayd_id_buffer), "%" PRIu64, *relayd_id);
d2956687
JG
4940 if (ret > 0 && ret < sizeof(relayd_id_buffer)) {
4941 relayd_id_str = relayd_id_buffer;
4942 } else {
4943 relayd_id_str = "(formatting error)";
4944 }
bbc4768c
JG
4945 }
4946 if (close_command) {
28ab034a 4947 close_command_name = lttng_trace_chunk_command_type_get_name(*close_command);
bbc4768c 4948 }
d2956687
JG
4949
4950 DBG("Consumer close trace chunk command: relayd_id = %s"
28ab034a
JG
4951 ", session_id = %" PRIu64 ", chunk_id = %" PRIu64 ", close command = %s",
4952 relayd_id_str,
4953 session_id,
4954 chunk_id,
4955 close_command_name);
bbc4768c 4956
d2956687 4957 chunk = lttng_trace_chunk_registry_find_chunk(
28ab034a 4958 the_consumer_data.chunk_registry, session_id, chunk_id);
bbc4768c 4959 if (!chunk) {
28ab034a
JG
4960 ERR("Failed to find chunk: session_id = %" PRIu64 ", chunk_id = %" PRIu64,
4961 session_id,
4962 chunk_id);
d2956687 4963 ret_code = LTTCOMM_CONSUMERD_UNKNOWN_TRACE_CHUNK;
a1ae2ea5
JD
4964 goto end;
4965 }
4966
28ab034a 4967 chunk_status = lttng_trace_chunk_set_close_timestamp(chunk, chunk_close_timestamp);
d2956687
JG
4968 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
4969 ret_code = LTTCOMM_CONSUMERD_CLOSE_TRACE_CHUNK_FAILED;
4970 goto end;
45f1d9a1 4971 }
bbc4768c
JG
4972
4973 if (close_command) {
28ab034a 4974 chunk_status = lttng_trace_chunk_set_close_command(chunk, *close_command);
bbc4768c
JG
4975 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
4976 ret_code = LTTCOMM_CONSUMERD_CLOSE_TRACE_CHUNK_FAILED;
4977 goto end;
4978 }
4979 }
a1ae2ea5 4980
d2956687
JG
4981 /*
4982 * chunk is now invalid to access as we no longer hold a reference to
4983 * it; it is only kept around to compare it (by address) to the
4984 * current chunk found in the session's channels.
4985 */
4986 rcu_read_lock();
28ab034a 4987 cds_lfht_for_each_entry (the_consumer_data.channel_ht->ht, &iter.iter, channel, node.node) {
d2956687 4988 int ret;
a1ae2ea5 4989
d2956687
JG
4990 /*
4991 * Only change the channel's chunk to NULL if it still
4992 * references the chunk being closed. The channel may
4993 * reference a newer channel in the case of a session
4994 * rotation. When a session rotation occurs, the "next"
4995 * chunk is created before the "current" chunk is closed.
4996 */
4997 if (channel->trace_chunk != chunk) {
4998 continue;
4999 }
cd9adb8b 5000 ret = lttng_consumer_channel_set_trace_chunk(channel, nullptr);
d2956687
JG
5001 if (ret) {
5002 /*
5003 * Attempt to close the chunk on as many channels as
5004 * possible.
5005 */
5006 ret_code = LTTCOMM_CONSUMERD_CLOSE_TRACE_CHUNK_FAILED;
5007 }
a1ae2ea5 5008 }
bbc4768c
JG
5009
5010 if (relayd_id) {
5011 int ret;
5012 struct consumer_relayd_sock_pair *relayd;
5013
5014 relayd = consumer_find_relayd(*relayd_id);
5015 if (relayd) {
5016 pthread_mutex_lock(&relayd->ctrl_sock_mutex);
28ab034a 5017 ret = relayd_close_trace_chunk(&relayd->control_sock, chunk, path);
bbc4768c
JG
5018 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
5019 } else {
28ab034a 5020 ERR("Failed to find relay daemon socket: relayd_id = %" PRIu64, *relayd_id);
bbc4768c
JG
5021 }
5022
5023 if (!relayd || ret) {
5024 ret_code = LTTCOMM_CONSUMERD_CLOSE_TRACE_CHUNK_FAILED;
5025 goto error_unlock;
5026 }
5027 }
5028error_unlock:
d2956687
JG
5029 rcu_read_unlock();
5030end:
bbc4768c
JG
5031 /*
5032 * Release the reference returned by the "find" operation and
5033 * the session daemon's implicit reference to the chunk.
5034 */
5035 lttng_trace_chunk_put(chunk);
5036 lttng_trace_chunk_put(chunk);
5037
d2956687 5038 return ret_code;
a1ae2ea5 5039}
3654ed19 5040
28ab034a
JG
5041enum lttcomm_return_code
5042lttng_consumer_trace_chunk_exists(const uint64_t *relayd_id, uint64_t session_id, uint64_t chunk_id)
3654ed19 5043{
c35f9726 5044 int ret;
d2956687 5045 enum lttcomm_return_code ret_code;
d2956687
JG
5046 char relayd_id_buffer[MAX_INT_DEC_LEN(*relayd_id)];
5047 const char *relayd_id_str = "(none)";
c35f9726 5048 const bool is_local_trace = !relayd_id;
cd9adb8b 5049 struct consumer_relayd_sock_pair *relayd = nullptr;
6b584c2e 5050 bool chunk_exists_local, chunk_exists_remote;
d2956687
JG
5051
5052 if (relayd_id) {
d2956687 5053 /* Only used for logging purposes. */
28ab034a 5054 ret = snprintf(relayd_id_buffer, sizeof(relayd_id_buffer), "%" PRIu64, *relayd_id);
d2956687
JG
5055 if (ret > 0 && ret < sizeof(relayd_id_buffer)) {
5056 relayd_id_str = relayd_id_buffer;
5057 } else {
5058 relayd_id_str = "(formatting error)";
5059 }
d01ef216 5060 }
d2956687
JG
5061
5062 DBG("Consumer trace chunk exists command: relayd_id = %s"
28ab034a
JG
5063 ", chunk_id = %" PRIu64,
5064 relayd_id_str,
5065 chunk_id);
6b584c2e 5066 ret = lttng_trace_chunk_registry_chunk_exists(
28ab034a 5067 the_consumer_data.chunk_registry, session_id, chunk_id, &chunk_exists_local);
6b584c2e
JG
5068 if (ret) {
5069 /* Internal error. */
5070 ERR("Failed to query the existence of a trace chunk");
5071 ret_code = LTTCOMM_CONSUMERD_FATAL;
13e3b280 5072 goto end;
6b584c2e 5073 }
28ab034a 5074 DBG("Trace chunk %s locally", chunk_exists_local ? "exists" : "does not exist");
6b584c2e 5075 if (chunk_exists_local) {
c35f9726 5076 ret_code = LTTCOMM_CONSUMERD_TRACE_CHUNK_EXISTS_LOCAL;
c35f9726
JG
5077 goto end;
5078 } else if (is_local_trace) {
5079 ret_code = LTTCOMM_CONSUMERD_UNKNOWN_TRACE_CHUNK;
5080 goto end;
5081 }
5082
5083 rcu_read_lock();
5084 relayd = consumer_find_relayd(*relayd_id);
5085 if (!relayd) {
5086 ERR("Failed to find relayd %" PRIu64, *relayd_id);
5087 ret_code = LTTCOMM_CONSUMERD_INVALID_PARAMETERS;
5088 goto end_rcu_unlock;
5089 }
5090 DBG("Looking up existence of trace chunk on relay daemon");
5091 pthread_mutex_lock(&relayd->ctrl_sock_mutex);
28ab034a 5092 ret = relayd_trace_chunk_exists(&relayd->control_sock, chunk_id, &chunk_exists_remote);
c35f9726
JG
5093 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
5094 if (ret < 0) {
5095 ERR("Failed to look-up the existence of trace chunk on relay daemon");
5096 ret_code = LTTCOMM_CONSUMERD_RELAYD_FAIL;
5097 goto end_rcu_unlock;
5098 }
5099
28ab034a
JG
5100 ret_code = chunk_exists_remote ? LTTCOMM_CONSUMERD_TRACE_CHUNK_EXISTS_REMOTE :
5101 LTTCOMM_CONSUMERD_UNKNOWN_TRACE_CHUNK;
5102 DBG("Trace chunk %s on relay daemon", chunk_exists_remote ? "exists" : "does not exist");
d2956687 5103
c35f9726
JG
5104end_rcu_unlock:
5105 rcu_read_unlock();
5106end:
d2956687 5107 return ret_code;
3654ed19 5108}
5f3aff8b 5109
28ab034a 5110static int consumer_clear_monitored_channel(struct lttng_consumer_channel *channel)
5f3aff8b
MD
5111{
5112 struct lttng_ht *ht;
5113 struct lttng_consumer_stream *stream;
5114 struct lttng_ht_iter iter;
5115 int ret;
5116
fa29bfbf 5117 ht = the_consumer_data.stream_per_chan_id_ht;
5f3aff8b
MD
5118
5119 rcu_read_lock();
5120 cds_lfht_for_each_entry_duplicate(ht->ht,
28ab034a
JG
5121 ht->hash_fct(&channel->key, lttng_ht_seed),
5122 ht->match_fct,
5123 &channel->key,
5124 &iter.iter,
5125 stream,
5126 node_channel_id.node)
5127 {
5f3aff8b
MD
5128 /*
5129 * Protect against teardown with mutex.
5130 */
5131 pthread_mutex_lock(&stream->lock);
5132 if (cds_lfht_is_node_deleted(&stream->node.node)) {
5133 goto next;
5134 }
5135 ret = consumer_clear_stream(stream);
5136 if (ret) {
5137 goto error_unlock;
5138 }
5139 next:
5140 pthread_mutex_unlock(&stream->lock);
5141 }
5142 rcu_read_unlock();
5143 return LTTCOMM_CONSUMERD_SUCCESS;
5144
5145error_unlock:
5146 pthread_mutex_unlock(&stream->lock);
5147 rcu_read_unlock();
5148 return ret;
5149}
5150
5151int lttng_consumer_clear_channel(struct lttng_consumer_channel *channel)
5152{
5153 int ret;
5154
5155 DBG("Consumer clear channel %" PRIu64, channel->key);
5156
5157 if (channel->type == CONSUMER_CHANNEL_TYPE_METADATA) {
5158 /*
5159 * Nothing to do for the metadata channel/stream.
5160 * Snapshot mechanism already take care of the metadata
5161 * handling/generation, and monitored channels only need to
5162 * have their data stream cleared..
5163 */
5164 ret = LTTCOMM_CONSUMERD_SUCCESS;
5165 goto end;
5166 }
5167
5168 if (!channel->monitor) {
5169 ret = consumer_clear_unmonitored_channel(channel);
5170 } else {
5171 ret = consumer_clear_monitored_channel(channel);
5172 }
5173end:
5174 return ret;
5175}
04ed9e10 5176
28ab034a 5177enum lttcomm_return_code lttng_consumer_open_channel_packets(struct lttng_consumer_channel *channel)
04ed9e10
JG
5178{
5179 struct lttng_consumer_stream *stream;
5180 enum lttcomm_return_code ret = LTTCOMM_CONSUMERD_SUCCESS;
5181
5182 if (channel->metadata_stream) {
5183 ERR("Open channel packets command attempted on a metadata channel");
5184 ret = LTTCOMM_CONSUMERD_INVALID_PARAMETERS;
5185 goto end;
5186 }
5187
5188 rcu_read_lock();
28ab034a 5189 cds_list_for_each_entry (stream, &channel->streams.head, send_node) {
503fefca 5190 enum consumer_stream_open_packet_status status;
04ed9e10
JG
5191
5192 pthread_mutex_lock(&stream->lock);
5193 if (cds_lfht_is_node_deleted(&stream->node.node)) {
5194 goto next;
5195 }
5196
503fefca 5197 status = consumer_stream_open_packet(stream);
04ed9e10 5198 switch (status) {
503fefca 5199 case CONSUMER_STREAM_OPEN_PACKET_STATUS_OPENED:
04ed9e10 5200 DBG("Opened a packet in \"open channel packets\" command: stream id = %" PRIu64
28ab034a
JG
5201 ", channel name = %s, session id = %" PRIu64,
5202 stream->key,
5203 stream->chan->name,
5204 stream->chan->session_id);
04ed9e10
JG
5205 stream->opened_packet_in_current_trace_chunk = true;
5206 break;
503fefca 5207 case CONSUMER_STREAM_OPEN_PACKET_STATUS_NO_SPACE:
04ed9e10 5208 DBG("No space left to open a packet in \"open channel packets\" command: stream id = %" PRIu64
28ab034a
JG
5209 ", channel name = %s, session id = %" PRIu64,
5210 stream->key,
5211 stream->chan->name,
5212 stream->chan->session_id);
04ed9e10 5213 break;
503fefca 5214 case CONSUMER_STREAM_OPEN_PACKET_STATUS_ERROR:
04ed9e10
JG
5215 /*
5216 * Only unexpected internal errors can lead to this
5217 * failing. Report an unknown error.
5218 */
5219 ERR("Failed to flush empty buffer in \"open channel packets\" command: stream id = %" PRIu64
28ab034a
JG
5220 ", channel id = %" PRIu64 ", channel name = %s"
5221 ", session id = %" PRIu64,
5222 stream->key,
5223 channel->key,
5224 channel->name,
5225 channel->session_id);
04ed9e10
JG
5226 ret = LTTCOMM_CONSUMERD_UNKNOWN_ERROR;
5227 goto error_unlock;
5228 default:
5229 abort();
5230 }
5231
5232 next:
5233 pthread_mutex_unlock(&stream->lock);
5234 }
5235
5236end_rcu_unlock:
5237 rcu_read_unlock();
5238end:
5239 return ret;
5240
5241error_unlock:
5242 pthread_mutex_unlock(&stream->lock);
5243 goto end_rcu_unlock;
5244}
881fc67f
MD
5245
5246void lttng_consumer_sigbus_handle(void *addr)
5247{
5248 lttng_ustconsumer_sigbus_handle(addr);
5249}
This page took 0.440834 seconds and 4 git commands to generate.