Use flash id to write image to flash

Update the item updater helper functions to take the flash id instead of
the version id since flash id is the name of the volumes/partitions.

The flash id was being persisted for the mmc layout with the name of
"partlabel". This is not needed anymore since the flash id is now being
passed by the service files.

The write functions/service files still use the version id to know where
the image files are located in /tmp/. They then set the value of flash
id (Path property) which is then used by the other functions such as
Delete and setting the u-boot environment variables.

Tested: Code update and Delete functions work on ubi and mmc.

Change-Id: I87c5b8ae2e24af30256dc3b436859835f14cda05
Signed-off-by: Adriana Kobylak <anoo@us.ibm.com>
diff --git a/item_updater.cpp b/item_updater.cpp
index e7de3d0..94de753 100644
--- a/item_updater.cpp
+++ b/item_updater.cpp
@@ -375,24 +375,18 @@
     {
         auto flashId = it->second->path();
 
-        // Delete ReadOnly partitions if it's not active
-        removeReadOnlyPartition(entryId);
-        removePersistDataDirectory(flashId);
+        // Delete version data if it has been installed on flash (path is not
+        // the upload directory)
+        if (flashId.find(IMG_UPLOAD_DIR) == std::string::npos)
+        {
+            removeReadOnlyPartition(entryId);
+            removePersistDataDirectory(flashId);
+            helper.clearEntry(flashId);
+        }
 
         // Removing entry in versions map
         this->versions.erase(entryId);
     }
-    else
-    {
-        // Delete ReadOnly partitions even if we can't find the version
-        removeReadOnlyPartition(entryId);
-
-        error(
-            "Failed to find version ({VERSIONID}) in item updater versions map; unable to remove.",
-            "VERSIONID", entryId);
-    }
-
-    helper.clearEntry(entryId);
 
     return;
 }
@@ -445,7 +439,7 @@
 {
     auto flashId = versions.find(versionId)->second->path();
     storePriority(flashId, value);
-    helper.setEntry(versionId, value);
+    helper.setEntry(flashId, value);
 }
 
 void ItemUpdater::freePriority(uint8_t value, const std::string& versionId)
@@ -511,7 +505,8 @@
 
 void ItemUpdater::removeReadOnlyPartition(std::string versionId)
 {
-    helper.removeVersion(versionId);
+    auto flashId = versions.find(versionId)->second->path();
+    helper.removeVersion(flashId);
 }
 
 bool ItemUpdater::fieldModeEnabled(bool value)
@@ -647,7 +642,8 @@
 
 void ItemUpdater::updateUbootEnvVars(const std::string& versionId)
 {
-    helper.updateUbootVersionId(versionId);
+    auto flashId = versions.find(versionId)->second->path();
+    helper.updateUbootVersionId(flashId);
 }
 
 void ItemUpdater::resetUbootEnvVars()
diff --git a/item_updater_helper.hpp b/item_updater_helper.hpp
index de48df4..b328285 100644
--- a/item_updater_helper.hpp
+++ b/item_updater_helper.hpp
@@ -48,17 +48,17 @@
     /** @brief Do factory reset */
     void factoryReset();
 
-    /** @brief Remove the image with the version id
+    /** @brief Remove the image with the flash id
      *
-     * @param[in] versionId - The version id of the image
+     * @param[in] flashId - The flash id of the image
      */
-    void removeVersion(const std::string& versionId);
+    void removeVersion(const std::string& flashId);
 
-    /** @brief Update version id in uboot env
+    /** @brief Update flash id in uboot env
      *
-     * @param[in] versionId - The version id of the image
+     * @param[in] flashId - The flash id of the image
      */
-    void updateUbootVersionId(const std::string& versionId);
+    void updateUbootVersionId(const std::string& flashId);
 
     /** @brief Mirror Uboot to the alt uboot partition */
     void mirrorAlt();
diff --git a/mmc/flash.cpp b/mmc/flash.cpp
index 3bd67fa..e1c5e9c 100644
--- a/mmc/flash.cpp
+++ b/mmc/flash.cpp
@@ -3,6 +3,7 @@
 #include "flash.hpp"
 
 #include "activation.hpp"
