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