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