git: 62ce4a798f2c - stable/14 - cpufreq_dt: Find the closest frequency

From: Emmanuel Vadot <manu_at_FreeBSD.org>
Date: Wed, 18 Oct 2023 14:30:53 UTC
The branch stable/14 has been updated by manu:

URL: https://cgit.FreeBSD.org/src/commit/?id=62ce4a798f2c8a6357e8bc0c46e0f3e077ca1958

commit 62ce4a798f2c8a6357e8bc0c46e0f3e077ca1958
Author:     Emmanuel Vadot <manu@FreeBSD.org>
AuthorDate: 2023-09-06 16:40:17 +0000
Commit:     Emmanuel Vadot <manu@FreeBSD.org>
CommitDate: 2023-10-18 14:30:22 +0000

    cpufreq_dt: Find the closest frequency
    
    When building the frequencies table we convert the value in the DTS to
    megahertz and loose precision. While it's not a problem for most of the
    DTS it is when the expected frequency value is strict down to the hertz.
    So it's either we don't truncate the value and have some ugly and long
    values in the sysctls or we just find the closest frequency.
    Do the latter.
    
    Reviewed by:    mmel
    Differential Revision:  https://reviews.freebsd.org/D41762
    Sponsored by:   Beckhoff Automation GmbH & Co. KG
    
    (cherry picked from commit 17c17872ca98df0e2b9f9c7a2c41ef73f7dee21a)
---
 sys/dev/cpufreq/cpufreq_dt.c | 21 +++++++++++++++------
 1 file changed, 15 insertions(+), 6 deletions(-)

diff --git a/sys/dev/cpufreq/cpufreq_dt.c b/sys/dev/cpufreq/cpufreq_dt.c
index aaeada3a4e58..be434cabb4fd 100644
--- a/sys/dev/cpufreq/cpufreq_dt.c
+++ b/sys/dev/cpufreq/cpufreq_dt.c
@@ -104,17 +104,26 @@ static const struct cpufreq_dt_opp *
 cpufreq_dt_find_opp(device_t dev, uint64_t freq)
 {
 	struct cpufreq_dt_softc *sc;
-	ssize_t n;
+	uint64_t diff, best_diff;
+	ssize_t n, best_n;
 
 	sc = device_get_softc(dev);
 
+	diff = 0;
+	best_diff = ~0;
 	DPRINTF(dev, "Looking for freq %ju\n", freq);
-	for (n = 0; n < sc->nopp; n++)
-		if (CPUFREQ_CMP(sc->opp[n].freq, freq))
-			return (&sc->opp[n]);
+	for (n = 0; n < sc->nopp; n++) {
+		diff = abs64((int64_t)sc->opp[n].freq - (int64_t)freq);
+		DPRINTF(dev, "Testing %ju, diff is %ju\n", sc->opp[n].freq, diff);
+		if (diff < best_diff) {
+			best_diff = diff;
+			best_n = n;
+			DPRINTF(dev, "%ju is best for now\n", sc->opp[n].freq);
+		}
+	}
 
-	DPRINTF(dev, "Couldn't find one\n");
-	return (NULL);
+	DPRINTF(dev, "Will use %ju\n", sc->opp[best_n].freq);
+	return (&sc->opp[best_n]);
 }
 
 static void