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