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