Update vpd read and write flow

The commit implement changes to log Pel and call out
FRU and record in case of any ECC failure while reading
the vpd data for the FRU and continue with the processing
of rest of the records.

In case of write, BMC reboot is blocked till the VPD is
updated. Doing this will restrict any data/Ecc corruption
due to BMC reboot while VPD data is being updated.

Tested:
Corrupted vpd for tpm_wilson then triggered collection of
vpd for the FRU.
Pel was logged calling out the FRU

'''
root@rain127bmc:~# ibm-read-vpd --file /sys/bus/i2c/drivers/at24/0-0051/eeprom
root@rain127bmc:~# peltool -a
[
{
"Private Header": {
    "Section Version":          "1",
    "Sub-section type":         "0",
    "Created by":               "0x4000",
    "Created at":               "06/10/2022 06:36:59",
    "Committed at":             "06/10/2022 06:36:59",
    "Creator Subsystem":        "BMC",
    "CSSVER":                   "",
    "Platform Log Id":          "0x50002B35",
    "Entry Id":                 "0x50002B35",
    "BMC Event Log Id":         "10"
},
"User Header": {
    "Section Version":          "1",
    "Sub-section type":         "0",
    "Log Committed by":         "0x2000",
    "Subsystem":                "CEC Hardware - VPD Interface",
    "Event Scope":              "Entire Platform",
    "Event Severity":           "Predictive Error",
    "Event Type":               "Not Applicable",
    "Action Flags": [
                                "Service Action Required",
                                "Report Externally",
                                "HMC Call Home"
    ],
    "Host Transmission":        "Not Sent",
    "HMC Transmission":         "Not Sent"
},
"Primary SRC": {
    "Section Version":          "1",
    "Sub-section type":         "1",
    "Created by":               "0x4000",
    "SRC Version":              "0x02",
    "SRC Format":               "0x55",
    "Virtual Progress SRC":     "False",
    "I5/OS Service Event Bit":  "False",
    "Hypervisor Dump Initiated":"False",
    "Backplane CCIN":           "2E43",
    "Terminate FW Error":       "False",
    "Deconfigured":             "False",
    "Guarded":                  "False",
    "Error Details": {
        "Message":              "A VPD ecc exception occurred."
    },
    "Valid Word Count":         "0x09",
    "Reference Code":           "BD554002",
    "Hex Word 2":               "00080255",
    "Hex Word 3":               "2E430010",
    "Hex Word 4":               "00000000",
    "Hex Word 5":               "00000000",
    "Hex Word 6":               "00000000",
    "Hex Word 7":               "00000000",
    "Hex Word 8":               "00000000",
    "Hex Word 9":               "00000000",
    "Callout Section": {
        "Callout Count":        "1",
        "Callouts": [{
            "FRU Type":         "Normal Hardware FRU",
            "Priority":         "Mandatory, replace all with this type as a unit",
            "Location Code":    "U78DB.ND0.WZS002U-P0-C22",
            "Part Number":      "02WF429",
            "CCIN":             "6B59",
            "Serial Number":    "Y131UF09S00H"
        }]
    }
},
"Extended User Header": {
    "Section Version":          "1",
    "Sub-section type":         "0",
    "Created by":               "0x2000",
    "Reporting Machine Type":   "9105-42A",
    "Reporting Serial Number":  "13BE990",
    "FW Released Ver":          "",
    "FW SubSys Version":        "fw1020.00-58.9",
    "Common Ref Time":          "00/00/0000 00:00:00",
    "Symptom Id Len":           "20",
    "Symptom Id":               "BD554002_2E430010"
},
"Failing MTMS": {
    "Section Version":          "1",
    "Sub-section type":         "0",
    "Created by":               "0x2000",
    "Machine Type Model":       "9105-42A",
    "Serial Number":            "13BE990"
},
"User Data 0": {
    "Section Version": "1",
    "Sub-section type": "1",
    "Created by": "0x2000",
    "BMCState": "Ready",
    "BootState": "SecondaryProcInit",
    "ChassisState": "On",
    "FW Version ID": "fw1020.00-58.9-3-gb29698f8cf",
    "HostState": "Running",
    "System IM": "50001000"
},
"User Data 1": {
    "Section Version": "1",
    "Sub-section type": "1",
    "Created by": "0x2000",
    "CALLOUT_INVENTORY_PATH": "/xyz/openbmc_project/inventory/system/chassis/motherboard/tpm_wilson",
    "DESCRIPTION": "ERROR: ECC check did not pass for the Record:VINI"
}
}
]
'''

