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