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