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