New upstream version 18.02
[deb_dpdk.git] / lib / librte_eal / common / eal_common_timer.c
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright(c) 2010-2014 Intel Corporation
3  */
4
5 #include <string.h>
6 #include <stdio.h>
7 #include <unistd.h>
8 #include <inttypes.h>
9 #include <sys/types.h>
10 #include <errno.h>
11
12 #include <rte_common.h>
13 #include <rte_log.h>
14 #include <rte_cycles.h>
15 #include <rte_pause.h>
16
17 #include "eal_private.h"
18
19 /* The frequency of the RDTSC timer resolution */
20 static uint64_t eal_tsc_resolution_hz;
21
22 /* Pointer to user delay function */
23 void (*rte_delay_us)(unsigned int) = NULL;
24
25 void
26 rte_delay_us_block(unsigned int us)
27 {
28         const uint64_t start = rte_get_timer_cycles();
29         const uint64_t ticks = (uint64_t)us * rte_get_timer_hz() / 1E6;
30         while ((rte_get_timer_cycles() - start) < ticks)
31                 rte_pause();
32 }
33
34 uint64_t
35 rte_get_tsc_hz(void)
36 {
37         return eal_tsc_resolution_hz;
38 }
39
40 static uint64_t
41 estimate_tsc_freq(void)
42 {
43         RTE_LOG(WARNING, EAL, "WARNING: TSC frequency estimated roughly"
44                 " - clock timings may be less accurate.\n");
45         /* assume that the sleep(1) will sleep for 1 second */
46         uint64_t start = rte_rdtsc();
47         sleep(1);
48         return rte_rdtsc() - start;
49 }
50
51 void
52 set_tsc_freq(void)
53 {
54         uint64_t freq;
55
56         freq = get_tsc_freq_arch();
57         if (!freq)
58                 freq = get_tsc_freq();
59         if (!freq)
60                 freq = estimate_tsc_freq();
61
62         RTE_LOG(DEBUG, EAL, "TSC frequency is ~%" PRIu64 " KHz\n", freq / 1000);
63         eal_tsc_resolution_hz = freq;
64 }
65
66 void rte_delay_us_callback_register(void (*userfunc)(unsigned int))
67 {
68         rte_delay_us = userfunc;
69 }
70
71 RTE_INIT(rte_timer_init)
72 {
73         /* set rte_delay_us_block as a delay function */
74         rte_delay_us_callback_register(rte_delay_us_block);
75 }