1 #include "platform.hpp"
2 
3 #include "common/types.hpp"
4 #include "common/utils.hpp"
5 #include "event_parser.hpp"
6 #include "pdr.hpp"
7 #include "pdr_numeric_effecter.hpp"
8 #include "pdr_state_effecter.hpp"
9 #include "pdr_state_sensor.hpp"
10 #include "pdr_utils.hpp"
11 #include "platform_numeric_effecter.hpp"
12 #include "platform_state_effecter.hpp"
13 #include "platform_state_sensor.hpp"
14 #include "pldmd/dbus_impl_requester.hpp"
15 #include "pldmd/handler.hpp"
16 #include "requester/handler.hpp"
17 
18 #include <libpldm/entity.h>
19 #include <libpldm/state_set.h>
20 
21 #include <phosphor-logging/lg2.hpp>
22 
23 PHOSPHOR_LOG2_USING;
24 
25 using namespace pldm::utils;
26 using namespace pldm::responder::pdr;
27 using namespace pldm::responder::pdr_utils;
28 
29 namespace pldm
30 {
31 namespace responder
32 {
33 namespace platform
34 {
35 using InternalFailure =
36     sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure;
37 
38 static const Json empty{};
39 
40 void Handler::addDbusObjMaps(
41     uint16_t id,
42     std::tuple<pdr_utils::DbusMappings, pdr_utils::DbusValMaps> dbusObj,
43     TypeId typeId)
44 {
45     if (typeId == TypeId::PLDM_SENSOR_ID)
46     {
47         sensorDbusObjMaps.emplace(id, dbusObj);
48     }
49     else
50     {
51         effecterDbusObjMaps.emplace(id, dbusObj);
52     }
53 }
54 
55 const std::tuple<pdr_utils::DbusMappings, pdr_utils::DbusValMaps>&
56     Handler::getDbusObjMaps(uint16_t id, TypeId typeId) const
57 {
58     if (typeId == TypeId::PLDM_SENSOR_ID)
59     {
60         return sensorDbusObjMaps.at(id);
61     }
62     else
63     {
64         return effecterDbusObjMaps.at(id);
65     }
66 }
67 
68 void Handler::generate(const pldm::utils::DBusHandler& dBusIntf,
69                        const std::vector<fs::path>& dir, Repo& repo)
70 {
71     for (const auto& directory : dir)
72     {
73         info("Checking if directory '{DIRECTORY}' exists", "DIRECTORY",
74              directory);
75         if (!fs::exists(directory))
76         {
77             return;
78         }
79     }
80 
81     // A map of PDR type to a lambda that handles creation of that PDR type.
82     // The lambda essentially would parse the platform specific PDR JSONs to
83     // generate the PDR structures. This function iterates through the map to
84     // invoke all lambdas, so that all PDR types can be created.
85 
86     const std::map<Type, generatePDR> generateHandlers = {
87         {PLDM_STATE_EFFECTER_PDR,
88          [this](const DBusHandler& dBusIntf, const auto& json,
89                 RepoInterface& repo) {
90              pdr_state_effecter::generateStateEffecterPDR<
91                  pldm::utils::DBusHandler, Handler>(dBusIntf, json, *this,
92                                                     repo);
93          }},
94         {PLDM_NUMERIC_EFFECTER_PDR,
95          [this](const DBusHandler& dBusIntf, const auto& json,
96                 RepoInterface& repo) {
97              pdr_numeric_effecter::generateNumericEffecterPDR<
98                  pldm::utils::DBusHandler, Handler>(dBusIntf, json, *this,
99                                                     repo);
100          }},
101         {PLDM_STATE_SENSOR_PDR, [this](const DBusHandler& dBusIntf,
102                                        const auto& json, RepoInterface& repo) {
103              pdr_state_sensor::generateStateSensorPDR<pldm::utils::DBusHandler,
104                                                       Handler>(dBusIntf, json,
105                                                                *this, repo);
106          }}};
107 
108     Type pdrType{};
109     for (const auto& directory : dir)
110     {
111         for (const auto& dirEntry : fs::directory_iterator(directory))
112         {
113             try
114             {
115                 if (fs::is_regular_file(dirEntry.path().string()))
116                 {
117                     auto json = readJson(dirEntry.path().string());
118                     if (!json.empty())
119                     {
120                         auto effecterPDRs = json.value("effecterPDRs", empty);
121                         for (const auto& effecter : effecterPDRs)
122                         {
123                             pdrType = effecter.value("pdrType", 0);
124                             generateHandlers.at(
125                                 pdrType)(dBusIntf, effecter, repo);
126                         }
127 
128                         auto sensorPDRs = json.value("sensorPDRs", empty);
129                         for (const auto& sensor : sensorPDRs)
130                         {
131                             pdrType = sensor.value("pdrType", 0);
132                             generateHandlers.at(
133                                 pdrType)(dBusIntf, sensor, repo);
134                         }
135                     }
136                 }
137             }
138             catch (const InternalFailure& e)
139             {
140                 error(
141                     "PDR config directory '{PATH}' does not exist or empty for '{TYPE}' pdr, error - {ERROR}",
142                     "PATH", dirEntry.path(), "TYPE", pdrType, "ERROR", e);
143             }
144             catch (const Json::exception& e)
145             {
146                 error(
147                     "Failed to parse PDR JSON file for '{TYPE}' pdr, error - {ERROR}",
148                     "TYPE", pdrType, "ERROR", e);
149                 pldm::utils::reportError(
150                     "xyz.openbmc_project.PLDM.Error.Generate.PDRJsonFileParseFail");
151             }
152             catch (const std::exception& e)
153             {
154                 error(
155                     "Failed to parse PDR JSON file for '{TYPE}' pdr, error - {ERROR}",
156                     "TYPE", pdrType, "ERROR", e);
157                 pldm::utils::reportError(
158                     "xyz.openbmc_project.PLDM.Error.Generate.PDRJsonFileParseFail");
159             }
160         }
161     }
162 }
163 
164 Response Handler::getPDR(const pldm_msg* request, size_t payloadLength)
165 {
166     if (oemPlatformHandler)
167     {
168         auto rc = oemPlatformHandler->checkBMCState();
169         if (rc != PLDM_SUCCESS)
170         {
171             return ccOnlyResponse(request, PLDM_ERROR_NOT_READY);
172         }
173     }
174 
175     // Build FRU table if not built, since entity association PDR's
176     // are built when the FRU table is constructed.
177     if (fruHandler)
178     {
179         fruHandler->buildFRUTable();
180     }
181 
182     if (!pdrCreated)
183     {
184         generateTerminusLocatorPDR(pdrRepo);
185         if (platformConfigHandler)
186         {
187             auto systemType = platformConfigHandler->getPlatformName();
188             if (systemType.has_value())
189             {
190                 // In case of normal poweron , the system type would have been
191                 // already filled by entity manager when ever BMC reaches Ready
192                 // state. If this is not filled by time we get a getpdr request
193                 // we can assume that the entity manager service is not present
194                 // on this system & continue to build the common PDR's.
195                 pdrJsonsDir.push_back(pdrJsonDir / systemType.value());
196             }
197         }
198 
199         if (oemPlatformHandler != nullptr)
200         {
201             oemPlatformHandler->buildOEMPDR(pdrRepo);
202         }
203         generate(*dBusIntf, pdrJsonsDir, pdrRepo);
204 
205         pdrCreated = true;
206 
207         if (dbusToPLDMEventHandler)
208         {
209             deferredGetPDREvent = std::make_unique<sdeventplus::source::Defer>(
210                 event,
211                 std::bind(std::mem_fn(&pldm::responder::platform::Handler::
212                                           _processPostGetPDRActions),
213                           this, std::placeholders::_1));
214         }
215     }
216 
217     Response response(sizeof(pldm_msg_hdr) + PLDM_GET_PDR_MIN_RESP_BYTES, 0);
218 
219     if (payloadLength != PLDM_GET_PDR_REQ_BYTES)
220     {
221         return CmdHandler::ccOnlyResponse(request, PLDM_ERROR_INVALID_LENGTH);
222     }
223 
224     uint32_t recordHandle{};
225     uint32_t dataTransferHandle{};
226     uint8_t transferOpFlag{};
227     uint16_t reqSizeBytes{};
228     uint16_t recordChangeNum{};
229 
230     auto rc = decode_get_pdr_req(request, payloadLength, &recordHandle,
231                                  &dataTransferHandle, &transferOpFlag,
232                                  &reqSizeBytes, &recordChangeNum);
233     if (rc != PLDM_SUCCESS)
234     {
235         return CmdHandler::ccOnlyResponse(request, rc);
236     }
237 
238     uint16_t respSizeBytes{};
239     uint8_t* recordData = nullptr;
240     try
241     {
242         pdr_utils::PdrEntry e;
243         auto record = pdr::getRecordByHandle(pdrRepo, recordHandle, e);
244         if (record == NULL)
245         {
246             return CmdHandler::ccOnlyResponse(
247                 request, PLDM_PLATFORM_INVALID_RECORD_HANDLE);
248         }
249 
250         if (reqSizeBytes)
251         {
252             respSizeBytes = e.size;
253             if (respSizeBytes > reqSizeBytes)
254             {
255                 respSizeBytes = reqSizeBytes;
256             }
257             recordData = e.data;
258         }
259         response.resize(sizeof(pldm_msg_hdr) + PLDM_GET_PDR_MIN_RESP_BYTES +
260                             respSizeBytes,
261                         0);
262         auto responsePtr = reinterpret_cast<pldm_msg*>(response.data());
263         rc = encode_get_pdr_resp(
264             request->hdr.instance_id, PLDM_SUCCESS, e.handle.nextRecordHandle,
265             0, PLDM_START_AND_END, respSizeBytes, recordData, 0, responsePtr);
266         if (rc != PLDM_SUCCESS)
267         {
268             return ccOnlyResponse(request, rc);
269         }
270     }
271     catch (const std::exception& e)
272     {
273         error(
274             "Failed to access PDR record handle '{RECORD_HANDLE}', error - {ERROR}",
275             "RECORD_HANDLE", recordHandle, "ERROR", e);
276         return CmdHandler::ccOnlyResponse(request, PLDM_ERROR);
277     }
278     return response;
279 }
280 
281 Response Handler::setStateEffecterStates(const pldm_msg* request,
282                                          size_t payloadLength)
283 {
284     Response response(
285         sizeof(pldm_msg_hdr) + PLDM_SET_STATE_EFFECTER_STATES_RESP_BYTES, 0);
286     auto responsePtr = reinterpret_cast<pldm_msg*>(response.data());
287     uint16_t effecterId;
288     uint8_t compEffecterCnt;
289     constexpr auto maxCompositeEffecterCnt = 8;
290     std::vector<set_effecter_state_field> stateField(maxCompositeEffecterCnt,
291                                                      {0, 0});
292 
293     if ((payloadLength > PLDM_SET_STATE_EFFECTER_STATES_REQ_BYTES) ||
294         (payloadLength < sizeof(effecterId) + sizeof(compEffecterCnt) +
295                              sizeof(set_effecter_state_field)))
296     {
297         return CmdHandler::ccOnlyResponse(request, PLDM_ERROR_INVALID_LENGTH);
298     }
299 
300     int rc = decode_set_state_effecter_states_req(
301         request, payloadLength, &effecterId, &compEffecterCnt,
302         stateField.data());
303 
304     if (rc != PLDM_SUCCESS)
305     {
306         return CmdHandler::ccOnlyResponse(request, rc);
307     }
308 
309     stateField.resize(compEffecterCnt);
310     const pldm::utils::DBusHandler dBusIntf;
311     uint16_t entityType{};
312     uint16_t entityInstance{};
313     uint16_t stateSetId{};
314 
315     if (isOemStateEffecter(*this, effecterId, compEffecterCnt, entityType,
316                            entityInstance, stateSetId) &&
317         oemPlatformHandler != nullptr &&
318         !effecterDbusObjMaps.contains(effecterId))
319     {
320         rc = oemPlatformHandler->oemSetStateEffecterStatesHandler(
321             entityType, entityInstance, stateSetId, compEffecterCnt, stateField,
322             effecterId);
323     }
324     else
325     {
326         rc = platform_state_effecter::setStateEffecterStatesHandler<
327             pldm::utils::DBusHandler, Handler>(dBusIntf, *this, effecterId,
328                                                stateField);
329     }
330     if (rc != PLDM_SUCCESS)
331     {
332         return CmdHandler::ccOnlyResponse(request, rc);
333     }
334 
335     rc = encode_set_state_effecter_states_resp(request->hdr.instance_id, rc,
336                                                responsePtr);
337     if (rc != PLDM_SUCCESS)
338     {
339         return ccOnlyResponse(request, rc);
340     }
341 
342     return response;
343 }
344 
345 Response Handler::platformEventMessage(const pldm_msg* request,
346                                        size_t payloadLength)
347 {
348     uint8_t formatVersion{};
349     uint8_t tid{};
350     uint8_t eventClass{};
351     size_t offset{};
352 
353     auto rc = decode_platform_event_message_req(
354         request, payloadLength, &formatVersion, &tid, &eventClass, &offset);
355     if (rc != PLDM_SUCCESS)
356     {
357         return CmdHandler::ccOnlyResponse(request, rc);
358     }
359 
360     if (eventClass == PLDM_HEARTBEAT_TIMER_ELAPSED_EVENT)
361     {
362         rc = PLDM_SUCCESS;
363         if (oemPlatformHandler)
364         {
365             if (oemPlatformHandler->watchDogRunning())
366             {
367                 oemPlatformHandler->resetWatchDogTimer();
368             }
369             else
370             {
371                 oemPlatformHandler->setSurvTimer(tid, true);
372             }
373         }
374     }
375     else
376     {
377         try
378         {
379             const auto& handlers = eventHandlers.at(eventClass);
380             for (const auto& handler : handlers)
381             {
382                 auto rc =
383                     handler(request, payloadLength, formatVersion, tid, offset);
384                 if (rc != PLDM_SUCCESS)
385                 {
386                     return CmdHandler::ccOnlyResponse(request, rc);
387                 }
388             }
389         }
390         catch (const std::out_of_range& e)
391         {
392             error("Failed to handle platform event msg, error - {ERROR}",
393                   "ERROR", e);
394             return CmdHandler::ccOnlyResponse(request, PLDM_ERROR_INVALID_DATA);
395         }
396     }
397     Response response(
398         sizeof(pldm_msg_hdr) + PLDM_PLATFORM_EVENT_MESSAGE_RESP_BYTES, 0);
399     auto responsePtr = reinterpret_cast<pldm_msg*>(response.data());
400 
401     rc = encode_platform_event_message_resp(request->hdr.instance_id, rc,
402                                             PLDM_EVENT_NO_LOGGING, responsePtr);
403     if (rc != PLDM_SUCCESS)
404     {
405         return ccOnlyResponse(request, rc);
406     }
407 
408     return response;
409 }
410 
411 int Handler::sensorEvent(const pldm_msg* request, size_t payloadLength,
412                          uint8_t /*formatVersion*/, uint8_t tid,
413                          size_t eventDataOffset)
414 {
415     uint16_t sensorId{};
416     uint8_t eventClass{};
417     size_t eventClassDataOffset{};
418     auto eventData =
419         reinterpret_cast<const uint8_t*>(request->payload) + eventDataOffset;
420     auto eventDataSize = payloadLength - eventDataOffset;
421 
422     auto rc = decode_sensor_event_data(eventData, eventDataSize, &sensorId,
423                                        &eventClass, &eventClassDataOffset);
424     if (rc != PLDM_SUCCESS)
425     {
426         return rc;
427     }
428 
429     auto eventClassData = reinterpret_cast<const uint8_t*>(request->payload) +
430                           eventDataOffset + eventClassDataOffset;
431     auto eventClassDataSize =
432         payloadLength - eventDataOffset - eventClassDataOffset;
433 
434     if (eventClass == PLDM_STATE_SENSOR_STATE)
435     {
436         uint8_t sensorOffset{};
437         uint8_t eventState{};
438         uint8_t previousEventState{};
439 
440         rc = decode_state_sensor_data(eventClassData, eventClassDataSize,
441                                       &sensorOffset, &eventState,
442                                       &previousEventState);
443         if (rc != PLDM_SUCCESS)
444         {
445             return PLDM_ERROR;
446         }
447 
448         // Emitting state sensor event signal
449         emitStateSensorEventSignal(tid, sensorId, sensorOffset, eventState,
450                                    previousEventState);
451 
452         // If there are no HOST PDR's, there is no further action
453         if (hostPDRHandler == NULL)
454         {
455             return PLDM_SUCCESS;
456         }
457 
458         // Handle PLDM events for which PDR is available
459         SensorEntry sensorEntry{tid, sensorId};
460 
461         pldm::pdr::EntityInfo entityInfo{};
462         pldm::pdr::CompositeSensorStates compositeSensorStates{};
463         std::vector<pldm::pdr::StateSetId> stateSetIds{};
464 
465         try
466         {
467             std::tie(entityInfo, compositeSensorStates, stateSetIds) =
468                 hostPDRHandler->lookupSensorInfo(sensorEntry);
469         }
470         catch (const std::out_of_range&)
471         {
472             // If there is no mapping for tid, sensorId combination, try
473             // PLDM_TID_RESERVED, sensorId for terminus that is yet to
474             // implement TL PDR.
475             try
476             {
477                 sensorEntry.terminusID = PLDM_TID_RESERVED;
478                 std::tie(entityInfo, compositeSensorStates, stateSetIds) =
479                     hostPDRHandler->lookupSensorInfo(sensorEntry);
480             }
481             // If there is no mapping for events return PLDM_SUCCESS
482             catch (const std::out_of_range&)
483             {
484                 return PLDM_SUCCESS;
485             }
486         }
487 
488         if (sensorOffset >= compositeSensorStates.size())
489         {
490             return PLDM_ERROR_INVALID_DATA;
491         }
492 
493         const auto& possibleStates = compositeSensorStates[sensorOffset];
494         if (!possibleStates.contains(eventState))
495         {
496             return PLDM_ERROR_INVALID_DATA;
497         }
498 
499         const auto& [containerId, entityType, entityInstance] = entityInfo;
500         events::StateSensorEntry stateSensorEntry{
501             containerId,
502             entityType,
503             entityInstance,
504             sensorOffset,
505             stateSetIds[sensorOffset],
506             false};
507         return hostPDRHandler->handleStateSensorEvent(stateSensorEntry,
508                                                       eventState);
509     }
510     else
511     {
512         return PLDM_ERROR_INVALID_DATA;
513     }
514 
515     return PLDM_SUCCESS;
516 }
517 
518 int Handler::pldmPDRRepositoryChgEvent(
519     const pldm_msg* request, size_t payloadLength, uint8_t /*formatVersion*/,
520     uint8_t tid, size_t eventDataOffset)
521 {
522     uint8_t eventDataFormat{};
523     uint8_t numberOfChangeRecords{};
524     size_t dataOffset{};
525 
526     auto eventData =
527         reinterpret_cast<const uint8_t*>(request->payload) + eventDataOffset;
528     auto eventDataSize = payloadLength - eventDataOffset;
529 
530     auto rc = decode_pldm_pdr_repository_chg_event_data(
531         eventData, eventDataSize, &eventDataFormat, &numberOfChangeRecords,
532         &dataOffset);
533     if (rc != PLDM_SUCCESS)
534     {
535         return rc;
536     }
537 
538     PDRRecordHandles pdrRecordHandles;
539 
540     if (eventDataFormat == FORMAT_IS_PDR_TYPES)
541     {
542         return PLDM_ERROR_INVALID_DATA;
543     }
544 
545     if (eventDataFormat == FORMAT_IS_PDR_HANDLES)
546     {
547         uint8_t eventDataOperation{};
548         uint8_t numberOfChangeEntries{};
549 
550         auto changeRecordData = eventData + dataOffset;
551         auto changeRecordDataSize = eventDataSize - dataOffset;
552 
553         while (changeRecordDataSize)
554         {
555             rc = decode_pldm_pdr_repository_change_record_data(
556                 changeRecordData, changeRecordDataSize, &eventDataOperation,
557                 &numberOfChangeEntries, &dataOffset);
558 
559             if (rc != PLDM_SUCCESS)
560             {
561                 return rc;
562             }
563 
564             if (eventDataOperation == PLDM_RECORDS_ADDED ||
565                 eventDataOperation == PLDM_RECORDS_MODIFIED)
566             {
567                 if (eventDataOperation == PLDM_RECORDS_MODIFIED)
568                 {
569                     hostPDRHandler->isHostPdrModified = true;
570                 }
571 
572                 rc = getPDRRecordHandles(
573                     reinterpret_cast<const ChangeEntry*>(
574                         changeRecordData + dataOffset),
575                     changeRecordDataSize - dataOffset,
576                     static_cast<size_t>(numberOfChangeEntries),
577                     pdrRecordHandles);
578 
579                 if (rc != PLDM_SUCCESS)
580                 {
581                     return rc;
582                 }
583             }
584 
585             changeRecordData +=
586                 dataOffset + (numberOfChangeEntries * sizeof(ChangeEntry));
587             changeRecordDataSize -=
588                 dataOffset + (numberOfChangeEntries * sizeof(ChangeEntry));
589         }
590     }
591     if (hostPDRHandler)
592     {
593         // if we get a Repository change event with the eventDataFormat
594         // as REFRESH_ENTIRE_REPOSITORY, then delete all the PDR's that
595         // have the matched Terminus handle
596         if (eventDataFormat == REFRESH_ENTIRE_REPOSITORY)
597         {
598             // We cannot get the Repo change event from the Terminus
599             // that is not already added to the BMC repository
600 
601             for (auto it = hostPDRHandler->tlPDRInfo.cbegin();
602                  it != hostPDRHandler->tlPDRInfo.cend();)
603             {
604                 if (std::get<0>(it->second) == tid)
605                 {
606                     pldm_pdr_remove_pdrs_by_terminus_handle(pdrRepo.getPdr(),
607                                                             it->first);
608                     hostPDRHandler->tlPDRInfo.erase(it++);
609                 }
610                 else
611                 {
612                     ++it;
613                 }
614             }
615         }
616         hostPDRHandler->fetchPDR(std::move(pdrRecordHandles));
617     }
618 
619     return PLDM_SUCCESS;
620 }
621 
622 int Handler::getPDRRecordHandles(
623     const ChangeEntry* changeEntryData, size_t changeEntryDataSize,
624     size_t numberOfChangeEntries, PDRRecordHandles& pdrRecordHandles)
625 {
626     if (numberOfChangeEntries > (changeEntryDataSize / sizeof(ChangeEntry)))
627     {
628         return PLDM_ERROR_INVALID_DATA;
629     }
630     for (size_t i = 0; i < numberOfChangeEntries; i++)
631     {
632         pdrRecordHandles.push_back(changeEntryData[i]);
633     }
634     return PLDM_SUCCESS;
635 }
636 
637 Response Handler::getNumericEffecterValue(const pldm_msg* request,
638                                           size_t payloadLength)
639 {
640     if (payloadLength != PLDM_GET_NUMERIC_EFFECTER_VALUE_REQ_BYTES)
641     {
642         return ccOnlyResponse(request, PLDM_ERROR_INVALID_LENGTH);
643     }
644 
645     uint16_t effecterId{};
646     auto rc = decode_get_numeric_effecter_value_req(request, payloadLength,
647                                                     &effecterId);
648     if (rc != PLDM_SUCCESS)
649     {
650         return ccOnlyResponse(request, rc);
651     }
652 
653     const pldm::utils::DBusHandler dBusIntf;
654     uint8_t effecterDataSize{};
655     pldm::utils::PropertyValue dbusValue;
656     std::string propertyType;
657     using effecterOperationalState = uint8_t;
658     using completionCode = uint8_t;
659 
660     rc = platform_numeric_effecter::getNumericEffecterData<
661         pldm::utils::DBusHandler, Handler>(
662         dBusIntf, *this, effecterId, effecterDataSize, propertyType, dbusValue);
663 
664     if (rc != PLDM_SUCCESS)
665     {
666         return ccOnlyResponse(request, rc);
667     }
668 
669     // Refer DSP0248_1.2.0.pdf (section 22.3, Table 48)
670     // Completion Code (uint8), Effecter Data Size(uint8), Effecter Operational
671     // State(uint8), PendingValue (uint8|sint8|uint16|sint16|uint32|sint32 )
672     // PresentValue (uint8|sint8|uint16|sint16|uint32|sint32 )
673     // Size of PendingValue and PresentValue calculated based on size is
674     // provided in effecter data size
675     size_t responsePayloadLength =
676         sizeof(completionCode) + sizeof(effecterDataSize) +
677         sizeof(effecterOperationalState) +
678         getEffecterDataSize(effecterDataSize) +
679         getEffecterDataSize(effecterDataSize);
680 
681     Response response(responsePayloadLength + sizeof(pldm_msg_hdr));
682     auto responsePtr = reinterpret_cast<pldm_msg*>(response.data());
683 
684     rc = platform_numeric_effecter::getNumericEffecterValueHandler(
685         propertyType, dbusValue, effecterDataSize, responsePtr,
686         responsePayloadLength, request->hdr.instance_id);
687 
688     if (rc != PLDM_SUCCESS)
689     {
690         error(
691             "Failed to get response of GetNumericEffecterValue for effecter ID '{EFFECTERID}', response code '{RC}'.",
692             "EFFECTERID", effecterId, "RC", rc);
693         return ccOnlyResponse(request, rc);
694     }
695     return response;
696 }
697 
698 Response Handler::setNumericEffecterValue(const pldm_msg* request,
699                                           size_t payloadLength)
700 {
701     Response response(
702         sizeof(pldm_msg_hdr) + PLDM_SET_NUMERIC_EFFECTER_VALUE_RESP_BYTES);
703     uint16_t effecterId{};
704     uint8_t effecterDataSize{};
705     uint8_t effecterValue[4] = {};
706 
707     if ((payloadLength > sizeof(effecterId) + sizeof(effecterDataSize) +
708                              sizeof(union_effecter_data_size)) ||
709         (payloadLength < sizeof(effecterId) + sizeof(effecterDataSize) + 1))
710     {
711         return ccOnlyResponse(request, PLDM_ERROR_INVALID_LENGTH);
712     }
713 
714     int rc = decode_set_numeric_effecter_value_req(
715         request, payloadLength, &effecterId, &effecterDataSize, effecterValue);
716 
717     if (rc == PLDM_SUCCESS)
718     {
719         const pldm::utils::DBusHandler dBusIntf;
720         rc = platform_numeric_effecter::setNumericEffecterValueHandler<
721             pldm::utils::DBusHandler, Handler>(
722             dBusIntf, *this, effecterId, effecterDataSize, effecterValue,
723             sizeof(effecterValue));
724     }
725 
726     return ccOnlyResponse(request, rc);
727 }
728 
729 void Handler::generateTerminusLocatorPDR(Repo& repo)
730 {
731     std::vector<uint8_t> pdrBuffer(sizeof(pldm_terminus_locator_pdr));
732 
733     auto pdr = reinterpret_cast<pldm_terminus_locator_pdr*>(pdrBuffer.data());
734 
735     pdr->hdr.record_handle = 0;
736     pdr->hdr.version = 1;
737     pdr->hdr.type = PLDM_TERMINUS_LOCATOR_PDR;
738     pdr->hdr.record_change_num = 0;
739     pdr->hdr.length = sizeof(pldm_terminus_locator_pdr) - sizeof(pldm_pdr_hdr);
740     pdr->terminus_handle = TERMINUS_HANDLE;
741     pdr->validity = PLDM_TL_PDR_VALID;
742     pdr->tid = TERMINUS_ID;
743     pdr->container_id = 0x0;
744     pdr->terminus_locator_type = PLDM_TERMINUS_LOCATOR_TYPE_MCTP_EID;
745     pdr->terminus_locator_value_size =
746         sizeof(pldm_terminus_locator_type_mctp_eid);
747     auto locatorValue = reinterpret_cast<pldm_terminus_locator_type_mctp_eid*>(
748         pdr->terminus_locator_value);
749     locatorValue->eid = pldm::BmcMctpEid;
750 
751     PdrEntry pdrEntry{};
752     pdrEntry.data = pdrBuffer.data();
753     pdrEntry.size = pdrBuffer.size();
754     repo.addRecord(pdrEntry);
755     if (hostPDRHandler)
756     {
757         hostPDRHandler->tlPDRInfo.insert_or_assign(
758             pdr->terminus_handle,
759             std::make_tuple(pdr->tid, locatorValue->eid, pdr->validity));
760     }
761 }
762 
763 Response Handler::getStateSensorReadings(const pldm_msg* request,
764                                          size_t payloadLength)
765 {
766     uint16_t sensorId{};
767     bitfield8_t sensorRearm{};
768     uint8_t reserved{};
769 
770     if (payloadLength != PLDM_GET_STATE_SENSOR_READINGS_REQ_BYTES)
771     {
772         return ccOnlyResponse(request, PLDM_ERROR_INVALID_LENGTH);
773     }
774 
775     int rc = decode_get_state_sensor_readings_req(
776         request, payloadLength, &sensorId, &sensorRearm, &reserved);
777 
778     if (rc != PLDM_SUCCESS)
779     {
780         return ccOnlyResponse(request, rc);
781     }
782 
783     // 0x01 to 0x08
784     uint8_t sensorRearmCount = std::popcount(sensorRearm.byte);
785     std::vector<get_sensor_state_field> stateField(sensorRearmCount);
786     uint8_t comSensorCnt{};
787     const pldm::utils::DBusHandler dBusIntf;
788 
789     uint16_t entityType{};
790     uint16_t entityInstance{};
791     uint16_t stateSetId{};
792 
793     if (isOemStateSensor(*this, sensorId, sensorRearmCount, comSensorCnt,
794                          entityType, entityInstance, stateSetId) &&
795         oemPlatformHandler != nullptr && !sensorDbusObjMaps.contains(sensorId))
796     {
797         rc = oemPlatformHandler->getOemStateSensorReadingsHandler(
798             entityType, entityInstance, stateSetId, comSensorCnt, stateField);
799     }
800     else
801     {
802         rc = platform_state_sensor::getStateSensorReadingsHandler<
803             pldm::utils::DBusHandler, Handler>(
804             dBusIntf, *this, sensorId, sensorRearmCount, comSensorCnt,
805             stateField, dbusToPLDMEventHandler->getSensorCache());
806     }
807 
808     if (rc != PLDM_SUCCESS)
809     {
810         return ccOnlyResponse(request, rc);
811     }
812 
813     Response response(
814         sizeof(pldm_msg_hdr) + PLDM_GET_STATE_SENSOR_READINGS_MIN_RESP_BYTES +
815         sizeof(get_sensor_state_field) * comSensorCnt);
816     auto responsePtr = reinterpret_cast<pldm_msg*>(response.data());
817     rc = encode_get_state_sensor_readings_resp(
818         request->hdr.instance_id, rc, comSensorCnt, stateField.data(),
819         responsePtr);
820     if (rc != PLDM_SUCCESS)
821     {
822         return ccOnlyResponse(request, rc);
823     }
824 
825     return response;
826 }
827 
828 void Handler::_processPostGetPDRActions(sdeventplus::source::EventBase&
829                                         /*source */)
830 {
831     deferredGetPDREvent.reset();
832     dbusToPLDMEventHandler->listenSensorEvent(pdrRepo, sensorDbusObjMaps);
833 }
834 
835 bool isOemStateSensor(Handler& handler, uint16_t sensorId,
836                       uint8_t sensorRearmCount, uint8_t& compSensorCnt,
837                       uint16_t& entityType, uint16_t& entityInstance,
838                       uint16_t& stateSetId)
839 {
840     pldm_state_sensor_pdr* pdr = nullptr;
841 
842     std::unique_ptr<pldm_pdr, decltype(&pldm_pdr_destroy)> stateSensorPdrRepo(
843         pldm_pdr_init(), pldm_pdr_destroy);
844     if (!stateSensorPdrRepo)
845     {
846         error("Failed to instantiate state sensor PDR repository");
847         return false;
848     }
849     Repo stateSensorPDRs(stateSensorPdrRepo.get());
850     getRepoByType(handler.getRepo(), stateSensorPDRs, PLDM_STATE_SENSOR_PDR);
851     if (stateSensorPDRs.empty())
852     {
853         error("Failed to get record by PDR type");
854         return false;
855     }
856 
857     PdrEntry pdrEntry{};
858     auto pdrRecord = stateSensorPDRs.getFirstRecord(pdrEntry);
859     while (pdrRecord)
860     {
861         pdr = reinterpret_cast<pldm_state_sensor_pdr*>(pdrEntry.data);
862         assert(pdr != NULL);
863         if (pdr->sensor_id != sensorId)
864         {
865             pdr = nullptr;
866             pdrRecord = stateSensorPDRs.getNextRecord(pdrRecord, pdrEntry);
867             continue;
868         }
869         auto tmpEntityType = pdr->entity_type;
870         auto tmpEntityInstance = pdr->entity_instance;
871         auto tmpCompSensorCnt = pdr->composite_sensor_count;
872         auto tmpPossibleStates =
873             reinterpret_cast<state_sensor_possible_states*>(
874                 pdr->possible_states);
875         auto tmpStateSetId = tmpPossibleStates->state_set_id;
876 
877         if (sensorRearmCount > tmpCompSensorCnt)
878         {
879             error(
880                 "The requester sent wrong sensor rearm count '{SENSOR_REARM_COUNT}' for the sensor ID '{SENSORID}'.",
881                 "SENSOR_REARM_COUNT", (uint16_t)sensorRearmCount, "SENSORID",
882                 sensorId);
883             break;
884         }
885 
886         if ((tmpEntityType >= PLDM_OEM_ENTITY_TYPE_START &&
887              tmpEntityType <= PLDM_OEM_ENTITY_TYPE_END) ||
888             (tmpStateSetId >= PLDM_OEM_STATE_SET_ID_START &&
889              tmpStateSetId < PLDM_OEM_STATE_SET_ID_END))
890         {
891             entityType = tmpEntityType;
892             entityInstance = tmpEntityInstance;
893             stateSetId = tmpStateSetId;
894             compSensorCnt = tmpCompSensorCnt;
895             return true;
896         }
897         else
898         {
899             return false;
900         }
901     }
902     return false;
903 }
904 
905 bool isOemStateEffecter(Handler& handler, uint16_t effecterId,
906                         uint8_t compEffecterCnt, uint16_t& entityType,
907                         uint16_t& entityInstance, uint16_t& stateSetId)
908 {
909     pldm_state_effecter_pdr* pdr = nullptr;
910 
911     std::unique_ptr<pldm_pdr, decltype(&pldm_pdr_destroy)> stateEffecterPdrRepo(
912         pldm_pdr_init(), pldm_pdr_destroy);
913     if (!stateEffecterPdrRepo)
914     {
915         error("Failed to instantiate state effecter PDR repository");
916         return false;
917     }
918     Repo stateEffecterPDRs(stateEffecterPdrRepo.get());
919     getRepoByType(handler.getRepo(), stateEffecterPDRs,
920                   PLDM_STATE_EFFECTER_PDR);
921     if (stateEffecterPDRs.empty())
922     {
923         error("Failed to get record by PDR type");
924         return false;
925     }
926 
927     PdrEntry pdrEntry{};
928     auto pdrRecord = stateEffecterPDRs.getFirstRecord(pdrEntry);
929     while (pdrRecord)
930     {
931         pdr = reinterpret_cast<pldm_state_effecter_pdr*>(pdrEntry.data);
932         assert(pdr != NULL);
933         if (pdr->effecter_id != effecterId)
934         {
935             pdr = nullptr;
936             pdrRecord = stateEffecterPDRs.getNextRecord(pdrRecord, pdrEntry);
937             continue;
938         }
939 
940         auto tmpEntityType = pdr->entity_type;
941         auto tmpEntityInstance = pdr->entity_instance;
942         auto tmpPossibleStates =
943             reinterpret_cast<state_effecter_possible_states*>(
944                 pdr->possible_states);
945         auto tmpStateSetId = tmpPossibleStates->state_set_id;
946 
947         if (compEffecterCnt > pdr->composite_effecter_count)
948         {
949             error(
950                 "The requester sent wrong composite effecter count '{COMPOSITE_EFFECTER_COUNT}' for the effecter ID '{EFFECTERID}'.",
951                 "COMPOSITE_EFFECTER_COUNT", compEffecterCnt, "EFFECTERID",
952                 effecterId);
953             return false;
954         }
955 
956         if ((tmpEntityType >= PLDM_OEM_ENTITY_TYPE_START &&
957              tmpEntityType <= PLDM_OEM_ENTITY_TYPE_END) ||
958             (tmpStateSetId >= PLDM_OEM_STATE_SET_ID_START &&
959              tmpStateSetId < PLDM_OEM_STATE_SET_ID_END))
960         {
961             entityType = tmpEntityType;
962             entityInstance = tmpEntityInstance;
963             stateSetId = tmpStateSetId;
964             return true;
965         }
966         else
967         {
968             return false;
969         }
970     }
971     return false;
972 }
973 
974 void Handler::setEventReceiver()
975 {
976     std::vector<uint8_t> requestMsg(
977         sizeof(pldm_msg_hdr) + PLDM_SET_EVENT_RECEIVER_REQ_BYTES);
978     auto request = reinterpret_cast<pldm_msg*>(requestMsg.data());
979     auto instanceId = instanceIdDb->next(eid);
980     uint8_t eventMessageGlobalEnable =
981         PLDM_EVENT_MESSAGE_GLOBAL_ENABLE_ASYNC_KEEP_ALIVE;
982     uint8_t transportProtocolType = PLDM_TRANSPORT_PROTOCOL_TYPE_MCTP;
983     uint8_t eventReceiverAddressInfo = pldm::BmcMctpEid;
984     uint16_t heartbeatTimer = HEARTBEAT_TIMEOUT;
985 
986     auto rc = encode_set_event_receiver_req(
987         instanceId, eventMessageGlobalEnable, transportProtocolType,
988         eventReceiverAddressInfo, heartbeatTimer, request);
989     if (rc != PLDM_SUCCESS)
990     {
991         instanceIdDb->free(eid, instanceId);
992         error(
993             "Failed to encode set event receiver request, response code '{RC}'",
994             "RC", lg2::hex, rc);
995         return;
996     }
997 
998     auto processSetEventReceiverResponse = [](mctp_eid_t /*eid*/,
999                                               const pldm_msg* response,
1000                                               size_t respMsgLen) {
1001         if (response == nullptr || !respMsgLen)
1002         {
1003             error("Failed to receive response for setEventReceiver command");
1004             return;
1005         }
1006 
1007         uint8_t completionCode{};
1008         auto rc = decode_set_event_receiver_resp(response, respMsgLen,
1009                                                  &completionCode);
1010         if (rc || completionCode)
1011         {
1012             error(
1013                 "Failed to decode setEventReceiver command, response code '{RC}' and completion code '{CC}'",
1014                 "RC", rc, "CC", completionCode);
1015             pldm::utils::reportError(
1016                 "xyz.openbmc_project.bmc.pldm.InternalFailure");
1017         }
1018     };
1019     rc = handler->registerRequest(
1020         eid, instanceId, PLDM_PLATFORM, PLDM_SET_EVENT_RECEIVER,
1021         std::move(requestMsg), std::move(processSetEventReceiverResponse));
1022 
1023     if (rc != PLDM_SUCCESS)
1024     {
1025         error("Failed to send the setEventReceiver request");
1026     }
1027 
1028     if (oemPlatformHandler)
1029     {
1030         oemPlatformHandler->countSetEventReceiver();
1031         oemPlatformHandler->checkAndDisableWatchDog();
1032     }
1033 }
1034 
1035 } // namespace platform
1036 } // namespace responder
1037 } // namespace pldm
1038