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