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