Merge pull request #1082 from vchong/load_img_v2_parse_optee_header

hikey*: Add LOAD_IMAGE_V2 and OP-TEE header parsing support
diff --git a/docs/user-guide.rst b/docs/user-guide.rst
index 043af63..1181495 100644
--- a/docs/user-guide.rst
+++ b/docs/user-guide.rst
@@ -405,6 +405,13 @@
    AArch64 and facilitates the loading of ``SP_MIN`` and BL33 as AArch32 executable
    images.
 
+-  ``KEY_ALG``: This build flag enables the user to select the algorithm to be
+   used for generating the PKCS keys and subsequent signing of the certificate.
+   It accepts 3 values viz ``rsa``, ``rsa_1_5``, ``ecdsa``. The ``rsa_1_5`` is
+   the legacy PKCS#1 RSA 1.5 algorithm which is not TBBR compliant and is
+   retained only for compatibility. The default value of this flag is ``rsa``
+   which is the TBBR compliant PKCS#1 RSA 2.1 scheme.
+
 -  ``LDFLAGS``: Extra user options appended to the linkers' command line in
    addition to the one set by the build system.
 
diff --git a/drivers/auth/mbedtls/mbedtls_crypto.mk b/drivers/auth/mbedtls/mbedtls_crypto.mk
index cb81d4d..21b857b 100644
--- a/drivers/auth/mbedtls/mbedtls_crypto.mk
+++ b/drivers/auth/mbedtls/mbedtls_crypto.mk
@@ -7,9 +7,15 @@
 include drivers/auth/mbedtls/mbedtls_common.mk
 
 # The platform may define the variable 'TF_MBEDTLS_KEY_ALG' to select the key
-# algorithm to use. Default algorithm is RSA.
+# algorithm to use. If the variable is not defined, select it based on algorithm
+# used for key generation `KEY_ALG`. If `KEY_ALG` is not defined or is
+# defined to `rsa`/`rsa_1_5`, then set the variable to `rsa`.
 ifeq (${TF_MBEDTLS_KEY_ALG},)
-    TF_MBEDTLS_KEY_ALG		:=	rsa
+    ifeq (${KEY_ALG}, ecdsa)
+        TF_MBEDTLS_KEY_ALG		:=	ecdsa
+    else
+        TF_MBEDTLS_KEY_ALG		:=	rsa
+    endif
 endif
 
 # If MBEDTLS_KEY_ALG build flag is defined use it to set TF_MBEDTLS_KEY_ALG for
diff --git a/include/common/aarch32/asm_macros.S b/include/common/aarch32/asm_macros.S
index 3adcbf5..f573744 100644
--- a/include/common/aarch32/asm_macros.S
+++ b/include/common/aarch32/asm_macros.S
@@ -80,6 +80,19 @@
 	.endm
 
 	/*
+	 * Helper macro to generate the best mov/movw/movt combinations
+	 * according to the value to be moved.
+	 */
+	.macro mov_imm _reg, _val
+		.if ((\_val) & 0xffff0000) == 0
+			mov	\_reg, #(\_val)
+		.else
+			movw	\_reg, #((\_val) & 0xffff)
+			movt	\_reg, #((\_val) >> 16)
+		.endif
+	.endm
+
+	/*
 	 * Macro to mark instances where we're jumping to a function and don't
 	 * expect a return. To provide the function being jumped to with
 	 * additional information, we use 'bl' instruction to jump rather than
diff --git a/include/common/aarch64/asm_macros.S b/include/common/aarch64/asm_macros.S
index 528e29e..6d6989c 100644
--- a/include/common/aarch64/asm_macros.S
+++ b/include/common/aarch64/asm_macros.S
@@ -65,8 +65,12 @@
 	 * security, robustness and potentially facilitates debugging.
 	 */
 	.macro vector_entry  label
+	.cfi_sections .debug_frame
 	.section .vectors, "ax"
 	.align 7, 0
+	.type \label, %function
+	.func \label
+	.cfi_startproc
 	\label:
 	.endm
 
@@ -77,6 +81,8 @@
 	 * vector entry as the parameter
 	 */
 	.macro check_vector_size since
+	  .endfunc
+	  .cfi_endproc
 	  .if (. - \since) > (32 * 4)
 	    .error "Vector exceeds 32 instructions"
 	  .endif
diff --git a/include/common/asm_macros_common.S b/include/common/asm_macros_common.S
index dbc9e2d..6a02e18 100644
--- a/include/common/asm_macros_common.S
+++ b/include/common/asm_macros_common.S
@@ -12,11 +12,12 @@
 	 * to enable elimination of unused code during linking. It also adds
 	 * basic debug information to enable call stack printing most of the
 	 * time. The optional _align parameter can be used to force a
