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