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