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 #pragma once
18 #include <algorithm>
19 #include <cmath>
20 #include <cstdint>
21 #include <iostream>
22
23 namespace ipmi
24 {
25 static constexpr int16_t maxInt10 = 0x1FF;
26 static constexpr int16_t minInt10 = -0x200;
27 static constexpr int8_t maxInt4 = 7;
28 static constexpr int8_t minInt4 = -8;
29
30 // 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.
baseInRange(double base)34 static 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
scaleFloatExp(double & base,int8_t & expShift)54 static inline bool scaleFloatExp(double& base, int8_t& expShift)
55 {
56 // 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
normalizeIntExp(int16_t & ibase,int8_t & expShift,double & dbase)111 static 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
getSensorAttributes(const double max,const double min,int16_t & mValue,int8_t & rExp,int16_t & bValue,int8_t & bExp,bool & bSigned)158 static 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)
161 {
162 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
174 if (max <= min)
175 {
176 std::cerr << "getSensorAttributes: Max must be greater than min\n";
177 return false;
178 }
179
180 // 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;
187
188 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)
199 {
200 // 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.
204 bSigned = true;
205 lowestX = -128.0;
206 }
207 else
208 {
209 bSigned = false;
210 lowestX = 0.0;
211 }
212
213 // 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;
217
218 // Step 2: Constrain M, and set rExp accordingly
219 if (!(scaleFloatExp(dM, rExp)))
220 {
221 std::cerr << "getSensorAttributes: Multiplier range exceeds scale (M="
222 << dM << ", rExp=" << (int)rExp << ")\n";
223 return false;
224 }
225
226 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)
232 {
233 std::cerr << "getSensorAttributes: Multiplier range below scale\n";
234 return false;
235 }
236
237 // 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
239
240 // 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)))
250 {
251 std::cerr << "getSensorAttributes: Offset (B=" << dB << ", bExp="
252 << (int)bExp << ") exceeds multiplier scale (M=" << dM
253 << ", rExp=" << (int)rExp << ")\n";
254 return false;
255 }
256
257 bValue = static_cast<int16_t>(std::round(dB));
258
259 normalizeIntExp(bValue, bExp, dB);
260
261 // Unlike the multiplier, it is perfectly OK for bValue to be zero
262 return true;
263 }
264
scaleIPMIValueFromDouble(const double value,const int16_t mValue,const int8_t rExp,const int16_t bValue,const int8_t bExp,const bool bSigned)265 static 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)
268 {
269 // Avoid division by zero below
270 if (mValue == 0)
271 {
272 throw std::out_of_range("Scaling multiplier is uninitialized");
273 }
274
275 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.
295 if (bSigned)
296 {
297 minClamp = std::numeric_limits<int8_t>::lowest();
298 maxClamp = std::numeric_limits<int8_t>::max();
299 }
300 else
301 {
302 minClamp = std::numeric_limits<uint8_t>::lowest();
303 maxClamp = std::numeric_limits<uint8_t>::max();
304 }
305
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);
311 }
312
getScaledIPMIValue(const double value,const double max,const double min)313 static 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;
320 bool bSigned = false;
321
322 bool result =
323 getSensorAttributes(max, min, mValue, rExp, bValue, bExp, bSigned);
324 if (!result)
325 {
326 throw std::runtime_error("Illegal sensor attributes");
327 }
328
329 return scaleIPMIValueFromDouble(value, mValue, rExp, bValue, bExp, bSigned);
330 }
331
332 } // namespace ipmi
333