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