xref: /openbmc/phosphor-host-ipmid/sensorhandler.cpp (revision a6fb32d899c7b6c19201fc0d4ab7417a47958e33)
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>
143b1071adSGeorge Liu #include <phosphor-logging/lg2.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 
455087b075SGeorge Liu void registerNetFnSenFunctions() __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(
1691318a5edSPatrick Williams             s.first,
1701318a5edSPatrick Williams             std::make_unique<sdbusplus::bus::match_t>(
171be5c6b2aSLei YU                 bus,
172be5c6b2aSLei YU                 type::signal() + path(s.second.sensorPath) +
173be5c6b2aSLei YU                     member("PropertiesChanged"s) +
174be5c6b2aSLei YU                     interface("org.freedesktop.DBus.Properties"s),
1759714050fSLei YU                 [&s](auto& msg) {
1761318a5edSPatrick Williams                     fillSensorIdServiceMap(
1771318a5edSPatrick Williams                         s.second.sensorPath,
1781318a5edSPatrick Williams                         s.second.propertyInterfaces.begin()->first, s.first);
1799714050fSLei YU                     try
1809714050fSLei YU                     {
1818e8152c5SLei YU                         // This is signal callback
1828e8152c5SLei YU                         std::string interfaceName;
1838e8152c5SLei YU                         msg.read(interfaceName);
1848e8152c5SLei YU                         ipmi::PropertyMap props;
1858e8152c5SLei YU                         msg.read(props);
1868e8152c5SLei YU                         s.second.getFunc(s.first, s.second, props);
1879714050fSLei YU                     }
1889714050fSLei YU                     catch (const std::exception& e)
1899714050fSLei YU                     {
1909714050fSLei YU                         sensorCacheMap[s.first].reset();
1919714050fSLei YU                     }
192be5c6b2aSLei YU                 }));
1934a105cd6SJian Zhang     }
1945d82f474SPatrick Williams     sensorsOwnerMatch = std::make_unique<sdbusplus::bus::match_t>(
1957f3a70f0SLei YU         bus, nameOwnerChanged(), [](auto& msg) {
1967f3a70f0SLei YU             std::string name;
1977f3a70f0SLei YU             std::string oldOwner;
1987f3a70f0SLei YU             std::string newOwner;
1997f3a70f0SLei YU             msg.read(name, oldOwner, newOwner);
2007f3a70f0SLei YU 
2017f3a70f0SLei YU             if (!name.empty() && newOwner.empty())
2027f3a70f0SLei YU             {
2037f3a70f0SLei YU                 // The service exits
2047f3a70f0SLei YU                 const auto it = serviceToIdMap.find(name);
2057f3a70f0SLei YU                 if (it == serviceToIdMap.end())
2067f3a70f0SLei YU                 {
2077f3a70f0SLei YU                     return;
2087f3a70f0SLei YU                 }
2097f3a70f0SLei YU                 for (const auto& id : it->second)
2107f3a70f0SLei YU                 {
2117f3a70f0SLei YU                     // Invalidate cache
2127f3a70f0SLei YU                     sensorCacheMap[id].reset();
2137f3a70f0SLei YU                 }
2147f3a70f0SLei YU             }
2157f3a70f0SLei YU         });
216be5c6b2aSLei YU }
217962e68baSLei YU #endif
218be5c6b2aSLei YU 
2192ae09b9aSEmily Shaffer // Use a lookup table to find the interface name of a specific sensor
2202ae09b9aSEmily Shaffer // This will be used until an alternative is found.  this is the first
2212ae09b9aSEmily Shaffer // step for mapping IPMI
find_openbmc_path(uint8_t num,dbus_interface_t * interface)2220b02be92SPatrick Venture int find_openbmc_path(uint8_t num, dbus_interface_t* interface)
2230b02be92SPatrick Venture {
224db0cbe64SPatrick Venture     const auto& sensor_it = ipmi::sensor::sensors.find(num);
225db0cbe64SPatrick Venture     if (sensor_it == ipmi::sensor::sensors.end())
2262ae09b9aSEmily Shaffer     {
227ba23ff71SAdriana Kobylak         // The sensor map does not contain the sensor requested
228ba23ff71SAdriana Kobylak         return -EINVAL;
2292ae09b9aSEmily Shaffer     }
2302ae09b9aSEmily Shaffer 
2312ae09b9aSEmily Shaffer     const auto& info = sensor_it->second;
2322ae09b9aSEmily Shaffer 
233a008871dSGeorge Liu     std::string serviceName{};
234a008871dSGeorge Liu     try
235a008871dSGeorge Liu     {
236a008871dSGeorge Liu         sdbusplus::bus_t bus{ipmid_get_sd_bus_connection()};
2371318a5edSPatrick Williams         serviceName =
2381318a5edSPatrick Williams             ipmi::getService(bus, info.sensorInterface, info.sensorPath);
239a008871dSGeorge Liu     }
240a008871dSGeorge Liu     catch (const sdbusplus::exception_t&)
2410b02be92SPatrick Venture     {
242b51bf9c8SPatrick Venture         std::fprintf(stderr, "Failed to get %s busname: %s\n",
243a008871dSGeorge Liu                      info.sensorPath.c_str(), serviceName.c_str());
244a008871dSGeorge Liu         return -EINVAL;
2452ae09b9aSEmily Shaffer     }
2462ae09b9aSEmily Shaffer 
2472ae09b9aSEmily Shaffer     interface->sensortype = info.sensorType;
248a008871dSGeorge Liu     strcpy(interface->bus, serviceName.c_str());
2492ae09b9aSEmily Shaffer     strcpy(interface->path, info.sensorPath.c_str());
2502ae09b9aSEmily Shaffer     // Take the interface name from the beginning of the DbusInterfaceMap. This
2512ae09b9aSEmily Shaffer     // works for the Value interface but may not suffice for more complex
2522ae09b9aSEmily Shaffer     // sensors.
2532ae09b9aSEmily Shaffer     // tracked https://github.com/openbmc/phosphor-host-ipmid/issues/103
2540b02be92SPatrick Venture     strcpy(interface->interface,
2550b02be92SPatrick Venture            info.propertyInterfaces.begin()->first.c_str());
2562ae09b9aSEmily Shaffer     interface->sensornumber = num;
2572ae09b9aSEmily Shaffer 
258a008871dSGeorge Liu     return 0;
2592ae09b9aSEmily Shaffer }
2602ae09b9aSEmily Shaffer 
261d700e76aSTom /////////////////////////////////////////////////////////////////////
262d700e76aSTom //
263d700e76aSTom // Routines used by ipmi commands wanting to interact on the dbus
264d700e76aSTom //
265d700e76aSTom /////////////////////////////////////////////////////////////////////
set_sensor_dbus_state_s(uint8_t number,const char * method,const char * value)2660b02be92SPatrick Venture int set_sensor_dbus_state_s(uint8_t number, const char* method,
2670b02be92SPatrick Venture                             const char* value)
2680b02be92SPatrick Venture {
269d700e76aSTom     dbus_interface_t a;
270d700e76aSTom     int r;
271d700e76aSTom     sd_bus_error error = SD_BUS_ERROR_NULL;
272*a6fb32d8SJayanth Othayoth     sd_bus_message* m = nullptr;
273d700e76aSTom 
2742ae09b9aSEmily Shaffer     r = find_openbmc_path(number, &a);
275d700e76aSTom 
2760b02be92SPatrick Venture     if (r < 0)
2770b02be92SPatrick Venture     {
278b51bf9c8SPatrick Venture         std::fprintf(stderr, "Failed to find Sensor 0x%02x\n", number);
279d700e76aSTom         return 0;
280d700e76aSTom     }
281d700e76aSTom 
2820b02be92SPatrick Venture     r = sd_bus_message_new_method_call(bus, &m, a.bus, a.path, a.interface,
2830b02be92SPatrick Venture                                        method);
2840b02be92SPatrick Venture     if (r < 0)
2850b02be92SPatrick Venture     {
286b51bf9c8SPatrick Venture         std::fprintf(stderr, "Failed to create a method call: %s",
287b51bf9c8SPatrick Venture                      strerror(-r));
288d700e76aSTom         goto final;
289d700e76aSTom     }
290d700e76aSTom 
291d700e76aSTom     r = sd_bus_message_append(m, "v", "s", value);
2920b02be92SPatrick Venture     if (r < 0)
2930b02be92SPatrick Venture     {
294b51bf9c8SPatrick Venture         std::fprintf(stderr, "Failed to create a input parameter: %s",
295b51bf9c8SPatrick Venture                      strerror(-r));
296d700e76aSTom         goto final;
297d700e76aSTom     }
298d700e76aSTom 
299*a6fb32d8SJayanth Othayoth     r = sd_bus_call(bus, m, 0, &error, nullptr);
3000b02be92SPatrick Venture     if (r < 0)
3010b02be92SPatrick Venture     {
302b51bf9c8SPatrick Venture         std::fprintf(stderr, "Failed to call the method: %s", strerror(-r));
303d700e76aSTom     }
304d700e76aSTom 
305d700e76aSTom final:
306d700e76aSTom     sd_bus_error_free(&error);
307d700e76aSTom     m = sd_bus_message_unref(m);
308d700e76aSTom 
309d700e76aSTom     return 0;
310d700e76aSTom }
set_sensor_dbus_state_y(uint8_t number,const char * method,const uint8_t value)3110b02be92SPatrick Venture int set_sensor_dbus_state_y(uint8_t number, const char* method,
3120b02be92SPatrick Venture                             const uint8_t value)
3130b02be92SPatrick Venture {
314d700e76aSTom     dbus_interface_t a;
315d700e76aSTom     int r;
316d700e76aSTom     sd_bus_error error = SD_BUS_ERROR_NULL;
317*a6fb32d8SJayanth Othayoth     sd_bus_message* m = nullptr;
318d700e76aSTom 
3192ae09b9aSEmily Shaffer     r = find_openbmc_path(number, &a);
320d700e76aSTom 
3210b02be92SPatrick Venture     if (r < 0)
3220b02be92SPatrick Venture     {
323b51bf9c8SPatrick Venture         std::fprintf(stderr, "Failed to find Sensor 0x%02x\n", number);
324d700e76aSTom         return 0;
325d700e76aSTom     }
326d700e76aSTom 
3270b02be92SPatrick Venture     r = sd_bus_message_new_method_call(bus, &m, a.bus, a.path, a.interface,
3280b02be92SPatrick Venture                                        method);
3290b02be92SPatrick Venture     if (r < 0)
3300b02be92SPatrick Venture     {
331b51bf9c8SPatrick Venture         std::fprintf(stderr, "Failed to create a method call: %s",
332b51bf9c8SPatrick Venture                      strerror(-r));
333d700e76aSTom         goto final;
334d700e76aSTom     }
335d700e76aSTom 
336d700e76aSTom     r = sd_bus_message_append(m, "v", "i", value);
3370b02be92SPatrick Venture     if (r < 0)
3380b02be92SPatrick Venture     {
339b51bf9c8SPatrick Venture         std::fprintf(stderr, "Failed to create a input parameter: %s",
340b51bf9c8SPatrick Venture                      strerror(-r));
341d700e76aSTom         goto final;
342d700e76aSTom     }
343d700e76aSTom 
344*a6fb32d8SJayanth Othayoth     r = sd_bus_call(bus, m, 0, &error, nullptr);
3450b02be92SPatrick Venture     if (r < 0)
3460b02be92SPatrick Venture     {
347b51bf9c8SPatrick Venture         std::fprintf(stderr, "12 Failed to call the method: %s", strerror(-r));
348d700e76aSTom     }
349d700e76aSTom 
350d700e76aSTom final:
351d700e76aSTom     sd_bus_error_free(&error);
352d700e76aSTom     m = sd_bus_message_unref(m);
353d700e76aSTom 
354d700e76aSTom     return 0;
355d700e76aSTom }
356d700e76aSTom 
dbus_to_sensor_type(char * p)3570b02be92SPatrick Venture uint8_t dbus_to_sensor_type(char* p)
3580b02be92SPatrick Venture {
35998a23840SMatthew Barth     sensorTypemap_t* s = g_SensorTypeMap;
36098a23840SMatthew Barth     char r = 0;
3610b02be92SPatrick Venture     while (s->number != 0xFF)
3620b02be92SPatrick Venture     {
3630b02be92SPatrick Venture         if (!strcmp(s->dbusname, p))
3640b02be92SPatrick Venture         {
365558184eaSTom Joseph             r = s->typecode;
36698a23840SMatthew Barth             break;
36798a23840SMatthew Barth         }
36898a23840SMatthew Barth         s++;
36998a23840SMatthew Barth     }
37098a23840SMatthew Barth 
37198a23840SMatthew Barth     if (s->number == 0xFF)
37298a23840SMatthew Barth         printf("Failed to find Sensor Type %s\n", p);
37398a23840SMatthew Barth 
37498a23840SMatthew Barth     return r;
37598a23840SMatthew Barth }
37698a23840SMatthew Barth 
get_type_from_interface(dbus_interface_t dbus_if)3770b02be92SPatrick Venture uint8_t get_type_from_interface(dbus_interface_t dbus_if)
3780b02be92SPatrick Venture {
37956003453SBrad Bishop     uint8_t type;
38098a23840SMatthew Barth 
38198a23840SMatthew Barth     // This is where sensors that do not exist in dbus but do
38298a23840SMatthew Barth     // exist in the host code stop.  This should indicate it
38398a23840SMatthew Barth     // is not a supported sensor
3840b02be92SPatrick Venture     if (dbus_if.interface[0] == 0)
3850b02be92SPatrick Venture     {
3860b02be92SPatrick Venture         return 0;
3870b02be92SPatrick Venture     }
38898a23840SMatthew Barth 
3897117441cSEmily Shaffer     // Fetch type from interface itself.
3907117441cSEmily Shaffer     if (dbus_if.sensortype != 0)
3917117441cSEmily Shaffer     {
3927117441cSEmily Shaffer         type = dbus_if.sensortype;
3930b02be92SPatrick Venture     }
3940b02be92SPatrick Venture     else
3950b02be92SPatrick Venture     {
39698a23840SMatthew Barth         // Non InventoryItems
3974491a46fSPatrick Venture         char* p = strrchr(dbus_if.path, '/');
39856003453SBrad Bishop         type = dbus_to_sensor_type(p + 1);
39998a23840SMatthew Barth     }
40098a23840SMatthew Barth 
40156003453SBrad Bishop     return type;
40298a23840SMatthew Barth }
40398a23840SMatthew Barth 
404391f3303SEmily Shaffer // Replaces find_sensor
find_type_for_sensor_number(uint8_t num)4050b02be92SPatrick Venture uint8_t find_type_for_sensor_number(uint8_t num)
4060b02be92SPatrick Venture {
407391f3303SEmily Shaffer     int r;
408391f3303SEmily Shaffer     dbus_interface_t dbus_if;
4092ae09b9aSEmily Shaffer     r = find_openbmc_path(num, &dbus_if);
4100b02be92SPatrick Venture     if (r < 0)
4110b02be92SPatrick Venture     {
412b51bf9c8SPatrick Venture         std::fprintf(stderr, "Could not find sensor %d\n", num);
41391875f77SLei YU         return 0;
414391f3303SEmily Shaffer     }
415391f3303SEmily Shaffer     return get_type_from_interface(dbus_if);
416391f3303SEmily Shaffer }
417391f3303SEmily Shaffer 
418a8be7dc8SDeepak Kumar Sahu /**
419a8be7dc8SDeepak Kumar Sahu  *  @brief implements the get sensor type command.
420a8be7dc8SDeepak Kumar Sahu  *  @param - sensorNumber
421a8be7dc8SDeepak Kumar Sahu  *
422a8be7dc8SDeepak Kumar Sahu  *  @return IPMI completion code plus response data on success.
423a8be7dc8SDeepak Kumar Sahu  *   - sensorType
424a8be7dc8SDeepak Kumar Sahu  *   - eventType
425a8be7dc8SDeepak Kumar Sahu  **/
426a8be7dc8SDeepak Kumar Sahu 
427a8be7dc8SDeepak Kumar Sahu ipmi::RspType<uint8_t, // sensorType
428a8be7dc8SDeepak Kumar Sahu               uint8_t  // eventType
429a8be7dc8SDeepak Kumar Sahu               >
ipmiGetSensorType(uint8_t sensorNumber)430a8be7dc8SDeepak Kumar Sahu     ipmiGetSensorType(uint8_t sensorNumber)
43198a23840SMatthew Barth {
43264b7621cSWang Xiaohua     const auto it = ipmi::sensor::sensors.find(sensorNumber);
43364b7621cSWang Xiaohua     if (it == ipmi::sensor::sensors.end())
4340b02be92SPatrick Venture     {
43564b7621cSWang Xiaohua         // The sensor map does not contain the sensor requested
436a8be7dc8SDeepak Kumar Sahu         return ipmi::responseSensorInvalid();
43798a23840SMatthew Barth     }
43898a23840SMatthew Barth 
43964b7621cSWang Xiaohua     const auto& info = it->second;
44064b7621cSWang Xiaohua     uint8_t sensorType = info.sensorType;
44164b7621cSWang Xiaohua     uint8_t eventType = info.sensorReadingType;
44264b7621cSWang Xiaohua 
443a8be7dc8SDeepak Kumar Sahu     return ipmi::responseSuccess(sensorType, eventType);
44498a23840SMatthew Barth }
44598a23840SMatthew Barth 
4460b02be92SPatrick Venture const std::set<std::string> analogSensorInterfaces = {
447cc941e15SEmily Shaffer     "xyz.openbmc_project.Sensor.Value",
448e9a64056SPatrick Venture     "xyz.openbmc_project.Control.FanPwm",
449cc941e15SEmily Shaffer };
450cc941e15SEmily Shaffer 
isAnalogSensor(const std::string & interface)451cc941e15SEmily Shaffer bool isAnalogSensor(const std::string& interface)
452cc941e15SEmily Shaffer {
453cc941e15SEmily Shaffer     return (analogSensorInterfaces.count(interface));
454cc941e15SEmily Shaffer }
455cc941e15SEmily Shaffer 
4569da3a750SDeepak Kumar Sahu /**
4579da3a750SDeepak Kumar Sahu @brief This command is used to set sensorReading.
4589da3a750SDeepak Kumar Sahu 
4599da3a750SDeepak Kumar Sahu @param
4609da3a750SDeepak Kumar Sahu     -  sensorNumber
4619da3a750SDeepak Kumar Sahu     -  operation
4629da3a750SDeepak Kumar Sahu     -  reading
4639da3a750SDeepak Kumar Sahu     -  assertOffset0_7
4649da3a750SDeepak Kumar Sahu     -  assertOffset8_14
4659da3a750SDeepak Kumar Sahu     -  deassertOffset0_7
4669da3a750SDeepak Kumar Sahu     -  deassertOffset8_14
4679da3a750SDeepak Kumar Sahu     -  eventData1
4689da3a750SDeepak Kumar Sahu     -  eventData2
4699da3a750SDeepak Kumar Sahu     -  eventData3
4709da3a750SDeepak Kumar Sahu 
4719da3a750SDeepak Kumar Sahu @return completion code on success.
4729da3a750SDeepak Kumar Sahu **/
4739da3a750SDeepak 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)4741318a5edSPatrick Williams ipmi::RspType<> ipmiSetSensorReading(
4751318a5edSPatrick Williams     uint8_t sensorNumber, uint8_t operation, uint8_t reading,
4761318a5edSPatrick Williams     uint8_t assertOffset0_7, uint8_t assertOffset8_14,
4771318a5edSPatrick Williams     uint8_t deassertOffset0_7, uint8_t deassertOffset8_14, uint8_t eventData1,
4781318a5edSPatrick Williams     uint8_t eventData2, uint8_t eventData3)
479be703f71STom Joseph {
4803b1071adSGeorge Liu     lg2::debug("IPMI SET_SENSOR, sensorNumber: {SENSOR_NUM}", "SENSOR_NUM",
4813b1071adSGeorge Liu                lg2::hex, sensorNumber);
4829da3a750SDeepak Kumar Sahu 
4830634e989SArun P. Mohanan     if (sensorNumber == 0xFF)
4840634e989SArun P. Mohanan     {
4850634e989SArun P. Mohanan         return ipmi::responseInvalidFieldRequest();
4860634e989SArun P. Mohanan     }
4879da3a750SDeepak Kumar Sahu     ipmi::sensor::SetSensorReadingReq cmdData;
4889da3a750SDeepak Kumar Sahu 
4899da3a750SDeepak Kumar Sahu     cmdData.number = sensorNumber;
4909da3a750SDeepak Kumar Sahu     cmdData.operation = operation;
4919da3a750SDeepak Kumar Sahu     cmdData.reading = reading;
4929da3a750SDeepak Kumar Sahu     cmdData.assertOffset0_7 = assertOffset0_7;
4939da3a750SDeepak Kumar Sahu     cmdData.assertOffset8_14 = assertOffset8_14;
4949da3a750SDeepak Kumar Sahu     cmdData.deassertOffset0_7 = deassertOffset0_7;
4959da3a750SDeepak Kumar Sahu     cmdData.deassertOffset8_14 = deassertOffset8_14;
4969da3a750SDeepak Kumar Sahu     cmdData.eventData1 = eventData1;
4979da3a750SDeepak Kumar Sahu     cmdData.eventData2 = eventData2;
4989da3a750SDeepak Kumar Sahu     cmdData.eventData3 = eventData3;
499be703f71STom Joseph 
500be703f71STom Joseph     // Check if the Sensor Number is present
501db0cbe64SPatrick Venture     const auto iter = ipmi::sensor::sensors.find(sensorNumber);
502db0cbe64SPatrick Venture     if (iter == ipmi::sensor::sensors.end())
503be703f71STom Joseph     {
5049da3a750SDeepak Kumar Sahu         updateSensorRecordFromSSRAESC(&sensorNumber);
5059da3a750SDeepak Kumar Sahu         return ipmi::responseSuccess();
506be703f71STom Joseph     }
507be703f71STom Joseph 
50818e99992SDhruvaraj Subhashchandran     try
50918e99992SDhruvaraj Subhashchandran     {
5100922bde4SJayanth Othayoth         if (ipmi::sensor::Mutability::Write !=
5110922bde4SJayanth Othayoth             (iter->second.mutability & ipmi::sensor::Mutability::Write))
5120922bde4SJayanth Othayoth         {
5133b1071adSGeorge Liu             lg2::error("Sensor Set operation is not allowed, "
5143b1071adSGeorge Liu                        "sensorNumber: {SENSOR_NUM}",
5153b1071adSGeorge Liu                        "SENSOR_NUM", lg2::hex, 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     {
5233b1071adSGeorge Liu         lg2::error("Set sensor failed, sensorNumber: {SENSOR_NUM}",
5243b1071adSGeorge Liu                    "SENSOR_NUM", lg2::hex, sensorNumber);
52518e99992SDhruvaraj Subhashchandran         commit<InternalFailure>();
5269da3a750SDeepak Kumar Sahu         return ipmi::responseUnspecifiedError();
52718e99992SDhruvaraj Subhashchandran     }
5288202432fSTom Joseph     catch (const std::runtime_error& e)
5298202432fSTom Joseph     {
5303b1071adSGeorge Liu         lg2::error("runtime error: {ERROR}", "ERROR", e);
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 
6141318a5edSPatrick Williams                 return ipmi::responseSuccess(
6151318a5edSPatrick Williams                     senReading, reserved, readState, senScanState,
6161318a5edSPatrick Williams                     allEventMessageState, 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 
6331318a5edSPatrick Williams         return ipmi::responseSuccess(
6341318a5edSPatrick Williams             getResponse.reading, uint5_t(0),
6351318a5edSPatrick Williams             getResponse.readingOrStateUnavailable, 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 
updateWarningThreshold(uint8_t lowerValue,uint8_t upperValue,get_sdr::GetSensorThresholdsResponse & resp)664402024a8SGeorge Liu void updateWarningThreshold(uint8_t lowerValue, uint8_t upperValue,
665402024a8SGeorge Liu                             get_sdr::GetSensorThresholdsResponse& resp)
666402024a8SGeorge Liu {
667402024a8SGeorge Liu     resp.lowerNonCritical = lowerValue;
668402024a8SGeorge Liu     resp.upperNonCritical = upperValue;
669402024a8SGeorge Liu     if (lowerValue)
670402024a8SGeorge Liu     {
671402024a8SGeorge Liu         resp.validMask |= static_cast<uint8_t>(
672402024a8SGeorge Liu             ipmi::sensor::ThresholdMask::NON_CRITICAL_LOW_MASK);
673402024a8SGeorge Liu     }
674402024a8SGeorge Liu 
675402024a8SGeorge Liu     if (upperValue)
676402024a8SGeorge Liu     {
677402024a8SGeorge Liu         resp.validMask |= static_cast<uint8_t>(
678402024a8SGeorge Liu             ipmi::sensor::ThresholdMask::NON_CRITICAL_HIGH_MASK);
679402024a8SGeorge Liu     }
680402024a8SGeorge Liu }
681402024a8SGeorge Liu 
updateCriticalThreshold(uint8_t lowerValue,uint8_t upperValue,get_sdr::GetSensorThresholdsResponse & resp)682402024a8SGeorge Liu void updateCriticalThreshold(uint8_t lowerValue, uint8_t upperValue,
683402024a8SGeorge Liu                              get_sdr::GetSensorThresholdsResponse& resp)
684402024a8SGeorge Liu {
685402024a8SGeorge Liu     resp.lowerCritical = lowerValue;
686402024a8SGeorge Liu     resp.upperCritical = upperValue;
687402024a8SGeorge Liu     if (lowerValue)
688402024a8SGeorge Liu     {
689402024a8SGeorge Liu         resp.validMask |= static_cast<uint8_t>(
690402024a8SGeorge Liu             ipmi::sensor::ThresholdMask::CRITICAL_LOW_MASK);
691402024a8SGeorge Liu     }
692402024a8SGeorge Liu 
693402024a8SGeorge Liu     if (upperValue)
694402024a8SGeorge Liu     {
695402024a8SGeorge Liu         resp.validMask |= static_cast<uint8_t>(
696402024a8SGeorge Liu             ipmi::sensor::ThresholdMask::CRITICAL_HIGH_MASK);
697402024a8SGeorge Liu     }
698402024a8SGeorge Liu }
699402024a8SGeorge Liu 
updateNonRecoverableThreshold(uint8_t lowerValue,uint8_t upperValue,get_sdr::GetSensorThresholdsResponse & resp)700402024a8SGeorge Liu void updateNonRecoverableThreshold(uint8_t lowerValue, uint8_t upperValue,
701402024a8SGeorge Liu                                    get_sdr::GetSensorThresholdsResponse& resp)
702402024a8SGeorge Liu {
703402024a8SGeorge Liu     resp.lowerNonRecoverable = lowerValue;
704402024a8SGeorge Liu     resp.upperNonRecoverable = upperValue;
705402024a8SGeorge Liu     if (lowerValue)
706402024a8SGeorge Liu     {
707402024a8SGeorge Liu         resp.validMask |= static_cast<uint8_t>(
708402024a8SGeorge Liu             ipmi::sensor::ThresholdMask::NON_RECOVERABLE_LOW_MASK);
709402024a8SGeorge Liu     }
710402024a8SGeorge Liu 
711402024a8SGeorge Liu     if (upperValue)
712402024a8SGeorge Liu     {
713402024a8SGeorge Liu         resp.validMask |= static_cast<uint8_t>(
714402024a8SGeorge Liu             ipmi::sensor::ThresholdMask::NON_RECOVERABLE_HIGH_MASK);
715402024a8SGeorge Liu     }
716402024a8SGeorge Liu }
717402024a8SGeorge Liu 
getSensorThresholds(ipmi::Context::ptr & ctx,uint8_t sensorNum)71869b4c281SPatrick Williams get_sdr::GetSensorThresholdsResponse getSensorThresholds(
71969b4c281SPatrick Williams     ipmi::Context::ptr& ctx, uint8_t sensorNum)
7200ac0dd23STom Joseph {
721515bc375SWilliam A. Kennington III     get_sdr::GetSensorThresholdsResponse resp{};
722db0cbe64SPatrick Venture     const auto iter = ipmi::sensor::sensors.find(sensorNum);
7230ac0dd23STom Joseph     const auto info = iter->second;
7240ac0dd23STom Joseph 
72589a83b67SKonstantin Aladyshev     std::string service;
72689a83b67SKonstantin Aladyshev     boost::system::error_code ec;
72789a83b67SKonstantin Aladyshev     ec = ipmi::getService(ctx, info.sensorInterface, info.sensorPath, service);
72889a83b67SKonstantin Aladyshev     if (ec)
72989a83b67SKonstantin Aladyshev     {
73089a83b67SKonstantin Aladyshev         return resp;
73189a83b67SKonstantin Aladyshev     }
7320ac0dd23STom Joseph 
7339154caabSWilly Tu     int32_t minClamp;
7349154caabSWilly Tu     int32_t maxClamp;
7359154caabSWilly Tu     int32_t rawData;
7369154caabSWilly Tu     constexpr uint8_t sensorUnitsSignedBits = 2 << 6;
7379154caabSWilly Tu     constexpr uint8_t signedDataFormat = 0x80;
7389154caabSWilly Tu     if ((info.sensorUnits1 & sensorUnitsSignedBits) == signedDataFormat)
7399154caabSWilly Tu     {
7409154caabSWilly Tu         minClamp = std::numeric_limits<int8_t>::lowest();
7419154caabSWilly Tu         maxClamp = std::numeric_limits<int8_t>::max();
7429154caabSWilly Tu     }
7439154caabSWilly Tu     else
7449154caabSWilly Tu     {
7459154caabSWilly Tu         minClamp = std::numeric_limits<uint8_t>::lowest();
7469154caabSWilly Tu         maxClamp = std::numeric_limits<uint8_t>::max();
7479154caabSWilly Tu     }
7480ac0dd23STom Joseph 
749402024a8SGeorge Liu     static std::vector<std::string> thresholdNames{"Warning", "Critical",
750402024a8SGeorge Liu                                                    "NonRecoverable"};
7510ac0dd23STom Joseph 
752402024a8SGeorge Liu     for (const auto& thresholdName : thresholdNames)
7530ac0dd23STom Joseph     {
754402024a8SGeorge Liu         std::string thresholdInterface =
755402024a8SGeorge Liu             "xyz.openbmc_project.Sensor.Threshold." + thresholdName;
756402024a8SGeorge Liu         std::string thresholdLow = thresholdName + "Low";
757402024a8SGeorge Liu         std::string thresholdHigh = thresholdName + "High";
7580ac0dd23STom Joseph 
759402024a8SGeorge Liu         ipmi::PropertyMap thresholds;
76089a83b67SKonstantin Aladyshev         ec = ipmi::getAllDbusProperties(ctx, service, info.sensorPath,
761402024a8SGeorge Liu                                         thresholdInterface, thresholds);
762402024a8SGeorge Liu         if (ec)
76389a83b67SKonstantin Aladyshev         {
764402024a8SGeorge Liu             continue;
7650ac0dd23STom Joseph         }
7660ac0dd23STom Joseph 
767402024a8SGeorge Liu         double lowValue = ipmi::mappedVariant<double>(
768402024a8SGeorge Liu             thresholds, thresholdLow, std::numeric_limits<double>::quiet_NaN());
769402024a8SGeorge Liu         double highValue = ipmi::mappedVariant<double>(
770402024a8SGeorge Liu             thresholds, thresholdHigh,
771402024a8SGeorge Liu             std::numeric_limits<double>::quiet_NaN());
772402024a8SGeorge Liu 
773402024a8SGeorge Liu         uint8_t lowerValue = 0;
774402024a8SGeorge Liu         uint8_t upperValue = 0;
775402024a8SGeorge Liu         if (std::isfinite(lowValue))
7760ac0dd23STom Joseph         {
777402024a8SGeorge Liu             lowValue *= std::pow(10, info.scale - info.exponentR);
778402024a8SGeorge Liu             rawData = round((lowValue - info.scaledOffset) / info.coefficientM);
779402024a8SGeorge Liu             lowerValue =
7809154caabSWilly Tu                 static_cast<uint8_t>(std::clamp(rawData, minClamp, maxClamp));
781402024a8SGeorge Liu         }
782402024a8SGeorge Liu 
783402024a8SGeorge Liu         if (std::isfinite(highValue))
784402024a8SGeorge Liu         {
785402024a8SGeorge Liu             highValue *= std::pow(10, info.scale - info.exponentR);
786402024a8SGeorge Liu             rawData =
787402024a8SGeorge Liu                 round((highValue - info.scaledOffset) / info.coefficientM);
788402024a8SGeorge Liu             upperValue =
789402024a8SGeorge Liu                 static_cast<uint8_t>(std::clamp(rawData, minClamp, maxClamp));
790402024a8SGeorge Liu         }
791402024a8SGeorge Liu 
792402024a8SGeorge Liu         if (thresholdName == "Warning")
793402024a8SGeorge Liu         {
794402024a8SGeorge Liu             updateWarningThreshold(lowerValue, upperValue, resp);
795402024a8SGeorge Liu         }
796402024a8SGeorge Liu         else if (thresholdName == "Critical")
797402024a8SGeorge Liu         {
798402024a8SGeorge Liu             updateCriticalThreshold(lowerValue, upperValue, resp);
799402024a8SGeorge Liu         }
800402024a8SGeorge Liu         else if (thresholdName == "NonRecoverable")
801402024a8SGeorge Liu         {
802402024a8SGeorge Liu             updateNonRecoverableThreshold(lowerValue, upperValue, resp);
8030ac0dd23STom Joseph         }
80489a83b67SKonstantin Aladyshev     }
805996c9798Sjayaprakash Mutyala 
806996c9798Sjayaprakash Mutyala     return resp;
8070ac0dd23STom Joseph }
8080ac0dd23STom Joseph 
809996c9798Sjayaprakash Mutyala /** @brief implements the get sensor thresholds command
81089a83b67SKonstantin Aladyshev  *  @param ctx - IPMI context pointer
811996c9798Sjayaprakash Mutyala  *  @param sensorNum - sensor number
812996c9798Sjayaprakash Mutyala  *
813996c9798Sjayaprakash Mutyala  *  @returns IPMI completion code plus response data
814996c9798Sjayaprakash Mutyala  *   - validMask - threshold mask
815996c9798Sjayaprakash Mutyala  *   - lower non-critical threshold - IPMI messaging state
816996c9798Sjayaprakash Mutyala  *   - lower critical threshold - link authentication state
817996c9798Sjayaprakash Mutyala  *   - lower non-recoverable threshold - callback state
818996c9798Sjayaprakash Mutyala  *   - upper non-critical threshold
819996c9798Sjayaprakash Mutyala  *   - upper critical
820996c9798Sjayaprakash Mutyala  *   - upper non-recoverable
821996c9798Sjayaprakash Mutyala  */
822996c9798Sjayaprakash Mutyala ipmi::RspType<uint8_t, // validMask
823996c9798Sjayaprakash Mutyala               uint8_t, // lowerNonCritical
824996c9798Sjayaprakash Mutyala               uint8_t, // lowerCritical
825996c9798Sjayaprakash Mutyala               uint8_t, // lowerNonRecoverable
826996c9798Sjayaprakash Mutyala               uint8_t, // upperNonCritical
827996c9798Sjayaprakash Mutyala               uint8_t, // upperCritical
828996c9798Sjayaprakash Mutyala               uint8_t  // upperNonRecoverable
829996c9798Sjayaprakash Mutyala               >
ipmiSensorGetSensorThresholds(ipmi::Context::ptr & ctx,uint8_t sensorNum)83089a83b67SKonstantin Aladyshev     ipmiSensorGetSensorThresholds(ipmi::Context::ptr& ctx, uint8_t sensorNum)
8315c0beec1SDhruvaraj Subhashchandran {
8320ac0dd23STom Joseph     constexpr auto valueInterface = "xyz.openbmc_project.Sensor.Value";
8335c0beec1SDhruvaraj Subhashchandran 
834db0cbe64SPatrick Venture     const auto iter = ipmi::sensor::sensors.find(sensorNum);
835db0cbe64SPatrick Venture     if (iter == ipmi::sensor::sensors.end())
8365c0beec1SDhruvaraj Subhashchandran     {
837996c9798Sjayaprakash Mutyala         return ipmi::responseSensorInvalid();
8385c0beec1SDhruvaraj Subhashchandran     }
8395c0beec1SDhruvaraj Subhashchandran 
8400ac0dd23STom Joseph     const auto info = iter->second;
8415c0beec1SDhruvaraj Subhashchandran 
8425c0beec1SDhruvaraj Subhashchandran     // Proceed only if the sensor value interface is implemented.
8430ac0dd23STom Joseph     if (info.propertyInterfaces.find(valueInterface) ==
8440ac0dd23STom Joseph         info.propertyInterfaces.end())
8455c0beec1SDhruvaraj Subhashchandran     {
8465c0beec1SDhruvaraj Subhashchandran         // return with valid mask as 0
847996c9798Sjayaprakash Mutyala         return ipmi::responseSuccess();
8485c0beec1SDhruvaraj Subhashchandran     }
8495c0beec1SDhruvaraj Subhashchandran 
85014a47819SLei YU     auto it = sensorThresholdMap.find(sensorNum);
85114a47819SLei YU     if (it == sensorThresholdMap.end())
85214a47819SLei YU     {
8537a34a6caSGeorge Liu         auto resp = getSensorThresholds(ctx, sensorNum);
8547a34a6caSGeorge Liu         if (resp.validMask == 0)
8557a34a6caSGeorge Liu         {
8567a34a6caSGeorge Liu             return ipmi::responseSensorInvalid();
8577a34a6caSGeorge Liu         }
8587a34a6caSGeorge Liu         sensorThresholdMap[sensorNum] = std::move(resp);
85914a47819SLei YU     }
86014a47819SLei YU 
86114a47819SLei YU     const auto& resp = sensorThresholdMap[sensorNum];
8625c0beec1SDhruvaraj Subhashchandran 
8631318a5edSPatrick Williams     return ipmi::responseSuccess(
8641318a5edSPatrick Williams         resp.validMask, resp.lowerNonCritical, resp.lowerCritical,
8651318a5edSPatrick Williams         resp.lowerNonRecoverable, resp.upperNonCritical, resp.upperCritical,
866996c9798Sjayaprakash Mutyala         resp.upperNonRecoverable);
8675c0beec1SDhruvaraj Subhashchandran }
8685c0beec1SDhruvaraj Subhashchandran 
869f93da667SLotus Xu /** @brief implements the Set Sensor threshold command
870f93da667SLotus Xu  *  @param sensorNumber        - sensor number
871f93da667SLotus Xu  *  @param lowerNonCriticalThreshMask
872f93da667SLotus Xu  *  @param lowerCriticalThreshMask
873f93da667SLotus Xu  *  @param lowerNonRecovThreshMask
874f93da667SLotus Xu  *  @param upperNonCriticalThreshMask
875f93da667SLotus Xu  *  @param upperCriticalThreshMask
876f93da667SLotus Xu  *  @param upperNonRecovThreshMask
877f93da667SLotus Xu  *  @param reserved
878f93da667SLotus Xu  *  @param lowerNonCritical    - lower non-critical threshold
879f93da667SLotus Xu  *  @param lowerCritical       - Lower critical threshold
880f93da667SLotus Xu  *  @param lowerNonRecoverable - Lower non recovarable threshold
881f93da667SLotus Xu  *  @param upperNonCritical    - Upper non-critical threshold
882f93da667SLotus Xu  *  @param upperCritical       - Upper critical
883f93da667SLotus Xu  *  @param upperNonRecoverable - Upper Non-recoverable
884f93da667SLotus Xu  *
885f93da667SLotus Xu  *  @returns IPMI completion code
886f93da667SLotus 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)887f93da667SLotus Xu ipmi::RspType<> ipmiSenSetSensorThresholds(
888f93da667SLotus Xu     ipmi::Context::ptr& ctx, uint8_t sensorNum, bool lowerNonCriticalThreshMask,
889f93da667SLotus Xu     bool lowerCriticalThreshMask, bool lowerNonRecovThreshMask,
890f93da667SLotus Xu     bool upperNonCriticalThreshMask, bool upperCriticalThreshMask,
891f93da667SLotus Xu     bool upperNonRecovThreshMask, uint2_t reserved, uint8_t lowerNonCritical,
89211d68897SWilly Tu     uint8_t lowerCritical, uint8_t, uint8_t upperNonCritical,
89311d68897SWilly Tu     uint8_t upperCritical, uint8_t)
894f93da667SLotus Xu {
895f93da667SLotus Xu     if (reserved)
896f93da667SLotus Xu     {
897f93da667SLotus Xu         return ipmi::responseInvalidFieldRequest();
898f93da667SLotus Xu     }
899f93da667SLotus Xu 
900f93da667SLotus Xu     // lower nc and upper nc not suppported on any sensor
901f93da667SLotus Xu     if (lowerNonRecovThreshMask || upperNonRecovThreshMask)
902f93da667SLotus Xu     {
903f93da667SLotus Xu         return ipmi::responseInvalidFieldRequest();
904f93da667SLotus Xu     }
905f93da667SLotus Xu 
906f93da667SLotus Xu     // if none of the threshold mask are set, nothing to do
907f93da667SLotus Xu     if (!(lowerNonCriticalThreshMask | lowerCriticalThreshMask |
908f93da667SLotus Xu           lowerNonRecovThreshMask | upperNonCriticalThreshMask |
909f93da667SLotus Xu           upperCriticalThreshMask | upperNonRecovThreshMask))
910f93da667SLotus Xu     {
911f93da667SLotus Xu         return ipmi::responseSuccess();
912f93da667SLotus Xu     }
913f93da667SLotus Xu 
914f93da667SLotus Xu     constexpr auto valueInterface = "xyz.openbmc_project.Sensor.Value";
915f93da667SLotus Xu 
916f93da667SLotus Xu     const auto iter = ipmi::sensor::sensors.find(sensorNum);
917f93da667SLotus Xu     if (iter == ipmi::sensor::sensors.end())
918f93da667SLotus Xu     {
919f93da667SLotus Xu         return ipmi::responseSensorInvalid();
920f93da667SLotus Xu     }
921f93da667SLotus Xu 
922f93da667SLotus Xu     const auto& info = iter->second;
923f93da667SLotus Xu 
924f93da667SLotus Xu     // Proceed only if the sensor value interface is implemented.
925f93da667SLotus Xu     if (info.propertyInterfaces.find(valueInterface) ==
926f93da667SLotus Xu         info.propertyInterfaces.end())
927f93da667SLotus Xu     {
928f93da667SLotus Xu         // return with valid mask as 0
929f93da667SLotus Xu         return ipmi::responseSuccess();
930f93da667SLotus Xu     }
931f93da667SLotus Xu 
932f93da667SLotus Xu     constexpr auto warningThreshIntf =
933f93da667SLotus Xu         "xyz.openbmc_project.Sensor.Threshold.Warning";
934f93da667SLotus Xu     constexpr auto criticalThreshIntf =
935f93da667SLotus Xu         "xyz.openbmc_project.Sensor.Threshold.Critical";
936f93da667SLotus Xu 
937f93da667SLotus Xu     std::string service;
938f93da667SLotus Xu     boost::system::error_code ec;
939f93da667SLotus Xu     ec = ipmi::getService(ctx, info.sensorInterface, info.sensorPath, service);
940f93da667SLotus Xu     if (ec)
941f93da667SLotus Xu     {
942f93da667SLotus Xu         return ipmi::responseResponseError();
943f93da667SLotus Xu     }
944f93da667SLotus Xu     // store a vector of property name, value to set, and interface
945f93da667SLotus Xu     std::vector<std::tuple<std::string, uint8_t, std::string>> thresholdsToSet;
946f93da667SLotus Xu 
947f93da667SLotus Xu     // define the indexes of the tuple
948f93da667SLotus Xu     constexpr uint8_t propertyName = 0;
949f93da667SLotus Xu     constexpr uint8_t thresholdValue = 1;
950f93da667SLotus Xu     constexpr uint8_t interface = 2;
951f93da667SLotus Xu     // verifiy all needed fields are present
952f93da667SLotus Xu     if (lowerCriticalThreshMask || upperCriticalThreshMask)
953f93da667SLotus Xu     {
954f93da667SLotus Xu         ipmi::PropertyMap findThreshold;
955f93da667SLotus Xu         ec = ipmi::getAllDbusProperties(ctx, service, info.sensorPath,
956f93da667SLotus Xu                                         criticalThreshIntf, findThreshold);
957f93da667SLotus Xu 
958f93da667SLotus Xu         if (!ec)
959f93da667SLotus Xu         {
960f93da667SLotus Xu             if (lowerCriticalThreshMask)
961f93da667SLotus Xu             {
962f93da667SLotus Xu                 auto findLower = findThreshold.find("CriticalLow");
963f93da667SLotus Xu                 if (findLower == findThreshold.end())
964f93da667SLotus Xu                 {
965f93da667SLotus Xu                     return ipmi::responseInvalidFieldRequest();
966f93da667SLotus Xu                 }
967f93da667SLotus Xu                 thresholdsToSet.emplace_back("CriticalLow", lowerCritical,
968f93da667SLotus Xu                                              criticalThreshIntf);
969f93da667SLotus Xu             }
970f93da667SLotus Xu             if (upperCriticalThreshMask)
971f93da667SLotus Xu             {
972f93da667SLotus Xu                 auto findUpper = findThreshold.find("CriticalHigh");
973f93da667SLotus Xu                 if (findUpper == findThreshold.end())
974f93da667SLotus Xu                 {
975f93da667SLotus Xu                     return ipmi::responseInvalidFieldRequest();
976f93da667SLotus Xu                 }
977f93da667SLotus Xu                 thresholdsToSet.emplace_back("CriticalHigh", upperCritical,
978f93da667SLotus Xu                                              criticalThreshIntf);
979f93da667SLotus Xu             }
980f93da667SLotus Xu         }
981f93da667SLotus Xu     }
982f93da667SLotus Xu     if (lowerNonCriticalThreshMask || upperNonCriticalThreshMask)
983f93da667SLotus Xu     {
984f93da667SLotus Xu         ipmi::PropertyMap findThreshold;
985f93da667SLotus Xu         ec = ipmi::getAllDbusProperties(ctx, service, info.sensorPath,
986f93da667SLotus Xu                                         warningThreshIntf, findThreshold);
987f93da667SLotus Xu 
988f93da667SLotus Xu         if (!ec)
989f93da667SLotus Xu         {
990f93da667SLotus Xu             if (lowerNonCriticalThreshMask)
991f93da667SLotus Xu             {
992f93da667SLotus Xu                 auto findLower = findThreshold.find("WarningLow");
993f93da667SLotus Xu                 if (findLower == findThreshold.end())
994f93da667SLotus Xu                 {
995f93da667SLotus Xu                     return ipmi::responseInvalidFieldRequest();
996f93da667SLotus Xu                 }
997f93da667SLotus Xu                 thresholdsToSet.emplace_back("WarningLow", lowerNonCritical,
998f93da667SLotus Xu                                              warningThreshIntf);
999f93da667SLotus Xu             }
1000f93da667SLotus Xu             if (upperNonCriticalThreshMask)
1001f93da667SLotus Xu             {
1002f93da667SLotus Xu                 auto findUpper = findThreshold.find("WarningHigh");
1003f93da667SLotus Xu                 if (findUpper == findThreshold.end())
1004f93da667SLotus Xu                 {
1005f93da667SLotus Xu                     return ipmi::responseInvalidFieldRequest();
1006f93da667SLotus Xu                 }
1007f93da667SLotus Xu                 thresholdsToSet.emplace_back("WarningHigh", upperNonCritical,
1008f93da667SLotus Xu                                              warningThreshIntf);
1009f93da667SLotus Xu             }
1010f93da667SLotus Xu         }
1011f93da667SLotus Xu     }
1012f93da667SLotus Xu     for (const auto& property : thresholdsToSet)
1013f93da667SLotus Xu     {
1014f93da667SLotus Xu         // from section 36.3 in the IPMI Spec, assume all linear
1015f93da667SLotus Xu         double valueToSet =
1016f93da667SLotus Xu             ((info.coefficientM * std::get<thresholdValue>(property)) +
1017f93da667SLotus Xu              (info.scaledOffset * std::pow(10.0, info.scale))) *
1018f93da667SLotus Xu             std::pow(10.0, info.exponentR);
1019f93da667SLotus Xu         ipmi::setDbusProperty(
1020f93da667SLotus Xu             ctx, service, info.sensorPath, std::get<interface>(property),
1021f93da667SLotus Xu             std::get<propertyName>(property), ipmi::Value(valueToSet));
1022f93da667SLotus Xu     }
1023f93da667SLotus Xu 
102414a47819SLei YU     // Invalidate the cache
102514a47819SLei YU     sensorThresholdMap.erase(sensorNum);
1026f93da667SLotus Xu     return ipmi::responseSuccess();
1027f93da667SLotus Xu }
1028f93da667SLotus Xu 
1029d957823eSjayaprakash Mutyala /** @brief implements the get SDR Info command
1030d957823eSjayaprakash Mutyala  *  @param count - Operation
1031d957823eSjayaprakash Mutyala  *
1032d957823eSjayaprakash Mutyala  *  @returns IPMI completion code plus response data
1033d957823eSjayaprakash Mutyala  *   - sdrCount - sensor/SDR count
1034d957823eSjayaprakash Mutyala  *   - lunsAndDynamicPopulation - static/Dynamic sensor population flag
1035d957823eSjayaprakash Mutyala  */
1036d957823eSjayaprakash Mutyala ipmi::RspType<uint8_t, // respcount
1037d957823eSjayaprakash Mutyala               uint8_t  // dynamic population flags
1038d957823eSjayaprakash Mutyala               >
ipmiSensorGetDeviceSdrInfo(std::optional<uint8_t> count)1039d957823eSjayaprakash Mutyala     ipmiSensorGetDeviceSdrInfo(std::optional<uint8_t> count)
1040d06e0e7eSEmily Shaffer {
1041d957823eSjayaprakash Mutyala     uint8_t sdrCount;
1042d957823eSjayaprakash Mutyala     // multiple LUNs not supported.
1043d957823eSjayaprakash Mutyala     constexpr uint8_t lunsAndDynamicPopulation = 1;
1044d957823eSjayaprakash Mutyala     constexpr uint8_t getSdrCount = 0x01;
1045d957823eSjayaprakash Mutyala     constexpr uint8_t getSensorCount = 0x00;
1046d957823eSjayaprakash Mutyala 
1047d957823eSjayaprakash Mutyala     if (count.value_or(0) == getSdrCount)
1048d06e0e7eSEmily Shaffer     {
1049d957823eSjayaprakash Mutyala         // Get SDR count. This returns the total number of SDRs in the device.
105087fd2cd1SPatrick Venture         const auto& entityRecords =
105187fd2cd1SPatrick Venture             ipmi::sensor::EntityInfoMapContainer::getContainer()
105287fd2cd1SPatrick Venture                 ->getIpmiEntityRecords();
1053fbc6c9d7SPatrick Williams         sdrCount = ipmi::sensor::sensors.size() + frus.size() +
1054fbc6c9d7SPatrick Williams                    entityRecords.size();
1055d957823eSjayaprakash Mutyala     }
1056d957823eSjayaprakash Mutyala     else if (count.value_or(0) == getSensorCount)
1057d957823eSjayaprakash Mutyala     {
1058d957823eSjayaprakash Mutyala         // Get Sensor count. This returns the number of sensors
1059db0cbe64SPatrick Venture         sdrCount = ipmi::sensor::sensors.size();
1060d06e0e7eSEmily Shaffer     }
1061d06e0e7eSEmily Shaffer     else
1062d06e0e7eSEmily Shaffer     {
1063d957823eSjayaprakash Mutyala         return ipmi::responseInvalidCommandOnLun();
1064d06e0e7eSEmily Shaffer     }
1065d06e0e7eSEmily Shaffer 
1066d957823eSjayaprakash Mutyala     return ipmi::responseSuccess(sdrCount, lunsAndDynamicPopulation);
1067d06e0e7eSEmily Shaffer }
1068d06e0e7eSEmily Shaffer 
1069d957823eSjayaprakash Mutyala /** @brief implements the reserve SDR command
1070d957823eSjayaprakash Mutyala  *  @returns IPMI completion code plus response data
1071d957823eSjayaprakash Mutyala  *   - reservationID - reservation ID
1072d957823eSjayaprakash Mutyala  */
ipmiSensorReserveSdr()1073d957823eSjayaprakash Mutyala ipmi::RspType<uint16_t> ipmiSensorReserveSdr()
1074a344afc0SEmily Shaffer {
1075a344afc0SEmily Shaffer     // A constant reservation ID is okay until we implement add/remove SDR.
1076d957823eSjayaprakash Mutyala     constexpr uint16_t reservationID = 1;
1077a344afc0SEmily Shaffer 
1078d957823eSjayaprakash Mutyala     return ipmi::responseSuccess(reservationID);
1079a344afc0SEmily Shaffer }
108098a23840SMatthew Barth 
setUnitFieldsForObject(const ipmi::sensor::Info * info,get_sdr::SensorDataFullRecordBody * body)1081dc212b23STom Joseph void setUnitFieldsForObject(const ipmi::sensor::Info* info,
1082cc941e15SEmily Shaffer                             get_sdr::SensorDataFullRecordBody* body)
1083bbef71c2SEmily Shaffer {
1084523e2d1bSWilly Tu     namespace server = sdbusplus::server::xyz::openbmc_project::sensor;
1085dc212b23STom Joseph     try
1086dc212b23STom Joseph     {
1087dc212b23STom Joseph         auto unit = server::Value::convertUnitFromString(info->unit);
1088bbef71c2SEmily Shaffer         // Unit strings defined in
1089bbef71c2SEmily Shaffer         // phosphor-dbus-interfaces/xyz/openbmc_project/Sensor/Value.interface.yaml
1090bbef71c2SEmily Shaffer         switch (unit)
1091bbef71c2SEmily Shaffer         {
1092bbef71c2SEmily Shaffer             case server::Value::Unit::DegreesC:
1093bbef71c2SEmily Shaffer                 body->sensor_units_2_base = get_sdr::SENSOR_UNIT_DEGREES_C;
1094bbef71c2SEmily Shaffer                 break;
1095bbef71c2SEmily Shaffer             case server::Value::Unit::RPMS:
1096812e44c7SKirill Pakhomov                 body->sensor_units_2_base = get_sdr::SENSOR_UNIT_RPM;
1097bbef71c2SEmily Shaffer                 break;
1098bbef71c2SEmily Shaffer             case server::Value::Unit::Volts:
1099bbef71c2SEmily Shaffer                 body->sensor_units_2_base = get_sdr::SENSOR_UNIT_VOLTS;
1100bbef71c2SEmily Shaffer                 break;
1101bbef71c2SEmily Shaffer             case server::Value::Unit::Meters:
1102bbef71c2SEmily Shaffer                 body->sensor_units_2_base = get_sdr::SENSOR_UNIT_METERS;
1103bbef71c2SEmily Shaffer                 break;
1104bbef71c2SEmily Shaffer             case server::Value::Unit::Amperes:
1105bbef71c2SEmily Shaffer                 body->sensor_units_2_base = get_sdr::SENSOR_UNIT_AMPERES;
1106bbef71c2SEmily Shaffer                 break;
1107bbef71c2SEmily Shaffer             case server::Value::Unit::Joules:
1108bbef71c2SEmily Shaffer                 body->sensor_units_2_base = get_sdr::SENSOR_UNIT_JOULES;
1109bbef71c2SEmily Shaffer                 break;
1110dc212b23STom Joseph             case server::Value::Unit::Watts:
1111dc212b23STom Joseph                 body->sensor_units_2_base = get_sdr::SENSOR_UNIT_WATTS;
1112dc212b23STom Joseph                 break;
1113bbef71c2SEmily Shaffer             default:
1114cc941e15SEmily Shaffer                 // Cannot be hit.
1115b51bf9c8SPatrick Venture                 std::fprintf(stderr, "Unknown value unit type: = %s\n",
1116dc212b23STom Joseph                              info->unit.c_str());
1117cc941e15SEmily Shaffer         }
1118cc941e15SEmily Shaffer     }
111964678b85SPatrick Venture     catch (const sdbusplus::exception::InvalidEnumString& e)
1120cc941e15SEmily Shaffer     {
11213b1071adSGeorge Liu         lg2::warning("Warning: no unit provided for sensor!");
1122cc941e15SEmily Shaffer     }
1123cc941e15SEmily Shaffer }
1124cc941e15SEmily Shaffer 
populate_record_from_dbus(get_sdr::SensorDataFullRecordBody * body,const ipmi::sensor::Info * info,ipmi_data_len_t)1125cc941e15SEmily Shaffer ipmi_ret_t populate_record_from_dbus(get_sdr::SensorDataFullRecordBody* body,
1126cc941e15SEmily Shaffer                                      const ipmi::sensor::Info* info,
112711d68897SWilly Tu                                      ipmi_data_len_t)
1128cc941e15SEmily Shaffer {
1129cc941e15SEmily Shaffer     /* Functional sensor case */
1130cc941e15SEmily Shaffer     if (isAnalogSensor(info->propertyInterfaces.begin()->first))
1131cc941e15SEmily Shaffer     {
1132c5324251STony Lee         body->sensor_units_1 = info->sensorUnits1; // default is 0. unsigned, no
1133c5324251STony Lee                                                    // rate, no modifier, not a %
1134cc941e15SEmily Shaffer         /* Unit info */
1135dc212b23STom Joseph         setUnitFieldsForObject(info, body);
113610f4959aSEmily Shaffer 
113710f4959aSEmily Shaffer         get_sdr::body::set_b(info->coefficientB, body);
113810f4959aSEmily Shaffer         get_sdr::body::set_m(info->coefficientM, body);
113910f4959aSEmily Shaffer         get_sdr::body::set_b_exp(info->exponentB, body);
1140dc212b23STom Joseph         get_sdr::body::set_r_exp(info->exponentR, body);
11419642391dSTom Joseph     }
11429642391dSTom Joseph 
11439642391dSTom Joseph     /* ID string */
1144be4ffa87SJeremy Kerr     auto id_string = info->sensorName;
1145be4ffa87SJeremy Kerr 
1146be4ffa87SJeremy Kerr     if (id_string.empty())
1147be4ffa87SJeremy Kerr     {
1148be4ffa87SJeremy Kerr         id_string = info->sensorNameFunc(*info);
1149be4ffa87SJeremy Kerr     }
11509642391dSTom Joseph 
1151bbef71c2SEmily Shaffer     if (id_string.length() > FULL_RECORD_ID_STR_MAX_LENGTH)
1152bbef71c2SEmily Shaffer     {
1153bbef71c2SEmily Shaffer         get_sdr::body::set_id_strlen(FULL_RECORD_ID_STR_MAX_LENGTH, body);
1154bbef71c2SEmily Shaffer     }
1155bbef71c2SEmily Shaffer     else
1156bbef71c2SEmily Shaffer     {
1157bbef71c2SEmily Shaffer         get_sdr::body::set_id_strlen(id_string.length(), body);
1158bbef71c2SEmily Shaffer     }
115951136984SPaul Fertser     get_sdr::body::set_id_type(3, body); // "8-bit ASCII + Latin 1"
1160bbef71c2SEmily Shaffer     strncpy(body->id_string, id_string.c_str(),
1161bbef71c2SEmily Shaffer             get_sdr::body::get_id_strlen(body));
1162bbef71c2SEmily Shaffer 
1163bbef71c2SEmily Shaffer     return IPMI_CC_OK;
1164bbef71c2SEmily Shaffer };
1165bbef71c2SEmily Shaffer 
ipmi_fru_get_sdr(ipmi_request_t request,ipmi_response_t response,ipmi_data_len_t data_len)1166e0cc8553SRatan Gupta ipmi_ret_t ipmi_fru_get_sdr(ipmi_request_t request, ipmi_response_t response,
1167e0cc8553SRatan Gupta                             ipmi_data_len_t data_len)
1168e0cc8553SRatan Gupta {
1169e0cc8553SRatan Gupta     auto req = reinterpret_cast<get_sdr::GetSdrReq*>(request);
1170e0cc8553SRatan Gupta     auto resp = reinterpret_cast<get_sdr::GetSdrResp*>(response);
1171e0cc8553SRatan Gupta     get_sdr::SensorDataFruRecord record{};
1172e0cc8553SRatan Gupta     auto dataLength = 0;
1173e0cc8553SRatan Gupta 
1174e0cc8553SRatan Gupta     auto fru = frus.begin();
1175e0cc8553SRatan Gupta     uint8_t fruID{};
1176e0cc8553SRatan Gupta     auto recordID = get_sdr::request::get_record_id(req);
1177e0cc8553SRatan Gupta 
1178e0cc8553SRatan Gupta     fruID = recordID - FRU_RECORD_ID_START;
1179e0cc8553SRatan Gupta     fru = frus.find(fruID);
1180e0cc8553SRatan Gupta     if (fru == frus.end())
1181e0cc8553SRatan Gupta     {
1182e0cc8553SRatan Gupta         return IPMI_CC_SENSOR_INVALID;
1183e0cc8553SRatan Gupta     }
1184e0cc8553SRatan Gupta 
1185e0cc8553SRatan Gupta     /* Header */
1186e0cc8553SRatan Gupta     get_sdr::header::set_record_id(recordID, &(record.header));
1187e0cc8553SRatan Gupta     record.header.sdr_version = SDR_VERSION; // Based on IPMI Spec v2.0 rev 1.1
1188e0cc8553SRatan Gupta     record.header.record_type = get_sdr::SENSOR_DATA_FRU_RECORD;
1189e0cc8553SRatan Gupta     record.header.record_length = sizeof(record.key) + sizeof(record.body);
1190e0cc8553SRatan Gupta 
1191e0cc8553SRatan Gupta     /* Key */
1192e0cc8553SRatan Gupta     record.key.fruID = fruID;
1193e0cc8553SRatan Gupta     record.key.accessLun |= IPMI_LOGICAL_FRU;
119468d9d405SMatt Simmering     record.key.deviceAddress = BMCTargetAddress;
1195e0cc8553SRatan Gupta 
1196e0cc8553SRatan Gupta     /* Body */
1197e0cc8553SRatan Gupta     record.body.entityID = fru->second[0].entityID;
1198e0cc8553SRatan Gupta     record.body.entityInstance = fru->second[0].entityInstance;
1199e0cc8553SRatan Gupta     record.body.deviceType = fruInventoryDevice;
1200e0cc8553SRatan Gupta     record.body.deviceTypeModifier = IPMIFruInventory;
1201e0cc8553SRatan Gupta 
1202e0cc8553SRatan Gupta     /* Device ID string */
12030b02be92SPatrick Venture     auto deviceID =
12040b02be92SPatrick Venture         fru->second[0].path.substr(fru->second[0].path.find_last_of('/') + 1,
1205e0cc8553SRatan Gupta                                    fru->second[0].path.length());
1206e0cc8553SRatan Gupta 
1207e0cc8553SRatan Gupta     if (deviceID.length() > get_sdr::FRU_RECORD_DEVICE_ID_MAX_LENGTH)
1208e0cc8553SRatan Gupta     {
1209e0cc8553SRatan Gupta         get_sdr::body::set_device_id_strlen(
12100b02be92SPatrick Venture             get_sdr::FRU_RECORD_DEVICE_ID_MAX_LENGTH, &(record.body));
1211e0cc8553SRatan Gupta     }
1212e0cc8553SRatan Gupta     else
1213e0cc8553SRatan Gupta     {
12140b02be92SPatrick Venture         get_sdr::body::set_device_id_strlen(deviceID.length(), &(record.body));
1215e0cc8553SRatan Gupta     }
1216e0cc8553SRatan Gupta 
1217e0cc8553SRatan Gupta     strncpy(record.body.deviceID, deviceID.c_str(),
1218e0cc8553SRatan Gupta             get_sdr::body::get_device_id_strlen(&(record.body)));
1219e0cc8553SRatan Gupta 
1220e0cc8553SRatan Gupta     if (++fru == frus.end())
1221e0cc8553SRatan Gupta     {
12229c11894eSJaghathiswari Rankappagounder Natarajan         // we have reached till end of fru, so assign the next record id to
12239c11894eSJaghathiswari Rankappagounder Natarajan         // 512(Max fru ID = 511) + Entity Record ID(may start with 0).
122487fd2cd1SPatrick Venture         const auto& entityRecords =
122587fd2cd1SPatrick Venture             ipmi::sensor::EntityInfoMapContainer::getContainer()
122687fd2cd1SPatrick Venture                 ->getIpmiEntityRecords();
12271318a5edSPatrick Williams         auto next_record_id =
12281318a5edSPatrick Williams             (entityRecords.size())
12291318a5edSPatrick Williams                 ? entityRecords.begin()->first + ENTITY_RECORD_ID_START
12309c11894eSJaghathiswari Rankappagounder Natarajan                 : END_OF_RECORD;
12319c11894eSJaghathiswari Rankappagounder Natarajan         get_sdr::response::set_next_record_id(next_record_id, resp);
12329c11894eSJaghathiswari Rankappagounder Natarajan     }
12339c11894eSJaghathiswari Rankappagounder Natarajan     else
12349c11894eSJaghathiswari Rankappagounder Natarajan     {
12359c11894eSJaghathiswari Rankappagounder Natarajan         get_sdr::response::set_next_record_id(
12369c11894eSJaghathiswari Rankappagounder Natarajan             (FRU_RECORD_ID_START + fru->first), resp);
12379c11894eSJaghathiswari Rankappagounder Natarajan     }
12389c11894eSJaghathiswari Rankappagounder Natarajan 
12399c11894eSJaghathiswari Rankappagounder Natarajan     // Check for invalid offset size
12409c11894eSJaghathiswari Rankappagounder Natarajan     if (req->offset > sizeof(record))
12419c11894eSJaghathiswari Rankappagounder Natarajan     {
12429c11894eSJaghathiswari Rankappagounder Natarajan         return IPMI_CC_PARM_OUT_OF_RANGE;
12439c11894eSJaghathiswari Rankappagounder Natarajan     }
12449c11894eSJaghathiswari Rankappagounder Natarajan 
12459c11894eSJaghathiswari Rankappagounder Natarajan     dataLength = std::min(static_cast<size_t>(req->bytes_to_read),
12469c11894eSJaghathiswari Rankappagounder Natarajan                           sizeof(record) - req->offset);
12479c11894eSJaghathiswari Rankappagounder Natarajan 
12489c11894eSJaghathiswari Rankappagounder Natarajan     std::memcpy(resp->record_data,
12499c11894eSJaghathiswari Rankappagounder Natarajan                 reinterpret_cast<uint8_t*>(&record) + req->offset, dataLength);
12509c11894eSJaghathiswari Rankappagounder Natarajan 
12519c11894eSJaghathiswari Rankappagounder Natarajan     *data_len = dataLength;
12529c11894eSJaghathiswari Rankappagounder Natarajan     *data_len += 2; // additional 2 bytes for next record ID
12539c11894eSJaghathiswari Rankappagounder Natarajan 
12549c11894eSJaghathiswari Rankappagounder Natarajan     return IPMI_CC_OK;
12559c11894eSJaghathiswari Rankappagounder Natarajan }
12569c11894eSJaghathiswari Rankappagounder Natarajan 
ipmi_entity_get_sdr(ipmi_request_t request,ipmi_response_t response,ipmi_data_len_t data_len)12579c11894eSJaghathiswari Rankappagounder Natarajan ipmi_ret_t ipmi_entity_get_sdr(ipmi_request_t request, ipmi_response_t response,
12589c11894eSJaghathiswari Rankappagounder Natarajan                                ipmi_data_len_t data_len)
12599c11894eSJaghathiswari Rankappagounder Natarajan {
12609c11894eSJaghathiswari Rankappagounder Natarajan     auto req = reinterpret_cast<get_sdr::GetSdrReq*>(request);
12619c11894eSJaghathiswari Rankappagounder Natarajan     auto resp = reinterpret_cast<get_sdr::GetSdrResp*>(response);
12629c11894eSJaghathiswari Rankappagounder Natarajan     get_sdr::SensorDataEntityRecord record{};
12639c11894eSJaghathiswari Rankappagounder Natarajan     auto dataLength = 0;
12649c11894eSJaghathiswari Rankappagounder Natarajan 
126587fd2cd1SPatrick Venture     const auto& entityRecords =
126687fd2cd1SPatrick Venture         ipmi::sensor::EntityInfoMapContainer::getContainer()
126787fd2cd1SPatrick Venture             ->getIpmiEntityRecords();
126883a0b848SPatrick Venture     auto entity = entityRecords.begin();
12699c11894eSJaghathiswari Rankappagounder Natarajan     uint8_t entityRecordID;
12709c11894eSJaghathiswari Rankappagounder Natarajan     auto recordID = get_sdr::request::get_record_id(req);
12719c11894eSJaghathiswari Rankappagounder Natarajan 
12729c11894eSJaghathiswari Rankappagounder Natarajan     entityRecordID = recordID - ENTITY_RECORD_ID_START;
127383a0b848SPatrick Venture     entity = entityRecords.find(entityRecordID);
127483a0b848SPatrick Venture     if (entity == entityRecords.end())
12759c11894eSJaghathiswari Rankappagounder Natarajan     {
12769c11894eSJaghathiswari Rankappagounder Natarajan         return IPMI_CC_SENSOR_INVALID;
12779c11894eSJaghathiswari Rankappagounder Natarajan     }
12789c11894eSJaghathiswari Rankappagounder Natarajan 
12799c11894eSJaghathiswari Rankappagounder Natarajan     /* Header */
12809c11894eSJaghathiswari Rankappagounder Natarajan     get_sdr::header::set_record_id(recordID, &(record.header));
12819c11894eSJaghathiswari Rankappagounder Natarajan     record.header.sdr_version = SDR_VERSION; // Based on IPMI Spec v2.0 rev 1.1
12829c11894eSJaghathiswari Rankappagounder Natarajan     record.header.record_type = get_sdr::SENSOR_DATA_ENTITY_RECORD;
12839c11894eSJaghathiswari Rankappagounder Natarajan     record.header.record_length = sizeof(record.key) + sizeof(record.body);
12849c11894eSJaghathiswari Rankappagounder Natarajan 
12859c11894eSJaghathiswari Rankappagounder Natarajan     /* Key */
12869c11894eSJaghathiswari Rankappagounder Natarajan     record.key.containerEntityId = entity->second.containerEntityId;
12879c11894eSJaghathiswari Rankappagounder Natarajan     record.key.containerEntityInstance = entity->second.containerEntityInstance;
12889c11894eSJaghathiswari Rankappagounder Natarajan     get_sdr::key::set_flags(entity->second.isList, entity->second.isLinked,
12899c11894eSJaghathiswari Rankappagounder Natarajan                             &(record.key));
12909c11894eSJaghathiswari Rankappagounder Natarajan     record.key.entityId1 = entity->second.containedEntities[0].first;
12919c11894eSJaghathiswari Rankappagounder Natarajan     record.key.entityInstance1 = entity->second.containedEntities[0].second;
12929c11894eSJaghathiswari Rankappagounder Natarajan 
12939c11894eSJaghathiswari Rankappagounder Natarajan     /* Body */
12949c11894eSJaghathiswari Rankappagounder Natarajan     record.body.entityId2 = entity->second.containedEntities[1].first;
12959c11894eSJaghathiswari Rankappagounder Natarajan     record.body.entityInstance2 = entity->second.containedEntities[1].second;
12969c11894eSJaghathiswari Rankappagounder Natarajan     record.body.entityId3 = entity->second.containedEntities[2].first;
12979c11894eSJaghathiswari Rankappagounder Natarajan     record.body.entityInstance3 = entity->second.containedEntities[2].second;
12989c11894eSJaghathiswari Rankappagounder Natarajan     record.body.entityId4 = entity->second.containedEntities[3].first;
12999c11894eSJaghathiswari Rankappagounder Natarajan     record.body.entityInstance4 = entity->second.containedEntities[3].second;
13009c11894eSJaghathiswari Rankappagounder Natarajan 
130183a0b848SPatrick Venture     if (++entity == entityRecords.end())
13029c11894eSJaghathiswari Rankappagounder Natarajan     {
13030b02be92SPatrick Venture         get_sdr::response::set_next_record_id(END_OF_RECORD,
13040b02be92SPatrick Venture                                               resp); // last record
1305e0cc8553SRatan Gupta     }
1306e0cc8553SRatan Gupta     else
1307e0cc8553SRatan Gupta     {
1308e0cc8553SRatan Gupta         get_sdr::response::set_next_record_id(
13099c11894eSJaghathiswari Rankappagounder Natarajan             (ENTITY_RECORD_ID_START + entity->first), resp);
1310e0cc8553SRatan Gupta     }
1311e0cc8553SRatan Gupta 
13120fbdbce2SEmily Shaffer     // Check for invalid offset size
13130fbdbce2SEmily Shaffer     if (req->offset > sizeof(record))
1314e0cc8553SRatan Gupta     {
13150fbdbce2SEmily Shaffer         return IPMI_CC_PARM_OUT_OF_RANGE;
1316e0cc8553SRatan Gupta     }
1317e0cc8553SRatan Gupta 
13180fbdbce2SEmily Shaffer     dataLength = std::min(static_cast<size_t>(req->bytes_to_read),
13190fbdbce2SEmily Shaffer                           sizeof(record) - req->offset);
1320e0cc8553SRatan Gupta 
1321b51bf9c8SPatrick Venture     std::memcpy(resp->record_data,
13221cd85963SJason M. Bills                 reinterpret_cast<uint8_t*>(&record) + req->offset, dataLength);
1323e0cc8553SRatan Gupta 
1324e0cc8553SRatan Gupta     *data_len = dataLength;
1325e0cc8553SRatan Gupta     *data_len += 2; // additional 2 bytes for next record ID
1326e0cc8553SRatan Gupta 
1327e0cc8553SRatan Gupta     return IPMI_CC_OK;
1328e0cc8553SRatan Gupta }
1329e0cc8553SRatan 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)133011d68897SWilly Tu ipmi_ret_t ipmi_sen_get_sdr(ipmi_netfn_t, ipmi_cmd_t, ipmi_request_t request,
133111d68897SWilly Tu                             ipmi_response_t response, ipmi_data_len_t data_len,
133211d68897SWilly Tu                             ipmi_context_t)
1333bbef71c2SEmily Shaffer {
1334bbef71c2SEmily Shaffer     ipmi_ret_t ret = IPMI_CC_OK;
1335bbef71c2SEmily Shaffer     get_sdr::GetSdrReq* req = (get_sdr::GetSdrReq*)request;
1336bbef71c2SEmily Shaffer     get_sdr::GetSdrResp* resp = (get_sdr::GetSdrResp*)response;
133738426dd5SPatrick Venture 
1338bbef71c2SEmily Shaffer     // Note: we use an iterator so we can provide the next ID at the end of
1339bbef71c2SEmily Shaffer     // the call.
1340db0cbe64SPatrick Venture     auto sensor = ipmi::sensor::sensors.begin();
1341e0cc8553SRatan Gupta     auto recordID = get_sdr::request::get_record_id(req);
1342bbef71c2SEmily Shaffer 
1343bbef71c2SEmily Shaffer     // At the beginning of a scan, the host side will send us id=0.
1344e0cc8553SRatan Gupta     if (recordID != 0)
1345bbef71c2SEmily Shaffer     {
13469c11894eSJaghathiswari Rankappagounder Natarajan         // recordID 0 to 255 means it is a FULL record.
13479c11894eSJaghathiswari Rankappagounder Natarajan         // recordID 256 to 511 means it is a FRU record.
13489c11894eSJaghathiswari Rankappagounder Natarajan         // recordID greater then 511 means it is a Entity Association
13499c11894eSJaghathiswari Rankappagounder Natarajan         // record. Currently we are supporting three record types: FULL
13509c11894eSJaghathiswari Rankappagounder Natarajan         // record, FRU record and Enttiy Association record.
13519c11894eSJaghathiswari Rankappagounder Natarajan         if (recordID >= ENTITY_RECORD_ID_START)
13529c11894eSJaghathiswari Rankappagounder Natarajan         {
13539c11894eSJaghathiswari Rankappagounder Natarajan             return ipmi_entity_get_sdr(request, response, data_len);
13549c11894eSJaghathiswari Rankappagounder Natarajan         }
13559c11894eSJaghathiswari Rankappagounder Natarajan         else if (recordID >= FRU_RECORD_ID_START &&
13569c11894eSJaghathiswari Rankappagounder Natarajan                  recordID < ENTITY_RECORD_ID_START)
1357e0cc8553SRatan Gupta         {
1358e0cc8553SRatan Gupta             return ipmi_fru_get_sdr(request, response, data_len);
1359e0cc8553SRatan Gupta         }
1360e0cc8553SRatan Gupta         else
1361e0cc8553SRatan Gupta         {
1362db0cbe64SPatrick Venture             sensor = ipmi::sensor::sensors.find(recordID);
1363db0cbe64SPatrick Venture             if (sensor == ipmi::sensor::sensors.end())
1364e0cc8553SRatan Gupta             {
1365bbef71c2SEmily Shaffer                 return IPMI_CC_SENSOR_INVALID;
1366bbef71c2SEmily Shaffer             }
1367bbef71c2SEmily Shaffer         }
1368e0cc8553SRatan Gupta     }
1369bbef71c2SEmily Shaffer 
1370bbef71c2SEmily Shaffer     uint8_t sensor_id = sensor->first;
1371bbef71c2SEmily Shaffer 
137214a47819SLei YU     auto it = sdrCacheMap.find(sensor_id);
137314a47819SLei YU     if (it == sdrCacheMap.end())
137414a47819SLei YU     {
1375bbef71c2SEmily Shaffer         /* Header */
137611d68897SWilly Tu         get_sdr::SensorDataFullRecord record = {};
1377bbef71c2SEmily Shaffer         get_sdr::header::set_record_id(sensor_id, &(record.header));
1378bbef71c2SEmily Shaffer         record.header.sdr_version = 0x51; // Based on IPMI Spec v2.0 rev 1.1
1379bbef71c2SEmily Shaffer         record.header.record_type = get_sdr::SENSOR_DATA_FULL_RECORD;
1380158ac703SPatrick Venture         record.header.record_length = sizeof(record.key) + sizeof(record.body);
1381bbef71c2SEmily Shaffer 
1382bbef71c2SEmily Shaffer         /* Key */
13839642391dSTom Joseph         get_sdr::key::set_owner_id_bmc(&(record.key));
1384bbef71c2SEmily Shaffer         record.key.sensor_number = sensor_id;
1385bbef71c2SEmily Shaffer 
1386bbef71c2SEmily Shaffer         /* Body */
13879642391dSTom Joseph         record.body.entity_id = sensor->second.entityType;
1388bbef71c2SEmily Shaffer         record.body.sensor_type = sensor->second.sensorType;
1389bbef71c2SEmily Shaffer         record.body.event_reading_type = sensor->second.sensorReadingType;
13909642391dSTom Joseph         record.body.entity_instance = sensor->second.instance;
13910780df10SJaghathiswari Rankappagounder Natarajan         if (ipmi::sensor::Mutability::Write ==
13920780df10SJaghathiswari Rankappagounder Natarajan             (sensor->second.mutability & ipmi::sensor::Mutability::Write))
13930780df10SJaghathiswari Rankappagounder Natarajan         {
13940780df10SJaghathiswari Rankappagounder Natarajan             get_sdr::body::init_settable_state(true, &(record.body));
13950780df10SJaghathiswari Rankappagounder Natarajan         }
1396bbef71c2SEmily Shaffer 
1397bbef71c2SEmily Shaffer         // Set the type-specific details given the DBus interface
139838426dd5SPatrick Venture         populate_record_from_dbus(&(record.body), &(sensor->second), data_len);
139914a47819SLei YU         sdrCacheMap[sensor_id] = std::move(record);
140014a47819SLei YU     }
140114a47819SLei YU 
140214a47819SLei YU     const auto& record = sdrCacheMap[sensor_id];
1403bbef71c2SEmily Shaffer 
1404db0cbe64SPatrick Venture     if (++sensor == ipmi::sensor::sensors.end())
1405bbef71c2SEmily Shaffer     {
1406e0cc8553SRatan Gupta         // we have reached till end of sensor, so assign the next record id
1407e0cc8553SRatan Gupta         // to 256(Max Sensor ID = 255) + FRU ID(may start with 0).
140838426dd5SPatrick Venture         auto next_record_id = (frus.size())
140938426dd5SPatrick Venture                                   ? frus.begin()->first + FRU_RECORD_ID_START
14100b02be92SPatrick Venture                                   : END_OF_RECORD;
1411e0cc8553SRatan Gupta 
1412e0cc8553SRatan Gupta         get_sdr::response::set_next_record_id(next_record_id, resp);
1413bbef71c2SEmily Shaffer     }
1414bbef71c2SEmily Shaffer     else
1415bbef71c2SEmily Shaffer     {
1416bbef71c2SEmily Shaffer         get_sdr::response::set_next_record_id(sensor->first, resp);
1417bbef71c2SEmily Shaffer     }
1418bbef71c2SEmily Shaffer 
14196c9ee519SEmily Shaffer     if (req->offset > sizeof(record))
14206c9ee519SEmily Shaffer     {
14216c9ee519SEmily Shaffer         return IPMI_CC_PARM_OUT_OF_RANGE;
14226c9ee519SEmily Shaffer     }
14236c9ee519SEmily Shaffer 
14246c9ee519SEmily Shaffer     // data_len will ultimately be the size of the record, plus
14256c9ee519SEmily Shaffer     // the size of the next record ID:
14266c9ee519SEmily Shaffer     *data_len = std::min(static_cast<size_t>(req->bytes_to_read),
14276c9ee519SEmily Shaffer                          sizeof(record) - req->offset);
14286c9ee519SEmily Shaffer 
14296c9ee519SEmily Shaffer     std::memcpy(resp->record_data,
143014a47819SLei YU                 reinterpret_cast<const uint8_t*>(&record) + req->offset,
143114a47819SLei YU                 *data_len);
14326c9ee519SEmily Shaffer 
14336c9ee519SEmily Shaffer     // data_len should include the LSB and MSB:
1434fbc6c9d7SPatrick Williams     *data_len += sizeof(resp->next_record_id_lsb) +
1435fbc6c9d7SPatrick Williams                  sizeof(resp->next_record_id_msb);
1436bbef71c2SEmily Shaffer 
1437bbef71c2SEmily Shaffer     return ret;
1438bbef71c2SEmily Shaffer }
1439bbef71c2SEmily Shaffer 
isFromSystemChannel()14403342a8e0SJia, Chunhui static bool isFromSystemChannel()
14413342a8e0SJia, Chunhui {
14423342a8e0SJia, Chunhui     // TODO we could not figure out where the request is from based on IPMI
14433342a8e0SJia, Chunhui     // command handler parameters. because of it, we can not differentiate
14443342a8e0SJia, Chunhui     // request from SMS/SMM or IPMB channel
14453342a8e0SJia, Chunhui     return true;
14463342a8e0SJia, Chunhui }
14473342a8e0SJia, Chunhui 
ipmicmdPlatformEvent(ipmi_netfn_t,ipmi_cmd_t,ipmi_request_t request,ipmi_response_t,ipmi_data_len_t dataLen,ipmi_context_t)144811d68897SWilly Tu ipmi_ret_t ipmicmdPlatformEvent(ipmi_netfn_t, ipmi_cmd_t,
144911d68897SWilly Tu                                 ipmi_request_t request, ipmi_response_t,
145011d68897SWilly Tu                                 ipmi_data_len_t dataLen, ipmi_context_t)
14513342a8e0SJia, Chunhui {
14523342a8e0SJia, Chunhui     uint16_t generatorID;
14533342a8e0SJia, Chunhui     size_t count;
14543342a8e0SJia, Chunhui     bool assert = true;
14553342a8e0SJia, Chunhui     std::string sensorPath;
14563342a8e0SJia, Chunhui     size_t paraLen = *dataLen;
14573342a8e0SJia, Chunhui     PlatformEventRequest* req;
14583342a8e0SJia, Chunhui     *dataLen = 0;
14593342a8e0SJia, Chunhui 
14603342a8e0SJia, Chunhui     if ((paraLen < selSystemEventSizeWith1Bytes) ||
14613342a8e0SJia, Chunhui         (paraLen > selSystemEventSizeWith3Bytes))
14623342a8e0SJia, Chunhui     {
14633342a8e0SJia, Chunhui         return IPMI_CC_REQ_DATA_LEN_INVALID;
14643342a8e0SJia, Chunhui     }
14653342a8e0SJia, Chunhui 
14663342a8e0SJia, Chunhui     if (isFromSystemChannel())
14673342a8e0SJia, Chunhui     { // first byte for SYSTEM Interface is Generator ID
14683342a8e0SJia, Chunhui         // +1 to get common struct
14693342a8e0SJia, Chunhui         req = reinterpret_cast<PlatformEventRequest*>((uint8_t*)request + 1);
14703342a8e0SJia, Chunhui         // Capture the generator ID
14713342a8e0SJia, Chunhui         generatorID = *reinterpret_cast<uint8_t*>(request);
14723342a8e0SJia, Chunhui         // Platform Event usually comes from other firmware, like BIOS.
14733342a8e0SJia, Chunhui         // Unlike BMC sensor, it does not have BMC DBUS sensor path.
14743342a8e0SJia, Chunhui         sensorPath = "System";
14753342a8e0SJia, Chunhui     }
14763342a8e0SJia, Chunhui     else
14773342a8e0SJia, Chunhui     {
14783342a8e0SJia, Chunhui         req = reinterpret_cast<PlatformEventRequest*>(request);
14793342a8e0SJia, Chunhui         // TODO GenratorID for IPMB is combination of RqSA and RqLUN
14803342a8e0SJia, Chunhui         generatorID = 0xff;
14813342a8e0SJia, Chunhui         sensorPath = "IPMB";
14823342a8e0SJia, Chunhui     }
14833342a8e0SJia, Chunhui     // Content of event data field depends on sensor class.
14843342a8e0SJia, Chunhui     // When data0 bit[5:4] is non-zero, valid data counts is 3.
14853342a8e0SJia, Chunhui     // When data0 bit[7:6] is non-zero, valid data counts is 2.
14863342a8e0SJia, Chunhui     if (((req->data[0] & byte3EnableMask) != 0 &&
14873342a8e0SJia, Chunhui          paraLen < selSystemEventSizeWith3Bytes) ||
14883342a8e0SJia, Chunhui         ((req->data[0] & byte2EnableMask) != 0 &&
14893342a8e0SJia, Chunhui          paraLen < selSystemEventSizeWith2Bytes))
14903342a8e0SJia, Chunhui     {
14913342a8e0SJia, Chunhui         return IPMI_CC_REQ_DATA_LEN_INVALID;
14923342a8e0SJia, Chunhui     }
14933342a8e0SJia, Chunhui 
14943342a8e0SJia, Chunhui     // Count bytes of Event Data
14953342a8e0SJia, Chunhui     if ((req->data[0] & byte3EnableMask) != 0)
14963342a8e0SJia, Chunhui     {
14973342a8e0SJia, Chunhui         count = 3;
14983342a8e0SJia, Chunhui     }
14993342a8e0SJia, Chunhui     else if ((req->data[0] & byte2EnableMask) != 0)
15003342a8e0SJia, Chunhui     {
15013342a8e0SJia, Chunhui         count = 2;
15023342a8e0SJia, Chunhui     }
15033342a8e0SJia, Chunhui     else
15043342a8e0SJia, Chunhui     {
15053342a8e0SJia, Chunhui         count = 1;
15063342a8e0SJia, Chunhui     }
15073342a8e0SJia, Chunhui     assert = req->eventDirectionType & directionMask ? false : true;
15083342a8e0SJia, Chunhui     std::vector<uint8_t> eventData(req->data, req->data + count);
15093342a8e0SJia, Chunhui 
15105d82f474SPatrick Williams     sdbusplus::bus_t dbus(bus);
15111318a5edSPatrick Williams     std::string service =
15121318a5edSPatrick Williams         ipmi::getService(dbus, ipmiSELAddInterface, ipmiSELPath);
15135d82f474SPatrick Williams     sdbusplus::message_t writeSEL = dbus.new_method_call(
15143342a8e0SJia, Chunhui         service.c_str(), ipmiSELPath, ipmiSELAddInterface, "IpmiSelAdd");
15153342a8e0SJia, Chunhui     writeSEL.append(ipmiSELAddMessage, sensorPath, eventData, assert,
15163342a8e0SJia, Chunhui                     generatorID);
15173342a8e0SJia, Chunhui     try
15183342a8e0SJia, Chunhui     {
15193342a8e0SJia, Chunhui         dbus.call(writeSEL);
15203342a8e0SJia, Chunhui     }
1521a2ad2da8SPatrick Williams     catch (const sdbusplus::exception_t& e)
15223342a8e0SJia, Chunhui     {
15233b1071adSGeorge Liu         lg2::error("exception message: {ERROR}", "ERROR", e);
15243342a8e0SJia, Chunhui         return IPMI_CC_UNSPECIFIED_ERROR;
15253342a8e0SJia, Chunhui     }
15263342a8e0SJia, Chunhui     return IPMI_CC_OK;
15273342a8e0SJia, Chunhui }
15283342a8e0SJia, Chunhui 
registerNetFnSenFunctions()15295087b075SGeorge Liu void registerNetFnSenFunctions()
153098a23840SMatthew Barth {
1531d351a729SWilly Tu     // Handlers with dbus-sdr handler implementation.
1532d351a729SWilly Tu     // Do not register the hander if it dynamic sensors stack is used.
1533a8be7dc8SDeepak Kumar Sahu 
1534d351a729SWilly Tu #ifndef FEATURE_DYNAMIC_SENSORS
1535be5c6b2aSLei YU 
1536962e68baSLei YU #ifdef FEATURE_SENSORS_CACHE
1537be5c6b2aSLei YU     // Initialize the sensor matches
1538be5c6b2aSLei YU     initSensorMatches();
1539962e68baSLei YU #endif
1540be5c6b2aSLei YU 
15410573237fSTom     // <Set Sensor Reading and Event Status>
15429da3a750SDeepak Kumar Sahu     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnSensor,
15439da3a750SDeepak Kumar Sahu                           ipmi::sensor_event::cmdSetSensorReadingAndEvtSts,
15449da3a750SDeepak Kumar Sahu                           ipmi::Privilege::Operator, ipmiSetSensorReading);
15450573237fSTom     // <Get Sensor Reading>
15464c3feba5Sjayaprakash Mutyala     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnSensor,
15474c3feba5Sjayaprakash Mutyala                           ipmi::sensor_event::cmdGetSensorReading,
15484c3feba5Sjayaprakash Mutyala                           ipmi::Privilege::User, ipmiSensorGetSensorReading);
1549a344afc0SEmily Shaffer 
15505ca50959STom Joseph     // <Reserve Device SDR Repository>
1551d957823eSjayaprakash Mutyala     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnSensor,
1552d957823eSjayaprakash Mutyala                           ipmi::sensor_event::cmdReserveDeviceSdrRepository,
1553d957823eSjayaprakash Mutyala                           ipmi::Privilege::User, ipmiSensorReserveSdr);
155498a23840SMatthew Barth 
15555ca50959STom Joseph     // <Get Device SDR Info>
1556d957823eSjayaprakash Mutyala     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnSensor,
1557d957823eSjayaprakash Mutyala                           ipmi::sensor_event::cmdGetDeviceSdrInfo,
1558d957823eSjayaprakash Mutyala                           ipmi::Privilege::User, ipmiSensorGetDeviceSdrInfo);
1559bbef71c2SEmily Shaffer 
15605c0beec1SDhruvaraj Subhashchandran     // <Get Sensor Thresholds>
1561996c9798Sjayaprakash Mutyala     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnSensor,
1562996c9798Sjayaprakash Mutyala                           ipmi::sensor_event::cmdGetSensorThreshold,
1563996c9798Sjayaprakash Mutyala                           ipmi::Privilege::User, ipmiSensorGetSensorThresholds);
15645c0beec1SDhruvaraj Subhashchandran 
1565f93da667SLotus Xu     // <Set Sensor Thresholds>
1566f93da667SLotus Xu     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnSensor,
1567f93da667SLotus Xu                           ipmi::sensor_event::cmdSetSensorThreshold,
1568f93da667SLotus Xu                           ipmi::Privilege::User, ipmiSenSetSensorThresholds);
1569d3d2fe29SVivekanand Veeracholan 
1570d3d2fe29SVivekanand Veeracholan     // <Get Device SDR>
1571f7452cb6SGeorge Liu     ipmi_register_callback(NETFUN_SENSOR, ipmi::sensor_event::cmdGetDeviceSdr,
1572f7452cb6SGeorge Liu                            nullptr, ipmi_sen_get_sdr, PRIVILEGE_USER);
1573d3d2fe29SVivekanand Veeracholan 
1574d351a729SWilly Tu #endif
1575d351a729SWilly Tu 
1576d351a729SWilly Tu     // Common Handers used by both implementation.
1577d351a729SWilly Tu 
1578d351a729SWilly Tu     // <Platform Event Message>
1579f7452cb6SGeorge Liu     ipmi_register_callback(NETFUN_SENSOR, ipmi::sensor_event::cmdPlatformEvent,
1580f7452cb6SGeorge Liu                            nullptr, ipmicmdPlatformEvent, PRIVILEGE_OPERATOR);
1581d351a729SWilly Tu 
1582d351a729SWilly Tu     // <Get Sensor Type>
1583d351a729SWilly Tu     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnSensor,
1584d351a729SWilly Tu                           ipmi::sensor_event::cmdGetSensorType,
1585d351a729SWilly Tu                           ipmi::Privilege::User, ipmiGetSensorType);
1586d351a729SWilly Tu 
158798a23840SMatthew Barth     return;
158898a23840SMatthew Barth }
1589