at commit 89bab1db

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/ring_buffer_types.h>
8 #include <linux/sched/isolation.h>
9 #include <linux/trace_recursion.h>
10 #include <linux/panic_notifier.h>
11 #include <linux/trace_events.h>
12 #include <linux/ring_buffer.h>
13 #include <linux/trace_clock.h>
14 #include <linux/sched/clock.h>
15 #include <linux/cacheflush.h>
16 #include <linux/trace_seq.h>
17 #include <linux/spinlock.h>
18 #include <linux/irq_work.h>
19 #include <linux/security.h>
20 #include <linux/uaccess.h>
21 #include <linux/hardirq.h>
22 #include <linux/kthread.h> /* for self test */
23 #include <linux/module.h>
24 #include <linux/percpu.h>
25 #include <linux/mutex.h>
26 #include <linux/delay.h>
27 #include <linux/slab.h>
28 #include <linux/init.h>
29 #include <linux/hash.h>
30 #include <linux/list.h>
31 #include <linux/cpu.h>
32 #include <linux/oom.h>
33 #include <linux/mm.h>
34
35 #include <asm/ring_buffer.h>
36 #include <asm/local64.h>
37 #include <asm/local.h>
38 #include <asm/setup.h>
39
40 #include "trace.h"
41
42 /*
43 * The "absolute" timestamp in the buffer is only 59 bits.
44 * If a clock has the 5 MSBs set, it needs to be saved and
45 * reinserted.
46 */
47 #define TS_MSB (0xf8ULL << 56)
48 #define ABS_TS_MASK (~TS_MSB)
49
50 static void update_pages_handler(struct work_struct *work);
51
52 #define RING_BUFFER_META_MAGIC 0xBADFEED
53
54 struct ring_buffer_meta {
55 int magic;
56 int struct_sizes;
57 unsigned long total_size;
58 unsigned long buffers_offset;
59 };
60
61 struct ring_buffer_cpu_meta {
62 unsigned long first_buffer;
63 unsigned long head_buffer;
64 unsigned long commit_buffer;
65 __u32 subbuf_size;
66 __u32 nr_subbufs;
67 #ifdef CONFIG_RING_BUFFER_PERSISTENT_INJECT
68 __u32 nr_invalid;
69 __u32 entry_bytes;
70 #endif
71 int buffers[];
72 };
73
74 /*
75 * The ring buffer header is special. We must manually up keep it.
76 */
77 int ring_buffer_print_entry_header(struct trace_seq *s)
78 {
79 trace_seq_puts(s, "# compressed entry header\n");
80 trace_seq_puts(s, "\ttype_len : 5 bits\n");
81 trace_seq_puts(s, "\ttime_delta : 27 bits\n");
82 trace_seq_puts(s, "\tarray : 32 bits\n");
83 trace_seq_putc(s, '\n');
84 trace_seq_printf(s, "\tpadding : type == %d\n",
85 RINGBUF_TYPE_PADDING);
86 trace_seq_printf(s, "\ttime_extend : type == %d\n",
87 RINGBUF_TYPE_TIME_EXTEND);
88 trace_seq_printf(s, "\ttime_stamp : type == %d\n",
89 RINGBUF_TYPE_TIME_STAMP);
90 trace_seq_printf(s, "\tdata max type_len == %d\n",
91 RINGBUF_TYPE_DATA_TYPE_LEN_MAX);
92
93 return !trace_seq_has_overflowed(s);
94 }
95
96 /*
97 * The ring buffer is made up of a list of pages. A separate list of pages is
98 * allocated for each CPU. A writer may only write to a buffer that is
99 * associated with the CPU it is currently executing on. A reader may read
100 * from any per cpu buffer.
101 *
102 * The reader is special. For each per cpu buffer, the reader has its own
103 * reader page. When a reader has read the entire reader page, this reader
104 * page is swapped with another page in the ring buffer.
105 *
106 * Now, as long as the writer is off the reader page, the reader can do what
107 * ever it wants with that page. The writer will never write to that page
108 * again (as long as it is out of the ring buffer).
109 *
110 * Here's some silly ASCII art.
111 *
112 * +------+
113 * |reader| RING BUFFER
114 * |page |
115 * +------+ +---+ +---+ +---+
116 * | |-->| |-->| |
117 * +---+ +---+ +---+
118 * ^ |
119 * | |
120 * +---------------+
121 *
122 *
123 * +------+
124 * |reader| RING BUFFER
125 * |page |------------------v
126 * +------+ +---+ +---+ +---+
127 * | |-->| |-->| |
128 * +---+ +---+ +---+
129 * ^ |
130 * | |
131 * +---------------+
132 *
133 *
134 * +------+
135 * |reader| RING BUFFER
136 * |page |------------------v
137 * +------+ +---+ +---+ +---+
138 * ^ | |-->| |-->| |
139 * | +---+ +---+ +---+
140 * | |
141 * | |
142 * +------------------------------+
143 *
144 *
145 * +------+
146 * |buffer| RING BUFFER
147 * |page |------------------v
148 * +------+ +---+ +---+ +---+
149 * ^ | | | |-->| |
150 * | New +---+ +---+ +---+
151 * | Reader------^ |
152 * | page |
153 * +------------------------------+
154 *
155 *
156 * After we make this swap, the reader can hand this page off to the splice
157 * code and be done with it. It can even allocate a new page if it needs to
158 * and swap that into the ring buffer.
159 *
160 * We will be using cmpxchg soon to make all this lockless.
161 *
162 */
163
164 /* Used for individual buffers (after the counter) */
165 #define RB_BUFFER_OFF (1 << 20)
166
167 /* define RINGBUF_TYPE_DATA for 'case RINGBUF_TYPE_DATA:' */
168 #define RINGBUF_TYPE_DATA 0 ... RINGBUF_TYPE_DATA_TYPE_LEN_MAX
169
170 enum {
171 RB_LEN_TIME_EXTEND = 8,
172 RB_LEN_TIME_STAMP = 8,
173 };
174
175 #define skip_time_extend(event) \
176 ((struct ring_buffer_event *)((char *)event + RB_LEN_TIME_EXTEND))
177
178 #define extended_time(event) \
179 (event->type_len >= RINGBUF_TYPE_TIME_EXTEND)
180
181 static inline bool rb_null_event(struct ring_buffer_event *event)
182 {
183 return event->type_len == RINGBUF_TYPE_PADDING && !event->time_delta;
184 }
185
186 static void rb_event_set_padding(struct ring_buffer_event *event)
187 {
188 /* padding has a NULL time_delta */
189 event->type_len = RINGBUF_TYPE_PADDING;
190 event->time_delta = 0;
191 }
192
193 static unsigned
194 rb_event_data_length(struct ring_buffer_event *event)
195 {
196 unsigned length;
197
198 if (event->type_len)
199 length = event->type_len * RB_ALIGNMENT;
200 else
201 length = event->array[0];
202 return length + RB_EVNT_HDR_SIZE;
203 }
204
205 /*
206 * Return the length of the given event. Will return
207 * the length of the time extend if the event is a
208 * time extend.
209 */
210 static inline unsigned
211 rb_event_length(struct ring_buffer_event *event)
212 {
213 switch (event->type_len) {
214 case RINGBUF_TYPE_PADDING:
215 if (rb_null_event(event))
216 /* undefined */
217 return -1;
218 return event->array[0] + RB_EVNT_HDR_SIZE;
219
220 case RINGBUF_TYPE_TIME_EXTEND:
221 return RB_LEN_TIME_EXTEND;
222
223 case RINGBUF_TYPE_TIME_STAMP:
224 return RB_LEN_TIME_STAMP;
225
226 case RINGBUF_TYPE_DATA:
227 return rb_event_data_length(event);
228 default:
229 WARN_ON_ONCE(1);
230 }
231 /* not hit */
232 return 0;
233 }
234
235 /*
236 * Return total length of time extend and data,
237 * or just the event length for all other events.
238 */
239 static inline unsigned
240 rb_event_ts_length(struct ring_buffer_event *event)
241 {
242 unsigned len = 0;
243
244 if (extended_time(event)) {
245 /* time extends include the data event after it */
246 len = RB_LEN_TIME_EXTEND;
247 event = skip_time_extend(event);
248 }
249 return len + rb_event_length(event);
250 }
251
252 /**
253 * ring_buffer_event_length - return the length of the event
254 * @event: the event to get the length of
255 *
256 * Returns the size of the data load of a data event.
257 * If the event is something other than a data event, it
258 * returns the size of the event itself. With the exception
259 * of a TIME EXTEND, where it still returns the size of the
260 * data load of the data event after it.
261 */
262 unsigned ring_buffer_event_length(struct ring_buffer_event *event)
263 {
264 unsigned length;
265
266 if (extended_time(event))
267 event = skip_time_extend(event);
268
269 length = rb_event_length(event);
270 if (event->type_len > RINGBUF_TYPE_DATA_TYPE_LEN_MAX)
271 return length;
272 length -= RB_EVNT_HDR_SIZE;
273 if (length > RB_MAX_SMALL_DATA + sizeof(event->array[0]) ||
274 RB_FORCE_8BYTE_ALIGNMENT)
275 length -= sizeof(event->array[0]);
276 return length;
277 }
278 EXPORT_SYMBOL_GPL(ring_buffer_event_length);
279
280 /* inline for ring buffer fast paths */
281 static __always_inline void *
282 rb_event_data(struct ring_buffer_event *event)
283 {
284 if (extended_time(event))
285 event = skip_time_extend(event);
286 WARN_ON_ONCE(event->type_len > RINGBUF_TYPE_DATA_TYPE_LEN_MAX);
287 /* If length is in len field, then array[0] has the data */
288 if (event->type_len)
289 return (void *)&event->array[0];
290 /* Otherwise length is in array[0] and array[1] has the data */
291 return (void *)&event->array[1];
292 }
293
294 /**
295 * ring_buffer_event_data - return the data of the event
296 * @event: the event to get the data from
297 */
298 void *ring_buffer_event_data(struct ring_buffer_event *event)
299 {
300 return rb_event_data(event);
301 }
302 EXPORT_SYMBOL_GPL(ring_buffer_event_data);
303
304 #define for_each_buffer_cpu(buffer, cpu) \
305 for_each_cpu(cpu, buffer->cpumask)
306
307 #define for_each_online_buffer_cpu(buffer, cpu) \
308 for_each_cpu_and(cpu, buffer->cpumask, cpu_online_mask)
309
310 static u64 rb_event_time_stamp(struct ring_buffer_event *event)
311 {
312 u64 ts;
313
314 ts = event->array[0];
315 ts <<= TS_SHIFT;
316 ts += event->time_delta;
317
318 return ts;
319 }
320
321 /* Flag when events were overwritten */
322 #define RB_MISSED_EVENTS (1 << 31)
323 /* Missed count stored at end */
324 #define RB_MISSED_STORED (1 << 30)
325
326 #define RB_MISSED_MASK (3 << 30)
327
328 struct buffer_data_read_page {
329 unsigned order; /* order of the page */
330 struct buffer_data_page *data; /* actual data, stored in this page */
331 };
332
333 static __always_inline unsigned int rb_read_page_capacity(struct buffer_data_read_page *rpage)
334 {
335 return (PAGE_SIZE << rpage->order) - BUF_PAGE_HDR_SIZE;
336 }
337
338 /* The number of bits for static buffer ids */
339 #define RB_STATIC_BITS 30
340
341 /*
342 * Note, the buffer_page list must be first. The buffer pages
343 * are allocated in cache lines, which means that each buffer
344 * page will be at the beginning of a cache line, and thus
345 * the least significant bits will be zero. We use this to
346 * add flags in the list struct pointers, to make the ring buffer
347 * lockless.
348 */
349 struct buffer_page {
350 struct list_head list; /* list of buffer pages */
351 local_t write; /* index for next write */
352 unsigned read; /* index for next read */
353 local_t entries; /* entries on this page */
354 unsigned long real_end; /* real end of data */
355 unsigned order; /* order of the page */
356 u32 id:RB_STATIC_BITS; /* ID for external mapping */
357 u32 range:1; /* Mapped via a range */
358 struct buffer_data_page *page; /* Actual data page */
359 };
360
361 /*
362 * The buffer page counters, write and entries, must be reset
363 * atomically when crossing page boundaries. To synchronize this
364 * update, two counters are inserted into the number. One is
365 * the actual counter for the write position or count on the page.
366 *
367 * The other is a counter of updaters. Before an update happens
368 * the update partition of the counter is incremented. This will
369 * allow the updater to update the counter atomically.
370 *
371 * The counter is 20 bits, and the state data is 12.
372 */
373 #define RB_WRITE_MASK 0xfffff
374 #define RB_WRITE_INTCNT (1 << 20)
375
376 static void rb_init_data_page(struct buffer_data_page *bpage)
377 {
378 local_set(&bpage->commit, 0);
379 bpage->time_stamp = 0;
380 }
381
382 static __always_inline long rb_data_page_commit(struct buffer_data_page *dpage)
383 {
384 return local_read(&dpage->commit);
385 }
386
387 static __always_inline long rb_data_page_size(struct buffer_data_page *dpage)
388 {
389 return rb_data_page_commit(dpage) & ~RB_MISSED_MASK;
390 }
391
392 static __always_inline unsigned int rb_page_commit(struct buffer_page *bpage)
393 {
394 return rb_data_page_commit(bpage->page);
395 }
396
397 static __always_inline unsigned int rb_page_size(struct buffer_page *bpage)
398 {
399 return rb_data_page_size(bpage->page);
400 }
401
402 /**
403 * rb_page_capacity - Get the capacity of a buffer page
404 * @bpage: The buffer page
405 *
406 * Return: The maximum size available for events in the given buffer page.
407 */
408 static __always_inline unsigned int rb_page_capacity(struct buffer_page *bpage)
409 {
410 return (PAGE_SIZE << bpage->order) - BUF_PAGE_HDR_SIZE;
411 }
412
413 static void free_buffer_page(struct buffer_page *bpage)
414 {
415 /* Range pages are not to be freed */
416 if (!bpage->range)
417 free_pages((unsigned long)bpage->page, bpage->order);
418 kfree(bpage);
419 }
420
421 /*
422 * For best performance, allocate cpu buffer data cache line sized
423 * and per CPU.
424 */
425 #define alloc_cpu_buffer(cpu) (struct ring_buffer_per_cpu *) \
426 kzalloc_node(ALIGN(sizeof(struct ring_buffer_per_cpu), \
427 cache_line_size()), GFP_KERNEL, cpu_to_node(cpu))
428
429 #define alloc_cpu_page(cpu) (struct buffer_page *) \
430 kzalloc_node(ALIGN(sizeof(struct buffer_page), \
431 cache_line_size()), GFP_KERNEL, cpu_to_node(cpu))
432
433 static struct buffer_data_page *alloc_cpu_data(int cpu, int order)
434 {
435 struct buffer_data_page *dpage;
436 struct page *page;
437 gfp_t mflags;
438
439 /*
440 * __GFP_RETRY_MAYFAIL flag makes sure that the allocation fails
441 * gracefully without invoking oom-killer and the system is not
442 * destabilized.
443 */
444 mflags = GFP_KERNEL | __GFP_RETRY_MAYFAIL | __GFP_COMP | __GFP_ZERO;
445
446 page = alloc_pages_node(cpu_to_node(cpu), mflags, order);
447 if (!page)
448 return NULL;
449
450 dpage = page_address(page);
451 rb_init_data_page(dpage);
452
453 return dpage;
454 }
455
456 struct rb_irq_work {
457 struct irq_work work;
458 wait_queue_head_t waiters;
459 wait_queue_head_t full_waiters;
460 atomic_t seq;
461 bool waiters_pending;
462 bool full_waiters_pending;
463 bool wakeup_full;
464 };
465
466 /*
467 * Structure to hold event state and handle nested events.
468 */
469 struct rb_event_info {
470 u64 ts;
471 u64 delta;
472 u64 before;
473 u64 after;
474 unsigned long length;
475 struct buffer_page *tail_page;
476 int add_timestamp;
477 };
478
479 /*
480 * Used for the add_timestamp
481 * NONE
482 * EXTEND - wants a time extend
483 * ABSOLUTE - the buffer requests all events to have absolute time stamps
484 * FORCE - force a full time stamp.
485 */
486 enum {
487 RB_ADD_STAMP_NONE = 0,
488 RB_ADD_STAMP_EXTEND = BIT(1),
489 RB_ADD_STAMP_ABSOLUTE = BIT(2),
490 RB_ADD_STAMP_FORCE = BIT(3)
491 };
492 /*
493 * Used for which event context the event is in.
494 * TRANSITION = 0
495 * NMI = 1
496 * IRQ = 2
497 * SOFTIRQ = 3
498 * NORMAL = 4
499 *
500 * See trace_recursive_lock() comment below for more details.
501 */
502 enum {
503 RB_CTX_TRANSITION,
504 RB_CTX_NMI,
505 RB_CTX_IRQ,
506 RB_CTX_SOFTIRQ,
507 RB_CTX_NORMAL,
508 RB_CTX_MAX
509 };
510
511 struct rb_time_struct {
512 local64_t time;
513 };
514 typedef struct rb_time_struct rb_time_t;
515
516 #define MAX_NEST 5
517
518 /*
519 * head_page == tail_page && head == tail then buffer is empty.
520 */
521 struct ring_buffer_per_cpu {
522 int cpu;
523 atomic_t record_disabled;
524 atomic_t resize_disabled;
525 struct trace_buffer *buffer;
526 raw_spinlock_t reader_lock; /* serialize readers */
527 arch_spinlock_t lock;
528 struct lock_class_key lock_key;
529 struct buffer_data_read_page free_page;
530 unsigned long nr_pages;
531 unsigned int current_context;
532 struct list_head *pages;
533 /* pages generation counter, incremented when the list changes */
534 unsigned long cnt;
535 struct buffer_page *head_page; /* read from head */
536 struct buffer_page *tail_page; /* write to tail */
537 struct buffer_page *commit_page; /* committed pages */
538 struct buffer_page *reader_page;
539 unsigned long lost_events;
540 unsigned long last_overrun;
541 unsigned long nest;
542 local_t entries_bytes;
543 local_t entries;
544 local_t overrun;
545 local_t commit_overrun;
546 local_t dropped_events;
547 local_t committing;
548 local_t commits;
549 local_t pages_touched;
550 local_t pages_lost;
551 local_t pages_read;
552 long last_pages_touch;
553 size_t shortest_full;
554 unsigned long read;
555 unsigned long read_bytes;
556 rb_time_t write_stamp;
557 rb_time_t before_stamp;
558 u64 event_stamp[MAX_NEST];
559 u64 read_stamp;
560 /* pages removed since last reset */
561 unsigned long pages_removed;
562
563 unsigned int user_mapped; /* user space mapping */
564 struct mutex mapping_lock;
565 struct buffer_page **subbuf_ids; /* ID to subbuf VA */
566 struct trace_buffer_meta *meta_page;
567 struct ring_buffer_cpu_meta *ring_meta;
568
569 struct ring_buffer_remote *remote;
570
571 /* ring buffer pages to update, > 0 to add, < 0 to remove */
572 long nr_pages_to_update;
573 struct list_head new_pages; /* new pages to add */
574 struct work_struct update_pages_work;
575 struct completion update_done;
576
577 struct rb_irq_work irq_work;
578 };
579
580 struct trace_buffer {
581 unsigned flags;
582 atomic_t record_disabled;
583 atomic_t resizing;
584 cpumask_var_t cpumask;
585
586 struct lock_class_key *reader_lock_key;
587
588 struct mutex mutex;
589
590 struct ring_buffer_per_cpu **buffers;
591
592 struct ring_buffer_remote *remote;
593
594 struct hlist_node node;
595 u64 (*clock)(void);
596
597 struct rb_irq_work irq_work;
598 bool time_stamp_abs;
599
600 unsigned long range_addr_start;
601 unsigned long range_addr_end;
602 struct notifier_block flush_nb;
603
604 struct ring_buffer_meta *meta;
605
606 unsigned int subbuf_order;
607 };
608
609 static __always_inline unsigned int rb_subbuf_size(struct trace_buffer *buffer)
610 {
611 return PAGE_SIZE << buffer->subbuf_order;
612 }
613
614 /**
615 * rb_subbuf_capacity - Get the capacity of a subbuffer
616 * @buffer: A trace buffer
617 *
618 * Unsafe to use without holding trace_buffer::mutex or with resizing enabled.
619 * Consider rb_page_capacity() instead.
620 *
621 * Return: The maximum size available for events in a trace buffer subbuffer.
622 */
623 static __always_inline unsigned int rb_subbuf_capacity(struct trace_buffer *buffer)
624 {
625 return rb_subbuf_size(buffer) - BUF_PAGE_HDR_SIZE;
626 }
627
628 /**
629 * rb_subbuf_max_data_size - Get the maximum payload size of a single event
630 * @buffer: A trace buffer
631 *
632 * Return: The maximum data payload size that can be stored in a single event.
633 */
634 static __always_inline unsigned int rb_subbuf_max_data_size(struct trace_buffer *buffer)
635 {
636 struct ring_buffer_event *event;
637
638 /*
639 * surely rb_subbuf_capacity() is bigger than
640 * RINGBUF_TYPE_DATA_TYPE_LEN_MAX (see ring_buffer_event_length).
641 */
642 return rb_subbuf_capacity(buffer) - RB_EVNT_HDR_SIZE - sizeof(event->array[0]);
643 }
644
645 /**
646 * rb_subbuf_start - Get the start address of a subbuffer
647 * @buffer: A trace buffer
648 * @addr: An address of an event on a subbuffer
649 *
650 * Return: The start of the subbuffer for where @addr sits
651 */
652 static __always_inline
653 unsigned long rb_subbuf_start(struct trace_buffer *buffer, unsigned long addr)
654 {
655 return addr & ~((unsigned long)(rb_subbuf_size(buffer) - 1));
656 }
657
658 static bool rb_is_static(struct ring_buffer_per_cpu *cpu_buffer)
659 {
660 return cpu_buffer->user_mapped || cpu_buffer->remote || cpu_buffer->ring_meta;
661 }
662
663 static unsigned long rb_static_max_pages(void)
664 {
665 /*
666 * Static ring buffers are using bpage::id and must account for the
667 * reader page.
668 */
669 return (1UL << RB_STATIC_BITS) - 1;
670 }
671
672 struct ring_buffer_iter {
673 struct ring_buffer_per_cpu *cpu_buffer;
674 unsigned long head;
675 unsigned long next_event;
676 struct buffer_page *head_page;
677 struct buffer_page *cache_reader_page;
678 unsigned long cache_read;
679 unsigned long cache_pages_removed;
680 u64 read_stamp;
681 u64 page_stamp;
682 struct ring_buffer_event *event;
683 size_t event_size;
684 int missed_events;
685 };
686
687 int ring_buffer_print_page_header(struct trace_buffer *buffer, struct trace_seq *s)
688 {
689 struct buffer_data_page field;
690
691 trace_seq_printf(s, "\tfield: u64 timestamp;\t"
692 "offset:0;\tsize:%u;\tsigned:%u;\n",
693 (unsigned int)sizeof(field.time_stamp),
694 (unsigned int)is_signed_type(u64));
695
696 trace_seq_printf(s, "\tfield: local_t commit;\t"
697 "offset:%u;\tsize:%u;\tsigned:%u;\n",
698 (unsigned int)offsetof(typeof(field), commit),
699 (unsigned int)sizeof(field.commit),
700 (unsigned int)is_signed_type(long));
701
702 trace_seq_printf(s, "\tfield: char overwrite;\t"
703 "offset:%u;\tsize:%u;\tsigned:%u;\n",
704 (unsigned int)offsetof(typeof(field), commit),
705 1,
706 (unsigned int)is_signed_type(char));
707
708 trace_seq_printf(s, "\tfield: char data;\t"
709 "offset:%u;\tsize:%u;\tsigned:%u;\n",
710 (unsigned int)offsetof(typeof(field), data),
711 (unsigned int)(buffer ? rb_subbuf_capacity(buffer) :
712 PAGE_SIZE - BUF_PAGE_HDR_SIZE),
713 (unsigned int)is_signed_type(char));
714
715 return !trace_seq_has_overflowed(s);
716 }
717
718 static inline void rb_time_read(rb_time_t *t, u64 *ret)
719 {
720 *ret = local64_read(&t->time);
721 }
722 static void rb_time_set(rb_time_t *t, u64 val)
723 {
724 local64_set(&t->time, val);
725 }
726
727 /*
728 * Enable this to make sure that the event passed to
729 * ring_buffer_event_time_stamp() is not committed and also
730 * is on the buffer that it passed in.
731 */
732 //#define RB_VERIFY_EVENT
733 #ifdef RB_VERIFY_EVENT
734 static struct list_head *rb_list_head(struct list_head *list);
735 static void verify_event(struct ring_buffer_per_cpu *cpu_buffer,
736 void *event)
737 {
738 struct buffer_page *page = cpu_buffer->commit_page;
739 struct buffer_page *tail_page = READ_ONCE(cpu_buffer->tail_page);
740 struct list_head *next;
741 long commit, write;
742 unsigned long addr = (unsigned long)event;
743 bool done = false;
744 int stop = 0;
745
746 /* Make sure the event exists and is not committed yet */
747 do {
748 if (page == tail_page || WARN_ON_ONCE(stop++ > 100))
749 done = true;
750 commit = rb_page_commit(page);
751 write = local_read(&page->write);
752 if (addr >= (unsigned long)&page->page->data[commit] &&
753 addr < (unsigned long)&page->page->data[write])
754 return;
755
756 next = rb_list_head(page->list.next);
757 page = list_entry(next, struct buffer_page, list);
758 } while (!done);
759 WARN_ON_ONCE(1);
760 }
761 #else
762 static inline void verify_event(struct ring_buffer_per_cpu *cpu_buffer,
763 void *event)
764 {
765 }
766 #endif
767
768 /*
769 * The absolute time stamp drops the 5 MSBs and some clocks may
770 * require them. The rb_fix_abs_ts() will take a previous full
771 * time stamp, and add the 5 MSB of that time stamp on to the
772 * saved absolute time stamp. Then they are compared in case of
773 * the unlikely event that the latest time stamp incremented
774 * the 5 MSB.
775 */
776 static inline u64 rb_fix_abs_ts(u64 abs, u64 save_ts)
777 {
778 if (save_ts & TS_MSB) {
779 abs |= save_ts & TS_MSB;
780 /* Check for overflow */
781 if (unlikely(abs < save_ts))
782 abs += 1ULL << 59;
783 }
784 return abs;
785 }
786
787 static inline u64 rb_time_stamp(struct trace_buffer *buffer);
788
789 /**
790 * ring_buffer_event_time_stamp - return the event's current time stamp
791 * @buffer: The buffer that the event is on
792 * @event: the event to get the time stamp of
793 *
794 * Note, this must be called after @event is reserved, and before it is
795 * committed to the ring buffer. And must be called from the same
796 * context where the event was reserved (normal, softirq, irq, etc).
797 *
798 * Returns the time stamp associated with the current event.
799 * If the event has an extended time stamp, then that is used as
800 * the time stamp to return.
801 * In the highly unlikely case that the event was nested more than
802 * the max nesting, then the write_stamp of the buffer is returned,
803 * otherwise current time is returned, but that really neither of
804 * the last two cases should ever happen.
805 */
806 u64 ring_buffer_event_time_stamp(struct trace_buffer *buffer,
807 struct ring_buffer_event *event)
808 {
809 struct ring_buffer_per_cpu *cpu_buffer = buffer->buffers[smp_processor_id()];
810 unsigned int nest;
811 u64 ts;
812
813 /* If the event includes an absolute time, then just use that */
814 if (event->type_len == RINGBUF_TYPE_TIME_STAMP) {
815 ts = rb_event_time_stamp(event);
816 return rb_fix_abs_ts(ts, cpu_buffer->tail_page->page->time_stamp);
817 }
818
819 nest = local_read(&cpu_buffer->committing);
820 verify_event(cpu_buffer, event);
821 if (WARN_ON_ONCE(!nest))
822 goto fail;
823
824 /* Read the current saved nesting level time stamp */
825 if (likely(--nest < MAX_NEST))
826 return cpu_buffer->event_stamp[nest];
827
828 /* Shouldn't happen, warn if it does */
829 WARN_ONCE(1, "nest (%d) greater than max", nest);
830
831 fail:
832 rb_time_read(&cpu_buffer->write_stamp, &ts);
833
834 return ts;
835 }
836
837 /**
838 * ring_buffer_nr_dirty_pages - get the number of used pages in the ring buffer
839 * @buffer: The ring_buffer to get the number of pages from
840 * @cpu: The cpu of the ring_buffer to get the number of pages from
841 *
842 * Returns the number of pages that have content in the ring buffer.
843 */
844 size_t ring_buffer_nr_dirty_pages(struct trace_buffer *buffer, int cpu)
845 {
846 size_t read;
847 size_t lost;
848 size_t cnt;
849
850 read = local_read(&buffer->buffers[cpu]->pages_read);
851 lost = local_read(&buffer->buffers[cpu]->pages_lost);
852 cnt = local_read(&buffer->buffers[cpu]->pages_touched);
853
854 if (WARN_ON_ONCE(cnt < lost))
855 return 0;
856
857 cnt -= lost;
858
859 /* The reader can read an empty page, but not more than that */
860 if (cnt < read) {
861 WARN_ON_ONCE(read > cnt + 1);
862 return 0;
863 }
864
865 return cnt - read;
866 }
867
868 static __always_inline bool full_hit(struct trace_buffer *buffer, int cpu, int full)
869 {
870 struct ring_buffer_per_cpu *cpu_buffer = buffer->buffers[cpu];
871 size_t nr_pages;
872 size_t dirty;
873
874 nr_pages = cpu_buffer->nr_pages;
875 if (!nr_pages || !full)
876 return true;
877
878 /*
879 * Add one as dirty will never equal nr_pages, as the sub-buffer
880 * that the writer is on is not counted as dirty.
881 * This is needed if "buffer_percent" is set to 100.
882 */
883 dirty = ring_buffer_nr_dirty_pages(buffer, cpu) + 1;
884
885 return (dirty * 100) >= (full * nr_pages);
886 }
887
888 /*
889 * rb_wake_up_waiters - wake up tasks waiting for ring buffer input
890 *
891 * Schedules a delayed work to wake up any task that is blocked on the
892 * ring buffer waiters queue.
893 */
894 static void rb_wake_up_waiters(struct irq_work *work)
895 {
896 struct rb_irq_work *rbwork = container_of(work, struct rb_irq_work, work);
897
898 /* For waiters waiting for the first wake up */
899 (void)atomic_fetch_inc_release(&rbwork->seq);
900
901 wake_up_all(&rbwork->waiters);
902 if (rbwork->full_waiters_pending || rbwork->wakeup_full) {
903 /* Only cpu_buffer sets the above flags */
904 struct ring_buffer_per_cpu *cpu_buffer =
905 container_of(rbwork, struct ring_buffer_per_cpu, irq_work);
906
907 scoped_guard(raw_spinlock_irqsave, &cpu_buffer->reader_lock) {
908 rbwork->wakeup_full = false;
909 rbwork->full_waiters_pending = false;
910
911 /* Waking up all waiters, they will reset the shortest full */
912 cpu_buffer->shortest_full = 0;
913 }
914
915 wake_up_all(&rbwork->full_waiters);
916 }
917 }
918
919 /**
920 * ring_buffer_wake_waiters - wake up any waiters on this ring buffer
921 * @buffer: The ring buffer to wake waiters on
922 * @cpu: The CPU buffer to wake waiters on
923 *
924 * In the case of a file that represents a ring buffer is closing,
925 * it is prudent to wake up any waiters that are on this.
926 */
927 void ring_buffer_wake_waiters(struct trace_buffer *buffer, int cpu)
928 {
929 struct ring_buffer_per_cpu *cpu_buffer;
930 struct rb_irq_work *rbwork;
931
932 if (!buffer)
933 return;
934
935 if (cpu == RING_BUFFER_ALL_CPUS) {
936
937 /* Wake up individual ones too. One level recursion */
938 for_each_buffer_cpu(buffer, cpu)
939 ring_buffer_wake_waiters(buffer, cpu);
940
941 rbwork = &buffer->irq_work;
942 } else {
943 if (WARN_ON_ONCE(!buffer->buffers))
944 return;
945 if (WARN_ON_ONCE(cpu >= nr_cpu_ids))
946 return;
947
948 cpu_buffer = buffer->buffers[cpu];
949 /* The CPU buffer may not have been initialized yet */
950 if (!cpu_buffer)
951 return;
952 rbwork = &cpu_buffer->irq_work;
953 }
954
955 /* This can be called in any context */
956 irq_work_queue(&rbwork->work);
957 }
958
959 static bool rb_watermark_hit(struct trace_buffer *buffer, int cpu, int full)
960 {
961 struct ring_buffer_per_cpu *cpu_buffer;
962 bool ret = false;
963
964 /* Reads of all CPUs always waits for any data */
965 if (cpu == RING_BUFFER_ALL_CPUS)
966 return !ring_buffer_empty(buffer);
967
968 cpu_buffer = buffer->buffers[cpu];
969
970 if (!ring_buffer_empty_cpu(buffer, cpu)) {
971 unsigned long flags;
972 bool pagebusy;
973
974 if (!full)
975 return true;
976
977 raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
978 pagebusy = cpu_buffer->reader_page == cpu_buffer->commit_page;
979 ret = !pagebusy && full_hit(buffer, cpu, full);
980
981 if (!ret && (!cpu_buffer->shortest_full ||
982 cpu_buffer->shortest_full > full)) {
983 cpu_buffer->shortest_full = full;
984 }
985 raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
986 }
987 return ret;
988 }
989
990 static inline bool
991 rb_wait_cond(struct rb_irq_work *rbwork, struct trace_buffer *buffer,
992 int cpu, int full, ring_buffer_cond_fn cond, void *data)
993 {
994 if (rb_watermark_hit(buffer, cpu, full))
995 return true;
996
997 if (cond(data))
998 return true;
999
1000 /*
1001 * The events can happen in critical sections where
1002 * checking a work queue can cause deadlocks.
1003 * After adding a task to the queue, this flag is set
1004 * only to notify events to try to wake up the queue
1005 * using irq_work.
1006 *
1007 * We don't clear it even if the buffer is no longer
1008 * empty. The flag only causes the next event to run
1009 * irq_work to do the work queue wake up. The worse
1010 * that can happen if we race with !trace_empty() is that
1011 * an event will cause an irq_work to try to wake up
1012 * an empty queue.
1013 *
1014 * There's no reason to protect this flag either, as
1015 * the work queue and irq_work logic will do the necessary
1016 * synchronization for the wake ups. The only thing
1017 * that is necessary is that the wake up happens after
1018 * a task has been queued. It's OK for spurious wake ups.
1019 */
1020 if (full)
1021 rbwork->full_waiters_pending = true;
1022 else
1023 rbwork->waiters_pending = true;
1024
1025 return false;
1026 }
1027
1028 struct rb_wait_data {
1029 struct rb_irq_work *irq_work;
1030 int seq;
1031 };
1032
1033 /*
1034 * The default wait condition for ring_buffer_wait() is to just to exit the
1035 * wait loop the first time it is woken up.
1036 */
1037 static bool rb_wait_once(void *data)
1038 {
1039 struct rb_wait_data *rdata = data;
1040 struct rb_irq_work *rbwork = rdata->irq_work;
1041
1042 return atomic_read_acquire(&rbwork->seq) != rdata->seq;
1043 }
1044
1045 /**
1046 * ring_buffer_wait - wait for input to the ring buffer
1047 * @buffer: buffer to wait on
1048 * @cpu: the cpu buffer to wait on
1049 * @full: wait until the percentage of pages are available, if @cpu != RING_BUFFER_ALL_CPUS
1050 * @cond: condition function to break out of wait (NULL to run once)
1051 * @data: the data to pass to @cond.
1052 *
1053 * If @cpu == RING_BUFFER_ALL_CPUS then the task will wake up as soon
1054 * as data is added to any of the @buffer's cpu buffers. Otherwise
1055 * it will wait for data to be added to a specific cpu buffer.
1056 */
1057 int ring_buffer_wait(struct trace_buffer *buffer, int cpu, int full,
1058 ring_buffer_cond_fn cond, void *data)
1059 {
1060 struct ring_buffer_per_cpu *cpu_buffer;
1061 struct wait_queue_head *waitq;
1062 struct rb_irq_work *rbwork;
1063 struct rb_wait_data rdata;
1064 int ret = 0;
1065
1066 /*
1067 * Depending on what the caller is waiting for, either any
1068 * data in any cpu buffer, or a specific buffer, put the
1069 * caller on the appropriate wait queue.
1070 */
1071 if (cpu == RING_BUFFER_ALL_CPUS) {
1072 rbwork = &buffer->irq_work;
1073 /* Full only makes sense on per cpu reads */
1074 full = 0;
1075 } else {
1076 if (!cpumask_test_cpu(cpu, buffer->cpumask))
1077 return -ENODEV;
1078 cpu_buffer = buffer->buffers[cpu];
1079 rbwork = &cpu_buffer->irq_work;
1080 }
1081
1082 if (full)
1083 waitq = &rbwork->full_waiters;
1084 else
1085 waitq = &rbwork->waiters;
1086
1087 /* Set up to exit loop as soon as it is woken */
1088 if (!cond) {
1089 cond = rb_wait_once;
1090 rdata.irq_work = rbwork;
1091 rdata.seq = atomic_read_acquire(&rbwork->seq);
1092 data = &rdata;
1093 }
1094
1095 ret = wait_event_interruptible((*waitq),
1096 rb_wait_cond(rbwork, buffer, cpu, full, cond, data));
1097
1098 return ret;
1099 }
1100
1101 /**
1102 * ring_buffer_poll_wait - poll on buffer input
1103 * @buffer: buffer to wait on
1104 * @cpu: the cpu buffer to wait on
1105 * @filp: the file descriptor
1106 * @poll_table: The poll descriptor
1107 * @full: wait until the percentage of pages are available, if @cpu != RING_BUFFER_ALL_CPUS
1108 *
1109 * If @cpu == RING_BUFFER_ALL_CPUS then the task will wake up as soon
1110 * as data is added to any of the @buffer's cpu buffers. Otherwise
1111 * it will wait for data to be added to a specific cpu buffer.
1112 *
1113 * Returns EPOLLIN | EPOLLRDNORM if data exists in the buffers,
1114 * zero otherwise.
1115 */
1116 __poll_t ring_buffer_poll_wait(struct trace_buffer *buffer, int cpu,
1117 struct file *filp, poll_table *poll_table, int full)
1118 {
1119 struct ring_buffer_per_cpu *cpu_buffer;
1120 struct rb_irq_work *rbwork;
1121
1122 if (cpu == RING_BUFFER_ALL_CPUS) {
1123 rbwork = &buffer->irq_work;
1124 full = 0;
1125 } else {
1126 if (!cpumask_test_cpu(cpu, buffer->cpumask))
1127 return EPOLLERR;
1128
1129 cpu_buffer = buffer->buffers[cpu];
1130 rbwork = &cpu_buffer->irq_work;
1131 }
1132
1133 if (full) {
1134 poll_wait(filp, &rbwork->full_waiters, poll_table);
1135
1136 if (rb_watermark_hit(buffer, cpu, full))
1137 return EPOLLIN | EPOLLRDNORM;
1138 /*
1139 * Only allow full_waiters_pending update to be seen after
1140 * the shortest_full is set (in rb_watermark_hit). If the
1141 * writer sees the full_waiters_pending flag set, it will
1142 * compare the amount in the ring buffer to shortest_full.
1143 * If the amount in the ring buffer is greater than the
1144 * shortest_full percent, it will call the irq_work handler
1145 * to wake up this list. The irq_handler will reset shortest_full
1146 * back to zero. That's done under the reader_lock, but
1147 * the below smp_mb() makes sure that the update to
1148 * full_waiters_pending doesn't leak up into the above.
1149 */
1150 smp_mb();
1151 rbwork->full_waiters_pending = true;
1152 return 0;
1153 }
1154
1155 poll_wait(filp, &rbwork->waiters, poll_table);
1156 rbwork->waiters_pending = true;
1157
1158 /*
1159 * There's a tight race between setting the waiters_pending and
1160 * checking if the ring buffer is empty. Once the waiters_pending bit
1161 * is set, the next event will wake the task up, but we can get stuck
1162 * if there's only a single event in.
1163 *
1164 * FIXME: Ideally, we need a memory barrier on the writer side as well,
1165 * but adding a memory barrier to all events will cause too much of a
1166 * performance hit in the fast path. We only need a memory barrier when
1167 * the buffer goes from empty to having content. But as this race is
1168 * extremely small, and it's not a problem if another event comes in, we
1169 * will fix it later.
1170 */
1171 smp_mb();
1172
1173 if ((cpu == RING_BUFFER_ALL_CPUS && !ring_buffer_empty(buffer)) ||
1174 (cpu != RING_BUFFER_ALL_CPUS && !ring_buffer_empty_cpu(buffer, cpu)))
1175 return EPOLLIN | EPOLLRDNORM;
1176 return 0;
1177 }
1178
1179 /* buffer may be either ring_buffer or ring_buffer_per_cpu */
1180 #define RB_WARN_ON(b, cond) \
1181 ({ \
1182 int _____ret = unlikely(cond); \
1183 if (_____ret) { \
1184 if (__same_type(*(b), struct ring_buffer_per_cpu)) { \
1185 struct ring_buffer_per_cpu *__b = \
1186 (void *)b; \
1187 atomic_inc(&__b->buffer->record_disabled); \
1188 } else \
1189 atomic_inc(&b->record_disabled); \
1190 WARN_ON(1); \
1191 } \
1192 _____ret; \
1193 })
1194
1195 /* Up this if you want to test the TIME_EXTENTS and normalization */
1196 #define DEBUG_SHIFT 0
1197
1198 static inline u64 rb_time_stamp(struct trace_buffer *buffer)
1199 {
1200 u64 ts;
1201
1202 /* Skip retpolines :-( */
1203 if (IS_ENABLED(CONFIG_MITIGATION_RETPOLINE) && likely(buffer->clock == trace_clock_local))
1204 ts = trace_clock_local();
1205 else
1206 ts = buffer->clock();
1207
1208 /* shift to debug/test normalization and TIME_EXTENTS */
1209 return ts << DEBUG_SHIFT;
1210 }
1211
1212 u64 ring_buffer_time_stamp(struct trace_buffer *buffer)
1213 {
1214 u64 time;
1215
1216 preempt_disable_notrace();
1217 time = rb_time_stamp(buffer);
1218 preempt_enable_notrace();
1219
1220 return time;
1221 }
1222 EXPORT_SYMBOL_GPL(ring_buffer_time_stamp);
1223
1224 void ring_buffer_normalize_time_stamp(struct trace_buffer *buffer,
1225 int cpu, u64 *ts)
1226 {
1227 /* Just stupid testing the normalize function and deltas */
1228 *ts >>= DEBUG_SHIFT;
1229 }
1230 EXPORT_SYMBOL_GPL(ring_buffer_normalize_time_stamp);
1231
1232 /*
1233 * Making the ring buffer lockless makes things tricky.
1234 * Although writes only happen on the CPU that they are on,
1235 * and they only need to worry about interrupts. Reads can
1236 * happen on any CPU.
1237 *
1238 * The reader page is always off the ring buffer, but when the
1239 * reader finishes with a page, it needs to swap its page with
1240 * a new one from the buffer. The reader needs to take from
1241 * the head (writes go to the tail). But if a writer is in overwrite
1242 * mode and wraps, it must push the head page forward.
1243 *
1244 * Here lies the problem.
1245 *
1246 * The reader must be careful to replace only the head page, and
1247 * not another one. As described at the top of the file in the
1248 * ASCII art, the reader sets its old page to point to the next
1249 * page after head. It then sets the page after head to point to
1250 * the old reader page. But if the writer moves the head page
1251 * during this operation, the reader could end up with the tail.
1252 *
1253 * We use cmpxchg to help prevent this race. We also do something
1254 * special with the page before head. We set the LSB to 1.
1255 *
1256 * When the writer must push the page forward, it will clear the
1257 * bit that points to the head page, move the head, and then set
1258 * the bit that points to the new head page.
1259 *
1260 * We also don't want an interrupt coming in and moving the head
1261 * page on another writer. Thus we use the second LSB to catch
1262 * that too. Thus:
1263 *
1264 * head->list->prev->next bit 1 bit 0
1265 * ------- -------
1266 * Normal page 0 0
1267 * Points to head page 0 1
1268 * New head page 1 0
1269 *
1270 * Note we can not trust the prev pointer of the head page, because:
1271 *
1272 * +----+ +-----+ +-----+
1273 * | |------>| T |---X--->| N |
1274 * | |<------| | | |
1275 * +----+ +-----+ +-----+
1276 * ^ ^ |
1277 * | +-----+ | |
1278 * +----------| R |----------+ |
1279 * | |<-----------+
1280 * +-----+
1281 *
1282 * Key: ---X--> HEAD flag set in pointer
1283 * T Tail page
1284 * R Reader page
1285 * N Next page
1286 *
1287 * (see __rb_reserve_next() to see where this happens)
1288 *
1289 * What the above shows is that the reader just swapped out
1290 * the reader page with a page in the buffer, but before it
1291 * could make the new header point back to the new page added
1292 * it was preempted by a writer. The writer moved forward onto
1293 * the new page added by the reader and is about to move forward
1294 * again.
1295 *
1296 * You can see, it is legitimate for the previous pointer of
1297 * the head (or any page) not to point back to itself. But only
1298 * temporarily.
1299 */
1300
1301 #define RB_PAGE_NORMAL 0UL
1302 #define RB_PAGE_HEAD 1UL
1303 #define RB_PAGE_UPDATE 2UL
1304
1305
1306 #define RB_FLAG_MASK 3UL
1307
1308 /* PAGE_MOVED is not part of the mask */
1309 #define RB_PAGE_MOVED 4UL
1310
1311 /*
1312 * rb_list_head - remove any bit
1313 */
1314 static struct list_head *rb_list_head(struct list_head *list)
1315 {
1316 unsigned long val = (unsigned long)list;
1317
1318 return (struct list_head *)(val & ~RB_FLAG_MASK);
1319 }
1320
1321 /*
1322 * rb_is_head_page - test if the given page is the head page
1323 *
1324 * Because the reader may move the head_page pointer, we can
1325 * not trust what the head page is (it may be pointing to
1326 * the reader page). But if the next page is a header page,
1327 * its flags will be non zero.
1328 */
1329 static inline int
1330 rb_is_head_page(struct buffer_page *page, struct list_head *list)
1331 {
1332 unsigned long val;
1333
1334 val = (unsigned long)list->next;
1335
1336 if ((val & ~RB_FLAG_MASK) != (unsigned long)&page->list)
1337 return RB_PAGE_MOVED;
1338
1339 return val & RB_FLAG_MASK;
1340 }
1341
1342 /*
1343 * rb_is_reader_page
1344 *
1345 * The unique thing about the reader page, is that, if the
1346 * writer is ever on it, the previous pointer never points
1347 * back to the reader page.
1348 */
1349 static bool rb_is_reader_page(struct buffer_page *page)
1350 {
1351 struct list_head *list = page->list.prev;
1352
1353 return rb_list_head(list->next) != &page->list;
1354 }
1355
1356 /*
1357 * rb_set_list_to_head - set a list_head to be pointing to head.
1358 */
1359 static void rb_set_list_to_head(struct list_head *list)
1360 {
1361 unsigned long *ptr;
1362
1363 ptr = (unsigned long *)&list->next;
1364 *ptr |= RB_PAGE_HEAD;
1365 *ptr &= ~RB_PAGE_UPDATE;
1366 }
1367
1368 /*
1369 * rb_head_page_activate - sets up head page
1370 */
1371 static void rb_head_page_activate(struct ring_buffer_per_cpu *cpu_buffer)
1372 {
1373 struct buffer_page *head;
1374
1375 head = cpu_buffer->head_page;
1376 if (!head)
1377 return;
1378
1379 /*
1380 * Set the previous list pointer to have the HEAD flag.
1381 */
1382 rb_set_list_to_head(head->list.prev);
1383
1384 if (cpu_buffer->ring_meta) {
1385 struct ring_buffer_cpu_meta *meta = cpu_buffer->ring_meta;
1386 meta->head_buffer = (unsigned long)head->page;
1387 }
1388 }
1389
1390 static void rb_list_head_clear(struct list_head *list)
1391 {
1392 unsigned long *ptr = (unsigned long *)&list->next;
1393
1394 *ptr &= ~RB_FLAG_MASK;
1395 }
1396
1397 /*
1398 * rb_head_page_deactivate - clears head page ptr (for free list)
1399 */
1400 static void
1401 rb_head_page_deactivate(struct ring_buffer_per_cpu *cpu_buffer)
1402 {
1403 struct list_head *hd;
1404
1405 /* Go through the whole list and clear any pointers found. */
1406 rb_list_head_clear(cpu_buffer->pages);
1407
1408 list_for_each(hd, cpu_buffer->pages)
1409 rb_list_head_clear(hd);
1410 }
1411
1412 static int rb_head_page_set(struct ring_buffer_per_cpu *cpu_buffer,
1413 struct buffer_page *head,
1414 struct buffer_page *prev,
1415 int old_flag, int new_flag)
1416 {
1417 struct list_head *list;
1418 unsigned long val = (unsigned long)&head->list;
1419 unsigned long ret;
1420
1421 list = &prev->list;
1422
1423 val &= ~RB_FLAG_MASK;
1424
1425 ret = cmpxchg((unsigned long *)&list->next,
1426 val | old_flag, val | new_flag);
1427
1428 /* check if the reader took the page */
1429 if ((ret & ~RB_FLAG_MASK) != val)
1430 return RB_PAGE_MOVED;
1431
1432 return ret & RB_FLAG_MASK;
1433 }
1434
1435 static int rb_head_page_set_update(struct ring_buffer_per_cpu *cpu_buffer,
1436 struct buffer_page *head,
1437 struct buffer_page *prev,
1438 int old_flag)
1439 {
1440 return rb_head_page_set(cpu_buffer, head, prev,
1441 old_flag, RB_PAGE_UPDATE);
1442 }
1443
1444 static int rb_head_page_set_head(struct ring_buffer_per_cpu *cpu_buffer,
1445 struct buffer_page *head,
1446 struct buffer_page *prev,
1447 int old_flag)
1448 {
1449 return rb_head_page_set(cpu_buffer, head, prev,
1450 old_flag, RB_PAGE_HEAD);
1451 }
1452
1453 static int rb_head_page_set_normal(struct ring_buffer_per_cpu *cpu_buffer,
1454 struct buffer_page *head,
1455 struct buffer_page *prev,
1456 int old_flag)
1457 {
1458 return rb_head_page_set(cpu_buffer, head, prev,
1459 old_flag, RB_PAGE_NORMAL);
1460 }
1461
1462 static inline void rb_inc_page(struct buffer_page **bpage)
1463 {
1464 struct list_head *p = rb_list_head((*bpage)->list.next);
1465
1466 *bpage = list_entry(p, struct buffer_page, list);
1467 }
1468
1469 static inline void rb_dec_page(struct buffer_page **bpage)
1470 {
1471 struct list_head *p = rb_list_head((*bpage)->list.prev);
1472
1473 *bpage = list_entry(p, struct buffer_page, list);
1474 }
1475
1476 static struct buffer_page *
1477 rb_set_head_page(struct ring_buffer_per_cpu *cpu_buffer)
1478 {
1479 struct buffer_page *head;
1480 struct buffer_page *page;
1481 struct list_head *list;
1482 int i;
1483
1484 if (RB_WARN_ON(cpu_buffer, !cpu_buffer->head_page))
1485 return NULL;
1486
1487 /* sanity check */
1488 list = cpu_buffer->pages;
1489 if (RB_WARN_ON(cpu_buffer, rb_list_head(list->prev->next) != list))
1490 return NULL;
1491
1492 page = head = cpu_buffer->head_page;
1493 /*
1494 * It is possible that the writer moves the header behind
1495 * where we started, and we miss in one loop.
1496 * A second loop should grab the header, but we'll do
1497 * three loops just because I'm paranoid.
1498 */
1499 for (i = 0; i < 3; i++) {
1500 do {
1501 if (rb_is_head_page(page, page->list.prev)) {
1502 cpu_buffer->head_page = page;
1503 return page;
1504 }
1505 rb_inc_page(&page);
1506 } while (page != head);
1507 }
1508
1509 RB_WARN_ON(cpu_buffer, 1);
1510
1511 return NULL;
1512 }
1513
1514 static bool rb_head_page_replace(struct buffer_page *old,
1515 struct buffer_page *new)
1516 {
1517 unsigned long *ptr = (unsigned long *)&old->list.prev->next;
1518 unsigned long val;
1519
1520 val = *ptr & ~RB_FLAG_MASK;
1521 val |= RB_PAGE_HEAD;
1522
1523 return try_cmpxchg(ptr, &val, (unsigned long)&new->list);
1524 }
1525
1526 /*
1527 * rb_tail_page_update - move the tail page forward
1528 */
1529 static void rb_tail_page_update(struct ring_buffer_per_cpu *cpu_buffer,
1530 struct buffer_page *tail_page,
1531 struct buffer_page *next_page)
1532 {
1533 unsigned long old_entries;
1534 unsigned long old_write;
1535
1536 /*
1537 * The tail page now needs to be moved forward.
1538 *
1539 * We need to reset the tail page, but without messing
1540 * with possible erasing of data brought in by interrupts
1541 * that have moved the tail page and are currently on it.
1542 *
1543 * We add a counter to the write field to denote this.
1544 */
1545 old_write = local_add_return(RB_WRITE_INTCNT, &next_page->write);
1546 old_entries = local_add_return(RB_WRITE_INTCNT, &next_page->entries);
1547
1548 /*
1549 * Just make sure we have seen our old_write and synchronize
1550 * with any interrupts that come in.
1551 */
1552 barrier();
1553
1554 /*
1555 * If the tail page is still the same as what we think
1556 * it is, then it is up to us to update the tail
1557 * pointer.
1558 */
1559 if (tail_page == READ_ONCE(cpu_buffer->tail_page)) {
1560 /* Zero the write counter */
1561 unsigned long val = old_write & ~RB_WRITE_MASK;
1562 unsigned long eval = old_entries & ~RB_WRITE_MASK;
1563
1564 /*
1565 * This will only succeed if an interrupt did
1566 * not come in and change it. In which case, we
1567 * do not want to modify it.
1568 *
1569 * We add (void) to let the compiler know that we do not care
1570 * about the return value of these functions. We use the
1571 * cmpxchg to only update if an interrupt did not already
1572 * do it for us. If the cmpxchg fails, we don't care.
1573 */
1574 (void)local_cmpxchg(&next_page->write, old_write, val);
1575 (void)local_cmpxchg(&next_page->entries, old_entries, eval);
1576
1577 /*
1578 * No need to worry about races with clearing out the commit.
1579 * it only can increment when a commit takes place. But that
1580 * only happens in the outer most nested commit.
1581 */
1582 local_set(&next_page->page->commit, 0);
1583
1584 /* Either we update tail_page or an interrupt does */
1585 if (try_cmpxchg(&cpu_buffer->tail_page, &tail_page, next_page))
1586 local_inc(&cpu_buffer->pages_touched);
1587 }
1588 }
1589
1590 static void rb_check_bpage(struct ring_buffer_per_cpu *cpu_buffer,
1591 struct buffer_page *bpage)
1592 {
1593 unsigned long val = (unsigned long)bpage;
1594
1595 RB_WARN_ON(cpu_buffer, val & RB_FLAG_MASK);
1596 }
1597
1598 static bool rb_check_links(struct ring_buffer_per_cpu *cpu_buffer,
1599 struct list_head *list)
1600 {
1601 if (RB_WARN_ON(cpu_buffer,
1602 rb_list_head(rb_list_head(list->next)->prev) != list))
1603 return false;
1604
1605 if (RB_WARN_ON(cpu_buffer,
1606 rb_list_head(rb_list_head(list->prev)->next) != list))
1607 return false;
1608
1609 return true;
1610 }
1611
1612 /**
1613 * rb_check_pages - integrity check of buffer pages
1614 * @cpu_buffer: CPU buffer with pages to test
1615 *
1616 * As a safety measure we check to make sure the data pages have not
1617 * been corrupted.
1618 */
1619 static void rb_check_pages(struct ring_buffer_per_cpu *cpu_buffer)
1620 {
1621 struct list_head *head, *tmp;
1622 unsigned long buffer_cnt;
1623 unsigned long flags;
1624 int nr_loops = 0;
1625
1626 /*
1627 * Walk the linked list underpinning the ring buffer and validate all
1628 * its next and prev links.
1629 *
1630 * The check acquires the reader_lock to avoid concurrent processing
1631 * with code that could be modifying the list. However, the lock cannot
1632 * be held for the entire duration of the walk, as this would make the
1633 * time when interrupts are disabled non-deterministic, dependent on the
1634 * ring buffer size. Therefore, the code releases and re-acquires the
1635 * lock after checking each page. The ring_buffer_per_cpu.cnt variable
1636 * is then used to detect if the list was modified while the lock was
1637 * not held, in which case the check needs to be restarted.
1638 *
1639 * The code attempts to perform the check at most three times before
1640 * giving up. This is acceptable because this is only a self-validation
1641 * to detect problems early on. In practice, the list modification
1642 * operations are fairly spaced, and so this check typically succeeds at
1643 * most on the second try.
1644 */
1645 again:
1646 if (++nr_loops > 3)
1647 return;
1648
1649 raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
1650 head = rb_list_head(cpu_buffer->pages);
1651 if (!rb_check_links(cpu_buffer, head))
1652 goto out_locked;
1653 buffer_cnt = cpu_buffer->cnt;
1654 tmp = head;
1655 raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
1656
1657 while (true) {
1658 raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
1659
1660 if (buffer_cnt != cpu_buffer->cnt) {
1661 /* The list was updated, try again. */
1662 raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
1663 goto again;
1664 }
1665
1666 tmp = rb_list_head(tmp->next);
1667 if (tmp == head)
1668 /* The iteration circled back, all is done. */
1669 goto out_locked;
1670
1671 if (!rb_check_links(cpu_buffer, tmp))
1672 goto out_locked;
1673
1674 raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
1675 }
1676
1677 out_locked:
1678 raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
1679 }
1680
1681 /*
1682 * Take an address, add the meta data size as well as the array of
1683 * array subbuffer indexes, then align it to a subbuffer size.
1684 *
1685 * This is used to help find the next per cpu subbuffer within a mapped range.
1686 */
1687 static unsigned long
1688 rb_range_align_subbuf(unsigned long addr, unsigned int subbuf_size, unsigned long nr_subbufs)
1689 {
1690 addr += sizeof(struct ring_buffer_cpu_meta) +
1691 sizeof(int) * nr_subbufs;
1692 return ALIGN(addr, subbuf_size);
1693 }
1694
1695 /*
1696 * Return the ring_buffer_meta for a given @cpu.
1697 */
1698 static void *rb_range_meta(struct trace_buffer *buffer, unsigned long nr_pages, int cpu)
1699 {
1700 unsigned int subbuf_size = rb_subbuf_size(buffer);
1701 struct ring_buffer_cpu_meta *meta;
1702 struct ring_buffer_meta *bmeta;
1703 unsigned long ptr, nr_subbufs;
1704
1705 bmeta = buffer->meta;
1706 if (!bmeta)
1707 return NULL;
1708
1709 ptr = (unsigned long)bmeta + bmeta->buffers_offset;
1710 meta = (struct ring_buffer_cpu_meta *)ptr;
1711
1712 /* When nr_pages passed in is zero, the first meta has already been initialized */
1713 if (!nr_pages) {
1714 nr_subbufs = meta->nr_subbufs;
1715 } else {
1716 /* Include the reader page */
1717 nr_subbufs = nr_pages + 1;
1718 }
1719
1720 /*
1721 * The first chunk may not be subbuffer aligned, where as
1722 * the rest of the chunks are.
1723 */
1724 if (cpu) {
1725 ptr = rb_range_align_subbuf(ptr, subbuf_size, nr_subbufs);
1726 ptr += subbuf_size * nr_subbufs;
1727
1728 /* We can use multiplication to find chunks greater than 1 */
1729 if (cpu > 1) {
1730 unsigned long size;
1731 unsigned long p;
1732
1733 /* Save the beginning of this CPU chunk */
1734 p = ptr;
1735 ptr = rb_range_align_subbuf(ptr, subbuf_size, nr_subbufs);
1736 ptr += subbuf_size * nr_subbufs;
1737
1738 /* Now all chunks after this are the same size */
1739 size = ptr - p;
1740 ptr += size * (cpu - 2);
1741 }
1742 }
1743 return (void *)ptr;
1744 }
1745
1746 /* Return the start of subbufs given the meta pointer */
1747 static void *rb_subbufs_from_meta(struct ring_buffer_cpu_meta *meta)
1748 {
1749 unsigned int subbuf_size = meta->subbuf_size;
1750 unsigned long ptr;
1751
1752 ptr = (unsigned long)meta;
1753 ptr = rb_range_align_subbuf(ptr, subbuf_size, meta->nr_subbufs);
1754
1755 return (void *)ptr;
1756 }
1757
1758 /*
1759 * Return a specific sub-buffer for a given @cpu defined by @idx.
1760 */
1761 static void *rb_range_buffer(struct ring_buffer_per_cpu *cpu_buffer, unsigned long idx)
1762 {
1763 struct ring_buffer_cpu_meta *meta;
1764 unsigned int subbuf_size;
1765 unsigned long ptr;
1766
1767 meta = rb_range_meta(cpu_buffer->buffer, 0, cpu_buffer->cpu);
1768 if (!meta)
1769 return NULL;
1770
1771 if (WARN_ON_ONCE(idx >= meta->nr_subbufs))
1772 return NULL;
1773
1774 subbuf_size = meta->subbuf_size;
1775
1776 /* Map this buffer to the order that's in meta->buffers[] */
1777 idx = meta->buffers[idx];
1778
1779 ptr = (unsigned long)rb_subbufs_from_meta(meta);
1780
1781 ptr += (unsigned long)subbuf_size * idx;
1782 if (ptr + subbuf_size > cpu_buffer->buffer->range_addr_end)
1783 return NULL;
1784
1785 return (void *)ptr;
1786 }
1787
1788 /*
1789 * See if the existing memory contains a valid meta section.
1790 * if so, use that, otherwise initialize it.
1791 */
1792 static bool rb_meta_init(struct trace_buffer *buffer, int scratch_size)
1793 {
1794 unsigned long ptr = buffer->range_addr_start;
1795 struct ring_buffer_meta *bmeta;
1796 unsigned long total_size;
1797 int struct_sizes;
1798
1799 bmeta = (struct ring_buffer_meta *)ptr;
1800 buffer->meta = bmeta;
1801
1802 total_size = buffer->range_addr_end - buffer->range_addr_start;
1803
1804 struct_sizes = sizeof(struct ring_buffer_cpu_meta);
1805 struct_sizes |= sizeof(*bmeta) << 16;
1806
1807 /* The first buffer will start word size after the meta page */
1808 ptr += sizeof(*bmeta);
1809 ptr = ALIGN(ptr, sizeof(long));
1810 ptr += scratch_size;
1811
1812 if (bmeta->magic != RING_BUFFER_META_MAGIC) {
1813 pr_info("Ring buffer boot meta mismatch of magic\n");
1814 goto init;
1815 }
1816
1817 if (bmeta->struct_sizes != struct_sizes) {
1818 pr_info("Ring buffer boot meta mismatch of struct size\n");
1819 goto init;
1820 }
1821
1822 if (bmeta->total_size != total_size) {
1823 pr_info("Ring buffer boot meta mismatch of total size\n");
1824 goto init;
1825 }
1826
1827 if (bmeta->buffers_offset > bmeta->total_size) {
1828 pr_info("Ring buffer boot meta mismatch of offset outside of total size\n");
1829 goto init;
1830 }
1831
1832 if (bmeta->buffers_offset != (void *)ptr - (void *)bmeta) {
1833 pr_info("Ring buffer boot meta mismatch of first buffer offset\n");
1834 goto init;
1835 }
1836
1837 return true;
1838
1839 init:
1840 bmeta->magic = RING_BUFFER_META_MAGIC;
1841 bmeta->struct_sizes = struct_sizes;
1842 bmeta->total_size = total_size;
1843 bmeta->buffers_offset = (void *)ptr - (void *)bmeta;
1844
1845 /* Zero out the scratch pad */
1846 memset((void *)bmeta + sizeof(*bmeta), 0, bmeta->buffers_offset - sizeof(*bmeta));
1847
1848 return false;
1849 }
1850
1851 /*
1852 * See if the existing memory contains valid ring buffer data.
1853 * As the previous kernel must be the same as this kernel, all
1854 * the calculations (size of buffers and number of buffers)
1855 * must be the same.
1856 */
1857 static bool rb_cpu_meta_valid(struct ring_buffer_cpu_meta *meta, int cpu,
1858 struct trace_buffer *buffer, unsigned long nr_pages,
1859 unsigned long *subbuf_mask)
1860 {
1861 unsigned long buffers_start;
1862 unsigned long buffers_end;
1863 unsigned long i;
1864
1865 if (!subbuf_mask)
1866 return false;
1867
1868 if (meta->subbuf_size != PAGE_SIZE) {
1869 pr_info("Ring buffer boot meta [%d] invalid subbuf_size\n", cpu);
1870 return false;
1871 }
1872
1873 if (meta->nr_subbufs != nr_pages + 1) {
1874 pr_info("Ring buffer boot meta [%d] invalid nr_subbufs\n", cpu);
1875 return false;
1876 }
1877
1878 buffers_start = meta->first_buffer;
1879 buffers_end = meta->first_buffer + (meta->nr_subbufs * PAGE_SIZE);
1880
1881 /* Is the head and commit buffers within the range of buffers? */
1882 if (meta->head_buffer < buffers_start ||
1883 meta->head_buffer >= buffers_end) {
1884 pr_info("Ring buffer boot meta [%d] head buffer out of range\n", cpu);
1885 return false;
1886 }
1887
1888 if (meta->commit_buffer < buffers_start ||
1889 meta->commit_buffer >= buffers_end) {
1890 pr_info("Ring buffer boot meta [%d] commit buffer out of range\n", cpu);
1891 return false;
1892 }
1893
1894 bitmap_clear(subbuf_mask, 0, meta->nr_subbufs);
1895
1896 /*
1897 * Ensure the meta::buffers array has correct data. The data in each subbufs
1898 * are checked later in rb_meta_validate_events().
1899 */
1900 for (i = 0; i < meta->nr_subbufs; i++) {
1901 if (meta->buffers[i] < 0 ||
1902 meta->buffers[i] >= meta->nr_subbufs) {
1903 pr_info("Ring buffer boot meta [%d] array out of range\n", cpu);
1904 return false;
1905 }
1906
1907 if (test_bit(meta->buffers[i], subbuf_mask)) {
1908 pr_info("Ring buffer boot meta [%d] array has duplicates\n", cpu);
1909 return false;
1910 }
1911
1912 set_bit(meta->buffers[i], subbuf_mask);
1913 }
1914
1915 return true;
1916 }
1917
1918 static int rb_meta_subbuf_idx(struct ring_buffer_cpu_meta *meta, void *subbuf);
1919
1920 static int rb_read_data_buffer(struct buffer_data_page *dpage, int tail, int cpu,
1921 unsigned long long *timestamp, u64 *delta_ptr)
1922 {
1923 struct ring_buffer_event *event;
1924 u64 ts, delta;
1925 int events = 0;
1926 int len;
1927 int e;
1928
1929 *delta_ptr = 0;
1930 *timestamp = 0;
1931
1932 ts = dpage->time_stamp;
1933
1934 for (e = 0; e < tail; e += len) {
1935
1936 event = (struct ring_buffer_event *)(dpage->data + e);
1937 len = rb_event_length(event);
1938 if (len <= 0 || len > tail - e)
1939 return -1;
1940
1941 switch (event->type_len) {
1942
1943 case RINGBUF_TYPE_TIME_EXTEND:
1944 delta = rb_event_time_stamp(event);
1945 ts += delta;
1946 break;
1947
1948 case RINGBUF_TYPE_TIME_STAMP:
1949 delta = rb_event_time_stamp(event);
1950 delta = rb_fix_abs_ts(delta, ts);
1951 if (delta < ts) {
1952 *delta_ptr = delta;
1953 *timestamp = ts;
1954 return -1;
1955 }
1956 ts = delta;
1957 break;
1958
1959 case RINGBUF_TYPE_PADDING:
1960 if (event->time_delta == 1)
1961 break;
1962 fallthrough;
1963 case RINGBUF_TYPE_DATA:
1964 events++;
1965 ts += event->time_delta;
1966 break;
1967
1968 default:
1969 return -1;
1970 }
1971 }
1972 *timestamp = ts;
1973 return events;
1974 }
1975
1976 struct rb_validation_state {
1977 unsigned long entries;
1978 unsigned long entry_bytes;
1979 int discarded;
1980 u64 ts;
1981 };
1982
1983 static int __rb_validate_buffer(struct buffer_page *bpage, int cpu,
1984 struct ring_buffer_cpu_meta *meta,
1985 u64 prev_ts, u64 next_ts)
1986 {
1987 struct buffer_data_page *dpage = bpage->page;
1988 unsigned long long ts;
1989 unsigned long tail;
1990 u64 delta;
1991 int ret;
1992
1993 /*
1994 * When a sub-buffer is recovered from a read, the commit value may
1995 * have RB_MISSED_* bits set, as these bits are reset on reuse.
1996 * Even after clearing these bits, a commit value greater than the
1997 * subbuf_size is considered invalid.
1998 */
1999 tail = rb_data_page_commit(dpage);
2000 if (tail <= meta->subbuf_size - BUF_PAGE_HDR_SIZE)
2001 ret = rb_read_data_buffer(dpage, tail, cpu, &ts, &delta);
2002 else
2003 ret = -1;
2004
2005 /*
2006 * The timestamp must be greater than @prev_ts and smaller than @next_ts.
2007 * Since this function works in both forward (verify) and reverse (unwind)
2008 * loop, we don't know both @prev_ts and @next_ts at the same time.
2009 * So use the known boundary as the boundary.
2010 */
2011 if (ret < 0 || (prev_ts && prev_ts > ts) || (next_ts && ts > next_ts)) {
2012 local_set(&bpage->entries, 0);
2013 /*
2014 * Note, the RB_MISSED_EVENTS is only set inside the main write
2015 * buffer by this verification logic. The normal ring buffer
2016 * has this bit set when the page is read and passed to the
2017 * consumers.
2018 */
2019 local_set(&dpage->commit, RB_MISSED_EVENTS);
2020 dpage->time_stamp = prev_ts ? prev_ts : next_ts;
2021 ret = -1;
2022 } else {
2023 local_set(&bpage->entries, ret);
2024 }
2025
2026 return ret;
2027 }
2028
2029 /**
2030 * rb_validate_buffer - validates a single buffer page and updates the state.
2031 * @bpage: buffer page to validate
2032 * @cpu_buffer: cpu_buffer this page belongs to
2033 * @meta: meta of the cpu_buffer
2034 * @state: validation state
2035 * @prev_ts: previous buffer's timestamp (optional)
2036 * @next_ts: next buffer's timestamp (optional)
2037 *
2038 * If the page is invalid (wrong event length or timestamp), it increments the
2039 * discarded counter and warns it. Otherwise, it updates the validation state.
2040 */
2041 static void rb_validate_buffer(struct buffer_page *bpage,
2042 struct ring_buffer_per_cpu *cpu_buffer,
2043 struct ring_buffer_cpu_meta *meta,
2044 struct rb_validation_state *state,
2045 u64 prev_ts, u64 next_ts)
2046 {
2047 int ret;
2048
2049 ret = __rb_validate_buffer(bpage, cpu_buffer->cpu, meta, prev_ts, next_ts);
2050 if (ret < 0) {
2051 if (!state->discarded)
2052 pr_info("Ring buffer meta [%d] invalid buffer page detected\n",
2053 cpu_buffer->cpu);
2054 state->discarded++;
2055 } else {
2056 /* If the buffer has content, update pages_touched */
2057 if (ret)
2058 local_inc(&cpu_buffer->pages_touched);
2059
2060 state->entries += ret;
2061 state->entry_bytes += rb_page_size(bpage);
2062 state->ts = bpage->page->time_stamp;
2063 }
2064 }
2065
2066 static void rb_meta_inject_reader_page(struct ring_buffer_per_cpu *cpu_buffer,
2067 struct ring_buffer_cpu_meta *meta,
2068 struct buffer_page *orig_head,
2069 struct buffer_page *head_page)
2070 {
2071 struct buffer_page *bpage = orig_head;
2072 int i;
2073
2074 rb_dec_page(&bpage);
2075 /*
2076 * Insert the reader_page before the original head page.
2077 * Since the list encode RB_PAGE flags, general list
2078 * operations should be avoided.
2079 */
2080 cpu_buffer->reader_page->list.next = &orig_head->list;
2081 cpu_buffer->reader_page->list.prev = orig_head->list.prev;
2082 orig_head->list.prev = &cpu_buffer->reader_page->list;
2083 bpage->list.next = &cpu_buffer->reader_page->list;
2084
2085 /* Make the head_page the reader page */
2086 cpu_buffer->reader_page = head_page;
2087 bpage = head_page;
2088 rb_inc_page(&head_page);
2089 head_page->list.prev = bpage->list.prev;
2090 rb_dec_page(&bpage);
2091 bpage->list.next = &head_page->list;
2092 rb_set_list_to_head(&bpage->list);
2093 cpu_buffer->pages = &head_page->list;
2094
2095 cpu_buffer->head_page = head_page;
2096 meta->head_buffer = (unsigned long)head_page->page;
2097
2098 /* Reset all the indexes */
2099 bpage = cpu_buffer->reader_page;
2100 meta->buffers[0] = rb_meta_subbuf_idx(meta, bpage->page);
2101 bpage->id = 0;
2102
2103 for (i = 1, bpage = head_page; i < meta->nr_subbufs;
2104 i++, rb_inc_page(&bpage)) {
2105 meta->buffers[i] = rb_meta_subbuf_idx(meta, bpage->page);
2106 bpage->id = i;
2107 }
2108 }
2109
2110 /* If the meta data has been validated, now validate the events */
2111 static void rb_meta_validate_events(struct ring_buffer_per_cpu *cpu_buffer)
2112 {
2113 struct ring_buffer_cpu_meta *meta = cpu_buffer->ring_meta;
2114 struct buffer_page *head_page, *orig_head, *orig_reader;
2115 struct rb_validation_state state = { 0 };
2116 bool skip = false;
2117 unsigned long i;
2118 int ret;
2119
2120 if (!meta || !meta->head_buffer)
2121 return;
2122
2123 orig_head = head_page = cpu_buffer->head_page;
2124 orig_reader = cpu_buffer->reader_page;
2125
2126 /* Do the head page first */
2127 ret = __rb_validate_buffer(head_page, cpu_buffer->cpu, meta, 0, 0);
2128 if (ret < 0) {
2129 pr_info("Ring buffer meta [%d] invalid head page detected\n",
2130 cpu_buffer->cpu);
2131 /* Don't bother rewinding */
2132 skip = true;
2133 state.ts = 0;
2134 } else {
2135 state.ts = head_page->page->time_stamp;
2136 }
2137
2138 /* Do the reader page - reader must be previous to head. */
2139 rb_validate_buffer(orig_reader, cpu_buffer, meta, &state, 0, state.ts);
2140
2141 if (skip)
2142 goto skip_rewind;
2143
2144 /*
2145 * Try to rewind the head so that we can read the pages which are already
2146 * read in the previous boot.
2147 */
2148 if (head_page == cpu_buffer->tail_page)
2149 goto skip_rewind;
2150
2151 rb_dec_page(&head_page);
2152 for (i = 0; i < meta->nr_subbufs + 1; i++, rb_dec_page(&head_page)) {
2153
2154 /* Rewind until tail (writer) page. */
2155 if (head_page == cpu_buffer->tail_page)
2156 break;
2157
2158 /* Rewind until unused page (no timestamp, no commit). */
2159 if (!head_page->page->time_stamp && rb_page_commit(head_page) == 0)
2160 break;
2161
2162 /*
2163 * Skip if the page is invalid, or its timestamp is newer than the
2164 * previous valid page.
2165 */
2166 rb_validate_buffer(head_page, cpu_buffer, meta, &state, 0, state.ts);
2167 }
2168 if (i)
2169 pr_info("Ring buffer [%d] rewound %lu pages\n", cpu_buffer->cpu, i);
2170
2171 /* The last rewound page must be skipped. */
2172 if (head_page != orig_head)
2173 rb_inc_page(&head_page);
2174
2175 /*
2176 * If the ring buffer was rewound, then inject the reader page
2177 * into the location just before the original head page.
2178 */
2179 if (head_page != orig_head) {
2180 rb_meta_inject_reader_page(cpu_buffer, meta, orig_head, head_page);
2181 /* We'll restart verifying from orig_head */
2182 head_page = orig_head;
2183 }
2184
2185 skip_rewind:
2186 /* If the commit_buffer is the reader page, update the commit page */
2187 if (meta->commit_buffer == (unsigned long)cpu_buffer->reader_page->page) {
2188 cpu_buffer->commit_page = cpu_buffer->reader_page;
2189 /* Nothing more to do, the only page is the reader page */
2190 goto done;
2191 }
2192 state.ts = head_page->page->time_stamp;
2193
2194 /* Iterate until finding the commit page */
2195 for (i = 0; i < meta->nr_subbufs + 1; i++, rb_inc_page(&head_page)) {
2196
2197 /* The original reader page has already been checked/counted. */
2198 if (head_page == orig_reader)
2199 continue;
2200
2201 rb_validate_buffer(head_page, cpu_buffer, meta, &state, state.ts, 0);
2202
2203 if (head_page == cpu_buffer->commit_page)
2204 break;
2205 }
2206
2207 if (head_page != cpu_buffer->commit_page) {
2208 pr_info("Ring buffer meta [%d] commit page not found\n",
2209 cpu_buffer->cpu);
2210 goto invalid;
2211 }
2212 done:
2213 local_set(&cpu_buffer->entries, state.entries);
2214 local_set(&cpu_buffer->entries_bytes, state.entry_bytes);
2215
2216 pr_info("Ring buffer meta [%d] is from previous boot!", cpu_buffer->cpu);
2217 if (state.discarded)
2218 pr_cont(" (%d pages discarded)", state.discarded);
2219 pr_cont("\n");
2220
2221 #ifdef CONFIG_RING_BUFFER_PERSISTENT_INJECT
2222 if (meta->nr_invalid)
2223 pr_warn("Ring buffer testing [%d] invalid pages: %s (%d/%d)\n",
2224 cpu_buffer->cpu,
2225 (state.discarded == meta->nr_invalid) ? "PASSED" : "FAILED",
2226 state.discarded, meta->nr_invalid);
2227 if (meta->entry_bytes)
2228 pr_warn("Ring buffer testing [%d] entry_bytes: %s (%ld/%ld)\n",
2229 cpu_buffer->cpu,
2230 (state.entry_bytes == meta->entry_bytes) ? "PASSED" : "FAILED",
2231 (long)state.entry_bytes, (long)meta->entry_bytes);
2232 meta->nr_invalid = 0;
2233 meta->entry_bytes = 0;
2234 #endif
2235 return;
2236
2237 invalid:
2238 /* The content of the buffers are invalid, reset the meta data */
2239 meta->head_buffer = 0;
2240 meta->commit_buffer = 0;
2241
2242 /* Reset the reader page */
2243 local_set(&cpu_buffer->reader_page->entries, 0);
2244 rb_init_data_page(cpu_buffer->reader_page->page);
2245
2246 /* Reset all the subbuffers */
2247 for (i = 0; i < meta->nr_subbufs - 1; i++, rb_inc_page(&head_page)) {
2248 local_set(&head_page->entries, 0);
2249 rb_init_data_page(head_page->page);
2250 }
2251 }
2252
2253 static void rb_range_meta_init(struct trace_buffer *buffer, unsigned long nr_pages,
2254 int scratch_size)
2255 {
2256 struct ring_buffer_cpu_meta *meta;
2257 unsigned long *subbuf_mask;
2258 unsigned long delta;
2259 void *subbuf;
2260 bool valid = false;
2261 int cpu;
2262 int i;
2263
2264 /* Create a mask to test the subbuf array */
2265 subbuf_mask = bitmap_alloc(nr_pages + 1, GFP_KERNEL);
2266 /* If subbuf_mask fails to allocate, then rb_meta_valid() will return false */
2267
2268 if (rb_meta_init(buffer, scratch_size))
2269 valid = true;
2270
2271 for (cpu = 0; cpu < nr_cpu_ids; cpu++) {
2272 void *next_meta;
2273
2274 meta = rb_range_meta(buffer, nr_pages, cpu);
2275
2276 if (valid && rb_cpu_meta_valid(meta, cpu, buffer, nr_pages, subbuf_mask)) {
2277 /* Make the mappings match the current address */
2278 subbuf = rb_subbufs_from_meta(meta);
2279 delta = (unsigned long)subbuf - meta->first_buffer;
2280 meta->first_buffer += delta;
2281 meta->head_buffer += delta;
2282 meta->commit_buffer += delta;
2283 continue;
2284 }
2285
2286 if (cpu < nr_cpu_ids - 1)
2287 next_meta = rb_range_meta(buffer, nr_pages, cpu + 1);
2288 else
2289 next_meta = (void *)buffer->range_addr_end;
2290
2291 memset(meta, 0, next_meta - (void *)meta);
2292
2293 meta->nr_subbufs = nr_pages + 1;
2294 meta->subbuf_size = PAGE_SIZE;
2295
2296 subbuf = rb_subbufs_from_meta(meta);
2297
2298 meta->first_buffer = (unsigned long)subbuf;
2299
2300 /*
2301 * The buffers[] array holds the order of the sub-buffers
2302 * that are after the meta data. The sub-buffers may
2303 * be swapped out when read and inserted into a different
2304 * location of the ring buffer. Although their addresses
2305 * remain the same, the buffers[] array contains the
2306 * index into the sub-buffers holding their actual order.
2307 */
2308 for (i = 0; i < meta->nr_subbufs; i++) {
2309 meta->buffers[i] = i;
2310 rb_init_data_page(subbuf);
2311 subbuf += meta->subbuf_size;
2312 }
2313 }
2314 bitmap_free(subbuf_mask);
2315 }
2316
2317 static void *rbm_start(struct seq_file *m, loff_t *pos)
2318 {
2319 struct ring_buffer_per_cpu *cpu_buffer = m->private;
2320 struct ring_buffer_cpu_meta *meta = cpu_buffer->ring_meta;
2321 unsigned long val;
2322
2323 if (!meta)
2324 return NULL;
2325
2326 if (*pos > meta->nr_subbufs)
2327 return NULL;
2328
2329 val = *pos;
2330 val++;
2331
2332 return (void *)val;
2333 }
2334
2335 static void *rbm_next(struct seq_file *m, void *v, loff_t *pos)
2336 {
2337 (*pos)++;
2338
2339 return rbm_start(m, pos);
2340 }
2341
2342 static int rbm_show(struct seq_file *m, void *v)
2343 {
2344 struct ring_buffer_per_cpu *cpu_buffer = m->private;
2345 struct ring_buffer_cpu_meta *meta = cpu_buffer->ring_meta;
2346 unsigned long val = (unsigned long)v;
2347 struct buffer_data_page *dpage;
2348
2349 if (val == 1) {
2350 seq_printf(m, "head_buffer: %d\n",
2351 rb_meta_subbuf_idx(meta, (void *)meta->head_buffer));
2352 seq_printf(m, "commit_buffer: %d\n",
2353 rb_meta_subbuf_idx(meta, (void *)meta->commit_buffer));
2354 seq_printf(m, "subbuf_size: %u\n", meta->subbuf_size);
2355 seq_printf(m, "nr_subbufs: %u\n", meta->nr_subbufs);
2356 return 0;
2357 }
2358
2359 val -= 2;
2360 dpage = rb_range_buffer(cpu_buffer, val);
2361 seq_printf(m, "buffer[%ld]: %d (commit: %ld)\n",
2362 val, meta->buffers[val], dpage ? rb_data_page_commit(dpage) : -1);
2363
2364 return 0;
2365 }
2366
2367 static void rbm_stop(struct seq_file *m, void *p)
2368 {
2369 }
2370
2371 static const struct seq_operations rb_meta_seq_ops = {
2372 .start = rbm_start,
2373 .next = rbm_next,
2374 .show = rbm_show,
2375 .stop = rbm_stop,
2376 };
2377
2378 int ring_buffer_meta_seq_init(struct file *file, struct trace_buffer *buffer, int cpu)
2379 {
2380 struct seq_file *m;
2381 int ret;
2382
2383 if (!cpumask_test_cpu(cpu, buffer->cpumask))
2384 return -ENODEV;
2385
2386 ret = seq_open(file, &rb_meta_seq_ops);
2387 if (ret)
2388 return ret;
2389
2390 m = file->private_data;
2391 m->private = buffer->buffers[cpu];
2392
2393 return 0;
2394 }
2395
2396 /* Map the buffer_pages to the previous head and commit pages */
2397 static void rb_meta_buffer_update(struct ring_buffer_per_cpu *cpu_buffer,
2398 struct buffer_page *bpage)
2399 {
2400 struct ring_buffer_cpu_meta *meta = cpu_buffer->ring_meta;
2401
2402 if (meta->head_buffer == (unsigned long)bpage->page)
2403 cpu_buffer->head_page = bpage;
2404
2405 if (meta->commit_buffer == (unsigned long)bpage->page) {
2406 cpu_buffer->commit_page = bpage;
2407 cpu_buffer->tail_page = bpage;
2408 }
2409 }
2410
2411 static struct ring_buffer_desc *ring_buffer_desc(struct trace_buffer_desc *trace_desc, int cpu)
2412 {
2413 struct ring_buffer_desc *desc, *end;
2414 size_t len;
2415 int i;
2416
2417 if (!trace_desc || !trace_desc->nr_cpus)
2418 return NULL;
2419
2420 end = (struct ring_buffer_desc *)((void *)trace_desc + trace_desc->struct_len);
2421 desc = __first_ring_buffer_desc(trace_desc);
2422 len = struct_size(desc, page_va, desc->nr_page_va);
2423 desc = (struct ring_buffer_desc *)((void *)desc + (len * cpu));
2424
2425 if (desc < end && desc->cpu == cpu)
2426 return desc;
2427
2428 /* Missing CPUs, need to linear search */
2429 for_each_ring_buffer_desc(desc, i, trace_desc) {
2430 if (desc->cpu == cpu)
2431 return desc;
2432 }
2433
2434 return NULL;
2435 }
2436
2437 static void *ring_buffer_desc_page(struct ring_buffer_desc *desc, unsigned int page_id)
2438 {
2439 return page_id >= desc->nr_page_va ? NULL : (void *)desc->page_va[page_id];
2440 }
2441
2442 static int __rb_allocate_pages(struct ring_buffer_per_cpu *cpu_buffer,
2443 unsigned long nr_pages, struct list_head *pages)
2444 {
2445 struct trace_buffer *buffer = cpu_buffer->buffer;
2446 struct ring_buffer_cpu_meta *meta = NULL;
2447 struct buffer_page *bpage, *tmp;
2448 bool user_thread = current->mm != NULL;
2449 struct ring_buffer_desc *desc = NULL;
2450 long i;
2451
2452 /*
2453 * Check if the available memory is there first.
2454 * Note, si_mem_available() only gives us a rough estimate of available
2455 * memory. It may not be accurate. But we don't care, we just want
2456 * to prevent doing any allocation when it is obvious that it is
2457 * not going to succeed.
2458 */
2459 i = si_mem_available();
2460 if (i < nr_pages)
2461 return -ENOMEM;
2462
2463 /*
2464 * If a user thread allocates too much, and si_mem_available()
2465 * reports there's enough memory, even though there is not.
2466 * Make sure the OOM killer kills this thread. This can happen
2467 * even with RETRY_MAYFAIL because another task may be doing
2468 * an allocation after this task has taken all memory.
2469 * This is the task the OOM killer needs to take out during this
2470 * loop, even if it was triggered by an allocation somewhere else.
2471 */
2472 if (user_thread)
2473 set_current_oom_origin();
2474
2475 if (buffer->range_addr_start)
2476 meta = rb_range_meta(buffer, nr_pages, cpu_buffer->cpu);
2477
2478 if (buffer->remote) {
2479 desc = ring_buffer_desc(buffer->remote->desc, cpu_buffer->cpu);
2480 if (!desc || WARN_ON(desc->nr_page_va != (nr_pages + 1)))
2481 return -EINVAL;
2482 }
2483
2484 for (i = 0; i < nr_pages; i++) {
2485
2486 bpage = alloc_cpu_page(cpu_buffer->cpu);
2487 if (!bpage)
2488 goto free_pages;
2489
2490 rb_check_bpage(cpu_buffer, bpage);
2491
2492 /*
2493 * Append the pages as for mapped buffers we want to keep
2494 * the order
2495 */
2496 list_add_tail(&bpage->list, pages);
2497
2498 if (meta) {
2499 /* A range was given. Use that for the buffer page */
2500 bpage->page = rb_range_buffer(cpu_buffer, i + 1);
2501 if (!bpage->page)
2502 goto free_pages;
2503 /* If this is valid from a previous boot */
2504 if (meta->head_buffer)
2505 rb_meta_buffer_update(cpu_buffer, bpage);
2506 bpage->range = 1;
2507 bpage->id = i + 1;
2508 } else if (desc) {
2509 void *p = ring_buffer_desc_page(desc, i + 1);
2510
2511 if (WARN_ON(!p))
2512 goto free_pages;
2513
2514 bpage->page = p;
2515 bpage->range = 1; /* bpage->page can't be freed */
2516 bpage->id = i + 1;
2517 cpu_buffer->subbuf_ids[i + 1] = bpage;
2518 } else {
2519 bpage->page = alloc_cpu_data(cpu_buffer->cpu,
2520 cpu_buffer->buffer->subbuf_order);
2521 if (!bpage->page)
2522 goto free_pages;
2523 }
2524 bpage->order = cpu_buffer->buffer->subbuf_order;
2525
2526 if (user_thread && fatal_signal_pending(current))
2527 goto free_pages;
2528 }
2529 if (user_thread)
2530 clear_current_oom_origin();
2531
2532 return 0;
2533
2534 free_pages:
2535 list_for_each_entry_safe(bpage, tmp, pages, list) {
2536 list_del_init(&bpage->list);
2537 free_buffer_page(bpage);
2538 }
2539 if (user_thread)
2540 clear_current_oom_origin();
2541
2542 return -ENOMEM;
2543 }
2544
2545 static int rb_allocate_pages(struct ring_buffer_per_cpu *cpu_buffer,
2546 unsigned long nr_pages)
2547 {
2548 LIST_HEAD(pages);
2549
2550 WARN_ON(!nr_pages);
2551
2552 if (__rb_allocate_pages(cpu_buffer, nr_pages, &pages))
2553 return -ENOMEM;
2554
2555 /*
2556 * The ring buffer page list is a circular list that does not
2557 * start and end with a list head. All page list items point to
2558 * other pages.
2559 */
2560 cpu_buffer->pages = pages.next;
2561 list_del(&pages);
2562
2563 cpu_buffer->nr_pages = nr_pages;
2564
2565 rb_check_pages(cpu_buffer);
2566
2567 return 0;
2568 }
2569
2570 static struct ring_buffer_per_cpu *
2571 rb_allocate_cpu_buffer(struct trace_buffer *buffer, unsigned long nr_pages, int cpu)
2572 {
2573 struct ring_buffer_per_cpu *cpu_buffer __free(kfree) =
2574 alloc_cpu_buffer(cpu);
2575 struct ring_buffer_cpu_meta *meta;
2576 struct buffer_page *bpage;
2577 int ret;
2578
2579 if (!cpu_buffer)
2580 return NULL;
2581
2582 cpu_buffer->cpu = cpu;
2583 cpu_buffer->buffer = buffer;
2584 raw_spin_lock_init(&cpu_buffer->reader_lock);
2585 lockdep_set_class(&cpu_buffer->reader_lock, buffer->reader_lock_key);
2586 cpu_buffer->lock = (arch_spinlock_t)__ARCH_SPIN_LOCK_UNLOCKED;
2587 INIT_WORK(&cpu_buffer->update_pages_work, update_pages_handler);
2588 init_completion(&cpu_buffer->update_done);
2589 init_irq_work(&cpu_buffer->irq_work.work, rb_wake_up_waiters);
2590 init_waitqueue_head(&cpu_buffer->irq_work.waiters);
2591 init_waitqueue_head(&cpu_buffer->irq_work.full_waiters);
2592 mutex_init(&cpu_buffer->mapping_lock);
2593
2594 bpage = alloc_cpu_page(cpu);
2595 if (!bpage)
2596 return NULL;
2597 bpage->order = cpu_buffer->buffer->subbuf_order;
2598
2599 rb_check_bpage(cpu_buffer, bpage);
2600
2601 cpu_buffer->reader_page = bpage;
2602
2603 if (buffer->range_addr_start) {
2604 /*
2605 * Range mapped buffers have the same restrictions as memory
2606 * mapped ones do.
2607 */
2608 cpu_buffer->ring_meta = rb_range_meta(buffer, nr_pages, cpu);
2609 bpage->page = rb_range_buffer(cpu_buffer, 0);
2610 if (!bpage->page)
2611 goto fail_free_reader;
2612 if (cpu_buffer->ring_meta->head_buffer)
2613 rb_meta_buffer_update(cpu_buffer, bpage);
2614 bpage->range = 1;
2615
2616 atomic_inc(&cpu_buffer->resize_disabled);
2617 } else if (buffer->remote) {
2618 struct ring_buffer_desc *desc = ring_buffer_desc(buffer->remote->desc, cpu);
2619
2620 if (!desc)
2621 goto fail_free_reader;
2622
2623 cpu_buffer->remote = buffer->remote;
2624 cpu_buffer->meta_page = (struct trace_buffer_meta *)(void *)desc->meta_va;
2625 cpu_buffer->nr_pages = nr_pages;
2626 cpu_buffer->subbuf_ids = kzalloc_objs(*cpu_buffer->subbuf_ids,
2627 cpu_buffer->nr_pages + 1);
2628 if (!cpu_buffer->subbuf_ids)
2629 goto fail_free_reader;
2630
2631 /* Remote buffers are read-only and immutable */
2632 atomic_inc(&cpu_buffer->record_disabled);
2633 atomic_inc(&cpu_buffer->resize_disabled);
2634
2635 bpage->page = ring_buffer_desc_page(desc, cpu_buffer->meta_page->reader.id);
2636 if (!bpage->page)
2637 goto fail_free_reader;
2638
2639 bpage->range = 1;
2640 cpu_buffer->subbuf_ids[0] = bpage;
2641 } else {
2642 bpage->page = alloc_cpu_data(cpu, bpage->order);
2643 if (!bpage->page)
2644 goto fail_free_reader;
2645 }
2646
2647 INIT_LIST_HEAD(&cpu_buffer->reader_page->list);
2648 INIT_LIST_HEAD(&cpu_buffer->new_pages);
2649
2650 ret = rb_allocate_pages(cpu_buffer, nr_pages);
2651 if (ret < 0)
2652 goto fail_free_reader;
2653
2654 rb_meta_validate_events(cpu_buffer);
2655
2656 /* If the boot meta was valid then this has already been updated */
2657 meta = cpu_buffer->ring_meta;
2658 if (!meta || !meta->head_buffer ||
2659 !cpu_buffer->head_page || !cpu_buffer->commit_page || !cpu_buffer->tail_page) {
2660 if (meta && meta->head_buffer &&
2661 (cpu_buffer->head_page || cpu_buffer->commit_page || cpu_buffer->tail_page)) {
2662 pr_warn("Ring buffer meta buffers not all mapped\n");
2663 if (!cpu_buffer->head_page)
2664 pr_warn(" Missing head_page\n");
2665 if (!cpu_buffer->commit_page)
2666 pr_warn(" Missing commit_page\n");
2667 if (!cpu_buffer->tail_page)
2668 pr_warn(" Missing tail_page\n");
2669 }
2670
2671 cpu_buffer->head_page
2672 = list_entry(cpu_buffer->pages, struct buffer_page, list);
2673 cpu_buffer->tail_page = cpu_buffer->commit_page = cpu_buffer->head_page;
2674
2675 rb_head_page_activate(cpu_buffer);
2676
2677 if (cpu_buffer->ring_meta)
2678 meta->commit_buffer = meta->head_buffer;
2679 } else {
2680 /* The valid meta buffer still needs to activate the head page */
2681 rb_head_page_activate(cpu_buffer);
2682 }
2683
2684 return_ptr(cpu_buffer);
2685
2686 fail_free_reader:
2687 kfree(cpu_buffer->subbuf_ids);
2688 free_buffer_page(cpu_buffer->reader_page);
2689
2690 return NULL;
2691 }
2692
2693 static void rb_free_cpu_buffer(struct ring_buffer_per_cpu *cpu_buffer)
2694 {
2695 struct list_head *head = cpu_buffer->pages;
2696 struct buffer_page *bpage, *tmp;
2697
2698 irq_work_sync(&cpu_buffer->irq_work.work);
2699
2700 if (cpu_buffer->remote)
2701 kfree(cpu_buffer->subbuf_ids);
2702
2703 free_buffer_page(cpu_buffer->reader_page);
2704
2705 if (head) {
2706 rb_head_page_deactivate(cpu_buffer);
2707
2708 list_for_each_entry_safe(bpage, tmp, head, list) {
2709 list_del_init(&bpage->list);
2710 free_buffer_page(bpage);
2711 }
2712 bpage = list_entry(head, struct buffer_page, list);
2713 free_buffer_page(bpage);
2714 }
2715
2716 free_pages((unsigned long)cpu_buffer->free_page.data, cpu_buffer->free_page.order);
2717
2718 kfree(cpu_buffer);
2719 }
2720
2721 #ifdef CONFIG_RING_BUFFER_PERSISTENT_INJECT
2722 static void rb_test_inject_invalid_pages(struct trace_buffer *buffer)
2723 {
2724 struct ring_buffer_per_cpu *cpu_buffer;
2725 struct ring_buffer_cpu_meta *meta;
2726 struct buffer_data_page *dpage;
2727 unsigned long entry_bytes = 0;
2728 unsigned int subbuf_size;
2729 unsigned long ptr;
2730 int invalid = 0;
2731 int cpu;
2732 int i;
2733
2734 if (!(buffer->flags & RB_FL_TESTING))
2735 return;
2736
2737 guard(preempt)();
2738 cpu = smp_processor_id();
2739
2740 cpu_buffer = buffer->buffers[cpu];
2741 if (!cpu_buffer)
2742 return;
2743 meta = cpu_buffer->ring_meta;
2744 if (!meta)
2745 return;
2746
2747 ptr = (unsigned long)rb_subbufs_from_meta(meta);
2748 subbuf_size = meta->subbuf_size;
2749
2750 for (i = 0; i < meta->nr_subbufs; i++) {
2751 unsigned long idx = meta->buffers[i];
2752
2753 dpage = (void *)(ptr + idx * subbuf_size);
2754 /* Skip unused pages */
2755 if (!rb_data_page_commit(dpage))
2756 continue;
2757
2758 /*
2759 * Invalidate even pages or multiples of 5. This will cause 3
2760 * contiguous invalidated(empty) pages.
2761 */
2762 if (!(i & 0x1) || !(i % 5)) {
2763 local_add(subbuf_size + 1, &dpage->commit);
2764 invalid++;
2765 } else {
2766 /* Count total commit bytes. */
2767 entry_bytes += rb_data_page_size(dpage);
2768 }
2769 }
2770
2771 pr_info("Inject invalidated %d pages on CPU%d, total size: %ld\n",
2772 invalid, cpu, (long)entry_bytes);
2773 meta->nr_invalid = invalid;
2774 meta->entry_bytes = entry_bytes;
2775 }
2776 #else /* !CONFIG_RING_BUFFER_PERSISTENT_INJECT */
2777 #define rb_test_inject_invalid_pages(buffer) do { } while (0)
2778 #endif
2779
2780 /* Stop recording on a persistent buffer and flush cache if needed. */
2781 static int rb_flush_buffer_cb(struct notifier_block *nb, unsigned long event, void *data)
2782 {
2783 struct trace_buffer *buffer = container_of(nb, struct trace_buffer, flush_nb);
2784
2785 ring_buffer_record_off(buffer);
2786 rb_test_inject_invalid_pages(buffer);
2787 arch_ring_buffer_flush_range(buffer->range_addr_start, buffer->range_addr_end);
2788 return NOTIFY_DONE;
2789 }
2790
2791 static struct trace_buffer *alloc_buffer(unsigned long size, unsigned flags,
2792 int order, unsigned long start,
2793 unsigned long end,
2794 unsigned long scratch_size,
2795 struct lock_class_key *key,
2796 struct ring_buffer_remote *remote)
2797 {
2798 struct trace_buffer *buffer __free(kfree) = NULL;
2799 unsigned int subbuf_size;
2800 unsigned long nr_pages;
2801 int bsize;
2802 int cpu;
2803 int ret;
2804
2805 /* keep it in its own cache line */
2806 buffer = kzalloc(ALIGN(sizeof(*buffer), cache_line_size()),
2807 GFP_KERNEL);
2808 if (!buffer)
2809 return NULL;
2810
2811 if (!zalloc_cpumask_var(&buffer->cpumask, GFP_KERNEL))
2812 return NULL;
2813
2814 buffer->subbuf_order = order;
2815 subbuf_size = (PAGE_SIZE << order);
2816
2817 buffer->flags = flags;
2818 buffer->clock = trace_clock_local;
2819 buffer->reader_lock_key = key;
2820
2821 init_irq_work(&buffer->irq_work.work, rb_wake_up_waiters);
2822 init_waitqueue_head(&buffer->irq_work.waiters);
2823
2824
2825 bsize = sizeof(void *) * nr_cpu_ids;
2826 buffer->buffers = kzalloc(ALIGN(bsize, cache_line_size()),
2827 GFP_KERNEL);
2828 if (!buffer->buffers)
2829 goto fail_free_cpumask;
2830
2831 cpu = raw_smp_processor_id();
2832
2833 /* If start/end are specified, then that overrides size */
2834 if (start && end) {
2835 unsigned long buffers_start;
2836 unsigned long ptr;
2837 int n;
2838
2839 /* Make sure that start is word aligned */
2840 start = ALIGN(start, sizeof(long));
2841
2842 /* scratch_size needs to be aligned too */
2843 scratch_size = ALIGN(scratch_size, sizeof(long));
2844
2845 /* Subtract the buffer meta data and word aligned */
2846 buffers_start = start + sizeof(struct ring_buffer_cpu_meta);
2847 buffers_start = ALIGN(buffers_start, sizeof(long));
2848 buffers_start += scratch_size;
2849
2850 /* Calculate the size for the per CPU data */
2851 size = end - buffers_start;
2852 size = size / nr_cpu_ids;
2853
2854 if (size < sizeof(struct ring_buffer_cpu_meta))
2855 goto fail_free_buffers;
2856 /*
2857 * The number of sub-buffers (nr_pages) is determined by the
2858 * total size allocated minus the meta data size.
2859 * Then that is divided by the number of per CPU buffers
2860 * needed, plus account for the integer array index that
2861 * will be appended to the meta data.
2862 */
2863 nr_pages = (size - sizeof(struct ring_buffer_cpu_meta)) /
2864 (subbuf_size + sizeof(int));
2865
2866 if (nr_pages > rb_static_max_pages())
2867 goto fail_free_buffers;
2868
2869 /* Need at least two pages plus the reader page */
2870 if (nr_pages < 3)
2871 goto fail_free_buffers;
2872
2873 again:
2874 /* Make sure that the size fits aligned */
2875 for (n = 0, ptr = buffers_start; n < nr_cpu_ids; n++) {
2876 ptr += sizeof(struct ring_buffer_cpu_meta) +
2877 sizeof(int) * nr_pages;
2878 ptr = ALIGN(ptr, subbuf_size);
2879 ptr += subbuf_size * nr_pages;
2880 }
2881 if (ptr > end) {
2882 if (nr_pages <= 3)
2883 goto fail_free_buffers;
2884 nr_pages--;
2885 goto again;
2886 }
2887
2888 /* nr_pages should not count the reader page */
2889 nr_pages--;
2890 buffer->range_addr_start = start;
2891 buffer->range_addr_end = end;
2892
2893 rb_range_meta_init(buffer, nr_pages, scratch_size);
2894 } else if (remote) {
2895 struct ring_buffer_desc *desc = ring_buffer_desc(remote->desc, cpu);
2896
2897 buffer->remote = remote;
2898 /* The writer is remote. This ring-buffer is read-only */
2899 atomic_inc(&buffer->record_disabled);
2900 nr_pages = desc->nr_page_va - 1;
2901
2902 if (nr_pages > rb_static_max_pages())
2903 goto fail_free_buffers;
2904
2905 if (nr_pages < 2)
2906 goto fail_free_buffers;
2907 } else {
2908 /* need at least two pages */
2909 nr_pages = DIV_ROUND_UP(size, rb_subbuf_capacity(buffer));
2910 if (nr_pages < 2)
2911 nr_pages = 2;
2912 }
2913
2914 cpumask_set_cpu(cpu, buffer->cpumask);
2915 buffer->buffers[cpu] = rb_allocate_cpu_buffer(buffer, nr_pages, cpu);
2916 if (!buffer->buffers[cpu])
2917 goto fail_free_buffers;
2918
2919 ret = cpuhp_state_add_instance(CPUHP_TRACE_RB_PREPARE, &buffer->node);
2920 if (ret < 0)
2921 goto fail_free_buffers;
2922
2923 mutex_init(&buffer->mutex);
2924
2925 /* Persistent ring buffer needs to flush cache before reboot. */
2926 if (start && end) {
2927 buffer->flush_nb.notifier_call = rb_flush_buffer_cb;
2928 atomic_notifier_chain_register(&panic_notifier_list, &buffer->flush_nb);
2929 }
2930
2931 return_ptr(buffer);
2932
2933 fail_free_buffers:
2934 for_each_buffer_cpu(buffer, cpu) {
2935 if (buffer->buffers[cpu])
2936 rb_free_cpu_buffer(buffer->buffers[cpu]);
2937 }
2938 kfree(buffer->buffers);
2939
2940 fail_free_cpumask:
2941 free_cpumask_var(buffer->cpumask);
2942
2943 return NULL;
2944 }
2945
2946 /**
2947 * __ring_buffer_alloc - allocate a new ring_buffer
2948 * @size: the size in bytes per cpu that is needed.
2949 * @flags: attributes to set for the ring buffer.
2950 * @key: ring buffer reader_lock_key.
2951 *
2952 * Currently the only flag that is available is the RB_FL_OVERWRITE
2953 * flag. This flag means that the buffer will overwrite old data
2954 * when the buffer wraps. If this flag is not set, the buffer will
2955 * drop data when the tail hits the head.
2956 */
2957 struct trace_buffer *__ring_buffer_alloc(unsigned long size, unsigned flags,
2958 struct lock_class_key *key)
2959 {
2960 /* Default buffer page size - one system page */
2961 return alloc_buffer(size, flags, 0, 0, 0, 0, key, NULL);
2962
2963 }
2964 EXPORT_SYMBOL_GPL(__ring_buffer_alloc);
2965
2966 /**
2967 * __ring_buffer_alloc_range - allocate a new ring_buffer from existing memory
2968 * @size: the size in bytes per cpu that is needed.
2969 * @flags: attributes to set for the ring buffer.
2970 * @order: sub-buffer order
2971 * @start: start of allocated range
2972 * @range_size: size of allocated range
2973 * @scratch_size: size of scratch area (for preallocated memory buffers)
2974 * @key: ring buffer reader_lock_key.
2975 *
2976 * Currently the only flag that is available is the RB_FL_OVERWRITE
2977 * flag. This flag means that the buffer will overwrite old data
2978 * when the buffer wraps. If this flag is not set, the buffer will
2979 * drop data when the tail hits the head.
2980 */
2981 struct trace_buffer *__ring_buffer_alloc_range(unsigned long size, unsigned flags,
2982 int order, unsigned long start,
2983 unsigned long range_size,
2984 unsigned long scratch_size,
2985 struct lock_class_key *key)
2986 {
2987 return alloc_buffer(size, flags, order, start, start + range_size,
2988 scratch_size, key, NULL);
2989 }
2990
2991 /**
2992 * __ring_buffer_alloc_remote - allocate a new ring_buffer from a remote
2993 * @remote: Contains a description of the ring-buffer pages and remote callbacks.
2994 * @key: ring buffer reader_lock_key.
2995 */
2996 struct trace_buffer *__ring_buffer_alloc_remote(struct ring_buffer_remote *remote,
2997 struct lock_class_key *key)
2998 {
2999 return alloc_buffer(0, 0, 0, 0, 0, 0, key, remote);
3000 }
3001
3002 void *ring_buffer_meta_scratch(struct trace_buffer *buffer, unsigned int *size)
3003 {
3004 struct ring_buffer_meta *meta;
3005 void *ptr;
3006
3007 if (!buffer || !buffer->meta)
3008 return NULL;
3009
3010 meta = buffer->meta;
3011
3012 ptr = (void *)ALIGN((unsigned long)meta + sizeof(*meta), sizeof(long));
3013
3014 if (size)
3015 *size = (void *)meta + meta->buffers_offset - ptr;
3016
3017 return ptr;
3018 }
3019
3020 /**
3021 * ring_buffer_free - free a ring buffer.
3022 * @buffer: the buffer to free.
3023 */
3024 void
3025 ring_buffer_free(struct trace_buffer *buffer)
3026 {
3027 int cpu;
3028
3029 if (buffer->range_addr_start && buffer->range_addr_end)
3030 atomic_notifier_chain_unregister(&panic_notifier_list, &buffer->flush_nb);
3031
3032 cpuhp_state_remove_instance(CPUHP_TRACE_RB_PREPARE, &buffer->node);
3033
3034 irq_work_sync(&buffer->irq_work.work);
3035
3036 for_each_buffer_cpu(buffer, cpu)
3037 rb_free_cpu_buffer(buffer->buffers[cpu]);
3038
3039 kfree(buffer->buffers);
3040 free_cpumask_var(buffer->cpumask);
3041
3042 kfree(buffer);
3043 }
3044 EXPORT_SYMBOL_GPL(ring_buffer_free);
3045
3046 void ring_buffer_set_clock(struct trace_buffer *buffer,
3047 u64 (*clock)(void))
3048 {
3049 buffer->clock = clock;
3050 }
3051
3052 void ring_buffer_set_time_stamp_abs(struct trace_buffer *buffer, bool abs)
3053 {
3054 buffer->time_stamp_abs = abs;
3055 }
3056
3057 bool ring_buffer_time_stamp_abs(struct trace_buffer *buffer)
3058 {
3059 return buffer->time_stamp_abs;
3060 }
3061
3062 static inline unsigned long rb_page_entries(struct buffer_page *bpage)
3063 {
3064 return local_read(&bpage->entries) & RB_WRITE_MASK;
3065 }
3066
3067 static inline unsigned long rb_page_write(struct buffer_page *bpage)
3068 {
3069 return local_read(&bpage->write) & RB_WRITE_MASK;
3070 }
3071
3072 static bool
3073 rb_remove_pages(struct ring_buffer_per_cpu *cpu_buffer, unsigned long nr_pages)
3074 {
3075 struct list_head *tail_page, *to_remove, *next_page;
3076 struct buffer_page *to_remove_page, *tmp_iter_page;
3077 struct buffer_page *last_page, *first_page;
3078 unsigned long nr_removed;
3079 unsigned long head_bit;
3080 int page_entries;
3081
3082 head_bit = 0;
3083
3084 raw_spin_lock_irq(&cpu_buffer->reader_lock);
3085 atomic_inc(&cpu_buffer->record_disabled);
3086 /*
3087 * We don't race with the readers since we have acquired the reader
3088 * lock. We also don't race with writers after disabling recording.
3089 * This makes it easy to figure out the first and the last page to be
3090 * removed from the list. We unlink all the pages in between including
3091 * the first and last pages. This is done in a busy loop so that we
3092 * lose the least number of traces.
3093 * The pages are freed after we restart recording and unlock readers.
3094 */
3095 tail_page = &cpu_buffer->tail_page->list;
3096
3097 /*
3098 * tail page might be on reader page, we remove the next page
3099 * from the ring buffer
3100 */
3101 if (cpu_buffer->tail_page == cpu_buffer->reader_page)
3102 tail_page = rb_list_head(tail_page->next);
3103 to_remove = tail_page;
3104
3105 /* start of pages to remove */
3106 first_page = list_entry(rb_list_head(to_remove->next),
3107 struct buffer_page, list);
3108
3109 for (nr_removed = 0; nr_removed < nr_pages; nr_removed++) {
3110 to_remove = rb_list_head(to_remove)->next;
3111 head_bit |= (unsigned long)to_remove & RB_PAGE_HEAD;
3112 }
3113 /* Read iterators need to reset themselves when some pages removed */
3114 cpu_buffer->pages_removed += nr_removed;
3115
3116 next_page = rb_list_head(to_remove)->next;
3117
3118 /*
3119 * Now we remove all pages between tail_page and next_page.
3120 * Make sure that we have head_bit value preserved for the
3121 * next page
3122 */
3123 tail_page->next = (struct list_head *)((unsigned long)next_page |
3124 head_bit);
3125 next_page = rb_list_head(next_page);
3126 next_page->prev = tail_page;
3127
3128 /* make sure pages points to a valid page in the ring buffer */
3129 cpu_buffer->pages = next_page;
3130 cpu_buffer->cnt++;
3131
3132 /* update head page */
3133 if (head_bit)
3134 cpu_buffer->head_page = list_entry(next_page,
3135 struct buffer_page, list);
3136
3137 /* pages are removed, resume tracing and then free the pages */
3138 atomic_dec(&cpu_buffer->record_disabled);
3139 raw_spin_unlock_irq(&cpu_buffer->reader_lock);
3140
3141 RB_WARN_ON(cpu_buffer, list_empty(cpu_buffer->pages));
3142
3143 /* last buffer page to remove */
3144 last_page = list_entry(rb_list_head(to_remove), struct buffer_page,
3145 list);
3146 tmp_iter_page = first_page;
3147
3148 do {
3149 cond_resched();
3150
3151 to_remove_page = tmp_iter_page;
3152 rb_inc_page(&tmp_iter_page);
3153
3154 /* update the counters */
3155 page_entries = rb_page_entries(to_remove_page);
3156 if (page_entries) {
3157 /*
3158 * If something was added to this page, it was full
3159 * since it is not the tail page. So we deduct the
3160 * bytes consumed in ring buffer from here.
3161 * Increment overrun to account for the lost events.
3162 */
3163 local_add(page_entries, &cpu_buffer->overrun);
3164 local_sub(rb_page_commit(to_remove_page), &cpu_buffer->entries_bytes);
3165 local_inc(&cpu_buffer->pages_lost);
3166 }
3167
3168 /*
3169 * We have already removed references to this list item, just
3170 * free up the buffer_page and its page
3171 */
3172 free_buffer_page(to_remove_page);
3173 nr_removed--;
3174
3175 } while (to_remove_page != last_page);
3176
3177 RB_WARN_ON(cpu_buffer, nr_removed);
3178
3179 return nr_removed == 0;
3180 }
3181
3182 static bool
3183 rb_insert_pages(struct ring_buffer_per_cpu *cpu_buffer)
3184 {
3185 struct list_head *pages = &cpu_buffer->new_pages;
3186 unsigned long flags;
3187 bool success;
3188 int retries;
3189
3190 /* Can be called at early boot up, where interrupts must not been enabled */
3191 raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
3192 /*
3193 * We are holding the reader lock, so the reader page won't be swapped
3194 * in the ring buffer. Now we are racing with the writer trying to
3195 * move head page and the tail page.
3196 * We are going to adapt the reader page update process where:
3197 * 1. We first splice the start and end of list of new pages between
3198 * the head page and its previous page.
3199 * 2. We cmpxchg the prev_page->next to point from head page to the
3200 * start of new pages list.
3201 * 3. Finally, we update the head->prev to the end of new list.
3202 *
3203 * We will try this process 10 times, to make sure that we don't keep
3204 * spinning.
3205 */
3206 retries = 10;
3207 success = false;
3208 while (retries--) {
3209 struct list_head *head_page, *prev_page;
3210 struct list_head *last_page, *first_page;
3211 struct list_head *head_page_with_bit;
3212 struct buffer_page *hpage = rb_set_head_page(cpu_buffer);
3213
3214 if (!hpage)
3215 break;
3216 head_page = &hpage->list;
3217 prev_page = head_page->prev;
3218
3219 first_page = pages->next;
3220 last_page = pages->prev;
3221
3222 head_page_with_bit = (struct list_head *)
3223 ((unsigned long)head_page | RB_PAGE_HEAD);
3224
3225 last_page->next = head_page_with_bit;
3226 first_page->prev = prev_page;
3227
3228 /* caution: head_page_with_bit gets updated on cmpxchg failure */
3229 if (try_cmpxchg(&prev_page->next,
3230 &head_page_with_bit, first_page)) {
3231 /*
3232 * yay, we replaced the page pointer to our new list,
3233 * now, we just have to update to head page's prev
3234 * pointer to point to end of list
3235 */
3236 head_page->prev = last_page;
3237 cpu_buffer->cnt++;
3238 success = true;
3239 break;
3240 }
3241 }
3242
3243 if (success)
3244 INIT_LIST_HEAD(pages);
3245 /*
3246 * If we weren't successful in adding in new pages, warn and stop
3247 * tracing
3248 */
3249 RB_WARN_ON(cpu_buffer, !success);
3250 raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
3251
3252 /* free pages if they weren't inserted */
3253 if (!success) {
3254 struct buffer_page *bpage, *tmp;
3255 list_for_each_entry_safe(bpage, tmp, &cpu_buffer->new_pages,
3256 list) {
3257 list_del_init(&bpage->list);
3258 free_buffer_page(bpage);
3259 }
3260 }
3261 return success;
3262 }
3263
3264 static void rb_update_pages(struct ring_buffer_per_cpu *cpu_buffer)
3265 {
3266 bool success;
3267
3268 if (cpu_buffer->nr_pages_to_update > 0)
3269 success = rb_insert_pages(cpu_buffer);
3270 else
3271 success = rb_remove_pages(cpu_buffer,
3272 -cpu_buffer->nr_pages_to_update);
3273
3274 if (success)
3275 cpu_buffer->nr_pages += cpu_buffer->nr_pages_to_update;
3276 }
3277
3278 static void update_pages_handler(struct work_struct *work)
3279 {
3280 struct ring_buffer_per_cpu *cpu_buffer = container_of(work,
3281 struct ring_buffer_per_cpu, update_pages_work);
3282 rb_update_pages(cpu_buffer);
3283 complete(&cpu_buffer->update_done);
3284 }
3285
3286 /**
3287 * ring_buffer_resize - resize the ring buffer
3288 * @buffer: the buffer to resize.
3289 * @size: the new size.
3290 * @cpu_id: the cpu buffer to resize
3291 *
3292 * Minimum size is 2 * rb_subbuf_capacity(buffer).
3293 *
3294 * Returns 0 on success and < 0 on failure.
3295 */
3296 int ring_buffer_resize(struct trace_buffer *buffer, unsigned long size,
3297 int cpu_id)
3298 {
3299 struct ring_buffer_per_cpu *cpu_buffer;
3300 unsigned long nr_pages;
3301 int cpu, err;
3302
3303 /*
3304 * Always succeed at resizing a non-existent buffer:
3305 */
3306 if (!buffer)
3307 return 0;
3308
3309 /* Make sure the requested buffer exists */
3310 if (cpu_id != RING_BUFFER_ALL_CPUS &&
3311 !cpumask_test_cpu(cpu_id, buffer->cpumask))
3312 return 0;
3313
3314 /*
3315 * Keep CPUs from coming online while resizing to synchronize
3316 * with new per CPU buffers being created.
3317 */
3318 guard(cpus_read_lock)();
3319
3320 /* prevent another thread from changing buffer sizes */
3321 mutex_lock(&buffer->mutex);
3322 atomic_inc(&buffer->resizing);
3323
3324 nr_pages = DIV_ROUND_UP(size, rb_subbuf_capacity(buffer));
3325
3326 /* we need a minimum of two pages */
3327 if (nr_pages < 2)
3328 nr_pages = 2;
3329
3330 if (cpu_id == RING_BUFFER_ALL_CPUS) {
3331 /*
3332 * Don't succeed if resizing is disabled, as a reader might be
3333 * manipulating the ring buffer and is expecting a sane state while
3334 * this is true.
3335 */
3336 for_each_buffer_cpu(buffer, cpu) {
3337 cpu_buffer = buffer->buffers[cpu];
3338 if (atomic_read(&cpu_buffer->resize_disabled)) {
3339 err = -EBUSY;
3340 goto out_err_unlock;
3341 }
3342 }
3343
3344 /* calculate the pages to update */
3345 for_each_buffer_cpu(buffer, cpu) {
3346 cpu_buffer = buffer->buffers[cpu];
3347
3348 cpu_buffer->nr_pages_to_update = nr_pages -
3349 cpu_buffer->nr_pages;
3350 /*
3351 * nothing more to do for removing pages or no update
3352 */
3353 if (cpu_buffer->nr_pages_to_update <= 0)
3354 continue;
3355 /*
3356 * to add pages, make sure all new pages can be
3357 * allocated without receiving ENOMEM
3358 */
3359 INIT_LIST_HEAD(&cpu_buffer->new_pages);
3360 if (__rb_allocate_pages(cpu_buffer, cpu_buffer->nr_pages_to_update,
3361 &cpu_buffer->new_pages)) {
3362 /* not enough memory for new pages */
3363 err = -ENOMEM;
3364 goto out_err;
3365 }
3366
3367 cond_resched();
3368 }
3369
3370 /*
3371 * Fire off all the required work handlers
3372 * We can't schedule on offline CPUs, but it's not necessary
3373 * since we can change their buffer sizes without any race.
3374 */
3375 for_each_buffer_cpu(buffer, cpu) {
3376 cpu_buffer = buffer->buffers[cpu];
3377 if (!cpu_buffer->nr_pages_to_update)
3378 continue;
3379
3380 /* Can't run something on an offline CPU. */
3381 if (!cpu_online(cpu)) {
3382 rb_update_pages(cpu_buffer);
3383 cpu_buffer->nr_pages_to_update = 0;
3384 } else {
3385 /* Run directly if possible. */
3386 migrate_disable();
3387 if (cpu != smp_processor_id()) {
3388 migrate_enable();
3389 schedule_work_on(cpu,
3390 &cpu_buffer->update_pages_work);
3391 } else {
3392 update_pages_handler(&cpu_buffer->update_pages_work);
3393 migrate_enable();
3394 }
3395 }
3396 }
3397
3398 /* wait for all the updates to complete */
3399 for_each_buffer_cpu(buffer, cpu) {
3400 cpu_buffer = buffer->buffers[cpu];
3401 if (!cpu_buffer->nr_pages_to_update)
3402 continue;
3403
3404 if (cpu_online(cpu))
3405 wait_for_completion(&cpu_buffer->update_done);
3406 cpu_buffer->nr_pages_to_update = 0;
3407 }
3408
3409 } else {
3410 cpu_buffer = buffer->buffers[cpu_id];
3411
3412 if (nr_pages == cpu_buffer->nr_pages)
3413 goto out;
3414
3415 /*
3416 * Don't succeed if resizing is disabled, as a reader might be
3417 * manipulating the ring buffer and is expecting a sane state while
3418 * this is true.
3419 */
3420 if (atomic_read(&cpu_buffer->resize_disabled)) {
3421 err = -EBUSY;
3422 goto out_err_unlock;
3423 }
3424
3425 cpu_buffer->nr_pages_to_update = nr_pages -
3426 cpu_buffer->nr_pages;
3427
3428 INIT_LIST_HEAD(&cpu_buffer->new_pages);
3429 if (cpu_buffer->nr_pages_to_update > 0 &&
3430 __rb_allocate_pages(cpu_buffer, cpu_buffer->nr_pages_to_update,
3431 &cpu_buffer->new_pages)) {
3432 err = -ENOMEM;
3433 goto out_err;
3434 }
3435
3436 /* Can't run something on an offline CPU. */
3437 if (!cpu_online(cpu_id))
3438 rb_update_pages(cpu_buffer);
3439 else {
3440 /* Run directly if possible. */
3441 migrate_disable();
3442 if (cpu_id == smp_processor_id()) {
3443 rb_update_pages(cpu_buffer);
3444 migrate_enable();
3445 } else {
3446 migrate_enable();
3447 schedule_work_on(cpu_id,
3448 &cpu_buffer->update_pages_work);
3449 wait_for_completion(&cpu_buffer->update_done);
3450 }
3451 }
3452
3453 cpu_buffer->nr_pages_to_update = 0;
3454 }
3455
3456 out:
3457 /*
3458 * The ring buffer resize can happen with the ring buffer
3459 * enabled, so that the update disturbs the tracing as little
3460 * as possible. But if the buffer is disabled, we do not need
3461 * to worry about that, and we can take the time to verify
3462 * that the buffer is not corrupt.
3463 */
3464 if (atomic_read(&buffer->record_disabled)) {
3465 atomic_inc(&buffer->record_disabled);
3466 /*
3467 * Even though the buffer was disabled, we must make sure
3468 * that it is truly disabled before calling rb_check_pages.
3469 * There could have been a race between checking
3470 * record_disable and incrementing it.
3471 */
3472 synchronize_rcu();
3473 for_each_buffer_cpu(buffer, cpu) {
3474 cpu_buffer = buffer->buffers[cpu];
3475 rb_check_pages(cpu_buffer);
3476 }
3477 atomic_dec(&buffer->record_disabled);
3478 }
3479
3480 atomic_dec(&buffer->resizing);
3481 mutex_unlock(&buffer->mutex);
3482 return 0;
3483
3484 out_err:
3485 for_each_buffer_cpu(buffer, cpu) {
3486 struct buffer_page *bpage, *tmp;
3487
3488 cpu_buffer = buffer->buffers[cpu];
3489 cpu_buffer->nr_pages_to_update = 0;
3490
3491 if (list_empty(&cpu_buffer->new_pages))
3492 continue;
3493
3494 list_for_each_entry_safe(bpage, tmp, &cpu_buffer->new_pages,
3495 list) {
3496 list_del_init(&bpage->list);
3497 free_buffer_page(bpage);
3498
3499 cond_resched();
3500 }
3501 }
3502 out_err_unlock:
3503 atomic_dec(&buffer->resizing);
3504 mutex_unlock(&buffer->mutex);
3505 return err;
3506 }
3507 EXPORT_SYMBOL_GPL(ring_buffer_resize);
3508
3509 void ring_buffer_change_overwrite(struct trace_buffer *buffer, int val)
3510 {
3511 mutex_lock(&buffer->mutex);
3512 if (val)
3513 buffer->flags |= RB_FL_OVERWRITE;
3514 else
3515 buffer->flags &= ~RB_FL_OVERWRITE;
3516 mutex_unlock(&buffer->mutex);
3517 }
3518 EXPORT_SYMBOL_GPL(ring_buffer_change_overwrite);
3519
3520 static __always_inline void *__rb_page_index(struct buffer_page *bpage, unsigned index)
3521 {
3522 return bpage->page->data + index;
3523 }
3524
3525 static __always_inline struct ring_buffer_event *
3526 rb_reader_event(struct ring_buffer_per_cpu *cpu_buffer)
3527 {
3528 return __rb_page_index(cpu_buffer->reader_page,
3529 cpu_buffer->reader_page->read);
3530 }
3531
3532 static struct ring_buffer_event *
3533 rb_iter_head_event(struct ring_buffer_iter *iter)
3534 {
3535 struct ring_buffer_event *event;
3536 struct buffer_page *iter_head_page = iter->head_page;
3537 unsigned long commit;
3538 unsigned length;
3539
3540 if (iter->head != iter->next_event)
3541 return iter->event;
3542
3543 /*
3544 * When the writer goes across pages, it issues a cmpxchg which
3545 * is a mb(), which will synchronize with the rmb here.
3546 * (see rb_tail_page_update() and __rb_reserve_next())
3547 */
3548 commit = rb_page_size(iter_head_page);
3549 smp_rmb();
3550
3551 /* An event needs to be at least 8 bytes in size */
3552 if (iter->head > commit - 8)
3553 goto reset;
3554
3555 event = __rb_page_index(iter_head_page, iter->head);
3556 length = rb_event_length(event);
3557
3558 /*
3559 * READ_ONCE() doesn't work on functions and we don't want the
3560 * compiler doing any crazy optimizations with length.
3561 */
3562 barrier();
3563
3564 if ((iter->head + length) > commit || length > iter->event_size)
3565 /* Writer corrupted the read? */
3566 goto reset;
3567
3568 memcpy(iter->event, event, length);
3569 /*
3570 * If the page stamp is still the same after this rmb() then the
3571 * event was safely copied without the writer entering the page.
3572 */
3573 smp_rmb();
3574
3575 /* Make sure the page didn't change since we read this */
3576 if (iter->page_stamp != iter_head_page->page->time_stamp ||
3577 commit > rb_page_size(iter_head_page))
3578 goto reset;
3579
3580 iter->next_event = iter->head + length;
3581 return iter->event;
3582 reset:
3583 /* Reset to the beginning */
3584 iter->page_stamp = iter->read_stamp = iter->head_page->page->time_stamp;
3585 iter->head = 0;
3586 iter->next_event = 0;
3587 iter->missed_events = 1;
3588 return NULL;
3589 }
3590
3591 static __always_inline unsigned
3592 rb_commit_index(struct ring_buffer_per_cpu *cpu_buffer)
3593 {
3594 return rb_page_commit(cpu_buffer->commit_page);
3595 }
3596
3597 static __always_inline unsigned
3598 rb_event_index(struct ring_buffer_per_cpu *cpu_buffer, struct ring_buffer_event *event)
3599 {
3600 unsigned long addr = (unsigned long)event;
3601
3602 addr &= (unsigned long)rb_subbuf_size(cpu_buffer->buffer) - 1;
3603
3604 return addr - BUF_PAGE_HDR_SIZE;
3605 }
3606
3607 static void rb_inc_iter(struct ring_buffer_iter *iter)
3608 {
3609 struct ring_buffer_per_cpu *cpu_buffer = iter->cpu_buffer;
3610
3611 /*
3612 * The iterator could be on the reader page (it starts there).
3613 * But the head could have moved, since the reader was
3614 * found. Check for this case and assign the iterator
3615 * to the head page instead of next.
3616 */
3617 if (iter->head_page == cpu_buffer->reader_page)
3618 iter->head_page = rb_set_head_page(cpu_buffer);
3619 else
3620 rb_inc_page(&iter->head_page);
3621
3622 if (rb_page_commit(iter->head_page) & RB_MISSED_EVENTS)
3623 iter->missed_events = -1;
3624
3625 iter->page_stamp = iter->read_stamp = iter->head_page->page->time_stamp;
3626 iter->head = 0;
3627 iter->next_event = 0;
3628 }
3629
3630 /* Return the index into the sub-buffers for a given sub-buffer */
3631 static int rb_meta_subbuf_idx(struct ring_buffer_cpu_meta *meta, void *subbuf)
3632 {
3633 void *subbuf_array = rb_subbufs_from_meta(meta);
3634
3635 return (subbuf - subbuf_array) / meta->subbuf_size;
3636 }
3637
3638 static void rb_update_meta_head(struct ring_buffer_per_cpu *cpu_buffer,
3639 struct buffer_page *next_page)
3640 {
3641 struct ring_buffer_cpu_meta *meta = cpu_buffer->ring_meta;
3642 unsigned long old_head = (unsigned long)next_page->page;
3643 unsigned long new_head;
3644
3645 rb_inc_page(&next_page);
3646 new_head = (unsigned long)next_page->page;
3647
3648 /*
3649 * Only move it forward once, if something else came in and
3650 * moved it forward, then we don't want to touch it.
3651 */
3652 (void)cmpxchg(&meta->head_buffer, old_head, new_head);
3653 }
3654
3655 static void rb_update_meta_reader(struct ring_buffer_per_cpu *cpu_buffer,
3656 struct buffer_page *reader)
3657 {
3658 struct ring_buffer_cpu_meta *meta = cpu_buffer->ring_meta;
3659 void *old_reader = cpu_buffer->reader_page->page;
3660 void *new_reader = reader->page;
3661 int id;
3662
3663 id = reader->id;
3664 cpu_buffer->reader_page->id = id;
3665 reader->id = 0;
3666
3667 meta->buffers[0] = rb_meta_subbuf_idx(meta, new_reader);
3668 meta->buffers[id] = rb_meta_subbuf_idx(meta, old_reader);
3669
3670 /* The head pointer is the one after the reader */
3671 rb_update_meta_head(cpu_buffer, reader);
3672 }
3673
3674 /*
3675 * rb_handle_head_page - writer hit the head page
3676 *
3677 * Returns: +1 to retry page
3678 * 0 to continue
3679 * -1 on error
3680 */
3681 static int
3682 rb_handle_head_page(struct ring_buffer_per_cpu *cpu_buffer,
3683 struct buffer_page *tail_page,
3684 struct buffer_page *next_page)
3685 {
3686 struct buffer_page *new_head;
3687 int entries;
3688 int type;
3689 int ret;
3690
3691 entries = rb_page_entries(next_page);
3692
3693 /*
3694 * The hard part is here. We need to move the head
3695 * forward, and protect against both readers on
3696 * other CPUs and writers coming in via interrupts.
3697 */
3698 type = rb_head_page_set_update(cpu_buffer, next_page, tail_page,
3699 RB_PAGE_HEAD);
3700
3701 /*
3702 * type can be one of four:
3703 * NORMAL - an interrupt already moved it for us
3704 * HEAD - we are the first to get here.
3705 * UPDATE - we are the interrupt interrupting
3706 * a current move.
3707 * MOVED - a reader on another CPU moved the next
3708 * pointer to its reader page. Give up
3709 * and try again.
3710 */
3711
3712 switch (type) {
3713 case RB_PAGE_HEAD:
3714 /*
3715 * We changed the head to UPDATE, thus
3716 * it is our responsibility to update
3717 * the counters.
3718 */
3719 local_add(entries, &cpu_buffer->overrun);
3720 local_sub(rb_page_commit(next_page), &cpu_buffer->entries_bytes);
3721 local_inc(&cpu_buffer->pages_lost);
3722
3723 if (cpu_buffer->ring_meta)
3724 rb_update_meta_head(cpu_buffer, next_page);
3725 /*
3726 * The entries will be zeroed out when we move the
3727 * tail page.
3728 */
3729
3730 /* still more to do */
3731 break;
3732
3733 case RB_PAGE_UPDATE:
3734 /*
3735 * This is an interrupt that interrupt the
3736 * previous update. Still more to do.
3737 */
3738 break;
3739 case RB_PAGE_NORMAL:
3740 /*
3741 * An interrupt came in before the update
3742 * and processed this for us.
3743 * Nothing left to do.
3744 */
3745 return 1;
3746 case RB_PAGE_MOVED:
3747 /*
3748 * The reader is on another CPU and just did
3749 * a swap with our next_page.
3750 * Try again.
3751 */
3752 return 1;
3753 default:
3754 RB_WARN_ON(cpu_buffer, 1); /* WTF??? */
3755 return -1;
3756 }
3757
3758 /*
3759 * Now that we are here, the old head pointer is
3760 * set to UPDATE. This will keep the reader from
3761 * swapping the head page with the reader page.
3762 * The reader (on another CPU) will spin till
3763 * we are finished.
3764 *
3765 * We just need to protect against interrupts
3766 * doing the job. We will set the next pointer
3767 * to HEAD. After that, we set the old pointer
3768 * to NORMAL, but only if it was HEAD before.
3769 * otherwise we are an interrupt, and only
3770 * want the outer most commit to reset it.
3771 */
3772 new_head = next_page;
3773 rb_inc_page(&new_head);
3774
3775 ret = rb_head_page_set_head(cpu_buffer, new_head, next_page,
3776 RB_PAGE_NORMAL);
3777
3778 /*
3779 * Valid returns are:
3780 * HEAD - an interrupt came in and already set it.
3781 * NORMAL - One of two things:
3782 * 1) We really set it.
3783 * 2) A bunch of interrupts came in and moved
3784 * the page forward again.
3785 */
3786 switch (ret) {
3787 case RB_PAGE_HEAD:
3788 case RB_PAGE_NORMAL:
3789 /* OK */
3790 break;
3791 default:
3792 RB_WARN_ON(cpu_buffer, 1);
3793 return -1;
3794 }
3795
3796 /*
3797 * It is possible that an interrupt came in,
3798 * set the head up, then more interrupts came in
3799 * and moved it again. When we get back here,
3800 * the page would have been set to NORMAL but we
3801 * just set it back to HEAD.
3802 *
3803 * How do you detect this? Well, if that happened
3804 * the tail page would have moved.
3805 */
3806 if (ret == RB_PAGE_NORMAL) {
3807 struct buffer_page *buffer_tail_page;
3808
3809 buffer_tail_page = READ_ONCE(cpu_buffer->tail_page);
3810 /*
3811 * If the tail had moved passed next, then we need
3812 * to reset the pointer.
3813 */
3814 if (buffer_tail_page != tail_page &&
3815 buffer_tail_page != next_page)
3816 rb_head_page_set_normal(cpu_buffer, new_head,
3817 next_page,
3818 RB_PAGE_HEAD);
3819 }
3820
3821 /*
3822 * If this was the outer most commit (the one that
3823 * changed the original pointer from HEAD to UPDATE),
3824 * then it is up to us to reset it to NORMAL.
3825 */
3826 if (type == RB_PAGE_HEAD) {
3827 ret = rb_head_page_set_normal(cpu_buffer, next_page,
3828 tail_page,
3829 RB_PAGE_UPDATE);
3830 if (RB_WARN_ON(cpu_buffer,
3831 ret != RB_PAGE_UPDATE))
3832 return -1;
3833 }
3834
3835 return 0;
3836 }
3837
3838 static inline void
3839 rb_reset_tail(struct ring_buffer_per_cpu *cpu_buffer,
3840 unsigned long tail, struct rb_event_info *info)
3841 {
3842 struct buffer_page *tail_page = info->tail_page;
3843 unsigned long bsize = rb_page_capacity(tail_page);
3844 struct ring_buffer_event *event;
3845 unsigned long length = info->length;
3846
3847 /*
3848 * Only the event that crossed the page boundary
3849 * must fill the old tail_page with padding.
3850 */
3851 if (tail >= bsize) {
3852 /*
3853 * If the page was filled, then we still need
3854 * to update the real_end. Reset it to zero
3855 * and the reader will ignore it.
3856 */
3857 if (tail == bsize)
3858 tail_page->real_end = 0;
3859
3860 local_sub(length, &tail_page->write);
3861 return;
3862 }
3863
3864 event = __rb_page_index(tail_page, tail);
3865
3866 /*
3867 * Save the original length to the meta data.
3868 * This will be used by the reader to add lost event
3869 * counter.
3870 */
3871 tail_page->real_end = tail;
3872
3873 /*
3874 * If this event is bigger than the minimum size, then
3875 * we need to be careful that we don't subtract the
3876 * write counter enough to allow another writer to slip
3877 * in on this page.
3878 * We put in a discarded commit instead, to make sure
3879 * that this space is not used again, and this space will
3880 * not be accounted into 'entries_bytes'.
3881 *
3882 * If we are less than the minimum size, we don't need to
3883 * worry about it.
3884 */
3885 if (tail > (bsize - RB_EVNT_MIN_SIZE)) {
3886 /* No room for any events */
3887
3888 /* Mark the rest of the page with padding */
3889 rb_event_set_padding(event);
3890
3891 /* Make sure the padding is visible before the write update */
3892 smp_wmb();
3893
3894 /* Set the write back to the previous setting */
3895 local_sub(length, &tail_page->write);
3896 return;
3897 }
3898
3899 /* Put in a discarded event */
3900 event->array[0] = (bsize - tail) - RB_EVNT_HDR_SIZE;
3901 event->type_len = RINGBUF_TYPE_PADDING;
3902 /* time delta must be non zero */
3903 event->time_delta = 1;
3904
3905 /* account for padding bytes */
3906 local_add(bsize - tail, &cpu_buffer->entries_bytes);
3907
3908 /* Make sure the padding is visible before the tail_page->write update */
3909 smp_wmb();
3910
3911 /* Set write to end of buffer */
3912 length = (tail + length) - bsize;
3913 local_sub(length, &tail_page->write);
3914 }
3915
3916 static inline void rb_end_commit(struct ring_buffer_per_cpu *cpu_buffer);
3917
3918 /*
3919 * This is the slow path, force gcc not to inline it.
3920 */
3921 static noinline struct ring_buffer_event *
3922 rb_move_tail(struct ring_buffer_per_cpu *cpu_buffer,
3923 unsigned long tail, struct rb_event_info *info)
3924 {
3925 struct buffer_page *tail_page = info->tail_page;
3926 struct buffer_page *commit_page = cpu_buffer->commit_page;
3927 struct trace_buffer *buffer = cpu_buffer->buffer;
3928 struct buffer_page *next_page;
3929 int ret;
3930
3931 next_page = tail_page;
3932
3933 rb_inc_page(&next_page);
3934
3935 /*
3936 * If for some reason, we had an interrupt storm that made
3937 * it all the way around the buffer, bail, and warn
3938 * about it.
3939 */
3940 if (unlikely(next_page == commit_page)) {
3941 local_inc(&cpu_buffer->commit_overrun);
3942 goto out_reset;
3943 }
3944
3945 /*
3946 * This is where the fun begins!
3947 *
3948 * We are fighting against races between a reader that
3949 * could be on another CPU trying to swap its reader
3950 * page with the buffer head.
3951 *
3952 * We are also fighting against interrupts coming in and
3953 * moving the head or tail on us as well.
3954 *
3955 * If the next page is the head page then we have filled
3956 * the buffer, unless the commit page is still on the
3957 * reader page.
3958 */
3959 if (rb_is_head_page(next_page, &tail_page->list)) {
3960
3961 /*
3962 * If the commit is not on the reader page, then
3963 * move the header page.
3964 */
3965 if (!rb_is_reader_page(cpu_buffer->commit_page)) {
3966 /*
3967 * If we are not in overwrite mode,
3968 * this is easy, just stop here.
3969 */
3970 if (!(buffer->flags & RB_FL_OVERWRITE)) {
3971 local_inc(&cpu_buffer->dropped_events);
3972 goto out_reset;
3973 }
3974
3975 ret = rb_handle_head_page(cpu_buffer,
3976 tail_page,
3977 next_page);
3978 if (ret < 0)
3979 goto out_reset;
3980 if (ret)
3981 goto out_again;
3982 } else {
3983 /*
3984 * We need to be careful here too. The
3985 * commit page could still be on the reader
3986 * page. We could have a small buffer, and
3987 * have filled up the buffer with events
3988 * from interrupts and such, and wrapped.
3989 *
3990 * Note, if the tail page is also on the
3991 * reader_page, we let it move out.
3992 */
3993 if (unlikely((cpu_buffer->commit_page !=
3994 cpu_buffer->tail_page) &&
3995 (cpu_buffer->commit_page ==
3996 cpu_buffer->reader_page))) {
3997 local_inc(&cpu_buffer->commit_overrun);
3998 goto out_reset;
3999 }
4000 }
4001 }
4002
4003 rb_tail_page_update(cpu_buffer, tail_page, next_page);
4004
4005 out_again:
4006
4007 rb_reset_tail(cpu_buffer, tail, info);
4008
4009 /* Commit what we have for now. */
4010 rb_end_commit(cpu_buffer);
4011 /* rb_end_commit() decs committing */
4012 local_inc(&cpu_buffer->committing);
4013
4014 /* fail and let the caller try again */
4015 return ERR_PTR(-EAGAIN);
4016
4017 out_reset:
4018 /* reset write */
4019 rb_reset_tail(cpu_buffer, tail, info);
4020
4021 return NULL;
4022 }
4023
4024 /* Slow path */
4025 static struct ring_buffer_event *
4026 rb_add_time_stamp(struct ring_buffer_per_cpu *cpu_buffer,
4027 struct ring_buffer_event *event, u64 delta, bool abs)
4028 {
4029 if (abs)
4030 event->type_len = RINGBUF_TYPE_TIME_STAMP;
4031 else
4032 event->type_len = RINGBUF_TYPE_TIME_EXTEND;
4033
4034 /* Not the first event on the page, or not delta? */
4035 if (abs || rb_event_index(cpu_buffer, event)) {
4036 event->time_delta = delta & TS_MASK;
4037 event->array[0] = delta >> TS_SHIFT;
4038 } else {
4039 /* nope, just zero it */
4040 event->time_delta = 0;
4041 event->array[0] = 0;
4042 }
4043
4044 return skip_time_extend(event);
4045 }
4046
4047 static void
4048 rb_check_timestamp(struct ring_buffer_per_cpu *cpu_buffer,
4049 struct rb_event_info *info)
4050 {
4051 u64 write_stamp;
4052
4053 WARN_ONCE(1, "Delta way too big! %llu ts=%llu before=%llu after=%llu write stamp=%llu\n%s",
4054 (unsigned long long)info->delta,
4055 (unsigned long long)info->ts,
4056 (unsigned long long)info->before,
4057 (unsigned long long)info->after,
4058 (unsigned long long)({rb_time_read(&cpu_buffer->write_stamp, &write_stamp); write_stamp;}),
4059 sched_clock_stable() ? "" :
4060 "If you just came from a suspend/resume,\n"
4061 "please switch to the trace global clock:\n"
4062 " echo global > /sys/kernel/tracing/trace_clock\n"
4063 "or add trace_clock=global to the kernel command line\n");
4064 }
4065
4066 static void rb_add_timestamp(struct ring_buffer_per_cpu *cpu_buffer,
4067 struct ring_buffer_event **event,
4068 struct rb_event_info *info,
4069 u64 *delta,
4070 unsigned int *length)
4071 {
4072 bool abs = info->add_timestamp &
4073 (RB_ADD_STAMP_FORCE | RB_ADD_STAMP_ABSOLUTE);
4074
4075 if (unlikely(info->delta > (1ULL << 59))) {
4076 /*
4077 * Some timers can use more than 59 bits, and when a timestamp
4078 * is added to the buffer, it will lose those bits.
4079 */
4080 if (abs && (info->ts & TS_MSB)) {
4081 info->delta &= ABS_TS_MASK;
4082
4083 /* did the clock go backwards */
4084 } else if (info->before == info->after && info->before > info->ts) {
4085 /* not interrupted */
4086 static int once;
4087
4088 /*
4089 * This is possible with a recalibrating of the TSC.
4090 * Do not produce a call stack, but just report it.
4091 */
4092 if (!once) {
4093 once++;
4094 pr_warn("Ring buffer clock went backwards: %llu -> %llu\n",
4095 info->before, info->ts);
4096 }
4097 } else
4098 rb_check_timestamp(cpu_buffer, info);
4099 if (!abs)
4100 info->delta = 0;
4101 }
4102 *event = rb_add_time_stamp(cpu_buffer, *event, info->delta, abs);
4103 *length -= RB_LEN_TIME_EXTEND;
4104 *delta = 0;
4105 }
4106
4107 /**
4108 * rb_update_event - update event type and data
4109 * @cpu_buffer: The per cpu buffer of the @event
4110 * @event: the event to update
4111 * @info: The info to update the @event with (contains length and delta)
4112 *
4113 * Update the type and data fields of the @event. The length
4114 * is the actual size that is written to the ring buffer,
4115 * and with this, we can determine what to place into the
4116 * data field.
4117 */
4118 static void
4119 rb_update_event(struct ring_buffer_per_cpu *cpu_buffer,
4120 struct ring_buffer_event *event,
4121 struct rb_event_info *info)
4122 {
4123 unsigned length = info->length;
4124 u64 delta = info->delta;
4125 unsigned int nest = local_read(&cpu_buffer->committing) - 1;
4126
4127 if (!WARN_ON_ONCE(nest >= MAX_NEST))
4128 cpu_buffer->event_stamp[nest] = info->ts;
4129
4130 /*
4131 * If we need to add a timestamp, then we
4132 * add it to the start of the reserved space.
4133 */
4134 if (unlikely(info->add_timestamp))
4135 rb_add_timestamp(cpu_buffer, &event, info, &delta, &length);
4136
4137 event->time_delta = delta;
4138 length -= RB_EVNT_HDR_SIZE;
4139 if (length > RB_MAX_SMALL_DATA || RB_FORCE_8BYTE_ALIGNMENT) {
4140 event->type_len = 0;
4141 event->array[0] = length;
4142 } else
4143 event->type_len = DIV_ROUND_UP(length, RB_ALIGNMENT);
4144 }
4145
4146 static unsigned rb_calculate_event_length(unsigned length)
4147 {
4148 struct ring_buffer_event event; /* Used only for sizeof array */
4149
4150 /* zero length can cause confusions */
4151 if (!length)
4152 length++;
4153
4154 if (length > RB_MAX_SMALL_DATA || RB_FORCE_8BYTE_ALIGNMENT)
4155 length += sizeof(event.array[0]);
4156
4157 length += RB_EVNT_HDR_SIZE;
4158 length = ALIGN(length, RB_ARCH_ALIGNMENT);
4159
4160 /*
4161 * In case the time delta is larger than the 27 bits for it
4162 * in the header, we need to add a timestamp. If another
4163 * event comes in when trying to discard this one to increase
4164 * the length, then the timestamp will be added in the allocated
4165 * space of this event. If length is bigger than the size needed
4166 * for the TIME_EXTEND, then padding has to be used. The events
4167 * length must be either RB_LEN_TIME_EXTEND, or greater than or equal
4168 * to RB_LEN_TIME_EXTEND + 8, as 8 is the minimum size for padding.
4169 * As length is a multiple of 4, we only need to worry if it
4170 * is 12 (RB_LEN_TIME_EXTEND + 4).
4171 */
4172 if (length == RB_LEN_TIME_EXTEND + RB_ALIGNMENT)
4173 length += RB_ALIGNMENT;
4174
4175 return length;
4176 }
4177
4178 static inline bool
4179 rb_try_to_discard(struct ring_buffer_per_cpu *cpu_buffer,
4180 struct ring_buffer_event *event)
4181 {
4182 unsigned long new_index, old_index;
4183 struct buffer_page *bpage;
4184 unsigned long addr;
4185
4186 new_index = rb_event_index(cpu_buffer, event);
4187 old_index = new_index + rb_event_ts_length(event);
4188 addr = rb_subbuf_start(cpu_buffer->buffer, (unsigned long)event);
4189
4190 bpage = READ_ONCE(cpu_buffer->tail_page);
4191
4192 /*
4193 * Make sure the tail_page is still the same and
4194 * the next write location is the end of this event
4195 */
4196 if (bpage->page == (void *)addr && rb_page_write(bpage) == old_index) {
4197 unsigned long write_mask =
4198 local_read(&bpage->write) & ~RB_WRITE_MASK;
4199 unsigned long event_length = rb_event_length(event);
4200
4201 /*
4202 * For the before_stamp to be different than the write_stamp
4203 * to make sure that the next event adds an absolute
4204 * value and does not rely on the saved write stamp, which
4205 * is now going to be bogus.
4206 *
4207 * By setting the before_stamp to zero, the next event
4208 * is not going to use the write_stamp and will instead
4209 * create an absolute timestamp. This means there's no
4210 * reason to update the wirte_stamp!
4211 */
4212 rb_time_set(&cpu_buffer->before_stamp, 0);
4213
4214 /*
4215 * If an event were to come in now, it would see that the
4216 * write_stamp and the before_stamp are different, and assume
4217 * that this event just added itself before updating
4218 * the write stamp. The interrupting event will fix the
4219 * write stamp for us, and use an absolute timestamp.
4220 */
4221
4222 /*
4223 * This is on the tail page. It is possible that
4224 * a write could come in and move the tail page
4225 * and write to the next page. That is fine
4226 * because we just shorten what is on this page.
4227 */
4228 old_index += write_mask;
4229 new_index += write_mask;
4230
4231 /* caution: old_index gets updated on cmpxchg failure */
4232 if (local_try_cmpxchg(&bpage->write, &old_index, new_index)) {
4233 /* update counters */
4234 local_sub(event_length, &cpu_buffer->entries_bytes);
4235 return true;
4236 }
4237 }
4238
4239 /* could not discard */
4240 return false;
4241 }
4242
4243 static void rb_start_commit(struct ring_buffer_per_cpu *cpu_buffer)
4244 {
4245 local_inc(&cpu_buffer->committing);
4246 local_inc(&cpu_buffer->commits);
4247 }
4248
4249 static __always_inline void
4250 rb_set_commit_to_write(struct ring_buffer_per_cpu *cpu_buffer)
4251 {
4252 unsigned long max_count;
4253
4254 /*
4255 * We only race with interrupts and NMIs on this CPU.
4256 * If we own the commit event, then we can commit
4257 * all others that interrupted us, since the interruptions
4258 * are in stack format (they finish before they come
4259 * back to us). This allows us to do a simple loop to
4260 * assign the commit to the tail.
4261 */
4262 again:
4263 max_count = cpu_buffer->nr_pages * 100;
4264
4265 while (cpu_buffer->commit_page != READ_ONCE(cpu_buffer->tail_page)) {
4266 if (RB_WARN_ON(cpu_buffer, !(--max_count)))
4267 return;
4268 if (RB_WARN_ON(cpu_buffer,
4269 rb_is_reader_page(cpu_buffer->tail_page)))
4270 return;
4271 /*
4272 * No need for a memory barrier here, as the update
4273 * of the tail_page did it for this page.
4274 */
4275 local_set(&cpu_buffer->commit_page->page->commit,
4276 rb_page_write(cpu_buffer->commit_page));
4277 rb_inc_page(&cpu_buffer->commit_page);
4278 if (cpu_buffer->ring_meta) {
4279 struct ring_buffer_cpu_meta *meta = cpu_buffer->ring_meta;
4280 meta->commit_buffer = (unsigned long)cpu_buffer->commit_page->page;
4281 }
4282 /* add barrier to keep gcc from optimizing too much */
4283 barrier();
4284 }
4285 while (rb_commit_index(cpu_buffer) !=
4286 rb_page_write(cpu_buffer->commit_page)) {
4287
4288 /* Make sure the readers see the content of what is committed. */
4289 smp_wmb();
4290 local_set(&cpu_buffer->commit_page->page->commit,
4291 rb_page_write(cpu_buffer->commit_page));
4292 RB_WARN_ON(cpu_buffer,
4293 rb_page_commit(cpu_buffer->commit_page) & ~RB_WRITE_MASK);
4294 barrier();
4295 }
4296
4297 /* again, keep gcc from optimizing */
4298 barrier();
4299
4300 /*
4301 * If an interrupt came in just after the first while loop
4302 * and pushed the tail page forward, we will be left with
4303 * a dangling commit that will never go forward.
4304 */
4305 if (unlikely(cpu_buffer->commit_page != READ_ONCE(cpu_buffer->tail_page)))
4306 goto again;
4307 }
4308
4309 static __always_inline void rb_end_commit(struct ring_buffer_per_cpu *cpu_buffer)
4310 {
4311 unsigned long commits;
4312
4313 if (RB_WARN_ON(cpu_buffer,
4314 !local_read(&cpu_buffer->committing)))
4315 return;
4316
4317 again:
4318 commits = local_read(&cpu_buffer->commits);
4319 /* synchronize with interrupts */
4320 barrier();
4321 if (local_read(&cpu_buffer->committing) == 1)
4322 rb_set_commit_to_write(cpu_buffer);
4323
4324 local_dec(&cpu_buffer->committing);
4325
4326 /* synchronize with interrupts */
4327 barrier();
4328
4329 /*
4330 * Need to account for interrupts coming in between the
4331 * updating of the commit page and the clearing of the
4332 * committing counter.
4333 */
4334 if (unlikely(local_read(&cpu_buffer->commits) != commits) &&
4335 !local_read(&cpu_buffer->committing)) {
4336 local_inc(&cpu_buffer->committing);
4337 goto again;
4338 }
4339 }
4340
4341 static inline void rb_event_discard(struct ring_buffer_event *event)
4342 {
4343 if (extended_time(event))
4344 event = skip_time_extend(event);
4345
4346 /* array[0] holds the actual length for the discarded event */
4347 event->array[0] = rb_event_data_length(event) - RB_EVNT_HDR_SIZE;
4348 event->type_len = RINGBUF_TYPE_PADDING;
4349 /* time delta must be non zero */
4350 if (!event->time_delta)
4351 event->time_delta = 1;
4352 }
4353
4354 static void rb_commit(struct ring_buffer_per_cpu *cpu_buffer)
4355 {
4356 local_inc(&cpu_buffer->entries);
4357 rb_end_commit(cpu_buffer);
4358 }
4359
4360 static bool
4361 rb_irq_work_queue(struct rb_irq_work *irq_work)
4362 {
4363 int cpu;
4364
4365 /* irq_work_queue_on() is not NMI-safe */
4366 if (unlikely(in_nmi()))
4367 return irq_work_queue(&irq_work->work);
4368
4369 /*
4370 * If CPU isolation is not active, cpu is always the current
4371 * CPU, and the following is equivallent to irq_work_queue().
4372 */
4373 cpu = housekeeping_any_cpu(HK_TYPE_KERNEL_NOISE);
4374 return irq_work_queue_on(&irq_work->work, cpu);
4375 }
4376
4377 static __always_inline void
4378 rb_wakeups(struct trace_buffer *buffer, struct ring_buffer_per_cpu *cpu_buffer)
4379 {
4380 if (buffer->irq_work.waiters_pending) {
4381 buffer->irq_work.waiters_pending = false;
4382 /* irq_work_queue() supplies it's own memory barriers */
4383 rb_irq_work_queue(&buffer->irq_work);
4384 }
4385
4386 if (cpu_buffer->irq_work.waiters_pending) {
4387 cpu_buffer->irq_work.waiters_pending = false;
4388 /* irq_work_queue() supplies it's own memory barriers */
4389 rb_irq_work_queue(&cpu_buffer->irq_work);
4390 }
4391
4392 if (cpu_buffer->last_pages_touch == local_read(&cpu_buffer->pages_touched))
4393 return;
4394
4395 if (cpu_buffer->reader_page == cpu_buffer->commit_page)
4396 return;
4397
4398 if (!cpu_buffer->irq_work.full_waiters_pending)
4399 return;
4400
4401 cpu_buffer->last_pages_touch = local_read(&cpu_buffer->pages_touched);
4402
4403 if (!full_hit(buffer, cpu_buffer->cpu, cpu_buffer->shortest_full))
4404 return;
4405
4406 cpu_buffer->irq_work.wakeup_full = true;
4407 cpu_buffer->irq_work.full_waiters_pending = false;
4408 /* irq_work_queue() supplies it's own memory barriers */
4409 rb_irq_work_queue(&cpu_buffer->irq_work);
4410 }
4411
4412 #ifdef CONFIG_RING_BUFFER_RECORD_RECURSION
4413 # define do_ring_buffer_record_recursion() \
4414 do_ftrace_record_recursion(_THIS_IP_, _RET_IP_)
4415 #else
4416 # define do_ring_buffer_record_recursion() do { } while (0)
4417 #endif
4418
4419 /*
4420 * The lock and unlock are done within a preempt disable section.
4421 * The current_context per_cpu variable can only be modified
4422 * by the current task between lock and unlock. But it can
4423 * be modified more than once via an interrupt. To pass this
4424 * information from the lock to the unlock without having to
4425 * access the 'in_interrupt()' functions again (which do show
4426 * a bit of overhead in something as critical as function tracing,
4427 * we use a bitmask trick.
4428 *
4429 * bit 1 = NMI context
4430 * bit 2 = IRQ context
4431 * bit 3 = SoftIRQ context
4432 * bit 4 = normal context.
4433 *
4434 * This works because this is the order of contexts that can
4435 * preempt other contexts. A SoftIRQ never preempts an IRQ
4436 * context.
4437 *
4438 * When the context is determined, the corresponding bit is
4439 * checked and set (if it was set, then a recursion of that context
4440 * happened).
4441 *
4442 * On unlock, we need to clear this bit. To do so, just subtract
4443 * 1 from the current_context and AND it to itself.
4444 *
4445 * (binary)
4446 * 101 - 1 = 100
4447 * 101 & 100 = 100 (clearing bit zero)
4448 *
4449 * 1010 - 1 = 1001
4450 * 1010 & 1001 = 1000 (clearing bit 1)
4451 *
4452 * The least significant bit can be cleared this way, and it
4453 * just so happens that it is the same bit corresponding to
4454 * the current context.
4455 *
4456 * Now the TRANSITION bit breaks the above slightly. The TRANSITION bit
4457 * is set when a recursion is detected at the current context, and if
4458 * the TRANSITION bit is already set, it will fail the recursion.
4459 * This is needed because there's a lag between the changing of
4460 * interrupt context and updating the preempt count. In this case,
4461 * a false positive will be found. To handle this, one extra recursion
4462 * is allowed, and this is done by the TRANSITION bit. If the TRANSITION
4463 * bit is already set, then it is considered a recursion and the function
4464 * ends. Otherwise, the TRANSITION bit is set, and that bit is returned.
4465 *
4466 * On the trace_recursive_unlock(), the TRANSITION bit will be the first
4467 * to be cleared. Even if it wasn't the context that set it. That is,
4468 * if an interrupt comes in while NORMAL bit is set and the ring buffer
4469 * is called before preempt_count() is updated, since the check will
4470 * be on the NORMAL bit, the TRANSITION bit will then be set. If an
4471 * NMI then comes in, it will set the NMI bit, but when the NMI code
4472 * does the trace_recursive_unlock() it will clear the TRANSITION bit
4473 * and leave the NMI bit set. But this is fine, because the interrupt
4474 * code that set the TRANSITION bit will then clear the NMI bit when it
4475 * calls trace_recursive_unlock(). If another NMI comes in, it will
4476 * set the TRANSITION bit and continue.
4477 *
4478 * Note: The TRANSITION bit only handles a single transition between context.
4479 */
4480
4481 static __always_inline bool
4482 trace_recursive_lock(struct ring_buffer_per_cpu *cpu_buffer)
4483 {
4484 unsigned int val = cpu_buffer->current_context;
4485 int bit = interrupt_context_level();
4486
4487 bit = RB_CTX_NORMAL - bit;
4488
4489 if (unlikely(val & (1 << (bit + cpu_buffer->nest)))) {
4490 /*
4491 * It is possible that this was called by transitioning
4492 * between interrupt context, and preempt_count() has not
4493 * been updated yet. In this case, use the TRANSITION bit.
4494 */
4495 bit = RB_CTX_TRANSITION;
4496 if (val & (1 << (bit + cpu_buffer->nest))) {
4497 do_ring_buffer_record_recursion();
4498 return true;
4499 }
4500 }
4501
4502 val |= (1 << (bit + cpu_buffer->nest));
4503 cpu_buffer->current_context = val;
4504
4505 return false;
4506 }
4507
4508 static __always_inline void
4509 trace_recursive_unlock(struct ring_buffer_per_cpu *cpu_buffer)
4510 {
4511 cpu_buffer->current_context &=
4512 cpu_buffer->current_context - (1 << cpu_buffer->nest);
4513 }
4514
4515 /* The recursive locking above uses 5 bits */
4516 #define NESTED_BITS 5
4517
4518 /**
4519 * ring_buffer_nest_start - Allow to trace while nested
4520 * @buffer: The ring buffer to modify
4521 *
4522 * The ring buffer has a safety mechanism to prevent recursion.
4523 * But there may be a case where a trace needs to be done while
4524 * tracing something else. In this case, calling this function
4525 * will allow this function to nest within a currently active
4526 * ring_buffer_lock_reserve().
4527 *
4528 * Call this function before calling another ring_buffer_lock_reserve() and
4529 * call ring_buffer_nest_end() after the nested ring_buffer_unlock_commit().
4530 */
4531 void ring_buffer_nest_start(struct trace_buffer *buffer)
4532 {
4533 struct ring_buffer_per_cpu *cpu_buffer;
4534 int cpu;
4535
4536 /* Enabled by ring_buffer_nest_end() */
4537 preempt_disable_notrace();
4538 cpu = raw_smp_processor_id();
4539 cpu_buffer = buffer->buffers[cpu];
4540 /* This is the shift value for the above recursive locking */
4541 cpu_buffer->nest += NESTED_BITS;
4542 }
4543
4544 /**
4545 * ring_buffer_nest_end - Allow to trace while nested
4546 * @buffer: The ring buffer to modify
4547 *
4548 * Must be called after ring_buffer_nest_start() and after the
4549 * ring_buffer_unlock_commit().
4550 */
4551 void ring_buffer_nest_end(struct trace_buffer *buffer)
4552 {
4553 struct ring_buffer_per_cpu *cpu_buffer;
4554 int cpu;
4555
4556 /* disabled by ring_buffer_nest_start() */
4557 cpu = raw_smp_processor_id();
4558 cpu_buffer = buffer->buffers[cpu];
4559 /* This is the shift value for the above recursive locking */
4560 cpu_buffer->nest -= NESTED_BITS;
4561 preempt_enable_notrace();
4562 }
4563
4564 /**
4565 * ring_buffer_unlock_commit - commit a reserved
4566 * @buffer: The buffer to commit to
4567 *
4568 * This commits the data to the ring buffer, and releases any locks held.
4569 *
4570 * Must be paired with ring_buffer_lock_reserve.
4571 */
4572 int ring_buffer_unlock_commit(struct trace_buffer *buffer)
4573 {
4574 struct ring_buffer_per_cpu *cpu_buffer;
4575 int cpu = raw_smp_processor_id();
4576
4577 cpu_buffer = buffer->buffers[cpu];
4578
4579 rb_commit(cpu_buffer);
4580
4581 rb_wakeups(buffer, cpu_buffer);
4582
4583 trace_recursive_unlock(cpu_buffer);
4584
4585 preempt_enable_notrace();
4586
4587 return 0;
4588 }
4589 EXPORT_SYMBOL_GPL(ring_buffer_unlock_commit);
4590
4591 /* Special value to validate all deltas on a page. */
4592 #define CHECK_FULL_PAGE 1L
4593
4594 #ifdef CONFIG_RING_BUFFER_VALIDATE_TIME_DELTAS
4595
4596 static const char *show_irq_str(int bits)
4597 {
4598 static const char * type[] = {
4599 ".", // 0
4600 "s", // 1
4601 "h", // 2
4602 "Hs", // 3
4603 "n", // 4
4604 "Ns", // 5
4605 "Nh", // 6
4606 "NHs", // 7
4607 };
4608
4609 return type[bits];
4610 }
4611
4612 /* Assume this is a trace event */
4613 static const char *show_flags(struct ring_buffer_event *event)
4614 {
4615 struct trace_entry *entry;
4616 int bits = 0;
4617
4618 if (rb_event_data_length(event) - RB_EVNT_HDR_SIZE < sizeof(*entry))
4619 return "X";
4620
4621 entry = ring_buffer_event_data(event);
4622
4623 if (entry->flags & TRACE_FLAG_SOFTIRQ)
4624 bits |= 1;
4625
4626 if (entry->flags & TRACE_FLAG_HARDIRQ)
4627 bits |= 2;
4628
4629 if (entry->flags & TRACE_FLAG_NMI)
4630 bits |= 4;
4631
4632 return show_irq_str(bits);
4633 }
4634
4635 static const char *show_irq(struct ring_buffer_event *event)
4636 {
4637 struct trace_entry *entry;
4638
4639 if (rb_event_data_length(event) - RB_EVNT_HDR_SIZE < sizeof(*entry))
4640 return "";
4641
4642 entry = ring_buffer_event_data(event);
4643 if (entry->flags & TRACE_FLAG_IRQS_OFF)
4644 return "d";
4645 return "";
4646 }
4647
4648 static const char *show_interrupt_level(void)
4649 {
4650 unsigned long pc = preempt_count();
4651 unsigned char level = 0;
4652
4653 if (pc & SOFTIRQ_OFFSET)
4654 level |= 1;
4655
4656 if (pc & HARDIRQ_MASK)
4657 level |= 2;
4658
4659 if (pc & NMI_MASK)
4660 level |= 4;
4661
4662 return show_irq_str(level);
4663 }
4664
4665 static void dump_buffer_page(struct buffer_data_page *dpage,
4666 struct rb_event_info *info,
4667 unsigned long tail)
4668 {
4669 struct ring_buffer_event *event;
4670 u64 ts, delta;
4671 int e;
4672
4673 ts = dpage->time_stamp;
4674 pr_warn(" [%lld] PAGE TIME STAMP\n", ts);
4675
4676 for (e = 0; e < tail; e += rb_event_length(event)) {
4677
4678 event = (struct ring_buffer_event *)(dpage->data + e);
4679
4680 switch (event->type_len) {
4681
4682 case RINGBUF_TYPE_TIME_EXTEND:
4683 delta = rb_event_time_stamp(event);
4684 ts += delta;
4685 pr_warn(" 0x%x: [%lld] delta:%lld TIME EXTEND\n",
4686 e, ts, delta);
4687 break;
4688
4689 case RINGBUF_TYPE_TIME_STAMP:
4690 delta = rb_event_time_stamp(event);
4691 ts = rb_fix_abs_ts(delta, ts);
4692 pr_warn(" 0x%x: [%lld] absolute:%lld TIME STAMP\n",
4693 e, ts, delta);
4694 break;
4695
4696 case RINGBUF_TYPE_PADDING:
4697 ts += event->time_delta;
4698 pr_warn(" 0x%x: [%lld] delta:%d PADDING\n",
4699 e, ts, event->time_delta);
4700 break;
4701
4702 case RINGBUF_TYPE_DATA:
4703 ts += event->time_delta;
4704 pr_warn(" 0x%x: [%lld] delta:%d %s%s\n",
4705 e, ts, event->time_delta,
4706 show_flags(event), show_irq(event));
4707 break;
4708
4709 default:
4710 break;
4711 }
4712 }
4713 pr_warn("expected end:0x%lx last event actually ended at:0x%x\n", tail, e);
4714 }
4715
4716 static DEFINE_PER_CPU(atomic_t, checking);
4717 static atomic_t ts_dump;
4718
4719 #define buffer_warn_return(fmt, ...) \
4720 do { \
4721 /* If another report is happening, ignore this one */ \
4722 if (atomic_inc_return(&ts_dump) != 1) { \
4723 atomic_dec(&ts_dump); \
4724 goto out; \
4725 } \
4726 atomic_inc(&cpu_buffer->record_disabled); \
4727 pr_warn(fmt, ##__VA_ARGS__); \
4728 dump_buffer_page(dpage, info, tail); \
4729 atomic_dec(&ts_dump); \
4730 /* There's some cases in boot up that this can happen */ \
4731 if (WARN_ON_ONCE(system_state != SYSTEM_BOOTING)) \
4732 /* Do not re-enable checking */ \
4733 return; \
4734 } while (0)
4735
4736 /*
4737 * Check if the current event time stamp matches the deltas on
4738 * the buffer page.
4739 */
4740 static void check_buffer(struct ring_buffer_per_cpu *cpu_buffer,
4741 struct rb_event_info *info,
4742 unsigned long tail)
4743 {
4744 struct buffer_data_page *dpage;
4745 u64 ts, delta;
4746 bool full = false;
4747 int ret;
4748
4749 dpage = info->tail_page->page;
4750
4751 if (tail == CHECK_FULL_PAGE) {
4752 full = true;
4753 tail = rb_data_page_commit(dpage);
4754 } else if (info->add_timestamp &
4755 (RB_ADD_STAMP_FORCE | RB_ADD_STAMP_ABSOLUTE)) {
4756 /* Ignore events with absolute time stamps */
4757 return;
4758 }
4759
4760 /*
4761 * Do not check the first event (skip possible extends too).
4762 * Also do not check if previous events have not been committed.
4763 */
4764 if (tail <= 8 || tail > rb_data_page_commit(dpage))
4765 return;
4766
4767 /*
4768 * If this interrupted another event,
4769 */
4770 if (atomic_inc_return(this_cpu_ptr(&checking)) != 1)
4771 goto out;
4772
4773 ret = rb_read_data_buffer(dpage, tail, cpu_buffer->cpu, &ts, &delta);
4774 if (ret < 0) {
4775 if (delta < ts) {
4776 buffer_warn_return("[CPU: %d]ABSOLUTE TIME WENT BACKWARDS: last ts: %lld absolute ts: %lld clock:%pS\n",
4777 cpu_buffer->cpu, ts, delta,
4778 cpu_buffer->buffer->clock);
4779 goto out;
4780 }
4781 }
4782 if ((full && ts > info->ts) ||
4783 (!full && ts + info->delta != info->ts)) {
4784 buffer_warn_return("[CPU: %d]TIME DOES NOT MATCH expected:%lld actual:%lld delta:%lld before:%lld after:%lld%s context:%s\ntrace clock:%pS",
4785 cpu_buffer->cpu,
4786 ts + info->delta, info->ts, info->delta,
4787 info->before, info->after,
4788 full ? " (full)" : "", show_interrupt_level(),
4789 cpu_buffer->buffer->clock);
4790 }
4791 out:
4792 atomic_dec(this_cpu_ptr(&checking));
4793 }
4794 #else
4795 static inline void check_buffer(struct ring_buffer_per_cpu *cpu_buffer,
4796 struct rb_event_info *info,
4797 unsigned long tail)
4798 {
4799 }
4800 #endif /* CONFIG_RING_BUFFER_VALIDATE_TIME_DELTAS */
4801
4802 static struct ring_buffer_event *
4803 __rb_reserve_next(struct ring_buffer_per_cpu *cpu_buffer,
4804 struct rb_event_info *info)
4805 {
4806 struct ring_buffer_event *event;
4807 struct buffer_page *tail_page;
4808 unsigned long tail, write, w;
4809
4810 /* Don't let the compiler play games with cpu_buffer->tail_page */
4811 tail_page = info->tail_page = READ_ONCE(cpu_buffer->tail_page);
4812
4813 /*A*/ w = local_read(&tail_page->write) & RB_WRITE_MASK;
4814 barrier();
4815 rb_time_read(&cpu_buffer->before_stamp, &info->before);
4816 rb_time_read(&cpu_buffer->write_stamp, &info->after);
4817 barrier();
4818 info->ts = rb_time_stamp(cpu_buffer->buffer);
4819
4820 if ((info->add_timestamp & RB_ADD_STAMP_ABSOLUTE)) {
4821 info->delta = info->ts;
4822 } else {
4823 /*
4824 * If interrupting an event time update, we may need an
4825 * absolute timestamp.
4826 * Don't bother if this is the start of a new page (w == 0).
4827 */
4828 if (!w) {
4829 /* Use the sub-buffer timestamp */
4830 info->delta = 0;
4831 } else if (unlikely(info->before != info->after)) {
4832 info->add_timestamp |= RB_ADD_STAMP_FORCE | RB_ADD_STAMP_EXTEND;
4833 info->length += RB_LEN_TIME_EXTEND;
4834 } else {
4835 info->delta = info->ts - info->after;
4836 if (unlikely(test_time_stamp(info->delta))) {
4837 info->add_timestamp |= RB_ADD_STAMP_EXTEND;
4838 info->length += RB_LEN_TIME_EXTEND;
4839 }
4840 }
4841 }
4842
4843 /*B*/ rb_time_set(&cpu_buffer->before_stamp, info->ts);
4844
4845 /*C*/ write = local_add_return(info->length, &tail_page->write);
4846
4847 /* set write to only the index of the write */
4848 write &= RB_WRITE_MASK;
4849
4850 tail = write - info->length;
4851
4852 /* See if we shot pass the end of this buffer page */
4853 if (unlikely(write > rb_page_capacity(tail_page))) {
4854 check_buffer(cpu_buffer, info, CHECK_FULL_PAGE);
4855 return rb_move_tail(cpu_buffer, tail, info);
4856 }
4857
4858 if (likely(tail == w)) {
4859 /* Nothing interrupted us between A and C */
4860 /*D*/ rb_time_set(&cpu_buffer->write_stamp, info->ts);
4861 /*
4862 * If something came in between C and D, the write stamp
4863 * may now not be in sync. But that's fine as the before_stamp
4864 * will be different and then next event will just be forced
4865 * to use an absolute timestamp.
4866 */
4867 if (likely(!(info->add_timestamp &
4868 (RB_ADD_STAMP_FORCE | RB_ADD_STAMP_ABSOLUTE))))
4869 /* This did not interrupt any time update */
4870 info->delta = info->ts - info->after;
4871 else
4872 /* Just use full timestamp for interrupting event */
4873 info->delta = info->ts;
4874 check_buffer(cpu_buffer, info, tail);
4875 } else {
4876 u64 ts;
4877 /* SLOW PATH - Interrupted between A and C */
4878
4879 /* Save the old before_stamp */
4880 rb_time_read(&cpu_buffer->before_stamp, &info->before);
4881
4882 /*
4883 * Read a new timestamp and update the before_stamp to make
4884 * the next event after this one force using an absolute
4885 * timestamp. This is in case an interrupt were to come in
4886 * between E and F.
4887 */
4888 ts = rb_time_stamp(cpu_buffer->buffer);
4889 rb_time_set(&cpu_buffer->before_stamp, ts);
4890
4891 barrier();
4892 /*E*/ rb_time_read(&cpu_buffer->write_stamp, &info->after);
4893 barrier();
4894 /*F*/ if (write == (local_read(&tail_page->write) & RB_WRITE_MASK) &&
4895 info->after == info->before && info->after < ts) {
4896 /*
4897 * Nothing came after this event between C and F, it is
4898 * safe to use info->after for the delta as it
4899 * matched info->before and is still valid.
4900 */
4901 info->delta = ts - info->after;
4902 } else {
4903 /*
4904 * Interrupted between C and F:
4905 * Lost the previous events time stamp. Just set the
4906 * delta to zero, and this will be the same time as
4907 * the event this event interrupted. And the events that
4908 * came after this will still be correct (as they would
4909 * have built their delta on the previous event.
4910 */
4911 info->delta = 0;
4912 }
4913 info->ts = ts;
4914 info->add_timestamp &= ~RB_ADD_STAMP_FORCE;
4915 }
4916
4917 /*
4918 * If this is the first commit on the page, then it has the same
4919 * timestamp as the page itself.
4920 */
4921 if (unlikely(!tail && !(info->add_timestamp &
4922 (RB_ADD_STAMP_FORCE | RB_ADD_STAMP_ABSOLUTE))))
4923 info->delta = 0;
4924
4925 /* We reserved something on the buffer */
4926
4927 event = __rb_page_index(tail_page, tail);
4928 rb_update_event(cpu_buffer, event, info);
4929
4930 local_inc(&tail_page->entries);
4931
4932 /*
4933 * If this is the first commit on the page, then update
4934 * its timestamp.
4935 */
4936 if (unlikely(!tail))
4937 tail_page->page->time_stamp = info->ts;
4938
4939 /* account for these added bytes */
4940 local_add(info->length, &cpu_buffer->entries_bytes);
4941
4942 return event;
4943 }
4944
4945 static __always_inline struct ring_buffer_event *
4946 rb_reserve_next_event(struct trace_buffer *buffer,
4947 struct ring_buffer_per_cpu *cpu_buffer,
4948 unsigned long length)
4949 {
4950 struct ring_buffer_event *event;
4951 struct rb_event_info info;
4952 int nr_loops = 0;
4953 int add_ts_default;
4954
4955 /*
4956 * ring buffer does cmpxchg as well as atomic64 operations
4957 * (which some archs use locking for atomic64), make sure this
4958 * is safe in NMI context
4959 */
4960 if ((!IS_ENABLED(CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG) ||
4961 IS_ENABLED(CONFIG_GENERIC_ATOMIC64)) &&
4962 (unlikely(in_nmi()))) {
4963 return NULL;
4964 }
4965
4966 rb_start_commit(cpu_buffer);
4967 /* The commit page can not change after this */
4968
4969 #ifdef CONFIG_RING_BUFFER_ALLOW_SWAP
4970 /*
4971 * Due to the ability to swap a cpu buffer from a buffer
4972 * it is possible it was swapped before we committed.
4973 * (committing stops a swap). We check for it here and
4974 * if it happened, we have to fail the write.
4975 */
4976 barrier();
4977 if (unlikely(READ_ONCE(cpu_buffer->buffer) != buffer)) {
4978 local_dec(&cpu_buffer->committing);
4979 local_dec(&cpu_buffer->commits);
4980 return NULL;
4981 }
4982 #endif
4983
4984 info.length = rb_calculate_event_length(length);
4985
4986 if (ring_buffer_time_stamp_abs(cpu_buffer->buffer)) {
4987 add_ts_default = RB_ADD_STAMP_ABSOLUTE;
4988 info.length += RB_LEN_TIME_EXTEND;
4989 if (info.length > rb_subbuf_max_data_size(cpu_buffer->buffer))
4990 goto out_fail;
4991 } else {
4992 add_ts_default = RB_ADD_STAMP_NONE;
4993 }
4994
4995 again:
4996 info.add_timestamp = add_ts_default;
4997 info.delta = 0;
4998
4999 /*
5000 * We allow for interrupts to reenter here and do a trace.
5001 * If one does, it will cause this original code to loop
5002 * back here. Even with heavy interrupts happening, this
5003 * should only happen a few times in a row. If this happens
5004 * 1000 times in a row, there must be either an interrupt
5005 * storm or we have something buggy.
5006 * Bail!
5007 */
5008 if (RB_WARN_ON(cpu_buffer, ++nr_loops > 1000))
5009 goto out_fail;
5010
5011 event = __rb_reserve_next(cpu_buffer, &info);
5012
5013 if (unlikely(PTR_ERR(event) == -EAGAIN)) {
5014 if (info.add_timestamp & (RB_ADD_STAMP_FORCE | RB_ADD_STAMP_EXTEND))
5015 info.length -= RB_LEN_TIME_EXTEND;
5016 goto again;
5017 }
5018
5019 if (likely(event))
5020 return event;
5021 out_fail:
5022 rb_end_commit(cpu_buffer);
5023 return NULL;
5024 }
5025
5026 /**
5027 * ring_buffer_lock_reserve - reserve a part of the buffer
5028 * @buffer: the ring buffer to reserve from
5029 * @length: the length of the data to reserve (excluding event header)
5030 *
5031 * Returns a reserved event on the ring buffer to copy directly to.
5032 * The user of this interface will need to get the body to write into
5033 * and can use the ring_buffer_event_data() interface.
5034 *
5035 * The length is the length of the data needed, not the event length
5036 * which also includes the event header.
5037 *
5038 * Must be paired with ring_buffer_unlock_commit, unless NULL is returned.
5039 * If NULL is returned, then nothing has been allocated or locked.
5040 */
5041 struct ring_buffer_event *
5042 ring_buffer_lock_reserve(struct trace_buffer *buffer, unsigned long length)
5043 {
5044 struct ring_buffer_per_cpu *cpu_buffer;
5045 struct ring_buffer_event *event;
5046 int cpu;
5047
5048 /* If we are tracing schedule, we don't want to recurse */
5049 preempt_disable_notrace();
5050
5051 if (unlikely(atomic_read(&buffer->record_disabled)))
5052 goto out;
5053
5054 cpu = raw_smp_processor_id();
5055
5056 if (unlikely(!cpumask_test_cpu(cpu, buffer->cpumask)))
5057 goto out;
5058
5059 cpu_buffer = buffer->buffers[cpu];
5060
5061 if (unlikely(atomic_read(&cpu_buffer->record_disabled)))
5062 goto out;
5063
5064 if (unlikely(length > rb_subbuf_max_data_size(buffer)))
5065 goto out;
5066
5067 if (unlikely(trace_recursive_lock(cpu_buffer)))
5068 goto out;
5069
5070 event = rb_reserve_next_event(buffer, cpu_buffer, length);
5071 if (!event)
5072 goto out_unlock;
5073
5074 return event;
5075
5076 out_unlock:
5077 trace_recursive_unlock(cpu_buffer);
5078 out:
5079 preempt_enable_notrace();
5080 return NULL;
5081 }
5082 EXPORT_SYMBOL_GPL(ring_buffer_lock_reserve);
5083
5084 /*
5085 * Decrement the entries to the page that an event is on.
5086 * The event does not even need to exist, only the pointer
5087 * to the page it is on. This may only be called before the commit
5088 * takes place.
5089 */
5090 static inline void
5091 rb_decrement_entry(struct ring_buffer_per_cpu *cpu_buffer,
5092 struct ring_buffer_event *event)
5093 {
5094 unsigned long addr = (unsigned long)event;
5095 struct buffer_page *bpage = cpu_buffer->commit_page;
5096 struct buffer_page *start;
5097
5098 addr = rb_subbuf_start(cpu_buffer->buffer, addr);
5099
5100 /* Do the likely case first */
5101 if (likely(bpage->page == (void *)addr)) {
5102 local_dec(&bpage->entries);
5103 return;
5104 }
5105
5106 /*
5107 * Because the commit page may be on the reader page we
5108 * start with the next page and check the end loop there.
5109 */
5110 rb_inc_page(&bpage);
5111 start = bpage;
5112 do {
5113 if (bpage->page == (void *)addr) {
5114 local_dec(&bpage->entries);
5115 return;
5116 }
5117 rb_inc_page(&bpage);
5118 } while (bpage != start);
5119
5120 /* commit not part of this buffer?? */
5121 RB_WARN_ON(cpu_buffer, 1);
5122 }
5123
5124 /**
5125 * ring_buffer_discard_commit - discard an event that has not been committed
5126 * @buffer: the ring buffer
5127 * @event: non committed event to discard
5128 *
5129 * Sometimes an event that is in the ring buffer needs to be ignored.
5130 * This function lets the user discard an event in the ring buffer
5131 * and then that event will not be read later.
5132 *
5133 * This function only works if it is called before the item has been
5134 * committed. It will try to free the event from the ring buffer
5135 * if another event has not been added behind it.
5136 *
5137 * If another event has been added behind it, it will set the event
5138 * up as discarded, and perform the commit.
5139 *
5140 * If this function is called, do not call ring_buffer_unlock_commit on
5141 * the event.
5142 */
5143 void ring_buffer_discard_commit(struct trace_buffer *buffer,
5144 struct ring_buffer_event *event)
5145 {
5146 struct ring_buffer_per_cpu *cpu_buffer;
5147 int cpu;
5148
5149 /* The event is discarded regardless */
5150 rb_event_discard(event);
5151
5152 cpu = smp_processor_id();
5153 cpu_buffer = buffer->buffers[cpu];
5154
5155 /*
5156 * This must only be called if the event has not been
5157 * committed yet. Thus we can assume that preemption
5158 * is still disabled.
5159 */
5160 RB_WARN_ON(buffer, !local_read(&cpu_buffer->committing));
5161
5162 rb_decrement_entry(cpu_buffer, event);
5163 rb_try_to_discard(cpu_buffer, event);
5164 rb_end_commit(cpu_buffer);
5165
5166 trace_recursive_unlock(cpu_buffer);
5167
5168 preempt_enable_notrace();
5169
5170 }
5171 EXPORT_SYMBOL_GPL(ring_buffer_discard_commit);
5172
5173 /**
5174 * ring_buffer_write - write data to the buffer without reserving
5175 * @buffer: The ring buffer to write to.
5176 * @length: The length of the data being written (excluding the event header)
5177 * @data: The data to write to the buffer.
5178 *
5179 * This is like ring_buffer_lock_reserve and ring_buffer_unlock_commit as
5180 * one function. If you already have the data to write to the buffer, it
5181 * may be easier to simply call this function.
5182 *
5183 * Note, like ring_buffer_lock_reserve, the length is the length of the data
5184 * and not the length of the event which would hold the header.
5185 */
5186 int ring_buffer_write(struct trace_buffer *buffer,
5187 unsigned long length,
5188 void *data)
5189 {
5190 struct ring_buffer_per_cpu *cpu_buffer;
5191 struct ring_buffer_event *event;
5192 void *body;
5193 int ret = -EBUSY;
5194 int cpu;
5195
5196 guard(preempt_notrace)();
5197
5198 if (atomic_read(&buffer->record_disabled))
5199 return -EBUSY;
5200
5201 cpu = raw_smp_processor_id();
5202
5203 if (!cpumask_test_cpu(cpu, buffer->cpumask))
5204 return -EBUSY;
5205
5206 cpu_buffer = buffer->buffers[cpu];
5207
5208 if (atomic_read(&cpu_buffer->record_disabled))
5209 return -EBUSY;
5210
5211 if (length > rb_subbuf_max_data_size(buffer))
5212 return -EBUSY;
5213
5214 if (unlikely(trace_recursive_lock(cpu_buffer)))
5215 return -EBUSY;
5216
5217 event = rb_reserve_next_event(buffer, cpu_buffer, length);
5218 if (!event)
5219 goto out_unlock;
5220
5221 body = rb_event_data(event);
5222
5223 memcpy(body, data, length);
5224
5225 rb_commit(cpu_buffer);
5226
5227 rb_wakeups(buffer, cpu_buffer);
5228
5229 ret = 0;
5230
5231 out_unlock:
5232 trace_recursive_unlock(cpu_buffer);
5233 return ret;
5234 }
5235 EXPORT_SYMBOL_GPL(ring_buffer_write);
5236
5237 /*
5238 * The total entries in the ring buffer is the running counter
5239 * of entries entered into the ring buffer, minus the sum of
5240 * the entries read from the ring buffer and the number of
5241 * entries that were overwritten.
5242 */
5243 static inline unsigned long
5244 rb_num_of_entries(struct ring_buffer_per_cpu *cpu_buffer)
5245 {
5246 return local_read(&cpu_buffer->entries) -
5247 (local_read(&cpu_buffer->overrun) + cpu_buffer->read);
5248 }
5249
5250 static bool rb_per_cpu_empty(struct ring_buffer_per_cpu *cpu_buffer)
5251 {
5252 return !rb_num_of_entries(cpu_buffer);
5253 }
5254
5255 /**
5256 * ring_buffer_record_disable - stop all writes into the buffer
5257 * @buffer: The ring buffer to stop writes to.
5258 *
5259 * This prevents all writes to the buffer. Any attempt to write
5260 * to the buffer after this will fail and return NULL.
5261 *
5262 * The caller should call synchronize_rcu() after this.
5263 */
5264 void ring_buffer_record_disable(struct trace_buffer *buffer)
5265 {
5266 atomic_inc(&buffer->record_disabled);
5267 }
5268 EXPORT_SYMBOL_GPL(ring_buffer_record_disable);
5269
5270 /**
5271 * ring_buffer_record_enable - enable writes to the buffer
5272 * @buffer: The ring buffer to enable writes
5273 *
5274 * Note, multiple disables will need the same number of enables
5275 * to truly enable the writing (much like preempt_disable).
5276 */
5277 void ring_buffer_record_enable(struct trace_buffer *buffer)
5278 {
5279 atomic_dec(&buffer->record_disabled);
5280 }
5281 EXPORT_SYMBOL_GPL(ring_buffer_record_enable);
5282
5283 /**
5284 * ring_buffer_record_off - stop all writes into the buffer
5285 * @buffer: The ring buffer to stop writes to.
5286 *
5287 * This prevents all writes to the buffer. Any attempt to write
5288 * to the buffer after this will fail and return NULL.
5289 *
5290 * This is different than ring_buffer_record_disable() as
5291 * it works like an on/off switch, where as the disable() version
5292 * must be paired with a enable().
5293 */
5294 void ring_buffer_record_off(struct trace_buffer *buffer)
5295 {
5296 unsigned int rd;
5297 unsigned int new_rd;
5298
5299 rd = atomic_read(&buffer->record_disabled);
5300 do {
5301 new_rd = rd | RB_BUFFER_OFF;
5302 } while (!atomic_try_cmpxchg(&buffer->record_disabled, &rd, new_rd));
5303 }
5304 EXPORT_SYMBOL_GPL(ring_buffer_record_off);
5305
5306 /**
5307 * ring_buffer_record_on - restart writes into the buffer
5308 * @buffer: The ring buffer to start writes to.
5309 *
5310 * This enables all writes to the buffer that was disabled by
5311 * ring_buffer_record_off().
5312 *
5313 * This is different than ring_buffer_record_enable() as
5314 * it works like an on/off switch, where as the enable() version
5315 * must be paired with a disable().
5316 */
5317 void ring_buffer_record_on(struct trace_buffer *buffer)
5318 {
5319 unsigned int rd;
5320 unsigned int new_rd;
5321
5322 rd = atomic_read(&buffer->record_disabled);
5323 do {
5324 new_rd = rd & ~RB_BUFFER_OFF;
5325 } while (!atomic_try_cmpxchg(&buffer->record_disabled, &rd, new_rd));
5326 }
5327 EXPORT_SYMBOL_GPL(ring_buffer_record_on);
5328
5329 /**
5330 * ring_buffer_record_is_on - return true if the ring buffer can write
5331 * @buffer: The ring buffer to see if write is enabled
5332 *
5333 * Returns true if the ring buffer is in a state that it accepts writes.
5334 */
5335 bool ring_buffer_record_is_on(struct trace_buffer *buffer)
5336 {
5337 return !atomic_read(&buffer->record_disabled);
5338 }
5339
5340 /**
5341 * ring_buffer_record_is_set_on - return true if the ring buffer is set writable
5342 * @buffer: The ring buffer to see if write is set enabled
5343 *
5344 * Returns true if the ring buffer is set writable by ring_buffer_record_on().
5345 * Note that this does NOT mean it is in a writable state.
5346 *
5347 * It may return true when the ring buffer has been disabled by
5348 * ring_buffer_record_disable(), as that is a temporary disabling of
5349 * the ring buffer.
5350 */
5351 bool ring_buffer_record_is_set_on(struct trace_buffer *buffer)
5352 {
5353 return !(atomic_read(&buffer->record_disabled) & RB_BUFFER_OFF);
5354 }
5355
5356 /**
5357 * ring_buffer_record_is_on_cpu - return true if the ring buffer can write
5358 * @buffer: The ring buffer to see if write is enabled
5359 * @cpu: The CPU to test if the ring buffer can write too
5360 *
5361 * Returns true if the ring buffer is in a state that it accepts writes
5362 * for a particular CPU.
5363 */
5364 bool ring_buffer_record_is_on_cpu(struct trace_buffer *buffer, int cpu)
5365 {
5366 struct ring_buffer_per_cpu *cpu_buffer;
5367
5368 cpu_buffer = buffer->buffers[cpu];
5369
5370 return ring_buffer_record_is_set_on(buffer) &&
5371 !atomic_read(&cpu_buffer->record_disabled);
5372 }
5373
5374 /**
5375 * ring_buffer_record_disable_cpu - stop all writes into the cpu_buffer
5376 * @buffer: The ring buffer to stop writes to.
5377 * @cpu: The CPU buffer to stop
5378 *
5379 * This prevents all writes to the buffer. Any attempt to write
5380 * to the buffer after this will fail and return NULL.
5381 *
5382 * The caller should call synchronize_rcu() after this.
5383 */
5384 void ring_buffer_record_disable_cpu(struct trace_buffer *buffer, int cpu)
5385 {
5386 struct ring_buffer_per_cpu *cpu_buffer;
5387
5388 if (!cpumask_test_cpu(cpu, buffer->cpumask))
5389 return;
5390
5391 cpu_buffer = buffer->buffers[cpu];
5392 atomic_inc(&cpu_buffer->record_disabled);
5393 }
5394 EXPORT_SYMBOL_GPL(ring_buffer_record_disable_cpu);
5395
5396 /**
5397 * ring_buffer_record_enable_cpu - enable writes to the buffer
5398 * @buffer: The ring buffer to enable writes
5399 * @cpu: The CPU to enable.
5400 *
5401 * Note, multiple disables will need the same number of enables
5402 * to truly enable the writing (much like preempt_disable).
5403 */
5404 void ring_buffer_record_enable_cpu(struct trace_buffer *buffer, int cpu)
5405 {
5406 struct ring_buffer_per_cpu *cpu_buffer;
5407
5408 if (!cpumask_test_cpu(cpu, buffer->cpumask))
5409 return;
5410
5411 cpu_buffer = buffer->buffers[cpu];
5412 atomic_dec(&cpu_buffer->record_disabled);
5413 }
5414 EXPORT_SYMBOL_GPL(ring_buffer_record_enable_cpu);
5415
5416 /**
5417 * ring_buffer_oldest_event_ts - get the oldest event timestamp from the buffer
5418 * @buffer: The ring buffer
5419 * @cpu: The per CPU buffer to read from.
5420 */
5421 u64 ring_buffer_oldest_event_ts(struct trace_buffer *buffer, int cpu)
5422 {
5423 unsigned long flags;
5424 struct ring_buffer_per_cpu *cpu_buffer;
5425 struct buffer_page *bpage;
5426 u64 ret = 0;
5427
5428 if (!cpumask_test_cpu(cpu, buffer->cpumask))
5429 return 0;
5430
5431 cpu_buffer = buffer->buffers[cpu];
5432 raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
5433 /*
5434 * if the tail is on reader_page, oldest time stamp is on the reader
5435 * page
5436 */
5437 if (cpu_buffer->tail_page == cpu_buffer->reader_page)
5438 bpage = cpu_buffer->reader_page;
5439 else
5440 bpage = rb_set_head_page(cpu_buffer);
5441 if (bpage)
5442 ret = bpage->page->time_stamp;
5443 raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
5444
5445 return ret;
5446 }
5447 EXPORT_SYMBOL_GPL(ring_buffer_oldest_event_ts);
5448
5449 /**
5450 * ring_buffer_bytes_cpu - get the number of bytes unconsumed in a cpu buffer
5451 * @buffer: The ring buffer
5452 * @cpu: The per CPU buffer to read from.
5453 */
5454 unsigned long ring_buffer_bytes_cpu(struct trace_buffer *buffer, int cpu)
5455 {
5456 struct ring_buffer_per_cpu *cpu_buffer;
5457 unsigned long ret;
5458
5459 if (!cpumask_test_cpu(cpu, buffer->cpumask))
5460 return 0;
5461
5462 cpu_buffer = buffer->buffers[cpu];
5463 ret = local_read(&cpu_buffer->entries_bytes) - cpu_buffer->read_bytes;
5464
5465 return ret;
5466 }
5467 EXPORT_SYMBOL_GPL(ring_buffer_bytes_cpu);
5468
5469 /**
5470 * ring_buffer_entries_cpu - get the number of entries in a cpu buffer
5471 * @buffer: The ring buffer
5472 * @cpu: The per CPU buffer to get the entries from.
5473 */
5474 unsigned long ring_buffer_entries_cpu(struct trace_buffer *buffer, int cpu)
5475 {
5476 struct ring_buffer_per_cpu *cpu_buffer;
5477
5478 if (!cpumask_test_cpu(cpu, buffer->cpumask))
5479 return 0;
5480
5481 cpu_buffer = buffer->buffers[cpu];
5482
5483 return rb_num_of_entries(cpu_buffer);
5484 }
5485 EXPORT_SYMBOL_GPL(ring_buffer_entries_cpu);
5486
5487 /**
5488 * ring_buffer_overrun_cpu - get the number of overruns caused by the ring
5489 * buffer wrapping around (only if RB_FL_OVERWRITE is on).
5490 * @buffer: The ring buffer
5491 * @cpu: The per CPU buffer to get the number of overruns from
5492 */
5493 unsigned long ring_buffer_overrun_cpu(struct trace_buffer *buffer, int cpu)
5494 {
5495 struct ring_buffer_per_cpu *cpu_buffer;
5496 unsigned long ret;
5497
5498 if (!cpumask_test_cpu(cpu, buffer->cpumask))
5499 return 0;
5500
5501 cpu_buffer = buffer->buffers[cpu];
5502 ret = local_read(&cpu_buffer->overrun);
5503
5504 return ret;
5505 }
5506 EXPORT_SYMBOL_GPL(ring_buffer_overrun_cpu);
5507
5508 /**
5509 * ring_buffer_commit_overrun_cpu - get the number of overruns caused by
5510 * commits failing due to the buffer wrapping around while there are uncommitted
5511 * events, such as during an interrupt storm.
5512 * @buffer: The ring buffer
5513 * @cpu: The per CPU buffer to get the number of overruns from
5514 */
5515 unsigned long
5516 ring_buffer_commit_overrun_cpu(struct trace_buffer *buffer, int cpu)
5517 {
5518 struct ring_buffer_per_cpu *cpu_buffer;
5519 unsigned long ret;
5520
5521 if (!cpumask_test_cpu(cpu, buffer->cpumask))
5522 return 0;
5523
5524 cpu_buffer = buffer->buffers[cpu];
5525 ret = local_read(&cpu_buffer->commit_overrun);
5526
5527 return ret;
5528 }
5529 EXPORT_SYMBOL_GPL(ring_buffer_commit_overrun_cpu);
5530
5531 /**
5532 * ring_buffer_dropped_events_cpu - get the number of dropped events caused by
5533 * the ring buffer filling up (only if RB_FL_OVERWRITE is off).
5534 * @buffer: The ring buffer
5535 * @cpu: The per CPU buffer to get the number of overruns from
5536 */
5537 unsigned long
5538 ring_buffer_dropped_events_cpu(struct trace_buffer *buffer, int cpu)
5539 {
5540 struct ring_buffer_per_cpu *cpu_buffer;
5541 unsigned long ret;
5542
5543 if (!cpumask_test_cpu(cpu, buffer->cpumask))
5544 return 0;
5545
5546 cpu_buffer = buffer->buffers[cpu];
5547 ret = local_read(&cpu_buffer->dropped_events);
5548
5549 return ret;
5550 }
5551 EXPORT_SYMBOL_GPL(ring_buffer_dropped_events_cpu);
5552
5553 /**
5554 * ring_buffer_read_events_cpu - get the number of events successfully read
5555 * @buffer: The ring buffer
5556 * @cpu: The per CPU buffer to get the number of events read
5557 */
5558 unsigned long
5559 ring_buffer_read_events_cpu(struct trace_buffer *buffer, int cpu)
5560 {
5561 struct ring_buffer_per_cpu *cpu_buffer;
5562
5563 if (!cpumask_test_cpu(cpu, buffer->cpumask))
5564 return 0;
5565
5566 cpu_buffer = buffer->buffers[cpu];
5567 return cpu_buffer->read;
5568 }
5569 EXPORT_SYMBOL_GPL(ring_buffer_read_events_cpu);
5570
5571 /**
5572 * ring_buffer_entries - get the number of entries in a buffer
5573 * @buffer: The ring buffer
5574 *
5575 * Returns the total number of entries in the ring buffer
5576 * (all CPU entries)
5577 */
5578 unsigned long ring_buffer_entries(struct trace_buffer *buffer)
5579 {
5580 struct ring_buffer_per_cpu *cpu_buffer;
5581 unsigned long entries = 0;
5582 int cpu;
5583
5584 /* if you care about this being correct, lock the buffer */
5585 for_each_buffer_cpu(buffer, cpu) {
5586 cpu_buffer = buffer->buffers[cpu];
5587 entries += rb_num_of_entries(cpu_buffer);
5588 }
5589
5590 return entries;
5591 }
5592 EXPORT_SYMBOL_GPL(ring_buffer_entries);
5593
5594 /**
5595 * ring_buffer_overruns - get the number of overruns in buffer
5596 * @buffer: The ring buffer
5597 *
5598 * Returns the total number of overruns in the ring buffer
5599 * (all CPU entries)
5600 */
5601 unsigned long ring_buffer_overruns(struct trace_buffer *buffer)
5602 {
5603 struct ring_buffer_per_cpu *cpu_buffer;
5604 unsigned long overruns = 0;
5605 int cpu;
5606
5607 /* if you care about this being correct, lock the buffer */
5608 for_each_buffer_cpu(buffer, cpu) {
5609 cpu_buffer = buffer->buffers[cpu];
5610 overruns += local_read(&cpu_buffer->overrun);
5611 }
5612
5613 return overruns;
5614 }
5615 EXPORT_SYMBOL_GPL(ring_buffer_overruns);
5616
5617 static bool rb_read_remote_meta_page(struct ring_buffer_per_cpu *cpu_buffer)
5618 {
5619 local_set(&cpu_buffer->entries, READ_ONCE(cpu_buffer->meta_page->entries));
5620 local_set(&cpu_buffer->overrun, READ_ONCE(cpu_buffer->meta_page->overrun));
5621 local_set(&cpu_buffer->pages_touched, READ_ONCE(cpu_buffer->meta_page->pages_touched));
5622 local_set(&cpu_buffer->pages_lost, READ_ONCE(cpu_buffer->meta_page->pages_lost));
5623
5624 return rb_num_of_entries(cpu_buffer);
5625 }
5626
5627 static void rb_update_remote_head(struct ring_buffer_per_cpu *cpu_buffer)
5628 {
5629 struct buffer_page *next, *orig;
5630 int retry = 3;
5631
5632 orig = next = cpu_buffer->head_page;
5633 rb_inc_page(&next);
5634
5635 /* Run after the writer */
5636 while (cpu_buffer->head_page->page->time_stamp > next->page->time_stamp) {
5637 rb_inc_page(&next);
5638
5639 rb_list_head_clear(cpu_buffer->head_page->list.prev);
5640 rb_inc_page(&cpu_buffer->head_page);
5641 rb_set_list_to_head(cpu_buffer->head_page->list.prev);
5642
5643 if (cpu_buffer->head_page == orig) {
5644 if (WARN_ON_ONCE(!(--retry)))
5645 return;
5646 }
5647 }
5648
5649 orig = cpu_buffer->commit_page = cpu_buffer->head_page;
5650 retry = 3;
5651
5652 while (cpu_buffer->commit_page->page->time_stamp < next->page->time_stamp) {
5653 rb_inc_page(&next);
5654 rb_inc_page(&cpu_buffer->commit_page);
5655
5656 if (cpu_buffer->commit_page == orig) {
5657 if (WARN_ON_ONCE(!(--retry)))
5658 return;
5659 }
5660 }
5661 }
5662
5663 static void rb_iter_reset(struct ring_buffer_iter *iter)
5664 {
5665 struct ring_buffer_per_cpu *cpu_buffer = iter->cpu_buffer;
5666
5667 if (cpu_buffer->remote) {
5668 rb_read_remote_meta_page(cpu_buffer);
5669 rb_update_remote_head(cpu_buffer);
5670 }
5671
5672 /* Iterator usage is expected to have record disabled */
5673 iter->head_page = cpu_buffer->reader_page;
5674 iter->head = cpu_buffer->reader_page->read;
5675 iter->next_event = iter->head;
5676 iter->missed_events = 0;
5677
5678 iter->cache_reader_page = iter->head_page;
5679 iter->cache_read = cpu_buffer->read;
5680 iter->cache_pages_removed = cpu_buffer->pages_removed;
5681
5682 if (iter->head) {
5683 iter->read_stamp = cpu_buffer->read_stamp;
5684 iter->page_stamp = cpu_buffer->reader_page->page->time_stamp;
5685 } else {
5686 iter->read_stamp = iter->head_page->page->time_stamp;
5687 iter->page_stamp = iter->read_stamp;
5688 }
5689 }
5690
5691 /**
5692 * ring_buffer_iter_reset - reset an iterator
5693 * @iter: The iterator to reset
5694 *
5695 * Resets the iterator, so that it will start from the beginning
5696 * again.
5697 */
5698 void ring_buffer_iter_reset(struct ring_buffer_iter *iter)
5699 {
5700 struct ring_buffer_per_cpu *cpu_buffer;
5701 unsigned long flags;
5702
5703 if (!iter)
5704 return;
5705
5706 cpu_buffer = iter->cpu_buffer;
5707
5708 raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
5709 rb_iter_reset(iter);
5710 raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
5711 }
5712 EXPORT_SYMBOL_GPL(ring_buffer_iter_reset);
5713
5714 /**
5715 * ring_buffer_iter_empty - check if an iterator has no more to read
5716 * @iter: The iterator to check
5717 */
5718 int ring_buffer_iter_empty(struct ring_buffer_iter *iter)
5719 {
5720 struct ring_buffer_per_cpu *cpu_buffer;
5721 struct buffer_page *reader;
5722 struct buffer_page *head_page;
5723 struct buffer_page *commit_page;
5724 struct buffer_page *curr_commit_page;
5725 unsigned commit;
5726 u64 curr_commit_ts;
5727 u64 commit_ts;
5728
5729 cpu_buffer = iter->cpu_buffer;
5730 reader = cpu_buffer->reader_page;
5731 head_page = cpu_buffer->head_page;
5732 commit_page = READ_ONCE(cpu_buffer->commit_page);
5733 commit_ts = commit_page->page->time_stamp;
5734
5735 /*
5736 * When the writer goes across pages, it issues a cmpxchg which
5737 * is a mb(), which will synchronize with the rmb here.
5738 * (see rb_tail_page_update())
5739 */
5740 smp_rmb();
5741 commit = rb_page_size(commit_page);
5742 /* We want to make sure that the commit page doesn't change */
5743 smp_rmb();
5744
5745 /* Make sure commit page didn't change */
5746 curr_commit_page = READ_ONCE(cpu_buffer->commit_page);
5747 curr_commit_ts = READ_ONCE(curr_commit_page->page->time_stamp);
5748
5749 /* If the commit page changed, then there's more data */
5750 if (curr_commit_page != commit_page ||
5751 curr_commit_ts != commit_ts)
5752 return 0;
5753
5754 /* Still racy, as it may return a false positive, but that's OK */
5755 return ((iter->head_page == commit_page && iter->head >= commit) ||
5756 (iter->head_page == reader && commit_page == head_page &&
5757 head_page->read == commit &&
5758 iter->head == rb_page_size(cpu_buffer->reader_page)));
5759 }
5760 EXPORT_SYMBOL_GPL(ring_buffer_iter_empty);
5761
5762 static void
5763 rb_update_read_stamp(struct ring_buffer_per_cpu *cpu_buffer,
5764 struct ring_buffer_event *event)
5765 {
5766 u64 delta;
5767
5768 switch (event->type_len) {
5769 case RINGBUF_TYPE_PADDING:
5770 return;
5771
5772 case RINGBUF_TYPE_TIME_EXTEND:
5773 delta = rb_event_time_stamp(event);
5774 cpu_buffer->read_stamp += delta;
5775 return;
5776
5777 case RINGBUF_TYPE_TIME_STAMP:
5778 delta = rb_event_time_stamp(event);
5779 delta = rb_fix_abs_ts(delta, cpu_buffer->read_stamp);
5780 cpu_buffer->read_stamp = delta;
5781 return;
5782
5783 case RINGBUF_TYPE_DATA:
5784 cpu_buffer->read_stamp += event->time_delta;
5785 return;
5786
5787 default:
5788 RB_WARN_ON(cpu_buffer, 1);
5789 }
5790 }
5791
5792 static void
5793 rb_update_iter_read_stamp(struct ring_buffer_iter *iter,
5794 struct ring_buffer_event *event)
5795 {
5796 u64 delta;
5797
5798 switch (event->type_len) {
5799 case RINGBUF_TYPE_PADDING:
5800 return;
5801
5802 case RINGBUF_TYPE_TIME_EXTEND:
5803 delta = rb_event_time_stamp(event);
5804 iter->read_stamp += delta;
5805 return;
5806
5807 case RINGBUF_TYPE_TIME_STAMP:
5808 delta = rb_event_time_stamp(event);
5809 delta = rb_fix_abs_ts(delta, iter->read_stamp);
5810 iter->read_stamp = delta;
5811 return;
5812
5813 case RINGBUF_TYPE_DATA:
5814 iter->read_stamp += event->time_delta;
5815 return;
5816
5817 default:
5818 RB_WARN_ON(iter->cpu_buffer, 1);
5819 }
5820 }
5821
5822 static struct buffer_page *
5823 __rb_get_reader_page_from_remote(struct ring_buffer_per_cpu *cpu_buffer)
5824 {
5825 struct buffer_page *new_reader, *prev_reader, *prev_head, *new_head, *last;
5826
5827 if (!rb_read_remote_meta_page(cpu_buffer))
5828 return NULL;
5829
5830 /* More to read on the reader page */
5831 if (cpu_buffer->reader_page->read < rb_page_size(cpu_buffer->reader_page)) {
5832 if (!cpu_buffer->reader_page->read)
5833 cpu_buffer->read_stamp = cpu_buffer->reader_page->page->time_stamp;
5834 return cpu_buffer->reader_page;
5835 }
5836
5837 prev_reader = cpu_buffer->subbuf_ids[cpu_buffer->meta_page->reader.id];
5838
5839 if (cpu_buffer->remote->swap_reader_page(cpu_buffer->cpu,
5840 cpu_buffer->remote->priv)) {
5841 pr_warn_ratelimited("Remote reader page swap failed\n");
5842 return NULL;
5843 }
5844 /* nr_pages doesn't include the reader page */
5845 if (WARN_ON_ONCE(cpu_buffer->meta_page->reader.id > cpu_buffer->nr_pages))
5846 return NULL;
5847
5848 new_reader = cpu_buffer->subbuf_ids[cpu_buffer->meta_page->reader.id];
5849
5850 WARN_ON_ONCE(prev_reader == new_reader);
5851
5852 prev_head = new_reader; /* New reader was also the previous head */
5853 new_head = prev_head;
5854 rb_inc_page(&new_head);
5855 last = prev_head;
5856 rb_dec_page(&last);
5857
5858 /* Clear the old HEAD flag */
5859 rb_list_head_clear(cpu_buffer->head_page->list.prev);
5860
5861 prev_reader->list.next = prev_head->list.next;
5862 prev_reader->list.prev = prev_head->list.prev;
5863
5864 /* Swap prev_reader with new_reader */
5865 last->list.next = &prev_reader->list;
5866 new_head->list.prev = &prev_reader->list;
5867
5868 new_reader->list.prev = &new_reader->list;
5869 new_reader->list.next = &new_head->list;
5870
5871 /* Reactivate the HEAD flag */
5872 rb_set_list_to_head(&last->list);
5873
5874 cpu_buffer->head_page = new_head;
5875 cpu_buffer->reader_page = new_reader;
5876 cpu_buffer->reader_page->read = 0;
5877 cpu_buffer->pages = &new_head->list;
5878 cpu_buffer->read_stamp = new_reader->page->time_stamp;
5879 cpu_buffer->lost_events = cpu_buffer->meta_page->reader.lost_events;
5880
5881 return rb_page_size(cpu_buffer->reader_page) ? cpu_buffer->reader_page : NULL;
5882 }
5883
5884 static struct buffer_page *
5885 __rb_get_reader_page(struct ring_buffer_per_cpu *cpu_buffer)
5886 {
5887 unsigned long max_loops = cpu_buffer->ring_meta ? cpu_buffer->nr_pages : 3;
5888 struct buffer_page *reader = NULL;
5889 unsigned long nr_loops = 0;
5890 unsigned long overwrite;
5891 unsigned long flags;
5892 int missed_events = 0;
5893 bool ret;
5894
5895 local_irq_save(flags);
5896 arch_spin_lock(&cpu_buffer->lock);
5897
5898 again:
5899 /*
5900 * This should normally only loop twice. But because the
5901 * start of the reader inserts an empty page, it causes a
5902 * case where we will loop three times. There should be no
5903 * reason to loop four times unless the ring buffer is a
5904 * recovered persistent ring buffer. For persistent ring buffers,
5905 * invalid pages are reset during recovery, so there may be more
5906 * than 3 contiguous pages can be empty, but less than nr_pages.
5907 */
5908 if (RB_WARN_ON(cpu_buffer, ++nr_loops > max_loops)) {
5909 reader = NULL;
5910 goto out;
5911 }
5912
5913 reader = cpu_buffer->reader_page;
5914
5915 /* If there's more to read, return this page */
5916 if (cpu_buffer->reader_page->read < rb_page_size(reader))
5917 goto out;
5918
5919 /* Never should we have an index greater than the size */
5920 if (RB_WARN_ON(cpu_buffer,
5921 cpu_buffer->reader_page->read > rb_page_size(reader)))
5922 goto out;
5923
5924 /* check if we caught up to the tail */
5925 reader = NULL;
5926 if (cpu_buffer->commit_page == cpu_buffer->reader_page)
5927 goto out;
5928
5929 /* Don't bother swapping if the ring buffer is empty */
5930 if (rb_num_of_entries(cpu_buffer) == 0)
5931 goto out;
5932
5933 /*
5934 * Reset the reader page to size zero.
5935 */
5936 local_set(&cpu_buffer->reader_page->write, 0);
5937 local_set(&cpu_buffer->reader_page->entries, 0);
5938 rb_init_data_page(cpu_buffer->reader_page->page);
5939 cpu_buffer->reader_page->real_end = 0;
5940
5941 spin:
5942 /*
5943 * Splice the empty reader page into the list around the head.
5944 */
5945 reader = rb_set_head_page(cpu_buffer);
5946 if (!reader)
5947 goto out;
5948 cpu_buffer->reader_page->list.next = rb_list_head(reader->list.next);
5949 cpu_buffer->reader_page->list.prev = reader->list.prev;
5950
5951 /*
5952 * cpu_buffer->pages just needs to point to the buffer, it
5953 * has no specific buffer page to point to. Lets move it out
5954 * of our way so we don't accidentally swap it.
5955 */
5956 cpu_buffer->pages = reader->list.prev;
5957
5958 /* The reader page will be pointing to the new head */
5959 rb_set_list_to_head(&cpu_buffer->reader_page->list);
5960
5961 /*
5962 * We want to make sure we read the overruns after we set up our
5963 * pointers to the next object. The writer side does a
5964 * cmpxchg to cross pages which acts as the mb on the writer
5965 * side. Note, the reader will constantly fail the swap
5966 * while the writer is updating the pointers, so this
5967 * guarantees that the overwrite recorded here is the one we
5968 * want to compare with the last_overrun.
5969 */
5970 smp_mb();
5971 overwrite = local_read(&(cpu_buffer->overrun));
5972
5973 /*
5974 * Here's the tricky part.
5975 *
5976 * We need to move the pointer past the header page.
5977 * But we can only do that if a writer is not currently
5978 * moving it. The page before the header page has the
5979 * flag bit '1' set if it is pointing to the page we want.
5980 * but if the writer is in the process of moving it
5981 * then it will be '2' or already moved '0'.
5982 */
5983
5984 ret = rb_head_page_replace(reader, cpu_buffer->reader_page);
5985
5986 /*
5987 * If we did not convert it, then we must try again.
5988 */
5989 if (!ret)
5990 goto spin;
5991
5992 if (rb_page_commit(reader) & RB_MISSED_EVENTS)
5993 missed_events = -1;
5994
5995 if (cpu_buffer->ring_meta)
5996 rb_update_meta_reader(cpu_buffer, reader);
5997
5998 /*
5999 * Yay! We succeeded in replacing the page.
6000 *
6001 * Now make the new head point back to the reader page.
6002 */
6003 rb_list_head(reader->list.next)->prev = &cpu_buffer->reader_page->list;
6004 rb_inc_page(&cpu_buffer->head_page);
6005
6006 cpu_buffer->cnt++;
6007 local_inc(&cpu_buffer->pages_read);
6008
6009 /* Finally update the reader page to the new head */
6010 cpu_buffer->reader_page = reader;
6011 cpu_buffer->reader_page->read = 0;
6012
6013 if (overwrite != cpu_buffer->last_overrun) {
6014 cpu_buffer->lost_events = overwrite - cpu_buffer->last_overrun;
6015 cpu_buffer->last_overrun = overwrite;
6016 }
6017
6018 goto again;
6019
6020 out:
6021 /* Update the read_stamp on the first event */
6022 if (reader && reader->read == 0)
6023 cpu_buffer->read_stamp = reader->page->time_stamp;
6024
6025 arch_spin_unlock(&cpu_buffer->lock);
6026 local_irq_restore(flags);
6027
6028 /*
6029 * The writer has preempt disable, wait for it. But not forever
6030 * Although, 1 second is pretty much "forever"
6031 */
6032 #define USECS_WAIT 1000000
6033 for (nr_loops = 0; nr_loops < USECS_WAIT; nr_loops++) {
6034 /* If the write is past the end of page, a writer is still updating it */
6035 if (likely(!reader || rb_page_write(reader) <= rb_page_capacity(reader)))
6036 break;
6037
6038 udelay(1);
6039
6040 /* Get the latest version of the reader write value */
6041 smp_rmb();
6042 }
6043
6044 /* The writer is not moving forward? Something is wrong */
6045 if (RB_WARN_ON(cpu_buffer, nr_loops == USECS_WAIT))
6046 reader = NULL;
6047
6048 /*
6049 * Make sure we see any padding after the write update
6050 * (see rb_reset_tail()).
6051 *
6052 * In addition, a writer may be writing on the reader page
6053 * if the page has not been fully filled, so the read barrier
6054 * is also needed to make sure we see the content of what is
6055 * committed by the writer (see rb_set_commit_to_write()).
6056 */
6057 smp_rmb();
6058
6059 if (!cpu_buffer->lost_events)
6060 cpu_buffer->lost_events = missed_events;
6061
6062 return reader;
6063 }
6064
6065 static struct buffer_page *
6066 rb_get_reader_page(struct ring_buffer_per_cpu *cpu_buffer)
6067 {
6068 return cpu_buffer->remote ? __rb_get_reader_page_from_remote(cpu_buffer) :
6069 __rb_get_reader_page(cpu_buffer);
6070 }
6071
6072 static void rb_advance_reader(struct ring_buffer_per_cpu *cpu_buffer)
6073 {
6074 struct ring_buffer_event *event;
6075 struct buffer_page *reader;
6076 unsigned length;
6077
6078 reader = rb_get_reader_page(cpu_buffer);
6079
6080 /* This function should not be called when buffer is empty */
6081 if (RB_WARN_ON(cpu_buffer, !reader))
6082 return;
6083
6084 event = rb_reader_event(cpu_buffer);
6085
6086 if (event->type_len <= RINGBUF_TYPE_DATA_TYPE_LEN_MAX)
6087 cpu_buffer->read++;
6088
6089 rb_update_read_stamp(cpu_buffer, event);
6090
6091 length = rb_event_length(event);
6092 cpu_buffer->reader_page->read += length;
6093 cpu_buffer->read_bytes += length;
6094 }
6095
6096 static void rb_advance_iter(struct ring_buffer_iter *iter)
6097 {
6098 struct ring_buffer_per_cpu *cpu_buffer;
6099
6100 cpu_buffer = iter->cpu_buffer;
6101
6102 /* If head == next_event then we need to jump to the next event */
6103 if (iter->head == iter->next_event) {
6104 /* If the event gets overwritten again, there's nothing to do */
6105 if (rb_iter_head_event(iter) == NULL)
6106 return;
6107 }
6108
6109 iter->head = iter->next_event;
6110
6111 /*
6112 * Check if we are at the end of the buffer.
6113 */
6114 if (iter->next_event >= rb_page_size(iter->head_page)) {
6115 /* discarded commits can make the page empty */
6116 if (iter->head_page == cpu_buffer->commit_page)
6117 return;
6118 rb_inc_iter(iter);
6119 return;
6120 }
6121
6122 rb_update_iter_read_stamp(iter, iter->event);
6123 }
6124
6125 static int rb_lost_events(struct ring_buffer_per_cpu *cpu_buffer)
6126 {
6127 return cpu_buffer->lost_events;
6128 }
6129
6130 static struct ring_buffer_event *
6131 rb_buffer_peek(struct ring_buffer_per_cpu *cpu_buffer, u64 *ts,
6132 unsigned long *lost_events)
6133 {
6134 struct ring_buffer_event *event;
6135 struct buffer_page *reader;
6136 int nr_loops = 0;
6137
6138 if (ts)
6139 *ts = 0;
6140 again:
6141 /*
6142 * We repeat when a time extend is encountered.
6143 * Since the time extend is always attached to a data event,
6144 * we should never loop more than once.
6145 * (We never hit the following condition more than twice).
6146 */
6147 if (RB_WARN_ON(cpu_buffer, ++nr_loops > 2))
6148 return NULL;
6149
6150 reader = rb_get_reader_page(cpu_buffer);
6151 if (!reader)
6152 return NULL;
6153
6154 event = rb_reader_event(cpu_buffer);
6155
6156 switch (event->type_len) {
6157 case RINGBUF_TYPE_PADDING:
6158 if (rb_null_event(event))
6159 RB_WARN_ON(cpu_buffer, 1);
6160 /*
6161 * Because the writer could be discarding every
6162 * event it creates (which would probably be bad)
6163 * if we were to go back to "again" then we may never
6164 * catch up, and will trigger the warn on, or lock
6165 * the box. Return the padding, and we will release
6166 * the current locks, and try again.
6167 */
6168 return event;
6169
6170 case RINGBUF_TYPE_TIME_EXTEND:
6171 /* Internal data, OK to advance */
6172 rb_advance_reader(cpu_buffer);
6173 goto again;
6174
6175 case RINGBUF_TYPE_TIME_STAMP:
6176 if (ts) {
6177 *ts = rb_event_time_stamp(event);
6178 *ts = rb_fix_abs_ts(*ts, reader->page->time_stamp);
6179 ring_buffer_normalize_time_stamp(cpu_buffer->buffer,
6180 cpu_buffer->cpu, ts);
6181 }
6182 /* Internal data, OK to advance */
6183 rb_advance_reader(cpu_buffer);
6184 goto again;
6185
6186 case RINGBUF_TYPE_DATA:
6187 if (ts && !(*ts)) {
6188 *ts = cpu_buffer->read_stamp + event->time_delta;
6189 ring_buffer_normalize_time_stamp(cpu_buffer->buffer,
6190 cpu_buffer->cpu, ts);
6191 }
6192 if (lost_events)
6193 *lost_events = rb_lost_events(cpu_buffer);
6194 return event;
6195
6196 default:
6197 RB_WARN_ON(cpu_buffer, 1);
6198 }
6199
6200 return NULL;
6201 }
6202 EXPORT_SYMBOL_GPL(ring_buffer_peek);
6203
6204 static struct ring_buffer_event *
6205 rb_iter_peek(struct ring_buffer_iter *iter, u64 *ts)
6206 {
6207 struct trace_buffer *buffer;
6208 struct ring_buffer_per_cpu *cpu_buffer;
6209 struct ring_buffer_event *event;
6210 unsigned long nr_loops = 0;
6211 unsigned long max_loops;
6212
6213 if (ts)
6214 *ts = 0;
6215
6216 cpu_buffer = iter->cpu_buffer;
6217 buffer = cpu_buffer->buffer;
6218 max_loops = cpu_buffer->ring_meta ? cpu_buffer->nr_pages : 3;
6219
6220 /*
6221 * Check if someone performed a consuming read to the buffer
6222 * or removed some pages from the buffer. In these cases,
6223 * iterator was invalidated and we need to reset it.
6224 */
6225 if (unlikely(iter->cache_read != cpu_buffer->read ||
6226 iter->cache_reader_page != cpu_buffer->reader_page ||
6227 iter->cache_pages_removed != cpu_buffer->pages_removed))
6228 rb_iter_reset(iter);
6229
6230 again:
6231 if (ring_buffer_iter_empty(iter))
6232 return NULL;
6233
6234 /*
6235 * As the writer can mess with what the iterator is trying
6236 * to read, just give up if we fail to get an event after
6237 * three tries. The iterator is not as reliable when reading
6238 * the ring buffer with an active write as the consumer is.
6239 * Do not warn if the three failures is reached.
6240 */
6241 if (++nr_loops > max_loops)
6242 return NULL;
6243
6244 if (rb_per_cpu_empty(cpu_buffer))
6245 return NULL;
6246
6247 if (iter->head >= rb_page_size(iter->head_page)) {
6248 rb_inc_iter(iter);
6249 goto again;
6250 }
6251
6252 event = rb_iter_head_event(iter);
6253 if (!event)
6254 goto again;
6255
6256 switch (event->type_len) {
6257 case RINGBUF_TYPE_PADDING:
6258 if (rb_null_event(event)) {
6259 rb_inc_iter(iter);
6260 goto again;
6261 }
6262 rb_advance_iter(iter);
6263 return event;
6264
6265 case RINGBUF_TYPE_TIME_EXTEND:
6266 /* Internal data, OK to advance */
6267 rb_advance_iter(iter);
6268 goto again;
6269
6270 case RINGBUF_TYPE_TIME_STAMP:
6271 if (ts) {
6272 *ts = rb_event_time_stamp(event);
6273 *ts = rb_fix_abs_ts(*ts, iter->head_page->page->time_stamp);
6274 ring_buffer_normalize_time_stamp(cpu_buffer->buffer,
6275 cpu_buffer->cpu, ts);
6276 }
6277 /* Internal data, OK to advance */
6278 rb_advance_iter(iter);
6279 goto again;
6280
6281 case RINGBUF_TYPE_DATA:
6282 if (ts && !(*ts)) {
6283 *ts = iter->read_stamp + event->time_delta;
6284 ring_buffer_normalize_time_stamp(buffer,
6285 cpu_buffer->cpu, ts);
6286 }
6287 return event;
6288
6289 default:
6290 RB_WARN_ON(cpu_buffer, 1);
6291 }
6292
6293 return NULL;
6294 }
6295 EXPORT_SYMBOL_GPL(ring_buffer_iter_peek);
6296
6297 static inline bool rb_reader_lock(struct ring_buffer_per_cpu *cpu_buffer)
6298 {
6299 if (likely(!in_nmi())) {
6300 raw_spin_lock(&cpu_buffer->reader_lock);
6301 return true;
6302 }
6303
6304 /*
6305 * If an NMI die dumps out the content of the ring buffer
6306 * trylock must be used to prevent a deadlock if the NMI
6307 * preempted a task that holds the ring buffer locks. If
6308 * we get the lock then all is fine, if not, then continue
6309 * to do the read, but this can corrupt the ring buffer,
6310 * so it must be permanently disabled from future writes.
6311 * Reading from NMI is a oneshot deal.
6312 */
6313 if (raw_spin_trylock(&cpu_buffer->reader_lock))
6314 return true;
6315
6316 /* Continue without locking, but disable the ring buffer */
6317 atomic_inc(&cpu_buffer->record_disabled);
6318 return false;
6319 }
6320
6321 static inline void
6322 rb_reader_unlock(struct ring_buffer_per_cpu *cpu_buffer, bool locked)
6323 {
6324 if (likely(locked))
6325 raw_spin_unlock(&cpu_buffer->reader_lock);
6326 }
6327
6328 /**
6329 * ring_buffer_peek - peek at the next event to be read
6330 * @buffer: The ring buffer to read
6331 * @cpu: The cpu to peak at
6332 * @ts: The timestamp counter of this event.
6333 * @lost_events: a variable to store if events were lost (may be NULL)
6334 *
6335 * This will return the event that will be read next, but does
6336 * not consume the data.
6337 */
6338 struct ring_buffer_event *
6339 ring_buffer_peek(struct trace_buffer *buffer, int cpu, u64 *ts,
6340 unsigned long *lost_events)
6341 {
6342 struct ring_buffer_per_cpu *cpu_buffer = buffer->buffers[cpu];
6343 struct ring_buffer_event *event;
6344 unsigned long flags;
6345 bool dolock;
6346
6347 if (!cpumask_test_cpu(cpu, buffer->cpumask))
6348 return NULL;
6349
6350 again:
6351 local_irq_save(flags);
6352 dolock = rb_reader_lock(cpu_buffer);
6353 event = rb_buffer_peek(cpu_buffer, ts, lost_events);
6354 if (event && event->type_len == RINGBUF_TYPE_PADDING)
6355 rb_advance_reader(cpu_buffer);
6356 rb_reader_unlock(cpu_buffer, dolock);
6357 local_irq_restore(flags);
6358
6359 if (event && event->type_len == RINGBUF_TYPE_PADDING)
6360 goto again;
6361
6362 return event;
6363 }
6364
6365 /** ring_buffer_iter_dropped - report if there are dropped events
6366 * @iter: The ring buffer iterator
6367 *
6368 * Returns true if there was dropped events since the last peek.
6369 */
6370 bool ring_buffer_iter_dropped(struct ring_buffer_iter *iter)
6371 {
6372 return iter->missed_events != 0;
6373 }
6374 EXPORT_SYMBOL_GPL(ring_buffer_iter_dropped);
6375
6376 /**
6377 * ring_buffer_iter_peek - peek at the next event to be read
6378 * @iter: The ring buffer iterator
6379 * @ts: The timestamp counter of this event.
6380 *
6381 * This will return the event that will be read next, but does
6382 * not increment the iterator.
6383 */
6384 struct ring_buffer_event *
6385 ring_buffer_iter_peek(struct ring_buffer_iter *iter, u64 *ts)
6386 {
6387 struct ring_buffer_per_cpu *cpu_buffer = iter->cpu_buffer;
6388 struct ring_buffer_event *event;
6389 unsigned long flags;
6390
6391 again:
6392 raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
6393 event = rb_iter_peek(iter, ts);
6394 raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
6395
6396 if (event && event->type_len == RINGBUF_TYPE_PADDING)
6397 goto again;
6398
6399 return event;
6400 }
6401
6402 /**
6403 * ring_buffer_consume - return an event and consume it
6404 * @buffer: The ring buffer to get the next event from
6405 * @cpu: the cpu to read the buffer from
6406 * @ts: a variable to store the timestamp (may be NULL)
6407 * @lost_events: a variable to store if events were lost (may be NULL)
6408 *
6409 * Returns the next event in the ring buffer, and that event is consumed.
6410 * Meaning, that sequential reads will keep returning a different event,
6411 * and eventually empty the ring buffer if the producer is slower.
6412 */
6413 struct ring_buffer_event *
6414 ring_buffer_consume(struct trace_buffer *buffer, int cpu, u64 *ts,
6415 unsigned long *lost_events)
6416 {
6417 struct ring_buffer_per_cpu *cpu_buffer;
6418 struct ring_buffer_event *event = NULL;
6419 unsigned long flags;
6420 bool dolock;
6421
6422 again:
6423 /* might be called in atomic */
6424 preempt_disable();
6425
6426 if (!cpumask_test_cpu(cpu, buffer->cpumask))
6427 goto out;
6428
6429 cpu_buffer = buffer->buffers[cpu];
6430 local_irq_save(flags);
6431 dolock = rb_reader_lock(cpu_buffer);
6432
6433 event = rb_buffer_peek(cpu_buffer, ts, lost_events);
6434 if (event) {
6435 cpu_buffer->lost_events = 0;
6436 rb_advance_reader(cpu_buffer);
6437 }
6438
6439 rb_reader_unlock(cpu_buffer, dolock);
6440 local_irq_restore(flags);
6441
6442 out:
6443 preempt_enable();
6444
6445 if (event && event->type_len == RINGBUF_TYPE_PADDING)
6446 goto again;
6447
6448 return event;
6449 }
6450 EXPORT_SYMBOL_GPL(ring_buffer_consume);
6451
6452 /**
6453 * ring_buffer_read_start - start a non consuming read of the buffer
6454 * @buffer: The ring buffer to read from
6455 * @cpu: The cpu buffer to iterate over
6456 * @flags: gfp flags to use for memory allocation
6457 *
6458 * This creates an iterator to allow non-consuming iteration through
6459 * the buffer. If the buffer is disabled for writing, it will produce
6460 * the same information each time, but if the buffer is still writing
6461 * then the first hit of a write will cause the iteration to stop.
6462 *
6463 * Must be paired with ring_buffer_read_finish.
6464 */
6465 struct ring_buffer_iter *
6466 ring_buffer_read_start(struct trace_buffer *buffer, int cpu, gfp_t flags)
6467 {
6468 struct ring_buffer_iter *iter __free(kfree) = kzalloc_obj(*iter, flags);
6469 struct ring_buffer_per_cpu *cpu_buffer;
6470
6471 if (!iter)
6472 return NULL;
6473
6474 if (!cpumask_test_cpu(cpu, buffer->cpumask))
6475 return NULL;
6476
6477 cpu_buffer = buffer->buffers[cpu];
6478
6479 /*
6480 * Only KDB is using GFP_ATOMIC, for the others, lock the buffer to
6481 * prevent concurrent resizing.
6482 */
6483 if (gfpflags_allow_blocking(flags))
6484 mutex_lock(&buffer->mutex);
6485
6486 atomic_inc(&cpu_buffer->resize_disabled);
6487
6488 if (gfpflags_allow_blocking(flags))
6489 mutex_unlock(&buffer->mutex);
6490
6491 /* Holds the entire event: data and meta data. */
6492 iter->event_size = rb_page_capacity(READ_ONCE(cpu_buffer->reader_page));
6493 iter->event = kmalloc(iter->event_size, flags);
6494 if (!iter->event) {
6495 atomic_dec(&cpu_buffer->resize_disabled);
6496 return NULL;
6497 }
6498 iter->cpu_buffer = cpu_buffer;
6499
6500 guard(raw_spinlock_irqsave)(&cpu_buffer->reader_lock);
6501 arch_spin_lock(&cpu_buffer->lock);
6502 rb_iter_reset(iter);
6503 arch_spin_unlock(&cpu_buffer->lock);
6504
6505 return_ptr(iter);
6506 }
6507 EXPORT_SYMBOL_GPL(ring_buffer_read_start);
6508
6509 /**
6510 * ring_buffer_read_finish - finish reading the iterator of the buffer
6511 * @iter: The iterator retrieved by ring_buffer_start
6512 *
6513 * This re-enables resizing of the buffer, and frees the iterator.
6514 */
6515 void
6516 ring_buffer_read_finish(struct ring_buffer_iter *iter)
6517 {
6518 struct ring_buffer_per_cpu *cpu_buffer = iter->cpu_buffer;
6519
6520 /* Use this opportunity to check the integrity of the ring buffer. */
6521 rb_check_pages(cpu_buffer);
6522
6523 atomic_dec(&cpu_buffer->resize_disabled);
6524 kfree(iter->event);
6525 kfree(iter);
6526 }
6527 EXPORT_SYMBOL_GPL(ring_buffer_read_finish);
6528
6529 /**
6530 * ring_buffer_iter_advance - advance the iterator to the next location
6531 * @iter: The ring buffer iterator
6532 *
6533 * Move the location of the iterator such that the next read will
6534 * be the next location of the iterator.
6535 */
6536 void ring_buffer_iter_advance(struct ring_buffer_iter *iter)
6537 {
6538 struct ring_buffer_per_cpu *cpu_buffer = iter->cpu_buffer;
6539 unsigned long flags;
6540
6541 raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
6542 iter->missed_events = 0;
6543 rb_advance_iter(iter);
6544
6545 raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
6546 }
6547 EXPORT_SYMBOL_GPL(ring_buffer_iter_advance);
6548
6549 /**
6550 * ring_buffer_size - return the size of the ring buffer (in bytes)
6551 * @buffer: The ring buffer.
6552 * @cpu: The CPU to get ring buffer size from.
6553 */
6554 unsigned long ring_buffer_size(struct trace_buffer *buffer, int cpu)
6555 {
6556 if (!cpumask_test_cpu(cpu, buffer->cpumask))
6557 return 0;
6558
6559 return rb_subbuf_capacity(buffer) * buffer->buffers[cpu]->nr_pages;
6560 }
6561 EXPORT_SYMBOL_GPL(ring_buffer_size);
6562
6563 /**
6564 * ring_buffer_max_event_size - return the max data size of an event
6565 * @buffer: The ring buffer.
6566 *
6567 * Returns the maximum size an event can be.
6568 */
6569 unsigned long ring_buffer_max_event_size(struct trace_buffer *buffer)
6570 {
6571 /* If abs timestamp is requested, events have a timestamp too */
6572 if (ring_buffer_time_stamp_abs(buffer))
6573 return rb_subbuf_max_data_size(buffer) - RB_LEN_TIME_EXTEND;
6574
6575 return rb_subbuf_max_data_size(buffer);
6576 }
6577 EXPORT_SYMBOL_GPL(ring_buffer_max_event_size);
6578
6579 static void rb_clear_buffer_page(struct buffer_page *page)
6580 {
6581 local_set(&page->write, 0);
6582 local_set(&page->entries, 0);
6583 rb_init_data_page(page->page);
6584 page->read = 0;
6585 }
6586
6587 /*
6588 * When the buffer is memory mapped to user space, each sub buffer
6589 * has a unique id that is used by the meta data to tell the user
6590 * where the current reader page is.
6591 *
6592 * For a normal allocated ring buffer, the id is saved in the buffer page
6593 * id field, and updated via this function.
6594 *
6595 * But for a fixed memory mapped buffer, the id is already assigned for
6596 * fixed memory ordering in the memory layout and can not be used. Instead
6597 * the index of where the page lies in the memory layout is used.
6598 *
6599 * For the normal pages, set the buffer page id with the passed in @id
6600 * value and return that.
6601 *
6602 * For fixed memory mapped pages, get the page index in the memory layout
6603 * and return that as the id.
6604 */
6605 static int rb_page_id(struct ring_buffer_per_cpu *cpu_buffer,
6606 struct buffer_page *bpage, int id)
6607 {
6608 /*
6609 * For boot buffers, the id is the index,
6610 * otherwise, set the buffer page with this id
6611 */
6612 if (cpu_buffer->ring_meta)
6613 id = rb_meta_subbuf_idx(cpu_buffer->ring_meta, bpage->page);
6614 else
6615 bpage->id = id;
6616
6617 return id;
6618 }
6619
6620 static void rb_update_meta_page(struct ring_buffer_per_cpu *cpu_buffer)
6621 {
6622 struct trace_buffer_meta *meta = cpu_buffer->meta_page;
6623
6624 if (!meta)
6625 return;
6626
6627 meta->reader.read = cpu_buffer->reader_page->read;
6628 meta->reader.id = rb_page_id(cpu_buffer, cpu_buffer->reader_page,
6629 cpu_buffer->reader_page->id);
6630
6631 meta->reader.lost_events = cpu_buffer->lost_events;
6632
6633 meta->entries = local_read(&cpu_buffer->entries);
6634 meta->overrun = local_read(&cpu_buffer->overrun);
6635 meta->read = cpu_buffer->read;
6636 meta->pages_lost = local_read(&cpu_buffer->pages_lost);
6637 meta->pages_touched = local_read(&cpu_buffer->pages_touched);
6638
6639 /* Some archs do not have data cache coherency between kernel and user-space */
6640 flush_kernel_vmap_range(cpu_buffer->meta_page, PAGE_SIZE);
6641 }
6642
6643 static void
6644 rb_reset_cpu(struct ring_buffer_per_cpu *cpu_buffer)
6645 {
6646 struct buffer_page *page;
6647
6648 if (cpu_buffer->remote) {
6649 if (!cpu_buffer->remote->reset)
6650 return;
6651
6652 cpu_buffer->remote->reset(cpu_buffer->cpu, cpu_buffer->remote->priv);
6653 rb_read_remote_meta_page(cpu_buffer);
6654
6655 /* Read related values, not covered by the meta-page */
6656 local_set(&cpu_buffer->pages_read, 0);
6657 cpu_buffer->read = 0;
6658 cpu_buffer->read_bytes = 0;
6659 cpu_buffer->last_overrun = 0;
6660 cpu_buffer->reader_page->read = 0;
6661
6662 return;
6663 }
6664
6665 rb_head_page_deactivate(cpu_buffer);
6666
6667 cpu_buffer->head_page
6668 = list_entry(cpu_buffer->pages, struct buffer_page, list);
6669 rb_clear_buffer_page(cpu_buffer->head_page);
6670 list_for_each_entry(page, cpu_buffer->pages, list) {
6671 rb_clear_buffer_page(page);
6672 }
6673
6674 cpu_buffer->tail_page = cpu_buffer->head_page;
6675 cpu_buffer->commit_page = cpu_buffer->head_page;
6676
6677 INIT_LIST_HEAD(&cpu_buffer->reader_page->list);
6678 INIT_LIST_HEAD(&cpu_buffer->new_pages);
6679 rb_clear_buffer_page(cpu_buffer->reader_page);
6680
6681 local_set(&cpu_buffer->entries_bytes, 0);
6682 local_set(&cpu_buffer->overrun, 0);
6683 local_set(&cpu_buffer->commit_overrun, 0);
6684 local_set(&cpu_buffer->dropped_events, 0);
6685 local_set(&cpu_buffer->entries, 0);
6686 local_set(&cpu_buffer->committing, 0);
6687 local_set(&cpu_buffer->commits, 0);
6688 local_set(&cpu_buffer->pages_touched, 0);
6689 local_set(&cpu_buffer->pages_lost, 0);
6690 local_set(&cpu_buffer->pages_read, 0);
6691 cpu_buffer->last_pages_touch = 0;
6692 cpu_buffer->shortest_full = 0;
6693 cpu_buffer->read = 0;
6694 cpu_buffer->read_bytes = 0;
6695
6696 rb_time_set(&cpu_buffer->write_stamp, 0);
6697 rb_time_set(&cpu_buffer->before_stamp, 0);
6698
6699 memset(cpu_buffer->event_stamp, 0, sizeof(cpu_buffer->event_stamp));
6700
6701 cpu_buffer->lost_events = 0;
6702 cpu_buffer->last_overrun = 0;
6703
6704 rb_head_page_activate(cpu_buffer);
6705 cpu_buffer->pages_removed = 0;
6706
6707 rb_update_meta_page(cpu_buffer);
6708 if (cpu_buffer->ring_meta) {
6709 struct ring_buffer_cpu_meta *meta = cpu_buffer->ring_meta;
6710
6711 meta->commit_buffer = meta->head_buffer;
6712 }
6713 }
6714
6715 /* Must have disabled the cpu buffer then done a synchronize_rcu */
6716 static void reset_disabled_cpu_buffer(struct ring_buffer_per_cpu *cpu_buffer)
6717 {
6718 guard(raw_spinlock_irqsave)(&cpu_buffer->reader_lock);
6719
6720 if (RB_WARN_ON(cpu_buffer, local_read(&cpu_buffer->committing)))
6721 return;
6722
6723 arch_spin_lock(&cpu_buffer->lock);
6724
6725 rb_reset_cpu(cpu_buffer);
6726
6727 arch_spin_unlock(&cpu_buffer->lock);
6728 }
6729
6730 /**
6731 * ring_buffer_reset_cpu - reset a ring buffer per CPU buffer
6732 * @buffer: The ring buffer to reset a per cpu buffer of
6733 * @cpu: The CPU buffer to be reset
6734 */
6735 void ring_buffer_reset_cpu(struct trace_buffer *buffer, int cpu)
6736 {
6737 struct ring_buffer_per_cpu *cpu_buffer = buffer->buffers[cpu];
6738
6739 if (!cpumask_test_cpu(cpu, buffer->cpumask))
6740 return;
6741
6742 /* prevent another thread from changing buffer sizes */
6743 mutex_lock(&buffer->mutex);
6744
6745 atomic_inc(&cpu_buffer->resize_disabled);
6746 atomic_inc(&cpu_buffer->record_disabled);
6747
6748 /* Make sure all commits have finished */
6749 synchronize_rcu();
6750
6751 reset_disabled_cpu_buffer(cpu_buffer);
6752
6753 atomic_dec(&cpu_buffer->record_disabled);
6754 atomic_dec(&cpu_buffer->resize_disabled);
6755
6756 mutex_unlock(&buffer->mutex);
6757 }
6758 EXPORT_SYMBOL_GPL(ring_buffer_reset_cpu);
6759
6760 /* Flag to ensure proper resetting of atomic variables */
6761 #define RESET_BIT (1 << 30)
6762
6763 /**
6764 * ring_buffer_reset_online_cpus - reset a ring buffer per CPU buffer
6765 * @buffer: The ring buffer to reset a per cpu buffer of
6766 */
6767 void ring_buffer_reset_online_cpus(struct trace_buffer *buffer)
6768 {
6769 struct ring_buffer_per_cpu *cpu_buffer;
6770 int cpu;
6771
6772 /* prevent another thread from changing buffer sizes */
6773 mutex_lock(&buffer->mutex);
6774
6775 for_each_online_buffer_cpu(buffer, cpu) {
6776 cpu_buffer = buffer->buffers[cpu];
6777
6778 atomic_add(RESET_BIT, &cpu_buffer->resize_disabled);
6779 atomic_inc(&cpu_buffer->record_disabled);
6780 }
6781
6782 /* Make sure all commits have finished */
6783 synchronize_rcu();
6784
6785 for_each_buffer_cpu(buffer, cpu) {
6786 cpu_buffer = buffer->buffers[cpu];
6787
6788 /*
6789 * If a CPU came online during the synchronize_rcu(), then
6790 * ignore it.
6791 */
6792 if (!(atomic_read(&cpu_buffer->resize_disabled) & RESET_BIT))
6793 continue;
6794
6795 reset_disabled_cpu_buffer(cpu_buffer);
6796
6797 atomic_dec(&cpu_buffer->record_disabled);
6798 atomic_sub(RESET_BIT, &cpu_buffer->resize_disabled);
6799 }
6800
6801 mutex_unlock(&buffer->mutex);
6802 }
6803
6804 /**
6805 * ring_buffer_reset - reset a ring buffer
6806 * @buffer: The ring buffer to reset all cpu buffers
6807 */
6808 void ring_buffer_reset(struct trace_buffer *buffer)
6809 {
6810 struct ring_buffer_per_cpu *cpu_buffer;
6811 int cpu;
6812
6813 /* prevent another thread from changing buffer sizes */
6814 mutex_lock(&buffer->mutex);
6815
6816 for_each_buffer_cpu(buffer, cpu) {
6817 cpu_buffer = buffer->buffers[cpu];
6818
6819 atomic_inc(&cpu_buffer->resize_disabled);
6820 atomic_inc(&cpu_buffer->record_disabled);
6821 }
6822
6823 /* Make sure all commits have finished */
6824 synchronize_rcu();
6825
6826 for_each_buffer_cpu(buffer, cpu) {
6827 cpu_buffer = buffer->buffers[cpu];
6828
6829 reset_disabled_cpu_buffer(cpu_buffer);
6830
6831 atomic_dec(&cpu_buffer->record_disabled);
6832 atomic_dec(&cpu_buffer->resize_disabled);
6833 }
6834
6835 mutex_unlock(&buffer->mutex);
6836 }
6837 EXPORT_SYMBOL_GPL(ring_buffer_reset);
6838
6839 /**
6840 * ring_buffer_empty - is the ring buffer empty?
6841 * @buffer: The ring buffer to test
6842 */
6843 bool ring_buffer_empty(struct trace_buffer *buffer)
6844 {
6845 struct ring_buffer_per_cpu *cpu_buffer;
6846 unsigned long flags;
6847 bool dolock;
6848 bool ret;
6849 int cpu;
6850
6851 /* yes this is racy, but if you don't like the race, lock the buffer */
6852 for_each_buffer_cpu(buffer, cpu) {
6853 cpu_buffer = buffer->buffers[cpu];
6854 local_irq_save(flags);
6855 dolock = rb_reader_lock(cpu_buffer);
6856 ret = rb_per_cpu_empty(cpu_buffer);
6857 rb_reader_unlock(cpu_buffer, dolock);
6858 local_irq_restore(flags);
6859
6860 if (!ret)
6861 return false;
6862 }
6863
6864 return true;
6865 }
6866 EXPORT_SYMBOL_GPL(ring_buffer_empty);
6867
6868 /**
6869 * ring_buffer_empty_cpu - is a cpu buffer of a ring buffer empty?
6870 * @buffer: The ring buffer
6871 * @cpu: The CPU buffer to test
6872 */
6873 bool ring_buffer_empty_cpu(struct trace_buffer *buffer, int cpu)
6874 {
6875 struct ring_buffer_per_cpu *cpu_buffer;
6876 unsigned long flags;
6877 bool dolock;
6878 bool ret;
6879
6880 if (!cpumask_test_cpu(cpu, buffer->cpumask))
6881 return true;
6882
6883 cpu_buffer = buffer->buffers[cpu];
6884 local_irq_save(flags);
6885 dolock = rb_reader_lock(cpu_buffer);
6886 ret = rb_per_cpu_empty(cpu_buffer);
6887 rb_reader_unlock(cpu_buffer, dolock);
6888 local_irq_restore(flags);
6889
6890 return ret;
6891 }
6892 EXPORT_SYMBOL_GPL(ring_buffer_empty_cpu);
6893
6894 int ring_buffer_poll_remote(struct trace_buffer *buffer, int cpu)
6895 {
6896 struct ring_buffer_per_cpu *cpu_buffer;
6897
6898 if (cpu != RING_BUFFER_ALL_CPUS) {
6899 if (!cpumask_test_cpu(cpu, buffer->cpumask))
6900 return -EINVAL;
6901
6902 cpu_buffer = buffer->buffers[cpu];
6903
6904 guard(raw_spinlock)(&cpu_buffer->reader_lock);
6905 if (rb_read_remote_meta_page(cpu_buffer))
6906 rb_wakeups(buffer, cpu_buffer);
6907
6908 return 0;
6909 }
6910
6911 guard(cpus_read_lock)();
6912
6913 /*
6914 * Make sure all the ring buffers are up to date before we start reading
6915 * them.
6916 */
6917 for_each_buffer_cpu(buffer, cpu) {
6918 cpu_buffer = buffer->buffers[cpu];
6919
6920 guard(raw_spinlock)(&cpu_buffer->reader_lock);
6921 rb_read_remote_meta_page(cpu_buffer);
6922 }
6923
6924 for_each_buffer_cpu(buffer, cpu) {
6925 cpu_buffer = buffer->buffers[cpu];
6926
6927 if (rb_num_of_entries(cpu_buffer))
6928 rb_wakeups(buffer, cpu_buffer);
6929 }
6930
6931 return 0;
6932 }
6933
6934 #ifdef CONFIG_RING_BUFFER_ALLOW_SWAP
6935 /**
6936 * ring_buffer_swap_cpu - swap a CPU buffer between two ring buffers
6937 * @buffer_a: One buffer to swap with
6938 * @buffer_b: The other buffer to swap with
6939 * @cpu: the CPU of the buffers to swap
6940 *
6941 * This function is useful for tracers that want to take a "snapshot"
6942 * of a CPU buffer and has another back up buffer lying around.
6943 * it is expected that the tracer handles the cpu buffer not being
6944 * used at the moment.
6945 */
6946 int ring_buffer_swap_cpu(struct trace_buffer *buffer_a,
6947 struct trace_buffer *buffer_b, int cpu)
6948 {
6949 struct ring_buffer_per_cpu *cpu_buffer_a;
6950 struct ring_buffer_per_cpu *cpu_buffer_b;
6951 int ret = -EBUSY;
6952
6953 if (!cpumask_test_cpu(cpu, buffer_a->cpumask) ||
6954 !cpumask_test_cpu(cpu, buffer_b->cpumask))
6955 return -EINVAL;
6956
6957 cpu_buffer_a = buffer_a->buffers[cpu];
6958 cpu_buffer_b = buffer_b->buffers[cpu];
6959
6960 /* It's up to the callers to not try to swap static buffers */
6961 if (WARN_ON_ONCE(rb_is_static(cpu_buffer_a) || rb_is_static(cpu_buffer_b)))
6962 return -EBUSY;
6963
6964 /* At least make sure the two buffers are somewhat the same */
6965 if (cpu_buffer_a->nr_pages != cpu_buffer_b->nr_pages)
6966 return -EINVAL;
6967
6968 if (buffer_a->subbuf_order != buffer_b->subbuf_order)
6969 return -EINVAL;
6970
6971 if (atomic_read(&buffer_a->record_disabled))
6972 return -EAGAIN;
6973
6974 if (atomic_read(&buffer_b->record_disabled))
6975 return -EAGAIN;
6976
6977 if (atomic_read(&cpu_buffer_a->record_disabled))
6978 return -EAGAIN;
6979
6980 if (atomic_read(&cpu_buffer_b->record_disabled))
6981 return -EAGAIN;
6982
6983 /*
6984 * We can't do a synchronize_rcu here because this
6985 * function can be called in atomic context.
6986 * Normally this will be called from the same CPU as cpu.
6987 * If not it's up to the caller to protect this.
6988 */
6989 atomic_inc(&cpu_buffer_a->record_disabled);
6990 atomic_inc(&cpu_buffer_b->record_disabled);
6991
6992 /* Do not swap if either buffer is in the process of writing */
6993 if (cpu_buffer_a->current_context)
6994 goto out_dec;
6995 if (cpu_buffer_b->current_context)
6996 goto out_dec;
6997
6998 /*
6999 * When resize is in progress, we cannot swap it because
7000 * it will mess the state of the cpu buffer.
7001 */
7002 if (atomic_read(&buffer_a->resizing))
7003 goto out_dec;
7004 if (atomic_read(&buffer_b->resizing))
7005 goto out_dec;
7006
7007 buffer_a->buffers[cpu] = cpu_buffer_b;
7008 buffer_b->buffers[cpu] = cpu_buffer_a;
7009
7010 cpu_buffer_b->buffer = buffer_a;
7011 cpu_buffer_a->buffer = buffer_b;
7012
7013 ret = 0;
7014
7015 out_dec:
7016 atomic_dec(&cpu_buffer_a->record_disabled);
7017 atomic_dec(&cpu_buffer_b->record_disabled);
7018 return ret;
7019 }
7020 EXPORT_SYMBOL_GPL(ring_buffer_swap_cpu);
7021 #endif /* CONFIG_RING_BUFFER_ALLOW_SWAP */
7022
7023 /**
7024 * ring_buffer_alloc_read_page - allocate a page to read from buffer
7025 * @buffer: the buffer to allocate for.
7026 * @cpu: the cpu buffer to allocate.
7027 * @rpage: pointer to pass in an already allocated page (can be NULL)
7028 * and returns the allocated page.
7029 *
7030 * This function is used in conjunction with ring_buffer_read_page().
7031 * When reading a full page from the ring buffer, these functions
7032 * can be used to speed up the process. The calling function should
7033 * allocate a few pages first with this function. Then when it
7034 * needs to get pages from the ring buffer, it passes the result
7035 * of this function into ring_buffer_read_page(), which will swap
7036 * the page that was allocated, with the read page of the buffer.
7037 *
7038 * If @rpage is provided, and it has a different order than the current
7039 * subbuffer order, its payload will be freed and re-allocated. If it
7040 * already matches the order, it is simply returned.
7041 *
7042 * Returns:
7043 * 0 on success, < 0 on error
7044 */
7045 int ring_buffer_alloc_read_page(struct trace_buffer *buffer, int cpu,
7046 struct buffer_data_read_page **rpage)
7047 {
7048 struct ring_buffer_per_cpu *cpu_buffer;
7049 unsigned long flags;
7050 unsigned int order;
7051
7052 if (!cpumask_test_cpu(cpu, buffer->cpumask))
7053 return -ENODEV;
7054
7055 if (!rpage)
7056 return -EINVAL;
7057
7058 order = READ_ONCE(buffer->subbuf_order);
7059
7060 if (*rpage) {
7061 if ((*rpage)->order == order)
7062 return 0;
7063
7064 /* We can reuse rpage, but we discard the payload */
7065 free_pages((unsigned long)(*rpage)->data, (*rpage)->order);
7066 (*rpage)->data = NULL;
7067 } else {
7068 *rpage = kzalloc_obj(**rpage);
7069 if (!*rpage)
7070 return -ENOMEM;
7071 }
7072
7073 (*rpage)->order = order;
7074 cpu_buffer = buffer->buffers[cpu];
7075
7076 local_irq_save(flags);
7077 arch_spin_lock(&cpu_buffer->lock);
7078
7079 if (cpu_buffer->free_page.data) {
7080 **rpage = cpu_buffer->free_page;
7081 cpu_buffer->free_page.data = NULL;
7082 }
7083
7084 arch_spin_unlock(&cpu_buffer->lock);
7085 local_irq_restore(flags);
7086
7087 if ((*rpage)->data) {
7088 rb_init_data_page((*rpage)->data);
7089 } else {
7090 (*rpage)->data = alloc_cpu_data(cpu, (*rpage)->order);
7091 if (!(*rpage)->data) {
7092 kfree(*rpage);
7093 *rpage = NULL;
7094 return -ENOMEM;
7095 }
7096 }
7097
7098 return 0;
7099 }
7100 EXPORT_SYMBOL_GPL(ring_buffer_alloc_read_page);
7101
7102 /**
7103 * ring_buffer_free_read_page - free an allocated read page
7104 * @buffer: the buffer the page was allocate for
7105 * @cpu: the cpu buffer the page came from
7106 * @rpage: the buffer_data_read_page to free
7107 *
7108 * Free a page allocated from ring_buffer_alloc_read_page.
7109 */
7110 void ring_buffer_free_read_page(struct trace_buffer *buffer, int cpu,
7111 struct buffer_data_read_page *rpage)
7112 {
7113 struct ring_buffer_per_cpu *cpu_buffer;
7114 struct buffer_data_page *dpage;
7115 unsigned long flags;
7116 struct page *page;
7117
7118 if (!buffer || !buffer->buffers || !buffer->buffers[cpu])
7119 return;
7120
7121 if (!rpage)
7122 return;
7123
7124 dpage = rpage->data;
7125 if (!dpage)
7126 goto out;
7127
7128 page = virt_to_page(dpage);
7129
7130 cpu_buffer = buffer->buffers[cpu];
7131
7132 /*
7133 * If the page is still in use someplace else, or order of the page
7134 * is different from the subbuffer order of the buffer -
7135 * we can't reuse it
7136 */
7137 if (page_ref_count(page) > 1 || rpage->order != READ_ONCE(buffer->subbuf_order))
7138 goto out;
7139
7140 local_irq_save(flags);
7141 arch_spin_lock(&cpu_buffer->lock);
7142
7143 if (!cpu_buffer->free_page.data) {
7144 cpu_buffer->free_page = *rpage;
7145 dpage = NULL;
7146 }
7147
7148 arch_spin_unlock(&cpu_buffer->lock);
7149 local_irq_restore(flags);
7150
7151 out:
7152 free_pages((unsigned long)dpage, rpage->order);
7153 kfree(rpage);
7154 }
7155 EXPORT_SYMBOL_GPL(ring_buffer_free_read_page);
7156
7157 /**
7158 * ring_buffer_read_page - extract a page from the ring buffer
7159 * @buffer: buffer to extract from
7160 * @data_page: the page to use allocated from ring_buffer_alloc_read_page
7161 * @len: amount to extract
7162 * @cpu: the cpu of the buffer to extract
7163 * @full: should the extraction only happen when the page is full.
7164 *
7165 * This function will pull out a page from the ring buffer and consume it.
7166 * @data_page must be the address of the variable that was returned
7167 * from ring_buffer_alloc_read_page. This is because the page might be used
7168 * to swap with a page in the ring buffer.
7169 *
7170 * for example:
7171 * rpage = ring_buffer_alloc_read_page(buffer, cpu);
7172 * if (IS_ERR(rpage))
7173 * return PTR_ERR(rpage);
7174 * ret = ring_buffer_read_page(buffer, rpage, len, cpu, 0);
7175 * if (ret >= 0)
7176 * process_page(ring_buffer_read_page_data(rpage), ret);
7177 * ring_buffer_free_read_page(buffer, cpu, rpage);
7178 *
7179 * When @full is set, the function will not return true unless
7180 * the writer is off the reader page.
7181 *
7182 * Note: it is up to the calling functions to handle sleeps and wakeups.
7183 * The ring buffer can be used anywhere in the kernel and can not
7184 * blindly call wake_up. The layer that uses the ring buffer must be
7185 * responsible for that.
7186 *
7187 * Returns:
7188 * >=0 if data has been transferred, returns the offset of consumed data.
7189 * <0 if no data has been transferred.
7190 */
7191 int ring_buffer_read_page(struct trace_buffer *buffer,
7192 struct buffer_data_read_page *data_page,
7193 size_t len, int cpu, int full)
7194 {
7195 struct ring_buffer_per_cpu *cpu_buffer = buffer->buffers[cpu];
7196 struct ring_buffer_event *event;
7197 struct buffer_data_page *dpage;
7198 struct buffer_page *reader;
7199 long missed_events;
7200 unsigned int commit;
7201 unsigned int size;
7202 unsigned int read;
7203 u64 save_timestamp;
7204
7205 if (!cpumask_test_cpu(cpu, buffer->cpumask))
7206 return -1;
7207
7208 /*
7209 * If len is not big enough to hold the page header, then
7210 * we can not copy anything.
7211 */
7212 if (len <= BUF_PAGE_HDR_SIZE)
7213 return -1;
7214
7215 len -= BUF_PAGE_HDR_SIZE;
7216
7217 if (!data_page || !data_page->data)
7218 return -1;
7219
7220 dpage = data_page->data;
7221 if (!dpage)
7222 return -1;
7223
7224 len = min_t(size_t, len, rb_read_page_capacity(data_page));
7225
7226 guard(raw_spinlock_irqsave)(&cpu_buffer->reader_lock);
7227
7228 reader = rb_get_reader_page(cpu_buffer);
7229 if (!reader)
7230 return -1;
7231
7232 event = rb_reader_event(cpu_buffer);
7233
7234 read = reader->read;
7235 commit = rb_page_commit(reader);
7236 size = rb_page_size(reader);
7237
7238 /* Check if any events were dropped */
7239 missed_events = cpu_buffer->lost_events;
7240
7241 /*
7242 * It is not possible to swap the reader page if:
7243 * - It has been partially read
7244 * - len is not big enough to read it entirely
7245 * - A writer is still on it
7246 * - The ring buffer is static
7247 * - The order doesn't match
7248 */
7249 if (read || (len < (size - read)) ||
7250 cpu_buffer->reader_page == cpu_buffer->commit_page ||
7251 rb_is_static(cpu_buffer) ||
7252 data_page->order != reader->order) {
7253 struct buffer_data_page *rpage = cpu_buffer->reader_page->page;
7254 unsigned int rpos = read;
7255 unsigned int pos = 0;
7256 unsigned int event_size;
7257 unsigned int flags = 0;
7258
7259 /* If a full page is requested, it cannot be the commit page */
7260 if (full && cpu_buffer->reader_page == cpu_buffer->commit_page)
7261 return -1;
7262
7263 if (len > (size - read))
7264 len = (size - read);
7265
7266 /* Always keep the time extend and data together */
7267 event_size = rb_event_ts_length(event);
7268
7269 if (len < event_size)
7270 return -1;
7271
7272 if (commit & RB_MISSED_EVENTS)
7273 flags = RB_MISSED_EVENTS;
7274
7275 /* save the current timestamp, since the user will need it */
7276 save_timestamp = cpu_buffer->read_stamp;
7277
7278 /* Need to copy one event at a time */
7279 do {
7280 /* We need the size of one event, because
7281 * rb_advance_reader only advances by one event,
7282 * whereas rb_event_ts_length may include the size of
7283 * one or two events.
7284 * We have already ensured there's enough space if this
7285 * is a time extend. */
7286 event_size = rb_event_length(event);
7287 memcpy(dpage->data + pos, rpage->data + rpos, event_size);
7288
7289 len -= event_size;
7290
7291 rb_advance_reader(cpu_buffer);
7292 rpos = reader->read;
7293 pos += event_size;
7294
7295 if (rpos >= size)
7296 break;
7297
7298 event = rb_reader_event(cpu_buffer);
7299 /* Always keep the time extend and data together */
7300 event_size = rb_event_ts_length(event);
7301 } while (len >= event_size);
7302
7303 /* update dpage */
7304 local_set(&dpage->commit, pos | flags);
7305 dpage->time_stamp = save_timestamp;
7306
7307 /* we copied everything to the beginning */
7308 read = 0;
7309 } else {
7310 /* update the entry counter */
7311 cpu_buffer->read += rb_page_entries(reader);
7312 cpu_buffer->read_bytes += rb_page_size(reader);
7313
7314 /* swap the pages */
7315 rb_init_data_page(dpage);
7316 dpage = reader->page;
7317 reader->page = data_page->data;
7318 local_set(&reader->write, 0);
7319 local_set(&reader->entries, 0);
7320 reader->read = 0;
7321 data_page->data = dpage;
7322 if (!missed_events && rb_data_page_commit(dpage) & RB_MISSED_EVENTS)
7323 missed_events = -1;
7324
7325 /*
7326 * Use the real_end for the data size,
7327 * This gives us a chance to store the lost events
7328 * on the page.
7329 */
7330 if (reader->real_end)
7331 local_set(&dpage->commit, reader->real_end);
7332 }
7333
7334 cpu_buffer->lost_events = 0;
7335
7336 size = rb_data_page_size(dpage);
7337 /*
7338 * Set a flag in the commit field if we lost events
7339 */
7340 if (missed_events) {
7341 /*
7342 * If there is room at the end of the page to save the
7343 * missed events, then record it there.
7344 */
7345 if (missed_events > 0 &&
7346 rb_read_page_capacity(data_page) - size >= sizeof(missed_events)) {
7347 memcpy(&dpage->data[size], &missed_events,
7348 sizeof(missed_events));
7349 local_add(RB_MISSED_STORED, &dpage->commit);
7350 size += sizeof(missed_events);
7351 }
7352 /*
7353 * Note, for the persistent ring buffer, the RB_MISSED_EVENTS
7354 * may have been set in the main buffer via the verification code.
7355 * But here, dpage is a copy of that page and has not yet had
7356 * the RB_MISSED_EVENTS set. As for the normal buffers,
7357 * the main write buffer does not set these bits and it needs
7358 * to be set here.
7359 */
7360 local_add(RB_MISSED_EVENTS, &dpage->commit);
7361 }
7362
7363 /*
7364 * This page may be off to user land. Zero it out here.
7365 */
7366 if (size < rb_read_page_capacity(data_page))
7367 memset(&dpage->data[size], 0, rb_read_page_capacity(data_page) - size);
7368
7369 return read;
7370 }
7371 EXPORT_SYMBOL_GPL(ring_buffer_read_page);
7372
7373 /**
7374 * ring_buffer_read_page_data - get pointer to the data in the page.
7375 * @page: the page to get the data from
7376 *
7377 * Returns pointer to the actual data in this page.
7378 */
7379 void *ring_buffer_read_page_data(struct buffer_data_read_page *page)
7380 {
7381 return page->data;
7382 }
7383 EXPORT_SYMBOL_GPL(ring_buffer_read_page_data);
7384
7385 /**
7386 * ring_buffer_read_page_size - get size of the read page.
7387 * @rpage: the page to get the size from
7388 *
7389 * Returns size of the page in bytes.
7390 */
7391 unsigned int ring_buffer_read_page_size(struct buffer_data_read_page *rpage)
7392 {
7393 return rpage ? PAGE_SIZE << rpage->order : 0;
7394 }
7395 EXPORT_SYMBOL_GPL(ring_buffer_read_page_size);
7396
7397 /**
7398 * ring_buffer_subbuf_size_get - get size of the sub buffer.
7399 * @buffer: the buffer to get the sub buffer size from
7400 *
7401 * Returns size of the sub buffer, in bytes.
7402 */
7403 int ring_buffer_subbuf_size_get(struct trace_buffer *buffer)
7404 {
7405 return rb_subbuf_size(buffer);
7406 }
7407 EXPORT_SYMBOL_GPL(ring_buffer_subbuf_size_get);
7408
7409 /**
7410 * ring_buffer_subbuf_order_get - get order of system sub pages in one buffer page.
7411 * @buffer: The ring_buffer to get the system sub page order from
7412 *
7413 * By default, one ring buffer sub page equals to one system page. This parameter
7414 * is configurable, per ring buffer. The size of the ring buffer sub page can be
7415 * extended, but must be an order of system page size.
7416 *
7417 * Returns the order of buffer sub page size, in system pages:
7418 * 0 means the sub buffer size is 1 system page and so forth.
7419 * In case of an error < 0 is returned.
7420 */
7421 int ring_buffer_subbuf_order_get(struct trace_buffer *buffer)
7422 {
7423 if (!buffer)
7424 return -EINVAL;
7425
7426 return buffer->subbuf_order;
7427 }
7428 EXPORT_SYMBOL_GPL(ring_buffer_subbuf_order_get);
7429
7430 /**
7431 * ring_buffer_subbuf_order_set - set the size of ring buffer sub page.
7432 * @buffer: The ring_buffer to set the new page size.
7433 * @order: Order of the system pages in one sub buffer page
7434 *
7435 * By default, one ring buffer pages equals to one system page. This API can be
7436 * used to set new size of the ring buffer page. The size must be order of
7437 * system page size, that's why the input parameter @order is the order of
7438 * system pages that are allocated for one ring buffer page:
7439 * 0 - 1 system page
7440 * 1 - 2 system pages
7441 * 3 - 4 system pages
7442 * ...
7443 *
7444 * Returns 0 on success or < 0 in case of an error.
7445 */
7446 int ring_buffer_subbuf_order_set(struct trace_buffer *buffer, int order)
7447 {
7448 struct ring_buffer_per_cpu *cpu_buffer;
7449 struct buffer_page *bpage, *tmp;
7450 unsigned int old_capacity;
7451 unsigned long nr_pages;
7452 int old_order;
7453 int psize;
7454 int err;
7455 int cpu;
7456
7457 if (!buffer || order < 0)
7458 return -EINVAL;
7459
7460 psize = (1 << order) * PAGE_SIZE;
7461 if (psize <= BUF_PAGE_HDR_SIZE)
7462 return -EINVAL;
7463
7464 /* Size of a subbuf cannot be greater than the write counter */
7465 if (psize > RB_WRITE_MASK + 1)
7466 return -EINVAL;
7467
7468 /* prevent another thread from changing buffer sizes */
7469 guard(mutex)(&buffer->mutex);
7470
7471 old_order = buffer->subbuf_order;
7472 if (old_order == order)
7473 return 0;
7474
7475 old_capacity = rb_subbuf_capacity(buffer);
7476
7477 /* The mmap fast path reads subbuf_order without buffer->mutex. */
7478 for_each_buffer_cpu(buffer, cpu) {
7479 if (!cpumask_test_cpu(cpu, buffer->cpumask))
7480 continue;
7481 if (atomic_read(&buffer->buffers[cpu]->resize_disabled))
7482 return -EBUSY;
7483 }
7484
7485 atomic_inc(&buffer->record_disabled);
7486
7487 /* Make sure all commits have finished */
7488 synchronize_rcu();
7489
7490 WRITE_ONCE(buffer->subbuf_order, order);
7491
7492 /* Make sure all new buffers are allocated, before deleting the old ones */
7493 for_each_buffer_cpu(buffer, cpu) {
7494
7495 if (!cpumask_test_cpu(cpu, buffer->cpumask))
7496 continue;
7497
7498 cpu_buffer = buffer->buffers[cpu];
7499
7500 if (atomic_read(&cpu_buffer->resize_disabled)) {
7501 err = -EBUSY;
7502 goto error;
7503 }
7504
7505 /* Update the number of pages to match the new size */
7506 nr_pages = old_capacity * buffer->buffers[cpu]->nr_pages;
7507 nr_pages = DIV_ROUND_UP(nr_pages, rb_subbuf_capacity(buffer));
7508
7509 /* we need a minimum of two pages */
7510 if (nr_pages < 2)
7511 nr_pages = 2;
7512
7513 cpu_buffer->nr_pages_to_update = nr_pages;
7514
7515 /* Include the reader page */
7516 nr_pages++;
7517
7518 /* Allocate the new size buffer */
7519 INIT_LIST_HEAD(&cpu_buffer->new_pages);
7520 if (__rb_allocate_pages(cpu_buffer, nr_pages,
7521 &cpu_buffer->new_pages)) {
7522 /* not enough memory for new pages */
7523 err = -ENOMEM;
7524 goto error;
7525 }
7526 }
7527
7528 for_each_buffer_cpu(buffer, cpu) {
7529 struct buffer_data_read_page old_free_data_page;
7530 struct list_head old_pages;
7531 unsigned long flags;
7532
7533 if (!cpumask_test_cpu(cpu, buffer->cpumask))
7534 continue;
7535
7536 cpu_buffer = buffer->buffers[cpu];
7537
7538 raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
7539
7540 /* Clear the head bit to make the link list normal to read */
7541 rb_head_page_deactivate(cpu_buffer);
7542
7543 /*
7544 * Collect buffers from the cpu_buffer pages list and the
7545 * reader_page on old_pages, so they can be freed later when not
7546 * under a spinlock. The pages list is a linked list with no
7547 * head, adding old_pages turns it into a regular list with
7548 * old_pages being the head.
7549 */
7550 list_add(&old_pages, cpu_buffer->pages);
7551 list_add(&cpu_buffer->reader_page->list, &old_pages);
7552
7553 /* One page was allocated for the reader page */
7554 cpu_buffer->reader_page = list_entry(cpu_buffer->new_pages.next,
7555 struct buffer_page, list);
7556 list_del_init(&cpu_buffer->reader_page->list);
7557
7558 /* Install the new pages, remove the head from the list */
7559 cpu_buffer->pages = cpu_buffer->new_pages.next;
7560 list_del_init(&cpu_buffer->new_pages);
7561 cpu_buffer->cnt++;
7562
7563 cpu_buffer->head_page
7564 = list_entry(cpu_buffer->pages, struct buffer_page, list);
7565 cpu_buffer->tail_page = cpu_buffer->commit_page = cpu_buffer->head_page;
7566
7567 cpu_buffer->nr_pages = cpu_buffer->nr_pages_to_update;
7568 cpu_buffer->nr_pages_to_update = 0;
7569
7570 arch_spin_lock(&cpu_buffer->lock);
7571 old_free_data_page = cpu_buffer->free_page;
7572 cpu_buffer->free_page.data = NULL;
7573 arch_spin_unlock(&cpu_buffer->lock);
7574
7575 rb_head_page_activate(cpu_buffer);
7576
7577 raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
7578
7579 /* Free old sub buffers */
7580 list_for_each_entry_safe(bpage, tmp, &old_pages, list) {
7581 list_del_init(&bpage->list);
7582 free_buffer_page(bpage);
7583 }
7584 free_pages((unsigned long)old_free_data_page.data, old_free_data_page.order);
7585
7586 rb_check_pages(cpu_buffer);
7587 }
7588
7589 atomic_dec(&buffer->record_disabled);
7590
7591 return 0;
7592
7593 error:
7594 WRITE_ONCE(buffer->subbuf_order, old_order);
7595
7596 atomic_dec(&buffer->record_disabled);
7597
7598 for_each_buffer_cpu(buffer, cpu) {
7599 cpu_buffer = buffer->buffers[cpu];
7600
7601 if (!cpu_buffer->nr_pages_to_update)
7602 continue;
7603
7604 list_for_each_entry_safe(bpage, tmp, &cpu_buffer->new_pages, list) {
7605 list_del_init(&bpage->list);
7606 free_buffer_page(bpage);
7607 }
7608 }
7609
7610 return err;
7611 }
7612 EXPORT_SYMBOL_GPL(ring_buffer_subbuf_order_set);
7613
7614 static int rb_alloc_meta_page(struct ring_buffer_per_cpu *cpu_buffer)
7615 {
7616 struct page *page;
7617
7618 if (cpu_buffer->meta_page)
7619 return 0;
7620
7621 page = alloc_page(GFP_USER | __GFP_ZERO);
7622 if (!page)
7623 return -ENOMEM;
7624
7625 cpu_buffer->meta_page = page_to_virt(page);
7626
7627 return 0;
7628 }
7629
7630 static void rb_free_meta_page(struct ring_buffer_per_cpu *cpu_buffer)
7631 {
7632 unsigned long addr = (unsigned long)cpu_buffer->meta_page;
7633
7634 free_page(addr);
7635 cpu_buffer->meta_page = NULL;
7636 }
7637
7638 static void rb_setup_ids_meta_page(struct ring_buffer_per_cpu *cpu_buffer,
7639 struct buffer_page **subbuf_ids)
7640 {
7641 struct trace_buffer_meta *meta = cpu_buffer->meta_page;
7642 unsigned long nr_subbufs = cpu_buffer->nr_pages + 1;
7643 struct buffer_page *first_subbuf, *subbuf;
7644 unsigned int cnt = 0;
7645 unsigned int id = 0;
7646
7647 id = rb_page_id(cpu_buffer, cpu_buffer->reader_page, id);
7648 subbuf_ids[id++] = cpu_buffer->reader_page;
7649 cnt++;
7650
7651 first_subbuf = subbuf = rb_set_head_page(cpu_buffer);
7652 do {
7653 id = rb_page_id(cpu_buffer, subbuf, id);
7654
7655 if (WARN_ON(id >= nr_subbufs))
7656 break;
7657
7658 subbuf_ids[id] = subbuf;
7659
7660 rb_inc_page(&subbuf);
7661 id++;
7662 cnt++;
7663 } while (subbuf != first_subbuf);
7664
7665 WARN_ON(cnt != nr_subbufs);
7666
7667 /* install subbuf ID to bpage translation */
7668 cpu_buffer->subbuf_ids = subbuf_ids;
7669
7670 meta->meta_struct_len = sizeof(*meta);
7671 meta->nr_subbufs = nr_subbufs;
7672 meta->subbuf_size = rb_subbuf_size(cpu_buffer->buffer);
7673 meta->meta_page_size = meta->subbuf_size;
7674
7675 rb_update_meta_page(cpu_buffer);
7676 }
7677
7678 static struct ring_buffer_per_cpu *
7679 rb_get_mapped_buffer(struct trace_buffer *buffer, int cpu)
7680 {
7681 struct ring_buffer_per_cpu *cpu_buffer;
7682
7683 if (!cpumask_test_cpu(cpu, buffer->cpumask))
7684 return ERR_PTR(-EINVAL);
7685
7686 cpu_buffer = buffer->buffers[cpu];
7687
7688 mutex_lock(&cpu_buffer->mapping_lock);
7689
7690 if (!cpu_buffer->user_mapped) {
7691 mutex_unlock(&cpu_buffer->mapping_lock);
7692 return ERR_PTR(-ENODEV);
7693 }
7694
7695 return cpu_buffer;
7696 }
7697
7698 static void rb_put_mapped_buffer(struct ring_buffer_per_cpu *cpu_buffer)
7699 {
7700 mutex_unlock(&cpu_buffer->mapping_lock);
7701 }
7702
7703 /*
7704 * Fast-path for rb_buffer_(un)map(). Called whenever the meta-page doesn't need
7705 * to be set-up or torn-down.
7706 */
7707 static int __rb_inc_dec_mapped(struct ring_buffer_per_cpu *cpu_buffer,
7708 bool inc)
7709 {
7710 unsigned long flags;
7711
7712 lockdep_assert_held(&cpu_buffer->mapping_lock);
7713
7714 if (inc && cpu_buffer->user_mapped == UINT_MAX)
7715 return -EBUSY;
7716
7717 if (WARN_ON(!inc && cpu_buffer->user_mapped == 0))
7718 return -EINVAL;
7719
7720 mutex_lock(&cpu_buffer->buffer->mutex);
7721 raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
7722
7723 if (inc)
7724 cpu_buffer->user_mapped++;
7725 else
7726 cpu_buffer->user_mapped--;
7727
7728 raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
7729 mutex_unlock(&cpu_buffer->buffer->mutex);
7730
7731 return 0;
7732 }
7733
7734 /*
7735 * +--------------+ pgoff == 0
7736 * | meta page |
7737 * +--------------+ pgoff == 1
7738 * | subbuffer 0 |
7739 * | |
7740 * +--------------+ pgoff == (1 + (1 << subbuf_order))
7741 * | subbuffer 1 |
7742 * | |
7743 * ...
7744 */
7745 #ifdef CONFIG_MMU
7746 static int __rb_map_vma(struct ring_buffer_per_cpu *cpu_buffer,
7747 struct vm_area_struct *vma)
7748 {
7749 unsigned long nr_subbufs, nr_pages, nr_vma_pages;
7750 pgoff_t pgoff = vma_start_pgoff(vma);
7751 unsigned int subbuf_pages, subbuf_order;
7752 struct page **pages __free(kfree) = NULL;
7753 int p = 0, s = 0;
7754 int err;
7755
7756 /* Refuse MP_PRIVATE or writable mappings */
7757 if (vma->vm_flags & VM_WRITE || vma->vm_flags & VM_EXEC ||
7758 !(vma->vm_flags & VM_MAYSHARE))
7759 return -EPERM;
7760
7761 subbuf_order = cpu_buffer->buffer->subbuf_order;
7762 subbuf_pages = 1 << subbuf_order;
7763
7764 if (subbuf_order && pgoff % subbuf_pages)
7765 return -EINVAL;
7766
7767 /*
7768 * Make sure the mapping cannot become writable later. Also tell the VM
7769 * to not touch these pages (VM_DONTCOPY | VM_DONTEXPAND).
7770 */
7771 vm_flags_mod(vma, VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP,
7772 VM_MAYWRITE);
7773
7774 lockdep_assert_held(&cpu_buffer->mapping_lock);
7775
7776 nr_subbufs = cpu_buffer->nr_pages + 1; /* + reader-subbuf */
7777 nr_pages = ((nr_subbufs + 1) << subbuf_order); /* + meta-page */
7778 if (nr_pages <= pgoff)
7779 return -EINVAL;
7780
7781 nr_pages -= pgoff;
7782
7783 nr_vma_pages = vma_pages(vma);
7784 if (!nr_vma_pages || nr_vma_pages > nr_pages)
7785 return -EINVAL;
7786
7787 nr_pages = nr_vma_pages;
7788
7789 pages = kzalloc_objs(*pages, nr_pages);
7790 if (!pages)
7791 return -ENOMEM;
7792
7793 if (!pgoff) {
7794 unsigned long meta_page_padding;
7795
7796 pages[p++] = virt_to_page(cpu_buffer->meta_page);
7797
7798 /*
7799 * Pad with the zero-page to align the meta-page with the
7800 * sub-buffers.
7801 */
7802 meta_page_padding = subbuf_pages - 1;
7803 while (meta_page_padding-- && p < nr_pages) {
7804 unsigned long __maybe_unused zero_addr =
7805 vma->vm_start + (PAGE_SIZE * p);
7806
7807 pages[p++] = ZERO_PAGE(zero_addr);
7808 }
7809 } else {
7810 /* Skip the meta-page */
7811 pgoff -= subbuf_pages;
7812
7813 s += pgoff / subbuf_pages;
7814 }
7815
7816 while (p < nr_pages) {
7817 struct buffer_page *subbuf;
7818 struct page *page;
7819 int off = 0;
7820
7821 if (WARN_ON_ONCE(s >= nr_subbufs))
7822 return -EINVAL;
7823
7824 subbuf = cpu_buffer->subbuf_ids[s];
7825 page = virt_to_page((void *)subbuf->page);
7826
7827 for (; off < (1 << (subbuf_order)); off++, page++) {
7828 if (p >= nr_pages)
7829 break;
7830
7831 pages[p++] = page;
7832 }
7833 s++;
7834 }
7835
7836 err = vm_insert_pages(vma, vma->vm_start, pages, &nr_pages);
7837
7838 return err;
7839 }
7840 #else
7841 static int __rb_map_vma(struct ring_buffer_per_cpu *cpu_buffer,
7842 struct vm_area_struct *vma)
7843 {
7844 return -EOPNOTSUPP;
7845 }
7846 #endif
7847
7848 int ring_buffer_map(struct trace_buffer *buffer, int cpu,
7849 struct vm_area_struct *vma)
7850 {
7851 struct ring_buffer_per_cpu *cpu_buffer;
7852 struct buffer_page **subbuf_ids;
7853 unsigned long flags;
7854 int err;
7855
7856 if (!cpumask_test_cpu(cpu, buffer->cpumask) || buffer->remote)
7857 return -EINVAL;
7858
7859 cpu_buffer = buffer->buffers[cpu];
7860
7861 guard(mutex)(&cpu_buffer->mapping_lock);
7862
7863 if (cpu_buffer->user_mapped) {
7864 err = __rb_map_vma(cpu_buffer, vma);
7865 if (!err)
7866 err = __rb_inc_dec_mapped(cpu_buffer, true);
7867 return err;
7868 }
7869
7870 /* prevent another thread from changing buffer/sub-buffer sizes */
7871 guard(mutex)(&buffer->mutex);
7872
7873 if (cpu_buffer->nr_pages > rb_static_max_pages())
7874 return -E2BIG;
7875
7876 err = rb_alloc_meta_page(cpu_buffer);
7877 if (err)
7878 return err;
7879
7880 /* subbuf_ids includes the reader while nr_pages does not */
7881 subbuf_ids = kcalloc(cpu_buffer->nr_pages + 1, sizeof(*subbuf_ids), GFP_KERNEL);
7882 if (!subbuf_ids) {
7883 rb_free_meta_page(cpu_buffer);
7884 return -ENOMEM;
7885 }
7886
7887 atomic_inc(&cpu_buffer->resize_disabled);
7888
7889 /*
7890 * Lock all readers to block any subbuf swap until the subbuf IDs are
7891 * assigned.
7892 */
7893 raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
7894 rb_setup_ids_meta_page(cpu_buffer, subbuf_ids);
7895
7896 raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
7897
7898 err = __rb_map_vma(cpu_buffer, vma);
7899 if (!err) {
7900 raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
7901 /* This is the first time it is mapped by user */
7902 cpu_buffer->user_mapped = 1;
7903 raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
7904 } else {
7905 kfree(cpu_buffer->subbuf_ids);
7906 cpu_buffer->subbuf_ids = NULL;
7907 rb_free_meta_page(cpu_buffer);
7908 atomic_dec(&cpu_buffer->resize_disabled);
7909 }
7910
7911 return err;
7912 }
7913
7914 /*
7915 * This is called when a VMA is duplicated (e.g., on fork()) to increment
7916 * the user_mapped counter without remapping pages.
7917 */
7918 void ring_buffer_map_dup(struct trace_buffer *buffer, int cpu)
7919 {
7920 struct ring_buffer_per_cpu *cpu_buffer;
7921
7922 if (WARN_ON(!cpumask_test_cpu(cpu, buffer->cpumask)))
7923 return;
7924
7925 cpu_buffer = buffer->buffers[cpu];
7926
7927 guard(mutex)(&cpu_buffer->mapping_lock);
7928
7929 if (cpu_buffer->user_mapped)
7930 __rb_inc_dec_mapped(cpu_buffer, true);
7931 else
7932 WARN(1, "Unexpected buffer stat, it should be mapped");
7933 }
7934
7935 int ring_buffer_unmap(struct trace_buffer *buffer, int cpu)
7936 {
7937 struct ring_buffer_per_cpu *cpu_buffer;
7938 unsigned long flags;
7939
7940 if (!cpumask_test_cpu(cpu, buffer->cpumask))
7941 return -EINVAL;
7942
7943 cpu_buffer = buffer->buffers[cpu];
7944
7945 guard(mutex)(&cpu_buffer->mapping_lock);
7946
7947 if (!cpu_buffer->user_mapped) {
7948 return -ENODEV;
7949 } else if (cpu_buffer->user_mapped > 1) {
7950 __rb_inc_dec_mapped(cpu_buffer, false);
7951 return 0;
7952 }
7953
7954 guard(mutex)(&buffer->mutex);
7955 raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
7956
7957 /* This is the last user space mapping */
7958 cpu_buffer->user_mapped = 0;
7959
7960 raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
7961
7962 kfree(cpu_buffer->subbuf_ids);
7963 cpu_buffer->subbuf_ids = NULL;
7964 rb_free_meta_page(cpu_buffer);
7965 atomic_dec(&cpu_buffer->resize_disabled);
7966
7967 return 0;
7968 }
7969
7970 int ring_buffer_map_get_reader(struct trace_buffer *buffer, int cpu)
7971 {
7972 struct ring_buffer_per_cpu *cpu_buffer;
7973 struct buffer_page *reader;
7974 unsigned long missed_events;
7975 unsigned long reader_size;
7976 unsigned long flags;
7977
7978 cpu_buffer = rb_get_mapped_buffer(buffer, cpu);
7979 if (IS_ERR(cpu_buffer))
7980 return (int)PTR_ERR(cpu_buffer);
7981
7982 raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
7983
7984 consume:
7985 if (rb_per_cpu_empty(cpu_buffer))
7986 goto out;
7987
7988 reader_size = rb_page_size(cpu_buffer->reader_page);
7989
7990 /*
7991 * There are data to be read on the current reader page, we can
7992 * return to the caller. But before that, we assume the latter will read
7993 * everything. Let's update the kernel reader accordingly.
7994 */
7995 if (cpu_buffer->reader_page->read < reader_size) {
7996 while (cpu_buffer->reader_page->read < reader_size)
7997 rb_advance_reader(cpu_buffer);
7998 goto out;
7999 }
8000
8001 reader = rb_get_reader_page(cpu_buffer);
8002 if (!reader)
8003 goto out;
8004
8005 /* Check if any events were dropped */
8006 missed_events = cpu_buffer->lost_events;
8007
8008 if (missed_events) {
8009 if (cpu_buffer->reader_page != cpu_buffer->commit_page) {
8010 struct buffer_data_page *dpage = reader->page;
8011 unsigned int commit;
8012 /*
8013 * Use the real_end for the data size,
8014 * This gives us a chance to store the lost events
8015 * on the page.
8016 */
8017 if (reader->real_end)
8018 local_set(&dpage->commit, reader->real_end);
8019 /*
8020 * If there is room at the end of the page to save the
8021 * missed events, then record it there.
8022 */
8023 commit = rb_page_size(reader);
8024 if (rb_page_capacity(reader) - commit >= sizeof(missed_events)) {
8025 memcpy(&dpage->data[commit], &missed_events,
8026 sizeof(missed_events));
8027 local_add(RB_MISSED_STORED, &dpage->commit);
8028 }
8029 local_add(RB_MISSED_EVENTS, &dpage->commit);
8030 } else if (!WARN_ONCE(cpu_buffer->reader_page == cpu_buffer->tail_page,
8031 "Reader on commit with %ld missed events",
8032 missed_events)) {
8033 /*
8034 * There shouldn't be any missed events if the tail_page
8035 * is on the reader page. But if the tail page is not on the
8036 * reader page and the commit_page is, that would mean that
8037 * there's a commit_overrun (an interrupt preempted an
8038 * addition of an event and then filled the buffer
8039 * with new events). In this case it's not an
8040 * error, but it should still be reported.
8041 *
8042 * TODO: Add missed events to the page for user space to know.
8043 */
8044 pr_info("Ring buffer [%d] commit overrun lost %ld events at timestamp:%lld\n",
8045 cpu, missed_events, cpu_buffer->reader_page->page->time_stamp);
8046 }
8047 }
8048
8049 cpu_buffer->lost_events = 0;
8050
8051 goto consume;
8052
8053 out:
8054 /* Some archs do not have data cache coherency between kernel and user-space */
8055 flush_kernel_vmap_range(cpu_buffer->reader_page->page,
8056 rb_subbuf_size(buffer));
8057
8058 rb_update_meta_page(cpu_buffer);
8059
8060 raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
8061 rb_put_mapped_buffer(cpu_buffer);
8062
8063 return 0;
8064 }
8065
8066 static void rb_cpu_sync(void *data)
8067 {
8068 /* Not really needed, but documents what is happening */
8069 smp_rmb();
8070 }
8071
8072 /*
8073 * We only allocate new buffers, never free them if the CPU goes down.
8074 * If we were to free the buffer, then the user would lose any trace that was in
8075 * the buffer.
8076 */
8077 int trace_rb_cpu_prepare(unsigned int cpu, struct hlist_node *node)
8078 {
8079 struct trace_buffer *buffer;
8080 long nr_pages_same;
8081 int cpu_i;
8082 unsigned long nr_pages;
8083
8084 buffer = container_of(node, struct trace_buffer, node);
8085 if (cpumask_test_cpu(cpu, buffer->cpumask))
8086 return 0;
8087
8088 nr_pages = 0;
8089 nr_pages_same = 1;
8090 /* check if all cpu sizes are same */
8091 for_each_buffer_cpu(buffer, cpu_i) {
8092 /* fill in the size from first enabled cpu */
8093 if (nr_pages == 0)
8094 nr_pages = buffer->buffers[cpu_i]->nr_pages;
8095 if (nr_pages != buffer->buffers[cpu_i]->nr_pages) {
8096 nr_pages_same = 0;
8097 break;
8098 }
8099 }
8100 /* allocate minimum pages, user can later expand it */
8101 if (!nr_pages_same)
8102 nr_pages = 2;
8103 buffer->buffers[cpu] =
8104 rb_allocate_cpu_buffer(buffer, nr_pages, cpu);
8105 if (!buffer->buffers[cpu]) {
8106 WARN(1, "failed to allocate ring buffer on CPU %u\n",
8107 cpu);
8108 return -ENOMEM;
8109 }
8110
8111 /*
8112 * Ensure trace_buffer readers observe the newly allocated
8113 * ring_buffer_per_cpu before they check the cpumask. Instead of using a
8114 * read barrier for all readers, send an IPI.
8115 */
8116 if (unlikely(system_state == SYSTEM_RUNNING)) {
8117 on_each_cpu(rb_cpu_sync, NULL, 1);
8118 /* Not really needed, but documents what is happening */
8119 smp_wmb();
8120 }
8121
8122 cpumask_set_cpu(cpu, buffer->cpumask);
8123 return 0;
8124 }
8125
8126 #ifdef CONFIG_RING_BUFFER_STARTUP_TEST
8127 /*
8128 * This is a basic integrity check of the ring buffer.
8129 * Late in the boot cycle this test will run when configured in.
8130 * It will kick off a thread per CPU that will go into a loop
8131 * writing to the per cpu ring buffer various sizes of data.
8132 * Some of the data will be large items, some small.
8133 *
8134 * Another thread is created that goes into a spin, sending out
8135 * IPIs to the other CPUs to also write into the ring buffer.
8136 * this is to test the nesting ability of the buffer.
8137 *
8138 * Basic stats are recorded and reported. If something in the
8139 * ring buffer should happen that's not expected, a big warning
8140 * is displayed and all ring buffers are disabled.
8141 */
8142 static struct task_struct *rb_threads[NR_CPUS] __initdata;
8143
8144 struct rb_test_data {
8145 struct trace_buffer *buffer;
8146 unsigned long events;
8147 unsigned long bytes_written;
8148 unsigned long bytes_alloc;
8149 unsigned long bytes_dropped;
8150 unsigned long events_nested;
8151 unsigned long bytes_written_nested;
8152 unsigned long bytes_alloc_nested;
8153 unsigned long bytes_dropped_nested;
8154 int min_size_nested;
8155 int max_size_nested;
8156 int max_size;
8157 int min_size;
8158 int cpu;
8159 int cnt;
8160 };
8161
8162 static struct rb_test_data rb_data[NR_CPUS] __initdata;
8163
8164 /* 1 meg per cpu */
8165 #define RB_TEST_BUFFER_SIZE 1048576
8166
8167 static char rb_string[] __initdata =
8168 "abcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()?+\\"
8169 "?+|:';\",.<>/?abcdefghijklmnopqrstuvwxyz1234567890"
8170 "!@#$%^&*()?+\\?+|:';\",.<>/?abcdefghijklmnopqrstuv";
8171
8172 static bool rb_test_started __initdata;
8173
8174 struct rb_item {
8175 int size;
8176 char str[];
8177 };
8178
8179 static __init int rb_write_something(struct rb_test_data *data, bool nested)
8180 {
8181 struct ring_buffer_event *event;
8182 struct rb_item *item;
8183 bool started;
8184 int event_len;
8185 int size;
8186 int len;
8187 int cnt;
8188
8189 /* Have nested writes different that what is written */
8190 cnt = data->cnt + (nested ? 27 : 0);
8191
8192 /* Multiply cnt by ~e, to make some unique increment */
8193 size = (cnt * 68 / 25) % (sizeof(rb_string) - 1);
8194
8195 len = size + sizeof(struct rb_item);
8196
8197 started = rb_test_started;
8198 /* read rb_test_started before checking buffer enabled */
8199 smp_rmb();
8200
8201 event = ring_buffer_lock_reserve(data->buffer, len);
8202 if (!event) {
8203 /* Ignore dropped events before test starts. */
8204 if (started) {
8205 if (nested)
8206 data->bytes_dropped_nested += len;
8207 else
8208 data->bytes_dropped += len;
8209 }
8210 return len;
8211 }
8212
8213 event_len = ring_buffer_event_length(event);
8214
8215 if (RB_WARN_ON(data->buffer, event_len < len))
8216 goto out;
8217
8218 item = ring_buffer_event_data(event);
8219 item->size = size;
8220 memcpy(item->str, rb_string, size);
8221
8222 if (nested) {
8223 data->bytes_alloc_nested += event_len;
8224 data->bytes_written_nested += len;
8225 data->events_nested++;
8226 if (!data->min_size_nested || len < data->min_size_nested)
8227 data->min_size_nested = len;
8228 if (len > data->max_size_nested)
8229 data->max_size_nested = len;
8230 } else {
8231 data->bytes_alloc += event_len;
8232 data->bytes_written += len;
8233 data->events++;
8234 if (!data->min_size || len < data->min_size)
8235 data->max_size = len;
8236 if (len > data->max_size)
8237 data->max_size = len;
8238 }
8239
8240 out:
8241 ring_buffer_unlock_commit(data->buffer);
8242
8243 return 0;
8244 }
8245
8246 static __init int rb_test(void *arg)
8247 {
8248 struct rb_test_data *data = arg;
8249
8250 while (!kthread_should_stop()) {
8251 rb_write_something(data, false);
8252 data->cnt++;
8253
8254 set_current_state(TASK_INTERRUPTIBLE);
8255 /* Now sleep between a min of 100-300us and a max of 1ms */
8256 usleep_range(((data->cnt % 3) + 1) * 100, 1000);
8257 }
8258
8259 return 0;
8260 }
8261
8262 static __init void rb_ipi(void *ignore)
8263 {
8264 struct rb_test_data *data;
8265 int cpu = smp_processor_id();
8266
8267 data = &rb_data[cpu];
8268 rb_write_something(data, true);
8269 }
8270
8271 static __init int rb_hammer_test(void *arg)
8272 {
8273 while (!kthread_should_stop()) {
8274
8275 /* Send an IPI to all cpus to write data! */
8276 smp_call_function(rb_ipi, NULL, 1);
8277 /* No sleep, but for non preempt, let others run */
8278 schedule();
8279 }
8280
8281 return 0;
8282 }
8283
8284 static __init int test_ringbuffer(void)
8285 {
8286 struct task_struct *rb_hammer;
8287 struct trace_buffer *buffer;
8288 int cpu;
8289 int ret = 0;
8290
8291 if (security_locked_down(LOCKDOWN_TRACEFS)) {
8292 pr_warn("Lockdown is enabled, skipping ring buffer tests\n");
8293 return 0;
8294 }
8295
8296 pr_info("Running ring buffer tests...\n");
8297
8298 buffer = ring_buffer_alloc(RB_TEST_BUFFER_SIZE, RB_FL_OVERWRITE);
8299 if (WARN_ON(!buffer))
8300 return 0;
8301
8302 /* Disable buffer so that threads can't write to it yet */
8303 ring_buffer_record_off(buffer);
8304
8305 for_each_online_cpu(cpu) {
8306 rb_data[cpu].buffer = buffer;
8307 rb_data[cpu].cpu = cpu;
8308 rb_data[cpu].cnt = cpu;
8309 rb_threads[cpu] = kthread_run_on_cpu(rb_test, &rb_data[cpu],
8310 cpu, "rbtester/%u");
8311 if (WARN_ON(IS_ERR(rb_threads[cpu]))) {
8312 pr_cont("FAILED\n");
8313 ret = PTR_ERR(rb_threads[cpu]);
8314 goto out_free;
8315 }
8316 }
8317
8318 /* Now create the rb hammer! */
8319 rb_hammer = kthread_run(rb_hammer_test, NULL, "rbhammer");
8320 if (WARN_ON(IS_ERR(rb_hammer))) {
8321 pr_cont("FAILED\n");
8322 ret = PTR_ERR(rb_hammer);
8323 goto out_free;
8324 }
8325
8326 ring_buffer_record_on(buffer);
8327 /*
8328 * Show buffer is enabled before setting rb_test_started.
8329 * Yes there's a small race window where events could be
8330 * dropped and the thread won't catch it. But when a ring
8331 * buffer gets enabled, there will always be some kind of
8332 * delay before other CPUs see it. Thus, we don't care about
8333 * those dropped events. We care about events dropped after
8334 * the threads see that the buffer is active.
8335 */
8336 smp_wmb();
8337 rb_test_started = true;
8338
8339 set_current_state(TASK_INTERRUPTIBLE);
8340 /* Just run for 10 seconds */
8341 schedule_timeout(10 * HZ);
8342
8343 kthread_stop(rb_hammer);
8344
8345 out_free:
8346 for_each_online_cpu(cpu) {
8347 if (IS_ERR_OR_NULL(rb_threads[cpu]))
8348 break;
8349 kthread_stop(rb_threads[cpu]);
8350 }
8351 if (ret) {
8352 ring_buffer_free(buffer);
8353 return ret;
8354 }
8355
8356 /* Report! */
8357 pr_info("finished\n");
8358 for_each_online_cpu(cpu) {
8359 struct ring_buffer_event *event;
8360 struct rb_test_data *data = &rb_data[cpu];
8361 struct rb_item *item;
8362 unsigned long total_events;
8363 unsigned long total_dropped;
8364 unsigned long total_written;
8365 unsigned long total_alloc;
8366 unsigned long total_read = 0;
8367 unsigned long total_size = 0;
8368 unsigned long total_len = 0;
8369 unsigned long total_lost = 0;
8370 unsigned long lost;
8371 int big_event_size;
8372 int small_event_size;
8373
8374 ret = -1;
8375
8376 total_events = data->events + data->events_nested;
8377 total_written = data->bytes_written + data->bytes_written_nested;
8378 total_alloc = data->bytes_alloc + data->bytes_alloc_nested;
8379 total_dropped = data->bytes_dropped + data->bytes_dropped_nested;
8380
8381 big_event_size = data->max_size + data->max_size_nested;
8382 small_event_size = data->min_size + data->min_size_nested;
8383
8384 pr_info("CPU %d:\n", cpu);
8385 pr_info(" events: %ld\n", total_events);
8386 pr_info(" dropped bytes: %ld\n", total_dropped);
8387 pr_info(" alloced bytes: %ld\n", total_alloc);
8388 pr_info(" written bytes: %ld\n", total_written);
8389 pr_info(" biggest event: %d\n", big_event_size);
8390 pr_info(" smallest event: %d\n", small_event_size);
8391
8392 if (RB_WARN_ON(buffer, total_dropped))
8393 break;
8394
8395 ret = 0;
8396
8397 while ((event = ring_buffer_consume(buffer, cpu, NULL, &lost))) {
8398 total_lost += lost;
8399 item = ring_buffer_event_data(event);
8400 total_len += ring_buffer_event_length(event);
8401 total_size += item->size + sizeof(struct rb_item);
8402 if (memcmp(&item->str[0], rb_string, item->size) != 0) {
8403 pr_info("FAILED!\n");
8404 pr_info("buffer had: %.*s\n", item->size, item->str);
8405 pr_info("expected: %.*s\n", item->size, rb_string);
8406 RB_WARN_ON(buffer, 1);
8407 ret = -1;
8408 break;
8409 }
8410 total_read++;
8411 }
8412 if (ret)
8413 break;
8414
8415 ret = -1;
8416
8417 pr_info(" read events: %ld\n", total_read);
8418 pr_info(" lost events: %ld\n", total_lost);
8419 pr_info(" total events: %ld\n", total_lost + total_read);
8420 pr_info(" recorded len bytes: %ld\n", total_len);
8421 pr_info(" recorded size bytes: %ld\n", total_size);
8422 if (total_lost) {
8423 pr_info(" With dropped events, record len and size may not match\n"
8424 " alloced and written from above\n");
8425 } else {
8426 if (RB_WARN_ON(buffer, total_len != total_alloc ||
8427 total_size != total_written))
8428 break;
8429 }
8430 if (RB_WARN_ON(buffer, total_lost + total_read != total_events))
8431 break;
8432
8433 ret = 0;
8434 }
8435 if (!ret)
8436 pr_info("Ring buffer PASSED!\n");
8437
8438 ring_buffer_free(buffer);
8439 return 0;
8440 }
8441
8442 late_initcall(test_ringbuffer);
8443 #endif /* CONFIG_RING_BUFFER_STARTUP_TEST */