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