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