e827e9225dcbe76f1b40702d549ae3584d0012b8
[external/binutils.git] / gdb / nat / linux-btrace.c
1 /* Linux-dependent part of branch trace support for GDB, and GDBserver.
2
3    Copyright (C) 2013-2015 Free Software Foundation, Inc.
4
5    Contributed by Intel Corp. <markus.t.metzger@intel.com>
6
7    This file is part of GDB.
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
21
22 #include "common-defs.h"
23 #include "linux-btrace.h"
24 #include "common-regcache.h"
25 #include "gdb_wait.h"
26 #include "x86-cpuid.h"
27
28 #ifdef HAVE_SYS_SYSCALL_H
29 #include <sys/syscall.h>
30 #endif
31
32 #if HAVE_LINUX_PERF_EVENT_H && defined(SYS_perf_event_open)
33
34 #include <stdint.h>
35 #include <unistd.h>
36 #include <sys/mman.h>
37 #include <sys/user.h>
38 #include <sys/ptrace.h>
39 #include <sys/types.h>
40 #include <signal.h>
41
42 /* A branch trace record in perf_event.  */
43 struct perf_event_bts
44 {
45   /* The linear address of the branch source.  */
46   uint64_t from;
47
48   /* The linear address of the branch destination.  */
49   uint64_t to;
50 };
51
52 /* A perf_event branch trace sample.  */
53 struct perf_event_sample
54 {
55   /* The perf_event sample header.  */
56   struct perf_event_header header;
57
58   /* The perf_event branch tracing payload.  */
59   struct perf_event_bts bts;
60 };
61
62 /* Return non-zero if there is new data in PEVENT; zero otherwise.  */
63
64 static int
65 perf_event_new_data (const struct perf_event_buffer *pev)
66 {
67   return *pev->data_head != pev->last_head;
68 }
69
70 /* Check whether an address is in the kernel.  */
71
72 static inline int
73 perf_event_is_kernel_addr (const struct btrace_target_info *tinfo,
74                            uint64_t addr)
75 {
76   uint64_t mask;
77
78   /* If we don't know the size of a pointer, we can't check.  Let's assume it's
79      not a kernel address in this case.  */
80   if (tinfo->ptr_bits == 0)
81     return 0;
82
83   /* A bit mask for the most significant bit in an address.  */
84   mask = (uint64_t) 1 << (tinfo->ptr_bits - 1);
85
86   /* Check whether the most significant bit in the address is set.  */
87   return (addr & mask) != 0;
88 }
89
90 /* Check whether a perf event record should be skipped.  */
91
92 static inline int
93 perf_event_skip_bts_record (const struct btrace_target_info *tinfo,
94                             const struct perf_event_bts *bts)
95 {
96   /* The hardware may report branches from kernel into user space.  Branches
97      from user into kernel space will be suppressed.  We filter the former to
98      provide a consistent branch trace excluding kernel.  */
99   return perf_event_is_kernel_addr (tinfo, bts->from);
100 }
101
102 /* Perform a few consistency checks on a perf event sample record.  This is
103    meant to catch cases when we get out of sync with the perf event stream.  */
104
105 static inline int
106 perf_event_sample_ok (const struct perf_event_sample *sample)
107 {
108   if (sample->header.type != PERF_RECORD_SAMPLE)
109     return 0;
110
111   if (sample->header.size != sizeof (*sample))
112     return 0;
113
114   return 1;
115 }
116
117 /* Branch trace is collected in a circular buffer [begin; end) as pairs of from
118    and to addresses (plus a header).
119
120    Start points into that buffer at the next sample position.
121    We read the collected samples backwards from start.
122
123    While reading the samples, we convert the information into a list of blocks.
124    For two adjacent samples s1 and s2, we form a block b such that b.begin =
125    s1.to and b.end = s2.from.
126
127    In case the buffer overflows during sampling, one sample may have its lower
128    part at the end and its upper part at the beginning of the buffer.  */
129
130 static VEC (btrace_block_s) *
131 perf_event_read_bts (struct btrace_target_info* tinfo, const uint8_t *begin,
132                      const uint8_t *end, const uint8_t *start,
133                      unsigned long long size)
134 {
135   VEC (btrace_block_s) *btrace = NULL;
136   struct perf_event_sample sample;
137   unsigned long long read = 0;
138   struct btrace_block block = { 0, 0 };
139   struct regcache *regcache;
140
141   gdb_assert (begin <= start);
142   gdb_assert (start <= end);
143
144   /* The first block ends at the current pc.  */
145   regcache = get_thread_regcache_for_ptid (tinfo->ptid);
146   block.end = regcache_read_pc (regcache);
147
148   /* The buffer may contain a partial record as its last entry (i.e. when the
149      buffer size is not a multiple of the sample size).  */
150   read = sizeof (sample) - 1;
151
152   for (; read < size; read += sizeof (sample))
153     {
154       const struct perf_event_sample *psample;
155
156       /* Find the next perf_event sample in a backwards traversal.  */
157       start -= sizeof (sample);
158
159       /* If we're still inside the buffer, we're done.  */
160       if (begin <= start)
161         psample = (const struct perf_event_sample *) start;
162       else
163         {
164           int missing;
165
166           /* We're to the left of the ring buffer, we will wrap around and
167              reappear at the very right of the ring buffer.  */
168
169           missing = (begin - start);
170           start = (end - missing);
171
172           /* If the entire sample is missing, we're done.  */
173           if (missing == sizeof (sample))
174             psample = (const struct perf_event_sample *) start;
175           else
176             {
177               uint8_t *stack;
178
179               /* The sample wrapped around.  The lower part is at the end and
180                  the upper part is at the beginning of the buffer.  */
181               stack = (uint8_t *) &sample;
182
183               /* Copy the two parts so we have a contiguous sample.  */
184               memcpy (stack, start, missing);
185               memcpy (stack + missing, begin, sizeof (sample) - missing);
186
187               psample = &sample;
188             }
189         }
190
191       if (!perf_event_sample_ok (psample))
192         {
193           warning (_("Branch trace may be incomplete."));
194           break;
195         }
196
197       if (perf_event_skip_bts_record (tinfo, &psample->bts))
198         continue;
199
200       /* We found a valid sample, so we can complete the current block.  */
201       block.begin = psample->bts.to;
202
203       VEC_safe_push (btrace_block_s, btrace, &block);
204
205       /* Start the next block.  */
206       block.end = psample->bts.from;
207     }
208
209   /* Push the last block (i.e. the first one of inferior execution), as well.
210      We don't know where it ends, but we know where it starts.  If we're
211      reading delta trace, we can fill in the start address later on.
212      Otherwise we will prune it.  */
213   block.begin = 0;
214   VEC_safe_push (btrace_block_s, btrace, &block);
215
216   return btrace;
217 }
218
219 /* Check whether the kernel supports BTS.  */
220
221 static int
222 kernel_supports_bts (void)
223 {
224   struct perf_event_attr attr;
225   pid_t child, pid;
226   int status, file;
227
228   errno = 0;
229   child = fork ();
230   switch (child)
231     {
232     case -1:
233       warning (_("test bts: cannot fork: %s."), strerror (errno));
234       return 0;
235
236     case 0:
237       status = ptrace (PTRACE_TRACEME, 0, NULL, NULL);
238       if (status != 0)
239         {
240           warning (_("test bts: cannot PTRACE_TRACEME: %s."),
241                    strerror (errno));
242           _exit (1);
243         }
244
245       status = raise (SIGTRAP);
246       if (status != 0)
247         {
248           warning (_("test bts: cannot raise SIGTRAP: %s."),
249                    strerror (errno));
250           _exit (1);
251         }
252
253       _exit (1);
254
255     default:
256       pid = waitpid (child, &status, 0);
257       if (pid != child)
258         {
259           warning (_("test bts: bad pid %ld, error: %s."),
260                    (long) pid, strerror (errno));
261           return 0;
262         }
263
264       if (!WIFSTOPPED (status))
265         {
266           warning (_("test bts: expected stop. status: %d."),
267                    status);
268           return 0;
269         }
270
271       memset (&attr, 0, sizeof (attr));
272
273       attr.type = PERF_TYPE_HARDWARE;
274       attr.config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS;
275       attr.sample_period = 1;
276       attr.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_ADDR;
277       attr.exclude_kernel = 1;
278       attr.exclude_hv = 1;
279       attr.exclude_idle = 1;
280
281       file = syscall (SYS_perf_event_open, &attr, child, -1, -1, 0);
282       if (file >= 0)
283         close (file);
284
285       kill (child, SIGKILL);
286       ptrace (PTRACE_KILL, child, NULL, NULL);
287
288       pid = waitpid (child, &status, 0);
289       if (pid != child)
290         {
291           warning (_("test bts: bad pid %ld, error: %s."),
292                    (long) pid, strerror (errno));
293           if (!WIFSIGNALED (status))
294             warning (_("test bts: expected killed. status: %d."),
295                      status);
296         }
297
298       return (file >= 0);
299     }
300 }
301
302 /* Check whether an Intel cpu supports BTS.  */
303
304 static int
305 intel_supports_bts (void)
306 {
307   unsigned int cpuid, model, family;
308
309   if (!x86_cpuid (1, &cpuid, NULL, NULL, NULL))
310     return 0;
311
312   family = (cpuid >> 8) & 0xf;
313   model = (cpuid >> 4) & 0xf;
314
315   switch (family)
316     {
317     case 0x6:
318       model += (cpuid >> 12) & 0xf0;
319
320       switch (model)
321         {
322         case 0x1a: /* Nehalem */
323         case 0x1f:
324         case 0x1e:
325         case 0x2e:
326         case 0x25: /* Westmere */
327         case 0x2c:
328         case 0x2f:
329         case 0x2a: /* Sandy Bridge */
330         case 0x2d:
331         case 0x3a: /* Ivy Bridge */
332
333           /* AAJ122: LBR, BTM, or BTS records may have incorrect branch
334              "from" information afer an EIST transition, T-states, C1E, or
335              Adaptive Thermal Throttling.  */
336           return 0;
337         }
338     }
339
340   return 1;
341 }
342
343 /* Check whether the cpu supports BTS.  */
344
345 static int
346 cpu_supports_bts (void)
347 {
348   unsigned int ebx, ecx, edx;
349
350   if (!x86_cpuid (0, NULL, &ebx, &ecx, &edx))
351     return 0;
352
353   if (ebx == signature_INTEL_ebx && ecx == signature_INTEL_ecx
354       && edx == signature_INTEL_edx)
355     return intel_supports_bts ();
356
357   /* Don't know about others.  Let's assume they do.  */
358   return 1;
359 }
360
361 /* Check whether the linux target supports BTS.  */
362
363 static int
364 linux_supports_bts (void)
365 {
366   static int cached;
367
368   if (cached == 0)
369     {
370       if (!kernel_supports_bts ())
371         cached = -1;
372       else if (!cpu_supports_bts ())
373         cached = -1;
374       else
375         cached = 1;
376     }
377
378   return cached > 0;
379 }
380
381 /* See linux-btrace.h.  */
382
383 int
384 linux_supports_btrace (struct target_ops *ops, enum btrace_format format)
385 {
386   switch (format)
387     {
388     case BTRACE_FORMAT_NONE:
389       return 0;
390
391     case BTRACE_FORMAT_BTS:
392       return linux_supports_bts ();
393     }
394
395   internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
396 }
397
398 /* Enable branch tracing in BTS format.  */
399
400 static struct btrace_target_info *
401 linux_enable_bts (ptid_t ptid, const struct btrace_config *conf)
402 {
403   struct perf_event_mmap_page *header;
404   struct btrace_target_info *tinfo;
405   struct btrace_tinfo_bts *bts;
406   int pid, pg;
407
408   tinfo = xzalloc (sizeof (*tinfo));
409   tinfo->ptid = ptid;
410   tinfo->ptr_bits = 0;
411
412   tinfo->conf.format = BTRACE_FORMAT_BTS;
413   bts = &tinfo->variant.bts;
414
415   bts->attr.size = sizeof (bts->attr);
416   bts->attr.type = PERF_TYPE_HARDWARE;
417   bts->attr.config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS;
418   bts->attr.sample_period = 1;
419
420   /* We sample from and to address.  */
421   bts->attr.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_ADDR;
422
423   bts->attr.exclude_kernel = 1;
424   bts->attr.exclude_hv = 1;
425   bts->attr.exclude_idle = 1;
426
427   pid = ptid_get_lwp (ptid);
428   if (pid == 0)
429     pid = ptid_get_pid (ptid);
430
431   errno = 0;
432   bts->file = syscall (SYS_perf_event_open, &bts->attr, pid, -1, -1, 0);
433   if (bts->file < 0)
434     goto err;
435
436   /* We try to allocate as much buffer as we can get.
437      We could allow the user to specify the size of the buffer, but then
438      we'd leave this search for the maximum buffer size to him.  */
439   for (pg = 4; pg >= 0; --pg)
440     {
441       /* The number of pages we request needs to be a power of two.  */
442       header = mmap (NULL, ((1 << pg) + 1) * PAGE_SIZE, PROT_READ, MAP_SHARED,
443                      bts->file, 0);
444       if (header != MAP_FAILED)
445         break;
446     }
447
448   if (header == MAP_FAILED)
449     goto err_file;
450
451   bts->header = header;
452   bts->bts.mem = ((const uint8_t *) header) + PAGE_SIZE;
453   bts->bts.size = (1 << pg) * PAGE_SIZE;
454   bts->bts.data_head = &header->data_head;
455   bts->bts.last_head = 0;
456
457   return tinfo;
458
459  err_file:
460   /* We were not able to allocate any buffer.  */
461   close (bts->file);
462
463  err:
464   xfree (tinfo);
465   return NULL;
466 }
467
468 /* See linux-btrace.h.  */
469
470 struct btrace_target_info *
471 linux_enable_btrace (ptid_t ptid, const struct btrace_config *conf)
472 {
473   struct btrace_target_info *tinfo;
474
475   tinfo = NULL;
476   switch (conf->format)
477     {
478     case BTRACE_FORMAT_NONE:
479       break;
480
481     case BTRACE_FORMAT_BTS:
482       tinfo = linux_enable_bts (ptid, conf);
483       break;
484     }
485
486   return tinfo;
487 }
488
489 /* Disable BTS tracing.  */
490
491 static enum btrace_error
492 linux_disable_bts (struct btrace_tinfo_bts *tinfo)
493 {
494   munmap((void *) tinfo->header, tinfo->bts.size + PAGE_SIZE);
495   close (tinfo->file);
496
497   return BTRACE_ERR_NONE;
498 }
499
500 /* See linux-btrace.h.  */
501
502 enum btrace_error
503 linux_disable_btrace (struct btrace_target_info *tinfo)
504 {
505   enum btrace_error errcode;
506
507   errcode = BTRACE_ERR_NOT_SUPPORTED;
508   switch (tinfo->conf.format)
509     {
510     case BTRACE_FORMAT_NONE:
511       break;
512
513     case BTRACE_FORMAT_BTS:
514       errcode = linux_disable_bts (&tinfo->variant.bts);
515       break;
516     }
517
518   if (errcode == BTRACE_ERR_NONE)
519     xfree (tinfo);
520
521   return errcode;
522 }
523
524 /* Read branch trace data in BTS format for the thread given by TINFO into
525    BTRACE using the TYPE reading method.  */
526
527 static enum btrace_error
528 linux_read_bts (struct btrace_data_bts *btrace,
529                 struct btrace_target_info *tinfo,
530                 enum btrace_read_type type)
531 {
532   struct perf_event_buffer *pevent;
533   const uint8_t *begin, *end, *start;
534   unsigned long long data_head, data_tail, buffer_size, size;
535   unsigned int retries = 5;
536
537   pevent = &tinfo->variant.bts.bts;
538
539   /* For delta reads, we return at least the partial last block containing
540      the current PC.  */
541   if (type == BTRACE_READ_NEW && !perf_event_new_data (pevent))
542     return BTRACE_ERR_NONE;
543
544   buffer_size = pevent->size;
545   data_tail = pevent->last_head;
546
547   /* We may need to retry reading the trace.  See below.  */
548   while (retries--)
549     {
550       data_head = *pevent->data_head;
551
552       /* Delete any leftover trace from the previous iteration.  */
553       VEC_free (btrace_block_s, btrace->blocks);
554
555       if (type == BTRACE_READ_DELTA)
556         {
557           /* Determine the number of bytes to read and check for buffer
558              overflows.  */
559
560           /* Check for data head overflows.  We might be able to recover from
561              those but they are very unlikely and it's not really worth the
562              effort, I think.  */
563           if (data_head < data_tail)
564             return BTRACE_ERR_OVERFLOW;
565
566           /* If the buffer is smaller than the trace delta, we overflowed.  */
567           size = data_head - data_tail;
568           if (buffer_size < size)
569             return BTRACE_ERR_OVERFLOW;
570         }
571       else
572         {
573           /* Read the entire buffer.  */
574           size = buffer_size;
575
576           /* Adjust the size if the buffer has not overflowed, yet.  */
577           if (data_head < size)
578             size = data_head;
579         }
580
581       /* Data_head keeps growing; the buffer itself is circular.  */
582       begin = pevent->mem;
583       start = begin + data_head % buffer_size;
584
585       if (data_head <= buffer_size)
586         end = start;
587       else
588         end = begin + pevent->size;
589
590       btrace->blocks = perf_event_read_bts (tinfo, begin, end, start, size);
591
592       /* The stopping thread notifies its ptracer before it is scheduled out.
593          On multi-core systems, the debugger might therefore run while the
594          kernel might be writing the last branch trace records.
595
596          Let's check whether the data head moved while we read the trace.  */
597       if (data_head == *pevent->data_head)
598         break;
599     }
600
601   pevent->last_head = data_head;
602
603   /* Prune the incomplete last block (i.e. the first one of inferior execution)
604      if we're not doing a delta read.  There is no way of filling in its zeroed
605      BEGIN element.  */
606   if (!VEC_empty (btrace_block_s, btrace->blocks)
607       && type != BTRACE_READ_DELTA)
608     VEC_pop (btrace_block_s, btrace->blocks);
609
610   return BTRACE_ERR_NONE;
611 }
612
613 /* See linux-btrace.h.  */
614
615 enum btrace_error
616 linux_read_btrace (struct btrace_data *btrace,
617                    struct btrace_target_info *tinfo,
618                    enum btrace_read_type type)
619 {
620   switch (tinfo->conf.format)
621     {
622     case BTRACE_FORMAT_NONE:
623       return BTRACE_ERR_NOT_SUPPORTED;
624
625     case BTRACE_FORMAT_BTS:
626       /* We read btrace in BTS format.  */
627       btrace->format = BTRACE_FORMAT_BTS;
628       btrace->variant.bts.blocks = NULL;
629
630       return linux_read_bts (&btrace->variant.bts, tinfo, type);
631     }
632
633   internal_error (__FILE__, __LINE__, _("Unkown branch trace format."));
634 }
635
636 /* See linux-btrace.h.  */
637
638 const struct btrace_config *
639 linux_btrace_conf (const struct btrace_target_info *tinfo)
640 {
641   return &tinfo->conf;
642 }
643
644 #else /* !HAVE_LINUX_PERF_EVENT_H */
645
646 /* See linux-btrace.h.  */
647
648 int
649 linux_supports_btrace (struct target_ops *ops, enum btrace_format format)
650 {
651   return 0;
652 }
653
654 /* See linux-btrace.h.  */
655
656 struct btrace_target_info *
657 linux_enable_btrace (ptid_t ptid, const struct btrace_config *conf)
658 {
659   return NULL;
660 }
661
662 /* See linux-btrace.h.  */
663
664 enum btrace_error
665 linux_disable_btrace (struct btrace_target_info *tinfo)
666 {
667   return BTRACE_ERR_NOT_SUPPORTED;
668 }
669
670 /* See linux-btrace.h.  */
671
672 enum btrace_error
673 linux_read_btrace (struct btrace_data *btrace,
674                    struct btrace_target_info *tinfo,
675                    enum btrace_read_type type)
676 {
677   return BTRACE_ERR_NOT_SUPPORTED;
678 }
679
680 /* See linux-btrace.h.  */
681
682 const struct btrace_config *
683 linux_btrace_conf (const struct btrace_target_info *tinfo)
684 {
685   return NULL;
686 }
687
688 #endif /* !HAVE_LINUX_PERF_EVENT_H */