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