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