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