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