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