blob: e06b2e1a27791002e4053f3e757f8b2df65caeab [file] [log] [blame]
Jason M. Bills3f7c5e42018-10-03 14:00:41 -07001/*
2// Copyright (c) 2017 2018 Intel Corporation
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15*/
16
17#pragma once
Josh Lehan17e21c22019-11-18 17:57:37 -080018#include <algorithm>
Jason M. Bills72867de2018-11-28 12:46:59 -080019#include <cmath>
Vernon Maueryae339042023-06-16 14:41:20 -070020#include <cstdint>
Jason M. Bills72867de2018-11-28 12:46:59 -080021#include <iostream>
Jason M. Bills3f7c5e42018-10-03 14:00:41 -070022
23namespace ipmi
24{
Jason M. Bills72867de2018-11-28 12:46:59 -080025static constexpr int16_t maxInt10 = 0x1FF;
James Feist39417c72019-01-03 09:14:24 -080026static constexpr int16_t minInt10 = -0x200;
Jason M. Bills72867de2018-11-28 12:46:59 -080027static constexpr int8_t maxInt4 = 7;
28static constexpr int8_t minInt4 = -8;
29
Josh Lehan17e21c22019-11-18 17:57:37 -080030// Helper function to avoid repeated complicated expression
31// TODO(): Refactor to add a proper sensorutils.cpp file,
32// instead of putting everything in this header as it is now,
33// so that helper functions can be correctly hidden from callers.
34static inline bool baseInRange(double base)
35{
36 auto min10 = static_cast<double>(minInt10);
37 auto max10 = static_cast<double>(maxInt10);
38
39 return ((base >= min10) && (base <= max10));
40}
41
42// Helper function for internal use by getSensorAttributes()
43// Ensures floating-point "base" is within bounds,
44// and adjusts integer exponent "expShift" accordingly.
45// To minimize data loss when later truncating to integer,
46// the floating-point "base" will be as large as possible,
47// but still within the bounds (minInt10,maxInt10).
48// The bounds of "expShift" are (minInt4,maxInt4).
49// Consider this equation: n = base * (10.0 ** expShift)
50// This function will try to maximize "base",
51// adjusting "expShift" to keep the value "n" unchanged,
52// while keeping base and expShift within bounds.
53// Returns true if successful, modifies values in-place
54static inline bool scaleFloatExp(double& base, int8_t& expShift)
55{
Josh Lehan17e21c22019-11-18 17:57:37 -080056 // Comparing with zero should be OK, zero is special in floating-point
57 // If base is exactly zero, no adjustment of the exponent is necessary
58 if (base == 0.0)
59 {
60 return true;
61 }
62
63 // As long as base value is within allowed range, expand precision
64 // This will help to avoid loss when later rounding to integer
65 while (baseInRange(base))
66 {
67 if (expShift <= minInt4)
68 {
69 // Already at the minimum expShift, can not decrement it more
70 break;
71 }
72
73 // Multiply by 10, but shift decimal point to the left, no net change
74 base *= 10.0;
75 --expShift;
76 }
77
78 // As long as base value is *not* within range, shrink precision
79 // This will pull base value closer to zero, thus within range
80 while (!(baseInRange(base)))
81 {
82 if (expShift >= maxInt4)
83 {
84 // Already at the maximum expShift, can not increment it more
85 break;
86 }
87
88 // Divide by 10, but shift decimal point to the right, no net change
89 base /= 10.0;
90 ++expShift;
91 }
92
93 // If the above loop was not able to pull it back within range,
94 // the base value is beyond what expShift can represent, return false.
95 return baseInRange(base);
96}
97
98// Helper function for internal use by getSensorAttributes()
99// Ensures integer "ibase" is no larger than necessary,
100// by normalizing it so that the decimal point shift is in the exponent,
101// whenever possible.
102// This provides more consistent results,
103// as many equivalent solutions are collapsed into one consistent solution.
104// If integer "ibase" is a clean multiple of 10,
105// divide it by 10 (this is lossless), so it is closer to zero.
106// Also modify floating-point "dbase" at the same time,
107// as both integer and floating-point base share the same expShift.
108// Example: (ibase=300, expShift=2) becomes (ibase=3, expShift=4)
109// because the underlying value is the same: 200*(10**2) == 2*(10**4)
110// Always successful, modifies values in-place
111static inline void normalizeIntExp(int16_t& ibase, int8_t& expShift,
112 double& dbase)
113{
114 for (;;)
115 {
116 // If zero, already normalized, ensure exponent also zero
117 if (ibase == 0)
118 {
119 expShift = 0;
120 break;
121 }
122
123 // If not cleanly divisible by 10, already normalized
124 if ((ibase % 10) != 0)
125 {
126 break;
127 }
128
129 // If exponent already at max, already normalized
130 if (expShift >= maxInt4)
131 {
132 break;
133 }
134
135 // Bring values closer to zero, correspondingly shift exponent,
136 // without changing the underlying number that this all represents,
137 // similar to what is done by scaleFloatExp().
138 // The floating-point base must be kept in sync with the integer base,
139 // as both floating-point and integer share the same exponent.
140 ibase /= 10;
141 dbase /= 10.0;
142 ++expShift;
143 }
144}
145
146// The IPMI equation:
147// y = (Mx + (B * 10^(bExp))) * 10^(rExp)
148// Section 36.3 of this document:
149// https://www.intel.com/content/dam/www/public/us/en/documents/product-briefs/ipmi-second-gen-interface-spec-v2-rev1-1.pdf
150//
151// The goal is to exactly match the math done by the ipmitool command,
152// at the other side of the interface:
153// https://github.com/ipmitool/ipmitool/blob/42a023ff0726c80e8cc7d30315b987fe568a981d/lib/ipmi_sdr.c#L360
154//
155// To use with Wolfram Alpha, make all variables single letters
156// bExp becomes E, rExp becomes R
157// https://www.wolframalpha.com/input/?i=y%3D%28%28M*x%29%2B%28B*%2810%5EE%29%29%29*%2810%5ER%29
Patrick Williams1bcced02024-08-16 15:20:24 -0400158static inline bool getSensorAttributes(
159 const double max, const double min, int16_t& mValue, int8_t& rExp,
160 int16_t& bValue, int8_t& bExp, bool& bSigned)
Jason M. Bills72867de2018-11-28 12:46:59 -0800161{
Josh Lehan17e21c22019-11-18 17:57:37 -0800162 if (!(std::isfinite(min)))
163 {
164 std::cerr << "getSensorAttributes: Min value is unusable\n";
165 return false;
166 }
167 if (!(std::isfinite(max)))
168 {
169 std::cerr << "getSensorAttributes: Max value is unusable\n";
170 return false;
171 }
172
173 // Because NAN has already been tested for, this comparison works
James Feist39417c72019-01-03 09:14:24 -0800174 if (max <= min)
Jason M. Bills72867de2018-11-28 12:46:59 -0800175 {
Vernon Mauery53870d72019-06-04 14:21:10 -0700176 std::cerr << "getSensorAttributes: Max must be greater than min\n";
Jason M. Bills72867de2018-11-28 12:46:59 -0800177 return false;
178 }
James Feist39417c72019-01-03 09:14:24 -0800179
Josh Lehan17e21c22019-11-18 17:57:37 -0800180 // Given min and max, we must solve for M, B, bExp, rExp
181 // y comes in from D-Bus (the actual sensor reading)
182 // x is calculated from y by scaleIPMIValueFromDouble() below
183 // If y is min, x should equal = 0 (or -128 if signed)
184 // If y is max, x should equal 255 (or 127 if signed)
185 double fullRange = max - min;
186 double lowestX;
Jason M. Bills72867de2018-11-28 12:46:59 -0800187
Josh Lehan17e21c22019-11-18 17:57:37 -0800188 rExp = 0;
189 bExp = 0;
190
191 // TODO(): The IPMI document is ambiguous, as to whether
192 // the resulting byte should be signed or unsigned,
193 // essentially leaving it up to the caller.
194 // The document just refers to it as "raw reading",
195 // or "byte of reading", without giving further details.
196 // Previous code set it signed if min was less than zero,
197 // so I'm sticking with that, until I learn otherwise.
198 if (min < 0.0)
Jason M. Bills72867de2018-11-28 12:46:59 -0800199 {
Josh Lehan17e21c22019-11-18 17:57:37 -0800200 // TODO(): It would be worth experimenting with the range (-127,127),
201 // instead of the range (-128,127), because this
202 // would give good symmetry around zero, and make results look better.
203 // Divide by 254 instead of 255, and change -128 to -127 elsewhere.
Jason M. Bills72867de2018-11-28 12:46:59 -0800204 bSigned = true;
Josh Lehan17e21c22019-11-18 17:57:37 -0800205 lowestX = -128.0;
Jason M. Bills72867de2018-11-28 12:46:59 -0800206 }
207 else
208 {
209 bSigned = false;
Josh Lehan17e21c22019-11-18 17:57:37 -0800210 lowestX = 0.0;
Jason M. Bills72867de2018-11-28 12:46:59 -0800211 }
212
Josh Lehan17e21c22019-11-18 17:57:37 -0800213 // Step 1: Set y to (max - min), set x to 255, set B to 0, solve for M
214 // This works, regardless of signed or unsigned,
215 // because total range is the same.
216 double dM = fullRange / 255.0;
Jason M. Bills72867de2018-11-28 12:46:59 -0800217
Josh Lehan17e21c22019-11-18 17:57:37 -0800218 // Step 2: Constrain M, and set rExp accordingly
219 if (!(scaleFloatExp(dM, rExp)))
Jason M. Bills72867de2018-11-28 12:46:59 -0800220 {
Josh Lehan17e21c22019-11-18 17:57:37 -0800221 std::cerr << "getSensorAttributes: Multiplier range exceeds scale (M="
222 << dM << ", rExp=" << (int)rExp << ")\n";
223 return false;
Jason M. Bills72867de2018-11-28 12:46:59 -0800224 }
225
Josh Lehan17e21c22019-11-18 17:57:37 -0800226 mValue = static_cast<int16_t>(std::round(dM));
227
228 normalizeIntExp(mValue, rExp, dM);
229
230 // The multiplier can not be zero, for obvious reasons
231 if (mValue == 0)
Jason M. Bills72867de2018-11-28 12:46:59 -0800232 {
Josh Lehan17e21c22019-11-18 17:57:37 -0800233 std::cerr << "getSensorAttributes: Multiplier range below scale\n";
234 return false;
Jason M. Bills72867de2018-11-28 12:46:59 -0800235 }
236
Josh Lehan17e21c22019-11-18 17:57:37 -0800237 // Step 3: set y to min, set x to min, keep M and rExp, solve for B
238 // If negative, x will be -128 (the most negative possible byte), not 0
Jason M. Bills72867de2018-11-28 12:46:59 -0800239
Josh Lehan17e21c22019-11-18 17:57:37 -0800240 // Solve the IPMI equation for B, instead of y
241 // https://www.wolframalpha.com/input/?i=solve+y%3D%28%28M*x%29%2B%28B*%2810%5EE%29%29%29*%2810%5ER%29+for+B
242 // B = 10^(-rExp - bExp) (y - M 10^rExp x)
243 // TODO(): Compare with this alternative solution from SageMathCell
244 // https://sagecell.sagemath.org/?z=eJyrtC1LLNJQr1TX5KqAMCuATF8I0xfIdIIwnYDMIteKAggPxAIKJMEFkiACxfk5Zaka0ZUKtrYKGhq-CloKFZoK2goaTkCWhqGBgpaWAkilpqYmQgBklmasjoKTJgDAECTH&lang=sage&interacts=eJyLjgUAARUAuQ==
245 double dB = std::pow(10.0, ((-rExp) - bExp)) *
246 (min - ((dM * std::pow(10.0, rExp) * lowestX)));
247
248 // Step 4: Constrain B, and set bExp accordingly
249 if (!(scaleFloatExp(dB, bExp)))
Jason M. Bills72867de2018-11-28 12:46:59 -0800250 {
Patrick Williams1bcced02024-08-16 15:20:24 -0400251 std::cerr << "getSensorAttributes: Offset (B=" << dB << ", bExp="
252 << (int)bExp << ") exceeds multiplier scale (M=" << dM
Josh Lehan17e21c22019-11-18 17:57:37 -0800253 << ", rExp=" << (int)rExp << ")\n";
254 return false;
Jason M. Bills72867de2018-11-28 12:46:59 -0800255 }
256
Josh Lehan17e21c22019-11-18 17:57:37 -0800257 bValue = static_cast<int16_t>(std::round(dB));
Jason M. Bills72867de2018-11-28 12:46:59 -0800258
Josh Lehan17e21c22019-11-18 17:57:37 -0800259 normalizeIntExp(bValue, bExp, dB);
Jason M. Bills72867de2018-11-28 12:46:59 -0800260
Josh Lehan17e21c22019-11-18 17:57:37 -0800261 // Unlike the multiplier, it is perfectly OK for bValue to be zero
Jason M. Bills72867de2018-11-28 12:46:59 -0800262 return true;
263}
264
Patrick Williams1bcced02024-08-16 15:20:24 -0400265static inline uint8_t scaleIPMIValueFromDouble(
266 const double value, const int16_t mValue, const int8_t rExp,
267 const int16_t bValue, const int8_t bExp, const bool bSigned)
Jason M. Bills72867de2018-11-28 12:46:59 -0800268{
Josh Lehan17e21c22019-11-18 17:57:37 -0800269 // Avoid division by zero below
270 if (mValue == 0)
271 {
272 throw std::out_of_range("Scaling multiplier is uninitialized");
273 }
James Feist39417c72019-01-03 09:14:24 -0800274
Josh Lehan17e21c22019-11-18 17:57:37 -0800275 auto dM = static_cast<double>(mValue);
276 auto dB = static_cast<double>(bValue);
277
278 // Solve the IPMI equation for x, instead of y
279 // https://www.wolframalpha.com/input/?i=solve+y%3D%28%28M*x%29%2B%28B*%2810%5EE%29%29%29*%2810%5ER%29+for+x
280 // x = (10^(-rExp) (y - B 10^(rExp + bExp)))/M and M 10^rExp!=0
281 // TODO(): Compare with this alternative solution from SageMathCell
282 // https://sagecell.sagemath.org/?z=eJyrtC1LLNJQr1TX5KqAMCuATF8I0xfIdIIwnYDMIteKAggPxAIKJMEFkiACxfk5Zaka0ZUKtrYKGhq-CloKFZoK2goaTkCWhqGBgpaWAkilpqYmQgBklmasDlAlAMB8JP0=&lang=sage&interacts=eJyLjgUAARUAuQ==
283 double dX =
284 (std::pow(10.0, -rExp) * (value - (dB * std::pow(10.0, rExp + bExp)))) /
285 dM;
286
287 auto scaledValue = static_cast<int32_t>(std::round(dX));
288
289 int32_t minClamp;
290 int32_t maxClamp;
291
292 // Because of rounding and integer truncation of scaling factors,
293 // sometimes the resulting byte is slightly out of range.
294 // Still allow this, but clamp the values to range.
Jason M. Bills72867de2018-11-28 12:46:59 -0800295 if (bSigned)
296 {
Josh Lehan17e21c22019-11-18 17:57:37 -0800297 minClamp = std::numeric_limits<int8_t>::lowest();
298 maxClamp = std::numeric_limits<int8_t>::max();
Jason M. Bills72867de2018-11-28 12:46:59 -0800299 }
300 else
301 {
Josh Lehan17e21c22019-11-18 17:57:37 -0800302 minClamp = std::numeric_limits<uint8_t>::lowest();
303 maxClamp = std::numeric_limits<uint8_t>::max();
Jason M. Bills72867de2018-11-28 12:46:59 -0800304 }
Josh Lehan17e21c22019-11-18 17:57:37 -0800305
306 auto clampedValue = std::clamp(scaledValue, minClamp, maxClamp);
307
308 // This works for both signed and unsigned,
309 // because it is the same underlying byte storage.
310 return static_cast<uint8_t>(clampedValue);
Jason M. Bills72867de2018-11-28 12:46:59 -0800311}
312
313static inline uint8_t getScaledIPMIValue(const double value, const double max,
314 const double min)
315{
316 int16_t mValue = 0;
317 int8_t rExp = 0;
318 int16_t bValue = 0;
319 int8_t bExp = 0;
Josh Lehan17e21c22019-11-18 17:57:37 -0800320 bool bSigned = false;
Jason M. Bills72867de2018-11-28 12:46:59 -0800321
Patrick Williams1bcced02024-08-16 15:20:24 -0400322 bool result =
323 getSensorAttributes(max, min, mValue, rExp, bValue, bExp, bSigned);
Jason M. Bills72867de2018-11-28 12:46:59 -0800324 if (!result)
325 {
James Feist39417c72019-01-03 09:14:24 -0800326 throw std::runtime_error("Illegal sensor attributes");
Jason M. Bills72867de2018-11-28 12:46:59 -0800327 }
Josh Lehan17e21c22019-11-18 17:57:37 -0800328
Jason M. Bills72867de2018-11-28 12:46:59 -0800329 return scaleIPMIValueFromDouble(value, mValue, rExp, bValue, bExp, bSigned);
330}
331
James Feist2a265d52019-04-08 11:16:27 -0700332} // namespace ipmi