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