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