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