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