at commit 3f23cae0

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;
3634
3635 subbuf_array = (void *)meta + sizeof(int) * meta->nr_subbufs;
3636 subbuf_array = (void *)ALIGN((unsigned long)subbuf_array, meta->subbuf_size);
3637 return (subbuf - subbuf_array) / meta->subbuf_size;
3638 }
3639
3640 static void rb_update_meta_head(struct ring_buffer_per_cpu *cpu_buffer,
3641 struct buffer_page *next_page)
3642 {
3643 struct ring_buffer_cpu_meta *meta = cpu_buffer->ring_meta;
3644 unsigned long old_head = (unsigned long)next_page->page;
3645 unsigned long new_head;
3646
3647 rb_inc_page(&next_page);
3648 new_head = (unsigned long)next_page->page;
3649
3650 /*
3651 * Only move it forward once, if something else came in and
3652 * moved it forward, then we don't want to touch it.
3653 */
3654 (void)cmpxchg(&meta->head_buffer, old_head, new_head);
3655 }
3656
3657 static void rb_update_meta_reader(struct ring_buffer_per_cpu *cpu_buffer,
3658 struct buffer_page *reader)
3659 {
3660 struct ring_buffer_cpu_meta *meta = cpu_buffer->ring_meta;
3661 void *old_reader = cpu_buffer->reader_page->page;
3662 void *new_reader = reader->page;
3663 int id;
3664
3665 id = reader->id;
3666 cpu_buffer->reader_page->id = id;
3667 reader->id = 0;
3668
3669 meta->buffers[0] = rb_meta_subbuf_idx(meta, new_reader);
3670 meta->buffers[id] = rb_meta_subbuf_idx(meta, old_reader);
3671
3672 /* The head pointer is the one after the reader */
3673 rb_update_meta_head(cpu_buffer, reader);
3674 }
3675
3676 /*
3677 * rb_handle_head_page - writer hit the head page
3678 *
3679 * Returns: +1 to retry page
3680 * 0 to continue
3681 * -1 on error
3682 */
3683 static int
3684 rb_handle_head_page(struct ring_buffer_per_cpu *cpu_buffer,
3685 struct buffer_page *tail_page,
3686 struct buffer_page *next_page)
3687 {
3688 struct buffer_page *new_head;
3689 int entries;
3690 int type;
3691 int ret;
3692
3693 entries = rb_page_entries(next_page);
3694
3695 /*
3696 * The hard part is here. We need to move the head
3697 * forward, and protect against both readers on
3698 * other CPUs and writers coming in via interrupts.
3699 */
3700 type = rb_head_page_set_update(cpu_buffer, next_page, tail_page,
3701 RB_PAGE_HEAD);
3702
3703 /*
3704 * type can be one of four:
3705 * NORMAL - an interrupt already moved it for us
3706 * HEAD - we are the first to get here.
3707 * UPDATE - we are the interrupt interrupting
3708 * a current move.
3709 * MOVED - a reader on another CPU moved the next
3710 * pointer to its reader page. Give up
3711 * and try again.
3712 */
3713
3714 switch (type) {
3715 case RB_PAGE_HEAD:
3716 /*
3717 * We changed the head to UPDATE, thus
3718 * it is our responsibility to update
3719 * the counters.
3720 */
3721 local_add(entries, &cpu_buffer->overrun);
3722 local_sub(rb_page_commit(next_page), &cpu_buffer->entries_bytes);
3723 local_inc(&cpu_buffer->pages_lost);
3724
3725 if (cpu_buffer->ring_meta)
3726 rb_update_meta_head(cpu_buffer, next_page);
3727 /*
3728 * The entries will be zeroed out when we move the
3729 * tail page.
3730 */
3731
3732 /* still more to do */
3733 break;
3734
3735 case RB_PAGE_UPDATE:
3736 /*
3737 * This is an interrupt that interrupt the
3738 * previous update. Still more to do.
3739 */
3740 break;
3741 case RB_PAGE_NORMAL:
3742 /*
3743 * An interrupt came in before the update
3744 * and processed this for us.
3745 * Nothing left to do.
3746 */
3747 return 1;
3748 case RB_PAGE_MOVED:
3749 /*
3750 * The reader is on another CPU and just did
3751 * a swap with our next_page.
3752 * Try again.
3753 */
3754 return 1;
3755 default:
3756 RB_WARN_ON(cpu_buffer, 1); /* WTF??? */
3757 return -1;
3758 }
3759
3760 /*
3761 * Now that we are here, the old head pointer is
3762 * set to UPDATE. This will keep the reader from
3763 * swapping the head page with the reader page.
3764 * The reader (on another CPU) will spin till
3765 * we are finished.
3766 *
3767 * We just need to protect against interrupts
3768 * doing the job. We will set the next pointer
3769 * to HEAD. After that, we set the old pointer
3770 * to NORMAL, but only if it was HEAD before.
3771 * otherwise we are an interrupt, and only
3772 * want the outer most commit to reset it.
3773 */
3774 new_head = next_page;
3775 rb_inc_page(&new_head);
3776
3777 ret = rb_head_page_set_head(cpu_buffer, new_head, next_page,
3778 RB_PAGE_NORMAL);
3779
3780 /*
3781 * Valid returns are:
3782 * HEAD - an interrupt came in and already set it.
3783 * NORMAL - One of two things:
3784 * 1) We really set it.
3785 * 2) A bunch of interrupts came in and moved
3786 * the page forward again.
3787 */
3788 switch (ret) {
3789 case RB_PAGE_HEAD:
3790 case RB_PAGE_NORMAL:
3791 /* OK */
3792 break;
3793 default:
3794 RB_WARN_ON(cpu_buffer, 1);
3795 return -1;
3796 }
3797
3798 /*
3799 * It is possible that an interrupt came in,
3800 * set the head up, then more interrupts came in
3801 * and moved it again. When we get back here,
3802 * the page would have been set to NORMAL but we
3803 * just set it back to HEAD.
3804 *
3805 * How do you detect this? Well, if that happened
3806 * the tail page would have moved.
3807 */
3808 if (ret == RB_PAGE_NORMAL) {
3809 struct buffer_page *buffer_tail_page;
3810
3811 buffer_tail_page = READ_ONCE(cpu_buffer->tail_page);
3812 /*
3813 * If the tail had moved passed next, then we need
3814 * to reset the pointer.
3815 */
3816 if (buffer_tail_page != tail_page &&
3817 buffer_tail_page != next_page)
3818 rb_head_page_set_normal(cpu_buffer, new_head,
3819 next_page,
3820 RB_PAGE_HEAD);
3821 }
3822
3823 /*
3824 * If this was the outer most commit (the one that
3825 * changed the original pointer from HEAD to UPDATE),
3826 * then it is up to us to reset it to NORMAL.
3827 */
3828 if (type == RB_PAGE_HEAD) {
3829 ret = rb_head_page_set_normal(cpu_buffer, next_page,
3830 tail_page,
3831 RB_PAGE_UPDATE);
3832 if (RB_WARN_ON(cpu_buffer,
3833 ret != RB_PAGE_UPDATE))
3834 return -1;
3835 }
3836
3837 return 0;
3838 }
3839
3840 static inline void
3841 rb_reset_tail(struct ring_buffer_per_cpu *cpu_buffer,
3842 unsigned long tail, struct rb_event_info *info)
3843 {
3844 struct buffer_page *tail_page = info->tail_page;
3845 unsigned long bsize = rb_page_capacity(tail_page);
3846 struct ring_buffer_event *event;
3847 unsigned long length = info->length;
3848
3849 /*
3850 * Only the event that crossed the page boundary
3851 * must fill the old tail_page with padding.
3852 */
3853 if (tail >= bsize) {
3854 /*
3855 * If the page was filled, then we still need
3856 * to update the real_end. Reset it to zero
3857 * and the reader will ignore it.
3858 */
3859 if (tail == bsize)
3860 tail_page->real_end = 0;
3861
3862 local_sub(length, &tail_page->write);
3863 return;
3864 }
3865
3866 event = __rb_page_index(tail_page, tail);
3867
3868 /*
3869 * Save the original length to the meta data.
3870 * This will be used by the reader to add lost event
3871 * counter.
3872 */
3873 tail_page->real_end = tail;
3874
3875 /*
3876 * If this event is bigger than the minimum size, then
3877 * we need to be careful that we don't subtract the
3878 * write counter enough to allow another writer to slip
3879 * in on this page.
3880 * We put in a discarded commit instead, to make sure
3881 * that this space is not used again, and this space will
3882 * not be accounted into 'entries_bytes'.
3883 *
3884 * If we are less than the minimum size, we don't need to
3885 * worry about it.
3886 */
3887 if (tail > (bsize - RB_EVNT_MIN_SIZE)) {
3888 /* No room for any events */
3889
3890 /* Mark the rest of the page with padding */
3891 rb_event_set_padding(event);
3892
3893 /* Make sure the padding is visible before the write update */
3894 smp_wmb();
3895
3896 /* Set the write back to the previous setting */
3897 local_sub(length, &tail_page->write);
3898 return;
3899 }
3900
3901 /* Put in a discarded event */
3902 event->array[0] = (bsize - tail) - RB_EVNT_HDR_SIZE;
3903 event->type_len = RINGBUF_TYPE_PADDING;
3904 /* time delta must be non zero */
3905 event->time_delta = 1;
3906
3907 /* account for padding bytes */
3908 local_add(bsize - tail, &cpu_buffer->entries_bytes);
3909
3910 /* Make sure the padding is visible before the tail_page->write update */
3911 smp_wmb();
3912
3913 /* Set write to end of buffer */
3914 length = (tail + length) - bsize;
3915 local_sub(length, &tail_page->write);
3916 }
3917
3918 static inline void rb_end_commit(struct ring_buffer_per_cpu *cpu_buffer);
3919
3920 /*
3921 * This is the slow path, force gcc not to inline it.
3922 */
3923 static noinline struct ring_buffer_event *
3924 rb_move_tail(struct ring_buffer_per_cpu *cpu_buffer,
3925 unsigned long tail, struct rb_event_info *info)
3926 {
3927 struct buffer_page *tail_page = info->tail_page;
3928 struct buffer_page *commit_page = cpu_buffer->commit_page;
3929 struct trace_buffer *buffer = cpu_buffer->buffer;
3930 struct buffer_page *next_page;
3931 int ret;
3932
3933 next_page = tail_page;
3934
3935 rb_inc_page(&next_page);
3936
3937 /*
3938 * If for some reason, we had an interrupt storm that made
3939 * it all the way around the buffer, bail, and warn
3940 * about it.
3941 */
3942 if (unlikely(next_page == commit_page)) {
3943 local_inc(&cpu_buffer->commit_overrun);
3944 goto out_reset;
3945 }
3946
3947 /*
3948 * This is where the fun begins!
3949 *
3950 * We are fighting against races between a reader that
3951 * could be on another CPU trying to swap its reader
3952 * page with the buffer head.
3953 *
3954 * We are also fighting against interrupts coming in and
3955 * moving the head or tail on us as well.
3956 *
3957 * If the next page is the head page then we have filled
3958 * the buffer, unless the commit page is still on the
3959 * reader page.
3960 */
3961 if (rb_is_head_page(next_page, &tail_page->list)) {
3962
3963 /*
3964 * If the commit is not on the reader page, then
3965 * move the header page.
3966 */
3967 if (!rb_is_reader_page(cpu_buffer->commit_page)) {
3968 /*
3969 * If we are not in overwrite mode,
3970 * this is easy, just stop here.
3971 */
3972 if (!(buffer->flags & RB_FL_OVERWRITE)) {
3973 local_inc(&cpu_buffer->dropped_events);
3974 goto out_reset;
3975 }
3976
3977 ret = rb_handle_head_page(cpu_buffer,
3978 tail_page,
3979 next_page);
3980 if (ret < 0)
3981 goto out_reset;
3982 if (ret)
3983 goto out_again;
3984 } else {
3985 /*
3986 * We need to be careful here too. The
3987 * commit page could still be on the reader
3988 * page. We could have a small buffer, and
3989 * have filled up the buffer with events
3990 * from interrupts and such, and wrapped.
3991 *
3992 * Note, if the tail page is also on the
3993 * reader_page, we let it move out.
3994 */
3995 if (unlikely((cpu_buffer->commit_page !=
3996 cpu_buffer->tail_page) &&
3997 (cpu_buffer->commit_page ==
3998 cpu_buffer->reader_page))) {
3999 local_inc(&cpu_buffer->commit_overrun);
4000 goto out_reset;
4001 }
4002 }
4003 }
4004
4005 rb_tail_page_update(cpu_buffer, tail_page, next_page);
4006
4007 out_again:
4008
4009 rb_reset_tail(cpu_buffer, tail, info);
4010
4011 /* Commit what we have for now. */
4012 rb_end_commit(cpu_buffer);
4013 /* rb_end_commit() decs committing */
4014 local_inc(&cpu_buffer->committing);
4015
4016 /* fail and let the caller try again */
4017 return ERR_PTR(-EAGAIN);
4018
4019 out_reset:
4020 /* reset write */
4021 rb_reset_tail(cpu_buffer, tail, info);
4022
4023 return NULL;
4024 }
4025
4026 /* Slow path */
4027 static struct ring_buffer_event *
4028 rb_add_time_stamp(struct ring_buffer_per_cpu *cpu_buffer,
4029 struct ring_buffer_event *event, u64 delta, bool abs)
4030 {
4031 if (abs)
4032 event->type_len = RINGBUF_TYPE_TIME_STAMP;
4033 else
4034 event->type_len = RINGBUF_TYPE_TIME_EXTEND;
4035
4036 /* Not the first event on the page, or not delta? */
4037 if (abs || rb_event_index(cpu_buffer, event)) {
4038 event->time_delta = delta & TS_MASK;
4039 event->array[0] = delta >> TS_SHIFT;
4040 } else {
4041 /* nope, just zero it */
4042 event->time_delta = 0;
4043 event->array[0] = 0;
4044 }
4045
4046 return skip_time_extend(event);
4047 }
4048
4049 static void
4050 rb_check_timestamp(struct ring_buffer_per_cpu *cpu_buffer,
4051 struct rb_event_info *info)
4052 {
4053 u64 write_stamp;
4054
4055 WARN_ONCE(1, "Delta way too big! %llu ts=%llu before=%llu after=%llu write stamp=%llu\n%s",
4056 (unsigned long long)info->delta,
4057 (unsigned long long)info->ts,
4058 (unsigned long long)info->before,
4059 (unsigned long long)info->after,
4060 (unsigned long long)({rb_time_read(&cpu_buffer->write_stamp, &write_stamp); write_stamp;}),
4061 sched_clock_stable() ? "" :
4062 "If you just came from a suspend/resume,\n"
4063 "please switch to the trace global clock:\n"
4064 " echo global > /sys/kernel/tracing/trace_clock\n"
4065 "or add trace_clock=global to the kernel command line\n");
4066 }
4067
4068 static void rb_add_timestamp(struct ring_buffer_per_cpu *cpu_buffer,
4069 struct ring_buffer_event **event,
4070 struct rb_event_info *info,
4071 u64 *delta,
4072 unsigned int *length)
4073 {
4074 bool abs = info->add_timestamp &
4075 (RB_ADD_STAMP_FORCE | RB_ADD_STAMP_ABSOLUTE);
4076
4077 if (unlikely(info->delta > (1ULL << 59))) {
4078 /*
4079 * Some timers can use more than 59 bits, and when a timestamp
4080 * is added to the buffer, it will lose those bits.
4081 */
4082 if (abs && (info->ts & TS_MSB)) {
4083 info->delta &= ABS_TS_MASK;
4084
4085 /* did the clock go backwards */
4086 } else if (info->before == info->after && info->before > info->ts) {
4087 /* not interrupted */
4088 static int once;
4089
4090 /*
4091 * This is possible with a recalibrating of the TSC.
4092 * Do not produce a call stack, but just report it.
4093 */
4094 if (!once) {
4095 once++;
4096 pr_warn("Ring buffer clock went backwards: %llu -> %llu\n",
4097 info->before, info->ts);
4098 }
4099 } else
4100 rb_check_timestamp(cpu_buffer, info);
4101 if (!abs)
4102 info->delta = 0;
4103 }
4104 *event = rb_add_time_stamp(cpu_buffer, *event, info->delta, abs);
4105 *length -= RB_LEN_TIME_EXTEND;
4106 *delta = 0;
4107 }
4108
4109 /**
4110 * rb_update_event - update event type and data
4111 * @cpu_buffer: The per cpu buffer of the @event
4112 * @event: the event to update
4113 * @info: The info to update the @event with (contains length and delta)
4114 *
4115 * Update the type and data fields of the @event. The length
4116 * is the actual size that is written to the ring buffer,
4117 * and with this, we can determine what to place into the
4118 * data field.
4119 */
4120 static void
4121 rb_update_event(struct ring_buffer_per_cpu *cpu_buffer,
4122 struct ring_buffer_event *event,
4123 struct rb_event_info *info)
4124 {
4125 unsigned length = info->length;
4126 u64 delta = info->delta;
4127 unsigned int nest = local_read(&cpu_buffer->committing) - 1;
4128
4129 if (!WARN_ON_ONCE(nest >= MAX_NEST))
4130 cpu_buffer->event_stamp[nest] = info->ts;
4131
4132 /*
4133 * If we need to add a timestamp, then we
4134 * add it to the start of the reserved space.
4135 */
4136 if (unlikely(info->add_timestamp))
4137 rb_add_timestamp(cpu_buffer, &event, info, &delta, &length);
4138
4139 event->time_delta = delta;
4140 length -= RB_EVNT_HDR_SIZE;
4141 if (length > RB_MAX_SMALL_DATA || RB_FORCE_8BYTE_ALIGNMENT) {
4142 event->type_len = 0;
4143 event->array[0] = length;
4144 } else
4145 event->type_len = DIV_ROUND_UP(length, RB_ALIGNMENT);
4146 }
4147
4148 static unsigned rb_calculate_event_length(unsigned length)
4149 {
4150 struct ring_buffer_event event; /* Used only for sizeof array */
4151
4152 /* zero length can cause confusions */
4153 if (!length)
4154 length++;
4155
4156 if (length > RB_MAX_SMALL_DATA || RB_FORCE_8BYTE_ALIGNMENT)
4157 length += sizeof(event.array[0]);
4158
4159 length += RB_EVNT_HDR_SIZE;
4160 length = ALIGN(length, RB_ARCH_ALIGNMENT);
4161
4162 /*
4163 * In case the time delta is larger than the 27 bits for it
4164 * in the header, we need to add a timestamp. If another
4165 * event comes in when trying to discard this one to increase
4166 * the length, then the timestamp will be added in the allocated
4167 * space of this event. If length is bigger than the size needed
4168 * for the TIME_EXTEND, then padding has to be used. The events
4169 * length must be either RB_LEN_TIME_EXTEND, or greater than or equal
4170 * to RB_LEN_TIME_EXTEND + 8, as 8 is the minimum size for padding.
4171 * As length is a multiple of 4, we only need to worry if it
4172 * is 12 (RB_LEN_TIME_EXTEND + 4).
4173 */
4174 if (length == RB_LEN_TIME_EXTEND + RB_ALIGNMENT)
4175 length += RB_ALIGNMENT;
4176
4177 return length;
4178 }
4179
4180 static inline bool
4181 rb_try_to_discard(struct ring_buffer_per_cpu *cpu_buffer,
4182 struct ring_buffer_event *event)
4183 {
4184 unsigned long new_index, old_index;
4185 struct buffer_page *bpage;
4186 unsigned long addr;
4187
4188 new_index = rb_event_index(cpu_buffer, event);
4189 old_index = new_index + rb_event_ts_length(event);
4190 addr = rb_subbuf_start(cpu_buffer->buffer, (unsigned long)event);
4191
4192 bpage = READ_ONCE(cpu_buffer->tail_page);
4193
4194 /*
4195 * Make sure the tail_page is still the same and
4196 * the next write location is the end of this event
4197 */
4198 if (bpage->page == (void *)addr && rb_page_write(bpage) == old_index) {
4199 unsigned long write_mask =
4200 local_read(&bpage->write) & ~RB_WRITE_MASK;
4201 unsigned long event_length = rb_event_length(event);
4202
4203 /*
4204 * For the before_stamp to be different than the write_stamp
4205 * to make sure that the next event adds an absolute
4206 * value and does not rely on the saved write stamp, which
4207 * is now going to be bogus.
4208 *
4209 * By setting the before_stamp to zero, the next event
4210 * is not going to use the write_stamp and will instead
4211 * create an absolute timestamp. This means there's no
4212 * reason to update the wirte_stamp!
4213 */
4214 rb_time_set(&cpu_buffer->before_stamp, 0);
4215
4216 /*
4217 * If an event were to come in now, it would see that the
4218 * write_stamp and the before_stamp are different, and assume
4219 * that this event just added itself before updating
4220 * the write stamp. The interrupting event will fix the
4221 * write stamp for us, and use an absolute timestamp.
4222 */
4223
4224 /*
4225 * This is on the tail page. It is possible that
4226 * a write could come in and move the tail page
4227 * and write to the next page. That is fine
4228 * because we just shorten what is on this page.
4229 */
4230 old_index += write_mask;
4231 new_index += write_mask;
4232
4233 /* caution: old_index gets updated on cmpxchg failure */
4234 if (local_try_cmpxchg(&bpage->write, &old_index, new_index)) {
4235 /* update counters */
4236 local_sub(event_length, &cpu_buffer->entries_bytes);
4237 return true;
4238 }
4239 }
4240
4241 /* could not discard */
4242 return false;
4243 }
4244
4245 static void rb_start_commit(struct ring_buffer_per_cpu *cpu_buffer)
4246 {
4247 local_inc(&cpu_buffer->committing);
4248 local_inc(&cpu_buffer->commits);
4249 }
4250
4251 static __always_inline void
4252 rb_set_commit_to_write(struct ring_buffer_per_cpu *cpu_buffer)
4253 {
4254 unsigned long max_count;
4255
4256 /*
4257 * We only race with interrupts and NMIs on this CPU.
4258 * If we own the commit event, then we can commit
4259 * all others that interrupted us, since the interruptions
4260 * are in stack format (they finish before they come
4261 * back to us). This allows us to do a simple loop to
4262 * assign the commit to the tail.
4263 */
4264 again:
4265 max_count = cpu_buffer->nr_pages * 100;
4266
4267 while (cpu_buffer->commit_page != READ_ONCE(cpu_buffer->tail_page)) {
4268 if (RB_WARN_ON(cpu_buffer, !(--max_count)))
4269 return;
4270 if (RB_WARN_ON(cpu_buffer,
4271 rb_is_reader_page(cpu_buffer->tail_page)))
4272 return;
4273 /*
4274 * No need for a memory barrier here, as the update
4275 * of the tail_page did it for this page.
4276 */
4277 local_set(&cpu_buffer->commit_page->page->commit,
4278 rb_page_write(cpu_buffer->commit_page));
4279 rb_inc_page(&cpu_buffer->commit_page);
4280 if (cpu_buffer->ring_meta) {
4281 struct ring_buffer_cpu_meta *meta = cpu_buffer->ring_meta;
4282 meta->commit_buffer = (unsigned long)cpu_buffer->commit_page->page;
4283 }
4284 /* add barrier to keep gcc from optimizing too much */
4285 barrier();
4286 }
4287 while (rb_commit_index(cpu_buffer) !=
4288 rb_page_write(cpu_buffer->commit_page)) {
4289
4290 /* Make sure the readers see the content of what is committed. */
4291 smp_wmb();
4292 local_set(&cpu_buffer->commit_page->page->commit,
4293 rb_page_write(cpu_buffer->commit_page));
4294 RB_WARN_ON(cpu_buffer,
4295 rb_page_commit(cpu_buffer->commit_page) & ~RB_WRITE_MASK);
4296 barrier();
4297 }
4298
4299 /* again, keep gcc from optimizing */
4300 barrier();
4301
4302 /*
4303 * If an interrupt came in just after the first while loop
4304 * and pushed the tail page forward, we will be left with
4305 * a dangling commit that will never go forward.
4306 */
4307 if (unlikely(cpu_buffer->commit_page != READ_ONCE(cpu_buffer->tail_page)))
4308 goto again;
4309 }
4310
4311 static __always_inline void rb_end_commit(struct ring_buffer_per_cpu *cpu_buffer)
4312 {
4313 unsigned long commits;
4314
4315 if (RB_WARN_ON(cpu_buffer,
4316 !local_read(&cpu_buffer->committing)))
4317 return;
4318
4319 again:
4320 commits = local_read(&cpu_buffer->commits);
4321 /* synchronize with interrupts */
4322 barrier();
4323 if (local_read(&cpu_buffer->committing) == 1)
4324 rb_set_commit_to_write(cpu_buffer);
4325
4326 local_dec(&cpu_buffer->committing);
4327
4328 /* synchronize with interrupts */
4329 barrier();
4330
4331 /*
4332 * Need to account for interrupts coming in between the
4333 * updating of the commit page and the clearing of the
4334 * committing counter.
4335 */
4336 if (unlikely(local_read(&cpu_buffer->commits) != commits) &&
4337 !local_read(&cpu_buffer->committing)) {
4338 local_inc(&cpu_buffer->committing);
4339 goto again;
4340 }
4341 }
4342
4343 static inline void rb_event_discard(struct ring_buffer_event *event)
4344 {
4345 if (extended_time(event))
4346 event = skip_time_extend(event);
4347
4348 /* array[0] holds the actual length for the discarded event */
4349 event->array[0] = rb_event_data_length(event) - RB_EVNT_HDR_SIZE;
4350 event->type_len = RINGBUF_TYPE_PADDING;
4351 /* time delta must be non zero */
4352 if (!event->time_delta)
4353 event->time_delta = 1;
4354 }
4355
4356 static void rb_commit(struct ring_buffer_per_cpu *cpu_buffer)
4357 {
4358 local_inc(&cpu_buffer->entries);
4359 rb_end_commit(cpu_buffer);
4360 }
4361
4362 static bool
4363 rb_irq_work_queue(struct rb_irq_work *irq_work)
4364 {
4365 int cpu;
4366
4367 /* irq_work_queue_on() is not NMI-safe */
4368 if (unlikely(in_nmi()))
4369 return irq_work_queue(&irq_work->work);
4370
4371 /*
4372 * If CPU isolation is not active, cpu is always the current
4373 * CPU, and the following is equivallent to irq_work_queue().
4374 */
4375 cpu = housekeeping_any_cpu(HK_TYPE_KERNEL_NOISE);
4376 return irq_work_queue_on(&irq_work->work, cpu);
4377 }
4378
4379 static __always_inline void
4380 rb_wakeups(struct trace_buffer *buffer, struct ring_buffer_per_cpu *cpu_buffer)
4381 {
4382 if (buffer->irq_work.waiters_pending) {
4383 buffer->irq_work.waiters_pending = false;
4384 /* irq_work_queue() supplies it's own memory barriers */
4385 rb_irq_work_queue(&buffer->irq_work);
4386 }
4387
4388 if (cpu_buffer->irq_work.waiters_pending) {
4389 cpu_buffer->irq_work.waiters_pending = false;
4390 /* irq_work_queue() supplies it's own memory barriers */
4391 rb_irq_work_queue(&cpu_buffer->irq_work);
4392 }
4393
4394 if (cpu_buffer->last_pages_touch == local_read(&cpu_buffer->pages_touched))
4395 return;
4396
4397 if (cpu_buffer->reader_page == cpu_buffer->commit_page)
4398 return;
4399
4400 if (!cpu_buffer->irq_work.full_waiters_pending)
4401 return;
4402
4403 cpu_buffer->last_pages_touch = local_read(&cpu_buffer->pages_touched);
4404
4405 if (!full_hit(buffer, cpu_buffer->cpu, cpu_buffer->shortest_full))
4406 return;
4407
4408 cpu_buffer->irq_work.wakeup_full = true;
4409 cpu_buffer->irq_work.full_waiters_pending = false;
4410 /* irq_work_queue() supplies it's own memory barriers */
4411 rb_irq_work_queue(&cpu_buffer->irq_work);
4412 }
4413
4414 #ifdef CONFIG_RING_BUFFER_RECORD_RECURSION
4415 # define do_ring_buffer_record_recursion() \
4416 do_ftrace_record_recursion(_THIS_IP_, _RET_IP_)
4417 #else
4418 # define do_ring_buffer_record_recursion() do { } while (0)
4419 #endif
4420
4421 /*
4422 * The lock and unlock are done within a preempt disable section.
4423 * The current_context per_cpu variable can only be modified
4424 * by the current task between lock and unlock. But it can
4425 * be modified more than once via an interrupt. To pass this
4426 * information from the lock to the unlock without having to
4427 * access the 'in_interrupt()' functions again (which do show
4428 * a bit of overhead in something as critical as function tracing,
4429 * we use a bitmask trick.
4430 *
4431 * bit 1 = NMI context
4432 * bit 2 = IRQ context
4433 * bit 3 = SoftIRQ context
4434 * bit 4 = normal context.
4435 *
4436 * This works because this is the order of contexts that can
4437 * preempt other contexts. A SoftIRQ never preempts an IRQ
4438 * context.
4439 *
4440 * When the context is determined, the corresponding bit is
4441 * checked and set (if it was set, then a recursion of that context
4442 * happened).
4443 *
4444 * On unlock, we need to clear this bit. To do so, just subtract
4445 * 1 from the current_context and AND it to itself.
4446 *
4447 * (binary)
4448 * 101 - 1 = 100
4449 * 101 & 100 = 100 (clearing bit zero)
4450 *
4451 * 1010 - 1 = 1001
4452 * 1010 & 1001 = 1000 (clearing bit 1)
4453 *
4454 * The least significant bit can be cleared this way, and it
4455 * just so happens that it is the same bit corresponding to
4456 * the current context.
4457 *
4458 * Now the TRANSITION bit breaks the above slightly. The TRANSITION bit
4459 * is set when a recursion is detected at the current context, and if
4460 * the TRANSITION bit is already set, it will fail the recursion.
4461 * This is needed because there's a lag between the changing of
4462 * interrupt context and updating the preempt count. In this case,
4463 * a false positive will be found. To handle this, one extra recursion
4464 * is allowed, and this is done by the TRANSITION bit. If the TRANSITION
4465 * bit is already set, then it is considered a recursion and the function
4466 * ends. Otherwise, the TRANSITION bit is set, and that bit is returned.
4467 *
4468 * On the trace_recursive_unlock(), the TRANSITION bit will be the first
4469 * to be cleared. Even if it wasn't the context that set it. That is,
4470 * if an interrupt comes in while NORMAL bit is set and the ring buffer
4471 * is called before preempt_count() is updated, since the check will
4472 * be on the NORMAL bit, the TRANSITION bit will then be set. If an
4473 * NMI then comes in, it will set the NMI bit, but when the NMI code
4474 * does the trace_recursive_unlock() it will clear the TRANSITION bit
4475 * and leave the NMI bit set. But this is fine, because the interrupt
4476 * code that set the TRANSITION bit will then clear the NMI bit when it
4477 * calls trace_recursive_unlock(). If another NMI comes in, it will
4478 * set the TRANSITION bit and continue.
4479 *
4480 * Note: The TRANSITION bit only handles a single transition between context.
4481 */
4482
4483 static __always_inline bool
4484 trace_recursive_lock(struct ring_buffer_per_cpu *cpu_buffer)
4485 {
4486 unsigned int val = cpu_buffer->current_context;
4487 int bit = interrupt_context_level();
4488
4489 bit = RB_CTX_NORMAL - bit;
4490
4491 if (unlikely(val & (1 << (bit + cpu_buffer->nest)))) {
4492 /*
4493 * It is possible that this was called by transitioning
4494 * between interrupt context, and preempt_count() has not
4495 * been updated yet. In this case, use the TRANSITION bit.
4496 */
4497 bit = RB_CTX_TRANSITION;
4498 if (val & (1 << (bit + cpu_buffer->nest))) {
4499 do_ring_buffer_record_recursion();
4500 return true;
4501 }
4502 }
4503
4504 val |= (1 << (bit + cpu_buffer->nest));
4505 cpu_buffer->current_context = val;
4506
4507 return false;
4508 }
4509
4510 static __always_inline void
4511 trace_recursive_unlock(struct ring_buffer_per_cpu *cpu_buffer)
4512 {
4513 cpu_buffer->current_context &=
4514 cpu_buffer->current_context - (1 << cpu_buffer->nest);
4515 }
4516
4517 /* The recursive locking above uses 5 bits */
4518 #define NESTED_BITS 5
4519
4520 /**
4521 * ring_buffer_nest_start - Allow to trace while nested
4522 * @buffer: The ring buffer to modify
4523 *
4524 * The ring buffer has a safety mechanism to prevent recursion.
4525 * But there may be a case where a trace needs to be done while
4526 * tracing something else. In this case, calling this function
4527 * will allow this function to nest within a currently active
4528 * ring_buffer_lock_reserve().
4529 *
4530 * Call this function before calling another ring_buffer_lock_reserve() and
4531 * call ring_buffer_nest_end() after the nested ring_buffer_unlock_commit().
4532 */
4533 void ring_buffer_nest_start(struct trace_buffer *buffer)
4534 {
4535 struct ring_buffer_per_cpu *cpu_buffer;
4536 int cpu;
4537
4538 /* Enabled by ring_buffer_nest_end() */
4539 preempt_disable_notrace();
4540 cpu = raw_smp_processor_id();
4541 cpu_buffer = buffer->buffers[cpu];
4542 /* This is the shift value for the above recursive locking */
4543 cpu_buffer->nest += NESTED_BITS;
4544 }
4545
4546 /**
4547 * ring_buffer_nest_end - Allow to trace while nested
4548 * @buffer: The ring buffer to modify
4549 *
4550 * Must be called after ring_buffer_nest_start() and after the
4551 * ring_buffer_unlock_commit().
4552 */
4553 void ring_buffer_nest_end(struct trace_buffer *buffer)
4554 {
4555 struct ring_buffer_per_cpu *cpu_buffer;
4556 int cpu;
4557
4558 /* disabled by ring_buffer_nest_start() */
4559 cpu = raw_smp_processor_id();
4560 cpu_buffer = buffer->buffers[cpu];
4561 /* This is the shift value for the above recursive locking */
4562 cpu_buffer->nest -= NESTED_BITS;
4563 preempt_enable_notrace();
4564 }
4565
4566 /**
4567 * ring_buffer_unlock_commit - commit a reserved
4568 * @buffer: The buffer to commit to
4569 *
4570 * This commits the data to the ring buffer, and releases any locks held.
4571 *
4572 * Must be paired with ring_buffer_lock_reserve.
4573 */
4574 int ring_buffer_unlock_commit(struct trace_buffer *buffer)
4575 {
4576 struct ring_buffer_per_cpu *cpu_buffer;
4577 int cpu = raw_smp_processor_id();
4578
4579 cpu_buffer = buffer->buffers[cpu];
4580
4581 rb_commit(cpu_buffer);
4582
4583 rb_wakeups(buffer, cpu_buffer);
4584
4585 trace_recursive_unlock(cpu_buffer);
4586
4587 preempt_enable_notrace();
4588
4589 return 0;
4590 }
4591 EXPORT_SYMBOL_GPL(ring_buffer_unlock_commit);
4592
4593 /* Special value to validate all deltas on a page. */
4594 #define CHECK_FULL_PAGE 1L
4595
4596 #ifdef CONFIG_RING_BUFFER_VALIDATE_TIME_DELTAS
4597
4598 static const char *show_irq_str(int bits)
4599 {
4600 static const char * type[] = {
4601 ".", // 0
4602 "s", // 1
4603 "h", // 2
4604 "Hs", // 3
4605 "n", // 4
4606 "Ns", // 5
4607 "Nh", // 6
4608 "NHs", // 7
4609 };
4610
4611 return type[bits];
4612 }
4613
4614 /* Assume this is a trace event */
4615 static const char *show_flags(struct ring_buffer_event *event)
4616 {
4617 struct trace_entry *entry;
4618 int bits = 0;
4619
4620 if (rb_event_data_length(event) - RB_EVNT_HDR_SIZE < sizeof(*entry))
4621 return "X";
4622
4623 entry = ring_buffer_event_data(event);
4624
4625 if (entry->flags & TRACE_FLAG_SOFTIRQ)
4626 bits |= 1;
4627
4628 if (entry->flags & TRACE_FLAG_HARDIRQ)
4629 bits |= 2;
4630
4631 if (entry->flags & TRACE_FLAG_NMI)
4632 bits |= 4;
4633
4634 return show_irq_str(bits);
4635 }
4636
4637 static const char *show_irq(struct ring_buffer_event *event)
4638 {
4639 struct trace_entry *entry;
4640
4641 if (rb_event_data_length(event) - RB_EVNT_HDR_SIZE < sizeof(*entry))
4642 return "";
4643
4644 entry = ring_buffer_event_data(event);
4645 if (entry->flags & TRACE_FLAG_IRQS_OFF)
4646 return "d";
4647 return "";
4648 }
4649
4650 static const char *show_interrupt_level(void)
4651 {
4652 unsigned long pc = preempt_count();
4653 unsigned char level = 0;
4654
4655 if (pc & SOFTIRQ_OFFSET)
4656 level |= 1;
4657
4658 if (pc & HARDIRQ_MASK)
4659 level |= 2;
4660
4661 if (pc & NMI_MASK)
4662 level |= 4;
4663
4664 return show_irq_str(level);
4665 }
4666
4667 static void dump_buffer_page(struct buffer_data_page *dpage,
4668 struct rb_event_info *info,
4669 unsigned long tail)
4670 {
4671 struct ring_buffer_event *event;
4672 u64 ts, delta;
4673 int e;
4674
4675 ts = dpage->time_stamp;
4676 pr_warn(" [%lld] PAGE TIME STAMP\n", ts);
4677
4678 for (e = 0; e < tail; e += rb_event_length(event)) {
4679
4680 event = (struct ring_buffer_event *)(dpage->data + e);
4681
4682 switch (event->type_len) {
4683
4684 case RINGBUF_TYPE_TIME_EXTEND:
4685 delta = rb_event_time_stamp(event);
4686 ts += delta;
4687 pr_warn(" 0x%x: [%lld] delta:%lld TIME EXTEND\n",
4688 e, ts, delta);
4689 break;
4690
4691 case RINGBUF_TYPE_TIME_STAMP:
4692 delta = rb_event_time_stamp(event);
4693 ts = rb_fix_abs_ts(delta, ts);
4694 pr_warn(" 0x%x: [%lld] absolute:%lld TIME STAMP\n",
4695 e, ts, delta);
4696 break;
4697
4698 case RINGBUF_TYPE_PADDING:
4699 ts += event->time_delta;
4700 pr_warn(" 0x%x: [%lld] delta:%d PADDING\n",
4701 e, ts, event->time_delta);
4702 break;
4703
4704 case RINGBUF_TYPE_DATA:
4705 ts += event->time_delta;
4706 pr_warn(" 0x%x: [%lld] delta:%d %s%s\n",
4707 e, ts, event->time_delta,
4708 show_flags(event), show_irq(event));
4709 break;
4710
4711 default:
4712 break;
4713 }
4714 }
4715 pr_warn("expected end:0x%lx last event actually ended at:0x%x\n", tail, e);
4716 }
4717
4718 static DEFINE_PER_CPU(atomic_t, checking);
4719 static atomic_t ts_dump;
4720
4721 #define buffer_warn_return(fmt, ...) \
4722 do { \
4723 /* If another report is happening, ignore this one */ \
4724 if (atomic_inc_return(&ts_dump) != 1) { \
4725 atomic_dec(&ts_dump); \
4726 goto out; \
4727 } \
4728 atomic_inc(&cpu_buffer->record_disabled); \
4729 pr_warn(fmt, ##__VA_ARGS__); \
4730 dump_buffer_page(dpage, info, tail); \
4731 atomic_dec(&ts_dump); \
4732 /* There's some cases in boot up that this can happen */ \
4733 if (WARN_ON_ONCE(system_state != SYSTEM_BOOTING)) \
4734 /* Do not re-enable checking */ \
4735 return; \
4736 } while (0)
4737
4738 /*
4739 * Check if the current event time stamp matches the deltas on
4740 * the buffer page.
4741 */
4742 static void check_buffer(struct ring_buffer_per_cpu *cpu_buffer,
4743 struct rb_event_info *info,
4744 unsigned long tail)
4745 {
4746 struct buffer_data_page *dpage;
4747 u64 ts, delta;
4748 bool full = false;
4749 int ret;
4750
4751 dpage = info->tail_page->page;
4752
4753 if (tail == CHECK_FULL_PAGE) {
4754 full = true;
4755 tail = rb_data_page_commit(dpage);
4756 } else if (info->add_timestamp &
4757 (RB_ADD_STAMP_FORCE | RB_ADD_STAMP_ABSOLUTE)) {
4758 /* Ignore events with absolute time stamps */
4759 return;
4760 }
4761
4762 /*
4763 * Do not check the first event (skip possible extends too).
4764 * Also do not check if previous events have not been committed.
4765 */
4766 if (tail <= 8 || tail > rb_data_page_commit(dpage))
4767 return;
4768
4769 /*
4770 * If this interrupted another event,
4771 */
4772 if (atomic_inc_return(this_cpu_ptr(&checking)) != 1)
4773 goto out;
4774
4775 ret = rb_read_data_buffer(dpage, tail, cpu_buffer->cpu, &ts, &delta);
4776 if (ret < 0) {
4777 if (delta < ts) {
4778 buffer_warn_return("[CPU: %d]ABSOLUTE TIME WENT BACKWARDS: last ts: %lld absolute ts: %lld clock:%pS\n",
4779 cpu_buffer->cpu, ts, delta,
4780 cpu_buffer->buffer->clock);
4781 goto out;
4782 }
4783 }
4784 if ((full && ts > info->ts) ||
4785 (!full && ts + info->delta != info->ts)) {
4786 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",
4787 cpu_buffer->cpu,
4788 ts + info->delta, info->ts, info->delta,
4789 info->before, info->after,
4790 full ? " (full)" : "", show_interrupt_level(),
4791 cpu_buffer->buffer->clock);
4792 }
4793 out:
4794 atomic_dec(this_cpu_ptr(&checking));
4795 }
4796 #else
4797 static inline void check_buffer(struct ring_buffer_per_cpu *cpu_buffer,
4798 struct rb_event_info *info,
4799 unsigned long tail)
4800 {
4801 }
4802 #endif /* CONFIG_RING_BUFFER_VALIDATE_TIME_DELTAS */
4803
4804 static struct ring_buffer_event *
4805 __rb_reserve_next(struct ring_buffer_per_cpu *cpu_buffer,
4806 struct rb_event_info *info)
4807 {
4808 struct ring_buffer_event *event;
4809 struct buffer_page *tail_page;
4810 unsigned long tail, write, w;
4811
4812 /* Don't let the compiler play games with cpu_buffer->tail_page */
4813 tail_page = info->tail_page = READ_ONCE(cpu_buffer->tail_page);
4814
4815 /*A*/ w = local_read(&tail_page->write) & RB_WRITE_MASK;
4816 barrier();
4817 rb_time_read(&cpu_buffer->before_stamp, &info->before);
4818 rb_time_read(&cpu_buffer->write_stamp, &info->after);
4819 barrier();
4820 info->ts = rb_time_stamp(cpu_buffer->buffer);
4821
4822 if ((info->add_timestamp & RB_ADD_STAMP_ABSOLUTE)) {
4823 info->delta = info->ts;
4824 } else {
4825 /*
4826 * If interrupting an event time update, we may need an
4827 * absolute timestamp.
4828 * Don't bother if this is the start of a new page (w == 0).
4829 */
4830 if (!w) {
4831 /* Use the sub-buffer timestamp */
4832 info->delta = 0;
4833 } else if (unlikely(info->before != info->after)) {
4834 info->add_timestamp |= RB_ADD_STAMP_FORCE | RB_ADD_STAMP_EXTEND;
4835 info->length += RB_LEN_TIME_EXTEND;
4836 } else {
4837 info->delta = info->ts - info->after;
4838 if (unlikely(test_time_stamp(info->delta))) {
4839 info->add_timestamp |= RB_ADD_STAMP_EXTEND;
4840 info->length += RB_LEN_TIME_EXTEND;
4841 }
4842 }
4843 }
4844
4845 /*B*/ rb_time_set(&cpu_buffer->before_stamp, info->ts);
4846
4847 /*C*/ write = local_add_return(info->length, &tail_page->write);
4848
4849 /* set write to only the index of the write */
4850 write &= RB_WRITE_MASK;
4851
4852 tail = write - info->length;
4853
4854 /* See if we shot pass the end of this buffer page */
4855 if (unlikely(write > rb_page_capacity(tail_page))) {
4856 check_buffer(cpu_buffer, info, CHECK_FULL_PAGE);
4857 return rb_move_tail(cpu_buffer, tail, info);
4858 }
4859
4860 if (likely(tail == w)) {
4861 /* Nothing interrupted us between A and C */
4862 /*D*/ rb_time_set(&cpu_buffer->write_stamp, info->ts);
4863 /*
4864 * If something came in between C and D, the write stamp
4865 * may now not be in sync. But that's fine as the before_stamp
4866 * will be different and then next event will just be forced
4867 * to use an absolute timestamp.
4868 */
4869 if (likely(!(info->add_timestamp &
4870 (RB_ADD_STAMP_FORCE | RB_ADD_STAMP_ABSOLUTE))))
4871 /* This did not interrupt any time update */
4872 info->delta = info->ts - info->after;
4873 else
4874 /* Just use full timestamp for interrupting event */
4875 info->delta = info->ts;
4876 check_buffer(cpu_buffer, info, tail);
4877 } else {
4878 u64 ts;
4879 /* SLOW PATH - Interrupted between A and C */
4880
4881 /* Save the old before_stamp */
4882 rb_time_read(&cpu_buffer->before_stamp, &info->before);
4883
4884 /*
4885 * Read a new timestamp and update the before_stamp to make
4886 * the next event after this one force using an absolute
4887 * timestamp. This is in case an interrupt were to come in
4888 * between E and F.
4889 */
4890 ts = rb_time_stamp(cpu_buffer->buffer);
4891 rb_time_set(&cpu_buffer->before_stamp, ts);
4892
4893 barrier();
4894 /*E*/ rb_time_read(&cpu_buffer->write_stamp, &info->after);
4895 barrier();
4896 /*F*/ if (write == (local_read(&tail_page->write) & RB_WRITE_MASK) &&
4897 info->after == info->before && info->after < ts) {
4898 /*
4899 * Nothing came after this event between C and F, it is
4900 * safe to use info->after for the delta as it
4901 * matched info->before and is still valid.
4902 */
4903 info->delta = ts - info->after;
4904 } else {
4905 /*
4906 * Interrupted between C and F:
4907 * Lost the previous events time stamp. Just set the
4908 * delta to zero, and this will be the same time as
4909 * the event this event interrupted. And the events that
4910 * came after this will still be correct (as they would
4911 * have built their delta on the previous event.
4912 */
4913 info->delta = 0;
4914 }
4915 info->ts = ts;
4916 info->add_timestamp &= ~RB_ADD_STAMP_FORCE;
4917 }
4918
4919 /*
4920 * If this is the first commit on the page, then it has the same
4921 * timestamp as the page itself.
4922 */
4923 if (unlikely(!tail && !(info->add_timestamp &
4924 (RB_ADD_STAMP_FORCE | RB_ADD_STAMP_ABSOLUTE))))
4925 info->delta = 0;
4926
4927 /* We reserved something on the buffer */
4928
4929 event = __rb_page_index(tail_page, tail);
4930 rb_update_event(cpu_buffer, event, info);
4931
4932 local_inc(&tail_page->entries);
4933
4934 /*
4935 * If this is the first commit on the page, then update
4936 * its timestamp.
4937 */
4938 if (unlikely(!tail))
4939 tail_page->page->time_stamp = info->ts;
4940
4941 /* account for these added bytes */
4942 local_add(info->length, &cpu_buffer->entries_bytes);
4943
4944 return event;
4945 }
4946
4947 static __always_inline struct ring_buffer_event *
4948 rb_reserve_next_event(struct trace_buffer *buffer,
4949 struct ring_buffer_per_cpu *cpu_buffer,
4950 unsigned long length)
4951 {
4952 struct ring_buffer_event *event;
4953 struct rb_event_info info;
4954 int nr_loops = 0;
4955 int add_ts_default;
4956
4957 /*
4958 * ring buffer does cmpxchg as well as atomic64 operations
4959 * (which some archs use locking for atomic64), make sure this
4960 * is safe in NMI context
4961 */
4962 if ((!IS_ENABLED(CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG) ||
4963 IS_ENABLED(CONFIG_GENERIC_ATOMIC64)) &&
4964 (unlikely(in_nmi()))) {
4965 return NULL;
4966 }
4967
4968 rb_start_commit(cpu_buffer);
4969 /* The commit page can not change after this */
4970
4971 #ifdef CONFIG_RING_BUFFER_ALLOW_SWAP
4972 /*
4973 * Due to the ability to swap a cpu buffer from a buffer
4974 * it is possible it was swapped before we committed.
4975 * (committing stops a swap). We check for it here and
4976 * if it happened, we have to fail the write.
4977 */
4978 barrier();
4979 if (unlikely(READ_ONCE(cpu_buffer->buffer) != buffer)) {
4980 local_dec(&cpu_buffer->committing);
4981 local_dec(&cpu_buffer->commits);
4982 return NULL;
4983 }
4984 #endif
4985
4986 info.length = rb_calculate_event_length(length);
4987
4988 if (ring_buffer_time_stamp_abs(cpu_buffer->buffer)) {
4989 add_ts_default = RB_ADD_STAMP_ABSOLUTE;
4990 info.length += RB_LEN_TIME_EXTEND;
4991 if (info.length > rb_subbuf_max_data_size(cpu_buffer->buffer))
4992 goto out_fail;
4993 } else {
4994 add_ts_default = RB_ADD_STAMP_NONE;
4995 }
4996
4997 again:
4998 info.add_timestamp = add_ts_default;
4999 info.delta = 0;
5000
5001 /*
5002 * We allow for interrupts to reenter here and do a trace.
5003 * If one does, it will cause this original code to loop
5004 * back here. Even with heavy interrupts happening, this
5005 * should only happen a few times in a row. If this happens
5006 * 1000 times in a row, there must be either an interrupt
5007 * storm or we have something buggy.
5008 * Bail!
5009 */
5010 if (RB_WARN_ON(cpu_buffer, ++nr_loops > 1000))
5011 goto out_fail;
5012
5013 event = __rb_reserve_next(cpu_buffer, &info);
5014
5015 if (unlikely(PTR_ERR(event) == -EAGAIN)) {
5016 if (info.add_timestamp & (RB_ADD_STAMP_FORCE | RB_ADD_STAMP_EXTEND))
5017 info.length -= RB_LEN_TIME_EXTEND;
5018 goto again;
5019 }
5020
5021 if (likely(event))
5022 return event;
5023 out_fail:
5024 rb_end_commit(cpu_buffer);
5025 return NULL;
5026 }
5027
5028 /**
5029 * ring_buffer_lock_reserve - reserve a part of the buffer
5030 * @buffer: the ring buffer to reserve from
5031 * @length: the length of the data to reserve (excluding event header)
5032 *
5033 * Returns a reserved event on the ring buffer to copy directly to.
5034 * The user of this interface will need to get the body to write into
5035 * and can use the ring_buffer_event_data() interface.
5036 *
5037 * The length is the length of the data needed, not the event length
5038 * which also includes the event header.
5039 *
5040 * Must be paired with ring_buffer_unlock_commit, unless NULL is returned.
5041 * If NULL is returned, then nothing has been allocated or locked.
5042 */
5043 struct ring_buffer_event *
5044 ring_buffer_lock_reserve(struct trace_buffer *buffer, unsigned long length)
5045 {
5046 struct ring_buffer_per_cpu *cpu_buffer;
5047 struct ring_buffer_event *event;
5048 int cpu;
5049
5050 /* If we are tracing schedule, we don't want to recurse */
5051 preempt_disable_notrace();
5052
5053 if (unlikely(atomic_read(&buffer->record_disabled)))
5054 goto out;
5055
5056 cpu = raw_smp_processor_id();
5057
5058 if (unlikely(!cpumask_test_cpu(cpu, buffer->cpumask)))
5059 goto out;
5060
5061 cpu_buffer = buffer->buffers[cpu];
5062
5063 if (unlikely(atomic_read(&cpu_buffer->record_disabled)))
5064 goto out;
5065
5066 if (unlikely(length > rb_subbuf_max_data_size(buffer)))
5067 goto out;
5068
5069 if (unlikely(trace_recursive_lock(cpu_buffer)))
5070 goto out;
5071
5072 event = rb_reserve_next_event(buffer, cpu_buffer, length);
5073 if (!event)
5074 goto out_unlock;
5075
5076 return event;
5077
5078 out_unlock:
5079 trace_recursive_unlock(cpu_buffer);
5080 out:
5081 preempt_enable_notrace();
5082 return NULL;
5083 }
5084 EXPORT_SYMBOL_GPL(ring_buffer_lock_reserve);
5085
5086 /*
5087 * Decrement the entries to the page that an event is on.
5088 * The event does not even need to exist, only the pointer
5089 * to the page it is on. This may only be called before the commit
5090 * takes place.
5091 */
5092 static inline void
5093 rb_decrement_entry(struct ring_buffer_per_cpu *cpu_buffer,
5094 struct ring_buffer_event *event)
5095 {
5096 unsigned long addr = (unsigned long)event;
5097 struct buffer_page *bpage = cpu_buffer->commit_page;
5098 struct buffer_page *start;
5099
5100 addr = rb_subbuf_start(cpu_buffer->buffer, addr);
5101
5102 /* Do the likely case first */
5103 if (likely(bpage->page == (void *)addr)) {
5104 local_dec(&bpage->entries);
5105 return;
5106 }
5107
5108 /*
5109 * Because the commit page may be on the reader page we
5110 * start with the next page and check the end loop there.
5111 */
5112 rb_inc_page(&bpage);
5113 start = bpage;
5114 do {
5115 if (bpage->page == (void *)addr) {
5116 local_dec(&bpage->entries);
5117 return;
5118 }
5119 rb_inc_page(&bpage);
5120 } while (bpage != start);
5121
5122 /* commit not part of this buffer?? */
5123 RB_WARN_ON(cpu_buffer, 1);
5124 }
5125
5126 /**
5127 * ring_buffer_discard_commit - discard an event that has not been committed
5128 * @buffer: the ring buffer
5129 * @event: non committed event to discard
5130 *
5131 * Sometimes an event that is in the ring buffer needs to be ignored.
5132 * This function lets the user discard an event in the ring buffer
5133 * and then that event will not be read later.
5134 *
5135 * This function only works if it is called before the item has been
5136 * committed. It will try to free the event from the ring buffer
5137 * if another event has not been added behind it.
5138 *
5139 * If another event has been added behind it, it will set the event
5140 * up as discarded, and perform the commit.
5141 *
5142 * If this function is called, do not call ring_buffer_unlock_commit on
5143 * the event.
5144 */
5145 void ring_buffer_discard_commit(struct trace_buffer *buffer,
5146 struct ring_buffer_event *event)
5147 {
5148 struct ring_buffer_per_cpu *cpu_buffer;
5149 int cpu;
5150
5151 /* The event is discarded regardless */
5152 rb_event_discard(event);
5153
5154 cpu = smp_processor_id();
5155 cpu_buffer = buffer->buffers[cpu];
5156
5157 /*
5158 * This must only be called if the event has not been
5159 * committed yet. Thus we can assume that preemption
5160 * is still disabled.
5161 */
5162 RB_WARN_ON(buffer, !local_read(&cpu_buffer->committing));
5163
5164 rb_decrement_entry(cpu_buffer, event);
5165 rb_try_to_discard(cpu_buffer, event);
5166 rb_end_commit(cpu_buffer);
5167
5168 trace_recursive_unlock(cpu_buffer);
5169
5170 preempt_enable_notrace();
5171
5172 }
5173 EXPORT_SYMBOL_GPL(ring_buffer_discard_commit);
5174
5175 /**
5176 * ring_buffer_write - write data to the buffer without reserving
5177 * @buffer: The ring buffer to write to.
5178 * @length: The length of the data being written (excluding the event header)
5179 * @data: The data to write to the buffer.
5180 *
5181 * This is like ring_buffer_lock_reserve and ring_buffer_unlock_commit as
5182 * one function. If you already have the data to write to the buffer, it
5183 * may be easier to simply call this function.
5184 *
5185 * Note, like ring_buffer_lock_reserve, the length is the length of the data
5186 * and not the length of the event which would hold the header.
5187 */
5188 int ring_buffer_write(struct trace_buffer *buffer,
5189 unsigned long length,
5190 void *data)
5191 {
5192 struct ring_buffer_per_cpu *cpu_buffer;
5193 struct ring_buffer_event *event;
5194 void *body;
5195 int ret = -EBUSY;
5196 int cpu;
5197
5198 guard(preempt_notrace)();
5199
5200 if (atomic_read(&buffer->record_disabled))
5201 return -EBUSY;
5202
5203 cpu = raw_smp_processor_id();
5204
5205 if (!cpumask_test_cpu(cpu, buffer->cpumask))
5206 return -EBUSY;
5207
5208 cpu_buffer = buffer->buffers[cpu];
5209
5210 if (atomic_read(&cpu_buffer->record_disabled))
5211 return -EBUSY;
5212
5213 if (length > rb_subbuf_max_data_size(buffer))
5214 return -EBUSY;
5215
5216 if (unlikely(trace_recursive_lock(cpu_buffer)))
5217 return -EBUSY;
5218
5219 event = rb_reserve_next_event(buffer, cpu_buffer, length);
5220 if (!event)
5221 goto out_unlock;
5222
5223 body = rb_event_data(event);
5224
5225 memcpy(body, data, length);
5226
5227 rb_commit(cpu_buffer);
5228
5229 rb_wakeups(buffer, cpu_buffer);
5230
5231 ret = 0;
5232
5233 out_unlock:
5234 trace_recursive_unlock(cpu_buffer);
5235 return ret;
5236 }
5237 EXPORT_SYMBOL_GPL(ring_buffer_write);
5238
5239 /*
5240 * The total entries in the ring buffer is the running counter
5241 * of entries entered into the ring buffer, minus the sum of
5242 * the entries read from the ring buffer and the number of
5243 * entries that were overwritten.
5244 */
5245 static inline unsigned long
5246 rb_num_of_entries(struct ring_buffer_per_cpu *cpu_buffer)
5247 {
5248 return local_read(&cpu_buffer->entries) -
5249 (local_read(&cpu_buffer->overrun) + cpu_buffer->read);
5250 }
5251
5252 static bool rb_per_cpu_empty(struct ring_buffer_per_cpu *cpu_buffer)
5253 {
5254 return !rb_num_of_entries(cpu_buffer);
5255 }
5256
5257 /**
5258 * ring_buffer_record_disable - stop all writes into the buffer
5259 * @buffer: The ring buffer to stop writes to.
5260 *
5261 * This prevents all writes to the buffer. Any attempt to write
5262 * to the buffer after this will fail and return NULL.
5263 *
5264 * The caller should call synchronize_rcu() after this.
5265 */
5266 void ring_buffer_record_disable(struct trace_buffer *buffer)
5267 {
5268 atomic_inc(&buffer->record_disabled);
5269 }
5270 EXPORT_SYMBOL_GPL(ring_buffer_record_disable);
5271
5272 /**
5273 * ring_buffer_record_enable - enable writes to the buffer
5274 * @buffer: The ring buffer to enable writes
5275 *
5276 * Note, multiple disables will need the same number of enables
5277 * to truly enable the writing (much like preempt_disable).
5278 */
5279 void ring_buffer_record_enable(struct trace_buffer *buffer)
5280 {
5281 atomic_dec(&buffer->record_disabled);
5282 }
5283 EXPORT_SYMBOL_GPL(ring_buffer_record_enable);
5284
5285 /**
5286 * ring_buffer_record_off - stop all writes into the buffer
5287 * @buffer: The ring buffer to stop writes to.
5288 *
5289 * This prevents all writes to the buffer. Any attempt to write
5290 * to the buffer after this will fail and return NULL.
5291 *
5292 * This is different than ring_buffer_record_disable() as
5293 * it works like an on/off switch, where as the disable() version
5294 * must be paired with a enable().
5295 */
5296 void ring_buffer_record_off(struct trace_buffer *buffer)
5297 {
5298 unsigned int rd;
5299 unsigned int new_rd;
5300
5301 rd = atomic_read(&buffer->record_disabled);
5302 do {
5303 new_rd = rd | RB_BUFFER_OFF;
5304 } while (!atomic_try_cmpxchg(&buffer->record_disabled, &rd, new_rd));
5305 }
5306 EXPORT_SYMBOL_GPL(ring_buffer_record_off);
5307
5308 /**
5309 * ring_buffer_record_on - restart writes into the buffer
5310 * @buffer: The ring buffer to start writes to.
5311 *
5312 * This enables all writes to the buffer that was disabled by
5313 * ring_buffer_record_off().
5314 *
5315 * This is different than ring_buffer_record_enable() as
5316 * it works like an on/off switch, where as the enable() version
5317 * must be paired with a disable().
5318 */
5319 void ring_buffer_record_on(struct trace_buffer *buffer)
5320 {
5321 unsigned int rd;
5322 unsigned int new_rd;
5323
5324 rd = atomic_read(&buffer->record_disabled);
5325 do {
5326 new_rd = rd & ~RB_BUFFER_OFF;
5327 } while (!atomic_try_cmpxchg(&buffer->record_disabled, &rd, new_rd));
5328 }
5329 EXPORT_SYMBOL_GPL(ring_buffer_record_on);
5330
5331 /**
5332 * ring_buffer_record_is_on - return true if the ring buffer can write
5333 * @buffer: The ring buffer to see if write is enabled
5334 *
5335 * Returns true if the ring buffer is in a state that it accepts writes.
5336 */
5337 bool ring_buffer_record_is_on(struct trace_buffer *buffer)
5338 {
5339 return !atomic_read(&buffer->record_disabled);
5340 }
5341
5342 /**
5343 * ring_buffer_record_is_set_on - return true if the ring buffer is set writable
5344 * @buffer: The ring buffer to see if write is set enabled
5345 *
5346 * Returns true if the ring buffer is set writable by ring_buffer_record_on().
5347 * Note that this does NOT mean it is in a writable state.
5348 *
5349 * It may return true when the ring buffer has been disabled by
5350 * ring_buffer_record_disable(), as that is a temporary disabling of
5351 * the ring buffer.
5352 */
5353 bool ring_buffer_record_is_set_on(struct trace_buffer *buffer)
5354 {
5355 return !(atomic_read(&buffer->record_disabled) & RB_BUFFER_OFF);
5356 }
5357
5358 /**
5359 * ring_buffer_record_is_on_cpu - return true if the ring buffer can write
5360 * @buffer: The ring buffer to see if write is enabled
5361 * @cpu: The CPU to test if the ring buffer can write too
5362 *
5363 * Returns true if the ring buffer is in a state that it accepts writes
5364 * for a particular CPU.
5365 */
5366 bool ring_buffer_record_is_on_cpu(struct trace_buffer *buffer, int cpu)
5367 {
5368 struct ring_buffer_per_cpu *cpu_buffer;
5369
5370 cpu_buffer = buffer->buffers[cpu];
5371
5372 return ring_buffer_record_is_set_on(buffer) &&
5373 !atomic_read(&cpu_buffer->record_disabled);
5374 }
5375
5376 /**
5377 * ring_buffer_record_disable_cpu - stop all writes into the cpu_buffer
5378 * @buffer: The ring buffer to stop writes to.
5379 * @cpu: The CPU buffer to stop
5380 *
5381 * This prevents all writes to the buffer. Any attempt to write
5382 * to the buffer after this will fail and return NULL.
5383 *
5384 * The caller should call synchronize_rcu() after this.
5385 */
5386 void ring_buffer_record_disable_cpu(struct trace_buffer *buffer, int cpu)
5387 {
5388 struct ring_buffer_per_cpu *cpu_buffer;
5389
5390 if (!cpumask_test_cpu(cpu, buffer->cpumask))
5391 return;
5392
5393 cpu_buffer = buffer->buffers[cpu];
5394 atomic_inc(&cpu_buffer->record_disabled);
5395 }
5396 EXPORT_SYMBOL_GPL(ring_buffer_record_disable_cpu);
5397
5398 /**
5399 * ring_buffer_record_enable_cpu - enable writes to the buffer
5400 * @buffer: The ring buffer to enable writes
5401 * @cpu: The CPU to enable.
5402 *
5403 * Note, multiple disables will need the same number of enables
5404 * to truly enable the writing (much like preempt_disable).
5405 */
5406 void ring_buffer_record_enable_cpu(struct trace_buffer *buffer, int cpu)
5407 {
5408 struct ring_buffer_per_cpu *cpu_buffer;
5409
5410 if (!cpumask_test_cpu(cpu, buffer->cpumask))
5411 return;
5412
5413 cpu_buffer = buffer->buffers[cpu];
5414 atomic_dec(&cpu_buffer->record_disabled);
5415 }
5416 EXPORT_SYMBOL_GPL(ring_buffer_record_enable_cpu);
5417
5418 /**
5419 * ring_buffer_oldest_event_ts - get the oldest event timestamp from the buffer
5420 * @buffer: The ring buffer
5421 * @cpu: The per CPU buffer to read from.
5422 */
5423 u64 ring_buffer_oldest_event_ts(struct trace_buffer *buffer, int cpu)
5424 {
5425 unsigned long flags;
5426 struct ring_buffer_per_cpu *cpu_buffer;
5427 struct buffer_page *bpage;
5428 u64 ret = 0;
5429
5430 if (!cpumask_test_cpu(cpu, buffer->cpumask))
5431 return 0;
5432
5433 cpu_buffer = buffer->buffers[cpu];
5434 raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
5435 /*
5436 * if the tail is on reader_page, oldest time stamp is on the reader
5437 * page
5438 */
5439 if (cpu_buffer->tail_page == cpu_buffer->reader_page)
5440 bpage = cpu_buffer->reader_page;
5441 else
5442 bpage = rb_set_head_page(cpu_buffer);
5443 if (bpage)
5444 ret = bpage->page->time_stamp;
5445 raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
5446
5447 return ret;
5448 }
5449 EXPORT_SYMBOL_GPL(ring_buffer_oldest_event_ts);
5450
5451 /**
5452 * ring_buffer_bytes_cpu - get the number of bytes unconsumed in a cpu buffer
5453 * @buffer: The ring buffer
5454 * @cpu: The per CPU buffer to read from.
5455 */
5456 unsigned long ring_buffer_bytes_cpu(struct trace_buffer *buffer, int cpu)
5457 {
5458 struct ring_buffer_per_cpu *cpu_buffer;
5459 unsigned long ret;
5460
5461 if (!cpumask_test_cpu(cpu, buffer->cpumask))
5462 return 0;
5463
5464 cpu_buffer = buffer->buffers[cpu];
5465 ret = local_read(&cpu_buffer->entries_bytes) - cpu_buffer->read_bytes;
5466
5467 return ret;
5468 }
5469 EXPORT_SYMBOL_GPL(ring_buffer_bytes_cpu);
5470
5471 /**
5472 * ring_buffer_entries_cpu - get the number of entries in a cpu buffer
5473 * @buffer: The ring buffer
5474 * @cpu: The per CPU buffer to get the entries from.
5475 */
5476 unsigned long ring_buffer_entries_cpu(struct trace_buffer *buffer, int cpu)
5477 {
5478 struct ring_buffer_per_cpu *cpu_buffer;
5479
5480 if (!cpumask_test_cpu(cpu, buffer->cpumask))
5481 return 0;
5482
5483 cpu_buffer = buffer->buffers[cpu];
5484
5485 return rb_num_of_entries(cpu_buffer);
5486 }
5487 EXPORT_SYMBOL_GPL(ring_buffer_entries_cpu);
5488
5489 /**
5490 * ring_buffer_overrun_cpu - get the number of overruns caused by the ring
5491 * buffer wrapping around (only if RB_FL_OVERWRITE is on).
5492 * @buffer: The ring buffer
5493 * @cpu: The per CPU buffer to get the number of overruns from
5494 */
5495 unsigned long ring_buffer_overrun_cpu(struct trace_buffer *buffer, int cpu)
5496 {
5497 struct ring_buffer_per_cpu *cpu_buffer;
5498 unsigned long ret;
5499
5500 if (!cpumask_test_cpu(cpu, buffer->cpumask))
5501 return 0;
5502
5503 cpu_buffer = buffer->buffers[cpu];
5504 ret = local_read(&cpu_buffer->overrun);
5505
5506 return ret;
5507 }
5508 EXPORT_SYMBOL_GPL(ring_buffer_overrun_cpu);
5509
5510 /**
5511 * ring_buffer_commit_overrun_cpu - get the number of overruns caused by
5512 * commits failing due to the buffer wrapping around while there are uncommitted
5513 * events, such as during an interrupt storm.
5514 * @buffer: The ring buffer
5515 * @cpu: The per CPU buffer to get the number of overruns from
5516 */
5517 unsigned long
5518 ring_buffer_commit_overrun_cpu(struct trace_buffer *buffer, int cpu)
5519 {
5520 struct ring_buffer_per_cpu *cpu_buffer;
5521 unsigned long ret;
5522
5523 if (!cpumask_test_cpu(cpu, buffer->cpumask))
5524 return 0;
5525
5526 cpu_buffer = buffer->buffers[cpu];
5527 ret = local_read(&cpu_buffer->commit_overrun);
5528
5529 return ret;
5530 }
5531 EXPORT_SYMBOL_GPL(ring_buffer_commit_overrun_cpu);
5532
5533 /**
5534 * ring_buffer_dropped_events_cpu - get the number of dropped events caused by
5535 * the ring buffer filling up (only if RB_FL_OVERWRITE is off).
5536 * @buffer: The ring buffer
5537 * @cpu: The per CPU buffer to get the number of overruns from
5538 */
5539 unsigned long
5540 ring_buffer_dropped_events_cpu(struct trace_buffer *buffer, int cpu)
5541 {
5542 struct ring_buffer_per_cpu *cpu_buffer;
5543 unsigned long ret;
5544
5545 if (!cpumask_test_cpu(cpu, buffer->cpumask))
5546 return 0;
5547
5548 cpu_buffer = buffer->buffers[cpu];
5549 ret = local_read(&cpu_buffer->dropped_events);
5550
5551 return ret;
5552 }
5553 EXPORT_SYMBOL_GPL(ring_buffer_dropped_events_cpu);
5554
5555 /**
5556 * ring_buffer_read_events_cpu - get the number of events successfully read
5557 * @buffer: The ring buffer
5558 * @cpu: The per CPU buffer to get the number of events read
5559 */
5560 unsigned long
5561 ring_buffer_read_events_cpu(struct trace_buffer *buffer, int cpu)
5562 {
5563 struct ring_buffer_per_cpu *cpu_buffer;
5564
5565 if (!cpumask_test_cpu(cpu, buffer->cpumask))
5566 return 0;
5567
5568 cpu_buffer = buffer->buffers[cpu];
5569 return cpu_buffer->read;
5570 }
5571 EXPORT_SYMBOL_GPL(ring_buffer_read_events_cpu);
5572
5573 /**
5574 * ring_buffer_entries - get the number of entries in a buffer
5575 * @buffer: The ring buffer
5576 *
5577 * Returns the total number of entries in the ring buffer
5578 * (all CPU entries)
5579 */
5580 unsigned long ring_buffer_entries(struct trace_buffer *buffer)
5581 {
5582 struct ring_buffer_per_cpu *cpu_buffer;
5583 unsigned long entries = 0;
5584 int cpu;
5585
5586 /* if you care about this being correct, lock the buffer */
5587 for_each_buffer_cpu(buffer, cpu) {
5588 cpu_buffer = buffer->buffers[cpu];
5589 entries += rb_num_of_entries(cpu_buffer);
5590 }
5591
5592 return entries;
5593 }
5594 EXPORT_SYMBOL_GPL(ring_buffer_entries);
5595
5596 /**
5597 * ring_buffer_overruns - get the number of overruns in buffer
5598 * @buffer: The ring buffer
5599 *
5600 * Returns the total number of overruns in the ring buffer
5601 * (all CPU entries)
5602 */
5603 unsigned long ring_buffer_overruns(struct trace_buffer *buffer)
5604 {
5605 struct ring_buffer_per_cpu *cpu_buffer;
5606 unsigned long overruns = 0;
5607 int cpu;
5608
5609 /* if you care about this being correct, lock the buffer */
5610 for_each_buffer_cpu(buffer, cpu) {
5611 cpu_buffer = buffer->buffers[cpu];
5612 overruns += local_read(&cpu_buffer->overrun);
5613 }
5614
5615 return overruns;
5616 }
5617 EXPORT_SYMBOL_GPL(ring_buffer_overruns);
5618
5619 static bool rb_read_remote_meta_page(struct ring_buffer_per_cpu *cpu_buffer)
5620 {
5621 local_set(&cpu_buffer->entries, READ_ONCE(cpu_buffer->meta_page->entries));
5622 local_set(&cpu_buffer->overrun, READ_ONCE(cpu_buffer->meta_page->overrun));
5623 local_set(&cpu_buffer->pages_touched, READ_ONCE(cpu_buffer->meta_page->pages_touched));
5624 local_set(&cpu_buffer->pages_lost, READ_ONCE(cpu_buffer->meta_page->pages_lost));
5625
5626 return rb_num_of_entries(cpu_buffer);
5627 }
5628
5629 static void rb_update_remote_head(struct ring_buffer_per_cpu *cpu_buffer)
5630 {
5631 struct buffer_page *next, *orig;
5632 int retry = 3;
5633
5634 orig = next = cpu_buffer->head_page;
5635 rb_inc_page(&next);
5636
5637 /* Run after the writer */
5638 while (cpu_buffer->head_page->page->time_stamp > next->page->time_stamp) {
5639 rb_inc_page(&next);
5640
5641 rb_list_head_clear(cpu_buffer->head_page->list.prev);
5642 rb_inc_page(&cpu_buffer->head_page);
5643 rb_set_list_to_head(cpu_buffer->head_page->list.prev);
5644
5645 if (cpu_buffer->head_page == orig) {
5646 if (WARN_ON_ONCE(!(--retry)))
5647 return;
5648 }
5649 }
5650
5651 orig = cpu_buffer->commit_page = cpu_buffer->head_page;
5652 retry = 3;
5653
5654 while (cpu_buffer->commit_page->page->time_stamp < next->page->time_stamp) {
5655 rb_inc_page(&next);
5656 rb_inc_page(&cpu_buffer->commit_page);
5657
5658 if (cpu_buffer->commit_page == orig) {
5659 if (WARN_ON_ONCE(!(--retry)))
5660 return;
5661 }
5662 }
5663 }
5664
5665 static void rb_iter_reset(struct ring_buffer_iter *iter)
5666 {
5667 struct ring_buffer_per_cpu *cpu_buffer = iter->cpu_buffer;
5668
5669 if (cpu_buffer->remote) {
5670 rb_read_remote_meta_page(cpu_buffer);
5671 rb_update_remote_head(cpu_buffer);
5672 }
5673
5674 /* Iterator usage is expected to have record disabled */
5675 iter->head_page = cpu_buffer->reader_page;
5676 iter->head = cpu_buffer->reader_page->read;
5677 iter->next_event = iter->head;
5678 iter->missed_events = 0;
5679
5680 iter->cache_reader_page = iter->head_page;
5681 iter->cache_read = cpu_buffer->read;
5682 iter->cache_pages_removed = cpu_buffer->pages_removed;
5683
5684 if (iter->head) {
5685 iter->read_stamp = cpu_buffer->read_stamp;
5686 iter->page_stamp = cpu_buffer->reader_page->page->time_stamp;
5687 } else {
5688 iter->read_stamp = iter->head_page->page->time_stamp;
5689 iter->page_stamp = iter->read_stamp;
5690 }
5691 }
5692
5693 /**
5694 * ring_buffer_iter_reset - reset an iterator
5695 * @iter: The iterator to reset
5696 *
5697 * Resets the iterator, so that it will start from the beginning
5698 * again.
5699 */
5700 void ring_buffer_iter_reset(struct ring_buffer_iter *iter)
5701 {
5702 struct ring_buffer_per_cpu *cpu_buffer;
5703 unsigned long flags;
5704
5705 if (!iter)
5706 return;
5707
5708 cpu_buffer = iter->cpu_buffer;
5709
5710 raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
5711 rb_iter_reset(iter);
5712 raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
5713 }
5714 EXPORT_SYMBOL_GPL(ring_buffer_iter_reset);
5715
5716 /**
5717 * ring_buffer_iter_empty - check if an iterator has no more to read
5718 * @iter: The iterator to check
5719 */
5720 int ring_buffer_iter_empty(struct ring_buffer_iter *iter)
5721 {
5722 struct ring_buffer_per_cpu *cpu_buffer;
5723 struct buffer_page *reader;
5724 struct buffer_page *head_page;
5725 struct buffer_page *commit_page;
5726 struct buffer_page *curr_commit_page;
5727 unsigned commit;
5728 u64 curr_commit_ts;
5729 u64 commit_ts;
5730
5731 cpu_buffer = iter->cpu_buffer;
5732 reader = cpu_buffer->reader_page;
5733 head_page = cpu_buffer->head_page;
5734 commit_page = READ_ONCE(cpu_buffer->commit_page);
5735 commit_ts = commit_page->page->time_stamp;
5736
5737 /*
5738 * When the writer goes across pages, it issues a cmpxchg which
5739 * is a mb(), which will synchronize with the rmb here.
5740 * (see rb_tail_page_update())
5741 */
5742 smp_rmb();
5743 commit = rb_page_size(commit_page);
5744 /* We want to make sure that the commit page doesn't change */
5745 smp_rmb();
5746
5747 /* Make sure commit page didn't change */
5748 curr_commit_page = READ_ONCE(cpu_buffer->commit_page);
5749 curr_commit_ts = READ_ONCE(curr_commit_page->page->time_stamp);
5750
5751 /* If the commit page changed, then there's more data */
5752 if (curr_commit_page != commit_page ||
5753 curr_commit_ts != commit_ts)
5754 return 0;
5755
5756 /* Still racy, as it may return a false positive, but that's OK */
5757 return ((iter->head_page == commit_page && iter->head >= commit) ||
5758 (iter->head_page == reader && commit_page == head_page &&
5759 head_page->read == commit &&
5760 iter->head == rb_page_size(cpu_buffer->reader_page)));
5761 }
5762 EXPORT_SYMBOL_GPL(ring_buffer_iter_empty);
5763
5764 static void
5765 rb_update_read_stamp(struct ring_buffer_per_cpu *cpu_buffer,
5766 struct ring_buffer_event *event)
5767 {
5768 u64 delta;
5769
5770 switch (event->type_len) {
5771 case RINGBUF_TYPE_PADDING:
5772 return;
5773
5774 case RINGBUF_TYPE_TIME_EXTEND:
5775 delta = rb_event_time_stamp(event);
5776 cpu_buffer->read_stamp += delta;
5777 return;
5778
5779 case RINGBUF_TYPE_TIME_STAMP:
5780 delta = rb_event_time_stamp(event);
5781 delta = rb_fix_abs_ts(delta, cpu_buffer->read_stamp);
5782 cpu_buffer->read_stamp = delta;
5783 return;
5784
5785 case RINGBUF_TYPE_DATA:
5786 cpu_buffer->read_stamp += event->time_delta;
5787 return;
5788
5789 default:
5790 RB_WARN_ON(cpu_buffer, 1);
5791 }
5792 }
5793
5794 static void
5795 rb_update_iter_read_stamp(struct ring_buffer_iter *iter,
5796 struct ring_buffer_event *event)
5797 {
5798 u64 delta;
5799
5800 switch (event->type_len) {
5801 case RINGBUF_TYPE_PADDING:
5802 return;
5803
5804 case RINGBUF_TYPE_TIME_EXTEND:
5805 delta = rb_event_time_stamp(event);
5806 iter->read_stamp += delta;
5807 return;
5808
5809 case RINGBUF_TYPE_TIME_STAMP:
5810 delta = rb_event_time_stamp(event);
5811 delta = rb_fix_abs_ts(delta, iter->read_stamp);
5812 iter->read_stamp = delta;
5813 return;
5814
5815 case RINGBUF_TYPE_DATA:
5816 iter->read_stamp += event->time_delta;
5817 return;
5818
5819 default:
5820 RB_WARN_ON(iter->cpu_buffer, 1);
5821 }
5822 }
5823
5824 static struct buffer_page *
5825 __rb_get_reader_page_from_remote(struct ring_buffer_per_cpu *cpu_buffer)
5826 {
5827 struct buffer_page *new_reader, *prev_reader, *prev_head, *new_head, *last;
5828
5829 if (!rb_read_remote_meta_page(cpu_buffer))
5830 return NULL;
5831
5832 /* More to read on the reader page */
5833 if (cpu_buffer->reader_page->read < rb_page_size(cpu_buffer->reader_page)) {
5834 if (!cpu_buffer->reader_page->read)
5835 cpu_buffer->read_stamp = cpu_buffer->reader_page->page->time_stamp;
5836 return cpu_buffer->reader_page;
5837 }
5838
5839 prev_reader = cpu_buffer->subbuf_ids[cpu_buffer->meta_page->reader.id];
5840
5841 if (cpu_buffer->remote->swap_reader_page(cpu_buffer->cpu,
5842 cpu_buffer->remote->priv)) {
5843 pr_warn_ratelimited("Remote reader page swap failed\n");
5844 return NULL;
5845 }
5846 /* nr_pages doesn't include the reader page */
5847 if (WARN_ON_ONCE(cpu_buffer->meta_page->reader.id > cpu_buffer->nr_pages))
5848 return NULL;
5849
5850 new_reader = cpu_buffer->subbuf_ids[cpu_buffer->meta_page->reader.id];
5851
5852 WARN_ON_ONCE(prev_reader == new_reader);
5853
5854 prev_head = new_reader; /* New reader was also the previous head */
5855 new_head = prev_head;
5856 rb_inc_page(&new_head);
5857 last = prev_head;
5858 rb_dec_page(&last);
5859
5860 /* Clear the old HEAD flag */
5861 rb_list_head_clear(cpu_buffer->head_page->list.prev);
5862
5863 prev_reader->list.next = prev_head->list.next;
5864 prev_reader->list.prev = prev_head->list.prev;
5865
5866 /* Swap prev_reader with new_reader */
5867 last->list.next = &prev_reader->list;
5868 new_head->list.prev = &prev_reader->list;
5869
5870 new_reader->list.prev = &new_reader->list;
5871 new_reader->list.next = &new_head->list;
5872
5873 /* Reactivate the HEAD flag */
5874 rb_set_list_to_head(&last->list);
5875
5876 cpu_buffer->head_page = new_head;
5877 cpu_buffer->reader_page = new_reader;
5878 cpu_buffer->reader_page->read = 0;
5879 cpu_buffer->pages = &new_head->list;
5880 cpu_buffer->read_stamp = new_reader->page->time_stamp;
5881 cpu_buffer->lost_events = cpu_buffer->meta_page->reader.lost_events;
5882
5883 return rb_page_size(cpu_buffer->reader_page) ? cpu_buffer->reader_page : NULL;
5884 }
5885
5886 static struct buffer_page *
5887 __rb_get_reader_page(struct ring_buffer_per_cpu *cpu_buffer)
5888 {
5889 unsigned long max_loops = cpu_buffer->ring_meta ? cpu_buffer->nr_pages : 3;
5890 struct buffer_page *reader = NULL;
5891 unsigned long nr_loops = 0;
5892 unsigned long overwrite;
5893 unsigned long flags;
5894 int missed_events = 0;
5895 bool ret;
5896
5897 local_irq_save(flags);
5898 arch_spin_lock(&cpu_buffer->lock);
5899
5900 again:
5901 /*
5902 * This should normally only loop twice. But because the
5903 * start of the reader inserts an empty page, it causes a
5904 * case where we will loop three times. There should be no
5905 * reason to loop four times unless the ring buffer is a
5906 * recovered persistent ring buffer. For persistent ring buffers,
5907 * invalid pages are reset during recovery, so there may be more
5908 * than 3 contiguous pages can be empty, but less than nr_pages.
5909 */
5910 if (RB_WARN_ON(cpu_buffer, ++nr_loops > max_loops)) {
5911 reader = NULL;
5912 goto out;
5913 }
5914
5915 reader = cpu_buffer->reader_page;
5916
5917 /* If there's more to read, return this page */
5918 if (cpu_buffer->reader_page->read < rb_page_size(reader))
5919 goto out;
5920
5921 /* Never should we have an index greater than the size */
5922 if (RB_WARN_ON(cpu_buffer,
5923 cpu_buffer->reader_page->read > rb_page_size(reader)))
5924 goto out;
5925
5926 /* check if we caught up to the tail */
5927 reader = NULL;
5928 if (cpu_buffer->commit_page == cpu_buffer->reader_page)
5929 goto out;
5930
5931 /* Don't bother swapping if the ring buffer is empty */
5932 if (rb_num_of_entries(cpu_buffer) == 0)
5933 goto out;
5934
5935 /*
5936 * Reset the reader page to size zero.
5937 */
5938 local_set(&cpu_buffer->reader_page->write, 0);
5939 local_set(&cpu_buffer->reader_page->entries, 0);
5940 rb_init_data_page(cpu_buffer->reader_page->page);
5941 cpu_buffer->reader_page->real_end = 0;
5942
5943 spin:
5944 /*
5945 * Splice the empty reader page into the list around the head.
5946 */
5947 reader = rb_set_head_page(cpu_buffer);
5948 if (!reader)
5949 goto out;
5950 cpu_buffer->reader_page->list.next = rb_list_head(reader->list.next);
5951 cpu_buffer->reader_page->list.prev = reader->list.prev;
5952
5953 /*
5954 * cpu_buffer->pages just needs to point to the buffer, it
5955 * has no specific buffer page to point to. Lets move it out
5956 * of our way so we don't accidentally swap it.
5957 */
5958 cpu_buffer->pages = reader->list.prev;
5959
5960 /* The reader page will be pointing to the new head */
5961 rb_set_list_to_head(&cpu_buffer->reader_page->list);
5962
5963 /*
5964 * We want to make sure we read the overruns after we set up our
5965 * pointers to the next object. The writer side does a
5966 * cmpxchg to cross pages which acts as the mb on the writer
5967 * side. Note, the reader will constantly fail the swap
5968 * while the writer is updating the pointers, so this
5969 * guarantees that the overwrite recorded here is the one we
5970 * want to compare with the last_overrun.
5971 */
5972 smp_mb();
5973 overwrite = local_read(&(cpu_buffer->overrun));
5974
5975 /*
5976 * Here's the tricky part.
5977 *
5978 * We need to move the pointer past the header page.
5979 * But we can only do that if a writer is not currently
5980 * moving it. The page before the header page has the
5981 * flag bit '1' set if it is pointing to the page we want.
5982 * but if the writer is in the process of moving it
5983 * then it will be '2' or already moved '0'.
5984 */
5985
5986 ret = rb_head_page_replace(reader, cpu_buffer->reader_page);
5987
5988 /*
5989 * If we did not convert it, then we must try again.
5990 */
5991 if (!ret)
5992 goto spin;
5993
5994 if (rb_page_commit(reader) & RB_MISSED_EVENTS)
5995 missed_events = -1;
5996
5997 if (cpu_buffer->ring_meta)
5998 rb_update_meta_reader(cpu_buffer, reader);
5999
6000 /*
6001 * Yay! We succeeded in replacing the page.
6002 *
6003 * Now make the new head point back to the reader page.
6004 */
6005 rb_list_head(reader->list.next)->prev = &cpu_buffer->reader_page->list;
6006 rb_inc_page(&cpu_buffer->head_page);
6007
6008 cpu_buffer->cnt++;
6009 local_inc(&cpu_buffer->pages_read);
6010
6011 /* Finally update the reader page to the new head */
6012 cpu_buffer->reader_page = reader;
6013 cpu_buffer->reader_page->read = 0;
6014
6015 if (overwrite != cpu_buffer->last_overrun) {
6016 cpu_buffer->lost_events = overwrite - cpu_buffer->last_overrun;
6017 cpu_buffer->last_overrun = overwrite;
6018 }
6019
6020 goto again;
6021
6022 out:
6023 /* Update the read_stamp on the first event */
6024 if (reader && reader->read == 0)
6025 cpu_buffer->read_stamp = reader->page->time_stamp;
6026
6027 arch_spin_unlock(&cpu_buffer->lock);
6028 local_irq_restore(flags);
6029
6030 /*
6031 * The writer has preempt disable, wait for it. But not forever
6032 * Although, 1 second is pretty much "forever"
6033 */
6034 #define USECS_WAIT 1000000
6035 for (nr_loops = 0; nr_loops < USECS_WAIT; nr_loops++) {
6036 /* If the write is past the end of page, a writer is still updating it */
6037 if (likely(!reader || rb_page_write(reader) <= rb_page_capacity(reader)))
6038 break;
6039
6040 udelay(1);
6041
6042 /* Get the latest version of the reader write value */
6043 smp_rmb();
6044 }
6045
6046 /* The writer is not moving forward? Something is wrong */
6047 if (RB_WARN_ON(cpu_buffer, nr_loops == USECS_WAIT))
6048 reader = NULL;
6049
6050 /*
6051 * Make sure we see any padding after the write update
6052 * (see rb_reset_tail()).
6053 *
6054 * In addition, a writer may be writing on the reader page
6055 * if the page has not been fully filled, so the read barrier
6056 * is also needed to make sure we see the content of what is
6057 * committed by the writer (see rb_set_commit_to_write()).
6058 */
6059 smp_rmb();
6060
6061 if (!cpu_buffer->lost_events)
6062 cpu_buffer->lost_events = missed_events;
6063
6064 return reader;
6065 }
6066
6067 static struct buffer_page *
6068 rb_get_reader_page(struct ring_buffer_per_cpu *cpu_buffer)
6069 {
6070 return cpu_buffer->remote ? __rb_get_reader_page_from_remote(cpu_buffer) :
6071 __rb_get_reader_page(cpu_buffer);
6072 }
6073
6074 static void rb_advance_reader(struct ring_buffer_per_cpu *cpu_buffer)
6075 {
6076 struct ring_buffer_event *event;
6077 struct buffer_page *reader;
6078 unsigned length;
6079
6080 reader = rb_get_reader_page(cpu_buffer);
6081
6082 /* This function should not be called when buffer is empty */
6083 if (RB_WARN_ON(cpu_buffer, !reader))
6084 return;
6085
6086 event = rb_reader_event(cpu_buffer);
6087
6088 if (event->type_len <= RINGBUF_TYPE_DATA_TYPE_LEN_MAX)
6089 cpu_buffer->read++;
6090
6091 rb_update_read_stamp(cpu_buffer, event);
6092
6093 length = rb_event_length(event);
6094 cpu_buffer->reader_page->read += length;
6095 cpu_buffer->read_bytes += length;
6096 }
6097
6098 static void rb_advance_iter(struct ring_buffer_iter *iter)
6099 {
6100 struct ring_buffer_per_cpu *cpu_buffer;
6101
6102 cpu_buffer = iter->cpu_buffer;
6103
6104 /* If head == next_event then we need to jump to the next event */
6105 if (iter->head == iter->next_event) {
6106 /* If the event gets overwritten again, there's nothing to do */
6107 if (rb_iter_head_event(iter) == NULL)
6108 return;
6109 }
6110
6111 iter->head = iter->next_event;
6112
6113 /*
6114 * Check if we are at the end of the buffer.
6115 */
6116 if (iter->next_event >= rb_page_size(iter->head_page)) {
6117 /* discarded commits can make the page empty */
6118 if (iter->head_page == cpu_buffer->commit_page)
6119 return;
6120 rb_inc_iter(iter);
6121 return;
6122 }
6123
6124 rb_update_iter_read_stamp(iter, iter->event);
6125 }
6126
6127 static int rb_lost_events(struct ring_buffer_per_cpu *cpu_buffer)
6128 {
6129 return cpu_buffer->lost_events;
6130 }
6131
6132 static struct ring_buffer_event *
6133 rb_buffer_peek(struct ring_buffer_per_cpu *cpu_buffer, u64 *ts,
6134 unsigned long *lost_events)
6135 {
6136 struct ring_buffer_event *event;
6137 struct buffer_page *reader;
6138 int nr_loops = 0;
6139
6140 if (ts)
6141 *ts = 0;
6142 again:
6143 /*
6144 * We repeat when a time extend is encountered.
6145 * Since the time extend is always attached to a data event,
6146 * we should never loop more than once.
6147 * (We never hit the following condition more than twice).
6148 */
6149 if (RB_WARN_ON(cpu_buffer, ++nr_loops > 2))
6150 return NULL;
6151
6152 reader = rb_get_reader_page(cpu_buffer);
6153 if (!reader)
6154 return NULL;
6155
6156 event = rb_reader_event(cpu_buffer);
6157
6158 switch (event->type_len) {
6159 case RINGBUF_TYPE_PADDING:
6160 if (rb_null_event(event))
6161 RB_WARN_ON(cpu_buffer, 1);
6162 /*
6163 * Because the writer could be discarding every
6164 * event it creates (which would probably be bad)
6165 * if we were to go back to "again" then we may never
6166 * catch up, and will trigger the warn on, or lock
6167 * the box. Return the padding, and we will release
6168 * the current locks, and try again.
6169 */
6170 return event;
6171
6172 case RINGBUF_TYPE_TIME_EXTEND:
6173 /* Internal data, OK to advance */
6174 rb_advance_reader(cpu_buffer);
6175 goto again;
6176
6177 case RINGBUF_TYPE_TIME_STAMP:
6178 if (ts) {
6179 *ts = rb_event_time_stamp(event);
6180 *ts = rb_fix_abs_ts(*ts, reader->page->time_stamp);
6181 ring_buffer_normalize_time_stamp(cpu_buffer->buffer,
6182 cpu_buffer->cpu, ts);
6183 }
6184 /* Internal data, OK to advance */
6185 rb_advance_reader(cpu_buffer);
6186 goto again;
6187
6188 case RINGBUF_TYPE_DATA:
6189 if (ts && !(*ts)) {
6190 *ts = cpu_buffer->read_stamp + event->time_delta;
6191 ring_buffer_normalize_time_stamp(cpu_buffer->buffer,
6192 cpu_buffer->cpu, ts);
6193 }
6194 if (lost_events)
6195 *lost_events = rb_lost_events(cpu_buffer);
6196 return event;
6197
6198 default:
6199 RB_WARN_ON(cpu_buffer, 1);
6200 }
6201
6202 return NULL;
6203 }
6204 EXPORT_SYMBOL_GPL(ring_buffer_peek);
6205
6206 static struct ring_buffer_event *
6207 rb_iter_peek(struct ring_buffer_iter *iter, u64 *ts)
6208 {
6209 struct trace_buffer *buffer;
6210 struct ring_buffer_per_cpu *cpu_buffer;
6211 struct ring_buffer_event *event;
6212 unsigned long nr_loops = 0;
6213 unsigned long max_loops;
6214
6215 if (ts)
6216 *ts = 0;
6217
6218 cpu_buffer = iter->cpu_buffer;
6219 buffer = cpu_buffer->buffer;
6220 max_loops = cpu_buffer->ring_meta ? cpu_buffer->nr_pages : 3;
6221
6222 /*
6223 * Check if someone performed a consuming read to the buffer
6224 * or removed some pages from the buffer. In these cases,
6225 * iterator was invalidated and we need to reset it.
6226 */
6227 if (unlikely(iter->cache_read != cpu_buffer->read ||
6228 iter->cache_reader_page != cpu_buffer->reader_page ||
6229 iter->cache_pages_removed != cpu_buffer->pages_removed))
6230 rb_iter_reset(iter);
6231
6232 again:
6233 if (ring_buffer_iter_empty(iter))
6234 return NULL;
6235
6236 /*
6237 * As the writer can mess with what the iterator is trying
6238 * to read, just give up if we fail to get an event after
6239 * three tries. The iterator is not as reliable when reading
6240 * the ring buffer with an active write as the consumer is.
6241 * Do not warn if the three failures is reached.
6242 */
6243 if (++nr_loops > max_loops)
6244 return NULL;
6245
6246 if (rb_per_cpu_empty(cpu_buffer))
6247 return NULL;
6248
6249 if (iter->head >= rb_page_size(iter->head_page)) {
6250 rb_inc_iter(iter);
6251 goto again;
6252 }
6253
6254 event = rb_iter_head_event(iter);
6255 if (!event)
6256 goto again;
6257
6258 switch (event->type_len) {
6259 case RINGBUF_TYPE_PADDING:
6260 if (rb_null_event(event)) {
6261 rb_inc_iter(iter);
6262 goto again;
6263 }
6264 rb_advance_iter(iter);
6265 return event;
6266
6267 case RINGBUF_TYPE_TIME_EXTEND:
6268 /* Internal data, OK to advance */
6269 rb_advance_iter(iter);
6270 goto again;
6271
6272 case RINGBUF_TYPE_TIME_STAMP:
6273 if (ts) {
6274 *ts = rb_event_time_stamp(event);
6275 *ts = rb_fix_abs_ts(*ts, iter->head_page->page->time_stamp);
6276 ring_buffer_normalize_time_stamp(cpu_buffer->buffer,
6277 cpu_buffer->cpu, ts);
6278 }
6279 /* Internal data, OK to advance */
6280 rb_advance_iter(iter);
6281 goto again;
6282
6283 case RINGBUF_TYPE_DATA:
6284 if (ts && !(*ts)) {
6285 *ts = iter->read_stamp + event->time_delta;
6286 ring_buffer_normalize_time_stamp(buffer,
6287 cpu_buffer->cpu, ts);
6288 }
6289 return event;
6290
6291 default:
6292 RB_WARN_ON(cpu_buffer, 1);
6293 }
6294
6295 return NULL;
6296 }
6297 EXPORT_SYMBOL_GPL(ring_buffer_iter_peek);
6298
6299 static inline bool rb_reader_lock(struct ring_buffer_per_cpu *cpu_buffer)
6300 {
6301 if (likely(!in_nmi())) {
6302 raw_spin_lock(&cpu_buffer->reader_lock);
6303 return true;
6304 }
6305
6306 /*
6307 * If an NMI die dumps out the content of the ring buffer
6308 * trylock must be used to prevent a deadlock if the NMI
6309 * preempted a task that holds the ring buffer locks. If
6310 * we get the lock then all is fine, if not, then continue
6311 * to do the read, but this can corrupt the ring buffer,
6312 * so it must be permanently disabled from future writes.
6313 * Reading from NMI is a oneshot deal.
6314 */
6315 if (raw_spin_trylock(&cpu_buffer->reader_lock))
6316 return true;
6317
6318 /* Continue without locking, but disable the ring buffer */
6319 atomic_inc(&cpu_buffer->record_disabled);
6320 return false;
6321 }
6322
6323 static inline void
6324 rb_reader_unlock(struct ring_buffer_per_cpu *cpu_buffer, bool locked)
6325 {
6326 if (likely(locked))
6327 raw_spin_unlock(&cpu_buffer->reader_lock);
6328 }
6329
6330 /**
6331 * ring_buffer_peek - peek at the next event to be read
6332 * @buffer: The ring buffer to read
6333 * @cpu: The cpu to peak at
6334 * @ts: The timestamp counter of this event.
6335 * @lost_events: a variable to store if events were lost (may be NULL)
6336 *
6337 * This will return the event that will be read next, but does
6338 * not consume the data.
6339 */
6340 struct ring_buffer_event *
6341 ring_buffer_peek(struct trace_buffer *buffer, int cpu, u64 *ts,
6342 unsigned long *lost_events)
6343 {
6344 struct ring_buffer_per_cpu *cpu_buffer = buffer->buffers[cpu];
6345 struct ring_buffer_event *event;
6346 unsigned long flags;
6347 bool dolock;
6348
6349 if (!cpumask_test_cpu(cpu, buffer->cpumask))
6350 return NULL;
6351
6352 again:
6353 local_irq_save(flags);
6354 dolock = rb_reader_lock(cpu_buffer);
6355 event = rb_buffer_peek(cpu_buffer, ts, lost_events);
6356 if (event && event->type_len == RINGBUF_TYPE_PADDING)
6357 rb_advance_reader(cpu_buffer);
6358 rb_reader_unlock(cpu_buffer, dolock);
6359 local_irq_restore(flags);
6360
6361 if (event && event->type_len == RINGBUF_TYPE_PADDING)
6362 goto again;
6363
6364 return event;
6365 }
6366
6367 /** ring_buffer_iter_dropped - report if there are dropped events
6368 * @iter: The ring buffer iterator
6369 *
6370 * Returns true if there was dropped events since the last peek.
6371 */
6372 bool ring_buffer_iter_dropped(struct ring_buffer_iter *iter)
6373 {
6374 return iter->missed_events != 0;
6375 }
6376 EXPORT_SYMBOL_GPL(ring_buffer_iter_dropped);
6377
6378 /**
6379 * ring_buffer_iter_peek - peek at the next event to be read
6380 * @iter: The ring buffer iterator
6381 * @ts: The timestamp counter of this event.
6382 *
6383 * This will return the event that will be read next, but does
6384 * not increment the iterator.
6385 */
6386 struct ring_buffer_event *
6387 ring_buffer_iter_peek(struct ring_buffer_iter *iter, u64 *ts)
6388 {
6389 struct ring_buffer_per_cpu *cpu_buffer = iter->cpu_buffer;
6390 struct ring_buffer_event *event;
6391 unsigned long flags;
6392
6393 again:
6394 raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
6395 event = rb_iter_peek(iter, ts);
6396 raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
6397
6398 if (event && event->type_len == RINGBUF_TYPE_PADDING)
6399 goto again;
6400
6401 return event;
6402 }
6403
6404 /**
6405 * ring_buffer_consume - return an event and consume it
6406 * @buffer: The ring buffer to get the next event from
6407 * @cpu: the cpu to read the buffer from
6408 * @ts: a variable to store the timestamp (may be NULL)
6409 * @lost_events: a variable to store if events were lost (may be NULL)
6410 *
6411 * Returns the next event in the ring buffer, and that event is consumed.
6412 * Meaning, that sequential reads will keep returning a different event,
6413 * and eventually empty the ring buffer if the producer is slower.
6414 */
6415 struct ring_buffer_event *
6416 ring_buffer_consume(struct trace_buffer *buffer, int cpu, u64 *ts,
6417 unsigned long *lost_events)
6418 {
6419 struct ring_buffer_per_cpu *cpu_buffer;
6420 struct ring_buffer_event *event = NULL;
6421 unsigned long flags;
6422 bool dolock;
6423
6424 again:
6425 /* might be called in atomic */
6426 preempt_disable();
6427
6428 if (!cpumask_test_cpu(cpu, buffer->cpumask))
6429 goto out;
6430
6431 cpu_buffer = buffer->buffers[cpu];
6432 local_irq_save(flags);
6433 dolock = rb_reader_lock(cpu_buffer);
6434
6435 event = rb_buffer_peek(cpu_buffer, ts, lost_events);
6436 if (event) {
6437 cpu_buffer->lost_events = 0;
6438 rb_advance_reader(cpu_buffer);
6439 }
6440
6441 rb_reader_unlock(cpu_buffer, dolock);
6442 local_irq_restore(flags);
6443
6444 out:
6445 preempt_enable();
6446
6447 if (event && event->type_len == RINGBUF_TYPE_PADDING)
6448 goto again;
6449
6450 return event;
6451 }
6452 EXPORT_SYMBOL_GPL(ring_buffer_consume);
6453
6454 /**
6455 * ring_buffer_read_start - start a non consuming read of the buffer
6456 * @buffer: The ring buffer to read from
6457 * @cpu: The cpu buffer to iterate over
6458 * @flags: gfp flags to use for memory allocation
6459 *
6460 * This creates an iterator to allow non-consuming iteration through
6461 * the buffer. If the buffer is disabled for writing, it will produce
6462 * the same information each time, but if the buffer is still writing
6463 * then the first hit of a write will cause the iteration to stop.
6464 *
6465 * Must be paired with ring_buffer_read_finish.
6466 */
6467 struct ring_buffer_iter *
6468 ring_buffer_read_start(struct trace_buffer *buffer, int cpu, gfp_t flags)
6469 {
6470 struct ring_buffer_iter *iter __free(kfree) = kzalloc_obj(*iter, flags);
6471 struct ring_buffer_per_cpu *cpu_buffer;
6472
6473 if (!iter)
6474 return NULL;
6475
6476 if (!cpumask_test_cpu(cpu, buffer->cpumask))
6477 return NULL;
6478
6479 cpu_buffer = buffer->buffers[cpu];
6480
6481 /*
6482 * Only KDB is using GFP_ATOMIC, for the others, lock the buffer to
6483 * prevent concurrent resizing.
6484 */
6485 if (gfpflags_allow_blocking(flags))
6486 mutex_lock(&buffer->mutex);
6487
6488 atomic_inc(&cpu_buffer->resize_disabled);
6489
6490 if (gfpflags_allow_blocking(flags))
6491 mutex_unlock(&buffer->mutex);
6492
6493 /* Holds the entire event: data and meta data. */
6494 iter->event_size = rb_page_capacity(READ_ONCE(cpu_buffer->reader_page));
6495 iter->event = kmalloc(iter->event_size, flags);
6496 if (!iter->event) {
6497 atomic_dec(&cpu_buffer->resize_disabled);
6498 return NULL;
6499 }
6500 iter->cpu_buffer = cpu_buffer;
6501
6502 guard(raw_spinlock_irqsave)(&cpu_buffer->reader_lock);
6503 arch_spin_lock(&cpu_buffer->lock);
6504 rb_iter_reset(iter);
6505 arch_spin_unlock(&cpu_buffer->lock);
6506
6507 return_ptr(iter);
6508 }
6509 EXPORT_SYMBOL_GPL(ring_buffer_read_start);
6510
6511 /**
6512 * ring_buffer_read_finish - finish reading the iterator of the buffer
6513 * @iter: The iterator retrieved by ring_buffer_start
6514 *
6515 * This re-enables resizing of the buffer, and frees the iterator.
6516 */
6517 void
6518 ring_buffer_read_finish(struct ring_buffer_iter *iter)
6519 {
6520 struct ring_buffer_per_cpu *cpu_buffer = iter->cpu_buffer;
6521
6522 /* Use this opportunity to check the integrity of the ring buffer. */
6523 rb_check_pages(cpu_buffer);
6524
6525 atomic_dec(&cpu_buffer->resize_disabled);
6526 kfree(iter->event);
6527 kfree(iter);
6528 }
6529 EXPORT_SYMBOL_GPL(ring_buffer_read_finish);
6530
6531 /**
6532 * ring_buffer_iter_advance - advance the iterator to the next location
6533 * @iter: The ring buffer iterator
6534 *
6535 * Move the location of the iterator such that the next read will
6536 * be the next location of the iterator.
6537 */
6538 void ring_buffer_iter_advance(struct ring_buffer_iter *iter)
6539 {
6540 struct ring_buffer_per_cpu *cpu_buffer = iter->cpu_buffer;
6541 unsigned long flags;
6542
6543 raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
6544 iter->missed_events = 0;
6545 rb_advance_iter(iter);
6546
6547 raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
6548 }
6549 EXPORT_SYMBOL_GPL(ring_buffer_iter_advance);
6550
6551 /**
6552 * ring_buffer_size - return the size of the ring buffer (in bytes)
6553 * @buffer: The ring buffer.
6554 * @cpu: The CPU to get ring buffer size from.
6555 */
6556 unsigned long ring_buffer_size(struct trace_buffer *buffer, int cpu)
6557 {
6558 if (!cpumask_test_cpu(cpu, buffer->cpumask))
6559 return 0;
6560
6561 return rb_subbuf_capacity(buffer) * buffer->buffers[cpu]->nr_pages;
6562 }
6563 EXPORT_SYMBOL_GPL(ring_buffer_size);
6564
6565 /**
6566 * ring_buffer_max_event_size - return the max data size of an event
6567 * @buffer: The ring buffer.
6568 *
6569 * Returns the maximum size an event can be.
6570 */
6571 unsigned long ring_buffer_max_event_size(struct trace_buffer *buffer)
6572 {
6573 /* If abs timestamp is requested, events have a timestamp too */
6574 if (ring_buffer_time_stamp_abs(buffer))
6575 return rb_subbuf_max_data_size(buffer) - RB_LEN_TIME_EXTEND;
6576
6577 return rb_subbuf_max_data_size(buffer);
6578 }
6579 EXPORT_SYMBOL_GPL(ring_buffer_max_event_size);
6580
6581 static void rb_clear_buffer_page(struct buffer_page *page)
6582 {
6583 local_set(&page->write, 0);
6584 local_set(&page->entries, 0);
6585 rb_init_data_page(page->page);
6586 page->read = 0;
6587 }
6588
6589 /*
6590 * When the buffer is memory mapped to user space, each sub buffer
6591 * has a unique id that is used by the meta data to tell the user
6592 * where the current reader page is.
6593 *
6594 * For a normal allocated ring buffer, the id is saved in the buffer page
6595 * id field, and updated via this function.
6596 *
6597 * But for a fixed memory mapped buffer, the id is already assigned for
6598 * fixed memory ordering in the memory layout and can not be used. Instead
6599 * the index of where the page lies in the memory layout is used.
6600 *
6601 * For the normal pages, set the buffer page id with the passed in @id
6602 * value and return that.
6603 *
6604 * For fixed memory mapped pages, get the page index in the memory layout
6605 * and return that as the id.
6606 */
6607 static int rb_page_id(struct ring_buffer_per_cpu *cpu_buffer,
6608 struct buffer_page *bpage, int id)
6609 {
6610 /*
6611 * For boot buffers, the id is the index,
6612 * otherwise, set the buffer page with this id
6613 */
6614 if (cpu_buffer->ring_meta)
6615 id = rb_meta_subbuf_idx(cpu_buffer->ring_meta, bpage->page);
6616 else
6617 bpage->id = id;
6618
6619 return id;
6620 }
6621
6622 static void rb_update_meta_page(struct ring_buffer_per_cpu *cpu_buffer)
6623 {
6624 struct trace_buffer_meta *meta = cpu_buffer->meta_page;
6625
6626 if (!meta)
6627 return;
6628
6629 meta->reader.read = cpu_buffer->reader_page->read;
6630 meta->reader.id = rb_page_id(cpu_buffer, cpu_buffer->reader_page,
6631 cpu_buffer->reader_page->id);
6632
6633 meta->reader.lost_events = cpu_buffer->lost_events;
6634
6635 meta->entries = local_read(&cpu_buffer->entries);
6636 meta->overrun = local_read(&cpu_buffer->overrun);
6637 meta->read = cpu_buffer->read;
6638 meta->pages_lost = local_read(&cpu_buffer->pages_lost);
6639 meta->pages_touched = local_read(&cpu_buffer->pages_touched);
6640
6641 /* Some archs do not have data cache coherency between kernel and user-space */
6642 flush_kernel_vmap_range(cpu_buffer->meta_page, PAGE_SIZE);
6643 }
6644
6645 static void
6646 rb_reset_cpu(struct ring_buffer_per_cpu *cpu_buffer)
6647 {
6648 struct buffer_page *page;
6649
6650 if (cpu_buffer->remote) {
6651 if (!cpu_buffer->remote->reset)
6652 return;
6653
6654 cpu_buffer->remote->reset(cpu_buffer->cpu, cpu_buffer->remote->priv);
6655 rb_read_remote_meta_page(cpu_buffer);
6656
6657 /* Read related values, not covered by the meta-page */
6658 local_set(&cpu_buffer->pages_read, 0);
6659 cpu_buffer->read = 0;
6660 cpu_buffer->read_bytes = 0;
6661 cpu_buffer->last_overrun = 0;
6662 cpu_buffer->reader_page->read = 0;
6663
6664 return;
6665 }
6666
6667 rb_head_page_deactivate(cpu_buffer);
6668
6669 cpu_buffer->head_page
6670 = list_entry(cpu_buffer->pages, struct buffer_page, list);
6671 rb_clear_buffer_page(cpu_buffer->head_page);
6672 list_for_each_entry(page, cpu_buffer->pages, list) {
6673 rb_clear_buffer_page(page);
6674 }
6675
6676 cpu_buffer->tail_page = cpu_buffer->head_page;
6677 cpu_buffer->commit_page = cpu_buffer->head_page;
6678
6679 INIT_LIST_HEAD(&cpu_buffer->reader_page->list);
6680 INIT_LIST_HEAD(&cpu_buffer->new_pages);
6681 rb_clear_buffer_page(cpu_buffer->reader_page);
6682
6683 local_set(&cpu_buffer->entries_bytes, 0);
6684 local_set(&cpu_buffer->overrun, 0);
6685 local_set(&cpu_buffer->commit_overrun, 0);
6686 local_set(&cpu_buffer->dropped_events, 0);
6687 local_set(&cpu_buffer->entries, 0);
6688 local_set(&cpu_buffer->committing, 0);
6689 local_set(&cpu_buffer->commits, 0);
6690 local_set(&cpu_buffer->pages_touched, 0);
6691 local_set(&cpu_buffer->pages_lost, 0);
6692 local_set(&cpu_buffer->pages_read, 0);
6693 cpu_buffer->last_pages_touch = 0;
6694 cpu_buffer->shortest_full = 0;
6695 cpu_buffer->read = 0;
6696 cpu_buffer->read_bytes = 0;
6697
6698 rb_time_set(&cpu_buffer->write_stamp, 0);
6699 rb_time_set(&cpu_buffer->before_stamp, 0);
6700
6701 memset(cpu_buffer->event_stamp, 0, sizeof(cpu_buffer->event_stamp));
6702
6703 cpu_buffer->lost_events = 0;
6704 cpu_buffer->last_overrun = 0;
6705
6706 rb_head_page_activate(cpu_buffer);
6707 cpu_buffer->pages_removed = 0;
6708
6709 rb_update_meta_page(cpu_buffer);
6710 if (cpu_buffer->ring_meta) {
6711 struct ring_buffer_cpu_meta *meta = cpu_buffer->ring_meta;
6712
6713 meta->commit_buffer = meta->head_buffer;
6714 }
6715 }
6716
6717 /* Must have disabled the cpu buffer then done a synchronize_rcu */
6718 static void reset_disabled_cpu_buffer(struct ring_buffer_per_cpu *cpu_buffer)
6719 {
6720 guard(raw_spinlock_irqsave)(&cpu_buffer->reader_lock);
6721
6722 if (RB_WARN_ON(cpu_buffer, local_read(&cpu_buffer->committing)))
6723 return;
6724
6725 arch_spin_lock(&cpu_buffer->lock);
6726
6727 rb_reset_cpu(cpu_buffer);
6728
6729 arch_spin_unlock(&cpu_buffer->lock);
6730 }
6731
6732 /**
6733 * ring_buffer_reset_cpu - reset a ring buffer per CPU buffer
6734 * @buffer: The ring buffer to reset a per cpu buffer of
6735 * @cpu: The CPU buffer to be reset
6736 */
6737 void ring_buffer_reset_cpu(struct trace_buffer *buffer, int cpu)
6738 {
6739 struct ring_buffer_per_cpu *cpu_buffer = buffer->buffers[cpu];
6740
6741 if (!cpumask_test_cpu(cpu, buffer->cpumask))
6742 return;
6743
6744 /* prevent another thread from changing buffer sizes */
6745 mutex_lock(&buffer->mutex);
6746
6747 atomic_inc(&cpu_buffer->resize_disabled);
6748 atomic_inc(&cpu_buffer->record_disabled);
6749
6750 /* Make sure all commits have finished */
6751 synchronize_rcu();
6752
6753 reset_disabled_cpu_buffer(cpu_buffer);
6754
6755 atomic_dec(&cpu_buffer->record_disabled);
6756 atomic_dec(&cpu_buffer->resize_disabled);
6757
6758 mutex_unlock(&buffer->mutex);
6759 }
6760 EXPORT_SYMBOL_GPL(ring_buffer_reset_cpu);
6761
6762 /* Flag to ensure proper resetting of atomic variables */
6763 #define RESET_BIT (1 << 30)
6764
6765 /**
6766 * ring_buffer_reset_online_cpus - reset a ring buffer per CPU buffer
6767 * @buffer: The ring buffer to reset a per cpu buffer of
6768 */
6769 void ring_buffer_reset_online_cpus(struct trace_buffer *buffer)
6770 {
6771 struct ring_buffer_per_cpu *cpu_buffer;
6772 int cpu;
6773
6774 /* prevent another thread from changing buffer sizes */
6775 mutex_lock(&buffer->mutex);
6776
6777 for_each_online_buffer_cpu(buffer, cpu) {
6778 cpu_buffer = buffer->buffers[cpu];
6779
6780 atomic_add(RESET_BIT, &cpu_buffer->resize_disabled);
6781 atomic_inc(&cpu_buffer->record_disabled);
6782 }
6783
6784 /* Make sure all commits have finished */
6785 synchronize_rcu();
6786
6787 for_each_buffer_cpu(buffer, cpu) {
6788 cpu_buffer = buffer->buffers[cpu];
6789
6790 /*
6791 * If a CPU came online during the synchronize_rcu(), then
6792 * ignore it.
6793 */
6794 if (!(atomic_read(&cpu_buffer->resize_disabled) & RESET_BIT))
6795 continue;
6796
6797 reset_disabled_cpu_buffer(cpu_buffer);
6798
6799 atomic_dec(&cpu_buffer->record_disabled);
6800 atomic_sub(RESET_BIT, &cpu_buffer->resize_disabled);
6801 }
6802
6803 mutex_unlock(&buffer->mutex);
6804 }
6805
6806 /**
6807 * ring_buffer_reset - reset a ring buffer
6808 * @buffer: The ring buffer to reset all cpu buffers
6809 */
6810 void ring_buffer_reset(struct trace_buffer *buffer)
6811 {
6812 struct ring_buffer_per_cpu *cpu_buffer;
6813 int cpu;
6814
6815 /* prevent another thread from changing buffer sizes */
6816 mutex_lock(&buffer->mutex);
6817
6818 for_each_buffer_cpu(buffer, cpu) {
6819 cpu_buffer = buffer->buffers[cpu];
6820
6821 atomic_inc(&cpu_buffer->resize_disabled);
6822 atomic_inc(&cpu_buffer->record_disabled);
6823 }
6824
6825 /* Make sure all commits have finished */
6826 synchronize_rcu();
6827
6828 for_each_buffer_cpu(buffer, cpu) {
6829 cpu_buffer = buffer->buffers[cpu];
6830
6831 reset_disabled_cpu_buffer(cpu_buffer);
6832
6833 atomic_dec(&cpu_buffer->record_disabled);
6834 atomic_dec(&cpu_buffer->resize_disabled);
6835 }
6836
6837 mutex_unlock(&buffer->mutex);
6838 }
6839 EXPORT_SYMBOL_GPL(ring_buffer_reset);
6840
6841 /**
6842 * ring_buffer_empty - is the ring buffer empty?
6843 * @buffer: The ring buffer to test
6844 */
6845 bool ring_buffer_empty(struct trace_buffer *buffer)
6846 {
6847 struct ring_buffer_per_cpu *cpu_buffer;
6848 unsigned long flags;
6849 bool dolock;
6850 bool ret;
6851 int cpu;
6852
6853 /* yes this is racy, but if you don't like the race, lock the buffer */
6854 for_each_buffer_cpu(buffer, cpu) {
6855 cpu_buffer = buffer->buffers[cpu];
6856 local_irq_save(flags);
6857 dolock = rb_reader_lock(cpu_buffer);
6858 ret = rb_per_cpu_empty(cpu_buffer);
6859 rb_reader_unlock(cpu_buffer, dolock);
6860 local_irq_restore(flags);
6861
6862 if (!ret)
6863 return false;
6864 }
6865
6866 return true;
6867 }
6868 EXPORT_SYMBOL_GPL(ring_buffer_empty);
6869
6870 /**
6871 * ring_buffer_empty_cpu - is a cpu buffer of a ring buffer empty?
6872 * @buffer: The ring buffer
6873 * @cpu: The CPU buffer to test
6874 */
6875 bool ring_buffer_empty_cpu(struct trace_buffer *buffer, int cpu)
6876 {
6877 struct ring_buffer_per_cpu *cpu_buffer;
6878 unsigned long flags;
6879 bool dolock;
6880 bool ret;
6881
6882 if (!cpumask_test_cpu(cpu, buffer->cpumask))
6883 return true;
6884
6885 cpu_buffer = buffer->buffers[cpu];
6886 local_irq_save(flags);
6887 dolock = rb_reader_lock(cpu_buffer);
6888 ret = rb_per_cpu_empty(cpu_buffer);
6889 rb_reader_unlock(cpu_buffer, dolock);
6890 local_irq_restore(flags);
6891
6892 return ret;
6893 }
6894 EXPORT_SYMBOL_GPL(ring_buffer_empty_cpu);
6895
6896 int ring_buffer_poll_remote(struct trace_buffer *buffer, int cpu)
6897 {
6898 struct ring_buffer_per_cpu *cpu_buffer;
6899
6900 if (cpu != RING_BUFFER_ALL_CPUS) {
6901 if (!cpumask_test_cpu(cpu, buffer->cpumask))
6902 return -EINVAL;
6903
6904 cpu_buffer = buffer->buffers[cpu];
6905
6906 guard(raw_spinlock)(&cpu_buffer->reader_lock);
6907 if (rb_read_remote_meta_page(cpu_buffer))
6908 rb_wakeups(buffer, cpu_buffer);
6909
6910 return 0;
6911 }
6912
6913 guard(cpus_read_lock)();
6914
6915 /*
6916 * Make sure all the ring buffers are up to date before we start reading
6917 * them.
6918 */
6919 for_each_buffer_cpu(buffer, cpu) {
6920 cpu_buffer = buffer->buffers[cpu];
6921
6922 guard(raw_spinlock)(&cpu_buffer->reader_lock);
6923 rb_read_remote_meta_page(cpu_buffer);
6924 }
6925
6926 for_each_buffer_cpu(buffer, cpu) {
6927 cpu_buffer = buffer->buffers[cpu];
6928
6929 if (rb_num_of_entries(cpu_buffer))
6930 rb_wakeups(buffer, cpu_buffer);
6931 }
6932
6933 return 0;
6934 }
6935
6936 #ifdef CONFIG_RING_BUFFER_ALLOW_SWAP
6937 /**
6938 * ring_buffer_swap_cpu - swap a CPU buffer between two ring buffers
6939 * @buffer_a: One buffer to swap with
6940 * @buffer_b: The other buffer to swap with
6941 * @cpu: the CPU of the buffers to swap
6942 *
6943 * This function is useful for tracers that want to take a "snapshot"
6944 * of a CPU buffer and has another back up buffer lying around.
6945 * it is expected that the tracer handles the cpu buffer not being
6946 * used at the moment.
6947 */
6948 int ring_buffer_swap_cpu(struct trace_buffer *buffer_a,
6949 struct trace_buffer *buffer_b, int cpu)
6950 {
6951 struct ring_buffer_per_cpu *cpu_buffer_a;
6952 struct ring_buffer_per_cpu *cpu_buffer_b;
6953 int ret = -EBUSY;
6954
6955 if (!cpumask_test_cpu(cpu, buffer_a->cpumask) ||
6956 !cpumask_test_cpu(cpu, buffer_b->cpumask))
6957 return -EINVAL;
6958
6959 cpu_buffer_a = buffer_a->buffers[cpu];
6960 cpu_buffer_b = buffer_b->buffers[cpu];
6961
6962 /* It's up to the callers to not try to swap static buffers */
6963 if (WARN_ON_ONCE(rb_is_static(cpu_buffer_a) || rb_is_static(cpu_buffer_b)))
6964 return -EBUSY;
6965
6966 /* At least make sure the two buffers are somewhat the same */
6967 if (cpu_buffer_a->nr_pages != cpu_buffer_b->nr_pages)
6968 return -EINVAL;
6969
6970 if (buffer_a->subbuf_order != buffer_b->subbuf_order)
6971 return -EINVAL;
6972
6973 if (atomic_read(&buffer_a->record_disabled))
6974 return -EAGAIN;
6975
6976 if (atomic_read(&buffer_b->record_disabled))
6977 return -EAGAIN;
6978
6979 if (atomic_read(&cpu_buffer_a->record_disabled))
6980 return -EAGAIN;
6981
6982 if (atomic_read(&cpu_buffer_b->record_disabled))
6983 return -EAGAIN;
6984
6985 /*
6986 * We can't do a synchronize_rcu here because this
6987 * function can be called in atomic context.
6988 * Normally this will be called from the same CPU as cpu.
6989 * If not it's up to the caller to protect this.
6990 */
6991 atomic_inc(&cpu_buffer_a->record_disabled);
6992 atomic_inc(&cpu_buffer_b->record_disabled);
6993
6994 /* Do not swap if either buffer is in the process of writing */
6995 if (cpu_buffer_a->current_context)
6996 goto out_dec;
6997 if (cpu_buffer_b->current_context)
6998 goto out_dec;
6999
7000 /*
7001 * When resize is in progress, we cannot swap it because
7002 * it will mess the state of the cpu buffer.
7003 */
7004 if (atomic_read(&buffer_a->resizing))
7005 goto out_dec;
7006 if (atomic_read(&buffer_b->resizing))
7007 goto out_dec;
7008
7009 buffer_a->buffers[cpu] = cpu_buffer_b;
7010 buffer_b->buffers[cpu] = cpu_buffer_a;
7011
7012 cpu_buffer_b->buffer = buffer_a;
7013 cpu_buffer_a->buffer = buffer_b;
7014
7015 ret = 0;
7016
7017 out_dec:
7018 atomic_dec(&cpu_buffer_a->record_disabled);
7019 atomic_dec(&cpu_buffer_b->record_disabled);
7020 return ret;
7021 }
7022 EXPORT_SYMBOL_GPL(ring_buffer_swap_cpu);
7023 #endif /* CONFIG_RING_BUFFER_ALLOW_SWAP */
7024
7025 /**
7026 * ring_buffer_alloc_read_page - allocate a page to read from buffer
7027 * @buffer: the buffer to allocate for.
7028 * @cpu: the cpu buffer to allocate.
7029 * @rpage: pointer to pass in an already allocated page (can be NULL)
7030 * and returns the allocated page.
7031 *
7032 * This function is used in conjunction with ring_buffer_read_page().
7033 * When reading a full page from the ring buffer, these functions
7034 * can be used to speed up the process. The calling function should
7035 * allocate a few pages first with this function. Then when it
7036 * needs to get pages from the ring buffer, it passes the result
7037 * of this function into ring_buffer_read_page(), which will swap
7038 * the page that was allocated, with the read page of the buffer.
7039 *
7040 * If @rpage is provided, and it has a different order than the current
7041 * subbuffer order, its payload will be freed and re-allocated. If it
7042 * already matches the order, it is simply returned.
7043 *
7044 * Returns:
7045 * 0 on success, < 0 on error
7046 */
7047 int ring_buffer_alloc_read_page(struct trace_buffer *buffer, int cpu,
7048 struct buffer_data_read_page **rpage)
7049 {
7050 struct ring_buffer_per_cpu *cpu_buffer;
7051 unsigned long flags;
7052 unsigned int order;
7053
7054 if (!cpumask_test_cpu(cpu, buffer->cpumask))
7055 return -ENODEV;
7056
7057 if (!rpage)
7058 return -EINVAL;
7059
7060 order = READ_ONCE(buffer->subbuf_order);
7061
7062 if (*rpage) {
7063 if ((*rpage)->order == order)
7064 return 0;
7065
7066 /* We can reuse rpage, but we discard the payload */
7067 free_pages((unsigned long)(*rpage)->data, (*rpage)->order);
7068 (*rpage)->data = NULL;
7069 } else {
7070 *rpage = kzalloc_obj(**rpage);
7071 if (!*rpage)
7072 return -ENOMEM;
7073 }
7074
7075 (*rpage)->order = order;
7076 cpu_buffer = buffer->buffers[cpu];
7077
7078 local_irq_save(flags);
7079 arch_spin_lock(&cpu_buffer->lock);
7080
7081 if (cpu_buffer->free_page.data) {
7082 **rpage = cpu_buffer->free_page;
7083 cpu_buffer->free_page.data = NULL;
7084 }
7085
7086 arch_spin_unlock(&cpu_buffer->lock);
7087 local_irq_restore(flags);
7088
7089 if ((*rpage)->data) {
7090 rb_init_data_page((*rpage)->data);
7091 } else {
7092 (*rpage)->data = alloc_cpu_data(cpu, (*rpage)->order);
7093 if (!(*rpage)->data) {
7094 kfree(*rpage);
7095 *rpage = NULL;
7096 return -ENOMEM;
7097 }
7098 }
7099
7100 return 0;
7101 }
7102 EXPORT_SYMBOL_GPL(ring_buffer_alloc_read_page);
7103
7104 /**
7105 * ring_buffer_free_read_page - free an allocated read page
7106 * @buffer: the buffer the page was allocate for
7107 * @cpu: the cpu buffer the page came from
7108 * @rpage: the buffer_data_read_page to free
7109 *
7110 * Free a page allocated from ring_buffer_alloc_read_page.
7111 */
7112 void ring_buffer_free_read_page(struct trace_buffer *buffer, int cpu,
7113 struct buffer_data_read_page *rpage)
7114 {
7115 struct ring_buffer_per_cpu *cpu_buffer;
7116 struct buffer_data_page *dpage;
7117 unsigned long flags;
7118 struct page *page;
7119
7120 if (!buffer || !buffer->buffers || !buffer->buffers[cpu])
7121 return;
7122
7123 if (!rpage)
7124 return;
7125
7126 dpage = rpage->data;
7127 if (!dpage)
7128 goto out;
7129
7130 page = virt_to_page(dpage);
7131
7132 cpu_buffer = buffer->buffers[cpu];
7133
7134 /*
7135 * If the page is still in use someplace else, or order of the page
7136 * is different from the subbuffer order of the buffer -
7137 * we can't reuse it
7138 */
7139 if (page_ref_count(page) > 1 || rpage->order != READ_ONCE(buffer->subbuf_order))
7140 goto out;
7141
7142 local_irq_save(flags);
7143 arch_spin_lock(&cpu_buffer->lock);
7144
7145 if (!cpu_buffer->free_page.data) {
7146 cpu_buffer->free_page = *rpage;
7147 dpage = NULL;
7148 }
7149
7150 arch_spin_unlock(&cpu_buffer->lock);
7151 local_irq_restore(flags);
7152
7153 out:
7154 free_pages((unsigned long)dpage, rpage->order);
7155 kfree(rpage);
7156 }
7157 EXPORT_SYMBOL_GPL(ring_buffer_free_read_page);
7158
7159 /**
7160 * ring_buffer_read_page - extract a page from the ring buffer
7161 * @buffer: buffer to extract from
7162 * @data_page: the page to use allocated from ring_buffer_alloc_read_page
7163 * @len: amount to extract
7164 * @cpu: the cpu of the buffer to extract
7165 * @full: should the extraction only happen when the page is full.
7166 *
7167 * This function will pull out a page from the ring buffer and consume it.
7168 * @data_page must be the address of the variable that was returned
7169 * from ring_buffer_alloc_read_page. This is because the page might be used
7170 * to swap with a page in the ring buffer.
7171 *
7172 * for example:
7173 * rpage = ring_buffer_alloc_read_page(buffer, cpu);
7174 * if (IS_ERR(rpage))
7175 * return PTR_ERR(rpage);
7176 * ret = ring_buffer_read_page(buffer, rpage, len, cpu, 0);
7177 * if (ret >= 0)
7178 * process_page(ring_buffer_read_page_data(rpage), ret);
7179 * ring_buffer_free_read_page(buffer, cpu, rpage);
7180 *
7181 * When @full is set, the function will not return true unless
7182 * the writer is off the reader page.
7183 *
7184 * Note: it is up to the calling functions to handle sleeps and wakeups.
7185 * The ring buffer can be used anywhere in the kernel and can not
7186 * blindly call wake_up. The layer that uses the ring buffer must be
7187 * responsible for that.
7188 *
7189 * Returns:
7190 * >=0 if data has been transferred, returns the offset of consumed data.
7191 * <0 if no data has been transferred.
7192 */
7193 int ring_buffer_read_page(struct trace_buffer *buffer,
7194 struct buffer_data_read_page *data_page,
7195 size_t len, int cpu, int full)
7196 {
7197 struct ring_buffer_per_cpu *cpu_buffer = buffer->buffers[cpu];
7198 struct ring_buffer_event *event;
7199 struct buffer_data_page *dpage;
7200 struct buffer_page *reader;
7201 long missed_events;
7202 unsigned int commit;
7203 unsigned int size;
7204 unsigned int read;
7205 u64 save_timestamp;
7206
7207 if (!cpumask_test_cpu(cpu, buffer->cpumask))
7208 return -1;
7209
7210 /*
7211 * If len is not big enough to hold the page header, then
7212 * we can not copy anything.
7213 */
7214 if (len <= BUF_PAGE_HDR_SIZE)
7215 return -1;
7216
7217 len -= BUF_PAGE_HDR_SIZE;
7218
7219 if (!data_page || !data_page->data)
7220 return -1;
7221
7222 dpage = data_page->data;
7223 if (!dpage)
7224 return -1;
7225
7226 len = min_t(size_t, len, rb_read_page_capacity(data_page));
7227
7228 guard(raw_spinlock_irqsave)(&cpu_buffer->reader_lock);
7229
7230 reader = rb_get_reader_page(cpu_buffer);
7231 if (!reader)
7232 return -1;
7233
7234 event = rb_reader_event(cpu_buffer);
7235
7236 read = reader->read;
7237 commit = rb_page_commit(reader);
7238 size = rb_page_size(reader);
7239
7240 /* Check if any events were dropped */
7241 missed_events = cpu_buffer->lost_events;
7242
7243 /*
7244 * It is not possible to swap the reader page if:
7245 * - It has been partially read
7246 * - len is not big enough to read it entirely
7247 * - A writer is still on it
7248 * - The ring buffer is static
7249 * - The order doesn't match
7250 */
7251 if (read || (len < (size - read)) ||
7252 cpu_buffer->reader_page == cpu_buffer->commit_page ||
7253 rb_is_static(cpu_buffer) ||
7254 data_page->order != reader->order) {
7255 struct buffer_data_page *rpage = cpu_buffer->reader_page->page;
7256 unsigned int rpos = read;
7257 unsigned int pos = 0;
7258 unsigned int event_size;
7259 unsigned int flags = 0;
7260
7261 /* If a full page is requested, it cannot be the commit page */
7262 if (full && cpu_buffer->reader_page == cpu_buffer->commit_page)
7263 return -1;
7264
7265 if (len > (size - read))
7266 len = (size - read);
7267
7268 /* Always keep the time extend and data together */
7269 event_size = rb_event_ts_length(event);
7270
7271 if (len < event_size)
7272 return -1;
7273
7274 if (commit & RB_MISSED_EVENTS)
7275 flags = RB_MISSED_EVENTS;
7276
7277 /* save the current timestamp, since the user will need it */
7278 save_timestamp = cpu_buffer->read_stamp;
7279
7280 /* Need to copy one event at a time */
7281 do {
7282 /* We need the size of one event, because
7283 * rb_advance_reader only advances by one event,
7284 * whereas rb_event_ts_length may include the size of
7285 * one or two events.
7286 * We have already ensured there's enough space if this
7287 * is a time extend. */
7288 event_size = rb_event_length(event);
7289 memcpy(dpage->data + pos, rpage->data + rpos, event_size);
7290
7291 len -= event_size;
7292
7293 rb_advance_reader(cpu_buffer);
7294 rpos = reader->read;
7295 pos += event_size;
7296
7297 if (rpos >= size)
7298 break;
7299
7300 event = rb_reader_event(cpu_buffer);
7301 /* Always keep the time extend and data together */
7302 event_size = rb_event_ts_length(event);
7303 } while (len >= event_size);
7304
7305 /* update dpage */
7306 local_set(&dpage->commit, pos | flags);
7307 dpage->time_stamp = save_timestamp;
7308
7309 /* we copied everything to the beginning */
7310 read = 0;
7311 } else {
7312 /* update the entry counter */
7313 cpu_buffer->read += rb_page_entries(reader);
7314 cpu_buffer->read_bytes += rb_page_size(reader);
7315
7316 /* swap the pages */
7317 rb_init_data_page(dpage);
7318 dpage = reader->page;
7319 reader->page = data_page->data;
7320 local_set(&reader->write, 0);
7321 local_set(&reader->entries, 0);
7322 reader->read = 0;
7323 data_page->data = dpage;
7324 if (!missed_events && rb_data_page_commit(dpage) & RB_MISSED_EVENTS)
7325 missed_events = -1;
7326
7327 /*
7328 * Use the real_end for the data size,
7329 * This gives us a chance to store the lost events
7330 * on the page.
7331 */
7332 if (reader->real_end)
7333 local_set(&dpage->commit, reader->real_end);
7334 }
7335
7336 cpu_buffer->lost_events = 0;
7337
7338 size = rb_data_page_size(dpage);
7339 /*
7340 * Set a flag in the commit field if we lost events
7341 */
7342 if (missed_events) {
7343 /*
7344 * If there is room at the end of the page to save the
7345 * missed events, then record it there.
7346 */
7347 if (missed_events > 0 &&
7348 rb_read_page_capacity(data_page) - size >= sizeof(missed_events)) {
7349 memcpy(&dpage->data[size], &missed_events,
7350 sizeof(missed_events));
7351 local_add(RB_MISSED_STORED, &dpage->commit);
7352 size += sizeof(missed_events);
7353 }
7354 /*
7355 * Note, for the persistent ring buffer, the RB_MISSED_EVENTS
7356 * may have been set in the main buffer via the verification code.
7357 * But here, dpage is a copy of that page and has not yet had
7358 * the RB_MISSED_EVENTS set. As for the normal buffers,
7359 * the main write buffer does not set these bits and it needs
7360 * to be set here.
7361 */
7362 local_add(RB_MISSED_EVENTS, &dpage->commit);
7363 }
7364
7365 /*
7366 * This page may be off to user land. Zero it out here.
7367 */
7368 if (size < rb_read_page_capacity(data_page))
7369 memset(&dpage->data[size], 0, rb_read_page_capacity(data_page) - size);
7370
7371 return read;
7372 }
7373 EXPORT_SYMBOL_GPL(ring_buffer_read_page);
7374
7375 /**
7376 * ring_buffer_read_page_data - get pointer to the data in the page.
7377 * @page: the page to get the data from
7378 *
7379 * Returns pointer to the actual data in this page.
7380 */
7381 void *ring_buffer_read_page_data(struct buffer_data_read_page *page)
7382 {
7383 return page->data;
7384 }
7385 EXPORT_SYMBOL_GPL(ring_buffer_read_page_data);
7386
7387 /**
7388 * ring_buffer_read_page_size - get size of the read page.
7389 * @rpage: the page to get the size from
7390 *
7391 * Returns size of the page in bytes.
7392 */
7393 unsigned int ring_buffer_read_page_size(struct buffer_data_read_page *rpage)
7394 {
7395 return rpage ? PAGE_SIZE << rpage->order : 0;
7396 }
7397 EXPORT_SYMBOL_GPL(ring_buffer_read_page_size);
7398
7399 /**
7400 * ring_buffer_subbuf_size_get - get size of the sub buffer.
7401 * @buffer: the buffer to get the sub buffer size from
7402 *
7403 * Returns size of the sub buffer, in bytes.
7404 */
7405 int ring_buffer_subbuf_size_get(struct trace_buffer *buffer)
7406 {
7407 return rb_subbuf_size(buffer);
7408 }
7409 EXPORT_SYMBOL_GPL(ring_buffer_subbuf_size_get);
7410
7411 /**
7412 * ring_buffer_subbuf_order_get - get order of system sub pages in one buffer page.
7413 * @buffer: The ring_buffer to get the system sub page order from
7414 *
7415 * By default, one ring buffer sub page equals to one system page. This parameter
7416 * is configurable, per ring buffer. The size of the ring buffer sub page can be
7417 * extended, but must be an order of system page size.
7418 *
7419 * Returns the order of buffer sub page size, in system pages:
7420 * 0 means the sub buffer size is 1 system page and so forth.
7421 * In case of an error < 0 is returned.
7422 */
7423 int ring_buffer_subbuf_order_get(struct trace_buffer *buffer)
7424 {
7425 if (!buffer)
7426 return -EINVAL;
7427
7428 return buffer->subbuf_order;
7429 }
7430 EXPORT_SYMBOL_GPL(ring_buffer_subbuf_order_get);
7431
7432 /**
7433 * ring_buffer_subbuf_order_set - set the size of ring buffer sub page.
7434 * @buffer: The ring_buffer to set the new page size.
7435 * @order: Order of the system pages in one sub buffer page
7436 *
7437 * By default, one ring buffer pages equals to one system page. This API can be
7438 * used to set new size of the ring buffer page. The size must be order of
7439 * system page size, that's why the input parameter @order is the order of
7440 * system pages that are allocated for one ring buffer page:
7441 * 0 - 1 system page
7442 * 1 - 2 system pages
7443 * 3 - 4 system pages
7444 * ...
7445 *
7446 * Returns 0 on success or < 0 in case of an error.
7447 */
7448 int ring_buffer_subbuf_order_set(struct trace_buffer *buffer, int order)
7449 {
7450 struct ring_buffer_per_cpu *cpu_buffer;
7451 struct buffer_page *bpage, *tmp;
7452 unsigned int old_capacity;
7453 unsigned long nr_pages;
7454 int old_order;
7455 int psize;
7456 int err;
7457 int cpu;
7458
7459 if (!buffer || order < 0)
7460 return -EINVAL;
7461
7462 psize = (1 << order) * PAGE_SIZE;
7463 if (psize <= BUF_PAGE_HDR_SIZE)
7464 return -EINVAL;
7465
7466 /* Size of a subbuf cannot be greater than the write counter */
7467 if (psize > RB_WRITE_MASK + 1)
7468 return -EINVAL;
7469
7470 /* prevent another thread from changing buffer sizes */
7471 guard(mutex)(&buffer->mutex);
7472
7473 old_order = buffer->subbuf_order;
7474 if (old_order == order)
7475 return 0;
7476
7477 old_capacity = rb_subbuf_capacity(buffer);
7478
7479 /* The mmap fast path reads subbuf_order without buffer->mutex. */
7480 for_each_buffer_cpu(buffer, cpu) {
7481 if (!cpumask_test_cpu(cpu, buffer->cpumask))
7482 continue;
7483 if (atomic_read(&buffer->buffers[cpu]->resize_disabled))
7484 return -EBUSY;
7485 }
7486
7487 atomic_inc(&buffer->record_disabled);
7488
7489 /* Make sure all commits have finished */
7490 synchronize_rcu();
7491
7492 WRITE_ONCE(buffer->subbuf_order, order);
7493
7494 /* Make sure all new buffers are allocated, before deleting the old ones */
7495 for_each_buffer_cpu(buffer, cpu) {
7496
7497 if (!cpumask_test_cpu(cpu, buffer->cpumask))
7498 continue;
7499
7500 cpu_buffer = buffer->buffers[cpu];
7501
7502 if (atomic_read(&cpu_buffer->resize_disabled)) {
7503 err = -EBUSY;
7504 goto error;
7505 }
7506
7507 /* Update the number of pages to match the new size */
7508 nr_pages = old_capacity * buffer->buffers[cpu]->nr_pages;
7509 nr_pages = DIV_ROUND_UP(nr_pages, rb_subbuf_capacity(buffer));
7510
7511 /* we need a minimum of two pages */
7512 if (nr_pages < 2)
7513 nr_pages = 2;
7514
7515 cpu_buffer->nr_pages_to_update = nr_pages;
7516
7517 /* Include the reader page */
7518 nr_pages++;
7519
7520 /* Allocate the new size buffer */
7521 INIT_LIST_HEAD(&cpu_buffer->new_pages);
7522 if (__rb_allocate_pages(cpu_buffer, nr_pages,
7523 &cpu_buffer->new_pages)) {
7524 /* not enough memory for new pages */
7525 err = -ENOMEM;
7526 goto error;
7527 }
7528 }
7529
7530 for_each_buffer_cpu(buffer, cpu) {
7531 struct buffer_data_read_page old_free_data_page;
7532 struct list_head old_pages;
7533 unsigned long flags;
7534
7535 if (!cpumask_test_cpu(cpu, buffer->cpumask))
7536 continue;
7537
7538 cpu_buffer = buffer->buffers[cpu];
7539
7540 raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
7541
7542 /* Clear the head bit to make the link list normal to read */
7543 rb_head_page_deactivate(cpu_buffer);
7544
7545 /*
7546 * Collect buffers from the cpu_buffer pages list and the
7547 * reader_page on old_pages, so they can be freed later when not
7548 * under a spinlock. The pages list is a linked list with no
7549 * head, adding old_pages turns it into a regular list with
7550 * old_pages being the head.
7551 */
7552 list_add(&old_pages, cpu_buffer->pages);
7553 list_add(&cpu_buffer->reader_page->list, &old_pages);
7554
7555 /* One page was allocated for the reader page */
7556 cpu_buffer->reader_page = list_entry(cpu_buffer->new_pages.next,
7557 struct buffer_page, list);
7558 list_del_init(&cpu_buffer->reader_page->list);
7559
7560 /* Install the new pages, remove the head from the list */
7561 cpu_buffer->pages = cpu_buffer->new_pages.next;
7562 list_del_init(&cpu_buffer->new_pages);
7563 cpu_buffer->cnt++;
7564
7565 cpu_buffer->head_page
7566 = list_entry(cpu_buffer->pages, struct buffer_page, list);
7567 cpu_buffer->tail_page = cpu_buffer->commit_page = cpu_buffer->head_page;
7568
7569 cpu_buffer->nr_pages = cpu_buffer->nr_pages_to_update;
7570 cpu_buffer->nr_pages_to_update = 0;
7571
7572 arch_spin_lock(&cpu_buffer->lock);
7573 old_free_data_page = cpu_buffer->free_page;
7574 cpu_buffer->free_page.data = NULL;
7575 arch_spin_unlock(&cpu_buffer->lock);
7576
7577 rb_head_page_activate(cpu_buffer);
7578
7579 raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
7580
7581 /* Free old sub buffers */
7582 list_for_each_entry_safe(bpage, tmp, &old_pages, list) {
7583 list_del_init(&bpage->list);
7584 free_buffer_page(bpage);
7585 }
7586 free_pages((unsigned long)old_free_data_page.data, old_free_data_page.order);
7587
7588 rb_check_pages(cpu_buffer);
7589 }
7590
7591 atomic_dec(&buffer->record_disabled);
7592
7593 return 0;
7594
7595 error:
7596 WRITE_ONCE(buffer->subbuf_order, old_order);
7597
7598 atomic_dec(&buffer->record_disabled);
7599
7600 for_each_buffer_cpu(buffer, cpu) {
7601 cpu_buffer = buffer->buffers[cpu];
7602
7603 if (!cpu_buffer->nr_pages_to_update)
7604 continue;
7605
7606 list_for_each_entry_safe(bpage, tmp, &cpu_buffer->new_pages, list) {
7607 list_del_init(&bpage->list);
7608 free_buffer_page(bpage);
7609 }
7610 }
7611
7612 return err;
7613 }
7614 EXPORT_SYMBOL_GPL(ring_buffer_subbuf_order_set);
7615
7616 static int rb_alloc_meta_page(struct ring_buffer_per_cpu *cpu_buffer)
7617 {
7618 struct page *page;
7619
7620 if (cpu_buffer->meta_page)
7621 return 0;
7622
7623 page = alloc_page(GFP_USER | __GFP_ZERO);
7624 if (!page)
7625 return -ENOMEM;
7626
7627 cpu_buffer->meta_page = page_to_virt(page);
7628
7629 return 0;
7630 }
7631
7632 static void rb_free_meta_page(struct ring_buffer_per_cpu *cpu_buffer)
7633 {
7634 unsigned long addr = (unsigned long)cpu_buffer->meta_page;
7635
7636 free_page(addr);
7637 cpu_buffer->meta_page = NULL;
7638 }
7639
7640 static void rb_setup_ids_meta_page(struct ring_buffer_per_cpu *cpu_buffer,
7641 struct buffer_page **subbuf_ids)
7642 {
7643 struct trace_buffer_meta *meta = cpu_buffer->meta_page;
7644 unsigned long nr_subbufs = cpu_buffer->nr_pages + 1;
7645 struct buffer_page *first_subbuf, *subbuf;
7646 unsigned int cnt = 0;
7647 unsigned int id = 0;
7648
7649 id = rb_page_id(cpu_buffer, cpu_buffer->reader_page, id);
7650 subbuf_ids[id++] = cpu_buffer->reader_page;
7651 cnt++;
7652
7653 first_subbuf = subbuf = rb_set_head_page(cpu_buffer);
7654 do {
7655 id = rb_page_id(cpu_buffer, subbuf, id);
7656
7657 if (WARN_ON(id >= nr_subbufs))
7658 break;
7659
7660 subbuf_ids[id] = subbuf;
7661
7662 rb_inc_page(&subbuf);
7663 id++;
7664 cnt++;
7665 } while (subbuf != first_subbuf);
7666
7667 WARN_ON(cnt != nr_subbufs);
7668
7669 /* install subbuf ID to bpage translation */
7670 cpu_buffer->subbuf_ids = subbuf_ids;
7671
7672 meta->meta_struct_len = sizeof(*meta);
7673 meta->nr_subbufs = nr_subbufs;
7674 meta->subbuf_size = rb_subbuf_size(cpu_buffer->buffer);
7675 meta->meta_page_size = meta->subbuf_size;
7676
7677 rb_update_meta_page(cpu_buffer);
7678 }
7679
7680 static struct ring_buffer_per_cpu *
7681 rb_get_mapped_buffer(struct trace_buffer *buffer, int cpu)
7682 {
7683 struct ring_buffer_per_cpu *cpu_buffer;
7684
7685 if (!cpumask_test_cpu(cpu, buffer->cpumask))
7686 return ERR_PTR(-EINVAL);
7687
7688 cpu_buffer = buffer->buffers[cpu];
7689
7690 mutex_lock(&cpu_buffer->mapping_lock);
7691
7692 if (!cpu_buffer->user_mapped) {
7693 mutex_unlock(&cpu_buffer->mapping_lock);
7694 return ERR_PTR(-ENODEV);
7695 }
7696
7697 return cpu_buffer;
7698 }
7699
7700 static void rb_put_mapped_buffer(struct ring_buffer_per_cpu *cpu_buffer)
7701 {
7702 mutex_unlock(&cpu_buffer->mapping_lock);
7703 }
7704
7705 /*
7706 * Fast-path for rb_buffer_(un)map(). Called whenever the meta-page doesn't need
7707 * to be set-up or torn-down.
7708 */
7709 static int __rb_inc_dec_mapped(struct ring_buffer_per_cpu *cpu_buffer,
7710 bool inc)
7711 {
7712 unsigned long flags;
7713
7714 lockdep_assert_held(&cpu_buffer->mapping_lock);
7715
7716 if (inc && cpu_buffer->user_mapped == UINT_MAX)
7717 return -EBUSY;
7718
7719 if (WARN_ON(!inc && cpu_buffer->user_mapped == 0))
7720 return -EINVAL;
7721
7722 mutex_lock(&cpu_buffer->buffer->mutex);
7723 raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
7724
7725 if (inc)
7726 cpu_buffer->user_mapped++;
7727 else
7728 cpu_buffer->user_mapped--;
7729
7730 raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
7731 mutex_unlock(&cpu_buffer->buffer->mutex);
7732
7733 return 0;
7734 }
7735
7736 /*
7737 * +--------------+ pgoff == 0
7738 * | meta page |
7739 * +--------------+ pgoff == 1
7740 * | subbuffer 0 |
7741 * | |
7742 * +--------------+ pgoff == (1 + (1 << subbuf_order))
7743 * | subbuffer 1 |
7744 * | |
7745 * ...
7746 */
7747 #ifdef CONFIG_MMU
7748 static int __rb_map_vma(struct ring_buffer_per_cpu *cpu_buffer,
7749 struct vm_area_struct *vma)
7750 {
7751 unsigned long nr_subbufs, nr_pages, nr_vma_pages;
7752 pgoff_t pgoff = vma_start_pgoff(vma);
7753 unsigned int subbuf_pages, subbuf_order;
7754 struct page **pages __free(kfree) = NULL;
7755 int p = 0, s = 0;
7756 int err;
7757
7758 /* Refuse MP_PRIVATE or writable mappings */
7759 if (vma->vm_flags & VM_WRITE || vma->vm_flags & VM_EXEC ||
7760 !(vma->vm_flags & VM_MAYSHARE))
7761 return -EPERM;
7762
7763 subbuf_order = cpu_buffer->buffer->subbuf_order;
7764 subbuf_pages = 1 << subbuf_order;
7765
7766 if (subbuf_order && pgoff % subbuf_pages)
7767 return -EINVAL;
7768
7769 /*
7770 * Make sure the mapping cannot become writable later. Also tell the VM
7771 * to not touch these pages (VM_DONTCOPY | VM_DONTEXPAND).
7772 */
7773 vm_flags_mod(vma, VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP,
7774 VM_MAYWRITE);
7775
7776 lockdep_assert_held(&cpu_buffer->mapping_lock);
7777
7778 nr_subbufs = cpu_buffer->nr_pages + 1; /* + reader-subbuf */
7779 nr_pages = ((nr_subbufs + 1) << subbuf_order); /* + meta-page */
7780 if (nr_pages <= pgoff)
7781 return -EINVAL;
7782
7783 nr_pages -= pgoff;
7784
7785 nr_vma_pages = vma_pages(vma);
7786 if (!nr_vma_pages || nr_vma_pages > nr_pages)
7787 return -EINVAL;
7788
7789 nr_pages = nr_vma_pages;
7790
7791 pages = kzalloc_objs(*pages, nr_pages);
7792 if (!pages)
7793 return -ENOMEM;
7794
7795 if (!pgoff) {
7796 unsigned long meta_page_padding;
7797
7798 pages[p++] = virt_to_page(cpu_buffer->meta_page);
7799
7800 /*
7801 * Pad with the zero-page to align the meta-page with the
7802 * sub-buffers.
7803 */
7804 meta_page_padding = subbuf_pages - 1;
7805 while (meta_page_padding-- && p < nr_pages) {
7806 unsigned long __maybe_unused zero_addr =
7807 vma->vm_start + (PAGE_SIZE * p);
7808
7809 pages[p++] = ZERO_PAGE(zero_addr);
7810 }
7811 } else {
7812 /* Skip the meta-page */
7813 pgoff -= subbuf_pages;
7814
7815 s += pgoff / subbuf_pages;
7816 }
7817
7818 while (p < nr_pages) {
7819 struct buffer_page *subbuf;
7820 struct page *page;
7821 int off = 0;
7822
7823 if (WARN_ON_ONCE(s >= nr_subbufs))
7824 return -EINVAL;
7825
7826 subbuf = cpu_buffer->subbuf_ids[s];
7827 page = virt_to_page((void *)subbuf->page);
7828
7829 for (; off < (1 << (subbuf_order)); off++, page++) {
7830 if (p >= nr_pages)
7831 break;
7832
7833 pages[p++] = page;
7834 }
7835 s++;
7836 }
7837
7838 err = vm_insert_pages(vma, vma->vm_start, pages, &nr_pages);
7839
7840 return err;
7841 }
7842 #else
7843 static int __rb_map_vma(struct ring_buffer_per_cpu *cpu_buffer,
7844 struct vm_area_struct *vma)
7845 {
7846 return -EOPNOTSUPP;
7847 }
7848 #endif
7849
7850 int ring_buffer_map(struct trace_buffer *buffer, int cpu,
7851 struct vm_area_struct *vma)
7852 {
7853 struct ring_buffer_per_cpu *cpu_buffer;
7854 struct buffer_page **subbuf_ids;
7855 unsigned long flags;
7856 int err;
7857
7858 if (!cpumask_test_cpu(cpu, buffer->cpumask) || buffer->remote)
7859 return -EINVAL;
7860
7861 cpu_buffer = buffer->buffers[cpu];
7862
7863 guard(mutex)(&cpu_buffer->mapping_lock);
7864
7865 if (cpu_buffer->user_mapped) {
7866 err = __rb_map_vma(cpu_buffer, vma);
7867 if (!err)
7868 err = __rb_inc_dec_mapped(cpu_buffer, true);
7869 return err;
7870 }
7871
7872 /* prevent another thread from changing buffer/sub-buffer sizes */
7873 guard(mutex)(&buffer->mutex);
7874
7875 if (cpu_buffer->nr_pages > rb_static_max_pages())
7876 return -E2BIG;
7877
7878 err = rb_alloc_meta_page(cpu_buffer);
7879 if (err)
7880 return err;
7881
7882 /* subbuf_ids includes the reader while nr_pages does not */
7883 subbuf_ids = kcalloc(cpu_buffer->nr_pages + 1, sizeof(*subbuf_ids), GFP_KERNEL);
7884 if (!subbuf_ids) {
7885 rb_free_meta_page(cpu_buffer);
7886 return -ENOMEM;
7887 }
7888
7889 atomic_inc(&cpu_buffer->resize_disabled);
7890
7891 /*
7892 * Lock all readers to block any subbuf swap until the subbuf IDs are
7893 * assigned.
7894 */
7895 raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
7896 rb_setup_ids_meta_page(cpu_buffer, subbuf_ids);
7897
7898 raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
7899
7900 err = __rb_map_vma(cpu_buffer, vma);
7901 if (!err) {
7902 raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
7903 /* This is the first time it is mapped by user */
7904 cpu_buffer->user_mapped = 1;
7905 raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
7906 } else {
7907 kfree(cpu_buffer->subbuf_ids);
7908 cpu_buffer->subbuf_ids = NULL;
7909 rb_free_meta_page(cpu_buffer);
7910 atomic_dec(&cpu_buffer->resize_disabled);
7911 }
7912
7913 return err;
7914 }
7915
7916 /*
7917 * This is called when a VMA is duplicated (e.g., on fork()) to increment
7918 * the user_mapped counter without remapping pages.
7919 */
7920 void ring_buffer_map_dup(struct trace_buffer *buffer, int cpu)
7921 {
7922 struct ring_buffer_per_cpu *cpu_buffer;
7923
7924 if (WARN_ON(!cpumask_test_cpu(cpu, buffer->cpumask)))
7925 return;
7926
7927 cpu_buffer = buffer->buffers[cpu];
7928
7929 guard(mutex)(&cpu_buffer->mapping_lock);
7930
7931 if (cpu_buffer->user_mapped)
7932 __rb_inc_dec_mapped(cpu_buffer, true);
7933 else
7934 WARN(1, "Unexpected buffer stat, it should be mapped");
7935 }
7936
7937 int ring_buffer_unmap(struct trace_buffer *buffer, int cpu)
7938 {
7939 struct ring_buffer_per_cpu *cpu_buffer;
7940 unsigned long flags;
7941
7942 if (!cpumask_test_cpu(cpu, buffer->cpumask))
7943 return -EINVAL;
7944
7945 cpu_buffer = buffer->buffers[cpu];
7946
7947 guard(mutex)(&cpu_buffer->mapping_lock);
7948
7949 if (!cpu_buffer->user_mapped) {
7950 return -ENODEV;
7951 } else if (cpu_buffer->user_mapped > 1) {
7952 __rb_inc_dec_mapped(cpu_buffer, false);
7953 return 0;
7954 }
7955
7956 guard(mutex)(&buffer->mutex);
7957 raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
7958
7959 /* This is the last user space mapping */
7960 cpu_buffer->user_mapped = 0;
7961
7962 raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
7963
7964 kfree(cpu_buffer->subbuf_ids);
7965 cpu_buffer->subbuf_ids = NULL;
7966 rb_free_meta_page(cpu_buffer);
7967 atomic_dec(&cpu_buffer->resize_disabled);
7968
7969 return 0;
7970 }
7971
7972 int ring_buffer_map_get_reader(struct trace_buffer *buffer, int cpu)
7973 {
7974 struct ring_buffer_per_cpu *cpu_buffer;
7975 struct buffer_page *reader;
7976 unsigned long missed_events;
7977 unsigned long reader_size;
7978 unsigned long flags;
7979
7980 cpu_buffer = rb_get_mapped_buffer(buffer, cpu);
7981 if (IS_ERR(cpu_buffer))
7982 return (int)PTR_ERR(cpu_buffer);
7983
7984 raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
7985
7986 consume:
7987 if (rb_per_cpu_empty(cpu_buffer))
7988 goto out;
7989
7990 reader_size = rb_page_size(cpu_buffer->reader_page);
7991
7992 /*
7993 * There are data to be read on the current reader page, we can
7994 * return to the caller. But before that, we assume the latter will read
7995 * everything. Let's update the kernel reader accordingly.
7996 */
7997 if (cpu_buffer->reader_page->read < reader_size) {
7998 while (cpu_buffer->reader_page->read < reader_size)
7999 rb_advance_reader(cpu_buffer);
8000 goto out;
8001 }
8002
8003 /* Did the reader catch up with the writer? */
8004 if (cpu_buffer->reader_page == cpu_buffer->commit_page)
8005 goto out;
8006
8007 reader = rb_get_reader_page(cpu_buffer);
8008 if (WARN_ON(!reader))
8009 goto out;
8010
8011 /* Check if any events were dropped */
8012 missed_events = cpu_buffer->lost_events;
8013
8014 if (missed_events) {
8015 if (cpu_buffer->reader_page != cpu_buffer->commit_page) {
8016 struct buffer_data_page *dpage = reader->page;
8017 unsigned int commit;
8018 /*
8019 * Use the real_end for the data size,
8020 * This gives us a chance to store the lost events
8021 * on the page.
8022 */
8023 if (reader->real_end)
8024 local_set(&dpage->commit, reader->real_end);
8025 /*
8026 * If there is room at the end of the page to save the
8027 * missed events, then record it there.
8028 */
8029 commit = rb_page_size(reader);
8030 if (rb_page_capacity(reader) - commit >= sizeof(missed_events)) {
8031 memcpy(&dpage->data[commit], &missed_events,
8032 sizeof(missed_events));
8033 local_add(RB_MISSED_STORED, &dpage->commit);
8034 }
8035 local_add(RB_MISSED_EVENTS, &dpage->commit);
8036 } else if (!WARN_ONCE(cpu_buffer->reader_page == cpu_buffer->tail_page,
8037 "Reader on commit with %ld missed events",
8038 missed_events)) {
8039 /*
8040 * There shouldn't be any missed events if the tail_page
8041 * is on the reader page. But if the tail page is not on the
8042 * reader page and the commit_page is, that would mean that
8043 * there's a commit_overrun (an interrupt preempted an
8044 * addition of an event and then filled the buffer
8045 * with new events). In this case it's not an
8046 * error, but it should still be reported.
8047 *
8048 * TODO: Add missed events to the page for user space to know.
8049 */
8050 pr_info("Ring buffer [%d] commit overrun lost %ld events at timestamp:%lld\n",
8051 cpu, missed_events, cpu_buffer->reader_page->page->time_stamp);
8052 }
8053 }
8054
8055 cpu_buffer->lost_events = 0;
8056
8057 goto consume;
8058
8059 out:
8060 /* Some archs do not have data cache coherency between kernel and user-space */
8061 flush_kernel_vmap_range(cpu_buffer->reader_page->page,
8062 rb_subbuf_size(buffer));
8063
8064 rb_update_meta_page(cpu_buffer);
8065
8066 raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
8067 rb_put_mapped_buffer(cpu_buffer);
8068
8069 return 0;
8070 }
8071
8072 static void rb_cpu_sync(void *data)
8073 {
8074 /* Not really needed, but documents what is happening */
8075 smp_rmb();
8076 }
8077
8078 /*
8079 * We only allocate new buffers, never free them if the CPU goes down.
8080 * If we were to free the buffer, then the user would lose any trace that was in
8081 * the buffer.
8082 */
8083 int trace_rb_cpu_prepare(unsigned int cpu, struct hlist_node *node)
8084 {
8085 struct trace_buffer *buffer;
8086 long nr_pages_same;
8087 int cpu_i;
8088 unsigned long nr_pages;
8089
8090 buffer = container_of(node, struct trace_buffer, node);
8091 if (cpumask_test_cpu(cpu, buffer->cpumask))
8092 return 0;
8093
8094 nr_pages = 0;
8095 nr_pages_same = 1;
8096 /* check if all cpu sizes are same */
8097 for_each_buffer_cpu(buffer, cpu_i) {
8098 /* fill in the size from first enabled cpu */
8099 if (nr_pages == 0)
8100 nr_pages = buffer->buffers[cpu_i]->nr_pages;
8101 if (nr_pages != buffer->buffers[cpu_i]->nr_pages) {
8102 nr_pages_same = 0;
8103 break;
8104 }
8105 }
8106 /* allocate minimum pages, user can later expand it */
8107 if (!nr_pages_same)
8108 nr_pages = 2;
8109 buffer->buffers[cpu] =
8110 rb_allocate_cpu_buffer(buffer, nr_pages, cpu);
8111 if (!buffer->buffers[cpu]) {
8112 WARN(1, "failed to allocate ring buffer on CPU %u\n",
8113 cpu);
8114 return -ENOMEM;
8115 }
8116
8117 /*
8118 * Ensure trace_buffer readers observe the newly allocated
8119 * ring_buffer_per_cpu before they check the cpumask. Instead of using a
8120 * read barrier for all readers, send an IPI.
8121 */
8122 if (unlikely(system_state == SYSTEM_RUNNING)) {
8123 on_each_cpu(rb_cpu_sync, NULL, 1);
8124 /* Not really needed, but documents what is happening */
8125 smp_wmb();
8126 }
8127
8128 cpumask_set_cpu(cpu, buffer->cpumask);
8129 return 0;
8130 }
8131
8132 #ifdef CONFIG_RING_BUFFER_STARTUP_TEST
8133 /*
8134 * This is a basic integrity check of the ring buffer.
8135 * Late in the boot cycle this test will run when configured in.
8136 * It will kick off a thread per CPU that will go into a loop
8137 * writing to the per cpu ring buffer various sizes of data.
8138 * Some of the data will be large items, some small.
8139 *
8140 * Another thread is created that goes into a spin, sending out
8141 * IPIs to the other CPUs to also write into the ring buffer.
8142 * this is to test the nesting ability of the buffer.
8143 *
8144 * Basic stats are recorded and reported. If something in the
8145 * ring buffer should happen that's not expected, a big warning
8146 * is displayed and all ring buffers are disabled.
8147 */
8148 static struct task_struct *rb_threads[NR_CPUS] __initdata;
8149
8150 struct rb_test_data {
8151 struct trace_buffer *buffer;
8152 unsigned long events;
8153 unsigned long bytes_written;
8154 unsigned long bytes_alloc;
8155 unsigned long bytes_dropped;
8156 unsigned long events_nested;
8157 unsigned long bytes_written_nested;
8158 unsigned long bytes_alloc_nested;
8159 unsigned long bytes_dropped_nested;
8160 int min_size_nested;
8161 int max_size_nested;
8162 int max_size;
8163 int min_size;
8164 int cpu;
8165 int cnt;
8166 };
8167
8168 static struct rb_test_data rb_data[NR_CPUS] __initdata;
8169
8170 /* 1 meg per cpu */
8171 #define RB_TEST_BUFFER_SIZE 1048576
8172
8173 static char rb_string[] __initdata =
8174 "abcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()?+\\"
8175 "?+|:';\",.<>/?abcdefghijklmnopqrstuvwxyz1234567890"
8176 "!@#$%^&*()?+\\?+|:';\",.<>/?abcdefghijklmnopqrstuv";
8177
8178 static bool rb_test_started __initdata;
8179
8180 struct rb_item {
8181 int size;
8182 char str[];
8183 };
8184
8185 static __init int rb_write_something(struct rb_test_data *data, bool nested)
8186 {
8187 struct ring_buffer_event *event;
8188 struct rb_item *item;
8189 bool started;
8190 int event_len;
8191 int size;
8192 int len;
8193 int cnt;
8194
8195 /* Have nested writes different that what is written */
8196 cnt = data->cnt + (nested ? 27 : 0);
8197
8198 /* Multiply cnt by ~e, to make some unique increment */
8199 size = (cnt * 68 / 25) % (sizeof(rb_string) - 1);
8200
8201 len = size + sizeof(struct rb_item);
8202
8203 started = rb_test_started;
8204 /* read rb_test_started before checking buffer enabled */
8205 smp_rmb();
8206
8207 event = ring_buffer_lock_reserve(data->buffer, len);
8208 if (!event) {
8209 /* Ignore dropped events before test starts. */
8210 if (started) {
8211 if (nested)
8212 data->bytes_dropped_nested += len;
8213 else
8214 data->bytes_dropped += len;
8215 }
8216 return len;
8217 }
8218
8219 event_len = ring_buffer_event_length(event);
8220
8221 if (RB_WARN_ON(data->buffer, event_len < len))
8222 goto out;
8223
8224 item = ring_buffer_event_data(event);
8225 item->size = size;
8226 memcpy(item->str, rb_string, size);
8227
8228 if (nested) {
8229 data->bytes_alloc_nested += event_len;
8230 data->bytes_written_nested += len;
8231 data->events_nested++;
8232 if (!data->min_size_nested || len < data->min_size_nested)
8233 data->min_size_nested = len;
8234 if (len > data->max_size_nested)
8235 data->max_size_nested = len;
8236 } else {
8237 data->bytes_alloc += event_len;
8238 data->bytes_written += len;
8239 data->events++;
8240 if (!data->min_size || len < data->min_size)
8241 data->max_size = len;
8242 if (len > data->max_size)
8243 data->max_size = len;
8244 }
8245
8246 out:
8247 ring_buffer_unlock_commit(data->buffer);
8248
8249 return 0;
8250 }
8251
8252 static __init int rb_test(void *arg)
8253 {
8254 struct rb_test_data *data = arg;
8255
8256 while (!kthread_should_stop()) {
8257 rb_write_something(data, false);
8258 data->cnt++;
8259
8260 set_current_state(TASK_INTERRUPTIBLE);
8261 /* Now sleep between a min of 100-300us and a max of 1ms */
8262 usleep_range(((data->cnt % 3) + 1) * 100, 1000);
8263 }
8264
8265 return 0;
8266 }
8267
8268 static __init void rb_ipi(void *ignore)
8269 {
8270 struct rb_test_data *data;
8271 int cpu = smp_processor_id();
8272
8273 data = &rb_data[cpu];
8274 rb_write_something(data, true);
8275 }
8276
8277 static __init int rb_hammer_test(void *arg)
8278 {
8279 while (!kthread_should_stop()) {
8280
8281 /* Send an IPI to all cpus to write data! */
8282 smp_call_function(rb_ipi, NULL, 1);
8283 /* No sleep, but for non preempt, let others run */
8284 schedule();
8285 }
8286
8287 return 0;
8288 }
8289
8290 static __init int test_ringbuffer(void)
8291 {
8292 struct task_struct *rb_hammer;
8293 struct trace_buffer *buffer;
8294 int cpu;
8295 int ret = 0;
8296
8297 if (security_locked_down(LOCKDOWN_TRACEFS)) {
8298 pr_warn("Lockdown is enabled, skipping ring buffer tests\n");
8299 return 0;
8300 }
8301
8302 pr_info("Running ring buffer tests...\n");
8303
8304 buffer = ring_buffer_alloc(RB_TEST_BUFFER_SIZE, RB_FL_OVERWRITE);
8305 if (WARN_ON(!buffer))
8306 return 0;
8307
8308 /* Disable buffer so that threads can't write to it yet */
8309 ring_buffer_record_off(buffer);
8310
8311 for_each_online_cpu(cpu) {
8312 rb_data[cpu].buffer = buffer;
8313 rb_data[cpu].cpu = cpu;
8314 rb_data[cpu].cnt = cpu;
8315 rb_threads[cpu] = kthread_run_on_cpu(rb_test, &rb_data[cpu],
8316 cpu, "rbtester/%u");
8317 if (WARN_ON(IS_ERR(rb_threads[cpu]))) {
8318 pr_cont("FAILED\n");
8319 ret = PTR_ERR(rb_threads[cpu]);
8320 goto out_free;
8321 }
8322 }
8323
8324 /* Now create the rb hammer! */
8325 rb_hammer = kthread_run(rb_hammer_test, NULL, "rbhammer");
8326 if (WARN_ON(IS_ERR(rb_hammer))) {
8327 pr_cont("FAILED\n");
8328 ret = PTR_ERR(rb_hammer);
8329 goto out_free;
8330 }
8331
8332 ring_buffer_record_on(buffer);
8333 /*
8334 * Show buffer is enabled before setting rb_test_started.
8335 * Yes there's a small race window where events could be
8336 * dropped and the thread won't catch it. But when a ring
8337 * buffer gets enabled, there will always be some kind of
8338 * delay before other CPUs see it. Thus, we don't care about
8339 * those dropped events. We care about events dropped after
8340 * the threads see that the buffer is active.
8341 */
8342 smp_wmb();
8343 rb_test_started = true;
8344
8345 set_current_state(TASK_INTERRUPTIBLE);
8346 /* Just run for 10 seconds */
8347 schedule_timeout(10 * HZ);
8348
8349 kthread_stop(rb_hammer);
8350
8351 out_free:
8352 for_each_online_cpu(cpu) {
8353 if (IS_ERR_OR_NULL(rb_threads[cpu]))
8354 break;
8355 kthread_stop(rb_threads[cpu]);
8356 }
8357 if (ret) {
8358 ring_buffer_free(buffer);
8359 return ret;
8360 }
8361
8362 /* Report! */
8363 pr_info("finished\n");
8364 for_each_online_cpu(cpu) {
8365 struct ring_buffer_event *event;
8366 struct rb_test_data *data = &rb_data[cpu];
8367 struct rb_item *item;
8368 unsigned long total_events;
8369 unsigned long total_dropped;
8370 unsigned long total_written;
8371 unsigned long total_alloc;
8372 unsigned long total_read = 0;
8373 unsigned long total_size = 0;
8374 unsigned long total_len = 0;
8375 unsigned long total_lost = 0;
8376 unsigned long lost;
8377 int big_event_size;
8378 int small_event_size;
8379
8380 ret = -1;
8381
8382 total_events = data->events + data->events_nested;
8383 total_written = data->bytes_written + data->bytes_written_nested;
8384 total_alloc = data->bytes_alloc + data->bytes_alloc_nested;
8385 total_dropped = data->bytes_dropped + data->bytes_dropped_nested;
8386
8387 big_event_size = data->max_size + data->max_size_nested;
8388 small_event_size = data->min_size + data->min_size_nested;
8389
8390 pr_info("CPU %d:\n", cpu);
8391 pr_info(" events: %ld\n", total_events);
8392 pr_info(" dropped bytes: %ld\n", total_dropped);
8393 pr_info(" alloced bytes: %ld\n", total_alloc);
8394 pr_info(" written bytes: %ld\n", total_written);
8395 pr_info(" biggest event: %d\n", big_event_size);
8396 pr_info(" smallest event: %d\n", small_event_size);
8397
8398 if (RB_WARN_ON(buffer, total_dropped))
8399 break;
8400
8401 ret = 0;
8402
8403 while ((event = ring_buffer_consume(buffer, cpu, NULL, &lost))) {
8404 total_lost += lost;
8405 item = ring_buffer_event_data(event);
8406 total_len += ring_buffer_event_length(event);
8407 total_size += item->size + sizeof(struct rb_item);
8408 if (memcmp(&item->str[0], rb_string, item->size) != 0) {
8409 pr_info("FAILED!\n");
8410 pr_info("buffer had: %.*s\n", item->size, item->str);
8411 pr_info("expected: %.*s\n", item->size, rb_string);
8412 RB_WARN_ON(buffer, 1);
8413 ret = -1;
8414 break;
8415 }
8416 total_read++;
8417 }
8418 if (ret)
8419 break;
8420
8421 ret = -1;
8422
8423 pr_info(" read events: %ld\n", total_read);
8424 pr_info(" lost events: %ld\n", total_lost);
8425 pr_info(" total events: %ld\n", total_lost + total_read);
8426 pr_info(" recorded len bytes: %ld\n", total_len);
8427 pr_info(" recorded size bytes: %ld\n", total_size);
8428 if (total_lost) {
8429 pr_info(" With dropped events, record len and size may not match\n"
8430 " alloced and written from above\n");
8431 } else {
8432 if (RB_WARN_ON(buffer, total_len != total_alloc ||
8433 total_size != total_written))
8434 break;
8435 }
8436 if (RB_WARN_ON(buffer, total_lost + total_read != total_events))
8437 break;
8438
8439 ret = 0;
8440 }
8441 if (!ret)
8442 pr_info("Ring buffer PASSED!\n");
8443
8444 ring_buffer_free(buffer);
8445 return 0;
8446 }
8447
8448 late_initcall(test_ringbuffer);
8449 #endif /* CONFIG_RING_BUFFER_STARTUP_TEST */