vboot2: Fix saving the slot we tried back to nv storage

Previously, we only kept that slot info in RAM.  We read it from NV
storage, but never wrote it back.

Added a test to confirm proper behavior (and made sure it failed
before patching 2misc.c with the fix).

BUG=chrome-os-partner:32583
BRANCH=none
TEST=VBOOT2=1 make runtests

Change-Id: Ie12124d9cbe417914fbde14ea5086380d637240f
Signed-off-by: Randall Spangler <rspangler@chromium.org>
Reviewed-on: https://chromium-review.googlesource.com/221214
Reviewed-by: Daisuke Nojiri <dnojiri@chromium.org>
diff --git a/firmware/2lib/2misc.c b/firmware/2lib/2misc.c
index 5d063b9..94ad0c3 100644
--- a/firmware/2lib/2misc.c
+++ b/firmware/2lib/2misc.c
@@ -344,6 +344,9 @@
 		vb2_nv_set(ctx, VB2_NV_TRY_COUNT, tries - 1);
 	}
 
+	/* Store the slot we're trying */
+	vb2_nv_set(ctx, VB2_NV_FW_TRIED, sd->fw_slot);
+
 	/* Set context flag if we're using slot B */
 	if (sd->fw_slot)
 		ctx->flags |= VB2_CONTEXT_FW_SLOT_B;
diff --git a/tests/vb2_misc_tests.c b/tests/vb2_misc_tests.c
index 74837c5..72c284c 100644
--- a/tests/vb2_misc_tests.c
+++ b/tests/vb2_misc_tests.c
@@ -414,6 +414,7 @@
 	TEST_EQ(vb2_nv_get(&cc, VB2_NV_FW_RESULT),
 		VB2_FW_RESULT_UNKNOWN, "result unknown");
 	TEST_NEQ(sd->status & VB2_SD_STATUS_CHOSE_SLOT, 0, "chose slot");
+	TEST_EQ(vb2_nv_get(&cc, VB2_NV_FW_TRIED), 0, "tried A");
 	TEST_EQ(sd->fw_slot, 0, "selected A");
 	TEST_EQ(cc.flags & VB2_CONTEXT_FW_SLOT_B, 0, "didn't choose B");
 
@@ -424,6 +425,7 @@
 	TEST_EQ(vb2_nv_get(&cc, VB2_NV_FW_RESULT),
 		VB2_FW_RESULT_UNKNOWN, "result unknown");
 	TEST_NEQ(sd->status & VB2_SD_STATUS_CHOSE_SLOT, 0, "chose slot");
+	TEST_EQ(vb2_nv_get(&cc, VB2_NV_FW_TRIED), 1, "tried B");
 	TEST_EQ(sd->fw_slot, 1, "selected B");
 	TEST_NEQ(cc.flags & VB2_CONTEXT_FW_SLOT_B, 0, "ctx says choose B");
 
@@ -433,6 +435,7 @@
 	TEST_SUCC(vb2_select_fw_slot(&cc), "select slot A out of tries");
 	TEST_EQ(vb2_nv_get(&cc, VB2_NV_TRY_NEXT), 1, "try B next");
 	TEST_NEQ(sd->status & VB2_SD_STATUS_CHOSE_SLOT, 0, "chose slot");
+	TEST_EQ(vb2_nv_get(&cc, VB2_NV_FW_TRIED), 1, "tried B");
 	TEST_EQ(sd->fw_slot, 1, "selected B");
 	TEST_NEQ(cc.flags & VB2_CONTEXT_FW_SLOT_B, 0, "ctx says choose B");
 
@@ -443,6 +446,7 @@
 	TEST_EQ(vb2_nv_get(&cc, VB2_NV_FW_RESULT),
 		VB2_FW_RESULT_TRYING, "result trying");
 	TEST_NEQ(sd->status & VB2_SD_STATUS_CHOSE_SLOT, 0, "chose slot");
+	TEST_EQ(vb2_nv_get(&cc, VB2_NV_FW_TRIED), 0, "tried A");
 	TEST_EQ(sd->fw_slot, 0, "selected A");
 	TEST_EQ(cc.flags & VB2_CONTEXT_FW_SLOT_B, 0, "didn't choose B");
 	TEST_EQ(vb2_nv_get(&cc, VB2_NV_TRY_COUNT), 2, "tries decremented");