openpower: mmc: physical reset triggers bios reset

The service openpower-bios-factory-reset runs during startup and
calls bios_reset_check. This method determines whether the
factory-reset-toggle gpio has changed since the last reboot and
triggers a bios reset if it has. This decouples the code to check
for bios resets from the code in item_updater_mmc::reset and from
the BMC factory reset code.

Tested: Verified that the reset-gpio-val file was created to store
the previous value of the environment variable rwreset. Added files
to /media/hostfw and verified that they were removed upon reboot
when the value in reset-gpio-val differed from rwreset.

Signed-off-by: Isaac Kurth <isaac.kurth@ibm.com>
Change-Id: I9942c1826f800a2ce9aef4b9456b3f4acc4b94fe
diff --git a/meson.build b/meson.build
index 33869a9..2c0d3c4 100644
--- a/meson.build
+++ b/meson.build
@@ -126,6 +126,7 @@
     extra_unit_files += [
         'mmc/obmc-flash-bios-init.service',
         'mmc/obmc-flash-bios-patch.service',
+        'mmc/openpower-bios-factory-reset.service',
     ]
 endif
 
diff --git a/mmc/obmc-flash-bios b/mmc/obmc-flash-bios
index 478e63f..7d2a1a9 100644
--- a/mmc/obmc-flash-bios
+++ b/mmc/obmc-flash-bios
@@ -1,5 +1,21 @@
 #!/bin/sh
 
+bios_reset_if_needed() {
+  resetval=$(fw_printenv -n rwreset 2>/dev/nell)
+  if [ "$resetval" = "0" ] || [ "$resetval" = "1" ]; then
+    varstore="/media/hostfw/reset-gpio-val"
+    if [ -f "$varstore" ]; then
+      if [ "$resetval" != "$(cat $varstore)" ]; then
+        if busctl call org.open_power.Software.Host.Updater /xyz/openbmc_project/software xyz.openbmc_project.Common.FactoryReset Reset; then
+          echo "$resetval" > "$varstore"
+        fi
+      fi
+    else
+      echo "$resetval" > "$varstore"
+    fi
+  fi
+}
+
 mmc_init() {
   base_dir="/media/hostfw"
   ro_dir="${base_dir}/running-ro"
@@ -128,6 +144,9 @@
 }
 
 case "$1" in
+  bios-reset-if-needed)
+    bios_reset_if_needed
+    ;;
   mmc-init)
     mmc_init
     ;;
@@ -135,7 +154,7 @@
     mmc_patch
     ;;
   *)
-    echo "Invalid argument"
+    echo "Invalid argument: $1" >&2
     exit 1
     ;;
 esac
diff --git a/mmc/openpower-bios-factory-reset.service b/mmc/openpower-bios-factory-reset.service
new file mode 100644
index 0000000..5acabb7
--- /dev/null
+++ b/mmc/openpower-bios-factory-reset.service
@@ -0,0 +1,12 @@
+[Unit]
+Description=Perform a bios reset if the GPIO changed
+Before=pldmd.service
+After=org.open_power.Software.Host.Updater.service
+
+[Service]
+Type=oneshot
+RemainAfterExit=yes
+ExecStart=/usr/bin/obmc-flash-bios bios-reset-if-needed
+
+[Install]
+WantedBy=multi-user.target