blob: e448cee6aaed1720d293b802f7f862a4b25c4fd5 [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{
Josh Lehan17e21c22019-11-18 17:57:37 -080055 // Comparing with zero should be OK, zero is special in floating-point
56 // If base is exactly zero, no adjustment of the exponent is necessary
57 if (base == 0.0)
58 {
59 return true;
60 }
61
62 // As long as base value is within allowed range, expand precision
63 // This will help to avoid loss when later rounding to integer
64 while (baseInRange(base))
65 {
66 if (expShift <= minInt4)
67 {
68 // Already at the minimum expShift, can not decrement it more
69 break;
70 }
71
72 // Multiply by 10, but shift decimal point to the left, no net change
73 base *= 10.0;
74 --expShift;
75 }
76
77 // As long as base value is *not* within range, shrink precision
78 // This will pull base value closer to zero, thus within range
79 while (!(baseInRange(base)))
80 {
81 if (expShift >= maxInt4)
82 {
83 // Already at the maximum expShift, can not increment it more
84 break;
85 }
86
87 // Divide by 10, but shift decimal point to the right, no net change
88 base /= 10.0;
89 ++expShift;
90 }
91
92 // If the above loop was not able to pull it back within range,
93 // the base value is beyond what expShift can represent, return false.
94 return baseInRange(base);
95}
96
97// Helper function for internal use by getSensorAttributes()
98// Ensures integer "ibase" is no larger than necessary,
99// by normalizing it so that the decimal point shift is in the exponent,
100// whenever possible.
101// This provides more consistent results,
102// as many equivalent solutions are collapsed into one consistent solution.
103// If integer "ibase" is a clean multiple of 10,
104// divide it by 10 (this is lossless), so it is closer to zero.
105// Also modify floating-point "dbase" at the same time,
106// as both integer and floating-point base share the same expShift.
107// Example: (ibase=300, expShift=2) becomes (ibase=3, expShift=4)
108// because the underlying value is the same: 200*(10**2) == 2*(10**4)
109// Always successful, modifies values in-place
110static inline void normalizeIntExp(int16_t& ibase, int8_t& expShift,
111 double& dbase)
112{
113 for (;;)
114 {
115 // If zero, already normalized, ensure exponent also zero
116 if (ibase == 0)
117 {
118 expShift = 0;
119 break;
120 }
121
122 // If not cleanly divisible by 10, already normalized
123 if ((ibase % 10) != 0)
124 {
125 break;
126 }
127
128 // If exponent already at max, already normalized
129 if (expShift >= maxInt4)
130 {
131 break;
132 }
133
134 // Bring values closer to zero, correspondingly shift exponent,
135 // without changing the underlying number that this all represents,
136 // similar to what is done by scaleFloatExp().
137 // The floating-point base must be kept in sync with the integer base,
138 // as both floating-point and integer share the same exponent.
139 ibase /= 10;
140 dbase /= 10.0;
141 ++expShift;
142 }
143}
144
145// The IPMI equation:
146// y = (Mx + (B * 10^(bExp))) * 10^(rExp)
147// Section 36.3 of this document:
148// https://www.intel.com/content/dam/www/public/us/en/documents/product-briefs/ipmi-second-gen-interface-spec-v2-rev1-1.pdf
149//
150// The goal is to exactly match the math done by the ipmitool command,
151// at the other side of the interface:
152// https://github.com/ipmitool/ipmitool/blob/42a023ff0726c80e8cc7d30315b987fe568a981d/lib/ipmi_sdr.c#L360
153//
154// To use with Wolfram Alpha, make all variables single letters
155// bExp becomes E, rExp becomes R
156// 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 -0800157static inline bool getSensorAttributes(const double max, const double min,
158 int16_t& mValue, int8_t& rExp,
159 int16_t& bValue, int8_t& bExp,
160 bool& bSigned)
161{
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 {
Josh Lehan17e21c22019-11-18 17:57:37 -0800251 std::cerr << "getSensorAttributes: Offset (B=" << dB
252 << ", bExp=" << (int)bExp
253 << ") exceeds multiplier scale (M=" << dM
254 << ", rExp=" << (int)rExp << ")\n";
255 return false;
Jason M. Bills72867de2018-11-28 12:46:59 -0800256 }
257
Josh Lehan17e21c22019-11-18 17:57:37 -0800258 bValue = static_cast<int16_t>(std::round(dB));
Jason M. Bills72867de2018-11-28 12:46:59 -0800259
Josh Lehan17e21c22019-11-18 17:57:37 -0800260 normalizeIntExp(bValue, bExp, dB);
Jason M. Bills72867de2018-11-28 12:46:59 -0800261
Josh Lehan17e21c22019-11-18 17:57:37 -0800262 // Unlike the multiplier, it is perfectly OK for bValue to be zero
Jason M. Bills72867de2018-11-28 12:46:59 -0800263 return true;
264}
265
266static inline uint8_t
Josh Lehan17e21c22019-11-18 17:57:37 -0800267 scaleIPMIValueFromDouble(const double value, const int16_t mValue,
268 const int8_t rExp, const int16_t bValue,
Jason M. Bills72867de2018-11-28 12:46:59 -0800269 const int8_t bExp, const bool bSigned)
270{
Josh Lehan17e21c22019-11-18 17:57:37 -0800271 // Avoid division by zero below
272 if (mValue == 0)
273 {
274 throw std::out_of_range("Scaling multiplier is uninitialized");
275 }
James Feist39417c72019-01-03 09:14:24 -0800276
Josh Lehan17e21c22019-11-18 17:57:37 -0800277 auto dM = static_cast<double>(mValue);
278 auto dB = static_cast<double>(bValue);
279
280 // Solve the IPMI equation for x, instead of y
281 // 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
282 // x = (10^(-rExp) (y - B 10^(rExp + bExp)))/M and M 10^rExp!=0
283 // TODO(): Compare with this alternative solution from SageMathCell
284 // https://sagecell.sagemath.org/?z=eJyrtC1LLNJQr1TX5KqAMCuATF8I0xfIdIIwnYDMIteKAggPxAIKJMEFkiACxfk5Zaka0ZUKtrYKGhq-CloKFZoK2goaTkCWhqGBgpaWAkilpqYmQgBklmasDlAlAMB8JP0=&lang=sage&interacts=eJyLjgUAARUAuQ==
285 double dX =
286 (std::pow(10.0, -rExp) * (value - (dB * std::pow(10.0, rExp + bExp)))) /
287 dM;
288
289 auto scaledValue = static_cast<int32_t>(std::round(dX));
290
291 int32_t minClamp;
292 int32_t maxClamp;
293
294 // Because of rounding and integer truncation of scaling factors,
295 // sometimes the resulting byte is slightly out of range.
296 // Still allow this, but clamp the values to range.
Jason M. Bills72867de2018-11-28 12:46:59 -0800297 if (bSigned)
298 {
Josh Lehan17e21c22019-11-18 17:57:37 -0800299 minClamp = std::numeric_limits<int8_t>::lowest();
300 maxClamp = std::numeric_limits<int8_t>::max();
Jason M. Bills72867de2018-11-28 12:46:59 -0800301 }
302 else
303 {
Josh Lehan17e21c22019-11-18 17:57:37 -0800304 minClamp = std::numeric_limits<uint8_t>::lowest();
305 maxClamp = std::numeric_limits<uint8_t>::max();
Jason M. Bills72867de2018-11-28 12:46:59 -0800306 }
Josh Lehan17e21c22019-11-18 17:57:37 -0800307
308 auto clampedValue = std::clamp(scaledValue, minClamp, maxClamp);
309
310 // This works for both signed and unsigned,
311 // because it is the same underlying byte storage.
312 return static_cast<uint8_t>(clampedValue);
Jason M. Bills72867de2018-11-28 12:46:59 -0800313}
314
315static inline uint8_t getScaledIPMIValue(const double value, const double max,
316 const double min)
317{
318 int16_t mValue = 0;
319 int8_t rExp = 0;
320 int16_t bValue = 0;
321 int8_t bExp = 0;
Josh Lehan17e21c22019-11-18 17:57:37 -0800322 bool bSigned = false;
Jason M. Bills72867de2018-11-28 12:46:59 -0800323
Josh Lehan17e21c22019-11-18 17:57:37 -0800324 bool result =
325 getSensorAttributes(max, min, mValue, rExp, bValue, bExp, bSigned);
Jason M. Bills72867de2018-11-28 12:46:59 -0800326 if (!result)
327 {
James Feist39417c72019-01-03 09:14:24 -0800328 throw std::runtime_error("Illegal sensor attributes");
Jason M. Bills72867de2018-11-28 12:46:59 -0800329 }
Josh Lehan17e21c22019-11-18 17:57:37 -0800330
Jason M. Bills72867de2018-11-28 12:46:59 -0800331 return scaleIPMIValueFromDouble(value, mValue, rExp, bValue, bExp, bSigned);
332}
333
James Feist2a265d52019-04-08 11:16:27 -0700334} // namespace ipmi