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