1 #include "config.h"
2 
3 #include "sensorhandler.hpp"
4 
5 #include "fruread.hpp"
6 
7 #include <mapper.h>
8 #include <systemd/sd-bus.h>
9 
10 #include <bitset>
11 #include <cmath>
12 #include <cstring>
13 #include <ipmid/api.hpp>
14 #include <ipmid/types.hpp>
15 #include <ipmid/utils.hpp>
16 #include <phosphor-logging/elog-errors.hpp>
17 #include <phosphor-logging/log.hpp>
18 #include <sdbusplus/message/types.hpp>
19 #include <set>
20 #include <xyz/openbmc_project/Common/error.hpp>
21 #include <xyz/openbmc_project/Sensor/Value/server.hpp>
22 
23 static constexpr uint8_t fruInventoryDevice = 0x10;
24 static constexpr uint8_t IPMIFruInventory = 0x02;
25 static constexpr uint8_t BMCSlaveAddress = 0x20;
26 
27 extern int updateSensorRecordFromSSRAESC(const void*);
28 extern sd_bus* bus;
29 
30 namespace ipmi
31 {
32 namespace sensor
33 {
34 extern const IdInfoMap sensors;
35 } // namespace sensor
36 } // namespace ipmi
37 
38 extern const FruMap frus;
39 
40 using namespace phosphor::logging;
41 using InternalFailure =
42     sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure;
43 
44 void register_netfn_sen_functions() __attribute__((constructor));
45 
46 struct sensorTypemap_t
47 {
48     uint8_t number;
49     uint8_t typecode;
50     char dbusname[32];
51 };
52 
53 sensorTypemap_t g_SensorTypeMap[] = {
54 
55     {0x01, 0x6F, "Temp"},
56     {0x0C, 0x6F, "DIMM"},
57     {0x0C, 0x6F, "MEMORY_BUFFER"},
58     {0x07, 0x6F, "PROC"},
59     {0x07, 0x6F, "CORE"},
60     {0x07, 0x6F, "CPU"},
61     {0x0F, 0x6F, "BootProgress"},
62     {0xe9, 0x09, "OccStatus"}, // E9 is an internal mapping to handle sensor
63                                // type code os 0x09
64     {0xC3, 0x6F, "BootCount"},
65     {0x1F, 0x6F, "OperatingSystemStatus"},
66     {0x12, 0x6F, "SYSTEM_EVENT"},
67     {0xC7, 0x03, "SYSTEM"},
68     {0xC7, 0x03, "MAIN_PLANAR"},
69     {0xC2, 0x6F, "PowerCap"},
70     {0x0b, 0xCA, "PowerSupplyRedundancy"},
71     {0xDA, 0x03, "TurboAllowed"},
72     {0xD8, 0xC8, "PowerSupplyDerating"},
73     {0xFF, 0x00, ""},
74 };
75 
76 struct sensor_data_t
77 {
78     uint8_t sennum;
79 } __attribute__((packed));
80 
81 struct sensorreadingresp_t
82 {
83     uint8_t value;
84     uint8_t operation;
85     uint8_t indication[2];
86 } __attribute__((packed));
87 
88 namespace ipmi
89 {
90 namespace sensor
91 {
92 extern const EntityInfoMap entities;
93 
94 const EntityInfoMap& getIpmiEntityRecords()
95 {
96     return entities;
97 }
98 
99 } // namespace sensor
100 } // namespace ipmi
101 
102 int get_bus_for_path(const char* path, char** busname)
103 {
104     return mapper_get_service(bus, path, busname);
105 }
106 
107 // Use a lookup table to find the interface name of a specific sensor
108 // This will be used until an alternative is found.  this is the first
109 // step for mapping IPMI
110 int find_openbmc_path(uint8_t num, dbus_interface_t* interface)
111 {
112     int rc;
113 
114     const auto& sensor_it = ipmi::sensor::sensors.find(num);
115     if (sensor_it == ipmi::sensor::sensors.end())
116     {
117         // The sensor map does not contain the sensor requested
118         return -EINVAL;
119     }
120 
121     const auto& info = sensor_it->second;
122 
123     char* busname = nullptr;
124     rc = get_bus_for_path(info.sensorPath.c_str(), &busname);
125     if (rc < 0)
126     {
127         std::fprintf(stderr, "Failed to get %s busname: %s\n",
128                      info.sensorPath.c_str(), busname);
129         goto final;
130     }
131 
132     interface->sensortype = info.sensorType;
133     strcpy(interface->bus, busname);
134     strcpy(interface->path, info.sensorPath.c_str());
135     // Take the interface name from the beginning of the DbusInterfaceMap. This
136     // works for the Value interface but may not suffice for more complex
137     // sensors.
138     // tracked https://github.com/openbmc/phosphor-host-ipmid/issues/103
139     strcpy(interface->interface,
140            info.propertyInterfaces.begin()->first.c_str());
141     interface->sensornumber = num;
142 
143 final:
144     free(busname);
145     return rc;
146 }
147 
148 /////////////////////////////////////////////////////////////////////
149 //
150 // Routines used by ipmi commands wanting to interact on the dbus
151 //
152 /////////////////////////////////////////////////////////////////////
153 int set_sensor_dbus_state_s(uint8_t number, const char* method,
154                             const char* value)
155 {
156 
157     dbus_interface_t a;
158     int r;
159     sd_bus_error error = SD_BUS_ERROR_NULL;
160     sd_bus_message* m = NULL;
161 
162     r = find_openbmc_path(number, &a);
163 
164     if (r < 0)
165     {
166         std::fprintf(stderr, "Failed to find Sensor 0x%02x\n", number);
167         return 0;
168     }
169 
170     r = sd_bus_message_new_method_call(bus, &m, a.bus, a.path, a.interface,
171                                        method);
172     if (r < 0)
173     {
174         std::fprintf(stderr, "Failed to create a method call: %s",
175                      strerror(-r));
176         goto final;
177     }
178 
179     r = sd_bus_message_append(m, "v", "s", value);
180     if (r < 0)
181     {
182         std::fprintf(stderr, "Failed to create a input parameter: %s",
183                      strerror(-r));
184         goto final;
185     }
186 
187     r = sd_bus_call(bus, m, 0, &error, NULL);
188     if (r < 0)
189     {
190         std::fprintf(stderr, "Failed to call the method: %s", strerror(-r));
191     }
192 
193 final:
194     sd_bus_error_free(&error);
195     m = sd_bus_message_unref(m);
196 
197     return 0;
198 }
199 int set_sensor_dbus_state_y(uint8_t number, const char* method,
200                             const uint8_t value)
201 {
202 
203     dbus_interface_t a;
204     int r;
205     sd_bus_error error = SD_BUS_ERROR_NULL;
206     sd_bus_message* m = NULL;
207 
208     r = find_openbmc_path(number, &a);
209 
210     if (r < 0)
211     {
212         std::fprintf(stderr, "Failed to find Sensor 0x%02x\n", number);
213         return 0;
214     }
215 
216     r = sd_bus_message_new_method_call(bus, &m, a.bus, a.path, a.interface,
217                                        method);
218     if (r < 0)
219     {
220         std::fprintf(stderr, "Failed to create a method call: %s",
221                      strerror(-r));
222         goto final;
223     }
224 
225     r = sd_bus_message_append(m, "v", "i", value);
226     if (r < 0)
227     {
228         std::fprintf(stderr, "Failed to create a input parameter: %s",
229                      strerror(-r));
230         goto final;
231     }
232 
233     r = sd_bus_call(bus, m, 0, &error, NULL);
234     if (r < 0)
235     {
236         std::fprintf(stderr, "12 Failed to call the method: %s", strerror(-r));
237     }
238 
239 final:
240     sd_bus_error_free(&error);
241     m = sd_bus_message_unref(m);
242 
243     return 0;
244 }
245 
246 uint8_t dbus_to_sensor_type(char* p)
247 {
248 
249     sensorTypemap_t* s = g_SensorTypeMap;
250     char r = 0;
251     while (s->number != 0xFF)
252     {
253         if (!strcmp(s->dbusname, p))
254         {
255             r = s->typecode;
256             break;
257         }
258         s++;
259     }
260 
261     if (s->number == 0xFF)
262         printf("Failed to find Sensor Type %s\n", p);
263 
264     return r;
265 }
266 
267 uint8_t get_type_from_interface(dbus_interface_t dbus_if)
268 {
269 
270     uint8_t type;
271 
272     // This is where sensors that do not exist in dbus but do
273     // exist in the host code stop.  This should indicate it
274     // is not a supported sensor
275     if (dbus_if.interface[0] == 0)
276     {
277         return 0;
278     }
279 
280     // Fetch type from interface itself.
281     if (dbus_if.sensortype != 0)
282     {
283         type = dbus_if.sensortype;
284     }
285     else
286     {
287         // Non InventoryItems
288         char* p = strrchr(dbus_if.path, '/');
289         type = dbus_to_sensor_type(p + 1);
290     }
291 
292     return type;
293 }
294 
295 // Replaces find_sensor
296 uint8_t find_type_for_sensor_number(uint8_t num)
297 {
298     int r;
299     dbus_interface_t dbus_if;
300     r = find_openbmc_path(num, &dbus_if);
301     if (r < 0)
302     {
303         std::fprintf(stderr, "Could not find sensor %d\n", num);
304         return 0;
305     }
306     return get_type_from_interface(dbus_if);
307 }
308 
309 ipmi_ret_t ipmi_sen_get_sensor_type(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
310                                     ipmi_request_t request,
311                                     ipmi_response_t response,
312                                     ipmi_data_len_t data_len,
313                                     ipmi_context_t context)
314 {
315     auto reqptr = static_cast<sensor_data_t*>(request);
316     ipmi_ret_t rc = IPMI_CC_OK;
317 
318     printf("IPMI GET_SENSOR_TYPE [0x%02X]\n", reqptr->sennum);
319 
320     // TODO Not sure what the System-event-sensor is suppose to return
321     // need to ask Hostboot team
322     unsigned char buf[] = {0x00, 0x6F};
323 
324     buf[0] = find_type_for_sensor_number(reqptr->sennum);
325 
326     // HACK UNTIL Dbus gets updated or we find a better way
327     if (buf[0] == 0)
328     {
329         rc = IPMI_CC_SENSOR_INVALID;
330     }
331 
332     *data_len = sizeof(buf);
333     std::memcpy(response, &buf, *data_len);
334 
335     return rc;
336 }
337 
338 const std::set<std::string> analogSensorInterfaces = {
339     "xyz.openbmc_project.Sensor.Value",
340     "xyz.openbmc_project.Control.FanPwm",
341 };
342 
343 bool isAnalogSensor(const std::string& interface)
344 {
345     return (analogSensorInterfaces.count(interface));
346 }
347 
348 /**
349 @brief This command is used to set sensorReading.
350 
351 @param
352     -  sensorNumber
353     -  operation
354     -  reading
355     -  assertOffset0_7
356     -  assertOffset8_14
357     -  deassertOffset0_7
358     -  deassertOffset8_14
359     -  eventData1
360     -  eventData2
361     -  eventData3
362 
363 @return completion code on success.
364 **/
365 
366 ipmi::RspType<> ipmiSetSensorReading(uint8_t sensorNumber, uint8_t operation,
367                                      uint8_t reading, uint8_t assertOffset0_7,
368                                      uint8_t assertOffset8_14,
369                                      uint8_t deassertOffset0_7,
370                                      uint8_t deassertOffset8_14,
371                                      uint8_t eventData1, uint8_t eventData2,
372                                      uint8_t eventData3)
373 {
374     log<level::DEBUG>("IPMI SET_SENSOR",
375                       entry("SENSOR_NUM=0x%02x", sensorNumber));
376 
377     ipmi::sensor::SetSensorReadingReq cmdData;
378 
379     cmdData.number = sensorNumber;
380     cmdData.operation = operation;
381     cmdData.reading = reading;
382     cmdData.assertOffset0_7 = assertOffset0_7;
383     cmdData.assertOffset8_14 = assertOffset8_14;
384     cmdData.deassertOffset0_7 = deassertOffset0_7;
385     cmdData.deassertOffset8_14 = deassertOffset8_14;
386     cmdData.eventData1 = eventData1;
387     cmdData.eventData2 = eventData2;
388     cmdData.eventData3 = eventData3;
389 
390     // Check if the Sensor Number is present
391     const auto iter = ipmi::sensor::sensors.find(sensorNumber);
392     if (iter == ipmi::sensor::sensors.end())
393     {
394         updateSensorRecordFromSSRAESC(&sensorNumber);
395         return ipmi::responseSuccess();
396     }
397 
398     try
399     {
400         if (ipmi::sensor::Mutability::Write !=
401             (iter->second.mutability & ipmi::sensor::Mutability::Write))
402         {
403             log<level::ERR>("Sensor Set operation is not allowed",
404                             entry("SENSOR_NUM=%d", sensorNumber));
405             return ipmi::responseIllegalCommand();
406         }
407         auto ipmiRC = iter->second.updateFunc(cmdData, iter->second);
408         return ipmi::response(ipmiRC);
409     }
410     catch (InternalFailure& e)
411     {
412         log<level::ERR>("Set sensor failed",
413                         entry("SENSOR_NUM=%d", sensorNumber));
414         commit<InternalFailure>();
415         return ipmi::responseUnspecifiedError();
416     }
417     catch (const std::runtime_error& e)
418     {
419         log<level::ERR>(e.what());
420         return ipmi::responseUnspecifiedError();
421     }
422 }
423 
424 ipmi_ret_t ipmi_sen_get_sensor_reading(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
425                                        ipmi_request_t request,
426                                        ipmi_response_t response,
427                                        ipmi_data_len_t data_len,
428                                        ipmi_context_t context)
429 {
430     auto reqptr = static_cast<sensor_data_t*>(request);
431     auto resp = static_cast<sensorreadingresp_t*>(response);
432     ipmi::sensor::GetSensorResponse getResponse{};
433     static constexpr auto scanningEnabledBit = 6;
434 
435     const auto iter = ipmi::sensor::sensors.find(reqptr->sennum);
436     if (iter == ipmi::sensor::sensors.end())
437     {
438         return IPMI_CC_SENSOR_INVALID;
439     }
440     if (ipmi::sensor::Mutability::Read !=
441         (iter->second.mutability & ipmi::sensor::Mutability::Read))
442     {
443         return IPMI_CC_ILLEGAL_COMMAND;
444     }
445 
446     try
447     {
448         getResponse = iter->second.getFunc(iter->second);
449         *data_len = getResponse.size();
450         std::memcpy(resp, getResponse.data(), *data_len);
451         resp->operation = 1 << scanningEnabledBit;
452         return IPMI_CC_OK;
453     }
454 #ifdef UPDATE_FUNCTIONAL_ON_FAIL
455     catch (const SensorFunctionalError& e)
456     {
457         return IPMI_CC_RESPONSE_ERROR;
458     }
459 #endif
460     catch (const std::exception& e)
461     {
462         *data_len = getResponse.size();
463         std::memcpy(resp, getResponse.data(), *data_len);
464         return IPMI_CC_OK;
465     }
466 }
467 
468 void getSensorThresholds(uint8_t sensorNum,
469                          get_sdr::GetSensorThresholdsResponse* response)
470 {
471     constexpr auto warningThreshIntf =
472         "xyz.openbmc_project.Sensor.Threshold.Warning";
473     constexpr auto criticalThreshIntf =
474         "xyz.openbmc_project.Sensor.Threshold.Critical";
475 
476     sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()};
477 
478     const auto iter = ipmi::sensor::sensors.find(sensorNum);
479     const auto info = iter->second;
480 
481     auto service = ipmi::getService(bus, info.sensorInterface, info.sensorPath);
482 
483     auto warnThresholds = ipmi::getAllDbusProperties(
484         bus, service, info.sensorPath, warningThreshIntf);
485 
486     double warnLow = std::visit(ipmi::VariantToDoubleVisitor(),
487                                 warnThresholds["WarningLow"]);
488     double warnHigh = std::visit(ipmi::VariantToDoubleVisitor(),
489                                  warnThresholds["WarningHigh"]);
490 
491     if (warnLow != 0)
492     {
493         warnLow *= std::pow(10, info.scale - info.exponentR);
494         response->lowerNonCritical = static_cast<uint8_t>(
495             (warnLow - info.scaledOffset) / info.coefficientM);
496         response->validMask |= static_cast<uint8_t>(
497             ipmi::sensor::ThresholdMask::NON_CRITICAL_LOW_MASK);
498     }
499 
500     if (warnHigh != 0)
501     {
502         warnHigh *= std::pow(10, info.scale - info.exponentR);
503         response->upperNonCritical = static_cast<uint8_t>(
504             (warnHigh - info.scaledOffset) / info.coefficientM);
505         response->validMask |= static_cast<uint8_t>(
506             ipmi::sensor::ThresholdMask::NON_CRITICAL_HIGH_MASK);
507     }
508 
509     auto critThresholds = ipmi::getAllDbusProperties(
510         bus, service, info.sensorPath, criticalThreshIntf);
511     double critLow = std::visit(ipmi::VariantToDoubleVisitor(),
512                                 critThresholds["CriticalLow"]);
513     double critHigh = std::visit(ipmi::VariantToDoubleVisitor(),
514                                  critThresholds["CriticalHigh"]);
515 
516     if (critLow != 0)
517     {
518         critLow *= std::pow(10, info.scale - info.exponentR);
519         response->lowerCritical = static_cast<uint8_t>(
520             (critLow - info.scaledOffset) / info.coefficientM);
521         response->validMask |= static_cast<uint8_t>(
522             ipmi::sensor::ThresholdMask::CRITICAL_LOW_MASK);
523     }
524 
525     if (critHigh != 0)
526     {
527         critHigh *= std::pow(10, info.scale - info.exponentR);
528         response->upperCritical = static_cast<uint8_t>(
529             (critHigh - info.scaledOffset) / info.coefficientM);
530         response->validMask |= static_cast<uint8_t>(
531             ipmi::sensor::ThresholdMask::CRITICAL_HIGH_MASK);
532     }
533 }
534 
535 ipmi_ret_t ipmi_sen_get_sensor_thresholds(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
536                                           ipmi_request_t request,
537                                           ipmi_response_t response,
538                                           ipmi_data_len_t data_len,
539                                           ipmi_context_t context)
540 {
541     constexpr auto valueInterface = "xyz.openbmc_project.Sensor.Value";
542 
543     if (*data_len != sizeof(uint8_t))
544     {
545         *data_len = 0;
546         return IPMI_CC_REQ_DATA_LEN_INVALID;
547     }
548 
549     auto sensorNum = *(reinterpret_cast<const uint8_t*>(request));
550     *data_len = 0;
551 
552     const auto iter = ipmi::sensor::sensors.find(sensorNum);
553     if (iter == ipmi::sensor::sensors.end())
554     {
555         return IPMI_CC_SENSOR_INVALID;
556     }
557 
558     const auto info = iter->second;
559 
560     // Proceed only if the sensor value interface is implemented.
561     if (info.propertyInterfaces.find(valueInterface) ==
562         info.propertyInterfaces.end())
563     {
564         // return with valid mask as 0
565         return IPMI_CC_OK;
566     }
567 
568     auto responseData =
569         reinterpret_cast<get_sdr::GetSensorThresholdsResponse*>(response);
570 
571     try
572     {
573         getSensorThresholds(sensorNum, responseData);
574     }
575     catch (std::exception& e)
576     {
577         // Mask if the property is not present
578         responseData->validMask = 0;
579     }
580 
581     *data_len = sizeof(get_sdr::GetSensorThresholdsResponse);
582     return IPMI_CC_OK;
583 }
584 
585 ipmi_ret_t ipmi_sen_wildcard(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
586                              ipmi_request_t request, ipmi_response_t response,
587                              ipmi_data_len_t data_len, ipmi_context_t context)
588 {
589     ipmi_ret_t rc = IPMI_CC_INVALID;
590 
591     printf("IPMI S/E Wildcard Netfn:[0x%X], Cmd:[0x%X]\n", netfn, cmd);
592     *data_len = 0;
593 
594     return rc;
595 }
596 
597 /** @brief implements the get SDR Info command
598  *  @param count - Operation
599  *
600  *  @returns IPMI completion code plus response data
601  *   - sdrCount - sensor/SDR count
602  *   - lunsAndDynamicPopulation - static/Dynamic sensor population flag
603  */
604 ipmi::RspType<uint8_t, // respcount
605               uint8_t  // dynamic population flags
606               >
607     ipmiSensorGetDeviceSdrInfo(std::optional<uint8_t> count)
608 {
609     uint8_t sdrCount;
610     // multiple LUNs not supported.
611     constexpr uint8_t lunsAndDynamicPopulation = 1;
612     constexpr uint8_t getSdrCount = 0x01;
613     constexpr uint8_t getSensorCount = 0x00;
614 
615     if (count.value_or(0) == getSdrCount)
616     {
617         // Get SDR count. This returns the total number of SDRs in the device.
618         const auto& entityRecords = ipmi::sensor::getIpmiEntityRecords();
619         sdrCount =
620             ipmi::sensor::sensors.size() + frus.size() + entityRecords.size();
621     }
622     else if (count.value_or(0) == getSensorCount)
623     {
624         // Get Sensor count. This returns the number of sensors
625         sdrCount = ipmi::sensor::sensors.size();
626     }
627     else
628     {
629         return ipmi::responseInvalidCommandOnLun();
630     }
631 
632     return ipmi::responseSuccess(sdrCount, lunsAndDynamicPopulation);
633 }
634 
635 /** @brief implements the reserve SDR command
636  *  @returns IPMI completion code plus response data
637  *   - reservationID - reservation ID
638  */
639 ipmi::RspType<uint16_t> ipmiSensorReserveSdr()
640 {
641     // A constant reservation ID is okay until we implement add/remove SDR.
642     constexpr uint16_t reservationID = 1;
643 
644     return ipmi::responseSuccess(reservationID);
645 }
646 
647 void setUnitFieldsForObject(const ipmi::sensor::Info* info,
648                             get_sdr::SensorDataFullRecordBody* body)
649 {
650     namespace server = sdbusplus::xyz::openbmc_project::Sensor::server;
651     try
652     {
653         auto unit = server::Value::convertUnitFromString(info->unit);
654         // Unit strings defined in
655         // phosphor-dbus-interfaces/xyz/openbmc_project/Sensor/Value.interface.yaml
656         switch (unit)
657         {
658             case server::Value::Unit::DegreesC:
659                 body->sensor_units_2_base = get_sdr::SENSOR_UNIT_DEGREES_C;
660                 break;
661             case server::Value::Unit::RPMS:
662                 body->sensor_units_2_base = get_sdr::SENSOR_UNIT_RPM;
663                 break;
664             case server::Value::Unit::Volts:
665                 body->sensor_units_2_base = get_sdr::SENSOR_UNIT_VOLTS;
666                 break;
667             case server::Value::Unit::Meters:
668                 body->sensor_units_2_base = get_sdr::SENSOR_UNIT_METERS;
669                 break;
670             case server::Value::Unit::Amperes:
671                 body->sensor_units_2_base = get_sdr::SENSOR_UNIT_AMPERES;
672                 break;
673             case server::Value::Unit::Joules:
674                 body->sensor_units_2_base = get_sdr::SENSOR_UNIT_JOULES;
675                 break;
676             case server::Value::Unit::Watts:
677                 body->sensor_units_2_base = get_sdr::SENSOR_UNIT_WATTS;
678                 break;
679             default:
680                 // Cannot be hit.
681                 std::fprintf(stderr, "Unknown value unit type: = %s\n",
682                              info->unit.c_str());
683         }
684     }
685     catch (const sdbusplus::exception::InvalidEnumString& e)
686     {
687         log<level::WARNING>("Warning: no unit provided for sensor!");
688     }
689 }
690 
691 ipmi_ret_t populate_record_from_dbus(get_sdr::SensorDataFullRecordBody* body,
692                                      const ipmi::sensor::Info* info,
693                                      ipmi_data_len_t data_len)
694 {
695     /* Functional sensor case */
696     if (isAnalogSensor(info->propertyInterfaces.begin()->first))
697     {
698 
699         body->sensor_units_1 = 0; // unsigned, no rate, no modifier, not a %
700 
701         /* Unit info */
702         setUnitFieldsForObject(info, body);
703 
704         get_sdr::body::set_b(info->coefficientB, body);
705         get_sdr::body::set_m(info->coefficientM, body);
706         get_sdr::body::set_b_exp(info->exponentB, body);
707         get_sdr::body::set_r_exp(info->exponentR, body);
708 
709         get_sdr::body::set_id_type(0b00, body); // 00 = unicode
710     }
711 
712     /* ID string */
713     auto id_string = info->sensorNameFunc(*info);
714 
715     if (id_string.length() > FULL_RECORD_ID_STR_MAX_LENGTH)
716     {
717         get_sdr::body::set_id_strlen(FULL_RECORD_ID_STR_MAX_LENGTH, body);
718     }
719     else
720     {
721         get_sdr::body::set_id_strlen(id_string.length(), body);
722     }
723     strncpy(body->id_string, id_string.c_str(),
724             get_sdr::body::get_id_strlen(body));
725 
726     return IPMI_CC_OK;
727 };
728 
729 ipmi_ret_t ipmi_fru_get_sdr(ipmi_request_t request, ipmi_response_t response,
730                             ipmi_data_len_t data_len)
731 {
732     auto req = reinterpret_cast<get_sdr::GetSdrReq*>(request);
733     auto resp = reinterpret_cast<get_sdr::GetSdrResp*>(response);
734     get_sdr::SensorDataFruRecord record{};
735     auto dataLength = 0;
736 
737     auto fru = frus.begin();
738     uint8_t fruID{};
739     auto recordID = get_sdr::request::get_record_id(req);
740 
741     fruID = recordID - FRU_RECORD_ID_START;
742     fru = frus.find(fruID);
743     if (fru == frus.end())
744     {
745         return IPMI_CC_SENSOR_INVALID;
746     }
747 
748     /* Header */
749     get_sdr::header::set_record_id(recordID, &(record.header));
750     record.header.sdr_version = SDR_VERSION; // Based on IPMI Spec v2.0 rev 1.1
751     record.header.record_type = get_sdr::SENSOR_DATA_FRU_RECORD;
752     record.header.record_length = sizeof(record.key) + sizeof(record.body);
753 
754     /* Key */
755     record.key.fruID = fruID;
756     record.key.accessLun |= IPMI_LOGICAL_FRU;
757     record.key.deviceAddress = BMCSlaveAddress;
758 
759     /* Body */
760     record.body.entityID = fru->second[0].entityID;
761     record.body.entityInstance = fru->second[0].entityInstance;
762     record.body.deviceType = fruInventoryDevice;
763     record.body.deviceTypeModifier = IPMIFruInventory;
764 
765     /* Device ID string */
766     auto deviceID =
767         fru->second[0].path.substr(fru->second[0].path.find_last_of('/') + 1,
768                                    fru->second[0].path.length());
769 
770     if (deviceID.length() > get_sdr::FRU_RECORD_DEVICE_ID_MAX_LENGTH)
771     {
772         get_sdr::body::set_device_id_strlen(
773             get_sdr::FRU_RECORD_DEVICE_ID_MAX_LENGTH, &(record.body));
774     }
775     else
776     {
777         get_sdr::body::set_device_id_strlen(deviceID.length(), &(record.body));
778     }
779 
780     strncpy(record.body.deviceID, deviceID.c_str(),
781             get_sdr::body::get_device_id_strlen(&(record.body)));
782 
783     if (++fru == frus.end())
784     {
785         // we have reached till end of fru, so assign the next record id to
786         // 512(Max fru ID = 511) + Entity Record ID(may start with 0).
787         const auto& entityRecords = ipmi::sensor::getIpmiEntityRecords();
788         auto next_record_id =
789             (entityRecords.size())
790                 ? entityRecords.begin()->first + ENTITY_RECORD_ID_START
791                 : END_OF_RECORD;
792         get_sdr::response::set_next_record_id(next_record_id, resp);
793     }
794     else
795     {
796         get_sdr::response::set_next_record_id(
797             (FRU_RECORD_ID_START + fru->first), resp);
798     }
799 
800     // Check for invalid offset size
801     if (req->offset > sizeof(record))
802     {
803         return IPMI_CC_PARM_OUT_OF_RANGE;
804     }
805 
806     dataLength = std::min(static_cast<size_t>(req->bytes_to_read),
807                           sizeof(record) - req->offset);
808 
809     std::memcpy(resp->record_data,
810                 reinterpret_cast<uint8_t*>(&record) + req->offset, dataLength);
811 
812     *data_len = dataLength;
813     *data_len += 2; // additional 2 bytes for next record ID
814 
815     return IPMI_CC_OK;
816 }
817 
818 ipmi_ret_t ipmi_entity_get_sdr(ipmi_request_t request, ipmi_response_t response,
819                                ipmi_data_len_t data_len)
820 {
821     auto req = reinterpret_cast<get_sdr::GetSdrReq*>(request);
822     auto resp = reinterpret_cast<get_sdr::GetSdrResp*>(response);
823     get_sdr::SensorDataEntityRecord record{};
824     auto dataLength = 0;
825 
826     const auto& entityRecords = ipmi::sensor::getIpmiEntityRecords();
827     auto entity = entityRecords.begin();
828     uint8_t entityRecordID;
829     auto recordID = get_sdr::request::get_record_id(req);
830 
831     entityRecordID = recordID - ENTITY_RECORD_ID_START;
832     entity = entityRecords.find(entityRecordID);
833     if (entity == entityRecords.end())
834     {
835         return IPMI_CC_SENSOR_INVALID;
836     }
837 
838     /* Header */
839     get_sdr::header::set_record_id(recordID, &(record.header));
840     record.header.sdr_version = SDR_VERSION; // Based on IPMI Spec v2.0 rev 1.1
841     record.header.record_type = get_sdr::SENSOR_DATA_ENTITY_RECORD;
842     record.header.record_length = sizeof(record.key) + sizeof(record.body);
843 
844     /* Key */
845     record.key.containerEntityId = entity->second.containerEntityId;
846     record.key.containerEntityInstance = entity->second.containerEntityInstance;
847     get_sdr::key::set_flags(entity->second.isList, entity->second.isLinked,
848                             &(record.key));
849     record.key.entityId1 = entity->second.containedEntities[0].first;
850     record.key.entityInstance1 = entity->second.containedEntities[0].second;
851 
852     /* Body */
853     record.body.entityId2 = entity->second.containedEntities[1].first;
854     record.body.entityInstance2 = entity->second.containedEntities[1].second;
855     record.body.entityId3 = entity->second.containedEntities[2].first;
856     record.body.entityInstance3 = entity->second.containedEntities[2].second;
857     record.body.entityId4 = entity->second.containedEntities[3].first;
858     record.body.entityInstance4 = entity->second.containedEntities[3].second;
859 
860     if (++entity == entityRecords.end())
861     {
862         get_sdr::response::set_next_record_id(END_OF_RECORD,
863                                               resp); // last record
864     }
865     else
866     {
867         get_sdr::response::set_next_record_id(
868             (ENTITY_RECORD_ID_START + entity->first), resp);
869     }
870 
871     // Check for invalid offset size
872     if (req->offset > sizeof(record))
873     {
874         return IPMI_CC_PARM_OUT_OF_RANGE;
875     }
876 
877     dataLength = std::min(static_cast<size_t>(req->bytes_to_read),
878                           sizeof(record) - req->offset);
879 
880     std::memcpy(resp->record_data,
881                 reinterpret_cast<uint8_t*>(&record) + req->offset, dataLength);
882 
883     *data_len = dataLength;
884     *data_len += 2; // additional 2 bytes for next record ID
885 
886     return IPMI_CC_OK;
887 }
888 
889 ipmi_ret_t ipmi_sen_get_sdr(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
890                             ipmi_request_t request, ipmi_response_t response,
891                             ipmi_data_len_t data_len, ipmi_context_t context)
892 {
893     ipmi_ret_t ret = IPMI_CC_OK;
894     get_sdr::GetSdrReq* req = (get_sdr::GetSdrReq*)request;
895     get_sdr::GetSdrResp* resp = (get_sdr::GetSdrResp*)response;
896     get_sdr::SensorDataFullRecord record = {0};
897 
898     // Note: we use an iterator so we can provide the next ID at the end of
899     // the call.
900     auto sensor = ipmi::sensor::sensors.begin();
901     auto recordID = get_sdr::request::get_record_id(req);
902 
903     // At the beginning of a scan, the host side will send us id=0.
904     if (recordID != 0)
905     {
906         // recordID 0 to 255 means it is a FULL record.
907         // recordID 256 to 511 means it is a FRU record.
908         // recordID greater then 511 means it is a Entity Association
909         // record. Currently we are supporting three record types: FULL
910         // record, FRU record and Enttiy Association record.
911         if (recordID >= ENTITY_RECORD_ID_START)
912         {
913             return ipmi_entity_get_sdr(request, response, data_len);
914         }
915         else if (recordID >= FRU_RECORD_ID_START &&
916                  recordID < ENTITY_RECORD_ID_START)
917         {
918             return ipmi_fru_get_sdr(request, response, data_len);
919         }
920         else
921         {
922             sensor = ipmi::sensor::sensors.find(recordID);
923             if (sensor == ipmi::sensor::sensors.end())
924             {
925                 return IPMI_CC_SENSOR_INVALID;
926             }
927         }
928     }
929 
930     uint8_t sensor_id = sensor->first;
931 
932     /* Header */
933     get_sdr::header::set_record_id(sensor_id, &(record.header));
934     record.header.sdr_version = 0x51; // Based on IPMI Spec v2.0 rev 1.1
935     record.header.record_type = get_sdr::SENSOR_DATA_FULL_RECORD;
936     record.header.record_length = sizeof(get_sdr::SensorDataFullRecord);
937 
938     /* Key */
939     get_sdr::key::set_owner_id_bmc(&(record.key));
940     record.key.sensor_number = sensor_id;
941 
942     /* Body */
943     record.body.entity_id = sensor->second.entityType;
944     record.body.sensor_type = sensor->second.sensorType;
945     record.body.event_reading_type = sensor->second.sensorReadingType;
946     record.body.entity_instance = sensor->second.instance;
947     if (ipmi::sensor::Mutability::Write ==
948         (sensor->second.mutability & ipmi::sensor::Mutability::Write))
949     {
950         get_sdr::body::init_settable_state(true, &(record.body));
951     }
952 
953     // Set the type-specific details given the DBus interface
954     ret =
955         populate_record_from_dbus(&(record.body), &(sensor->second), data_len);
956 
957     if (++sensor == ipmi::sensor::sensors.end())
958     {
959         // we have reached till end of sensor, so assign the next record id
960         // to 256(Max Sensor ID = 255) + FRU ID(may start with 0).
961         auto next_record_id = (frus.size())
962                                   ? frus.begin()->first + FRU_RECORD_ID_START
963                                   : END_OF_RECORD;
964 
965         get_sdr::response::set_next_record_id(next_record_id, resp);
966     }
967     else
968     {
969         get_sdr::response::set_next_record_id(sensor->first, resp);
970     }
971 
972     if (req->offset > sizeof(record))
973     {
974         return IPMI_CC_PARM_OUT_OF_RANGE;
975     }
976 
977     // data_len will ultimately be the size of the record, plus
978     // the size of the next record ID:
979     *data_len = std::min(static_cast<size_t>(req->bytes_to_read),
980                          sizeof(record) - req->offset);
981 
982     std::memcpy(resp->record_data,
983                 reinterpret_cast<uint8_t*>(&record) + req->offset, *data_len);
984 
985     // data_len should include the LSB and MSB:
986     *data_len +=
987         sizeof(resp->next_record_id_lsb) + sizeof(resp->next_record_id_msb);
988 
989     return ret;
990 }
991 
992 static bool isFromSystemChannel()
993 {
994     // TODO we could not figure out where the request is from based on IPMI
995     // command handler parameters. because of it, we can not differentiate
996     // request from SMS/SMM or IPMB channel
997     return true;
998 }
999 
1000 ipmi_ret_t ipmicmdPlatformEvent(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
1001                                 ipmi_request_t request,
1002                                 ipmi_response_t response,
1003                                 ipmi_data_len_t dataLen, ipmi_context_t context)
1004 {
1005     uint16_t generatorID;
1006     size_t count;
1007     bool assert = true;
1008     std::string sensorPath;
1009     size_t paraLen = *dataLen;
1010     PlatformEventRequest* req;
1011     *dataLen = 0;
1012 
1013     if ((paraLen < selSystemEventSizeWith1Bytes) ||
1014         (paraLen > selSystemEventSizeWith3Bytes))
1015     {
1016         return IPMI_CC_REQ_DATA_LEN_INVALID;
1017     }
1018 
1019     if (isFromSystemChannel())
1020     { // first byte for SYSTEM Interface is Generator ID
1021         // +1 to get common struct
1022         req = reinterpret_cast<PlatformEventRequest*>((uint8_t*)request + 1);
1023         // Capture the generator ID
1024         generatorID = *reinterpret_cast<uint8_t*>(request);
1025         // Platform Event usually comes from other firmware, like BIOS.
1026         // Unlike BMC sensor, it does not have BMC DBUS sensor path.
1027         sensorPath = "System";
1028     }
1029     else
1030     {
1031         req = reinterpret_cast<PlatformEventRequest*>(request);
1032         // TODO GenratorID for IPMB is combination of RqSA and RqLUN
1033         generatorID = 0xff;
1034         sensorPath = "IPMB";
1035     }
1036     // Content of event data field depends on sensor class.
1037     // When data0 bit[5:4] is non-zero, valid data counts is 3.
1038     // When data0 bit[7:6] is non-zero, valid data counts is 2.
1039     if (((req->data[0] & byte3EnableMask) != 0 &&
1040          paraLen < selSystemEventSizeWith3Bytes) ||
1041         ((req->data[0] & byte2EnableMask) != 0 &&
1042          paraLen < selSystemEventSizeWith2Bytes))
1043     {
1044         return IPMI_CC_REQ_DATA_LEN_INVALID;
1045     }
1046 
1047     // Count bytes of Event Data
1048     if ((req->data[0] & byte3EnableMask) != 0)
1049     {
1050         count = 3;
1051     }
1052     else if ((req->data[0] & byte2EnableMask) != 0)
1053     {
1054         count = 2;
1055     }
1056     else
1057     {
1058         count = 1;
1059     }
1060     assert = req->eventDirectionType & directionMask ? false : true;
1061     std::vector<uint8_t> eventData(req->data, req->data + count);
1062 
1063     sdbusplus::bus::bus dbus(bus);
1064     std::string service =
1065         ipmi::getService(dbus, ipmiSELAddInterface, ipmiSELPath);
1066     sdbusplus::message::message writeSEL = dbus.new_method_call(
1067         service.c_str(), ipmiSELPath, ipmiSELAddInterface, "IpmiSelAdd");
1068     writeSEL.append(ipmiSELAddMessage, sensorPath, eventData, assert,
1069                     generatorID);
1070     try
1071     {
1072         dbus.call(writeSEL);
1073     }
1074     catch (sdbusplus::exception_t& e)
1075     {
1076         phosphor::logging::log<phosphor::logging::level::ERR>(e.what());
1077         return IPMI_CC_UNSPECIFIED_ERROR;
1078     }
1079     return IPMI_CC_OK;
1080 }
1081 
1082 void register_netfn_sen_functions()
1083 {
1084     // <Wildcard Command>
1085     ipmi_register_callback(NETFUN_SENSOR, IPMI_CMD_WILDCARD, nullptr,
1086                            ipmi_sen_wildcard, PRIVILEGE_USER);
1087 
1088     // <Platform Event Message>
1089     ipmi_register_callback(NETFUN_SENSOR, IPMI_CMD_PLATFORM_EVENT, nullptr,
1090                            ipmicmdPlatformEvent, PRIVILEGE_OPERATOR);
1091     // <Get Sensor Type>
1092     ipmi_register_callback(NETFUN_SENSOR, IPMI_CMD_GET_SENSOR_TYPE, nullptr,
1093                            ipmi_sen_get_sensor_type, PRIVILEGE_USER);
1094 
1095     // <Set Sensor Reading and Event Status>
1096     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnSensor,
1097                           ipmi::sensor_event::cmdSetSensorReadingAndEvtSts,
1098                           ipmi::Privilege::Operator, ipmiSetSensorReading);
1099     // <Get Sensor Reading>
1100     ipmi_register_callback(NETFUN_SENSOR, IPMI_CMD_GET_SENSOR_READING, nullptr,
1101                            ipmi_sen_get_sensor_reading, PRIVILEGE_USER);
1102 
1103     // <Reserve Device SDR Repository>
1104     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnSensor,
1105                           ipmi::sensor_event::cmdReserveDeviceSdrRepository,
1106                           ipmi::Privilege::User, ipmiSensorReserveSdr);
1107 
1108     // <Get Device SDR Info>
1109     ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnSensor,
1110                           ipmi::sensor_event::cmdGetDeviceSdrInfo,
1111                           ipmi::Privilege::User, ipmiSensorGetDeviceSdrInfo);
1112 
1113     // <Get Device SDR>
1114     ipmi_register_callback(NETFUN_SENSOR, IPMI_CMD_GET_DEVICE_SDR, nullptr,
1115                            ipmi_sen_get_sdr, PRIVILEGE_USER);
1116 
1117     // <Get Sensor Thresholds>
1118     ipmi_register_callback(NETFUN_SENSOR, IPMI_CMD_GET_SENSOR_THRESHOLDS,
1119                            nullptr, ipmi_sen_get_sensor_thresholds,
1120                            PRIVILEGE_USER);
1121 
1122     return;
1123 }
1124