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