Signed-off-by: Sunny Srivastava <sunnsr25@in.ibm.com>
Change-Id: Ie7c7fff5699d8b89d5aa0995f4074ccb3fdd6c37
diff --git a/vpd-manager/editor_impl.cpp b/vpd-manager/editor_impl.cpp
index 0f25794..27f1a80 100644
--- a/vpd-manager/editor_impl.cpp
+++ b/vpd-manager/editor_impl.cpp
@@ -8,6 +8,9 @@
 #include "parser_factory.hpp"
 #include "vpd_exceptions.hpp"
 
+#include <phosphor-logging/elog-errors.hpp>
+#include <xyz/openbmc_project/Common/error.hpp>
+
 #include "vpdecc/vpdecc.h"
 
 using namespace openpower::vpd::parser::interface;
@@ -499,88 +502,170 @@
     common::utility::callPIM(std::move(objects));
 }
 
+#ifndef ManagerTest
+static void enableRebootGuard()
+{
+    try
+    {
+        auto bus = sdbusplus::bus::new_default();
+        auto method = bus.new_method_call(
+            "org.freedesktop.systemd1", "/org/freedesktop/systemd1",
+            "org.freedesktop.systemd1.Manager", "StartUnit");
+        method.append("reboot-guard-enable.service", "replace");
+        bus.call_noreply(method);
+    }
+    catch (const sdbusplus::exception::exception& e)
+    {
+        std::string errMsg =
+            "Bus call to enable BMC reboot failed for reason: ";
+        errMsg += e.what();
+
+        throw std::runtime_error(errMsg);
+    }
+}
+
+static void disableRebootGuard()
+{
+    try
+    {
+        auto bus = sdbusplus::bus::new_default();
+        auto method = bus.new_method_call(
+            "org.freedesktop.systemd1", "/org/freedesktop/systemd1",
+            "org.freedesktop.systemd1.Manager", "StartUnit");
+        method.append("reboot-guard-disable.service", "replace");
+        bus.call_noreply(method);
+    }
+    catch (const sdbusplus::exception::exception& e)
+    {
+        using namespace phosphor::logging;
+        using InternalFailure =
+            sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure;
+
+        std::string errMsg =
+            "Bus call to disable BMC reboot failed for reason: ";
+        errMsg += e.what();
+
+        log<level::ERR>("Disable boot guard failed");
+        elog<InternalFailure>();
+
+        throw std::runtime_error(errMsg);
+    }
+}
+#endif
+
 void EditorImpl::updateKeyword(const Binary& kwdData, uint32_t offset,
                                const bool& updCache)
 {
-    startOffset = offset;
+    try
+    {
+        startOffset = offset;
 #ifndef ManagerTest
-    // TODO: Figure out a better way to get max possible VPD size.
-    Binary completeVPDFile;
-    completeVPDFile.resize(65504);
-    vpdFileStream.open(vpdFilePath,
-                       std::ios::in | std::ios::out | std::ios::binary);
+        // Restrict BMC from rebooting when VPD is being written. This will
+        // prevent any data/ECC corruption in case BMC reboots while VPD update.
+        enableRebootGuard();
 
-    vpdFileStream.seekg(startOffset, std::ios_base::cur);
-    vpdFileStream.read(reinterpret_cast<char*>(&completeVPDFile[0]), 65504);
-    completeVPDFile.resize(vpdFileStream.gcount());
-    vpdFileStream.clear(std::ios_base::eofbit);
+        // TODO: Figure out a better way to get max possible VPD size.
+        Binary completeVPDFile;
+        completeVPDFile.resize(65504);
+        vpdFileStream.open(vpdFilePath,
+                           std::ios::in | std::ios::out | std::ios::binary);
 
-    vpdFile = completeVPDFile;
+        vpdFileStream.seekg(startOffset, std::ios_base::cur);
+        vpdFileStream.read(reinterpret_cast<char*>(&completeVPDFile[0]), 65504);
+        completeVPDFile.resize(vpdFileStream.gcount());
+        vpdFileStream.clear(std::ios_base::eofbit);
+
+        vpdFile = completeVPDFile;
+
+        if (objPath.empty() &&
+            jsonFile["frus"].find(vpdFilePath) != jsonFile["frus"].end())
+        {
+            objPath = jsonFile["frus"][vpdFilePath][0]["inventoryPath"]
+                          .get_ref<const nlohmann::json::string_t&>();
+        }
 
 #else
 
-    Binary completeVPDFile = vpdFile;
+        Binary completeVPDFile = vpdFile;
 
 #endif
-    if (vpdFile.empty())
-    {
-        throw std::runtime_error("Invalid File");
-    }
-    auto iterator = vpdFile.cbegin();
-    std::advance(iterator, IPZ_DATA_START);
-
-    Byte vpdType = *iterator;
-    if (vpdType == KW_VAL_PAIR_START_TAG)
-    {
-        ParserInterface* Iparser = ParserFactory::getParser(completeVPDFile);
-        IpzVpdParser* ipzParser = dynamic_cast<IpzVpdParser*>(Iparser);
-
-        try
+        if (vpdFile.empty())
         {
-            if (ipzParser == nullptr)
-            {
-                throw std::runtime_error("Invalid cast");
-            }
-
-            ipzParser->processHeader();
-            delete ipzParser;
-            ipzParser = nullptr;
-            // ParserFactory::freeParser(Iparser);
-
-            // process VTOC for PTT rkwd
-            readVTOC();
-
-            // check record for keywrod
-            checkRecordForKwd();
-
-            // update the data to the file
-            updateData(kwdData);
-
-            // update the ECC data for the record once data has been updated
-            updateRecordECC();
-
-            if (updCache)
-            {
-#ifndef ManagerTest
-                // update the cache once data has been updated
-                updateCache();
-#endif
-            }
+            throw std::runtime_error("Invalid File");
         }
-        catch (const std::exception& e)
+        auto iterator = vpdFile.cbegin();
+        std::advance(iterator, IPZ_DATA_START);
+
+        Byte vpdType = *iterator;
+        if (vpdType == KW_VAL_PAIR_START_TAG)
         {
-            if (ipzParser != nullptr)
+            // objPath should be empty only in case of test run.
+            ParserInterface* Iparser =
+                ParserFactory::getParser(completeVPDFile, objPath);
+            IpzVpdParser* ipzParser = dynamic_cast<IpzVpdParser*>(Iparser);
+
+            try
             {
+                if (ipzParser == nullptr)
+                {
+                    throw std::runtime_error("Invalid cast");
+                }
+
+                ipzParser->processHeader();
                 delete ipzParser;
+                ipzParser = nullptr;
+                // ParserFactory::freeParser(Iparser);
+
+                // process VTOC for PTT rkwd
+                readVTOC();
+
+                // check record for keywrod
+                checkRecordForKwd();
+
+                // update the data to the file
+                updateData(kwdData);
+
+                // update the ECC data for the record once data has been updated
+                updateRecordECC();
+
+                if (updCache)
+                {
+#ifndef ManagerTest
+                    // update the cache once data has been updated
+                    updateCache();
+#endif
+                }
             }
-            throw std::runtime_error(e.what());
+            catch (const std::exception& e)
+            {
+                if (ipzParser != nullptr)
+                {
+                    delete ipzParser;
+                }
+                throw std::runtime_error(e.what());
+            }
+
+#ifndef ManagerTest
+            // Once VPD data and Ecc update is done, disable BMC boot guard.
+            disableRebootGuard();
+#endif
+
+            return;
         }
-        return;
+        else
+        {
+            throw openpower::vpd::exceptions::VpdDataException(
+                "Could not find start tag in VPD " + vpdFilePath);
+        }
     }
-    else
+    catch (const std::exception& e)
     {
-        throw openpower::vpd::exceptions::VpdDataException(
-            "Could not find start tag in VPD " + vpdFilePath);
+#ifndef ManagerTest
+        // Disable reboot guard.
+        disableRebootGuard();
+#endif
+
+        throw std::runtime_error(e.what());
     }
 }
 } // namespace editor