Merge branch '2019-05-09-master-imports'

- Minor fixes (ata memory leak, implement feedback on ohci-da8xx
  changes, avb test fix, mmc test fix, spelling fixes, make FIT really
  optional, fit-dtb blob cleanups, TI K3 workflow improvements, bootz
  can boot barebox on 32bit ARM).
diff --git a/.gitignore b/.gitignore
index c2afcfb..d8b7b77 100644
--- a/.gitignore
+++ b/.gitignore
@@ -35,7 +35,7 @@
 #
 # Top-level generic files
 #
-fit-dtb.blob
+fit-dtb.blob*
 /MLO*
 /SPL*
 /System.map
diff --git a/Makefile b/Makefile
index 9fb90c0..afe3bbe 100644
--- a/Makefile
+++ b/Makefile
@@ -1015,6 +1015,17 @@
 	@echo >&2 "===================================================="
 endif
 endif
+ifneq ($(CONFIG_WATCHDOG)$(CONFIG_HW_WATCHDOG),)
+ifneq ($(CONFIG_WDT),y)
+	@echo >&2 "===================== WARNING ======================"
+	@echo >&2 "This board does not use CONFIG_WDT (DM watchdog support)."
+	@echo >&2 "Please update the board to use CONFIG_WDT before the"
+	@echo >&2 "v2019.10 release."
+	@echo >&2 "Failure to update by the deadline may result in board removal."
+	@echo >&2 "See doc/driver-model/MIGRATION.txt for more info."
+	@echo >&2 "===================================================="
+endif
+endif
 	@# Check that this build does not use CONFIG options that we do not
 	@# know about unless they are in Kconfig. All the existing CONFIG
 	@# options are whitelisted, so new ones should not be added.
@@ -1047,6 +1058,10 @@
 
 fit-dtb.blob: dts/dt.dtb FORCE
 	$(call if_changed,mkimage)
+ifneq ($(SOURCE_DATE_EPOCH),)
+	touch -d @$(SOURCE_DATE_EPOCH) fit-dtb.blob
+	chmod 0600 fit-dtb.blob
+endif
 
 MKIMAGEFLAGS_fit-dtb.blob = -f auto -A $(ARCH) -T firmware -C none -O u-boot \
 	-a 0 -e 0 -E \
@@ -1780,7 +1795,7 @@
 			$(filter-out include, $(shell ls -1 $d 2>/dev/null))))
 
 CLEAN_FILES += include/bmp_logo.h include/bmp_logo_data.h \
-	       boot* u-boot* MLO* SPL System.map fit-dtb.blob
+	       boot* u-boot* MLO* SPL System.map fit-dtb.blob*
 
 # Directories & files removed with 'make mrproper'
 MRPROPER_DIRS  += include/config include/generated spl tpl \
diff --git a/arch/arm/lib/zimage.c b/arch/arm/lib/zimage.c
index 09ab331..4930529 100644
--- a/arch/arm/lib/zimage.c
+++ b/arch/arm/lib/zimage.c
@@ -9,6 +9,7 @@
 #include <common.h>
 
 #define	LINUX_ARM_ZIMAGE_MAGIC	0x016f2818
