19cf85627SBrandon Kim #include "config.h"
29cf85627SBrandon Kim 
346470a38SPatrick Venture #include "sensorhandler.hpp"
40b02be92SPatrick Venture 
50b02be92SPatrick Venture #include "fruread.hpp"
60b02be92SPatrick Venture 
798a23840SMatthew Barth #include <systemd/sd-bus.h>
80b02be92SPatrick Venture 
9e08fbffcSVernon Mauery #include <ipmid/api.hpp>
109cf0838aSVernon Mauery #include <ipmid/entity_map_json.hpp>
1133250240SVernon Mauery #include <ipmid/types.hpp>
126a98fe7fSVernon Mauery #include <ipmid/utils.hpp>
1318e99992SDhruvaraj Subhashchandran #include <phosphor-logging/elog-errors.hpp>
140b02be92SPatrick Venture #include <phosphor-logging/log.hpp>
154c008028SWilliam A. Kennington III #include <sdbusplus/message/types.hpp>
160b02be92SPatrick Venture #include <xyz/openbmc_project/Common/error.hpp>
170b02be92SPatrick Venture #include <xyz/openbmc_project/Sensor/Value/server.hpp>
180b02be92SPatrick Venture 
19fbc6c9d7SPatrick Williams #include <bitset>
20fbc6c9d7SPatrick Williams #include <cmath>
21fbc6c9d7SPatrick Williams #include <cstring>
22fbc6c9d7SPatrick Williams #include <set>
23fbc6c9d7SPatrick Williams 
24e0cc8553SRatan Gupta static constexpr uint8_t fruInventoryDevice = 0x10;
25e0cc8553SRatan Gupta static constexpr uint8_t IPMIFruInventory = 0x02;
2668d9d405SMatt Simmering static constexpr uint8_t BMCTargetAddress = 0x20;
27e0cc8553SRatan Gupta 
2898a23840SMatthew Barth extern int updateSensorRecordFromSSRAESC(const void*);
29d700e76aSTom extern sd_bus* bus;
30db0cbe64SPatrick Venture 
31db0cbe64SPatrick Venture namespace ipmi
32db0cbe64SPatrick Venture {
33db0cbe64SPatrick Venture namespace sensor
34db0cbe64SPatrick Venture {
35db0cbe64SPatrick Venture extern const IdInfoMap sensors;
36db0cbe64SPatrick Venture } // namespace sensor
37db0cbe64SPatrick Venture } // namespace ipmi
38db0cbe64SPatrick Venture 
39e0cc8553SRatan Gupta extern const FruMap frus;
40e0cc8553SRatan Gupta 
41be703f71STom Joseph using namespace phosphor::logging;
4218e99992SDhruvaraj Subhashchandran using InternalFailure =
43523e2d1bSWilly Tu     sdbusplus::error::xyz::openbmc_project::common::InternalFailure;
4498a23840SMatthew Barth 
4598a23840SMatthew Barth void register_netfn_sen_functions() __attribute__((constructor));
4698a23840SMatthew Barth 
470b02be92SPatrick Venture struct sensorTypemap_t
480b02be92SPatrick Venture {
4998a23840SMatthew Barth     uint8_t number;
5098a23840SMatthew Barth     uint8_t typecode;
5198a23840SMatthew Barth     char dbusname[32];
5298a23840SMatthew Barth };
5398a23840SMatthew Barth 
5498a23840SMatthew Barth sensorTypemap_t g_SensorTypeMap[] = {
5598a23840SMatthew Barth 
5698a23840SMatthew Barth     {0x01, 0x6F, "Temp"},
5798a23840SMatthew Barth     {0x0C, 0x6F, "DIMM"},
5898a23840SMatthew Barth     {0x0C, 0x6F, "MEMORY_BUFFER"},
5998a23840SMatthew Barth     {0x07, 0x6F, "PROC"},
6098a23840SMatthew Barth     {0x07, 0x6F, "CORE"},
6198a23840SMatthew Barth     {0x07, 0x6F, "CPU"},
6298a23840SMatthew Barth     {0x0F, 0x6F, "BootProgress"},
630b02be92SPatrick Venture     {0xe9, 0x09, "OccStatus"}, // E9 is an internal mapping to handle sensor
640b02be92SPatrick Venture                                // type code os 0x09
6598a23840SMatthew Barth     {0xC3, 0x6F, "BootCount"},
6698a23840SMatthew Barth     {0x1F, 0x6F, "OperatingSystemStatus"},
6798a23840SMatthew Barth     {0x12, 0x6F, "SYSTEM_EVENT"},
6898a23840SMatthew Barth     {0xC7, 0x03, "SYSTEM"},
6998a23840SMatthew Barth     {0xC7, 0x03, "MAIN_PLANAR"},
7098a23840SMatthew Barth     {0xC2, 0x6F, "PowerCap"},
71558184eaSTom Joseph     {0x0b, 0xCA, "PowerSupplyRedundancy"},
720661beb1SJayanth Othayoth     {0xDA, 0x03, "TurboAllowed"},
73558184eaSTom Joseph     {0xD8, 0xC8, "PowerSupplyDerating"},
7498a23840SMatthew Barth     {0xFF, 0x00, ""},
7598a23840SMatthew Barth };
7698a23840SMatthew Barth 
770b02be92SPatrick Venture struct sensor_data_t
780b02be92SPatrick Venture {
7998a23840SMatthew Barth     uint8_t sennum;
8098a23840SMatthew Barth } __attribute__((packed));
8198a23840SMatthew Barth 
8214a47819SLei YU using SDRCacheMap = std::unordered_map<uint8_t, get_sdr::SensorDataFullRecord>;
8314a47819SLei YU SDRCacheMap sdrCacheMap __attribute__((init_priority(101)));
8414a47819SLei YU 
8514a47819SLei YU using SensorThresholdMap =
8614a47819SLei YU     std::unordered_map<uint8_t, get_sdr::GetSensorThresholdsResponse>;
8714a47819SLei YU SensorThresholdMap sensorThresholdMap __attribute__((init_priority(101)));
8814a47819SLei YU 
89962e68baSLei YU #ifdef FEATURE_SENSORS_CACHE
905d82f474SPatrick Williams std::map<uint8_t, std::unique_ptr<sdbusplus::bus::match_t>> sensorAddedMatches
915d82f474SPatrick Williams     __attribute__((init_priority(101)));
925d82f474SPatrick Williams std::map<uint8_t, std::unique_ptr<sdbusplus::bus::match_t>> sensorUpdatedMatches
935d82f474SPatrick Williams     __attribute__((init_priority(101)));
945d82f474SPatrick Williams std::map<uint8_t, std::unique_ptr<sdbusplus::bus::match_t>> sensorRemovedMatches
955d82f474SPatrick Williams     __attribute__((init_priority(101)));
965d82f474SPatrick Williams std::unique_ptr<sdbusplus::bus::match_t> sensorsOwnerMatch
977f3a70f0SLei YU     __attribute__((init_priority(101)));
98be5c6b2aSLei YU 
999714050fSLei YU ipmi::sensor::SensorCacheMap sensorCacheMap __attribute__((init_priority(101)));
1008c2c048eSLei YU 
1017f3a70f0SLei YU // It is needed to know which objects belong to which service, so that when a
1027f3a70f0SLei YU // service exits without interfacesRemoved signal, we could invaildate the cache
1037f3a70f0SLei YU // that is related to the service. It uses below two variables:
1047f3a70f0SLei YU // - idToServiceMap records which sensors are known to have a related service;
1057f3a70f0SLei YU // - serviceToIdMap maps a service to the sensors.
1067f3a70f0SLei YU using sensorIdToServiceMap = std::unordered_map<uint8_t, std::string>;
1077f3a70f0SLei YU sensorIdToServiceMap idToServiceMap __attribute__((init_priority(101)));
1087f3a70f0SLei YU 
1097f3a70f0SLei YU using sensorServiceToIdMap = std::unordered_map<std::string, std::set<uint8_t>>;
1107f3a70f0SLei YU sensorServiceToIdMap serviceToIdMap __attribute__((init_priority(101)));
1117f3a70f0SLei YU 
fillSensorIdServiceMap(const std::string &,const std::string &,uint8_t id,const std::string & service)11211d68897SWilly Tu static void fillSensorIdServiceMap(const std::string&,
1137f3a70f0SLei YU                                    const std::string& /*intf*/, uint8_t id,
1147f3a70f0SLei YU                                    const std::string& service)
1157f3a70f0SLei YU {
1167f3a70f0SLei YU     if (idToServiceMap.find(id) != idToServiceMap.end())
1177f3a70f0SLei YU     {
1187f3a70f0SLei YU         return;
1197f3a70f0SLei YU     }
1207f3a70f0SLei YU     idToServiceMap[id] = service;
1217f3a70f0SLei YU     serviceToIdMap[service].insert(id);
1227f3a70f0SLei YU }
1237f3a70f0SLei YU 
fillSensorIdServiceMap(const std::string & obj,const std::string & intf,uint8_t id)1247f3a70f0SLei YU static void fillSensorIdServiceMap(const std::string& obj,
1257f3a70f0SLei YU                                    const std::string& intf, uint8_t id)
1267f3a70f0SLei YU {
1277f3a70f0SLei YU     if (idToServiceMap.find(id) != idToServiceMap.end())
1287f3a70f0SLei YU     {
1297f3a70f0SLei YU         return;
1307f3a70f0SLei YU     }
1317f3a70f0SLei YU     try
1327f3a70f0SLei YU     {
1335d82f474SPatrick Williams         sdbusplus::bus_t bus{ipmid_get_sd_bus_connection()};
1347f3a70f0SLei YU         auto service = ipmi::getService(bus, intf, obj);
1357f3a70f0SLei YU         idToServiceMap[id] = service;
1367f3a70f0SLei YU         serviceToIdMap[service].insert(id);
1377f3a70f0SLei YU     }
1387f3a70f0SLei YU     catch (...)
1397f3a70f0SLei YU     {
1407f3a70f0SLei YU         // Ignore
1417f3a70f0SLei YU     }
1427f3a70f0SLei YU }
1437f3a70f0SLei YU 
initSensorMatches()144be5c6b2aSLei YU void initSensorMatches()
145be5c6b2aSLei YU {
146be5c6b2aSLei YU     using namespace sdbusplus::bus::match::rules;
1475d82f474SPatrick Williams     sdbusplus::bus_t bus{ipmid_get_sd_bus_connection()};
148be5c6b2aSLei YU     for (const auto& s : ipmi::sensor::sensors)
149be5c6b2aSLei YU     {
150be5c6b2aSLei YU         sensorAddedMatches.emplace(
151be5c6b2aSLei YU             s.first,
1525d82f474SPatrick Williams             std::make_unique<sdbusplus::bus::match_t>(
153be5c6b2aSLei YU                 bus, interfacesAdded() + argNpath(0, s.second.sensorPath),
1547f3a70f0SLei YU                 [id = s.first, obj = s.second.sensorPath,
1557f3a70f0SLei YU                  intf = s.second.propertyInterfaces.begin()->first](
1567f3a70f0SLei YU                     auto& /*msg*/) { fillSensorIdServiceMap(obj, intf, id); }));
1577f3a70f0SLei YU         sensorRemovedMatches.emplace(
1587f3a70f0SLei YU             s.first,
1595d82f474SPatrick Williams             std::make_unique<sdbusplus::bus::match_t>(
1607f3a70f0SLei YU                 bus, interfacesRemoved() + argNpath(0, s.second.sensorPath),
1617f3a70f0SLei YU                 [id = s.first](auto& /*msg*/) {
1627f3a70f0SLei YU             // Ideally this should work.
1637f3a70f0SLei YU             // But when a service is terminated or crashed, it does not
1647f3a70f0SLei YU             // emit interfacesRemoved signal. In that case it's handled
1657f3a70f0SLei YU             // by sensorsOwnerMatch
1667f3a70f0SLei YU             sensorCacheMap[id].reset();
167be5c6b2aSLei YU         }));
168be5c6b2aSLei YU         sensorUpdatedMatches.emplace(
1695d82f474SPatrick Williams             s.first, std::make_unique<sdbusplus::bus::match_t>(
170be5c6b2aSLei YU                          bus,
171be5c6b2aSLei YU                          type::signal() + path(s.second.sensorPath) +
172be5c6b2aSLei YU                              member("PropertiesChanged"s) +
173be5c6b2aSLei YU                              interface("org.freedesktop.DBus.Properties"s),
1749714050fSLei YU                          [&s](auto& msg) {
175fbc6c9d7SPatrick Williams             fillSensorIdServiceMap(s.second.sensorPath,
1767f3a70f0SLei YU                                    s.second.propertyInterfaces.begin()->first,
1777f3a70f0SLei YU                                    s.first);
1789714050fSLei YU             try
1799714050fSLei YU             {
1808e8152c5SLei YU                 // This is signal callback
1818e8152c5SLei YU                 std::string interfaceName;
1828e8152c5SLei YU                 msg.read(interfaceName);
1838e8152c5SLei YU                 ipmi::PropertyMap props;
1848e8152c5SLei YU                 msg.read(props);
1858e8152c5SLei YU                 s.second.getFunc(s.first, s.second, props);
1869714050fSLei YU             }
1879714050fSLei YU             catch (const std::exception& e)
1889714050fSLei YU             {
1899714050fSLei YU                 sensorCacheMap[s.first].reset();
1909714050fSLei YU             }
191be5c6b2aSLei YU         }));
1924a105cd6SJian Zhang     }
1935d82f474SPatrick Williams     sensorsOwnerMatch = std::make_unique<sdbusplus::bus::match_t>(
1947f3a70f0SLei YU         bus, nameOwnerChanged(), [](auto& msg) {
1957f3a70f0SLei YU         std::string name;
1967f3a70f0SLei YU         std::string oldOwner;
1977f3a70f0SLei YU         std::string newOwner;
1987f3a70f0SLei YU         msg.read(name, oldOwner, newOwner);
1997f3a70f0SLei YU 
2007f3a70f0SLei YU         if (!name.empty() && newOwner.empty())
2017f3a70f0SLei YU         {
2027f3a70f0SLei YU             // The service exits
2037f3a70f0SLei YU             const auto it = serviceToIdMap.find(name);
2047f3a70f0SLei YU             if (it == serviceToIdMap.end())
2057f3a70f0SLei YU             {
2067f3a70f0SLei YU                 return;
2077f3a70f0SLei YU             }
2087f3a70f0SLei YU             for (const auto& id : it->second)
2097f3a70f0SLei YU             {
2107f3a70f0SLei YU                 // Invalidate cache
2117f3a70f0SLei YU                 sensorCacheMap[id].reset();
2127f3a70f0SLei YU             }
2137f3a70f0SLei YU         }
2147f3a70f0SLei YU     });
215be5c6b2aSLei YU }
216962e68baSLei YU #endif
217be5c6b2aSLei YU 
2182ae09b9aSEmily Shaffer // Use a lookup table to find the interface name of a specific sensor
2192ae09b9aSEmily Shaffer // This will be used until an alternative is found.  this is the first
2202ae09b9aSEmily Shaffer // step for mapping IPMI
find_openbmc_path(uint8_t num,dbus_interface_t * interface)2210b02be92SPatrick Venture int find_openbmc_path(uint8_t num, dbus_interface_t* interface)
2220b02be92SPatrick Venture {
223db0cbe64SPatrick Venture     const auto& sensor_it = ipmi::sensor::sensors.find(num);
224db0cbe64SPatrick Venture     if (sensor_it == ipmi::sensor::sensors.end())
2252ae09b9aSEmily Shaffer     {
226ba23ff71SAdriana Kobylak         // The sensor map does not contain the sensor requested
227ba23ff71SAdriana Kobylak         return -EINVAL;
2282ae09b9aSEmily Shaffer     }
2292ae09b9aSEmily Shaffer 
2302ae09b9aSEmily Shaffer     const auto& info = sensor_it->second;
2312ae09b9aSEmily Shaffer 
232*a008871dSGeorge Liu     std::string serviceName{};
233*a008871dSGeorge Liu     try
234*a008871dSGeorge Liu     {
235*a008871dSGeorge Liu         sdbusplus::bus_t bus{ipmid_get_sd_bus_connection()};
236*a008871dSGeorge Liu         serviceName = ipmi::getService(bus, info.sensorInterface,
237*a008871dSGeorge Liu                                        info.sensorPath);
238*a008871dSGeorge Liu     }
239*a008871dSGeorge Liu     catch (const sdbusplus::exception_t&)
2400b02be92SPatrick Venture     {
241b51bf9c8SPatrick Venture         std::fprintf(stderr, "Failed to get %s busname: %s\n",
242*a008871dSGeorge Liu                      info.sensorPath.c_str(), serviceName.c_str());
243*a008871dSGeorge Liu         return -EINVAL;
2442ae09b9aSEmily Shaffer     }
2452ae09b9aSEmily Shaffer 
2462ae09b9aSEmily Shaffer     interface->sensortype = info.sensorType;
247*a008871dSGeorge Liu     strcpy(interface->bus, serviceName.c_str());
2482ae09b9aSEmily Shaffer     strcpy(interface->path, info.sensorPath.c_str());
2492ae09b9aSEmily Shaffer     // Take the interface name from the beginning of the DbusInterfaceMap. This
2502ae09b9aSEmily Shaffer     // works for the Value interface but may not suffice for more complex
2512ae09b9aSEmily Shaffer     // sensors.
2522ae09b9aSEmily Shaffer     // tracked https://github.com/openbmc/phosphor-host-ipmid/issues/103
2530b02be92SPatrick Venture     strcpy(interface->interface,
2540b02be92SPatrick Venture            info.propertyInterfaces.begin()->first.c_str());
2552ae09b9aSEmily Shaffer     interface->sensornumber = num;
2562ae09b9aSEmily Shaffer 
257*a008871dSGeorge Liu     return 0;
2582ae09b9aSEmily Shaffer }
2592ae09b9aSEmily Shaffer 
260d700e76aSTom /////////////////////////////////////////////////////////////////////
261d700e76aSTom //
262d700e76aSTom // Routines used by ipmi commands wanting to interact on the dbus
263d700e76aSTom //
264d700e76aSTom /////////////////////////////////////////////////////////////////////
set_sensor_dbus_state_s(uint8_t number,const char * method,const char * value)2650b02be92SPatrick Venture int set_sensor_dbus_state_s(uint8_t number, const char* method,
2660b02be92SPatrick Venture                             const char* value)
2670b02be92SPatrick Venture {
268d700e76aSTom     dbus_interface_t a;
269d700e76aSTom     int r;
270d700e76aSTom     sd_bus_error error = SD_BUS_ERROR_NULL;
271d700e76aSTom     sd_bus_message* m = NULL;
272d700e76aSTom 
2732ae09b9aSEmily Shaffer     r = find_openbmc_path(number, &a);
274d700e76aSTom 
2750b02be92SPatrick Venture     if (r < 0)
2760b02be92SPatrick Venture     {
277b51bf9c8SPatrick Venture         std::fprintf(stderr, "Failed to find Sensor 0x%02x\n", number);
278d700e76aSTom         return 0;
279d700e76aSTom     }
280d700e76aSTom 
2810b02be92SPatrick Venture     r = sd_bus_message_new_method_call(bus, &m, a.bus, a.path, a.interface,
2820b02be92SPatrick Venture                                        method);
2830b02be92SPatrick Venture     if (r < 0)
2840b02be92SPatrick Venture     {
285b51bf9c8SPatrick Venture         std::fprintf(stderr, "Failed to create a method call: %s",
286b51bf9c8SPatrick Venture                      strerror(-r));
287d700e76aSTom         goto final;
288d700e76aSTom     }
289d700e76aSTom 
290d700e76aSTom     r = sd_bus_message_append(m, "v", "s", value);
2910b02be92SPatrick Venture     if (r < 0)
2920b02be92SPatrick Venture     {
293b51bf9c8SPatrick Venture         std::fprintf(stderr, "Failed to create a input parameter: %s",
294b51bf9c8SPatrick Venture                      strerror(-r));
295d700e76aSTom         goto final;
296d700e76aSTom     }
297d700e76aSTom 
298d700e76aSTom     r = sd_bus_call(bus, m, 0, &error, NULL);
2990b02be92SPatrick Venture     if (r < 0)
3000b02be92SPatrick Venture     {
301b51bf9c8SPatrick Venture         std::fprintf(stderr, "Failed to call the method: %s", strerror(-r));
302d700e76aSTom     }
303d700e76aSTom 
304d700e76aSTom final:
305d700e76aSTom     sd_bus_error_free(&error);
306d700e76aSTom     m = sd_bus_message_unref(m);
307d700e76aSTom 
308d700e76aSTom     return 0;
309d700e76aSTom }
set_sensor_dbus_state_y(uint8_t number,const char * method,const uint8_t value)3100b02be92SPatrick Venture int set_sensor_dbus_state_y(uint8_t number, const char* method,
3110b02be92SPatrick Venture                             const uint8_t value)
3120b02be92SPatrick Venture {
313d700e76aSTom     dbus_interface_t a;
314d700e76aSTom     int r;
315d700e76aSTom     sd_bus_error error = SD_BUS_ERROR_NULL;
316d700e76aSTom     sd_bus_message* m = NULL;
317d700e76aSTom 
3182ae09b9aSEmily Shaffer     r = find_openbmc_path(number, &a);
319d700e76aSTom 
3200b02be92SPatrick Venture     if (r < 0)
3210b02be92SPatrick Venture     {
322b51bf9c8SPatrick Venture         std::fprintf(stderr, "Failed to find Sensor 0x%02x\n", number);
323d700e76aSTom         return 0;
324d700e76aSTom     }
325d700e76aSTom 
3260b02be92SPatrick Venture     r = sd_bus_message_new_method_call(bus, &m, a.bus, a.path, a.interface,
3270b02be92SPatrick Venture                                        method);
3280b02be92SPatrick Venture     if (r < 0)
3290b02be92SPatrick Venture     {
330b51bf9c8SPatrick Venture         std::fprintf(stderr, "Failed to create a method call: %s",
331b51bf9c8SPatrick Venture                      strerror(-r));
332d700e76aSTom         goto final;
333d700e76aSTom     }
334d700e76aSTom 
335d700e76aSTom     r = sd_bus_message_append(m, "v", "i", value);
3360b02be92SPatrick Venture     if (r < 0)
3370b02be92SPatrick Venture     {
338b51bf9c8SPatrick Venture         std::fprintf(stderr, "Failed to create a input parameter: %s",
339b51bf9c8SPatrick Venture                      strerror(-r));
340d700e76aSTom         goto final;
341d700e76aSTom     }
342d700e76aSTom 
343d700e76aSTom     r = sd_bus_call(bus, m, 0, &error, NULL);
3440b02be92SPatrick Venture     if (r < 0)
3450b02be92SPatrick Venture     {
346b51bf9c8SPatrick Venture         std::fprintf(stderr, "12 Failed to call the method: %s", strerror(-r));
347d700e76aSTom     }
348d700e76aSTom 
349d700e76aSTom final:
350d700e76aSTom     sd_bus_error_free(&error);
351d700e76aSTom     m = sd_bus_message_unref(m);
352d700e76aSTom 
353d700e76aSTom     return 0;
354d700e76aSTom }
355d700e76aSTom 
dbus_to_sensor_type(char * p)3560b02be92SPatrick Venture uint8_t dbus_to_sensor_type(char* p)
3570b02be92SPatrick Venture {
35898a23840SMatthew Barth     sensorTypemap_t* s = g_SensorTypeMap;
35998a23840SMatthew Barth     char r = 0;
3600b02be92SPatrick Venture     while (s->number != 0xFF)
3610b02be92SPatrick Venture     {
3620b02be92SPatrick Venture         if (!strcmp(s->dbusname, p))
3630b02be92SPatrick Venture         {
364558184eaSTom Joseph             r = s->typecode;
36598a23840SMatthew Barth             break;
36698a23840SMatthew Barth         }
36798a23840SMatthew Barth         s++;
36898a23840SMatthew Barth     }
36998a23840SMatthew Barth 
37098a23840SMatthew Barth     if (s->number == 0xFF)
37198a23840SMatthew Barth         printf("Failed to find Sensor Type %s\n", p);
37298a23840SMatthew Barth 
37398a23840SMatthew Barth     return r;
37498a23840SMatthew Barth }
37598a23840SMatthew Barth 
get_type_from_interface(dbus_interface_t dbus_if)3760b02be92SPatrick Venture uint8_t get_type_from_interface(dbus_interface_t dbus_if)
3770b02be92SPatrick Venture {
37856003453SBrad Bishop     uint8_t type;
37998a23840SMatthew Barth 
38098a23840SMatthew Barth     // This is where sensors that do not exist in dbus but do
38198a23840SMatthew Barth     // exist in the host code stop.  This should indicate it
38298a23840SMatthew Barth     // is not a supported sensor
3830b02be92SPatrick Venture     if (dbus_if.interface[0] == 0)
3840b02be92SPatrick Venture     {
3850b02be92SPatrick Venture         return 0;
3860b02be92SPatrick Venture     }
38798a23840SMatthew Barth 
3887117441cSEmily Shaffer     // Fetch type from interface itself.
3897117441cSEmily Shaffer     if (dbus_if.sensortype != 0)
3907117441cSEmily Shaffer     {
3917117441cSEmily Shaffer         type = dbus_if.sensortype;
3920b02be92SPatrick Venture     }
3930b02be92SPatrick Venture     else
3940b02be92SPatrick Venture     {
39598a23840SMatthew Barth         // Non InventoryItems
3964491a46fSPatrick Venture         char* p = strrchr(dbus_if.path, '/');
39756003453SBrad Bishop         type = dbus_to_sensor_type(p + 1);
39898a23840SMatthew Barth     }
39998a23840SMatthew Barth 
40056003453SBrad Bishop     return type;
40198a23840SMatthew Barth }
40298a23840SMatthew Barth 
403391f3303SEmily Shaffer // Replaces find_sensor
find_type_for_sensor_number(uint8_t num)4040b02be92SPatrick Venture uint8_t find_type_for_sensor_number(uint8_t num)
4050b02be92SPatrick Venture {
406391f3303SEmily Shaffer     int r;
407391f3303SEmily Shaffer     dbus_interface_t dbus_if;
4082ae09b9aSEmily Shaffer     r = find_openbmc_path(num, &dbus_if);
4090b02be92SPatrick Venture     if (r < 0)
4100b02be92SPatrick Venture     {
411b51bf9c8SPatrick Venture         std::fprintf(stderr, "Could not find sensor %d\n", num);
41291875f77SLei YU         return 0;
413391f3303SEmily Shaffer     }
414391f3303SEmily Shaffer     return get_type_from_interface(dbus_if);
415391f3303SEmily Shaffer }
416391f3303SEmily Shaffer 
417a8be7dc8SDeepak Kumar Sahu /**
418a8be7dc8SDeepak Kumar Sahu  *  @brief implements the get sensor type command.
419a8be7dc8SDeepak Kumar Sahu  *  @param - sensorNumber
420a8be7dc8SDeepak Kumar Sahu  *
421a8be7dc8SDeepak Kumar Sahu  *  @return IPMI completion code plus response data on success.
422a8be7dc8SDeepak Kumar Sahu  *   - sensorType
423a8be7dc8SDeepak Kumar Sahu  *   - eventType
424a8be7dc8SDeepak Kumar Sahu  **/
425a8be7dc8SDeepak Kumar Sahu 
426a8be7dc8SDeepak Kumar Sahu ipmi::RspType<uint8_t, // sensorType
427a8be7dc8SDeepak Kumar Sahu               uint8_t  // eventType
428a8be7dc8SDeepak Kumar Sahu               >
ipmiGetSensorType(uint8_t sensorNumber)429a8be7dc8SDeepak Kumar Sahu     ipmiGetSensorType(uint8_t sensorNumber)
43098a23840SMatthew Barth {
43164b7621cSWang Xiaohua     const auto it = ipmi::sensor::sensors.find(sensorNumber);
43264b7621cSWang Xiaohua     if (it == ipmi::sensor::sensors.end())
4330b02be92SPatrick Venture     {
43464b7621cSWang Xiaohua         // The sensor map does not contain the sensor requested
435a8be7dc8SDeepak Kumar Sahu         return ipmi::responseSensorInvalid();
43698a23840SMatthew Barth     }
43798a23840SMatthew Barth 
43864b7621cSWang Xiaohua     const auto& info = it->second;
43964b7621cSWang Xiaohua     uint8_t sensorType = info.sensorType;
44064b7621cSWang Xiaohua     uint8_t eventType = info.sensorReadingType;
44164b7621cSWang Xiaohua 
442a8be7dc8SDeepak Kumar Sahu     return ipmi::responseSuccess(sensorType, eventType);
44398a23840SMatthew Barth }
44498a23840SMatthew Barth 
4450b02be92SPatrick Venture const std::set<std::string> analogSensorInterfaces = {
446cc941e15SEmily Shaffer     "xyz.openbmc_project.Sensor.Value",
447e9a64056SPatrick Venture     "xyz.openbmc_project.Control.FanPwm",
448cc941e15SEmily Shaffer };
449cc941e15SEmily Shaffer 
isAnalogSensor(const std::string & interface)450cc941e15SEmily Shaffer bool isAnalogSensor(const std::string& interface)
451cc941e15SEmily Shaffer {
452cc941e15SEmily Shaffer     return (analogSensorInterfaces.count(interface));
453cc941e15SEmily Shaffer }
454cc941e15SEmily Shaffer 
4559da3a750SDeepak Kumar Sahu /**
4569da3a750SDeepak Kumar Sahu @brief This command is used to set sensorReading.
4579da3a750SDeepak Kumar Sahu 
4589da3a750SDeepak Kumar Sahu @param
4599da3a750SDeepak Kumar Sahu     -  sensorNumber
4609da3a750SDeepak Kumar Sahu     -  operation
4619da3a750SDeepak Kumar Sahu     -  reading
4629da3a750SDeepak Kumar Sahu     -  assertOffset0_7
4639da3a750SDeepak Kumar Sahu     -  assertOffset8_14
4649da3a750SDeepak Kumar Sahu     -  deassertOffset0_7
4659da3a750SDeepak Kumar Sahu     -  deassertOffset8_14
4669da3a750SDeepak Kumar Sahu     -  eventData1
4679da3a750SDeepak Kumar Sahu     -  eventData2
4689da3a750SDeepak Kumar Sahu     -  eventData3
4699da3a750SDeepak Kumar Sahu 
4709da3a750SDeepak Kumar Sahu @return completion code on success.
4719da3a750SDeepak Kumar Sahu **/
4729da3a750SDeepak Kumar Sahu 
ipmiSetSensorReading(uint8_t sensorNumber,uint8_t operation,uint8_t reading,uint8_t assertOffset0_7,uint8_t assertOffset8_14,uint8_t deassertOffset0_7,uint8_t deassertOffset8_14,uint8_t eventData1,uint8_t eventData2,uint8_t eventData3)4739da3a750SDeepak Kumar Sahu ipmi::RspType<> ipmiSetSensorReading(uint8_t sensorNumber, uint8_t operation,
4749da3a750SDeepak Kumar Sahu                                      uint8_t reading, uint8_t assertOffset0_7,
4759da3a750SDeepak Kumar Sahu                                      uint8_t assertOffset8_14,
4769da3a750SDeepak Kumar Sahu                                      uint8_t deassertOffset0_7,
4779da3a750SDeepak Kumar Sahu                                      uint8_t deassertOffset8_14,
4789da3a750SDeepak Kumar Sahu                                      uint8_t eventData1, uint8_t eventData2,
4799da3a750SDeepak Kumar Sahu                                      uint8_t eventData3)
480be703f71STom Joseph {
4819da3a750SDeepak Kumar Sahu     log<level::DEBUG>("IPMI SET_SENSOR",
4829da3a750SDeepak Kumar Sahu                       entry("SENSOR_NUM=0x%02x", sensorNumber));
4839da3a750SDeepak Kumar Sahu 
4840634e989SArun P. Mohanan     if (sensorNumber == 0xFF)
4850634e989SArun P. Mohanan     {
4860634e989SArun P. Mohanan         return ipmi::responseInvalidFieldRequest();
4870634e989SArun P. Mohanan     }
4889da3a750SDeepak Kumar Sahu     ipmi::sensor::SetSensorReadingReq cmdData;
4899da3a750SDeepak Kumar Sahu 
4909da3a750SDeepak Kumar Sahu     cmdData.number = sensorNumber;
4919da3a750SDeepak Kumar Sahu     cmdData.operation = operation;
4929da3a750SDeepak Kumar Sahu     cmdData.reading = reading;
4939da3a750SDeepak Kumar Sahu     cmdData.assertOffset0_7 = assertOffset0_7;
4949da3a750SDeepak Kumar Sahu     cmdData.assertOffset8_14 = assertOffset8_14;
4959da3a750SDeepak Kumar Sahu     cmdData.deassertOffset0_7 = deassertOffset0_7;
4969da3a750SDeepak Kumar Sahu     cmdData.deassertOffset8_14 = deassertOffset8_14;
4979da3a750SDeepak Kumar Sahu     cmdData.eventData1 = eventData1;
4989da3a750SDeepak Kumar Sahu     cmdData.eventData2 = eventData2;
4999da3a750SDeepak Kumar Sahu     cmdData.eventData3 = eventData3;
500be703f71STom Joseph 
501be703f71STom Joseph     // Check if the Sensor Number is present
502db0cbe64SPatrick Venture     const auto iter = ipmi::sensor::sensors.find(sensorNumber);
503db0cbe64SPatrick Venture     if (iter == ipmi::sensor::sensors.end())
504be703f71STom Joseph     {
5059da3a750SDeepak Kumar Sahu         updateSensorRecordFromSSRAESC(&sensorNumber);
5069da3a750SDeepak Kumar Sahu         return ipmi::responseSuccess();
507be703f71STom Joseph     }
508be703f71STom Joseph 
50918e99992SDhruvaraj Subhashchandran     try
51018e99992SDhruvaraj Subhashchandran     {
5110922bde4SJayanth Othayoth         if (ipmi::sensor::Mutability::Write !=
5120922bde4SJayanth Othayoth             (iter->second.mutability & ipmi::sensor::Mutability::Write))
5130922bde4SJayanth Othayoth         {
5140922bde4SJayanth Othayoth             log<level::ERR>("Sensor Set operation is not allowed",
5159da3a750SDeepak Kumar Sahu                             entry("SENSOR_NUM=%d", sensorNumber));
5169da3a750SDeepak Kumar Sahu             return ipmi::responseIllegalCommand();
5170922bde4SJayanth Othayoth         }
5189da3a750SDeepak Kumar Sahu         auto ipmiRC = iter->second.updateFunc(cmdData, iter->second);
5199da3a750SDeepak Kumar Sahu         return ipmi::response(ipmiRC);
520be703f71STom Joseph     }
521a2ad2da8SPatrick Williams     catch (const InternalFailure& e)
52218e99992SDhruvaraj Subhashchandran     {
52318e99992SDhruvaraj Subhashchandran         log<level::ERR>("Set sensor failed",
5249da3a750SDeepak Kumar Sahu                         entry("SENSOR_NUM=%d", sensorNumber));
52518e99992SDhruvaraj Subhashchandran         commit<InternalFailure>();
5269da3a750SDeepak Kumar Sahu         return ipmi::responseUnspecifiedError();
52718e99992SDhruvaraj Subhashchandran     }
5288202432fSTom Joseph     catch (const std::runtime_error& e)
5298202432fSTom Joseph     {
5308202432fSTom Joseph         log<level::ERR>(e.what());
5319da3a750SDeepak Kumar Sahu         return ipmi::responseUnspecifiedError();
5328202432fSTom Joseph     }
53398a23840SMatthew Barth }
53498a23840SMatthew Barth 
5354c3feba5Sjayaprakash Mutyala /** @brief implements the get sensor reading command
5364c3feba5Sjayaprakash Mutyala  *  @param sensorNum - sensor number
5374c3feba5Sjayaprakash Mutyala  *
5384c3feba5Sjayaprakash Mutyala  *  @returns IPMI completion code plus response data
5394c3feba5Sjayaprakash Mutyala  *   - senReading           - sensor reading
5404c3feba5Sjayaprakash Mutyala  *   - reserved
5414c3feba5Sjayaprakash Mutyala  *   - readState            - sensor reading state enabled
5424c3feba5Sjayaprakash Mutyala  *   - senScanState         - sensor scan state disabled
5434c3feba5Sjayaprakash Mutyala  *   - allEventMessageState - all Event message state disabled
5444c3feba5Sjayaprakash Mutyala  *   - assertionStatesLsb   - threshold levels states
5454c3feba5Sjayaprakash Mutyala  *   - assertionStatesMsb   - discrete reading sensor states
5464c3feba5Sjayaprakash Mutyala  */
5474c3feba5Sjayaprakash Mutyala ipmi::RspType<uint8_t, // sensor reading
5483ee668f9STom Joseph 
5494c3feba5Sjayaprakash Mutyala               uint5_t, // reserved
5504c3feba5Sjayaprakash Mutyala               bool,    // reading state
5514cc42556SSui Chen               bool,    // 0 = sensor scanning state disabled
5524cc42556SSui Chen               bool,    // 0 = all event messages disabled
5534c3feba5Sjayaprakash Mutyala 
5544c3feba5Sjayaprakash Mutyala               uint8_t, // threshold levels states
5554c3feba5Sjayaprakash Mutyala               uint8_t  // discrete reading sensor states
5564c3feba5Sjayaprakash Mutyala               >
ipmiSensorGetSensorReading(ipmi::Context::ptr & ctx,uint8_t sensorNum)55711d68897SWilly Tu     ipmiSensorGetSensorReading([[maybe_unused]] ipmi::Context::ptr& ctx,
55811d68897SWilly Tu                                uint8_t sensorNum)
5594c3feba5Sjayaprakash Mutyala {
5604c3feba5Sjayaprakash Mutyala     if (sensorNum == 0xFF)
5614c3feba5Sjayaprakash Mutyala     {
5624c3feba5Sjayaprakash Mutyala         return ipmi::responseInvalidFieldRequest();
5634c3feba5Sjayaprakash Mutyala     }
5644c3feba5Sjayaprakash Mutyala 
5654c3feba5Sjayaprakash Mutyala     const auto iter = ipmi::sensor::sensors.find(sensorNum);
566db0cbe64SPatrick Venture     if (iter == ipmi::sensor::sensors.end())
56714c15467STom Joseph     {
5684c3feba5Sjayaprakash Mutyala         return ipmi::responseSensorInvalid();
56914c15467STom Joseph     }
57013b87a3eSTom Joseph     if (ipmi::sensor::Mutability::Read !=
57113b87a3eSTom Joseph         (iter->second.mutability & ipmi::sensor::Mutability::Read))
57213b87a3eSTom Joseph     {
5734c3feba5Sjayaprakash Mutyala         return ipmi::responseIllegalCommand();
57413b87a3eSTom Joseph     }
57514c15467STom Joseph 
57614c15467STom Joseph     try
57714c15467STom Joseph     {
5788c2c048eSLei YU #ifdef FEATURE_SENSORS_CACHE
5798e8152c5SLei YU         auto& sensorData = sensorCacheMap[sensorNum];
5809714050fSLei YU         if (!sensorData.has_value())
5819714050fSLei YU         {
582a55e9ea1SLei YU             // No cached value, try read it
5838e8152c5SLei YU             std::string service;
5848e8152c5SLei YU             boost::system::error_code ec;
585a55e9ea1SLei YU             const auto& sensorInfo = iter->second;
5868e8152c5SLei YU             ec = ipmi::getService(ctx, sensorInfo.sensorInterface,
5878e8152c5SLei YU                                   sensorInfo.sensorPath, service);
5888e8152c5SLei YU             if (ec)
589a55e9ea1SLei YU             {
5908e8152c5SLei YU                 return ipmi::responseUnspecifiedError();
591a55e9ea1SLei YU             }
5927f3a70f0SLei YU             fillSensorIdServiceMap(sensorInfo.sensorPath,
5937f3a70f0SLei YU                                    sensorInfo.propertyInterfaces.begin()->first,
5947f3a70f0SLei YU                                    iter->first, service);
5958e8152c5SLei YU 
5968e8152c5SLei YU             ipmi::PropertyMap props;
5978e8152c5SLei YU             ec = ipmi::getAllDbusProperties(
5988e8152c5SLei YU                 ctx, service, sensorInfo.sensorPath,
5998e8152c5SLei YU                 sensorInfo.propertyInterfaces.begin()->first, props);
6008e8152c5SLei YU             if (ec)
601a55e9ea1SLei YU             {
6028e8152c5SLei YU                 fprintf(stderr, "Failed to get sensor %s, %d: %s\n",
6038e8152c5SLei YU                         sensorInfo.sensorPath.c_str(), ec.value(),
6048e8152c5SLei YU                         ec.message().c_str());
6059714050fSLei YU                 // Intitilizing with default values
6069714050fSLei YU                 constexpr uint8_t senReading = 0;
6079714050fSLei YU                 constexpr uint5_t reserved{0};
6089714050fSLei YU                 constexpr bool readState = true;
6099714050fSLei YU                 constexpr bool senScanState = false;
6109714050fSLei YU                 constexpr bool allEventMessageState = false;
6119714050fSLei YU                 constexpr uint8_t assertionStatesLsb = 0;
6129714050fSLei YU                 constexpr uint8_t assertionStatesMsb = 0;
6139714050fSLei YU 
614a55e9ea1SLei YU                 return ipmi::responseSuccess(senReading, reserved, readState,
615a55e9ea1SLei YU                                              senScanState, allEventMessageState,
616a55e9ea1SLei YU                                              assertionStatesLsb,
617a55e9ea1SLei YU                                              assertionStatesMsb);
618a55e9ea1SLei YU             }
6198e8152c5SLei YU             sensorInfo.getFunc(sensorNum, sensorInfo, props);
6209714050fSLei YU         }
6219714050fSLei YU         return ipmi::responseSuccess(
6229714050fSLei YU             sensorData->response.reading, uint5_t(0),
6239714050fSLei YU             sensorData->response.readingOrStateUnavailable,
6249714050fSLei YU             sensorData->response.scanningEnabled,
6259714050fSLei YU             sensorData->response.allEventMessagesEnabled,
6269714050fSLei YU             sensorData->response.thresholdLevelsStates,
6279714050fSLei YU             sensorData->response.discreteReadingSensorStates);
6289714050fSLei YU 
6298c2c048eSLei YU #else
6304cc42556SSui Chen         ipmi::sensor::GetSensorResponse getResponse =
6314cc42556SSui Chen             iter->second.getFunc(iter->second);
6324c3feba5Sjayaprakash Mutyala 
6334cc42556SSui Chen         return ipmi::responseSuccess(getResponse.reading, uint5_t(0),
6344cc42556SSui Chen                                      getResponse.readingOrStateUnavailable,
6354cc42556SSui Chen                                      getResponse.scanningEnabled,
6364cc42556SSui Chen                                      getResponse.allEventMessagesEnabled,
6374cc42556SSui Chen                                      getResponse.thresholdLevelsStates,
6384cc42556SSui Chen                                      getResponse.discreteReadingSensorStates);
6398c2c048eSLei YU #endif
64014c15467STom Joseph     }
6419cf85627SBrandon Kim #ifdef UPDATE_FUNCTIONAL_ON_FAIL
6429cf85627SBrandon Kim     catch (const SensorFunctionalError& e)
6439cf85627SBrandon Kim     {
6444c3feba5Sjayaprakash Mutyala         return ipmi::responseResponseError();
6459cf85627SBrandon Kim     }
6469cf85627SBrandon Kim #endif
6473ee668f9STom Joseph     catch (const std::exception& e)
64814c15467STom Joseph     {
6494c3feba5Sjayaprakash Mutyala         // Intitilizing with default values
6504c3feba5Sjayaprakash Mutyala         constexpr uint8_t senReading = 0;
6514c3feba5Sjayaprakash Mutyala         constexpr uint5_t reserved{0};
6524c3feba5Sjayaprakash Mutyala         constexpr bool readState = true;
6534c3feba5Sjayaprakash Mutyala         constexpr bool senScanState = false;
6544c3feba5Sjayaprakash Mutyala         constexpr bool allEventMessageState = false;
6554c3feba5Sjayaprakash Mutyala         constexpr uint8_t assertionStatesLsb = 0;
6564c3feba5Sjayaprakash Mutyala         constexpr uint8_t assertionStatesMsb = 0;
6574c3feba5Sjayaprakash Mutyala 
6584c3feba5Sjayaprakash Mutyala         return ipmi::responseSuccess(senReading, reserved, readState,
6594c3feba5Sjayaprakash Mutyala                                      senScanState, allEventMessageState,
6604c3feba5Sjayaprakash Mutyala                                      assertionStatesLsb, assertionStatesMsb);
66114c15467STom Joseph     }
66298a23840SMatthew Barth }
66398a23840SMatthew Barth 
66489a83b67SKonstantin Aladyshev get_sdr::GetSensorThresholdsResponse
getSensorThresholds(ipmi::Context::ptr & ctx,uint8_t sensorNum)66589a83b67SKonstantin Aladyshev     getSensorThresholds(ipmi::Context::ptr& ctx, uint8_t sensorNum)
6660ac0dd23STom Joseph {
667515bc375SWilliam A. Kennington III     get_sdr::GetSensorThresholdsResponse resp{};
6680ac0dd23STom Joseph     constexpr auto warningThreshIntf =
6690ac0dd23STom Joseph         "xyz.openbmc_project.Sensor.Threshold.Warning";
6700ac0dd23STom Joseph     constexpr auto criticalThreshIntf =
6710ac0dd23STom Joseph         "xyz.openbmc_project.Sensor.Threshold.Critical";
6720ac0dd23STom Joseph 
673db0cbe64SPatrick Venture     const auto iter = ipmi::sensor::sensors.find(sensorNum);
6740ac0dd23STom Joseph     const auto info = iter->second;
6750ac0dd23STom Joseph 
67689a83b67SKonstantin Aladyshev     std::string service;
67789a83b67SKonstantin Aladyshev     boost::system::error_code ec;
67889a83b67SKonstantin Aladyshev     ec = ipmi::getService(ctx, info.sensorInterface, info.sensorPath, service);
67989a83b67SKonstantin Aladyshev     if (ec)
68089a83b67SKonstantin Aladyshev     {
68189a83b67SKonstantin Aladyshev         return resp;
68289a83b67SKonstantin Aladyshev     }
6830ac0dd23STom Joseph 
68489a83b67SKonstantin Aladyshev     ipmi::PropertyMap warnThresholds;
68589a83b67SKonstantin Aladyshev     ec = ipmi::getAllDbusProperties(ctx, service, info.sensorPath,
68689a83b67SKonstantin Aladyshev                                     warningThreshIntf, warnThresholds);
6879154caabSWilly Tu     int32_t minClamp;
6889154caabSWilly Tu     int32_t maxClamp;
6899154caabSWilly Tu     int32_t rawData;
6909154caabSWilly Tu     constexpr uint8_t sensorUnitsSignedBits = 2 << 6;
6919154caabSWilly Tu     constexpr uint8_t signedDataFormat = 0x80;
6929154caabSWilly Tu     if ((info.sensorUnits1 & sensorUnitsSignedBits) == signedDataFormat)
6939154caabSWilly Tu     {
6949154caabSWilly Tu         minClamp = std::numeric_limits<int8_t>::lowest();
6959154caabSWilly Tu         maxClamp = std::numeric_limits<int8_t>::max();
6969154caabSWilly Tu     }
6979154caabSWilly Tu     else
6989154caabSWilly Tu     {
6999154caabSWilly Tu         minClamp = std::numeric_limits<uint8_t>::lowest();
7009154caabSWilly Tu         maxClamp = std::numeric_limits<uint8_t>::max();
7019154caabSWilly Tu     }
70289a83b67SKonstantin Aladyshev     if (!ec)
70389a83b67SKonstantin Aladyshev     {
70492079a24SHieu Huynh         double warnLow = ipmi::mappedVariant<double>(
70592079a24SHieu Huynh             warnThresholds, "WarningLow",
70692079a24SHieu Huynh             std::numeric_limits<double>::quiet_NaN());
70792079a24SHieu Huynh         double warnHigh = ipmi::mappedVariant<double>(
70892079a24SHieu Huynh             warnThresholds, "WarningHigh",
70992079a24SHieu Huynh             std::numeric_limits<double>::quiet_NaN());
7100ac0dd23STom Joseph 
711e0a41100SKonstantin Aladyshev         if (std::isfinite(warnLow))
7120ac0dd23STom Joseph         {
713586d35b4SPatrick Venture             warnLow *= std::pow(10, info.scale - info.exponentR);
7149154caabSWilly Tu             rawData = round((warnLow - info.scaledOffset) / info.coefficientM);
7159154caabSWilly Tu             resp.lowerNonCritical =
7169154caabSWilly Tu                 static_cast<uint8_t>(std::clamp(rawData, minClamp, maxClamp));
717996c9798Sjayaprakash Mutyala             resp.validMask |= static_cast<uint8_t>(
7180ac0dd23STom Joseph                 ipmi::sensor::ThresholdMask::NON_CRITICAL_LOW_MASK);
7190ac0dd23STom Joseph         }
7200ac0dd23STom Joseph 
721e0a41100SKonstantin Aladyshev         if (std::isfinite(warnHigh))
7220ac0dd23STom Joseph         {
723586d35b4SPatrick Venture             warnHigh *= std::pow(10, info.scale - info.exponentR);
7249154caabSWilly Tu             rawData = round((warnHigh - info.scaledOffset) / info.coefficientM);
7259154caabSWilly Tu             resp.upperNonCritical =
7269154caabSWilly Tu                 static_cast<uint8_t>(std::clamp(rawData, minClamp, maxClamp));
727996c9798Sjayaprakash Mutyala             resp.validMask |= static_cast<uint8_t>(
7280ac0dd23STom Joseph                 ipmi::sensor::ThresholdMask::NON_CRITICAL_HIGH_MASK);
7290ac0dd23STom Joseph         }
73089a83b67SKonstantin Aladyshev     }
7310ac0dd23STom Joseph 
73289a83b67SKonstantin Aladyshev     ipmi::PropertyMap critThresholds;
73389a83b67SKonstantin Aladyshev     ec = ipmi::getAllDbusProperties(ctx, service, info.sensorPath,
73489a83b67SKonstantin Aladyshev                                     criticalThreshIntf, critThresholds);
73589a83b67SKonstantin Aladyshev     if (!ec)
73689a83b67SKonstantin Aladyshev     {
73792079a24SHieu Huynh         double critLow = ipmi::mappedVariant<double>(
73892079a24SHieu Huynh             critThresholds, "CriticalLow",
73992079a24SHieu Huynh             std::numeric_limits<double>::quiet_NaN());
74092079a24SHieu Huynh         double critHigh = ipmi::mappedVariant<double>(
74192079a24SHieu Huynh             critThresholds, "CriticalHigh",
74292079a24SHieu Huynh             std::numeric_limits<double>::quiet_NaN());
7430ac0dd23STom Joseph 
744e0a41100SKonstantin Aladyshev         if (std::isfinite(critLow))
7450ac0dd23STom Joseph         {
746586d35b4SPatrick Venture             critLow *= std::pow(10, info.scale - info.exponentR);
7479154caabSWilly Tu             rawData = round((critLow - info.scaledOffset) / info.coefficientM);
7489154caabSWilly Tu             resp.lowerCritical =
7499154caabSWilly Tu                 static_cast<uint8_t>(std::clamp(rawData, minClamp, maxClamp));
750996c9798Sjayaprakash Mutyala             resp.validMask |= static_cast<uint8_t>(
7510ac0dd23STom Joseph                 ipmi::sensor::ThresholdMask::CRITICAL_LOW_MASK);
7520ac0dd23STom Joseph         }
7530ac0dd23STom Joseph 
754e0a41100SKonstantin Aladyshev         if (std::isfinite(critHigh))
7550ac0dd23STom Joseph         {
756586d35b4SPatrick Venture             critHigh *= std::pow(10, info.scale - info.exponentR);
7579154caabSWilly Tu             rawData = round((critHigh - info.scaledOffset) / info.coefficientM);
7589154caabSWilly Tu             resp.upperCritical =
7599154caabSWilly Tu                 static_cast<uint8_t>(std::clamp(rawData, minClamp, maxClamp));
760996c9798Sjayaprakash Mutyala             resp.validMask |= static_cast<uint8_t>(
7610ac0dd23STom Joseph                 ipmi::sensor::ThresholdMask::CRITICAL_HIGH_MASK);
7620ac0dd23STom Joseph         }
76389a83b67SKonstantin Aladyshev     }
764996c9798Sjayaprakash Mutyala 
765996c9798Sjayaprakash Mutyala     return resp;
7660ac0dd23STom Joseph }
7670ac0dd23STom Joseph 
768996c9798Sjayaprakash Mutyala /** @brief implements the get sensor thresholds command
76989a83b67SKonstantin Aladyshev  *  @param ctx - IPMI context pointer
770996c9798Sjayaprakash Mutyala  *  @param sensorNum - sensor number
771996c9798Sjayaprakash Mutyala  *
772996c9798Sjayaprakash Mutyala  *  @returns IPMI completion code plus response data
773996c9798Sjayaprakash Mutyala  *   - validMask - threshold mask
774996c9798Sjayaprakash Mutyala  *   - lower non-critical threshold - IPMI messaging state
775996c9798Sjayaprakash Mutyala  *   - lower critical threshold - link authentication state
776996c9798Sjayaprakash Mutyala  *   - lower non-recoverable threshold - callback state
777996c9798Sjayaprakash Mutyala  *   - upper non-critical threshold
778996c9798Sjayaprakash Mutyala  *   - upper critical
779996c9798Sjayaprakash Mutyala  *   - upper non-recoverable
780996c9798Sjayaprakash Mutyala  */
781996c9798Sjayaprakash Mutyala ipmi::RspType<uint8_t, // validMask
782996c9798Sjayaprakash Mutyala               uint8_t, // lowerNonCritical
783996c9798Sjayaprakash Mutyala               uint8_t, // lowerCritical
784996c9798Sjayaprakash Mutyala               uint8_t, // lowerNonRecoverable
785996c9798Sjayaprakash Mutyala               uint8_t, // upperNonCritical
786996c9798Sjayaprakash Mutyala               uint8_t, // upperCritical
787996c9798Sjayaprakash Mutyala               uint8_t  // upperNonRecoverable
788996c9798Sjayaprakash Mutyala               >
ipmiSensorGetSensorThresholds(ipmi::Context::ptr & ctx,uint8_t sensorNum)78989a83b67SKonstantin Aladyshev     ipmiSensorGetSensorThresholds(ipmi::Context::ptr& ctx, uint8_t sensorNum)
7905c0beec1SDhruvaraj Subhashchandran {
7910ac0dd23STom Joseph     constexpr auto valueInterface = "xyz.openbmc_project.Sensor.Value";
7925c0beec1SDhruvaraj Subhashchandran 
793db0cbe64SPatrick Venture     const auto iter = ipmi::sensor::sensors.find(sensorNum);
794db0cbe64SPatrick Venture     if (iter == ipmi::sensor::sensors.end())
7955c0beec1SDhruvaraj Subhashchandran     {
796996c9798Sjayaprakash Mutyala         return ipmi::responseSensorInvalid();
7975c0beec1SDhruvaraj Subhashchandran     }
7985c0beec1SDhruvaraj Subhashchandran 
7990ac0dd23STom Joseph     const auto info = iter->second;
8005c0beec1SDhruvaraj Subhashchandran 
8015c0beec1SDhruvaraj Subhashchandran     // Proceed only if the sensor value interface is implemented.
8020ac0dd23STom Joseph     if (info.propertyInterfaces.find(valueInterface) ==
8030ac0dd23STom Joseph         info.propertyInterfaces.end())
8045c0beec1SDhruvaraj Subhashchandran     {
8055c0beec1SDhruvaraj Subhashchandran         // return with valid mask as 0
806996c9798Sjayaprakash Mutyala         return ipmi::responseSuccess();
8075c0beec1SDhruvaraj Subhashchandran     }
8085c0beec1SDhruvaraj Subhashchandran 
80914a47819SLei YU     auto it = sensorThresholdMap.find(sensorNum);
81014a47819SLei YU     if (it == sensorThresholdMap.end())
81114a47819SLei YU     {
81214a47819SLei YU         sensorThresholdMap[sensorNum] = getSensorThresholds(ctx, sensorNum);
81314a47819SLei YU     }
81414a47819SLei YU 
81514a47819SLei YU     const auto& resp = sensorThresholdMap[sensorNum];
8165c0beec1SDhruvaraj Subhashchandran 
817996c9798Sjayaprakash Mutyala     return ipmi::responseSuccess(resp.validMask, resp.lowerNonCritical,
818996c9798Sjayaprakash Mutyala                                  resp.lowerCritical, resp.lowerNonRecoverable,
819996c9798Sjayaprakash Mutyala                                  resp.upperNonCritical, resp.upperCritical,
820996c9798Sjayaprakash Mutyala                                  resp.upperNonRecoverable);
8215c0beec1SDhruvaraj Subhashchandran }
8225c0beec1SDhruvaraj Subhashchandran 
823f93da667SLotus Xu /** @brief implements the Set Sensor threshold command
824f93da667SLotus Xu  *  @param sensorNumber        - sensor number
825f93da667SLotus Xu  *  @param lowerNonCriticalThreshMask
826f93da667SLotus Xu  *  @param lowerCriticalThreshMask
827f93da667SLotus Xu  *  @param lowerNonRecovThreshMask
828f93da667SLotus Xu  *  @param upperNonCriticalThreshMask
829f93da667SLotus Xu  *  @param upperCriticalThreshMask
830f93da667SLotus Xu  *  @param upperNonRecovThreshMask
831f93da667SLotus Xu  *  @param reserved
832f93da667SLotus Xu  *  @param lowerNonCritical    - lower non-critical threshold
833f93da667SLotus Xu  *  @param lowerCritical       - Lower critical threshold
834f93da667SLotus Xu  *  @param lowerNonRecoverable - Lower non recovarable threshold
835f93da667SLotus Xu  *  @param upperNonCritical    - Upper non-critical threshold
836f93da667SLotus Xu  *  @param upperCritical       - Upper critical
837f93da667SLotus Xu  *  @param upperNonRecoverable - Upper Non-recoverable
838f93da667SLotus Xu  *
839f93da667SLotus Xu  *  @returns IPMI completion code
840f93da667SLotus Xu  */
ipmiSenSetSensorThresholds(ipmi::Context::ptr & ctx,uint8_t sensorNum,bool lowerNonCriticalThreshMask,bool lowerCriticalThreshMask,bool lowerNonRecovThreshMask,bool upperNonCriticalThreshMask,bool upperCriticalThreshMask,bool upperNonRecovThreshMask,uint2_t reserved,uint8_t lowerNonCritical,uint8_t lowerCritical,uint8_t,uint8_t upperNonCritical,uint8_t upperCritical,uint8_t)841f93da667SLotus Xu ipmi::RspType<> ipmiSenSetSensorThresholds(
842f93da667SLotus Xu     ipmi::Context::ptr& ctx, uint8_t sensorNum, bool lowerNonCriticalThreshMask,
843f93da667SLotus Xu     bool lowerCriticalThreshMask, bool lowerNonRecovThreshMask,
844f93da667SLotus Xu     bool upperNonCriticalThreshMask, bool upperCriticalThreshMask,
845f93da667SLotus Xu     bool upperNonRecovThreshMask, uint2_t reserved, uint8_t lowerNonCritical,
84611d68897SWilly Tu     uint8_t lowerCritical, uint8_t, uint8_t upperNonCritical,
84711d68897SWilly Tu     uint8_t upperCritical, uint8_t)
848f93da667SLotus Xu {
849f93da667SLotus Xu     if (reserved)
850f93da667SLotus Xu     {
851f93da667SLotus Xu         return ipmi::responseInvalidFieldRequest();
852f93da667SLotus Xu     }
853f93da667SLotus Xu 
854f93da667SLotus Xu     // lower nc and upper nc not suppported on any sensor
855f93da667SLotus Xu     if (lowerNonRecovThreshMask || upperNonRecovThreshMask)
856f93da667SLotus Xu     {
857f93da667SLotus Xu         return ipmi::responseInvalidFieldRequest();
858f93da667SLotus Xu     }
859f93da667SLotus Xu 
860f93da667SLotus Xu     // if none of the threshold mask are set, nothing to do
861f93da667SLotus Xu     if (!(lowerNonCriticalThreshMask | lowerCriticalThreshMask |
862f93da667SLotus Xu           lowerNonRecovThreshMask | upperNonCriticalThreshMask |
863f93da667SLotus Xu           upperCriticalThreshMask | upperNonRecovThreshMask))
864f93da667SLotus Xu     {
865f93da667SLotus Xu         return ipmi::responseSuccess();
866f93da667SLotus Xu     }
867f93da667SLotus Xu 
868f93da667SLotus Xu     constexpr auto valueInterface = "xyz.openbmc_project.Sensor.Value";
869f93da667SLotus Xu 
870f93da667SLotus Xu     const auto iter = ipmi::sensor::sensors.find(sensorNum);
871f93da667SLotus Xu     if (iter == ipmi::sensor::sensors.end())
872f93da667SLotus Xu     {
873f93da667SLotus Xu         return ipmi::responseSensorInvalid();
874f93da667SLotus Xu     }
875f93da667SLotus Xu 
876f93da667SLotus Xu     const auto& info = iter->second;
877f93da667SLotus Xu 
878f93da667SLotus Xu     // Proceed only if the sensor value interface is implemented.
879f93da667SLotus Xu     if (info.propertyInterfaces.find(valueInterface) ==
880f93da667SLotus Xu         info.propertyInterfaces.end())
881f93da667SLotus Xu     {
882f93da667SLotus Xu         // return with valid mask as 0
883f93da667SLotus Xu         return ipmi::responseSuccess();
884f93da667SLotus Xu     }
885f93da667SLotus Xu 
886f93da667SLotus Xu     constexpr auto warningThreshIntf =
887f93da667SLotus Xu         "xyz.openbmc_project.Sensor.Threshold.Warning";
888f93da667SLotus Xu     constexpr auto criticalThreshIntf =
889f93da667SLotus Xu         "xyz.openbmc_project.Sensor.Threshold.Critical";
890f93da667SLotus Xu 
891f93da667SLotus Xu     std::string service;
892f93da667SLotus Xu     boost::system::error_code ec;
893f93da667SLotus Xu     ec = ipmi::getService(ctx, info.sensorInterface, info.sensorPath, service);
894f93da667SLotus Xu     if (ec)
895f93da667SLotus Xu     {
896f93da667SLotus Xu         return ipmi::responseResponseError();
897f93da667SLotus Xu     }
898f93da667SLotus Xu     // store a vector of property name, value to set, and interface
899f93da667SLotus Xu     std::vector<std::tuple<std::string, uint8_t, std::string>> thresholdsToSet;
900f93da667SLotus Xu 
901f93da667SLotus Xu     // define the indexes of the tuple
902f93da667SLotus Xu     constexpr uint8_t propertyName = 0;
903f93da667SLotus Xu     constexpr uint8_t thresholdValue = 1;
904f93da667SLotus Xu     constexpr uint8_t interface = 2;
905f93da667SLotus Xu     // verifiy all needed fields are present
906f93da667SLotus Xu     if (lowerCriticalThreshMask || upperCriticalThreshMask)
907f93da667SLotus Xu     {
908f93da667SLotus Xu         ipmi::PropertyMap findThreshold;
909f93da667SLotus Xu         ec = ipmi::getAllDbusProperties(ctx, service, info.sensorPath,
910f93da667SLotus Xu                                         criticalThreshIntf, findThreshold);
911f93da667SLotus Xu 
912f93da667SLotus Xu         if (!ec)
913f93da667SLotus Xu         {
914f93da667SLotus Xu             if (lowerCriticalThreshMask)
915f93da667SLotus Xu             {
916f93da667SLotus Xu                 auto findLower = findThreshold.find("CriticalLow");
917f93da667SLotus Xu                 if (findLower == findThreshold.end())
918f93da667SLotus Xu                 {
919f93da667SLotus Xu                     return ipmi::responseInvalidFieldRequest();
920f93da667SLotus Xu                 }
921f93da667SLotus Xu                 thresholdsToSet.emplace_back("CriticalLow", lowerCritical,
922f93da667SLotus Xu                                              criticalThreshIntf);
923f93da667SLotus Xu             }
924f93da667SLotus Xu             if (upperCriticalThreshMask)
925f93da667SLotus Xu             {
926f93da667SLotus Xu                 auto findUpper = findThreshold.find("CriticalHigh");
927f93da667SLotus Xu                 if (findUpper == findThreshold.end())
928f93da667SLotus Xu                 {
929f93da667SLotus Xu                     return ipmi::responseInvalidFieldRequest();
930f93da667SLotus Xu                 }
931f93da667SLotus Xu                 thresholdsToSet.emplace_back("CriticalHigh", upperCritical,
932f93da667SLotus Xu                                              criticalThreshIntf);
933f93da667SLotus Xu             }
934f93da667SLotus Xu         }
935f93da667SLotus Xu     }
936f93da667SLotus Xu     if (lowerNonCriticalThreshMask || upperNonCriticalThreshMask)
937f93da667SLotus Xu     {
938f93da667SLotus Xu         ipmi::PropertyMap findThreshold;
939f93da667SLotus Xu         ec = ipmi::getAllDbusProperties(ctx, service, info.sensorPath,
940f93da667SLotus Xu                                         warningThreshIntf, findThreshold);
941f93da667SLotus Xu 
942f93da667SLotus Xu         if (!ec)
943f93da667SLotus Xu         {
944f93da667SLotus Xu             if (lowerNonCriticalThreshMask)
945f93da667SLotus Xu             {
946f93da667SLotus Xu                 auto findLower = findThreshold.find("WarningLow");
947f93da667SLotus Xu                 if (findLower == findThreshold.end())
948f93da667SLotus Xu                 {
949f93da667SLotus Xu                     return ipmi::responseInvalidFieldRequest();
950f93da667SLotus Xu                 }
951f93da667SLotus Xu                 thresholdsToSet.emplace_back("WarningLow", lowerNonCritical,
952f93da667SLotus Xu                                              warningThreshIntf);
953f93da667SLotus Xu             }
954f93da667SLotus Xu             if (upperNonCriticalThreshMask)
955f93da667SLotus Xu             {
956f93da667SLotus Xu                 auto findUpper = findThreshold.find("WarningHigh");
957f93da667SLotus Xu                 if (findUpper == findThreshold.end())
958f93da667SLotus Xu                 {
959f93da667SLotus Xu                     return ipmi::responseInvalidFieldRequest();
960f93da667SLotus Xu                 }
961f93da667SLotus Xu                 thresholdsToSet.emplace_back("WarningHigh", upperNonCritical,
962f93da667SLotus Xu                                              warningThreshIntf);
963f93da667SLotus Xu             }
964f93da667SLotus Xu         }
965f93da667SLotus Xu     }
966f93da667SLotus Xu     for (const auto& property : thresholdsToSet)
967f93da667SLotus Xu     {
968f93da667SLotus Xu         // from section 36.3 in the IPMI Spec, assume all linear
969f93da667SLotus Xu         double valueToSet =
970f93da667SLotus Xu             ((info.coefficientM * std::get<thresholdValue>(property)) +
971f93da667SLotus Xu              (info.scaledOffset * std::pow(10.0, info.scale))) *
972f93da667SLotus Xu             std::pow(10.0, info.exponentR);
973f93da667SLotus Xu         ipmi::setDbusProperty(
974f93da667SLotus Xu             ctx, service, info.sensorPath, std::get<interface>(property),
975f93da667SLotus Xu             std::get<propertyName>(property), ipmi::Value(valueToSet));
976f93da667SLotus Xu     }
977f93da667SLotus Xu 
97814a47819SLei YU     // Invalidate the cache
97914a47819SLei YU     sensorThresholdMap.erase(sensorNum);
980f93da667SLotus Xu     return ipmi::responseSuccess();
981f93da667SLotus Xu }
982f93da667SLotus Xu 
983d957823eSjayaprakash Mutyala /** @brief implements the get SDR Info command
984d957823eSjayaprakash Mutyala  *  @param count - Operation
985d957823eSjayaprakash Mutyala  *
986d957823eSjayaprakash Mutyala  *  @returns IPMI completion code plus response data
987d957823eSjayaprakash Mutyala  *   - sdrCount - sensor/SDR count
988d957823eSjayaprakash Mutyala  *   - lunsAndDynamicPopulation - static/Dynamic sensor population flag
989d957823eSjayaprakash Mutyala  */
990d957823eSjayaprakash Mutyala ipmi::RspType<uint8_t, // respcount
991d957823eSjayaprakash Mutyala               uint8_t  // dynamic population flags
992d957823eSjayaprakash Mutyala               >
ipmiSensorGetDeviceSdrInfo(std::optional<uint8_t> count)993d957823eSjayaprakash Mutyala     ipmiSensorGetDeviceSdrInfo(std::optional<uint8_t> count)
994d06e0e7eSEmily Shaffer {
995d957823eSjayaprakash Mutyala     uint8_t sdrCount;
996d957823eSjayaprakash Mutyala     // multiple LUNs not supported.
997d957823eSjayaprakash Mutyala     constexpr uint8_t lunsAndDynamicPopulation = 1;
998d957823eSjayaprakash Mutyala     constexpr uint8_t getSdrCount = 0x01;
999d957823eSjayaprakash Mutyala     constexpr uint8_t getSensorCount = 0x00;
1000d957823eSjayaprakash Mutyala 
1001d957823eSjayaprakash Mutyala     if (count.value_or(0) == getSdrCount)
1002d06e0e7eSEmily Shaffer     {
1003d957823eSjayaprakash Mutyala         // Get SDR count. This returns the total number of SDRs in the device.
100487fd2cd1SPatrick Venture         const auto& entityRecords =
100587fd2cd1SPatrick Venture             ipmi::sensor::EntityInfoMapContainer::getContainer()
100687fd2cd1SPatrick Venture                 ->getIpmiEntityRecords();
1007fbc6c9d7SPatrick Williams         sdrCount = ipmi::sensor::sensors.size() + frus.size() +
1008fbc6c9d7SPatrick Williams                    entityRecords.size();
1009d957823eSjayaprakash Mutyala     }
1010d957823eSjayaprakash Mutyala     else if (count.value_or(0) == getSensorCount)
1011d957823eSjayaprakash Mutyala     {
1012d957823eSjayaprakash Mutyala         // Get Sensor count. This returns the number of sensors
1013db0cbe64SPatrick Venture         sdrCount = ipmi::sensor::sensors.size();
1014d06e0e7eSEmily Shaffer     }
1015d06e0e7eSEmily Shaffer     else
1016d06e0e7eSEmily Shaffer     {
1017d957823eSjayaprakash Mutyala         return ipmi::responseInvalidCommandOnLun();
1018d06e0e7eSEmily Shaffer     }
1019d06e0e7eSEmily Shaffer 
1020d957823eSjayaprakash Mutyala     return ipmi::responseSuccess(sdrCount, lunsAndDynamicPopulation);
1021d06e0e7eSEmily Shaffer }
1022d06e0e7eSEmily Shaffer 
1023d957823eSjayaprakash Mutyala /** @brief implements the reserve SDR command
1024d957823eSjayaprakash Mutyala  *  @returns IPMI completion code plus response data
1025d957823eSjayaprakash Mutyala  *   - reservationID - reservation ID
1026d957823eSjayaprakash Mutyala  */
ipmiSensorReserveSdr()1027d957823eSjayaprakash Mutyala ipmi::RspType<uint16_t> ipmiSensorReserveSdr()
1028a344afc0SEmily Shaffer {
1029a344afc0SEmily Shaffer     // A constant reservation ID is okay until we implement add/remove SDR.
1030d957823eSjayaprakash Mutyala     constexpr uint16_t reservationID = 1;
1031a344afc0SEmily Shaffer 
1032d957823eSjayaprakash Mutyala     return ipmi::responseSuccess(reservationID);
1033a344afc0SEmily Shaffer }
103498a23840SMatthew Barth 
setUnitFieldsForObject(const ipmi::sensor::Info * info,get_sdr::SensorDataFullRecordBody * body)1035dc212b23STom Joseph void setUnitFieldsForObject(const ipmi::sensor::Info* info,
1036cc941e15SEmily Shaffer                             get_sdr::SensorDataFullRecordBody* body)
1037bbef71c2SEmily Shaffer {
1038523e2d1bSWilly Tu     namespace server = sdbusplus::server::xyz::openbmc_project::sensor;
1039dc212b23STom Joseph     try
1040dc212b23STom Joseph     {
1041dc212b23STom Joseph         auto unit = server::Value::convertUnitFromString(info->unit);
1042bbef71c2SEmily Shaffer         // Unit strings defined in
1043bbef71c2SEmily Shaffer         // phosphor-dbus-interfaces/xyz/openbmc_project/Sensor/Value.interface.yaml
1044bbef71c2SEmily Shaffer         switch (unit)
1045bbef71c2SEmily Shaffer         {
1046bbef71c2SEmily Shaffer             case server::Value::Unit::DegreesC:
1047bbef71c2SEmily Shaffer                 body->sensor_units_2_base = get_sdr::SENSOR_UNIT_DEGREES_C;
1048bbef71c2SEmily Shaffer                 break;
1049bbef71c2SEmily Shaffer             case server::Value::Unit::RPMS:
1050812e44c7SKirill Pakhomov                 body->sensor_units_2_base = get_sdr::SENSOR_UNIT_RPM;
1051bbef71c2SEmily Shaffer                 break;
1052bbef71c2SEmily Shaffer             case server::Value::Unit::Volts:
1053bbef71c2SEmily Shaffer                 body->sensor_units_2_base = get_sdr::SENSOR_UNIT_VOLTS;
1054bbef71c2SEmily Shaffer                 break;
1055bbef71c2SEmily Shaffer             case server::Value::Unit::Meters:
1056bbef71c2SEmily Shaffer                 body->sensor_units_2_base = get_sdr::SENSOR_UNIT_METERS;
1057bbef71c2SEmily Shaffer                 break;
1058bbef71c2SEmily Shaffer             case server::Value::Unit::Amperes:
1059bbef71c2SEmily Shaffer                 body->sensor_units_2_base = get_sdr::SENSOR_UNIT_AMPERES;
1060bbef71c2SEmily Shaffer                 break;
1061bbef71c2SEmily Shaffer             case server::Value::Unit::Joules:
1062bbef71c2SEmily Shaffer                 body->sensor_units_2_base = get_sdr::SENSOR_UNIT_JOULES;
1063bbef71c2SEmily Shaffer                 break;
1064dc212b23STom Joseph             case server::Value::Unit::Watts:
1065dc212b23STom Joseph                 body->sensor_units_2_base = get_sdr::SENSOR_UNIT_WATTS;
1066dc212b23STom Joseph                 break;
1067bbef71c2SEmily Shaffer             default:
1068cc941e15SEmily Shaffer                 // Cannot be hit.
1069b51bf9c8SPatrick Venture                 std::fprintf(stderr, "Unknown value unit type: = %s\n",
1070dc212b23STom Joseph                              info->unit.c_str());
1071cc941e15SEmily Shaffer         }
1072cc941e15SEmily Shaffer     }
107364678b85SPatrick Venture     catch (const sdbusplus::exception::InvalidEnumString& e)
1074cc941e15SEmily Shaffer     {
1075cc941e15SEmily Shaffer         log<level::WARNING>("Warning: no unit provided for sensor!");
1076cc941e15SEmily Shaffer     }
1077cc941e15SEmily Shaffer }
1078cc941e15SEmily Shaffer 
populate_record_from_dbus(get_sdr::SensorDataFullRecordBody * body,const ipmi::sensor::Info * info,ipmi_data_len_t)1079cc941e15SEmily Shaffer ipmi_ret_t populate_record_from_dbus(get_sdr::SensorDataFullRecordBody* body,
1080cc941e15SEmily Shaffer                                      const ipmi::sensor::Info* info,
108111d68897SWilly Tu                                      ipmi_data_len_t)
1082cc941e15SEmily Shaffer {
1083cc941e15SEmily Shaffer     /* Functional sensor case */
1084cc941e15SEmily Shaffer     if (isAnalogSensor(info->propertyInterfaces.begin()->first))
1085cc941e15SEmily Shaffer     {
1086c5324251STony Lee         body->sensor_units_1 = info->sensorUnits1; // default is 0. unsigned, no
1087c5324251STony Lee                                                    // rate, no modifier, not a %
1088cc941e15SEmily Shaffer         /* Unit info */
1089dc212b23STom Joseph         setUnitFieldsForObject(info, body);
109010f4959aSEmily Shaffer 
109110f4959aSEmily Shaffer         get_sdr::body::set_b(info->coefficientB, body);
109210f4959aSEmily Shaffer         get_sdr::body::set_m(info->coefficientM, body);
109310f4959aSEmily Shaffer         get_sdr::body::set_b_exp(info->exponentB, body);
1094dc212b23STom Joseph         get_sdr::body::set_r_exp(info->exponentR, body);
10959642391dSTom Joseph     }
10969642391dSTom Joseph 
10979642391dSTom Joseph     /* ID string */
1098be4ffa87SJeremy Kerr     auto id_string = info->sensorName;
1099be4ffa87SJeremy Kerr 
1100be4ffa87SJeremy Kerr     if (id_string.empty())
1101be4ffa87SJeremy Kerr     {
1102be4ffa87SJeremy Kerr         id_string = info->sensorNameFunc(*info);
1103be4ffa87SJeremy Kerr     }
11049642391dSTom Joseph 
1105bbef71c2SEmily Shaffer     if (id_string.length() > FULL_RECORD_ID_STR_MAX_LENGTH)
1106bbef71c2SEmily Shaffer     {
1107bbef71c2SEmily Shaffer         get_sdr::body::set_id_strlen(FULL_RECORD_ID_STR_MAX_LENGTH, body);
1108bbef71c2SEmily Shaffer     }
1109bbef71c2SEmily Shaffer     else
1110bbef71c2SEmily Shaffer     {
1111bbef71c2SEmily Shaffer         get_sdr::body::set_id_strlen(id_string.length(), body);
1112bbef71c2SEmily Shaffer     }
111351136984SPaul Fertser     get_sdr::body::set_id_type(3, body); // "8-bit ASCII + Latin 1"
1114bbef71c2SEmily Shaffer     strncpy(body->id_string, id_string.c_str(),
1115bbef71c2SEmily Shaffer             get_sdr::body::get_id_strlen(body));
1116bbef71c2SEmily Shaffer 
1117bbef71c2SEmily Shaffer     return IPMI_CC_OK;
1118bbef71c2SEmily Shaffer };
1119bbef71c2SEmily Shaffer 
ipmi_fru_get_sdr(ipmi_request_t request,ipmi_response_t response,ipmi_data_len_t data_len)1120e0cc8553SRatan Gupta ipmi_ret_t ipmi_fru_get_sdr(ipmi_request_t request, ipmi_response_t response,
1121e0cc8553SRatan Gupta                             ipmi_data_len_t data_len)
1122e0cc8553SRatan Gupta {
1123e0cc8553SRatan Gupta     auto req = reinterpret_cast<get_sdr::GetSdrReq*>(request);
1124e0cc8553SRatan Gupta     auto resp = reinterpret_cast<get_sdr::GetSdrResp*>(response);
1125e0cc8553SRatan Gupta     get_sdr::SensorDataFruRecord record{};
1126e0cc8553SRatan Gupta     auto dataLength = 0;
1127e0cc8553SRatan Gupta 
1128e0cc8553SRatan Gupta     auto fru = frus.begin();
1129e0cc8553SRatan Gupta     uint8_t fruID{};
1130e0cc8553SRatan Gupta     auto recordID = get_sdr::request::get_record_id(req);
1131e0cc8553SRatan Gupta 
1132e0cc8553SRatan Gupta     fruID = recordID - FRU_RECORD_ID_START;
1133e0cc8553SRatan Gupta     fru = frus.find(fruID);
1134e0cc8553SRatan Gupta     if (fru == frus.end())
1135e0cc8553SRatan Gupta     {
1136e0cc8553SRatan Gupta         return IPMI_CC_SENSOR_INVALID;
1137e0cc8553SRatan Gupta     }
1138e0cc8553SRatan Gupta 
1139e0cc8553SRatan Gupta     /* Header */
1140e0cc8553SRatan Gupta     get_sdr::header::set_record_id(recordID, &(record.header));
1141e0cc8553SRatan Gupta     record.header.sdr_version = SDR_VERSION; // Based on IPMI Spec v2.0 rev 1.1
1142e0cc8553SRatan Gupta     record.header.record_type = get_sdr::SENSOR_DATA_FRU_RECORD;
1143e0cc8553SRatan Gupta     record.header.record_length = sizeof(record.key) + sizeof(record.body);
1144e0cc8553SRatan Gupta 
1145e0cc8553SRatan Gupta     /* Key */
1146e0cc8553SRatan Gupta     record.key.fruID = fruID;
1147e0cc8553SRatan Gupta     record.key.accessLun |= IPMI_LOGICAL_FRU;
114868d9d405SMatt Simmering     record.key.deviceAddress = BMCTargetAddress;
1149e0cc8553SRatan Gupta 
1150e0cc8553SRatan Gupta     /* Body */
1151e0cc8553SRatan Gupta     record.body.entityID = fru->second[0].entityID;
1152e0cc8553SRatan Gupta     record.body.entityInstance = fru->second[0].entityInstance;
1153e0cc8553SRatan Gupta     record.body.deviceType = fruInventoryDevice;
1154e0cc8553SRatan Gupta     record.body.deviceTypeModifier = IPMIFruInventory;
1155e0cc8553SRatan Gupta 
1156e0cc8553SRatan Gupta     /* Device ID string */
11570b02be92SPatrick Venture     auto deviceID =
11580b02be92SPatrick Venture         fru->second[0].path.substr(fru->second[0].path.find_last_of('/') + 1,
1159e0cc8553SRatan Gupta                                    fru->second[0].path.length());
1160e0cc8553SRatan Gupta 
1161e0cc8553SRatan Gupta     if (deviceID.length() > get_sdr::FRU_RECORD_DEVICE_ID_MAX_LENGTH)
1162e0cc8553SRatan Gupta     {
1163e0cc8553SRatan Gupta         get_sdr::body::set_device_id_strlen(
11640b02be92SPatrick Venture             get_sdr::FRU_RECORD_DEVICE_ID_MAX_LENGTH, &(record.body));
1165e0cc8553SRatan Gupta     }
1166e0cc8553SRatan Gupta     else
1167e0cc8553SRatan Gupta     {
11680b02be92SPatrick Venture         get_sdr::body::set_device_id_strlen(deviceID.length(), &(record.body));
1169e0cc8553SRatan Gupta     }
1170e0cc8553SRatan Gupta 
1171e0cc8553SRatan Gupta     strncpy(record.body.deviceID, deviceID.c_str(),
1172e0cc8553SRatan Gupta             get_sdr::body::get_device_id_strlen(&(record.body)));
1173e0cc8553SRatan Gupta 
1174e0cc8553SRatan Gupta     if (++fru == frus.end())
1175e0cc8553SRatan Gupta     {
11769c11894eSJaghathiswari Rankappagounder Natarajan         // we have reached till end of fru, so assign the next record id to
11779c11894eSJaghathiswari Rankappagounder Natarajan         // 512(Max fru ID = 511) + Entity Record ID(may start with 0).
117887fd2cd1SPatrick Venture         const auto& entityRecords =
117987fd2cd1SPatrick Venture             ipmi::sensor::EntityInfoMapContainer::getContainer()
118087fd2cd1SPatrick Venture                 ->getIpmiEntityRecords();
1181fbc6c9d7SPatrick Williams         auto next_record_id = (entityRecords.size())
1182fbc6c9d7SPatrick Williams                                   ? entityRecords.begin()->first +
1183fbc6c9d7SPatrick Williams                                         ENTITY_RECORD_ID_START
11849c11894eSJaghathiswari Rankappagounder Natarajan                                   : END_OF_RECORD;
11859c11894eSJaghathiswari Rankappagounder Natarajan         get_sdr::response::set_next_record_id(next_record_id, resp);
11869c11894eSJaghathiswari Rankappagounder Natarajan     }
11879c11894eSJaghathiswari Rankappagounder Natarajan     else
11889c11894eSJaghathiswari Rankappagounder Natarajan     {
11899c11894eSJaghathiswari Rankappagounder Natarajan         get_sdr::response::set_next_record_id(
11909c11894eSJaghathiswari Rankappagounder Natarajan             (FRU_RECORD_ID_START + fru->first), resp);
11919c11894eSJaghathiswari Rankappagounder Natarajan     }
11929c11894eSJaghathiswari Rankappagounder Natarajan 
11939c11894eSJaghathiswari Rankappagounder Natarajan     // Check for invalid offset size
11949c11894eSJaghathiswari Rankappagounder Natarajan     if (req->offset > sizeof(record))
11959c11894eSJaghathiswari Rankappagounder Natarajan     {
11969c11894eSJaghathiswari Rankappagounder Natarajan         return IPMI_CC_PARM_OUT_OF_RANGE;
11979c11894eSJaghathiswari Rankappagounder Natarajan     }
11989c11894eSJaghathiswari Rankappagounder Natarajan 
11999c11894eSJaghathiswari Rankappagounder Natarajan     dataLength = std::min(static_cast<size_t>(req->bytes_to_read),
12009c11894eSJaghathiswari Rankappagounder Natarajan                           sizeof(record) - req->offset);
12019c11894eSJaghathiswari Rankappagounder Natarajan 
12029c11894eSJaghathiswari Rankappagounder Natarajan     std::memcpy(resp->record_data,
12039c11894eSJaghathiswari Rankappagounder Natarajan                 reinterpret_cast<uint8_t*>(&record) + req->offset, dataLength);
12049c11894eSJaghathiswari Rankappagounder Natarajan 
12059c11894eSJaghathiswari Rankappagounder Natarajan     *data_len = dataLength;
12069c11894eSJaghathiswari Rankappagounder Natarajan     *data_len += 2; // additional 2 bytes for next record ID
12079c11894eSJaghathiswari Rankappagounder Natarajan 
12089c11894eSJaghathiswari Rankappagounder Natarajan     return IPMI_CC_OK;
12099c11894eSJaghathiswari Rankappagounder Natarajan }
12109c11894eSJaghathiswari Rankappagounder Natarajan 
ipmi_entity_get_sdr(ipmi_request_t request,ipmi_response_t response,ipmi_data_len_t data_len)12119c11894eSJaghathiswari Rankappagounder Natarajan ipmi_ret_t ipmi_entity_get_sdr(ipmi_request_t request, ipmi_response_t response,
12129c11894eSJaghathiswari Rankappagounder Natarajan                                ipmi_data_len_t data_len)
12139c11894eSJaghathiswari Rankappagounder Natarajan {
12149c11894eSJaghathiswari Rankappagounder Natarajan     auto req = reinterpret_cast<get_sdr::GetSdrReq*>(request);
12159c11894eSJaghathiswari Rankappagounder Natarajan     auto resp = reinterpret_cast<get_sdr::GetSdrResp*>(response);
12169c11894eSJaghathiswari Rankappagounder Natarajan     get_sdr::SensorDataEntityRecord record{};
12179c11894eSJaghathiswari Rankappagounder Natarajan     auto dataLength = 0;
12189c11894eSJaghathiswari Rankappagounder Natarajan 
121987fd2cd1SPatrick Venture     const auto& entityRecords =
122087fd2cd1SPatrick Venture         ipmi::sensor::EntityInfoMapContainer::getContainer()
122187fd2cd1SPatrick Venture             ->getIpmiEntityRecords();
122283a0b848SPatrick Venture     auto entity = entityRecords.begin();
12239c11894eSJaghathiswari Rankappagounder Natarajan     uint8_t entityRecordID;
12249c11894eSJaghathiswari Rankappagounder Natarajan     auto recordID = get_sdr::request::get_record_id(req);
12259c11894eSJaghathiswari Rankappagounder Natarajan 
12269c11894eSJaghathiswari Rankappagounder Natarajan     entityRecordID = recordID - ENTITY_RECORD_ID_START;
122783a0b848SPatrick Venture     entity = entityRecords.find(entityRecordID);
122883a0b848SPatrick Venture     if (entity == entityRecords.end())
12299c11894eSJaghathiswari Rankappagounder Natarajan     {
12309c11894eSJaghathiswari Rankappagounder Natarajan         return IPMI_CC_SENSOR_INVALID;
12319c11894eSJaghathiswari Rankappagounder Natarajan     }
12329c11894eSJaghathiswari Rankappagounder Natarajan 
12339c11894eSJaghathiswari Rankappagounder Natarajan     /* Header */
12349c11894eSJaghathiswari Rankappagounder Natarajan     get_sdr::header::set_record_id(recordID, &(record.header));
12359c11894eSJaghathiswari Rankappagounder Natarajan     record.header.sdr_version = SDR_VERSION; // Based on IPMI Spec v2.0 rev 1.1
12369c11894eSJaghathiswari Rankappagounder Natarajan     record.header.record_type = get_sdr::SENSOR_DATA_ENTITY_RECORD;
12379c11894eSJaghathiswari Rankappagounder Natarajan     record.header.record_length = sizeof(record.key) + sizeof(record.body);
12389c11894eSJaghathiswari Rankappagounder Natarajan 
12399c11894eSJaghathiswari Rankappagounder Natarajan     /* Key */
12409c11894eSJaghathiswari Rankappagounder Natarajan     record.key.containerEntityId = entity->second.containerEntityId;
12419c11894eSJaghathiswari Rankappagounder Natarajan     record.key.containerEntityInstance = entity->second.containerEntityInstance;
12429c11894eSJaghathiswari Rankappagounder Natarajan     get_sdr::key::set_flags(entity->second.isList, entity->second.isLinked,
12439c11894eSJaghathiswari Rankappagounder Natarajan                             &(record.key));
12449c11894eSJaghathiswari Rankappagounder Natarajan     record.key.entityId1 = entity->second.containedEntities[0].first;
12459c11894eSJaghathiswari Rankappagounder Natarajan     record.key.entityInstance1 = entity->second.containedEntities[0].second;
12469c11894eSJaghathiswari Rankappagounder Natarajan 
12479c11894eSJaghathiswari Rankappagounder Natarajan     /* Body */
12489c11894eSJaghathiswari Rankappagounder Natarajan     record.body.entityId2 = entity->second.containedEntities[1].first;
12499c11894eSJaghathiswari Rankappagounder Natarajan     record.body.entityInstance2 = entity->second.containedEntities[1].second;
12509c11894eSJaghathiswari Rankappagounder Natarajan     record.body.entityId3 = entity->second.containedEntities[2].first;
12519c11894eSJaghathiswari Rankappagounder Natarajan     record.body.entityInstance3 = entity->second.containedEntities[2].second;
12529c11894eSJaghathiswari Rankappagounder Natarajan     record.body.entityId4 = entity->second.containedEntities[3].first;
12539c11894eSJaghathiswari Rankappagounder Natarajan     record.body.entityInstance4 = entity->second.containedEntities[3].second;
12549c11894eSJaghathiswari Rankappagounder Natarajan 
125583a0b848SPatrick Venture     if (++entity == entityRecords.end())
12569c11894eSJaghathiswari Rankappagounder Natarajan     {
12570b02be92SPatrick Venture         get_sdr::response::set_next_record_id(END_OF_RECORD,
12580b02be92SPatrick Venture                                               resp); // last record
1259e0cc8553SRatan Gupta     }
1260e0cc8553SRatan Gupta     else
1261e0cc8553SRatan Gupta     {
1262e0cc8553SRatan Gupta         get_sdr::response::set_next_record_id(
12639c11894eSJaghathiswari Rankappagounder Natarajan             (ENTITY_RECORD_ID_START + entity->first), resp);
1264e0cc8553SRatan Gupta     }
1265e0cc8553SRatan Gupta 
12660fbdbce2SEmily Shaffer     // Check for invalid offset size
12670fbdbce2SEmily Shaffer     if (req->offset > sizeof(record))
1268e0cc8553SRatan Gupta     {
12690fbdbce2SEmily Shaffer         return IPMI_CC_PARM_OUT_OF_RANGE;
1270e0cc8553SRatan Gupta     }
1271e0cc8553SRatan Gupta 
12720fbdbce2SEmily Shaffer     dataLength = std::min(static_cast<size_t>(req->bytes_to_read),
12730fbdbce2SEmily Shaffer                           sizeof(record) - req->offset);
1274e0cc8553SRatan Gupta 
1275b51bf9c8SPatrick Venture     std::memcpy(resp->record_data,
12761cd85963SJason M. Bills                 reinterpret_cast<uint8_t*>(&record) + req->offset, dataLength);
1277e0cc8553SRatan Gupta 
1278e0cc8553SRatan Gupta     *data_len = dataLength;
1279e0cc8553SRatan Gupta     *data_len += 2; // additional 2 bytes for next record ID
1280e0cc8553SRatan Gupta 
1281e0cc8553SRatan Gupta     return IPMI_CC_OK;
1282e0cc8553SRatan Gupta }
1283e0cc8553SRatan Gupta 
ipmi_sen_get_sdr(ipmi_netfn_t,ipmi_cmd_t,ipmi_request_t request,ipmi_response_t response,ipmi_data_len_t data_len,ipmi_context_t)128411d68897SWilly Tu ipmi_ret_t ipmi_sen_get_sdr(ipmi_netfn_t, ipmi_cmd_t, ipmi_request_t request,
128511d68897SWilly Tu                             ipmi_response_t response, ipmi_data_len_t data_len,
128611d68897SWilly Tu                             ipmi_context_t)
1287bbef71c2SEmily Shaffer {
1288bbef71c2SEmily Shaffer     ipmi_ret_t ret = IPMI_CC_OK;
1289bbef71c2SEmily Shaffer     get_sdr::GetSdrReq* req = (get_sdr::GetSdrReq*)request;
1290bbef71c2SEmily Shaffer     get_sdr::GetSdrResp* resp = (get_sdr::GetSdrResp*)response;
129138426dd5SPatrick Venture 
1292bbef71c2SEmily Shaffer     // Note: we use an iterator so we can provide the next ID at the end of
1293bbef71c2SEmily Shaffer     // the call.
1294db0cbe64SPatrick Venture     auto sensor = ipmi::sensor::sensors.begin();
1295e0cc8553SRatan Gupta     auto recordID = get_sdr::request::get_record_id(req);
1296bbef71c2SEmily Shaffer 
1297bbef71c2SEmily Shaffer     // At the beginning of a scan, the host side will send us id=0.
1298e0cc8553SRatan Gupta     if (recordID != 0)
1299bbef71c2SEmily Shaffer     {
13009c11894eSJaghathiswari Rankappagounder Natarajan         // recordID 0 to 255 means it is a FULL record.
13019c11894eSJaghathiswari Rankappagounder Natarajan         // recordID 256 to 511 means it is a FRU record.
13029c11894eSJaghathiswari Rankappagounder Natarajan         // recordID greater then 511 means it is a Entity Association
13039c11894eSJaghathiswari Rankappagounder Natarajan         // record. Currently we are supporting three record types: FULL
13049c11894eSJaghathiswari Rankappagounder Natarajan         // record, FRU record and Enttiy Association record.
13059c11894eSJaghathiswari Rankappagounder Natarajan         if (recordID >= ENTITY_RECORD_ID_START)
13069c11894eSJaghathiswari Rankappagounder Natarajan         {
13079c11894eSJaghathiswari Rankappagounder Natarajan             return ipmi_entity_get_sdr(request, response, data_len);
13089c11894eSJaghathiswari Rankappagounder Natarajan         }
13099c11894eSJaghathiswari Rankappagounder Natarajan         else if (recordID >= FRU_RECORD_ID_START &&
13109c11894eSJaghathiswari Rankappagounder Natarajan                  recordID < ENTITY_RECORD_ID_START)
1311e0cc8553SRatan Gupta         {
1312e0cc8553SRatan Gupta             return ipmi_fru_get_sdr(request, response, data_len);
1313e0cc8553SRatan Gupta         }
1314e0cc8553SRatan Gupta         else
1315e0cc8553SRatan Gupta         {
1316db0cbe64SPatrick Venture             sensor = ipmi::sensor::sensors.find(recordID);
1317db0cbe64SPatrick Venture             if (sensor == ipmi::sensor::sensors.end())
1318e0cc8553SRatan Gupta             {
1319bbef71c2SEmily Shaffer                 return IPMI_CC_SENSOR_INVALID;
1320bbef71c2SEmily Shaffer             }
1321bbef71c2SEmily Shaffer         }
1322e0cc8553SRatan Gupta     }
1323bbef71c2SEmily Shaffer 
1324bbef71c2SEmily Shaffer     uint8_t sensor_id = sensor->first;
1325bbef71c2SEmily Shaffer 
132614a47819SLei YU     auto it = sdrCacheMap.find(sensor_id);
132714a47819SLei YU     if (it == sdrCacheMap.end())
132814a47819SLei YU     {
1329bbef71c2SEmily Shaffer         /* Header */
133011d68897SWilly Tu         get_sdr::SensorDataFullRecord record = {};
1331bbef71c2SEmily Shaffer         get_sdr::header::set_record_id(sensor_id, &(record.header));
1332bbef71c2SEmily Shaffer         record.header.sdr_version = 0x51; // Based on IPMI Spec v2.0 rev 1.1
1333bbef71c2SEmily Shaffer         record.header.record_type = get_sdr::SENSOR_DATA_FULL_RECORD;
1334158ac703SPatrick Venture         record.header.record_length = sizeof(record.key) + sizeof(record.body);
1335bbef71c2SEmily Shaffer 
1336bbef71c2SEmily Shaffer         /* Key */
13379642391dSTom Joseph         get_sdr::key::set_owner_id_bmc(&(record.key));
1338bbef71c2SEmily Shaffer         record.key.sensor_number = sensor_id;
1339bbef71c2SEmily Shaffer 
1340bbef71c2SEmily Shaffer         /* Body */
13419642391dSTom Joseph         record.body.entity_id = sensor->second.entityType;
1342bbef71c2SEmily Shaffer         record.body.sensor_type = sensor->second.sensorType;
1343bbef71c2SEmily Shaffer         record.body.event_reading_type = sensor->second.sensorReadingType;
13449642391dSTom Joseph         record.body.entity_instance = sensor->second.instance;
13450780df10SJaghathiswari Rankappagounder Natarajan         if (ipmi::sensor::Mutability::Write ==
13460780df10SJaghathiswari Rankappagounder Natarajan             (sensor->second.mutability & ipmi::sensor::Mutability::Write))
13470780df10SJaghathiswari Rankappagounder Natarajan         {
13480780df10SJaghathiswari Rankappagounder Natarajan             get_sdr::body::init_settable_state(true, &(record.body));
13490780df10SJaghathiswari Rankappagounder Natarajan         }
1350bbef71c2SEmily Shaffer 
1351bbef71c2SEmily Shaffer         // Set the type-specific details given the DBus interface
135238426dd5SPatrick Venture         populate_record_from_dbus(&(record.body), &(sensor->second), data_len);
135314a47819SLei YU         sdrCacheMap[sensor_id] = std::move(record);
135414a47819SLei YU     }
135514a47819SLei YU 
135614a47819SLei YU     const auto& record = sdrCacheMap[sensor_id];
1357bbef71c2SEmily Shaffer 
1358db0cbe64SPatrick Venture     if (++sensor == ipmi::sensor::sensors.end())
1359bbef71c2SEmily Shaffer     {
1360e0cc8553SRatan Gupta         // we have reached till end of sensor, so assign the next record id
1361e0cc8553SRatan Gupta         // to 256(Max Sensor ID = 255) + FRU ID(may start with 0).
136238426dd5SPatrick Venture         auto next_record_id = (frus.size())
136338426dd5SPatrick Venture                                   ? frus.begin()->first + FRU_RECORD_ID_START
13640b02be92SPatrick Venture                                   : END_OF_RECORD;
1365e0cc8553SRatan Gupta 
1366e0cc8553SRatan Gupta         get_sdr::response::set_next_record_id(next_record_id, resp);
1367bbef71c2SEmily Shaffer     }
1368bbef71c2SEmily Shaffer     else
1369bbef71c2SEmily Shaffer     {
1370bbef71c2SEmily Shaffer         get_sdr::response::set_next_record_id(sensor->first, resp);
1371bbef71c2SEmily Shaffer     }
1372bbef71c2SEmily Shaffer 
13736c9ee519SEmily Shaffer     if (req->offset > sizeof(record))
13746c9ee519SEmily Shaffer     {
13756c9ee519SEmily Shaffer         return IPMI_CC_PARM_OUT_OF_RANGE;
13766c9ee519SEmily Shaffer     }
13776c9ee519SEmily Shaffer 
13786c9ee519SEmily Shaffer     // data_len will ultimately be the size of the record, plus
13796c9ee519SEmily Shaffer     // the size of the next record ID:
13806c9ee519SEmily Shaffer     *data_len = std::min(static_cast<size_t>(req->bytes_to_read),
13816c9ee519SEmily Shaffer                          sizeof(record) - req->offset);
13826c9ee519SEmily Shaffer 
13836c9ee519SEmily Shaffer     std::memcpy(resp->record_data,
138414a47819SLei YU                 reinterpret_cast<const uint8_t*>(&record) + req->offset,
138514a47819SLei YU                 *data_len);
13866c9ee519SEmily Shaffer 
13876c9ee519SEmily Shaffer     // data_len should include the LSB and MSB:
1388fbc6c9d7SPatrick Williams     *data_len += sizeof(resp->next_record_id_lsb) +
1389fbc6c9d7SPatrick Williams                  sizeof(resp->next_record_id_msb);
1390bbef71c2SEmily Shaffer 
1391bbef71c2SEmily Shaffer     return ret;
1392bbef71c2SEmily Shaffer }
1393bbef71c2SEmily Shaffer 
isFromSystemChannel()13943342a8e0SJia, Chunhui static bool isFromSystemChannel()
13953342a8e0SJia, Chunhui {
13963342a8e0SJia, Chunhui     // TODO we could not figure out where the request is from based on IPMI
13973342a8e0SJia, Chunhui     // command handler parameters. because of it, we can not differentiate
13983342a8e0SJia, Chunhui     // request from SMS/SMM or IPMB channel
13993342a8e0SJia, Chunhui     return true;
14003342a8e0SJia, Chunhui }
14013342a8e0SJia, Chunhui 
ipmicmdPlatformEvent(ipmi_netfn_t,ipmi_cmd_t,ipmi_request_t request,ipmi_response_t,ipmi_data_len_t dataLen,ipmi_context_t)140211d68897SWilly Tu ipmi_ret_t ipmicmdPlatformEvent(ipmi_netfn_t, ipmi_cmd_t,
140311d68897SWilly Tu                                 ipmi_request_t request, ipmi_response_t,
140411d68897SWilly Tu                                 ipmi_data_len_t dataLen, ipmi_context_t)
14053342a8e0SJia, Chunhui {
14063342a8e0SJia, Chunhui     uint16_t generatorID;
14073342a8e0SJia, Chunhui     size_t count;
14083342a8e0SJia, Chunhui     bool assert = true;
14093342a8e0SJia, Chunhui     std::string sensorPath;
14103342a8e0SJia, Chunhui     size_t paraLen = *dataLen;
14113342a8e0SJia, Chunhui     PlatformEventRequest* req;
14123342a8e0SJia, Chunhui     *dataLen = 0;
14133342a8e0SJia, Chunhui 
14143342a8e0SJia, Chunhui     if ((paraLen < selSystemEventSizeWith1Bytes) ||
14153342a8e0SJia, Chunhui         (paraLen > selSystemEventSizeWith3Bytes))
14163342a8e0SJia, Chunhui     {
14173342a8e0SJia, Chunhui         return IPMI_CC_REQ_DATA_LEN_INVALID;
14183342a8e0SJia, Chunhui     }
14193342a8e0SJia, Chunhui 
14203342a8e0SJia, Chunhui     if (isFromSystemChannel())
14213342a8e0SJia, Chunhui     { // first byte for SYSTEM Interface is Generator ID
14223342a8e0SJia, Chunhui         // +1 to get common struct
14233342a8e0SJia, Chunhui         req = reinterpret_cast<PlatformEventRequest*>((uint8_t*)request + 1);
14243342a8e0SJia, Chunhui         // Capture the generator ID
14253342a8e0SJia, Chunhui         generatorID = *reinterpret_cast<uint8_t*>(request);
14263342a8e0SJia, Chunhui         // Platform Event usually comes from other firmware, like BIOS.
14273342a8e0SJia, Chunhui         // Unlike BMC sensor, it does not have BMC DBUS sensor path.
14283342a8e0SJia, Chunhui         sensorPath = "System";
14293342a8e0SJia, Chunhui     }
14303342a8e0SJia, Chunhui     else
14313342a8e0SJia, Chunhui     {
14323342a8e0SJia, Chunhui         req = reinterpret_cast<PlatformEventRequest*>(request);
14333342a8e0SJia, Chunhui         // TODO GenratorID for IPMB is combination of RqSA and RqLUN
14343342a8e0SJia, Chunhui         generatorID = 0xff;
14353342a8e0SJia, Chunhui         sensorPath = "IPMB";
14363342a8e0SJia, Chunhui     }
14373342a8e0SJia, Chunhui     // Content of event data field depends on sensor class.
14383342a8e0SJia, Chunhui     // When data0 bit[5:4] is non-zero, valid data counts is 3.
14393342a8e0SJia, Chunhui     // When data0 bit[7:6] is non-zero, valid data counts is 2.
14403342a8e0SJia, Chunhui     if (((req->data[0] & byte3EnableMask) != 0 &&
14413342a8e0SJia, Chunhui          paraLen < selSystemEventSizeWith3Bytes) ||
14423342a8e0SJia, Chunhui         ((req->data[0] & byte2EnableMask) != 0 &&
14433342a8e0SJia, Chunhui          paraLen < selSystemEventSizeWith2Bytes))
14443342a8e0SJia, Chunhui     {
14453342a8e0SJia, Chunhui         return IPMI_CC_REQ_DATA_LEN_INVALID;
14463342a8e0SJia, Chunhui     }
14473342a8e0SJia, Chunhui 
14483342a8e0SJia, Chunhui     // Count bytes of Event Data
14493342a8e0SJia, Chunhui     if ((req->data[0] & byte3EnableMask) != 0)
14503342a8e0SJia, Chunhui     {
14513342a8e0SJia, Chunhui         count = 3;
14523342a8e0SJia, Chunhui     }
14533342a8e0SJia, Chunhui     else if ((req->data[0] & byte2EnableMask) != 0)
14543342a8e0SJia, Chunhui     {
14553342a8e0SJia, Chunhui         count = 2;
14563342a8e0SJia, Chunhui     }
14573342a8e0SJia, Chunhui     else
14583342a8e0SJia, Chunhui     {
14593342a8e0SJia, Chunhui         count = 1;
14603342a8e0SJia, Chunhui     }
14613342a8e0SJia, Chunhui     assert = req->eventDirectionType & directionMask ? false : true;
14623342a8e0SJia, Chunhui     std::vector<uint8_t> eventData(req->data, req->data + count);
14633342a8e0SJia, Chunhui 
14645d82f474SPatrick Williams     sdbusplus::bus_t dbus(bus);
1465fbc6c9d7SPatrick Williams     std::string service = ipmi::getService(dbus, ipmiSELAddInterface,
1466fbc6c9d7SPatrick Williams                                            ipmiSELPath);
14675d82f474SPatrick Williams     sdbusplus::message_t writeSEL = dbus.new_method_call(
14683342a8e0SJia, Chunhui         service.c_str(), ipmiSELPath, ipmiSELAddInterface, "IpmiSelAdd");
14693342a8e0SJia, Chunhui     writeSEL.append(ipmiSELAddMessage, sensorPath, eventData, assert,
14703342a8e0SJia, Chunhui                     generatorID);
14713342a8e0SJia, Chunhui     try
14723342a8e0SJia, Chunhui     {
14733342a8e0SJia, Chunhui         dbus.call(writeSEL);
14743342a8e0SJia, Chunhui     }
1475a2ad2da8SPatrick Williams     catch (const sdbusplus::exception_t& e)
14763342a8e0SJia, Chunhui     {
14773342a8e0SJia, Chunhui         phosphor::logging::log<phosphor::logging::level::ERR>(e.what());
14783342a8e0SJia, Chunhui         return IPMI_CC_UNSPECIFIED_ERROR;
14793342a8e0SJia, Chunhui     }
14803342a8e0SJia, Chunhui     return IPMI_CC_OK;
14813342a8e0SJia, Chunhui }
14823342a8e0SJia, Chunhui 
register_netfn_sen_functions()148398a23840SMatthew Barth void register_netfn_sen_functions()
148498a23840SMatthew Barth {
1485d351a729SWilly Tu     // Handlers with dbus-sdr handler implementation.
1486d351a729SWilly Tu     // Do not register the hander if it dynamic sensors stack is used.
1487a8be7dc8SDeepak Kumar Sahu 
1488d351a729SWilly Tu #ifndef FEATURE_DYNAMIC_SENSORS
1489be5c6b2aSLei YU 
1490962e68baSLei YU #ifdef FEATURE_SENSORS_CACHE
1491be5c6b2aSLei YU     // Initialize the sensor matches
1492be5c6b2aSLei YU     initSensorMatches();
1493962e68baSLei YU #endif
1494be5c6b2aSLei YU 
14950573237fSTom     // <Set Sensor Reading and Event Status>
14969da3a750SDeepak Kumar Sahu     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnSensor,
14979da3a750SDeepak Kumar Sahu                           ipmi::sensor_event::cmdSetSensorReadingAndEvtSts,
14989da3a750SDeepak Kumar Sahu                           ipmi::Privilege::Operator, ipmiSetSensorReading);
14990573237fSTom     // <Get Sensor Reading>
15004c3feba5Sjayaprakash Mutyala     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnSensor,
15014c3feba5Sjayaprakash Mutyala                           ipmi::sensor_event::cmdGetSensorReading,
15024c3feba5Sjayaprakash Mutyala                           ipmi::Privilege::User, ipmiSensorGetSensorReading);
1503a344afc0SEmily Shaffer 
15045ca50959STom Joseph     // <Reserve Device SDR Repository>
1505d957823eSjayaprakash Mutyala     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnSensor,
1506d957823eSjayaprakash Mutyala                           ipmi::sensor_event::cmdReserveDeviceSdrRepository,
1507d957823eSjayaprakash Mutyala                           ipmi::Privilege::User, ipmiSensorReserveSdr);
150898a23840SMatthew Barth 
15095ca50959STom Joseph     // <Get Device SDR Info>
1510d957823eSjayaprakash Mutyala     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnSensor,
1511d957823eSjayaprakash Mutyala                           ipmi::sensor_event::cmdGetDeviceSdrInfo,
1512d957823eSjayaprakash Mutyala                           ipmi::Privilege::User, ipmiSensorGetDeviceSdrInfo);
1513bbef71c2SEmily Shaffer 
15145c0beec1SDhruvaraj Subhashchandran     // <Get Sensor Thresholds>
1515996c9798Sjayaprakash Mutyala     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnSensor,
1516996c9798Sjayaprakash Mutyala                           ipmi::sensor_event::cmdGetSensorThreshold,
1517996c9798Sjayaprakash Mutyala                           ipmi::Privilege::User, ipmiSensorGetSensorThresholds);
15185c0beec1SDhruvaraj Subhashchandran 
1519f93da667SLotus Xu     // <Set Sensor Thresholds>
1520f93da667SLotus Xu     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnSensor,
1521f93da667SLotus Xu                           ipmi::sensor_event::cmdSetSensorThreshold,
1522f93da667SLotus Xu                           ipmi::Privilege::User, ipmiSenSetSensorThresholds);
1523d3d2fe29SVivekanand Veeracholan 
1524d3d2fe29SVivekanand Veeracholan     // <Get Device SDR>
1525d3d2fe29SVivekanand Veeracholan     ipmi_register_callback(NETFUN_SENSOR, IPMI_CMD_GET_DEVICE_SDR, nullptr,
1526d3d2fe29SVivekanand Veeracholan                            ipmi_sen_get_sdr, PRIVILEGE_USER);
1527d3d2fe29SVivekanand Veeracholan 
1528d351a729SWilly Tu #endif
1529d351a729SWilly Tu 
1530d351a729SWilly Tu     // Common Handers used by both implementation.
1531d351a729SWilly Tu 
1532d351a729SWilly Tu     // <Platform Event Message>
1533d351a729SWilly Tu     ipmi_register_callback(NETFUN_SENSOR, IPMI_CMD_PLATFORM_EVENT, nullptr,
1534d351a729SWilly Tu                            ipmicmdPlatformEvent, PRIVILEGE_OPERATOR);
1535d351a729SWilly Tu 
1536d351a729SWilly Tu     // <Get Sensor Type>
1537d351a729SWilly Tu     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnSensor,
1538d351a729SWilly Tu                           ipmi::sensor_event::cmdGetSensorType,
1539d351a729SWilly Tu                           ipmi::Privilege::User, ipmiGetSensorType);
1540d351a729SWilly Tu 
154198a23840SMatthew Barth     return;
154298a23840SMatthew Barth }
1543