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