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