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