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