xref: /linux/kernel/trace/ring_buffer.c (revision 76a0a6d58318fff8b14530ed9b99c7065995db29)
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 	cpu_buffer->cnt++;
5895 
5896 	if (!rb_page_size(cpu_buffer->reader_page))
5897 		return NULL;
5898 
5899 out:
5900 	/*
5901 	 * Order page::commit read before page::data and page::time_stamp, most
5902 	 * likely paired with simple_ring_buffer_commit().
5903 	 */
5904 	smp_rmb();
5905 
5906 	if (!cpu_buffer->reader_page->read)
5907 		cpu_buffer->read_stamp = cpu_buffer->reader_page->page->time_stamp;
5908 
5909 	return cpu_buffer->reader_page;
5910 }
5911 
5912 static struct buffer_page *
5913 __rb_get_reader_page(struct ring_buffer_per_cpu *cpu_buffer)
5914 {
5915 	unsigned long max_loops = cpu_buffer->ring_meta ? cpu_buffer->nr_pages : 3;
5916 	struct buffer_page *reader = NULL;
5917 	unsigned long nr_loops = 0;
5918 	unsigned long overwrite;
5919 	unsigned long flags;
5920 	int missed_events = 0;
5921 	bool ret;
5922 
5923 	local_irq_save(flags);
5924 	arch_spin_lock(&cpu_buffer->lock);
5925 
5926  again:
5927 	/*
5928 	 * This should normally only loop twice. But because the
5929 	 * start of the reader inserts an empty page, it causes a
5930 	 * case where we will loop three times. There should be no
5931 	 * reason to loop four times unless the ring buffer is a
5932 	 * recovered persistent ring buffer. For persistent ring buffers,
5933 	 * invalid pages are reset during recovery, so there may be more
5934 	 * than 3 contiguous pages can be empty, but less than nr_pages.
5935 	 */
5936 	if (RB_WARN_ON(cpu_buffer, ++nr_loops > max_loops)) {
5937 		reader = NULL;
5938 		goto out;
5939 	}
5940 
5941 	reader = cpu_buffer->reader_page;
5942 
5943 	/* If there's more to read, return this page */
5944 	if (cpu_buffer->reader_page->read < rb_page_size(reader))
5945 		goto out;
5946 
5947 	/* Never should we have an index greater than the size */
5948 	if (RB_WARN_ON(cpu_buffer,
5949 		       cpu_buffer->reader_page->read > rb_page_size(reader)))
5950 		goto out;
5951 
5952 	/* check if we caught up to the tail */
5953 	reader = NULL;
5954 	if (cpu_buffer->commit_page == cpu_buffer->reader_page)
5955 		goto out;
5956 
5957 	/* Don't bother swapping if the ring buffer is empty */
5958 	if (rb_num_of_entries(cpu_buffer) == 0)
5959 		goto out;
5960 
5961 	/*
5962 	 * Reset the reader page to size zero.
5963 	 */
5964 	local_set(&cpu_buffer->reader_page->write, 0);
5965 	local_set(&cpu_buffer->reader_page->entries, 0);
5966 	rb_init_data_page(cpu_buffer->reader_page->page);
5967 	cpu_buffer->reader_page->real_end = 0;
5968 
5969  spin:
5970 	/*
5971 	 * Splice the empty reader page into the list around the head.
5972 	 */
5973 	reader = rb_set_head_page(cpu_buffer);
5974 	if (!reader)
5975 		goto out;
5976 	cpu_buffer->reader_page->list.next = rb_list_head(reader->list.next);
5977 	cpu_buffer->reader_page->list.prev = reader->list.prev;
5978 
5979 	/*
5980 	 * cpu_buffer->pages just needs to point to the buffer, it
5981 	 *  has no specific buffer page to point to. Lets move it out
5982 	 *  of our way so we don't accidentally swap it.
5983 	 */
5984 	cpu_buffer->pages = reader->list.prev;
5985 
5986 	/* The reader page will be pointing to the new head */
5987 	rb_set_list_to_head(&cpu_buffer->reader_page->list);
5988 
5989 	/*
5990 	 * We want to make sure we read the overruns after we set up our
5991 	 * pointers to the next object. The writer side does a
5992 	 * cmpxchg to cross pages which acts as the mb on the writer
5993 	 * side. Note, the reader will constantly fail the swap
5994 	 * while the writer is updating the pointers, so this
5995 	 * guarantees that the overwrite recorded here is the one we
5996 	 * want to compare with the last_overrun.
5997 	 */
5998 	smp_mb();
5999 	overwrite = local_read(&(cpu_buffer->overrun));
6000 
6001 	/*
6002 	 * Here's the tricky part.
6003 	 *
6004 	 * We need to move the pointer past the header page.
6005 	 * But we can only do that if a writer is not currently
6006 	 * moving it. The page before the header page has the
6007 	 * flag bit '1' set if it is pointing to the page we want.
6008 	 * but if the writer is in the process of moving it
6009 	 * then it will be '2' or already moved '0'.
6010 	 */
6011 
6012 	ret = rb_head_page_replace(reader, cpu_buffer->reader_page);
6013 
6014 	/*
6015 	 * If we did not convert it, then we must try again.
6016 	 */
6017 	if (!ret)
6018 		goto spin;
6019 
6020 	if (rb_page_commit(reader) & RB_MISSED_EVENTS)
6021 		missed_events = -1;
6022 
6023 	if (cpu_buffer->ring_meta)
6024 		rb_update_meta_reader(cpu_buffer, reader);
6025 
6026 	/*
6027 	 * Yay! We succeeded in replacing the page.
6028 	 *
6029 	 * Now make the new head point back to the reader page.
6030 	 */
6031 	rb_list_head(reader->list.next)->prev = &cpu_buffer->reader_page->list;
6032 	rb_inc_page(&cpu_buffer->head_page);
6033 
6034 	cpu_buffer->cnt++;
6035 	local_inc(&cpu_buffer->pages_read);
6036 
6037 	/* Finally update the reader page to the new head */
6038 	cpu_buffer->reader_page = reader;
6039 	cpu_buffer->reader_page->read = 0;
6040 
6041 	if (overwrite != cpu_buffer->last_overrun) {
6042 		cpu_buffer->lost_events = overwrite - cpu_buffer->last_overrun;
6043 		cpu_buffer->last_overrun = overwrite;
6044 	}
6045 
6046 	goto again;
6047 
6048  out:
6049 	/* Update the read_stamp on the first event */
6050 	if (reader && reader->read == 0)
6051 		cpu_buffer->read_stamp = reader->page->time_stamp;
6052 
6053 	arch_spin_unlock(&cpu_buffer->lock);
6054 	local_irq_restore(flags);
6055 
6056 	/*
6057 	 * The writer has preempt disable, wait for it. But not forever
6058 	 * Although, 1 second is pretty much "forever"
6059 	 */
6060 #define USECS_WAIT	1000000
6061         for (nr_loops = 0; nr_loops < USECS_WAIT; nr_loops++) {
6062 		/* If the write is past the end of page, a writer is still updating it */
6063 		if (likely(!reader || rb_page_write(reader) <= rb_page_capacity(reader)))
6064 			break;
6065 
6066 		udelay(1);
6067 
6068 		/* Get the latest version of the reader write value */
6069 		smp_rmb();
6070 	}
6071 
6072 	/* The writer is not moving forward? Something is wrong */
6073 	if (RB_WARN_ON(cpu_buffer, nr_loops == USECS_WAIT))
6074 		reader = NULL;
6075 
6076 	/*
6077 	 * Make sure we see any padding after the write update
6078 	 * (see rb_reset_tail()).
6079 	 *
6080 	 * In addition, a writer may be writing on the reader page
6081 	 * if the page has not been fully filled, so the read barrier
6082 	 * is also needed to make sure we see the content of what is
6083 	 * committed by the writer (see rb_set_commit_to_write()).
6084 	 */
6085 	smp_rmb();
6086 
6087 	if (!cpu_buffer->lost_events)
6088 		cpu_buffer->lost_events = missed_events;
6089 
6090 	return reader;
6091 }
6092 
6093 static struct buffer_page *
6094 rb_get_reader_page(struct ring_buffer_per_cpu *cpu_buffer)
6095 {
6096 	return cpu_buffer->remote ? __rb_get_reader_page_from_remote(cpu_buffer) :
6097 				    __rb_get_reader_page(cpu_buffer);
6098 }
6099 
6100 static void rb_advance_reader(struct ring_buffer_per_cpu *cpu_buffer)
6101 {
6102 	struct ring_buffer_event *event;
6103 	struct buffer_page *reader;
6104 	unsigned length;
6105 
6106 	reader = rb_get_reader_page(cpu_buffer);
6107 
6108 	/* This function should not be called when buffer is empty */
6109 	if (RB_WARN_ON(cpu_buffer, !reader))
6110 		return;
6111 
6112 	event = rb_reader_event(cpu_buffer);
6113 
6114 	if (event->type_len <= RINGBUF_TYPE_DATA_TYPE_LEN_MAX)
6115 		cpu_buffer->read++;
6116 
6117 	rb_update_read_stamp(cpu_buffer, event);
6118 
6119 	length = rb_event_length(event);
6120 	cpu_buffer->reader_page->read += length;
6121 	cpu_buffer->read_bytes += length;
6122 }
6123 
6124 static void rb_advance_iter(struct ring_buffer_iter *iter)
6125 {
6126 	struct ring_buffer_per_cpu *cpu_buffer;
6127 
6128 	cpu_buffer = iter->cpu_buffer;
6129 
6130 	/* If head == next_event then we need to jump to the next event */
6131 	if (iter->head == iter->next_event) {
6132 		/* If the event gets overwritten again, there's nothing to do */
6133 		if (rb_iter_head_event(iter) == NULL)
6134 			return;
6135 	}
6136 
6137 	iter->head = iter->next_event;
6138 
6139 	/*
6140 	 * Check if we are at the end of the buffer.
6141 	 */
6142 	if (iter->next_event >= rb_page_size(iter->head_page)) {
6143 		/* discarded commits can make the page empty */
6144 		if (iter->head_page == cpu_buffer->commit_page)
6145 			return;
6146 		rb_inc_iter(iter);
6147 		return;
6148 	}
6149 
6150 	rb_update_iter_read_stamp(iter, iter->event);
6151 }
6152 
6153 static int rb_lost_events(struct ring_buffer_per_cpu *cpu_buffer)
6154 {
6155 	return cpu_buffer->lost_events;
6156 }
6157 
6158 static struct ring_buffer_event *
6159 rb_buffer_peek(struct ring_buffer_per_cpu *cpu_buffer, u64 *ts,
6160 	       unsigned long *lost_events)
6161 {
6162 	struct ring_buffer_event *event;
6163 	struct buffer_page *reader;
6164 	int nr_loops = 0;
6165 
6166 	if (ts)
6167 		*ts = 0;
6168  again:
6169 	/*
6170 	 * We repeat when a time extend is encountered.
6171 	 * Since the time extend is always attached to a data event,
6172 	 * we should never loop more than once.
6173 	 * (We never hit the following condition more than twice).
6174 	 */
6175 	if (RB_WARN_ON(cpu_buffer, ++nr_loops > 2))
6176 		return NULL;
6177 
6178 	reader = rb_get_reader_page(cpu_buffer);
6179 	if (!reader)
6180 		return NULL;
6181 
6182 	event = rb_reader_event(cpu_buffer);
6183 
6184 	switch (event->type_len) {
6185 	case RINGBUF_TYPE_PADDING:
6186 		if (rb_null_event(event))
6187 			RB_WARN_ON(cpu_buffer, 1);
6188 		/*
6189 		 * Because the writer could be discarding every
6190 		 * event it creates (which would probably be bad)
6191 		 * if we were to go back to "again" then we may never
6192 		 * catch up, and will trigger the warn on, or lock
6193 		 * the box. Return the padding, and we will release
6194 		 * the current locks, and try again.
6195 		 */
6196 		return event;
6197 
6198 	case RINGBUF_TYPE_TIME_EXTEND:
6199 		/* Internal data, OK to advance */
6200 		rb_advance_reader(cpu_buffer);
6201 		goto again;
6202 
6203 	case RINGBUF_TYPE_TIME_STAMP:
6204 		if (ts) {
6205 			*ts = rb_event_time_stamp(event);
6206 			*ts = rb_fix_abs_ts(*ts, reader->page->time_stamp);
6207 			ring_buffer_normalize_time_stamp(cpu_buffer->buffer,
6208 							 cpu_buffer->cpu, ts);
6209 		}
6210 		/* Internal data, OK to advance */
6211 		rb_advance_reader(cpu_buffer);
6212 		goto again;
6213 
6214 	case RINGBUF_TYPE_DATA:
6215 		if (ts && !(*ts)) {
6216 			*ts = cpu_buffer->read_stamp + event->time_delta;
6217 			ring_buffer_normalize_time_stamp(cpu_buffer->buffer,
6218 							 cpu_buffer->cpu, ts);
6219 		}
6220 		if (lost_events)
6221 			*lost_events = rb_lost_events(cpu_buffer);
6222 		return event;
6223 
6224 	default:
6225 		RB_WARN_ON(cpu_buffer, 1);
6226 	}
6227 
6228 	return NULL;
6229 }
6230 EXPORT_SYMBOL_GPL(ring_buffer_peek);
6231 
6232 static struct ring_buffer_event *
6233 rb_iter_peek(struct ring_buffer_iter *iter, u64 *ts)
6234 {
6235 	struct trace_buffer *buffer;
6236 	struct ring_buffer_per_cpu *cpu_buffer;
6237 	struct ring_buffer_event *event;
6238 	unsigned long nr_loops = 0;
6239 	unsigned long max_loops;
6240 
6241 	if (ts)
6242 		*ts = 0;
6243 
6244 	cpu_buffer = iter->cpu_buffer;
6245 	buffer = cpu_buffer->buffer;
6246 	max_loops = cpu_buffer->ring_meta ? cpu_buffer->nr_pages : 3;
6247 
6248 	/*
6249 	 * Check if someone performed a consuming read to the buffer
6250 	 * or removed some pages from the buffer. In these cases,
6251 	 * iterator was invalidated and we need to reset it.
6252 	 */
6253 	if (unlikely(iter->cache_read != cpu_buffer->read ||
6254 		     iter->cache_reader_page != cpu_buffer->reader_page ||
6255 		     iter->cache_pages_removed != cpu_buffer->pages_removed))
6256 		rb_iter_reset(iter);
6257 
6258  again:
6259 	if (ring_buffer_iter_empty(iter))
6260 		return NULL;
6261 
6262 	/*
6263 	 * As the writer can mess with what the iterator is trying
6264 	 * to read, just give up if we fail to get an event after
6265 	 * three tries. The iterator is not as reliable when reading
6266 	 * the ring buffer with an active write as the consumer is.
6267 	 * Do not warn if the three failures is reached.
6268 	 */
6269 	if (++nr_loops > max_loops)
6270 		return NULL;
6271 
6272 	if (rb_per_cpu_empty(cpu_buffer))
6273 		return NULL;
6274 
6275 	if (iter->head >= rb_page_size(iter->head_page)) {
6276 		rb_inc_iter(iter);
6277 		goto again;
6278 	}
6279 
6280 	event = rb_iter_head_event(iter);
6281 	if (!event)
6282 		goto again;
6283 
6284 	switch (event->type_len) {
6285 	case RINGBUF_TYPE_PADDING:
6286 		if (rb_null_event(event)) {
6287 			rb_inc_iter(iter);
6288 			goto again;
6289 		}
6290 		rb_advance_iter(iter);
6291 		return event;
6292 
6293 	case RINGBUF_TYPE_TIME_EXTEND:
6294 		/* Internal data, OK to advance */
6295 		rb_advance_iter(iter);
6296 		goto again;
6297 
6298 	case RINGBUF_TYPE_TIME_STAMP:
6299 		if (ts) {
6300 			*ts = rb_event_time_stamp(event);
6301 			*ts = rb_fix_abs_ts(*ts, iter->head_page->page->time_stamp);
6302 			ring_buffer_normalize_time_stamp(cpu_buffer->buffer,
6303 							 cpu_buffer->cpu, ts);
6304 		}
6305 		/* Internal data, OK to advance */
6306 		rb_advance_iter(iter);
6307 		goto again;
6308 
6309 	case RINGBUF_TYPE_DATA:
6310 		if (ts && !(*ts)) {
6311 			*ts = iter->read_stamp + event->time_delta;
6312 			ring_buffer_normalize_time_stamp(buffer,
6313 							 cpu_buffer->cpu, ts);
6314 		}
6315 		return event;
6316 
6317 	default:
6318 		RB_WARN_ON(cpu_buffer, 1);
6319 	}
6320 
6321 	return NULL;
6322 }
6323 EXPORT_SYMBOL_GPL(ring_buffer_iter_peek);
6324 
6325 static inline bool rb_reader_lock(struct ring_buffer_per_cpu *cpu_buffer)
6326 {
6327 	if (likely(!in_nmi())) {
6328 		raw_spin_lock(&cpu_buffer->reader_lock);
6329 		return true;
6330 	}
6331 
6332 	/*
6333 	 * If an NMI die dumps out the content of the ring buffer
6334 	 * trylock must be used to prevent a deadlock if the NMI
6335 	 * preempted a task that holds the ring buffer locks. If
6336 	 * we get the lock then all is fine, if not, then continue
6337 	 * to do the read, but this can corrupt the ring buffer,
6338 	 * so it must be permanently disabled from future writes.
6339 	 * Reading from NMI is a oneshot deal.
6340 	 */
6341 	if (raw_spin_trylock(&cpu_buffer->reader_lock))
6342 		return true;
6343 
6344 	/* Continue without locking, but disable the ring buffer */
6345 	atomic_inc(&cpu_buffer->record_disabled);
6346 	return false;
6347 }
6348 
6349 static inline void
6350 rb_reader_unlock(struct ring_buffer_per_cpu *cpu_buffer, bool locked)
6351 {
6352 	if (likely(locked))
6353 		raw_spin_unlock(&cpu_buffer->reader_lock);
6354 }
6355 
6356 /**
6357  * ring_buffer_peek - peek at the next event to be read
6358  * @buffer: The ring buffer to read
6359  * @cpu: The cpu to peak at
6360  * @ts: The timestamp counter of this event.
6361  * @lost_events: a variable to store if events were lost (may be NULL)
6362  *
6363  * This will return the event that will be read next, but does
6364  * not consume the data.
6365  */
6366 struct ring_buffer_event *
6367 ring_buffer_peek(struct trace_buffer *buffer, int cpu, u64 *ts,
6368 		 unsigned long *lost_events)
6369 {
6370 	struct ring_buffer_per_cpu *cpu_buffer = buffer->buffers[cpu];
6371 	struct ring_buffer_event *event;
6372 	unsigned long flags;
6373 	bool dolock;
6374 
6375 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
6376 		return NULL;
6377 
6378  again:
6379 	local_irq_save(flags);
6380 	dolock = rb_reader_lock(cpu_buffer);
6381 	event = rb_buffer_peek(cpu_buffer, ts, lost_events);
6382 	if (event && event->type_len == RINGBUF_TYPE_PADDING)
6383 		rb_advance_reader(cpu_buffer);
6384 	rb_reader_unlock(cpu_buffer, dolock);
6385 	local_irq_restore(flags);
6386 
6387 	if (event && event->type_len == RINGBUF_TYPE_PADDING)
6388 		goto again;
6389 
6390 	return event;
6391 }
6392 
6393 /** ring_buffer_iter_dropped - report if there are dropped events
6394  * @iter: The ring buffer iterator
6395  *
6396  * Returns true if there was dropped events since the last peek.
6397  */
6398 bool ring_buffer_iter_dropped(struct ring_buffer_iter *iter)
6399 {
6400 	return iter->missed_events != 0;
6401 }
6402 EXPORT_SYMBOL_GPL(ring_buffer_iter_dropped);
6403 
6404 /**
6405  * ring_buffer_iter_peek - peek at the next event to be read
6406  * @iter: The ring buffer iterator
6407  * @ts: The timestamp counter of this event.
6408  *
6409  * This will return the event that will be read next, but does
6410  * not increment the iterator.
6411  */
6412 struct ring_buffer_event *
6413 ring_buffer_iter_peek(struct ring_buffer_iter *iter, u64 *ts)
6414 {
6415 	struct ring_buffer_per_cpu *cpu_buffer = iter->cpu_buffer;
6416 	struct ring_buffer_event *event;
6417 	unsigned long flags;
6418 
6419  again:
6420 	raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
6421 	event = rb_iter_peek(iter, ts);
6422 	raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
6423 
6424 	if (event && event->type_len == RINGBUF_TYPE_PADDING)
6425 		goto again;
6426 
6427 	return event;
6428 }
6429 
6430 /**
6431  * ring_buffer_consume - return an event and consume it
6432  * @buffer: The ring buffer to get the next event from
6433  * @cpu: the cpu to read the buffer from
6434  * @ts: a variable to store the timestamp (may be NULL)
6435  * @lost_events: a variable to store if events were lost (may be NULL)
6436  *
6437  * Returns the next event in the ring buffer, and that event is consumed.
6438  * Meaning, that sequential reads will keep returning a different event,
6439  * and eventually empty the ring buffer if the producer is slower.
6440  */
6441 struct ring_buffer_event *
6442 ring_buffer_consume(struct trace_buffer *buffer, int cpu, u64 *ts,
6443 		    unsigned long *lost_events)
6444 {
6445 	struct ring_buffer_per_cpu *cpu_buffer;
6446 	struct ring_buffer_event *event = NULL;
6447 	unsigned long flags;
6448 	bool dolock;
6449 
6450  again:
6451 	/* might be called in atomic */
6452 	preempt_disable();
6453 
6454 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
6455 		goto out;
6456 
6457 	cpu_buffer = buffer->buffers[cpu];
6458 	local_irq_save(flags);
6459 	dolock = rb_reader_lock(cpu_buffer);
6460 
6461 	event = rb_buffer_peek(cpu_buffer, ts, lost_events);
6462 	if (event) {
6463 		cpu_buffer->lost_events = 0;
6464 		rb_advance_reader(cpu_buffer);
6465 	}
6466 
6467 	rb_reader_unlock(cpu_buffer, dolock);
6468 	local_irq_restore(flags);
6469 
6470  out:
6471 	preempt_enable();
6472 
6473 	if (event && event->type_len == RINGBUF_TYPE_PADDING)
6474 		goto again;
6475 
6476 	return event;
6477 }
6478 EXPORT_SYMBOL_GPL(ring_buffer_consume);
6479 
6480 /**
6481  * ring_buffer_read_start - start a non consuming read of the buffer
6482  * @buffer: The ring buffer to read from
6483  * @cpu: The cpu buffer to iterate over
6484  * @flags: gfp flags to use for memory allocation
6485  *
6486  * This creates an iterator to allow non-consuming iteration through
6487  * the buffer. If the buffer is disabled for writing, it will produce
6488  * the same information each time, but if the buffer is still writing
6489  * then the first hit of a write will cause the iteration to stop.
6490  *
6491  * Must be paired with ring_buffer_read_finish.
6492  */
6493 struct ring_buffer_iter *
6494 ring_buffer_read_start(struct trace_buffer *buffer, int cpu, gfp_t flags)
6495 {
6496 	struct ring_buffer_iter *iter __free(kfree) = kzalloc_obj(*iter, flags);
6497 	struct ring_buffer_per_cpu *cpu_buffer;
6498 
6499 	if (!iter)
6500 		return NULL;
6501 
6502 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
6503 		return NULL;
6504 
6505 	cpu_buffer = buffer->buffers[cpu];
6506 
6507 	/*
6508 	 * Only KDB is using GFP_ATOMIC, for the others, lock the buffer to
6509 	 * prevent concurrent resizing.
6510 	 */
6511 	if (gfpflags_allow_blocking(flags))
6512 		mutex_lock(&buffer->mutex);
6513 
6514 	atomic_inc(&cpu_buffer->resize_disabled);
6515 
6516 	if (gfpflags_allow_blocking(flags))
6517 		mutex_unlock(&buffer->mutex);
6518 
6519 	/* Holds the entire event: data and meta data. */
6520 	iter->event_size = rb_page_capacity(READ_ONCE(cpu_buffer->reader_page));
6521 	iter->event = kmalloc(iter->event_size, flags);
6522 	if (!iter->event) {
6523 		atomic_dec(&cpu_buffer->resize_disabled);
6524 		return NULL;
6525 	}
6526 	iter->cpu_buffer = cpu_buffer;
6527 
6528 	guard(raw_spinlock_irqsave)(&cpu_buffer->reader_lock);
6529 	arch_spin_lock(&cpu_buffer->lock);
6530 	rb_iter_reset(iter);
6531 	arch_spin_unlock(&cpu_buffer->lock);
6532 
6533 	return_ptr(iter);
6534 }
6535 EXPORT_SYMBOL_GPL(ring_buffer_read_start);
6536 
6537 /**
6538  * ring_buffer_read_finish - finish reading the iterator of the buffer
6539  * @iter: The iterator retrieved by ring_buffer_start
6540  *
6541  * This re-enables resizing of the buffer, and frees the iterator.
6542  */
6543 void
6544 ring_buffer_read_finish(struct ring_buffer_iter *iter)
6545 {
6546 	struct ring_buffer_per_cpu *cpu_buffer = iter->cpu_buffer;
6547 
6548 	/* Use this opportunity to check the integrity of the ring buffer. */
6549 	rb_check_pages(cpu_buffer);
6550 
6551 	atomic_dec(&cpu_buffer->resize_disabled);
6552 	kfree(iter->event);
6553 	kfree(iter);
6554 }
6555 EXPORT_SYMBOL_GPL(ring_buffer_read_finish);
6556 
6557 /**
6558  * ring_buffer_iter_advance - advance the iterator to the next location
6559  * @iter: The ring buffer iterator
6560  *
6561  * Move the location of the iterator such that the next read will
6562  * be the next location of the iterator.
6563  */
6564 void ring_buffer_iter_advance(struct ring_buffer_iter *iter)
6565 {
6566 	struct ring_buffer_per_cpu *cpu_buffer = iter->cpu_buffer;
6567 	unsigned long flags;
6568 
6569 	raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
6570 	iter->missed_events = 0;
6571 	rb_advance_iter(iter);
6572 
6573 	raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
6574 }
6575 EXPORT_SYMBOL_GPL(ring_buffer_iter_advance);
6576 
6577 /**
6578  * ring_buffer_capacity - return the capacity of the ring buffer (in bytes)
6579  * @buffer: The ring buffer.
6580  * @cpu: The CPU to get ring buffer capacity from.
6581  *
6582  * Capacity is the total memory available for recording event data in the
6583  * ring buffer. It excludes subbuffer headers.
6584  *
6585  * Returns the capacity in bytes, or 0 if the CPU is not set in the buffer mask.
6586  */
6587 unsigned long ring_buffer_capacity(struct trace_buffer *buffer, int cpu)
6588 {
6589 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
6590 		return 0;
6591 
6592 	return rb_subbuf_capacity(buffer) * buffer->buffers[cpu]->nr_pages;
6593 }
6594 EXPORT_SYMBOL_GPL(ring_buffer_capacity);
6595 
6596 /**
6597  * ring_buffer_max_event_size - return the max data size of an event
6598  * @buffer: The ring buffer.
6599  *
6600  * Returns the maximum size an event can be.
6601  */
6602 unsigned long ring_buffer_max_event_size(struct trace_buffer *buffer)
6603 {
6604 	/* If abs timestamp is requested, events have a timestamp too */
6605 	if (ring_buffer_time_stamp_abs(buffer))
6606 		return rb_subbuf_max_data_size(buffer) - RB_LEN_TIME_EXTEND;
6607 
6608 	return rb_subbuf_max_data_size(buffer);
6609 }
6610 EXPORT_SYMBOL_GPL(ring_buffer_max_event_size);
6611 
6612 static void rb_clear_buffer_page(struct buffer_page *page)
6613 {
6614 	local_set(&page->write, 0);
6615 	local_set(&page->entries, 0);
6616 	rb_init_data_page(page->page);
6617 	page->read = 0;
6618 }
6619 
6620 /*
6621  * When the buffer is memory mapped to user space, each sub buffer
6622  * has a unique id that is used by the meta data to tell the user
6623  * where the current reader page is.
6624  *
6625  * For a normal allocated ring buffer, the id is saved in the buffer page
6626  * id field, and updated via this function.
6627  *
6628  * But for a fixed memory mapped buffer, the id is already assigned for
6629  * fixed memory ordering in the memory layout and can not be used. Instead
6630  * the index of where the page lies in the memory layout is used.
6631  *
6632  * For the normal pages, set the buffer page id with the passed in @id
6633  * value and return that.
6634  *
6635  * For fixed memory mapped pages, get the page index in the memory layout
6636  * and return that as the id.
6637  */
6638 static int rb_page_id(struct ring_buffer_per_cpu *cpu_buffer,
6639 		      struct buffer_page *bpage, int id)
6640 {
6641 	/*
6642 	 * For boot buffers, the id is the index,
6643 	 * otherwise, set the buffer page with this id
6644 	 */
6645 	if (cpu_buffer->ring_meta)
6646 		id = rb_meta_subbuf_idx(cpu_buffer->ring_meta, bpage->page);
6647 	else
6648 		bpage->id = id;
6649 
6650 	return id;
6651 }
6652 
6653 static void rb_update_meta_page(struct ring_buffer_per_cpu *cpu_buffer)
6654 {
6655 	struct trace_buffer_meta *meta = cpu_buffer->meta_page;
6656 
6657 	if (!meta)
6658 		return;
6659 
6660 	meta->reader.read = cpu_buffer->reader_page->read;
6661 	meta->reader.id = rb_page_id(cpu_buffer, cpu_buffer->reader_page,
6662 				     cpu_buffer->reader_page->id);
6663 
6664 	meta->reader.lost_events = cpu_buffer->lost_events;
6665 
6666 	meta->entries = local_read(&cpu_buffer->entries);
6667 	meta->overrun = local_read(&cpu_buffer->overrun);
6668 	meta->read = cpu_buffer->read;
6669 	meta->pages_lost = local_read(&cpu_buffer->pages_lost);
6670 	meta->pages_touched = local_read(&cpu_buffer->pages_touched);
6671 
6672 	/* Some archs do not have data cache coherency between kernel and user-space */
6673 	flush_kernel_vmap_range(cpu_buffer->meta_page, PAGE_SIZE);
6674 }
6675 
6676 static void
6677 rb_reset_cpu(struct ring_buffer_per_cpu *cpu_buffer)
6678 {
6679 	struct buffer_page *page;
6680 
6681 	if (cpu_buffer->remote) {
6682 		if (!cpu_buffer->remote->reset)
6683 			return;
6684 
6685 		cpu_buffer->remote->reset(cpu_buffer->cpu, cpu_buffer->remote->priv);
6686 		rb_read_remote_meta_page(cpu_buffer);
6687 
6688 		/* Read related values, not covered by the meta-page */
6689 		local_set(&cpu_buffer->pages_read, 0);
6690 		cpu_buffer->read = 0;
6691 		cpu_buffer->read_bytes = 0;
6692 		cpu_buffer->last_overrun = 0;
6693 		cpu_buffer->reader_page->read = 0;
6694 
6695 		return;
6696 	}
6697 
6698 	rb_head_page_deactivate(cpu_buffer);
6699 
6700 	cpu_buffer->head_page
6701 		= list_entry(cpu_buffer->pages, struct buffer_page, list);
6702 	rb_clear_buffer_page(cpu_buffer->head_page);
6703 	list_for_each_entry(page, cpu_buffer->pages, list) {
6704 		rb_clear_buffer_page(page);
6705 	}
6706 
6707 	cpu_buffer->tail_page = cpu_buffer->head_page;
6708 	cpu_buffer->commit_page = cpu_buffer->head_page;
6709 
6710 	INIT_LIST_HEAD(&cpu_buffer->reader_page->list);
6711 	INIT_LIST_HEAD(&cpu_buffer->new_pages);
6712 	rb_clear_buffer_page(cpu_buffer->reader_page);
6713 
6714 	local_set(&cpu_buffer->entries_bytes, 0);
6715 	local_set(&cpu_buffer->overrun, 0);
6716 	local_set(&cpu_buffer->commit_overrun, 0);
6717 	local_set(&cpu_buffer->dropped_events, 0);
6718 	local_set(&cpu_buffer->entries, 0);
6719 	local_set(&cpu_buffer->committing, 0);
6720 	local_set(&cpu_buffer->commits, 0);
6721 	local_set(&cpu_buffer->pages_touched, 0);
6722 	local_set(&cpu_buffer->pages_lost, 0);
6723 	local_set(&cpu_buffer->pages_read, 0);
6724 	cpu_buffer->last_pages_touch = 0;
6725 	cpu_buffer->shortest_full = 0;
6726 	cpu_buffer->read = 0;
6727 	cpu_buffer->read_bytes = 0;
6728 
6729 	rb_time_set(&cpu_buffer->write_stamp, 0);
6730 	rb_time_set(&cpu_buffer->before_stamp, 0);
6731 
6732 	memset(cpu_buffer->event_stamp, 0, sizeof(cpu_buffer->event_stamp));
6733 
6734 	cpu_buffer->lost_events = 0;
6735 	cpu_buffer->last_overrun = 0;
6736 
6737 	rb_head_page_activate(cpu_buffer);
6738 	cpu_buffer->pages_removed = 0;
6739 
6740 	rb_update_meta_page(cpu_buffer);
6741 	if (cpu_buffer->ring_meta) {
6742 		struct ring_buffer_cpu_meta *meta = cpu_buffer->ring_meta;
6743 
6744 		meta->commit_buffer = meta->head_buffer;
6745 	}
6746 }
6747 
6748 /* Must have disabled the cpu buffer then done a synchronize_rcu */
6749 static void reset_disabled_cpu_buffer(struct ring_buffer_per_cpu *cpu_buffer)
6750 {
6751 	guard(raw_spinlock_irqsave)(&cpu_buffer->reader_lock);
6752 
6753 	if (RB_WARN_ON(cpu_buffer, local_read(&cpu_buffer->committing)))
6754 		return;
6755 
6756 	arch_spin_lock(&cpu_buffer->lock);
6757 
6758 	rb_reset_cpu(cpu_buffer);
6759 
6760 	arch_spin_unlock(&cpu_buffer->lock);
6761 }
6762 
6763 /**
6764  * ring_buffer_reset_cpu - reset a ring buffer per CPU buffer
6765  * @buffer: The ring buffer to reset a per cpu buffer of
6766  * @cpu: The CPU buffer to be reset
6767  */
6768 void ring_buffer_reset_cpu(struct trace_buffer *buffer, int cpu)
6769 {
6770 	struct ring_buffer_per_cpu *cpu_buffer = buffer->buffers[cpu];
6771 
6772 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
6773 		return;
6774 
6775 	/* prevent another thread from changing buffer sizes */
6776 	mutex_lock(&buffer->mutex);
6777 
6778 	atomic_inc(&cpu_buffer->resize_disabled);
6779 	atomic_inc(&cpu_buffer->record_disabled);
6780 
6781 	/* Make sure all commits have finished */
6782 	synchronize_rcu();
6783 
6784 	reset_disabled_cpu_buffer(cpu_buffer);
6785 
6786 	atomic_dec(&cpu_buffer->record_disabled);
6787 	atomic_dec(&cpu_buffer->resize_disabled);
6788 
6789 	mutex_unlock(&buffer->mutex);
6790 }
6791 EXPORT_SYMBOL_GPL(ring_buffer_reset_cpu);
6792 
6793 /* Flag to ensure proper resetting of atomic variables */
6794 #define RESET_BIT	(1 << 30)
6795 
6796 /**
6797  * ring_buffer_reset_online_cpus - reset a ring buffer per CPU buffer
6798  * @buffer: The ring buffer to reset a per cpu buffer of
6799  */
6800 void ring_buffer_reset_online_cpus(struct trace_buffer *buffer)
6801 {
6802 	struct ring_buffer_per_cpu *cpu_buffer;
6803 	int cpu;
6804 
6805 	/* prevent another thread from changing buffer sizes */
6806 	mutex_lock(&buffer->mutex);
6807 
6808 	for_each_online_buffer_cpu(buffer, cpu) {
6809 		cpu_buffer = buffer->buffers[cpu];
6810 
6811 		atomic_add(RESET_BIT, &cpu_buffer->resize_disabled);
6812 		atomic_inc(&cpu_buffer->record_disabled);
6813 	}
6814 
6815 	/* Make sure all commits have finished */
6816 	synchronize_rcu();
6817 
6818 	for_each_buffer_cpu(buffer, cpu) {
6819 		cpu_buffer = buffer->buffers[cpu];
6820 
6821 		/*
6822 		 * If a CPU came online during the synchronize_rcu(), then
6823 		 * ignore it.
6824 		 */
6825 		if (!(atomic_read(&cpu_buffer->resize_disabled) & RESET_BIT))
6826 			continue;
6827 
6828 		reset_disabled_cpu_buffer(cpu_buffer);
6829 
6830 		atomic_dec(&cpu_buffer->record_disabled);
6831 		atomic_sub(RESET_BIT, &cpu_buffer->resize_disabled);
6832 	}
6833 
6834 	mutex_unlock(&buffer->mutex);
6835 }
6836 
6837 /**
6838  * ring_buffer_reset - reset a ring buffer
6839  * @buffer: The ring buffer to reset all cpu buffers
6840  */
6841 void ring_buffer_reset(struct trace_buffer *buffer)
6842 {
6843 	struct ring_buffer_per_cpu *cpu_buffer;
6844 	int cpu;
6845 
6846 	/* prevent another thread from changing buffer sizes */
6847 	mutex_lock(&buffer->mutex);
6848 
6849 	for_each_buffer_cpu(buffer, cpu) {
6850 		cpu_buffer = buffer->buffers[cpu];
6851 
6852 		atomic_inc(&cpu_buffer->resize_disabled);
6853 		atomic_inc(&cpu_buffer->record_disabled);
6854 	}
6855 
6856 	/* Make sure all commits have finished */
6857 	synchronize_rcu();
6858 
6859 	for_each_buffer_cpu(buffer, cpu) {
6860 		cpu_buffer = buffer->buffers[cpu];
6861 
6862 		reset_disabled_cpu_buffer(cpu_buffer);
6863 
6864 		atomic_dec(&cpu_buffer->record_disabled);
6865 		atomic_dec(&cpu_buffer->resize_disabled);
6866 	}
6867 
6868 	mutex_unlock(&buffer->mutex);
6869 }
6870 EXPORT_SYMBOL_GPL(ring_buffer_reset);
6871 
6872 /**
6873  * ring_buffer_empty - is the ring buffer empty?
6874  * @buffer: The ring buffer to test
6875  */
6876 bool ring_buffer_empty(struct trace_buffer *buffer)
6877 {
6878 	struct ring_buffer_per_cpu *cpu_buffer;
6879 	unsigned long flags;
6880 	bool dolock;
6881 	bool ret;
6882 	int cpu;
6883 
6884 	/* yes this is racy, but if you don't like the race, lock the buffer */
6885 	for_each_buffer_cpu(buffer, cpu) {
6886 		cpu_buffer = buffer->buffers[cpu];
6887 		local_irq_save(flags);
6888 		dolock = rb_reader_lock(cpu_buffer);
6889 		ret = rb_per_cpu_empty(cpu_buffer);
6890 		rb_reader_unlock(cpu_buffer, dolock);
6891 		local_irq_restore(flags);
6892 
6893 		if (!ret)
6894 			return false;
6895 	}
6896 
6897 	return true;
6898 }
6899 EXPORT_SYMBOL_GPL(ring_buffer_empty);
6900 
6901 /**
6902  * ring_buffer_empty_cpu - is a cpu buffer of a ring buffer empty?
6903  * @buffer: The ring buffer
6904  * @cpu: The CPU buffer to test
6905  */
6906 bool ring_buffer_empty_cpu(struct trace_buffer *buffer, int cpu)
6907 {
6908 	struct ring_buffer_per_cpu *cpu_buffer;
6909 	unsigned long flags;
6910 	bool dolock;
6911 	bool ret;
6912 
6913 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
6914 		return true;
6915 
6916 	cpu_buffer = buffer->buffers[cpu];
6917 	local_irq_save(flags);
6918 	dolock = rb_reader_lock(cpu_buffer);
6919 	ret = rb_per_cpu_empty(cpu_buffer);
6920 	rb_reader_unlock(cpu_buffer, dolock);
6921 	local_irq_restore(flags);
6922 
6923 	return ret;
6924 }
6925 EXPORT_SYMBOL_GPL(ring_buffer_empty_cpu);
6926 
6927 int ring_buffer_poll_remote(struct trace_buffer *buffer, int cpu)
6928 {
6929 	struct ring_buffer_per_cpu *cpu_buffer;
6930 
6931 	if (cpu != RING_BUFFER_ALL_CPUS) {
6932 		if (!cpumask_test_cpu(cpu, buffer->cpumask))
6933 			return -EINVAL;
6934 
6935 		cpu_buffer = buffer->buffers[cpu];
6936 
6937 		guard(raw_spinlock)(&cpu_buffer->reader_lock);
6938 		rb_read_remote_meta_page(cpu_buffer);
6939 		if (rb_num_of_entries(cpu_buffer))
6940 			rb_wakeups(buffer, cpu_buffer);
6941 
6942 		return 0;
6943 	}
6944 
6945 	guard(cpus_read_lock)();
6946 
6947 	/*
6948 	 * Make sure all the ring buffers are up to date before we start reading
6949 	 * them.
6950 	 */
6951 	for_each_buffer_cpu(buffer, cpu) {
6952 		cpu_buffer = buffer->buffers[cpu];
6953 
6954 		guard(raw_spinlock)(&cpu_buffer->reader_lock);
6955 		rb_read_remote_meta_page(cpu_buffer);
6956 	}
6957 
6958 	for_each_buffer_cpu(buffer, cpu) {
6959 		cpu_buffer = buffer->buffers[cpu];
6960 
6961 		if (rb_num_of_entries(cpu_buffer))
6962 			rb_wakeups(buffer, cpu_buffer);
6963 	}
6964 
6965 	return 0;
6966 }
6967 
6968 #ifdef CONFIG_RING_BUFFER_ALLOW_SWAP
6969 /**
6970  * ring_buffer_swap_cpu - swap a CPU buffer between two ring buffers
6971  * @buffer_a: One buffer to swap with
6972  * @buffer_b: The other buffer to swap with
6973  * @cpu: the CPU of the buffers to swap
6974  *
6975  * This function is useful for tracers that want to take a "snapshot"
6976  * of a CPU buffer and has another back up buffer lying around.
6977  * it is expected that the tracer handles the cpu buffer not being
6978  * used at the moment.
6979  */
6980 int ring_buffer_swap_cpu(struct trace_buffer *buffer_a,
6981 			 struct trace_buffer *buffer_b, int cpu)
6982 {
6983 	struct ring_buffer_per_cpu *cpu_buffer_a;
6984 	struct ring_buffer_per_cpu *cpu_buffer_b;
6985 	int ret = -EBUSY;
6986 
6987 	if (!cpumask_test_cpu(cpu, buffer_a->cpumask) ||
6988 	    !cpumask_test_cpu(cpu, buffer_b->cpumask))
6989 		return -EINVAL;
6990 
6991 	cpu_buffer_a = buffer_a->buffers[cpu];
6992 	cpu_buffer_b = buffer_b->buffers[cpu];
6993 
6994 	/* It's up to the callers to not try to swap static buffers */
6995 	if (WARN_ON_ONCE(rb_is_static(cpu_buffer_a) || rb_is_static(cpu_buffer_b)))
6996 		return -EBUSY;
6997 
6998 	/* At least make sure the two buffers are somewhat the same */
6999 	if (cpu_buffer_a->nr_pages != cpu_buffer_b->nr_pages)
7000 		return -EINVAL;
7001 
7002 	if (buffer_a->subbuf_order != buffer_b->subbuf_order)
7003 		return -EINVAL;
7004 
7005 	if (atomic_read(&buffer_a->record_disabled))
7006 		return -EAGAIN;
7007 
7008 	if (atomic_read(&buffer_b->record_disabled))
7009 		return -EAGAIN;
7010 
7011 	if (atomic_read(&cpu_buffer_a->record_disabled))
7012 		return -EAGAIN;
7013 
7014 	if (atomic_read(&cpu_buffer_b->record_disabled))
7015 		return -EAGAIN;
7016 
7017 	/*
7018 	 * We can't do a synchronize_rcu here because this
7019 	 * function can be called in atomic context.
7020 	 * Normally this will be called from the same CPU as cpu.
7021 	 * If not it's up to the caller to protect this.
7022 	 */
7023 	atomic_inc(&cpu_buffer_a->record_disabled);
7024 	atomic_inc(&cpu_buffer_b->record_disabled);
7025 
7026 	/* Do not swap if either buffer is in the process of writing */
7027 	if (cpu_buffer_a->current_context)
7028 		goto out_dec;
7029 	if (cpu_buffer_b->current_context)
7030 		goto out_dec;
7031 
7032 	/*
7033 	 * When resize is in progress, we cannot swap it because
7034 	 * it will mess the state of the cpu buffer.
7035 	 */
7036 	if (atomic_read(&buffer_a->resizing))
7037 		goto out_dec;
7038 	if (atomic_read(&buffer_b->resizing))
7039 		goto out_dec;
7040 
7041 	buffer_a->buffers[cpu] = cpu_buffer_b;
7042 	buffer_b->buffers[cpu] = cpu_buffer_a;
7043 
7044 	cpu_buffer_b->buffer = buffer_a;
7045 	cpu_buffer_a->buffer = buffer_b;
7046 
7047 	ret = 0;
7048 
7049 out_dec:
7050 	atomic_dec(&cpu_buffer_a->record_disabled);
7051 	atomic_dec(&cpu_buffer_b->record_disabled);
7052 	return ret;
7053 }
7054 EXPORT_SYMBOL_GPL(ring_buffer_swap_cpu);
7055 #endif /* CONFIG_RING_BUFFER_ALLOW_SWAP */
7056 
7057 /**
7058  * ring_buffer_alloc_read_page - allocate a page to read from buffer
7059  * @buffer: the buffer to allocate for.
7060  * @cpu: the cpu buffer to allocate.
7061  * @rpage: pointer to pass in an already allocated page (can be NULL)
7062  *         and returns the allocated page.
7063  *
7064  * This function is used in conjunction with ring_buffer_read_page().
7065  * When reading a full page from the ring buffer, these functions
7066  * can be used to speed up the process. The calling function should
7067  * allocate a few pages first with this function. Then when it
7068  * needs to get pages from the ring buffer, it passes the result
7069  * of this function into ring_buffer_read_page(), which will swap
7070  * the page that was allocated, with the read page of the buffer.
7071  *
7072  * If @rpage is provided, and it has a different order than the current
7073  * subbuffer order, its payload will be freed and re-allocated. If it
7074  * already matches the order, it is simply returned.
7075  *
7076  * Returns:
7077  *  0 on success, < 0 on error
7078  */
7079 int ring_buffer_alloc_read_page(struct trace_buffer *buffer, int cpu,
7080 				struct buffer_data_read_page **rpage)
7081 {
7082 	struct ring_buffer_per_cpu *cpu_buffer;
7083 	unsigned long flags;
7084 	unsigned int order;
7085 
7086 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
7087 		return -ENODEV;
7088 
7089 	if (!rpage)
7090 		return -EINVAL;
7091 
7092 	order = READ_ONCE(buffer->subbuf_order);
7093 
7094 	if (*rpage) {
7095 		if ((*rpage)->order == order)
7096 			return 0;
7097 
7098 		/* We can reuse rpage, but we discard the payload */
7099 		free_pages((unsigned long)(*rpage)->data, (*rpage)->order);
7100 		(*rpage)->data = NULL;
7101 	} else {
7102 		*rpage = kzalloc_obj(**rpage);
7103 		if (!*rpage)
7104 			return -ENOMEM;
7105 	}
7106 
7107 	(*rpage)->order = order;
7108 	cpu_buffer = buffer->buffers[cpu];
7109 
7110 	local_irq_save(flags);
7111 	arch_spin_lock(&cpu_buffer->lock);
7112 
7113 	if (cpu_buffer->free_page.data) {
7114 		**rpage = cpu_buffer->free_page;
7115 		cpu_buffer->free_page.data = NULL;
7116 	}
7117 
7118 	arch_spin_unlock(&cpu_buffer->lock);
7119 	local_irq_restore(flags);
7120 
7121 	if ((*rpage)->data) {
7122 		rb_init_data_page((*rpage)->data);
7123 	} else {
7124 		(*rpage)->data = alloc_cpu_data(cpu, (*rpage)->order);
7125 		if (!(*rpage)->data) {
7126 			kfree(*rpage);
7127 			*rpage = NULL;
7128 			return -ENOMEM;
7129 		}
7130 	}
7131 
7132 	return 0;
7133 }
7134 EXPORT_SYMBOL_GPL(ring_buffer_alloc_read_page);
7135 
7136 /**
7137  * ring_buffer_free_read_page - free an allocated read page
7138  * @buffer: the buffer the page was allocate for
7139  * @cpu: the cpu buffer the page came from
7140  * @rpage: the buffer_data_read_page to free
7141  *
7142  * Free a page allocated from ring_buffer_alloc_read_page.
7143  */
7144 void ring_buffer_free_read_page(struct trace_buffer *buffer, int cpu,
7145 				struct buffer_data_read_page *rpage)
7146 {
7147 	struct ring_buffer_per_cpu *cpu_buffer;
7148 	struct buffer_data_page *dpage;
7149 	unsigned long flags;
7150 	struct page *page;
7151 
7152 	if (!buffer || !buffer->buffers || !buffer->buffers[cpu])
7153 		return;
7154 
7155 	if (!rpage)
7156 		return;
7157 
7158 	dpage = rpage->data;
7159 	if (!dpage)
7160 		goto out;
7161 
7162 	page = virt_to_page(dpage);
7163 
7164 	cpu_buffer = buffer->buffers[cpu];
7165 
7166 	/*
7167 	 * If the page is still in use someplace else, or order of the page
7168 	 * is different from the subbuffer order of the buffer -
7169 	 * we can't reuse it
7170 	 */
7171 	if (page_ref_count(page) > 1 || rpage->order != READ_ONCE(buffer->subbuf_order))
7172 		goto out;
7173 
7174 	local_irq_save(flags);
7175 	arch_spin_lock(&cpu_buffer->lock);
7176 
7177 	if (!cpu_buffer->free_page.data) {
7178 		cpu_buffer->free_page = *rpage;
7179 		dpage = NULL;
7180 	}
7181 
7182 	arch_spin_unlock(&cpu_buffer->lock);
7183 	local_irq_restore(flags);
7184 
7185  out:
7186 	free_pages((unsigned long)dpage, rpage->order);
7187 	kfree(rpage);
7188 }
7189 EXPORT_SYMBOL_GPL(ring_buffer_free_read_page);
7190 
7191 /**
7192  * ring_buffer_read_page - extract a page from the ring buffer
7193  * @buffer: buffer to extract from
7194  * @data_page: the page to use allocated from ring_buffer_alloc_read_page
7195  * @len: amount to extract
7196  * @cpu: the cpu of the buffer to extract
7197  * @full: should the extraction only happen when the page is full.
7198  *
7199  * This function will pull out a page from the ring buffer and consume it.
7200  * @data_page must be the address of the variable that was returned
7201  * from ring_buffer_alloc_read_page. This is because the page might be used
7202  * to swap with a page in the ring buffer.
7203  *
7204  * for example:
7205  *	rpage = ring_buffer_alloc_read_page(buffer, cpu);
7206  *	if (IS_ERR(rpage))
7207  *		return PTR_ERR(rpage);
7208  *	ret = ring_buffer_read_page(buffer, rpage, len, cpu, 0);
7209  *	if (ret >= 0)
7210  *		process_page(ring_buffer_read_page_data(rpage), ret);
7211  *	ring_buffer_free_read_page(buffer, cpu, rpage);
7212  *
7213  * When @full is set, the function will not return true unless
7214  * the writer is off the reader page.
7215  *
7216  * Note: it is up to the calling functions to handle sleeps and wakeups.
7217  *  The ring buffer can be used anywhere in the kernel and can not
7218  *  blindly call wake_up. The layer that uses the ring buffer must be
7219  *  responsible for that.
7220  *
7221  * Returns:
7222  *  >=0 if data has been transferred, returns the offset of consumed data.
7223  *  <0 if no data has been transferred.
7224  */
7225 int ring_buffer_read_page(struct trace_buffer *buffer,
7226 			  struct buffer_data_read_page *data_page,
7227 			  size_t len, int cpu, int full)
7228 {
7229 	struct ring_buffer_per_cpu *cpu_buffer = buffer->buffers[cpu];
7230 	struct ring_buffer_event *event;
7231 	struct buffer_data_page *dpage;
7232 	struct buffer_page *reader;
7233 	long missed_events;
7234 	unsigned int commit;
7235 	unsigned int size;
7236 	unsigned int read;
7237 	u64 save_timestamp;
7238 
7239 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
7240 		return -1;
7241 
7242 	/*
7243 	 * If len is not big enough to hold the page header, then
7244 	 * we can not copy anything.
7245 	 */
7246 	if (len <= BUF_PAGE_HDR_SIZE)
7247 		return -1;
7248 
7249 	len -= BUF_PAGE_HDR_SIZE;
7250 
7251 	if (!data_page || !data_page->data)
7252 		return -1;
7253 
7254 	dpage = data_page->data;
7255 	if (!dpage)
7256 		return -1;
7257 
7258 	len = min_t(size_t, len, rb_read_page_capacity(data_page));
7259 
7260 	guard(raw_spinlock_irqsave)(&cpu_buffer->reader_lock);
7261 
7262 	reader = rb_get_reader_page(cpu_buffer);
7263 	if (!reader)
7264 		return -1;
7265 
7266 	event = rb_reader_event(cpu_buffer);
7267 
7268 	read = reader->read;
7269 	commit = rb_page_commit(reader);
7270 	size = rb_page_size(reader);
7271 
7272 	/* Check if any events were dropped */
7273 	missed_events = cpu_buffer->lost_events;
7274 
7275 	 /*
7276 	  * It is not possible to swap the reader page if:
7277 	  *   - It has been partially read
7278 	  *   - len is not big enough to read it entirely
7279 	  *   - A writer is still on it
7280 	  *   - The ring buffer is static
7281 	  *   - The order doesn't match
7282 	  */
7283 	if (read || (len < (size - read)) ||
7284 	    cpu_buffer->reader_page == cpu_buffer->commit_page ||
7285 	    rb_is_static(cpu_buffer) ||
7286 	    data_page->order != reader->order) {
7287 		struct buffer_data_page *rpage = cpu_buffer->reader_page->page;
7288 		unsigned int rpos = read;
7289 		unsigned int pos = 0;
7290 		unsigned int event_size;
7291 		unsigned int flags = 0;
7292 
7293 		/* If a full page is requested, it cannot be the commit page */
7294 		if (full && cpu_buffer->reader_page == cpu_buffer->commit_page)
7295 			return -1;
7296 
7297 		if (len > (size - read))
7298 			len = (size - read);
7299 
7300 		/* Always keep the time extend and data together */
7301 		event_size = rb_event_ts_length(event);
7302 
7303 		if (len < event_size)
7304 			return -1;
7305 
7306 		if (commit & RB_MISSED_EVENTS)
7307 			flags = RB_MISSED_EVENTS;
7308 
7309 		/* save the current timestamp, since the user will need it */
7310 		save_timestamp = cpu_buffer->read_stamp;
7311 
7312 		/* Need to copy one event at a time */
7313 		do {
7314 			/* We need the size of one event, because
7315 			 * rb_advance_reader only advances by one event,
7316 			 * whereas rb_event_ts_length may include the size of
7317 			 * one or two events.
7318 			 * We have already ensured there's enough space if this
7319 			 * is a time extend. */
7320 			event_size = rb_event_length(event);
7321 			memcpy(dpage->data + pos, rpage->data + rpos, event_size);
7322 
7323 			len -= event_size;
7324 
7325 			rb_advance_reader(cpu_buffer);
7326 			rpos = reader->read;
7327 			pos += event_size;
7328 
7329 			if (rpos >= size)
7330 				break;
7331 
7332 			event = rb_reader_event(cpu_buffer);
7333 			/* Always keep the time extend and data together */
7334 			event_size = rb_event_ts_length(event);
7335 		} while (len >= event_size);
7336 
7337 		/* update dpage */
7338 		local_set(&dpage->commit, pos | flags);
7339 		dpage->time_stamp = save_timestamp;
7340 
7341 		/* we copied everything to the beginning */
7342 		read = 0;
7343 	} else {
7344 		/* update the entry counter */
7345 		cpu_buffer->read += rb_page_entries(reader);
7346 		cpu_buffer->read_bytes += rb_page_size(reader);
7347 
7348 		/* swap the pages */
7349 		rb_init_data_page(dpage);
7350 		dpage = reader->page;
7351 		reader->page = data_page->data;
7352 		local_set(&reader->write, 0);
7353 		local_set(&reader->entries, 0);
7354 		reader->read = 0;
7355 		data_page->data = dpage;
7356 		if (!missed_events && rb_data_page_commit(dpage) & RB_MISSED_EVENTS)
7357 			missed_events = -1;
7358 
7359 		/*
7360 		 * Use the real_end for the data size,
7361 		 * This gives us a chance to store the lost events
7362 		 * on the page.
7363 		 */
7364 		if (reader->real_end)
7365 			local_set(&dpage->commit, reader->real_end);
7366 	}
7367 
7368 	cpu_buffer->lost_events = 0;
7369 
7370 	size = rb_data_page_size(dpage);
7371 	/*
7372 	 * Set a flag in the commit field if we lost events
7373 	 */
7374 	if (missed_events) {
7375 		/*
7376 		 * If there is room at the end of the page to save the
7377 		 * missed events, then record it there.
7378 		 */
7379 		if (missed_events > 0 &&
7380 		    rb_read_page_capacity(data_page) - size >= sizeof(missed_events)) {
7381 			memcpy(&dpage->data[size], &missed_events,
7382 			       sizeof(missed_events));
7383 			local_add(RB_MISSED_STORED, &dpage->commit);
7384 			size += sizeof(missed_events);
7385 		}
7386 		/*
7387 		 * Note, for the persistent ring buffer, the RB_MISSED_EVENTS
7388 		 * may have been set in the main buffer via the verification code.
7389 		 * But here, dpage is a copy of that page and has not yet had
7390 		 * the RB_MISSED_EVENTS set. As for the normal buffers,
7391 		 * the main write buffer does not set these bits and it needs
7392 		 * to be set here.
7393 		 */
7394 		local_add(RB_MISSED_EVENTS, &dpage->commit);
7395 	}
7396 
7397 	/*
7398 	 * This page may be off to user land. Zero it out here.
7399 	 */
7400 	if (size < rb_read_page_capacity(data_page))
7401 		memset(&dpage->data[size], 0, rb_read_page_capacity(data_page) - size);
7402 
7403 	return read;
7404 }
7405 EXPORT_SYMBOL_GPL(ring_buffer_read_page);
7406 
7407 /**
7408  * ring_buffer_read_page_data - get pointer to the data in the page.
7409  * @page:  the page to get the data from
7410  *
7411  * Returns pointer to the actual data in this page.
7412  */
7413 void *ring_buffer_read_page_data(struct buffer_data_read_page *page)
7414 {
7415 	return page->data;
7416 }
7417 EXPORT_SYMBOL_GPL(ring_buffer_read_page_data);
7418 
7419 /**
7420  * ring_buffer_read_page_size - get size of the read page.
7421  * @rpage:  the page to get the size from
7422  *
7423  * Returns size of the page in bytes.
7424  */
7425 unsigned int ring_buffer_read_page_size(struct buffer_data_read_page *rpage)
7426 {
7427 	return rpage ? PAGE_SIZE << rpage->order : 0;
7428 }
7429 EXPORT_SYMBOL_GPL(ring_buffer_read_page_size);
7430 
7431 /**
7432  * ring_buffer_subbuf_size_get - get size of the sub buffer.
7433  * @buffer: the buffer to get the sub buffer size from
7434  *
7435  * Returns size of the sub buffer, in bytes.
7436  */
7437 int ring_buffer_subbuf_size_get(struct trace_buffer *buffer)
7438 {
7439 	return rb_subbuf_size(buffer);
7440 }
7441 EXPORT_SYMBOL_GPL(ring_buffer_subbuf_size_get);
7442 
7443 /**
7444  * ring_buffer_subbuf_order_get - get order of system sub pages in one buffer page.
7445  * @buffer: The ring_buffer to get the system sub page order from
7446  *
7447  * By default, one ring buffer sub page equals to one system page. This parameter
7448  * is configurable, per ring buffer. The size of the ring buffer sub page can be
7449  * extended, but must be an order of system page size.
7450  *
7451  * Returns the order of buffer sub page size, in system pages:
7452  * 0 means the sub buffer size is 1 system page and so forth.
7453  * In case of an error < 0 is returned.
7454  */
7455 int ring_buffer_subbuf_order_get(struct trace_buffer *buffer)
7456 {
7457 	if (!buffer)
7458 		return -EINVAL;
7459 
7460 	return buffer->subbuf_order;
7461 }
7462 EXPORT_SYMBOL_GPL(ring_buffer_subbuf_order_get);
7463 
7464 /**
7465  * ring_buffer_subbuf_order_set - set the size of ring buffer sub page.
7466  * @buffer: The ring_buffer to set the new page size.
7467  * @order: Order of the system pages in one sub buffer page
7468  *
7469  * By default, one ring buffer pages equals to one system page. This API can be
7470  * used to set new size of the ring buffer page. The size must be order of
7471  * system page size, that's why the input parameter @order is the order of
7472  * system pages that are allocated for one ring buffer page:
7473  *  0 - 1 system page
7474  *  1 - 2 system pages
7475  *  3 - 4 system pages
7476  *  ...
7477  *
7478  * Returns 0 on success or < 0 in case of an error.
7479  */
7480 int ring_buffer_subbuf_order_set(struct trace_buffer *buffer, int order)
7481 {
7482 	struct ring_buffer_per_cpu *cpu_buffer;
7483 	struct buffer_page *bpage, *tmp;
7484 	unsigned int old_capacity;
7485 	unsigned long nr_pages;
7486 	int old_order;
7487 	int psize;
7488 	int err;
7489 	int cpu;
7490 
7491 	if (!buffer || order < 0)
7492 		return -EINVAL;
7493 
7494 	psize = (1 << order) * PAGE_SIZE;
7495 	if (psize <= BUF_PAGE_HDR_SIZE)
7496 		return -EINVAL;
7497 
7498 	/* Size of a subbuf cannot be greater than the write counter */
7499 	if (psize > RB_WRITE_MASK + 1)
7500 		return -EINVAL;
7501 
7502 	guard(cpus_read_lock)();
7503 
7504 	/* prevent another thread from changing buffer sizes */
7505 	guard(mutex)(&buffer->mutex);
7506 
7507 	old_order = buffer->subbuf_order;
7508 	if (old_order == order)
7509 		return 0;
7510 
7511 	old_capacity = rb_subbuf_capacity(buffer);
7512 
7513 	/* Check it is resizable before we touch subbuf_order */
7514 	if (rb_resize_disabled(buffer, RING_BUFFER_ALL_CPUS))
7515 		return -EBUSY;
7516 
7517 	atomic_inc(&buffer->record_disabled);
7518 
7519 	/* Make sure all commits have finished */
7520 	synchronize_rcu();
7521 
7522 	WRITE_ONCE(buffer->subbuf_order, order);
7523 
7524 	/* Make sure all new buffers are allocated, before deleting the old ones */
7525 	for_each_buffer_cpu(buffer, cpu) {
7526 		cpu_buffer = buffer->buffers[cpu];
7527 
7528 		/* Update the number of pages to match the new size */
7529 		nr_pages = rb_calculate_nr_pages(buffer,
7530 						 old_capacity * buffer->buffers[cpu]->nr_pages);
7531 
7532 		cpu_buffer->nr_pages_to_update = nr_pages;
7533 
7534 		/* Include the reader page */
7535 		nr_pages++;
7536 
7537 		/* Allocate the new size buffer */
7538 		INIT_LIST_HEAD(&cpu_buffer->new_pages);
7539 		if (__rb_allocate_pages(cpu_buffer, nr_pages,
7540 					&cpu_buffer->new_pages)) {
7541 			/* not enough memory for new pages */
7542 			err = -ENOMEM;
7543 			goto error;
7544 		}
7545 	}
7546 
7547 	for_each_buffer_cpu(buffer, cpu) {
7548 		struct buffer_data_read_page old_free_data_page;
7549 		struct list_head old_pages;
7550 		unsigned long flags;
7551 
7552 		cpu_buffer = buffer->buffers[cpu];
7553 
7554 		raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
7555 
7556 		/* Clear the head bit to make the link list normal to read */
7557 		rb_head_page_deactivate(cpu_buffer);
7558 
7559 		/*
7560 		 * Collect buffers from the cpu_buffer pages list and the
7561 		 * reader_page on old_pages, so they can be freed later when not
7562 		 * under a spinlock. The pages list is a linked list with no
7563 		 * head, adding old_pages turns it into a regular list with
7564 		 * old_pages being the head.
7565 		 */
7566 		list_add(&old_pages, cpu_buffer->pages);
7567 		list_add(&cpu_buffer->reader_page->list, &old_pages);
7568 
7569 		/* One page was allocated for the reader page */
7570 		cpu_buffer->reader_page = list_entry(cpu_buffer->new_pages.next,
7571 						     struct buffer_page, list);
7572 		list_del_init(&cpu_buffer->reader_page->list);
7573 
7574 		/* Install the new pages, remove the head from the list */
7575 		cpu_buffer->pages = cpu_buffer->new_pages.next;
7576 		list_del_init(&cpu_buffer->new_pages);
7577 		cpu_buffer->cnt++;
7578 
7579 		cpu_buffer->head_page
7580 			= list_entry(cpu_buffer->pages, struct buffer_page, list);
7581 		cpu_buffer->tail_page = cpu_buffer->commit_page = cpu_buffer->head_page;
7582 
7583 		cpu_buffer->nr_pages = cpu_buffer->nr_pages_to_update;
7584 		cpu_buffer->nr_pages_to_update = 0;
7585 
7586 		arch_spin_lock(&cpu_buffer->lock);
7587 		old_free_data_page = cpu_buffer->free_page;
7588 		cpu_buffer->free_page.data = NULL;
7589 		arch_spin_unlock(&cpu_buffer->lock);
7590 
7591 		rb_head_page_activate(cpu_buffer);
7592 
7593 		raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
7594 
7595 		/* Free old sub buffers */
7596 		list_for_each_entry_safe(bpage, tmp, &old_pages, list) {
7597 			list_del_init(&bpage->list);
7598 			free_buffer_page(bpage);
7599 		}
7600 		free_pages((unsigned long)old_free_data_page.data, old_free_data_page.order);
7601 
7602 		rb_check_pages(cpu_buffer);
7603 	}
7604 
7605 	atomic_dec(&buffer->record_disabled);
7606 
7607 	return 0;
7608 
7609 error:
7610 	WRITE_ONCE(buffer->subbuf_order, old_order);
7611 
7612 	atomic_dec(&buffer->record_disabled);
7613 
7614 	for_each_buffer_cpu(buffer, cpu) {
7615 		cpu_buffer = buffer->buffers[cpu];
7616 
7617 		if (!cpu_buffer->nr_pages_to_update)
7618 			continue;
7619 
7620 		list_for_each_entry_safe(bpage, tmp, &cpu_buffer->new_pages, list) {
7621 			list_del_init(&bpage->list);
7622 			free_buffer_page(bpage);
7623 		}
7624 	}
7625 
7626 	return err;
7627 }
7628 EXPORT_SYMBOL_GPL(ring_buffer_subbuf_order_set);
7629 
7630 static int rb_alloc_meta_page(struct ring_buffer_per_cpu *cpu_buffer)
7631 {
7632 	struct page *page;
7633 
7634 	if (cpu_buffer->meta_page)
7635 		return 0;
7636 
7637 	page = alloc_page(GFP_USER | __GFP_ZERO);
7638 	if (!page)
7639 		return -ENOMEM;
7640 
7641 	cpu_buffer->meta_page = page_to_virt(page);
7642 
7643 	return 0;
7644 }
7645 
7646 static void rb_free_meta_page(struct ring_buffer_per_cpu *cpu_buffer)
7647 {
7648 	unsigned long addr = (unsigned long)cpu_buffer->meta_page;
7649 
7650 	free_page(addr);
7651 	cpu_buffer->meta_page = NULL;
7652 }
7653 
7654 static void rb_setup_ids_meta_page(struct ring_buffer_per_cpu *cpu_buffer,
7655 				   struct buffer_page **subbuf_ids)
7656 {
7657 	struct trace_buffer_meta *meta = cpu_buffer->meta_page;
7658 	unsigned long nr_subbufs = cpu_buffer->nr_pages + 1;
7659 	struct buffer_page *first_subbuf, *subbuf;
7660 	unsigned int cnt = 0;
7661 	unsigned int id = 0;
7662 
7663 	id = rb_page_id(cpu_buffer, cpu_buffer->reader_page, id);
7664 	subbuf_ids[id++] = cpu_buffer->reader_page;
7665 	cnt++;
7666 
7667 	first_subbuf = subbuf = rb_set_head_page(cpu_buffer);
7668 	do {
7669 		id = rb_page_id(cpu_buffer, subbuf, id);
7670 
7671 		if (WARN_ON(id >= nr_subbufs))
7672 			break;
7673 
7674 		subbuf_ids[id] = subbuf;
7675 
7676 		rb_inc_page(&subbuf);
7677 		id++;
7678 		cnt++;
7679 	} while (subbuf != first_subbuf);
7680 
7681 	WARN_ON(cnt != nr_subbufs);
7682 
7683 	/* install subbuf ID to bpage translation */
7684 	cpu_buffer->subbuf_ids = subbuf_ids;
7685 
7686 	meta->meta_struct_len = sizeof(*meta);
7687 	meta->nr_subbufs = nr_subbufs;
7688 	meta->subbuf_size = rb_subbuf_size(cpu_buffer->buffer);
7689 	meta->meta_page_size = meta->subbuf_size;
7690 
7691 	rb_update_meta_page(cpu_buffer);
7692 }
7693 
7694 static struct ring_buffer_per_cpu *
7695 rb_get_mapped_buffer(struct trace_buffer *buffer, int cpu)
7696 {
7697 	struct ring_buffer_per_cpu *cpu_buffer;
7698 
7699 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
7700 		return ERR_PTR(-EINVAL);
7701 
7702 	cpu_buffer = buffer->buffers[cpu];
7703 
7704 	mutex_lock(&cpu_buffer->mapping_lock);
7705 
7706 	if (!cpu_buffer->user_mapped) {
7707 		mutex_unlock(&cpu_buffer->mapping_lock);
7708 		return ERR_PTR(-ENODEV);
7709 	}
7710 
7711 	return cpu_buffer;
7712 }
7713 
7714 static void rb_put_mapped_buffer(struct ring_buffer_per_cpu *cpu_buffer)
7715 {
7716 	mutex_unlock(&cpu_buffer->mapping_lock);
7717 }
7718 
7719 /*
7720  * Fast-path for rb_buffer_(un)map(). Called whenever the meta-page doesn't need
7721  * to be set-up or torn-down.
7722  */
7723 static int __rb_inc_dec_mapped(struct ring_buffer_per_cpu *cpu_buffer,
7724 			       bool inc)
7725 {
7726 	unsigned long flags;
7727 
7728 	lockdep_assert_held(&cpu_buffer->mapping_lock);
7729 
7730 	if (inc && cpu_buffer->user_mapped == UINT_MAX)
7731 		return -EBUSY;
7732 
7733 	if (WARN_ON(!inc && cpu_buffer->user_mapped == 0))
7734 		return -EINVAL;
7735 
7736 	mutex_lock(&cpu_buffer->buffer->mutex);
7737 	raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
7738 
7739 	if (inc)
7740 		cpu_buffer->user_mapped++;
7741 	else
7742 		cpu_buffer->user_mapped--;
7743 
7744 	raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
7745 	mutex_unlock(&cpu_buffer->buffer->mutex);
7746 
7747 	return 0;
7748 }
7749 
7750 /*
7751  *   +--------------+  pgoff == 0
7752  *   |   meta page  |
7753  *   +--------------+  pgoff == 1
7754  *   | subbuffer 0  |
7755  *   |              |
7756  *   +--------------+  pgoff == (1 + (1 << subbuf_order))
7757  *   | subbuffer 1  |
7758  *   |              |
7759  *         ...
7760  */
7761 #ifdef CONFIG_MMU
7762 static int __rb_map_vma(struct ring_buffer_per_cpu *cpu_buffer,
7763 			struct vm_area_struct *vma)
7764 {
7765 	unsigned long nr_subbufs, nr_pages, nr_vma_pages;
7766 	pgoff_t pgoff = vma_start_pgoff(vma);
7767 	unsigned int subbuf_pages, subbuf_order;
7768 	struct page **pages __free(kfree) = NULL;
7769 	int p = 0, s = 0;
7770 	int err;
7771 
7772 	/* Refuse MP_PRIVATE or writable mappings */
7773 	if (vma->vm_flags & VM_WRITE || vma->vm_flags & VM_EXEC ||
7774 	    !(vma->vm_flags & VM_MAYSHARE))
7775 		return -EPERM;
7776 
7777 	subbuf_order = cpu_buffer->buffer->subbuf_order;
7778 	subbuf_pages = 1 << subbuf_order;
7779 
7780 	if (subbuf_order && pgoff % subbuf_pages)
7781 		return -EINVAL;
7782 
7783 	/*
7784 	 * Make sure the mapping cannot become writable later. Also tell the VM
7785 	 * to not touch these pages (VM_DONTCOPY | VM_DONTEXPAND).
7786 	 */
7787 	vm_flags_mod(vma, VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP,
7788 		     VM_MAYWRITE);
7789 
7790 	lockdep_assert_held(&cpu_buffer->mapping_lock);
7791 
7792 	nr_subbufs = cpu_buffer->nr_pages + 1; /* + reader-subbuf */
7793 	nr_pages = ((nr_subbufs + 1) << subbuf_order); /* + meta-page */
7794 	if (nr_pages <= pgoff)
7795 		return -EINVAL;
7796 
7797 	nr_pages -= pgoff;
7798 
7799 	nr_vma_pages = vma_pages(vma);
7800 	if (!nr_vma_pages || nr_vma_pages > nr_pages)
7801 		return -EINVAL;
7802 
7803 	nr_pages = nr_vma_pages;
7804 
7805 	pages = kzalloc_objs(*pages, nr_pages);
7806 	if (!pages)
7807 		return -ENOMEM;
7808 
7809 	if (!pgoff) {
7810 		unsigned long meta_page_padding;
7811 
7812 		pages[p++] = virt_to_page(cpu_buffer->meta_page);
7813 
7814 		/*
7815 		 * Pad with the zero-page to align the meta-page with the
7816 		 * sub-buffers.
7817 		 */
7818 		meta_page_padding = subbuf_pages - 1;
7819 		while (meta_page_padding-- && p < nr_pages) {
7820 			unsigned long __maybe_unused zero_addr =
7821 				vma->vm_start + (PAGE_SIZE * p);
7822 
7823 			pages[p++] = ZERO_PAGE(zero_addr);
7824 		}
7825 	} else {
7826 		/* Skip the meta-page */
7827 		pgoff -= subbuf_pages;
7828 
7829 		s += pgoff / subbuf_pages;
7830 	}
7831 
7832 	while (p < nr_pages) {
7833 		struct buffer_page *subbuf;
7834 		struct page *page;
7835 		int off = 0;
7836 
7837 		if (WARN_ON_ONCE(s >= nr_subbufs))
7838 			return -EINVAL;
7839 
7840 		subbuf = cpu_buffer->subbuf_ids[s];
7841 		page = virt_to_page((void *)subbuf->page);
7842 
7843 		for (; off < (1 << (subbuf_order)); off++, page++) {
7844 			if (p >= nr_pages)
7845 				break;
7846 
7847 			pages[p++] = page;
7848 		}
7849 		s++;
7850 	}
7851 
7852 	err = vm_insert_pages(vma, vma->vm_start, pages, &nr_pages);
7853 
7854 	return err;
7855 }
7856 #else
7857 static int __rb_map_vma(struct ring_buffer_per_cpu *cpu_buffer,
7858 			struct vm_area_struct *vma)
7859 {
7860 	return -EOPNOTSUPP;
7861 }
7862 #endif
7863 
7864 int ring_buffer_map(struct trace_buffer *buffer, int cpu,
7865 		    struct vm_area_struct *vma)
7866 {
7867 	struct ring_buffer_per_cpu *cpu_buffer;
7868 	struct buffer_page **subbuf_ids;
7869 	unsigned long flags;
7870 	int err;
7871 
7872 	if (!cpumask_test_cpu(cpu, buffer->cpumask) || buffer->remote)
7873 		return -EINVAL;
7874 
7875 	cpu_buffer = buffer->buffers[cpu];
7876 
7877 	guard(mutex)(&cpu_buffer->mapping_lock);
7878 
7879 	if (cpu_buffer->user_mapped) {
7880 		err = __rb_map_vma(cpu_buffer, vma);
7881 		if (!err)
7882 			err = __rb_inc_dec_mapped(cpu_buffer, true);
7883 		return err;
7884 	}
7885 
7886 	/* prevent another thread from changing buffer/sub-buffer sizes */
7887 	guard(mutex)(&buffer->mutex);
7888 
7889 	if (cpu_buffer->nr_pages > rb_static_max_pages())
7890 		return -E2BIG;
7891 
7892 	err = rb_alloc_meta_page(cpu_buffer);
7893 	if (err)
7894 		return err;
7895 
7896 	/* subbuf_ids includes the reader while nr_pages does not */
7897 	subbuf_ids = kzalloc_objs(*subbuf_ids, cpu_buffer->nr_pages + 1);
7898 	if (!subbuf_ids) {
7899 		rb_free_meta_page(cpu_buffer);
7900 		return -ENOMEM;
7901 	}
7902 
7903 	atomic_inc(&cpu_buffer->resize_disabled);
7904 
7905 	/*
7906 	 * Lock all readers to block any subbuf swap until the subbuf IDs are
7907 	 * assigned.
7908 	 */
7909 	raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
7910 	rb_setup_ids_meta_page(cpu_buffer, subbuf_ids);
7911 
7912 	raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
7913 
7914 	err = __rb_map_vma(cpu_buffer, vma);
7915 	if (!err) {
7916 		raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
7917 		/* This is the first time it is mapped by user */
7918 		cpu_buffer->user_mapped = 1;
7919 		raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
7920 	} else {
7921 		kfree(cpu_buffer->subbuf_ids);
7922 		cpu_buffer->subbuf_ids = NULL;
7923 		rb_free_meta_page(cpu_buffer);
7924 		atomic_dec(&cpu_buffer->resize_disabled);
7925 	}
7926 
7927 	return err;
7928 }
7929 
7930 /*
7931  * This is called when a VMA is duplicated (e.g., on fork()) to increment
7932  * the user_mapped counter without remapping pages.
7933  */
7934 void ring_buffer_map_dup(struct trace_buffer *buffer, int cpu)
7935 {
7936 	struct ring_buffer_per_cpu *cpu_buffer;
7937 
7938 	if (WARN_ON(!cpumask_test_cpu(cpu, buffer->cpumask)))
7939 		return;
7940 
7941 	cpu_buffer = buffer->buffers[cpu];
7942 
7943 	guard(mutex)(&cpu_buffer->mapping_lock);
7944 
7945 	if (cpu_buffer->user_mapped)
7946 		__rb_inc_dec_mapped(cpu_buffer, true);
7947 	else
7948 		WARN(1, "Unexpected buffer stat, it should be mapped");
7949 }
7950 
7951 int ring_buffer_unmap(struct trace_buffer *buffer, int cpu)
7952 {
7953 	struct ring_buffer_per_cpu *cpu_buffer;
7954 	unsigned long flags;
7955 
7956 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
7957 		return -EINVAL;
7958 
7959 	cpu_buffer = buffer->buffers[cpu];
7960 
7961 	guard(mutex)(&cpu_buffer->mapping_lock);
7962 
7963 	if (!cpu_buffer->user_mapped) {
7964 		return -ENODEV;
7965 	} else if (cpu_buffer->user_mapped > 1) {
7966 		__rb_inc_dec_mapped(cpu_buffer, false);
7967 		return 0;
7968 	}
7969 
7970 	guard(mutex)(&buffer->mutex);
7971 	raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
7972 
7973 	/* This is the last user space mapping */
7974 	cpu_buffer->user_mapped = 0;
7975 
7976 	raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
7977 
7978 	kfree(cpu_buffer->subbuf_ids);
7979 	cpu_buffer->subbuf_ids = NULL;
7980 	rb_free_meta_page(cpu_buffer);
7981 	atomic_dec(&cpu_buffer->resize_disabled);
7982 
7983 	return 0;
7984 }
7985 
7986 int ring_buffer_map_get_reader(struct trace_buffer *buffer, int cpu)
7987 {
7988 	struct ring_buffer_per_cpu *cpu_buffer;
7989 	struct buffer_page *reader;
7990 	unsigned long missed_events;
7991 	unsigned long reader_size;
7992 	unsigned long flags;
7993 
7994 	cpu_buffer = rb_get_mapped_buffer(buffer, cpu);
7995 	if (IS_ERR(cpu_buffer))
7996 		return (int)PTR_ERR(cpu_buffer);
7997 
7998 	raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
7999 
8000 consume:
8001 	if (rb_per_cpu_empty(cpu_buffer))
8002 		goto out;
8003 
8004 	reader_size = rb_page_size(cpu_buffer->reader_page);
8005 
8006 	/*
8007 	 * There are data to be read on the current reader page, we can
8008 	 * return to the caller. But before that, we assume the latter will read
8009 	 * everything. Let's update the kernel reader accordingly.
8010 	 */
8011 	if (cpu_buffer->reader_page->read < reader_size) {
8012 		while (cpu_buffer->reader_page->read < reader_size)
8013 			rb_advance_reader(cpu_buffer);
8014 		goto out;
8015 	}
8016 
8017 	reader = rb_get_reader_page(cpu_buffer);
8018 	if (!reader)
8019 		goto out;
8020 
8021 	/* Check if any events were dropped */
8022 	missed_events = cpu_buffer->lost_events;
8023 
8024 	if (missed_events) {
8025 		if (cpu_buffer->reader_page != cpu_buffer->commit_page) {
8026 			struct buffer_data_page *dpage = reader->page;
8027 			unsigned int commit;
8028 			/*
8029 			 * Use the real_end for the data size,
8030 			 * This gives us a chance to store the lost events
8031 			 * on the page.
8032 			 */
8033 			if (reader->real_end)
8034 				local_set(&dpage->commit, reader->real_end);
8035 			/*
8036 			 * If there is room at the end of the page to save the
8037 			 * missed events, then record it there.
8038 			 */
8039 			commit = rb_page_size(reader);
8040 			if (rb_page_capacity(reader) - commit >= sizeof(missed_events)) {
8041 				memcpy(&dpage->data[commit], &missed_events,
8042 				       sizeof(missed_events));
8043 				local_add(RB_MISSED_STORED, &dpage->commit);
8044 			}
8045 			local_add(RB_MISSED_EVENTS, &dpage->commit);
8046 		} else if (!WARN_ONCE(cpu_buffer->reader_page == cpu_buffer->tail_page,
8047 				      "Reader on commit with %ld missed events",
8048 				      missed_events)) {
8049 			/*
8050 			 * There shouldn't be any missed events if the tail_page
8051 			 * is on the reader page. But if the tail page is not on the
8052 			 * reader page and the commit_page is, that would mean that
8053 			 * there's a commit_overrun (an interrupt preempted an
8054 			 * addition of an event and then filled the buffer
8055 			 * with new events). In this case it's not an
8056 			 * error, but it should still be reported.
8057 			 *
8058 			 * TODO: Add missed events to the page for user space to know.
8059 			 */
8060 			pr_info("Ring buffer [%d] commit overrun lost %ld events at timestamp:%lld\n",
8061 				cpu, missed_events, cpu_buffer->reader_page->page->time_stamp);
8062 		}
8063 	}
8064 
8065 	cpu_buffer->lost_events = 0;
8066 
8067 	goto consume;
8068 
8069 out:
8070 	/* Some archs do not have data cache coherency between kernel and user-space */
8071 	flush_kernel_vmap_range(cpu_buffer->reader_page->page,
8072 				rb_subbuf_size(buffer));
8073 
8074 	rb_update_meta_page(cpu_buffer);
8075 
8076 	raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
8077 	rb_put_mapped_buffer(cpu_buffer);
8078 
8079 	return 0;
8080 }
8081 
8082 static void rb_cpu_sync(void *data)
8083 {
8084 	/* Not really needed, but documents what is happening */
8085 	smp_rmb();
8086 }
8087 
8088 /*
8089  * We only allocate new buffers, never free them if the CPU goes down.
8090  * If we were to free the buffer, then the user would lose any trace that was in
8091  * the buffer.
8092  */
8093 int trace_rb_cpu_prepare(unsigned int cpu, struct hlist_node *node)
8094 {
8095 	struct trace_buffer *buffer;
8096 	long nr_pages_same;
8097 	int cpu_i;
8098 	unsigned long nr_pages;
8099 
8100 	buffer = container_of(node, struct trace_buffer, node);
8101 	if (cpumask_test_cpu(cpu, buffer->cpumask))
8102 		return 0;
8103 
8104 	nr_pages = 0;
8105 	nr_pages_same = 1;
8106 	/* check if all cpu sizes are same */
8107 	for_each_buffer_cpu(buffer, cpu_i) {
8108 		/* fill in the size from first enabled cpu */
8109 		if (nr_pages == 0)
8110 			nr_pages = buffer->buffers[cpu_i]->nr_pages;
8111 		if (nr_pages != buffer->buffers[cpu_i]->nr_pages) {
8112 			nr_pages_same = 0;
8113 			break;
8114 		}
8115 	}
8116 	/* allocate minimum pages, user can later expand it */
8117 	if (!nr_pages_same)
8118 		nr_pages = RING_BUFFER_MIN_NR_PAGES;
8119 	buffer->buffers[cpu] =
8120 		rb_allocate_cpu_buffer(buffer, nr_pages, cpu);
8121 	if (!buffer->buffers[cpu]) {
8122 		pr_warn("failed to allocate ring buffer on CPU %u\n", cpu);
8123 		return -ENOMEM;
8124 	}
8125 
8126 	/*
8127 	 * Ensure trace_buffer readers observe the newly allocated
8128 	 * ring_buffer_per_cpu before they check the cpumask. Instead of using a
8129 	 * read barrier for all readers, send an IPI.
8130 	 */
8131 	if (unlikely(system_state == SYSTEM_RUNNING)) {
8132 		on_each_cpu(rb_cpu_sync, NULL, 1);
8133 		/* Not really needed, but documents what is happening */
8134 		smp_wmb();
8135 	}
8136 
8137 	cpumask_set_cpu(cpu, buffer->cpumask);
8138 	return 0;
8139 }
8140 
8141 #ifdef CONFIG_RING_BUFFER_STARTUP_TEST
8142 /*
8143  * This is a basic integrity check of the ring buffer.
8144  * Late in the boot cycle this test will run when configured in.
8145  * It will kick off a thread per CPU that will go into a loop
8146  * writing to the per cpu ring buffer various sizes of data.
8147  * Some of the data will be large items, some small.
8148  *
8149  * Another thread is created that goes into a spin, sending out
8150  * IPIs to the other CPUs to also write into the ring buffer.
8151  * this is to test the nesting ability of the buffer.
8152  *
8153  * Basic stats are recorded and reported. If something in the
8154  * ring buffer should happen that's not expected, a big warning
8155  * is displayed and all ring buffers are disabled.
8156  */
8157 static struct task_struct *rb_threads[NR_CPUS] __initdata;
8158 
8159 struct rb_test_data {
8160 	struct trace_buffer *buffer;
8161 	unsigned long		events;
8162 	unsigned long		bytes_written;
8163 	unsigned long		bytes_alloc;
8164 	unsigned long		bytes_dropped;
8165 	unsigned long		events_nested;
8166 	unsigned long		bytes_written_nested;
8167 	unsigned long		bytes_alloc_nested;
8168 	unsigned long		bytes_dropped_nested;
8169 	int			min_size_nested;
8170 	int			max_size_nested;
8171 	int			max_size;
8172 	int			min_size;
8173 	int			cpu;
8174 	int			cnt;
8175 };
8176 
8177 static struct rb_test_data rb_data[NR_CPUS] __initdata;
8178 
8179 /* 1 meg per cpu */
8180 #define RB_TEST_BUFFER_SIZE	1048576
8181 
8182 static char rb_string[] __initdata =
8183 	"abcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()?+\\"
8184 	"?+|:';\",.<>/?abcdefghijklmnopqrstuvwxyz1234567890"
8185 	"!@#$%^&*()?+\\?+|:';\",.<>/?abcdefghijklmnopqrstuv";
8186 
8187 static bool rb_test_started __initdata;
8188 
8189 struct rb_item {
8190 	int size;
8191 	char str[];
8192 };
8193 
8194 static __init int rb_write_something(struct rb_test_data *data, bool nested)
8195 {
8196 	struct ring_buffer_event *event;
8197 	struct rb_item *item;
8198 	bool started;
8199 	int event_len;
8200 	int size;
8201 	int len;
8202 	int cnt;
8203 
8204 	/* Have nested writes different that what is written */
8205 	cnt = data->cnt + (nested ? 27 : 0);
8206 
8207 	/* Multiply cnt by ~e, to make some unique increment */
8208 	size = (cnt * 68 / 25) % (sizeof(rb_string) - 1);
8209 
8210 	len = size + sizeof(struct rb_item);
8211 
8212 	started = rb_test_started;
8213 	/* read rb_test_started before checking buffer enabled */
8214 	smp_rmb();
8215 
8216 	event = ring_buffer_lock_reserve(data->buffer, len);
8217 	if (!event) {
8218 		/* Ignore dropped events before test starts. */
8219 		if (started) {
8220 			if (nested)
8221 				data->bytes_dropped_nested += len;
8222 			else
8223 				data->bytes_dropped += len;
8224 		}
8225 		return len;
8226 	}
8227 
8228 	event_len = ring_buffer_event_length(event);
8229 
8230 	if (RB_WARN_ON(data->buffer, event_len < len))
8231 		goto out;
8232 
8233 	item = ring_buffer_event_data(event);
8234 	item->size = size;
8235 	memcpy(item->str, rb_string, size);
8236 
8237 	if (nested) {
8238 		data->bytes_alloc_nested += event_len;
8239 		data->bytes_written_nested += len;
8240 		data->events_nested++;
8241 		if (!data->min_size_nested || len < data->min_size_nested)
8242 			data->min_size_nested = len;
8243 		if (len > data->max_size_nested)
8244 			data->max_size_nested = len;
8245 	} else {
8246 		data->bytes_alloc += event_len;
8247 		data->bytes_written += len;
8248 		data->events++;
8249 		if (!data->min_size || len < data->min_size)
8250 			data->max_size = len;
8251 		if (len > data->max_size)
8252 			data->max_size = len;
8253 	}
8254 
8255  out:
8256 	ring_buffer_unlock_commit(data->buffer);
8257 
8258 	return 0;
8259 }
8260 
8261 static __init int rb_test(void *arg)
8262 {
8263 	struct rb_test_data *data = arg;
8264 
8265 	while (!kthread_should_stop()) {
8266 		rb_write_something(data, false);
8267 		data->cnt++;
8268 
8269 		set_current_state(TASK_INTERRUPTIBLE);
8270 		/* Now sleep between a min of 100-300us and a max of 1ms */
8271 		usleep_range(((data->cnt % 3) + 1) * 100, 1000);
8272 	}
8273 
8274 	return 0;
8275 }
8276 
8277 static __init void rb_ipi(void *ignore)
8278 {
8279 	struct rb_test_data *data;
8280 	int cpu = smp_processor_id();
8281 
8282 	data = &rb_data[cpu];
8283 	rb_write_something(data, true);
8284 }
8285 
8286 static __init int rb_hammer_test(void *arg)
8287 {
8288 	while (!kthread_should_stop()) {
8289 
8290 		/* Send an IPI to all cpus to write data! */
8291 		smp_call_function(rb_ipi, NULL, 1);
8292 		/* No sleep, but for non preempt, let others run */
8293 		schedule();
8294 	}
8295 
8296 	return 0;
8297 }
8298 
8299 static __init int test_ringbuffer(void)
8300 {
8301 	struct task_struct *rb_hammer;
8302 	struct trace_buffer *buffer;
8303 	int cpu;
8304 	int ret = 0;
8305 
8306 	if (security_locked_down(LOCKDOWN_TRACEFS)) {
8307 		pr_warn("Lockdown is enabled, skipping ring buffer tests\n");
8308 		return 0;
8309 	}
8310 
8311 	pr_info("Running ring buffer tests...\n");
8312 
8313 	buffer = ring_buffer_alloc(RB_TEST_BUFFER_SIZE, RB_FL_OVERWRITE);
8314 	if (WARN_ON(!buffer))
8315 		return 0;
8316 
8317 	/* Disable buffer so that threads can't write to it yet */
8318 	ring_buffer_record_off(buffer);
8319 
8320 	for_each_online_cpu(cpu) {
8321 		rb_data[cpu].buffer = buffer;
8322 		rb_data[cpu].cpu = cpu;
8323 		rb_data[cpu].cnt = cpu;
8324 		rb_threads[cpu] = kthread_run_on_cpu(rb_test, &rb_data[cpu],
8325 						     cpu, "rbtester/%u");
8326 		if (WARN_ON(IS_ERR(rb_threads[cpu]))) {
8327 			pr_cont("FAILED\n");
8328 			ret = PTR_ERR(rb_threads[cpu]);
8329 			goto out_free;
8330 		}
8331 	}
8332 
8333 	/* Now create the rb hammer! */
8334 	rb_hammer = kthread_run(rb_hammer_test, NULL, "rbhammer");
8335 	if (WARN_ON(IS_ERR(rb_hammer))) {
8336 		pr_cont("FAILED\n");
8337 		ret = PTR_ERR(rb_hammer);
8338 		goto out_free;
8339 	}
8340 
8341 	ring_buffer_record_on(buffer);
8342 	/*
8343 	 * Show buffer is enabled before setting rb_test_started.
8344 	 * Yes there's a small race window where events could be
8345 	 * dropped and the thread won't catch it. But when a ring
8346 	 * buffer gets enabled, there will always be some kind of
8347 	 * delay before other CPUs see it. Thus, we don't care about
8348 	 * those dropped events. We care about events dropped after
8349 	 * the threads see that the buffer is active.
8350 	 */
8351 	smp_wmb();
8352 	rb_test_started = true;
8353 
8354 	set_current_state(TASK_INTERRUPTIBLE);
8355 	/* Just run for 10 seconds */
8356 	schedule_timeout(10 * HZ);
8357 
8358 	kthread_stop(rb_hammer);
8359 
8360  out_free:
8361 	for_each_online_cpu(cpu) {
8362 		if (IS_ERR_OR_NULL(rb_threads[cpu]))
8363 			break;
8364 		kthread_stop(rb_threads[cpu]);
8365 	}
8366 	if (ret) {
8367 		ring_buffer_free(buffer);
8368 		return ret;
8369 	}
8370 
8371 	/* Report! */
8372 	pr_info("finished\n");
8373 	for_each_online_cpu(cpu) {
8374 		struct ring_buffer_event *event;
8375 		struct rb_test_data *data = &rb_data[cpu];
8376 		struct rb_item *item;
8377 		unsigned long total_events;
8378 		unsigned long total_dropped;
8379 		unsigned long total_written;
8380 		unsigned long total_alloc;
8381 		unsigned long total_read = 0;
8382 		unsigned long total_size = 0;
8383 		unsigned long total_len = 0;
8384 		unsigned long total_lost = 0;
8385 		unsigned long lost;
8386 		int big_event_size;
8387 		int small_event_size;
8388 
8389 		ret = -1;
8390 
8391 		total_events = data->events + data->events_nested;
8392 		total_written = data->bytes_written + data->bytes_written_nested;
8393 		total_alloc = data->bytes_alloc + data->bytes_alloc_nested;
8394 		total_dropped = data->bytes_dropped + data->bytes_dropped_nested;
8395 
8396 		big_event_size = data->max_size + data->max_size_nested;
8397 		small_event_size = data->min_size + data->min_size_nested;
8398 
8399 		pr_info("CPU %d:\n", cpu);
8400 		pr_info("              events:    %ld\n", total_events);
8401 		pr_info("       dropped bytes:    %ld\n", total_dropped);
8402 		pr_info("       alloced bytes:    %ld\n", total_alloc);
8403 		pr_info("       written bytes:    %ld\n", total_written);
8404 		pr_info("       biggest event:    %d\n", big_event_size);
8405 		pr_info("      smallest event:    %d\n", small_event_size);
8406 
8407 		if (RB_WARN_ON(buffer, total_dropped))
8408 			break;
8409 
8410 		ret = 0;
8411 
8412 		while ((event = ring_buffer_consume(buffer, cpu, NULL, &lost))) {
8413 			total_lost += lost;
8414 			item = ring_buffer_event_data(event);
8415 			total_len += ring_buffer_event_length(event);
8416 			total_size += item->size + sizeof(struct rb_item);
8417 			if (memcmp(&item->str[0], rb_string, item->size) != 0) {
8418 				pr_info("FAILED!\n");
8419 				pr_info("buffer had: %.*s\n", item->size, item->str);
8420 				pr_info("expected:   %.*s\n", item->size, rb_string);
8421 				RB_WARN_ON(buffer, 1);
8422 				ret = -1;
8423 				break;
8424 			}
8425 			total_read++;
8426 		}
8427 		if (ret)
8428 			break;
8429 
8430 		ret = -1;
8431 
8432 		pr_info("         read events:   %ld\n", total_read);
8433 		pr_info("         lost events:   %ld\n", total_lost);
8434 		pr_info("        total events:   %ld\n", total_lost + total_read);
8435 		pr_info("  recorded len bytes:   %ld\n", total_len);
8436 		pr_info(" recorded size bytes:   %ld\n", total_size);
8437 		if (total_lost) {
8438 			pr_info(" With dropped events, record len and size may not match\n"
8439 				" alloced and written from above\n");
8440 		} else {
8441 			if (RB_WARN_ON(buffer, total_len != total_alloc ||
8442 				       total_size != total_written))
8443 				break;
8444 		}
8445 		if (RB_WARN_ON(buffer, total_lost + total_read != total_events))
8446 			break;
8447 
8448 		ret = 0;
8449 	}
8450 	if (!ret)
8451 		pr_info("Ring buffer PASSED!\n");
8452 
8453 	ring_buffer_free(buffer);
8454 	return 0;
8455 }
8456 
8457 late_initcall(test_ringbuffer);
8458 #endif /* CONFIG_RING_BUFFER_STARTUP_TEST */
8459