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