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