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