+#include "item_updater.hpp"
 
 namespace phosphor
 {
@@ -33,7 +34,8 @@
     msg.read(newStateID, newStateObjPath, newStateUnit, newStateResult);
 
     auto mmcServiceFile = "obmc-flash-mmc@" + versionId + ".service";
-    auto mmcSetPrimary = "obmc-flash-mmc-setprimary@" + versionId + ".service";
+    auto flashId = parent.versions.find(versionId)->second->path();
+    auto mmcSetPrimary = "obmc-flash-mmc-setprimary@" + flashId + ".service";
 
     if (newStateUnit == mmcServiceFile && newStateResult == "done")
     {
diff --git a/mmc/item_updater_helper.cpp b/mmc/item_updater_helper.cpp
index d3279c0..70a94bf 100644
--- a/mmc/item_updater_helper.cpp
+++ b/mmc/item_updater_helper.cpp
@@ -34,11 +34,11 @@
     utils::execute("/sbin/fw_setenv", "rwreset", "true");
 }
 
-void Helper::removeVersion(const std::string& versionId)
+void Helper::removeVersion(const std::string& flashId)
 {
     auto method = bus.new_method_call(SYSTEMD_BUSNAME, SYSTEMD_PATH,
                                       SYSTEMD_INTERFACE, "StartUnit");
-    auto serviceFile = "obmc-flash-mmc-remove@" + versionId + ".service";
+    auto serviceFile = "obmc-flash-mmc-remove@" + flashId + ".service";
     method.append(serviceFile, "replace");
     bus.call_noreply(method);
 
@@ -48,11 +48,11 @@
     std::this_thread::sleep_for(removeWait);
 }
 
-void Helper::updateUbootVersionId(const std::string& versionId)
+void Helper::updateUbootVersionId(const std::string& flashId)
 {
     auto method = bus.new_method_call(SYSTEMD_BUSNAME, SYSTEMD_PATH,
                                       SYSTEMD_INTERFACE, "StartUnit");
-    auto serviceFile = "obmc-flash-mmc-setprimary@" + versionId + ".service";
+    auto serviceFile = "obmc-flash-mmc-setprimary@" + flashId + ".service";
     method.append(serviceFile, "replace");
     bus.call_noreply(method);
 
diff --git a/mmc/obmc-flash-mmc-setprimary@.service.in b/mmc/obmc-flash-mmc-setprimary@.service.in
index 69feafb..77c724b 100644
--- a/mmc/obmc-flash-mmc-setprimary@.service.in
+++ b/mmc/obmc-flash-mmc-setprimary@.service.in
@@ -1,5 +1,5 @@
 [Unit]
-Description=Set %I as primary version
+Description=Set %I as primary partition
 
 [Service]
 Type=oneshot
diff --git a/mmc/obmc-flash-mmc@.service.in b/mmc/obmc-flash-mmc@.service.in
index f8b4262..6cdbdb1 100644
--- a/mmc/obmc-flash-mmc@.service.in
+++ b/mmc/obmc-flash-mmc@.service.in
@@ -1,6 +1,5 @@
 [Unit]
 Description=Write image %I to BMC storage
-OnFailure=obmc-flash-mmc-remove@%i.service
 
 [Service]
 Type=oneshot
diff --git a/obmc-flash-bmc b/obmc-flash-bmc
index 8cf49c1..aa9773f 100644
--- a/obmc-flash-bmc
+++ b/obmc-flash-bmc
@@ -232,8 +232,11 @@
         vols=$(ubinfo -a | grep "rofs-" | cut -c 14-)
         vols=(${vols})
     else
+        flashid=$(busctl get-property xyz.openbmc_project.Software.BMC.Updater \
+            "/xyz/openbmc_project/software/${activeVersion}" \
+            xyz.openbmc_project.Common.FilePath Path |  awk '{print $NF;}' | tr -d '"')
         vols=$(ubinfo -a | grep "rofs-" | \
-                grep -v "$activeVersion" | cut -c 14-)
+                grep -v "$flashid" | cut -c 14-) || true
         vols=(${vols})
     fi
 
@@ -370,7 +373,7 @@
 }
 
 update_env_vars() {
-  vol="$(findubi rofs-"${version}")"
+  vol="$(findubi rofs-"${flashid}")"
   if [ -z "${vol}" ]; then
     return 1
   fi
@@ -379,7 +382,7 @@
   if [ ! -e "${block}" ]; then
     return 1
   fi
-  ubi_setenv "kernelname=kernel-${version}"
+  ubi_setenv "kernelname=kernel-${flashid}"
   ubi_setenv "ubiblock=$(echo "${ubidevid}" | sed 's/_/,/')"
   ubi_setenv "root=${block}"
 }
