Rename "tsc" to "timestamp"
[lttng-ust.git] / src / common / ringbuffer / ring_buffer_frontend.c
CommitLineData
852c2936 1/*
c0c0989a 2 * SPDX-License-Identifier: LGPL-2.1-only
852c2936 3 *
e92f3e28
MD
4 * Copyright (C) 2005-2012 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
5 *
852c2936
MD
6 * Ring buffer wait-free buffer synchronization. Producer-consumer and flight
7 * recorder (overwrite) modes. See thesis:
8 *
9 * Desnoyers, Mathieu (2009), "Low-Impact Operating System Tracing", Ph.D.
10 * dissertation, Ecole Polytechnique de Montreal.
11 * http://www.lttng.org/pub/thesis/desnoyers-dissertation-2009-12.pdf
12 *
13 * - Algorithm presentation in Chapter 5:
14 * "Lockless Multi-Core High-Throughput Buffering".
15 * - Algorithm formal verification in Section 8.6:
16 * "Formal verification of LTTng"
17 *
18 * Author:
19 * Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
20 *
21 * Inspired from LTT and RelayFS:
22 * Karim Yaghmour <karim@opersys.com>
23 * Tom Zanussi <zanussi@us.ibm.com>
24 * Bob Wisniewski <bob@watson.ibm.com>
25 * And from K42 :
26 * Bob Wisniewski <bob@watson.ibm.com>
27 *
28 * Buffer reader semantic :
29 *
30 * - get_subbuf_size
31 * while buffer is not finalized and empty
32 * - get_subbuf
33 * - if return value != 0, continue
34 * - splice one subbuffer worth of data to a pipe
35 * - splice the data from pipe to disk/network
36 * - put_subbuf
852c2936
MD
37 */
38
3fbec7dc 39#define _LGPL_SOURCE
a6352fd4 40#include <sys/types.h>
431d5cf0
MD
41#include <sys/mman.h>
42#include <sys/stat.h>
03d2d293 43#include <unistd.h>
431d5cf0 44#include <fcntl.h>
03d2d293
MD
45#include <signal.h>
46#include <time.h>
932b85fa 47#include <stdbool.h>
fb31eb73 48#include <stdint.h>
14641deb 49#include <urcu/compiler.h>
a6352fd4 50#include <urcu/ref.h>
8c90a710 51#include <urcu/tls-compat.h>
327d9447 52#include <poll.h>
9d315d6d 53#include "common/macros.h"
14641deb 54
eae3c729 55#include <lttng/ust-utils.h>
0b4b8811 56#include <lttng/ust-ringbuffer-context.h>
3d3a2bb8 57
74cc1f59 58#include "common/smp.h"
0466ac28 59#include "ringbuffer-config.h"
2fed87ae 60#include "vatomic.h"
4931a13e
MD
61#include "backend.h"
62#include "frontend.h"
a6352fd4 63#include "shm.h"
6f97f9c2 64#include "rb-init.h"
27b98e6c 65#include "common/compat/errno.h" /* For ENODATA */
97572c04 66#include "common/populate.h"
852c2936 67
64493e4f
MD
68/* Print DBG() messages about events lost only every 1048576 hits */
69#define DBG_PRINT_NR_LOST (1UL << 20)
70
34a91bdb
MD
71#define LTTNG_UST_RB_SIG_FLUSH SIGRTMIN
72#define LTTNG_UST_RB_SIG_READ SIGRTMIN + 1
73#define LTTNG_UST_RB_SIG_TEARDOWN SIGRTMIN + 2
03d2d293 74#define CLOCKID CLOCK_MONOTONIC
dddba398
MD
75#define LTTNG_UST_RING_BUFFER_GET_RETRY 10
76#define LTTNG_UST_RING_BUFFER_RETRY_DELAY_MS 10
6f97f9c2 77#define RETRY_DELAY_MS 100 /* 100 ms. */
03d2d293 78
a9ff648c
MD
79/*
80 * Non-static to ensure the compiler does not optimize away the xor.
81 */
95fa2ba4
MJ
82uint8_t lttng_crash_magic_xor[]
83 __attribute__((visibility("hidden")));
a9ff648c
MD
84uint8_t lttng_crash_magic_xor[] = RB_CRASH_DUMP_ABI_MAGIC_XOR;
85
2432c3c9
MD
86/*
87 * Use POSIX SHM: shm_open(3) and shm_unlink(3).
88 * close(2) to close the fd returned by shm_open.
89 * shm_unlink releases the shared memory object name.
90 * ftruncate(2) sets the size of the memory object.
91 * mmap/munmap maps the shared memory obj to a virtual address in the
92 * calling proceess (should be done both in libust and consumer).
93 * See shm_overview(7) for details.
94 * Pass file descriptor returned by shm_open(3) to ltt-sessiond through
95 * a UNIX socket.
96 *
97 * Since we don't need to access the object using its name, we can
98 * immediately shm_unlink(3) it, and only keep the handle with its file
99 * descriptor.
100 */
101
852c2936
MD
102/*
103 * Internal structure representing offsets to use at a sub-buffer switch.
104 */
105struct switch_offsets {
106 unsigned long begin, end, old;
107 size_t pre_header_padding, size;
1ad21f70
MD
108 unsigned int switch_new_start:1, switch_new_end:1, switch_old_start:1,
109 switch_old_end:1;
852c2936
MD
110};
111
16adecf1 112DEFINE_URCU_TLS(unsigned int, lib_ring_buffer_nesting);
852c2936 113
cb7378b3
MD
114/*
115 * wakeup_fd_mutex protects wakeup fd use by timer from concurrent
116 * close.
117 */
118static pthread_mutex_t wakeup_fd_mutex = PTHREAD_MUTEX_INITIALIZER;
119
852c2936 120static
b5457df5
MD
121void lib_ring_buffer_print_errors(struct lttng_ust_ring_buffer_channel *chan,
122 struct lttng_ust_ring_buffer *buf, int cpu,
009769ca 123 struct lttng_ust_shm_handle *handle);
852c2936 124
03d2d293
MD
125/*
126 * Handle timer teardown race wrt memory free of private data by
127 * ring buffer signals are handled by a single thread, which permits
128 * a synchronization point between handling of each signal.
64bf51a6 129 * Protected by the lock within the structure.
03d2d293
MD
130 */
131struct timer_signal_data {
132 pthread_t tid; /* thread id managing signals */
133 int setup_done;
134 int qs_done;
64bf51a6 135 pthread_mutex_t lock;
03d2d293
MD
136};
137
64bf51a6
MD
138static struct timer_signal_data timer_signal = {
139 .tid = 0,
140 .setup_done = 0,
141 .qs_done = 0,
142 .lock = PTHREAD_MUTEX_INITIALIZER,
143};
03d2d293 144
b2c5f61a 145static bool lttng_ust_allow_blocking;
6f97f9c2 146
b2c5f61a 147void lttng_ust_ringbuffer_set_allow_blocking(void)
6f97f9c2 148{
b2c5f61a
MD
149 lttng_ust_allow_blocking = true;
150}
151
152/* Get blocking timeout, in ms */
b5457df5 153static int lttng_ust_ringbuffer_get_timeout(struct lttng_ust_ring_buffer_channel *chan)
b2c5f61a
MD
154{
155 if (!lttng_ust_allow_blocking)
156 return 0;
157 return chan->u.s.blocking_timeout_ms;
6f97f9c2
MD
158}
159
852c2936
MD
160/**
161 * lib_ring_buffer_reset - Reset ring buffer to initial values.
162 * @buf: Ring buffer.
163 *
164 * Effectively empty the ring buffer. Should be called when the buffer is not
165 * used for writing. The ring buffer can be opened for reading, but the reader
166 * should not be using the iterator concurrently with reset. The previous
167 * current iterator record is reset.
168 */
b5457df5 169void lib_ring_buffer_reset(struct lttng_ust_ring_buffer *buf,
38fae1d3 170 struct lttng_ust_shm_handle *handle)
852c2936 171{
b5457df5
MD
172 struct lttng_ust_ring_buffer_channel *chan;
173 const struct lttng_ust_ring_buffer_config *config;
852c2936
MD
174 unsigned int i;
175
34daae3e
MD
176 chan = shmp(handle, buf->backend.chan);
177 if (!chan)
15500a1b 178 return;
34daae3e 179 config = &chan->backend.config;
852c2936
MD
180 /*
181 * Reset iterator first. It will put the subbuffer if it currently holds
182 * it.
183 */
852c2936
MD
184 v_set(config, &buf->offset, 0);
185 for (i = 0; i < chan->backend.num_subbuf; i++) {
15500a1b
MD
186 struct commit_counters_hot *cc_hot;
187 struct commit_counters_cold *cc_cold;
6c737d05 188 uint64_t *ts_end;
15500a1b
MD
189
190 cc_hot = shmp_index(handle, buf->commit_hot, i);
191 if (!cc_hot)
192 return;
193 cc_cold = shmp_index(handle, buf->commit_cold, i);
194 if (!cc_cold)
195 return;
6c737d05
MD
196 ts_end = shmp_index(handle, buf->ts_end, i);
197 if (!ts_end)
198 return;
15500a1b
MD
199 v_set(config, &cc_hot->cc, 0);
200 v_set(config, &cc_hot->seq, 0);
201 v_set(config, &cc_cold->cc_sb, 0);
6c737d05 202 *ts_end = 0;
852c2936 203 }
a6352fd4
MD
204 uatomic_set(&buf->consumed, 0);
205 uatomic_set(&buf->record_disabled, 0);
373ea80a 206 v_set(config, &buf->last_timestamp, 0);
1d498196 207 lib_ring_buffer_backend_reset(&buf->backend, handle);
852c2936
MD
208 /* Don't reset number of active readers */
209 v_set(config, &buf->records_lost_full, 0);
210 v_set(config, &buf->records_lost_wrap, 0);
211 v_set(config, &buf->records_lost_big, 0);
212 v_set(config, &buf->records_count, 0);
213 v_set(config, &buf->records_overrun, 0);
214 buf->finalized = 0;
215}
852c2936
MD
216
217/**
218 * channel_reset - Reset channel to initial values.
219 * @chan: Channel.
220 *
221 * Effectively empty the channel. Should be called when the channel is not used
222 * for writing. The channel can be opened for reading, but the reader should not
223 * be using the iterator concurrently with reset. The previous current iterator
224 * record is reset.
225 */
b5457df5 226void channel_reset(struct lttng_ust_ring_buffer_channel *chan)
852c2936
MD
227{
228 /*
229 * Reset iterators first. Will put the subbuffer if held for reading.
230 */
a6352fd4 231 uatomic_set(&chan->record_disabled, 0);
852c2936
MD
232 /* Don't reset commit_count_mask, still valid */
233 channel_backend_reset(&chan->backend);
234 /* Don't reset switch/read timer interval */
235 /* Don't reset notifiers and notifier enable bits */
236 /* Don't reset reader reference count */
237}
852c2936 238
a9ff648c 239static
b5457df5 240void init_crash_abi(const struct lttng_ust_ring_buffer_config *config,
a9ff648c 241 struct lttng_crash_abi *crash_abi,
b5457df5 242 struct lttng_ust_ring_buffer *buf,
a9ff648c
MD
243 struct channel_backend *chanb,
244 struct shm_object *shmobj,
245 struct lttng_ust_shm_handle *handle)
246{
247 int i;
248
249 for (i = 0; i < RB_CRASH_DUMP_ABI_MAGIC_LEN; i++)
250 crash_abi->magic[i] = lttng_crash_magic_xor[i] ^ 0xFF;
251 crash_abi->mmap_length = shmobj->memory_map_size;
252 crash_abi->endian = RB_CRASH_ENDIAN;
253 crash_abi->major = RB_CRASH_DUMP_ABI_MAJOR;
254 crash_abi->minor = RB_CRASH_DUMP_ABI_MINOR;
255 crash_abi->word_size = sizeof(unsigned long);
256 crash_abi->layout_type = LTTNG_CRASH_TYPE_UST;
257
258 /* Offset of fields */
259 crash_abi->offset.prod_offset =
260 (uint32_t) ((char *) &buf->offset - (char *) buf);
261 crash_abi->offset.consumed_offset =
262 (uint32_t) ((char *) &buf->consumed - (char *) buf);
263 crash_abi->offset.commit_hot_array =
264 (uint32_t) ((char *) shmp(handle, buf->commit_hot) - (char *) buf);
265 crash_abi->offset.commit_hot_seq =
266 offsetof(struct commit_counters_hot, seq);
267 crash_abi->offset.buf_wsb_array =
268 (uint32_t) ((char *) shmp(handle, buf->backend.buf_wsb) - (char *) buf);
269 crash_abi->offset.buf_wsb_id =
b5457df5 270 offsetof(struct lttng_ust_ring_buffer_backend_subbuffer, id);
a9ff648c
MD
271 crash_abi->offset.sb_array =
272 (uint32_t) ((char *) shmp(handle, buf->backend.array) - (char *) buf);
273 crash_abi->offset.sb_array_shmp_offset =
b5457df5 274 offsetof(struct lttng_ust_ring_buffer_backend_pages_shmp,
a9ff648c
MD
275 shmp._ref.offset);
276 crash_abi->offset.sb_backend_p_offset =
b5457df5 277 offsetof(struct lttng_ust_ring_buffer_backend_pages,
a9ff648c
MD
278 p._ref.offset);
279
280 /* Field length */
281 crash_abi->length.prod_offset = sizeof(buf->offset);
282 crash_abi->length.consumed_offset = sizeof(buf->consumed);
283 crash_abi->length.commit_hot_seq =
284 sizeof(((struct commit_counters_hot *) NULL)->seq);
285 crash_abi->length.buf_wsb_id =
b5457df5 286 sizeof(((struct lttng_ust_ring_buffer_backend_subbuffer *) NULL)->id);
a9ff648c 287 crash_abi->length.sb_array_shmp_offset =
b5457df5 288 sizeof(((struct lttng_ust_ring_buffer_backend_pages_shmp *) NULL)->shmp._ref.offset);
a9ff648c 289 crash_abi->length.sb_backend_p_offset =
b5457df5 290 sizeof(((struct lttng_ust_ring_buffer_backend_pages *) NULL)->p._ref.offset);
a9ff648c
MD
291
292 /* Array stride */
293 crash_abi->stride.commit_hot_array =
294 sizeof(struct commit_counters_hot);
295 crash_abi->stride.buf_wsb_array =
b5457df5 296 sizeof(struct lttng_ust_ring_buffer_backend_subbuffer);
a9ff648c 297 crash_abi->stride.sb_array =
b5457df5 298 sizeof(struct lttng_ust_ring_buffer_backend_pages_shmp);
a9ff648c
MD
299
300 /* Buffer constants */
301 crash_abi->buf_size = chanb->buf_size;
302 crash_abi->subbuf_size = chanb->subbuf_size;
303 crash_abi->num_subbuf = chanb->num_subbuf;
304 crash_abi->mode = (uint32_t) chanb->config.mode;
305
306 if (config->cb.content_size_field) {
307 size_t offset, length;
308
309 config->cb.content_size_field(config, &offset, &length);
310 crash_abi->offset.content_size = offset;
311 crash_abi->length.content_size = length;
312 } else {
313 crash_abi->offset.content_size = 0;
314 crash_abi->length.content_size = 0;
315 }
316 if (config->cb.packet_size_field) {
317 size_t offset, length;
318
319 config->cb.packet_size_field(config, &offset, &length);
320 crash_abi->offset.packet_size = offset;
321 crash_abi->length.packet_size = length;
322 } else {
323 crash_abi->offset.packet_size = 0;
324 crash_abi->length.packet_size = 0;
325 }
326}
327
852c2936
MD
328/*
329 * Must be called under cpu hotplug protection.
330 */
b5457df5 331int lib_ring_buffer_create(struct lttng_ust_ring_buffer *buf,
a6352fd4 332 struct channel_backend *chanb, int cpu,
38fae1d3 333 struct lttng_ust_shm_handle *handle,
1d498196 334 struct shm_object *shmobj)
852c2936 335{
b5457df5
MD
336 const struct lttng_ust_ring_buffer_config *config = &chanb->config;
337 struct lttng_ust_ring_buffer_channel *chan = caa_container_of(chanb,
338 struct lttng_ust_ring_buffer_channel, backend);
339 struct lttng_ust_ring_buffer_backend_subbuffer *wsb;
340 struct lttng_ust_ring_buffer_channel *shmp_chan;
15500a1b 341 struct commit_counters_hot *cc_hot;
f0fde1c3 342 void *priv = channel_get_private_config(chan);
852c2936 343 size_t subbuf_header_size;
373ea80a 344 uint64_t timestamp;
852c2936
MD
345 int ret;
346
347 /* Test for cpu hotplug */
348 if (buf->backend.allocated)
349 return 0;
350
1d498196
MD
351 align_shm(shmobj, __alignof__(struct commit_counters_hot));
352 set_shmp(buf->commit_hot,
353 zalloc_shm(shmobj,
354 sizeof(struct commit_counters_hot) * chan->backend.num_subbuf));
355 if (!shmp(handle, buf->commit_hot)) {
a9ff648c 356 return -ENOMEM;
852c2936
MD
357 }
358
1d498196
MD
359 align_shm(shmobj, __alignof__(struct commit_counters_cold));
360 set_shmp(buf->commit_cold,
361 zalloc_shm(shmobj,
362 sizeof(struct commit_counters_cold) * chan->backend.num_subbuf));
363 if (!shmp(handle, buf->commit_cold)) {
852c2936
MD
364 ret = -ENOMEM;
365 goto free_commit;
366 }
367
6c737d05
MD
368 align_shm(shmobj, __alignof__(uint64_t));
369 set_shmp(buf->ts_end,
370 zalloc_shm(shmobj,
371 sizeof(uint64_t) * chan->backend.num_subbuf));
372 if (!shmp(handle, buf->ts_end)) {
373 ret = -ENOMEM;
374 goto free_commit_cold;
375 }
376
377
a9ff648c
MD
378 ret = lib_ring_buffer_backend_create(&buf->backend, &chan->backend,
379 cpu, handle, shmobj);
380 if (ret) {
381 goto free_init;
382 }
383
852c2936
MD
384 /*
385 * Write the subbuffer header for first subbuffer so we know the total
386 * duration of data gathering.
387 */
388 subbuf_header_size = config->cb.subbuffer_header_size();
389 v_set(config, &buf->offset, subbuf_header_size);
15500a1b
MD
390 wsb = shmp_index(handle, buf->backend.buf_wsb, 0);
391 if (!wsb) {
392 ret = -EPERM;
393 goto free_chanbuf;
394 }
395 subbuffer_id_clear_noref(config, &wsb->id);
396 shmp_chan = shmp(handle, buf->backend.chan);
397 if (!shmp_chan) {
398 ret = -EPERM;
399 goto free_chanbuf;
400 }
373ea80a
MD
401 timestamp = config->cb.ring_buffer_clock_read(shmp_chan);
402 config->cb.buffer_begin(buf, timestamp, 0, handle);
15500a1b
MD
403 cc_hot = shmp_index(handle, buf->commit_hot, 0);
404 if (!cc_hot) {
405 ret = -EPERM;
406 goto free_chanbuf;
407 }
408 v_add(config, subbuf_header_size, &cc_hot->cc);
409 v_add(config, subbuf_header_size, &cc_hot->seq);
852c2936
MD
410
411 if (config->cb.buffer_create) {
1d498196 412 ret = config->cb.buffer_create(buf, priv, cpu, chanb->name, handle);
852c2936 413 if (ret)
a9ff648c 414 goto free_chanbuf;
852c2936 415 }
a9ff648c
MD
416
417 init_crash_abi(config, &buf->crash_abi, buf, chanb, shmobj, handle);
418
852c2936 419 buf->backend.allocated = 1;
852c2936
MD
420 return 0;
421
422 /* Error handling */
423free_init:
6c737d05
MD
424 /* ts_end will be freed by shm teardown */
425free_commit_cold:
a6352fd4 426 /* commit_cold will be freed by shm teardown */
852c2936 427free_commit:
a6352fd4 428 /* commit_hot will be freed by shm teardown */
852c2936 429free_chanbuf:
852c2936
MD
430 return ret;
431}
432
03d2d293 433static
2208d8b5
MJ
434void lib_ring_buffer_channel_switch_timer(int sig __attribute__((unused)),
435 siginfo_t *si, void *uc __attribute__((unused)))
852c2936 436{
b5457df5 437 const struct lttng_ust_ring_buffer_config *config;
03d2d293 438 struct lttng_ust_shm_handle *handle;
b5457df5 439 struct lttng_ust_ring_buffer_channel *chan;
03d2d293
MD
440 int cpu;
441
442 assert(CMM_LOAD_SHARED(timer_signal.tid) == pthread_self());
443
444 chan = si->si_value.sival_ptr;
445 handle = chan->handle;
446 config = &chan->backend.config;
852c2936 447
34a91bdb 448 DBG("Switch timer for channel %p\n", chan);
03d2d293 449
4dcd7e80
MD
450 /*
451 * Only flush buffers periodically if readers are active.
452 */
cb7378b3 453 pthread_mutex_lock(&wakeup_fd_mutex);
03d2d293
MD
454 if (config->alloc == RING_BUFFER_ALLOC_PER_CPU) {
455 for_each_possible_cpu(cpu) {
b5457df5 456 struct lttng_ust_ring_buffer *buf =
03d2d293 457 shmp(handle, chan->backend.buf[cpu].shmp);
34daae3e
MD
458
459 if (!buf)
15500a1b 460 goto end;
4dcd7e80
MD
461 if (uatomic_read(&buf->active_readers))
462 lib_ring_buffer_switch_slow(buf, SWITCH_ACTIVE,
463 chan->handle);
03d2d293
MD
464 }
465 } else {
b5457df5 466 struct lttng_ust_ring_buffer *buf =
03d2d293
MD
467 shmp(handle, chan->backend.buf[0].shmp);
468
34daae3e 469 if (!buf)
15500a1b 470 goto end;
34a91bdb
MD
471 if (uatomic_read(&buf->active_readers))
472 lib_ring_buffer_switch_slow(buf, SWITCH_ACTIVE,
473 chan->handle);
474 }
15500a1b 475end:
34a91bdb
MD
476 pthread_mutex_unlock(&wakeup_fd_mutex);
477 return;
478}
479
b07cd987 480static
b5457df5
MD
481int lib_ring_buffer_poll_deliver(const struct lttng_ust_ring_buffer_config *config,
482 struct lttng_ust_ring_buffer *buf,
483 struct lttng_ust_ring_buffer_channel *chan,
b07cd987
MD
484 struct lttng_ust_shm_handle *handle)
485{
486 unsigned long consumed_old, consumed_idx, commit_count, write_offset;
15500a1b 487 struct commit_counters_cold *cc_cold;
b07cd987
MD
488
489 consumed_old = uatomic_read(&buf->consumed);
490 consumed_idx = subbuf_index(consumed_old, chan);
15500a1b
MD
491 cc_cold = shmp_index(handle, buf->commit_cold, consumed_idx);
492 if (!cc_cold)
493 return 0;
494 commit_count = v_read(config, &cc_cold->cc_sb);
b07cd987
MD
495 /*
496 * No memory barrier here, since we are only interested
497 * in a statistically correct polling result. The next poll will
498 * get the data is we are racing. The mb() that ensures correct
499 * memory order is in get_subbuf.
500 */
501 write_offset = v_read(config, &buf->offset);
502
503 /*
504 * Check that the subbuffer we are trying to consume has been
505 * already fully committed.
506 */
507
508 if (((commit_count - chan->backend.subbuf_size)
509 & chan->commit_count_mask)
510 - (buf_trunc(consumed_old, chan)
511 >> chan->backend.num_subbuf_order)
512 != 0)
513 return 0;
514
515 /*
516 * Check that we are not about to read the same subbuffer in
517 * which the writer head is.
518 */
519 if (subbuf_trunc(write_offset, chan) - subbuf_trunc(consumed_old, chan)
520 == 0)
521 return 0;
522
523 return 1;
524}
525
526static
b5457df5 527void lib_ring_buffer_wakeup(struct lttng_ust_ring_buffer *buf,
b07cd987
MD
528 struct lttng_ust_shm_handle *handle)
529{
530 int wakeup_fd = shm_get_wakeup_fd(handle, &buf->self._ref);
531 sigset_t sigpipe_set, pending_set, old_set;
532 int ret, sigpipe_was_pending = 0;
533
534 if (wakeup_fd < 0)
535 return;
536
537 /*
538 * Wake-up the other end by writing a null byte in the pipe
539 * (non-blocking). Important note: Because writing into the
540 * pipe is non-blocking (and therefore we allow dropping wakeup
541 * data, as long as there is wakeup data present in the pipe
542 * buffer to wake up the consumer), the consumer should perform
543 * the following sequence for waiting:
544 * 1) empty the pipe (reads).
545 * 2) check if there is data in the buffer.
546 * 3) wait on the pipe (poll).
547 *
548 * Discard the SIGPIPE from write(), not disturbing any SIGPIPE
549 * that might be already pending. If a bogus SIGPIPE is sent to
550 * the entire process concurrently by a malicious user, it may
551 * be simply discarded.
552 */
553 ret = sigemptyset(&pending_set);
554 assert(!ret);
555 /*
556 * sigpending returns the mask of signals that are _both_
557 * blocked for the thread _and_ pending for either the thread or
558 * the entire process.
559 */
560 ret = sigpending(&pending_set);
561 assert(!ret);
562 sigpipe_was_pending = sigismember(&pending_set, SIGPIPE);
563 /*
564 * If sigpipe was pending, it means it was already blocked, so
565 * no need to block it.
566 */
567 if (!sigpipe_was_pending) {
568 ret = sigemptyset(&sigpipe_set);
569 assert(!ret);
570 ret = sigaddset(&sigpipe_set, SIGPIPE);
571 assert(!ret);
572 ret = pthread_sigmask(SIG_BLOCK, &sigpipe_set, &old_set);
573 assert(!ret);
574 }
575 do {
576 ret = write(wakeup_fd, "", 1);
577 } while (ret == -1L && errno == EINTR);
578 if (ret == -1L && errno == EPIPE && !sigpipe_was_pending) {
579 struct timespec timeout = { 0, 0 };
580 do {
581 ret = sigtimedwait(&sigpipe_set, NULL,
582 &timeout);
583 } while (ret == -1L && errno == EINTR);
584 }
585 if (!sigpipe_was_pending) {
586 ret = pthread_sigmask(SIG_SETMASK, &old_set, NULL);
587 assert(!ret);
588 }
589}
590
34a91bdb 591static
b5457df5 592void lib_ring_buffer_channel_do_read(struct lttng_ust_ring_buffer_channel *chan)
34a91bdb 593{
b5457df5 594 const struct lttng_ust_ring_buffer_config *config;
34a91bdb
MD
595 struct lttng_ust_shm_handle *handle;
596 int cpu;
597
598 handle = chan->handle;
599 config = &chan->backend.config;
600
601 /*
602 * Only flush buffers periodically if readers are active.
603 */
604 pthread_mutex_lock(&wakeup_fd_mutex);
605 if (config->alloc == RING_BUFFER_ALLOC_PER_CPU) {
606 for_each_possible_cpu(cpu) {
b5457df5 607 struct lttng_ust_ring_buffer *buf =
34a91bdb
MD
608 shmp(handle, chan->backend.buf[cpu].shmp);
609
34daae3e 610 if (!buf)
15500a1b 611 goto end;
34a91bdb
MD
612 if (uatomic_read(&buf->active_readers)
613 && lib_ring_buffer_poll_deliver(config, buf,
614 chan, handle)) {
615 lib_ring_buffer_wakeup(buf, handle);
616 }
617 }
618 } else {
b5457df5 619 struct lttng_ust_ring_buffer *buf =
34a91bdb
MD
620 shmp(handle, chan->backend.buf[0].shmp);
621
34daae3e 622 if (!buf)
15500a1b 623 goto end;
34a91bdb
MD
624 if (uatomic_read(&buf->active_readers)
625 && lib_ring_buffer_poll_deliver(config, buf,
626 chan, handle)) {
627 lib_ring_buffer_wakeup(buf, handle);
628 }
03d2d293 629 }
15500a1b 630end:
cb7378b3 631 pthread_mutex_unlock(&wakeup_fd_mutex);
34a91bdb
MD
632}
633
634static
2208d8b5
MJ
635void lib_ring_buffer_channel_read_timer(int sig __attribute__((unused)),
636 siginfo_t *si, void *uc __attribute__((unused)))
34a91bdb 637{
b5457df5 638 struct lttng_ust_ring_buffer_channel *chan;
34a91bdb
MD
639
640 assert(CMM_LOAD_SHARED(timer_signal.tid) == pthread_self());
641 chan = si->si_value.sival_ptr;
642 DBG("Read timer for channel %p\n", chan);
643 lib_ring_buffer_channel_do_read(chan);
03d2d293
MD
644 return;
645}
646
647static
648void rb_setmask(sigset_t *mask)
649{
650 int ret;
651
652 ret = sigemptyset(mask);
653 if (ret) {
654 PERROR("sigemptyset");
655 }
34a91bdb
MD
656 ret = sigaddset(mask, LTTNG_UST_RB_SIG_FLUSH);
657 if (ret) {
658 PERROR("sigaddset");
659 }
660 ret = sigaddset(mask, LTTNG_UST_RB_SIG_READ);
03d2d293
MD
661 if (ret) {
662 PERROR("sigaddset");
663 }
664 ret = sigaddset(mask, LTTNG_UST_RB_SIG_TEARDOWN);
665 if (ret) {
666 PERROR("sigaddset");
667 }
668}
669
670static
2208d8b5 671void *sig_thread(void *arg __attribute__((unused)))
03d2d293
MD
672{
673 sigset_t mask;
674 siginfo_t info;
675 int signr;
676
677 /* Only self thread will receive signal mask. */
678 rb_setmask(&mask);
679 CMM_STORE_SHARED(timer_signal.tid, pthread_self());
680
681 for (;;) {
682 signr = sigwaitinfo(&mask, &info);
683 if (signr == -1) {
34a91bdb
MD
684 if (errno != EINTR)
685 PERROR("sigwaitinfo");
03d2d293
MD
686 continue;
687 }
34a91bdb 688 if (signr == LTTNG_UST_RB_SIG_FLUSH) {
03d2d293
MD
689 lib_ring_buffer_channel_switch_timer(info.si_signo,
690 &info, NULL);
34a91bdb
MD
691 } else if (signr == LTTNG_UST_RB_SIG_READ) {
692 lib_ring_buffer_channel_read_timer(info.si_signo,
693 &info, NULL);
03d2d293
MD
694 } else if (signr == LTTNG_UST_RB_SIG_TEARDOWN) {
695 cmm_smp_mb();
696 CMM_STORE_SHARED(timer_signal.qs_done, 1);
697 cmm_smp_mb();
698 } else {
699 ERR("Unexptected signal %d\n", info.si_signo);
700 }
701 }
702 return NULL;
703}
704
705/*
03d2d293
MD
706 * Ensure only a single thread listens on the timer signal.
707 */
708static
709void lib_ring_buffer_setup_timer_thread(void)
710{
711 pthread_t thread;
712 int ret;
713
64bf51a6 714 pthread_mutex_lock(&timer_signal.lock);
03d2d293 715 if (timer_signal.setup_done)
64bf51a6 716 goto end;
03d2d293
MD
717
718 ret = pthread_create(&thread, NULL, &sig_thread, NULL);
719 if (ret) {
720 errno = ret;
721 PERROR("pthread_create");
722 }
723 ret = pthread_detach(thread);
724 if (ret) {
725 errno = ret;
726 PERROR("pthread_detach");
727 }
728 timer_signal.setup_done = 1;
64bf51a6
MD
729end:
730 pthread_mutex_unlock(&timer_signal.lock);
852c2936
MD
731}
732
03d2d293 733/*
64bf51a6 734 * Wait for signal-handling thread quiescent state.
03d2d293 735 */
64bf51a6
MD
736static
737void lib_ring_buffer_wait_signal_thread_qs(unsigned int signr)
738{
739 sigset_t pending_set;
740 int ret;
741
742 /*
743 * We need to be the only thread interacting with the thread
744 * that manages signals for teardown synchronization.
745 */
746 pthread_mutex_lock(&timer_signal.lock);
747
748 /*
749 * Ensure we don't have any signal queued for this channel.
750 */
751 for (;;) {
752 ret = sigemptyset(&pending_set);
753 if (ret == -1) {
754 PERROR("sigemptyset");
755 }
756 ret = sigpending(&pending_set);
757 if (ret == -1) {
758 PERROR("sigpending");
759 }
760 if (!sigismember(&pending_set, signr))
761 break;
762 caa_cpu_relax();
763 }
764
765 /*
766 * From this point, no new signal handler will be fired that
767 * would try to access "chan". However, we still need to wait
768 * for any currently executing handler to complete.
769 */
770 cmm_smp_mb();
771 CMM_STORE_SHARED(timer_signal.qs_done, 0);
772 cmm_smp_mb();
773
774 /*
775 * Kill with LTTNG_UST_RB_SIG_TEARDOWN, so signal management
776 * thread wakes up.
777 */
778 kill(getpid(), LTTNG_UST_RB_SIG_TEARDOWN);
779
780 while (!CMM_LOAD_SHARED(timer_signal.qs_done))
781 caa_cpu_relax();
782 cmm_smp_mb();
783
784 pthread_mutex_unlock(&timer_signal.lock);
785}
786
03d2d293 787static
b5457df5 788void lib_ring_buffer_channel_switch_timer_start(struct lttng_ust_ring_buffer_channel *chan)
852c2936 789{
03d2d293
MD
790 struct sigevent sev;
791 struct itimerspec its;
792 int ret;
852c2936 793
03d2d293 794 if (!chan->switch_timer_interval || chan->switch_timer_enabled)
852c2936
MD
795 return;
796
03d2d293
MD
797 chan->switch_timer_enabled = 1;
798
799 lib_ring_buffer_setup_timer_thread();
800
ba702529 801 memset(&sev, 0, sizeof(sev));
03d2d293 802 sev.sigev_notify = SIGEV_SIGNAL;
34a91bdb 803 sev.sigev_signo = LTTNG_UST_RB_SIG_FLUSH;
03d2d293
MD
804 sev.sigev_value.sival_ptr = chan;
805 ret = timer_create(CLOCKID, &sev, &chan->switch_timer);
806 if (ret == -1) {
807 PERROR("timer_create");
808 }
809
810 its.it_value.tv_sec = chan->switch_timer_interval / 1000000;
f8921d33 811 its.it_value.tv_nsec = (chan->switch_timer_interval % 1000000) * 1000;
03d2d293
MD
812 its.it_interval.tv_sec = its.it_value.tv_sec;
813 its.it_interval.tv_nsec = its.it_value.tv_nsec;
814
815 ret = timer_settime(chan->switch_timer, 0, &its, NULL);
816 if (ret == -1) {
817 PERROR("timer_settime");
818 }
819}
820
03d2d293 821static
b5457df5 822void lib_ring_buffer_channel_switch_timer_stop(struct lttng_ust_ring_buffer_channel *chan)
03d2d293 823{
34a91bdb 824 int ret;
03d2d293
MD
825
826 if (!chan->switch_timer_interval || !chan->switch_timer_enabled)
827 return;
828
829 ret = timer_delete(chan->switch_timer);
830 if (ret == -1) {
831 PERROR("timer_delete");
832 }
833
64bf51a6 834 lib_ring_buffer_wait_signal_thread_qs(LTTNG_UST_RB_SIG_FLUSH);
03d2d293
MD
835
836 chan->switch_timer = 0;
837 chan->switch_timer_enabled = 0;
852c2936
MD
838}
839
34a91bdb 840static
b5457df5 841void lib_ring_buffer_channel_read_timer_start(struct lttng_ust_ring_buffer_channel *chan)
852c2936 842{
b5457df5 843 const struct lttng_ust_ring_buffer_config *config = &chan->backend.config;
34a91bdb
MD
844 struct sigevent sev;
845 struct itimerspec its;
846 int ret;
852c2936 847
34a91bdb
MD
848 if (config->wakeup != RING_BUFFER_WAKEUP_BY_TIMER
849 || !chan->read_timer_interval || chan->read_timer_enabled)
850 return;
852c2936 851
34a91bdb 852 chan->read_timer_enabled = 1;
852c2936 853
34a91bdb 854 lib_ring_buffer_setup_timer_thread();
852c2936 855
34a91bdb
MD
856 sev.sigev_notify = SIGEV_SIGNAL;
857 sev.sigev_signo = LTTNG_UST_RB_SIG_READ;
858 sev.sigev_value.sival_ptr = chan;
859 ret = timer_create(CLOCKID, &sev, &chan->read_timer);
860 if (ret == -1) {
861 PERROR("timer_create");
862 }
852c2936 863
34a91bdb 864 its.it_value.tv_sec = chan->read_timer_interval / 1000000;
f8921d33 865 its.it_value.tv_nsec = (chan->read_timer_interval % 1000000) * 1000;
34a91bdb
MD
866 its.it_interval.tv_sec = its.it_value.tv_sec;
867 its.it_interval.tv_nsec = its.it_value.tv_nsec;
852c2936 868
34a91bdb
MD
869 ret = timer_settime(chan->read_timer, 0, &its, NULL);
870 if (ret == -1) {
871 PERROR("timer_settime");
872 }
852c2936
MD
873}
874
34a91bdb 875static
b5457df5 876void lib_ring_buffer_channel_read_timer_stop(struct lttng_ust_ring_buffer_channel *chan)
852c2936 877{
b5457df5 878 const struct lttng_ust_ring_buffer_config *config = &chan->backend.config;
34a91bdb 879 int ret;
852c2936
MD
880
881 if (config->wakeup != RING_BUFFER_WAKEUP_BY_TIMER
34a91bdb 882 || !chan->read_timer_interval || !chan->read_timer_enabled)
852c2936
MD
883 return;
884
34a91bdb
MD
885 ret = timer_delete(chan->read_timer);
886 if (ret == -1) {
887 PERROR("timer_delete");
888 }
889
852c2936
MD
890 /*
891 * do one more check to catch data that has been written in the last
892 * timer period.
893 */
34a91bdb
MD
894 lib_ring_buffer_channel_do_read(chan);
895
64bf51a6 896 lib_ring_buffer_wait_signal_thread_qs(LTTNG_UST_RB_SIG_READ);
34a91bdb
MD
897
898 chan->read_timer = 0;
899 chan->read_timer_enabled = 0;
852c2936
MD
900}
901
b5457df5 902static void channel_unregister_notifiers(struct lttng_ust_ring_buffer_channel *chan,
2208d8b5 903 struct lttng_ust_shm_handle *handle __attribute__((unused)))
852c2936 904{
03d2d293 905 lib_ring_buffer_channel_switch_timer_stop(chan);
34a91bdb 906 lib_ring_buffer_channel_read_timer_stop(chan);
852c2936
MD
907}
908
b5457df5 909static void channel_print_errors(struct lttng_ust_ring_buffer_channel *chan,
009769ca
MD
910 struct lttng_ust_shm_handle *handle)
911{
b5457df5 912 const struct lttng_ust_ring_buffer_config *config =
009769ca
MD
913 &chan->backend.config;
914 int cpu;
915
916 if (config->alloc == RING_BUFFER_ALLOC_PER_CPU) {
917 for_each_possible_cpu(cpu) {
b5457df5 918 struct lttng_ust_ring_buffer *buf =
009769ca 919 shmp(handle, chan->backend.buf[cpu].shmp);
15500a1b
MD
920 if (buf)
921 lib_ring_buffer_print_errors(chan, buf, cpu, handle);
009769ca
MD
922 }
923 } else {
b5457df5 924 struct lttng_ust_ring_buffer *buf =
009769ca
MD
925 shmp(handle, chan->backend.buf[0].shmp);
926
15500a1b
MD
927 if (buf)
928 lib_ring_buffer_print_errors(chan, buf, -1, handle);
009769ca
MD
929 }
930}
931
b5457df5 932static void channel_free(struct lttng_ust_ring_buffer_channel *chan,
6548fca4
MD
933 struct lttng_ust_shm_handle *handle,
934 int consumer)
852c2936 935{
74d81a6c 936 channel_backend_free(&chan->backend, handle);
431d5cf0 937 /* chan is freed by shm teardown */
6548fca4 938 shm_object_table_destroy(handle->table, consumer);
1d498196 939 free(handle);
852c2936
MD
940}
941
942/**
943 * channel_create - Create channel.
944 * @config: ring buffer instance configuration
945 * @name: name of the channel
f0fde1c3
MD
946 * @priv_data_align: alignment, in bytes, of the private data area. (config)
947 * @priv_data_size: length, in bytes, of the private data area. (config)
948 * @priv_data_init: initialization data for private data. (config)
949 * @priv: local private data (memory owner by caller)
852c2936
MD
950 * @buf_addr: pointer the the beginning of the preallocated buffer contiguous
951 * address mapping. It is used only by RING_BUFFER_STATIC
952 * configuration. It can be set to NULL for other backends.
953 * @subbuf_size: subbuffer size
954 * @num_subbuf: number of subbuffers
955 * @switch_timer_interval: Time interval (in us) to fill sub-buffers with
956 * padding to let readers get those sub-buffers.
957 * Used for live streaming.
958 * @read_timer_interval: Time interval (in us) to wake up pending readers.
5ea386c3
MD
959 * @stream_fds: array of stream file descriptors.
960 * @nr_stream_fds: number of file descriptors in array.
852c2936
MD
961 *
962 * Holds cpu hotplug.
963 * Returns NULL on failure.
964 */
b5457df5 965struct lttng_ust_shm_handle *channel_create(const struct lttng_ust_ring_buffer_config *config,
a3f61e7f 966 const char *name,
a3f61e7f
MD
967 size_t priv_data_align,
968 size_t priv_data_size,
d028eddb 969 void *priv_data_init,
f0fde1c3 970 void *priv,
2208d8b5 971 void *buf_addr __attribute__((unused)), size_t subbuf_size,
852c2936 972 size_t num_subbuf, unsigned int switch_timer_interval,
a9ff648c 973 unsigned int read_timer_interval,
b2c5f61a
MD
974 const int *stream_fds, int nr_stream_fds,
975 int64_t blocking_timeout)
852c2936 976{
24622edc 977 int ret;
a3f61e7f 978 size_t shmsize, chansize;
b5457df5 979 struct lttng_ust_ring_buffer_channel *chan;
38fae1d3 980 struct lttng_ust_shm_handle *handle;
1d498196 981 struct shm_object *shmobj;
74d81a6c 982 unsigned int nr_streams;
b2c5f61a 983 int64_t blocking_timeout_ms;
97572c04 984 bool populate = lttng_ust_map_populate_is_enabled();
74d81a6c
MD
985
986 if (config->alloc == RING_BUFFER_ALLOC_PER_CPU)
a616fb4e 987 nr_streams = get_possible_cpus_array_len();
74d81a6c
MD
988 else
989 nr_streams = 1;
852c2936 990
5ea386c3
MD
991 if (nr_stream_fds != nr_streams)
992 return NULL;
993
b2c5f61a
MD
994 if (blocking_timeout < -1) {
995 return NULL;
996 }
997 /* usec to msec */
998 if (blocking_timeout == -1) {
999 blocking_timeout_ms = -1;
1000 } else {
1001 blocking_timeout_ms = blocking_timeout / 1000;
1002 if (blocking_timeout_ms != (int32_t) blocking_timeout_ms) {
1003 return NULL;
1004 }
1005 }
1006
852c2936
MD
1007 if (lib_ring_buffer_check_config(config, switch_timer_interval,
1008 read_timer_interval))
1009 return NULL;
1010
97572c04 1011 handle = zmalloc_populate(sizeof(struct lttng_ust_shm_handle), populate);
431d5cf0
MD
1012 if (!handle)
1013 return NULL;
1014
1d498196 1015 /* Allocate table for channel + per-cpu buffers */
97572c04 1016 handle->table = shm_object_table_create(1 + get_possible_cpus_array_len(), populate);
1d498196
MD
1017 if (!handle->table)
1018 goto error_table_alloc;
852c2936 1019
1d498196 1020 /* Calculate the shm allocation layout */
b5457df5
MD
1021 shmsize = sizeof(struct lttng_ust_ring_buffer_channel);
1022 shmsize += lttng_ust_offset_align(shmsize, __alignof__(struct lttng_ust_ring_buffer_shmp));
1023 shmsize += sizeof(struct lttng_ust_ring_buffer_shmp) * nr_streams;
a3f61e7f 1024 chansize = shmsize;
74d81a6c 1025 if (priv_data_align)
b72687b8 1026 shmsize += lttng_ust_offset_align(shmsize, priv_data_align);
a3f61e7f 1027 shmsize += priv_data_size;
a6352fd4 1028
74d81a6c 1029 /* Allocate normal memory for channel (not shared) */
a9ff648c 1030 shmobj = shm_object_table_alloc(handle->table, shmsize, SHM_OBJECT_MEM,
97572c04 1031 -1, -1, populate);
b5a14697
MD
1032 if (!shmobj)
1033 goto error_append;
b5457df5 1034 /* struct lttng_ust_ring_buffer_channel is at object 0, offset 0 (hardcoded) */
a3f61e7f 1035 set_shmp(handle->chan, zalloc_shm(shmobj, chansize));
57773204
MD
1036 assert(handle->chan._ref.index == 0);
1037 assert(handle->chan._ref.offset == 0);
1d498196 1038 chan = shmp(handle, handle->chan);
a6352fd4 1039 if (!chan)
1d498196 1040 goto error_append;
74d81a6c 1041 chan->nr_streams = nr_streams;
a6352fd4 1042
a3f61e7f
MD
1043 /* space for private data */
1044 if (priv_data_size) {
f0fde1c3
MD
1045 void *priv_config;
1046
a3f61e7f
MD
1047 DECLARE_SHMP(void, priv_data_alloc);
1048
1049 align_shm(shmobj, priv_data_align);
1050 chan->priv_data_offset = shmobj->allocated_len;
1051 set_shmp(priv_data_alloc, zalloc_shm(shmobj, priv_data_size));
1052 if (!shmp(handle, priv_data_alloc))
1053 goto error_append;
f0fde1c3
MD
1054 priv_config = channel_get_private_config(chan);
1055 memcpy(priv_config, priv_data_init, priv_data_size);
a3f61e7f
MD
1056 } else {
1057 chan->priv_data_offset = -1;
a3f61e7f
MD
1058 }
1059
b2c5f61a
MD
1060 chan->u.s.blocking_timeout_ms = (int32_t) blocking_timeout_ms;
1061
f0fde1c3
MD
1062 channel_set_private(chan, priv);
1063
a3f61e7f 1064 ret = channel_backend_init(&chan->backend, name, config,
a9ff648c 1065 subbuf_size, num_subbuf, handle,
5ea386c3 1066 stream_fds);
852c2936 1067 if (ret)
1d498196 1068 goto error_backend_init;
852c2936 1069
03d2d293 1070 chan->handle = handle;
852c2936 1071 chan->commit_count_mask = (~0UL >> chan->backend.num_subbuf_order);
852c2936 1072
34a91bdb
MD
1073 chan->switch_timer_interval = switch_timer_interval;
1074 chan->read_timer_interval = read_timer_interval;
03d2d293 1075 lib_ring_buffer_channel_switch_timer_start(chan);
34a91bdb 1076 lib_ring_buffer_channel_read_timer_start(chan);
852c2936 1077
431d5cf0 1078 return handle;
852c2936 1079
1d498196
MD
1080error_backend_init:
1081error_append:
6548fca4 1082 shm_object_table_destroy(handle->table, 1);
1d498196 1083error_table_alloc:
431d5cf0 1084 free(handle);
852c2936
MD
1085 return NULL;
1086}
852c2936 1087
74d81a6c 1088struct lttng_ust_shm_handle *channel_handle_create(void *data,
ff0f5728
MD
1089 uint64_t memory_map_size,
1090 int wakeup_fd)
193183fb 1091{
38fae1d3 1092 struct lttng_ust_shm_handle *handle;
193183fb 1093 struct shm_object *object;
97572c04 1094 bool populate = lttng_ust_map_populate_is_enabled();
193183fb 1095
97572c04 1096 handle = zmalloc_populate(sizeof(struct lttng_ust_shm_handle), populate);
193183fb
MD
1097 if (!handle)
1098 return NULL;
1099
1100 /* Allocate table for channel + per-cpu buffers */
97572c04 1101 handle->table = shm_object_table_create(1 + get_possible_cpus_array_len(), populate);
193183fb
MD
1102 if (!handle->table)
1103 goto error_table_alloc;
1104 /* Add channel object */
74d81a6c 1105 object = shm_object_table_append_mem(handle->table, data,
ff0f5728 1106 memory_map_size, wakeup_fd);
193183fb
MD
1107 if (!object)
1108 goto error_table_object;
b5457df5 1109 /* struct lttng_ust_ring_buffer_channel is at object 0, offset 0 (hardcoded) */
57773204
MD
1110 handle->chan._ref.index = 0;
1111 handle->chan._ref.offset = 0;
193183fb
MD
1112 return handle;
1113
1114error_table_object:
6548fca4 1115 shm_object_table_destroy(handle->table, 0);
193183fb
MD
1116error_table_alloc:
1117 free(handle);
1118 return NULL;
1119}
1120
38fae1d3 1121int channel_handle_add_stream(struct lttng_ust_shm_handle *handle,
74d81a6c
MD
1122 int shm_fd, int wakeup_fd, uint32_t stream_nr,
1123 uint64_t memory_map_size)
193183fb
MD
1124{
1125 struct shm_object *object;
1126
1127 /* Add stream object */
74d81a6c
MD
1128 object = shm_object_table_append_shm(handle->table,
1129 shm_fd, wakeup_fd, stream_nr,
97572c04 1130 memory_map_size, lttng_ust_map_populate_cpu_is_enabled(stream_nr));
193183fb 1131 if (!object)
74d81a6c 1132 return -EINVAL;
193183fb
MD
1133 return 0;
1134}
1135
74d81a6c
MD
1136unsigned int channel_handle_get_nr_streams(struct lttng_ust_shm_handle *handle)
1137{
1138 assert(handle->table);
1139 return handle->table->allocated_len - 1;
1140}
1141
852c2936 1142static
b5457df5 1143void channel_release(struct lttng_ust_ring_buffer_channel *chan, struct lttng_ust_shm_handle *handle,
6548fca4 1144 int consumer)
852c2936 1145{
6548fca4 1146 channel_free(chan, handle, consumer);
852c2936
MD
1147}
1148
1149/**
1150 * channel_destroy - Finalize, wait for q.s. and destroy channel.
1151 * @chan: channel to destroy
1152 *
1153 * Holds cpu hotplug.
431d5cf0
MD
1154 * Call "destroy" callback, finalize channels, decrement the channel
1155 * reference count. Note that when readers have completed data
1156 * consumption of finalized channels, get_subbuf() will return -ENODATA.
a60af3a5 1157 * They should release their handle at that point.
852c2936 1158 */
b5457df5 1159void channel_destroy(struct lttng_ust_ring_buffer_channel *chan, struct lttng_ust_shm_handle *handle,
74d81a6c 1160 int consumer)
852c2936 1161{
74d81a6c
MD
1162 if (consumer) {
1163 /*
1164 * Note: the consumer takes care of finalizing and
1165 * switching the buffers.
1166 */
1167 channel_unregister_notifiers(chan, handle);
3d0ef9f6
MD
1168 /*
1169 * The consumer prints errors.
1170 */
1171 channel_print_errors(chan, handle);
824f40b8
MD
1172 }
1173
431d5cf0
MD
1174 /*
1175 * sessiond/consumer are keeping a reference on the shm file
1176 * descriptor directly. No need to refcount.
1177 */
6548fca4 1178 channel_release(chan, handle, consumer);
a3f61e7f 1179 return;
852c2936 1180}
852c2936 1181
b5457df5
MD
1182struct lttng_ust_ring_buffer *channel_get_ring_buffer(
1183 const struct lttng_ust_ring_buffer_config *config,
1184 struct lttng_ust_ring_buffer_channel *chan, int cpu,
38fae1d3 1185 struct lttng_ust_shm_handle *handle,
74d81a6c
MD
1186 int *shm_fd, int *wait_fd,
1187 int *wakeup_fd,
63b3205f
MD
1188 uint64_t *memory_map_size,
1189 void **memory_map_addr)
852c2936 1190{
381c0f1e
MD
1191 struct shm_ref *ref;
1192
1193 if (config->alloc == RING_BUFFER_ALLOC_GLOBAL) {
74d81a6c 1194 cpu = 0;
381c0f1e 1195 } else {
a616fb4e 1196 if (cpu >= get_possible_cpus_array_len())
e095d803 1197 return NULL;
381c0f1e 1198 }
74d81a6c
MD
1199 ref = &chan->backend.buf[cpu].shmp._ref;
1200 *shm_fd = shm_get_shm_fd(handle, ref);
1201 *wait_fd = shm_get_wait_fd(handle, ref);
1202 *wakeup_fd = shm_get_wakeup_fd(handle, ref);
1203 if (shm_get_shm_size(handle, ref, memory_map_size))
1204 return NULL;
63b3205f 1205 *memory_map_addr = handle->table->objects[ref->index].memory_map;
74d81a6c 1206 return shmp(handle, chan->backend.buf[cpu].shmp);
852c2936 1207}
852c2936 1208
2208d8b5 1209int ring_buffer_channel_close_wait_fd(
b5457df5
MD
1210 const struct lttng_ust_ring_buffer_config *config __attribute__((unused)),
1211 struct lttng_ust_ring_buffer_channel *chan __attribute__((unused)),
2208d8b5 1212 struct lttng_ust_shm_handle *handle)
ff0f5728
MD
1213{
1214 struct shm_ref *ref;
1215
1216 ref = &handle->chan._ref;
1217 return shm_close_wait_fd(handle, ref);
1218}
1219
2208d8b5 1220int ring_buffer_channel_close_wakeup_fd(
b5457df5
MD
1221 const struct lttng_ust_ring_buffer_config *config __attribute__((unused)),
1222 struct lttng_ust_ring_buffer_channel *chan __attribute__((unused)),
2208d8b5 1223 struct lttng_ust_shm_handle *handle)
ff0f5728
MD
1224{
1225 struct shm_ref *ref;
1226
1227 ref = &handle->chan._ref;
1228 return shm_close_wakeup_fd(handle, ref);
1229}
1230
b5457df5
MD
1231int ring_buffer_stream_close_wait_fd(const struct lttng_ust_ring_buffer_config *config,
1232 struct lttng_ust_ring_buffer_channel *chan,
74d81a6c
MD
1233 struct lttng_ust_shm_handle *handle,
1234 int cpu)
852c2936 1235{
74d81a6c
MD
1236 struct shm_ref *ref;
1237
1238 if (config->alloc == RING_BUFFER_ALLOC_GLOBAL) {
1239 cpu = 0;
1240 } else {
a616fb4e 1241 if (cpu >= get_possible_cpus_array_len())
74d81a6c 1242 return -EINVAL;
824f40b8 1243 }
74d81a6c
MD
1244 ref = &chan->backend.buf[cpu].shmp._ref;
1245 return shm_close_wait_fd(handle, ref);
1246}
1247
b5457df5
MD
1248int ring_buffer_stream_close_wakeup_fd(const struct lttng_ust_ring_buffer_config *config,
1249 struct lttng_ust_ring_buffer_channel *chan,
74d81a6c
MD
1250 struct lttng_ust_shm_handle *handle,
1251 int cpu)
1252{
1253 struct shm_ref *ref;
cb7378b3 1254 int ret;
74d81a6c
MD
1255
1256 if (config->alloc == RING_BUFFER_ALLOC_GLOBAL) {
1257 cpu = 0;
1258 } else {
a616fb4e 1259 if (cpu >= get_possible_cpus_array_len())
74d81a6c
MD
1260 return -EINVAL;
1261 }
1262 ref = &chan->backend.buf[cpu].shmp._ref;
cb7378b3
MD
1263 pthread_mutex_lock(&wakeup_fd_mutex);
1264 ret = shm_close_wakeup_fd(handle, ref);
1265 pthread_mutex_unlock(&wakeup_fd_mutex);
1266 return ret;
74d81a6c
MD
1267}
1268
b5457df5 1269int lib_ring_buffer_open_read(struct lttng_ust_ring_buffer *buf,
2208d8b5 1270 struct lttng_ust_shm_handle *handle __attribute__((unused)))
74d81a6c 1271{
a6352fd4 1272 if (uatomic_cmpxchg(&buf->active_readers, 0, 1) != 0)
852c2936 1273 return -EBUSY;
a6352fd4 1274 cmm_smp_mb();
852c2936
MD
1275 return 0;
1276}
852c2936 1277
b5457df5 1278void lib_ring_buffer_release_read(struct lttng_ust_ring_buffer *buf,
74d81a6c 1279 struct lttng_ust_shm_handle *handle)
852c2936 1280{
b5457df5 1281 struct lttng_ust_ring_buffer_channel *chan = shmp(handle, buf->backend.chan);
852c2936 1282
15500a1b
MD
1283 if (!chan)
1284 return;
a6352fd4
MD
1285 CHAN_WARN_ON(chan, uatomic_read(&buf->active_readers) != 1);
1286 cmm_smp_mb();
1287 uatomic_dec(&buf->active_readers);
852c2936
MD
1288}
1289
1290/**
1291 * lib_ring_buffer_snapshot - save subbuffer position snapshot (for read)
1292 * @buf: ring buffer
1293 * @consumed: consumed count indicating the position where to read
1294 * @produced: produced count, indicates position when to stop reading
1295 *
1296 * Returns -ENODATA if buffer is finalized, -EAGAIN if there is currently no
1297 * data to read at consumed position, or 0 if the get operation succeeds.
852c2936
MD
1298 */
1299
b5457df5 1300int lib_ring_buffer_snapshot(struct lttng_ust_ring_buffer *buf,
1d498196 1301 unsigned long *consumed, unsigned long *produced,
38fae1d3 1302 struct lttng_ust_shm_handle *handle)
852c2936 1303{
b5457df5
MD
1304 struct lttng_ust_ring_buffer_channel *chan;
1305 const struct lttng_ust_ring_buffer_config *config;
852c2936
MD
1306 unsigned long consumed_cur, write_offset;
1307 int finalized;
1308
15500a1b
MD
1309 chan = shmp(handle, buf->backend.chan);
1310 if (!chan)
1311 return -EPERM;
1312 config = &chan->backend.config;
14641deb 1313 finalized = CMM_ACCESS_ONCE(buf->finalized);
852c2936
MD
1314 /*
1315 * Read finalized before counters.
1316 */
a6352fd4
MD
1317 cmm_smp_rmb();
1318 consumed_cur = uatomic_read(&buf->consumed);
852c2936
MD
1319 /*
1320 * No need to issue a memory barrier between consumed count read and
1321 * write offset read, because consumed count can only change
1322 * concurrently in overwrite mode, and we keep a sequence counter
1323 * identifier derived from the write offset to check we are getting
1324 * the same sub-buffer we are expecting (the sub-buffers are atomically
1325 * "tagged" upon writes, tags are checked upon read).
1326 */
1327 write_offset = v_read(config, &buf->offset);
1328
1329 /*
1330 * Check that we are not about to read the same subbuffer in
1331 * which the writer head is.
1332 */
1333 if (subbuf_trunc(write_offset, chan) - subbuf_trunc(consumed_cur, chan)
1334 == 0)
1335 goto nodata;
1336
1337 *consumed = consumed_cur;
1338 *produced = subbuf_trunc(write_offset, chan);
1339
1340 return 0;
1341
1342nodata:
1343 /*
1344 * The memory barriers __wait_event()/wake_up_interruptible() take care
1345 * of "raw_spin_is_locked" memory ordering.
1346 */
1347 if (finalized)
1348 return -ENODATA;
852c2936
MD
1349 else
1350 return -EAGAIN;
1351}
852c2936 1352
f45930b7
JG
1353/**
1354 * Performs the same function as lib_ring_buffer_snapshot(), but the positions
1355 * are saved regardless of whether the consumed and produced positions are
1356 * in the same subbuffer.
1357 * @buf: ring buffer
1358 * @consumed: consumed byte count indicating the last position read
1359 * @produced: produced byte count indicating the last position written
1360 *
1361 * This function is meant to provide information on the exact producer and
1362 * consumer positions without regard for the "snapshot" feature.
1363 */
1364int lib_ring_buffer_snapshot_sample_positions(
b5457df5 1365 struct lttng_ust_ring_buffer *buf,
f45930b7
JG
1366 unsigned long *consumed, unsigned long *produced,
1367 struct lttng_ust_shm_handle *handle)
1368{
b5457df5
MD
1369 struct lttng_ust_ring_buffer_channel *chan;
1370 const struct lttng_ust_ring_buffer_config *config;
f45930b7
JG
1371
1372 chan = shmp(handle, buf->backend.chan);
1373 if (!chan)
1374 return -EPERM;
1375 config = &chan->backend.config;
1376 cmm_smp_rmb();
1377 *consumed = uatomic_read(&buf->consumed);
1378 /*
1379 * No need to issue a memory barrier between consumed count read and
1380 * write offset read, because consumed count can only change
1381 * concurrently in overwrite mode, and we keep a sequence counter
1382 * identifier derived from the write offset to check we are getting
1383 * the same sub-buffer we are expecting (the sub-buffers are atomically
1384 * "tagged" upon writes, tags are checked upon read).
1385 */
1386 *produced = v_read(config, &buf->offset);
1387 return 0;
1388}
1389
852c2936 1390/**
d1a996f5 1391 * lib_ring_buffer_move_consumer - move consumed counter forward
852c2936
MD
1392 * @buf: ring buffer
1393 * @consumed_new: new consumed count value
1394 */
b5457df5 1395void lib_ring_buffer_move_consumer(struct lttng_ust_ring_buffer *buf,
1d498196 1396 unsigned long consumed_new,
38fae1d3 1397 struct lttng_ust_shm_handle *handle)
852c2936 1398{
b5457df5
MD
1399 struct lttng_ust_ring_buffer_backend *bufb = &buf->backend;
1400 struct lttng_ust_ring_buffer_channel *chan;
852c2936
MD
1401 unsigned long consumed;
1402
15500a1b
MD
1403 chan = shmp(handle, bufb->chan);
1404 if (!chan)
1405 return;
74d81a6c 1406 CHAN_WARN_ON(chan, uatomic_read(&buf->active_readers) != 1);
852c2936
MD
1407
1408 /*
1409 * Only push the consumed value forward.
1410 * If the consumed cmpxchg fails, this is because we have been pushed by
1411 * the writer in flight recorder mode.
1412 */
a6352fd4 1413 consumed = uatomic_read(&buf->consumed);
852c2936 1414 while ((long) consumed - (long) consumed_new < 0)
a6352fd4
MD
1415 consumed = uatomic_cmpxchg(&buf->consumed, consumed,
1416 consumed_new);
852c2936 1417}
852c2936
MD
1418
1419/**
1420 * lib_ring_buffer_get_subbuf - get exclusive access to subbuffer for reading
1421 * @buf: ring buffer
1422 * @consumed: consumed count indicating the position where to read
1423 *
1424 * Returns -ENODATA if buffer is finalized, -EAGAIN if there is currently no
1425 * data to read at consumed position, or 0 if the get operation succeeds.
852c2936 1426 */
b5457df5 1427int lib_ring_buffer_get_subbuf(struct lttng_ust_ring_buffer *buf,
1d498196 1428 unsigned long consumed,
38fae1d3 1429 struct lttng_ust_shm_handle *handle)
852c2936 1430{
b5457df5
MD
1431 struct lttng_ust_ring_buffer_channel *chan;
1432 const struct lttng_ust_ring_buffer_config *config;
852c2936 1433 unsigned long consumed_cur, consumed_idx, commit_count, write_offset;
dddba398 1434 int ret, finalized, nr_retry = LTTNG_UST_RING_BUFFER_GET_RETRY;
15500a1b 1435 struct commit_counters_cold *cc_cold;
852c2936 1436
15500a1b
MD
1437 chan = shmp(handle, buf->backend.chan);
1438 if (!chan)
1439 return -EPERM;
1440 config = &chan->backend.config;
852c2936 1441retry:
14641deb 1442 finalized = CMM_ACCESS_ONCE(buf->finalized);
852c2936
MD
1443 /*
1444 * Read finalized before counters.
1445 */
a6352fd4
MD
1446 cmm_smp_rmb();
1447 consumed_cur = uatomic_read(&buf->consumed);
852c2936 1448 consumed_idx = subbuf_index(consumed, chan);
15500a1b
MD
1449 cc_cold = shmp_index(handle, buf->commit_cold, consumed_idx);
1450 if (!cc_cold)
1451 return -EPERM;
1452 commit_count = v_read(config, &cc_cold->cc_sb);
852c2936
MD
1453 /*
1454 * Make sure we read the commit count before reading the buffer
1455 * data and the write offset. Correct consumed offset ordering
1456 * wrt commit count is insured by the use of cmpxchg to update
1457 * the consumed offset.
852c2936 1458 */
a6352fd4
MD
1459 /*
1460 * Local rmb to match the remote wmb to read the commit count
1461 * before the buffer data and the write offset.
1462 */
1463 cmm_smp_rmb();
852c2936
MD
1464
1465 write_offset = v_read(config, &buf->offset);
1466
1467 /*
1468 * Check that the buffer we are getting is after or at consumed_cur
1469 * position.
1470 */
1471 if ((long) subbuf_trunc(consumed, chan)
1472 - (long) subbuf_trunc(consumed_cur, chan) < 0)
1473 goto nodata;
1474
1475 /*
1476 * Check that the subbuffer we are trying to consume has been
dddba398
MD
1477 * already fully committed. There are a few causes that can make
1478 * this unavailability situation occur:
1479 *
1480 * Temporary (short-term) situation:
1481 * - Application is running on a different CPU, between reserve
1482 * and commit ring buffer operations,
1483 * - Application is preempted between reserve and commit ring
1484 * buffer operations,
1485 *
1486 * Long-term situation:
1487 * - Application is stopped (SIGSTOP) between reserve and commit
1488 * ring buffer operations. Could eventually be resumed by
1489 * SIGCONT.
1490 * - Application is killed (SIGTERM, SIGINT, SIGKILL) between
1491 * reserve and commit ring buffer operation.
1492 *
1493 * From a consumer perspective, handling short-term
1494 * unavailability situations is performed by retrying a few
1495 * times after a delay. Handling long-term unavailability
1496 * situations is handled by failing to get the sub-buffer.
1497 *
1498 * In all of those situations, if the application is taking a
1499 * long time to perform its commit after ring buffer space
1500 * reservation, we can end up in a situation where the producer
1501 * will fill the ring buffer and try to write into the same
1502 * sub-buffer again (which has a missing commit). This is
1503 * handled by the producer in the sub-buffer switch handling
1504 * code of the reserve routine by detecting unbalanced
1505 * reserve/commit counters and discarding all further events
1506 * until the situation is resolved in those situations. Two
1507 * scenarios can occur:
1508 *
1509 * 1) The application causing the reserve/commit counters to be
1510 * unbalanced has been terminated. In this situation, all
1511 * further events will be discarded in the buffers, and no
1512 * further buffer data will be readable by the consumer
1513 * daemon. Tearing down the UST tracing session and starting
1514 * anew is a work-around for those situations. Note that this
1515 * only affects per-UID tracing. In per-PID tracing, the
1516 * application vanishes with the termination, and therefore
1517 * no more data needs to be written to the buffers.
1518 * 2) The application causing the unbalance has been delayed for
1519 * a long time, but will eventually try to increment the
1520 * commit counter after eventually writing to the sub-buffer.
1521 * This situation can cause events to be discarded until the
1522 * application resumes its operations.
852c2936
MD
1523 */
1524 if (((commit_count - chan->backend.subbuf_size)
1525 & chan->commit_count_mask)
0bade047 1526 - (buf_trunc(consumed, chan)
852c2936 1527 >> chan->backend.num_subbuf_order)
dddba398
MD
1528 != 0) {
1529 if (nr_retry-- > 0) {
1530 if (nr_retry <= (LTTNG_UST_RING_BUFFER_GET_RETRY >> 1))
1531 (void) poll(NULL, 0, LTTNG_UST_RING_BUFFER_RETRY_DELAY_MS);
1532 goto retry;
1533 } else {
1534 goto nodata;
1535 }
1536 }
852c2936
MD
1537
1538 /*
1539 * Check that we are not about to read the same subbuffer in
1540 * which the writer head is.
1541 */
0bade047 1542 if (subbuf_trunc(write_offset, chan) - subbuf_trunc(consumed, chan)
852c2936
MD
1543 == 0)
1544 goto nodata;
1545
1546 /*
1547 * Failure to get the subbuffer causes a busy-loop retry without going
1548 * to a wait queue. These are caused by short-lived race windows where
1549 * the writer is getting access to a subbuffer we were trying to get
1550 * access to. Also checks that the "consumed" buffer count we are
1551 * looking for matches the one contained in the subbuffer id.
dddba398
MD
1552 *
1553 * The short-lived race window described here can be affected by
1554 * application signals and preemption, thus requiring to bound
1555 * the loop to a maximum number of retry.
852c2936
MD
1556 */
1557 ret = update_read_sb_index(config, &buf->backend, &chan->backend,
1d498196
MD
1558 consumed_idx, buf_trunc_val(consumed, chan),
1559 handle);
dddba398
MD
1560 if (ret) {
1561 if (nr_retry-- > 0) {
1562 if (nr_retry <= (LTTNG_UST_RING_BUFFER_GET_RETRY >> 1))
1563 (void) poll(NULL, 0, LTTNG_UST_RING_BUFFER_RETRY_DELAY_MS);
1564 goto retry;
1565 } else {
1566 goto nodata;
1567 }
1568 }
852c2936
MD
1569 subbuffer_id_clear_noref(config, &buf->backend.buf_rsb.id);
1570
1571 buf->get_subbuf_consumed = consumed;
1572 buf->get_subbuf = 1;
1573
1574 return 0;
1575
1576nodata:
1577 /*
1578 * The memory barriers __wait_event()/wake_up_interruptible() take care
1579 * of "raw_spin_is_locked" memory ordering.
1580 */
1581 if (finalized)
1582 return -ENODATA;
852c2936
MD
1583 else
1584 return -EAGAIN;
1585}
852c2936
MD
1586
1587/**
1588 * lib_ring_buffer_put_subbuf - release exclusive subbuffer access
1589 * @buf: ring buffer
1590 */
b5457df5 1591void lib_ring_buffer_put_subbuf(struct lttng_ust_ring_buffer *buf,
38fae1d3 1592 struct lttng_ust_shm_handle *handle)
852c2936 1593{
b5457df5
MD
1594 struct lttng_ust_ring_buffer_backend *bufb = &buf->backend;
1595 struct lttng_ust_ring_buffer_channel *chan;
1596 const struct lttng_ust_ring_buffer_config *config;
15500a1b 1597 unsigned long sb_bindex, consumed_idx, consumed;
b5457df5
MD
1598 struct lttng_ust_ring_buffer_backend_pages_shmp *rpages;
1599 struct lttng_ust_ring_buffer_backend_pages *backend_pages;
852c2936 1600
15500a1b
MD
1601 chan = shmp(handle, bufb->chan);
1602 if (!chan)
1603 return;
1604 config = &chan->backend.config;
74d81a6c 1605 CHAN_WARN_ON(chan, uatomic_read(&buf->active_readers) != 1);
852c2936
MD
1606
1607 if (!buf->get_subbuf) {
1608 /*
1609 * Reader puts a subbuffer it did not get.
1610 */
1611 CHAN_WARN_ON(chan, 1);
1612 return;
1613 }
1614 consumed = buf->get_subbuf_consumed;
1615 buf->get_subbuf = 0;
1616
1617 /*
1618 * Clear the records_unread counter. (overruns counter)
1619 * Can still be non-zero if a file reader simply grabbed the data
1620 * without using iterators.
1621 * Can be below zero if an iterator is used on a snapshot more than
1622 * once.
1623 */
15500a1b
MD
1624 sb_bindex = subbuffer_id_get_index(config, bufb->buf_rsb.id);
1625 rpages = shmp_index(handle, bufb->array, sb_bindex);
1626 if (!rpages)
1627 return;
1628 backend_pages = shmp(handle, rpages->shmp);
1629 if (!backend_pages)
1630 return;
1631 v_add(config, v_read(config, &backend_pages->records_unread),
1632 &bufb->records_read);
1633 v_set(config, &backend_pages->records_unread, 0);
852c2936
MD
1634 CHAN_WARN_ON(chan, config->mode == RING_BUFFER_OVERWRITE
1635 && subbuffer_id_is_noref(config, bufb->buf_rsb.id));
1636 subbuffer_id_set_noref(config, &bufb->buf_rsb.id);
1637
1638 /*
1639 * Exchange the reader subbuffer with the one we put in its place in the
1640 * writer subbuffer table. Expect the original consumed count. If
1641 * update_read_sb_index fails, this is because the writer updated the
1642 * subbuffer concurrently. We should therefore keep the subbuffer we
1643 * currently have: it has become invalid to try reading this sub-buffer
1644 * consumed count value anyway.
1645 */
1646 consumed_idx = subbuf_index(consumed, chan);
1647 update_read_sb_index(config, &buf->backend, &chan->backend,
1d498196
MD
1648 consumed_idx, buf_trunc_val(consumed, chan),
1649 handle);
852c2936
MD
1650 /*
1651 * update_read_sb_index return value ignored. Don't exchange sub-buffer
1652 * if the writer concurrently updated it.
1653 */
1654}
852c2936
MD
1655
1656/*
1657 * cons_offset is an iterator on all subbuffer offsets between the reader
1658 * position and the writer position. (inclusive)
1659 */
1660static
b5457df5
MD
1661void lib_ring_buffer_print_subbuffer_errors(struct lttng_ust_ring_buffer *buf,
1662 struct lttng_ust_ring_buffer_channel *chan,
852c2936 1663 unsigned long cons_offset,
1d498196 1664 int cpu,
38fae1d3 1665 struct lttng_ust_shm_handle *handle)
852c2936 1666{
b5457df5 1667 const struct lttng_ust_ring_buffer_config *config = &chan->backend.config;
852c2936 1668 unsigned long cons_idx, commit_count, commit_count_sb;
15500a1b
MD
1669 struct commit_counters_hot *cc_hot;
1670 struct commit_counters_cold *cc_cold;
852c2936
MD
1671
1672 cons_idx = subbuf_index(cons_offset, chan);
15500a1b
MD
1673 cc_hot = shmp_index(handle, buf->commit_hot, cons_idx);
1674 if (!cc_hot)
1675 return;
1676 cc_cold = shmp_index(handle, buf->commit_cold, cons_idx);
1677 if (!cc_cold)
1678 return;
1679 commit_count = v_read(config, &cc_hot->cc);
1680 commit_count_sb = v_read(config, &cc_cold->cc_sb);
852c2936
MD
1681
1682 if (subbuf_offset(commit_count, chan) != 0)
4d3c9523 1683 DBG("ring buffer %s, cpu %d: "
852c2936
MD
1684 "commit count in subbuffer %lu,\n"
1685 "expecting multiples of %lu bytes\n"
1686 " [ %lu bytes committed, %lu bytes reader-visible ]\n",
1687 chan->backend.name, cpu, cons_idx,
1688 chan->backend.subbuf_size,
1689 commit_count, commit_count_sb);
1690
4d3c9523 1691 DBG("ring buffer: %s, cpu %d: %lu bytes committed\n",
852c2936
MD
1692 chan->backend.name, cpu, commit_count);
1693}
1694
1695static
b5457df5
MD
1696void lib_ring_buffer_print_buffer_errors(struct lttng_ust_ring_buffer *buf,
1697 struct lttng_ust_ring_buffer_channel *chan,
f0fde1c3 1698 int cpu, struct lttng_ust_shm_handle *handle)
852c2936 1699{
b5457df5 1700 const struct lttng_ust_ring_buffer_config *config = &chan->backend.config;
852c2936
MD
1701 unsigned long write_offset, cons_offset;
1702
852c2936
MD
1703 /*
1704 * No need to order commit_count, write_offset and cons_offset reads
1705 * because we execute at teardown when no more writer nor reader
1706 * references are left.
1707 */
1708 write_offset = v_read(config, &buf->offset);
a6352fd4 1709 cons_offset = uatomic_read(&buf->consumed);
852c2936 1710 if (write_offset != cons_offset)
4d3c9523 1711 DBG("ring buffer %s, cpu %d: "
852c2936
MD
1712 "non-consumed data\n"
1713 " [ %lu bytes written, %lu bytes read ]\n",
1714 chan->backend.name, cpu, write_offset, cons_offset);
1715
a6352fd4 1716 for (cons_offset = uatomic_read(&buf->consumed);
852c2936
MD
1717 (long) (subbuf_trunc((unsigned long) v_read(config, &buf->offset),
1718 chan)
1719 - cons_offset) > 0;
1720 cons_offset = subbuf_align(cons_offset, chan))
1721 lib_ring_buffer_print_subbuffer_errors(buf, chan, cons_offset,
1d498196 1722 cpu, handle);
852c2936
MD
1723}
1724
1725static
b5457df5
MD
1726void lib_ring_buffer_print_errors(struct lttng_ust_ring_buffer_channel *chan,
1727 struct lttng_ust_ring_buffer *buf, int cpu,
009769ca 1728 struct lttng_ust_shm_handle *handle)
852c2936 1729{
b5457df5 1730 const struct lttng_ust_ring_buffer_config *config = &chan->backend.config;
852c2936 1731
a1360615
MD
1732 if (!strcmp(chan->backend.name, "relay-metadata-mmap")) {
1733 DBG("ring buffer %s: %lu records written, "
1734 "%lu records overrun\n",
1735 chan->backend.name,
1736 v_read(config, &buf->records_count),
1737 v_read(config, &buf->records_overrun));
1738 } else {
1739 DBG("ring buffer %s, cpu %d: %lu records written, "
1740 "%lu records overrun\n",
1741 chan->backend.name, cpu,
1742 v_read(config, &buf->records_count),
1743 v_read(config, &buf->records_overrun));
1744
1745 if (v_read(config, &buf->records_lost_full)
1746 || v_read(config, &buf->records_lost_wrap)
1747 || v_read(config, &buf->records_lost_big))
1748 DBG("ring buffer %s, cpu %d: records were lost. Caused by:\n"
1749 " [ %lu buffer full, %lu nest buffer wrap-around, "
1750 "%lu event too big ]\n",
1751 chan->backend.name, cpu,
1752 v_read(config, &buf->records_lost_full),
1753 v_read(config, &buf->records_lost_wrap),
1754 v_read(config, &buf->records_lost_big));
1755 }
f0fde1c3 1756 lib_ring_buffer_print_buffer_errors(buf, chan, cpu, handle);
852c2936
MD
1757}
1758
1759/*
1760 * lib_ring_buffer_switch_old_start: Populate old subbuffer header.
1761 *
48f22436
MD
1762 * Only executed by SWITCH_FLUSH, which can be issued while tracing is
1763 * active or at buffer finalization (destroy).
852c2936
MD
1764 */
1765static
b5457df5
MD
1766void lib_ring_buffer_switch_old_start(struct lttng_ust_ring_buffer *buf,
1767 struct lttng_ust_ring_buffer_channel *chan,
852c2936 1768 struct switch_offsets *offsets,
f27b0770 1769 const struct lttng_ust_ring_buffer_ctx *ctx,
38fae1d3 1770 struct lttng_ust_shm_handle *handle)
852c2936 1771{
b5457df5 1772 const struct lttng_ust_ring_buffer_config *config = &chan->backend.config;
852c2936
MD
1773 unsigned long oldidx = subbuf_index(offsets->old, chan);
1774 unsigned long commit_count;
3d3c3833 1775 struct commit_counters_hot *cc_hot;
852c2936 1776
373ea80a 1777 config->cb.buffer_begin(buf, ctx->priv->timestamp, oldidx, handle);
852c2936
MD
1778
1779 /*
1780 * Order all writes to buffer before the commit count update that will
1781 * determine that the subbuffer is full.
1782 */
a6352fd4 1783 cmm_smp_wmb();
3d3c3833 1784 cc_hot = shmp_index(handle, buf->commit_hot, oldidx);
15500a1b
MD
1785 if (!cc_hot)
1786 return;
852c2936 1787 v_add(config, config->cb.subbuffer_header_size(),
3d3c3833
MD
1788 &cc_hot->cc);
1789 commit_count = v_read(config, &cc_hot->cc);
852c2936
MD
1790 /* Check if the written buffer has to be delivered */
1791 lib_ring_buffer_check_deliver(config, buf, chan, offsets->old,
f27b0770 1792 commit_count, oldidx, handle, ctx);
d2fe4771 1793 lib_ring_buffer_write_commit_counter(config, buf, chan,
80249235 1794 offsets->old + config->cb.subbuffer_header_size(),
3d3c3833 1795 commit_count, handle, cc_hot);
852c2936
MD
1796}
1797
1798/*
1799 * lib_ring_buffer_switch_old_end: switch old subbuffer
1800 *
1801 * Note : offset_old should never be 0 here. It is ok, because we never perform
1802 * buffer switch on an empty subbuffer in SWITCH_ACTIVE mode. The caller
1803 * increments the offset_old value when doing a SWITCH_FLUSH on an empty
1804 * subbuffer.
1805 */
1806static
b5457df5
MD
1807void lib_ring_buffer_switch_old_end(struct lttng_ust_ring_buffer *buf,
1808 struct lttng_ust_ring_buffer_channel *chan,
852c2936 1809 struct switch_offsets *offsets,
f27b0770 1810 const struct lttng_ust_ring_buffer_ctx *ctx,
38fae1d3 1811 struct lttng_ust_shm_handle *handle)
852c2936 1812{
b5457df5 1813 const struct lttng_ust_ring_buffer_config *config = &chan->backend.config;
852c2936
MD
1814 unsigned long oldidx = subbuf_index(offsets->old - 1, chan);
1815 unsigned long commit_count, padding_size, data_size;
3d3c3833 1816 struct commit_counters_hot *cc_hot;
6c737d05 1817 uint64_t *ts_end;
852c2936
MD
1818
1819 data_size = subbuf_offset(offsets->old - 1, chan) + 1;
1820 padding_size = chan->backend.subbuf_size - data_size;
1d498196
MD
1821 subbuffer_set_data_size(config, &buf->backend, oldidx, data_size,
1822 handle);
852c2936 1823
6c737d05
MD
1824 ts_end = shmp_index(handle, buf->ts_end, oldidx);
1825 if (!ts_end)
1826 return;
852c2936 1827 /*
6c737d05
MD
1828 * This is the last space reservation in that sub-buffer before
1829 * it gets delivered. This provides exclusive access to write to
1830 * this sub-buffer's ts_end. There are also no concurrent
1831 * readers of that ts_end because delivery of that sub-buffer is
1832 * postponed until the commit counter is incremented for the
1833 * current space reservation.
1834 */
373ea80a 1835 *ts_end = ctx->priv->timestamp;
6c737d05
MD
1836
1837 /*
1838 * Order all writes to buffer and store to ts_end before the commit
1839 * count update that will determine that the subbuffer is full.
852c2936 1840 */
a6352fd4 1841 cmm_smp_wmb();
3d3c3833 1842 cc_hot = shmp_index(handle, buf->commit_hot, oldidx);
15500a1b
MD
1843 if (!cc_hot)
1844 return;
3d3c3833
MD
1845 v_add(config, padding_size, &cc_hot->cc);
1846 commit_count = v_read(config, &cc_hot->cc);
852c2936 1847 lib_ring_buffer_check_deliver(config, buf, chan, offsets->old - 1,
f27b0770 1848 commit_count, oldidx, handle, ctx);
d2fe4771
MD
1849 lib_ring_buffer_write_commit_counter(config, buf, chan,
1850 offsets->old + padding_size, commit_count, handle,
3d3c3833 1851 cc_hot);
852c2936
MD
1852}
1853
1854/*
1855 * lib_ring_buffer_switch_new_start: Populate new subbuffer.
1856 *
1857 * This code can be executed unordered : writers may already have written to the
1858 * sub-buffer before this code gets executed, caution. The commit makes sure
1859 * that this code is executed before the deliver of this sub-buffer.
1860 */
1861static
b5457df5
MD
1862void lib_ring_buffer_switch_new_start(struct lttng_ust_ring_buffer *buf,
1863 struct lttng_ust_ring_buffer_channel *chan,
852c2936 1864 struct switch_offsets *offsets,
f27b0770 1865 const struct lttng_ust_ring_buffer_ctx *ctx,
38fae1d3 1866 struct lttng_ust_shm_handle *handle)
852c2936 1867{
b5457df5 1868 const struct lttng_ust_ring_buffer_config *config = &chan->backend.config;
852c2936
MD
1869 unsigned long beginidx = subbuf_index(offsets->begin, chan);
1870 unsigned long commit_count;
3d3c3833 1871 struct commit_counters_hot *cc_hot;
852c2936 1872
373ea80a 1873 config->cb.buffer_begin(buf, ctx->priv->timestamp, beginidx, handle);
852c2936
MD
1874
1875 /*
1876 * Order all writes to buffer before the commit count update that will
1877 * determine that the subbuffer is full.
1878 */
a6352fd4 1879 cmm_smp_wmb();
3d3c3833 1880 cc_hot = shmp_index(handle, buf->commit_hot, beginidx);
15500a1b
MD
1881 if (!cc_hot)
1882 return;
1883 v_add(config, config->cb.subbuffer_header_size(), &cc_hot->cc);
3d3c3833 1884 commit_count = v_read(config, &cc_hot->cc);
852c2936
MD
1885 /* Check if the written buffer has to be delivered */
1886 lib_ring_buffer_check_deliver(config, buf, chan, offsets->begin,
f27b0770 1887 commit_count, beginidx, handle, ctx);
d2fe4771 1888 lib_ring_buffer_write_commit_counter(config, buf, chan,
80249235 1889 offsets->begin + config->cb.subbuffer_header_size(),
3d3c3833 1890 commit_count, handle, cc_hot);
852c2936
MD
1891}
1892
1ad21f70
MD
1893/*
1894 * lib_ring_buffer_switch_new_end: finish switching current subbuffer
1895 *
3962118d
MD
1896 * Calls subbuffer_set_data_size() to set the data size of the current
1897 * sub-buffer. We do not need to perform check_deliver nor commit here,
1898 * since this task will be done by the "commit" of the event for which
1899 * we are currently doing the space reservation.
1ad21f70
MD
1900 */
1901static
b5457df5
MD
1902void lib_ring_buffer_switch_new_end(struct lttng_ust_ring_buffer *buf,
1903 struct lttng_ust_ring_buffer_channel *chan,
1ad21f70 1904 struct switch_offsets *offsets,
f27b0770 1905 const struct lttng_ust_ring_buffer_ctx *ctx,
1ad21f70
MD
1906 struct lttng_ust_shm_handle *handle)
1907{
b5457df5 1908 const struct lttng_ust_ring_buffer_config *config = &chan->backend.config;
3962118d 1909 unsigned long endidx, data_size;
6c737d05 1910 uint64_t *ts_end;
1ad21f70 1911
3962118d 1912 endidx = subbuf_index(offsets->end - 1, chan);
1ad21f70 1913 data_size = subbuf_offset(offsets->end - 1, chan) + 1;
1ad21f70
MD
1914 subbuffer_set_data_size(config, &buf->backend, endidx, data_size,
1915 handle);
6c737d05
MD
1916 ts_end = shmp_index(handle, buf->ts_end, endidx);
1917 if (!ts_end)
1918 return;
1919 /*
1920 * This is the last space reservation in that sub-buffer before
1921 * it gets delivered. This provides exclusive access to write to
1922 * this sub-buffer's ts_end. There are also no concurrent
1923 * readers of that ts_end because delivery of that sub-buffer is
1924 * postponed until the commit counter is incremented for the
1925 * current space reservation.
1926 */
373ea80a 1927 *ts_end = ctx->priv->timestamp;
1ad21f70
MD
1928}
1929
852c2936
MD
1930/*
1931 * Returns :
1932 * 0 if ok
1933 * !0 if execution must be aborted.
1934 */
1935static
1936int lib_ring_buffer_try_switch_slow(enum switch_mode mode,
b5457df5
MD
1937 struct lttng_ust_ring_buffer *buf,
1938 struct lttng_ust_ring_buffer_channel *chan,
852c2936 1939 struct switch_offsets *offsets,
f27b0770 1940 struct lttng_ust_ring_buffer_ctx *ctx,
2dac206d 1941 struct lttng_ust_shm_handle *handle)
852c2936 1942{
b5457df5 1943 const struct lttng_ust_ring_buffer_config *config = &chan->backend.config;
2dac206d 1944 unsigned long off, reserve_commit_diff;
852c2936
MD
1945
1946 offsets->begin = v_read(config, &buf->offset);
1947 offsets->old = offsets->begin;
1948 offsets->switch_old_start = 0;
1949 off = subbuf_offset(offsets->begin, chan);
1950
373ea80a 1951 ctx->priv->timestamp = config->cb.ring_buffer_clock_read(chan);
852c2936
MD
1952
1953 /*
1954 * Ensure we flush the header of an empty subbuffer when doing the
1955 * finalize (SWITCH_FLUSH). This ensures that we end up knowing the
1956 * total data gathering duration even if there were no records saved
1957 * after the last buffer switch.
1958 * In SWITCH_ACTIVE mode, switch the buffer when it contains events.
1959 * SWITCH_ACTIVE only flushes the current subbuffer, dealing with end of
1960 * subbuffer header as appropriate.
1961 * The next record that reserves space will be responsible for
1962 * populating the following subbuffer header. We choose not to populate
1963 * the next subbuffer header here because we want to be able to use
a6352fd4
MD
1964 * SWITCH_ACTIVE for periodical buffer flush, which must
1965 * guarantee that all the buffer content (records and header
1966 * timestamps) are visible to the reader. This is required for
1967 * quiescence guarantees for the fusion merge.
852c2936 1968 */
2dac206d
MD
1969 if (mode != SWITCH_FLUSH && !off)
1970 return -1; /* we do not have to switch : buffer is empty */
1971
1972 if (caa_unlikely(off == 0)) {
1973 unsigned long sb_index, commit_count;
15500a1b 1974 struct commit_counters_cold *cc_cold;
2dac206d
MD
1975
1976 /*
48f22436
MD
1977 * We are performing a SWITCH_FLUSH. There may be concurrent
1978 * writes into the buffer if e.g. invoked while performing a
1979 * snapshot on an active trace.
2dac206d 1980 *
48f22436
MD
1981 * If the client does not save any header information
1982 * (sub-buffer header size == 0), don't switch empty subbuffer
1983 * on finalize, because it is invalid to deliver a completely
1984 * empty subbuffer.
2dac206d
MD
1985 */
1986 if (!config->cb.subbuffer_header_size())
1987 return -1;
1988
1989 /* Test new buffer integrity */
1990 sb_index = subbuf_index(offsets->begin, chan);
15500a1b
MD
1991 cc_cold = shmp_index(handle, buf->commit_cold, sb_index);
1992 if (!cc_cold)
1993 return -1;
1994 commit_count = v_read(config, &cc_cold->cc_sb);
2dac206d
MD
1995 reserve_commit_diff =
1996 (buf_trunc(offsets->begin, chan)
1997 >> chan->backend.num_subbuf_order)
1998 - (commit_count & chan->commit_count_mask);
1999 if (caa_likely(reserve_commit_diff == 0)) {
2000 /* Next subbuffer not being written to. */
2001 if (caa_unlikely(config->mode != RING_BUFFER_OVERWRITE &&
2002 subbuf_trunc(offsets->begin, chan)
2003 - subbuf_trunc((unsigned long)
2004 uatomic_read(&buf->consumed), chan)
2005 >= chan->backend.buf_size)) {
2006 /*
2007 * We do not overwrite non consumed buffers
2008 * and we are full : don't switch.
2009 */
852c2936 2010 return -1;
2dac206d
MD
2011 } else {
2012 /*
2013 * Next subbuffer not being written to, and we
2014 * are either in overwrite mode or the buffer is
2015 * not full. It's safe to write in this new
2016 * subbuffer.
2017 */
2018 }
2019 } else {
852c2936 2020 /*
2dac206d
MD
2021 * Next subbuffer reserve offset does not match the
2022 * commit offset. Don't perform switch in
2023 * producer-consumer and overwrite mode. Caused by
2024 * either a writer OOPS or too many nested writes over a
2025 * reserve/commit pair.
852c2936 2026 */
2dac206d 2027 return -1;
852c2936 2028 }
2dac206d
MD
2029
2030 /*
2031 * Need to write the subbuffer start header on finalize.
2032 */
2033 offsets->switch_old_start = 1;
2034 }
2035 offsets->begin = subbuf_align(offsets->begin, chan);
852c2936
MD
2036 /* Note: old points to the next subbuf at offset 0 */
2037 offsets->end = offsets->begin;
f27b0770
MD
2038 /*
2039 * Populate the records lost counters prior to performing a
2040 * sub-buffer switch.
2041 */
2042 ctx->priv->records_lost_full = v_read(config, &buf->records_lost_full);
2043 ctx->priv->records_lost_wrap = v_read(config, &buf->records_lost_wrap);
2044 ctx->priv->records_lost_big = v_read(config, &buf->records_lost_big);
852c2936
MD
2045 return 0;
2046}
2047
2048/*
2049 * Force a sub-buffer switch. This operation is completely reentrant : can be
2050 * called while tracing is active with absolutely no lock held.
2051 *
ef1a13e0
MD
2052 * For RING_BUFFER_SYNC_PER_CPU ring buffers, as a v_cmpxchg is used for
2053 * some atomic operations, this function must be called from the CPU
2054 * which owns the buffer for a ACTIVE flush. However, for
2055 * RING_BUFFER_SYNC_GLOBAL ring buffers, this function can be called
2056 * from any CPU.
852c2936 2057 */
b5457df5 2058void lib_ring_buffer_switch_slow(struct lttng_ust_ring_buffer *buf, enum switch_mode mode,
38fae1d3 2059 struct lttng_ust_shm_handle *handle)
852c2936 2060{
b5457df5
MD
2061 struct lttng_ust_ring_buffer_channel *chan;
2062 const struct lttng_ust_ring_buffer_config *config;
f27b0770
MD
2063 struct lttng_ust_ring_buffer_ctx_private ctx_priv;
2064 struct lttng_ust_ring_buffer_ctx ctx;
852c2936
MD
2065 struct switch_offsets offsets;
2066 unsigned long oldidx;
852c2936 2067
f27b0770 2068 ctx.priv = &ctx_priv;
15500a1b
MD
2069 chan = shmp(handle, buf->backend.chan);
2070 if (!chan)
2071 return;
2072 config = &chan->backend.config;
2073
852c2936
MD
2074 offsets.size = 0;
2075
2076 /*
2077 * Perform retryable operations.
2078 */
2079 do {
2080 if (lib_ring_buffer_try_switch_slow(mode, buf, chan, &offsets,
f27b0770 2081 &ctx, handle))
852c2936
MD
2082 return; /* Switch not needed */
2083 } while (v_cmpxchg(config, &buf->offset, offsets.old, offsets.end)
2084 != offsets.old);
2085
2086 /*
373ea80a
MD
2087 * Atomically update last_timestamp. This update races against concurrent
2088 * atomic updates, but the race will always cause supplementary full
2089 * timestamp records, never the opposite (missing a full timestamp
2090 * record when it would be needed).
852c2936 2091 */
373ea80a 2092 save_last_timestamp(config, buf, ctx.priv->timestamp);
852c2936
MD
2093
2094 /*
2095 * Push the reader if necessary
2096 */
2097 lib_ring_buffer_reserve_push_reader(buf, chan, offsets.old);
2098
2099 oldidx = subbuf_index(offsets.old, chan);
1d498196 2100 lib_ring_buffer_clear_noref(config, &buf->backend, oldidx, handle);
852c2936
MD
2101
2102 /*
2103 * May need to populate header start on SWITCH_FLUSH.
2104 */
2105 if (offsets.switch_old_start) {
f27b0770 2106 lib_ring_buffer_switch_old_start(buf, chan, &offsets, &ctx, handle);
852c2936
MD
2107 offsets.old += config->cb.subbuffer_header_size();
2108 }
2109
2110 /*
2111 * Switch old subbuffer.
2112 */
f27b0770 2113 lib_ring_buffer_switch_old_end(buf, chan, &offsets, &ctx, handle);
852c2936 2114}
852c2936 2115
6f97f9c2
MD
2116static
2117bool handle_blocking_retry(int *timeout_left_ms)
2118{
2119 int timeout = *timeout_left_ms, delay;
2120
2121 if (caa_likely(!timeout))
2122 return false; /* Do not retry, discard event. */
2123 if (timeout < 0) /* Wait forever. */
2124 delay = RETRY_DELAY_MS;
2125 else
2126 delay = min_t(int, timeout, RETRY_DELAY_MS);
2127 (void) poll(NULL, 0, delay);
2128 if (timeout > 0)
2129 *timeout_left_ms -= delay;
2130 return true; /* Retry. */
2131}
2132
852c2936
MD
2133/*
2134 * Returns :
2135 * 0 if ok
2136 * -ENOSPC if event size is too large for packet.
2137 * -ENOBUFS if there is currently not enough space in buffer for the event.
2138 * -EIO if data cannot be written into the buffer for any other reason.
2139 */
2140static
b5457df5
MD
2141int lib_ring_buffer_try_reserve_slow(struct lttng_ust_ring_buffer *buf,
2142 struct lttng_ust_ring_buffer_channel *chan,
852c2936 2143 struct switch_offsets *offsets,
b5457df5 2144 struct lttng_ust_ring_buffer_ctx *ctx,
e56bb47c 2145 void *client_ctx)
852c2936 2146{
b5457df5
MD
2147 struct lttng_ust_ring_buffer_ctx_private *ctx_private = ctx->priv;
2148 const struct lttng_ust_ring_buffer_config *config = &chan->backend.config;
8936b6c0 2149 struct lttng_ust_shm_handle *handle = chan->handle;
e185cf4b 2150 unsigned long reserve_commit_diff, offset_cmp;
b2c5f61a 2151 int timeout_left_ms = lttng_ust_ringbuffer_get_timeout(chan);
852c2936 2152
e185cf4b
MD
2153retry:
2154 offsets->begin = offset_cmp = v_read(config, &buf->offset);
852c2936
MD
2155 offsets->old = offsets->begin;
2156 offsets->switch_new_start = 0;
1ad21f70 2157 offsets->switch_new_end = 0;
852c2936
MD
2158 offsets->switch_old_end = 0;
2159 offsets->pre_header_padding = 0;
2160
373ea80a
MD
2161 ctx_private->timestamp = config->cb.ring_buffer_clock_read(chan);
2162 if ((int64_t) ctx_private->timestamp == -EIO)
852c2936
MD
2163 return -EIO;
2164
373ea80a
MD
2165 if (last_timestamp_overflow(config, buf, ctx_private->timestamp))
2166 ctx_private->rflags |= RING_BUFFER_RFLAG_FULL_TIMESTAMP;
852c2936 2167
8936b6c0 2168 if (caa_unlikely(subbuf_offset(offsets->begin, chan) == 0)) {
852c2936
MD
2169 offsets->switch_new_start = 1; /* For offsets->begin */
2170 } else {
2171 offsets->size = config->cb.record_header_size(config, chan,
2172 offsets->begin,
2173 &offsets->pre_header_padding,
e56bb47c 2174 ctx, client_ctx);
852c2936 2175 offsets->size +=
b5457df5 2176 lttng_ust_ring_buffer_align(offsets->begin + offsets->size,
8936b6c0 2177 ctx->largest_align)
852c2936 2178 + ctx->data_size;
b5a3dfa5 2179 if (caa_unlikely(subbuf_offset(offsets->begin, chan) +
852c2936
MD
2180 offsets->size > chan->backend.subbuf_size)) {
2181 offsets->switch_old_end = 1; /* For offsets->old */
2182 offsets->switch_new_start = 1; /* For offsets->begin */
2183 }
2184 }
b5a3dfa5 2185 if (caa_unlikely(offsets->switch_new_start)) {
e185cf4b 2186 unsigned long sb_index, commit_count;
15500a1b 2187 struct commit_counters_cold *cc_cold;
852c2936
MD
2188
2189 /*
2190 * We are typically not filling the previous buffer completely.
2191 */
b5a3dfa5 2192 if (caa_likely(offsets->switch_old_end))
852c2936
MD
2193 offsets->begin = subbuf_align(offsets->begin, chan);
2194 offsets->begin = offsets->begin
2195 + config->cb.subbuffer_header_size();
2196 /* Test new buffer integrity */
2197 sb_index = subbuf_index(offsets->begin, chan);
e185cf4b
MD
2198 /*
2199 * Read buf->offset before buf->commit_cold[sb_index].cc_sb.
2200 * lib_ring_buffer_check_deliver() has the matching
2201 * memory barriers required around commit_cold cc_sb
2202 * updates to ensure reserve and commit counter updates
2203 * are not seen reordered when updated by another CPU.
2204 */
2205 cmm_smp_rmb();
15500a1b
MD
2206 cc_cold = shmp_index(handle, buf->commit_cold, sb_index);
2207 if (!cc_cold)
2208 return -1;
2209 commit_count = v_read(config, &cc_cold->cc_sb);
e185cf4b
MD
2210 /* Read buf->commit_cold[sb_index].cc_sb before buf->offset. */
2211 cmm_smp_rmb();
2212 if (caa_unlikely(offset_cmp != v_read(config, &buf->offset))) {
2213 /*
2214 * The reserve counter have been concurrently updated
2215 * while we read the commit counter. This means the
2216 * commit counter we read might not match buf->offset
2217 * due to concurrent update. We therefore need to retry.
2218 */
2219 goto retry;
2220 }
852c2936
MD
2221 reserve_commit_diff =
2222 (buf_trunc(offsets->begin, chan)
2223 >> chan->backend.num_subbuf_order)
e185cf4b 2224 - (commit_count & chan->commit_count_mask);
b5a3dfa5 2225 if (caa_likely(reserve_commit_diff == 0)) {
852c2936 2226 /* Next subbuffer not being written to. */
b5a3dfa5 2227 if (caa_unlikely(config->mode != RING_BUFFER_OVERWRITE &&
852c2936
MD
2228 subbuf_trunc(offsets->begin, chan)
2229 - subbuf_trunc((unsigned long)
a6352fd4 2230 uatomic_read(&buf->consumed), chan)
852c2936 2231 >= chan->backend.buf_size)) {
64493e4f
MD
2232 unsigned long nr_lost;
2233
6f97f9c2
MD
2234 if (handle_blocking_retry(&timeout_left_ms))
2235 goto retry;
2236
852c2936
MD
2237 /*
2238 * We do not overwrite non consumed buffers
2239 * and we are full : record is lost.
2240 */
64493e4f 2241 nr_lost = v_read(config, &buf->records_lost_full);
852c2936 2242 v_inc(config, &buf->records_lost_full);
64493e4f
MD
2243 if ((nr_lost & (DBG_PRINT_NR_LOST - 1)) == 0) {
2244 DBG("%lu or more records lost in (%s:%d) (buffer full)\n",
2245 nr_lost + 1, chan->backend.name,
2246 buf->backend.cpu);
2247 }
852c2936
MD
2248 return -ENOBUFS;
2249 } else {
2250 /*
2251 * Next subbuffer not being written to, and we
2252 * are either in overwrite mode or the buffer is
2253 * not full. It's safe to write in this new
2254 * subbuffer.
2255 */
2256 }
2257 } else {
64493e4f
MD
2258 unsigned long nr_lost;
2259
852c2936
MD
2260 /*
2261 * Next subbuffer reserve offset does not match the
e185cf4b
MD
2262 * commit offset, and this did not involve update to the
2263 * reserve counter. Drop record in producer-consumer and
852c2936
MD
2264 * overwrite mode. Caused by either a writer OOPS or too
2265 * many nested writes over a reserve/commit pair.
2266 */
64493e4f 2267 nr_lost = v_read(config, &buf->records_lost_wrap);
852c2936 2268 v_inc(config, &buf->records_lost_wrap);
64493e4f
MD
2269 if ((nr_lost & (DBG_PRINT_NR_LOST - 1)) == 0) {
2270 DBG("%lu or more records lost in (%s:%d) (wrap-around)\n",
2271 nr_lost + 1, chan->backend.name,
2272 buf->backend.cpu);
2273 }
852c2936
MD
2274 return -EIO;
2275 }
2276 offsets->size =
2277 config->cb.record_header_size(config, chan,
2278 offsets->begin,
2279 &offsets->pre_header_padding,
e56bb47c 2280 ctx, client_ctx);
852c2936 2281 offsets->size +=
b5457df5 2282 lttng_ust_ring_buffer_align(offsets->begin + offsets->size,
852c2936
MD
2283 ctx->largest_align)
2284 + ctx->data_size;
b5a3dfa5 2285 if (caa_unlikely(subbuf_offset(offsets->begin, chan)
852c2936 2286 + offsets->size > chan->backend.subbuf_size)) {
64493e4f
MD
2287 unsigned long nr_lost;
2288
852c2936
MD
2289 /*
2290 * Record too big for subbuffers, report error, don't
2291 * complete the sub-buffer switch.
2292 */
64493e4f 2293 nr_lost = v_read(config, &buf->records_lost_big);
852c2936 2294 v_inc(config, &buf->records_lost_big);
64493e4f
MD
2295 if ((nr_lost & (DBG_PRINT_NR_LOST - 1)) == 0) {
2296 DBG("%lu or more records lost in (%s:%d) record size "
2297 " of %zu bytes is too large for buffer\n",
2298 nr_lost + 1, chan->backend.name,
2299 buf->backend.cpu, offsets->size);
2300 }
852c2936
MD
2301 return -ENOSPC;
2302 } else {
2303 /*
2304 * We just made a successful buffer switch and the
2305 * record fits in the new subbuffer. Let's write.
2306 */
2307 }
2308 } else {
2309 /*
2310 * Record fits in the current buffer and we are not on a switch
2311 * boundary. It's safe to write.
2312 */
2313 }
2314 offsets->end = offsets->begin + offsets->size;
1ad21f70
MD
2315
2316 if (caa_unlikely(subbuf_offset(offsets->end, chan) == 0)) {
2317 /*
2318 * The offset_end will fall at the very beginning of the next
2319 * subbuffer.
2320 */
2321 offsets->switch_new_end = 1; /* For offsets->begin */
2322 }
f27b0770
MD
2323 /*
2324 * Populate the records lost counters when the space reservation
2325 * may cause a sub-buffer switch.
2326 */
2327 if (offsets->switch_new_end || offsets->switch_old_end) {
2328 ctx_private->records_lost_full = v_read(config, &buf->records_lost_full);
2329 ctx_private->records_lost_wrap = v_read(config, &buf->records_lost_wrap);
2330 ctx_private->records_lost_big = v_read(config, &buf->records_lost_big);
2331 }
852c2936
MD
2332 return 0;
2333}
2334
2335/**
2336 * lib_ring_buffer_reserve_slow - Atomic slot reservation in a buffer.
2337 * @ctx: ring buffer context.
2338 *
2339 * Return : -NOBUFS if not enough space, -ENOSPC if event size too large,
2340 * -EIO for other errors, else returns 0.
2341 * It will take care of sub-buffer switching.
2342 */
b5457df5 2343int lib_ring_buffer_reserve_slow(struct lttng_ust_ring_buffer_ctx *ctx,
e56bb47c 2344 void *client_ctx)
852c2936 2345{
b5457df5
MD
2346 struct lttng_ust_ring_buffer_ctx_private *ctx_private = ctx->priv;
2347 struct lttng_ust_ring_buffer_channel *chan = ctx_private->chan;
8936b6c0 2348 struct lttng_ust_shm_handle *handle = chan->handle;
b5457df5
MD
2349 const struct lttng_ust_ring_buffer_config *config = &chan->backend.config;
2350 struct lttng_ust_ring_buffer *buf;
852c2936
MD
2351 struct switch_offsets offsets;
2352 int ret;
2353
2354 if (config->alloc == RING_BUFFER_ALLOC_PER_CPU)
8936b6c0 2355 buf = shmp(handle, chan->backend.buf[ctx_private->reserve_cpu].shmp);
852c2936 2356 else
1d498196 2357 buf = shmp(handle, chan->backend.buf[0].shmp);
15500a1b
MD
2358 if (!buf)
2359 return -EIO;
8936b6c0 2360 ctx_private->buf = buf;
852c2936
MD
2361
2362 offsets.size = 0;
2363
2364 do {
2365 ret = lib_ring_buffer_try_reserve_slow(buf, chan, &offsets,
e56bb47c 2366 ctx, client_ctx);
b5a3dfa5 2367 if (caa_unlikely(ret))
852c2936 2368 return ret;
b5a3dfa5 2369 } while (caa_unlikely(v_cmpxchg(config, &buf->offset, offsets.old,
852c2936
MD
2370 offsets.end)
2371 != offsets.old));
2372
2373 /*
373ea80a
MD
2374 * Atomically update last_timestamp. This update races against concurrent
2375 * atomic updates, but the race will always cause supplementary full
2376 * timestamp records, never the opposite (missing a full timestamp
2377 * record when it would be needed).
852c2936 2378 */
373ea80a 2379 save_last_timestamp(config, buf, ctx_private->timestamp);
852c2936
MD
2380
2381 /*
2382 * Push the reader if necessary
2383 */
2384 lib_ring_buffer_reserve_push_reader(buf, chan, offsets.end - 1);
2385
2386 /*
2387 * Clear noref flag for this subbuffer.
2388 */
2389 lib_ring_buffer_clear_noref(config, &buf->backend,
1d498196
MD
2390 subbuf_index(offsets.end - 1, chan),
2391 handle);
852c2936
MD
2392
2393 /*
2394 * Switch old subbuffer if needed.
2395 */
b5a3dfa5 2396 if (caa_unlikely(offsets.switch_old_end)) {
852c2936 2397 lib_ring_buffer_clear_noref(config, &buf->backend,
1d498196
MD
2398 subbuf_index(offsets.old - 1, chan),
2399 handle);
f27b0770 2400 lib_ring_buffer_switch_old_end(buf, chan, &offsets, ctx, handle);
852c2936
MD
2401 }
2402
2403 /*
2404 * Populate new subbuffer.
2405 */
b5a3dfa5 2406 if (caa_unlikely(offsets.switch_new_start))
f27b0770 2407 lib_ring_buffer_switch_new_start(buf, chan, &offsets, ctx, handle);
852c2936 2408
1ad21f70 2409 if (caa_unlikely(offsets.switch_new_end))
f27b0770 2410 lib_ring_buffer_switch_new_end(buf, chan, &offsets, ctx, handle);
1ad21f70 2411
8936b6c0
MD
2412 ctx_private->slot_size = offsets.size;
2413 ctx_private->pre_offset = offsets.begin;
2414 ctx_private->buf_offset = offsets.begin + offsets.pre_header_padding;
852c2936
MD
2415 return 0;
2416}
f645cfa7 2417
b07cd987 2418static
b5457df5
MD
2419void lib_ring_buffer_vmcore_check_deliver(const struct lttng_ust_ring_buffer_config *config,
2420 struct lttng_ust_ring_buffer *buf,
b07cd987
MD
2421 unsigned long commit_count,
2422 unsigned long idx,
2423 struct lttng_ust_shm_handle *handle)
2424{
15500a1b
MD
2425 struct commit_counters_hot *cc_hot;
2426
2427 if (config->oops != RING_BUFFER_OOPS_CONSISTENCY)
2428 return;
2429 cc_hot = shmp_index(handle, buf->commit_hot, idx);
2430 if (!cc_hot)
2431 return;
2432 v_set(config, &cc_hot->seq, commit_count);
b07cd987
MD
2433}
2434
9c995331
MD
2435/*
2436 * The ring buffer can count events recorded and overwritten per buffer,
2437 * but it is disabled by default due to its performance overhead.
2438 */
2439#ifdef LTTNG_RING_BUFFER_COUNT_EVENTS
2440static
b5457df5
MD
2441void deliver_count_events(const struct lttng_ust_ring_buffer_config *config,
2442 struct lttng_ust_ring_buffer *buf,
9c995331
MD
2443 unsigned long idx,
2444 struct lttng_ust_shm_handle *handle)
2445{
2446 v_add(config, subbuffer_get_records_count(config,
2447 &buf->backend, idx, handle),
2448 &buf->records_count);
2449 v_add(config, subbuffer_count_records_overrun(config,
2450 &buf->backend, idx, handle),
2451 &buf->records_overrun);
2452}
2453#else /* LTTNG_RING_BUFFER_COUNT_EVENTS */
2454static
2208d8b5 2455void deliver_count_events(
b5457df5
MD
2456 const struct lttng_ust_ring_buffer_config *config __attribute__((unused)),
2457 struct lttng_ust_ring_buffer *buf __attribute__((unused)),
2208d8b5
MJ
2458 unsigned long idx __attribute__((unused)),
2459 struct lttng_ust_shm_handle *handle __attribute__((unused)))
9c995331
MD
2460{
2461}
2462#endif /* #else LTTNG_RING_BUFFER_COUNT_EVENTS */
2463
b5457df5
MD
2464void lib_ring_buffer_check_deliver_slow(const struct lttng_ust_ring_buffer_config *config,
2465 struct lttng_ust_ring_buffer *buf,
2466 struct lttng_ust_ring_buffer_channel *chan,
b07cd987
MD
2467 unsigned long offset,
2468 unsigned long commit_count,
2469 unsigned long idx,
2470 struct lttng_ust_shm_handle *handle,
f27b0770 2471 const struct lttng_ust_ring_buffer_ctx *ctx)
b07cd987
MD
2472{
2473 unsigned long old_commit_count = commit_count
2474 - chan->backend.subbuf_size;
15500a1b 2475 struct commit_counters_cold *cc_cold;
b07cd987
MD
2476
2477 /*
2478 * If we succeeded at updating cc_sb below, we are the subbuffer
2479 * writer delivering the subbuffer. Deals with concurrent
2480 * updates of the "cc" value without adding a add_return atomic
2481 * operation to the fast path.
2482 *
2483 * We are doing the delivery in two steps:
2484 * - First, we cmpxchg() cc_sb to the new value
2485 * old_commit_count + 1. This ensures that we are the only
2486 * subbuffer user successfully filling the subbuffer, but we
2487 * do _not_ set the cc_sb value to "commit_count" yet.
2488 * Therefore, other writers that would wrap around the ring
2489 * buffer and try to start writing to our subbuffer would
2490 * have to drop records, because it would appear as
2491 * non-filled.
2492 * We therefore have exclusive access to the subbuffer control
2493 * structures. This mutual exclusion with other writers is
2494 * crucially important to perform record overruns count in
2495 * flight recorder mode locklessly.
2496 * - When we are ready to release the subbuffer (either for
2497 * reading or for overrun by other writers), we simply set the
2498 * cc_sb value to "commit_count" and perform delivery.
2499 *
2500 * The subbuffer size is least 2 bytes (minimum size: 1 page).
2501 * This guarantees that old_commit_count + 1 != commit_count.
2502 */
2503
2504 /*
2505 * Order prior updates to reserve count prior to the
2506 * commit_cold cc_sb update.
2507 */
2508 cmm_smp_wmb();
15500a1b
MD
2509 cc_cold = shmp_index(handle, buf->commit_cold, idx);
2510 if (!cc_cold)
2511 return;
2512 if (caa_likely(v_cmpxchg(config, &cc_cold->cc_sb,
b07cd987
MD
2513 old_commit_count, old_commit_count + 1)
2514 == old_commit_count)) {
6c737d05
MD
2515 uint64_t *ts_end;
2516
b07cd987
MD
2517 /*
2518 * Start of exclusive subbuffer access. We are
2519 * guaranteed to be the last writer in this subbuffer
2520 * and any other writer trying to access this subbuffer
2521 * in this state is required to drop records.
6c737d05
MD
2522 *
2523 * We can read the ts_end for the current sub-buffer
2524 * which has been saved by the very last space
2525 * reservation for the current sub-buffer.
2526 *
2527 * Order increment of commit counter before reading ts_end.
b07cd987 2528 */
6c737d05
MD
2529 cmm_smp_mb();
2530 ts_end = shmp_index(handle, buf->ts_end, idx);
2531 if (!ts_end)
2532 return;
9c995331 2533 deliver_count_events(config, buf, idx, handle);
6c737d05 2534 config->cb.buffer_end(buf, *ts_end, idx,
b07cd987
MD
2535 lib_ring_buffer_get_data_size(config,
2536 buf,
2537 idx,
2538 handle),
f27b0770 2539 handle, ctx);
b07cd987
MD
2540
2541 /*
2542 * Increment the packet counter while we have exclusive
2543 * access.
2544 */
2545 subbuffer_inc_packet_count(config, &buf->backend, idx, handle);
2546
2547 /*
2548 * Set noref flag and offset for this subbuffer id.
2549 * Contains a memory barrier that ensures counter stores
2550 * are ordered before set noref and offset.
2551 */
2552 lib_ring_buffer_set_noref_offset(config, &buf->backend, idx,
2553 buf_trunc_val(offset, chan), handle);
2554
2555 /*
2556 * Order set_noref and record counter updates before the
2557 * end of subbuffer exclusive access. Orders with
2558 * respect to writers coming into the subbuffer after
2559 * wrap around, and also order wrt concurrent readers.
2560 */
2561 cmm_smp_mb();
2562 /* End of exclusive subbuffer access */
15500a1b 2563 v_set(config, &cc_cold->cc_sb, commit_count);
b07cd987
MD
2564 /*
2565 * Order later updates to reserve count after
2566 * the commit cold cc_sb update.
2567 */
2568 cmm_smp_wmb();
2569 lib_ring_buffer_vmcore_check_deliver(config, buf,
2570 commit_count, idx, handle);
2571
2572 /*
2573 * RING_BUFFER_WAKEUP_BY_WRITER wakeup is not lock-free.
2574 */
2575 if (config->wakeup == RING_BUFFER_WAKEUP_BY_WRITER
2576 && uatomic_read(&buf->active_readers)
2577 && lib_ring_buffer_poll_deliver(config, buf, chan, handle)) {
2578 lib_ring_buffer_wakeup(buf, handle);
2579 }
2580 }
2581}
2582
f645cfa7 2583/*
a9fd951a 2584 * Force a read (imply TLS allocation for dlopen) of TLS variables.
f645cfa7 2585 */
a9fd951a 2586void lttng_ringbuffer_alloc_tls(void)
f645cfa7 2587{
742ac92a 2588 __asm__ __volatile__ ("" : : "m" (URCU_TLS(lib_ring_buffer_nesting)));
f645cfa7 2589}
03d2d293
MD
2590
2591void lib_ringbuffer_signal_init(void)
2592{
2593 sigset_t mask;
2594 int ret;
2595
2596 /*
2597 * Block signal for entire process, so only our thread processes
2598 * it.
2599 */
2600 rb_setmask(&mask);
2601 ret = pthread_sigmask(SIG_BLOCK, &mask, NULL);
2602 if (ret) {
2603 errno = ret;
2604 PERROR("pthread_sigmask");
2605 }
2606}
This page took 0.182448 seconds and 4 git commands to generate.