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