// SPDX-License-Identifier: GPL-2.0-only1/*2* Copyright (C) 2012 Regents of the University of California3*/45#include <linux/delay.h>6#include <linux/math.h>7#include <linux/param.h>8#include <linux/timex.h>9#include <linux/types.h>10#include <linux/export.h>1112#include <asm/processor.h>1314/*15* This is copies from arch/arm/include/asm/delay.h16*17* Loop (or tick) based delay:18*19* loops = loops_per_jiffy * jiffies_per_sec * delay_us / us_per_sec20*21* where:22*23* jiffies_per_sec = HZ24* us_per_sec = 100000025*26* Therefore the constant part is HZ / 1000000 which is a small27* fractional number. To make this usable with integer math, we28* scale up this constant by 2^31, perform the actual multiplication,29* and scale the result back down by 2^31 with a simple shift:30*31* loops = (loops_per_jiffy * delay_us * UDELAY_MULT) >> 3132*33* where:34*35* UDELAY_MULT = 2^31 * HZ / 100000036* = (2^31 / 1000000) * HZ37* = 2147.483648 * HZ38* = 2147 * HZ + 483648 * HZ / 100000039*40* 31 is the biggest scale shift value that won't overflow 32 bits for41* delay_us * UDELAY_MULT assuming HZ <= 1000 and delay_us <= 2000.42*/43#define MAX_UDELAY_US 200044#define MAX_UDELAY_HZ 100045#define UDELAY_MULT (2147UL * HZ + 483648UL * HZ / 1000000UL)46#define UDELAY_SHIFT 314748#if HZ > MAX_UDELAY_HZ49#error "HZ > MAX_UDELAY_HZ"50#endif5152/*53* RISC-V supports both UDELAY and NDELAY. This is largely the same as above,54* but with different constants. I added 10 bits to the shift to get this, but55* the result is that I need a 64-bit multiply, which is slow on 32-bit56* platforms.57*58* NDELAY_MULT = 2^41 * HZ / 100000000059* = (2^41 / 1000000000) * HZ60* = 2199.02325555 * HZ61* = 2199 * HZ + 23255550 * HZ / 100000000062*63* The maximum here is to avoid 64-bit overflow, but it isn't checked as it64* won't happen.65*/66#define MAX_NDELAY_NS (1ULL << 42)67#define MAX_NDELAY_HZ MAX_UDELAY_HZ68#define NDELAY_MULT ((unsigned long long)(2199ULL * HZ + 23255550ULL * HZ / 1000000000ULL))69#define NDELAY_SHIFT 417071#if HZ > MAX_NDELAY_HZ72#error "HZ > MAX_NDELAY_HZ"73#endif7475void __delay(unsigned long cycles)76{77u64 t0 = get_cycles();7879while ((unsigned long)(get_cycles() - t0) < cycles)80cpu_relax();81}82EXPORT_SYMBOL(__delay);8384void udelay(unsigned long usecs)85{86u64 ucycles = (u64)usecs * lpj_fine * UDELAY_MULT;87u64 n;8889if (unlikely(usecs > MAX_UDELAY_US)) {90n = (u64)usecs * riscv_timebase;91do_div(n, 1000000);9293__delay(n);94return;95}9697__delay(ucycles >> UDELAY_SHIFT);98}99EXPORT_SYMBOL(udelay);100101void ndelay(unsigned long nsecs)102{103/*104* This doesn't bother checking for overflow, as it won't happen (it's105* an hour) of delay.106*/107unsigned long long ncycles = nsecs * lpj_fine * NDELAY_MULT;108__delay(ncycles >> NDELAY_SHIFT);109}110EXPORT_SYMBOL(ndelay);111112113