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