Because we are limited by unsigned ints, we need to be able to provide inputs in milliunits which can get scaled up to fit in the linear mode registers.
For example: 3.4 is a valid input, and now we can provide 3400 and scale it into the register without losing the 0.4 Signed-off-by: Titus Rwantare <[email protected]> --- hw/i2c/pmbus_device.c | 39 +++++++++++++++++++++++++++++++++++ include/hw/i2c/pmbus_device.h | 18 ++++++++++++++++ 2 files changed, 57 insertions(+) diff --git a/hw/i2c/pmbus_device.c b/hw/i2c/pmbus_device.c index b1f9843f52..e2e1e0e945 100644 --- a/hw/i2c/pmbus_device.c +++ b/hw/i2c/pmbus_device.c @@ -8,6 +8,7 @@ #include "qemu/osdep.h" #include <math.h> +#include <stdint.h> #include "hw/i2c/pmbus_device.h" #include "migration/vmstate.h" #include "qemu/module.h" @@ -38,6 +39,25 @@ uint16_t pmbus_data2linear_mode(uint16_t value, int exp) return value >> exp; } +uint16_t pmbus_milliunits2linear_mode(uint32_t value, int exp) +{ + uint32_t ret; + + /* L = D * 2^(-e) */ + if (exp < 0) { + ret = DIV_ROUND_CLOSEST((value << (-exp)), 1000); + } else { + ret = DIV_ROUND_CLOSEST((value >> exp), 1000); + } + + /* clamp value to maximum if it exceeds representable value*/ + if (ret > UINT16_MAX) { + return UINT16_MAX; + } + + return ret; +} + uint16_t pmbus_linear_mode2data(uint16_t value, int exp) { /* D = L * 2^e */ @@ -47,6 +67,25 @@ uint16_t pmbus_linear_mode2data(uint16_t value, int exp) return value << exp; } +uint32_t pmbus_linear_mode2milliunits(uint16_t value, int exp) +{ + /* D = L * 2^e */ + uint64_t v = (uint64_t)value; + uint64_t ret; + + if (exp < 0) { + ret = (v * 1000) >> (-exp); + } else { + ret = (v << exp) * 1000; + } + + if (ret > UINT32_MAX) { + return UINT32_MAX; + } + + return (uint32_t)ret; +} + void pmbus_send(PMBusDevice *pmdev, const uint8_t *data, uint16_t len) { if (pmdev->out_buf_len + len > SMBUS_DATA_MAX_LEN) { diff --git a/include/hw/i2c/pmbus_device.h b/include/hw/i2c/pmbus_device.h index f195c11384..9f3569e997 100644 --- a/include/hw/i2c/pmbus_device.h +++ b/include/hw/i2c/pmbus_device.h @@ -481,6 +481,15 @@ uint32_t pmbus_direct_mode2data(PMBusCoefficients c, uint16_t value); */ uint16_t pmbus_data2linear_mode(uint16_t value, int exp); +/** + * Convert milliunit sensor value to linear mode format + * + * L = D * 2^(-e) + * + * @return uint16 + */ +uint16_t pmbus_milliunits2linear_mode(uint32_t value, int exp); + /** * Convert linear mode formatted data into sensor reading * @@ -490,6 +499,15 @@ uint16_t pmbus_data2linear_mode(uint16_t value, int exp); */ uint16_t pmbus_linear_mode2data(uint16_t value, int exp); +/** + * Convert linear mode formatted data into sensor reading in milliunits + * + * D = L * 2^e + * + * @return uint32 value in milliunits + */ +uint32_t pmbus_linear_mode2milliunits(uint16_t value, int exp); + /** * @brief Send a block of data over PMBus * Assumes that the bytes in the block are already ordered correctly, -- 2.55.0.rc2.803.g1fd1e6609c-goog
