Fix: release reference to created chunk if it can't be published
[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{
1017 int ret = 0;
1018 const bool is_local_trace = channel->relayd_id == -1ULL;
1019 bool update_stream_trace_chunk;
1020 struct cds_lfht_iter iter;
1021 struct lttng_consumer_stream *stream;
1022 unsigned long channel_hash;
1023
1024 pthread_mutex_lock(&channel->lock);
b6921a17
JG
1025 if (channel->is_deleted) {
1026 /*
1027 * The channel has been logically deleted and should no longer
1028 * be used. It has released its reference to its current trace
1029 * chunk and should not acquire a new one.
1030 *
1031 * Return success as there is nothing for the caller to do.
1032 */
1033 goto end;
1034 }
d2956687
JG
1035 /*
1036 * A stream can transition to a state where it and its channel
1037 * no longer belong to a trace chunk. For instance, this happens when
1038 * a session is rotated while it is inactive. After the rotation
1039 * of an inactive session completes, the channel and its streams no
1040 * longer belong to a trace chunk.
1041 *
1042 * However, if a session is stopped, rotated, and started again,
1043 * the session daemon will create a new chunk and send it to its peers.
1044 * In that case, the streams' transition to a new chunk can be performed
1045 * immediately.
1046 *
1047 * This trace chunk transition could also be performed lazily when
1048 * a buffer is consumed. However, creating the files here allows the
1049 * consumer daemon to report any creation error to the session daemon
1050 * and cause the start of the tracing session to fail.
1051 */
1052 update_stream_trace_chunk = !channel->trace_chunk && new_trace_chunk;
1053
1054 /*
1055 * The acquisition of the reference cannot fail (barring
1056 * a severe internal error) since a reference to the published
1057 * chunk is already held by the caller.
1058 */
1059 if (new_trace_chunk) {
1060 const bool acquired_reference = lttng_trace_chunk_get(
1061 new_trace_chunk);
1062
1063 assert(acquired_reference);
1064 }
1065
1066 lttng_trace_chunk_put(channel->trace_chunk);
1067 channel->trace_chunk = new_trace_chunk;
1068 if (!is_local_trace || !new_trace_chunk) {
1069 /* Not an error. */
1070 goto end;
1071 }
1072
1073 if (!update_stream_trace_chunk) {
1074 goto end;
1075 }
1076
1077 channel_hash = consumer_data.stream_per_chan_id_ht->hash_fct(
1078 &channel->key, lttng_ht_seed);
1079 rcu_read_lock();
1080 cds_lfht_for_each_entry_duplicate(consumer_data.stream_per_chan_id_ht->ht,
1081 channel_hash,
1082 consumer_data.stream_per_chan_id_ht->match_fct,
1083 &channel->key, &iter, stream, node_channel_id.node) {
1084 bool acquired_reference, should_regenerate_metadata = false;
1085
1086 acquired_reference = lttng_trace_chunk_get(channel->trace_chunk);
1087 assert(acquired_reference);
1088
1089 pthread_mutex_lock(&stream->lock);
1090
1091 /*
1092 * On a transition from "no-chunk" to a new chunk, a metadata
1093 * stream's content must be entirely dumped. This must occcur
1094 * _after_ the creation of the metadata stream's output files
1095 * as the consumption thread (not necessarily the one executing
1096 * this) may start to consume during the call to
1097 * consumer_metadata_stream_dump().
1098 */
1099 should_regenerate_metadata =
1100 stream->metadata_flag &&
1101 !stream->trace_chunk && channel->trace_chunk;
1102 stream->trace_chunk = channel->trace_chunk;
1103 ret = consumer_stream_create_output_files(stream, true);
1104 if (ret) {
1105 pthread_mutex_unlock(&stream->lock);
1106 goto end_rcu_unlock;
1107 }
1108 if (should_regenerate_metadata) {
1109 ret = consumer_metadata_stream_dump(stream);
1110 }
1111 pthread_mutex_unlock(&stream->lock);
1112 if (ret) {
1113 goto end_rcu_unlock;
1114 }
1115 }
1116end_rcu_unlock:
1117 rcu_read_unlock();
1118end:
1119 pthread_mutex_unlock(&channel->lock);
1120 return ret;
1121}
1122
3bd1e081 1123/*
ffe60014
DG
1124 * Allocate and return a new lttng_consumer_channel object using the given key
1125 * to initialize the hash table node.
1126 *
1127 * On error, return NULL.
3bd1e081 1128 */
886224ff 1129struct lttng_consumer_channel *consumer_allocate_channel(uint64_t key,
ffe60014 1130 uint64_t session_id,
d2956687 1131 const uint64_t *chunk_id,
ffe60014
DG
1132 const char *pathname,
1133 const char *name,
57a269f2 1134 uint64_t relayd_id,
1624d5b7
JD
1135 enum lttng_event_output output,
1136 uint64_t tracefile_size,
2bba9e53 1137 uint64_t tracefile_count,
1950109e 1138 uint64_t session_id_per_pid,
ecc48a90 1139 unsigned int monitor,
d7ba1388 1140 unsigned int live_timer_interval,
3d071855 1141 const char *root_shm_path,
d7ba1388 1142 const char *shm_path)
3bd1e081 1143{
d2956687
JG
1144 struct lttng_consumer_channel *channel = NULL;
1145 struct lttng_trace_chunk *trace_chunk = NULL;
1146
1147 if (chunk_id) {
1148 trace_chunk = lttng_trace_chunk_registry_find_chunk(
1149 consumer_data.chunk_registry, session_id,
1150 *chunk_id);
1151 if (!trace_chunk) {
1152 ERR("Failed to find trace chunk reference during creation of channel");
1153 goto end;
1154 }
1155 }
3bd1e081 1156
276b26d1 1157 channel = zmalloc(sizeof(*channel));
3bd1e081 1158 if (channel == NULL) {
7a57cf92 1159 PERROR("malloc struct lttng_consumer_channel");
3bd1e081
MD
1160 goto end;
1161 }
ffe60014
DG
1162
1163 channel->key = key;
3bd1e081 1164 channel->refcount = 0;
ffe60014 1165 channel->session_id = session_id;
1950109e 1166 channel->session_id_per_pid = session_id_per_pid;
ffe60014 1167 channel->relayd_id = relayd_id;
1624d5b7
JD
1168 channel->tracefile_size = tracefile_size;
1169 channel->tracefile_count = tracefile_count;
2bba9e53 1170 channel->monitor = monitor;
ecc48a90 1171 channel->live_timer_interval = live_timer_interval;
a9838785 1172 pthread_mutex_init(&channel->lock, NULL);
ec6ea7d0 1173 pthread_mutex_init(&channel->timer_lock, NULL);
ffe60014 1174
0c759fc9
DG
1175 switch (output) {
1176 case LTTNG_EVENT_SPLICE:
1177 channel->output = CONSUMER_CHANNEL_SPLICE;
1178 break;
1179 case LTTNG_EVENT_MMAP:
1180 channel->output = CONSUMER_CHANNEL_MMAP;
1181 break;
1182 default:
1183 assert(0);
1184 free(channel);
1185 channel = NULL;
1186 goto end;
1187 }
1188
07b86b52
JD
1189 /*
1190 * In monitor mode, the streams associated with the channel will be put in
1191 * a special list ONLY owned by this channel. So, the refcount is set to 1
1192 * here meaning that the channel itself has streams that are referenced.
1193 *
1194 * On a channel deletion, once the channel is no longer visible, the
1195 * refcount is decremented and checked for a zero value to delete it. With
1196 * streams in no monitor mode, it will now be safe to destroy the channel.
1197 */
1198 if (!channel->monitor) {
1199 channel->refcount = 1;
1200 }
1201
ffe60014
DG
1202 strncpy(channel->pathname, pathname, sizeof(channel->pathname));
1203 channel->pathname[sizeof(channel->pathname) - 1] = '\0';
1204
1205 strncpy(channel->name, name, sizeof(channel->name));
1206 channel->name[sizeof(channel->name) - 1] = '\0';
1207
3d071855
MD
1208 if (root_shm_path) {
1209 strncpy(channel->root_shm_path, root_shm_path, sizeof(channel->root_shm_path));
1210 channel->root_shm_path[sizeof(channel->root_shm_path) - 1] = '\0';
1211 }
d7ba1388
MD
1212 if (shm_path) {
1213 strncpy(channel->shm_path, shm_path, sizeof(channel->shm_path));
1214 channel->shm_path[sizeof(channel->shm_path) - 1] = '\0';
1215 }
1216
d88aee68 1217 lttng_ht_node_init_u64(&channel->node, channel->key);
5c3892a6
JG
1218 lttng_ht_node_init_u64(&channel->channels_by_session_id_ht_node,
1219 channel->session_id);
d8ef542d
MD
1220
1221 channel->wait_fd = -1;
ffe60014
DG
1222 CDS_INIT_LIST_HEAD(&channel->streams.head);
1223
d2956687
JG
1224 if (trace_chunk) {
1225 int ret = lttng_consumer_channel_set_trace_chunk(channel,
1226 trace_chunk);
1227 if (ret) {
1228 goto error;
1229 }
1230 }
1231
62a7b8ed 1232 DBG("Allocated channel (key %" PRIu64 ")", channel->key);
3bd1e081 1233
3bd1e081 1234end:
d2956687 1235 lttng_trace_chunk_put(trace_chunk);
3bd1e081 1236 return channel;
d2956687
JG
1237error:
1238 consumer_del_channel(channel);
1239 channel = NULL;
1240 goto end;
3bd1e081
MD
1241}
1242
1243/*
1244 * Add a channel to the global list protected by a mutex.
821fffb2 1245 *
b5a6470f 1246 * Always return 0 indicating success.
3bd1e081 1247 */
d8ef542d
MD
1248int consumer_add_channel(struct lttng_consumer_channel *channel,
1249 struct lttng_consumer_local_data *ctx)
3bd1e081 1250{
3bd1e081 1251 pthread_mutex_lock(&consumer_data.lock);
a9838785 1252 pthread_mutex_lock(&channel->lock);
ec6ea7d0 1253 pthread_mutex_lock(&channel->timer_lock);
c77fc10a 1254
b5a6470f
DG
1255 /*
1256 * This gives us a guarantee that the channel we are about to add to the
1257 * channel hash table will be unique. See this function comment on the why
1258 * we need to steel the channel key at this stage.
1259 */
1260 steal_channel_key(channel->key);
c77fc10a 1261
b5a6470f 1262 rcu_read_lock();
d88aee68 1263 lttng_ht_add_unique_u64(consumer_data.channel_ht, &channel->node);
5c3892a6
JG
1264 lttng_ht_add_u64(consumer_data.channels_by_session_id_ht,
1265 &channel->channels_by_session_id_ht_node);
6065ceec 1266 rcu_read_unlock();
d2956687 1267 channel->is_published = true;
b5a6470f 1268
ec6ea7d0 1269 pthread_mutex_unlock(&channel->timer_lock);
a9838785 1270 pthread_mutex_unlock(&channel->lock);
3bd1e081 1271 pthread_mutex_unlock(&consumer_data.lock);
702b1ea4 1272
b5a6470f 1273 if (channel->wait_fd != -1 && channel->type == CONSUMER_CHANNEL_TYPE_DATA) {
a0cbdd2e 1274 notify_channel_pipe(ctx, channel, -1, CONSUMER_CHANNEL_ADD);
d8ef542d 1275 }
b5a6470f
DG
1276
1277 return 0;
3bd1e081
MD
1278}
1279
1280/*
1281 * Allocate the pollfd structure and the local view of the out fds to avoid
1282 * doing a lookup in the linked list and concurrency issues when writing is
1283 * needed. Called with consumer_data.lock held.
1284 *
1285 * Returns the number of fds in the structures.
1286 */
ffe60014
DG
1287static int update_poll_array(struct lttng_consumer_local_data *ctx,
1288 struct pollfd **pollfd, struct lttng_consumer_stream **local_stream,
9a2fcf78 1289 struct lttng_ht *ht, int *nb_inactive_fd)
3bd1e081 1290{
3bd1e081 1291 int i = 0;
e4421fec
DG
1292 struct lttng_ht_iter iter;
1293 struct lttng_consumer_stream *stream;
3bd1e081 1294
ffe60014
DG
1295 assert(ctx);
1296 assert(ht);
1297 assert(pollfd);
1298 assert(local_stream);
1299
3bd1e081 1300 DBG("Updating poll fd array");
9a2fcf78 1301 *nb_inactive_fd = 0;
481d6c57 1302 rcu_read_lock();
43c34bc3 1303 cds_lfht_for_each_entry(ht->ht, &iter.iter, stream, node.node) {
8994307f
DG
1304 /*
1305 * Only active streams with an active end point can be added to the
1306 * poll set and local stream storage of the thread.
1307 *
1308 * There is a potential race here for endpoint_status to be updated
1309 * just after the check. However, this is OK since the stream(s) will
1310 * be deleted once the thread is notified that the end point state has
1311 * changed where this function will be called back again.
9a2fcf78
JD
1312 *
1313 * We track the number of inactive FDs because they still need to be
1314 * closed by the polling thread after a wakeup on the data_pipe or
1315 * metadata_pipe.
8994307f 1316 */
d2956687 1317 if (stream->endpoint_status == CONSUMER_ENDPOINT_INACTIVE) {
9a2fcf78 1318 (*nb_inactive_fd)++;
3bd1e081
MD
1319 continue;
1320 }
7972aab2
DG
1321 /*
1322 * This clobbers way too much the debug output. Uncomment that if you
1323 * need it for debugging purposes.
7972aab2 1324 */
e4421fec 1325 (*pollfd)[i].fd = stream->wait_fd;
3bd1e081 1326 (*pollfd)[i].events = POLLIN | POLLPRI;
e4421fec 1327 local_stream[i] = stream;
3bd1e081
MD
1328 i++;
1329 }
481d6c57 1330 rcu_read_unlock();
3bd1e081
MD
1331
1332 /*
50f8ae69 1333 * Insert the consumer_data_pipe at the end of the array and don't
3bd1e081
MD
1334 * increment i so nb_fd is the number of real FD.
1335 */
acdb9057 1336 (*pollfd)[i].fd = lttng_pipe_get_readfd(ctx->consumer_data_pipe);
509bb1cf 1337 (*pollfd)[i].events = POLLIN | POLLPRI;
02b3d176
DG
1338
1339 (*pollfd)[i + 1].fd = lttng_pipe_get_readfd(ctx->consumer_wakeup_pipe);
1340 (*pollfd)[i + 1].events = POLLIN | POLLPRI;
3bd1e081
MD
1341 return i;
1342}
1343
1344/*
84382d49
MD
1345 * Poll on the should_quit pipe and the command socket return -1 on
1346 * error, 1 if should exit, 0 if data is available on the command socket
3bd1e081
MD
1347 */
1348int lttng_consumer_poll_socket(struct pollfd *consumer_sockpoll)
1349{
1350 int num_rdy;
1351
88f2b785 1352restart:
3bd1e081
MD
1353 num_rdy = poll(consumer_sockpoll, 2, -1);
1354 if (num_rdy == -1) {
88f2b785
MD
1355 /*
1356 * Restart interrupted system call.
1357 */
1358 if (errno == EINTR) {
1359 goto restart;
1360 }
7a57cf92 1361 PERROR("Poll error");
84382d49 1362 return -1;
3bd1e081 1363 }
509bb1cf 1364 if (consumer_sockpoll[0].revents & (POLLIN | POLLPRI)) {
3bd1e081 1365 DBG("consumer_should_quit wake up");
84382d49 1366 return 1;
3bd1e081
MD
1367 }
1368 return 0;
3bd1e081
MD
1369}
1370
1371/*
1372 * Set the error socket.
1373 */
ffe60014
DG
1374void lttng_consumer_set_error_sock(struct lttng_consumer_local_data *ctx,
1375 int sock)
3bd1e081
MD
1376{
1377 ctx->consumer_error_socket = sock;
1378}
1379
1380/*
1381 * Set the command socket path.
1382 */
3bd1e081
MD
1383void lttng_consumer_set_command_sock_path(
1384 struct lttng_consumer_local_data *ctx, char *sock)
1385{
1386 ctx->consumer_command_sock_path = sock;
1387}
1388
1389/*
1390 * Send return code to the session daemon.
1391 * If the socket is not defined, we return 0, it is not a fatal error
1392 */
ffe60014 1393int lttng_consumer_send_error(struct lttng_consumer_local_data *ctx, int cmd)
3bd1e081
MD
1394{
1395 if (ctx->consumer_error_socket > 0) {
1396 return lttcomm_send_unix_sock(ctx->consumer_error_socket, &cmd,
1397 sizeof(enum lttcomm_sessiond_command));
1398 }
1399
1400 return 0;
1401}
1402
1403/*
228b5bf7
DG
1404 * Close all the tracefiles and stream fds and MUST be called when all
1405 * instances are destroyed i.e. when all threads were joined and are ended.
3bd1e081
MD
1406 */
1407void lttng_consumer_cleanup(void)
1408{
e4421fec 1409 struct lttng_ht_iter iter;
ffe60014 1410 struct lttng_consumer_channel *channel;
e10aec8f 1411 unsigned int trace_chunks_left;
6065ceec
DG
1412
1413 rcu_read_lock();
3bd1e081 1414
ffe60014
DG
1415 cds_lfht_for_each_entry(consumer_data.channel_ht->ht, &iter.iter, channel,
1416 node.node) {
702b1ea4 1417 consumer_del_channel(channel);
3bd1e081 1418 }
6065ceec
DG
1419
1420 rcu_read_unlock();
d6ce1df2 1421
d6ce1df2 1422 lttng_ht_destroy(consumer_data.channel_ht);
5c3892a6 1423 lttng_ht_destroy(consumer_data.channels_by_session_id_ht);
228b5bf7
DG
1424
1425 cleanup_relayd_ht();
1426
d8ef542d
MD
1427 lttng_ht_destroy(consumer_data.stream_per_chan_id_ht);
1428
228b5bf7
DG
1429 /*
1430 * This HT contains streams that are freed by either the metadata thread or
1431 * the data thread so we do *nothing* on the hash table and simply destroy
1432 * it.
1433 */
1434 lttng_ht_destroy(consumer_data.stream_list_ht);
28cc88f3 1435
e10aec8f
MD
1436 /*
1437 * Trace chunks in the registry may still exist if the session
1438 * daemon has encountered an internal error and could not
1439 * tear down its sessions and/or trace chunks properly.
1440 *
1441 * Release the session daemon's implicit reference to any remaining
1442 * trace chunk and print an error if any trace chunk was found. Note
1443 * that there are _no_ legitimate cases for trace chunks to be left,
1444 * it is a leak. However, it can happen following a crash of the
1445 * session daemon and not emptying the registry would cause an assertion
1446 * to hit.
1447 */
1448 trace_chunks_left = lttng_trace_chunk_registry_put_each_chunk(
1449 consumer_data.chunk_registry);
1450 if (trace_chunks_left) {
1451 ERR("%u trace chunks are leaked by lttng-consumerd. "
1452 "This can be caused by an internal error of the session daemon.",
1453 trace_chunks_left);
1454 }
1455 /* Run all callbacks freeing each chunk. */
1456 rcu_barrier();
28cc88f3 1457 lttng_trace_chunk_registry_destroy(consumer_data.chunk_registry);
3bd1e081
MD
1458}
1459
1460/*
1461 * Called from signal handler.
1462 */
1463void lttng_consumer_should_exit(struct lttng_consumer_local_data *ctx)
1464{
6cd525e8
MD
1465 ssize_t ret;
1466
10211f5c 1467 CMM_STORE_SHARED(consumer_quit, 1);
6cd525e8
MD
1468 ret = lttng_write(ctx->consumer_should_quit[1], "4", 1);
1469 if (ret < 1) {
7a57cf92 1470 PERROR("write consumer quit");
3bd1e081 1471 }
ab1027f4
DG
1472
1473 DBG("Consumer flag that it should quit");
3bd1e081
MD
1474}
1475
5199ffc4
JG
1476
1477/*
1478 * Flush pending writes to trace output disk file.
1479 */
1480static
00e2e675
DG
1481void lttng_consumer_sync_trace_file(struct lttng_consumer_stream *stream,
1482 off_t orig_offset)
3bd1e081 1483{
c7a78aab 1484 int ret;
3bd1e081
MD
1485 int outfd = stream->out_fd;
1486
1487 /*
1488 * This does a blocking write-and-wait on any page that belongs to the
1489 * subbuffer prior to the one we just wrote.
1490 * Don't care about error values, as these are just hints and ways to
1491 * limit the amount of page cache used.
1492 */
ffe60014 1493 if (orig_offset < stream->max_sb_size) {
3bd1e081
MD
1494 return;
1495 }
ffe60014
DG
1496 lttng_sync_file_range(outfd, orig_offset - stream->max_sb_size,
1497 stream->max_sb_size,
3bd1e081
MD
1498 SYNC_FILE_RANGE_WAIT_BEFORE
1499 | SYNC_FILE_RANGE_WRITE
1500 | SYNC_FILE_RANGE_WAIT_AFTER);
1501 /*
1502 * Give hints to the kernel about how we access the file:
1503 * POSIX_FADV_DONTNEED : we won't re-access data in a near future after
1504 * we write it.
1505 *
1506 * We need to call fadvise again after the file grows because the
1507 * kernel does not seem to apply fadvise to non-existing parts of the
1508 * file.
1509 *
1510 * Call fadvise _after_ having waited for the page writeback to
1511 * complete because the dirty page writeback semantic is not well
1512 * defined. So it can be expected to lead to lower throughput in
1513 * streaming.
1514 */
c7a78aab 1515 ret = posix_fadvise(outfd, orig_offset - stream->max_sb_size,
ffe60014 1516 stream->max_sb_size, POSIX_FADV_DONTNEED);
a0d0e127 1517 if (ret && ret != -ENOSYS) {
a74a5f4a
JG
1518 errno = ret;
1519 PERROR("posix_fadvise on fd %i", outfd);
c7a78aab 1520 }
3bd1e081
MD
1521}
1522
1523/*
1524 * Initialise the necessary environnement :
1525 * - create a new context
1526 * - create the poll_pipe
1527 * - create the should_quit pipe (for signal handler)
1528 * - create the thread pipe (for splice)
1529 *
1530 * Takes a function pointer as argument, this function is called when data is
1531 * available on a buffer. This function is responsible to do the
1532 * kernctl_get_next_subbuf, read the data with mmap or splice depending on the
1533 * buffer configuration and then kernctl_put_next_subbuf at the end.
1534 *
1535 * Returns a pointer to the new context or NULL on error.
1536 */
1537struct lttng_consumer_local_data *lttng_consumer_create(
1538 enum lttng_consumer_type type,
4078b776 1539 ssize_t (*buffer_ready)(struct lttng_consumer_stream *stream,
d41f73b7 1540 struct lttng_consumer_local_data *ctx),
3bd1e081
MD
1541 int (*recv_channel)(struct lttng_consumer_channel *channel),
1542 int (*recv_stream)(struct lttng_consumer_stream *stream),
30319bcb 1543 int (*update_stream)(uint64_t stream_key, uint32_t state))
3bd1e081 1544{
d8ef542d 1545 int ret;
3bd1e081
MD
1546 struct lttng_consumer_local_data *ctx;
1547
1548 assert(consumer_data.type == LTTNG_CONSUMER_UNKNOWN ||
1549 consumer_data.type == type);
1550 consumer_data.type = type;
1551
effcf122 1552 ctx = zmalloc(sizeof(struct lttng_consumer_local_data));
3bd1e081 1553 if (ctx == NULL) {
7a57cf92 1554 PERROR("allocating context");
3bd1e081
MD
1555 goto error;
1556 }
1557
1558 ctx->consumer_error_socket = -1;
331744e3 1559 ctx->consumer_metadata_socket = -1;
75d83e50 1560 pthread_mutex_init(&ctx->metadata_socket_lock, NULL);
3bd1e081
MD
1561 /* assign the callbacks */
1562 ctx->on_buffer_ready = buffer_ready;
1563 ctx->on_recv_channel = recv_channel;
1564 ctx->on_recv_stream = recv_stream;
1565 ctx->on_update_stream = update_stream;
1566
acdb9057
DG
1567 ctx->consumer_data_pipe = lttng_pipe_open(0);
1568 if (!ctx->consumer_data_pipe) {
3bd1e081
MD
1569 goto error_poll_pipe;
1570 }
1571
02b3d176
DG
1572 ctx->consumer_wakeup_pipe = lttng_pipe_open(0);
1573 if (!ctx->consumer_wakeup_pipe) {
1574 goto error_wakeup_pipe;
1575 }
1576
3bd1e081
MD
1577 ret = pipe(ctx->consumer_should_quit);
1578 if (ret < 0) {
7a57cf92 1579 PERROR("Error creating recv pipe");
3bd1e081
MD
1580 goto error_quit_pipe;
1581 }
1582
d8ef542d
MD
1583 ret = pipe(ctx->consumer_channel_pipe);
1584 if (ret < 0) {
1585 PERROR("Error creating channel pipe");
1586 goto error_channel_pipe;
1587 }
1588
13886d2d
DG
1589 ctx->consumer_metadata_pipe = lttng_pipe_open(0);
1590 if (!ctx->consumer_metadata_pipe) {
fb3a43a9
DG
1591 goto error_metadata_pipe;
1592 }
3bd1e081 1593
e9404c27
JG
1594 ctx->channel_monitor_pipe = -1;
1595
fb3a43a9 1596 return ctx;
3bd1e081 1597
fb3a43a9 1598error_metadata_pipe:
d8ef542d
MD
1599 utils_close_pipe(ctx->consumer_channel_pipe);
1600error_channel_pipe:
d8ef542d 1601 utils_close_pipe(ctx->consumer_should_quit);
3bd1e081 1602error_quit_pipe:
02b3d176
DG
1603 lttng_pipe_destroy(ctx->consumer_wakeup_pipe);
1604error_wakeup_pipe:
acdb9057 1605 lttng_pipe_destroy(ctx->consumer_data_pipe);
3bd1e081
MD
1606error_poll_pipe:
1607 free(ctx);
1608error:
1609 return NULL;
1610}
1611
282dadbc
MD
1612/*
1613 * Iterate over all streams of the hashtable and free them properly.
1614 */
1615static void destroy_data_stream_ht(struct lttng_ht *ht)
1616{
1617 struct lttng_ht_iter iter;
1618 struct lttng_consumer_stream *stream;
1619
1620 if (ht == NULL) {
1621 return;
1622 }
1623
1624 rcu_read_lock();
1625 cds_lfht_for_each_entry(ht->ht, &iter.iter, stream, node.node) {
1626 /*
1627 * Ignore return value since we are currently cleaning up so any error
1628 * can't be handled.
1629 */
1630 (void) consumer_del_stream(stream, ht);
1631 }
1632 rcu_read_unlock();
1633
1634 lttng_ht_destroy(ht);
1635}
1636
1637/*
1638 * Iterate over all streams of the metadata hashtable and free them
1639 * properly.
1640 */
1641static void destroy_metadata_stream_ht(struct lttng_ht *ht)
1642{
1643 struct lttng_ht_iter iter;
1644 struct lttng_consumer_stream *stream;
1645
1646 if (ht == NULL) {
1647 return;
1648 }
1649
1650 rcu_read_lock();
1651 cds_lfht_for_each_entry(ht->ht, &iter.iter, stream, node.node) {
1652 /*
1653 * Ignore return value since we are currently cleaning up so any error
1654 * can't be handled.
1655 */
1656 (void) consumer_del_metadata_stream(stream, ht);
1657 }
1658 rcu_read_unlock();
1659
1660 lttng_ht_destroy(ht);
1661}
1662
3bd1e081
MD
1663/*
1664 * Close all fds associated with the instance and free the context.
1665 */
1666void lttng_consumer_destroy(struct lttng_consumer_local_data *ctx)
1667{
4c462e79
MD
1668 int ret;
1669
ab1027f4
DG
1670 DBG("Consumer destroying it. Closing everything.");
1671
4f2e75b9
DG
1672 if (!ctx) {
1673 return;
1674 }
1675
282dadbc
MD
1676 destroy_data_stream_ht(data_ht);
1677 destroy_metadata_stream_ht(metadata_ht);
1678
4c462e79
MD
1679 ret = close(ctx->consumer_error_socket);
1680 if (ret) {
1681 PERROR("close");
1682 }
331744e3
JD
1683 ret = close(ctx->consumer_metadata_socket);
1684 if (ret) {
1685 PERROR("close");
1686 }
d8ef542d 1687 utils_close_pipe(ctx->consumer_channel_pipe);
acdb9057 1688 lttng_pipe_destroy(ctx->consumer_data_pipe);
13886d2d 1689 lttng_pipe_destroy(ctx->consumer_metadata_pipe);
02b3d176 1690 lttng_pipe_destroy(ctx->consumer_wakeup_pipe);
d8ef542d 1691 utils_close_pipe(ctx->consumer_should_quit);
fb3a43a9 1692
3bd1e081
MD
1693 unlink(ctx->consumer_command_sock_path);
1694 free(ctx);
1695}
1696
6197aea7
DG
1697/*
1698 * Write the metadata stream id on the specified file descriptor.
1699 */
1700static int write_relayd_metadata_id(int fd,
1701 struct lttng_consumer_stream *stream,
239f61af 1702 unsigned long padding)
6197aea7 1703{
6cd525e8 1704 ssize_t ret;
1d4dfdef 1705 struct lttcomm_relayd_metadata_payload hdr;
6197aea7 1706
1d4dfdef
DG
1707 hdr.stream_id = htobe64(stream->relayd_stream_id);
1708 hdr.padding_size = htobe32(padding);
6cd525e8
MD
1709 ret = lttng_write(fd, (void *) &hdr, sizeof(hdr));
1710 if (ret < sizeof(hdr)) {
d7b75ec8 1711 /*
6f04ed72 1712 * This error means that the fd's end is closed so ignore the PERROR
d7b75ec8
DG
1713 * not to clubber the error output since this can happen in a normal
1714 * code path.
1715 */
1716 if (errno != EPIPE) {
1717 PERROR("write metadata stream id");
1718 }
1719 DBG3("Consumer failed to write relayd metadata id (errno: %d)", errno);
534d2592
DG
1720 /*
1721 * Set ret to a negative value because if ret != sizeof(hdr), we don't
1722 * handle writting the missing part so report that as an error and
1723 * don't lie to the caller.
1724 */
1725 ret = -1;
6197aea7
DG
1726 goto end;
1727 }
1d4dfdef
DG
1728 DBG("Metadata stream id %" PRIu64 " with padding %lu written before data",
1729 stream->relayd_stream_id, padding);
6197aea7
DG
1730
1731end:
6cd525e8 1732 return (int) ret;
6197aea7
DG
1733}
1734
3bd1e081 1735/*
09e26845
DG
1736 * Mmap the ring buffer, read it and write the data to the tracefile. This is a
1737 * core function for writing trace buffers to either the local filesystem or
1738 * the network.
1739 *
d2956687 1740 * It must be called with the stream and the channel lock held.
79d4ffb7 1741 *
09e26845 1742 * Careful review MUST be put if any changes occur!
3bd1e081
MD
1743 *
1744 * Returns the number of bytes written
1745 */
4078b776 1746ssize_t lttng_consumer_on_read_subbuffer_mmap(
3bd1e081 1747 struct lttng_consumer_local_data *ctx,
1d4dfdef 1748 struct lttng_consumer_stream *stream, unsigned long len,
309167d2 1749 unsigned long padding,
50adc264 1750 struct ctf_packet_index *index)
3bd1e081 1751{
f02e1e8a 1752 unsigned long mmap_offset;
ffe60014 1753 void *mmap_base;
994ab360 1754 ssize_t ret = 0;
f02e1e8a
DG
1755 off_t orig_offset = stream->out_fd_offset;
1756 /* Default is on the disk */
1757 int outfd = stream->out_fd;
f02e1e8a 1758 struct consumer_relayd_sock_pair *relayd = NULL;
8994307f 1759 unsigned int relayd_hang_up = 0;
f02e1e8a
DG
1760
1761 /* RCU lock for the relayd pointer */
1762 rcu_read_lock();
7fd975c5 1763 assert(stream->net_seq_idx != (uint64_t) -1ULL ||
948411cd 1764 stream->trace_chunk);
d2956687 1765
f02e1e8a 1766 /* Flag that the current stream if set for network streaming. */
da009f2c 1767 if (stream->net_seq_idx != (uint64_t) -1ULL) {
f02e1e8a
DG
1768 relayd = consumer_find_relayd(stream->net_seq_idx);
1769 if (relayd == NULL) {
56591bac 1770 ret = -EPIPE;
f02e1e8a
DG
1771 goto end;
1772 }
1773 }
1774
1775 /* get the offset inside the fd to mmap */
3bd1e081
MD
1776 switch (consumer_data.type) {
1777 case LTTNG_CONSUMER_KERNEL:
ffe60014 1778 mmap_base = stream->mmap_base;
f02e1e8a 1779 ret = kernctl_get_mmap_read_offset(stream->wait_fd, &mmap_offset);
994ab360 1780 if (ret < 0) {
56591bac 1781 PERROR("tracer ctl get_mmap_read_offset");
56591bac
MD
1782 goto end;
1783 }
f02e1e8a 1784 break;
7753dea8
MD
1785 case LTTNG_CONSUMER32_UST:
1786 case LTTNG_CONSUMER64_UST:
ffe60014
DG
1787 mmap_base = lttng_ustctl_get_mmap_base(stream);
1788 if (!mmap_base) {
1789 ERR("read mmap get mmap base for stream %s", stream->name);
994ab360 1790 ret = -EPERM;
ffe60014
DG
1791 goto end;
1792 }
1793 ret = lttng_ustctl_get_mmap_read_offset(stream, &mmap_offset);
56591bac
MD
1794 if (ret != 0) {
1795 PERROR("tracer ctl get_mmap_read_offset");
994ab360 1796 ret = -EINVAL;
56591bac
MD
1797 goto end;
1798 }
f02e1e8a 1799 break;
3bd1e081
MD
1800 default:
1801 ERR("Unknown consumer_data type");
1802 assert(0);
1803 }
b9182dd9 1804
f02e1e8a
DG
1805 /* Handle stream on the relayd if the output is on the network */
1806 if (relayd) {
1807 unsigned long netlen = len;
1808
1809 /*
1810 * Lock the control socket for the complete duration of the function
1811 * since from this point on we will use the socket.
1812 */
1813 if (stream->metadata_flag) {
1814 /* Metadata requires the control socket. */
1815 pthread_mutex_lock(&relayd->ctrl_sock_mutex);
93ec662e
JD
1816 if (stream->reset_metadata_flag) {
1817 ret = relayd_reset_metadata(&relayd->control_sock,
1818 stream->relayd_stream_id,
1819 stream->metadata_version);
1820 if (ret < 0) {
1821 relayd_hang_up = 1;
1822 goto write_error;
1823 }
1824 stream->reset_metadata_flag = 0;
1825 }
1d4dfdef 1826 netlen += sizeof(struct lttcomm_relayd_metadata_payload);
f02e1e8a
DG
1827 }
1828
1d4dfdef 1829 ret = write_relayd_stream_header(stream, netlen, padding, relayd);
994ab360
DG
1830 if (ret < 0) {
1831 relayd_hang_up = 1;
1832 goto write_error;
1833 }
1834 /* Use the returned socket. */
1835 outfd = ret;
f02e1e8a 1836
994ab360
DG
1837 /* Write metadata stream id before payload */
1838 if (stream->metadata_flag) {
239f61af 1839 ret = write_relayd_metadata_id(outfd, stream, padding);
994ab360 1840 if (ret < 0) {
8994307f
DG
1841 relayd_hang_up = 1;
1842 goto write_error;
1843 }
f02e1e8a 1844 }
1d4dfdef
DG
1845 } else {
1846 /* No streaming, we have to set the len with the full padding */
1847 len += padding;
1624d5b7 1848
93ec662e
JD
1849 if (stream->metadata_flag && stream->reset_metadata_flag) {
1850 ret = utils_truncate_stream_file(stream->out_fd, 0);
1851 if (ret < 0) {
1852 ERR("Reset metadata file");
1853 goto end;
1854 }
1855 stream->reset_metadata_flag = 0;
1856 }
1857
1624d5b7
JD
1858 /*
1859 * Check if we need to change the tracefile before writing the packet.
1860 */
1861 if (stream->chan->tracefile_size > 0 &&
1862 (stream->tracefile_size_current + len) >
1863 stream->chan->tracefile_size) {
d2956687
JG
1864 ret = consumer_stream_rotate_output_files(stream);
1865 if (ret) {
1624d5b7
JD
1866 goto end;
1867 }
309167d2 1868 outfd = stream->out_fd;
a1ae300f 1869 orig_offset = 0;
1624d5b7
JD
1870 }
1871 stream->tracefile_size_current += len;
309167d2
JD
1872 if (index) {
1873 index->offset = htobe64(stream->out_fd_offset);
1874 }
f02e1e8a
DG
1875 }
1876
d02b8372
DG
1877 /*
1878 * This call guarantee that len or less is returned. It's impossible to
1879 * receive a ret value that is bigger than len.
1880 */
1881 ret = lttng_write(outfd, mmap_base + mmap_offset, len);
1882 DBG("Consumer mmap write() ret %zd (len %lu)", ret, len);
1883 if (ret < 0 || ((size_t) ret != len)) {
1884 /*
1885 * Report error to caller if nothing was written else at least send the
1886 * amount written.
1887 */
1888 if (ret < 0) {
994ab360 1889 ret = -errno;
f02e1e8a 1890 }
994ab360 1891 relayd_hang_up = 1;
f02e1e8a 1892
d02b8372 1893 /* Socket operation failed. We consider the relayd dead */
fcf0f774 1894 if (errno == EPIPE) {
d02b8372
DG
1895 /*
1896 * This is possible if the fd is closed on the other side
1897 * (outfd) or any write problem. It can be verbose a bit for a
1898 * normal execution if for instance the relayd is stopped
1899 * abruptly. This can happen so set this to a DBG statement.
1900 */
1901 DBG("Consumer mmap write detected relayd hang up");
994ab360
DG
1902 } else {
1903 /* Unhandled error, print it and stop function right now. */
1904 PERROR("Error in write mmap (ret %zd != len %lu)", ret, len);
f02e1e8a 1905 }
994ab360 1906 goto write_error;
d02b8372
DG
1907 }
1908 stream->output_written += ret;
d02b8372
DG
1909
1910 /* This call is useless on a socket so better save a syscall. */
1911 if (!relayd) {
1912 /* This won't block, but will start writeout asynchronously */
1913 lttng_sync_file_range(outfd, stream->out_fd_offset, len,
1914 SYNC_FILE_RANGE_WRITE);
1915 stream->out_fd_offset += len;
f5dbe415 1916 lttng_consumer_sync_trace_file(stream, orig_offset);
f02e1e8a 1917 }
f02e1e8a 1918
8994307f
DG
1919write_error:
1920 /*
1921 * This is a special case that the relayd has closed its socket. Let's
1922 * cleanup the relayd object and all associated streams.
1923 */
1924 if (relayd && relayd_hang_up) {
9276e5c8
JR
1925 ERR("Relayd hangup. Cleaning up relayd %" PRIu64".", relayd->net_seq_idx);
1926 lttng_consumer_cleanup_relayd(relayd);
8994307f
DG
1927 }
1928
f02e1e8a
DG
1929end:
1930 /* Unlock only if ctrl socket used */
1931 if (relayd && stream->metadata_flag) {
1932 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
1933 }
1934
1935 rcu_read_unlock();
994ab360 1936 return ret;
3bd1e081
MD
1937}
1938
1939/*
1940 * Splice the data from the ring buffer to the tracefile.
1941 *
79d4ffb7
DG
1942 * It must be called with the stream lock held.
1943 *
3bd1e081
MD
1944 * Returns the number of bytes spliced.
1945 */
4078b776 1946ssize_t lttng_consumer_on_read_subbuffer_splice(
3bd1e081 1947 struct lttng_consumer_local_data *ctx,
1d4dfdef 1948 struct lttng_consumer_stream *stream, unsigned long len,
309167d2 1949 unsigned long padding,
50adc264 1950 struct ctf_packet_index *index)
3bd1e081 1951{
f02e1e8a
DG
1952 ssize_t ret = 0, written = 0, ret_splice = 0;
1953 loff_t offset = 0;
1954 off_t orig_offset = stream->out_fd_offset;
1955 int fd = stream->wait_fd;
1956 /* Default is on the disk */
1957 int outfd = stream->out_fd;
f02e1e8a 1958 struct consumer_relayd_sock_pair *relayd = NULL;
fb3a43a9 1959 int *splice_pipe;
8994307f 1960 unsigned int relayd_hang_up = 0;
f02e1e8a 1961
3bd1e081
MD
1962 switch (consumer_data.type) {
1963 case LTTNG_CONSUMER_KERNEL:
f02e1e8a 1964 break;
7753dea8
MD
1965 case LTTNG_CONSUMER32_UST:
1966 case LTTNG_CONSUMER64_UST:
f02e1e8a 1967 /* Not supported for user space tracing */
3bd1e081
MD
1968 return -ENOSYS;
1969 default:
1970 ERR("Unknown consumer_data type");
1971 assert(0);
3bd1e081
MD
1972 }
1973
f02e1e8a
DG
1974 /* RCU lock for the relayd pointer */
1975 rcu_read_lock();
1976
1977 /* Flag that the current stream if set for network streaming. */
da009f2c 1978 if (stream->net_seq_idx != (uint64_t) -1ULL) {
f02e1e8a
DG
1979 relayd = consumer_find_relayd(stream->net_seq_idx);
1980 if (relayd == NULL) {
ad0b0d23 1981 written = -ret;
f02e1e8a
DG
1982 goto end;
1983 }
1984 }
a2361a61 1985 splice_pipe = stream->splice_pipe;
fb3a43a9 1986
f02e1e8a 1987 /* Write metadata stream id before payload */
1d4dfdef 1988 if (relayd) {
ad0b0d23 1989 unsigned long total_len = len;
f02e1e8a 1990
1d4dfdef
DG
1991 if (stream->metadata_flag) {
1992 /*
1993 * Lock the control socket for the complete duration of the function
1994 * since from this point on we will use the socket.
1995 */
1996 pthread_mutex_lock(&relayd->ctrl_sock_mutex);
1997
93ec662e
JD
1998 if (stream->reset_metadata_flag) {
1999 ret = relayd_reset_metadata(&relayd->control_sock,
2000 stream->relayd_stream_id,
2001 stream->metadata_version);
2002 if (ret < 0) {
2003 relayd_hang_up = 1;
2004 goto write_error;
2005 }
2006 stream->reset_metadata_flag = 0;
2007 }
239f61af 2008 ret = write_relayd_metadata_id(splice_pipe[1], stream,
1d4dfdef
DG
2009 padding);
2010 if (ret < 0) {
2011 written = ret;
ad0b0d23
DG
2012 relayd_hang_up = 1;
2013 goto write_error;
1d4dfdef
DG
2014 }
2015
2016 total_len += sizeof(struct lttcomm_relayd_metadata_payload);
2017 }
2018
2019 ret = write_relayd_stream_header(stream, total_len, padding, relayd);
ad0b0d23
DG
2020 if (ret < 0) {
2021 written = ret;
2022 relayd_hang_up = 1;
2023 goto write_error;
f02e1e8a 2024 }
ad0b0d23
DG
2025 /* Use the returned socket. */
2026 outfd = ret;
1d4dfdef
DG
2027 } else {
2028 /* No streaming, we have to set the len with the full padding */
2029 len += padding;
1624d5b7 2030
93ec662e
JD
2031 if (stream->metadata_flag && stream->reset_metadata_flag) {
2032 ret = utils_truncate_stream_file(stream->out_fd, 0);
2033 if (ret < 0) {
2034 ERR("Reset metadata file");
2035 goto end;
2036 }
2037 stream->reset_metadata_flag = 0;
2038 }
1624d5b7
JD
2039 /*
2040 * Check if we need to change the tracefile before writing the packet.
2041 */
2042 if (stream->chan->tracefile_size > 0 &&
2043 (stream->tracefile_size_current + len) >
2044 stream->chan->tracefile_size) {
d2956687 2045 ret = consumer_stream_rotate_output_files(stream);
1624d5b7 2046 if (ret < 0) {
ad0b0d23 2047 written = ret;
1624d5b7
JD
2048 goto end;
2049 }
309167d2 2050 outfd = stream->out_fd;
a1ae300f 2051 orig_offset = 0;
1624d5b7
JD
2052 }
2053 stream->tracefile_size_current += len;
309167d2 2054 index->offset = htobe64(stream->out_fd_offset);
f02e1e8a
DG
2055 }
2056
2057 while (len > 0) {
1d4dfdef
DG
2058 DBG("splice chan to pipe offset %lu of len %lu (fd : %d, pipe: %d)",
2059 (unsigned long)offset, len, fd, splice_pipe[1]);
fb3a43a9 2060 ret_splice = splice(fd, &offset, splice_pipe[1], NULL, len,
f02e1e8a
DG
2061 SPLICE_F_MOVE | SPLICE_F_MORE);
2062 DBG("splice chan to pipe, ret %zd", ret_splice);
2063 if (ret_splice < 0) {
d02b8372 2064 ret = errno;
ad0b0d23 2065 written = -ret;
d02b8372 2066 PERROR("Error in relay splice");
f02e1e8a
DG
2067 goto splice_error;
2068 }
2069
2070 /* Handle stream on the relayd if the output is on the network */
ad0b0d23
DG
2071 if (relayd && stream->metadata_flag) {
2072 size_t metadata_payload_size =
2073 sizeof(struct lttcomm_relayd_metadata_payload);
2074
2075 /* Update counter to fit the spliced data */
2076 ret_splice += metadata_payload_size;
2077 len += metadata_payload_size;
2078 /*
2079 * We do this so the return value can match the len passed as
2080 * argument to this function.
2081 */
2082 written -= metadata_payload_size;
f02e1e8a
DG
2083 }
2084
2085 /* Splice data out */
fb3a43a9 2086 ret_splice = splice(splice_pipe[0], NULL, outfd, NULL,
f02e1e8a 2087 ret_splice, SPLICE_F_MOVE | SPLICE_F_MORE);
a2361a61
JD
2088 DBG("Consumer splice pipe to file (out_fd: %d), ret %zd",
2089 outfd, ret_splice);
f02e1e8a 2090 if (ret_splice < 0) {
d02b8372 2091 ret = errno;
ad0b0d23
DG
2092 written = -ret;
2093 relayd_hang_up = 1;
2094 goto write_error;
f02e1e8a 2095 } else if (ret_splice > len) {
d02b8372
DG
2096 /*
2097 * We don't expect this code path to be executed but you never know
2098 * so this is an extra protection agains a buggy splice().
2099 */
f02e1e8a 2100 ret = errno;
ad0b0d23 2101 written += ret_splice;
d02b8372
DG
2102 PERROR("Wrote more data than requested %zd (len: %lu)", ret_splice,
2103 len);
f02e1e8a 2104 goto splice_error;
d02b8372
DG
2105 } else {
2106 /* All good, update current len and continue. */
2107 len -= ret_splice;
f02e1e8a 2108 }
f02e1e8a
DG
2109
2110 /* This call is useless on a socket so better save a syscall. */
2111 if (!relayd) {
2112 /* This won't block, but will start writeout asynchronously */
2113 lttng_sync_file_range(outfd, stream->out_fd_offset, ret_splice,
2114 SYNC_FILE_RANGE_WRITE);
2115 stream->out_fd_offset += ret_splice;
2116 }
e5d1a9b3 2117 stream->output_written += ret_splice;
f02e1e8a
DG
2118 written += ret_splice;
2119 }
f5dbe415
JG
2120 if (!relayd) {
2121 lttng_consumer_sync_trace_file(stream, orig_offset);
2122 }
f02e1e8a
DG
2123 goto end;
2124
8994307f
DG
2125write_error:
2126 /*
2127 * This is a special case that the relayd has closed its socket. Let's
2128 * cleanup the relayd object and all associated streams.
2129 */
2130 if (relayd && relayd_hang_up) {
9276e5c8
JR
2131 ERR("Relayd hangup. Cleaning up relayd %" PRIu64".", relayd->net_seq_idx);
2132 lttng_consumer_cleanup_relayd(relayd);
8994307f
DG
2133 /* Skip splice error so the consumer does not fail */
2134 goto end;
2135 }
2136
f02e1e8a
DG
2137splice_error:
2138 /* send the appropriate error description to sessiond */
2139 switch (ret) {
f02e1e8a 2140 case EINVAL:
f73fabfd 2141 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_SPLICE_EINVAL);
f02e1e8a
DG
2142 break;
2143 case ENOMEM:
f73fabfd 2144 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_SPLICE_ENOMEM);
f02e1e8a
DG
2145 break;
2146 case ESPIPE:
f73fabfd 2147 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_SPLICE_ESPIPE);
f02e1e8a
DG
2148 break;
2149 }
2150
2151end:
2152 if (relayd && stream->metadata_flag) {
2153 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
2154 }
2155
2156 rcu_read_unlock();
2157 return written;
3bd1e081
MD
2158}
2159
15055ce5
JD
2160/*
2161 * Sample the snapshot positions for a specific fd
2162 *
2163 * Returns 0 on success, < 0 on error
2164 */
2165int lttng_consumer_sample_snapshot_positions(struct lttng_consumer_stream *stream)
2166{
2167 switch (consumer_data.type) {
2168 case LTTNG_CONSUMER_KERNEL:
2169 return lttng_kconsumer_sample_snapshot_positions(stream);
2170 case LTTNG_CONSUMER32_UST:
2171 case LTTNG_CONSUMER64_UST:
2172 return lttng_ustconsumer_sample_snapshot_positions(stream);
2173 default:
2174 ERR("Unknown consumer_data type");
2175 assert(0);
2176 return -ENOSYS;
2177 }
2178}
3bd1e081
MD
2179/*
2180 * Take a snapshot for a specific fd
2181 *
2182 * Returns 0 on success, < 0 on error
2183 */
ffe60014 2184int lttng_consumer_take_snapshot(struct lttng_consumer_stream *stream)
3bd1e081
MD
2185{
2186 switch (consumer_data.type) {
2187 case LTTNG_CONSUMER_KERNEL:
ffe60014 2188 return lttng_kconsumer_take_snapshot(stream);
7753dea8
MD
2189 case LTTNG_CONSUMER32_UST:
2190 case LTTNG_CONSUMER64_UST:
ffe60014 2191 return lttng_ustconsumer_take_snapshot(stream);
3bd1e081
MD
2192 default:
2193 ERR("Unknown consumer_data type");
2194 assert(0);
2195 return -ENOSYS;
2196 }
3bd1e081
MD
2197}
2198
2199/*
2200 * Get the produced position
2201 *
2202 * Returns 0 on success, < 0 on error
2203 */
ffe60014 2204int lttng_consumer_get_produced_snapshot(struct lttng_consumer_stream *stream,
3bd1e081
MD
2205 unsigned long *pos)
2206{
2207 switch (consumer_data.type) {
2208 case LTTNG_CONSUMER_KERNEL:
ffe60014 2209 return lttng_kconsumer_get_produced_snapshot(stream, pos);
7753dea8
MD
2210 case LTTNG_CONSUMER32_UST:
2211 case LTTNG_CONSUMER64_UST:
ffe60014 2212 return lttng_ustconsumer_get_produced_snapshot(stream, pos);
3bd1e081
MD
2213 default:
2214 ERR("Unknown consumer_data type");
2215 assert(0);
2216 return -ENOSYS;
2217 }
2218}
2219
15055ce5
JD
2220/*
2221 * Get the consumed position (free-running counter position in bytes).
2222 *
2223 * Returns 0 on success, < 0 on error
2224 */
2225int lttng_consumer_get_consumed_snapshot(struct lttng_consumer_stream *stream,
2226 unsigned long *pos)
2227{
2228 switch (consumer_data.type) {
2229 case LTTNG_CONSUMER_KERNEL:
2230 return lttng_kconsumer_get_consumed_snapshot(stream, pos);
2231 case LTTNG_CONSUMER32_UST:
2232 case LTTNG_CONSUMER64_UST:
2233 return lttng_ustconsumer_get_consumed_snapshot(stream, pos);
2234 default:
2235 ERR("Unknown consumer_data type");
2236 assert(0);
2237 return -ENOSYS;
2238 }
2239}
2240
3bd1e081
MD
2241int lttng_consumer_recv_cmd(struct lttng_consumer_local_data *ctx,
2242 int sock, struct pollfd *consumer_sockpoll)
2243{
2244 switch (consumer_data.type) {
2245 case LTTNG_CONSUMER_KERNEL:
2246 return lttng_kconsumer_recv_cmd(ctx, sock, consumer_sockpoll);
7753dea8
MD
2247 case LTTNG_CONSUMER32_UST:
2248 case LTTNG_CONSUMER64_UST:
3bd1e081
MD
2249 return lttng_ustconsumer_recv_cmd(ctx, sock, consumer_sockpoll);
2250 default:
2251 ERR("Unknown consumer_data type");
2252 assert(0);
2253 return -ENOSYS;
2254 }
2255}
2256
6d574024 2257void lttng_consumer_close_all_metadata(void)
d88aee68
DG
2258{
2259 switch (consumer_data.type) {
2260 case LTTNG_CONSUMER_KERNEL:
2261 /*
2262 * The Kernel consumer has a different metadata scheme so we don't
2263 * close anything because the stream will be closed by the session
2264 * daemon.
2265 */
2266 break;
2267 case LTTNG_CONSUMER32_UST:
2268 case LTTNG_CONSUMER64_UST:
2269 /*
2270 * Close all metadata streams. The metadata hash table is passed and
2271 * this call iterates over it by closing all wakeup fd. This is safe
2272 * because at this point we are sure that the metadata producer is
2273 * either dead or blocked.
2274 */
6d574024 2275 lttng_ustconsumer_close_all_metadata(metadata_ht);
d88aee68
DG
2276 break;
2277 default:
2278 ERR("Unknown consumer_data type");
2279 assert(0);
2280 }
2281}
2282
fb3a43a9
DG
2283/*
2284 * Clean up a metadata stream and free its memory.
2285 */
e316aad5
DG
2286void consumer_del_metadata_stream(struct lttng_consumer_stream *stream,
2287 struct lttng_ht *ht)
fb3a43a9 2288{
a6ef8ee6
JG
2289 struct lttng_consumer_channel *channel = NULL;
2290 bool free_channel = false;
fb3a43a9
DG
2291
2292 assert(stream);
2293 /*
2294 * This call should NEVER receive regular stream. It must always be
2295 * metadata stream and this is crucial for data structure synchronization.
2296 */
2297 assert(stream->metadata_flag);
2298
e316aad5
DG
2299 DBG3("Consumer delete metadata stream %d", stream->wait_fd);
2300
74251bb8 2301 pthread_mutex_lock(&consumer_data.lock);
a6ef8ee6
JG
2302 /*
2303 * Note that this assumes that a stream's channel is never changed and
2304 * that the stream's lock doesn't need to be taken to sample its
2305 * channel.
2306 */
2307 channel = stream->chan;
2308 pthread_mutex_lock(&channel->lock);
3dad2c0f 2309 pthread_mutex_lock(&stream->lock);
a6ef8ee6 2310 if (channel->metadata_cache) {
081424af 2311 /* Only applicable to userspace consumers. */
a6ef8ee6 2312 pthread_mutex_lock(&channel->metadata_cache->lock);
081424af 2313 }
8994307f 2314
6d574024
DG
2315 /* Remove any reference to that stream. */
2316 consumer_stream_delete(stream, ht);
ca22feea 2317
6d574024
DG
2318 /* Close down everything including the relayd if one. */
2319 consumer_stream_close(stream);
2320 /* Destroy tracer buffers of the stream. */
2321 consumer_stream_destroy_buffers(stream);
fb3a43a9
DG
2322
2323 /* Atomically decrement channel refcount since other threads can use it. */
a6ef8ee6
JG
2324 if (!uatomic_sub_return(&channel->refcount, 1)
2325 && !uatomic_read(&channel->nb_init_stream_left)) {
c30aaa51 2326 /* Go for channel deletion! */
a6ef8ee6 2327 free_channel = true;
fb3a43a9 2328 }
a6ef8ee6 2329 stream->chan = NULL;
fb3a43a9 2330
73811ecc
DG
2331 /*
2332 * Nullify the stream reference so it is not used after deletion. The
6d574024
DG
2333 * channel lock MUST be acquired before being able to check for a NULL
2334 * pointer value.
73811ecc 2335 */
a6ef8ee6 2336 channel->metadata_stream = NULL;
73811ecc 2337
a6ef8ee6
JG
2338 if (channel->metadata_cache) {
2339 pthread_mutex_unlock(&channel->metadata_cache->lock);
081424af 2340 }
3dad2c0f 2341 pthread_mutex_unlock(&stream->lock);
a6ef8ee6 2342 pthread_mutex_unlock(&channel->lock);
74251bb8 2343 pthread_mutex_unlock(&consumer_data.lock);
e316aad5 2344
a6ef8ee6
JG
2345 if (free_channel) {
2346 consumer_del_channel(channel);
e316aad5
DG
2347 }
2348
d2956687
JG
2349 lttng_trace_chunk_put(stream->trace_chunk);
2350 stream->trace_chunk = NULL;
6d574024 2351 consumer_stream_free(stream);
fb3a43a9
DG
2352}
2353
2354/*
2355 * Action done with the metadata stream when adding it to the consumer internal
2356 * data structures to handle it.
2357 */
66d583dc 2358void consumer_add_metadata_stream(struct lttng_consumer_stream *stream)
fb3a43a9 2359{
5ab66908 2360 struct lttng_ht *ht = metadata_ht;
76082088 2361 struct lttng_ht_iter iter;
d88aee68 2362 struct lttng_ht_node_u64 *node;
fb3a43a9 2363
e316aad5
DG
2364 assert(stream);
2365 assert(ht);
2366
d88aee68 2367 DBG3("Adding metadata stream %" PRIu64 " to hash table", stream->key);
e316aad5
DG
2368
2369 pthread_mutex_lock(&consumer_data.lock);
a9838785 2370 pthread_mutex_lock(&stream->chan->lock);
ec6ea7d0 2371 pthread_mutex_lock(&stream->chan->timer_lock);
2e818a6a 2372 pthread_mutex_lock(&stream->lock);
e316aad5 2373
e316aad5
DG
2374 /*
2375 * From here, refcounts are updated so be _careful_ when returning an error
2376 * after this point.
2377 */
2378
fb3a43a9 2379 rcu_read_lock();
76082088
DG
2380
2381 /*
2382 * Lookup the stream just to make sure it does not exist in our internal
2383 * state. This should NEVER happen.
2384 */
d88aee68
DG
2385 lttng_ht_lookup(ht, &stream->key, &iter);
2386 node = lttng_ht_iter_get_node_u64(&iter);
76082088
DG
2387 assert(!node);
2388
e316aad5 2389 /*
ffe60014
DG
2390 * When nb_init_stream_left reaches 0, we don't need to trigger any action
2391 * in terms of destroying the associated channel, because the action that
e316aad5
DG
2392 * causes the count to become 0 also causes a stream to be added. The
2393 * channel deletion will thus be triggered by the following removal of this
2394 * stream.
2395 */
ffe60014 2396 if (uatomic_read(&stream->chan->nb_init_stream_left) > 0) {
f2ad556d
MD
2397 /* Increment refcount before decrementing nb_init_stream_left */
2398 cmm_smp_wmb();
ffe60014 2399 uatomic_dec(&stream->chan->nb_init_stream_left);
e316aad5
DG
2400 }
2401
d88aee68 2402 lttng_ht_add_unique_u64(ht, &stream->node);
ca22feea 2403
446156b4 2404 lttng_ht_add_u64(consumer_data.stream_per_chan_id_ht,
d8ef542d
MD
2405 &stream->node_channel_id);
2406
ca22feea
DG
2407 /*
2408 * Add stream to the stream_list_ht of the consumer data. No need to steal
2409 * the key since the HT does not use it and we allow to add redundant keys
2410 * into this table.
2411 */
d88aee68 2412 lttng_ht_add_u64(consumer_data.stream_list_ht, &stream->node_session_id);
ca22feea 2413
fb3a43a9 2414 rcu_read_unlock();
e316aad5 2415
2e818a6a 2416 pthread_mutex_unlock(&stream->lock);
a9838785 2417 pthread_mutex_unlock(&stream->chan->lock);
ec6ea7d0 2418 pthread_mutex_unlock(&stream->chan->timer_lock);
e316aad5 2419 pthread_mutex_unlock(&consumer_data.lock);
fb3a43a9
DG
2420}
2421
8994307f
DG
2422/*
2423 * Delete data stream that are flagged for deletion (endpoint_status).
2424 */
2425static void validate_endpoint_status_data_stream(void)
2426{
2427 struct lttng_ht_iter iter;
2428 struct lttng_consumer_stream *stream;
2429
2430 DBG("Consumer delete flagged data stream");
2431
2432 rcu_read_lock();
2433 cds_lfht_for_each_entry(data_ht->ht, &iter.iter, stream, node.node) {
2434 /* Validate delete flag of the stream */
79d4ffb7 2435 if (stream->endpoint_status == CONSUMER_ENDPOINT_ACTIVE) {
8994307f
DG
2436 continue;
2437 }
2438 /* Delete it right now */
2439 consumer_del_stream(stream, data_ht);
2440 }
2441 rcu_read_unlock();
2442}
2443
2444/*
2445 * Delete metadata stream that are flagged for deletion (endpoint_status).
2446 */
2447static void validate_endpoint_status_metadata_stream(
2448 struct lttng_poll_event *pollset)
2449{
2450 struct lttng_ht_iter iter;
2451 struct lttng_consumer_stream *stream;
2452
2453 DBG("Consumer delete flagged metadata stream");
2454
2455 assert(pollset);
2456
2457 rcu_read_lock();
2458 cds_lfht_for_each_entry(metadata_ht->ht, &iter.iter, stream, node.node) {
2459 /* Validate delete flag of the stream */
79d4ffb7 2460 if (stream->endpoint_status == CONSUMER_ENDPOINT_ACTIVE) {
8994307f
DG
2461 continue;
2462 }
2463 /*
2464 * Remove from pollset so the metadata thread can continue without
2465 * blocking on a deleted stream.
2466 */
2467 lttng_poll_del(pollset, stream->wait_fd);
2468
2469 /* Delete it right now */
2470 consumer_del_metadata_stream(stream, metadata_ht);
2471 }
2472 rcu_read_unlock();
2473}
2474
fb3a43a9
DG
2475/*
2476 * Thread polls on metadata file descriptor and write them on disk or on the
2477 * network.
2478 */
7d980def 2479void *consumer_thread_metadata_poll(void *data)
fb3a43a9 2480{
1fc79fb4 2481 int ret, i, pollfd, err = -1;
fb3a43a9 2482 uint32_t revents, nb_fd;
e316aad5 2483 struct lttng_consumer_stream *stream = NULL;
fb3a43a9 2484 struct lttng_ht_iter iter;
d88aee68 2485 struct lttng_ht_node_u64 *node;
fb3a43a9
DG
2486 struct lttng_poll_event events;
2487 struct lttng_consumer_local_data *ctx = data;
2488 ssize_t len;
2489
2490 rcu_register_thread();
2491
1fc79fb4
MD
2492 health_register(health_consumerd, HEALTH_CONSUMERD_TYPE_METADATA);
2493
2d57de81
MD
2494 if (testpoint(consumerd_thread_metadata)) {
2495 goto error_testpoint;
2496 }
2497
9ce5646a
MD
2498 health_code_update();
2499
fb3a43a9
DG
2500 DBG("Thread metadata poll started");
2501
fb3a43a9
DG
2502 /* Size is set to 1 for the consumer_metadata pipe */
2503 ret = lttng_poll_create(&events, 2, LTTNG_CLOEXEC);
2504 if (ret < 0) {
2505 ERR("Poll set creation failed");
d8ef542d 2506 goto end_poll;
fb3a43a9
DG
2507 }
2508
13886d2d
DG
2509 ret = lttng_poll_add(&events,
2510 lttng_pipe_get_readfd(ctx->consumer_metadata_pipe), LPOLLIN);
fb3a43a9
DG
2511 if (ret < 0) {
2512 goto end;
2513 }
2514
2515 /* Main loop */
2516 DBG("Metadata main loop started");
2517
2518 while (1) {
fb3a43a9 2519restart:
7fa2082e 2520 health_code_update();
9ce5646a 2521 health_poll_entry();
7fa2082e 2522 DBG("Metadata poll wait");
fb3a43a9 2523 ret = lttng_poll_wait(&events, -1);
7fa2082e
MD
2524 DBG("Metadata poll return from wait with %d fd(s)",
2525 LTTNG_POLL_GETNB(&events));
9ce5646a 2526 health_poll_exit();
40063ead 2527 DBG("Metadata event caught in thread");
fb3a43a9
DG
2528 if (ret < 0) {
2529 if (errno == EINTR) {
40063ead 2530 ERR("Poll EINTR caught");
fb3a43a9
DG
2531 goto restart;
2532 }
d9607cd7
MD
2533 if (LTTNG_POLL_GETNB(&events) == 0) {
2534 err = 0; /* All is OK */
2535 }
2536 goto end;
fb3a43a9
DG
2537 }
2538
0d9c5d77
DG
2539 nb_fd = ret;
2540
e316aad5 2541 /* From here, the event is a metadata wait fd */
fb3a43a9 2542 for (i = 0; i < nb_fd; i++) {
9ce5646a
MD
2543 health_code_update();
2544
fb3a43a9
DG
2545 revents = LTTNG_POLL_GETEV(&events, i);
2546 pollfd = LTTNG_POLL_GETFD(&events, i);
2547
13886d2d 2548 if (pollfd == lttng_pipe_get_readfd(ctx->consumer_metadata_pipe)) {
03e43155 2549 if (revents & LPOLLIN) {
13886d2d
DG
2550 ssize_t pipe_len;
2551
2552 pipe_len = lttng_pipe_read(ctx->consumer_metadata_pipe,
2553 &stream, sizeof(stream));
6cd525e8 2554 if (pipe_len < sizeof(stream)) {
03e43155
MD
2555 if (pipe_len < 0) {
2556 PERROR("read metadata stream");
2557 }
fb3a43a9 2558 /*
03e43155
MD
2559 * Remove the pipe from the poll set and continue the loop
2560 * since their might be data to consume.
fb3a43a9 2561 */
03e43155
MD
2562 lttng_poll_del(&events,
2563 lttng_pipe_get_readfd(ctx->consumer_metadata_pipe));
2564 lttng_pipe_read_close(ctx->consumer_metadata_pipe);
fb3a43a9
DG
2565 continue;
2566 }
2567
8994307f
DG
2568 /* A NULL stream means that the state has changed. */
2569 if (stream == NULL) {
2570 /* Check for deleted streams. */
2571 validate_endpoint_status_metadata_stream(&events);
3714380f 2572 goto restart;
8994307f
DG
2573 }
2574
fb3a43a9
DG
2575 DBG("Adding metadata stream %d to poll set",
2576 stream->wait_fd);
2577
fb3a43a9
DG
2578 /* Add metadata stream to the global poll events list */
2579 lttng_poll_add(&events, stream->wait_fd,
6d574024 2580 LPOLLIN | LPOLLPRI | LPOLLHUP);
03e43155
MD
2581 } else if (revents & (LPOLLERR | LPOLLHUP)) {
2582 DBG("Metadata thread pipe hung up");
2583 /*
2584 * Remove the pipe from the poll set and continue the loop
2585 * since their might be data to consume.
2586 */
2587 lttng_poll_del(&events,
2588 lttng_pipe_get_readfd(ctx->consumer_metadata_pipe));
2589 lttng_pipe_read_close(ctx->consumer_metadata_pipe);
2590 continue;
2591 } else {
2592 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
2593 goto end;
fb3a43a9
DG
2594 }
2595
e316aad5 2596 /* Handle other stream */
fb3a43a9
DG
2597 continue;
2598 }
2599
d09e1200 2600 rcu_read_lock();
d88aee68
DG
2601 {
2602 uint64_t tmp_id = (uint64_t) pollfd;
2603
2604 lttng_ht_lookup(metadata_ht, &tmp_id, &iter);
2605 }
2606 node = lttng_ht_iter_get_node_u64(&iter);
e316aad5 2607 assert(node);
fb3a43a9
DG
2608
2609 stream = caa_container_of(node, struct lttng_consumer_stream,
58b1f425 2610 node);
fb3a43a9 2611
03e43155
MD
2612 if (revents & (LPOLLIN | LPOLLPRI)) {
2613 /* Get the data out of the metadata file descriptor */
2614 DBG("Metadata available on fd %d", pollfd);
2615 assert(stream->wait_fd == pollfd);
2616
2617 do {
2618 health_code_update();
2619
2620 len = ctx->on_buffer_ready(stream, ctx);
2621 /*
2622 * We don't check the return value here since if we get
83f4233d 2623 * a negative len, it means an error occurred thus we
03e43155
MD
2624 * simply remove it from the poll set and free the
2625 * stream.
2626 */
2627 } while (len > 0);
2628
2629 /* It's ok to have an unavailable sub-buffer */
2630 if (len < 0 && len != -EAGAIN && len != -ENODATA) {
2631 /* Clean up stream from consumer and free it. */
2632 lttng_poll_del(&events, stream->wait_fd);
2633 consumer_del_metadata_stream(stream, metadata_ht);
2634 }
2635 } else if (revents & (LPOLLERR | LPOLLHUP)) {
e316aad5 2636 DBG("Metadata fd %d is hup|err.", pollfd);
fb3a43a9
DG
2637 if (!stream->hangup_flush_done
2638 && (consumer_data.type == LTTNG_CONSUMER32_UST
2639 || consumer_data.type == LTTNG_CONSUMER64_UST)) {
2640 DBG("Attempting to flush and consume the UST buffers");
2641 lttng_ustconsumer_on_stream_hangup(stream);
2642
2643 /* We just flushed the stream now read it. */
4bb94b75 2644 do {
9ce5646a
MD
2645 health_code_update();
2646
4bb94b75
DG
2647 len = ctx->on_buffer_ready(stream, ctx);
2648 /*
2649 * We don't check the return value here since if we get
83f4233d 2650 * a negative len, it means an error occurred thus we
4bb94b75
DG
2651 * simply remove it from the poll set and free the
2652 * stream.
2653 */
2654 } while (len > 0);
fb3a43a9
DG
2655 }
2656
fb3a43a9 2657 lttng_poll_del(&events, stream->wait_fd);
e316aad5
DG
2658 /*
2659 * This call update the channel states, closes file descriptors
2660 * and securely free the stream.
2661 */
2662 consumer_del_metadata_stream(stream, metadata_ht);
03e43155
MD
2663 } else {
2664 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
6f2f1a70 2665 rcu_read_unlock();
03e43155 2666 goto end;
fb3a43a9 2667 }
e316aad5 2668 /* Release RCU lock for the stream looked up */
d09e1200 2669 rcu_read_unlock();
fb3a43a9
DG
2670 }
2671 }
2672
1fc79fb4
MD
2673 /* All is OK */
2674 err = 0;
fb3a43a9
DG
2675end:
2676 DBG("Metadata poll thread exiting");
fb3a43a9 2677
d8ef542d
MD
2678 lttng_poll_clean(&events);
2679end_poll:
2d57de81 2680error_testpoint:
1fc79fb4
MD
2681 if (err) {
2682 health_error();
2683 ERR("Health error occurred in %s", __func__);
2684 }
2685 health_unregister(health_consumerd);
fb3a43a9
DG
2686 rcu_unregister_thread();
2687 return NULL;
2688}
2689
3bd1e081 2690/*
e4421fec 2691 * This thread polls the fds in the set to consume the data and write
3bd1e081
MD
2692 * it to tracefile if necessary.
2693 */
7d980def 2694void *consumer_thread_data_poll(void *data)
3bd1e081 2695{
1fc79fb4 2696 int num_rdy, num_hup, high_prio, ret, i, err = -1;
3bd1e081
MD
2697 struct pollfd *pollfd = NULL;
2698 /* local view of the streams */
c869f647 2699 struct lttng_consumer_stream **local_stream = NULL, *new_stream = NULL;
3bd1e081 2700 /* local view of consumer_data.fds_count */
8bdcc002
JG
2701 int nb_fd = 0;
2702 /* 2 for the consumer_data_pipe and wake up pipe */
2703 const int nb_pipes_fd = 2;
9a2fcf78
JD
2704 /* Number of FDs with CONSUMER_ENDPOINT_INACTIVE but still open. */
2705 int nb_inactive_fd = 0;
3bd1e081 2706 struct lttng_consumer_local_data *ctx = data;
00e2e675 2707 ssize_t len;
3bd1e081 2708
e7b994a3
DG
2709 rcu_register_thread();
2710
1fc79fb4
MD
2711 health_register(health_consumerd, HEALTH_CONSUMERD_TYPE_DATA);
2712
2d57de81
MD
2713 if (testpoint(consumerd_thread_data)) {
2714 goto error_testpoint;
2715 }
2716
9ce5646a
MD
2717 health_code_update();
2718
4df6c8cb
MD
2719 local_stream = zmalloc(sizeof(struct lttng_consumer_stream *));
2720 if (local_stream == NULL) {
2721 PERROR("local_stream malloc");
2722 goto end;
2723 }
3bd1e081
MD
2724
2725 while (1) {
9ce5646a
MD
2726 health_code_update();
2727
3bd1e081
MD
2728 high_prio = 0;
2729 num_hup = 0;
2730
2731 /*
e4421fec 2732 * the fds set has been updated, we need to update our
3bd1e081
MD
2733 * local array as well
2734 */
2735 pthread_mutex_lock(&consumer_data.lock);
2736 if (consumer_data.need_update) {
0e428499
DG
2737 free(pollfd);
2738 pollfd = NULL;
2739
2740 free(local_stream);
2741 local_stream = NULL;
3bd1e081 2742
8bdcc002 2743 /* Allocate for all fds */
261de637 2744 pollfd = zmalloc((consumer_data.stream_count + nb_pipes_fd) * sizeof(struct pollfd));
3bd1e081 2745 if (pollfd == NULL) {
7a57cf92 2746 PERROR("pollfd malloc");
3bd1e081
MD
2747 pthread_mutex_unlock(&consumer_data.lock);
2748 goto end;
2749 }
2750
261de637 2751 local_stream = zmalloc((consumer_data.stream_count + nb_pipes_fd) *
747f8642 2752 sizeof(struct lttng_consumer_stream *));
3bd1e081 2753 if (local_stream == NULL) {
7a57cf92 2754 PERROR("local_stream malloc");
3bd1e081
MD
2755 pthread_mutex_unlock(&consumer_data.lock);
2756 goto end;
2757 }
ffe60014 2758 ret = update_poll_array(ctx, &pollfd, local_stream,
9a2fcf78 2759 data_ht, &nb_inactive_fd);
3bd1e081
MD
2760 if (ret < 0) {
2761 ERR("Error in allocating pollfd or local_outfds");
f73fabfd 2762 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_POLL_ERROR);
3bd1e081
MD
2763 pthread_mutex_unlock(&consumer_data.lock);
2764 goto end;
2765 }
2766 nb_fd = ret;
2767 consumer_data.need_update = 0;
2768 }
2769 pthread_mutex_unlock(&consumer_data.lock);
2770
4078b776 2771 /* No FDs and consumer_quit, consumer_cleanup the thread */
9a2fcf78
JD
2772 if (nb_fd == 0 && nb_inactive_fd == 0 &&
2773 CMM_LOAD_SHARED(consumer_quit) == 1) {
1fc79fb4 2774 err = 0; /* All is OK */
4078b776
MD
2775 goto end;
2776 }
3bd1e081 2777 /* poll on the array of fds */
88f2b785 2778 restart:
261de637 2779 DBG("polling on %d fd", nb_fd + nb_pipes_fd);
cf0bcb51
JG
2780 if (testpoint(consumerd_thread_data_poll)) {
2781 goto end;
2782 }
9ce5646a 2783 health_poll_entry();
261de637 2784 num_rdy = poll(pollfd, nb_fd + nb_pipes_fd, -1);
9ce5646a 2785 health_poll_exit();
3bd1e081
MD
2786 DBG("poll num_rdy : %d", num_rdy);
2787 if (num_rdy == -1) {
88f2b785
MD
2788 /*
2789 * Restart interrupted system call.
2790 */
2791 if (errno == EINTR) {
2792 goto restart;
2793 }
7a57cf92 2794 PERROR("Poll error");
f73fabfd 2795 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_POLL_ERROR);
3bd1e081
MD
2796 goto end;
2797 } else if (num_rdy == 0) {
2798 DBG("Polling thread timed out");
2799 goto end;
2800 }
2801
80957876
JG
2802 if (caa_unlikely(data_consumption_paused)) {
2803 DBG("Data consumption paused, sleeping...");
2804 sleep(1);
2805 goto restart;
2806 }
2807
3bd1e081 2808 /*
50f8ae69 2809 * If the consumer_data_pipe triggered poll go directly to the
00e2e675
DG
2810 * beginning of the loop to update the array. We want to prioritize
2811 * array update over low-priority reads.
3bd1e081 2812 */
509bb1cf 2813 if (pollfd[nb_fd].revents & (POLLIN | POLLPRI)) {
ab30f567 2814 ssize_t pipe_readlen;
04fdd819 2815
50f8ae69 2816 DBG("consumer_data_pipe wake up");
acdb9057
DG
2817 pipe_readlen = lttng_pipe_read(ctx->consumer_data_pipe,
2818 &new_stream, sizeof(new_stream));
6cd525e8
MD
2819 if (pipe_readlen < sizeof(new_stream)) {
2820 PERROR("Consumer data pipe");
23f5f35d
DG
2821 /* Continue so we can at least handle the current stream(s). */
2822 continue;
2823 }
c869f647
DG
2824
2825 /*
2826 * If the stream is NULL, just ignore it. It's also possible that
2827 * the sessiond poll thread changed the consumer_quit state and is
2828 * waking us up to test it.
2829 */
2830 if (new_stream == NULL) {
8994307f 2831 validate_endpoint_status_data_stream();
c869f647
DG
2832 continue;
2833 }
2834
c869f647 2835 /* Continue to update the local streams and handle prio ones */
3bd1e081
MD
2836 continue;
2837 }
2838
02b3d176
DG
2839 /* Handle wakeup pipe. */
2840 if (pollfd[nb_fd + 1].revents & (POLLIN | POLLPRI)) {
2841 char dummy;
2842 ssize_t pipe_readlen;
2843
2844 pipe_readlen = lttng_pipe_read(ctx->consumer_wakeup_pipe, &dummy,
2845 sizeof(dummy));
2846 if (pipe_readlen < 0) {
2847 PERROR("Consumer data wakeup pipe");
2848 }
2849 /* We've been awakened to handle stream(s). */
2850 ctx->has_wakeup = 0;
2851 }
2852
3bd1e081
MD
2853 /* Take care of high priority channels first. */
2854 for (i = 0; i < nb_fd; i++) {
9ce5646a
MD
2855 health_code_update();
2856
9617607b
DG
2857 if (local_stream[i] == NULL) {
2858 continue;
2859 }
fb3a43a9 2860 if (pollfd[i].revents & POLLPRI) {
d41f73b7
MD
2861 DBG("Urgent read on fd %d", pollfd[i].fd);
2862 high_prio = 1;
4078b776 2863 len = ctx->on_buffer_ready(local_stream[i], ctx);
d41f73b7 2864 /* it's ok to have an unavailable sub-buffer */
b64403e3 2865 if (len < 0 && len != -EAGAIN && len != -ENODATA) {
ab1027f4
DG
2866 /* Clean the stream and free it. */
2867 consumer_del_stream(local_stream[i], data_ht);
9617607b 2868 local_stream[i] = NULL;
4078b776
MD
2869 } else if (len > 0) {
2870 local_stream[i]->data_read = 1;
d41f73b7 2871 }
3bd1e081
MD
2872 }
2873 }
2874
4078b776
MD
2875 /*
2876 * If we read high prio channel in this loop, try again
2877 * for more high prio data.
2878 */
2879 if (high_prio) {
3bd1e081
MD
2880 continue;
2881 }
2882
2883 /* Take care of low priority channels. */
4078b776 2884 for (i = 0; i < nb_fd; i++) {
9ce5646a
MD
2885 health_code_update();
2886
9617607b
DG
2887 if (local_stream[i] == NULL) {
2888 continue;
2889 }
4078b776 2890 if ((pollfd[i].revents & POLLIN) ||
02b3d176
DG
2891 local_stream[i]->hangup_flush_done ||
2892 local_stream[i]->has_data) {
4078b776
MD
2893 DBG("Normal read on fd %d", pollfd[i].fd);
2894 len = ctx->on_buffer_ready(local_stream[i], ctx);
2895 /* it's ok to have an unavailable sub-buffer */
b64403e3 2896 if (len < 0 && len != -EAGAIN && len != -ENODATA) {
ab1027f4
DG
2897 /* Clean the stream and free it. */
2898 consumer_del_stream(local_stream[i], data_ht);
9617607b 2899 local_stream[i] = NULL;
4078b776
MD
2900 } else if (len > 0) {
2901 local_stream[i]->data_read = 1;
2902 }
2903 }
2904 }
2905
2906 /* Handle hangup and errors */
2907 for (i = 0; i < nb_fd; i++) {
9ce5646a
MD
2908 health_code_update();
2909
9617607b
DG
2910 if (local_stream[i] == NULL) {
2911 continue;
2912 }
4078b776
MD
2913 if (!local_stream[i]->hangup_flush_done
2914 && (pollfd[i].revents & (POLLHUP | POLLERR | POLLNVAL))
2915 && (consumer_data.type == LTTNG_CONSUMER32_UST
2916 || consumer_data.type == LTTNG_CONSUMER64_UST)) {
2917 DBG("fd %d is hup|err|nval. Attempting flush and read.",
9617607b 2918 pollfd[i].fd);
4078b776
MD
2919 lttng_ustconsumer_on_stream_hangup(local_stream[i]);
2920 /* Attempt read again, for the data we just flushed. */
2921 local_stream[i]->data_read = 1;
2922 }
2923 /*
2924 * If the poll flag is HUP/ERR/NVAL and we have
2925 * read no data in this pass, we can remove the
2926 * stream from its hash table.
2927 */
2928 if ((pollfd[i].revents & POLLHUP)) {
2929 DBG("Polling fd %d tells it has hung up.", pollfd[i].fd);
2930 if (!local_stream[i]->data_read) {
43c34bc3 2931 consumer_del_stream(local_stream[i], data_ht);
9617607b 2932 local_stream[i] = NULL;
4078b776
MD
2933 num_hup++;
2934 }
2935 } else if (pollfd[i].revents & POLLERR) {
2936 ERR("Error returned in polling fd %d.", pollfd[i].fd);
2937 if (!local_stream[i]->data_read) {
43c34bc3 2938 consumer_del_stream(local_stream[i], data_ht);
9617607b 2939 local_stream[i] = NULL;
4078b776
MD
2940 num_hup++;
2941 }
2942 } else if (pollfd[i].revents & POLLNVAL) {
2943 ERR("Polling fd %d tells fd is not open.", pollfd[i].fd);
2944 if (!local_stream[i]->data_read) {
43c34bc3 2945 consumer_del_stream(local_stream[i], data_ht);
9617607b 2946 local_stream[i] = NULL;
4078b776 2947 num_hup++;
3bd1e081
MD
2948 }
2949 }
9617607b
DG
2950 if (local_stream[i] != NULL) {
2951 local_stream[i]->data_read = 0;
2952 }
3bd1e081
MD
2953 }
2954 }
1fc79fb4
MD
2955 /* All is OK */
2956 err = 0;
3bd1e081
MD
2957end:
2958 DBG("polling thread exiting");
0e428499
DG
2959 free(pollfd);
2960 free(local_stream);
fb3a43a9
DG
2961
2962 /*
2963 * Close the write side of the pipe so epoll_wait() in
7d980def
DG
2964 * consumer_thread_metadata_poll can catch it. The thread is monitoring the
2965 * read side of the pipe. If we close them both, epoll_wait strangely does
2966 * not return and could create a endless wait period if the pipe is the
2967 * only tracked fd in the poll set. The thread will take care of closing
2968 * the read side.
fb3a43a9 2969 */
13886d2d 2970 (void) lttng_pipe_write_close(ctx->consumer_metadata_pipe);
fb3a43a9 2971
2d57de81 2972error_testpoint:
1fc79fb4
MD
2973 if (err) {
2974 health_error();
2975 ERR("Health error occurred in %s", __func__);
2976 }
2977 health_unregister(health_consumerd);
2978
e7b994a3 2979 rcu_unregister_thread();
3bd1e081
MD
2980 return NULL;
2981}
2982
d8ef542d
MD
2983/*
2984 * Close wake-up end of each stream belonging to the channel. This will
2985 * allow the poll() on the stream read-side to detect when the
2986 * write-side (application) finally closes them.
2987 */
2988static
2989void consumer_close_channel_streams(struct lttng_consumer_channel *channel)
2990{
2991 struct lttng_ht *ht;
2992 struct lttng_consumer_stream *stream;
2993 struct lttng_ht_iter iter;
2994
2995 ht = consumer_data.stream_per_chan_id_ht;
2996
2997 rcu_read_lock();
2998 cds_lfht_for_each_entry_duplicate(ht->ht,
2999 ht->hash_fct(&channel->key, lttng_ht_seed),
3000 ht->match_fct, &channel->key,
3001 &iter.iter, stream, node_channel_id.node) {
f2ad556d
MD
3002 /*
3003 * Protect against teardown with mutex.
3004 */
3005 pthread_mutex_lock(&stream->lock);
3006 if (cds_lfht_is_node_deleted(&stream->node.node)) {
3007 goto next;
3008 }
d8ef542d
MD
3009 switch (consumer_data.type) {
3010 case LTTNG_CONSUMER_KERNEL:
3011 break;
3012 case LTTNG_CONSUMER32_UST:
3013 case LTTNG_CONSUMER64_UST:
b4a650f3
DG
3014 if (stream->metadata_flag) {
3015 /* Safe and protected by the stream lock. */
3016 lttng_ustconsumer_close_metadata(stream->chan);
3017 } else {
3018 /*
3019 * Note: a mutex is taken internally within
3020 * liblttng-ust-ctl to protect timer wakeup_fd
3021 * use from concurrent close.
3022 */
3023 lttng_ustconsumer_close_stream_wakeup(stream);
3024 }
d8ef542d
MD
3025 break;
3026 default:
3027 ERR("Unknown consumer_data type");
3028 assert(0);
3029 }
f2ad556d
MD
3030 next:
3031 pthread_mutex_unlock(&stream->lock);
d8ef542d
MD
3032 }
3033 rcu_read_unlock();
3034}
3035
3036static void destroy_channel_ht(struct lttng_ht *ht)
3037{
3038 struct lttng_ht_iter iter;
3039 struct lttng_consumer_channel *channel;
3040 int ret;
3041
3042 if (ht == NULL) {
3043 return;
3044 }
3045
3046 rcu_read_lock();
3047 cds_lfht_for_each_entry(ht->ht, &iter.iter, channel, wait_fd_node.node) {
3048 ret = lttng_ht_del(ht, &iter);
3049 assert(ret != 0);
3050 }
3051 rcu_read_unlock();
3052
3053 lttng_ht_destroy(ht);
3054}
3055
3056/*
3057 * This thread polls the channel fds to detect when they are being
3058 * closed. It closes all related streams if the channel is detected as
3059 * closed. It is currently only used as a shim layer for UST because the
3060 * consumerd needs to keep the per-stream wakeup end of pipes open for
3061 * periodical flush.
3062 */
3063void *consumer_thread_channel_poll(void *data)
3064{
1fc79fb4 3065 int ret, i, pollfd, err = -1;
d8ef542d
MD
3066 uint32_t revents, nb_fd;
3067 struct lttng_consumer_channel *chan = NULL;
3068 struct lttng_ht_iter iter;
3069 struct lttng_ht_node_u64 *node;
3070 struct lttng_poll_event events;
3071 struct lttng_consumer_local_data *ctx = data;
3072 struct lttng_ht *channel_ht;
3073
3074 rcu_register_thread();
3075
1fc79fb4
MD
3076 health_register(health_consumerd, HEALTH_CONSUMERD_TYPE_CHANNEL);
3077
2d57de81
MD
3078 if (testpoint(consumerd_thread_channel)) {
3079 goto error_testpoint;
3080 }
3081
9ce5646a
MD
3082 health_code_update();
3083
d8ef542d
MD
3084 channel_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
3085 if (!channel_ht) {
3086 /* ENOMEM at this point. Better to bail out. */
3087 goto end_ht;
3088 }
3089
3090 DBG("Thread channel poll started");
3091
3092 /* Size is set to 1 for the consumer_channel pipe */
3093 ret = lttng_poll_create(&events, 2, LTTNG_CLOEXEC);
3094 if (ret < 0) {
3095 ERR("Poll set creation failed");
3096 goto end_poll;
3097 }
3098
3099 ret = lttng_poll_add(&events, ctx->consumer_channel_pipe[0], LPOLLIN);
3100 if (ret < 0) {
3101 goto end;
3102 }
3103
3104 /* Main loop */
3105 DBG("Channel main loop started");
3106
3107 while (1) {
d8ef542d 3108restart:
7fa2082e
MD
3109 health_code_update();
3110 DBG("Channel poll wait");
9ce5646a 3111 health_poll_entry();
d8ef542d 3112 ret = lttng_poll_wait(&events, -1);
7fa2082e
MD
3113 DBG("Channel poll return from wait with %d fd(s)",
3114 LTTNG_POLL_GETNB(&events));
9ce5646a 3115 health_poll_exit();
40063ead 3116 DBG("Channel event caught in thread");
d8ef542d
MD
3117 if (ret < 0) {
3118 if (errno == EINTR) {
40063ead 3119 ERR("Poll EINTR caught");
d8ef542d
MD
3120 goto restart;
3121 }
d9607cd7
MD
3122 if (LTTNG_POLL_GETNB(&events) == 0) {
3123 err = 0; /* All is OK */
3124 }
d8ef542d
MD
3125 goto end;
3126 }
3127
3128 nb_fd = ret;
3129
3130 /* From here, the event is a channel wait fd */
3131 for (i = 0; i < nb_fd; i++) {
9ce5646a
MD
3132 health_code_update();
3133
d8ef542d
MD
3134 revents = LTTNG_POLL_GETEV(&events, i);
3135 pollfd = LTTNG_POLL_GETFD(&events, i);
3136
d8ef542d 3137 if (pollfd == ctx->consumer_channel_pipe[0]) {
03e43155 3138 if (revents & LPOLLIN) {
d8ef542d 3139 enum consumer_channel_action action;
a0cbdd2e 3140 uint64_t key;
d8ef542d 3141
a0cbdd2e 3142 ret = read_channel_pipe(ctx, &chan, &key, &action);
d8ef542d 3143 if (ret <= 0) {
03e43155
MD
3144 if (ret < 0) {
3145 ERR("Error reading channel pipe");
3146 }
3147 lttng_poll_del(&events, ctx->consumer_channel_pipe[0]);
d8ef542d
MD
3148 continue;
3149 }
3150
3151 switch (action) {
3152 case CONSUMER_CHANNEL_ADD:
3153 DBG("Adding channel %d to poll set",
3154 chan->wait_fd);
3155
3156 lttng_ht_node_init_u64(&chan->wait_fd_node,
3157 chan->wait_fd);
c7260a81 3158 rcu_read_lock();
d8ef542d
MD
3159 lttng_ht_add_unique_u64(channel_ht,
3160 &chan->wait_fd_node);
c7260a81 3161 rcu_read_unlock();
d8ef542d
MD
3162 /* Add channel to the global poll events list */
3163 lttng_poll_add(&events, chan->wait_fd,
03e43155 3164 LPOLLERR | LPOLLHUP);
d8ef542d 3165 break;
a0cbdd2e
MD
3166 case CONSUMER_CHANNEL_DEL:
3167 {
b4a650f3
DG
3168 /*
3169 * This command should never be called if the channel
3170 * has streams monitored by either the data or metadata
3171 * thread. The consumer only notify this thread with a
3172 * channel del. command if it receives a destroy
3173 * channel command from the session daemon that send it
3174 * if a command prior to the GET_CHANNEL failed.
3175 */
3176
c7260a81 3177 rcu_read_lock();
a0cbdd2e
MD
3178 chan = consumer_find_channel(key);
3179 if (!chan) {
c7260a81 3180 rcu_read_unlock();
a0cbdd2e
MD
3181 ERR("UST consumer get channel key %" PRIu64 " not found for del channel", key);
3182 break;
3183 }
3184 lttng_poll_del(&events, chan->wait_fd);
f623cc0b 3185 iter.iter.node = &chan->wait_fd_node.node;
a0cbdd2e
MD
3186 ret = lttng_ht_del(channel_ht, &iter);
3187 assert(ret == 0);
a0cbdd2e 3188
f2a444f1
DG
3189 switch (consumer_data.type) {
3190 case LTTNG_CONSUMER_KERNEL:
3191 break;
3192 case LTTNG_CONSUMER32_UST:
3193 case LTTNG_CONSUMER64_UST:
212d67a2
DG
3194 health_code_update();
3195 /* Destroy streams that might have been left in the stream list. */
3196 clean_channel_stream_list(chan);
f2a444f1
DG
3197 break;
3198 default:
3199 ERR("Unknown consumer_data type");
3200 assert(0);
3201 }
3202
a0cbdd2e
MD
3203 /*
3204 * Release our own refcount. Force channel deletion even if
3205 * streams were not initialized.
3206 */
3207 if (!uatomic_sub_return(&chan->refcount, 1)) {
3208 consumer_del_channel(chan);
3209 }
c7260a81 3210 rcu_read_unlock();
a0cbdd2e
MD
3211 goto restart;
3212 }
d8ef542d
MD
3213 case CONSUMER_CHANNEL_QUIT:
3214 /*
3215 * Remove the pipe from the poll set and continue the loop
3216 * since their might be data to consume.
3217 */
3218 lttng_poll_del(&events, ctx->consumer_channel_pipe[0]);
3219 continue;
3220 default:
3221 ERR("Unknown action");
3222 break;
3223 }
03e43155
MD
3224 } else if (revents & (LPOLLERR | LPOLLHUP)) {
3225 DBG("Channel thread pipe hung up");
3226 /*
3227 * Remove the pipe from the poll set and continue the loop
3228 * since their might be data to consume.
3229 */
3230 lttng_poll_del(&events, ctx->consumer_channel_pipe[0]);
3231 continue;
3232 } else {
3233 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
3234 goto end;
d8ef542d
MD
3235 }
3236