Clean-up: consumer: fix -Wshadow error in lttng_consumer_trace_chunk_exists
[lttng-tools.git] / src / common / consumer / consumer.c
1 /*
2 * Copyright (C) 2011 Julien Desfossez <julien.desfossez@polymtl.ca>
3 * Copyright (C) 2011 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
4 * Copyright (C) 2012 David Goulet <dgoulet@efficios.com>
5 *
6 * SPDX-License-Identifier: GPL-2.0-only
7 *
8 */
9
10 #include "common/index/ctf-index.h"
11 #define _LGPL_SOURCE
12 #include <assert.h>
13 #include <poll.h>
14 #include <pthread.h>
15 #include <stdlib.h>
16 #include <string.h>
17 #include <sys/mman.h>
18 #include <sys/socket.h>
19 #include <sys/types.h>
20 #include <unistd.h>
21 #include <inttypes.h>
22 #include <signal.h>
23
24 #include <bin/lttng-consumerd/health-consumerd.h>
25 #include <common/common.h>
26 #include <common/utils.h>
27 #include <common/time.h>
28 #include <common/compat/poll.h>
29 #include <common/compat/endian.h>
30 #include <common/index/index.h>
31 #include <common/kernel-ctl/kernel-ctl.h>
32 #include <common/sessiond-comm/relayd.h>
33 #include <common/sessiond-comm/sessiond-comm.h>
34 #include <common/kernel-consumer/kernel-consumer.h>
35 #include <common/relayd/relayd.h>
36 #include <common/ust-consumer/ust-consumer.h>
37 #include <common/consumer/consumer-timer.h>
38 #include <common/consumer/consumer.h>
39 #include <common/consumer/consumer-stream.h>
40 #include <common/consumer/consumer-testpoint.h>
41 #include <common/align.h>
42 #include <common/consumer/consumer-metadata-cache.h>
43 #include <common/trace-chunk.h>
44 #include <common/trace-chunk-registry.h>
45 #include <common/string-utils/format.h>
46 #include <common/dynamic-array.h>
47
48 struct lttng_consumer_global_data consumer_data = {
49 .stream_count = 0,
50 .need_update = 1,
51 .type = LTTNG_CONSUMER_UNKNOWN,
52 };
53
54 enum consumer_channel_action {
55 CONSUMER_CHANNEL_ADD,
56 CONSUMER_CHANNEL_DEL,
57 CONSUMER_CHANNEL_QUIT,
58 };
59
60 struct consumer_channel_msg {
61 enum consumer_channel_action action;
62 struct lttng_consumer_channel *chan; /* add */
63 uint64_t key; /* del */
64 };
65
66 /* Flag used to temporarily pause data consumption from testpoints. */
67 int data_consumption_paused;
68
69 /*
70 * Flag to inform the polling thread to quit when all fd hung up. Updated by
71 * the consumer_thread_receive_fds when it notices that all fds has hung up.
72 * Also updated by the signal handler (consumer_should_exit()). Read by the
73 * polling threads.
74 */
75 int consumer_quit;
76
77 /*
78 * Global hash table containing respectively metadata and data streams. The
79 * stream element in this ht should only be updated by the metadata poll thread
80 * for the metadata and the data poll thread for the data.
81 */
82 static struct lttng_ht *metadata_ht;
83 static struct lttng_ht *data_ht;
84
85 static const char *get_consumer_domain(void)
86 {
87 switch (consumer_data.type) {
88 case LTTNG_CONSUMER_KERNEL:
89 return DEFAULT_KERNEL_TRACE_DIR;
90 case LTTNG_CONSUMER64_UST:
91 /* Fall-through. */
92 case LTTNG_CONSUMER32_UST:
93 return DEFAULT_UST_TRACE_DIR;
94 default:
95 abort();
96 }
97 }
98
99 /*
100 * Notify a thread lttng pipe to poll back again. This usually means that some
101 * global state has changed so we just send back the thread in a poll wait
102 * call.
103 */
104 static void notify_thread_lttng_pipe(struct lttng_pipe *pipe)
105 {
106 struct lttng_consumer_stream *null_stream = NULL;
107
108 assert(pipe);
109
110 (void) lttng_pipe_write(pipe, &null_stream, sizeof(null_stream));
111 }
112
113 static void notify_health_quit_pipe(int *pipe)
114 {
115 ssize_t ret;
116
117 ret = lttng_write(pipe[1], "4", 1);
118 if (ret < 1) {
119 PERROR("write consumer health quit");
120 }
121 }
122
123 static void notify_channel_pipe(struct lttng_consumer_local_data *ctx,
124 struct lttng_consumer_channel *chan,
125 uint64_t key,
126 enum consumer_channel_action action)
127 {
128 struct consumer_channel_msg msg;
129 ssize_t ret;
130
131 memset(&msg, 0, sizeof(msg));
132
133 msg.action = action;
134 msg.chan = chan;
135 msg.key = key;
136 ret = lttng_write(ctx->consumer_channel_pipe[1], &msg, sizeof(msg));
137 if (ret < sizeof(msg)) {
138 PERROR("notify_channel_pipe write error");
139 }
140 }
141
142 void notify_thread_del_channel(struct lttng_consumer_local_data *ctx,
143 uint64_t key)
144 {
145 notify_channel_pipe(ctx, NULL, key, CONSUMER_CHANNEL_DEL);
146 }
147
148 static int read_channel_pipe(struct lttng_consumer_local_data *ctx,
149 struct lttng_consumer_channel **chan,
150 uint64_t *key,
151 enum consumer_channel_action *action)
152 {
153 struct consumer_channel_msg msg;
154 ssize_t ret;
155
156 ret = lttng_read(ctx->consumer_channel_pipe[0], &msg, sizeof(msg));
157 if (ret < sizeof(msg)) {
158 ret = -1;
159 goto error;
160 }
161 *action = msg.action;
162 *chan = msg.chan;
163 *key = msg.key;
164 error:
165 return (int) ret;
166 }
167
168 /*
169 * Cleanup the stream list of a channel. Those streams are not yet globally
170 * visible
171 */
172 static void clean_channel_stream_list(struct lttng_consumer_channel *channel)
173 {
174 struct lttng_consumer_stream *stream, *stmp;
175
176 assert(channel);
177
178 /* Delete streams that might have been left in the stream list. */
179 cds_list_for_each_entry_safe(stream, stmp, &channel->streams.head,
180 send_node) {
181 cds_list_del(&stream->send_node);
182 /*
183 * Once a stream is added to this list, the buffers were created so we
184 * have a guarantee that this call will succeed. Setting the monitor
185 * mode to 0 so we don't lock nor try to delete the stream from the
186 * global hash table.
187 */
188 stream->monitor = 0;
189 consumer_stream_destroy(stream, NULL);
190 }
191 }
192
193 /*
194 * Find a stream. The consumer_data.lock must be locked during this
195 * call.
196 */
197 static struct lttng_consumer_stream *find_stream(uint64_t key,
198 struct lttng_ht *ht)
199 {
200 struct lttng_ht_iter iter;
201 struct lttng_ht_node_u64 *node;
202 struct lttng_consumer_stream *stream = NULL;
203
204 assert(ht);
205
206 /* -1ULL keys are lookup failures */
207 if (key == (uint64_t) -1ULL) {
208 return NULL;
209 }
210
211 rcu_read_lock();
212
213 lttng_ht_lookup(ht, &key, &iter);
214 node = lttng_ht_iter_get_node_u64(&iter);
215 if (node != NULL) {
216 stream = caa_container_of(node, struct lttng_consumer_stream, node);
217 }
218
219 rcu_read_unlock();
220
221 return stream;
222 }
223
224 static void steal_stream_key(uint64_t key, struct lttng_ht *ht)
225 {
226 struct lttng_consumer_stream *stream;
227
228 rcu_read_lock();
229 stream = find_stream(key, ht);
230 if (stream) {
231 stream->key = (uint64_t) -1ULL;
232 /*
233 * We don't want the lookup to match, but we still need
234 * to iterate on this stream when iterating over the hash table. Just
235 * change the node key.
236 */
237 stream->node.key = (uint64_t) -1ULL;
238 }
239 rcu_read_unlock();
240 }
241
242 /*
243 * Return a channel object for the given key.
244 *
245 * RCU read side lock MUST be acquired before calling this function and
246 * protects the channel ptr.
247 */
248 struct lttng_consumer_channel *consumer_find_channel(uint64_t key)
249 {
250 struct lttng_ht_iter iter;
251 struct lttng_ht_node_u64 *node;
252 struct lttng_consumer_channel *channel = NULL;
253
254 /* -1ULL keys are lookup failures */
255 if (key == (uint64_t) -1ULL) {
256 return NULL;
257 }
258
259 lttng_ht_lookup(consumer_data.channel_ht, &key, &iter);
260 node = lttng_ht_iter_get_node_u64(&iter);
261 if (node != NULL) {
262 channel = caa_container_of(node, struct lttng_consumer_channel, node);
263 }
264
265 return channel;
266 }
267
268 /*
269 * There is a possibility that the consumer does not have enough time between
270 * the close of the channel on the session daemon and the cleanup in here thus
271 * once we have a channel add with an existing key, we know for sure that this
272 * channel will eventually get cleaned up by all streams being closed.
273 *
274 * This function just nullifies the already existing channel key.
275 */
276 static void steal_channel_key(uint64_t key)
277 {
278 struct lttng_consumer_channel *channel;
279
280 rcu_read_lock();
281 channel = consumer_find_channel(key);
282 if (channel) {
283 channel->key = (uint64_t) -1ULL;
284 /*
285 * We don't want the lookup to match, but we still need to iterate on
286 * this channel when iterating over the hash table. Just change the
287 * node key.
288 */
289 channel->node.key = (uint64_t) -1ULL;
290 }
291 rcu_read_unlock();
292 }
293
294 static void free_channel_rcu(struct rcu_head *head)
295 {
296 struct lttng_ht_node_u64 *node =
297 caa_container_of(head, struct lttng_ht_node_u64, head);
298 struct lttng_consumer_channel *channel =
299 caa_container_of(node, struct lttng_consumer_channel, node);
300
301 switch (consumer_data.type) {
302 case LTTNG_CONSUMER_KERNEL:
303 break;
304 case LTTNG_CONSUMER32_UST:
305 case LTTNG_CONSUMER64_UST:
306 lttng_ustconsumer_free_channel(channel);
307 break;
308 default:
309 ERR("Unknown consumer_data type");
310 abort();
311 }
312 free(channel);
313 }
314
315 /*
316 * RCU protected relayd socket pair free.
317 */
318 static void free_relayd_rcu(struct rcu_head *head)
319 {
320 struct lttng_ht_node_u64 *node =
321 caa_container_of(head, struct lttng_ht_node_u64, head);
322 struct consumer_relayd_sock_pair *relayd =
323 caa_container_of(node, struct consumer_relayd_sock_pair, node);
324
325 /*
326 * Close all sockets. This is done in the call RCU since we don't want the
327 * socket fds to be reassigned thus potentially creating bad state of the
328 * relayd object.
329 *
330 * We do not have to lock the control socket mutex here since at this stage
331 * there is no one referencing to this relayd object.
332 */
333 (void) relayd_close(&relayd->control_sock);
334 (void) relayd_close(&relayd->data_sock);
335
336 pthread_mutex_destroy(&relayd->ctrl_sock_mutex);
337 free(relayd);
338 }
339
340 /*
341 * Destroy and free relayd socket pair object.
342 */
343 void consumer_destroy_relayd(struct consumer_relayd_sock_pair *relayd)
344 {
345 int ret;
346 struct lttng_ht_iter iter;
347
348 if (relayd == NULL) {
349 return;
350 }
351
352 DBG("Consumer destroy and close relayd socket pair");
353
354 iter.iter.node = &relayd->node.node;
355 ret = lttng_ht_del(consumer_data.relayd_ht, &iter);
356 if (ret != 0) {
357 /* We assume the relayd is being or is destroyed */
358 return;
359 }
360
361 /* RCU free() call */
362 call_rcu(&relayd->node.head, free_relayd_rcu);
363 }
364
365 /*
366 * Remove a channel from the global list protected by a mutex. This function is
367 * also responsible for freeing its data structures.
368 */
369 void consumer_del_channel(struct lttng_consumer_channel *channel)
370 {
371 struct lttng_ht_iter iter;
372
373 DBG("Consumer delete channel key %" PRIu64, channel->key);
374
375 pthread_mutex_lock(&consumer_data.lock);
376 pthread_mutex_lock(&channel->lock);
377
378 /* Destroy streams that might have been left in the stream list. */
379 clean_channel_stream_list(channel);
380
381 if (channel->live_timer_enabled == 1) {
382 consumer_timer_live_stop(channel);
383 }
384 if (channel->monitor_timer_enabled == 1) {
385 consumer_timer_monitor_stop(channel);
386 }
387
388 switch (consumer_data.type) {
389 case LTTNG_CONSUMER_KERNEL:
390 break;
391 case LTTNG_CONSUMER32_UST:
392 case LTTNG_CONSUMER64_UST:
393 lttng_ustconsumer_del_channel(channel);
394 break;
395 default:
396 ERR("Unknown consumer_data type");
397 assert(0);
398 goto end;
399 }
400
401 lttng_trace_chunk_put(channel->trace_chunk);
402 channel->trace_chunk = NULL;
403
404 if (channel->is_published) {
405 int ret;
406
407 rcu_read_lock();
408 iter.iter.node = &channel->node.node;
409 ret = lttng_ht_del(consumer_data.channel_ht, &iter);
410 assert(!ret);
411
412 iter.iter.node = &channel->channels_by_session_id_ht_node.node;
413 ret = lttng_ht_del(consumer_data.channels_by_session_id_ht,
414 &iter);
415 assert(!ret);
416 rcu_read_unlock();
417 }
418
419 channel->is_deleted = true;
420 call_rcu(&channel->node.head, free_channel_rcu);
421 end:
422 pthread_mutex_unlock(&channel->lock);
423 pthread_mutex_unlock(&consumer_data.lock);
424 }
425
426 /*
427 * Iterate over the relayd hash table and destroy each element. Finally,
428 * destroy the whole hash table.
429 */
430 static void cleanup_relayd_ht(void)
431 {
432 struct lttng_ht_iter iter;
433 struct consumer_relayd_sock_pair *relayd;
434
435 rcu_read_lock();
436
437 cds_lfht_for_each_entry(consumer_data.relayd_ht->ht, &iter.iter, relayd,
438 node.node) {
439 consumer_destroy_relayd(relayd);
440 }
441
442 rcu_read_unlock();
443
444 lttng_ht_destroy(consumer_data.relayd_ht);
445 }
446
447 /*
448 * Update the end point status of all streams having the given network sequence
449 * index (relayd index).
450 *
451 * It's atomically set without having the stream mutex locked which is fine
452 * because we handle the write/read race with a pipe wakeup for each thread.
453 */
454 static void update_endpoint_status_by_netidx(uint64_t net_seq_idx,
455 enum consumer_endpoint_status status)
456 {
457 struct lttng_ht_iter iter;
458 struct lttng_consumer_stream *stream;
459
460 DBG("Consumer set delete flag on stream by idx %" PRIu64, net_seq_idx);
461
462 rcu_read_lock();
463
464 /* Let's begin with metadata */
465 cds_lfht_for_each_entry(metadata_ht->ht, &iter.iter, stream, node.node) {
466 if (stream->net_seq_idx == net_seq_idx) {
467 uatomic_set(&stream->endpoint_status, status);
468 DBG("Delete flag set to metadata stream %d", stream->wait_fd);
469 }
470 }
471
472 /* Follow up by the data streams */
473 cds_lfht_for_each_entry(data_ht->ht, &iter.iter, stream, node.node) {
474 if (stream->net_seq_idx == net_seq_idx) {
475 uatomic_set(&stream->endpoint_status, status);
476 DBG("Delete flag set to data stream %d", stream->wait_fd);
477 }
478 }
479 rcu_read_unlock();
480 }
481
482 /*
483 * Cleanup a relayd object by flagging every associated streams for deletion,
484 * destroying the object meaning removing it from the relayd hash table,
485 * closing the sockets and freeing the memory in a RCU call.
486 *
487 * If a local data context is available, notify the threads that the streams'
488 * state have changed.
489 */
490 void lttng_consumer_cleanup_relayd(struct consumer_relayd_sock_pair *relayd)
491 {
492 uint64_t netidx;
493
494 assert(relayd);
495
496 DBG("Cleaning up relayd object ID %"PRIu64, relayd->net_seq_idx);
497
498 /* Save the net sequence index before destroying the object */
499 netidx = relayd->net_seq_idx;
500
501 /*
502 * Delete the relayd from the relayd hash table, close the sockets and free
503 * the object in a RCU call.
504 */
505 consumer_destroy_relayd(relayd);
506
507 /* Set inactive endpoint to all streams */
508 update_endpoint_status_by_netidx(netidx, CONSUMER_ENDPOINT_INACTIVE);
509
510 /*
511 * With a local data context, notify the threads that the streams' state
512 * have changed. The write() action on the pipe acts as an "implicit"
513 * memory barrier ordering the updates of the end point status from the
514 * read of this status which happens AFTER receiving this notify.
515 */
516 notify_thread_lttng_pipe(relayd->ctx->consumer_data_pipe);
517 notify_thread_lttng_pipe(relayd->ctx->consumer_metadata_pipe);
518 }
519
520 /*
521 * Flag a relayd socket pair for destruction. Destroy it if the refcount
522 * reaches zero.
523 *
524 * RCU read side lock MUST be aquired before calling this function.
525 */
526 void consumer_flag_relayd_for_destroy(struct consumer_relayd_sock_pair *relayd)
527 {
528 assert(relayd);
529
530 /* Set destroy flag for this object */
531 uatomic_set(&relayd->destroy_flag, 1);
532
533 /* Destroy the relayd if refcount is 0 */
534 if (uatomic_read(&relayd->refcount) == 0) {
535 consumer_destroy_relayd(relayd);
536 }
537 }
538
539 /*
540 * Completly destroy stream from every visiable data structure and the given
541 * hash table if one.
542 *
543 * One this call returns, the stream object is not longer usable nor visible.
544 */
545 void consumer_del_stream(struct lttng_consumer_stream *stream,
546 struct lttng_ht *ht)
547 {
548 consumer_stream_destroy(stream, ht);
549 }
550
551 /*
552 * XXX naming of del vs destroy is all mixed up.
553 */
554 void consumer_del_stream_for_data(struct lttng_consumer_stream *stream)
555 {
556 consumer_stream_destroy(stream, data_ht);
557 }
558
559 void consumer_del_stream_for_metadata(struct lttng_consumer_stream *stream)
560 {
561 consumer_stream_destroy(stream, metadata_ht);
562 }
563
564 void consumer_stream_update_channel_attributes(
565 struct lttng_consumer_stream *stream,
566 struct lttng_consumer_channel *channel)
567 {
568 stream->channel_read_only_attributes.tracefile_size =
569 channel->tracefile_size;
570 }
571
572 /*
573 * Add a stream to the global list protected by a mutex.
574 */
575 void consumer_add_data_stream(struct lttng_consumer_stream *stream)
576 {
577 struct lttng_ht *ht = data_ht;
578
579 assert(stream);
580 assert(ht);
581
582 DBG3("Adding consumer stream %" PRIu64, stream->key);
583
584 pthread_mutex_lock(&consumer_data.lock);
585 pthread_mutex_lock(&stream->chan->lock);
586 pthread_mutex_lock(&stream->chan->timer_lock);
587 pthread_mutex_lock(&stream->lock);
588 rcu_read_lock();
589
590 /* Steal stream identifier to avoid having streams with the same key */
591 steal_stream_key(stream->key, ht);
592
593 lttng_ht_add_unique_u64(ht, &stream->node);
594
595 lttng_ht_add_u64(consumer_data.stream_per_chan_id_ht,
596 &stream->node_channel_id);
597
598 /*
599 * Add stream to the stream_list_ht of the consumer data. No need to steal
600 * the key since the HT does not use it and we allow to add redundant keys
601 * into this table.
602 */
603 lttng_ht_add_u64(consumer_data.stream_list_ht, &stream->node_session_id);
604
605 /*
606 * When nb_init_stream_left reaches 0, we don't need to trigger any action
607 * in terms of destroying the associated channel, because the action that
608 * causes the count to become 0 also causes a stream to be added. The
609 * channel deletion will thus be triggered by the following removal of this
610 * stream.
611 */
612 if (uatomic_read(&stream->chan->nb_init_stream_left) > 0) {
613 /* Increment refcount before decrementing nb_init_stream_left */
614 cmm_smp_wmb();
615 uatomic_dec(&stream->chan->nb_init_stream_left);
616 }
617
618 /* Update consumer data once the node is inserted. */
619 consumer_data.stream_count++;
620 consumer_data.need_update = 1;
621
622 rcu_read_unlock();
623 pthread_mutex_unlock(&stream->lock);
624 pthread_mutex_unlock(&stream->chan->timer_lock);
625 pthread_mutex_unlock(&stream->chan->lock);
626 pthread_mutex_unlock(&consumer_data.lock);
627 }
628
629 /*
630 * Add relayd socket to global consumer data hashtable. RCU read side lock MUST
631 * be acquired before calling this.
632 */
633 static int add_relayd(struct consumer_relayd_sock_pair *relayd)
634 {
635 int ret = 0;
636 struct lttng_ht_node_u64 *node;
637 struct lttng_ht_iter iter;
638
639 assert(relayd);
640
641 lttng_ht_lookup(consumer_data.relayd_ht,
642 &relayd->net_seq_idx, &iter);
643 node = lttng_ht_iter_get_node_u64(&iter);
644 if (node != NULL) {
645 goto end;
646 }
647 lttng_ht_add_unique_u64(consumer_data.relayd_ht, &relayd->node);
648
649 end:
650 return ret;
651 }
652
653 /*
654 * Allocate and return a consumer relayd socket.
655 */
656 static struct consumer_relayd_sock_pair *consumer_allocate_relayd_sock_pair(
657 uint64_t net_seq_idx)
658 {
659 struct consumer_relayd_sock_pair *obj = NULL;
660
661 /* net sequence index of -1 is a failure */
662 if (net_seq_idx == (uint64_t) -1ULL) {
663 goto error;
664 }
665
666 obj = zmalloc(sizeof(struct consumer_relayd_sock_pair));
667 if (obj == NULL) {
668 PERROR("zmalloc relayd sock");
669 goto error;
670 }
671
672 obj->net_seq_idx = net_seq_idx;
673 obj->refcount = 0;
674 obj->destroy_flag = 0;
675 obj->control_sock.sock.fd = -1;
676 obj->data_sock.sock.fd = -1;
677 lttng_ht_node_init_u64(&obj->node, obj->net_seq_idx);
678 pthread_mutex_init(&obj->ctrl_sock_mutex, NULL);
679
680 error:
681 return obj;
682 }
683
684 /*
685 * Find a relayd socket pair in the global consumer data.
686 *
687 * Return the object if found else NULL.
688 * RCU read-side lock must be held across this call and while using the
689 * returned object.
690 */
691 struct consumer_relayd_sock_pair *consumer_find_relayd(uint64_t key)
692 {
693 struct lttng_ht_iter iter;
694 struct lttng_ht_node_u64 *node;
695 struct consumer_relayd_sock_pair *relayd = NULL;
696
697 /* Negative keys are lookup failures */
698 if (key == (uint64_t) -1ULL) {
699 goto error;
700 }
701
702 lttng_ht_lookup(consumer_data.relayd_ht, &key,
703 &iter);
704 node = lttng_ht_iter_get_node_u64(&iter);
705 if (node != NULL) {
706 relayd = caa_container_of(node, struct consumer_relayd_sock_pair, node);
707 }
708
709 error:
710 return relayd;
711 }
712
713 /*
714 * Find a relayd and send the stream
715 *
716 * Returns 0 on success, < 0 on error
717 */
718 int consumer_send_relayd_stream(struct lttng_consumer_stream *stream,
719 char *path)
720 {
721 int ret = 0;
722 struct consumer_relayd_sock_pair *relayd;
723
724 assert(stream);
725 assert(stream->net_seq_idx != -1ULL);
726 assert(path);
727
728 /* The stream is not metadata. Get relayd reference if exists. */
729 rcu_read_lock();
730 relayd = consumer_find_relayd(stream->net_seq_idx);
731 if (relayd != NULL) {
732 /* Add stream on the relayd */
733 pthread_mutex_lock(&relayd->ctrl_sock_mutex);
734 ret = relayd_add_stream(&relayd->control_sock, stream->name,
735 get_consumer_domain(), path, &stream->relayd_stream_id,
736 stream->chan->tracefile_size,
737 stream->chan->tracefile_count,
738 stream->trace_chunk);
739 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
740 if (ret < 0) {
741 ERR("Relayd add stream failed. Cleaning up relayd %" PRIu64".", relayd->net_seq_idx);
742 lttng_consumer_cleanup_relayd(relayd);
743 goto end;
744 }
745
746 uatomic_inc(&relayd->refcount);
747 stream->sent_to_relayd = 1;
748 } else {
749 ERR("Stream %" PRIu64 " relayd ID %" PRIu64 " unknown. Can't send it.",
750 stream->key, stream->net_seq_idx);
751 ret = -1;
752 goto end;
753 }
754
755 DBG("Stream %s with key %" PRIu64 " sent to relayd id %" PRIu64,
756 stream->name, stream->key, stream->net_seq_idx);
757
758 end:
759 rcu_read_unlock();
760 return ret;
761 }
762
763 /*
764 * Find a relayd and send the streams sent message
765 *
766 * Returns 0 on success, < 0 on error
767 */
768 int consumer_send_relayd_streams_sent(uint64_t net_seq_idx)
769 {
770 int ret = 0;
771 struct consumer_relayd_sock_pair *relayd;
772
773 assert(net_seq_idx != -1ULL);
774
775 /* The stream is not metadata. Get relayd reference if exists. */
776 rcu_read_lock();
777 relayd = consumer_find_relayd(net_seq_idx);
778 if (relayd != NULL) {
779 /* Add stream on the relayd */
780 pthread_mutex_lock(&relayd->ctrl_sock_mutex);
781 ret = relayd_streams_sent(&relayd->control_sock);
782 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
783 if (ret < 0) {
784 ERR("Relayd streams sent failed. Cleaning up relayd %" PRIu64".", relayd->net_seq_idx);
785 lttng_consumer_cleanup_relayd(relayd);
786 goto end;
787 }
788 } else {
789 ERR("Relayd ID %" PRIu64 " unknown. Can't send streams_sent.",
790 net_seq_idx);
791 ret = -1;
792 goto end;
793 }
794
795 ret = 0;
796 DBG("All streams sent relayd id %" PRIu64, net_seq_idx);
797
798 end:
799 rcu_read_unlock();
800 return ret;
801 }
802
803 /*
804 * Find a relayd and close the stream
805 */
806 void close_relayd_stream(struct lttng_consumer_stream *stream)
807 {
808 struct consumer_relayd_sock_pair *relayd;
809
810 /* The stream is not metadata. Get relayd reference if exists. */
811 rcu_read_lock();
812 relayd = consumer_find_relayd(stream->net_seq_idx);
813 if (relayd) {
814 consumer_stream_relayd_close(stream, relayd);
815 }
816 rcu_read_unlock();
817 }
818
819 /*
820 * Handle stream for relayd transmission if the stream applies for network
821 * streaming where the net sequence index is set.
822 *
823 * Return destination file descriptor or negative value on error.
824 */
825 static int write_relayd_stream_header(struct lttng_consumer_stream *stream,
826 size_t data_size, unsigned long padding,
827 struct consumer_relayd_sock_pair *relayd)
828 {
829 int outfd = -1, ret;
830 struct lttcomm_relayd_data_hdr data_hdr;
831
832 /* Safety net */
833 assert(stream);
834 assert(relayd);
835
836 /* Reset data header */
837 memset(&data_hdr, 0, sizeof(data_hdr));
838
839 if (stream->metadata_flag) {
840 /* Caller MUST acquire the relayd control socket lock */
841 ret = relayd_send_metadata(&relayd->control_sock, data_size);
842 if (ret < 0) {
843 goto error;
844 }
845
846 /* Metadata are always sent on the control socket. */
847 outfd = relayd->control_sock.sock.fd;
848 } else {
849 /* Set header with stream information */
850 data_hdr.stream_id = htobe64(stream->relayd_stream_id);
851 data_hdr.data_size = htobe32(data_size);
852 data_hdr.padding_size = htobe32(padding);
853
854 /*
855 * Note that net_seq_num below is assigned with the *current* value of
856 * next_net_seq_num and only after that the next_net_seq_num will be
857 * increment. This is why when issuing a command on the relayd using
858 * this next value, 1 should always be substracted in order to compare
859 * the last seen sequence number on the relayd side to the last sent.
860 */
861 data_hdr.net_seq_num = htobe64(stream->next_net_seq_num);
862 /* Other fields are zeroed previously */
863
864 ret = relayd_send_data_hdr(&relayd->data_sock, &data_hdr,
865 sizeof(data_hdr));
866 if (ret < 0) {
867 goto error;
868 }
869
870 ++stream->next_net_seq_num;
871
872 /* Set to go on data socket */
873 outfd = relayd->data_sock.sock.fd;
874 }
875
876 error:
877 return outfd;
878 }
879
880 /*
881 * Write a character on the metadata poll pipe to wake the metadata thread.
882 * Returns 0 on success, -1 on error.
883 */
884 int consumer_metadata_wakeup_pipe(const struct lttng_consumer_channel *channel)
885 {
886 int ret = 0;
887
888 DBG("Waking up metadata poll thread (writing to pipe): channel name = '%s'",
889 channel->name);
890 if (channel->monitor && channel->metadata_stream) {
891 const char dummy = 'c';
892 const ssize_t write_ret = lttng_write(
893 channel->metadata_stream->ust_metadata_poll_pipe[1],
894 &dummy, 1);
895
896 if (write_ret < 1) {
897 if (errno == EWOULDBLOCK) {
898 /*
899 * This is fine, the metadata poll thread
900 * is having a hard time keeping-up, but
901 * it will eventually wake-up and consume
902 * the available data.
903 */
904 ret = 0;
905 } else {
906 PERROR("Failed to write to UST metadata pipe while attempting to wake-up the metadata poll thread");
907 ret = -1;
908 goto end;
909 }
910 }
911 }
912
913 end:
914 return ret;
915 }
916
917 /*
918 * Trigger a dump of the metadata content. Following/during the succesful
919 * completion of this call, the metadata poll thread will start receiving
920 * metadata packets to consume.
921 *
922 * The caller must hold the channel and stream locks.
923 */
924 static
925 int consumer_metadata_stream_dump(struct lttng_consumer_stream *stream)
926 {
927 int ret;
928
929 ASSERT_LOCKED(stream->chan->lock);
930 ASSERT_LOCKED(stream->lock);
931 assert(stream->metadata_flag);
932 assert(stream->chan->trace_chunk);
933
934 switch (consumer_data.type) {
935 case LTTNG_CONSUMER_KERNEL:
936 /*
937 * Reset the position of what has been read from the
938 * metadata cache to 0 so we can dump it again.
939 */
940 ret = kernctl_metadata_cache_dump(stream->wait_fd);
941 break;
942 case LTTNG_CONSUMER32_UST:
943 case LTTNG_CONSUMER64_UST:
944 /*
945 * Reset the position pushed from the metadata cache so it
946 * will write from the beginning on the next push.
947 */
948 stream->ust_metadata_pushed = 0;
949 ret = consumer_metadata_wakeup_pipe(stream->chan);
950 break;
951 default:
952 ERR("Unknown consumer_data type");
953 abort();
954 }
955 if (ret < 0) {
956 ERR("Failed to dump the metadata cache");
957 }
958 return ret;
959 }
960
961 static
962 int lttng_consumer_channel_set_trace_chunk(
963 struct lttng_consumer_channel *channel,
964 struct lttng_trace_chunk *new_trace_chunk)
965 {
966 pthread_mutex_lock(&channel->lock);
967 if (channel->is_deleted) {
968 /*
969 * The channel has been logically deleted and should no longer
970 * be used. It has released its reference to its current trace
971 * chunk and should not acquire a new one.
972 *
973 * Return success as there is nothing for the caller to do.
974 */
975 goto end;
976 }
977
978 /*
979 * The acquisition of the reference cannot fail (barring
980 * a severe internal error) since a reference to the published
981 * chunk is already held by the caller.
982 */
983 if (new_trace_chunk) {
984 const bool acquired_reference = lttng_trace_chunk_get(
985 new_trace_chunk);
986
987 assert(acquired_reference);
988 }
989
990 lttng_trace_chunk_put(channel->trace_chunk);
991 channel->trace_chunk = new_trace_chunk;
992 end:
993 pthread_mutex_unlock(&channel->lock);
994 return 0;
995 }
996
997 /*
998 * Allocate and return a new lttng_consumer_channel object using the given key
999 * to initialize the hash table node.
1000 *
1001 * On error, return NULL.
1002 */
1003 struct lttng_consumer_channel *consumer_allocate_channel(uint64_t key,
1004 uint64_t session_id,
1005 const uint64_t *chunk_id,
1006 const char *pathname,
1007 const char *name,
1008 uint64_t relayd_id,
1009 enum lttng_event_output output,
1010 uint64_t tracefile_size,
1011 uint64_t tracefile_count,
1012 uint64_t session_id_per_pid,
1013 unsigned int monitor,
1014 unsigned int live_timer_interval,
1015 bool is_in_live_session,
1016 const char *root_shm_path,
1017 const char *shm_path)
1018 {
1019 struct lttng_consumer_channel *channel = NULL;
1020 struct lttng_trace_chunk *trace_chunk = NULL;
1021
1022 if (chunk_id) {
1023 trace_chunk = lttng_trace_chunk_registry_find_chunk(
1024 consumer_data.chunk_registry, session_id,
1025 *chunk_id);
1026 if (!trace_chunk) {
1027 ERR("Failed to find trace chunk reference during creation of channel");
1028 goto end;
1029 }
1030 }
1031
1032 channel = zmalloc(sizeof(*channel));
1033 if (channel == NULL) {
1034 PERROR("malloc struct lttng_consumer_channel");
1035 goto end;
1036 }
1037
1038 channel->key = key;
1039 channel->refcount = 0;
1040 channel->session_id = session_id;
1041 channel->session_id_per_pid = session_id_per_pid;
1042 channel->relayd_id = relayd_id;
1043 channel->tracefile_size = tracefile_size;
1044 channel->tracefile_count = tracefile_count;
1045 channel->monitor = monitor;
1046 channel->live_timer_interval = live_timer_interval;
1047 channel->is_live = is_in_live_session;
1048 pthread_mutex_init(&channel->lock, NULL);
1049 pthread_mutex_init(&channel->timer_lock, NULL);
1050
1051 switch (output) {
1052 case LTTNG_EVENT_SPLICE:
1053 channel->output = CONSUMER_CHANNEL_SPLICE;
1054 break;
1055 case LTTNG_EVENT_MMAP:
1056 channel->output = CONSUMER_CHANNEL_MMAP;
1057 break;
1058 default:
1059 assert(0);
1060 free(channel);
1061 channel = NULL;
1062 goto end;
1063 }
1064
1065 /*
1066 * In monitor mode, the streams associated with the channel will be put in
1067 * a special list ONLY owned by this channel. So, the refcount is set to 1
1068 * here meaning that the channel itself has streams that are referenced.
1069 *
1070 * On a channel deletion, once the channel is no longer visible, the
1071 * refcount is decremented and checked for a zero value to delete it. With
1072 * streams in no monitor mode, it will now be safe to destroy the channel.
1073 */
1074 if (!channel->monitor) {
1075 channel->refcount = 1;
1076 }
1077
1078 strncpy(channel->pathname, pathname, sizeof(channel->pathname));
1079 channel->pathname[sizeof(channel->pathname) - 1] = '\0';
1080
1081 strncpy(channel->name, name, sizeof(channel->name));
1082 channel->name[sizeof(channel->name) - 1] = '\0';
1083
1084 if (root_shm_path) {
1085 strncpy(channel->root_shm_path, root_shm_path, sizeof(channel->root_shm_path));
1086 channel->root_shm_path[sizeof(channel->root_shm_path) - 1] = '\0';
1087 }
1088 if (shm_path) {
1089 strncpy(channel->shm_path, shm_path, sizeof(channel->shm_path));
1090 channel->shm_path[sizeof(channel->shm_path) - 1] = '\0';
1091 }
1092
1093 lttng_ht_node_init_u64(&channel->node, channel->key);
1094 lttng_ht_node_init_u64(&channel->channels_by_session_id_ht_node,
1095 channel->session_id);
1096
1097 channel->wait_fd = -1;
1098 CDS_INIT_LIST_HEAD(&channel->streams.head);
1099
1100 if (trace_chunk) {
1101 int ret = lttng_consumer_channel_set_trace_chunk(channel,
1102 trace_chunk);
1103 if (ret) {
1104 goto error;
1105 }
1106 }
1107
1108 DBG("Allocated channel (key %" PRIu64 ")", channel->key);
1109
1110 end:
1111 lttng_trace_chunk_put(trace_chunk);
1112 return channel;
1113 error:
1114 consumer_del_channel(channel);
1115 channel = NULL;
1116 goto end;
1117 }
1118
1119 /*
1120 * Add a channel to the global list protected by a mutex.
1121 *
1122 * Always return 0 indicating success.
1123 */
1124 int consumer_add_channel(struct lttng_consumer_channel *channel,
1125 struct lttng_consumer_local_data *ctx)
1126 {
1127 pthread_mutex_lock(&consumer_data.lock);
1128 pthread_mutex_lock(&channel->lock);
1129 pthread_mutex_lock(&channel->timer_lock);
1130
1131 /*
1132 * This gives us a guarantee that the channel we are about to add to the
1133 * channel hash table will be unique. See this function comment on the why
1134 * we need to steel the channel key at this stage.
1135 */
1136 steal_channel_key(channel->key);
1137
1138 rcu_read_lock();
1139 lttng_ht_add_unique_u64(consumer_data.channel_ht, &channel->node);
1140 lttng_ht_add_u64(consumer_data.channels_by_session_id_ht,
1141 &channel->channels_by_session_id_ht_node);
1142 rcu_read_unlock();
1143 channel->is_published = true;
1144
1145 pthread_mutex_unlock(&channel->timer_lock);
1146 pthread_mutex_unlock(&channel->lock);
1147 pthread_mutex_unlock(&consumer_data.lock);
1148
1149 if (channel->wait_fd != -1 && channel->type == CONSUMER_CHANNEL_TYPE_DATA) {
1150 notify_channel_pipe(ctx, channel, -1, CONSUMER_CHANNEL_ADD);
1151 }
1152
1153 return 0;
1154 }
1155
1156 /*
1157 * Allocate the pollfd structure and the local view of the out fds to avoid
1158 * doing a lookup in the linked list and concurrency issues when writing is
1159 * needed. Called with consumer_data.lock held.
1160 *
1161 * Returns the number of fds in the structures.
1162 */
1163 static int update_poll_array(struct lttng_consumer_local_data *ctx,
1164 struct pollfd **pollfd, struct lttng_consumer_stream **local_stream,
1165 struct lttng_ht *ht, int *nb_inactive_fd)
1166 {
1167 int i = 0;
1168 struct lttng_ht_iter iter;
1169 struct lttng_consumer_stream *stream;
1170
1171 assert(ctx);
1172 assert(ht);
1173 assert(pollfd);
1174 assert(local_stream);
1175
1176 DBG("Updating poll fd array");
1177 *nb_inactive_fd = 0;
1178 rcu_read_lock();
1179 cds_lfht_for_each_entry(ht->ht, &iter.iter, stream, node.node) {
1180 /*
1181 * Only active streams with an active end point can be added to the
1182 * poll set and local stream storage of the thread.
1183 *
1184 * There is a potential race here for endpoint_status to be updated
1185 * just after the check. However, this is OK since the stream(s) will
1186 * be deleted once the thread is notified that the end point state has
1187 * changed where this function will be called back again.
1188 *
1189 * We track the number of inactive FDs because they still need to be
1190 * closed by the polling thread after a wakeup on the data_pipe or
1191 * metadata_pipe.
1192 */
1193 if (stream->endpoint_status == CONSUMER_ENDPOINT_INACTIVE) {
1194 (*nb_inactive_fd)++;
1195 continue;
1196 }
1197 /*
1198 * This clobbers way too much the debug output. Uncomment that if you
1199 * need it for debugging purposes.
1200 */
1201 (*pollfd)[i].fd = stream->wait_fd;
1202 (*pollfd)[i].events = POLLIN | POLLPRI;
1203 local_stream[i] = stream;
1204 i++;
1205 }
1206 rcu_read_unlock();
1207
1208 /*
1209 * Insert the consumer_data_pipe at the end of the array and don't
1210 * increment i so nb_fd is the number of real FD.
1211 */
1212 (*pollfd)[i].fd = lttng_pipe_get_readfd(ctx->consumer_data_pipe);
1213 (*pollfd)[i].events = POLLIN | POLLPRI;
1214
1215 (*pollfd)[i + 1].fd = lttng_pipe_get_readfd(ctx->consumer_wakeup_pipe);
1216 (*pollfd)[i + 1].events = POLLIN | POLLPRI;
1217 return i;
1218 }
1219
1220 /*
1221 * Poll on the should_quit pipe and the command socket return -1 on
1222 * error, 1 if should exit, 0 if data is available on the command socket
1223 */
1224 int lttng_consumer_poll_socket(struct pollfd *consumer_sockpoll)
1225 {
1226 int num_rdy;
1227
1228 restart:
1229 num_rdy = poll(consumer_sockpoll, 2, -1);
1230 if (num_rdy == -1) {
1231 /*
1232 * Restart interrupted system call.
1233 */
1234 if (errno == EINTR) {
1235 goto restart;
1236 }
1237 PERROR("Poll error");
1238 return -1;
1239 }
1240 if (consumer_sockpoll[0].revents & (POLLIN | POLLPRI)) {
1241 DBG("consumer_should_quit wake up");
1242 return 1;
1243 }
1244 return 0;
1245 }
1246
1247 /*
1248 * Set the error socket.
1249 */
1250 void lttng_consumer_set_error_sock(struct lttng_consumer_local_data *ctx,
1251 int sock)
1252 {
1253 ctx->consumer_error_socket = sock;
1254 }
1255
1256 /*
1257 * Set the command socket path.
1258 */
1259 void lttng_consumer_set_command_sock_path(
1260 struct lttng_consumer_local_data *ctx, char *sock)
1261 {
1262 ctx->consumer_command_sock_path = sock;
1263 }
1264
1265 /*
1266 * Send return code to the session daemon.
1267 * If the socket is not defined, we return 0, it is not a fatal error
1268 */
1269 int lttng_consumer_send_error(struct lttng_consumer_local_data *ctx, int cmd)
1270 {
1271 if (ctx->consumer_error_socket > 0) {
1272 return lttcomm_send_unix_sock(ctx->consumer_error_socket, &cmd,
1273 sizeof(enum lttcomm_sessiond_command));
1274 }
1275
1276 return 0;
1277 }
1278
1279 /*
1280 * Close all the tracefiles and stream fds and MUST be called when all
1281 * instances are destroyed i.e. when all threads were joined and are ended.
1282 */
1283 void lttng_consumer_cleanup(void)
1284 {
1285 struct lttng_ht_iter iter;
1286 struct lttng_consumer_channel *channel;
1287 unsigned int trace_chunks_left;
1288
1289 rcu_read_lock();
1290
1291 cds_lfht_for_each_entry(consumer_data.channel_ht->ht, &iter.iter, channel,
1292 node.node) {
1293 consumer_del_channel(channel);
1294 }
1295
1296 rcu_read_unlock();
1297
1298 lttng_ht_destroy(consumer_data.channel_ht);
1299 lttng_ht_destroy(consumer_data.channels_by_session_id_ht);
1300
1301 cleanup_relayd_ht();
1302
1303 lttng_ht_destroy(consumer_data.stream_per_chan_id_ht);
1304
1305 /*
1306 * This HT contains streams that are freed by either the metadata thread or
1307 * the data thread so we do *nothing* on the hash table and simply destroy
1308 * it.
1309 */
1310 lttng_ht_destroy(consumer_data.stream_list_ht);
1311
1312 /*
1313 * Trace chunks in the registry may still exist if the session
1314 * daemon has encountered an internal error and could not
1315 * tear down its sessions and/or trace chunks properly.
1316 *
1317 * Release the session daemon's implicit reference to any remaining
1318 * trace chunk and print an error if any trace chunk was found. Note
1319 * that there are _no_ legitimate cases for trace chunks to be left,
1320 * it is a leak. However, it can happen following a crash of the
1321 * session daemon and not emptying the registry would cause an assertion
1322 * to hit.
1323 */
1324 trace_chunks_left = lttng_trace_chunk_registry_put_each_chunk(
1325 consumer_data.chunk_registry);
1326 if (trace_chunks_left) {
1327 ERR("%u trace chunks are leaked by lttng-consumerd. "
1328 "This can be caused by an internal error of the session daemon.",
1329 trace_chunks_left);
1330 }
1331 /* Run all callbacks freeing each chunk. */
1332 rcu_barrier();
1333 lttng_trace_chunk_registry_destroy(consumer_data.chunk_registry);
1334 }
1335
1336 /*
1337 * Called from signal handler.
1338 */
1339 void lttng_consumer_should_exit(struct lttng_consumer_local_data *ctx)
1340 {
1341 ssize_t ret;
1342
1343 CMM_STORE_SHARED(consumer_quit, 1);
1344 ret = lttng_write(ctx->consumer_should_quit[1], "4", 1);
1345 if (ret < 1) {
1346 PERROR("write consumer quit");
1347 }
1348
1349 DBG("Consumer flag that it should quit");
1350 }
1351
1352
1353 /*
1354 * Flush pending writes to trace output disk file.
1355 */
1356 static
1357 void lttng_consumer_sync_trace_file(struct lttng_consumer_stream *stream,
1358 off_t orig_offset)
1359 {
1360 int ret;
1361 int outfd = stream->out_fd;
1362
1363 /*
1364 * This does a blocking write-and-wait on any page that belongs to the
1365 * subbuffer prior to the one we just wrote.
1366 * Don't care about error values, as these are just hints and ways to
1367 * limit the amount of page cache used.
1368 */
1369 if (orig_offset < stream->max_sb_size) {
1370 return;
1371 }
1372 lttng_sync_file_range(outfd, orig_offset - stream->max_sb_size,
1373 stream->max_sb_size,
1374 SYNC_FILE_RANGE_WAIT_BEFORE
1375 | SYNC_FILE_RANGE_WRITE
1376 | SYNC_FILE_RANGE_WAIT_AFTER);
1377 /*
1378 * Give hints to the kernel about how we access the file:
1379 * POSIX_FADV_DONTNEED : we won't re-access data in a near future after
1380 * we write it.
1381 *
1382 * We need to call fadvise again after the file grows because the
1383 * kernel does not seem to apply fadvise to non-existing parts of the
1384 * file.
1385 *
1386 * Call fadvise _after_ having waited for the page writeback to
1387 * complete because the dirty page writeback semantic is not well
1388 * defined. So it can be expected to lead to lower throughput in
1389 * streaming.
1390 */
1391 ret = posix_fadvise(outfd, orig_offset - stream->max_sb_size,
1392 stream->max_sb_size, POSIX_FADV_DONTNEED);
1393 if (ret && ret != -ENOSYS) {
1394 errno = ret;
1395 PERROR("posix_fadvise on fd %i", outfd);
1396 }
1397 }
1398
1399 /*
1400 * Initialise the necessary environnement :
1401 * - create a new context
1402 * - create the poll_pipe
1403 * - create the should_quit pipe (for signal handler)
1404 * - create the thread pipe (for splice)
1405 *
1406 * Takes a function pointer as argument, this function is called when data is
1407 * available on a buffer. This function is responsible to do the
1408 * kernctl_get_next_subbuf, read the data with mmap or splice depending on the
1409 * buffer configuration and then kernctl_put_next_subbuf at the end.
1410 *
1411 * Returns a pointer to the new context or NULL on error.
1412 */
1413 struct lttng_consumer_local_data *lttng_consumer_create(
1414 enum lttng_consumer_type type,
1415 ssize_t (*buffer_ready)(struct lttng_consumer_stream *stream,
1416 struct lttng_consumer_local_data *ctx, bool locked_by_caller),
1417 int (*recv_channel)(struct lttng_consumer_channel *channel),
1418 int (*recv_stream)(struct lttng_consumer_stream *stream),
1419 int (*update_stream)(uint64_t stream_key, uint32_t state))
1420 {
1421 int ret;
1422 struct lttng_consumer_local_data *ctx;
1423
1424 assert(consumer_data.type == LTTNG_CONSUMER_UNKNOWN ||
1425 consumer_data.type == type);
1426 consumer_data.type = type;
1427
1428 ctx = zmalloc(sizeof(struct lttng_consumer_local_data));
1429 if (ctx == NULL) {
1430 PERROR("allocating context");
1431 goto error;
1432 }
1433
1434 ctx->consumer_error_socket = -1;
1435 ctx->consumer_metadata_socket = -1;
1436 pthread_mutex_init(&ctx->metadata_socket_lock, NULL);
1437 /* assign the callbacks */
1438 ctx->on_buffer_ready = buffer_ready;
1439 ctx->on_recv_channel = recv_channel;
1440 ctx->on_recv_stream = recv_stream;
1441 ctx->on_update_stream = update_stream;
1442
1443 ctx->consumer_data_pipe = lttng_pipe_open(0);
1444 if (!ctx->consumer_data_pipe) {
1445 goto error_poll_pipe;
1446 }
1447
1448 ctx->consumer_wakeup_pipe = lttng_pipe_open(0);
1449 if (!ctx->consumer_wakeup_pipe) {
1450 goto error_wakeup_pipe;
1451 }
1452
1453 ret = pipe(ctx->consumer_should_quit);
1454 if (ret < 0) {
1455 PERROR("Error creating recv pipe");
1456 goto error_quit_pipe;
1457 }
1458
1459 ret = pipe(ctx->consumer_channel_pipe);
1460 if (ret < 0) {
1461 PERROR("Error creating channel pipe");
1462 goto error_channel_pipe;
1463 }
1464
1465 ctx->consumer_metadata_pipe = lttng_pipe_open(0);
1466 if (!ctx->consumer_metadata_pipe) {
1467 goto error_metadata_pipe;
1468 }
1469
1470 ctx->channel_monitor_pipe = -1;
1471
1472 return ctx;
1473
1474 error_metadata_pipe:
1475 utils_close_pipe(ctx->consumer_channel_pipe);
1476 error_channel_pipe:
1477 utils_close_pipe(ctx->consumer_should_quit);
1478 error_quit_pipe:
1479 lttng_pipe_destroy(ctx->consumer_wakeup_pipe);
1480 error_wakeup_pipe:
1481 lttng_pipe_destroy(ctx->consumer_data_pipe);
1482 error_poll_pipe:
1483 free(ctx);
1484 error:
1485 return NULL;
1486 }
1487
1488 /*
1489 * Iterate over all streams of the hashtable and free them properly.
1490 */
1491 static void destroy_data_stream_ht(struct lttng_ht *ht)
1492 {
1493 struct lttng_ht_iter iter;
1494 struct lttng_consumer_stream *stream;
1495
1496 if (ht == NULL) {
1497 return;
1498 }
1499
1500 rcu_read_lock();
1501 cds_lfht_for_each_entry(ht->ht, &iter.iter, stream, node.node) {
1502 /*
1503 * Ignore return value since we are currently cleaning up so any error
1504 * can't be handled.
1505 */
1506 (void) consumer_del_stream(stream, ht);
1507 }
1508 rcu_read_unlock();
1509
1510 lttng_ht_destroy(ht);
1511 }
1512
1513 /*
1514 * Iterate over all streams of the metadata hashtable and free them
1515 * properly.
1516 */
1517 static void destroy_metadata_stream_ht(struct lttng_ht *ht)
1518 {
1519 struct lttng_ht_iter iter;
1520 struct lttng_consumer_stream *stream;
1521
1522 if (ht == NULL) {
1523 return;
1524 }
1525
1526 rcu_read_lock();
1527 cds_lfht_for_each_entry(ht->ht, &iter.iter, stream, node.node) {
1528 /*
1529 * Ignore return value since we are currently cleaning up so any error
1530 * can't be handled.
1531 */
1532 (void) consumer_del_metadata_stream(stream, ht);
1533 }
1534 rcu_read_unlock();
1535
1536 lttng_ht_destroy(ht);
1537 }
1538
1539 /*
1540 * Close all fds associated with the instance and free the context.
1541 */
1542 void lttng_consumer_destroy(struct lttng_consumer_local_data *ctx)
1543 {
1544 int ret;
1545
1546 DBG("Consumer destroying it. Closing everything.");
1547
1548 if (!ctx) {
1549 return;
1550 }
1551
1552 destroy_data_stream_ht(data_ht);
1553 destroy_metadata_stream_ht(metadata_ht);
1554
1555 ret = close(ctx->consumer_error_socket);
1556 if (ret) {
1557 PERROR("close");
1558 }
1559 ret = close(ctx->consumer_metadata_socket);
1560 if (ret) {
1561 PERROR("close");
1562 }
1563 utils_close_pipe(ctx->consumer_channel_pipe);
1564 lttng_pipe_destroy(ctx->consumer_data_pipe);
1565 lttng_pipe_destroy(ctx->consumer_metadata_pipe);
1566 lttng_pipe_destroy(ctx->consumer_wakeup_pipe);
1567 utils_close_pipe(ctx->consumer_should_quit);
1568
1569 unlink(ctx->consumer_command_sock_path);
1570 free(ctx);
1571 }
1572
1573 /*
1574 * Write the metadata stream id on the specified file descriptor.
1575 */
1576 static int write_relayd_metadata_id(int fd,
1577 struct lttng_consumer_stream *stream,
1578 unsigned long padding)
1579 {
1580 ssize_t ret;
1581 struct lttcomm_relayd_metadata_payload hdr;
1582
1583 hdr.stream_id = htobe64(stream->relayd_stream_id);
1584 hdr.padding_size = htobe32(padding);
1585 ret = lttng_write(fd, (void *) &hdr, sizeof(hdr));
1586 if (ret < sizeof(hdr)) {
1587 /*
1588 * This error means that the fd's end is closed so ignore the PERROR
1589 * not to clubber the error output since this can happen in a normal
1590 * code path.
1591 */
1592 if (errno != EPIPE) {
1593 PERROR("write metadata stream id");
1594 }
1595 DBG3("Consumer failed to write relayd metadata id (errno: %d)", errno);
1596 /*
1597 * Set ret to a negative value because if ret != sizeof(hdr), we don't
1598 * handle writting the missing part so report that as an error and
1599 * don't lie to the caller.
1600 */
1601 ret = -1;
1602 goto end;
1603 }
1604 DBG("Metadata stream id %" PRIu64 " with padding %lu written before data",
1605 stream->relayd_stream_id, padding);
1606
1607 end:
1608 return (int) ret;
1609 }
1610
1611 /*
1612 * Mmap the ring buffer, read it and write the data to the tracefile. This is a
1613 * core function for writing trace buffers to either the local filesystem or
1614 * the network.
1615 *
1616 * It must be called with the stream and the channel lock held.
1617 *
1618 * Careful review MUST be put if any changes occur!
1619 *
1620 * Returns the number of bytes written
1621 */
1622 ssize_t lttng_consumer_on_read_subbuffer_mmap(
1623 struct lttng_consumer_stream *stream,
1624 const struct lttng_buffer_view *buffer,
1625 unsigned long padding)
1626 {
1627 ssize_t ret = 0;
1628 off_t orig_offset = stream->out_fd_offset;
1629 /* Default is on the disk */
1630 int outfd = stream->out_fd;
1631 struct consumer_relayd_sock_pair *relayd = NULL;
1632 unsigned int relayd_hang_up = 0;
1633 const size_t subbuf_content_size = buffer->size - padding;
1634 size_t write_len;
1635
1636 /* RCU lock for the relayd pointer */
1637 rcu_read_lock();
1638 assert(stream->net_seq_idx != (uint64_t) -1ULL ||
1639 stream->trace_chunk);
1640
1641 /* Flag that the current stream if set for network streaming. */
1642 if (stream->net_seq_idx != (uint64_t) -1ULL) {
1643 relayd = consumer_find_relayd(stream->net_seq_idx);
1644 if (relayd == NULL) {
1645 ret = -EPIPE;
1646 goto end;
1647 }
1648 }
1649
1650 /* Handle stream on the relayd if the output is on the network */
1651 if (relayd) {
1652 unsigned long netlen = subbuf_content_size;
1653
1654 /*
1655 * Lock the control socket for the complete duration of the function
1656 * since from this point on we will use the socket.
1657 */
1658 if (stream->metadata_flag) {
1659 /* Metadata requires the control socket. */
1660 pthread_mutex_lock(&relayd->ctrl_sock_mutex);
1661 if (stream->reset_metadata_flag) {
1662 ret = relayd_reset_metadata(&relayd->control_sock,
1663 stream->relayd_stream_id,
1664 stream->metadata_version);
1665 if (ret < 0) {
1666 relayd_hang_up = 1;
1667 goto write_error;
1668 }
1669 stream->reset_metadata_flag = 0;
1670 }
1671 netlen += sizeof(struct lttcomm_relayd_metadata_payload);
1672 }
1673
1674 ret = write_relayd_stream_header(stream, netlen, padding, relayd);
1675 if (ret < 0) {
1676 relayd_hang_up = 1;
1677 goto write_error;
1678 }
1679 /* Use the returned socket. */
1680 outfd = ret;
1681
1682 /* Write metadata stream id before payload */
1683 if (stream->metadata_flag) {
1684 ret = write_relayd_metadata_id(outfd, stream, padding);
1685 if (ret < 0) {
1686 relayd_hang_up = 1;
1687 goto write_error;
1688 }
1689 }
1690
1691 write_len = subbuf_content_size;
1692 } else {
1693 /* No streaming; we have to write the full padding. */
1694 if (stream->metadata_flag && stream->reset_metadata_flag) {
1695 ret = utils_truncate_stream_file(stream->out_fd, 0);
1696 if (ret < 0) {
1697 ERR("Reset metadata file");
1698 goto end;
1699 }
1700 stream->reset_metadata_flag = 0;
1701 }
1702
1703 /*
1704 * Check if we need to change the tracefile before writing the packet.
1705 */
1706 if (stream->chan->tracefile_size > 0 &&
1707 (stream->tracefile_size_current + buffer->size) >
1708 stream->chan->tracefile_size) {
1709 ret = consumer_stream_rotate_output_files(stream);
1710 if (ret) {
1711 goto end;
1712 }
1713 outfd = stream->out_fd;
1714 orig_offset = 0;
1715 }
1716 stream->tracefile_size_current += buffer->size;
1717 write_len = buffer->size;
1718 }
1719
1720 /*
1721 * This call guarantee that len or less is returned. It's impossible to
1722 * receive a ret value that is bigger than len.
1723 */
1724 ret = lttng_write(outfd, buffer->data, write_len);
1725 DBG("Consumer mmap write() ret %zd (len %zu)", ret, write_len);
1726 if (ret < 0 || ((size_t) ret != write_len)) {
1727 /*
1728 * Report error to caller if nothing was written else at least send the
1729 * amount written.
1730 */
1731 if (ret < 0) {
1732 ret = -errno;
1733 }
1734 relayd_hang_up = 1;
1735
1736 /* Socket operation failed. We consider the relayd dead */
1737 if (errno == EPIPE) {
1738 /*
1739 * This is possible if the fd is closed on the other side
1740 * (outfd) or any write problem. It can be verbose a bit for a
1741 * normal execution if for instance the relayd is stopped
1742 * abruptly. This can happen so set this to a DBG statement.
1743 */
1744 DBG("Consumer mmap write detected relayd hang up");
1745 } else {
1746 /* Unhandled error, print it and stop function right now. */
1747 PERROR("Error in write mmap (ret %zd != write_len %zu)", ret,
1748 write_len);
1749 }
1750 goto write_error;
1751 }
1752 stream->output_written += ret;
1753
1754 /* This call is useless on a socket so better save a syscall. */
1755 if (!relayd) {
1756 /* This won't block, but will start writeout asynchronously */
1757 lttng_sync_file_range(outfd, stream->out_fd_offset, write_len,
1758 SYNC_FILE_RANGE_WRITE);
1759 stream->out_fd_offset += write_len;
1760 lttng_consumer_sync_trace_file(stream, orig_offset);
1761 }
1762
1763 write_error:
1764 /*
1765 * This is a special case that the relayd has closed its socket. Let's
1766 * cleanup the relayd object and all associated streams.
1767 */
1768 if (relayd && relayd_hang_up) {
1769 ERR("Relayd hangup. Cleaning up relayd %" PRIu64".", relayd->net_seq_idx);
1770 lttng_consumer_cleanup_relayd(relayd);
1771 }
1772
1773 end:
1774 /* Unlock only if ctrl socket used */
1775 if (relayd && stream->metadata_flag) {
1776 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
1777 }
1778
1779 rcu_read_unlock();
1780 return ret;
1781 }
1782
1783 /*
1784 * Splice the data from the ring buffer to the tracefile.
1785 *
1786 * It must be called with the stream lock held.
1787 *
1788 * Returns the number of bytes spliced.
1789 */
1790 ssize_t lttng_consumer_on_read_subbuffer_splice(
1791 struct lttng_consumer_local_data *ctx,
1792 struct lttng_consumer_stream *stream, unsigned long len,
1793 unsigned long padding)
1794 {
1795 ssize_t ret = 0, written = 0, ret_splice = 0;
1796 loff_t offset = 0;
1797 off_t orig_offset = stream->out_fd_offset;
1798 int fd = stream->wait_fd;
1799 /* Default is on the disk */
1800 int outfd = stream->out_fd;
1801 struct consumer_relayd_sock_pair *relayd = NULL;
1802 int *splice_pipe;
1803 unsigned int relayd_hang_up = 0;
1804
1805 switch (consumer_data.type) {
1806 case LTTNG_CONSUMER_KERNEL:
1807 break;
1808 case LTTNG_CONSUMER32_UST:
1809 case LTTNG_CONSUMER64_UST:
1810 /* Not supported for user space tracing */
1811 return -ENOSYS;
1812 default:
1813 ERR("Unknown consumer_data type");
1814 assert(0);
1815 }
1816
1817 /* RCU lock for the relayd pointer */
1818 rcu_read_lock();
1819
1820 /* Flag that the current stream if set for network streaming. */
1821 if (stream->net_seq_idx != (uint64_t) -1ULL) {
1822 relayd = consumer_find_relayd(stream->net_seq_idx);
1823 if (relayd == NULL) {
1824 written = -ret;
1825 goto end;
1826 }
1827 }
1828 splice_pipe = stream->splice_pipe;
1829
1830 /* Write metadata stream id before payload */
1831 if (relayd) {
1832 unsigned long total_len = len;
1833
1834 if (stream->metadata_flag) {
1835 /*
1836 * Lock the control socket for the complete duration of the function
1837 * since from this point on we will use the socket.
1838 */
1839 pthread_mutex_lock(&relayd->ctrl_sock_mutex);
1840
1841 if (stream->reset_metadata_flag) {
1842 ret = relayd_reset_metadata(&relayd->control_sock,
1843 stream->relayd_stream_id,
1844 stream->metadata_version);
1845 if (ret < 0) {
1846 relayd_hang_up = 1;
1847 goto write_error;
1848 }
1849 stream->reset_metadata_flag = 0;
1850 }
1851 ret = write_relayd_metadata_id(splice_pipe[1], stream,
1852 padding);
1853 if (ret < 0) {
1854 written = ret;
1855 relayd_hang_up = 1;
1856 goto write_error;
1857 }
1858
1859 total_len += sizeof(struct lttcomm_relayd_metadata_payload);
1860 }
1861
1862 ret = write_relayd_stream_header(stream, total_len, padding, relayd);
1863 if (ret < 0) {
1864 written = ret;
1865 relayd_hang_up = 1;
1866 goto write_error;
1867 }
1868 /* Use the returned socket. */
1869 outfd = ret;
1870 } else {
1871 /* No streaming, we have to set the len with the full padding */
1872 len += padding;
1873
1874 if (stream->metadata_flag && stream->reset_metadata_flag) {
1875 ret = utils_truncate_stream_file(stream->out_fd, 0);
1876 if (ret < 0) {
1877 ERR("Reset metadata file");
1878 goto end;
1879 }
1880 stream->reset_metadata_flag = 0;
1881 }
1882 /*
1883 * Check if we need to change the tracefile before writing the packet.
1884 */
1885 if (stream->chan->tracefile_size > 0 &&
1886 (stream->tracefile_size_current + len) >
1887 stream->chan->tracefile_size) {
1888 ret = consumer_stream_rotate_output_files(stream);
1889 if (ret < 0) {
1890 written = ret;
1891 goto end;
1892 }
1893 outfd = stream->out_fd;
1894 orig_offset = 0;
1895 }
1896 stream->tracefile_size_current += len;
1897 }
1898
1899 while (len > 0) {
1900 DBG("splice chan to pipe offset %lu of len %lu (fd : %d, pipe: %d)",
1901 (unsigned long)offset, len, fd, splice_pipe[1]);
1902 ret_splice = splice(fd, &offset, splice_pipe[1], NULL, len,
1903 SPLICE_F_MOVE | SPLICE_F_MORE);
1904 DBG("splice chan to pipe, ret %zd", ret_splice);
1905 if (ret_splice < 0) {
1906 ret = errno;
1907 written = -ret;
1908 PERROR("Error in relay splice");
1909 goto splice_error;
1910 }
1911
1912 /* Handle stream on the relayd if the output is on the network */
1913 if (relayd && stream->metadata_flag) {
1914 size_t metadata_payload_size =
1915 sizeof(struct lttcomm_relayd_metadata_payload);
1916
1917 /* Update counter to fit the spliced data */
1918 ret_splice += metadata_payload_size;
1919 len += metadata_payload_size;
1920 /*
1921 * We do this so the return value can match the len passed as
1922 * argument to this function.
1923 */
1924 written -= metadata_payload_size;
1925 }
1926
1927 /* Splice data out */
1928 ret_splice = splice(splice_pipe[0], NULL, outfd, NULL,
1929 ret_splice, SPLICE_F_MOVE | SPLICE_F_MORE);
1930 DBG("Consumer splice pipe to file (out_fd: %d), ret %zd",
1931 outfd, ret_splice);
1932 if (ret_splice < 0) {
1933 ret = errno;
1934 written = -ret;
1935 relayd_hang_up = 1;
1936 goto write_error;
1937 } else if (ret_splice > len) {
1938 /*
1939 * We don't expect this code path to be executed but you never know
1940 * so this is an extra protection agains a buggy splice().
1941 */
1942 ret = errno;
1943 written += ret_splice;
1944 PERROR("Wrote more data than requested %zd (len: %lu)", ret_splice,
1945 len);
1946 goto splice_error;
1947 } else {
1948 /* All good, update current len and continue. */
1949 len -= ret_splice;
1950 }
1951
1952 /* This call is useless on a socket so better save a syscall. */
1953 if (!relayd) {
1954 /* This won't block, but will start writeout asynchronously */
1955 lttng_sync_file_range(outfd, stream->out_fd_offset, ret_splice,
1956 SYNC_FILE_RANGE_WRITE);
1957 stream->out_fd_offset += ret_splice;
1958 }
1959 stream->output_written += ret_splice;
1960 written += ret_splice;
1961 }
1962 if (!relayd) {
1963 lttng_consumer_sync_trace_file(stream, orig_offset);
1964 }
1965 goto end;
1966
1967 write_error:
1968 /*
1969 * This is a special case that the relayd has closed its socket. Let's
1970 * cleanup the relayd object and all associated streams.
1971 */
1972 if (relayd && relayd_hang_up) {
1973 ERR("Relayd hangup. Cleaning up relayd %" PRIu64".", relayd->net_seq_idx);
1974 lttng_consumer_cleanup_relayd(relayd);
1975 /* Skip splice error so the consumer does not fail */
1976 goto end;
1977 }
1978
1979 splice_error:
1980 /* send the appropriate error description to sessiond */
1981 switch (ret) {
1982 case EINVAL:
1983 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_SPLICE_EINVAL);
1984 break;
1985 case ENOMEM:
1986 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_SPLICE_ENOMEM);
1987 break;
1988 case ESPIPE:
1989 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_SPLICE_ESPIPE);
1990 break;
1991 }
1992
1993 end:
1994 if (relayd && stream->metadata_flag) {
1995 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
1996 }
1997
1998 rcu_read_unlock();
1999 return written;
2000 }
2001
2002 /*
2003 * Sample the snapshot positions for a specific fd
2004 *
2005 * Returns 0 on success, < 0 on error
2006 */
2007 int lttng_consumer_sample_snapshot_positions(struct lttng_consumer_stream *stream)
2008 {
2009 switch (consumer_data.type) {
2010 case LTTNG_CONSUMER_KERNEL:
2011 return lttng_kconsumer_sample_snapshot_positions(stream);
2012 case LTTNG_CONSUMER32_UST:
2013 case LTTNG_CONSUMER64_UST:
2014 return lttng_ustconsumer_sample_snapshot_positions(stream);
2015 default:
2016 ERR("Unknown consumer_data type");
2017 assert(0);
2018 return -ENOSYS;
2019 }
2020 }
2021 /*
2022 * Take a snapshot for a specific fd
2023 *
2024 * Returns 0 on success, < 0 on error
2025 */
2026 int lttng_consumer_take_snapshot(struct lttng_consumer_stream *stream)
2027 {
2028 switch (consumer_data.type) {
2029 case LTTNG_CONSUMER_KERNEL:
2030 return lttng_kconsumer_take_snapshot(stream);
2031 case LTTNG_CONSUMER32_UST:
2032 case LTTNG_CONSUMER64_UST:
2033 return lttng_ustconsumer_take_snapshot(stream);
2034 default:
2035 ERR("Unknown consumer_data type");
2036 assert(0);
2037 return -ENOSYS;
2038 }
2039 }
2040
2041 /*
2042 * Get the produced position
2043 *
2044 * Returns 0 on success, < 0 on error
2045 */
2046 int lttng_consumer_get_produced_snapshot(struct lttng_consumer_stream *stream,
2047 unsigned long *pos)
2048 {
2049 switch (consumer_data.type) {
2050 case LTTNG_CONSUMER_KERNEL:
2051 return lttng_kconsumer_get_produced_snapshot(stream, pos);
2052 case LTTNG_CONSUMER32_UST:
2053 case LTTNG_CONSUMER64_UST:
2054 return lttng_ustconsumer_get_produced_snapshot(stream, pos);
2055 default:
2056 ERR("Unknown consumer_data type");
2057 assert(0);
2058 return -ENOSYS;
2059 }
2060 }
2061
2062 /*
2063 * Get the consumed position (free-running counter position in bytes).
2064 *
2065 * Returns 0 on success, < 0 on error
2066 */
2067 int lttng_consumer_get_consumed_snapshot(struct lttng_consumer_stream *stream,
2068 unsigned long *pos)
2069 {
2070 switch (consumer_data.type) {
2071 case LTTNG_CONSUMER_KERNEL:
2072 return lttng_kconsumer_get_consumed_snapshot(stream, pos);
2073 case LTTNG_CONSUMER32_UST:
2074 case LTTNG_CONSUMER64_UST:
2075 return lttng_ustconsumer_get_consumed_snapshot(stream, pos);
2076 default:
2077 ERR("Unknown consumer_data type");
2078 assert(0);
2079 return -ENOSYS;
2080 }
2081 }
2082
2083 int lttng_consumer_recv_cmd(struct lttng_consumer_local_data *ctx,
2084 int sock, struct pollfd *consumer_sockpoll)
2085 {
2086 switch (consumer_data.type) {
2087 case LTTNG_CONSUMER_KERNEL:
2088 return lttng_kconsumer_recv_cmd(ctx, sock, consumer_sockpoll);
2089 case LTTNG_CONSUMER32_UST:
2090 case LTTNG_CONSUMER64_UST:
2091 return lttng_ustconsumer_recv_cmd(ctx, sock, consumer_sockpoll);
2092 default:
2093 ERR("Unknown consumer_data type");
2094 assert(0);
2095 return -ENOSYS;
2096 }
2097 }
2098
2099 static
2100 void lttng_consumer_close_all_metadata(void)
2101 {
2102 switch (consumer_data.type) {
2103 case LTTNG_CONSUMER_KERNEL:
2104 /*
2105 * The Kernel consumer has a different metadata scheme so we don't
2106 * close anything because the stream will be closed by the session
2107 * daemon.
2108 */
2109 break;
2110 case LTTNG_CONSUMER32_UST:
2111 case LTTNG_CONSUMER64_UST:
2112 /*
2113 * Close all metadata streams. The metadata hash table is passed and
2114 * this call iterates over it by closing all wakeup fd. This is safe
2115 * because at this point we are sure that the metadata producer is
2116 * either dead or blocked.
2117 */
2118 lttng_ustconsumer_close_all_metadata(metadata_ht);
2119 break;
2120 default:
2121 ERR("Unknown consumer_data type");
2122 assert(0);
2123 }
2124 }
2125
2126 /*
2127 * Clean up a metadata stream and free its memory.
2128 */
2129 void consumer_del_metadata_stream(struct lttng_consumer_stream *stream,
2130 struct lttng_ht *ht)
2131 {
2132 struct lttng_consumer_channel *channel = NULL;
2133 bool free_channel = false;
2134
2135 assert(stream);
2136 /*
2137 * This call should NEVER receive regular stream. It must always be
2138 * metadata stream and this is crucial for data structure synchronization.
2139 */
2140 assert(stream->metadata_flag);
2141
2142 DBG3("Consumer delete metadata stream %d", stream->wait_fd);
2143
2144 pthread_mutex_lock(&consumer_data.lock);
2145 /*
2146 * Note that this assumes that a stream's channel is never changed and
2147 * that the stream's lock doesn't need to be taken to sample its
2148 * channel.
2149 */
2150 channel = stream->chan;
2151 pthread_mutex_lock(&channel->lock);
2152 pthread_mutex_lock(&stream->lock);
2153 if (channel->metadata_cache) {
2154 /* Only applicable to userspace consumers. */
2155 pthread_mutex_lock(&channel->metadata_cache->lock);
2156 }
2157
2158 /* Remove any reference to that stream. */
2159 consumer_stream_delete(stream, ht);
2160
2161 /* Close down everything including the relayd if one. */
2162 consumer_stream_close(stream);
2163 /* Destroy tracer buffers of the stream. */
2164 consumer_stream_destroy_buffers(stream);
2165
2166 /* Atomically decrement channel refcount since other threads can use it. */
2167 if (!uatomic_sub_return(&channel->refcount, 1)
2168 && !uatomic_read(&channel->nb_init_stream_left)) {
2169 /* Go for channel deletion! */
2170 free_channel = true;
2171 }
2172 stream->chan = NULL;
2173
2174 /*
2175 * Nullify the stream reference so it is not used after deletion. The
2176 * channel lock MUST be acquired before being able to check for a NULL
2177 * pointer value.
2178 */
2179 channel->metadata_stream = NULL;
2180
2181 if (channel->metadata_cache) {
2182 pthread_mutex_unlock(&channel->metadata_cache->lock);
2183 }
2184 pthread_mutex_unlock(&stream->lock);
2185 pthread_mutex_unlock(&channel->lock);
2186 pthread_mutex_unlock(&consumer_data.lock);
2187
2188 if (free_channel) {
2189 consumer_del_channel(channel);
2190 }
2191
2192 lttng_trace_chunk_put(stream->trace_chunk);
2193 stream->trace_chunk = NULL;
2194 consumer_stream_free(stream);
2195 }
2196
2197 /*
2198 * Action done with the metadata stream when adding it to the consumer internal
2199 * data structures to handle it.
2200 */
2201 void consumer_add_metadata_stream(struct lttng_consumer_stream *stream)
2202 {
2203 struct lttng_ht *ht = metadata_ht;
2204 struct lttng_ht_iter iter;
2205 struct lttng_ht_node_u64 *node;
2206
2207 assert(stream);
2208 assert(ht);
2209
2210 DBG3("Adding metadata stream %" PRIu64 " to hash table", stream->key);
2211
2212 pthread_mutex_lock(&consumer_data.lock);
2213 pthread_mutex_lock(&stream->chan->lock);
2214 pthread_mutex_lock(&stream->chan->timer_lock);
2215 pthread_mutex_lock(&stream->lock);
2216
2217 /*
2218 * From here, refcounts are updated so be _careful_ when returning an error
2219 * after this point.
2220 */
2221
2222 rcu_read_lock();
2223
2224 /*
2225 * Lookup the stream just to make sure it does not exist in our internal
2226 * state. This should NEVER happen.
2227 */
2228 lttng_ht_lookup(ht, &stream->key, &iter);
2229 node = lttng_ht_iter_get_node_u64(&iter);
2230 assert(!node);
2231
2232 /*
2233 * When nb_init_stream_left reaches 0, we don't need to trigger any action
2234 * in terms of destroying the associated channel, because the action that
2235 * causes the count to become 0 also causes a stream to be added. The
2236 * channel deletion will thus be triggered by the following removal of this
2237 * stream.
2238 */
2239 if (uatomic_read(&stream->chan->nb_init_stream_left) > 0) {
2240 /* Increment refcount before decrementing nb_init_stream_left */
2241 cmm_smp_wmb();
2242 uatomic_dec(&stream->chan->nb_init_stream_left);
2243 }
2244
2245 lttng_ht_add_unique_u64(ht, &stream->node);
2246
2247 lttng_ht_add_u64(consumer_data.stream_per_chan_id_ht,
2248 &stream->node_channel_id);
2249
2250 /*
2251 * Add stream to the stream_list_ht of the consumer data. No need to steal
2252 * the key since the HT does not use it and we allow to add redundant keys
2253 * into this table.
2254 */
2255 lttng_ht_add_u64(consumer_data.stream_list_ht, &stream->node_session_id);
2256
2257 rcu_read_unlock();
2258
2259 pthread_mutex_unlock(&stream->lock);
2260 pthread_mutex_unlock(&stream->chan->lock);
2261 pthread_mutex_unlock(&stream->chan->timer_lock);
2262 pthread_mutex_unlock(&consumer_data.lock);
2263 }
2264
2265 /*
2266 * Delete data stream that are flagged for deletion (endpoint_status).
2267 */
2268 static void validate_endpoint_status_data_stream(void)
2269 {
2270 struct lttng_ht_iter iter;
2271 struct lttng_consumer_stream *stream;
2272
2273 DBG("Consumer delete flagged data stream");
2274
2275 rcu_read_lock();
2276 cds_lfht_for_each_entry(data_ht->ht, &iter.iter, stream, node.node) {
2277 /* Validate delete flag of the stream */
2278 if (stream->endpoint_status == CONSUMER_ENDPOINT_ACTIVE) {
2279 continue;
2280 }
2281 /* Delete it right now */
2282 consumer_del_stream(stream, data_ht);
2283 }
2284 rcu_read_unlock();
2285 }
2286
2287 /*
2288 * Delete metadata stream that are flagged for deletion (endpoint_status).
2289 */
2290 static void validate_endpoint_status_metadata_stream(
2291 struct lttng_poll_event *pollset)
2292 {
2293 struct lttng_ht_iter iter;
2294 struct lttng_consumer_stream *stream;
2295
2296 DBG("Consumer delete flagged metadata stream");
2297
2298 assert(pollset);
2299
2300 rcu_read_lock();
2301 cds_lfht_for_each_entry(metadata_ht->ht, &iter.iter, stream, node.node) {
2302 /* Validate delete flag of the stream */
2303 if (stream->endpoint_status == CONSUMER_ENDPOINT_ACTIVE) {
2304 continue;
2305 }
2306 /*
2307 * Remove from pollset so the metadata thread can continue without
2308 * blocking on a deleted stream.
2309 */
2310 lttng_poll_del(pollset, stream->wait_fd);
2311
2312 /* Delete it right now */
2313 consumer_del_metadata_stream(stream, metadata_ht);
2314 }
2315 rcu_read_unlock();
2316 }
2317
2318 /*
2319 * Thread polls on metadata file descriptor and write them on disk or on the
2320 * network.
2321 */
2322 void *consumer_thread_metadata_poll(void *data)
2323 {
2324 int ret, i, pollfd, err = -1;
2325 uint32_t revents, nb_fd;
2326 struct lttng_consumer_stream *stream = NULL;
2327 struct lttng_ht_iter iter;
2328 struct lttng_ht_node_u64 *node;
2329 struct lttng_poll_event events;
2330 struct lttng_consumer_local_data *ctx = data;
2331 ssize_t len;
2332
2333 rcu_register_thread();
2334
2335 health_register(health_consumerd, HEALTH_CONSUMERD_TYPE_METADATA);
2336
2337 if (testpoint(consumerd_thread_metadata)) {
2338 goto error_testpoint;
2339 }
2340
2341 health_code_update();
2342
2343 DBG("Thread metadata poll started");
2344
2345 /* Size is set to 1 for the consumer_metadata pipe */
2346 ret = lttng_poll_create(&events, 2, LTTNG_CLOEXEC);
2347 if (ret < 0) {
2348 ERR("Poll set creation failed");
2349 goto end_poll;
2350 }
2351
2352 ret = lttng_poll_add(&events,
2353 lttng_pipe_get_readfd(ctx->consumer_metadata_pipe), LPOLLIN);
2354 if (ret < 0) {
2355 goto end;
2356 }
2357
2358 /* Main loop */
2359 DBG("Metadata main loop started");
2360
2361 while (1) {
2362 restart:
2363 health_code_update();
2364 health_poll_entry();
2365 DBG("Metadata poll wait");
2366 ret = lttng_poll_wait(&events, -1);
2367 DBG("Metadata poll return from wait with %d fd(s)",
2368 LTTNG_POLL_GETNB(&events));
2369 health_poll_exit();
2370 DBG("Metadata event caught in thread");
2371 if (ret < 0) {
2372 if (errno == EINTR) {
2373 ERR("Poll EINTR caught");
2374 goto restart;
2375 }
2376 if (LTTNG_POLL_GETNB(&events) == 0) {
2377 err = 0; /* All is OK */
2378 }
2379 goto end;
2380 }
2381
2382 nb_fd = ret;
2383
2384 /* From here, the event is a metadata wait fd */
2385 for (i = 0; i < nb_fd; i++) {
2386 health_code_update();
2387
2388 revents = LTTNG_POLL_GETEV(&events, i);
2389 pollfd = LTTNG_POLL_GETFD(&events, i);
2390
2391 if (pollfd == lttng_pipe_get_readfd(ctx->consumer_metadata_pipe)) {
2392 if (revents & LPOLLIN) {
2393 ssize_t pipe_len;
2394
2395 pipe_len = lttng_pipe_read(ctx->consumer_metadata_pipe,
2396 &stream, sizeof(stream));
2397 if (pipe_len < sizeof(stream)) {
2398 if (pipe_len < 0) {
2399 PERROR("read metadata stream");
2400 }
2401 /*
2402 * Remove the pipe from the poll set and continue the loop
2403 * since their might be data to consume.
2404 */
2405 lttng_poll_del(&events,
2406 lttng_pipe_get_readfd(ctx->consumer_metadata_pipe));
2407 lttng_pipe_read_close(ctx->consumer_metadata_pipe);
2408 continue;
2409 }
2410
2411 /* A NULL stream means that the state has changed. */
2412 if (stream == NULL) {
2413 /* Check for deleted streams. */
2414 validate_endpoint_status_metadata_stream(&events);
2415 goto restart;
2416 }
2417
2418 DBG("Adding metadata stream %d to poll set",
2419 stream->wait_fd);
2420
2421 /* Add metadata stream to the global poll events list */
2422 lttng_poll_add(&events, stream->wait_fd,
2423 LPOLLIN | LPOLLPRI | LPOLLHUP);
2424 } else if (revents & (LPOLLERR | LPOLLHUP)) {
2425 DBG("Metadata thread pipe hung up");
2426 /*
2427 * Remove the pipe from the poll set and continue the loop
2428 * since their might be data to consume.
2429 */
2430 lttng_poll_del(&events,
2431 lttng_pipe_get_readfd(ctx->consumer_metadata_pipe));
2432 lttng_pipe_read_close(ctx->consumer_metadata_pipe);
2433 continue;
2434 } else {
2435 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
2436 goto end;
2437 }
2438
2439 /* Handle other stream */
2440 continue;
2441 }
2442
2443 rcu_read_lock();
2444 {
2445 uint64_t tmp_id = (uint64_t) pollfd;
2446
2447 lttng_ht_lookup(metadata_ht, &tmp_id, &iter);
2448 }
2449 node = lttng_ht_iter_get_node_u64(&iter);
2450 assert(node);
2451
2452 stream = caa_container_of(node, struct lttng_consumer_stream,
2453 node);
2454
2455 if (revents & (LPOLLIN | LPOLLPRI)) {
2456 /* Get the data out of the metadata file descriptor */
2457 DBG("Metadata available on fd %d", pollfd);
2458 assert(stream->wait_fd == pollfd);
2459
2460 do {
2461 health_code_update();
2462
2463 len = ctx->on_buffer_ready(stream, ctx, false);
2464 /*
2465 * We don't check the return value here since if we get
2466 * a negative len, it means an error occurred thus we
2467 * simply remove it from the poll set and free the
2468 * stream.
2469 */
2470 } while (len > 0);
2471
2472 /* It's ok to have an unavailable sub-buffer */
2473 if (len < 0 && len != -EAGAIN && len != -ENODATA) {
2474 /* Clean up stream from consumer and free it. */
2475 lttng_poll_del(&events, stream->wait_fd);
2476 consumer_del_metadata_stream(stream, metadata_ht);
2477 }
2478 } else if (revents & (LPOLLERR | LPOLLHUP)) {
2479 DBG("Metadata fd %d is hup|err.", pollfd);
2480 if (!stream->hangup_flush_done
2481 && (consumer_data.type == LTTNG_CONSUMER32_UST
2482 || consumer_data.type == LTTNG_CONSUMER64_UST)) {
2483 DBG("Attempting to flush and consume the UST buffers");
2484 lttng_ustconsumer_on_stream_hangup(stream);
2485
2486 /* We just flushed the stream now read it. */
2487 do {
2488 health_code_update();
2489
2490 len = ctx->on_buffer_ready(stream, ctx, false);
2491 /*
2492 * We don't check the return value here since if we get
2493 * a negative len, it means an error occurred thus we
2494 * simply remove it from the poll set and free the
2495 * stream.
2496 */
2497 } while (len > 0);
2498 }
2499
2500 lttng_poll_del(&events, stream->wait_fd);
2501 /*
2502 * This call update the channel states, closes file descriptors
2503 * and securely free the stream.
2504 */
2505 consumer_del_metadata_stream(stream, metadata_ht);
2506 } else {
2507 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
2508 rcu_read_unlock();
2509 goto end;
2510 }
2511 /* Release RCU lock for the stream looked up */
2512 rcu_read_unlock();
2513 }
2514 }
2515
2516 /* All is OK */
2517 err = 0;
2518 end:
2519 DBG("Metadata poll thread exiting");
2520
2521 lttng_poll_clean(&events);
2522 end_poll:
2523 error_testpoint:
2524 if (err) {
2525 health_error();
2526 ERR("Health error occurred in %s", __func__);
2527 }
2528 health_unregister(health_consumerd);
2529 rcu_unregister_thread();
2530 return NULL;
2531 }
2532
2533 /*
2534 * This thread polls the fds in the set to consume the data and write
2535 * it to tracefile if necessary.
2536 */
2537 void *consumer_thread_data_poll(void *data)
2538 {
2539 int num_rdy, num_hup, high_prio, ret, i, err = -1;
2540 struct pollfd *pollfd = NULL;
2541 /* local view of the streams */
2542 struct lttng_consumer_stream **local_stream = NULL, *new_stream = NULL;
2543 /* local view of consumer_data.fds_count */
2544 int nb_fd = 0;
2545 /* 2 for the consumer_data_pipe and wake up pipe */
2546 const int nb_pipes_fd = 2;
2547 /* Number of FDs with CONSUMER_ENDPOINT_INACTIVE but still open. */
2548 int nb_inactive_fd = 0;
2549 struct lttng_consumer_local_data *ctx = data;
2550 ssize_t len;
2551
2552 rcu_register_thread();
2553
2554 health_register(health_consumerd, HEALTH_CONSUMERD_TYPE_DATA);
2555
2556 if (testpoint(consumerd_thread_data)) {
2557 goto error_testpoint;
2558 }
2559
2560 health_code_update();
2561
2562 local_stream = zmalloc(sizeof(struct lttng_consumer_stream *));
2563 if (local_stream == NULL) {
2564 PERROR("local_stream malloc");
2565 goto end;
2566 }
2567
2568 while (1) {
2569 health_code_update();
2570
2571 high_prio = 0;
2572 num_hup = 0;
2573
2574 /*
2575 * the fds set has been updated, we need to update our
2576 * local array as well
2577 */
2578 pthread_mutex_lock(&consumer_data.lock);
2579 if (consumer_data.need_update) {
2580 free(pollfd);
2581 pollfd = NULL;
2582
2583 free(local_stream);
2584 local_stream = NULL;
2585
2586 /* Allocate for all fds */
2587 pollfd = zmalloc((consumer_data.stream_count + nb_pipes_fd) * sizeof(struct pollfd));
2588 if (pollfd == NULL) {
2589 PERROR("pollfd malloc");
2590 pthread_mutex_unlock(&consumer_data.lock);
2591 goto end;
2592 }
2593
2594 local_stream = zmalloc((consumer_data.stream_count + nb_pipes_fd) *
2595 sizeof(struct lttng_consumer_stream *));
2596 if (local_stream == NULL) {
2597 PERROR("local_stream malloc");
2598 pthread_mutex_unlock(&consumer_data.lock);
2599 goto end;
2600 }
2601 ret = update_poll_array(ctx, &pollfd, local_stream,
2602 data_ht, &nb_inactive_fd);
2603 if (ret < 0) {
2604 ERR("Error in allocating pollfd or local_outfds");
2605 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_POLL_ERROR);
2606 pthread_mutex_unlock(&consumer_data.lock);
2607 goto end;
2608 }
2609 nb_fd = ret;
2610 consumer_data.need_update = 0;
2611 }
2612 pthread_mutex_unlock(&consumer_data.lock);
2613
2614 /* No FDs and consumer_quit, consumer_cleanup the thread */
2615 if (nb_fd == 0 && nb_inactive_fd == 0 &&
2616 CMM_LOAD_SHARED(consumer_quit) == 1) {
2617 err = 0; /* All is OK */
2618 goto end;
2619 }
2620 /* poll on the array of fds */
2621 restart:
2622 DBG("polling on %d fd", nb_fd + nb_pipes_fd);
2623 if (testpoint(consumerd_thread_data_poll)) {
2624 goto end;
2625 }
2626 health_poll_entry();
2627 num_rdy = poll(pollfd, nb_fd + nb_pipes_fd, -1);
2628 health_poll_exit();
2629 DBG("poll num_rdy : %d", num_rdy);
2630 if (num_rdy == -1) {
2631 /*
2632 * Restart interrupted system call.
2633 */
2634 if (errno == EINTR) {
2635 goto restart;
2636 }
2637 PERROR("Poll error");
2638 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_POLL_ERROR);
2639 goto end;
2640 } else if (num_rdy == 0) {
2641 DBG("Polling thread timed out");
2642 goto end;
2643 }
2644
2645 if (caa_unlikely(data_consumption_paused)) {
2646 DBG("Data consumption paused, sleeping...");
2647 sleep(1);
2648 goto restart;
2649 }
2650
2651 /*
2652 * If the consumer_data_pipe triggered poll go directly to the
2653 * beginning of the loop to update the array. We want to prioritize
2654 * array update over low-priority reads.
2655 */
2656 if (pollfd[nb_fd].revents & (POLLIN | POLLPRI)) {
2657 ssize_t pipe_readlen;
2658
2659 DBG("consumer_data_pipe wake up");
2660 pipe_readlen = lttng_pipe_read(ctx->consumer_data_pipe,
2661 &new_stream, sizeof(new_stream));
2662 if (pipe_readlen < sizeof(new_stream)) {
2663 PERROR("Consumer data pipe");
2664 /* Continue so we can at least handle the current stream(s). */
2665 continue;
2666 }
2667
2668 /*
2669 * If the stream is NULL, just ignore it. It's also possible that
2670 * the sessiond poll thread changed the consumer_quit state and is
2671 * waking us up to test it.
2672 */
2673 if (new_stream == NULL) {
2674 validate_endpoint_status_data_stream();
2675 continue;
2676 }
2677
2678 /* Continue to update the local streams and handle prio ones */
2679 continue;
2680 }
2681
2682 /* Handle wakeup pipe. */
2683 if (pollfd[nb_fd + 1].revents & (POLLIN | POLLPRI)) {
2684 char dummy;
2685 ssize_t pipe_readlen;
2686
2687 pipe_readlen = lttng_pipe_read(ctx->consumer_wakeup_pipe, &dummy,
2688 sizeof(dummy));
2689 if (pipe_readlen < 0) {
2690 PERROR("Consumer data wakeup pipe");
2691 }
2692 /* We've been awakened to handle stream(s). */
2693 ctx->has_wakeup = 0;
2694 }
2695
2696 /* Take care of high priority channels first. */
2697 for (i = 0; i < nb_fd; i++) {
2698 health_code_update();
2699
2700 if (local_stream[i] == NULL) {
2701 continue;
2702 }
2703 if (pollfd[i].revents & POLLPRI) {
2704 DBG("Urgent read on fd %d", pollfd[i].fd);
2705 high_prio = 1;
2706 len = ctx->on_buffer_ready(local_stream[i], ctx, false);
2707 /* it's ok to have an unavailable sub-buffer */
2708 if (len < 0 && len != -EAGAIN && len != -ENODATA) {
2709 /* Clean the stream and free it. */
2710 consumer_del_stream(local_stream[i], data_ht);
2711 local_stream[i] = NULL;
2712 } else if (len > 0) {
2713 local_stream[i]->data_read = 1;
2714 }
2715 }
2716 }
2717
2718 /*
2719 * If we read high prio channel in this loop, try again
2720 * for more high prio data.
2721 */
2722 if (high_prio) {
2723 continue;
2724 }
2725
2726 /* Take care of low priority channels. */
2727 for (i = 0; i < nb_fd; i++) {
2728 health_code_update();
2729
2730 if (local_stream[i] == NULL) {
2731 continue;
2732 }
2733 if ((pollfd[i].revents & POLLIN) ||
2734 local_stream[i]->hangup_flush_done ||
2735 local_stream[i]->has_data) {
2736 DBG("Normal read on fd %d", pollfd[i].fd);
2737 len = ctx->on_buffer_ready(local_stream[i], ctx, false);
2738 /* it's ok to have an unavailable sub-buffer */
2739 if (len < 0 && len != -EAGAIN && len != -ENODATA) {
2740 /* Clean the stream and free it. */
2741 consumer_del_stream(local_stream[i], data_ht);
2742 local_stream[i] = NULL;
2743 } else if (len > 0) {
2744 local_stream[i]->data_read = 1;
2745 }
2746 }
2747 }
2748
2749 /* Handle hangup and errors */
2750 for (i = 0; i < nb_fd; i++) {
2751 health_code_update();
2752
2753 if (local_stream[i] == NULL) {
2754 continue;
2755 }
2756 if (!local_stream[i]->hangup_flush_done
2757 && (pollfd[i].revents & (POLLHUP | POLLERR | POLLNVAL))
2758 && (consumer_data.type == LTTNG_CONSUMER32_UST
2759 || consumer_data.type == LTTNG_CONSUMER64_UST)) {
2760 DBG("fd %d is hup|err|nval. Attempting flush and read.",
2761 pollfd[i].fd);
2762 lttng_ustconsumer_on_stream_hangup(local_stream[i]);
2763 /* Attempt read again, for the data we just flushed. */
2764 local_stream[i]->data_read = 1;
2765 }
2766 /*
2767 * If the poll flag is HUP/ERR/NVAL and we have
2768 * read no data in this pass, we can remove the
2769 * stream from its hash table.
2770 */
2771 if ((pollfd[i].revents & POLLHUP)) {
2772 DBG("Polling fd %d tells it has hung up.", pollfd[i].fd);
2773 if (!local_stream[i]->data_read) {
2774 consumer_del_stream(local_stream[i], data_ht);
2775 local_stream[i] = NULL;
2776 num_hup++;
2777 }
2778 } else if (pollfd[i].revents & POLLERR) {
2779 ERR("Error returned in polling fd %d.", pollfd[i].fd);
2780 if (!local_stream[i]->data_read) {
2781 consumer_del_stream(local_stream[i], data_ht);
2782 local_stream[i] = NULL;
2783 num_hup++;
2784 }
2785 } else if (pollfd[i].revents & POLLNVAL) {
2786 ERR("Polling fd %d tells fd is not open.", pollfd[i].fd);
2787 if (!local_stream[i]->data_read) {
2788 consumer_del_stream(local_stream[i], data_ht);
2789 local_stream[i] = NULL;
2790 num_hup++;
2791 }
2792 }
2793 if (local_stream[i] != NULL) {
2794 local_stream[i]->data_read = 0;
2795 }
2796 }
2797 }
2798 /* All is OK */
2799 err = 0;
2800 end:
2801 DBG("polling thread exiting");
2802 free(pollfd);
2803 free(local_stream);
2804
2805 /*
2806 * Close the write side of the pipe so epoll_wait() in
2807 * consumer_thread_metadata_poll can catch it. The thread is monitoring the
2808 * read side of the pipe. If we close them both, epoll_wait strangely does
2809 * not return and could create a endless wait period if the pipe is the
2810 * only tracked fd in the poll set. The thread will take care of closing
2811 * the read side.
2812 */
2813 (void) lttng_pipe_write_close(ctx->consumer_metadata_pipe);
2814
2815 error_testpoint:
2816 if (err) {
2817 health_error();
2818 ERR("Health error occurred in %s", __func__);
2819 }
2820 health_unregister(health_consumerd);
2821
2822 rcu_unregister_thread();
2823 return NULL;
2824 }
2825
2826 /*
2827 * Close wake-up end of each stream belonging to the channel. This will
2828 * allow the poll() on the stream read-side to detect when the
2829 * write-side (application) finally closes them.
2830 */
2831 static
2832 void consumer_close_channel_streams(struct lttng_consumer_channel *channel)
2833 {
2834 struct lttng_ht *ht;
2835 struct lttng_consumer_stream *stream;
2836 struct lttng_ht_iter iter;
2837
2838 ht = consumer_data.stream_per_chan_id_ht;
2839
2840 rcu_read_lock();
2841 cds_lfht_for_each_entry_duplicate(ht->ht,
2842 ht->hash_fct(&channel->key, lttng_ht_seed),
2843 ht->match_fct, &channel->key,
2844 &iter.iter, stream, node_channel_id.node) {
2845 /*
2846 * Protect against teardown with mutex.
2847 */
2848 pthread_mutex_lock(&stream->lock);
2849 if (cds_lfht_is_node_deleted(&stream->node.node)) {
2850 goto next;
2851 }
2852 switch (consumer_data.type) {
2853 case LTTNG_CONSUMER_KERNEL:
2854 break;
2855 case LTTNG_CONSUMER32_UST:
2856 case LTTNG_CONSUMER64_UST:
2857 if (stream->metadata_flag) {
2858 /* Safe and protected by the stream lock. */
2859 lttng_ustconsumer_close_metadata(stream->chan);
2860 } else {
2861 /*
2862 * Note: a mutex is taken internally within
2863 * liblttng-ust-ctl to protect timer wakeup_fd
2864 * use from concurrent close.
2865 */
2866 lttng_ustconsumer_close_stream_wakeup(stream);
2867 }
2868 break;
2869 default:
2870 ERR("Unknown consumer_data type");
2871 assert(0);
2872 }
2873 next:
2874 pthread_mutex_unlock(&stream->lock);
2875 }
2876 rcu_read_unlock();
2877 }
2878
2879 static void destroy_channel_ht(struct lttng_ht *ht)
2880 {
2881 struct lttng_ht_iter iter;
2882 struct lttng_consumer_channel *channel;
2883 int ret;
2884
2885 if (ht == NULL) {
2886 return;
2887 }
2888
2889 rcu_read_lock();
2890 cds_lfht_for_each_entry(ht->ht, &iter.iter, channel, wait_fd_node.node) {
2891 ret = lttng_ht_del(ht, &iter);
2892 assert(ret != 0);
2893 }
2894 rcu_read_unlock();
2895
2896 lttng_ht_destroy(ht);
2897 }
2898
2899 /*
2900 * This thread polls the channel fds to detect when they are being
2901 * closed. It closes all related streams if the channel is detected as
2902 * closed. It is currently only used as a shim layer for UST because the
2903 * consumerd needs to keep the per-stream wakeup end of pipes open for
2904 * periodical flush.
2905 */
2906 void *consumer_thread_channel_poll(void *data)
2907 {
2908 int ret, i, pollfd, err = -1;
2909 uint32_t revents, nb_fd;
2910 struct lttng_consumer_channel *chan = NULL;
2911 struct lttng_ht_iter iter;
2912 struct lttng_ht_node_u64 *node;
2913 struct lttng_poll_event events;
2914 struct lttng_consumer_local_data *ctx = data;
2915 struct lttng_ht *channel_ht;
2916
2917 rcu_register_thread();
2918
2919 health_register(health_consumerd, HEALTH_CONSUMERD_TYPE_CHANNEL);
2920
2921 if (testpoint(consumerd_thread_channel)) {
2922 goto error_testpoint;
2923 }
2924
2925 health_code_update();
2926
2927 channel_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
2928 if (!channel_ht) {
2929 /* ENOMEM at this point. Better to bail out. */
2930 goto end_ht;
2931 }
2932
2933 DBG("Thread channel poll started");
2934
2935 /* Size is set to 1 for the consumer_channel pipe */
2936 ret = lttng_poll_create(&events, 2, LTTNG_CLOEXEC);
2937 if (ret < 0) {
2938 ERR("Poll set creation failed");
2939 goto end_poll;
2940 }
2941
2942 ret = lttng_poll_add(&events, ctx->consumer_channel_pipe[0], LPOLLIN);
2943 if (ret < 0) {
2944 goto end;
2945 }
2946
2947 /* Main loop */
2948 DBG("Channel main loop started");
2949
2950 while (1) {
2951 restart:
2952 health_code_update();
2953 DBG("Channel poll wait");
2954 health_poll_entry();
2955 ret = lttng_poll_wait(&events, -1);
2956 DBG("Channel poll return from wait with %d fd(s)",
2957 LTTNG_POLL_GETNB(&events));
2958 health_poll_exit();
2959 DBG("Channel event caught in thread");
2960 if (ret < 0) {
2961 if (errno == EINTR) {
2962 ERR("Poll EINTR caught");
2963 goto restart;
2964 }
2965 if (LTTNG_POLL_GETNB(&events) == 0) {
2966 err = 0; /* All is OK */
2967 }
2968 goto end;
2969 }
2970
2971 nb_fd = ret;
2972
2973 /* From here, the event is a channel wait fd */
2974 for (i = 0; i < nb_fd; i++) {
2975 health_code_update();
2976
2977 revents = LTTNG_POLL_GETEV(&events, i);
2978 pollfd = LTTNG_POLL_GETFD(&events, i);
2979
2980 if (pollfd == ctx->consumer_channel_pipe[0]) {
2981 if (revents & LPOLLIN) {
2982 enum consumer_channel_action action;
2983 uint64_t key;
2984
2985 ret = read_channel_pipe(ctx, &chan, &key, &action);
2986 if (ret <= 0) {
2987 if (ret < 0) {
2988 ERR("Error reading channel pipe");
2989 }
2990 lttng_poll_del(&events, ctx->consumer_channel_pipe[0]);
2991 continue;
2992 }
2993
2994 switch (action) {
2995 case CONSUMER_CHANNEL_ADD:
2996 DBG("Adding channel %d to poll set",
2997 chan->wait_fd);
2998
2999 lttng_ht_node_init_u64(&chan->wait_fd_node,
3000 chan->wait_fd);
3001 rcu_read_lock();
3002 lttng_ht_add_unique_u64(channel_ht,
3003 &chan->wait_fd_node);
3004 rcu_read_unlock();
3005 /* Add channel to the global poll events list */
3006 lttng_poll_add(&events, chan->wait_fd,
3007 LPOLLERR | LPOLLHUP);
3008 break;
3009 case CONSUMER_CHANNEL_DEL:
3010 {
3011 /*
3012 * This command should never be called if the channel
3013 * has streams monitored by either the data or metadata
3014 * thread. The consumer only notify this thread with a
3015 * channel del. command if it receives a destroy
3016 * channel command from the session daemon that send it
3017 * if a command prior to the GET_CHANNEL failed.
3018 */
3019
3020 rcu_read_lock();
3021 chan = consumer_find_channel(key);
3022 if (!chan) {
3023 rcu_read_unlock();
3024 ERR("UST consumer get channel key %" PRIu64 " not found for del channel", key);
3025 break;
3026 }
3027 lttng_poll_del(&events, chan->wait_fd);
3028 iter.iter.node = &chan->wait_fd_node.node;
3029 ret = lttng_ht_del(channel_ht, &iter);
3030 assert(ret == 0);
3031
3032 switch (consumer_data.type) {
3033 case LTTNG_CONSUMER_KERNEL:
3034 break;
3035 case LTTNG_CONSUMER32_UST:
3036 case LTTNG_CONSUMER64_UST:
3037 health_code_update();
3038 /* Destroy streams that might have been left in the stream list. */
3039 clean_channel_stream_list(chan);
3040 break;
3041 default:
3042 ERR("Unknown consumer_data type");
3043 assert(0);
3044 }
3045
3046 /*
3047 * Release our own refcount. Force channel deletion even if
3048 * streams were not initialized.
3049 */
3050 if (!uatomic_sub_return(&chan->refcount, 1)) {
3051 consumer_del_channel(chan);
3052 }
3053 rcu_read_unlock();
3054 goto restart;
3055 }
3056 case CONSUMER_CHANNEL_QUIT:
3057 /*
3058 * Remove the pipe from the poll set and continue the loop
3059 * since their might be data to consume.
3060 */
3061 lttng_poll_del(&events, ctx->consumer_channel_pipe[0]);
3062 continue;
3063 default:
3064 ERR("Unknown action");
3065 break;
3066 }
3067 } else if (revents & (LPOLLERR | LPOLLHUP)) {
3068 DBG("Channel thread pipe hung up");
3069 /*
3070 * Remove the pipe from the poll set and continue the loop
3071 * since their might be data to consume.
3072 */
3073 lttng_poll_del(&events, ctx->consumer_channel_pipe[0]);
3074 continue;
3075 } else {
3076 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
3077 goto end;
3078 }
3079
3080 /* Handle other stream */
3081 continue;
3082 }
3083
3084 rcu_read_lock();
3085 {
3086 uint64_t tmp_id = (uint64_t) pollfd;
3087
3088 lttng_ht_lookup(channel_ht, &tmp_id, &iter);
3089 }
3090 node = lttng_ht_iter_get_node_u64(&iter);
3091 assert(node);
3092
3093 chan = caa_container_of(node, struct lttng_consumer_channel,
3094 wait_fd_node);
3095
3096 /* Check for error event */
3097 if (revents & (LPOLLERR | LPOLLHUP)) {
3098 DBG("Channel fd %d is hup|err.", pollfd);
3099
3100 lttng_poll_del(&events, chan->wait_fd);
3101 ret = lttng_ht_del(channel_ht, &iter);
3102 assert(ret == 0);
3103
3104 /*
3105 * This will close the wait fd for each stream associated to
3106 * this channel AND monitored by the data/metadata thread thus
3107 * will be clean by the right thread.
3108 */
3109 consumer_close_channel_streams(chan);
3110
3111 /* Release our own refcount */
3112 if (!uatomic_sub_return(&chan->refcount, 1)
3113 && !uatomic_read(&chan->nb_init_stream_left)) {
3114 consumer_del_channel(chan);
3115 }
3116 } else {
3117 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
3118 rcu_read_unlock();
3119 goto end;
3120 }
3121
3122 /* Release RCU lock for the channel looked up */
3123 rcu_read_unlock();
3124 }
3125 }
3126
3127 /* All is OK */
3128 err = 0;
3129 end:
3130 lttng_poll_clean(&events);
3131 end_poll:
3132 destroy_channel_ht(channel_ht);
3133 end_ht:
3134 error_testpoint:
3135 DBG("Channel poll thread exiting");
3136 if (err) {
3137 health_error();
3138 ERR("Health error occurred in %s", __func__);
3139 }
3140 health_unregister(health_consumerd);
3141 rcu_unregister_thread();
3142 return NULL;
3143 }
3144
3145 static int set_metadata_socket(struct lttng_consumer_local_data *ctx,
3146 struct pollfd *sockpoll, int client_socket)
3147 {
3148 int ret;
3149
3150 assert(ctx);
3151 assert(sockpoll);
3152
3153 ret = lttng_consumer_poll_socket(sockpoll);
3154 if (ret) {
3155 goto error;
3156 }
3157 DBG("Metadata connection on client_socket");
3158
3159 /* Blocking call, waiting for transmission */
3160 ctx->consumer_metadata_socket = lttcomm_accept_unix_sock(client_socket);
3161 if (ctx->consumer_metadata_socket < 0) {
3162 WARN("On accept metadata");
3163 ret = -1;
3164 goto error;
3165 }
3166 ret = 0;
3167
3168 error:
3169 return ret;
3170 }
3171
3172 /*
3173 * This thread listens on the consumerd socket and receives the file
3174 * descriptors from the session daemon.
3175 */
3176 void *consumer_thread_sessiond_poll(void *data)
3177 {
3178 int sock = -1, client_socket, ret, err = -1;
3179 /*
3180 * structure to poll for incoming data on communication socket avoids
3181 * making blocking sockets.
3182 */
3183 struct pollfd consumer_sockpoll[2];
3184 struct lttng_consumer_local_data *ctx = data;
3185
3186 rcu_register_thread();
3187
3188 health_register(health_consumerd, HEALTH_CONSUMERD_TYPE_SESSIOND);
3189
3190 if (testpoint(consumerd_thread_sessiond)) {
3191 goto error_testpoint;
3192 }
3193
3194 health_code_update();
3195
3196 DBG("Creating command socket %s", ctx->consumer_command_sock_path);
3197 unlink(ctx->consumer_command_sock_path);
3198 client_socket = lttcomm_create_unix_sock(ctx->consumer_command_sock_path);
3199 if (client_socket < 0) {
3200 ERR("Cannot create command socket");
3201 goto end;
3202 }
3203
3204 ret = lttcomm_listen_unix_sock(client_socket);
3205 if (ret < 0) {
3206 goto end;
3207 }
3208
3209 DBG("Sending ready command to lttng-sessiond");
3210 ret = lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_COMMAND_SOCK_READY);
3211 /* return < 0 on error, but == 0 is not fatal */
3212 if (ret < 0) {
3213 ERR("Error sending ready command to lttng-sessiond");
3214 goto end;
3215 }
3216
3217 /* prepare the FDs to poll : to client socket and the should_quit pipe */
3218 consumer_sockpoll[0].fd = ctx->consumer_should_quit[0];
3219 consumer_sockpoll[0].events = POLLIN | POLLPRI;
3220 consumer_sockpoll[1].fd = client_socket;
3221 consumer_sockpoll[1].events = POLLIN | POLLPRI;
3222
3223 ret = lttng_consumer_poll_socket(consumer_sockpoll);
3224 if (ret) {
3225 if (ret > 0) {
3226 /* should exit */
3227 err = 0;
3228 }
3229 goto end;
3230 }
3231 DBG("Connection on client_socket");
3232
3233 /* Blocking call, waiting for transmission */
3234 sock = lttcomm_accept_unix_sock(client_socket);
3235 if (sock < 0) {
3236 WARN(&qu