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