BMC RR : Read and update the status for BMC reset

This commit reads the status of the host owned sensors by
sending a getStateSensorReading command and then
updates the D-Bus backend for BMC reset.

This commit also updates the TLPDR from the host
based on the valid bit in the TLPDR.

Earlier the PDR record handles where assigned in an incremental order
starting from 0, now the numbering has been decided
to be within the specified range as below
BMC: 0x00000001 to 0x00FFFFFF (0x00000000 is reserved per PLDM spec)
Hostboot: 0x01000000 to 0x01FFFFFF
PHYP: 0x02000000 to 0x02FFFFFF
Reserved: 0x03000000 to 0xFFFFFFFF

This commit handles the numbering of the PDR record handles.

Tested the following scenarios on a rainier system
1. restart pldmd when Host is not running
2. restart pldmd when Host is running
3. restart pldmd when Host is not running and then ipl

Using pldmtool the DBus backened is verified.

Signed-off-by: Pavithra Barithaya <pavithra.b@ibm.com>
Change-Id: Idb9eb642dbf766bb587a3a4075e4dce2c9da2de5
diff --git a/host-bmc/host_pdr_handler.cpp b/host-bmc/host_pdr_handler.cpp
index a786ed4..45b178b 100644
--- a/host-bmc/host_pdr_handler.cpp
+++ b/host-bmc/host_pdr_handler.cpp
@@ -367,6 +367,13 @@
     static PDRList stateSensorPDRs{};
     static TLPDRMap tlpdrInfo{};
     uint32_t nextRecordHandle{};
+    std::vector<TlInfo> tlInfo;
+    uint8_t tlEid = 0;
+    bool tlValid = true;
+    uint32_t rh = 0;
+    uint16_t terminusHandle = 0;
+    uint8_t tid = 0;
+
     uint8_t completionCode{};
     uint32_t nextDataTransferHandle{};
     uint8_t transferFlag{};
@@ -413,7 +420,23 @@
         }
         else
         {
+            // when nextRecordHandle is 0, we need the recordHandle of the last
+            // PDR and not 0-1.
+            if (!nextRecordHandle)
+            {
+                rh = nextRecordHandle;
+            }
+            else
+            {
+                rh = nextRecordHandle - 1;
+            }
+
             auto pdrHdr = reinterpret_cast<pldm_pdr_hdr*>(pdr.data());
+            if (!rh)
+            {
+                rh = pdrHdr->record_handle;
+            }
+
             if (pdrHdr->type == PLDM_PDR_ENTITY_ASSOCIATION)
             {
                 this->mergeEntityAssociations(pdr);
@@ -430,12 +453,41 @@
                         static_cast<pldm::pdr::TerminusHandle>(
                             tlpdr->terminus_handle),
                         static_cast<pldm::pdr::TerminusID>(tlpdr->tid));
+
+                    terminusHandle = tlpdr->terminus_handle;
+                    tid = tlpdr->tid;
+                    auto terminus_locator_type = tlpdr->terminus_locator_type;
+                    if (terminus_locator_type ==
+                        PLDM_TERMINUS_LOCATOR_TYPE_MCTP_EID)
+                    {
+                        auto locatorValue = reinterpret_cast<
+                            const pldm_terminus_locator_type_mctp_eid*>(
+                            tlpdr->terminus_locator_value);
+                        tlEid = static_cast<uint8_t>(locatorValue->eid);
+                    }
+                    if (tlpdr->validity == 0)
+                    {
+                        tlValid = false;
+                    }
+                    tlInfo.emplace_back(
+                        TlInfo{tlpdr->validity, static_cast<uint8_t>(tlEid),
+                               tlpdr->tid, tlpdr->terminus_handle});
                 }
                 else if (pdrHdr->type == PLDM_STATE_SENSOR_PDR)
                 {
                     stateSensorPDRs.emplace_back(pdr);
                 }
-                pldm_pdr_add(repo, pdr.data(), respCount, 0, true);
+
+                // if the TLPDR is invalid update the repo accordingly
+                if (!tlValid)
+                {
+                    pldm_pdr_update_TL_pdr(repo, terminusHandle, tid, tlEid,
+                                           tlValid);
+                }
+                else
+                {
+                    pldm_pdr_add(repo, pdr.data(), respCount, rh, true);
+                }
             }
         }
     }
@@ -443,6 +495,10 @@
     {
         /*received last record*/
         this->parseStateSensorPDRs(stateSensorPDRs, tlpdrInfo);
+        if (isHostUp())
+        {
+            this->setHostSensorState(stateSensorPDRs, tlInfo);
+        }
         stateSensorPDRs.clear();
         tlpdrInfo.clear();
         if (merged)
@@ -596,4 +652,166 @@
     return responseReceived;
 }
 
