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