@@ -554,31 +557,20 @@
     mount ${hostfwdir}/hostfw-${label} ${hostfwdir}/alternate -o ro
   fi
 
-  # Store the label where the other properties like purpose and priority are
-  # preserved via the storePriority() function in the serialize files, so that
-  # it can be used for the remove function.
-  label_dir="/var/lib/phosphor-bmc-code-mgmt/${version}"
-  label_file="${label_dir}/partlabel"
-  mkdir -p "${label_dir}"
-  echo "${label}" > "${label_file}"
-
   set_flashid "${label}"
 }
 
 mmc_remove() {
   # Render the filesystem unbootable by wiping out the first 1MB, this
   # invalidates the filesystem header.
-  # If the label property does not exist, assume it's the secondary
-  # (non-running) one since the running device should not be erased.
-  label=""
-  label_file="/var/lib/phosphor-bmc-code-mgmt/${version}/partlabel"
-  if [ -f "${label_file}" ]; then
-    label="$(cat "${label_file}")"
-  else
-    label="$(mmc_get_secondary_label)"
+  # Check if the requested id is the one the BMC is running from since dd
+  # can still write and corrupt the running partition.
+  primaryid="$(mmc_get_primary_label)"
+  if [[ "${flashid}" == "${primaryid}" ]]; then
+    return -1
   fi
-  dd if=/dev/zero of=/dev/disk/by-partlabel/boot-${label} count=2048
-  dd if=/dev/zero of=/dev/disk/by-partlabel/rofs-${label} count=2048
+  dd if=/dev/zero of=/dev/disk/by-partlabel/boot-${flashid} count=2048
+  dd if=/dev/zero of=/dev/disk/by-partlabel/rofs-${flashid} count=2048
 
   hostfw_alt="hostfw/alternate"
   if grep -q "${hostfw_alt}" /proc/mounts; then
@@ -588,30 +580,14 @@
   hostfw_base="hostfw "
   if grep -q "${hostfw_base}" /proc/mounts; then
     hostfw_base=$(grep "${hostfw_base}" /proc/mounts | cut -d " " -f 2)
-    rm -f ${hostfw_base}/hostfw-${label}
+    rm -f ${hostfw_base}/hostfw-${flashid}
   fi
 }
 
 # Set the requested version as primary for the BMC to boot from upon reboot.
 mmc_setprimary() {
-  # Point root to the label of the requested BMC rootfs. If the label property
-  # does not exist, determine if the requested version is functional or not.
-  label=""
-  label_file="/var/lib/phosphor-bmc-code-mgmt/${version}/partlabel"
-  if [ -f "${label_file}" ]; then
-    label="$(cat "${label_file}")"
-  else
-    functional="$(busctl call xyz.openbmc_project.ObjectMapper \
-                  /xyz/openbmc_project/software/functional \
-                  org.freedesktop.DBus.Properties Get ss \
-                  xyz.openbmc_project.Association endpoints)"
-    if [[ "${functional}" =~ "${version}" ]]; then
-      label="$(mmc_get_primary_label)"
-    else
-      label="$(mmc_get_secondary_label)"
-    fi
-  fi
-  fw_setenv bootside "${label}"
+  # Point root to the flashid of the requested BMC rootfs.
+  fw_setenv bootside "${flashid}"
 }
 
 case "$1" in
@@ -665,7 +641,7 @@
     backup_env_vars
     ;;
   updateubootvars)
-    version="$2"
+    flashid="$2"
     update_env_vars
     ;;
   rebootguardenable)
@@ -683,11 +659,11 @@
     mmc_update
     ;;
   mmc-remove)
