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