+#define	BAREBOX_IMAGE_MAGIC	0x00786f62
 
 struct arm_z_header {
 	uint32_t	code[9];
@@ -21,9 +22,10 @@
 {
 	struct arm_z_header *zi = (struct arm_z_header *)image;
 
-	if (zi->zi_magic != LINUX_ARM_ZIMAGE_MAGIC) {
+	if (zi->zi_magic != LINUX_ARM_ZIMAGE_MAGIC &&
+	    zi->zi_magic != BAREBOX_IMAGE_MAGIC) {
 #ifndef CONFIG_SPL_FRAMEWORK
-		puts("Bad Linux ARM zImage magic!\n");
+		puts("zimage: Bad magic!\n");
 #endif
 		return 1;
 	}
diff --git a/arch/arm/mach-k3/config.mk b/arch/arm/mach-k3/config.mk
index 2d8f61f..f6b63db 100644
--- a/arch/arm/mach-k3/config.mk
+++ b/arch/arm/mach-k3/config.mk
@@ -11,31 +11,11 @@
 $(error "No openssl in $(PATH), consider installing openssl")
 endif
 
-SHA_VALUE=  $(shell openssl dgst -sha512 -hex $(obj)/u-boot-spl.bin | sed -e "s/^.*= //g")
 IMAGE_SIZE= $(shell cat $(obj)/u-boot-spl.bin | wc -c)
-LOADADDR= $(shell echo $(CONFIG_SPL_TEXT_BASE) | sed -e "s/^0x//g")
 MAX_SIZE= $(shell printf "%d" $(CONFIG_SYS_K3_MAX_DOWNLODABLE_IMAGE_SIZE))
 
-# Parameters to get populated into the x509 template
-SED_OPTS=  -e s/TEST_IMAGE_LENGTH/$(IMAGE_SIZE)/
-SED_OPTS+= -e s/TEST_IMAGE_SHA_VAL/$(SHA_VALUE)/
-SED_OPTS+= -e s/TEST_CERT_TYPE/1/		# CERT_TYPE_PRIMARY_IMAGE_BIN
-SED_OPTS+= -e s/TEST_BOOT_CORE/$(CONFIG_SYS_K3_BOOT_CORE_ID)/
-SED_OPTS+= -e s/TEST_BOOT_ARCH_WIDTH/32/
-SED_OPTS+= -e s/TEST_BOOT_ADDR/$(LOADADDR)/
-
-# Command to generate ecparam key
-quiet_cmd_genkey = OPENSSL $@
-cmd_genkey = openssl ecparam -out $@ -name prime256v1 -genkey
-
-# Command to generate x509 certificate
-quiet_cmd_gencert = OPENSSL $@
-cmd_gencert = cat $(srctree)/tools/k3_x509template.txt | sed $(SED_OPTS) > u-boot-spl-x509.txt; \
-	openssl req -new -x509 -key $(KEY) -nodes -outform DER -out $@ -config u-boot-spl-x509.txt -sha512
-
-# If external key is not provided, generate key using openssl.
 ifeq ($(CONFIG_SYS_K3_KEY), "")
-KEY=u-boot-spl-eckey.pem
+KEY=""
 # On HS use real key or warn if not available
 ifeq ($(CONFIG_TI_SECURE_DEVICE),y)
 ifneq ($(wildcard $(TI_SECURE_DEV_PKG)/keys/custMpk.pem),)
@@ -48,15 +28,9 @@
 KEY=$(patsubst "%",$(srctree)/%,$(CONFIG_SYS_K3_KEY))
 endif
 
-u-boot-spl-eckey.pem: FORCE
-	$(call if_changed,genkey)
-
 # tiboot3.bin is mandated by ROM and ROM only supports R5 boot.
 # So restrict tiboot3.bin creation for CPU_V7R.
 ifdef CONFIG_CPU_V7R
-u-boot-spl-cert.bin: $(KEY) $(obj)/u-boot-spl.bin image_check FORCE
-	$(call if_changed,gencert)
-
 image_check: $(obj)/u-boot-spl.bin FORCE
 	@if [ $(IMAGE_SIZE) -gt $(MAX_SIZE) ]; then			    \
 		echo "===============================================" >&2; \
@@ -66,8 +40,9 @@
 		exit 1;							    \
 	fi
 
-tiboot3.bin: u-boot-spl-cert.bin $(obj)/u-boot-spl.bin FORCE
-	$(call if_changed,cat)
+tiboot3.bin: image_check FORCE
+	$(srctree)/tools/k3_gen_x509_cert.sh -c 16 -b $(obj)/u-boot-spl.bin \
+				-o $@ -l $(CONFIG_SPL_TEXT_BASE) -k $(KEY)
 
 ALL-y	+= tiboot3.bin
 endif
diff --git a/arch/x86/Kconfig b/arch/x86/Kconfig
index 45a5336..70f9398 100644
--- a/arch/x86/Kconfig
+++ b/arch/x86/Kconfig
@@ -421,7 +421,7 @@
 	  For platforms that use Intel FSP for the memory initialization,
 	  please check FSP output HOB via U-Boot command 'fsp hob' to see
 	  if there is FSP_NON_VOLATILE_STORAGE_HOB_GUID (asm/fsp/fsp_hob.h).
-	  If such GUID does not exist, MRC cache is not avaiable on such
+	  If such GUID does not exist, MRC cache is not available on such
 	  platform (eg: Intel Queensbay), which means selecting this option
 	  here does not make any difference.
 
diff --git a/arch/x86/cpu/i386/interrupt.c b/arch/x86/cpu/i386/interrupt.c
index 1ea415b..47df317 100644
--- a/arch/x86/cpu/i386/interrupt.c
+++ b/arch/x86/cpu/i386/interrupt.c
@@ -37,7 +37,7 @@
 	"Overflow",
 	"BOUND Range Exceeded",
 	"Invalid Opcode (Undefined Opcode)",
-	"Device Not Avaiable (No Math Coprocessor)",
+	"Device Not Available (No Math Coprocessor)",
 	"Double Fault",
 	"Coprocessor Segment Overrun",
 	"Invalid TSS",
diff --git a/arch/x86/lib/fsp/fsp_common.c b/arch/x86/lib/fsp/fsp_common.c
index d5ed1d5..ed0827c 100644
--- a/arch/x86/lib/fsp/fsp_common.c
+++ b/arch/x86/lib/fsp/fsp_common.c
@@ -138,7 +138,7 @@
 			}
 
 			/*
-			 * DM is not avaiable yet at this point, hence call
+			 * DM is not available yet at this point, hence call
 			 * CMOS access library which does not depend on DM.
 			 */
 			stack = cmos_read32(CMOS_FSP_STACK_ADDR);
diff --git a/common/bootm.c b/common/bootm.c
index b5d37d3..d193751 100644
--- a/common/bootm.c
+++ b/common/bootm.c
@@ -924,6 +924,7 @@
 	memmove(to, from, len);
 }
 
+#if defined(CONFIG_FIT_SIGNATURE)
 static int bootm_host_load_image(const void *fit, int req_image_type)
 {
 	const char *fit_uname_config = NULL;
@@ -988,5 +989,6 @@
 	/* Return the first error we found */
 	return err;
 }
+#endif
 
 #endif /* ndef USE_HOSTCC */
diff --git a/common/fdt_support.c b/common/fdt_support.c
index ab08a01..4e7cf6e 100644
--- a/common/fdt_support.c
+++ b/common/fdt_support.c
@@ -597,6 +597,7 @@
 	uint64_t addr, size;
 	int total, ret;
 	uint actualsize;
+	int fdt_memrsv = 0;
 
 	if (!blob)
 		return 0;
@@ -606,6 +607,7 @@
 		fdt_get_mem_rsv(blob, i, &addr, &size);
 		if (addr == (uintptr_t)blob) {
 			fdt_del_mem_rsv(blob, i);
+			fdt_memrsv = 1;
 			break;
 		}
 	}
