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