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