@@ -627,10 +629,12 @@
 	/* Change the fdt header to reflect the correct size */
 	fdt_set_totalsize(blob, actualsize);
 
-	/* Add the new reservation */
-	ret = fdt_add_mem_rsv(blob, map_to_sysmem(blob), actualsize);
-	if (ret < 0)
-		return ret;
+	if (fdt_memrsv) {
+		/* Add the new reservation */
+		ret = fdt_add_mem_rsv(blob, map_to_sysmem(blob), actualsize);
+		if (ret < 0)
+			return ret;
+	}
 
 	return actualsize;
 }
diff --git a/common/spl/Kconfig b/common/spl/Kconfig
index dd078fe..c7cd344 100644
--- a/common/spl/Kconfig
+++ b/common/spl/Kconfig
@@ -282,7 +282,7 @@
 	  checksum is a 160-bit (20-byte) hash value used to check that the
 	  image contents have not been corrupted or maliciously altered.
 	  While SHA1 is fairly secure it is coming to the end of its life
-	  due to the expanding computing power avaiable to brute-force
+	  due to the expanding computing power available to brute-force
 	  attacks. For more security, consider SHA256.
 
 config SPL_SHA256_SUPPORT
diff --git a/drivers/ata/ahci.c b/drivers/ata/ahci.c
index 5fafb63..188d843 100644
--- a/drivers/ata/ahci.c
+++ b/drivers/ata/ahci.c
@@ -571,15 +571,12 @@
 		return -1;
 	}
 
-	mem = malloc(AHCI_PORT_PRIV_DMA_SZ + 2048);
+	mem = memalign(2048, AHCI_PORT_PRIV_DMA_SZ);
 	if (!mem) {
 		free(pp);
 		printf("%s: No mem for table!\n", __func__);
 		return -ENOMEM;
 	}
-
-	/* Aligned to 2048-bytes */
-	mem = memalign(2048, AHCI_PORT_PRIV_DMA_SZ);
 	memset(mem, 0, AHCI_PORT_PRIV_DMA_SZ);
 
 	/*
diff --git a/drivers/remoteproc/k3_system_controller.c b/drivers/remoteproc/k3_system_controller.c
index 214ea18..44e56c7 100644
--- a/drivers/remoteproc/k3_system_controller.c
+++ b/drivers/remoteproc/k3_system_controller.c
@@ -301,7 +301,7 @@
 
 static const struct k3_sysctrler_desc k3_sysctrler_am654_desc = {
 	.host_id = 4,				/* HOST_ID_R5_1 */
-	.max_rx_timeout_us = 400000,
+	.max_rx_timeout_us = 800000,
 	.max_msg_size = 60,
 };
 
