1 /*
2  * Copyright (c)  2018 Intel Corporation.
3  * Copyright (c)  2018-present Facebook.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 
18 #pragma once
19 #include <ipmid/api.h>
20 
21 #include <phosphor-logging/log.hpp>
22 
23 #include <cmath>
24 #include <iostream>
25 
26 namespace ipmi
27 {
28 
29 static constexpr int16_t maxInt10 = 0x1FF;
30 static constexpr int16_t minInt10 = -0x200;
31 static constexpr int8_t maxInt4 = 7;
32 static constexpr int8_t minInt4 = -8;
33 
34 enum class SensorUnits : uint8_t
35 {
36     unspecified = 0x0,
37     degreesC = 0x1,
38     volts = 0x4,
39     amps = 0x5,
40     watts = 0x6,
41     rpm = 0x12,
42 };
43 
44 enum class SensorTypeCodes : uint8_t
45 {
46     reserved = 0x0,
47     temperature = 0x1,
48     voltage = 0x2,
49     current = 0x3,
50     fan = 0x4,
51     other = 0xB,
52 };
53 
54 struct CmpStrVersion
55 {
56     bool operator()(std::string a, std::string b) const
57     {
58         return strverscmp(a.c_str(), b.c_str()) < 0;
59     }
60 };
61 
62 using SensorSubTree = boost::container::flat_map<
63     std::string,
64     boost::container::flat_map<std::string, std::vector<std::string>>,
65     CmpStrVersion>;
66 
67 inline static bool getSensorSubtree(SensorSubTree& subtree)
68 {
69     sd_bus* bus = NULL;
70     int ret = sd_bus_default_system(&bus);
71     if (ret < 0)
72     {
73         phosphor::logging::log<phosphor::logging::level::ERR>(
74             "Failed to connect to system bus",
75             phosphor::logging::entry("ERRNO=0x%X", -ret));
76         sd_bus_unref(bus);
77         return false;
78     }
79     sdbusplus::bus_t dbus(bus);
80     auto mapperCall = dbus.new_method_call("xyz.openbmc_project.ObjectMapper",
81                                            "/xyz/openbmc_project/object_mapper",
82                                            "xyz.openbmc_project.ObjectMapper",
83                                            "GetSubTree");
84     static constexpr const auto depth = 2;
85     static constexpr std::array<const char*, 3> interfaces = {
86         "xyz.openbmc_project.Sensor.Value",
87         "xyz.openbmc_project.Sensor.Threshold.Warning",
88         "xyz.openbmc_project.Sensor.Threshold.Critical"};
89     mapperCall.append("/xyz/openbmc_project/sensors", depth, interfaces);
90 
91     try
92     {
93         auto mapperReply = dbus.call(mapperCall);
94         subtree.clear();
95         mapperReply.read(subtree);
96     }
97     catch (sdbusplus::exception_t& e)
98     {
99         phosphor::logging::log<phosphor::logging::level::ERR>(e.what());
100         return false;
101     }
102     return true;
103 }
104 
105 // Specify the comparison required to sort and find char* map objects
106 struct CmpStr
107 {
108     bool operator()(const char* a, const char* b) const
109     {
110         return std::strcmp(a, b) < 0;
111     }
112 };
113 
114 const static boost::container::flat_map<const char*, SensorUnits, CmpStr>
115     sensorUnits{{{"temperature", SensorUnits::degreesC},
116                  {"voltage", SensorUnits::volts},
117                  {"current", SensorUnits::amps},
118                  {"fan_tach", SensorUnits::rpm},
119                  {"power", SensorUnits::watts}}};
120 
121 const static boost::container::flat_map<const char*, SensorTypeCodes, CmpStr>
122     sensorTypes{{{"temperature", SensorTypeCodes::temperature},
123                  {"voltage", SensorTypeCodes::voltage},
124                  {"current", SensorTypeCodes::current},
125                  {"fan_tach", SensorTypeCodes::fan},
126                  {"fan_pwm", SensorTypeCodes::fan},
127                  {"power", SensorTypeCodes::other}}};
128 
129 inline static std::string getSensorTypeStringFromPath(const std::string& path)
130 {
131     // get sensor type string from path, path is defined as
132     // /xyz/openbmc_project/sensors/<type>/label
133     size_t typeEnd = path.rfind("/");
134     if (typeEnd == std::string::npos)
135     {
136         return path;
137     }
138     size_t typeStart = path.rfind("/", typeEnd - 1);
139     if (typeStart == std::string::npos)
140     {
141         return path;
142     }
143     // Start at the character after the '/'
144     typeStart++;
145     return path.substr(typeStart, typeEnd - typeStart);
146 }
147 
148 inline static uint8_t getSensorTypeFromPath(const std::string& path)
149 {
150     uint8_t sensorType = 0;
151     std::string type = getSensorTypeStringFromPath(path);
152     auto findSensor = sensorTypes.find(type.c_str());
153     if (findSensor != sensorTypes.end())
154     {
155         sensorType = static_cast<uint8_t>(findSensor->second);
156     } // else default 0x0 RESERVED
157 
158     return sensorType;
159 }
160 
161 inline static uint8_t getSensorEventTypeFromPath(const std::string&)
162 {
163     // TODO: Add support for additional reading types as needed
164     return 0x1; // reading type = threshold
165 }
166 
167 static inline bool getSensorAttributes(const double max, const double min,
168                                        int16_t& mValue, int8_t& rExp,
169                                        int16_t& bValue, int8_t& bExp,
170                                        bool& bSigned)
171 {
172     // computing y = (10^rRexp) * (Mx + (B*(10^Bexp)))
173     // check for 0, assume always positive
174     double mDouble;
175     double bDouble;
176     if (max <= min)
177     {
178         phosphor::logging::log<phosphor::logging::level::DEBUG>(
179             "getSensorAttributes: Max must be greater than min");
180         return false;
181     }
182 
183     mDouble = (max - min) / 0xFF;
184 
185     if (min < 0)
186     {
187         bSigned = true;
188         bDouble = floor(0.5 + ((max + min) / 2));
189     }
190     else
191     {
192         bSigned = false;
193         bDouble = min;
194     }
195 
196     rExp = 0;
197 
198     // M too big for 10 bit variable
199     while (mDouble > maxInt10)
200     {
201         if (rExp >= maxInt4)
202         {
203             phosphor::logging::log<phosphor::logging::level::DEBUG>(
204                 "rExp Too big, Max and Min range too far",
205                 phosphor::logging::entry("REXP=%d", rExp));
206             return false;
207         }
208         mDouble /= 10;
209         rExp++;
210     }
211 
212     // M too small, loop until we lose less than 1 eight bit count of precision
213     while (((mDouble - floor(mDouble)) / mDouble) > (1.0 / 255))
214     {
215         if (rExp <= minInt4)
216         {
217             phosphor::logging::log<phosphor::logging::level::DEBUG>(
218                 "rExp Too Small, Max and Min range too close");
219             return false;
220         }
221         // check to see if we reached the limit of where we can adjust back the
222         // B value
223         if (bDouble / std::pow(10, rExp + minInt4 - 1) > bDouble)
224         {
225             if (mDouble < 1.0)
226             {
227                 phosphor::logging::log<phosphor::logging::level::DEBUG>(
228                     "Could not find mValue and B value with enough "
229                     "precision.");
230                 return false;
231             }
232             break;
233         }
234         // can't multiply M any more, max precision reached
235         else if (mDouble * 10 > maxInt10)
236         {
237             break;
238         }
239         mDouble *= 10;
240         rExp--;
241     }
242 
243     bDouble /= std::pow(10, rExp);
244     bExp = 0;
245 
246     // B too big for 10 bit variable
247     while (bDouble > maxInt10 || bDouble < minInt10)
248     {
249         if (bExp >= maxInt4)
250         {
251             phosphor::logging::log<phosphor::logging::level::DEBUG>(
252                 "bExp Too Big, Max and Min range need to be adjusted");
253             return false;
254         }
255         bDouble /= 10;
256         bExp++;
257     }
258 
259     while (((fabs(bDouble) - floor(fabs(bDouble))) / fabs(bDouble)) >
260            (1.0 / 255))
261     {
262         if (bExp <= minInt4)
263         {
264             phosphor::logging::log<phosphor::logging::level::DEBUG>(
265                 "bExp Too Small, Max and Min range need to be adjusted");
266             return false;
267         }
268         bDouble *= 10;
269         bExp -= 1;
270     }
271 
272     mValue = static_cast<int16_t>(mDouble) & maxInt10;
273     bValue = static_cast<int16_t>(bDouble) & maxInt10;
274 
275     return true;
276 }
277 
278 static inline uint8_t
279     scaleIPMIValueFromDouble(const double value, const uint16_t mValue,
280                              const int8_t rExp, const uint16_t bValue,
281                              const int8_t bExp, const bool bSigned)
282 {
283     uint32_t scaledValue =
284         (value - (bValue * std::pow(10, bExp) * std::pow(10, rExp))) /
285         (mValue * std::pow(10, rExp));
286 
287     if (scaledValue > std::numeric_limits<uint8_t>::max() ||
288         scaledValue < std::numeric_limits<uint8_t>::lowest())
289     {
290         throw std::out_of_range("Value out of range");
291     }
292     if (bSigned)
293     {
294         return static_cast<int8_t>(scaledValue);
295     }
296     else
297     {
298         return static_cast<uint8_t>(scaledValue);
299     }
300 }
301 
302 static inline uint8_t getScaledIPMIValue(const double value, const double max,
303                                          const double min)
304 {
305     int16_t mValue = 0;
306     int8_t rExp = 0;
307     int16_t bValue = 0;
308     int8_t bExp = 0;
309     bool bSigned = 0;
310     bool result = 0;
311 
312     result = getSensorAttributes(max, min, mValue, rExp, bValue, bExp, bSigned);
313     if (!result)
314     {
315         throw std::runtime_error("Illegal sensor attributes");
316     }
317     return scaleIPMIValueFromDouble(value, mValue, rExp, bValue, bExp, bSigned);
318 }
319 } // namespace ipmi
320