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