diff --git a/drivers/tee/sandbox.c b/drivers/tee/sandbox.c
index a136bc9..2f3355c 100644
--- a/drivers/tee/sandbox.c
+++ b/drivers/tee/sandbox.c
@@ -178,7 +178,7 @@
 		if (!ep)
 			return TEE_ERROR_ITEM_NOT_FOUND;
 
-		value_sz = strlen(ep->data);
+		value_sz = strlen(ep->data) + 1;
 		memcpy(value, ep->data, value_sz);
 
 		return TEE_SUCCESS;
diff --git a/drivers/usb/host/ohci-da8xx.c b/drivers/usb/host/ohci-da8xx.c
index e8a495f..233df57 100644
--- a/drivers/usb/host/ohci-da8xx.c
+++ b/drivers/usb/host/ohci-da8xx.c
@@ -93,6 +93,10 @@
 	err = 0;
 	priv->clock_count = 0;
 	clock_nb = dev_count_phandle_with_args(dev, "clocks", "#clock-cells");
+
+	if (clock_nb < 0)
+		return clock_nb;
+
 	if (clock_nb > 0) {
 		priv->clocks = devm_kcalloc(dev, clock_nb, sizeof(struct clk),
 					    GFP_KERNEL);
@@ -112,9 +116,6 @@
 			}
 			priv->clock_count++;
 		}
-	} else if (clock_nb != -ENOENT) {
-		dev_err(dev, "failed to get clock phandle(%d)\n", clock_nb);
-		return clock_nb;
 	}
 
 	err = usb_cpu_init();
@@ -170,6 +171,6 @@
 	.remove = ohci_da8xx_remove,
 	.ops	= &ohci_usb_ops,
 	.priv_auto_alloc_size = sizeof(struct da8xx_ohci),
-	.flags	= DM_FLAG_ALLOC_PRIV_DMA,
+	.flags	= DM_FLAG_ALLOC_PRIV_DMA | DM_FLAG_OS_PREPARE,
 };
 #endif
diff --git a/env/Kconfig b/env/Kconfig
index 7830066..70858d3 100644
--- a/env/Kconfig
+++ b/env/Kconfig
@@ -351,14 +351,14 @@
 	  Value of the SPI chip select for environment.
 
 config USE_ENV_SPI_MAX_HZ
-	bool "SPI flash bus for environment"
+	bool "SPI flash max frequency for environment"
 	depends on ENV_IS_IN_SPI_FLASH
 	help
 	  Force the SPI max work clock for environment.
 	  If not defined, use CONFIG_SF_DEFAULT_SPEED.
 
 config ENV_SPI_MAX_HZ
-	int "Value of SPI flash max work for environment"
+	int "Value of SPI flash max frequency for environment"
 	depends on USE_ENV_SPI_MAX_HZ
 	help
 	  Value of the SPI max work clock for environment.
diff --git a/include/bootm.h b/include/bootm.h
index e2cc6d4..f771b73 100644
--- a/include/bootm.h
+++ b/include/bootm.h
@@ -42,7 +42,9 @@
 
 boot_os_fn *bootm_os_get_boot_func(int os);
 
+#if defined(CONFIG_FIT_SIGNATURE)
 int bootm_host_load_images(const void *fit, int cfg_noffset);
+#endif
 
 int boot_selected_os(int argc, char * const argv[], int state,
 		     bootm_headers_t *images, boot_os_fn *boot_fn);
diff --git a/test/py/tests/test_mmc_rd.py b/test/py/tests/test_mmc_rd.py
index 2dc715b..a25aa5f 100644
--- a/test/py/tests/test_mmc_rd.py
+++ b/test/py/tests/test_mmc_rd.py
@@ -13,6 +13,53 @@
 This test relies on boardenv_* to containing configuration values to define
 which MMC devices should be tested. For example:
 
