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