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