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