1/*
2 * Copyright 2017, Data61
3 * Commonwealth Scientific and Industrial Research Organisation (CSIRO)
4 * ABN 41 687 119 230.
5 *
6 * This software may be distributed and modified according to the terms of
7 * the BSD 2-Clause license. Note that NO WARRANTY is provided.
8 * See "LICENSE_BSD2.txt" for details.
9 *
10 * @TAG(DATA61_BSD)
11 */
12
13#include <autoconf.h>
14#include <platsupport/gen_config.h>
15#include <platsupport/arch/tsc.h>
16#include <platsupport/delay.h>
17#include <stdint.h>
18#include <stdio.h>
19
20#define DEFAULT_CPUFREQ 1500000000UL
21
22static unsigned long cpufreq_hint = DEFAULT_CPUFREQ;
23#define CYCLES_PER_US(cpufreq) (cpufreq / 1000000)
24
25static void
26ps_do_cycle_delay(uint64_t cycles)
27{
28    uint64_t end = rdtsc_pure() + cycles;
29
30    while (1) {
31        if (end <= rdtsc_pure()) {
32            break;
33        }
34    }
35}
36
37void
38ps_udelay(unsigned long us)
39{
40    ps_do_cycle_delay((uint64_t)us * CYCLES_PER_US(cpufreq_hint));
41}
42
43void
44ps_cpufreq_hint(unsigned long hz)
45{
46    if (hz == 0) {
47        ZF_LOGW("%s:%d - Invalid CPU frequency for delay loop, use the default\n",
48		__FILE__, __LINE__);
49        hz = DEFAULT_CPUFREQ;
50    }
51
52    cpufreq_hint = hz;
53}
54