-    version="$2"
+    flashid="$2"
     mmc_remove
     ;;
   mmc-setprimary)
-    version="$2"
+    flashid="$2"
     mmc_setprimary
     ;;
   *)
diff --git a/static/item_updater_helper.cpp b/static/item_updater_helper.cpp
index 6be36bf..38de972 100644
--- a/static/item_updater_helper.cpp
+++ b/static/item_updater_helper.cpp
@@ -31,12 +31,12 @@
     utils::execute("/sbin/fw_setenv", "openbmconce", "factory-reset");
 }
 
-void Helper::removeVersion(const std::string& /* versionId */)
+void Helper::removeVersion(const std::string& /* flashId */)
 {
     // Empty
 }
 
-void Helper::updateUbootVersionId(const std::string& /* versionId */)
+void Helper::updateUbootVersionId(const std::string& /* flashId */)
 {
     // Empty
 }
diff --git a/ubi/flash.cpp b/ubi/flash.cpp
index c58eefc..0089d01 100644
--- a/ubi/flash.cpp
+++ b/ubi/flash.cpp
@@ -1,6 +1,7 @@
 #include "config.h"
 
 #include "activation.hpp"
+#include "item_updater.hpp"
 
 namespace phosphor
 {
@@ -39,8 +40,9 @@
 
     auto rwServiceFile = "obmc-flash-bmc-ubirw.service";
     auto roServiceFile = "obmc-flash-bmc-ubiro@" + versionId + ".service";
+    auto flashId = parent.versions.find(versionId)->second->path();
     auto ubootVarsServiceFile =
-        "obmc-flash-bmc-updateubootvars@" + versionId + ".service";
+        "obmc-flash-bmc-updateubootvars@" + flashId + ".service";
 
     if (newStateUnit == rwServiceFile && newStateResult == "done")
     {
diff --git a/ubi/item_updater_helper.cpp b/ubi/item_updater_helper.cpp
index 92c8e84..acb73a0 100644
--- a/ubi/item_updater_helper.cpp
+++ b/ubi/item_updater_helper.cpp
@@ -51,9 +51,9 @@
     utils::execute("/sbin/fw_setenv", "rwreset", "true");
 }
 
-void Helper::removeVersion(const std::string& versionId)
+void Helper::removeVersion(const std::string& flashId)
 {
-    auto serviceFile = "obmc-flash-bmc-ubiro-remove@" + versionId + ".service";
+    auto serviceFile = "obmc-flash-bmc-ubiro-remove@" + flashId + ".service";
 
     // Remove the read-only partitions.
     auto method = bus.new_method_call(SYSTEMD_BUSNAME, SYSTEMD_PATH,
@@ -62,12 +62,12 @@
     bus.call_noreply(method);
 }
 
-void Helper::updateUbootVersionId(const std::string& versionId)
+void Helper::updateUbootVersionId(const std::string& flashId)
 {
     auto method = bus.new_method_call(SYSTEMD_BUSNAME, SYSTEMD_PATH,
                                       SYSTEMD_INTERFACE, "StartUnit");
     auto updateEnvVarsFile =
-        "obmc-flash-bmc-updateubootvars@" + versionId + ".service";
+        "obmc-flash-bmc-updateubootvars@" + flashId + ".service";
     method.append(updateEnvVarsFile, "replace");
 
     try
@@ -76,7 +76,8 @@
     }
     catch (const sdbusplus::exception::exception& e)
     {
-        error("Failed to update u-boot env variables", "VERSIONID", versionId);
+        error("Failed to update u-boot env variables: {FLASHID}", "FLASHID",
+              flashId);
     }
 }
 
diff --git a/ubi/obmc-flash-bmc-updateubootvars@.service.in b/ubi/obmc-flash-bmc-updateubootvars@.service.in
index a041bfe..a0bf07c 100644
--- a/ubi/obmc-flash-bmc-updateubootvars@.service.in
+++ b/ubi/obmc-flash-bmc-updateubootvars@.service.in
@@ -1,5 +1,5 @@
 [Unit]
-Description= Updates the u-boot variable to point BMC version to %I
+Description=Updates the u-boot variable to point BMC to %I
 
 [Service]
 Type=oneshot