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