1 #include "sensorhandler.hpp"
2 
3 #include "fruread.hpp"
4 #include "ipmid.hpp"
5 #include "types.hpp"
6 #include "utils.hpp"
7 
8 #include <host-ipmid/ipmid-api.h>
9 #include <mapper.h>
10 #include <math.h>
11 #include <stdio.h>
12 #include <string.h>
13 #include <systemd/sd-bus.h>
14 
15 #include <bitset>
16 #include <phosphor-logging/elog-errors.hpp>
17 #include <phosphor-logging/log.hpp>
18 #include <set>
19 #include <xyz/openbmc_project/Common/error.hpp>
20 #include <xyz/openbmc_project/Sensor/Value/server.hpp>
21 
22 static constexpr uint8_t fruInventoryDevice = 0x10;
23 static constexpr uint8_t IPMIFruInventory = 0x02;
24 static constexpr uint8_t BMCSlaveAddress = 0x20;
25 
26 extern int updateSensorRecordFromSSRAESC(const void*);
27 extern sd_bus* bus;
28 extern const ipmi::sensor::IdInfoMap sensors;
29 extern const FruMap frus;
30 
31 using namespace phosphor::logging;
32 using InternalFailure =
33     sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure;
34 
35 void register_netfn_sen_functions() __attribute__((constructor));
36 
37 struct sensorTypemap_t
38 {
39     uint8_t number;
40     uint8_t typecode;
41     char dbusname[32];
42 };
43 
44 sensorTypemap_t g_SensorTypeMap[] = {
45 
46     {0x01, 0x6F, "Temp"},
47     {0x0C, 0x6F, "DIMM"},
48     {0x0C, 0x6F, "MEMORY_BUFFER"},
49     {0x07, 0x6F, "PROC"},
50     {0x07, 0x6F, "CORE"},
51     {0x07, 0x6F, "CPU"},
52     {0x0F, 0x6F, "BootProgress"},
53     {0xe9, 0x09, "OccStatus"}, // E9 is an internal mapping to handle sensor
54                                // type code os 0x09
55     {0xC3, 0x6F, "BootCount"},
56     {0x1F, 0x6F, "OperatingSystemStatus"},
57     {0x12, 0x6F, "SYSTEM_EVENT"},
58     {0xC7, 0x03, "SYSTEM"},
59     {0xC7, 0x03, "MAIN_PLANAR"},
60     {0xC2, 0x6F, "PowerCap"},
61     {0x0b, 0xCA, "PowerSupplyRedundancy"},
62     {0xDA, 0x03, "TurboAllowed"},
63     {0xD8, 0xC8, "PowerSupplyDerating"},
64     {0xFF, 0x00, ""},
65 };
66 
67 struct sensor_data_t
68 {
69     uint8_t sennum;
70 } __attribute__((packed));
71 
72 struct sensorreadingresp_t
73 {
74     uint8_t value;
75     uint8_t operation;
76     uint8_t indication[2];
77 } __attribute__((packed));
78 
79 int get_bus_for_path(const char* path, char** busname)
80 {
81     return mapper_get_service(bus, path, busname);
82 }
83 
84 // Use a lookup table to find the interface name of a specific sensor
85 // This will be used until an alternative is found.  this is the first
86 // step for mapping IPMI
87 int find_openbmc_path(uint8_t num, dbus_interface_t* interface)
88 {
89     int rc;
90 
91     const auto& sensor_it = sensors.find(num);
92     if (sensor_it == sensors.end())
93     {
94         // The sensor map does not contain the sensor requested
95         return -EINVAL;
96     }
97 
98     const auto& info = sensor_it->second;
99 
100     char* busname = nullptr;
101     rc = get_bus_for_path(info.sensorPath.c_str(), &busname);
102     if (rc < 0)
103     {
104         fprintf(stderr, "Failed to get %s busname: %s\n",
105                 info.sensorPath.c_str(), busname);
106         goto final;
107     }
108 
109     interface->sensortype = info.sensorType;
110     strcpy(interface->bus, busname);
111     strcpy(interface->path, info.sensorPath.c_str());
112     // Take the interface name from the beginning of the DbusInterfaceMap. This
113     // works for the Value interface but may not suffice for more complex
114     // sensors.
115     // tracked https://github.com/openbmc/phosphor-host-ipmid/issues/103
116     strcpy(interface->interface,
117            info.propertyInterfaces.begin()->first.c_str());
118     interface->sensornumber = num;
119 
120 final:
121     free(busname);
122     return rc;
123 }
124 
125 /////////////////////////////////////////////////////////////////////
126 //
127 // Routines used by ipmi commands wanting to interact on the dbus
128 //
129 /////////////////////////////////////////////////////////////////////
130 int set_sensor_dbus_state_s(uint8_t number, const char* method,
131                             const char* value)
132 {
133 
134     dbus_interface_t a;
135     int r;
136     sd_bus_error error = SD_BUS_ERROR_NULL;
137     sd_bus_message* m = NULL;
138 
139     fprintf(ipmidbus,
140             "Attempting to set a dbus Variant Sensor 0x%02x via %s with a "
141             "value of %s\n",
142             number, method, value);
143 
144     r = find_openbmc_path(number, &a);
145 
146     if (r < 0)
147     {
148         fprintf(stderr, "Failed to find Sensor 0x%02x\n", number);
149         return 0;
150     }
151 
152     r = sd_bus_message_new_method_call(bus, &m, a.bus, a.path, a.interface,
153                                        method);
154     if (r < 0)
155     {
156         fprintf(stderr, "Failed to create a method call: %s", strerror(-r));
157         goto final;
158     }
159 
160     r = sd_bus_message_append(m, "v", "s", value);
161     if (r < 0)
162     {
163         fprintf(stderr, "Failed to create a input parameter: %s", strerror(-r));
164         goto final;
165     }
166 
167     r = sd_bus_call(bus, m, 0, &error, NULL);
168     if (r < 0)
169     {
170         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     fprintf(ipmidbus,
189             "Attempting to set a dbus Variant Sensor 0x%02x via %s with a "
190             "value of 0x%02x\n",
191             number, method, value);
192 
193     r = find_openbmc_path(number, &a);
194 
195     if (r < 0)
196     {
197         fprintf(stderr, "Failed to find Sensor 0x%02x\n", number);
198         return 0;
199     }
200 
201     r = sd_bus_message_new_method_call(bus, &m, a.bus, a.path, a.interface,
202                                        method);
203     if (r < 0)
204     {
205         fprintf(stderr, "Failed to create a method call: %s", strerror(-r));
206         goto final;
207     }
208 
209     r = sd_bus_message_append(m, "v", "i", value);
210     if (r < 0)
211     {
212         fprintf(stderr, "Failed to create a input parameter: %s", strerror(-r));
213         goto final;
214     }
215 
216     r = sd_bus_call(bus, m, 0, &error, NULL);
217     if (r < 0)
218     {
219         fprintf(stderr, "12 Failed to call the method: %s", strerror(-r));
220     }
221 
222 final:
223     sd_bus_error_free(&error);
224     m = sd_bus_message_unref(m);
225 
226     return 0;
227 }
228 
229 uint8_t dbus_to_sensor_type(char* p)
230 {
231 
232     sensorTypemap_t* s = g_SensorTypeMap;
233     char r = 0;
234     while (s->number != 0xFF)
235     {
236         if (!strcmp(s->dbusname, p))
237         {
238             r = s->typecode;
239             break;
240         }
241         s++;
242     }
243 
244     if (s->number == 0xFF)
245         printf("Failed to find Sensor Type %s\n", p);
246 
247     return r;
248 }
249 
250 uint8_t get_type_from_interface(dbus_interface_t dbus_if)
251 {
252 
253     char* p;
254     uint8_t type;
255 
256     // This is where sensors that do not exist in dbus but do
257     // exist in the host code stop.  This should indicate it
258     // is not a supported sensor
259     if (dbus_if.interface[0] == 0)
260     {
261         return 0;
262     }
263 
264     // Fetch type from interface itself.
265     if (dbus_if.sensortype != 0)
266     {
267         type = dbus_if.sensortype;
268     }
269     else
270     {
271         // Non InventoryItems
272         p = strrchr(dbus_if.path, '/');
273         type = dbus_to_sensor_type(p + 1);
274     }
275 
276     return type;
277 }
278 
279 // Replaces find_sensor
280 uint8_t find_type_for_sensor_number(uint8_t num)
281 {
282     int r;
283     dbus_interface_t dbus_if;
284     r = find_openbmc_path(num, &dbus_if);
285     if (r < 0)
286     {
287         fprintf(stderr, "Could not find sensor %d\n", num);
288         return 0;
289     }
290     return get_type_from_interface(dbus_if);
291 }
292 
293 ipmi_ret_t ipmi_sen_get_sensor_type(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
294                                     ipmi_request_t request,
295                                     ipmi_response_t response,
296                                     ipmi_data_len_t data_len,
297                                     ipmi_context_t context)
298 {
299     sensor_data_t* reqptr = (sensor_data_t*)request;
300     ipmi_ret_t rc = IPMI_CC_OK;
301 
302     printf("IPMI GET_SENSOR_TYPE [0x%02X]\n", reqptr->sennum);
303 
304     // TODO Not sure what the System-event-sensor is suppose to return
305     // need to ask Hostboot team
306     unsigned char buf[] = {0x00, 0x6F};
307 
308     buf[0] = find_type_for_sensor_number(reqptr->sennum);
309 
310     // HACK UNTIL Dbus gets updated or we find a better way
311     if (buf[0] == 0)
312     {
313         rc = IPMI_CC_SENSOR_INVALID;
314     }
315 
316     *data_len = sizeof(buf);
317     memcpy(response, &buf, *data_len);
318 
319     return rc;
320 }
321 
322 const std::set<std::string> analogSensorInterfaces = {
323     "xyz.openbmc_project.Sensor.Value",
324     "xyz.openbmc_project.Control.FanPwm",
325 };
326 
327 bool isAnalogSensor(const std::string& interface)
328 {
329     return (analogSensorInterfaces.count(interface));
330 }
331 
332 ipmi_ret_t setSensorReading(void* request)
333 {
334     ipmi::sensor::SetSensorReadingReq cmdData =
335         *(static_cast<ipmi::sensor::SetSensorReadingReq*>(request));
336 
337     // Check if the Sensor Number is present
338     const auto iter = sensors.find(cmdData.number);
339     if (iter == sensors.end())
340     {
341         return IPMI_CC_SENSOR_INVALID;
342     }
343 
344     try
345     {
346         if (ipmi::sensor::Mutability::Write !=
347             (iter->second.mutability & ipmi::sensor::Mutability::Write))
348         {
349             log<level::ERR>("Sensor Set operation is not allowed",
350                             entry("SENSOR_NUM=%d", cmdData.number));
351             return IPMI_CC_ILLEGAL_COMMAND;
352         }
353         return iter->second.updateFunc(cmdData, iter->second);
354     }
355     catch (InternalFailure& e)
356     {
357         log<level::ERR>("Set sensor failed",
358                         entry("SENSOR_NUM=%d", cmdData.number));
359         commit<InternalFailure>();
360     }
361     catch (const std::runtime_error& e)
362     {
363         log<level::ERR>(e.what());
364     }
365 
366     return IPMI_CC_UNSPECIFIED_ERROR;
367 }
368 
369 ipmi_ret_t ipmi_sen_set_sensor(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
370                                ipmi_request_t request, ipmi_response_t response,
371                                ipmi_data_len_t data_len, ipmi_context_t context)
372 {
373     sensor_data_t* reqptr = (sensor_data_t*)request;
374 
375     log<level::DEBUG>("IPMI SET_SENSOR",
376                       entry("SENSOR_NUM=0x%02x", reqptr->sennum));
377 
378     /*
379      * This would support the Set Sensor Reading command for the presence
380      * and functional state of Processor, Core & DIMM. For the remaining
381      * sensors the existing support is invoked.
382      */
383     auto ipmiRC = setSensorReading(request);
384 
385     if (ipmiRC == IPMI_CC_SENSOR_INVALID)
386     {
387         updateSensorRecordFromSSRAESC(reqptr);
388         ipmiRC = IPMI_CC_OK;
389     }
390 
391     *data_len = 0;
392     return ipmiRC;
393 }
394 
395 ipmi_ret_t ipmi_sen_get_sensor_reading(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
396                                        ipmi_request_t request,
397                                        ipmi_response_t response,
398                                        ipmi_data_len_t data_len,
399                                        ipmi_context_t context)
400 {
401     sensor_data_t* reqptr = (sensor_data_t*)request;
402     sensorreadingresp_t* resp = (sensorreadingresp_t*)response;
403     ipmi::sensor::GetSensorResponse getResponse{};
404     static constexpr auto scanningEnabledBit = 6;
405 
406     const auto iter = sensors.find(reqptr->sennum);
407     if (iter == sensors.end())
408     {
409         return IPMI_CC_SENSOR_INVALID;
410     }
411     if (ipmi::sensor::Mutability::Read !=
412         (iter->second.mutability & ipmi::sensor::Mutability::Read))
413     {
414         return IPMI_CC_ILLEGAL_COMMAND;
415     }
416 
417     try
418     {
419         getResponse = iter->second.getFunc(iter->second);
420         *data_len = getResponse.size();
421         memcpy(resp, getResponse.data(), *data_len);
422         resp->operation = 1 << scanningEnabledBit;
423         return IPMI_CC_OK;
424     }
425     catch (const std::exception& e)
426     {
427         *data_len = getResponse.size();
428         memcpy(resp, getResponse.data(), *data_len);
429         return IPMI_CC_OK;
430     }
431 }
432 
433 void getSensorThresholds(uint8_t sensorNum,
434                          get_sdr::GetSensorThresholdsResponse* response)
435 {
436     constexpr auto warningThreshIntf =
437         "xyz.openbmc_project.Sensor.Threshold.Warning";
438     constexpr auto criticalThreshIntf =
439         "xyz.openbmc_project.Sensor.Threshold.Critical";
440 
441     sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()};
442 
443     const auto iter = sensors.find(sensorNum);
444     const auto info = iter->second;
445 
446     auto service = ipmi::getService(bus, info.sensorInterface, info.sensorPath);
447 
448     auto warnThresholds = ipmi::getAllDbusProperties(
449         bus, service, info.sensorPath, warningThreshIntf);
450 
451     double warnLow = mapbox::util::apply_visitor(ipmi::VariantToDoubleVisitor(),
452                                                  warnThresholds["WarningLow"]);
453     double warnHigh = mapbox::util::apply_visitor(
454         ipmi::VariantToDoubleVisitor(), warnThresholds["WarningHigh"]);
455 
456     if (warnLow != 0)
457     {
458         warnLow *= pow(10, info.scale - info.exponentR);
459         response->lowerNonCritical = static_cast<uint8_t>(
460             (warnLow - info.scaledOffset) / info.coefficientM);
461         response->validMask |= static_cast<uint8_t>(
462             ipmi::sensor::ThresholdMask::NON_CRITICAL_LOW_MASK);
463     }
464 
465     if (warnHigh != 0)
466     {
467         warnHigh *= pow(10, info.scale - info.exponentR);
468         response->upperNonCritical = static_cast<uint8_t>(
469             (warnHigh - info.scaledOffset) / info.coefficientM);
470         response->validMask |= static_cast<uint8_t>(
471             ipmi::sensor::ThresholdMask::NON_CRITICAL_HIGH_MASK);
472     }
473 
474     auto critThresholds = ipmi::getAllDbusProperties(
475         bus, service, info.sensorPath, criticalThreshIntf);
476     double critLow = mapbox::util::apply_visitor(ipmi::VariantToDoubleVisitor(),
477                                                  critThresholds["CriticalLow"]);
478     double critHigh = mapbox::util::apply_visitor(
479         ipmi::VariantToDoubleVisitor(), critThresholds["CriticalHigh"]);
480 
481     if (critLow != 0)
482     {
483         critLow *= pow(10, info.scale - info.exponentR);
484         response->lowerCritical = static_cast<uint8_t>(
485             (critLow - info.scaledOffset) / info.coefficientM);
486         response->validMask |= static_cast<uint8_t>(
487             ipmi::sensor::ThresholdMask::CRITICAL_LOW_MASK);
488     }
489 
490     if (critHigh != 0)
491     {
492         critHigh *= pow(10, info.scale - info.exponentR);
493         response->upperCritical = static_cast<uint8_t>(
494             (critHigh - info.scaledOffset) / info.coefficientM);
495         response->validMask |= static_cast<uint8_t>(
496             ipmi::sensor::ThresholdMask::CRITICAL_HIGH_MASK);
497     }
498 }
499 
500 ipmi_ret_t ipmi_sen_get_sensor_thresholds(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
501                                           ipmi_request_t request,
502                                           ipmi_response_t response,
503                                           ipmi_data_len_t data_len,
504                                           ipmi_context_t context)
505 {
506     constexpr auto valueInterface = "xyz.openbmc_project.Sensor.Value";
507 
508     if (*data_len != sizeof(uint8_t))
509     {
510         *data_len = 0;
511         return IPMI_CC_REQ_DATA_LEN_INVALID;
512     }
513 
514     auto sensorNum = *(reinterpret_cast<const uint8_t*>(request));
515     *data_len = 0;
516 
517     const auto iter = sensors.find(sensorNum);
518     if (iter == sensors.end())
519     {
520         return IPMI_CC_SENSOR_INVALID;
521     }
522 
523     const auto info = iter->second;
524 
525     // Proceed only if the sensor value interface is implemented.
526     if (info.propertyInterfaces.find(valueInterface) ==
527         info.propertyInterfaces.end())
528     {
529         // return with valid mask as 0
530         return IPMI_CC_OK;
531     }
532 
533     auto responseData =
534         reinterpret_cast<get_sdr::GetSensorThresholdsResponse*>(response);
535 
536     try
537     {
538         getSensorThresholds(sensorNum, responseData);
539     }
540     catch (std::exception& e)
541     {
542         // Mask if the property is not present
543         responseData->validMask = 0;
544     }
545 
546     *data_len = sizeof(get_sdr::GetSensorThresholdsResponse);
547     return IPMI_CC_OK;
548 }
549 
550 ipmi_ret_t ipmi_sen_wildcard(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
551                              ipmi_request_t request, ipmi_response_t response,
552                              ipmi_data_len_t data_len, ipmi_context_t context)
553 {
554     ipmi_ret_t rc = IPMI_CC_INVALID;
555 
556     printf("IPMI S/E Wildcard Netfn:[0x%X], Cmd:[0x%X]\n", netfn, cmd);
557     *data_len = 0;
558 
559     return rc;
560 }
561 
562 ipmi_ret_t ipmi_sen_get_sdr_info(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
563                                  ipmi_request_t request,
564                                  ipmi_response_t response,
565                                  ipmi_data_len_t data_len,
566                                  ipmi_context_t context)
567 {
568     auto resp = static_cast<get_sdr_info::GetSdrInfoResp*>(response);
569     if (request == nullptr ||
570         get_sdr_info::request::get_count(request) == false)
571     {
572         // Get Sensor Count
573         resp->count = sensors.size() + frus.size();
574     }
575     else
576     {
577         resp->count = 1;
578     }
579 
580     // Multiple LUNs not supported.
581     namespace response = get_sdr_info::response;
582     response::set_lun_present(0, &(resp->luns_and_dynamic_population));
583     response::set_lun_not_present(1, &(resp->luns_and_dynamic_population));
584     response::set_lun_not_present(2, &(resp->luns_and_dynamic_population));
585     response::set_lun_not_present(3, &(resp->luns_and_dynamic_population));
586     response::set_static_population(&(resp->luns_and_dynamic_population));
587 
588     *data_len = SDR_INFO_RESP_SIZE;
589 
590     return IPMI_CC_OK;
591 }
592 
593 ipmi_ret_t ipmi_sen_reserve_sdr(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
594                                 ipmi_request_t request,
595                                 ipmi_response_t response,
596                                 ipmi_data_len_t data_len,
597                                 ipmi_context_t context)
598 {
599     // A constant reservation ID is okay until we implement add/remove SDR.
600     const uint16_t reservation_id = 1;
601     *(uint16_t*)response = reservation_id;
602     *data_len = sizeof(uint16_t);
603 
604     printf("Created new IPMI SDR reservation ID %d\n", *(uint16_t*)response);
605     return IPMI_CC_OK;
606 }
607 
608 void setUnitFieldsForObject(const ipmi::sensor::Info* info,
609                             get_sdr::SensorDataFullRecordBody* body)
610 {
611     namespace server = sdbusplus::xyz::openbmc_project::Sensor::server;
612     try
613     {
614         auto unit = server::Value::convertUnitFromString(info->unit);
615         // Unit strings defined in
616         // phosphor-dbus-interfaces/xyz/openbmc_project/Sensor/Value.interface.yaml
617         switch (unit)
618         {
619             case server::Value::Unit::DegreesC:
620                 body->sensor_units_2_base = get_sdr::SENSOR_UNIT_DEGREES_C;
621                 break;
622             case server::Value::Unit::RPMS:
623                 body->sensor_units_2_base =
624                     get_sdr::SENSOR_UNIT_REVOLUTIONS;      // revolutions
625                 get_sdr::body::set_rate_unit(0b100, body); // per minute
626                 break;
627             case server::Value::Unit::Volts:
628                 body->sensor_units_2_base = get_sdr::SENSOR_UNIT_VOLTS;
629                 break;
630             case server::Value::Unit::Meters:
631                 body->sensor_units_2_base = get_sdr::SENSOR_UNIT_METERS;
632                 break;
633             case server::Value::Unit::Amperes:
634                 body->sensor_units_2_base = get_sdr::SENSOR_UNIT_AMPERES;
635                 break;
636             case server::Value::Unit::Joules:
637                 body->sensor_units_2_base = get_sdr::SENSOR_UNIT_JOULES;
638                 break;
639             case server::Value::Unit::Watts:
640                 body->sensor_units_2_base = get_sdr::SENSOR_UNIT_WATTS;
641                 break;
642             default:
643                 // Cannot be hit.
644                 fprintf(stderr, "Unknown value unit type: = %s\n",
645                         info->unit.c_str());
646         }
647     }
648     catch (sdbusplus::exception::InvalidEnumString e)
649     {
650         log<level::WARNING>("Warning: no unit provided for sensor!");
651     }
652 }
653 
654 ipmi_ret_t populate_record_from_dbus(get_sdr::SensorDataFullRecordBody* body,
655                                      const ipmi::sensor::Info* info,
656                                      ipmi_data_len_t data_len)
657 {
658     /* Functional sensor case */
659     if (isAnalogSensor(info->propertyInterfaces.begin()->first))
660     {
661 
662         body->sensor_units_1 = 0; // unsigned, no rate, no modifier, not a %
663 
664         /* Unit info */
665         setUnitFieldsForObject(info, body);
666 
667         get_sdr::body::set_b(info->coefficientB, body);
668         get_sdr::body::set_m(info->coefficientM, body);
669         get_sdr::body::set_b_exp(info->exponentB, body);
670         get_sdr::body::set_r_exp(info->exponentR, body);
671 
672         get_sdr::body::set_id_type(0b00, body); // 00 = unicode
673     }
674 
675     /* ID string */
676     auto id_string = info->sensorNameFunc(*info);
677 
678     if (id_string.length() > FULL_RECORD_ID_STR_MAX_LENGTH)
679     {
680         get_sdr::body::set_id_strlen(FULL_RECORD_ID_STR_MAX_LENGTH, body);
681     }
682     else
683     {
684         get_sdr::body::set_id_strlen(id_string.length(), body);
685     }
686     strncpy(body->id_string, id_string.c_str(),
687             get_sdr::body::get_id_strlen(body));
688 
689     return IPMI_CC_OK;
690 };
691 
692 ipmi_ret_t ipmi_fru_get_sdr(ipmi_request_t request, ipmi_response_t response,
693                             ipmi_data_len_t data_len)
694 {
695     auto req = reinterpret_cast<get_sdr::GetSdrReq*>(request);
696     auto resp = reinterpret_cast<get_sdr::GetSdrResp*>(response);
697     get_sdr::SensorDataFruRecord record{};
698     auto dataLength = 0;
699 
700     auto fru = frus.begin();
701     uint8_t fruID{};
702     auto recordID = get_sdr::request::get_record_id(req);
703 
704     fruID = recordID - FRU_RECORD_ID_START;
705     fru = frus.find(fruID);
706     if (fru == frus.end())
707     {
708         return IPMI_CC_SENSOR_INVALID;
709     }
710 
711     /* Header */
712     get_sdr::header::set_record_id(recordID, &(record.header));
713     record.header.sdr_version = SDR_VERSION; // Based on IPMI Spec v2.0 rev 1.1
714     record.header.record_type = get_sdr::SENSOR_DATA_FRU_RECORD;
715     record.header.record_length = sizeof(record.key) + sizeof(record.body);
716 
717     /* Key */
718     record.key.fruID = fruID;
719     record.key.accessLun |= IPMI_LOGICAL_FRU;
720     record.key.deviceAddress = BMCSlaveAddress;
721 
722     /* Body */
723     record.body.entityID = fru->second[0].entityID;
724     record.body.entityInstance = fru->second[0].entityInstance;
725     record.body.deviceType = fruInventoryDevice;
726     record.body.deviceTypeModifier = IPMIFruInventory;
727 
728     /* Device ID string */
729     auto deviceID =
730         fru->second[0].path.substr(fru->second[0].path.find_last_of('/') + 1,
731                                    fru->second[0].path.length());
732 
733     if (deviceID.length() > get_sdr::FRU_RECORD_DEVICE_ID_MAX_LENGTH)
734     {
735         get_sdr::body::set_device_id_strlen(
736             get_sdr::FRU_RECORD_DEVICE_ID_MAX_LENGTH, &(record.body));
737     }
738     else
739     {
740         get_sdr::body::set_device_id_strlen(deviceID.length(), &(record.body));
741     }
742 
743     strncpy(record.body.deviceID, deviceID.c_str(),
744             get_sdr::body::get_device_id_strlen(&(record.body)));
745 
746     if (++fru == frus.end())
747     {
748         get_sdr::response::set_next_record_id(END_OF_RECORD,
749                                               resp); // last record
750     }
751     else
752     {
753         get_sdr::response::set_next_record_id(
754             (FRU_RECORD_ID_START + fru->first), resp);
755     }
756 
757     if (req->bytes_to_read > (sizeof(*resp) - req->offset))
758     {
759         dataLength = (sizeof(*resp) - req->offset);
760     }
761     else
762     {
763         dataLength = req->bytes_to_read;
764     }
765 
766     if (dataLength <= 0)
767     {
768         return IPMI_CC_REQ_DATA_LEN_INVALID;
769     }
770 
771     memcpy(resp->record_data, reinterpret_cast<uint8_t*>(&record) + req->offset,
772            (dataLength));
773 
774     *data_len = dataLength;
775     *data_len += 2; // additional 2 bytes for next record ID
776 
777     return IPMI_CC_OK;
778 }
779 
780 ipmi_ret_t ipmi_sen_get_sdr(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
781                             ipmi_request_t request, ipmi_response_t response,
782                             ipmi_data_len_t data_len, ipmi_context_t context)
783 {
784     ipmi_ret_t ret = IPMI_CC_OK;
785     get_sdr::GetSdrReq* req = (get_sdr::GetSdrReq*)request;
786     get_sdr::GetSdrResp* resp = (get_sdr::GetSdrResp*)response;
787     get_sdr::SensorDataFullRecord record = {0};
788     if (req != NULL)
789     {
790         // Note: we use an iterator so we can provide the next ID at the end of
791         // the call.
792         auto sensor = sensors.begin();
793         auto recordID = get_sdr::request::get_record_id(req);
794 
795         // At the beginning of a scan, the host side will send us id=0.
796         if (recordID != 0)
797         {
798             // recordID greater then 255,it means it is a FRU record.
799             // Currently we are supporting two record types either FULL record
800             // or FRU record.
801             if (recordID >= FRU_RECORD_ID_START)
802             {
803                 return ipmi_fru_get_sdr(request, response, data_len);
804             }
805             else
806             {
807                 sensor = sensors.find(recordID);
808                 if (sensor == sensors.end())
809                 {
810                     return IPMI_CC_SENSOR_INVALID;
811                 }
812             }
813         }
814 
815         uint8_t sensor_id = sensor->first;
816 
817         /* Header */
818         get_sdr::header::set_record_id(sensor_id, &(record.header));
819         record.header.sdr_version = 0x51; // Based on IPMI Spec v2.0 rev 1.1
820         record.header.record_type = get_sdr::SENSOR_DATA_FULL_RECORD;
821         record.header.record_length = sizeof(get_sdr::SensorDataFullRecord);
822 
823         /* Key */
824         get_sdr::key::set_owner_id_bmc(&(record.key));
825         record.key.sensor_number = sensor_id;
826 
827         /* Body */
828         record.body.entity_id = sensor->second.entityType;
829         record.body.sensor_type = sensor->second.sensorType;
830         record.body.event_reading_type = sensor->second.sensorReadingType;
831         record.body.entity_instance = sensor->second.instance;
832 
833         // Set the type-specific details given the DBus interface
834         ret = populate_record_from_dbus(&(record.body), &(sensor->second),
835                                         data_len);
836 
837         if (++sensor == sensors.end())
838         {
839             // we have reached till end of sensor, so assign the next record id
840             // to 256(Max Sensor ID = 255) + FRU ID(may start with 0).
841             auto next_record_id =
842                 (frus.size()) ? frus.begin()->first + FRU_RECORD_ID_START
843                               : END_OF_RECORD;
844 
845             get_sdr::response::set_next_record_id(next_record_id, resp);
846         }
847         else
848         {
849             get_sdr::response::set_next_record_id(sensor->first, resp);
850         }
851 
852         *data_len = sizeof(get_sdr::GetSdrResp) - req->offset;
853         memcpy(resp->record_data, (char*)&record + req->offset,
854                sizeof(get_sdr::SensorDataFullRecord) - req->offset);
855     }
856 
857     return ret;
858 }
859 
860 void register_netfn_sen_functions()
861 {
862     // <Wildcard Command>
863     ipmi_register_callback(NETFUN_SENSOR, IPMI_CMD_WILDCARD, nullptr,
864                            ipmi_sen_wildcard, PRIVILEGE_USER);
865 
866     // <Get Sensor Type>
867     ipmi_register_callback(NETFUN_SENSOR, IPMI_CMD_GET_SENSOR_TYPE, nullptr,
868                            ipmi_sen_get_sensor_type, PRIVILEGE_USER);
869 
870     // <Set Sensor Reading and Event Status>
871     ipmi_register_callback(NETFUN_SENSOR, IPMI_CMD_SET_SENSOR, nullptr,
872                            ipmi_sen_set_sensor, PRIVILEGE_OPERATOR);
873 
874     // <Get Sensor Reading>
875     ipmi_register_callback(NETFUN_SENSOR, IPMI_CMD_GET_SENSOR_READING, nullptr,
876                            ipmi_sen_get_sensor_reading, PRIVILEGE_USER);
877 
878     // <Reserve Device SDR Repository>
879     ipmi_register_callback(NETFUN_SENSOR, IPMI_CMD_RESERVE_DEVICE_SDR_REPO,
880                            nullptr, ipmi_sen_reserve_sdr, PRIVILEGE_USER);
881 
882     // <Get Device SDR Info>
883     ipmi_register_callback(NETFUN_SENSOR, IPMI_CMD_GET_DEVICE_SDR_INFO, nullptr,
884                            ipmi_sen_get_sdr_info, PRIVILEGE_USER);
885 
886     // <Get Device SDR>
887     ipmi_register_callback(NETFUN_SENSOR, IPMI_CMD_GET_DEVICE_SDR, nullptr,
888                            ipmi_sen_get_sdr, PRIVILEGE_USER);
889 
890     // <Get Sensor Thresholds>
891     ipmi_register_callback(NETFUN_SENSOR, IPMI_CMD_GET_SENSOR_THRESHOLDS,
892                            nullptr, ipmi_sen_get_sensor_thresholds,
893                            PRIVILEGE_USER);
894 
895     return;
896 }
897