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