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