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