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