-	 * non-standard alignment (indicated in powers of 2). Do *not* try to
-	 * use a raw .align directive. Since func switches to a new section,
-	 * this would not have the desired effect.
+	 * non-standard alignment (indicated in powers of 2). The default is
+	 * _align=2 because both Aarch32 and Aarch64 instructions must be
+	 * word aligned. Do *not* try to use a raw .align directive. Since func
+	 * switches to a new section, this would not have the desired effect.
 	 */
-	.macro func _name, _align=-1
+	.macro func _name, _align=2
 	/*
 	 * Add Call Frame Information entry in the .debug_frame section for
 	 * debugger consumption. This enables callstack printing in debuggers.
@@ -36,9 +37,7 @@
 	 * .debug_frame
 	 */
 	.cfi_startproc
-	.if (\_align) != -1
-		.align \_align
-	.endif
+	.align \_align
 	\_name:
 	.endm
 
diff --git a/include/lib/el3_runtime/cpu_data.h b/include/lib/el3_runtime/cpu_data.h
index 1e8bfa7..c0c3a19 100644
--- a/include/lib/el3_runtime/cpu_data.h
+++ b/include/lib/el3_runtime/cpu_data.h
@@ -7,12 +7,15 @@
 #ifndef __CPU_DATA_H__
 #define __CPU_DATA_H__
 
+#include <platform_def.h>	/* CACHE_WRITEBACK_GRANULE required */
+
 #ifdef AARCH32
 
 #if CRASH_REPORTING
 #error "Crash reporting is not supported in AArch32"
 #endif
 #define CPU_DATA_CPU_OPS_PTR		0x0
+#define CPU_DATA_CRASH_BUF_OFFSET	0x4
 
 #else /* AARCH32 */
 
@@ -25,14 +28,18 @@
 #endif /* AARCH32 */
 
 #if CRASH_REPORTING
-#define CPU_DATA_LOG2SIZE		7
 #define CPU_DATA_CRASH_BUF_END		(CPU_DATA_CRASH_BUF_OFFSET + \
 						CPU_DATA_CRASH_BUF_SIZE)
 #else
-#define CPU_DATA_LOG2SIZE		6
 #define CPU_DATA_CRASH_BUF_END		CPU_DATA_CRASH_BUF_OFFSET
 #endif
 
+/* cpu_data size is the data size rounded up to the platform cache line size */
+#define CPU_DATA_SIZE			(((CPU_DATA_CRASH_BUF_END + \
+					CACHE_WRITEBACK_GRANULE - 1) / \
+						CACHE_WRITEBACK_GRANULE) * \
+							CACHE_WRITEBACK_GRANULE)
+
 #if ENABLE_RUNTIME_INSTRUMENTATION
 /* Temporary space to store PMF timestamps from assembly code */
 #define CPU_DATA_PMF_TS_COUNT		1
@@ -98,8 +105,8 @@
 	assert_cpu_data_crash_stack_offset_mismatch);
 #endif
 
-CASSERT((1 << CPU_DATA_LOG2SIZE) == sizeof(cpu_data_t),
-	assert_cpu_data_log2size_mismatch);
+CASSERT(CPU_DATA_SIZE == sizeof(cpu_data_t),
+		assert_cpu_data_size_mismatch);
 
 CASSERT(CPU_DATA_CPU_OPS_PTR == __builtin_offsetof
 		(cpu_data_t, cpu_ops_ptr),
diff --git a/include/plat/arm/common/arm_def.h b/include/plat/arm/common/arm_def.h
index d44e278..2b0d894 100644
--- a/include/plat/arm/common/arm_def.h
+++ b/include/plat/arm/common/arm_def.h
@@ -113,6 +113,15 @@
 					ARM_OPTEE_PAGEABLE_LOAD_BASE,	\
 					ARM_OPTEE_PAGEABLE_LOAD_SIZE,	\
 					MT_MEMORY | MT_RW | MT_SECURE)
+
+/*
+ * Map the memory for the OP-TEE core (also known as OP-TEE pager when paging
+ * support is enabled).
+ */
+#define ARM_MAP_OPTEE_CORE_MEM		MAP_REGION_FLAT(		\
+						BL32_BASE,		\
+						BL32_LIMIT - BL32_BASE,	\
+						MT_MEMORY | MT_RW | MT_SECURE)
 #endif /* SPD_opteed */
 
 #define ARM_NS_DRAM1_BASE		ARM_DRAM1_BASE
