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