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