+# Configuration data for test_mmc_dev, test_mmc_rescan, test_mmc_info; defines
+# whole MMC devices that mmc dev/rescan/info commands may operate upon.
+env__mmc_dev_configs = (
+    {
+        'fixture_id': 'emmc-boot0',
+        'is_emmc': True,
+        'devid': 0,
+        'partid': 1,
+        'info_device': ???,
+        'info_speed': ???,
+        'info_mode': ???,
+        'info_buswidth': ???.
+    },
+    {
+        'fixture_id': 'emmc-boot1',
+        'is_emmc': True,
+        'devid': 0,
+        'partid': 2,
+        'info_device': ???,
+        'info_speed': ???,
+        'info_mode': ???,
+        'info_buswidth': ???.
+    },
+    {
+        'fixture_id': 'emmc-data',
+        'is_emmc': True,
+        'devid': 0,
+        'partid': 0,
+        'info_device': ???,
+        'info_speed': ???,
+        'info_mode': ???,
+        'info_buswidth': ???.
+    },
+    {
+        'fixture_id': 'sd',
+        'is_emmc': False,
+        'devid': 1,
+        'partid': None,
+        'info_device': ???,
+        'info_speed': ???,
+        'info_mode': ???,
+        'info_buswidth': ???.
+    },
+}
+
+# Configuration data for test_mmc_rd; defines regions of the MMC (entire
+# devices, or ranges of sectors) which can be read:
 env__mmc_rd_configs = (
     {
         'fixture_id': 'emmc-boot0',
@@ -85,12 +132,12 @@
     assert good_response in response
 
 @pytest.mark.buildconfigspec('cmd_mmc')
-def test_mmc_dev(u_boot_console, env__mmc_rd_config):
+def test_mmc_dev(u_boot_console, env__mmc_dev_config):
     """Test the "mmc dev" command.
 
     Args:
         u_boot_console: A U-Boot console connection.
-        env__mmc_rd_config: The single MMC configuration on which
+        env__mmc_dev_config: The single MMC configuration on which
             to run the test. See the file-level comment above for details
             of the format.
 
@@ -98,20 +145,20 @@
         Nothing.
     """
 
-    is_emmc = env__mmc_rd_config['is_emmc']
-    devid = env__mmc_rd_config['devid']
-    partid = env__mmc_rd_config.get('partid', 0)
+    is_emmc = env__mmc_dev_config['is_emmc']
+    devid = env__mmc_dev_config['devid']
+    partid = env__mmc_dev_config.get('partid', 0)
 
     # Select MMC device
     mmc_dev(u_boot_console, is_emmc, devid, partid)
 
 @pytest.mark.buildconfigspec('cmd_mmc')
-def test_mmc_rescan(u_boot_console, env__mmc_rd_config):
+def test_mmc_rescan(u_boot_console, env__mmc_dev_config):
     """Test the "mmc rescan" command.
 
     Args:
         u_boot_console: A U-Boot console connection.
-        env__mmc_rd_config: The single MMC configuration on which
+        env__mmc_dev_config: The single MMC configuration on which
             to run the test. See the file-level comment above for details
             of the format.
 
@@ -119,9 +166,9 @@
         Nothing.
     """
 
-    is_emmc = env__mmc_rd_config['is_emmc']
-    devid = env__mmc_rd_config['devid']
-    partid = env__mmc_rd_config.get('partid', 0)
+    is_emmc = env__mmc_dev_config['is_emmc']
+    devid = env__mmc_dev_config['devid']
+    partid = env__mmc_dev_config.get('partid', 0)
 
     # Select MMC device
     mmc_dev(u_boot_console, is_emmc, devid, partid)
@@ -132,12 +179,12 @@
     assert 'no card present' not in response
 
 @pytest.mark.buildconfigspec('cmd_mmc')
-def test_mmc_info(u_boot_console, env__mmc_rd_config):
+def test_mmc_info(u_boot_console, env__mmc_dev_config):
     """Test the "mmc info" command.
 
     Args:
         u_boot_console: A U-Boot console connection.
-        env__mmc_rd_config: The single MMC configuration on which
+        env__mmc_dev_config: The single MMC configuration on which
             to run the test. See the file-level comment above for details
             of the format.
 
@@ -145,13 +192,13 @@
         Nothing.
     """
 
-    is_emmc = env__mmc_rd_config['is_emmc']
-    devid = env__mmc_rd_config['devid']
-    partid = env__mmc_rd_config.get('partid', 0)
-    info_device = env__mmc_rd_config['info_device']
-    info_speed = env__mmc_rd_config['info_speed']
-    info_mode = env__mmc_rd_config['info_mode']
-    info_buswidth = env__mmc_rd_config['info_buswidth']
+    is_emmc = env__mmc_dev_config['is_emmc']
+    devid = env__mmc_dev_config['devid']
+    partid = env__mmc_dev_config.get('partid', 0)
+    info_device = env__mmc_dev_config['info_device']
+    info_speed = env__mmc_dev_config['info_speed']
+    info_mode = env__mmc_dev_config['info_mode']
+    info_buswidth = env__mmc_dev_config['info_buswidth']
 
     # Select MMC device
     mmc_dev(u_boot_console, is_emmc, devid, partid)
diff --git a/tools/Makefile b/tools/Makefile
index eadeba4..e2f572c 100644
--- a/tools/Makefile
+++ b/tools/Makefile
@@ -58,6 +58,7 @@
 
 hostprogs-$(CONFIG_CMD_BOOTEFI_SELFTEST) += file2include
 
+FIT_OBJS-$(CONFIG_FIT) := fit_common.o fit_image.o image-host.o common/image-fit.o
 FIT_SIG_OBJS-$(CONFIG_FIT_SIGNATURE) := common/image-sig.o
 
 # The following files are synced with upstream DTC.
@@ -80,16 +81,13 @@
 # common objs for dumpimage and mkimage
 dumpimage-mkimage-objs := aisimage.o \
 			atmelimage.o \
+			$(FIT_OBJS-y) \
 			$(FIT_SIG_OBJS-y) \
 			common/bootm.o \
 			lib/crc32.o \
 			default_image.o \
 			lib/fdtdec_common.o \
 			lib/fdtdec.o \
-			fit_common.o \
-			fit_image.o \
-			common/image-fit.o \
-			image-host.o \
 			common/image.o \
 			imagetool.o \
 			imximage.o \
diff --git a/tools/k3_gen_x509_cert.sh b/tools/k3_gen_x509_cert.sh
new file mode 100755
index 0000000..b6d055f
--- /dev/null
+++ b/tools/k3_gen_x509_cert.sh
@@ -0,0 +1,244 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0+ OR BSD-3-Clause
+#
+# Script to add K3 specific x509 cetificate to a binary.
+#
+
+# Variables
+OUTPUT=tiboot3.bin
+TEMP_X509=x509-temp.cert
+CERT=certificate.bin
+RAND_KEY=eckey.pem
+LOADADDR=0x41c00000
+BOOTCORE_OPTS=0
+BOOTCORE=16
+
+gen_degen_template() {
+cat << 'EOF' > degen-template.txt
+
+asn1=SEQUENCE:rsa_key
+
+[rsa_key]
+version=INTEGER:0
+modulus=INTEGER:0xDEGEN_MODULUS
+pubExp=INTEGER:1
+privExp=INTEGER:1
+p=INTEGER:0xDEGEN_P
+q=INTEGER:0xDEGEN_Q
+e1=INTEGER:1
+e2=INTEGER:1
+coeff=INTEGER:0xDEGEN_COEFF
+EOF
+}
+
+# Generate x509 Template
+gen_template() {
+cat << 'EOF' > x509-template.txt
+ [ req ]
+ distinguished_name     = req_distinguished_name
+ x509_extensions        = v3_ca
+ prompt                 = no
+ dirstring_type         = nobmp
+
+ [ req_distinguished_name ]
+ C                      = US
+ ST                     = TX
+ L                      = Dallas
+ O                      = Texas Instruments Incorporated
+ OU                     = Processors
+ CN                     = TI support
+ emailAddress           = support@ti.com
+
+ [ v3_ca ]
+ basicConstraints = CA:true
+ 1.3.6.1.4.1.294.1.1 = ASN1:SEQUENCE:boot_seq
+ 1.3.6.1.4.1.294.1.2 = ASN1:SEQUENCE:image_integrity
+ 1.3.6.1.4.1.294.1.3 = ASN1:SEQUENCE:swrv
+# 1.3.6.1.4.1.294.1.4 = ASN1:SEQUENCE:encryption
+ 1.3.6.1.4.1.294.1.8 = ASN1:SEQUENCE:debug
+
+ [ boot_seq ]
+ certType = INTEGER:TEST_CERT_TYPE
+ bootCore = INTEGER:TEST_BOOT_CORE
+ bootCoreOpts = INTEGER:TEST_BOOT_CORE_OPTS
+ destAddr = FORMAT:HEX,OCT:TEST_BOOT_ADDR
+ imageSize = INTEGER:TEST_IMAGE_LENGTH
+
+ [ image_integrity ]
+ shaType = OID:2.16.840.1.101.3.4.2.3
+ shaValue = FORMAT:HEX,OCT:TEST_IMAGE_SHA_VAL
+
+ [ swrv ]
+ swrv = INTEGER:0
+
+# [ encryption ]
+# initalVector = FORMAT:HEX,OCT:TEST_IMAGE_ENC_IV
+# randomString = FORMAT:HEX,OCT:TEST_IMAGE_ENC_RS
+# iterationCnt = INTEGER:TEST_IMAGE_KEY_DERIVE_INDEX
+# salt = FORMAT:HEX,OCT:TEST_IMAGE_KEY_DERIVE_SALT
+
+ [ debug ]
+ debugUID = FORMAT:HEX,OCT:0000000000000000000000000000000000000000000000000000000000000000
+ debugType = INTEGER:4
+ coreDbgEn = INTEGER:0
+ coreDbgSecEn = INTEGER:0
+EOF
+}
+
+parse_key() {
+	sed '/\ \ \ \ /s/://g' key.txt | awk  '!/\ \ \ \ / {printf("\n%s\n", $0)}; /\ \ \ \ / {printf("%s", $0)}' | sed 's/\ \ \ \ //g' | awk "/$1:/{getline; print}"
+}
+
+gen_degen_key() {
+# Generate a 4096 bit RSA Key
+	openssl genrsa -out key.pem 1024 >>/dev/null 2>&1
+	openssl rsa -in key.pem -text -out key.txt >>/dev/null 2>&1
+	DEGEN_MODULUS=$( parse_key 'modulus' )
+	DEGEN_P=$( parse_key 'prime1' )
+	DEGEN_Q=$( parse_key 'prime2' )
+	DEGEN_COEFF=$( parse_key 'coefficient' )
+	gen_degen_template
+
+	sed -e "s/DEGEN_MODULUS/$DEGEN_MODULUS/"\
+		-e "s/DEGEN_P/$DEGEN_P/" \
+		-e "s/DEGEN_Q/$DEGEN_Q/" \
+		-e "s/DEGEN_COEFF/$DEGEN_COEFF/" \
+		 degen-template.txt > degenerateKey.txt
+
+	openssl asn1parse -genconf degenerateKey.txt -out degenerateKey.der >>/dev/null 2>&1
+	openssl rsa -in degenerateKey.der -inform DER -outform PEM -out $RAND_KEY >>/dev/null 2>&1
+	KEY=$RAND_KEY
+	rm key.pem key.txt degen-template.txt degenerateKey.txt degenerateKey.der
+}
+
+declare -A options_help
+usage() {
+	if [ -n "$*" ]; then
+		echo "ERROR: $*"
+	fi
+	echo -n "Usage: $0 "
+	for option in "${!options_help[@]}"
+	do
+		arg=`echo ${options_help[$option]}|cut -d ':' -f1`
+		if [ -n "$arg" ]; then
+			arg=" $arg"
+		fi
+		echo -n "[-$option$arg] "
+	done
+	echo
+	echo -e "\nWhere:"
+	for option in "${!options_help[@]}"
+	do
+		arg=`echo ${options_help[$option]}|cut -d ':' -f1`
+		txt=`echo ${options_help[$option]}|cut -d ':' -f2`
+		tb="\t\t\t"
+		if [ -n "$arg" ]; then
+			arg=" $arg"
+			tb="\t"
+		fi
+		echo -e "   -$option$arg:$tb$txt"
+	done
+	echo
+	echo "Examples of usage:-"
+	echo "# Example of signing the SYSFW binary with rsa degenerate key"
+	echo "    $0 -c 0 -b ti-sci-firmware-am6x.bin -o sysfw.bin -l 0x40000"
+	echo "# Example of signing the SPL binary with rsa degenerate key"
+	echo "    $0 -c 16 -b spl/u-boot-spl.bin -o tiboot3.bin -l 0x41c00000"
+}
+
+options_help[b]="bin_file:Bin file that needs to be signed"
+options_help[k]="key_file:file with key inside it. If not provided script generates a rsa degenerate key."
+options_help[o]="output_file:Name of the final output file. default to $OUTPUT"
+options_help[c]="core_id:target core id on which the image would be running. Default to $BOOTCORE"
+options_help[l]="loadaddr: Target load address of the binary in hex. Default to $LOADADDR"
+
+while getopts "b:k:o:c:l:h" opt
+do
+	case $opt in
+	b)
+		BIN=$OPTARG
+	;;
+	k)
+		KEY=$OPTARG
+	;;
+	o)
+		OUTPUT=$OPTARG
+	;;
+	l)
+		LOADADDR=$OPTARG
+	;;
+	c)
+		BOOTCORE=$OPTARG
+	;;
+	h)
+		usage
+		exit 0
+	;;
+	\?)
+		usage "Invalid Option '-$OPTARG'"
+		exit 1
+	;;
+	:)
+		usage "Option '-$OPTARG' Needs an argument."
+		exit 1
+	;;
+	esac
+done
+
+if [ "$#" -eq 0 ]; then
+	usage "Arguments missing"
+	exit 1
+fi
+
+if [ -z "$BIN" ]; then
+	usage "Bin file missing in arguments"
+	exit 1
+fi
+
+# Generate rsa degenerate key if user doesn't provide a key
+if [ -z "$KEY" ]; then
+	gen_degen_key
+fi
+
+if [ $BOOTCORE == 0 ]; then	# BOOTCORE M3, loaded by ROM
+	CERTTYPE=2
+elif [ $BOOTCORE == 16 ]; then	# BOOTCORE R5, loaded by ROM
+	CERTTYPE=1
+else				# Non BOOTCORE, loaded by SYSFW
+	BOOTCORE_OPTS_VER=$(printf "%01x" 1)
+	# Add input args option for SET and CLR flags.
+	BOOTCORE_OPTS_SETFLAG=$(printf "%08x" 0)
+	BOOTCORE_OPTS_CLRFLAG=$(printf "%08x" 0x100) # Clear FLAG_ARMV8_AARCH32
+	BOOTCORE_OPTS="0x$BOOTCORE_OPTS_VER$BOOTCORE_OPTS_SETFLAG$BOOTCORE_OPTS_CLRFLAG"
+	# Set the cert type to zero.
+	# We are not using public/private key store now
+	CERTTYPE=$(printf "0x%08x" 0)
+fi
+
+SHA_VAL=`openssl dgst -sha512 -hex $BIN | sed -e "s/^.*= //g"`
+BIN_SIZE=`cat $BIN | wc -c`
+ADDR=`printf "%08x" $LOADADDR`
+
+gen_cert() {
+	#echo "Certificate being generated :"
+	#echo "	LOADADDR = 0x$ADDR"
+	#echo "	IMAGE_SIZE = $BIN_SIZE"
+	#echo "	CERT_TYPE = $CERTTYPE"
+	sed -e "s/TEST_IMAGE_LENGTH/$BIN_SIZE/"	\
+		-e "s/TEST_IMAGE_SHA_VAL/$SHA_VAL/" \
+		-e "s/TEST_CERT_TYPE/$CERTTYPE/" \
+		-e "s/TEST_BOOT_CORE_OPTS/$BOOTCORE_OPTS/" \
+		-e "s/TEST_BOOT_CORE/$BOOTCORE/" \
+		-e "s/TEST_BOOT_ADDR/$ADDR/" x509-template.txt > $TEMP_X509
+	openssl req -new -x509 -key $KEY -nodes -outform DER -out $CERT -config $TEMP_X509 -sha512
+}
+
+gen_template
+gen_cert
+cat $CERT $BIN > $OUTPUT
+
+# Remove all intermediate files
+rm $TEMP_X509 $CERT x509-template.txt
+if [ "$KEY" == "$RAND_KEY" ]; then
+	rm $RAND_KEY
+fi
diff --git a/tools/k3_x509template.txt b/tools/k3_x509template.txt
deleted file mode 100644
index f176ff3..0000000
--- a/tools/k3_x509template.txt
+++ /dev/null
@@ -1,48 +0,0 @@
- [ req ]
- distinguished_name     = req_distinguished_name
- x509_extensions        = v3_ca
- prompt                 = no
- dirstring_type         = nobmp
-
- [ req_distinguished_name ]
- C                      = US
- ST                     = TX
- L                      = Dallas
- O                      = Texas Instruments Incorporated
- OU                     = Processors
- CN                     = TI Support
- emailAddress           = support@ti.com
-
- [ v3_ca ]
- basicConstraints = CA:true
- 1.3.6.1.4.1.294.1.1 = ASN1:SEQUENCE:boot_seq
- 1.3.6.1.4.1.294.1.2 = ASN1:SEQUENCE:image_integrity
- 1.3.6.1.4.1.294.1.3 = ASN1:SEQUENCE:swrv
-# 1.3.6.1.4.1.294.1.4 = ASN1:SEQUENCE:encryption
- 1.3.6.1.4.1.294.1.8 = ASN1:SEQUENCE:debug
-
- [ boot_seq ]
- certType = INTEGER:TEST_CERT_TYPE
- bootCore = INTEGER:TEST_BOOT_CORE
- bootCoreOpts = INTEGER:TEST_BOOT_ARCH_WIDTH
- destAddr = FORMAT:HEX,OCT:TEST_BOOT_ADDR
- imageSize = INTEGER:TEST_IMAGE_LENGTH
-
- [ image_integrity ]
- shaType = OID:2.16.840.1.101.3.4.2.3
- shaValue = FORMAT:HEX,OCT:TEST_IMAGE_SHA_VAL
-
- [ swrv ]
- swrv = INTEGER:0
-
-# [ encryption ]
-# initalVector = FORMAT:HEX,OCT:TEST_IMAGE_ENC_IV
-# randomString = FORMAT:HEX,OCT:TEST_IMAGE_ENC_RS
-# iterationCnt = INTEGER:TEST_IMAGE_KEY_DERIVE_INDEX
-# salt = FORMAT:HEX,OCT:TEST_IMAGE_KEY_DERIVE_SALT
-
- [ debug ]
- debugUID = FORMAT:HEX,OCT:0000000000000000000000000000000000000000000000000000000000000000
- debugType = INTEGER:4
- coreDbgEn = INTEGER:0
- coreDbgSecEn = INTEGER:0