diff --git a/lib/el3_runtime/aarch32/cpu_data.S b/lib/el3_runtime/aarch32/cpu_data.S
index 3d6b806..68d6415 100644
--- a/lib/el3_runtime/aarch32/cpu_data.S
+++ b/lib/el3_runtime/aarch32/cpu_data.S
@@ -34,7 +34,9 @@
  * -----------------------------------------------------------------
  */
 func _cpu_data_by_index
+	mov_imm	r1, CPU_DATA_SIZE
+	mul	r0, r0, r1
 	ldr	r1, =percpu_data
-	add	r0, r1, r0, LSL #CPU_DATA_LOG2SIZE
+	add	r0, r0, r1
 	bx	lr
 endfunc _cpu_data_by_index
diff --git a/lib/el3_runtime/aarch64/cpu_data.S b/lib/el3_runtime/aarch64/cpu_data.S
index de48816..96be081 100644
--- a/lib/el3_runtime/aarch64/cpu_data.S
+++ b/lib/el3_runtime/aarch64/cpu_data.S
@@ -39,7 +39,9 @@
  * -----------------------------------------------------------------
  */
 func _cpu_data_by_index
+	mov_imm	x1, CPU_DATA_SIZE
+	mul	x0, x0, x1
 	adr	x1, percpu_data
-	add	x0, x1, x0, LSL #CPU_DATA_LOG2SIZE
+	add	x0, x0, x1
 	ret
 endfunc _cpu_data_by_index
diff --git a/make_helpers/defaults.mk b/make_helpers/defaults.mk
index 302d937..8601046 100644
--- a/make_helpers/defaults.mk
+++ b/make_helpers/defaults.mk
@@ -81,6 +81,9 @@
 # operations.
 HW_ASSISTED_COHERENCY		:= 0
 
+# Set the default algorithm for the generation of Trusted Board Boot keys
+KEY_ALG				:= rsa
+
 # Flag to enable new version of image loading
 LOAD_IMAGE_V2			:= 0
 
diff --git a/plat/arm/board/common/board_css_common.c b/plat/arm/board/common/board_css_common.c
index 2495e28..68f70a7 100644
--- a/plat/arm/board/common/board_css_common.c
+++ b/plat/arm/board/common/board_css_common.c
@@ -37,6 +37,7 @@
 	ARM_MAP_TSP_SEC_MEM,
 #endif
 #ifdef SPD_opteed
+	ARM_MAP_OPTEE_CORE_MEM,
 	ARM_OPTEE_PAGEABLE_LOAD_MEM,
 #endif
 	{0}
diff --git a/plat/arm/board/fvp/fvp_common.c b/plat/arm/board/fvp/fvp_common.c
index e232745..e869f5b 100644
--- a/plat/arm/board/fvp/fvp_common.c
+++ b/plat/arm/board/fvp/fvp_common.c
@@ -90,6 +90,7 @@
 	ARM_MAP_BL31_SEC_DRAM,
 #endif
 #ifdef SPD_opteed
+	ARM_MAP_OPTEE_CORE_MEM,
 	ARM_OPTEE_PAGEABLE_LOAD_MEM,
 #endif
 	{0}
diff --git a/plat/arm/common/arm_common.mk b/plat/arm/common/arm_common.mk
index 20372c2..af94ac2 100644
--- a/plat/arm/common/arm_common.mk
+++ b/plat/arm/common/arm_common.mk
@@ -174,9 +174,6 @@
 
 ifneq (${TRUSTED_BOARD_BOOT},0)
 
-    # By default, ARM platforms use RSA keys
-    KEY_ALG		:=	rsa
-
     # Include common TBB sources
     AUTH_SOURCES	:=	drivers/auth/auth_mod.c				\
 				drivers/auth/crypto_mod.c			\
@@ -195,8 +192,6 @@
 
     $(eval $(call FWU_FIP_ADD_IMG,NS_BL2U,--fwu))
 
-    TF_MBEDTLS_KEY_ALG	:=	${KEY_ALG}
-
     # We expect to locate the *.mk files under the directories specified below
 ifeq (${ARM_CRYPTOCELL_INTEG},0)
     CRYPTO_LIB_MK := drivers/auth/mbedtls/mbedtls_crypto.mk
