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