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