diff --git a/plat/socionext/uniphier/uniphier_nand.c b/plat/socionext/uniphier/uniphier_nand.c
index 88f906c..a118b85 100644
--- a/plat/socionext/uniphier/uniphier_nand.c
+++ b/plat/socionext/uniphier/uniphier_nand.c
@@ -108,7 +108,7 @@
 
 	/* if possible, save the result for future re-use */
 	if (block < ARRAY_SIZE(nand->bbt))
-	    nand->bbt[block] = is_bad;
+		nand->bbt[block] = is_bad;
 
 	if (is_bad)
 		WARN("found bad block at %d. skip.\n", block);
diff --git a/plat/socionext/uniphier/uniphier_usb.c b/plat/socionext/uniphier/uniphier_usb.c
index 49ca8e5..4be0e90 100644
--- a/plat/socionext/uniphier/uniphier_usb.c
+++ b/plat/socionext/uniphier/uniphier_usb.c
@@ -16,6 +16,7 @@
 
 #define UNIPHIER_LD11_USB_DESC_BASE	0x30010000
 #define UNIPHIER_LD20_USB_DESC_BASE	0x30014000
+#define UNIPHIER_PXS3_USB_DESC_BASE	0x30014000
 
 #define UNIPHIER_SRB_OCM_CONT		0x61200000
 
@@ -41,6 +42,13 @@
 	void *dev_desc;
 };
 
+struct uniphier_pxs3_op {
+	uint8_t __pad[184];
+	struct uniphier_ld20_trans_op *trans_op;
+	void *__pad2;
+	void *dev_desc;
+};
+
 static int (*__uniphier_usb_read)(int lba, uintptr_t buf, size_t size);
 
 static void uniphier_ld11_usb_init(void)
@@ -91,14 +99,27 @@
 	return ret ? 0 : -1;
 }
 
+static void uniphier_pxs3_usb_init(void)
+{
+	struct uniphier_pxs3_op *op = (void *)UNIPHIER_PXS3_USB_DESC_BASE;
+
+	op->trans_op = (void *)(op + 1);
+
+	op->dev_desc = op->trans_op + 1;
+}
+
 static int uniphier_pxs3_usb_read(int lba, uintptr_t buf, size_t size)
 {
-	static int (*rom_usb_read)(unsigned int lba, unsigned int size,
-				   uintptr_t buf);
+	static int (*rom_usb_read)(uintptr_t desc, unsigned int lba,
+				   unsigned int size, uintptr_t buf);
+	int ret;
 
-	rom_usb_read = (__typeof(rom_usb_read))0x100c;
+	rom_usb_read = (__typeof(rom_usb_read))0x39e8;
 
-	return rom_usb_read(lba, size, buf);
+	/* ROM-API - return 1 on success, 0 on error */
+	ret = rom_usb_read(UNIPHIER_PXS3_USB_DESC_BASE, lba, size, buf);
+
+	return ret ? 0 : -1;
 }
 
 struct uniphier_usb_rom_param {
@@ -116,6 +137,7 @@
 		.read = uniphier_ld20_usb_read,
 	},
 	[UNIPHIER_SOC_PXS3] = {
+		.init = uniphier_pxs3_usb_init,
 		.read = uniphier_pxs3_usb_read,
 	},
 };
diff --git a/tools/cert_create/include/cert.h b/tools/cert_create/include/cert.h
index 543f122..256e7af 100644
--- a/tools/cert_create/include/cert.h
+++ b/tools/cert_create/include/cert.h
@@ -48,7 +48,7 @@
 int cert_init(void);
 cert_t *cert_get_by_opt(const char *opt);
 int cert_add_ext(X509 *issuer, X509 *subject, int nid, char *value);
-int cert_new(cert_t *cert, int days, int ca, STACK_OF(X509_EXTENSION) * sk);
+int cert_new(int key_alg, cert_t *cert, int days, int ca, STACK_OF(X509_EXTENSION) * sk);
 
 /* Macro to register the certificates used in the CoT */
 #define REGISTER_COT(_certs) \
diff --git a/tools/cert_create/include/key.h b/tools/cert_create/include/key.h
index 4b9e882..304fa61 100644
--- a/tools/cert_create/include/key.h
+++ b/tools/cert_create/include/key.h
@@ -22,7 +22,8 @@
 
 /* Supported key algorithms */
 enum {
-	KEY_ALG_RSA,
+	KEY_ALG_RSA,		/* RSA PSS as defined by PKCS#1 v2.1 (default) */
+	KEY_ALG_RSA_1_5,	/* RSA as defined by PKCS#1 v1.5 */
 #ifndef OPENSSL_NO_EC
 	KEY_ALG_ECDSA,
 #endif /* OPENSSL_NO_EC */
diff --git a/tools/cert_create/src/cert.c b/tools/cert_create/src/cert.c
index 9775664..1b84e36 100644
--- a/tools/cert_create/src/cert.c
+++ b/tools/cert_create/src/cert.c
@@ -79,7 +79,7 @@
 	return 1;
 }
 
