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