[PATCH] hw/adc: add default vref and defend against DIV0 for npcm7xx

Alex Bennée posted 1 patch 2 weeks, 4 days ago
Patches applied successfully (tree, apply log)
git fetch https://github.com/patchew-project/qemu tags/patchew/20260908191011.4089504-1-alex.bennee@linaro.org
Maintainers: Alistair Francis <alistair@alistair23.me>, Peter Maydell <peter.maydell@linaro.org>, Tyrone Ting <kfting@nuvoton.com>, Hao Wu <wuhaotsh@google.com>
hw/adc/npcm7xx_adc.c | 10 +++++++---
1 file changed, 7 insertions(+), 3 deletions(-)
[PATCH] hw/adc: add default vref and defend against DIV0 for npcm7xx
Posted by Alex Bennée 2 weeks, 4 days ago
Googling seems to imply vref is usually expected to be somewhere
between 1.6V and 2.5V. For lack of any better idea default it to the
internal reference voltage. While at it guard against div0 which in
the real world is likely going to saturate the result.

Fixes: https://gitlab.com/qemu-project/qemu/-/work_items/550
Signed-off-by: Alex Bennée <alex.bennee@linaro.org>
---
 hw/adc/npcm7xx_adc.c | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)

diff --git a/hw/adc/npcm7xx_adc.c b/hw/adc/npcm7xx_adc.c
index 3584c27c75a..54d3cfaa813 100644
--- a/hw/adc/npcm7xx_adc.c
+++ b/hw/adc/npcm7xx_adc.c
@@ -57,11 +57,14 @@ static uint32_t npcm7xx_adc_convert(uint32_t input, uint32_t ref)
 {
     uint32_t result;
 
-    result = input * (NPCM7XX_ADC_MAX_RESULT + 1) / ref;
-    if (result > NPCM7XX_ADC_MAX_RESULT) {
+    if (ref) {
+        result = input * (NPCM7XX_ADC_MAX_RESULT + 1) / ref;
+        if (result > NPCM7XX_ADC_MAX_RESULT) {
+            result = NPCM7XX_ADC_MAX_RESULT;
+        }
+    } else {
         result = NPCM7XX_ADC_MAX_RESULT;
     }
-
     return result;
 }
 
@@ -244,6 +247,7 @@ static void npcm7xx_adc_init(Object *obj)
         object_property_add_uint32_ptr(obj, "adci[*]",
                 &s->adci[i], OBJ_PROP_FLAG_READWRITE);
     }
+    s->vref = NPCM7XX_ADC_DEFAULT_IREF;
     object_property_add_uint32_ptr(obj, "vref",
             &s->vref, OBJ_PROP_FLAG_WRITE);
     npcm7xx_adc_calibrate(s);
-- 
2.47.3