fix alternate boot after watchdog reset

If the watchdog resets and results in booting from the alternate flash
chip, the ubiblock uboot environment variables were not set correctly
by simply mirroring the primary flash values. Instead, we need to flip
the chip so that we correctly boot from the backup kernel.

Resolves openbmc/openbmc#2840

Change-Id: Iabf93053015704049244aea81e83a797b0b16650
Signed-off-by: Eddie James <eajames@us.ibm.com>
diff --git a/meta-phosphor/common/recipes-phosphor/flash/phosphor-software-manager/obmc-flash-bmc b/meta-phosphor/common/recipes-phosphor/flash/phosphor-software-manager/obmc-flash-bmc
index da62b10..4bb7091 100644
--- a/meta-phosphor/common/recipes-phosphor/flash/phosphor-software-manager/obmc-flash-bmc
+++ b/meta-phosphor/common/recipes-phosphor/flash/phosphor-software-manager/obmc-flash-bmc
@@ -29,6 +29,13 @@
   echo "${m}"
 }
 
+# Get the mtd device number only (return X of mtdX)
+findmtdnum() {
+  m="$(findmtd "$1")"
+  m="${m##mtd}"
+  echo "${m}"
+}
+
 # Get the ubi device number (ubiX_Y)
 findubi() {
   u="$(grep -xl "$1" /sys/class/ubi/ubi?/subsystem/ubi*/name)"
@@ -258,6 +265,41 @@
   fw_setenv -c /etc/alt_fw_env.config "${varName}" "${value}"
 }
 
+# When the alternate bmc chip boots, u-boot thinks its the primary mtdX.
+# Therefore need to swap the chip numbers when copying the ubiblock and root to
+# alternate bmc u-boot environment.
+copy_ubiblock_to_alt() {
+  value="$(fw_printenv -n ubiblock)"
+  bmcNum="$(findmtdnum "bmc")"
+  altNum="$(findmtdnum "alt-bmc")"
+  replaceAlt="${value/${altNum},/${bmcNum},}"
+
+  if [[ "${value}" == "${replaceAlt}" ]]; then
+    replaceBmc="${value/${bmcNum},/${altNum},}"
+    value=${replaceBmc}
+  else
+    value=${replaceAlt}
+  fi
+
+  fw_setenv -c /etc/alt_fw_env.config ubiblock "${value}"
+}
+
+copy_root_to_alt() {
+  value="$(fw_printenv -n root)"
+  bmcNum="$(findmtdnum "bmc")"
+  altNum="$(findmtdnum "alt-bmc")"
+  replaceAlt="${value/${altNum}_/${bmcNum}_}"
+
+  if [[ "${value}" == "${replaceAlt}" ]]; then
+    replaceBmc="${value/${bmcNum}_/${altNum}_}"
+    value=${replaceBmc}
+  else
+    value=${replaceAlt}
+  fi
+
+  fw_setenv -c /etc/alt_fw_env.config root "${value}"
+}
+
 ubi_setenv() {
     # The U-Boot environment maintains two banks of environment variables.
     # The banks need to be consistent with each other to ensure that these
@@ -283,8 +325,8 @@
 
 backup_env_vars() {
   copy_env_var_to_alt kernelname
-  copy_env_var_to_alt ubiblock
-  copy_env_var_to_alt root
+  copy_ubiblock_to_alt
+  copy_root_to_alt
 }
 
 update_env_vars() {