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