blob: c7ce53ee70edfca8b3c8de6bc64b865a7e4afc04 [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
Jason M. Bills72867de2018-11-28 12:46:59 -0800158static inline bool getSensorAttributes(const double max, const double min,
159 int16_t& mValue, int8_t& rExp,
160 int16_t& bValue, int8_t& bExp,
161 bool& bSigned)
162{
Josh Lehan17e21c22019-11-18 17:57:37 -0800163 if (!(std::isfinite(min)))
164 {
165 std::cerr << "getSensorAttributes: Min value is unusable\n";
166 return false;
167 }
168 if (!(std::isfinite(max)))
169 {
170 std::cerr << "getSensorAttributes: Max value is unusable\n";
171 return false;
172 }
173
174 // Because NAN has already been tested for, this comparison works
James Feist39417c72019-01-03 09:14:24 -0800175 if (max <= min)
Jason M. Bills72867de2018-11-28 12:46:59 -0800176 {
Vernon Mauery53870d72019-06-04 14:21:10 -0700177 std::cerr << "getSensorAttributes: Max must be greater than min\n";
Jason M. Bills72867de2018-11-28 12:46:59 -0800178 return false;
179 }
James Feist39417c72019-01-03 09:14:24 -0800180
Josh Lehan17e21c22019-11-18 17:57:37 -0800181 // Given min and max, we must solve for M, B, bExp, rExp
182 // y comes in from D-Bus (the actual sensor reading)
183 // x is calculated from y by scaleIPMIValueFromDouble() below
184 // If y is min, x should equal = 0 (or -128 if signed)
185 // If y is max, x should equal 255 (or 127 if signed)
186 double fullRange = max - min;
187 double lowestX;
Jason M. Bills72867de2018-11-28 12:46:59 -0800188
Josh Lehan17e21c22019-11-18 17:57:37 -0800189 rExp = 0;
190 bExp = 0;
191
192 // TODO(): The IPMI document is ambiguous, as to whether
193 // the resulting byte should be signed or unsigned,
194 // essentially leaving it up to the caller.
195 // The document just refers to it as "raw reading",
196 // or "byte of reading", without giving further details.
197 // Previous code set it signed if min was less than zero,
198 // so I'm sticking with that, until I learn otherwise.
199 if (min < 0.0)
Jason M. Bills72867de2018-11-28 12:46:59 -0800200 {
Josh Lehan17e21c22019-11-18 17:57:37 -0800201 // TODO(): It would be worth experimenting with the range (-127,127),
202 // instead of the range (-128,127), because this
203 // would give good symmetry around zero, and make results look better.
204 // Divide by 254 instead of 255, and change -128 to -127 elsewhere.
Jason M. Bills72867de2018-11-28 12:46:59 -0800205 bSigned = true;
Josh Lehan17e21c22019-11-18 17:57:37 -0800206 lowestX = -128.0;
Jason M. Bills72867de2018-11-28 12:46:59 -0800207 }
208 else
209 {
210 bSigned = false;
Josh Lehan17e21c22019-11-18 17:57:37 -0800211 lowestX = 0.0;
Jason M. Bills72867de2018-11-28 12:46:59 -0800212 }
213
Josh Lehan17e21c22019-11-18 17:57:37 -0800214 // Step 1: Set y to (max - min), set x to 255, set B to 0, solve for M
215 // This works, regardless of signed or unsigned,
216 // because total range is the same.
217 double dM = fullRange / 255.0;
Jason M. Bills72867de2018-11-28 12:46:59 -0800218
Josh Lehan17e21c22019-11-18 17:57:37 -0800219 // Step 2: Constrain M, and set rExp accordingly
220 if (!(scaleFloatExp(dM, rExp)))
Jason M. Bills72867de2018-11-28 12:46:59 -0800221 {
Josh Lehan17e21c22019-11-18 17:57:37 -0800222 std::cerr << "getSensorAttributes: Multiplier range exceeds scale (M="
223 << dM << ", rExp=" << (int)rExp << ")\n";
224 return false;
Jason M. Bills72867de2018-11-28 12:46:59 -0800225 }
226
Josh Lehan17e21c22019-11-18 17:57:37 -0800227 mValue = static_cast<int16_t>(std::round(dM));
228
229 normalizeIntExp(mValue, rExp, dM);
230
231 // The multiplier can not be zero, for obvious reasons
232 if (mValue == 0)
Jason M. Bills72867de2018-11-28 12:46:59 -0800233 {
Josh Lehan17e21c22019-11-18 17:57:37 -0800234 std::cerr << "getSensorAttributes: Multiplier range below scale\n";
235 return false;
Jason M. Bills72867de2018-11-28 12:46:59 -0800236 }
237
Josh Lehan17e21c22019-11-18 17:57:37 -0800238 // Step 3: set y to min, set x to min, keep M and rExp, solve for B
239 // If negative, x will be -128 (the most negative possible byte), not 0
Jason M. Bills72867de2018-11-28 12:46:59 -0800240
Josh Lehan17e21c22019-11-18 17:57:37 -0800241 // Solve the IPMI equation for B, instead of y
242 // 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
243 // B = 10^(-rExp - bExp) (y - M 10^rExp x)
244 // TODO(): Compare with this alternative solution from SageMathCell
245 // https://sagecell.sagemath.org/?z=eJyrtC1LLNJQr1TX5KqAMCuATF8I0xfIdIIwnYDMIteKAggPxAIKJMEFkiACxfk5Zaka0ZUKtrYKGhq-CloKFZoK2goaTkCWhqGBgpaWAkilpqYmQgBklmasjoKTJgDAECTH&lang=sage&interacts=eJyLjgUAARUAuQ==
246 double dB = std::pow(10.0, ((-rExp) - bExp)) *
247 (min - ((dM * std::pow(10.0, rExp) * lowestX)));
248
249 // Step 4: Constrain B, and set bExp accordingly
250 if (!(scaleFloatExp(dB, bExp)))
Jason M. Bills72867de2018-11-28 12:46:59 -0800251 {
Josh Lehan17e21c22019-11-18 17:57:37 -0800252 std::cerr << "getSensorAttributes: Offset (B=" << dB
253 << ", bExp=" << (int)bExp
254 << ") exceeds multiplier scale (M=" << dM
255 << ", rExp=" << (int)rExp << ")\n";
256 return false;
Jason M. Bills72867de2018-11-28 12:46:59 -0800257 }
258
Josh Lehan17e21c22019-11-18 17:57:37 -0800259 bValue = static_cast<int16_t>(std::round(dB));
Jason M. Bills72867de2018-11-28 12:46:59 -0800260
Josh Lehan17e21c22019-11-18 17:57:37 -0800261 normalizeIntExp(bValue, bExp, dB);
Jason M. Bills72867de2018-11-28 12:46:59 -0800262
Josh Lehan17e21c22019-11-18 17:57:37 -0800263 // Unlike the multiplier, it is perfectly OK for bValue to be zero
Jason M. Bills72867de2018-11-28 12:46:59 -0800264 return true;
265}
266
267static inline uint8_t
Josh Lehan17e21c22019-11-18 17:57:37 -0800268 scaleIPMIValueFromDouble(const double value, const int16_t mValue,
269 const int8_t rExp, const int16_t bValue,
Jason M. Bills72867de2018-11-28 12:46:59 -0800270 const int8_t bExp, const bool bSigned)
271{
Josh Lehan17e21c22019-11-18 17:57:37 -0800272 // Avoid division by zero below
273 if (mValue == 0)
274 {
275 throw std::out_of_range("Scaling multiplier is uninitialized");
276 }
James Feist39417c72019-01-03 09:14:24 -0800277
Josh Lehan17e21c22019-11-18 17:57:37 -0800278 auto dM = static_cast<double>(mValue);
279 auto dB = static_cast<double>(bValue);
280
281 // Solve the IPMI equation for x, instead of y
282 // 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
283 // x = (10^(-rExp) (y - B 10^(rExp + bExp)))/M and M 10^rExp!=0
284 // TODO(): Compare with this alternative solution from SageMathCell
285 // https://sagecell.sagemath.org/?z=eJyrtC1LLNJQr1TX5KqAMCuATF8I0xfIdIIwnYDMIteKAggPxAIKJMEFkiACxfk5Zaka0ZUKtrYKGhq-CloKFZoK2goaTkCWhqGBgpaWAkilpqYmQgBklmasDlAlAMB8JP0=&lang=sage&interacts=eJyLjgUAARUAuQ==
286 double dX =
287 (std::pow(10.0, -rExp) * (value - (dB * std::pow(10.0, rExp + bExp)))) /
288 dM;
289
290 auto scaledValue = static_cast<int32_t>(std::round(dX));
291
292 int32_t minClamp;
293 int32_t maxClamp;
294
295 // Because of rounding and integer truncation of scaling factors,
296 // sometimes the resulting byte is slightly out of range.
297 // Still allow this, but clamp the values to range.
Jason M. Bills72867de2018-11-28 12:46:59 -0800298 if (bSigned)
299 {
Josh Lehan17e21c22019-11-18 17:57:37 -0800300 minClamp = std::numeric_limits<int8_t>::lowest();
301 maxClamp = std::numeric_limits<int8_t>::max();
Jason M. Bills72867de2018-11-28 12:46:59 -0800302 }
303 else
304 {
Josh Lehan17e21c22019-11-18 17:57:37 -0800305 minClamp = std::numeric_limits<uint8_t>::lowest();
306 maxClamp = std::numeric_limits<uint8_t>::max();
Jason M. Bills72867de2018-11-28 12:46:59 -0800307 }
Josh Lehan17e21c22019-11-18 17:57:37 -0800308
309 auto clampedValue = std::clamp(scaledValue, minClamp, maxClamp);
310
311 // This works for both signed and unsigned,
312 // because it is the same underlying byte storage.
313 return static_cast<uint8_t>(clampedValue);
Jason M. Bills72867de2018-11-28 12:46:59 -0800314}
315
316static inline uint8_t getScaledIPMIValue(const double value, const double max,
317 const double min)
318{
319 int16_t mValue = 0;
320 int8_t rExp = 0;
321 int16_t bValue = 0;
322 int8_t bExp = 0;
Josh Lehan17e21c22019-11-18 17:57:37 -0800323 bool bSigned = false;
Jason M. Bills72867de2018-11-28 12:46:59 -0800324
Patrick Williamsb37abfb2023-05-10 07:50:33 -0500325 bool result = getSensorAttributes(max, min, mValue, rExp, bValue, bExp,
326 bSigned);
Jason M. Bills72867de2018-11-28 12:46:59 -0800327 if (!result)
328 {
James Feist39417c72019-01-03 09:14:24 -0800329 throw std::runtime_error("Illegal sensor attributes");
Jason M. Bills72867de2018-11-28 12:46:59 -0800330 }
Josh Lehan17e21c22019-11-18 17:57:37 -0800331
Jason M. Bills72867de2018-11-28 12:46:59 -0800332 return scaleIPMIValueFromDouble(value, mValue, rExp, bValue, bExp, bSigned);
333}
334
James Feist2a265d52019-04-08 11:16:27 -0700335} // namespace ipmi