-int cert_new(cert_t *cert, int days, int ca, STACK_OF(X509_EXTENSION) * sk)
+int cert_new(int key_alg, cert_t *cert, int days, int ca, STACK_OF(X509_EXTENSION) * sk)
 {
 	EVP_PKEY *pkey = keys[cert->key].key;
 	cert_t *issuer_cert = &certs[cert->issuer];
@@ -90,7 +90,7 @@
 	X509_NAME *name;
 	ASN1_INTEGER *sno;
 	int i, num, rc = 0;
-	EVP_MD_CTX  mdCtx;
+	EVP_MD_CTX mdCtx;
 	EVP_PKEY_CTX *pKeyCtx = NULL;
 
 	/* Create the certificate structure */
@@ -112,24 +112,32 @@
 	}
 
 	EVP_MD_CTX_init(&mdCtx);
+
+	/* Sign the certificate with the issuer key */
 	if (!EVP_DigestSignInit(&mdCtx, &pKeyCtx, EVP_sha256(), NULL, ikey)) {
 		ERR_print_errors_fp(stdout);
 		goto END;
 	}
 
-	if (!EVP_PKEY_CTX_set_rsa_padding(pKeyCtx, RSA_PKCS1_PSS_PADDING)) {
-		ERR_print_errors_fp(stdout);
-		goto END;
-	}
+	/*
+	 * Set additional parameters if algorithm is RSA PSS. This is not
+	 * required for RSA 1.5 or ECDSA.
+	 */
+	if (key_alg == KEY_ALG_RSA) {
+		if (!EVP_PKEY_CTX_set_rsa_padding(pKeyCtx, RSA_PKCS1_PSS_PADDING)) {
+			ERR_print_errors_fp(stdout);
+			goto END;
+		}
 
-	if (!EVP_PKEY_CTX_set_rsa_pss_saltlen(pKeyCtx, RSA_SALT_LEN)) {
-		ERR_print_errors_fp(stdout);
-		goto END;
-	}
+		if (!EVP_PKEY_CTX_set_rsa_pss_saltlen(pKeyCtx, RSA_SALT_LEN)) {
+			ERR_print_errors_fp(stdout);
+			goto END;
+		}
 
-	if (!EVP_PKEY_CTX_set_rsa_mgf1_md(pKeyCtx, EVP_sha256())) {
-		ERR_print_errors_fp(stdout);
-		goto END;
+		if (!EVP_PKEY_CTX_set_rsa_mgf1_md(pKeyCtx, EVP_sha256())) {
+			ERR_print_errors_fp(stdout);
+			goto END;
+		}
 	}
 
 	/* x509.v3 */
diff --git a/tools/cert_create/src/main.c b/tools/cert_create/src/main.c
index f14601c..df59961 100644
--- a/tools/cert_create/src/main.c
+++ b/tools/cert_create/src/main.c
@@ -89,6 +89,7 @@
 
 static const char *key_algs_str[] = {
 	[KEY_ALG_RSA] = "rsa",
+	[KEY_ALG_RSA_1_5] = "rsa_1_5",
 #ifndef OPENSSL_NO_EC
 	[KEY_ALG_ECDSA] = "ecdsa"
 #endif /* OPENSSL_NO_EC */
@@ -223,7 +224,8 @@
 	},
 	{
 		{ "key-alg", required_argument, NULL, 'a' },
-		"Key algorithm: 'rsa' (default), 'ecdsa'"
+		"Key algorithm: 'rsa' (default) - RSAPSS scheme as per \
+PKCS#1 v2.1, 'rsa_1_5' - RSA PKCS#1 v1.5, 'ecdsa'"
 	},
 	{
 		{ "save-keys", no_argument, NULL, 'k' },
@@ -450,8 +452,8 @@
 			sk_X509_EXTENSION_push(sk, cert_ext);
 		}
 
-		/* Create certificate. Signed with ROT key */
-		if (cert->fn && !cert_new(cert, VAL_DAYS, 0, sk)) {
+		/* Create certificate. Signed with corresponding key */
+		if (cert->fn && !cert_new(key_alg, cert, VAL_DAYS, 0, sk)) {
 			ERROR("Cannot create %s\n", cert->cn);
 			exit(1);
 		}