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