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