x86, ds: add leakage warning
[linux-2.6] / arch / x86 / kernel / ds.c
1 /*
2  * Debug Store support
3  *
4  * This provides a low-level interface to the hardware's Debug Store
5  * feature that is used for branch trace store (BTS) and
6  * precise-event based sampling (PEBS).
7  *
8  * It manages:
9  * - DS and BTS hardware configuration
10  * - buffer overflow handling (to be done)
11  * - buffer access
12  *
13  * It does not do:
14  * - security checking (is the caller allowed to trace the task)
15  * - buffer allocation (memory accounting)
16  *
17  *
18  * Copyright (C) 2007-2009 Intel Corporation.
19  * Markus Metzger <markus.t.metzger@intel.com>, 2007-2009
20  */
21
22 #include <linux/kernel.h>
23 #include <linux/string.h>
24 #include <linux/errno.h>
25 #include <linux/sched.h>
26 #include <linux/slab.h>
27 #include <linux/mm.h>
28 #include <linux/trace_clock.h>
29
30 #include <asm/ds.h>
31
32 #include "ds_selftest.h"
33
34 /*
35  * The configuration for a particular DS hardware implementation:
36  */
37 struct ds_configuration {
38         /* The name of the configuration: */
39         const char              *name;
40
41         /* The size of pointer-typed fields in DS, BTS, and PEBS: */
42         unsigned char           sizeof_ptr_field;
43
44         /* The size of a BTS/PEBS record in bytes: */
45         unsigned char           sizeof_rec[2];
46
47         /* Control bit-masks indexed by enum ds_feature: */
48         unsigned long           ctl[dsf_ctl_max];
49 };
50 static DEFINE_PER_CPU(struct ds_configuration, ds_cfg_array);
51
52 #define ds_cfg per_cpu(ds_cfg_array, smp_processor_id())
53
54 /* Maximal size of a DS configuration: */
55 #define MAX_SIZEOF_DS           (12 * 8)
56
57 /* Maximal size of a BTS record: */
58 #define MAX_SIZEOF_BTS          (3 * 8)
59
60 /* BTS and PEBS buffer alignment: */
61 #define DS_ALIGNMENT            (1 << 3)
62
63 /* Mask of control bits in the DS MSR register: */
64 #define BTS_CONTROL                               \
65         ( ds_cfg.ctl[dsf_bts]                   | \
66           ds_cfg.ctl[dsf_bts_kernel]            | \
67           ds_cfg.ctl[dsf_bts_user]              | \
68           ds_cfg.ctl[dsf_bts_overflow] )
69
70 /*
71  * A BTS or PEBS tracer.
72  *
73  * This holds the configuration of the tracer and serves as a handle
74  * to identify tracers.
75  */
76 struct ds_tracer {
77         /* The DS context (partially) owned by this tracer. */
78         struct ds_context       *context;
79         /* The buffer provided on ds_request() and its size in bytes. */
80         void                    *buffer;
81         size_t                  size;
82 };
83
84 struct bts_tracer {
85         /* The common DS part: */
86         struct ds_tracer        ds;
87
88         /* The trace including the DS configuration: */
89         struct bts_trace        trace;
90
91         /* Buffer overflow notification function: */
92         bts_ovfl_callback_t     ovfl;
93
94         /* Active flags affecting trace collection. */
95         unsigned int            flags;
96 };
97
98 struct pebs_tracer {
99         /* The common DS part: */
100         struct ds_tracer        ds;
101
102         /* The trace including the DS configuration: */
103         struct pebs_trace       trace;
104
105         /* Buffer overflow notification function: */
106         pebs_ovfl_callback_t    ovfl;
107 };
108
109 /*
110  * Debug Store (DS) save area configuration (see Intel64 and IA32
111  * Architectures Software Developer's Manual, section 18.5)
112  *
113  * The DS configuration consists of the following fields; different
114  * architetures vary in the size of those fields.
115  *
116  * - double-word aligned base linear address of the BTS buffer
117  * - write pointer into the BTS buffer
118  * - end linear address of the BTS buffer (one byte beyond the end of
119  *   the buffer)
120  * - interrupt pointer into BTS buffer
121  *   (interrupt occurs when write pointer passes interrupt pointer)
122  * - double-word aligned base linear address of the PEBS buffer
123  * - write pointer into the PEBS buffer
124  * - end linear address of the PEBS buffer (one byte beyond the end of
125  *   the buffer)
126  * - interrupt pointer into PEBS buffer
127  *   (interrupt occurs when write pointer passes interrupt pointer)
128  * - value to which counter is reset following counter overflow
129  *
130  * Later architectures use 64bit pointers throughout, whereas earlier
131  * architectures use 32bit pointers in 32bit mode.
132  *
133  *
134  * We compute the base address for the first 8 fields based on:
135  * - the field size stored in the DS configuration
136  * - the relative field position
137  * - an offset giving the start of the respective region
138  *
139  * This offset is further used to index various arrays holding
140  * information for BTS and PEBS at the respective index.
141  *
142  * On later 32bit processors, we only access the lower 32bit of the
143  * 64bit pointer fields. The upper halves will be zeroed out.
144  */
145
146 enum ds_field {
147         ds_buffer_base = 0,
148         ds_index,
149         ds_absolute_maximum,
150         ds_interrupt_threshold,
151 };
152
153 enum ds_qualifier {
154         ds_bts = 0,
155         ds_pebs
156 };
157
158 static inline unsigned long
159 ds_get(const unsigned char *base, enum ds_qualifier qual, enum ds_field field)
160 {
161         base += (ds_cfg.sizeof_ptr_field * (field + (4 * qual)));
162         return *(unsigned long *)base;
163 }
164
165 static inline void
166 ds_set(unsigned char *base, enum ds_qualifier qual, enum ds_field field,
167        unsigned long value)
168 {
169         base += (ds_cfg.sizeof_ptr_field * (field + (4 * qual)));
170         (*(unsigned long *)base) = value;
171 }
172
173
174 /*
175  * Locking is done only for allocating BTS or PEBS resources.
176  */
177 static DEFINE_SPINLOCK(ds_lock);
178
179 /*
180  * We either support (system-wide) per-cpu or per-thread allocation.
181  * We distinguish the two based on the task_struct pointer, where a
182  * NULL pointer indicates per-cpu allocation for the current cpu.
183  *
184  * Allocations are use-counted. As soon as resources are allocated,
185  * further allocations must be of the same type (per-cpu or
186  * per-thread). We model this by counting allocations (i.e. the number
187  * of tracers of a certain type) for one type negatively:
188  *   =0  no tracers
189  *   >0  number of per-thread tracers
190  *   <0  number of per-cpu tracers
191  *
192  * Tracers essentially gives the number of ds contexts for a certain
193  * type of allocation.
194  */
195 static atomic_t tracers = ATOMIC_INIT(0);
196
197 static inline int get_tracer(struct task_struct *task)
198 {
199         int error;
200
201         spin_lock_irq(&ds_lock);
202
203         if (task) {
204                 error = -EPERM;
205                 if (atomic_read(&tracers) < 0)
206                         goto out;
207                 atomic_inc(&tracers);
208         } else {
209                 error = -EPERM;
210                 if (atomic_read(&tracers) > 0)
211                         goto out;
212                 atomic_dec(&tracers);
213         }
214
215         error = 0;
216 out:
217         spin_unlock_irq(&ds_lock);
218         return error;
219 }
220
221 static inline void put_tracer(struct task_struct *task)
222 {
223         if (task)
224                 atomic_dec(&tracers);
225         else
226                 atomic_inc(&tracers);
227 }
228
229 /*
230  * The DS context is either attached to a thread or to a cpu:
231  * - in the former case, the thread_struct contains a pointer to the
232  *   attached context.
233  * - in the latter case, we use a static array of per-cpu context
234  *   pointers.
235  *
236  * Contexts are use-counted. They are allocated on first access and
237  * deallocated when the last user puts the context.
238  */
239 struct ds_context {
240         /* The DS configuration; goes into MSR_IA32_DS_AREA: */
241         unsigned char           ds[MAX_SIZEOF_DS];
242
243         /* The owner of the BTS and PEBS configuration, respectively: */
244         struct bts_tracer       *bts_master;
245         struct pebs_tracer      *pebs_master;
246
247         /* Use count: */
248         unsigned long           count;
249
250         /* Pointer to the context pointer field: */
251         struct ds_context       **this;
252
253         /* The traced task; NULL for cpu tracing: */
254         struct task_struct      *task;
255
256         /* The traced cpu; only valid if task is NULL: */
257         int                     cpu;
258 };
259
260 static DEFINE_PER_CPU(struct ds_context *, cpu_context);
261
262
263 static struct ds_context *ds_get_context(struct task_struct *task, int cpu)
264 {
265         struct ds_context **p_context =
266                 (task ? &task->thread.ds_ctx : &per_cpu(cpu_context, cpu));
267         struct ds_context *context = NULL;
268         struct ds_context *new_context = NULL;
269
270         /* Chances are small that we already have a context. */
271         new_context = kzalloc(sizeof(*new_context), GFP_KERNEL);
272         if (!new_context)
273                 return NULL;
274
275         spin_lock_irq(&ds_lock);
276
277         context = *p_context;
278         if (likely(!context)) {
279                 context = new_context;
280
281                 context->this = p_context;
282                 context->task = task;
283                 context->cpu = cpu;
284                 context->count = 0;
285
286                 *p_context = context;
287         }
288
289         context->count++;
290
291         spin_unlock_irq(&ds_lock);
292
293         if (context != new_context)
294                 kfree(new_context);
295
296         return context;
297 }
298
299 static void ds_put_context(struct ds_context *context)
300 {
301         struct task_struct *task;
302         unsigned long irq;
303
304         if (!context)
305                 return;
306
307         spin_lock_irqsave(&ds_lock, irq);
308
309         if (--context->count) {
310                 spin_unlock_irqrestore(&ds_lock, irq);
311                 return;
312         }
313
314         *(context->this) = NULL;
315
316         task = context->task;
317
318         if (task)
319                 clear_tsk_thread_flag(task, TIF_DS_AREA_MSR);
320
321         /*
322          * We leave the (now dangling) pointer to the DS configuration in
323          * the DS_AREA msr. This is as good or as bad as replacing it with
324          * NULL - the hardware would crash if we enabled tracing.
325          *
326          * This saves us some problems with having to write an msr on a
327          * different cpu while preventing others from doing the same for the
328          * next context for that same cpu.
329          */
330
331         spin_unlock_irqrestore(&ds_lock, irq);
332
333         /* The context might still be in use for context switching. */
334         if (task && (task != current))
335                 wait_task_context_switch(task);
336
337         kfree(context);
338 }
339
340 static void ds_install_ds_area(struct ds_context *context)
341 {
342         unsigned long ds;
343
344         ds = (unsigned long)context->ds;
345
346         /*
347          * There is a race between the bts master and the pebs master.
348          *
349          * The thread/cpu access is synchronized via get/put_cpu() for
350          * task tracing and via wrmsr_on_cpu for cpu tracing.
351          *
352          * If bts and pebs are collected for the same task or same cpu,
353          * the same confiuration is written twice.
354          */
355         if (context->task) {
356                 get_cpu();
357                 if (context->task == current)
358                         wrmsrl(MSR_IA32_DS_AREA, ds);
359                 set_tsk_thread_flag(context->task, TIF_DS_AREA_MSR);
360                 put_cpu();
361         } else
362                 wrmsr_on_cpu(context->cpu, MSR_IA32_DS_AREA,
363                              (u32)((u64)ds), (u32)((u64)ds >> 32));
364 }
365
366 /*
367  * Call the tracer's callback on a buffer overflow.
368  *
369  * context: the ds context
370  * qual: the buffer type
371  */
372 static void ds_overflow(struct ds_context *context, enum ds_qualifier qual)
373 {
374         switch (qual) {
375         case ds_bts:
376                 if (context->bts_master &&
377                     context->bts_master->ovfl)
378                         context->bts_master->ovfl(context->bts_master);
379                 break;
380         case ds_pebs:
381                 if (context->pebs_master &&
382                     context->pebs_master->ovfl)
383                         context->pebs_master->ovfl(context->pebs_master);
384                 break;
385         }
386 }
387
388
389 /*
390  * Write raw data into the BTS or PEBS buffer.
391  *
392  * The remainder of any partially written record is zeroed out.
393  *
394  * context: the DS context
395  * qual:    the buffer type
396  * record:  the data to write
397  * size:    the size of the data
398  */
399 static int ds_write(struct ds_context *context, enum ds_qualifier qual,
400                     const void *record, size_t size)
401 {
402         int bytes_written = 0;
403
404         if (!record)
405                 return -EINVAL;
406
407         while (size) {
408                 unsigned long base, index, end, write_end, int_th;
409                 unsigned long write_size, adj_write_size;
410
411                 /*
412                  * Write as much as possible without producing an
413                  * overflow interrupt.
414                  *
415                  * Interrupt_threshold must either be
416                  * - bigger than absolute_maximum or
417                  * - point to a record between buffer_base and absolute_maximum
418                  *
419                  * Index points to a valid record.
420                  */
421                 base   = ds_get(context->ds, qual, ds_buffer_base);
422                 index  = ds_get(context->ds, qual, ds_index);
423                 end    = ds_get(context->ds, qual, ds_absolute_maximum);
424                 int_th = ds_get(context->ds, qual, ds_interrupt_threshold);
425
426                 write_end = min(end, int_th);
427
428                 /*
429                  * If we are already beyond the interrupt threshold,
430                  * we fill the entire buffer.
431                  */
432                 if (write_end <= index)
433                         write_end = end;
434
435                 if (write_end <= index)
436                         break;
437
438                 write_size = min((unsigned long) size, write_end - index);
439                 memcpy((void *)index, record, write_size);
440
441                 record = (const char *)record + write_size;
442                 size -= write_size;
443                 bytes_written += write_size;
444
445                 adj_write_size = write_size / ds_cfg.sizeof_rec[qual];
446                 adj_write_size *= ds_cfg.sizeof_rec[qual];
447
448                 /* Zero out trailing bytes. */
449                 memset((char *)index + write_size, 0,
450                        adj_write_size - write_size);
451                 index += adj_write_size;
452
453                 if (index >= end)
454                         index = base;
455                 ds_set(context->ds, qual, ds_index, index);
456
457                 if (index >= int_th)
458                         ds_overflow(context, qual);
459         }
460
461         return bytes_written;
462 }
463
464
465 /*
466  * Branch Trace Store (BTS) uses the following format. Different
467  * architectures vary in the size of those fields.
468  * - source linear address
469  * - destination linear address
470  * - flags
471  *
472  * Later architectures use 64bit pointers throughout, whereas earlier
473  * architectures use 32bit pointers in 32bit mode.
474  *
475  * We compute the base address for the fields based on:
476  * - the field size stored in the DS configuration
477  * - the relative field position
478  *
479  * In order to store additional information in the BTS buffer, we use
480  * a special source address to indicate that the record requires
481  * special interpretation.
482  *
483  * Netburst indicated via a bit in the flags field whether the branch
484  * was predicted; this is ignored.
485  *
486  * We use two levels of abstraction:
487  * - the raw data level defined here
488  * - an arch-independent level defined in ds.h
489  */
490
491 enum bts_field {
492         bts_from,
493         bts_to,
494         bts_flags,
495
496         bts_qual                = bts_from,
497         bts_clock               = bts_to,
498         bts_pid                 = bts_flags,
499
500         bts_qual_mask           = (bts_qual_max - 1),
501         bts_escape              = ((unsigned long)-1 & ~bts_qual_mask)
502 };
503
504 static inline unsigned long bts_get(const char *base, enum bts_field field)
505 {
506         base += (ds_cfg.sizeof_ptr_field * field);
507         return *(unsigned long *)base;
508 }
509
510 static inline void bts_set(char *base, enum bts_field field, unsigned long val)
511 {
512         base += (ds_cfg.sizeof_ptr_field * field);;
513         (*(unsigned long *)base) = val;
514 }
515
516
517 /*
518  * The raw BTS data is architecture dependent.
519  *
520  * For higher-level users, we give an arch-independent view.
521  * - ds.h defines struct bts_struct
522  * - bts_read translates one raw bts record into a bts_struct
523  * - bts_write translates one bts_struct into the raw format and
524  *   writes it into the top of the parameter tracer's buffer.
525  *
526  * return: bytes read/written on success; -Eerrno, otherwise
527  */
528 static int
529 bts_read(struct bts_tracer *tracer, const void *at, struct bts_struct *out)
530 {
531         if (!tracer)
532                 return -EINVAL;
533
534         if (at < tracer->trace.ds.begin)
535                 return -EINVAL;
536
537         if (tracer->trace.ds.end < (at + tracer->trace.ds.size))
538                 return -EINVAL;
539
540         memset(out, 0, sizeof(*out));
541         if ((bts_get(at, bts_qual) & ~bts_qual_mask) == bts_escape) {
542                 out->qualifier = (bts_get(at, bts_qual) & bts_qual_mask);
543                 out->variant.event.clock = bts_get(at, bts_clock);
544                 out->variant.event.pid = bts_get(at, bts_pid);
545         } else {
546                 out->qualifier = bts_branch;
547                 out->variant.lbr.from = bts_get(at, bts_from);
548                 out->variant.lbr.to   = bts_get(at, bts_to);
549
550                 if (!out->variant.lbr.from && !out->variant.lbr.to)
551                         out->qualifier = bts_invalid;
552         }
553
554         return ds_cfg.sizeof_rec[ds_bts];
555 }
556
557 static int bts_write(struct bts_tracer *tracer, const struct bts_struct *in)
558 {
559         unsigned char raw[MAX_SIZEOF_BTS];
560
561         if (!tracer)
562                 return -EINVAL;
563
564         if (MAX_SIZEOF_BTS < ds_cfg.sizeof_rec[ds_bts])
565                 return -EOVERFLOW;
566
567         switch (in->qualifier) {
568         case bts_invalid:
569                 bts_set(raw, bts_from, 0);
570                 bts_set(raw, bts_to, 0);
571                 bts_set(raw, bts_flags, 0);
572                 break;
573         case bts_branch:
574                 bts_set(raw, bts_from, in->variant.lbr.from);
575                 bts_set(raw, bts_to,   in->variant.lbr.to);
576                 bts_set(raw, bts_flags, 0);
577                 break;
578         case bts_task_arrives:
579         case bts_task_departs:
580                 bts_set(raw, bts_qual, (bts_escape | in->qualifier));
581                 bts_set(raw, bts_clock, in->variant.event.clock);
582                 bts_set(raw, bts_pid, in->variant.event.pid);
583                 break;
584         default:
585                 return -EINVAL;
586         }
587
588         return ds_write(tracer->ds.context, ds_bts, raw,
589                         ds_cfg.sizeof_rec[ds_bts]);
590 }
591
592
593 static void ds_write_config(struct ds_context *context,
594                             struct ds_trace *cfg, enum ds_qualifier qual)
595 {
596         unsigned char *ds = context->ds;
597
598         ds_set(ds, qual, ds_buffer_base, (unsigned long)cfg->begin);
599         ds_set(ds, qual, ds_index, (unsigned long)cfg->top);
600         ds_set(ds, qual, ds_absolute_maximum, (unsigned long)cfg->end);
601         ds_set(ds, qual, ds_interrupt_threshold, (unsigned long)cfg->ith);
602 }
603
604 static void ds_read_config(struct ds_context *context,
605                            struct ds_trace *cfg, enum ds_qualifier qual)
606 {
607         unsigned char *ds = context->ds;
608
609         cfg->begin = (void *)ds_get(ds, qual, ds_buffer_base);
610         cfg->top = (void *)ds_get(ds, qual, ds_index);
611         cfg->end = (void *)ds_get(ds, qual, ds_absolute_maximum);
612         cfg->ith = (void *)ds_get(ds, qual, ds_interrupt_threshold);
613 }
614
615 static void ds_init_ds_trace(struct ds_trace *trace, enum ds_qualifier qual,
616                              void *base, size_t size, size_t ith,
617                              unsigned int flags) {
618         unsigned long buffer, adj;
619
620         /*
621          * Adjust the buffer address and size to meet alignment
622          * constraints:
623          * - buffer is double-word aligned
624          * - size is multiple of record size
625          *
626          * We checked the size at the very beginning; we have enough
627          * space to do the adjustment.
628          */
629         buffer = (unsigned long)base;
630
631         adj = ALIGN(buffer, DS_ALIGNMENT) - buffer;
632         buffer += adj;
633         size   -= adj;
634
635         trace->n = size / ds_cfg.sizeof_rec[qual];
636         trace->size = ds_cfg.sizeof_rec[qual];
637
638         size = (trace->n * trace->size);
639
640         trace->begin = (void *)buffer;
641         trace->top = trace->begin;
642         trace->end = (void *)(buffer + size);
643         /*
644          * The value for 'no threshold' is -1, which will set the
645          * threshold outside of the buffer, just like we want it.
646          */
647         ith *= ds_cfg.sizeof_rec[qual];
648         trace->ith = (void *)(buffer + size - ith);
649
650         trace->flags = flags;
651 }
652
653
654 static int ds_request(struct ds_tracer *tracer, struct ds_trace *trace,
655                       enum ds_qualifier qual, struct task_struct *task,
656                       int cpu, void *base, size_t size, size_t th)
657 {
658         struct ds_context *context;
659         int error;
660
661         error = -EOPNOTSUPP;
662         if (!ds_cfg.sizeof_rec[qual])
663                 goto out;
664
665         error = -EINVAL;
666         if (!base)
667                 goto out;
668
669         /* We need space for alignment adjustments in ds_init_ds_trace(). */
670         error = -EINVAL;
671         if (size < (DS_ALIGNMENT + ds_cfg.sizeof_rec[qual]))
672                 goto out;
673
674         if (th != (size_t)-1) {
675                 th *= ds_cfg.sizeof_rec[qual];
676
677                 error = -EINVAL;
678                 if (size <= th)
679                         goto out;
680         }
681
682         tracer->buffer = base;
683         tracer->size = size;
684
685         error = -ENOMEM;
686         context = ds_get_context(task, cpu);
687         if (!context)
688                 goto out;
689         tracer->context = context;
690
691         /*
692          * Defer any tracer-specific initialization work for the context until
693          * context ownership has been clarified.
694          */
695
696         error = 0;
697  out:
698         return error;
699 }
700
701 static struct bts_tracer *ds_request_bts(struct task_struct *task, int cpu,
702                                          void *base, size_t size,
703                                          bts_ovfl_callback_t ovfl, size_t th,
704                                          unsigned int flags)
705 {
706         struct bts_tracer *tracer;
707         int error;
708
709         /* Buffer overflow notification is not yet implemented. */
710         error = -EOPNOTSUPP;
711         if (ovfl)
712                 goto out;
713
714         error = get_tracer(task);
715         if (error < 0)
716                 goto out;
717
718         error = -ENOMEM;
719         tracer = kzalloc(sizeof(*tracer), GFP_KERNEL);
720         if (!tracer)
721                 goto out_put_tracer;
722         tracer->ovfl = ovfl;
723
724         /* Do some more error checking and acquire a tracing context. */
725         error = ds_request(&tracer->ds, &tracer->trace.ds,
726                            ds_bts, task, cpu, base, size, th);
727         if (error < 0)
728                 goto out_tracer;
729
730         /* Claim the bts part of the tracing context we acquired above. */
731         spin_lock_irq(&ds_lock);
732
733         error = -EPERM;
734         if (tracer->ds.context->bts_master)
735                 goto out_unlock;
736         tracer->ds.context->bts_master = tracer;
737
738         spin_unlock_irq(&ds_lock);
739
740         /*
741          * Now that we own the bts part of the context, let's complete the
742          * initialization for that part.
743          */
744         ds_init_ds_trace(&tracer->trace.ds, ds_bts, base, size, th, flags);
745         ds_write_config(tracer->ds.context, &tracer->trace.ds, ds_bts);
746         ds_install_ds_area(tracer->ds.context);
747
748         tracer->trace.read  = bts_read;
749         tracer->trace.write = bts_write;
750
751         /* Start tracing. */
752         ds_resume_bts(tracer);
753
754         return tracer;
755
756  out_unlock:
757         spin_unlock_irq(&ds_lock);
758         ds_put_context(tracer->ds.context);
759  out_tracer:
760         kfree(tracer);
761  out_put_tracer:
762         put_tracer(task);
763  out:
764         return ERR_PTR(error);
765 }
766
767 struct bts_tracer *ds_request_bts_task(struct task_struct *task,
768                                        void *base, size_t size,
769                                        bts_ovfl_callback_t ovfl,
770                                        size_t th, unsigned int flags)
771 {
772         return ds_request_bts(task, 0, base, size, ovfl, th, flags);
773 }
774
775 struct bts_tracer *ds_request_bts_cpu(int cpu, void *base, size_t size,
776                                       bts_ovfl_callback_t ovfl,
777                                       size_t th, unsigned int flags)
778 {
779         return ds_request_bts(NULL, cpu, base, size, ovfl, th, flags);
780 }
781
782 static struct pebs_tracer *ds_request_pebs(struct task_struct *task, int cpu,
783                                            void *base, size_t size,
784                                            pebs_ovfl_callback_t ovfl, size_t th,
785                                            unsigned int flags)
786 {
787         struct pebs_tracer *tracer;
788         int error;
789
790         /* Buffer overflow notification is not yet implemented. */
791         error = -EOPNOTSUPP;
792         if (ovfl)
793                 goto out;
794
795         error = get_tracer(task);
796         if (error < 0)
797                 goto out;
798
799         error = -ENOMEM;
800         tracer = kzalloc(sizeof(*tracer), GFP_KERNEL);
801         if (!tracer)
802                 goto out_put_tracer;
803         tracer->ovfl = ovfl;
804
805         /* Do some more error checking and acquire a tracing context. */
806         error = ds_request(&tracer->ds, &tracer->trace.ds,
807                            ds_pebs, task, cpu, base, size, th);
808         if (error < 0)
809                 goto out_tracer;
810
811         /* Claim the pebs part of the tracing context we acquired above. */
812         spin_lock_irq(&ds_lock);
813
814         error = -EPERM;
815         if (tracer->ds.context->pebs_master)
816                 goto out_unlock;
817         tracer->ds.context->pebs_master = tracer;
818
819         spin_unlock_irq(&ds_lock);
820
821         /*
822          * Now that we own the pebs part of the context, let's complete the
823          * initialization for that part.
824          */
825         ds_init_ds_trace(&tracer->trace.ds, ds_pebs, base, size, th, flags);
826         ds_write_config(tracer->ds.context, &tracer->trace.ds, ds_pebs);
827         ds_install_ds_area(tracer->ds.context);
828
829         /* Start tracing. */
830         ds_resume_pebs(tracer);
831
832         return tracer;
833
834  out_unlock:
835         spin_unlock_irq(&ds_lock);
836         ds_put_context(tracer->ds.context);
837  out_tracer:
838         kfree(tracer);
839  out_put_tracer:
840         put_tracer(task);
841  out:
842         return ERR_PTR(error);
843 }
844
845 struct pebs_tracer *ds_request_pebs_task(struct task_struct *task,
846                                          void *base, size_t size,
847                                          pebs_ovfl_callback_t ovfl,
848                                          size_t th, unsigned int flags)
849 {
850         return ds_request_pebs(task, 0, base, size, ovfl, th, flags);
851 }
852
853 struct pebs_tracer *ds_request_pebs_cpu(int cpu, void *base, size_t size,
854                                         pebs_ovfl_callback_t ovfl,
855                                         size_t th, unsigned int flags)
856 {
857         return ds_request_pebs(NULL, cpu, base, size, ovfl, th, flags);
858 }
859
860 static void ds_free_bts(struct bts_tracer *tracer)
861 {
862         struct task_struct *task;
863
864         task = tracer->ds.context->task;
865
866         WARN_ON_ONCE(tracer->ds.context->bts_master != tracer);
867         tracer->ds.context->bts_master = NULL;
868
869         /* Make sure tracing stopped and the tracer is not in use. */
870         if (task && (task != current))
871                 wait_task_context_switch(task);
872
873         ds_put_context(tracer->ds.context);
874         put_tracer(task);
875
876         kfree(tracer);
877 }
878
879 void ds_release_bts(struct bts_tracer *tracer)
880 {
881         might_sleep();
882
883         if (!tracer)
884                 return;
885
886         ds_suspend_bts(tracer);
887         ds_free_bts(tracer);
888 }
889
890 int ds_release_bts_noirq(struct bts_tracer *tracer)
891 {
892         struct task_struct *task;
893         unsigned long irq;
894         int error;
895
896         if (!tracer)
897                 return 0;
898
899         task = tracer->ds.context->task;
900
901         local_irq_save(irq);
902
903         error = -EPERM;
904         if (!task &&
905             (tracer->ds.context->cpu != smp_processor_id()))
906                 goto out;
907
908         error = -EPERM;
909         if (task && (task != current))
910                 goto out;
911
912         ds_suspend_bts_noirq(tracer);
913         ds_free_bts(tracer);
914
915         error = 0;
916  out:
917         local_irq_restore(irq);
918         return error;
919 }
920
921 static void update_task_debugctlmsr(struct task_struct *task,
922                                     unsigned long debugctlmsr)
923 {
924         task->thread.debugctlmsr = debugctlmsr;
925
926         get_cpu();
927         if (task == current)
928                 update_debugctlmsr(debugctlmsr);
929
930         if (task->thread.debugctlmsr)
931                 set_tsk_thread_flag(task, TIF_DEBUGCTLMSR);
932         else
933                 clear_tsk_thread_flag(task, TIF_DEBUGCTLMSR);
934         put_cpu();
935 }
936
937 void ds_suspend_bts(struct bts_tracer *tracer)
938 {
939         struct task_struct *task;
940         unsigned long debugctlmsr;
941         int cpu;
942
943         if (!tracer)
944                 return;
945
946         tracer->flags = 0;
947
948         task = tracer->ds.context->task;
949         cpu  = tracer->ds.context->cpu;
950
951         WARN_ON(!task && irqs_disabled());
952
953         debugctlmsr = (task ?
954                        task->thread.debugctlmsr :
955                        get_debugctlmsr_on_cpu(cpu));
956         debugctlmsr &= ~BTS_CONTROL;
957
958         if (task)
959                 update_task_debugctlmsr(task, debugctlmsr);
960         else
961                 update_debugctlmsr_on_cpu(cpu, debugctlmsr);
962 }
963
964 int ds_suspend_bts_noirq(struct bts_tracer *tracer)
965 {
966         struct task_struct *task;
967         unsigned long debugctlmsr, irq;
968         int cpu, error = 0;
969
970         if (!tracer)
971                 return 0;
972
973         tracer->flags = 0;
974
975         task = tracer->ds.context->task;
976         cpu  = tracer->ds.context->cpu;
977
978         local_irq_save(irq);
979
980         error = -EPERM;
981         if (!task && (cpu != smp_processor_id()))
982                 goto out;
983
984         debugctlmsr = (task ?
985                        task->thread.debugctlmsr :
986                        get_debugctlmsr());
987         debugctlmsr &= ~BTS_CONTROL;
988
989         if (task)
990                 update_task_debugctlmsr(task, debugctlmsr);
991         else
992                 update_debugctlmsr(debugctlmsr);
993
994         error = 0;
995  out:
996         local_irq_restore(irq);
997         return error;
998 }
999
1000 static unsigned long ds_bts_control(struct bts_tracer *tracer)
1001 {
1002         unsigned long control;
1003
1004         control = ds_cfg.ctl[dsf_bts];
1005         if (!(tracer->trace.ds.flags & BTS_KERNEL))
1006                 control |= ds_cfg.ctl[dsf_bts_kernel];
1007         if (!(tracer->trace.ds.flags & BTS_USER))
1008                 control |= ds_cfg.ctl[dsf_bts_user];
1009
1010         return control;
1011 }
1012
1013 void ds_resume_bts(struct bts_tracer *tracer)
1014 {
1015         struct task_struct *task;
1016         unsigned long debugctlmsr;
1017         int cpu;
1018
1019         if (!tracer)
1020                 return;
1021
1022         tracer->flags = tracer->trace.ds.flags;
1023
1024         task = tracer->ds.context->task;
1025         cpu  = tracer->ds.context->cpu;
1026
1027         WARN_ON(!task && irqs_disabled());
1028
1029         debugctlmsr = (task ?
1030                        task->thread.debugctlmsr :
1031                        get_debugctlmsr_on_cpu(cpu));
1032         debugctlmsr |= ds_bts_control(tracer);
1033
1034         if (task)
1035                 update_task_debugctlmsr(task, debugctlmsr);
1036         else
1037                 update_debugctlmsr_on_cpu(cpu, debugctlmsr);
1038 }
1039
1040 int ds_resume_bts_noirq(struct bts_tracer *tracer)
1041 {
1042         struct task_struct *task;
1043         unsigned long debugctlmsr, irq;
1044         int cpu, error = 0;
1045
1046         if (!tracer)
1047                 return 0;
1048
1049         tracer->flags = tracer->trace.ds.flags;
1050
1051         task = tracer->ds.context->task;
1052         cpu  = tracer->ds.context->cpu;
1053
1054         local_irq_save(irq);
1055
1056         error = -EPERM;
1057         if (!task && (cpu != smp_processor_id()))
1058                 goto out;
1059
1060         debugctlmsr = (task ?
1061                        task->thread.debugctlmsr :
1062                        get_debugctlmsr());
1063         debugctlmsr |= ds_bts_control(tracer);
1064
1065         if (task)
1066                 update_task_debugctlmsr(task, debugctlmsr);
1067         else
1068                 update_debugctlmsr(debugctlmsr);
1069
1070         error = 0;
1071  out:
1072         local_irq_restore(irq);
1073         return error;
1074 }
1075
1076 static void ds_free_pebs(struct pebs_tracer *tracer)
1077 {
1078         struct task_struct *task;
1079
1080         task = tracer->ds.context->task;
1081
1082         WARN_ON_ONCE(tracer->ds.context->pebs_master != tracer);
1083         tracer->ds.context->pebs_master = NULL;
1084
1085         ds_put_context(tracer->ds.context);
1086         put_tracer(task);
1087
1088         kfree(tracer);
1089 }
1090
1091 void ds_release_pebs(struct pebs_tracer *tracer)
1092 {
1093         might_sleep();
1094
1095         if (!tracer)
1096                 return;
1097
1098         ds_suspend_pebs(tracer);
1099         ds_free_pebs(tracer);
1100 }
1101
1102 int ds_release_pebs_noirq(struct pebs_tracer *tracer)
1103 {
1104         struct task_struct *task;
1105         unsigned long irq;
1106         int error;
1107
1108         if (!tracer)
1109                 return 0;
1110
1111         task = tracer->ds.context->task;
1112
1113         local_irq_save(irq);
1114
1115         error = -EPERM;
1116         if (!task &&
1117             (tracer->ds.context->cpu != smp_processor_id()))
1118                 goto out;
1119
1120         error = -EPERM;
1121         if (task && (task != current))
1122                 goto out;
1123
1124         ds_suspend_pebs_noirq(tracer);
1125         ds_free_pebs(tracer);
1126
1127         error = 0;
1128  out:
1129         local_irq_restore(irq);
1130         return error;
1131 }
1132
1133 void ds_suspend_pebs(struct pebs_tracer *tracer)
1134 {
1135
1136 }
1137
1138 int ds_suspend_pebs_noirq(struct pebs_tracer *tracer)
1139 {
1140         return 0;
1141 }
1142
1143 void ds_resume_pebs(struct pebs_tracer *tracer)
1144 {
1145
1146 }
1147
1148 int ds_resume_pebs_noirq(struct pebs_tracer *tracer)
1149 {
1150         return 0;
1151 }
1152
1153 const struct bts_trace *ds_read_bts(struct bts_tracer *tracer)
1154 {
1155         if (!tracer)
1156                 return NULL;
1157
1158         ds_read_config(tracer->ds.context, &tracer->trace.ds, ds_bts);
1159         return &tracer->trace;
1160 }
1161
1162 const struct pebs_trace *ds_read_pebs(struct pebs_tracer *tracer)
1163 {
1164         if (!tracer)
1165                 return NULL;
1166
1167         ds_read_config(tracer->ds.context, &tracer->trace.ds, ds_pebs);
1168         tracer->trace.reset_value =
1169                 *(u64 *)(tracer->ds.context->ds +
1170                          (ds_cfg.sizeof_ptr_field * 8));
1171
1172         return &tracer->trace;
1173 }
1174
1175 int ds_reset_bts(struct bts_tracer *tracer)
1176 {
1177         if (!tracer)
1178                 return -EINVAL;
1179
1180         tracer->trace.ds.top = tracer->trace.ds.begin;
1181
1182         ds_set(tracer->ds.context->ds, ds_bts, ds_index,
1183                (unsigned long)tracer->trace.ds.top);
1184
1185         return 0;
1186 }
1187
1188 int ds_reset_pebs(struct pebs_tracer *tracer)
1189 {
1190         if (!tracer)
1191                 return -EINVAL;
1192
1193         tracer->trace.ds.top = tracer->trace.ds.begin;
1194
1195         ds_set(tracer->ds.context->ds, ds_bts, ds_index,
1196                (unsigned long)tracer->trace.ds.top);
1197
1198         return 0;
1199 }
1200
1201 int ds_set_pebs_reset(struct pebs_tracer *tracer, u64 value)
1202 {
1203         if (!tracer)
1204                 return -EINVAL;
1205
1206         *(u64 *)(tracer->ds.context->ds +
1207                  (ds_cfg.sizeof_ptr_field * 8)) = value;
1208
1209         return 0;
1210 }
1211
1212 static const struct ds_configuration ds_cfg_netburst = {
1213         .name = "Netburst",
1214         .ctl[dsf_bts]           = (1 << 2) | (1 << 3),
1215         .ctl[dsf_bts_kernel]    = (1 << 5),
1216         .ctl[dsf_bts_user]      = (1 << 6),
1217 };
1218 static const struct ds_configuration ds_cfg_pentium_m = {
1219         .name = "Pentium M",
1220         .ctl[dsf_bts]           = (1 << 6) | (1 << 7),
1221 };
1222 static const struct ds_configuration ds_cfg_core2_atom = {
1223         .name = "Core 2/Atom",
1224         .ctl[dsf_bts]           = (1 << 6) | (1 << 7),
1225         .ctl[dsf_bts_kernel]    = (1 << 9),
1226         .ctl[dsf_bts_user]      = (1 << 10),
1227 };
1228
1229 static void
1230 ds_configure(const struct ds_configuration *cfg,
1231              struct cpuinfo_x86 *cpu)
1232 {
1233         unsigned long nr_pebs_fields = 0;
1234
1235         printk(KERN_INFO "[ds] using %s configuration\n", cfg->name);
1236
1237 #ifdef __i386__
1238         nr_pebs_fields = 10;
1239 #else
1240         nr_pebs_fields = 18;
1241 #endif
1242
1243         memset(&ds_cfg, 0, sizeof(ds_cfg));
1244         ds_cfg = *cfg;
1245
1246         ds_cfg.sizeof_ptr_field =
1247                 (cpu_has(cpu, X86_FEATURE_DTES64) ? 8 : 4);
1248
1249         ds_cfg.sizeof_rec[ds_bts]  = ds_cfg.sizeof_ptr_field * 3;
1250         ds_cfg.sizeof_rec[ds_pebs] = ds_cfg.sizeof_ptr_field * nr_pebs_fields;
1251
1252         if (!cpu_has(cpu, X86_FEATURE_BTS)) {
1253                 ds_cfg.sizeof_rec[ds_bts] = 0;
1254                 printk(KERN_INFO "[ds] bts not available\n");
1255         }
1256         if (!cpu_has(cpu, X86_FEATURE_PEBS)) {
1257                 ds_cfg.sizeof_rec[ds_pebs] = 0;
1258                 printk(KERN_INFO "[ds] pebs not available\n");
1259         }
1260
1261         printk(KERN_INFO "[ds] sizes: address: %u bit, ",
1262                8 * ds_cfg.sizeof_ptr_field);
1263         printk("bts/pebs record: %u/%u bytes\n",
1264                ds_cfg.sizeof_rec[ds_bts], ds_cfg.sizeof_rec[ds_pebs]);
1265
1266         WARN_ON_ONCE(MAX_SIZEOF_DS < (12 * ds_cfg.sizeof_ptr_field));
1267 }
1268
1269 void __cpuinit ds_init_intel(struct cpuinfo_x86 *c)
1270 {
1271         switch (c->x86) {
1272         case 0x6:
1273                 switch (c->x86_model) {
1274                 case 0x9:
1275                 case 0xd: /* Pentium M */
1276                         ds_configure(&ds_cfg_pentium_m, c);
1277                         break;
1278                 case 0xf:
1279                 case 0x17: /* Core2 */
1280                 case 0x1c: /* Atom */
1281                         ds_configure(&ds_cfg_core2_atom, c);
1282                         break;
1283                 case 0x1a: /* Core i7 */
1284                 default:
1285                         /* Sorry, don't know about them. */
1286                         break;
1287                 }
1288                 break;
1289         case 0xf:
1290                 switch (c->x86_model) {
1291                 case 0x0:
1292                 case 0x1:
1293                 case 0x2: /* Netburst */
1294                         ds_configure(&ds_cfg_netburst, c);
1295                         break;
1296                 default:
1297                         /* Sorry, don't know about them. */
1298                         break;
1299                 }
1300                 break;
1301         default:
1302                 /* Sorry, don't know about them. */
1303                 break;
1304         }
1305 }
1306
1307 static inline void ds_take_timestamp(struct ds_context *context,
1308                                      enum bts_qualifier qualifier,
1309                                      struct task_struct *task)
1310 {
1311         struct bts_tracer *tracer = context->bts_master;
1312         struct bts_struct ts;
1313
1314         /* Prevent compilers from reading the tracer pointer twice. */
1315         barrier();
1316
1317         if (!tracer || !(tracer->flags & BTS_TIMESTAMPS))
1318                 return;
1319
1320         memset(&ts, 0, sizeof(ts));
1321         ts.qualifier            = qualifier;
1322         ts.variant.event.clock  = trace_clock_global();
1323         ts.variant.event.pid    = task->pid;
1324
1325         bts_write(tracer, &ts);
1326 }
1327
1328 /*
1329  * Change the DS configuration from tracing prev to tracing next.
1330  */
1331 void ds_switch_to(struct task_struct *prev, struct task_struct *next)
1332 {
1333         struct ds_context *prev_ctx     = prev->thread.ds_ctx;
1334         struct ds_context *next_ctx     = next->thread.ds_ctx;
1335         unsigned long debugctlmsr       = next->thread.debugctlmsr;
1336
1337         /* Make sure all data is read before we start. */
1338         barrier();
1339
1340         if (prev_ctx) {
1341                 update_debugctlmsr(0);
1342
1343                 ds_take_timestamp(prev_ctx, bts_task_departs, prev);
1344         }
1345
1346         if (next_ctx) {
1347                 ds_take_timestamp(next_ctx, bts_task_arrives, next);
1348
1349                 wrmsrl(MSR_IA32_DS_AREA, (unsigned long)next_ctx->ds);
1350         }
1351
1352         update_debugctlmsr(debugctlmsr);
1353 }
1354
1355 static __init int ds_selftest(void)
1356 {
1357         if (ds_cfg.sizeof_rec[ds_bts]) {
1358                 int error;
1359
1360                 error = ds_selftest_bts();
1361                 if (error) {
1362                         WARN(1, "[ds] selftest failed. disabling bts.\n");
1363                         ds_cfg.sizeof_rec[ds_bts] = 0;
1364                 }
1365         }
1366
1367         if (ds_cfg.sizeof_rec[ds_pebs]) {
1368                 int error;
1369
1370                 error = ds_selftest_pebs();
1371                 if (error) {
1372                         WARN(1, "[ds] selftest failed. disabling pebs.\n");
1373                         ds_cfg.sizeof_rec[ds_pebs] = 0;
1374                 }
1375         }
1376
1377         return 0;
1378 }
1379 device_initcall(ds_selftest);