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