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