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