New upstream version 18.02
[deb_dpdk.git] / lib / librte_eal / common / arch / x86 / rte_cycles.c
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright(c) 2017 Intel Corporation
3  */
4
5 #include <fcntl.h>
6 #include <unistd.h>
7 #include <cpuid.h>
8
9 #include <rte_common.h>
10
11 #include "eal_private.h"
12
13 static unsigned int
14 rte_cpu_get_model(uint32_t fam_mod_step)
15 {
16         uint32_t family, model, ext_model;
17
18         family = (fam_mod_step >> 8) & 0xf;
19         model = (fam_mod_step >> 4) & 0xf;
20
21         if (family == 6 || family == 15) {
22                 ext_model = (fam_mod_step >> 16) & 0xf;
23                 model += (ext_model << 4);
24         }
25
26         return model;
27 }
28
29 static int32_t
30 rdmsr(int msr, uint64_t *val)
31 {
32 #ifdef RTE_EXEC_ENV_LINUXAPP
33         int fd;
34         int ret;
35
36         fd = open("/dev/cpu/0/msr", O_RDONLY);
37         if (fd < 0)
38                 return fd;
39
40         ret = pread(fd, val, sizeof(uint64_t), msr);
41
42         close(fd);
43
44         return ret;
45 #else
46         RTE_SET_USED(msr);
47         RTE_SET_USED(val);
48
49         return -1;
50 #endif
51 }
52
53 static uint32_t
54 check_model_wsm_nhm(uint8_t model)
55 {
56         switch (model) {
57         /* Westmere */
58         case 0x25:
59         case 0x2C:
60         case 0x2F:
61         /* Nehalem */
62         case 0x1E:
63         case 0x1F:
64         case 0x1A:
65         case 0x2E:
66                 return 1;
67         }
68
69         return 0;
70 }
71
72 static uint32_t
73 check_model_gdm_dnv(uint8_t model)
74 {
75         switch (model) {
76         /* Goldmont */
77         case 0x5C:
78         /* Denverton */
79         case 0x5F:
80                 return 1;
81         }
82
83         return 0;
84 }
85
86 uint64_t
87 get_tsc_freq_arch(void)
88 {
89         uint64_t tsc_hz = 0;
90         uint32_t a, b, c, d, maxleaf;
91         uint8_t mult, model;
92         int32_t ret;
93
94         /*
95          * Time Stamp Counter and Nominal Core Crystal Clock
96          * Information Leaf
97          */
98         maxleaf = __get_cpuid_max(0, NULL);
99
100         if (maxleaf >= 0x15) {
101                 __cpuid(0x15, a, b, c, d);
102
103                 /* EBX : TSC/Crystal ratio, ECX : Crystal Hz */
104                 if (b && c)
105                         return c * (b / a);
106         }
107
108         __cpuid(0x1, a, b, c, d);
109         model = rte_cpu_get_model(a);
110
111         if (check_model_wsm_nhm(model))
112                 mult = 133;
113         else if ((c & bit_AVX) || check_model_gdm_dnv(model))
114                 mult = 100;
115         else
116                 return 0;
117
118         ret = rdmsr(0xCE, &tsc_hz);
119         if (ret < 0)
120                 return 0;
121
122         return ((tsc_hz >> 8) & 0xff) * mult * 1E6;
123 }