1 /*
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 #include "dbus-sdr/sensorutils.hpp"
18
19 #include <algorithm>
20 #include <cmath>
21 #include <iostream>
22
23 namespace ipmi
24 {
25
26 // Helper function to avoid repeated complicated expression
baseInRange(double base)27 static bool baseInRange(double base)
28 {
29 auto min10 = static_cast<double>(minInt10);
30 auto max10 = static_cast<double>(maxInt10);
31
32 return ((base >= min10) && (base <= max10));
33 }
34
35 // Helper function for internal use by getSensorAttributes()
36 // Ensures floating-point "base" is within bounds,
37 // and adjusts integer exponent "expShift" accordingly.
38 // To minimize data loss when later truncating to integer,
39 // the floating-point "base" will be as large as possible,
40 // but still within the bounds (minInt10,maxInt10).
41 // The bounds of "expShift" are (minInt4,maxInt4).
42 // Consider this equation: n = base * (10.0 ** expShift)
43 // This function will try to maximize "base",
44 // adjusting "expShift" to keep the value "n" unchanged,
45 // while keeping base and expShift within bounds.
46 // Returns true if successful, modifies values in-place
scaleFloatExp(double & base,int8_t & expShift)47 static bool scaleFloatExp(double& base, int8_t& expShift)
48 {
49 // Comparing with zero should be OK, zero is special in floating-point
50 // If base is exactly zero, no adjustment of the exponent is necessary
51 if (base == 0.0)
52 {
53 return true;
54 }
55
56 // As long as base value is within allowed range, expand precision
57 // This will help to avoid loss when later rounding to integer
58 while (baseInRange(base))
59 {
60 if (expShift <= minInt4)
61 {
62 // Already at the minimum expShift, can not decrement it more
63 break;
64 }
65
66 // Multiply by 10, but shift decimal point to the left, no net change
67 base *= 10.0;
68 --expShift;
69 }
70
71 // As long as base value is *not* within range, shrink precision
72 // This will pull base value closer to zero, thus within range
73 while (!(baseInRange(base)))
74 {
75 if (expShift >= maxInt4)
76 {
77 // Already at the maximum expShift, can not increment it more
78 break;
79 }
80
81 // Divide by 10, but shift decimal point to the right, no net change
82 base /= 10.0;
83 ++expShift;
84 }
85
86 // If the above loop was not able to pull it back within range,
87 // the base value is beyond what expShift can represent, return false.
88 return baseInRange(base);
89 }
90
91 // Helper function for internal use by getSensorAttributes()
92 // Ensures integer "ibase" is no larger than necessary,
93 // by normalizing it so that the decimal point shift is in the exponent,
94 // whenever possible.
95 // This provides more consistent results,
96 // as many equivalent solutions are collapsed into one consistent solution.
97 // If integer "ibase" is a clean multiple of 10,
98 // divide it by 10 (this is lossless), so it is closer to zero.
99 // Also modify floating-point "dbase" at the same time,
100 // as both integer and floating-point base share the same expShift.
101 // Example: (ibase=300, expShift=2) becomes (ibase=3, expShift=4)
102 // because the underlying value is the same: 200*(10**2) == 2*(10**4)
103 // Always successful, modifies values in-place
normalizeIntExp(int16_t & ibase,int8_t & expShift,double & dbase)104 static void normalizeIntExp(int16_t& ibase, int8_t& expShift, double& dbase)
105 {
106 for (;;)
107 {
108 // If zero, already normalized, ensure exponent also zero
109 if (ibase == 0)
110 {
111 expShift = 0;
112 break;
113 }
114
115 // If not cleanly divisible by 10, already normalized
116 if ((ibase % 10) != 0)
117 {
118 break;
119 }
120
121 // If exponent already at max, already normalized
122 if (expShift >= maxInt4)
123 {
124 break;
125 }
126
127 // Bring values closer to zero, correspondingly shift exponent,
128 // without changing the underlying number that this all represents,
129 // similar to what is done by scaleFloatExp().
130 // The floating-point base must be kept in sync with the integer base,
131 // as both floating-point and integer share the same exponent.
132 ibase /= 10;
133 dbase /= 10.0;
134 ++expShift;
135 }
136 }
137
138 // The IPMI equation:
139 // y = (Mx + (B * 10^(bExp))) * 10^(rExp)
140 // Section 36.3 of this document:
141 // https://www.intel.com/content/dam/www/public/us/en/documents/product-briefs/ipmi-second-gen-interface-spec-v2-rev1-1.pdf
142 //
143 // The goal is to exactly match the math done by the ipmitool command,
144 // at the other side of the interface:
145 // https://github.com/ipmitool/ipmitool/blob/42a023ff0726c80e8cc7d30315b987fe568a981d/lib/ipmi_sdr.c#L360
146 //
147 // To use with Wolfram Alpha, make all variables single letters
148 // bExp becomes E, rExp becomes R
149 // https://www.wolframalpha.com/input/?i=y%3D%28%28M*x%29%2B%28B*%2810%5EE%29%29%29*%2810%5ER%29
getSensorAttributes(const double max,const double min,int16_t & mValue,int8_t & rExp,int16_t & bValue,int8_t & bExp,bool & bSigned)150 bool getSensorAttributes(const double max, const double min, int16_t& mValue,
151 int8_t& rExp, int16_t& bValue, int8_t& bExp,
152 bool& bSigned)
153 {
154 if (!(std::isfinite(min)))
155 {
156 std::cerr << "getSensorAttributes: Min value is unusable\n";
157 return false;
158 }
159 if (!(std::isfinite(max)))
160 {
161 std::cerr << "getSensorAttributes: Max value is unusable\n";
162 return false;
163 }
164
165 // Because NAN has already been tested for, this comparison works
166 if (max <= min)
167 {
168 std::cerr << "getSensorAttributes: Max must be greater than min\n";
169 return false;
170 }
171
172 // Given min and max, we must solve for M, B, bExp, rExp
173 // y comes in from D-Bus (the actual sensor reading)
174 // x is calculated from y by scaleIPMIValueFromDouble() below
175 // If y is min, x should equal = 0 (or -128 if signed)
176 // If y is max, x should equal 255 (or 127 if signed)
177 double fullRange = max - min;
178 double lowestX;
179
180 rExp = 0;
181 bExp = 0;
182
183 // TODO(): The IPMI document is ambiguous, as to whether
184 // the resulting byte should be signed or unsigned,
185 // essentially leaving it up to the caller.
186 // The document just refers to it as "raw reading",
187 // or "byte of reading", without giving further details.
188 // Previous code set it signed if min was less than zero,
189 // so I'm sticking with that, until I learn otherwise.
190 if (min < 0.0)
191 {
192 // TODO(): It would be worth experimenting with the range (-127,127),
193 // instead of the range (-128,127), because this
194 // would give good symmetry around zero, and make results look better.
195 // Divide by 254 instead of 255, and change -128 to -127 elsewhere.
196 bSigned = true;
197 lowestX = -128.0;
198 }
199 else
200 {
201 bSigned = false;
202 lowestX = 0.0;
203 }
204
205 // Step 1: Set y to (max - min), set x to 255, set B to 0, solve for M
206 // This works, regardless of signed or unsigned,
207 // because total range is the same.
208 double dM = fullRange / 255.0;
209
210 // Step 2: Constrain M, and set rExp accordingly
211 if (!(scaleFloatExp(dM, rExp)))
212 {
213 std::cerr << "getSensorAttributes: Multiplier range exceeds scale (M="
214 << dM << ", rExp=" << (int)rExp << ")\n";
215 return false;
216 }
217
218 mValue = static_cast<int16_t>(std::round(dM));
219
220 normalizeIntExp(mValue, rExp, dM);
221
222 // The multiplier can not be zero, for obvious reasons
223 if (mValue == 0)
224 {
225 std::cerr << "getSensorAttributes: Multiplier range below scale\n";
226 return false;
227 }
228
229 // Step 3: set y to min, set x to min, keep M and rExp, solve for B
230 // If negative, x will be -128 (the most negative possible byte), not 0
231
232 // Solve the IPMI equation for B, instead of y
233 // 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
234 // B = 10^(-rExp - bExp) (y - M 10^rExp x)
235 // TODO(): Compare with this alternative solution from SageMathCell
236 // https://sagecell.sagemath.org/?z=eJyrtC1LLNJQr1TX5KqAMCuATF8I0xfIdIIwnYDMIteKAggPxAIKJMEFkiACxfk5Zaka0ZUKtrYKGhq-CloKFZoK2goaTkCWhqGBgpaWAkilpqYmQgBklmasjoKTJgDAECTH&lang=sage&interacts=eJyLjgUAARUAuQ==
237 double dB = std::pow(10.0, ((-rExp) - bExp)) *
238 (min - ((dM * std::pow(10.0, rExp) * lowestX)));
239
240 // Step 4: Constrain B, and set bExp accordingly
241 if (!(scaleFloatExp(dB, bExp)))
242 {
243 std::cerr << "getSensorAttributes: Offset (B=" << dB << ", bExp="
244 << (int)bExp << ") exceeds multiplier scale (M=" << dM
245 << ", rExp=" << (int)rExp << ")\n";
246 return false;
247 }
248
249 bValue = static_cast<int16_t>(std::round(dB));
250
251 normalizeIntExp(bValue, bExp, dB);
252
253 // Unlike the multiplier, it is perfectly OK for bValue to be zero
254 return true;
255 }
256
scaleIPMIValueFromDouble(const double value,const int16_t mValue,const int8_t rExp,const int16_t bValue,const int8_t bExp,const bool bSigned)257 uint8_t scaleIPMIValueFromDouble(const double value, const int16_t mValue,
258 const int8_t rExp, const int16_t bValue,
259 const int8_t bExp, const bool bSigned)
260 {
261 // Avoid division by zero below
262 if (mValue == 0)
263 {
264 throw std::out_of_range("Scaling multiplier is uninitialized");
265 }
266
267 auto dM = static_cast<double>(mValue);
268 auto dB = static_cast<double>(bValue);
269
270 // Solve the IPMI equation for x, instead of y
271 // 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
272 // x = (10^(-rExp) (y - B 10^(rExp + bExp)))/M and M 10^rExp!=0
273 // TODO(): Compare with this alternative solution from SageMathCell
274 // https://sagecell.sagemath.org/?z=eJyrtC1LLNJQr1TX5KqAMCuATF8I0xfIdIIwnYDMIteKAggPxAIKJMEFkiACxfk5Zaka0ZUKtrYKGhq-CloKFZoK2goaTkCWhqGBgpaWAkilpqYmQgBklmasDlAlAMB8JP0=&lang=sage&interacts=eJyLjgUAARUAuQ==
275 double dX =
276 (std::pow(10.0, -rExp) * (value - (dB * std::pow(10.0, rExp + bExp)))) /
277 dM;
278
279 auto scaledValue = static_cast<int32_t>(std::round(dX));
280
281 int32_t minClamp;
282 int32_t maxClamp;
283
284 // Because of rounding and integer truncation of scaling factors,
285 // sometimes the resulting byte is slightly out of range.
286 // Still allow this, but clamp the values to range.
287 if (bSigned)
288 {
289 minClamp = std::numeric_limits<int8_t>::lowest();
290 maxClamp = std::numeric_limits<int8_t>::max();
291 }
292 else
293 {
294 minClamp = std::numeric_limits<uint8_t>::lowest();
295 maxClamp = std::numeric_limits<uint8_t>::max();
296 }
297
298 auto clampedValue = std::clamp(scaledValue, minClamp, maxClamp);
299
300 // This works for both signed and unsigned,
301 // because it is the same underlying byte storage.
302 return static_cast<uint8_t>(clampedValue);
303 }
304
getScaledIPMIValue(const double value,const double max,const double min)305 uint8_t getScaledIPMIValue(const double value, const double max,
306 const double min)
307 {
308 int16_t mValue = 0;
309 int8_t rExp = 0;
310 int16_t bValue = 0;
311 int8_t bExp = 0;
312 bool bSigned = false;
313
314 bool result =
315 getSensorAttributes(max, min, mValue, rExp, bValue, bExp, bSigned);
316 if (!result)
317 {
318 throw std::runtime_error("Illegal sensor attributes");
319 }
320
321 return scaleIPMIValueFromDouble(value, mValue, rExp, bValue, bExp, bSigned);
322 }
323
324 } // namespace ipmi
325