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