+void HostPDRHandler::setHostSensorState(const PDRList& stateSensorPDRs,
+                                        const std::vector<TlInfo>& tlinfo)
+{
+    for (const auto& stateSensorPDR : stateSensorPDRs)
+    {
+        auto pdr = reinterpret_cast<const pldm_state_sensor_pdr*>(
+            stateSensorPDR.data());
+
+        if (!pdr)
+        {
+            std::cerr << "Failed to get State sensor PDR" << std::endl;
+            pldm::utils::reportError(
+                "xyz.openbmc_project.bmc.pldm.InternalFailure");
+            return;
+        }
+
+        uint16_t sensorId = pdr->sensor_id;
+
+        for (auto info : tlinfo)
+        {
+            if (info.terminusHandle == pdr->terminus_handle)
+            {
+                if (info.valid == PLDM_TL_PDR_VALID)
+                {
+                    mctp_eid = info.eid;
+                }
+
+                bitfield8_t sensorRearm;
+                sensorRearm.byte = 0;
+                uint8_t tid = info.tid;
+
+                auto instanceId = requester.getInstanceId(mctp_eid);
+                std::vector<uint8_t> requestMsg(
+                    sizeof(pldm_msg_hdr) +
+                    PLDM_GET_STATE_SENSOR_READINGS_REQ_BYTES);
+                auto request = reinterpret_cast<pldm_msg*>(requestMsg.data());
+                auto rc = encode_get_state_sensor_readings_req(
+                    instanceId, sensorId, sensorRearm, 0, request);
+
+                if (rc != PLDM_SUCCESS)
+                {
+                    requester.markFree(mctp_eid, instanceId);
+                    std::cerr << "Failed to "
+                                 "encode_get_state_sensor_readings_req, rc = "
+                              << rc << std::endl;
+                    pldm::utils::reportError(
+                        "xyz.openbmc_project.bmc.pldm.InternalFailure");
+                    return;
+                }
+
+                auto getStateSensorReadingRespHandler = [=, this](
+                                                            mctp_eid_t /*eid*/,
+                                                            const pldm_msg*
+                                                                response,
+                                                            size_t respMsgLen) {
+                    if (response == nullptr || !respMsgLen)
+                    {
+                        std::cerr << "Failed to receive response for "
+                                     "getStateSensorReading command \n";
+                        return;
+                    }
+                    std::array<get_sensor_state_field, 8> stateField{};
+                    uint8_t completionCode = 0;
+                    uint8_t comp_sensor_count = 0;
+
+                    auto rc = decode_get_state_sensor_readings_resp(
+                        response, respMsgLen, &completionCode,
+                        &comp_sensor_count, stateField.data());
+
+                    if (rc != PLDM_SUCCESS || completionCode != PLDM_SUCCESS)
+                    {
+                        std::cerr
+                            << "Failed to "
+                               "decode_get_state_sensor_readings_resp, rc = "
+                            << rc
+                            << " cc=" << static_cast<unsigned>(completionCode)
+                            << std::endl;
+                        pldm::utils::reportError(
+                            "xyz.openbmc_project.bmc.pldm.InternalFailure");
+                    }
+
+                    uint8_t eventState;
+                    uint8_t previousEventState;
+                    uint8_t sensorOffset = comp_sensor_count - 1;
+
+                    for (size_t i = 0; i < comp_sensor_count; i++)
+                    {
+                        eventState = stateField[i].present_state;
+                        previousEventState = stateField[i].previous_state;
+
+                        emitStateSensorEventSignal(tid, sensorId, sensorOffset,
+                                                   eventState,
+                                                   previousEventState);
+
+                        SensorEntry sensorEntry{tid, sensorId};
+
+                        pldm::pdr::EntityInfo entityInfo{};
+                        pldm::pdr::CompositeSensorStates
+                            compositeSensorStates{};
+
+                        try
+                        {
+                            std::tie(entityInfo, compositeSensorStates) =
+                                lookupSensorInfo(sensorEntry);
+                        }
+                        catch (const std::out_of_range& e)
+                        {
+                            try
+                            {
+                                sensorEntry.terminusID = PLDM_TID_RESERVED;
+                                std::tie(entityInfo, compositeSensorStates) =
+                                    lookupSensorInfo(sensorEntry);
+                            }
+                            catch (const std::out_of_range& e)
+                            {
+                                std::cerr << "No mapping for the events"
+                                          << std::endl;
+                            }
+                        }
+
+                        if (sensorOffset > compositeSensorStates.size())
+                        {
+                            std::cerr
+                                << " Error Invalid data, Invalid sensor offset"
+                                << std::endl;
+                            return;
+                        }
+
+                        const auto& possibleStates =
+                            compositeSensorStates[sensorOffset];
+                        if (possibleStates.find(eventState) ==
+                            possibleStates.end())
+                        {
+                            std::cerr
+                                << " Error invalid_data, Invalid event state"
+                                << std::endl;
+                            return;
+                        }
+                        const auto& [containerId, entityType, entityInstance] =
+                            entityInfo;
+                        pldm::responder::events::StateSensorEntry
+                            stateSensorEntry{containerId, entityType,
+                                             entityInstance, sensorOffset};
+                        handleStateSensorEvent(stateSensorEntry, eventState);
+                    }
+                };
+
+                rc = handler->registerRequest(
+                    mctp_eid, instanceId, PLDM_PLATFORM,
+                    PLDM_GET_STATE_SENSOR_READINGS, std::move(requestMsg),
+                    std::move(getStateSensorReadingRespHandler));
+
+                if (rc != PLDM_SUCCESS)
+                {
+                    std::cerr << " Failed to send request to get State sensor "
+                                 "reading on Host "
+                              << std::endl;
+                }
+            }
+        }
+    }
+}
 } // namespace pldm