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