blob: 5e1b9f6e77f31f1436e60c75bd3b1338c18f8e90 [file] [log] [blame]
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001// SPDX-License-Identifier: GPL-2.0
2/*
3 * Generic ring buffer
4 *
5 * Copyright (C) 2008 Steven Rostedt <srostedt@redhat.com>
6 */
7#include <linux/trace_events.h>
8#include <linux/ring_buffer.h>
9#include <linux/trace_clock.h>
10#include <linux/sched/clock.h>
11#include <linux/trace_seq.h>
12#include <linux/spinlock.h>
13#include <linux/irq_work.h>
Olivier Deprez0e641232021-09-23 10:07:05 +020014#include <linux/security.h>
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000015#include <linux/uaccess.h>
16#include <linux/hardirq.h>
17#include <linux/kthread.h> /* for self test */
18#include <linux/module.h>
19#include <linux/percpu.h>
20#include <linux/mutex.h>
21#include <linux/delay.h>
22#include <linux/slab.h>
23#include <linux/init.h>
24#include <linux/hash.h>
25#include <linux/list.h>
26#include <linux/cpu.h>
27#include <linux/oom.h>
28
29#include <asm/local.h>
30
31static void update_pages_handler(struct work_struct *work);
32
33/*
34 * The ring buffer header is special. We must manually up keep it.
35 */
36int ring_buffer_print_entry_header(struct trace_seq *s)
37{
38 trace_seq_puts(s, "# compressed entry header\n");
39 trace_seq_puts(s, "\ttype_len : 5 bits\n");
40 trace_seq_puts(s, "\ttime_delta : 27 bits\n");
41 trace_seq_puts(s, "\tarray : 32 bits\n");
42 trace_seq_putc(s, '\n');
43 trace_seq_printf(s, "\tpadding : type == %d\n",
44 RINGBUF_TYPE_PADDING);
45 trace_seq_printf(s, "\ttime_extend : type == %d\n",
46 RINGBUF_TYPE_TIME_EXTEND);
47 trace_seq_printf(s, "\ttime_stamp : type == %d\n",
48 RINGBUF_TYPE_TIME_STAMP);
49 trace_seq_printf(s, "\tdata max type_len == %d\n",
50 RINGBUF_TYPE_DATA_TYPE_LEN_MAX);
51
52 return !trace_seq_has_overflowed(s);
53}
54
55/*
56 * The ring buffer is made up of a list of pages. A separate list of pages is
57 * allocated for each CPU. A writer may only write to a buffer that is
58 * associated with the CPU it is currently executing on. A reader may read
59 * from any per cpu buffer.
60 *
61 * The reader is special. For each per cpu buffer, the reader has its own
62 * reader page. When a reader has read the entire reader page, this reader
63 * page is swapped with another page in the ring buffer.
64 *
65 * Now, as long as the writer is off the reader page, the reader can do what
66 * ever it wants with that page. The writer will never write to that page
67 * again (as long as it is out of the ring buffer).
68 *
69 * Here's some silly ASCII art.
70 *
71 * +------+
72 * |reader| RING BUFFER
73 * |page |
74 * +------+ +---+ +---+ +---+
75 * | |-->| |-->| |
76 * +---+ +---+ +---+
77 * ^ |
78 * | |
79 * +---------------+
80 *
81 *
82 * +------+
83 * |reader| RING BUFFER
84 * |page |------------------v
85 * +------+ +---+ +---+ +---+
86 * | |-->| |-->| |
87 * +---+ +---+ +---+
88 * ^ |
89 * | |
90 * +---------------+
91 *
92 *
93 * +------+
94 * |reader| RING BUFFER
95 * |page |------------------v
96 * +------+ +---+ +---+ +---+
97 * ^ | |-->| |-->| |
98 * | +---+ +---+ +---+
99 * | |
100 * | |
101 * +------------------------------+
102 *
103 *
104 * +------+
105 * |buffer| RING BUFFER
106 * |page |------------------v
107 * +------+ +---+ +---+ +---+
108 * ^ | | | |-->| |
109 * | New +---+ +---+ +---+
110 * | Reader------^ |
111 * | page |
112 * +------------------------------+
113 *
114 *
115 * After we make this swap, the reader can hand this page off to the splice
116 * code and be done with it. It can even allocate a new page if it needs to
117 * and swap that into the ring buffer.
118 *
119 * We will be using cmpxchg soon to make all this lockless.
120 *
121 */
122
123/* Used for individual buffers (after the counter) */
124#define RB_BUFFER_OFF (1 << 20)
125
126#define BUF_PAGE_HDR_SIZE offsetof(struct buffer_data_page, data)
127
128#define RB_EVNT_HDR_SIZE (offsetof(struct ring_buffer_event, array))
129#define RB_ALIGNMENT 4U
130#define RB_MAX_SMALL_DATA (RB_ALIGNMENT * RINGBUF_TYPE_DATA_TYPE_LEN_MAX)
131#define RB_EVNT_MIN_SIZE 8U /* two 32bit words */
Olivier Deprez0e641232021-09-23 10:07:05 +0200132
133#ifndef CONFIG_HAVE_64BIT_ALIGNED_ACCESS
134# define RB_FORCE_8BYTE_ALIGNMENT 0
135# define RB_ARCH_ALIGNMENT RB_ALIGNMENT
136#else
137# define RB_FORCE_8BYTE_ALIGNMENT 1
138# define RB_ARCH_ALIGNMENT 8U
139#endif
140
141#define RB_ALIGN_DATA __aligned(RB_ARCH_ALIGNMENT)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000142
143/* define RINGBUF_TYPE_DATA for 'case RINGBUF_TYPE_DATA:' */
144#define RINGBUF_TYPE_DATA 0 ... RINGBUF_TYPE_DATA_TYPE_LEN_MAX
145
146enum {
147 RB_LEN_TIME_EXTEND = 8,
148 RB_LEN_TIME_STAMP = 8,
149};
150
151#define skip_time_extend(event) \
152 ((struct ring_buffer_event *)((char *)event + RB_LEN_TIME_EXTEND))
153
154#define extended_time(event) \
155 (event->type_len >= RINGBUF_TYPE_TIME_EXTEND)
156
157static inline int rb_null_event(struct ring_buffer_event *event)
158{
159 return event->type_len == RINGBUF_TYPE_PADDING && !event->time_delta;
160}
161
162static void rb_event_set_padding(struct ring_buffer_event *event)
163{
164 /* padding has a NULL time_delta */
165 event->type_len = RINGBUF_TYPE_PADDING;
166 event->time_delta = 0;
167}
168
169static unsigned
170rb_event_data_length(struct ring_buffer_event *event)
171{
172 unsigned length;
173
174 if (event->type_len)
175 length = event->type_len * RB_ALIGNMENT;
176 else
177 length = event->array[0];
178 return length + RB_EVNT_HDR_SIZE;
179}
180
181/*
182 * Return the length of the given event. Will return
183 * the length of the time extend if the event is a
184 * time extend.
185 */
186static inline unsigned
187rb_event_length(struct ring_buffer_event *event)
188{
189 switch (event->type_len) {
190 case RINGBUF_TYPE_PADDING:
191 if (rb_null_event(event))
192 /* undefined */
193 return -1;
194 return event->array[0] + RB_EVNT_HDR_SIZE;
195
196 case RINGBUF_TYPE_TIME_EXTEND:
197 return RB_LEN_TIME_EXTEND;
198
199 case RINGBUF_TYPE_TIME_STAMP:
200 return RB_LEN_TIME_STAMP;
201
202 case RINGBUF_TYPE_DATA:
203 return rb_event_data_length(event);
204 default:
205 BUG();
206 }
207 /* not hit */
208 return 0;
209}
210
211/*
212 * Return total length of time extend and data,
213 * or just the event length for all other events.
214 */
215static inline unsigned
216rb_event_ts_length(struct ring_buffer_event *event)
217{
218 unsigned len = 0;
219
220 if (extended_time(event)) {
221 /* time extends include the data event after it */
222 len = RB_LEN_TIME_EXTEND;
223 event = skip_time_extend(event);
224 }
225 return len + rb_event_length(event);
226}
227
228/**
229 * ring_buffer_event_length - return the length of the event
230 * @event: the event to get the length of
231 *
232 * Returns the size of the data load of a data event.
233 * If the event is something other than a data event, it
234 * returns the size of the event itself. With the exception
235 * of a TIME EXTEND, where it still returns the size of the
236 * data load of the data event after it.
237 */
238unsigned ring_buffer_event_length(struct ring_buffer_event *event)
239{
240 unsigned length;
241
242 if (extended_time(event))
243 event = skip_time_extend(event);
244
245 length = rb_event_length(event);
246 if (event->type_len > RINGBUF_TYPE_DATA_TYPE_LEN_MAX)
247 return length;
248 length -= RB_EVNT_HDR_SIZE;
249 if (length > RB_MAX_SMALL_DATA + sizeof(event->array[0]))
250 length -= sizeof(event->array[0]);
251 return length;
252}
253EXPORT_SYMBOL_GPL(ring_buffer_event_length);
254
255/* inline for ring buffer fast paths */
256static __always_inline void *
257rb_event_data(struct ring_buffer_event *event)
258{
259 if (extended_time(event))
260 event = skip_time_extend(event);
261 BUG_ON(event->type_len > RINGBUF_TYPE_DATA_TYPE_LEN_MAX);
262 /* If length is in len field, then array[0] has the data */
263 if (event->type_len)
264 return (void *)&event->array[0];
265 /* Otherwise length is in array[0] and array[1] has the data */
266 return (void *)&event->array[1];
267}
268
269/**
270 * ring_buffer_event_data - return the data of the event
271 * @event: the event to get the data from
272 */
273void *ring_buffer_event_data(struct ring_buffer_event *event)
274{
275 return rb_event_data(event);
276}
277EXPORT_SYMBOL_GPL(ring_buffer_event_data);
278
279#define for_each_buffer_cpu(buffer, cpu) \
280 for_each_cpu(cpu, buffer->cpumask)
281
282#define TS_SHIFT 27
283#define TS_MASK ((1ULL << TS_SHIFT) - 1)
284#define TS_DELTA_TEST (~TS_MASK)
285
286/**
287 * ring_buffer_event_time_stamp - return the event's extended timestamp
288 * @event: the event to get the timestamp of
289 *
290 * Returns the extended timestamp associated with a data event.
291 * An extended time_stamp is a 64-bit timestamp represented
292 * internally in a special way that makes the best use of space
293 * contained within a ring buffer event. This function decodes
294 * it and maps it to a straight u64 value.
295 */
296u64 ring_buffer_event_time_stamp(struct ring_buffer_event *event)
297{
298 u64 ts;
299
300 ts = event->array[0];
301 ts <<= TS_SHIFT;
302 ts += event->time_delta;
303
304 return ts;
305}
306
307/* Flag when events were overwritten */
308#define RB_MISSED_EVENTS (1 << 31)
309/* Missed count stored at end */
310#define RB_MISSED_STORED (1 << 30)
311
312#define RB_MISSED_FLAGS (RB_MISSED_EVENTS|RB_MISSED_STORED)
313
314struct buffer_data_page {
315 u64 time_stamp; /* page time stamp */
316 local_t commit; /* write committed index */
317 unsigned char data[] RB_ALIGN_DATA; /* data of buffer page */
318};
319
320/*
321 * Note, the buffer_page list must be first. The buffer pages
322 * are allocated in cache lines, which means that each buffer
323 * page will be at the beginning of a cache line, and thus
324 * the least significant bits will be zero. We use this to
325 * add flags in the list struct pointers, to make the ring buffer
326 * lockless.
327 */
328struct buffer_page {
329 struct list_head list; /* list of buffer pages */
330 local_t write; /* index for next write */
331 unsigned read; /* index for next read */
332 local_t entries; /* entries on this page */
333 unsigned long real_end; /* real end of data */
334 struct buffer_data_page *page; /* Actual data page */
335};
336
337/*
338 * The buffer page counters, write and entries, must be reset
339 * atomically when crossing page boundaries. To synchronize this
340 * update, two counters are inserted into the number. One is
341 * the actual counter for the write position or count on the page.
342 *
343 * The other is a counter of updaters. Before an update happens
344 * the update partition of the counter is incremented. This will
345 * allow the updater to update the counter atomically.
346 *
347 * The counter is 20 bits, and the state data is 12.
348 */
349#define RB_WRITE_MASK 0xfffff
350#define RB_WRITE_INTCNT (1 << 20)
351
352static void rb_init_page(struct buffer_data_page *bpage)
353{
354 local_set(&bpage->commit, 0);
355}
356
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000357/*
358 * Also stolen from mm/slob.c. Thanks to Mathieu Desnoyers for pointing
359 * this issue out.
360 */
361static void free_buffer_page(struct buffer_page *bpage)
362{
363 free_page((unsigned long)bpage->page);
364 kfree(bpage);
365}
366
367/*
368 * We need to fit the time_stamp delta into 27 bits.
369 */
370static inline int test_time_stamp(u64 delta)
371{
372 if (delta & TS_DELTA_TEST)
373 return 1;
374 return 0;
375}
376
377#define BUF_PAGE_SIZE (PAGE_SIZE - BUF_PAGE_HDR_SIZE)
378
379/* Max payload is BUF_PAGE_SIZE - header (8bytes) */
380#define BUF_MAX_DATA_SIZE (BUF_PAGE_SIZE - (sizeof(u32) * 2))
381
382int ring_buffer_print_page_header(struct trace_seq *s)
383{
384 struct buffer_data_page field;
385
386 trace_seq_printf(s, "\tfield: u64 timestamp;\t"
387 "offset:0;\tsize:%u;\tsigned:%u;\n",
388 (unsigned int)sizeof(field.time_stamp),
389 (unsigned int)is_signed_type(u64));
390
391 trace_seq_printf(s, "\tfield: local_t commit;\t"
392 "offset:%u;\tsize:%u;\tsigned:%u;\n",
393 (unsigned int)offsetof(typeof(field), commit),
394 (unsigned int)sizeof(field.commit),
395 (unsigned int)is_signed_type(long));
396
397 trace_seq_printf(s, "\tfield: int overwrite;\t"
398 "offset:%u;\tsize:%u;\tsigned:%u;\n",
399 (unsigned int)offsetof(typeof(field), commit),
400 1,
401 (unsigned int)is_signed_type(long));
402
403 trace_seq_printf(s, "\tfield: char data;\t"
404 "offset:%u;\tsize:%u;\tsigned:%u;\n",
405 (unsigned int)offsetof(typeof(field), data),
406 (unsigned int)BUF_PAGE_SIZE,
407 (unsigned int)is_signed_type(char));
408
409 return !trace_seq_has_overflowed(s);
410}
411
412struct rb_irq_work {
413 struct irq_work work;
414 wait_queue_head_t waiters;
415 wait_queue_head_t full_waiters;
416 bool waiters_pending;
417 bool full_waiters_pending;
418 bool wakeup_full;
419};
420
421/*
422 * Structure to hold event state and handle nested events.
423 */
424struct rb_event_info {
425 u64 ts;
426 u64 delta;
427 unsigned long length;
428 struct buffer_page *tail_page;
429 int add_timestamp;
430};
431
432/*
433 * Used for which event context the event is in.
Olivier Deprez0e641232021-09-23 10:07:05 +0200434 * TRANSITION = 0
435 * NMI = 1
436 * IRQ = 2
437 * SOFTIRQ = 3
438 * NORMAL = 4
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000439 *
440 * See trace_recursive_lock() comment below for more details.
441 */
442enum {
Olivier Deprez0e641232021-09-23 10:07:05 +0200443 RB_CTX_TRANSITION,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000444 RB_CTX_NMI,
445 RB_CTX_IRQ,
446 RB_CTX_SOFTIRQ,
447 RB_CTX_NORMAL,
448 RB_CTX_MAX
449};
450
451/*
452 * head_page == tail_page && head == tail then buffer is empty.
453 */
454struct ring_buffer_per_cpu {
455 int cpu;
456 atomic_t record_disabled;
457 struct ring_buffer *buffer;
458 raw_spinlock_t reader_lock; /* serialize readers */
459 arch_spinlock_t lock;
460 struct lock_class_key lock_key;
461 struct buffer_data_page *free_page;
462 unsigned long nr_pages;
463 unsigned int current_context;
464 struct list_head *pages;
465 struct buffer_page *head_page; /* read from head */
466 struct buffer_page *tail_page; /* write to tail */
467 struct buffer_page *commit_page; /* committed pages */
468 struct buffer_page *reader_page;
469 unsigned long lost_events;
470 unsigned long last_overrun;
471 unsigned long nest;
472 local_t entries_bytes;
473 local_t entries;
474 local_t overrun;
475 local_t commit_overrun;
476 local_t dropped_events;
477 local_t committing;
478 local_t commits;
David Brazdil0f672f62019-12-10 10:32:29 +0000479 local_t pages_touched;
480 local_t pages_read;
481 long last_pages_touch;
482 size_t shortest_full;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000483 unsigned long read;
484 unsigned long read_bytes;
485 u64 write_stamp;
486 u64 read_stamp;
487 /* ring buffer pages to update, > 0 to add, < 0 to remove */
488 long nr_pages_to_update;
489 struct list_head new_pages; /* new pages to add */
490 struct work_struct update_pages_work;
491 struct completion update_done;
492
493 struct rb_irq_work irq_work;
494};
495
496struct ring_buffer {
497 unsigned flags;
498 int cpus;
499 atomic_t record_disabled;
500 atomic_t resize_disabled;
501 cpumask_var_t cpumask;
502
503 struct lock_class_key *reader_lock_key;
504
505 struct mutex mutex;
506
507 struct ring_buffer_per_cpu **buffers;
508
509 struct hlist_node node;
510 u64 (*clock)(void);
511
512 struct rb_irq_work irq_work;
513 bool time_stamp_abs;
514};
515
516struct ring_buffer_iter {
517 struct ring_buffer_per_cpu *cpu_buffer;
518 unsigned long head;
519 struct buffer_page *head_page;
520 struct buffer_page *cache_reader_page;
521 unsigned long cache_read;
522 u64 read_stamp;
523};
524
David Brazdil0f672f62019-12-10 10:32:29 +0000525/**
526 * ring_buffer_nr_pages - get the number of buffer pages in the ring buffer
527 * @buffer: The ring_buffer to get the number of pages from
528 * @cpu: The cpu of the ring_buffer to get the number of pages from
529 *
530 * Returns the number of pages used by a per_cpu buffer of the ring buffer.
531 */
532size_t ring_buffer_nr_pages(struct ring_buffer *buffer, int cpu)
533{
534 return buffer->buffers[cpu]->nr_pages;
535}
536
537/**
538 * ring_buffer_nr_pages_dirty - get the number of used pages in the ring buffer
539 * @buffer: The ring_buffer to get the number of pages from
540 * @cpu: The cpu of the ring_buffer to get the number of pages from
541 *
542 * Returns the number of pages that have content in the ring buffer.
543 */
544size_t ring_buffer_nr_dirty_pages(struct ring_buffer *buffer, int cpu)
545{
546 size_t read;
547 size_t cnt;
548
549 read = local_read(&buffer->buffers[cpu]->pages_read);
550 cnt = local_read(&buffer->buffers[cpu]->pages_touched);
551 /* The reader can read an empty page, but not more than that */
552 if (cnt < read) {
553 WARN_ON_ONCE(read > cnt + 1);
554 return 0;
555 }
556
557 return cnt - read;
558}
559
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000560/*
561 * rb_wake_up_waiters - wake up tasks waiting for ring buffer input
562 *
563 * Schedules a delayed work to wake up any task that is blocked on the
564 * ring buffer waiters queue.
565 */
566static void rb_wake_up_waiters(struct irq_work *work)
567{
568 struct rb_irq_work *rbwork = container_of(work, struct rb_irq_work, work);
569
570 wake_up_all(&rbwork->waiters);
571 if (rbwork->wakeup_full) {
572 rbwork->wakeup_full = false;
573 wake_up_all(&rbwork->full_waiters);
574 }
575}
576
577/**
578 * ring_buffer_wait - wait for input to the ring buffer
579 * @buffer: buffer to wait on
580 * @cpu: the cpu buffer to wait on
581 * @full: wait until a full page is available, if @cpu != RING_BUFFER_ALL_CPUS
582 *
583 * If @cpu == RING_BUFFER_ALL_CPUS then the task will wake up as soon
584 * as data is added to any of the @buffer's cpu buffers. Otherwise
585 * it will wait for data to be added to a specific cpu buffer.
586 */
David Brazdil0f672f62019-12-10 10:32:29 +0000587int ring_buffer_wait(struct ring_buffer *buffer, int cpu, int full)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000588{
589 struct ring_buffer_per_cpu *uninitialized_var(cpu_buffer);
590 DEFINE_WAIT(wait);
591 struct rb_irq_work *work;
592 int ret = 0;
593
594 /*
595 * Depending on what the caller is waiting for, either any
596 * data in any cpu buffer, or a specific buffer, put the
597 * caller on the appropriate wait queue.
598 */
599 if (cpu == RING_BUFFER_ALL_CPUS) {
600 work = &buffer->irq_work;
601 /* Full only makes sense on per cpu reads */
David Brazdil0f672f62019-12-10 10:32:29 +0000602 full = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000603 } else {
604 if (!cpumask_test_cpu(cpu, buffer->cpumask))
605 return -ENODEV;
606 cpu_buffer = buffer->buffers[cpu];
607 work = &cpu_buffer->irq_work;
608 }
609
610
611 while (true) {
612 if (full)
613 prepare_to_wait(&work->full_waiters, &wait, TASK_INTERRUPTIBLE);
614 else
615 prepare_to_wait(&work->waiters, &wait, TASK_INTERRUPTIBLE);
616
617 /*
618 * The events can happen in critical sections where
619 * checking a work queue can cause deadlocks.
620 * After adding a task to the queue, this flag is set
621 * only to notify events to try to wake up the queue
622 * using irq_work.
623 *
624 * We don't clear it even if the buffer is no longer
625 * empty. The flag only causes the next event to run
626 * irq_work to do the work queue wake up. The worse
627 * that can happen if we race with !trace_empty() is that
628 * an event will cause an irq_work to try to wake up
629 * an empty queue.
630 *
631 * There's no reason to protect this flag either, as
632 * the work queue and irq_work logic will do the necessary
633 * synchronization for the wake ups. The only thing
634 * that is necessary is that the wake up happens after
635 * a task has been queued. It's OK for spurious wake ups.
636 */
637 if (full)
638 work->full_waiters_pending = true;
639 else
640 work->waiters_pending = true;
641
642 if (signal_pending(current)) {
643 ret = -EINTR;
644 break;
645 }
646
647 if (cpu == RING_BUFFER_ALL_CPUS && !ring_buffer_empty(buffer))
648 break;
649
650 if (cpu != RING_BUFFER_ALL_CPUS &&
651 !ring_buffer_empty_cpu(buffer, cpu)) {
652 unsigned long flags;
653 bool pagebusy;
David Brazdil0f672f62019-12-10 10:32:29 +0000654 size_t nr_pages;
655 size_t dirty;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000656
657 if (!full)
658 break;
659
660 raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
661 pagebusy = cpu_buffer->reader_page == cpu_buffer->commit_page;
David Brazdil0f672f62019-12-10 10:32:29 +0000662 nr_pages = cpu_buffer->nr_pages;
663 dirty = ring_buffer_nr_dirty_pages(buffer, cpu);
664 if (!cpu_buffer->shortest_full ||
665 cpu_buffer->shortest_full < full)
666 cpu_buffer->shortest_full = full;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000667 raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
David Brazdil0f672f62019-12-10 10:32:29 +0000668 if (!pagebusy &&
669 (!nr_pages || (dirty * 100) > full * nr_pages))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000670 break;
671 }
672
673 schedule();
674 }
675
676 if (full)
677 finish_wait(&work->full_waiters, &wait);
678 else
679 finish_wait(&work->waiters, &wait);
680
681 return ret;
682}
683
684/**
685 * ring_buffer_poll_wait - poll on buffer input
686 * @buffer: buffer to wait on
687 * @cpu: the cpu buffer to wait on
688 * @filp: the file descriptor
689 * @poll_table: The poll descriptor
690 *
691 * If @cpu == RING_BUFFER_ALL_CPUS then the task will wake up as soon
692 * as data is added to any of the @buffer's cpu buffers. Otherwise
693 * it will wait for data to be added to a specific cpu buffer.
694 *
695 * Returns EPOLLIN | EPOLLRDNORM if data exists in the buffers,
696 * zero otherwise.
697 */
698__poll_t ring_buffer_poll_wait(struct ring_buffer *buffer, int cpu,
699 struct file *filp, poll_table *poll_table)
700{
701 struct ring_buffer_per_cpu *cpu_buffer;
702 struct rb_irq_work *work;
703
704 if (cpu == RING_BUFFER_ALL_CPUS)
705 work = &buffer->irq_work;
706 else {
707 if (!cpumask_test_cpu(cpu, buffer->cpumask))
708 return -EINVAL;
709
710 cpu_buffer = buffer->buffers[cpu];
711 work = &cpu_buffer->irq_work;
712 }
713
714 poll_wait(filp, &work->waiters, poll_table);
715 work->waiters_pending = true;
716 /*
717 * There's a tight race between setting the waiters_pending and
718 * checking if the ring buffer is empty. Once the waiters_pending bit
719 * is set, the next event will wake the task up, but we can get stuck
720 * if there's only a single event in.
721 *
722 * FIXME: Ideally, we need a memory barrier on the writer side as well,
723 * but adding a memory barrier to all events will cause too much of a
724 * performance hit in the fast path. We only need a memory barrier when
725 * the buffer goes from empty to having content. But as this race is
726 * extremely small, and it's not a problem if another event comes in, we
727 * will fix it later.
728 */
729 smp_mb();
730
731 if ((cpu == RING_BUFFER_ALL_CPUS && !ring_buffer_empty(buffer)) ||
732 (cpu != RING_BUFFER_ALL_CPUS && !ring_buffer_empty_cpu(buffer, cpu)))
733 return EPOLLIN | EPOLLRDNORM;
734 return 0;
735}
736
737/* buffer may be either ring_buffer or ring_buffer_per_cpu */
738#define RB_WARN_ON(b, cond) \
739 ({ \
740 int _____ret = unlikely(cond); \
741 if (_____ret) { \
742 if (__same_type(*(b), struct ring_buffer_per_cpu)) { \
743 struct ring_buffer_per_cpu *__b = \
744 (void *)b; \
745 atomic_inc(&__b->buffer->record_disabled); \
746 } else \
747 atomic_inc(&b->record_disabled); \
748 WARN_ON(1); \
749 } \
750 _____ret; \
751 })
752
753/* Up this if you want to test the TIME_EXTENTS and normalization */
754#define DEBUG_SHIFT 0
755
756static inline u64 rb_time_stamp(struct ring_buffer *buffer)
757{
758 /* shift to debug/test normalization and TIME_EXTENTS */
759 return buffer->clock() << DEBUG_SHIFT;
760}
761
762u64 ring_buffer_time_stamp(struct ring_buffer *buffer, int cpu)
763{
764 u64 time;
765
766 preempt_disable_notrace();
767 time = rb_time_stamp(buffer);
David Brazdil0f672f62019-12-10 10:32:29 +0000768 preempt_enable_notrace();
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000769
770 return time;
771}
772EXPORT_SYMBOL_GPL(ring_buffer_time_stamp);
773
774void ring_buffer_normalize_time_stamp(struct ring_buffer *buffer,
775 int cpu, u64 *ts)
776{
777 /* Just stupid testing the normalize function and deltas */
778 *ts >>= DEBUG_SHIFT;
779}
780EXPORT_SYMBOL_GPL(ring_buffer_normalize_time_stamp);
781
782/*
783 * Making the ring buffer lockless makes things tricky.
784 * Although writes only happen on the CPU that they are on,
785 * and they only need to worry about interrupts. Reads can
786 * happen on any CPU.
787 *
788 * The reader page is always off the ring buffer, but when the
789 * reader finishes with a page, it needs to swap its page with
790 * a new one from the buffer. The reader needs to take from
791 * the head (writes go to the tail). But if a writer is in overwrite
792 * mode and wraps, it must push the head page forward.
793 *
794 * Here lies the problem.
795 *
796 * The reader must be careful to replace only the head page, and
797 * not another one. As described at the top of the file in the
798 * ASCII art, the reader sets its old page to point to the next
799 * page after head. It then sets the page after head to point to
800 * the old reader page. But if the writer moves the head page
801 * during this operation, the reader could end up with the tail.
802 *
803 * We use cmpxchg to help prevent this race. We also do something
804 * special with the page before head. We set the LSB to 1.
805 *
806 * When the writer must push the page forward, it will clear the
807 * bit that points to the head page, move the head, and then set
808 * the bit that points to the new head page.
809 *
810 * We also don't want an interrupt coming in and moving the head
811 * page on another writer. Thus we use the second LSB to catch
812 * that too. Thus:
813 *
814 * head->list->prev->next bit 1 bit 0
815 * ------- -------
816 * Normal page 0 0
817 * Points to head page 0 1
818 * New head page 1 0
819 *
820 * Note we can not trust the prev pointer of the head page, because:
821 *
822 * +----+ +-----+ +-----+
823 * | |------>| T |---X--->| N |
824 * | |<------| | | |
825 * +----+ +-----+ +-----+
826 * ^ ^ |
827 * | +-----+ | |
828 * +----------| R |----------+ |
829 * | |<-----------+
830 * +-----+
831 *
832 * Key: ---X--> HEAD flag set in pointer
833 * T Tail page
834 * R Reader page
835 * N Next page
836 *
837 * (see __rb_reserve_next() to see where this happens)
838 *
839 * What the above shows is that the reader just swapped out
840 * the reader page with a page in the buffer, but before it
841 * could make the new header point back to the new page added
842 * it was preempted by a writer. The writer moved forward onto
843 * the new page added by the reader and is about to move forward
844 * again.
845 *
846 * You can see, it is legitimate for the previous pointer of
847 * the head (or any page) not to point back to itself. But only
848 * temporarily.
849 */
850
851#define RB_PAGE_NORMAL 0UL
852#define RB_PAGE_HEAD 1UL
853#define RB_PAGE_UPDATE 2UL
854
855
856#define RB_FLAG_MASK 3UL
857
858/* PAGE_MOVED is not part of the mask */
859#define RB_PAGE_MOVED 4UL
860
861/*
862 * rb_list_head - remove any bit
863 */
864static struct list_head *rb_list_head(struct list_head *list)
865{
866 unsigned long val = (unsigned long)list;
867
868 return (struct list_head *)(val & ~RB_FLAG_MASK);
869}
870
871/*
872 * rb_is_head_page - test if the given page is the head page
873 *
874 * Because the reader may move the head_page pointer, we can
875 * not trust what the head page is (it may be pointing to
876 * the reader page). But if the next page is a header page,
877 * its flags will be non zero.
878 */
879static inline int
880rb_is_head_page(struct ring_buffer_per_cpu *cpu_buffer,
881 struct buffer_page *page, struct list_head *list)
882{
883 unsigned long val;
884
885 val = (unsigned long)list->next;
886
887 if ((val & ~RB_FLAG_MASK) != (unsigned long)&page->list)
888 return RB_PAGE_MOVED;
889
890 return val & RB_FLAG_MASK;
891}
892
893/*
894 * rb_is_reader_page
895 *
896 * The unique thing about the reader page, is that, if the
897 * writer is ever on it, the previous pointer never points
898 * back to the reader page.
899 */
900static bool rb_is_reader_page(struct buffer_page *page)
901{
902 struct list_head *list = page->list.prev;
903
904 return rb_list_head(list->next) != &page->list;
905}
906
907/*
908 * rb_set_list_to_head - set a list_head to be pointing to head.
909 */
910static void rb_set_list_to_head(struct ring_buffer_per_cpu *cpu_buffer,
911 struct list_head *list)
912{
913 unsigned long *ptr;
914
915 ptr = (unsigned long *)&list->next;
916 *ptr |= RB_PAGE_HEAD;
917 *ptr &= ~RB_PAGE_UPDATE;
918}
919
920/*
921 * rb_head_page_activate - sets up head page
922 */
923static void rb_head_page_activate(struct ring_buffer_per_cpu *cpu_buffer)
924{
925 struct buffer_page *head;
926
927 head = cpu_buffer->head_page;
928 if (!head)
929 return;
930
931 /*
932 * Set the previous list pointer to have the HEAD flag.
933 */
934 rb_set_list_to_head(cpu_buffer, head->list.prev);
935}
936
937static void rb_list_head_clear(struct list_head *list)
938{
939 unsigned long *ptr = (unsigned long *)&list->next;
940
941 *ptr &= ~RB_FLAG_MASK;
942}
943
944/*
945 * rb_head_page_deactivate - clears head page ptr (for free list)
946 */
947static void
948rb_head_page_deactivate(struct ring_buffer_per_cpu *cpu_buffer)
949{
950 struct list_head *hd;
951
952 /* Go through the whole list and clear any pointers found. */
953 rb_list_head_clear(cpu_buffer->pages);
954
955 list_for_each(hd, cpu_buffer->pages)
956 rb_list_head_clear(hd);
957}
958
959static int rb_head_page_set(struct ring_buffer_per_cpu *cpu_buffer,
960 struct buffer_page *head,
961 struct buffer_page *prev,
962 int old_flag, int new_flag)
963{
964 struct list_head *list;
965 unsigned long val = (unsigned long)&head->list;
966 unsigned long ret;
967
968 list = &prev->list;
969
970 val &= ~RB_FLAG_MASK;
971
972 ret = cmpxchg((unsigned long *)&list->next,
973 val | old_flag, val | new_flag);
974
975 /* check if the reader took the page */
976 if ((ret & ~RB_FLAG_MASK) != val)
977 return RB_PAGE_MOVED;
978
979 return ret & RB_FLAG_MASK;
980}
981
982static int rb_head_page_set_update(struct ring_buffer_per_cpu *cpu_buffer,
983 struct buffer_page *head,
984 struct buffer_page *prev,
985 int old_flag)
986{
987 return rb_head_page_set(cpu_buffer, head, prev,
988 old_flag, RB_PAGE_UPDATE);
989}
990
991static int rb_head_page_set_head(struct ring_buffer_per_cpu *cpu_buffer,
992 struct buffer_page *head,
993 struct buffer_page *prev,
994 int old_flag)
995{
996 return rb_head_page_set(cpu_buffer, head, prev,
997 old_flag, RB_PAGE_HEAD);
998}
999
1000static int rb_head_page_set_normal(struct ring_buffer_per_cpu *cpu_buffer,
1001 struct buffer_page *head,
1002 struct buffer_page *prev,
1003 int old_flag)
1004{
1005 return rb_head_page_set(cpu_buffer, head, prev,
1006 old_flag, RB_PAGE_NORMAL);
1007}
1008
1009static inline void rb_inc_page(struct ring_buffer_per_cpu *cpu_buffer,
1010 struct buffer_page **bpage)
1011{
1012 struct list_head *p = rb_list_head((*bpage)->list.next);
1013
1014 *bpage = list_entry(p, struct buffer_page, list);
1015}
1016
1017static struct buffer_page *
1018rb_set_head_page(struct ring_buffer_per_cpu *cpu_buffer)
1019{
1020 struct buffer_page *head;
1021 struct buffer_page *page;
1022 struct list_head *list;
1023 int i;
1024
1025 if (RB_WARN_ON(cpu_buffer, !cpu_buffer->head_page))
1026 return NULL;
1027
1028 /* sanity check */
1029 list = cpu_buffer->pages;
1030 if (RB_WARN_ON(cpu_buffer, rb_list_head(list->prev->next) != list))
1031 return NULL;
1032
1033 page = head = cpu_buffer->head_page;
1034 /*
1035 * It is possible that the writer moves the header behind
1036 * where we started, and we miss in one loop.
1037 * A second loop should grab the header, but we'll do
1038 * three loops just because I'm paranoid.
1039 */
1040 for (i = 0; i < 3; i++) {
1041 do {
1042 if (rb_is_head_page(cpu_buffer, page, page->list.prev)) {
1043 cpu_buffer->head_page = page;
1044 return page;
1045 }
1046 rb_inc_page(cpu_buffer, &page);
1047 } while (page != head);
1048 }
1049
1050 RB_WARN_ON(cpu_buffer, 1);
1051
1052 return NULL;
1053}
1054
1055static int rb_head_page_replace(struct buffer_page *old,
1056 struct buffer_page *new)
1057{
1058 unsigned long *ptr = (unsigned long *)&old->list.prev->next;
1059 unsigned long val;
1060 unsigned long ret;
1061
1062 val = *ptr & ~RB_FLAG_MASK;
1063 val |= RB_PAGE_HEAD;
1064
1065 ret = cmpxchg(ptr, val, (unsigned long)&new->list);
1066
1067 return ret == val;
1068}
1069
1070/*
1071 * rb_tail_page_update - move the tail page forward
1072 */
1073static void rb_tail_page_update(struct ring_buffer_per_cpu *cpu_buffer,
1074 struct buffer_page *tail_page,
1075 struct buffer_page *next_page)
1076{
1077 unsigned long old_entries;
1078 unsigned long old_write;
1079
1080 /*
1081 * The tail page now needs to be moved forward.
1082 *
1083 * We need to reset the tail page, but without messing
1084 * with possible erasing of data brought in by interrupts
1085 * that have moved the tail page and are currently on it.
1086 *
1087 * We add a counter to the write field to denote this.
1088 */
1089 old_write = local_add_return(RB_WRITE_INTCNT, &next_page->write);
1090 old_entries = local_add_return(RB_WRITE_INTCNT, &next_page->entries);
1091
David Brazdil0f672f62019-12-10 10:32:29 +00001092 local_inc(&cpu_buffer->pages_touched);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001093 /*
1094 * Just make sure we have seen our old_write and synchronize
1095 * with any interrupts that come in.
1096 */
1097 barrier();
1098
1099 /*
1100 * If the tail page is still the same as what we think
1101 * it is, then it is up to us to update the tail
1102 * pointer.
1103 */
1104 if (tail_page == READ_ONCE(cpu_buffer->tail_page)) {
1105 /* Zero the write counter */
1106 unsigned long val = old_write & ~RB_WRITE_MASK;
1107 unsigned long eval = old_entries & ~RB_WRITE_MASK;
1108
1109 /*
1110 * This will only succeed if an interrupt did
1111 * not come in and change it. In which case, we
1112 * do not want to modify it.
1113 *
1114 * We add (void) to let the compiler know that we do not care
1115 * about the return value of these functions. We use the
1116 * cmpxchg to only update if an interrupt did not already
1117 * do it for us. If the cmpxchg fails, we don't care.
1118 */
1119 (void)local_cmpxchg(&next_page->write, old_write, val);
1120 (void)local_cmpxchg(&next_page->entries, old_entries, eval);
1121
1122 /*
1123 * No need to worry about races with clearing out the commit.
1124 * it only can increment when a commit takes place. But that
1125 * only happens in the outer most nested commit.
1126 */
1127 local_set(&next_page->page->commit, 0);
1128
1129 /* Again, either we update tail_page or an interrupt does */
1130 (void)cmpxchg(&cpu_buffer->tail_page, tail_page, next_page);
1131 }
1132}
1133
1134static int rb_check_bpage(struct ring_buffer_per_cpu *cpu_buffer,
1135 struct buffer_page *bpage)
1136{
1137 unsigned long val = (unsigned long)bpage;
1138
1139 if (RB_WARN_ON(cpu_buffer, val & RB_FLAG_MASK))
1140 return 1;
1141
1142 return 0;
1143}
1144
1145/**
1146 * rb_check_list - make sure a pointer to a list has the last bits zero
1147 */
1148static int rb_check_list(struct ring_buffer_per_cpu *cpu_buffer,
1149 struct list_head *list)
1150{
1151 if (RB_WARN_ON(cpu_buffer, rb_list_head(list->prev) != list->prev))
1152 return 1;
1153 if (RB_WARN_ON(cpu_buffer, rb_list_head(list->next) != list->next))
1154 return 1;
1155 return 0;
1156}
1157
1158/**
1159 * rb_check_pages - integrity check of buffer pages
1160 * @cpu_buffer: CPU buffer with pages to test
1161 *
1162 * As a safety measure we check to make sure the data pages have not
1163 * been corrupted.
1164 */
1165static int rb_check_pages(struct ring_buffer_per_cpu *cpu_buffer)
1166{
1167 struct list_head *head = cpu_buffer->pages;
1168 struct buffer_page *bpage, *tmp;
1169
1170 /* Reset the head page if it exists */
1171 if (cpu_buffer->head_page)
1172 rb_set_head_page(cpu_buffer);
1173
1174 rb_head_page_deactivate(cpu_buffer);
1175
1176 if (RB_WARN_ON(cpu_buffer, head->next->prev != head))
1177 return -1;
1178 if (RB_WARN_ON(cpu_buffer, head->prev->next != head))
1179 return -1;
1180
1181 if (rb_check_list(cpu_buffer, head))
1182 return -1;
1183
1184 list_for_each_entry_safe(bpage, tmp, head, list) {
1185 if (RB_WARN_ON(cpu_buffer,
1186 bpage->list.next->prev != &bpage->list))
1187 return -1;
1188 if (RB_WARN_ON(cpu_buffer,
1189 bpage->list.prev->next != &bpage->list))
1190 return -1;
1191 if (rb_check_list(cpu_buffer, &bpage->list))
1192 return -1;
1193 }
1194
1195 rb_head_page_activate(cpu_buffer);
1196
1197 return 0;
1198}
1199
1200static int __rb_allocate_pages(long nr_pages, struct list_head *pages, int cpu)
1201{
1202 struct buffer_page *bpage, *tmp;
1203 bool user_thread = current->mm != NULL;
1204 gfp_t mflags;
1205 long i;
1206
1207 /*
1208 * Check if the available memory is there first.
1209 * Note, si_mem_available() only gives us a rough estimate of available
1210 * memory. It may not be accurate. But we don't care, we just want
1211 * to prevent doing any allocation when it is obvious that it is
1212 * not going to succeed.
1213 */
1214 i = si_mem_available();
1215 if (i < nr_pages)
1216 return -ENOMEM;
1217
1218 /*
1219 * __GFP_RETRY_MAYFAIL flag makes sure that the allocation fails
1220 * gracefully without invoking oom-killer and the system is not
1221 * destabilized.
1222 */
1223 mflags = GFP_KERNEL | __GFP_RETRY_MAYFAIL;
1224
1225 /*
1226 * If a user thread allocates too much, and si_mem_available()
1227 * reports there's enough memory, even though there is not.
1228 * Make sure the OOM killer kills this thread. This can happen
1229 * even with RETRY_MAYFAIL because another task may be doing
1230 * an allocation after this task has taken all memory.
1231 * This is the task the OOM killer needs to take out during this
1232 * loop, even if it was triggered by an allocation somewhere else.
1233 */
1234 if (user_thread)
1235 set_current_oom_origin();
1236 for (i = 0; i < nr_pages; i++) {
1237 struct page *page;
1238
1239 bpage = kzalloc_node(ALIGN(sizeof(*bpage), cache_line_size()),
1240 mflags, cpu_to_node(cpu));
1241 if (!bpage)
1242 goto free_pages;
1243
1244 list_add(&bpage->list, pages);
1245
1246 page = alloc_pages_node(cpu_to_node(cpu), mflags, 0);
1247 if (!page)
1248 goto free_pages;
1249 bpage->page = page_address(page);
1250 rb_init_page(bpage->page);
1251
1252 if (user_thread && fatal_signal_pending(current))
1253 goto free_pages;
1254 }
1255 if (user_thread)
1256 clear_current_oom_origin();
1257
1258 return 0;
1259
1260free_pages:
1261 list_for_each_entry_safe(bpage, tmp, pages, list) {
1262 list_del_init(&bpage->list);
1263 free_buffer_page(bpage);
1264 }
1265 if (user_thread)
1266 clear_current_oom_origin();
1267
1268 return -ENOMEM;
1269}
1270
1271static int rb_allocate_pages(struct ring_buffer_per_cpu *cpu_buffer,
1272 unsigned long nr_pages)
1273{
1274 LIST_HEAD(pages);
1275
1276 WARN_ON(!nr_pages);
1277
1278 if (__rb_allocate_pages(nr_pages, &pages, cpu_buffer->cpu))
1279 return -ENOMEM;
1280
1281 /*
1282 * The ring buffer page list is a circular list that does not
1283 * start and end with a list head. All page list items point to
1284 * other pages.
1285 */
1286 cpu_buffer->pages = pages.next;
1287 list_del(&pages);
1288
1289 cpu_buffer->nr_pages = nr_pages;
1290
1291 rb_check_pages(cpu_buffer);
1292
1293 return 0;
1294}
1295
1296static struct ring_buffer_per_cpu *
1297rb_allocate_cpu_buffer(struct ring_buffer *buffer, long nr_pages, int cpu)
1298{
1299 struct ring_buffer_per_cpu *cpu_buffer;
1300 struct buffer_page *bpage;
1301 struct page *page;
1302 int ret;
1303
1304 cpu_buffer = kzalloc_node(ALIGN(sizeof(*cpu_buffer), cache_line_size()),
1305 GFP_KERNEL, cpu_to_node(cpu));
1306 if (!cpu_buffer)
1307 return NULL;
1308
1309 cpu_buffer->cpu = cpu;
1310 cpu_buffer->buffer = buffer;
1311 raw_spin_lock_init(&cpu_buffer->reader_lock);
1312 lockdep_set_class(&cpu_buffer->reader_lock, buffer->reader_lock_key);
1313 cpu_buffer->lock = (arch_spinlock_t)__ARCH_SPIN_LOCK_UNLOCKED;
1314 INIT_WORK(&cpu_buffer->update_pages_work, update_pages_handler);
1315 init_completion(&cpu_buffer->update_done);
1316 init_irq_work(&cpu_buffer->irq_work.work, rb_wake_up_waiters);
1317 init_waitqueue_head(&cpu_buffer->irq_work.waiters);
1318 init_waitqueue_head(&cpu_buffer->irq_work.full_waiters);
1319
1320 bpage = kzalloc_node(ALIGN(sizeof(*bpage), cache_line_size()),
1321 GFP_KERNEL, cpu_to_node(cpu));
1322 if (!bpage)
1323 goto fail_free_buffer;
1324
1325 rb_check_bpage(cpu_buffer, bpage);
1326
1327 cpu_buffer->reader_page = bpage;
1328 page = alloc_pages_node(cpu_to_node(cpu), GFP_KERNEL, 0);
1329 if (!page)
1330 goto fail_free_reader;
1331 bpage->page = page_address(page);
1332 rb_init_page(bpage->page);
1333
1334 INIT_LIST_HEAD(&cpu_buffer->reader_page->list);
1335 INIT_LIST_HEAD(&cpu_buffer->new_pages);
1336
1337 ret = rb_allocate_pages(cpu_buffer, nr_pages);
1338 if (ret < 0)
1339 goto fail_free_reader;
1340
1341 cpu_buffer->head_page
1342 = list_entry(cpu_buffer->pages, struct buffer_page, list);
1343 cpu_buffer->tail_page = cpu_buffer->commit_page = cpu_buffer->head_page;
1344
1345 rb_head_page_activate(cpu_buffer);
1346
1347 return cpu_buffer;
1348
1349 fail_free_reader:
1350 free_buffer_page(cpu_buffer->reader_page);
1351
1352 fail_free_buffer:
1353 kfree(cpu_buffer);
1354 return NULL;
1355}
1356
1357static void rb_free_cpu_buffer(struct ring_buffer_per_cpu *cpu_buffer)
1358{
1359 struct list_head *head = cpu_buffer->pages;
1360 struct buffer_page *bpage, *tmp;
1361
1362 free_buffer_page(cpu_buffer->reader_page);
1363
1364 rb_head_page_deactivate(cpu_buffer);
1365
1366 if (head) {
1367 list_for_each_entry_safe(bpage, tmp, head, list) {
1368 list_del_init(&bpage->list);
1369 free_buffer_page(bpage);
1370 }
1371 bpage = list_entry(head, struct buffer_page, list);
1372 free_buffer_page(bpage);
1373 }
1374
1375 kfree(cpu_buffer);
1376}
1377
1378/**
1379 * __ring_buffer_alloc - allocate a new ring_buffer
1380 * @size: the size in bytes per cpu that is needed.
1381 * @flags: attributes to set for the ring buffer.
1382 *
1383 * Currently the only flag that is available is the RB_FL_OVERWRITE
1384 * flag. This flag means that the buffer will overwrite old data
1385 * when the buffer wraps. If this flag is not set, the buffer will
1386 * drop data when the tail hits the head.
1387 */
1388struct ring_buffer *__ring_buffer_alloc(unsigned long size, unsigned flags,
1389 struct lock_class_key *key)
1390{
1391 struct ring_buffer *buffer;
1392 long nr_pages;
1393 int bsize;
1394 int cpu;
1395 int ret;
1396
1397 /* keep it in its own cache line */
1398 buffer = kzalloc(ALIGN(sizeof(*buffer), cache_line_size()),
1399 GFP_KERNEL);
1400 if (!buffer)
1401 return NULL;
1402
1403 if (!zalloc_cpumask_var(&buffer->cpumask, GFP_KERNEL))
1404 goto fail_free_buffer;
1405
1406 nr_pages = DIV_ROUND_UP(size, BUF_PAGE_SIZE);
1407 buffer->flags = flags;
1408 buffer->clock = trace_clock_local;
1409 buffer->reader_lock_key = key;
1410
1411 init_irq_work(&buffer->irq_work.work, rb_wake_up_waiters);
1412 init_waitqueue_head(&buffer->irq_work.waiters);
1413
1414 /* need at least two pages */
1415 if (nr_pages < 2)
1416 nr_pages = 2;
1417
1418 buffer->cpus = nr_cpu_ids;
1419
1420 bsize = sizeof(void *) * nr_cpu_ids;
1421 buffer->buffers = kzalloc(ALIGN(bsize, cache_line_size()),
1422 GFP_KERNEL);
1423 if (!buffer->buffers)
1424 goto fail_free_cpumask;
1425
1426 cpu = raw_smp_processor_id();
1427 cpumask_set_cpu(cpu, buffer->cpumask);
1428 buffer->buffers[cpu] = rb_allocate_cpu_buffer(buffer, nr_pages, cpu);
1429 if (!buffer->buffers[cpu])
1430 goto fail_free_buffers;
1431
1432 ret = cpuhp_state_add_instance(CPUHP_TRACE_RB_PREPARE, &buffer->node);
1433 if (ret < 0)
1434 goto fail_free_buffers;
1435
1436 mutex_init(&buffer->mutex);
1437
1438 return buffer;
1439
1440 fail_free_buffers:
1441 for_each_buffer_cpu(buffer, cpu) {
1442 if (buffer->buffers[cpu])
1443 rb_free_cpu_buffer(buffer->buffers[cpu]);
1444 }
1445 kfree(buffer->buffers);
1446
1447 fail_free_cpumask:
1448 free_cpumask_var(buffer->cpumask);
1449
1450 fail_free_buffer:
1451 kfree(buffer);
1452 return NULL;
1453}
1454EXPORT_SYMBOL_GPL(__ring_buffer_alloc);
1455
1456/**
1457 * ring_buffer_free - free a ring buffer.
1458 * @buffer: the buffer to free.
1459 */
1460void
1461ring_buffer_free(struct ring_buffer *buffer)
1462{
1463 int cpu;
1464
1465 cpuhp_state_remove_instance(CPUHP_TRACE_RB_PREPARE, &buffer->node);
1466
1467 for_each_buffer_cpu(buffer, cpu)
1468 rb_free_cpu_buffer(buffer->buffers[cpu]);
1469
1470 kfree(buffer->buffers);
1471 free_cpumask_var(buffer->cpumask);
1472
1473 kfree(buffer);
1474}
1475EXPORT_SYMBOL_GPL(ring_buffer_free);
1476
1477void ring_buffer_set_clock(struct ring_buffer *buffer,
1478 u64 (*clock)(void))
1479{
1480 buffer->clock = clock;
1481}
1482
1483void ring_buffer_set_time_stamp_abs(struct ring_buffer *buffer, bool abs)
1484{
1485 buffer->time_stamp_abs = abs;
1486}
1487
1488bool ring_buffer_time_stamp_abs(struct ring_buffer *buffer)
1489{
1490 return buffer->time_stamp_abs;
1491}
1492
1493static void rb_reset_cpu(struct ring_buffer_per_cpu *cpu_buffer);
1494
1495static inline unsigned long rb_page_entries(struct buffer_page *bpage)
1496{
1497 return local_read(&bpage->entries) & RB_WRITE_MASK;
1498}
1499
1500static inline unsigned long rb_page_write(struct buffer_page *bpage)
1501{
1502 return local_read(&bpage->write) & RB_WRITE_MASK;
1503}
1504
1505static int
1506rb_remove_pages(struct ring_buffer_per_cpu *cpu_buffer, unsigned long nr_pages)
1507{
1508 struct list_head *tail_page, *to_remove, *next_page;
1509 struct buffer_page *to_remove_page, *tmp_iter_page;
1510 struct buffer_page *last_page, *first_page;
1511 unsigned long nr_removed;
1512 unsigned long head_bit;
1513 int page_entries;
1514
1515 head_bit = 0;
1516
1517 raw_spin_lock_irq(&cpu_buffer->reader_lock);
1518 atomic_inc(&cpu_buffer->record_disabled);
1519 /*
1520 * We don't race with the readers since we have acquired the reader
1521 * lock. We also don't race with writers after disabling recording.
1522 * This makes it easy to figure out the first and the last page to be
1523 * removed from the list. We unlink all the pages in between including
1524 * the first and last pages. This is done in a busy loop so that we
1525 * lose the least number of traces.
1526 * The pages are freed after we restart recording and unlock readers.
1527 */
1528 tail_page = &cpu_buffer->tail_page->list;
1529
1530 /*
1531 * tail page might be on reader page, we remove the next page
1532 * from the ring buffer
1533 */
1534 if (cpu_buffer->tail_page == cpu_buffer->reader_page)
1535 tail_page = rb_list_head(tail_page->next);
1536 to_remove = tail_page;
1537
1538 /* start of pages to remove */
1539 first_page = list_entry(rb_list_head(to_remove->next),
1540 struct buffer_page, list);
1541
1542 for (nr_removed = 0; nr_removed < nr_pages; nr_removed++) {
1543 to_remove = rb_list_head(to_remove)->next;
1544 head_bit |= (unsigned long)to_remove & RB_PAGE_HEAD;
1545 }
1546
1547 next_page = rb_list_head(to_remove)->next;
1548
1549 /*
1550 * Now we remove all pages between tail_page and next_page.
1551 * Make sure that we have head_bit value preserved for the
1552 * next page
1553 */
1554 tail_page->next = (struct list_head *)((unsigned long)next_page |
1555 head_bit);
1556 next_page = rb_list_head(next_page);
1557 next_page->prev = tail_page;
1558
1559 /* make sure pages points to a valid page in the ring buffer */
1560 cpu_buffer->pages = next_page;
1561
1562 /* update head page */
1563 if (head_bit)
1564 cpu_buffer->head_page = list_entry(next_page,
1565 struct buffer_page, list);
1566
1567 /*
1568 * change read pointer to make sure any read iterators reset
1569 * themselves
1570 */
1571 cpu_buffer->read = 0;
1572
1573 /* pages are removed, resume tracing and then free the pages */
1574 atomic_dec(&cpu_buffer->record_disabled);
1575 raw_spin_unlock_irq(&cpu_buffer->reader_lock);
1576
1577 RB_WARN_ON(cpu_buffer, list_empty(cpu_buffer->pages));
1578
1579 /* last buffer page to remove */
1580 last_page = list_entry(rb_list_head(to_remove), struct buffer_page,
1581 list);
1582 tmp_iter_page = first_page;
1583
1584 do {
1585 cond_resched();
1586
1587 to_remove_page = tmp_iter_page;
1588 rb_inc_page(cpu_buffer, &tmp_iter_page);
1589
1590 /* update the counters */
1591 page_entries = rb_page_entries(to_remove_page);
1592 if (page_entries) {
1593 /*
1594 * If something was added to this page, it was full
1595 * since it is not the tail page. So we deduct the
1596 * bytes consumed in ring buffer from here.
1597 * Increment overrun to account for the lost events.
1598 */
1599 local_add(page_entries, &cpu_buffer->overrun);
1600 local_sub(BUF_PAGE_SIZE, &cpu_buffer->entries_bytes);
1601 }
1602
1603 /*
1604 * We have already removed references to this list item, just
1605 * free up the buffer_page and its page
1606 */
1607 free_buffer_page(to_remove_page);
1608 nr_removed--;
1609
1610 } while (to_remove_page != last_page);
1611
1612 RB_WARN_ON(cpu_buffer, nr_removed);
1613
1614 return nr_removed == 0;
1615}
1616
1617static int
1618rb_insert_pages(struct ring_buffer_per_cpu *cpu_buffer)
1619{
1620 struct list_head *pages = &cpu_buffer->new_pages;
1621 int retries, success;
1622
1623 raw_spin_lock_irq(&cpu_buffer->reader_lock);
1624 /*
1625 * We are holding the reader lock, so the reader page won't be swapped
1626 * in the ring buffer. Now we are racing with the writer trying to
1627 * move head page and the tail page.
1628 * We are going to adapt the reader page update process where:
1629 * 1. We first splice the start and end of list of new pages between
1630 * the head page and its previous page.
1631 * 2. We cmpxchg the prev_page->next to point from head page to the
1632 * start of new pages list.
1633 * 3. Finally, we update the head->prev to the end of new list.
1634 *
1635 * We will try this process 10 times, to make sure that we don't keep
1636 * spinning.
1637 */
1638 retries = 10;
1639 success = 0;
1640 while (retries--) {
1641 struct list_head *head_page, *prev_page, *r;
1642 struct list_head *last_page, *first_page;
1643 struct list_head *head_page_with_bit;
1644
1645 head_page = &rb_set_head_page(cpu_buffer)->list;
1646 if (!head_page)
1647 break;
1648 prev_page = head_page->prev;
1649
1650 first_page = pages->next;
1651 last_page = pages->prev;
1652
1653 head_page_with_bit = (struct list_head *)
1654 ((unsigned long)head_page | RB_PAGE_HEAD);
1655
1656 last_page->next = head_page_with_bit;
1657 first_page->prev = prev_page;
1658
1659 r = cmpxchg(&prev_page->next, head_page_with_bit, first_page);
1660
1661 if (r == head_page_with_bit) {
1662 /*
1663 * yay, we replaced the page pointer to our new list,
1664 * now, we just have to update to head page's prev
1665 * pointer to point to end of list
1666 */
1667 head_page->prev = last_page;
1668 success = 1;
1669 break;
1670 }
1671 }
1672
1673 if (success)
1674 INIT_LIST_HEAD(pages);
1675 /*
1676 * If we weren't successful in adding in new pages, warn and stop
1677 * tracing
1678 */
1679 RB_WARN_ON(cpu_buffer, !success);
1680 raw_spin_unlock_irq(&cpu_buffer->reader_lock);
1681
1682 /* free pages if they weren't inserted */
1683 if (!success) {
1684 struct buffer_page *bpage, *tmp;
1685 list_for_each_entry_safe(bpage, tmp, &cpu_buffer->new_pages,
1686 list) {
1687 list_del_init(&bpage->list);
1688 free_buffer_page(bpage);
1689 }
1690 }
1691 return success;
1692}
1693
1694static void rb_update_pages(struct ring_buffer_per_cpu *cpu_buffer)
1695{
1696 int success;
1697
1698 if (cpu_buffer->nr_pages_to_update > 0)
1699 success = rb_insert_pages(cpu_buffer);
1700 else
1701 success = rb_remove_pages(cpu_buffer,
1702 -cpu_buffer->nr_pages_to_update);
1703
1704 if (success)
1705 cpu_buffer->nr_pages += cpu_buffer->nr_pages_to_update;
1706}
1707
1708static void update_pages_handler(struct work_struct *work)
1709{
1710 struct ring_buffer_per_cpu *cpu_buffer = container_of(work,
1711 struct ring_buffer_per_cpu, update_pages_work);
1712 rb_update_pages(cpu_buffer);
1713 complete(&cpu_buffer->update_done);
1714}
1715
1716/**
1717 * ring_buffer_resize - resize the ring buffer
1718 * @buffer: the buffer to resize.
1719 * @size: the new size.
1720 * @cpu_id: the cpu buffer to resize
1721 *
1722 * Minimum size is 2 * BUF_PAGE_SIZE.
1723 *
1724 * Returns 0 on success and < 0 on failure.
1725 */
1726int ring_buffer_resize(struct ring_buffer *buffer, unsigned long size,
1727 int cpu_id)
1728{
1729 struct ring_buffer_per_cpu *cpu_buffer;
1730 unsigned long nr_pages;
Olivier Deprez0e641232021-09-23 10:07:05 +02001731 int cpu, err;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001732
1733 /*
1734 * Always succeed at resizing a non-existent buffer:
1735 */
1736 if (!buffer)
Olivier Deprez0e641232021-09-23 10:07:05 +02001737 return 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001738
1739 /* Make sure the requested buffer exists */
1740 if (cpu_id != RING_BUFFER_ALL_CPUS &&
1741 !cpumask_test_cpu(cpu_id, buffer->cpumask))
Olivier Deprez0e641232021-09-23 10:07:05 +02001742 return 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001743
1744 nr_pages = DIV_ROUND_UP(size, BUF_PAGE_SIZE);
1745
1746 /* we need a minimum of two pages */
1747 if (nr_pages < 2)
1748 nr_pages = 2;
1749
1750 size = nr_pages * BUF_PAGE_SIZE;
1751
1752 /*
1753 * Don't succeed if resizing is disabled, as a reader might be
1754 * manipulating the ring buffer and is expecting a sane state while
1755 * this is true.
1756 */
1757 if (atomic_read(&buffer->resize_disabled))
1758 return -EBUSY;
1759
1760 /* prevent another thread from changing buffer sizes */
1761 mutex_lock(&buffer->mutex);
1762
1763 if (cpu_id == RING_BUFFER_ALL_CPUS) {
1764 /* calculate the pages to update */
1765 for_each_buffer_cpu(buffer, cpu) {
1766 cpu_buffer = buffer->buffers[cpu];
1767
1768 cpu_buffer->nr_pages_to_update = nr_pages -
1769 cpu_buffer->nr_pages;
1770 /*
1771 * nothing more to do for removing pages or no update
1772 */
1773 if (cpu_buffer->nr_pages_to_update <= 0)
1774 continue;
1775 /*
1776 * to add pages, make sure all new pages can be
1777 * allocated without receiving ENOMEM
1778 */
1779 INIT_LIST_HEAD(&cpu_buffer->new_pages);
1780 if (__rb_allocate_pages(cpu_buffer->nr_pages_to_update,
1781 &cpu_buffer->new_pages, cpu)) {
1782 /* not enough memory for new pages */
1783 err = -ENOMEM;
1784 goto out_err;
1785 }
1786 }
1787
1788 get_online_cpus();
1789 /*
1790 * Fire off all the required work handlers
1791 * We can't schedule on offline CPUs, but it's not necessary
1792 * since we can change their buffer sizes without any race.
1793 */
1794 for_each_buffer_cpu(buffer, cpu) {
1795 cpu_buffer = buffer->buffers[cpu];
1796 if (!cpu_buffer->nr_pages_to_update)
1797 continue;
1798
1799 /* Can't run something on an offline CPU. */
1800 if (!cpu_online(cpu)) {
1801 rb_update_pages(cpu_buffer);
1802 cpu_buffer->nr_pages_to_update = 0;
1803 } else {
1804 schedule_work_on(cpu,
1805 &cpu_buffer->update_pages_work);
1806 }
1807 }
1808
1809 /* wait for all the updates to complete */
1810 for_each_buffer_cpu(buffer, cpu) {
1811 cpu_buffer = buffer->buffers[cpu];
1812 if (!cpu_buffer->nr_pages_to_update)
1813 continue;
1814
1815 if (cpu_online(cpu))
1816 wait_for_completion(&cpu_buffer->update_done);
1817 cpu_buffer->nr_pages_to_update = 0;
1818 }
1819
1820 put_online_cpus();
1821 } else {
1822 /* Make sure this CPU has been initialized */
1823 if (!cpumask_test_cpu(cpu_id, buffer->cpumask))
1824 goto out;
1825
1826 cpu_buffer = buffer->buffers[cpu_id];
1827
1828 if (nr_pages == cpu_buffer->nr_pages)
1829 goto out;
1830
1831 cpu_buffer->nr_pages_to_update = nr_pages -
1832 cpu_buffer->nr_pages;
1833
1834 INIT_LIST_HEAD(&cpu_buffer->new_pages);
1835 if (cpu_buffer->nr_pages_to_update > 0 &&
1836 __rb_allocate_pages(cpu_buffer->nr_pages_to_update,
1837 &cpu_buffer->new_pages, cpu_id)) {
1838 err = -ENOMEM;
1839 goto out_err;
1840 }
1841
1842 get_online_cpus();
1843
1844 /* Can't run something on an offline CPU. */
1845 if (!cpu_online(cpu_id))
1846 rb_update_pages(cpu_buffer);
1847 else {
1848 schedule_work_on(cpu_id,
1849 &cpu_buffer->update_pages_work);
1850 wait_for_completion(&cpu_buffer->update_done);
1851 }
1852
1853 cpu_buffer->nr_pages_to_update = 0;
1854 put_online_cpus();
1855 }
1856
1857 out:
1858 /*
1859 * The ring buffer resize can happen with the ring buffer
1860 * enabled, so that the update disturbs the tracing as little
1861 * as possible. But if the buffer is disabled, we do not need
1862 * to worry about that, and we can take the time to verify
1863 * that the buffer is not corrupt.
1864 */
1865 if (atomic_read(&buffer->record_disabled)) {
1866 atomic_inc(&buffer->record_disabled);
1867 /*
1868 * Even though the buffer was disabled, we must make sure
1869 * that it is truly disabled before calling rb_check_pages.
1870 * There could have been a race between checking
1871 * record_disable and incrementing it.
1872 */
David Brazdil0f672f62019-12-10 10:32:29 +00001873 synchronize_rcu();
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001874 for_each_buffer_cpu(buffer, cpu) {
1875 cpu_buffer = buffer->buffers[cpu];
1876 rb_check_pages(cpu_buffer);
1877 }
1878 atomic_dec(&buffer->record_disabled);
1879 }
1880
1881 mutex_unlock(&buffer->mutex);
Olivier Deprez0e641232021-09-23 10:07:05 +02001882 return 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001883
1884 out_err:
1885 for_each_buffer_cpu(buffer, cpu) {
1886 struct buffer_page *bpage, *tmp;
1887
1888 cpu_buffer = buffer->buffers[cpu];
1889 cpu_buffer->nr_pages_to_update = 0;
1890
1891 if (list_empty(&cpu_buffer->new_pages))
1892 continue;
1893
1894 list_for_each_entry_safe(bpage, tmp, &cpu_buffer->new_pages,
1895 list) {
1896 list_del_init(&bpage->list);
1897 free_buffer_page(bpage);
1898 }
1899 }
1900 mutex_unlock(&buffer->mutex);
1901 return err;
1902}
1903EXPORT_SYMBOL_GPL(ring_buffer_resize);
1904
1905void ring_buffer_change_overwrite(struct ring_buffer *buffer, int val)
1906{
1907 mutex_lock(&buffer->mutex);
1908 if (val)
1909 buffer->flags |= RB_FL_OVERWRITE;
1910 else
1911 buffer->flags &= ~RB_FL_OVERWRITE;
1912 mutex_unlock(&buffer->mutex);
1913}
1914EXPORT_SYMBOL_GPL(ring_buffer_change_overwrite);
1915
1916static __always_inline void *__rb_page_index(struct buffer_page *bpage, unsigned index)
1917{
1918 return bpage->page->data + index;
1919}
1920
1921static __always_inline struct ring_buffer_event *
1922rb_reader_event(struct ring_buffer_per_cpu *cpu_buffer)
1923{
1924 return __rb_page_index(cpu_buffer->reader_page,
1925 cpu_buffer->reader_page->read);
1926}
1927
1928static __always_inline struct ring_buffer_event *
1929rb_iter_head_event(struct ring_buffer_iter *iter)
1930{
1931 return __rb_page_index(iter->head_page, iter->head);
1932}
1933
1934static __always_inline unsigned rb_page_commit(struct buffer_page *bpage)
1935{
1936 return local_read(&bpage->page->commit);
1937}
1938
1939/* Size is determined by what has been committed */
1940static __always_inline unsigned rb_page_size(struct buffer_page *bpage)
1941{
1942 return rb_page_commit(bpage);
1943}
1944
1945static __always_inline unsigned
1946rb_commit_index(struct ring_buffer_per_cpu *cpu_buffer)
1947{
1948 return rb_page_commit(cpu_buffer->commit_page);
1949}
1950
1951static __always_inline unsigned
1952rb_event_index(struct ring_buffer_event *event)
1953{
1954 unsigned long addr = (unsigned long)event;
1955
1956 return (addr & ~PAGE_MASK) - BUF_PAGE_HDR_SIZE;
1957}
1958
1959static void rb_inc_iter(struct ring_buffer_iter *iter)
1960{
1961 struct ring_buffer_per_cpu *cpu_buffer = iter->cpu_buffer;
1962
1963 /*
1964 * The iterator could be on the reader page (it starts there).
1965 * But the head could have moved, since the reader was
1966 * found. Check for this case and assign the iterator
1967 * to the head page instead of next.
1968 */
1969 if (iter->head_page == cpu_buffer->reader_page)
1970 iter->head_page = rb_set_head_page(cpu_buffer);
1971 else
1972 rb_inc_page(cpu_buffer, &iter->head_page);
1973
1974 iter->read_stamp = iter->head_page->page->time_stamp;
1975 iter->head = 0;
1976}
1977
1978/*
1979 * rb_handle_head_page - writer hit the head page
1980 *
1981 * Returns: +1 to retry page
1982 * 0 to continue
1983 * -1 on error
1984 */
1985static int
1986rb_handle_head_page(struct ring_buffer_per_cpu *cpu_buffer,
1987 struct buffer_page *tail_page,
1988 struct buffer_page *next_page)
1989{
1990 struct buffer_page *new_head;
1991 int entries;
1992 int type;
1993 int ret;
1994
1995 entries = rb_page_entries(next_page);
1996
1997 /*
1998 * The hard part is here. We need to move the head
1999 * forward, and protect against both readers on
2000 * other CPUs and writers coming in via interrupts.
2001 */
2002 type = rb_head_page_set_update(cpu_buffer, next_page, tail_page,
2003 RB_PAGE_HEAD);
2004
2005 /*
2006 * type can be one of four:
2007 * NORMAL - an interrupt already moved it for us
2008 * HEAD - we are the first to get here.
2009 * UPDATE - we are the interrupt interrupting
2010 * a current move.
2011 * MOVED - a reader on another CPU moved the next
2012 * pointer to its reader page. Give up
2013 * and try again.
2014 */
2015
2016 switch (type) {
2017 case RB_PAGE_HEAD:
2018 /*
2019 * We changed the head to UPDATE, thus
2020 * it is our responsibility to update
2021 * the counters.
2022 */
2023 local_add(entries, &cpu_buffer->overrun);
2024 local_sub(BUF_PAGE_SIZE, &cpu_buffer->entries_bytes);
2025
2026 /*
2027 * The entries will be zeroed out when we move the
2028 * tail page.
2029 */
2030
2031 /* still more to do */
2032 break;
2033
2034 case RB_PAGE_UPDATE:
2035 /*
2036 * This is an interrupt that interrupt the
2037 * previous update. Still more to do.
2038 */
2039 break;
2040 case RB_PAGE_NORMAL:
2041 /*
2042 * An interrupt came in before the update
2043 * and processed this for us.
2044 * Nothing left to do.
2045 */
2046 return 1;
2047 case RB_PAGE_MOVED:
2048 /*
2049 * The reader is on another CPU and just did
2050 * a swap with our next_page.
2051 * Try again.
2052 */
2053 return 1;
2054 default:
2055 RB_WARN_ON(cpu_buffer, 1); /* WTF??? */
2056 return -1;
2057 }
2058
2059 /*
2060 * Now that we are here, the old head pointer is
2061 * set to UPDATE. This will keep the reader from
2062 * swapping the head page with the reader page.
2063 * The reader (on another CPU) will spin till
2064 * we are finished.
2065 *
2066 * We just need to protect against interrupts
2067 * doing the job. We will set the next pointer
2068 * to HEAD. After that, we set the old pointer
2069 * to NORMAL, but only if it was HEAD before.
2070 * otherwise we are an interrupt, and only
2071 * want the outer most commit to reset it.
2072 */
2073 new_head = next_page;
2074 rb_inc_page(cpu_buffer, &new_head);
2075
2076 ret = rb_head_page_set_head(cpu_buffer, new_head, next_page,
2077 RB_PAGE_NORMAL);
2078
2079 /*
2080 * Valid returns are:
2081 * HEAD - an interrupt came in and already set it.
2082 * NORMAL - One of two things:
2083 * 1) We really set it.
2084 * 2) A bunch of interrupts came in and moved
2085 * the page forward again.
2086 */
2087 switch (ret) {
2088 case RB_PAGE_HEAD:
2089 case RB_PAGE_NORMAL:
2090 /* OK */
2091 break;
2092 default:
2093 RB_WARN_ON(cpu_buffer, 1);
2094 return -1;
2095 }
2096
2097 /*
2098 * It is possible that an interrupt came in,
2099 * set the head up, then more interrupts came in
2100 * and moved it again. When we get back here,
2101 * the page would have been set to NORMAL but we
2102 * just set it back to HEAD.
2103 *
2104 * How do you detect this? Well, if that happened
2105 * the tail page would have moved.
2106 */
2107 if (ret == RB_PAGE_NORMAL) {
2108 struct buffer_page *buffer_tail_page;
2109
2110 buffer_tail_page = READ_ONCE(cpu_buffer->tail_page);
2111 /*
2112 * If the tail had moved passed next, then we need
2113 * to reset the pointer.
2114 */
2115 if (buffer_tail_page != tail_page &&
2116 buffer_tail_page != next_page)
2117 rb_head_page_set_normal(cpu_buffer, new_head,
2118 next_page,
2119 RB_PAGE_HEAD);
2120 }
2121
2122 /*
2123 * If this was the outer most commit (the one that
2124 * changed the original pointer from HEAD to UPDATE),
2125 * then it is up to us to reset it to NORMAL.
2126 */
2127 if (type == RB_PAGE_HEAD) {
2128 ret = rb_head_page_set_normal(cpu_buffer, next_page,
2129 tail_page,
2130 RB_PAGE_UPDATE);
2131 if (RB_WARN_ON(cpu_buffer,
2132 ret != RB_PAGE_UPDATE))
2133 return -1;
2134 }
2135
2136 return 0;
2137}
2138
2139static inline void
2140rb_reset_tail(struct ring_buffer_per_cpu *cpu_buffer,
2141 unsigned long tail, struct rb_event_info *info)
2142{
2143 struct buffer_page *tail_page = info->tail_page;
2144 struct ring_buffer_event *event;
2145 unsigned long length = info->length;
2146
2147 /*
2148 * Only the event that crossed the page boundary
2149 * must fill the old tail_page with padding.
2150 */
2151 if (tail >= BUF_PAGE_SIZE) {
2152 /*
2153 * If the page was filled, then we still need
2154 * to update the real_end. Reset it to zero
2155 * and the reader will ignore it.
2156 */
2157 if (tail == BUF_PAGE_SIZE)
2158 tail_page->real_end = 0;
2159
2160 local_sub(length, &tail_page->write);
2161 return;
2162 }
2163
2164 event = __rb_page_index(tail_page, tail);
2165
2166 /* account for padding bytes */
2167 local_add(BUF_PAGE_SIZE - tail, &cpu_buffer->entries_bytes);
2168
2169 /*
2170 * Save the original length to the meta data.
2171 * This will be used by the reader to add lost event
2172 * counter.
2173 */
2174 tail_page->real_end = tail;
2175
2176 /*
2177 * If this event is bigger than the minimum size, then
2178 * we need to be careful that we don't subtract the
2179 * write counter enough to allow another writer to slip
2180 * in on this page.
2181 * We put in a discarded commit instead, to make sure
2182 * that this space is not used again.
2183 *
2184 * If we are less than the minimum size, we don't need to
2185 * worry about it.
2186 */
2187 if (tail > (BUF_PAGE_SIZE - RB_EVNT_MIN_SIZE)) {
2188 /* No room for any events */
2189
2190 /* Mark the rest of the page with padding */
2191 rb_event_set_padding(event);
2192
2193 /* Set the write back to the previous setting */
2194 local_sub(length, &tail_page->write);
2195 return;
2196 }
2197
2198 /* Put in a discarded event */
2199 event->array[0] = (BUF_PAGE_SIZE - tail) - RB_EVNT_HDR_SIZE;
2200 event->type_len = RINGBUF_TYPE_PADDING;
2201 /* time delta must be non zero */
2202 event->time_delta = 1;
2203
2204 /* Set write to end of buffer */
2205 length = (tail + length) - BUF_PAGE_SIZE;
2206 local_sub(length, &tail_page->write);
2207}
2208
2209static inline void rb_end_commit(struct ring_buffer_per_cpu *cpu_buffer);
2210
2211/*
2212 * This is the slow path, force gcc not to inline it.
2213 */
2214static noinline struct ring_buffer_event *
2215rb_move_tail(struct ring_buffer_per_cpu *cpu_buffer,
2216 unsigned long tail, struct rb_event_info *info)
2217{
2218 struct buffer_page *tail_page = info->tail_page;
2219 struct buffer_page *commit_page = cpu_buffer->commit_page;
2220 struct ring_buffer *buffer = cpu_buffer->buffer;
2221 struct buffer_page *next_page;
2222 int ret;
2223
2224 next_page = tail_page;
2225
2226 rb_inc_page(cpu_buffer, &next_page);
2227
2228 /*
2229 * If for some reason, we had an interrupt storm that made
2230 * it all the way around the buffer, bail, and warn
2231 * about it.
2232 */
2233 if (unlikely(next_page == commit_page)) {
2234 local_inc(&cpu_buffer->commit_overrun);
2235 goto out_reset;
2236 }
2237
2238 /*
2239 * This is where the fun begins!
2240 *
2241 * We are fighting against races between a reader that
2242 * could be on another CPU trying to swap its reader
2243 * page with the buffer head.
2244 *
2245 * We are also fighting against interrupts coming in and
2246 * moving the head or tail on us as well.
2247 *
2248 * If the next page is the head page then we have filled
2249 * the buffer, unless the commit page is still on the
2250 * reader page.
2251 */
2252 if (rb_is_head_page(cpu_buffer, next_page, &tail_page->list)) {
2253
2254 /*
2255 * If the commit is not on the reader page, then
2256 * move the header page.
2257 */
2258 if (!rb_is_reader_page(cpu_buffer->commit_page)) {
2259 /*
2260 * If we are not in overwrite mode,
2261 * this is easy, just stop here.
2262 */
2263 if (!(buffer->flags & RB_FL_OVERWRITE)) {
2264 local_inc(&cpu_buffer->dropped_events);
2265 goto out_reset;
2266 }
2267
2268 ret = rb_handle_head_page(cpu_buffer,
2269 tail_page,
2270 next_page);
2271 if (ret < 0)
2272 goto out_reset;
2273 if (ret)
2274 goto out_again;
2275 } else {
2276 /*
2277 * We need to be careful here too. The
2278 * commit page could still be on the reader
2279 * page. We could have a small buffer, and
2280 * have filled up the buffer with events
2281 * from interrupts and such, and wrapped.
2282 *
2283 * Note, if the tail page is also the on the
2284 * reader_page, we let it move out.
2285 */
2286 if (unlikely((cpu_buffer->commit_page !=
2287 cpu_buffer->tail_page) &&
2288 (cpu_buffer->commit_page ==
2289 cpu_buffer->reader_page))) {
2290 local_inc(&cpu_buffer->commit_overrun);
2291 goto out_reset;
2292 }
2293 }
2294 }
2295
2296 rb_tail_page_update(cpu_buffer, tail_page, next_page);
2297
2298 out_again:
2299
2300 rb_reset_tail(cpu_buffer, tail, info);
2301
2302 /* Commit what we have for now. */
2303 rb_end_commit(cpu_buffer);
2304 /* rb_end_commit() decs committing */
2305 local_inc(&cpu_buffer->committing);
2306
2307 /* fail and let the caller try again */
2308 return ERR_PTR(-EAGAIN);
2309
2310 out_reset:
2311 /* reset write */
2312 rb_reset_tail(cpu_buffer, tail, info);
2313
2314 return NULL;
2315}
2316
2317/* Slow path, do not inline */
2318static noinline struct ring_buffer_event *
2319rb_add_time_stamp(struct ring_buffer_event *event, u64 delta, bool abs)
2320{
2321 if (abs)
2322 event->type_len = RINGBUF_TYPE_TIME_STAMP;
2323 else
2324 event->type_len = RINGBUF_TYPE_TIME_EXTEND;
2325
2326 /* Not the first event on the page, or not delta? */
2327 if (abs || rb_event_index(event)) {
2328 event->time_delta = delta & TS_MASK;
2329 event->array[0] = delta >> TS_SHIFT;
2330 } else {
2331 /* nope, just zero it */
2332 event->time_delta = 0;
2333 event->array[0] = 0;
2334 }
2335
2336 return skip_time_extend(event);
2337}
2338
2339static inline bool rb_event_is_commit(struct ring_buffer_per_cpu *cpu_buffer,
2340 struct ring_buffer_event *event);
2341
2342/**
2343 * rb_update_event - update event type and data
2344 * @event: the event to update
2345 * @type: the type of event
2346 * @length: the size of the event field in the ring buffer
2347 *
2348 * Update the type and data fields of the event. The length
2349 * is the actual size that is written to the ring buffer,
2350 * and with this, we can determine what to place into the
2351 * data field.
2352 */
2353static void
2354rb_update_event(struct ring_buffer_per_cpu *cpu_buffer,
2355 struct ring_buffer_event *event,
2356 struct rb_event_info *info)
2357{
2358 unsigned length = info->length;
2359 u64 delta = info->delta;
2360
2361 /* Only a commit updates the timestamp */
2362 if (unlikely(!rb_event_is_commit(cpu_buffer, event)))
2363 delta = 0;
2364
2365 /*
2366 * If we need to add a timestamp, then we
2367 * add it to the start of the reserved space.
2368 */
2369 if (unlikely(info->add_timestamp)) {
2370 bool abs = ring_buffer_time_stamp_abs(cpu_buffer->buffer);
2371
Olivier Deprez0e641232021-09-23 10:07:05 +02002372 event = rb_add_time_stamp(event, abs ? info->delta : delta, abs);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002373 length -= RB_LEN_TIME_EXTEND;
2374 delta = 0;
2375 }
2376
2377 event->time_delta = delta;
2378 length -= RB_EVNT_HDR_SIZE;
Olivier Deprez0e641232021-09-23 10:07:05 +02002379 if (length > RB_MAX_SMALL_DATA || RB_FORCE_8BYTE_ALIGNMENT) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002380 event->type_len = 0;
2381 event->array[0] = length;
2382 } else
2383 event->type_len = DIV_ROUND_UP(length, RB_ALIGNMENT);
2384}
2385
2386static unsigned rb_calculate_event_length(unsigned length)
2387{
2388 struct ring_buffer_event event; /* Used only for sizeof array */
2389
2390 /* zero length can cause confusions */
2391 if (!length)
2392 length++;
2393
Olivier Deprez0e641232021-09-23 10:07:05 +02002394 if (length > RB_MAX_SMALL_DATA || RB_FORCE_8BYTE_ALIGNMENT)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002395 length += sizeof(event.array[0]);
2396
2397 length += RB_EVNT_HDR_SIZE;
Olivier Deprez0e641232021-09-23 10:07:05 +02002398 length = ALIGN(length, RB_ARCH_ALIGNMENT);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002399
2400 /*
2401 * In case the time delta is larger than the 27 bits for it
2402 * in the header, we need to add a timestamp. If another
2403 * event comes in when trying to discard this one to increase
2404 * the length, then the timestamp will be added in the allocated
2405 * space of this event. If length is bigger than the size needed
2406 * for the TIME_EXTEND, then padding has to be used. The events
2407 * length must be either RB_LEN_TIME_EXTEND, or greater than or equal
2408 * to RB_LEN_TIME_EXTEND + 8, as 8 is the minimum size for padding.
2409 * As length is a multiple of 4, we only need to worry if it
2410 * is 12 (RB_LEN_TIME_EXTEND + 4).
2411 */
2412 if (length == RB_LEN_TIME_EXTEND + RB_ALIGNMENT)
2413 length += RB_ALIGNMENT;
2414
2415 return length;
2416}
2417
2418#ifndef CONFIG_HAVE_UNSTABLE_SCHED_CLOCK
2419static inline bool sched_clock_stable(void)
2420{
2421 return true;
2422}
2423#endif
2424
2425static inline int
2426rb_try_to_discard(struct ring_buffer_per_cpu *cpu_buffer,
2427 struct ring_buffer_event *event)
2428{
2429 unsigned long new_index, old_index;
2430 struct buffer_page *bpage;
2431 unsigned long index;
2432 unsigned long addr;
2433
2434 new_index = rb_event_index(event);
2435 old_index = new_index + rb_event_ts_length(event);
2436 addr = (unsigned long)event;
2437 addr &= PAGE_MASK;
2438
2439 bpage = READ_ONCE(cpu_buffer->tail_page);
2440
2441 if (bpage->page == (void *)addr && rb_page_write(bpage) == old_index) {
2442 unsigned long write_mask =
2443 local_read(&bpage->write) & ~RB_WRITE_MASK;
2444 unsigned long event_length = rb_event_length(event);
2445 /*
2446 * This is on the tail page. It is possible that
2447 * a write could come in and move the tail page
2448 * and write to the next page. That is fine
2449 * because we just shorten what is on this page.
2450 */
2451 old_index += write_mask;
2452 new_index += write_mask;
2453 index = local_cmpxchg(&bpage->write, old_index, new_index);
2454 if (index == old_index) {
2455 /* update counters */
2456 local_sub(event_length, &cpu_buffer->entries_bytes);
2457 return 1;
2458 }
2459 }
2460
2461 /* could not discard */
2462 return 0;
2463}
2464
2465static void rb_start_commit(struct ring_buffer_per_cpu *cpu_buffer)
2466{
2467 local_inc(&cpu_buffer->committing);
2468 local_inc(&cpu_buffer->commits);
2469}
2470
2471static __always_inline void
2472rb_set_commit_to_write(struct ring_buffer_per_cpu *cpu_buffer)
2473{
2474 unsigned long max_count;
2475
2476 /*
2477 * We only race with interrupts and NMIs on this CPU.
2478 * If we own the commit event, then we can commit
2479 * all others that interrupted us, since the interruptions
2480 * are in stack format (they finish before they come
2481 * back to us). This allows us to do a simple loop to
2482 * assign the commit to the tail.
2483 */
2484 again:
2485 max_count = cpu_buffer->nr_pages * 100;
2486
2487 while (cpu_buffer->commit_page != READ_ONCE(cpu_buffer->tail_page)) {
2488 if (RB_WARN_ON(cpu_buffer, !(--max_count)))
2489 return;
2490 if (RB_WARN_ON(cpu_buffer,
2491 rb_is_reader_page(cpu_buffer->tail_page)))
2492 return;
2493 local_set(&cpu_buffer->commit_page->page->commit,
2494 rb_page_write(cpu_buffer->commit_page));
2495 rb_inc_page(cpu_buffer, &cpu_buffer->commit_page);
2496 /* Only update the write stamp if the page has an event */
2497 if (rb_page_write(cpu_buffer->commit_page))
2498 cpu_buffer->write_stamp =
2499 cpu_buffer->commit_page->page->time_stamp;
2500 /* add barrier to keep gcc from optimizing too much */
2501 barrier();
2502 }
2503 while (rb_commit_index(cpu_buffer) !=
2504 rb_page_write(cpu_buffer->commit_page)) {
2505
2506 local_set(&cpu_buffer->commit_page->page->commit,
2507 rb_page_write(cpu_buffer->commit_page));
2508 RB_WARN_ON(cpu_buffer,
2509 local_read(&cpu_buffer->commit_page->page->commit) &
2510 ~RB_WRITE_MASK);
2511 barrier();
2512 }
2513
2514 /* again, keep gcc from optimizing */
2515 barrier();
2516
2517 /*
2518 * If an interrupt came in just after the first while loop
2519 * and pushed the tail page forward, we will be left with
2520 * a dangling commit that will never go forward.
2521 */
2522 if (unlikely(cpu_buffer->commit_page != READ_ONCE(cpu_buffer->tail_page)))
2523 goto again;
2524}
2525
2526static __always_inline void rb_end_commit(struct ring_buffer_per_cpu *cpu_buffer)
2527{
2528 unsigned long commits;
2529
2530 if (RB_WARN_ON(cpu_buffer,
2531 !local_read(&cpu_buffer->committing)))
2532 return;
2533
2534 again:
2535 commits = local_read(&cpu_buffer->commits);
2536 /* synchronize with interrupts */
2537 barrier();
2538 if (local_read(&cpu_buffer->committing) == 1)
2539 rb_set_commit_to_write(cpu_buffer);
2540
2541 local_dec(&cpu_buffer->committing);
2542
2543 /* synchronize with interrupts */
2544 barrier();
2545
2546 /*
2547 * Need to account for interrupts coming in between the
2548 * updating of the commit page and the clearing of the
2549 * committing counter.
2550 */
2551 if (unlikely(local_read(&cpu_buffer->commits) != commits) &&
2552 !local_read(&cpu_buffer->committing)) {
2553 local_inc(&cpu_buffer->committing);
2554 goto again;
2555 }
2556}
2557
2558static inline void rb_event_discard(struct ring_buffer_event *event)
2559{
2560 if (extended_time(event))
2561 event = skip_time_extend(event);
2562
2563 /* array[0] holds the actual length for the discarded event */
2564 event->array[0] = rb_event_data_length(event) - RB_EVNT_HDR_SIZE;
2565 event->type_len = RINGBUF_TYPE_PADDING;
2566 /* time delta must be non zero */
2567 if (!event->time_delta)
2568 event->time_delta = 1;
2569}
2570
2571static __always_inline bool
2572rb_event_is_commit(struct ring_buffer_per_cpu *cpu_buffer,
2573 struct ring_buffer_event *event)
2574{
2575 unsigned long addr = (unsigned long)event;
2576 unsigned long index;
2577
2578 index = rb_event_index(event);
2579 addr &= PAGE_MASK;
2580
2581 return cpu_buffer->commit_page->page == (void *)addr &&
2582 rb_commit_index(cpu_buffer) == index;
2583}
2584
2585static __always_inline void
2586rb_update_write_stamp(struct ring_buffer_per_cpu *cpu_buffer,
2587 struct ring_buffer_event *event)
2588{
2589 u64 delta;
2590
2591 /*
2592 * The event first in the commit queue updates the
2593 * time stamp.
2594 */
2595 if (rb_event_is_commit(cpu_buffer, event)) {
2596 /*
2597 * A commit event that is first on a page
2598 * updates the write timestamp with the page stamp
2599 */
2600 if (!rb_event_index(event))
2601 cpu_buffer->write_stamp =
2602 cpu_buffer->commit_page->page->time_stamp;
2603 else if (event->type_len == RINGBUF_TYPE_TIME_EXTEND) {
2604 delta = ring_buffer_event_time_stamp(event);
2605 cpu_buffer->write_stamp += delta;
2606 } else if (event->type_len == RINGBUF_TYPE_TIME_STAMP) {
2607 delta = ring_buffer_event_time_stamp(event);
2608 cpu_buffer->write_stamp = delta;
2609 } else
2610 cpu_buffer->write_stamp += event->time_delta;
2611 }
2612}
2613
2614static void rb_commit(struct ring_buffer_per_cpu *cpu_buffer,
2615 struct ring_buffer_event *event)
2616{
2617 local_inc(&cpu_buffer->entries);
2618 rb_update_write_stamp(cpu_buffer, event);
2619 rb_end_commit(cpu_buffer);
2620}
2621
2622static __always_inline void
2623rb_wakeups(struct ring_buffer *buffer, struct ring_buffer_per_cpu *cpu_buffer)
2624{
David Brazdil0f672f62019-12-10 10:32:29 +00002625 size_t nr_pages;
2626 size_t dirty;
2627 size_t full;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002628
2629 if (buffer->irq_work.waiters_pending) {
2630 buffer->irq_work.waiters_pending = false;
2631 /* irq_work_queue() supplies it's own memory barriers */
2632 irq_work_queue(&buffer->irq_work.work);
2633 }
2634
2635 if (cpu_buffer->irq_work.waiters_pending) {
2636 cpu_buffer->irq_work.waiters_pending = false;
2637 /* irq_work_queue() supplies it's own memory barriers */
2638 irq_work_queue(&cpu_buffer->irq_work.work);
2639 }
2640
David Brazdil0f672f62019-12-10 10:32:29 +00002641 if (cpu_buffer->last_pages_touch == local_read(&cpu_buffer->pages_touched))
2642 return;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002643
David Brazdil0f672f62019-12-10 10:32:29 +00002644 if (cpu_buffer->reader_page == cpu_buffer->commit_page)
2645 return;
2646
2647 if (!cpu_buffer->irq_work.full_waiters_pending)
2648 return;
2649
2650 cpu_buffer->last_pages_touch = local_read(&cpu_buffer->pages_touched);
2651
2652 full = cpu_buffer->shortest_full;
2653 nr_pages = cpu_buffer->nr_pages;
2654 dirty = ring_buffer_nr_dirty_pages(buffer, cpu_buffer->cpu);
2655 if (full && nr_pages && (dirty * 100) <= full * nr_pages)
2656 return;
2657
2658 cpu_buffer->irq_work.wakeup_full = true;
2659 cpu_buffer->irq_work.full_waiters_pending = false;
2660 /* irq_work_queue() supplies it's own memory barriers */
2661 irq_work_queue(&cpu_buffer->irq_work.work);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002662}
2663
2664/*
2665 * The lock and unlock are done within a preempt disable section.
2666 * The current_context per_cpu variable can only be modified
2667 * by the current task between lock and unlock. But it can
2668 * be modified more than once via an interrupt. To pass this
2669 * information from the lock to the unlock without having to
2670 * access the 'in_interrupt()' functions again (which do show
2671 * a bit of overhead in something as critical as function tracing,
2672 * we use a bitmask trick.
2673 *
Olivier Deprez0e641232021-09-23 10:07:05 +02002674 * bit 1 = NMI context
2675 * bit 2 = IRQ context
2676 * bit 3 = SoftIRQ context
2677 * bit 4 = normal context.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002678 *
2679 * This works because this is the order of contexts that can
2680 * preempt other contexts. A SoftIRQ never preempts an IRQ
2681 * context.
2682 *
2683 * When the context is determined, the corresponding bit is
2684 * checked and set (if it was set, then a recursion of that context
2685 * happened).
2686 *
2687 * On unlock, we need to clear this bit. To do so, just subtract
2688 * 1 from the current_context and AND it to itself.
2689 *
2690 * (binary)
2691 * 101 - 1 = 100
2692 * 101 & 100 = 100 (clearing bit zero)
2693 *
2694 * 1010 - 1 = 1001
2695 * 1010 & 1001 = 1000 (clearing bit 1)
2696 *
2697 * The least significant bit can be cleared this way, and it
2698 * just so happens that it is the same bit corresponding to
2699 * the current context.
Olivier Deprez0e641232021-09-23 10:07:05 +02002700 *
2701 * Now the TRANSITION bit breaks the above slightly. The TRANSITION bit
2702 * is set when a recursion is detected at the current context, and if
2703 * the TRANSITION bit is already set, it will fail the recursion.
2704 * This is needed because there's a lag between the changing of
2705 * interrupt context and updating the preempt count. In this case,
2706 * a false positive will be found. To handle this, one extra recursion
2707 * is allowed, and this is done by the TRANSITION bit. If the TRANSITION
2708 * bit is already set, then it is considered a recursion and the function
2709 * ends. Otherwise, the TRANSITION bit is set, and that bit is returned.
2710 *
2711 * On the trace_recursive_unlock(), the TRANSITION bit will be the first
2712 * to be cleared. Even if it wasn't the context that set it. That is,
2713 * if an interrupt comes in while NORMAL bit is set and the ring buffer
2714 * is called before preempt_count() is updated, since the check will
2715 * be on the NORMAL bit, the TRANSITION bit will then be set. If an
2716 * NMI then comes in, it will set the NMI bit, but when the NMI code
2717 * does the trace_recursive_unlock() it will clear the TRANSTION bit
2718 * and leave the NMI bit set. But this is fine, because the interrupt
2719 * code that set the TRANSITION bit will then clear the NMI bit when it
2720 * calls trace_recursive_unlock(). If another NMI comes in, it will
2721 * set the TRANSITION bit and continue.
2722 *
2723 * Note: The TRANSITION bit only handles a single transition between context.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002724 */
2725
2726static __always_inline int
2727trace_recursive_lock(struct ring_buffer_per_cpu *cpu_buffer)
2728{
2729 unsigned int val = cpu_buffer->current_context;
2730 unsigned long pc = preempt_count();
2731 int bit;
2732
2733 if (!(pc & (NMI_MASK | HARDIRQ_MASK | SOFTIRQ_OFFSET)))
2734 bit = RB_CTX_NORMAL;
2735 else
2736 bit = pc & NMI_MASK ? RB_CTX_NMI :
2737 pc & HARDIRQ_MASK ? RB_CTX_IRQ : RB_CTX_SOFTIRQ;
2738
Olivier Deprez0e641232021-09-23 10:07:05 +02002739 if (unlikely(val & (1 << (bit + cpu_buffer->nest)))) {
2740 /*
2741 * It is possible that this was called by transitioning
2742 * between interrupt context, and preempt_count() has not
2743 * been updated yet. In this case, use the TRANSITION bit.
2744 */
2745 bit = RB_CTX_TRANSITION;
2746 if (val & (1 << (bit + cpu_buffer->nest)))
2747 return 1;
2748 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002749
2750 val |= (1 << (bit + cpu_buffer->nest));
2751 cpu_buffer->current_context = val;
2752
2753 return 0;
2754}
2755
2756static __always_inline void
2757trace_recursive_unlock(struct ring_buffer_per_cpu *cpu_buffer)
2758{
2759 cpu_buffer->current_context &=
2760 cpu_buffer->current_context - (1 << cpu_buffer->nest);
2761}
2762
Olivier Deprez0e641232021-09-23 10:07:05 +02002763/* The recursive locking above uses 5 bits */
2764#define NESTED_BITS 5
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002765
2766/**
2767 * ring_buffer_nest_start - Allow to trace while nested
2768 * @buffer: The ring buffer to modify
2769 *
2770 * The ring buffer has a safety mechanism to prevent recursion.
2771 * But there may be a case where a trace needs to be done while
2772 * tracing something else. In this case, calling this function
2773 * will allow this function to nest within a currently active
2774 * ring_buffer_lock_reserve().
2775 *
2776 * Call this function before calling another ring_buffer_lock_reserve() and
2777 * call ring_buffer_nest_end() after the nested ring_buffer_unlock_commit().
2778 */
2779void ring_buffer_nest_start(struct ring_buffer *buffer)
2780{
2781 struct ring_buffer_per_cpu *cpu_buffer;
2782 int cpu;
2783
2784 /* Enabled by ring_buffer_nest_end() */
2785 preempt_disable_notrace();
2786 cpu = raw_smp_processor_id();
2787 cpu_buffer = buffer->buffers[cpu];
2788 /* This is the shift value for the above recursive locking */
2789 cpu_buffer->nest += NESTED_BITS;
2790}
2791
2792/**
2793 * ring_buffer_nest_end - Allow to trace while nested
2794 * @buffer: The ring buffer to modify
2795 *
2796 * Must be called after ring_buffer_nest_start() and after the
2797 * ring_buffer_unlock_commit().
2798 */
2799void ring_buffer_nest_end(struct ring_buffer *buffer)
2800{
2801 struct ring_buffer_per_cpu *cpu_buffer;
2802 int cpu;
2803
2804 /* disabled by ring_buffer_nest_start() */
2805 cpu = raw_smp_processor_id();
2806 cpu_buffer = buffer->buffers[cpu];
2807 /* This is the shift value for the above recursive locking */
2808 cpu_buffer->nest -= NESTED_BITS;
2809 preempt_enable_notrace();
2810}
2811
2812/**
2813 * ring_buffer_unlock_commit - commit a reserved
2814 * @buffer: The buffer to commit to
2815 * @event: The event pointer to commit.
2816 *
2817 * This commits the data to the ring buffer, and releases any locks held.
2818 *
2819 * Must be paired with ring_buffer_lock_reserve.
2820 */
2821int ring_buffer_unlock_commit(struct ring_buffer *buffer,
2822 struct ring_buffer_event *event)
2823{
2824 struct ring_buffer_per_cpu *cpu_buffer;
2825 int cpu = raw_smp_processor_id();
2826
2827 cpu_buffer = buffer->buffers[cpu];
2828
2829 rb_commit(cpu_buffer, event);
2830
2831 rb_wakeups(buffer, cpu_buffer);
2832
2833 trace_recursive_unlock(cpu_buffer);
2834
2835 preempt_enable_notrace();
2836
2837 return 0;
2838}
2839EXPORT_SYMBOL_GPL(ring_buffer_unlock_commit);
2840
2841static noinline void
2842rb_handle_timestamp(struct ring_buffer_per_cpu *cpu_buffer,
2843 struct rb_event_info *info)
2844{
2845 WARN_ONCE(info->delta > (1ULL << 59),
2846 KERN_WARNING "Delta way too big! %llu ts=%llu write stamp = %llu\n%s",
2847 (unsigned long long)info->delta,
2848 (unsigned long long)info->ts,
2849 (unsigned long long)cpu_buffer->write_stamp,
2850 sched_clock_stable() ? "" :
2851 "If you just came from a suspend/resume,\n"
2852 "please switch to the trace global clock:\n"
2853 " echo global > /sys/kernel/debug/tracing/trace_clock\n"
2854 "or add trace_clock=global to the kernel command line\n");
2855 info->add_timestamp = 1;
2856}
2857
2858static struct ring_buffer_event *
2859__rb_reserve_next(struct ring_buffer_per_cpu *cpu_buffer,
2860 struct rb_event_info *info)
2861{
2862 struct ring_buffer_event *event;
2863 struct buffer_page *tail_page;
2864 unsigned long tail, write;
2865
2866 /*
2867 * If the time delta since the last event is too big to
2868 * hold in the time field of the event, then we append a
2869 * TIME EXTEND event ahead of the data event.
2870 */
2871 if (unlikely(info->add_timestamp))
2872 info->length += RB_LEN_TIME_EXTEND;
2873
2874 /* Don't let the compiler play games with cpu_buffer->tail_page */
2875 tail_page = info->tail_page = READ_ONCE(cpu_buffer->tail_page);
2876 write = local_add_return(info->length, &tail_page->write);
2877
2878 /* set write to only the index of the write */
2879 write &= RB_WRITE_MASK;
2880 tail = write - info->length;
2881
2882 /*
2883 * If this is the first commit on the page, then it has the same
2884 * timestamp as the page itself.
2885 */
2886 if (!tail && !ring_buffer_time_stamp_abs(cpu_buffer->buffer))
2887 info->delta = 0;
2888
2889 /* See if we shot pass the end of this buffer page */
2890 if (unlikely(write > BUF_PAGE_SIZE))
2891 return rb_move_tail(cpu_buffer, tail, info);
2892
2893 /* We reserved something on the buffer */
2894
2895 event = __rb_page_index(tail_page, tail);
2896 rb_update_event(cpu_buffer, event, info);
2897
2898 local_inc(&tail_page->entries);
2899
2900 /*
2901 * If this is the first commit on the page, then update
2902 * its timestamp.
2903 */
2904 if (!tail)
2905 tail_page->page->time_stamp = info->ts;
2906
2907 /* account for these added bytes */
2908 local_add(info->length, &cpu_buffer->entries_bytes);
2909
2910 return event;
2911}
2912
2913static __always_inline struct ring_buffer_event *
2914rb_reserve_next_event(struct ring_buffer *buffer,
2915 struct ring_buffer_per_cpu *cpu_buffer,
2916 unsigned long length)
2917{
2918 struct ring_buffer_event *event;
2919 struct rb_event_info info;
2920 int nr_loops = 0;
2921 u64 diff;
2922
2923 rb_start_commit(cpu_buffer);
2924
2925#ifdef CONFIG_RING_BUFFER_ALLOW_SWAP
2926 /*
2927 * Due to the ability to swap a cpu buffer from a buffer
2928 * it is possible it was swapped before we committed.
2929 * (committing stops a swap). We check for it here and
2930 * if it happened, we have to fail the write.
2931 */
2932 barrier();
2933 if (unlikely(READ_ONCE(cpu_buffer->buffer) != buffer)) {
2934 local_dec(&cpu_buffer->committing);
2935 local_dec(&cpu_buffer->commits);
2936 return NULL;
2937 }
2938#endif
2939
2940 info.length = rb_calculate_event_length(length);
2941 again:
2942 info.add_timestamp = 0;
2943 info.delta = 0;
2944
2945 /*
2946 * We allow for interrupts to reenter here and do a trace.
2947 * If one does, it will cause this original code to loop
2948 * back here. Even with heavy interrupts happening, this
2949 * should only happen a few times in a row. If this happens
2950 * 1000 times in a row, there must be either an interrupt
2951 * storm or we have something buggy.
2952 * Bail!
2953 */
2954 if (RB_WARN_ON(cpu_buffer, ++nr_loops > 1000))
2955 goto out_fail;
2956
2957 info.ts = rb_time_stamp(cpu_buffer->buffer);
2958 diff = info.ts - cpu_buffer->write_stamp;
2959
2960 /* make sure this diff is calculated here */
2961 barrier();
2962
2963 if (ring_buffer_time_stamp_abs(buffer)) {
2964 info.delta = info.ts;
2965 rb_handle_timestamp(cpu_buffer, &info);
2966 } else /* Did the write stamp get updated already? */
2967 if (likely(info.ts >= cpu_buffer->write_stamp)) {
2968 info.delta = diff;
2969 if (unlikely(test_time_stamp(info.delta)))
2970 rb_handle_timestamp(cpu_buffer, &info);
2971 }
2972
2973 event = __rb_reserve_next(cpu_buffer, &info);
2974
2975 if (unlikely(PTR_ERR(event) == -EAGAIN)) {
2976 if (info.add_timestamp)
2977 info.length -= RB_LEN_TIME_EXTEND;
2978 goto again;
2979 }
2980
2981 if (!event)
2982 goto out_fail;
2983
2984 return event;
2985
2986 out_fail:
2987 rb_end_commit(cpu_buffer);
2988 return NULL;
2989}
2990
2991/**
2992 * ring_buffer_lock_reserve - reserve a part of the buffer
2993 * @buffer: the ring buffer to reserve from
2994 * @length: the length of the data to reserve (excluding event header)
2995 *
2996 * Returns a reserved event on the ring buffer to copy directly to.
2997 * The user of this interface will need to get the body to write into
2998 * and can use the ring_buffer_event_data() interface.
2999 *
3000 * The length is the length of the data needed, not the event length
3001 * which also includes the event header.
3002 *
3003 * Must be paired with ring_buffer_unlock_commit, unless NULL is returned.
3004 * If NULL is returned, then nothing has been allocated or locked.
3005 */
3006struct ring_buffer_event *
3007ring_buffer_lock_reserve(struct ring_buffer *buffer, unsigned long length)
3008{
3009 struct ring_buffer_per_cpu *cpu_buffer;
3010 struct ring_buffer_event *event;
3011 int cpu;
3012
3013 /* If we are tracing schedule, we don't want to recurse */
3014 preempt_disable_notrace();
3015
3016 if (unlikely(atomic_read(&buffer->record_disabled)))
3017 goto out;
3018
3019 cpu = raw_smp_processor_id();
3020
3021 if (unlikely(!cpumask_test_cpu(cpu, buffer->cpumask)))
3022 goto out;
3023
3024 cpu_buffer = buffer->buffers[cpu];
3025
3026 if (unlikely(atomic_read(&cpu_buffer->record_disabled)))
3027 goto out;
3028
3029 if (unlikely(length > BUF_MAX_DATA_SIZE))
3030 goto out;
3031
3032 if (unlikely(trace_recursive_lock(cpu_buffer)))
3033 goto out;
3034
3035 event = rb_reserve_next_event(buffer, cpu_buffer, length);
3036 if (!event)
3037 goto out_unlock;
3038
3039 return event;
3040
3041 out_unlock:
3042 trace_recursive_unlock(cpu_buffer);
3043 out:
3044 preempt_enable_notrace();
3045 return NULL;
3046}
3047EXPORT_SYMBOL_GPL(ring_buffer_lock_reserve);
3048
3049/*
3050 * Decrement the entries to the page that an event is on.
3051 * The event does not even need to exist, only the pointer
3052 * to the page it is on. This may only be called before the commit
3053 * takes place.
3054 */
3055static inline void
3056rb_decrement_entry(struct ring_buffer_per_cpu *cpu_buffer,
3057 struct ring_buffer_event *event)
3058{
3059 unsigned long addr = (unsigned long)event;
3060 struct buffer_page *bpage = cpu_buffer->commit_page;
3061 struct buffer_page *start;
3062
3063 addr &= PAGE_MASK;
3064
3065 /* Do the likely case first */
3066 if (likely(bpage->page == (void *)addr)) {
3067 local_dec(&bpage->entries);
3068 return;
3069 }
3070
3071 /*
3072 * Because the commit page may be on the reader page we
3073 * start with the next page and check the end loop there.
3074 */
3075 rb_inc_page(cpu_buffer, &bpage);
3076 start = bpage;
3077 do {
3078 if (bpage->page == (void *)addr) {
3079 local_dec(&bpage->entries);
3080 return;
3081 }
3082 rb_inc_page(cpu_buffer, &bpage);
3083 } while (bpage != start);
3084
3085 /* commit not part of this buffer?? */
3086 RB_WARN_ON(cpu_buffer, 1);
3087}
3088
3089/**
3090 * ring_buffer_commit_discard - discard an event that has not been committed
3091 * @buffer: the ring buffer
3092 * @event: non committed event to discard
3093 *
3094 * Sometimes an event that is in the ring buffer needs to be ignored.
3095 * This function lets the user discard an event in the ring buffer
3096 * and then that event will not be read later.
3097 *
3098 * This function only works if it is called before the item has been
3099 * committed. It will try to free the event from the ring buffer
3100 * if another event has not been added behind it.
3101 *
3102 * If another event has been added behind it, it will set the event
3103 * up as discarded, and perform the commit.
3104 *
3105 * If this function is called, do not call ring_buffer_unlock_commit on
3106 * the event.
3107 */
3108void ring_buffer_discard_commit(struct ring_buffer *buffer,
3109 struct ring_buffer_event *event)
3110{
3111 struct ring_buffer_per_cpu *cpu_buffer;
3112 int cpu;
3113
3114 /* The event is discarded regardless */
3115 rb_event_discard(event);
3116
3117 cpu = smp_processor_id();
3118 cpu_buffer = buffer->buffers[cpu];
3119
3120 /*
3121 * This must only be called if the event has not been
3122 * committed yet. Thus we can assume that preemption
3123 * is still disabled.
3124 */
3125 RB_WARN_ON(buffer, !local_read(&cpu_buffer->committing));
3126
3127 rb_decrement_entry(cpu_buffer, event);
3128 if (rb_try_to_discard(cpu_buffer, event))
3129 goto out;
3130
3131 /*
3132 * The commit is still visible by the reader, so we
3133 * must still update the timestamp.
3134 */
3135 rb_update_write_stamp(cpu_buffer, event);
3136 out:
3137 rb_end_commit(cpu_buffer);
3138
3139 trace_recursive_unlock(cpu_buffer);
3140
3141 preempt_enable_notrace();
3142
3143}
3144EXPORT_SYMBOL_GPL(ring_buffer_discard_commit);
3145
3146/**
3147 * ring_buffer_write - write data to the buffer without reserving
3148 * @buffer: The ring buffer to write to.
3149 * @length: The length of the data being written (excluding the event header)
3150 * @data: The data to write to the buffer.
3151 *
3152 * This is like ring_buffer_lock_reserve and ring_buffer_unlock_commit as
3153 * one function. If you already have the data to write to the buffer, it
3154 * may be easier to simply call this function.
3155 *
3156 * Note, like ring_buffer_lock_reserve, the length is the length of the data
3157 * and not the length of the event which would hold the header.
3158 */
3159int ring_buffer_write(struct ring_buffer *buffer,
3160 unsigned long length,
3161 void *data)
3162{
3163 struct ring_buffer_per_cpu *cpu_buffer;
3164 struct ring_buffer_event *event;
3165 void *body;
3166 int ret = -EBUSY;
3167 int cpu;
3168
3169 preempt_disable_notrace();
3170
3171 if (atomic_read(&buffer->record_disabled))
3172 goto out;
3173
3174 cpu = raw_smp_processor_id();
3175
3176 if (!cpumask_test_cpu(cpu, buffer->cpumask))
3177 goto out;
3178
3179 cpu_buffer = buffer->buffers[cpu];
3180
3181 if (atomic_read(&cpu_buffer->record_disabled))
3182 goto out;
3183
3184 if (length > BUF_MAX_DATA_SIZE)
3185 goto out;
3186
3187 if (unlikely(trace_recursive_lock(cpu_buffer)))
3188 goto out;
3189
3190 event = rb_reserve_next_event(buffer, cpu_buffer, length);
3191 if (!event)
3192 goto out_unlock;
3193
3194 body = rb_event_data(event);
3195
3196 memcpy(body, data, length);
3197
3198 rb_commit(cpu_buffer, event);
3199
3200 rb_wakeups(buffer, cpu_buffer);
3201
3202 ret = 0;
3203
3204 out_unlock:
3205 trace_recursive_unlock(cpu_buffer);
3206
3207 out:
3208 preempt_enable_notrace();
3209
3210 return ret;
3211}
3212EXPORT_SYMBOL_GPL(ring_buffer_write);
3213
3214static bool rb_per_cpu_empty(struct ring_buffer_per_cpu *cpu_buffer)
3215{
3216 struct buffer_page *reader = cpu_buffer->reader_page;
3217 struct buffer_page *head = rb_set_head_page(cpu_buffer);
3218 struct buffer_page *commit = cpu_buffer->commit_page;
3219
3220 /* In case of error, head will be NULL */
3221 if (unlikely(!head))
3222 return true;
3223
Olivier Deprez0e641232021-09-23 10:07:05 +02003224 /* Reader should exhaust content in reader page */
3225 if (reader->read != rb_page_commit(reader))
3226 return false;
3227
3228 /*
3229 * If writers are committing on the reader page, knowing all
3230 * committed content has been read, the ring buffer is empty.
3231 */
3232 if (commit == reader)
3233 return true;
3234
3235 /*
3236 * If writers are committing on a page other than reader page
3237 * and head page, there should always be content to read.
3238 */
3239 if (commit != head)
3240 return false;
3241
3242 /*
3243 * Writers are committing on the head page, we just need
3244 * to care about there're committed data, and the reader will
3245 * swap reader page with head page when it is to read data.
3246 */
3247 return rb_page_commit(commit) == 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003248}
3249
3250/**
3251 * ring_buffer_record_disable - stop all writes into the buffer
3252 * @buffer: The ring buffer to stop writes to.
3253 *
3254 * This prevents all writes to the buffer. Any attempt to write
3255 * to the buffer after this will fail and return NULL.
3256 *
David Brazdil0f672f62019-12-10 10:32:29 +00003257 * The caller should call synchronize_rcu() after this.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003258 */
3259void ring_buffer_record_disable(struct ring_buffer *buffer)
3260{
3261 atomic_inc(&buffer->record_disabled);
3262}
3263EXPORT_SYMBOL_GPL(ring_buffer_record_disable);
3264
3265/**
3266 * ring_buffer_record_enable - enable writes to the buffer
3267 * @buffer: The ring buffer to enable writes
3268 *
3269 * Note, multiple disables will need the same number of enables
3270 * to truly enable the writing (much like preempt_disable).
3271 */
3272void ring_buffer_record_enable(struct ring_buffer *buffer)
3273{
3274 atomic_dec(&buffer->record_disabled);
3275}
3276EXPORT_SYMBOL_GPL(ring_buffer_record_enable);
3277
3278/**
3279 * ring_buffer_record_off - stop all writes into the buffer
3280 * @buffer: The ring buffer to stop writes to.
3281 *
3282 * This prevents all writes to the buffer. Any attempt to write
3283 * to the buffer after this will fail and return NULL.
3284 *
3285 * This is different than ring_buffer_record_disable() as
3286 * it works like an on/off switch, where as the disable() version
3287 * must be paired with a enable().
3288 */
3289void ring_buffer_record_off(struct ring_buffer *buffer)
3290{
3291 unsigned int rd;
3292 unsigned int new_rd;
3293
3294 do {
3295 rd = atomic_read(&buffer->record_disabled);
3296 new_rd = rd | RB_BUFFER_OFF;
3297 } while (atomic_cmpxchg(&buffer->record_disabled, rd, new_rd) != rd);
3298}
3299EXPORT_SYMBOL_GPL(ring_buffer_record_off);
3300
3301/**
3302 * ring_buffer_record_on - restart writes into the buffer
3303 * @buffer: The ring buffer to start writes to.
3304 *
3305 * This enables all writes to the buffer that was disabled by
3306 * ring_buffer_record_off().
3307 *
3308 * This is different than ring_buffer_record_enable() as
3309 * it works like an on/off switch, where as the enable() version
3310 * must be paired with a disable().
3311 */
3312void ring_buffer_record_on(struct ring_buffer *buffer)
3313{
3314 unsigned int rd;
3315 unsigned int new_rd;
3316
3317 do {
3318 rd = atomic_read(&buffer->record_disabled);
3319 new_rd = rd & ~RB_BUFFER_OFF;
3320 } while (atomic_cmpxchg(&buffer->record_disabled, rd, new_rd) != rd);
3321}
3322EXPORT_SYMBOL_GPL(ring_buffer_record_on);
3323
3324/**
3325 * ring_buffer_record_is_on - return true if the ring buffer can write
3326 * @buffer: The ring buffer to see if write is enabled
3327 *
3328 * Returns true if the ring buffer is in a state that it accepts writes.
3329 */
3330bool ring_buffer_record_is_on(struct ring_buffer *buffer)
3331{
3332 return !atomic_read(&buffer->record_disabled);
3333}
3334
3335/**
3336 * ring_buffer_record_is_set_on - return true if the ring buffer is set writable
3337 * @buffer: The ring buffer to see if write is set enabled
3338 *
3339 * Returns true if the ring buffer is set writable by ring_buffer_record_on().
3340 * Note that this does NOT mean it is in a writable state.
3341 *
3342 * It may return true when the ring buffer has been disabled by
3343 * ring_buffer_record_disable(), as that is a temporary disabling of
3344 * the ring buffer.
3345 */
3346bool ring_buffer_record_is_set_on(struct ring_buffer *buffer)
3347{
3348 return !(atomic_read(&buffer->record_disabled) & RB_BUFFER_OFF);
3349}
3350
3351/**
3352 * ring_buffer_record_disable_cpu - stop all writes into the cpu_buffer
3353 * @buffer: The ring buffer to stop writes to.
3354 * @cpu: The CPU buffer to stop
3355 *
3356 * This prevents all writes to the buffer. Any attempt to write
3357 * to the buffer after this will fail and return NULL.
3358 *
David Brazdil0f672f62019-12-10 10:32:29 +00003359 * The caller should call synchronize_rcu() after this.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003360 */
3361void ring_buffer_record_disable_cpu(struct ring_buffer *buffer, int cpu)
3362{
3363 struct ring_buffer_per_cpu *cpu_buffer;
3364
3365 if (!cpumask_test_cpu(cpu, buffer->cpumask))
3366 return;
3367
3368 cpu_buffer = buffer->buffers[cpu];
3369 atomic_inc(&cpu_buffer->record_disabled);
3370}
3371EXPORT_SYMBOL_GPL(ring_buffer_record_disable_cpu);
3372
3373/**
3374 * ring_buffer_record_enable_cpu - enable writes to the buffer
3375 * @buffer: The ring buffer to enable writes
3376 * @cpu: The CPU to enable.
3377 *
3378 * Note, multiple disables will need the same number of enables
3379 * to truly enable the writing (much like preempt_disable).
3380 */
3381void ring_buffer_record_enable_cpu(struct ring_buffer *buffer, int cpu)
3382{
3383 struct ring_buffer_per_cpu *cpu_buffer;
3384
3385 if (!cpumask_test_cpu(cpu, buffer->cpumask))
3386 return;
3387
3388 cpu_buffer = buffer->buffers[cpu];
3389 atomic_dec(&cpu_buffer->record_disabled);
3390}
3391EXPORT_SYMBOL_GPL(ring_buffer_record_enable_cpu);
3392
3393/*
3394 * The total entries in the ring buffer is the running counter
3395 * of entries entered into the ring buffer, minus the sum of
3396 * the entries read from the ring buffer and the number of
3397 * entries that were overwritten.
3398 */
3399static inline unsigned long
3400rb_num_of_entries(struct ring_buffer_per_cpu *cpu_buffer)
3401{
3402 return local_read(&cpu_buffer->entries) -
3403 (local_read(&cpu_buffer->overrun) + cpu_buffer->read);
3404}
3405
3406/**
3407 * ring_buffer_oldest_event_ts - get the oldest event timestamp from the buffer
3408 * @buffer: The ring buffer
3409 * @cpu: The per CPU buffer to read from.
3410 */
3411u64 ring_buffer_oldest_event_ts(struct ring_buffer *buffer, int cpu)
3412{
3413 unsigned long flags;
3414 struct ring_buffer_per_cpu *cpu_buffer;
3415 struct buffer_page *bpage;
3416 u64 ret = 0;
3417
3418 if (!cpumask_test_cpu(cpu, buffer->cpumask))
3419 return 0;
3420
3421 cpu_buffer = buffer->buffers[cpu];
3422 raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
3423 /*
3424 * if the tail is on reader_page, oldest time stamp is on the reader
3425 * page
3426 */
3427 if (cpu_buffer->tail_page == cpu_buffer->reader_page)
3428 bpage = cpu_buffer->reader_page;
3429 else
3430 bpage = rb_set_head_page(cpu_buffer);
3431 if (bpage)
3432 ret = bpage->page->time_stamp;
3433 raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
3434
3435 return ret;
3436}
3437EXPORT_SYMBOL_GPL(ring_buffer_oldest_event_ts);
3438
3439/**
3440 * ring_buffer_bytes_cpu - get the number of bytes consumed in a cpu buffer
3441 * @buffer: The ring buffer
3442 * @cpu: The per CPU buffer to read from.
3443 */
3444unsigned long ring_buffer_bytes_cpu(struct ring_buffer *buffer, int cpu)
3445{
3446 struct ring_buffer_per_cpu *cpu_buffer;
3447 unsigned long ret;
3448
3449 if (!cpumask_test_cpu(cpu, buffer->cpumask))
3450 return 0;
3451
3452 cpu_buffer = buffer->buffers[cpu];
3453 ret = local_read(&cpu_buffer->entries_bytes) - cpu_buffer->read_bytes;
3454
3455 return ret;
3456}
3457EXPORT_SYMBOL_GPL(ring_buffer_bytes_cpu);
3458
3459/**
3460 * ring_buffer_entries_cpu - get the number of entries in a cpu buffer
3461 * @buffer: The ring buffer
3462 * @cpu: The per CPU buffer to get the entries from.
3463 */
3464unsigned long ring_buffer_entries_cpu(struct ring_buffer *buffer, int cpu)
3465{
3466 struct ring_buffer_per_cpu *cpu_buffer;
3467
3468 if (!cpumask_test_cpu(cpu, buffer->cpumask))
3469 return 0;
3470
3471 cpu_buffer = buffer->buffers[cpu];
3472
3473 return rb_num_of_entries(cpu_buffer);
3474}
3475EXPORT_SYMBOL_GPL(ring_buffer_entries_cpu);
3476
3477/**
3478 * ring_buffer_overrun_cpu - get the number of overruns caused by the ring
3479 * buffer wrapping around (only if RB_FL_OVERWRITE is on).
3480 * @buffer: The ring buffer
3481 * @cpu: The per CPU buffer to get the number of overruns from
3482 */
3483unsigned long ring_buffer_overrun_cpu(struct ring_buffer *buffer, int cpu)
3484{
3485 struct ring_buffer_per_cpu *cpu_buffer;
3486 unsigned long ret;
3487
3488 if (!cpumask_test_cpu(cpu, buffer->cpumask))
3489 return 0;
3490
3491 cpu_buffer = buffer->buffers[cpu];
3492 ret = local_read(&cpu_buffer->overrun);
3493
3494 return ret;
3495}
3496EXPORT_SYMBOL_GPL(ring_buffer_overrun_cpu);
3497
3498/**
3499 * ring_buffer_commit_overrun_cpu - get the number of overruns caused by
3500 * commits failing due to the buffer wrapping around while there are uncommitted
3501 * events, such as during an interrupt storm.
3502 * @buffer: The ring buffer
3503 * @cpu: The per CPU buffer to get the number of overruns from
3504 */
3505unsigned long
3506ring_buffer_commit_overrun_cpu(struct ring_buffer *buffer, int cpu)
3507{
3508 struct ring_buffer_per_cpu *cpu_buffer;
3509 unsigned long ret;
3510
3511 if (!cpumask_test_cpu(cpu, buffer->cpumask))
3512 return 0;
3513
3514 cpu_buffer = buffer->buffers[cpu];
3515 ret = local_read(&cpu_buffer->commit_overrun);
3516
3517 return ret;
3518}
3519EXPORT_SYMBOL_GPL(ring_buffer_commit_overrun_cpu);
3520
3521/**
3522 * ring_buffer_dropped_events_cpu - get the number of dropped events caused by
3523 * the ring buffer filling up (only if RB_FL_OVERWRITE is off).
3524 * @buffer: The ring buffer
3525 * @cpu: The per CPU buffer to get the number of overruns from
3526 */
3527unsigned long
3528ring_buffer_dropped_events_cpu(struct ring_buffer *buffer, int cpu)
3529{
3530 struct ring_buffer_per_cpu *cpu_buffer;
3531 unsigned long ret;
3532
3533 if (!cpumask_test_cpu(cpu, buffer->cpumask))
3534 return 0;
3535
3536 cpu_buffer = buffer->buffers[cpu];
3537 ret = local_read(&cpu_buffer->dropped_events);
3538
3539 return ret;
3540}
3541EXPORT_SYMBOL_GPL(ring_buffer_dropped_events_cpu);
3542
3543/**
3544 * ring_buffer_read_events_cpu - get the number of events successfully read
3545 * @buffer: The ring buffer
3546 * @cpu: The per CPU buffer to get the number of events read
3547 */
3548unsigned long
3549ring_buffer_read_events_cpu(struct ring_buffer *buffer, int cpu)
3550{
3551 struct ring_buffer_per_cpu *cpu_buffer;
3552
3553 if (!cpumask_test_cpu(cpu, buffer->cpumask))
3554 return 0;
3555
3556 cpu_buffer = buffer->buffers[cpu];
3557 return cpu_buffer->read;
3558}
3559EXPORT_SYMBOL_GPL(ring_buffer_read_events_cpu);
3560
3561/**
3562 * ring_buffer_entries - get the number of entries in a buffer
3563 * @buffer: The ring buffer
3564 *
3565 * Returns the total number of entries in the ring buffer
3566 * (all CPU entries)
3567 */
3568unsigned long ring_buffer_entries(struct ring_buffer *buffer)
3569{
3570 struct ring_buffer_per_cpu *cpu_buffer;
3571 unsigned long entries = 0;
3572 int cpu;
3573
3574 /* if you care about this being correct, lock the buffer */
3575 for_each_buffer_cpu(buffer, cpu) {
3576 cpu_buffer = buffer->buffers[cpu];
3577 entries += rb_num_of_entries(cpu_buffer);
3578 }
3579
3580 return entries;
3581}
3582EXPORT_SYMBOL_GPL(ring_buffer_entries);
3583
3584/**
3585 * ring_buffer_overruns - get the number of overruns in buffer
3586 * @buffer: The ring buffer
3587 *
3588 * Returns the total number of overruns in the ring buffer
3589 * (all CPU entries)
3590 */
3591unsigned long ring_buffer_overruns(struct ring_buffer *buffer)
3592{
3593 struct ring_buffer_per_cpu *cpu_buffer;
3594 unsigned long overruns = 0;
3595 int cpu;
3596
3597 /* if you care about this being correct, lock the buffer */
3598 for_each_buffer_cpu(buffer, cpu) {
3599 cpu_buffer = buffer->buffers[cpu];
3600 overruns += local_read(&cpu_buffer->overrun);
3601 }
3602
3603 return overruns;
3604}
3605EXPORT_SYMBOL_GPL(ring_buffer_overruns);
3606
3607static void rb_iter_reset(struct ring_buffer_iter *iter)
3608{
3609 struct ring_buffer_per_cpu *cpu_buffer = iter->cpu_buffer;
3610
3611 /* Iterator usage is expected to have record disabled */
3612 iter->head_page = cpu_buffer->reader_page;
3613 iter->head = cpu_buffer->reader_page->read;
3614
3615 iter->cache_reader_page = iter->head_page;
3616 iter->cache_read = cpu_buffer->read;
3617
3618 if (iter->head)
3619 iter->read_stamp = cpu_buffer->read_stamp;
3620 else
3621 iter->read_stamp = iter->head_page->page->time_stamp;
3622}
3623
3624/**
3625 * ring_buffer_iter_reset - reset an iterator
3626 * @iter: The iterator to reset
3627 *
3628 * Resets the iterator, so that it will start from the beginning
3629 * again.
3630 */
3631void ring_buffer_iter_reset(struct ring_buffer_iter *iter)
3632{
3633 struct ring_buffer_per_cpu *cpu_buffer;
3634 unsigned long flags;
3635
3636 if (!iter)
3637 return;
3638
3639 cpu_buffer = iter->cpu_buffer;
3640
3641 raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
3642 rb_iter_reset(iter);
3643 raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
3644}
3645EXPORT_SYMBOL_GPL(ring_buffer_iter_reset);
3646
3647/**
3648 * ring_buffer_iter_empty - check if an iterator has no more to read
3649 * @iter: The iterator to check
3650 */
3651int ring_buffer_iter_empty(struct ring_buffer_iter *iter)
3652{
3653 struct ring_buffer_per_cpu *cpu_buffer;
3654 struct buffer_page *reader;
3655 struct buffer_page *head_page;
3656 struct buffer_page *commit_page;
3657 unsigned commit;
3658
3659 cpu_buffer = iter->cpu_buffer;
3660
3661 /* Remember, trace recording is off when iterator is in use */
3662 reader = cpu_buffer->reader_page;
3663 head_page = cpu_buffer->head_page;
3664 commit_page = cpu_buffer->commit_page;
3665 commit = rb_page_commit(commit_page);
3666
3667 return ((iter->head_page == commit_page && iter->head == commit) ||
3668 (iter->head_page == reader && commit_page == head_page &&
3669 head_page->read == commit &&
3670 iter->head == rb_page_commit(cpu_buffer->reader_page)));
3671}
3672EXPORT_SYMBOL_GPL(ring_buffer_iter_empty);
3673
3674static void
3675rb_update_read_stamp(struct ring_buffer_per_cpu *cpu_buffer,
3676 struct ring_buffer_event *event)
3677{
3678 u64 delta;
3679
3680 switch (event->type_len) {
3681 case RINGBUF_TYPE_PADDING:
3682 return;
3683
3684 case RINGBUF_TYPE_TIME_EXTEND:
3685 delta = ring_buffer_event_time_stamp(event);
3686 cpu_buffer->read_stamp += delta;
3687 return;
3688
3689 case RINGBUF_TYPE_TIME_STAMP:
3690 delta = ring_buffer_event_time_stamp(event);
3691 cpu_buffer->read_stamp = delta;
3692 return;
3693
3694 case RINGBUF_TYPE_DATA:
3695 cpu_buffer->read_stamp += event->time_delta;
3696 return;
3697
3698 default:
3699 BUG();
3700 }
3701 return;
3702}
3703
3704static void
3705rb_update_iter_read_stamp(struct ring_buffer_iter *iter,
3706 struct ring_buffer_event *event)
3707{
3708 u64 delta;
3709
3710 switch (event->type_len) {
3711 case RINGBUF_TYPE_PADDING:
3712 return;
3713
3714 case RINGBUF_TYPE_TIME_EXTEND:
3715 delta = ring_buffer_event_time_stamp(event);
3716 iter->read_stamp += delta;
3717 return;
3718
3719 case RINGBUF_TYPE_TIME_STAMP:
3720 delta = ring_buffer_event_time_stamp(event);
3721 iter->read_stamp = delta;
3722 return;
3723
3724 case RINGBUF_TYPE_DATA:
3725 iter->read_stamp += event->time_delta;
3726 return;
3727
3728 default:
3729 BUG();
3730 }
3731 return;
3732}
3733
3734static struct buffer_page *
3735rb_get_reader_page(struct ring_buffer_per_cpu *cpu_buffer)
3736{
3737 struct buffer_page *reader = NULL;
3738 unsigned long overwrite;
3739 unsigned long flags;
3740 int nr_loops = 0;
3741 int ret;
3742
3743 local_irq_save(flags);
3744 arch_spin_lock(&cpu_buffer->lock);
3745
3746 again:
3747 /*
3748 * This should normally only loop twice. But because the
3749 * start of the reader inserts an empty page, it causes
3750 * a case where we will loop three times. There should be no
3751 * reason to loop four times (that I know of).
3752 */
3753 if (RB_WARN_ON(cpu_buffer, ++nr_loops > 3)) {
3754 reader = NULL;
3755 goto out;
3756 }
3757
3758 reader = cpu_buffer->reader_page;
3759
3760 /* If there's more to read, return this page */
3761 if (cpu_buffer->reader_page->read < rb_page_size(reader))
3762 goto out;
3763
3764 /* Never should we have an index greater than the size */
3765 if (RB_WARN_ON(cpu_buffer,
3766 cpu_buffer->reader_page->read > rb_page_size(reader)))
3767 goto out;
3768
3769 /* check if we caught up to the tail */
3770 reader = NULL;
3771 if (cpu_buffer->commit_page == cpu_buffer->reader_page)
3772 goto out;
3773
3774 /* Don't bother swapping if the ring buffer is empty */
3775 if (rb_num_of_entries(cpu_buffer) == 0)
3776 goto out;
3777
3778 /*
3779 * Reset the reader page to size zero.
3780 */
3781 local_set(&cpu_buffer->reader_page->write, 0);
3782 local_set(&cpu_buffer->reader_page->entries, 0);
3783 local_set(&cpu_buffer->reader_page->page->commit, 0);
3784 cpu_buffer->reader_page->real_end = 0;
3785
3786 spin:
3787 /*
3788 * Splice the empty reader page into the list around the head.
3789 */
3790 reader = rb_set_head_page(cpu_buffer);
3791 if (!reader)
3792 goto out;
3793 cpu_buffer->reader_page->list.next = rb_list_head(reader->list.next);
3794 cpu_buffer->reader_page->list.prev = reader->list.prev;
3795
3796 /*
3797 * cpu_buffer->pages just needs to point to the buffer, it
3798 * has no specific buffer page to point to. Lets move it out
3799 * of our way so we don't accidentally swap it.
3800 */
3801 cpu_buffer->pages = reader->list.prev;
3802
3803 /* The reader page will be pointing to the new head */
3804 rb_set_list_to_head(cpu_buffer, &cpu_buffer->reader_page->list);
3805
3806 /*
3807 * We want to make sure we read the overruns after we set up our
3808 * pointers to the next object. The writer side does a
3809 * cmpxchg to cross pages which acts as the mb on the writer
3810 * side. Note, the reader will constantly fail the swap
3811 * while the writer is updating the pointers, so this
3812 * guarantees that the overwrite recorded here is the one we
3813 * want to compare with the last_overrun.
3814 */
3815 smp_mb();
3816 overwrite = local_read(&(cpu_buffer->overrun));
3817
3818 /*
3819 * Here's the tricky part.
3820 *
3821 * We need to move the pointer past the header page.
3822 * But we can only do that if a writer is not currently
3823 * moving it. The page before the header page has the
3824 * flag bit '1' set if it is pointing to the page we want.
3825 * but if the writer is in the process of moving it
3826 * than it will be '2' or already moved '0'.
3827 */
3828
3829 ret = rb_head_page_replace(reader, cpu_buffer->reader_page);
3830
3831 /*
3832 * If we did not convert it, then we must try again.
3833 */
3834 if (!ret)
3835 goto spin;
3836
3837 /*
David Brazdil0f672f62019-12-10 10:32:29 +00003838 * Yay! We succeeded in replacing the page.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003839 *
3840 * Now make the new head point back to the reader page.
3841 */
3842 rb_list_head(reader->list.next)->prev = &cpu_buffer->reader_page->list;
3843 rb_inc_page(cpu_buffer, &cpu_buffer->head_page);
3844
David Brazdil0f672f62019-12-10 10:32:29 +00003845 local_inc(&cpu_buffer->pages_read);
3846
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003847 /* Finally update the reader page to the new head */
3848 cpu_buffer->reader_page = reader;
3849 cpu_buffer->reader_page->read = 0;
3850
3851 if (overwrite != cpu_buffer->last_overrun) {
3852 cpu_buffer->lost_events = overwrite - cpu_buffer->last_overrun;
3853 cpu_buffer->last_overrun = overwrite;
3854 }
3855
3856 goto again;
3857
3858 out:
3859 /* Update the read_stamp on the first event */
3860 if (reader && reader->read == 0)
3861 cpu_buffer->read_stamp = reader->page->time_stamp;
3862
3863 arch_spin_unlock(&cpu_buffer->lock);
3864 local_irq_restore(flags);
3865
3866 return reader;
3867}
3868
3869static void rb_advance_reader(struct ring_buffer_per_cpu *cpu_buffer)
3870{
3871 struct ring_buffer_event *event;
3872 struct buffer_page *reader;
3873 unsigned length;
3874
3875 reader = rb_get_reader_page(cpu_buffer);
3876
3877 /* This function should not be called when buffer is empty */
3878 if (RB_WARN_ON(cpu_buffer, !reader))
3879 return;
3880
3881 event = rb_reader_event(cpu_buffer);
3882
3883 if (event->type_len <= RINGBUF_TYPE_DATA_TYPE_LEN_MAX)
3884 cpu_buffer->read++;
3885
3886 rb_update_read_stamp(cpu_buffer, event);
3887
3888 length = rb_event_length(event);
3889 cpu_buffer->reader_page->read += length;
3890}
3891
3892static void rb_advance_iter(struct ring_buffer_iter *iter)
3893{
3894 struct ring_buffer_per_cpu *cpu_buffer;
3895 struct ring_buffer_event *event;
3896 unsigned length;
3897
3898 cpu_buffer = iter->cpu_buffer;
3899
3900 /*
3901 * Check if we are at the end of the buffer.
3902 */
3903 if (iter->head >= rb_page_size(iter->head_page)) {
3904 /* discarded commits can make the page empty */
3905 if (iter->head_page == cpu_buffer->commit_page)
3906 return;
3907 rb_inc_iter(iter);
3908 return;
3909 }
3910
3911 event = rb_iter_head_event(iter);
3912
3913 length = rb_event_length(event);
3914
3915 /*
3916 * This should not be called to advance the header if we are
3917 * at the tail of the buffer.
3918 */
3919 if (RB_WARN_ON(cpu_buffer,
3920 (iter->head_page == cpu_buffer->commit_page) &&
3921 (iter->head + length > rb_commit_index(cpu_buffer))))
3922 return;
3923
3924 rb_update_iter_read_stamp(iter, event);
3925
3926 iter->head += length;
3927
3928 /* check for end of page padding */
3929 if ((iter->head >= rb_page_size(iter->head_page)) &&
3930 (iter->head_page != cpu_buffer->commit_page))
3931 rb_inc_iter(iter);
3932}
3933
3934static int rb_lost_events(struct ring_buffer_per_cpu *cpu_buffer)
3935{
3936 return cpu_buffer->lost_events;
3937}
3938
3939static struct ring_buffer_event *
3940rb_buffer_peek(struct ring_buffer_per_cpu *cpu_buffer, u64 *ts,
3941 unsigned long *lost_events)
3942{
3943 struct ring_buffer_event *event;
3944 struct buffer_page *reader;
3945 int nr_loops = 0;
3946
3947 if (ts)
3948 *ts = 0;
3949 again:
3950 /*
3951 * We repeat when a time extend is encountered.
3952 * Since the time extend is always attached to a data event,
3953 * we should never loop more than once.
3954 * (We never hit the following condition more than twice).
3955 */
3956 if (RB_WARN_ON(cpu_buffer, ++nr_loops > 2))
3957 return NULL;
3958
3959 reader = rb_get_reader_page(cpu_buffer);
3960 if (!reader)
3961 return NULL;
3962
3963 event = rb_reader_event(cpu_buffer);
3964
3965 switch (event->type_len) {
3966 case RINGBUF_TYPE_PADDING:
3967 if (rb_null_event(event))
3968 RB_WARN_ON(cpu_buffer, 1);
3969 /*
3970 * Because the writer could be discarding every
3971 * event it creates (which would probably be bad)
3972 * if we were to go back to "again" then we may never
3973 * catch up, and will trigger the warn on, or lock
3974 * the box. Return the padding, and we will release
3975 * the current locks, and try again.
3976 */
3977 return event;
3978
3979 case RINGBUF_TYPE_TIME_EXTEND:
3980 /* Internal data, OK to advance */
3981 rb_advance_reader(cpu_buffer);
3982 goto again;
3983
3984 case RINGBUF_TYPE_TIME_STAMP:
3985 if (ts) {
3986 *ts = ring_buffer_event_time_stamp(event);
3987 ring_buffer_normalize_time_stamp(cpu_buffer->buffer,
3988 cpu_buffer->cpu, ts);
3989 }
3990 /* Internal data, OK to advance */
3991 rb_advance_reader(cpu_buffer);
3992 goto again;
3993
3994 case RINGBUF_TYPE_DATA:
3995 if (ts && !(*ts)) {
3996 *ts = cpu_buffer->read_stamp + event->time_delta;
3997 ring_buffer_normalize_time_stamp(cpu_buffer->buffer,
3998 cpu_buffer->cpu, ts);
3999 }
4000 if (lost_events)
4001 *lost_events = rb_lost_events(cpu_buffer);
4002 return event;
4003
4004 default:
4005 BUG();
4006 }
4007
4008 return NULL;
4009}
4010EXPORT_SYMBOL_GPL(ring_buffer_peek);
4011
4012static struct ring_buffer_event *
4013rb_iter_peek(struct ring_buffer_iter *iter, u64 *ts)
4014{
4015 struct ring_buffer *buffer;
4016 struct ring_buffer_per_cpu *cpu_buffer;
4017 struct ring_buffer_event *event;
4018 int nr_loops = 0;
4019
4020 if (ts)
4021 *ts = 0;
4022
4023 cpu_buffer = iter->cpu_buffer;
4024 buffer = cpu_buffer->buffer;
4025
4026 /*
4027 * Check if someone performed a consuming read to
4028 * the buffer. A consuming read invalidates the iterator
4029 * and we need to reset the iterator in this case.
4030 */
4031 if (unlikely(iter->cache_read != cpu_buffer->read ||
4032 iter->cache_reader_page != cpu_buffer->reader_page))
4033 rb_iter_reset(iter);
4034
4035 again:
4036 if (ring_buffer_iter_empty(iter))
4037 return NULL;
4038
4039 /*
4040 * We repeat when a time extend is encountered or we hit
4041 * the end of the page. Since the time extend is always attached
4042 * to a data event, we should never loop more than three times.
4043 * Once for going to next page, once on time extend, and
4044 * finally once to get the event.
4045 * (We never hit the following condition more than thrice).
4046 */
4047 if (RB_WARN_ON(cpu_buffer, ++nr_loops > 3))
4048 return NULL;
4049
4050 if (rb_per_cpu_empty(cpu_buffer))
4051 return NULL;
4052
4053 if (iter->head >= rb_page_size(iter->head_page)) {
4054 rb_inc_iter(iter);
4055 goto again;
4056 }
4057
4058 event = rb_iter_head_event(iter);
4059
4060 switch (event->type_len) {
4061 case RINGBUF_TYPE_PADDING:
4062 if (rb_null_event(event)) {
4063 rb_inc_iter(iter);
4064 goto again;
4065 }
4066 rb_advance_iter(iter);
4067 return event;
4068
4069 case RINGBUF_TYPE_TIME_EXTEND:
4070 /* Internal data, OK to advance */
4071 rb_advance_iter(iter);
4072 goto again;
4073
4074 case RINGBUF_TYPE_TIME_STAMP:
4075 if (ts) {
4076 *ts = ring_buffer_event_time_stamp(event);
4077 ring_buffer_normalize_time_stamp(cpu_buffer->buffer,
4078 cpu_buffer->cpu, ts);
4079 }
4080 /* Internal data, OK to advance */
4081 rb_advance_iter(iter);
4082 goto again;
4083
4084 case RINGBUF_TYPE_DATA:
4085 if (ts && !(*ts)) {
4086 *ts = iter->read_stamp + event->time_delta;
4087 ring_buffer_normalize_time_stamp(buffer,
4088 cpu_buffer->cpu, ts);
4089 }
4090 return event;
4091
4092 default:
4093 BUG();
4094 }
4095
4096 return NULL;
4097}
4098EXPORT_SYMBOL_GPL(ring_buffer_iter_peek);
4099
4100static inline bool rb_reader_lock(struct ring_buffer_per_cpu *cpu_buffer)
4101{
4102 if (likely(!in_nmi())) {
4103 raw_spin_lock(&cpu_buffer->reader_lock);
4104 return true;
4105 }
4106
4107 /*
4108 * If an NMI die dumps out the content of the ring buffer
4109 * trylock must be used to prevent a deadlock if the NMI
4110 * preempted a task that holds the ring buffer locks. If
4111 * we get the lock then all is fine, if not, then continue
4112 * to do the read, but this can corrupt the ring buffer,
4113 * so it must be permanently disabled from future writes.
4114 * Reading from NMI is a oneshot deal.
4115 */
4116 if (raw_spin_trylock(&cpu_buffer->reader_lock))
4117 return true;
4118
4119 /* Continue without locking, but disable the ring buffer */
4120 atomic_inc(&cpu_buffer->record_disabled);
4121 return false;
4122}
4123
4124static inline void
4125rb_reader_unlock(struct ring_buffer_per_cpu *cpu_buffer, bool locked)
4126{
4127 if (likely(locked))
4128 raw_spin_unlock(&cpu_buffer->reader_lock);
4129 return;
4130}
4131
4132/**
4133 * ring_buffer_peek - peek at the next event to be read
4134 * @buffer: The ring buffer to read
4135 * @cpu: The cpu to peak at
4136 * @ts: The timestamp counter of this event.
4137 * @lost_events: a variable to store if events were lost (may be NULL)
4138 *
4139 * This will return the event that will be read next, but does
4140 * not consume the data.
4141 */
4142struct ring_buffer_event *
4143ring_buffer_peek(struct ring_buffer *buffer, int cpu, u64 *ts,
4144 unsigned long *lost_events)
4145{
4146 struct ring_buffer_per_cpu *cpu_buffer = buffer->buffers[cpu];
4147 struct ring_buffer_event *event;
4148 unsigned long flags;
4149 bool dolock;
4150
4151 if (!cpumask_test_cpu(cpu, buffer->cpumask))
4152 return NULL;
4153
4154 again:
4155 local_irq_save(flags);
4156 dolock = rb_reader_lock(cpu_buffer);
4157 event = rb_buffer_peek(cpu_buffer, ts, lost_events);
4158 if (event && event->type_len == RINGBUF_TYPE_PADDING)
4159 rb_advance_reader(cpu_buffer);
4160 rb_reader_unlock(cpu_buffer, dolock);
4161 local_irq_restore(flags);
4162
4163 if (event && event->type_len == RINGBUF_TYPE_PADDING)
4164 goto again;
4165
4166 return event;
4167}
4168
4169/**
4170 * ring_buffer_iter_peek - peek at the next event to be read
4171 * @iter: The ring buffer iterator
4172 * @ts: The timestamp counter of this event.
4173 *
4174 * This will return the event that will be read next, but does
4175 * not increment the iterator.
4176 */
4177struct ring_buffer_event *
4178ring_buffer_iter_peek(struct ring_buffer_iter *iter, u64 *ts)
4179{
4180 struct ring_buffer_per_cpu *cpu_buffer = iter->cpu_buffer;
4181 struct ring_buffer_event *event;
4182 unsigned long flags;
4183
4184 again:
4185 raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
4186 event = rb_iter_peek(iter, ts);
4187 raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
4188
4189 if (event && event->type_len == RINGBUF_TYPE_PADDING)
4190 goto again;
4191
4192 return event;
4193}
4194
4195/**
4196 * ring_buffer_consume - return an event and consume it
4197 * @buffer: The ring buffer to get the next event from
4198 * @cpu: the cpu to read the buffer from
4199 * @ts: a variable to store the timestamp (may be NULL)
4200 * @lost_events: a variable to store if events were lost (may be NULL)
4201 *
4202 * Returns the next event in the ring buffer, and that event is consumed.
4203 * Meaning, that sequential reads will keep returning a different event,
4204 * and eventually empty the ring buffer if the producer is slower.
4205 */
4206struct ring_buffer_event *
4207ring_buffer_consume(struct ring_buffer *buffer, int cpu, u64 *ts,
4208 unsigned long *lost_events)
4209{
4210 struct ring_buffer_per_cpu *cpu_buffer;
4211 struct ring_buffer_event *event = NULL;
4212 unsigned long flags;
4213 bool dolock;
4214
4215 again:
4216 /* might be called in atomic */
4217 preempt_disable();
4218
4219 if (!cpumask_test_cpu(cpu, buffer->cpumask))
4220 goto out;
4221
4222 cpu_buffer = buffer->buffers[cpu];
4223 local_irq_save(flags);
4224 dolock = rb_reader_lock(cpu_buffer);
4225
4226 event = rb_buffer_peek(cpu_buffer, ts, lost_events);
4227 if (event) {
4228 cpu_buffer->lost_events = 0;
4229 rb_advance_reader(cpu_buffer);
4230 }
4231
4232 rb_reader_unlock(cpu_buffer, dolock);
4233 local_irq_restore(flags);
4234
4235 out:
4236 preempt_enable();
4237
4238 if (event && event->type_len == RINGBUF_TYPE_PADDING)
4239 goto again;
4240
4241 return event;
4242}
4243EXPORT_SYMBOL_GPL(ring_buffer_consume);
4244
4245/**
4246 * ring_buffer_read_prepare - Prepare for a non consuming read of the buffer
4247 * @buffer: The ring buffer to read from
4248 * @cpu: The cpu buffer to iterate over
David Brazdil0f672f62019-12-10 10:32:29 +00004249 * @flags: gfp flags to use for memory allocation
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004250 *
4251 * This performs the initial preparations necessary to iterate
4252 * through the buffer. Memory is allocated, buffer recording
4253 * is disabled, and the iterator pointer is returned to the caller.
4254 *
4255 * Disabling buffer recording prevents the reading from being
4256 * corrupted. This is not a consuming read, so a producer is not
4257 * expected.
4258 *
4259 * After a sequence of ring_buffer_read_prepare calls, the user is
4260 * expected to make at least one call to ring_buffer_read_prepare_sync.
4261 * Afterwards, ring_buffer_read_start is invoked to get things going
4262 * for real.
4263 *
4264 * This overall must be paired with ring_buffer_read_finish.
4265 */
4266struct ring_buffer_iter *
David Brazdil0f672f62019-12-10 10:32:29 +00004267ring_buffer_read_prepare(struct ring_buffer *buffer, int cpu, gfp_t flags)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004268{
4269 struct ring_buffer_per_cpu *cpu_buffer;
4270 struct ring_buffer_iter *iter;
4271
4272 if (!cpumask_test_cpu(cpu, buffer->cpumask))
4273 return NULL;
4274
David Brazdil0f672f62019-12-10 10:32:29 +00004275 iter = kmalloc(sizeof(*iter), flags);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004276 if (!iter)
4277 return NULL;
4278
4279 cpu_buffer = buffer->buffers[cpu];
4280
4281 iter->cpu_buffer = cpu_buffer;
4282
4283 atomic_inc(&buffer->resize_disabled);
4284 atomic_inc(&cpu_buffer->record_disabled);
4285
4286 return iter;
4287}
4288EXPORT_SYMBOL_GPL(ring_buffer_read_prepare);
4289
4290/**
4291 * ring_buffer_read_prepare_sync - Synchronize a set of prepare calls
4292 *
4293 * All previously invoked ring_buffer_read_prepare calls to prepare
4294 * iterators will be synchronized. Afterwards, read_buffer_read_start
4295 * calls on those iterators are allowed.
4296 */
4297void
4298ring_buffer_read_prepare_sync(void)
4299{
David Brazdil0f672f62019-12-10 10:32:29 +00004300 synchronize_rcu();
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004301}
4302EXPORT_SYMBOL_GPL(ring_buffer_read_prepare_sync);
4303
4304/**
4305 * ring_buffer_read_start - start a non consuming read of the buffer
4306 * @iter: The iterator returned by ring_buffer_read_prepare
4307 *
4308 * This finalizes the startup of an iteration through the buffer.
4309 * The iterator comes from a call to ring_buffer_read_prepare and
4310 * an intervening ring_buffer_read_prepare_sync must have been
4311 * performed.
4312 *
4313 * Must be paired with ring_buffer_read_finish.
4314 */
4315void
4316ring_buffer_read_start(struct ring_buffer_iter *iter)
4317{
4318 struct ring_buffer_per_cpu *cpu_buffer;
4319 unsigned long flags;
4320
4321 if (!iter)
4322 return;
4323
4324 cpu_buffer = iter->cpu_buffer;
4325
4326 raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
4327 arch_spin_lock(&cpu_buffer->lock);
4328 rb_iter_reset(iter);
4329 arch_spin_unlock(&cpu_buffer->lock);
4330 raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
4331}
4332EXPORT_SYMBOL_GPL(ring_buffer_read_start);
4333
4334/**
4335 * ring_buffer_read_finish - finish reading the iterator of the buffer
4336 * @iter: The iterator retrieved by ring_buffer_start
4337 *
4338 * This re-enables the recording to the buffer, and frees the
4339 * iterator.
4340 */
4341void
4342ring_buffer_read_finish(struct ring_buffer_iter *iter)
4343{
4344 struct ring_buffer_per_cpu *cpu_buffer = iter->cpu_buffer;
4345 unsigned long flags;
4346
4347 /*
4348 * Ring buffer is disabled from recording, here's a good place
4349 * to check the integrity of the ring buffer.
4350 * Must prevent readers from trying to read, as the check
4351 * clears the HEAD page and readers require it.
4352 */
4353 raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
4354 rb_check_pages(cpu_buffer);
4355 raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
4356
4357 atomic_dec(&cpu_buffer->record_disabled);
4358 atomic_dec(&cpu_buffer->buffer->resize_disabled);
4359 kfree(iter);
4360}
4361EXPORT_SYMBOL_GPL(ring_buffer_read_finish);
4362
4363/**
4364 * ring_buffer_read - read the next item in the ring buffer by the iterator
4365 * @iter: The ring buffer iterator
4366 * @ts: The time stamp of the event read.
4367 *
4368 * This reads the next event in the ring buffer and increments the iterator.
4369 */
4370struct ring_buffer_event *
4371ring_buffer_read(struct ring_buffer_iter *iter, u64 *ts)
4372{
4373 struct ring_buffer_event *event;
4374 struct ring_buffer_per_cpu *cpu_buffer = iter->cpu_buffer;
4375 unsigned long flags;
4376
4377 raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
4378 again:
4379 event = rb_iter_peek(iter, ts);
4380 if (!event)
4381 goto out;
4382
4383 if (event->type_len == RINGBUF_TYPE_PADDING)
4384 goto again;
4385
4386 rb_advance_iter(iter);
4387 out:
4388 raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
4389
4390 return event;
4391}
4392EXPORT_SYMBOL_GPL(ring_buffer_read);
4393
4394/**
4395 * ring_buffer_size - return the size of the ring buffer (in bytes)
4396 * @buffer: The ring buffer.
4397 */
4398unsigned long ring_buffer_size(struct ring_buffer *buffer, int cpu)
4399{
4400 /*
4401 * Earlier, this method returned
4402 * BUF_PAGE_SIZE * buffer->nr_pages
4403 * Since the nr_pages field is now removed, we have converted this to
4404 * return the per cpu buffer value.
4405 */
4406 if (!cpumask_test_cpu(cpu, buffer->cpumask))
4407 return 0;
4408
4409 return BUF_PAGE_SIZE * buffer->buffers[cpu]->nr_pages;
4410}
4411EXPORT_SYMBOL_GPL(ring_buffer_size);
4412
4413static void
4414rb_reset_cpu(struct ring_buffer_per_cpu *cpu_buffer)
4415{
4416 rb_head_page_deactivate(cpu_buffer);
4417
4418 cpu_buffer->head_page
4419 = list_entry(cpu_buffer->pages, struct buffer_page, list);
4420 local_set(&cpu_buffer->head_page->write, 0);
4421 local_set(&cpu_buffer->head_page->entries, 0);
4422 local_set(&cpu_buffer->head_page->page->commit, 0);
4423
4424 cpu_buffer->head_page->read = 0;
4425
4426 cpu_buffer->tail_page = cpu_buffer->head_page;
4427 cpu_buffer->commit_page = cpu_buffer->head_page;
4428
4429 INIT_LIST_HEAD(&cpu_buffer->reader_page->list);
4430 INIT_LIST_HEAD(&cpu_buffer->new_pages);
4431 local_set(&cpu_buffer->reader_page->write, 0);
4432 local_set(&cpu_buffer->reader_page->entries, 0);
4433 local_set(&cpu_buffer->reader_page->page->commit, 0);
4434 cpu_buffer->reader_page->read = 0;
4435
4436 local_set(&cpu_buffer->entries_bytes, 0);
4437 local_set(&cpu_buffer->overrun, 0);
4438 local_set(&cpu_buffer->commit_overrun, 0);
4439 local_set(&cpu_buffer->dropped_events, 0);
4440 local_set(&cpu_buffer->entries, 0);
4441 local_set(&cpu_buffer->committing, 0);
4442 local_set(&cpu_buffer->commits, 0);
David Brazdil0f672f62019-12-10 10:32:29 +00004443 local_set(&cpu_buffer->pages_touched, 0);
4444 local_set(&cpu_buffer->pages_read, 0);
4445 cpu_buffer->last_pages_touch = 0;
4446 cpu_buffer->shortest_full = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004447 cpu_buffer->read = 0;
4448 cpu_buffer->read_bytes = 0;
4449
4450 cpu_buffer->write_stamp = 0;
4451 cpu_buffer->read_stamp = 0;
4452
4453 cpu_buffer->lost_events = 0;
4454 cpu_buffer->last_overrun = 0;
4455
4456 rb_head_page_activate(cpu_buffer);
4457}
4458
4459/**
4460 * ring_buffer_reset_cpu - reset a ring buffer per CPU buffer
4461 * @buffer: The ring buffer to reset a per cpu buffer of
4462 * @cpu: The CPU buffer to be reset
4463 */
4464void ring_buffer_reset_cpu(struct ring_buffer *buffer, int cpu)
4465{
4466 struct ring_buffer_per_cpu *cpu_buffer = buffer->buffers[cpu];
4467 unsigned long flags;
4468
4469 if (!cpumask_test_cpu(cpu, buffer->cpumask))
4470 return;
Olivier Deprez0e641232021-09-23 10:07:05 +02004471 /* prevent another thread from changing buffer sizes */
4472 mutex_lock(&buffer->mutex);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004473
4474 atomic_inc(&buffer->resize_disabled);
4475 atomic_inc(&cpu_buffer->record_disabled);
4476
4477 /* Make sure all commits have finished */
David Brazdil0f672f62019-12-10 10:32:29 +00004478 synchronize_rcu();
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004479
4480 raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
4481
4482 if (RB_WARN_ON(cpu_buffer, local_read(&cpu_buffer->committing)))
4483 goto out;
4484
4485 arch_spin_lock(&cpu_buffer->lock);
4486
4487 rb_reset_cpu(cpu_buffer);
4488
4489 arch_spin_unlock(&cpu_buffer->lock);
4490
4491 out:
4492 raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
4493
4494 atomic_dec(&cpu_buffer->record_disabled);
4495 atomic_dec(&buffer->resize_disabled);
Olivier Deprez0e641232021-09-23 10:07:05 +02004496
4497 mutex_unlock(&buffer->mutex);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004498}
4499EXPORT_SYMBOL_GPL(ring_buffer_reset_cpu);
4500
4501/**
4502 * ring_buffer_reset - reset a ring buffer
4503 * @buffer: The ring buffer to reset all cpu buffers
4504 */
4505void ring_buffer_reset(struct ring_buffer *buffer)
4506{
4507 int cpu;
4508
4509 for_each_buffer_cpu(buffer, cpu)
4510 ring_buffer_reset_cpu(buffer, cpu);
4511}
4512EXPORT_SYMBOL_GPL(ring_buffer_reset);
4513
4514/**
4515 * rind_buffer_empty - is the ring buffer empty?
4516 * @buffer: The ring buffer to test
4517 */
4518bool ring_buffer_empty(struct ring_buffer *buffer)
4519{
4520 struct ring_buffer_per_cpu *cpu_buffer;
4521 unsigned long flags;
4522 bool dolock;
4523 int cpu;
4524 int ret;
4525
4526 /* yes this is racy, but if you don't like the race, lock the buffer */
4527 for_each_buffer_cpu(buffer, cpu) {
4528 cpu_buffer = buffer->buffers[cpu];
4529 local_irq_save(flags);
4530 dolock = rb_reader_lock(cpu_buffer);
4531 ret = rb_per_cpu_empty(cpu_buffer);
4532 rb_reader_unlock(cpu_buffer, dolock);
4533 local_irq_restore(flags);
4534
4535 if (!ret)
4536 return false;
4537 }
4538
4539 return true;
4540}
4541EXPORT_SYMBOL_GPL(ring_buffer_empty);
4542
4543/**
4544 * ring_buffer_empty_cpu - is a cpu buffer of a ring buffer empty?
4545 * @buffer: The ring buffer
4546 * @cpu: The CPU buffer to test
4547 */
4548bool ring_buffer_empty_cpu(struct ring_buffer *buffer, int cpu)
4549{
4550 struct ring_buffer_per_cpu *cpu_buffer;
4551 unsigned long flags;
4552 bool dolock;
4553 int ret;
4554
4555 if (!cpumask_test_cpu(cpu, buffer->cpumask))
4556 return true;
4557
4558 cpu_buffer = buffer->buffers[cpu];
4559 local_irq_save(flags);
4560 dolock = rb_reader_lock(cpu_buffer);
4561 ret = rb_per_cpu_empty(cpu_buffer);
4562 rb_reader_unlock(cpu_buffer, dolock);
4563 local_irq_restore(flags);
4564
4565 return ret;
4566}
4567EXPORT_SYMBOL_GPL(ring_buffer_empty_cpu);
4568
4569#ifdef CONFIG_RING_BUFFER_ALLOW_SWAP
4570/**
4571 * ring_buffer_swap_cpu - swap a CPU buffer between two ring buffers
4572 * @buffer_a: One buffer to swap with
4573 * @buffer_b: The other buffer to swap with
4574 *
4575 * This function is useful for tracers that want to take a "snapshot"
4576 * of a CPU buffer and has another back up buffer lying around.
4577 * it is expected that the tracer handles the cpu buffer not being
4578 * used at the moment.
4579 */
4580int ring_buffer_swap_cpu(struct ring_buffer *buffer_a,
4581 struct ring_buffer *buffer_b, int cpu)
4582{
4583 struct ring_buffer_per_cpu *cpu_buffer_a;
4584 struct ring_buffer_per_cpu *cpu_buffer_b;
4585 int ret = -EINVAL;
4586
4587 if (!cpumask_test_cpu(cpu, buffer_a->cpumask) ||
4588 !cpumask_test_cpu(cpu, buffer_b->cpumask))
4589 goto out;
4590
4591 cpu_buffer_a = buffer_a->buffers[cpu];
4592 cpu_buffer_b = buffer_b->buffers[cpu];
4593
4594 /* At least make sure the two buffers are somewhat the same */
4595 if (cpu_buffer_a->nr_pages != cpu_buffer_b->nr_pages)
4596 goto out;
4597
4598 ret = -EAGAIN;
4599
4600 if (atomic_read(&buffer_a->record_disabled))
4601 goto out;
4602
4603 if (atomic_read(&buffer_b->record_disabled))
4604 goto out;
4605
4606 if (atomic_read(&cpu_buffer_a->record_disabled))
4607 goto out;
4608
4609 if (atomic_read(&cpu_buffer_b->record_disabled))
4610 goto out;
4611
4612 /*
David Brazdil0f672f62019-12-10 10:32:29 +00004613 * We can't do a synchronize_rcu here because this
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004614 * function can be called in atomic context.
4615 * Normally this will be called from the same CPU as cpu.
4616 * If not it's up to the caller to protect this.
4617 */
4618 atomic_inc(&cpu_buffer_a->record_disabled);
4619 atomic_inc(&cpu_buffer_b->record_disabled);
4620
4621 ret = -EBUSY;
4622 if (local_read(&cpu_buffer_a->committing))
4623 goto out_dec;
4624 if (local_read(&cpu_buffer_b->committing))
4625 goto out_dec;
4626
4627 buffer_a->buffers[cpu] = cpu_buffer_b;
4628 buffer_b->buffers[cpu] = cpu_buffer_a;
4629
4630 cpu_buffer_b->buffer = buffer_a;
4631 cpu_buffer_a->buffer = buffer_b;
4632
4633 ret = 0;
4634
4635out_dec:
4636 atomic_dec(&cpu_buffer_a->record_disabled);
4637 atomic_dec(&cpu_buffer_b->record_disabled);
4638out:
4639 return ret;
4640}
4641EXPORT_SYMBOL_GPL(ring_buffer_swap_cpu);
4642#endif /* CONFIG_RING_BUFFER_ALLOW_SWAP */
4643
4644/**
4645 * ring_buffer_alloc_read_page - allocate a page to read from buffer
4646 * @buffer: the buffer to allocate for.
4647 * @cpu: the cpu buffer to allocate.
4648 *
4649 * This function is used in conjunction with ring_buffer_read_page.
4650 * When reading a full page from the ring buffer, these functions
4651 * can be used to speed up the process. The calling function should
4652 * allocate a few pages first with this function. Then when it
4653 * needs to get pages from the ring buffer, it passes the result
4654 * of this function into ring_buffer_read_page, which will swap
4655 * the page that was allocated, with the read page of the buffer.
4656 *
4657 * Returns:
4658 * The page allocated, or ERR_PTR
4659 */
4660void *ring_buffer_alloc_read_page(struct ring_buffer *buffer, int cpu)
4661{
4662 struct ring_buffer_per_cpu *cpu_buffer;
4663 struct buffer_data_page *bpage = NULL;
4664 unsigned long flags;
4665 struct page *page;
4666
4667 if (!cpumask_test_cpu(cpu, buffer->cpumask))
4668 return ERR_PTR(-ENODEV);
4669
4670 cpu_buffer = buffer->buffers[cpu];
4671 local_irq_save(flags);
4672 arch_spin_lock(&cpu_buffer->lock);
4673
4674 if (cpu_buffer->free_page) {
4675 bpage = cpu_buffer->free_page;
4676 cpu_buffer->free_page = NULL;
4677 }
4678
4679 arch_spin_unlock(&cpu_buffer->lock);
4680 local_irq_restore(flags);
4681
4682 if (bpage)
4683 goto out;
4684
4685 page = alloc_pages_node(cpu_to_node(cpu),
4686 GFP_KERNEL | __GFP_NORETRY, 0);
4687 if (!page)
4688 return ERR_PTR(-ENOMEM);
4689
4690 bpage = page_address(page);
4691
4692 out:
4693 rb_init_page(bpage);
4694
4695 return bpage;
4696}
4697EXPORT_SYMBOL_GPL(ring_buffer_alloc_read_page);
4698
4699/**
4700 * ring_buffer_free_read_page - free an allocated read page
4701 * @buffer: the buffer the page was allocate for
4702 * @cpu: the cpu buffer the page came from
4703 * @data: the page to free
4704 *
4705 * Free a page allocated from ring_buffer_alloc_read_page.
4706 */
4707void ring_buffer_free_read_page(struct ring_buffer *buffer, int cpu, void *data)
4708{
4709 struct ring_buffer_per_cpu *cpu_buffer = buffer->buffers[cpu];
4710 struct buffer_data_page *bpage = data;
4711 struct page *page = virt_to_page(bpage);
4712 unsigned long flags;
4713
4714 /* If the page is still in use someplace else, we can't reuse it */
4715 if (page_ref_count(page) > 1)
4716 goto out;
4717
4718 local_irq_save(flags);
4719 arch_spin_lock(&cpu_buffer->lock);
4720
4721 if (!cpu_buffer->free_page) {
4722 cpu_buffer->free_page = bpage;
4723 bpage = NULL;
4724 }
4725
4726 arch_spin_unlock(&cpu_buffer->lock);
4727 local_irq_restore(flags);
4728
4729 out:
4730 free_page((unsigned long)bpage);
4731}
4732EXPORT_SYMBOL_GPL(ring_buffer_free_read_page);
4733
4734/**
4735 * ring_buffer_read_page - extract a page from the ring buffer
4736 * @buffer: buffer to extract from
4737 * @data_page: the page to use allocated from ring_buffer_alloc_read_page
4738 * @len: amount to extract
4739 * @cpu: the cpu of the buffer to extract
4740 * @full: should the extraction only happen when the page is full.
4741 *
4742 * This function will pull out a page from the ring buffer and consume it.
4743 * @data_page must be the address of the variable that was returned
4744 * from ring_buffer_alloc_read_page. This is because the page might be used
4745 * to swap with a page in the ring buffer.
4746 *
4747 * for example:
4748 * rpage = ring_buffer_alloc_read_page(buffer, cpu);
4749 * if (IS_ERR(rpage))
4750 * return PTR_ERR(rpage);
4751 * ret = ring_buffer_read_page(buffer, &rpage, len, cpu, 0);
4752 * if (ret >= 0)
4753 * process_page(rpage, ret);
4754 *
4755 * When @full is set, the function will not return true unless
4756 * the writer is off the reader page.
4757 *
4758 * Note: it is up to the calling functions to handle sleeps and wakeups.
4759 * The ring buffer can be used anywhere in the kernel and can not
4760 * blindly call wake_up. The layer that uses the ring buffer must be
4761 * responsible for that.
4762 *
4763 * Returns:
4764 * >=0 if data has been transferred, returns the offset of consumed data.
4765 * <0 if no data has been transferred.
4766 */
4767int ring_buffer_read_page(struct ring_buffer *buffer,
4768 void **data_page, size_t len, int cpu, int full)
4769{
4770 struct ring_buffer_per_cpu *cpu_buffer = buffer->buffers[cpu];
4771 struct ring_buffer_event *event;
4772 struct buffer_data_page *bpage;
4773 struct buffer_page *reader;
4774 unsigned long missed_events;
4775 unsigned long flags;
4776 unsigned int commit;
4777 unsigned int read;
4778 u64 save_timestamp;
4779 int ret = -1;
4780
4781 if (!cpumask_test_cpu(cpu, buffer->cpumask))
4782 goto out;
4783
4784 /*
4785 * If len is not big enough to hold the page header, then
4786 * we can not copy anything.
4787 */
4788 if (len <= BUF_PAGE_HDR_SIZE)
4789 goto out;
4790
4791 len -= BUF_PAGE_HDR_SIZE;
4792
4793 if (!data_page)
4794 goto out;
4795
4796 bpage = *data_page;
4797 if (!bpage)
4798 goto out;
4799
4800 raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
4801
4802 reader = rb_get_reader_page(cpu_buffer);
4803 if (!reader)
4804 goto out_unlock;
4805
4806 event = rb_reader_event(cpu_buffer);
4807
4808 read = reader->read;
4809 commit = rb_page_commit(reader);
4810
4811 /* Check if any events were dropped */
4812 missed_events = cpu_buffer->lost_events;
4813
4814 /*
4815 * If this page has been partially read or
4816 * if len is not big enough to read the rest of the page or
4817 * a writer is still on the page, then
4818 * we must copy the data from the page to the buffer.
4819 * Otherwise, we can simply swap the page with the one passed in.
4820 */
4821 if (read || (len < (commit - read)) ||
4822 cpu_buffer->reader_page == cpu_buffer->commit_page) {
4823 struct buffer_data_page *rpage = cpu_buffer->reader_page->page;
4824 unsigned int rpos = read;
4825 unsigned int pos = 0;
4826 unsigned int size;
4827
4828 if (full)
4829 goto out_unlock;
4830
4831 if (len > (commit - read))
4832 len = (commit - read);
4833
4834 /* Always keep the time extend and data together */
4835 size = rb_event_ts_length(event);
4836
4837 if (len < size)
4838 goto out_unlock;
4839
4840 /* save the current timestamp, since the user will need it */
4841 save_timestamp = cpu_buffer->read_stamp;
4842
4843 /* Need to copy one event at a time */
4844 do {
4845 /* We need the size of one event, because
4846 * rb_advance_reader only advances by one event,
4847 * whereas rb_event_ts_length may include the size of
4848 * one or two events.
4849 * We have already ensured there's enough space if this
4850 * is a time extend. */
4851 size = rb_event_length(event);
4852 memcpy(bpage->data + pos, rpage->data + rpos, size);
4853
4854 len -= size;
4855
4856 rb_advance_reader(cpu_buffer);
4857 rpos = reader->read;
4858 pos += size;
4859
4860 if (rpos >= commit)
4861 break;
4862
4863 event = rb_reader_event(cpu_buffer);
4864 /* Always keep the time extend and data together */
4865 size = rb_event_ts_length(event);
4866 } while (len >= size);
4867
4868 /* update bpage */
4869 local_set(&bpage->commit, pos);
4870 bpage->time_stamp = save_timestamp;
4871
4872 /* we copied everything to the beginning */
4873 read = 0;
4874 } else {
4875 /* update the entry counter */
4876 cpu_buffer->read += rb_page_entries(reader);
4877 cpu_buffer->read_bytes += BUF_PAGE_SIZE;
4878
4879 /* swap the pages */
4880 rb_init_page(bpage);
4881 bpage = reader->page;
4882 reader->page = *data_page;
4883 local_set(&reader->write, 0);
4884 local_set(&reader->entries, 0);
4885 reader->read = 0;
4886 *data_page = bpage;
4887
4888 /*
4889 * Use the real_end for the data size,
4890 * This gives us a chance to store the lost events
4891 * on the page.
4892 */
4893 if (reader->real_end)
4894 local_set(&bpage->commit, reader->real_end);
4895 }
4896 ret = read;
4897
4898 cpu_buffer->lost_events = 0;
4899
4900 commit = local_read(&bpage->commit);
4901 /*
4902 * Set a flag in the commit field if we lost events
4903 */
4904 if (missed_events) {
4905 /* If there is room at the end of the page to save the
4906 * missed events, then record it there.
4907 */
4908 if (BUF_PAGE_SIZE - commit >= sizeof(missed_events)) {
4909 memcpy(&bpage->data[commit], &missed_events,
4910 sizeof(missed_events));
4911 local_add(RB_MISSED_STORED, &bpage->commit);
4912 commit += sizeof(missed_events);
4913 }
4914 local_add(RB_MISSED_EVENTS, &bpage->commit);
4915 }
4916
4917 /*
4918 * This page may be off to user land. Zero it out here.
4919 */
4920 if (commit < BUF_PAGE_SIZE)
4921 memset(&bpage->data[commit], 0, BUF_PAGE_SIZE - commit);
4922
4923 out_unlock:
4924 raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
4925
4926 out:
4927 return ret;
4928}
4929EXPORT_SYMBOL_GPL(ring_buffer_read_page);
4930
4931/*
4932 * We only allocate new buffers, never free them if the CPU goes down.
4933 * If we were to free the buffer, then the user would lose any trace that was in
4934 * the buffer.
4935 */
4936int trace_rb_cpu_prepare(unsigned int cpu, struct hlist_node *node)
4937{
4938 struct ring_buffer *buffer;
4939 long nr_pages_same;
4940 int cpu_i;
4941 unsigned long nr_pages;
4942
4943 buffer = container_of(node, struct ring_buffer, node);
4944 if (cpumask_test_cpu(cpu, buffer->cpumask))
4945 return 0;
4946
4947 nr_pages = 0;
4948 nr_pages_same = 1;
4949 /* check if all cpu sizes are same */
4950 for_each_buffer_cpu(buffer, cpu_i) {
4951 /* fill in the size from first enabled cpu */
4952 if (nr_pages == 0)
4953 nr_pages = buffer->buffers[cpu_i]->nr_pages;
4954 if (nr_pages != buffer->buffers[cpu_i]->nr_pages) {
4955 nr_pages_same = 0;
4956 break;
4957 }
4958 }
4959 /* allocate minimum pages, user can later expand it */
4960 if (!nr_pages_same)
4961 nr_pages = 2;
4962 buffer->buffers[cpu] =
4963 rb_allocate_cpu_buffer(buffer, nr_pages, cpu);
4964 if (!buffer->buffers[cpu]) {
4965 WARN(1, "failed to allocate ring buffer on CPU %u\n",
4966 cpu);
4967 return -ENOMEM;
4968 }
4969 smp_wmb();
4970 cpumask_set_cpu(cpu, buffer->cpumask);
4971 return 0;
4972}
4973
4974#ifdef CONFIG_RING_BUFFER_STARTUP_TEST
4975/*
4976 * This is a basic integrity check of the ring buffer.
4977 * Late in the boot cycle this test will run when configured in.
4978 * It will kick off a thread per CPU that will go into a loop
4979 * writing to the per cpu ring buffer various sizes of data.
4980 * Some of the data will be large items, some small.
4981 *
4982 * Another thread is created that goes into a spin, sending out
4983 * IPIs to the other CPUs to also write into the ring buffer.
4984 * this is to test the nesting ability of the buffer.
4985 *
4986 * Basic stats are recorded and reported. If something in the
4987 * ring buffer should happen that's not expected, a big warning
4988 * is displayed and all ring buffers are disabled.
4989 */
4990static struct task_struct *rb_threads[NR_CPUS] __initdata;
4991
4992struct rb_test_data {
4993 struct ring_buffer *buffer;
4994 unsigned long events;
4995 unsigned long bytes_written;
4996 unsigned long bytes_alloc;
4997 unsigned long bytes_dropped;
4998 unsigned long events_nested;
4999 unsigned long bytes_written_nested;
5000 unsigned long bytes_alloc_nested;
5001 unsigned long bytes_dropped_nested;
5002 int min_size_nested;
5003 int max_size_nested;
5004 int max_size;
5005 int min_size;
5006 int cpu;
5007 int cnt;
5008};
5009
5010static struct rb_test_data rb_data[NR_CPUS] __initdata;
5011
5012/* 1 meg per cpu */
5013#define RB_TEST_BUFFER_SIZE 1048576
5014
5015static char rb_string[] __initdata =
5016 "abcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()?+\\"
5017 "?+|:';\",.<>/?abcdefghijklmnopqrstuvwxyz1234567890"
5018 "!@#$%^&*()?+\\?+|:';\",.<>/?abcdefghijklmnopqrstuv";
5019
5020static bool rb_test_started __initdata;
5021
5022struct rb_item {
5023 int size;
5024 char str[];
5025};
5026
5027static __init int rb_write_something(struct rb_test_data *data, bool nested)
5028{
5029 struct ring_buffer_event *event;
5030 struct rb_item *item;
5031 bool started;
5032 int event_len;
5033 int size;
5034 int len;
5035 int cnt;
5036
5037 /* Have nested writes different that what is written */
5038 cnt = data->cnt + (nested ? 27 : 0);
5039
5040 /* Multiply cnt by ~e, to make some unique increment */
David Brazdil0f672f62019-12-10 10:32:29 +00005041 size = (cnt * 68 / 25) % (sizeof(rb_string) - 1);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005042
5043 len = size + sizeof(struct rb_item);
5044
5045 started = rb_test_started;
5046 /* read rb_test_started before checking buffer enabled */
5047 smp_rmb();
5048
5049 event = ring_buffer_lock_reserve(data->buffer, len);
5050 if (!event) {
5051 /* Ignore dropped events before test starts. */
5052 if (started) {
5053 if (nested)
5054 data->bytes_dropped += len;
5055 else
5056 data->bytes_dropped_nested += len;
5057 }
5058 return len;
5059 }
5060
5061 event_len = ring_buffer_event_length(event);
5062
5063 if (RB_WARN_ON(data->buffer, event_len < len))
5064 goto out;
5065
5066 item = ring_buffer_event_data(event);
5067 item->size = size;
5068 memcpy(item->str, rb_string, size);
5069
5070 if (nested) {
5071 data->bytes_alloc_nested += event_len;
5072 data->bytes_written_nested += len;
5073 data->events_nested++;
5074 if (!data->min_size_nested || len < data->min_size_nested)
5075 data->min_size_nested = len;
5076 if (len > data->max_size_nested)
5077 data->max_size_nested = len;
5078 } else {
5079 data->bytes_alloc += event_len;
5080 data->bytes_written += len;
5081 data->events++;
5082 if (!data->min_size || len < data->min_size)
5083 data->max_size = len;
5084 if (len > data->max_size)
5085 data->max_size = len;
5086 }
5087
5088 out:
5089 ring_buffer_unlock_commit(data->buffer, event);
5090
5091 return 0;
5092}
5093
5094static __init int rb_test(void *arg)
5095{
5096 struct rb_test_data *data = arg;
5097
5098 while (!kthread_should_stop()) {
5099 rb_write_something(data, false);
5100 data->cnt++;
5101
5102 set_current_state(TASK_INTERRUPTIBLE);
5103 /* Now sleep between a min of 100-300us and a max of 1ms */
5104 usleep_range(((data->cnt % 3) + 1) * 100, 1000);
5105 }
5106
5107 return 0;
5108}
5109
5110static __init void rb_ipi(void *ignore)
5111{
5112 struct rb_test_data *data;
5113 int cpu = smp_processor_id();
5114
5115 data = &rb_data[cpu];
5116 rb_write_something(data, true);
5117}
5118
5119static __init int rb_hammer_test(void *arg)
5120{
5121 while (!kthread_should_stop()) {
5122
5123 /* Send an IPI to all cpus to write data! */
5124 smp_call_function(rb_ipi, NULL, 1);
5125 /* No sleep, but for non preempt, let others run */
5126 schedule();
5127 }
5128
5129 return 0;
5130}
5131
5132static __init int test_ringbuffer(void)
5133{
5134 struct task_struct *rb_hammer;
5135 struct ring_buffer *buffer;
5136 int cpu;
5137 int ret = 0;
5138
Olivier Deprez0e641232021-09-23 10:07:05 +02005139 if (security_locked_down(LOCKDOWN_TRACEFS)) {
5140 pr_warning("Lockdown is enabled, skipping ring buffer tests\n");
5141 return 0;
5142 }
5143
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005144 pr_info("Running ring buffer tests...\n");
5145
5146 buffer = ring_buffer_alloc(RB_TEST_BUFFER_SIZE, RB_FL_OVERWRITE);
5147 if (WARN_ON(!buffer))
5148 return 0;
5149
5150 /* Disable buffer so that threads can't write to it yet */
5151 ring_buffer_record_off(buffer);
5152
5153 for_each_online_cpu(cpu) {
5154 rb_data[cpu].buffer = buffer;
5155 rb_data[cpu].cpu = cpu;
5156 rb_data[cpu].cnt = cpu;
5157 rb_threads[cpu] = kthread_create(rb_test, &rb_data[cpu],
5158 "rbtester/%d", cpu);
5159 if (WARN_ON(IS_ERR(rb_threads[cpu]))) {
5160 pr_cont("FAILED\n");
5161 ret = PTR_ERR(rb_threads[cpu]);
5162 goto out_free;
5163 }
5164
5165 kthread_bind(rb_threads[cpu], cpu);
5166 wake_up_process(rb_threads[cpu]);
5167 }
5168
5169 /* Now create the rb hammer! */
5170 rb_hammer = kthread_run(rb_hammer_test, NULL, "rbhammer");
5171 if (WARN_ON(IS_ERR(rb_hammer))) {
5172 pr_cont("FAILED\n");
5173 ret = PTR_ERR(rb_hammer);
5174 goto out_free;
5175 }
5176
5177 ring_buffer_record_on(buffer);
5178 /*
5179 * Show buffer is enabled before setting rb_test_started.
5180 * Yes there's a small race window where events could be
5181 * dropped and the thread wont catch it. But when a ring
5182 * buffer gets enabled, there will always be some kind of
5183 * delay before other CPUs see it. Thus, we don't care about
5184 * those dropped events. We care about events dropped after
5185 * the threads see that the buffer is active.
5186 */
5187 smp_wmb();
5188 rb_test_started = true;
5189
5190 set_current_state(TASK_INTERRUPTIBLE);
5191 /* Just run for 10 seconds */;
5192 schedule_timeout(10 * HZ);
5193
5194 kthread_stop(rb_hammer);
5195
5196 out_free:
5197 for_each_online_cpu(cpu) {
5198 if (!rb_threads[cpu])
5199 break;
5200 kthread_stop(rb_threads[cpu]);
5201 }
5202 if (ret) {
5203 ring_buffer_free(buffer);
5204 return ret;
5205 }
5206
5207 /* Report! */
5208 pr_info("finished\n");
5209 for_each_online_cpu(cpu) {
5210 struct ring_buffer_event *event;
5211 struct rb_test_data *data = &rb_data[cpu];
5212 struct rb_item *item;
5213 unsigned long total_events;
5214 unsigned long total_dropped;
5215 unsigned long total_written;
5216 unsigned long total_alloc;
5217 unsigned long total_read = 0;
5218 unsigned long total_size = 0;
5219 unsigned long total_len = 0;
5220 unsigned long total_lost = 0;
5221 unsigned long lost;
5222 int big_event_size;
5223 int small_event_size;
5224
5225 ret = -1;
5226
5227 total_events = data->events + data->events_nested;
5228 total_written = data->bytes_written + data->bytes_written_nested;
5229 total_alloc = data->bytes_alloc + data->bytes_alloc_nested;
5230 total_dropped = data->bytes_dropped + data->bytes_dropped_nested;
5231
5232 big_event_size = data->max_size + data->max_size_nested;
5233 small_event_size = data->min_size + data->min_size_nested;
5234
5235 pr_info("CPU %d:\n", cpu);
5236 pr_info(" events: %ld\n", total_events);
5237 pr_info(" dropped bytes: %ld\n", total_dropped);
5238 pr_info(" alloced bytes: %ld\n", total_alloc);
5239 pr_info(" written bytes: %ld\n", total_written);
5240 pr_info(" biggest event: %d\n", big_event_size);
5241 pr_info(" smallest event: %d\n", small_event_size);
5242
5243 if (RB_WARN_ON(buffer, total_dropped))
5244 break;
5245
5246 ret = 0;
5247
5248 while ((event = ring_buffer_consume(buffer, cpu, NULL, &lost))) {
5249 total_lost += lost;
5250 item = ring_buffer_event_data(event);
5251 total_len += ring_buffer_event_length(event);
5252 total_size += item->size + sizeof(struct rb_item);
5253 if (memcmp(&item->str[0], rb_string, item->size) != 0) {
5254 pr_info("FAILED!\n");
5255 pr_info("buffer had: %.*s\n", item->size, item->str);
5256 pr_info("expected: %.*s\n", item->size, rb_string);
5257 RB_WARN_ON(buffer, 1);
5258 ret = -1;
5259 break;
5260 }
5261 total_read++;
5262 }
5263 if (ret)
5264 break;
5265
5266 ret = -1;
5267
5268 pr_info(" read events: %ld\n", total_read);
5269 pr_info(" lost events: %ld\n", total_lost);
5270 pr_info(" total events: %ld\n", total_lost + total_read);
5271 pr_info(" recorded len bytes: %ld\n", total_len);
5272 pr_info(" recorded size bytes: %ld\n", total_size);
5273 if (total_lost)
5274 pr_info(" With dropped events, record len and size may not match\n"
5275 " alloced and written from above\n");
5276 if (!total_lost) {
5277 if (RB_WARN_ON(buffer, total_len != total_alloc ||
5278 total_size != total_written))
5279 break;
5280 }
5281 if (RB_WARN_ON(buffer, total_lost + total_read != total_events))
5282 break;
5283
5284 ret = 0;
5285 }
5286 if (!ret)
5287 pr_info("Ring buffer PASSED!\n");
5288
5289 ring_buffer_free(buffer);
5290 return 0;
5291}
5292
5293late_initcall(test_ringbuffer);
5294#endif /* CONFIG_RING_BUFFER_STARTUP_TEST */